diff --git a/Lang/ALGOL-68/00DESCRIPTION b/Lang/ALGOL-68/00DESCRIPTION index 0a9c8a8e1b..b250b649a7 100644 --- a/Lang/ALGOL-68/00DESCRIPTION +++ b/Lang/ALGOL-68/00DESCRIPTION @@ -142,24 +142,67 @@ program. Example: == Coercion (casting) == ALGOL 68 has a hierarchy of contexts which determine which kind of coercions are available at a particular point in the program. These contexts are: -* soft - deproceduring -* weak - dereferencing or deproceduring, yielding a name -* meek - dereferencing or deproceduring -* firm - meek, followed by uniting -* strong - firm, followed by widening, rowing or voiding - -Depending on the context a MODE (type) will be coerced (widened) to another type if there is no loss -of precision. For example: An INT will be coerced to a REAL, and a REAL will be -coerced to a LONG REAL. But not vice-versa. Examples: -* INT to REAL -* REAL to COMPL -* BITS to []BOOL -* BYTES to STRING +{|class="wikitable" +! Context name !! Context location !! Coercions available in this context!! Coercion examples +|- +!soft +|| The LHS of assignments, as "~" in: ~ := ... +|| deproceduring +|| +* deproceduring of: PROC REAL random: e.g. random +|- +!weak +|| +* Primaries of slices, as in "~" in: ~[1:99] +* Secondaries of selections, as "~" in: value OF ~ +|| all '''soft''' then weak dereferencing +|| +REF BOOL to REF BOOL +REF REF INT to REF INT +REF REF REF REAL to REF REAL +REF REF REF REF STRUCT to REF STRUCT +|- +!meek +|| +* Trimscripts (yielding INT) +* Enquiries: e.g. as "~" in the followingIF ~ THEN ... FI and FROM ~ BY ~ TO ~ WHILE ~ DO ... OD etc +* Primaries of calls (e.g. sin in sin(x)) +|| all '''weak''' then dereferencing +|| +REF REF BOOL to BOOL +REF REF REF INT to INT +|- +!firm +|| +*Operands of formulas as "~" in:OP: ~ * ~ +*Parameters of transput calls +|| all '''meek''' then uniting +|| e.g. UNION(INT,REAL) var := 1 +|- +!strong +||Right hand side of: +* Identity-declarations, as "~" in: REAL x = ~ +* Initialisations, as "~" in: REAL x := ~ +Also: +* Actual-parameters of calls, as "~" in:PROC: sin(~) +* Enclosed clauses of casts, as "~" in: REAL(~) +* Units of routine-texts +* Statements yielding VOID +* All parts (but one) of a balanced clause +* One side of an identity relation, as "~" in: ~ IS ~ +|| all '''firm''' then widening, rowing and voiding +||Widening occures if there is no loss of precision. For example: An INT will be coerced to a REAL, and a REAL will be coerced to a LONG REAL. But not vice-versa. Examples: +INT to LONG INT +INT to REAL +REAL to COMPL +BITS to []BOOL +BYTES to STRING A variable can also be coerced (rowed) to an array of length 1. For example: -* INT to [1]INT -* REAL to [1]REAL etc -Pointers are followed (dereferenced), For example: -* REF REF REAL to REAL +INT to [1]INT +REAL to [1]REAL etc +|} +For more details about Primaries and Secondaries refer to [[Operator_precedence#ALGOL_68|Operator precedence]]. + == Code Specimen == {{language programming paradigm|Concurrent}} {{language programming paradigm|Imperative}} \ No newline at end of file diff --git a/Lang/ALGOL-68/Case-sensitivity-of-identifiers b/Lang/ALGOL-68/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..d9116d9ae5 --- /dev/null +++ b/Lang/ALGOL-68/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL/00DESCRIPTION b/Lang/ALGOL/00DESCRIPTION index f66cf163bf..db3c72c635 100644 --- a/Lang/ALGOL/00DESCRIPTION +++ b/Lang/ALGOL/00DESCRIPTION @@ -1 +1,4 @@ -{{language}}{{stub}} \ No newline at end of file +{{stub}}{{language}} +;See +* [[ALGOL 60]] +* [[ALGOL 68]] \ No newline at end of file diff --git a/Lang/ANTLR/CSV-to-HTML-translation b/Lang/ANTLR/CSV-to-HTML-translation new file mode 120000 index 0000000000..e61501dbeb --- /dev/null +++ b/Lang/ANTLR/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/ANTLR \ No newline at end of file diff --git a/Lang/APL/Averages-Median b/Lang/APL/Averages-Median new file mode 120000 index 0000000000..868d445130 --- /dev/null +++ b/Lang/APL/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/APL \ No newline at end of file diff --git a/Lang/APL/Factors-of-an-integer b/Lang/APL/Factors-of-an-integer new file mode 120000 index 0000000000..2b7ebcce01 --- /dev/null +++ b/Lang/APL/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/APL \ No newline at end of file diff --git a/Lang/APL/Gray-code b/Lang/APL/Gray-code new file mode 120000 index 0000000000..61eadf93fe --- /dev/null +++ b/Lang/APL/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/APL \ No newline at end of file diff --git a/Lang/APL/Look-and-say-sequence b/Lang/APL/Look-and-say-sequence new file mode 120000 index 0000000000..08dc93e6cc --- /dev/null +++ b/Lang/APL/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/APL \ No newline at end of file diff --git a/Lang/APL/Sum-of-a-series b/Lang/APL/Sum-of-a-series new file mode 120000 index 0000000000..37354846df --- /dev/null +++ b/Lang/APL/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/APL \ No newline at end of file diff --git a/Lang/APL/Sum-of-squares b/Lang/APL/Sum-of-squares new file mode 120000 index 0000000000..5f93b418ab --- /dev/null +++ b/Lang/APL/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/APL \ No newline at end of file diff --git a/Lang/AWK/Hailstone-sequence b/Lang/AWK/Hailstone-sequence new file mode 120000 index 0000000000..392c67dace --- /dev/null +++ b/Lang/AWK/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/AWK \ No newline at end of file diff --git a/Lang/AWK/Largest-int-from-concatenated-ints b/Lang/AWK/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..12ae8af9b7 --- /dev/null +++ b/Lang/AWK/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/AWK \ No newline at end of file diff --git a/Lang/AWK/Middle-three-digits b/Lang/AWK/Middle-three-digits new file mode 120000 index 0000000000..0f69a5ada3 --- /dev/null +++ b/Lang/AWK/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/AWK \ No newline at end of file diff --git a/Lang/Ada/Harshad-or-Niven-series b/Lang/Ada/Harshad-or-Niven-series new file mode 120000 index 0000000000..5f2e126e84 --- /dev/null +++ b/Lang/Ada/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Ada \ No newline at end of file diff --git a/Lang/Ada/Largest-int-from-concatenated-ints b/Lang/Ada/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..d26e46195d --- /dev/null +++ b/Lang/Ada/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Ada \ No newline at end of file diff --git a/Lang/Ada/String-comparison b/Lang/Ada/String-comparison new file mode 120000 index 0000000000..3c570703f1 --- /dev/null +++ b/Lang/Ada/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Ada \ No newline at end of file diff --git a/Lang/Ada/Temperature-conversion b/Lang/Ada/Temperature-conversion new file mode 120000 index 0000000000..a3029aba46 --- /dev/null +++ b/Lang/Ada/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Ada \ No newline at end of file diff --git a/Lang/Aime/00DESCRIPTION b/Lang/Aime/00DESCRIPTION index d66e830a7a..9163b7831a 100644 --- a/Lang/Aime/00DESCRIPTION +++ b/Lang/Aime/00DESCRIPTION @@ -1,4 +1,8 @@ {{language|aime +|checking=static +|parampass=both +|safety=safe +|strength=strong |site=http://sourceforge.net/projects/aime-embedded/ }}{{language programming paradigm|Imperative}}[[derived from::C| ]] ''aime'' is a simple, [[C|C]]-like, [[procedural programming|procedural]], [[imperative programming|imperative]] computer programming language. It is designed as a lightweight language targeted towards application extension [http://en.wikipedia.org/wiki/List_of_programming_languages_by_category#Extension_languages]. As such, the aime interpreter is easily embeddable in other applications. For the same reasons, the language stresses application integrity and accessibility. \ No newline at end of file diff --git a/Lang/Aime/Arrays b/Lang/Aime/Arrays new file mode 120000 index 0000000000..1dd0eed0c1 --- /dev/null +++ b/Lang/Aime/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Aime \ No newline at end of file diff --git a/Lang/Aime/Assertions b/Lang/Aime/Assertions new file mode 120000 index 0000000000..af901df967 --- /dev/null +++ b/Lang/Aime/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Aime \ No newline at end of file diff --git a/Lang/Aime/Balanced-brackets b/Lang/Aime/Balanced-brackets new file mode 120000 index 0000000000..3457ac0b96 --- /dev/null +++ b/Lang/Aime/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Aime \ No newline at end of file diff --git a/Lang/Aime/Binary-digits b/Lang/Aime/Binary-digits new file mode 120000 index 0000000000..c6aaa34296 --- /dev/null +++ b/Lang/Aime/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Aime \ No newline at end of file diff --git a/Lang/Aime/Collections b/Lang/Aime/Collections new file mode 120000 index 0000000000..e1825d5ed5 --- /dev/null +++ b/Lang/Aime/Collections @@ -0,0 +1 @@ +../../Task/Collections/Aime \ No newline at end of file diff --git a/Lang/Aime/Command-line-arguments b/Lang/Aime/Command-line-arguments new file mode 120000 index 0000000000..f75f1c565e --- /dev/null +++ b/Lang/Aime/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Aime \ No newline at end of file diff --git a/Lang/Aime/Copy-a-string b/Lang/Aime/Copy-a-string new file mode 120000 index 0000000000..9589e7691b --- /dev/null +++ b/Lang/Aime/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Aime \ No newline at end of file diff --git a/Lang/Aime/Count-in-octal b/Lang/Aime/Count-in-octal new file mode 120000 index 0000000000..41dd2791f0 --- /dev/null +++ b/Lang/Aime/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Aime \ No newline at end of file diff --git a/Lang/Aime/Create-a-file b/Lang/Aime/Create-a-file new file mode 120000 index 0000000000..c940a87bb6 --- /dev/null +++ b/Lang/Aime/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Aime \ No newline at end of file diff --git a/Lang/Aime/Deepcopy b/Lang/Aime/Deepcopy new file mode 120000 index 0000000000..ec9709789f --- /dev/null +++ b/Lang/Aime/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Aime \ No newline at end of file diff --git a/Lang/Aime/Delegates b/Lang/Aime/Delegates new file mode 120000 index 0000000000..fe5e80b7a8 --- /dev/null +++ b/Lang/Aime/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Aime \ No newline at end of file diff --git a/Lang/Aime/Detect-division-by-zero b/Lang/Aime/Detect-division-by-zero new file mode 120000 index 0000000000..fb8c05b816 --- /dev/null +++ b/Lang/Aime/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Aime \ No newline at end of file diff --git a/Lang/Aime/Determine-if-a-string-is-numeric b/Lang/Aime/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..7c7c537f68 --- /dev/null +++ b/Lang/Aime/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Aime \ No newline at end of file diff --git a/Lang/Aime/Empty-program b/Lang/Aime/Empty-program new file mode 120000 index 0000000000..a60f2ad974 --- /dev/null +++ b/Lang/Aime/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Aime \ No newline at end of file diff --git a/Lang/Aime/Empty-string b/Lang/Aime/Empty-string new file mode 120000 index 0000000000..cfcd2b5dc9 --- /dev/null +++ b/Lang/Aime/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Aime \ No newline at end of file diff --git a/Lang/Aime/Ethiopian-multiplication b/Lang/Aime/Ethiopian-multiplication new file mode 120000 index 0000000000..f4489634bf --- /dev/null +++ b/Lang/Aime/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Aime \ No newline at end of file diff --git a/Lang/Aime/Even-or-odd b/Lang/Aime/Even-or-odd new file mode 120000 index 0000000000..d24ce762c0 --- /dev/null +++ b/Lang/Aime/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Aime \ No newline at end of file diff --git a/Lang/Aime/Fibonacci-sequence b/Lang/Aime/Fibonacci-sequence new file mode 120000 index 0000000000..f0162a669d --- /dev/null +++ b/Lang/Aime/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Aime \ No newline at end of file diff --git a/Lang/Aime/File-IO b/Lang/Aime/File-IO new file mode 120000 index 0000000000..757f42f07e --- /dev/null +++ b/Lang/Aime/File-IO @@ -0,0 +1 @@ +../../Task/File-IO/Aime \ No newline at end of file diff --git a/Lang/Aime/Filter b/Lang/Aime/Filter new file mode 120000 index 0000000000..2ab4d674a5 --- /dev/null +++ b/Lang/Aime/Filter @@ -0,0 +1 @@ +../../Task/Filter/Aime \ No newline at end of file diff --git a/Lang/Aime/Find-common-directory-path b/Lang/Aime/Find-common-directory-path new file mode 120000 index 0000000000..a80406399f --- /dev/null +++ b/Lang/Aime/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Aime \ No newline at end of file diff --git a/Lang/Aime/Flatten-a-list b/Lang/Aime/Flatten-a-list new file mode 120000 index 0000000000..55f74e83a8 --- /dev/null +++ b/Lang/Aime/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Aime \ No newline at end of file diff --git a/Lang/Aime/Function-definition b/Lang/Aime/Function-definition new file mode 120000 index 0000000000..dc6675bbb0 --- /dev/null +++ b/Lang/Aime/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Aime \ No newline at end of file diff --git a/Lang/Aime/Function-prototype b/Lang/Aime/Function-prototype new file mode 120000 index 0000000000..5a14a0f16c --- /dev/null +++ b/Lang/Aime/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Aime \ No newline at end of file diff --git a/Lang/Aime/Gray-code b/Lang/Aime/Gray-code new file mode 120000 index 0000000000..3b01109341 --- /dev/null +++ b/Lang/Aime/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Aime \ No newline at end of file diff --git a/Lang/Aime/Greatest-common-divisor b/Lang/Aime/Greatest-common-divisor new file mode 120000 index 0000000000..73d4003ead --- /dev/null +++ b/Lang/Aime/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Aime \ No newline at end of file diff --git a/Lang/Aime/Hello-world-Standard-error b/Lang/Aime/Hello-world-Standard-error new file mode 120000 index 0000000000..bd1002de36 --- /dev/null +++ b/Lang/Aime/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Aime \ No newline at end of file diff --git a/Lang/Aime/Input-loop b/Lang/Aime/Input-loop new file mode 120000 index 0000000000..237fb614d2 --- /dev/null +++ b/Lang/Aime/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Aime \ No newline at end of file diff --git a/Lang/Aime/Langtons-ant b/Lang/Aime/Langtons-ant new file mode 120000 index 0000000000..e81c9fb513 --- /dev/null +++ b/Lang/Aime/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Aime \ No newline at end of file diff --git a/Lang/Aime/Levenshtein-distance b/Lang/Aime/Levenshtein-distance new file mode 120000 index 0000000000..536d1097a4 --- /dev/null +++ b/Lang/Aime/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Aime \ No newline at end of file diff --git a/Lang/Aime/Literals-Floating-point b/Lang/Aime/Literals-Floating-point new file mode 120000 index 0000000000..7d8a8c86d0 --- /dev/null +++ b/Lang/Aime/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Aime \ No newline at end of file diff --git a/Lang/Aime/Loops-N-plus-one-half b/Lang/Aime/Loops-N-plus-one-half new file mode 120000 index 0000000000..782d9028a3 --- /dev/null +++ b/Lang/Aime/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Aime \ No newline at end of file diff --git a/Lang/Aime/Mad-Libs b/Lang/Aime/Mad-Libs new file mode 120000 index 0000000000..1b3070feef --- /dev/null +++ b/Lang/Aime/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Aime \ No newline at end of file diff --git a/Lang/Aime/Middle-three-digits b/Lang/Aime/Middle-three-digits new file mode 120000 index 0000000000..c1caa5c980 --- /dev/null +++ b/Lang/Aime/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Aime \ No newline at end of file diff --git a/Lang/Aime/Multiple-distinct-objects b/Lang/Aime/Multiple-distinct-objects new file mode 120000 index 0000000000..f7d781f363 --- /dev/null +++ b/Lang/Aime/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Aime \ No newline at end of file diff --git a/Lang/Aime/Non-decimal-radices-Convert b/Lang/Aime/Non-decimal-radices-Convert new file mode 120000 index 0000000000..9c0eab55b1 --- /dev/null +++ b/Lang/Aime/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Aime \ No newline at end of file diff --git a/Lang/Aime/Non-decimal-radices-Input b/Lang/Aime/Non-decimal-radices-Input new file mode 120000 index 0000000000..9976d7973a --- /dev/null +++ b/Lang/Aime/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Aime \ No newline at end of file diff --git a/Lang/Aime/Non-decimal-radices-Output b/Lang/Aime/Non-decimal-radices-Output new file mode 120000 index 0000000000..8d212f218f --- /dev/null +++ b/Lang/Aime/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Aime \ No newline at end of file diff --git a/Lang/Aime/Ordered-words b/Lang/Aime/Ordered-words new file mode 120000 index 0000000000..a31c051b42 --- /dev/null +++ b/Lang/Aime/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Aime \ No newline at end of file diff --git a/Lang/Aime/Program-name b/Lang/Aime/Program-name new file mode 120000 index 0000000000..473f7386a5 --- /dev/null +++ b/Lang/Aime/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Aime \ No newline at end of file diff --git a/Lang/Aime/Program-termination b/Lang/Aime/Program-termination new file mode 120000 index 0000000000..c9781082a8 --- /dev/null +++ b/Lang/Aime/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Aime \ No newline at end of file diff --git a/Lang/Aime/Quine b/Lang/Aime/Quine new file mode 120000 index 0000000000..52dcca1e4f --- /dev/null +++ b/Lang/Aime/Quine @@ -0,0 +1 @@ +../../Task/Quine/Aime \ No newline at end of file diff --git a/Lang/Aime/Real-constants-and-functions b/Lang/Aime/Real-constants-and-functions new file mode 120000 index 0000000000..f22102c298 --- /dev/null +++ b/Lang/Aime/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Aime \ No newline at end of file diff --git a/Lang/Aime/Reduced-row-echelon-form b/Lang/Aime/Reduced-row-echelon-form new file mode 120000 index 0000000000..db90127682 --- /dev/null +++ b/Lang/Aime/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Aime \ No newline at end of file diff --git a/Lang/Aime/Reverse-a-string b/Lang/Aime/Reverse-a-string new file mode 120000 index 0000000000..aa99c6b1c6 --- /dev/null +++ b/Lang/Aime/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Aime \ No newline at end of file diff --git a/Lang/Aime/Rock-paper-scissors b/Lang/Aime/Rock-paper-scissors new file mode 120000 index 0000000000..1259a7f183 --- /dev/null +++ b/Lang/Aime/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Aime \ No newline at end of file diff --git a/Lang/Aime/Search-a-list b/Lang/Aime/Search-a-list new file mode 120000 index 0000000000..fb39b649a6 --- /dev/null +++ b/Lang/Aime/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Aime \ No newline at end of file diff --git a/Lang/Aime/Self-referential-sequence b/Lang/Aime/Self-referential-sequence new file mode 120000 index 0000000000..936acfec49 --- /dev/null +++ b/Lang/Aime/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Aime \ No newline at end of file diff --git a/Lang/Aime/Semordnilap b/Lang/Aime/Semordnilap new file mode 120000 index 0000000000..f1d378c8bc --- /dev/null +++ b/Lang/Aime/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Aime \ No newline at end of file diff --git a/Lang/Aime/Set-consolidation b/Lang/Aime/Set-consolidation new file mode 120000 index 0000000000..49ab17a992 --- /dev/null +++ b/Lang/Aime/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Aime \ No newline at end of file diff --git a/Lang/Aime/String-concatenation b/Lang/Aime/String-concatenation new file mode 120000 index 0000000000..bc1ecf1f5a --- /dev/null +++ b/Lang/Aime/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Aime \ No newline at end of file diff --git a/Lang/Aime/String-length b/Lang/Aime/String-length new file mode 120000 index 0000000000..fb3907e51a --- /dev/null +++ b/Lang/Aime/String-length @@ -0,0 +1 @@ +../../Task/String-length/Aime \ No newline at end of file diff --git a/Lang/Aime/Substring-Top-and-tail b/Lang/Aime/Substring-Top-and-tail new file mode 120000 index 0000000000..5575ffdc06 --- /dev/null +++ b/Lang/Aime/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Aime \ No newline at end of file diff --git a/Lang/Aime/Sum-of-a-series b/Lang/Aime/Sum-of-a-series new file mode 120000 index 0000000000..2e5723e46f --- /dev/null +++ b/Lang/Aime/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Aime \ No newline at end of file diff --git a/Lang/Aime/Symmetric-difference b/Lang/Aime/Symmetric-difference new file mode 120000 index 0000000000..385f81b38f --- /dev/null +++ b/Lang/Aime/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Aime \ No newline at end of file diff --git a/Lang/Aime/Take-notes-on-the-command-line b/Lang/Aime/Take-notes-on-the-command-line new file mode 120000 index 0000000000..9a6dc3e99b --- /dev/null +++ b/Lang/Aime/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Aime \ No newline at end of file diff --git a/Lang/AppleScript/String-concatenation b/Lang/AppleScript/String-concatenation new file mode 120000 index 0000000000..b685754370 --- /dev/null +++ b/Lang/AppleScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/AppleScript \ No newline at end of file diff --git a/Lang/BASIC/Include-a-file b/Lang/BASIC/Include-a-file new file mode 120000 index 0000000000..f1bd82bcd4 --- /dev/null +++ b/Lang/BASIC/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Temperature-conversion b/Lang/BBC-BASIC/Temperature-conversion new file mode 120000 index 0000000000..8e728fd95c --- /dev/null +++ b/Lang/BBC-BASIC/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/BBC-BASIC \ No newline at end of file diff --git a/Lang/Babel/00DESCRIPTION b/Lang/Babel/00DESCRIPTION index 6e8ba18e2b..6da7289d0c 100644 --- a/Lang/Babel/00DESCRIPTION +++ b/Lang/Babel/00DESCRIPTION @@ -1,6 +1,6 @@ {{alertbox|#ffffe0|''Were you looking for the [[Common Lisp]] library? That category has now been [[:Category:Babel (library)|renamed]].''}} {{language}}Babel is an interpreted language designed by Clayton Bauman. It is an untyped, stack-based, postfix language with support for arrays, lists and hashes (dictionaries). Babel 1.0 will support built-in crypto-based verification of code in order to enable safer remote code execution. -Babel is implemented in [[C]]. It is still under development with a v0.9 release planned for December 2012, so please excuse the dust and debris in the [https://github.com/claytonkb/Babel current implementation]. +Babel is implemented in [[C]]. It is still under development with a v0.9 release planned for December 2013, so please excuse the dust and debris in the [https://github.com/claytonkb/Babel current implementation]. Check out the README and the doc/ folder on github for more information. \ No newline at end of file diff --git a/Lang/Bracmat/Associative-array-Creation b/Lang/Bracmat/Associative-array-Creation new file mode 120000 index 0000000000..ccbd7260b7 --- /dev/null +++ b/Lang/Bracmat/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Associative-array-Iteration b/Lang/Bracmat/Associative-array-Iteration new file mode 120000 index 0000000000..46edc2ddf6 --- /dev/null +++ b/Lang/Bracmat/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Binary-digits b/Lang/Bracmat/Binary-digits new file mode 120000 index 0000000000..c8db034ad6 --- /dev/null +++ b/Lang/Bracmat/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Case-sensitivity-of-identifiers b/Lang/Bracmat/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..721c42b0ac --- /dev/null +++ b/Lang/Bracmat/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Execute-a-Markov-algorithm b/Lang/Bracmat/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..706475ab15 --- /dev/null +++ b/Lang/Bracmat/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Greatest-element-of-a-list b/Lang/Bracmat/Greatest-element-of-a-list new file mode 120000 index 0000000000..0b59db7392 --- /dev/null +++ b/Lang/Bracmat/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Loops-Infinite b/Lang/Bracmat/Loops-Infinite new file mode 120000 index 0000000000..a9deca6c72 --- /dev/null +++ b/Lang/Bracmat/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Loops-N-plus-one-half b/Lang/Bracmat/Loops-N-plus-one-half new file mode 120000 index 0000000000..6e4227ae79 --- /dev/null +++ b/Lang/Bracmat/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Middle-three-digits b/Lang/Bracmat/Middle-three-digits new file mode 120000 index 0000000000..cf30e309fb --- /dev/null +++ b/Lang/Bracmat/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Read-a-file-line-by-line b/Lang/Bracmat/Read-a-file-line-by-line new file mode 120000 index 0000000000..9da12b37f3 --- /dev/null +++ b/Lang/Bracmat/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Same-Fringe b/Lang/Bracmat/Same-Fringe new file mode 120000 index 0000000000..1db37c3f1a --- /dev/null +++ b/Lang/Bracmat/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Search-a-list b/Lang/Bracmat/Search-a-list new file mode 120000 index 0000000000..65be3c082e --- /dev/null +++ b/Lang/Bracmat/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Semordnilap b/Lang/Bracmat/Semordnilap new file mode 120000 index 0000000000..8d75e46e6b --- /dev/null +++ b/Lang/Bracmat/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Send-an-unknown-method-call b/Lang/Bracmat/Send-an-unknown-method-call new file mode 120000 index 0000000000..9e0b8576b5 --- /dev/null +++ b/Lang/Bracmat/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Shell-one-liner b/Lang/Bracmat/Shell-one-liner new file mode 120000 index 0000000000..781433b4d1 --- /dev/null +++ b/Lang/Bracmat/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Short-circuit-evaluation b/Lang/Bracmat/Short-circuit-evaluation new file mode 120000 index 0000000000..040ca9cbd7 --- /dev/null +++ b/Lang/Bracmat/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Solve-a-Hidato-puzzle b/Lang/Bracmat/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..e51f24ed2b --- /dev/null +++ b/Lang/Bracmat/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/String-comparison b/Lang/Bracmat/String-comparison new file mode 120000 index 0000000000..6b57bf76dc --- /dev/null +++ b/Lang/Bracmat/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Sum-of-a-series b/Lang/Bracmat/Sum-of-a-series new file mode 120000 index 0000000000..50bc305c25 --- /dev/null +++ b/Lang/Bracmat/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Bracmat \ No newline at end of file diff --git a/Lang/C++/Anagrams-Deranged-anagrams b/Lang/C++/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..cb5cbac3c1 --- /dev/null +++ b/Lang/C++/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/C++ \ No newline at end of file diff --git a/Lang/C++/Brownian-tree b/Lang/C++/Brownian-tree new file mode 120000 index 0000000000..9a3861a4a1 --- /dev/null +++ b/Lang/C++/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/C++ \ No newline at end of file diff --git a/Lang/C++/Bulls-and-cows-Player b/Lang/C++/Bulls-and-cows-Player new file mode 120000 index 0000000000..d7ba9477db --- /dev/null +++ b/Lang/C++/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/C++ \ No newline at end of file diff --git a/Lang/C++/Calendar b/Lang/C++/Calendar new file mode 120000 index 0000000000..43e94ad28f --- /dev/null +++ b/Lang/C++/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/C++ \ No newline at end of file diff --git a/Lang/C++/Colour-pinstripe-Display b/Lang/C++/Colour-pinstripe-Display new file mode 120000 index 0000000000..923715ef89 --- /dev/null +++ b/Lang/C++/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/C++ \ No newline at end of file diff --git a/Lang/C++/Constrained-random-points-on-a-circle b/Lang/C++/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..faa26eb8b9 --- /dev/null +++ b/Lang/C++/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/C++ \ No newline at end of file diff --git a/Lang/C++/Deal-cards-for-FreeCell b/Lang/C++/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..d08c2c770c --- /dev/null +++ b/Lang/C++/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/C++ \ No newline at end of file diff --git a/Lang/C++/Discordian-date b/Lang/C++/Discordian-date new file mode 120000 index 0000000000..45b028b031 --- /dev/null +++ b/Lang/C++/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/C++ \ No newline at end of file diff --git a/Lang/C++/Dragon-curve b/Lang/C++/Dragon-curve new file mode 120000 index 0000000000..6dd9ec5a16 --- /dev/null +++ b/Lang/C++/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/C++ \ No newline at end of file diff --git a/Lang/C++/Floyds-triangle b/Lang/C++/Floyds-triangle new file mode 120000 index 0000000000..15b6756185 --- /dev/null +++ b/Lang/C++/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/C++ \ No newline at end of file diff --git a/Lang/C++/Forest-fire b/Lang/C++/Forest-fire new file mode 120000 index 0000000000..1d2ed11c46 --- /dev/null +++ b/Lang/C++/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/C++ \ No newline at end of file diff --git a/Lang/C++/Fractal-tree b/Lang/C++/Fractal-tree new file mode 120000 index 0000000000..4d61183f13 --- /dev/null +++ b/Lang/C++/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/C++ \ No newline at end of file diff --git a/Lang/C++/Image-noise b/Lang/C++/Image-noise new file mode 120000 index 0000000000..2090bcea27 --- /dev/null +++ b/Lang/C++/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/C++ \ No newline at end of file diff --git a/Lang/C++/Josephus-problem b/Lang/C++/Josephus-problem new file mode 120000 index 0000000000..31bed45f68 --- /dev/null +++ b/Lang/C++/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/C++ \ No newline at end of file diff --git a/Lang/C++/Langtons-ant b/Lang/C++/Langtons-ant new file mode 120000 index 0000000000..04ff483358 --- /dev/null +++ b/Lang/C++/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/C++ \ No newline at end of file diff --git a/Lang/C++/Largest-int-from-concatenated-ints b/Lang/C++/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..0c8a880d11 --- /dev/null +++ b/Lang/C++/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/C++ \ No newline at end of file diff --git a/Lang/C++/Linear-congruential-generator b/Lang/C++/Linear-congruential-generator new file mode 120000 index 0000000000..1c190b5a77 --- /dev/null +++ b/Lang/C++/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/C++ \ No newline at end of file diff --git a/Lang/C++/Maze-generation b/Lang/C++/Maze-generation new file mode 120000 index 0000000000..36bea47d3d --- /dev/null +++ b/Lang/C++/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/C++ \ No newline at end of file diff --git a/Lang/C++/Maze-solving b/Lang/C++/Maze-solving new file mode 120000 index 0000000000..5b3e0a9ba0 --- /dev/null +++ b/Lang/C++/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/C++ \ No newline at end of file diff --git a/Lang/C++/Modular-inverse b/Lang/C++/Modular-inverse new file mode 120000 index 0000000000..46b0c82024 --- /dev/null +++ b/Lang/C++/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/C++ \ No newline at end of file diff --git a/Lang/C++/N-queens-problem b/Lang/C++/N-queens-problem new file mode 120000 index 0000000000..5a7e60a726 --- /dev/null +++ b/Lang/C++/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/C++ \ No newline at end of file diff --git a/Lang/C++/Nautical-bell b/Lang/C++/Nautical-bell new file mode 120000 index 0000000000..a508a62c4e --- /dev/null +++ b/Lang/C++/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/C++ \ No newline at end of file diff --git a/Lang/C++/Pick-random-element b/Lang/C++/Pick-random-element new file mode 120000 index 0000000000..970742e748 --- /dev/null +++ b/Lang/C++/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/C++ \ No newline at end of file diff --git a/Lang/C++/Pig-the-dice-game b/Lang/C++/Pig-the-dice-game new file mode 120000 index 0000000000..0c9e718654 --- /dev/null +++ b/Lang/C++/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/C++ \ No newline at end of file diff --git a/Lang/C++/Pig-the-dice-game-Player b/Lang/C++/Pig-the-dice-game-Player new file mode 120000 index 0000000000..3282dce12b --- /dev/null +++ b/Lang/C++/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/C++ \ No newline at end of file diff --git a/Lang/C++/Pinstripe-Display b/Lang/C++/Pinstripe-Display new file mode 120000 index 0000000000..60315c5cb6 --- /dev/null +++ b/Lang/C++/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/C++ \ No newline at end of file diff --git a/Lang/C++/Plot-coordinate-pairs b/Lang/C++/Plot-coordinate-pairs new file mode 120000 index 0000000000..51ac602842 --- /dev/null +++ b/Lang/C++/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/C++ \ No newline at end of file diff --git a/Lang/C++/Random-number-generator--included- b/Lang/C++/Random-number-generator--included- new file mode 120000 index 0000000000..8c01dba38f --- /dev/null +++ b/Lang/C++/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/C++ \ No newline at end of file diff --git a/Lang/C++/Self-describing-numbers b/Lang/C++/Self-describing-numbers new file mode 120000 index 0000000000..b4512bee7c --- /dev/null +++ b/Lang/C++/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/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..6b4efce755 --- /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++/Solve-a-Hidato-puzzle b/Lang/C++/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..7af11ae4e2 --- /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++/Sorting-algorithms-Cocktail-sort b/Lang/C++/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..3926790401 --- /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-Counting-sort b/Lang/C++/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..17af373c5d --- /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-Shell-sort b/Lang/C++/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..9d9d67a2af --- /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++/Temperature-conversion b/Lang/C++/Temperature-conversion new file mode 120000 index 0000000000..44f0c6c6e8 --- /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/Dutch-national-flag-problem b/Lang/C/Dutch-national-flag-problem new file mode 120000 index 0000000000..d1a569ba27 --- /dev/null +++ b/Lang/C/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/C \ No newline at end of file diff --git a/Lang/C/Entropy b/Lang/C/Entropy new file mode 120000 index 0000000000..7ad11f0c38 --- /dev/null +++ b/Lang/C/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/C \ No newline at end of file diff --git a/Lang/C/I-before-E-except-after-C b/Lang/C/I-before-E-except-after-C new file mode 120000 index 0000000000..d7ec379bba --- /dev/null +++ b/Lang/C/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/C \ No newline at end of file diff --git a/Lang/C/List-comprehensions b/Lang/C/List-comprehensions new file mode 120000 index 0000000000..b2e8244923 --- /dev/null +++ b/Lang/C/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/C \ No newline at end of file diff --git a/Lang/C/String-comparison b/Lang/C/String-comparison new file mode 120000 index 0000000000..de0bdf677e --- /dev/null +++ b/Lang/C/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/C \ No newline at end of file diff --git a/Lang/COBOL/A+B b/Lang/COBOL/A+B new file mode 120000 index 0000000000..356ed352a7 --- /dev/null +++ b/Lang/COBOL/A+B @@ -0,0 +1 @@ +../../Task/A+B/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Apply-a-callback-to-an-array b/Lang/COBOL/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..bf322f47b8 --- /dev/null +++ b/Lang/COBOL/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Date-format b/Lang/COBOL/Date-format new file mode 120000 index 0000000000..8411a03214 --- /dev/null +++ b/Lang/COBOL/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Delete-a-file b/Lang/COBOL/Delete-a-file new file mode 120000 index 0000000000..f0734866c6 --- /dev/null +++ b/Lang/COBOL/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Determine-if-a-string-is-numeric b/Lang/COBOL/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..82229ed0e4 --- /dev/null +++ b/Lang/COBOL/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Even-or-odd b/Lang/COBOL/Even-or-odd new file mode 120000 index 0000000000..e085a30656 --- /dev/null +++ b/Lang/COBOL/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Guess-the-number b/Lang/COBOL/Guess-the-number new file mode 120000 index 0000000000..41b6c36aec --- /dev/null +++ b/Lang/COBOL/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Harshad-or-Niven-series b/Lang/COBOL/Harshad-or-Niven-series new file mode 120000 index 0000000000..550d789fec --- /dev/null +++ b/Lang/COBOL/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-Break b/Lang/COBOL/Loops-Break new file mode 120000 index 0000000000..2783fa23d6 --- /dev/null +++ b/Lang/COBOL/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-Downward-for b/Lang/COBOL/Loops-Downward-for new file mode 120000 index 0000000000..2ca74d7e57 --- /dev/null +++ b/Lang/COBOL/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-For b/Lang/COBOL/Loops-For new file mode 120000 index 0000000000..3230ae2d4e --- /dev/null +++ b/Lang/COBOL/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-Infinite b/Lang/COBOL/Loops-Infinite new file mode 120000 index 0000000000..74fbddd25b --- /dev/null +++ b/Lang/COBOL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Loops-N-plus-one-half b/Lang/COBOL/Loops-N-plus-one-half new file mode 120000 index 0000000000..bee6aa1136 --- /dev/null +++ b/Lang/COBOL/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Luhn-test-of-credit-card-numbers b/Lang/COBOL/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..f7b03e4982 --- /dev/null +++ b/Lang/COBOL/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Middle-three-digits b/Lang/COBOL/Middle-three-digits new file mode 120000 index 0000000000..1ddabc80bf --- /dev/null +++ b/Lang/COBOL/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Roman-numerals-Decode b/Lang/COBOL/Roman-numerals-Decode new file mode 120000 index 0000000000..c8cce906e0 --- /dev/null +++ b/Lang/COBOL/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Roman-numerals-Encode b/Lang/COBOL/Roman-numerals-Encode new file mode 120000 index 0000000000..567a07f00c --- /dev/null +++ b/Lang/COBOL/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sieve-of-Eratosthenes b/Lang/COBOL/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..70541d6aa8 --- /dev/null +++ b/Lang/COBOL/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sleep b/Lang/COBOL/Sleep new file mode 120000 index 0000000000..51869a0b25 --- /dev/null +++ b/Lang/COBOL/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/COBOL \ No newline at end of file diff --git a/Lang/COBOL/String-concatenation b/Lang/COBOL/String-concatenation new file mode 120000 index 0000000000..3655404a03 --- /dev/null +++ b/Lang/COBOL/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Terminal-control-Display-an-extended-character b/Lang/COBOL/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..270439c37a --- /dev/null +++ b/Lang/COBOL/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/COBOL \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Abstract-type b/Lang/Cache-ObjectScript/Abstract-type new file mode 120000 index 0000000000..54a946cf13 --- /dev/null +++ b/Lang/Cache-ObjectScript/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Object-serialization b/Lang/Cache-ObjectScript/Object-serialization new file mode 120000 index 0000000000..e28319045e --- /dev/null +++ b/Lang/Cache-ObjectScript/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Respond-to-an-unknown-method-call b/Lang/Cache-ObjectScript/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..850ed11be4 --- /dev/null +++ b/Lang/Cache-ObjectScript/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Send-an-unknown-method-call b/Lang/Cache-ObjectScript/Send-an-unknown-method-call new file mode 120000 index 0000000000..8dd85fde54 --- /dev/null +++ b/Lang/Cache-ObjectScript/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Singleton b/Lang/Cache-ObjectScript/Singleton new file mode 120000 index 0000000000..94bc001917 --- /dev/null +++ b/Lang/Cache-ObjectScript/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Chapel/Loops-For-with-a-specified-step b/Lang/Chapel/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..7a5037dd81 --- /dev/null +++ b/Lang/Chapel/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Chapel \ No newline at end of file diff --git a/Lang/Clojure/Semordnilap b/Lang/Clojure/Semordnilap new file mode 120000 index 0000000000..16e8375454 --- /dev/null +++ b/Lang/Clojure/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Clojure \ No newline at end of file diff --git a/Lang/Common-Lisp/Entropy b/Lang/Common-Lisp/Entropy new file mode 120000 index 0000000000..51621a9356 --- /dev/null +++ b/Lang/Common-Lisp/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/I-before-E-except-after-C b/Lang/Common-Lisp/I-before-E-except-after-C new file mode 120000 index 0000000000..2e2fccbf98 --- /dev/null +++ b/Lang/Common-Lisp/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Common-Lisp \ No newline at end of file diff --git a/Lang/D/First-class-environments b/Lang/D/First-class-environments new file mode 120000 index 0000000000..b5ed9e0608 --- /dev/null +++ b/Lang/D/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/D \ No newline at end of file diff --git a/Lang/D/Memory-allocation b/Lang/D/Memory-allocation new file mode 120000 index 0000000000..56db9e58e3 --- /dev/null +++ b/Lang/D/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/D \ No newline at end of file diff --git a/Lang/D/Pig-the-dice-game-Player b/Lang/D/Pig-the-dice-game-Player new file mode 120000 index 0000000000..e5ac71e549 --- /dev/null +++ b/Lang/D/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/D \ No newline at end of file diff --git a/Lang/D/Rosetta-Code-Fix-code-tags b/Lang/D/Rosetta-Code-Fix-code-tags new file mode 120000 index 0000000000..5663332dd6 --- /dev/null +++ b/Lang/D/Rosetta-Code-Fix-code-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Fix-code-tags/D \ No newline at end of file diff --git a/Lang/DWScript/Sort-an-integer-array b/Lang/DWScript/Sort-an-integer-array new file mode 120000 index 0000000000..17b964e4c4 --- /dev/null +++ b/Lang/DWScript/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/DWScript \ No newline at end of file diff --git a/Lang/Delphi/00DESCRIPTION b/Lang/Delphi/00DESCRIPTION index 5a14d212a8..3e2f6ac4af 100644 --- a/Lang/Delphi/00DESCRIPTION +++ b/Lang/Delphi/00DESCRIPTION @@ -22,7 +22,6 @@ Among Delphi's strengths are its easy learning curve, consistent language archit The Delphi XE2 version added support for 64-bit applications. It also added a cross platform compiler and component library allowing it to create cross platform applications for Mac OS X and iOS. The iOS support is actually achieved using the Free Pascal compiler. ==Variants== -* [[Free Pascal]] is an open source version of Delphi that implements most of the language. The Lazarus IDE and libraries emulates the RTL ([[wp:runtime library|runtime library]]) and VCL. * Embarcadero, and Borland before it, experimented with using the "Delphi" name to brand tools based on other languages. Examples include Delphi for [[:Category:PHP|PHP]] which was renamed RAD PHP, and Delphi Prism, which was renamed Embarcadero Prism. The latter makes use of the [[wp:Oxygene (programming language)|Oxygene]] dialect of Pascal provided by RemObjects Software, to build cross platform .NET and Mono applications. * There is also Delphi/400 which is actually the main Embarcadero Delphi product repackaged with AS/400 and sold by SystemObjects. * [[DWScript]] is a Delphi-hosted script engine that implements most of the Delphi language, along with FreePascal/Oxygene extensions. diff --git a/Lang/Eiffel/Factorial b/Lang/Eiffel/Factorial new file mode 120000 index 0000000000..eafa29ed15 --- /dev/null +++ b/Lang/Eiffel/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sum-of-a-series b/Lang/Eiffel/Sum-of-a-series new file mode 120000 index 0000000000..7be4f4f731 --- /dev/null +++ b/Lang/Eiffel/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Eiffel \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Standard-deviation b/Lang/Emacs-Lisp/Standard-deviation new file mode 120000 index 0000000000..5fe66f8f9a --- /dev/null +++ b/Lang/Emacs-Lisp/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Active-Directory-Connect b/Lang/Erlang/Active-Directory-Connect new file mode 120000 index 0000000000..6ab9e38d3a --- /dev/null +++ b/Lang/Erlang/Active-Directory-Connect @@ -0,0 +1 @@ +../../Task/Active-Directory-Connect/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Active-object b/Lang/Erlang/Active-object new file mode 120000 index 0000000000..b084c85b9f --- /dev/null +++ b/Lang/Erlang/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Anagrams-Deranged-anagrams b/Lang/Erlang/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..3288e797b1 --- /dev/null +++ b/Lang/Erlang/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Anonymous-recursion b/Lang/Erlang/Anonymous-recursion new file mode 120000 index 0000000000..dd55815d14 --- /dev/null +++ b/Lang/Erlang/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Arena-storage-pool b/Lang/Erlang/Arena-storage-pool new file mode 120000 index 0000000000..2842bff3a5 --- /dev/null +++ b/Lang/Erlang/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Arithmetic-Integer b/Lang/Erlang/Arithmetic-Integer new file mode 120000 index 0000000000..33f9e516cc --- /dev/null +++ b/Lang/Erlang/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Atomic-updates b/Lang/Erlang/Atomic-updates new file mode 120000 index 0000000000..2abf37aedf --- /dev/null +++ b/Lang/Erlang/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Averages-Mean-angle b/Lang/Erlang/Averages-Mean-angle new file mode 120000 index 0000000000..0b74a11393 --- /dev/null +++ b/Lang/Erlang/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Averages-Mean-time-of-day b/Lang/Erlang/Averages-Mean-time-of-day new file mode 120000 index 0000000000..a37d667447 --- /dev/null +++ b/Lang/Erlang/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Averages-Mode b/Lang/Erlang/Averages-Mode new file mode 120000 index 0000000000..64f6f1f400 --- /dev/null +++ b/Lang/Erlang/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Balanced-brackets b/Lang/Erlang/Balanced-brackets new file mode 120000 index 0000000000..13b00a7fd2 --- /dev/null +++ b/Lang/Erlang/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Case-sensitivity-of-identifiers b/Lang/Erlang/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..15c5e4b310 --- /dev/null +++ b/Lang/Erlang/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Create-a-file b/Lang/Erlang/Create-a-file new file mode 120000 index 0000000000..3657ad109a --- /dev/null +++ b/Lang/Erlang/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Day-of-the-week b/Lang/Erlang/Day-of-the-week new file mode 120000 index 0000000000..3932c45693 --- /dev/null +++ b/Lang/Erlang/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Even-or-odd b/Lang/Erlang/Even-or-odd new file mode 120000 index 0000000000..b3b61d99a0 --- /dev/null +++ b/Lang/Erlang/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Erlang \ No newline at end of file diff --git a/Lang/Erlang/File-modification-time b/Lang/Erlang/File-modification-time new file mode 120000 index 0000000000..5a34379a64 --- /dev/null +++ b/Lang/Erlang/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Floyds-triangle b/Lang/Erlang/Floyds-triangle new file mode 120000 index 0000000000..14456514d0 --- /dev/null +++ b/Lang/Erlang/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Guess-the-number b/Lang/Erlang/Guess-the-number new file mode 120000 index 0000000000..6643360faa --- /dev/null +++ b/Lang/Erlang/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Guess-the-number-With-feedback b/Lang/Erlang/Guess-the-number-With-feedback new file mode 120000 index 0000000000..250e95ee6a --- /dev/null +++ b/Lang/Erlang/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Guess-the-number-With-feedback--player- b/Lang/Erlang/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..0e4b8e6bc4 --- /dev/null +++ b/Lang/Erlang/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Haversine-formula b/Lang/Erlang/Haversine-formula new file mode 120000 index 0000000000..5e97f11f1d --- /dev/null +++ b/Lang/Erlang/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Here-document b/Lang/Erlang/Here-document new file mode 120000 index 0000000000..fdef278ce8 --- /dev/null +++ b/Lang/Erlang/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Identity-matrix b/Lang/Erlang/Identity-matrix new file mode 120000 index 0000000000..4df9fcae46 --- /dev/null +++ b/Lang/Erlang/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Input-loop b/Lang/Erlang/Input-loop new file mode 120000 index 0000000000..8dab1cacfc --- /dev/null +++ b/Lang/Erlang/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Least-common-multiple b/Lang/Erlang/Least-common-multiple new file mode 120000 index 0000000000..f08df5076b --- /dev/null +++ b/Lang/Erlang/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-Break b/Lang/Erlang/Loops-Break new file mode 120000 index 0000000000..2531cad83d --- /dev/null +++ b/Lang/Erlang/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-Continue b/Lang/Erlang/Loops-Continue new file mode 120000 index 0000000000..6ea7b4f2e8 --- /dev/null +++ b/Lang/Erlang/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-Downward-for b/Lang/Erlang/Loops-Downward-for new file mode 120000 index 0000000000..46a1bb18ef --- /dev/null +++ b/Lang/Erlang/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-For b/Lang/Erlang/Loops-For new file mode 120000 index 0000000000..4313047974 --- /dev/null +++ b/Lang/Erlang/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-For-with-a-specified-step b/Lang/Erlang/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..9c92749470 --- /dev/null +++ b/Lang/Erlang/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-N-plus-one-half b/Lang/Erlang/Loops-N-plus-one-half new file mode 120000 index 0000000000..18cd28ab4c --- /dev/null +++ b/Lang/Erlang/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Loops-While b/Lang/Erlang/Loops-While new file mode 120000 index 0000000000..9a62d7ee62 --- /dev/null +++ b/Lang/Erlang/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Middle-three-digits b/Lang/Erlang/Middle-three-digits new file mode 120000 index 0000000000..fc0cc81ff5 --- /dev/null +++ b/Lang/Erlang/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Order-two-numerical-lists b/Lang/Erlang/Order-two-numerical-lists new file mode 120000 index 0000000000..a84641e17f --- /dev/null +++ b/Lang/Erlang/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Pi b/Lang/Erlang/Pi new file mode 120000 index 0000000000..a06fbb794d --- /dev/null +++ b/Lang/Erlang/Pi @@ -0,0 +1 @@ +../../Task/Pi/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Pick-random-element b/Lang/Erlang/Pick-random-element new file mode 120000 index 0000000000..e3aef69f7a --- /dev/null +++ b/Lang/Erlang/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Plot-coordinate-pairs b/Lang/Erlang/Plot-coordinate-pairs new file mode 120000 index 0000000000..48c5ebc230 --- /dev/null +++ b/Lang/Erlang/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Program-termination b/Lang/Erlang/Program-termination new file mode 120000 index 0000000000..22a84fe9e6 --- /dev/null +++ b/Lang/Erlang/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Read-a-file-line-by-line b/Lang/Erlang/Read-a-file-line-by-line new file mode 120000 index 0000000000..c506d2da86 --- /dev/null +++ b/Lang/Erlang/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Read-a-specific-line-from-a-file b/Lang/Erlang/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..fdf96a576a --- /dev/null +++ b/Lang/Erlang/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Real-constants-and-functions b/Lang/Erlang/Real-constants-and-functions new file mode 120000 index 0000000000..04b06ec8c5 --- /dev/null +++ b/Lang/Erlang/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Return-multiple-values b/Lang/Erlang/Return-multiple-values new file mode 120000 index 0000000000..1f7da03a5f --- /dev/null +++ b/Lang/Erlang/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Roots-of-a-function b/Lang/Erlang/Roots-of-a-function new file mode 120000 index 0000000000..23df4283e3 --- /dev/null +++ b/Lang/Erlang/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Rosetta-Code-Rank-languages-by-popularity b/Lang/Erlang/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..2f795051dc --- /dev/null +++ b/Lang/Erlang/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Runtime-evaluation-In-an-environment b/Lang/Erlang/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..f9791bbdd8 --- /dev/null +++ b/Lang/Erlang/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Semordnilap b/Lang/Erlang/Semordnilap new file mode 120000 index 0000000000..c522459af0 --- /dev/null +++ b/Lang/Erlang/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sequence-of-non-squares b/Lang/Erlang/Sequence-of-non-squares new file mode 120000 index 0000000000..01170f31dd --- /dev/null +++ b/Lang/Erlang/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sierpinski-carpet b/Lang/Erlang/Sierpinski-carpet new file mode 120000 index 0000000000..78a8ea8fba --- /dev/null +++ b/Lang/Erlang/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Bubble-sort b/Lang/Erlang/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..b83720aaaa --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/String-comparison b/Lang/Erlang/String-comparison new file mode 120000 index 0000000000..9f0c5a72ad --- /dev/null +++ b/Lang/Erlang/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Erlang/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..9b0e00bc3f --- /dev/null +++ b/Lang/Erlang/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Substring-Top-and-tail b/Lang/Erlang/Substring-Top-and-tail new file mode 120000 index 0000000000..b08ecbc689 --- /dev/null +++ b/Lang/Erlang/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Temperature-conversion b/Lang/Erlang/Temperature-conversion new file mode 120000 index 0000000000..d3b8785740 --- /dev/null +++ b/Lang/Erlang/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Ternary-logic b/Lang/Erlang/Ternary-logic new file mode 120000 index 0000000000..e7fce74fec --- /dev/null +++ b/Lang/Erlang/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Erlang \ No newline at end of file diff --git a/Lang/Euphoria/Include-a-file b/Lang/Euphoria/Include-a-file new file mode 120000 index 0000000000..186d736a4d --- /dev/null +++ b/Lang/Euphoria/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Euphoria \ No newline at end of file diff --git a/Lang/FBSL/100-doors b/Lang/FBSL/100-doors new file mode 120000 index 0000000000..fea468a060 --- /dev/null +++ b/Lang/FBSL/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/FBSL \ No newline at end of file diff --git a/Lang/FBSL/A+B b/Lang/FBSL/A+B new file mode 120000 index 0000000000..a373400f75 --- /dev/null +++ b/Lang/FBSL/A+B @@ -0,0 +1 @@ +../../Task/A+B/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Ackermann-function b/Lang/FBSL/Ackermann-function new file mode 120000 index 0000000000..7d573b205a --- /dev/null +++ b/Lang/FBSL/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Active-object b/Lang/FBSL/Active-object new file mode 120000 index 0000000000..050dc86904 --- /dev/null +++ b/Lang/FBSL/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Add-a-variable-to-a-class-instance-at-runtime b/Lang/FBSL/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..d16e6a84d7 --- /dev/null +++ b/Lang/FBSL/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Align-columns b/Lang/FBSL/Align-columns new file mode 120000 index 0000000000..39598b5f3b --- /dev/null +++ b/Lang/FBSL/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Anagrams b/Lang/FBSL/Anagrams new file mode 120000 index 0000000000..24dd03d3b9 --- /dev/null +++ b/Lang/FBSL/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Animate-a-pendulum b/Lang/FBSL/Animate-a-pendulum new file mode 120000 index 0000000000..8c0460df39 --- /dev/null +++ b/Lang/FBSL/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Animation b/Lang/FBSL/Animation new file mode 120000 index 0000000000..7231c42ba4 --- /dev/null +++ b/Lang/FBSL/Animation @@ -0,0 +1 @@ +../../Task/Animation/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Anonymous-recursion b/Lang/FBSL/Anonymous-recursion new file mode 120000 index 0000000000..04a7d69810 --- /dev/null +++ b/Lang/FBSL/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Apply-a-callback-to-an-array b/Lang/FBSL/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..0f0f77ddaa --- /dev/null +++ b/Lang/FBSL/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Array-concatenation b/Lang/FBSL/Array-concatenation new file mode 120000 index 0000000000..6f219f30b4 --- /dev/null +++ b/Lang/FBSL/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Arrays b/Lang/FBSL/Arrays new file mode 120000 index 0000000000..d20fd16eea --- /dev/null +++ b/Lang/FBSL/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Assertions b/Lang/FBSL/Assertions new file mode 120000 index 0000000000..a354c23ba7 --- /dev/null +++ b/Lang/FBSL/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Binary-search b/Lang/FBSL/Binary-search new file mode 120000 index 0000000000..220aad1c6c --- /dev/null +++ b/Lang/FBSL/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap b/Lang/FBSL/Bitmap new file mode 120000 index 0000000000..3884b2024d --- /dev/null +++ b/Lang/FBSL/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-B-zier-curves-Cubic b/Lang/FBSL/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..0d03bd2d99 --- /dev/null +++ b/Lang/FBSL/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-B-zier-curves-Quadratic b/Lang/FBSL/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..9939386cb2 --- /dev/null +++ b/Lang/FBSL/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-Bresenhams-line-algorithm b/Lang/FBSL/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..9c7487dc5a --- /dev/null +++ b/Lang/FBSL/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-Flood-fill b/Lang/FBSL/Bitmap-Flood-fill new file mode 120000 index 0000000000..20779e8dbf --- /dev/null +++ b/Lang/FBSL/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-Histogram b/Lang/FBSL/Bitmap-Histogram new file mode 120000 index 0000000000..895a21589a --- /dev/null +++ b/Lang/FBSL/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-Midpoint-circle-algorithm b/Lang/FBSL/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..df9e3289ee --- /dev/null +++ b/Lang/FBSL/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-Read-a-PPM-file b/Lang/FBSL/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..50e5feeefd --- /dev/null +++ b/Lang/FBSL/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Bitmap-Write-a-PPM-file b/Lang/FBSL/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..94be2d7feb --- /dev/null +++ b/Lang/FBSL/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Character-matching b/Lang/FBSL/Character-matching new file mode 120000 index 0000000000..96ef0d1b65 --- /dev/null +++ b/Lang/FBSL/Character-matching @@ -0,0 +1 @@ +../../Task/Character-matching/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Day-of-the-week b/Lang/FBSL/Day-of-the-week new file mode 120000 index 0000000000..c5c203fc81 --- /dev/null +++ b/Lang/FBSL/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/FBSL \ No newline at end of file diff --git a/Lang/FBSL/File-size b/Lang/FBSL/File-size new file mode 120000 index 0000000000..27584bc165 --- /dev/null +++ b/Lang/FBSL/File-size @@ -0,0 +1 @@ +../../Task/File-size/FBSL \ No newline at end of file diff --git a/Lang/FBSL/FizzBuzz b/Lang/FBSL/FizzBuzz new file mode 120000 index 0000000000..ddbfa9b879 --- /dev/null +++ b/Lang/FBSL/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Grayscale-image b/Lang/FBSL/Grayscale-image new file mode 120000 index 0000000000..d379baf25a --- /dev/null +++ b/Lang/FBSL/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Harshad-or-Niven-series b/Lang/FBSL/Harshad-or-Niven-series new file mode 120000 index 0000000000..e177b8d6f0 --- /dev/null +++ b/Lang/FBSL/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Haversine-formula b/Lang/FBSL/Haversine-formula new file mode 120000 index 0000000000..9a5b4a13cd --- /dev/null +++ b/Lang/FBSL/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Letter-frequency b/Lang/FBSL/Letter-frequency new file mode 120000 index 0000000000..6eaaa4ee5b --- /dev/null +++ b/Lang/FBSL/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Loops-For b/Lang/FBSL/Loops-For new file mode 120000 index 0000000000..dd8d8414c2 --- /dev/null +++ b/Lang/FBSL/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Loops-For-with-a-specified-step b/Lang/FBSL/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..010f116dbf --- /dev/null +++ b/Lang/FBSL/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Loops-N-plus-one-half b/Lang/FBSL/Loops-N-plus-one-half new file mode 120000 index 0000000000..e4bb882c5e --- /dev/null +++ b/Lang/FBSL/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Ordered-words b/Lang/FBSL/Ordered-words new file mode 120000 index 0000000000..a323c3ef93 --- /dev/null +++ b/Lang/FBSL/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Palindrome-detection b/Lang/FBSL/Palindrome-detection new file mode 120000 index 0000000000..611bb0c658 --- /dev/null +++ b/Lang/FBSL/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Primality-by-trial-division b/Lang/FBSL/Primality-by-trial-division new file mode 120000 index 0000000000..804e68e4cc --- /dev/null +++ b/Lang/FBSL/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/FBSL \ No newline at end of file diff --git a/Lang/FBSL/Rot-13 b/Lang/FBSL/Rot-13 new file mode 120000 index 0000000000..a0c8cccd3d --- /dev/null +++ b/Lang/FBSL/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/FBSL \ No newline at end of file diff --git a/Lang/Factor/24-game b/Lang/Factor/24-game new file mode 120000 index 0000000000..17bbc5a881 --- /dev/null +++ b/Lang/Factor/24-game @@ -0,0 +1 @@ +../../Task/24-game/Factor \ No newline at end of file diff --git a/Lang/Factor/Dinesmans-multiple-dwelling-problem b/Lang/Factor/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..6331199eaa --- /dev/null +++ b/Lang/Factor/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Factor \ No newline at end of file diff --git a/Lang/Factor/Fast-Fourier-transform b/Lang/Factor/Fast-Fourier-transform new file mode 120000 index 0000000000..6c642894ec --- /dev/null +++ b/Lang/Factor/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Factor \ No newline at end of file diff --git a/Lang/Factor/Guess-the-number-With-feedback b/Lang/Factor/Guess-the-number-With-feedback new file mode 120000 index 0000000000..11ff660bed --- /dev/null +++ b/Lang/Factor/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Factor \ No newline at end of file diff --git a/Lang/Factor/Josephus-problem b/Lang/Factor/Josephus-problem new file mode 120000 index 0000000000..74d7dd5961 --- /dev/null +++ b/Lang/Factor/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Factor \ No newline at end of file diff --git a/Lang/Factor/Numerical-integration b/Lang/Factor/Numerical-integration new file mode 120000 index 0000000000..e7f8b00eea --- /dev/null +++ b/Lang/Factor/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Factor \ No newline at end of file diff --git a/Lang/Factor/Show-the-epoch b/Lang/Factor/Show-the-epoch new file mode 120000 index 0000000000..3853f8e795 --- /dev/null +++ b/Lang/Factor/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Factor \ No newline at end of file diff --git a/Lang/Factor/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Factor/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..b88713f36c --- /dev/null +++ b/Lang/Factor/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Factor \ No newline at end of file diff --git a/Lang/Fish/Quine b/Lang/Fish/Quine new file mode 120000 index 0000000000..0d421b0905 --- /dev/null +++ b/Lang/Fish/Quine @@ -0,0 +1 @@ +../../Task/Quine/Fish \ No newline at end of file diff --git a/Lang/Fish/Sorting-algorithms-Bubble-sort b/Lang/Fish/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..1a2dcfcae2 --- /dev/null +++ b/Lang/Fish/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Fish \ No newline at end of file diff --git a/Lang/Forth/Arithmetic-geometric-mean b/Lang/Forth/Arithmetic-geometric-mean new file mode 120000 index 0000000000..511ba7bcd8 --- /dev/null +++ b/Lang/Forth/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Forth \ No newline at end of file diff --git a/Lang/Forth/Entropy b/Lang/Forth/Entropy new file mode 120000 index 0000000000..90b4cca71a --- /dev/null +++ b/Lang/Forth/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Forth \ No newline at end of file diff --git a/Lang/Forth/Euler-method b/Lang/Forth/Euler-method new file mode 120000 index 0000000000..66ead5d796 --- /dev/null +++ b/Lang/Forth/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Forth \ No newline at end of file diff --git a/Lang/Forth/Floyds-triangle b/Lang/Forth/Floyds-triangle new file mode 120000 index 0000000000..865d4a1500 --- /dev/null +++ b/Lang/Forth/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Forth \ No newline at end of file diff --git a/Lang/Forth/Start-from-a-main-routine b/Lang/Forth/Start-from-a-main-routine new file mode 120000 index 0000000000..f337e51cef --- /dev/null +++ b/Lang/Forth/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Forth \ No newline at end of file diff --git a/Lang/Forth/String-comparison b/Lang/Forth/String-comparison new file mode 120000 index 0000000000..ebb4a22ce5 --- /dev/null +++ b/Lang/Forth/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Forth \ No newline at end of file diff --git a/Lang/Forth/Sum-digits-of-an-integer b/Lang/Forth/Sum-digits-of-an-integer new file mode 120000 index 0000000000..d314dd8dc8 --- /dev/null +++ b/Lang/Forth/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Forth \ No newline at end of file diff --git a/Lang/Fortran/Binary-digits b/Lang/Fortran/Binary-digits new file mode 120000 index 0000000000..8dcc8b0a70 --- /dev/null +++ b/Lang/Fortran/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Entropy b/Lang/Fortran/Entropy new file mode 120000 index 0000000000..308f038a81 --- /dev/null +++ b/Lang/Fortran/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Floyds-triangle b/Lang/Fortran/Floyds-triangle new file mode 120000 index 0000000000..de98601e40 --- /dev/null +++ b/Lang/Fortran/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Harshad-or-Niven-series b/Lang/Fortran/Harshad-or-Niven-series new file mode 120000 index 0000000000..403f33fc16 --- /dev/null +++ b/Lang/Fortran/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Fortran \ No newline at end of file diff --git a/Lang/Fortran/I-before-E-except-after-C b/Lang/Fortran/I-before-E-except-after-C new file mode 120000 index 0000000000..8698265b91 --- /dev/null +++ b/Lang/Fortran/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Josephus-problem b/Lang/Fortran/Josephus-problem new file mode 120000 index 0000000000..b7a65511b9 --- /dev/null +++ b/Lang/Fortran/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/LU-decomposition b/Lang/Fortran/LU-decomposition new file mode 120000 index 0000000000..1974a1a60a --- /dev/null +++ b/Lang/Fortran/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Last-Friday-of-each-month b/Lang/Fortran/Last-Friday-of-each-month new file mode 120000 index 0000000000..5afe75e765 --- /dev/null +++ b/Lang/Fortran/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Letter-frequency b/Lang/Fortran/Letter-frequency new file mode 120000 index 0000000000..fa69af6652 --- /dev/null +++ b/Lang/Fortran/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Matrix-arithmetic b/Lang/Fortran/Matrix-arithmetic new file mode 120000 index 0000000000..c5c133a1f6 --- /dev/null +++ b/Lang/Fortran/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Return-multiple-values b/Lang/Fortran/Return-multiple-values new file mode 120000 index 0000000000..9b047859a6 --- /dev/null +++ b/Lang/Fortran/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Semordnilap b/Lang/Fortran/Semordnilap new file mode 120000 index 0000000000..87da4d0e53 --- /dev/null +++ b/Lang/Fortran/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ternary-logic b/Lang/Fortran/Ternary-logic new file mode 120000 index 0000000000..0da5e32d39 --- /dev/null +++ b/Lang/Fortran/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Fortran \ No newline at end of file diff --git a/Lang/Go/Resistor-mesh b/Lang/Go/Resistor-mesh new file mode 120000 index 0000000000..18addbde45 --- /dev/null +++ b/Lang/Go/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Go \ No newline at end of file diff --git a/Lang/Haskell/Josephus-problem b/Lang/Haskell/Josephus-problem new file mode 120000 index 0000000000..83b26d7f68 --- /dev/null +++ b/Lang/Haskell/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Haskell \ No newline at end of file diff --git a/Lang/Haskell/MD5-Implementation b/Lang/Haskell/MD5-Implementation new file mode 120000 index 0000000000..16b4341b82 --- /dev/null +++ b/Lang/Haskell/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Haskell \ No newline at end of file diff --git a/Lang/Icon/I-before-E-except-after-C b/Lang/Icon/I-before-E-except-after-C new file mode 120000 index 0000000000..4306fd7792 --- /dev/null +++ b/Lang/Icon/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Icon \ No newline at end of file diff --git a/Lang/Io/Hailstone-sequence b/Lang/Io/Hailstone-sequence new file mode 120000 index 0000000000..2539d6a071 --- /dev/null +++ b/Lang/Io/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Io \ No newline at end of file diff --git a/Lang/Io/Hello-world-Web-server b/Lang/Io/Hello-world-Web-server new file mode 120000 index 0000000000..6b39d45e41 --- /dev/null +++ b/Lang/Io/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Io \ No newline at end of file diff --git a/Lang/J/00DESCRIPTION b/Lang/J/00DESCRIPTION index 41d0c83465..207d78a850 100644 --- a/Lang/J/00DESCRIPTION +++ b/Lang/J/00DESCRIPTION @@ -31,9 +31,9 @@ The J programming language was designed and developed by [http://en.wikipedia.or == Reading J == -J is meant to be read with the aid of a computer. J sentences are single lines and trying variations and simplifications of an expression is common practice. The first step in understanding any J sentence is to understand the data you started with and the data which resulted. When learning how a J sentence works, you can also try simpler sentences which the same data or perhaps related data. +J is meant to be read with the aid of a computer. J sentences are single lines and trying variations and simplifications of an expression is common practice. The first step in understanding any J sentence is to understand the data you started with and the data which resulted. When learning how a J sentence works, you can also try simpler sentences with the same data or perhaps related data. -Unless you attend an institution which has made a J interpreter available to you through your web browser, if you want to see how J works you should probably [http://www.jsoftware.com/stable.htm install] a copy of J -- or you can try one of the "try me" links, below. If you want to understand how to experiment with alternative expressions you should probably study some of its [[j:Guides/Getting%20Started#Documentation|documentation]]. +Unless you attend an institution which has made a J interpreter available to you through your web browser (or preinstalled on your machine), if you want to see how J works you should probably [http://www.jsoftware.com/stable.htm install] a copy of J -- or you can try one of the "try me" links, below. If you want to understand how to experiment with alternative expressions you should probably also be studying some of its [[j:Guides/Getting%20Started#Documentation|documentation]]. For example, the phrase (+/ % #) finds the average of a list of numbers. @@ -59,6 +59,14 @@ To understand how this works, you might try working with simpler sentences and t By themselves, these experiments mean nothing, but if you know that +/ was finding the sum of a list and # was finding the length of a list and that % was dividing the two quantities (and looks almost like one of the classical division symbols) then these experiments might help confirm that you have understood things properly. +== Some Perspective == + +If you wish to use J you will also have to learn a few grammatical rules (J's parser has [http://www.jsoftware.com/help/dictionary/dicte.htm 9 reduction rules] and "shift" and "accept" - the above examples use four of those rules). J verbs have two definitions - a single argument "monadic" definition and a two argument "dyadic" definition. These terms are borrowed from music and are distinct from Haskell's use of the word "monad". The dyadic definitions are in some sense related to LISP's "cons cell" but are implemented as grammar rather than data structure, and are a pervasive part of the language. + +Another pervasive feature of the language is [[wp:Rank_(J_programming_language)|rank]]. + +The language represents capabilities of hardware. For example, if language did not have an internal stack, a word's definition could not be used during the execution of that word. All current J implementations support recursion, but in some sense this is a convenience, and it's reasonable to imagine J implementations which do not (perhaps in a "compile to silicon" implementation). + == J on RosettaCode == Discussion of the goals of the J community on RC and general guidelines for presenting J solutions takes place at [[J/HouseStyle|House Style]]. diff --git a/Lang/J/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/J/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..186ec7d029 --- /dev/null +++ b/Lang/J/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J \ No newline at end of file diff --git a/Lang/J/Function-prototype b/Lang/J/Function-prototype new file mode 120000 index 0000000000..0b80969605 --- /dev/null +++ b/Lang/J/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/J \ No newline at end of file diff --git a/Lang/J/Harshad-or-Niven-series b/Lang/J/Harshad-or-Niven-series new file mode 120000 index 0000000000..6c4b1d7c25 --- /dev/null +++ b/Lang/J/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/J \ No newline at end of file diff --git a/Lang/J/Josephus-problem b/Lang/J/Josephus-problem new file mode 120000 index 0000000000..a97b98ead6 --- /dev/null +++ b/Lang/J/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/J \ No newline at end of file diff --git a/Lang/J/Mad-Libs b/Lang/J/Mad-Libs new file mode 120000 index 0000000000..b922617a05 --- /dev/null +++ b/Lang/J/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/J \ No newline at end of file diff --git a/Lang/Java/Averages-Mean-angle b/Lang/Java/Averages-Mean-angle new file mode 120000 index 0000000000..d835e86c4d --- /dev/null +++ b/Lang/Java/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Java \ No newline at end of file diff --git a/Lang/Java/Entropy b/Lang/Java/Entropy new file mode 120000 index 0000000000..ad7a0fb32b --- /dev/null +++ b/Lang/Java/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Java \ No newline at end of file diff --git a/Lang/Java/Globally-replace-text-in-several-files b/Lang/Java/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..09415a10e6 --- /dev/null +++ b/Lang/Java/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Java \ No newline at end of file diff --git a/Lang/Java/I-before-E-except-after-C b/Lang/Java/I-before-E-except-after-C new file mode 120000 index 0000000000..f8bee84df4 --- /dev/null +++ b/Lang/Java/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Java \ No newline at end of file diff --git a/Lang/Java/Include-a-file b/Lang/Java/Include-a-file new file mode 120000 index 0000000000..5bddf68614 --- /dev/null +++ b/Lang/Java/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Java \ No newline at end of file diff --git a/Lang/Java/Mad-Libs b/Lang/Java/Mad-Libs new file mode 120000 index 0000000000..b02d42d43a --- /dev/null +++ b/Lang/Java/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Java \ No newline at end of file diff --git a/Lang/Java/Remove-lines-from-a-file b/Lang/Java/Remove-lines-from-a-file new file mode 120000 index 0000000000..7868597523 --- /dev/null +++ b/Lang/Java/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Java \ No newline at end of file diff --git a/Lang/Java/Seven-sided-dice-from-five-sided-dice b/Lang/Java/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..4978b6b0ab --- /dev/null +++ b/Lang/Java/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Bead-sort b/Lang/Java/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..c3e13d4d5b --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Permutation-sort b/Lang/Java/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..1108e6b081 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Radix-sort b/Lang/Java/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..cd6c32b2c5 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Java \ No newline at end of file diff --git a/Lang/JavaScript/Semordnilap b/Lang/JavaScript/Semordnilap new file mode 120000 index 0000000000..813920f716 --- /dev/null +++ b/Lang/JavaScript/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/JavaScript \ No newline at end of file diff --git a/Lang/Julia/00DESCRIPTION b/Lang/Julia/00DESCRIPTION index 06f7875a8f..359ef23da9 100644 --- a/Lang/Julia/00DESCRIPTION +++ b/Lang/Julia/00DESCRIPTION @@ -1,4 +1,7 @@ {{stub}} {{language | Julia | site=http://julialang.org/ }} -Julia is a high-level, high-performance dynamic programming language for technical computing, with syntax silimar to [[MATLAB]]'s. It provides a sophisticated compiler, distributed parallel execution, numerical accuracy, and an extensive mathematical function library. \ No newline at end of file +Julia is a high-level, high-performance dynamic programming language for technical computing, with syntax silimar to [[MATLAB]]'s. +It provides a sophisticated compiler, distributed parallel execution, numerical accuracy, and an extensive mathematical function library. +It is a functional language that uses multiple dispatch as it's primary paradigm. +It has first-class types and homoiconic macros. \ No newline at end of file diff --git a/Lang/Julia/24-game b/Lang/Julia/24-game new file mode 120000 index 0000000000..19241d73b3 --- /dev/null +++ b/Lang/Julia/24-game @@ -0,0 +1 @@ +../../Task/24-game/Julia \ No newline at end of file diff --git a/Lang/Julia/24-game-Solve b/Lang/Julia/24-game-Solve new file mode 120000 index 0000000000..adc0993d28 --- /dev/null +++ b/Lang/Julia/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Julia \ No newline at end of file diff --git a/Lang/Julia/GUI-component-interaction b/Lang/Julia/GUI-component-interaction new file mode 120000 index 0000000000..87c5ad5ef7 --- /dev/null +++ b/Lang/Julia/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Julia \ No newline at end of file diff --git a/Lang/Julia/GUI-enabling-disabling-of-controls b/Lang/Julia/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..9b8e8d6499 --- /dev/null +++ b/Lang/Julia/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Julia \ No newline at end of file diff --git a/Lang/Julia/Greatest-common-divisor b/Lang/Julia/Greatest-common-divisor new file mode 120000 index 0000000000..d949d0c7d9 --- /dev/null +++ b/Lang/Julia/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Julia \ No newline at end of file diff --git a/Lang/Julia/Higher-order-functions b/Lang/Julia/Higher-order-functions new file mode 120000 index 0000000000..11e0bf2d24 --- /dev/null +++ b/Lang/Julia/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Julia \ No newline at end of file diff --git a/Lang/Julia/Identity-matrix b/Lang/Julia/Identity-matrix new file mode 120000 index 0000000000..9b7bc296a2 --- /dev/null +++ b/Lang/Julia/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Julia \ No newline at end of file diff --git a/Lang/Julia/Infinity b/Lang/Julia/Infinity new file mode 120000 index 0000000000..48f77b8ea8 --- /dev/null +++ b/Lang/Julia/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Julia \ No newline at end of file diff --git a/Lang/Julia/Quine b/Lang/Julia/Quine new file mode 120000 index 0000000000..02455dc44c --- /dev/null +++ b/Lang/Julia/Quine @@ -0,0 +1 @@ +../../Task/Quine/Julia \ No newline at end of file diff --git a/Lang/Julia/Sleep b/Lang/Julia/Sleep new file mode 120000 index 0000000000..b59b577f79 --- /dev/null +++ b/Lang/Julia/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Julia \ No newline at end of file diff --git a/Lang/Julia/Sockets b/Lang/Julia/Sockets new file mode 120000 index 0000000000..4f802f593c --- /dev/null +++ b/Lang/Julia/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Julia \ No newline at end of file diff --git a/Lang/LOLCODE/Hello-world-Text b/Lang/LOLCODE/Hello-world-Text new file mode 120000 index 0000000000..c0b8843401 --- /dev/null +++ b/Lang/LOLCODE/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/LOLCODE \ No newline at end of file diff --git a/Lang/Lang5/Mandelbrot-set b/Lang/Lang5/Mandelbrot-set new file mode 120000 index 0000000000..3979abc833 --- /dev/null +++ b/Lang/Lang5/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Lang5 \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Miller-Rabin-primality-test b/Lang/Liberty-BASIC/Miller-Rabin-primality-test new file mode 120000 index 0000000000..01eccc1a73 --- /dev/null +++ b/Lang/Liberty-BASIC/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Logo/Arithmetic-geometric-mean b/Lang/Logo/Arithmetic-geometric-mean new file mode 120000 index 0000000000..5441d08f83 --- /dev/null +++ b/Lang/Logo/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Logo \ No newline at end of file diff --git a/Lang/Logo/Equilibrium-index b/Lang/Logo/Equilibrium-index new file mode 120000 index 0000000000..3c76c0dec7 --- /dev/null +++ b/Lang/Logo/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Logo \ No newline at end of file diff --git a/Lang/Logo/Substring-Top-and-tail b/Lang/Logo/Substring-Top-and-tail new file mode 120000 index 0000000000..d6a8150554 --- /dev/null +++ b/Lang/Logo/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Logo \ No newline at end of file diff --git a/Lang/Lua/00DESCRIPTION b/Lang/Lua/00DESCRIPTION index 9dac59a30b..8b27c1bfda 100644 --- a/Lang/Lua/00DESCRIPTION +++ b/Lang/Lua/00DESCRIPTION @@ -1,5 +1,5 @@ {{language|Lua -|exec=JIT +|exec=interpreted |strength=strong |safety=safe |express=implicit diff --git a/Lang/Lua/Call-a-function b/Lang/Lua/Call-a-function new file mode 120000 index 0000000000..35d747fc66 --- /dev/null +++ b/Lang/Lua/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Call-an-object-method b/Lang/Lua/Call-an-object-method new file mode 120000 index 0000000000..9870882892 --- /dev/null +++ b/Lang/Lua/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Lua \ No newline at end of file diff --git a/Lang/Lua/First-class-environments b/Lang/Lua/First-class-environments new file mode 120000 index 0000000000..ba03e3a409 --- /dev/null +++ b/Lang/Lua/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Lua \ No newline at end of file diff --git a/Lang/Lua/Jump-anywhere b/Lang/Lua/Jump-anywhere new file mode 120000 index 0000000000..78c16fb3cc --- /dev/null +++ b/Lang/Lua/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Lua \ No newline at end of file diff --git a/Lang/Lua/Send-an-unknown-method-call b/Lang/Lua/Send-an-unknown-method-call new file mode 120000 index 0000000000..e50da97eb4 --- /dev/null +++ b/Lang/Lua/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Lua \ No newline at end of file diff --git a/Lang/Lua/String-comparison b/Lang/Lua/String-comparison new file mode 120000 index 0000000000..73fdb010db --- /dev/null +++ b/Lang/Lua/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Lua \ No newline at end of file diff --git a/Lang/Mathematica/Harshad-or-Niven-series b/Lang/Mathematica/Harshad-or-Niven-series new file mode 120000 index 0000000000..4adeb4aba7 --- /dev/null +++ b/Lang/Mathematica/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Mathematica \ No newline at end of file diff --git a/Lang/Mercury/Read-entire-file b/Lang/Mercury/Read-entire-file new file mode 120000 index 0000000000..8db58b31cb --- /dev/null +++ b/Lang/Mercury/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Mercury \ No newline at end of file diff --git a/Lang/Modula-2/Hello-world-Web-server b/Lang/Modula-2/Hello-world-Web-server new file mode 120000 index 0000000000..55ca528bf1 --- /dev/null +++ b/Lang/Modula-2/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Modula-2 \ No newline at end of file diff --git a/Lang/NetRexx/Averages-Mean-angle b/Lang/NetRexx/Averages-Mean-angle new file mode 120000 index 0000000000..f7e42007b7 --- /dev/null +++ b/Lang/NetRexx/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Entropy b/Lang/NetRexx/Entropy new file mode 120000 index 0000000000..eb375685d8 --- /dev/null +++ b/Lang/NetRexx/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Executable-library b/Lang/NetRexx/Executable-library new file mode 120000 index 0000000000..ad22b47ba3 --- /dev/null +++ b/Lang/NetRexx/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Extreme-floating-point-values b/Lang/NetRexx/Extreme-floating-point-values new file mode 120000 index 0000000000..5e7b38a87e --- /dev/null +++ b/Lang/NetRexx/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Factors-of-an-integer b/Lang/NetRexx/Factors-of-an-integer new file mode 120000 index 0000000000..498fb672e7 --- /dev/null +++ b/Lang/NetRexx/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/File-modification-time b/Lang/NetRexx/File-modification-time new file mode 120000 index 0000000000..46aa968b0c --- /dev/null +++ b/Lang/NetRexx/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Letter-frequency b/Lang/NetRexx/Letter-frequency new file mode 120000 index 0000000000..a7ade91e19 --- /dev/null +++ b/Lang/NetRexx/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Permutations b/Lang/NetRexx/Permutations new file mode 120000 index 0000000000..9c7777605a --- /dev/null +++ b/Lang/NetRexx/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Pancake-sort b/Lang/NetRexx/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..ed2c29898f --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Permutation-sort b/Lang/NetRexx/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..4a731beb74 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Radix-sort b/Lang/NetRexx/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..d24b9b7757 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sum-of-squares b/Lang/NetRexx/Sum-of-squares new file mode 120000 index 0000000000..9d5124c7b4 --- /dev/null +++ b/Lang/NetRexx/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/NetRexx \ No newline at end of file diff --git a/Lang/Objeck/00DESCRIPTION b/Lang/Objeck/00DESCRIPTION index 109c10a8b7..1669baa9f6 100644 --- a/Lang/Objeck/00DESCRIPTION +++ b/Lang/Objeck/00DESCRIPTION @@ -9,6 +9,8 @@ |LCT=yes}} {{language programming paradigm|Object-oriented}}{{language programming paradigm|functional}} -The '''Objeck Programming Language''' is an [[object-oriented]] computing language with [[functional programming|functional]] features. The language has ties with [[C sharp|C#]], [[Scheme]] and indirectly [[Ruby]]. In this language all data types, except for higher-order functions, are treated as objects. The language contains all of the basic features of a general-purpose (Turing complete) programming language with an emphasis placed on OOP simplicity. The programming environment consists of an optimizing compiler, virtual machine with associated [[Garbage collection|garbage collector]] and [[JIT]] compiler along with a command-line debugger. The compiler emits binary [[bytecode]] that is executed by the runtime system. The runtime system has the ability to translate the bytecode into AMD64 or IA-32 machine code on the fly. +The '''Objeck Programming Language''' is an [[object-oriented]] computing language with [[functional programming|functional]] features. The language has ties with [[C sharp|C#]], [[Scheme]] and indirectly [[Ruby]]. In this language all data types, except for higher-order functions, are treated as objects. The language contains all of the basic features of a general-purpose (Turing complete) programming language with an emphasis placed on OOP simplicity. -For more information check out the [http://objeck-lang.sourceforge.net/guide Objeck Programmer's Guide] ([https://sourceforge.net/p/objeck-lang/code/3289/tree/main/docs/guide/objeck_lang.pdf?format=raw pdf]) or this YouTube [http://www.youtube.com/watch?v=Mk2Kfb-WESU video]. The language can be [http://sourceforge.net/projects/objeck-lang/files/ obtained] from the main project homepage. Also, check out the IRC channel #objeck on freenode.net. \ No newline at end of file +The programming environment consists of an optimizing compiler, virtual machine with associated [[Garbage collection|garbage collector]] and [[JIT]] compiler along with a command-line debugger. The compiler emits binary [[bytecode]] that is executed by the runtime system. The runtime system has the ability to translate the bytecode into AMD64 or IA-32 machine code on the fly. + +For more information check out the [http://objeck-lang.sourceforge.net/guide Objeck Programmer's Guide] ([http://sourceforge.net/p/objeck-lang/code/HEAD/tree/main/docs/guide/objeck_lang.pdf?format=raw pdf]) or this YouTube [http://www.youtube.com/watch?v=Mk2Kfb-WESU video]. The language can be [http://sourceforge.net/projects/objeck-lang/files/ obtained] from the main project homepage. Also, check out the IRC channel #objeck on freenode.net. \ No newline at end of file diff --git a/Lang/Objeck/Arithmetic-geometric-mean b/Lang/Objeck/Arithmetic-geometric-mean new file mode 120000 index 0000000000..5d93b9a5d8 --- /dev/null +++ b/Lang/Objeck/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Averages-Mode b/Lang/Objeck/Averages-Mode new file mode 120000 index 0000000000..58b64930dc --- /dev/null +++ b/Lang/Objeck/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Averages-Simple-moving-average b/Lang/Objeck/Averages-Simple-moving-average new file mode 120000 index 0000000000..60f88fdf2b --- /dev/null +++ b/Lang/Objeck/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Caesar-cipher b/Lang/Objeck/Caesar-cipher new file mode 120000 index 0000000000..69c8202bbe --- /dev/null +++ b/Lang/Objeck/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Count-in-factors b/Lang/Objeck/Count-in-factors new file mode 120000 index 0000000000..2686949d31 --- /dev/null +++ b/Lang/Objeck/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Harshad-or-Niven-series b/Lang/Objeck/Harshad-or-Niven-series new file mode 120000 index 0000000000..97d553ce8b --- /dev/null +++ b/Lang/Objeck/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Objeck \ No newline at end of file diff --git a/Lang/Objeck/I-before-E-except-after-C b/Lang/Objeck/I-before-E-except-after-C new file mode 120000 index 0000000000..8395b957bc --- /dev/null +++ b/Lang/Objeck/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Identity-matrix b/Lang/Objeck/Identity-matrix new file mode 120000 index 0000000000..200ec581df --- /dev/null +++ b/Lang/Objeck/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Josephus-problem b/Lang/Objeck/Josephus-problem new file mode 120000 index 0000000000..e00fb85196 --- /dev/null +++ b/Lang/Objeck/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Man-or-boy-test b/Lang/Objeck/Man-or-boy-test new file mode 120000 index 0000000000..ac5072f8ac --- /dev/null +++ b/Lang/Objeck/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Pig-the-dice-game b/Lang/Objeck/Pig-the-dice-game new file mode 120000 index 0000000000..ded5d421c4 --- /dev/null +++ b/Lang/Objeck/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Range-extraction b/Lang/Objeck/Range-extraction new file mode 120000 index 0000000000..47556fccbc --- /dev/null +++ b/Lang/Objeck/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Objeck \ No newline at end of file diff --git a/Lang/Objective-C/Haversine-formula b/Lang/Objective-C/Haversine-formula new file mode 120000 index 0000000000..4090351b17 --- /dev/null +++ b/Lang/Objective-C/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Objective-C \ No newline at end of file diff --git a/Lang/Octave/Find-the-missing-permutation b/Lang/Octave/Find-the-missing-permutation new file mode 120000 index 0000000000..4c9aa7ad45 --- /dev/null +++ b/Lang/Octave/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Octave \ No newline at end of file diff --git a/Lang/Order/Higher-order-functions b/Lang/Order/Higher-order-functions new file mode 120000 index 0000000000..89f0e0d376 --- /dev/null +++ b/Lang/Order/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Order \ No newline at end of file diff --git a/Lang/PARI-GP/Entropy b/Lang/PARI-GP/Entropy new file mode 120000 index 0000000000..fe636fc38f --- /dev/null +++ b/Lang/PARI-GP/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Harshad-or-Niven-series b/Lang/PARI-GP/Harshad-or-Niven-series new file mode 120000 index 0000000000..ea4889a071 --- /dev/null +++ b/Lang/PARI-GP/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Largest-int-from-concatenated-ints b/Lang/PARI-GP/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..82a40a194a --- /dev/null +++ b/Lang/PARI-GP/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Middle-three-digits b/Lang/PARI-GP/Middle-three-digits new file mode 120000 index 0000000000..8680ce9e13 --- /dev/null +++ b/Lang/PARI-GP/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/Character-matching b/Lang/PHP/Character-matching new file mode 120000 index 0000000000..8298cc63af --- /dev/null +++ b/Lang/PHP/Character-matching @@ -0,0 +1 @@ +../../Task/Character-matching/PHP \ No newline at end of file diff --git a/Lang/PL-I/Case-sensitivity-of-identifiers b/Lang/PL-I/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..c902d4f2cf --- /dev/null +++ b/Lang/PL-I/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/PL-I \ No newline at end of file diff --git a/Lang/PL-SQL/100-doors b/Lang/PL-SQL/100-doors new file mode 120000 index 0000000000..ca6bc91c09 --- /dev/null +++ b/Lang/PL-SQL/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/PL-SQL \ No newline at end of file diff --git a/Lang/Perl-6/Brownian-tree b/Lang/Perl-6/Brownian-tree new file mode 120000 index 0000000000..70d2a9c2ad --- /dev/null +++ b/Lang/Perl-6/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Colour-bars-Display b/Lang/Perl-6/Colour-bars-Display new file mode 120000 index 0000000000..4908736932 --- /dev/null +++ b/Lang/Perl-6/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Colour-pinstripe-Display b/Lang/Perl-6/Colour-pinstripe-Display new file mode 120000 index 0000000000..1b88cba8d5 --- /dev/null +++ b/Lang/Perl-6/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Create-a-file-on-magnetic-tape b/Lang/Perl-6/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..64f79e5d0b --- /dev/null +++ b/Lang/Perl-6/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Date-manipulation b/Lang/Perl-6/Date-manipulation new file mode 120000 index 0000000000..7409dba028 --- /dev/null +++ b/Lang/Perl-6/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Determine-if-only-one-instance-is-running b/Lang/Perl-6/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..3247a854e6 --- /dev/null +++ b/Lang/Perl-6/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/First-class-environments b/Lang/Perl-6/First-class-environments new file mode 120000 index 0000000000..21919c12d1 --- /dev/null +++ b/Lang/Perl-6/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Galton-box-animation b/Lang/Perl-6/Galton-box-animation new file mode 120000 index 0000000000..e93ff7cb7a --- /dev/null +++ b/Lang/Perl-6/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Keyboard-macros b/Lang/Perl-6/Keyboard-macros new file mode 120000 index 0000000000..1b18106ed3 --- /dev/null +++ b/Lang/Perl-6/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/MD4 b/Lang/Perl-6/MD4 new file mode 120000 index 0000000000..e34ece4ead --- /dev/null +++ b/Lang/Perl-6/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Matrix-arithmetic b/Lang/Perl-6/Matrix-arithmetic new file mode 120000 index 0000000000..1d371b7c95 --- /dev/null +++ b/Lang/Perl-6/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Multiplicative-order b/Lang/Perl-6/Multiplicative-order new file mode 120000 index 0000000000..072280209d --- /dev/null +++ b/Lang/Perl-6/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Permutation-test b/Lang/Perl-6/Permutation-test new file mode 120000 index 0000000000..c329f21270 --- /dev/null +++ b/Lang/Perl-6/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Pig-the-dice-game-Player b/Lang/Perl-6/Pig-the-dice-game-Player new file mode 120000 index 0000000000..a38f3680b3 --- /dev/null +++ b/Lang/Perl-6/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Pinstripe-Display b/Lang/Perl-6/Pinstripe-Display new file mode 120000 index 0000000000..406aa294f5 --- /dev/null +++ b/Lang/Perl-6/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rosetta-Code-Find-unimplemented-tasks b/Lang/Perl-6/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..fe10280bde --- /dev/null +++ b/Lang/Perl-6/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Rosetta-Code-Fix-code-tags b/Lang/Perl-6/Rosetta-Code-Fix-code-tags new file mode 120000 index 0000000000..7386f1eb5e --- /dev/null +++ b/Lang/Perl-6/Rosetta-Code-Fix-code-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Fix-code-tags/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Coloured-text b/Lang/Perl-6/Terminal-control-Coloured-text new file mode 120000 index 0000000000..bba0b8f7fe --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Cursor-movement b/Lang/Perl-6/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..b99f862f0f --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Preserve-screen b/Lang/Perl-6/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..d4e580bfc4 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/MD4 b/Lang/Perl/MD4 new file mode 120000 index 0000000000..8e29a87a10 --- /dev/null +++ b/Lang/Perl/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Perl \ No newline at end of file diff --git a/Lang/Perl/Temperature-conversion b/Lang/Perl/Temperature-conversion new file mode 120000 index 0000000000..0331f81a34 --- /dev/null +++ b/Lang/Perl/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Perl \ No newline at end of file diff --git a/Lang/PowerBASIC/Include-a-file b/Lang/PowerBASIC/Include-a-file new file mode 120000 index 0000000000..712c59ffe8 --- /dev/null +++ b/Lang/PowerBASIC/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/PowerBASIC \ No newline at end of file diff --git a/Lang/Prolog/Binary-digits b/Lang/Prolog/Binary-digits new file mode 120000 index 0000000000..835eaec348 --- /dev/null +++ b/Lang/Prolog/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Evolutionary-algorithm b/Lang/Prolog/Evolutionary-algorithm new file mode 120000 index 0000000000..b2a20f069a --- /dev/null +++ b/Lang/Prolog/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Fast-Fourier-transform b/Lang/Prolog/Fast-Fourier-transform new file mode 120000 index 0000000000..84e0272d05 --- /dev/null +++ b/Lang/Prolog/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Hello-world-Web-server b/Lang/Prolog/Hello-world-Web-server new file mode 120000 index 0000000000..73a7bb9937 --- /dev/null +++ b/Lang/Prolog/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Langtons-ant b/Lang/Prolog/Langtons-ant new file mode 120000 index 0000000000..730665471e --- /dev/null +++ b/Lang/Prolog/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Quaternion-type b/Lang/Prolog/Quaternion-type new file mode 120000 index 0000000000..458f5f70bc --- /dev/null +++ b/Lang/Prolog/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Bubble-sort b/Lang/Prolog/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..731359775e --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Cocktail-sort b/Lang/Prolog/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..29a16d5a01 --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Prolog \ No newline at end of file diff --git a/Lang/Protium/Loops-N-plus-one-half b/Lang/Protium/Loops-N-plus-one-half new file mode 120000 index 0000000000..ccf5e85e7c --- /dev/null +++ b/Lang/Protium/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Protium \ No newline at end of file diff --git a/Lang/PureBasic/Middle-three-digits b/Lang/PureBasic/Middle-three-digits new file mode 120000 index 0000000000..0bed3b1b8a --- /dev/null +++ b/Lang/PureBasic/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/PureBasic \ No newline at end of file diff --git a/Lang/R/Josephus-problem b/Lang/R/Josephus-problem new file mode 120000 index 0000000000..11e06e327a --- /dev/null +++ b/Lang/R/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/R \ No newline at end of file diff --git a/Lang/REALbasic/FizzBuzz b/Lang/REALbasic/FizzBuzz new file mode 120000 index 0000000000..49ed3cf68e --- /dev/null +++ b/Lang/REALbasic/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/Hello-world-Web-server b/Lang/REALbasic/Hello-world-Web-server new file mode 120000 index 0000000000..ef9d461637 --- /dev/null +++ b/Lang/REALbasic/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/REALbasic \ No newline at end of file diff --git a/Lang/REXX/Euler-method b/Lang/REXX/Euler-method new file mode 120000 index 0000000000..b5e28a13a3 --- /dev/null +++ b/Lang/REXX/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/REXX \ No newline at end of file diff --git a/Lang/REXX/Exceptions b/Lang/REXX/Exceptions new file mode 120000 index 0000000000..0703356021 --- /dev/null +++ b/Lang/REXX/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/REXX \ No newline at end of file diff --git a/Lang/REXX/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/REXX/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..f89c4adabe --- /dev/null +++ b/Lang/REXX/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/REXX \ No newline at end of file diff --git a/Lang/REXX/Holidays-related-to-Easter b/Lang/REXX/Holidays-related-to-Easter new file mode 120000 index 0000000000..fdf1fd7267 --- /dev/null +++ b/Lang/REXX/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/REXX \ No newline at end of file diff --git a/Lang/REXX/Matrix-arithmetic b/Lang/REXX/Matrix-arithmetic new file mode 120000 index 0000000000..1e4edc79ea --- /dev/null +++ b/Lang/REXX/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/REXX \ No newline at end of file diff --git a/Lang/REXX/Optional-parameters b/Lang/REXX/Optional-parameters new file mode 120000 index 0000000000..d73eb27b34 --- /dev/null +++ b/Lang/REXX/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/REXX \ No newline at end of file diff --git a/Lang/REXX/Order-two-numerical-lists b/Lang/REXX/Order-two-numerical-lists new file mode 120000 index 0000000000..f8da3669ba --- /dev/null +++ b/Lang/REXX/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/REXX \ No newline at end of file diff --git a/Lang/REXX/Random-number-generator--included- b/Lang/REXX/Random-number-generator--included- new file mode 120000 index 0000000000..aff0e135c5 --- /dev/null +++ b/Lang/REXX/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/REXX \ No newline at end of file diff --git a/Lang/Racket/00DESCRIPTION b/Lang/Racket/00DESCRIPTION index 611195ed12..004ff32234 100644 --- a/Lang/Racket/00DESCRIPTION +++ b/Lang/Racket/00DESCRIPTION @@ -1,5 +1,5 @@ {{language}} -'''Racket''' (at one time called 'PLT Scheme') is a member of the Lisp and Scheme family of languages. The Racket language (like Clojure, for example) draws freely from the various strands of its lineage. +'''Racket''' (renamed from "PLT Scheme" years ago) is a member of the Lisp and Scheme family of languages. Racket draws freely from the various strands of its lineage. -* [http://racket-lang.org Home page] +* [http://racket-lang.org/ Home page] * [http://en.wikipedia.org/wiki/Racket_(programming_language) Wikipedia] \ No newline at end of file diff --git a/Lang/Racket/24-game-Solve b/Lang/Racket/24-game-Solve new file mode 120000 index 0000000000..6094be00ff --- /dev/null +++ b/Lang/Racket/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Racket \ No newline at end of file diff --git a/Lang/Racket/Active-Directory-Connect b/Lang/Racket/Active-Directory-Connect new file mode 120000 index 0000000000..61dbad0ec1 --- /dev/null +++ b/Lang/Racket/Active-Directory-Connect @@ -0,0 +1 @@ +../../Task/Active-Directory-Connect/Racket \ No newline at end of file diff --git a/Lang/Racket/Anagrams-Deranged-anagrams b/Lang/Racket/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..00ca9369af --- /dev/null +++ b/Lang/Racket/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Racket \ No newline at end of file diff --git a/Lang/Racket/Arena-storage-pool b/Lang/Racket/Arena-storage-pool new file mode 120000 index 0000000000..eabd1b282e --- /dev/null +++ b/Lang/Racket/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Racket \ No newline at end of file diff --git a/Lang/Racket/Arithmetic-Rational b/Lang/Racket/Arithmetic-Rational new file mode 120000 index 0000000000..36546c6653 --- /dev/null +++ b/Lang/Racket/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Racket \ No newline at end of file diff --git a/Lang/Racket/Arithmetic-evaluation b/Lang/Racket/Arithmetic-evaluation new file mode 120000 index 0000000000..5c1894498d --- /dev/null +++ b/Lang/Racket/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Racket \ No newline at end of file diff --git a/Lang/Racket/Average-loop-length b/Lang/Racket/Average-loop-length new file mode 120000 index 0000000000..d63ad537e9 --- /dev/null +++ b/Lang/Racket/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Racket \ No newline at end of file diff --git a/Lang/Racket/Averages-Mean-time-of-day b/Lang/Racket/Averages-Mean-time-of-day new file mode 120000 index 0000000000..4c50d71269 --- /dev/null +++ b/Lang/Racket/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Racket \ No newline at end of file diff --git a/Lang/Racket/Averages-Mode b/Lang/Racket/Averages-Mode new file mode 120000 index 0000000000..f2cc65f0b5 --- /dev/null +++ b/Lang/Racket/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Racket \ No newline at end of file diff --git a/Lang/Racket/Averages-Root-mean-square b/Lang/Racket/Averages-Root-mean-square new file mode 120000 index 0000000000..d113a6773d --- /dev/null +++ b/Lang/Racket/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Racket \ No newline at end of file diff --git a/Lang/Racket/Averages-Simple-moving-average b/Lang/Racket/Averages-Simple-moving-average new file mode 120000 index 0000000000..163812ac02 --- /dev/null +++ b/Lang/Racket/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitcoin-address-validation b/Lang/Racket/Bitcoin-address-validation new file mode 120000 index 0000000000..b9d8e8dc62 --- /dev/null +++ b/Lang/Racket/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-B-zier-curves-Cubic b/Lang/Racket/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..c4b0ca1add --- /dev/null +++ b/Lang/Racket/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-B-zier-curves-Quadratic b/Lang/Racket/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..1d54d6244e --- /dev/null +++ b/Lang/Racket/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-Bresenhams-line-algorithm b/Lang/Racket/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..9bd5a447e5 --- /dev/null +++ b/Lang/Racket/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-Midpoint-circle-algorithm b/Lang/Racket/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..8fd24c5e08 --- /dev/null +++ b/Lang/Racket/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitmap-Read-a-PPM-file b/Lang/Racket/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..f31962d339 --- /dev/null +++ b/Lang/Racket/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Bulls-and-cows b/Lang/Racket/Bulls-and-cows new file mode 120000 index 0000000000..c58766d774 --- /dev/null +++ b/Lang/Racket/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Racket \ No newline at end of file diff --git a/Lang/Racket/CRC-32 b/Lang/Racket/CRC-32 new file mode 120000 index 0000000000..37b6cc4eb0 --- /dev/null +++ b/Lang/Racket/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Racket \ No newline at end of file diff --git a/Lang/Racket/Calendar b/Lang/Racket/Calendar new file mode 120000 index 0000000000..d12eb86b1c --- /dev/null +++ b/Lang/Racket/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Racket \ No newline at end of file diff --git a/Lang/Racket/Calendar---for-real-programmers b/Lang/Racket/Calendar---for-real-programmers new file mode 120000 index 0000000000..652953a553 --- /dev/null +++ b/Lang/Racket/Calendar---for-real-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-real-programmers/Racket \ No newline at end of file diff --git a/Lang/Racket/Call-a-function b/Lang/Racket/Call-a-function new file mode 120000 index 0000000000..9f6f6edc6a --- /dev/null +++ b/Lang/Racket/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Racket \ No newline at end of file diff --git a/Lang/Racket/Carmichael-3-strong-pseudoprimes b/Lang/Racket/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..e886df79e0 --- /dev/null +++ b/Lang/Racket/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Racket \ No newline at end of file diff --git a/Lang/Racket/Character-codes b/Lang/Racket/Character-codes new file mode 120000 index 0000000000..41a6554887 --- /dev/null +++ b/Lang/Racket/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Racket \ No newline at end of file diff --git a/Lang/Racket/Chat-server b/Lang/Racket/Chat-server new file mode 120000 index 0000000000..1832684f08 --- /dev/null +++ b/Lang/Racket/Chat-server @@ -0,0 +1 @@ +../../Task/Chat-server/Racket \ No newline at end of file diff --git a/Lang/Racket/Check-Machin-like-formulas b/Lang/Racket/Check-Machin-like-formulas new file mode 120000 index 0000000000..9407f952d2 --- /dev/null +++ b/Lang/Racket/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/Racket \ No newline at end of file diff --git a/Lang/Racket/Check-that-file-exists b/Lang/Racket/Check-that-file-exists new file mode 120000 index 0000000000..098e2a09b9 --- /dev/null +++ b/Lang/Racket/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Racket \ No newline at end of file diff --git a/Lang/Racket/Checkpoint-synchronization b/Lang/Racket/Checkpoint-synchronization new file mode 120000 index 0000000000..017929310b --- /dev/null +++ b/Lang/Racket/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/Racket \ No newline at end of file diff --git a/Lang/Racket/Cholesky-decomposition b/Lang/Racket/Cholesky-decomposition new file mode 120000 index 0000000000..f69ba751c3 --- /dev/null +++ b/Lang/Racket/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Racket \ No newline at end of file diff --git a/Lang/Racket/Closest-pair-problem b/Lang/Racket/Closest-pair-problem new file mode 120000 index 0000000000..5b9a925129 --- /dev/null +++ b/Lang/Racket/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Collections b/Lang/Racket/Collections new file mode 120000 index 0000000000..7c7a2570bc --- /dev/null +++ b/Lang/Racket/Collections @@ -0,0 +1 @@ +../../Task/Collections/Racket \ No newline at end of file diff --git a/Lang/Racket/Colour-bars-Display b/Lang/Racket/Colour-bars-Display new file mode 120000 index 0000000000..68ebccd9f1 --- /dev/null +++ b/Lang/Racket/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Racket \ No newline at end of file diff --git a/Lang/Racket/Colour-pinstripe-Display b/Lang/Racket/Colour-pinstripe-Display new file mode 120000 index 0000000000..0babbab3dc --- /dev/null +++ b/Lang/Racket/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Racket \ No newline at end of file diff --git a/Lang/Racket/Colour-pinstripe-Printer b/Lang/Racket/Colour-pinstripe-Printer new file mode 120000 index 0000000000..7d211c5034 --- /dev/null +++ b/Lang/Racket/Colour-pinstripe-Printer @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Printer/Racket \ No newline at end of file diff --git a/Lang/Racket/Combinations b/Lang/Racket/Combinations new file mode 120000 index 0000000000..4a41f4bf18 --- /dev/null +++ b/Lang/Racket/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Racket \ No newline at end of file diff --git a/Lang/Racket/Combinations-with-repetitions b/Lang/Racket/Combinations-with-repetitions new file mode 120000 index 0000000000..e103111b63 --- /dev/null +++ b/Lang/Racket/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Racket \ No newline at end of file diff --git a/Lang/Racket/Conditional-structures b/Lang/Racket/Conditional-structures new file mode 120000 index 0000000000..6f5bd005c6 --- /dev/null +++ b/Lang/Racket/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Racket \ No newline at end of file diff --git a/Lang/Racket/Constrained-random-points-on-a-circle b/Lang/Racket/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..a1093600cd --- /dev/null +++ b/Lang/Racket/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Racket \ No newline at end of file diff --git a/Lang/Racket/Continued-fraction b/Lang/Racket/Continued-fraction new file mode 120000 index 0000000000..e473568744 --- /dev/null +++ b/Lang/Racket/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Racket \ No newline at end of file diff --git a/Lang/Racket/Copy-a-string b/Lang/Racket/Copy-a-string new file mode 120000 index 0000000000..cbb3ca3689 --- /dev/null +++ b/Lang/Racket/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Racket \ No newline at end of file diff --git a/Lang/Racket/Count-occurrences-of-a-substring b/Lang/Racket/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..af80d049e5 --- /dev/null +++ b/Lang/Racket/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Racket \ No newline at end of file diff --git a/Lang/Racket/Count-the-coins b/Lang/Racket/Count-the-coins new file mode 120000 index 0000000000..78fc6ac07b --- /dev/null +++ b/Lang/Racket/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Racket \ No newline at end of file diff --git a/Lang/Racket/Create-a-file-on-magnetic-tape b/Lang/Racket/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..b4e9c79940 --- /dev/null +++ b/Lang/Racket/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Racket \ No newline at end of file diff --git a/Lang/Racket/Create-a-two-dimensional-array-at-runtime b/Lang/Racket/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..f9550393cf --- /dev/null +++ b/Lang/Racket/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Racket \ No newline at end of file diff --git a/Lang/Racket/Create-an-object-at-a-given-address b/Lang/Racket/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..84364e8f68 --- /dev/null +++ b/Lang/Racket/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/Racket \ No newline at end of file diff --git a/Lang/Racket/Cut-a-rectangle b/Lang/Racket/Cut-a-rectangle new file mode 120000 index 0000000000..cc13ce2205 --- /dev/null +++ b/Lang/Racket/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Racket \ No newline at end of file diff --git a/Lang/Racket/Date-manipulation b/Lang/Racket/Date-manipulation new file mode 120000 index 0000000000..37f5a8a274 --- /dev/null +++ b/Lang/Racket/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Racket \ No newline at end of file diff --git a/Lang/Racket/Day-of-the-week b/Lang/Racket/Day-of-the-week new file mode 120000 index 0000000000..02af77d42d --- /dev/null +++ b/Lang/Racket/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Racket \ No newline at end of file diff --git a/Lang/Racket/Deal-cards-for-FreeCell b/Lang/Racket/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..e97f44c166 --- /dev/null +++ b/Lang/Racket/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Racket \ No newline at end of file diff --git a/Lang/Racket/Death-Star b/Lang/Racket/Death-Star new file mode 120000 index 0000000000..e64e18c94d --- /dev/null +++ b/Lang/Racket/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/Racket \ No newline at end of file diff --git a/Lang/Racket/Deepcopy b/Lang/Racket/Deepcopy new file mode 120000 index 0000000000..57b23bd8ca --- /dev/null +++ b/Lang/Racket/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Racket \ No newline at end of file diff --git a/Lang/Racket/Delete-a-file b/Lang/Racket/Delete-a-file new file mode 120000 index 0000000000..814fe005e5 --- /dev/null +++ b/Lang/Racket/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Determine-if-only-one-instance-is-running b/Lang/Racket/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..bb321f27b7 --- /dev/null +++ b/Lang/Racket/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/Racket \ No newline at end of file diff --git a/Lang/Racket/Dinesmans-multiple-dwelling-problem b/Lang/Racket/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..a2c17d9485 --- /dev/null +++ b/Lang/Racket/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Dining-philosophers b/Lang/Racket/Dining-philosophers new file mode 120000 index 0000000000..0a8e8598a7 --- /dev/null +++ b/Lang/Racket/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Racket \ No newline at end of file diff --git a/Lang/Racket/Distributed-programming b/Lang/Racket/Distributed-programming new file mode 120000 index 0000000000..362ff1f573 --- /dev/null +++ b/Lang/Racket/Distributed-programming @@ -0,0 +1 @@ +../../Task/Distributed-programming/Racket \ No newline at end of file diff --git a/Lang/Racket/Doubly-linked-list-Definition b/Lang/Racket/Doubly-linked-list-Definition new file mode 120000 index 0000000000..5765866d13 --- /dev/null +++ b/Lang/Racket/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Racket \ No newline at end of file diff --git a/Lang/Racket/Doubly-linked-list-Element-definition b/Lang/Racket/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..351fd693b0 --- /dev/null +++ b/Lang/Racket/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Racket \ No newline at end of file diff --git a/Lang/Racket/Doubly-linked-list-Traversal b/Lang/Racket/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..a934cb21b1 --- /dev/null +++ b/Lang/Racket/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Racket \ No newline at end of file diff --git a/Lang/Racket/Draw-a-cuboid b/Lang/Racket/Draw-a-cuboid new file mode 120000 index 0000000000..915da4e670 --- /dev/null +++ b/Lang/Racket/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Racket \ No newline at end of file diff --git a/Lang/Racket/Dutch-national-flag-problem b/Lang/Racket/Dutch-national-flag-problem new file mode 120000 index 0000000000..2abd3dafdb --- /dev/null +++ b/Lang/Racket/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Dynamic-variable-names b/Lang/Racket/Dynamic-variable-names new file mode 120000 index 0000000000..a7cf1920c6 --- /dev/null +++ b/Lang/Racket/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Racket \ No newline at end of file diff --git a/Lang/Racket/Enforced-immutability b/Lang/Racket/Enforced-immutability new file mode 120000 index 0000000000..2cf14a1d75 --- /dev/null +++ b/Lang/Racket/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Racket \ No newline at end of file diff --git a/Lang/Racket/Enumerations b/Lang/Racket/Enumerations new file mode 120000 index 0000000000..b51fca2df1 --- /dev/null +++ b/Lang/Racket/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Racket \ No newline at end of file diff --git a/Lang/Racket/Equilibrium-index b/Lang/Racket/Equilibrium-index new file mode 120000 index 0000000000..76aa3082a6 --- /dev/null +++ b/Lang/Racket/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Racket \ No newline at end of file diff --git a/Lang/Racket/Ethiopian-multiplication b/Lang/Racket/Ethiopian-multiplication new file mode 120000 index 0000000000..7fc235341f --- /dev/null +++ b/Lang/Racket/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Racket \ No newline at end of file diff --git a/Lang/Racket/Euler-method b/Lang/Racket/Euler-method new file mode 120000 index 0000000000..5fb9078afa --- /dev/null +++ b/Lang/Racket/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Racket \ No newline at end of file diff --git a/Lang/Racket/Evolutionary-algorithm b/Lang/Racket/Evolutionary-algorithm new file mode 120000 index 0000000000..23681bbf03 --- /dev/null +++ b/Lang/Racket/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Racket/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..a805775697 --- /dev/null +++ b/Lang/Racket/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Racket \ No newline at end of file diff --git a/Lang/Racket/Executable-library b/Lang/Racket/Executable-library new file mode 120000 index 0000000000..fddc8b4ae4 --- /dev/null +++ b/Lang/Racket/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Racket \ No newline at end of file diff --git a/Lang/Racket/Execute-Brain---- b/Lang/Racket/Execute-Brain---- new file mode 120000 index 0000000000..8f02609d77 --- /dev/null +++ b/Lang/Racket/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Racket \ No newline at end of file diff --git a/Lang/Racket/Execute-HQ9+ b/Lang/Racket/Execute-HQ9+ new file mode 120000 index 0000000000..52e62e80cb --- /dev/null +++ b/Lang/Racket/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Racket \ No newline at end of file diff --git a/Lang/Racket/Execute-a-Markov-algorithm b/Lang/Racket/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..7afd3b276d --- /dev/null +++ b/Lang/Racket/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Execute-a-system-command b/Lang/Racket/Execute-a-system-command new file mode 120000 index 0000000000..55067eaf2c --- /dev/null +++ b/Lang/Racket/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Racket \ No newline at end of file diff --git a/Lang/Racket/Exponentiation-operator b/Lang/Racket/Exponentiation-operator new file mode 120000 index 0000000000..d55a4f48a3 --- /dev/null +++ b/Lang/Racket/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Racket \ No newline at end of file diff --git a/Lang/Racket/Extend-your-language b/Lang/Racket/Extend-your-language new file mode 120000 index 0000000000..cf1e8dc0a6 --- /dev/null +++ b/Lang/Racket/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Racket \ No newline at end of file diff --git a/Lang/Racket/Extreme-floating-point-values b/Lang/Racket/Extreme-floating-point-values new file mode 120000 index 0000000000..f99a9eda6d --- /dev/null +++ b/Lang/Racket/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Racket \ No newline at end of file diff --git a/Lang/Racket/Factors-of-a-Mersenne-number b/Lang/Racket/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..175792b363 --- /dev/null +++ b/Lang/Racket/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Racket \ No newline at end of file diff --git a/Lang/Racket/Factors-of-an-integer b/Lang/Racket/Factors-of-an-integer new file mode 120000 index 0000000000..4e38bcfa00 --- /dev/null +++ b/Lang/Racket/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Racket \ No newline at end of file diff --git a/Lang/Racket/Fast-Fourier-transform b/Lang/Racket/Fast-Fourier-transform new file mode 120000 index 0000000000..c4817df125 --- /dev/null +++ b/Lang/Racket/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Racket \ No newline at end of file diff --git a/Lang/Racket/Fibonacci-n-step-number-sequences b/Lang/Racket/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..2e2ec44263 --- /dev/null +++ b/Lang/Racket/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Racket \ No newline at end of file diff --git a/Lang/Racket/File-IO b/Lang/Racket/File-IO new file mode 120000 index 0000000000..36bf4089f3 --- /dev/null +++ b/Lang/Racket/File-IO @@ -0,0 +1 @@ +../../Task/File-IO/Racket \ No newline at end of file diff --git a/Lang/Racket/File-size b/Lang/Racket/File-size new file mode 120000 index 0000000000..94e0e6cdd7 --- /dev/null +++ b/Lang/Racket/File-size @@ -0,0 +1 @@ +../../Task/File-size/Racket \ No newline at end of file diff --git a/Lang/Racket/Filter b/Lang/Racket/Filter new file mode 120000 index 0000000000..acead43b38 --- /dev/null +++ b/Lang/Racket/Filter @@ -0,0 +1 @@ +../../Task/Filter/Racket \ No newline at end of file diff --git a/Lang/Racket/Find-common-directory-path b/Lang/Racket/Find-common-directory-path new file mode 120000 index 0000000000..25ae41183e --- /dev/null +++ b/Lang/Racket/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Racket \ No newline at end of file diff --git a/Lang/Racket/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Racket/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..a5526eb1d7 --- /dev/null +++ b/Lang/Racket/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Racket \ No newline at end of file diff --git a/Lang/Racket/Find-limit-of-recursion b/Lang/Racket/Find-limit-of-recursion new file mode 120000 index 0000000000..f2c1b32efe --- /dev/null +++ b/Lang/Racket/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Racket \ No newline at end of file diff --git a/Lang/Racket/Find-the-missing-permutation b/Lang/Racket/Find-the-missing-permutation new file mode 120000 index 0000000000..5638767036 --- /dev/null +++ b/Lang/Racket/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Racket \ No newline at end of file diff --git a/Lang/Racket/First-class-environments b/Lang/Racket/First-class-environments new file mode 120000 index 0000000000..7b91c4846a --- /dev/null +++ b/Lang/Racket/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Racket \ No newline at end of file diff --git a/Lang/Racket/First-class-functions-Use-numbers-analogously b/Lang/Racket/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..3a8ff87a06 --- /dev/null +++ b/Lang/Racket/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Racket \ No newline at end of file diff --git a/Lang/Racket/Five-weekends b/Lang/Racket/Five-weekends new file mode 120000 index 0000000000..89917c2483 --- /dev/null +++ b/Lang/Racket/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Racket \ No newline at end of file diff --git a/Lang/Racket/Flow-control-structures b/Lang/Racket/Flow-control-structures new file mode 120000 index 0000000000..be32382382 --- /dev/null +++ b/Lang/Racket/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Racket \ No newline at end of file diff --git a/Lang/Racket/Fork b/Lang/Racket/Fork new file mode 120000 index 0000000000..96e53114dc --- /dev/null +++ b/Lang/Racket/Fork @@ -0,0 +1 @@ +../../Task/Fork/Racket \ No newline at end of file diff --git a/Lang/Racket/Formal-power-series b/Lang/Racket/Formal-power-series new file mode 120000 index 0000000000..0cabf016a4 --- /dev/null +++ b/Lang/Racket/Formal-power-series @@ -0,0 +1 @@ +../../Task/Formal-power-series/Racket \ No newline at end of file diff --git a/Lang/Racket/Formatted-numeric-output b/Lang/Racket/Formatted-numeric-output new file mode 120000 index 0000000000..a0592294c0 --- /dev/null +++ b/Lang/Racket/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Racket \ No newline at end of file diff --git a/Lang/Racket/Forward-difference b/Lang/Racket/Forward-difference new file mode 120000 index 0000000000..0a4fb7bab7 --- /dev/null +++ b/Lang/Racket/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Racket \ No newline at end of file diff --git a/Lang/Racket/Four-bit-adder b/Lang/Racket/Four-bit-adder new file mode 120000 index 0000000000..0b9a09bf61 --- /dev/null +++ b/Lang/Racket/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Racket \ No newline at end of file diff --git a/Lang/Racket/Fractal-tree b/Lang/Racket/Fractal-tree new file mode 120000 index 0000000000..3ed1d86717 --- /dev/null +++ b/Lang/Racket/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Racket \ No newline at end of file diff --git a/Lang/Racket/Function-frequency b/Lang/Racket/Function-frequency new file mode 120000 index 0000000000..cdfa545550 --- /dev/null +++ b/Lang/Racket/Function-frequency @@ -0,0 +1 @@ +../../Task/Function-frequency/Racket \ No newline at end of file diff --git a/Lang/Racket/Function-prototype b/Lang/Racket/Function-prototype new file mode 120000 index 0000000000..642b967c3d --- /dev/null +++ b/Lang/Racket/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Racket \ No newline at end of file diff --git a/Lang/Racket/GUI-Maximum-window-dimensions b/Lang/Racket/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..7415768c47 --- /dev/null +++ b/Lang/Racket/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Racket \ No newline at end of file diff --git a/Lang/Racket/GUI-component-interaction b/Lang/Racket/GUI-component-interaction new file mode 120000 index 0000000000..cf53d974ea --- /dev/null +++ b/Lang/Racket/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Racket \ No newline at end of file diff --git a/Lang/Racket/GUI-enabling-disabling-of-controls b/Lang/Racket/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..5dd36d31a9 --- /dev/null +++ b/Lang/Racket/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Racket \ No newline at end of file diff --git a/Lang/Racket/Gamma-function b/Lang/Racket/Gamma-function new file mode 120000 index 0000000000..a55079004e --- /dev/null +++ b/Lang/Racket/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Racket \ No newline at end of file diff --git a/Lang/Racket/Globally-replace-text-in-several-files b/Lang/Racket/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..69253895b2 --- /dev/null +++ b/Lang/Racket/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Racket \ No newline at end of file diff --git a/Lang/Racket/Grayscale-image b/Lang/Racket/Grayscale-image new file mode 120000 index 0000000000..b5cd578f28 --- /dev/null +++ b/Lang/Racket/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Racket \ No newline at end of file diff --git a/Lang/Racket/Guess-the-number b/Lang/Racket/Guess-the-number new file mode 120000 index 0000000000..dd2c20290d --- /dev/null +++ b/Lang/Racket/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Racket \ No newline at end of file diff --git a/Lang/Racket/Guess-the-number-With-feedback b/Lang/Racket/Guess-the-number-With-feedback new file mode 120000 index 0000000000..ae2a03dea1 --- /dev/null +++ b/Lang/Racket/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Racket \ No newline at end of file diff --git a/Lang/Racket/Guess-the-number-With-feedback--player- b/Lang/Racket/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..bc437534eb --- /dev/null +++ b/Lang/Racket/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Racket \ No newline at end of file diff --git a/Lang/Racket/HTTPS-Client-authenticated b/Lang/Racket/HTTPS-Client-authenticated new file mode 120000 index 0000000000..61a1fb171e --- /dev/null +++ b/Lang/Racket/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Racket \ No newline at end of file diff --git a/Lang/Racket/Handle-a-signal b/Lang/Racket/Handle-a-signal new file mode 120000 index 0000000000..72094383ad --- /dev/null +++ b/Lang/Racket/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Racket \ No newline at end of file diff --git a/Lang/Racket/Happy-numbers b/Lang/Racket/Happy-numbers new file mode 120000 index 0000000000..5fc1692d96 --- /dev/null +++ b/Lang/Racket/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Hello-world-Line-printer b/Lang/Racket/Hello-world-Line-printer new file mode 120000 index 0000000000..f3604f3914 --- /dev/null +++ b/Lang/Racket/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Racket \ No newline at end of file diff --git a/Lang/Racket/Hello-world-Newline-omission b/Lang/Racket/Hello-world-Newline-omission new file mode 120000 index 0000000000..2f8265dba9 --- /dev/null +++ b/Lang/Racket/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Racket \ No newline at end of file diff --git a/Lang/Racket/Honeycombs b/Lang/Racket/Honeycombs new file mode 120000 index 0000000000..651920568d --- /dev/null +++ b/Lang/Racket/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/Racket \ No newline at end of file diff --git a/Lang/Racket/I-before-E-except-after-C b/Lang/Racket/I-before-E-except-after-C new file mode 120000 index 0000000000..b57b252837 --- /dev/null +++ b/Lang/Racket/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Racket \ No newline at end of file diff --git a/Lang/Racket/Integer-comparison b/Lang/Racket/Integer-comparison new file mode 120000 index 0000000000..397a239d59 --- /dev/null +++ b/Lang/Racket/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Racket \ No newline at end of file diff --git a/Lang/Racket/Inverted-index b/Lang/Racket/Inverted-index new file mode 120000 index 0000000000..988ca6f8e4 --- /dev/null +++ b/Lang/Racket/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/Racket \ No newline at end of file diff --git a/Lang/Racket/Josephus-problem b/Lang/Racket/Josephus-problem new file mode 120000 index 0000000000..f0f9ddd5c8 --- /dev/null +++ b/Lang/Racket/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Jump-anywhere b/Lang/Racket/Jump-anywhere new file mode 120000 index 0000000000..3e2c0f1240 --- /dev/null +++ b/Lang/Racket/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Racket \ No newline at end of file diff --git a/Lang/Racket/K-means++-clustering b/Lang/Racket/K-means++-clustering new file mode 120000 index 0000000000..01512ad0ac --- /dev/null +++ b/Lang/Racket/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/Racket \ No newline at end of file diff --git a/Lang/Racket/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Racket/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..7d1d2ccfe6 --- /dev/null +++ b/Lang/Racket/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Racket \ No newline at end of file diff --git a/Lang/Racket/Keyboard-input-Keypress-check b/Lang/Racket/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..e388f4492c --- /dev/null +++ b/Lang/Racket/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Racket \ No newline at end of file diff --git a/Lang/Racket/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Racket/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..862dc17f5d --- /dev/null +++ b/Lang/Racket/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Racket \ No newline at end of file diff --git a/Lang/Racket/Keyboard-macros b/Lang/Racket/Keyboard-macros new file mode 120000 index 0000000000..6b269e7ca4 --- /dev/null +++ b/Lang/Racket/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Racket \ No newline at end of file diff --git a/Lang/Racket/Knapsack-problem-0-1 b/Lang/Racket/Knapsack-problem-0-1 new file mode 120000 index 0000000000..13c881160f --- /dev/null +++ b/Lang/Racket/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Racket \ No newline at end of file diff --git a/Lang/Racket/Knapsack-problem-Bounded b/Lang/Racket/Knapsack-problem-Bounded new file mode 120000 index 0000000000..ac1a713c5e --- /dev/null +++ b/Lang/Racket/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Racket \ No newline at end of file diff --git a/Lang/Racket/Knapsack-problem-Continuous b/Lang/Racket/Knapsack-problem-Continuous new file mode 120000 index 0000000000..b3c731899c --- /dev/null +++ b/Lang/Racket/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Racket \ No newline at end of file diff --git a/Lang/Racket/Knights-tour b/Lang/Racket/Knights-tour new file mode 120000 index 0000000000..25e128b24e --- /dev/null +++ b/Lang/Racket/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Racket \ No newline at end of file diff --git a/Lang/Racket/Knuth-shuffle b/Lang/Racket/Knuth-shuffle new file mode 120000 index 0000000000..44b6da239f --- /dev/null +++ b/Lang/Racket/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Racket \ No newline at end of file diff --git a/Lang/Racket/Largest-int-from-concatenated-ints b/Lang/Racket/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..d51e0696d5 --- /dev/null +++ b/Lang/Racket/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Racket \ No newline at end of file diff --git a/Lang/Racket/Last-Friday-of-each-month b/Lang/Racket/Last-Friday-of-each-month new file mode 120000 index 0000000000..55f44984d8 --- /dev/null +++ b/Lang/Racket/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Racket \ No newline at end of file diff --git a/Lang/Racket/Last-letter-first-letter b/Lang/Racket/Last-letter-first-letter new file mode 120000 index 0000000000..fdd4cf47e0 --- /dev/null +++ b/Lang/Racket/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Racket \ No newline at end of file diff --git a/Lang/Racket/Least-common-multiple b/Lang/Racket/Least-common-multiple new file mode 120000 index 0000000000..7ea4c72f20 --- /dev/null +++ b/Lang/Racket/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Racket \ No newline at end of file diff --git a/Lang/Racket/Literals-Floating-point b/Lang/Racket/Literals-Floating-point new file mode 120000 index 0000000000..275147e125 --- /dev/null +++ b/Lang/Racket/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Racket \ No newline at end of file diff --git a/Lang/Racket/Literals-String b/Lang/Racket/Literals-String new file mode 120000 index 0000000000..8a5fa1a380 --- /dev/null +++ b/Lang/Racket/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Racket \ No newline at end of file diff --git a/Lang/Racket/Logical-operations b/Lang/Racket/Logical-operations new file mode 120000 index 0000000000..e0bdb0d333 --- /dev/null +++ b/Lang/Racket/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Racket \ No newline at end of file diff --git a/Lang/Racket/Long-multiplication b/Lang/Racket/Long-multiplication new file mode 120000 index 0000000000..57fdfa4290 --- /dev/null +++ b/Lang/Racket/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Racket \ No newline at end of file diff --git a/Lang/Racket/Longest-string-challenge b/Lang/Racket/Longest-string-challenge new file mode 120000 index 0000000000..82c6bd48f0 --- /dev/null +++ b/Lang/Racket/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Racket \ No newline at end of file diff --git a/Lang/Racket/Look-and-say-sequence b/Lang/Racket/Look-and-say-sequence new file mode 120000 index 0000000000..7a8d3ff3ef --- /dev/null +++ b/Lang/Racket/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Racket \ No newline at end of file diff --git a/Lang/Racket/Loops-N-plus-one-half b/Lang/Racket/Loops-N-plus-one-half new file mode 120000 index 0000000000..42ec78c9af --- /dev/null +++ b/Lang/Racket/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Racket \ No newline at end of file diff --git a/Lang/Racket/Luhn-test-of-credit-card-numbers b/Lang/Racket/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..c7f250a617 --- /dev/null +++ b/Lang/Racket/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/MD4 b/Lang/Racket/MD4 new file mode 120000 index 0000000000..366f6bffeb --- /dev/null +++ b/Lang/Racket/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Racket \ No newline at end of file diff --git a/Lang/Racket/MD5-Implementation b/Lang/Racket/MD5-Implementation new file mode 120000 index 0000000000..64ed4685f3 --- /dev/null +++ b/Lang/Racket/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Racket \ No newline at end of file diff --git a/Lang/Racket/Mad-Libs b/Lang/Racket/Mad-Libs new file mode 120000 index 0000000000..fe1d629dfc --- /dev/null +++ b/Lang/Racket/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Racket \ No newline at end of file diff --git a/Lang/Racket/Map-range b/Lang/Racket/Map-range new file mode 120000 index 0000000000..a6e31c55a1 --- /dev/null +++ b/Lang/Racket/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Racket \ No newline at end of file diff --git a/Lang/Racket/Matrix-arithmetic b/Lang/Racket/Matrix-arithmetic new file mode 120000 index 0000000000..211e318cde --- /dev/null +++ b/Lang/Racket/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Racket \ No newline at end of file diff --git a/Lang/Racket/Matrix-exponentiation-operator b/Lang/Racket/Matrix-exponentiation-operator new file mode 120000 index 0000000000..2d2fbd3f8b --- /dev/null +++ b/Lang/Racket/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Racket \ No newline at end of file diff --git a/Lang/Racket/Maze-generation b/Lang/Racket/Maze-generation new file mode 120000 index 0000000000..e3cc18738c --- /dev/null +++ b/Lang/Racket/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Racket \ No newline at end of file diff --git a/Lang/Racket/Maze-solving b/Lang/Racket/Maze-solving new file mode 120000 index 0000000000..2ee62cdb84 --- /dev/null +++ b/Lang/Racket/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Racket \ No newline at end of file diff --git a/Lang/Racket/Memory-allocation b/Lang/Racket/Memory-allocation new file mode 120000 index 0000000000..d2f318f201 --- /dev/null +++ b/Lang/Racket/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/Racket \ No newline at end of file diff --git a/Lang/Racket/Memory-layout-of-a-data-structure b/Lang/Racket/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..6a9c4e0728 --- /dev/null +++ b/Lang/Racket/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/Racket \ No newline at end of file diff --git a/Lang/Racket/Menu b/Lang/Racket/Menu new file mode 120000 index 0000000000..e5ea9e64ed --- /dev/null +++ b/Lang/Racket/Menu @@ -0,0 +1 @@ +../../Task/Menu/Racket \ No newline at end of file diff --git a/Lang/Racket/Metered-concurrency b/Lang/Racket/Metered-concurrency new file mode 120000 index 0000000000..cd9d22cb90 --- /dev/null +++ b/Lang/Racket/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Racket \ No newline at end of file diff --git a/Lang/Racket/Metronome b/Lang/Racket/Metronome new file mode 120000 index 0000000000..657ded6715 --- /dev/null +++ b/Lang/Racket/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Racket \ No newline at end of file diff --git a/Lang/Racket/Miller-Rabin-primality-test b/Lang/Racket/Miller-Rabin-primality-test new file mode 120000 index 0000000000..db07b51bff --- /dev/null +++ b/Lang/Racket/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Racket \ No newline at end of file diff --git a/Lang/Racket/Minesweeper-game b/Lang/Racket/Minesweeper-game new file mode 120000 index 0000000000..d7d84ff227 --- /dev/null +++ b/Lang/Racket/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Racket \ No newline at end of file diff --git a/Lang/Racket/Modular-exponentiation b/Lang/Racket/Modular-exponentiation new file mode 120000 index 0000000000..fd351f2f74 --- /dev/null +++ b/Lang/Racket/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Racket \ No newline at end of file diff --git a/Lang/Racket/Modular-inverse b/Lang/Racket/Modular-inverse new file mode 120000 index 0000000000..aa85526e72 --- /dev/null +++ b/Lang/Racket/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Racket \ No newline at end of file diff --git a/Lang/Racket/Monty-Hall-problem b/Lang/Racket/Monty-Hall-problem new file mode 120000 index 0000000000..2ce26b9cb2 --- /dev/null +++ b/Lang/Racket/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Morse-code b/Lang/Racket/Morse-code new file mode 120000 index 0000000000..4d11bab6bc --- /dev/null +++ b/Lang/Racket/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Racket \ No newline at end of file diff --git a/Lang/Racket/Multiple-regression b/Lang/Racket/Multiple-regression new file mode 120000 index 0000000000..103aa47b64 --- /dev/null +++ b/Lang/Racket/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Racket \ No newline at end of file diff --git a/Lang/Racket/Multiplication-tables b/Lang/Racket/Multiplication-tables new file mode 120000 index 0000000000..4e94f9b757 --- /dev/null +++ b/Lang/Racket/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Racket \ No newline at end of file diff --git a/Lang/Racket/Multiplicative-order b/Lang/Racket/Multiplicative-order new file mode 120000 index 0000000000..190b922840 --- /dev/null +++ b/Lang/Racket/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Racket \ No newline at end of file diff --git a/Lang/Racket/Multisplit b/Lang/Racket/Multisplit new file mode 120000 index 0000000000..8fb2cccc58 --- /dev/null +++ b/Lang/Racket/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Racket \ No newline at end of file diff --git a/Lang/Racket/Mutex b/Lang/Racket/Mutex new file mode 120000 index 0000000000..61c87915d1 --- /dev/null +++ b/Lang/Racket/Mutex @@ -0,0 +1 @@ +../../Task/Mutex/Racket \ No newline at end of file diff --git a/Lang/Racket/Mutual-recursion b/Lang/Racket/Mutual-recursion new file mode 120000 index 0000000000..ff448baec8 --- /dev/null +++ b/Lang/Racket/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Racket \ No newline at end of file diff --git a/Lang/Racket/N-queens-problem b/Lang/Racket/N-queens-problem new file mode 120000 index 0000000000..75a8cd8aed --- /dev/null +++ b/Lang/Racket/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Narcissist b/Lang/Racket/Narcissist new file mode 120000 index 0000000000..cc0ec989bd --- /dev/null +++ b/Lang/Racket/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Racket \ No newline at end of file diff --git a/Lang/Racket/Non-continuous-subsequences b/Lang/Racket/Non-continuous-subsequences new file mode 120000 index 0000000000..76cba4d073 --- /dev/null +++ b/Lang/Racket/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Racket \ No newline at end of file diff --git a/Lang/Racket/Non-decimal-radices-Convert b/Lang/Racket/Non-decimal-radices-Convert new file mode 120000 index 0000000000..df04067f3c --- /dev/null +++ b/Lang/Racket/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Racket \ No newline at end of file diff --git a/Lang/Racket/Non-decimal-radices-Input b/Lang/Racket/Non-decimal-radices-Input new file mode 120000 index 0000000000..f08d111594 --- /dev/null +++ b/Lang/Racket/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Racket \ No newline at end of file diff --git a/Lang/Racket/Non-decimal-radices-Output b/Lang/Racket/Non-decimal-radices-Output new file mode 120000 index 0000000000..aa664a1b9d --- /dev/null +++ b/Lang/Racket/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Racket \ No newline at end of file diff --git a/Lang/Racket/Nth-root b/Lang/Racket/Nth-root new file mode 120000 index 0000000000..3431c17da3 --- /dev/null +++ b/Lang/Racket/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Racket \ No newline at end of file diff --git a/Lang/Racket/Null-object b/Lang/Racket/Null-object new file mode 120000 index 0000000000..ecbf1535b7 --- /dev/null +++ b/Lang/Racket/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Racket \ No newline at end of file diff --git a/Lang/Racket/Number-names b/Lang/Racket/Number-names new file mode 120000 index 0000000000..f2646e660f --- /dev/null +++ b/Lang/Racket/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Racket \ No newline at end of file diff --git a/Lang/Racket/Number-reversal-game b/Lang/Racket/Number-reversal-game new file mode 120000 index 0000000000..7380d3a61a --- /dev/null +++ b/Lang/Racket/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Racket \ No newline at end of file diff --git a/Lang/Racket/Numerical-integration b/Lang/Racket/Numerical-integration new file mode 120000 index 0000000000..cc0170e26e --- /dev/null +++ b/Lang/Racket/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Racket \ No newline at end of file diff --git a/Lang/Racket/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Racket/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..cbce79435d --- /dev/null +++ b/Lang/Racket/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket \ No newline at end of file diff --git a/Lang/Racket/One-dimensional-cellular-automata b/Lang/Racket/One-dimensional-cellular-automata new file mode 120000 index 0000000000..2a49a4ce8b --- /dev/null +++ b/Lang/Racket/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Racket \ No newline at end of file diff --git a/Lang/Racket/One-of-n-lines-in-a-file b/Lang/Racket/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..c25983a688 --- /dev/null +++ b/Lang/Racket/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Operator-precedence b/Lang/Racket/Operator-precedence new file mode 120000 index 0000000000..8e610cc9e0 --- /dev/null +++ b/Lang/Racket/Operator-precedence @@ -0,0 +1 @@ +../../Task/Operator-precedence/Racket \ No newline at end of file diff --git a/Lang/Racket/Order-two-numerical-lists b/Lang/Racket/Order-two-numerical-lists new file mode 120000 index 0000000000..1896b35b6f --- /dev/null +++ b/Lang/Racket/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Racket \ No newline at end of file diff --git a/Lang/Racket/Ordered-Partitions b/Lang/Racket/Ordered-Partitions new file mode 120000 index 0000000000..dac2754e58 --- /dev/null +++ b/Lang/Racket/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/Racket \ No newline at end of file diff --git a/Lang/Racket/Ordered-words b/Lang/Racket/Ordered-words new file mode 120000 index 0000000000..e5cf7e7d59 --- /dev/null +++ b/Lang/Racket/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Racket \ No newline at end of file diff --git a/Lang/Racket/Pangram-checker b/Lang/Racket/Pangram-checker new file mode 120000 index 0000000000..4cc56cebbf --- /dev/null +++ b/Lang/Racket/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Racket \ No newline at end of file diff --git a/Lang/Racket/Parallel-calculations b/Lang/Racket/Parallel-calculations new file mode 120000 index 0000000000..10d4dad172 --- /dev/null +++ b/Lang/Racket/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Racket \ No newline at end of file diff --git a/Lang/Racket/Parsing-RPN-calculator-algorithm b/Lang/Racket/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..27407f040a --- /dev/null +++ b/Lang/Racket/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Parsing-RPN-to-infix-conversion b/Lang/Racket/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..7047c941dc --- /dev/null +++ b/Lang/Racket/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Racket \ No newline at end of file diff --git a/Lang/Racket/Percentage-difference-between-images b/Lang/Racket/Percentage-difference-between-images new file mode 120000 index 0000000000..f5d004a0b5 --- /dev/null +++ b/Lang/Racket/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/Racket \ No newline at end of file diff --git a/Lang/Racket/Perfect-numbers b/Lang/Racket/Perfect-numbers new file mode 120000 index 0000000000..15abdb7936 --- /dev/null +++ b/Lang/Racket/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Permutations b/Lang/Racket/Permutations new file mode 120000 index 0000000000..599eeaebb1 --- /dev/null +++ b/Lang/Racket/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Racket \ No newline at end of file diff --git a/Lang/Racket/Permutations-Derangements b/Lang/Racket/Permutations-Derangements new file mode 120000 index 0000000000..c54bf76a9b --- /dev/null +++ b/Lang/Racket/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Racket \ No newline at end of file diff --git a/Lang/Racket/Permutations-by-swapping b/Lang/Racket/Permutations-by-swapping new file mode 120000 index 0000000000..fa252faeb6 --- /dev/null +++ b/Lang/Racket/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Racket \ No newline at end of file diff --git a/Lang/Racket/Pick-random-element b/Lang/Racket/Pick-random-element new file mode 120000 index 0000000000..18cbccb0bd --- /dev/null +++ b/Lang/Racket/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Racket \ No newline at end of file diff --git a/Lang/Racket/Pig-the-dice-game b/Lang/Racket/Pig-the-dice-game new file mode 120000 index 0000000000..1eeed62c3f --- /dev/null +++ b/Lang/Racket/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Racket \ No newline at end of file diff --git a/Lang/Racket/Pig-the-dice-game-Player b/Lang/Racket/Pig-the-dice-game-Player new file mode 120000 index 0000000000..49d55a754f --- /dev/null +++ b/Lang/Racket/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/Racket \ No newline at end of file diff --git a/Lang/Racket/Pinstripe-Display b/Lang/Racket/Pinstripe-Display new file mode 120000 index 0000000000..58e48c6992 --- /dev/null +++ b/Lang/Racket/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Racket \ No newline at end of file diff --git a/Lang/Racket/Pinstripe-Printer b/Lang/Racket/Pinstripe-Printer new file mode 120000 index 0000000000..fb6d702fb8 --- /dev/null +++ b/Lang/Racket/Pinstripe-Printer @@ -0,0 +1 @@ +../../Task/Pinstripe-Printer/Racket \ No newline at end of file diff --git a/Lang/Racket/Plot-coordinate-pairs b/Lang/Racket/Plot-coordinate-pairs new file mode 120000 index 0000000000..046713c4b6 --- /dev/null +++ b/Lang/Racket/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Racket \ No newline at end of file diff --git a/Lang/Racket/Pointers-and-references b/Lang/Racket/Pointers-and-references new file mode 120000 index 0000000000..e516a92e0f --- /dev/null +++ b/Lang/Racket/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Racket \ No newline at end of file diff --git a/Lang/Racket/Polynomial-regression b/Lang/Racket/Polynomial-regression new file mode 120000 index 0000000000..01a4bbe42c --- /dev/null +++ b/Lang/Racket/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Racket \ No newline at end of file diff --git a/Lang/Racket/Price-fraction b/Lang/Racket/Price-fraction new file mode 120000 index 0000000000..2854fd2b75 --- /dev/null +++ b/Lang/Racket/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Racket \ No newline at end of file diff --git a/Lang/Racket/Primality-by-trial-division b/Lang/Racket/Primality-by-trial-division new file mode 120000 index 0000000000..966201f483 --- /dev/null +++ b/Lang/Racket/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Racket \ No newline at end of file diff --git a/Lang/Racket/Prime-decomposition b/Lang/Racket/Prime-decomposition new file mode 120000 index 0000000000..e73a22e827 --- /dev/null +++ b/Lang/Racket/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Racket \ No newline at end of file diff --git a/Lang/Racket/Priority-queue b/Lang/Racket/Priority-queue new file mode 120000 index 0000000000..4f62e8b5df --- /dev/null +++ b/Lang/Racket/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Racket \ No newline at end of file diff --git a/Lang/Racket/Probabilistic-choice b/Lang/Racket/Probabilistic-choice new file mode 120000 index 0000000000..7a99e4788e --- /dev/null +++ b/Lang/Racket/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Racket \ No newline at end of file diff --git a/Lang/Racket/Problem-of-Apollonius b/Lang/Racket/Problem-of-Apollonius new file mode 120000 index 0000000000..0636bb8798 --- /dev/null +++ b/Lang/Racket/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/Racket \ No newline at end of file diff --git a/Lang/Racket/Program-termination b/Lang/Racket/Program-termination new file mode 120000 index 0000000000..5bb8f7767d --- /dev/null +++ b/Lang/Racket/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Racket \ No newline at end of file diff --git a/Lang/Racket/Pythagorean-triples b/Lang/Racket/Pythagorean-triples new file mode 120000 index 0000000000..c3a22bec61 --- /dev/null +++ b/Lang/Racket/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Racket \ No newline at end of file diff --git a/Lang/Racket/QR-decomposition b/Lang/Racket/QR-decomposition new file mode 120000 index 0000000000..0c4085c9c8 --- /dev/null +++ b/Lang/Racket/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Racket \ No newline at end of file diff --git a/Lang/Racket/Quaternion-type b/Lang/Racket/Quaternion-type new file mode 120000 index 0000000000..88e3ea41c9 --- /dev/null +++ b/Lang/Racket/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Racket \ No newline at end of file diff --git a/Lang/Racket/Queue-Definition b/Lang/Racket/Queue-Definition new file mode 120000 index 0000000000..d5fdba8897 --- /dev/null +++ b/Lang/Racket/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Racket \ No newline at end of file diff --git a/Lang/Racket/Queue-Usage b/Lang/Racket/Queue-Usage new file mode 120000 index 0000000000..8364927e8b --- /dev/null +++ b/Lang/Racket/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Racket \ No newline at end of file diff --git a/Lang/Racket/Quine b/Lang/Racket/Quine new file mode 120000 index 0000000000..4cbb2b5bda --- /dev/null +++ b/Lang/Racket/Quine @@ -0,0 +1 @@ +../../Task/Quine/Racket \ No newline at end of file diff --git a/Lang/Racket/RIPEMD-160 b/Lang/Racket/RIPEMD-160 new file mode 120000 index 0000000000..08ed9496da --- /dev/null +++ b/Lang/Racket/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Racket \ No newline at end of file diff --git a/Lang/Racket/Random-number-generator--device- b/Lang/Racket/Random-number-generator--device- new file mode 120000 index 0000000000..9a28c372aa --- /dev/null +++ b/Lang/Racket/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Racket \ No newline at end of file diff --git a/Lang/Racket/Random-numbers b/Lang/Racket/Random-numbers new file mode 120000 index 0000000000..1b17e68750 --- /dev/null +++ b/Lang/Racket/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Range-extraction b/Lang/Racket/Range-extraction new file mode 120000 index 0000000000..0c18347749 --- /dev/null +++ b/Lang/Racket/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Racket \ No newline at end of file diff --git a/Lang/Racket/Rate-counter b/Lang/Racket/Rate-counter new file mode 120000 index 0000000000..e8ec827a6e --- /dev/null +++ b/Lang/Racket/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Racket \ No newline at end of file diff --git a/Lang/Racket/Read-a-configuration-file b/Lang/Racket/Read-a-configuration-file new file mode 120000 index 0000000000..9af2a699bc --- /dev/null +++ b/Lang/Racket/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Read-a-specific-line-from-a-file b/Lang/Racket/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..064aba9fb8 --- /dev/null +++ b/Lang/Racket/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Record-sound b/Lang/Racket/Record-sound new file mode 120000 index 0000000000..00ab02f19a --- /dev/null +++ b/Lang/Racket/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Racket \ No newline at end of file diff --git a/Lang/Racket/Remove-duplicate-elements b/Lang/Racket/Remove-duplicate-elements new file mode 120000 index 0000000000..ed71570621 --- /dev/null +++ b/Lang/Racket/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Racket \ No newline at end of file diff --git a/Lang/Racket/Remove-lines-from-a-file b/Lang/Racket/Remove-lines-from-a-file new file mode 120000 index 0000000000..3b8f67912a --- /dev/null +++ b/Lang/Racket/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Respond-to-an-unknown-method-call b/Lang/Racket/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..4ed7f39f95 --- /dev/null +++ b/Lang/Racket/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Racket \ No newline at end of file diff --git a/Lang/Racket/Return-multiple-values b/Lang/Racket/Return-multiple-values new file mode 120000 index 0000000000..285f8f32af --- /dev/null +++ b/Lang/Racket/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Racket \ No newline at end of file diff --git a/Lang/Racket/Rock-paper-scissors b/Lang/Racket/Rock-paper-scissors new file mode 120000 index 0000000000..06bfb7a5cb --- /dev/null +++ b/Lang/Racket/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Racket \ No newline at end of file diff --git a/Lang/Racket/Roman-numerals-Decode b/Lang/Racket/Roman-numerals-Decode new file mode 120000 index 0000000000..9a3b6e8a48 --- /dev/null +++ b/Lang/Racket/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Racket \ No newline at end of file diff --git a/Lang/Racket/Roman-numerals-Encode b/Lang/Racket/Roman-numerals-Encode new file mode 120000 index 0000000000..1673d43423 --- /dev/null +++ b/Lang/Racket/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Racket \ No newline at end of file diff --git a/Lang/Racket/Roots-of-a-function b/Lang/Racket/Roots-of-a-function new file mode 120000 index 0000000000..762ad3a54b --- /dev/null +++ b/Lang/Racket/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Racket \ No newline at end of file diff --git a/Lang/Racket/Roots-of-a-quadratic-function b/Lang/Racket/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..99f7972ab2 --- /dev/null +++ b/Lang/Racket/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Racket \ No newline at end of file diff --git a/Lang/Racket/Rosetta-Code-Count-examples b/Lang/Racket/Rosetta-Code-Count-examples new file mode 120000 index 0000000000..b9d3365fda --- /dev/null +++ b/Lang/Racket/Rosetta-Code-Count-examples @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Count-examples/Racket \ No newline at end of file diff --git a/Lang/Racket/Rosetta-Code-Find-unimplemented-tasks b/Lang/Racket/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..82f76d4f9e --- /dev/null +++ b/Lang/Racket/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Racket \ No newline at end of file diff --git a/Lang/Racket/Rosetta-Code-Fix-code-tags b/Lang/Racket/Rosetta-Code-Fix-code-tags new file mode 120000 index 0000000000..b44514c3fb --- /dev/null +++ b/Lang/Racket/Rosetta-Code-Fix-code-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Fix-code-tags/Racket \ No newline at end of file diff --git a/Lang/Racket/Run-length-encoding b/Lang/Racket/Run-length-encoding new file mode 120000 index 0000000000..ec46e8e648 --- /dev/null +++ b/Lang/Racket/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Racket \ No newline at end of file diff --git a/Lang/Racket/Runtime-evaluation b/Lang/Racket/Runtime-evaluation new file mode 120000 index 0000000000..9b2c0de67f --- /dev/null +++ b/Lang/Racket/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Racket \ No newline at end of file diff --git a/Lang/Racket/Runtime-evaluation-In-an-environment b/Lang/Racket/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..7a820a9e61 --- /dev/null +++ b/Lang/Racket/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Racket \ No newline at end of file diff --git a/Lang/Racket/SHA-256 b/Lang/Racket/SHA-256 new file mode 120000 index 0000000000..1a9197d5b5 --- /dev/null +++ b/Lang/Racket/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Racket \ No newline at end of file diff --git a/Lang/Racket/Safe-addition b/Lang/Racket/Safe-addition new file mode 120000 index 0000000000..67d0801e6d --- /dev/null +++ b/Lang/Racket/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Racket \ No newline at end of file diff --git a/Lang/Racket/Scope-Function-names-and-labels b/Lang/Racket/Scope-Function-names-and-labels new file mode 120000 index 0000000000..b77089cb02 --- /dev/null +++ b/Lang/Racket/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Racket \ No newline at end of file diff --git a/Lang/Racket/Self-describing-numbers b/Lang/Racket/Self-describing-numbers new file mode 120000 index 0000000000..d85b6758fc --- /dev/null +++ b/Lang/Racket/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Self-referential-sequence b/Lang/Racket/Self-referential-sequence new file mode 120000 index 0000000000..bf3fd3dd21 --- /dev/null +++ b/Lang/Racket/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Racket \ No newline at end of file diff --git a/Lang/Racket/Semordnilap b/Lang/Racket/Semordnilap new file mode 120000 index 0000000000..e59d43f9db --- /dev/null +++ b/Lang/Racket/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Racket \ No newline at end of file diff --git a/Lang/Racket/Send-an-unknown-method-call b/Lang/Racket/Send-an-unknown-method-call new file mode 120000 index 0000000000..b8106be0c8 --- /dev/null +++ b/Lang/Racket/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Racket \ No newline at end of file diff --git a/Lang/Racket/Set-consolidation b/Lang/Racket/Set-consolidation new file mode 120000 index 0000000000..72871bbb51 --- /dev/null +++ b/Lang/Racket/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Racket \ No newline at end of file diff --git a/Lang/Racket/Set-of-real-numbers b/Lang/Racket/Set-of-real-numbers new file mode 120000 index 0000000000..91275d1ee6 --- /dev/null +++ b/Lang/Racket/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Racket \ No newline at end of file diff --git a/Lang/Racket/Set-puzzle b/Lang/Racket/Set-puzzle new file mode 120000 index 0000000000..10b1572e36 --- /dev/null +++ b/Lang/Racket/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Seven-sided-dice-from-five-sided-dice b/Lang/Racket/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..1d1d490609 --- /dev/null +++ b/Lang/Racket/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Racket \ No newline at end of file diff --git a/Lang/Racket/Sierpinski-carpet b/Lang/Racket/Sierpinski-carpet new file mode 120000 index 0000000000..12bf6dde67 --- /dev/null +++ b/Lang/Racket/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Racket \ No newline at end of file diff --git a/Lang/Racket/Sierpinski-triangle b/Lang/Racket/Sierpinski-triangle new file mode 120000 index 0000000000..53f1b101df --- /dev/null +++ b/Lang/Racket/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Racket \ No newline at end of file diff --git a/Lang/Racket/Sierpinski-triangle-Graphical b/Lang/Racket/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..3160fdd4a4 --- /dev/null +++ b/Lang/Racket/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Racket \ No newline at end of file diff --git a/Lang/Racket/Sieve-of-Eratosthenes b/Lang/Racket/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c312a2aa5a --- /dev/null +++ b/Lang/Racket/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Racket \ No newline at end of file diff --git a/Lang/Racket/Simulate-input-Keyboard b/Lang/Racket/Simulate-input-Keyboard new file mode 120000 index 0000000000..c07bdc9211 --- /dev/null +++ b/Lang/Racket/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Racket \ No newline at end of file diff --git a/Lang/Racket/Singly-linked-list-Element-definition b/Lang/Racket/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..f8502be306 --- /dev/null +++ b/Lang/Racket/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Racket \ No newline at end of file diff --git a/Lang/Racket/Singly-linked-list-Element-insertion b/Lang/Racket/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..6071957342 --- /dev/null +++ b/Lang/Racket/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Racket \ No newline at end of file diff --git a/Lang/Racket/Singly-linked-list-Traversal b/Lang/Racket/Singly-linked-list-Traversal new file mode 120000 index 0000000000..13e22774f9 --- /dev/null +++ b/Lang/Racket/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Racket \ No newline at end of file diff --git a/Lang/Racket/Sort-an-array-of-composite-structures b/Lang/Racket/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..3021d56dc1 --- /dev/null +++ b/Lang/Racket/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Racket \ No newline at end of file diff --git a/Lang/Racket/Sort-an-integer-array b/Lang/Racket/Sort-an-integer-array new file mode 120000 index 0000000000..8199d3890c --- /dev/null +++ b/Lang/Racket/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Racket \ No newline at end of file diff --git a/Lang/Racket/Sort-disjoint-sublist b/Lang/Racket/Sort-disjoint-sublist new file mode 120000 index 0000000000..5b0e7e9093 --- /dev/null +++ b/Lang/Racket/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Racket \ No newline at end of file diff --git a/Lang/Racket/Sort-stability b/Lang/Racket/Sort-stability new file mode 120000 index 0000000000..e5e6d5c8ad --- /dev/null +++ b/Lang/Racket/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Racket \ No newline at end of file diff --git a/Lang/Racket/Sort-using-a-custom-comparator b/Lang/Racket/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..e783f0147e --- /dev/null +++ b/Lang/Racket/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Bubble-sort b/Lang/Racket/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..fcf61fc531 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Cocktail-sort b/Lang/Racket/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..8a9ff0192b --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Comb-sort b/Lang/Racket/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..5831a905ae --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Counting-sort b/Lang/Racket/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..0b25a88fb9 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Gnome-sort b/Lang/Racket/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..af7b8cb0c1 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Heapsort b/Lang/Racket/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..3b503d47ed --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Merge-sort b/Lang/Racket/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..e83062daec --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Pancake-sort b/Lang/Racket/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..bdbae871b0 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Permutation-sort b/Lang/Racket/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..8fdd66dc40 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Quicksort b/Lang/Racket/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..319422c6bd --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Radix-sort b/Lang/Racket/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..df3a17a7e6 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Selection-sort b/Lang/Racket/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..48502743f6 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Shell-sort b/Lang/Racket/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..dafa2de77b --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Stooge-sort b/Lang/Racket/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..cb811e4427 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Strand-sort b/Lang/Racket/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..93995dcab5 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Speech-synthesis b/Lang/Racket/Speech-synthesis new file mode 120000 index 0000000000..f4603dacbd --- /dev/null +++ b/Lang/Racket/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Racket \ No newline at end of file diff --git a/Lang/Racket/Spiral-matrix b/Lang/Racket/Spiral-matrix new file mode 120000 index 0000000000..18c1528d2e --- /dev/null +++ b/Lang/Racket/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Racket \ No newline at end of file diff --git a/Lang/Racket/Stable-marriage-problem b/Lang/Racket/Stable-marriage-problem new file mode 120000 index 0000000000..0e969bdd81 --- /dev/null +++ b/Lang/Racket/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Racket \ No newline at end of file diff --git a/Lang/Racket/Stack-traces b/Lang/Racket/Stack-traces new file mode 120000 index 0000000000..10f122210f --- /dev/null +++ b/Lang/Racket/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Racket \ No newline at end of file diff --git a/Lang/Racket/Stair-climbing-puzzle b/Lang/Racket/Stair-climbing-puzzle new file mode 120000 index 0000000000..055f6ecc7b --- /dev/null +++ b/Lang/Racket/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Racket \ No newline at end of file diff --git a/Lang/Racket/Standard-deviation b/Lang/Racket/Standard-deviation new file mode 120000 index 0000000000..b548b53cd2 --- /dev/null +++ b/Lang/Racket/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Racket \ No newline at end of file diff --git a/Lang/Racket/Stem-and-leaf-plot b/Lang/Racket/Stem-and-leaf-plot new file mode 120000 index 0000000000..329eed50fb --- /dev/null +++ b/Lang/Racket/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Racket \ No newline at end of file diff --git a/Lang/Racket/String-case b/Lang/Racket/String-case new file mode 120000 index 0000000000..69990f0884 --- /dev/null +++ b/Lang/Racket/String-case @@ -0,0 +1 @@ +../../Task/String-case/Racket \ No newline at end of file diff --git a/Lang/Racket/String-concatenation b/Lang/Racket/String-concatenation new file mode 120000 index 0000000000..63c269d1c3 --- /dev/null +++ b/Lang/Racket/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Racket \ No newline at end of file diff --git a/Lang/Racket/String-length b/Lang/Racket/String-length new file mode 120000 index 0000000000..76ea7ab4cd --- /dev/null +++ b/Lang/Racket/String-length @@ -0,0 +1 @@ +../../Task/String-length/Racket \ No newline at end of file diff --git a/Lang/Racket/Strip-a-set-of-characters-from-a-string b/Lang/Racket/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..4a69b2df94 --- /dev/null +++ b/Lang/Racket/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Racket \ No newline at end of file diff --git a/Lang/Racket/Strip-block-comments b/Lang/Racket/Strip-block-comments new file mode 120000 index 0000000000..fa46b9b966 --- /dev/null +++ b/Lang/Racket/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Racket \ No newline at end of file diff --git a/Lang/Racket/Strip-comments-from-a-string b/Lang/Racket/Strip-comments-from-a-string new file mode 120000 index 0000000000..f52173c00d --- /dev/null +++ b/Lang/Racket/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Racket \ No newline at end of file diff --git a/Lang/Racket/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Racket/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..bafbbe21f1 --- /dev/null +++ b/Lang/Racket/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Racket \ No newline at end of file diff --git a/Lang/Racket/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Racket/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..df6203eaff --- /dev/null +++ b/Lang/Racket/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Racket \ No newline at end of file diff --git a/Lang/Racket/Substring b/Lang/Racket/Substring new file mode 120000 index 0000000000..87bdd13b8a --- /dev/null +++ b/Lang/Racket/Substring @@ -0,0 +1 @@ +../../Task/Substring/Racket \ No newline at end of file diff --git a/Lang/Racket/Subtractive-generator b/Lang/Racket/Subtractive-generator new file mode 120000 index 0000000000..93e940a61d --- /dev/null +++ b/Lang/Racket/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Racket \ No newline at end of file diff --git a/Lang/Racket/Sum-digits-of-an-integer b/Lang/Racket/Sum-digits-of-an-integer new file mode 120000 index 0000000000..d4c0528c1b --- /dev/null +++ b/Lang/Racket/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Racket \ No newline at end of file diff --git a/Lang/Racket/Table-creation-Postal-addresses b/Lang/Racket/Table-creation-Postal-addresses new file mode 120000 index 0000000000..54638b2fd5 --- /dev/null +++ b/Lang/Racket/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Racket \ No newline at end of file diff --git a/Lang/Racket/Take-notes-on-the-command-line b/Lang/Racket/Take-notes-on-the-command-line new file mode 120000 index 0000000000..273506e3a6 --- /dev/null +++ b/Lang/Racket/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Racket \ No newline at end of file diff --git a/Lang/Racket/Temperature-conversion b/Lang/Racket/Temperature-conversion new file mode 120000 index 0000000000..7716010b04 --- /dev/null +++ b/Lang/Racket/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Clear-the-screen b/Lang/Racket/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..7e869cdd41 --- /dev/null +++ b/Lang/Racket/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Coloured-text b/Lang/Racket/Terminal-control-Coloured-text new file mode 120000 index 0000000000..ad9b1aec8f --- /dev/null +++ b/Lang/Racket/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Cursor-movement b/Lang/Racket/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..e1754f9951 --- /dev/null +++ b/Lang/Racket/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Cursor-positioning b/Lang/Racket/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..9dcd94f1e5 --- /dev/null +++ b/Lang/Racket/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Dimensions b/Lang/Racket/Terminal-control-Dimensions new file mode 120000 index 0000000000..9e9e21415b --- /dev/null +++ b/Lang/Racket/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Display-an-extended-character b/Lang/Racket/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..7e4c24fc62 --- /dev/null +++ b/Lang/Racket/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Hiding-the-cursor b/Lang/Racket/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..810a0553d5 --- /dev/null +++ b/Lang/Racket/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Inverse-video b/Lang/Racket/Terminal-control-Inverse-video new file mode 120000 index 0000000000..17afd58563 --- /dev/null +++ b/Lang/Racket/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Positional-read b/Lang/Racket/Terminal-control-Positional-read new file mode 120000 index 0000000000..14575392e9 --- /dev/null +++ b/Lang/Racket/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Preserve-screen b/Lang/Racket/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..8e5edca633 --- /dev/null +++ b/Lang/Racket/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Ringing-the-terminal-bell b/Lang/Racket/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..fc64124e41 --- /dev/null +++ b/Lang/Racket/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Racket \ No newline at end of file diff --git a/Lang/Racket/Terminal-control-Unicode-output b/Lang/Racket/Terminal-control-Unicode-output new file mode 120000 index 0000000000..52d77bf908 --- /dev/null +++ b/Lang/Racket/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Racket \ No newline at end of file diff --git a/Lang/Raven/99-Bottles-of-Beer b/Lang/Raven/99-Bottles-of-Beer new file mode 120000 index 0000000000..a450ff6071 --- /dev/null +++ b/Lang/Raven/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Raven \ No newline at end of file diff --git a/Lang/Raven/Arithmetic-geometric-mean b/Lang/Raven/Arithmetic-geometric-mean new file mode 120000 index 0000000000..0a437ffd42 --- /dev/null +++ b/Lang/Raven/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Raven \ No newline at end of file diff --git a/Lang/Raven/Boolean-values b/Lang/Raven/Boolean-values new file mode 120000 index 0000000000..dd8855e9cb --- /dev/null +++ b/Lang/Raven/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Raven \ No newline at end of file diff --git a/Lang/Raven/Greatest-common-divisor b/Lang/Raven/Greatest-common-divisor new file mode 120000 index 0000000000..196f1c5c1a --- /dev/null +++ b/Lang/Raven/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Raven \ No newline at end of file diff --git a/Lang/Raven/Greatest-element-of-a-list b/Lang/Raven/Greatest-element-of-a-list new file mode 120000 index 0000000000..6355355937 --- /dev/null +++ b/Lang/Raven/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Raven \ No newline at end of file diff --git a/Lang/Raven/Greatest-subsequential-sum b/Lang/Raven/Greatest-subsequential-sum new file mode 120000 index 0000000000..f1a21cfbdc --- /dev/null +++ b/Lang/Raven/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Raven \ No newline at end of file diff --git a/Lang/Raven/Hamming-numbers b/Lang/Raven/Hamming-numbers new file mode 120000 index 0000000000..d77c910236 --- /dev/null +++ b/Lang/Raven/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Raven \ No newline at end of file diff --git a/Lang/Raven/Haversine-formula b/Lang/Raven/Haversine-formula new file mode 120000 index 0000000000..1c9dd10c62 --- /dev/null +++ b/Lang/Raven/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Raven \ No newline at end of file diff --git a/Lang/Raven/Here-document b/Lang/Raven/Here-document new file mode 120000 index 0000000000..3cbe8812cc --- /dev/null +++ b/Lang/Raven/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Raven \ No newline at end of file diff --git a/Lang/Raven/Higher-order-functions b/Lang/Raven/Higher-order-functions new file mode 120000 index 0000000000..5790b43897 --- /dev/null +++ b/Lang/Raven/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Raven \ No newline at end of file diff --git a/Lang/Raven/Integer-comparison b/Lang/Raven/Integer-comparison new file mode 120000 index 0000000000..eac2719b1a --- /dev/null +++ b/Lang/Raven/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Raven \ No newline at end of file diff --git a/Lang/Raven/Integer-sequence b/Lang/Raven/Integer-sequence new file mode 120000 index 0000000000..fa14d9d1fa --- /dev/null +++ b/Lang/Raven/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Raven \ No newline at end of file diff --git a/Lang/Raven/Leap-year b/Lang/Raven/Leap-year new file mode 120000 index 0000000000..b6a3057764 --- /dev/null +++ b/Lang/Raven/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Raven \ No newline at end of file diff --git a/Lang/Raven/Letter-frequency b/Lang/Raven/Letter-frequency new file mode 120000 index 0000000000..b9a6dc8df0 --- /dev/null +++ b/Lang/Raven/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Raven \ No newline at end of file diff --git a/Lang/Raven/Loops-For-with-a-specified-step b/Lang/Raven/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..0f7329fd32 --- /dev/null +++ b/Lang/Raven/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Raven \ No newline at end of file diff --git a/Lang/Raven/Null-object b/Lang/Raven/Null-object new file mode 120000 index 0000000000..c6e5de5cc5 --- /dev/null +++ b/Lang/Raven/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Raven \ No newline at end of file diff --git a/Lang/Raven/Price-fraction b/Lang/Raven/Price-fraction new file mode 120000 index 0000000000..ddbcd9281d --- /dev/null +++ b/Lang/Raven/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Raven \ No newline at end of file diff --git a/Lang/Raven/Program-name b/Lang/Raven/Program-name new file mode 120000 index 0000000000..803f8e90d0 --- /dev/null +++ b/Lang/Raven/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Raven \ No newline at end of file diff --git a/Lang/Raven/Random-numbers b/Lang/Raven/Random-numbers new file mode 120000 index 0000000000..4ef65a13c4 --- /dev/null +++ b/Lang/Raven/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Raven \ No newline at end of file diff --git a/Lang/Raven/Range-expansion b/Lang/Raven/Range-expansion new file mode 120000 index 0000000000..07cecd7b22 --- /dev/null +++ b/Lang/Raven/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Raven \ No newline at end of file diff --git a/Lang/Raven/Read-entire-file b/Lang/Raven/Read-entire-file new file mode 120000 index 0000000000..0eb6292568 --- /dev/null +++ b/Lang/Raven/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Raven \ No newline at end of file diff --git a/Lang/Raven/Rename-a-file b/Lang/Raven/Rename-a-file new file mode 120000 index 0000000000..a578186a34 --- /dev/null +++ b/Lang/Raven/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Raven \ No newline at end of file diff --git a/Lang/Raven/Return-multiple-values b/Lang/Raven/Return-multiple-values new file mode 120000 index 0000000000..99b8b1f7fb --- /dev/null +++ b/Lang/Raven/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Raven \ No newline at end of file diff --git a/Lang/Raven/Reverse-a-string b/Lang/Raven/Reverse-a-string new file mode 120000 index 0000000000..00a53d3d5d --- /dev/null +++ b/Lang/Raven/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Raven \ No newline at end of file diff --git a/Lang/Raven/Rot-13 b/Lang/Raven/Rot-13 new file mode 120000 index 0000000000..5c7ba1b7f3 --- /dev/null +++ b/Lang/Raven/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Raven \ No newline at end of file diff --git a/Lang/Raven/Stack-traces b/Lang/Raven/Stack-traces new file mode 120000 index 0000000000..37dba725dc --- /dev/null +++ b/Lang/Raven/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Raven \ No newline at end of file diff --git a/Lang/Raven/String-concatenation b/Lang/Raven/String-concatenation new file mode 120000 index 0000000000..c2bd3b49c5 --- /dev/null +++ b/Lang/Raven/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Raven \ No newline at end of file diff --git a/Lang/Raven/Substring b/Lang/Raven/Substring new file mode 120000 index 0000000000..90f7b750e1 --- /dev/null +++ b/Lang/Raven/Substring @@ -0,0 +1 @@ +../../Task/Substring/Raven \ No newline at end of file diff --git a/Lang/Raven/Substring-Top-and-tail b/Lang/Raven/Substring-Top-and-tail new file mode 120000 index 0000000000..b7751daf2b --- /dev/null +++ b/Lang/Raven/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Raven \ No newline at end of file diff --git a/Lang/Raven/Sum-of-a-series b/Lang/Raven/Sum-of-a-series new file mode 120000 index 0000000000..234deb85da --- /dev/null +++ b/Lang/Raven/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Raven \ No newline at end of file diff --git a/Lang/Raven/Sum-of-squares b/Lang/Raven/Sum-of-squares new file mode 120000 index 0000000000..53ef41fec6 --- /dev/null +++ b/Lang/Raven/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Raven \ No newline at end of file diff --git a/Lang/Raven/System-time b/Lang/Raven/System-time new file mode 120000 index 0000000000..762d0cc5dc --- /dev/null +++ b/Lang/Raven/System-time @@ -0,0 +1 @@ +../../Task/System-time/Raven \ No newline at end of file diff --git a/Lang/Ruby/Modular-inverse b/Lang/Ruby/Modular-inverse new file mode 120000 index 0000000000..5443647508 --- /dev/null +++ b/Lang/Ruby/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Factorial b/Lang/Run-BASIC/Factorial new file mode 120000 index 0000000000..e062c40a41 --- /dev/null +++ b/Lang/Run-BASIC/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/N-queens-problem b/Lang/Run-BASIC/N-queens-problem new file mode 120000 index 0000000000..f97f30a031 --- /dev/null +++ b/Lang/Run-BASIC/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Short-circuit-evaluation b/Lang/Run-BASIC/Short-circuit-evaluation new file mode 120000 index 0000000000..272eea3d37 --- /dev/null +++ b/Lang/Run-BASIC/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Run-BASIC \ No newline at end of file diff --git a/Lang/SQL/Primality-by-trial-division b/Lang/SQL/Primality-by-trial-division new file mode 120000 index 0000000000..c80773a4c3 --- /dev/null +++ b/Lang/SQL/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/SQL \ No newline at end of file diff --git a/Lang/SQL/Rot-13 b/Lang/SQL/Rot-13 new file mode 120000 index 0000000000..f2dd19dfde --- /dev/null +++ b/Lang/SQL/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/SQL \ No newline at end of file diff --git a/Lang/SQL/Run-length-encoding b/Lang/SQL/Run-length-encoding new file mode 120000 index 0000000000..298d54c273 --- /dev/null +++ b/Lang/SQL/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/SQL \ No newline at end of file diff --git a/Lang/Scala/Cholesky-decomposition b/Lang/Scala/Cholesky-decomposition new file mode 120000 index 0000000000..fac29b1398 --- /dev/null +++ b/Lang/Scala/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Scala \ No newline at end of file diff --git a/Lang/Scala/Harshad-or-Niven-series b/Lang/Scala/Harshad-or-Niven-series new file mode 120000 index 0000000000..bb17f608ce --- /dev/null +++ b/Lang/Scala/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Scala \ No newline at end of file diff --git a/Lang/Scala/Largest-int-from-concatenated-ints b/Lang/Scala/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..dffedfc042 --- /dev/null +++ b/Lang/Scala/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Scala \ No newline at end of file diff --git a/Lang/Scala/Number-names b/Lang/Scala/Number-names new file mode 120000 index 0000000000..1fde11c800 --- /dev/null +++ b/Lang/Scala/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Scala \ No newline at end of file diff --git a/Lang/Scala/Ordered-words b/Lang/Scala/Ordered-words new file mode 120000 index 0000000000..08edf6a098 --- /dev/null +++ b/Lang/Scala/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Scala \ No newline at end of file diff --git a/Lang/Scala/Semordnilap b/Lang/Scala/Semordnilap new file mode 120000 index 0000000000..f459600706 --- /dev/null +++ b/Lang/Scala/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Scala \ No newline at end of file diff --git a/Lang/Sed/FizzBuzz b/Lang/Sed/FizzBuzz new file mode 120000 index 0000000000..b2d3c06047 --- /dev/null +++ b/Lang/Sed/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Sed \ No newline at end of file diff --git a/Lang/Seed7/00DESCRIPTION b/Lang/Seed7/00DESCRIPTION index b89818e07b..c6767895fa 100644 --- a/Lang/Seed7/00DESCRIPTION +++ b/Lang/Seed7/00DESCRIPTION @@ -1,7 +1,7 @@ {{language|Seed7 |site=http://seed7.sourceforge.net/ |checking=static -|exec=interpreted}} +|exec=both}} {{language programming paradigm|object-oriented}}'''Seed7''' is a general-purpose programming language designed by Thomas Mertes. It is a higher level language compared to [[Ada]], [[C]] / [[C++]] and [[Java]]. The Seed7 interpreter, and the example programs are [[Open source|open-source]] software. An open-source Seed7 [[compiler]] is also available. In Seed7 new statements and operators can be declared easily. Functions with type results and type parameters are more elegant than the usual template or generics concept. [[Object-oriented_programming|Object orientation]] is used when it brings advantages and not in places when other solutions are more obvious. Although Seed7 contains several concepts of other programming languages it cannot be seen as direct descendant of another programming language. diff --git a/Lang/Seed7/Anagrams b/Lang/Seed7/Anagrams new file mode 120000 index 0000000000..7453659752 --- /dev/null +++ b/Lang/Seed7/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Arithmetic-Rational b/Lang/Seed7/Arithmetic-Rational new file mode 120000 index 0000000000..a4713ef6c4 --- /dev/null +++ b/Lang/Seed7/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Arithmetic-geometric-mean b/Lang/Seed7/Arithmetic-geometric-mean new file mode 120000 index 0000000000..7350bd9f36 --- /dev/null +++ b/Lang/Seed7/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Arrays b/Lang/Seed7/Arrays new file mode 120000 index 0000000000..a565fa9237 --- /dev/null +++ b/Lang/Seed7/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Averages-Mean-angle b/Lang/Seed7/Averages-Mean-angle new file mode 120000 index 0000000000..6ce141c1c6 --- /dev/null +++ b/Lang/Seed7/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Averages-Mode b/Lang/Seed7/Averages-Mode new file mode 120000 index 0000000000..c4ca764260 --- /dev/null +++ b/Lang/Seed7/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Best-shuffle b/Lang/Seed7/Best-shuffle new file mode 120000 index 0000000000..0b0a1c48ca --- /dev/null +++ b/Lang/Seed7/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Call-a-function b/Lang/Seed7/Call-a-function new file mode 120000 index 0000000000..0f50528412 --- /dev/null +++ b/Lang/Seed7/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Catalan-numbers b/Lang/Seed7/Catalan-numbers new file mode 120000 index 0000000000..beff004b64 --- /dev/null +++ b/Lang/Seed7/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Check-Machin-like-formulas b/Lang/Seed7/Check-Machin-like-formulas new file mode 120000 index 0000000000..ab7320e952 --- /dev/null +++ b/Lang/Seed7/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Cholesky-decomposition b/Lang/Seed7/Cholesky-decomposition new file mode 120000 index 0000000000..ce28fb7903 --- /dev/null +++ b/Lang/Seed7/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Digital-root b/Lang/Seed7/Digital-root new file mode 120000 index 0000000000..659398393d --- /dev/null +++ b/Lang/Seed7/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Discordian-date b/Lang/Seed7/Discordian-date new file mode 120000 index 0000000000..473e34f7b9 --- /dev/null +++ b/Lang/Seed7/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Exceptions b/Lang/Seed7/Exceptions new file mode 120000 index 0000000000..aa02172ef2 --- /dev/null +++ b/Lang/Seed7/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Execute-Brain---- b/Lang/Seed7/Execute-Brain---- new file mode 120000 index 0000000000..02c824b9ab --- /dev/null +++ b/Lang/Seed7/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Execute-SNUSP b/Lang/Seed7/Execute-SNUSP new file mode 120000 index 0000000000..08c1565fec --- /dev/null +++ b/Lang/Seed7/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Factors-of-a-Mersenne-number b/Lang/Seed7/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..ed068b32cd --- /dev/null +++ b/Lang/Seed7/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Fibonacci-n-step-number-sequences b/Lang/Seed7/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..32d2b9da54 --- /dev/null +++ b/Lang/Seed7/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Floyds-triangle b/Lang/Seed7/Floyds-triangle new file mode 120000 index 0000000000..68de473cfa --- /dev/null +++ b/Lang/Seed7/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Guess-the-number-With-feedback--player- b/Lang/Seed7/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..de42711676 --- /dev/null +++ b/Lang/Seed7/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Happy-numbers b/Lang/Seed7/Happy-numbers new file mode 120000 index 0000000000..69190d8213 --- /dev/null +++ b/Lang/Seed7/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Harshad-or-Niven-series b/Lang/Seed7/Harshad-or-Niven-series new file mode 120000 index 0000000000..5108ecb1e8 --- /dev/null +++ b/Lang/Seed7/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Haversine-formula b/Lang/Seed7/Haversine-formula new file mode 120000 index 0000000000..5463c72d5a --- /dev/null +++ b/Lang/Seed7/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Hello-world-Web-server b/Lang/Seed7/Hello-world-Web-server new file mode 120000 index 0000000000..02ba282ed3 --- /dev/null +++ b/Lang/Seed7/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Holidays-related-to-Easter b/Lang/Seed7/Holidays-related-to-Easter new file mode 120000 index 0000000000..f0609080dd --- /dev/null +++ b/Lang/Seed7/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/I-before-E-except-after-C b/Lang/Seed7/I-before-E-except-after-C new file mode 120000 index 0000000000..357b798222 --- /dev/null +++ b/Lang/Seed7/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Identity-matrix b/Lang/Seed7/Identity-matrix new file mode 120000 index 0000000000..1684187021 --- /dev/null +++ b/Lang/Seed7/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Inheritance-Single b/Lang/Seed7/Inheritance-Single new file mode 120000 index 0000000000..b9b47ef90f --- /dev/null +++ b/Lang/Seed7/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Josephus-problem b/Lang/Seed7/Josephus-problem new file mode 120000 index 0000000000..9cc4846e5b --- /dev/null +++ b/Lang/Seed7/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Knapsack-problem-Unbounded b/Lang/Seed7/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..30ccd287f8 --- /dev/null +++ b/Lang/Seed7/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Knuth-shuffle b/Lang/Seed7/Knuth-shuffle new file mode 120000 index 0000000000..e249a889a8 --- /dev/null +++ b/Lang/Seed7/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Last-Friday-of-each-month b/Lang/Seed7/Last-Friday-of-each-month new file mode 120000 index 0000000000..ce280f9697 --- /dev/null +++ b/Lang/Seed7/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Linear-congruential-generator b/Lang/Seed7/Linear-congruential-generator new file mode 120000 index 0000000000..f70450f36f --- /dev/null +++ b/Lang/Seed7/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Longest-common-subsequence b/Lang/Seed7/Longest-common-subsequence new file mode 120000 index 0000000000..7b12340bd5 --- /dev/null +++ b/Lang/Seed7/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Mad-Libs b/Lang/Seed7/Mad-Libs new file mode 120000 index 0000000000..e711fb566e --- /dev/null +++ b/Lang/Seed7/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Miller-Rabin-primality-test b/Lang/Seed7/Miller-Rabin-primality-test new file mode 120000 index 0000000000..298c8872f9 --- /dev/null +++ b/Lang/Seed7/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Modular-exponentiation b/Lang/Seed7/Modular-exponentiation new file mode 120000 index 0000000000..91a0902ce1 --- /dev/null +++ b/Lang/Seed7/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Modular-inverse b/Lang/Seed7/Modular-inverse new file mode 120000 index 0000000000..63977a2038 --- /dev/null +++ b/Lang/Seed7/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Multiple-distinct-objects b/Lang/Seed7/Multiple-distinct-objects new file mode 120000 index 0000000000..1f48322936 --- /dev/null +++ b/Lang/Seed7/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/N-queens-problem b/Lang/Seed7/N-queens-problem new file mode 120000 index 0000000000..033050bf8c --- /dev/null +++ b/Lang/Seed7/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Non-decimal-radices-Convert b/Lang/Seed7/Non-decimal-radices-Convert new file mode 120000 index 0000000000..67cc2f7a3f --- /dev/null +++ b/Lang/Seed7/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Non-decimal-radices-Input b/Lang/Seed7/Non-decimal-radices-Input new file mode 120000 index 0000000000..0c58a023f4 --- /dev/null +++ b/Lang/Seed7/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Operator-precedence b/Lang/Seed7/Operator-precedence new file mode 120000 index 0000000000..140d0558f9 --- /dev/null +++ b/Lang/Seed7/Operator-precedence @@ -0,0 +1 @@ +../../Task/Operator-precedence/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Order-two-numerical-lists b/Lang/Seed7/Order-two-numerical-lists new file mode 120000 index 0000000000..1bb8780c7d --- /dev/null +++ b/Lang/Seed7/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Pi b/Lang/Seed7/Pi new file mode 120000 index 0000000000..e1582e2be6 --- /dev/null +++ b/Lang/Seed7/Pi @@ -0,0 +1 @@ +../../Task/Pi/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Polymorphism b/Lang/Seed7/Polymorphism new file mode 120000 index 0000000000..d94633b957 --- /dev/null +++ b/Lang/Seed7/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Rock-paper-scissors b/Lang/Seed7/Rock-paper-scissors new file mode 120000 index 0000000000..a2e462b0c6 --- /dev/null +++ b/Lang/Seed7/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Semordnilap b/Lang/Seed7/Semordnilap new file mode 120000 index 0000000000..e164087e16 --- /dev/null +++ b/Lang/Seed7/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/String-comparison b/Lang/Seed7/String-comparison new file mode 120000 index 0000000000..dc1adb7046 --- /dev/null +++ b/Lang/Seed7/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Subtractive-generator b/Lang/Seed7/Subtractive-generator new file mode 120000 index 0000000000..fe89dd795e --- /dev/null +++ b/Lang/Seed7/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Temperature-conversion b/Lang/Seed7/Temperature-conversion new file mode 120000 index 0000000000..295ba26e6b --- /dev/null +++ b/Lang/Seed7/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Terminal-control-Ringing-the-terminal-bell b/Lang/Seed7/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..56d57415fe --- /dev/null +++ b/Lang/Seed7/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Seed7 \ No newline at end of file diff --git a/Lang/Smalltalk/Euler-method b/Lang/Smalltalk/Euler-method new file mode 120000 index 0000000000..fa57b43f0d --- /dev/null +++ b/Lang/Smalltalk/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Smalltalk \ No newline at end of file diff --git a/Lang/UNIX-Shell/Determine-if-a-string-is-numeric b/Lang/UNIX-Shell/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..692b61692d --- /dev/null +++ b/Lang/UNIX-Shell/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Range-expansion b/Lang/UNIX-Shell/Range-expansion new file mode 120000 index 0000000000..61d7621eaf --- /dev/null +++ b/Lang/UNIX-Shell/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Range-extraction b/Lang/UNIX-Shell/Range-extraction new file mode 120000 index 0000000000..4cc4bc0661 --- /dev/null +++ b/Lang/UNIX-Shell/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Reverse-a-string b/Lang/UNIX-Shell/Reverse-a-string new file mode 120000 index 0000000000..fc78238c9f --- /dev/null +++ b/Lang/UNIX-Shell/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Roman-numerals-Decode b/Lang/UNIX-Shell/Roman-numerals-Decode new file mode 120000 index 0000000000..ef35c57cef --- /dev/null +++ b/Lang/UNIX-Shell/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sierpinski-carpet b/Lang/UNIX-Shell/Sierpinski-carpet new file mode 120000 index 0000000000..54a5ee55af --- /dev/null +++ b/Lang/UNIX-Shell/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/UNIX-Shell \ No newline at end of file diff --git a/Lang/X86-Assembly/Hofstadter-Conway-$10,000-sequence b/Lang/X86-Assembly/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..3bdca1894e --- /dev/null +++ b/Lang/X86-Assembly/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Leap-year b/Lang/X86-Assembly/Leap-year new file mode 120000 index 0000000000..fa0eae715e --- /dev/null +++ b/Lang/X86-Assembly/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/X86-Assembly \ No newline at end of file diff --git a/Task/100-doors/D/100-doors.d b/Task/100-doors/D/100-doors.d index 36a6d0204c..65e8f69802 100644 --- a/Task/100-doors/D/100-doors.d +++ b/Task/100-doors/D/100-doors.d @@ -1,36 +1,31 @@ -import std.stdio; +import std.stdio, std.algorithm, std.range; -enum DoorState { Closed, Open } -alias DoorState[] Doors; +enum DoorState : bool { closed, open } +alias Doors = DoorState[]; -Doors flipUnoptimized(Doors doors) { - doors[] = DoorState.Closed; - foreach (i; 0 .. doors.length) - for (int j = i; j < doors.length; j += i+1) - if (doors[j] == DoorState.Open) - doors[j] = DoorState.Closed; +Doors flipUnoptimized(Doors doors) pure nothrow { + doors[] = DoorState.closed; + + foreach (immutable i; 0 .. doors.length) + for (int j = i; j < doors.length; j += i + 1) + if (doors[j] == DoorState.open) + doors[j] = DoorState.closed; else - doors[j] = DoorState.Open; + doors[j] = DoorState.open; return doors; } -Doors flipOptimized(Doors doors) { - doors[] = DoorState.Closed; - for (int i = 1; i*i <= doors.length; i++) - doors[i*i - 1] = DoorState.Open; +Doors flipOptimized(Doors doors) pure nothrow { + doors[] = DoorState.closed; + for (int i = 1; i ^^ 2 <= doors.length; i++) + doors[i ^^ 2 - 1] = DoorState.open; return doors; } -// test program void main() { auto doors = new Doors(100); - foreach (i, door; flipUnoptimized(doors)) - if (door == DoorState.Open) - write(i+1, " "); - writeln(); - foreach (i, door; flipOptimized(doors)) - if (door == DoorState.Open) - write(i+1, " "); - writeln(); + foreach (const open; [doors.dup.flipUnoptimized, + doors.dup.flipOptimized]) + iota(1, open.length + 1).filter!(i => open[i - 1]).writeln; } diff --git a/Task/100-doors/FBSL/100-doors-1.fbsl b/Task/100-doors/FBSL/100-doors-1.fbsl new file mode 100644 index 0000000000..1366413ba0 --- /dev/null +++ b/Task/100-doors/FBSL/100-doors-1.fbsl @@ -0,0 +1,15 @@ +#AppType Console + +Dim doors[], n As Integer = 100 + +For Dim i = 1 To n + For Dim j = i To n Step i + doors[j] = Not doors[j] + Next +Next + +For i = 1 To n + If doors[i] Then Print "Door ", i, " is open" +Next + +Pause diff --git a/Task/100-doors/FBSL/100-doors-2.fbsl b/Task/100-doors/FBSL/100-doors-2.fbsl new file mode 100644 index 0000000000..acf28ad036 --- /dev/null +++ b/Task/100-doors/FBSL/100-doors-2.fbsl @@ -0,0 +1,12 @@ +#APPTYPE CONSOLE + +DIM i = 0, j = 0, door = 1 + +WHILE INCR(i) < 101 + IF i = door THEN + PRINT "Door ", door, " open" + INCR(door, INCR((INCR(j) << 1))) + END IF +WEND + +PAUSE diff --git a/Task/100-doors/Factor/100-doors-1.factor b/Task/100-doors/Factor/100-doors-1.factor new file mode 100644 index 0000000000..6dccd9b759 --- /dev/null +++ b/Task/100-doors/Factor/100-doors-1.factor @@ -0,0 +1,23 @@ +USING: bit-arrays formatting fry kernel math math.ranges +sequences ; +IN: rosetta.doors + +CONSTANT: number-of-doors 100 + +: multiples ( n -- range ) + 0 number-of-doors rot ; + +: toggle-multiples ( n doors -- ) + [ multiples ] dip '[ _ [ not ] change-nth ] each ; + +: toggle-all-multiples ( doors -- ) + [ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each ; + +: print-doors ( doors -- ) + [ + swap "open" "closed" ? "Door %d is %s\n" printf + ] each-index ; + +: main ( -- ) + number-of-doors 1 + + [ toggle-all-multiples ] [ print-doors ] bi ; diff --git a/Task/100-doors/Factor/100-doors-2.factor b/Task/100-doors/Factor/100-doors-2.factor new file mode 100644 index 0000000000..863a254354 --- /dev/null +++ b/Task/100-doors/Factor/100-doors-2.factor @@ -0,0 +1,8 @@ +USING: + formatting + math math.primes.factors math.ranges + sequences ; +IN: rosetta-doors2 + +: main ( -- ) + 100 [1,b] [ divisors length odd? ] filter "Open %[%d, %]\n" printf ; diff --git a/Task/100-doors/Java/100-doors-2.java b/Task/100-doors/Java/100-doors-2.java index 318cd39a24..fbc73e7d13 100644 --- a/Task/100-doors/Java/100-doors-2.java +++ b/Task/100-doors/Java/100-doors-2.java @@ -1,13 +1,11 @@ public class Doors { - public static void main(final String[] args) - { - boolean[] doors = new boolean[100]; - - for (int pass = 0; pass < 10; pass++) - doors[(pass + 1) * (pass + 1) - 1] = true; - - for(int i = 0; i < 100; i++) - System.out.println("Door #" + (i + 1) + " is " + (doors[i] ? "open." : "closed.")); - } + public static void main(String[] args) + { + boolean[] doors=new boolean[100]; + for(int i=0;i<10;i++) + doors[i*(i+2)]=true; + for(int i=0;i<100;i++) + System.out.println("Door #"+(i+1)+" is"+(doors[i]?"open.":" closed.")); + } } diff --git a/Task/100-doors/Java/100-doors-3.java b/Task/100-doors/Java/100-doors-3.java index 2d89ca9dc4..7722346acf 100644 --- a/Task/100-doors/Java/100-doors-3.java +++ b/Task/100-doors/Java/100-doors-3.java @@ -1,12 +1,8 @@ public class Doors { - public static void main(final String[] args) - { - StringBuilder sb = new StringBuilder(); - - for (int i = 1; i <= 10; i++) - sb.append("Door #").append(i*i).append(" is open\n"); - - System.out.println(sb.toString()); - } + public static void main(String[] args) + { + for(int i=0;i<10;i++) + System.out.println("Door #"+(i*(i+2)+1)+" is open."); + } } diff --git a/Task/100-doors/Java/100-doors-4.java b/Task/100-doors/Java/100-doors-4.java index 4d4b8e884c..318cd39a24 100644 --- a/Task/100-doors/Java/100-doors-4.java +++ b/Task/100-doors/Java/100-doors-4.java @@ -1,13 +1,13 @@ -public class Doors{ - public static void main(String[] args){ - int i; - for(i = 1; i < 101; i++){ - double sqrt = Math.sqrt(i); - if(sqrt != (int)sqrt){ - System.out.println("Door " + i + " is closed"); - }else{ - System.out.println("Door " + i + " is open"); - } - } - } +public class Doors +{ + public static void main(final String[] args) + { + boolean[] doors = new boolean[100]; + + for (int pass = 0; pass < 10; pass++) + doors[(pass + 1) * (pass + 1) - 1] = true; + + for(int i = 0; i < 100; i++) + System.out.println("Door #" + (i + 1) + " is " + (doors[i] ? "open." : "closed.")); + } } diff --git a/Task/100-doors/Java/100-doors-5.java b/Task/100-doors/Java/100-doors-5.java new file mode 100644 index 0000000000..2d89ca9dc4 --- /dev/null +++ b/Task/100-doors/Java/100-doors-5.java @@ -0,0 +1,12 @@ +public class Doors +{ + public static void main(final String[] args) + { + StringBuilder sb = new StringBuilder(); + + for (int i = 1; i <= 10; i++) + sb.append("Door #").append(i*i).append(" is open\n"); + + System.out.println(sb.toString()); + } +} diff --git a/Task/100-doors/Java/100-doors-6.java b/Task/100-doors/Java/100-doors-6.java new file mode 100644 index 0000000000..4d4b8e884c --- /dev/null +++ b/Task/100-doors/Java/100-doors-6.java @@ -0,0 +1,13 @@ +public class Doors{ + public static void main(String[] args){ + int i; + for(i = 1; i < 101; i++){ + double sqrt = Math.sqrt(i); + if(sqrt != (int)sqrt){ + System.out.println("Door " + i + " is closed"); + }else{ + System.out.println("Door " + i + " is open"); + } + } + } +} diff --git a/Task/100-doors/PL-SQL/100-doors.sql b/Task/100-doors/PL-SQL/100-doors.sql new file mode 100644 index 0000000000..6075d674c6 --- /dev/null +++ b/Task/100-doors/PL-SQL/100-doors.sql @@ -0,0 +1,31 @@ +DECLARE + TYPE doorsarray IS VARRAY(100) OF BOOLEAN; + doors doorsarray := doorsarray(); +BEGIN + +doors.EXTEND(100); --ACCOMMODATE 100 DOORS + +FOR i IN 1 .. doors.COUNT --MAKE ALL 100 DOORS FALSE TO INITIALISE + LOOP + doors(i) := FALSE; + END LOOP; + +FOR j IN 1 .. 100 --ITERATE THRU USING MOD LOGIC AND FLIP THE DOOR RIGHT OPEN OR CLOSE + LOOP + FOR k IN 1 .. 100 + LOOP + IF MOD(k,j)=0 THEN + doors(k) := NOT doors(k); + END IF; + END LOOP; + END LOOP; + +FOR l IN 1 .. doors.COUNT --PRINT THE STATUS IF ALL 100 DOORS AFTER ALL ITERATION + LOOP + DBMS_OUTPUT.PUT_LINE('DOOR '||l||' IS -->> '||CASE WHEN SYS.DBMS_SQLTCB_INTERNAL.I_CONVERT_FROM_BOOLEAN(doors(l)) = 'TRUE' + THEN 'OPEN' + ELSE 'CLOSED' + END); + END LOOP; + +END; diff --git a/Task/100-doors/PowerShell/100-doors-4.psh b/Task/100-doors/PowerShell/100-doors-4.psh new file mode 100644 index 0000000000..9012ac03a5 --- /dev/null +++ b/Task/100-doors/PowerShell/100-doors-4.psh @@ -0,0 +1,3 @@ +1..100|foreach-object {$pipe += "toggle $_ |"} -begin {$pipe=""} +filter toggle($pass) {$_.door = $_.door -xor !($_.index % $pass);$_} +invoke-expression "1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host" diff --git a/Task/100-doors/Racket/100-doors-1.rkt b/Task/100-doors/Racket/100-doors-1.rkt index c2795cf52f..ac648913f3 100644 --- a/Task/100-doors/Racket/100-doors-1.rkt +++ b/Task/100-doors/Racket/100-doors-1.rkt @@ -1,28 +1,17 @@ #lang racket -;; Like "map", but the proc must take an index as well as the element. -(define (map-index proc seq) - (for/list ([(elt i) (in-indexed seq)]) - (proc elt i))) - -;; Applies PROC to every STEPth element of SEQ, leaving the others -;; unchanged. -(define (map-step proc step seq) - (map-index - (lambda (elt i) - ((if (zero? (remainder i step) ) - proc - values) elt)) - seq)) +;; Applies fun to every step-th element of seq, leaving the others unchanged. +(define (map-step fun step seq) + (for/list ([elt seq] [i (in-naturals)]) + ((if (zero? (modulo i step)) fun values) elt))) (define (toggle-nth n seq) (map-step not n seq)) (define (solve seq) - (for/fold ([result seq]) - ([(_ pass) (in-indexed seq)]) - (toggle-nth (add1 pass) result))) + (for/fold ([result seq]) ([_ seq] [pass (in-naturals 1)]) + (toggle-nth pass result))) -(for ([(door index) (in-indexed (solve (make-vector 100 #f)))]) - (when door - (printf "~a is open~%" index))) +(for ([door (solve (make-vector 101 #f))] [index (in-naturals)] + #:when (and door (> index 0))) + (printf "~a is open~%" index)) diff --git a/Task/100-doors/Racket/100-doors-2.rkt b/Task/100-doors/Racket/100-doors-2.rkt index 8440ef4002..35af77432e 100644 --- a/Task/100-doors/Racket/100-doors-2.rkt +++ b/Task/100-doors/Racket/100-doors-2.rkt @@ -1,6 +1,3 @@ #lang racket - -(for-each (lambda (x) (printf "~a is open\n" x)) - (filter (lambda (x) - (exact-integer? (sqrt x))) - (sequence->list (in-range 1 101)))) +(for ([x (in-range 1 101)] #:when (exact-integer? (sqrt x))) + (printf "~a is open\n" x)) diff --git a/Task/100-doors/Racket/100-doors-3.rkt b/Task/100-doors/Racket/100-doors-3.rkt index bb232f0c33..eeb07dc491 100644 --- a/Task/100-doors/Racket/100-doors-3.rkt +++ b/Task/100-doors/Racket/100-doors-3.rkt @@ -1,20 +1,16 @@ #lang slideshow -(define-syntax-rule (vector-neg-set! vec pos) +(define-syntax-rule (vector-neg! vec pos) (vector-set! vec pos (not (vector-ref vec pos)))) (define (make-doors) (define doors (make-vector 100 #f)) - (for ([i (in-range 100)]) - (for ([j (in-range i 100 (add1 i))]) - (vector-neg-set! doors j))) + (for* ([i 100] [j (in-range i 100 (add1 i))]) (vector-neg! doors j)) doors) -(displayln (list->string (for/list ([d (make-doors)]) - (if d #\o #\-)))) +(displayln (list->string (for/list ([d (make-doors)]) (if d #\o #\-)))) -(define (closed-door) (inset (filled-rectangle 4 20) 2)) -(define (open-door) (inset (rectangle 4 20) 2)) +(define closed-door (inset (filled-rectangle 4 20) 2)) +(define open-door (inset (rectangle 4 20) 2)) -(for/fold ([doors (rectangle 0 0)]) - ([open? (make-doors)]) - (hc-append doors (if open? (open-door) (closed-door)))) +(for/fold ([doors (rectangle 0 0)]) ([open? (make-doors)]) + (hc-append doors (if open? open-door closed-door))) diff --git a/Task/100-doors/Ruby/100-doors-1.rb b/Task/100-doors/Ruby/100-doors-1.rb index cbfbab6894..6fcbbe9834 100644 --- a/Task/100-doors/Ruby/100-doors-1.rb +++ b/Task/100-doors/Ruby/100-doors-1.rb @@ -1,31 +1,31 @@ class Door - attr_reader :state - def initialize - @state=:closed - end - - def close; @state=:closed; end - def open; @state=:open; end - - def closed?; @state==:closed; end - def open?; @state==:open; end - - def toggle - if closed? - open - else - close - end - end - - def to_s; @state.to_s; end + attr_reader :state + def initialize + @state=:closed + end + + def close; @state=:closed; end + def open; @state=:open; end + + def closed?; @state==:closed; end + def open?; @state==:open; end + + def toggle + if closed? + open + else + close + end + end + + def to_s; @state.to_s; end end doors=Array.new(100){Door.new} 1.upto(100) do |multiplier| - doors.each_with_index do |door, i| - door.toggle if (i+1)%multiplier==0 - end + doors.each_with_index do |door, i| + door.toggle if (i+1)%multiplier==0 + end end doors.each_with_index{|door, i| puts "Door #{i+1} is #{door}."} diff --git a/Task/100-doors/Ruby/100-doors-2.rb b/Task/100-doors/Ruby/100-doors-2.rb index 92dbf4f3e3..800a2cc796 100644 --- a/Task/100-doors/Ruby/100-doors-2.rb +++ b/Task/100-doors/Ruby/100-doors-2.rb @@ -1,19 +1,18 @@ n = 100 Open = "open" Closed = "closed" -def Open.f - Closed +def Open.toggle + Closed end -def Closed.f - Open +def Closed.toggle + Open end doors = [Closed] * (n+1) for mul in 1..n - for x in 1..n - doors[mul*x] = (doors[mul*x] || break).f - end + for x in 1..n/mul + doors[mul*x] = doors[mul*x].toggle + end end -doors.each_with_index { - |b, i| - puts "Door #{i} is #{b}" if i>0 +doors.each_with_index { |b, i| + puts "Door #{i} is #{b}" if i>0 } diff --git a/Task/100-doors/Ruby/100-doors-3.rb b/Task/100-doors/Ruby/100-doors-3.rb index 9c4df2ab80..5a572783e7 100644 --- a/Task/100-doors/Ruby/100-doors-3.rb +++ b/Task/100-doors/Ruby/100-doors-3.rb @@ -1,4 +1,4 @@ n = 100 (1..n).each do |i| - puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}" + puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}" end diff --git a/Task/100-doors/Ruby/100-doors-4.rb b/Task/100-doors/Ruby/100-doors-4.rb index 703b34dd1d..484a772dd3 100644 --- a/Task/100-doors/Ruby/100-doors-4.rb +++ b/Task/100-doors/Ruby/100-doors-4.rb @@ -1,7 +1,7 @@ doors = [false] * 100 100.times do |i| - (i .. doors.length).step(i+1) do |j| + (i ... doors.length).step(i+1) do |j| doors[j] = !doors[j] end end -puts doors.inspect +puts doors.map.with_index{|d,i| "Door #{i+1} is #{d ? 'open' : 'closed'}."} diff --git a/Task/100-doors/Rust/100-doors-1.rust b/Task/100-doors/Rust/100-doors-1.rust new file mode 100644 index 0000000000..714291be07 --- /dev/null +++ b/Task/100-doors/Rust/100-doors-1.rust @@ -0,0 +1,15 @@ +fn main() { + let mut door_open = [false, ..100]; + + for uint::range(1, 101) |pass| { + for uint::range(1, 101) |door| { + if door % pass == 0 { + door_open[door - 1] = !door_open[door - 1] + } + }; + } + for door_open.eachi |i, state| { + io::println(fmt!("Door %u is %s.", i + 1, + if *state { "open" } else { "closed" })); + } +} diff --git a/Task/100-doors/Rust/100-doors-2.rust b/Task/100-doors/Rust/100-doors-2.rust new file mode 100644 index 0000000000..78364b66ff --- /dev/null +++ b/Task/100-doors/Rust/100-doors-2.rust @@ -0,0 +1,7 @@ +fn main() { + for int::range(1,101) |i| { + let x = float::pow(i as f64, 0.5); + let state = if x == float::round(x) {"open"} else {"closed"}; + io::println(fmt!("Door %i is %s", i, state)); + } +} diff --git a/Task/100-doors/ZED/100-doors.zed b/Task/100-doors/ZED/100-doors.zed index 7c564757da..ffbb6d5b31 100644 --- a/Task/100-doors/ZED/100-doors.zed +++ b/Task/100-doors/ZED/100-doors.zed @@ -1,54 +1,47 @@ -("100doors") -100doors +(100doors) +comment (always) -(message) (first) 100 (100passes) (doors) +(pr) (first) 100 (passes) 1 (doors) (doors) -an infinite list of closed doors +comment (always) (c) "'closed" (doors) -(100passes) doors -[open closed closed closed ...] -(always) -(100passes1) 1 doors - -(100passes1) count doors -101 [open closed closed open ...] +(passes) count doors +comment (>) count 100 doors -(100passes1) count doors -3 [open closed open closed ...] +(passes) count doors +comment (always) -(100passes1) (add1) count - (flip-and-count) count doors +(passes) (add1) count + (pass) count doors -(flip-and-count) frequency doors -3 [open closed open closed ...] +(pass) n doors +comment (always) -(flip-and-count1) frequency frequency doors +(pass1) n n doors -(flip-and-count1) frequency count doors -3 1 [open closed open closed ...] -(=) count 1 -(c) (flip-door-state) (1) doors - (flip-and-count) frequency (!) doors +(pass1) n m doors +comment +(=) m 1 +(c) (toggle) (1) doors + (pass) n (!) doors -(flip-and-count1) frequency count doors -3 3 [open closed open closed ...] -(always) +(pass1) n m doors +comment +(>) m 1 (c) (1) doors - (flip-and-count1) frequency - (sub1) count - (!) doors + (pass1) n (sub1) m (!) doors -(flip-door-state) state -'closed -(=) state "'closed" +(toggle) door +comment +(=) door "'closed" "'open" -(flip-door-state) state -'open -(=) state "'open" +(toggle) door +comment +(=) door "'open" "'closed" diff --git a/Task/24-game-Solve/Julia/24-game-solve.julia b/Task/24-game-Solve/Julia/24-game-solve.julia new file mode 100644 index 0000000000..c3ab76d9bf --- /dev/null +++ b/Task/24-game-Solve/Julia/24-game-solve.julia @@ -0,0 +1,19 @@ +function solve24(nums) + length(nums) != 4 && error("Input must be a 4-element Array") + syms = [+,-,*,/] + for x in syms, y in syms, z in syms + for i = 1:24 + a,b,c,d = nthperm(nums,i) + if round(x(y(a,b),z(c,d)),5) == 24 + return "($a$y$b)$x($c$z$d)" + elseif round(x(a,y(b,z(c,d))),5) == 24 + return "$a$x($b$y($c$z$d))" + elseif round(x(y(z(c,d),b),a),5) == 24 + return "(($c$z$d)$y$b)$x$a" + elseif round(x(y(b,z(c,d)),a),5) == 24 + return "($b$y($c$z$d))$x$a" + end + end + end + return "0" +end diff --git a/Task/24-game-Solve/Racket/24-game-solve-1.rkt b/Task/24-game-Solve/Racket/24-game-solve-1.rkt new file mode 100644 index 0000000000..5fe7cc1c09 --- /dev/null +++ b/Task/24-game-Solve/Racket/24-game-solve-1.rkt @@ -0,0 +1,16 @@ +(define (in-variants n1 o1 n2 o2 n3 o3 n4) + (let ([o1n (object-name o1)] + [o2n (object-name o2)] + [o3n (object-name o3)]) + (with-handlers ((exn:fail:contract:divide-by-zero? (λ (_) empty-sequence))) + (in-parallel + (list (o1 (o2 (o3 n1 n2) n3) n4) + (o1 (o2 n1 (o3 n2 n3)) n4) + (o1 (o2 n1 n2) (o3 n3 n4)) + (o1 n1 (o2 (o3 n2 n3) n4)) + (o1 n1 (o2 n2 (o3 n3 n4)))) + (list `(((,n1 ,o3n ,n2) ,o2n ,n3) ,o1n ,n4) + `((,n1 ,o2n (,n2 ,o3n ,n3)) ,o1n ,n4) + `((,n1 ,o2n ,n2) ,o1n (,n3 ,o3n ,n4)) + `(,n1 ,o1n ((,n2 ,o3n ,n3) ,o2n ,n4)) + `(,n1 ,o1n (,n2 ,o2n (,n3 ,o3n ,n4)))))))) diff --git a/Task/24-game-Solve/Racket/24-game-solve-2.rkt b/Task/24-game-Solve/Racket/24-game-solve-2.rkt new file mode 100644 index 0000000000..6c8a7e336b --- /dev/null +++ b/Task/24-game-Solve/Racket/24-game-solve-2.rkt @@ -0,0 +1,15 @@ +(define (find-solutions numbers (goal 24)) + (define in-operations (list + - * /)) + (remove-duplicates + (for*/list ([n1 numbers] + [n2 (remove-from numbers n1)] + [n3 (remove-from numbers n1 n2)] + [n4 (remove-from numbers n1 n2 n3)] + [o1 in-operations] + [o2 in-operations] + [o3 in-operations] + [(res expr) (in-variants n1 o1 n2 o2 n3 o3 n4)] + #:when (= res goal)) + expr))) + +(define (remove-from numbers . n) (foldr remq numbers n)) diff --git a/Task/24-game/Factor/24-game-1.factor b/Task/24-game/Factor/24-game-1.factor new file mode 100644 index 0000000000..4d199dd36b --- /dev/null +++ b/Task/24-game/Factor/24-game-1.factor @@ -0,0 +1,42 @@ +USING: + combinators.short-circuit + continuations + eval + formatting + fry + kernel + io + math math.ranges + prettyprint + random + sequences + sets ; +IN: 24game + +: choose4 ( -- seq ) + 4 [ 9 [1,b] random ] replicate ; + +: step ( numbers -- ? ) + readln + [ + parse-string + { + ! Is only allowed tokens used? + [ swap { + - / * } append subset? ] + ! Digit count in expression should be equal to the given numbers. + [ [ number? ] count swap length = ] + ! Of course it must evaluate to 24 + [ nip call( -- x ) 24 = ] + } 2&& + [ f "You got it!" ] + [ t "Expression isnt valid, or doesnt evaluate to 24." ] + if + ] + [ 3drop f "Could not parse that." ] + recover print flush ; + +: main ( -- ) + choose4 + [ "Your numbers are %[%s, %], make an expression\n" printf flush ] + [ '[ _ step ] loop ] + bi ; diff --git a/Task/24-game/Factor/24-game-2.factor b/Task/24-game/Factor/24-game-2.factor new file mode 100644 index 0000000000..7a02ef793d --- /dev/null +++ b/Task/24-game/Factor/24-game-2.factor @@ -0,0 +1,4 @@ +IN: scratchpad main +Your numbers are { 4, 1, 8, 2 }, make an expression +8 4 + 2 * 1 / +You got it! diff --git a/Task/24-game/Julia/24-game.julia b/Task/24-game/Julia/24-game.julia new file mode 100644 index 0000000000..c779179e8d --- /dev/null +++ b/Task/24-game/Julia/24-game.julia @@ -0,0 +1,56 @@ +function twentyfour() + function check(input) + d = ref(Int) + for i in input.args + if typeof(i) == Expr + c = check(i) + typeof(c) == String || append!(d,c) + elseif contains([:*,:/,:-,:+],i) + continue + elseif contains([1:9],i) + push!(d,i) + continue + elseif i > 9 || i < 1 + d = "Sorry, $i is not allowed, please use only numbers between 1 and 9" + else + d = "Sorry, $i isn't allowed" + end + end + return d + end + new_digits() = [rand(1:9),rand(1:9),rand(1:9),rand(1:9)] + answer = new_digits() + print("The 24 Game\nYou will be given any four digits in the range 1 to 9, which may have repetitions.\n + Using just the +, -, *, and / operators show how to make an answer of 24.\n + Use parentheses, (), to ensure proper order of evaulation.\n + Enter 'n' for a new set of digits, and 'q' to quit. Good luck!\n + Here's your first 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n + >") + while true + input = chomp(readline(STDIN)) + input == "q" && break + if input == "n" + answer = new_digits() + print("\nLet's try again, go ahead and guess\n Here's your 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n>") + continue + end + input = try + parse(input) + catch + print("I couldn't calculate your answer, please try again\n>"); + continue + end + c = check(input) + cc = all([sum(i .== answer) == sum(i .== c) for i in answer]) + !cc && (print("Sorry, valid digits are \n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n are allowed and all four must be used. Please try again\n>"); continue) + if eval(input) == 24 + answer = new_digits() + print("\nYou did it!\nLet's do another round, or enter 'q' to quit\n + Here's your 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n + >") + continue + else + print("\nSorry your answer calculates to $(eval(input))\nTry again\n>") + end + end +end diff --git a/Task/24-game/Racket/24-game-1.rkt b/Task/24-game/Racket/24-game-1.rkt new file mode 100644 index 0000000000..9540f6ae51 --- /dev/null +++ b/Task/24-game/Racket/24-game-1.rkt @@ -0,0 +1,35 @@ +#lang racket + +(define (interprete expr numbers) + ;; the cashe for used numbers + (define cashe numbers) + + ;; updating the cashe and handling invalid cases + (define (update-cashe! x) + (unless (member x numbers) (error "Number is not in the given set:" x)) + (unless (member x cashe) (error "Number is used more times then it was given:" x)) + (set! cashe (remq x cashe))) + + ;; the parser + (define parse + (match-lambda + ;; parsing arythmetics + [`(,x ... + ,y ...) (+ (parse x) (parse y))] + [`(,x ... - ,y ...) (- (parse x) (parse y))] + [`(,x ... * ,y ...) (* (parse x) (parse y))] + [`(,x ... / ,y ...) (/ (parse x) (parse y))] + [`(,x ,op ,y ...) (error "Unknown operator: " op)] + ;; opening redundant brackets + [`(,expr) (parse expr)] + ;; parsing numbers + [(? number? x) (update-cashe! x) x] + ;; unknown token + [x (error "Not a number: " x)])) + + ;; parse the expresion + (define result (parse expr)) + + ;; return the result if cashe is empty + (if (empty? cashe) + result + (error "You didn`t use all numbers!"))) diff --git a/Task/24-game/Racket/24-game-2.rkt b/Task/24-game/Racket/24-game-2.rkt new file mode 100644 index 0000000000..716d7e05fe --- /dev/null +++ b/Task/24-game/Racket/24-game-2.rkt @@ -0,0 +1,36 @@ +;; starting the program +(define (start) + (displayln "Combine given four numbers using operations + - * / to get 24.") + (displayln "Input 'q' to quit or your answer like '1 - 3 * (2 + 3)'") + (new-game)) + +;; starting a new game +(define (new-game) + ;; create a new number set + (define numbers (build-list 4 (λ (_) (+ 1 (random 9))))) + (apply printf "Your numbers: ~a ~a ~a ~a\n" numbers) + (new-input numbers)) + +;; processing a new user input +(define (new-input numbers) + ;; if an exception is raized while processing, show the exeption message + ;; and prompt for another input, but do not stop the program. + (with-handlers ([exn? (λ (exn) + (displayln (exn-message exn)) + (new-input numbers))]) + ;; get the answer + (define user-expr (read-the-answer)) + ;; interprete it + (case user-expr + [(q) (display "Good buy!")] + [(n) (new-game)] + [else (define ans (interprete user-expr numbers)) + (case ans + [(24) (printf "Indeed! ~a = 24\n" user-expr) + (new-game)] + [else (error "Wrong!" user-expr '= ans)])]))) + +;; reading and preparing the user's answer +;; "1 + 2 * (3 + 4)" --> '(1 + 2 * (3 + 4)) +(define (read-the-answer) + (read (open-input-string (format "(~a)" (read-line))))) diff --git a/Task/99-Bottles-of-Beer/FBSL/99-bottles-of-beer.fbsl b/Task/99-Bottles-of-Beer/FBSL/99-bottles-of-beer.fbsl index 6374d43017..3cefee652c 100644 --- a/Task/99-Bottles-of-Beer/FBSL/99-bottles-of-beer.fbsl +++ b/Task/99-Bottles-of-Beer/FBSL/99-bottles-of-beer.fbsl @@ -1,6 +1,4 @@ -#Option Explicit #AppType Console -#Include Class Wall bottles diff --git a/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt b/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt index 1f56319152..d10a60c1f2 100644 --- a/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt +++ b/Task/99-Bottles-of-Beer/Racket/99-bottles-of-beer.rkt @@ -1,11 +1,8 @@ #lang racket - -(define (plural n) - (string-append (number->string n) " bottle" (if (equal? n 1) "" "s"))) - (define (sing bottles) - (printf "~a of beer on the wall\n~a of beer\nTake on down, pass it around\n~a of beer on the wall\n\n" - (plural bottles) (plural bottles) (plural (sub1 bottles)))) - -(for ((i (in-range 100 0 -1))) - (sing i)) + (define (plural n) (~a n " bottle" (if (= n 1) "" "s"))) + (printf "~a of beer on the wall\n~a of beer\n~ + Take one down, pass it around\n~a of beer on the wall\n\n" + (plural bottles) (plural bottles) (plural (sub1 bottles))) + (unless (= 1 bottles) (sing (sub1 bottles)))) +(sing 100) diff --git a/Task/99-Bottles-of-Beer/Raven/99-bottles-of-beer.raven b/Task/99-Bottles-of-Beer/Raven/99-bottles-of-beer.raven new file mode 100644 index 0000000000..61861a1e20 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Raven/99-bottles-of-beer.raven @@ -0,0 +1,13 @@ +99 0 1 range each as $i + $i 1 = if + "bottle" as $b + else + "bottles" format as $b + $b $i "%d %s of beer on the wall,\n" print + $b $i "%d %s of beer,\n" print + "Take one down, pass it around,\n" print + $i 2 = if + "1 bottle" + else + $i 1 - "%d bottles" format + "%s of beer on the wall.\n\n" print diff --git a/Task/A+B/COBOL/a+b.cobol b/Task/A+B/COBOL/a+b.cobol new file mode 100644 index 0000000000..48ce2239b2 --- /dev/null +++ b/Task/A+B/COBOL/a+b.cobol @@ -0,0 +1,20 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. A-Plus-B. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 A PIC S9(5). + 01 B PIC S9(5). + + 01 A-B-Sum PIC S9(5). + + PROCEDURE DIVISION. + ACCEPT A + ACCEPT B + + ADD A TO B GIVING A-B-Sum + + DISPLAY A-B-Sum + + GOBACK + . diff --git a/Task/A+B/FBSL/a+b.fbsl b/Task/A+B/FBSL/a+b.fbsl new file mode 100644 index 0000000000..65a4f26fc3 --- /dev/null +++ b/Task/A+B/FBSL/a+b.fbsl @@ -0,0 +1,7 @@ +#APPTYPE CONSOLE + +DIM %a, %b +SCANF("%d%d", @a, @b) +PRINT a, "+", b, "=", a + b + +PAUSE diff --git a/Task/A+B/Go/a+b.go b/Task/A+B/Go/a+b.go index 64511a0712..cd8ab7804f 100644 --- a/Task/A+B/Go/a+b.go +++ b/Task/A+B/Go/a+b.go @@ -4,6 +4,6 @@ import "fmt" func main() { var a, b int - fmt.Scanf("%d %d", &a, &b) - fmt.Printf("%d\n", a+b) + fmt.Scan(&a, &b) + fmt.Println(a + b) } diff --git a/Task/A+B/Julia/a+b.julia b/Task/A+B/Julia/a+b.julia new file mode 100644 index 0000000000..a6513cfc2e --- /dev/null +++ b/Task/A+B/Julia/a+b.julia @@ -0,0 +1,6 @@ +#A+B +function AB() + input = sum(map(int,split(readline(STDIN)," "))) + println(input) +end +AB() diff --git a/Task/A+B/ZED/a+b.zed b/Task/A+B/ZED/a+b.zed index 0e80569b99..de54df4381 100644 --- a/Task/A+B/ZED/a+b.zed +++ b/Task/A+B/ZED/a+b.zed @@ -1,5 +1,5 @@ -("A+B") -A+B +(A+B) +comment (always) (+) (read) (default-input-port) (read) (default-input-port) diff --git a/Task/Abstract-type/Cache-ObjectScript/abstract-type-1.cos b/Task/Abstract-type/Cache-ObjectScript/abstract-type-1.cos new file mode 100644 index 0000000000..bb8b46b71a --- /dev/null +++ b/Task/Abstract-type/Cache-ObjectScript/abstract-type-1.cos @@ -0,0 +1,15 @@ +Class Abstract.Class.Shape [ Abstract ] +{ +Parameter SHAPE = 1; +Property Name As %String; +Method Description() {} +} + +Class Abstract.Class.Square Extends (%RegisteredObject, Shape) +{ +Method Description() +{ + Write "SHAPE=", ..#SHAPE, ! + Write ..%ClassName()_$Case(..%Extends(..%PackageName()_".Shape"), 1: " is a ", : " is not a ")_"shape" +} +} diff --git a/Task/Abstract-type/Cache-ObjectScript/abstract-type-2.cos b/Task/Abstract-type/Cache-ObjectScript/abstract-type-2.cos new file mode 100644 index 0000000000..c9817f9dd0 --- /dev/null +++ b/Task/Abstract-type/Cache-ObjectScript/abstract-type-2.cos @@ -0,0 +1,14 @@ +Class Abstract.DataType.Shape [ ClassType = datatype ] +{ +Parameter SHAPE = 1; +Method Description() {} +} + +Class Abstract.DataType.Square Extends (%RegisteredObject, Shape) +{ +Method Description() +{ + Write "SHAPE=", ..#SHAPE, ! + Write ..%ClassName()_$Case(..%Extends(..%PackageName()_".Shape"), 1: " is a ", : " is not a ")_"shape" +} +} diff --git a/Task/Abstract-type/Julia/abstract-type-1.julia b/Task/Abstract-type/Julia/abstract-type-1.julia new file mode 100644 index 0000000000..a27849a327 --- /dev/null +++ b/Task/Abstract-type/Julia/abstract-type-1.julia @@ -0,0 +1,2 @@ +abstract «name» +abstract «name» <: «supertype» diff --git a/Task/Abstract-type/Julia/abstract-type-2.julia b/Task/Abstract-type/Julia/abstract-type-2.julia new file mode 100644 index 0000000000..70af29b407 --- /dev/null +++ b/Task/Abstract-type/Julia/abstract-type-2.julia @@ -0,0 +1,6 @@ +abstract Number +abstract Real <: Number +abstract FloatingPoint <: Real +abstract Integer <: Real +abstract Signed <: Integer +abstract Unsigned <: Integer diff --git a/Task/Accumulator-factory/Julia/accumulator-factory.julia b/Task/Accumulator-factory/Julia/accumulator-factory.julia index 798534f6e5..0a6dd73cfd 100644 --- a/Task/Accumulator-factory/Julia/accumulator-factory.julia +++ b/Task/Accumulator-factory/Julia/accumulator-factory.julia @@ -1,20 +1,7 @@ -julia> function accumulator(i) - function f(n) - i += n - return i - end - return f +function accumulator(i) + f(n) = i += n end -# method added to generic function accumulator - -julia> x = accumulator(1) -# methods for generic function f -f(Any,) at none:3 - -julia> x(5) -6 - -julia> print(accumulator(3)) -f -julia> print(x(2.3)) -8.3 +x = accumulator(1) +x(5) +accumulator(3) +x(2.3) diff --git a/Task/Accumulator-factory/Racket/accumulator-factory.rkt b/Task/Accumulator-factory/Racket/accumulator-factory.rkt index 9786773767..7c08cb1b9a 100644 --- a/Task/Accumulator-factory/Racket/accumulator-factory.rkt +++ b/Task/Accumulator-factory/Racket/accumulator-factory.rkt @@ -1,6 +1,4 @@ #lang racket - -(define (accumulator n) - (lambda (i) - (set! n (+ n i)) - n)) +(define ((accumulator n) i) + (set! n (+ n i)) + n) diff --git a/Task/Ackermann-function/Eiffel/ackermann-function.e b/Task/Ackermann-function/Eiffel/ackermann-function.e index 25a0bdd19a..07730f3a3b 100644 --- a/Task/Ackermann-function/Eiffel/ackermann-function.e +++ b/Task/Ackermann-function/Eiffel/ackermann-function.e @@ -3,7 +3,7 @@ note URI: "http://rosettacode.org/wiki/Ackermann_function" class - ACKERMAN_EXAMPLE + APPLICATION create make @@ -27,15 +27,14 @@ feature {NONE} -- Initialization feature -- Access - ackerman (m: NATURAL; n: NATURAL): NATURAL + ackerman (m, n: NATURAL): NATURAL do if m = 0 then Result := n + 1 - elseif m > 0 and n = 0 then + elseif n = 0 then Result := ackerman (m - 1, 1) - elseif m > 0 and n > 0 then + else Result := ackerman (m - 1, ackerman (m, n - 1)) end end - end diff --git a/Task/Ackermann-function/Erlang/ackermann-function.erl b/Task/Ackermann-function/Erlang/ackermann-function.erl index d59d55aed7..0a79c28ecb 100644 --- a/Task/Ackermann-function/Erlang/ackermann-function.erl +++ b/Task/Ackermann-function/Erlang/ackermann-function.erl @@ -1,10 +1,8 @@ --module(main). --export([main/1]). +-module(ack). +-export([main/1, ack/2]). -main( [ A | [ B |[]]]) -> - io:fwrite("~p~n",[ack(toi(A),toi(B))]). - -toi(E) -> element(1,string:to_integer(E)). +main( [A, B] ) -> + io:fwrite( "~p~n",[ack(erlang:list_to_integer(A), erlang:list_to_integer(B))] ). ack(0,N) -> N + 1; ack(M,0) -> ack(M-1, 1); diff --git a/Task/Ackermann-function/FBSL/ackermann-function-1.fbsl b/Task/Ackermann-function/FBSL/ackermann-function-1.fbsl new file mode 100644 index 0000000000..a905590672 --- /dev/null +++ b/Task/Ackermann-function/FBSL/ackermann-function-1.fbsl @@ -0,0 +1,22 @@ +#APPTYPE CONSOLE + +TestAckermann() + +PAUSE + +SUB TestAckermann() + FOR DIM m = 0 TO 3 + FOR DIM n = 0 TO 10 + PRINT AckermannF(m, n), " "; + NEXT + PRINT + NEXT +END SUB + +FUNCTION AckermannF(m AS INTEGER, n AS INTEGER) AS INTEGER + IF NOT m THEN RETURN n + 1 + IF NOT n THEN RETURN AckermannA(m - 1, 1) + RETURN AckermannC(m - 1, AckermannF(m, n - 1)) +END FUNCTION + +DYNC AckermannC(m AS INTEGER, n AS INTEGER) AS INTEGER diff --git a/Task/Ackermann-function/FBSL/ackermann-function-2.fbsl b/Task/Ackermann-function/FBSL/ackermann-function-2.fbsl new file mode 100644 index 0000000000..476db1899d --- /dev/null +++ b/Task/Ackermann-function/FBSL/ackermann-function-2.fbsl @@ -0,0 +1,11 @@ + int Ackermann(int m, int n) + { + if (!m) return n + 1; + if (!n) return Ackermann(m - 1, 1); + return Ackermann(m - 1, Ackermann(m, n - 1)); + } + + int main(int m, int n) + { + return Ackermann(m, n); + } diff --git a/Task/Ackermann-function/FBSL/ackermann-function-3.fbsl b/Task/Ackermann-function/FBSL/ackermann-function-3.fbsl new file mode 100644 index 0000000000..91ed24f284 --- /dev/null +++ b/Task/Ackermann-function/FBSL/ackermann-function-3.fbsl @@ -0,0 +1,3 @@ +END DYNC + +DYNASM AckermannA(m AS INTEGER, n AS INTEGER) AS INTEGER diff --git a/Task/Ackermann-function/FBSL/ackermann-function-4.fbsl b/Task/Ackermann-function/FBSL/ackermann-function-4.fbsl new file mode 100644 index 0000000000..b54f220ddb --- /dev/null +++ b/Task/Ackermann-function/FBSL/ackermann-function-4.fbsl @@ -0,0 +1,35 @@ + ENTER 0, 0 + INVOKE Ackermann, m, n + LEAVE + RET + + @Ackermann + ENTER 0, 0 + + .IF DWORD PTR [m] .THEN + JMP @F + .ENDIF + MOV EAX, n + INC EAX + JMP xit + + @@ + .IF DWORD PTR [n] .THEN + JMP @F + .ENDIF + MOV EAX, m + DEC EAX + INVOKE Ackermann, EAX, 1 + JMP xit + + @@ + MOV EAX, n + DEC EAX + INVOKE Ackermann, m, EAX + MOV ECX, m + DEC ECX + INVOKE Ackermann, ECX, EAX + + @xit + LEAVE + RET 8 diff --git a/Task/Ackermann-function/FBSL/ackermann-function-5.fbsl b/Task/Ackermann-function/FBSL/ackermann-function-5.fbsl new file mode 100644 index 0000000000..f220b06725 --- /dev/null +++ b/Task/Ackermann-function/FBSL/ackermann-function-5.fbsl @@ -0,0 +1 @@ +END DYNASM diff --git a/Task/Ackermann-function/Julia/ackermann-function-1.julia b/Task/Ackermann-function/Julia/ackermann-function-1.julia new file mode 100644 index 0000000000..95db90894e --- /dev/null +++ b/Task/Ackermann-function/Julia/ackermann-function-1.julia @@ -0,0 +1,9 @@ +function ack(m,n) + if m == 0 + return n + 1 + elseif n == 0 + return ack(m-1,1) + else + return ack(m-1,ack(m,n-1)) + end +end diff --git a/Task/Ackermann-function/Julia/ackermann-function-2.julia b/Task/Ackermann-function/Julia/ackermann-function-2.julia new file mode 100644 index 0000000000..63b6c3710c --- /dev/null +++ b/Task/Ackermann-function/Julia/ackermann-function-2.julia @@ -0,0 +1 @@ +ack2(m,n) = m == 0 ? n + 1 : n == 0 ? ack2(m-1,1) : ack2(m-1,ack2(m,n-1)) diff --git a/Task/Ackermann-function/Racket/ackermann-function.rkt b/Task/Ackermann-function/Racket/ackermann-function.rkt index 554373d035..009ce57f34 100644 --- a/Task/Ackermann-function/Racket/ackermann-function.rkt +++ b/Task/Ackermann-function/Racket/ackermann-function.rkt @@ -1,7 +1,5 @@ #lang racket (define (ackermann m n) (cond [(zero? m) (add1 n)] - [(and (> m 0) (zero? n)) - (ackermann (sub1 m) 1)] - [(and (> m 0) (> n 0)) - (ackermann (sub1 m) (ackermann m (sub1 n)))])) + [(zero? n) (ackermann (sub1 m) 1)] + [else (ackermann (sub1 m) (ackermann m (sub1 n)))])) diff --git a/Task/Ackermann-function/ZED/ackermann-function.zed b/Task/Ackermann-function/ZED/ackermann-function.zed index eb8990588c..45e2cc586f 100644 --- a/Task/Ackermann-function/ZED/ackermann-function.zed +++ b/Task/Ackermann-function/ZED/ackermann-function.zed @@ -1,14 +1,14 @@ -("ackermann") m n +(ackermann) m n 0 3 (zero?) m (add1) n -("ackermann") m n +(ackermann) m n 2 0 (and) (positive?) m (zero?) n -("ackermann") (sub1) m 1 +(ackermann) (sub1) m 1 -("ackermann") m n +(ackermann) m n 2 3 (and) (positive?) m (positive?) n -("ackermann") (sub1) m ("ackermann") m (sub1) n +(ackermann) (sub1) m (ackermann) m (sub1) n diff --git a/Task/Active-Directory-Connect/Erlang/active-directory-connect.erl b/Task/Active-Directory-Connect/Erlang/active-directory-connect.erl new file mode 100644 index 0000000000..da3293d0ae --- /dev/null +++ b/Task/Active-Directory-Connect/Erlang/active-directory-connect.erl @@ -0,0 +1,7 @@ +-module(ldap_example). +-export( [main/1] ). + +main( [Host, DN, Password] ) -> + {ok, Handle} = eldap:open( [Host] ), + ok = eldap:simple_bind( Handle, DN, Password ), + eldap:close( Handle ). diff --git a/Task/Active-Directory-Connect/Racket/active-directory-connect.rkt b/Task/Active-Directory-Connect/Racket/active-directory-connect.rkt new file mode 100644 index 0000000000..ff0cc5dd52 --- /dev/null +++ b/Task/Active-Directory-Connect/Racket/active-directory-connect.rkt @@ -0,0 +1,16 @@ +#lang racket + +(require ffi/unsafe ffi/unsafe/define) + +(define-ffi-definer defldap (ffi-lib "libldap")) +(defldap ldap_init (_fun _string _int -> _pointer)) +(defldap ldap_unbind (_fun _pointer -> _void)) +(defldap ldap_simple_bind_s (_fun _pointer _string _string -> _int)) +(defldap ldap_err2string (_fun _int -> _string)) + +(define name ...) +(define password ...) +(define ld (ldap_init "ldap.somewhere.com" 389)) +(ldap_simple_bind_s ld name password) + +(ldap_unbind ld) diff --git a/Task/Active-object/Erlang/active-object.erl b/Task/Active-object/Erlang/active-object.erl new file mode 100644 index 0000000000..1e9110cb9d --- /dev/null +++ b/Task/Active-object/Erlang/active-object.erl @@ -0,0 +1,62 @@ +-module( active_object ). +-export( [delete/1, input/2, new/0, output/1, task/1] ). +-compile({no_auto_import,[time/0]}). + +delete( Object ) -> + Object ! stop. + +input( Object, Fun ) -> + Object ! {input, Fun}. + +new( ) -> + K = fun zero/1, + S = 0, + T0 = seconds_with_decimals(), + erlang:spawn( fun() -> loop(K, S, T0) end ). + +output( Object ) -> + Object ! {output, erlang:self()}, + receive + {output, Object, Output} -> Output + end. + +task( Integrate_millisec ) -> + Object = new(), + {ok, _Ref} = timer:send_interval( Integrate_millisec, Object, integrate ), + io:fwrite( "New ~p~n", [output(Object)] ), + input( Object, fun sine/1 ), + timer:sleep( 2000 ), + io:fwrite( "Sine ~p~n", [output(Object)] ), + input( Object, fun zero/1 ), + timer:sleep( 500 ), + io:fwrite( "Approx ~p~n", [output(Object)] ), + delete( Object ). + + + +loop( Fun, Sum, T0 ) -> + receive + integrate -> + T1 = seconds_with_decimals(), + New_sum = trapeze( Sum, Fun, T0, T1 ), + loop( Fun, New_sum, T1 ); + stop -> + ok; + {input, New_fun} -> + loop( New_fun, Sum, T0 ); + {output, Pid} -> + Pid ! {output, erlang:self(), Sum}, + loop( Fun, Sum, T0 ) + end. + +sine( T ) -> + math:sin( 2 * math:pi() * 0.5 * T ). + +seconds_with_decimals() -> + {Megaseconds, Seconds, Microseconds} = os:timestamp(), + (Megaseconds * 1000000) + Seconds + (Microseconds / 1000000). + +trapeze( Sum, Fun, T0, T1 ) -> + Sum + (Fun(T1) + Fun(T0)) * (T1 - T0) / 2. + +zero( _ ) -> 0. diff --git a/Task/Active-object/FBSL/active-object.fbsl b/Task/Active-object/FBSL/active-object.fbsl new file mode 100644 index 0000000000..211d1f5250 --- /dev/null +++ b/Task/Active-object/FBSL/active-object.fbsl @@ -0,0 +1,94 @@ +#APPTYPE CONSOLE + +#INCLUDE + +DIM Entity AS NEW Integrator(): Sleep(2000) ' respawn and do the job + +Entity.Relax(): Sleep(500) ' get some rest + +PRINT ">>> ", Entity.Yield(): DELETE Entity ' report and die + +PAUSE + +' ------------- End Program Code ------------- + +#DEFINE SpawnMutex CreateMutex(NULL, FALSE, "mutex") +#DEFINE LockMutex WaitForSingleObject(mutex, INFINITE) +#DEFINE UnlockMutex ReleaseMutex(mutex) +#DEFINE KillMutex CloseHandle(mutex) + +CLASS Integrator + + PRIVATE: + + TYPE LARGE_INTEGER + lowPart AS INTEGER + highPart AS INTEGER + END TYPE + + DIM dfreq AS DOUBLE, dlast AS DOUBLE, dnow AS DOUBLE, llint AS LARGE_INTEGER + DIM dret0 AS DOUBLE, dret1 AS DOUBLE, mutex AS INTEGER, sum AS DOUBLE, thread AS INTEGER + + ' -------------------------------------------- + SUB INITIALIZE() + mutex = SpawnMutex + QueryPerformanceFrequency(@llint) + dfreq = LargeInt2Double(llint) + QueryPerformanceCounter(@llint) + dlast = LargeInt2Double(llint) / dfreq + thread = FBSLTHREAD(ADDRESSOF Sampler) + FBSLTHREADRESUME(thread) + END SUB + SUB TERMINATE() + ' nothing special + END SUB + ' -------------------------------------------- + + SUB Sampler() + DO + LockMutex + Sleep(5) + QueryPerformanceCounter(@llint) + dnow = LargeInt2Double(llint) / dfreq + dret0 = Task(dlast): dret1 = Task(dnow) + sum = sum + (dret1 + dret0) * (dnow - dlast) / 2 + dlast = dnow + UnlockMutex + LOOP + END SUB + + FUNCTION LargeInt2Double(obj AS VARIANT) AS DOUBLE + STATIC ret + ret = obj.highPart + IF obj.highPart < 0 THEN ret = ret + (2 ^ 32) + ret = ret * 2 ^ 32 + ret = ret + obj.lowPart + IF obj.lowPart < 0 THEN ret = ret + (2 ^ 32) + RETURN ret + END FUNCTION + + PUBLIC: + + METHOD Relax() + LockMutex + ADDRESSOF Task = ADDRESSOF Idle + UnlockMutex + END METHOD + + METHOD Yield() AS DOUBLE + LockMutex + Yield = sum + FBSLTHREADKILL(thread) + UnlockMutex + KillMutex + END METHOD + +END CLASS + +FUNCTION Idle(BYVAL t AS DOUBLE) AS DOUBLE + RETURN 0.0 +END FUNCTION + +FUNCTION Task(BYVAL t AS DOUBLE) AS DOUBLE + RETURN SIN(2 * PI * 0.5 * t) +END FUNCTION diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/FBSL/add-a-variable-to-a-class-instance-at-runtime.fbsl b/Task/Add-a-variable-to-a-class-instance-at-runtime/FBSL/add-a-variable-to-a-class-instance-at-runtime.fbsl new file mode 100644 index 0000000000..a57066ddad --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/FBSL/add-a-variable-to-a-class-instance-at-runtime.fbsl @@ -0,0 +1,31 @@ +#APPTYPE CONSOLE + +CLASS Growable + + PRIVATE: + + DIM instructions AS STRING = "Sleep(1)" + :ExecCode + DIM dummy AS INTEGER = EXECLINE(instructions, 1) + + PUBLIC: + + METHOD Absorb(code AS STRING) + instructions = code + GOTO ExecCode + END METHOD + + METHOD Yield() AS VARIANT + RETURN result + END METHOD + +END CLASS + +DIM Sponge AS NEW Growable() + +Sponge.Absorb("DIM b AS VARIANT = 1234567890: DIM result AS VARIANT = b") +PRINT Sponge.Yield() +Sponge.Absorb("b = ""Hello world!"": result = b") +PRINT Sponge.Yield() + +PAUSE diff --git a/Task/Align-columns/FBSL/align-columns.fbsl b/Task/Align-columns/FBSL/align-columns.fbsl new file mode 100644 index 0000000000..5e5b2d9c8c --- /dev/null +++ b/Task/Align-columns/FBSL/align-columns.fbsl @@ -0,0 +1,35 @@ +#APPTYPE CONSOLE + +DIM s = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +are$delineated$by$a$single$'dollar'$character,$write$a$program +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ +column$are$separated$by$at$least$one$space. +Further,$allow$for$each$word$in$a$column$to$be$either$left$ +justified,$right$justified,$or$center$justified$within$its$column." + +DIM lines[] = SPLIT(s, CRLF), tokens[], l, t, length, margin, justify = "center" + +FOREACH l IN lines + tokens = SPLIT(l, "$") + FOREACH t IN tokens + IF STRLEN(t) > length THEN length = INCR(STRLEN) + NEXT +NEXT + +FOREACH l IN lines + tokens = SPLIT(l, "$") + FOREACH t IN tokens + SELECT CASE justify + CASE "left" + PRINT t, SPACE(length - STRLEN(t)); + CASE "center" + margin = (length - STRLEN(t)) \ 2 + PRINT SPACE(margin), t, SPACE(length - STRLEN - margin); + CASE "right" + PRINT SPACE(length - STRLEN(t)), t; + END SELECT + NEXT + PRINT +NEXT + +PAUSE diff --git a/Task/Anagrams-Deranged-anagrams/C++/anagrams-deranged-anagrams.cpp b/Task/Anagrams-Deranged-anagrams/C++/anagrams-deranged-anagrams.cpp new file mode 100644 index 0000000000..e910c0a09a --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/C++/anagrams-deranged-anagrams.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +bool is_deranged(const std::string& left, const std::string& right) +{ + return (left.size() == right.size()) && + (std::inner_product(left.begin(), left.end(), right.begin(), 0, std::plus(), std::equal_to()) == 0); +} + +int main() +{ + std::ifstream input("unixdict.txt"); + if (!input) { + std::cerr << "can't open input file\n"; + return EXIT_FAILURE; + } + + typedef std::set WordList; + typedef std::map AnagraMap; + AnagraMap anagrams; + + std::pair result; + size_t longest = 0; + + for (std::string value; input >> value; /**/) { + std::string key(value); + std::sort(key.begin(), key.end()); + + if (longest < value.length()) { // is it a long candidate? + if (0 < anagrams.count(key)) { // is it an anagram? + for (const auto& prior : anagrams[key]) { + if (is_deranged(prior, value)) { // are they deranged? + result = std::make_pair(prior, value); + longest = value.length(); + } + } + } + } + anagrams[key].insert(value); + } + + std::cout << result.first << ' ' << result.second << '\n'; + return EXIT_SUCCESS; +} diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d new file mode 100644 index 0000000000..838bc0b8c1 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-1.d @@ -0,0 +1,19 @@ +void main() { + import std.stdio, std.file, std.algorithm, std.string, std.range, + std.functional, std.exception; + + string[][const ubyte[]] anags; + foreach (w; "unixdict.txt".readText.split) + anags[w.dup.representation.sort().release.assumeUnique] ~= w; + + anags + .byValue + .map!(words => cartesianProduct(words, words) + .filter!(ww => ww[].zip.all!q{ a[0] != a[1] }) + .array) + .filter!(not!empty) + .array + .schwartzSort!q{ a[0][0].length } + .back[0] + .writeln; +} diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d new file mode 100644 index 0000000000..074dda58ff --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-2.d @@ -0,0 +1,28 @@ +import std.stdio, std.file, std.algorithm, std.string, + std.typecons, std.range, std.functional; + +auto findDeranged(in string[] words) pure /*nothrow*/ { + //return words.pairwise.filter!(ww=> ww[].zip.all!q{a[0] != a[1]}); + Tuple!(string, string)[] result; + foreach (immutable i, const w1; words) + foreach (const w2; words[i + 1 .. $]) + if (zip(w1, w2).all!q{ a[0] != a[1] }) + result ~= tuple(w1, w2); + return result; +} + +void main() { + Appender!(string[])[30] wClasses; + foreach (word; std.algorithm.splitter("unixdict.txt".readText)) + wClasses[$ - word.length] ~= word; + + "Longest deranged anagrams:".writeln; + foreach (words; wClasses[].map!q{ a.data }.filter!(not!empty)) { + string[][const ubyte[]] anags; // Assume ASCII input. + foreach (w; words) + anags[w.dup.representation.sort().release.idup] ~= w; + auto pairs = anags.byValue.map!findDeranged.join; + if (!pairs.empty) + return writefln(" %s, %s", pairs.front[]); + } +} diff --git a/Task/Anagrams-Deranged-anagrams/Erlang/anagrams-deranged-anagrams.erl b/Task/Anagrams-Deranged-anagrams/Erlang/anagrams-deranged-anagrams.erl new file mode 100644 index 0000000000..d97774d0d6 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Erlang/anagrams-deranged-anagrams.erl @@ -0,0 +1,45 @@ +-module( deranged_anagrams ). +-export( [task/0] ). + +task() -> + httpc_start(), + Words = words( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ), + Anagram_dict = anagrams:fetch( Words, dict:new() ), + Deranged_anagrams = deranged_anagrams( Anagram_dict ), + {_Length, Longest_anagrams} = dict:fold( fun keep_longest/3, {0, []}, Deranged_anagrams ), + Longest_anagrams. + + + +deranged_anagrams( Dict ) -> + Deranged_dict = dict:map( fun deranged_words/2, Dict ), + dict:filter( fun is_anagram/2, Deranged_dict ). + +deranged_words( _Key, [H | T] ) -> + [{H, X} || X <- T, is_deranged_word(H, X)]. + +httpc_start() -> + inets:start(), + inets:start( httpc, [] ). + +keep_longest( _Key, [{One, _} | _]=New, {Length, Acc} ) -> + keep_longest_new( erlang:length(One), Length, New, Acc ). + +keep_longest_new( New_length, Acc_length, New, _Acc ) when New_length > Acc_length -> + {New_length, New}; +keep_longest_new( New_length, Acc_length, New, Acc ) when New_length =:= Acc_length -> + {Acc_length, Acc ++ New}; +keep_longest_new( _New_length, Acc_length, _New, Acc ) -> + {Acc_length, Acc}. + +is_anagram( _Key, [] ) -> false; +is_anagram( _Key, _Value ) -> true. + +is_deranged_word( Word1, Word2 ) -> + lists:all( fun is_deranged_char/1, lists:zip(Word1, Word2) ). + +is_deranged_char( {One, Two} ) -> One =/= Two. + +words( URL ) -> + {ok, {{_HTTP, 200, "OK"}, _Headers, Body}} = httpc:request( URL ), + string:tokens( Body, "\n" ). diff --git a/Task/Anagrams-Deranged-anagrams/Python/anagrams-deranged-anagrams-2.py b/Task/Anagrams-Deranged-anagrams/Python/anagrams-deranged-anagrams-2.py index 76822ab9db..7103b05318 100644 --- a/Task/Anagrams-Deranged-anagrams/Python/anagrams-deranged-anagrams-2.py +++ b/Task/Anagrams-Deranged-anagrams/Python/anagrams-deranged-anagrams-2.py @@ -2,17 +2,15 @@ from itertools import izip, ifilter from collections import defaultdict def find_deranged(words): - result = [] - for i, w1 in enumerate(words): - for w2 in words[i+1:]: - if all(a != b for a,b in izip(w1, w2)): - result.append((w1, w2)) - return result + return [(w1, w2) for i, w1 in enumerate(words) + for w2 in words[i + 1:] + if all(a != b for a,b in izip(w1, w2))] def main(): wclasses = [[] for _ in xrange(30)] for word in open("unixdict.txt").read().split(): wclasses[-len(word)].append(word) + print "Longest deranged anagrams:" for words in ifilter(None, wclasses): anags = defaultdict(list) diff --git a/Task/Anagrams-Deranged-anagrams/Racket/anagrams-deranged-anagrams.rkt b/Task/Anagrams-Deranged-anagrams/Racket/anagrams-deranged-anagrams.rkt new file mode 100644 index 0000000000..d7e7cab494 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Racket/anagrams-deranged-anagrams.rkt @@ -0,0 +1,42 @@ +#lang racket +(define word-list-file "data/unixdict.txt") + +(define (read-words-into-anagram-keyed-hash) + (define (anagram-key word) (sort (string->list word) char (length v) 1)) v) + > #:key (compose string-length first))) + + +(define (deranged-anagram-pairs l (acc null)) + (define (deranged-anagram-pair? hd tl) + (define (first-underanged-char? hd tl) + (for/first + (((c h) (in-parallel hd tl)) + #:when (char=? c h)) c)) + (not (first-underanged-char? hd tl))) + + (if (null? l) acc + (let ((hd (car l)) (tl (cdr l))) + (deranged-anagram-pairs + tl + (append acc (map (lambda (x) (list hd x)) + (filter (curry deranged-anagram-pair? hd) tl))))))) + +;; for*/first give the first set of deranged anagrams (as per the RC problem) +;; for*/list gives a full list of the sets of deranged anagrams (which might be interesting) +(for*/first + ((anagrams (in-list anagrams-list)) + (daps (in-value (deranged-anagram-pairs anagrams))) + #:unless (null? daps)) + daps) diff --git a/Task/Anagrams/AWK/anagrams-1.awk b/Task/Anagrams/AWK/anagrams-1.awk new file mode 100644 index 0000000000..deb36cc1fb --- /dev/null +++ b/Task/Anagrams/AWK/anagrams-1.awk @@ -0,0 +1,26 @@ +# JUMBLEA.AWK - words with the most duplicate spellings +# syntax: GAWK -f JUMBLEA.AWK UNIXDICT.TXT +{ for (i=1; i<=NF; i++) { + w = sortstr(toupper($i)) + arr[w] = arr[w] $i " " + n = gsub(/ /,"&",arr[w]) + if (max_n < n) { max_n = n } + } +} +END { + for (w in arr) { + if (gsub(/ /,"&",arr[w]) == max_n) { + printf("%s\t%s\n",w,arr[w]) + } + } + exit(0) +} +function sortstr(str, i,j,leng) { + leng = length(str) + for (i=2; i<=leng; i++) { + for (j=i; j>1 && substr(str,j-1,1) > substr(str,j,1); j--) { + str = substr(str,1,j-2) substr(str,j,1) substr(str,j-1,1) substr(str,j+1) + } + } + return(str) +} diff --git a/Task/Anagrams/AWK/anagrams-2.awk b/Task/Anagrams/AWK/anagrams-2.awk new file mode 100644 index 0000000000..409fcbbd05 --- /dev/null +++ b/Task/Anagrams/AWK/anagrams-2.awk @@ -0,0 +1,17 @@ +#!/bin/gawk -f + +{ patsplit($0, chars, ".") + asort(chars) + sorted = "" + for (i = 1; i <= length(chars); i++) + sorted = sorted chars[i] + + if (++count[sorted] > countMax) countMax++ + accum[sorted] = accum[sorted] " " $0 +} + +END { + for (i in accum) + if (count[i] == countMax) + print substr(accum[i], 2) +} diff --git a/Task/Anagrams/Clojure/anagrams.clj b/Task/Anagrams/Clojure/anagrams.clj index b72065f746..3bab3f5693 100644 --- a/Task/Anagrams/Clojure/anagrams.clj +++ b/Task/Anagrams/Clojure/anagrams.clj @@ -2,9 +2,9 @@ (def groups (with-open [r (io/reader wordfile)] - (group-by sort (line-seq r))) + (group-by sort (line-seq r)))) -(let [wordlists (sort-by (comp - count) (vals groups) +(let [wordlists (sort-by (comp - count) (vals groups)) maxlength (count (first wordlists))] (doseq [wordlist (take-while #(= (count %) maxlength) wordlists)] (println wordlist)) diff --git a/Task/Anagrams/Common-Lisp/anagrams-4.lisp b/Task/Anagrams/Common-Lisp/anagrams-4.lisp index 7a2eb4555c..077815ca61 100644 --- a/Task/Anagrams/Common-Lisp/anagrams-4.lisp +++ b/Task/Anagrams/Common-Lisp/anagrams-4.lisp @@ -1,9 +1,9 @@ -import std.stdio, std.algorithm, std.range, std.string; +import std.stdio, std.algorithm, std.range, std.string, std.exception; void main() { - dstring[][dstring] anags; - foreach (dchar[] w; File("unixdict.txt").lines()) - anags[w.chomp().sort().release().idup] ~= w.chomp().idup; - immutable m = anags.byValue.map!(ws => ws.length)().reduce!max(); - writefln("%(%s\n%)", anags.byValue.filter!(ws => ws.length == m)()); + string[][const ubyte[]] an; + foreach (w; "unixdict.txt".File.byLine(KeepTerminator.no)) + an[w.dup.representation.sort().release.assumeUnique] ~= w.idup; + immutable m = an.byValue.map!q{ a.length }.reduce!max; + writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m)); } diff --git a/Task/Anagrams/Common-Lisp/anagrams-5.lisp b/Task/Anagrams/Common-Lisp/anagrams-5.lisp index 5ce22043d5..cd5cfc1fa8 100644 --- a/Task/Anagrams/Common-Lisp/anagrams-5.lisp +++ b/Task/Anagrams/Common-Lisp/anagrams-5.lisp @@ -1,13 +1,13 @@ -import std.stdio, std.algorithm, std.file; +import std.stdio, std.algorithm, std.file, std.string; void main() { - char[] keys = cast(char[])read("unixdict.txt"); - string vals = keys.idup; + char[] keys = cast(char[])"unixdict.txt".read; + immutable vals = keys.idup; string[][string] anags; - foreach (w; std.array.splitter(keys)) { - const k = cast(string)sort(cast(ubyte[])w).release(); + foreach (w; keys.splitter) { + immutable k = cast(string)w.representation.sort().release; anags[k] ~= vals[k.ptr-keys.ptr .. k.ptr-keys.ptr + k.length]; } - immutable m = anags.byValue.map!(ws => ws.length)().reduce!max(); - writefln("%(%s\n%)", filter!(ws => ws.length == m)(anags.byValue)); + immutable m = anags.byValue.map!q{ a.length }.reduce!max; + writefln("%(%s\n%)", anags.byValue.filter!(ws => ws.length == m)); } diff --git a/Task/Anagrams/FBSL/anagrams-1.fbsl b/Task/Anagrams/FBSL/anagrams-1.fbsl new file mode 100644 index 0000000000..9878494348 --- /dev/null +++ b/Task/Anagrams/FBSL/anagrams-1.fbsl @@ -0,0 +1,160 @@ +#APPTYPE CONSOLE + +DIM gtc = GetTickCount() +Anagram() +PRINT "Done in ", (GetTickCount() - gtc) / 1000, " seconds" + +PAUSE + +DYNC Anagram() + #include + #include + + char* sortedWord(const char* word, char* wbuf) + { + char* p1, *p2, *endwrd; + char t; + int swaps; + + strcpy(wbuf, word); + endwrd = wbuf + strlen(wbuf); + do { + swaps = 0; + p1 = wbuf; p2 = endwrd - 1; + while (p1 < p2) { + if (*p2 >* p1) { + t = *p2; *p2 = *p1; *p1 = t; + swaps = 1; + } + p1++; p2--; + } + p1 = wbuf; p2 = p1 + 1; + while (p2 < endwrd) { + if (*p2 >* p1) { + t = *p2; *p2 = *p1; *p1 = t; + swaps = 1; + } + p1++; p2++; + } + } while (swaps); + return wbuf; + } + + static short cxmap[] = { + 0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56, + 0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24, + 0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03, + 0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49, + 0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f, + 0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36, + 0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a, + 0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57, + }; + #define CXMAP_SIZE (sizeof(cxmap) / sizeof(short)) + + int Str_Hash(const char* key, int ix_max) + { + const char* cp; + short mash; + int hash = 33501551; + for (cp = key; *cp; cp++) { + mash = cxmap[*cp % CXMAP_SIZE]; + hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash << 1) + (mash << 5)); + hash &= 0x3FFFFFFF; + } + return hash % ix_max; + } + + typedef struct sDictWord* DictWord; + struct sDictWord { + const char* word; + DictWord next; + }; + + typedef struct sHashEntry* HashEntry; + struct sHashEntry { + const char* key; + HashEntry next; + DictWord words; + HashEntry link; + short wordCount; + }; + + #define HT_SIZE 8192 + + HashEntry hashTable[HT_SIZE]; + + HashEntry mostPerms = NULL; + + int buildAnagrams(FILE* fin) + { + char buffer[40]; + char bufr2[40]; + char* hkey; + int hix; + HashEntry he, *hep; + DictWord we; + int maxPC = 2; + int numWords = 0; + + while (fgets(buffer, 40, fin)) { + for (hkey = buffer; *hkey && (*hkey != '\n'); hkey++); + *hkey = 0; + hkey = sortedWord(buffer, bufr2); + hix = Str_Hash(hkey, HT_SIZE); + he = hashTable[hix]; hep = &hashTable[hix]; + while (he && strcmp(he->key, hkey)) { + hep = &he->next; + he = he->next; + } + if (! he) { + he = (HashEntry)malloc(sizeof(struct sHashEntry)); + he->next = NULL; + he->key = strdup(hkey); + he->wordCount = 0; + he->words = NULL; + he->link = NULL; + *hep = he; + } + we = (DictWord)malloc(sizeof(struct sDictWord)); + we->word = strdup(buffer); + we->next = he->words; + he->words = we; + he->wordCount++; + if (maxPC < he->wordCount) { + maxPC = he->wordCount; + mostPerms = he; + he->link = NULL; + } + else if (maxPC == he->wordCount) { + he->link = mostPerms; + mostPerms = he; + } + numWords++; + } + printf("%d words in dictionary max ana=%d\n", numWords, maxPC); + return maxPC; + } + + void main() + { + HashEntry he; + DictWord we; + FILE* f1; + + f1 = fopen("unixdict.txt", "r"); + buildAnagrams(f1); + fclose(f1); + + f1 = fopen("anaout.txt", "w"); + + for (he = mostPerms; he; he = he->link) { + fprintf(f1, "%d: ", he->wordCount); + for (we = he->words; we; we = we->next) { + fprintf(f1, "%s, ", we->word); + } + fprintf(f1, "\n"); + } + fclose(f1); + } +END DYNC diff --git a/Task/Anagrams/FBSL/anagrams-2.fbsl b/Task/Anagrams/FBSL/anagrams-2.fbsl new file mode 100644 index 0000000000..ec10e8820f --- /dev/null +++ b/Task/Anagrams/FBSL/anagrams-2.fbsl @@ -0,0 +1,4 @@ + "resource:unixdict.txt" utf8 file-lines + [ [ natural-sort >string ] keep ] { } map>assoc sort-keys + [ [ first ] compare +eq+ = ] monotonic-split + dup 0 [ length max ] reduce '[ length _ = ] filter [ values ] map . diff --git a/Task/Anagrams/FBSL/anagrams-3.fbsl b/Task/Anagrams/FBSL/anagrams-3.fbsl new file mode 100644 index 0000000000..2c7862cb56 --- /dev/null +++ b/Task/Anagrams/FBSL/anagrams-3.fbsl @@ -0,0 +1,8 @@ +{ + { "abel" "able" "bale" "bela" "elba" } + { "caret" "carte" "cater" "crate" "trace" } + { "angel" "angle" "galen" "glean" "lange" } + { "alger" "glare" "lager" "large" "regal" } + { "elan" "lane" "lean" "lena" "neal" } + { "evil" "levi" "live" "veil" "vile" } +} diff --git a/Task/Anagrams/OCaml/anagrams.ocaml b/Task/Anagrams/OCaml/anagrams.ocaml index 8275d822b2..7cfd4217c5 100644 --- a/Task/Anagrams/OCaml/anagrams.ocaml +++ b/Task/Anagrams/OCaml/anagrams.ocaml @@ -1,14 +1,14 @@ let explode str = let l = ref [] in - let len = String.length str in - for i = len - 1 downto 0 do + let n = String.length str in + for i = n - 1 downto 0 do l := str.[i] :: !l done; (!l) let implode li = - let len = List.length li in - let s = String.create len in + let n = List.length li in + let s = String.create n in let i = ref 0 in List.iter (fun c -> s.[!i] <- c; incr i) li; (s) @@ -18,7 +18,7 @@ let () = let ic = open_in "unixdict.txt" in try while true do let w = input_line ic in - let k = implode(List.sort compare (explode w)) in + let k = implode (List.sort compare (explode w)) in let l = try Hashtbl.find h k with Not_found -> [] @@ -29,6 +29,5 @@ let () = Hashtbl.iter (fun _ lw -> if List.length lw >= n then ( List.iter (Printf.printf " %s") lw; - print_newline()) - ) h; -;; + print_newline () ) + ) h diff --git a/Task/Anagrams/Racket/anagrams.rkt b/Task/Anagrams/Racket/anagrams.rkt new file mode 100644 index 0000000000..b6a10447e4 --- /dev/null +++ b/Task/Anagrams/Racket/anagrams.rkt @@ -0,0 +1,21 @@ +#lang racket + +(require net/url) + +(define (get-lines url-string) + (define port (get-pure-port (string->url url-string))) + (for/list ([l (in-lines port)]) l)) + +(define (hash-words words) + (for/fold ([ws-hash (hash)]) ([w words]) + (hash-update ws-hash + (list->string (sort (string->list w) < #:key (λ (c) (char->integer c)))) + (λ (ws) (cons w ws)) + (λ () '())))) + +(define (get-maxes h) + (define max-ws (apply max (map length (hash-values h)))) + (define max-keys (filter (λ (k) (= (length (hash-ref h k)) max-ws)) (hash-keys h))) + (map (λ (k) (hash-ref h k)) max-keys)) + +(get-maxes (hash-words (get-lines "http://www.puzzlers.org/pub/wordlists/unixdict.txt"))) diff --git a/Task/Anagrams/Seed7/anagrams.seed7 b/Task/Anagrams/Seed7/anagrams.seed7 new file mode 100644 index 0000000000..b9083d0fb8 --- /dev/null +++ b/Task/Anagrams/Seed7/anagrams.seed7 @@ -0,0 +1,56 @@ +$ include "seed7_05.s7i"; + include "gethttp.s7i"; + include "strifile.s7i"; + +const type: anagramHash is hash [string] array string; + +const func string: sort (in string: stri) is func + result + var string: sortedStri is ""; + local + var integer: i is 0; + var integer: j is 0; + var char: ch is ' '; + begin + sortedStri := stri; + for i range 1 to length(sortedStri) do + for j range succ(i) to length(sortedStri) do + if sortedStri[i] > sortedStri[j] then + ch := sortedStri[i]; + sortedStri @:= [i] sortedStri[j]; + sortedStri @:= [j] ch; + end if; + end for; + end for; + end func; + +const proc: main is func + local + var file: dictFile is STD_NULL; + var string: word is ""; + var string: sortedLetters is ""; + var anagramHash: anagrams is anagramHash.value; + var integer: length is 0; + var integer: maxLength is 0; + begin + dictFile := openStrifile(getHttp("www.puzzlers.org/pub/wordlists/unixdict.txt")); + while hasNext(dictFile) do + readln(dictFile, word); + sortedLetters := sort(word); + if sortedLetters in anagrams then + anagrams[sortedLetters] &:= word; + else + anagrams @:= [sortedLetters] [] (word); + end if; + length := length(anagrams[sortedLetters]); + if length > maxLength then + maxLength := length; + end if; + end while; + close(dictFile); + for sortedLetters range sort(keys(anagrams)) do + if length(anagrams[sortedLetters]) = maxLength then + writeln(join(anagrams[sortedLetters], ", ")); + end if; + end for; + end func; diff --git a/Task/Animate-a-pendulum/FBSL/animate-a-pendulum.fbsl b/Task/Animate-a-pendulum/FBSL/animate-a-pendulum.fbsl new file mode 100644 index 0000000000..48482b9f16 --- /dev/null +++ b/Task/Animate-a-pendulum/FBSL/animate-a-pendulum.fbsl @@ -0,0 +1,57 @@ +#INCLUDE + +FBSLSETTEXT(ME, "Pendulum") +FBSL.SETTIMER(ME, 1000, 10) +RESIZE(ME, 0, 0, 300, 200) +CENTER(ME) +SHOW(ME) + +BEGIN EVENTS + SELECT CASE CBMSG + CASE WM_TIMER + ' Request redraw + InvalidateRect(ME, NULL, FALSE) + RETURN 0 + CASE WM_PAINT + Swing() + CASE WM_CLOSE + FBSL.KILLTIMER(ME, 1000) + END SELECT +END EVENTS + +SUB Swing() + TYPE RECT: %rcLeft, %rcTop, %rcRight, %rcBottom: END TYPE + STATIC rc AS RECT, !!acceleration, !!velocity, !!angle = M_PI_2, %pendulum = 100 + + GetClientRect(ME, @rc) + + ' Recalculate + DIM headX = rc.rcRight / 2, headY = rc.rcBottom / 4 + DIM tailX = headX + SIN(angle) * pendulum + DIM tailY = headY + COS(angle) * pendulum + + acceleration = -9.81 / pendulum * SIN(angle) + INCR(velocity, acceleration * 0.1)(angle, velocity * 0.1) + + ' Create backbuffer + CreateCompatibleDC(GetDC(ME)) + SelectObject(CreateCompatibleDC, CreateCompatibleBitmap(GetDC, rc.rcRight, rc.rcBottom)) + + ' Draw to backbuffer + FILLSTYLE(FILL_SOLID): FILLCOLOR(RGB(200, 200, 0)) + LINE(CreateCompatibleDC, 0, 0, rc.rcRight, rc.rcBottom, GetSysColor(COLOR_BTNHILIGHT), TRUE, TRUE) + LINE(CreateCompatibleDC, 0, headY, rc.rcRight, headY, GetSysColor(COLOR_3DSHADOW)) + DRAWWIDTH(3) + LINE(CreateCompatibleDC, headX, headY, tailX, tailY, RGB(200, 0, 0)) + DRAWWIDTH(1) + CIRCLE(CreateCompatibleDC, headX, headY, 2, GetSysColor, 0, 360, 1, TRUE) + CIRCLE(CreateCompatibleDC, tailX, tailY, 10, GetSysColor, 0, 360, 1, FALSE) + + ' Blit to window + BitBlt(GetDC, 0, 0, rc.rcRight, rc.rcBottom, CreateCompatibleDC, 0, 0, SRCCOPY) + ReleaseDC(ME, GetDC) + + ' Delete backbuffer + DeleteObject(SelectObject(CreateCompatibleDC, SelectObject)) + DeleteDC(CreateCompatibleDC) +END SUB diff --git a/Task/Animate-a-pendulum/Racket/animate-a-pendulum.rkt b/Task/Animate-a-pendulum/Racket/animate-a-pendulum.rkt index 9db707cf40..b19272bd38 100644 --- a/Task/Animate-a-pendulum/Racket/animate-a-pendulum.rkt +++ b/Task/Animate-a-pendulum/Racket/animate-a-pendulum.rkt @@ -1,7 +1,6 @@ #lang racket -(require 2htdp/image - 2htdp/universe) +(require 2htdp/image 2htdp/universe) (define (pendulum) (define (accel θ) (- (sin θ))) diff --git a/Task/Animation/FBSL/animation.fbsl b/Task/Animation/FBSL/animation.fbsl new file mode 100644 index 0000000000..4a6764f1fa --- /dev/null +++ b/Task/Animation/FBSL/animation.fbsl @@ -0,0 +1,30 @@ +#INCLUDE + +FBSLSETTEXT(ME, "Hello world! ") +RESIZE(ME, 0, 0, 220, 0) +CENTER(ME) +SHOW(ME) +SetTimer(ME, 1000, 100, NULL) + +BEGIN EVENTS + STATIC bForward AS BOOLEAN = TRUE + IF CBMSG = WM_TIMER THEN + Marquee(bForward) + RETURN 0 + ELSEIF CBMSG = WM_NCLBUTTONDOWN THEN + IF CBWPARAM = HTCAPTION THEN bForward = NOT bForward + ELSEIF CBMSG = WM_CLOSE THEN + KillTimer(ME, 1000) + END IF +END EVENTS + +SUB Marquee(BYVAL forward AS BOOLEAN) + STATIC caption AS STRING = FBSLGETTEXT(ME) + STATIC length AS INTEGER = STRLEN(caption) + IF forward THEN + caption = RIGHT(caption, 1) & LEFT(caption, length - 1) + ELSE + caption = MID(caption, 2) & LEFT(caption, 1) + END IF + FBSLSETTEXT(ME, caption) +END SUB diff --git a/Task/Anonymous-recursion/C++/anonymous-recursion-1.cpp b/Task/Anonymous-recursion/C++/anonymous-recursion-1.cpp index c04d0fc664..0844d395f8 100644 --- a/Task/Anonymous-recursion/C++/anonymous-recursion-1.cpp +++ b/Task/Anonymous-recursion/C++/anonymous-recursion-1.cpp @@ -1,4 +1,4 @@ -double fib(const double n) +double fib(double n) { if(n < 0) { @@ -6,10 +6,9 @@ double fib(const double n) } else { - class actual_fib + struct actual_fib { - public: - static double calc(const double n) + static double calc(double n) { if(n < 2) { diff --git a/Task/Anonymous-recursion/C++/anonymous-recursion-3.cpp b/Task/Anonymous-recursion/C++/anonymous-recursion-3.cpp new file mode 100644 index 0000000000..2c6cead305 --- /dev/null +++ b/Task/Anonymous-recursion/C++/anonymous-recursion-3.cpp @@ -0,0 +1,26 @@ +double fib(double n) +{ + if(n < 0) + { + throw "Invalid argument passed to fib"; + } + else + { + struct actual_fib + { + double operator()(double n) + { + if(n < 2) + { + return n; + } + else + { + return (*this)(n-1) + (*this)(n-2); + } + } + }; + + return actual_fib()(n); + } +} diff --git a/Task/Anonymous-recursion/Erlang/anonymous-recursion.erl b/Task/Anonymous-recursion/Erlang/anonymous-recursion.erl new file mode 100644 index 0000000000..a0795ae9ff --- /dev/null +++ b/Task/Anonymous-recursion/Erlang/anonymous-recursion.erl @@ -0,0 +1,15 @@ +-module( anonymous_recursion ). +-export( [fib/1, fib_internal/1] ). + +fib( N ) when N >= 0 -> + fib( N, 1, 0 ). + +fib_internal( N ) when N >= 0 -> + Fun = fun (_F, 0, _Next, Acc ) -> Acc; + (F, N, Next, Acc) -> F( F, N - 1, Acc+Next, Next ) + end, + Fun( Fun, N, 1, 0 ). + + +fib( 0, _Next, Acc ) -> Acc; +fib( N, Next, Acc ) -> fib( N - 1, Acc+Next, Next ). diff --git a/Task/Anonymous-recursion/FBSL/anonymous-recursion.fbsl b/Task/Anonymous-recursion/FBSL/anonymous-recursion.fbsl new file mode 100644 index 0000000000..f9a58fb7d5 --- /dev/null +++ b/Task/Anonymous-recursion/FBSL/anonymous-recursion.fbsl @@ -0,0 +1,22 @@ +#APPTYPE CONSOLE + +FUNCTION Fibonacci(n) + IF n < 0 THEN + RETURN "Nuts!" + ELSE + RETURN Fib(n) + END IF + FUNCTION Fib(m) + IF m < 2 THEN + Fib = m + ELSE + Fib = Fib(m - 1) + Fib(m - 2) + END IF + END FUNCTION +END FUNCTION + +PRINT Fibonacci(-1.5) +PRINT Fibonacci(1.5) +PRINT Fibonacci(13.666) + +PAUSE diff --git a/Task/Anonymous-recursion/Java/anonymous-recursion-2.java b/Task/Anonymous-recursion/Java/anonymous-recursion-2.java index 1e517400d1..d3a05115ac 100644 --- a/Task/Anonymous-recursion/Java/anonymous-recursion-2.java +++ b/Task/Anonymous-recursion/Java/anonymous-recursion-2.java @@ -6,18 +6,18 @@ interface SelfApplicable { } class Utils { - public static SelfApplicable, Function>, Function>> y(Class input, Class output) { + public static SelfApplicable, Function>, Function>> y() { 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 Function, Function>, Function> fix() { + return Utils.y().apply(Utils.y()); } public static long fib(int m) { if (m < 0) throw new IllegalArgumentException("n can not be a negative number"); - return fix(Integer.class, Long.class).apply( + return Utils.fix().apply( f -> n -> (n < 2) ? n : (f.apply(n - 1) + f.apply(n - 2)) ).apply(m); } diff --git a/Task/Anonymous-recursion/PHP/anonymous-recursion-3.php b/Task/Anonymous-recursion/PHP/anonymous-recursion-3.php new file mode 100644 index 0000000000..143268f7bc --- /dev/null +++ b/Task/Anonymous-recursion/PHP/anonymous-recursion-3.php @@ -0,0 +1,18 @@ + diff --git a/Task/Anonymous-recursion/Python/anonymous-recursion-2.py b/Task/Anonymous-recursion/Python/anonymous-recursion-2.py index a484e767df..eba1e1c0fa 100644 --- a/Task/Anonymous-recursion/Python/anonymous-recursion-2.py +++ b/Task/Anonymous-recursion/Python/anonymous-recursion-2.py @@ -1,4 +1,5 @@ ->>> Y = lambda f: (lambda x: x(x))(lambda y: lambda *args: f(y(y), *args)) +>>>from functools import partial +>>> Y = lambda f: (lambda x: x(x))(lambda y: partial(f, lambda *args: y(y)(*args))) >>> fib = lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Anonymous-recursion/Racket/anonymous-recursion-3.rkt b/Task/Anonymous-recursion/Racket/anonymous-recursion-3.rkt new file mode 100644 index 0000000000..cc6b1113a6 --- /dev/null +++ b/Task/Anonymous-recursion/Racket/anonymous-recursion-3.rkt @@ -0,0 +1,14 @@ +#lang racket +;; We use Z combinator (applicative order fixed-point operator) +(define Z + (λ (f) + ((λ (x) (f (λ (g) ((x x) g)))) + (λ (x) (f (λ (g) ((x x) g))))))) + +(define fibonacci + (Z (λ (fibo) + (λ (n) + (if (<= n 2) + 1 + (+ (fibo (- n 1)) + (fibo (- n 2)))))))) diff --git a/Task/Apply-a-callback-to-an-array/C++/apply-a-callback-to-an-array-5.cpp b/Task/Apply-a-callback-to-an-array/C++/apply-a-callback-to-an-array-5.cpp index dc4b996099..4367c64fab 100644 --- a/Task/Apply-a-callback-to-an-array/C++/apply-a-callback-to-an-array-5.cpp +++ b/Task/Apply-a-callback-to-an-array/C++/apply-a-callback-to-an-array-5.cpp @@ -3,13 +3,13 @@ #include #include -int main( ) { - std::vector< int > intVec( 10 ) ; - std::iota( intVec.begin( ) , intVec.end( ) , 1 ) ;//fill the vector - std::transform( intVec.begin( ) , intVec.end( ) , intVec.begin( ) , - [ ] ( int i ) { return i * i ; } ) ; //transform it with closures - std::copy( intVec.begin( ) , intVec.end( ) , - std::ostream_iterator ( std::cout , " " ) ) ; - std::cout << std::endl ; - return 0 ; +int main() { + std::vector intVec(10); + std::iota(std::begin(intVec), std::end(intVec), 1 ); // Fill the vector + std::transform(std::begin(intVec) , std::end(intVec), std::begin(intVec), + [](int i) { return i * i ; } ); // Transform it with closures + std::copy(std::begin(intVec), end(intVec) , + std::ostream_iterator(std::cout, " ")); + std::cout << std::endl; + return 0; } diff --git a/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol b/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol new file mode 100644 index 0000000000..6f5c473b5e --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol @@ -0,0 +1,23 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Map. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Table-Size CONSTANT 30. + + LOCAL-STORAGE SECTION. + 01 I USAGE UNSIGNED-INT. + + LINKAGE SECTION. + 01 Table-Param. + 03 Table-Values USAGE COMP-2 OCCURS Table-Size TIMES. + + 01 Func-Id PIC X(30). + + PROCEDURE DIVISION USING Table-Param Func-Id. + PERFORM VARYING I FROM 1 BY 1 UNTIL Table-Size < I + CALL Func-Id USING BY REFERENCE Table-Values (I) + END-PERFORM + + GOBACK + . diff --git a/Task/Apply-a-callback-to-an-array/FBSL/apply-a-callback-to-an-array-1.fbsl b/Task/Apply-a-callback-to-an-array/FBSL/apply-a-callback-to-an-array-1.fbsl new file mode 100644 index 0000000000..1db21b6785 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/FBSL/apply-a-callback-to-an-array-1.fbsl @@ -0,0 +1,17 @@ +#APPTYPE CONSOLE + +FOREACH DIM e IN MyMap(Add42, {1, 2, 3}) + PRINT e, " "; +NEXT + +PAUSE + +FUNCTION MyMap(f, a) + DIM ret[] + FOREACH DIM e IN a + ret[] = f(e) + NEXT + RETURN ret +END FUNCTION + +FUNCTION Add42(n): RETURN n + 42: END FUNCTION diff --git a/Task/Apply-a-callback-to-an-array/FBSL/apply-a-callback-to-an-array-2.fbsl b/Task/Apply-a-callback-to-an-array/FBSL/apply-a-callback-to-an-array-2.fbsl new file mode 100644 index 0000000000..5a9e2c2171 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/FBSL/apply-a-callback-to-an-array-2.fbsl @@ -0,0 +1,17 @@ +#APPTYPE CONSOLE + +DIM languages[] = {{"English", {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}}, _ + {"French", {"un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf", "dix"}}} + +MAP(SpeakALanguage, languages) + +PAUSE + +SUB NameANumber(lang, nb, number) + PRINT "The number ", nb, " is called ", STRENC(number), " in ", lang +END SUB + +SUB SpeakALanguage(lang) + MAP(NameANumber, lang[0], 1 TO 10, lang[1]) + PRINT LPAD("", 40, "-") +END SUB diff --git a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia new file mode 100644 index 0000000000..f53b19a706 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia @@ -0,0 +1,22 @@ +numbers = [1, 3, 5, 7] + +square1 = [square(n) for n in numbers] # list comprehension + +squares2a = map(square, numbers) # functional form + +squares2b = map(x -> x*x, numbers) # functional form with `lambda` + +#There is also extended block form for the map function +squares2c = map(numbers) do x + sum = 0 + for i = 1:x + sum += x^2 #trivial, but you get the point + end + return sum +end + +squares3 = [n * n for n in numbers] # no need for a function, + +squares4 = numbers .* numbers #element-wise operation + +squares4a = numbers .^ 2 #includes .+, .-, ./, comparison, and bitwise operations as well diff --git a/Task/Apply-a-callback-to-an-array/Racket/apply-a-callback-to-an-array.rkt b/Task/Apply-a-callback-to-an-array/Racket/apply-a-callback-to-an-array.rkt index 14d0d0b3b4..f4df11366c 100644 --- a/Task/Apply-a-callback-to-an-array/Racket/apply-a-callback-to-an-array.rkt +++ b/Task/Apply-a-callback-to-an-array/Racket/apply-a-callback-to-an-array.rkt @@ -1,7 +1,7 @@ #lang racket -;; using the `for/vector` comprehension form +;; using the `for/vector' comprehension form (for/vector ([i #(1 2 3 4 5)]) (sqr i)) -;; the usual functional `map` +;; the usual functional `map' (vector-map sqr #(1 2 3 4 5)) diff --git a/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia b/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia index 902ae23e88..f88b442618 100644 --- a/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia +++ b/Task/Arbitrary-precision-integers--included-/Julia/arbitrary-precision-integers--included-.julia @@ -1,5 +1,5 @@ julia> @elapsed big = string(BigInt(5)^4^3^2) -0.06799983978271484 seconds +0.017507363 julia> length(big) 183231 diff --git a/Task/Arena-storage-pool/Erlang/arena-storage-pool.erl b/Task/Arena-storage-pool/Erlang/arena-storage-pool.erl new file mode 100644 index 0000000000..aa6c26f361 --- /dev/null +++ b/Task/Arena-storage-pool/Erlang/arena-storage-pool.erl @@ -0,0 +1,30 @@ +-module( arena_storage_pool ). + +-export( [task/0] ). + +task() -> + Pid = erlang:spawn_opt( fun() -> loop([]) end, [{min_heap_size, 10000}] ), + set( Pid, 1, ett ), + set( Pid, "kalle", "hobbe" ), + V1 = get( Pid, 1 ), + V2 = get( Pid, "kalle" ), + true = (V1 =:= ett) and (V2 =:= "hobbe"), + erlang:exit( Pid, normal ). + + + +get( Pid, Key ) -> + Pid ! {get, Key, erlang:self()}, + receive + {value, Value, Pid} -> Value + end. + +loop( List ) -> + receive + {set, Key, Value} -> loop( [{Key, Value} | proplists:delete(Key, List)] ); + {get, Key, Pid} -> + Pid ! {value, proplists:get_value(Key, List), erlang:self()}, + loop( List ) + end. + +set( Pid, Key, Value ) -> Pid ! {set, Key, Value}. diff --git a/Task/Arena-storage-pool/Racket/arena-storage-pool.rkt b/Task/Arena-storage-pool/Racket/arena-storage-pool.rkt new file mode 100644 index 0000000000..66e23907c6 --- /dev/null +++ b/Task/Arena-storage-pool/Racket/arena-storage-pool.rkt @@ -0,0 +1,9 @@ +(malloc 1000 'raw) ; raw allocation, bypass the GC, requires free()-ing +(malloc 1000 'uncollectable) ; no GC, for use with other GCs that Racket can be configured with +(malloc 1000 'atomic) ; a block of memory without internal pointers +(malloc 1000 'nonatomic) ; a block of pointers +(malloc 1000 'eternal) ; uncollectable & atomic, similar to raw malloc but no freeing +(malloc 1000 'stubborn) ; can be declared immutable when mutation is done +(malloc 1000 'interior) ; allocate an immovable block with possible pointers into it +(malloc 1000 'atomic-interior) ; same for atomic chunks +(malloc-immobile-cell v) ; allocates a single cell that the GC will not move diff --git a/Task/Arithmetic-Integer/Erlang/arithmetic-integer.erl b/Task/Arithmetic-Integer/Erlang/arithmetic-integer.erl new file mode 100644 index 0000000000..aa376dd853 --- /dev/null +++ b/Task/Arithmetic-Integer/Erlang/arithmetic-integer.erl @@ -0,0 +1,14 @@ +% Implemented by Arjun Sunel +-module(arith). +-export([start/0]). + +start() -> + case io:fread("","~d~d") of + {ok, [A,B]} -> + io:format("Sum = ~w~n",[A+B]), + io:format("Difference = ~w~n",[A-B]), + io:format("Product = ~w~n",[A*B]), + io:format("Quotient = ~w~n",[A div B]), % truncates towards zero + io:format("Remainder= ~w~n",[A rem B]), % same sign as the first operand + halt() + end. diff --git a/Task/Arithmetic-Integer/Perl-6/arithmetic-integer.pl6 b/Task/Arithmetic-Integer/Perl-6/arithmetic-integer.pl6 index b01650c1ef..2695a6a00a 100644 --- a/Task/Arithmetic-Integer/Perl-6/arithmetic-integer.pl6 +++ b/Task/Arithmetic-Integer/Perl-6/arithmetic-integer.pl6 @@ -1,5 +1,5 @@ -my Int $a = floor $*IN.get; -my Int $b = floor $*IN.get; +my Int $a = get.floor; +my Int $b = get.floor; say 'sum: ', $a + $b; say 'difference: ', $a - $b; diff --git a/Task/Arithmetic-Rational/Racket/arithmetic-rational.rkt b/Task/Arithmetic-Rational/Racket/arithmetic-rational.rkt new file mode 100644 index 0000000000..c9021ebe8c --- /dev/null +++ b/Task/Arithmetic-Rational/Racket/arithmetic-rational.rkt @@ -0,0 +1,2 @@ +-> (* 1/7 14) +2 diff --git a/Task/Arithmetic-Rational/Seed7/arithmetic-rational.seed7 b/Task/Arithmetic-Rational/Seed7/arithmetic-rational.seed7 new file mode 100644 index 0000000000..8eeb96a144 --- /dev/null +++ b/Task/Arithmetic-Rational/Seed7/arithmetic-rational.seed7 @@ -0,0 +1,29 @@ +$ include "seed7_05.s7i"; + include "rational.s7i"; + +const func boolean: isPerfect (in integer: candidate) is func + result + var boolean: isPerfect is FALSE; + local + var integer: divisor is 0; + var rational: sum is rational.value; + begin + sum := 1 / candidate; + for divisor range 2 to sqrt(candidate) do + if candidate mod divisor = 0 then + sum +:= 1 / divisor + 1 / (candidate div divisor); + end if; + end for; + isPerfect := sum = rat(1); + end func; + +const proc: main is func + local + var integer: candidate is 0; + begin + for candidate range 2 to 2 ** 19 - 1 do + if isPerfect(candidate) then + writeln(candidate <& " is perfect"); + end if; + end for; + end func; diff --git a/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx b/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx index 925d8abc9e..a710022e93 100644 --- a/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx +++ b/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx @@ -15,7 +15,7 @@ j=0; do forever; j=j+1; if j>L then leave; _=substr(x,j,1); _2=getX() z=z _ $; iterate end if _=='+' | _=="-" then do; p_=word(z,words(z)) /*last Z token*/ - if p_=='(' then z=z 0 /handle unary ±*/ + if p_=='(' then z=z 0 /*handle unary±*/ z=z _ $; iterate end lets=0; sigs=0; #=_ @@ -27,7 +27,7 @@ j=0; do forever; j=j+1; if j>L then leave; _=substr(x,j,1); _2=getX() end /*exp*/ if pos(_,nchars)==0 then leave lets=lets+datatype(_,'M') /*keep track of # of exponents. */ - #=# || translate(_,'EEEEE','eDdQq') /*keep buildingthe num.*/ + #=# || translate(_,'EEEEE','eDdQq') /*keep building the num*/ end /*j*/ j=j-1 if \datatype(#,'N') then call serr 'invalid number: ' # diff --git a/Task/Arithmetic-evaluation/Racket/arithmetic-evaluation.rkt b/Task/Arithmetic-evaluation/Racket/arithmetic-evaluation.rkt new file mode 100644 index 0000000000..64c2518055 --- /dev/null +++ b/Task/Arithmetic-evaluation/Racket/arithmetic-evaluation.rkt @@ -0,0 +1,35 @@ +#lang racket + +(require parser-tools/yacc parser-tools/lex + (prefix-in ~ parser-tools/lex-sre)) + +(define-tokens value-tokens (NUM)) +(define-empty-tokens op-tokens (OPEN CLOSE + - * / EOF NEG)) + +(define lex + (lexer [(eof) 'EOF] + [whitespace (lex input-port)] + [(~or "+" "-" "*" "/") (string->symbol lexeme)] + ["(" 'OPEN] + [")" 'CLOSE] + [(~: (~+ numeric) (~? #\. (~* numeric))) + (token-NUM (string->number lexeme))])) + +(define parse + (parser [start E] [end EOF] + [tokens value-tokens op-tokens] + [error void] + [precs (left - +) (left * /) (left NEG)] + [grammar (E [(NUM) $1] + [(E + E) (+ $1 $3)] + [(E - E) (- $1 $3)] + [(E * E) (* $1 $3)] + [(E / E) (/ $1 $3)] + [(- E) (prec NEG) (- $2)] + [(OPEN E CLOSE) $2])])) + +(define (calc str) + (define i (open-input-string str)) + (displayln (parse (λ() (lex i))))) + +(calc "(1 + 2 * 3) - (1+2)*-3") diff --git a/Task/Arithmetic-geometric-mean/Forth/arithmetic-geometric-mean.fth b/Task/Arithmetic-geometric-mean/Forth/arithmetic-geometric-mean.fth new file mode 100644 index 0000000000..d3242c572f --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Forth/arithmetic-geometric-mean.fth @@ -0,0 +1,9 @@ +: agm ( a g -- m ) + begin + fover fover f+ 2e f/ + frot frot f* fsqrt + fover fover 1e-15 f~ + until + fdrop ; + +1e 2e -0.5e f** agm f. \ 0.847213084793979 diff --git a/Task/Arithmetic-geometric-mean/Logo/arithmetic-geometric-mean.logo b/Task/Arithmetic-geometric-mean/Logo/arithmetic-geometric-mean.logo new file mode 100644 index 0000000000..6c8ef1685b --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Logo/arithmetic-geometric-mean.logo @@ -0,0 +1,9 @@ +to about :a :b + output and [:a - :b < 1e-15] [:a - :b > -1e-15] +end +to agm :arith :geom + if about :arith :geom [output :arith] + output agm (:arith + :geom)/2 sqrt (:arith * :geom) +end + +show agm 1 1/sqrt 2 diff --git a/Task/Arithmetic-geometric-mean/Objeck/arithmetic-geometric-mean.objeck b/Task/Arithmetic-geometric-mean/Objeck/arithmetic-geometric-mean.objeck new file mode 100644 index 0000000000..4401c7730c --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Objeck/arithmetic-geometric-mean.objeck @@ -0,0 +1,16 @@ +class ArithmeticMean { + function : Amg(a : Float, g : Float) ~ Nil { + a1 := a; + g1 := g; + while((a1-g1)->Abs() >= Float->Power(10, -14)) { + tmp := (a1+g1)/2.0; + g1 := Float->SquareRoot(a1*g1); + a1 := tmp; + }; + a1->PrintLine(); + } + + function : Main(args : String[]) ~ Nil { + Amg(1,1/Float->SquareRoot(2)); + } +} diff --git a/Task/Arithmetic-geometric-mean/Raven/arithmetic-geometric-mean.raven b/Task/Arithmetic-geometric-mean/Raven/arithmetic-geometric-mean.raven new file mode 100644 index 0000000000..8fe1166c08 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Raven/arithmetic-geometric-mean.raven @@ -0,0 +1,12 @@ +define agm use $a, $g, $errlim + # $errlim $g $a "%d %g %d\n" print + $a 1.0 + as $t + repeat $a 1.0 * $g - abs -15 exp10 $a * > while + $a $g + 2 / as $t + $a $g * sqrt as $g + $t as $a + $g $a $t "t: %g a: %g g: %g\n" print + $a + + +16 1 2 sqrt / 1 agm "agm: %.15g\n" print diff --git a/Task/Arithmetic-geometric-mean/Seed7/arithmetic-geometric-mean.seed7 b/Task/Arithmetic-geometric-mean/Seed7/arithmetic-geometric-mean.seed7 new file mode 100644 index 0000000000..9e913dbcc9 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Seed7/arithmetic-geometric-mean.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + +const func float: agm (in var float: a, in var float: g) is func + result + var float: agm is 0.0; + local + const float: iota is 1.0E-7; + var float: a1 is 0.0; + var float: g1 is 0.0; + begin + if a * g < 0.0 then + raise RANGE_ERROR; + else + while abs(a - g) > iota do + a1 := (a + g) / 2.0; + g1 := sqrt(a * g); + a := a1; + g := g1; + end while; + agm := a; + end if; + end func; + +const proc: main is func + begin + writeln(agm(1.0, 2.0) digits 6); + writeln(agm(1.0, 1.0 / sqrt(2.0)) digits 6); + end func; diff --git a/Task/Array-concatenation/C++/array-concatenation-1.cpp b/Task/Array-concatenation/C++/array-concatenation-1.cpp new file mode 100644 index 0000000000..1dea6457b5 --- /dev/null +++ b/Task/Array-concatenation/C++/array-concatenation-1.cpp @@ -0,0 +1,14 @@ +#include +#include + +int main() +{ + std::vector a(3), b(4); + a[0] = 11; a[1] = 12; a[2] = 13; + b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24; + + a.insert(a.end(), b.begin(), b.end()); + + for (int i = 0; i < a.size(); ++i) + std::cout << "a[" << i << "] = " << a[i] << "\n"; +} diff --git a/Task/Array-concatenation/C++/array-concatenation-2.cpp b/Task/Array-concatenation/C++/array-concatenation-2.cpp new file mode 100644 index 0000000000..13c7db203f --- /dev/null +++ b/Task/Array-concatenation/C++/array-concatenation-2.cpp @@ -0,0 +1,13 @@ +#include +#include + +int main() { + std::vector a {1, 2, 3, 4}; + std::vector b {5, 6, 7, 8, 9}; + + a.insert(a.end(), b.begin(), b.end()); + + for(int& i: a) std::cout << i << " "; + std::cout << std::endl; + return 0; +} diff --git a/Task/Array-concatenation/FBSL/array-concatenation.fbsl b/Task/Array-concatenation/FBSL/array-concatenation.fbsl new file mode 100644 index 0000000000..28e14530f1 --- /dev/null +++ b/Task/Array-concatenation/FBSL/array-concatenation.fbsl @@ -0,0 +1,9 @@ +#APPTYPE CONSOLE + +DIM aint[] ={1, 2, 3}, astr[] ={"one", "two", "three"}, asng[] ={!1, !2, !3} + +FOREACH DIM e IN ARRAYMERGE(aint, astr, asng) + PRINT e, " "; +NEXT + +PAUSE diff --git a/Task/Array-concatenation/Julia/array-concatenation.julia b/Task/Array-concatenation/Julia/array-concatenation.julia index edd741fcf0..b7aa341da9 100644 --- a/Task/Array-concatenation/Julia/array-concatenation.julia +++ b/Task/Array-concatenation/Julia/array-concatenation.julia @@ -1,5 +1,9 @@ a = [1,2,3] b = [4,5,6] ab = [a,b] -#alternative +# the above bracket notation simply generates a call to vcat ab = vcat(a,b) +# hcat is short for `horizontal concatenation` +ab = hcat(a,b) #ab -> 3x2 matrix +# the append!(a,b) method is mutating, appending `b` to `a` +append!(a,b) # a now equals [1,2,3,4,5,6] diff --git a/Task/Arrays/Aime/arrays-1.aime b/Task/Arrays/Aime/arrays-1.aime new file mode 100644 index 0000000000..104f2e6d66 --- /dev/null +++ b/Task/Arrays/Aime/arrays-1.aime @@ -0,0 +1 @@ +list l; diff --git a/Task/Arrays/Aime/arrays-2.aime b/Task/Arrays/Aime/arrays-2.aime new file mode 100644 index 0000000000..6e4b48d959 --- /dev/null +++ b/Task/Arrays/Aime/arrays-2.aime @@ -0,0 +1,3 @@ +l_append(l, 3); +l_append(l, "arrays"); +l_append(l, pow); diff --git a/Task/Arrays/Aime/arrays-3.aime b/Task/Arrays/Aime/arrays-3.aime new file mode 100644 index 0000000000..fb7e555bbc --- /dev/null +++ b/Task/Arrays/Aime/arrays-3.aime @@ -0,0 +1,2 @@ +l_push(l, 3, .5); +l_push(l, 4, __type(l)); diff --git a/Task/Arrays/Aime/arrays-4.aime b/Task/Arrays/Aime/arrays-4.aime new file mode 100644 index 0000000000..a673173cf4 --- /dev/null +++ b/Task/Arrays/Aime/arrays-4.aime @@ -0,0 +1,2 @@ +l_p_integer(l, 5, -1024); +l_p_real(l, 6, 88); diff --git a/Task/Arrays/Aime/arrays-5.aime b/Task/Arrays/Aime/arrays-5.aime new file mode 100644 index 0000000000..16e3e913c9 --- /dev/null +++ b/Task/Arrays/Aime/arrays-5.aime @@ -0,0 +1 @@ +l_query(l, 5); diff --git a/Task/Arrays/Aime/arrays-6.aime b/Task/Arrays/Aime/arrays-6.aime new file mode 100644 index 0000000000..25c3f5e838 --- /dev/null +++ b/Task/Arrays/Aime/arrays-6.aime @@ -0,0 +1,2 @@ +l_q_real(l, 6); +l_q_text(l, 1); diff --git a/Task/Arrays/C++/arrays-1.cpp b/Task/Arrays/C++/arrays-1.cpp index daf8076357..5170b61377 100644 --- a/Task/Arrays/C++/arrays-1.cpp +++ b/Task/Arrays/C++/arrays-1.cpp @@ -1,4 +1,16 @@ - // Qt - QVector myArray4(10); - myArray4.push_back(1); - myArray4.push_back(2); +#include +#include +#include + +int main() { + std::array words = {"One", "Four", "Eight"}; + words[2] = "Three"; + words.at(1) = "Two"; + + std::reverse(words.begin(), words.end()); + + for(auto& word: words) std::cout << word << " "; + std::cout << std::endl; + + return 0; +} diff --git a/Task/Arrays/C++/arrays-2.cpp b/Task/Arrays/C++/arrays-2.cpp index 27f88be34e..daf8076357 100644 --- a/Task/Arrays/C++/arrays-2.cpp +++ b/Task/Arrays/C++/arrays-2.cpp @@ -1,4 +1,4 @@ - // MFC - CArray myArray5(10); - myArray5.Add(1); - myArray5.Add(2); + // Qt + QVector myArray4(10); + myArray4.push_back(1); + myArray4.push_back(2); diff --git a/Task/Arrays/C++/arrays-3.cpp b/Task/Arrays/C++/arrays-3.cpp index 6c52abd0c0..27f88be34e 100644 --- a/Task/Arrays/C++/arrays-3.cpp +++ b/Task/Arrays/C++/arrays-3.cpp @@ -1,6 +1,4 @@ -int myArray[2]; - -myArray[0] = 1; -myArray[1] = 3; - -cout << myArray[1] << endl; + // MFC + CArray myArray5(10); + myArray5.Add(1); + myArray5.Add(2); diff --git a/Task/Arrays/C++/arrays-4.cpp b/Task/Arrays/C++/arrays-4.cpp index 41d3fd046a..6c52abd0c0 100644 --- a/Task/Arrays/C++/arrays-4.cpp +++ b/Task/Arrays/C++/arrays-4.cpp @@ -1,7 +1,6 @@ -int* myArray = new int[10]; +int myArray[2]; myArray[0] = 1; myArray[1] = 3; cout << myArray[1] << endl; -delete [] myArray; diff --git a/Task/Arrays/C++/arrays-5.cpp b/Task/Arrays/C++/arrays-5.cpp index b5119b9644..41d3fd046a 100644 --- a/Task/Arrays/C++/arrays-5.cpp +++ b/Task/Arrays/C++/arrays-5.cpp @@ -1,8 +1,7 @@ -vector myArray2; +int* myArray = new int[10]; -myArray2.push_back(1); -myArray2.push_back(3); +myArray[0] = 1; +myArray[1] = 3; -myArray2[0] = 2; - -cout << myArray2[0] << endl; +cout << myArray[1] << endl; +delete [] myArray; diff --git a/Task/Arrays/C++/arrays-6.cpp b/Task/Arrays/C++/arrays-6.cpp index f753436759..b5119b9644 100644 --- a/Task/Arrays/C++/arrays-6.cpp +++ b/Task/Arrays/C++/arrays-6.cpp @@ -1,25 +1,8 @@ -#include -using std::cout; -using std::endl; +vector myArray2; -#include -#include -#include +myArray2.push_back(1); +myArray2.push_back(3); -int main() -{ - boost::array A; - A[0] = 5; // not bounds checked - A[1] = 2; - A.at(2) = 3; // this is bounds checked. +myArray2[0] = 2; - cout << A[0] << endl; // not bounds checked - - for (int i =0; i < 3; ++i) { - cout << A.at(i) << endl; // this is bounds checked - } - - // use it as you would any STL ordered container. - std::reverse(A.begin(),A.end()); - BOOST_FOREACH(int i, A){cout << i << endl;} -} +cout << myArray2[0] << endl; diff --git a/Task/Arrays/C++/arrays-7.cpp b/Task/Arrays/C++/arrays-7.cpp new file mode 100644 index 0000000000..f753436759 --- /dev/null +++ b/Task/Arrays/C++/arrays-7.cpp @@ -0,0 +1,25 @@ +#include +using std::cout; +using std::endl; + +#include +#include +#include + +int main() +{ + boost::array A; + A[0] = 5; // not bounds checked + A[1] = 2; + A.at(2) = 3; // this is bounds checked. + + cout << A[0] << endl; // not bounds checked + + for (int i =0; i < 3; ++i) { + cout << A.at(i) << endl; // this is bounds checked + } + + // use it as you would any STL ordered container. + std::reverse(A.begin(),A.end()); + BOOST_FOREACH(int i, A){cout << i << endl;} +} diff --git a/Task/Arrays/FBSL/arrays.fbsl b/Task/Arrays/FBSL/arrays.fbsl new file mode 100644 index 0000000000..68a5fc3110 --- /dev/null +++ b/Task/Arrays/FBSL/arrays.fbsl @@ -0,0 +1,41 @@ +#APPTYPE CONSOLE + +DIM v[-1 TO 1] ' static Variant +v[-1] = -1 +v[0] = "zero" +v[1] = !1.0 +FOREACH DIM e IN v + PRINT e, " "; +NEXT +PRINT + +DIM i[-1 TO 1] AS INTEGER ' static strong-type Integer/Single/Double/String +i[-1] = -1 +i[0] = "zero" +i[1] = !1 +FOREACH e IN i + PRINT e, " "; +NEXT +PRINT + +DIM d[] AS INTEGER ' dynamic strong-type Integer/Single/Double/String +d[] = -1 +d[] = "zero" +d[] = !1 +FOREACH e IN d + PRINT e, " "; +NEXT +PRINT + +DIM a[] = {-1, "zero", !1} ' dynamic Variant w/ anonymous array initialization +FOREACH e IN a + PRINT e, " "; +NEXT +PRINT + +FOREACH e IN {-1, "zero", !1} ' anonymous Variant + PRINT e, " "; +NEXT +PRINT + +PAUSE diff --git a/Task/Arrays/Seed7/arrays.seed7 b/Task/Arrays/Seed7/arrays.seed7 new file mode 100644 index 0000000000..cdd3fa33c2 --- /dev/null +++ b/Task/Arrays/Seed7/arrays.seed7 @@ -0,0 +1,35 @@ +$ include "seed7_05.s7i"; + +const type: charArray is array [char] string; # Define an array type for arrays with char index. +const type: twoDim is array array char; # Define an array type for a two dimensional array. + +const proc: main is func + local + var array integer: array1 is 10 times 0; # Array with 10 elements of 0. + var array boolean: array2 is [0 .. 4] times TRUE; # Array with 5 elements of TRUE. + var array integer: array3 is [] (1, 2, 3, 4); # Array with the elements 1, 2, 3, 4. + var array string: array4 is [] ("foo", "bar"); # Array with string elements. + var array char: array5 is [0] ('a', 'b', 'c'); # Array with indices starting from 0. + const array integer: array6 is [] (2, 3, 5, 7, 11); # Array constant. + var charArray: array7 is ['1'] ("one", "two"); # Array with char index starting from '1'. + var twoDim: array8 is [] ([] ('a', 'b'), # Define two dimensional array. + [] ('A', 'B')); + begin + writeln(length(array1)); # Get array length (= number of array elements). + writeln(length(array2)); # Writes 5, because array2 has 5 array elements. + writeln(array4[2]); # Get array element ("bar"). By default array indices start from 1. + writeln(array5[1]); # Writes b, because the indices of array5 start from 0. + writeln(array7['2']); # Writes two, because the indices of array7 start from '1'. + writeln(array8[2][2]); # Writes B, because both indices start from 1. + writeln(minIdx(array7)); # Get minumum index of array ('1'). + array3[1] := 5; # Replace element. Now array3 has the elements 5, 2, 3, 4. + writeln(remove(array3, 3)); # Remove 3rd element. Now array3 has the elements 5, 2, 4. + array1 := array6; # Assign a whole array. + array1 &:= [] (13, 17); # Append an array. + array1 &:= 19; # Append an element. + array1 := array3[2 ..]; # Assign a slice beginning with the second element. + array1 := array3[.. 5]; # Assign a slice up to the fifth element. + array1 := array3[3 .. 4]; # Assign a slice from the third to the fourth element. + array1 := array3[2 len 4]; # Assign a slice of four elements beginning with the second element. + array1 := array3 & array6; # Concatenate two arrays and assign the result to array1. + end func; diff --git a/Task/Assertions/Aime/assertions.aime b/Task/Assertions/Aime/assertions.aime new file mode 100644 index 0000000000..b66bc50f67 --- /dev/null +++ b/Task/Assertions/Aime/assertions.aime @@ -0,0 +1,6 @@ +integer x; + +x = 41; +if (x != 42) { + error("x is not 42"); +} diff --git a/Task/Assertions/FBSL/assertions.fbsl b/Task/Assertions/FBSL/assertions.fbsl new file mode 100644 index 0000000000..3bc60c0ba8 --- /dev/null +++ b/Task/Assertions/FBSL/assertions.fbsl @@ -0,0 +1,14 @@ +#APPTYPE CONSOLE + +DECLARE asserter + +FUNCTION Assert(expression) + DIM cmd AS STRING = "DIM asserter AS INTEGER = (" & expression & ")" + EXECLINE(cmd, 1) + IF asserter = 0 THEN PRINT "Assertion: ", expression, " failed" +END FUNCTION + +Assert("1<2") +Assert("1>2") + +PAUSE diff --git a/Task/Associative-array-Creation/Bracmat/associative-array-creation.bracmat b/Task/Associative-array-Creation/Bracmat/associative-array-creation.bracmat new file mode 100644 index 0000000000..b4a3fcccdd --- /dev/null +++ b/Task/Associative-array-Creation/Bracmat/associative-array-creation.bracmat @@ -0,0 +1,10 @@ + new$hash:?myhash +& (myhash..insert)$(title."Some title") +& (myhash..insert)$(formula.a+b+x^7) +& (myhash..insert)$(fruit.apples oranges kiwis) +& (myhash..insert)$(meat.) +& (myhash..insert)$(fruit.melons bananas) +& out$(myhash..find)$fruit +& (myhash..remove)$formula +& (myhash..insert)$(formula.x^2+y^2) +& out$(myhash..find)$formula; diff --git a/Task/Associative-array-Iteration/Bracmat/associative-array-iteration.bracmat b/Task/Associative-array-Iteration/Bracmat/associative-array-iteration.bracmat new file mode 100644 index 0000000000..9da56ef931 --- /dev/null +++ b/Task/Associative-array-Iteration/Bracmat/associative-array-iteration.bracmat @@ -0,0 +1,18 @@ +( new$hash:?myhash +& (myhash..insert)$(title."Some title") +& (myhash..insert)$(formula.a+b+x^7) +& (myhash..insert)$(fruit.apples oranges kiwis) +& (myhash..insert)$(meat.) +& (myhash..insert)$(fruit.melons bananas) +& (myhash..remove)$formula +& (myhash..insert)$(formula.x^2+y^2) +& (myhash..forall) + $ ( + = key value + . whl + ' ( !arg:(?key.?value) ?arg + & put$("key:" !key "\nvalue:" !value \n) + ) + & put$\n + ) +); diff --git a/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp b/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp index b36f44ece5..1268cbb3f6 100644 --- a/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp +++ b/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp @@ -1,12 +1,33 @@ -std::map myDict; -myDict["hello"] = 1; -myDict["world"] = 2; -myDict["!"] = 3; +#include +#include +#include +#include -// iterating over key-value pairs: -for (std::map::iterator it = myDict.begin(); it != myDict.end(); it++) { - // the thing pointed to by the iterator is a pair - std::string key = it->first; - int value = it->second; - std::cout << "key = " << key << ", value = " << value << std::endl; +int main() { + using MyDict = std::map; + + MyDict dict = { + {"One", 1}, + {"Two", 2}, + {"Three", 7} + }; + + dict["Three"] = 3; + + std::cout << "One: " << dict["One"] << std::endl; + + // Make vector of the keys from our map + std::vector keys; + std::transform(dict.begin(), dict.end(), std::back_inserter(keys), + [](MyDict::value_type& kv) { return kv.first; }); + + std::cout << "Keys: " << std::endl; + for(auto& key: keys) std::cout << " " << key << std::endl; + + std::cout << "Key/Value pairs: " << std::endl; + for(auto& kv: dict) { + std::cout << " " << kv.first << ": " << kv.second << std::endl; + } + + return 0; } diff --git a/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp b/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp index c4fd35b812..b36f44ece5 100644 --- a/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp +++ b/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp @@ -1,21 +1,12 @@ -#include -#include -#include -#include +std::map myDict; +myDict["hello"] = 1; +myDict["world"] = 2; +myDict["!"] = 3; -using namespace std; - -int main() -{ - map myDict; - myDict["hello"] = 1; - myDict["world"] = 2; - myDict["!"] = 3; - - for_each(myDict.begin(), myDict.end(), - [](const pair& p) - { - cout << "key = " << p.first << ", value = " << p.second << endl; - }); - return 0; +// iterating over key-value pairs: +for (std::map::iterator it = myDict.begin(); it != myDict.end(); it++) { + // the thing pointed to by the iterator is a pair + std::string key = it->first; + int value = it->second; + std::cout << "key = " << key << ", value = " << value << std::endl; } diff --git a/Task/Atomic-updates/Erlang/atomic-updates.erl b/Task/Atomic-updates/Erlang/atomic-updates.erl new file mode 100644 index 0000000000..666e8c916c --- /dev/null +++ b/Task/Atomic-updates/Erlang/atomic-updates.erl @@ -0,0 +1,88 @@ +-module( atomic_updates ). +-export( [buckets/1, buckets_get/2, buckets_get_all/1, buckets_move_contents/4, task/0] ). + +buckets( N ) -> + Buckets = erlang:list_to_tuple( lists:seq(1, N) ), + erlang:spawn_link( fun() -> buckets_loop(Buckets) end ). + +buckets_get( N, Buckets_pid ) -> + {is_buckets_alive, true} = {is_buckets_alive, erlang:is_process_alive( Buckets_pid )}, + Buckets_pid ! {get, N, erlang:self()}, + receive + {value, Buckets_pid, Value} -> Value + end. + +buckets_get_all( Buckets_pid ) -> + {is_buckets_alive, true} = {is_buckets_alive, erlang:is_process_alive( Buckets_pid )}, + Buckets_pid ! {get_all, erlang:self()}, + receive + {values, Buckets_pid, Values} -> Values + end. + +buckets_move_contents( Amount, From, To, Buckets_pid ) -> + {is_buckets_alive, true} = {is_buckets_alive, erlang:is_process_alive( Buckets_pid )}, + Buckets_pid ! {move_contents, Amount, From, To, erlang:self()}, + receive + {move_contents_done, Buckets_pid} -> ok + end. + +task() -> + erlang:spawn( fun() -> + N = 10, + Buckets = buckets( N ), + erlang:spawn_link( fun() -> closer_loop(N, Buckets) end ), + erlang:spawn_link( fun() -> redistribute_loop(N, Buckets) end ), + display_loop( 0, N, Buckets ), + erlang:exit( stop ) + end ). + + + +closer_loop( N, Buckets ) -> + One = random:uniform( N ), + Two = random:uniform( N ), + Difference = buckets_get( One, Buckets ) - buckets_get( Two, Buckets ), + {Amount, From, To} = closer_loop_how_to_move( Difference, One, Two ), + buckets_move_contents( Amount, From, To, Buckets ), + closer_loop( N, Buckets ). + +closer_loop_how_to_move( Difference, One, Two ) when Difference < 0 -> + {-1* Difference div 2, Two, One}; +closer_loop_how_to_move( Difference, One, Two ) -> + {Difference div 2, One, Two}. + +buckets_loop( Buckets ) -> + receive + {get, N, Pid} -> + Pid ! {value, erlang:self(), erlang:element( N, Buckets )}, + buckets_loop( Buckets ); + {get_all, Pid} -> + Pid ! {values, erlang:self(), erlang:tuple_to_list( Buckets )}, + buckets_loop( Buckets ); + {move_contents, Amount, From, To, Pid} -> + Pid ! {move_contents_done, erlang:self()}, + buckets_loop( buckets_loop_move_contents(Amount, From, To, Buckets) ) + end. + +buckets_loop_move_contents( _Amount, Same, Same, Buckets ) -> + Buckets; +buckets_loop_move_contents( Amount, From, To, Buckets ) -> + Amount_from = erlang:element( From, Buckets ), + Clamped_amount = erlang:min( Amount, Amount_from ), + Removed = erlang:setelement( From, Buckets, Amount_from - Clamped_amount ), + Amount_to = erlang:element( To, Buckets ) + Clamped_amount, + erlang:setelement( To, Removed, Amount_to ). + +display_loop( N, N, _Buckets ) -> ok; +display_loop( Counter, N, Buckets ) -> + Contents = buckets_get_all( Buckets ), + io:fwrite( "~p = ~p~n", [Contents, lists:sum(Contents)] ), + timer:sleep( 100 ), + display_loop( Counter + 1, N, Buckets ). + +redistribute_loop( N, Buckets ) -> + Amount = random:uniform( N ), + From = random:uniform( N ), + To = random:uniform( N ), + buckets_move_contents( Amount, From, To, Buckets ), + redistribute_loop( N, Buckets ). diff --git a/Task/Average-loop-length/Racket/average-loop-length.rkt b/Task/Average-loop-length/Racket/average-loop-length.rkt new file mode 100644 index 0000000000..7a805fa7c2 --- /dev/null +++ b/Task/Average-loop-length/Racket/average-loop-length.rkt @@ -0,0 +1,27 @@ +#lang racket +(require (only-in math factorial)) + +(define (analytical n) + (for/sum ([i (in-range 1 (add1 n))]) + (/ (factorial n) (expt n i) (factorial (- n i))))) + +(define (test n times) + (define (count-times seen times) + (define x (random n)) + (if (memq x seen) times (count-times (cons x seen) (add1 times)))) + (/ (for/fold ([count 0]) ([i times]) (count-times '() count)) + times)) + +(define (test-table max-n times) + (displayln " n avg theory error\n------------------------") + (for ([i (in-range 1 (add1 max-n))]) + (define average (test i times)) + (define theory (analytical i)) + (define difference (* (abs (sub1 (/ average theory))) 100)) + (displayln (~a (~a i #:width 2 #:align 'right) + " " (real->decimal-string average 4) + " " (real->decimal-string theory 4) + " " (real->decimal-string difference 4) + "%")))) + +(test-table 20 10000) diff --git a/Task/Averages-Arithmetic-mean/Erlang/averages-arithmetic-mean.erl b/Task/Averages-Arithmetic-mean/Erlang/averages-arithmetic-mean.erl index 9f9d472c92..7817246931 100644 --- a/Task/Averages-Arithmetic-mean/Erlang/averages-arithmetic-mean.erl +++ b/Task/Averages-Arithmetic-mean/Erlang/averages-arithmetic-mean.erl @@ -1,2 +1,2 @@ mean([]) -> 0; -mean(L) -> lists:sum(L)/length(L). +mean(L) -> lists:sum(L)/erlang:length(L). diff --git a/Task/Averages-Arithmetic-mean/Julia/averages-arithmetic-mean.julia b/Task/Averages-Arithmetic-mean/Julia/averages-arithmetic-mean.julia index 8ff131b323..3219e3d96a 100644 --- a/Task/Averages-Arithmetic-mean/Julia/averages-arithmetic-mean.julia +++ b/Task/Averages-Arithmetic-mean/Julia/averages-arithmetic-mean.julia @@ -1,5 +1,6 @@ julia> mean([1,2,3]) 2.0 - +julia> mean(1:10) +5.5 julia> mean([]) ERROR: mean of empty collection undefined: [] diff --git a/Task/Averages-Mean-angle/D/averages-mean-angle.d b/Task/Averages-Mean-angle/D/averages-mean-angle.d index d635855a51..003a84c824 100644 --- a/Task/Averages-Mean-angle/D/averages-mean-angle.d +++ b/Task/Averages-Mean-angle/D/averages-mean-angle.d @@ -5,12 +5,12 @@ auto radians(T)(in T d) pure nothrow { return d * PI / 180; } auto degrees(T)(in T r) pure nothrow { return r * 180 / PI; } real meanAngle(T)(in T[] D) /*pure nothrow*/ { - immutable t = reduce!((a,d) => a + expi(radians(d)))(complex(0),D); - return (t / D.length).arg().degrees(); + immutable t = reduce!((a, d) => a + d.radians.expi)(0.complex, D); + return (t / D.length).arg.degrees; } void main() { foreach (angles; [[350, 10], [90, 180, 270, 360], [10, 20, 30]]) - writefln("The mean angle of %s is: %.2f degrees", - angles, meanAngle(angles)); + writefln("The mean angle of %s is: %.2f degrees", + angles, angles.meanAngle); } diff --git a/Task/Averages-Mean-angle/Erlang/averages-mean-angle.erl b/Task/Averages-Mean-angle/Erlang/averages-mean-angle.erl new file mode 100644 index 0000000000..53c0057259 --- /dev/null +++ b/Task/Averages-Mean-angle/Erlang/averages-mean-angle.erl @@ -0,0 +1,19 @@ +-module( mean_angle ). +-export( [from_degrees/1, task/0] ). + +from_degrees( Angles ) -> + Radians = [radians(X) || X <- Angles], + Sines = [math:sin(X) || X <- Radians], + Coses = [math:cos(X) || X <- Radians], + erlang:round( degrees(math:atan2( average(Sines), average(Coses) )) ). + +task() -> + Angles = [[350, 10], [90, 180, 270, 360], [10, 20, 30]], + [io:fwrite( "Mean angle of ~p is: ~p~n", [X, from_degrees(X)] ) || X <- Angles]. + + +average( List ) -> lists:sum( List ) / erlang:length( List ). + +degrees( Radians ) -> Radians * 180 / math:pi(). + +radians( Degrees ) -> Degrees * math:pi() / 180. diff --git a/Task/Averages-Mean-angle/Java/averages-mean-angle.java b/Task/Averages-Mean-angle/Java/averages-mean-angle.java new file mode 100644 index 0000000000..52c4abe02f --- /dev/null +++ b/Task/Averages-Mean-angle/Java/averages-mean-angle.java @@ -0,0 +1,60 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RAvgMeanAngle { + + private static final List> samples; + + static { + samples = new ArrayList<>(); + samples.add(Arrays.asList(350.0, 10.0)); + samples.add(Arrays.asList(90.0, 180.0, 270.0, 360.0)); + samples.add(Arrays.asList(10.0, 20.0, 30.0)); + samples.add(Arrays.asList(370.0)); + samples.add(Arrays.asList(180.0)); + } + + public RAvgMeanAngle() { + + return; + } + + public double getMeanAngle(List sample) { + + double x_component = 0.0; + double y_component = 0.0; + double avg_d, avg_r; + + for (double angle_d : sample) { + double angle_r; + angle_r = Math.toRadians(angle_d); + x_component += Math.cos(angle_r); + y_component += Math.sin(angle_r); + } + x_component /= sample.size(); + y_component /= sample.size(); + avg_r = Math.atan2(y_component, x_component); + avg_d = Math.toDegrees(avg_r); + + return avg_d; + } + + public static void main(String[] args) { + + runSample(args); + + return; + } + + public static void runSample(String[] args) { + + RAvgMeanAngle main = new RAvgMeanAngle(); + for (List sample : samples) { + double meanAngle = main.getMeanAngle(sample); + System.out.printf("The mean angle of %s is:%n%12.6f%n%n", sample, meanAngle); + } + + return; + } +} diff --git a/Task/Averages-Mean-angle/NetRexx/averages-mean-angle.netrexx b/Task/Averages-Mean-angle/NetRexx/averages-mean-angle.netrexx new file mode 100644 index 0000000000..9f2a940177 --- /dev/null +++ b/Task/Averages-Mean-angle/NetRexx/averages-mean-angle.netrexx @@ -0,0 +1,33 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary +numeric digits 80 + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getMeanAngle(angles) private static binary + x_component = double 0.0 + y_component = double 0.0 + aK = int angles.words() + loop a_ = 1 to aK + angle_d = double angles.word(a_) + angle_r = double Math.toRadians(angle_d) + x_component = x_component + Math.cos(angle_r) + y_component = y_component + Math.sin(angle_r) + end a_ + x_component = x_component / aK + y_component = y_component / aK + avg_r = Math.atan2(y_component, x_component) + avg_d = Math.toDegrees(avg_r) + return avg_d + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + angleSet = [ '350 10', '90 180 270 360', '10 20 30', '370', '180' ] + loop angles over angleSet + say 'The mean angle of' angles.space(1, ',') 'is:' + say ' 'getMeanAngle(angles).format(6, 6) + say + end angles + return diff --git a/Task/Averages-Mean-angle/Seed7/averages-mean-angle.seed7 b/Task/Averages-Mean-angle/Seed7/averages-mean-angle.seed7 new file mode 100644 index 0000000000..9c5cd77599 --- /dev/null +++ b/Task/Averages-Mean-angle/Seed7/averages-mean-angle.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + include "complex.s7i"; + +const func float: deg2rad (in float: degree) is + return degree * PI / 180.0; + +const func float: rad2deg (in float: rad) is + return rad * 180.0 / PI; + +const func float: meanAngle (in array float: degrees) is func + result + var float: mean is 0.0; + local + var float: degree is 0.0; + var complex: sum is complex.value; + begin + for degree range degrees do + sum +:= polar(1.0, deg2rad(degree)); + end for; + mean := rad2deg(arg(sum / complex conv length(degrees))); + end func; + +const proc: main is func + begin + writeln(meanAngle([] (350.0, 10.0)) digits 4); + writeln(meanAngle([] (90.0, 180.0, 270.0, 360.0)) digits 4); + writeln(meanAngle([] (10.0, 20.0, 30.0)) digits 4); + end func; diff --git a/Task/Averages-Mean-time-of-day/Erlang/averages-mean-time-of-day.erl b/Task/Averages-Mean-time-of-day/Erlang/averages-mean-time-of-day.erl new file mode 100644 index 0000000000..fb717b1cf4 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Erlang/averages-mean-time-of-day.erl @@ -0,0 +1,30 @@ +-module( mean_time_of_day ). +-export( [from_times/1, task/0] ). + +from_times( Times ) -> + Seconds = [seconds_from_time(X) || X <- Times], + Degrees = [degrees_from_seconds(X) || X <- Seconds], + Average = mean_angle:from_degrees( Degrees ), + time_from_seconds( seconds_from_degrees(Average) ). + +task() -> + Times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"], + io:fwrite( "The mean time of ~p is: ~p~n", [Times, from_times(Times)] ). + + + +degrees_from_seconds( Seconds ) when Seconds < (24 * 3600) -> (Seconds * 360) / (24 * 3600). + +seconds_from_degrees( Degrees ) when Degrees < 0 -> seconds_from_degrees( Degrees + 360 ); +seconds_from_degrees( Degrees ) when Degrees < 360 -> (Degrees * 24 * 3600) / 360. + +seconds_from_time( Time ) -> + {ok, [Hours, Minutes, Seconds], _Rest} = io_lib:fread( "~d:~d:~d", Time ), + Hours * 3600 + Minutes * 60 + Seconds. + +time_from_seconds( Seconds_float ) -> + Seconds = erlang:round( Seconds_float ), + Hours = Seconds div 3600, + Minutes = (Seconds - (Hours * 3600)) div 60, + Secs = Seconds - (Hours * 3600) - (Minutes * 60), + lists:flatten( io_lib:format("~2.10.0B:~2.10.0B:~2.10.0B", [Hours, Minutes, Secs]) ). diff --git a/Task/Averages-Mean-time-of-day/Racket/averages-mean-time-of-day.rkt b/Task/Averages-Mean-time-of-day/Racket/averages-mean-time-of-day.rkt new file mode 100644 index 0000000000..33ec2f1ff7 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Racket/averages-mean-time-of-day.rkt @@ -0,0 +1,20 @@ +#lang racket +(define (mean-angle/radians as) + (define n (length as)) + (atan (* (/ 1 n) (for/sum ([αj as]) (sin αj))) + (* (/ 1 n) (for/sum ([αj as]) (cos αj))))) +(define (mean-time times) + (define secs/day (* 60 60 24)) + (define (time->deg time) + (/ (for/fold ([sum 0]) ([t (map string->number (string-split time ":"))]) + (+ (* 60 sum) t)) + secs/day 1/360 (/ 180 pi))) + (define secs + (modulo (inexact->exact (round (* (mean-angle/radians (map time->deg times)) + (/ 180 pi) 1/360 secs/day))) + secs/day)) + (let loop ([s secs] [ts '()]) + (if (zero? s) (string-join ts ":") + (let-values ([(q r) (quotient/remainder s 60)]) + (loop q (cons (~r r #:min-width 2 #:pad-string "0") ts)))))) +(mean-time '("23:00:17" "23:40:20" "00:12:45" "00:17:19")) diff --git a/Task/Averages-Median/APL/averages-median-1.apl b/Task/Averages-Median/APL/averages-median-1.apl new file mode 100644 index 0000000000..126a09229c --- /dev/null +++ b/Task/Averages-Median/APL/averages-median-1.apl @@ -0,0 +1 @@ +median←{v←⍵[⍋⍵]⋄.5×v[⌈¯1+.5×⍴v]+v[⌊.5×⍴v]} ⍝ Assumes ⎕IO←0 diff --git a/Task/Averages-Median/APL/averages-median-2.apl b/Task/Averages-Median/APL/averages-median-2.apl new file mode 100644 index 0000000000..d36e534710 --- /dev/null +++ b/Task/Averages-Median/APL/averages-median-2.apl @@ -0,0 +1 @@ +⎕IO←0 diff --git a/Task/Averages-Median/APL/averages-median-3.apl b/Task/Averages-Median/APL/averages-median-3.apl new file mode 100644 index 0000000000..9c1c78d2af --- /dev/null +++ b/Task/Averages-Median/APL/averages-median-3.apl @@ -0,0 +1,2 @@ +⎕IO←1 +median←{v←⍵[⍋⍵] ⋄ 0.5×v[⌈0.5×⍴v]+v[⌊1+0.5×⍴v]} diff --git a/Task/Averages-Median/C/averages-median-1.c b/Task/Averages-Median/C/averages-median-1.c index 33840b61d3..66fabd5561 100644 --- a/Task/Averages-Median/C/averages-median-1.c +++ b/Task/Averages-Median/C/averages-median-1.c @@ -7,9 +7,8 @@ typedef struct floatList { } *FloatList; int floatcmp( const void *a, const void *b) { - if (*(float *)a > *(float *)b) return 1; - else if (*(float *)a < *(float *)b) return -1; - else return 0; + if (*(const float *)a < *(const float *)b) return -1; + else return *(const float *)a > *(const float *)b; } float median( FloatList fl ) diff --git a/Task/Averages-Median/C/averages-median-2.c b/Task/Averages-Median/C/averages-median-2.c index 5fca1166e5..14e449a4d4 100644 --- a/Task/Averages-Median/C/averages-median-2.c +++ b/Task/Averages-Median/C/averages-median-2.c @@ -33,7 +33,7 @@ int qselect(int *x, int k, int len) int icmp(const void *a, const void *b) { - return *(int*)a < *(int*)b ? -1 : *(int*)a > *(int*) b; + return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*) b; } int main() diff --git a/Task/Averages-Median/Julia/averages-median.julia b/Task/Averages-Median/Julia/averages-median.julia index 407dbf74ec..febfec9074 100644 --- a/Task/Averages-Median/Julia/averages-median.julia +++ b/Task/Averages-Median/Julia/averages-median.julia @@ -1,4 +1,10 @@ - julia> values = [1:10] - [1,2,3,4,5,6,7,8,9,10] - julia> median(values) - 5.5 +function median2(n) + s = sort(n) + len = length(n) + len%2 == 0 && return (s[ifloor(len/2)+1] + s[ifloor(len/2)])/2 + return s[ifloor(len/2)+1] +end +a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] +b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2] +@assert median(a) == median2(a) +@assert median(b) == median2(b) diff --git a/Task/Averages-Median/Perl-6/averages-median-1.pl6 b/Task/Averages-Median/Perl-6/averages-median-1.pl6 new file mode 100644 index 0000000000..91de232a45 --- /dev/null +++ b/Task/Averages-Median/Perl-6/averages-median-1.pl6 @@ -0,0 +1,4 @@ +sub median { + my @a = sort @_; + return (@a[@a.end / 2] + @a[@a / 2]) / 2; +} diff --git a/Task/Averages-Median/Perl-6/averages-median-2.pl6 b/Task/Averages-Median/Perl-6/averages-median-2.pl6 new file mode 100644 index 0000000000..a58faedc98 --- /dev/null +++ b/Task/Averages-Median/Perl-6/averages-median-2.pl6 @@ -0,0 +1 @@ +sub median { 2 R/ [+] @_.sort[@_.end / 2, @_ / 2] } diff --git a/Task/Averages-Mode/C/averages-mode.c b/Task/Averages-Mode/C/averages-mode.c index 159463683e..133eeebd3f 100644 --- a/Task/Averages-Mode/C/averages-mode.c +++ b/Task/Averages-Mode/C/averages-mode.c @@ -5,13 +5,13 @@ typedef struct { double v; int c; } vcount; int cmp_dbl(const void *a, const void *b) { - double x = *(double*)a - *(double*)b; + double x = *(const double*)a - *(const double*)b; return x < 0 ? -1 : x > 0; } int vc_cmp(const void *a, const void *b) { - return ((vcount*)b)->c - ((vcount*)a)->c; + return ((const vcount*)b)->c - ((const vcount*)a)->c; } int get_mode(double* x, int len, vcount **list) diff --git a/Task/Averages-Mode/D/averages-mode.d b/Task/Averages-Mode/D/averages-mode.d index e20dd5ad3c..71537ef17d 100644 --- a/Task/Averages-Mode/D/averages-mode.d +++ b/Task/Averages-Mode/D/averages-mode.d @@ -1,17 +1,17 @@ import std.stdio, std.algorithm, std.array; -T[] mode(T)(T[] items) /*pure nothrow*/ { +auto mode(T)(T[] items) /*pure nothrow*/ { int[T] aa; foreach (item; items) aa[item]++; - int m = aa.byValue.reduce!max(); - return aa.byKey.filter!(k => aa[k] == m)().array(); + immutable m = aa.byValue.reduce!max; + return aa.byKey.filter!(k => aa[k] == m); } void main() { auto data = [1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6]; - writeln("Mode: ", data.mode()); + writeln("Mode: ", data.mode); data ~= 2; - writeln("Mode: ", data.mode()); + writeln("Mode: ", data.mode); } diff --git a/Task/Averages-Mode/Erlang/averages-mode.erl b/Task/Averages-Mode/Erlang/averages-mode.erl new file mode 100644 index 0000000000..d45c333ef5 --- /dev/null +++ b/Task/Averages-Mode/Erlang/averages-mode.erl @@ -0,0 +1,21 @@ +-module( mode ). +-export( [example/0, values/1] ). + +example() -> + Set = [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"], + io:fwrite( "In ~p the mode(s) is(are): ~p~n", [Set, values(Set)] ). + +values( Set ) -> + Dict = lists:foldl( fun values_count/2, dict:new(), Set ), + [X || {X, _Y} <- dict:fold( fun keep_maxs/3, [{0, 0}], Dict )]. + + + +keep_maxs( Key, Value, [{_Max_key, Max_value} | _] ) when Value > Max_value -> + [{Key, Value}]; +keep_maxs( Key, Value, [{_Max_key, Max_value} | _]=Maxs ) when Value =:= Max_value -> + [{Key, Value} | Maxs]; +keep_maxs( _Key, _Value, Maxs ) -> + Maxs. + +values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ). diff --git a/Task/Averages-Mode/Objeck/averages-mode.objeck b/Task/Averages-Mode/Objeck/averages-mode.objeck new file mode 100644 index 0000000000..6dc93e5ccc --- /dev/null +++ b/Task/Averages-Mode/Objeck/averages-mode.objeck @@ -0,0 +1,50 @@ +use Collection; + +class Mode { + function : Main(args : String[]) ~ Nil { + Print(Mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])); + Print(Mode([1, 2, 4, 4, 1])); + } + + function : Mode(coll : Int[]) ~ IntVector { + seen := IntMap->New(); + max := 0; + maxElems := IntVector->New(); + + each(i : coll) { + value := coll[i]; + + featched := seen->Find(value)->As(IntHolder); + if(featched <> Nil) { + seen->Remove(value); + seen->Insert(value, IntHolder->New(featched->Get() + 1)); + } + else { + seen->Insert(value, IntHolder->New(1)); + }; + + featched := seen->Find(value)->As(IntHolder); + if(featched->Get() > max) { + max := featched->Get(); + maxElems->Empty(); + maxElems->AddBack(value); + } + else if(featched->Get() = max) { + maxElems->AddBack(value); + }; + }; + + return maxElems; + } + + function : Print(out : IntVector) ~ Nil { + '['->Print(); + each(i : out) { + out->Get(i)->Print(); + if(i + 1 < out->Size()) { + ", "->Print(); + }; + }; + ']'->PrintLine(); + } +} diff --git a/Task/Averages-Mode/Racket/averages-mode.rkt b/Task/Averages-Mode/Racket/averages-mode.rkt new file mode 100644 index 0000000000..9f4dd60486 --- /dev/null +++ b/Task/Averages-Mode/Racket/averages-mode.rkt @@ -0,0 +1,18 @@ +#lang racket + +(define (mode seq) + (define frequencies (make-hash)) + (for ([s seq]) + (hash-update! frequencies + s + (lambda (freq) (add1 freq)) + 0)) + (for/fold ([ms null] + [freq 0]) + ([(k v) (in-hash frequencies)]) + (cond [(> v freq) + (values (list k) v)] + [(= v freq) + (values (cons k ms) freq)] + [else + (values ms freq)]))) diff --git a/Task/Averages-Mode/Seed7/averages-mode.seed7 b/Task/Averages-Mode/Seed7/averages-mode.seed7 new file mode 100644 index 0000000000..888594a6d1 --- /dev/null +++ b/Task/Averages-Mode/Seed7/averages-mode.seed7 @@ -0,0 +1,51 @@ +$ include "seed7_05.s7i"; + +const proc: createModeFunction (in type: elemType) is func + begin + + const func array elemType: mode (in array elemType: data) is func + result + var array elemType: maxElems is 0 times elemType.value; + local + var hash [elemType] integer: counts is (hash [elemType] integer).value; + var elemType: aValue is elemType.value; + var integer: maximum is 0; + begin + for aValue range data do + if aValue in counts then + incr(counts[aValue]); + else + counts @:= [aValue] 1; + end if; + if counts[aValue] > maximum then + maximum := counts[aValue]; + maxElems := [] (aValue); + elsif counts[aValue] = maximum then + maxElems &:= aValue; + end if; + end for; + end func; + + const func string: str (in array elemType: data) is func + result + var string: result is ""; + local + var elemType: anElement is elemType.value; + begin + for anElement range data do + result &:= " " & str(anElement); + end for; + result := result[2 ..]; + end func; + + enable_output(array elemType); + + end func; + +createModeFunction(integer); + +const proc: main is func + begin + writeln(mode([] (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); + writeln(mode([] (1, 1, 2, 4, 4))); + end func; diff --git a/Task/Averages-Root-mean-square/Racket/averages-root-mean-square.rkt b/Task/Averages-Root-mean-square/Racket/averages-root-mean-square.rkt new file mode 100644 index 0000000000..7e6c982a1b --- /dev/null +++ b/Task/Averages-Root-mean-square/Racket/averages-root-mean-square.rkt @@ -0,0 +1,3 @@ +#lang racket +(define (rms nums) + (sqrt (/ (for/sum ([n nums]) (* n n)) (length nums)))) diff --git a/Task/Averages-Simple-moving-average/Objeck/averages-simple-moving-average.objeck b/Task/Averages-Simple-moving-average/Objeck/averages-simple-moving-average.objeck new file mode 100644 index 0000000000..44990a455f --- /dev/null +++ b/Task/Averages-Simple-moving-average/Objeck/averages-simple-moving-average.objeck @@ -0,0 +1,45 @@ +use Collection; + +class MovingAverage { + @window : FloatQueue; + @period : Int; + @sum : Float; + + New(period : Int) { + @window := FloatQueue->New(); + @period := period; + } + + method : NewNum(num : Float) ~ Nil { + @sum += num; + @window->Add(num); + if(@window->Size() > @period) { + @sum -= @window->Remove(); + }; + } + + method : GetAvg() ~ Float { + if(@window->IsEmpty()) { + return 0; # technically the average is undefined + }; + + return @sum / @window->Size(); + } + + function : Main(args : String[]) ~ Nil { + testData := [1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 1.0]; + windowSizes := [3.0, 5.0]; + + each(i : windowSizes) { + windSize := windowSizes[i]; + ma := MovingAverage->New(windSize); + each(j : testData) { + x := testData[j]; + ma->NewNum(x); + avg := ma->GetAvg(); + "Next number = {$x}, SMA = {$avg}"->PrintLine(); + }; + IO.Console->PrintLine(); + }; + } +} diff --git a/Task/Averages-Simple-moving-average/Racket/averages-simple-moving-average.rkt b/Task/Averages-Simple-moving-average/Racket/averages-simple-moving-average.rkt new file mode 100644 index 0000000000..e4368f8b9a --- /dev/null +++ b/Task/Averages-Simple-moving-average/Racket/averages-simple-moving-average.rkt @@ -0,0 +1,21 @@ +#lang racket + +(require data/queue) + +(define (simple-moving-average period) + (define queue (make-queue)) + (define sum 0.0) + + (lambda (x) + (enqueue! queue x) + (set! sum (+ sum x)) + (when (> (queue-length queue) period) + (set! sum (- sum (dequeue! queue)))) + (/ sum (queue-length queue)))) + +;; Tests +(define sma3 (simple-moving-average 3)) +(define sma5 (simple-moving-average 5)) +(for/lists (lst1 lst2) + ([i '(1 2 3 4 5 5 4 3 2 1)]) + (values (sma3 i) (sma5 i))) diff --git a/Task/Balanced-brackets/Aime/balanced-brackets.aime b/Task/Balanced-brackets/Aime/balanced-brackets.aime new file mode 100644 index 0000000000..5257bf1549 --- /dev/null +++ b/Task/Balanced-brackets/Aime/balanced-brackets.aime @@ -0,0 +1,66 @@ +integer +unbalanced(text s) +{ + integer b, i; + + b = 0; + i = 0; + while (i < length(s)) { + if (character(s, i) == '[') { + b += 1; + } else { + b -= 1; + if (b < 0) { + break; + } + } + + i += 1; + } + + return b; +} + +text +generate(integer d) +{ + integer i; + text s; + + i = d; + while (i) { + s = insert(s, 0, '['); + i -= 1; + } + + i = d; + while (i) { + s = insert(s, drand(length(s)), ']'); + i -= 1; + } + + return s; +} + +integer +main(void) +{ + integer i; + + i = 0; + while (i < 10) { + text s; + + s = generate(i); + o_text(s); + o_text(" is "); + if (unbalanced(s)) { + o_text("un"); + } + o_text("balanced\n"); + + i += 1; + } + + return 0; +} diff --git a/Task/Balanced-brackets/Clojure/balanced-brackets.clj b/Task/Balanced-brackets/Clojure/balanced-brackets.clj index ebe2af1867..2a8fa58080 100644 --- a/Task/Balanced-brackets/Clojure/balanced-brackets.clj +++ b/Task/Balanced-brackets/Clojure/balanced-brackets.clj @@ -12,17 +12,3 @@ (when (= (peek stack) \[) (recur coll (pop stack)))) (zero? (count stack))))) - -user> (->> (range 10) - (map gen-brackets ,) - (map (juxt identity balanced?) ,) vec) -[["" true] - ["[]" true] - ["[[]]" true] - ["[][[]]" true] - ["[]][][][" nil] - ["[[[[[]]]]]" true] - ["]][[][][[[]]" nil] - ["[]]]][[[[]][][" nil] - ["][][[]]][[][][][" nil] - ["][][]]][]][[[][[[]" nil] diff --git a/Task/Balanced-brackets/D/balanced-brackets-1.d b/Task/Balanced-brackets/D/balanced-brackets-1.d index ffde7bf9d0..e6915430c4 100644 --- a/Task/Balanced-brackets/D/balanced-brackets-1.d +++ b/Task/Balanced-brackets/D/balanced-brackets-1.d @@ -1,10 +1,8 @@ -import std.stdio, std.algorithm, std.random; +import std.stdio, std.algorithm, std.random, std.range; void main() { - foreach (i; 1 .. 9) { - string s; - foreach (_; 0 .. i * 2) - s ~= "[]"[uniform(0, 2)]; + foreach (immutable i; 1 .. 9) { + immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, 2)]).array; writeln(s.balancedParens('[', ']') ? " OK: " : "bad: ", s); } } diff --git a/Task/Balanced-brackets/D/balanced-brackets-2.d b/Task/Balanced-brackets/D/balanced-brackets-2.d index f0c6aafc6c..1ad6bedecd 100644 --- a/Task/Balanced-brackets/D/balanced-brackets-2.d +++ b/Task/Balanced-brackets/D/balanced-brackets-2.d @@ -1,20 +1,23 @@ -import std.stdio, std.random; +import std.stdio, std.random, std.range, std.algorithm; + +bool isBalanced(in string txt) pure nothrow { + auto count = 0; + + foreach (immutable c; txt) { + if (c == ']') { + count--; + if (count < 0) + return false; + } else if (c == '[') + count++; + } + + return count == 0; +} void main() { -NEXT_STR: - foreach (j; 1 .. 9) { - string s; - foreach (_; 0 .. j * 2) - s ~= "[]"[uniform(0, 2)]; - - int balance; - foreach (i, c; s) { - balance += (c == '[') ? 1 : ((c == ']') ? -1 : 0); - if (balance < 0 || balance >= s.length - i) { - writefln("BAD: %s (%s)", s, balance < 0 ? "-" : "+"); - continue NEXT_STR; - } - } - writefln(" OK: %s (=)", s); + foreach (immutable i; 1 .. 9) { + immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, 2)]).array; + writeln(s.isBalanced ? " OK " : "Bad ", s); } } diff --git a/Task/Balanced-brackets/D/balanced-brackets-3.d b/Task/Balanced-brackets/D/balanced-brackets-3.d index d586906668..0f106ed6a7 100644 --- a/Task/Balanced-brackets/D/balanced-brackets-3.d +++ b/Task/Balanced-brackets/D/balanced-brackets-3.d @@ -1,20 +1,19 @@ import std.stdio, std.random, std.conv, std.range, std.algorithm; -bool isBalanced(in char[] s) pure nothrow { - static bool bal(in char[] s, in int nb=0) pure nothrow { +bool isBalanced(in string s) pure nothrow { + static bool bal(in string s, in int nb = 0) pure nothrow { if (nb == 0 && s.empty) return true; if (s.empty || nb < 0) return false; if (s[0] == '[') return bal(s[1 .. $], nb + 1); if (s[0] == ']') return bal(s[1 .. $], nb - 1); - return bal(s[1 .. $], nb); // ignore char + return bal(s[1 .. $], nb); // Ignore char. } return bal(s); } void main() { - foreach (i; 1 .. 9) { - auto sr = iota(i * 2).map!(_ => ['[',']'][uniform(0, 2)])(); - auto s = sr.array(); - writefln("%5s: %s", s.isBalanced().text(), s); + foreach (immutable i; 1 .. 9) { + immutable s = iota(i * 2).map!(_ => "[]"[uniform(0, 2)]).array; + writeln(s.isBalanced ? " OK " : "Bad ", s); } } diff --git a/Task/Balanced-brackets/Erlang/balanced-brackets.erl b/Task/Balanced-brackets/Erlang/balanced-brackets.erl new file mode 100644 index 0000000000..ce135dda62 --- /dev/null +++ b/Task/Balanced-brackets/Erlang/balanced-brackets.erl @@ -0,0 +1,29 @@ +-module( balanced_brackets ). +-export( [generate/1, is_balanced/1, task/0] ). + +generate( N ) -> + [generate_bracket(random:uniform()) || _X <- lists:seq(1, 2*N)]. + +is_balanced( String ) -> is_balanced_loop( String, 0 ). + +task() -> + lists:foreach( fun (N) -> + String = generate( N ), + Result = is_balanced( String ), + io:fwrite( "~s is ~s~n", [String, task_balanced(Result)] ) + end, + lists:seq(0, 5) ). + + + +is_balanced_loop( _String, N ) when N < 0 -> false; +is_balanced_loop( [], 0 ) -> true; +is_balanced_loop( [], _N ) -> false; +is_balanced_loop( [$[ | T], N ) -> is_balanced_loop( T, N + 1 ); +is_balanced_loop( [$] | T], N ) -> is_balanced_loop( T, N - 1 ). + +generate_bracket( N ) when N =< 0.5 -> $[; +generate_bracket( N ) when N > 0.5 -> $]. + +task_balanced( true ) -> "OK"; +task_balanced( false ) -> "NOT OK". diff --git a/Task/Balanced-brackets/Run-BASIC/balanced-brackets.run b/Task/Balanced-brackets/Run-BASIC/balanced-brackets.run index d24763e6c1..540bc69477 100644 --- a/Task/Balanced-brackets/Run-BASIC/balanced-brackets.run +++ b/Task/Balanced-brackets/Run-BASIC/balanced-brackets.run @@ -10,7 +10,7 @@ brk$(8) = "[]][][][[[]]" brk$(9) = "][]][[" brk$(10) = "[]][][][[]" -for i = 1 to 10 +for i = 0 to 10 b$ = brk$(i) while instr(b$,"[]") <> 0 x = instr(b$,"[]") diff --git a/Task/Balanced-ternary/D/balanced-ternary.d b/Task/Balanced-ternary/D/balanced-ternary.d index 8ddc97e1d9..51a2404d03 100644 --- a/Task/Balanced-ternary/D/balanced-ternary.d +++ b/Task/Balanced-ternary/D/balanced-ternary.d @@ -2,7 +2,7 @@ import std.stdio, std.bigint, std.range, std.algorithm, std.array, std.conv, std.exception; struct BalancedTernary { - enum Dig : byte { N=-1, Z=0, P=+1 } // digits + enum Dig : byte { N=-1, Z=0, P=+1 } // Digits. Dig[] digits; // Represented as a list of 0, 1 or -1s, // with least significant digit first. @@ -20,11 +20,11 @@ struct BalancedTernary { [Dig.Z, Dig.P]]; this(string inp) { - this.digits = map!(c => cast()str2dig[c])(retro(inp)).array(); + this.digits = inp.retro().map!(c => cast()str2dig[c]).array; } this(long inp) { - this.digits = _bint2ternary(BigInt(inp)); + this.digits = _bint2ternary(inp.BigInt); } this(BigInt inp) { @@ -32,7 +32,7 @@ struct BalancedTernary { } this(BalancedTernary inp) { - // no need to dup, they are virtually immutable + // No need to dup, they are virtually immutable. this.digits = inp.digits; } @@ -42,19 +42,19 @@ struct BalancedTernary { static Dig[] _bint2ternary(/*in*/ BigInt n) { static py_div(T1, T2)(T1 a, T2 b) { - if (a < 0) - if (b < 0) - return -a / -b; - else - return -(-a / b) - (-a % b != 0 ? 1 : 0); - else if (b < 0) - return -(a / -b) - (a % -b != 0 ? 1 : 0); - else - return a / b; + if (a < 0) { + return (b < 0) ? + -a / -b : + -(-a / b) - (-a % b != 0 ? 1 : 0); + } else { + return (b < 0) ? + -(a / -b) - (a % -b != 0 ? 1 : 0) : + a / b; + } } if (n == 0) return []; - switch (((n % 3) + 3) % 3) { // (n % 3) is the remainder + switch (((n % 3) + 3) % 3) { // (n % 3) is the remainder. case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); @@ -63,18 +63,16 @@ struct BalancedTernary { } @property BigInt toBint() const { - return reduce!((y,x) => x + 3 * y)(BigInt(0), retro(digits)); + return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const { if (digits.empty) return "0"; - //return map!(d => dig2str[d + 1])(retro(digits)).array(); - auto r = map!(d => cast()dig2str[d+1])(retro(digits)).array(); - return assumeUnique(r); /// + return digits.retro.map!(d => dig2str[d + 1]).array; } static Dig[] neg_(Dig[] digs) { - return map!(d => -d)(digs).array(); + return digs.map!q{ -a }.array; } BalancedTernary opUnary(string op:"-")() { @@ -93,7 +91,7 @@ struct BalancedTernary { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; auto res = add_(a[1 .. $], b[1 .. $], dc[1]); - // trim leading zeros + // Trim leading zeros. if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else diff --git a/Task/Balanced-ternary/Haskell/balanced-ternary.hs b/Task/Balanced-ternary/Haskell/balanced-ternary.hs index da40860af6..6da454b2a2 100644 --- a/Task/Balanced-ternary/Haskell/balanced-ternary.hs +++ b/Task/Balanced-ternary/Haskell/balanced-ternary.hs @@ -29,9 +29,7 @@ strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1 intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger -btInt = f . btList where - f [] = 0 - f (a:as) = a + 3 * f as +btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) @@ -41,8 +39,7 @@ instance Num BalancedTernary where (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] - mul_ [] _ = [] - mul_ (a:as) b = listAdd (map (a*) b) (0:mul_ as b) where + mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as -- we don't need to define binary "-" by hand diff --git a/Task/Best-shuffle/Seed7/best-shuffle.seed7 b/Task/Best-shuffle/Seed7/best-shuffle.seed7 new file mode 100644 index 0000000000..27f9c4c846 --- /dev/null +++ b/Task/Best-shuffle/Seed7/best-shuffle.seed7 @@ -0,0 +1,41 @@ +$ include "seed7_05.s7i"; + +const func string: bestShuffle (in string: stri) is func + result + var string: shuffled is ""; + local + var char: tmp is ' '; + var integer: i is 0; + var integer: j is 0; + begin + shuffled := stri; + for key i range shuffled do + for key j range shuffled do + if i <> j and stri[i] <> shuffled[j] and stri[j] <> shuffled[i] then + tmp := shuffled[i]; + shuffled @:= [i] shuffled[j]; + shuffled @:= [j] tmp; + end if; + end for; + end for; + end func; + +const proc: main is func + local + const array string: testData is [] ("abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"); + var string: original is ""; + var string: shuffled is ""; + var integer: j is 0; + var integer: score is 0; + begin + for original range testData do + shuffled := bestShuffle(original); + score := 0; + for key j range shuffled do + if original[j] = shuffled[j] then + incr(score); + end if; + end for; + writeln(original <& ", " <& shuffled <& ", (" <& score <& ")"); + end for; + end func; diff --git a/Task/Binary-digits/Aime/binary-digits.aime b/Task/Binary-digits/Aime/binary-digits.aime new file mode 100644 index 0000000000..2d43e17b65 --- /dev/null +++ b/Task/Binary-digits/Aime/binary-digits.aime @@ -0,0 +1,8 @@ +o_xinteger(2, 0); +o_byte('\n'); +o_xinteger(2, 5); +o_byte('\n'); +o_xinteger(2, 50); +o_byte('\n'); +o_xinteger(2, 9000); +o_byte('\n'); diff --git a/Task/Binary-digits/Bracmat/binary-digits.bracmat b/Task/Binary-digits/Bracmat/binary-digits.bracmat new file mode 100644 index 0000000000..cea241db6f --- /dev/null +++ b/Task/Binary-digits/Bracmat/binary-digits.bracmat @@ -0,0 +1,17 @@ + ( dec2bin + = bit bits + . :?bits + & whl + ' ( !arg:>0 + & mod$(!arg,2):?bit + & div$(!arg,2):?arg + & !bit !bits:?bits + ) + & (str$!bits:~|0) + ) +& 0 5 50 9000 423785674235000123456789:?numbers +& whl + ' ( !numbers:%?dec ?numbers + & put$(str$(!dec ":\n" dec2bin$!dec \n\n)) + ) +; diff --git a/Task/Binary-digits/COBOL/binary-digits-1.cobol b/Task/Binary-digits/COBOL/binary-digits-1.cobol new file mode 100644 index 0000000000..07df80957e --- /dev/null +++ b/Task/Binary-digits/COBOL/binary-digits-1.cobol @@ -0,0 +1,26 @@ +IDENTIFICATION DIVISION. + PROGRAM-ID. SAMPLE. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 binary_number pic X(21). + 01 str pic X(21). + 01 binary_digit pic X. + 01 digit pic 9. + 01 n pic 9(7). + 01 nstr pic X(7). + + PROCEDURE DIVISION. + accept nstr + move nstr to n + perform until n equal 0 + divide n by 2 giving n remainder digit + move digit to binary_digit + string binary_digit DELIMITED BY SIZE + binary_number DELIMITED BY SPACE + into str + move str to binary_number + end-perform. + display binary_number + stop run. diff --git a/Task/Binary-digits/COBOL/binary-digits-2.cobol b/Task/Binary-digits/COBOL/binary-digits-2.cobol new file mode 100644 index 0000000000..3dc11fedb9 --- /dev/null +++ b/Task/Binary-digits/COBOL/binary-digits-2.cobol @@ -0,0 +1,27 @@ +IDENTIFICATION DIVISION. +PROGRAM-ID. binary-conversion. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 binary-number pic X(21). +01 digit pic 9. +01 n pic 9(7). +01 nstr pic X(7). +01 ptr pic 99. + +PROCEDURE DIVISION. + display "Number: " with no advancing. + accept nstr. + move nstr to n. + move zeroes to binary-number. + move length binary-number to ptr. + perform until n equal 0 + divide n by 2 giving n remainder digit + move digit to binary-number(ptr:1) + subtract 1 from ptr + if ptr < 1 + exit perform + end-if + end-perform. + display binary-number. + stop run. diff --git a/Task/Binary-digits/Fortran/binary-digits.f b/Task/Binary-digits/Fortran/binary-digits.f new file mode 100644 index 0000000000..8c15fd0574 --- /dev/null +++ b/Task/Binary-digits/Fortran/binary-digits.f @@ -0,0 +1,57 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Sun May 19 23:14:14 +! +!a=./F && make $a && $a < unixdict.txt +!f95 -Wall -ffree-form F.F -o F +!101 +!110010 +!10001100101000 +! +!Compilation finished at Sun May 19 23:14:14 +! +! +! tobin=: -.&' '@":@#: +! tobin 5 +!101 +! tobin 50 +!110010 +! tobin 9000 +!10001100101000 + +program bits + implicit none + integer, dimension(3) :: a + integer :: i + data a/5,50,9000/ + do i = 1, 3 + call s(a(i)) + enddo + +contains + + subroutine s(a) + integer, intent(in) :: a + integer :: i + if (a .eq. 0) then + write(6,'(a)')'0' + return + endif + do i = 31, 0, -1 + if (btest(a, i)) exit + enddo + do while (0 .lt. i) + if (btest(a, i)) then + write(6,'(a)',advance='no')'1' + else + write(6,'(a)',advance='no')'0' + endif + i = i-1 + enddo + if (btest(a, i)) then + write(6,'(a)')'1' + else + write(6,'(a)')'0' + endif + end subroutine s + +end program bits diff --git a/Task/Binary-digits/NetRexx/binary-digits.netrexx b/Task/Binary-digits/NetRexx/binary-digits.netrexx index a4118704a0..1e42058361 100644 --- a/Task/Binary-digits/NetRexx/binary-digits.netrexx +++ b/Task/Binary-digits/NetRexx/binary-digits.netrexx @@ -1,12 +1,18 @@ /* NetRexx */ +options replace format comments java crossref symbols nobinary -options replace format comments java crossref savelog symbols nobinary - -nums = [5, 50, 9000] - -loop n_ = 0 to nums.length - 1 - v_ = nums[n_] - say v_.d2x.x2b.strip('L', 0) - end n_ - +runSample(arg) return + +method getBinaryDigits(nr) public static + bd = nr.d2x.x2b.strip('L', 0) + if bd.length = 0 then bd = 0 + return bd + +method runSample(arg) public static + parse arg list + if list = '' then list = '0 5 50 9000' + loop n_ = 1 to list.words + w_ = list.word(n_) + say w_.right(20)':' getBinaryDigits(w_) + end n_ diff --git a/Task/Binary-digits/PL-I/binary-digits-1.pli b/Task/Binary-digits/PL-I/binary-digits-1.pli index dd2046616a..a0452819f2 100644 --- a/Task/Binary-digits/PL-I/binary-digits-1.pli +++ b/Task/Binary-digits/PL-I/binary-digits-1.pli @@ -1 +1 @@ -put list (25) (B); +put edit (25) (B); diff --git a/Task/Binary-digits/Prolog/binary-digits.pro b/Task/Binary-digits/Prolog/binary-digits.pro new file mode 100644 index 0000000000..39612f4198 --- /dev/null +++ b/Task/Binary-digits/Prolog/binary-digits.pro @@ -0,0 +1,2 @@ +binary(X) :- format('~2r~n', [X]). +main :- maplist(binary, [5,50,9000]), halt. diff --git a/Task/Binary-digits/REXX/binary-digits-1.rexx b/Task/Binary-digits/REXX/binary-digits-1.rexx index 6efcaa9091..29170cf9f5 100644 --- a/Task/Binary-digits/REXX/binary-digits-1.rexx +++ b/Task/Binary-digits/REXX/binary-digits-1.rexx @@ -1,11 +1,9 @@ /*REXX program demonstrates converting decimal ───► binary. */ numeric digits 1000 - x.1 = 0 x.2 = 5 x.3 = 50 x.4 = 9000 - do j=1 for 4 y = x2b(d2x(x.j)) + 0 say right(x.j,20) 'decimal, and in binary:' y diff --git a/Task/Binary-digits/REXX/binary-digits-2.rexx b/Task/Binary-digits/REXX/binary-digits-2.rexx index d8ced54a37..1826a5fba7 100644 --- a/Task/Binary-digits/REXX/binary-digits-2.rexx +++ b/Task/Binary-digits/REXX/binary-digits-2.rexx @@ -1,10 +1,8 @@ /*REXX program demonstrates converting decimal ───► binary. */ - x.1 = 0 x.2 = 5 x.3 = 50 x.4 = 9000 - do j=1 for 4 y = strip( x2b( d2x( x.j )), 'L', 0) if y=='' then y=0 diff --git a/Task/Binary-digits/REXX/binary-digits-3.rexx b/Task/Binary-digits/REXX/binary-digits-3.rexx index 63f3f1829a..10ea026a0d 100644 --- a/Task/Binary-digits/REXX/binary-digits-3.rexx +++ b/Task/Binary-digits/REXX/binary-digits-3.rexx @@ -1,5 +1,4 @@ /*REXX program demonstrates converting decimal ───► binary. */ - x.1 = 0 x.2 = 5 x.3 = 50 diff --git a/Task/Binary-digits/Racket/binary-digits.rkt b/Task/Binary-digits/Racket/binary-digits.rkt index ce748521d8..f4f05a4e50 100644 --- a/Task/Binary-digits/Racket/binary-digits.rkt +++ b/Task/Binary-digits/Racket/binary-digits.rkt @@ -1,3 +1,5 @@ #lang racket -(for ([i 16]) - (displayln (number->string i 2))) +;; Option 1: binary formatter +(for ([i 16]) (printf "~b\n" i)) +;; Option 2: explicit conversion +(for ([i 16]) (displayln (number->string i 2))) diff --git a/Task/Binary-search/Brat/binary-search.brat b/Task/Binary-search/Brat/binary-search.brat index 6d86f7d3f5..ef62f367a0 100644 --- a/Task/Binary-search/Brat/binary-search.brat +++ b/Task/Binary-search/Brat/binary-search.brat @@ -1,20 +1,20 @@ binary_search = { search_array, value, low, high | - true? high < low - { null } - { - mid = ((low + high) / 2).to_i - true? search_array[mid] > value - { binary_search search_array, value, low, mid - 1 } - { true? search_array[mid] < value - { binary_search search_array, value, mid + 1, high } - { mid } - } - } + true? high < low + { null } + { + mid = ((low + high) / 2).to_i + + true? search_array[mid] > value + { binary_search search_array, value, low, mid - 1 } + { true? search_array[mid] < value + { binary_search search_array, value, mid + 1, high } + { mid } + } + } } #Populate array -numbers = [] -1000.times { i | numbers << random i } +numbers = 1000.of { random 1000 } #Sort the array numbers.sort! @@ -24,7 +24,7 @@ x = random 1000 p "Looking for #{x}" -index = binary_search numbers, x, 0, numbers.length +index = binary_search numbers, x, 0, numbers.length - 1 null? index { p "Not found" } diff --git a/Task/Binary-search/FBSL/binary-search-1.fbsl b/Task/Binary-search/FBSL/binary-search-1.fbsl new file mode 100644 index 0000000000..c19049d916 --- /dev/null +++ b/Task/Binary-search/FBSL/binary-search-1.fbsl @@ -0,0 +1,22 @@ +#APPTYPE CONSOLE + +DIM va[], sign = {1, -1}, toggle + +PRINT "Loading ... "; +DIM gtc = GetTickCount() +FOR DIM i = 0 TO 1000000 + va[] = sign[toggle] * PI * i + toggle = NOT toggle ' randomize the array +NEXT +PRINT "done in ", GetTickCount() - gtc, " milliseconds" + +PRINT "Sorting ... "; +gtc = GetTickCount() +QUICKSORT(va) ' quick sort the array +PRINT "done in ", GetTickCount() - gtc, " milliseconds" + +gtc = GetTickCount() +PRINT 1000000 * PI, " found at index ", BSEARCH(va, 1000000 * PI), _ ' binary search through the array + " in ", GetTickCount() - gtc, " milliseconds" + +PAUSE diff --git a/Task/Binary-search/FBSL/binary-search-2.fbsl b/Task/Binary-search/FBSL/binary-search-2.fbsl new file mode 100644 index 0000000000..fb06cf02b1 --- /dev/null +++ b/Task/Binary-search/FBSL/binary-search-2.fbsl @@ -0,0 +1,29 @@ +#APPTYPE CONSOLE + +DIM va[] + +PRINT "Loading ... "; +DIM gtc = GetTickCount() +FOR DIM i = 0 TO 1000000: va[] = i * PI: NEXT +PRINT "done in ", GetTickCount() - gtc, " milliseconds" + +gtc = GetTickCount() +PRINT 1000000 * PI, " found at index ", BSearchIter(va, 1000000 * PI), _ + " in ", GetTickCount() - gtc, " milliseconds" + +PAUSE + +FUNCTION BSearchIter(BYVAL array, BYVAL num) + STATIC low = LBOUND(va), high = UBOUND(va) + WHILE low <= high + DIM midp = (high + low) \ 2 + IF array[midp] > num THEN + high = midp - 1 + ELSEIF array[midp] < num THEN + low = midp + 1 + ELSE + RETURN midp + END IF + WEND + RETURN -1 +END FUNCTION diff --git a/Task/Binary-search/FBSL/binary-search-3.fbsl b/Task/Binary-search/FBSL/binary-search-3.fbsl new file mode 100644 index 0000000000..b672683590 --- /dev/null +++ b/Task/Binary-search/FBSL/binary-search-3.fbsl @@ -0,0 +1,25 @@ +#APPTYPE CONSOLE + +DIM va[] + +PRINT "Loading ... "; +DIM gtc = GetTickCount() +FOR DIM i = 0 TO 1000000: va[] = i * PI: NEXT +PRINT "done in ", GetTickCount() - gtc, " milliseconds" + +gtc = GetTickCount() +PRINT 1000000 * PI, " found at index ", BSearchRec(va, 1000000 * PI, LBOUND(va), UBOUND(va)), _ + " in ", GetTickCount() - gtc, " milliseconds" + +PAUSE + +FUNCTION BSearchRec(BYVAL array, BYVAL num, BYVAL low, BYVAL high) + IF high < low THEN RETURN -1 + DIM midp = (high + low) \ 2 + IF array[midp] > num THEN + RETURN BSearchRec(array, num, low, midp - 1) + ELSEIF array[midp] < num THEN + RETURN BSearchRec(array, num, midp + 1, high) + END IF + RETURN midp +END FUNCTION diff --git a/Task/Binary-search/MATLAB/binary-search-3.m b/Task/Binary-search/MATLAB/binary-search-3.m index a8252d9248..cf48733627 100644 --- a/Task/Binary-search/MATLAB/binary-search-3.m +++ b/Task/Binary-search/MATLAB/binary-search-3.m @@ -1,6 +1,6 @@ function mid = binarySearchIter(list,value) - low = 0; + low = 1; high = numel(list) - 1; while( low <= high ) diff --git a/Task/Binary-search/PL-I/binary-search.pli b/Task/Binary-search/PL-I/binary-search.pli index 5c9dc74ac8..bcc2a17147 100644 --- a/Task/Binary-search/PL-I/binary-search.pli +++ b/Task/Binary-search/PL-I/binary-search.pli @@ -4,13 +4,13 @@ search: procedure (A, M) returns (fixed binary); declare (l, r, mid) fixed binary; l = lbound(a,1)-1; r = hbound(A,1)+1; - do while (l+1 < r); + do while (l <= r); mid = (l+r)/2; if A(mid) = M then return (mid); if A(mid) < M then - L = mid; + L = mid+1; else - R = mid; + R = mid-1; end; return (lbound(A,1)-1); end search; diff --git a/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl b/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl index ae82cdfa43..04c790a1c9 100644 --- a/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl +++ b/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl @@ -19,8 +19,11 @@ sub unbase58 { } sub check_bitcoin_address { + # does nothing if the address is valid + # dies otherwise use Digest::SHA qw(sha256); my @byte = unbase58 shift; - die unless join('', map { chr } @byte[21..24]) eq + die "wrong checksum" unless + join('', map { chr } @byte[21..24]) eq substr sha256(sha256 pack 'C*', @byte[0..20]), 0, 4; } diff --git a/Task/Bitcoin-address-validation/Racket/bitcoin-address-validation.rkt b/Task/Bitcoin-address-validation/Racket/bitcoin-address-validation.rkt new file mode 100644 index 0000000000..15646436bb --- /dev/null +++ b/Task/Bitcoin-address-validation/Racket/bitcoin-address-validation.rkt @@ -0,0 +1,44 @@ +#lang racket/base + +;; Same sha-256 interface as the same-named task +(require ffi/unsafe ffi/unsafe/define openssl/libcrypto) +(define-ffi-definer defcrypto libcrypto) +(defcrypto SHA256_Init (_fun _pointer -> _int)) +(defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) +(defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) +(define (sha256 bytes) + (define ctx (malloc 128)) + (define result (make-bytes 32)) + (SHA256_Init ctx) + (SHA256_Update ctx bytes (bytes-length bytes)) + (SHA256_Final result ctx) + result) + +;; base58 decoding +(define base58-digits + (let ([v (make-vector 128 #f)]) + (for ([i (in-naturals)] + [c "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"]) + (vector-set! v (char->integer c) i)) + v)) +(define (base58->integer str) + (for/fold ([n 0]) ([c str]) + (+ (* n 58) (vector-ref base58-digits (char->integer c))))) + +(define (int->bytes n digits) + (list->bytes (let loop ([n n] [digits digits] [acc '()]) + (if (zero? digits) acc + (let-values ([(q r) (quotient/remainder n 256)]) + (loop q (sub1 digits) (cons r acc))))))) + +(define (validate-bitcoin-address str) + (define bs (int->bytes (base58->integer str) 25)) + (equal? (subbytes (sha256 (sha256 (subbytes bs 0 21))) 0 4) + (subbytes bs 21))) + +;; additional tests taken from the other solutions +(validate-bitcoin-address "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i") ; => #t +(validate-bitcoin-address "1111111111111111111114oLvT2") ; => #t +(validate-bitcoin-address "17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j") ; => #t +(validate-bitcoin-address "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9") ; => #t +(validate-bitcoin-address "1badbadbadbadbadbadbadbadbadbadbad") ; => #f diff --git a/Task/Bitmap-B-zier-curves-Cubic/FBSL/bitmap-b-zier-curves-cubic.fbsl b/Task/Bitmap-B-zier-curves-Cubic/FBSL/bitmap-b-zier-curves-cubic.fbsl new file mode 100644 index 0000000000..fedcf3ca0c --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/FBSL/bitmap-b-zier-curves-cubic.fbsl @@ -0,0 +1,57 @@ +#DEFINE WM_LBUTTONDOWN 513 +#DEFINE WM_CLOSE 16 + +FBSLSETTEXT(ME, "Bezier Cubic") +FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color +DRAWWIDTH(5) ' Adjust point size +FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments + +RESIZE(ME, 0, 0, 235, 235) +CENTER(ME) +SHOW(ME) + +DIM Height AS INTEGER +FBSL.GETCLIENTRECT(ME, 0, 0, 0, Height) + +BEGIN EVENTS + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: BezierCube(160, 150, 10, 120, 30, 0, 150, 50, 20) ' Draw + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT +END EVENTS + +SUB BezierCube(x1, y1, x2, y2, x3, y3, x4, y4, n) + TYPE POINTAPI + x AS INTEGER + y AS INTEGER + END TYPE + + DIM t, t1, a, b, c, d, p[n] AS POINTAPI + + FOR DIM i = 0 TO n + t = i / n: t1 = 1 - t + a = t1 ^ 3 + b = 3 * t * t1 ^ 2 + c = 3 * t ^ 2 * t1 + d = t ^ 3 + p[i].x = a * x1 + b * x2 + c * x3 + d * x4 + 0.5 + p[i].y = Height - (a * y1 + b * y2 + c * y3 + d * y4 + 0.5) + NEXT + + FOR i = 0 TO n - 1 + Bresenham(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y) + NEXT + + SUB Bresenham(x0, y0, x1, y1) + DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1) + DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1) + DIM tmp, er = IIF(dx > dy, dx, -dy) / 2 + + WHILE NOT (x0 = x1 ANDALSO y0 = y1) + PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order + tmp = er + IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF + IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF + WEND + END SUB +END SUB diff --git a/Task/Bitmap-B-zier-curves-Cubic/Racket/bitmap-b-zier-curves-cubic.rkt b/Task/Bitmap-B-zier-curves-Cubic/Racket/bitmap-b-zier-curves-cubic.rkt new file mode 100644 index 0000000000..9d427c3ecb --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Racket/bitmap-b-zier-curves-cubic.rkt @@ -0,0 +1,26 @@ +#lang racket +(require racket/draw) + +(define (draw-line dc p q) + (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)])) + +(define (draw-lines dc ps) + (void + (for/fold ([p0 (first ps)]) ([p (rest ps)]) + (draw-line dc p0 p) + p))) + +(define (int t p q) + (define ((int1 t) x0 x1) (+ (* (- 1 t) x0) (* t x1))) + (map (int1 t) p q)) + +(define (bezier-points p0 p1 p2 p3) + (for/list ([t (in-range 0.0 1.0 (/ 1.0 20))]) + (int t (int t p0 p1) (int t p2 p3)))) + +(define bm (make-object bitmap% 17 17)) +(define dc (new bitmap-dc% [bitmap bm])) +(send dc set-smoothing 'unsmoothed) +(send dc set-pen "red" 1 'solid) +(draw-lines dc (bezier-points '(16 1) '(1 4) '(3 16) '(15 11))) +bm diff --git a/Task/Bitmap-B-zier-curves-Quadratic/FBSL/bitmap-b-zier-curves-quadratic.fbsl b/Task/Bitmap-B-zier-curves-Quadratic/FBSL/bitmap-b-zier-curves-quadratic.fbsl new file mode 100644 index 0000000000..e11cea0038 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/FBSL/bitmap-b-zier-curves-quadratic.fbsl @@ -0,0 +1,56 @@ +#DEFINE WM_LBUTTONDOWN 513 +#DEFINE WM_CLOSE 16 + +FBSLSETTEXT(ME, "Bezier Quadratic") +FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color +DRAWWIDTH(5) ' Adjust point size +FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments + +RESIZE(ME, 0, 0, 235, 235) +CENTER(ME) +SHOW(ME) + +DIM Height AS INTEGER +FBSL.GETCLIENTRECT(ME, 0, 0, 0, Height) + +BEGIN EVENTS + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: BezierQuad(10, 100, 250, 270, 150, 20, 20) ' Draw + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT +END EVENTS + +SUB BezierQuad(x1, y1, x2, y2, x3, y3, n) + TYPE POINTAPI + x AS INTEGER + y AS INTEGER + END TYPE + + DIM t, t1, a, b, c, p[n] AS POINTAPI + + FOR DIM i = 0 TO n + t = i / n: t1 = 1 - t + a = t1 ^ 2 + b = 2 * t * t1 + c = t ^ 2 + p[i].x = a * x1 + b * x2 + c * x3 + 0.5 + p[i].y = Height - (a * y1 + b * y2 + c * y3 + 0.5) + NEXT + + FOR i = 0 TO n - 1 + Bresenham(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y) + NEXT + + SUB Bresenham(x0, y0, x1, y1) + DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1) + DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1) + DIM tmp, er = IIF(dx > dy, dx, -dy) / 2 + + WHILE NOT (x0 = x1 ANDALSO y0 = y1) + PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order + tmp = er + IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF + IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF + WEND + END SUB +END SUB diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Racket/bitmap-b-zier-curves-quadratic.rkt b/Task/Bitmap-B-zier-curves-Quadratic/Racket/bitmap-b-zier-curves-quadratic.rkt new file mode 100644 index 0000000000..eea9c51686 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Racket/bitmap-b-zier-curves-quadratic.rkt @@ -0,0 +1,26 @@ +#lang racket +(require racket/draw) + +(define (draw-line dc p q) + (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)])) + +(define (draw-lines dc ps) + (void + (for/fold ([p0 (first ps)]) ([p (rest ps)]) + (draw-line dc p0 p) + p))) + +(define (int t p q) + (define ((int1 t) x0 x1) (+ (* (- 1 t) x0) (* t x1))) + (map (int1 t) p q)) + +(define (bezier-points p0 p1 p2) + (for/list ([t (in-range 0.0 1.0 (/ 1.0 20))]) + (int t (int t p0 p1) (int t p1 p2)))) + +(define bm (make-object bitmap% 17 17)) +(define dc (new bitmap-dc% [bitmap bm])) +(send dc set-smoothing 'unsmoothed) +(send dc set-pen "red" 1 'solid) +(draw-lines dc (bezier-points '(16 1) '(1 4) '(3 16))) +bm diff --git a/Task/Bitmap-Bresenhams-line-algorithm/FBSL/bitmap-bresenhams-line-algorithm.fbsl b/Task/Bitmap-Bresenhams-line-algorithm/FBSL/bitmap-bresenhams-line-algorithm.fbsl new file mode 100644 index 0000000000..f0077cb883 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/FBSL/bitmap-bresenhams-line-algorithm.fbsl @@ -0,0 +1,35 @@ +#DEFINE WM_LBUTTONDOWN 513 +#DEFINE WM_CLOSE 16 + +FBSLSETTEXT(ME, "Bresenham") ' Set form caption +FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: set persistent background color +DRAWWIDTH(5) ' Adjust point size +FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments + +RESIZE(ME, 0, 0, 200, 235) +CENTER(ME) +SHOW(ME) + +BEGIN EVENTS + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: Rhombus() ' Draw + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT +END EVENTS + +SUB Rhombus() + Bresenham(50, 100, 100, 190)(100, 190, 150, 100)(150, 100, 100, 10)(100, 10, 50, 100) + + SUB Bresenham(x0, y0, x1, y1) + DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1) + DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1) + DIM tmp, er = IIF(dx > dy, dx, -dy) / 2 + + WHILE NOT (x0 = x1 ANDALSO y0 = y1) + PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order + tmp = er + IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF + IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF + WEND + END SUB +END SUB diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Racket/bitmap-bresenhams-line-algorithm.rkt b/Task/Bitmap-Bresenhams-line-algorithm/Racket/bitmap-bresenhams-line-algorithm.rkt new file mode 100644 index 0000000000..323bceb6af --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Racket/bitmap-bresenhams-line-algorithm.rkt @@ -0,0 +1,33 @@ +#lang racket +(require racket/draw) + +(define (draw-line dc x0 y0 x1 y1) + (define dx (abs (- x1 x0))) + (define dy (abs (- y1 y0))) + (define sx (if (> x0 x1) -1 1)) + (define sy (if (> y0 y1) -1 1)) + (cond + [(> dx dy) + (let loop ([x x0] [y y0] [err (/ dx 2.0)]) + (unless (= x x1) + (send dc draw-point x y) + (define newerr (- err dy)) + (if (< newerr 0) + (loop (+ x sx) (+ y sy) (+ newerr dx)) + (loop (+ x sx) y newerr))))] + [else + (let loop ([x x0] [y y0] [err (/ dy 2.0)]) + (unless (= y y1) + (send dc draw-point x y) + (define newerr (- err dy)) + (if (< newerr 0) + (loop (+ x sx) (+ y sy) newerr) + (loop x (+ y sy) (+ newerr dy)))))])) + +(define bm (make-object bitmap% 17 17)) +(define dc (new bitmap-dc% [bitmap bm])) +(send dc set-smoothing 'unsmoothed) +(send dc set-pen "red" 1 'solid) +(for ([points '((1 8 8 16) (8 16 16 8) (16 8 8 1) (8 1 1 8))]) + (apply draw-line (cons dc points))) +bm diff --git a/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl b/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl new file mode 100644 index 0000000000..2cc3085c3c --- /dev/null +++ b/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl @@ -0,0 +1,37 @@ +#DEFINE WM_LBUTTONDOWN 513 +#DEFINE WM_CLOSE 16 + +FBSLSETTEXT(ME, "Before Flood Fill") ' Set form caption +FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color +FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments + +RESIZE(ME, 0, 0, 220, 220) +CENTER(ME) +SHOW(ME) + +DIM Breadth AS INTEGER, Height AS INTEGER +FBSL.GETCLIENTRECT(ME, 0, 0, Breadth, Height) + +DrawCircles() ' Initialize circles + +BEGIN EVENTS + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: FillCircles() ' Flood fill circles + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT +END EVENTS + +SUB FillCircles() + FILL(FBSL.GETDC, Breadth / 2, Height / 2, &HFFFF) ' Yellow: flood fill using intrinsics + FOR DIM x = 0 TO Breadth / 2 ' Red: flood fill iteratively + FOR DIM y = 0 TO Height / 2 + IF NOT POINT(FBSL.GETDC, x, y) THEN PSET(FBSL.GETDC, x, y, &HFF) + NEXT + NEXT + FBSLSETTEXT(ME, "After Flood Fill") ' Reset form caption +END SUB + +SUB DrawCircles() ' Concatenate function calls + CIRCLE(FBSL.GETDC, Breadth / 2, Height / 2, 85, &HFFFFFF, 0, 360, 1, TRUE) _ ' White + (FBSL.GETDC, Breadth / 3, Height / 3, 30, 0, 0, 360, 1, TRUE) ' Black +END SUB diff --git a/Task/Bitmap-Histogram/FBSL/bitmap-histogram.fbsl b/Task/Bitmap-Histogram/FBSL/bitmap-histogram.fbsl new file mode 100644 index 0000000000..caccb395fa --- /dev/null +++ b/Task/Bitmap-Histogram/FBSL/bitmap-histogram.fbsl @@ -0,0 +1,50 @@ +#DEFINE WM_CLOSE 16 + +DIM colored = ".\LenaClr.bmp", grayscale = ".\LenaGry.bmp", blackwhite = ".\LenaBnw.bmp" +DIM head, tail, r, g, b, l, m, ptr, blobsize = 54 ' sizeof BMP headers + +FILEGET(FILEOPEN(colored, BINARY), FILELEN(colored)): FILECLOSE(FILEOPEN) ' fill buffer +head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' get buffer bounds + +ToGrayScale() ' derive grayscale image and save it to disk +ToBlackAndWhite() ' ditto, black-and-white image + +FBSLSETTEXT(ME, "Clr") ' display colored image +FBSLTILE(ME, FBSLLOADIMAGE(colored)) +RESIZE(ME, 0, 0, 136, 162): CENTER(ME): SHOW(ME) + +FBSLTILE(FBSLFORM("Gry"), FBSLLOADIMAGE(grayscale)) ' ditto, grayscale +RESIZE(FBSLFORM, 0, 0, 136, 162): CENTER(FBSLFORM): SHOW(FBSLFORM) + +FBSLTILE(FBSLFORM("B/w"), FBSLLOADIMAGE(blackwhite)) ' ditto, black-and-white +RESIZE(FBSLFORM, 0, 0, 136, 162): CENTER(FBSLFORM): SHOW(FBSLFORM) + +BEGIN EVENTS ' main message loop + IF CBMSG = WM_CLOSE THEN DESTROY(ME) ' click any [X] button to quit +END EVENTS + +SUB ToGrayScale() + FOR ptr = head TO tail STEP 3 + b = PEEK(ptr + 0, 1) ' Windows stores colors in BGR order + g = PEEK(ptr + 1, 1) + r = PEEK(ptr + 2, 1) + l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' derive luminance + POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' set pixel to shade of gray + m = m + l + NEXT + FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save grayscale image +END SUB + +SUB ToBlackAndWhite() + STATIC b = CHR(0), w = CHR(255) ' initialize once + + m = m / (tail - head) * 3 ' derive median + FOR ptr = head TO tail STEP 3 + IF PEEK(ptr + 0, 1) < m THEN ' set pixel black + POKE(ptr + 0, b)(ptr + 1, b)(ptr + 2, b) + ELSE ' set pixel white + POKE(ptr + 0, w)(ptr + 1, w)(ptr + 2, w) + END IF + NEXT + FILEPUT(FILEOPEN(blackwhite, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save b/w image +END SUB diff --git a/Task/Bitmap-Midpoint-circle-algorithm/BBC-BASIC/bitmap-midpoint-circle-algorithm-4.bbc b/Task/Bitmap-Midpoint-circle-algorithm/BBC-BASIC/bitmap-midpoint-circle-algorithm-4.bbc new file mode 100644 index 0000000000..e8525915f3 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/BBC-BASIC/bitmap-midpoint-circle-algorithm-4.bbc @@ -0,0 +1,48 @@ + /// + /// Draws a circle. + /// + /// + /// The destination image. + /// + /// + /// The x center position of the circle. + /// + /// + /// The y center position of the circle. + /// + /// + /// The radius of the circle. + /// + /// + /// The color to use. + /// + public static void DrawCircle(this GenericImage image, int centerX, int centerY, int radius, Color color) + { + int d = (5 - radius * 4) / 4; + int x = 0; + int y = radius; + + do + { + // ensure index is in range before setting (depends on your image implementation) + // in this case we check if the pixel location is within the bounds of the image before setting the pixel + if (centerX + x >= 0 && centerX + x <= image.Width - 1 && centerY + y >= 0 && centerY + y <= image.Height - 1) image[centerX + x, centerY + y] = color; + if (centerX + x >= 0 && centerX + x <= image.Width - 1 && centerY - y >= 0 && centerY - y <= image.Height - 1) image[centerX + x, centerY - y] = color; + if (centerX - x >= 0 && centerX - x <= image.Width - 1 && centerY + y >= 0 && centerY + y <= image.Height - 1) image[centerX - x, centerY + y] = color; + if (centerX - x >= 0 && centerX - x <= image.Width - 1 && centerY - y >= 0 && centerY - y <= image.Height - 1) image[centerX - x, centerY - y] = color; + if (centerX + y >= 0 && centerX + y <= image.Width - 1 && centerY + x >= 0 && centerY + x <= image.Height - 1) image[centerX + y, centerY + x] = color; + if (centerX + y >= 0 && centerX + y <= image.Width - 1 && centerY - x >= 0 && centerY - x <= image.Height - 1) image[centerX + y, centerY - x] = color; + if (centerX - y >= 0 && centerX - y <= image.Width - 1 && centerY + x >= 0 && centerY + x <= image.Height - 1) image[centerX - y, centerY + x] = color; + if (centerX - y >= 0 && centerX - y <= image.Width - 1 && centerY - x >= 0 && centerY - x <= image.Height - 1) image[centerX - y, centerY - x] = color; + if (d < 0) + { + d += 2 * x + 1; + } + else + { + d += 2 * (x - y) + 1; + y--; + } + x++; + } while (x <= y); + } diff --git a/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl b/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl new file mode 100644 index 0000000000..4ab0e557c9 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl @@ -0,0 +1,41 @@ +#DEFINE WM_LBUTTONDOWN 513 +#DEFINE WM_CLOSE 16 + +FBSLSETTEXT(ME, "Bresenham Circle") ' Set form caption +FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color +FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments + +RESIZE(ME, 0, 0, 220, 220) +CENTER(ME) +SHOW(ME) + +DIM Breadth AS INTEGER, Height AS INTEGER +FBSL.GETCLIENTRECT(ME, 0, 0, Breadth, Height) + +BEGIN EVENTS ' Main message loop + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: MidpointCircle() ' Draw + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT +END EVENTS + +SUB MidpointCircle() + BresenhamCircle(Breadth \ 2, Height \ 2, 80, &HFF) ' Red: Windows stores colors in BGR order + BresenhamCircle(Breadth \ 2, Height \ 2, 40, 0) ' Black + + SUB BresenhamCircle(cx, cy, radius, colour) + DIM x = 0, y = radius, f = 1 - radius, dx = 0, dy = -2 * radius + + PSET(FBSL.GETDC, cx, cy + radius, colour)(FBSL.GETDC, cx, cy - radius, colour) + PSET(FBSL.GETDC, cx + radius, cy, colour)(FBSL.GETDC, cx - radius, cy, colour) + + WHILE x < y + IF f >= 0 THEN: DECR(y): INCR(dy, 2)(f, dy): END IF ' Try also "IF f THEN" :) + INCR(x)(dx, 2)(f, dx + 1) + PSET(FBSL.GETDC, cx + x, cy + y, colour)(FBSL.GETDC, cx - x, cy + y, colour) + PSET(FBSL.GETDC, cx + x, cy - y, colour)(FBSL.GETDC, cx - x, cy - y, colour) + PSET(FBSL.GETDC, cx + y, cy + x, colour)(FBSL.GETDC, cx - y, cy + x, colour) + PSET(FBSL.GETDC, cx + y, cy - x, colour)(FBSL.GETDC, cx - y, cy - x, colour) + WEND + END SUB +END SUB diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Racket/bitmap-midpoint-circle-algorithm.rkt b/Task/Bitmap-Midpoint-circle-algorithm/Racket/bitmap-midpoint-circle-algorithm.rkt new file mode 100644 index 0000000000..410b73e134 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Racket/bitmap-midpoint-circle-algorithm.rkt @@ -0,0 +1,43 @@ +#lang racket +(require racket/draw) + +(define-syntax ⊕ (syntax-rules () [(_ id e) (set! id (+ id e))])) + +(define (draw-point dc x y) + (send dc draw-point x y)) + +(define (draw-circle dc x0 y0 r) + (define f (- 1 r)) + (define ddf_x 1) + (define ddf_y (* -2 r)) + (define x 0) + (define y r) + (draw-point dc x0 (+ y0 r)) + (draw-point dc x0 (- y0 r)) + (draw-point dc (+ x0 r) y0) + (draw-point dc (- x0 r) y0) + (let loop () + (when (< x y) + (when (>= f 0) + (⊕ y -1) + (⊕ ddf_y 2) + (⊕ f ddf_y)) + (⊕ x 1) + (⊕ ddf_x 2) + (⊕ f ddf_x) + (draw-point dc (+ x0 x) (+ y0 y)) + (draw-point dc (- x0 x) (+ y0 y)) + (draw-point dc (+ x0 x) (- y0 y)) + (draw-point dc (- x0 x) (- y0 y)) + (draw-point dc (+ x0 y) (+ y0 x)) + (draw-point dc (- x0 y) (+ y0 x)) + (draw-point dc (+ x0 y) (- y0 x)) + (draw-point dc (- x0 y) (- y0 x)) + (loop)))) + +(define bm (make-object bitmap% 25 25)) +(define dc (new bitmap-dc% [bitmap bm])) +(send dc set-smoothing 'unsmoothed) +(send dc set-pen "red" 1 'solid) +(draw-circle dc 12 12 12) +bm diff --git a/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl b/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl new file mode 100644 index 0000000000..b2d7f3528e --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl @@ -0,0 +1,18 @@ +#ESCAPECHARS ON + +DIM colored = ".\\Lena.ppm", grayscale = ".\\LenaGry.ppm" +DIM head, tail, r, g, b, l, ptr, blobsize + +FILEGET(FILEOPEN(colored, BINARY), FILELEN(colored)): FILECLOSE(FILEOPEN) ' Load buffer +blobsize = INSTR(FILEGET, "\n255\n") + 4 ' Get sizeof PPM header +head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' Set loop bounds + +FOR ptr = head TO tail STEP 3 ' Transform color triplets + r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order + g = PEEK(ptr + 1, 1) + b = PEEK(ptr + 2, 1) + l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance + POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale +NEXT + +FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer diff --git a/Task/Bitmap-Read-a-PPM-file/Racket/bitmap-read-a-ppm-file.rkt b/Task/Bitmap-Read-a-PPM-file/Racket/bitmap-read-a-ppm-file.rkt new file mode 100644 index 0000000000..55371d2e9b --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Racket/bitmap-read-a-ppm-file.rkt @@ -0,0 +1,22 @@ +#lang racket +(require racket/draw) + +(define (read-ppm port) + (parameterize ([current-input-port port]) + (define magic (read)) + (define width (read)) + (define height (read)) + (define maxcol (read)) + (define bm (make-object bitmap% width height)) + (define dc (new bitmap-dc% [bitmap bm])) + (send dc set-smoothing 'unsmoothed) + (define (adjust v) (* 255 (/ v maxcol))) + (for/list ([x width]) + (for/list ([y height]) + (define red (read)) + (define green (read)) + (define blue (read)) + (define color (make-object color% (adjust red) (adjust green) (adjust blue))) + (send dc set-pen color 1 'solid) + (send dc draw-point x y))) + bm)) diff --git a/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl b/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl new file mode 100644 index 0000000000..2c7f0057d2 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl @@ -0,0 +1,23 @@ +#ESCAPECHARS ON + +DIM bmpin = ".\\LenaClr.bmp", ppmout = ".\\Lena.ppm", bmpblob = 54 ' Size of BMP file headers +FILEGET(FILEOPEN(bmpin, BINARY), FILELEN(bmpin)): FILECLOSE(FILEOPEN) ' Fill buffer + +DIM ppmheader AS STRING * 256, breadth, height +LET(breadth, height) = 128 ' Image width and height +SPRINTF(ppmheader, "P6\n%d %d\n255\n", breadth, height) ' Create PPM file header + +DIM ppmdata AS STRING * (STRLEN(ppmheader) + FILELEN - bmpblob) +DIM head = @ppmdata + STRLEN, tail = @FILEGET + FILELEN - breadth * 3 - 2 ' Start of last scanline +ppmdata = ppmheader ' Copy PPM file header + +WHILE tail >= @FILEGET + bmpblob ' Flip upside down + FOR DIM w = 0 TO (breadth - 1) * 3 STEP 3 + POKE(head + 0 + w, CHR(PEEK(tail + 2 + w, 1))) ' Swap R + POKE(head + 1 + w, CHR(PEEK(tail + 1 + w, 1))) ' Keep G + POKE(head + 2 + w, CHR(PEEK(tail + 0 + w, 1))) ' Swap B + NEXT + INCR(head, breadth * 3): DECR(tail, breadth * 3) ' Next scanline +WEND + +FILEPUT(FILEOPEN(ppmout, BINARY_NEW), ppmdata): FILECLOSE(FILEOPEN) diff --git a/Task/Bitmap/FBSL/bitmap.fbsl b/Task/Bitmap/FBSL/bitmap.fbsl new file mode 100644 index 0000000000..910530fbc6 --- /dev/null +++ b/Task/Bitmap/FBSL/bitmap.fbsl @@ -0,0 +1,22 @@ +#DEFINE WM_LBUTTONDOWN 513 +#DEFINE WM_RBUTTONDOWN 516 +#DEFINE WM_CLOSE 16 + +FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: set persistent background color +DRAWWIDTH(5) ' Adjust point size +FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments + +RESIZE(ME, 0, 0, 300, 200) +CENTER(ME) +SHOW(ME) + +BEGIN EVENTS + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN ' Set color at current coords as hex literal + PSET(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM), &H0000FF) ' Red: Windows stores colors in BGR order + CASE WM_RBUTTONDOWN ' Get color at current coords as hex literal + FBSLSETTEXT(ME, "&H" & HEX(POINT(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM)))) + CASE WM_CLOSE ' Clean up + FBSL.RELEASEDC(ME, FBSL.GETDC) + END SELECT +END EVENTS diff --git a/Task/Boolean-values/Julia/boolean-values-1.julia b/Task/Boolean-values/Julia/boolean-values-1.julia new file mode 100644 index 0000000000..0777fd1564 --- /dev/null +++ b/Task/Boolean-values/Julia/boolean-values-1.julia @@ -0,0 +1,9 @@ +julia> t = true +true + +julia> typeof(t) +Bool +julia> if 1 + println("true") + end +ERROR: type: non-boolean (Int64) used in boolean context diff --git a/Task/Boolean-values/Julia/boolean-values-2.julia b/Task/Boolean-values/Julia/boolean-values-2.julia new file mode 100644 index 0000000000..43d20dbd5a --- /dev/null +++ b/Task/Boolean-values/Julia/boolean-values-2.julia @@ -0,0 +1,13 @@ +julia> bool +# methods for generic function bool +bool(x::Bool) at bool.jl:9 +bool(x::Number) at bool.jl:10 +bool(x::AbstractArray{Bool,N}) at abstractarray.jl:219 +bool(x::AbstractArray{T,N}) at abstractarray.jl:220 +julia> bool(-2:2) +5-element Bool Array: + true + true + false + true + true diff --git a/Task/Boolean-values/Raven/boolean-values.raven b/Task/Boolean-values/Raven/boolean-values.raven new file mode 100644 index 0000000000..a1185f0643 --- /dev/null +++ b/Task/Boolean-values/Raven/boolean-values.raven @@ -0,0 +1,5 @@ +TRUE print +FALSE print +2 1 > print # TRUE (-1) +3 2 < print # FALSE (0) +42 FALSE != # TRUE (-1) diff --git a/Task/Brownian-tree/C++/brownian-tree.cpp b/Task/Brownian-tree/C++/brownian-tree.cpp new file mode 100644 index 0000000000..8c9ebd1be1 --- /dev/null +++ b/Task/Brownian-tree/C++/brownian-tree.cpp @@ -0,0 +1,287 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +enum states { SEED, GROWING, MOVING, REST }; +enum treeStates { NONE, MOVER, TREE }; +const int MAX_SIDE = 480, MAX_MOVERS = 511, MAX_CELLS = 15137; + +//-------------------------------------------------------------------------------------------------- +class point +{ +public: + point() { x = y = 0; } + point( int a, int b ) { x = a; y = b; } + void set( int a, int b ) { x = a; y = b; } + + int x, y; +}; +//-------------------------------------------------------------------------------------------------- +class movers +{ +public: + point pos; + bool moving; + movers() : moving( false ){} +}; +//-------------------------------------------------------------------------------------------------- +class myBitmap +{ +public: + myBitmap() : pen( NULL ) {} + ~myBitmap() + { + DeleteObject( pen ); + DeleteDC( hdc ); + DeleteObject( bmp ); + } + + bool create( int w, int h ) + { + BITMAPINFO bi; + ZeroMemory( &bi, sizeof( bi ) ); + + bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); + bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biWidth = w; + bi.bmiHeader.biHeight = -h; + + HDC dc = GetDC( GetConsoleWindow() ); + bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); + if( !bmp ) return false; + + hdc = CreateCompatibleDC( dc ); + SelectObject( hdc, bmp ); + ReleaseDC( GetConsoleWindow(), dc ); + + width = w; height = h; + + return true; + } + + void clear() + { + ZeroMemory( pBits, width * height * sizeof( DWORD ) ); + } + + void setPenColor( DWORD clr ) + { + if( pen ) DeleteObject( pen ); + pen = CreatePen( PS_SOLID, 1, clr ); + SelectObject( hdc, pen ); + } + + void saveBitmap( string path ) + { + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + DWORD* dwpBits; + DWORD wb; + HANDLE file; + + GetObject( bmp, sizeof( bitmap ), &bitmap ); + + dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; + ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); + ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); + ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); + + infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + infoheader.bmiHeader.biCompression = BI_RGB; + infoheader.bmiHeader.biPlanes = 1; + infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); + infoheader.bmiHeader.biHeight = bitmap.bmHeight; + infoheader.bmiHeader.biWidth = bitmap.bmWidth; + infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); + + fileheader.bfType = 0x4D42; + fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); + fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; + + GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); + + file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); + WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); + WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); + CloseHandle( file ); + + delete [] dwpBits; + } + + HDC getDC() { return hdc; } + int getWidth() { return width; } + int getHeight() { return height; } + +private: + HBITMAP bmp; + HDC hdc; + HPEN pen; + void *pBits; + int width, height; +}; +//-------------------------------------------------------------------------------------------------- +class brownianTree +{ +public: + brownianTree() + { + _bmp.create( MAX_SIDE, MAX_SIDE ); + init(); + } + + void init() + { + _cellCount = 0; + ZeroMemory( _grid, sizeof( _grid ) ); + _bmp.clear(); + _state = SEED; + } + +bool mainLoop() + { + switch( _state ) + { + case REST: saveTree(); return false; + case SEED: doSeed(); break; + case GROWING: startMovers(); break; + case MOVING: moveMovers(); + } + return true; + } + + myBitmap* getBmp() { return &_bmp; } + +private: + void saveTree() + { + for( int y = 0; y < MAX_SIDE; y++ ) + for( int x = 0; x < MAX_SIDE; x++ ) + if( _grid[x][y] == TREE ) + SetPixel( _bmp.getDC(), x, y, RGB( 255, 120, 0 ) ); + + _bmp.saveBitmap( "f:\\rc\\tree.bmp" ); + } + + void doSeed() + { + int x = MAX_SIDE - MAX_SIDE / 2, y = MAX_SIDE / 4; + _grid[rand() % x + y][rand() % x + y] = TREE; + _cellCount++; + _state = GROWING; + } + + void addMover( movers* m ) + { + m->moving = true; + int x = MAX_SIDE - MAX_SIDE / 2, y = MAX_SIDE / 4, a, b; + while( true ) + { + a = rand() % x + y; b = rand() % x + y; + if( _grid[a][b] == NONE ) break; + } + + m->pos.set( a, b ); + _grid[a][b] = MOVER; + } + + void startMovers() + { + movers* m; + for( int c = 0; c < MAX_MOVERS; c++ ) + { + m = &_movers[c]; + addMover( m ); + } + _state = MOVING; + } + + void addToTree( movers* m ) + { + m->moving = false; + _grid[m->pos.x][m->pos.y] = TREE; + if( ++_cellCount >= MAX_CELLS ) _state = REST; + + COORD c = { 0, 1 }; + SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); + cout << "Cells added: " << _cellCount << " from " << MAX_CELLS << " => " << static_cast( 100 * _cellCount ) / static_cast( MAX_CELLS ) << "% "; + } + + bool moveIt( movers* m ) + { + point f[8]; int ff = 0; + for( int y = -1; y < 2; y++ ) + { + for( int x = -1; x < 2; x++ ) + { + if( !x && !y ) continue; + int a = m->pos.x + x, b = m->pos.y + y; + if( a < 0 || b < 0 || a >= MAX_SIDE || b >= MAX_SIDE ) + { + addToTree( m ); + return true; + } + switch( _grid[a][b] ) + { + case TREE: + addToTree( m ); + return true; + case NONE: + f[ff++].set( a, b ); + } + } + } + + if( ff < 1 ) return false; + + _grid[m->pos.x][m->pos.y] = NONE; + m->pos = f[rand() % ff]; + _grid[m->pos.x][m->pos.y] = MOVER; + + return false; + } + + void moveMovers() + { + movers* mm; + for( int m = 0; m < MAX_MOVERS; m++ ) + { + mm = &_movers[m]; + if( !mm->moving ) continue; + if( moveIt( mm ) && _cellCount < MAX_CELLS ) addMover( mm ); + } + } + + states _state; + BYTE _grid[MAX_SIDE][MAX_SIDE]; + myBitmap _bmp; + int _cellCount; + movers _movers[MAX_MOVERS]; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); + srand( GetTickCount() ); + + brownianTree tree; + + DWORD now = GetTickCount(); + while( tree.mainLoop() ); + + now = GetTickCount() - now; + cout << endl << endl << "It took " << now / 1000 << " seconds to complete the task!" << endl << endl; + + BitBlt( GetDC( GetConsoleWindow() ), 20, 90, MAX_SIDE, MAX_SIDE, tree.getBmp()->getDC(), 0, 0, SRCCOPY ); + + system( "pause" ); + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Brownian-tree/Perl-6/brownian-tree.pl6 b/Task/Brownian-tree/Perl-6/brownian-tree.pl6 new file mode 100644 index 0000000000..dcb96b3b36 --- /dev/null +++ b/Task/Brownian-tree/Perl-6/brownian-tree.pl6 @@ -0,0 +1,72 @@ +constant size = 100; +constant particlenum = 1_000; + + +constant mid = size div 2; + +my $spawnradius = 5; +my @map; + +sub set($x, $y) { + @map[$x][$y] = True; +} + +sub get($x, $y) { + return @map[$x][$y] || False; +} + +set(mid, mid); +my @blocks = " ","\c[UPPER HALF BLOCK]", "\c[LOWER HALF BLOCK]","\c[FULL BLOCK]"; + +sub infix:<█>($a, $b) { + @blocks[$a + 2 * $b] +} + +sub display { + my $start = 0; + my $end = size; + say (for $start, $start + 2 ... $end -> $y { + (for $start..$end -> $x { + if abs(($x&$y) - mid) < $spawnradius { + get($x, $y) █ get($x, $y+1); + } else { + " " + } + }).join + }).join("\n") +} + +for ^particlenum -> $progress { + my Int $x; + my Int $y; + my &reset = { + repeat { + ($x, $y) = (mid - $spawnradius..mid + $spawnradius).pick, (mid - $spawnradius, mid + $spawnradius).pick; + ($x, $y) = ($y, $x) if (True, False).pick(); + } while get($x,$y); + } + reset; + + while not get($x-1|$x|$x+1, $y-1|$y|$y+1) { + $x = ($x-1, $x, $x+1).pick; + $y = ($y-1, $y, $y+1).pick; + if (False xx 3, True).pick { + $x = $x >= mid ?? $x - 1 !! $x + 1; + $y = $y >= mid ?? $y - 1 !! $y + 1; + } + if abs(($x | $y) - mid) > $spawnradius { + reset; + } + } + set($x,$y); + display if $progress %% 50; + if $spawnradius < mid && abs(($x|$y) - mid) > $spawnradius - 5 { + $spawnradius = $spawnradius + 1; + } +} + +say ""; +display; +say ""; +say "time elapsed: ", (now - BEGIN { now }).Num.fmt("%.2f"), " seconds"; +say ""; diff --git a/Task/Bulls-and-cows-Player/C++/bulls-and-cows-player.cpp b/Task/Bulls-and-cows-Player/C++/bulls-and-cows-player.cpp new file mode 100644 index 0000000000..41ef9c1df6 --- /dev/null +++ b/Task/Bulls-and-cows-Player/C++/bulls-and-cows-player.cpp @@ -0,0 +1,119 @@ +#include +#include +#include +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +const unsigned int LEN = 4; + +//-------------------------------------------------------------------------------------------------- +class CowsAndBulls_Player +{ +public: + CowsAndBulls_Player() { fillPool(); } + void play() { secret = createSecret(); guess(); } + +private: + void guess() + { + pair res; int cc = 1; + cout << endl << " SECRET: " << secret << endl << "==============" << endl; + cout << "+-----------+---------+--------+\n| GUESS | BULLS | COWS |\n+-----------+---------+--------+\n"; + while( true ) + { + string gs = gimmeANumber(); + if( gs.empty() ) { cout << endl << "Something went wrong with the scoring..." << endl << "Cannot find an answer!" << endl; return; } + if( scoreIt( gs, res ) ) { cout << endl << "I found the secret number!" << endl << "It is: " << gs << endl; return; } + cout << "| " << gs << " | " << setw( 3 ) << res.first << " | " << setw( 3 ) << res.second << " |\n+-----------+---------+--------+\n"; + clearPool( gs, res ); + } + } + + void clearPool( string gs, pair& r ) + { + vector::iterator pi = pool.begin(); + while( pi != pool.end() ) + { + if( removeIt( gs, ( *pi ), r ) ) pi = pool.erase( pi ); + else pi++; + } + } + + string gimmeANumber() + { + if( pool.empty() ) return ""; + return pool[rand() % pool.size()]; + } + + void fillPool() + { + for( int x = 1234; x < 9877; x++ ) + { + ostringstream oss; oss << x; + if( check( oss.str() ) ) pool.push_back( oss.str() ); + } + } + + bool check( string s ) + { + for( string::iterator si = s.begin(); si != s.end(); si++ ) + { + if( ( *si ) == '0' ) return false; + if( count( s.begin(), s.end(), ( *si ) ) > 1 ) return false; + } + return true; + } + + bool removeIt( string gs, string ts, pair& res ) + { + pair tp; getScore( gs, ts, tp ); + return tp != res; + } + + bool scoreIt( string gs, pair& res ) + { + getScore( gs, secret, res ); + return res.first == LEN; + } + + void getScore( string gs, string st, pair& pr ) + { + pr.first = pr.second = 0; + for( unsigned int ui = 0; ui < LEN; ui++ ) + { + if( gs[ui] == st[ui] ) pr.first++; + else + { + for( unsigned int vi = 0; vi < LEN; vi++ ) + if( gs[ui] == st[vi] ) pr.second++; + } + } + } + + string createSecret() + { + string n = "123456789", rs = ""; + while( rs.length() < LEN ) + { + int r = rand() % n.length(); + rs += n[r]; n.erase( r, 1 ); + } + return rs; + } + + string secret; + vector pool; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + srand( static_cast( time( NULL ) ) ); CowsAndBulls_Player cb; + cb.play(); cout << endl << endl; + return system( "pause" ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Bulls-and-cows/D/bulls-and-cows.d b/Task/Bulls-and-cows/D/bulls-and-cows.d index 11d22c87db..76b9e55cfe 100644 --- a/Task/Bulls-and-cows/D/bulls-and-cows.d +++ b/Task/Bulls-and-cows/D/bulls-and-cows.d @@ -3,21 +3,21 @@ import std.stdio, std.random, std.string, std.algorithm, void main() { enum size = 4; - dchar[] ddigits = "123456789"d.dup; - //immutable chosen = array(randomCover(ddigits))[0 .. size]; - const chosen = randomCover(ddigits, rndGen).take(size).array(); + immutable ddigits = "123456789"d; + //immutable chosen = ddigits.randomCover.take(size).array; + const chosen = ddigits.randomCover(rndGen).take(size).array; writeln("Guess a number composed of ", size, " unique digits from 1 to 9 in random order."); - int nGuesses; + uint nGuesses; while (true) { nGuesses++; dstring guess; while (true) { writef("\nNext guess (%d): ", nGuesses); - guess = readln().strip().dtext(); + guess = readln.strip.dtext; if (guess.countchars(ddigits) == size && - guess.dup.sort().uniq().walkLength() == size) + guess.dup.sort().uniq.walkLength == size) break; writefln("I need %d unique digits from 1 to 9, no spaces", size); } @@ -27,10 +27,10 @@ void main() { break; } - immutable bulls = count!q{ a[0] == a[1] }(zip(guess, chosen)); - immutable cows = count!(i => guess[i] != chosen[i] && - chosen.canFind(guess[i])) - (iota(size)); + immutable bulls = zip(guess, chosen).count!q{ a[0] == a[1] }; + immutable cows = iota(size) + .count!(i => guess[i] != chosen[i] && + chosen.canFind(guess[i])); writefln(" %d Bulls\n %d Cows", bulls, cows); } } diff --git a/Task/Bulls-and-cows/Julia/bulls-and-cows.julia b/Task/Bulls-and-cows/Julia/bulls-and-cows.julia index adbc927e0a..bc1a5add6f 100644 --- a/Task/Bulls-and-cows/Julia/bulls-and-cows.julia +++ b/Task/Bulls-and-cows/Julia/bulls-and-cows.julia @@ -1,18 +1,28 @@ function cowsbulls() - print("Welcome to Cows & Bulls! I've picked a 4 digit number, go ahead and type your guess.\n + print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n You get one bull for every right number in the right position.\n - You get one cow for every right number in the wrong position.\n + You get one cow for every right number, but in the wrong position.\n Enter 'n' to pick a new number and 'q' to quit.\n>") - new_number() = string(rand(1:9))*string(rand(1:9))*string(rand(1:9))*string(rand(1:9)) + function new_number() + s = [1:9] + n = "" + for i = 9:-1:6 + n *= string(delete!(s,rand(1:i))) + end + return n + end answer = new_number() while true input = chomp(readline(STDIN)) input == "q" && break - input == "n" && begin answer = new_number(); print("\nLet's try again, go ahead and guess\n>"); continue end - !ismatch(r"^[1-9]{4}$",string(input)) && begin print("Invalid guess: Please enter a 4-digit number\n"); continue end + if input == "n" + answer = new_number() + print("\nI've picked a new number, go ahead and guess\n>") + continue + end + !ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue) if input == answer print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>") - continue else bulls = sum(answer.data .== input.data) cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4]) diff --git a/Task/Bulls-and-cows/OCaml/bulls-and-cows.ocaml b/Task/Bulls-and-cows/OCaml/bulls-and-cows.ocaml index b3d1df99e6..3a04a64dbe 100644 --- a/Task/Bulls-and-cows/OCaml/bulls-and-cows.ocaml +++ b/Task/Bulls-and-cows/OCaml/bulls-and-cows.ocaml @@ -1,4 +1,4 @@ -let rec input() = +let rec input () = let s = read_line () in try if String.length s <> 4 then raise Exit; @@ -13,7 +13,7 @@ let rec input() = List.map (fun c -> int_of_string (String.make 1 c)) t with Exit -> prerr_endline "That is an invalid entry. Please try again."; - input() + input () ;; let print_score g t = @@ -30,7 +30,7 @@ let print_score g t = ;; let () = - Random.self_init(); + Random.self_init (); let rec mkgoal acc = function 4 -> acc | i -> let n = succ(Random.int 9) in @@ -41,7 +41,7 @@ let () = let g = mkgoal [] 0 in let found = ref false in while not !found do - let t = input() in + let t = input () in if t = g then found := true else print_score g t diff --git a/Task/Bulls-and-cows/Racket/bulls-and-cows.rkt b/Task/Bulls-and-cows/Racket/bulls-and-cows.rkt new file mode 100644 index 0000000000..b7c094087b --- /dev/null +++ b/Task/Bulls-and-cows/Racket/bulls-and-cows.rkt @@ -0,0 +1,58 @@ +#lang racket + +; secret : (listof exact-nonnegative-integer?) +(define secret + (foldr (λ (n result) + (cons n (map (λ (y) (if (>= y n) (add1 y) y)) + result))) + '() + (map random '(10 9 8 7)))) + +; (count-bulls/cows guess) -> (values exact-nonnegative-integer? +; exact-nonnegative-integer?) +; guess : (listof exact-nonnegative-integer?) +(define (count-bulls/cows guess) + (let* ([bulls (map = guess secret)] + [cow-candidates (filter-map (λ (x y) (if (false? x) y #f)) + bulls + secret)] + [cows (filter (curryr member cow-candidates) guess)]) + (values (length (filter ((curry equal?) #t) bulls)) + (length cows)))) + +; (valid-guess guess-str) -> (or/c (listof exact-nonnegative-integer?) #f) +; guess-str : string? +(define (valid-guess guess-str) + (define (char->digit c) + (- (char->integer c) (char->integer #\0))) + (if (regexp-match-exact? #px"[0-9]{4}" guess-str) + (let ([guess (map char->digit (string->list guess-str))]) + (if (andmap (λ (x) (equal? (count ((curry equal?) x) guess) 1)) + guess) + guess + #f)) + #f)) + +; Game states +(define win #t) +(define game #f) + +; (main-loop state step) -> void? +; state : boolean? +; step : exact-nonnegative-integer? +(define (main-loop state step) + (if (equal? state win) + (printf "You won after ~a guesses." step) + (begin + (let* ([guess-str (read-line)] + [guess (valid-guess guess-str)]) + (if (false? guess) + (begin (displayln "Guess should include exactly four different digits") + (main-loop state step)) + (let-values ([(bulls cows) (count-bulls/cows guess)]) + (if (= bulls 4) + (main-loop win (add1 step)) + (begin (printf "Bulls: ~a Cows: ~a\n" bulls cows) + (main-loop state (add1 step)))))))))) + +(main-loop game 0) diff --git a/Task/CRC-32/Racket/crc-32-1.rkt b/Task/CRC-32/Racket/crc-32-1.rkt new file mode 100644 index 0000000000..0e0a1eecf4 --- /dev/null +++ b/Task/CRC-32/Racket/crc-32-1.rkt @@ -0,0 +1,15 @@ +#lang racket +(define (bytes-crc32 data) + (bitwise-xor + (for/fold ([accum #xFFFFFFFF]) + ([byte (in-bytes data)]) + (for/fold ([accum (bitwise-xor accum byte)]) + ([num (in-range 0 8)]) + (bitwise-xor (quotient accum 2) + (* #xEDB88320 (bitwise-and accum 1))))) + #xFFFFFFFF)) + +(define (crc32 s) + (bytes-crc32 (string->bytes/utf-8 s))) + +(format "~x" (crc32 "The quick brown fox jumps over the lazy dog")) diff --git a/Task/CRC-32/Racket/crc-32-2.rkt b/Task/CRC-32/Racket/crc-32-2.rkt new file mode 100644 index 0000000000..e1fb4d3cbd --- /dev/null +++ b/Task/CRC-32/Racket/crc-32-2.rkt @@ -0,0 +1 @@ +"414fa339" diff --git a/Task/CSV-to-HTML-translation/ANTLR/csv-to-html-translation.antlr b/Task/CSV-to-HTML-translation/ANTLR/csv-to-html-translation.antlr new file mode 100644 index 0000000000..3a9a15e10e --- /dev/null +++ b/Task/CSV-to-HTML-translation/ANTLR/csv-to-html-translation.antlr @@ -0,0 +1,9 @@ +// Create an HTML Table from comma seperated values +// Nigel Galloway - June 2nd., 2013 +grammar csv2html; +dialog : {System.out.println("");}header body+{System.out.println("
");} ; +header : {System.out.println("");}row{System.out.println("");}row{System.out.println("" + $Field.text.replace("<","<").replace(">",">") + "");}; +Field : ~[,\n\r]+; diff --git a/Task/Caesar-cipher/D/caesar-cipher-1.d b/Task/Caesar-cipher/D/caesar-cipher-1.d index 447d25dc88..61f7ee8512 100644 --- a/Task/Caesar-cipher/D/caesar-cipher-1.d +++ b/Task/Caesar-cipher/D/caesar-cipher-1.d @@ -1,20 +1,21 @@ import std.stdio, std.traits; -pure S rot(S)(in S s, in int key) if (isSomeString!S) { - auto res = s.dup; +pure S rot(S)(in S s, in int key) pure /*nothrow*/ +if (isSomeString!S) { + auto res = s.dup; // Not nothrow. - foreach (i, ref c; res) { + foreach (immutable i, ref c; res) { if ('a' <= c && c <= 'z') c = ((c - 'a' + key) % 26 + 'a'); else if ('A' <= c && c <= 'Z') c = ((c - 'A' + key) % 26 + 'A'); } - return cast(S) res; + return res; } void main() { - int key = 3; - auto txt = "The five boxing wizards jump quickly"; + enum key = 3; + immutable txt = "The five boxing wizards jump quickly"; writeln("Original: ", txt); writeln("Encrypted: ", txt.rot(key)); writeln("Decrypted: ", txt.rot(key).rot(26 - key)); diff --git a/Task/Caesar-cipher/D/caesar-cipher-3.d b/Task/Caesar-cipher/D/caesar-cipher-3.d new file mode 100644 index 0000000000..5fcf4bf0a8 --- /dev/null +++ b/Task/Caesar-cipher/D/caesar-cipher-3.d @@ -0,0 +1,17 @@ +import std.stdio, std.ascii, std.string, std.algorithm; + +string rot(in string s, in int key) pure /*nothrow*/ { + auto uppr = uppercase.dup.representation; + bringToFront(uppr[0 .. key], uppr[key .. $]); + auto lowr = lowercase.dup.representation; + bringToFront(lowr[0 .. key], lowr[key .. $]); + return s.translate(makeTrans(letters, cast(char[])(uppr ~ lowr))); +} + +void main() { + enum key = 3; + immutable txt = "The five boxing wizards jump quickly"; + writeln("Original: ", txt); + writeln("Encrypted: ", txt.rot(key)); + writeln("Decrypted: ", txt.rot(key).rot(26 - key)); +} diff --git a/Task/Caesar-cipher/Objeck/caesar-cipher.objeck b/Task/Caesar-cipher/Objeck/caesar-cipher.objeck new file mode 100644 index 0000000000..07caa71b18 --- /dev/null +++ b/Task/Caesar-cipher/Objeck/caesar-cipher.objeck @@ -0,0 +1,29 @@ +class Caesar { + function : native : Encode(enc : String, offset : Int) ~ String { + offset := offset % 26 + 26; + encoded := ""; + enc := enc->ToLower(); + each(i : enc) { + c := enc->Get(i); + if(c->IsChar()) { + j := (c - 'a' + offset) % 26; + encoded->Append(j + 'a'); + } + else { + encoded->Append(c); + }; + }; + + return encoded; + } + + function : Decode(enc : String, offset : Int) ~ String { + return Encode(enc, offset * -1); + } + + function : Main(args : String[]) ~ Nil { + enc := Encode("The quick brown fox Jumped over the lazy Dog", 12); + enc->PrintLine(); + Decode(enc, 12)->PrintLine(); + } +} diff --git a/Task/Caesar-cipher/Racket/caesar-cipher.rkt b/Task/Caesar-cipher/Racket/caesar-cipher.rkt new file mode 100644 index 0000000000..a51e5c7c08 --- /dev/null +++ b/Task/Caesar-cipher/Racket/caesar-cipher.rkt @@ -0,0 +1,19 @@ +#lang racket + +(define A (char->integer #\A)) +(define Z (char->integer #\Z)) +(define a (char->integer #\a)) +(define z (char->integer #\z)) + +(define (rotate c n) + (define cnum (char->integer c)) + (define (shift base) (integer->char (+ base (modulo (+ n (- cnum base)) 26)))) + (cond [(<= A cnum Z) (shift A)] + [(<= a cnum z) (shift a)] + [else c])) + +(define (caesar s n) + (list->string (for/list ([c (in-string s)]) (rotate c n)))) + +(define (encrypt s) (caesar s 1)) +(define (decrypt s) (caesar s -1)) diff --git a/Task/Calendar---for-real-programmers/Racket/calendar---for-real-programmers.rkt b/Task/Calendar---for-real-programmers/Racket/calendar---for-real-programmers.rkt new file mode 100644 index 0000000000..46f1fb83fb --- /dev/null +++ b/Task/Calendar---for-real-programmers/Racket/calendar---for-real-programmers.rkt @@ -0,0 +1,35 @@ +#CI(MODULE NAME-OF-THIS-FILE RACKET +(REQUIRE RACKET/DATE) +(DEFINE (CALENDAR YR) + (DEFINE (NSPLIT N L) (IF (NULL? L) L (CONS (TAKE L N) (NSPLIT N (DROP L N))))) + (DEFINE MONTHS + (FOR/LIST ([MN (IN-NATURALS 1)] + [MNAME '(JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY + AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER)]) + (DEFINE S (FIND-SECONDS 0 0 12 1 MN YR)) + (DEFINE PFX (DATE-WEEK-DAY (SECONDS->DATE S))) + (DEFINE DAYS + (LET ([? (IF (= MN 12) (Λ(X Y) Y) (Λ(X Y) X))]) + (ROUND (/ (- (FIND-SECONDS 0 0 12 1 (? (+ 1 MN) 1) (? YR (+ 1 YR))) S) + 60 60 24)))) + (LIST* (~A MNAME #:WIDTH 20 #:ALIGN 'CENTER) "SU MO TU WE TH FR SA" + (MAP STRING-JOIN + (NSPLIT 7 `(,@(MAKE-LIST PFX " ") + ,@(FOR/LIST ([D DAYS]) + (~A (+ D 1) #:WIDTH 2 #:ALIGN 'RIGHT)) + ,@(MAKE-LIST (- 42 PFX DAYS) " "))))))) + (LET* ([S '(" 11,-~4-._3. 41-4! 10/ ()=(2) 3\\ 40~A! 9( 3( 80 39-4! 10\\._\\" + ", ,-4'! 5#2X3@7! 12/ 2-3'~2;! 11/ 4/~2|-! 9=( 3~4 2|! 3/~42\\! " + "2/_23\\! /_25\\!/_27\\! 3|_20|! 3|_20|! 3|_20|! 3| 20|!!")] + [S (REGEXP-REPLACE* "!" (STRING-APPEND* S) "~%")] + [S (REGEXP-REPLACE* "@" S (STRING-FOLDCASE "X"))] + [S (REGEXP-REPLACE* ".(?:[1-7][0-9]*|[1-9])" S + (Λ(M) (MAKE-STRING (STRING->NUMBER (SUBSTRING M 1)) + (STRING-REF M 0))))]) + (PRINTF S YR)) + (FOR-EACH (COMPOSE1 DISPLAYLN STRING-TITLECASE) + (DROPF-RIGHT (FOR*/LIST ([3MS (NSPLIT 3 MONTHS)] [S (APPLY MAP LIST 3MS)]) + (REGEXP-REPLACE " +$" (STRING-JOIN S " ") "")) + (Λ(S) (EQUAL? "" S))))) + +(CALENDAR 1969)) diff --git a/Task/Calendar/C++/calendar.cpp b/Task/Calendar/C++/calendar.cpp new file mode 100644 index 0000000000..f63e41af47 --- /dev/null +++ b/Task/Calendar/C++/calendar.cpp @@ -0,0 +1,156 @@ +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + + +//-------------------------------------------------------------------------------------------------- +class calender +{ +public: + void drawCalender( int y ) + { + year = y; + for( int i = 0; i < 12; i++ ) + firstdays[i] = getfirstday( i ); + + isleapyear(); + build(); + } + +private: + void isleapyear() + { + isleap = false; + + if( !( year % 4 ) ) + { + if( year % 100 ) isleap = true; + else if( !( year % 400 ) ) isleap = true; + } + } + + int getfirstday( int m ) + { + int y = year; + + int f = y + 1 + 3 * m - 1; + m++; + if( m < 3 ) y--; + else f -= int( .4 * m + 2.3 ); + + f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); + f %= 7; + + return f; + } + + void build() + { + int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + int lc = 0, lco = 0, ystr = 7, start = 2, fd = 0, m = 0; + HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); + COORD pos = { 0, ystr }; + draw(); + + for( int i = 0; i < 4; i++ ) + { + for( int j = 0; j < 3; j++ ) + { + int d = firstdays[fd++], dm = days[m++]; + pos.X = d * 3 + start; + SetConsoleCursorPosition( h, pos ); + + for( int dd = 0; dd < dm; dd++ ) + { + if( dd < 9 ) cout << 0 << dd + 1 << " "; + else cout << dd + 1 << " "; + + pos.X += 3; + if( pos.X - start > 20 ) + { + pos.X = start; pos.Y++; + SetConsoleCursorPosition( h, pos ); + } + } + + start += 23; + pos.X = start; pos.Y = ystr; + SetConsoleCursorPosition( h, pos ); + } + ystr += 9; start = 2; + pos.Y = ystr; + } + } + + void draw() + { + system( "cls" ); + cout << "+--------------------------------------------------------------------+" << endl; + cout << "| [SNOOPY] |" << endl; + cout << "| |" << endl; + cout << "| == " << year << " == |" << endl; + cout << "+----------------------+----------------------+----------------------+" << endl; + cout << "| JANUARY | FEBRUARY | MARCH |" << endl; + cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "+----------------------+----------------------+----------------------+" << endl; + cout << "| APRIL | MAY | JUNE |" << endl; + cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "+----------------------+----------------------+----------------------+" << endl; + cout << "| JULY | AUGUST | SEPTEMBER |" << endl; + cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "+----------------------+----------------------+----------------------+" << endl; + cout << "| OCTOBER | NOVEMBER | DECEMBER |" << endl; + cout << "| SU MO TU WE TH FR SA | SU MO TU WE TH FR SA | SU MO TU WE TH FR SA |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "| | | |" << endl; + cout << "+----------------------+----------------------+----------------------+" << endl; + } + + int firstdays[12], year; + bool isleap; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + int y; + calender cal; + + while( true ) + { + system( "cls" ); + cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; + cin >> y; + if( !y ) return 0; + + cal.drawCalender( y ); + cout << endl << endl << endl << endl << endl << endl << endl << endl; + + system( "pause" ); + } + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Calendar/Racket/calendar.rkt b/Task/Calendar/Racket/calendar.rkt new file mode 100644 index 0000000000..3494429752 --- /dev/null +++ b/Task/Calendar/Racket/calendar.rkt @@ -0,0 +1,34 @@ +#lang racket +(require racket/date) +(define (calendar yr) + (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) + (define months + (for/list ([mn (in-naturals 1)] + [mname '(January February March April May June July + August September October November December)]) + (define s (find-seconds 0 0 12 1 mn yr)) + (define pfx (date-week-day (seconds->date s))) + (define days + (let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))]) + (round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s) + 60 60 24)))) + (list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa" + (map string-join + (nsplit 7 `(,@(make-list pfx " ") + ,@(for/list ([d days]) + (~a (+ d 1) #:width 2 #:align 'right)) + ,@(make-list (- 42 pfx days) " "))))))) + (let* ([s '(" 11,-~4-._3. 41-4! 10/ ()=(2) 3\\ 40~a! 9( 3( 80 39-4! 10\\._\\" + ", ,-4'! 5#2X3x7! 12/ 2-3'~2;! 11/ 4/~2|-! 9=( 3~4 2|! 3/~42\\! " + "2/_23\\! /_25\\!/_27\\! 3|_20|! 3|_20|! 3|_20|! 3| 20|!!")] + [s (regexp-replace* #rx"!" (string-append* s) "\n")] + [s (regexp-replace* #rx".(?:[1-7][0-9]*|[1-9])" s + (λ(m) (make-string (string->number (substring m 1)) + (string-ref m 0))))]) + (printf s yr)) + (for-each displayln + (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) + (regexp-replace #rx" +$" (string-join s " ") "")) + (λ(s) (equal? "" s))))) + +(calendar 1969) diff --git a/Task/Call-a-function-in-a-shared-library/Julia/call-a-function-in-a-shared-library.julia b/Task/Call-a-function-in-a-shared-library/Julia/call-a-function-in-a-shared-library.julia index 26dc8e2edf..7f17a6599b 100644 --- a/Task/Call-a-function-in-a-shared-library/Julia/call-a-function-in-a-shared-library.julia +++ b/Task/Call-a-function-in-a-shared-library/Julia/call-a-function-in-a-shared-library.julia @@ -1,3 +1,5 @@ -#ccall((symbol, library), RetType, (ArgType1, ...), ArgVar1, ...) - ccall( (:GetDoubleClickTime, "User32"), stdcall, - Uint, (), ) +#this example works on Windows +ccall( (:GetDoubleClickTime, "User32"), stdcall, + Uint, (), ) + +ccall( (:clock, "libc"), Int32, ()) diff --git a/Task/Call-a-function/Lua/call-a-function.lua b/Task/Call-a-function/Lua/call-a-function.lua new file mode 100644 index 0000000000..4ad7fcccb2 --- /dev/null +++ b/Task/Call-a-function/Lua/call-a-function.lua @@ -0,0 +1,32 @@ +-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped. +function fixed (a, b, c) print(a, b, c) end +fixed() --> nil nil nil +fixed(1, 2, 3, 4, 5) --> 1 2 3 + +-- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of values. +function vararg (...) print(...) end +vararg(1, 2, 3, 4, 5) -- 1 2 3 4 5 + +-- Lua also allows dropping the parentheses if table or string literals are used as the sole argument +print "some string" +print { foo = "bar" } -- also serves as a form of named arguments + +-- First-class functions in expression context +print(("this is backwards uppercase"):gsub("%w+", function (s) return s:upper():reverse() end)) + +-- Functions can return multiple values (including none), which can be counted via select() +local iter, obj, start = ipairs { 1, 2, 3 } +print(select("#", (function () end)())) --> 0 +print(select("#", unpack { 1, 2, 3, 4 })) --> 4 + +-- Partial application +function prefix (pre) + return function (suf) return pre .. suf end +end + +local prefixed = prefix "foo" +print(prefixed "bar", prefixed "baz", prefixed "quux") + +-- nil, booleans, and numbers are always passed by value. Everything else is always passed by reference. +-- There is no separate notion of subroutines +-- Built-in functions are not easily distinguishable from user-defined functions diff --git a/Task/Call-a-function/Racket/call-a-function.rkt b/Task/Call-a-function/Racket/call-a-function.rkt new file mode 100644 index 0000000000..4ca02abd90 --- /dev/null +++ b/Task/Call-a-function/Racket/call-a-function.rkt @@ -0,0 +1,38 @@ +#lang racket + +;; Calling a function that requires no arguments +(foo) + +;; Calling a function with a fixed number of arguments +(foo 1 2 3) + +;; Calling a function with optional arguments +;; Calling a function with a variable number of arguments +(foo 1 2 3) ; same in both cases + +;; Calling a function with named arguments +(foo 1 2 #:x 3) ; using #:keywords for the names + +;; Using a function in statement context +;; Using a function in first-class context within an expression +;; Obtaining the return value of a function +;; -> Makes no sense for Racket, as well as most other functional PLs + +;; Distinguishing built-in functions and user-defined functions +(primitive? foo) +;; but this is mostly useless, since most of Racket is implemented in +;; itself + +;; Distinguishing subroutines and functions +;; -> No difference, though `!' is an idiomatic suffix for names of +;; side-effect functions, and they usually return (void) + +;; Stating whether arguments are passed by value or by reference + +;; -> Always by value, but it's possible to implement languages with +;; other argument passing styles, including passing arguments by +;; reference (eg, there is "#lang algol60") + +;; Is partial application possible and how +(curry foo 1 2) ; later apply this on 3 +(λ(x) (foo 1 2 x)) ; a direct way of doing the same diff --git a/Task/Call-a-function/Seed7/call-a-function-1.seed7 b/Task/Call-a-function/Seed7/call-a-function-1.seed7 new file mode 100644 index 0000000000..694479ac8d --- /dev/null +++ b/Task/Call-a-function/Seed7/call-a-function-1.seed7 @@ -0,0 +1,3 @@ +env := environment; # Call a function that requires no arguments. +env := environment(); # Alternative possibility to call of a function with no arguments. +cmp := compare(i, j); # Call a function with a fixed number of arguments. diff --git a/Task/Call-a-function/Seed7/call-a-function-2.seed7 b/Task/Call-a-function/Seed7/call-a-function-2.seed7 new file mode 100644 index 0000000000..f51b2bb4da --- /dev/null +++ b/Task/Call-a-function/Seed7/call-a-function-2.seed7 @@ -0,0 +1,2 @@ +write(aFile, "asdf"); # Variant of write with a parameter to specify a file. +write("asdf"); # Variant of write which writes to the file OUT. diff --git a/Task/Call-a-function/Seed7/call-a-function-3.seed7 b/Task/Call-a-function/Seed7/call-a-function-3.seed7 new file mode 100644 index 0000000000..74ca83712e --- /dev/null +++ b/Task/Call-a-function/Seed7/call-a-function-3.seed7 @@ -0,0 +1,13 @@ +const func integer: sum (in array integer: intElems) is func + result + var integer: sum is 0; + local + var integer: element is 0; + begin + for element range intElems do + sum +:= element; + end for; + end func; + +s := sum([] (1, 2, 3)); # Use an aggregate to generate an array. +t := sum([] (2, 3, 5, 7)); diff --git a/Task/Call-a-function/Seed7/call-a-function-4.seed7 b/Task/Call-a-function/Seed7/call-a-function-4.seed7 new file mode 100644 index 0000000000..8fb0ac40e4 --- /dev/null +++ b/Task/Call-a-function/Seed7/call-a-function-4.seed7 @@ -0,0 +1 @@ +write("Nr: " <& num); # Use operators to concatenate arguments. diff --git a/Task/Call-a-function/Seed7/call-a-function-5.seed7 b/Task/Call-a-function/Seed7/call-a-function-5.seed7 new file mode 100644 index 0000000000..76a52ad1e6 --- /dev/null +++ b/Task/Call-a-function/Seed7/call-a-function-5.seed7 @@ -0,0 +1 @@ +ignore(getln(IN)); # Using a function in statement context (ignore the result). diff --git a/Task/Call-a-function/Seed7/call-a-function-6.seed7 b/Task/Call-a-function/Seed7/call-a-function-6.seed7 new file mode 100644 index 0000000000..cf8cd18682 --- /dev/null +++ b/Task/Call-a-function/Seed7/call-a-function-6.seed7 @@ -0,0 +1 @@ +seq := doMap([](1, 2, 4, 6, 10, 12, 16), x, succ(x)); diff --git a/Task/Call-an-object-method/Lua/call-an-object-method-1.lua b/Task/Call-an-object-method/Lua/call-an-object-method-1.lua new file mode 100644 index 0000000000..9c410471e4 --- /dev/null +++ b/Task/Call-an-object-method/Lua/call-an-object-method-1.lua @@ -0,0 +1,4 @@ +local object = { name = "foo", func = function (self) print(self.name) end } + +object:func() -- with : sugar +object.func(object) -- without : sugar diff --git a/Task/Call-an-object-method/Lua/call-an-object-method-2.lua b/Task/Call-an-object-method/Lua/call-an-object-method-2.lua new file mode 100644 index 0000000000..3ce115ac14 --- /dev/null +++ b/Task/Call-an-object-method/Lua/call-an-object-method-2.lua @@ -0,0 +1,9 @@ +local methods = { } +function methods:func () -- if a function is declared using :, it is given an implicit 'self' parameter + print(self.name) +end + +local object = setmetatable({ name = "foo" }, { __index = methods }) + +object:func() -- with : sugar +methods.func(object) -- without : sugar diff --git a/Task/Call-an-object-method/Lua/call-an-object-method-3.lua b/Task/Call-an-object-method/Lua/call-an-object-method-3.lua new file mode 100644 index 0000000000..262e92444c --- /dev/null +++ b/Task/Call-an-object-method/Lua/call-an-object-method-3.lua @@ -0,0 +1,16 @@ +local count = 0 +local box = { } +local boxmt = { __index = box } +function box:tellSecret () + return self.secret +end + +local M = { } +function M.new () + count = count + 1 + return setmetatable({ secret = count, contents = count % 2 == 0 and "rabbit" or "rock" }, boxmt) +end +function M.count () + return count +end +return M diff --git a/Task/Call-an-object-method/Lua/call-an-object-method-4.lua b/Task/Call-an-object-method/Lua/call-an-object-method-4.lua new file mode 100644 index 0000000000..d84843aab5 --- /dev/null +++ b/Task/Call-an-object-method/Lua/call-an-object-method-4.lua @@ -0,0 +1,6 @@ +local box = require 'box' + +local b = box.new() + +print(b:tellSecret()) +print(box.count()) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Racket/carmichael-3-strong-pseudoprimes-1.rkt b/Task/Carmichael-3-strong-pseudoprimes/Racket/carmichael-3-strong-pseudoprimes-1.rkt new file mode 100644 index 0000000000..2a91ba87a0 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Racket/carmichael-3-strong-pseudoprimes-1.rkt @@ -0,0 +1,16 @@ +#lang racket +(require math) + +(for ([p1 (in-range 3 62)] #:when (prime? p1)) + (for ([h3 (in-range 2 p1)]) + (define g (+ p1 h3)) + (let next ([d 1]) + (when (< d g) + (when (and (zero? (modulo (* g (- p1 1)) d)) + (= (modulo (- (sqr p1)) h3) (modulo d h3))) + (define p2 (+ 1 (quotient (* g (- p1 1)) d))) + (when (prime? p2) + (define p3 (+ 1 (quotient (* p1 p2) h3))) + (when (and (prime? p3) (= 1 (modulo (* p2 p3) (- p1 1)))) + (displayln (list p1 p2 p3 '=> (* p1 p2 p3)))))) + (next (+ d 1)))))) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Racket/carmichael-3-strong-pseudoprimes-2.rkt b/Task/Carmichael-3-strong-pseudoprimes/Racket/carmichael-3-strong-pseudoprimes-2.rkt new file mode 100644 index 0000000000..92d6cc523b --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Racket/carmichael-3-strong-pseudoprimes-2.rkt @@ -0,0 +1,62 @@ +(3 11 17 => 561) +(5 29 73 => 10585) +(5 17 29 => 2465) +(5 13 17 => 1105) +(7 19 67 => 8911) +(7 31 73 => 15841) +(7 23 41 => 6601) +(7 73 103 => 52633) +(13 61 397 => 314821) +(13 97 421 => 530881) +(13 37 97 => 46657) +(13 37 61 => 29341) +(17 41 233 => 162401) +(17 353 1201 => 7207201) +(19 43 409 => 334153) +(19 199 271 => 1024651) +(23 199 353 => 1615681) +(29 113 1093 => 3581761) +(29 197 953 => 5444489) +(31 991 15361 => 471905281) +(31 61 631 => 1193221) +(31 151 1171 => 5481451) +(31 61 271 => 512461) +(31 61 211 => 399001) +(31 271 601 => 5049001) +(31 181 331 => 1857241) +(37 109 2017 => 8134561) +(37 73 541 => 1461241) +(37 613 1621 => 36765901) +(37 73 181 => 488881) +(37 73 109 => 294409) +(41 1721 35281 => 2489462641) +(41 881 12041 => 434932961) +(41 101 461 => 1909001) +(41 241 761 => 7519441) +(41 241 521 => 5148001) +(41 73 137 => 410041) +(41 61 101 => 252601) +(43 631 13567 => 368113411) +(43 127 1093 => 5968873) +(43 211 757 => 6868261) +(43 631 1597 => 43331401) +(43 127 211 => 1152271) +(43 211 337 => 3057601) +(43 433 643 => 11972017) +(43 547 673 => 15829633) +(43 3361 3907 => 564651361) +(47 3359 6073 => 958762729) +(47 1151 1933 => 104569501) +(47 3727 5153 => 902645857) +(53 157 2081 => 17316001) +(53 79 599 => 2508013) +(53 157 521 => 4335241) +(59 1451 2089 => 178837201) +(61 421 12841 => 329769721) +(61 1301 19841 => 1574601601) +(61 277 2113 => 35703361) +(61 541 3001 => 99036001) +(61 661 2521 => 101649241) +(61 271 571 => 9439201) +(61 241 421 => 6189121) +(61 3361 4021 => 824389441) diff --git a/Task/Case-sensitivity-of-identifiers/ALGOL-68/case-sensitivity-of-identifiers.alg b/Task/Case-sensitivity-of-identifiers/ALGOL-68/case-sensitivity-of-identifiers.alg new file mode 100644 index 0000000000..4216ef2342 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/ALGOL-68/case-sensitivity-of-identifiers.alg @@ -0,0 +1,12 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +STRING dog = "Benjamin"; +OP D = (INT og)STRING: "Samba"; +OP DOG = (INT gy)STRING: "Bernie"; +INT og=~, gy=~; + +main:( + printf(($"The three dogs are named "g", "g" and "g"."l$, dog, Dog, DOGgy)); + 0 +) diff --git a/Task/Case-sensitivity-of-identifiers/Bracmat/case-sensitivity-of-identifiers.bracmat b/Task/Case-sensitivity-of-identifiers/Bracmat/case-sensitivity-of-identifiers.bracmat new file mode 100644 index 0000000000..6b88c2803a --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Bracmat/case-sensitivity-of-identifiers.bracmat @@ -0,0 +1,5 @@ +( Benjamin:?dog +& Samba:?Dog +& Bernie:?DOG +& out$("There are three dogs:" !dog !Dog and !DOG) +); diff --git a/Task/Case-sensitivity-of-identifiers/Erlang/case-sensitivity-of-identifiers.erl b/Task/Case-sensitivity-of-identifiers/Erlang/case-sensitivity-of-identifiers.erl new file mode 100644 index 0000000000..2ebf173304 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Erlang/case-sensitivity-of-identifiers.erl @@ -0,0 +1,9 @@ +-module( case_sensitivity_of_identifiers ). + +-export( [task/0] ). + +task() -> + catch dog = "Benjamin", % Function will crash without catch + Dog = "Samba", + DOG = "Bernie", + io:fwrite( "The three dogs are named ~s, ~s and ~s~n", [dog, Dog, DOG] ). diff --git a/Task/Case-sensitivity-of-identifiers/PL-I/case-sensitivity-of-identifiers.pli b/Task/Case-sensitivity-of-identifiers/PL-I/case-sensitivity-of-identifiers.pli new file mode 100644 index 0000000000..be1a0acd10 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/PL-I/case-sensitivity-of-identifiers.pli @@ -0,0 +1,12 @@ +*process or(!) source xref attributes macro options; + /********************************************************************* + * Program to show that PL/I is case-insensitive + * 28.05.2013 Walter Pachl + *********************************************************************/ + case: proc options(main); + Dcl dog Char(20) Var; + dog = "Benjamin"; + Dog = "Samba"; + DOG = "Bernie"; + Put Edit(dog,Dog,DOG)(Skip,3(a,x(1))); + End; diff --git a/Task/Case-sensitivity-of-identifiers/REXX/case-sensitivity-of-identifiers.rexx b/Task/Case-sensitivity-of-identifiers/REXX/case-sensitivity-of-identifiers.rexx index 54ac252809..7834746e19 100644 --- a/Task/Case-sensitivity-of-identifiers/REXX/case-sensitivity-of-identifiers.rexx +++ b/Task/Case-sensitivity-of-identifiers/REXX/case-sensitivity-of-identifiers.rexx @@ -1,4 +1,4 @@ -/*demonstrate case insensative REXX variable names. (for the most part).*/ +/*demonstrate case insensitive REXX variable names. (for the most part).*/ dog = 'Benjamin' Dog = 'Samba' DOG = 'Bernie' diff --git a/Task/Catalan-numbers/00DESCRIPTION b/Task/Catalan-numbers/00DESCRIPTION index 9a089629db..cd1bef3d6a 100644 --- a/Task/Catalan-numbers/00DESCRIPTION +++ b/Task/Catalan-numbers/00DESCRIPTION @@ -6,8 +6,3 @@ Or alternatively (also recursive): :C_0 = 1 \quad \mbox{and} \quad C_n=\frac{2(2n-1)}{n+1}C_{n-1}, Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. [[Memoization]] is not required, but may be worth the effort when using the second method above. - -;Cf.: -* [[Pascal's triangle]] -* [http://milan.milanovic.org/math/english/fibo/fibo4.html Catalan Numbers and the Pascal Triangle] -* http://rosettacode.org/wiki/Catalan_numbers#An_Alternative_Approach diff --git a/Task/Catalan-numbers/JavaScript/catalan-numbers.js b/Task/Catalan-numbers/JavaScript/catalan-numbers.js new file mode 100644 index 0000000000..ffea51d934 --- /dev/null +++ b/Task/Catalan-numbers/JavaScript/catalan-numbers.js @@ -0,0 +1,29 @@ +Catalan +

diff --git a/Task/Catalan-numbers/Julia/catalan-numbers.julia b/Task/Catalan-numbers/Julia/catalan-numbers.julia
index a01697bae4..66e184e714 100644
--- a/Task/Catalan-numbers/Julia/catalan-numbers.julia
+++ b/Task/Catalan-numbers/Julia/catalan-numbers.julia
@@ -1,3 +1,8 @@
-function catalan(n)
-	binomial(2n,n)/(n+1)
+function catalan(bn::Integer)
+    if bn < 0
+        throw(DomainError())
+    else
+        n = BigInt(bn)
+    end
+    return binomial(2n, n)/(n + 1)
 end
diff --git a/Task/Catalan-numbers/Seed7/catalan-numbers.seed7 b/Task/Catalan-numbers/Seed7/catalan-numbers.seed7
new file mode 100644
index 0000000000..4b066ed65f
--- /dev/null
+++ b/Task/Catalan-numbers/Seed7/catalan-numbers.seed7
@@ -0,0 +1,11 @@
+$ include "seed7_05.s7i";
+  include "bigint.s7i";
+
+const proc: main is func
+  local
+    var bigInteger: n is 0_;
+  begin
+    for n range 0_ to 15_ do
+      writeln((2_ * n) ! n div succ(n));
+    end for;
+  end func;
diff --git a/Task/Character-codes/Racket/character-codes.rkt b/Task/Character-codes/Racket/character-codes.rkt
new file mode 100644
index 0000000000..ab28419f41
--- /dev/null
+++ b/Task/Character-codes/Racket/character-codes.rkt
@@ -0,0 +1,11 @@
+#lang racket
+
+(define (code ch)
+  (printf "The unicode number for ~s is ~a\n" ch (char->integer ch)))
+(code #\a)
+(code #\λ)
+
+(define (char n)
+  (printf "The unicode number ~a is the character ~s\n" n (integer->char n)))
+(char 97)
+(char 955)
diff --git a/Task/Character-matching/FBSL/character-matching.fbsl b/Task/Character-matching/FBSL/character-matching.fbsl
new file mode 100644
index 0000000000..20e5c2b5b0
--- /dev/null
+++ b/Task/Character-matching/FBSL/character-matching.fbsl
@@ -0,0 +1,15 @@
+#APPTYPE CONSOLE
+
+DIM s = "roko, mat jane do"
+
+IF LEFT(s, 4) = "roko" THEN PRINT STRENC(s), " starts with ", STRENC("roko")
+IF INSTR(s, "mat") THEN PRINT STRENC(s), " contains ", STRENC("mat"), " at ", INSTR
+IF RIGHT(s, 2) = "do" THEN PRINT STRENC(s), " ends with ", STRENC("do")
+PRINT STRENC(s), " contains ", STRENC("o"), " at the following locations:", InstrEx(s, "o")
+
+PAUSE
+
+SUB InstrEx(mane, match)
+    INSTR = 0
+    WHILE INSTR(mane, match, INSTR + 1): PRINT " ", INSTR;: WEND
+END SUB
diff --git a/Task/Character-matching/PHP/character-matching-1.php b/Task/Character-matching/PHP/character-matching-1.php
new file mode 100644
index 0000000000..91050a57a8
--- /dev/null
+++ b/Task/Character-matching/PHP/character-matching-1.php
@@ -0,0 +1,59 @@
+0) { // look for other occurrences
+  $pl=$pos; // list of positions
+  $p=$pos;  //
+  $x="*************************************";
+  $h=$haystack;
+  while ($p>0) {
+    $h=substr($x,0,$p).substr($h,$p);
+    $p=rexxpos($h,$needle);
+    if ( $p>0 ) { $n=$n+1; $pl=$pl.", ".$p; }
+  }
+       if ($n==1) { $txt="needle found once in haystack, position: $pl."; }
+  else if ($n==2) { $txt="needle found twice in haystack, position(s): $pl."; }
+  else            { $txt="needle found $n times in haystack, position(s): $pl."; }
+}
+else              { $txt="needle not found in haystack."; }
+?>
+
+  
+    Character Matching
+    
+    
+    
+  
+  
+    

Haystack: ''

+

Needle:   ''

+

+ +

+ + diff --git a/Task/Character-matching/PHP/character-matching-2.php b/Task/Character-matching/PHP/character-matching-2.php new file mode 100644 index 0000000000..7f7728db99 --- /dev/null +++ b/Task/Character-matching/PHP/character-matching-2.php @@ -0,0 +1,41 @@ + + + + + + Character matching + + +
+

Character matching

+

Given two strings, demonstrate the following 3 types of matchings: +

    +
  1. Determining if the first string starts with second string +
  2. Determining if the first string contains the second string at any location +
  3. Determining if the first string ends with the second string +
+

Optional requirements: +

    +
  1. Print the location of the match(es) for part 2 +
  2. Handle multiple occurrences of a string for part 2. +
+

+ Haystack: +

+

+ Needle:   +

+

Press + to invoke chmx.php.

+
+ + diff --git a/Task/Chat-server/Racket/chat-server.rkt b/Task/Chat-server/Racket/chat-server.rkt new file mode 100644 index 0000000000..d9be5caf7a --- /dev/null +++ b/Task/Chat-server/Racket/chat-server.rkt @@ -0,0 +1,21 @@ +#lang racket + +(define outs (list (current-output-port))) +(define ((tell-all who o) line) + (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) + +(define ((client i o)) + (define nick (begin (display "Nick: " o) (read-line i))) + (define tell (tell-all nick o)) + (let loop ([line "(joined)"]) + (if (eof-object? line) + (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) + (begin (tell line) (loop (read-line i)))))) + +(define (chat-server listener) + (define-values [i o] (tcp-accept listener)) + (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) + (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) + +(void (thread (λ() (chat-server (tcp-listen 12321))))) +((client (current-input-port) (current-output-port))) diff --git a/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas-1.pl6 b/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas-1.pl6 new file mode 100644 index 0000000000..b59bc958e1 --- /dev/null +++ b/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas-1.pl6 @@ -0,0 +1,20 @@ +use Test; +plan *; + +is tan(atan(1/2)+atan(1/3)), 1; +is tan(2*atan(1/3)+atan(1/7)), 1; +is tan(4*atan(1/5)-atan(1/239)), 1; +is tan(5*atan(1/7)+2*atan(3/79)), 1; +is tan(5*atan(29/278)+7*atan(3/79)), 1; +is tan(atan(1/2)+atan(1/5)+atan(1/8)), 1; +is tan(4*atan(1/5)-atan(1/70)+atan(1/99)), 1; +is tan(5*atan(1/7)+4*atan(1/53)+2*atan(1/4443)), 1; +is tan(6*atan(1/8)+2*atan(1/57)+atan(1/239)), 1; +is tan(8*atan(1/10)-atan(1/239)-4*atan(1/515)), 1; +is tan(12*atan(1/18)+8*atan(1/57)-5*atan(1/239)), 1; +is tan(16*atan(1/21)+3*atan(1/239)+4*atan(3/1042)), 1; +is tan(22*atan(1/28)+2*atan(1/443)-5*atan(1/1393)-10*atan(1/11018)), 1; +is tan(22*atan(1/38)+17*atan(7/601)+10*atan(7/8149)), 1; +is tan(44*atan(1/57)+7*atan(1/239)-12*atan(1/682)+24*atan(1/12943)), 1; +is tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12943)), 1; +is tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12944)), 1; diff --git a/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas-2.pl6 b/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas-2.pl6 new file mode 100644 index 0000000000..a0562899bf --- /dev/null +++ b/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas-2.pl6 @@ -0,0 +1,9 @@ +use Test; +plan *; + +for lines() { + is tan(.eval), /INCORRECT/ ?? none(1) !! 1 given + .subst(/'pi/4 = '/, '')\ + .subst(/arctan/, 'atan', :g)\ + .subst(/'[INCORRECT]'/, '# INCORRECT') +} diff --git a/Task/Check-Machin-like-formulas/Racket/check-machin-like-formulas-1.rkt b/Task/Check-Machin-like-formulas/Racket/check-machin-like-formulas-1.rkt new file mode 100644 index 0000000000..912b3b1fa3 --- /dev/null +++ b/Task/Check-Machin-like-formulas/Racket/check-machin-like-formulas-1.rkt @@ -0,0 +1,56 @@ +#lang racket +(define (reduce e) + (match e + [(? number? a) a] + [(list '+ (? number? a) (? number? b)) (+ a b)] + [(list '- (? number? a) (? number? b)) (- a b)] + [(list '- (? number? a)) (- a)] + [(list '* (? number? a) (? number? b)) (* a b)] + [(list '/ (? number? a) (? number? b)) (/ a b)] + [(list '+ a b) (reduce `(+ ,(reduce a) ,(reduce b)))] + [(list '- a b) (reduce `(- ,(reduce a) ,(reduce b)))] + [(list '- a) (reduce `(- ,(reduce a)))] + [(list '* a b) (reduce `(* ,(reduce a) ,(reduce b)))] + [(list '/ a b) (reduce `(/ ,(reduce a) ,(reduce b)))] + [(list 'tan (list 'arctan a)) (reduce a)] + [(list 'tan (list '- a)) (reduce `(- ,(reduce `(tan ,a))))] + [(list 'tan (list '+ a b)) (reduce `(/ (+ (tan ,a) (tan ,b)) + (- 1 (* (tan ,a) (tan ,b)))))] + [(list 'tan (list '+ a b c ...)) (reduce `(tan (+ ,a (+ ,b ,@c))))] + [(list 'tan (list '- a b)) (reduce `(/ (+ (tan ,a) (tan (- ,b))) + (- 1 (* (tan ,a) (tan (- ,b))))))] + [(list 'tan (list '* 1 a)) (reduce `(tan ,a))] + [(list 'tan (list '* (? number? n) a)) + (cond [(< n 0) (reduce `(- (tan (* ,(- n) ,a))))] + [(= n 0) 0] + [(even? n) (reduce `(tan (+ (* ,(/ n 2) ,a) (* ,(/ n 2) ,a))))] + [else (reduce `(tan (+ ,a (* ,(- n 1) ,a))))])])) + +(define correct-formulas + '((tan (+ (arctan 1/2) (arctan 1/3))) + (tan (+ (* 2 (arctan 1/3)) (arctan 1/7))) + (tan (- (* 4 (arctan 1/5)) (arctan 1/239))) + (tan (+ (* 5 (arctan 1/7)) (* 2 (arctan 3/79)))) + (tan (+ (* 5 (arctan 29/278)) (* 7 (arctan 3/79)))) + (tan (+ (arctan 1/2) (arctan 1/5) (arctan 1/8))) + (tan (+ (* 4 (arctan 1/5)) (* -1 (arctan 1/70)) (arctan 1/99))) + (tan (+ (* 5 (arctan 1/7)) (* 4 (arctan 1/53)) (* 2 (arctan 1/4443)))) + (tan (+ (* 6 (arctan 1/8)) (* 2 (arctan 1/57)) (arctan 1/239))) + (tan (+ (* 8 (arctan 1/10)) (* -1 (arctan 1/239)) (* -4 (arctan 1/515)))) + (tan (+ (* 12 (arctan 1/18)) (* 8 (arctan 1/57)) (* -5 (arctan 1/239)))) + (tan (+ (* 16 (arctan 1/21)) (* 3 (arctan 1/239)) (* 4 (arctan 3/1042)))) + (tan (+ (* 22 (arctan 1/28)) (* 2 (arctan 1/443)) (* -5 (arctan 1/1393)) (* -10 (arctan 1/11018)))) + (tan (+ (* 22 (arctan 1/38)) (* 17 (arctan 7/601)) (* 10 (arctan 7/8149)))) + (tan (+ (* 44 (arctan 1/57)) (* 7 (arctan 1/239)) (* -12 (arctan 1/682)) (* 24 (arctan 1/12943)))) + (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682)) + (* 44 (arctan 1/5357)) (* 68 (arctan 1/12943)))))) + +(define wrong-formula + '(tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682)) + (* 44 (arctan 1/5357)) (* 68 (arctan 1/12944))))) + +(displayln "Do all correct formulas reduce to 1?") +(for/and ([f correct-formulas]) (= 1 (reduce f))) + +(displayln "The incorrect formula reduces to:") +(reduce wrong-formula) diff --git a/Task/Check-Machin-like-formulas/Racket/check-machin-like-formulas-2.rkt b/Task/Check-Machin-like-formulas/Racket/check-machin-like-formulas-2.rkt new file mode 100644 index 0000000000..f4be12241f --- /dev/null +++ b/Task/Check-Machin-like-formulas/Racket/check-machin-like-formulas-2.rkt @@ -0,0 +1,4 @@ +Do all correct formulas reduce to 1? +#t +The incorrect formula reduces to: +1009288018000944050967896710431587186456256928584351786643498522649995492271475761189348270710224618853590682465929080006511691833816436374107451368838065354726517908250456341991684635768915704374493675498637876700129004484434187627909285979251682006538817341793224963346197503893270875008524149334251672855130857035205217929335932890740051319216343365800342290782260673215928499123722781078448297609548233999010983373327601187505623621602789012550584784738082074783523787011976757247516095289966708782862528690942242793667539020699840402353522108223/1009288837315638583415701528780402795721935641614456853534313491853293025565940011104051964874275710024625850092154664245109626053906509780125743180758231049920425664246286578958307532545458843067352531217230461290763258378749459637420702619029075083089762088232401888676895047947363883809724322868121990870409574061477638203859217672620508200713073485398199091153535700094640095900731630771349477187594074169815106104524371099618096164871416282464532355211521113449237814080332335526420331468258917484010722587072087349909684004660371264507984339711 diff --git a/Task/Check-Machin-like-formulas/Seed7/check-machin-like-formulas.seed7 b/Task/Check-Machin-like-formulas/Seed7/check-machin-like-formulas.seed7 new file mode 100644 index 0000000000..079bf8cb0b --- /dev/null +++ b/Task/Check-Machin-like-formulas/Seed7/check-machin-like-formulas.seed7 @@ -0,0 +1,72 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + include "bigrat.s7i"; + +const type: mTerms is array array bigInteger; + +const array mTerms: testCases is [] ( + [] ([] ( 1_, 1_, 2_), [] ( 1_, 1_, 3_)), + [] ([] ( 2_, 1_, 3_), [] ( 1_, 1_, 7_)), + [] ([] ( 4_, 1_, 5_), [] (-1_, 1_, 239_)), + [] ([] ( 5_, 1_, 7_), [] ( 2_, 3_, 79_)), + [] ([] ( 1_, 1_, 2_), [] ( 1_, 1_, 5_), [] ( 1_, 1_, 8_)), + [] ([] ( 4_, 1_, 5_), [] (-1_, 1_, 70_), [] ( 1_, 1_, 99_)), + [] ([] ( 5_, 1_, 7_), [] ( 4_, 1_, 53_), [] ( 2_, 1_, 4443_)), + [] ([] ( 6_, 1_, 8_), [] ( 2_, 1_, 57_), [] ( 1_, 1_, 239_)), + [] ([] ( 8_, 1_, 10_), [] (-1_, 1_, 239_), [] ( -4_, 1_, 515_)), + [] ([] (12_, 1_, 18_), [] ( 8_, 1_, 57_), [] ( -5_, 1_, 239_)), + [] ([] (16_, 1_, 21_), [] ( 3_, 1_, 239_), [] ( 4_, 3_, 1042_)), + [] ([] (22_, 1_, 28_), [] ( 2_, 1_, 443_), [] ( -5_, 1_, 1393_), [] (-10_, 1_, 11018_)), + [] ([] (22_, 1_, 38_), [] (17_, 7_, 601_), [] ( 10_, 7_, 8149_)), + [] ([] (44_, 1_, 57_), [] ( 7_, 1_, 239_), [] (-12_, 1_, 682_), [] ( 24_, 1_, 12943_)), + [] ([] (88_, 1_, 172_), [] (51_, 1_, 239_), [] ( 32_, 1_, 682_), [] ( 44_, 1_, 5357_), [] (68_, 1_, 12943_)), + [] ([] (88_, 1_, 172_), [] (51_, 1_, 239_), [] ( 32_, 1_, 682_), [] ( 44_, 1_, 5357_), [] (68_, 1_, 12944_)) + ); + +const func bigRational: tanEval (in bigInteger: coef, in bigRational: f) is func + result + var bigRational: tanEval is bigRational.value; + local + var bigRational: a is bigRational.value; + var bigRational: b is bigRational.value; + begin + if coef = 1_ then + tanEval := f; + elsif coef < 0_ then + tanEval := -tanEval(-coef, f); + else + a := tanEval(coef div 2_, f); + b := tanEval(coef - coef div 2_, f); + tanEval := (a + b) / (1_/1_ - a * b); + end if; + end func; + +const func bigRational: tans (in mTerms: terms) is func + result + var bigRational: tans is bigRational.value; + local + var bigRational: a is bigRational.value; + var bigRational: b is bigRational.value; + begin + if length(terms) = 1 then + tans := tanEval(terms[1][1], terms[1][2] / terms[1][3]); + else + a := tans(terms[.. length(terms) div 2]); + b := tans(terms[succ(length(terms) div 2) ..]); + tans := (a + b) / (1_/1_ - a * b); + end if; + end func; + +const proc: main is func + local + var integer: index is 0; + var array bigInteger: term is 0 times 0_; + begin + for key index range testCases do + write(tans(testCases[index]) = 1_/1_ <& ": pi/4 = "); + for term range testCases[index] do + write([0] ("+", "-")[ord(term[1] < 0_)] <& abs(term[1]) <& "*arctan(" <& term[2] <& "/" <& term[3] <& ")"); + end for; + writeln; + end for; + end func; diff --git a/Task/Check-that-file-exists/Erlang/check-that-file-exists.erl b/Task/Check-that-file-exists/Erlang/check-that-file-exists.erl index b21ff923b0..c5a82b4fe0 100644 --- a/Task/Check-that-file-exists/Erlang/check-that-file-exists.erl +++ b/Task/Check-that-file-exists/Erlang/check-that-file-exists.erl @@ -1,23 +1,12 @@ #!/usr/bin/escript -file_exists(Filename) -> - { Flag, _ } = file:read_file_info(Filename), Flag == ok. +existence( true ) ->"exists"; +existence( false ) ->"does not exist". -dir_exists(Filename) -> - { Flag, Info } = file:read_file_info(Filename), - (Flag == ok) andalso (element(3, Info) == directory). +print_result(Type, Name, Flag) -> io:fwrite( "~s ~s ~s~n", [Type, Name, existence(Flag)] ). -print_result(Flag, Filename) -> - Tail = if - Flag -> "exists"; - true -> "does not exist" - end, - io:put_chars(lists:concat([Filename, " ", Tail, "\n"])). - -check_file(Filename) -> print_result(file_exists(Filename), Filename). -check_dir(Filename) -> print_result(dir_exists(Filename), Filename). main(_) -> - check_file("input.txt"), - check_dir("docs"), - check_file("/input.txt"), - check_dir("/docs"). + print_result( "File", "input.txt", filelib:is_regular("input.txt") ), + print_result( "Directory", "docs", filelib:is_dir("docs") ), + print_result( "File", "/input.txt", filelib:is_regular("/input.txt") ), + print_result( "Directory", "/docs", filelib:is_dir("/docs") ). diff --git a/Task/Check-that-file-exists/Racket/check-that-file-exists.rkt b/Task/Check-that-file-exists/Racket/check-that-file-exists.rkt new file mode 100644 index 0000000000..fc4348d137 --- /dev/null +++ b/Task/Check-that-file-exists/Racket/check-that-file-exists.rkt @@ -0,0 +1,14 @@ +#lang racket + +;; here +(file-exists? "input.txt") +(file-exists? "docs") + +;; in the root +(file-exists? "/input.txt") +(file-exists? "/docs") + +;; or in the root with relative paths +(parameterize ([current-directory "/"]) + (and (file-exists? "input.txt") + (file-exists? "docs"))) diff --git a/Task/Checkpoint-synchronization/Racket/checkpoint-synchronization-1.rkt b/Task/Checkpoint-synchronization/Racket/checkpoint-synchronization-1.rkt new file mode 100644 index 0000000000..d946d6a738 --- /dev/null +++ b/Task/Checkpoint-synchronization/Racket/checkpoint-synchronization-1.rkt @@ -0,0 +1,44 @@ +#lang racket +(define t 5) ; total number of threads +(define count 0) ; number of threads arrived at rendezvous +(define mutex (make-semaphore 1)) ; exclusive access to count +(define turnstile (make-semaphore 0)) +(define turnstile2 (make-semaphore 1)) +(define ch (make-channel)) + +(define (make-producer name start) + (λ () + (let loop ([n start]) + (sleep (* 0.01 (random 10))) ; "compute" something + ;; rendezvous + (semaphore-wait mutex) + (set! count (+ count 1)) ; we have arrived + (when (= count t) ; are we the last to arrive? + (semaphore-wait turnstile2) + (semaphore-post turnstile)) + (semaphore-post mutex) + ; avoid deadlock problem: + (semaphore-wait turnstile) + (semaphore-post turnstile) + ; critical point + (channel-put ch n) ; send result to controller + ; leave properly + (semaphore-wait mutex) + (set! count (- count 1)) + (when (= count 0) ; are we the last to leave? + (semaphore-wait turnstile) + (semaphore-post turnstile2)) + (semaphore-post mutex) + + (semaphore-wait turnstile2) + (semaphore-post turnstile2) + + (loop (+ n t))))) + +; start t workers: +(map (λ(start) (thread (make-producer start start))) + (range 0 t)) + +(let loop () + (displayln (for/list ([_ t]) (channel-get ch))) + (loop)) diff --git a/Task/Checkpoint-synchronization/Racket/checkpoint-synchronization-2.rkt b/Task/Checkpoint-synchronization/Racket/checkpoint-synchronization-2.rkt new file mode 100644 index 0000000000..cb33a7211a --- /dev/null +++ b/Task/Checkpoint-synchronization/Racket/checkpoint-synchronization-2.rkt @@ -0,0 +1,21 @@ +(1 4 2 0 3) +(6 9 7 8 5) +(11 10 14 12 13) +(16 15 18 19 17) +(24 21 20 23 22) +(29 25 28 27 26) +(30 33 34 32 31) +(37 38 39 35 36) +(44 43 41 40 42) +(46 45 48 49 47) +(50 53 51 54 52) +(56 57 58 55 59) +(60 63 62 61 64) +(66 69 65 68 67) +(73 70 74 71 72) +(78 77 76 79 75) +(82 80 81 84 83) +(87 89 88 86 85) +(92 93 90 91 94) +(97 98 99 95 96) +... diff --git a/Task/Cholesky-decomposition/Racket/cholesky-decomposition-1.rkt b/Task/Cholesky-decomposition/Racket/cholesky-decomposition-1.rkt new file mode 100644 index 0000000000..ca1f8cbea4 --- /dev/null +++ b/Task/Cholesky-decomposition/Racket/cholesky-decomposition-1.rkt @@ -0,0 +1,28 @@ +#lang racket +(require math) + +(define (cholesky A) + (define mref matrix-ref) + (define n (matrix-num-rows A)) + (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) + (define (set L i j x) (vector-set! (vector-ref L i) j x)) + (define (ref L i j) (vector-ref (vector-ref L i) j)) + (for* ([i n] [k n]) + (set L i k + (cond + [(= i k) + (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] + [(> i k) + (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) + (ref L k k))] + [else 0]))) + L) + +(cholesky (matrix [[25 15 -5] + [15 18 0] + [-5 0 11]])) + +(cholesky (matrix [[18 22 54 42] + [22 70 86 62] + [54 86 174 134] + [42 62 134 106]])) diff --git a/Task/Cholesky-decomposition/Racket/cholesky-decomposition-2.rkt b/Task/Cholesky-decomposition/Racket/cholesky-decomposition-2.rkt new file mode 100644 index 0000000000..3ba4ec3991 --- /dev/null +++ b/Task/Cholesky-decomposition/Racket/cholesky-decomposition-2.rkt @@ -0,0 +1,7 @@ +'#(#(5 0 0) + #(3 3 0) + #(-1 1 3)) +'#(#(4.242640687119285 0 0 0) + #( 5.185449728701349 6.565905201197403 0 0) + #(12.727922061357857 3.0460384954008553 1.6497422479090704 0) + #( 9.899494936611665 1.6245538642137891 1.849711005231382 1.3926212476455924)) diff --git a/Task/Cholesky-decomposition/Scala/cholesky-decomposition.scala b/Task/Cholesky-decomposition/Scala/cholesky-decomposition.scala new file mode 100644 index 0000000000..e054577a6b --- /dev/null +++ b/Task/Cholesky-decomposition/Scala/cholesky-decomposition.scala @@ -0,0 +1,61 @@ +case class Matrix( val matrix:Array[Array[Double]] ) { + + // Assuming matrix is positive-definite, symmetric and not empty... + + val rows,cols = matrix.size + + def getOption( r:Int, c:Int ) : Option[Double] = Pair(r,c) match { + case (r,c) if r < rows && c < rows => Some(matrix(r)(c)) + case _ => None + } + + def isLowerTriangle( r:Int, c:Int ) : Boolean = { c <= r } + def isDiagonal( r:Int, c:Int ) : Boolean = { r == c} + + override def toString = matrix.map(_.mkString(", ")).mkString("\n") + + /** + * Perform Cholesky Decomposition of this matrix + */ + lazy val cholesky : Matrix = { + + val l = Array.ofDim[Double](rows*cols) + + for( i <- (0 until rows); j <- (0 until cols) ) yield { + + val s = (for( k <- (0 until j) ) yield { l(i*rows+k) * l(j*rows+k) }).sum + + l(i*rows+j) = (i,j) match { + case (r,c) if isDiagonal(r,c) => scala.math.sqrt(matrix(i)(i) - s) + case (r,c) if isLowerTriangle(r,c) => (1.0 / l(j*rows+j) * (matrix(i)(j) - s)) + case _ => 0 + } + } + + val m = Array.ofDim[Double](rows,cols) + for( i <- (0 until rows); j <- (0 until cols) ) m(i)(j) = l(i*rows+j) + Matrix(m) + } +} + +// A little test... +val a1 = Matrix(Array[Array[Double]](Array(25,15,-5),Array(15,18,0),Array(-5,0,11))) +val a2 = Matrix(Array[Array[Double]](Array(18,22,54,42), Array(22,70,86,62), Array(54,86,174,134), Array(42,62,134,106))) + +val l1 = a1.cholesky +val l2 = a2.cholesky + + +// Given test results +val r1 = Array[Double](5,0,0,3,3,0,-1,1,3) +val r2 = Array[Double](4.24264,0.00000,0.00000,0.00000,5.18545,6.56591,0.00000,0.00000, + 12.72792,3.04604,1.64974,0.00000,9.89949,1.62455,1.84971,1.39262) + +// Verify assertions +(l1.matrix.flatten.zip(r1)).foreach{ case (result,test) => + assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001) +} + +(l2.matrix.flatten.zip(r2)).foreach{ case (result,test) => + assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001) +} diff --git a/Task/Cholesky-decomposition/Seed7/cholesky-decomposition.seed7 b/Task/Cholesky-decomposition/Seed7/cholesky-decomposition.seed7 new file mode 100644 index 0000000000..08c3d096dd --- /dev/null +++ b/Task/Cholesky-decomposition/Seed7/cholesky-decomposition.seed7 @@ -0,0 +1,60 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + +const type: matrix is array array float; + +const func matrix: cholesky (in matrix: a) is func + result + var matrix: cholesky is 0 times 0 times 0.0; + local + var integer: i is 0; + var integer: j is 0; + var integer: k is 0; + var float: sum is 0.0; + begin + cholesky := length(a) times length(a) times 0.0; + for key i range cholesky do + for j range 1 to i do + sum := 0.0; + for k range 1 to j do + sum +:= cholesky[i][k] * cholesky[j][k]; + end for; + if i = j then + cholesky[i][i] := sqrt(a[i][i] - sum) + else + cholesky[i][j] := (a[i][j] - sum) / cholesky[j][j]; + end if; + end for; + end for; + end func; + +const proc: writeMat (in matrix: a) is func + local + var integer: i is 0; + var float: num is 0.0; + begin + for key i range a do + for num range a[i] do + write(num digits 5 lpad 8); + end for; + writeln; + end for; + end func; + +const matrix: m1 is [] ( + [] (25.0, 15.0, -5.0), + [] (15.0, 18.0, 0.0), + [] (-5.0, 0.0, 11.0)); +const matrix: m2 is [] ( + [] (18.0, 22.0, 54.0, 42.0), + [] (22.0, 70.0, 86.0, 62.0), + [] (54.0, 86.0, 174.0, 134.0), + [] (42.0, 62.0, 134.0, 106.0)); + +const proc: main is func + begin + writeMat(cholesky(m1)); + writeln; + writeMat(cholesky(m2)); + end func; diff --git a/Task/Closest-pair-problem/Racket/closest-pair-problem-1.rkt b/Task/Closest-pair-problem/Racket/closest-pair-problem-1.rkt new file mode 100644 index 0000000000..56f18b6dad --- /dev/null +++ b/Task/Closest-pair-problem/Racket/closest-pair-problem-1.rkt @@ -0,0 +1,15 @@ +#lang racket +(define (dist z0 z1) (magnitude (- z1 z0))) +(define (dist* zs) (apply dist zs)) + +(define (closest-pair zs) + (if (< (length zs) 2) + -inf.0 + (first + (sort (for/list ([z0 zs]) + (list z0 (argmin (λ(z) (if (= z z0) +inf.0 (dist z z0))) zs))) + < #:key dist*)))) + +(define result (closest-pair '(0+1i 1+2i 3+4i))) +(displayln (~a "Closest points: " result)) +(displayln (~a "Distance: " (dist* result))) diff --git a/Task/Closest-pair-problem/Racket/closest-pair-problem-2.rkt b/Task/Closest-pair-problem/Racket/closest-pair-problem-2.rkt new file mode 100644 index 0000000000..0963cfb6f3 --- /dev/null +++ b/Task/Closest-pair-problem/Racket/closest-pair-problem-2.rkt @@ -0,0 +1,2 @@ +Closest points: (0+1i 1+2i) +Distance: 1.4142135623730951 diff --git a/Task/Collections/Aime/collections-1.aime b/Task/Collections/Aime/collections-1.aime new file mode 100644 index 0000000000..104f2e6d66 --- /dev/null +++ b/Task/Collections/Aime/collections-1.aime @@ -0,0 +1 @@ +list l; diff --git a/Task/Collections/Aime/collections-2.aime b/Task/Collections/Aime/collections-2.aime new file mode 100644 index 0000000000..7a6f729390 --- /dev/null +++ b/Task/Collections/Aime/collections-2.aime @@ -0,0 +1,3 @@ +l_p_integer(l, 0, 7); +l_push(l, "a string"); +l_append(l, 2.5); diff --git a/Task/Collections/Aime/collections-3.aime b/Task/Collections/Aime/collections-3.aime new file mode 100644 index 0000000000..3f2486f91e --- /dev/null +++ b/Task/Collections/Aime/collections-3.aime @@ -0,0 +1,3 @@ +l_query(l, 2); +l_head(l); +l_q_text(l, 1); diff --git a/Task/Collections/Aime/collections-4.aime b/Task/Collections/Aime/collections-4.aime new file mode 100644 index 0000000000..4868afeb8a --- /dev/null +++ b/Task/Collections/Aime/collections-4.aime @@ -0,0 +1 @@ +record r; diff --git a/Task/Collections/Aime/collections-5.aime b/Task/Collections/Aime/collections-5.aime new file mode 100644 index 0000000000..12b9dd2faa --- /dev/null +++ b/Task/Collections/Aime/collections-5.aime @@ -0,0 +1,2 @@ +r_p_integer(r, "key1", 7); +r_put(r, "key2", "a string"); diff --git a/Task/Collections/Aime/collections-6.aime b/Task/Collections/Aime/collections-6.aime new file mode 100644 index 0000000000..3a2750998f --- /dev/null +++ b/Task/Collections/Aime/collections-6.aime @@ -0,0 +1,2 @@ +r_query(r, "key1"); +r_tail(r); diff --git a/Task/Collections/Racket/collections.rkt b/Task/Collections/Racket/collections.rkt new file mode 100644 index 0000000000..ee8441834e --- /dev/null +++ b/Task/Collections/Racket/collections.rkt @@ -0,0 +1,8 @@ +#lang racket + +;; create a list +(list 1 2 3 4) +;; create a list of size N +(make-list 100 0) +;; add an element to the front of a list (non-destructively) +(cons 1 (list 2 3 4)) diff --git a/Task/Collections/Ruby/collections-1.rb b/Task/Collections/Ruby/collections-1.rb index 8ff9b3b5a0..10ae7d056f 100644 --- a/Task/Collections/Ruby/collections-1.rb +++ b/Task/Collections/Ruby/collections-1.rb @@ -1,8 +1,12 @@ # creating an empty array and adding values -a = [] # => [] -a[0] = 1 # => [1] -a[3] = 2 # => [1, nil, nil, 2] +a = [] #=> [] +a[0] = 1 #=> [1] +a[3] = "abc" #=> [1, nil, nil, "abc"] +a << 3.14 #=> [1, nil, nil, "abc", 3.14] # creating an array with the constructor -a = Array.new # => [] +a = Array.new #=> [] +a = Array.new(3) #=> [nil, nil, nil] +a = Array.new(3, 0) #=> [0, 0, 0] +a = Array.new(3){|i| i*2} #=> [0, 2, 4] diff --git a/Task/Collections/Ruby/collections-2.rb b/Task/Collections/Ruby/collections-2.rb index 437bb285a6..6f15f724dc 100644 --- a/Task/Collections/Ruby/collections-2.rb +++ b/Task/Collections/Ruby/collections-2.rb @@ -1,9 +1,23 @@ # creating an empty hash -h = {} # => {} -h["a"] = 1 # => {"a" => 1} -h["test"] = 2.4 # => {"a" => 1, "test" => 2.4} -h[3] = "Hello" # => {"a" => 1, "test" => 2.4, 3 => "Hello"} +h = {} #=> {} +h["a"] = 1 #=> {"a"=>1} +h["test"] = 2.4 #=> {"a"=>1, "test"=>2.4} +h[3] = "Hello" #=> {"a"=>1, "test"=>2.4, 3=>"Hello"} +h = {a:1, test:2.4, World!:"Hello"} + #=> {:a=>1, :test=>2.4, :World!=>"Hello"} # creating a hash with the constructor -h = Hash.new # => {} +h = Hash.new #=> {} (default value : nil) +p h[1] #=> nil +h = Hash.new(0) #=> {} (default value : 0) +p h[1] #=> 0 +p h #=> {} +h = Hash.new{|hash, key| key.to_s} + #=> {} +p h[123] #=> "123" +p h #=> {} +h = Hash.new{|hash, key| hash[key] = "foo#{key}"} + #=> {} +p h[1] #=> "foo1" +p h #=> {1=>"foo1"} diff --git a/Task/Collections/Ruby/collections-3.rb b/Task/Collections/Ruby/collections-3.rb new file mode 100644 index 0000000000..57466a7e88 --- /dev/null +++ b/Task/Collections/Ruby/collections-3.rb @@ -0,0 +1,22 @@ +# creating a struct + +Person = Struct.new(:name, :age, :sex) + +a = Person.new("Peter", 15, :Man) +p a[0] #=> "Peter" +p a[:age] #=> 15 +p a.sex #=> :Man +p a.to_a #=> ["Peter", 15, :Man] +p a.to_h #=> {:name=>"Peter", :age=>15, :sex=>:Man} + +b = Person.new +p b #=> # +b.name = "Margaret" +b["age"] = 18 +b[-1] = :Woman +p b.values #=> ["Margaret", 18, :Woman] +p b.members #=> [:name, :age, :sex] +p b.size #=> 3 + +c = Person["Daniel", 22, :Man] +p c.to_h #=> {:name=>"Daniel", :age=>22, :sex=>:Man} diff --git a/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 b/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 new file mode 100644 index 0000000000..dd03d6b894 --- /dev/null +++ b/Task/Colour-bars-Display/Perl-6/colour-bars-display.pl6 @@ -0,0 +1,29 @@ +my $HOR = 1280; +my $VERT = 720; + +my @colors = map -> $r, $g, $b { Buf.new: ($r, $g, $b) xx $HOR div 8 }, + 0, 0, 0, + 255, 0, 0, + 0,255, 0, + 0, 0,255, + 255, 0,255, + 0,255,255, + 255,255, 0, + 255,255,255; + +my $PPM = open "colorbars.ppm", :w, :bin or die "Can't create colorbars.ppm: $!"; + +$PPM.print: qq:to/EOH/; + P6 + # colorbars.ppm + $HOR $VERT + 255 + EOH + +for ^$VERT -> $v { + for ^@colors -> $h { + $PPM.write: @colors[$h]; + } +} + +$PPM.close; diff --git a/Task/Colour-bars-Display/Racket/colour-bars-display.rkt b/Task/Colour-bars-Display/Racket/colour-bars-display.rkt new file mode 100644 index 0000000000..fd2827234f --- /dev/null +++ b/Task/Colour-bars-Display/Racket/colour-bars-display.rkt @@ -0,0 +1,24 @@ +#lang racket/gui + +(define-values [W H] (get-display-size #t)) + +(define colors + '("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White")) + +(define (paint-pinstripe canvas dc) + (send dc set-pen "black" 0 'transparent) + (for ([x (in-range 0 W (/ W (length colors)))] [c colors]) + (send* dc (set-brush c 'solid) (draw-rectangle x 0 W H)))) + +(define full-frame% + (class frame% + (define/override (on-subwindow-char r e) + (when (eq? 'escape (send e get-key-code)) + (send this show #f))) + (super-new + [label "Color bars"] [width W] [height H] + [style '(no-caption no-resize-border hide-menu-bar no-system-menu)]) + (define c (new canvas% [parent this] [paint-callback paint-pinstripe])) + (send this show #t))) + +(void (new full-frame%)) diff --git a/Task/Colour-pinstripe-Display/C++/colour-pinstripe-display.cpp b/Task/Colour-pinstripe-Display/C++/colour-pinstripe-display.cpp new file mode 100644 index 0000000000..578acb5b2f --- /dev/null +++ b/Task/Colour-pinstripe-Display/C++/colour-pinstripe-display.cpp @@ -0,0 +1,120 @@ +#include + +//-------------------------------------------------------------------------------------------------- +class pinstripe +{ +public: + pinstripe() { createColors(); } + void setDimensions( int x, int y ) { _mw = x; _mh = y; } + void createColors() + { + colors[0] = 0; colors[1] = 255; colors[2] = RGB( 0, 255, 0 ); + colors[3] = RGB( 0, 0, 255 ); colors[4] = RGB( 255, 0, 255 ); + colors[5] = RGB( 0, 255, 255 ); colors[6] = RGB( 255, 255, 0 ); + colors[7] = RGB( 255, 255, 255 ); + } + + void draw( HDC dc ) + { + HPEN pen; + int lh = _mh / 4, row, cp; + for( int lw = 1; lw < 5; lw++ ) + { + cp = 0; + row = ( lw - 1 ) * lh; + for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw ) + { + pen = CreatePen( PS_SOLID, lw, colors[cp] ); + ++cp %= 8; + + SelectObject( dc, pen ); + MoveToEx( dc, x, row, NULL ); + LineTo( dc, x, row + lh ); + DeleteObject( pen ); + } + } + } + +private: + int _mw, _mh; + DWORD colors[8]; +}; +//-------------------------------------------------------------------------------------------------- +pinstripe pin; + +//-------------------------------------------------------------------------------------------------- +void PaintWnd( HWND hWnd ) +{ + PAINTSTRUCT ps; + HDC hdc = BeginPaint( hWnd, &ps ); + pin.draw( hdc ); + EndPaint( hWnd, &ps ); +} +//-------------------------------------------------------------------------------------------------- +LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) +{ + switch( msg ) + { + case WM_DESTROY: PostQuitMessage( 0 ); break; + case WM_PAINT: PaintWnd( hWnd ); break; + default: + return DefWindowProc( hWnd, msg, wParam, lParam ); + } + return 0; +} +//-------------------------------------------------------------------------------------------------- +HWND InitAll( HINSTANCE hInstance ) +{ + WNDCLASSEX wcex; + ZeroMemory( &wcex, sizeof( wcex ) ); + + wcex.cbSize = sizeof( WNDCLASSEX ); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.hInstance = hInstance; + wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); + wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); + wcex.lpszClassName = "_CLR_PS_"; + + RegisterClassEx( &wcex ); + return CreateWindow( "_CLR_PS_", ".: Clr Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL ); +} +//-------------------------------------------------------------------------------------------------- +int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) +{ + srand( GetTickCount() ); + + HWND hwnd = InitAll( hInstance ); + if( !hwnd ) return -1; + + int mw = GetSystemMetrics( SM_CXSCREEN ), + mh = GetSystemMetrics( SM_CYSCREEN ); + + pin.setDimensions( mw, mh ); + + RECT rc = { 0, 0, mw, mh }; + + AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 ); + int w = rc.right - rc.left, + h = rc.bottom - rc.top; + + int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ), + posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 ); + + SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER ); + ShowWindow( hwnd, nCmdShow ); + UpdateWindow( hwnd ); + + MSG msg; + ZeroMemory( &msg, sizeof( msg ) ); + while( msg.message != WM_QUIT ) + { + if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) + { + TranslateMessage( &msg ); + DispatchMessage( &msg ); + } + } + return UnregisterClass( "_CLR_PS_", hInstance ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Colour-pinstripe-Display/Perl-6/colour-pinstripe-display.pl6 b/Task/Colour-pinstripe-Display/Perl-6/colour-pinstripe-display.pl6 new file mode 100644 index 0000000000..9fbbdeee14 --- /dev/null +++ b/Task/Colour-pinstripe-Display/Perl-6/colour-pinstripe-display.pl6 @@ -0,0 +1,30 @@ +my $HOR = 1280; +my $VERT = 720; + +my @colors = map -> $r, $g, $b { [$r, $g, $b] }, + 0, 0, 0, + 255, 0, 0, + 0,255, 0, + 0, 0,255, + 255, 0,255, + 0,255,255, + 255,255, 0, + 255,255,255; + +my $PPM = open "pinstripes.ppm", :w, :bin or die "Can't create pinstripes.ppm: $!"; + +$PPM.print: qq:to/EOH/; + P6 + # pinstripes.ppm + $HOR $VERT + 255 + EOH + +my $vzones = $VERT div 4; +for 1..4 -> $w { + my $hzones = ceiling $HOR / $w / +@colors; + my $line = Buf.new: ((@colors Xxx $w) xx $hzones).splice(0,$HOR).map: *.values; + $PPM.write: $line for ^$vzones; +} + +$PPM.close; diff --git a/Task/Colour-pinstripe-Display/Racket/colour-pinstripe-display.rkt b/Task/Colour-pinstripe-Display/Racket/colour-pinstripe-display.rkt new file mode 100644 index 0000000000..ef946aa4ae --- /dev/null +++ b/Task/Colour-pinstripe-Display/Racket/colour-pinstripe-display.rkt @@ -0,0 +1,30 @@ +#lang racket/gui + +(define-values [W H] (get-display-size #t)) + +(define parts 4) +(define colors + '("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White")) + +(define (paint-pinstripe canvas dc) + (send dc set-pen "black" 0 'transparent) + (send dc set-brush "black" 'solid) + (define H* (round (/ H parts))) + (for ([row parts]) + (define Y (* row H*)) + (for ([X (in-range 0 W (add1 row))] [c (in-cycle colors)]) + (send dc set-brush c 'solid) + (send dc draw-rectangle X Y (add1 row) H*)))) + +(define full-frame% + (class frame% + (define/override (on-subwindow-char r e) + (when (eq? 'escape (send e get-key-code)) + (send this show #f))) + (super-new + [label "Color Pinstripe"] [width W] [height H] + [style '(no-caption no-resize-border hide-menu-bar no-system-menu)]) + (define c (new canvas% [parent this] [paint-callback paint-pinstripe])) + (send this show #t))) + +(void (new full-frame%)) diff --git a/Task/Colour-pinstripe-Printer/Racket/colour-pinstripe-printer.rkt b/Task/Colour-pinstripe-Printer/Racket/colour-pinstripe-printer.rkt new file mode 100644 index 0000000000..303498430a --- /dev/null +++ b/Task/Colour-pinstripe-Printer/Racket/colour-pinstripe-printer.rkt @@ -0,0 +1,21 @@ +#lang racket/gui + +(define parts 4) + +(define dc (new printer-dc%)) +(send* dc (start-doc "Colour Pinstripe") (start-page)) + +(define-values [W H] (send dc get-size)) +(define parts 4) +(define colors + '("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White")) +(send dc set-pen "black" 0 'transparent) +(send dc set-brush "black" 'solid) +(define H* (round (/ H parts))) +(for ([row parts]) + (define Y (* row H*)) + (for ([X (in-range 0 W (add1 row))] [c (in-cycle colors)]) + (send dc set-brush c 'solid) + (send dc draw-rectangle X Y (add1 row) H*))) + +(send* dc (end-page) (end-doc)) diff --git a/Task/Combinations-with-repetitions/00DESCRIPTION b/Task/Combinations-with-repetitions/00DESCRIPTION index dac3339d8e..fc50ae4a19 100644 --- a/Task/Combinations-with-repetitions/00DESCRIPTION +++ b/Task/Combinations-with-repetitions/00DESCRIPTION @@ -12,3 +12,6 @@ The set of combinations with repetitions is computed from a set, S '''References:''' * [[wp:Combination|k-combination with repetitions]] + +'''See Also:''' +{{Template:Combinations and permutations}} diff --git a/Task/Combinations-with-repetitions/D/combinations-with-repetitions-1.d b/Task/Combinations-with-repetitions/D/combinations-with-repetitions-1.d new file mode 100644 index 0000000000..3583ca7429 --- /dev/null +++ b/Task/Combinations-with-repetitions/D/combinations-with-repetitions-1.d @@ -0,0 +1,86 @@ +import std.stdio, std.range; + +const struct CombRep { + immutable uint nt, nc; + private immutable ulong[] combVal; + + this(in uint numType, in uint numChoice) pure nothrow + in { + assert(0 < numType && numType + numChoice <= 64, + "Valid only for nt + nc <= 64 (ulong bit size)"); + } body { + nt = numType; + nc = numChoice; + if (nc == 0) + return; + ulong v = (1UL << (nt - 1)) - 1; + + // Init to smallest number that has nt-1 bit set + // a set bit is metaphored as a _type_ seperator. + immutable limit = v << nc; + + // Limit is the largest nt-1 bit set number that has nc + // zero-bit a zero-bit means a _choice_ between _type_ + // seperators. + while (v <= limit) { + combVal ~= v; + if (v == 0) + break; + // Get next nt-1 bit number. + immutable t = (v | (v - 1)) + 1; + v = t | ((((t & -t) / (v & -v)) >> 1) - 1); + } + } + + uint length() @property const pure nothrow { + return combVal.length; + } + + uint[] opIndex(in uint idx) const pure nothrow { + return val2set(combVal[idx]); + } + + int opApply(immutable int delegate(in ref uint[]) dg) { + foreach (immutable v; combVal) { + auto set = val2set(v); + if (dg(set)) + break; + } + return 1; + } + + private uint[] val2set(in ulong v) const pure nothrow { + // Convert bit pattern to selection set + immutable uint bitLimit = nt + nc - 1; + uint typeIdx = 0; + uint[] set; + foreach (immutable bitNum; 0 .. bitLimit) + if (v & (1 << (bitLimit - bitNum - 1))) + typeIdx++; + else + set ~= typeIdx; + return set; + } +} + +// For finite Random Access Range. +auto combRep(R)(R types, in uint numChoice) /*pure nothrow*/ +if (hasLength!R && isRandomAccessRange!R) { + ElementType!R[][] result; + + foreach (const s; CombRep(types.length, numChoice)) { + ElementType!R[] r; + foreach (immutable i; s) + r ~= types[i]; + result ~= r; + } + + return result; +} + +void main() { + foreach (const e; combRep(["iced", "jam", "plain"], 2)) + writefln("%-(%5s %)", e); + writeln("Ways to select 3 from 10 types is ", + CombRep(10, 3).length); +} diff --git a/Task/Combinations-with-repetitions/D/combinations-with-repetitions-2.d b/Task/Combinations-with-repetitions/D/combinations-with-repetitions-2.d new file mode 100644 index 0000000000..9a70af085d --- /dev/null +++ b/Task/Combinations-with-repetitions/D/combinations-with-repetitions-2.d @@ -0,0 +1,16 @@ +import std.stdio, std.range, std.algorithm; + +T[][] combsRep(T)(T[] lst, in int k) { + if (k == 0) + return [[]]; + if (lst.empty) + return null; + + return combsRep(lst, k - 1).map!(L => lst[0] ~ L).array + ~ combsRep(lst[1 .. $], k); +} + +void main() { + ["iced", "jam", "plain"].combsRep(2).writeln; + 10.iota.array.combsRep(3).length.writeln; +} diff --git a/Task/Combinations-with-repetitions/Racket/combinations-with-repetitions.rkt b/Task/Combinations-with-repetitions/Racket/combinations-with-repetitions.rkt new file mode 100644 index 0000000000..37abb6e998 --- /dev/null +++ b/Task/Combinations-with-repetitions/Racket/combinations-with-repetitions.rkt @@ -0,0 +1,7 @@ +#lang racket +(define (combinations xs k) + (cond [(= k 0) '(())] + [(empty? xs) '()] + [(append (combinations (rest xs) k) + (map (λ(x) (cons (first xs) x)) + (combinations xs (- k 1))))])) diff --git a/Task/Combinations/00DESCRIPTION b/Task/Combinations/00DESCRIPTION index 32bf885ca0..bccf71426b 100644 --- a/Task/Combinations/00DESCRIPTION +++ b/Task/Combinations/00DESCRIPTION @@ -12,3 +12,6 @@ For example, 3 comb 5 is 2 3 4 If it is more "natural" in your language to start counting from 1 instead of 0 the combinations can be of the integers from 1 to n. + +'''See Also:''' +{{Template:Combinations and permutations}} diff --git a/Task/Combinations/ALGOL-68/combinations-1.alg b/Task/Combinations/ALGOL-68/combinations-1.alg new file mode 100644 index 0000000000..1f7d9aec5f --- /dev/null +++ b/Task/Combinations/ALGOL-68/combinations-1.alg @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- # + +COMMENT REQUIRED BY "prelude_combinations_generative.a68" + MODE COMBDATA = ~; +PROVIDES: +# COMBDATA*=~* # +# comb*=~ list* # +END COMMENT + +MODE COMBDATALIST = REF[]COMBDATA; +MODE COMBDATALISTYIELD = PROC(COMBDATALIST)VOID; + +PROC comb gen combinations = (INT m, COMBDATALIST list, COMBDATALISTYIELD yield)VOID:( + CASE m IN + # case 1: transpose list # + FOR i TO UPB list DO yield(list[i]) OD + OUT + [m + LWB list - 1]COMBDATA out; + INT index out := 1; + FOR i TO UPB list DO + COMBDATA first = list[i]; + # FOR COMBDATALIST sub recombination IN # comb gen combinations(m - 1, list[i+1:] #) DO (#, + ## (COMBDATALIST sub recombination)VOID:( + out[LWB list ] := first; + out[LWB list+1:] := sub recombination; + yield(out) + # OD #)) + OD + ESAC +); + +SKIP diff --git a/Task/Combinations/ALGOL-68/combinations-2.alg b/Task/Combinations/ALGOL-68/combinations-2.alg new file mode 100644 index 0000000000..540d71e835 --- /dev/null +++ b/Task/Combinations/ALGOL-68/combinations-2.alg @@ -0,0 +1,21 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +CO REQUIRED BY "prelude_combinations.a68" CO + MODE COMBDATA = INT; +#PROVIDES:# +# COMBDATA~=INT~ # +# comb ~=int list ~# +PR READ "prelude_combinations.a68" PR; + +FORMAT data fmt = $g(0)$; + +main:( + INT m = 3; + FORMAT list fmt = $"("n(m-1)(f(data fmt)",")f(data fmt)")"$; + FLEX[0]COMBDATA test data list := (1,2,3,4,5); +# FOR COMBDATALIST recombination data IN # comb gen combinations(m, test data list #) DO (#, +## (COMBDATALIST recombination)VOID:( + printf ((list fmt, recombination, $l$)) +# OD # )) +) diff --git a/Task/Combinations/J/combinations-1.j b/Task/Combinations/J/combinations-1.j index 5755d528dc..cf86f6b0c2 100644 --- a/Task/Combinations/J/combinations-1.j +++ b/Task/Combinations/J/combinations-1.j @@ -1,5 +1,5 @@ comb1=: dyad define c=. 1 {.~ - d=. 1+y-x z=. i.1 0 - for_j. (d-1+y)+/&i.d do. z=. (c#j) ,. z{~;(-c){.&.><i.{.c=. +/\.c end. + for_j. (d-1+y)+/&i.d do. z=. (c#j) ,. z{~;(-c){.&.>/:~-:\:~)"1)@(# #: [: i. ^~) diff --git a/Task/Combinations/Julia/combinations.julia b/Task/Combinations/Julia/combinations.julia index 9b5980a997..fa5e5688c4 100644 --- a/Task/Combinations/Julia/combinations.julia +++ b/Task/Combinations/Julia/combinations.julia @@ -1,13 +1,3 @@ -julia> for i in @task combinations(1:5,3) +for i in @task combinations(1:5,3) println(i) end -[1, 2, 3] -[1, 2, 4] -[1, 3, 4] -[2, 3, 4] -[1, 2, 5] -[1, 3, 5] -[2, 3, 5] -[1, 4, 5] -[2, 4, 5] -[3, 4, 5] diff --git a/Task/Combinations/Perl-6/combinations.pl6 b/Task/Combinations/Perl-6/combinations.pl6 index f626d331bb..d5b36fc438 100644 --- a/Task/Combinations/Perl-6/combinations.pl6 +++ b/Task/Combinations/Perl-6/combinations.pl6 @@ -3,9 +3,10 @@ proto combine (Int, @) {*} multi combine (0, @) { [] } multi combine ($, []) { () } multi combine ($n, [$head, *@tail]) { - map( { [$head, @^others] }, - combine($n-1, @tail) ), - combine($n, @tail); + gather { + take [$head, @$_] for combine($n-1, @tail); + take [ @$_ ] for combine($n , @tail); + } } -.say for combine(3, [^5]); +say combine(3, [^5]).perl; diff --git a/Task/Combinations/Racket/combinations.rkt b/Task/Combinations/Racket/combinations.rkt new file mode 100644 index 0000000000..ddf4274693 --- /dev/null +++ b/Task/Combinations/Racket/combinations.rkt @@ -0,0 +1,9 @@ +(define sublists + (match-lambda** + [(0 _) '(())] + [(_ '()) '()] + [(m (cons x xs)) (append (map (curry cons x) (sublists (- m 1) xs)) + (sublists m xs))])) + +(define (combinations n m) + (sublists n (range m))) diff --git a/Task/Command-line-arguments/Aime/command-line-arguments.aime b/Task/Command-line-arguments/Aime/command-line-arguments.aime new file mode 100644 index 0000000000..8af9721fb9 --- /dev/null +++ b/Task/Command-line-arguments/Aime/command-line-arguments.aime @@ -0,0 +1,8 @@ +integer i; + +i = 0; +while (i < argc()) { + o_text(argv(i)); + o_byte('\n'); + i += 1; +} diff --git a/Task/Command-line-arguments/Common-Lisp/command-line-arguments.lisp b/Task/Command-line-arguments/Common-Lisp/command-line-arguments.lisp index 778f2c8e15..d806bfde05 100644 --- a/Task/Command-line-arguments/Common-Lisp/command-line-arguments.lisp +++ b/Task/Command-line-arguments/Common-Lisp/command-line-arguments.lisp @@ -2,6 +2,7 @@ (or #+clisp (ext:argv) #+sbcl sb-ext:*posix-argv* + #+abcl ext:*command-line-argument-list* #+clozure (ccl::command-line-arguments) #+gcl si:*command-args* #+ecl (loop for i from 0 below (si:argc) collect (si:argv i)) diff --git a/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt b/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt index ddc2387297..bb4831edf6 100644 --- a/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt +++ b/Task/Command-line-arguments/Racket/command-line-arguments-2.rkt @@ -1,3 +1,2 @@ #lang racket -(for ([arg (current-command-line-arguments)]) - (displayln arg)) +(for ([arg (current-command-line-arguments)]) (displayln arg)) diff --git a/Task/Comments/00DESCRIPTION b/Task/Comments/00DESCRIPTION index 44bd57d71d..5bda1e7a05 100644 --- a/Task/Comments/00DESCRIPTION +++ b/Task/Comments/00DESCRIPTION @@ -1,4 +1,4 @@ -Demonstrate all ways to include text in a language source file which is completely ignored by the compiler or interpreter. +All ways to include text in a language source file that's completely ignored by the compiler or interpreter. '''See Also:'''
-* [http://xkcd.com/156 xkcd] (Humor: hand gesture denoting // for "commenting out" people). +* [http://xkcd.com/156 xkcd] (Humor: hand gesture denoting // for "commenting out" people.) diff --git a/Task/Comments/COBOL/comments-1.cobol b/Task/Comments/COBOL/comments-1.cobol new file mode 100644 index 0000000000..e019391287 --- /dev/null +++ b/Task/Comments/COBOL/comments-1.cobol @@ -0,0 +1 @@ + * an asterisk in 7th column comments the line out diff --git a/Task/Comments/COBOL/comments-2.cobol b/Task/Comments/COBOL/comments-2.cobol new file mode 100644 index 0000000000..ed93c0c92f --- /dev/null +++ b/Task/Comments/COBOL/comments-2.cobol @@ -0,0 +1 @@ +*> This comment syntax was defined in COBOL 2002. diff --git a/Task/Comments/Racket/comments.rkt b/Task/Comments/Racket/comments.rkt index 3336d7ec7c..fd3022d7c6 100644 --- a/Task/Comments/Racket/comments.rkt +++ b/Task/Comments/Racket/comments.rkt @@ -1,2 +1,8 @@ -; this is a coment +; this is a to-end-of-line coment + +#| balanced comment, #| can be nested |# |# + #;(this expression is ignored) + +#; ; the following expression is commented because of the #; in the beginning +(ignored) diff --git a/Task/Compare-sorting-algorithms-performance/C/compare-sorting-algorithms-performance-4.c b/Task/Compare-sorting-algorithms-performance/C/compare-sorting-algorithms-performance-4.c index 140c85909d..6daf8e4e5b 100644 --- a/Task/Compare-sorting-algorithms-performance/C/compare-sorting-algorithms-performance-4.c +++ b/Task/Compare-sorting-algorithms-performance/C/compare-sorting-algorithms-performance-4.c @@ -42,8 +42,8 @@ int action_merge(int size) int doublecompare( const void *a, const void *b ) { - if ( *(double *)a == *(double *)b ) return 0; - if ( *(double *)a < *(double *)b ) return -1; else return 1; + if ( *(const double *)a < *(const double *)b ) return -1; + else return *(const double *)a > *(const double *)b; } int action_qsort(int size) { diff --git a/Task/Concurrent-computing/C++/concurrent-computing-1.cpp b/Task/Concurrent-computing/C++/concurrent-computing-1.cpp new file mode 100644 index 0000000000..483f1b8d90 --- /dev/null +++ b/Task/Concurrent-computing/C++/concurrent-computing-1.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +#include +#include + +int main() +{ + std::random_device rd; + std::mt19937 eng(rd()); // mt19937 generator with a hardware random seed. + std::uniform_int_distribution<> dist(1,1000); + std::vector threads; + + for(auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) { + // between 1 and 1000ms per our distribution + std::chrono::milliseconds duration(dist(eng)); + + threads.push_back(std::thread([str, duration](){ + std::this_thread::sleep_for(duration); + std::cout << str; + })); + } + + for(auto& t: threads) t.join(); + + return 0; +} diff --git a/Task/Concurrent-computing/C++/concurrent-computing-2.cpp b/Task/Concurrent-computing/C++/concurrent-computing-2.cpp new file mode 100644 index 0000000000..dad8ecbf6a --- /dev/null +++ b/Task/Concurrent-computing/C++/concurrent-computing-2.cpp @@ -0,0 +1,20 @@ +#include +#include // MSVC++ + +void a(void) { std::cout << "Eat\n"; } +void b(void) { std::cout << "At\n"; } +void c(void) { std::cout << "Joe's\n"; } + +int main() +{ + // function pointers + Concurrency::parallel_invoke(&a, &b, &c); + + // C++11 lambda functions + Concurrency::parallel_invoke( + []{ std::cout << "Enjoy\n"; }, + []{ std::cout << "Rosetta\n"; }, + []{ std::cout << "Code\n"; } + ); + return 0; +} diff --git a/Task/Concurrent-computing/Racket/concurrent-computing.rkt b/Task/Concurrent-computing/Racket/concurrent-computing.rkt index ea337494d5..7b02d50bef 100644 --- a/Task/Concurrent-computing/Racket/concurrent-computing.rkt +++ b/Task/Concurrent-computing/Racket/concurrent-computing.rkt @@ -1,4 +1,3 @@ #lang racket - (for ([str '("Enjoy" "Rosetta" "Code")]) (thread (λ () (displayln str)))) diff --git a/Task/Conditional-structures/Racket/conditional-structures-1.rkt b/Task/Conditional-structures/Racket/conditional-structures-1.rkt new file mode 100644 index 0000000000..398f001da0 --- /dev/null +++ b/Task/Conditional-structures/Racket/conditional-structures-1.rkt @@ -0,0 +1,3 @@ +(if (< x 10) + "small" + "big") diff --git a/Task/Conditional-structures/Racket/conditional-structures-2.rkt b/Task/Conditional-structures/Racket/conditional-structures-2.rkt new file mode 100644 index 0000000000..8b3c6b160c --- /dev/null +++ b/Task/Conditional-structures/Racket/conditional-structures-2.rkt @@ -0,0 +1,3 @@ +(when (< x 10) + (define y (* x 10)) + (printf "small\n")) diff --git a/Task/Conditional-structures/Racket/conditional-structures-3.rkt b/Task/Conditional-structures/Racket/conditional-structures-3.rkt new file mode 100644 index 0000000000..a15df5ed20 --- /dev/null +++ b/Task/Conditional-structures/Racket/conditional-structures-3.rkt @@ -0,0 +1,7 @@ +(printf "x is ~a\n" + (cond [(< x 1) "tiny"] + [(< x 10) "small"] + [(< x 100) "medium"] + [(< x 10000) "big"] + [(< x 100000000) "huge"] + [else "gigantic"])) diff --git a/Task/Conditional-structures/Racket/conditional-structures-4.rkt b/Task/Conditional-structures/Racket/conditional-structures-4.rkt new file mode 100644 index 0000000000..b5f43ce340 --- /dev/null +++ b/Task/Conditional-structures/Racket/conditional-structures-4.rkt @@ -0,0 +1,8 @@ +(case x + [(1) "one"] + [(2) "two"] + [(3) "three"] + [(4) "four"] + [(6 8) "even"] + [(5 7 9) "odd"] + [else "something else"]) diff --git a/Task/Constrained-random-points-on-a-circle/C++/constrained-random-points-on-a-circle.cpp b/Task/Constrained-random-points-on-a-circle/C++/constrained-random-points-on-a-circle.cpp new file mode 100644 index 0000000000..b9333a79b8 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/C++/constrained-random-points-on-a-circle.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class point +{ +public: + int x, y; + point() { x = y = 0; } + point( int a, int b ) { x = a; y = b; } + void set( int a, int b ) { x = a; y = b; } +}; +//-------------------------------------------------------------------------------------------------- +class rndCircle +{ +public: + void draw() + { + createPoints(); + drawPoints(); + } + +private: + void createPoints() + { + point pt; + for( int x = 0; x < 200; x++ ) + { + int a, b, c; + while( true ) + { + a = rand() % 31 - 15; + b = rand() % 31 - 15; + c = a * a + b * b; + if( c >= 100 && c <= 225 ) break; + } + pt.set( a, b ); + _ptList.push_back( pt ); + } + } + + void drawPoints() + { + HDC dc = GetDC( GetConsoleWindow() ); + for( list::iterator it = _ptList.begin(); it != _ptList.end(); it++ ) + SetPixel( dc, 300 + 10 * ( *it ).x, 300 + 10 * ( *it ).y, RGB( 255, 255, 0 ) ); + } + + list _ptList; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); + srand( GetTickCount() ); + rndCircle c; + c.draw(); + system( "pause" ); + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Constrained-random-points-on-a-circle/D/constrained-random-points-on-a-circle.d b/Task/Constrained-random-points-on-a-circle/D/constrained-random-points-on-a-circle.d index 50040edc9a..c55836c85d 100644 --- a/Task/Constrained-random-points-on-a-circle/D/constrained-random-points-on-a-circle.d +++ b/Task/Constrained-random-points-on-a-circle/D/constrained-random-points-on-a-circle.d @@ -3,12 +3,12 @@ import std.stdio, std.random, std.math, std.complex; void main() { char[31][31] table = ' '; - foreach (i; 0 .. 100) { + foreach (immutable _; 0 .. 100) { int x, y; do { x = uniform(-15, 16); y = uniform(-15, 16); - } while(abs(12.5 - complex(x, y).abs()) > 2.5); + } while(abs(12.5 - complex(x, y).abs) > 2.5); table[x + 15][y + 15] = '*'; } diff --git a/Task/Constrained-random-points-on-a-circle/Racket/constrained-random-points-on-a-circle.rkt b/Task/Constrained-random-points-on-a-circle/Racket/constrained-random-points-on-a-circle.rkt new file mode 100644 index 0000000000..0b18e9bbcb --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Racket/constrained-random-points-on-a-circle.rkt @@ -0,0 +1,11 @@ +#lang racket + +(require plot plot/utils) + +(plot (points (for*/lists (result) + ([_ (in-naturals)] + #:break (= 100 (length result)) + [xy (in-value (v- (vector (random 31) (random 31)) + #(15 15)))] + #:when (<= 10 (vmag xy) 15)) + xy))) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-1.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-1.j new file mode 100644 index 0000000000..773b6c248a --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-1.j @@ -0,0 +1 @@ +cf=. }:@:({:"1@:((, <.)@%@-/@] ::]^:(<_) (, <.)) %&x:&>/) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-2.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-2.j new file mode 100644 index 0000000000..0cc352517f --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-2.j @@ -0,0 +1,12 @@ + cf each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 +┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐ +│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│ +└───┴─┴─────┴─────┴───┴─────────────────────────────────┴─────────┘ + cf each 14142 10000;141421 100000;1414214 1000000;14142136 10000000 +┌──────────────────┬───────────────────────────┬────────────────────────────┬─────────────────────────────────┐ +│1 2 2 2 2 2 1 1 29│1 2 2 2 2 2 2 3 1 1 3 1 7 2│1 2 2 2 2 2 2 2 3 6 1 2 1 12│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│ +└──────────────────┴───────────────────────────┴────────────────────────────┴─────────────────────────────────┘ + cf each 31 10;314 100;3142 1000;31428 10000;314285 100000;3142857 1000000;31428571 10000000;314285714 100000000 +┌────┬─────┬──────────┬───────┬────────┬──────────┬────────────┬───────────┐ +│3 10│3 7 7│3 7 23 1 2│3 7 357│3 7 2857│3 7 142857│3 7 476190 3│3 7 7142857│ +└────┴─────┴──────────┴───────┴────────┴──────────┴────────────┴───────────┘ diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-3.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-3.j new file mode 100644 index 0000000000..fc012d1b45 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-3.j @@ -0,0 +1,2 @@ + 3 7 =&((+ %)/) 3 7 _ +1 diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-4.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-4.j new file mode 100644 index 0000000000..057a8ff7f7 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-4.j @@ -0,0 +1,2 @@ + _2 25 1 2 =&((+ %)/) _1 _1 _24 _1 _2 +1 diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-5.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-5.j new file mode 100644 index 0000000000..38bde9faa9 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-5.j @@ -0,0 +1,33 @@ +coclass'cf' +create =: dyad def 'EMPTY [ N =: x , y' +destroy =: codestroy +r2cf =: monad define + if. 0 (= {:) N do. _ return. end. + RV =. <.@:(%/) N + N =: ({. , |/)@:|. N + RV +) + +cocurrent'base' +CF =: conew'cf' + +Until =: conjunction def 'u^:(-.@:v)^:_' + +(,. }.@:}:@:((,r2cf__CF)Until(_-:{:))@:(8[create__CF/)&.>)1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 +Note 'Output' +┌─────────────────┬─────────────────────────────────┐ +│1 2 │0 2 │ +├─────────────────┼─────────────────────────────────┤ +│3 1 │3 │ +├─────────────────┼─────────────────────────────────┤ +│23 8 │2 1 7 │ +├─────────────────┼─────────────────────────────────┤ +│13 11 │1 5 2 │ +├─────────────────┼─────────────────────────────────┤ +│22 7 │3 7 │ +├─────────────────┼─────────────────────────────────┤ +│14142136 10000000│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│ +├─────────────────┼─────────────────────────────────┤ +│_151 77 │_2 25 1 2 │ +└─────────────────┴─────────────────────────────────┘ +) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-6.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-6.j new file mode 100644 index 0000000000..6069e8e7f2 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-6.j @@ -0,0 +1,13 @@ + f =: 3 : 0 +a =. {.y +b =. {:y +out=. <. a%b +while. b > 1 do. +'a b' =. b; b|a +out=. out , <. a%b +end. +) + f each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 +┌───┬─┬─────┬─────┬───┬───────────────────────────────────┬─────────┐ +│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 _│_2 25 1 2│ +└───┴─┴─────┴─────┴───┴───────────────────────────────────┴─────────┘ diff --git a/Task/Continued-fraction/Racket/continued-fraction-1.rkt b/Task/Continued-fraction/Racket/continued-fraction-1.rkt new file mode 100644 index 0000000000..17cc4f0630 --- /dev/null +++ b/Task/Continued-fraction/Racket/continued-fraction-1.rkt @@ -0,0 +1,16 @@ +#lang racket +(define (calc cf n) + (match/values (cf 0) + [(a0 b0) + (+ a0 + (for/fold ([t 0.0]) ([i (in-range (+ n 1) 0 -1)]) + (match/values (cf i) + [(a b) (/ b (+ a t))])))])) + +(define (cf-sqrt i) (values (if (> i 0) 2 1) 1)) +(define (cf-napier i) (values (if (> i 0) i 2) (if (> i 1) (- i 1) 1))) +(define (cf-pi i) (values (if (> i 0) 6 3) (sqr (- (* 2 i) 1)))) + +(calc cf-sqrt 200) +(calc cf-napier 200) +(calc cf-pi 200) diff --git a/Task/Continued-fraction/Racket/continued-fraction-2.rkt b/Task/Continued-fraction/Racket/continued-fraction-2.rkt new file mode 100644 index 0000000000..dee8753781 --- /dev/null +++ b/Task/Continued-fraction/Racket/continued-fraction-2.rkt @@ -0,0 +1,3 @@ +1.4142135623730951 +2.7182818284590455 +3.1415926839198063 diff --git a/Task/Continued-fraction/Racket/continued-fraction-3.rkt b/Task/Continued-fraction/Racket/continued-fraction-3.rkt new file mode 100644 index 0000000000..3fc62603f3 --- /dev/null +++ b/Task/Continued-fraction/Racket/continued-fraction-3.rkt @@ -0,0 +1,19 @@ +#lang racket +(require math) +(bf-precision 2048) ; in bits + +(define (calc cf n) + (match/values (cf 0) + [(a0 b0) + (bf+ (bf a0) + (for/fold ([t (bf 0)]) ([i (in-range (+ n 1) 0 -1)]) + (match/values (cf i) + [(a b) (bf/ (bf b) (bf+ (bf a) t))])))])) + +(define (cf-sqrt i) (values (if (> i 0) 2 1) 1)) +(define (cf-napier i) (values (if (> i 0) i 2) (if (> i 1) (- i 1) 1))) +(define (cf-pi i) (values (if (> i 0) 6 3) (sqr (- (* 2 i) 1)))) + +(calc cf-sqrt 200) +(calc cf-napier 200) +(calc cf-pi 200) diff --git a/Task/Continued-fraction/Racket/continued-fraction-4.rkt b/Task/Continued-fraction/Racket/continued-fraction-4.rkt new file mode 100644 index 0000000000..7be15dc22b --- /dev/null +++ b/Task/Continued-fraction/Racket/continued-fraction-4.rkt @@ -0,0 +1,3 @@ +(bf #e1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358960036439214262599769155193770031712304888324413327207659690547583107739957489062466508437105234564161085482146113860092820802430986649987683947729823677905101453725898480737256099166805538057375451207262441039818826744940289448489312217214883459060818483750848688583833366310472320771259749181255428309841375829513581694269249380272698662595131575038315461736928338289219865139248048189188905788104310928762952913687232022557677738108337499350045588767581063729) +(bf #e2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408914993488416750924476146066808226480016847741185374234544243710753907774499206955170276183860626133138458300075204493382656029760673711320070932870912744374704723624212700454495421842219077173525899689811474120614457405772696521446961165559468253835854362096088934714907384964847142748311021268578658461064714894910680584249490719358138073078291397044213736982988247857479512745588762993966446075) +(bf #e3.14159268391980626493420192940831754203350026401337226640663040854412059241988978103217808449508253393479795573626200366332733859609651462659489470805432281782785922056335606047700127154963266242144951481397480765182268219697420028007903565511884267297358842935537138583640066772149177226656227031792115896439889412205871076985598822285367358003457939603015797225018209619662200081521930463480571130673429337524564941105654923909951299948539893933654293161126559643573974163405197696633200469475250152247413175932572922175467223988860975105100904322239324381097207835036465269418118204894206705789759765527734394105147) diff --git a/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d b/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d index bdcb1c3ea0..55a86b2039 100644 --- a/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d +++ b/Task/Conways-Game-of-Life/D/conways-game-of-life-1.d @@ -1,4 +1,5 @@ -import std.stdio,std.string,std.algorithm,std.typetuple,std.array; +import std.stdio, std.string, std.algorithm, std.typetuple, + std.array, std.conv; struct GameOfLife { enum Cell : char { dead = ' ', alive = '#' } @@ -10,13 +11,10 @@ struct GameOfLife { } void opIndexAssign(in string[] v, in size_t y, in size_t x) - pure nothrow { - foreach (nr, row; v) - foreach (nc, state; row) { - //grid[y + nr][x + nc] = to!Cell(state); - assert(state == Cell.dead || state == Cell.alive); - grid[y + nr][x + nc] = cast(Cell)state; - } + /*pure nothrow*/ { + foreach (immutable nr, row; v) + foreach (immutable nc, state; row) + grid[y + nr][x + nc] = state.to!Cell; } void iteration() pure nothrow { @@ -25,15 +23,15 @@ struct GameOfLife { foreach (row; newGrid) row[0] = row[$ - 1] = Cell.dead; - foreach (r; 1 .. grid.length - 1) - foreach (c; 1 .. grid[0].length - 1) { - int count = 0; - foreach (i; -1 .. 2) - foreach (j; -1 .. 2) + foreach (immutable r; 1 .. grid.length - 1) + foreach (immutable c; 1 .. grid[0].length - 1) { + uint count = 0; + foreach (immutable i; -1 .. 2) + foreach (immutable j; -1 .. 2) if (i != 0 || j != 0) count += grid[r + i][c + j] == Cell.alive; - auto a = count == 3 || - (count == 2 && grid[r][c] == Cell.alive); + immutable a = count == 3 || + (count == 2 && grid[r][c] == Cell.alive); newGrid[r][c] = a ? Cell.alive : Cell.dead; } @@ -41,12 +39,13 @@ struct GameOfLife { } string toString() const pure nothrow { - string ret = "-".replicate(grid[0].length - 1) ~ "\n"; - foreach (row; grid[1 .. $ - 1]) - ret ~= "|" ~ cast(char[])row[1 .. $-1] ~ "|\n"; + auto ret = "-".replicate(grid[0].length - 1) ~ "\n"; + foreach (const row; grid[1 .. $ - 1]) + ret ~= "|" ~ cast(char[])row[1 .. $ - 1] ~ "|\n"; return ret ~ "-".replicate(grid[0].length - 1); } } + void main() { immutable glider1 = [" #", "# #", " ##"]; immutable glider2 = ["# ", "# #", "## "]; @@ -59,7 +58,7 @@ void main() { uni[5, 50] = [" # #", "# ", "# #", "#### "]; writeln(uni); - foreach (i; 0 .. 20) { + foreach (immutable _; 0 .. 20) { uni.iteration(); writeln(uni); } diff --git a/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d b/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d index fffa9574b2..a47d219824 100644 --- a/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d +++ b/Task/Conways-Game-of-Life/D/conways-game-of-life-2.d @@ -1,10 +1,11 @@ -import std.stdio,std.string,std.algorithm,std.typetuple,std.array; +import std.stdio, std.string, std.algorithm, std.typetuple, + std.array, std.conv; template Iota(int start, int stop) { static if (stop <= start) alias TypeTuple!() Iota; else - alias TypeTuple!(Iota!(start, stop-1), stop-1) Iota; + alias TypeTuple!(Iota!(start, stop - 1), stop - 1) Iota; } struct GameOfLife { @@ -12,36 +13,33 @@ struct GameOfLife { Cell[] grid, newGrid; immutable size_t nCols; - this(int nx, int ny) pure nothrow { + this(in int nx, in int ny) pure nothrow { nCols = nx + 2; grid = new typeof(grid)(nCols * (ny + 2)); newGrid = new typeof(grid)(grid.length); } void opIndexAssign(in string[] v, in size_t y, in size_t x) - pure nothrow { - foreach (nr, row; v) - foreach (nc, state; row) { - //grid[(y + nr) * nCols + x + nc] = to!Cell(state); - assert(state == Cell.dead || state == Cell.alive); - grid[(y + nr) * nCols + x + nc] = cast(Cell)state; - } + /*pure nothrow*/ { + foreach (immutable nr, const row; v) + foreach (immutable nc, immutable state; row) + grid[(y + nr) * nCols + x + nc] = state.to!Cell; } void iteration() { newGrid[0 .. nCols] = Cell.dead; newGrid[$ - nCols .. $] = Cell.dead; - foreach (nr; 1 .. (newGrid.length / nCols) - 1) { + foreach (immutable nr; 1 .. (newGrid.length / nCols) - 1) { newGrid[nr * nCols + 0] = Cell.dead; newGrid[nr * nCols + nCols - 1] = Cell.dead; } - foreach (nr; 1 .. (grid.length / nCols) - 1) { + foreach (immutable nr; 1 .. (grid.length / nCols) - 1) { size_t nr_nCols = nr * nCols; - foreach (nc; 1 .. nCols - 1) { + foreach (immutable nc; 1 .. nCols - 1) { uint count = 0; - /*static*/ foreach (i; Iota!(-1, 2)) - /*static*/ foreach (j; Iota!(-1, 2)) + /*static*/ foreach (immutable i; Iota!(-1, 2)) + /*static*/ foreach (immutable j; Iota!(-1, 2)) static if (i != 0 || j != 0) count += (grid[nr_nCols + i * nCols + nc + j] == Cell.alive); @@ -56,7 +54,7 @@ struct GameOfLife { string toString() const pure nothrow { string ret = "-".replicate(nCols - 1) ~ "\n"; - foreach (nr; 1 .. (grid.length / nCols) - 1) + foreach (immutable nr; 1 .. (grid.length / nCols) - 1) ret ~= "|" ~ cast(char[])grid[nr * nCols + 1 .. nr * nCols + nCols - 1] ~ "|\n"; @@ -76,7 +74,7 @@ void main() { uni[5, 50] = [" # #", "# ", "# #", "#### "]; writeln(uni); - foreach (i; 0 .. 20) { + foreach (immutable _; 0 .. 20) { uni.iteration(); writeln(uni); } diff --git a/Task/Conways-Game-of-Life/Go/conways-game-of-life.go b/Task/Conways-Game-of-Life/Go/conways-game-of-life.go index cb1b7d2bfa..e3a593a817 100644 --- a/Task/Conways-Game-of-Life/Go/conways-game-of-life.go +++ b/Task/Conways-Game-of-Life/Go/conways-game-of-life.go @@ -1,83 +1,98 @@ package main -import "fmt" - -const ( - rows = 3 - cols = 3 - empty = '·' // middle dot - alive = '*' - start = "···***···" - sz = (rows + 2) * (cols + 2) +import ( + "bytes" + "fmt" + "math/rand" + "time" ) -var ( - cs = make([]rune, sz) - ns = make([]int, sz) - nb [8]int -) +type Field struct { + s [][]bool + w, h int +} + +func NewField(w, h int) Field { + s := make([][]bool, h) + for i := range s { + s[i] = make([]bool, w) + } + return Field{s: s, w: w, h: h} +} + +func (f Field) Set(x, y int, b bool) { + f.s[y][x] = b +} + +func (f Field) Next(x, y int) bool { + on := 0 + for i := -1; i <= 1; i++ { + for j := -1; j <= 1; j++ { + if f.State(x+i, y+j) && !(j == 0 && i == 0) { + on++ + } + } + } + return on == 3 || on == 2 && f.State(x, y) +} + +func (f Field) State(x, y int) bool { + for y < 0 { + y += f.h + } + for x < 0 { + x += f.w + } + return f.s[y%f.h][x%f.w] +} + +type Life struct { + w, h int + a, b Field +} + +func NewLife(w, h int) *Life { + a := NewField(w, h) + for i := 0; i < (w * h / 2); i++ { + a.Set(rand.Intn(w), rand.Intn(h), true) + } + return &Life{ + a: a, + b: NewField(w, h), + w: w, h: h, + } +} + +func (l *Life) Step() { + for y := 0; y < l.h; y++ { + for x := 0; x < l.w; x++ { + l.b.Set(x, y, l.a.Next(x, y)) + } + } + l.a, l.b = l.b, l.a +} + +func (l *Life) String() string { + var buf bytes.Buffer + for y := 0; y < l.h; y++ { + for x := 0; x < l.w; x++ { + b := byte(' ') + if l.a.State(x, y) { + b = '*' + } + buf.WriteByte(b) + } + buf.WriteByte('\n') + } + return buf.String() +} func main() { - // initialize empty (really we just need the border) - for i := range cs { - cs[i] = empty - } - // initialize start - si := []rune(start) - for row := 1; row <= rows; row++ { - for col := 1; col <= cols; col++ { - cs[row*(cols+2)+col] = si[(row-1)*cols+col-1] - } - } - // initialize neighbor offsets - for i := 0; i < 3; i++ { - nb[i] = i - cols - 3 - nb[i+3] = i + cols + 1 - } - nb[6] = -1 - nb[7] = 1 - // run - printU() - for g := 0; g < 3; g++ { - genU() - printU() - } -} - -func genU() { - // compute n - for row := 1; row <= rows; row++ { - for col := 1; col <= cols; col++ { - cx := row*(cols+2) + col - n := 0 - for _, d := range nb { - if cs[cx+d] == '*' { - n++ - } - } - ns[cx] = n - } - } - // update c - for row := 1; row <= rows; row++ { - for col := 1; col <= cols; col++ { - cx := row*(cols+2) + col - if cs[cx] == '*' { - switch ns[cx] { - case 0, 1, 4, 5, 6, 7, 8: - cs[cx] = '·' - } - } else if ns[cx] == 3 { - cs[cx] = '*' - } - } - } -} - -func printU() { - fmt.Println("") - for row := 1; row <= rows; row++ { - cx := row*(cols+2) + 1 - fmt.Println(string(cs[cx : cx+cols])) - } + l := NewLife(80, 15) + for i := 0; i < 300; i++ { + l.Step() + fmt.Print("\x0c") + fmt.Println(l) + time.Sleep(time.Second / 30) + } } diff --git a/Task/Conways-Game-of-Life/Java/conways-game-of-life-1.java b/Task/Conways-Game-of-Life/Java/conways-game-of-life-1.java new file mode 100644 index 0000000000..e5c820c75f --- /dev/null +++ b/Task/Conways-Game-of-Life/Java/conways-game-of-life-1.java @@ -0,0 +1,91 @@ +public class GameOfLife{ + public static void main(String[] args){ + String[] dish= { + "_#_", + "_#_", + "_#_",}; + int gens= 3; + for(int i= 0;i < gens;i++){ + System.out.println("Generation " + i + ":"); + print(dish); + dish= life(dish); + } + } + + public static String[] life(String[] dish){ + String[] newGen= new String[dish.length]; + for(int row= 0;row < dish.length;row++){//each row + newGen[row]= ""; + for(int i= 0;i < dish[row].length();i++){//each char in the row + String above= "";//neighbors above + String same= "";//neighbors in the same row + String below= "";//neighbors below + if(i == 0){//all the way on the left + //no one above if on the top row + //otherwise grab the neighbors from above + above= (row == 0) ? null : dish[row - 1].substring(i, + i + 2); + same= dish[row].substring(i + 1, i + 2); + //no one below if on the bottom row + //otherwise grab the neighbors from below + below= (row == dish.length - 1) ? null : dish[row + 1] + .substring(i, i + 2); + }else if(i == dish[row].length() - 1){//right + //no one above if on the top row + //otherwise grab the neighbors from above + above= (row == 0) ? null : dish[row - 1].substring(i - 1, + i + 1); + same= dish[row].substring(i - 1, i); + //no one below if on the bottom row + //otherwise grab the neighbors from below + below= (row == dish.length - 1) ? null : dish[row + 1] + .substring(i - 1, i + 1); + }else{//anywhere else + //no one above if on the top row + //otherwise grab the neighbors from above + above= (row == 0) ? null : dish[row - 1].substring(i - 1, + i + 2); + same= dish[row].substring(i - 1, i) + + dish[row].substring(i + 1, i + 2); + //no one below if on the bottom row + //otherwise grab the neighbors from below + below= (row == dish.length - 1) ? null : dish[row + 1] + .substring(i - 1, i + 2); + } + int neighbors= getNeighbors(above, same, below); + if(neighbors < 2 || neighbors > 3){ + newGen[row]+= "_";//<2 or >3 neighbors -> die + }else if(neighbors == 3){ + newGen[row]+= "#";//3 neighbors -> spawn/live + }else{ + newGen[row]+= dish[row].charAt(i);//2 neighbors -> stay + } + } + } + return newGen; + } + + public static int getNeighbors(String above, String same, String below){ + int ans= 0; + if(above != null){//no one above + for(char x: above.toCharArray()){//each neighbor from above + if(x == '#') ans++;//count it if someone is here + } + } + for(char x: same.toCharArray()){//two on either side + if(x == '#') ans++;//count it if someone is here + } + if(below != null){//no one below + for(char x: below.toCharArray()){//each neighbor below + if(x == '#') ans++;//count it if someone is here + } + } + return ans; + } + + public static void print(String[] dish){ + for(String s: dish){ + System.out.println(s); + } + } +} diff --git a/Task/Conways-Game-of-Life/Java/conways-game-of-life-2.java b/Task/Conways-Game-of-Life/Java/conways-game-of-life-2.java new file mode 100644 index 0000000000..6fc32b3692 --- /dev/null +++ b/Task/Conways-Game-of-Life/Java/conways-game-of-life-2.java @@ -0,0 +1,154 @@ +//package conway; + +import java.util.*; +import java.io.*; + +public class GameOfLife +{ + //Set grid size + int l=20,b=60; + public static void main(String[] args) + { + + GameOfLife now=new GameOfLife(); + now.setGame(); + } + void setGame() + { + char[][] config=new char[l][b]; + startGame(config,l,b); + } + void startGame(char[][] mat,int l, int b) + { + Scanner s=new Scanner(System.in); + String ch=""; + float per=0; + while(!ch.equals("y")) + { + per=setConfig(mat); + //setCustomConfig(mat,"GOLglidergun.txt"); + display2D(mat); + System.out.println((per*100)+"% of grid filled."); + System.out.println("Begin? y/n"); + ch=s.nextLine(); + } + while(!ch.equals("x")) + { + mat=transform(mat,l,b); + display2D(mat); + + System.out.println("Ctrl+Z to stop."); + + try + { + Thread.sleep(100); + } + catch(Exception e) + { + System.out.println("Something went horribly wrong."); + } + + //ch=s.nextLine(); + } + s.close(); + System.out.println("Game Over"); + } + + char[][] transform(char[][] mat,int l, int b) + { + + char[][] newmat=new char[l][b]; + for(int i=0;i3) + return '_'; + return '*'; + } + else + { + if(count==3) + return '*'; + return '_'; + } + } + int around(char[][] mat, int i, int j) + { + int count=0; + for(int x=i-1;x<=i+1;x++) + for(int y=j-1;y<=j+1;y++) + { + if(x==i&&y==j) + continue; + count+=eval(mat,x,y); + } + return count; + } + int eval(char[][] mat, int i, int j) + { + if(i<0||j<0||i==l||j==b) + return 0; + if(mat[i][j]=='*') + return 1; + return 0; + } + + float setCustomConfig(char[][] arr,String infile) + { + try + { + BufferedReader br=new BufferedReader(new FileReader(infile)); + String line; + for(int i=0;i= i (rows grid)) 0) - ((>= j (cols grid)) 0) - ((vector-ref (vector-ref grid i) j)))) + (cond [(< i 0) 0] + [(< j 0) 0] + [(>= i (rows grid)) 0] + [(>= j (cols grid)) 0] + [else (vector-ref (vector-ref grid i) j)])) (define (2d-refs grid indices) (map (lambda (ind) (2d-ref grid (car ind) (cadr ind))) indices)) (define (2d-set! grid i j val) - (begin - (vector-set! (vector-ref grid i) j val) - grid)) + (vector-set! (vector-ref grid i) j val) + grid) ;;; cartesian product of 2 lists (define (cart l1 l2) (if (empty? l1) - '() - (append (let loop ((n (car l1)) (l l2)) - (if (empty? l) '() (cons (list n (car l)) (loop n (cdr l))))) - (cart (cdr l1) l2)))) + '() + (append (let loop ([n (car l1)] [l l2]) + (if (empty? l) '() (cons (list n (car l)) (loop n (cdr l))))) + (cart (cdr l1) l2)))) ;;; Count living cells in the neighbourhood (define (n-count grid i j) @@ -60,16 +58,14 @@ (list->vector (list (list->vector '(0 0 0 1 0 0 0 0 0)) (list->vector '(0 0 1 1 0 0 0 0 0))))) - (define (next-state rules grid i j) - (let ((current (2d-ref grid i j)) - (N (n-count grid i j))) + (let ([current (2d-ref grid i j)] + [N (n-count grid i j)]) (2d-ref rules current N))) (define (next-grid rules grid) - (let ((new-grid (make-empty-grid (rows grid) (cols grid)))) - (let loop ((i 0) - (j 0)) + (let ([new-grid (make-empty-grid (rows grid) (cols grid))]) + (let loop ([i 0] [j 0]) (if (>= i (rows grid)) new-grid (if (>= j (cols grid)) @@ -78,50 +74,51 @@ (loop i (+ j 1)))))))) (define (next-grid! rules grid) - (let ((new-grid (next-grid rules grid))) - (let loop ((i 0)) - (if (< i (rows grid)) - (begin (vector-set! grid i (vector-ref new-grid i)) - (loop (+ i 1))) - grid)))) + (let ([new-grid (next-grid rules grid)]) + (let loop ((i 0)) + (if (< i (rows grid)) + (begin (vector-set! grid i (vector-ref new-grid i)) + (loop (+ i 1))) + grid)))) ;;; ;;; Image / Animation ;;; (define (grid->image grid) - (let ((m (rows grid)) - (n (cols grid)) - (size 5)) - (let loop ((img (rectangle (* m size) (* n size) "solid" "white")) - (i 0) - (j 0)) + (let ([m (rows grid)] [n (cols grid)] [size 5]) + (let loop ([img (rectangle (* m size) (* n size) "solid" "white")] + [i 0] [j 0]) (if (>= i (rows grid)) img (if (>= j (cols grid)) (loop img (+ i 1) 0) (if (= (2d-ref grid i j) 1) - (loop (underlay/xy img (* i (+ 1 size)) (* j (+ 1 size)) (square (- size 2) "solid" "black")) i (+ j 1)) + (loop (underlay/xy img (* i (+ 1 size)) (* j (+ 1 size)) + (square (- size 2) "solid" "black")) + i (+ j 1)) (loop img i (+ j 1)))))))) (define (game-of-life grid refresh_time) - (animate (lambda (n) (if (= (modulo n refresh_time) 0) - (grid->image (next-grid! conway-rules grid)) - (grid->image grid))))) + (animate (lambda (n) + (if (= (modulo n refresh_time) 0) + (grid->image (next-grid! conway-rules grid)) + (grid->image grid))))) ;;; ;;; Examples ;;; -(define (blinker) (make-grid 3 3 '((0 1) (1 1) (2 1)))) +(define (blinker) + (make-grid 3 3 '((0 1) (1 1) (2 1)))) -(define (thunder) (make-grid 70 50 '((30 19) (30 20) (30 21) (29 17) (30 17) (31 17)))) +(define (thunder) + (make-grid 70 50 '((30 19) (30 20) (30 21) (29 17) (30 17) (31 17)))) (define (cross) - (let loop ((i 0) - (l '())) + (let loop ([i 0] [l '()]) (if (>= i 80) (make-grid 80 80 l) (loop (+ i 1) (cons (list i i) (cons (list (- 79 i) i) l)))))) diff --git a/Task/Copy-a-string/Aime/copy-a-string-1.aime b/Task/Copy-a-string/Aime/copy-a-string-1.aime new file mode 100644 index 0000000000..6e7b1c96c2 --- /dev/null +++ b/Task/Copy-a-string/Aime/copy-a-string-1.aime @@ -0,0 +1,3 @@ +text s, t; +t = "Rosetta"; +s = t; diff --git a/Task/Copy-a-string/Aime/copy-a-string-2.aime b/Task/Copy-a-string/Aime/copy-a-string-2.aime new file mode 100644 index 0000000000..b2c69c51f6 --- /dev/null +++ b/Task/Copy-a-string/Aime/copy-a-string-2.aime @@ -0,0 +1,7 @@ +data s, t; +# Copy -t- into -s- +b_copy(s, t); +# Set -s- as a reference of the object -t- is pointing +b_set(s, t); +# or: +s = t; diff --git a/Task/Copy-a-string/Racket/copy-a-string.rkt b/Task/Copy-a-string/Racket/copy-a-string.rkt new file mode 100644 index 0000000000..48796889b8 --- /dev/null +++ b/Task/Copy-a-string/Racket/copy-a-string.rkt @@ -0,0 +1,14 @@ +#lang racket + +(let* ([s1 "Hey"] + [s2 s1] + [s3 (string-copy s1)] + [s4 s3]) + (printf "s1 and s2 refer to ~a strings\n" + (if (eq? s1 s2) "the same" "different")) ; same + (printf "s1 and s3 refer to ~a strings\n" + (if (eq? s1 s3) "the same" "different")) ; different + (printf "s3 and s4 refer to ~a strings\n" + (if (eq? s3 s4) "the same" "different")) ; same + (string-fill! s3 #\!) + (printf "~a~a~a~a\n" s1 s2 s3 s4)) ; outputs "HeyHey!!!!!!" diff --git a/Task/Count-in-factors/Objeck/count-in-factors.objeck b/Task/Count-in-factors/Objeck/count-in-factors.objeck new file mode 100644 index 0000000000..df928d621d --- /dev/null +++ b/Task/Count-in-factors/Objeck/count-in-factors.objeck @@ -0,0 +1,53 @@ +class CountingInFactors { + function : Main(args : String[]) ~ Nil { + for(i := 1; i <= 10; i += 1;){ + count := CountInFactors(i); + ("{$i} = {$count}")->PrintLine(); + }; + + for(i := 9991; i <= 10000; i += 1;){ + count := CountInFactors(i); + ("{$i} = {$count}")->PrintLine(); + }; + } + + function : CountInFactors(n : Int) ~ String { + if(n = 1) { + return "1"; + }; + + sb := ""; + n := CheckFactor(2, n, sb); + if(n = 1) { + return sb; + }; + + n := CheckFactor(3, n, sb); + if(n = 1) { + return sb; + }; + + for(i := 5; i <= n; i += 2;) { + if(i % 3 <> 0) { + n := CheckFactor(i, n, sb); + if(n = 1) { + break; + }; + }; + }; + + return sb; + } + + function : CheckFactor(mult : Int, n : Int, sb : String) ~ Int { + while(n % mult = 0 ) { + if(sb->Size() > 0) { + sb->Append(" x "); + }; + sb->Append(mult); + n /= mult; + }; + + return n; + } +} diff --git a/Task/Count-in-factors/Racket/count-in-factors.rkt b/Task/Count-in-factors/Racket/count-in-factors.rkt index 1f529bdd2e..79e90b19d0 100644 --- a/Task/Count-in-factors/Racket/count-in-factors.rkt +++ b/Task/Count-in-factors/Racket/count-in-factors.rkt @@ -6,10 +6,7 @@ [(list p 1) (~a p)] [(list p n) (~a p "^" n)])) -(define (factors fs) - (add-between (map ~ fs) " * ")) - (for ([x (in-range 2 20)]) (display (~a x " = ")) - (map display (factors (factorize x))) + (for-each display (add-between (map ~ (factorize x)) " * ")) (newline)) diff --git a/Task/Count-in-octal/Aime/count-in-octal.aime b/Task/Count-in-octal/Aime/count-in-octal.aime new file mode 100644 index 0000000000..a984219c0f --- /dev/null +++ b/Task/Count-in-octal/Aime/count-in-octal.aime @@ -0,0 +1,8 @@ +integer o; + +o = 0; +do { + o_xinteger(8, o); + o_byte('\n'); + o += 1; +} while (0 < o); diff --git a/Task/Count-in-octal/Ruby/count-in-octal.rb b/Task/Count-in-octal/Ruby/count-in-octal.rb index e3a4c76b99..8418bf9b82 100644 --- a/Task/Count-in-octal/Ruby/count-in-octal.rb +++ b/Task/Count-in-octal/Ruby/count-in-octal.rb @@ -3,3 +3,13 @@ loop do puts "%o" % n n += 1 end + +# or +for n in 0..Float::INFINITY + puts n.to_s(8) +end + +# or +0.upto(1/0.0) do |n| + printf "%o\n", n +end diff --git a/Task/Count-occurrences-of-a-substring/Racket/count-occurrences-of-a-substring-1.rkt b/Task/Count-occurrences-of-a-substring/Racket/count-occurrences-of-a-substring-1.rkt new file mode 100644 index 0000000000..8ebe90b94e --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Racket/count-occurrences-of-a-substring-1.rkt @@ -0,0 +1,2 @@ +(define count-substring + (compose length regexp-match*)) diff --git a/Task/Count-occurrences-of-a-substring/Racket/count-occurrences-of-a-substring-2.rkt b/Task/Count-occurrences-of-a-substring/Racket/count-occurrences-of-a-substring-2.rkt new file mode 100644 index 0000000000..29741df1b5 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Racket/count-occurrences-of-a-substring-2.rkt @@ -0,0 +1,4 @@ +> (count-substring "th" "the three truths") +3 +> (count-substring "abab" "ababababab") +2 diff --git a/Task/Count-the-coins/Racket/count-the-coins-1.rkt b/Task/Count-the-coins/Racket/count-the-coins-1.rkt new file mode 100644 index 0000000000..7e87074f7a --- /dev/null +++ b/Task/Count-the-coins/Racket/count-the-coins-1.rkt @@ -0,0 +1,10 @@ +#lang racket +(define (ways-to-make-change cents coins) + (cond ((null? coins) 0) + ((negative? cents) 0) + ((zero? cents) 1) + (else + (+ (ways-to-make-change cents (cdr coins)) + (ways-to-make-change (- cents (car coins)) coins))))) + +(ways-to-make-change 100 '(25 10 5 1)) ; -> 242 diff --git a/Task/Count-the-coins/Racket/count-the-coins-2.rkt b/Task/Count-the-coins/Racket/count-the-coins-2.rkt new file mode 100644 index 0000000000..3fa81c250c --- /dev/null +++ b/Task/Count-the-coins/Racket/count-the-coins-2.rkt @@ -0,0 +1,25 @@ +#lang racket + +(define memos (make-hash)) +(define (ways-to-make-change cents coins) + (cond [(or (empty? coins) (negative? cents)) 0] + [(zero? cents) 1] + [else (define (answerer-for-new-arguments) + (+ (ways-to-make-change cents (rest coins)) + (ways-to-make-change (- cents (first coins)) coins))) + (hash-ref! memos (cons cents coins) answerer-for-new-arguments)])) + +(time (ways-to-make-change 100 '(25 10 5 1))) +(time (ways-to-make-change 100000 '(100 50 25 10 5 1))) +(time (ways-to-make-change 1000000 '(200 100 50 20 10 5 2 1))) + +#| Times in milliseconds, and results: + + cpu time: 1 real time: 1 gc time: 0 + 242 + + cpu time: 524 real time: 553 gc time: 163 + 13398445413854501 + + cpu time: 20223 real time: 20673 gc time: 10233 + 99341140660285639188927260001 |# diff --git a/Task/Create-a-file-on-magnetic-tape/Perl-6/create-a-file-on-magnetic-tape.pl6 b/Task/Create-a-file-on-magnetic-tape/Perl-6/create-a-file-on-magnetic-tape.pl6 new file mode 100644 index 0000000000..bc738d58de --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Perl-6/create-a-file-on-magnetic-tape.pl6 @@ -0,0 +1,3 @@ +my $tape = open "/dev/tape", :w or die "Can't open tape: $!"; +$tape.say: "I am a tape file now, or hope to be soon."; +$tape.close; diff --git a/Task/Create-a-file-on-magnetic-tape/Racket/create-a-file-on-magnetic-tape.rkt b/Task/Create-a-file-on-magnetic-tape/Racket/create-a-file-on-magnetic-tape.rkt new file mode 100644 index 0000000000..ad7760d5d5 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Racket/create-a-file-on-magnetic-tape.rkt @@ -0,0 +1,3 @@ +#lang racket +(with-output-to-file "/dev/tape" #:exists 'append + (λ() (displayln "I am a cheap imitation of the Perl code for a boring problem"))) diff --git a/Task/Create-a-file/Aime/create-a-file.aime b/Task/Create-a-file/Aime/create-a-file.aime new file mode 100644 index 0000000000..f3640aab67 --- /dev/null +++ b/Task/Create-a-file/Aime/create-a-file.aime @@ -0,0 +1,37 @@ +# Make a directory using the -mkdir- program +void +mkdir(text p) +{ + sshell ss; + + b_cast(ss_path(ss), "mkdir"); + + l_append(ss_argv(ss), "mkdir"); + l_append(ss_argv(ss), p); + + ss_link(ss); +} + +void +create_file(text p) +{ + file f; + + f_open(f, p, OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 00644); +} + +void +create_pair(text prefix) +{ + create_file(cat(prefix, "output.txt")); + mkdir(cat(prefix, "docs")); +} + +integer +main(void) +{ + create_pair(""); + create_pair("/"); + + return 0; +} diff --git a/Task/Create-a-file/Erlang/create-a-file.erl b/Task/Create-a-file/Erlang/create-a-file.erl new file mode 100644 index 0000000000..2abdde95a9 --- /dev/null +++ b/Task/Create-a-file/Erlang/create-a-file.erl @@ -0,0 +1,8 @@ +-module(new_file). +-export([main/0]). + +main() -> + ok = file:write_file( "output.txt", <<>> ), + ok = file:make_dir( "docs" ), + ok = file:write_file( filename:join(["/", "output.txt"]), <<>> ), + ok = file:make_dir( filename:join(["/", "docs"]) ). diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Racket/create-a-two-dimensional-array-at-runtime.rkt b/Task/Create-a-two-dimensional-array-at-runtime/Racket/create-a-two-dimensional-array-at-runtime.rkt new file mode 100644 index 0000000000..4d0d3f89f9 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Racket/create-a-two-dimensional-array-at-runtime.rkt @@ -0,0 +1,12 @@ +#lang racket + +(printf "Enter XY dimensions: ") +(define xy (cons (read) (read))) +(define array (for/vector ([x (car xy)]) (for/vector ([y (cdr xy)]) 0))) + +(printf "Enter a number for the top-left: ") +(vector-set! (vector-ref array 0) 0 (read)) +(printf "Enter a number for the bottom-right: ") +(vector-set! (vector-ref array (sub1 (car xy))) (sub1 (cdr xy)) (read)) + +array diff --git a/Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ocaml b/Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ocaml index c66221fe53..de2cdac1c6 100644 --- a/Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ocaml +++ b/Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ocaml @@ -3,14 +3,14 @@ let () = let s = Buffer.add_string buf in Random.self_init(); s ""; - s ""; + s ""; s ""; List.iter (fun v -> s ("") ) ["X"; "Y"; "Z"]; s ""; s ""; - s ""; + s ""; for i = 0 to pred 3 do s (""); for j = 0 to pred 3 do diff --git a/Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ocaml b/Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ocaml index b67a95ee37..043ffa5320 100644 --- a/Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ocaml +++ b/Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ocaml @@ -1,8 +1,8 @@ #use "topfind" #require "tyxml" -module X = XHTML.M_01_01 (* XHTML 1.1 *) -module P = XHTML.P_01_01 +module X = Xhtml.M_01_01 (* XHTML 1.1 *) +module P = Xhtml.P_01_01 let make_table () = let td1 = X.td [X.pcdata "1"] in diff --git a/Task/Create-an-object-at-a-given-address/Racket/create-an-object-at-a-given-address.rkt b/Task/Create-an-object-at-a-given-address/Racket/create-an-object-at-a-given-address.rkt new file mode 100644 index 0000000000..83fb28d3f2 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/Racket/create-an-object-at-a-given-address.rkt @@ -0,0 +1,25 @@ +#lang racket +(require ffi/unsafe) + +(define x #"Foo") +;; Get the address of the `x' object +(printf "The address of `x' is: ~s\n" (cast x _scheme _long)) +(define address (cast x _bytes _long)) +(printf "The address of the bytestring it holds: ~s\n" address) +(define y (cast address _long _bytes)) +(printf "Converting this back to a bytestring: ~s\n" y) +(bytes-set! y 0 71) +(printf "Changed the converted bytestring: ~s\n" y) +(printf "The original one is now: ~s\n" x) +;; But (bytes-set! x 0 71) will throw an error since `x' is immutable, +;; showing that we've really modifed the memory directly in a way that +;; the runtime doesn't like. + +;; Also, the above can fail at any moment if a GC happens, since +;; Racket's GC moves objects. So a proper way to do this is not to +;; start from an existing object, but allocate one outside of the GC's +;; reach, using raw malloc(): +(define buf (malloc 4 'raw)) +(make-sized-byte-string buf 4) +;; or start with a given address of something like a memory-mapped IO +;; object diff --git a/Task/Cut-a-rectangle/Common-Lisp/cut-a-rectangle-1.lisp b/Task/Cut-a-rectangle/Common-Lisp/cut-a-rectangle-1.lisp index 12dab66f06..3f083fb2c2 100644 --- a/Task/Cut-a-rectangle/Common-Lisp/cut-a-rectangle-1.lisp +++ b/Task/Cut-a-rectangle/Common-Lisp/cut-a-rectangle-1.lisp @@ -1,7 +1,7 @@ (defun cut-it (w h &optional (recur t)) (if (oddp (* w h)) (return-from cut-it 0)) (if (oddp h) (rotatef w h)) - (if (= w 1) (return-from cut-it h)) + (if (= w 1) (return-from cut-it 1)) (let ((cnt 0) (m (make-array (list (1+ h) (1+ w)) diff --git a/Task/Cut-a-rectangle/Racket/cut-a-rectangle.rkt b/Task/Cut-a-rectangle/Racket/cut-a-rectangle.rkt new file mode 100644 index 0000000000..6a450034e2 --- /dev/null +++ b/Task/Cut-a-rectangle/Racket/cut-a-rectangle.rkt @@ -0,0 +1,48 @@ +#lang racket + +(define (cuts W H [count 0]) ; count = #f => visualize instead + (define W1 (add1 W)) (define H1 (add1 H)) + (define B (make-vector (* W1 H1) #f)) + (define (fD d) (cadr (assq d '([U D] [D U] [L R] [R L] [#f #f] [#t #t])))) + (define (fP p) (- (* W1 H1) p 1)) + (define (Bset! p d) (vector-set! B p d) (vector-set! B (fP p) (fD d))) + (define center (/ (fP 0) 2)) + (when (integer? center) (Bset! center #t)) + (define (run c* d) + (define p (- center c*)) + (Bset! p d) + (let loop ([p p]) + (define-values [q r] (quotient/remainder p W1)) + (if (and (< 0 r W) (< 0 q H)) + (for ([d '(U D L R)]) + (define n (+ p (case d [(U) (- W1)] [(D) W1] [(L) -1] [(R) 1]))) + (unless (vector-ref B n) (Bset! n (fD d)) (loop n) (Bset! n #f))) + (if count (set! count (add1 count)) (visualize B W H)))) + (Bset! p #f)) + (when (even? W) (run (if (odd? H) (/ W1 2) W1) 'D)) + (when (even? H) (run (if (odd? W) 1/2 1) 'R)) + (or count (void))) + +(define (visualize B W H) + (define W2 (+ 2 (* W 2))) (define H2 (+ 1 (* H 2))) + (define str (make-string (* H2 W2) #\space)) + (define (Sset! i c) (string-set! str i c)) + (for ([i (in-range (- W2 1) (* W2 H2) W2)]) (Sset! i #\newline)) + (for ([i (in-range 0 (- W2 1))]) (Sset! i #\#) (Sset! (+ i (* W2 H 2)) #\#)) + (for ([i (in-range 0 (* W2 H2) W2)]) (Sset! i #\#) (Sset! (+ i W2 -2) #\#)) + (for* ([i (add1 W)] [j (add1 H)]) + (define p (* 2 (+ i (* j W2)))) + (define b (vector-ref B (+ i (* j (+ W 1))))) + (cond [b (Sset! p #\#) + (define d (case b [(U) (- W2)] [(D) W2] [(R) 1] [(L) -1])) + (when (integer? d) (Sset! (+ p d) #\#))] + [(equal? #\space (string-ref str p)) (Sset! p #\.)])) + (display str) (newline)) + +(printf "Counts:\n") +(for* ([W (in-range 1 10)] [H (in-range 1 (add1 W))] + #:unless (and (odd? W) (odd? H))) + (printf "~s x ~s: ~s\n" W H (cuts W H))) + +(newline) +(cuts 4 3 #f) diff --git a/Task/DNS-query/Cache-ObjectScript/dns-query.cos b/Task/DNS-query/Cache-ObjectScript/dns-query.cos index 6afc744e83..3b170d51e7 100644 --- a/Task/DNS-query/Cache-ObjectScript/dns-query.cos +++ b/Task/DNS-query/Cache-ObjectScript/dns-query.cos @@ -6,14 +6,14 @@ ClassMethod QueryDNS(pHost As %String, Output ip As %List) As %Status // some initialisation Set ip=$ListBuild() - // check input and host operating system - If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { - Quit $$$ERROR($$$GeneralError, "Invalid host name.") - } + // check host operating system and input parameters Set os=$Case($ZVersion(1), 1: "vms", 2: "win", 3: "*nx", : "") If (os="vms")||(os="") Quit $$$ERROR($$$GeneralError, "Not implemented.") If os="win" Set cmd="nslookup "_pHost If os="*nx" Set cmd="host "_pHost + If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { + Quit $$$ERROR($$$GeneralError, "Invalid host name.") + } // enable end-of-file flagging Do $System.Process.SetZEOF(1) diff --git a/Task/Date-format/COBOL/date-format.cobol b/Task/Date-format/COBOL/date-format.cobol new file mode 100644 index 0000000000..76c554f613 --- /dev/null +++ b/Task/Date-format/COBOL/date-format.cobol @@ -0,0 +1,64 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Date-Format. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 Days-Area. + 03 Days-Data. + 05 FILLER PIC X(9) VALUE "Monday". + 05 FILLER PIC X(9) VALUE "Tuesday". + 05 FILLER PIC X(9) VALUE "Wednesday". + 05 FILLER PIC X(9) VALUE "Thursday". + 05 FILLER PIC X(9) VALUE "Friday". + 05 FILLER PIC X(9) VALUE "Saturday". + 05 FILLER PIC X(9) VALUE "Sunday". + + 03 Days-Values REDEFINES Days-Data. + 05 Days-Table PIC X(9) OCCURS 7 TIMES. + + 01 Months-Area. + 03 Months-Data. + 05 FILLER PIC X(9) VALUE "January". + 05 FILLER PIC X(9) VALUE "February". + 05 FILLER PIC X(9) VALUE "March". + 05 FILLER PIC X(9) VALUE "April". + 05 FILLER PIC X(9) VALUE "May". + 05 FILLER PIC X(9) VALUE "June". + 05 FILLER PIC X(9) VALUE "July". + 05 FILLER PIC X(9) VALUE "August". + 05 FILLER PIC X(9) VALUE "September". + 05 FILLER PIC X(9) VALUE "October". + 05 FILLER PIC X(9) VALUE "November". + 05 FILLER PIC X(9) VALUE "December". + + 03 Months-Values REDEFINES Months-Data. + 05 Months-Table PIC X(9) OCCURS 12 TIMES. + + 01 Current-Date-Str. + 03 Current-Year PIC X(4). + 03 Current-Month PIC X(2). + 03 Current-Day PIC X(2). + + 01 Current-Day-Of-Week PIC 9. + + PROCEDURE DIVISION. + MOVE FUNCTION CURRENT-DATE (1:8) TO Current-Date-Str + + DISPLAY Current-Year "-" Current-Month "-" Current-Day + + ACCEPT Current-Day-Of-Week FROM DAY-OF-WEEK + DISPLAY + FUNCTION TRIM( + Days-Table (FUNCTION NUMVAL(Current-Day-Of-Week))) + ", " + FUNCTION TRIM( + Months-Table (FUNCTION NUMVAL(Current-Month))) + " " + Current-Day + ", " + Current-Year + END-DISPLAY + + GOBACK + . diff --git a/Task/Date-manipulation/PL-I/date-manipulation.pli b/Task/Date-manipulation/PL-I/date-manipulation.pli index c685dbb749..1670ea204b 100644 --- a/Task/Date-manipulation/PL-I/date-manipulation.pli +++ b/Task/Date-manipulation/PL-I/date-manipulation.pli @@ -5,4 +5,4 @@ seconds = SECS(DATETIME()); seconds = seconds + 12*60*60; -put list (SECSTODATE(secs)); +put list (SECSTODATE(seconds)); diff --git a/Task/Date-manipulation/Perl-6/date-manipulation.pl6 b/Task/Date-manipulation/Perl-6/date-manipulation.pl6 new file mode 100644 index 0000000000..a5b1ec18f3 --- /dev/null +++ b/Task/Date-manipulation/Perl-6/date-manipulation.pl6 @@ -0,0 +1,52 @@ +my @month = ; +my %month = (@month Z=> ^12).flat, (@month».substr(0,3) Z=> ^12).flat, 'Sept' => 8; + +grammar US-DateTime { + rule TOP { ','? ','? \" to clear at (row,col), or~n" clear-string) + (format (string-append "--- \"~a \" to flag a possible mine " + "(or clear a flag) at (row,col).~n") + assume-string))) + (let ([b (init-board 4 6)]) + (displayln (format "There are ~a mines.~n" (mine-count b))) + (let run () + (show-board b) + (display "enter move: ") + ;parse either failed or gave the procedure to execute + (let ([proc? (parse-and-create-move! b (read-line))]) + ;was the parse successful? + (if proc? + ;then run it + (if (proc?) + ;didn't lose, so either we won or we're not done + (if (win? b) (displayln "CLEAR!") (run)) + (displayln "BOOM!")) + ;parse failed + (run)))))) diff --git a/Task/Modular-exponentiation/Racket/modular-exponentiation-1.rkt b/Task/Modular-exponentiation/Racket/modular-exponentiation-1.rkt new file mode 100644 index 0000000000..ea35a93e0e --- /dev/null +++ b/Task/Modular-exponentiation/Racket/modular-exponentiation-1.rkt @@ -0,0 +1,6 @@ +#lang racket +(require math) +(define a 2988348162058574136915891421498819466320163312926952423791023078876139) +(define b 2351399303373464486466122544523690094744975233415544072992656881240319) +(define m (expt 10 40)) +(modular-expt a b m) diff --git a/Task/Modular-exponentiation/Racket/modular-exponentiation-2.rkt b/Task/Modular-exponentiation/Racket/modular-exponentiation-2.rkt new file mode 100644 index 0000000000..5780a0ee51 --- /dev/null +++ b/Task/Modular-exponentiation/Racket/modular-exponentiation-2.rkt @@ -0,0 +1 @@ +1527229998585248450016808958343740453059 diff --git a/Task/Modular-exponentiation/Seed7/modular-exponentiation-1.seed7 b/Task/Modular-exponentiation/Seed7/modular-exponentiation-1.seed7 new file mode 100644 index 0000000000..d7fdaa8255 --- /dev/null +++ b/Task/Modular-exponentiation/Seed7/modular-exponentiation-1.seed7 @@ -0,0 +1,9 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const proc: main is func + begin + writeln(modPow(2988348162058574136915891421498819466320163312926952423791023078876139_, + 2351399303373464486466122544523690094744975233415544072992656881240319_, + 10_ ** 40)); + end func; diff --git a/Task/Modular-exponentiation/Seed7/modular-exponentiation-2.seed7 b/Task/Modular-exponentiation/Seed7/modular-exponentiation-2.seed7 new file mode 100644 index 0000000000..68ece7d370 --- /dev/null +++ b/Task/Modular-exponentiation/Seed7/modular-exponentiation-2.seed7 @@ -0,0 +1,17 @@ +const func bigInteger: modPow (in var bigInteger: base, + in var bigInteger: exponent, in bigInteger: modulus) is func + result + var bigInteger: power is 1_; + begin + if exponent < 0_ or modulus < 0_ then + raise RANGE_ERROR; + else + while exponent > 0_ do + if odd(exponent) then + power := (power * base) mod modulus; + end if; + exponent >>:= 1; + base := base ** 2 mod modulus; + end while; + end if; + end func; diff --git a/Task/Modular-inverse/C++/modular-inverse.cpp b/Task/Modular-inverse/C++/modular-inverse.cpp new file mode 100644 index 0000000000..ecfbfa1748 --- /dev/null +++ b/Task/Modular-inverse/C++/modular-inverse.cpp @@ -0,0 +1,21 @@ +#include + using namespace std; + +int mul_inv(int a, int b) +{ + int b0 = b, t, q; + int x0 = 0, x1 = 1; + if (b == 1) return 1; + while (a > 1) { + q = a / b; + t = b, b = a % b, a = t; + t = x0, x0 = x1 - q * x0, x1 = t; + } + if (x1 < 0) x1 += b0; + return x1; +} + +int main(void) { + cout< 0_ then + a := a mod b; + end if; + b_bak := b; + while b <> 0_ do + temp := b; + quotient := a div b; + b := a rem b; + a := temp; + + temp := x; + x := lastx - quotient * x; + lastx := temp; + + temp := y; + y := lasty - quotient * y; + lasty := temp; + end while; + if a = 1_ then + modularInverse := lastx; + if modularInverse < 0_ then + modularInverse +:= b_bak; + end if; + else + raise RANGE_ERROR; + end if; + end func; diff --git a/Task/Monte-Carlo-methods/Mathematica/monte-carlo-methods-4.math b/Task/Monte-Carlo-methods/Mathematica/monte-carlo-methods-4.math new file mode 100644 index 0000000000..83e1684b9a --- /dev/null +++ b/Task/Monte-Carlo-methods/Mathematica/monte-carlo-methods-4.math @@ -0,0 +1,2 @@ +monteCarloPi = 4. Mean[UnitStep[1 - Total[RandomReal[1, {2, #}]^2]]] &; +monteCarloPi /@ (10^Range@6) diff --git a/Task/Monty-Hall-problem/Racket/monty-hall-problem.rkt b/Task/Monty-Hall-problem/Racket/monty-hall-problem.rkt new file mode 100644 index 0000000000..a4e5179e9d --- /dev/null +++ b/Task/Monty-Hall-problem/Racket/monty-hall-problem.rkt @@ -0,0 +1,36 @@ +#lang racket + +(define (get-last-door a b) ; assumes a != b + (vector-ref '#(- 2 1 + 2 - 0 + 1 0 -) + (+ a (* 3 b)))) + +(define (run-game strategy) + (define car-door (random 3)) + (define first-choice (random 3)) + (define revealed-goat + (if (= car-door first-choice) + (let ([r (random 2)]) (if (<= car-door r) (add1 r) r)) ; random + (get-last-door car-door first-choice))) ; reveal goat + (define final-choice (strategy first-choice revealed-goat)) + (define win? (eq? final-choice car-door)) + ;; (printf "car: ~s\nfirst: ~s\nreveal: ~s\nfinal: ~s\n => ~s\n\n" + ;; car-door first-choice revealed-goat final-choice + ;; (if win? 'win 'lose)) + win?) + +(define (keep-choice first-choice revealed-goat) + first-choice) + +(define (change-choice first-choice revealed-goat) + (get-last-door first-choice revealed-goat)) + +(define (test-strategy strategy) + (define N 10000000) + (define wins (for/sum ([i (in-range N)]) (if (run-game strategy) 1 0))) + (printf "~a: ~a%\n" + (object-name strategy) + (exact->inexact (/ wins N 1/100)))) + +(for-each test-strategy (list keep-choice change-choice)) diff --git a/Task/Morse-code/Racket/morse-code.rkt b/Task/Morse-code/Racket/morse-code.rkt new file mode 100644 index 0000000000..3118ab47a0 --- /dev/null +++ b/Task/Morse-code/Racket/morse-code.rkt @@ -0,0 +1,40 @@ +#lang racket +(require ffi/unsafe ffi/unsafe/define) +(define-ffi-definer defmm (ffi-lib "Winmm")) +(defmm midiOutOpen (_fun [h : (_ptr o _int32)] [_int = -1] [_pointer = #f] + [_pointer = #f] [_int32 = 0] -> _void -> h)) +(defmm midiOutShortMsg (_fun _int32 _int32 -> _void)) +(define M (midiOutOpen)) +(define (midi x y z) (midiOutShortMsg M (+ x (* 256 y) (* 65536 z)))) + +(define raw-codes + '("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.----" + "|2..---|3...--|4....-|5.....|6-....|7--...|8---..|9----.|0-----")) + +(define codes + (for/list ([x (regexp-split #rx"\\|" (string-append* raw-codes))]) + (cons (string-ref x 0) (substring x 1)))) + +(define (morse str [unit 0.1]) + (define (sound len) + (midi #x90 72 127) (sleep (* len unit)) + (midi #x90 72 0) (sleep unit)) + (define (play str) + (midi #xC0 #x35 0) ; use a cute voice + (for ([c str]) + (case c [(#\.) (sound 1)] [(#\-) (sound 3)] [(#\ ) (sleep (* 3 unit))]))) + (let* ([str (string-foldcase str)] + [str (regexp-replace* #rx"[,:;]+" str " ")] + [str (regexp-replace* #rx"[.!?]+" str ".")] + [str (string-normalize-spaces str)]) + (for ([s (string-split str)]) + (define m + (string-join + (for/list ([c s]) + (cond [(assq c codes) => cdr] + [else (case c [(#\space) " "] [(#\.) " "] [else ""])])))) + (printf "~a: ~a\n" s m) + (play (string-append m " "))))) + +(morse "Say something here") diff --git a/Task/Mouse-position/Racket/mouse-position.rkt b/Task/Mouse-position/Racket/mouse-position.rkt index 124b744faa..ad6646654e 100644 --- a/Task/Mouse-position/Racket/mouse-position.rkt +++ b/Task/Mouse-position/Racket/mouse-position.rkt @@ -1,4 +1,4 @@ #lang racket/gui -(define-values (point _) (get-current-mouse-state)) +(define-values [point _] (get-current-mouse-state)) (send point get-x) (send point get-y) diff --git a/Task/Multifactorial/Perl/multifactorial.pl b/Task/Multifactorial/Perl/multifactorial.pl new file mode 100644 index 0000000000..d44b3e3ca3 --- /dev/null +++ b/Task/Multifactorial/Perl/multifactorial.pl @@ -0,0 +1,14 @@ +{ # <-- scoping the cache and bigint clause + my @cache; + use bigint; + sub mfact { + my ($s, $n) = @_; + return 1 if $n <= 0; + $cache[$s][$n] //= $n * mfact($s, $n - $s); + } +} + +for my $s (1 .. 10) { + print "step=$s: "; + print join(" ", map(mfact($s, $_), 1 .. 10)), "\n"; +} diff --git a/Task/Multiple-distinct-objects/Aime/multiple-distinct-objects.aime b/Task/Multiple-distinct-objects/Aime/multiple-distinct-objects.aime new file mode 100644 index 0000000000..dcfc82748c --- /dev/null +++ b/Task/Multiple-distinct-objects/Aime/multiple-distinct-objects.aime @@ -0,0 +1,66 @@ +void +show_sublist(list l) +{ + integer i; + + i = 0; + while (i < l_length(l)) { + if (i) { + o_space(1); + } + o_integer(l_q_integer(l, i)); + i += 1; + } +} + +void +show_list(list l) +{ + integer i; + + i = 0; + while (i < l_length(l)) { + o_text(" ["); + show_sublist(l_q_list(l, i)); + o_text("]"); + i += 1; + } + + o_byte('\n'); +} + +list +multiple_distinct(integer n, object o) +{ + list l; + + while (n) { + l_append(l, o); + n -= 1; + } + + return l; +} + +integer +main(void) +{ + list l, z; + + # create a list of integers - `3' will serve as initializer + l = multiple_distinct(8, 3); + + l_clear(l); + + # create a list of distinct lists - `z' will serve as initializer + l_append(z, 4); + l = multiple_distinct(8, z); + + # modify one of the sublists + l_r_integer(l_q_list(l, 3), 0, 7); + + # display the list of lists + show_list(l); + + return 0; +} diff --git a/Task/Multiple-distinct-objects/Seed7/multiple-distinct-objects.seed7 b/Task/Multiple-distinct-objects/Seed7/multiple-distinct-objects.seed7 new file mode 100644 index 0000000000..9ffe3bfc50 --- /dev/null +++ b/Task/Multiple-distinct-objects/Seed7/multiple-distinct-objects.seed7 @@ -0,0 +1,20 @@ +$ include "seed7_05.s7i"; + +const func array file: openFiles (in array string: fileNames) is func + result + var array file: fileArray is 0 times STD_NULL; # Define array variable + local + var integer: i is 0; + begin + fileArray := length(fileNames) times STD_NULL; # Array size computed at run-time + for key i range fileArray do + fileArray[i] := open(fileNames[i], "r"); # Assign multiple distinct objects + end for; + end func; + +const proc: main is func + local + var array file: files is 0 times STD_NULL; + begin + files := openFiles([] ("abc.txt", "def.txt", "ghi.txt", "jkl.txt")); + end func; diff --git a/Task/Multiple-regression/Racket/multiple-regression-1.rkt b/Task/Multiple-regression/Racket/multiple-regression-1.rkt new file mode 100644 index 0000000000..099e1d0e1f --- /dev/null +++ b/Task/Multiple-regression/Racket/multiple-regression-1.rkt @@ -0,0 +1,6 @@ +#lang racket +(require math) +(define T matrix-transpose) + +(define (fit X y) + (matrix-solve (matrix* (T X) X) (matrix* (T X) y))) diff --git a/Task/Multiple-regression/Racket/multiple-regression-2.rkt b/Task/Multiple-regression/Racket/multiple-regression-2.rkt new file mode 100644 index 0000000000..abe4ffa447 --- /dev/null +++ b/Task/Multiple-regression/Racket/multiple-regression-2.rkt @@ -0,0 +1,10 @@ +(fit (matrix [[1 2] + [2 5] + [3 7] + [4 9]]) + (matrix [[1] + [2] + [3] + [9]])) +; Output: +(array #[#[9 1/3] #[-3 1/3]]) diff --git a/Task/Multiplication-tables/Racket/multiplication-tables.rkt b/Task/Multiplication-tables/Racket/multiplication-tables.rkt new file mode 100644 index 0000000000..e5451dcb54 --- /dev/null +++ b/Task/Multiplication-tables/Racket/multiplication-tables.rkt @@ -0,0 +1,10 @@ +#lang racket + +(define (show-line xs) + (for ([x xs]) (display (~a x #:width 4 #:align 'right))) + (newline)) + +(show-line (cons "" (range 1 13))) +(for ([y (in-range 1 13)]) + (show-line (cons y (for/list ([x (in-range 1 13)]) + (if (<= y x) (* x y) ""))))) diff --git a/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 b/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 new file mode 100644 index 0000000000..b1d0536065 --- /dev/null +++ b/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 @@ -0,0 +1,51 @@ +my @primes := 2, grep *.is-prime, (3,5,7...*); + +sub factor($a is copy) { + gather { + for @primes -> $p { + my $j = 0; + while $a %% $p { + $a div= $p; + $j++; + } + take $p => $j if $j > 0; + last if $a < $p * $p; + } + + take $a => 1 if $a > 1; + } +} + +sub mo-prime($a, $p, $e) { + my $m = $p ** $e; + my $t = ($p - 1) * ($p ** ($e - 1)); # = Phi($p**$e) where $p prime + my @qs = 1; + for factor($t) -> $f { + @qs = @qs.map(-> $q { (0..$f.value).map(-> $j { $q * $f.key ** $j }) }); + } + @qs.sort(); + + @qs.first(-> $q { expmod( $a, $q, $m ) == 1}); +} + +sub mo($a, $m) { + $a gcd $m == 1 || die "$a and $m are not relatively prime"; + [lcm] 1, factor($m).map(-> $r { mo-prime($a, $r.key, $r.value) }); +} + +sub MAIN("test") { + use Test; + + for (10, 21, 25, 150, 1231, 123141, 34131) -> $n { + # say factor($n).perl; + # say factor($n).map(-> $pair { $pair.key ** $pair.value }).perl; + is ([*] factor($n).map(-> $pair { $pair.key ** $pair.value })), $n, "$n factors correctly"; + } + + is mo(37, 1000), 100, 'mo(37,1000) == 100'; + my $b = 10**20-1; + is mo(2, $b), 3748806900, 'mo(2,10**20-1) == 3748806900'; + is mo(17, $b), 1499522760, 'mo(17,10**20-1) == 1499522760'; + $b = 100001; + is mo(54, $b), 9090, 'mo(54,100001) == 9090'; +} diff --git a/Task/Multiplicative-order/Racket/multiplicative-order-1.rkt b/Task/Multiplicative-order/Racket/multiplicative-order-1.rkt new file mode 100644 index 0000000000..ed09750aaf --- /dev/null +++ b/Task/Multiplicative-order/Racket/multiplicative-order-1.rkt @@ -0,0 +1,25 @@ +#lang racket +(require math) + +(define (order a n) + (unless (coprime? a n) (error 'order "arguments must be coprime")) + (for/fold ([o 1]) ([r (factorize n)]) + (lcm o (order1 a r)))) + +(define (order1 a p&e) + (match-define (list p e) p&e) + (define m (expt p e)) + (define t (* (- p 1) (expt p (- e 1)))) + (define qs + (for/fold ([qs '(1)]) ([f (factorize t)]) + (match f [(list f0 f1) + (for*/list ([q qs] [j (in-range (+ 1 f1))]) + (* q (expt f0 j)))]))) + (for/or ([q (sort qs <)] #:when (= (modular-expt a q m) 1)) q)) + + +(order 37 1000) +(order (+ (expt 10 100) 1) 7919) +(order (+ (expt 10 1000) 1) 15485863) +(order (- (expt 10 10000) 1) 22801763489) +(order 13 (+ 1 (expt 10 80))) diff --git a/Task/Multiplicative-order/Racket/multiplicative-order-2.rkt b/Task/Multiplicative-order/Racket/multiplicative-order-2.rkt new file mode 100644 index 0000000000..c17a2ed609 --- /dev/null +++ b/Task/Multiplicative-order/Racket/multiplicative-order-2.rkt @@ -0,0 +1,5 @@ +100 +3959 +15485862 +22801763488 +109609547199756140150989321269669269476675495992554276140800 diff --git a/Task/Multisplit/Racket/multisplit.rkt b/Task/Multisplit/Racket/multisplit.rkt new file mode 100644 index 0000000000..ea9c6da75c --- /dev/null +++ b/Task/Multisplit/Racket/multisplit.rkt @@ -0,0 +1,3 @@ +#lang racket +(regexp-match* #rx"==|!=|=" "a!===b=!=c" #:gap-select? #t #:match-select values) +;; => '("a" ("!=") "" ("==") "b" ("=") "" ("!=") "c") diff --git a/Task/Mutex/Racket/mutex-1.rkt b/Task/Mutex/Racket/mutex-1.rkt new file mode 100644 index 0000000000..7a515140b9 --- /dev/null +++ b/Task/Mutex/Racket/mutex-1.rkt @@ -0,0 +1,6 @@ +(define foo + (let ([sema (make-semaphore 1)]) + (lambda (x) + (dynamic-wind (λ() (semaphore-wait sema)) + (λ() (... do something ...)) + (λ() (semaphore-post sema)))))) diff --git a/Task/Mutex/Racket/mutex-2.rkt b/Task/Mutex/Racket/mutex-2.rkt new file mode 100644 index 0000000000..aab6e0a6aa --- /dev/null +++ b/Task/Mutex/Racket/mutex-2.rkt @@ -0,0 +1,10 @@ +(define-syntax-rule (define/atomic (name arg ...) E ...) + (define name + (let ([sema (make-semaphore 1)]) + (lambda (arg ...) + (dynamic-wind (λ() (semaphore-wait sema)) + (λ() E ...) + (λ() (semaphore-post sema))))))) +;; this does the same as the above now: +(define/atomic (foo x) + (... do something ...)) diff --git a/Task/Mutual-recursion/Racket/mutual-recursion.rkt b/Task/Mutual-recursion/Racket/mutual-recursion.rkt new file mode 100644 index 0000000000..ac9888a88d --- /dev/null +++ b/Task/Mutual-recursion/Racket/mutual-recursion.rkt @@ -0,0 +1,10 @@ +#lang racket +(define (F n) + (if (>= 0 n) + 1 + (- n (M (F (sub1 n)))))) + +(define (M n) + (if (>= 0 n) + 0 + (- n (F (M (sub1 n)))))) diff --git a/Task/N-queens-problem/C++/n-queens-problem-1.cpp b/Task/N-queens-problem/C++/n-queens-problem-1.cpp new file mode 100644 index 0000000000..83a56c113d --- /dev/null +++ b/Task/N-queens-problem/C++/n-queens-problem-1.cpp @@ -0,0 +1,100 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class point +{ +public: + int x, y; + point(){ x = y = 0; } + void set( int a, int b ){ x = a; y = b; } +}; +//-------------------------------------------------------------------------------------------------- +class nQueens +{ +public: + void solve( int c ) + { + _count = c; int len = ( c + 1 ) * ( c + 1 ); _queens = new bool[len]; memset( _queens, 0, len ); + _cl = new bool[c]; memset( _cl, 0, c ); _ln = new bool[c]; memset( _ln, 0, c ); + point pt; pt.set( rand() % c, rand() % c ); putQueens( pt, c ); displayBoard(); + delete [] _queens; delete [] _ln; delete [] _cl; + } + +private: + void displayBoard() + { + system( "cls" ); string t = "+---+", q = "| Q |", s = "| |"; + COORD c = { 0, 0 }; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); + for( int y = 0, cy = 0; y < _count; y++ ) + { + int yy = y * _count; + for( int x = 0; x < _count; x++ ) + { + SetConsoleCursorPosition( h, c ); cout << t; + c.Y++; SetConsoleCursorPosition( h, c ); + if( _queens[x + yy] ) cout << q; else cout << s; + c.Y++; SetConsoleCursorPosition( h, c ); + cout << t; c.Y = cy; c.X += 4; + } + cy += 2; c.X = 0; c.Y = cy; + } + } + + bool checkD( int x, int y, int a, int b ) + { + if( x < 0 || y < 0 || x >= _count || y >= _count ) return true; + if( _queens[x + y * _count] ) return false; + if( checkD( x + a, y + b, a, b ) ) return true; + return false; + } + + bool check( int x, int y ) + { + if( _ln[y] || _cl[x] ) return false; + if( !checkD( x, y, -1, -1 ) ) return false; + if( !checkD( x, y, 1, -1 ) ) return false; + if( !checkD( x, y, -1, 1 ) ) return false; + if( !checkD( x, y, 1, 1 ) ) return false; + return true; + } + + bool putQueens( point pt, int cnt ) + { + int it = _count; + while( it ) + { + if( !cnt ) return true; + if( check( pt.x, pt.y ) ) + { + _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = true; + point tmp = pt; if( ++tmp.x >= _count ) tmp.x = 0; if( ++tmp.y >= _count ) tmp.y = 0; + if( putQueens( tmp, cnt - 1 ) ) return true; + _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = false; + } + if( ++pt.x >= _count ) pt.x = 0; + it--; + } + return false; + } + + int _count; + bool* _queens, *_ln, *_cl; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + nQueens n; int nq; + while( true ) + { + system( "cls" ); cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> nq; + if( nq < 4 ) return 0; n.solve( nq ); cout << endl << endl; + system( "pause" ); + } + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/N-queens-problem/C++/n-queens-problem-2.cpp b/Task/N-queens-problem/C++/n-queens-problem-2.cpp new file mode 100644 index 0000000000..0e2a19d453 --- /dev/null +++ b/Task/N-queens-problem/C++/n-queens-problem-2.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +typedef unsigned int uint; + +//-------------------------------------------------------------------------------------------------- +class nQueens_Heuristic +{ +public: + void solve( uint n ) { makeList( n ); drawBoard( n ); } + +private: + void drawBoard( uint n ) + { + system( "cls" ); string t = "+---+", q = "| Q |", s = "| |"; + COORD c = { 0, 0 }; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); + uint w = 0; + for( uint y = 0, cy = 0; y < n; y++ ) + { + for( uint x = 0; x < n; x++ ) + { + SetConsoleCursorPosition( h, c ); cout << t; + c.Y++; SetConsoleCursorPosition( h, c ); + if( x + 1 == solution[w] ) cout << q; else cout << s; + c.Y++; SetConsoleCursorPosition( h, c ); + cout << t; c.Y = cy; c.X += 4; + } + cy += 2; c.X = 0; c.Y = cy; w++; + } + solution.clear(); odd.clear(); evn.clear(); + } + + void makeList( uint n ) + { + uint r = n % 6; + for( uint x = 1; x <= n; x++ ) + { + if( x & 1 ) odd.push_back( x ); + else evn.push_back( x ); + } + if( r == 2 ) + { + swap( odd[0], odd[1] ); + odd.erase( find( odd.begin(), odd.end(), 5 ) ); + odd.push_back( 5 ); + } + else if( r == 3 ) + { + odd.erase( odd.begin() ); odd.erase( odd.begin() ); + odd.push_back( 1 ); odd.push_back( 3 ); + evn.erase( evn.begin() ); evn.push_back( 2 ); + } + vector::iterator it = evn.begin(); + while( it != evn.end() ) + { + solution.push_back( ( *it ) ); + it++; + } + it = odd.begin(); + while( it != odd.end() ) + { + solution.push_back( ( *it ) ); + it++; + } + } + + vector odd, evn, solution; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + uint n; nQueens_Heuristic nQH; + while( true ) + { + cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> n; + if( n < 4 ) return 0; + nQH.solve( n ); cout << endl << endl; + } + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/N-queens-problem/Haskell/n-queens-problem-1.hs b/Task/N-queens-problem/Haskell/n-queens-problem-1.hs new file mode 100644 index 0000000000..d857c8f2a9 --- /dev/null +++ b/Task/N-queens-problem/Haskell/n-queens-problem-1.hs @@ -0,0 +1,31 @@ +import Control.Monad +import Data.List + +-- given n, "queens n" solves the n-queens problem, returning a list of all the +-- safe arrangements. each solution is a list of the columns where the queens are +-- located for each row +queens :: Int -> [[Int]] +queens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n] where + + -- foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a + -- foldM folds (from left to right) in the list monad, which is convenient for + -- "nondeterminstically" finding "all possible solutions" of something. the + -- initial value [] corresponds to the only safe arrangement of queens in 0 rows + + -- given a safe arrangement y of queens in the first i rows, and a list of + -- possible choices, "oneMoreQueen y _" returns a list of all the safe + -- arrangements of queens in the first (i+1) rows along with remaining choices + oneMoreQueen (y,d) _ = [ (x:y, d\\[x]) | x <- d, safe x y] + +-- "safe x y" tests whether a queen at column x is safe from previous +-- queens as recorded in y +safe x y = and [ x /= c && x /= c + n && x /= c - n | (n,c) <- zip [1..] y] + +-- prints what the board looks like for a solution; with an extra newline +printSolution y = do + let n = length y + mapM_ (\x -> putStrLn [if z == x then 'Q' else '.' | z <- [1..n]]) y + putStrLn "" + +-- prints all the solutions for 6 queens +main = mapM_ printSolution $ queens 6 diff --git a/Task/N-queens-problem/Haskell/n-queens-problem-2.hs b/Task/N-queens-problem/Haskell/n-queens-problem-2.hs new file mode 100644 index 0000000000..d9eac355f8 --- /dev/null +++ b/Task/N-queens-problem/Haskell/n-queens-problem-2.hs @@ -0,0 +1,11 @@ +import Control.Monad (foldM) +import Data.List ((\\)) + +main :: IO () +main = mapM_ print $ queens 8 + +queens :: Int -> [[Int]] +queens n = foldM f [] [1..n] + where + f qs k = [q:qs | q <- [1..n] \\ qs, q `notDiag` qs] + q `notDiag` qs = and [abs (q - qi) /= i | (qi,i) <- qs `zip` [1..]] diff --git a/Task/N-queens-problem/Mathematica/n-queens-problem-3.math b/Task/N-queens-problem/Mathematica/n-queens-problem-3.math new file mode 100644 index 0000000000..39621e28c5 --- /dev/null +++ b/Task/N-queens-problem/Mathematica/n-queens-problem-3.math @@ -0,0 +1,8 @@ +n=8;cnt=1;per=Permutations[Range[n],{n}];(* All Permutations of length n *) + Do[per[[q]]=Partition[Riffle[Reverse[Range[n]],per[[q]]],2],{q,1,Length[per]}];(* Riffled in the reverse of [range n] partitioned into pairs*) + Do[w=Subsets[per[[t]],{2}];(* This is a full subset of the previous set of pairs taken 2 at a time *) +tot=0; + Do[y=Abs[w[[q,1,1]]-w[[q,2,1]]];x=Abs[w[[q,1,2]]-w[[q,2,2]]];If[x==y,tot++],{q,1,Length[w]}];(* x and y are the abs values of x1-y1 and x2-y2 if equal they are on same diagonal *) + If[tot==0,g=Grid[Table[" ",{n},{n}],Alignment->Center,Frame->All,Spacings->{1.2,1}];(* If no clashing diagonals setup an array and print the permutation and the grid*) + Do[g[[1,per[[t,w,1]],per[[t,w,2]]]]="Q",{w,1,n}]; + Print[cnt," ",per[[t]]," ",g];cnt++],{t,1,Length[per]}] diff --git a/Task/N-queens-problem/Prolog/n-queens-problem-4.pro b/Task/N-queens-problem/Prolog/n-queens-problem-4.pro new file mode 100644 index 0000000000..5cb0a4f6c3 --- /dev/null +++ b/Task/N-queens-problem/Prolog/n-queens-problem-4.pro @@ -0,0 +1,23 @@ +% 8 queens problem. +% q(Row) represents a queen, allocated one per row. No rows ever clash. +% The columns are chosen iteratively from available columns held in a +% list, reduced with each allocation, so we need never check verticals. +% For diagonals, we check prior to allocation whether each newly placed +% queen will clash with any of the prior placements. This prevents +% most invalid permutations from ever being attempted. +can_place(_, []) :- !. % success for empty board +can_place(q(R,C),Board) :- % check diagonals against allocated queens + member(q(Ra,Ca), Board), abs(Ra-R) =:= abs(Ca-C), !, fail. +can_place(_,_). % succeed if no diagonals failed + +queens([], [], Board, Board). % found a solution +queens([q(R)|Queens], Columns, Board, Solution) :- + nth0(_,Columns,C,Free), can_place(q(R,C),Board), % find all solutions + queens(Queens,Free,[q(R,C)|Board], Solution). % recursively + +queens :- + findall(q(N), between(0,7,N), Queens), findall(N, between(0,7,N), Columns), + findall(B, queens(Queens, Columns, [], B), Boards), % backtrack over all + length(Boards, Len), writef('%w solutions:\n', [Len]), % Output solutions + member(R,Boards), reverse(R,Board), writef(' - %w\n', [Board]), fail. +queens. diff --git a/Task/N-queens-problem/Racket/n-queens-problem-1.rkt b/Task/N-queens-problem/Racket/n-queens-problem-1.rkt new file mode 100644 index 0000000000..032f17d5bb --- /dev/null +++ b/Task/N-queens-problem/Racket/n-queens-problem-1.rkt @@ -0,0 +1,30 @@ +#lang racket + +(struct Q (x y) #:transparent) + +;; returns true if given q1 and q2 do not conflict +(define (safe? q1 q2) + (match* (q1 q2) + [((Q x1 y1) (Q x2 y2)) + (not (or (= x1 x2) (= y1 y2) + (= (abs (- x1 x2)) (abs (- y1 y2)))))])) + +;; returns true if given q doesn't conflict with anything in given list of qs +(define (safe-lst? q qs) (for/and ([q2 qs]) (safe? q q2))) + +(define (nqueens n) + ;; qs is partial solution; x y is current position to try + (let loop ([qs null] [x 0] [y 0]) + (cond [(= (length qs) n) qs] ; found a solution + [(>= x n) (loop qs 0 (add1 y))] ; go to next row + [(>= y n) #f] ; current solution is invalid + [else + (define q (Q x y)) + (if (safe-lst? q qs) ; is current position safe? + (or (loop (cons q qs) 0 (add1 y)) ; optimistically place a queen + ; (and move pos to next row) + (loop qs (add1 x) y)) ; backtrack if it fails + (loop qs (add1 x) y))]))) + +(nqueens 8) +; => (list (Q 3 7) (Q 1 6) (Q 6 5) (Q 2 4) (Q 5 3) (Q 7 2) (Q 4 1) (Q 0 0)) diff --git a/Task/N-queens-problem/Racket/n-queens-problem-2.rkt b/Task/N-queens-problem/Racket/n-queens-problem-2.rkt new file mode 100644 index 0000000000..4c38af2588 --- /dev/null +++ b/Task/N-queens-problem/Racket/n-queens-problem-2.rkt @@ -0,0 +1,10 @@ +(require htdp/show-queen) + +(define (show-nqueens n) + (define qs (time (nqueens n))) + (show-queen + (for/list ([row n]) + (for/list ([col n]) + (if (member (Q row col) qs) #t #f))))) + +(show-nqueens 8) diff --git a/Task/N-queens-problem/Racket/n-queens-problem-3.rkt b/Task/N-queens-problem/Racket/n-queens-problem-3.rkt new file mode 100644 index 0000000000..eaa87514b8 --- /dev/null +++ b/Task/N-queens-problem/Racket/n-queens-problem-3.rkt @@ -0,0 +1,45 @@ +#lang racket + +(struct Q (x y) #:transparent) + +(define-syntax-rule (lcons x y) (cons x (lazy y))) + +(define (lazy-filter p? lst) + (define flst (force lst)) + (if (null? flst) '() + (let ([x (car flst)]) + (if (p? x) + (lcons x (lazy-filter p? (cdr flst))) + (lazy-filter p? (cdr flst)))))) + +(define (lazy-foldr f base lst) + (define flst (force lst)) + (if (null? flst) base + (f (car flst) (lazy (lazy-foldr f base (cdr flst)))))) + +(define (tails lst) + (if (null? lst) '(()) + (cons lst (tails (cdr lst))))) + +(define (safe? q1 q2) + (match* (q1 q2) + [((Q x1 y1) (Q x2 y2)) + (not (or (= x1 x2) (= y1 y2) + (= (abs (- x1 x2)) (abs (- y1 y2)))))])) + +(define (safe-lst? lst) + (or (null? lst) + (let ([q1 (car lst)]) + (for/and ([q2 (cdr lst)]) (safe? q1 q2))))) + +(define (valid? lst) (andmap safe-lst? (tails lst))) + +(define (nqueens n) + (define all-possible-solutions + (for/fold ([qss-so-far '(())]) ([row (in-range n)]) + (lazy-foldr + (λ (qs new-qss) + (append (for/list ([col (in-range n)]) (cons (Q row col) qs)) + new-qss)) + '() qss-so-far))) + (lazy-filter valid? all-possible-solutions)) diff --git a/Task/N-queens-problem/Racket/n-queens-problem-4.rkt b/Task/N-queens-problem/Racket/n-queens-problem-4.rkt new file mode 100644 index 0000000000..540cfde5a1 --- /dev/null +++ b/Task/N-queens-problem/Racket/n-queens-problem-4.rkt @@ -0,0 +1,2 @@ +(car (nqueens 8)) +;; => (list (Q 7 3) (Q 6 1) (Q 5 6) (Q 4 2) (Q 3 5) (Q 2 7) (Q 1 4) (Q 0 0)) diff --git a/Task/N-queens-problem/Racket/n-queens-problem-5.rkt b/Task/N-queens-problem/Racket/n-queens-problem-5.rkt new file mode 100644 index 0000000000..353f559e4d --- /dev/null +++ b/Task/N-queens-problem/Racket/n-queens-problem-5.rkt @@ -0,0 +1,101 @@ +(define (force-and-print qs) + (define forced (force qs)) + (unless (null? forced) + (printf "~v\n" (car forced)) + (force-and-print (cdr forced)))) + +(force-and-print (nqueens 8)) + +; => +;(list (Q 7 3) (Q 6 1) (Q 5 6) (Q 4 2) (Q 3 5) (Q 2 7) (Q 1 4) (Q 0 0)) +;(list (Q 7 4) (Q 6 1) (Q 5 3) (Q 4 6) (Q 3 2) (Q 2 7) (Q 1 5) (Q 0 0)) +;(list (Q 7 2) (Q 6 4) (Q 5 1) (Q 4 7) (Q 3 5) (Q 2 3) (Q 1 6) (Q 0 0)) +;(list (Q 7 2) (Q 6 5) (Q 5 3) (Q 4 1) (Q 3 7) (Q 2 4) (Q 1 6) (Q 0 0)) +;(list (Q 7 4) (Q 6 6) (Q 5 0) (Q 4 2) (Q 3 7) (Q 2 5) (Q 1 3) (Q 0 1)) +;(list (Q 7 3) (Q 6 5) (Q 5 7) (Q 4 2) (Q 3 0) (Q 2 6) (Q 1 4) (Q 0 1)) +;(list (Q 7 2) (Q 6 5) (Q 5 7) (Q 4 0) (Q 3 3) (Q 2 6) (Q 1 4) (Q 0 1)) +;(list (Q 7 4) (Q 6 2) (Q 5 7) (Q 4 3) (Q 3 6) (Q 2 0) (Q 1 5) (Q 0 1)) +;(list (Q 7 4) (Q 6 6) (Q 5 3) (Q 4 0) (Q 3 2) (Q 2 7) (Q 1 5) (Q 0 1)) +;(list (Q 7 3) (Q 6 0) (Q 5 4) (Q 4 7) (Q 3 5) (Q 2 2) (Q 1 6) (Q 0 1)) +;(list (Q 7 2) (Q 6 5) (Q 5 3) (Q 4 0) (Q 3 7) (Q 2 4) (Q 1 6) (Q 0 1)) +;(list (Q 7 3) (Q 6 6) (Q 5 4) (Q 4 2) (Q 3 0) (Q 2 5) (Q 1 7) (Q 0 1)) +;(list (Q 7 5) (Q 6 3) (Q 5 1) (Q 4 7) (Q 3 4) (Q 2 6) (Q 1 0) (Q 0 2)) +;(list (Q 7 5) (Q 6 3) (Q 5 6) (Q 4 0) (Q 3 7) (Q 2 1) (Q 1 4) (Q 0 2)) +;(list (Q 7 0) (Q 6 6) (Q 5 3) (Q 4 5) (Q 3 7) (Q 2 1) (Q 1 4) (Q 0 2)) +;(list (Q 7 5) (Q 6 7) (Q 5 1) (Q 4 3) (Q 3 0) (Q 2 6) (Q 1 4) (Q 0 2)) +;(list (Q 7 5) (Q 6 1) (Q 5 6) (Q 4 0) (Q 3 3) (Q 2 7) (Q 1 4) (Q 0 2)) +;(list (Q 7 3) (Q 6 6) (Q 5 0) (Q 4 7) (Q 3 4) (Q 2 1) (Q 1 5) (Q 0 2)) +;(list (Q 7 4) (Q 6 7) (Q 5 3) (Q 4 0) (Q 3 6) (Q 2 1) (Q 1 5) (Q 0 2)) +;(list (Q 7 3) (Q 6 7) (Q 5 0) (Q 4 4) (Q 3 6) (Q 2 1) (Q 1 5) (Q 0 2)) +;(list (Q 7 1) (Q 6 6) (Q 5 4) (Q 4 7) (Q 3 0) (Q 2 3) (Q 1 5) (Q 0 2)) +;(list (Q 7 0) (Q 6 6) (Q 5 4) (Q 4 7) (Q 3 1) (Q 2 3) (Q 1 5) (Q 0 2)) +;(list (Q 7 1) (Q 6 4) (Q 5 6) (Q 4 3) (Q 3 0) (Q 2 7) (Q 1 5) (Q 0 2)) +;(list (Q 7 3) (Q 6 1) (Q 5 6) (Q 4 4) (Q 3 0) (Q 2 7) (Q 1 5) (Q 0 2)) +;(list (Q 7 4) (Q 6 6) (Q 5 0) (Q 4 3) (Q 3 1) (Q 2 7) (Q 1 5) (Q 0 2)) +;(list (Q 7 5) (Q 6 3) (Q 5 0) (Q 4 4) (Q 3 7) (Q 2 1) (Q 1 6) (Q 0 2)) +;(list (Q 7 4) (Q 6 0) (Q 5 3) (Q 4 5) (Q 3 7) (Q 2 1) (Q 1 6) (Q 0 2)) +;(list (Q 7 4) (Q 6 1) (Q 5 5) (Q 4 0) (Q 3 6) (Q 2 3) (Q 1 7) (Q 0 2)) +;(list (Q 7 5) (Q 6 2) (Q 5 6) (Q 4 1) (Q 3 7) (Q 2 4) (Q 1 0) (Q 0 3)) +;(list (Q 7 1) (Q 6 6) (Q 5 2) (Q 4 5) (Q 3 7) (Q 2 4) (Q 1 0) (Q 0 3)) +;(list (Q 7 6) (Q 6 2) (Q 5 0) (Q 4 5) (Q 3 7) (Q 2 4) (Q 1 1) (Q 0 3)) +;(list (Q 7 4) (Q 6 0) (Q 5 7) (Q 4 5) (Q 3 2) (Q 2 6) (Q 1 1) (Q 0 3)) +;(list (Q 7 0) (Q 6 4) (Q 5 7) (Q 4 5) (Q 3 2) (Q 2 6) (Q 1 1) (Q 0 3)) +;(list (Q 7 2) (Q 6 5) (Q 5 7) (Q 4 0) (Q 3 4) (Q 2 6) (Q 1 1) (Q 0 3)) +;(list (Q 7 5) (Q 6 2) (Q 5 0) (Q 4 6) (Q 3 4) (Q 2 7) (Q 1 1) (Q 0 3)) +;(list (Q 7 6) (Q 6 4) (Q 5 2) (Q 4 0) (Q 3 5) (Q 2 7) (Q 1 1) (Q 0 3)) +;(list (Q 7 6) (Q 6 2) (Q 5 7) (Q 4 1) (Q 3 4) (Q 2 0) (Q 1 5) (Q 0 3)) +;(list (Q 7 4) (Q 6 2) (Q 5 0) (Q 4 6) (Q 3 1) (Q 2 7) (Q 1 5) (Q 0 3)) +;(list (Q 7 1) (Q 6 4) (Q 5 6) (Q 4 0) (Q 3 2) (Q 2 7) (Q 1 5) (Q 0 3)) +;(list (Q 7 2) (Q 6 5) (Q 5 1) (Q 4 4) (Q 3 7) (Q 2 0) (Q 1 6) (Q 0 3)) +;(list (Q 7 5) (Q 6 0) (Q 5 4) (Q 4 1) (Q 3 7) (Q 2 2) (Q 1 6) (Q 0 3)) +;(list (Q 7 7) (Q 6 2) (Q 5 0) (Q 4 5) (Q 3 1) (Q 2 4) (Q 1 6) (Q 0 3)) +;(list (Q 7 1) (Q 6 7) (Q 5 5) (Q 4 0) (Q 3 2) (Q 2 4) (Q 1 6) (Q 0 3)) +;(list (Q 7 4) (Q 6 6) (Q 5 1) (Q 4 5) (Q 3 2) (Q 2 0) (Q 1 7) (Q 0 3)) +;(list (Q 7 2) (Q 6 5) (Q 5 1) (Q 4 6) (Q 3 4) (Q 2 0) (Q 1 7) (Q 0 3)) +;(list (Q 7 5) (Q 6 1) (Q 5 6) (Q 4 0) (Q 3 2) (Q 2 4) (Q 1 7) (Q 0 3)) +;(list (Q 7 2) (Q 6 6) (Q 5 1) (Q 4 7) (Q 3 5) (Q 2 3) (Q 1 0) (Q 0 4)) +;(list (Q 7 5) (Q 6 2) (Q 5 6) (Q 4 1) (Q 3 3) (Q 2 7) (Q 1 0) (Q 0 4)) +;(list (Q 7 3) (Q 6 1) (Q 5 6) (Q 4 2) (Q 3 5) (Q 2 7) (Q 1 0) (Q 0 4)) +;(list (Q 7 6) (Q 6 0) (Q 5 2) (Q 4 7) (Q 3 5) (Q 2 3) (Q 1 1) (Q 0 4)) +;(list (Q 7 0) (Q 6 5) (Q 5 7) (Q 4 2) (Q 3 6) (Q 2 3) (Q 1 1) (Q 0 4)) +;(list (Q 7 2) (Q 6 7) (Q 5 3) (Q 4 6) (Q 3 0) (Q 2 5) (Q 1 1) (Q 0 4)) +;(list (Q 7 5) (Q 6 2) (Q 5 6) (Q 4 3) (Q 3 0) (Q 2 7) (Q 1 1) (Q 0 4)) +;(list (Q 7 6) (Q 6 3) (Q 5 1) (Q 4 7) (Q 3 5) (Q 2 0) (Q 1 2) (Q 0 4)) +;(list (Q 7 3) (Q 6 5) (Q 5 7) (Q 4 1) (Q 3 6) (Q 2 0) (Q 1 2) (Q 0 4)) +;(list (Q 7 1) (Q 6 5) (Q 5 0) (Q 4 6) (Q 3 3) (Q 2 7) (Q 1 2) (Q 0 4)) +;(list (Q 7 1) (Q 6 3) (Q 5 5) (Q 4 7) (Q 3 2) (Q 2 0) (Q 1 6) (Q 0 4)) +;(list (Q 7 2) (Q 6 5) (Q 5 7) (Q 4 1) (Q 3 3) (Q 2 0) (Q 1 6) (Q 0 4)) +;(list (Q 7 5) (Q 6 2) (Q 5 0) (Q 4 7) (Q 3 3) (Q 2 1) (Q 1 6) (Q 0 4)) +;(list (Q 7 7) (Q 6 3) (Q 5 0) (Q 4 2) (Q 3 5) (Q 2 1) (Q 1 6) (Q 0 4)) +;(list (Q 7 3) (Q 6 7) (Q 5 0) (Q 4 2) (Q 3 5) (Q 2 1) (Q 1 6) (Q 0 4)) +;(list (Q 7 1) (Q 6 5) (Q 5 7) (Q 4 2) (Q 3 0) (Q 2 3) (Q 1 6) (Q 0 4)) +;(list (Q 7 6) (Q 6 1) (Q 5 5) (Q 4 2) (Q 3 0) (Q 2 3) (Q 1 7) (Q 0 4)) +;(list (Q 7 2) (Q 6 5) (Q 5 1) (Q 4 6) (Q 3 0) (Q 2 3) (Q 1 7) (Q 0 4)) +;(list (Q 7 3) (Q 6 6) (Q 5 2) (Q 4 7) (Q 3 1) (Q 2 4) (Q 1 0) (Q 0 5)) +;(list (Q 7 3) (Q 6 7) (Q 5 4) (Q 4 2) (Q 3 0) (Q 2 6) (Q 1 1) (Q 0 5)) +;(list (Q 7 2) (Q 6 4) (Q 5 7) (Q 4 3) (Q 3 0) (Q 2 6) (Q 1 1) (Q 0 5)) +;(list (Q 7 3) (Q 6 1) (Q 5 7) (Q 4 4) (Q 3 6) (Q 2 0) (Q 1 2) (Q 0 5)) +;(list (Q 7 4) (Q 6 6) (Q 5 1) (Q 4 3) (Q 3 7) (Q 2 0) (Q 1 2) (Q 0 5)) +;(list (Q 7 6) (Q 6 3) (Q 5 1) (Q 4 4) (Q 3 7) (Q 2 0) (Q 1 2) (Q 0 5)) +;(list (Q 7 7) (Q 6 1) (Q 5 3) (Q 4 0) (Q 3 6) (Q 2 4) (Q 1 2) (Q 0 5)) +;(list (Q 7 6) (Q 6 1) (Q 5 3) (Q 4 0) (Q 3 7) (Q 2 4) (Q 1 2) (Q 0 5)) +;(list (Q 7 4) (Q 6 0) (Q 5 7) (Q 4 3) (Q 3 1) (Q 2 6) (Q 1 2) (Q 0 5)) +;(list (Q 7 3) (Q 6 0) (Q 5 4) (Q 4 7) (Q 3 1) (Q 2 6) (Q 1 2) (Q 0 5)) +;(list (Q 7 4) (Q 6 1) (Q 5 7) (Q 4 0) (Q 3 3) (Q 2 6) (Q 1 2) (Q 0 5)) +;(list (Q 7 2) (Q 6 6) (Q 5 1) (Q 4 7) (Q 3 4) (Q 2 0) (Q 1 3) (Q 0 5)) +;(list (Q 7 2) (Q 6 0) (Q 5 6) (Q 4 4) (Q 3 7) (Q 2 1) (Q 1 3) (Q 0 5)) +;(list (Q 7 7) (Q 6 1) (Q 5 4) (Q 4 2) (Q 3 0) (Q 2 6) (Q 1 3) (Q 0 5)) +;(list (Q 7 2) (Q 6 4) (Q 5 1) (Q 4 7) (Q 3 0) (Q 2 6) (Q 1 3) (Q 0 5)) +;(list (Q 7 2) (Q 6 4) (Q 5 6) (Q 4 0) (Q 3 3) (Q 2 1) (Q 1 7) (Q 0 5)) +;(list (Q 7 4) (Q 6 1) (Q 5 3) (Q 4 5) (Q 3 7) (Q 2 2) (Q 1 0) (Q 0 6)) +;(list (Q 7 5) (Q 6 2) (Q 5 4) (Q 4 7) (Q 3 0) (Q 2 3) (Q 1 1) (Q 0 6)) +;(list (Q 7 4) (Q 6 7) (Q 5 3) (Q 4 0) (Q 3 2) (Q 2 5) (Q 1 1) (Q 0 6)) +;(list (Q 7 3) (Q 6 1) (Q 5 4) (Q 4 7) (Q 3 5) (Q 2 0) (Q 1 2) (Q 0 6)) +;(list (Q 7 3) (Q 6 5) (Q 5 0) (Q 4 4) (Q 3 1) (Q 2 7) (Q 1 2) (Q 0 6)) +;(list (Q 7 5) (Q 6 2) (Q 5 0) (Q 4 7) (Q 3 4) (Q 2 1) (Q 1 3) (Q 0 6)) +;(list (Q 7 4) (Q 6 2) (Q 5 0) (Q 4 5) (Q 3 7) (Q 2 1) (Q 1 3) (Q 0 6)) +;(list (Q 7 3) (Q 6 1) (Q 5 7) (Q 4 5) (Q 3 0) (Q 2 2) (Q 1 4) (Q 0 6)) +;(list (Q 7 5) (Q 6 2) (Q 5 4) (Q 4 6) (Q 3 0) (Q 2 3) (Q 1 1) (Q 0 7)) +;(list (Q 7 5) (Q 6 3) (Q 5 6) (Q 4 0) (Q 3 2) (Q 2 4) (Q 1 1) (Q 0 7)) +;(list (Q 7 3) (Q 6 6) (Q 5 4) (Q 4 1) (Q 3 5) (Q 2 0) (Q 1 2) (Q 0 7)) +;(list (Q 7 4) (Q 6 6) (Q 5 1) (Q 4 5) (Q 3 2) (Q 2 0) (Q 1 3) (Q 0 7)) diff --git a/Task/N-queens-problem/Racket/n-queens-problem-6.rkt b/Task/N-queens-problem/Racket/n-queens-problem-6.rkt new file mode 100644 index 0000000000..42f09bdb51 --- /dev/null +++ b/Task/N-queens-problem/Racket/n-queens-problem-6.rkt @@ -0,0 +1,56 @@ +#lang racket +(define (remove x lst) + (for/list ([i (in-range (length lst))] + #:when (not (= x i))) + (list-ref lst i))) + +(define (switch-pairs lst) + (cond [(null? lst) '()] + [(null? (cdr lst)) (list '() (car lst))] + [else (append (list (cadr lst) (car lst)) + (switch-pairs (cddr lst)))])) + +(define (switch-places a1 a2 lst) + (for/list ([i (length lst)]) + (list-ref lst (cond [(= a1 i) a2] [(= a2 i) a1] [else i])))) + +(define (position-queens n) + (cond [(= 1 n) (list (list 1))] + [(> 4 n) #f] + [else (possible-queens n)])) + +(define (possible-queens n) + (define rem (remainder n 12)) + (define lst (build-list n add1)) + (define evens (filter even? lst)) + (define odds (filter odd? lst)) + (cond [(or (= rem 9) (= rem 3)) (case3or9 evens odds)] + [(= rem 8) (case8 evens odds)] + [(= rem 2) (case2 evens odds)] + [else (append evens odds)])) + +(define (case3or9 evens odds) + (for/fold ([acum (append (cdr evens) (list (car evens)) odds)]) + ([i (in-list '(1 3))]) + (append (remove (list-ref acum i) acum) (list i)))) + +(define (case8 evens odds) + (append evens (switch-pairs odds))) + +(define (case2 evens odds) + (define nums (append evens odds)) + (define idx (map (λ(i) (list-ref nums i)) '(1 3 5))) + (append (remove (caddr idx) + (switch-places (car idx) (cadr idx) nums)) + '(5))) + +(define (queens n) + (define position-numbers (position-queens n)) + (define positions-on-board + (for/list ([i n]) (cons i (sub1 (list-ref position-numbers i))))) + (for/list ([x n]) + (for/list ([y n]) + (if (member (cons x y) positions-on-board) "Q" ".")))) + +(define (print-queens n) + (for ([x (queens n)]) (displayln (string-join x)))) diff --git a/Task/N-queens-problem/Run-BASIC/n-queens-problem.run b/Task/N-queens-problem/Run-BASIC/n-queens-problem.run new file mode 100644 index 0000000000..23d992b72b --- /dev/null +++ b/Task/N-queens-problem/Run-BASIC/n-queens-problem.run @@ -0,0 +1,112 @@ +[loop] +input "How many queens (N>=4)";n +if n < 4 then + print "Must be greater than 4" + goto [loop] +end if + +dim plot$(100,100) +dim q(n+20) +dim e(n+20) +dim o(n+20) +r=n mod 6 +if r<>2 and r<>3 then + gosub [samp] + goto [shoBoard] +end if +for i=1 to int(n/2) + e(i) = 2 * i +next +for i=1 to int((n/2)+.5) + o(i) = 2 *i-1 +next +if r = 2 then gosub [edt2] +if r = 3 then gosub [edt3] +s = 1 +for i=1 to n + if e(i)>0 then + q(s) = e(i) + s = s+1 + end if +next +for i=1 to n + if o(i) > 0 then + q(s) = o(i) + s = s + 1 + end if +next +' print board +[shoBoard] +cls +for i = 1 to n + plot$(i,26-q(i)) = "*" + plot$(i,24-n) = chr$(96+i) + plot$(n+1,26-i) = str$(i) +next i +for ii = 1 to 100 + for jj = 1 to 100 + print left$(plot$(jj,ii)+" ",1); + next jj +print +next ii +end + +' the simple case +[samp] +p = 1 +for i = 1 to n + if i mod 2=0 then + q(p) = i + p = p + 1 + end if +next i +for i = 1 to n + if i mod 2 then + q(p) = i + p = p + 1 + end if +next +return +' edit list when remainder is 2 +[edt2] +for i=1 to n + if o(i) = 3 then + o(i) = 1 + else + if o(i)=1 then o(i) = 3 + end if + if o(i) = 5 then + o(i)= o(i) -1 + else + if o(i) = 0 then + o(i) = 5 + return + end if + end if +next + +' edit list when remainder is 3 +[edt3] +for i = 1 to n + if e(i) = 2 then + e(i) = e(i)-1 + else + if e(i) = 0 then + e(i) = 2 + goto [more] + end if + end if +next i +' edit list some more +[more] +for i = 1 to n + if (o(i)=1 or o(i)=3) then + o(i) = o(i)-1 + else + if o(i) = 0 then + o(i) = 1 + o(i+1) = 3 + return + end if + end if +next diff --git a/Task/N-queens-problem/Seed7/n-queens-problem.seed7 b/Task/N-queens-problem/Seed7/n-queens-problem.seed7 new file mode 100644 index 0000000000..5865c7d66d --- /dev/null +++ b/Task/N-queens-problem/Seed7/n-queens-problem.seed7 @@ -0,0 +1,51 @@ +$ include "seed7_05.s7i"; + +var array integer: board is 8 times 0; +var integer: solutionNum is 0; + +const func boolean: safe (in integer: y) is func + result + var boolean: safe is TRUE; + local + var integer: i is 1; + begin + while i < y and safe do + safe := board[y - i] <> board[y] and + board[y - i] <> board[y] - i and + board[y - i] <> board[y] + i; + incr(i); + end while; + end func; + +const proc: putBoard is func + local + var integer: y is 0; + begin + incr(solutionNum); + writeln; + writeln("Solution " <& solutionNum); + for y range 1 to 8 do + writeln("|_" mult pred(board[y]) <& "|Q" <& "|_" mult (8 - board[y]) <& "|"); + end for; + end func; + +const proc: main is func + local + var integer: y is 1; + begin + while y >= 1 do + repeat + incr(board[y]); + until board[y] > 8 or safe(y); + if board[y] <= 8 then + if y < 8 then + incr(y); + board[y] := 0; + else + putBoard; + end if; + else + decr(y); + end if; + end while; + end func; diff --git a/Task/Narcissist/Racket/narcissist.rkt b/Task/Narcissist/Racket/narcissist.rkt new file mode 100644 index 0000000000..32940c7e7b --- /dev/null +++ b/Task/Narcissist/Racket/narcissist.rkt @@ -0,0 +1,5 @@ +-> ((lambda (x) (equal? (read) (list x (list 'quote x)))) + '(lambda (x) (equal? (read) (list x (list 'quote x))))) +((lambda (x) (equal? (read) (list x (list 'quote x)))) + '(lambda (x) (equal? (read) (list x (list 'quote x))))) +#t diff --git a/Task/Nautical-bell/00DESCRIPTION b/Task/Nautical-bell/00DESCRIPTION index f900f892b9..01ffa892de 100644 --- a/Task/Nautical-bell/00DESCRIPTION +++ b/Task/Nautical-bell/00DESCRIPTION @@ -2,3 +2,6 @@ The task is to write a small program that emulates a [[wp:Ship's bell#Timing_of_ The bell timing should be in accordance with [[wp:GMT|Greenwich Mean Time]], unless locale dictates otherwise. It is permissible for the program to [[Run as a daemon or service|daemonize]], or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. + +;Cf.: +* [[Sleep]] diff --git a/Task/Nautical-bell/C++/nautical-bell.cpp b/Task/Nautical-bell/C++/nautical-bell.cpp new file mode 100644 index 0000000000..39d62c4b79 --- /dev/null +++ b/Task/Nautical-bell/C++/nautical-bell.cpp @@ -0,0 +1,69 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class bells +{ +public: + void start() + { + watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; + count[0] = "One"; count[1] = "Two"; count[2] = "Three"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight"; + _inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL ); + } +private: + static DWORD WINAPI bell( LPVOID p ) + { + DWORD wait = _inst->waitTime(); + while( true ) + { + Sleep( wait ); + _inst->playBell(); + wait = _inst->waitTime(); + } + return 0; + } + + DWORD waitTime() + { + GetLocalTime( &st ); + int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute; + return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) ); + } + + void playBell() + { + GetLocalTime( &st ); + int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b; + int w = ( 60 * st.wHour + st.wMinute ); + if( w < 1 ) w = 5; else w = ( w - 1 ) / 240; + char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute ); + + cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell"; + if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl; + + for( int x = 0, c = 1; x < b; x++, c++ ) + { + cout << "\7"; Sleep( 500 ); + if( !( c % 2 ) ) Sleep( 300 ); + } + } + + SYSTEMTIME st; + string watch[7], count[8]; + static bells* _inst; +}; +//-------------------------------------------------------------------------------------------------- +bells* bells::_inst = 0; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + bells b; b.start(); + while( 1 ); // <- runs forever! + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Non-continuous-subsequences/Haskell/non-continuous-subsequences-5.hs b/Task/Non-continuous-subsequences/Haskell/non-continuous-subsequences-5.hs index 1783736edc..7a4f78b3de 100644 --- a/Task/Non-continuous-subsequences/Haskell/non-continuous-subsequences-5.hs +++ b/Task/Non-continuous-subsequences/Haskell/non-continuous-subsequences-5.hs @@ -1,9 +1,8 @@ import Data.List (inits, tails) -subseqs [] = [] -subseqs (x:xs) = [x] : map (x:) s ++ s where s = subseqs xs +subseqs = foldr (\x s -> [x] : map (x:) s ++ s) [] -consecs x = concatMap (tail.inits) (tails x) +consecs = concatMap (tail.inits) . tails minus [] [] = [] minus (a:as) bb@(b:bs) diff --git a/Task/Non-continuous-subsequences/Racket/non-continuous-subsequences-1.rkt b/Task/Non-continuous-subsequences/Racket/non-continuous-subsequences-1.rkt new file mode 100644 index 0000000000..e06becc591 --- /dev/null +++ b/Task/Non-continuous-subsequences/Racket/non-continuous-subsequences-1.rkt @@ -0,0 +1,4 @@ +(define (subsets l) + (if (null? l) '(()) + (append (for/list ([l2 (subsets (cdr l))]) (cons (car l) l2)) + (subsets (cdr l))))) diff --git a/Task/Non-continuous-subsequences/Racket/non-continuous-subsequences-2.rkt b/Task/Non-continuous-subsequences/Racket/non-continuous-subsequences-2.rkt new file mode 100644 index 0000000000..899d05ca74 --- /dev/null +++ b/Task/Non-continuous-subsequences/Racket/non-continuous-subsequences-2.rkt @@ -0,0 +1,9 @@ +#lang racket +(define (non-continuous-subseqs l) + (let loop ([l l] [x 0]) + (if (null? l) (if (>= x 3) '(()) '()) + (append (for/list ([l2 (loop (cdr l) (if (even? x) (add1 x) x))]) + (cons (car l) l2)) + (loop (cdr l) (if (odd? x) (add1 x) x)))))) +(non-continuous-subseqs '(1 2 3 4)) +;; => '((1 2 4) (1 3 4) (1 3) (1 4) (2 4)) diff --git a/Task/Non-decimal-radices-Convert/Aime/non-decimal-radices-convert.aime b/Task/Non-decimal-radices-Convert/Aime/non-decimal-radices-convert.aime new file mode 100644 index 0000000000..ebbae832aa --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Aime/non-decimal-radices-convert.aime @@ -0,0 +1,13 @@ +o_text(bfxa(0, 0, 16, 1000000)); +o_byte('\n'); +o_text(bfxa(0, 0, 5, 1000000)); +o_byte('\n'); +o_text(bfxa(0, 0, 2, 1000000)); +o_byte('\n'); + +o_integer(alpha("f4240", 16)); +o_byte('\n'); +o_integer(alpha("224000000", 5)); +o_byte('\n'); +o_integer(alpha("11110100001001000000", 2)); +o_byte('\n'); diff --git a/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-3.d b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-3.d new file mode 100644 index 0000000000..b9f8cb93dd --- /dev/null +++ b/Task/Non-decimal-radices-Convert/D/non-decimal-radices-convert-3.d @@ -0,0 +1,36 @@ +import std.stdio, std.conv, std.algorithm, std.exception, std.ascii, + std.array; + +alias Digits = ubyte[]; + +Digits toBase(ulong number, in ubyte base) pure nothrow { + Digits result; + while (number) { + result = number % base ~ result; + number /= base; + } + return result; +} + +ulong fromBase(in Digits digits, in ubyte base) pure nothrow { + return reduce!((n, k) => n * base + k)(0, digits); +} + +string fromDigits(in Digits digits) pure nothrow { + return digits + .map!(d => cast(char)(d < 10 ? d + '0' : d + 'a' - 10)) + .array; +} + +Digits toDigits(in string number) pure /*nothrow*/ { + static ubyte convert(in dchar d) pure nothrow { + if (d.isDigit) return cast(typeof(return))(d - '0'); + if (d.isUpper) return cast(typeof(return))(d - 'A' + 10); + else return cast(typeof(return))(d - 'a' + 10); + } + return number.map!convert.array; +} + +void main() { + "1ABcd".toDigits.fromBase(16).writeln; +} diff --git a/Task/Non-decimal-radices-Convert/Racket/non-decimal-radices-convert.rkt b/Task/Non-decimal-radices-Convert/Racket/non-decimal-radices-convert.rkt new file mode 100644 index 0000000000..70abab00b7 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Racket/non-decimal-radices-convert.rkt @@ -0,0 +1,21 @@ +#lang racket + +;; Both assume valid inputs +(define (num->str N r) + (let loop ([N N] [digits '()]) + (define-values [N1 d] (quotient/remainder N r)) + (define digits1 (cons (integer->char (+ d (if (< d 10) 48 55))) digits)) + (if (zero? N) (list->string digits1) (loop N1 digits1)))) +(define (str->num S r) + (for/fold ([N 0]) + ([B (string->bytes/utf-8 (string-upcase S))]) + (+ (* N r) (- B (if (< 64 B) 55 48))))) + +;; To try it out: +(define (random-test) + (define N (random 1000000)) + (define r (+ 2 (random 35))) + (define S (num->str N r)) + (define M (str->num S r)) + (printf "~s -> ~a#~a -> ~a => ~a\n" N S r M (if (= M N) 'OK 'BAD))) +;; (random-test) diff --git a/Task/Non-decimal-radices-Convert/Seed7/non-decimal-radices-convert.seed7 b/Task/Non-decimal-radices-Convert/Seed7/non-decimal-radices-convert.seed7 new file mode 100644 index 0000000000..bf08f9ed25 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Seed7/non-decimal-radices-convert.seed7 @@ -0,0 +1,11 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const proc: main is func + begin + writeln(60272032366_ radix 36); # Convert bigInteger to string + writeln(591458 radix 36); # Convert integer to string + + writeln(bigInteger("rosetta", 36)); # Convert string to bigInteger + writeln(integer("code", 36)); # Convert string to integer + end func; diff --git a/Task/Non-decimal-radices-Input/Aime/non-decimal-radices-input.aime b/Task/Non-decimal-radices-Input/Aime/non-decimal-radices-input.aime new file mode 100644 index 0000000000..cd4e0c635f --- /dev/null +++ b/Task/Non-decimal-radices-Input/Aime/non-decimal-radices-input.aime @@ -0,0 +1,11 @@ +o_integer(alpha("f4240", 16)); +o_byte('\n'); +o_integer(alpha("224000000", 5)); +o_byte('\n'); +o_integer(alpha("11110100001001000000", 2)); +o_byte('\n'); + +o_integer(alpha("03641100", 0)); +o_byte('\n'); +o_integer(alpha("0xf4240", 0)); +o_byte('\n'); diff --git a/Task/Non-decimal-radices-Input/Racket/non-decimal-radices-input.rkt b/Task/Non-decimal-radices-Input/Racket/non-decimal-radices-input.rkt new file mode 100644 index 0000000000..c164eb87da --- /dev/null +++ b/Task/Non-decimal-radices-Input/Racket/non-decimal-radices-input.rkt @@ -0,0 +1,16 @@ +#lang racket + +;; Number literals can use #x, #o, and #b for different radices +(list 123 #x7B #o173 #b1111011) +;; -> '(123 123 123 123) + +;; Explicit conversion of strings can use any radix up to 16 +(list (string->number "123") + (string->number "123" 10) + (string->number "7B" 16) + (string->number "83" 15) + (string->number "96" 13) + (string->number "173" 8) + (string->number "11120" 3) + (string->number "1111011" 2)) +;; -> '(123 123 123 123 123 123 123 123) diff --git a/Task/Non-decimal-radices-Input/Seed7/non-decimal-radices-input.seed7 b/Task/Non-decimal-radices-Input/Seed7/non-decimal-radices-input.seed7 new file mode 100644 index 0000000000..b2ac66e878 --- /dev/null +++ b/Task/Non-decimal-radices-Input/Seed7/non-decimal-radices-input.seed7 @@ -0,0 +1,11 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + begin + writeln(integer("0123459", 10)); + writeln(integer("abcf123", 16)); + writeln(integer("7651", 8)); + writeln(integer("1010011010", 2)); + writeln(integer("tplig0", 32)); + writeln(integer("gc0uy9", 36)); + end func; diff --git a/Task/Non-decimal-radices-Output/Aime/non-decimal-radices-output.aime b/Task/Non-decimal-radices-Output/Aime/non-decimal-radices-output.aime new file mode 100644 index 0000000000..8e59aac2a8 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Aime/non-decimal-radices-output.aime @@ -0,0 +1,6 @@ +o_xinteger(16, 1000000); +o_byte('\n'); +o_xinteger(5, 1000000); +o_byte('\n'); +o_xinteger(2, 1000000); +o_byte('\n'); diff --git a/Task/Non-decimal-radices-Output/Racket/non-decimal-radices-output.rkt b/Task/Non-decimal-radices-Output/Racket/non-decimal-radices-output.rkt new file mode 100644 index 0000000000..c667e4bfd8 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Racket/non-decimal-radices-output.rkt @@ -0,0 +1,12 @@ +#lang racket + +;; Explicit conversion of numbers can use the standard radices +(map (λ(r) (number->string 123 r)) '(2 8 10 16)) +;; -> '("1111011" "173" "123" "7b") + +;; There is also the `~r' formatting function that works with any radix +;; up to 36 +(for/list ([r (in-range 2 37)]) (~r 123 #:base r)) +;; -> '("1111011" "02111" "3231" "344" "323" "432" "173" "641" "123" "201" +;; "3a" "69" "b8" "38" "7b" "47" "f6" "96" "36" "i5" "d5" "85" "35" +;; "n4" "j4" "f4" "b4" "74" "34" "u3" "r3" "o3" "l3" "i3" "f3") diff --git a/Task/Nth-root/Racket/nth-root.rkt b/Task/Nth-root/Racket/nth-root.rkt new file mode 100644 index 0000000000..4e88a76e66 --- /dev/null +++ b/Task/Nth-root/Racket/nth-root.rkt @@ -0,0 +1,15 @@ +#lang racket + +(define (nth-root number root (tolerance 0.001)) + (define (acceptable? next current) + (< (abs (- next current)) tolerance)) + + (define (improve current) + (/ (+ (* (- root 1) current) (/ number (expt current (- root 1)))) root)) + + (define (loop current) + (define next-guess (improve current)) + (if (acceptable? next-guess current) + next-guess + (loop next-guess))) + (loop 1.0)) diff --git a/Task/Null-object/Racket/null-object.rkt b/Task/Null-object/Racket/null-object.rkt new file mode 100644 index 0000000000..8869e4a252 --- /dev/null +++ b/Task/Null-object/Racket/null-object.rkt @@ -0,0 +1,6 @@ +-> null +'() +-> (null? null) +#t +-> (null? 3) +#f diff --git a/Task/Null-object/Raven/null-object.raven b/Task/Null-object/Raven/null-object.raven new file mode 100644 index 0000000000..a1d70cca5f --- /dev/null +++ b/Task/Null-object/Raven/null-object.raven @@ -0,0 +1,9 @@ +NULL as $v +$v NULL = # TRUE +$v NULL != # FALSE + +1 NULL = # FALSE +1.1 NULL = # FALSE + +NULL as $v2 +$v2 $v = # TRUE diff --git a/Task/Number-names/D/number-names.d b/Task/Number-names/D/number-names.d index 3cb383e82b..833dcc36c3 100644 --- a/Task/Number-names/D/number-names.d +++ b/Task/Number-names/D/number-names.d @@ -1,60 +1,78 @@ -import std.stdio, std.string; +import std.stdio, std.array, std.algorithm, std.bigint, std.range; -string spellInteger(in long n) pure nothrow { - static immutable tens = ["", "", "twenty", "thirty", "forty", - "fifty", "sixty", "seventy", "eighty", "ninety"]; +immutable tens = ["", "", "twenty", "thirty", "forty", + "fifty", "sixty", "seventy", "eighty", "ninety"]; +immutable small = ["zero", "one", "two", "three", "four", "five", + "six", "seven", "eight", "nine", "ten", "eleven", + "twelve", "thirteen", "fourteen", "fifteen", + "sixteen", "seventeen", "eighteen", "nineteen"]; +immutable huge = ["", ""] ~ ["m", "b", "tr", "quadr", "quint", + "sext", "sept", "oct", "non", "dec"] + .map!q{ a ~ "illion" }.array; - static immutable small = "zero one two three four five six - seven eight nine ten eleven twelve thirteen fourteen - fifteen sixteen seventeen eighteen nineteen".split(); - - static immutable bl = ["", "", "m", "b", "tr", - "quadr", "quint", "sext", "sept", "oct", "non", "dec"]; - - static string nonZero(in string c, in int n) pure nothrow { - return n == 0 ? "" : c ~ spellInteger(n); +string spellBigInt(BigInt n) { + static string nonZero(string c, BigInt n, string connect="") { + return n == 0 ? "" : connect ~ c ~ n.spellBigInt; } - static string big(in int e, in int n) pure nothrow { + static string lastAnd(string num) { + if (num.canFind(",")) { + string pre = num.retro.find(",").retro[0 .. $ - 1]; + string last = num[pre.length + 1 .. $]; + if (!last.canFind(" and ")) + last = " and" ~ last; + num = pre ~ "," ~ last; + } + return num; + } + + static string big(in uint e, BigInt n) { switch (e) { - case 0: return spellInteger(n); - case 1: return spellInteger(n) ~ " thousand"; - default: return spellInteger(n) ~ " " ~ bl[e] ~ "illion"; + case 0: return n.spellBigInt; + case 1: return n.spellBigInt ~ " thousand"; + default: return n.spellBigInt ~ " " ~ huge[e]; } } - /// Generates the value of the digits of n in - /// base 1000 (i.e. 3-digit chunks), in reverse. - static int[] base1000Reverse(in long nn) pure nothrow { - long n = nn; - int[] result; - while (n) { - result ~= n % 1000; - n /= 1000; - } - return result; - } - if (n < 0) { - return "negative " ~ spellInteger(-n); + return "minus " ~ spellBigInt(-n); + } else if (n < 20) { + return small[n.toInt]; + } else if (n < 100) { + BigInt a = n / 10; + BigInt b = n % 10; + return tens[a.toInt] ~ nonZero("-", b); } else if (n < 1000) { - int ni = cast(int)n; // D doesn't infer this. - if (ni < 20) { - return small[ni]; - } else if (ni < 100) { - return tens[ni / 10] ~ nonZero("-", ni % 10); - } else // ni < 1000 - return small[ni / 100] ~ " hundred" ~ - nonZero(" ", ni % 100); + BigInt a = n / 100; + BigInt b = n % 100; + return small[a.toInt] ~ " hundred" ~ nonZero(" ", b, " and"); } else { - string[] pieces; - foreach_reverse (e, x; base1000Reverse(n)) - pieces ~= big(e, x); - return pieces.join(", "); + string[] bigs; + uint e = 0; + while (n != 0) { + BigInt r = n % 1000; + n /= 1000; + if (r != 0) + bigs ~= big(e, r); + e++; + } + + return lastAnd(bigs.retro.join(", ")); } } -void main() { - foreach (i; -10 .. 1_000) - writeln(i, " ", spellInteger(i)); +version(number_names_main) { + void main() { + foreach (n; [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]) + writefln("%+4d -> %s", n, n.BigInt.spellBigInt); + writeln; + + auto n = 2_0121_002_001; + while (n) { + writefln("%-12d -> %s", n, n.BigInt.spellBigInt); + n /= -10; + } + writefln("%-12d -> %s", n, n.BigInt.spellBigInt); + writeln; + } } diff --git a/Task/Number-names/PureBasic/number-names-2.purebasic b/Task/Number-names/PureBasic/number-names-2.purebasic index ec60e1b8b0..5030932b32 100644 --- a/Task/Number-names/PureBasic/number-names-2.purebasic +++ b/Task/Number-names/PureBasic/number-names-2.purebasic @@ -1,48 +1,64 @@ +TENS = [None, None, "twenty", "thirty", "forty", + "fifty", "sixty", "seventy", "eighty", "ninety"] +SMALL = ["zero", "one", "two", "three", "four", "five", + "six", "seven", "eight", "nine", "ten", "eleven", + "twelve", "thirteen", "fourteen", "fifteen", + "sixteen", "seventeen", "eighteen", "nineteen"] +HUGE = [None, None] + [h + "illion" + for h in ("m", "b", "tr", "quadr", "quint", "sext", + "sept", "oct", "non", "dec")] + +def nonzero(c, n, connect=''): + return "" if n == 0 else connect + c + spell_integer(n) + +def last_and(num): + if ',' in num: + pre, last = num.rsplit(',', 1) + if ' and ' not in last: + last = ' and' + last + num = ''.join([pre, ',', last]) + return num + +def big(e, n): + if e == 0: + return spell_integer(n) + elif e == 1: + return spell_integer(n) + " thousand" + else: + return spell_integer(n) + " " + HUGE[e] + +def base1000_rev(n): + # generates the value of the digits of n in base 1000 + # (i.e. 3-digit chunks), in reverse. + while n != 0: + n, r = divmod(n, 1000) + yield r + def spell_integer(n): - tens = [None, None, "twenty", "thirty", "forty", - "fifty", "sixty", "seventy", "eighty", "ninety"] - - small = ["zero", "one", "two", "three", "four", "five", - "six", "seven", "eight", "nine", "ten", "eleven", - "twelve", "thirteen", "fourteen", "fifteen", - "sixteen", "seventeen", "eighteen", "nineteen"] - - bl = [None, None, "m", "b", "tr", "quadr", - "quint", "sext", "sept", "oct", "non", "dec"] - - def nonzero(c, n): - return "" if n == 0 else c + spell_integer(n) - - def big(e, n): - if e == 0: - return spell_integer(n) - elif e == 1: - return spell_integer(n) + " thousand" - else: - return spell_integer(n) + " " + bl[e] + "illion" - - def base1000_rev(n): - # generates the value of the digits of n in base 1000 - # (i.e. 3-digit chunks), in reverse. - while n != 0: - n, r = divmod(n, 1000) - yield r - if n < 0: - return "negative " + spell_integer(-n) + return "minus " + spell_integer(-n) elif n < 20: - return small[n] + return SMALL[n] elif n < 100: a, b = divmod(n, 10) - return tens[a] + nonzero("-", b) + return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) - return small[a] + " hundred" + nonzero(" ", b) + return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: - return ", ".join([big(e, x) for e, x in - enumerate(base1000_rev(n)) if x][::-1]) + num = ", ".join([big(e, x) for e, x in + enumerate(base1000_rev(n)) if x][::-1]) + return last_and(num) -# example -print spell_integer(1278) -print spell_integer(1752) -print spell_integer(2010) +if __name__ == '__main__': + # examples + for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): + print('%+4i -> %s' % (n, spell_integer(n))) + print('') + + n = 201021002001 + while n: + print('%-12i -> %s' % (n, spell_integer(n))) + n //= -10 + print('%-12i -> %s' % (n, spell_integer(n))) + print('') diff --git a/Task/Number-names/Racket/number-names.rkt b/Task/Number-names/Racket/number-names.rkt new file mode 100644 index 0000000000..e750168547 --- /dev/null +++ b/Task/Number-names/Racket/number-names.rkt @@ -0,0 +1,37 @@ +#lang racket + +(define smalls + (map symbol->string + '(zero one two three four five six seven eight nine ten eleven twelve + thirteen fourteen fifteen sixteen seventeen eighteen nineteen))) + +(define tens + (map symbol->string + '(zero ten twenty thirty forty fifty sixty seventy eighty ninety))) + +(define larges + (map symbol->string + '(thousand million billion trillion quadrillion quintillion sextillion + septillion octillion nonillion decillion undecillion duodecillion + tredecillion quattuordecillion quindecillion sexdecillion + septendecillion octodecillion novemdecillion vigintillion))) + +(define (integer->english n) + (define (step div suffix separator [subformat integer->english]) + (define-values [q r] (quotient/remainder n div)) + (define S (if suffix (~a (subformat q) " " suffix) (subformat q))) + (if (zero? r) S (~a S separator (integer->english r)))) + (cond [(< n 0) (~a "negative " (integer->english (- n)))] + [(< n 20) (list-ref smalls n)] + [(< n 100) (step 10 #f "-" (curry list-ref tens))] + [(< n 1000) (step 100 "hundred" " and ")] + [else (let loop ([N 1000000] [D 1000] [unit larges]) + (cond [(null? unit) + (error 'integer->english "number too big: ~e" n)] + [(< n N) (step D (car unit) ", ")] + [else (loop (* 1000 N) (* 1000 D) (cdr unit))]))])) + +(for ([n 10]) + (define e (expt 10 n)) + (define r (+ (* e (random e)) (random e))) + (printf "~s: ~a\n" r (integer->english r))) diff --git a/Task/Number-names/Scala/number-names.scala b/Task/Number-names/Scala/number-names.scala new file mode 100644 index 0000000000..4946561376 --- /dev/null +++ b/Task/Number-names/Scala/number-names.scala @@ -0,0 +1,69 @@ +/** + * Spells a number longhand + * + * @example longhand( 1234 ) // results in: one thousand two hundred thirty-four + */ +def longhand( v:Long, showAnd:Boolean = false, showHyphen:Boolean = true ) : String = { + // Based on a solution of Rex Kerr's + + val onesAndTeens = { + val a1 = Array[String]("") + val a2 = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ") + val a3 = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ") + a1 ++ a2 ++ a3 + } + + val tens = { + val a1 = Array[String]("","") + val a2 = "twen thir for fif six seven eigh nine".split(' ').map(_ + "ty") + a1 ++ a2 + } + + val hundredString = "hundred " + val andString = if( showAnd ) "and " else "" + val hyphenString = if( showHyphen ) "-" else " " + + val powersOfThousands = { + val a1 = Array[String]("","thousand ") + val a2 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ") + val a3 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ") + val a4 = "vigint cent".split(' ').map(_ + "illion ") + a1 ++ a2 ++ a3 ++ a4 + } + + + // 234 becomes "two hundred [and] thirty-four" + def composeScale( v:String, isFirst:Boolean ) : String = { + + val e1 = (v.map(_.toString.toInt).reverse zip List("","-","hundred")).reverse + + e1.map { + case (d,"hundred") if d > 0 => onesAndTeens(d) + hundredString + andString + case (d,"-") if d > 1 && !e1.contains((0,"")) && isFirst => tens(d) + hyphenString + case (d,"-") if d > 1 && !e1.contains((0,"")) => tens(d) + " " + case (d,"-") if d > 1 => tens(d) + case (d,"") if e1.contains((1,"-")) => onesAndTeens(d+10) + case (d,"") => onesAndTeens(d) + case _ => "" + }.mkString + } + + def compose( s:String ) : String = { + + // "1234" becomes List(((1,false),"thousand"), ((234,true),"")) + val thousands = { + def first( s:String ) = (true) #:: Stream.continually(false) // First element true others false + val e1 = s.reverse.grouped(3).map(_.reverse).toList // Group into powers of thousands + val e2 = e1 zip first(s) // Mark the first element + val e3 = e2 zip powersOfThousands // Name the powers of Thousands + e3.reverse // Put it back to most-significant first + } + + thousands.map { case ((v,isFirst),s) => composeScale( v, isFirst ) + s }.mkString.trim + } + + if( v < 0 ) "minus " + compose((-v).toString) else compose(v.toString) +} + +// A little test... +println( Long.MaxValue-13 + " is \"" + longhand( Long.MaxValue-13 ) + "\"" ) diff --git a/Task/Number-reversal-game/D/number-reversal-game.d b/Task/Number-reversal-game/D/number-reversal-game.d index 9037386310..cc0ba2f5a2 100644 --- a/Task/Number-reversal-game/D/number-reversal-game.d +++ b/Task/Number-reversal-game/D/number-reversal-game.d @@ -2,14 +2,14 @@ import std.stdio, std.random, std.string, std.conv, std.algorithm, std.range; void main() { - auto data = iota(1, 10).array(); - do data.randomShuffle(); - while (data.isSorted()); + auto data = iota(1, 10).array; + do data.randomShuffle; + while (data.isSorted); int trial; - while (!data.isSorted()) { + while (!data.isSorted) { writef("%d: %s How many numbers to flip? ", ++trial, data); - data[0 .. readln().strip().to!size_t()].reverse(); + data[0 .. readln.strip.to!uint].reverse; } writefln("\nYou took %d attempts.", trial); } diff --git a/Task/Number-reversal-game/Racket/number-reversal-game.rkt b/Task/Number-reversal-game/Racket/number-reversal-game.rkt new file mode 100644 index 0000000000..dd126ee85f --- /dev/null +++ b/Task/Number-reversal-game/Racket/number-reversal-game.rkt @@ -0,0 +1,8 @@ +#lang racket +(let loop ([nums (range 1 10)] [n 0]) + (cond [(apply < nums) (if (zero? n) + (loop (shuffle nums) 0) + (printf "Done in ~s steps.\n" n))] + [else (printf "Step #~s: ~s\nFlip how many? " n nums) + (define-values (l r) (split-at nums (read))) + (loop (append (reverse l) r) (add1 n))])) diff --git a/Task/Numeric-error-propagation/00DESCRIPTION b/Task/Numeric-error-propagation/00DESCRIPTION index adffba66cc..e9fa06b75a 100644 --- a/Task/Numeric-error-propagation/00DESCRIPTION +++ b/Task/Numeric-error-propagation/00DESCRIPTION @@ -12,7 +12,7 @@ If f, a, and b are values with uncertainties σf, σa, and :* If f = ac then '''σf = |fc(σa / a)|''' :Caution: -::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for exam[ple. See [[Talk:Numeric_error_propagation|the talk page]] for some of the implications of this issue. +::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See [[Talk:Numeric_error_propagation|the talk page]] for some of the implications of this issue. ;Task details: # Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations. diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-1.rkt b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-1.rkt new file mode 100644 index 0000000000..1edbbff2d7 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-1.rkt @@ -0,0 +1,14 @@ +(define (LegendreP n x) + (let compute ([n n] [Pn-1 x] [Pn-2 1]) + (case n + [(0) Pn-2] + [(1) Pn-1] + [else (compute (- n 1) + (/ (- (* (- (* 2 n) 1) x Pn-1) + (* (- n 1) Pn-2)) n) + Pn-1)]))) + +(define (LegendreP′ n x) + (* (/ n (- (* x x) 1)) + (- (* x (LegendreP n x)) + (LegendreP (- n 1) x)))) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-2.rkt b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-2.rkt new file mode 100644 index 0000000000..30c236a932 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-2.rkt @@ -0,0 +1,13 @@ +(define (LegendreP-root n i) + ; newton-raphson step + (define (newton-step x) + (- x (/ (LegendreP n x) (LegendreP′ n x)))) + ; initial guess + (define x0 (cos (* pi (/ (- i 1/4) (+ n 1/2))))) + ; computation of a root with relative accuracy 1e-15 + (if (< (abs x0) 1e-15) + 0 + (let next ([x′ (newton-step x0)] [x x0]) + (if (< (abs (/ (- x′ x) (+ x′ x))) 1e-15) + x′ + (next (newton-step x′) x′))))) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-3.rkt b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-3.rkt new file mode 100644 index 0000000000..77f1c20771 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-3.rkt @@ -0,0 +1,16 @@ +(define (Gauss-Legendre-quadrature n) + ;; positive roots + (define roots + (for/list ([i (in-range (floor (/ n 2)))]) + (LegendreP-root n (+ i 1)))) + ;; weights for positive roots + (define weights + (for/list ([x (in-list roots)]) + (/ 2 (- 1 (sqr x)) (sqr (LegendreP′ n x))))) + ;; all roots and weights + (values (append (map - roots) + (if (odd? n) (list 0) '()) + (reverse roots)) + (append weights + (if (odd? n) (list (/ 2 (sqr (LegendreP′ n 0)))) '()) + (reverse weights)))) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-4.rkt b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-4.rkt new file mode 100644 index 0000000000..fe6a9fe579 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-4.rkt @@ -0,0 +1,6 @@ +(define (integrate f a b #:nodes (n 5)) + (define m (/ (+ a b) 2)) + (define d (/ (- b a) 2)) + (define-values [x w] (Gauss-Legendre-quadrature n)) + (define (g x) (f (+ m (* d x)))) + (* d (+ (apply + (map * w (map g x)))))) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-5.rkt b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-5.rkt new file mode 100644 index 0000000000..1117cf29f9 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-5.rkt @@ -0,0 +1,9 @@ +> (Gauss-Legendre-quadrature 5) +'(-0.906179845938664 -0.5384693101056831 0 0.5384693101056831 0.906179845938664) +'(0.23692688505618875 0.47862867049936625 128/225 0.47862867049936625 0.23692688505618875) + +> (integrate exp -3 3) +20.035577718385547 + +> (- (exp 3) (exp -3) +20.035749854819805 diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-6.rkt b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-6.rkt new file mode 100644 index 0000000000..d7e8c064ef --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Racket/numerical-integration-gauss-legendre-quadrature-6.rkt @@ -0,0 +1,8 @@ +> (require plot) +> (parameterize ([plot-x-label "Number of Gaussian nodes"] + [plot-y-label "Integration error"] + [plot-y-transform log-transform] + [plot-y-ticks (log-ticks #:base 10)]) + (plot (points (for/list ([n (in-range 2 11)]) + (list n (abs (- (integrate exp -3 3 #:nodes n) + (- (exp 3) (exp -3))))))))) diff --git a/Task/Numerical-integration/Factor/numerical-integration.factor b/Task/Numerical-integration/Factor/numerical-integration.factor new file mode 100644 index 0000000000..55559a4a3c --- /dev/null +++ b/Task/Numerical-integration/Factor/numerical-integration.factor @@ -0,0 +1,12 @@ +USE: math.functions +IN: scratchpad 0 1 [ 3 ^ ] integrate-simpson . +1/4 +IN: scratchpad 1000 num-steps set-global +IN: scratchpad 1.0 100 [ -1 ^ ] integrate-simpson . +4.605173316272971 +IN: scratchpad 5000000 num-steps set-global +IN: scratchpad 0 5000 [ ] integrate-simpson . +12500000 +IN: scratchpad 6000000 num-steps set-global +IN: scratchpad 0 6000 [ ] integrate-simpson . +18000000 diff --git a/Task/Numerical-integration/Racket/numerical-integration-1.rkt b/Task/Numerical-integration/Racket/numerical-integration-1.rkt new file mode 100644 index 0000000000..7a115aa920 --- /dev/null +++ b/Task/Numerical-integration/Racket/numerical-integration-1.rkt @@ -0,0 +1,23 @@ +#lang racket +(define (integrate f a b steps meth) + (define h (/ (- b a) steps)) + (* h (for/sum ([i steps]) + (meth f (+ a (* h i)) h)))) + +(define (left-rect f x h) (f x)) +(define (mid-rect f x h) (f (+ x (/ h 2)))) +(define (right-rect f x h)(f (+ x h))) +(define (trapezium f x h) (/ (+ (f x) (f (+ x h))) 2)) +(define (simpson f x h) (/ (+ (f x) (* 4 (f (+ x (/ h 2)))) (f (+ x h))) 6)) + +(define (test f a b s n) + (displayln n) + (for ([meth (list left-rect mid-rect right-rect trapezium simpson)] + [name '( left-rect mid-rect right-rect trapezium simpson)]) + (displayln (~a name ":\t" (integrate f a b s meth)))) + (newline)) + +(test (λ(x) (* x x x)) 0. 1. 100 "CUBED") +(test (λ(x) (/ x)) 1. 100. 1000 "RECIPROCAL") +(test (λ(x) x) 0. 5000. 5000000 "IDENTITY") +(test (λ(x) x) 0. 6000. 6000000 "IDENTITY") diff --git a/Task/Numerical-integration/Racket/numerical-integration-2.rkt b/Task/Numerical-integration/Racket/numerical-integration-2.rkt new file mode 100644 index 0000000000..12c9d1b1e5 --- /dev/null +++ b/Task/Numerical-integration/Racket/numerical-integration-2.rkt @@ -0,0 +1,27 @@ +CUBED +left-rect: 0.24502500000000005 +mid-rect: 0.24998750000000006 +right-rect: 0.25502500000000006 +trapezium: 0.250025 +simpson: 0.25 + +RECIPROCAL +left-rect: 4.65499105751468 +mid-rect: 4.604762548678376 +right-rect: 4.55698105751468 +trapezium: 4.605986057514676 +simpson: 4.605170384957133 + +IDENTITY +left-rect: 12499997.5 +mid-rect: 12500000.0 +right-rect: 12500002.5 +trapezium: 12500000.0 +simpson: 12500000.0 + +IDENTITY +left-rect: 17999997.000000004 +mid-rect: 17999999.999999993 +right-rect: 18000003.000000004 +trapezium: 17999999.999999993 +simpson: 17999999.999999993 diff --git a/Task/Object-serialization/Cache-ObjectScript/object-serialization-1.cos b/Task/Object-serialization/Cache-ObjectScript/object-serialization-1.cos new file mode 100644 index 0000000000..b63b4b1aa4 --- /dev/null +++ b/Task/Object-serialization/Cache-ObjectScript/object-serialization-1.cos @@ -0,0 +1,26 @@ +Class Serialize.Employee Extends %SerialObject +{ + +Method %OnNew(ByRef pId As %Integer = 0, pDepartment As %String, pName As %String) As %Status +{ + Do ..IDSet(pId) + Set pId=pId+1 + Do ..DepartmentSet(pDepartment) + Do ..NameSet(pName) + Quit $$$OK +} + +Method Print() +{ + Write "[", ..%ClassName(), "]", ! + Write "- ID: "_..IDGet(), ! + Write "- Name: "_..NameGet(), ! + Write "- Department: "_..DepartmentGet(), ! + Quit +} + +Property ID As %Integer [ Private ]; +Property Name As %String [ Private ]; +Property Department As %String [ Private ]; + +} diff --git a/Task/Object-serialization/Cache-ObjectScript/object-serialization-2.cos b/Task/Object-serialization/Cache-ObjectScript/object-serialization-2.cos new file mode 100644 index 0000000000..d69d7e76d4 --- /dev/null +++ b/Task/Object-serialization/Cache-ObjectScript/object-serialization-2.cos @@ -0,0 +1,25 @@ +Class Serialize.Worker Extends Employee +{ + +Method %OnNew(ByRef pId As %Integer = 0, pDepartment As %String, pName As %String, pHourlyPay As %Numeric) As %Status +{ + Do ..HourlyPaySet(pHourlyPay) + Quit ##super(.pId, pDepartment, pName) +} + +Method Print() +{ + Do ##super() + Write "- Hourly Pay: ", $FNumber(..HourlyPayGet(), ",", 2), ! + Quit +} + +Method HourlyPaySet(pHourlyPay As %Numeric) As %Status [ ServerOnly = 1 ] +{ + Set i%HourlyPay=$Select(pHourlyPay<0: 0, 1: pHourlyPay) + Quit $$$OK +} + +Property HourlyPay As %Numeric [ Private ]; + +} diff --git a/Task/Object-serialization/Cache-ObjectScript/object-serialization-3.cos b/Task/Object-serialization/Cache-ObjectScript/object-serialization-3.cos new file mode 100644 index 0000000000..e59157f732 --- /dev/null +++ b/Task/Object-serialization/Cache-ObjectScript/object-serialization-3.cos @@ -0,0 +1,59 @@ +Class Serialize.Example Extends %SerialObject +{ + +ClassMethod Main() +{ + Do ..Save("/temp/objects.dat") + Do ..Load("/temp/objects.dat") + Quit +} + +ClassMethod Save(pFilename As %String) +{ + // creating objects of base class + Set emp1 = ##class(Employee).%New(.id, "Maintenance", "Fritz Schmalstieg") + Set emp2 = ##class(Employee).%New(.id, "Maintenance", "John Berry") + Set emp3 = ##class(Employee).%New(.id, "Repair", "Pawel Lichatschow") + Set emp4 = ##class(Employee).%New(.id, "IT", "Marian Niculescu") + + // creating objects of derived class + Set worker1 = ##class(Worker).%New(.id, "Maintenance", "Laurent Le Chef", 20) + Set worker2 = ##class(Worker).%New(.id, "IT", "Srinivan Taraman", 55.35) + + // put objects into collections + Set example = ..%New() + Set sc = example.Employees.Insert(emp1) + Set sc = example.Employees.Insert(emp2) + Set sc = example.Employees.Insert(emp3) + Set sc = example.Employees.Insert(emp4) + Set sc = example.Workers.Insert(worker1) + Set sc = example.Workers.Insert(worker2) + + // serialize the data and save to a file + Set sc=example.%GetSwizzleObject(,.oid) + Set fs=##class(%Stream.FileBinary).%New() + Set fs.Filename=pFilename + Set sc=fs.Write(oid) + Set sc=fs.%Save() + Quit +} + +ClassMethod Load(pFilename As %String) +{ + // read serialized data from file + Set fs=##class(%Stream.FileBinary).%New() + Set fs.Filename=pFilename + Set oid=fs.Read(.len, .sc) + + // open the example object + Set example = ..%Open(oid,, .sc) + Do example.Employees.GetAt(1).Print() + Do example.Employees.GetAt(3).Print() + Do example.Workers.GetAt(2).Print() + Quit +} + +Property Employees As list Of Employee; +Property Workers As list Of Worker; + +} diff --git a/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata.rkt b/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata.rkt new file mode 100644 index 0000000000..ee459876fa --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata.rkt @@ -0,0 +1,27 @@ +#lang racket + +(define (update cells) + (for/list ([crowding (map + + (append '(0) (drop-right cells 1)) + cells + (append (drop cells 1) '(0)))]) + (if (= 2 crowding) 1 0))) + +(define (life-of cells time) + (unless (zero? time) + (displayln cells) + (life-of (update cells) (sub1 time)))) + +(life-of '(0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0) + 10) + +#| (0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0) + (0 1 0 1 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0) + (0 0 1 1 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0) + (0 0 1 1 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0 0) + (0 0 1 1 0 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0) + (0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0) + (0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0) + (0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0) + (0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) + (0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) |# diff --git a/Task/One-of-n-lines-in-a-file/Racket/one-of-n-lines-in-a-file.rkt b/Task/One-of-n-lines-in-a-file/Racket/one-of-n-lines-in-a-file.rkt new file mode 100644 index 0000000000..1699eb967f --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Racket/one-of-n-lines-in-a-file.rkt @@ -0,0 +1,63 @@ +#lang racket + +(define (one-of-n n) + (for/fold ([n 0]) ([i (in-range 1 n)]) + (if (zero? (random (add1 i))) i n))) + +(define (try n times) + (define rs (make-vector n 0)) + (for ([i (in-range times)]) + (define r (one-of-n n)) + (vector-set! rs r (add1 (vector-ref rs r)))) + (vector->list rs)) + +(define TIMES 1000000) +(for ([n (in-range 1 21)]) + (define rs (try n TIMES)) + (printf "~a: ~a\n ~a\n" (~a #:width 2 n) rs + (map (lambda (r) (~a (round (/ r TIMES 1/100)) "%")) rs))) + +#| Sample Run: + +1 : (1000000) + (100%) +2 : (499702 500298) + (50% 50%) +3 : (332426 333314 334260) + (33% 33% 33%) +4 : (249925 250083 249695 250297) + (25% 25% 25% 25%) +5 : (200304 199798 199920 199983 199995) + (20% 20% 20% 20% 20%) +6 : (166276 167085 165955 166792 167143 166749) + (17% 17% 17% 17% 17% 17%) +7 : (142067 143242 142749 142997 143248 142746 142951) + (14% 14% 14% 14% 14% 14% 14%) +8 : (125026 125187 125214 124770 124785 125141 125039 124838) + (13% 13% 13% 12% 12% 13% 13% 12%) +9 : (111551 111013 110741 111292 111105 110627 110570 111685 111416) + (11% 11% 11% 11% 11% 11% 11% 11% 11%) +10: (100322 100031 100176 100590 99799 99892 100305 99955 99493 99437) + (10% 10% 10% 10% 10% 10% 10% 10% 10% 10%) +11: (91237 90706 90962 90901 90872 91002 91164 90967 90092 90706 91391) + (9% 9% 9% 9% 9% 9% 9% 9% 9% 9% 9%) +12: (83046 83556 83003 84128 83264 83305 83093 83202 83430 83605 83276 83092) + (8% 8% 8% 8% 8% 8% 8% 8% 8% 8% 8% 8%) +13: (77282 76936 76667 76659 76771 76736 77165 77190 77341 76469 76985 76942 76857) + (8% 8% 8% 8% 8% 8% 8% 8% 8% 8% 8% 8% 8%) +14: (71389 71496 71141 71314 71670 72062 71979 71361 71198 71457 70854 71686 71300 71093) + (7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7%) +15: (66534 66571 66072 66977 66803 66894 67076 66409 66306 67222 66590 66780 66341 66680 66745) + (7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7% 7%) +16: (62155 62496 62846 62136 62447 62714 62228 62454 62527 62577 62775 62692 62491 62231 62460 62771) + (6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6%) +17: (58852 59046 58726 58782 58979 58725 59051 58935 58910 59082 58567 58863 58625 58922 58648 58456 58831) + (6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6%) +18: (55204 55683 55547 55492 55671 55467 55801 55704 55235 55411 55482 55387 55679 55557 55398 55649 55815 55818) + (6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6% 6%) +19: (52564 52283 52918 52363 52316 52511 52500 53042 52594 52720 52577 52623 52762 53047 52798 52832 52267 52550 52733) + (5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5%) +20: (50107 50008 49786 50128 50431 49905 50109 49781 50099 50117 49772 50128 49721 49937 49735 50067 49865 50155 50231 49918) + (5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5% 5%) + +|# diff --git a/Task/OpenGL/BBC-BASIC/opengl.bbc b/Task/OpenGL/BBC-BASIC/opengl.bbc index 69866fae81..93aa1cc58a 100644 --- a/Task/OpenGL/BBC-BASIC/opengl.bbc +++ b/Task/OpenGL/BBC-BASIC/opengl.bbc @@ -27,7 +27,7 @@ ON CLOSE PROCcleanup : QUIT ON ERROR PROCcleanup : SYS "MessageBox", @hwnd%, REPORT$, 0, 48 : QUIT - DIM GLcolor{r, g, b}, GLvertex{x, y} + DIM GLcolor{r#, g#, b#}, GLvertex{x#, y#} DIM pfd{nSize{l&,h&}, nVersion{l&,h&}, dwFlags%, iPixelType&, cColorBits&, \ \ cRedBits&, cRedShift&, cGreenBits&, cGreenShift&, cBlueBits&, cBlueShift&, \ \ cAlphaBits&, cAlphaShift&, cAccumBits&, cAccumRedBits&, cAccumGreenBits&, \ @@ -58,17 +58,17 @@ WAIT 2 SYS `glClear`, GL_COLOR_BUFFER_BIT OR GL_DEPTH_BUFFER_BIT SYS `glBegin`, GL_TRIANGLES - GLcolor.r = 1.0 : GLcolor.g = 0.0 : GLcolor.b = 0.0 + GLcolor.r# = 1.0 : GLcolor.g# = 0.0 : GLcolor.b# = 0.0 SYS `glColor3dv`, GLcolor{} - GLvertex.x = 0.0 : GLvertex.y = 0.8 + GLvertex.x# = 0.0 : GLvertex.y# = 0.8 SYS `glVertex2dv`, GLvertex{} - GLcolor.r = 0.0 : GLcolor.g = 1.0 : GLcolor.b = 0.0 + GLcolor.r# = 0.0 : GLcolor.g# = 1.0 : GLcolor.b# = 0.0 SYS `glColor3dv`, GLcolor{} - GLvertex.x = 0.8 : GLvertex.y = -0.8 + GLvertex.x# = 0.8 : GLvertex.y# = -0.8 SYS `glVertex2dv`, GLvertex{} - GLcolor.r = 0.0 : GLcolor.g = 0.0 : GLcolor.b = 1.0 + GLcolor.r# = 0.0 : GLcolor.g# = 0.0 : GLcolor.b# = 1.0 SYS `glColor3dv`, GLcolor{} - GLvertex.x = -0.8 : GLvertex.y = -0.8 + GLvertex.x# = -0.8 : GLvertex.y# = -0.8 SYS `glVertex2dv`, GLvertex{} SYS `glEnd` SYS "SwapBuffers", ghDC% diff --git a/Task/OpenGL/Racket/opengl.rkt b/Task/OpenGL/Racket/opengl.rkt index 7c43c2f773..88bfbbea89 100644 --- a/Task/OpenGL/Racket/opengl.rkt +++ b/Task/OpenGL/Racket/opengl.rkt @@ -1,4 +1,4 @@ - #lang racket/gui +#lang racket/gui (require sgl/gl) (define (resize w h) @@ -29,21 +29,14 @@ (define my-canvas% (class* canvas% () (inherit with-gl-context swap-gl-buffers) - - (define/override (on-paint) - (with-gl-context - (lambda () - (draw-opengl) - (swap-gl-buffers)))) - + (define/override (on-paint) + (with-gl-context (λ() (draw-opengl) (swap-gl-buffers)))) (define/override (on-size width height) - (with-gl-context - (lambda () - (resize width height)))) - + (with-gl-context (λ() (resize width height)))) (super-instantiate () (style '(gl))))) -(define win (new frame% (label "Racket Rosetta Code OpenGL example") (min-width 200) (min-height 200))) -(define gl (new my-canvas% (parent win))) +(define win (new frame% [label "Racket Rosetta Code OpenGL example"] + [min-width 200] [min-height 200])) +(define gl (new my-canvas% [parent win])) (send win show #t) diff --git a/Task/Operator-precedence/Racket/operator-precedence.rkt b/Task/Operator-precedence/Racket/operator-precedence.rkt new file mode 100644 index 0000000000..71f77aa9b9 --- /dev/null +++ b/Task/Operator-precedence/Racket/operator-precedence.rkt @@ -0,0 +1 @@ +(function arguments ...) diff --git a/Task/Operator-precedence/Seed7/operator-precedence-1.seed7 b/Task/Operator-precedence/Seed7/operator-precedence-1.seed7 new file mode 100644 index 0000000000..ea9e162440 --- /dev/null +++ b/Task/Operator-precedence/Seed7/operator-precedence-1.seed7 @@ -0,0 +1 @@ +$ syntax expr: .(). + .() is -> 7; diff --git a/Task/Operator-precedence/Seed7/operator-precedence-2.seed7 b/Task/Operator-precedence/Seed7/operator-precedence-2.seed7 new file mode 100644 index 0000000000..985e37a096 --- /dev/null +++ b/Task/Operator-precedence/Seed7/operator-precedence-2.seed7 @@ -0,0 +1 @@ +.(). + .() diff --git a/Task/Optional-parameters/C/optional-parameters.c b/Task/Optional-parameters/C/optional-parameters.c index 5da69a17b3..d2c93f500c 100644 --- a/Task/Optional-parameters/C/optional-parameters.c +++ b/Task/Optional-parameters/C/optional-parameters.c @@ -20,8 +20,8 @@ struct { int CmprRows( const void *aa, const void *bb) { - String *rA = *(String **)aa; - String *rB = *(String **)bb; + String *rA = *(String *const *)aa; + String *rB = *(String *const *)bb; int sortCol = sortSpec.column; String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol]; @@ -66,7 +66,7 @@ int sortTable(Table tbl, const char* argSpec,... ) } } va_end(vl); - qsort( tbl->rows, tbl->n_rows, sizeof(String *), &CmprRows); + qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows); return 0; } diff --git a/Task/Optional-parameters/REXX/optional-parameters-1.rexx b/Task/Optional-parameters/REXX/optional-parameters-1.rexx new file mode 100644 index 0000000000..cb275c1729 --- /dev/null +++ b/Task/Optional-parameters/REXX/optional-parameters-1.rexx @@ -0,0 +1,19 @@ +sortStrings: procedure expose @. /*stemmed array is named: @. */ +col=1; reverse='NO'; order='LEXICOGRAPHIC' /*set the defaults.*/ +arg options + do j=1 for words(options); x=word(options,j) + + select + when datatype(x,'W') then col=x/1 + when pos('=',x)==0 then order=x + otherwise parse var x nam '=' value + end /*select*/ + end /*j*/ + + /*check for errors here: COL isn't positive, */ + /* REVERSE value isn't NO or YES, */ + /* ORDER value is recognized ... */ + +... main body of string sort here ... + +return diff --git a/Task/Optional-parameters/REXX/optional-parameters-2.rexx b/Task/Optional-parameters/REXX/optional-parameters-2.rexx new file mode 100644 index 0000000000..9752ea399f --- /dev/null +++ b/Task/Optional-parameters/REXX/optional-parameters-2.rexx @@ -0,0 +1,4 @@ +/*REXX example to use the SortStrings subroutine with optional args. */ + /*...define array (@.nnn) of strings here...*/ +call sortStrings 'Reverse=no' 3 + /*stick a fork in it, we're done.*/ diff --git a/Task/Order-two-numerical-lists/Erlang/order-two-numerical-lists.erl b/Task/Order-two-numerical-lists/Erlang/order-two-numerical-lists.erl new file mode 100644 index 0000000000..b1b93523ea --- /dev/null +++ b/Task/Order-two-numerical-lists/Erlang/order-two-numerical-lists.erl @@ -0,0 +1,4 @@ +5> [1,2,3] < [1,2,3,4]. +true +6> [1,2,3] < [1,2,4]. +true diff --git a/Task/Order-two-numerical-lists/REXX/order-two-numerical-lists.rexx b/Task/Order-two-numerical-lists/REXX/order-two-numerical-lists.rexx new file mode 100644 index 0000000000..0310dde5e3 --- /dev/null +++ b/Task/Order-two-numerical-lists/REXX/order-two-numerical-lists.rexx @@ -0,0 +1,19 @@ +/*REXX pgm finds if list1 #f diff --git a/Task/Order-two-numerical-lists/Seed7/order-two-numerical-lists.seed7 b/Task/Order-two-numerical-lists/Seed7/order-two-numerical-lists.seed7 new file mode 100644 index 0000000000..7b6eb694eb --- /dev/null +++ b/Task/Order-two-numerical-lists/Seed7/order-two-numerical-lists.seed7 @@ -0,0 +1,13 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + begin + writeln([] (1) < [] (1, 2)); # If the first list runs out of elements the result is TRUE. + writeln([] (1, 2) < [] (1)); # If the second list runs out of elements the result is FALSE. + writeln([] (1, 2) < [] (1, 2)); # If both lists run out of elements the result is FALSE. + writeln([] (1, 2, 3) < [] (1, 1, 3)); # The second element is greater than --> FALSE + writeln([] (1, 2, 3) < [] (1, 3, 3)); # The second element is less than --> TRUE + writeln(0 times 0 < [] (1)); # The empty list is less than any nonempty list --> TRUE + writeln([] (1) < 0 times 0); # Any nonempty list is not less than the empty list --> FALSE + writeln(0 times 0 < 0 times 0); # The empty list is not less than the empty list --> FALSE + end func; diff --git a/Task/Ordered-Partitions/Racket/ordered-partitions.rkt b/Task/Ordered-Partitions/Racket/ordered-partitions.rkt new file mode 100644 index 0000000000..9bfa8a4429 --- /dev/null +++ b/Task/Ordered-Partitions/Racket/ordered-partitions.rkt @@ -0,0 +1,23 @@ +#lang racket +(define (comb k xs) + (cond [(zero? k) (list (cons '() xs))] + [(null? xs) '()] + [else (append (for/list ([cszs (comb (sub1 k) (cdr xs))]) + (cons (cons (car xs) (car cszs)) (cdr cszs))) + (for/list ([cszs (comb k (cdr xs))]) + (cons (car cszs) (cons (car xs) (cdr cszs)))))])) +(define (partitions xs) + (define (p xs ks) + (if (null? ks) + '(()) + (for*/list ([cszs (comb (car ks) xs)] [rs (p (cdr cszs) (cdr ks))]) + (cons (car cszs) rs)))) + (p (range 1 (add1 (foldl + 0 xs))) xs)) + +(define (run . xs) + (printf "partitions~s:\n" xs) + (for ([x (partitions xs)]) (printf " ~s\n" x)) + (newline)) + +(run 2 0 2) +(run 1 1 1) diff --git a/Task/Ordered-words/Aime/ordered-words.aime b/Task/Ordered-words/Aime/ordered-words.aime new file mode 100644 index 0000000000..b2b9abdb6c --- /dev/null +++ b/Task/Ordered-words/Aime/ordered-words.aime @@ -0,0 +1,57 @@ +integer +ordered(text s) +{ + integer a, i, l; + + a = 1; + + l = length(s); + if (l) { + l -= 1; + i = 0; + while (i < l) { + if (character(s, i + 1) < character(s, i)) { + a = 0; + break; + } + i += 1; + } + } + + return a; +} + +integer +main(void) +{ + integer l, m; + file f; + list w; + text s; + + f_affix(f, "unixdict.txt"); + + m = 0; + + while ((l = f_line(f, s)) != -1) { + if (m <= l) { + if (ordered(s)) { + if (m < l) { + m = l; + l_clear(w); + } + l_append(w, s); + } + } + } + + l = l_length(w); + m = 0; + while (m < l) { + o_text(l_q_text(w, m)); + o_byte('\n'); + m += 1; + } + + return 0; +} diff --git a/Task/Ordered-words/D/ordered-words-3.d b/Task/Ordered-words/D/ordered-words-3.d index 214bcb7611..d13e4d9258 100644 --- a/Task/Ordered-words/D/ordered-words-3.d +++ b/Task/Ordered-words/D/ordered-words-3.d @@ -1,7 +1,7 @@ import std.stdio, std.algorithm, std.range, std.file, std.string; void main() { - auto ws = "unixdict.txt".readText().split().filter!isSorted(); - immutable maxLen = ws.map!walkLength().reduce!max(); - writefln("%-(%s\n%)", ws.filter!(w => w.length == maxLen)()); + auto words = "unixdict.txt".readText.split.filter!isSorted; + immutable maxLen = words.map!q{a.length}.reduce!max; + writefln("%-(%s\n%)", words.filter!(w => w.length == maxLen)); } diff --git a/Task/Ordered-words/FBSL/ordered-words.fbsl b/Task/Ordered-words/FBSL/ordered-words.fbsl new file mode 100644 index 0000000000..d9b4b75d0d --- /dev/null +++ b/Task/Ordered-words/FBSL/ordered-words.fbsl @@ -0,0 +1,33 @@ +#APPTYPE CONSOLE + +FUNCTION RESTfulGET(url) + DIM %HTTP = CREATEOBJECT("WinHttp.WinHttpRequest.5.1") + CALLMETHOD(HTTP, ".open %s, %s, %d", "GET", url, FALSE) + CALLMETHOD(HTTP, ".send") + RETURN GETVALUE("%s", HTTP, ".ResponseText") +END FUNCTION + +DIM $TEXT = RESTfulGET("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +DIM dict[] = Split(TEXT, CHR(10)) +DIM max AS INTEGER = UBOUND(dict) +DIM theword AS STRING +DIM words[] +FOR DIM i = 0 TO max + theWord = dict[i] + IF isOrdered(theWord) THEN + words[LEN(theWord)] = words[LEN(theWord)] & " " & theWord + END IF +NEXT + +PRINT words[UBOUND(words)] + +PAUSE + +FUNCTION isOrdered(s) + FOR DIM i = 1 TO LEN(s) - 1 + IF s{i} > s{i + 1} THEN + RETURN FALSE + END IF + NEXT + RETURN TRUE +END FUNCTION diff --git a/Task/Ordered-words/Factor/ordered-words.factor b/Task/Ordered-words/Factor/ordered-words.factor index 48bbe157c6..1bc37cd630 100644 --- a/Task/Ordered-words/Factor/ordered-words.factor +++ b/Task/Ordered-words/Factor/ordered-words.factor @@ -1,19 +1,17 @@ -USING: fry grouping io io.encodings.utf8 io.files kernel math -math.order sequences unicode.case ; -IN: ordered-words +USING: grouping http.client io io.encodings.utf8 io.files +io.files.temp kernel math memoize sequences sequences.extras +unicode.case urls ; +IN: rosetta-code.ordered-words -CONSTANT: dict-file "vocab:ordered-words/unixdict.txt" - -: word-list ( -- seq ) - dict-file utf8 file-lines ; +MEMO: word-list ( -- seq ) + "unixdict.txt" temp-file dup exists? [ + URL" http://puzzlers.org/pub/wordlists/unixdict.txt" + over download-to + ] unless utf8 file-lines ; : ordered-word? ( word -- ? ) - >lower 2 [ first2 <= ] all? ; + >lower [ <= ] monotonic? ; -: filter-longest-words ( seq -- seq' ) - dup [ length ] [ max ] map-reduce - '[ length _ = ] filter ; - -: main ( -- ) +: ordered-words-main ( -- ) word-list [ ordered-word? ] filter - filter-longest-words [ print ] each ; + all-longest [ print ] each ; diff --git a/Task/Ordered-words/Haskell/ordered-words-1.hs b/Task/Ordered-words/Haskell/ordered-words-1.hs index 9ea03dc4b4..2c266a620c 100644 --- a/Task/Ordered-words/Haskell/ordered-words-1.hs +++ b/Task/Ordered-words/Haskell/ordered-words-1.hs @@ -5,15 +5,13 @@ isOrdered wws@(_:ws) = and $ zipWith (<=) wws ws -keepLongest _ acc [] = acc -keepLongest max acc (w:ws) = - let len = length w in - case compare len max of - LT -> keepLongest max acc ws - EQ -> keepLongest max (w:acc) ws - GT -> keepLongest len [w] ws - -longestOrderedWords = reverse . keepLongest 0 [] . filter isOrdered +longestOrderedWords = reverse . snd . foldl f (0,[]) . filter isOrdered + where f (max, acc) w = + let len = length w in + case compare len max of + LT -> (max, acc) + EQ -> (max, w:acc) + GT -> (len, [w]) main = do str <- getContents diff --git a/Task/Ordered-words/Racket/ordered-words.rkt b/Task/Ordered-words/Racket/ordered-words.rkt new file mode 100644 index 0000000000..dfa09ec8c1 --- /dev/null +++ b/Task/Ordered-words/Racket/ordered-words.rkt @@ -0,0 +1,20 @@ +#lang racket +(require net/url) + +(define dict "http://www.puzzlers.org/pub/wordlists/unixdict.txt") + +(define (ordered? str) + (define lower (string-downcase str)) + (for/and ([i (in-range 1 (string-length str))]) + (char<=? (string-ref lower (sub1 i)) (string-ref lower i)))) + +(define words (port->lines (get-pure-port (string->url dict)))) + +(let loop ([len 0] [longs '()] [words words]) + (if (null? words) + (for-each displayln (reverse longs)) + (let* ([word (car words)] [words (cdr words)] + [wlen (string-length word)]) + (if (or (< wlen len) (not (ordered? word))) + (loop len longs words) + (loop wlen (cons word (if (> wlen len) '() longs)) words))))) diff --git a/Task/Ordered-words/Scala/ordered-words.scala b/Task/Ordered-words/Scala/ordered-words.scala new file mode 100644 index 0000000000..d46e33c771 --- /dev/null +++ b/Task/Ordered-words/Scala/ordered-words.scala @@ -0,0 +1,20 @@ +val wordsAll = scala.io.Source.fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.toSeq + +/** + * Given a sequence of words return a sub-sequence of the + * words that have characters in sorted order. + */ +def orderedWords( words:Seq[String] ) : Seq[(String)] = { + + def isOrdered( s:String ) : Boolean = + (s.foldLeft( (true,'@') ){ + case ((false,_),_) => return false + case ((true,prev),c) => ((prev <= c),c) + })._1 + + wordsAll.filter( isOrdered(_) ).toSeq +} + +val ww = orderedWords( wordsAll ).sortBy( -_.length ) + +println( ww.takeWhile( _.length == ww.head.length ).mkString("\n") ) diff --git a/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl b/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl new file mode 100644 index 0000000000..14134e8e70 --- /dev/null +++ b/Task/Palindrome-detection/FBSL/palindrome-detection-1.fbsl @@ -0,0 +1,27 @@ +#APPTYPE CONSOLE + +FUNCTION IsPalindrome(BYVAL s AS STRING) AS INTEGER + DIM sTemp AS STRING = LCASE(s) + DIM n AS INTEGER = 1, nLen = STRLEN(sTemp) + DO + IF n >= nLen THEN EXIT DO + IF sTemp{n} < "a" OR sTemp{n} > "z" THEN + sTemp = STRDEL(sTemp, n, 1) + nLen = STRLEN(sTemp) + ELSE + n = n + 1 + END IF + LOOP + + FOR DIM i = 1 TO STRLEN(sTemp) \ 2 ' only check half of the string, if scanning from both ends + IF sTemp{i} <> sTemp{STRLEN - (i - 1)} THEN RETURN FALSE + NEXT + + RETURN TRUE +END FUNCTION + +PRINT IsPalindrome("a toyota") +PRINT IsPalindrome("madam i'm adam") +PRINT IsPalindrome("the rain in Spain falls mainly on the rooftops") + +PAUSE diff --git a/Task/Palindrome-detection/FBSL/palindrome-detection-2.fbsl b/Task/Palindrome-detection/FBSL/palindrome-detection-2.fbsl new file mode 100644 index 0000000000..ffff75586d --- /dev/null +++ b/Task/Palindrome-detection/FBSL/palindrome-detection-2.fbsl @@ -0,0 +1 @@ +Outputs 1, 1, 0 respectively diff --git a/Task/Palindrome-detection/NetRexx/palindrome-detection.netrexx b/Task/Palindrome-detection/NetRexx/palindrome-detection.netrexx index 5465dd390d..7c8245ef51 100644 --- a/Task/Palindrome-detection/NetRexx/palindrome-detection.netrexx +++ b/Task/Palindrome-detection/NetRexx/palindrome-detection.netrexx @@ -12,5 +12,6 @@ if pal==0 then say "The string isn't palindromic." else say 'The string is palindromic.' method isPal(x) static - x=x.upper().space(0) /* removes all blanks (spaces). */ - return x==x.reverse() /* returns 1 if exactly equal, */ + x=x.upper().space(0) /* removes all blanks (spaces) */ + /* and translate to uppercase. */ + return x==x.reverse() /* returns 1 if exactly equal */ diff --git a/Task/Palindrome-detection/REXX/palindrome-detection.rexx b/Task/Palindrome-detection/REXX/palindrome-detection.rexx index d796068e5b..01c85ad9f1 100644 --- a/Task/Palindrome-detection/REXX/palindrome-detection.rexx +++ b/Task/Palindrome-detection/REXX/palindrome-detection.rexx @@ -1,17 +1,13 @@ -/*REXX program checks to see if a phrase is palindromic. */ - -y = 'In girum imus nocte et consumimur igni' - - /*translation: We walk around in the night and */ - /* we are burnt by the fire (of love). */ +/*REXX pgm checks if a phrase is palindromic (ignoring blanks and case).*/ +y = 'In girum imus nocte et consumimur igni' /* [↓] translation.*/ + /*We walk around in the night and we are burnt by the fire (of love).*/ say 'string = ' y say if isPal(y) then say 'The string is palindromic.' else say "The string isn't palindromic." exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────ISPAL subroutine────────────────────*/ isPal: procedure; arg x /*uppercases the value of arg X. */ -x = space(x,0) /*removes all blanks (spaces). */ +x=space(x,0) /*remove all blanks from the str.*/ return x==reverse(x) /*returns 1 if exactly equal, */ /* " 0 if not equal. */ diff --git a/Task/Pangram-checker/Racket/pangram-checker.rkt b/Task/Pangram-checker/Racket/pangram-checker.rkt new file mode 100644 index 0000000000..82a47d64eb --- /dev/null +++ b/Task/Pangram-checker/Racket/pangram-checker.rkt @@ -0,0 +1,5 @@ +#lang racket +(define (pangram? str) + (define chars (regexp-replace* #rx"[^a-z]+" (string-downcase str) "")) + (= 26 (length (remove-duplicates (string->list chars))))) +(pangram? "The quick Brown Fox jumps over the Lazy Dog") diff --git a/Task/Parallel-calculations/Racket/parallel-calculations-1.rkt b/Task/Parallel-calculations/Racket/parallel-calculations-1.rkt new file mode 100644 index 0000000000..a45676f93f --- /dev/null +++ b/Task/Parallel-calculations/Racket/parallel-calculations-1.rkt @@ -0,0 +1,25 @@ +#lang racket +(require math) +(provide main) + +(define (smallest-factor n) + (list (first (first (factorize n))) n)) + +(define numbers + '(112272537195293 112582718962171 112272537095293 + 115280098190773 115797840077099 1099726829285419)) + +(define (main) + ; create as many instances of Racket as + ; there are numbers: + (define ps + (for/list ([_ numbers]) + (place ch + (place-channel-put + ch + (smallest-factor + (place-channel-get ch)))))) + ; send the numbers to the instances: + (map place-channel-put ps numbers) + ; get the results and find the maximum: + (argmax first (map place-channel-get ps))) diff --git a/Task/Parallel-calculations/Racket/parallel-calculations-2.rkt b/Task/Parallel-calculations/Racket/parallel-calculations-2.rkt new file mode 100644 index 0000000000..faf2e5464b --- /dev/null +++ b/Task/Parallel-calculations/Racket/parallel-calculations-2.rkt @@ -0,0 +1,2 @@ +> (main) +'(544651 115797840077099) diff --git a/Task/Parsing-RPN-calculator-algorithm/Racket/parsing-rpn-calculator-algorithm-1.rkt b/Task/Parsing-RPN-calculator-algorithm/Racket/parsing-rpn-calculator-algorithm-1.rkt new file mode 100644 index 0000000000..5582ddd753 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Racket/parsing-rpn-calculator-algorithm-1.rkt @@ -0,0 +1,14 @@ +#lang racket + +(define (calculate-RPN expr) + (for/fold ([stack '()]) ([token expr]) + (printf "~a\t -> ~a~N" token stack) + (match* (token stack) + [((? number? n) s) (cons n s)] + [('+ (list x y s ___)) (cons (+ x y) s)] + [('- (list x y s ___)) (cons (- y x) s)] + [('* (list x y s ___)) (cons (* x y) s)] + [('/ (list x y s ___)) (cons (/ y x) s)] + [('^ (list x y s ___)) (cons (expt y x) s)] + [(x s) (error "calculate-RPN: Cannot calculate the expression:" + (reverse (cons x s)))]))) diff --git a/Task/Parsing-RPN-calculator-algorithm/Racket/parsing-rpn-calculator-algorithm-2.rkt b/Task/Parsing-RPN-calculator-algorithm/Racket/parsing-rpn-calculator-algorithm-2.rkt new file mode 100644 index 0000000000..759094282d --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Racket/parsing-rpn-calculator-algorithm-2.rkt @@ -0,0 +1 @@ +(calculate-RPN (in-port read (open-input-string "3.0 4 2 * 1 5 - 2 3 ^ ^ / +"))) diff --git a/Task/Parsing-RPN-to-infix-conversion/Racket/parsing-rpn-to-infix-conversion.rkt b/Task/Parsing-RPN-to-infix-conversion/Racket/parsing-rpn-to-infix-conversion.rkt new file mode 100644 index 0000000000..c2b57de6c6 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/Racket/parsing-rpn-to-infix-conversion.rkt @@ -0,0 +1,32 @@ +#lang racket +(require racket/dict) + +(define (RPN->infix expr) + (define-values (res _) + (for/fold ([stack '()] [prec '()]) ([t expr]) + (show t stack prec) + (cond + [(dict-has-key? operators t) + (match-define (list pt at) (dict-ref operators t)) + (match-define (list y x ss ...) stack) + (match-define (list py px ps ...) prec) + (define fexpr + (cond + [(> pt (max px py)) "(~a) ~a (~a)"] + [(or (< px pt) (and (= pt px) (eq? at 'r))) "(~a) ~a ~a"] + [(or (< py pt) (and (= pt py) (eq? at 'l))) "~a ~a (~a)"] + [else "~a ~a ~a"])) + (define term (format fexpr x t y)) + (values (cons term ss) (cons pt ps))] + [else (values (cons t stack) (cons +inf.0 prec))]))) + (car res)) + +;; the list of operators and their properties +(define operators '((+ 2 l) (- 2 l) (* 3 l) (/ 3 l) (^ 4 r))) + +;; printing out the intermediate stages +(define (show t stack prec) + (printf "~a\t" t) + (for ([s stack] [p prec]) + (if (eq? +inf.0 p) (printf "[~a] " s) (printf "[~a {~a}] " s p))) + (newline)) diff --git a/Task/Pascals-triangle/00DESCRIPTION b/Task/Pascals-triangle/00DESCRIPTION index f1c19926e7..fff12d4078 100644 --- a/Task/Pascals-triangle/00DESCRIPTION +++ b/Task/Pascals-triangle/00DESCRIPTION @@ -6,3 +6,6 @@ where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row would be 1 (since the first element of each row doesn't have two elements above it), 4 (1 + 3), 6 (3 + 3), 4 (3 + 1), and 1 (since the last element of each row doesn't have two elements above it). Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n. Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for n <= 0 does not need to be uniform, but should be noted. + +'''See also:''' +* [[Evaluate binomial coefficients]] diff --git a/Task/Pascals-triangle/D/pascals-triangle-2.d b/Task/Pascals-triangle/D/pascals-triangle-2.d index 0cad996a60..95120343a1 100644 --- a/Task/Pascals-triangle/D/pascals-triangle-2.d +++ b/Task/Pascals-triangle/D/pascals-triangle-2.d @@ -1,12 +1,11 @@ import std.stdio, std.algorithm, std.range; -auto pascal(in int n) /*pure nothrow*/ { - auto p = [[1]]; - foreach (_; 1 .. n) - p ~= zip(p[$-1] ~ 0, 0 ~ p[$-1]).map!q{a[0] + a[1]}().array(); - return p; +auto pascal() /*pure nothrow*/ { + return [1].recurrence!q{ zip(a[n - 1] ~ 0, 0 ~ a[n - 1]) + .map!q{a[0] + a[1]} + .array }; } void main() { - writeln(pascal(5)); + pascal.take(5).writeln; } diff --git a/Task/Pattern-matching/Racket/pattern-matching.rkt b/Task/Pattern-matching/Racket/pattern-matching.rkt index 72aed6ecfe..8596084821 100644 --- a/Task/Pattern-matching/Racket/pattern-matching.rkt +++ b/Task/Pattern-matching/Racket/pattern-matching.rkt @@ -1,28 +1,32 @@ #lang racket -(struct t-node (color t-left value t-right)) +;; Using short names to make the code line up nicely +(struct N (color left value right) #:prefab) (define (balance t) (match t - [(t-node 'black (t-node 'red (t-node 'red a x b) y c) z d) - (t-node 'red (t-node 'black a x b) y (t-node 'black c z d))] - [(t-node 'black (t-node 'red a x (t-node 'red b y c)) z d) - (t-node 'red (t-node 'black a x b) y (t-node 'black c z d))] - [(t-node 'black a x (t-node 'red (t-node 'red b y c) z d)) - (t-node 'red (t-node 'black a x b) y (t-node 'black c z d))] - [(t-node 'black a x (t-node 'red b y (t-node 'red c z d))) - (t-node 'red (t-node 'black a x b) y (t-node 'black c z d))] + [(N 'B (N 'R (N 'R a x b) y c) z d) (N 'R (N 'B a x b) y (N 'B c z d))] + [(N 'B (N 'R a x (N 'R b y c)) z d) (N 'R (N 'B a x b) y (N 'B c z d))] + [(N 'B a x (N 'R (N 'R b y c) z d)) (N 'R (N 'B a x b) y (N 'B c z d))] + [(N 'B a x (N 'R b y (N 'R c z d))) (N 'R (N 'B a x b) y (N 'B c z d))] [else t])) (define (insert x s) (define (ins t) (match t - ['empty (t-node 'red 'empty x 'empty)] - [(t-node c a y b) - (cond [(< x y) - (balance (t-node c (ins a) y b))] - [(> x y) - (balance (t-node c a y (ins b)))] - [else t])])) - (match (ins s) - [(t-node _ a y b) (t-node 'black a y b)])) + ['empty (N 'R 'empty x 'empty)] + [(N c l v r) (cond [(< x v) (balance (N c (ins l) v r))] + [(> x v) (balance (N c l v (ins r)))] + [else t])])) + (match (ins s) [(N _ l v r) (N 'B l v r)])) + +(define (visualize t0) + (let loop ([t t0] [last? #t] [indent '()]) + (define (I mid last) (cond [(eq? t t0) ""] [last? mid] [else last])) + (for-each display (reverse indent)) + (printf "~a~a[~a]\n" (I "\\-" "+-") (N-value t) (N-color t)) + (define subs (filter N? (list (N-left t) (N-right t)))) + (for ([s subs] [n (in-range (sub1 (length subs)) -1 -1)]) + (loop s (zero? n) (cons (I " " "| ") indent))))) + +(visualize (for/fold ([t 'empty]) ([i 16]) (insert i t))) diff --git a/Task/Percentage-difference-between-images/Racket/percentage-difference-between-images.rkt b/Task/Percentage-difference-between-images/Racket/percentage-difference-between-images.rkt new file mode 100644 index 0000000000..ba820093a0 --- /dev/null +++ b/Task/Percentage-difference-between-images/Racket/percentage-difference-between-images.rkt @@ -0,0 +1,22 @@ +#lang racket +(require racket/draw) + +(define (percentage-difference bitmap1 bitmap2) + (define width (send bitmap1 get-width)) + (define height (send bitmap1 get-height)) + (define buffer1 (make-bytes (* width height 4))) + (define buffer2 (make-bytes (* width height 4))) + (send (send bitmap1 make-dc) get-argb-pixels 0 0 width height buffer1) + (send (send bitmap2 make-dc) get-argb-pixels 0 0 width height buffer2) + (/ (* 100.0 + (for/fold ((difference 0)) + ((i (in-naturals)) (x1 (in-bytes buffer1)) (x2 (in-bytes buffer2))) + (if (zero? (remainder i 4)) + difference + (+ difference (abs (- x1 x2)))))) + width height 3 256)) + +(define lenna50 (read-bitmap "lenna50.jpg")) +(define lenna100 (read-bitmap "lenna100.jpg")) + +(percentage-difference lenna50 lenna100) ;-> 1.7749329408009846 diff --git a/Task/Perfect-numbers/Racket/perfect-numbers.rkt b/Task/Perfect-numbers/Racket/perfect-numbers.rkt new file mode 100644 index 0000000000..65cfc2a025 --- /dev/null +++ b/Task/Perfect-numbers/Racket/perfect-numbers.rkt @@ -0,0 +1,12 @@ +#lang racket +(define (perfect? n) + (= n + (for/fold ((sum 0)) + ((i (in-range 1 (add1 (floor (/ n 2)))))) + (if (= (remainder n i) 0) + (+ sum i) + sum)))) + + +(filter perfect? (build-list 1000 values)) +;-> '(0 6 28 496) diff --git a/Task/Permutation-test/D/permutation-test-1.d b/Task/Permutation-test/D/permutation-test-1.d new file mode 100644 index 0000000000..a164c38353 --- /dev/null +++ b/Task/Permutation-test/D/permutation-test-1.d @@ -0,0 +1,18 @@ +import std.stdio, std.algorithm, std.array, combinations3; + +alias sum = reduce!q{a + b}; + +auto permutationTest(T)(in T[] a, in T[] b) /*pure nothrow*/ { + immutable tObs = a.sum; + //auto combs = combinations!false(a ~ b, a.length); // Not a Range. + const combs = combinations(a ~ b, a.length).array; // Slow. + immutable under = combs.count!(perm => perm.sum <= tObs); + return under * 100.0 / combs.length; +} + +void main() { + immutable treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]; + immutable controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]; + immutable under = permutationTest(treatmentGroup, controlGroup); + writefln("Under =%6.2f%%\nOver =%6.2f%%", under, 100.0 - under); +} diff --git a/Task/Permutation-test/D/permutation-test-2.d b/Task/Permutation-test/D/permutation-test-2.d new file mode 100644 index 0000000000..ac8ee0a984 --- /dev/null +++ b/Task/Permutation-test/D/permutation-test-2.d @@ -0,0 +1,24 @@ +import std.stdio, std.algorithm, std.range; + +void main() { + immutable treatment = [85, 88, 75, 66, 25, 29, 83, 39, 97]; + immutable control = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]; + immutable both = treatment ~ control; + immutable sTreat = treatment.reduce!q{a + b}; + + T pick(T)(in size_t at, in size_t remain, in T accu) pure nothrow { + if (remain == 0) + return accu > sTreat; + + return pick(at - 1, remain - 1, accu + both[at - 1]) + + (at > remain ? pick(at - 1, remain, accu) : 0); + } + + alias mul = reduce!q{a * b}; + immutable t = mul(1.0, iota(both.length, treatment.length + 1, -1)) + .reduce!q{a / b}(iota(treatment.length, 0, -1)); + immutable gt = pick(both.length, treatment.length, 0); + immutable le = cast(int)(t - gt); + writefln(" > : %2.2f%% %d", 100.0 * gt / t, gt); + writefln("<= : %2.2f%% %d", 100.0 * le / t, le); +} diff --git a/Task/Permutation-test/Perl-6/permutation-test.pl6 b/Task/Permutation-test/Perl-6/permutation-test.pl6 new file mode 100644 index 0000000000..329a994422 --- /dev/null +++ b/Task/Permutation-test/Perl-6/permutation-test.pl6 @@ -0,0 +1,31 @@ +proto combine (Int, @) {*} + +multi combine (0, @) { [] } +multi combine ($, []) { () } +multi combine ($n, [$head, *@tail]) { + gather { + take [$head, @$_] for combine($n-1, @tail); + take [ @$_ ] for combine($n , @tail); + } +} + +sub stats ( @test, @all ) { + (([+] @test) / +@test ) - ([+] @all, (@test X* -1)) / (@all - @test) +} + + +my @treated = <85 88 75 66 25 29 83 39 97>; +my @control = <68 41 10 49 16 65 32 92 28 98>; +my @all = @treated, @control; + +my $base = stats( @treated, @all ); + +my @trials = 0, 0, 0; + +map { @trials[ 1 + ( stats( $_, @all ) <=> $base ) ]++ }, combine( +@treated, @all ); + +say 'Counts: <, =, > ', @trials; +say 'Less than : %', 100 * @trials[0] / [+] @trials; +say 'Equal to : %', 100 * @trials[1] / [+] @trials; +say 'Greater than : %', 100 * @trials[2] / [+] @trials; +say 'Less or Equal: %', 100 * ( [+] @trials[0,1] ) / [+] @trials; diff --git a/Task/Permutations-Derangements/Racket/permutations-derangements.rkt b/Task/Permutations-Derangements/Racket/permutations-derangements.rkt new file mode 100644 index 0000000000..c5ab4c57b9 --- /dev/null +++ b/Task/Permutations-Derangements/Racket/permutations-derangements.rkt @@ -0,0 +1,47 @@ +#lang racket + +(define (all-misplaced? l) + (for/and ([x (in-list l)] [n (in-naturals 1)]) (not (= x n)))) + +;; 1. Create a named function to generate derangements of the integers 0..n-1. +(define (derangements n) + (define (all-misplaced? l1 l2) + (or (null? l1) + (and (not (eq? (car l1) (car l2))) + (all-misplaced? (cdr l1) (cdr l2))))) + (define l (range n)) + (for/list ([p (permutations l)] #:when (all-misplaced? p l)) + p)) + +;; 2. Generate and show all the derangements of 4 integers using the above +;; routine. +(derangements 4) +;; -> '((1 0 3 2) (3 0 1 2) (1 3 0 2) (2 0 3 1) (2 3 0 1) +;; (3 2 0 1) (1 2 3 0) (2 3 1 0) (3 2 1 0)) + +;; 3. Create a function that calculates the subfactorial of n, !n. +(define (sub-fact n) + (if (< n 2) (- 1 n) + (* (+ (sub-fact (- n 1)) (sub-fact (- n 2))) (sub1 n)))) + +;; 4. Print and show a table of the counted number of derangements of n vs. the +;; calculated !n for n from 0..9 inclusive. +(for ([i 10]) + (printf "~a ~a ~a\n" i + (~a #:width 7 #:align 'right (length (derangements i))) + (sub-fact i))) +;; Output: +;; 0 1 1 +;; 1 0 0 +;; 2 1 1 +;; 3 2 2 +;; 4 9 9 +;; 5 44 44 +;; 6 265 265 +;; 7 1854 1854 +;; 8 14833 14833 +;; 9 133496 133496 + +;; Extra: !20 +(sub-fact 20) +;; -> 895014631192902121 diff --git a/Task/Permutations-Derangements/Ruby/permutations-derangements.rb b/Task/Permutations-Derangements/Ruby/permutations-derangements.rb index bb7d4ab69d..9688c295ae 100644 --- a/Task/Permutations-Derangements/Ruby/permutations-derangements.rb +++ b/Task/Permutations-Derangements/Ruby/permutations-derangements.rb @@ -13,13 +13,15 @@ def subfact(n) end end +puts "derangements for n = 4" +derangements(4).each{|d|p d} + +puts "\n n derange subfact" (0..9).each do |n| - s = subfact(n) - if n <= 4 - d = derangements(n) - puts "n=%d, subfact=%d, num_derangements=%d, %s" % [n, s, d.length, d] - else - puts "n=%d, subfact=%d" % [n, s] - end + puts "%2d :%8d,%8d" % [n, derangements(n).size, subfact(n)] +end + +puts "\nNumber of derangements" +(10..20).each do |n| + puts "#{n} : #{subfact(n)}" end -puts "n=20, subfact=#{subfact(20)}" diff --git a/Task/Permutations-by-swapping/Racket/permutations-by-swapping.rkt b/Task/Permutations-by-swapping/Racket/permutations-by-swapping.rkt new file mode 100644 index 0000000000..a0b00cf798 --- /dev/null +++ b/Task/Permutations-by-swapping/Racket/permutations-by-swapping.rkt @@ -0,0 +1,20 @@ +#lang racket + +(define (add-at l i x) + (if (zero? i) (cons x l) (cons (car l) (add-at (cdr l) (sub1 i) x)))) + +(define (permutations l) + (define (loop l) + (cond [(null? l) '(())] + [else (for*/list ([(p i) (in-indexed (loop (cdr l)))] + [i ((if (odd? i) identity reverse) + (range (add1 (length p))))]) + (add-at p i (car l)))])) + (for/list ([p (loop (reverse l))] [i (in-cycle '(1 -1))]) (cons i p))) + +(define (show-permutations l) + (printf "Permutations of ~s:\n" l) + (for ([p (permutations l)]) + (printf " ~a (~a)\n" (apply ~a (add-between (cdr p) ", ")) (car p)))) + +(for ([n (in-range 3 5)]) (show-permutations (range n))) diff --git a/Task/Permutations/00DESCRIPTION b/Task/Permutations/00DESCRIPTION index d4dcc2b6b9..fa72acb084 100644 --- a/Task/Permutations/00DESCRIPTION +++ b/Task/Permutations/00DESCRIPTION @@ -2,3 +2,6 @@ Write a program that generates all [[wp:Permutation|permutations]] of '''n''' di ;Cf. * [[Find the missing permutation]] * [[Permutations/Derangements]] + +'''See Also:''' +{{Template:Combinations and permutations}} diff --git a/Task/Permutations/ALGOL-68/permutations-1.alg b/Task/Permutations/ALGOL-68/permutations-1.alg index 53b680d214..11f0ddf5cd 100644 --- a/Task/Permutations/ALGOL-68/permutations-1.alg +++ b/Task/Permutations/ALGOL-68/permutations-1.alg @@ -1,61 +1,33 @@ -# Document prelude template usage: -TEMPLATE( - INT upb values := 4; - MODE VALUE = INT; - FORMAT value fmt := $g(0)$ -); # +# -*- coding: utf-8 -*- # -MODE - VALVALUES = [upb values]VALUE, VALUES = REF VALVALUES, - YIELDVALUES = PROC(VALUES)VOID; +COMMENT REQUIRED BY "prelude_permutations.a68" + MODE PERMDATA = ~; +PROVIDES: +# PERMDATA*=~* # +# perm*=~ list* # +END COMMENT -FORMAT - values fmt := $"("n(upb values-1)(f(value fmt)", ")f(value fmt)")"$; +MODE PERMDATALIST = REF[]PERMDATA; +MODE PERMDATALISTYIELD = PROC(PERMDATALIST)VOID; -# Generate permutations of the input values of valueues # -PROC gen values permutations = (VALUES values, YIELDVALUES yield)VOID: ( +# Generate permutations of the input data list of data list # +PROC perm gen permutations = (PERMDATALIST data list, PERMDATALISTYIELD yield)VOID: ( # Warning: this routine does not correctly handle duplicate elements # - IF LWB values = UPB values THEN - yield(values) + IF LWB data list = UPB data list THEN + yield(data list) ELSE - FOR elem FROM LWB values TO UPB values DO - VALUE first = values[elem]; - values[LWB values+1:elem] := values[:elem-1]; - values[LWB values] := first; - # FOR VALUES next values IN # gen values permutations(values[LWB values+1:] # ) DO #, - ## (VALUES next)VOID:( - yield(values) + FOR elem FROM LWB data list TO UPB data list DO + PERMDATA first = data list[elem]; + data list[LWB data list+1:elem] := data list[:elem-1]; + data list[LWB data list] := first; + # FOR PERMDATALIST next data list IN # perm gen permutations(data list[LWB data list+1:] # ) DO #, + ## (PERMDATALIST next)VOID:( + yield(data list) # OD #)); - values[:elem-1] := values[LWB values+1:elem]; - values[elem] := first + data list[:elem-1] := data list[LWB data list+1:elem]; + data list[elem] := first OD FI ); -############################################ -# Define some additional utility OPerators # -############################################ -PRIO P = 7; # OP to calculate number of permutations # -OP P = (INT n, k)INT: ( # n! OVER (n-k)! # - # ( n>k | n * ((n-1) P k) | n ); # - INT out := k; - FOR i FROM k+1 TO n DO out *:= i OD; - out -); - -# Define an operator for doing iterations over permutations # -PRIO DOPERM = 1; -OP (VALUES, YIELDVALUES)VOID DOPERM = gen values permutations; - -# Return an a matrix of permutations # -OP PERM = (VALUES in values)[, ]VALUE: ( - [(UPB in values-LWB in values+1) P 1, LWB in values:UPB in values]VALUE out; - INT elem := LWB out; - -# FOR VALUES values IN # in values DOPERM ( -## (VALUES values)VOID:( - out[elem, ] := values; - elem +:= 1 -# OD #)); - out -); +SKIP diff --git a/Task/Permutations/ALGOL-68/permutations-2.alg b/Task/Permutations/ALGOL-68/permutations-2.alg index 6303d83d8e..0e419432ea 100644 --- a/Task/Permutations/ALGOL-68/permutations-2.alg +++ b/Task/Permutations/ALGOL-68/permutations-2.alg @@ -1,23 +1,24 @@ -#!/usr/local/bin/a68g --script # +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # -PR READ "Template_Permutations.a68" PR # n.b. READ is nonstandard # -# USING( # - INT upb values := 4; - MODE VALUE = INT; # user defined # - FORMAT value fmt := $g(0)$ -# ) #; +CO REQUIRED BY "prelude_permutations.a68" CO + MODE PERMDATA = INT; +#PROVIDES:# +# PERM*=INT* # +# perm *=int list *# +PR READ "prelude_permutations.a68" PR; main:( - VALVALUES test case := (1, 22, 333, 44444); - print(("Number of permutations: ", UPB test case P 1, new line)); + FLEX[0]PERMDATA test case := (1, 22, 333, 44444); -COMMENT # Use the generator: # - # FOR ARRAY values IN # test case DOPERM ( - ## (ARRAY values)VOID:( - printf((values fmt, values, $l$)) - # OD #)); -END COMMENT + INT upb data list = UPB test case; + FORMAT + data fmt := $g(0)$, + data list fmt := $"("n(upb data list-1)(f(data fmt)", ")f(data fmt)")"$; + +# FOR DATALIST permutation IN # perm gen permutations(test case#) DO (#, +## (PERMDATALIST permutation)VOID:( + printf((data list fmt, permutation, $l$)) +# OD #)) -# or simply the operator: # - printf(($f(values fmt)l$, PERM test case)) ) diff --git a/Task/Permutations/Ada/permutations-1.ada b/Task/Permutations/Ada/permutations-1.ada new file mode 100644 index 0000000000..eb8bc13e53 --- /dev/null +++ b/Task/Permutations/Ada/permutations-1.ada @@ -0,0 +1,9 @@ +generic + N: positive; +package Generic_Perm is + subtype Element is Positive range 1 .. N; + type Permutation is array(Element) of Element; + + procedure Set_To_First(P: out Permutation; Is_Last: out Boolean); + procedure Go_To_Next(P: in out Permutation; Is_Last: out Boolean); +end Generic_Perm; diff --git a/Task/Permutations/Ada/permutations-2.ada b/Task/Permutations/Ada/permutations-2.ada new file mode 100644 index 0000000000..437a77fad2 --- /dev/null +++ b/Task/Permutations/Ada/permutations-2.ada @@ -0,0 +1,71 @@ +package body Generic_Perm is + + + procedure Set_To_First(P: out Permutation; Is_Last: out Boolean) is + begin + for I in P'Range loop + P (I) := I; + end loop; + Is_Last := P'Length = 1; + -- if P has a single element, the fist permutation is the last one + end Set_To_First; + + procedure Go_To_Next(P: in out Permutation; Is_Last: out Boolean) is + + procedure Swap (A, B : in out Integer) is + C : Integer := A; + begin + A := B; + B := C; + end Swap; + + I, J, K : Element; + begin + -- find longest tail decreasing sequence + -- after the loop, this sequence is I+1 .. n, + -- and the ith element will be exchanged later + -- with some element of the tail + Is_Last := True; + I := N - 1; + loop + if P (I) < P (I+1) + then + Is_Last := False; + exit; + end if; + + -- next instruction will raise an exception if I = 1, so + -- exit now (this is the last permutation) + exit when I = 1; + I := I - 1; + end loop; + + -- if all the elements of the permutation are in + -- decreasing order, this is the last one + if Is_Last then + return; + end if; + + -- sort the tail, i.e. reverse it, since it is in decreasing order + J := I + 1; + K := N; + while J < K loop + Swap (P (J), P (K)); + J := J + 1; + K := K - 1; + end loop; + + -- find lowest element in the tail greater than the ith element + J := N; + while P (J) > P (I) loop + J := J - 1; + end loop; + J := J + 1; + + -- exchange them + -- this will give the next permutation in lexicographic order, + -- since every element from ith to the last is minimum + Swap (P (I), P (J)); + end Go_To_Next; + +end Generic_Perm; diff --git a/Task/Permutations/Ada/permutations-3.ada b/Task/Permutations/Ada/permutations-3.ada new file mode 100644 index 0000000000..adc5b6cfa5 --- /dev/null +++ b/Task/Permutations/Ada/permutations-3.ada @@ -0,0 +1,30 @@ +with Ada.Text_IO, Ada.Command_Line, Generic_Perm; + +procedure Print_Perms is + package CML renames Ada.Command_Line; + package TIO renames Ada.Text_IO; +begin + declare + package Perms is new Generic_Perm(Positive'Value(CML.Argument(1))); + P : Perms.Permutation; + Done : Boolean := False; + + procedure Print(P: Perms.Permutation) is + begin + for I in P'Range loop + TIO.Put (Perms.Element'Image (P (I))); + end loop; + TIO.New_Line; + end Print; + begin + Perms.Set_To_First(P, Done); + loop + Print(P); + exit when Done; + Perms.Go_To_Next(P, Done); + end loop; + end; +exception + when Constraint_Error + => TIO.Put_Line ("*** Error: enter one numerical argument n with n >= 1"); +end Print_Perms; diff --git a/Task/Permutations/NetRexx/permutations.netrexx b/Task/Permutations/NetRexx/permutations.netrexx new file mode 100644 index 0000000000..2a51355ec8 --- /dev/null +++ b/Task/Permutations/NetRexx/permutations.netrexx @@ -0,0 +1,148 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +import java.util.List +import java.util.ArrayList + +-- ============================================================================= +/** + * Permutation Iterator + *
+ *
+ * Algorithm by E. W. Dijkstra, "A Discipline of Programming", Prentice-Hall, 1976, p.71 + */ +class RPermutationIterator implements Iterator + + -- --------------------------------------------------------------------------- + properties indirect + perms = List + permOrders = int[] + maxN + currentN + first = boolean + + -- --------------------------------------------------------------------------- + properties constant + isTrue = boolean (1 == 1) + isFalse = boolean (1 \= 1) + + -- --------------------------------------------------------------------------- + method RPermutationIterator(initial = List) public + setUp(initial) + return + + -- --------------------------------------------------------------------------- + method RPermutationIterator(initial = Object[]) public + init = ArrayList(initial.length) + loop elmt over initial + init.add(elmt) + end elmt + setUp(init) + return + + -- --------------------------------------------------------------------------- + method RPermutationIterator(initial = Rexx[]) public + init = ArrayList(initial.length) + loop elmt over initial + init.add(elmt) + end elmt + setUp(init) + return + + -- --------------------------------------------------------------------------- + method setUp(initial = List) private + setFirst(isTrue) + setPerms(initial) + setPermOrders(int[getPerms().size()]) + setMaxN(getPermOrders().length) + setCurrentN(0) + po = getPermOrders() + loop i_ = 0 while i_ < po.length + po[i_] = i_ + end i_ + return + + -- --------------------------------------------------------------------------- + method hasNext() public returns boolean + status = isTrue + if getCurrentN() == factorial(getMaxN()) then status = isFalse + setCurrentN(getCurrentN() + 1) + return status + + -- --------------------------------------------------------------------------- + method next() public returns Object + if isFirst() then setFirst(isFalse) + else do + po = getPermOrders() + i_ = getMaxN() - 1 + loop while po[i_ - 1] >= po[i_] + i_ = i_ - 1 + end + + j_ = getMaxN() + loop while po[j_ - 1] <= po[i_ - 1] + j_ = j_ - 1 + end + + swap(i_ - 1, j_ - 1) + + i_ = i_ + 1 + j_ = getMaxN() + loop while i_ < j_ + swap(i_ - 1, j_ - 1) + i_ = i_ + 1 + j_ = j_ - 1 + end + end + return reorder() + + -- --------------------------------------------------------------------------- + method remove() public signals UnsupportedOperationException + signal UnsupportedOperationException() + + -- --------------------------------------------------------------------------- + method swap(i_, j_) private + po = getPermOrders() + save = po[i_] + po[i_] = po[j_] + po[j_] = save + return + + -- --------------------------------------------------------------------------- + method reorder() private returns List + result = ArrayList(getPerms().size()) + loop ix over getPermOrders() + result.add(getPerms().get(ix)) + end ix + return result + + -- --------------------------------------------------------------------------- + /** + * Calculate n factorial: {@code n! = 1 * 2 * 3 .. * n} + * @param n + * @return n! + */ + method factorial(n) public static + fact = 1 + if n > 1 then loop i = 1 while i <= n + fact = fact * i + end i + return fact + + -- --------------------------------------------------------------------------- + method main(args = String[]) public static + thing02 = RPermutationIterator(['alpha', 'omega']) + thing03 = RPermutationIterator([String 'one', 'two', 'three']) + thing04 = RPermutationIterator(Arrays.asList([Integer(1), Integer(2), Integer(3), Integer(4)])) + things = [thing02, thing03, thing04] + loop thing over things + N = thing.getMaxN() + say 'Permutations:' N'! =' factorial(N) + loop lineCount = 1 while thing.hasNext() + prm = thing.next() + say lineCount.right(8)':' prm.toString() + end lineCount + say 'Permutations:' N'! =' factorial(N) + say + end thing + return diff --git a/Task/Permutations/Racket/permutations.rkt b/Task/Permutations/Racket/permutations.rkt new file mode 100644 index 0000000000..26f1f6eabd --- /dev/null +++ b/Task/Permutations/Racket/permutations.rkt @@ -0,0 +1,13 @@ +#lang racket + +;; using a builtin +(permutations '(A B C)) +;; -> '((A B C) (B A C) (A C B) (C A B) (B C A) (C B A)) + +;; a random simple version (which is actually pretty good for a simple version) +(define (perms l) + (let loop ([l l] [tail '()]) + (if (null? l) (list tail) + (append-map (λ(x) (loop (remq x l) (cons x tail))) l)))) +(perms '(A B C)) +;; -> '((C B A) (B C A) (C A B) (A C B) (B A C) (A B C)) diff --git a/Task/Pi/Erlang/pi.erl b/Task/Pi/Erlang/pi.erl new file mode 100644 index 0000000000..b1cbc6d821 --- /dev/null +++ b/Task/Pi/Erlang/pi.erl @@ -0,0 +1,29 @@ +% Implemented by Arjun Sunel +-module(pi_calculation). +-export([main/0]). + +main() -> + pi(1,0,1,1,3,3,0). + +pi(Q,R,T,K,N,L,C) -> + + if C=:=50 -> + io:format("\n"), + pi(Q,R,T,K,N,L,0) ; + + true -> + + if + (4*Q + R-T) < (N*T) -> + io:format("~p",[N]), + P = 10*(R-N*T), + pi(Q*10 , P, T , K , ((10*(3*Q+R)) div T)-10*N , L,C+1); + + true -> + P = (2*Q+R)*L, + M = (Q*(7*K)+2+(R*L)) div (T*L), + H = L+2, + J =K+ 1, + pi(Q*K, P , T*L ,J,M,H,C) + end + end. diff --git a/Task/Pi/Seed7/pi.seed7 b/Task/Pi/Seed7/pi.seed7 new file mode 100644 index 0000000000..80725f4f2d --- /dev/null +++ b/Task/Pi/Seed7/pi.seed7 @@ -0,0 +1,39 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const proc: main is func + local + var bigInteger: q is 1_; + var bigInteger: r is 0_; + var bigInteger: t is 1_; + var bigInteger: k is 1_; + var bigInteger: n is 3_; + var bigInteger: l is 3_; + var bigInteger: nn is 0_; + var bigInteger: nr is 0_; + var boolean: first is TRUE; + begin + while TRUE do + if 4_ * q + r - t < n * t then + write(n); + if first then + write("."); + first := FALSE; + end if; + nr := 10_ * (r - n * t); + n := 10_ * (3_ * q + r) div t - 10_ * n; + q *:= 10_; + r := nr; + flush(OUT); + else + nr := (2_ * q + r) * l; + nn := (q * (7_ * k + 2_) + r * l) div (t * l); + q *:= k; + t *:= l; + l +:= 2_; + incr(k); + n := nn; + r := nr; + end if; + end while; + end func; diff --git a/Task/Pick-random-element/C++/pick-random-element.cpp b/Task/Pick-random-element/C++/pick-random-element.cpp new file mode 100644 index 0000000000..4f4c5c437a --- /dev/null +++ b/Task/Pick-random-element/C++/pick-random-element.cpp @@ -0,0 +1,15 @@ +#include +#include +#include + +int main( ) { + std::vector numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ; + std::random_device seed ; + // generator + std::mt19937 engine( seed( ) ) ; + // number distribution + std::uniform_int_distribution choose( 0 , numbers.size( ) - 1 ) ; + std::cout << "random element picked : " << numbers[ choose( engine ) ] + << " !\n" ; + return 0 ; +} diff --git a/Task/Pick-random-element/D/pick-random-element.d b/Task/Pick-random-element/D/pick-random-element.d index 0a25baf4f7..118872647f 100644 --- a/Task/Pick-random-element/D/pick-random-element.d +++ b/Task/Pick-random-element/D/pick-random-element.d @@ -1,7 +1,6 @@ import std.stdio, std.random; void main() { - auto items = ["foo", "bar", "baz"]; - auto r = items[uniform(0, $)]; - writeln(r); + const items = ["foo", "bar", "baz"]; + items[uniform(0, $)].writeln; } diff --git a/Task/Pick-random-element/Erlang/pick-random-element.erl b/Task/Pick-random-element/Erlang/pick-random-element.erl new file mode 100644 index 0000000000..6f53d5062f --- /dev/null +++ b/Task/Pick-random-element/Erlang/pick-random-element.erl @@ -0,0 +1,8 @@ +% Implemented by Arjun Sunel +-module(pick_random). +-export([main/0]). + +main() -> + List =[1,2,3,4,5], + index = random:uniform(length(List)), + lists:nth(index,List). diff --git a/Task/Pick-random-element/Perl-6/pick-random-element-1.pl6 b/Task/Pick-random-element/Perl-6/pick-random-element-1.pl6 index 5654731e2e..266ed701b3 100644 --- a/Task/Pick-random-element/Perl-6/pick-random-element-1.pl6 +++ b/Task/Pick-random-element/Perl-6/pick-random-element-1.pl6 @@ -1,3 +1 @@ -(1..6).roll; # return 1 random value in the range 1 through 6 -(1..6).roll(3); # return a list of 3 random values in the range 1 through 6 -(1..6).roll(*); # return a lazy infinite list of random values in the range 1 through 6 +say (1, 2, 3).pick; diff --git a/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 b/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 index ebdf90d652..5654731e2e 100644 --- a/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 +++ b/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 @@ -1,5 +1,3 @@ -# define the deck -constant deck = 2..9, X~ <♠ ♣ ♥ ♦>; -deck.pick; # Pick a card -deck.pick(5); # Draw 5 -deck.pick(*); # Get a shuffled deck +(1..6).roll; # return 1 random value in the range 1 through 6 +(1..6).roll(3); # return a list of 3 random values in the range 1 through 6 +(1..6).roll(*); # return a lazy infinite list of random values in the range 1 through 6 diff --git a/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 b/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 index 6a758f28b2..ebdf90d652 100644 --- a/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 +++ b/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 @@ -1 +1,5 @@ -@array[@array * rand] +# define the deck +constant deck = 2..9, X~ <♠ ♣ ♥ ♦>; +deck.pick; # Pick a card +deck.pick(5); # Draw 5 +deck.pick(*); # Get a shuffled deck diff --git a/Task/Pick-random-element/Perl-6/pick-random-element-4.pl6 b/Task/Pick-random-element/Perl-6/pick-random-element-4.pl6 index d6737ba8f7..6a758f28b2 100644 --- a/Task/Pick-random-element/Perl-6/pick-random-element-4.pl6 +++ b/Task/Pick-random-element/Perl-6/pick-random-element-4.pl6 @@ -1 +1 @@ -say Bool.pick; # returns either True or False +@array[@array * rand] diff --git a/Task/Pick-random-element/Perl-6/pick-random-element-5.pl6 b/Task/Pick-random-element/Perl-6/pick-random-element-5.pl6 new file mode 100644 index 0000000000..d6737ba8f7 --- /dev/null +++ b/Task/Pick-random-element/Perl-6/pick-random-element-5.pl6 @@ -0,0 +1 @@ +say Bool.pick; # returns either True or False diff --git a/Task/Pick-random-element/Racket/pick-random-element.rkt b/Task/Pick-random-element/Racket/pick-random-element.rkt new file mode 100644 index 0000000000..ccbc8eea22 --- /dev/null +++ b/Task/Pick-random-element/Racket/pick-random-element.rkt @@ -0,0 +1,3 @@ +#lang racket +(define (pick-item l) + (list-ref l (random (length l)))) diff --git a/Task/Pig-the-dice-game-Player/C++/pig-the-dice-game-player.cpp b/Task/Pig-the-dice-game-Player/C++/pig-the-dice-game-player.cpp new file mode 100644 index 0000000000..3294769584 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/C++/pig-the-dice-game-player.cpp @@ -0,0 +1,159 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +const int PLAYERS = 4, MAX_POINTS = 100; + +//-------------------------------------------------------------------------------------------------- +enum Moves { ROLL, HOLD }; + +//-------------------------------------------------------------------------------------------------- +class player +{ +public: + player() { current_score = round_score = 0; } + void addCurrScore() { current_score += round_score; } + int getCurrScore() { return current_score; } + int getRoundScore() { return round_score; } + void addRoundScore( int rs ) { round_score += rs; } + void zeroRoundScore() { round_score = 0; } + virtual int getMove() = 0; + virtual ~player() {} + +protected: + int current_score, round_score; +}; +//-------------------------------------------------------------------------------------------------- +class RAND_Player : public player +{ + virtual int getMove() + { + if( round_score + current_score >= MAX_POINTS ) return HOLD; + + if( rand() % 10 < 5 ) return ROLL; + if( round_score > 0 ) return HOLD; + return ROLL; + } +}; +//-------------------------------------------------------------------------------------------------- +class Q2WIN_Player : public player +{ + virtual int getMove() + { + if( round_score + current_score >= MAX_POINTS ) return HOLD; + + int q = MAX_POINTS - current_score; + if( q < 6 ) return ROLL; + q /= 4; + if( round_score < q ) return ROLL; + return HOLD; + } +}; +//-------------------------------------------------------------------------------------------------- +class AL20_Player : public player +{ + virtual int getMove() + { + if( round_score + current_score >= MAX_POINTS ) return HOLD; + + if( round_score < 20 ) return ROLL; + return HOLD; + } +}; +//-------------------------------------------------------------------------------------------------- +class AL20T_Player : public player +{ + virtual int getMove() + { + if( round_score + current_score >= MAX_POINTS ) return HOLD; + + int d = ( 100 * round_score ) / 20; + if( round_score < 20 && d < rand() % 100 ) return ROLL; + return HOLD; + } +}; +//-------------------------------------------------------------------------------------------------- +class Auto_pigGame +{ +public: + Auto_pigGame() + { + _players[0] = new RAND_Player(); + _players[1] = new Q2WIN_Player(); + _players[2] = new AL20_Player(); + _players[3] = new AL20T_Player(); + } + + ~Auto_pigGame() + { + delete _players[0]; + delete _players[1]; + delete _players[2]; + delete _players[3]; + } + + void play() + { + int die, p = 0; + bool endGame = false; + + while( !endGame ) + { + switch( _players[p]->getMove() ) + { + case ROLL: + die = rand() % 6 + 1; + if( die == 1 ) + { + cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl; + nextTurn( p ); + continue; + } + _players[p]->addRoundScore( die ); + cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl; + break; + case HOLD: + _players[p]->addCurrScore(); + cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl; + if( _players[p]->getCurrScore() >= MAX_POINTS ) + endGame = true; + else nextTurn( p ); + + } + } + showScore(); + } + +private: + void nextTurn( int& p ) + { + _players[p]->zeroRoundScore(); + ++p %= PLAYERS; + } + + void showScore() + { + cout << endl; + cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl; + cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl; + cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl; + cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl; + + system( "pause" ); + } + + player* _players[PLAYERS]; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + srand( GetTickCount() ); + Auto_pigGame pg; + pg.play(); + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Pig-the-dice-game-Player/D/pig-the-dice-game-player.d b/Task/Pig-the-dice-game-Player/D/pig-the-dice-game-player.d new file mode 100644 index 0000000000..543de73806 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/D/pig-the-dice-game-player.d @@ -0,0 +1,124 @@ +import std.stdio, std.random; + +enum nPlayers = 4, maxPoints = 100; + +enum Moves { roll, hold } + +abstract class Player { + public: + final void addCurrScore() { current_score += round_score; } + final int getCurrScore() const { return current_score; } + final int getRoundScore() const { return round_score; } + final void addRoundScore(in int rs) { round_score += rs; } + final void zeroRoundScore() { round_score = 0; } + Moves getMove(); + + protected: + int current_score, round_score; +} + +final class PlayerRand : Player { + override Moves getMove() { + if (round_score + current_score >= maxPoints) + return Moves.hold; + + if (uniform(0, 2) == 0) + return Moves.roll; + if (round_score > 0) + return Moves.hold; + return Moves.roll; + } +} + +final class PlayerQ2Win : Player { + override Moves getMove() { + if (round_score + current_score >= maxPoints) + return Moves.hold; + + int q = maxPoints - current_score; + if (q < 6) + return Moves.roll; + q /= 4; + if (round_score < q) + return Moves.roll; + return Moves.hold; + } +} + +final class PlayerAL20 : Player { + override Moves getMove() { + if (round_score + current_score >= maxPoints) + return Moves.hold; + if (round_score < 20) + return Moves.roll; + return Moves.hold; + } +} + +final class PlayerAL20T : Player { + override Moves getMove() { + if (round_score + current_score >= maxPoints) + return Moves.hold; + + immutable d = (100 * round_score) / 20; + if (round_score < 20 && d < uniform(0, 100)) + return Moves.roll; + return Moves.hold; + } +} + +void main() { + //Player[nPlayers] players = [new PlayerRand, new PlayerQ2Win, + // new PlayerAL20, new PlayerAL20T]; + Player[nPlayers] players; + players[0] = new PlayerRand; + players[1] = new PlayerQ2Win; + players[2] = new PlayerAL20; + players[3] = new PlayerAL20T; + + void nextTurn(ref uint p) { + players[p].zeroRoundScore(); + p = (p + 1) % nPlayers; + } + + uint p = 0; + bool endGame = false; + + while (!endGame) { + final switch (players[p].getMove) { + case Moves.roll: + immutable die = uniform(1, 7); + + if (die == 1) { + writeln("Player ", p + 1, " rolled ", die, + " - current score: ", + players[p].getCurrScore, "\n"); + nextTurn(p); + continue; + } + players[p].addRoundScore(die); + writeln("Player ", p + 1, " rolled ", die, + " - round score: ", + players[p].getRoundScore); + break; + + case Moves.hold: + players[p].addCurrScore; + writeln("Player ", p + 1, + " holds - current score: ", + players[p].getCurrScore, "\n"); + if (players[p].getCurrScore >= maxPoints) + endGame = true; + else + nextTurn(p); + + } + } + + writeln; + writeln("Player I (Rand): ", players[0].getCurrScore); + writeln("Player II (Q2Win): ", players[1].getCurrScore); + writeln("Player III (AL20): ", players[2].getCurrScore); + writeln("Player IV (AL20T): ", players[3].getCurrScore, + "\n\n"); +} diff --git a/Task/Pig-the-dice-game-Player/Perl-6/pig-the-dice-game-player.pl6 b/Task/Pig-the-dice-game-Player/Perl-6/pig-the-dice-game-player.pl6 new file mode 100644 index 0000000000..e4191ff5a9 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Perl-6/pig-the-dice-game-player.pl6 @@ -0,0 +1,66 @@ +my $games = @*ARGS ?? (shift @*ARGS) !! 100; + +constant DIE = 1 .. 6; +constant GOAL = 100; + +class player { + has $.score is rw = 0; + has $.ante is rw; + has $.rolls is rw; + has &.strategy is rw = sub { False }; # default, always roll again + + method turn { + my $done_turn = False; + $.rolls = 0; + $.ante = 0; + repeat { + given DIE.roll { + $.rolls++; + when 1 { + $.ante = 0; + $done_turn = True; + } + when 2..* { + $.ante += $_; + } + } + $done_turn = True if $.score + $.ante >= GOAL or (&.strategy)(); + } until $done_turn; + $.score += $.ante; + } +} + +my @players; + +# default, go-for-broke, always roll again +@players[0] = player.new; + +# try to roll 5 times but no more per turn +@players[1] = player.new( strategy => sub { @players[1].rolls >= 5 } ); + +# try to accumulate at least 20 points per turn +@players[2] = player.new( strategy => sub { @players[2].ante > 20 } ); + +# random but 90% chance of rolling again +@players[3] = player.new( strategy => sub { 1.rand < .1 } ); + +# random but more conservative as approaches goal +@players[4] = player.new( strategy => sub { 1.rand < ( GOAL - @players[4].score ) * .6 / GOAL } ); + +my @wins = 0 xx @players; + +for ^ $games { + my $player = -1; + repeat { + $player++; + @players[$player % @players].turn; + } until @players[$player % @players].score >= GOAL; + + @wins[$player % @players]++; + + say join "\t", @players>>.score; + @players[$_].score = 0 for ^@players; # reset scores for next game +} + +say "\nSCORES: for $games games"; +say join "\t", @wins; diff --git a/Task/Pig-the-dice-game-Player/Racket/pig-the-dice-game-player.rkt b/Task/Pig-the-dice-game-Player/Racket/pig-the-dice-game-player.rkt new file mode 100644 index 0000000000..e8998ef3fa --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Racket/pig-the-dice-game-player.rkt @@ -0,0 +1,46 @@ +#lang racket + +(define (pig-the-dice #:print? [print? #t] . players) + (define prn (if print? (λ xs (apply printf xs) (flush-output)) void)) + (define names (for/list ([p players] [n (in-naturals 1)]) n)) + (define points (for/list ([p players]) (box 0))) + (with-handlers ([(negate exn?) identity]) + (for ([nm (in-cycle names)] [tp (in-cycle points)] [pl (in-cycle players)]) + (prn (string-join (for/list ([n names] [p points]) + (format "Player ~a, ~a points" n (unbox p))) + "; " #:before-first "Status: " #:after-last ".\n")) + (let turn ([p 0] [n 0]) + (prn "Player ~a, round #~a, [R]oll or [P]ass? " nm (+ 1 n)) + (define roll? (pl (unbox tp) p n)) + (unless (eq? pl human) (prn "~a\n" (if roll? 'R 'P))) + (if (not roll?) (set-box! tp (+ (unbox tp) p)) + (let ([r (+ 1 (random 6))]) + (prn " Dice roll: ~s => " r) + (if (= r 1) (prn "turn lost\n") + (let ([p (+ p r)]) (prn "~a points\n" p) (turn p (+ 1 n))))))) + (prn "--------------------\n") + (when (<= 100 (unbox tp)) (prn "Player ~a wins!\n" nm) (raise nm))))) + +(define (human total-points turn-points round#) + (case (string->symbol (car (regexp-match #px"[A-Za-z]?" (read-line)))) + [(R r) #t] [(P p) #f] [else (human total-points turn-points round#)])) + +;; Always do N rolls +(define ((n-rounds n) total-points turn-points round#) (< round# n)) +;; Roll until a given number of points +(define ((n-points n) total-points turn-points round#) (< turn-points n)) +;; Random decision +(define ((n-random n) total-points turn-points round#) (zero? (random n))) + +(define (n-runs n . players) + (define v (make-vector (length players) 0)) + (for ([i n]) + (define p (sub1 (apply pig-the-dice #:print? #f players))) + (vector-set! v p (add1 (vector-ref v p)))) + (for ([wins v] [i (in-naturals 1)]) + (printf "Player ~a: ~a%\n" i (round (/ wins n 1/100))))) + +;; Things to try +;; (n-runs 1000 (n-random 2) (n-random 3) (n-random 4)) +;; (n-runs 1000 (n-rounds 5) (n-points 24)) +;; (n-runs 1000 (n-rounds 5) (n-random 2)) diff --git a/Task/Pig-the-dice-game/C++/pig-the-dice-game.cpp b/Task/Pig-the-dice-game/C++/pig-the-dice-game.cpp new file mode 100644 index 0000000000..d5771f43ff --- /dev/null +++ b/Task/Pig-the-dice-game/C++/pig-the-dice-game.cpp @@ -0,0 +1,135 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +const int PLAYERS = 2, MAX_POINTS = 100; + +//-------------------------------------------------------------------------------------------------- +class player +{ +public: + player() { reset(); } + void reset() + { + name = ""; + current_score = round_score = 0; + } + string getName() { return name; } + void setName( string n ) { name = n; } + int getCurrScore() { return current_score; } + void addCurrScore() { current_score += round_score; } + int getRoundScore() { return round_score; } + void addRoundScore( int rs ) { round_score += rs; } + void zeroRoundScore() { round_score = 0; } + +private: + string name; + int current_score, round_score; +}; +//-------------------------------------------------------------------------------------------------- +class pigGame +{ +public: + pigGame() { resetPlayers(); } + + void play() + { + while( true ) + { + system( "cls" ); + int p = 0; + while( true ) + { + if( turn( p ) ) + { + praise( p ); + break; + } + + ++p %= PLAYERS; + } + + string r; + cout << "Do you want to play again ( y / n )? "; cin >> r; + if( r != "Y" && r != "y" ) return; + resetPlayers(); + } + } + +private: + void resetPlayers() + { + system( "cls" ); + string n; + for( int p = 0; p < PLAYERS; p++ ) + { + _players[p].reset(); + cout << "Enter name player " << p + 1 << ": "; cin >> n; + _players[p].setName( n ); + } + + } + + void praise( int p ) + { + system( "cls" ); + cout << "CONGRATULATIONS " << _players[p].getName() << ", you are the winner!" << endl << endl; + cout << "Final Score" << endl; + drawScoreboard(); + cout << endl << endl; + } + + void drawScoreboard() + { + for( int p = 0; p < PLAYERS; p++ ) + cout << _players[p].getName() << ": " << _players[p].getCurrScore() << " points" << endl; + cout << endl; + } + + bool turn( int p ) + { + system( "cls" ); + drawScoreboard(); + _players[p].zeroRoundScore(); + string r; + int die; + while( true ) + { + cout << _players[p].getName() << ", your round score is: " << _players[p].getRoundScore() << endl; + cout << "What do you want to do (H)old or (R)oll? "; cin >> r; + if( r == "h" || r == "H" ) + { + _players[p].addCurrScore(); + return _players[p].getCurrScore() >= MAX_POINTS; + } + if( r == "r" || r == "R" ) + { + die = rand() % 6 + 1; + if( die == 1 ) + { + cout << _players[p].getName() << ", your turn is over." << endl << endl; + system( "pause" ); + return false; + } + _players[p].addRoundScore( die ); + } + cout << endl; + } + return false; + } + + player _players[PLAYERS]; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + srand( GetTickCount() ); + pigGame pg; + pg.play(); + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Pig-the-dice-game/Objeck/pig-the-dice-game.objeck b/Task/Pig-the-dice-game/Objeck/pig-the-dice-game.objeck new file mode 100644 index 0000000000..c44118693d --- /dev/null +++ b/Task/Pig-the-dice-game/Objeck/pig-the-dice-game.objeck @@ -0,0 +1,39 @@ +class Pig { + function : Main(args : String[]) ~ Nil { + player_count := 2; + max_score := 100; + safe_score := Int->New[player_count]; + player := 0; score := 0; + + while(true) { + safe := safe_score[player]; + " Player {$player}: ({$safe}, {$score}) Rolling? (y/n) "->PrintLine(); + rolling := IO.Console->ReadString(); + if(safe_score[player] + score < max_score & (rolling->Equals("y") | rolling->Equals("yes"))) { + rolled := ((Float->Random() * 100.0)->As(Int) % 6) + 1; + " Rolled {$rolled}"->PrintLine(); + if(rolled = 1) { + safe := safe_score[player]; + " Bust! you lose {$score} but still keep your previous {$safe}\n"->PrintLine(); + score := 0; + player := (player + 1) % player_count; + } + else { + score += rolled; + }; + } + else { + safe_score[player] += score; + if(safe_score[player] >= max_score) { + break; + }; + safe := safe_score[player]; + " Sticking with {$safe}\n"->PrintLine(); + score := 0; + player := (player + 1) % player_count; + }; + }; + safe := safe_score[player]; + "\n\nPlayer {$player} wins with a score of {$safe}"->PrintLine(); + } +} diff --git a/Task/Pig-the-dice-game/Racket/pig-the-dice-game.rkt b/Task/Pig-the-dice-game/Racket/pig-the-dice-game.rkt new file mode 100644 index 0000000000..1202346e07 --- /dev/null +++ b/Task/Pig-the-dice-game/Racket/pig-the-dice-game.rkt @@ -0,0 +1,28 @@ +#lang racket + +(define (pig-the-dice #:print? [print? #t] . players) + (define prn (if print? (λ xs (apply printf xs) (flush-output)) void)) + (define names (for/list ([p players] [n (in-naturals 1)]) n)) + (define points (for/list ([p players]) (box 0))) + (with-handlers ([(negate exn?) identity]) + (for ([nm (in-cycle names)] [tp (in-cycle points)] [pl (in-cycle players)]) + (prn (string-join (for/list ([n names] [p points]) + (format "Player ~a, ~a points" n (unbox p))) + "; " #:before-first "Status: " #:after-last ".\n")) + (let turn ([p 0] [n 0]) + (prn "Player ~a, round #~a, [R]oll or [P]ass? " nm (+ 1 n)) + (define roll? (pl (unbox tp) p n)) + (unless (eq? pl human) (prn "~a\n" (if roll? 'R 'P))) + (if (not roll?) (set-box! tp (+ (unbox tp) p)) + (let ([r (+ 1 (random 6))]) + (prn " Dice roll: ~s => " r) + (if (= r 1) (prn "turn lost\n") + (let ([p (+ p r)]) (prn "~a points\n" p) (turn p (+ 1 n))))))) + (prn "--------------------\n") + (when (<= 100 (unbox tp)) (prn "Player ~a wins!\n" nm) (raise nm))))) + +(define (human total-points turn-points round#) + (case (string->symbol (car (regexp-match #px"[A-Za-z]?" (read-line)))) + [(R r) #t] [(P p) #f] [else (human total-points turn-points round#)])) + +(pig-the-dice #:print? #t human human) diff --git a/Task/Pinstripe-Display/C++/pinstripe-display.cpp b/Task/Pinstripe-Display/C++/pinstripe-display.cpp new file mode 100644 index 0000000000..eeafdee24c --- /dev/null +++ b/Task/Pinstripe-Display/C++/pinstripe-display.cpp @@ -0,0 +1,117 @@ +#include + +//-------------------------------------------------------------------------------------------------- +class pinstripe +{ +public: + pinstripe() { createColors(); } + void setDimensions( int x, int y ) { _mw = x; _mh = y; } + void createColors() + { + colors[0] = 0; colors[1] = RGB( 255, 255, 255 ); + } + + void draw( HDC dc ) + { + HPEN pen; + int lh = _mh / 4, row, cp; + for( int lw = 1; lw < 5; lw++ ) + { + cp = 0; + row = ( lw - 1 ) * lh; + for( int x = 0 + lw > 1 ? lw > 3 ? 2 : 1 : 0; x < _mw; x += lw ) + { + pen = CreatePen( PS_SOLID, lw, colors[cp] ); + ++cp %= 2; + + SelectObject( dc, pen ); + MoveToEx( dc, x, row, NULL ); + LineTo( dc, x, row + lh ); + DeleteObject( pen ); + } + } + } + +private: + int _mw, _mh; + DWORD colors[2]; +}; +//-------------------------------------------------------------------------------------------------- +pinstripe pin; + +//-------------------------------------------------------------------------------------------------- +void PaintWnd( HWND hWnd ) +{ + PAINTSTRUCT ps; + HDC hdc = BeginPaint( hWnd, &ps ); + pin.draw( hdc ); + EndPaint( hWnd, &ps ); +} +//-------------------------------------------------------------------------------------------------- +LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) +{ + switch( msg ) + { + case WM_DESTROY: PostQuitMessage( 0 ); break; + case WM_PAINT: PaintWnd( hWnd ); break; + default: + return DefWindowProc( hWnd, msg, wParam, lParam ); + } + return 0; +} +//-------------------------------------------------------------------------------------------------- +HWND InitAll( HINSTANCE hInstance ) +{ + WNDCLASSEX wcex; + ZeroMemory( &wcex, sizeof( wcex ) ); + + wcex.cbSize = sizeof( WNDCLASSEX ); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.hInstance = hInstance; + wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); + wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); + wcex.lpszClassName = "_BW_PS_"; + + RegisterClassEx( &wcex ); + return CreateWindow( "_BW_PS_", ".: Pinstripe -- PJorente :.", WS_POPUP, CW_USEDEFAULT, 0, 200, 200, NULL, NULL, hInstance, NULL ); +} +//-------------------------------------------------------------------------------------------------- +int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) +{ + srand( GetTickCount() ); + + HWND hwnd = InitAll( hInstance ); + if( !hwnd ) return -1; + + int mw = GetSystemMetrics( SM_CXSCREEN ), + mh = GetSystemMetrics( SM_CYSCREEN ); + + pin.setDimensions( mw, mh ); + + RECT rc = { 0, 0, mw, mh }; + + AdjustWindowRectEx( &rc, WS_POPUP, FALSE, 0 ); + int w = rc.right - rc.left, + h = rc.bottom - rc.top; + + int posX = ( GetSystemMetrics( SM_CXSCREEN ) >> 1 ) - ( w >> 1 ), + posY = ( GetSystemMetrics( SM_CYSCREEN ) >> 1 ) - ( h >> 1 ); + + SetWindowPos( hwnd, HWND_TOP, posX, posY, w, h, SWP_NOZORDER ); + ShowWindow( hwnd, nCmdShow ); + UpdateWindow( hwnd ); + + MSG msg; + ZeroMemory( &msg, sizeof( msg ) ); + while( msg.message != WM_QUIT ) + { + if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) + { + TranslateMessage( &msg ); + DispatchMessage( &msg ); + } + } + return UnregisterClass( "_BW_PS_", hInstance ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Pinstripe-Display/Perl-6/pinstripe-display.pl6 b/Task/Pinstripe-Display/Perl-6/pinstripe-display.pl6 new file mode 100644 index 0000000000..6304645aa6 --- /dev/null +++ b/Task/Pinstripe-Display/Perl-6/pinstripe-display.pl6 @@ -0,0 +1,22 @@ +my $HOR = 1280; +my $VERT = 720; + +my @colors = 0, 1; + +my $PPM = open "pinstripes.pgm", :w, :bin or die "Can't create pinstripes.ppm: $!"; + +$PPM.print: qq:to/EOH/; + P5 + # pinstripes.pgm + $HOR $VERT + 1 + EOH + +my $vzones = $VERT div 4; +for 1..4 -> $w { + my $hzones = ceiling $HOR / $w / +@colors; + my $line = Buf.new: ((@colors Xxx $w) xx $hzones).splice(0,$HOR); + $PPM.write: $line for ^$vzones; +} + +$PPM.close; diff --git a/Task/Pinstripe-Display/Racket/pinstripe-display.rkt b/Task/Pinstripe-Display/Racket/pinstripe-display.rkt new file mode 100644 index 0000000000..ef68ad8b96 --- /dev/null +++ b/Task/Pinstripe-Display/Racket/pinstripe-display.rkt @@ -0,0 +1,27 @@ +#lang racket/gui + +(define-values [W H] (get-display-size #t)) + +(define parts 4) + +(define (paint-pinstripe canvas dc) + (send dc set-pen "black" 0 'solid) + (send dc set-brush "black" 'solid) + (define H* (round (/ H parts))) + (for ([row parts]) + (define Y (* row H*)) + (for ([X (in-range 0 W (* (add1 row) 2))]) + (send dc draw-rectangle X Y (add1 row) H*)))) + +(define full-frame% + (class frame% + (define/override (on-subwindow-char r e) + (when (eq? 'escape (send e get-key-code)) + (send this show #f))) + (super-new + [label "Pinstripe"] [width W] [height H] + [style '(no-caption no-resize-border hide-menu-bar no-system-menu)]) + (define c (new canvas% [parent this] [paint-callback paint-pinstripe])) + (send this show #t))) + +(void (new full-frame%)) diff --git a/Task/Pinstripe-Printer/Racket/pinstripe-printer.rkt b/Task/Pinstripe-Printer/Racket/pinstripe-printer.rkt new file mode 100644 index 0000000000..62c1f21e37 --- /dev/null +++ b/Task/Pinstripe-Printer/Racket/pinstripe-printer.rkt @@ -0,0 +1,17 @@ +#lang racket/gui + +(define parts 4) + +(define dc (new printer-dc%)) +(send* dc (start-doc "Pinstripe") (start-page)) + +(define-values [W H] (send dc get-size)) +(send dc set-pen "black" 0 'solid) +(send dc set-brush "black" 'solid) +(define H* (round (/ H parts))) +(for ([row parts]) + (define Y (* row H*)) + (for ([X (in-range 0 W (* (add1 row) 2))]) + (send dc draw-rectangle X Y (add1 row) H*))) + +(send* dc (end-page) (end-doc)) diff --git a/Task/Plot-coordinate-pairs/C++/plot-coordinate-pairs.cpp b/Task/Plot-coordinate-pairs/C++/plot-coordinate-pairs.cpp new file mode 100644 index 0000000000..6db127b37f --- /dev/null +++ b/Task/Plot-coordinate-pairs/C++/plot-coordinate-pairs.cpp @@ -0,0 +1,223 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +const int HSTEP = 46, MWID = 40, MHEI = 471; +const float VSTEP = 2.3f; + +//-------------------------------------------------------------------------------------------------- +class vector2 +{ +public: + vector2() { x = y = 0; } + vector2( float a, float b ) { x = a; y = b; } + void set( float a, float b ) { x = a; y = b; } + float x, y; +}; +//-------------------------------------------------------------------------------------------------- +class myBitmap +{ +public: + myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} + ~myBitmap() + { + DeleteObject( pen ); + DeleteObject( brush ); + DeleteDC( hdc ); + DeleteObject( bmp ); + } + + bool create( int w, int h ) + { + BITMAPINFO bi; + ZeroMemory( &bi, sizeof( bi ) ); + bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); + bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biWidth = w; + bi.bmiHeader.biHeight = -h; + + HDC dc = GetDC( GetConsoleWindow() ); + bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); + if( !bmp ) return false; + + hdc = CreateCompatibleDC( dc ); + SelectObject( hdc, bmp ); + ReleaseDC( GetConsoleWindow(), dc ); + + width = w; height = h; + return true; + } + + void clear( BYTE clr = 0 ) + { + memset( pBits, clr, width * height * sizeof( DWORD ) ); + } + + void setBrushColor( DWORD bClr ) + { + if( brush ) DeleteObject( brush ); + brush = CreateSolidBrush( bClr ); + SelectObject( hdc, brush ); + } + + void setPenColor( DWORD c ) { clr = c; createPen(); } + + void setPenWidth( int w ) { wid = w; createPen(); } + + void saveBitmap( string path ) + { + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + DWORD wb; + + GetObject( bmp, sizeof( bitmap ), &bitmap ); + DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; + + ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); + ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); + ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); + + infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + infoheader.bmiHeader.biCompression = BI_RGB; + infoheader.bmiHeader.biPlanes = 1; + infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); + infoheader.bmiHeader.biHeight = bitmap.bmHeight; + infoheader.bmiHeader.biWidth = bitmap.bmWidth; + infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); + + fileheader.bfType = 0x4D42; + fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); + fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; + + GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); + + HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); + WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); + WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); + CloseHandle( file ); + + delete [] dwpBits; + } + + HDC getDC() const { return hdc; } + int getWidth() const { return width; } + int getHeight() const { return height; } + +private: + void createPen() + { + if( pen ) DeleteObject( pen ); + pen = CreatePen( PS_SOLID, wid, clr ); + SelectObject( hdc, pen ); + } + + HBITMAP bmp; + HDC hdc; + HPEN pen; + HBRUSH brush; + void *pBits; + int width, height, wid; + DWORD clr; +}; +//-------------------------------------------------------------------------------------------------- +class plot +{ +public: + plot() { bmp.create( 512, 512 ); } + + void draw( vector* pairs ) + { + bmp.clear( 0xff ); + drawGraph( pairs ); + plotIt( pairs ); + + HDC dc = GetDC( GetConsoleWindow() ); + BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); + ReleaseDC( GetConsoleWindow(), dc ); + //bmp.saveBitmap( "f:\\rc\\plot.bmp" ); + } + +private: + void drawGraph( vector* pairs ) + { + HDC dc = bmp.getDC(); + bmp.setPenColor( RGB( 240, 240, 240 ) ); + DWORD b = 11, c = 40, x; + RECT rc; char txt[8]; + + for( x = 0; x < pairs->size(); x++ ) + { + MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b ); + MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 ); + + wsprintf( txt, "%d", ( pairs->size() - x ) * 20 ); + SetRect( &rc, 0, b - 9, 36, b + 11 ); + DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); + + wsprintf( txt, "%d", x ); + SetRect( &rc, c - 8, 472, c + 8, 492 ); + DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE ); + + c += 46; b += 46; + } + + SetRect( &rc, 0, b - 9, 36, b + 11 ); + DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE ); + + bmp.setPenColor( 0 ); bmp.setPenWidth( 3 ); + MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 ); + MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 ); + } + + void plotIt( vector* pairs ) + { + HDC dc = bmp.getDC(); + HBRUSH br = CreateSolidBrush( 255 ); + RECT rc; + + bmp.setPenColor( 255 ); bmp.setPenWidth( 2 ); + vector::iterator it = pairs->begin(); + int a = MWID + HSTEP * static_cast( ( *it ).x ), b = MHEI - static_cast( VSTEP * ( *it ).y ); + MoveToEx( dc, a, b, NULL ); + SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br ); + + it++; + for( ; it < pairs->end(); it++ ) + { + a = MWID + HSTEP * static_cast( ( *it ).x ); + b = MHEI - static_cast( VSTEP * ( *it ).y ); + SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); + FillRect( dc, &rc, br ); LineTo( dc, a, b ); + } + + DeleteObject( br ); + } + + myBitmap bmp; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); + plot pt; + vector pairs; + pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) ); + pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) ); + pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) ); + pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) ); + pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) ); + + pt.draw( &pairs ); + system( "pause" ); + + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Plot-coordinate-pairs/Erlang/plot-coordinate-pairs.erl b/Task/Plot-coordinate-pairs/Erlang/plot-coordinate-pairs.erl new file mode 100644 index 0000000000..6f12a84ea0 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Erlang/plot-coordinate-pairs.erl @@ -0,0 +1,13 @@ +-module( plot_coordinate_pairs ). + +-export( [task/0, to_png_file/3] ). + +task() -> + Xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + Ys = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0], + File = "plot_coordinate_pairs", + to_png_file( File, Xs, Ys ). + +to_png_file( File, Xs, Ys ) -> + PNG = egd_chart:graph( [{File, lists:zip(Xs, Ys)}] ), + file:write_file( File ++ ".png", PNG ). diff --git a/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-1.rkt b/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-1.rkt new file mode 100644 index 0000000000..beafa1624a --- /dev/null +++ b/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-1.rkt @@ -0,0 +1,8 @@ +#lang racket +(require plot) + +(define x (build-list 10 values)) +(define y (list 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0)) + +(plot-new-window? #t) +(plot (points (map vector x y))) diff --git a/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-2.rkt b/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-2.rkt new file mode 100644 index 0000000000..beafa1624a --- /dev/null +++ b/Task/Plot-coordinate-pairs/Racket/plot-coordinate-pairs-2.rkt @@ -0,0 +1,8 @@ +#lang racket +(require plot) + +(define x (build-list 10 values)) +(define y (list 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0)) + +(plot-new-window? #t) +(plot (points (map vector x y))) diff --git a/Task/Pointers-and-references/Racket/pointers-and-references.rkt b/Task/Pointers-and-references/Racket/pointers-and-references.rkt new file mode 100644 index 0000000000..43784bb0be --- /dev/null +++ b/Task/Pointers-and-references/Racket/pointers-and-references.rkt @@ -0,0 +1,9 @@ +#lang racket + +(define (inc! b) (set-box! b (add1 (unbox b)))) + +(define b (box 0)) +(inc! b) +(inc! b) +(inc! b) +(unbox b) ; => 3 diff --git a/Task/Polymorphism/Seed7/polymorphism.seed7 b/Task/Polymorphism/Seed7/polymorphism.seed7 new file mode 100644 index 0000000000..1d532ba323 --- /dev/null +++ b/Task/Polymorphism/Seed7/polymorphism.seed7 @@ -0,0 +1,60 @@ +$ include "seed7_05.s7i"; + +const type: GraphicObj is new interface; + +const proc: print (in GraphicObj: aGraphicObj) is DYNAMIC; + + +const type: Point is new struct + var integer: x is 0; + var integer: y is 0; + end struct; + +type_implements_interface(Point, GraphicObj); + +const func Point: Point (in integer: x, in integer: y) is func + result + var Point: newPoint is Point.value; + begin + newPoint.x := x; + newPoint.y := y; + end func; + +const proc: print (in Point: aPoint) is func + begin + writeln("Point(" <& aPoint.x <& ", " <& aPoint.y <& ")"); + end func; + + +const type: Circle is sub Point struct + var integer: r is 0; + end struct; + +type_implements_interface(Circle, GraphicObj); + +const func Circle: Circle (in integer: x, in integer: y, in integer: r) is func + result + var Circle: newCircle is Circle.value; + begin + newCircle.x := x; + newCircle.y := y; + newCircle.r := r; + end func; + +const proc: print (in Circle: aCircle) is func + begin + writeln("Circle(" <& aCircle.x <& ", " <& aCircle.y <& ", " <& aCircle.r <& ")"); + end func; + + +const proc: main is func + local + var Point: pnt is Point(1, 2); + var Circle: circ is Circle(3, 4, 5); + var GraphicObj: graph is Point.value; + begin + graph := pnt; + print(graph); + graph := circ; + print(graph); + end func; diff --git a/Task/Polynomial-regression/Racket/polynomial-regression.rkt b/Task/Polynomial-regression/Racket/polynomial-regression.rkt new file mode 100644 index 0000000000..596eb5609f --- /dev/null +++ b/Task/Polynomial-regression/Racket/polynomial-regression.rkt @@ -0,0 +1,18 @@ +#lang racket +(require math plot) + +(define xs '(0 1 2 3 4 5 6 7 8 9 10)) +(define ys '(1 6 17 34 57 86 121 162 209 262 321)) + +(define (fit x y n) + (define Y (->col-matrix y)) + (define V (vandermonde-matrix x (+ n 1))) + (define VT (matrix-transpose V)) + (matrix->vector (matrix-solve (matrix* VT V) (matrix* VT Y)))) + +(define ((poly v) x) + (for/sum ([c v] [i (in-naturals)]) + (* c (expt x i)))) + +(plot (list (points (map vector xs ys)) + (function (poly (fit xs ys 2))))) diff --git a/Task/Power-set/Racket/power-set.rkt b/Task/Power-set/Racket/power-set.rkt index b747ef39aa..edbcbd2d28 100644 --- a/Task/Power-set/Racket/power-set.rkt +++ b/Task/Power-set/Racket/power-set.rkt @@ -1,8 +1,6 @@ ;;; Direct translation of 'functional' ruby method (define (powerset s) - (for/fold ([outer-set (set(set))]) - ([element s]) + (for/fold ([outer-set (set(set))]) ([element s]) (set-union outer-set - (list->set (set-map - outer-set - (λ(inner-set)(set-add inner-set element))))))) + (list->set (set-map outer-set + (λ(inner-set) (set-add inner-set element))))))) diff --git a/Task/Price-fraction/D/price-fraction.d b/Task/Price-fraction/D/price-fraction.d index 3066bbae36..c5a5589b99 100644 --- a/Task/Price-fraction/D/price-fraction.d +++ b/Task/Price-fraction/D/price-fraction.d @@ -1,20 +1,19 @@ -import std.stdio; +import std.stdio, std.range; double priceRounder(in double price) pure nothrow in { assert(price >= 0 && price <= 1.0); } body { - enum cin = [.06, .11, .16, .21, .26, .31, .36, .41, .46, .51, - .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01]; - enum cout = [.10, .18, .26, .32, .38, .44, .50, .54, .58, .62, - .66, .70, .74, .78, .82, .86, .90, .94, .98, 1.00]; - foreach (i, p; cin) - if (p >= price) - return cout[i]; - assert(0); + static immutable cin = [.06, .11, .16, .21, .26, .31, .36, .41, + .46, .51, .56, .61, .66, .71, .76, .81, + .86, .91, .96, 1.01], + cout = [.10, .18, .26, .32, .38, .44, .50, .54, + .58, .62, .66, .70, .74, .78, .82, .86, + .90, .94, .98, 1.00]; + return cout[cin.assumeSorted.lowerBound(price).length]; } void main() { - foreach (price; [0.7388727, 0.8593103, 0.826687, 0.3444635]) - writeln(priceRounder(price)); + foreach (const price; [0.7388727, 0.8593103, 0.826687, 0.3444635]) + price.priceRounder.writeln; } diff --git a/Task/Price-fraction/PL-I/price-fraction-1.pli b/Task/Price-fraction/PL-I/price-fraction-1.pli new file mode 100644 index 0000000000..146ee499cd --- /dev/null +++ b/Task/Price-fraction/PL-I/price-fraction-1.pli @@ -0,0 +1,14 @@ +declare t(20) fixed decimal (3,2) static initial ( + .06, .11, .16, .21, .26, .31, .36, .41, .46, .51, + .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01); +declare r(20) fixed decimal (3,2) static initial ( + .10, .18, .26, .32, .38, .44, .50, .54, .58, .62, + .66, .70, .74, .78, .82, .86, .90, .94, .98, 1); +declare x float, d fixed decimal (3,2); +declare i fixed binary; + +loop: + do i = 1 to 20; + if x < t(i) then + do; d = r(i); leave loop; end; + end; diff --git a/Task/Price-fraction/PL-I/price-fraction-2.pli b/Task/Price-fraction/PL-I/price-fraction-2.pli new file mode 100644 index 0000000000..6677a6809b --- /dev/null +++ b/Task/Price-fraction/PL-I/price-fraction-2.pli @@ -0,0 +1,15 @@ +cpt: Proc Options(main); + Dcl x Dec Fixed(4,2); + Do x=0 To 1 By 0.01; + Put Edit(x,' -> ',cp(x))(Skip,f(4,2),a,f(4,2)); + End; + cp: Proc(p) Returns(Dec Fixed(4,2)); + Dcl r(20) Dec Fixed(4,2) static init( + .10, .18, .26, .32, .38, .44, .50, .54, .58, .62, + .66, .70, .74, .78, .82, .86, .90, .94, .98, 1); + Dcl p Dec Fixed(4,2); + Dcl i Bin Fixed; + i=trunc((100*p-1)/5)+1; + Return(r(i)); + End; + End; diff --git a/Task/Price-fraction/REXX/price-fraction-1.rexx b/Task/Price-fraction/REXX/price-fraction-1.rexx new file mode 100644 index 0000000000..ba1e35c758 --- /dev/null +++ b/Task/Price-fraction/REXX/price-fraction-1.rexx @@ -0,0 +1,32 @@ +/*REXX program to rescale a (decimal fraction) price (0.99 ──► 1.00).*/ +pad=' ' /*for inserting spaces into msg. */ + do j=0 to 1 by .01; if j==0 then j=0.00 /*special case.*/ + say pad 'original price ──►' j pad adjPrice(j) " ◄── adjusted price" + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ADJPRICE subroutine─────────────────*/ +adjPrice: procedure; parse arg ? + select + when ?<0.06 then ?=0.10 + when ?<0.11 then ?=0.18 + when ?<0.16 then ?=0.26 + when ?<0.21 then ?=0.32 + when ?<0.26 then ?=0.38 + when ?<0.31 then ?=0.44 + when ?<0.36 then ?=0.50 + when ?<0.41 then ?=0.54 + when ?<0.46 then ?=0.58 + when ?<0.51 then ?=0.62 + when ?<0.56 then ?=0.66 + when ?<0.61 then ?=0.70 + when ?<0.66 then ?=0.74 + when ?<0.71 then ?=0.78 + when ?<0.76 then ?=0.82 + when ?<0.81 then ?=0.86 + when ?<0.86 then ?=0.90 + when ?<0.91 then ?=0.94 + when ?<0.96 then ?=0.98 + when ?<1.01 then ?=1.00 + otherwise nop + end /*select*/ +return ? diff --git a/Task/Price-fraction/REXX/price-fraction-2.rexx b/Task/Price-fraction/REXX/price-fraction-2.rexx new file mode 100644 index 0000000000..a6503aca45 --- /dev/null +++ b/Task/Price-fraction/REXX/price-fraction-2.rexx @@ -0,0 +1,22 @@ +/* REXX *************************************************************** +* Inspired by some other solutions tested with version 1 (above) +* 20.04.2013 Walter Pachl +**********************************************************************/ +Do x=0 To 1 By 0.01 + old=adjprice(x) + new=adjprice2(x) + If old<>new Then tag='??' + else tag='' + Say x old new tag + End +Exit + +adjprice2: Procedure + rl='0.10 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62', + '0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.00' + Do i=1 To 20 + Parse Var rl r.i rl + End + Parse Arg p + i=((100*p-1)%5+1) + Return r.i diff --git a/Task/Price-fraction/Racket/price-fraction.rkt b/Task/Price-fraction/Racket/price-fraction.rkt new file mode 100644 index 0000000000..a07939ee31 --- /dev/null +++ b/Task/Price-fraction/Racket/price-fraction.rkt @@ -0,0 +1,11 @@ +#lang racket + +(define table + '([0 #f] + [0.06 0.10] [0.11 0.18] [0.16 0.26] [0.21 0.32] [0.26 0.38] [0.31 0.44] + [0.36 0.50] [0.41 0.54] [0.46 0.58] [0.51 0.62] [0.56 0.66] [0.61 0.70] + [0.66 0.74] [0.71 0.78] [0.76 0.82] [0.81 0.86] [0.86 0.90] [0.91 0.94] + [0.96 0.98] [1.01 1.00]) + + ;; returns #f for negatives or values >= 1.01 +(define (convert x) (for/or ([c table]) (and (< x (car c)) (cadr c)))) diff --git a/Task/Price-fraction/Raven/price-fraction.raven b/Task/Price-fraction/Raven/price-fraction.raven new file mode 100644 index 0000000000..eac00faf17 --- /dev/null +++ b/Task/Price-fraction/Raven/price-fraction.raven @@ -0,0 +1,6 @@ +define getScaleFactor use $v + [ 0.1 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62 0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.0 ] as $vals + $v 100 * 1 - 5 / 20 min 0 max 1 prefer dup $v "val: %g indx: %d\n" print $vals swap get + +0 100 9 range each + 100.0 / dup getScaleFactor swap "%.2g -> %.2g\n" print diff --git a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-1.cobol b/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-1.cobol index eb7e15bd54..80dfb488f2 100644 --- a/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-1.cobol +++ b/Task/Primality-by-trial-division/COBOL/primality-by-trial-division-1.cobol @@ -1,44 +1,54 @@ -Identification division. -Program-id. prime-div. + >>source format is free +identification division. +program-id. prime-div. -Data division. -Working-storage section. +data division. +working-storage section. -* The number for which we are testing primality. +*> The number for which we are testing primality. 01 num pic 9(6) value 1. 01 out-num pic z(6). -* Division-related stuff. +*> Division-related stuff. 01 div pic 9(6). 01 div-lim pic 9(6). 01 rem pic 9(6). 88 not-prime value 0. -Procedure division. -Main. - Perform until num = 0 +procedure division. +main. + perform until num = 0 perform get-a-num perform is-prime move num to out-num - if not-prime display out-num " is not prime." - else display out-num " is prime." - end-perform. - Stop run. + if not-prime + display out-num " is not prime." + else + display out-num " is prime." + end-if + end-perform -Is-prime. - if num < 4 + stop run + . + +is-prime. + if num = 1 + move 0 to rem + else if num < 4 move 1 to rem else compute div-lim = function sqrt(num) + 1 - perform - with test after - varying div from 2 by 1 - until div = div-lim or not-prime + perform with test after varying div from 2 by 1 + until (div = div-lim) or not-prime compute rem = function mod(num, div) - end-perform - end-if. + end-perform + end-if + . -Get-a-num. - Display "Enter a possible prime number (0 to stop): " with no advancing. - Accept num. - If num = 0 stop run. +get-a-num. + display "Enter a possible prime number (0 to stop): " with no advancing + accept num + if num = 0 + stop run + end-if + . diff --git a/Task/Primality-by-trial-division/FBSL/primality-by-trial-division.fbsl b/Task/Primality-by-trial-division/FBSL/primality-by-trial-division.fbsl new file mode 100644 index 0000000000..2c54648481 --- /dev/null +++ b/Task/Primality-by-trial-division/FBSL/primality-by-trial-division.fbsl @@ -0,0 +1,39 @@ +#APPTYPE CONSOLE + +FUNCTION ISPRIME(n AS INTEGER) AS INTEGER + IF n = 2 THEN + RETURN TRUE + ELSEIF n <= 1 ORELSE n MOD 2 = 0 THEN + RETURN FALSE + ELSE + FOR DIM i = 3 TO SQR(n) STEP 2 + IF n MOD i = 0 THEN + RETURN FALSE + END IF + NEXT + RETURN TRUE + END IF +END FUNCTION + +FUNCTION ISPRIME2(N AS INTEGER) AS INTEGER + IF N <= 1 THEN RETURN FALSE + DIM I AS INTEGER = 2 + WHILE I * I <= N + IF N MOD I = 0 THEN + RETURN FALSE + END IF + I = I + 1 + WEND + RETURN TRUE +END FUNCTION + +' Test and display primes 1 .. 50 +DIM n AS INTEGER + +FOR n = 1 TO 50 + IF ISPRIME(n) THEN + PRINT n, " "; + END IF +NEXT + +PAUSE diff --git a/Task/Primality-by-trial-division/Racket/primality-by-trial-division.rkt b/Task/Primality-by-trial-division/Racket/primality-by-trial-division.rkt new file mode 100644 index 0000000000..debe504d44 --- /dev/null +++ b/Task/Primality-by-trial-division/Racket/primality-by-trial-division.rkt @@ -0,0 +1,8 @@ +#lang racket + +(define (prime? number) + (cond ((not (positive? number)) #f) + ((= 1 number) #f) + ((even? number) (= 2 number)) + (else (for/and ((i (in-range 3 (ceiling (sqrt number))))) + (not (zero? (remainder number i))))))) diff --git a/Task/Primality-by-trial-division/SQL/primality-by-trial-division.sql b/Task/Primality-by-trial-division/SQL/primality-by-trial-division.sql new file mode 100644 index 0000000000..d8c6063866 --- /dev/null +++ b/Task/Primality-by-trial-division/SQL/primality-by-trial-division.sql @@ -0,0 +1,29 @@ +declare @number int +set @number = 514229 -- number to check + +;with cte(number) as +( + select 2 + union all + select number+1 + from cte + where number+1 < @number +) +select + cast(@number as varchar(100)) + + case + when exists + ( + select * + from + ( + select number, @number % number modNumber + from cte + ) tmp + where tmp.modNumber = 0 + ) + then ' is composite' + else + ' is prime' + end primalityTest +option (maxrecursion 0) diff --git a/Task/Prime-decomposition/Python/prime-decomposition-2.py b/Task/Prime-decomposition/Python/prime-decomposition-2.py index f714b346e2..fc2495b4a6 100644 --- a/Task/Prime-decomposition/Python/prime-decomposition-2.py +++ b/Task/Prime-decomposition/Python/prime-decomposition-2.py @@ -1,18 +1,21 @@ -primelist = [2,3] +primelist = [2, 3] def is_prime(n): - for y in primes(): - if not n % y: return False - if n > y * y: return True + if n in primelist: return True + if n < primelist[-1]: return False + + for y in primes(): + if not n % y: return False + if n < y * y: return True def primes(): - for n in primelist: yield n + for n in primelist: yield n - n = primelist[-1] + 2 - while True: - n += 2 - for x in primelist: - if not n % x: break - if x * x > n: - primelist.append(n) - yield n - break + n = primelist[-1] + while True: + n += 2 + for x in primelist: + if not n % x: break + if x * x > n: + primelist.append(n) + yield n + break diff --git a/Task/Prime-decomposition/Racket/prime-decomposition-1.rkt b/Task/Prime-decomposition/Racket/prime-decomposition-1.rkt new file mode 100644 index 0000000000..a1efe7bc50 --- /dev/null +++ b/Task/Prime-decomposition/Racket/prime-decomposition-1.rkt @@ -0,0 +1,4 @@ +#lang racket +(require math) +(define (factors n) + (append-map (λ (x) (make-list (cadr x) (car x))) (factorize n))) diff --git a/Task/Prime-decomposition/Racket/prime-decomposition-2.rkt b/Task/Prime-decomposition/Racket/prime-decomposition-2.rkt new file mode 100644 index 0000000000..c629ec8582 --- /dev/null +++ b/Task/Prime-decomposition/Racket/prime-decomposition-2.rkt @@ -0,0 +1,7 @@ +#lang racket +(define (factors number) + (let loop ([n number] [i 2]) + (if (= n 1) + '() + (let-values ([(q r) (quotient/remainder n i)]) + (if (zero? r) (cons i (loop q i)) (loop n (add1 i))))))) diff --git a/Task/Priority-queue/Haskell/priority-queue-2.hs b/Task/Priority-queue/Haskell/priority-queue-2.hs index 5af2976c9c..299d0926d5 100644 --- a/Task/Priority-queue/Haskell/priority-queue-2.hs +++ b/Task/Priority-queue/Haskell/priority-queue-2.hs @@ -28,17 +28,16 @@ hLength Nil = 0 hLength h = cnt h hFromList :: (Ord a) => [a] -> MinHeap a -hFromList xs = hlist Nil xs where - hlist h [] = h - hlist h (x:xs) = hlist (hPush x h) xs +hFromList = foldl (flip hPush) Nil hToList :: (Ord a) => MinHeap a -> [a] -hToList Nil = [] -hToList h = x:hToList hh where (x,hh) = hPop h +hToList = unfoldr f where + f Nil = Nothing + f h = Just $ hPop h -main = mapM print $ (hToList (hFromList [ +main = mapM_ print $ hToList $ hFromList [ (3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), - (2, "Tax return")])) + (2, "Tax return")] diff --git a/Task/Priority-queue/Racket/priority-queue-1.rkt b/Task/Priority-queue/Racket/priority-queue-1.rkt new file mode 100644 index 0000000000..1363b8b8f7 --- /dev/null +++ b/Task/Priority-queue/Racket/priority-queue-1.rkt @@ -0,0 +1,24 @@ +#lang racket +(require data/heap) + +(define pq (make-heap (λ(x y) (<= (second x) (second y))))) + +(define (insert! x pri) + (heap-add! pq (list pri x))) + +(define (remove-min!) + (begin0 + (first (heap-min pq)) + (heap-remove-min! pq))) + +(insert! 3 "Clear drains") +(insert! 4 "Feed cat") +(insert! 5 "Make tea") +(insert! 1 "Solve RC tasks") +(insert! 2 "Tax return") + +(remove-min!) +(remove-min!) +(remove-min!) +(remove-min!) +(remove-min!) diff --git a/Task/Priority-queue/Racket/priority-queue-2.rkt b/Task/Priority-queue/Racket/priority-queue-2.rkt new file mode 100644 index 0000000000..1e7d8deba9 --- /dev/null +++ b/Task/Priority-queue/Racket/priority-queue-2.rkt @@ -0,0 +1,5 @@ +"Solve RC tasks" +"Tax return" +"Clear drains" +"Feed cat" +"Make tea" diff --git a/Task/Probabilistic-choice/Racket/probabilistic-choice.rkt b/Task/Probabilistic-choice/Racket/probabilistic-choice.rkt new file mode 100644 index 0000000000..3637cc2bf2 --- /dev/null +++ b/Task/Probabilistic-choice/Racket/probabilistic-choice.rkt @@ -0,0 +1,87 @@ +#lang racket +;;; returns a probabalistic choice from the sequence choices +;;; choices generates two values -- the chosen value and a +;;; probability (weight) of the choice. +;;; +;;; Note that a hash where keys are choices and values are probabilities +;;; is such a sequence. +;;; +;;; if the total probability < 1 then choice could return #f +;;; if the total probability > 1 then some choices may be impossible +(define (probabalistic-choice choices) + (let-values + (((_ choice) ;; the fold provides two values, we only need the second + ;; the first will always be a negative number showing that + ;; I've run out of random steam + (for/fold + ((rnd (random)) + (choice #f)) + (((v p) choices) + #:break (<= rnd 0)) + (values (- rnd p) v)))) + choice)) + +;;; ditto, but all probabilities must be exact rationals +;;; the optional lcd +;;; +;;; not the most efficient, since it provides a wrapper (and demo) +;;; for p-c/i-w below +(define (probabalistic-choice/exact + choices + #:gcd (GCD (/ (apply gcd (hash-values choices))))) + (probabalistic-choice/integer-weights + (for/hash (((k v) choices)) + (values k (* v GCD))) + #:sum-of-weights GCD)) + +;;; this proves useful in Rock-Paper-Scissors +(define (probabalistic-choice/integer-weights + choices + #:sum-of-weights (sum-of-weights (apply + (hash-values choices)))) + (let-values + (((_ choice) + (for/fold + ((rnd (random sum-of-weights)) + (choice #f)) + (((v p) choices) + #:break (< rnd 0)) + (values (- rnd p) v)))) + choice)) + +(module+ test + (define test-samples (make-parameter 1000000)) + + (define (test-p-c-function f w) + (define test-selection (make-hash)) + (for* ((i (in-range 0 (test-samples))) + (c (in-value (f w)))) + (when (zero? (modulo i 100000)) (eprintf "~a," (quotient i 100000))) + (hash-update! test-selection c add1 0)) + (printf "~a~%choice\tcount\texpected\tratio\terror~%" f) + (for* (((k v) (in-hash test-selection)) + (e (in-value (* (test-samples) (hash-ref w k))))) + (printf "~a\t~a\t~a\t~a\t~a%~%" + k v e + (/ v (test-samples)) + (real->decimal-string + (exact->inexact (* 100 (/ (- v e) e))))))) + + (define test-weightings/rosetta + (hash + 'aleph 1/5 + 'beth 1/6 + 'gimel 1/7 + 'daleth 1/8 + 'he 1/9 + 'waw 1/10 + 'zayin 1/11 + 'heth 1759/27720; adjusted so that probabilities add to 1 + )) + + (define test-weightings/50:50 (hash 'woo 1/2 'yay 1/2)) + (define test-weightings/1:2:3 (hash 'woo 1 'yay 2 'foo 3)) + + (test-p-c-function probabalistic-choice test-weightings/50:50) + (test-p-c-function probabalistic-choice/exact test-weightings/50:50) + (test-p-c-function probabalistic-choice test-weightings/rosetta) + (test-p-c-function probabalistic-choice/exact test-weightings/rosetta)) diff --git a/Task/Problem-of-Apollonius/Racket/problem-of-apollonius.rkt b/Task/Problem-of-Apollonius/Racket/problem-of-apollonius.rkt new file mode 100644 index 0000000000..9cc0af59e6 --- /dev/null +++ b/Task/Problem-of-Apollonius/Racket/problem-of-apollonius.rkt @@ -0,0 +1,84 @@ +#lang slideshow + +(struct circle (x y r) #:prefab) + +(define (apollonius c1 c2 c3 s1 s2 s3) + (define x1 (circle-x c1)) + (define y1 (circle-y c1)) + (define r1 (circle-r c1)) + (define x2 (circle-x c2)) + (define y2 (circle-y c2)) + (define r2 (circle-r c2)) + (define x3 (circle-x c3)) + (define y3 (circle-y c3)) + (define r3 (circle-r c3)) + + (define v11 (- (* 2 x2) (* 2 x1))) + (define v12 (- (* 2 y2) (* 2 y1))) + (define v13 (+ (- (* x1 x1) (* x2 x2)) + (- (* y1 y1) (* y2 y2)) + (- (* r2 r2) (* r1 r1)))) + (define v14 (- (* 2 s2 r2) (* 2 s1 r1))) + + (define v21 (- (* 2 x3) (* 2 x2))) + (define v22 (- (* 2 y3) (* 2 y2))) + (define v23 (+ (- (* x2 x2) (* x3 x3)) + (- (* y2 y2) (* y3 y3)) + (- (* r3 r3) (* r2 r2)))) + (define v24 (- (* 2 s3 r3) (* 2 s2 r2))) + + (define w12 (/ v12 v11)) + (define w13 (/ v13 v11)) + (define w14 (/ v14 v11)) + + (define w22 (- (/ v22 v21) w12)) + (define w23 (- (/ v23 v21) w13)) + (define w24 (- (/ v24 v21) w14)) + + (define P (- (/ w23 w22))) + (define Q (/ w24 w22)) + (define M (- (+ (* w12 P) w13))) + (define N (- w14 (* w12 Q))) + + (define a (+ (* N N) (* Q Q) -1)) + (define b (+ (- (* 2 M N) (* 2 N x1)) + (- (* 2 P Q) (* 2 Q y1)) + (* 2 s1 r1))) + (define c (- (+ (* x1 x1) (* M M) (* P P) (* y1 y1)) + (+ (* 2 M x1) (* 2 P y1) (* r1 r1)))) + + (define D (- (* b b) (* 4 a c))) + (define rs (/ (- (+ b (sqrt D))) (* 2 a))) + (define xs (+ M (* N rs))) + (define ys (+ P (* Q rs))) + (circle xs ys rs)) + +(define c1 (circle 0.0 0.0 1.0)) +(define c2 (circle 4.0 0.0 1.0)) +(define c3 (circle 2.0 4.0 2.0)) + +;; print solutions +(apollonius c1 c2 c3 1.0 1.0 1.0) +(apollonius c1 c2 c3 -1.0 -1.0 -1.0) + +;; visualize solutions +(require racket/gui/base) +(define (show-circles . circles+colors) + (define f (new frame% [label "Apollonius"] [width 300] [height 300])) + (define c + (new canvas% [parent f] + [paint-callback + (lambda (canvas dc) + (send* dc (set-origin 100 100) + (set-scale 20 20) + (set-pen "black" 1/10 'solid) + (set-brush "white" 'transparent)) + (for ([x circles+colors]) + (if (string? x) + (send dc set-pen x 1/5 'solid) + (let ([x (circle-x x)] [y (circle-y x)] [r (circle-r x)]) + (send dc draw-ellipse (- x r) (- y r) (* 2 r) (* 2 r))))))])) + (send f show #t)) +(show-circles "black" c1 c2 c3 + "green" (apollonius c1 c2 c3 1.0 1.0 1.0) + "red" (apollonius c1 c2 c3 -1.0 -1.0 -1.0)) diff --git a/Task/Program-name/Aime/program-name.aime b/Task/Program-name/Aime/program-name.aime new file mode 100644 index 0000000000..8677b28b15 --- /dev/null +++ b/Task/Program-name/Aime/program-name.aime @@ -0,0 +1,2 @@ +o_text(argv(0)); +o_byte('\n'); diff --git a/Task/Program-name/Erlang/program-name.erl b/Task/Program-name/Erlang/program-name.erl index 73deffc821..47c7bc807f 100644 --- a/Task/Program-name/Erlang/program-name.erl +++ b/Task/Program-name/Erlang/program-name.erl @@ -1,5 +1,15 @@ --module(scriptname). +%% Compile +%% +%% erlc scriptname.erl +%% +%% Run +%% +%% erl -noshell -s scriptname -main(_) -> - Program = ?FILE, - io:format("Program: ~s~n", [Program]). +-module(scriptname). +-export([start/0]). + +start() -> + Program = ?FILE, + io:format("Program: ~s~n", [Program]), + init:stop(). diff --git a/Task/Program-name/Raven/program-name.raven b/Task/Program-name/Raven/program-name.raven new file mode 100644 index 0000000000..06df3e83bc --- /dev/null +++ b/Task/Program-name/Raven/program-name.raven @@ -0,0 +1 @@ +ARGS list " " join "%s\n" print diff --git a/Task/Program-termination/Aime/program-termination.aime b/Task/Program-termination/Aime/program-termination.aime new file mode 100644 index 0000000000..f20f2d0920 --- /dev/null +++ b/Task/Program-termination/Aime/program-termination.aime @@ -0,0 +1,15 @@ +void +f1(integer a) +{ + if (a) { + exit(1); + } +} + +integer +main(void) +{ + f1(3); + + return 0; +} diff --git a/Task/Program-termination/Erlang/program-termination-1.erl b/Task/Program-termination/Erlang/program-termination-1.erl new file mode 100644 index 0000000000..6b03dcce60 --- /dev/null +++ b/Task/Program-termination/Erlang/program-termination-1.erl @@ -0,0 +1,3 @@ +% Implemented by Arjun Sunel +if problem -> + exit(1). diff --git a/Task/Program-termination/Erlang/program-termination-2.erl b/Task/Program-termination/Erlang/program-termination-2.erl new file mode 100644 index 0000000000..ce3c824111 --- /dev/null +++ b/Task/Program-termination/Erlang/program-termination-2.erl @@ -0,0 +1,3 @@ +% Implemented by Arjun Sunel +if problem -> + halt(). diff --git a/Task/Program-termination/Racket/program-termination-1.rkt b/Task/Program-termination/Racket/program-termination-1.rkt new file mode 100644 index 0000000000..7a418699a9 --- /dev/null +++ b/Task/Program-termination/Racket/program-termination-1.rkt @@ -0,0 +1,3 @@ +#lang racket +(run-stuff) +(when (something-bad-happened) (exit 1)) diff --git a/Task/Program-termination/Racket/program-termination-2.rkt b/Task/Program-termination/Racket/program-termination-2.rkt new file mode 100644 index 0000000000..24cd9ffeb8 --- /dev/null +++ b/Task/Program-termination/Racket/program-termination-2.rkt @@ -0,0 +1,8 @@ +#lang racket +(parameterize ([current-custodian (make-custodian)]) + (define (loop) (printf "looping\n") (sleep 1) (loop)) + (thread loop) ; start a thread under the new custodian + (sleep 5) + ;; kill it: this will kill the thread, and any other opened resources + ;; like file ports, network connections, etc + (custodian-shutdown-all (current-custodian))) diff --git a/Task/Pythagorean-triples/Racket/pythagorean-triples.rkt b/Task/Pythagorean-triples/Racket/pythagorean-triples.rkt new file mode 100644 index 0000000000..307df0a6b6 --- /dev/null +++ b/Task/Pythagorean-triples/Racket/pythagorean-triples.rkt @@ -0,0 +1,45 @@ +#lang racket + +#| Euclid's enumeration formula and counting is fast enough for extra credit. + + For maximum perimeter P₀, the primitive triples are enumerated by n,m with: + + 1 ≤ n < m + perimeter P(n, m) ≤ P₀ where P(n, m) = (m² - n²) + 2mn + (m² + n²) = 2m(m+n) + m and n of different parity and coprime. + + Since n < m, a simple close non-tight bound on n is P(n, n) < P₀. + For each of these the exact set of m's can be enumerated. + + Each primitive triple with perimeter p represents one triple for each kp ≤ P₀, + of which there are floor(P₀/p) k's. |# + +(define (P n m) (* 2 m (+ m n))) +(define (number-of-triples P₀) + (for/fold ([primitive 0] [all 0]) + ([n (in-naturals 1)] + #:break (>= (P n n) P₀)) + (for*/fold ([primitive′ primitive] [all′ all]) + ([m (in-naturals (+ n 1))] + #:break (> (P n m) P₀) + #:when (and (odd? (- m n)) (coprime? m n))) + (values (+ primitive′ 1) + (+ all′ (quotient P₀ (P n m))))))) + + +(define (print-results P₀) + (define-values (primitive all) (number-of-triples P₀)) + (printf "~a ~a:\n ~a, ~a.\n" + "Number of Pythagorean triples and primitive triples with perimeter ≤" + P₀ + all primitive)) +(print-results 100) +(time (print-results (* 100 1000 1000))) + +#| + Number of Pythagorean triples and primitive triples with perimeter ≤ 100: + 17, 7. + Number of Pythagorean triples and primitive triples with perimeter ≤ 100000000: + 113236940, 7023027. + cpu time: 11976 real time: 12215 gc time: 2381 +|# diff --git a/Task/QR-decomposition/J/qr-decomposition-1.j b/Task/QR-decomposition/J/qr-decomposition-1.j index 36424a8cce..0b95cfe834 100644 --- a/Task/QR-decomposition/J/qr-decomposition-1.j +++ b/Task/QR-decomposition/J/qr-decomposition-1.j @@ -1,16 +1 @@ -mp=: +/ . * NB. matrix product -h =: +@|: NB. conjugate transpose - -QR=: 3 : 0 - n=.{:$A=.y - if. 1>:n do. - A ((% {.@,) ; ]) %:(h A) mp A - else. - m =.>.n%2 - A0=.m{."1 A - A1=.m}."1 A - 'Q0 R0'=.QR A0 - 'Q1 R1'=.QR A1 - Q0 mp T=.(h Q0) mp A1 - (Q0,.Q1);(R0,.T),(-n){."1 R1 - end. -) + QR =: 128!:0 diff --git a/Task/QR-decomposition/J/qr-decomposition-2.j b/Task/QR-decomposition/J/qr-decomposition-2.j index 103e2256cb..acaa491aa9 100644 --- a/Task/QR-decomposition/J/qr-decomposition-2.j +++ b/Task/QR-decomposition/J/qr-decomposition-2.j @@ -1,6 +1,16 @@ - QR x:12 _51 4,6 167 _68,:_4 24 _41 -┌────────────────────┬──────────┐ -│ 6r7 _69r175 _58r175│14 21 _14│ -│ 3r7 158r175 6r175│ 0 175 _70│ -│_2r7 6r35 _33r35│ 0 0 35│ -└────────────────────┴──────────┘ + mp=: +/ . * NB. matrix product + h =: +@|: NB. conjugate transpose + + QR=: 3 : 0 + n=.{:$A=.y + if. 1>:n do. + A ((% {.@,) ; ]) %:(h A) mp A + else. + m =.>.n%2 + A0=.m{."1 A + A1=.m}."1 A + 'Q0 R0'=.QR A0 + 'Q1 R1'=.QR A1 - Q0 mp T=.(h Q0) mp A1 + (Q0,.Q1);(R0,.T),(-n){."1 R1 + end. + ) diff --git a/Task/QR-decomposition/J/qr-decomposition-3.j b/Task/QR-decomposition/J/qr-decomposition-3.j index 7cefa21018..a88c2b8a03 100644 --- a/Task/QR-decomposition/J/qr-decomposition-3.j +++ b/Task/QR-decomposition/J/qr-decomposition-3.j @@ -1,4 +1,6 @@ - X=:i.# Y=:1 6 17 34 57 86 121 162 209 262 321 - 'Q R'=: QR X ^/ i.3 - R %.~(|:Q)+/ .* Y -1 2 3 + QR 12 _51 4,6 167 _68,:_4 24 _41 ++-----------------------------+----------+ +| 0.857143 _0.394286 _0.331429|14 21 _14| +| 0.428571 0.902857 0.0342857| 0 175 _70| +|_0.285714 0.171429 _0.942857| 0 0 35| ++-----------------------------+----------+ diff --git a/Task/QR-decomposition/J/qr-decomposition-4.j b/Task/QR-decomposition/J/qr-decomposition-4.j new file mode 100644 index 0000000000..7cefa21018 --- /dev/null +++ b/Task/QR-decomposition/J/qr-decomposition-4.j @@ -0,0 +1,4 @@ + X=:i.# Y=:1 6 17 34 57 86 121 162 209 262 321 + 'Q R'=: QR X ^/ i.3 + R %.~(|:Q)+/ .* Y +1 2 3 diff --git a/Task/QR-decomposition/Racket/qr-decomposition-1.rkt b/Task/QR-decomposition/Racket/qr-decomposition-1.rkt new file mode 100644 index 0000000000..b996839021 --- /dev/null +++ b/Task/QR-decomposition/Racket/qr-decomposition-1.rkt @@ -0,0 +1,6 @@ +> (require math) +> (matrix-qr (matrix [[12 -51 4] + [ 6 167 -68] + [-4 24 -41]])) +(array #[#[6/7 -69/175 -58/175] #[3/7 158/175 6/175] #[-2/7 6/35 -33/35]]) +(array #[#[14 21 -14] #[0 175 -70] #[0 0 35]]) diff --git a/Task/QR-decomposition/Racket/qr-decomposition-2.rkt b/Task/QR-decomposition/Racket/qr-decomposition-2.rkt new file mode 100644 index 0000000000..f9a2742b1e --- /dev/null +++ b/Task/QR-decomposition/Racket/qr-decomposition-2.rkt @@ -0,0 +1,29 @@ +#lang racket +(require math/matrix math/array) +(define-values (T I col size) + (values ; short names + matrix-transpose identity-matrix matrix-col matrix-num-rows)) + +(define (scale c A) (matrix-scale A c)) +(define (unit n i) (build-matrix n 1 (λ (j _) (if (= j i) 1 0)))) + +(define (H u) + (matrix- (I (size u)) + (scale (/ 2 (matrix-dot u u)) + (matrix* u (T u))))) + +(define (normal a) + (define a0 (matrix-ref a 0 0)) + (matrix- a (scale (* (sgn a0) (matrix-2norm a)) + (unit (size a) 0)))) + +(define (QR A) + (define n (size A)) + (for/fold ([Q (I n)] [R A]) ([i (- n 1)]) + (define Hi (H (normal (submatrix R (:: i n) (:: i (+ i 1)))))) + (define Hi* (if (= i 0) Hi (block-diagonal-matrix (list (I i) Hi)))) + (values (matrix* Q Hi*) (matrix* Hi* R)))) + +(QR (matrix [[12 -51 4] + [ 6 167 -68] + [-4 24 -41]])) diff --git a/Task/QR-decomposition/Racket/qr-decomposition-3.rkt b/Task/QR-decomposition/Racket/qr-decomposition-3.rkt new file mode 100644 index 0000000000..a14b3e2cff --- /dev/null +++ b/Task/QR-decomposition/Racket/qr-decomposition-3.rkt @@ -0,0 +1,6 @@ +(array #[#[6/7 69/175 -58/175] + #[3/7 -158/175 6/175] + #[-2/7 -6/35 -33/35]]) +(array #[#[14 21 -14] + #[0 -175 70] + #[0 0 35]]) diff --git a/Task/Quaternion-type/J/quaternion-type-1.j b/Task/Quaternion-type/J/quaternion-type-1.j index ca295741f5..50142564eb 100644 --- a/Task/Quaternion-type/J/quaternion-type-1.j +++ b/Task/Quaternion-type/J/quaternion-type-1.j @@ -1,6 +1,6 @@ NB. utilities ip=: +/ .* NB. inner product - t4=. (_1^#:0 10 9 12)*0 7 16 23 A.=i.4 + T=. (_1^#:0 10 9 12)*0 7 16 23 A.=i.4 toQ=: 4&{."1 :[: NB. real scalars -> quaternion NB. task @@ -8,4 +8,4 @@ neg=: -&toQ NB. - y and x - y conj=: 1 _1 _1 _1 * toQ NB. + y add=: +&toQ NB. x + y - mul=: (ip t4 ip ])&toQ NB. x * y + mul=: (ip T ip ])&toQ NB. x * y diff --git a/Task/Quaternion-type/J/quaternion-type-2.j b/Task/Quaternion-type/J/quaternion-type-2.j index 15cca6a118..fdba752187 100644 --- a/Task/Quaternion-type/J/quaternion-type-2.j +++ b/Task/Quaternion-type/J/quaternion-type-2.j @@ -1,21 +1,20 @@ - q=: 1 2 3 4 - q1=: 2 3 4 5 - q2=: 3 4 5 6 - r=: 7 + T +1 0 0 0 +0 1 0 0 +0 0 1 0 +0 0 0 1 - norm q -5.47723 - neg q -_1 _2 _3 _4 - conj q -1 _2 _3 _4 - r add q -8 2 3 4 - q1 add q2 -5 7 9 11 - r mul q -7 14 21 28 - q1 mul q2 -_56 16 24 26 - q2 mul q1 -_56 18 20 28 +0 _1 0 0 +1 0 0 0 +0 0 0 _1 +0 0 1 0 + +0 0 _1 0 +0 0 0 1 +1 0 0 0 +0 _1 0 0 + +0 0 0 _1 +0 0 _1 0 +0 1 0 0 +1 0 0 0 diff --git a/Task/Quaternion-type/J/quaternion-type-3.j b/Task/Quaternion-type/J/quaternion-type-3.j new file mode 100644 index 0000000000..15cca6a118 --- /dev/null +++ b/Task/Quaternion-type/J/quaternion-type-3.j @@ -0,0 +1,21 @@ + q=: 1 2 3 4 + q1=: 2 3 4 5 + q2=: 3 4 5 6 + r=: 7 + + norm q +5.47723 + neg q +_1 _2 _3 _4 + conj q +1 _2 _3 _4 + r add q +8 2 3 4 + q1 add q2 +5 7 9 11 + r mul q +7 14 21 28 + q1 mul q2 +_56 16 24 26 + q2 mul q1 +_56 18 20 28 diff --git a/Task/Quaternion-type/Perl-6/quaternion-type.pl6 b/Task/Quaternion-type/Perl-6/quaternion-type.pl6 index 9b5cd3f7b5..11d6997c9a 100644 --- a/Task/Quaternion-type/Perl-6/quaternion-type.pl6 +++ b/Task/Quaternion-type/Perl-6/quaternion-type.pl6 @@ -1,4 +1,4 @@ -class Quaternion { +class Qu { has Real ( $.r, $.i, $.j, $.k ); multi method new ( Real $r, Real $i, Real $j, Real $k ) { @@ -10,8 +10,6 @@ class Quaternion { method norm ( ) { sqrt [+] self.reals X** 2 } } -subset Qu of Quaternion; # Makes a short alias - multi sub infix: ( Qu $a, Qu $b ) { [and] $a.reals Z== $b.reals } multi sub infix:<+> ( Qu $a, Real $b ) { $a.new: $b+$a.r, $a.i, $a.j, $a.k } multi sub infix:<+> ( Real $a, Qu $b ) { $b.new: $a+$b.r, $b.i, $b.j, $b.k } @@ -28,9 +26,9 @@ multi sub infix:<*> ( Qu $a, Qu $b ) { ( [+] @a_rijk Z* $k, $j, -$i, $r ); # k } -my Quaternion $q .= new: 1, 2, 3, 4; -my Quaternion $q1 .= new: 2, 3, 4, 5; -my Quaternion $q2 .= new: 3, 4, 5, 6; +my Qu $q .= new: 1, 2, 3, 4; +my Qu $q1 .= new: 2, 3, 4, 5; +my Qu $q2 .= new: 3, 4, 5, 6; my $r = 7; say "1) q norm = {$q.norm}"; diff --git a/Task/Quaternion-type/Prolog/quaternion-type-1.pro b/Task/Quaternion-type/Prolog/quaternion-type-1.pro new file mode 100644 index 0000000000..088110e996 --- /dev/null +++ b/Task/Quaternion-type/Prolog/quaternion-type-1.pro @@ -0,0 +1,22 @@ +% A quaternion is represented as a complex term qx/4 +add(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(R,I,J,K)) :- + !, R is R0+R1, I is I0+I1, J is J0+J1, K is K0+K1. +add(qx(R0,I,J,K), F, qx(R,I,J,K)) :- + number(F), !, R is R0 + F. +add(F, qx(R0,I,J,K), Qx) :- + add(qx(R0,I,J,K), F, Qx). +mul(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(R,I,J,K)) :- !, + R is R0*R1 - I0*I1 - J0*J1 - K0*K1, + I is R0*I1 + I0*R1 + J0*K1 - K0*J1, + J is R0*J1 - I0*K1 + J0*R1 + K0*I1, + K is R0*K1 + I0*J1 - J0*I1 + K0*R1. +mul(qx(R0,I0,J0,K0), F, qx(R,I,J,K)) :- + number(F), !, R is R0*F, I is I0*F, J is J0*F, K is K0*F. +mul(F, qx(R0,I0,J0,K0), Qx) :- + mul(qx(R0,I0,J0,K0),F,Qx). +abs(qx(R,I,J,K), Norm) :- + Norm is sqrt(R*R+I*I+J*J+K*K). +negate(qx(Ri,Ii,Ji,Ki),qx(R,I,J,K)) :- + R is -Ri, I is -Ii, J is -Ji, K is -Ki. +conjugate(qx(R,Ii,Ji,Ki),qx(R,I,J,K)) :- + I is -Ii, J is -Ji, K is -Ki. diff --git a/Task/Quaternion-type/Prolog/quaternion-type-2.pro b/Task/Quaternion-type/Prolog/quaternion-type-2.pro new file mode 100644 index 0000000000..818ba671d3 --- /dev/null +++ b/Task/Quaternion-type/Prolog/quaternion-type-2.pro @@ -0,0 +1,24 @@ +data(q, qx(1,2,3,4)). +data(q1, qx(2,3,4,5)). +data(q2, qx(3,4,5,6)). +data(r, 7). + +test :- data(Name, qx(A,B,C,D)), abs(qx(A,B,C,D), Norm), + writef('abs(%w) is %w\n', [Name, Norm]), fail. +test :- data(q, Qx), negate(Qx, Nqx), + writef('negate(%w) is %w\n', [q, Nqx]), fail. +test :- data(q, Qx), conjugate(Qx, Nqx), + writef('conjugate(%w) is %w\n', [q, Nqx]), fail. +test :- data(q1, Q1), data(q2, Q2), add(Q1, Q2, Qx), + writef('q1+q2 is %w\n', [Qx]), fail. +test :- data(q1, Q1), data(q2, Q2), add(Q2, Q1, Qx), + writef('q2+q1 is %w\n', [Qx]), fail. +test :- data(q, Qx), data(r, R), mul(Qx, R, Nqx), + writef('q*r is %w\n', [Nqx]), fail. +test :- data(q, Qx), data(r, R), mul(R, Qx, Nqx), + writef('r*q is %w\n', [Nqx]), fail. +test :- data(q1, Q1), data(q2, Q2), mul(Q1, Q2, Qx), + writef('q1*q2 is %w\n', [Qx]), fail. +test :- data(q1, Q1), data(q2, Q2), mul(Q2, Q1, Qx), + writef('q2*q1 is %w\n', [Qx]), fail. +test. diff --git a/Task/Quaternion-type/Racket/quaternion-type.rkt b/Task/Quaternion-type/Racket/quaternion-type.rkt new file mode 100644 index 0000000000..bafaa81231 --- /dev/null +++ b/Task/Quaternion-type/Racket/quaternion-type.rkt @@ -0,0 +1,75 @@ +#lang racket + +(struct quaternion (a b c d) + #:transparent) + +(define-match-expander quaternion: + (λ (stx) + (syntax-case stx () + [(_ a b c d) + #'(or (quaternion a b c d) + (and a (app (λ(_) 0) b) (app (λ(_) 0) c) (app (λ(_) 0) d)))]))) + +(define (norm q) + (match q + [(quaternion: a b c d) + (sqrt (+ (sqr a) (sqr b) (sqr c) (sqr d)))])) + +(define (negate q) + (match q + [(quaternion: a b c d) + (quaternion (- a) (- b) (- c) (- d))])) + +(define (conjugate q) + (match q + [(quaternion: a b c d) + (quaternion a (- b) (- c) (- d))])) + +(define (add q1 q2 . q-rest) + (let ((ans (match* (q1 q2) + [((quaternion: a1 b1 c1 d1) (quaternion: a2 b2 c2 d2)) + (quaternion (+ a1 a2) (+ b1 b2) (+ c1 c2) (+ d1 d2))]))) + (if (empty? q-rest) + ans + (apply add (cons ans q-rest))))) + +(define (multiply q1 q2 . q-rest) + (let ((ans (match* (q1 q2) + [((quaternion: a1 b1 c1 d1) (quaternion: a2 b2 c2 d2)) + (quaternion (- (* a1 a2) (* b1 b2) (* c1 c2) (* d1 d2)) + (+ (* a1 b2) (* b1 a2) (* c1 d2) (- (* d1 c2))) + (+ (* a1 c2) (- (* b1 d2)) (* c1 a2) (* d1 b2)) + (+ (* a1 d2) (* b1 c2) (- (* c1 b2)) (* d1 a2)))]))) + (if (empty? q-rest) + ans + (apply multiply (cons ans q-rest))))) + +;; Tests +(module+ main + (define i (quaternion 0 1 0 0)) + (define j (quaternion 0 0 1 0)) + (define k (quaternion 0 0 0 1)) + (displayln (multiply i j k)) + (newline) + + (define q (quaternion 1 2 3 4)) + (define q1 (quaternion 2 3 4 5)) + (define q2 (quaternion 3 4 5 6)) + (define r 7) + + (for ([quat (list q q1 q2)]) + (displayln quat) + (displayln (norm quat)) + (displayln (negate quat)) + (displayln (conjugate quat)) + (newline)) + + (add r q) + (add q1 q2) + (multiply r q) + + (newline) + (multiply q1 q2) + (multiply q2 q1) + (equal? (multiply q1 q2) + (multiply q2 q1))) diff --git a/Task/Queue-Definition/Racket/queue-definition-1.rkt b/Task/Queue-Definition/Racket/queue-definition-1.rkt new file mode 100644 index 0000000000..ec51806094 --- /dev/null +++ b/Task/Queue-Definition/Racket/queue-definition-1.rkt @@ -0,0 +1,22 @@ +#lang racket + +(define (make-queue) (mcons #f #f)) +(define (push! q x) + (define new (mcons x #f)) + (if (mcar q) (set-mcdr! (mcdr q) new) (set-mcar! q new)) + (set-mcdr! q new)) +(define (pop! q) + (define old (mcar q)) + (cond [(eq? old (mcdr q)) (set-mcar! q #f) (set-mcdr! q #f)] + [else (set-mcar! q (mcdr old))]) + (mcar old)) +(define (empty? q) + (not (mcar q))) + +(define Q (make-queue)) +(empty? Q) ; -> #t +(push! Q 'x) +(empty? Q) ; -> #f +(for ([x 3]) (push! Q x)) +(pop! Q) ; -> 'x +(list (pop! Q) (pop! Q) (pop! Q)) ; -> '(0 1 2) diff --git a/Task/Queue-Definition/Racket/queue-definition-2.rkt b/Task/Queue-Definition/Racket/queue-definition-2.rkt new file mode 100644 index 0000000000..0772b9eda4 --- /dev/null +++ b/Task/Queue-Definition/Racket/queue-definition-2.rkt @@ -0,0 +1,32 @@ +#lang racket +;; Invariants: +;; The elements in the queue are (append front (reverse back)). +;; Front is always non-empty (except for the empty queue). +(struct queue (front back)) + +(define empty (queue '() '())) + +(define (push x q) + (if (null? (queue-front q)) + (queue (reverse (cons x (queue-back q))) '()) + (queue (queue-front q) (cons x (queue-back q))))) + +(define (empty? q) + (null? (queue-front q))) + +(define (pop q) + (cond [(empty? q) (error 'pop "the queue is empty")] + [(not (null? (queue-front q))) + (if (null? (rest (queue-front q))) + (queue (reverse (queue-back q)) '()) + (queue (rest (queue-front q)) (queue-back q)))] + [else (queue (reverse (queue-back q)) '())])) + +(define (first q) + (cond [(empty? q) (error 'first "the queue is empty")] + [(car (queue-front q))])) + +;; Example: +(first (pop (pop (for/fold ([q empty]) ([x '(1 2 3 4)]) + (push x q))))) +;; => 3 diff --git a/Task/Queue-Usage/D/queue-usage-2.d b/Task/Queue-Usage/D/queue-usage-2.d index 69791d4537..e228295fed 100644 --- a/Task/Queue-Usage/D/queue-usage-2.d +++ b/Task/Queue-Usage/D/queue-usage-2.d @@ -1,12 +1,9 @@ module queue_usage2; -import std.traits: hasIndirections; - struct GrowableCircularQueue(T) { public size_t length; private size_t head, tail; private T[] A = [T.init]; - private uint power2 = 0; bool empty() const pure nothrow { return length == 0; @@ -21,20 +18,21 @@ struct GrowableCircularQueue(T) { A[(old.length - head) .. old.length] = old[0 .. head]; head = 0; tail = length; - power2++; } A[tail] = item; - tail = (tail + 1) & ((cast(size_t)1 << power2) - 1); + tail = (tail + 1) & (A.length - 1); length++; } T pop() pure { + import std.traits: hasIndirections; + if (length == 0) throw new Exception("GrowableCircularQueue is empty."); auto saved = A[head]; static if (hasIndirections!T) A[head] = T.init; // Help for the GC. - head = (head + 1) & ((cast(size_t)1 << power2) - 1); + head = (head + 1) & (A.length - 1); length--; return saved; } diff --git a/Task/Queue-Usage/Racket/queue-usage.rkt b/Task/Queue-Usage/Racket/queue-usage.rkt new file mode 100644 index 0000000000..8384c0c8f8 --- /dev/null +++ b/Task/Queue-Usage/Racket/queue-usage.rkt @@ -0,0 +1,17 @@ +#lang racket + +(require data/queue) + +(define queue (make-queue)) + +(enqueue! queue 'black) +(queue-empty? queue) ; #f + +(enqueue! queue 'red) +(enqueue! queue 'green) + +(dequeue! queue) ; 'black +(dequeue! queue) ; 'red +(dequeue! queue) ; 'green + +(queue-empty? queue) ; #t diff --git a/Task/Quine/Aime/quine.aime b/Task/Quine/Aime/quine.aime new file mode 100644 index 0000000000..f6f73138b3 --- /dev/null +++ b/Task/Quine/Aime/quine.aime @@ -0,0 +1,22 @@ +integer f; +text s, t; + +f = 36; +s = "integer f; +text s, t; + +f = 36; +s = \"\"; + +o_text(cut(s, 0, f)); +o_text(cut(s, 0, f - 1)); +o_etext(cut(s, f - 1, 2)); +o_text(cut(s, f + 1, 8888 - f)); +o_text(cut(s, f, 8888 - f)); +"; + +o_text(cut(s, 0, f)); +o_text(cut(s, 0, f - 1)); +o_etext(cut(s, f - 1, 2)); +o_text(cut(s, f + 1, 8888 - f)); +o_text(cut(s, f, 8888 - f)); diff --git a/Task/Quine/C++/quine.cpp b/Task/Quine/C++/quine.cpp index 80c68af98c..7e2fbcdfb5 100644 --- a/Task/Quine/C++/quine.cpp +++ b/Task/Quine/C++/quine.cpp @@ -1,5 +1,4 @@ #include -#include void quote(char const* c) { @@ -23,7 +22,7 @@ void quote(char const* c) int main() { char const* parts[] = { - "#include \n#include \n\nvoid quote(char const* c)\n{\n while (*c)\n {\n switch(*c)\n {\n case '\\\\':\n std::cout << \"\\\\\\\\\";break;\n case '\\n':\n std::cout << \"\\\\n\";break;\n case '\\\"':\n std::cout << \"\\\\\\\"\";break;\n default:\n std::cout << *c;\n }\n ++c;\n }\n}\n\nint main()\n{\n char const* parts[] = {\n \"", + "#include \n\nvoid quote(char const* c)\n{\n while (*c)\n {\n switch(*c)\n {\n case '\\\\':\n std::cout << \"\\\\\\\\\";break;\n case '\\n':\n std::cout << \"\\\\n\";break;\n case '\\\"':\n std::cout << \"\\\\\\\"\";break;\n default:\n std::cout << *c;\n }\n ++c;\n }\n}\n\nint main()\n{\n char const* parts[] = {\n \"", "\",\n \"", "\"\n };\n \n std::cout << parts[0];\n quote(parts[0]);\n std::cout << parts[1];\n quote(parts[1]);\n std::cout << parts[1];\n quote(parts[2]);\n std::cout << parts[2];\n\n return 0;\n}\n" }; diff --git a/Task/Quine/Fish/quine.fish b/Task/Quine/Fish/quine.fish new file mode 100644 index 0000000000..ae3e52e2d8 --- /dev/null +++ b/Task/Quine/Fish/quine.fish @@ -0,0 +1,3 @@ + 00000000000000000000++++++++++++++++++ v +2[$:{:@]$g:0=?v >o:4a*=?!v~1+:3=?;0ao> + >~" "^ >1+ ^ diff --git a/Task/Quine/Julia/quine.julia b/Task/Quine/Julia/quine.julia new file mode 100644 index 0000000000..209c9f6ffc --- /dev/null +++ b/Task/Quine/Julia/quine.julia @@ -0,0 +1,2 @@ +x="println(\"x=\$(repr(x))\\n\$x\")" +println("x=$(repr(x))\n$x") diff --git a/Task/Quine/Racket/quine.rkt b/Task/Quine/Racket/quine.rkt new file mode 100644 index 0000000000..8d4440b185 --- /dev/null +++ b/Task/Quine/Racket/quine.rkt @@ -0,0 +1 @@ +((λ (x) `(,x ',x)) '(λ (x) `(,x ',x))) diff --git a/Task/RIPEMD-160/Racket/ripemd-160-1.rkt b/Task/RIPEMD-160/Racket/ripemd-160-1.rkt new file mode 100644 index 0000000000..260fc23b50 --- /dev/null +++ b/Task/RIPEMD-160/Racket/ripemd-160-1.rkt @@ -0,0 +1,3 @@ +#lang racket +(require (planet soegaard/digest:1:2/digest)) +(ripemd160 #"Rosetta Code") diff --git a/Task/RIPEMD-160/Racket/ripemd-160-2.rkt b/Task/RIPEMD-160/Racket/ripemd-160-2.rkt new file mode 100644 index 0000000000..80fe1c3b82 --- /dev/null +++ b/Task/RIPEMD-160/Racket/ripemd-160-2.rkt @@ -0,0 +1 @@ +"b3be159860842cebaa7174c8fff0aa9e50a5199f" diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--5.c b/Task/Random-number-generator--device-/C/random-number-generator--device--5.c new file mode 100644 index 0000000000..2ae9f1abac --- /dev/null +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--5.c @@ -0,0 +1,11 @@ +#include +#include +#include + +int main() +{ + std::random_device rd; + std::uniform_int_distribution dist; + + std::cout << "Random Number: " << dist(rd) << std::endl; +} diff --git a/Task/Random-number-generator--device-/Racket/random-number-generator--device-.rkt b/Task/Random-number-generator--device-/Racket/random-number-generator--device-.rkt new file mode 100644 index 0000000000..ee6e62d293 --- /dev/null +++ b/Task/Random-number-generator--device-/Racket/random-number-generator--device-.rkt @@ -0,0 +1,4 @@ +#lang racket +;; Assuming a device to provide random bits: +(call-with-input-file* "/dev/random" + (λ(i) (integer-bytes->integer (read-bytes 4 i) #f))) diff --git a/Task/Random-number-generator--included-/C++/random-number-generator--included-.cpp b/Task/Random-number-generator--included-/C++/random-number-generator--included-.cpp new file mode 100644 index 0000000000..4a7a997557 --- /dev/null +++ b/Task/Random-number-generator--included-/C++/random-number-generator--included-.cpp @@ -0,0 +1,13 @@ +#include +#include +#include + +int main() +{ + std::random_device rd; + std::uniform_int_distribution dist(1, 10); + std::mt19937 mt(rd()); + + std::cout << "Random Number (hardware): " << dist(rd) << std::endl; + std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl; +} diff --git a/Task/Random-number-generator--included-/Erlang/random-number-generator--included--2.erl b/Task/Random-number-generator--included-/Erlang/random-number-generator--included--2.erl index c2807a6746..4430b81710 100644 --- a/Task/Random-number-generator--included-/Erlang/random-number-generator--included--2.erl +++ b/Task/Random-number-generator--included-/Erlang/random-number-generator--included--2.erl @@ -1,5 +1,5 @@ ... -{A1,A2,A3} = now(), +{A1,A2,A3} = erlang:now(), random:seed(A1, A2, A3), ...sequence of randoms used random:seed(A1, A2, A3), diff --git a/Task/Random-number-generator--included-/Erlang/random-number-generator--included--3.erl b/Task/Random-number-generator--included-/Erlang/random-number-generator--included--3.erl index 08309f5409..95ca0fd7a3 100644 --- a/Task/Random-number-generator--included-/Erlang/random-number-generator--included--3.erl +++ b/Task/Random-number-generator--included-/Erlang/random-number-generator--included--3.erl @@ -1 +1 @@ -Rfloat = uniform(), +Rfloat = random:uniform(), diff --git a/Task/Random-number-generator--included-/Erlang/random-number-generator--included--4.erl b/Task/Random-number-generator--included-/Erlang/random-number-generator--included--4.erl index aaeb681a9b..643f00d36c 100644 --- a/Task/Random-number-generator--included-/Erlang/random-number-generator--included--4.erl +++ b/Task/Random-number-generator--included-/Erlang/random-number-generator--included--4.erl @@ -1 +1 @@ -Rint = uniform(N), +Rint = random:uniform(N), diff --git a/Task/Random-number-generator--included-/REXX/random-number-generator--included--1.rexx b/Task/Random-number-generator--included-/REXX/random-number-generator--included--1.rexx new file mode 100644 index 0000000000..93a6ec326d --- /dev/null +++ b/Task/Random-number-generator--included-/REXX/random-number-generator--included--1.rexx @@ -0,0 +1,3 @@ + /*(below) returns a random integer between 100 & 200, inclusive.*/ + +y = random(100, 200) diff --git a/Task/Random-number-generator--included-/REXX/random-number-generator--included--2.rexx b/Task/Random-number-generator--included-/REXX/random-number-generator--included--2.rexx new file mode 100644 index 0000000000..72fec67fc9 --- /dev/null +++ b/Task/Random-number-generator--included-/REXX/random-number-generator--included--2.rexx @@ -0,0 +1,5 @@ +call random ,,44 /*the seed in this case is "44". */ + . + . + . +y = random(100, 200) diff --git a/Task/Random-numbers/C++/random-numbers-1.cpp b/Task/Random-numbers/C++/random-numbers-1.cpp index 8469364303..64b928b041 100644 --- a/Task/Random-numbers/C++/random-numbers-1.cpp +++ b/Task/Random-numbers/C++/random-numbers-1.cpp @@ -1,27 +1,17 @@ -#include // for rand -#include // for atan, sqrt, log, cos -#include // for generate_n - -double const pi = 4*std::atan(1.0); - -// simple functor for normal distribution -class normal_distribution -{ -public: - normal_distribution(double m, double s): mu(m), sigma(s) {} - double operator() const // returns a single normally distributed number - { - double r1 = (std::rand() + 1.0)/(RAND_MAX + 1.0); // gives equal distribution in (0, 1] - double r2 = (std::rand() + 1.0)/(RAND_MAX + 1.0); - return mu + sigma * std::sqrt(-2*std::log(r1))*std::cos(2*pi*r2); - } -private: - const double mu, sigma; -}; +#include +#include +#include +#include +using namespace std; int main() { - double array[1000]; - std::generate_n(array, 1000, normal_distribution(1.0, 0.5)); + random_device seed; + mt19937 engine(seed()); + normal_distribution<> dist(1.0, 0.5); + auto rnd = bind(dist, engine); + + vector v(1000); + generate(v.begin(), v.end(), rnd); return 0; } diff --git a/Task/Random-numbers/C++/random-numbers-2.cpp b/Task/Random-numbers/C++/random-numbers-2.cpp index 70e0a34fdb..8469364303 100644 --- a/Task/Random-numbers/C++/random-numbers-2.cpp +++ b/Task/Random-numbers/C++/random-numbers-2.cpp @@ -1,20 +1,27 @@ -#include -#include "boost/random.hpp" -#include "boost/generator_iterator.hpp" -#include -#include +#include // for rand +#include // for atan, sqrt, log, cos +#include // for generate_n -typedef boost::mt19937 RNGType; ///< mersenne twister generator +double const pi = 4*std::atan(1.0); -int main() { - RNGType rng; - boost::normal_distribution<> rdist(1.0,0.5); /**< normal distribution - with mean of 1.0 and standard deviation of 0.5 */ +// simple functor for normal distribution +class normal_distribution +{ +public: + normal_distribution(double m, double s): mu(m), sigma(s) {} + double operator() const // returns a single normally distributed number + { + double r1 = (std::rand() + 1.0)/(RAND_MAX + 1.0); // gives equal distribution in (0, 1] + double r2 = (std::rand() + 1.0)/(RAND_MAX + 1.0); + return mu + sigma * std::sqrt(-2*std::log(r1))*std::cos(2*pi*r2); + } +private: + const double mu, sigma; +}; - boost::variate_generator< RNGType, boost::normal_distribution<> > - get_rand(rng, rdist); - - std::vector v(1000); - generate(v.begin(),v.end(),get_rand); - return 0; +int main() +{ + double array[1000]; + std::generate_n(array, 1000, normal_distribution(1.0, 0.5)); + return 0; } diff --git a/Task/Random-numbers/C++/random-numbers-3.cpp b/Task/Random-numbers/C++/random-numbers-3.cpp index 64b928b041..70e0a34fdb 100644 --- a/Task/Random-numbers/C++/random-numbers-3.cpp +++ b/Task/Random-numbers/C++/random-numbers-3.cpp @@ -1,17 +1,20 @@ -#include -#include #include +#include "boost/random.hpp" +#include "boost/generator_iterator.hpp" +#include #include -using namespace std; -int main() -{ - random_device seed; - mt19937 engine(seed()); - normal_distribution<> dist(1.0, 0.5); - auto rnd = bind(dist, engine); +typedef boost::mt19937 RNGType; ///< mersenne twister generator - vector v(1000); - generate(v.begin(), v.end(), rnd); - return 0; +int main() { + RNGType rng; + boost::normal_distribution<> rdist(1.0,0.5); /**< normal distribution + with mean of 1.0 and standard deviation of 0.5 */ + + boost::variate_generator< RNGType, boost::normal_distribution<> > + get_rand(rng, rdist); + + std::vector v(1000); + generate(v.begin(),v.end(),get_rand); + return 0; } diff --git a/Task/Random-numbers/Racket/random-numbers.rkt b/Task/Random-numbers/Racket/random-numbers.rkt new file mode 100644 index 0000000000..b9ba9990ae --- /dev/null +++ b/Task/Random-numbers/Racket/random-numbers.rkt @@ -0,0 +1,3 @@ +#lang racket +(for/list ([i 1000]) + (add1 (* (sqrt (* -2 (log (random)))) (cos (* 2 pi (random))) 0.5))) diff --git a/Task/Random-numbers/Raven/random-numbers-1.raven b/Task/Random-numbers/Raven/random-numbers-1.raven new file mode 100644 index 0000000000..4e648bac20 --- /dev/null +++ b/Task/Random-numbers/Raven/random-numbers-1.raven @@ -0,0 +1,13 @@ +define PI + -1 acos + +define rand1 + 9999999 choose 1 + 10000000.0 / + +define randNormal + rand1 PI * 2 * cos + rand1 log -2 * sqrt + * + 2 / 1 + + +1000 each drop randNormal "%f\n" print diff --git a/Task/Random-numbers/Raven/random-numbers-2.raven b/Task/Random-numbers/Raven/random-numbers-2.raven new file mode 100644 index 0000000000..4ac3346da6 --- /dev/null +++ b/Task/Random-numbers/Raven/random-numbers-2.raven @@ -0,0 +1,3 @@ +raven rand.rv | awk '{sum+=$1; sumsq+=$1*$1;} END {print "stdev = " sqrt(sumsq/NR - (sum/NR)**2); print "mean = " sum/NR}' +stdev = 0.497773 +mean = 1.01497 diff --git a/Task/Range-expansion/D/range-expansion.d b/Task/Range-expansion/D/range-expansion.d index add4b55202..3155a53c06 100644 --- a/Task/Range-expansion/D/range-expansion.d +++ b/Task/Range-expansion/D/range-expansion.d @@ -1,14 +1,12 @@ -import std.stdio, std.regex, std.string, std.conv, std.range; +import std.stdio, std.regex, std.string, std.conv, std.range, + std.algorithm; int[] rangeExpand(in string txt) /*pure nothrow*/ { - typeof(return) result; - - foreach (r; std.string.split(txt, ",")) { + return txt.split(",").map!((r) { const m = r.match(r"^(-?\d+)(-?(-?\d+))?$").captures.array; - result ~= m[2].empty ? [m[1].to!int] : - iota(m[1].to!int, m[3].to!int + 1).array; - } - return result; + return m[2].empty ? [m[1].to!int] : + iota(m[1].to!int, m[3].to!int + 1).array; + }).join.array; } void main() { diff --git a/Task/Range-expansion/NetRexx/range-expansion.netrexx b/Task/Range-expansion/NetRexx/range-expansion.netrexx index 6a789108a1..4f776986e6 100644 --- a/Task/Range-expansion/NetRexx/range-expansion.netrexx +++ b/Task/Range-expansion/NetRexx/range-expansion.netrexx @@ -7,6 +7,8 @@ * Parse Var x ... -> Parse x ... **********************************************************************/ +parse arg old +if old = '' then old='-6,-3--1,3-5,7-11,14,15,17-20' /*original list of nums/ranges */ Say 'old='old /*show old list of nums/ranges. */ @@ -21,10 +23,12 @@ Parse x low =(dashpos) +1 high /* split the element */ Loop j=low To high /* output all numbers in range */ new=new||comma||j /* with separating commas */ + comma=',' /* from now on use comma */ End End - Else /* element is a number */ + Else Do /* element is a number */ new=new||comma||x /* append (with comma) */ - comma=',' /* from now on use comma */ + comma=',' /* from now on use comma */ + End End Say 'new='new /*show the expanded list */ diff --git a/Task/Range-expansion/REXX/range-expansion-1.rexx b/Task/Range-expansion/REXX/range-expansion-1.rexx index d0edf78475..8f621581ea 100644 --- a/Task/Range-expansion/REXX/range-expansion-1.rexx +++ b/Task/Range-expansion/REXX/range-expansion-1.rexx @@ -1,16 +1,13 @@ /*REXX program expands an ordered list of integers into an expanded list*/ -new= /*new list of numbers (so far). */ -old='-6,-3--1, 3-5, 7-11,14,15, 17-20' /*orig integers/ranges,*/ - /*blanks were added for comparing*/ -a=translate(old,,',') /*translate commas (,) to blanks.*/ - - do until a==''; parse var a X a /*obtain the next integer|range. */ - _=pos('-',X,2) /*find location of a dash (maybe)*/ - if _\==0 then do k=left(X,_-1) to substr(X,_+1) /*Dash? Process range*/ - new=new k /*append single integer at a time*/ - end /*k*/ - else new=new X /*append X to the new list. */ - end /*until*/ +old='-6,-3--1, 3-5, 7-11,14,15, 17-20'; a=translate(old,,',') +new= /*change , ──► blanks [↑] */ + do until a==''; parse var a X a /*obtain the next integer|range. */ + p=pos('-',X,2) /*find location of a dash (maybe)*/ + if p==0 then new=new X /*append X to the new list. */ + else do j=left(X,p-1) to substr(X,p+1) /*Range? Build it*/ + new=new j /*append single integer at a time*/ + end /*j*/ + end /*until*/ new=translate( strip(new), ',' ," ") /*remove first blank, add commas.*/ say 'old list =' old /*show old list of numbers/ranges*/ diff --git a/Task/Range-expansion/REXX/range-expansion-2.rexx b/Task/Range-expansion/REXX/range-expansion-2.rexx index d4f9988a52..3ec72c7d92 100644 --- a/Task/Range-expansion/REXX/range-expansion-2.rexx +++ b/Task/Range-expansion/REXX/range-expansion-2.rexx @@ -2,6 +2,8 @@ * 09.08.2012 Walter Pachl **********************************************************************/ + parse arg old + if old = '' then - old='-6,-3--1,3-5,7-11,14,15,17-20' /*original list of nums/ranges */ Say 'old='old /*show old list of nums/ranges. */ @@ -16,10 +18,12 @@ Parse Var x low =(dashpos) +1 high /* split the element */ Do j=low To high /* output all numbers in range */ new=new||comma||j /* with separating commas */ + comma=',' /* from now on use comma */ End End - Else /* element is a number */ + Else Do /* element is a number */ new=new||comma||x /* append (with comma) */ - comma=',' /* from now on use comma */ + comma=',' /* from now on use comma */ + End End Say 'new='new /*show the expanded list */ diff --git a/Task/Range-expansion/Raven/range-expansion.raven b/Task/Range-expansion/Raven/range-expansion.raven new file mode 100644 index 0000000000..3a2c25e05b --- /dev/null +++ b/Task/Range-expansion/Raven/range-expansion.raven @@ -0,0 +1,33 @@ +define get_num use $lst + # "-22" split by "-" is [ "", "22" ] so check if + # first list item is "" -> a negative number + $lst 0 get "" = if + # negative number + # + # convert str to integer and multiply by -1 + -1 $lst 1 get 0 prefer * + $lst shift $lst shift drop drop + else + # positive number + $lst 0 get 0 prefer + $lst shift drop + +define range_expand use $rng + [ ] as $res + $rng "," split each as $r + $r m/^(-?\d+)-(-?\d+)$/ TRUE = if + $r s/-/g as $parts + $parts get_num as $from + $parts get_num as $to + # int list to str list, then joined by "," + group + $from $to 1 range each "" prefer + list "," join $res push + # range doesn't include the $to, so add to end of generated range + $to "%d" $res push + else + $r $res push + $res "," join print + "\n" print + +'-6,-3--1,3-5,7-11,14,15,17-20' range_expand diff --git a/Task/Range-expansion/UNIX-Shell/range-expansion.sh b/Task/Range-expansion/UNIX-Shell/range-expansion.sh new file mode 100644 index 0000000000..c67dc5bfd6 --- /dev/null +++ b/Task/Range-expansion/UNIX-Shell/range-expansion.sh @@ -0,0 +1,19 @@ +#!/usr/bin/bash + +range_expand () ( + IFS=, + set -- $1 + n=$# + for element; do + if [[ $element =~ ^(-?[0-9]+)-(-?[0-9]+)$ ]]; then + set -- "$@" $(eval echo "{${BASH_REMATCH[1]}..${BASH_REMATCH[2]}}") + else + set -- "$@" $element + fi + done + shift $n + echo "$@" + # to return a comma-separated value: echo "${*// /,}" +) + +range_expand "-6,-3--1,3-5,7-11,14,15,17-20" diff --git a/Task/Range-extraction/D/range-extraction.d b/Task/Range-extraction/D/range-extraction.d index 936ffdfb48..091f2b6ebb 100644 --- a/Task/Range-extraction/D/range-extraction.d +++ b/Task/Range-extraction/D/range-extraction.d @@ -1,26 +1,22 @@ -import std.stdio, std.conv, std.string, std.algorithm; +import std.stdio, std.conv, std.string, std.algorithm, std.range; -string extractRanges(in int[] items) +string rangeExtraction(in int[] items) in { - assert(items.isSorted()); + assert(items.isSorted); } body { - string[] ranges; + if (items.empty) + return null; + auto ranges = [[items[0].text]]; - for (size_t i = 0; i < items.length; i++) { - immutable low = items[i]; - while (i < (items.length - 1) && (items[i] + 1) == items[i + 1]) - i++; - immutable hi = items[i]; - - if (hi - low >= 2) - ranges ~= text(low, '-', hi); - else if (hi - low == 1) - ranges ~= text(low, ',', hi); + foreach (immutable x, immutable y; items.zip(items[1 .. $])) + if (x + 1 == y) + ranges[$ - 1] ~= y.text; else - ranges ~= text(low); - } + ranges ~= [y.text]; - return ranges.join(","); + return ranges + .map!(r => r.length > 2 ? r[0] ~ "-" ~ r.back : r.join(",")) + .join(","); } void main() { @@ -30,5 +26,5 @@ void main() { [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]) - writeln(extractRanges(data)); + data.rangeExtraction.writeln; } diff --git a/Task/Range-extraction/J/range-extraction-3.j b/Task/Range-extraction/J/range-extraction-3.j new file mode 100644 index 0000000000..b6d173dfe7 --- /dev/null +++ b/Task/Range-extraction/J/range-extraction-3.j @@ -0,0 +1,2 @@ + extractRange i.101 +0-100 diff --git a/Task/Range-extraction/J/range-extraction-4.j b/Task/Range-extraction/J/range-extraction-4.j new file mode 100644 index 0000000000..76b7e3f267 --- /dev/null +++ b/Task/Range-extraction/J/range-extraction-4.j @@ -0,0 +1,2 @@ + extractRange (-. p:) i.101 +0,1,4,6,8-10,12,14-16,18,20-22,24-28,30,32-36,38-40,42,44-46,48-52,54-58,60,62-66,68-70,72,74-78,80-82,84-88,90-96,98-100 diff --git a/Task/Range-extraction/J/range-extraction-5.j b/Task/Range-extraction/J/range-extraction-5.j new file mode 100644 index 0000000000..2209fcc703 --- /dev/null +++ b/Task/Range-extraction/J/range-extraction-5.j @@ -0,0 +1,2 @@ + extractRange 2}. (-. p:) i.101 +4,6,8-10,12,14-16,18,20-22,24-28,30,32-36,38-40,42,44-46,48-52,54-58,60,62-66,68-70,72,74-78,80-82,84-88,90-96,98-100 diff --git a/Task/Range-extraction/Objeck/range-extraction.objeck b/Task/Range-extraction/Objeck/range-extraction.objeck new file mode 100644 index 0000000000..3fd5a5a786 --- /dev/null +++ b/Task/Range-extraction/Objeck/range-extraction.objeck @@ -0,0 +1,46 @@ +class IdentityMatrix { + function : Main(args : String[]) ~ Nil { + Compress2Range("-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20")->PrintLine(); + + Compress2Range("0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39")->PrintLine(); + } + + function : Compress2Range(expanded : String) ~ String { + result := ""; + nums := expanded->ReplaceAll(" ", "")->Split(","); + firstNum := nums[0]->ToInt(); + rangeSize := 0; + for(i:= 1; i < nums->Size(); i += 1;) { + thisNum := nums[i]->ToInt(); + if(thisNum - firstNum - rangeSize = 1) { + rangeSize += 1; + } + else{ + if(rangeSize <> 0){ + result->Append(firstNum); + result->Append((rangeSize = 1) ? ",": "-"); + result->Append(firstNum+rangeSize); + result->Append(","); + rangeSize := 0; + } + else { + result->Append(firstNum); + result->Append(","); + }; + firstNum := thisNum; + }; + }; + + if(rangeSize <> 0){ + result->Append(firstNum); + result->Append((rangeSize = 1) ? "," : "-"); + result->Append(firstNum + rangeSize); + rangeSize := 0; + } + else { + result->Append(firstNum); + }; + + return result; + } +} diff --git a/Task/Range-extraction/Python/range-extraction.py b/Task/Range-extraction/Python/range-extraction.py new file mode 100644 index 0000000000..799b1e6996 --- /dev/null +++ b/Task/Range-extraction/Python/range-extraction.py @@ -0,0 +1,28 @@ +def range_extract(lst): + 'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints' + lenlst = len(lst) + i = 0 + while i< lenlst: + low = lst[i] + while i = 2: + yield (low, hi) + elif hi - low == 1: + yield (low,) + yield (hi,) + else: + yield (low,) + i += 1 + +def printr(ranges): + print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r) + for r in ranges ) ) + +if __name__ == '__main__': + for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, + 8, 9, 10, 11, 14, 15, 17, 18, 19, 20], + [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]: + #print(list(range_extract(lst))) + printr(range_extract(lst)) diff --git a/Task/Range-extraction/REXX/range-extraction-1.rexx b/Task/Range-extraction/REXX/range-extraction-1.rexx index d4d22efbc9..ad0ff81a0f 100644 --- a/Task/Range-extraction/REXX/range-extraction-1.rexx +++ b/Task/Range-extraction/REXX/range-extraction-1.rexx @@ -1,30 +1,20 @@ -/*REXX program to test range extraction. */ -aaa='0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22', - '23 24 25 27 28 29 30 31 32 33 35 36 37 38 39' -say 'old =' aaa; say /*show the old range of numbers. */ +/*REXX program creates a range extraction from a list of integers. */ +old=0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 +w=words(old) /*number of integers in the list.*/ new= /*new list (maybe with ranges). */ -w=words(aaa) /*number of numbers in the list. */ - /*Note: index of DO (J) gets modified within loop !.*/ - do j=1 to w /*step through num word in list.*/ - _=word(aaa,j) /*get the Jth number in the list.*/ - new=new',' _ /*append Jth number to new list.*/ - inc=1 /*start with an increment of one.*/ + do j=1 to w; x=word(old,j) /*get the Jth number in the list.*/ + new=new',' x /*append Jth number to new list.*/ + inc=1; g= /*start with an increment of one.*/ + do k=j+1 to w; y=word(old,k) /*get the Kth number in the list.*/ + if y\=x+inc then leave /*is this number ¬> prev by inc ?*/ + inc=inc+1; g=y /*increase range, assign g (good)*/ + end /*k*/ + if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ + new=new'-'g /*indicate a range of numbers. */ + j =k-1 /*changing the J DO loop index.*/ + end /*j*/ - do k=j+1 to w /*now, search for end of range. */ - __=word(aaa,k) /*get the Kth number in the list.*/ - if __ \== _+inc then leave /*this number 1 > than prev? */ - inc=inc+1 /*yes, then increase the range. */ - g_ = __ /*placeholder for last good num. */ - end /*k*/ - - k=k-1 /*fudge the Kth word (subtract 1)*/ - if k == j then iterate /*no range? Then keep truckin'.*/ - if g_ == _+1 then iterate /*range of 1? Then keep truckin'.*/ - new=new'-'g_ /*indicate a range of numbers. */ - j=k /*Bad practice!! Change DO index.*/ - end /*j*/ - -new=substr(new,3) /*remove extraneous leading comma*/ -new=space(new,0) /*remove all spaces (blanks). */ -say 'new =' new /*display new list of numbers. */ +new=space(substr(new, 2), 0) /*elide leading comma, all blanks*/ +say 'old:' old /*show the old range of numbers. */ +say 'new:' new /*display new list of numbers. */ /*stick a fork in it, we're done.*/ diff --git a/Task/Range-extraction/REXX/range-extraction-2.rexx b/Task/Range-extraction/REXX/range-extraction-2.rexx index 706680a124..3559e93951 100644 --- a/Task/Range-extraction/REXX/range-extraction-2.rexx +++ b/Task/Range-extraction/REXX/range-extraction-2.rexx @@ -1,31 +1,20 @@ -/*REXX program to test range extraction. ****************************** -* 07.08.2012 Walter Pachl -**********************************************************************/ -aaa='0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29', - '30 31 32 33 35 36 37 38 39' -say 'old='aaa; -aaa=aaa 1e99 /* artificial number at the end */ -i=0 /* initialize index */ -ol='' /* initialize output string */ -comma='' /* will become a ',' lateron */ -inrange=0 -Do While i<=words(aaa) /* loop for all numbers */ - i=i+1 /* index of next number */ - n=word(aaa,i) /* the now current number */ - If n=1e99 Then Leave /* we are at the end */ - If inrange Then Do /* range was opened */ - If word(aaa,i+1)<>n+1 Then Do /* following word not in range */ - ol=ol||n /* so this number is the end */ - inrange=0 /* and the range is over */ - End /* else ignore current number */ - End - Else Do /* not in a range */ - ol=ol||comma||n /* add number (with comma) */ - comma=',' /* to the output string */ - If word(aaa,i+2)=n+2 Then Do /* if the nr after the next fits */ - inrange=1 /* open a range */ - ol=ol'-' /* append the range connector */ - End - End - End -Say 'new='ol +/*REXX program creates a range extraction from a list of integers. */ +old=0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 +w=words(old); j=0 /*number of integers in the list.*/ +new= /*new list (maybe with ranges). */ + do while j prev by inc ?*/ + inc=inc+1; g=y /*increase range, assign g (good)*/ + end /*k*/ + if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ + new=new'-'g /*indicate a range of numbers. */ + j =k-1 /*which number to examine next. */ + end /*while*/ + +new=space(substr(new, 2), 0) /*elide leading comma, all blanks*/ +say 'old:' old /*show the old range of numbers. */ +say 'new:' new /*display new list of numbers. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Range-extraction/REXX/range-extraction-3.rexx b/Task/Range-extraction/REXX/range-extraction-3.rexx new file mode 100644 index 0000000000..706680a124 --- /dev/null +++ b/Task/Range-extraction/REXX/range-extraction-3.rexx @@ -0,0 +1,31 @@ +/*REXX program to test range extraction. ****************************** +* 07.08.2012 Walter Pachl +**********************************************************************/ +aaa='0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29', + '30 31 32 33 35 36 37 38 39' +say 'old='aaa; +aaa=aaa 1e99 /* artificial number at the end */ +i=0 /* initialize index */ +ol='' /* initialize output string */ +comma='' /* will become a ',' lateron */ +inrange=0 +Do While i<=words(aaa) /* loop for all numbers */ + i=i+1 /* index of next number */ + n=word(aaa,i) /* the now current number */ + If n=1e99 Then Leave /* we are at the end */ + If inrange Then Do /* range was opened */ + If word(aaa,i+1)<>n+1 Then Do /* following word not in range */ + ol=ol||n /* so this number is the end */ + inrange=0 /* and the range is over */ + End /* else ignore current number */ + End + Else Do /* not in a range */ + ol=ol||comma||n /* add number (with comma) */ + comma=',' /* to the output string */ + If word(aaa,i+2)=n+2 Then Do /* if the nr after the next fits */ + inrange=1 /* open a range */ + ol=ol'-' /* append the range connector */ + End + End + End +Say 'new='ol diff --git a/Task/Range-extraction/Racket/range-extraction.rkt b/Task/Range-extraction/Racket/range-extraction.rkt new file mode 100644 index 0000000000..5dcdb0257c --- /dev/null +++ b/Task/Range-extraction/Racket/range-extraction.rkt @@ -0,0 +1,14 @@ +#lang racket + +(define (list->ranges xs) + (define (R lo hi) + (if (= lo hi) (~a lo) (~a lo (if (= 1 (- hi lo)) "," "-") hi))) + (let loop ([xs xs] [lo #f] [hi #f] [r '()]) + (cond [(null? xs) (string-join (reverse (if lo (cons (R lo hi) r) r)) ",")] + [(not hi) (loop (cdr xs) (car xs) (car xs) r)] + [(= 1 (- (car xs) hi)) (loop (cdr xs) lo (car xs) r)] + [else (loop xs #f #f (cons (R lo hi) r))]))) + +(list->ranges '(0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 + 24 25 27 28 29 30 31 32 33 35 36 37 38 39)) +;; -> "0-2,4,6-8,11,12,14-25,27-33,35-39" diff --git a/Task/Range-extraction/UNIX-Shell/range-extraction.sh b/Task/Range-extraction/UNIX-Shell/range-extraction.sh new file mode 100644 index 0000000000..8bfcb79111 --- /dev/null +++ b/Task/Range-extraction/UNIX-Shell/range-extraction.sh @@ -0,0 +1,30 @@ +#!/usr/bin/bash + +range_contract () ( + add_range () { + case $(( current - range_start )) in + 0) ranges+=( $range_start ) ;; + 1) ranges+=( $range_start $current ) ;; + *) ranges+=("$range_start-$current") ;; + esac + } + + ranges=() + range_start=$1 + current=$1 + shift + + for number; do + if (( number > current+1 )); then + add_range + range_start=$number + fi + current=$number + done + add_range + + x="${ranges[@]}" + echo ${x// /,} +) + +range_contract 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 diff --git a/Task/Rate-counter/Racket/rate-counter.rkt b/Task/Rate-counter/Racket/rate-counter.rkt new file mode 100644 index 0000000000..31a630b785 --- /dev/null +++ b/Task/Rate-counter/Racket/rate-counter.rkt @@ -0,0 +1,12 @@ +#lang racket + +;; Racket has a useful `time*' macro that does just what's requested: +;; run some expression N times, and produce timing results +(require unstable/time) + +;; Sample use: +(define (fib n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2))))) +(time* 10 (fib 38)) + +;; But of course, can be used to measure external processes too: +(time* 10 (system "sleep 1")) diff --git a/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm.rkt b/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm.rkt new file mode 100644 index 0000000000..f7c3e63219 --- /dev/null +++ b/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm.rkt @@ -0,0 +1,75 @@ +#lang racket + +(module pip racket + (require racket/contract) + + (provide point) + (provide seg) + (provide (contract-out [point-in-polygon? (-> + point? + list? + boolean?)])) + + (struct point (x y) #:transparent) + (struct seg (Ax Ay Bx By)) + (define ε 0.000001) + (define (neq? x y) (not (eq? x y))) + + (define (ray-cross-seg? r s) + (let* ([Ax (seg-Ax s)] [Ay (seg-Ay s)] + [Bx (seg-Bx s)] [By (seg-By s)] + [Px (point-x r)] [Pyo (point-y r)] + [Py (+ Pyo (if (or (eq? Pyo Ay) + (eq? Pyo By)) + ε 0))]) + + (cond [(or (< Py Ay) (> Py By)) #f] + [(> Px (max Ax Bx)) #f] + [(< Px (min Ax Bx)) #t] + [else + (let ([red (if (neq? Ax Px) + (/ (- By Ay) (- Bx Ax)) + +inf.0)] + [blue (if (neq? Ax Px) + (/ (- Py Ax) (- Px Ax)) + +inf.0)]) + (if (>= blue red) #t #f))]))) + + (define (point-in-polygon? point polygon) + (odd? + (for/fold ([c 0]) ([seg polygon]) + (+ c (if (ray-cross-seg? point seg) 1 0)))))) + +(require 'pip) + +(define test-point-list + (list + (point 5.0 5.0) + (point 5.0 8.0) + (point -10.0 5.0) + (point 0.0 5.0) + (point 10.0 5.0) + (point 8.0 5.0) + (point 10.0 10.0))) + +(define square + (list (seg 0.0 0.0 10.0 0.0) + (seg 10.0 0.0 10.0 10.0) + (seg 10.0 10.0 0.0 10.0) + (seg 0.0 0.0 0.0 10.0))) + +(define exagon + (list (seg 3.0 0.0 7.0 0.0) + (seg 7.0 0.0 10.0 5.0) + (seg 10.0 5.0 7.0 10.0) + (seg 7.0 10.0 3.0 10.0) + (seg 0.0 5.0 3.0 10.0) + (seg 3.0 0.0 0.0 5.0))) + +(define (test-figure fig name) + (printf "\ntesting ~a: \n" name) + (for ([p test-point-list]) + (printf "testing ~v: ~a\n" p (point-in-polygon? p fig)))) + +(test-figure square "square") +(test-figure exagon "exagon") diff --git a/Task/Read-a-configuration-file/Racket/read-a-configuration-file.rkt b/Task/Read-a-configuration-file/Racket/read-a-configuration-file.rkt new file mode 100644 index 0000000000..13acb58cdd --- /dev/null +++ b/Task/Read-a-configuration-file/Racket/read-a-configuration-file.rkt @@ -0,0 +1,11 @@ +#lang racket + +(require "options.rkt") + +(read-options "options-file") +(define-options fullname favouritefruit needspeeling seedsremoved otherfamily) +(printf "fullname = ~s\n" fullname) +(printf "favouritefruit = ~s\n" favouritefruit) +(printf "needspeeling = ~s\n" needspeeling) +(printf "seedsremoved = ~s\n" seedsremoved) +(printf "otherfamily = ~s\n" otherfamily) diff --git a/Task/Read-a-file-line-by-line/Bracmat/read-a-file-line-by-line.bracmat b/Task/Read-a-file-line-by-line/Bracmat/read-a-file-line-by-line.bracmat new file mode 100644 index 0000000000..6de343961f --- /dev/null +++ b/Task/Read-a-file-line-by-line/Bracmat/read-a-file-line-by-line.bracmat @@ -0,0 +1,10 @@ + fil$("test.txt",r) { r opens a text file, rb opens a binary file for reading } +& fil$(,STR,\n) { first argument empty: same as before (i.e. "test.txt") } + { if \n were replaced by e.g. "\n\t " we would read word-wise instead } +& 0:?lineno +& whl + ' ( fil$:(?line.?sep) { "sep" contains found stop character, i.e. \n } + & put$(line (1+!lineno:?lineno) ":" !line \n) + ) +& (fil$(,SET,-1)|); { Setting file position before start closes file, and fails. + Therefore the | } diff --git a/Task/Read-a-file-line-by-line/Erlang/read-a-file-line-by-line.erl b/Task/Read-a-file-line-by-line/Erlang/read-a-file-line-by-line.erl new file mode 100644 index 0000000000..39e002ab78 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Erlang/read-a-file-line-by-line.erl @@ -0,0 +1,12 @@ +-module( read_a_file_line_by_line ). + +-export( [into_list/1] ). + +into_list( File ) -> + {ok, IO} = file:open( File, [read] ), + into_list( io:get_line(IO, ''), IO, [] ). + + +into_list( eof, _IO, Acc ) -> lists:reverse( Acc ); +into_list( {error, _Error}, _IO, Acc ) -> lists:reverse( Acc ); +into_list( Line, IO, Acc ) -> into_list( io:get_line(IO, ''), IO, [Line | Acc] ). diff --git a/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia b/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia index 075a346263..6fbadf647e 100644 --- a/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia +++ b/Task/Read-a-file-line-by-line/Julia/read-a-file-line-by-line.julia @@ -1,5 +1,5 @@ -input = open("input_file","r") -for line in each_line(input) - #line operations +open("input_file","w") do f + for line in each_line(f) + #line operations + end end -close(input) diff --git a/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-1.ocaml b/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-1.ocaml new file mode 100644 index 0000000000..ff0602a5e2 --- /dev/null +++ b/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-1.ocaml @@ -0,0 +1,9 @@ +let () = + let ic = open_in "input.txt" in + try + while true do + let line = input_line ic in + print_endline line + done + with End_of_file -> + close_in ic diff --git a/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-2.ocaml b/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-2.ocaml new file mode 100644 index 0000000000..09d2422bae --- /dev/null +++ b/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-2.ocaml @@ -0,0 +1,17 @@ +let input_line_opt ic = + try Some (input_line ic) + with End_of_file -> None + +let read_lines ic = + let rec aux acc = + match input_line_opt ic with + | Some line -> aux (line::acc) + | None -> (List.rev acc) + in + aux [] + +let lines_of_file filename = + let ic = open_in filename in + let lines = read_lines ic in + close_in ic; + (lines) diff --git a/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-3.ocaml b/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-3.ocaml new file mode 100644 index 0000000000..b9ac7bb186 --- /dev/null +++ b/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line-3.ocaml @@ -0,0 +1,3 @@ +let () = + let lines = lines_of_file "unixdict.txt" in + List.iter print_endline lines diff --git a/Task/Read-a-specific-line-from-a-file/Erlang/read-a-specific-line-from-a-file.erl b/Task/Read-a-specific-line-from-a-file/Erlang/read-a-specific-line-from-a-file.erl new file mode 100644 index 0000000000..4b77ac51fd --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Erlang/read-a-specific-line-from-a-file.erl @@ -0,0 +1,30 @@ +-module( read_a_specific_line ). + +-export( [from_file/2, task/0] ). + +from_file( File, N ) -> line_nr( N, read_a_file_line_by_line:into_list(File) ). + +task() -> + Lines = read_a_file_line_by_line:into_list( "read_a_specific_line.erl" ), + Line_7 = line_nr( 7, Lines ), + Line_7. + + + +line_nr( N, Lines ) -> + try + case lists:nth( N, Lines ) + of "\n" -> erlang:exit( empty_line ) + ; Line -> Line + end + + catch + _Type:Error0 -> + Error = line_nr_error( Error0 ), + io:fwrite( "Error: ~p~n", [Error] ), + erlang:exit( Error ) + + end. + +line_nr_error( function_clause ) -> too_few_lines_in_file; +line_nr_error( Error ) -> Error. diff --git a/Task/Read-a-specific-line-from-a-file/Racket/read-a-specific-line-from-a-file.rkt b/Task/Read-a-specific-line-from-a-file/Racket/read-a-specific-line-from-a-file.rkt new file mode 100644 index 0000000000..f45f9528ad --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Racket/read-a-specific-line-from-a-file.rkt @@ -0,0 +1,9 @@ +#lang racket + +;; simple, but reads the whole file +(define s1 (list-ref (file->lines "some-file") 6)) + +;; more efficient: read and discare n-1 lines +(define s2 + (call-with-input-file "some-file" + (λ(i) (for/last ([line (in-lines i)] [n 7]) line)))) diff --git a/Task/Read-entire-file/Mercury/read-entire-file.mercury b/Task/Read-entire-file/Mercury/read-entire-file.mercury new file mode 100644 index 0000000000..18f8a4f469 --- /dev/null +++ b/Task/Read-entire-file/Mercury/read-entire-file.mercury @@ -0,0 +1,27 @@ +:- module read_entire_file. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module string. + +main(!IO) :- + io.open_input("file.txt", OpenResult, !IO), + ( + OpenResult = ok(File), + io.read_file_as_string(File, ReadResult, !IO), + ( + ReadResult = ok(FileContents), + io.write_string(FileContents, !IO) + ; + ReadResult = error(_, IO_Error), + io.stderr_stream(Stderr, !IO), + io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO) + ) + ; + OpenResult = error(IO_Error), + io.stderr_stream(Stderr, !IO), + io.write_string(Stderr, io.error_message(IO_Error) ++ "\n", !IO) + ). diff --git a/Task/Read-entire-file/Raven/read-entire-file-1.raven b/Task/Read-entire-file/Raven/read-entire-file-1.raven new file mode 100644 index 0000000000..122bcebbfc --- /dev/null +++ b/Task/Read-entire-file/Raven/read-entire-file-1.raven @@ -0,0 +1 @@ +'myfile.txt' read as $content_as_string diff --git a/Task/Read-entire-file/Raven/read-entire-file-2.raven b/Task/Read-entire-file/Raven/read-entire-file-2.raven new file mode 100644 index 0000000000..835cf4ccd5 --- /dev/null +++ b/Task/Read-entire-file/Raven/read-entire-file-2.raven @@ -0,0 +1,3 @@ +'file://r:/home/me/myfile.txt' open as $handle +$handle read as $content_as_string +$handle close diff --git a/Task/Real-constants-and-functions/Aime/real-constants-and-functions.aime b/Task/Real-constants-and-functions/Aime/real-constants-and-functions.aime new file mode 100644 index 0000000000..e0b22e8734 --- /dev/null +++ b/Task/Real-constants-and-functions/Aime/real-constants-and-functions.aime @@ -0,0 +1,12 @@ +# e +exp(1); +# pi +2 * asin(1); + +sqrt(x); +log(x); +exp(x); +fabs(x); +floor(x); +ceil(x); +pow(x, y); diff --git a/Task/Real-constants-and-functions/Erlang/real-constants-and-functions.erl b/Task/Real-constants-and-functions/Erlang/real-constants-and-functions.erl new file mode 100644 index 0000000000..dfffbbcd36 --- /dev/null +++ b/Task/Real-constants-and-functions/Erlang/real-constants-and-functions.erl @@ -0,0 +1,35 @@ +% Implemented by Arjun Sunel +-module(math_constants). +-export([main/0]). +main() -> + io:format("~p~n", [math:exp(1)] ), % e + io:format("~p~n", [math:pi()] ), % pi + io:format("~p~n", [math:sqrt(16)] ), % square root + io:format("~p~n", [math:log(10)] ), % natural logarithm + io:format("~p~n", [math:log10(10)] ), % base 10 logarithm + io:format("~p~n", [math:exp(2)] ), % e raised to the power of x + io:format("~p~n", [abs(-2.24)] ), % absolute value + io:format("~p~n", [floor(3.1423)] ), % floor + io:format("~p~n", [ceil(20.125)] ), % ceiling + io:format("~p~n", [math:pow(3,2)] ). % exponentiation + +floor(X) when X < 0 -> + T = trunc(X), + case X - T == 0 of + true -> T; + false -> T - 1 + end; + +floor(X) -> + trunc(X). + + +ceil(X) when X < 0 -> + trunc(X); + +ceil(X) -> + T = trunc(X), + case X - T == 0 of + true -> T; + false -> T + 1 + end. diff --git a/Task/Record-sound/Racket/record-sound.rkt b/Task/Record-sound/Racket/record-sound.rkt new file mode 100644 index 0000000000..fbfb3f8795 --- /dev/null +++ b/Task/Record-sound/Racket/record-sound.rkt @@ -0,0 +1,4 @@ +#lang racket +(define (record n) (with-input-from-file "/dev/dsp" ( () (read-bytes n)))) +(define (play bs) (display-to-file bs "/dev/dsp" #:exists 'append)) +(play (record 65536)) diff --git a/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime b/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime new file mode 100644 index 0000000000..faf12b48a1 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime @@ -0,0 +1,108 @@ +void +rref(list l, integer rows, integer columns) +{ + integer e, i, j, lead, r; + list u, v; + + lead = 0; + r = 0; + while (r < rows) { + if (columns <= lead) { + break; + } + + i = r; + while (!l_q_integer(l_q_list(l, i), lead)) { + i += 1; + if (i == rows) { + i = r; + lead += 1; + if (lead == columns) { + break; + } + } + } + if (lead == columns) { + break; + } + + u = l_q_list(l, i); + + l_spin(l, i, r); + e = l_q_integer(u, lead); + if (e) { + j = 0; + while (j < columns) { + l_r_integer(u, j, l_q_integer(u, j) / e); + j += 1; + } + } + + i = 0; + while (i < rows) { + if (i != r) { + v = l_q_list(l, i); + e = l_q_integer(v, lead); + j = 0; + while (j < columns) { + l_r_integer + (v, j, l_q_integer(v, j) - l_q_integer(u, j) * e); + j += 1; + } + } + i += 1; + } + + lead += 1; + + r += 1; + } +} + +void +display_2(list l, integer rows, integer columns) +{ + integer i, j; + list u; + + i = 0; + while (i < rows) { + u = l_q_list(l, i); + j = 0; + while (j < columns) { + o_winteger(4, l_q_integer(u, j)); + j += 1; + } + i += 1; + o_byte('\n'); + } +} + +list +new_list(...) +{ + integer i; + list l; + + i = -count(); + while (i) { + l_append(l, $i); + i += 1; + } + + return l; +} + +integer +main(void) +{ + list l; + + l = new_list(new_list(1, 2, -1, -4), + new_list(2, 3, -1, -11), + new_list(-2, 0, -3, 22)); + rref(l, 3, 4); + display_2(l, 3, 4); + + return 0; +} diff --git a/Task/Regular-expressions/Raven/regular-expressions-3.raven b/Task/Regular-expressions/Raven/regular-expressions-3.raven index 58171a66a4..a2969bfeb7 100644 --- a/Task/Regular-expressions/Raven/regular-expressions-3.raven +++ b/Task/Regular-expressions/Raven/regular-expressions-3.raven @@ -1 +1 @@ -str r/ a / another / print +str r/ a / another / print diff --git a/Task/Regular-expressions/Raven/regular-expressions-4.raven b/Task/Regular-expressions/Raven/regular-expressions-4.raven new file mode 100644 index 0000000000..cf9bcec61b --- /dev/null +++ b/Task/Regular-expressions/Raven/regular-expressions-4.raven @@ -0,0 +1 @@ +str r/ /_/ print diff --git a/Task/Regular-expressions/Raven/regular-expressions-5.raven b/Task/Regular-expressions/Raven/regular-expressions-5.raven new file mode 100644 index 0000000000..95a1b53090 --- /dev/null +++ b/Task/Regular-expressions/Raven/regular-expressions-5.raven @@ -0,0 +1 @@ +str r/ /_/g print diff --git a/Task/Regular-expressions/Raven/regular-expressions-6.raven b/Task/Regular-expressions/Raven/regular-expressions-6.raven new file mode 100644 index 0000000000..3a5f5267b5 --- /dev/null +++ b/Task/Regular-expressions/Raven/regular-expressions-6.raven @@ -0,0 +1 @@ +str r/ A / another /i print diff --git a/Task/Regular-expressions/Raven/regular-expressions-7.raven b/Task/Regular-expressions/Raven/regular-expressions-7.raven new file mode 100644 index 0000000000..b3ef7bec0b --- /dev/null +++ b/Task/Regular-expressions/Raven/regular-expressions-7.raven @@ -0,0 +1 @@ +str s/ / diff --git a/Task/Remove-duplicate-elements/C++/remove-duplicate-elements-5.cpp b/Task/Remove-duplicate-elements/C++/remove-duplicate-elements-5.cpp new file mode 100644 index 0000000000..b06167b7e0 --- /dev/null +++ b/Task/Remove-duplicate-elements/C++/remove-duplicate-elements-5.cpp @@ -0,0 +1,14 @@ +#include +#include +#include + +int main() { + std::vector data = {1, 2, 3, 2, 3, 4}; + + std::sort(data.begin(), data.end()); + data.erase(std::unique(data.begin(), data.end()), data.end()); + + for(int& i: data) std::cout << i << " "; + std::cout << std::endl; + return 0; +} diff --git a/Task/Remove-duplicate-elements/C/remove-duplicate-elements-3.c b/Task/Remove-duplicate-elements/C/remove-duplicate-elements-3.c index d52c287d7f..14a274b59e 100644 --- a/Task/Remove-duplicate-elements/C/remove-duplicate-elements-3.c +++ b/Task/Remove-duplicate-elements/C/remove-duplicate-elements-3.c @@ -3,7 +3,7 @@ int icmp(const void *a, const void *b) { -#define _I(x) *(int*)x +#define _I(x) *(const int*)x return _I(a) < _I(b) ? -1 : _I(a) > _I(b); #undef _I } diff --git a/Task/Remove-duplicate-elements/Erlang/remove-duplicate-elements.erl b/Task/Remove-duplicate-elements/Erlang/remove-duplicate-elements.erl index 7a33cd6d06..69819da228 100644 --- a/Task/Remove-duplicate-elements/Erlang/remove-duplicate-elements.erl +++ b/Task/Remove-duplicate-elements/Erlang/remove-duplicate-elements.erl @@ -1,2 +1,4 @@ List = [1, 2, 3, 2, 2, 4, 5, 5, 4, 6, 6, 5]. UniqueList = gb_sets:to_list(gb_sets:from_list(List)). +% Alternatively the builtin: +Unique_list = lists:usort( List ). diff --git a/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-1.rkt b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-1.rkt new file mode 100644 index 0000000000..c38c4a44d3 --- /dev/null +++ b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-1.rkt @@ -0,0 +1,2 @@ +-> (remove-duplicates '(2 1 3 2.0 a 4 5 b 4 3 a 7 1 3 x 2)) +'(2 1 3 2.0 a 4 5 b 7 x) diff --git a/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-2.rkt b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-2.rkt new file mode 100644 index 0000000000..44f8e6cd10 --- /dev/null +++ b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-2.rkt @@ -0,0 +1,2 @@ +(define (unique/hash lst) + (hash-keys (for/hash ([x (in-list lst)]) (values x #t)))) diff --git a/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-3.rkt b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-3.rkt new file mode 100644 index 0000000000..9baf6b0f6c --- /dev/null +++ b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-3.rkt @@ -0,0 +1 @@ +(define unique/set (compose1 set->list list->set)) diff --git a/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-4.rkt b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-4.rkt new file mode 100644 index 0000000000..a0f8edafb9 --- /dev/null +++ b/Task/Remove-duplicate-elements/Racket/remove-duplicate-elements-4.rkt @@ -0,0 +1,4 @@ +(define (unique seq #:same-test [same? equal?]) + (for/fold ([res '()]) + ([x seq] #:unless (memf (curry same? x) res)) + (cons x res))) diff --git a/Task/Remove-lines-from-a-file/Java/remove-lines-from-a-file.java b/Task/Remove-lines-from-a-file/Java/remove-lines-from-a-file.java new file mode 100644 index 0000000000..34018b4669 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Java/remove-lines-from-a-file.java @@ -0,0 +1,54 @@ +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; + +public class RemoveLines +{ + public static void main(String[] args) + { + //Enter name of the file here + String filename="foobar.txt"; + //Enter starting line here + int startline=1; + //Enter number of lines here. + int numlines=2; + + RemoveLines now=new RemoveLines(); + now.delete(filename,startline,numlines); + } + void delete(String filename, int startline, int numlines) + { + try + { + BufferedReader br=new BufferedReader(new FileReader(filename)); + + //String buffer to store contents of the file + StringBuffer sb=new StringBuffer(""); + + //Keep track of the line number + int linenumber=1; + String line; + + while((line=br.readLine())!=null) + { + //Store each valid line in the string buffer + if(linenumber=startline+numlines) + sb.append(line+"\n"); + linenumber++; + } + if(startline+numlines>linenumber) + System.out.println("End of file reached."); + br.close(); + + FileWriter fw=new FileWriter(new File(filename)); + //Write entire string buffer into the file + fw.write(sb.toString()); + fw.close(); + } + catch (Exception e) + { + System.out.println("Something went horribly wrong: "+e.getMessage()); + } + } +} diff --git a/Task/Remove-lines-from-a-file/Racket/remove-lines-from-a-file.rkt b/Task/Remove-lines-from-a-file/Racket/remove-lines-from-a-file.rkt new file mode 100644 index 0000000000..1836ce9368 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Racket/remove-lines-from-a-file.rkt @@ -0,0 +1,5 @@ +#lang racket +(define (remove-lines file from num) + (define lines (file->lines file)) + (define-values [pfx rest] (split-at lines (sub1 from))) + (display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace)) diff --git a/Task/Rename-a-file/Raven/rename-a-file.raven b/Task/Rename-a-file/Raven/rename-a-file.raven new file mode 100644 index 0000000000..10496ce9b5 --- /dev/null +++ b/Task/Rename-a-file/Raven/rename-a-file.raven @@ -0,0 +1 @@ +`mv /path/to/file/oldfile /path/to/file/newfile` shell diff --git a/Task/Repeat-a-string/Julia/repeat-a-string.julia b/Task/Repeat-a-string/Julia/repeat-a-string.julia index 61dfc34329..d25ec786b0 100644 --- a/Task/Repeat-a-string/Julia/repeat-a-string.julia +++ b/Task/Repeat-a-string/Julia/repeat-a-string.julia @@ -1,2 +1,4 @@ "ha"^5 '*'^5 +#the (^) operator is really just call to the `repeat` function +repeat("ha",5) diff --git a/Task/Repeat-a-string/Racket/repeat-a-string-1.rkt b/Task/Repeat-a-string/Racket/repeat-a-string-1.rkt index 5dd06c19f4..f6b102738d 100644 --- a/Task/Repeat-a-string/Racket/repeat-a-string-1.rkt +++ b/Task/Repeat-a-string/Racket/repeat-a-string-1.rkt @@ -1,4 +1,5 @@ -; fast +#lang racket +;; fast (define (string-repeat n str) - (apply string-append (make-list n str))) -(string-repeat 5 "ha") ==> "hahahahaha" + (string-append* (make-list n str))) +(string-repeat 5 "ha") ; => "hahahahaha" diff --git a/Task/Repeat-a-string/Racket/repeat-a-string-2.rkt b/Task/Repeat-a-string/Racket/repeat-a-string-2.rkt index 89fd319d64..bf26460c17 100644 --- a/Task/Repeat-a-string/Racket/repeat-a-string-2.rkt +++ b/Task/Repeat-a-string/Racket/repeat-a-string-2.rkt @@ -1,7 +1 @@ -; memory efficient -(define (string-repeat n string) - (with-output-to-string - (λ () - (for ([_ (in-range n)]) - (display string))))) -(string-repeat 5 "ha") ==> "hahahahaha" +(make-string 5 #\*) => "*****" diff --git a/Task/Resistor-mesh/Go/resistor-mesh.go b/Task/Resistor-mesh/Go/resistor-mesh.go new file mode 100644 index 0000000000..174acdfde4 --- /dev/null +++ b/Task/Resistor-mesh/Go/resistor-mesh.go @@ -0,0 +1,102 @@ +package main + +import "fmt" + +const ( + S = 10 +) + +type node struct { + v float64 + fixed int +} + +func alloc2(w, h int) [][]node { + a := make([][]node, h) + + for i := range a { + a[i] = make([]node, w) + } + return a +} + +func set_boundary(m [][]node) { + m[1][1].fixed = 1 + m[1][1].v = 1 + m[6][7].fixed = -1 + m[6][7].v = -1 +} + +func calc_diff(m [][]node, d [][]node, w, h int) float64 { + total := 0.0 + for i := 0; i < h; i++ { + for j := 0; j < w; j++ { + v := 0.0 + n := 0 + if i != 0 { + v += m[i-1][j].v + n++ + } + if j != 0 { + v += m[i][j-1].v + n++ + } + if i+1 < h { + v += m[i+1][j].v + n++ + } + if j+1 < w { + v += m[i][j+1].v + n++ + } + + v = m[i][j].v - v/float64(n) + d[i][j].v = v + if m[i][j].fixed == 0 { + total += v * v + } + } + } + return total +} + +func iter(m [][]node, w, h int) float64 { + d := alloc2(w, h) + diff := 1.0e10 + cur := []float64{0, 0, 0} + + for diff > 1e-24 { + set_boundary(m) + diff = calc_diff(m, d, w, h) + for i := 0; i < h; i++ { + for j := 0; j < w; j++ { + m[i][j].v -= d[i][j].v + } + } + } + + for i := 0; i < h; i++ { + for j := 0; j < w; j++ { + t := 0 + if i != 0 { + t += 1 + } + if j != 0 { + t += 1 + } + if i < h-1 { + t += 1 + } + if j < w-1 { + t += 1 + } + cur[m[i][j].fixed+1] += d[i][j].v * float64(t) + } + } + return (cur[2] - cur[0]) / 2 +} + +func main() { + mesh := alloc2(S, S) + fmt.Printf("R = %g\n", 2/iter(mesh, S, S)) +} diff --git a/Task/Respond-to-an-unknown-method-call/Cache-ObjectScript/respond-to-an-unknown-method-call.cos b/Task/Respond-to-an-unknown-method-call/Cache-ObjectScript/respond-to-an-unknown-method-call.cos new file mode 100644 index 0000000000..0a8dc7a3f6 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Cache-ObjectScript/respond-to-an-unknown-method-call.cos @@ -0,0 +1,33 @@ +Class DynamicDispatch.Example Extends %RegisteredObject +{ + +Method Foo() +{ + Write "This is foo", ! +} + +Method Bar() +{ + Write "This is bar", ! +} + +Method %DispatchMethod(Method As %String, Args...) +{ + Write "Tried to handle unknown method '"_Method_"'" + For i=1:1:$Get(Args) { + Write ", " If i=1 Write "with arguments: " + Write "'"_Args(i)_"'" + } + Write ! +} + +ClassMethod Test() +{ + Set obj=##class(DynamicDispatch.Example).%New() + Do obj.Foo() + Do obj.Bar() + Do obj.Grill() + Do obj.Ding("Dong", 11) +} + +} diff --git a/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-1.m b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-1.m new file mode 100644 index 0000000000..a3e25297b6 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-1.m @@ -0,0 +1,59 @@ +#include + +// The methods need to be declared somewhere +@interface Dummy : NSObject { } +- (void)grill; +- (void)ding:(NSString *)s; +@end + +@interface Example : NSObject { } +- (void)foo; +- (void)bar; +@end + +@implementation Example +- (void)foo { + NSLog(@"this is foo"); +} +- (void)bar { + NSLog(@"this is bar"); +} +- (void)forwardInvocation:(NSInvocation *)inv { + NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector])); + unsigned n = [[inv methodSignature] numberOfArguments]; + unsigned i; + for (i = 0; i < n-2; i++) { // first two arguments are the object and selector + id arg; // we assume that all arguments are objects + [inv getArgument:&arg atIndex:i+2]; + NSLog(@"argument #%u: %@", i, arg); + } +} +// forwardInvocation: does not work without methodSignatureForSelector: +- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { + int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1; + // we assume that all arguments are objects + // The type encoding is "v@:@@@...", where "v" is the return type, void + // "@" is the receiver, object type; ":" is the selector of the current method; + // and each "@" after corresponds to an object argument + return [NSMethodSignature signatureWithObjCTypes: + [[@"v@:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]]; +} +@end + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + id example = [[Example alloc] init]; + + [example foo]; // prints "this is foo" + [example bar]; // prints "this is bar" + [example grill]; // prints "tried to handle unknown method grill" + [example ding:@"dong"]; // prints "tried to handle unknown method ding:" + // prints "argument #0: dong" + [example release]; + + [pool release]; + + return 0; +} diff --git a/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-2.m b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-2.m new file mode 100644 index 0000000000..da7ddd2da2 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Objective-C/respond-to-an-unknown-method-call-2.m @@ -0,0 +1,57 @@ +#include + +// The methods need to be declared somewhere +@interface Dummy : NSObject { } +- (void)grill; +- (void)ding:(NSString *)s; +@end + +@interface Example : NSObject { } +- (void)foo; +- (void)bar; +@end + +@implementation Example +- (void)foo { + NSLog(@"this is foo"); +} +- (void)bar { + NSLog(@"this is bar"); +} +- (void)forwardInvocation:(NSInvocation *)inv { + NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector])); + unsigned n = [[inv methodSignature] numberOfArguments]; + unsigned i; + for (i = 0; i < n-2; i++) { // first two arguments are the object and selector + id __unsafe_unretained arg; // we assume that all arguments are objects + [inv getArgument:&arg atIndex:i+2]; + NSLog(@"argument #%u: %@", i, arg); + } +} +// forwardInvocation: does not work without methodSignatureForSelector: +- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { + int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1; + // we assume that all arguments are objects + // The type encoding is "v@:@@@...", where "v" is the return type, void + // "@" is the receiver, object type; ":" is the selector of the current method; + // and each "@" after corresponds to an object argument + return [NSMethodSignature signatureWithObjCTypes: + [[@"v@:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]]; +} +@end + +int main() +{ + @autoreleasepool { + + id example = [[Example alloc] init]; + + [example foo]; // prints "this is foo" + [example bar]; // prints "this is bar" + [example grill]; // prints "tried to handle unknown method grill" + [example ding:@"dong"]; // prints "tried to handle unknown method ding:" + // prints "argument #0: dong" + + } + return 0; +} diff --git a/Task/Respond-to-an-unknown-method-call/Racket/respond-to-an-unknown-method-call-1.rkt b/Task/Respond-to-an-unknown-method-call/Racket/respond-to-an-unknown-method-call-1.rkt new file mode 100644 index 0000000000..778856a493 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Racket/respond-to-an-unknown-method-call-1.rkt @@ -0,0 +1,25 @@ +#lang racket + +(require racket/class) + +(define-syntax-rule (send~ obj method x ...) + ;; note: this is a naive macro, a real one should avoid evaluating `obj' and + ;; the `xs' more than once + (with-handlers ([(λ(e) (and (exn:fail:object? e) + ;; only do this if there *is* an `unknown-method' + (memq 'unknown-method (interface->method-names + (object-interface o))))) + (λ(e) (send obj unknown-method 'method x ...))]) + (send obj method x ...))) + +(define foo% + (class object% + (define/public (foo x) + (printf "foo: ~s\n" x)) + (define/public (unknown-method name . xs) + (printf "Unknown method ~s: ~s\n" name xs)) + (super-new))) + +(define o (new foo%)) +(send~ o foo 1) ; => foo: 1 +(send~ o whatever 1) ; Unknown method whatever: (1) diff --git a/Task/Respond-to-an-unknown-method-call/Racket/respond-to-an-unknown-method-call-2.rkt b/Task/Respond-to-an-unknown-method-call/Racket/respond-to-an-unknown-method-call-2.rkt new file mode 100644 index 0000000000..0e95bb42ff --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Racket/respond-to-an-unknown-method-call-2.rkt @@ -0,0 +1,12 @@ +#lang swindle + +(defgeneric (foo x)) +(defmethod (no-applicable-method [m (singleton foo)] xs) + (echo "No method in" m "for" :w xs)) +(defmethod (foo [x ]) (echo "It's an integer")) + +(foo 1) +;; => It's an integer + +(foo "one") +;; => No method in # for "one" diff --git a/Task/Return-multiple-values/C/return-multiple-values-1.c b/Task/Return-multiple-values/C/return-multiple-values-1.c new file mode 100644 index 0000000000..728a541197 --- /dev/null +++ b/Task/Return-multiple-values/C/return-multiple-values-1.c @@ -0,0 +1,25 @@ +#include + +typedef struct{ + int integer; + float decimal; + char letter; + char string[100]; + double bigDecimal; +}Composite; + +Composite example() +{ + Composite C = {1, 2.3, 'a', "Hello World", 45.678}; + return C; +} + + +int main() +{ + Composite C = example(); + + printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}\n", C.integer, C.decimal, C.letter, C.string, C.bigDecimal); + + return 0; +} diff --git a/Task/Return-multiple-values/C/return-multiple-values-2.c b/Task/Return-multiple-values/C/return-multiple-values-2.c new file mode 100644 index 0000000000..72c27fb37c --- /dev/null +++ b/Task/Return-multiple-values/C/return-multiple-values-2.c @@ -0,0 +1,18 @@ +#include + +typedef struct { + char *first, *last; +} Name; + +Name whatsMyName() { + return (Name) { + .first = "James", + .last = "Bond", + }; +} + +int main() { + Name me = whatsMyName(); + printf("The name's %s. %s %s.\n", me.last, me.first, me.last); + return 0; +} diff --git a/Task/Return-multiple-values/Erlang/return-multiple-values.erl b/Task/Return-multiple-values/Erlang/return-multiple-values.erl new file mode 100644 index 0000000000..6cb55fc2e0 --- /dev/null +++ b/Task/Return-multiple-values/Erlang/return-multiple-values.erl @@ -0,0 +1,17 @@ +% Implemented by Arjun Sunel +-module(return_multi). +-export([main/0]). + +main() -> + K=multiply(3,4), + C =lists:nth(1,K), + D = lists:nth(2,K), + E = lists:nth(3,K), + io:format("~p~n",[C]), + io:format("~p~n",[D]), + io:format("~p~n",[E]). + +multiply(A,B) -> + case {A,B} of + {A, B} ->[A*B, A+B, A-B] + end. diff --git a/Task/Return-multiple-values/Fortran/return-multiple-values.f b/Task/Return-multiple-values/Fortran/return-multiple-values.f new file mode 100644 index 0000000000..041193dd63 --- /dev/null +++ b/Task/Return-multiple-values/Fortran/return-multiple-values.f @@ -0,0 +1,20 @@ +module multiple_values +implicit none +type res + integer :: p, m +end type + +contains + +function addsub(x,y) result(r) + integer :: x, y + type(res) :: r + r%p = x+y + r%m = x-y +end function +end module + +program main + use multiple_values + print *, addsub(33, 22) +end program diff --git a/Task/Return-multiple-values/Racket/return-multiple-values.rkt b/Task/Return-multiple-values/Racket/return-multiple-values.rkt new file mode 100644 index 0000000000..3c67f12be4 --- /dev/null +++ b/Task/Return-multiple-values/Racket/return-multiple-values.rkt @@ -0,0 +1,7 @@ +#lang racket +(values 4 5) + +(define (my-values . return-list) + (call/cc + (lambda (return) + (apply return return-list)))) diff --git a/Task/Return-multiple-values/Raven/return-multiple-values.raven b/Task/Return-multiple-values/Raven/return-multiple-values.raven new file mode 100644 index 0000000000..4bac6c2b46 --- /dev/null +++ b/Task/Return-multiple-values/Raven/return-multiple-values.raven @@ -0,0 +1,4 @@ +define multiReturn use $v + $v each + +3 multiReturn diff --git a/Task/Reverse-a-string/Aime/reverse-a-string.aime b/Task/Reverse-a-string/Aime/reverse-a-string.aime new file mode 100644 index 0000000000..b4e1888a13 --- /dev/null +++ b/Task/Reverse-a-string/Aime/reverse-a-string.aime @@ -0,0 +1,23 @@ +text +reverse(text s) +{ + data b; + integer i; + + i = length(s); + while (i) { + i -= 1; + b_insert(b, -1, character(s, i)); + } + + return b_string(b); +} + +integer +main(void) +{ + o_text(reverse("Hello, World!")); + o_byte('\n'); + + return 0; +} diff --git a/Task/Reverse-a-string/FBSL/reverse-a-string-1.fbsl b/Task/Reverse-a-string/FBSL/reverse-a-string-1.fbsl index c37971ad09..05c9f15646 100644 --- a/Task/Reverse-a-string/FBSL/reverse-a-string-1.fbsl +++ b/Task/Reverse-a-string/FBSL/reverse-a-string-1.fbsl @@ -1,8 +1,8 @@ Function StrRev1(ByVal $p1) dim $b = "" - repeat len(p1) - b = b & right(p1,1) - p1 = left(p1,len(p1)-1) - end repeat + REPEAT len(p1) + b = b & RIGHT(p1,1) + p1 = LEFT(p1,LEN(p1)-1) + END REPEAT return b End Function diff --git a/Task/Reverse-a-string/FBSL/reverse-a-string-2.fbsl b/Task/Reverse-a-string/FBSL/reverse-a-string-2.fbsl index 6024fba0bb..44f6fd3de3 100644 --- a/Task/Reverse-a-string/FBSL/reverse-a-string-2.fbsl +++ b/Task/Reverse-a-string/FBSL/reverse-a-string-2.fbsl @@ -1,8 +1,7 @@ Function StrRev2(ByVal $p1) - dim $b = "" - dim %i - for i = len(p1) downto 1 - b = b & mid(p1,i,1) + dim $b = "", %i + for i = len(p1) DOWNTO 1 + b = b & MID(p1,i,1) next return b End Function diff --git a/Task/Reverse-a-string/FBSL/reverse-a-string-5.fbsl b/Task/Reverse-a-string/FBSL/reverse-a-string-5.fbsl new file mode 100644 index 0000000000..5e005fc312 --- /dev/null +++ b/Task/Reverse-a-string/FBSL/reverse-a-string-5.fbsl @@ -0,0 +1,49 @@ +DYNASM RevStr(BYVAL s AS STRING) AS STRING + // get length of string + // divide by two + // setup pointers to head and tail + // iterate from 1 to (length \ 2) + // swap head with tail + // increment head pointer + // decrement tail pointer + + ENTER 0, 0 // = PUSH EBP: MOV EBP, ESP + PUSH EBX // by Windows convention EBX, EDI, ESI must be saved before modification + + MOV EAX, s // get string pointer + MOV ECX, EAX // duplicate it + + .WHILE BYTE PTR [ECX] <> 0 + + INC ECX // propagate to tail + + .WEND + + MOV EDX, ECX // duplicate tail pointer + DEC EDX // set it to last byte before trailing zero + + SUB ECX, EAX // get length in ECX in 1 CPU cycle + SHR ECX, 1 // get length \ 2 in 1 CPU cycle; that's the beauty of power-of-two division + + .WHILE ECX > 0 + + MOV BL, [EDX] // no need to XOR; just overwrite BL and BH contents + MOV BH, [EAX] // DynAsm deduces data size from destination register sizes + + MOV [EDX], BH // ditto, source register sizes + MOV [EAX], BL + + INC EAX // propagate pointers + DEC EDX + + DEC ECX // decrement counter + + .WEND + + // point to start of string again + MOV EAX, s // MOV = 1 CPU cycle, PUSH + POP = 2 CPU cycles + + POP EBX // by Windows convention ESI, EDI, EBX must be restored if modified + LEAVE // = POP EBP + RET +END DYNASM diff --git a/Task/Reverse-a-string/Raven/reverse-a-string.raven b/Task/Reverse-a-string/Raven/reverse-a-string.raven new file mode 100644 index 0000000000..5e81082950 --- /dev/null +++ b/Task/Reverse-a-string/Raven/reverse-a-string.raven @@ -0,0 +1 @@ +"asdf" reverse diff --git a/Task/Reverse-a-string/UNIX-Shell/reverse-a-string.sh b/Task/Reverse-a-string/UNIX-Shell/reverse-a-string.sh new file mode 100644 index 0000000000..cb83102b8f --- /dev/null +++ b/Task/Reverse-a-string/UNIX-Shell/reverse-a-string.sh @@ -0,0 +1,6 @@ +#!/bin/bash +str=abcde + +for((i=${#str}-1;i>=0;i--)); do rev="$rev${str:$i:1}"; done + +echo $rev diff --git a/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime new file mode 100644 index 0000000000..97cf20a9ee --- /dev/null +++ b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime @@ -0,0 +1,82 @@ +text +computer_play(record plays, record beats) +{ + integer a, total; + text s; + + total = r_q_integer(plays, "rock") + r_q_integer(plays, "paper") + + r_q_integer(plays, "scissors"); + a = drand(total - 1); + r_first(plays, s); + do { + if (a < r_q_integer(plays, s)) { + break; + } + a -= r_q_integer(plays, s); + } while (r_greater(plays, s, s)); + + return r_q_text(beats, s); +} + +integer +main(void) +{ + integer computer, human; + record beats, plays; + file f; + text s; + + computer = 0; + human = 0; + + f_affix(f, "/dev/stdin"); + + r_put(beats, "rock", "paper"); + r_put(beats, "paper", "scissors"); + r_put(beats, "scissors", "rock"); + + r_put(plays, "rock", 1); + r_put(plays, "paper", 1); + r_put(plays, "scissors", 1); + + while (1) { + o_text("Your choice [rock/paper/scissors]:\n"); + if (f_line(f, s) == -1) { + break; + } + + if (!r_key(plays, s)) { + o_text("Invalid choice, try again\n"); + } else { + text c; + + c = computer_play(plays, beats); + + o_text("Human: "); + o_text(s); + o_text(", Computer: "); + o_text(c); + o_text("\n"); + + if (!compare(s, c)) { + o_text("Draw\n"); + } elif (!compare(c, r_q_text(beats, s))) { + computer += 1; + o_text("Computer wins\n"); + } else { + human += 1; + o_text("Human wins\n"); + } + + r_r_integer(plays, s, r_q_integer(plays, s) + 1); + + o_text("Score: Human: "); + o_integer(human); + o_text(", Computer: "); + o_integer(computer); + o_text("\n"); + } + } + + return 0; +} diff --git a/Task/Rock-paper-scissors/C++/rock-paper-scissors.cpp b/Task/Rock-paper-scissors/C++/rock-paper-scissors.cpp index d51bdcb61e..e89f51f18f 100644 --- a/Task/Rock-paper-scissors/C++/rock-paper-scissors.cpp +++ b/Task/Rock-paper-scissors/C++/rock-paper-scissors.cpp @@ -6,7 +6,7 @@ using namespace std; //------------------------------------------------------------------------------- -enum choices { ROCK, PAPER, SCISSORS }; +enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C }; enum indexes { PLAYER, COMPUTER, DRAW }; //------------------------------------------------------------------------------- @@ -15,39 +15,40 @@ class stats public: stats() : _draw( 0 ) { - ZeroMemory( _moves, sizeof( _moves ) ); + ZeroMemory( _moves, sizeof( _moves ) ); ZeroMemory( _win, sizeof( _win ) ); } void draw() { _draw++; } void win( int p ) { _win[p]++; } void move( int p, int m ) { _moves[p][m]++; } int getMove( int p, int m ) { return _moves[p][m]; } + string format( int a ) + { + char t[32]; + wsprintf( t, "%.3d", a ); + string d( t ); + return d; + } + void print() { - char t[256]; - wsprintf( t, "%.4d", _draw ); string d( t ); - - wsprintf( t, "%.4d", _win[PLAYER] ); string pw( t ); - wsprintf( t, "%.4d", _moves[PLAYER][ROCK] ); string pr( t ); - wsprintf( t, "%.4d", _moves[PLAYER][PAPER] ); string pp( t ); - wsprintf( t, "%.4d", _moves[PLAYER][SCISSORS] ); string ps( t ); - - wsprintf( t, "%.4d", _win[COMPUTER] ); string cw( t ); - wsprintf( t, "%.4d", _moves[COMPUTER][ROCK] ); string cr( t ); - wsprintf( t, "%.4d", _moves[COMPUTER][PAPER] ); string cp( t ); - wsprintf( t, "%.4d", _moves[COMPUTER][SCISSORS] ); string cs( t ); + string d = format( _draw ), + pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ), + pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ), + pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ), + ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ), + pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ), + pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] ); system( "cls" ); cout << endl; - cout << "+--------------+----------+----------+----------+----------+----------+" << endl; - cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS |" << endl; - cout << "+--------------+----------+----------+----------+----------+----------+" << endl; - cout << "| PLAYER | " << pw << " | | " << pr; - cout << " | " << pp << " | " << ps << " |" << endl; - cout << "+--------------+----------+ " << d << " +----------+----------+----------+" << endl; - cout << "| COMPUTER | " << cw << " | | " << cr; - cout << " | " << cp << " | " << cs << " |" << endl; - cout << "+--------------+----------+----------+----------+----------+----------+" << endl; + cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; + cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl; + cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; + cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl; + cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl; + cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl; + cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << endl << endl; system( "pause" ); @@ -55,7 +56,7 @@ public: } private: - int _moves[2][3], _win[2], _draw; + int _moves[2][MX_C], _win[2], _draw; }; //------------------------------------------------------------------------------- class rps @@ -64,71 +65,52 @@ private: int makeMove() { int total = 0, r, s; - for( int i = 0; i < 3; total += statistics.getMove( PLAYER, i++ ) ); + for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) ); r = rand() % total; - s = statistics.getMove( PLAYER, ROCK ); - if( r < s ) return PAPER; - if( r - s < statistics.getMove( PLAYER, PAPER ) ) return SCISSORS; - return ROCK; - } - int checkWinner( int p, int m ) - { - if( p == ROCK ) + for( int i = ROCK; i < SCISSORS; i++ ) { - switch( m ) - { - case PAPER: return COMPUTER; - case SCISSORS: return PLAYER; - default: return DRAW; - } + s = statistics.getMove( PLAYER, i ); + if( r < s ) return ( i + 1 ); + r -= s; } - if( p == PAPER ) - { - switch( m ) - { - case SCISSORS: return COMPUTER; - case ROCK: return PLAYER; - default: return DRAW; - } - } - if( p == SCISSORS ) - { - switch( m ) - { - case ROCK: return COMPUTER; - case PAPER: return PLAYER; - default: return DRAW; - } - } - return DRAW; + + return ROCK; } void printMove( int p, int m ) { - string ms = ""; - switch( m ) - { - case 0: ms = "ROCK"; break; - case 1: ms = "PAPER"; break; - case 2: ms = "SCISSORS"; break; - } - if( p == COMPUTER ) cout << "My move: "; else cout << "Your move: "; - cout << ms << endl; + + switch( m ) + { + case ROCK: cout << "ROCK\n"; break; + case PAPER: cout << "PAPER\n"; break; + case SCISSORS: cout << "SCISSORS\n"; break; + case LIZARD: cout << "LIZARD\n"; break; + case SPOCK: cout << "SPOCK\n"; + } } public: + rps() + { + checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1; + checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0; + checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1; + checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0; + checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2; + } void play() { int p, r, m; while( true ) { - cout << "What is your move (1)ROCK (2)PAPER (3)SCISSORS (0)Quit ? "; + cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? "; cin >> p; if( !p || p < 0 ) break; - if( p > 0 && p < 4 ) + if( p > 0 && p < 6 ) { p--; cout << endl; @@ -139,34 +121,32 @@ public: statistics.move( COMPUTER, m ); printMove( COMPUTER, m ); - r = checkWinner( p, m ); + r = checker[p][m]; switch( r ) { case DRAW: - cout << endl << "DRAW!" << endl << endl; - statistics.draw(); - + cout << endl << "DRAW!" << endl << endl; + statistics.draw(); break; case COMPUTER: cout << endl << "I WIN!" << endl << endl; statistics.win( COMPUTER ); - break; case PLAYER: - cout << endl << "YOU WIN!" << endl << endl; - statistics.win( PLAYER ); + cout << endl << "YOU WIN!" << endl << endl; + statistics.win( PLAYER ); } - system( "pause" ); + system( "pause" ); } system( "cls" ); } - - statistics.print(); + statistics.print(); } private: stats statistics; + int checker[MX_C][MX_C]; }; //------------------------------------------------------------------------------- int main( int argc, char* argv[] ) diff --git a/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d b/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d new file mode 100644 index 0000000000..74b4929c8a --- /dev/null +++ b/Task/Rock-paper-scissors/D/rock-paper-scissors-1.d @@ -0,0 +1,60 @@ +import std.stdio, std.random, std.string, std.array, + std.typecons, std.traits, std.conv, std.algorithm; + +enum Choice { rock, paper, scissors } +immutable order = [EnumMembers!Choice]; + +uint[order.length] choiceFrequency; + +Choice whatBeats(in Choice ch) pure /*nothrow*/ { + return order[(order.countUntil(ch) + 1) % $]; +} + +Nullable!Choice checkWinner(in Choice a, in Choice b) +pure /*nothrow*/ { + alias TResult = typeof(return); + + if (b == whatBeats(a)) + return TResult(b); + else if (a == whatBeats(b)) + return TResult(a); + return TResult(); +} + +Choice getRandomChoice() /*nothrow*/ { + if (choiceFrequency[].reduce!q{a + b} == 0) + return uniform!Choice; + return order[choiceFrequency.dice].whatBeats; +} + +void main() { + writeln("Rock-Paper-Scissors Game"); + + while (true) { + write("Your choice (empty to end game): "); + immutable humanChoiceStr = readln.strip.toLower; + if (humanChoiceStr.empty) + break; + + Choice humanChoice; + try { + humanChoice = humanChoiceStr.to!Choice; + } catch (ConvException e) { + writeln("Wrong input: ", humanChoiceStr); + continue; + } + + immutable compChoice = getRandomChoice; + write("Computer picked ", compChoice, ", "); + + // Don't register the player choice until after + // the computer has made its choice. + choiceFrequency[humanChoice]++; + + immutable winner = checkWinner(humanChoice, compChoice); + if (winner.isNull) + writeln("Nobody wins!"); + else + writeln(winner.get, " wins!"); + } +} diff --git a/Task/Rock-paper-scissors/D/rock-paper-scissors-2.d b/Task/Rock-paper-scissors/D/rock-paper-scissors-2.d new file mode 100644 index 0000000000..cfd9c80370 --- /dev/null +++ b/Task/Rock-paper-scissors/D/rock-paper-scissors-2.d @@ -0,0 +1,55 @@ +import std.stdio, std.random, std.string, std.conv, std.array, + std.typecons; + +enum Choice { rock, paper, scissors } + +bool beats(in Choice c1, in Choice c2) pure nothrow { + return (c1 == Choice.paper && c2 == Choice.rock) || + (c1 == Choice.scissors && c2 == Choice.paper) || + (c1 == Choice.rock && c2 == Choice.scissors); +} + +Choice genMove(in int r, in int p, in int s) { + immutable x = uniform!"[]"(1, r + p + s); + if (x < s) return Choice.rock; + if (x <= s + r) return Choice.paper; + else return Choice.scissors; +} + +Nullable!To maybeTo(To, From)(From x) { + try { + return typeof(return)(x.to!To); + } catch (ConvException e) { + return typeof(return)(); + } +} + +void main() { + int r = 1, p = 1, s = 1; + + while (true) { + write("rock, paper or scissors? "); + immutable hs = readln.strip.toLower; + if (hs.empty) + break; + + immutable h = hs.maybeTo!Choice; + if (h.isNull) { + writeln("Wrong input: ", hs); + continue; + } + + immutable c = genMove(r, p, s); + writeln("Player: ", h, " Computer: ", c); + + if (beats(h, c)) writeln("Player wins\n"); + else if (beats(c, h)) writeln("Player loses\n"); + else writeln("Draw\n"); + + final switch (h.get) { + case Choice.rock: r++; break; + case Choice.paper: p++; break; + case Choice.scissors: s++; break; + } + } +} diff --git a/Task/Rock-paper-scissors/Racket/rock-paper-scissors.rkt b/Task/Rock-paper-scissors/Racket/rock-paper-scissors.rkt new file mode 100644 index 0000000000..a5343679fe --- /dev/null +++ b/Task/Rock-paper-scissors/Racket/rock-paper-scissors.rkt @@ -0,0 +1,34 @@ +#lang racket +(require math) + +(define history (make-hash '((paper . 1) (scissors . 1) (rock . 1)))) +(define total 3) + +(define (update-history! human-choice) + (set! total (+ total 1)) + (hash-update! history human-choice add1 0)) + +(define (pick-one) + (sample + (discrete-dist '(paper scissors rock) + (map (λ (x) (hash-ref history x)) + '(scissors paper rock))))) + +(define (find-winner computer human) + (define order '(scissors paper rock scissors)) + (cond + [(eq? computer human) 'none] + [(eq? (second (member computer order)) human) 'computer] + [ 'human])) + +(define (game-loop) + (define computer-choice (pick-one)) + (define human-choice (read)) + (define winner (find-winner computer-choice human-choice)) + (update-history! human-choice) + (displayln (~a "Computer picked " computer-choice ", " + "human picked " human-choice ", " + winner " wins.")) + (game-loop)) + +(game-loop) diff --git a/Task/Rock-paper-scissors/Seed7/rock-paper-scissors.seed7 b/Task/Rock-paper-scissors/Seed7/rock-paper-scissors.seed7 new file mode 100644 index 0000000000..6882c14e8b --- /dev/null +++ b/Task/Rock-paper-scissors/Seed7/rock-paper-scissors.seed7 @@ -0,0 +1,35 @@ +$ include "seed7_05.s7i"; +$ include "keybd.s7i"; + +const array string: rockPaperScissors is [] ("Rock", "Paper", "Scissors"); + +const proc: main is func + local + var char: command is ' '; + var integer: user is 0; + var integer: comp is 0; + begin + writeln("Hello, Welcome to rock-paper-scissors"); + repeat + write("Please type in 1 for Rock, 2 for Paper, 3 for Scissors, q to quit "); + flush(OUT); + repeat + command := lower(getc(KEYBOARD)); + until command in {'1', '2', '3', 'q'}; + writeln(command); + if command <> 'q' then + user := integer parse str(command); + comp := rand(1, 3); + writeln("You Played: " <& rockPaperScissors[user]); + writeln("Computer Played: " <& rockPaperScissors[comp]); + if comp = user then + writeln("You Tied"); + elsif succ(comp) = user or user + 2 = comp then + writeln("Yay, You Won!"); + else + writeln("Sorry, You Lost!"); + end if; + end if; + until command = 'q'; + writeln("Goodbye! Thanks for playing!"); + end func; diff --git a/Task/Roman-numerals-Decode/COBOL/roman-numerals-decode.cobol b/Task/Roman-numerals-Decode/COBOL/roman-numerals-decode.cobol new file mode 100644 index 0000000000..46efa814e7 --- /dev/null +++ b/Task/Roman-numerals-Decode/COBOL/roman-numerals-decode.cobol @@ -0,0 +1,75 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. UNROMAN. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 filler. + 03 i pic 9(02) comp. + 03 j pic 9(02) comp. + 03 k pic 9(02) comp. + 03 l pic 9(02) comp. + 01 inp-roman. + 03 inp-rom-ch pic x(01) occurs 20 times. + 01 inp-roman-digits. + 03 inp-rom-digit pic 9(01) occurs 20 times. + 01 ws-search-idx pic 9(02) comp. + 01 ws-tbl-table-def. + 03 filler pic x(05) value '1000M'. + 03 filler pic x(05) value '0500D'. + 03 filler pic x(05) value '0100C'. + 03 filler pic x(05) value '0050L'. + 03 filler pic x(05) value '0010X'. + 03 filler pic x(05) value '0005V'. + 03 filler pic x(05) value '0001I'. + 01 filler redefines ws-tbl-table-def. + 03 ws-tbl-roman occurs 07 times indexed by rx. + 05 ws-tbl-rom-val pic 9(04). + 05 ws-tbl-rom-ch pic x(01). + 01 ws-number pic s9(05) value 0. + 01 ws-number-pic pic zzzz9-. + + PROCEDURE DIVISION. + accept inp-roman + perform + until inp-roman = ' ' + move zeroes to inp-roman-digits + perform + varying i from 1 by +1 until inp-rom-ch (i) = ' ' + set rx to 1 + search ws-tbl-roman + at end + move 0 to inp-rom-digit (i) + when ws-tbl-rom-ch (rx) = inp-rom-ch (i) + set inp-rom-digit (i) to rx + end-search + end-perform + compute l = i - 1 + move 0 to ws-number + perform + varying i from 1 by +1 + until i > l or inp-rom-digit (i) = 0 + compute j = inp-rom-digit (i) + compute k = inp-rom-digit (i + 1) + if ws-tbl-rom-val (k) + > ws-tbl-rom-val (j) + compute ws-number + = ws-number + - ws-tbl-rom-val (j) + else + compute ws-number + = ws-number + + ws-tbl-rom-val (j) + end-if + end-perform + move ws-number to ws-number-pic + display '----------' + display 'roman=' inp-roman + display 'arabic=' ws-number-pic + if i < l or ws-number = 0 + display 'invalid/incomplete roman numeral at pos 'i + ' found ' inp-rom-ch (i) + end-if + accept inp-roman + end-perform + stop run + . + END PROGRAM UNROMAN. diff --git a/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode-1.lisp b/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode-1.lisp new file mode 100644 index 0000000000..439f436c18 --- /dev/null +++ b/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode-1.lisp @@ -0,0 +1,6 @@ +(defun mapcn (chars nums string) + (loop as char across string as i = (position char chars) collect (and i (nth i nums)))) + +(defun parse-roman (R) + (loop with nums = (mapcn "IVXLCDM" '(1 5 10 50 100 500 1000) R) + as (A B) on nums if A sum (if (and B (< A B)) (- A) A))) diff --git a/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode-2.lisp b/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode-2.lisp new file mode 100644 index 0000000000..a688e523c7 --- /dev/null +++ b/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode-2.lisp @@ -0,0 +1,2 @@ +(dolist (r '("MCMXC" "MDCLXVI" "MMVIII")) + (format t "~a:~10t~d~%" r (parse-roman r))) diff --git a/Task/Roman-numerals-Decode/REXX/roman-numerals-decode-2.rexx b/Task/Roman-numerals-Decode/REXX/roman-numerals-decode-2.rexx index a8c666e459..7f9c864a34 100644 --- a/Task/Roman-numerals-Decode/REXX/roman-numerals-decode-2.rexx +++ b/Task/Roman-numerals-Decode/REXX/roman-numerals-decode-2.rexx @@ -1,30 +1,29 @@ /*REXX program to convert Roman numeral number(s) to Arabic number(s). */ - -rYear='MCMXC' ; say right(rYear,9)':' rom2dec(rYear) -rYear='mmviii' ; say right(rYear,9)':' rom2dec(rYear) -rYear='MDCLXVI' ; say right(rYear,9)':' rom2dec(rYear) +rYear = 'MCMXC' ; say right(rYear,9)':' rom2dec(rYear) +rYear = 'mmviii' ; say right(rYear,9)':' rom2dec(rYear) +rYear = 'MDCLXVI' ; say right(rYear,9)':' rom2dec(rYear) exit -rom2dec: procedure; arg roman . -if verify(roman,'MDCLXVI')\==0 then do - say 'invalid Roman number:' roman - return '***error!***' - end +rom2dec: procedure; arg roman . +if verify(roman,'MDCLXVI')\==0 then do + say 'invalid Roman number:' roman + return '***error!***' + end #=rChar(right(roman,1)) /*start with the last numeral*/ - do j=1 for length(roman)-1 + do j=1 for length(roman) - 1 x=rChar(substr(roman,j ,1)) /*the current Roman numeral. */ y=rChar(substr(roman,j+1,1)) /*the next Roman numeral. */ - if xlist number))) + (+ (last lst) + (for/fold ((sum 0)) + ((i (in-list lst)) (i+1 (in-list (cdr lst)))) + (+ sum + (if (> i+1 i) + (- i) + i))))) + +(map decode/roman '("MCMXC" "MMVIII" "MDCLXVI")) +;-> '(1990 2008 1666) diff --git a/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode-1.sh b/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode-1.sh new file mode 100644 index 0000000000..7ad9d70121 --- /dev/null +++ b/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode-1.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +roman_to_dec() { + local rnum=$1 + local n=0 + local prev=0 + + for ((i=${#rnum}-1;i>=0;i--)) + do + case "${rnum:$i:1}" in + M) a=1000 ;; + D) a=500 ;; + C) a=100 ;; + L) a=50 ;; + X) a=10 ;; + V) a=5 ;; + I) a=1 ;; + esac + + if [[ $a -lt $prev ]] + then + let n-=a + else + let n+=a + fi + + prev=$a + done + + echo "$rnum = $n" +} + +roman_to_dec MCMXC +roman_to_dec MMVIII +roman_to_dec MDCLXVI diff --git a/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode-2.sh b/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode-2.sh new file mode 100644 index 0000000000..51dd365253 --- /dev/null +++ b/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode-2.sh @@ -0,0 +1,20 @@ +#!/bin/zsh +function parseroman () { + local max=0 sum i j + local -A conv + conv=(I 1 V 5 X 10 L 50 C 100 D 500 M 1000) + for j in ${(Oas::)1}; do + i=conv[$j] + if (( i >= max )); then + (( sum+=i )) + (( max=i )) + else + (( sum-=i )) + fi + done + echo $sum +} + +parseroman MCMXC +parseroman MMVIII +parseroman MDCLXVI diff --git a/Task/Roman-numerals-Encode/COBOL/roman-numerals-encode.cobol b/Task/Roman-numerals-Encode/COBOL/roman-numerals-encode.cobol new file mode 100644 index 0000000000..92dda47627 --- /dev/null +++ b/Task/Roman-numerals-Encode/COBOL/roman-numerals-encode.cobol @@ -0,0 +1,53 @@ +IDENTIFICATION DIVISION. +PROGRAM-ID. TOROMAN. +DATA DIVISION. +working-storage section. + 01 ws-number pic 9(4) value 0. + 01 ws-save-number pic 9(4). + 01 ws-tbl-def. + 03 filler pic x(7) value '1000M '. + 03 filler pic x(7) value '0900CM '. + 03 filler pic x(7) value '0500D '. + 03 filler pic x(7) value '0400CD '. + 03 filler pic x(7) value '0100C '. + 03 filler pic x(7) value '0090XC '. + 03 filler pic x(7) value '0050L '. + 03 filler pic x(7) value '0040XL '. + 03 filler pic x(7) value '0010X '. + 03 filler pic x(7) value '0009IX '. + 03 filler pic x(7) value '0005V '. + 03 filler pic x(7) value '0004IV '. + 03 filler pic x(7) value '0001I '. + 01 filler redefines ws-tbl-def. + 03 filler occurs 13 times indexed by rx. + 05 ws-tbl-divisor pic 9(4). + 05 ws-tbl-roman-ch pic x(1) occurs 3 times indexed by cx. + 01 ocx pic 99. + 01 ws-roman. + 03 ws-roman-ch pic x(1) occurs 16 times. +PROCEDURE DIVISION. + accept ws-number + perform + until ws-number = 0 + move ws-number to ws-save-number + if ws-number > 0 and ws-number < 4000 + initialize ws-roman + move 0 to ocx + perform varying rx from 1 by +1 + until ws-number = 0 + perform until ws-number < ws-tbl-divisor (rx) + perform varying cx from 1 by +1 + until ws-tbl-roman-ch (rx, cx) = spaces + compute ocx = ocx + 1 + move ws-tbl-roman-ch (rx, cx) to ws-roman-ch (ocx) + end-perform + compute ws-number = ws-number - ws-tbl-divisor (rx) + end-perform + end-perform + display 'inp=' ws-save-number ' roman=' ws-roman + else + display 'inp=' ws-save-number ' invalid' + end-if + accept ws-number + end-perform + . diff --git a/Task/Roman-numerals-Encode/Racket/roman-numerals-encode.rkt b/Task/Roman-numerals-Encode/Racket/roman-numerals-encode.rkt new file mode 100644 index 0000000000..b796d884db --- /dev/null +++ b/Task/Roman-numerals-Encode/Racket/roman-numerals-encode.rkt @@ -0,0 +1,15 @@ +#lang racket +(define (encode/roman number) + (cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000)))) + ((>= number 900) (string-append "CM" (encode/roman (- number 900)))) + ((>= number 500) (string-append "D" (encode/roman (- number 500)))) + ((>= number 400) (string-append "CD" (encode/roman (- number 400)))) + ((>= number 100) (string-append "C" (encode/roman (- number 100)))) + ((>= number 90) (string-append "XC" (encode/roman (- number 90)))) + ((>= number 50) (string-append "L" (encode/roman (- number 50)))) + ((>= number 40) (string-append "XL" (encode/roman (- number 40)))) + ((>= number 10) (string-append "X" (encode/roman (- number 10)))) + ((>= number 5) (string-append "V" (encode/roman (- number 5)))) + ((>= number 4) (string-append "IV" (encode/roman (- number 4)))) + ((>= number 1) (string-append "I" (encode/roman (- number 1)))) + (else ""))) diff --git a/Task/Roots-of-a-function/Erlang/roots-of-a-function.erl b/Task/Roots-of-a-function/Erlang/roots-of-a-function.erl new file mode 100644 index 0000000000..f56513d267 --- /dev/null +++ b/Task/Roots-of-a-function/Erlang/roots-of-a-function.erl @@ -0,0 +1,28 @@ +% Implemented by Arjun Sunel +-module(roots). +-export([main/0]). +main() -> + F = fun(X)->X*X*X - 3*X*X + 2*X end, + Step = 0.001, % Using smaller steps will provide more accurate results + Start = -1, + Stop = 3, + Sign = F(Start) > 0, + X = Start, + while(X, Step, Start, Stop, Sign,F). + +while(X, Step, Start, Stop, Sign,F) -> + Value = F(X), + if + Value == 0 -> % We hit a root + io:format("Root found at ~p~n",[X]), + while(X+Step, Step, Start, Stop, Value > 0,F); + + (Value < 0) == Sign -> % We passed a root + io:format("Root found near ~p~n",[X]), + while(X+Step , Step, Start, Stop, Value > 0,F); + + X > Stop -> + io:format("") ; + true -> + while(X+Step, Step, Start, Stop, Value > 0,F) + end. diff --git a/Task/Roots-of-a-function/Racket/roots-of-a-function-1.rkt b/Task/Roots-of-a-function/Racket/roots-of-a-function-1.rkt new file mode 100644 index 0000000000..f644999174 --- /dev/null +++ b/Task/Roots-of-a-function/Racket/roots-of-a-function-1.rkt @@ -0,0 +1,39 @@ +#lang racket + +;; Attempts to find all roots of a real-valued function f +;; in a given interval [a b] by dividing the interval into N parts +;; and using the root-finding method on each subinterval +;; which proves to contain a root. +(define (find-roots f a b + #:divisions [N 10] + #:method [method secant]) + (define h (/ (- b a) N)) + (for*/list ([x1 (in-range a b h)] + [x2 (in-value (+ x1 h))] + #:when (or (root? f x1) + (includes-root? f x1 x2))) + (find-root f x1 x2 #:method method))) + +;; Finds a root of a real-valued function f +;; in a given interval [a b]. +(define (find-root f a b #:method [method secant]) + (cond + [(root? f a) a] + [(root? f b) b] + [else (and (includes-root? f a b) (method f a b))])) + +;; Returns #t if x is a root of a real-valued function f +;; with absolute accuracy (tolerance). +(define (root? f x) (almost-equal? 0 (f x))) + +;; Returns #t if interval (a b) contains a root +;; (or the odd number of roots) of a real-valued function f. +(define (includes-root? f a b) (< (* (f a) (f b)) 0)) + +;; Returns #t if a and b are equal with respect to +;; the relative accuracy (tolerance). +(define (almost-equal? a b) + (or (< (abs (+ b a)) (tolerance)) + (< (abs (/ (- b a) (+ b a))) (tolerance)))) + +(define tolerance (make-parameter 5e-16)) diff --git a/Task/Roots-of-a-function/Racket/roots-of-a-function-2.rkt b/Task/Roots-of-a-function/Racket/roots-of-a-function-2.rkt new file mode 100644 index 0000000000..b556853738 --- /dev/null +++ b/Task/Roots-of-a-function/Racket/roots-of-a-function-2.rkt @@ -0,0 +1,17 @@ +(define (secant f a b) + (let next ([x1 a] [y1 (f a)] [x2 b] [y2 (f b)] [n 50]) + (define x3 (/ (- (* x1 y2) (* x2 y1)) (- y2 y1))) + (cond + ; if the method din't converge within given interval + ; switch to more robust bisection method + [(or (not (< a x3 b)) (zero? n)) (bisection f a b)] + [(almost-equal? x3 x2) x3] + [else (next x2 y2 x3 (f x3) (sub1 n))]))) + +(define (bisection f x1 x2) + (let divide ([a x1] [b x2]) + (and (<= (* (f a) (f b)) 0) + (let ([c (* 0.5 (+ a b))]) + (if (almost-equal? a b) + c + (or (divide a c) (divide c b))))))) diff --git a/Task/Roots-of-a-function/Racket/roots-of-a-function-3.rkt b/Task/Roots-of-a-function/Racket/roots-of-a-function-3.rkt new file mode 100644 index 0000000000..c20612a6c7 --- /dev/null +++ b/Task/Roots-of-a-function/Racket/roots-of-a-function-3.rkt @@ -0,0 +1,8 @@ +-> (find-root (λ (x) (- 2. (* x x))) 1 2) +1.414213562373095 +-> (sqrt 2) +1.4142135623730951 + +-> (define (f x) (+ (* x x x) (* -3.0 x x) (* 2.0 x))) +-> (find-roots f -3 4 #:divisions 50) +'(2.4932181969624796e-33 1.0 2.0) diff --git a/Task/Roots-of-a-function/Racket/roots-of-a-function-4.rkt b/Task/Roots-of-a-function/Racket/roots-of-a-function-4.rkt new file mode 100644 index 0000000000..b178f8189e --- /dev/null +++ b/Task/Roots-of-a-function/Racket/roots-of-a-function-4.rkt @@ -0,0 +1,7 @@ +(define (memoized f) + (define tbl (make-hash)) + (λ x + (cond [(hash-ref tbl x #f) => values] + [else (define res (apply f x)) + (hash-set! tbl x res) + res]))) diff --git a/Task/Roots-of-a-function/Racket/roots-of-a-function-5.rkt b/Task/Roots-of-a-function/Racket/roots-of-a-function-5.rkt new file mode 100644 index 0000000000..9af93b3a7f --- /dev/null +++ b/Task/Roots-of-a-function/Racket/roots-of-a-function-5.rkt @@ -0,0 +1,2 @@ +-> (find-roots (memoized f) -3 4 #:divisions 50) +'(2.4932181969624796e-33 1.0 2.0) diff --git a/Task/Roots-of-a-quadratic-function/Racket/roots-of-a-quadratic-function.rkt b/Task/Roots-of-a-quadratic-function/Racket/roots-of-a-quadratic-function.rkt new file mode 100644 index 0000000000..ec0f6fa69a --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Racket/roots-of-a-quadratic-function.rkt @@ -0,0 +1,13 @@ +#lang racket +(define (quadratic a b c) + (let* ((-b (- b)) + (delta (- (expt b 2) (* 4 a c))) + (denominator (* 2 a))) + (list + (/ (+ -b (sqrt delta)) denominator) + (/ (- -b (sqrt delta)) denominator)))) + +;(quadratic 1 0.0000000000001 -1) +;'(0.99999999999995 -1.00000000000005) +;(quadratic 1 0.0000000000001 1) +;'(-5e-014+1.0i -5e-014-1.0i) diff --git a/Task/Rosetta-Code-Count-examples/00DESCRIPTION b/Task/Rosetta-Code-Count-examples/00DESCRIPTION index 12fae61891..bbd4ccfa1f 100644 --- a/Task/Rosetta-Code-Count-examples/00DESCRIPTION +++ b/Task/Rosetta-Code-Count-examples/00DESCRIPTION @@ -9,3 +9,5 @@ Output: Abstract type: 10 examples. Total: X examples. + +You'll need to use the Media Wiki API, which you can find out about locally, [http://rosettacode.org/mw/api.php here], or in Media Wiki's API documentation at, [http://www.mediawiki.org/wiki/API_Query API:Query] diff --git a/Task/Rosetta-Code-Count-examples/Racket/rosetta-code-count-examples.rkt b/Task/Rosetta-Code-Count-examples/Racket/rosetta-code-count-examples.rkt new file mode 100644 index 0000000000..cf888a2d43 --- /dev/null +++ b/Task/Rosetta-Code-Count-examples/Racket/rosetta-code-count-examples.rkt @@ -0,0 +1,25 @@ +#lang racket + +(require net/url net/uri-codec json (only-in racket/dict [dict-ref ref])) + +(define (RC-get verb params) + ((compose1 get-pure-port string->url format) + "http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params))) + +(define (get-category catname) + (let loop ([c #f]) + (define t + ((compose1 read-json RC-get) 'api + `([action . "query"] [format . "json"] + [list . "categorymembers"] [cmtitle . ,(format "Category:~a" catname)] + [cmcontinue . ,(and c (ref c 'cmcontinue))] [cmlimit . "500"]))) + (define (c-m key) (ref (ref t key '()) 'categorymembers #f)) + (append (for/list ([page (c-m 'query)]) (ref page 'title)) + (cond [(c-m 'query-continue) => loop] [else '()])))) + +(printf "Total: ~a\n" + (for/sum ([task (get-category 'Programming_Tasks)]) + (define s ((compose1 length regexp-match-positions*) + #rx"=={{" (RC-get 'index `([action . "raw"] [title . ,task])))) + (printf "~a: ~a\n" task s) + s)) diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6/rosetta-code-find-unimplemented-tasks.pl6 b/Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6/rosetta-code-find-unimplemented-tasks.pl6 new file mode 100644 index 0000000000..ba4bcf7704 --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Perl-6/rosetta-code-find-unimplemented-tasks.pl6 @@ -0,0 +1,39 @@ +use JSON::Tiny; +sub MAIN ( Str $language = 'Perl_6' ) { + my @done_tasks = set tasks($language); + my @all_tasks = set tasks('Programming_Tasks'); + .say for @all_tasks (-) @done_tasks; +} + +sub url_of ( Str $category, Str $continue? ) { + my $cat = $category.subst( /<-[ A..Z a..z 0..9 . ~ _ - ]>/, + *.ord.fmt('%%%02X'), :g ); + + return 'http://rosettacode.org/mw/api.php?action=query&cmlimit=500' + ~ "&format=json&list=categorymembers&cmtitle=Category:$cat" + ~ ("&cmcontinue=$continue" if $continue); +} + +sub get_mirrored_page ( Str $url, Str $filename ) { + if $filename.IO !~~ :e or (now - $filename.IO.modified) > 3600 { + run('curl', '-sSo', $filename, $url) or die; + } + return slurp $filename; +} + +sub tasks ( Str $category ) { + my $continue = ''; + my @tasks = gather for 1..* -> $page_num { + my $href = from-json get_mirrored_page( + url_of( $category, $continue ), + "{$category}_{$page_num}.json", + ); + + take map *., $href.<query>.<categorymembers>.list; + + $continue = $href.<query-continue>.<categorymembers>.<cmcontinue> + or last; + } or die "Nothing found for category '$category'"; + + return @tasks; +} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Racket/rosetta-code-find-unimplemented-tasks.rkt b/Task/Rosetta-Code-Find-unimplemented-tasks/Racket/rosetta-code-find-unimplemented-tasks.rkt new file mode 100644 index 0000000000..1cdbfabc4c --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Racket/rosetta-code-find-unimplemented-tasks.rkt @@ -0,0 +1,27 @@ +#lang racket + +(require net/url net/uri-codec json (only-in racket/dict [dict-ref ref])) + +(define (RC-get verb params) + ((compose1 get-pure-port string->url format) + "http://rosettacode.org/mw/~a.php?~a" verb (alist->form-urlencoded params))) + +(define (get-category catname) + (let loop ([c #f]) + (define t + ((compose1 read-json RC-get) 'api + `([action . "query"] [format . "json"] + [list . "categorymembers"] [cmtitle . ,(format "Category:~a" catname)] + [cmcontinue . ,(and c (ref c 'cmcontinue))] [cmlimit . "500"]))) + (define (c-m key) (ref (ref t key '()) 'categorymembers #f)) + (append (for/list ([page (c-m 'query)]) (ref page 'title)) + (cond [(c-m 'query-continue) => loop] [else '()])))) + +;; The above is the required "library" code, same as the "Rosetta +;; Code/Count" entry + +(define (show-unimplemented lang) + (for-each displayln (remove* (get-category lang) + (get-category 'Programming_Tasks)))) + +(show-unimplemented 'Racket) ; see all of the Racket entries diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d new file mode 100644 index 0000000000..32127e6c94 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d @@ -0,0 +1,41 @@ +import std.stdio, std.regex; +import std.string: replace, split, format; + +immutable langs = "_div abap actionscript actionscript3 ada apache +applescript apt_sources asm asp autoit avisynth bash basic4gl bf +blitzbasic bnf boo c c_mac caddcl cadlisp cfdg cfm cil cobol cpp +cpp-qt csharp css d delphi diff dos dot eiffel email fortran +freebasic genero gettext glsl gml gnuplot groovy haskell hq9plus +html4strict idl ini inno intercal io java java5 javascript kixtart +klonec klonecpp latex lisp lolcode lotusformulas lotusscript +lscript lua m68k make matlab mirc modula3 mpasm mxml mysql nsis +objc ocaml ocaml-brief oobas oracle11 oracle8 pascal per perl php +php-brief pic16 pixelbender plsql povray powershell progress +prolog providex python qbasic rails reg robots ruby sas scala +scheme scilab sdlbasic smalltalk smarty sql tcl teraterm text +thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro +visualprolog whitespace winbatch xml xorg_conf xpp z80".split; + +string fixTags(string text) { + static immutable slang = "/lang"; + static immutable code = "code"; + + foreach (immutable lang; langs) { + text = text.replace("<%s>".format(lang), + "<lang %s>".format(lang)); + text = text.replace("</%s>".format(lang), + "<%s>".format(slang)); + } + + return text.replace("<%s (.+?)>(.*?)</%s>" + .format(code, code).regex("g"), + "<lang $1>$2<%s>".format(slang)); +} + +void main() { + ("lorem ipsum <c>some c code</c>dolor sit amet, <csharp>some " ~ + "csharp code</csharp> consectetur adipisicing elit, <code r>" ~ + " some r code </code>sed do eiusmod tempor incididunt") + .fixTags + .writeln; +} diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-2.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-2.d new file mode 100644 index 0000000000..91f9ad9045 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-2.d @@ -0,0 +1 @@ +some c code diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-3.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-3.d new file mode 100644 index 0000000000..cde535ef43 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-3.d @@ -0,0 +1 @@ +some csharp code diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-4.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-4.d new file mode 100644 index 0000000000..eaddfd85bb --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-4.d @@ -0,0 +1 @@ + some r code diff --git a/Task/Rosetta-Code-Fix-code-tags/Perl-6/rosetta-code-fix-code-tags.pl6 b/Task/Rosetta-Code-Fix-code-tags/Perl-6/rosetta-code-fix-code-tags.pl6 new file mode 100644 index 0000000000..c469d853fd --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Perl-6/rosetta-code-fix-code-tags.pl6 @@ -0,0 +1,26 @@ +my @langs = < + abap actionscript actionscript3 ada apache applescript apt_sources + asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c caddcl + cadlisp cfdg cfm cil c_mac cobol cpp cpp-qt csharp css d delphi + diff _div dos dot eiffel email fortran freebasic genero gettext + glsl gml gnuplot groovy haskell hq9plus html4strict idl ini inno + intercal io java java5 javascript kixtart klonec klonecpp latex lisp + lolcode lotusformulas lotusscript lscript lua m68k make matlab mirc + modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11 + oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray + powershell progress prolog providex python qbasic rails reg robots + ruby sas scala scheme scilab sdlbasic smalltalk smarty sql tcl teraterm + text thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro + visualprolog whitespace winbatch xml xorg_conf xpp z80 +>; + +$_ = slurp; + +for @langs -> $l { + s:g [ '<' $l '>' ] = "<lang $l>"; + s:g [ '</' $l '>' ] = '</' ~ 'lang>'; +} + +s:g [ '<code '(.+?) '>' (.*?) '</code>' ] = "<lang $0>{$1}</"~"lang>"; + +.say; diff --git a/Task/Rosetta-Code-Fix-code-tags/Racket/rosetta-code-fix-code-tags.rkt b/Task/Rosetta-Code-Fix-code-tags/Racket/rosetta-code-fix-code-tags.rkt new file mode 100644 index 0000000000..1f24c83270 --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/Racket/rosetta-code-fix-code-tags.rkt @@ -0,0 +1,20 @@ +#lang racket + +(define lang-names '("X" "Y" "Z")) + +(define rx + (regexp (string-join lang-names "|" + #:before-first "<((/?(?:code)?)(?:( )?(" + #:after-last "))?)>"))) + +(let loop () ; does all in a single scan + (define m (regexp-match rx (current-input-port) 0 #f (current-output-port))) + (when m + (define-values [all pfx space lang] (apply values (cdr m))) + (printf "<~a>" + (cond [(not lang) (if (equal? pfx #"/code") #"/lang" all)] + [space (if (equal? pfx #"code") (bytes-append #"lang " lang) all)] + [(equal? pfx #"") (bytes-append #"lang " lang)] + [(equal? pfx #"/") #"/lang"] + [else all])) + (loop))) diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION index 2068c99cb1..b80cb86d8b 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION @@ -1,50 +1,50 @@ Sort most popular programming languages based in number of members in Rosetta Code categories <br>(from http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000) -Sample output on March 27 2013: +Sample output on April 11 2013: -<pre> 1. 717 - Tcl - 2. 663 - Python - 3. 643 - C +<pre> 1. 725 - Tcl + 2. 668 - Python + 3. 650 - C 4. 626 - PicoLisp - 5. 622 - J - 6. 587 - Go - 7. 587 - Ruby - 8. 585 - D - 9. 568 - Perl 6 - 10. 564 - Ada - 11. 554 - Mathematica - 12. 535 - Perl - 13. 532 - Haskell + 5. 624 - J + 6. 593 - D + 7. 590 - Ruby + 8. 588 - Go + 9. 576 - Perl 6 + 10. 565 - Ada + 11. 555 - Mathematica + 12. 539 - Perl + 13. 536 - Haskell 14. 514 - BBC BASIC - 15. 505 - REXX - 16. 491 - Java - 17. 478 - OCaml + 15. 511 - REXX + 16. 493 - Java + 17. 481 - OCaml 18. 469 - PureBasic 19. 462 - Unicon 20. 430 - AutoHotkey 21. 429 - Icon 22. 425 - Common Lisp 23. 420 - C sharp - 24. 401 - C++ - 25. 366 - JavaScript - 26. 343 - Clojure - 27. 342 - Scala - 28. 341 - PARI/GP - 29. 326 - R - 30. 324 - Lua - 31. 316 - PHP - 32. 314 - ALGOL 68 - 33. 312 - Forth - 34. 305 - Pascal - 35. 296 - Groovy - 36. 294 - XPL0 - 37. 292 - Liberty BASIC - 38. 288 - Fortran - 39. 277 - Oz - 40. 275 - PL/I + 24. 404 - C++ + 25. 367 - JavaScript + 26. 346 - Clojure + 27. 343 - Scala + 28. 326 - R + 29. 324 - Lua + 30. 317 - PHP + 31. 315 - ALGOL 68 + 32. 313 - Forth + 33. 306 - Pascal + 34. 300 - Groovy + 35. 295 - XPL0 + 36. 292 - Liberty BASIC + 37. 288 - Fortran + 38. 278 - Oz + 39. 272 - E + 40. 270 - Seed7 ...</pre> -A complete ranked listing of all '''481''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. +A complete ranked listing of all '''488''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. Filtering wrong results is optional. You can check against [[Special:MostLinkedCategories]] diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript/rosetta-code-rank-languages-by-popularity.cos b/Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript/rosetta-code-rank-languages-by-popularity.cos index 5065b666e9..5259479c61 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript/rosetta-code-rank-languages-by-popularity.cos +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Cache-ObjectScript/rosetta-code-rank-languages-by-popularity.cos @@ -1,6 +1,4 @@ -Include %occSAX - -Class Utils.Net.RosettaCode Extends %ArrayOfDataTypes +Class Utils.Net.RosettaCode [ Abstract ] { ClassMethod GetTopLanguages(pHost As %String = "", pPath As %String = "", pTop As %Integer = 10) As %Status @@ -28,16 +26,43 @@ ClassMethod GetTopLanguages(pHost As %String = "", pPath As %String = "", pTop A While 'xhtml.AtEnd { Set line=xhtml.ReadLine() If line["!DOCTYPE" Continue + If line["<g:plusone></g:plusone>" { + Continue + Set line="<g:plusone xmlns:g='http://base.google.com/ns/1.0'></g:plusone>" + } Set sc=xml.WriteLine(line) } - // now parse xml stream - Set sc=##class(%XML.TextReader).ParseStream(xml, .hdlr,, $$$SAXDEFAULTS-$$$SAXNAMESPACES) + // create an instance of an %XML.XPATH.Document + Set sc=##class(%XML.XPATH.Document).CreateFromStream(xml, .xdoc) If $$$ISERR(sc) Quit sc + + // evaluate following 'XPath' expression + Set sc=xdoc.EvaluateExpression("//div[@id='bodyContent']//li", "a[contains(@href, '/Category:')]/ancestor::li", .res) - // get languages - Set array=..%New() - Set sc=array.GetLanguages(hdlr) + // iterate through list elements + Set array=##class(%ArrayOfDataTypes).%New() + Do { + Set dom=res.GetNext(.key) + If '$IsObject(dom) Quit + + // get language name and members + Set lang="" + While dom.Read() { + If 'dom.HasValue Continue + If lang="" { + If $Locate(dom.Value, "User|Tasks|Omit|attention|operations|Solutions by") Quit + Set lang=dom.Value Continue + } + If dom.Value["members" { + Set members=+$ZStrip(dom.Value, "<>P") + Set list=array.GetAt(members) + Set $List(list, $ListLength(list)+1)=lang + Set sc=array.SetAt(list, members) + Quit + } + } + } While key'="" If array.Count()=0 Quit $$$ERROR($$$GeneralError, "No languages found.") // show top entries @@ -52,57 +77,4 @@ ClassMethod GetTopLanguages(pHost As %String = "", pPath As %String = "", pTop A Quit $$$OK } -Method GetLanguages(pHandler As %XML.SAX.ContentHandler, pDepth As %Integer) As %Status [ Internal, Private ] -{ - // iterate through xml document, node by node - While pHandler.Read() { - - If '$Data(pDepth) { - - // find 'bodyContent' div element - If pHandler.AttributeCount, pHandler.MoveToAttributeName("id") { - If pHandler.Value="bodyContent" { - Set sc=..GetLanguages(pHandler, pHandler.Depth) - Quit - } - } - - } Else { - - // all done - If pDepth>pHandler.Depth Quit - - // get language name - If $Locate(pHandler.Path, "(/div/ul/li/a)$") { - If pHandler.AttributeCount, pHandler.MoveToAttributeName("href") { - If $Locate(pHandler.Value, "/Category:") { - Set sc=pHandler.MoveToContent() - Set lang=pHandler.Value - If $Locate(lang, "User|Tasks|Omit|attention|operations|Solutions by") Set lang="" - } - } - } - - // get members - If $Locate(pHandler.Path, "(/div/ul/li)$") { - If pHandler.HasValue, $Get(lang)'="" { - Set pos=$Locate(pHandler.Value, "(\d+) member") - If pos { - Set members=+$Extract(pHandler.Value, pos, *) - Set list=..GetAt(members) - Set $List(list, $ListLength(list)+1)=lang - Set sc=..SetAt(list, members) - Set lang="" - } - } - } - - } - - } - - // finished - Quit $$$OK -} - } diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Erlang/rosetta-code-rank-languages-by-popularity.erl b/Task/Rosetta-Code-Rank-languages-by-popularity/Erlang/rosetta-code-rank-languages-by-popularity.erl new file mode 100644 index 0000000000..25d240d82c --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Erlang/rosetta-code-rank-languages-by-popularity.erl @@ -0,0 +1,60 @@ +-module( rank_languages_by_popularity ). + +-export( [task/0] ). + +-record( print_fold, {place=0, place_step=1, previous_count=0} ). + +task() -> + ok = find_unimplemented_tasks:init(), + Category_programming_languages = find_unimplemented_tasks:rosetta_code_list_of( "Programming_Languages" ), + Programming_languages = [X || "Category:" ++ X <- Category_programming_languages], + {ok, {{_HTTP,200,"OK"}, _Headers, Body}} = httpc:request( "http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" ), + Count_categories = lists:sort( [{Y, X} || {X, Y} <- category_counts(Body, []), lists:member(X, Programming_languages)] ), + lists:foldr( fun place_count_category_write/2, #print_fold{}, Count_categories ). + + + +category_counts( "", [[] | Acc] ) -> Acc; +category_counts( String, Acc ) -> + {Begin, End} = category_count_begin_end( String ), + {Category_count, String_continuation} = category_count_extract( String, Begin, End ), + category_counts( String_continuation, [Category_count | Acc] ). + +category_count_begin_end( String ) -> + Begin = string:str( String, "/wiki/Category:" ), + End = string:str( string:substr(String, Begin), " member" ), + category_count_begin_end( Begin, End, erlang:length(" member") ). + +category_count_begin_end( _Begin, 0, _End_length ) -> {0, 0}; +category_count_begin_end( Begin, End, End_length ) -> + {Begin, Begin + End + End_length}. + +category_count_extract( _String, 0, _End ) -> {[], ""}; +category_count_extract( String, Begin, End ) -> + Category_count = category_count_extract( string:substr(String, Begin, End - Begin) ), + {Category_count, string:substr( String, End + 1 )}. + +category_count_extract( "/wiki/Category:" ++ T ) -> + Category_member = string:tokens( T, " " ), + Category = category_count_extract_category( Category_member ), + Member = category_count_extract_count( lists:reverse(Category_member) ), + {Category, Member}. + +category_count_extract_category( [Category | _T] ) -> + lists:map( fun category_count_extract_category_map/1, string:strip(Category, right, $") ). + +category_count_extract_category_map( $_ ) -> $\s; +category_count_extract_category_map( Character ) -> Character. + +category_count_extract_count( ["member" ++ _, "(" ++ N | _T] ) -> erlang:list_to_integer( N ); +category_count_extract_count( _T ) -> 0. + +place_count_category_write( {Count, Category}, Acc ) -> + Print_fold = place_count_category_write( Count, Acc ), + io:fwrite("~p. ~p - ~p~n", [Print_fold#print_fold.place, Count, Category] ), + Print_fold; + +place_count_category_write( Count, #print_fold{place_step=Place_step, previous_count=Count}=Print_fold ) -> + Print_fold#print_fold{place_step=Place_step + 1}; +place_count_category_write( Count, #print_fold{place=Place, place_step=Place_step} ) -> + #print_fold{place=Place + Place_step, previous_count=Count}. diff --git a/Task/Rot-13/FBSL/rot-13.fbsl b/Task/Rot-13/FBSL/rot-13.fbsl new file mode 100644 index 0000000000..c172ae7bb0 --- /dev/null +++ b/Task/Rot-13/FBSL/rot-13.fbsl @@ -0,0 +1,80 @@ +#APPTYPE CONSOLE + +REM Create a CircularQueue object +REM CQ.Store item +REM CQ.Find items +REM CQ.Forward nItems +REM CQ.Recall + +REM SO CQ init WITH "A"... "Z" +REM CQ.Find "B" +REM QC.Forward 13 +REM QC.Recall + +CLASS CircularQueue + items[] + head + tail + here + + SUB INITIALIZE(dArray) + head = 0 + tail = 0 + here = 0 + FOR DIM i = LBOUND(dArray) TO UBOUND(dArray) + items[tail] = dArray[i] + tail = tail + 1 + NEXT + END SUB + + SUB TERMINATE() + REM + END SUB + + METHOD Put(s AS STRING) + items[tail] = s + tail = tail + 1 + END METHOD + + METHOD Find(s AS STRING) + FOR DIM i = head TO tail - 1 + IF items[i] = s THEN + here = i + RETURN TRUE + END IF + NEXT + RETURN FALSE + END METHOD + + METHOD Move(n AS INTEGER) + DIM bound AS INTEGER = UBOUND(items) + 1 + here = (here + n) MOD bound + END METHOD + + METHOD Recall() + RETURN items[here] + END METHOD + + PROPERTY Size() + RETURN COUNT(items) + END PROPERTY +END CLASS + +DIM CQ AS NEW CircularQueue({"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"}) + +DIM c AS STRING +DIM isUppercase AS INTEGER +DIM s AS STRING = "nowhere ABJURER" + +FOR DIM i = 1 TO LEN(s) + c = MID(s, i, 1) + isUppercase = lstrcmp(LCASE(c), c) + IF CQ.Find(UCASE(c)) THEN + CQ.Move(13) + PRINT IIF(isUppercase, UCASE(CQ.Recall()), LCASE(CQ.Recall())) ; + ELSE + PRINT c; + END IF +NEXT + +PAUSE diff --git a/Task/Rot-13/Racket/rot-13.rkt b/Task/Rot-13/Racket/rot-13.rkt index 24d815d621..a68ff72aa1 100644 --- a/Task/Rot-13/Racket/rot-13.rkt +++ b/Task/Rot-13/Racket/rot-13.rkt @@ -14,4 +14,4 @@ (for ([f (if (null? files) '("-") files)]) (if (equal? f "-") (run (current-input-port) (current-output-port)) - (call-with-input-file f ( (i) (run i (current-output-port))))))) + (call-with-input-file f (λ(i) (run i (current-output-port))))))) diff --git a/Task/Rot-13/Raven/rot-13.raven b/Task/Rot-13/Raven/rot-13.raven new file mode 100644 index 0000000000..1d78179b07 --- /dev/null +++ b/Task/Rot-13/Raven/rot-13.raven @@ -0,0 +1,13 @@ +define rot13 use $str + $str each chr + dup m/[A-Ma-m]/ if + ord 13 + chr + else + dup m/[N-Zn-z]/ if + ord 13 - chr + $str length list "" join + +"12!ABJURER nowhere" +dup print "\nas rot13 is\n" print +rot13 +print "\n" print diff --git a/Task/Rot-13/SQL/rot-13.sql b/Task/Rot-13/SQL/rot-13.sql new file mode 100644 index 0000000000..3cb9e62490 --- /dev/null +++ b/Task/Rot-13/SQL/rot-13.sql @@ -0,0 +1,25 @@ +with cte(num) as +( + select 1 + union all + select num+1 + from cte +) +select cast(( +select char(ascii(chr) + + case + when ascii(chr) between ascii('a') and ascii('m') or + ascii(chr) between ascii('A') and ascii('M') then 13 + when ascii(chr) between ascii('n') and ascii('z') or + ascii(chr) between ascii('N') and ascii('Z') then -13 + else 0 + end) +from +( +select top(1000) num, + -- your string to be converted to ROT13 + substring('The Quick Brown Fox Jumps Over The Lazy Dog',num,1) chr +from cte +) tmp +For XML PATH ('')) as xml).value('.', 'VARCHAR(max)') rot13 +option (maxrecursion 0) diff --git a/Task/Run-length-encoding/J/run-length-encoding-3.j b/Task/Run-length-encoding/J/run-length-encoding-3.j new file mode 100644 index 0000000000..ee2a574682 --- /dev/null +++ b/Task/Run-length-encoding/J/run-length-encoding-3.j @@ -0,0 +1 @@ +rle=: ;@(<@(":@#,{.);.1~ 2 ~:/\ (a.{.@-.{.),]) diff --git a/Task/Run-length-encoding/Racket/run-length-encoding.rkt b/Task/Run-length-encoding/Racket/run-length-encoding.rkt new file mode 100644 index 0000000000..0be012d599 --- /dev/null +++ b/Task/Run-length-encoding/Racket/run-length-encoding.rkt @@ -0,0 +1,5 @@ +#lang racket +(define (encode str) + (regexp-replace* #px"(.)\\1*" str (λ (m c) (~a (string-length m) c)))) +(define (decode str) + (regexp-replace* #px"([0-9]+)(.)" str (λ (m n c) (make-string (string->number n) (string-ref c 0))))) diff --git a/Task/Run-length-encoding/SQL/run-length-encoding-1.sql b/Task/Run-length-encoding/SQL/run-length-encoding-1.sql new file mode 100644 index 0000000000..e3cbc74176 --- /dev/null +++ b/Task/Run-length-encoding/SQL/run-length-encoding-1.sql @@ -0,0 +1,47 @@ +-- variable table +drop table if exists var; +create temp table var ( value varchar(1000) ); +insert into var(value) select 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'; + +-- select +with recursive +ints(num) as +( + select 1 + union all + select num+1 + from ints + where num+1 <= length((select value from var)) +) +, +chars(num,chr,nextChr,isGroupEnd) as +( + select tmp.*, case when tmp.nextChr <> tmp.chr then 1 else 0 end groupEnds + from ( + select num, + substring((select value from var), num, 1) chr, + (select substring((select value from var), num+1, 1)) nextChr + from ints + ) tmp +) +select (select value from var) plain_text, ( + select string_agg(concat(cast(maxNoWithinGroup as varchar(10)) , chr), '' order by num) + from ( + select *, max(noWithinGroup) over (partition by chr, groupNo) maxNoWithinGroup + from ( + select num, + chr, + groupNo, + row_number() over( partition by chr, groupNo order by num) noWithinGroup + from ( + select *, (select count(*) + from chars chars2 + where chars2.isGroupEnd = 1 and + chars2.chr = chars.chr and + chars2.num < chars.num) groupNo + from chars + ) tmp + ) sub + ) final + where noWithinGroup = 1 + ) Rle_Compressed diff --git a/Task/Run-length-encoding/SQL/run-length-encoding-2.sql b/Task/Run-length-encoding/SQL/run-length-encoding-2.sql new file mode 100644 index 0000000000..461a44b5f4 --- /dev/null +++ b/Task/Run-length-encoding/SQL/run-length-encoding-2.sql @@ -0,0 +1,62 @@ +-- variable table +DROP TABLE IF EXISTS var; +CREATE temp TABLE var ( VALUE VARCHAR(1000) ); +INSERT INTO var(VALUE) SELECT '1A2B3C4D5E6F'; + +-- select +WITH recursive +ints(num) AS +( + SELECT 1 + UNION ALL + SELECT num+1 + FROM ints + WHERE num+1 <= LENGTH((SELECT VALUE FROM var)) +) +, +chars(num,chr,nextChr) AS +( + SELECT tmp.* + FROM ( + SELECT num, + SUBSTRING((SELECT VALUE FROM var), num, 1) chr, + (SELECT SUBSTRING((SELECT VALUE FROM var), num+1, 1)) nextChr + FROM ints + ) tmp +) +, +charsWithGroup(num,chr,nextChr,group_no) AS +( + SELECT *,(SELECT COUNT(*) + FROM chars chars2 + WHERE chars2.chr !~ '[0-9]' AND + chars2.num < chars.num) group_No + FROM chars +) +, +charsWithGroupAndLetter(num,chr,nextChr,group_no,group_letter) AS +( + SELECT *,(SELECT chr + FROM charsWithGroup g2 + where g2.group_no = charsWithGroup.group_no + ORDER BY num DESC + LIMIT 1) + FROM charsWithGroup +) +, +lettersWithCount(group_no,amount,group_letter) AS +( + SELECT group_no, string_agg(chr, '' ORDER BY num), group_letter + FROM charsWithGroupAndLetter + WHERE chr ~ '[0-9]' + GROUP BY group_no, group_letter +) +, +lettersReplicated(group_no,amount,group_letter, replicated_Letter) AS +( + SELECT *, rpad(group_letter, cast(amount as int), group_letter) + FROM lettersWithCount +) +select (SELECT value FROM var) rle_encoded, + string_agg(replicated_Letter, '' ORDER BY group_no) decoded_string +FROM lettersReplicated diff --git a/Task/Runtime-evaluation-In-an-environment/Erlang/runtime-evaluation-in-an-environment.erl b/Task/Runtime-evaluation-In-an-environment/Erlang/runtime-evaluation-in-an-environment.erl new file mode 100644 index 0000000000..7c08b79657 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Erlang/runtime-evaluation-in-an-environment.erl @@ -0,0 +1,23 @@ +-module( runtime_evaluation ). + +-export( [task/0] ). + +task() -> + Form = form_from_string( "X." ), + Variable1 = evaluate_form( Form, {'X', 1} ), + io:fwrite( "~p~n", [Variable1] ), + Variable2 = evaluate_form( Form, {'X', 2} ), + io:fwrite( "~p~n", [Variable2] ), + io:fwrite( "~p~n", [Variable2 - Variable1] ). + + + +evaluate_form( Form, {Variable_name, Value} ) -> + Bindings = erl_eval:add_binding( Variable_name, Value, erl_eval:new_bindings() ), + {value, Evaluation, _} = erl_eval:expr( Form, Bindings ), + Evaluation. + +form_from_string( String ) -> + {ok, Tokens, _} = erl_scan:string( String ), + {ok, [Form]} = erl_parse:parse_exprs( Tokens ), + Form. diff --git a/Task/Runtime-evaluation-In-an-environment/Perl-6/runtime-evaluation-in-an-environment.pl6 b/Task/Runtime-evaluation-In-an-environment/Perl-6/runtime-evaluation-in-an-environment.pl6 index 9f44e67c9b..9e3141d211 100644 --- a/Task/Runtime-evaluation-In-an-environment/Perl-6/runtime-evaluation-in-an-environment.pl6 +++ b/Task/Runtime-evaluation-In-an-environment/Perl-6/runtime-evaluation-in-an-environment.pl6 @@ -1,9 +1,4 @@ -sub eval_with_x { - my $code = @_.shift; - my $x = @_.shift; - my $first = eval $code; - $x = @_.shift; - return eval($code) - $first; -} +sub eval_with_x($code, *@x) { [R-] @x.map: -> \x { eval $code } } -print eval_with_x('3 * $x', 5, 10), "\n"; # Prints "15". +say eval_with_x('3 * x', 5, 10); # Says "15". +say eval_with_x('3 * x', 5, 10, 50); # Says "135". diff --git a/Task/Runtime-evaluation-In-an-environment/Racket/runtime-evaluation-in-an-environment-1.rkt b/Task/Runtime-evaluation-In-an-environment/Racket/runtime-evaluation-in-an-environment-1.rkt new file mode 100644 index 0000000000..beb421ca71 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Racket/runtime-evaluation-in-an-environment-1.rkt @@ -0,0 +1,5 @@ +#lang racket +(define ns (make-base-namespace)) +(define (eval-with-x code a b) + (define (with v) (eval `(let ([x ',v]) ,code) ns)) + (- (with b) (with a))) diff --git a/Task/Runtime-evaluation-In-an-environment/Racket/runtime-evaluation-in-an-environment-2.rkt b/Task/Runtime-evaluation-In-an-environment/Racket/runtime-evaluation-in-an-environment-2.rkt new file mode 100644 index 0000000000..e14d4e38fd --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Racket/runtime-evaluation-in-an-environment-2.rkt @@ -0,0 +1,7 @@ +#lang racket +(define ns (make-base-namespace)) +(define (eval-with-x code a b) + (define (with v) + (namespace-set-variable-value! 'x v #f ns) + (eval code ns)) + (- (with b) (with a))) diff --git a/Task/Runtime-evaluation/Erlang/runtime-evaluation.erl b/Task/Runtime-evaluation/Erlang/runtime-evaluation.erl index abb178cabd..a2585c8966 100644 --- a/Task/Runtime-evaluation/Erlang/runtime-evaluation.erl +++ b/Task/Runtime-evaluation/Erlang/runtime-evaluation.erl @@ -6,3 +6,5 @@ [{'X',17}] 4> {value, Value, _} = erl_eval:expr(Form, Bindings). {value,57,[{'X',17}]} +5> Value. +57 diff --git a/Task/Runtime-evaluation/Racket/runtime-evaluation.rkt b/Task/Runtime-evaluation/Racket/runtime-evaluation.rkt new file mode 100644 index 0000000000..53f2f65af9 --- /dev/null +++ b/Task/Runtime-evaluation/Racket/runtime-evaluation.rkt @@ -0,0 +1,8 @@ +#lang racket +(require racket/sandbox) +(define e (make-evaluator 'racket)) +(e '(define + *)) +(e '(+ 10 20)) +(+ 10 20) +;; (e '(delete-file "/etc/passwd")) +;; --> delete-file: `delete' access denied for /etc/passwd diff --git a/Task/S-Expressions/Python/s-expressions-1.py b/Task/S-Expressions/Python/s-expressions-1.py index f9a211b384..16532f854a 100644 --- a/Task/S-Expressions/Python/s-expressions-1.py +++ b/Task/S-Expressions/Python/s-expressions-1.py @@ -6,9 +6,9 @@ term_regex = r'''(?mx) \s*(?: (?P<brackl>\()| (?P<brackr>\))| - (?P<num>\d+\.\d+|\d+)\b| + (?P<num>\-?\d+\.\d+|\-?\d+)| (?P<sq>"[^"]*")| - (?P<s>\S+)\b + (?P<s>[^(^)\s]+) )''' def parse_sexp(sexp): diff --git a/Task/SEDOLs/Mercury/sedols.mercury b/Task/SEDOLs/Mercury/sedols.mercury index bdf4efc56b..7a0fe2b487 100644 --- a/Task/SEDOLs/Mercury/sedols.mercury +++ b/Task/SEDOLs/Mercury/sedols.mercury @@ -50,4 +50,4 @@ is_vowel('A'). is_vowel('E'). is_vowel('I'). is_vowel('O'). -is_vowel('O'). +is_vowel('U'). diff --git a/Task/SHA-1/Racket/sha-1-1.rkt b/Task/SHA-1/Racket/sha-1-1.rkt index 136fcc9e50..954e6590b6 100644 --- a/Task/SHA-1/Racket/sha-1-1.rkt +++ b/Task/SHA-1/Racket/sha-1-1.rkt @@ -1,4 +1,3 @@ #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 index 9af9d0a3dd..5fcd819879 100644 --- a/Task/SHA-1/Racket/sha-1-2.rkt +++ b/Task/SHA-1/Racket/sha-1-2.rkt @@ -1,4 +1,3 @@ #lang racket (require openssl/sha1) - (sha1 (open-input-string "Rosetta Code")) diff --git a/Task/SHA-256/00DESCRIPTION b/Task/SHA-256/00DESCRIPTION index c61f7df0f8..4e0bdf6ba6 100644 --- a/Task/SHA-256/00DESCRIPTION +++ b/Task/SHA-256/00DESCRIPTION @@ -1,3 +1,3 @@ -'''SHA-256''' is the recommended stronger alternative to [[SHA-1]]. +'''[[wp:SHA-256|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/Python/sha-256.py b/Task/SHA-256/Python/sha-256.py index 86ae372dea..31b7202e1d 100644 --- a/Task/SHA-256/Python/sha-256.py +++ b/Task/SHA-256/Python/sha-256.py @@ -1,4 +1,4 @@ >>> import hashlib ->>> hashlib.sha256( "Rosetta code" ).hexdigest() +>>> hashlib.sha256( "Rosetta code".encode() ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>> diff --git a/Task/SHA-256/Racket/sha-256.rkt b/Task/SHA-256/Racket/sha-256.rkt new file mode 100644 index 0000000000..4fdb8e57db --- /dev/null +++ b/Task/SHA-256/Racket/sha-256.rkt @@ -0,0 +1,20 @@ +#lang racket/base + +;; define a quick SH256 FFI interface, similar to the Racket's default +;; SHA1 interface +(require ffi/unsafe ffi/unsafe/define openssl/libcrypto + (only-in openssl/sha1 bytes->hex-string)) +(define-ffi-definer defcrypto libcrypto) +(defcrypto SHA256_Init (_fun _pointer -> _int)) +(defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) +(defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) +(define (sha256 bytes) + (define ctx (malloc 128)) + (define result (make-bytes 32)) + (SHA256_Init ctx) + (SHA256_Update ctx bytes (bytes-length bytes)) + (SHA256_Final result ctx) + (bytes->hex-string result)) + +;; use the defined wrapper to solve the task +(displayln (sha256 #"Rosetta code")) diff --git a/Task/Safe-addition/Racket/safe-addition.rkt b/Task/Safe-addition/Racket/safe-addition.rkt new file mode 100644 index 0000000000..406993dbaa --- /dev/null +++ b/Task/Safe-addition/Racket/safe-addition.rkt @@ -0,0 +1,27 @@ +#lang racket + +;; 1. Racket has exact unlimited integers and fractions, which can be +;; used to perform exact operations. For example, given an inexact +;; flonum, we can convert it to an exact fraction and work with that: +(define (exact+ x y) + (+ (inexact->exact x) (inexact->exact y))) +;; (A variant of this would be to keep all numbers exact, so the default +;; operations never get to inexact numbers) + +;; 2. We can implement the required operation using a bunch of +;; functionality provided by the math library, for example, use +;; `flnext' and `flprev' to get the surrounding numbers for both +;; inputs and use them to produce the resulting interval: +(require math) +(define (interval+ x y) + (cons (+ (flprev x) (flprev y)) (+ (flnext x) (flnext y)))) +(interval+ 1.14 2000.0) ; -> '(2001.1399999999999 . 2001.1400000000003) +;; (Note: I'm not a numeric expert in any way, so there must be room for +;; improvement here...) + +;; 3. Yet another option is to use the math library's bigfloats, with an +;; arbitrary precision: +(bf-precision 1024) ; 1024 bit floats +;; add two numbers, specified as strings to avoid rounding of number +;; literals +(bf+ (bf "1.14") (bf "2000.0")) diff --git a/Task/Same-Fringe/Bracmat/same-fringe.bracmat b/Task/Same-Fringe/Bracmat/same-fringe.bracmat new file mode 100644 index 0000000000..f6a91beabf --- /dev/null +++ b/Task/Same-Fringe/Bracmat/same-fringe.bracmat @@ -0,0 +1,38 @@ +( ( T + = + . ( next + = node stack rhs + . !arg:%?node ?stack + & whl + ' ( !node:(?node.?rhs) + & !rhs !stack:?stack + ) + & (!node.!stack) + ) + & !arg:(?stackA,?stackB) + & whl + ' ( !stackA:~ + & !stackB:~ + & next$!stackA:(?leafA.?stackA) + & next$!stackB:(?leafB.?stackB) + & !leafA:!leafB + ) + & out$!arg + & ( !stackA:!stackB: + & !leafA:!leafB + & out$equal + | out$"not equal" + ) + ) +& T$(x,x) +& T$((x.y),(x.y)) +& T$(((x.y).z),(x.y.z)) +& T$((x.y.z),(x.y.q)) +& T$((x.y),(x.y.q)) +& T$((x.y.z),(x.y)) +& T$(((x.y).z),(x.z.y)) +& T + $ ( (a.b.c.(x.y).z) + , (((a.b).c).x.y.z) + ) +); diff --git a/Task/Scope-Function-names-and-labels/Racket/scope-function-names-and-labels-1.rkt b/Task/Scope-Function-names-and-labels/Racket/scope-function-names-and-labels-1.rkt new file mode 100644 index 0000000000..b9a3e2f74b --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Racket/scope-function-names-and-labels-1.rkt @@ -0,0 +1,5 @@ +(define (foo x) + (define (bar y) (+ x y)) + (bar 2)) +(foo 1) ; => 3 +(bar 1) ; => error diff --git a/Task/Scope-Function-names-and-labels/Racket/scope-function-names-and-labels-2.rkt b/Task/Scope-Function-names-and-labels/Racket/scope-function-names-and-labels-2.rkt new file mode 100644 index 0000000000..2d8767142b --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Racket/scope-function-names-and-labels-2.rkt @@ -0,0 +1,5 @@ +(define (foo x) + (define (bar y) (+ x y)) + bar) +(foo 1) ; => #<procedure:bar> +((foo 1) 2) ; => 3 diff --git a/Task/Search-a-list/Aime/search-a-list.aime b/Task/Search-a-list/Aime/search-a-list.aime new file mode 100644 index 0000000000..8b87ac999c --- /dev/null +++ b/Task/Search-a-list/Aime/search-a-list.aime @@ -0,0 +1,69 @@ +integer +search(list l, text s) +{ + integer i; + + i = 0; + while (i < l_length(l)) { + if (!compare(l_q_text(l, i), s)) { + break; + } + i += 1; + } + + if (i == l_length(l)) { + i = -1; + } + + return i; +} + +void +search_for(list l, ...) +{ + integer i; + + i = 1; + while (i < count()) { + integer index; + + index = search(l, $i); + o_text($i); + if (index == -1) { + o_text(" is not in the haystack\n"); + } else { + o_text(" is at "); + o_integer(index); + o_text("\n"); + } + + i += 1; + } +} + +list +new_list(...) +{ + integer i; + list l; + + i = 0; + while (i < count()) { + l_append(l, $i); + i += 1; + } + + return l; +} + +integer +main(void) +{ + list l; + + l = new_list("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", + "Charlie", "Bush", "Boz", "Zag"); + search_for(l, "Bush", "Washington", "Zag"); + + return 0; +} diff --git a/Task/Search-a-list/Bracmat/search-a-list.bracmat b/Task/Search-a-list/Bracmat/search-a-list.bracmat new file mode 100644 index 0000000000..c8e83a8076 --- /dev/null +++ b/Task/Search-a-list/Bracmat/search-a-list.bracmat @@ -0,0 +1,23 @@ +( return the largest index to a needle that has multiple + occurrences in the haystack and print the needle + : ?list +& ( !list:? haystack [?index ? + & out$("The word 'haystack' occurs at 1-based index" !index) + | out$"The word 'haystack' does not occur" + ) +& ( !list + : ? %@?needle ? !needle ? + : ( ? !needle [?index (?&~) + | ? + & out + $ ( str + $ ( "The word '" + !needle + "' occurs more than once. The last 1-based index is " + !index + ) + ) + ) + | out$"No word occurs more than once." + ) +); diff --git a/Task/Self-describing-numbers/C++/self-describing-numbers.cpp b/Task/Self-describing-numbers/C++/self-describing-numbers.cpp new file mode 100644 index 0000000000..8ec259b3c0 --- /dev/null +++ b/Task/Self-describing-numbers/C++/self-describing-numbers.cpp @@ -0,0 +1,74 @@ +#include <iostream> + +//-------------------------------------------------------------------------------------------------- +typedef unsigned long long bigint; + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class sdn +{ +public: + bool check( bigint n ) + { + int cc = digitsCount( n ); + return compare( n, cc ); + } + + void displayAll( bigint s ) + { + for( bigint y = 1; y < s; y++ ) + if( check( y ) ) + cout << y << " is a Self-Describing Number." << endl; + } + +private: + bool compare( bigint n, int cc ) + { + bigint a; + while( cc ) + { + cc--; a = n % 10; + if( dig[cc] != a ) return false; + n -= a; n /= 10; + } + return true; + } + + int digitsCount( bigint n ) + { + int cc = 0; bigint a; + memset( dig, 0, sizeof( dig ) ); + while( n ) + { + a = n % 10; dig[a]++; + cc++ ; n -= a; n /= 10; + } + return cc; + } + + int dig[10]; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + sdn s; + s. displayAll( 1000000000000 ); + cout << endl << endl; system( "pause" ); + + bigint n; + while( true ) + { + system( "cls" ); + cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n; + if( !n ) return 0; + if( s.check( n ) ) cout << n << " is"; + else cout << n << " is NOT"; + cout << " a Self-Describing Number!" << endl << endl; + system( "pause" ); + } + + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Self-describing-numbers/D/self-describing-numbers-1.d b/Task/Self-describing-numbers/D/self-describing-numbers-1.d index 3dfabd2a32..5e65995a79 100644 --- a/Task/Self-describing-numbers/D/self-describing-numbers-1.d +++ b/Task/Self-describing-numbers/D/self-describing-numbers-1.d @@ -1,10 +1,10 @@ import std.stdio, std.algorithm, std.range, std.conv; -bool isSelfDescribing(in long n) { - auto nu = n.text().map!q{a - '0'}(); - return nu.equal( nu.length.iota().map!(a => count(nu, a))() ); +bool isSelfDescribing(in long n) /*pure nothrow*/ { + auto nu = n.text.map!q{a - '0'}; + return nu.length.iota.map!(a => nu.count(a)).equal(nu); } void main() { - writeln(iota(4_000_000).filter!isSelfDescribing()); + 4_000_000.iota.filter!isSelfDescribing.writeln; } diff --git a/Task/Self-describing-numbers/Julia/self-describing-numbers.julia b/Task/Self-describing-numbers/Julia/self-describing-numbers.julia index d14cc1af83..d7a61eb430 100644 --- a/Task/Self-describing-numbers/Julia/self-describing-numbers.julia +++ b/Task/Self-describing-numbers/Julia/self-describing-numbers.julia @@ -1,11 +1,9 @@ -julia> function selfie(x) - y = string(x) - return all([string(i[2]) == string(mapreduce(x->string(x)==string(i[1]-1),+,y)) for i in enumerate(y)]) +function selfie(x) + y = reverse(digits(x)) + len = length(y) + sum(y) != len && return false + for i = 1:len + y[i] != sum(y .== i-1) && return false + end + return true end -# method added to generic function selfie - -julia> selfie(2020) -true - -julia> selfie(2021) -false diff --git a/Task/Self-describing-numbers/Racket/self-describing-numbers.rkt b/Task/Self-describing-numbers/Racket/self-describing-numbers.rkt new file mode 100644 index 0000000000..85403f89b8 --- /dev/null +++ b/Task/Self-describing-numbers/Racket/self-describing-numbers.rkt @@ -0,0 +1,14 @@ +#lang racket +(define (get-digits number (lst null)) + (if (zero? number) + lst + (get-digits (quotient number 10) (cons (remainder number 10) lst)))) + +(define (self-describing? number) + (if (= number 0) #f + (let ((digits (get-digits number))) + (for/fold ((bool #t)) + ((i (in-range (length digits)))) + (and bool + (= (count (lambda (x) (= x i)) digits) + (list-ref digits i))))))) diff --git a/Task/Self-referential-sequence/Aime/self-referential-sequence.aime b/Task/Self-referential-sequence/Aime/self-referential-sequence.aime new file mode 100644 index 0000000000..0597f871b6 --- /dev/null +++ b/Task/Self-referential-sequence/Aime/self-referential-sequence.aime @@ -0,0 +1,100 @@ +text +next(text s, integer show) +{ + integer l; + record v; + data d; + text u; + + l = length(s); + while (l) { + integer e; + + l -= 1; + e = 0; + u = insert("", 0, character(s, l)); + r_g_integer(e, v, u); + r_f_integer(v, u, e + 1); + } + + if (r_last(v, u)) { + do { + b_paste(d, -1, itoa(r_q_integer(v, u))); + b_paste(d, -1, u); + } while (r_less(v, u, u)); + } + + if (show) { + o_text(b_string(d)); + o_newline(); + } + + return b_string(d); +} + +integer +depth(text s, integer i, record r) +{ + integer d; + + d = 0; + r_g_integer(d, r, s); + if (d <= 0) { + i += 1; + if (d) { + d += i; + } else { + d = -i; + } + r_f_integer(r, s, d); + i = depth(next(s, 0), i, r); + d = r_q_integer(r, s); + if (d <= 0) { + d = i + 1; + r_r_integer(r, s, d); + } + } + + return d; +} + +integer +main(void) +{ + integer d, e, i; + record r; + list l; + + d = 0; + i = 1000000; + while (i) { + i -= 1; + e = depth(itoa(i), 0, r); + if (e == d) { + lb_p_integer(l, i); + } elif (d < e) { + d = e; + l_clear(l); + lb_p_integer(l, i); + } + } + + o_text(cat3("longest length is ", itoa(d), "\n")); + while (l_length(l)) { + text s; + + o_newline(); + r_clear(r); + lf_e_integer(i, l); + o_integer(i); + o_newline(); + e = d - 1; + s = itoa(i); + while (e) { + s = next(s, 1); + e -= 1; + } + } + + return 0; +} diff --git a/Task/Self-referential-sequence/Racket/self-referential-sequence.rkt b/Task/Self-referential-sequence/Racket/self-referential-sequence.rkt new file mode 100644 index 0000000000..fb95fe336b --- /dev/null +++ b/Task/Self-referential-sequence/Racket/self-referential-sequence.rkt @@ -0,0 +1,36 @@ +#lang racket + +(define (next s) + (define v (make-vector 10 0)) + (for ([c s]) + (define d (- (char->integer #\9) (char->integer c))) + (vector-set! v d (add1 (vector-ref v d)))) + (string-append* (for/list ([x v] [i (in-range 9 -1 -1)] #:when (> x 0)) + (format "~a~a" x i)))) + +(define (seq-of s) + (reverse (let loop ([ns (list s)]) + (define n (next (car ns))) + (if (member n ns) ns (loop (cons n ns)))))) + +(define (sort-string s) + (list->string (sort (string->list s) char>?))) + +(define-values [len nums seq] + (for/fold ([*len #f] [*nums #f] [*seq #f]) + ([n (in-range 1000000 -1 -1)]) ; start at the high end + (define s (number->string n)) + (define sorted (sort-string s)) + (cond [(equal? s sorted) + (define seq (seq-of s)) + (define len (length seq)) + (cond [(or (not *len) (> len *len)) (values len (list s) seq)] + [(= len *len) (values len (cons s *nums) seq)] + [else (values *len *nums *seq)])] + ;; not sorted: see if it's a permutation of the best + [else (values + *len + (if (and *nums (member sorted *nums)) (cons s *nums) *nums) + *seq)]))) +(printf "Numbers: ~a\nLength: ~a\n" (string-join nums ", ") len) +(for ([n seq]) (printf " ~a\n" n)) diff --git a/Task/Semordnilap/Aime/semordnilap.aime b/Task/Semordnilap/Aime/semordnilap.aime new file mode 100644 index 0000000000..271519b279 --- /dev/null +++ b/Task/Semordnilap/Aime/semordnilap.aime @@ -0,0 +1,58 @@ +text +reverse(text s) +{ + data b; + integer i; + + i = length(s); + while (i) { + i -= 1; + b_insert(b, -1, character(s, i)); + } + + return b_string(b); +} + +integer +main(void) +{ + integer c, p; + record r; + file f; + text s; + + f_affix(f, "unixdict.txt"); + + while (f_line(f, s) != -1) { + r_p_integer(r, s, 0); + } + + c = 0; + p = 0; + + if (r_first(r, s)) { + do { + text t; + + t = reverse(s); + if (compare(s, t) > 0) { + if (r_key(r, t)) { + p += 1; + if (c < 5) { + c += 1; + o_text(s); + o_byte(' '); + o_text(t); + o_byte('\n'); + } + } + } + } while (r_greater(r, s, s)); + } + + o_text("Semordnilap pairs: "); + o_integer(p); + o_text("\n"); + + return 0; +} diff --git a/Task/Semordnilap/Bracmat/semordnilap.bracmat b/Task/Semordnilap/Bracmat/semordnilap.bracmat new file mode 100644 index 0000000000..f4c47dcb3e --- /dev/null +++ b/Task/Semordnilap/Bracmat/semordnilap.bracmat @@ -0,0 +1,24 @@ +( get'("unixdict.txt",STR):?dict +& new$hash:?H +& 0:?p +& ( @( !dict + : ? + ( [!p ?w \n [?p ? + & (H..insert)$(!w.rev$!w) + & ~ + ) + ) + | 0:?N + & (H..forall) + $ ( + = + . !arg:(?a.?b) + & !a:<!b + & (H..find)$!b + & !N+1:?N:<6 + & out$(!a !b) + | + ) + & out$(semordnilap !N dnuoF) + ) +); diff --git a/Task/Semordnilap/C/semordnilap.c b/Task/Semordnilap/C/semordnilap.c index 7d44b3d6d5..3749189594 100644 --- a/Task/Semordnilap/C/semordnilap.c +++ b/Task/Semordnilap/C/semordnilap.c @@ -15,7 +15,7 @@ static void reverse(char *s, int len) /* Wrap strcmp() for qsort(). */ static int strsort(const void *s1, const void *s2) { - return strcmp(*(char **) s1, *(char **) s2); + return strcmp(*(char *const *) s1, *(char *const *) s2); } int main(void) diff --git a/Task/Semordnilap/Clojure/semordnilap.clj b/Task/Semordnilap/Clojure/semordnilap.clj new file mode 100644 index 0000000000..37b96f7511 --- /dev/null +++ b/Task/Semordnilap/Clojure/semordnilap.clj @@ -0,0 +1,21 @@ +(use 'clojure.java.io) +(require '[clojure.string :as string]) + +(def dict-file (or (first *command-line-args*) "unixdict.txt")) + +(def dict (set (line-seq (reader dict-file)))) + +(defn semordnilap? [word] + (let [rev (string/reverse word)] + (and (not (= word rev)) (dict rev)))) + +(def semordnilaps + (filter (fn [[x y]] (<= (compare x y) 0)) + (map (fn [word] [word (string/reverse word)]) + (filter semordnilap? dict)))) + +(printf "There are %d semordnilaps in %s. Here are 5:\n" + (count semordnilaps) + dict-file) + +(dorun (map println (sort (take 5 (shuffle semordnilaps))))) diff --git a/Task/Semordnilap/Erlang/semordnilap.erl b/Task/Semordnilap/Erlang/semordnilap.erl new file mode 100644 index 0000000000..5ef1909bbb --- /dev/null +++ b/Task/Semordnilap/Erlang/semordnilap.erl @@ -0,0 +1,35 @@ +#!/usr/bin/env escript +main([]) -> main(["unixdict.txt"]); + +main([DictFile]) -> + Dict = sets:from_list(read_lines(DictFile)), + Semordnilaps = + lists:filter(fun([W,R]) -> W < R end, + lists:map(fun(W) -> [W, lists:reverse(W)] end, + semordnilaps(Dict))), + io:fwrite("There are ~b semordnilaps in ~s~n", + [length(Semordnilaps), DictFile]), + lists:map(fun([W,R]) -> io:fwrite("~s/~s~n", [W, R]) end, + lists:sort(lists:sublist(shuffle(Semordnilaps),1,5))). + +read_lines(Filename) when is_list(Filename) -> + { ok, File } = file:open(Filename, [read]), + read_lines(File); + +read_lines(File) when is_pid(File) -> + case file:read_line(File) of + {ok, Data} -> [chop(Data) | read_lines(File)]; + eof -> [] + end. + +is_semordnilap(Word, Dict) -> + Rev = lists:reverse(Word), + sets:is_element(Word, Dict) and sets:is_element(Rev, Dict). + +semordnilaps(Dict) -> + lists:filter(fun(W) -> is_semordnilap(W, Dict) end, sets:to_list(Dict)). + +shuffle(List) -> + [X||{_,X} <- lists:sort([ {random:uniform(), N} || N <- List])]. + +chop(L) -> [_|T] = lists:reverse(L), lists:reverse(T). diff --git a/Task/Semordnilap/Fortran/semordnilap.f b/Task/Semordnilap/Fortran/semordnilap.f new file mode 100644 index 0000000000..82a5504671 --- /dev/null +++ b/Task/Semordnilap/Fortran/semordnilap.f @@ -0,0 +1,117 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Sun May 19 21:50:08 +! +!a=./F && make $a && $a < unixdict.txt +!f95 -Wall -ffree-form F.F -o F +! 5 of 158 semordnilaps +!yaw +!room +!xi +!tim +!nova +! +! +!Compilation finished at Sun May 19 21:50:08 +! +! +! +! +! unixdict.txt information +! wc -l unixdict.txt #--> 25104 25 thousand entries +! gawk 'length(a)<length($0){a=$0}END{print a}' unixdict.txt #--> electroencephalography longest word has 22 characters +! gawk '/[A-Z]/{++a}END{print a}' unixdict.txt #--> <empty> the dictionary is lower case +! sort unixdict.txt | cmp - unixdict.txt #--> - unixdict.txt differ: byte 45, line 12 +! the dictionary is unsorted +! mmmmm the dictionary is sorted, according to subroutine bs. There's something about the ampersands within unixdict.txt I misunderstand. + +program Semordnilap + implicit none + integer :: i, ios, words, swords + character(len=24), dimension(32768) :: dictionary, backword + real, dimension(5) :: harvest + ! read the dictionary + open(7,file='unixdict.txt') + do words = 1, 32768 + read(7, '(a)', iostat = ios) dictionary(words) + if (ios .ne. 0) exit + enddo + close(7) + if (iachar(dictionary(words)(1:1)) .eq. 0) words = words-1 + ! sort the dictionary + call bs(dictionary, words) + !do i = 1, words + ! write(6,*) dictionary(i)(1:len_trim(dictionary(i))) ! with which we determine the dictionary was ordered + !enddo + swords = 0 + do i = 1, words + call reverse(dictionary(i), backword(swords+1)) + if ((binary_search(dictionary, words, backword(swords+1))) & ! the reversed word is in the dictionary + .and. (.not. binary_search(backword, swords, dictionary(i))) & ! and it's new + .and. (dictionary(i) .ne. backword(swords+1))) then ! and it's not a palindrome + swords = swords + 1 + call bs(backword, swords) + endif + enddo + call random_number(harvest) + call reverse('spalindromes', backword(swords+1)) + write(6, *) '5 of ', swords, backword(swords+1) + write(6,'(5(a/))') (backword(1+int(harvest(i)*(swords-2))), i=1,5) + +contains + + subroutine reverse(inp, outp) + character(len=*), intent(in) :: inp + character(len=*), intent(inout) :: outp + integer :: k, L + L = len_trim(inp) + do k = 1, L + outp(L+1-k:L+1-k) = inp(k:k) + enddo + do k = L+1, len(outp) + outp(k:k) = ' ' + enddo + end subroutine reverse + + subroutine bs(a, n) ! ok, despite having claimed that bubble sort should be unceremoniously buried, I'll use it anyway because I expect the dictionary is nearly ordered. It's also not a terrible sort for less than 5 items. + ! Please note, I tested bs using unixdict.txt randomized with sort --random . + character(len=*),dimension(*),intent(inout) :: a + integer, intent(in) :: n + integer :: i, j, k + logical :: done + character(len=1) :: t + do i=n-1, 1, -1 + done = .true. + do j=1, i + if (a(j+1) .lt. a(j)) then + done = .false. + do k = 1, max(len_trim(a(j+1)), len_trim(a(j))) + t = a(j+1)(k:k) + a(j+1)(k:k) = a(j)(k:k) + a(j)(k:k) = t(1:1) + enddo + endif + enddo + if (done) return + enddo + end subroutine bs + + logical function binary_search(source, n, target) + character(len=*),dimension(*),intent(in) :: source + character(len=*),intent(in) :: target + integer, intent(in) :: n + integer :: a,m,z + a = 1 + z = n + do while (a .lt. z) + m = a + (z - a) / 2 + if (target .lt. source(m)) then + z = m-1 + else + if (m .eq. a) exit + a = m + endif + enddo + binary_search = (target .eq. source(a)) .or. (target .eq. source(z)) + end function binary_search + +end program Semordnilap diff --git a/Task/Semordnilap/JavaScript/semordnilap-1.js b/Task/Semordnilap/JavaScript/semordnilap-1.js new file mode 100644 index 0000000000..693f20b6ae --- /dev/null +++ b/Task/Semordnilap/JavaScript/semordnilap-1.js @@ -0,0 +1,40 @@ +#!/usr/bin/env node +var fs = require('fs'); +var sys = require('sys'); + +var dictFile = process.argv[2] || "unixdict.txt"; + +var dict = {}; +fs.readFileSync(dictFile) + .toString() + .split('\n') + .forEach(function(word) { + dict[word] = word.split("").reverse().join(""); + }); + +function isSemordnilap(word) { return dict[dict[word]]; }; + +var semordnilaps = [] +for (var key in dict) { + if (isSemordnilap(key)) { + var rev = dict[key]; + if (key < rev) { + semordnilaps.push([key,rev]) ; + } + } +} + +var count = semordnilaps.length; +sys.puts("There are " + count + " semordnilaps in " + + dictFile + ". Here are 5:" ); + +var indices=[] +for (var i=0; i<count; ++i) { + if (Math.random() < 1/Math.ceil(i/5.0)) { + indices[i%5] = i + } +} +indices.sort() +for (var i=0; i<5; ++i) { + sys.puts(semordnilaps[indices[i]]); +} diff --git a/Task/Semordnilap/JavaScript/semordnilap-2.js b/Task/Semordnilap/JavaScript/semordnilap-2.js new file mode 100644 index 0000000000..4c4e7c464c --- /dev/null +++ b/Task/Semordnilap/JavaScript/semordnilap-2.js @@ -0,0 +1,38 @@ +#!/usr/bin/env rhino + +importPackage (java.io) + +var dictFile = arguments[0] || "unixdict.txt"; + +var reader = new BufferedReader(new FileReader(dictFile)); +var dict = {}; +var word; +while (word = reader.readLine()) { + dict[word] = word.split("").reverse().join(""); +} + +function isSemordnilap(word) { return dict[dict[word]]; }; + +var semordnilaps = [] +for (var key in dict) { + if (isSemordnilap(key)) { + var rev = dict[key]; + if (key < rev) { + semordnilaps.push([key,rev]) ; + } + } +} + +var count = semordnilaps.length; +print("There are " + count + " semordnilaps in " + + dictFile + ". Here are 5:" ); +var indices=[] +for (var i=0; i<count; ++i) { + if (Math.random() < 1/Math.ceil(i/5.0)) { + indices[i%5] = i + } +} +indices.sort() +for (var i=0; i<5; ++i) { + print(semordnilaps[indices[i]]); +} diff --git a/Task/Semordnilap/Racket/semordnilap.rkt b/Task/Semordnilap/Racket/semordnilap.rkt new file mode 100644 index 0000000000..91c8094c69 --- /dev/null +++ b/Task/Semordnilap/Racket/semordnilap.rkt @@ -0,0 +1,14 @@ +#lang racket +(define seen (make-hash)) +(define semordnilaps '()) +(call-with-input-file "/usr/share/dict/words" + (λ(i) (for ([l (in-lines i)]) + (define r (list->string (reverse (string->list l)))) + (unless (equal? r l) + (hash-set! seen l #t) + (when (hash-ref seen r #f) + (set! semordnilaps (cons (list r l) semordnilaps))))))) +(printf "Total semordnilaps found: ~s\n" (length semordnilaps)) +(printf "The five longest ones:\n") +(for ([s (take (sort semordnilaps > #:key (compose1 string-length car)) 5)]) + (apply printf " ~s ~s\n" s)) diff --git a/Task/Semordnilap/Ruby/semordnilap.rb b/Task/Semordnilap/Ruby/semordnilap.rb index 761dddaca5..89239a4acd 100644 --- a/Task/Semordnilap/Ruby/semordnilap.rb +++ b/Task/Semordnilap/Ruby/semordnilap.rb @@ -1,9 +1,8 @@ -DICT=File.readlines("unixdict.txt").collect{|line| line.tr("\n", "")} -res=[] +DICT=File.readlines("unixdict.txt").collect &:chomp i = 0 -DICT.collect {|z| z.reverse}.sort.each {|z| +res = DICT.collect(&:reverse).sort.select {|z| i+=1 while z > DICT[i] and i < DICT.length-1 - res.push z if z.eql?(DICT[i]) and z < z.reverse + z == DICT[i] and z < z.reverse } puts "There are #{res.length} semordnilaps, of which the following are 5:" res.sample(5).each {|z| puts "#{z} #{z.reverse}"} diff --git a/Task/Semordnilap/Scala/semordnilap.scala b/Task/Semordnilap/Scala/semordnilap.scala new file mode 100644 index 0000000000..95d6d2d560 --- /dev/null +++ b/Task/Semordnilap/Scala/semordnilap.scala @@ -0,0 +1,28 @@ +val wordsAll = scala.io.Source.fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.map(_.toLowerCase).to[IndexedSeq] + +/** + * Given a sequence of lower-case words return a sub-sequence + * of matches containing the word and its reverse if the two + * words are different. + */ +def semordnilap( words:Seq[String] ) : Seq[(String,String)] = { + + ( words. + zipWithIndex. // index will be needed to eliminate duplicate + filter { + case (w,i) => + val j = words.indexOf(w.reverse) // eg. (able,62) and (elba,7519) + i < j && w != w.reverse // save the matches which are not palindromes + } + ). + map { + case (w,i) => (w,w.reverse) // drop the index + } +} + +val ss = semordnilap(wordsAll) + +{ +println( ss.size + " matches, including: \n" ) +println( ss.take(5).mkString( "\n" ) ) +} diff --git a/Task/Semordnilap/Seed7/semordnilap.seed7 b/Task/Semordnilap/Seed7/semordnilap.seed7 new file mode 100644 index 0000000000..ba012dd75b --- /dev/null +++ b/Task/Semordnilap/Seed7/semordnilap.seed7 @@ -0,0 +1,37 @@ +$ include "seed7_05.s7i"; + include "gethttp.s7i"; + +const func string: reverse (in string: word) is func + result + var string: drow is ""; + local + var integer: index is 0; + begin + for index range length(word) downto 1 do + drow &:= word[index]; + end for; + end func; + +const proc: main is func + local + var array string: wordList is 0 times ""; + var set of string: words is (set of string).value; + var string: word is ""; + var string: drow is ""; + var integer: count is 0; + begin + wordList := split(lower(getHttp("www.puzzlers.org/pub/wordlists/unixdict.txt")), "\n"); + for word range wordList do + drow := reverse(word); + if drow not in words then + incl(words, word); + else + if count < 5 then + writeln(word <& " " <& drow); + end if; + incr(count); + end if; + end for; + writeln; + writeln("Semordnilap pairs: " <& count); + end func; diff --git a/Task/Send-an-unknown-method-call/Bracmat/send-an-unknown-method-call.bracmat b/Task/Send-an-unknown-method-call/Bracmat/send-an-unknown-method-call.bracmat new file mode 100644 index 0000000000..ad008ca8dc --- /dev/null +++ b/Task/Send-an-unknown-method-call/Bracmat/send-an-unknown-method-call.bracmat @@ -0,0 +1,19 @@ +(task= + ( oracle + = (predicate="is made of green cheese") + (generateTruth=.str$(!arg " " !(its.predicate) ".")) + (generateLie=.str$(!arg " " !(its.predicate) "!")) + ) +& new$oracle:?SourceOfKnowledge +& put + $ "You may ask the Source of Eternal Wisdom ONE thing. +Enter \"Truth\" or \"Lie\" on the next line and press the <Enter> key. +" +& whl + ' ( get':?trueorlie:~Truth:~Lie + & put$"Try again\n" + ) +& put$(str$("You want a " !trueorlie ". About what?" \n)) +& get'(,STR):?something +& (SourceOfKnowledge..str$(generate !trueorlie))$!something +); diff --git a/Task/Send-an-unknown-method-call/Cache-ObjectScript/send-an-unknown-method-call.cos b/Task/Send-an-unknown-method-call/Cache-ObjectScript/send-an-unknown-method-call.cos new file mode 100644 index 0000000000..06622ba85e --- /dev/null +++ b/Task/Send-an-unknown-method-call/Cache-ObjectScript/send-an-unknown-method-call.cos @@ -0,0 +1,14 @@ +Class Unknown.Example Extends %RegisteredObject +{ + +Method Foo() +{ + Write "This is foo", ! +} + +Method Bar() +{ + Write "This is bar", ! +} + +} diff --git a/Task/Send-an-unknown-method-call/Lua/send-an-unknown-method-call.lua b/Task/Send-an-unknown-method-call/Lua/send-an-unknown-method-call.lua new file mode 100644 index 0000000000..d01ac55f3d --- /dev/null +++ b/Task/Send-an-unknown-method-call/Lua/send-an-unknown-method-call.lua @@ -0,0 +1,5 @@ +local example = { } +function example:foo (x) return 42 + x end + +local name = "foo" +example[name](example, 5) --> 47 diff --git a/Task/Send-an-unknown-method-call/Racket/send-an-unknown-method-call.rkt b/Task/Send-an-unknown-method-call/Racket/send-an-unknown-method-call.rkt new file mode 100644 index 0000000000..090b13cd9e --- /dev/null +++ b/Task/Send-an-unknown-method-call/Racket/send-an-unknown-method-call.rkt @@ -0,0 +1,12 @@ +#lang racket +(define greeter + (new (class object% (super-new) + (define/public (hello name) + (displayln (~a "Hello " name ".")))))) + +; normal method call +(send greeter hello "World") + +; sending an unknown method +(define unknown 'hello) +(dynamic-send greeter unknown "World") diff --git a/Task/Send-email/Racket/send-email.rkt b/Task/Send-email/Racket/send-email.rkt index d534555d5a..927252bb04 100644 --- a/Task/Send-email/Racket/send-email.rkt +++ b/Task/Send-email/Racket/send-email.rkt @@ -1,6 +1,16 @@ #lang racket -(require net/head net/smtp) +;; using sendmail: +(require net/sendmail) +(send-mail-message + "sender@somewhere.com" "Some Subject" + '("recipient@elsewhere.com" "recipient2@elsewhere.com") + '("cc@elsewhere.com") + '("bcc@elsewhere.com") + (list "Some lines of text" "go here.")) + +;; and using smtp (and adding more headers here): +(require net/head net/smtp) (smtp-send-message "192.168.0.1" "Sender <sender@somewhere.com>" diff --git a/Task/Sequence-of-non-squares/Erlang/sequence-of-non-squares.erl b/Task/Sequence-of-non-squares/Erlang/sequence-of-non-squares.erl new file mode 100644 index 0000000000..6d5688574e --- /dev/null +++ b/Task/Sequence-of-non-squares/Erlang/sequence-of-non-squares.erl @@ -0,0 +1,9 @@ +% Implemented by Arjun Sunel +-module(non_squares). +-export([main/0]). + +main() -> + lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,22)), % First 22 non-squares. + lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,1000000)). % First 1 million non-squares. +non_square(N) -> + N+trunc(1/2+ math:sqrt(N)). diff --git a/Task/Set-consolidation/Aime/set-consolidation.aime b/Task/Set-consolidation/Aime/set-consolidation.aime new file mode 100644 index 0000000000..ba0e85afcc --- /dev/null +++ b/Task/Set-consolidation/Aime/set-consolidation.aime @@ -0,0 +1,130 @@ +void +display(list l) +{ + integer i; + text s; + + i = -l_length(l); + while (i) { + record r; + text u, v; + + o_text(s); + s = ", "; + o_text("{"); + r = l_q_record(l, i); + if (r_first(r, u)) { + do { + o_text(v); + v = ", "; + o_text(u); + } while (r_greater(r, u, u)); + } + o_text("}"); + i += 1; + } + + o_text("\n"); +} + +integer +intersect(record r, record u) +{ + integer a; + text s; + + a = 0; + if (r_first(r, s)) { + do { + if (r_key(u, s)) { + a = 1; + break; + } + } while (r_greater(r, s, s)); + } + + return a; +} + +void +merge(record u, record r) +{ + text s; + + if (r_first(r, s)) { + do { + r_add(u, s, r_query(r, s)); + } while (r_greater(r, s, s)); + } +} + +list +consolidate(list l) +{ + integer i; + + i = -l_length(l); + while (i) { + integer j; + record r; + + r = l_q_record(l, i); + i += 1; + j = i; + while (j) { + record u; + + u = l_q_record(l, j); + j += 1; + if (intersect(r, u)) { + merge(u, r); + l_delete(l, i - 1); + break; + } + } + } + + return l; +} + +list +L(...) +{ + integer i; + list l; + + i = -count(); + while (i) { + l_link(l, -1, $i); + i += 1; + } + + return l; +} + +record +R(...) +{ + integer i; + record r; + + i = -count(); + while (i) { + r_p_integer(r, $i, 0); + i += 1; + } + + return r; +} + +integer +main(void) +{ + display(consolidate(L(R("A", "B"), R("C", "D")))); + display(consolidate(L(R("A", "B"), R("B", "D")))); + display(consolidate(L(R("A", "B"), R("C", "D"), R("D", "B")))); + display(consolidate(L(R("H", "I", "K"), R("A", "B"), R("C", "D"), + R("D", "B"), R("F", "G", "K")))); + + return 0; +} diff --git a/Task/Set-consolidation/Racket/set-consolidation-1.rkt b/Task/Set-consolidation/Racket/set-consolidation-1.rkt new file mode 100644 index 0000000000..c96d685ee8 --- /dev/null +++ b/Task/Set-consolidation/Racket/set-consolidation-1.rkt @@ -0,0 +1,14 @@ +#lang racket +(define (consolidate ss) + (define (comb s cs) + (cond [(set-empty? s) cs] + [(empty? cs) (list s)] + [(set-empty? (set-intersect s (first cs))) + (cons (first cs) (comb s (rest cs)))] + [(consolidate (cons (set-union s (first cs)) (rest cs)))])) + (foldl comb '() ss)) + +(consolidate (list (set 'a 'b) (set 'c 'd))) +(consolidate (list (set 'a 'b) (set 'b 'c))) +(consolidate (list (set 'a 'b) (set 'c 'd) (set 'd 'b))) +(consolidate (list (set 'h 'i 'k) (set 'a 'b) (set 'c 'd) (set 'd 'b) (set 'f 'g 'h))) diff --git a/Task/Set-consolidation/Racket/set-consolidation-2.rkt b/Task/Set-consolidation/Racket/set-consolidation-2.rkt new file mode 100644 index 0000000000..85a270dcc3 --- /dev/null +++ b/Task/Set-consolidation/Racket/set-consolidation-2.rkt @@ -0,0 +1,4 @@ +(list (set 'b 'a) (set 'd 'c)) +(list (set 'a 'b 'c)) +(list (set 'a 'b 'd 'c)) +(list (set 'g 'h 'k 'i 'f) (set 'a 'b 'd 'c)) diff --git a/Task/Set-of-real-numbers/Racket/set-of-real-numbers.rkt b/Task/Set-of-real-numbers/Racket/set-of-real-numbers.rkt new file mode 100644 index 0000000000..4e514d0a9e --- /dev/null +++ b/Task/Set-of-real-numbers/Racket/set-of-real-numbers.rkt @@ -0,0 +1,42 @@ +#lang racket + +;; Use a macro to allow infix operators +(require (only-in racket [#%app #%%app])) +(define-for-syntax infixes '()) +(define-syntax (definfix stx) + (syntax-case stx () + [(_ (x . xs) body ...) #'(definfix x (λ xs body ...))] + [(_ x body) (begin (set! infixes (cons #'x infixes)) #'(define x body))])) +(define-syntax (#%app stx) + (syntax-case stx () + [(_ X op Y) + (and (identifier? #'op) (ormap (λ(o) (free-identifier=? #'op o)) infixes)) + #'(#%%app op X Y)] + [(_ f x ...) #'(#%%app f x ...)])) + + +;; Ranges: (X +-+ Y) => [X,Y]; (X --- Y) => (X,Y); and same for `+--' and `--+' +;; Simple implementation as functions + +;; Constructors +(definfix ((+-+ X Y) n) (<= X n Y)) ; [X,Y] +(definfix ((--- X Y) n) (< X n Y)) ; (X,Y) +(definfix ((+-- X Y) n) (and (<= X n) (< n Y))) ; [X,Y) +(definfix ((--+ X Y) n) (and (< X n) (<= n Y))) ; (X,Y] +(definfix ((== X) n) (= X n)) ; [X,X] +;; Set operations +(definfix ((∪ . Rs) n) (ormap (λ(p) (p n)) Rs)) +(definfix ((∩ . Rs) n) (andmap (λ(p) (p n)) Rs)) +(definfix ((∖ R1 R2) n) (and (R1 n) (not (R2 n)))) ; set-minus, not backslash +(define ((¬ R) n) (not (R n))) +;; Special sets +(define (∅ n) #f) +(define (ℜ n) #t) + +(define-syntax-rule (try set) + (apply printf "~a => ~a ~a ~a\n" (~s #:width 23 'set) + (let ([pred set]) (for/list ([i 3]) (if (pred i) 'Y 'N))))) +(try ((0 --+ 1) ∪ (0 +-- 2))) +(try ((0 +-- 2) ∩ (1 --+ 2))) +(try ((0 +-- 3) ∖ (0 --- 1))) +(try ((0 +-- 3) ∖ (0 +-+ 1))) diff --git a/Task/Set-puzzle/Racket/set-puzzle.rkt b/Task/Set-puzzle/Racket/set-puzzle.rkt new file mode 100644 index 0000000000..ea8e411512 --- /dev/null +++ b/Task/Set-puzzle/Racket/set-puzzle.rkt @@ -0,0 +1,36 @@ +#lang racket + +(struct card [bits name]) + +(define cards + (for/list ([C '(red green purple )] [Ci '(#o0001 #o0002 #o0004)] + #:when #t + [S '(oval squiggle diamond)] [Si '(#o0010 #o0020 #o0040)] + #:when #t + [N '(one two three )] [Ni '(#o0100 #o0200 #o0400)] + #:when #t + [D '(solid open striped)] [Di '(#o1000 #o2000 #o4000)]) + (card (bitwise-ior Ci Si Ni Di) (format "~a, ~a, ~a, ~a" C S N D)))) + +(define (nsubsets l n) + (cond [(zero? n) '(())] [(null? l) '()] + [else (append (for/list ([l2 (nsubsets (cdr l) (- n 1))]) + (cons (car l) l2)) + (nsubsets (cdr l) n))])) +(define (set? cards) + (regexp-match? #rx"^[1247]*$" + (number->string (apply bitwise-ior (map card-bits cards)) 8))) + +(define (deal C S) + (define hand (take (shuffle cards) C)) + (define 3sets (filter set? (nsubsets hand 3))) + (cond [(not (= S (length 3sets))) (deal C S)] + [else (printf "Dealt ~a cards:\n" C) + (for ([c hand]) (printf " ~a\n" (card-name c))) + (printf "\nContaining ~a sets:\n" S) + (for ([set 3sets]) + (for ([c set]) (printf " ~a\n" (card-name c))) + (newline))])) + +(deal 9 4) +(deal 12 6) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Java/seven-sided-dice-from-five-sided-dice.java b/Task/Seven-sided-dice-from-five-sided-dice/Java/seven-sided-dice-from-five-sided-dice.java new file mode 100644 index 0000000000..4129901c42 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Java/seven-sided-dice-from-five-sided-dice.java @@ -0,0 +1,21 @@ +import java.util.Random; +public class SevenSidedDice +{ + private static final Random rnd = new Random(); + public static void main(String[] args) + { + SevenSidedDice now=new SevenSidedDice(); + System.out.println("Random number from 1 to 7: "+now.seven()); + } + int seven() + { + int v=21; + while(v>20) + v=five()+five()*5-6; + return 1+v%7; + } + int five() + { + return 1+rnd.nextInt(5); + } +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Racket/seven-sided-dice-from-five-sided-dice-1.rkt b/Task/Seven-sided-dice-from-five-sided-dice/Racket/seven-sided-dice-from-five-sided-dice-1.rkt new file mode 100644 index 0000000000..0faa433ec2 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Racket/seven-sided-dice-from-five-sided-dice-1.rkt @@ -0,0 +1,6 @@ +#lang racket +(define (dice5) (add1 (random 5))) + +(define (dice7) + (define res (+ (* 5 (dice5)) (dice5) -6)) + (if (< res 21) (+ 1 (modulo res 7)) (dice7))) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Racket/seven-sided-dice-from-five-sided-dice-2.rkt b/Task/Seven-sided-dice-from-five-sided-dice/Racket/seven-sided-dice-from-five-sided-dice-2.rkt new file mode 100644 index 0000000000..c63eba3bec --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Racket/seven-sided-dice-from-five-sided-dice-2.rkt @@ -0,0 +1,9 @@ +-> (require math/statistics) +-> (samples->hash (for/list ([i 700000]) (dice7))) +'#hash((7 . 100392) + (6 . 100285) + (5 . 99774) + (4 . 100000) + (3 . 100000) + (2 . 99927) + (1 . 99622)) diff --git a/Task/Shell-one-liner/Bracmat/shell-one-liner-1.bracmat b/Task/Shell-one-liner/Bracmat/shell-one-liner-1.bracmat new file mode 100644 index 0000000000..3d3fb53d0a --- /dev/null +++ b/Task/Shell-one-liner/Bracmat/shell-one-liner-1.bracmat @@ -0,0 +1 @@ +bracmat "put$tay$(e^x,x,20)&" diff --git a/Task/Shell-one-liner/Bracmat/shell-one-liner-2.bracmat b/Task/Shell-one-liner/Bracmat/shell-one-liner-2.bracmat new file mode 100644 index 0000000000..c88f67ee96 --- /dev/null +++ b/Task/Shell-one-liner/Bracmat/shell-one-liner-2.bracmat @@ -0,0 +1 @@ +bracmat 'put$tay$(e^x,x,10)&' diff --git a/Task/Short-circuit-evaluation/Bracmat/short-circuit-evaluation.bracmat b/Task/Short-circuit-evaluation/Bracmat/short-circuit-evaluation.bracmat new file mode 100644 index 0000000000..59a3d6ed9b --- /dev/null +++ b/Task/Short-circuit-evaluation/Bracmat/short-circuit-evaluation.bracmat @@ -0,0 +1,28 @@ +( (a=.out$"I'm a"&!!arg) +& (b=.out$"I'm b"&!!arg) +& (false==~) +& (true==) +& !false !true:?outer +& whl + ' ( !outer:%?x ?outer + & !false !true:?inner + & whl + ' ( !inner:%?y ?inner + & out + $ ( Testing + (!!x&true|false) + AND + (!!y&true|false) + ) + & `(a$!x&b$!y) + & out + $ ( Testing + (!!x&true|false) + OR + (!!y&true|false) + ) + & `(a$!x|b$!y) + ) + ) +& done +); diff --git a/Task/Short-circuit-evaluation/Julia/short-circuit-evaluation.julia b/Task/Short-circuit-evaluation/Julia/short-circuit-evaluation.julia index a158c07445..d89f83d088 100644 --- a/Task/Short-circuit-evaluation/Julia/short-circuit-evaluation.julia +++ b/Task/Short-circuit-evaluation/Julia/short-circuit-evaluation.julia @@ -1,6 +1,9 @@ -a(x) = (println(" # Called function a($x) -> $x"); return x) -b(x) = (println(" # Called function a($x) -> $x"); return x) +a(x) = (println("\t# Called a($x)"); return x) +b(x) = (println("\t# Called b($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) + println("\nCalculating: x = a($i) && b($j)"); x = a(i) && b(j) + println("\tResult: x = $x") + println("\nCalculating: y = a($i) || b($j)"); y = a(i) || b(j) + println("\tResult: y = $y") end diff --git a/Task/Short-circuit-evaluation/Run-BASIC/short-circuit-evaluation.run b/Task/Short-circuit-evaluation/Run-BASIC/short-circuit-evaluation.run new file mode 100644 index 0000000000..5e05d9bde3 --- /dev/null +++ b/Task/Short-circuit-evaluation/Run-BASIC/short-circuit-evaluation.run @@ -0,0 +1,24 @@ +for k = 1 to 2 +ao$ = word$("AND,OR",k,",") +print "========= ";ao$;" ==============" +for i = 0 to 1 + for j = 0 to 1 + print "a("; i; ") ";ao$;" b("; j; ")" + res =a(i) 'call always +'print res;"<====" +if ao$ = "AND" and res <> 0 then res = b(j) +if ao$ = "OR" and res = 0 then res = b(j) + next +next +next k +end + +function a( t) + print chr$(9);"calls func a" + a = t +end function + +function b( t) + print chr$(9);"calls func b" + b = t +end function diff --git a/Task/Show-the-epoch/Factor/show-the-epoch.factor b/Task/Show-the-epoch/Factor/show-the-epoch.factor new file mode 100644 index 0000000000..f70d531715 --- /dev/null +++ b/Task/Show-the-epoch/Factor/show-the-epoch.factor @@ -0,0 +1,3 @@ +IN: USE: calendar calendar.format +IN: 0 micros>timestamp timestamp>ymdhms . +"1970-01-01 00:00:00" diff --git a/Task/Show-the-epoch/UNIX-Shell/show-the-epoch-1.sh b/Task/Show-the-epoch/UNIX-Shell/show-the-epoch-1.sh new file mode 100644 index 0000000000..fab910f3c4 --- /dev/null +++ b/Task/Show-the-epoch/UNIX-Shell/show-the-epoch-1.sh @@ -0,0 +1,2 @@ +$ date -ur 0 +Thu Jan 1 00:00:00 UTC 1970 diff --git a/Task/Show-the-epoch/UNIX-Shell/show-the-epoch-2.sh b/Task/Show-the-epoch/UNIX-Shell/show-the-epoch-2.sh new file mode 100644 index 0000000000..20bfcae299 --- /dev/null +++ b/Task/Show-the-epoch/UNIX-Shell/show-the-epoch-2.sh @@ -0,0 +1,2 @@ +$ TZ=UTC date --date "$(date +%s) seconds ago" +Thu Jan 1 00:00:00 UTC 1970 diff --git a/Task/Sierpinski-carpet/C++/sierpinski-carpet.cpp b/Task/Sierpinski-carpet/C++/sierpinski-carpet.cpp new file mode 100644 index 0000000000..bb6527cd7d --- /dev/null +++ b/Task/Sierpinski-carpet/C++/sierpinski-carpet.cpp @@ -0,0 +1,122 @@ +#include <windows.h> +#include <math.h> + +//-------------------------------------------------------------------------------------------------- +const int BMP_SIZE = 738; + +//-------------------------------------------------------------------------------------------------- +class Sierpinski +{ +public: + void draw( HDC wdc, int wid, int hei, int ord ) + { + _wdc = wdc; + _ord = wid / static_cast<int>( pow( 3.0, ord ) ); + drawIt( 0, 0, wid, hei ); + } + + void setHWND( HWND hwnd ) { _hwnd = hwnd; } + +private: + void drawIt( int x, int y, int wid, int hei ) + { + if( wid < _ord || hei < _ord ) return; + int w = wid / 3, h = hei / 3; + RECT rc; + SetRect( &rc, x + w, y + h, x + w + w, y + h + h ); + FillRect( _wdc, &rc, static_cast<HBRUSH>( GetStockObject( BLACK_BRUSH ) ) ); + + for( int a = 0; a < 3; a++ ) + for( int b = 0; b < 3; b++ ) + { + if( a == 1 && b == 1 ) continue; + drawIt( x + b * w, y + a * h, w, h ); + } + } + + HWND _hwnd; + HDC _wdc; + int _ord; +}; +//-------------------------------------------------------------------------------------------------- +class wnd +{ +public: + wnd() { _inst = this; } + int wnd::Run( HINSTANCE hInst ) + { + _hInst = hInst; + _hwnd = InitAll(); + + _carpet.setHWND( _hwnd ); + + ShowWindow( _hwnd, SW_SHOW ); + UpdateWindow( _hwnd ); + + MSG msg; + ZeroMemory( &msg, sizeof( msg ) ); + while( msg.message != WM_QUIT ) + { + if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) + { + TranslateMessage( &msg ); + DispatchMessage( &msg ); + } + } + return UnregisterClass( "_SIERPINSKI_", _hInst ); + } +private: + void wnd::doPaint( HDC dc ) { _carpet.draw( dc, BMP_SIZE, BMP_SIZE, 5 ); } + + static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) + { + switch( msg ) + { + case WM_DESTROY: PostQuitMessage( 0 ); break; + case WM_PAINT: + { + PAINTSTRUCT ps; + HDC dc = BeginPaint( hWnd, &ps ); + _inst->doPaint( dc ); + EndPaint( hWnd, &ps ); + } + default: + return DefWindowProc( hWnd, msg, wParam, lParam ); + } + return 0; + } + + HWND InitAll() + { + WNDCLASSEX wcex; + ZeroMemory( &wcex, sizeof( wcex ) ); + wcex.cbSize = sizeof( WNDCLASSEX ); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = ( WNDPROC )WndProc; + wcex.hInstance = _hInst; + wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); + wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); + wcex.lpszClassName = "_SIERPINSKI_"; + + RegisterClassEx( &wcex ); + + RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; + AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); + int w = rc.right - rc.left, + h = rc.bottom - rc.top; + return CreateWindow( "_SIERPINSKI_", ".: Sierpinski carpet -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); + } + + static wnd* _inst; + HINSTANCE _hInst; + HWND _hwnd; + Sierpinski _carpet; +}; +wnd* wnd::_inst = 0; +//-------------------------------------------------------------------------------------------------- +int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) +{ + wnd myWnd; + return myWnd.Run( hInstance ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d index 72947adbbb..27dd5c54f5 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d @@ -3,12 +3,12 @@ import std.stdio, std.string, std.algorithm, std.array; auto sierpinskiCarpet(in int n) /*pure nothrow*/ { auto r = ["#"]; foreach (_; 0 .. n) { - auto p = r.map!q{a ~ a ~ a}().array(); - r = p ~ r.map!q{a ~ a.replace("#", " ") ~ a}().array() ~ p; + auto p = r.map!q{a ~ a ~ a}.array; + r = p ~ r.map!q{a ~ a.replace("#", " ") ~ a}.array ~ p; } return r.join("\n"); } void main() { - writeln(sierpinskiCarpet(3)); + 3.sierpinskiCarpet.writeln; } diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d index b211b00b01..6c88d8cddf 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-2.d @@ -1,11 +1,14 @@ -import std.stdio, std.algorithm, std.range; +import std.stdio, std.algorithm, std.range, std.functional; auto nextCarpet(in string[] c) /*pure nothrow*/ { - const b = c.map!q{a ~ a ~ a}().array(); - return b ~ c.map!q{a ~ a.replace("#", " ") ~ a}().array() ~ b; + const b = c.map!q{a ~ a ~ a}.array; + return b ~ c.map!q{a ~ a.replace("#", " ") ~ a}.array ~ b; } void main() { - auto c = ["#"].recurrence!((a, n) => nextCarpet(a[n - 1]))(); - writefln("%-(%s\n%)", c.dropExactly(3).front); + ["#"] + .recurrence!((a, n) => a[n - 1].nextCarpet) + .dropExactly(3) + .front + .binaryReverseArgs!writefln("%-(%s\n%)"); } diff --git a/Task/Sierpinski-carpet/Erlang/sierpinski-carpet.erl b/Task/Sierpinski-carpet/Erlang/sierpinski-carpet.erl new file mode 100644 index 0000000000..8a91d983e2 --- /dev/null +++ b/Task/Sierpinski-carpet/Erlang/sierpinski-carpet.erl @@ -0,0 +1,19 @@ +% Implemented by Arjun Sunel +-module(carpet). +-export([main/0]). + +main() -> + sierpinski_carpet(3). + +sierpinski_carpet(N) -> + lists: foreach(fun(X) -> lists: foreach(fun(Y) -> carpet(X,Y) end,lists:seq(0,trunc(math:pow(3,N))-1)), io:format("\n") end, lists:seq(0,trunc(math:pow(3,N))-1)). + +carpet(X,Y) -> + if + X=:=0 ; Y=:=0 -> + io:format("*"); + (X rem 3)=:=1, (Y rem 3) =:=1 -> + io:format(" "); + true -> + carpet(X div 3, Y div 3) + end. diff --git a/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-3.hs b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-3.hs new file mode 100644 index 0000000000..4bea6fedac --- /dev/null +++ b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-3.hs @@ -0,0 +1,13 @@ +main :: IO () +main = putStr . unlines . (!!3) $ iterate next ["#"] + +next :: [String] -> [String] +next block = + block ! block ! block + ++ + block ! center ! block + ++ + block ! block ! block + where + (!) = zipWith (++) + center = map (map $ const ' ') block diff --git a/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-4.hs b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-4.hs new file mode 100644 index 0000000000..ea422a5105 --- /dev/null +++ b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-4.hs @@ -0,0 +1,63 @@ +{-# LANGUAGE DoRec #-} +import Control.Monad.Trans (lift) +import Data.Colour (Colour) + +import Diagrams.Prelude hiding (after) +import Diagrams.Backend.Cairo (Cairo) +import Diagrams.Backend.Cairo.Gtk (defaultRender) + +import Graphics.Rendering.Diagrams.Points () +import Graphics.UI.Gtk +import Graphics.UI.Gtk.Gdk.GC (gcNew) + + +main :: IO () +main = do + _ <- initGUI + window <- windowNew + _ <- window `onDestroy` mainQuit + window `windowSetResizable` False + + area <- drawingAreaNew + _ <- area `on` sizeRequest $ return (Requisition 500 500) + _ <- window `containerAdd` area + widgetShowAll window + + rec con <- area `on` exposeEvent $ do + lift $ signalDisconnect con + lift $ area `defaultRender` carpet 5 + switchToPixBuf area + mainGUI + + +-- just workaround for slow redrawing +switchToPixBuf :: DrawingArea -> EventM EExpose Bool +switchToPixBuf area = + eventArea >>= \ea -> lift $ do + dw <- widgetGetDrawWindow area + (w,h) <- drawableGetSize dw + Just pb <- pixbufGetFromDrawable dw ea + gc <- gcNew dw + _ <- area `on` exposeEvent $ lift $ + False <$ drawPixbuf dw gc pb 0 0 0 0 w h RgbDitherNone 0 0 + return False + + +carpet :: Int -> Diagram Cairo R2 +carpet = (iterate next (cell white) !!) + +-- of course, one can use hcat / vcat - combinators +next :: Diagram Cairo R2 -> Diagram Cairo R2 +next block = + scale (1/3) . centerXY $ + + (block ||| block ||| block) + === + (block ||| centr ||| block) + === + (block ||| block ||| block) + where + centr = cell black + +cell :: Colour Float -> Diagram Cairo R2 +cell color = square 1 # lineWidth 0 # fillColor color diff --git a/Task/Sierpinski-carpet/Racket/sierpinski-carpet.rkt b/Task/Sierpinski-carpet/Racket/sierpinski-carpet.rkt new file mode 100644 index 0000000000..ec52b0c905 --- /dev/null +++ b/Task/Sierpinski-carpet/Racket/sierpinski-carpet.rkt @@ -0,0 +1,10 @@ +#lang racket +(define (carpet n) + (if (zero? n) + '("#") + (let* ([prev (carpet (sub1 n))] + [spaces (regexp-replace* #rx"#" (car prev) " ")]) + (append (map (λ(x) (~a x x x)) prev) + (map (λ(x) (~a x spaces x)) prev) + (map (λ(x) (~a x x x)) prev))))) +(for-each displayln (carpet 3)) diff --git a/Task/Sierpinski-carpet/UNIX-Shell/sierpinski-carpet.sh b/Task/Sierpinski-carpet/UNIX-Shell/sierpinski-carpet.sh new file mode 100644 index 0000000000..a577b4987c --- /dev/null +++ b/Task/Sierpinski-carpet/UNIX-Shell/sierpinski-carpet.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +next() { + block="$1" + center="$(echo "$1" | tr '#' ' ')" + paste -d '' <(echo "$block") <(echo "$block" ) <(echo "$block") + paste -d '' <(echo "$block") <(echo "$center") <(echo "$block") + paste -d '' <(echo "$block") <(echo "$block" ) <(echo "$block") +} + +carpet="#" +for _ in {1..3} +do + carpet="$(next "$carpet")" +done + +echo "$carpet" diff --git a/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-1.math b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-1.math new file mode 100644 index 0000000000..9fa00fd02f --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-1.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/Mathematica/sierpinski-triangle-graphical-2.math b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-2.math new file mode 100644 index 0000000000..505a7c97b0 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-2.math @@ -0,0 +1,3 @@ +sierpinski[v_, 0] := Polygon@v; +sierpinski[v_, n_] := sierpinski[#, n - 1] & /@ (Mean /@ # & /@ v~Tuples~2~Partition~3); +Graphics@sierpinski[N@{{0, 0}, {1, 0}, {.5, .8}}, 3] diff --git a/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-3.math b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-3.math new file mode 100644 index 0000000000..0c1354322d --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical-3.math @@ -0,0 +1,3 @@ +sierpinski = Map[Mean, Partition[Tuples[#, 2], 3], {2}] &; +p = Nest[Join @@ sierpinski /@ # &, {{{0, 0}, {1, 0}, {.5, .8}}}, 3]; +Graphics[Polygon@p] diff --git a/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical.rkt b/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical.rkt new file mode 100644 index 0000000000..c5c8af8b95 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical.rkt @@ -0,0 +1,12 @@ +#lang racket +(require 2htdp/image) +(define (sierpinski n) + (if (zero? n) + (triangle 2 'solid 'red) + (let ([t (sierpinski (- n 1))]) + (freeze (above t (beside t t)))))) +;; the following will show the graphics if run in DrRacket +(sierpinski 8) +;; or use this to dump the image into a file, shown on the right +(require file/convertible) +(display-to-file (convert (sierpinski 8) 'png-bytes) "sierpinski.png") diff --git a/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d b/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d index d92d68fcdb..0e6cb48876 100644 --- a/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d +++ b/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d @@ -3,10 +3,10 @@ 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(); + foreach (immutable n; 0 .. level) { + immutable sp = " ".replicate(2 ^^ n); + d = d.map!(a => sp ~ a ~ sp).array ~ + d.map!(a => a ~ " " ~ a).array; } - d.join("\n").writeln(); + d.join("\n").writeln; } diff --git a/Task/Sierpinski-triangle/Racket/sierpinski-triangle.rkt b/Task/Sierpinski-triangle/Racket/sierpinski-triangle.rkt new file mode 100644 index 0000000000..8021245c8c --- /dev/null +++ b/Task/Sierpinski-triangle/Racket/sierpinski-triangle.rkt @@ -0,0 +1,9 @@ +#lang racket +(define (sierpinski n) + (if (zero? n) + '("*") + (let ([spaces (make-string (expt 2 (sub1 n)) #\space)] + [prev (sierpinski (sub1 n))]) + (append (map (λ(x) (~a spaces x spaces)) prev) + (map (λ(x) (~a x " " x)) prev))))) +(for-each displayln (sierpinski 5)) diff --git a/Task/Sieve-of-Eratosthenes/COBOL/sieve-of-eratosthenes.cobol b/Task/Sieve-of-Eratosthenes/COBOL/sieve-of-eratosthenes.cobol new file mode 100644 index 0000000000..44b25d8b20 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/COBOL/sieve-of-eratosthenes.cobol @@ -0,0 +1,55 @@ +*> Please ignore the asterisks in the first column of the next comments, +*> which are kludges to get syntax highlighting to work. + IDENTIFICATION DIVISION. + PROGRAM-ID. Sieve-Of-Eratosthenes. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 Max-Number USAGE UNSIGNED-INT. + 01 Max-Prime USAGE UNSIGNED-INT. + + 01 Num-Group. + 03 Num-Table PIC X VALUE "P" + OCCURS 1 TO 10000000 TIMES DEPENDING ON Max-Number + INDEXED BY Num-Index. + 88 Is-Prime VALUE "P" FALSE "N". + + 01 Current-Prime USAGE UNSIGNED-INT. + + 01 I USAGE UNSIGNED-INT. + + PROCEDURE DIVISION. + DISPLAY "Enter the limit: " WITH NO ADVANCING + ACCEPT Max-Number + DIVIDE Max-Number BY 2 GIVING Max-Prime + +* *> Set Is-Prime of all non-prime numbers to false. + SET Is-Prime (1) TO FALSE + PERFORM UNTIL Max-Prime < Current-Prime +* *> Set current-prime to next prime. + ADD 1 TO Current-Prime + PERFORM VARYING Num-Index FROM Current-Prime BY 1 + UNTIL Is-Prime (Num-Index) + END-PERFORM + MOVE Num-Index TO Current-Prime + +* *> Set Is-Prime of all multiples of current-prime to +* *> false, starting from current-prime sqaured. + COMPUTE Num-Index = Current-Prime ** 2 + PERFORM UNTIL Max-Number < Num-Index + SET Is-Prime (Num-Index) TO FALSE + SET Num-Index UP BY Current-Prime + END-PERFORM + END-PERFORM + +* *> Display the prime numbers. + PERFORM VARYING Num-Index FROM 1 BY 1 + UNTIL Max-Number < Num-Index + IF Is-Prime (Num-Index) + DISPLAY Num-Index + END-IF + END-PERFORM + + GOBACK + . diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d index df19a63f30..eaacabf791 100644 --- a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d @@ -5,10 +5,8 @@ struct IsPrime { //__gshared static BitArray multiples = [true, true, false]; __gshared static BitArray multiples; - static this() { - multiples.length = 3; - multiples[0] = true; - multiples[1] = true; + /*nothrow*/ static this() { + multiples.init([true, true, false]); } static bool opCall(in size_t n) /*nothrow*/ { @@ -27,14 +25,15 @@ struct IsPrime { for (size_t j = i * 2; j < newMax + 1; j += i) multiples[j] = true; } + return !multiples[n]; } } -version (eratosthenes3_main) { +version (sieve_of_eratosthenes3_main) { import std.stdio, std.range; + void main() { - // iota(50).filter!IsPrime().writeln(); - iota(50).filter!(i => IsPrime(i))().writeln(); + 50.iota.filter!IsPrime.writeln; } } diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-3.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-3.java index addb96f711..b4c091eba9 100644 --- a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-3.java +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-3.java @@ -6,7 +6,7 @@ public class Sieve{ LinkedList<Integer> primes = new LinkedList<Integer>(); BitSet nonPrimes = new BitSet(n+1); - for (int p = 2; p * p <= n ; p = nonPrimes.nextClearBit(p+1)) { + for (int p = 2; p <= n ; p = nonPrimes.nextClearBit(p+1)) { for (int i = p * p; i <= n; i += p) nonPrimes.set(i); primes.add(p); diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-1.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-1.rkt new file mode 100644 index 0000000000..67d6a46e4d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-1.rkt @@ -0,0 +1,14 @@ +#lang racket + +;; ugly imperative version +(define (sieve n) + (define non-primes '()) + (define primes '()) + (for ([i (in-range 2 (add1 n))]) + (unless (member i non-primes) + (set! primes (cons i primes)) + (for ([j (in-range (* i i) (add1 n) i)]) + (set! non-primes (cons j non-primes))))) + (reverse primes)) + +(sieve 100) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt new file mode 100644 index 0000000000..c53a08158f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt @@ -0,0 +1,14 @@ +#lang racket + +;; a little nicer, but still imperative +(define (sieve n) + (define primes (make-vector (add1 n) #t)) + (for* ([i (in-range 2 (add1 n))] + #:when (vector-ref primes i) + [j (in-range (* i i) (add1 n) i)]) + (vector-set! primes j #f)) + (for/list ([n (in-range 2 (add1 n))] + #:when (vector-ref primes n)) + n)) + +(sieve 100) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt new file mode 100644 index 0000000000..a5f69040cf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt @@ -0,0 +1,11 @@ +#lang lazy + +;; infinite list using lazy racket (see the language above) +(define nats (cons 1 (map add1 nats))) +(define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l)) +(define (sieve l) (cons (first l) (sieve (sift (first l) (rest l))))) +(define primes (sieve (rest nats))) + +(define (take-upto n l) + (if (<= (car l) n) (cons (car l) (take-upto n (cdr l))) '())) +(!! (take-upto 100 primes)) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt new file mode 100644 index 0000000000..43440e46b7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt @@ -0,0 +1,27 @@ +#lang racket + +;; infinite list using threads and channels (similar to newsqueak) +(define-syntax (bg-loop stx) + (syntax-case stx () + [(_ expr ...) + (with-syntax ([out! (datum->syntax stx 'out!)]) + #'(let ([out (make-channel)]) + (define (out! x) (channel-put out x)) + (thread (λ() (let loop () expr ... (loop)))) + out))])) +(define nats (bg-loop (for ([i (in-naturals 1)]) (out! i)))) +(define (filter pred? c) + (bg-loop (define x (channel-get c)) + (when (pred? x) (out! x)))) +(define (sift n c) + (filter (λ(x) (not (zero? (modulo x n)))) c)) +(define (sieve c) + (bg-loop (define x (channel-get c)) + (out! x) + (set! c (sift x c)))) +(define primes (begin (channel-get nats) (sieve nats))) + +(define (take-upto n c) + (let loop () + (let ([x (channel-get c)]) (if (<= x n) (cons x (loop)) '())))) +(take-upto 100 primes) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt new file mode 100644 index 0000000000..00a9f1e242 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt @@ -0,0 +1,18 @@ +#lang racket + +;; yet another variation of the same algorithm, this time using generators +(require racket/generator) + +(define nats (generator () (for ([i (in-naturals 1)]) (yield i)))) +(define (filter pred g) + (generator () (for ([i (in-producer g #f)] #:when (pred i)) (yield i)))) +(define (sift n g) (filter (λ(x) (not (zero? (modulo x n)))) g)) +(define (sieve g) + (generator () + (let loop ([g g]) (let ([x (g)]) (yield x) (loop (sift x g)))))) +(define primes (begin (nats) (sieve nats))) + +(define (take-upto n p) + (let loop () + (let ([x (p)]) (if (<= x n) (cons x (loop)) '())))) +(take-upto 100 primes) 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 index e567093c1d..86cef0e1d5 100644 --- a/Task/Sieve-of-Eratosthenes/Visual-Basic-.NET/sieve-of-eratosthenes.visual +++ b/Task/Sieve-of-Eratosthenes/Visual-Basic-.NET/sieve-of-eratosthenes.visual @@ -2,9 +2,9 @@ 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) +For n = 2 To Math.Sqrt(limit) If flags(n) = 0 Then - For k As Integer = n * n To limit Step n + For k = n * n To limit Step n flags(k) = 1 Next k End If diff --git a/Task/Simple-database/C/simple-database.c b/Task/Simple-database/C/simple-database.c index 0eca6b6697..4d2894e353 100644 --- a/Task/Simple-database/C/simple-database.c +++ b/Task/Simple-database/C/simple-database.c @@ -9,8 +9,8 @@ #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); } +static int by_##foo (const void*p1, const void*p2) { \ + return strcmp ((*(const pdb_t*)p1)->foo, (*(const pdb_t*)p2)->foo); } typedef struct db { char title[26]; char first_name[26]; @@ -20,8 +20,7 @@ typedef struct db { struct db *next; } db_t,*pdb_t; -typedef int (sort)(pdb_t*, pdb_t*); -typedef int (*compfn)(const void*, const void*); +typedef int (sort)(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); @@ -32,7 +31,8 @@ sort_by(title); static sort by_date; /* main */ int main (int argc, char **argv) { - char buf[100], *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; + char buf[100]; + const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; db_t db; db.next=NULL; pdb_t dblist; @@ -153,7 +153,7 @@ static pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) { pdb[i]=in_db; in_db=in_db->next; } - qsort (pdb,i,sizeof in_db,(compfn)sortby); + qsort (pdb,i,sizeof in_db,sortby); pdb[i-1]->next=NULL; for (;i;i--) { pdb[i-1]->next=pdb[i]; diff --git a/Task/Simulate-input-Keyboard/Racket/simulate-input-keyboard.rkt b/Task/Simulate-input-Keyboard/Racket/simulate-input-keyboard.rkt new file mode 100644 index 0000000000..e94f19536a --- /dev/null +++ b/Task/Simulate-input-Keyboard/Racket/simulate-input-keyboard.rkt @@ -0,0 +1,24 @@ +#lang racket/gui + +(define frame (new frame% + (label "Example") + (width 300) + (height 300))) ; Defines an instance of a frame to put the canvas in + +(define simulate-key-canvas% + (class canvas% + (define/public (simulate-key key) + (send this on-char key)) ; Creates a class that inherits from the standard canvas class, that can receive simulated key presses + + (define/override (on-char key) + (displayln (send key get-key-code))) ; Changes the method that receives key presses to show some output + + (super-new))) + +(define canvas + (new simulate-key-canvas% + (parent frame))) ; Defines an instance of the newly created class + +(send frame show #t) ; Shows the frame with a white canvas inside +(send canvas simulate-key (new key-event% (key-code #\k))) ; Sends the simulated key press (with a key-event% instance) +;outputs k diff --git a/Task/Singleton/Cache-ObjectScript/singleton.cos b/Task/Singleton/Cache-ObjectScript/singleton.cos new file mode 100644 index 0000000000..caa14da9fa --- /dev/null +++ b/Task/Singleton/Cache-ObjectScript/singleton.cos @@ -0,0 +1,131 @@ +/// The <CLASS>Singleton</CLASS> class represents a global singleton object that can +/// be instantiated by multiple processes. The 'Get' class method is used to obtain +/// an in-memory object reference and the 'Set' method is used to save any changes to +/// state. See below for an example. +/// +/// <EXAMPLE> +/// Set one=##class(Singleton).Get(,.sc) +/// Set one.GlobalProperty="Some Value" +/// Set sc=one.Set() +/// </EXAMPLE> +/// +/// This class can also be extended. +Class User.Singleton Extends %SerialObject +{ + +Property GlobalProperty As %String; + +/// Refer to <LINK href=/AboutConcurrency.html>About Concurrency</LINK> for more details +/// on the optional <var>pConcurrency</var> argument. +ClassMethod Get(pConcurrency As %Integer = -1, Output pStatus As %Status = {$$$OK}) As Singleton [ Final ] +{ + // check if singleton object already instantiated + Set oRef = "" + For { + Set oRef = $ZObjNext(oRef) If oRef = "" Quit + If oRef.%ClassName(1) = ..%ClassName(1) Quit + } + If $IsObject(oRef) Quit oRef + + // determine what lock needs to be applied + If '$IsValidNum(pConcurrency, 0, -1, 4) { + Set pStatus = $$$ERROR($$$LockTypeInvalid, pConcurrency) + Quit $$$NULLOREF + } + If pConcurrency = -1 Set pConcurrency = $Xecute("Quit "_..#DEFAULTCONCURRENCY) + + // acquire lock for global singleton object + Set lockTO = $ZUtil(115,4), lockOK = 1 + If pConcurrency<4, pConcurrency { + Lock +^CacheTempUser("Singleton", ..%ClassName(1))#"S":lockTO Set lockOK = $Test + } ElseIf pConcurrency = 4 { + Lock +^CacheTempUser("Singleton", ..%ClassName(1)):lockTO Set lockOK = $Test + } + If 'lockOK { + If pConcurrency = 4 { + Set pStatus = $$$ERROR($$$LockFailedToAcquireExclusive, ..%ClassName(1)) + } Else { + Set pStatus = $$$ERROR($$$LockFailedToAcquireRead, ..%ClassName(1)) + } + Quit $$$NULLOREF + } + + // retrieve global singleton object and deserialise + Set oId = $Get(^CacheTempUser("Singleton", ..%ClassName(1))) + Set oRef = ..%Open(oId) //,, .pStatus) + If '$IsObject(oRef) Set pStatus = $$$ERROR($$$GeneralError, "Failed to load singleton object.") + + // release temporary lock + If (pConcurrency = 1) || (pConcurrency = 2) { + Lock -^CacheTempUser("Singleton", ..%ClassName(1))#"S" + } + + // singleton object failed to load + If $$$ISERR(pStatus) { + // release retained lock + If pConcurrency = 3 { + Lock -^CacheTempUser("Singleton", ..%ClassName(1))#"S" + } + If pConcurrency = 4 { + Lock -^CacheTempUser("Singleton", ..%ClassName(1)) + } + Quit $$$NULLOREF + } + + // store concurrency state and return in-memory object reference + Set oRef.Concurrency = pConcurrency + Quit oRef +} + +Method Set() As %Status [ Final ] +{ + // check for version change + Set oId0 = $Get(^CacheTempUser("Singleton", ..%ClassName(1))) + Set oRef0 = ..%Open(oId0) //,, .sc) + If '$IsObject(oRef0) Quit $$$ERROR($$$GeneralError, "Failed to load singleton object.") + If oRef0.Version = ..Version { + Set ..Version = ..Version + 1 + } Else { + Quit $$$ERROR($$$ConcurrencyVersionMismatch, ..%ClassName(1)) + } + + // serialise local singleton object and check status code + Set sc = ..%GetSwizzleObject(,.oId) If $$$ISERR(sc) Quit sc + + // acquire exclusive lock on global singleton object + Set lockTO = $ZUtil(115,4) + Lock +^CacheTempUser("Singleton", ..%ClassName(1)):lockTO + If '$Test Quit $$$ERROR($$$LockFailedToAcquireExclusive, ..%ClassName(1)) + + // update global singleton object and release lock + Set ^CacheTempUser("Singleton", ..%ClassName(1)) = oId + Lock -^CacheTempUser("Singleton", ..%ClassName(1)) + Quit $$$OK +} + +Method %OnNew() As %Status [ Final, Internal ] +{ + // do not allow constructor method to be called + Quit $$$ERROR($$$GeneralError, "Can't instantiate directly.") +} + +Method %OnConstructClone() As %Status [ Final, Internal ] +{ + // do not allow singleton object to be cloned + Quit $$$ERROR($$$GeneralError, "Can't clone instance.") +} + +Method %OnClose() As %Status [ Final, Internal ] +{ + // reference count for singleton object is now zero, so + // release lock on global singleton object, if applicable + If ..Concurrency = 3 Lock -^CacheTempUser("Singleton", ..%ClassName(1))#"S" + If ..Concurrency = 4 Lock -^CacheTempUser("Singleton", ..%ClassName(1)) + Quit $$$OK +} + +Property Concurrency As %Integer [ Final, Private, Transient ]; + +Property Version As %Integer [ Final, Private ]; + +} diff --git a/Task/Singleton/Objective-C/singleton-1.m b/Task/Singleton/Objective-C/singleton-1.m index 28aa2a11ca..8eb0d58041 100644 --- a/Task/Singleton/Objective-C/singleton-1.m +++ b/Task/Singleton/Objective-C/singleton-1.m @@ -4,6 +4,6 @@ // any instance variables } -+ (SomeSingleton*)sharedInstance; ++ (SomeSingleton *)sharedInstance; @end diff --git a/Task/Singleton/Objective-C/singleton-2.m b/Task/Singleton/Objective-C/singleton-2.m index 6c8b8cf99b..6981c6b21a 100644 --- a/Task/Singleton/Objective-C/singleton-2.m +++ b/Task/Singleton/Objective-C/singleton-2.m @@ -1,10 +1,10 @@ // SomeSingleton.m @implementation SomeSingleton -+ (SomeSingleton*) sharedInstance ++ (SomeSingleton *) sharedInstance { - static sharedInstance = nil; - if(!sharedInstance) { + static SomeSingleton *sharedInstance = nil; + if (!sharedInstance) { sharedInstance = [[SomeSingleton alloc] init]; } return sharedInstance; @@ -25,7 +25,7 @@ return UINT_MAX; } -- (void)release +- (oneway void)release { // prevent release } diff --git a/Task/Singleton/Objective-C/singleton-3.m b/Task/Singleton/Objective-C/singleton-3.m new file mode 100644 index 0000000000..d3cbf9a716 --- /dev/null +++ b/Task/Singleton/Objective-C/singleton-3.m @@ -0,0 +1,10 @@ ++ (SomeSingleton *) sharedInstance +{ + static SomeSingleton *sharedInstance = nil; + @synchronized(self) { + if (!sharedInstance) { + sharedInstance = [[SomeSingleton alloc] init]; + } + } + return sharedInstance; +} diff --git a/Task/Singleton/Objective-C/singleton-4.m b/Task/Singleton/Objective-C/singleton-4.m new file mode 100644 index 0000000000..85c27689d6 --- /dev/null +++ b/Task/Singleton/Objective-C/singleton-4.m @@ -0,0 +1,9 @@ ++ (SomeSingleton *) sharedInstance +{ + static SomeSingleton *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[SomeSingleton alloc] init]; + }); + return sharedInstance; +} diff --git a/Task/Singleton/Racket/singleton-1.rkt b/Task/Singleton/Racket/singleton-1.rkt new file mode 100644 index 0000000000..e7d3afa867 --- /dev/null +++ b/Task/Singleton/Racket/singleton-1.rkt @@ -0,0 +1,6 @@ +#lang racket +(provide instance) +(define singleton% + (class object% + (super-new))) +(define instance (new singleton%)) diff --git a/Task/Singleton/Racket/singleton-2.rkt b/Task/Singleton/Racket/singleton-2.rkt new file mode 100644 index 0000000000..cff1549fe0 --- /dev/null +++ b/Task/Singleton/Racket/singleton-2.rkt @@ -0,0 +1,6 @@ +#lang racket +(provide instance) +(define instance + (new (class object% + (define/public (foo) 123) + (super-new)))) diff --git a/Task/Singly-linked-list-Element-definition/Racket/singly-linked-list-element-definition.rkt b/Task/Singly-linked-list-Element-definition/Racket/singly-linked-list-element-definition.rkt new file mode 100644 index 0000000000..17e1a4d99a --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Racket/singly-linked-list-element-definition.rkt @@ -0,0 +1,2 @@ +#lang racket +(mcons 1 (mcons 2 (mcons 3 '()))) ; a mutable list diff --git a/Task/Singly-linked-list-Element-insertion/Racket/singly-linked-list-element-insertion.rkt b/Task/Singly-linked-list-Element-insertion/Racket/singly-linked-list-element-insertion.rkt new file mode 100644 index 0000000000..a6e9144e08 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Racket/singly-linked-list-element-insertion.rkt @@ -0,0 +1,11 @@ +#lang racket + +;; insert b after a in a mutable list (assumes that a is in the input list) +(define (insert-after! list a b) + (if (equal? (mcar list) a) + (set-mcdr! list (mcons b (mcdr list))) + (insert-after! (mcdr list) a b))) + +(define l (mcons 1 (mcons 2 (mcons 3 '())))) +(insert-after! l 2 2.5) +l ; -> (mcons 1 (mcons 2 (mcons 2.5 (mcons 3)))) diff --git a/Task/Singly-linked-list-Traversal/Racket/singly-linked-list-traversal.rkt b/Task/Singly-linked-list-Traversal/Racket/singly-linked-list-traversal.rkt new file mode 100644 index 0000000000..6c4f4b3430 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Racket/singly-linked-list-traversal.rkt @@ -0,0 +1,29 @@ +#lang racket + +(define l (list 1 2 3)) + +;; scan the list and collect a list of function results +(map add1 l) + +;; scan the list and run some function on each element for its side-effect +(for-each displayln l) + +;; scan a list and sum up its elements +(foldl + 0 l) + +;; same as the above three, using a more modern syntax that is often +;; more convenient +(for/list ([x (in-list l)]) (add1 x)) +(for ([x (in-list l)]) (displayln x)) +(for/fold ([sum 0]) ([x (in-list l)]) (+ x sum)) + +;; the same as the first, but make up a vector of results +(for/vector ([x (in-list l)]) (add1 x)) + +;; there is less support for mutable pairs, but it's still extensive +;; enough to cover all the basics +(require racket/mpair) +(define ml (mlist 1 2 3)) +(mmap add1 ml) +(mfor-each displayln ml) +(for ([x (in-mlist ml)]) (displayln x)) diff --git a/Task/Sleep/00DESCRIPTION b/Task/Sleep/00DESCRIPTION index 79f052a965..98c56fff7d 100644 --- a/Task/Sleep/00DESCRIPTION +++ b/Task/Sleep/00DESCRIPTION @@ -4,3 +4,6 @@ Write a program that does the following in this order: * Sleep the main [[thread]] for the given amount of time. * Print "Awake!" * End. + +;Cf.: +* [[Nautical bell]] diff --git a/Task/Sleep/COBOL/sleep-1.cobol b/Task/Sleep/COBOL/sleep-1.cobol new file mode 100644 index 0000000000..99ad3d7e99 --- /dev/null +++ b/Task/Sleep/COBOL/sleep-1.cobol @@ -0,0 +1,18 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Sleep-In-Seconds. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Seconds-To-Sleep USAGE COMP-2. + + PROCEDURE DIVISION. + ACCEPT Seconds-To-Sleep + + DISPLAY "Sleeping..." + + CALL "C$SLEEP" USING BY CONTENT Seconds-To-Sleep + + DISPLAY "Awake!" + + GOBACK + . diff --git a/Task/Sleep/COBOL/sleep-2.cobol b/Task/Sleep/COBOL/sleep-2.cobol new file mode 100644 index 0000000000..022553ea3c --- /dev/null +++ b/Task/Sleep/COBOL/sleep-2.cobol @@ -0,0 +1,23 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Sleep-In-Nanoseconds. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Seconds-To-Sleep USAGE COMP-2. + 01 Nanoseconds-To-Sleep USAGE COMP-2. + 01 Nanoseconds-Per-Second CONSTANT 1000000000. + + PROCEDURE DIVISION. + ACCEPT Seconds-To-Sleep + MULTIPLY Seconds-To-Sleep BY Nanoseconds-Per-Second + GIVING Nanoseconds-To-Sleep + + DISPLAY "Sleeping..." + + CALL "CBL_OC_NANOSLEEP" + USING BY CONTENT Nanoseconds-To-Sleep + + DISPLAY "Awake!" + + GOBACK + . diff --git a/Task/Sleep/Julia/sleep.julia b/Task/Sleep/Julia/sleep.julia new file mode 100644 index 0000000000..4af8c3c700 --- /dev/null +++ b/Task/Sleep/Julia/sleep.julia @@ -0,0 +1,5 @@ +print("Please enter sleep duration in seconds: ") +input = int(readline(STDIN)) +println("Sleeping...") +sleep(input) +println("Awake!") diff --git a/Task/Sockets/Julia/sockets.julia b/Task/Sockets/Julia/sockets.julia new file mode 100644 index 0000000000..8db06e31d7 --- /dev/null +++ b/Task/Sockets/Julia/sockets.julia @@ -0,0 +1,3 @@ +socket = connect("localhost",256) +write(socket, "hello socket world") +close(socket) diff --git a/Task/Sokoban/D/sokoban-1.d b/Task/Sokoban/D/sokoban-1.d index 02a66219e3..63cf2bd9e0 100644 --- a/Task/Sokoban/D/sokoban-1.d +++ b/Task/Sokoban/D/sokoban-1.d @@ -1,7 +1,7 @@ import std.string, std.typecons, std.exception, std.algorithm; -import queue_usage2; // No queue in DMD 2.061 Phobos. +import queue_usage2; // No queue in Phobos 2.063. -immutable struct Board { +const struct Board { private enum El : char { floor=' ', wall='#', goal='.', box='$', player='@', boxOnGoal='*' } private alias string CTable; @@ -9,7 +9,7 @@ immutable struct Board { private immutable CTable sData, dData; private immutable int playerx, playery; - this(in string[] board) pure nothrow + this(in string[] board) pure nothrow const in { foreach (row; board) { assert(row.length == board[0].length, @@ -36,34 +36,34 @@ immutable struct Board { 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) + 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 + 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 + data2[(y + dy) * ncols + x + dx] = El.player; + data = data2.assumeUnique; // 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) + 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 + 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 + data2[(y + dy) * ncols + x + dx] = El.player; + data2[(y + 2*dy) * ncols + x + 2*dx] = El.boxOnGoal; + data = data2.assumeUnique; // Not enforced. return true; } private bool isSolved(in CTable data) const pure nothrow { - foreach (i, d; data) + foreach (immutable i, immutable d; data) if ((sData[i] == El.goal) != (d == El.boxOnGoal)) return false; return true; @@ -82,8 +82,8 @@ immutable struct Board { tuple(-1, 0, 'l', 'L')]; while (open.length) { - //immutable (cur, cSol, x, y) = open.pop(); - immutable item = open.pop(); + //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]; @@ -95,7 +95,7 @@ immutable struct Board { immutable int dx = di[0]; immutable int dy = di[1]; - if (temp[(y+dy) * ncols + x+dx] == El.boxOnGoal) { + 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]; @@ -118,7 +118,8 @@ immutable struct Board { void main() { import std.stdio, core.memory; - GC.disable(); // Uses about twice the memory + GC.disable; // Uses about twice the memory + immutable level = "####### # # @@ -129,6 +130,6 @@ void main() { #.# @# #######"; - immutable b = Board(level.splitLines()); - writeln(level, "\n\n", b.solve()); + const b = const(Board)(level.splitLines); + writeln(level, "\n\n", b.solve); } diff --git a/Task/Solve-a-Hidato-puzzle/Bracmat/solve-a-hidato-puzzle.bracmat b/Task/Solve-a-Hidato-puzzle/Bracmat/solve-a-hidato-puzzle.bracmat new file mode 100644 index 0000000000..1aa7c684ac --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Bracmat/solve-a-hidato-puzzle.bracmat @@ -0,0 +1,113 @@ +( + ( hidato + = Line solve lowest Ncells row column rpad + , Board colWidth maxDigits start curCol curRow + , range head line cellN solution output tail + . out$!arg + & @(!arg:? ((%@:>" ") ?:?arg)) + & 0:?row:?column + & :?Board + & ( Line + = token + . whl + ' ( @(!arg:?token [3 ?arg) + & ( ( @(!token:? "_" ?) + & :?token + | @(!token:? #?token (|" " ?)) + ) + & (!token.!row.!column) !Board:?Board + | + ) + & 1+!column:?column + ) + ) + & whl + ' ( @(!arg:?line \n ?arg) + & Line$!line + & 1+!row:?row + & 0:?column + ) + & Line$!arg + & ( range + = hi lo + . (!arg+1:?hi)+-2:?lo + & '($lo|$arg|$hi) + ) + & ( solve + = ToDo cellN row column head tail remainder + , candCell Solved rowCand colCand pattern recurse + . !arg:(?ToDo.?cellN.?row.?column) + & range$!row:(=?row) + & range$!column:(=?column) + & + ' ( ?head ($cellN.?rowCand.?colCand) ?tail + & (!rowCand.!colCand):($row.$column) + & !recurse + | ?head + (.($row.$column):(?rowCand.?colCand)) + (?tail&!recurse) + . ((!rowCand.!colCand).$cellN) + : ?candCell + & ( !head !tail: + & out$found! + & !candCell + | solve + $ ( !head !tail + . $cellN+1 + . !rowCand + . !colCand + ) + : ?remainder + & !candCell+!remainder + ) + : ?Solved + ) + : (=?pattern.?recurse) + & !ToDo:!pattern + & !Solved + ) + & infinity:?lowest + & ( !Board + : ? (<!lowest:#%?lowest.?start) (?&~) + | solve$(!Board.!lowest.!start):?solution + ) + & :?output + & 0:?curCol + & !solution:((?curRow.?).?)+?+[?Ncells + & @(!Ncells:? [?maxDigits) + & 1+!maxDigits:?colWidth + & ( rpad + = len + . !arg:(?arg.?len) + & @(str$(!arg " "):?arg [!len ?) + & !arg + ) + & whl + ' ( !solution:((?row.?column).?cellN)+?solution + & ( !row:>!curRow:?curRow + & !output \n:?output + & 0:?curCol + | + ) + & whl + ' ( !curCol+1:~>!column:?curCol + & !output rpad$(.!colWidth):?output + ) + & !output rev$(rpad$(rev$(str$(!cellN " ")).!colWidth)) + : ?output + & !curCol+1:?curCol + ) + & str$!output + ) +& " + __ 33 35 __ __ + __ __ 24 22 __ + __ __ __ 21 __ __ + __ 26 __ 13 40 11 + 27 __ __ __ 9 __ 1 + __ __ 18 __ __ + __ 7 __ __ + 5 __" + : ?board +& out$(hidato$!board) +); diff --git a/Task/Solve-a-Hidato-puzzle/C++/solve-a-hidato-puzzle.cpp b/Task/Solve-a-Hidato-puzzle/C++/solve-a-hidato-puzzle.cpp new file mode 100644 index 0000000000..9342315495 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/C++/solve-a-hidato-puzzle.cpp @@ -0,0 +1,152 @@ +#include <iostream> +#include <sstream> +#include <iterator> +#include <vector> + +//------------------------------------------------------------------------------ +using namespace std; + +//------------------------------------------------------------------------------ +struct node +{ + int val; + unsigned char neighbors; +}; +//------------------------------------------------------------------------------ +class hSolver +{ +public: + hSolver() + { + dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; + dy[0] = -1; dy[1] = -1; dy[2] = -1; dy[3] = 0; dy[4] = 0; dy[5] = 1; dy[6] = 1; dy[7] = 1; + } + + void solve( vector<string>& puzz, int max_wid ) + { + if( puzz.size() < 1 ) return; + wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; + int len = wid * hei, c = 0; max = 0; + arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); + weHave = new bool[len + 1]; memset( weHave, 0, len + 1 ); + + for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "*" ) { arr[c++].val = -1; continue; } + arr[c].val = atoi( ( *i ).c_str() ); + if( arr[c].val > 0 ) weHave[arr[c].val] = true; + if( max < arr[c].val ) max = arr[c].val; + c++; + } + + solveIt(); c = 0; + for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) == "." ) + { + ostringstream o; o << arr[c].val; + ( *i ) = o.str(); + } + c++; + } + delete [] arr; + delete [] weHave; + } + +private: + bool search( int x, int y, int w ) + { + if( w == max ) return true; + + node* n = &arr[x + y * wid]; + n->neighbors = getNeighbors( x, y ); + if( weHave[w] ) + { + for( int d = 0; d < 8; d++ ) + { + if( n->neighbors & ( 1 << d ) ) + { + int a = x + dx[d], b = y + dy[d]; + if( arr[a + b * wid].val == w ) + if( search( a, b, w + 1 ) ) return true; + } + } + return false; + } + + for( int d = 0; d < 8; d++ ) + { + if( n->neighbors & ( 1 << d ) ) + { + int a = x + dx[d], b = y + dy[d]; + if( arr[a + b * wid].val == 0 ) + { + arr[a + b * wid].val = w; + if( search( a, b, w + 1 ) ) return true; + arr[a + b * wid].val = 0; + } + } + } + return false; + } + + unsigned char getNeighbors( int x, int y ) + { + unsigned char c = 0; int m = -1, a, b; + for( int yy = -1; yy < 2; yy++ ) + for( int xx = -1; xx < 2; xx++ ) + { + if( !yy && !xx ) continue; + m++; a = x + xx, b = y + yy; + if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; + if( arr[a + b * wid].val > -1 ) c |= ( 1 << m ); + } + return c; + } + + void solveIt() + { + int x, y; findStart( x, y ); + if( x < 0 ) { cout << "\nCan't find start point!\n"; return; } + search( x, y, 2 ); + } + + void findStart( int& x, int& y ) + { + for( int b = 0; b < hei; b++ ) + for( int a = 0; a < wid; a++ ) + if( arr[a + wid * b].val == 1 ) { x = a; y = b; return; } + x = y = -1; + } + + int wid, hei, max, dx[8], dy[8]; + node* arr; + bool* weHave; +}; +//------------------------------------------------------------------------------ +int main( int argc, char* argv[] ) +{ + int wid; + string p = ". 33 35 . . * * * . . 24 22 . * * * . . . 21 . . * * . 26 . 13 40 11 * * 27 . . . 9 . 1 * * * . . 18 . . * * * * * . 7 . . * * * * * * 5 ."; wid = 8; + //string p = "54 . 60 59 . 67 . 69 . . 55 . . 63 65 . 72 71 51 50 56 62 . * * * * . . . 14 * * 17 . * 48 10 11 * 15 . 18 . 22 . 46 . * 3 . 19 23 . . 44 . 5 . 1 33 32 . . 43 7 . 36 . 27 . 31 42 . . 38 . 35 28 . 30"; wid = 9; + //string p = ". 58 . 60 . . 63 66 . 57 55 59 53 49 . 65 . 68 . 8 . . 50 . 46 45 . 10 6 . * * * . 43 70 . 11 12 * * * 72 71 . . 14 . * * * 30 39 . 15 3 17 . 28 29 . . 40 . . 19 22 . . 37 36 . 1 20 . 24 . 26 . 34 33"; wid = 9; + + istringstream iss( p ); vector<string> puzz; + copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); + hSolver s; s.solve( puzz, wid ); + + int c = 0; + for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) + { + if( ( *i ) != "*" && ( *i ) != "." ) + { + if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; + cout << ( *i ) << " "; + } + else cout << " "; + if( ++c >= wid ) { cout << endl; c = 0; } + } + cout << endl << endl; + return system( "pause" ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Sort-an-array-of-composite-structures/Racket/sort-an-array-of-composite-structures.rkt b/Task/Sort-an-array-of-composite-structures/Racket/sort-an-array-of-composite-structures.rkt new file mode 100644 index 0000000000..3539eab4d2 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Racket/sort-an-array-of-composite-structures.rkt @@ -0,0 +1,10 @@ +#lang racket + +(define data '([Joe 5531] [Adam 2341] [Bernie 122] [Walter 1234] [David 19])) + +(sort data < #:key cadr) +;; --> '((David 19) (Bernie 122) (Walter 1234) (Adam 2341) (Joe 5531)) + +;; Demonstrating a "key" that is not just a direct element +(sort data string<? #:key (compose1 symbol->string car)) +;; --> '((Adam 2341) (Bernie 122) (David 19) (Joe 5531) (Walter 1234)) diff --git a/Task/Sort-an-integer-array/DWScript/sort-an-integer-array.dw b/Task/Sort-an-integer-array/DWScript/sort-an-integer-array.dw new file mode 100644 index 0000000000..3062d9e9e8 --- /dev/null +++ b/Task/Sort-an-integer-array/DWScript/sort-an-integer-array.dw @@ -0,0 +1,3 @@ +var a : array of Integer := [5, 4, 3, 2, 1]; +a.Sort; // ascending natural sort +PrintLn(a.Map(IntToStr).Join(',')); // 1,2,3,4,5 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 index 8621a1cd42..b875986e7f 100644 --- a/Task/Sort-an-integer-array/Delphi/sort-an-integer-array.delphi +++ b/Task/Sort-an-integer-array/Delphi/sort-an-integer-array.delphi @@ -5,3 +5,4 @@ var begin a := TIntegerDynArray.Create(5, 4, 3, 2, 1); TArray.Sort<Integer>(a); +end; diff --git a/Task/Sort-an-integer-array/Racket/sort-an-integer-array.rkt b/Task/Sort-an-integer-array/Racket/sort-an-integer-array.rkt new file mode 100644 index 0000000000..d83be94b5e --- /dev/null +++ b/Task/Sort-an-integer-array/Racket/sort-an-integer-array.rkt @@ -0,0 +1,2 @@ +-> (sort '(1 9 2 8 3 7 4 6 5) <) +'(1 2 3 4 5 6 7 8 9) diff --git a/Task/Sort-disjoint-sublist/Racket/sort-disjoint-sublist.rkt b/Task/Sort-disjoint-sublist/Racket/sort-disjoint-sublist.rkt new file mode 100644 index 0000000000..3f17cf4245 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Racket/sort-disjoint-sublist.rkt @@ -0,0 +1,12 @@ +#lang racket + +(define (sort-disjoint l is) + (define xs + (sort (for/list ([x l] [i (in-naturals)] #:when (memq i is)) x) <)) + (let loop ([l l] [i 0] [xs xs]) + (cond [(null? l) l] + [(memq i is) (cons (car xs) (loop (cdr l) (add1 i) (cdr xs)))] + [else (cons (car l) (loop (cdr l) (add1 i) xs))]))) + +(sort-disjoint '(7 6 5 4 3 2 1 0) '(6 1 7)) +;; --> '(7 0 5 4 3 2 1 6) diff --git a/Task/Sort-stability/Racket/sort-stability.rkt b/Task/Sort-stability/Racket/sort-stability.rkt new file mode 100644 index 0000000000..af26d51bce --- /dev/null +++ b/Task/Sort-stability/Racket/sort-stability.rkt @@ -0,0 +1,17 @@ +#lang racket + +(sort '(("UK" "London") + ("US" "New York") + ("US" "Birmingham") + ("UK" "Birmingham")) + string<? #:key first) +;; -> (("UK" "London") ("UK" "Birmingham") +;; ("US" "New York") ("US" "Birmingham")) + +(sort '(("UK" "London") + ("US" "New York") + ("US" "Birmingham") + ("UK" "Birmingham")) + string<? #:key second) +;; -> '(("US" "Birmingham") ("UK" "Birmingham") +;; ("UK" "London") ("US" "New York")) 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 index 6e90221c97..f662e53afc 100644 --- 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 @@ -1,7 +1,8 @@ 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); + "here are Some sample strings to be sorted" + .split + .schwartzSort!q{ tuple(-a.length, a.toUpper) } + .writeln; } diff --git a/Task/Sort-using-a-custom-comparator/Racket/sort-using-a-custom-comparator.rkt b/Task/Sort-using-a-custom-comparator/Racket/sort-using-a-custom-comparator.rkt new file mode 100644 index 0000000000..91c99cd6fb --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Racket/sort-using-a-custom-comparator.rkt @@ -0,0 +1,15 @@ +#lang racket + +;; Using a combination of the two comparisons +(define (sort1 words) + (sort words (λ(x y) + (define xl (string-length x)) (define yl (string-length y)) + (or (> xl yl) (and (= xl yl) (string-ci<? x y)))))) +(sort1 '("Some" "pile" "of" "words")) +;; -> '("words" "pile" "Some" "of") + +;; Doing two sorts, relying on `sort's stability +(define (sort2 words) + (sort (sort words string-ci<?) > #:key string-length)) +(sort2 '("Some" "pile" "of" "words")) +;; -> '("words" "pile" "Some" "of") diff --git a/Task/Sorting-algorithms-Bead-sort/Java/sorting-algorithms-bead-sort.java b/Task/Sorting-algorithms-Bead-sort/Java/sorting-algorithms-bead-sort.java new file mode 100644 index 0000000000..a983021485 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Java/sorting-algorithms-bead-sort.java @@ -0,0 +1,80 @@ +public class BeadSort +{ + public static void main(String[] args) + { + BeadSort now=new BeadSort(); + int[] arr=new int[(int)(Math.random()*11)+5]; + for(int i=0;i<arr.length;i++) + arr[i]=(int)(Math.random()*10); + System.out.print("Unsorted: "); + now.display1D(arr); + + int[] sort=now.beadSort(arr); + System.out.print("Sorted: "); + now.display1D(sort); + } + int[] beadSort(int[] arr) + { + int max=0; + for(int i=0;i<arr.length;i++) + if(arr[i]>max) + max=arr[i]; + + //Set up abacus + char[][] grid=new char[arr.length][max]; + int[] levelcount=new int[max]; + for(int i=0;i<max;i++) + { + levelcount[i]=0; + for(int j=0;j<arr.length;j++) + grid[j][i]='_'; + } + /* + display1D(arr); + display1D(levelcount); + display2D(grid); + */ + + //Drop the beads + for(int i=0;i<arr.length;i++) + { + int num=arr[i]; + for(int j=0;num>0;j++) + { + grid[levelcount[j]++][j]='*'; + num--; + } + } + System.out.println(); + display2D(grid); + //Count the beads + int[] sorted=new int[arr.length]; + for(int i=0;i<arr.length;i++) + { + int putt=0; + for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++) + putt++; + sorted[i]=putt; + } + + return sorted; + } + void display1D(int[] arr) + { + for(int i=0;i<arr.length;i++) + System.out.print(arr[i]+" "); + System.out.println(); + } + void display1D(char[] arr) + { + for(int i=0;i<arr.length;i++) + System.out.print(arr[i]+" "); + System.out.println(); + } + void display2D(char[][] arr) + { + for(int i=0;i<arr.length;i++) + display1D(arr[i]); + System.out.println(); + } +} diff --git a/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort-1.java b/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort-1.java new file mode 100644 index 0000000000..b11c1a332f --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort-1.java @@ -0,0 +1,54 @@ +public class BogoSort +{ + public static void main(String[] args) + { + //Enter array to be sorted here + int[] arr={4,5,6,0,7,8,9,1,2,3}; + + BogoSort now=new BogoSort(); + System.out.print("Unsorted: "); + now.display1D(arr); + + now.bogo(arr); + + System.out.print("Sorted: "); + now.display1D(arr); + } + void bogo(int[] arr) + { + //Keep a track of the number of shuffles + int shuffle=1; + for(;!isSorted(arr);shuffle++) + shuffle(arr); + //Boast + System.out.println("This took "+shuffle+" shuffles."); + } + void shuffle(int[] arr) + { + //Standard Fisher-Yates shuffle algorithm + int i=arr.length-1; + while(i>0) + swap(arr,i--,(int)(Math.random()*i)); + } + void swap(int[] arr,int i,int j) + { + int temp=arr[i]; + arr[i]=arr[j]; + arr[j]=temp; + } + boolean isSorted(int[] arr) + { + + for(int i=1;i<arr.length;i++) + if(arr[i]<arr[i-1]) + return false; + return true; + } + void display1D(int[] arr) + { + for(int i=0;i<arr.length;i++) + System.out.print(arr[i]+" "); + System.out.println(); + } + +} diff --git a/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort-2.java b/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort-2.java new file mode 100644 index 0000000000..15e0f2f869 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort-2.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-Bubble-sort/Erlang/sorting-algorithms-bubble-sort.erl b/Task/Sorting-algorithms-Bubble-sort/Erlang/sorting-algorithms-bubble-sort.erl new file mode 100644 index 0000000000..19a13839d6 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Erlang/sorting-algorithms-bubble-sort.erl @@ -0,0 +1,16 @@ +-module( bubble_sort ). + +-export( [list/1, task/0] ). + +list( To_be_sorted ) -> sort( To_be_sorted, [], true ). + +task() -> + List = "asdqwe123", + Sorted = list( List ), + io:fwrite( "List ~p is sorted ~p~n", [List, Sorted] ). + + +sort( [], Acc, true ) -> lists:reverse( Acc ); +sort( [], Acc, false ) -> sort( lists:reverse(Acc), [], true ); +sort( [X, Y | T], Acc, _Done ) when X > Y -> sort( [X | T], [Y | Acc], false ); +sort( [X | T], Acc, Done ) -> sort( T, [X | Acc], Done ). diff --git a/Task/Sorting-algorithms-Bubble-sort/Fish/sorting-algorithms-bubble-sort.fish b/Task/Sorting-algorithms-Bubble-sort/Fish/sorting-algorithms-bubble-sort.fish new file mode 100644 index 0000000000..a1cd9208d5 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Fish/sorting-algorithms-bubble-sort.fish @@ -0,0 +1,8 @@ +v Sorts the (pre-loaded) stack + with bubblesort. +v < +\l0=?;l& +>&:1=?v1-&2[$:{:{](?${ + >~{ao ^ + >~}l &{ v +o","{n:&-1^?=0:&< diff --git a/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort.pro b/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort.pro new file mode 100644 index 0000000000..cc3e276ebe --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort.pro @@ -0,0 +1,20 @@ +%___________________________________________________________________________ +% Bubble sort + +bubble(0, Res, Res, sorted). +bubble(Len, [A,B|T], Res, unsorted) :- A > B, !, bubble(Len,[B,A|T], Res, _). +bubble(Len, [A|T], [A|Ts], Ch) :- L is Len-1, bubble(L, T, Ts, Ch). + +bubblesort(In, Out) :- length(In, Len), bubblesort(Len, In, Out). +bubblesort(0, In, In). +bubblesort(Len, In, Out) :- + bubble(Len, In, Bubbled, SortFlag), % bubble the list + (SortFlag=sorted -> Out=Bubbled; % list is already sorted + SegLen is Len - 1, % one fewer to process + writef('bubbled=%w\n', [Bubbled]), % show progress + bubblesort(SegLen, Bubbled, Out)). + +test :- In = [8,9,1,3,4,2,6,5,4], + writef(' input=%w\n', [In]), + bubblesort(In, R), + writef('-> %w\n', [R]). diff --git a/Task/Sorting-algorithms-Bubble-sort/Racket/sorting-algorithms-bubble-sort-1.rkt b/Task/Sorting-algorithms-Bubble-sort/Racket/sorting-algorithms-bubble-sort-1.rkt new file mode 100644 index 0000000000..fb56ccc813 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Racket/sorting-algorithms-bubble-sort-1.rkt @@ -0,0 +1,16 @@ +#lang racket + +(define (bubble-sort <? v) + (define len (vector-length v)) + (define ref vector-ref) + (let loop ([max len] + [again? #f]) + (for ([i (in-range 0 (- max 1))] + [j (in-range 1 max)]) + (define vi (ref v i)) + (when (<? (ref v j) vi) + (vector-set! v i (ref v j)) + (vector-set! v j vi) + (set! again? #t))) + (when again? (loop (- max 1) #f))) + v) diff --git a/Task/Sorting-algorithms-Bubble-sort/Racket/sorting-algorithms-bubble-sort-2.rkt b/Task/Sorting-algorithms-Bubble-sort/Racket/sorting-algorithms-bubble-sort-2.rkt new file mode 100644 index 0000000000..bab1412f3a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Racket/sorting-algorithms-bubble-sort-2.rkt @@ -0,0 +1 @@ +(bubble-sort < (for/vector ([_ 10]) (random 20))) diff --git a/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort.cpp b/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort.cpp new file mode 100644 index 0000000000..de45c091a3 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort.cpp @@ -0,0 +1,85 @@ +#include <iostream> +#include <windows.h> + +//-------------------------------------------------------------------------------------------------- +const int EL_COUNT = 77, LLEN = 11; + +//-------------------------------------------------------------------------------------------------- +class cocktailSort +{ +public: + void sort( int* arr, int len ) + { + bool notSorted = true; + while( notSorted ) + { + notSorted = false; + for( int a = 0; a < len - 1; a++ ) + { + if( arr[a] > arr[a + 1] ) + { + sSwap( arr[a], arr[a + 1] ); + notSorted = true; + } + } + + if( !notSorted ) break; + notSorted = false; + + for( int a = len - 1; a > 0; a-- ) + { + if( arr[a - 1] > arr[a] ) + { + sSwap( arr[a], arr[a - 1] ); + notSorted = true; + } + } + } + } + +private: + void sSwap( int& a, int& b ) + { + int t = a; + a = b; b = t; + } +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + srand( GetTickCount() ); + cocktailSort cs; + int arr[EL_COUNT]; + + for( int x = 0; x < EL_COUNT; x++ ) + arr[x] = rand() % EL_COUNT + 1; + + std::cout << "Original: " << std::endl << "==========" << std::endl; + for( int x = 0; x < EL_COUNT; x += LLEN ) + { + for( int s = x; s < x + LLEN; s++ ) + std::cout << arr[s] << ", "; + + std::cout << std::endl; + } + + //DWORD now = GetTickCount(); + cs.sort( arr, EL_COUNT ); + //now = GetTickCount() - now; + + std::cout << std::endl << std::endl << "Sorted: " << std::endl << "========" << std::endl; + for( int x = 0; x < EL_COUNT; x += LLEN ) + { + for( int s = x; s < x + LLEN; s++ ) + std::cout << arr[s] << ", "; + + std::cout << std::endl; + } + + std::cout << std::endl << std::endl << std::endl << std::endl; + //std::cout << now << std::endl << std::endl; + system( "pause" ); + + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Sorting-algorithms-Cocktail-sort/Prolog/sorting-algorithms-cocktail-sort.pro b/Task/Sorting-algorithms-Cocktail-sort/Prolog/sorting-algorithms-cocktail-sort.pro new file mode 100644 index 0000000000..021a9ecadc --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Prolog/sorting-algorithms-cocktail-sort.pro @@ -0,0 +1,18 @@ +ctail(_, [], Rev, Rev, sorted) :- write(Rev), nl. +ctail(fwrd, [A,B|T], In, Rev, unsorted) :- A > B, !, + ctail(fwrd, [B,A|T], In, Rev, _). +ctail(bkwd, [A,B|T], In, Rev, unsorted) :- A < B, !, + ctail(bkwd, [B,A|T], In, Rev, _). +ctail(D,[A|T], In, Rev, Ch) :- !, ctail(D, T, [A|In], Rev, Ch). + +cocktail([], []). +cocktail(In, [Min|Out]) :- + ctail(fwrd, In, [], [Max|Rev], SFlag), + ( SFlag=sorted->reverse([Max|Rev], [Min|Out]); + (ctail(bkwd, Rev, [Max], [Min|Tmp], SortFlag), + (SortFlag=sorted->Out=Tmp; !, cocktail(Tmp, Out)))). + +test :- In = [8,9,1,3,4,2,6,5,4], + writef(' input=%w\n', [In]), + cocktail(In, R), + writef('-> %w\n', [R]). diff --git a/Task/Sorting-algorithms-Cocktail-sort/Racket/sorting-algorithms-cocktail-sort.rkt b/Task/Sorting-algorithms-Cocktail-sort/Racket/sorting-algorithms-cocktail-sort.rkt new file mode 100644 index 0000000000..bc9e62e69a --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Racket/sorting-algorithms-cocktail-sort.rkt @@ -0,0 +1,16 @@ +#lang racket +(require (only-in srfi/43 vector-swap!)) + +(define (cocktail-sort! xs) + (define (ref i) (vector-ref xs i)) + (define (swap i j) (vector-swap! xs i j)) + (define len (vector-length xs)) + (define (bubble from to delta) + (for/fold ([swaps 0]) ([i (in-range from to delta)]) + (cond [(> (ref i) (ref (+ i 1))) + (swap i (+ i 1)) (+ swaps 1)] + [swaps]))) + (let loop () + (cond [(zero? (bubble 0 (- len 2) 1)) xs] + [(zero? (bubble (- len 2) 0 -1)) xs] + [(loop)]))) diff --git a/Task/Sorting-algorithms-Comb-sort/Racket/sorting-algorithms-comb-sort.rkt b/Task/Sorting-algorithms-Comb-sort/Racket/sorting-algorithms-comb-sort.rkt new file mode 100644 index 0000000000..93a3b48e92 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Racket/sorting-algorithms-comb-sort.rkt @@ -0,0 +1,18 @@ +#lang racket +(require (only-in srfi/43 vector-swap!)) + +(define (comb-sort xs) + (define (ref i) (vector-ref xs i)) + (define (swap i j) (vector-swap! xs i j)) + (define (new gap) (max 1 (exact-floor (/ gap 1.25)))) + (define size (vector-length xs)) + (let loop ([gap size] [swaps 0]) + (unless (and (= gap 1) (= swaps 0)) + (loop (new gap) + (for/fold ([swaps 0]) ([i (in-range 0 (- size gap))]) + (cond + [(> (ref i) (ref (+ i gap))) + (swap i (+ i gap)) + (+ swaps 1)] + [swaps]))))) + xs) diff --git a/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort.cpp b/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort.cpp new file mode 100644 index 0000000000..5a0d12cb93 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort.cpp @@ -0,0 +1,64 @@ +#include <iostream> +#include <time.h> + +//------------------------------------------------------------------------------ +using namespace std; + +//------------------------------------------------------------------------------ +const int MAX = 30; + +//------------------------------------------------------------------------------ +class cSort +{ +public: + void sort( int* arr, int len ) + { + int mi, mx, z = 0; findMinMax( arr, len, mi, mx ); + int nlen = ( mx - mi ) + 1; int* temp = new int[nlen]; + memset( temp, 0, nlen * sizeof( int ) ); + + for( int i = 0; i < len; i++ ) temp[arr[i] - mi]++; + + for( int i = mi; i <= mx; i++ ) + { + while( temp[i - mi] ) + { + arr[z++] = i; + temp[i - mi]--; + } + } + + delete [] temp; + } + +private: + void findMinMax( int* arr, int len, int& mi, int& mx ) + { + mi = INT_MAX; mx = 0; + for( int i = 0; i < len; i++ ) + { + if( arr[i] > mx ) mx = arr[i]; + if( arr[i] < mi ) mi = arr[i]; + } + } +}; +//------------------------------------------------------------------------------ +int main( int argc, char* argv[] ) +{ + srand( time( NULL ) ); int arr[MAX]; + for( int i = 0; i < MAX; i++ ) + arr[i] = rand() % 140 - rand() % 40 + 1; + + for( int i = 0; i < MAX; i++ ) + cout << arr[i] << ", "; + cout << endl << endl; + + cSort s; s.sort( arr, MAX ); + + for( int i = 0; i < MAX; i++ ) + cout << arr[i] << ", "; + cout << endl << endl; + + return system( "pause" ); +} +//------------------------------------------------------------------------------ diff --git a/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort-1.netrexx b/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort-1.netrexx new file mode 100644 index 0000000000..9765394601 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort-1.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/NetRexx/sorting-algorithms-counting-sort-2.netrexx b/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort-2.netrexx new file mode 100644 index 0000000000..d082c4024b --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort-2.netrexx @@ -0,0 +1,50 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method countingSort(icounts) public constant + + parse getMinMax(icounts) amin amax + array = 0 + loop ix = 1 to icounts.words + iw = icounts.word(ix) + 0 + array[iw] = array[iw] + 1 + end ix + ocounts = '' + loop ix = amin to amax + if array[ix] = 0 then iterate ix + loop for array[ix] + ocounts = ocounts ix + end + end ix + return ocounts.space + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getMinMax(icounts) public constant + + amin = Long.MAX_VALUE + amax = Long.MIN_VALUE + loop x_ = 1 to icounts.words + amin = icounts.word(x_).min(amin) + amax = icounts.word(x_).max(amax) + end x_ + + return amin amax + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static +parse arg icounts +if icounts = '' then - + icounts = - + ' 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' - + '0 -200 -6 -10 -0' - + '' + +say icounts.space +say countingSort(icounts) + +return diff --git a/Task/Sorting-algorithms-Counting-sort/Racket/sorting-algorithms-counting-sort-1.rkt b/Task/Sorting-algorithms-Counting-sort/Racket/sorting-algorithms-counting-sort-1.rkt new file mode 100644 index 0000000000..b2e538d927 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Racket/sorting-algorithms-counting-sort-1.rkt @@ -0,0 +1,12 @@ +#lang racket + +(define (counting-sort xs min max) + (define ns (make-vector (+ max (- min) 1) 0)) + (for ([x xs]) (vector-set! ns (- x min) (+ (vector-ref ns (- x min)) 1))) + (for/fold ([i 0]) ([n ns] [x (in-naturals)]) + (for ([j (in-range i (+ i n ))]) + (vector-set! xs j (+ x min))) + (+ i n)) + xs) + +(counting-sort (vector 0 9 3 8 1 -1 1 2 3 7 4) -1 10) diff --git a/Task/Sorting-algorithms-Counting-sort/Racket/sorting-algorithms-counting-sort-2.rkt b/Task/Sorting-algorithms-Counting-sort/Racket/sorting-algorithms-counting-sort-2.rkt new file mode 100644 index 0000000000..8ba6039805 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Racket/sorting-algorithms-counting-sort-2.rkt @@ -0,0 +1 @@ +'#(-1 0 1 1 2 3 3 4 7 8 9) 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 index 63fa198f38..93a4a63f84 100644 --- a/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb +++ b/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb @@ -1,10 +1,10 @@ class Array - def countingsort! - do_countingsort!(min, max) + def counting_sort + dup.counting_sort! end - protected - def do_countingsort!(min, max) + def counting_sort! + min, max = minmax count = Array.new(max - min + 1, 0) each {|number| count[number - min] += 1} z = 0 @@ -20,5 +20,6 @@ class Array 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(",") +p ary.counting_sort.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-Gnome-sort/Racket/sorting-algorithms-gnome-sort.rkt b/Task/Sorting-algorithms-Gnome-sort/Racket/sorting-algorithms-gnome-sort.rkt new file mode 100644 index 0000000000..073713a12c --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Racket/sorting-algorithms-gnome-sort.rkt @@ -0,0 +1,34 @@ +#lang racket + +;; Translation of the pseudo code +(define (gnome-sort1 a <=?) + (define size (vector-length a)) + (define (swap i j) + (define t (vector-ref a i)) + (vector-set! a i (vector-ref a j)) + (vector-set! a j t)) + (let loop ([i 1] [j 2]) + (when (< i size) + (if (<=? (vector-ref a (sub1 i)) (vector-ref a i)) + (loop j (add1 j)) + (begin (swap (sub1 i) i) + (let ([i (sub1 i)]) + (if (zero? i) + (loop j (add1 j)) + (loop i j))))))) + a) +(gnome-sort1 (vector 3 2 1 4 5 6) <=) + +;; a functional version, roughly like the Scheme entry +(define (gnome-sort2 l <=?) + (match l + [(list) l] + [(list x xs ...) + (let loop ([x `((,x) . ,xs)]) + (match x + [`(,ps) ps] + [`((,p . ,ps) ,n . ,ns) + (loop (cond [(<=? n p) `((,n ,p . ,ps) . ,ns)] + [(null? ps) `((,n) ,p . ,ns)] + [else `(,ps ,n ,p . ,ns)]))]))])) +(gnome-sort2 '(3 2 1 4 5 6) <=) diff --git a/Task/Sorting-algorithms-Heapsort/Racket/sorting-algorithms-heapsort.rkt b/Task/Sorting-algorithms-Heapsort/Racket/sorting-algorithms-heapsort.rkt new file mode 100644 index 0000000000..138ab4f6d2 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Racket/sorting-algorithms-heapsort.rkt @@ -0,0 +1,26 @@ +#lang racket +(require (only-in srfi/43 vector-swap!)) + +(define (heap-sort! xs) + (define (ref i) (vector-ref xs i)) + (define (swap! i j) (vector-swap! xs i j)) + (define size (vector-length xs)) + + (define (sift-down! r end) + (define c (+ (* 2 r) 1)) + (define c+1 (+ c 1)) + (when (<= c end) + (define child + (if (and (<= c+1 end) (< (ref c) (ref c+1))) + c+1 c)) + (when (< (ref r) (ref child)) + (swap! r child)) + (sift-down! child end))) + + (for ([i (in-range (quotient (- size 2) 2) -1 -1)]) + (sift-down! i (- size 1))) + + (for ([end (in-range (- size 1) 0 -1)]) + (swap! 0 end) + (sift-down! 0 (- end 1))) + xs) 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 index 1e3f4bdfb0..8adb738ffc 100644 --- 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 @@ -13,5 +13,5 @@ class Array end end ary = [7,6,5,9,8,4,3,1,2,0] -ary.insertionsort! +p 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 index f8b13edd28..317ebd1683 100644 --- 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 @@ -1,7 +1,5 @@ class Array def insertionsort! - return if length < 2 - 1.upto(length - 1) do |i| value = delete_at i j = i - 1 @@ -13,5 +11,5 @@ class Array end ary = [7,6,5,9,8,4,3,1,2,0] -ary.insertionsort! +p ary.insertionsort! # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Merge-sort/Racket/sorting-algorithms-merge-sort-1.rkt b/Task/Sorting-algorithms-Merge-sort/Racket/sorting-algorithms-merge-sort-1.rkt new file mode 100644 index 0000000000..767a185335 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Racket/sorting-algorithms-merge-sort-1.rkt @@ -0,0 +1,15 @@ +#lang racket + +(define (merge xs ys) + (cond [(empty? xs) ys] + [(empty? ys) xs] + [(match* (xs ys) + [((list* a as) (list* b bs)) + (cond [(<= a b) (cons a (merge as ys))] + [ (cons b (merge xs bs))])])])) + +(define (merge-sort xs) + (match xs + [(or (list) (list _)) xs] + [_ (define-values (ys zs) (split-at xs (quotient (length xs) 2))) + (merge (merge-sort ys) (merge-sort zs))])) diff --git a/Task/Sorting-algorithms-Merge-sort/Racket/sorting-algorithms-merge-sort-2.rkt b/Task/Sorting-algorithms-Merge-sort/Racket/sorting-algorithms-merge-sort-2.rkt new file mode 100644 index 0000000000..a6d0e40fb0 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Racket/sorting-algorithms-merge-sort-2.rkt @@ -0,0 +1,19 @@ +#lang racket + +(define (merge-sort xs) + (merge* (map list xs))) + +(define (merge* xss) + (match xss + [(list) '()] + [(list xs) xss] + [(list xs ys zss ...) + (merge* (cons (merge xs ys) (merge* zss)))])) + +(define (merge xs ys) + (cond [(empty? xs) ys] + [(empty? ys) xs] + [(match* (xs ys) + [((list* a as) (list* b bs)) + (cond [(<= a b) (cons a (merge as ys))] + [ (cons b (merge xs bs))])])])) diff --git a/Task/Sorting-algorithms-Pancake-sort/NetRexx/sorting-algorithms-pancake-sort.netrexx b/Task/Sorting-algorithms-Pancake-sort/NetRexx/sorting-algorithms-pancake-sort.netrexx new file mode 100644 index 0000000000..a2366a366d --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/NetRexx/sorting-algorithms-pancake-sort.netrexx @@ -0,0 +1,81 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +import java.util.List + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method pancakeSort(tlist = List, debug = (1 == 0)) private static returns List + + if tlist.size() > 1 then do + loop i_ = tlist.size() by -1 while i_ > 1 + maxPos = 0 + loop a_ = 0 while a_ < i_ + if Rexx tlist.get(a_) > Rexx tlist.get(maxPos) then maxPos = a_ + end a_ + if maxPos = i_ - 1 then iterate i_ + if maxPos > 0 then pancakeFlip(tlist, maxPos + 1, debug) + pancakeFlip(tlist, i_, debug) + end i_ + end + return tlist + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method pancakeFlip(tlist = List, offset, debug = (1 == 0)) private static returns List + z_ = offset - 1 + pl = 3 + if debug then do + plx = offset.length() + if plx > pl then pl = plx + say ' flip{1-'offset.right(pl, 0)'} Before:' tlist + end + loop i_ = 0 while i_ < z_ + Collections.swap(tlist, i_, z_) + z_ = z_ - 1 + end i_ + if debug then do + say ' flip{1-'offset.right(pl, 0)'} After:' tlist + end + return tlist + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + + isTrue = (1 == 1) + isFalse = \isTrue + + parse arg debug . + if '-debug'.abbrev(debug.lower(), 2) then debug = isTrue + else debug = isFalse + + lists = sampleData() + loop il = 1 to lists[0] + clist = words2list(lists[il]) + say ' Input:' clist + say 'Output:' pancakeSort(clist, debug) + say + end il + + return +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method sampleData() private static + lists = '' + i_ = 0 + i_ = i_ + 1; lists[0] = i_; lists[i_] = '1 4 3 5 2 9 8 7 6' + i_ = i_ + 1; lists[0] = i_; lists[i_] = '10 -9 8 -7 6 -5 4 -3 2 -1 0 -10 9 -8 7 -6 5 -4 3 -2 1' + i_ = i_ + 1; lists[0] = i_; lists[i_] = '88 18 31 44 4 0 8 81 14 78 20 76 84 33 73 75 82 5 62 70 12 7 1' + i_ = i_ + 1; lists[0] = i_; lists[i_] = '10 10.0 10.00 1 -10.0 10. -1' + i_ = i_ + 1; lists[0] = i_; lists[i_] = 'To be or not to be that is the question' + i_ = i_ + 1; lists[0] = i_; lists[i_] = '1' + return lists +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method words2list(wordlist) private static returns List + + clist = ArrayList() + loop w_ = 1 to wordlist.words() + clist.add(wordlist.word(w_)) + end w_ + + return clist diff --git a/Task/Sorting-algorithms-Pancake-sort/Racket/sorting-algorithms-pancake-sort.rkt b/Task/Sorting-algorithms-Pancake-sort/Racket/sorting-algorithms-pancake-sort.rkt new file mode 100644 index 0000000000..1652ac8d95 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Racket/sorting-algorithms-pancake-sort.rkt @@ -0,0 +1,12 @@ +#lang racket + +(define (pancake-sort l) + (define (flip l n) (append (reverse (take l n)) (drop l n))) + (for/fold ([l l]) ([i (in-range (length l) 1 -1)]) + (let* ([i2 (cdr (for/fold ([m #f]) ([x l] [j i]) + (if (and m (<= x (car m))) m (cons x j))))] + [l (if (zero? i2) l (flip l (add1 i2)))]) + (flip l i)))) + +(pancake-sort (shuffle (range 0 10))) +;; => '(0 1 2 3 4 5 6 7 8 9) 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 index a20723ac42..35dca1a6df 100644 --- a/Task/Sorting-algorithms-Pancake-sort/Ruby/sorting-algorithms-pancake-sort.rb +++ b/Task/Sorting-algorithms-Pancake-sort/Ruby/sorting-algorithms-pancake-sort.rb @@ -1,28 +1,19 @@ 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 + (self.size-1).downto(1) do |end_idx| + max = self[0..end_idx].max + max_idx = self[0..end_idx].index(max) 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 + p [num_flips += 1, self] if $DEBUG end self[0..end_idx] = self[0..end_idx].reverse - - if $DEBUG - num_flips += 1 - p [num_flips, self] - end + p [num_flips += 1, self] if $DEBUG end - self end end diff --git a/Task/Sorting-algorithms-Permutation-sort/Java/sorting-algorithms-permutation-sort.java b/Task/Sorting-algorithms-Permutation-sort/Java/sorting-algorithms-permutation-sort.java new file mode 100644 index 0000000000..b411413f14 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Java/sorting-algorithms-permutation-sort.java @@ -0,0 +1,52 @@ +import java.util.List; +import java.util.ArrayList; +import java.util.Arrays; + +public class PermutationSort +{ + public static void main(String[] args) + { + int[] a={3,2,1,8,9,4,6}; + System.out.println("Unsorted: " + Arrays.toString(a)); + a=pSort(a); + System.out.println("Sorted: " + Arrays.toString(a)); + } + public static int[] pSort(int[] a) + { + List<int[]> list=new ArrayList<int[]>(); + permute(a,a.length,list); + for(int[] x : list) + if(isSorted(x)) + return x; + return a; + } + private static void permute(int[] a, int n, List<int[]> list) + { + if (n == 1) + { + int[] b=new int[a.length]; + System.arraycopy(a, 0, b, 0, a.length); + list.add(b); + return; + } + for (int i = 0; i < n; i++) + { + swap(a, i, n-1); + permute(a, n-1, list); + swap(a, i, n-1); + } + } + private static boolean isSorted(int[] a) + { + for(int i=1;i<a.length;i++) + if(a[i-1]>a[i]) + return false; + return true; + } + private static void swap(int[] arr,int i, int j) + { + int temp=arr[i]; + arr[i]=arr[j]; + arr[j]=temp; + } +} diff --git a/Task/Sorting-algorithms-Permutation-sort/NetRexx/sorting-algorithms-permutation-sort.netrexx b/Task/Sorting-algorithms-Permutation-sort/NetRexx/sorting-algorithms-permutation-sort.netrexx new file mode 100644 index 0000000000..6a70a8290a --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/NetRexx/sorting-algorithms-permutation-sort.netrexx @@ -0,0 +1,84 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +import java.util.List +import java.util.ArrayList + +numeric digits 20 + +class RSortingPermutationsort public + + properties private static + iterations + maxIterations + + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method permutationSort(vlist = List) public static returns List + perm = RPermutationIterator(vlist) + iterations = 0 + maxIterations = RPermutationIterator.factorial(vlist.size()) + loop while perm.hasNext() + iterations = iterations + 1 + pl = List perm.next() + if isSorted(pl) then leave + else pl = null + end + return pl + + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method isSorted(ss = List) private static returns boolean + status = isTrue + loop ix = 1 while ix < ss.size() + vleft = Rexx ss.get(ix - 1) + vright = Rexx ss.get(ix) + if vleft.datatype('N') & vright.datatype('N') + then vtest = vleft > vright -- For numeric types we must use regular comparison. + else vtest = vleft >> vright -- For non-numeric/mixed types we must do strict comparison. + if vtest then do + status = isFalse + leave ix + end + end ix + return status + + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method runSample(arg) private static + placesList = - + "UK London, US New York, US Boston, US Washington" - + "UK Washington, US Birmingham, UK Birmingham, UK Boston" + anotherList = 'Alpha, Beta, Gamma, Beta' + reversed = '7, 6, 5, 4, 3, 2, 1' + unsorted = '734, 3, 1, 24, 324, -1024, -666, -1, 0, 324, 99999999' + lists = [makeList(placesList), makeList(anotherList), makeList(reversed), makeList(unsorted)] + loop il = 0 while il < lists.length + vlist = lists[il] + say vlist + runtime = System.nanoTime() + rlist = permutationSort(vlist) + runtime = System.nanoTime() - runtime + if rlist \= null then say rlist + else say 'sort failed' + say 'This permutation sort of' vlist.size() 'elements took' iterations 'passes (of' maxIterations') to complete. \-' + say 'Elapsed time:' (runtime / 10 ** 9)'s.' + say + end il + return + + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method makeList(in) public static returns List + lst = ArrayList() + loop while in > '' + parse in val ',' in + lst.add(val.strip()) + end + return lst + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method main(args = String[]) public static + runSample(Rexx(args)) + return + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method isTrue() public static returns boolean + return (1 == 1) + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method isFalse() public static returns boolean + return (1 == 0) diff --git a/Task/Sorting-algorithms-Permutation-sort/Racket/sorting-algorithms-permutation-sort.rkt b/Task/Sorting-algorithms-Permutation-sort/Racket/sorting-algorithms-permutation-sort.rkt new file mode 100644 index 0000000000..4a96ac9b8b --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Racket/sorting-algorithms-permutation-sort.rkt @@ -0,0 +1,4 @@ +#lang racket +(define (sort l) + (for/first ([p (in-permutations l)] #:when (apply <= p)) p)) +(sort '(6 1 5 2 4 3)) ; => '(1 2 3 4 5 6) diff --git a/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort.erl b/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort.erl index 3c130f1867..fdaabbc484 100644 --- a/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort.erl +++ b/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort.erl @@ -1,3 +1,7 @@ +-module( quicksort ). + +-export( [qsort/1] ). + qsort([]) -> []; qsort([X|Xs]) -> qsort([ Y || Y <- Xs, Y < X]) ++ [X] ++ qsort([ Y || Y <- Xs, Y >= X]). diff --git a/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f b/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f index 2540a01faf..9148b6d5a4 100644 --- a/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f +++ b/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f @@ -1,78 +1,89 @@ -MODULE Qsort_Module +module qsort_mod -IMPLICIT NONE +implicit none -CONTAINS +type group + integer :: order ! original order of unsorted data + real :: value ! values to be sorted by +end type group -RECURSIVE SUBROUTINE Qsort(a) +contains - INTEGER, INTENT(IN OUT) :: a(:) - INTEGER :: split +recursive subroutine QSort(a,na) - IF(size(a) > 1) THEN - CALL Partition(a, split) - CALL Qsort(a(:split-1)) - CALL Qsort(a(split:)) - END IF +! DUMMY ARGUMENTS +integer, intent(in) :: nA +type (group), dimension(nA), intent(in out) :: A -END SUBROUTINE Qsort +! LOCAL VARIABLES +integer :: left, right +real :: random +real :: pivot +type (group) :: temp +integer :: marker -SUBROUTINE Partition(a, marker) + if (nA > 1) then - INTEGER, INTENT(IN OUT) :: a(:) - INTEGER, INTENT(OUT) :: marker - INTEGER :: left, right, pivot, temp + call random_number(random) + pivot = A(int(random*real(nA-1))+1)%value ! random pivot (not best performance, but avoids worst-case) + left = 0 + right = nA + 1 - 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)%value > pivot) + right = right - 1 + end do + left = left + 1 + do while (A(left)%value < pivot) + left = left + 1 + end do + if (left < right) then + temp = A(left) + A(left) = A(right) + A(right) = temp + end if + end do - 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 - IF (left == right) THEN - marker = left + 1 - ELSE - marker = left - END IF + call QSort(A(:marker-1),marker-1) + call QSort(A(marker:),nA-marker+1) -END SUBROUTINE Partition + end if -END MODULE Qsort_Module +end subroutine QSort -PROGRAM Quicksort +end module qsort_mod - USE Qsort_Module +! Test Qsort Module +program qsort_test +use qsort_mod +implicit none - 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 +integer, parameter :: l = 8 +type (group), dimension(l) :: A +integer, dimension(3) :: seed = [1, 2, 3] +integer :: i +real :: random - WRITE (*, "(A)") "array is :-" - WRITE (*, "(10I5)") array - CALL Qsort(array) - WRITE (*,*) - WRITE (*, "(A)") "sorted array is :-" - WRITE (*,"(10I5)") array + write (*,*) "Unsorted Values:" + call random_seed(put = seed) + do i = 1, l + call random_number(random) + A(i)%value = random + A(i)%order = i + if (mod(i,4) == 0) write (*,"(4(I5,1X,F8.6))") A(i-3:i) + end do -END PROGRAM Quicksort + call QSort(A,l) + write (*,*) "Sorted Values:" + do i = 4, l, 4 + if (mod(i,4) == 0) write (*,"(4(I5,1X,F8.6))") A(i-3:i) + end do + +end program qsort_test diff --git a/Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java b/Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java index 141b6dec14..9744e2156f 100644 --- a/Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java +++ b/Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java @@ -1,7 +1,7 @@ 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 +if (!arr.isEmpty()) { + E pivot = arr.get(0); //This pivot can change to get faster results + List<E> less = new LinkedList<E>(); List<E> pivotList = new LinkedList<E>(); @@ -25,4 +25,7 @@ public static <E extends Comparable<? super E>> List<E> quickSort(List<E> arr) { less.addAll(pivotList); less.addAll(more); return less; + } +return arr; + } diff --git a/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort-1.math b/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort-1.math new file mode 100644 index 0000000000..d0e87fe0dd --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort-1.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/Mathematica/sorting-algorithms-quicksort-2.math b/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort-2.math new file mode 100644 index 0000000000..02ad189171 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort-2.math @@ -0,0 +1,2 @@ +qsort[{}] = {}; +qsort[{x_, xs___}] := Join[qsort@Select[{xs}, # <= x &], {x}, qsort@Select[{xs}, # > x &]]; diff --git a/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-1.rkt b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-1.rkt new file mode 100644 index 0000000000..c0fd84dde1 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-1.rkt @@ -0,0 +1,9 @@ +#lang racket +(define (quicksort a-list (compare <)) + (match a-list + ((list) + (list)) + ((cons x xs) + (append (quicksort (filter (lambda (element) (compare element x)) xs) compare) + (list x) + (quicksort (filter (lambda (element) (not (compare element x))) xs) compare))))) diff --git a/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-2.rkt b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-2.rkt new file mode 100644 index 0000000000..339b6867e4 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-2.rkt @@ -0,0 +1,4 @@ + (quicksort '(8 7 5 6 4 3 2)) +;returns '(2 3 4 5 6 7 8) +(quicksort '("Quicksort" "Mergesort" "Bubblesort") string<?) +;returns '("Bubblesort" "Mergesort" "Quicksort") diff --git a/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort.java b/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort.java new file mode 100644 index 0000000000..90febcfd43 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort.java @@ -0,0 +1,118 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class RSortingRadixsort00 { + + public RSortingRadixsort00() { + + return; + } + + public static int[] lsdRadixSort(int[] tlist) { + + List<Integer> intermediates; + int[] limits = getLimits(tlist); + tlist = rescale(tlist, limits[1]); + + for (int px = 1; px <= limits[2]; ++px) { + @SuppressWarnings("unchecked") + Queue<Integer> bukits[] = new Queue[10]; + for (int ix = 0; ix < tlist.length; ++ix) { + int cval = tlist[ix]; + int digit = (int) (cval / Math.pow(10, px - 1) % 10); + if (bukits[digit] == null) { + bukits[digit] = new LinkedList<>(); + } + bukits[digit].add(cval); + } + + intermediates = new ArrayList<>(); + for (int bi = 0; bi < 10; ++bi) { + if (bukits[bi] != null) { + while (bukits[bi].size() > 0) { + int nextd; + nextd = bukits[bi].poll(); + intermediates.add(nextd); + } + } + } + + for (int iw = 0; iw < intermediates.size(); ++iw) { + tlist[iw] = intermediates.get(iw); + } + } + + tlist = rescale(tlist, -limits[1]); + + return tlist; + } + + private static int[] rescale(int[] arry, int delta) { + + for (int ix = 0; ix < arry.length; ++ix) { + arry[ix] -= delta; + } + + return arry; + } + + private static int[] getLimits(int[] tlist) { + + int[] lims = new int[3]; + + for (int i_ = 0; i_ < tlist.length; ++i_) { + lims[0] = Math.max(lims[0], tlist[i_]); + lims[1] = Math.min(lims[1], tlist[i_]); + } + lims[2] = (int) Math.ceil(Math.log10(lims[0] - lims[1])); + + return lims; + } + + private static void runSample(String[] args) { + + int[][] lists = { + new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, }, + new int[] { -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, -0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }, + new int[] { 2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666, }, + new int[] { 170, 45, 75, 90, 2, 24, 802, 66, }, + new int[] { -170, -45, -75, -90, -2, -24, -802, -66, }, + }; + + long etime; + lsdRadixSort(Arrays.copyOf(lists[0], lists[0].length)); // do one pass to set up environment to remove it from timings + + for (int[] tlist : lists) { + System.out.println(array2list(tlist)); + etime = System.nanoTime(); + tlist = lsdRadixSort(tlist); + etime = System.nanoTime() - etime; + System.out.println(array2list(tlist)); + System.out.printf("Elapsed time: %fs%n", ((double) etime / 1_000_000_000.0)); + System.out.println(); + } + + return; + } + + private static List<Integer> array2list(int[] arry) { + + List<Integer> target = new ArrayList<>(arry.length); + + for (Integer iv : arry) { + target.add(iv); + } + + return target; + } + + public static void main(String[] args) { + + runSample(args); + + return; + } +} diff --git a/Task/Sorting-algorithms-Radix-sort/NetRexx/sorting-algorithms-radix-sort-1.netrexx b/Task/Sorting-algorithms-Radix-sort/NetRexx/sorting-algorithms-radix-sort-1.netrexx new file mode 100644 index 0000000000..23117965ba --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/NetRexx/sorting-algorithms-radix-sort-1.netrexx @@ -0,0 +1,72 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method radixSort(tlist = Rexx[]) public static returns Rexx[] + + -- scale the array to start at zero to allow handling of -ve values + parse getLimits(tlist) maxn minn maxl . + tlist = rescale(tlist, minn) + + loop px = maxl to 1 by -1 + bukits = '' + loop ix = 0 to tlist.length - 1 + cval = tlist[ix].right(maxl, 0) + parse cval . =(px) digit +1 . + bukits[digit] = bukits[digit] (cval + 0) -- simulates a stack + end ix + intermediates = '' + loop bi = 0 to 9 + intermediates = intermediates bukits[bi] -- sumulates unstack + end bi + -- reload array + loop iw = 1 to intermediates.words() + tlist[iw - 1] = intermediates.word(iw) + end iw + end px + + -- restore the array to original scale + tlist = rescale(tlist, -minn) + return tlist + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method rescale(arry = Rexx[], newbase) private static returns Rexx[] + loop ix = 0 to arry.length - 1 + arry[ix] = arry[ix] - newbase + end ix + return arry +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getLimits(arry = Rexx[]) private static returns Rexx + maxn = 0 + minn = 0 + maxl = 0 + loop i_ = 0 to arry.length - 1 + maxn = maxn.max(arry[i_]) + minn = minn.min(arry[i_]) + end i_ + maxl = (maxn - minn).length() + return maxn minn maxl +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + lists = [- + [2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666], - + [170, 45, 75, 90, 2, 24, 802, 66], - + [10, 9, 8, 7, 8, 5, 4, 3, 2, 1, 0], - + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - + [-10, -9, -8, -7, -8, -5, -4, -3, -2, -1, -0], - + [-0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10], - + [-10, -19, -18, -17, -18, -15, -14, -13, -12, -11, -100], - + [10, 9, 8, 7, 8, 5, 4, 3, 2, 1, 0, -0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10], - + [-10, -9, -8, -7, -8, -5, -4, -3, -2, -1, -0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - + ] + + loop il = 0 to lists.length - 1 + tlist = lists[il] + say ' Input:' Arrays.asList(tlist) + say 'Output:' Arrays.asList(radixSort(tlist)) + say + end il + return diff --git a/Task/Sorting-algorithms-Radix-sort/NetRexx/sorting-algorithms-radix-sort-2.netrexx b/Task/Sorting-algorithms-Radix-sort/NetRexx/sorting-algorithms-radix-sort-2.netrexx new file mode 100644 index 0000000000..9611b4ed74 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/NetRexx/sorting-algorithms-radix-sort-2.netrexx @@ -0,0 +1,86 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +import java.util.Queue + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method radixSort(tlist = Rexx[]) public static returns Rexx[] + + -- scale the array to start at zero to allow handling of -ve values + limits = '' + parse '!MAXN !MINN !MAXL' maxn_ minn_ maxl_ . + parse getLimits(tlist) maxn minn maxl . + limits[maxn_] = maxn + limits[minn_] = minn + limits[maxl_] = maxl + tlist = rescale(tlist, limits[minn_]) + + loop px = limits[maxl_] to 1 by -1 + bukits = Queue[10] -- stacks for digits 0 .. 9 + loop ix = 0 while ix < tlist.length + cval = tlist[ix].right(limits[maxl_], 0) + parse cval . =(px) digit +1 . -- extract next digit (fun with parse) + -- alternatively: digit = (cval % (10 ** (px - 1))) // 10 + if bukits[digit] == null then bukits[digit] = LinkedList() + bukits[digit].add((cval + 0)) + end ix + + intermediates = ArrayList() + loop bi = 0 to 9 + if bukits[bi] \= null then loop while bukits[bi].size() > 0 + nextd = bukits[bi].poll() + intermediates.add(nextd) + end + end bi + + -- reload result array + loop iw = 0 while iw < intermediates.size() + tlist[iw] = Rexx intermediates.get(iw) + end iw + end px + + -- restore the array to original scale + tlist = rescale(tlist, -limits[minn_]) + return tlist + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method rescale(arry = Rexx[], newbase) private static returns Rexx[] + loop ix = 0 to arry.length - 1 + arry[ix] = arry[ix] - newbase + end ix + return arry +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getLimits(arry = Rexx[]) private static returns Rexx + maxn = 0 + minn = 0 + maxl = 0 + loop i_ = 0 to arry.length - 1 + maxn = maxn.max(arry[i_]) + minn = minn.min(arry[i_]) + end i_ + maxl = (maxn - minn).length() + return maxn minn maxl +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + lists = [- + [2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666], - + [170, 45, 75, 90, 2, 24, 802, 66], - + [10, 9, 8, 7, 8, 5, 4, 3, 2, 1, 0], - + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - + [-10, -9, -8, -7, -8, -5, -4, -3, -2, -1, -0], - + [-0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10], - + [-10, -19, -18, -17, -18, -15, -14, -13, -12, -11, -100], - + [10, 9, 8, 7, 8, 5, 4, 3, 2, 1, 0, -0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10], - + [-10, -9, -8, -7, -8, -5, -4, -3, -2, -1, -0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - + ] + + loop il = 0 to lists.length - 1 + tlist = lists[il] + say ' Input:' Arrays.asList(tlist) + say 'Output:' Arrays.asList(radixSort(tlist)) + say + end il + return 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 index b500657641..7ce49cb805 100644 --- a/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx +++ b/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx @@ -5,62 +5,51 @@ 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', '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) +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 - + end /*n*/ 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) + 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 +!.#._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 + 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 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 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 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._ + 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._ @@ -69,13 +58,14 @@ radSort: procedure expose @. width; parse arg size; mote=c2d(' '); #=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*/ +#=0; do i=size by -1 to 1; if @.i>=0 then iterate; #=#+1; @@.#=@.i; end + do j=1 for size; if @.j <0 then iterate; #=#+1; @@.#=@.j; end + do k=1 for size; @.k=@@.k+0; end /*combine neg&pos radix lists*/ return /*───────────────────────────────────.radSortP subroutine───────────────*/ -.radSortP: parse arg bbb,nnn - do k=bbb+1 for nnn-1; q=@.k +.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 + jp=j+1; @.jp=q end /*k*/ return diff --git a/Task/Sorting-algorithms-Radix-sort/Racket/sorting-algorithms-radix-sort.rkt b/Task/Sorting-algorithms-Radix-sort/Racket/sorting-algorithms-radix-sort.rkt new file mode 100644 index 0000000000..2170d746a3 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Racket/sorting-algorithms-radix-sort.rkt @@ -0,0 +1,29 @@ +#lang racket + +(require data/queue) + +(define (radix-sort l r) + (define queues (for/vector #:length r ([_ r]) (make-queue))) + (let loop ([l l] [R 1]) + (define all-zero? #t) + (for ([x (in-list l)]) + (define x/R (quotient x R)) + (enqueue! (vector-ref queues (modulo x/R r)) x) + (unless (zero? x/R) (set! all-zero? #f))) + (if all-zero? l + (loop (let q-loop ([i 0]) + (define q (vector-ref queues i)) + (let dq-loop () + (if (queue-empty? q) + (if (< i (sub1 r)) (q-loop (add1 i)) '()) + (cons (dequeue! q) (dq-loop))))) + (* R r))))) + +(for/and ([i 10000]) ; run some tests on random lists with a random radix + (define (make-random-list) + (for/list ([i (+ 10 (random 10))]) (random 100000))) + (define (sorted? l) + (match l [(list) #t] [(list x) #t] + [(list x y more ...) (and (<= x y) (sorted? (cons y more)))])) + (sorted? (radix-sort (make-random-list) (+ 2 (random 98))))) +;; => #t, so all passed diff --git a/Task/Sorting-algorithms-Selection-sort/Racket/sorting-algorithms-selection-sort.rkt b/Task/Sorting-algorithms-Selection-sort/Racket/sorting-algorithms-selection-sort.rkt new file mode 100644 index 0000000000..559f23f970 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Racket/sorting-algorithms-selection-sort.rkt @@ -0,0 +1,5 @@ +#lang racket +(define (selection-sort xs) + (cond [(empty? xs) '()] + [else (define x0 (apply min xs)) + (cons x0 (selection-sort (remove x0 xs)))])) diff --git a/Task/Sorting-algorithms-Shell-sort/C++/sorting-algorithms-shell-sort.cpp b/Task/Sorting-algorithms-Shell-sort/C++/sorting-algorithms-shell-sort.cpp new file mode 100644 index 0000000000..f7c9d65837 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/C++/sorting-algorithms-shell-sort.cpp @@ -0,0 +1,73 @@ +#include <time.h> +#include <iostream> + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +const int MAX = 126; +class shell +{ +public: + shell() + { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; } + + void sort( int* a, int count ) + { + _cnt = count; + for( int x = 0; x < 9; x++ ) + if( count > _gap[x] ) + { _idx = x; break; } + + sortIt( a ); + } + +private: + void sortIt( int* arr ) + { + bool sorted = false; + while( true ) + { + sorted = true; + int st = 0; + for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] ) + { + if( arr[st] > arr[x] ) + { swap( arr[st], arr[x] ); sorted = false; } + st = x; + } + if( ++_idx >= 8 ) _idx = 8; + if( sorted && _idx == 8 ) break; + } + } + + void swap( int& a, int& b ) { int t = a; a = b; b = t; } + + int _gap[9], _idx, _cnt; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX]; + for( int x = 0; x < MAX; x++ ) + arr[x] = rand() % MAX - rand() % MAX; + + cout << " Before: \n=========\n"; + for( int x = 0; x < 7; x++ ) + { + for( int a = 0; a < 18; a++ ) + { cout << arr[x * 18 + a] << " "; } + cout << endl; + } + cout << endl; shell s; s.sort( arr, MAX ); + + cout << " After: \n========\n"; + for( int x = 0; x < 7; x++ ) + { + for( int a = 0; a < 18; a++ ) + { cout << arr[x * 18 + a] << " "; } + cout << endl; + } + cout << endl << endl; return system( "pause" ); +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Sorting-algorithms-Shell-sort/Racket/sorting-algorithms-shell-sort.rkt b/Task/Sorting-algorithms-Shell-sort/Racket/sorting-algorithms-shell-sort.rkt new file mode 100644 index 0000000000..b7a2e0fbb9 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Racket/sorting-algorithms-shell-sort.rkt @@ -0,0 +1,14 @@ +#lang racket +(define (shell-sort! xs) + (define (ref i) (vector-ref xs i)) + (define (new Δ) (if (= Δ 2) 1 (exact-floor (/ (* Δ 5) 11)))) + (let loop ([Δ (quotient (vector-length xs) 2)]) + (unless (= Δ 0) + (for ([xi (in-vector xs)] [i (in-naturals)]) + (let while ([i i]) + (cond [(and (>= i Δ) (> (ref (- i Δ)) xi)) + (vector-set! xs i (ref (- i Δ))) + (while (- i Δ))] + [(vector-set! xs i xi)]))) + (loop (new Δ)))) + xs) diff --git a/Task/Sorting-algorithms-Stooge-sort/Racket/sorting-algorithms-stooge-sort.rkt b/Task/Sorting-algorithms-Stooge-sort/Racket/sorting-algorithms-stooge-sort.rkt new file mode 100644 index 0000000000..7f1ef553d6 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Racket/sorting-algorithms-stooge-sort.rkt @@ -0,0 +1,12 @@ +#lang racket +(define (stooge-sort xs [i 0] [j (- (vector-length xs) 1)]) + (define (x i) (vector-ref xs i)) + (define (x! i v) (vector-set! xs i v)) + (define (swap! i j) (define t (x i)) (x! i (x j)) (x! j t)) + (when (> (x i) (x j)) (swap! i j)) + (when (> (- j i) 1) + (define t (quotient (+ j (- i) 1) 3)) + (stooge-sort xs i (- j t)) + (stooge-sort xs (+ i t) j) + (stooge-sort xs i (- j t))) + xs) diff --git a/Task/Sorting-algorithms-Strand-sort/Racket/sorting-algorithms-strand-sort.rkt b/Task/Sorting-algorithms-Strand-sort/Racket/sorting-algorithms-strand-sort.rkt new file mode 100644 index 0000000000..85277985e0 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Racket/sorting-algorithms-strand-sort.rkt @@ -0,0 +1,17 @@ +#lang racket +(require mzlib/list) +(define (merge xs ys) (merge-sorted-lists xs ys <=)) + +(define (strand-sort xs) + (let loop ([xs xs] [ys '[]]) + (cond [(empty? xs) ys] + [else (define-values (sorted unsorted) (extract-strand xs)) + (loop unsorted (merge sorted ys))]))) + +(define (extract-strand xs) + (for/fold ([strand '()] [unsorted '[]]) ([x xs]) + (if (or (empty? strand) (< x (first strand))) + (values (cons x strand) unsorted) + (values strand (cons x unsorted))))) + +(strand-sort (build-list 10 (λ(_) (random 15)))) diff --git a/Task/Soundex/COBOL/soundex.cobol b/Task/Soundex/COBOL/soundex.cobol index ddb4d1ebda..721d5cacf3 100644 --- a/Task/Soundex/COBOL/soundex.cobol +++ b/Task/Soundex/COBOL/soundex.cobol @@ -1,143 +1,149 @@ -**** soundex-test ********************************************* -* Demonstrate the soundex encoding functions. -*************************************************************** -Identification division. -Program-id. soundex-test. + **** sndxtest ********************************************* + * Demonstrate the soundex encoding functions. + *************************************************************** + Identification division. + Program-id. sndxtest. -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. + 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. + Procedure division. + Perform varying wrd-idx from 1 by 1 + until wrd-idx greater than 28 + call "sndxenc" using + by reference sample-word(wrd-idx) + by reference wrd-code + display wrd-code " " sample-word(wrd-idx) + end-perform. + Stop run. + + End program sndxtest. + + *** sndxenc ******************************************** + * Given a string return its soundex encoding. + *************************************************************** + Identification division. + Program-id. sndxenc. + + 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 reference 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 "sndxchar" using + by reference 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 str-rest-let(str-idx) = space + or sdx-idx greater than 3 + call "sndxchar" using + by reference 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 + 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. + continue. + End program sndxenc. -*** soundex-encode ******************************************** -* Given a string return its soundex encoding. -*************************************************************** -Identification division. -Program-id. soundex-encode. + *** sndxchar ********************************************** + * 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. sndxchar. -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. + 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 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. + Linkage section. + 01 char-to-encode pic x. + 01 char-sdx-code pic 9. -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. + Procedure division using + by reference 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 sndxchar. diff --git a/Task/Speech-synthesis/Racket/speech-synthesis.rkt b/Task/Speech-synthesis/Racket/speech-synthesis.rkt new file mode 100644 index 0000000000..d185eb2cb7 --- /dev/null +++ b/Task/Speech-synthesis/Racket/speech-synthesis.rkt @@ -0,0 +1,12 @@ +#lang racket +(require racket/lazy-require) +(lazy-require [ffi/com (com-create-instance com-release com-invoke)]) +(define (speak text) + (cond [(eq? 'windows (system-type)) + (define c (com-create-instance "SAPI.SpVoice")) + (com-invoke c "Speak" text) + (com-release c)] + [(ormap find-executable-path '("say" "espeak")) + => (λ(exe) (void (system* exe text)))] + [else (error 'speak "I'm speechless!")])) +(speak "This is an example of speech synthesis.") diff --git a/Task/Spiral-matrix/Racket/spiral-matrix-1.rkt b/Task/Spiral-matrix/Racket/spiral-matrix-1.rkt new file mode 100644 index 0000000000..0e0128609b --- /dev/null +++ b/Task/Spiral-matrix/Racket/spiral-matrix-1.rkt @@ -0,0 +1,24 @@ +#lang racket +(require math) + +(define (spiral rows columns) + (define (index x y) (+ (* x columns) y)) + (do ((N (* rows columns)) + (spiral (make-vector (* rows columns) #f)) + (dx 1) (dy 0) (x 0) (y 0) + (i 0 (+ i 1))) + ((= i N) spiral) + (vector-set! spiral (index y x) i) + (let ((nx (+ x dx)) (ny (+ y dy))) + (cond + ((and (< -1 nx columns) + (< -1 ny rows) + (not (vector-ref spiral (index ny nx)))) + (set! x nx) + (set! y ny)) + (else + (set!-values (dx dy) (values (- dy) dx)) + (set! x (+ x dx)) + (set! y (+ y dy))))))) + +(vector->matrix 4 4 (spiral 4 4)) diff --git a/Task/Spiral-matrix/Racket/spiral-matrix-2.rkt b/Task/Spiral-matrix/Racket/spiral-matrix-2.rkt new file mode 100644 index 0000000000..d65318fb29 --- /dev/null +++ b/Task/Spiral-matrix/Racket/spiral-matrix-2.rkt @@ -0,0 +1 @@ +(mutable-array #[#[0 1 2 3] #[11 12 13 4] #[10 15 14 5] #[9 8 7 6]]) diff --git a/Task/Spiral-matrix/Ruby/spiral-matrix.rb b/Task/Spiral-matrix/Ruby/spiral-matrix.rb index 71bf1f53c7..7d8e0d1ee2 100644 --- a/Task/Spiral-matrix/Ruby/spiral-matrix.rb +++ b/Task/Spiral-matrix/Ruby/spiral-matrix.rb @@ -1,15 +1,10 @@ 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 + delta = [[1,0], [0,1], [-1,0], [0,-1]].cycle x, y, value = -1, 0, -1 for run in runs - dx,dy = begin - delta.next - rescue StopIteration - delta.rewind - retry - end + dx,dy = delta.next run.times do |i| x += dx y += dy @@ -20,4 +15,9 @@ def spiral(n) spiral end +def print_matrix(m) + max = m.flatten.map{|x| x.to_s.size}.max + m.each {|row| puts row.map {|x| "%#{max}s " % x}.join} +end + print_matrix spiral(5) diff --git a/Task/Stable-marriage-problem/Racket/stable-marriage-problem.rkt b/Task/Stable-marriage-problem/Racket/stable-marriage-problem.rkt new file mode 100644 index 0000000000..05c91037e3 --- /dev/null +++ b/Task/Stable-marriage-problem/Racket/stable-marriage-problem.rkt @@ -0,0 +1,85 @@ +#lang racket + +(define 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])) +(define 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 ])) + +;; x is better than y according to the l order +(define (better? x y l) (memq y (cdr (memq x l)))) + +(define (stable-matching Mprefs Wprefs) + (define M (map car Mprefs)) + (define engagements (make-hasheq)) + (define preferences (make-hasheq)) + (define (engage! m w) + (hash-set! engagements m w) + (hash-set! engagements w m)) + (for ([m Mprefs]) (hash-set! preferences (car m) (cdr m))) + (for ([w Wprefs]) (hash-set! preferences (car w) (cdr w))) + (let loop () + (define m+w + (for/or ([m M]) + (and (not (hash-ref engagements m #f)) ; m is free + (let ([p (hash-ref preferences m)]) ; can propose + (and (pair? p) + (let ([w (car p)]) + (hash-set! preferences m (cdr p)) ; drop w from m + (cons m w))))))) + (when m+w + (define m (car m+w)) + (define w (cdr m+w)) + (define m* (hash-ref engagements w #f)) ; m* is w's prev engagement + (cond [(not m*) (engage! m w)] ; w is free + [(better? m m* (hash-ref preferences w)) ; w prefers m over m* + (engage! m w) + (hash-set! engagements m* #f)]) ; m* becomes free + (loop))) + engagements) + +(define (find-unstable Mprefs Wprefs matches) + (for*/or ([m (map car Mprefs)] [w (map car Wprefs)]) + (define w* (hash-ref matches m)) + (define m* (hash-ref matches w)) + (and (not (eq? m m*)) + (better? w w* (cdr (assq m Mprefs))) + (better? m m* (cdr (assq w Wprefs))) + (cons m w)))) + +(define (check-stability) + (let ([u (find-unstable MEN WOMEN matches)]) + (if u + (printf "Unstable: ~a and ~a prefer each other over partners.\n" + (car u) (cdr u)) + (printf "The match is stable.\n")))) +(define matches (stable-matching MEN WOMEN)) +(printf "Found matches:\n") +(for ([m (map car MEN)]) (printf " ~a, ~a\n" m (hash-ref matches m))) +(check-stability) +(let ([M (map car (take (shuffle MEN) 2))]) + (printf "Swapping wives of ~a and ~a\n" (car M) (cadr M)) + (define (swap! x y) + (define t (hash-ref matches x)) + (hash-set! matches x (hash-ref matches y)) + (hash-set! matches y t)) + (swap! (car M) (cadr M)) + (swap! (hash-ref matches (car M)) (hash-ref matches (cadr M)))) +(check-stability) diff --git a/Task/Stack-traces/Racket/stack-traces.rkt b/Task/Stack-traces/Racket/stack-traces.rkt new file mode 100644 index 0000000000..a8eb227e92 --- /dev/null +++ b/Task/Stack-traces/Racket/stack-traces.rkt @@ -0,0 +1,17 @@ +#lang racket + +;; To see these calls we do two things: mutate the binding to prevent +;; Racket from inlining the value; use a (void) call at the end so the +;; calls are not tail calls (which will otherwise not show on the +;; stack). +(define foo #f) +(set! foo (λ() (bar) (void))) +(define bar #f) +(set! bar (λ() (show-stacktrace) (void))) + +(define (show-stacktrace) + (for ([s (continuation-mark-set->context (current-continuation-marks))] + [i (in-naturals)]) + ;; show just the names, not the full source information + (when (car s) (printf "~s: ~s\n" i (car s))))) +(foo) diff --git a/Task/Stack-traces/Raven/stack-traces.raven b/Task/Stack-traces/Raven/stack-traces.raven new file mode 100644 index 0000000000..0ad43f4085 --- /dev/null +++ b/Task/Stack-traces/Raven/stack-traces.raven @@ -0,0 +1 @@ + [1 2 3 4] 42 { 'a' 1 'b' 2 'c' 3 } 34.1234 ( -1 -2 -3 ) "The quick brown fox" FILE dump diff --git a/Task/Stair-climbing-puzzle/Racket/stair-climbing-puzzle.rkt b/Task/Stair-climbing-puzzle/Racket/stair-climbing-puzzle.rkt new file mode 100644 index 0000000000..f9ac62f4f6 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Racket/stair-climbing-puzzle.rkt @@ -0,0 +1,11 @@ +#lang racket +(define p 0.5001) +(define (step) + (> p (random))) + +(define (step-up n) + (cond ((zero? n) 'done) + ((step) (step-up (sub1 n))) + (else (step-up (add1 n))))) + +(step-up 1) diff --git a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-1.l b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-1.l new file mode 100644 index 0000000000..262ab6af4f --- /dev/null +++ b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-1.l @@ -0,0 +1,19 @@ +(defun running-std (x) + ; ensure that we have a float to avoid potential integer math errors. + (setq x (float x)) + ; define variables to use + (defvar running-sum 0 "the running sum of all known values") + (defvar running-len 0 "the running number of all known values") + (defvar running-squared-sum 0 "the running squared sum of all known values") + ; and make them local to this buffer + (make-local-variable 'running-sum) + (make-local-variable 'running-len) + (make-local-variable 'running-squared-sum) + ; now process the new value + (setq running-sum (+ running-sum x)) + (setq running-len (1+ running-len)) + (setq running-squared-sum (+ running-squared-sum (* x x))) + ; and calculate the new standard deviation + (sqrt (- (/ running-squared-sum + running-len) (/ (* running-sum running-sum) + (* running-len running-len ))))) diff --git a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-2.l b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-2.l new file mode 100644 index 0000000000..3c3827172b --- /dev/null +++ b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-2.l @@ -0,0 +1,14 @@ +(with-temp-buffer + (loop for i in '(2 4 4 4 5 5 7 9) do + (insert (number-to-string (running-std i))) + (newline)) + (message (buffer-substring (point-min) (1- (point-max))))) + +"0.0 +1.0 +0.9428090415820636 +0.8660254037844386 +0.9797958971132716 +1.0 +1.399708424447531 +2.0" diff --git a/Task/Standard-deviation/Racket/standard-deviation.rkt b/Task/Standard-deviation/Racket/standard-deviation.rkt new file mode 100644 index 0000000000..858cc66db6 --- /dev/null +++ b/Task/Standard-deviation/Racket/standard-deviation.rkt @@ -0,0 +1,7 @@ +#lang racket +(require math) +(define running-stddev + (let ([ns '()]) + (λ(n) (set! ns (cons n ns)) (stddev ns)))) +;; run it on each number, return the last result +(last (map running-stddev '(2 4 4 4 5 5 7 9))) diff --git a/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-1.fth b/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-1.fth new file mode 100644 index 0000000000..e7e1d0b00e --- /dev/null +++ b/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-1.fth @@ -0,0 +1,5 @@ +include foo.fs +... +: main ... ; + +main bye diff --git a/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-2.fth b/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-2.fth new file mode 100644 index 0000000000..a8ea8c4370 --- /dev/null +++ b/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-2.fth @@ -0,0 +1 @@ +$ gforth -e "2 2 + . bye" diff --git a/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-3.fth b/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-3.fth new file mode 100644 index 0000000000..e831eb436b --- /dev/null +++ b/Task/Start-from-a-main-routine/Forth/start-from-a-main-routine-3.fth @@ -0,0 +1 @@ +' main turnkey app.exe 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 index 77c2f756c7..1c79185ad7 100644 --- 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 @@ -1,4 +1,4 @@ +#/usr/bin/env racket -tm #lang racket (provide main) -(define (main) - (displayln "Hello World!")) +(define (main . args) (displayln "Hello World!")) 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 index c162b5eb03..a82cf21542 100644 --- 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 @@ -3,7 +3,7 @@ int icmp(const void *a, const void *b) { - return *(int*)a < *(int*)b ? -1 : *(int*)a > *(int*)b; + return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) 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 index 9572425132..0db72c9098 100644 --- a/Task/Stem-and-leaf-plot/D/stem-and-leaf-plot.d +++ b/Task/Stem-and-leaf-plot/D/stem-and-leaf-plot.d @@ -12,7 +12,7 @@ void main() { int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; - immutable loHi = reduce!(min, max)(data); + immutable loHi = data.reduce!(min, max); 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/Racket/stem-and-leaf-plot.rkt b/Task/Stem-and-leaf-plot/Racket/stem-and-leaf-plot.rkt new file mode 100644 index 0000000000..a5b2c61a41 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Racket/stem-and-leaf-plot.rkt @@ -0,0 +1,10 @@ +#lang racket +(define (show-stem+leaf data) + (define xs (sort data <)) + (for ([stem (add1 (floor (/ (last xs) 10)))]) + (printf "~a|" (~a #:width 2 #:align 'right stem)) + (for ([i xs]) + (define-values [q r] (quotient/remainder i 10)) + (when (= q stem) (printf " ~a" r))) + (newline))) +(show-stem+leaf (sequence->list (in-producer read eof))) diff --git a/Task/String-case/6502-Assembly/string-case.6502 b/Task/String-case/6502-Assembly/string-case.6502 index 293777a338..fc6b9714ca 100644 --- a/Task/String-case/6502-Assembly/string-case.6502 +++ b/Task/String-case/6502-Assembly/string-case.6502 @@ -36,18 +36,15 @@ main ldx #sTest Point to the test string 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 +toUpper ldy #LittleA + sty Low set up the flip range + ldy #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 +toLower ldy #BigA + sty Low set up the flip range + ldy #BigZ +toLow2 sty High ; return via fall-thru to flip ;------------------------------------------------------ ; Given a NUL-terminated string at A:X, flip the case diff --git a/Task/String-case/Racket/string-case.rkt b/Task/String-case/Racket/string-case.rkt new file mode 100644 index 0000000000..00da10d1ca --- /dev/null +++ b/Task/String-case/Racket/string-case.rkt @@ -0,0 +1,9 @@ +#lang racket +(define example "alphaBETA") + +(string-upcase example) +;"ALPHABETA" +(string-downcase example) +;"alphabeta" +(string-titlecase example) +;"Alphabeta" diff --git a/Task/String-comparison/Ada/string-comparison.ada b/Task/String-comparison/Ada/string-comparison.ada new file mode 100644 index 0000000000..cdb37d778e --- /dev/null +++ b/Task/String-comparison/Ada/string-comparison.ada @@ -0,0 +1,27 @@ +with Ada.Text_IO, Ada.Characters.Handling; + +procedure String_Compare is + + procedure Print_Comparison (A, B: String) is + use Ada.Text_IO, Ada.Characters.Handling; + begin + Put_Line + ( """" & A & """ and """ & B & """: " & + (if A = B then "equal, " elsif To_Lower(A) = To_Lower(B) + then "case-insensitive-equal, " else "not equal at all, ") & + (if A /= B then "/=, " else "") & + (if A < B then "before, " else "") & + (if A > B then "after, " else "") & + (if A <= B then "<=, " else "(not <=), ") & "and " & + (if A >= B then ">=. " else "(not >=).") ); + end Print_Comparison; + +begin + Print_Comparison("this", "that"); + Print_Comparison("that", "this"); + Print_Comparison("THAT", "That"); + Print_Comparison("this", "This"); + Print_Comparison("this", "this"); + Print_Comparison("the", "there"); + Print_Comparison("there", "the"); +end String_Compare; diff --git a/Task/String-comparison/Bracmat/string-comparison.bracmat b/Task/String-comparison/Bracmat/string-comparison.bracmat new file mode 100644 index 0000000000..ee5d115a27 --- /dev/null +++ b/Task/String-comparison/Bracmat/string-comparison.bracmat @@ -0,0 +1,102 @@ +( {Comparing two strings for exact equality} +& ( ( @(abc:abc) + & @(123:%123) + {Previous pairs of strings are exactly equal} + ) + & ( @(abc:Abc) + | @(123:%246/2) + | @(abc:ab) + | @(123:%12) + | {Previous pairs of strings are not exactly equal} + ) + ) + {Comparing two strings for inequality (i.e., the inverse of exact equality)} +& ( ( @(abc:~<>abc) + & @(abc:~<>Abc) + {Previous pairs of strings are more or less equal} + ) + & ( @(abc:~<>ab) + | {Previous pairs of strings are not more or less equal} + ) + ) + {Comparing two strings to see if one is lexically ordered before than the other} +& ( ( @(Abc:<abc) + & @(Abc:<a) + & @(123:<%246/2) + & @(123:<%2) + & @(12:<%123) + & @(ab:<abc) + {Previous pairs of strings are lexically ordered one before the other} + ) + & ( @(abc:<abc) + | @(abc:<Abc) + | @(246/2:<%123) + | @(abc:<ab) + | @(123:<%12) + | @(123:<%123) + | {Previous pairs of strings are not lexically ordered one before the other} + ) + ) + {Comparing two strings to see if one is lexically ordered after than the other} +& ( ( @(abc:>Abc) + & @(a:>Abc) + & @(246/2:>%123) + & @(2:>%123) + & @(123:>%12) + & @(abc:>ab) + {Previous pairs of strings are lexically ordered one after the other} + ) + & ( @(abc:>abc) + | @(Abc:>abc) + | @(123:>%246/2) + | @(ab:>abc) + | @(12:>%123) + | @(123:>%123) + | {Previous pairs of strings are not lexically ordered one after the other} + ) + ) + {How to achieve both case sensitive comparisons and case insensitive comparisons within + the language} +& ( ( @(abc:~<>abc) + & @(abc:~<>Abc) + & @(БЪЛГАРСКИ:~<>български) + {Previous pairs of strings are more or less equal} + ) + & ( @(abc:~<>ab) + | {Previous pairs of strings are not more or less equal} + ) + ) + {How the language handles comparison of numeric strings if these are not treated lexically} +& ( ( @(246/2:123) + & @(2:<123) + & @(123:>12) + & @(123:246/2) + & @(12:<123) + {Previous numeric string comparisons succeed} + ) + & ( @(123:<246/2) + | @(12:>123) + | @(123:>123) + | @(123:~123) + | {Previous numeric string comparisons fail} + ) + ) + {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.} +& ( ( @(246/2:>12--3) + & @(2:>123kg) + & @(123:<12d) + & @(123:~24/6/2) + & @(12a:>123) + {Previous coercive string comparisons succeed} + ) + & ( @(2013-05-01:20130501) + | @(246/2a:123a) + | @(1239:<123-) + | {Previous coercive string comparisons fail} + ) + ) +& done +); diff --git a/Task/String-comparison/C/string-comparison-1.c b/Task/String-comparison/C/string-comparison-1.c new file mode 100644 index 0000000000..c40e20d337 --- /dev/null +++ b/Task/String-comparison/C/string-comparison-1.c @@ -0,0 +1,2 @@ +/* WRONG! */ +if (strcmp(a,b)) action_on_equality(); diff --git a/Task/String-comparison/C/string-comparison-2.c b/Task/String-comparison/C/string-comparison-2.c new file mode 100644 index 0000000000..f9c6a0945d --- /dev/null +++ b/Task/String-comparison/C/string-comparison-2.c @@ -0,0 +1,61 @@ +/* + compilation and test in bash + $ a=./c && make $a && $a ball bell ball ball YUP YEP ball BELL ball BALL YUP yep + cc -Wall -c -o c.o c.c + eq , ne , gt , lt , ge , le + ball 0 1 0 1 0 1 bell + ball 0 1 0 1 0 1 bell ignoring case + ball 1 0 0 0 1 1 ball + ball 1 0 0 0 1 1 ball ignoring case + YUP 0 1 1 0 1 0 YEP + YUP 0 1 1 0 1 0 YEP ignoring case + ball 0 1 1 0 1 0 BELL + ball 0 1 0 1 0 1 BELL ignoring case + ball 0 1 1 0 1 0 BALL + ball 1 0 0 0 1 1 BALL ignoring case + YUP 0 1 0 1 0 1 yep + YUP 0 1 1 0 1 0 yep ignoring case +*/ + +#include<string.h> + +#define STREQ(A,B) (0==strcmp((A),(B))) +#define STRNE(A,B) (!STREQ(A,B)) +#define STRLT(A,B) (strcmp((A),(B))<0) +#define STRLE(A,B) (strcmp((A),(B))<=0) +#define STRGT(A,B) STRLT(B,A) +#define STRGE(A,B) STRLE(B,A) + +#define STRCEQ(A,B) (0==strcasecmp((A),(B))) +#define STRCNE(A,B) (!STRCEQ(A,B)) +#define STRCLT(A,B) (strcasecmp((A),(B))<0) +#define STRCLE(A,B) (strcasecmp((A),(B))<=0) +#define STRCGT(A,B) STRCLT(B,A) +#define STRCGE(A,B) STRCLE(B,A) + +#include<stdio.h> + +void compare(const char*a, const char*b) { + printf("%s%2d%2d%2d%2d%2d%2d %s\n", + a, + STREQ(a,b), STRNE(a,b), STRGT(a,b), STRLT(a,b), STRGE(a,b), STRLE(a,b), + b + ); +} +void comparecase(const char*a, const char*b) { + printf("%s%2d%2d%2d%2d%2d%2d %s ignoring case\n", + a, + STRCEQ(a,b), STRCNE(a,b), STRCGT(a,b), STRCLT(a,b), STRCGE(a,b), STRCLE(a,b), + b + ); +} +int main(int ac, char*av[]) { + char*a,*b; + puts("\teq , ne , gt , lt , ge , le"); + while (0 < (ac -= 2)) { + a = *++av, b = *++av; + compare(a, b); + comparecase(a, b); + } + return 0; +} diff --git a/Task/String-comparison/Erlang/string-comparison.erl b/Task/String-comparison/Erlang/string-comparison.erl new file mode 100644 index 0000000000..e27ee04b3c --- /dev/null +++ b/Task/String-comparison/Erlang/string-comparison.erl @@ -0,0 +1,12 @@ +10> V = "abcd". +"abcd" +11> V =:= "abcd". +true +12> V =/= "abcd". +false +13> V < "b". +true +15> V > "aa". +true +16> string:to_lower(V) =:= string:to_lower("ABCD"). +true diff --git a/Task/String-comparison/Forth/string-comparison.fth b/Task/String-comparison/Forth/string-comparison.fth new file mode 100644 index 0000000000..d36e5a94e7 --- /dev/null +++ b/Task/String-comparison/Forth/string-comparison.fth @@ -0,0 +1,6 @@ +: str-eq ( str len str len -- ? ) compare 0= ; +: str-neq ( str len str len -- ? ) compare 0<> ; +: str-lt ( str len str len -- ? ) compare 0< ; +: str-gt ( str len str len -- ? ) compare 0> ; +: str-le ( str len str len -- ? ) compare 0<= ; +: str-ge ( str len str len -- ? ) compare 0>= ; diff --git a/Task/String-comparison/Lua/string-comparison.lua b/Task/String-comparison/Lua/string-comparison.lua new file mode 100644 index 0000000000..36cd6671ac --- /dev/null +++ b/Task/String-comparison/Lua/string-comparison.lua @@ -0,0 +1,19 @@ +function compare(a, b) + print(("%s is of type %s and %s is of type %s"):format( + a, type(a), + b, type(b) + )) + if a < b then print(('%s is strictly less than %s'):format(a, b)) end + if a <= b then print(('%s is less than or equal to %s'):format(a, b)) end + if a > b then print(('%s is strictly greater than %s'):format(a, b)) end + if a >= b then print(('%s is greater than or equal to %s'):format(a, b)) end + if a == b then print(('%s is equal to %s'):format(a, b)) end + if a ~= b then print(('%s is not equal to %s'):format(a, b)) end + print "" +end + +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-1.rexx b/Task/String-comparison/REXX/string-comparison-1.rexx new file mode 100644 index 0000000000..8b9934678e --- /dev/null +++ b/Task/String-comparison/REXX/string-comparison-1.rexx @@ -0,0 +1,17 @@ +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 any 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/REXX/string-comparison-2.rexx b/Task/String-comparison/REXX/string-comparison-2.rexx new file mode 100644 index 0000000000..046a354787 --- /dev/null +++ b/Task/String-comparison/REXX/string-comparison-2.rexx @@ -0,0 +1,23 @@ +/* REXX *************************************************************** +* 16.05.2013 Walter Pachl +**********************************************************************/ +Call test 'A','<','a' +Call test 'A','=',' a' +Call test 'A','==',' a' +Call test 'Walter','<',' Wolter' +Exit + +test: Procedure +Parse Arg o1,op,o2 +Say q(o1) op q(o2) '->' clcompare(o1,op,o2) +Return + +clcompare: Procedure +/* caseless comparison of the operands */ +Parse Arg opd1,op,opd2 +opd1u=translate(opd1) +opd2u=translate(opd2) +Interpret 'res=opd1u' op 'opd2u' +Return res + +q: Return '"'arg(1)'"' diff --git a/Task/String-comparison/Seed7/string-comparison-1.seed7 b/Task/String-comparison/Seed7/string-comparison-1.seed7 new file mode 100644 index 0000000000..99362b4b45 --- /dev/null +++ b/Task/String-comparison/Seed7/string-comparison-1.seed7 @@ -0,0 +1,25 @@ +$ include "seed7_05.s7i"; + +const proc: showComparisons (in string: a, in string: b) is func + begin + writeln("compare " <& literal(a) <& " with " <& literal(b) <&":"); + writeln("a = b returns: " <& a = b); + writeln("a <> b returns: " <& a <> b); + writeln("a < b returns: " <& a < b); + writeln("a > b returns: " <& a > b); + writeln("a <= b returns: " <& a <= b); + writeln("a >= b returns: " <& a >= b); + writeln("compare(a, b) returns: " <& compare(a, b)); + writeln("compare(lower(a), lower(b)) returns: " <& compare(a, b)); + end func; + +const proc: main is func + begin + showComparisons("this", "that"); + showComparisons("that", "this"); + showComparisons("THAT", "That"); + showComparisons("this", "This"); + showComparisons("this", "this"); + showComparisons("the", "there"); + showComparisons("there", "the"); + end func; diff --git a/Task/String-comparison/Seed7/string-comparison-2.seed7 b/Task/String-comparison/Seed7/string-comparison-2.seed7 new file mode 100644 index 0000000000..c9ece86681 --- /dev/null +++ b/Task/String-comparison/Seed7/string-comparison-2.seed7 @@ -0,0 +1,35 @@ +include "scanstri.s7i"; + +const func integer: cmpNumeric (in var string: stri1, in var string: stri2) is func + result + var integer: signumValue is 0; + local + var string: part1 is ""; + var string: part2 is ""; + begin + while signumValue = 0 and (stri1 <> "" or stri2 <> "") do + part1 := getDigits(stri1); + part2 := getDigits(stri2); + if part1 <> "" and part2 <> "" then + signumValue := compare(part1 lpad0 length(part2), part2 lpad0 length(part1)); + if signumValue = 0 then + signumValue := compare(length(part1), length(part2)); + end if; + elsif part1 <> "" then + signumValue := compare(part1, stri2); + elsif part2 <> "" then + signumValue := compare(stri1, part2); + end if; + if signumValue = 0 then + part1 := getNonDigits(stri1); + part2 := getNonDigits(stri2); + if part1 <> "" and part2 <> "" then + signumValue := compare(part1, part2); + elsif part1 <> "" then + signumValue := compare(part1, stri2); + elsif part2 <> "" then + signumValue := compare(stri1, part2); + end if; + end if; + end while; + end func; diff --git a/Task/String-comparison/UNIX-Shell/string-comparison-1.sh b/Task/String-comparison/UNIX-Shell/string-comparison-1.sh new file mode 100644 index 0000000000..17dd300f52 --- /dev/null +++ b/Task/String-comparison/UNIX-Shell/string-comparison-1.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-comparison/UNIX-Shell/string-comparison-2.sh b/Task/String-comparison/UNIX-Shell/string-comparison-2.sh new file mode 100644 index 0000000000..4fef70be37 --- /dev/null +++ b/Task/String-comparison/UNIX-Shell/string-comparison-2.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +isint() { + printf "%d" $1 >/dev/null 2>&1 +} + +compare() { + local a=$1 + local b=$2 + + [[ $a = $b ]] && echo "'$a' and '$b' are lexically equal" + [[ $a != $b ]] && echo "'$a' and '$b' are not lexically equal" + + [[ $a > $b ]] && echo "'$a' is lexically after '$b'" + [[ $a < $b ]] && echo "'$a' is lexically before '$b'" + + shopt -s nocasematch # Turn on case insensitivity + + [[ $a = $b ]] && echo "'$a' and '$b' are equal with case insensitivity" + + shopt -u nocasematch # Turn off case insensitivity + + # If args are numeric, perform some numeric comparisions + if isint $a && isint $b + then + [[ $a -eq $b ]] && echo "$a is numerically equal to $b" + [[ $a -gt $b ]] && echo "$a is numerically greater than $b" + [[ $a -lt $b ]] && echo "$a is numerically less than $b" + fi + + echo +} + + +compare foo foo +compare foo bar +compare FOO foo +compare 24 123 +compare 50 20 diff --git a/Task/String-concatenation/Aime/string-concatenation.aime b/Task/String-concatenation/Aime/string-concatenation.aime new file mode 100644 index 0000000000..923b9968f8 --- /dev/null +++ b/Task/String-concatenation/Aime/string-concatenation.aime @@ -0,0 +1,8 @@ +text s, v; + +s = "Hello"; +o_text(s); +o_newline(); +v = cat(s, ", World!"); +o_text(v); +o_newline(); diff --git a/Task/String-concatenation/AppleScript/string-concatenation.applescript b/Task/String-concatenation/AppleScript/string-concatenation.applescript new file mode 100644 index 0000000000..2f618e6f26 --- /dev/null +++ b/Task/String-concatenation/AppleScript/string-concatenation.applescript @@ -0,0 +1,5 @@ +try + set endMsg to "world!" + set totMsg to "Hello, " & endMsg + display dialog totMsg +end try diff --git a/Task/String-concatenation/COBOL/string-concatenation.cobol b/Task/String-concatenation/COBOL/string-concatenation.cobol new file mode 100644 index 0000000000..21f63d2303 --- /dev/null +++ b/Task/String-concatenation/COBOL/string-concatenation.cobol @@ -0,0 +1,15 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Concat. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Str PIC X(7) VALUE "Hello, ". + 01 Str2 PIC X(15). + + PROCEDURE DIVISION. + DISPLAY "Str : " Str + MOVE FUNCTION CONCATENATE(Str, " World!") TO Str2 + DISPLAY "Str2 : " Str2 + + GOBACK + . diff --git a/Task/String-concatenation/Racket/string-concatenation.rkt b/Task/String-concatenation/Racket/string-concatenation.rkt new file mode 100644 index 0000000000..45bb353397 --- /dev/null +++ b/Task/String-concatenation/Racket/string-concatenation.rkt @@ -0,0 +1,10 @@ +#lang racket +(define hello "hello") +(displayln hello) + +(define world (string-append hello " " "world" "!")) +(displayln world) + +;outputs: +; hello +; hello world! diff --git a/Task/String-concatenation/Raven/string-concatenation.raven b/Task/String-concatenation/Raven/string-concatenation.raven new file mode 100644 index 0000000000..c8ddc58bb5 --- /dev/null +++ b/Task/String-concatenation/Raven/string-concatenation.raven @@ -0,0 +1,15 @@ +# Cat strings +"First string and " "second string" cat print + +# Join +[ "First string" "second string" "third string" ] " and " join print + +# print +[ "First string" "second string" "third string" ] each print + +# Formatted print +"\n" "Third string" "Second string" "First string" "%s %s %s %s" print + +# Heredoc +" - NOT!!" as $x +"This is the only way to do it%($x)s" print diff --git a/Task/String-length/Aime/string-length.aime b/Task/String-length/Aime/string-length.aime new file mode 100644 index 0000000000..05bc619409 --- /dev/null +++ b/Task/String-length/Aime/string-length.aime @@ -0,0 +1 @@ +length("Hello, World!") diff --git a/Task/String-length/Racket/string-length-1.rkt b/Task/String-length/Racket/string-length-1.rkt new file mode 100644 index 0000000000..c067f5a875 --- /dev/null +++ b/Task/String-length/Racket/string-length-1.rkt @@ -0,0 +1 @@ +(define str "J\u0332o\u0332s\u0332e\u0301\u0332") diff --git a/Task/String-length/Racket/string-length-2.rkt b/Task/String-length/Racket/string-length-2.rkt new file mode 100644 index 0000000000..c0546e286c --- /dev/null +++ b/Task/String-length/Racket/string-length-2.rkt @@ -0,0 +1,2 @@ +-> (printf "str has ~a characters" (string-length str)) +str has 9 characters diff --git a/Task/String-length/Racket/string-length-3.rkt b/Task/String-length/Racket/string-length-3.rkt new file mode 100644 index 0000000000..7231528480 --- /dev/null +++ b/Task/String-length/Racket/string-length-3.rkt @@ -0,0 +1,2 @@ +-> (printf "str has ~a bytes in utf-8" (bytes-length (string->bytes/utf-8 str))) +str has 14 bytes in utf-8 diff --git a/Task/String-length/Ruby/string-length-1.rb b/Task/String-length/Ruby/string-length-1.rb new file mode 100644 index 0000000000..a1e56ed2df --- /dev/null +++ b/Task/String-length/Ruby/string-length-1.rb @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- + +puts "あいうえお".bytesize +# => 15 diff --git a/Task/String-length/Ruby/string-length-2.rb b/Task/String-length/Ruby/string-length-2.rb new file mode 100644 index 0000000000..47fcaa7776 --- /dev/null +++ b/Task/String-length/Ruby/string-length-2.rb @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- + +puts "あいうえお".length +# => 5 + +puts "あいうえお".size # alias for length +# => 5 diff --git a/Task/String-length/Ruby/string-length-3.rb b/Task/String-length/Ruby/string-length-3.rb new file mode 100644 index 0000000000..2a53b6cdfc --- /dev/null +++ b/Task/String-length/Ruby/string-length-3.rb @@ -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/Ruby/string-length-4.rb b/Task/String-length/Ruby/string-length-4.rb new file mode 100644 index 0000000000..af1ce7cb7f --- /dev/null +++ b/Task/String-length/Ruby/string-length-4.rb @@ -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/Ruby/string-length-5.rb b/Task/String-length/Ruby/string-length-5.rb new file mode 100644 index 0000000000..108634387d --- /dev/null +++ b/Task/String-length/Ruby/string-length-5.rb @@ -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/Ruby/string-length-6.rb b/Task/String-length/Ruby/string-length-6.rb new file mode 100644 index 0000000000..ac153f7564 --- /dev/null +++ b/Task/String-length/Ruby/string-length-6.rb @@ -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/Run-BASIC/string-length.run b/Task/String-length/Run-BASIC/string-length.run new file mode 100644 index 0000000000..16a5f26bfc --- /dev/null +++ b/Task/String-length/Run-BASIC/string-length.run @@ -0,0 +1,2 @@ +input a$ +print len(a$) 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 index 2d95d6c5b6..dbaf848ea7 100644 --- 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 @@ -1,22 +1,9 @@ -/* 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 +/*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.*/ +/*───────────────────────────────────STRIPCHARS 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-2.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx index 69cfc3a877..4b1d54aa04 100644 --- 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 @@ -1,9 +1,12 @@ -/*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 +/* REXX *************************************************************** +* If source and stripchars don't contain a hex 00 character, this works +* 06.07.2012 Walter Pachl +**********************************************************************/ +Say 'Sh ws soul strppr. Sh took my hrt! -- expected' +Say stripchars("She was a soul stripper. She took my heart!","aei") +Exit +stripchars: Parse Arg string,stripchars +result=translate(string,'00'x,' ') /* turn blanks into '00'x */ +result=translate(result,' ',stripchars) /* turn stripchars into ' ' */ +result=space(result,0) /* remove all blanks */ +Return translate(result,' ','00'x) /* '00'x back to blanks */ 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 index f1e6eb5a74..b6b9647afd 100644 --- 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 @@ -1,26 +1,9 @@ -/*╔══════════════════════════════╗ 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<b then $=$ || y || o /*didn't meet begin at ? */ - else do - $=$ || y || n /*build new STR from S. */ - #=#+1 /*bump occurance number. */ - end - end /*j*/ - /*Most REXX BIFs only ···*/ -return $ || h /* support three options.*/ +stripchars: Procedure + Parse Arg i,s /* get input and chars to be removed */ + o='' /* initialize result */ + Do While i\=='' /* loop through input */ + Parse Var i c +1 i /* get one character */ + If pos(c,s)=0 Then /* it's not to be removed */ + o=o||c /* append it to the result */ + End + Return o /* return the result */ diff --git a/Task/Strip-a-set-of-characters-from-a-string/Racket/strip-a-set-of-characters-from-a-string.rkt b/Task/Strip-a-set-of-characters-from-a-string/Racket/strip-a-set-of-characters-from-a-string.rkt new file mode 100644 index 0000000000..11b7fea1fc --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Racket/strip-a-set-of-characters-from-a-string.rkt @@ -0,0 +1,10 @@ +#lang racket + +;; Using list operations +(define (stripchars1 text chars) + (list->string (remove* (string->list chars) (string->list text)))) + +;; Using a regexp +;; => will be broken if chars have "-" or "]" or "\\" +(define (stripchars2 text chars) + (regexp-replace* (~a "[" chars "]+") text "")) diff --git a/Task/Strip-block-comments/Racket/strip-block-comments.rkt b/Task/Strip-block-comments/Racket/strip-block-comments.rkt new file mode 100644 index 0000000000..979bec6fe3 --- /dev/null +++ b/Task/Strip-block-comments/Racket/strip-block-comments.rkt @@ -0,0 +1,28 @@ +#lang at-exp racket + +;; default delimiters (strings -- not regexps) +(define comment-start-str "/*") +(define comment-end-str "*/") + +(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str]) + (regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2)) + text "")) + +((compose1 displayln strip-comments) + @~a{/** + * 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-comments-from-a-string/Racket/strip-comments-from-a-string.rkt b/Task/Strip-comments-from-a-string/Racket/strip-comments-from-a-string.rkt new file mode 100644 index 0000000000..6fc1c44aaa --- /dev/null +++ b/Task/Strip-comments-from-a-string/Racket/strip-comments-from-a-string.rkt @@ -0,0 +1,20 @@ +#lang at-exp racket + +(define comment-start-rx "[;#]") + +(define text + @~a{apples, pears # and bananas + apples, pears ; and bananas + }) + +(define (strip-comments text [rx comment-start-rx]) + (string-join + (for/list ([line (string-split text "\n")]) + (string-trim line (pregexp (~a "\\s*" rx ".*")) #:left? #f)) + "\n")) + +;; Alternatively, do it in a single regexp operation +(define (strip-comments2 text [rx comment-start-rx]) + (regexp-replace* (pregexp (~a "(?m:\\s*" rx ".*)")) text "")) + +(strip-comments2 text) ; -> "apples, pears\napples, pears" diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Racket/strip-control-codes-and-extended-characters-from-a-string.rkt b/Task/Strip-control-codes-and-extended-characters-from-a-string/Racket/strip-control-codes-and-extended-characters-from-a-string.rkt new file mode 100644 index 0000000000..10a54e884e --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Racket/strip-control-codes-and-extended-characters-from-a-string.rkt @@ -0,0 +1,6 @@ +#lang racket +;; Works on both strings (Unicode) and byte strings (raw/ASCII) +(define (strip-controls str) + (regexp-replace* #rx"[\0-\037\177]+" str "")) +(define (strip-controls-and-extended str) + (regexp-replace* #rx"[^\040-\176]+" str "")) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Erlang/strip-whitespace-from-a-string-top-and-tail.erl b/Task/Strip-whitespace-from-a-string-Top-and-tail/Erlang/strip-whitespace-from-a-string-top-and-tail.erl new file mode 100644 index 0000000000..4466da13d3 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Erlang/strip-whitespace-from-a-string-top-and-tail.erl @@ -0,0 +1,9 @@ +% Implemented by Arjun Sunel +1> string:strip(" Hello World! ", left). %remove leading whitespaces +"Hello World! " + +2> string:strip(" Hello World! ", right). % remove trailing whitespaces +" Hello World!" + +3> string:strip(" Hello World! ", both). % remove both leading and trailing whitespace +"Hello World!" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Factor/strip-whitespace-from-a-string-top-and-tail.factor b/Task/Strip-whitespace-from-a-string-Top-and-tail/Factor/strip-whitespace-from-a-string-top-and-tail.factor new file mode 100644 index 0000000000..1f7ea9d514 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Factor/strip-whitespace-from-a-string-top-and-tail.factor @@ -0,0 +1,4 @@ +USING: unicode.categories; +" test string " [ blank? ] trim ! leading and trailing +" test string " [ blank? ] trim-head ! only leading +" test string " [ blank? ] trim-tail ! only trailing 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 index 8115a5fe98..e2b3250b87 100644 --- 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 @@ -1,6 +1,6 @@ /*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. " +yyy=" this is a string that has leading/embedded/trailing blanks, fur shure. " /*white space also includes tabs (VT & HT),*/ /*among other characters. */ diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Racket/strip-whitespace-from-a-string-top-and-tail.rkt b/Task/Strip-whitespace-from-a-string-Top-and-tail/Racket/strip-whitespace-from-a-string-top-and-tail.rkt new file mode 100644 index 0000000000..893d5a79db --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Racket/strip-whitespace-from-a-string-top-and-tail.rkt @@ -0,0 +1,15 @@ +#lang racket + +;; Using Racket's `string-trim' + +(define str " \n\t foo bar \r\n ") + +;; both sides: +(string-trim str) ; -> "foo bar" + +;; one side: +(string-trim str #:right? #f) ; -> "foo bar \r\n " +(string-trim str #:left? #f) ; -> " \n\t foo bar" + +;; can also normalize spaces: +(string-normalize-spaces (string-trim str)) ; -> "foo bar" diff --git a/Task/Substring-Top-and-tail/Aime/substring-top-and-tail.aime b/Task/Substring-Top-and-tail/Aime/substring-top-and-tail.aime new file mode 100644 index 0000000000..e69e5e7ebb --- /dev/null +++ b/Task/Substring-Top-and-tail/Aime/substring-top-and-tail.aime @@ -0,0 +1,6 @@ +o_text(delete("knights", 0)); +o_newline(); +o_text(delete("knights", -1)); +o_newline(); +o_text(delete(delete("knights", 0), -1)); +o_newline(); diff --git a/Task/Substring-Top-and-tail/Erlang/substring-top-and-tail.erl b/Task/Substring-Top-and-tail/Erlang/substring-top-and-tail.erl new file mode 100644 index 0000000000..c2e4ce551b --- /dev/null +++ b/Task/Substring-Top-and-tail/Erlang/substring-top-and-tail.erl @@ -0,0 +1,6 @@ +% Implemented by Arjun Sunel +string:left("Hello", length("Hello")-1,$.). % To strip the word from the right by 1 + +string:right("Hello", length("Hello")-1,$.). % To strip the word from the left by 1 + +string:left(string:right("Hello", length("Hello")-1,$.), length("Hello")-2,$.). %To strip the word from both sides by 1. diff --git a/Task/Substring-Top-and-tail/Logo/substring-top-and-tail.logo b/Task/Substring-Top-and-tail/Logo/substring-top-and-tail.logo new file mode 100644 index 0000000000..91a6785fff --- /dev/null +++ b/Task/Substring-Top-and-tail/Logo/substring-top-and-tail.logo @@ -0,0 +1,4 @@ +make "s "|My string| +print butfirst :s +print butlast :s +print butfirst butlast :s diff --git a/Task/Substring-Top-and-tail/Raven/substring-top-and-tail.raven b/Task/Substring-Top-and-tail/Raven/substring-top-and-tail.raven new file mode 100644 index 0000000000..df08c5b429 --- /dev/null +++ b/Task/Substring-Top-and-tail/Raven/substring-top-and-tail.raven @@ -0,0 +1,15 @@ +define println use $s + $s print "\n" print + +"0123456789" as $str + +define offTheTop use $s + $s 1 0x7FFFFFFF extract + +define offTheTail use $s + $s 0 -1 extract + + +$str offTheTop println +$str offTheTail println +$str offTheTop offTheTail println diff --git a/Task/Substring/Racket/substring.rkt b/Task/Substring/Racket/substring.rkt new file mode 100644 index 0000000000..f4253c5e1d --- /dev/null +++ b/Task/Substring/Racket/substring.rkt @@ -0,0 +1,25 @@ +#lang racket + +(define str "abcdefghijklmnopqrstuvwxyz") + +(define n 10) +(define m 2) +(define start-char #\x) +(define start-str "xy") + +;; starting from n characters in and of m length; +(substring str n (+ n m)) ; -> "kl" + +;; starting from n characters in, up to the end of the string; +(substring str m) ; -> "klmnopqrstuvwxyz" + +;; whole string minus last character; +(substring str 0 (sub1 (string-length str))) ; -> "abcdefghijklmnopqrstuvwxy" + +;; starting from a known character within the string and of m length; +(substring str (caar (regexp-match-positions (regexp-quote (string start-char)) + str))) ; -> "xyz" + +;; starting from a known substring within the string and of m length. +(substring str (caar (regexp-match-positions (regexp-quote start-str) + str))) ; -> "xyz" diff --git a/Task/Substring/Raven/substring.raven b/Task/Substring/Raven/substring.raven new file mode 100644 index 0000000000..991d07be80 --- /dev/null +++ b/Task/Substring/Raven/substring.raven @@ -0,0 +1,26 @@ +define println use $s + $s print "\n" print + +"0123456789" as $str + +$str 3 2 extract println # at 4th pos get 2 chars +$str 8 4 extract println # at 9th pos get 4 chars (when only 1 char available) + + +$str 3 $str length extract println # at 4th pos get all chars to end of str +$str 3 0x7FFFFFFF extract println # at 4th pos get all chars to end of str + +$str 3 -1 extract println # at 4th pos get rest of chars but last one +$str 0 -1 extract println # all chars but last one + +"3" as $matchChr # starting chr for extraction +4 as $subLen # Nr chars after found starting char +$str $matchChr split as $l +"" $l 0 set $l $matchChr join +0 $subLen extract println + +"345" as $matchChrs # starting chrs for extraction +6 as $subLen # Nr chars after found starting chars +$str $matchChrs split as $l +"" $l 0 set $l $matchChrs join +0 $subLen extract println diff --git a/Task/Substring/Ruby/substring.rb b/Task/Substring/Ruby/substring.rb index 5b9b1b06d9..c3aff23642 100644 --- a/Task/Substring/Ruby/substring.rb +++ b/Task/Substring/Ruby/substring.rb @@ -1,9 +1,10 @@ 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/] +puts str[n, m] #=> cde +puts str[n..m] #=> cd +puts str[n..-1] #=> cdefgh +puts str[0..-2] #=> abcdefg +puts str[str.index('d'), m] #=> def +puts str[str.index('de'), m] #=> def +puts str[/a.*d/] #=> abcd diff --git a/Task/Subtractive-generator/Racket/subtractive-generator.rkt b/Task/Subtractive-generator/Racket/subtractive-generator.rkt new file mode 100644 index 0000000000..2e8a717850 --- /dev/null +++ b/Task/Subtractive-generator/Racket/subtractive-generator.rkt @@ -0,0 +1,30 @@ +#lang racket +(define (make-initial-state a-list max-i) + (for/fold ((state a-list)) + ((i (in-range (length a-list) max-i))) + (append state (list (- (list-ref state (- i 2)) (list-ref state (- i 1))))))) ;from the seed and 1 creates the initial state + +(define (shuffle a-list) + (for/list ((i (in-range (length a-list)))) + (list-ref a-list (modulo (* 34 (add1 i)) 55)))) ;shuffles the state + +(define (advance-state state (times 1)) + (cond ((= 0 times) state) + (else (advance-state + (cdr (append state + (list (modulo (- (list-ref state 0) (list-ref state 31)) + (expt 10 9))))) + (sub1 times))))) ;takes a state and the times it must be advanced, and returns the new state + +(define (create-substractive-generator s0) + (define s1 1) + (define first-state (make-initial-state (list s0 s1) 55)) + (define shuffled-state (shuffle first-state)) + (define last-state (advance-state shuffled-state 165)) + (lambda ((m (expt 10 9))) + (define new-state (advance-state last-state)) + (set! last-state new-state) + (modulo (car (reverse last-state)) m))) ;the lambda is a function with an optional argument + ;that returns a new random number each time it's called +(define rand (create-substractive-generator 292929)) +(build-list 3 (lambda (_) (rand))) ;returns a list made from the 3 wanted numbers diff --git a/Task/Subtractive-generator/Seed7/subtractive-generator.seed7 b/Task/Subtractive-generator/Seed7/subtractive-generator.seed7 new file mode 100644 index 0000000000..d7223b18a9 --- /dev/null +++ b/Task/Subtractive-generator/Seed7/subtractive-generator.seed7 @@ -0,0 +1,54 @@ +$ include "seed7_05.s7i"; + +const integer: MOD is 1000000000; + +const type: subtractiveGenerator is new struct + var array integer: state is [0 .. 54] times 0; + var integer: si is 0; + var integer: sj is 24; + end struct; + +const func integer: subrand (inout subtractiveGenerator: generator) is forward; + +const func subtractiveGenerator: subrandSeed (in var integer: p1) is func + result + var subtractiveGenerator: generator is subtractiveGenerator.value; + local + var integer: p2 is 1; + var integer: i is 0; + var integer: j is 21; + begin + generator.state[0] := p1 mod MOD; + for i range 1 to 54 do + generator.state[j] := p2; + p2 := (p1 - p2) mod MOD; + p1 := generator.state[j]; + j := (j + 21) mod 55; + end for; + for i range 1 to 165 do + ignore(subrand(generator)); + end for; + end func; + +const func integer: subrand (inout subtractiveGenerator: generator) is func + result + var integer: subrand is 0; + begin + if generator.si = generator.sj then + generator := subrandSeed(0); + end if; + generator.si := pred(generator.si) mod 55; + generator.sj := pred(generator.sj) mod 55; + subrand := (generator.state[generator.si] - generator.state[generator.sj]) mod MOD; + generator.state[generator.si] := subrand; + end func; + +const proc: main is func + local + var subtractiveGenerator: gen is subrandSeed(292929); + var integer: i is 0; + begin + for i range 1 to 10 do + writeln(subrand(gen)); + end for; + end func; diff --git a/Task/Sudoku/Java/sudoku.java b/Task/Sudoku/Java/sudoku.java index 70f69ff73e..ada5967fd1 100644 --- a/Task/Sudoku/Java/sudoku.java +++ b/Task/Sudoku/Java/sudoku.java @@ -20,8 +20,9 @@ public class Sudoku for(int i = 0; i < mBoard.length; i++) { for(int j = 0; j < mBoard.length; j++) { int value = mBoard[i][j]; - if(value != 0) + if(value != 0) { setSubsetValue(i, j, value, true); + } } } } @@ -39,19 +40,23 @@ public class Sudoku public boolean solve(int i, int j) { if(i == mBoardSize) { i = 0; - if(++j == mBoardSize) + if(++j == mBoardSize) { return true; + } } - if(mBoard[i][j] != 0) + if(mBoard[i][j] != 0) { return solve(i + 1, j); - for(int value = 1; value <= mBoardSize; value++) + } + 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)) + if(solve(i + 1, j)) { return true; + } setSubsetValue(i, j, value, false); } + } mBoard[i][j] = 0; return false; @@ -71,11 +76,13 @@ public class Sudoku public void print() { for(int i = 0; i < mBoardSize; i++) { - if(i % mBoxSize == 0) + if(i % mBoxSize == 0) { System.out.println(" -----------------------"); + } for(int j = 0; j < mBoardSize; j++) { - if(j % mBoxSize == 0) + if(j % mBoxSize == 0) { System.out.print("| "); + } System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : " "); System.out.print(' '); } diff --git a/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-1.l b/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-1.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-1.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/Emacs-Lisp/sum-and-product-of-an-array-2.l b/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-2.l new file mode 100644 index 0000000000..729a75bb13 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-2.l @@ -0,0 +1,3 @@ +(setq array '(1 2 3 4 5)) +(apply '+ array) +(apply '* array) diff --git a/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-3.l b/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-3.l new file mode 100644 index 0000000000..3c41d01903 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-3.l @@ -0,0 +1,3 @@ +(setq array [1 2 3 4 5]) +(apply '+ (append array nil)) +(apply '* (append array nil)) 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 index 4c2715be73..e545bc575c 100644 --- 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 @@ -1,21 +1,19 @@ +import std.stdio, std.bigint; + 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) { + for ( ; n; n /= base) 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))); + sumDigits(1).writeln; + sumDigits(1_234).writeln; + sumDigits(0xfe, 16).writeln; + sumDigits(0xf0e, 16).writeln; + sumDigits(1_234.BigInt).writeln; } diff --git a/Task/Sum-digits-of-an-integer/Forth/sum-digits-of-an-integer.fth b/Task/Sum-digits-of-an-integer/Forth/sum-digits-of-an-integer.fth new file mode 100644 index 0000000000..4aded6feb5 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Forth/sum-digits-of-an-integer.fth @@ -0,0 +1,5 @@ +: sum_int 0 begin over while swap base @ /mod swap rot + repeat nip ; + + 2 base ! 11110 sum_int decimal . cr +10 base ! 12345 sum_int decimal . cr +16 base ! f0e sum_int decimal . cr 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 index 8144ba49aa..cdb787cd51 100644 --- 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 @@ -1,29 +1,15 @@ def toBaseX(num, base): - output = [] - index = 0 - while num: - num, rem = divmod(num, base) - output.append(str(rem)) - return output + output = [] + while num: + num, rem = divmod(num, base) + output.append(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 +def sumDigits(num, base=10): + if base < 2: + print "Error: Base must be at least 2" + return + return sum(toBaseX(num, base)) print sumDigits(1) print sumDigits(12345) diff --git a/Task/Sum-digits-of-an-integer/Racket/sum-digits-of-an-integer.rkt b/Task/Sum-digits-of-an-integer/Racket/sum-digits-of-an-integer.rkt new file mode 100644 index 0000000000..3df9b4883d --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Racket/sum-digits-of-an-integer.rkt @@ -0,0 +1,22 @@ +#lang racket +(define (sum-of-digits n base (sum 0)) + (if (= n 0) + sum + (sum-of-digits (quotient n base) + base + (+ (remainder n base) sum)))) + +(for-each + (lambda (number-base-pair) + (define number (car number-base-pair)) + (define base (cadr number-base-pair)) + (displayln (format "(~a)_~a = ~a" number base (sum-of-digits number base)))) + '((1 10) (1234 10) (#xfe 16) (#xf0e 16))) + + + +; outputs: +; (1)_10 = 1 +; (1234)_10 = 10 +; (254)_16 = 29 +; (3854)_16 = 29 diff --git a/Task/Sum-of-a-series/APL/sum-of-a-series.apl b/Task/Sum-of-a-series/APL/sum-of-a-series.apl new file mode 100644 index 0000000000..f5b09f423d --- /dev/null +++ b/Task/Sum-of-a-series/APL/sum-of-a-series.apl @@ -0,0 +1,2 @@ + +/÷2*⍨⍳1000 +1.64393 diff --git a/Task/Sum-of-a-series/Aime/sum-of-a-series.aime b/Task/Sum-of-a-series/Aime/sum-of-a-series.aime new file mode 100644 index 0000000000..0d0373fbc8 --- /dev/null +++ b/Task/Sum-of-a-series/Aime/sum-of-a-series.aime @@ -0,0 +1,25 @@ +real +Invsqr(real n) +{ + return 1 / (n * n); +} + +integer +main(void) +{ + integer i; + real sum; + + sum = 0; + + i = 1; + while (i < 1000) { + sum += Invsqr(i); + i += 1; + } + + o_real(14, sum); + o_byte('\n'); + + return 0; +} diff --git a/Task/Sum-of-a-series/Bracmat/sum-of-a-series.bracmat b/Task/Sum-of-a-series/Bracmat/sum-of-a-series.bracmat new file mode 100644 index 0000000000..ec7c916045 --- /dev/null +++ b/Task/Sum-of-a-series/Bracmat/sum-of-a-series.bracmat @@ -0,0 +1,6 @@ +( 0:?i +& 0:?S +& whl'(1+!i:~>1000:?i&!i^-2+!S:?S) +& out$!S +& out$(flt$(!S,10)) +); diff --git a/Task/Sum-of-a-series/Eiffel/sum-of-a-series.e b/Task/Sum-of-a-series/Eiffel/sum-of-a-series.e new file mode 100644 index 0000000000..e69aac5b93 --- /dev/null +++ b/Task/Sum-of-a-series/Eiffel/sum-of-a-series.e @@ -0,0 +1,50 @@ +note + description: "Compute the n-th term of a series" + +class + SUM_OF_SERIES_EXAMPLE + +inherit + MATH_CONST + +create + make + +feature -- Initialization + + make + local + approximated, known: REAL_64 + do + known := Pi^2 / 6 + + approximated := sum_until (agent g, 1001) + print ("%Nzeta function exact value: %N") + print (known) + print ("%Nzeta function approximated value: %N") + print (approximated) + end + +feature -- Access + + g (k: INTEGER): REAL_64 + -- 'k'-th term of the serie + require + k_positive: k > 0 + do + Result := 1 / (k * k) + end + + sum_until (s: FUNCTION [ANY, TUPLE [INTEGER], REAL_64]; n: INTEGER): REAL_64 + -- sum of the 'n' first terms of 's' + require + n_positive: n > 0 + one_parameter: s.open_count = 1 + do + Result := 0 + across 1 |..| n as it loop + Result := Result + s.item ([it.item]) + end + end + +end 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 index 732c3cef0e..1229345d01 100644 --- 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 @@ -2,7 +2,8 @@ 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)*/ +numeric digits D /*use D digits: 9 is default for */ + /*REXX, 60 is this pgm's 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. */ 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 index f92a7e2355..f79e1f5629 100644 --- 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 @@ -2,7 +2,8 @@ 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).*/ +numeric digits D /*use D digits: 9 is default for */ + /*REXX, 60 is this pgm's 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. */ 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 index 080c1f205f..e6ba7728e4 100644 --- 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 @@ -3,7 +3,8 @@ 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).*/ +numeric digits D /*use D digits: 9 is default for */ + /*REXX, 60 is this pgm's 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.*/ diff --git a/Task/Sum-of-a-series/Raven/sum-of-a-series.raven b/Task/Sum-of-a-series/Raven/sum-of-a-series.raven new file mode 100644 index 0000000000..908a6ee3b0 --- /dev/null +++ b/Task/Sum-of-a-series/Raven/sum-of-a-series.raven @@ -0,0 +1,2 @@ +0 1 1000 1 range each 1.0 swap dup * / + +"%g\n" print diff --git a/Task/Sum-of-squares/APL/sum-of-squares.apl b/Task/Sum-of-squares/APL/sum-of-squares.apl new file mode 100644 index 0000000000..17ea52a29d --- /dev/null +++ b/Task/Sum-of-squares/APL/sum-of-squares.apl @@ -0,0 +1,5 @@ + square_sum←{+/2*⍨⍵} + square_sum 1 2 3 4 5 +55 + square_sum ⍬ ⍝The empty vector +0 diff --git a/Task/Sum-of-squares/Eiffel/sum-of-squares.e b/Task/Sum-of-squares/Eiffel/sum-of-squares.e index 261100c3ee..44fad27903 100644 --- a/Task/Sum-of-squares/Eiffel/sum-of-squares.e +++ b/Task/Sum-of-squares/Eiffel/sum-of-squares.e @@ -1,17 +1,31 @@ -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 +class + APPLICATION + +create + make + +feature -- Initialization + + make + local + a: ARRAY [INTEGER] + do + a := <<1, -2, 3>> + print ("%NSquare sum of <<1, 2, 3>>: " + sum_of_square (a).out) + + a := <<>> + print ("%NSquare sum of <<>>: " + sum_of_square (a).out) + end + +feature -- Access + + sum_of_square (a: ITERABLE [INTEGER]): NATURAL + -- sum of square of each items + do + Result := 0 + across a as it loop + Result := Result + (it.item * it.item).as_natural_32 + end + end + end diff --git a/Task/Sum-of-squares/NetRexx/sum-of-squares.netrexx b/Task/Sum-of-squares/NetRexx/sum-of-squares.netrexx new file mode 100644 index 0000000000..f9425a5c0c --- /dev/null +++ b/Task/Sum-of-squares/NetRexx/sum-of-squares.netrexx @@ -0,0 +1,17 @@ +/*NetRexx ************************************************************* +* program to sum the squares of a vector of fifteen numbers. +* translated from REXX +* 14.05.2013 Walter Pachl +**********************************************************************/ +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' /* vector with some #s. */ +n=words(v) +x='' +sum=0 /*initialize SUM to zero. */ + /*if vector is empty, sum = zero.*/ +loop Until x='' /*loop until list is exhausted */ + Parse v x v /* pick next number */ + If x>'' Then /* there is a number */ + sum=sum + x**2 /*add its square to the sum. */ + end +say "The sum of" n "elements for the V vector is:" sum diff --git a/Task/Sum-of-squares/REXX/sum-of-squares.rexx b/Task/Sum-of-squares/REXX/sum-of-squares.rexx index a270a2ec1a..315727bc14 100644 --- a/Task/Sum-of-squares/REXX/sum-of-squares.rexx +++ b/Task/Sum-of-squares/REXX/sum-of-squares.rexx @@ -3,9 +3,9 @@ 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.*/ + do k=1 for words(v) /*process each number in the list*/ 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 +say 'The sum of ' words(v) " elements for the V vector is: " sum /*stick a fork in it, we're done.*/ diff --git a/Task/Sum-of-squares/Raven/sum-of-squares.raven b/Task/Sum-of-squares/Raven/sum-of-squares.raven new file mode 100644 index 0000000000..ef22f7bf8d --- /dev/null +++ b/Task/Sum-of-squares/Raven/sum-of-squares.raven @@ -0,0 +1,4 @@ +define sumOfSqrs use $lst + 0 $lst each dup * + + +[ 1 2 3 4] sumOfSqrs "Sum of squares: %d\n" print 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 index 05fcb0dd66..22b5effdf3 100644 --- a/Task/Sutherland-Hodgman-polygon-clipping/C/sutherland-hodgman-polygon-clipping.c +++ b/Task/Sutherland-Hodgman-polygon-clipping/C/sutherland-hodgman-polygon-clipping.c @@ -58,7 +58,7 @@ typedef struct { int len, alloc; vec v; } poly_t, *poly; poly poly_new() { - poly p = malloc(sizeof(poly_t)); + poly p = (poly)malloc(sizeof(poly_t)); p->len = p->alloc = 0; p->v = 0; return p; @@ -77,7 +77,7 @@ 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 = (vec)realloc(p->v, sizeof(vec_t) * p->alloc); } p->v[p->len++] = *v; } 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 index 806024dfc8..1f2f587221 100644 --- 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 @@ -59,7 +59,9 @@ function clippedPolygon = sutherlandHodgman(subjectPolygon,clipPolygon) inputList = clippedPolygon; clippedPolygon = []; - previousVertex = inputList(end,:); + if ~isempty(inputList), + previousVertex = inputList(end,:); + end for subjectVertex = (1:size(inputList,1)) diff --git a/Task/Symmetric-difference/Aime/symmetric-difference.aime b/Task/Symmetric-difference/Aime/symmetric-difference.aime new file mode 100644 index 0000000000..ad849f74af --- /dev/null +++ b/Task/Symmetric-difference/Aime/symmetric-difference.aime @@ -0,0 +1,49 @@ +void +show_sdiff(record u, record x) +{ + record r; + text s; + + r_copy(r, u); + + if (r_first(x, s)) { + do { + if (r_key(r, s)) { + r_delete(r, s); + } else { + r_p_integer(r, s, 0); + } + } while (r_greater(x, s, s)); + } + + if (r_first(r, s)) { + do { + o_text(s); + o_byte('\n'); + } while (r_greater(r, s, s)); + } +} + +record +new_set(...) +{ + integer i; + record r; + + i = 0; + while (i < count()) { + r_p_integer(r, $i, 0); + i += 1; + } + + return r; +} + +integer +main(void) +{ + show_sdiff(new_set("John", "Bob", "Mary", "Serena"), + new_set("Jim", "Mary", "John", "Bob")); + + return 0; +} diff --git a/Task/System-time/REXX/system-time.rexx b/Task/System-time/REXX/system-time.rexx index 4f4ffc29b1..0da8ebcb90 100644 --- a/Task/System-time/REXX/system-time.rexx +++ b/Task/System-time/REXX/system-time.rexx @@ -7,5 +7,8 @@ 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('L') /* hh:mm:ss.ffffff (hh is 0 ---> 23). */ say time('Long') /* (same as above) */ + +say time('S') /* sssss (0 ---> 86399). */ +say time('Seconds') /*number of complete seconds since midnight.*/ diff --git a/Task/System-time/Raven/system-time.raven b/Task/System-time/Raven/system-time.raven new file mode 100644 index 0000000000..76b22a8da0 --- /dev/null +++ b/Task/System-time/Raven/system-time.raven @@ -0,0 +1 @@ +time dup print "\n" print int '%a %b %e %H:%M:%S %Y' date diff --git a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx new file mode 100644 index 0000000000..b51922fb90 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.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/REXX/table-creation-postal-addresses-2.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-2.rexx new file mode 100644 index 0000000000..e33e9020ab --- /dev/null +++ b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-2.rexx @@ -0,0 +1,35 @@ +/* REXX *************************************************************** +* 17.05.2013 Walter Pachl +* should work with every REXX. +* I use 0xxx for the tail because this can't be modified +**********************************************************************/ +USA.=''; USA.0=0 +Call add_usa 'Boston','MA','51 Franklin Street',,'FSF Inc.',, + '02110-1301' +Call add_usa 'Washington','DC','The Oval Office',, + '1600 Pennsylvania Avenue NW','The White House',20500 +call list_usa +Exit + +add_usa: +z=usa.0+1 +Parse Arg usa.z.0city,, + usa.z.0state,, + usa.z.0addr,, + usa.z.0addr2,, + usa.z.0name,, + usa.z.0zip +usa.0=z +Return + +list_usa: +Do z=1 To usa.0 + Say ' name -->' usa.z.0name + Say ' addr -->' usa.z.0addr + If usa.z.0addr2<>'' Then Say ' addr2 -->' usa.z.0addr2 + Say ' city -->' usa.z.0city + Say ' state -->' usa.z.0state + Say ' zip -->' usa.z.0zip + Say copies('-',40) + End +Return diff --git a/Task/Table-creation-Postal-addresses/Racket/table-creation-postal-addresses.rkt b/Task/Table-creation-Postal-addresses/Racket/table-creation-postal-addresses.rkt new file mode 100644 index 0000000000..2bf9cd2103 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Racket/table-creation-postal-addresses.rkt @@ -0,0 +1,50 @@ +#lang at-exp racket + +(require db) +(define postal (sqlite3-connect #:database "/tmp/postal.db" #:mode 'create)) + +(define (add! name street city state zip) + (query-exec postal + @~a{INSERT INTO addresses (name, street, city, state, zip) + VALUES (?, ?, ?, ?, ?)} + name street city state zip)) + +(unless (table-exists? postal "addresses") + (query-exec postal + @~a{CREATE TABLE addresses( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + street TEXT NOT NULL, + city TEXT NOT NULL, + state TEXT NOT NULL, + zip TEXT NOT NULL)})) + +(add! "FSF Inc." + "51 Franklin St" + "Boston" + "MA" + "02110-1301") +(add! "The White House" + "1600 Pennsylvania Avenue NW" + "Washington" + "DC" + "20500") +(add! "National Security Council" + "1700 Pennsylvania Avenue NW" + "Washington" + "DC" + "20500") + +(printf "Addresses:\n") +(for ([r (query-rows postal "SELECT * FROM addresses")]) + (printf " ~a.\n" (string-join (cdr (vector->list r)) ", "))) +(newline) + +(printf "By State+ZIP:\n") +(for ([z (query-rows postal "SELECT * FROM addresses" + #:group #("state" "zip"))]) + (printf " ~a, ~a:\n" (vector-ref z 0) (vector-ref z 1)) + (for ([r (vector-ref z 2)]) + (printf " ~a.\n" (string-join (cdr (vector->list r)) ", ")))) + +(disconnect postal) diff --git a/Task/Take-notes-on-the-command-line/Aime/take-notes-on-the-command-line.aime b/Task/Take-notes-on-the-command-line/Aime/take-notes-on-the-command-line.aime new file mode 100644 index 0000000000..a8a59f924e --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Aime/take-notes-on-the-command-line.aime @@ -0,0 +1,45 @@ +#! /usr/local/bin/aime -a + +if (argc() == 1) { + file f; + text s; + + f_open(f, "NOTES.TXT", OPEN_READONLY, 0); + + while (f_line(f, s) != -1) { + o_text(s); + o_text("\n"); + } +} else { + integer c, i; + date d; + file f; + + f_open(f, "NOTES.TXT", OPEN_APPEND | OPEN_CREATE | OPEN_WRITEONLY, 0644); + + d_now(d); + + f_fxinteger(f, 4, 10, d_year(d)); + f_text(f, "-"); + f_fxinteger(f, 2, 10, d_y_month(d)); + f_text(f, "-"); + f_fxinteger(f, 2, 10, d_m_day(d)); + f_text(f, " "); + f_fxinteger(f, 2, 10, d_d_hour(d)); + f_text(f, ":"); + f_fxinteger(f, 2, 10, d_h_minute(d)); + f_text(f, ":"); + f_fxinteger(f, 2, 10, d_m_second(d)); + f_text(f, "\n"); + + c = '\t'; + i = 1; + while (i < argc()) { + f_byte(f, c); + c = ' '; + f_text(f, argv(i)); + i += 1; + } + + f_byte(f, '\n'); +} diff --git a/Task/Take-notes-on-the-command-line/Racket/take-notes-on-the-command-line.rkt b/Task/Take-notes-on-the-command-line/Racket/take-notes-on-the-command-line.rkt new file mode 100644 index 0000000000..f882a78206 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Racket/take-notes-on-the-command-line.rkt @@ -0,0 +1,14 @@ +#!/bin/env racket +#lang racket +(define file "NOTES.TXT") +(require racket/date) +(command-line #:args notes + (if (null? notes) + (if (file-exists? file) + (call-with-input-file* file + (λ(i) (copy-port i (current-output-port)))) + (raise-user-error 'notes "missing ~a file" file)) + (call-with-output-file* file #:exists 'append + (λ(o) (fprintf o "~a\n\t~a\n" + (date->string (current-date) #t) + (string-join notes)))))) diff --git a/Task/Temperature-conversion/Ada/temperature-conversion.ada b/Task/Temperature-conversion/Ada/temperature-conversion.ada new file mode 100644 index 0000000000..3e44896d74 --- /dev/null +++ b/Task/Temperature-conversion/Ada/temperature-conversion.ada @@ -0,0 +1,14 @@ +with Ada.Float_Text_IO, Ada.Text_IO; use Ada.Float_Text_IO, Ada.Text_IO; + +procedure Temperatur_Conversion is + K: Float; + function C return Float is (K - 273.15); + function F return Float is (K * 1.8 - 459.67); + function R return Float is (K * 1.8); +begin + Get(K); New_Line; -- Format + Put("K: "); Put(K, Fore => 4, Aft => 2, Exp => 0); New_Line;-- K: dddd.dd + Put("C: "); Put(C, Fore => 4, Aft => 2, Exp => 0); New_Line;-- C: dddd.dd + Put("F: "); Put(F, Fore => 4, Aft => 2, Exp => 0); New_Line;-- F: dddd.dd + Put("R: "); Put(R, Fore => 4, Aft => 2, Exp => 0); New_Line;-- R: dddd.dd +end; diff --git a/Task/Temperature-conversion/BBC-BASIC/temperature-conversion.bbc b/Task/Temperature-conversion/BBC-BASIC/temperature-conversion.bbc new file mode 100644 index 0000000000..cd99bbcd00 --- /dev/null +++ b/Task/Temperature-conversion/BBC-BASIC/temperature-conversion.bbc @@ -0,0 +1,9 @@ +REPEAT + INPUT "Kelvin degrees (>=0): " K +UNTIL K>=0 +@%=&20208 +PRINT '"K = " K +PRINT "C = " K - 273.15 +PRINT "F = " K * 1.8 - 459.67 +PRINT "R = " K * 1.8 +END diff --git a/Task/Temperature-conversion/C++/temperature-conversion.cpp b/Task/Temperature-conversion/C++/temperature-conversion.cpp new file mode 100644 index 0000000000..910115c3f5 --- /dev/null +++ b/Task/Temperature-conversion/C++/temperature-conversion.cpp @@ -0,0 +1,54 @@ +#include <iostream> +#include <iomanip> + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class converter +{ +public: + converter() : KTC( 273.15f ), KTDel( 3.0f / 2.0f ), KTF( 9.0f / 5.0f ), KTNew( 33.0f / 100.0f ), + KTRank( 9.0f / 5.0f ), KTRe( 4.0f / 5.0f ), KTRom( 21.0f / 40.0f ) {} + + void convert( float kelvin ) + { + float cel = kelvin - KTC, + del = ( 373.15f - kelvin ) * KTDel, + fah = kelvin * KTF - 459.67f, + net = cel * KTNew, + rnk = kelvin * KTRank, + rea = cel * KTRe, + rom = cel * KTRom + 7.5f; + + cout << endl << left + << "TEMPERATURES:" << endl + << "===============" << endl << setw( 13 ) + << "CELCIUS:" << cel << endl << setw( 13 ) + << "DELISLE:" << del << endl << setw( 13 ) + << "FAHRENHEIT:" << fah << endl << setw( 13 ) + << "KELVIN:" << kelvin << endl << setw( 13 ) + << "NEWTON:" << net << endl << setw( 13 ) + << "RANKINE:" << rnk << endl << setw( 13 ) + << "REAUMUR:" << rea << endl << setw( 13 ) + << "ROMER:" << rom << endl << endl << endl; + } +private: + const float KTRank, KTC, KTF, KTRe, KTDel, KTNew, KTRom; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + converter con; + float k; + while( true ) + { + cout << "Enter the temperature in Kelvin to convert: "; + cin >> k; + con.convert( k ); + system( "pause" ); + system( "cls" ); + } + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/Temperature-conversion/Erlang/temperature-conversion.erl b/Task/Temperature-conversion/Erlang/temperature-conversion.erl new file mode 100644 index 0000000000..58fee92aa2 --- /dev/null +++ b/Task/Temperature-conversion/Erlang/temperature-conversion.erl @@ -0,0 +1,15 @@ +% Implemented by Arjun Sunel +-module(temp_conv). +-export([main/0]). + +main() -> + conversion(21). + +conversion(T) -> + io:format("\nK : ~p\n\n",[f(T)]), + io:format("C : ~p \n\n",[f(T - 273.15)]), + io:format("F : ~p\n\n",[f(T * 1.8 - 459.67)]), + io:format("R : ~p\n\n",[f(T * 1.8)]). + +f(A) -> + (round(A*100))/100 . diff --git a/Task/Temperature-conversion/Perl/temperature-conversion.pl b/Task/Temperature-conversion/Perl/temperature-conversion.pl new file mode 100644 index 0000000000..593be6da7e --- /dev/null +++ b/Task/Temperature-conversion/Perl/temperature-conversion.pl @@ -0,0 +1,27 @@ +#!/usr/bin/perl +use strict ; +use warnings ; + +sub kelvin_to_other_scales { + my $kelvin = shift ; + my $celsius = $kelvin - 273.15 ; + my $rankine = 9 * $kelvin / 5 ; + my $fahrenheit = $rankine - 459.67 ; + my @scales ; + push @scales , $kelvin , $celsius , $fahrenheit , $rankine ; + return @scales ; +} + +print "Enter a temperature in Kelvin: " ; +my $kelvin = <STDIN> ; +chomp $kelvin ; +while ( $kelvin < 0 ) { + print "Error! There are no negative kelvin degrees!\n" ; + $kelvin = <STDIN> ; + chomp $kelvin ; +} +my @scales = kelvin_to_other_scales( $kelvin ) ; +print "K $scales[ 0 ]\n" ; +print "C $scales[ 1 ]\n" ; +print "F $scales[ 2 ]\n" ; +print "R $scales[ 3 ]\n" ; diff --git a/Task/Temperature-conversion/REXX/temperature-conversion.rexx b/Task/Temperature-conversion/REXX/temperature-conversion.rexx index 7e2326e352..2496983f42 100644 --- a/Task/Temperature-conversion/REXX/temperature-conversion.rexx +++ b/Task/Temperature-conversion/REXX/temperature-conversion.rexx @@ -14,7 +14,7 @@ parse arg tList /*get specified temperature lists*/ end else u='k' /*assume Kelvin as per task req.*/ - uU=translate(u,'EE',"éÉ"); upper uU /*uppercase version of temp unit.*/ + 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) diff --git a/Task/Temperature-conversion/Racket/temperature-conversion.rkt b/Task/Temperature-conversion/Racket/temperature-conversion.rkt new file mode 100644 index 0000000000..7c74e08f68 --- /dev/null +++ b/Task/Temperature-conversion/Racket/temperature-conversion.rkt @@ -0,0 +1,25 @@ +#lang racket +(define (converter temp init final) + (define to-k + (case init + ('k temp) + ('c (+ 273.15 temp)) + ('f (* (+ temp 459.67) 5/9)) + ('r (* temp 5/9)))) + (case final + ('k to-k) + ('c (- to-k 273.15)) + ('f (- (* to-k 9/5) 459.67)) + ('r (* to-k 1.8)))) + +(define (kelvin-to-all temp) + (display (format "Kelvin: ~a \nCelsius: ~a \nFahrenheit: ~a \nRankine: ~a \n" + temp + (converter temp 'k 'c) + (converter temp 'k 'f) + (converter temp 'k 'r)))) +(kelvin-to-all 21) +;Kelvin: 21 +;Celsius: -252.14999999999998 +;Fahrenheit: -421.87 +;Rankine: 37.800000000000004 diff --git a/Task/Temperature-conversion/Seed7/temperature-conversion.seed7 b/Task/Temperature-conversion/Seed7/temperature-conversion.seed7 new file mode 100644 index 0000000000..a5c0dc8588 --- /dev/null +++ b/Task/Temperature-conversion/Seed7/temperature-conversion.seed7 @@ -0,0 +1,23 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const func float: celsius (in float: kelvin) is + return kelvin - 273.15; + +const func float: fahrenheit (in float: kelvin) is + return kelvin * 1.8 - 459.67; + +const func float: rankine (in float: kelvin) is + return kelvin * 1.8; + +const proc: main is func + local + var float: kelvin is 0.0; + begin + write("Enter temperature in kelvin: "); + readln(kelvin); + writeln("K: " <& kelvin digits 2 lpad 7); + writeln("C: " <& celsius(kelvin) digits 2 lpad 7); + writeln("F: " <& fahrenheit(kelvin) digits 2 lpad 7); + writeln("R: " <& rankine(kelvin) digits 2 lpad 7); + end func; diff --git a/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen-1.lua b/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen-1.lua new file mode 100644 index 0000000000..f24fd1daad --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen-1.lua @@ -0,0 +1 @@ +os.execute( "clear" ) diff --git a/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen-2.lua b/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen-2.lua new file mode 100644 index 0000000000..0b5c2718c9 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen-2.lua @@ -0,0 +1 @@ +os.execute( "cls" ) diff --git a/Task/Terminal-control-Clear-the-screen/Racket/terminal-control-clear-the-screen.rkt b/Task/Terminal-control-Clear-the-screen/Racket/terminal-control-clear-the-screen.rkt new file mode 100644 index 0000000000..b1e7cd710a --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Racket/terminal-control-clear-the-screen.rkt @@ -0,0 +1,4 @@ +#lang racket +(require (planet neil/charterm:3:0)) +(with-charterm + (void (charterm-clear-screen))) diff --git a/Task/Terminal-control-Coloured-text/Perl-6/terminal-control-coloured-text.pl6 b/Task/Terminal-control-Coloured-text/Perl-6/terminal-control-coloured-text.pl6 new file mode 100644 index 0000000000..dd4c223310 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Perl-6/terminal-control-coloured-text.pl6 @@ -0,0 +1,8 @@ +use Term::ANSIColor; + +say colored('RED ON WHITE', 'bold red on_white'); +say colored('GREEN', 'bold green'); +say colored('BLUE ON YELLOW', 'bold blue on_yellow'); +say colored('MAGENTA', 'bold magenta'); +say colored('CYAN ON RED', 'bold cyan on_red'); +say colored('YELLOW', 'bold yellow'); diff --git a/Task/Terminal-control-Coloured-text/Racket/terminal-control-coloured-text.rkt b/Task/Terminal-control-Coloured-text/Racket/terminal-control-coloured-text.rkt new file mode 100644 index 0000000000..b4b3b0a7da --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Racket/terminal-control-coloured-text.rkt @@ -0,0 +1,24 @@ +#lang racket + +;; Utility interfaces to the low-level command +(define (capability? cap) (system (~a "tput "cap" > /dev/null 2>&1"))) +(define (tput . xs) (system (apply ~a 'tput " " (add-between xs " "))) (void)) +(define (colorterm?) (and (capability? 'setaf) (capability? 'setab))) +(define color-map '([black 0] [red 1] [green 2] [yellow 3] + [blue 4] [magenta 5] [cyan 6] [white 7])) +(define (foreground color) (tput 'setaf (cadr (assq color color-map)))) +(define (background color) (tput 'setab (cadr (assq color color-map)))) +(define (reset) (tput 'sgr0) (void)) + +;; Demonstration of use +(if (colorterm?) + (begin (foreground 'blue) + (background 'yellow) + (displayln "Color output") + (reset)) + (displayln "Monochrome only")) +(if (capability? 'blink) + (begin (tput 'blink) + (displayln "Blinking output") + (reset)) + (displayln "Steady only")) diff --git a/Task/Terminal-control-Cursor-movement/Perl-6/terminal-control-cursor-movement.pl6 b/Task/Terminal-control-Cursor-movement/Perl-6/terminal-control-cursor-movement.pl6 new file mode 100644 index 0000000000..5e16bfb1bc --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Perl-6/terminal-control-cursor-movement.pl6 @@ -0,0 +1,13 @@ +shell "tput cub1"; # one position to the left +shell "tput cuf1"; # one position to the right +shell "tput cuu1"; # up one line +shell "tput cud1"; # down one line +shell "tput cr"; # beginning of line +shell "tput home"; # top left corner + +$_ = qx[stty -a </dev/tty 2>&1]; +my $rows = +m/'rows ' <(\d+)>/; +my $cols = +m/'columns ' <(\d+)>/; + +shell "tput hpa $cols"; # end of line +shell "tput cup $rows $cols"; # bottom right corner diff --git a/Task/Terminal-control-Cursor-movement/Racket/terminal-control-cursor-movement.rkt b/Task/Terminal-control-Cursor-movement/Racket/terminal-control-cursor-movement.rkt new file mode 100644 index 0000000000..7aebeb6474 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Racket/terminal-control-cursor-movement.rkt @@ -0,0 +1,24 @@ +#lang racket +(require (planet neil/charterm:3:0)) +(define x 0) +(define y 0) + +(define (on-key k) + (match k + ['down (move 0 -1)] + ['up (move 0 +1)] + ['right (move +1 0)] + ['left (move -1 0)] + [else #f])) + +(define (move dx dy) + (set! x (+ x dx)) + (set! y (+ y dy)) + (charterm-cursor x y)) + +(with-charterm + (charterm-clear-screen) + (charterm-cursor 0 0) + (let loop ([continue? #t]) + (when continue? + (loop (on-key (charterm-read-key)))))) diff --git a/Task/Terminal-control-Cursor-positioning/Racket/terminal-control-cursor-positioning.rkt b/Task/Terminal-control-Cursor-positioning/Racket/terminal-control-cursor-positioning.rkt new file mode 100644 index 0000000000..c5b7f36c12 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Racket/terminal-control-cursor-positioning.rkt @@ -0,0 +1,6 @@ +#lang racket +(require (planet neil/charterm:3:0)) +(with-charterm + (charterm-clear-screen) + (charterm-cursor 3 6) + (displayln "Hello World")) diff --git a/Task/Terminal-control-Dimensions/Racket/terminal-control-dimensions.rkt b/Task/Terminal-control-Dimensions/Racket/terminal-control-dimensions.rkt new file mode 100644 index 0000000000..abf3f1e9e3 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Racket/terminal-control-dimensions.rkt @@ -0,0 +1,4 @@ +#lang racket +(require (planet neil/charterm:3:0)) +(with-charterm + (charterm-screen-size)) diff --git a/Task/Terminal-control-Display-an-extended-character/COBOL/terminal-control-display-an-extended-character.cobol b/Task/Terminal-control-Display-an-extended-character/COBOL/terminal-control-display-an-extended-character.cobol new file mode 100644 index 0000000000..d48ccebffd --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/COBOL/terminal-control-display-an-extended-character.cobol @@ -0,0 +1,8 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Display-Pound. + + PROCEDURE DIVISION. + DISPLAY "£" + + GOBACK + . diff --git a/Task/Terminal-control-Display-an-extended-character/Racket/terminal-control-display-an-extended-character.rkt b/Task/Terminal-control-Display-an-extended-character/Racket/terminal-control-display-an-extended-character.rkt new file mode 100644 index 0000000000..72887f0459 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Racket/terminal-control-display-an-extended-character.rkt @@ -0,0 +1,2 @@ +#lang racket +(display "£") diff --git a/Task/Terminal-control-Hiding-the-cursor/Racket/terminal-control-hiding-the-cursor.rkt b/Task/Terminal-control-Hiding-the-cursor/Racket/terminal-control-hiding-the-cursor.rkt new file mode 100644 index 0000000000..7c124df38b --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Racket/terminal-control-hiding-the-cursor.rkt @@ -0,0 +1,2 @@ +#lang racket +(void (system "tput civis")) (sleep 2) (void (system "tput cvvis")) diff --git a/Task/Terminal-control-Inverse-video/Racket/terminal-control-inverse-video.rkt b/Task/Terminal-control-Inverse-video/Racket/terminal-control-inverse-video.rkt new file mode 100644 index 0000000000..4ac314a70f --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Racket/terminal-control-inverse-video.rkt @@ -0,0 +1,10 @@ +#lang racket +(require (planet neil/charterm:3:0)) + +(with-charterm + (charterm-clear-screen) + (charterm-cursor 0 0) + (charterm-inverse) + (charterm-display "Hello") + (charterm-normal) + (charterm-display "World")) diff --git a/Task/Terminal-control-Positional-read/Racket/terminal-control-positional-read.rkt b/Task/Terminal-control-Positional-read/Racket/terminal-control-positional-read.rkt new file mode 100644 index 0000000000..1656a78680 --- /dev/null +++ b/Task/Terminal-control-Positional-read/Racket/terminal-control-positional-read.rkt @@ -0,0 +1,10 @@ +#lang racket +(require ffi/unsafe ffi/unsafe/define) +(define-ffi-definer defwin #f) +(defwin GetStdHandle (_fun _int -> _pointer)) +(defwin ReadConsoleOutputCharacterA + (_fun _pointer _pointer _uint _uint [len : (_ptr o _uint)] -> _bool)) + +(define b (make-bytes 1 32)) +(and (ReadConsoleOutputCharacterA (GetStdHandle -11) b 1 #x50002) + (printf "The character at 3x6 is <~a>\n" b)) diff --git a/Task/Terminal-control-Preserve-screen/Perl-6/terminal-control-preserve-screen.pl6 b/Task/Terminal-control-Preserve-screen/Perl-6/terminal-control-preserve-screen.pl6 new file mode 100644 index 0000000000..bac225f125 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Perl-6/terminal-control-preserve-screen.pl6 @@ -0,0 +1,9 @@ +print "\e[?1049h\e[H"; +say "Alternate buffer!"; + +for 5,4...1 { + print "\rGoing back in: $_"; + sleep 1; +} + +print "\e[?1049l"; diff --git a/Task/Terminal-control-Preserve-screen/Racket/terminal-control-preserve-screen.rkt b/Task/Terminal-control-Preserve-screen/Racket/terminal-control-preserve-screen.rkt new file mode 100644 index 0000000000..e1f040f44b --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Racket/terminal-control-preserve-screen.rkt @@ -0,0 +1,11 @@ +#lang racket + +(require racket/system) +(define (flash str) + (system "tput smcup") + (displayln str) + (sleep 2) + (system "tput rmcup") + (void)) + +(flash "Hello world.") diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Racket/terminal-control-ringing-the-terminal-bell.rkt b/Task/Terminal-control-Ringing-the-terminal-bell/Racket/terminal-control-ringing-the-terminal-bell.rkt new file mode 100644 index 0000000000..2944344bc1 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Racket/terminal-control-ringing-the-terminal-bell.rkt @@ -0,0 +1,4 @@ +#lang racket +(require (planet neil/charterm:3:0)) +(with-charterm + (void (charterm-bell))) diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Seed7/terminal-control-ringing-the-terminal-bell.seed7 b/Task/Terminal-control-Ringing-the-terminal-bell/Seed7/terminal-control-ringing-the-terminal-bell.seed7 new file mode 100644 index 0000000000..fb85b0b77c --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Seed7/terminal-control-ringing-the-terminal-bell.seed7 @@ -0,0 +1,6 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + begin + write("\a"); + end func; diff --git a/Task/Terminal-control-Unicode-output/Racket/terminal-control-unicode-output.rkt b/Task/Terminal-control-Unicode-output/Racket/terminal-control-unicode-output.rkt new file mode 100644 index 0000000000..f09814083c --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Racket/terminal-control-unicode-output.rkt @@ -0,0 +1,5 @@ +#lang racket +(displayln + (if (regexp-match? #px"(?i:utf-?8)" + (or (getenv "LC_ALL") (getenv "LC_CTYPE") (getenv "LANG"))) + "\u25b3" "No Unicode detected.")) diff --git a/Task/Ternary-logic/Erlang/ternary-logic.erl b/Task/Ternary-logic/Erlang/ternary-logic.erl new file mode 100644 index 0000000000..6b90e73a36 --- /dev/null +++ b/Task/Ternary-logic/Erlang/ternary-logic.erl @@ -0,0 +1,74 @@ +% Implemented by Arjun Sunel +-module(ternary). +-export([main/0, nott/1, andd/2,orr/2, then/2, equiv/2]). + +main() -> + {ok, [A]} = io:fread("Enter A: ","~s"), + {ok, [B]} = io:fread("Enter B: ","~s"), + andd(A,B). + +nott(S) -> + if + S=="T" -> + io : format("F\n"); + + S=="F" -> + io : format("T\n"); + + true -> + io: format("?\n") + end. + +andd(A, B) -> + if + A=="T", B=="T" -> + io : format("T\n"); + + A=="F"; B=="F" -> + io : format("F\n"); + + true -> + io: format("?\n") + end. + + +orr(A, B) -> + if + A=="T"; B=="T" -> + io : format("T\n"); + + A=="?"; B=="?" -> + io : format("?\n"); + + true -> + io: format("F\n") + end. + + +then(A, B) -> + if + B=="T" -> + io : format("T\n"); + + A=="?" -> + io : format("?\n"); + + A=="F" -> + io :format("T\n"); + B=="F" -> + io:format("F\n"); + true -> + io: format("?\n") + end. + +equiv(A, B) -> + if + A=="?" -> + io : format("?\n"); + + A=="F" -> + io : format("~s\n", [nott(B)]); + + true -> + io: format("~s\n", [B]) + end. diff --git a/Task/Ternary-logic/Fortran/ternary-logic.f b/Task/Ternary-logic/Fortran/ternary-logic.f new file mode 100644 index 0000000000..a4934fe6a4 --- /dev/null +++ b/Task/Ternary-logic/Fortran/ternary-logic.f @@ -0,0 +1,97 @@ +!-*- mode: compilation; default-directory: "/tmp/" -*- +!Compilation started at Mon May 20 23:05:46 +! +!a=./f && make $a && $a < unixdict.txt +!gfortran -std=f2003 -Wall -ffree-form f.f03 -o f +! +!ternary not +! 1.0 0.5 0.0 +! +! +!ternary and +! 0.0 0.0 0.0 +! 0.0 0.5 0.5 +! 0.0 0.5 1.0 +! +! +!ternary or +! 0.0 0.5 1.0 +! 0.5 0.5 1.0 +! 1.0 1.0 1.0 +! +! +!ternary if +! 1.0 1.0 1.0 +! 0.5 0.5 1.0 +! 0.0 0.5 1.0 +! +! +!ternary eq +! 1.0 0.5 0.0 +! 0.5 0.5 0.5 +! 0.0 0.5 1.0 +! +! +!Compilation finished at Mon May 20 23:05:46 + + +!This program is based on the j implementation +!not=: -. +!and=: <. +!or =: >. +!if =: (>. -.)"0~ +!eq =: (<.&-. >. <.)"0 + +module trit + + real, parameter :: true = 1, false = 0, maybe = 0.5 + +contains + + real function tnot(y) + real, intent(in) :: y + tnot = 1 - y + end function tnot + + real function tand(x, y) + real, intent(in) :: x, y + tand = min(x, y) + end function tand + + real function tor(x, y) + real, intent(in) :: x, y + tor = max(x, y) + end function tor + + real function tif(x, y) + real, intent(in) :: x, y + tif = tor(y, tnot(x)) + end function tif + + real function teq(x, y) + real, intent(in) :: x, y + teq = tor(tand(tnot(x), tnot(y)), tand(x, y)) + end function teq + +end module trit + +program ternaryLogic + use trit + integer :: i + real, dimension(3) :: a = [false, maybe, true] ! (/ ... /) + write(6,'(/a)')'ternary not' ; write(6, '(3f4.1/)') (tnot(a(i)), i = 1 , 3) + write(6,'(/a)')'ternary and' ; call table(tand, a, a) + write(6,'(/a)')'ternary or' ; call table(tor, a, a) + write(6,'(/a)')'ternary if' ; call table(tif, a, a) + write(6,'(/a)')'ternary eq' ; call table(teq, a, a) + +contains + + subroutine table(u, x, y) ! for now, show the table. + real, external :: u + real, dimension(3), intent(in) :: x, y + integer :: i, j + write(6, '(3(3f4.1/))') ((u(x(i), y(j)), j=1,3), i=1,3) + end subroutine table + +end program ternaryLogic diff --git a/Task/Ternary-logic/Racket/ternary-logic.rkt b/Task/Ternary-logic/Racket/ternary-logic.rkt index 729d4eac68..83d5e6fdce 100644 --- a/Task/Ternary-logic/Racket/ternary-logic.rkt +++ b/Task/Ternary-logic/Racket/ternary-logic.rkt @@ -1,7 +1,7 @@ #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 +; to avoid the hassle of adding a maybe value that is as special as +; the two standard booleans, we'll use symbols to make our own (define-type trit (U 'true 'false 'maybe)) (: not (trit -> trit)) diff --git a/Task/Ternary-logic/Seed7/ternary-logic.seed7 b/Task/Ternary-logic/Seed7/ternary-logic.seed7 index 6c4cda63aa..b8ce88b117 100644 --- a/Task/Ternary-logic/Seed7/ternary-logic.seed7 +++ b/Task/Ternary-logic/Seed7/ternary-logic.seed7 @@ -78,12 +78,6 @@ const func trit: (in trit: aTrit1) == (in trit: aTrit2) is 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; diff --git a/Task/Test-a-function/Ada/test-a-function-1.ada b/Task/Test-a-function/Ada/test-a-function-1.ada new file mode 100644 index 0000000000..14415f06c4 --- /dev/null +++ b/Task/Test-a-function/Ada/test-a-function-1.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/Ada/test-a-function-2.ada b/Task/Test-a-function/Ada/test-a-function-2.ada new file mode 100644 index 0000000000..977f9d88c1 --- /dev/null +++ b/Task/Test-a-function/Ada/test-a-function-2.ada @@ -0,0 +1,5 @@ + function Palindrome (Text : String) return Boolean + with Post => Palindrome'Result = + (Text'Length < 2 or else + ((Text(Text'First) = Text(Text'Last)) and then + Palindrome(Text(Text'First+1 .. Text'Last-1))));
" ^ v ^ "
" ^ string_of_int i ^ "