diff --git a/Conf/.lang.yaml.swp b/Conf/.lang.yaml.swp index f7e01d8726..fa5b64bcda 100644 Binary files a/Conf/.lang.yaml.swp and b/Conf/.lang.yaml.swp differ diff --git a/Conf/.task.yaml.swp b/Conf/.task.yaml.swp index e47b69c5f4..39124cc3dc 100644 Binary files a/Conf/.task.yaml.swp and b/Conf/.task.yaml.swp differ diff --git a/Conf/lang.yaml b/Conf/lang.yaml index b29f15aed6..103c24eaef 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -92,6 +92,8 @@ JavaScript: LaTeX: ext: tex Lua: +MATLAB: + ext: m Perl: ext: pl PHP: diff --git a/Conf/task.yaml b/Conf/task.yaml index 1584fd26f4..93829a455c 100644 --- a/Conf/task.yaml +++ b/Conf/task.yaml @@ -1,6 +1,7 @@ 100 doors: 24 game: 99 Bottles of Beer: + A+B: Abstract type: Accumulator factory: @@ -13,7 +14,7 @@ Address of a variable: Align columns: Anagrams: Anagrams/Deranged anagrams: -# Animate a pendulum: +Animate a pendulum: Animation: Anonymous recursion: Apply a callback to an array: @@ -22,7 +23,7 @@ Arena storage pool: Arithmetic evaluation: Arithmetic-geometric mean: Arithmetic/Complex: -# Arithmetic/Integer: +Arithmetic/Integer: Arithmetic/Rational: Array concatenation: Arrays: @@ -35,10 +36,11 @@ Averages/Arithmetic mean: Averages/Mean angle: Averages/Mean time of day: Averages/Median: -# Averages/Mode: +Averages/Mode: Averages/Pythagorean means: Averages/Root mean square: Averages/Simple moving average: + Balanced brackets: Balanced ternary: Best shuffle: diff --git a/Lang/0815/Arithmetic-Integer b/Lang/0815/Arithmetic-Integer new file mode 120000 index 0000000000..0b422118f7 --- /dev/null +++ b/Lang/0815/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/0815 \ No newline at end of file diff --git a/Lang/6502-Assembly/Arithmetic-Integer b/Lang/6502-Assembly/Arithmetic-Integer new file mode 120000 index 0000000000..d4441b63d8 --- /dev/null +++ b/Lang/6502-Assembly/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/6502-Assembly \ No newline at end of file diff --git a/Lang/ABAP/Arithmetic-Integer b/Lang/ABAP/Arithmetic-Integer new file mode 120000 index 0000000000..7bc907b54b --- /dev/null +++ b/Lang/ABAP/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/ABAP \ No newline at end of file diff --git a/Lang/ACL2/Arithmetic-Integer b/Lang/ACL2/Arithmetic-Integer new file mode 120000 index 0000000000..0ba9516fc1 --- /dev/null +++ b/Lang/ACL2/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/ACL2 \ No newline at end of file diff --git a/Lang/ALGOL-68/Arithmetic-Integer b/Lang/ALGOL-68/Arithmetic-Integer new file mode 120000 index 0000000000..09ad13bc68 --- /dev/null +++ b/Lang/ALGOL-68/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/ALGOL-68 \ No newline at end of file diff --git a/Lang/AWK/Arithmetic-Integer b/Lang/AWK/Arithmetic-Integer new file mode 120000 index 0000000000..0aa856d8ce --- /dev/null +++ b/Lang/AWK/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/AWK \ No newline at end of file diff --git a/Lang/AWK/Averages-Mode b/Lang/AWK/Averages-Mode new file mode 120000 index 0000000000..07618fc71b --- /dev/null +++ b/Lang/AWK/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/AWK \ No newline at end of file diff --git a/Lang/ActionScript/Averages-Mode b/Lang/ActionScript/Averages-Mode new file mode 120000 index 0000000000..d4a1c50b21 --- /dev/null +++ b/Lang/ActionScript/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/ActionScript \ No newline at end of file diff --git a/Lang/Ada/Animate-a-pendulum b/Lang/Ada/Animate-a-pendulum new file mode 120000 index 0000000000..47c0707914 --- /dev/null +++ b/Lang/Ada/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Ada \ No newline at end of file diff --git a/Lang/Ada/Arithmetic-Integer b/Lang/Ada/Arithmetic-Integer new file mode 120000 index 0000000000..93bb6a9ed6 --- /dev/null +++ b/Lang/Ada/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Ada \ No newline at end of file diff --git a/Lang/Ada/Averages-Mode b/Lang/Ada/Averages-Mode new file mode 120000 index 0000000000..bffad684ed --- /dev/null +++ b/Lang/Ada/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Ada \ No newline at end of file diff --git a/Lang/Aikido/Arithmetic-Integer b/Lang/Aikido/Arithmetic-Integer new file mode 120000 index 0000000000..938f56f162 --- /dev/null +++ b/Lang/Aikido/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Aikido \ No newline at end of file diff --git a/Lang/AmigaE/Arithmetic-Integer b/Lang/AmigaE/Arithmetic-Integer new file mode 120000 index 0000000000..ba289d7af3 --- /dev/null +++ b/Lang/AmigaE/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/AmigaE \ No newline at end of file diff --git a/Lang/AutoHotkey/Arithmetic-Integer b/Lang/AutoHotkey/Arithmetic-Integer new file mode 120000 index 0000000000..353488e689 --- /dev/null +++ b/Lang/AutoHotkey/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Averages-Mode b/Lang/AutoHotkey/Averages-Mode new file mode 120000 index 0000000000..eb449c0b6e --- /dev/null +++ b/Lang/AutoHotkey/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/AutoHotkey \ No newline at end of file diff --git a/Lang/BASIC/Arithmetic-Integer b/Lang/BASIC/Arithmetic-Integer new file mode 120000 index 0000000000..b6021b95e6 --- /dev/null +++ b/Lang/BASIC/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/BASIC \ No newline at end of file diff --git a/Lang/Befunge/Arithmetic-Integer b/Lang/Befunge/Arithmetic-Integer new file mode 120000 index 0000000000..94774a5bba --- /dev/null +++ b/Lang/Befunge/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Befunge \ No newline at end of file diff --git a/Lang/C/Animate-a-pendulum b/Lang/C/Animate-a-pendulum new file mode 120000 index 0000000000..7c647c3d63 --- /dev/null +++ b/Lang/C/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/C \ No newline at end of file diff --git a/Lang/C/Arithmetic-Integer b/Lang/C/Arithmetic-Integer new file mode 120000 index 0000000000..9fdf8adc4b --- /dev/null +++ b/Lang/C/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/C \ No newline at end of file diff --git a/Lang/C/Averages-Mode b/Lang/C/Averages-Mode new file mode 120000 index 0000000000..cc5bb15cdb --- /dev/null +++ b/Lang/C/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/C \ No newline at end of file diff --git a/Lang/Clojure/Animate-a-pendulum b/Lang/Clojure/Animate-a-pendulum new file mode 120000 index 0000000000..ce8f5e97ac --- /dev/null +++ b/Lang/Clojure/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Arithmetic-Integer b/Lang/Clojure/Arithmetic-Integer new file mode 120000 index 0000000000..244f94be6c --- /dev/null +++ b/Lang/Clojure/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Averages-Mode b/Lang/Clojure/Averages-Mode new file mode 120000 index 0000000000..263717a350 --- /dev/null +++ b/Lang/Clojure/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Clojure \ No newline at end of file diff --git a/Lang/Eiffel/Arithmetic-Integer b/Lang/Eiffel/Arithmetic-Integer new file mode 120000 index 0000000000..4f38884ccf --- /dev/null +++ b/Lang/Eiffel/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Eiffel \ No newline at end of file diff --git a/Lang/Forth/Arithmetic-Integer b/Lang/Forth/Arithmetic-Integer new file mode 120000 index 0000000000..42aa5f1be6 --- /dev/null +++ b/Lang/Forth/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Forth \ No newline at end of file diff --git a/Lang/Fortran/Arithmetic-Integer b/Lang/Fortran/Arithmetic-Integer new file mode 120000 index 0000000000..af2d13349e --- /dev/null +++ b/Lang/Fortran/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Averages-Mode b/Lang/Fortran/Averages-Mode new file mode 120000 index 0000000000..7343c371ae --- /dev/null +++ b/Lang/Fortran/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Fortran \ No newline at end of file diff --git a/Lang/Go/Arithmetic-Integer b/Lang/Go/Arithmetic-Integer new file mode 120000 index 0000000000..a8868edcb0 --- /dev/null +++ b/Lang/Go/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Go \ No newline at end of file diff --git a/Lang/Go/Averages-Mode b/Lang/Go/Averages-Mode new file mode 120000 index 0000000000..e53ed6253b --- /dev/null +++ b/Lang/Go/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Go \ No newline at end of file diff --git a/Lang/Haskell/Animate-a-pendulum b/Lang/Haskell/Animate-a-pendulum new file mode 120000 index 0000000000..e9cd13e9b5 --- /dev/null +++ b/Lang/Haskell/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Arithmetic-Integer b/Lang/Haskell/Arithmetic-Integer new file mode 120000 index 0000000000..2e0b3f7862 --- /dev/null +++ b/Lang/Haskell/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Averages-Mode b/Lang/Haskell/Averages-Mode new file mode 120000 index 0000000000..2cf26d4fd1 --- /dev/null +++ b/Lang/Haskell/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Haskell \ No newline at end of file diff --git a/Lang/Java/Animate-a-pendulum b/Lang/Java/Animate-a-pendulum new file mode 120000 index 0000000000..8c52856472 --- /dev/null +++ b/Lang/Java/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Java \ No newline at end of file diff --git a/Lang/Java/Arithmetic-Integer b/Lang/Java/Arithmetic-Integer new file mode 120000 index 0000000000..047db1d5c1 --- /dev/null +++ b/Lang/Java/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Java \ No newline at end of file diff --git a/Lang/Java/Averages-Mode b/Lang/Java/Averages-Mode new file mode 120000 index 0000000000..4c63810194 --- /dev/null +++ b/Lang/Java/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Java \ No newline at end of file diff --git a/Lang/JavaScript/Animate-a-pendulum b/Lang/JavaScript/Animate-a-pendulum new file mode 120000 index 0000000000..e63558c957 --- /dev/null +++ b/Lang/JavaScript/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Arithmetic-Integer b/Lang/JavaScript/Arithmetic-Integer new file mode 120000 index 0000000000..03b3dff5a9 --- /dev/null +++ b/Lang/JavaScript/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Averages-Mode b/Lang/JavaScript/Averages-Mode new file mode 120000 index 0000000000..bd1a34fc61 --- /dev/null +++ b/Lang/JavaScript/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/JavaScript \ No newline at end of file diff --git a/Lang/Lua/Arithmetic-Integer b/Lang/Lua/Arithmetic-Integer new file mode 120000 index 0000000000..38ddaa586c --- /dev/null +++ b/Lang/Lua/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Lua \ No newline at end of file diff --git a/Lang/Lua/Averages-Mode b/Lang/Lua/Averages-Mode new file mode 120000 index 0000000000..2d8684b15d --- /dev/null +++ b/Lang/Lua/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Lua \ No newline at end of file diff --git a/Lang/MATLAB/0DESCRIPTION b/Lang/MATLAB/0DESCRIPTION new file mode 100644 index 0000000000..9d74762049 --- /dev/null +++ b/Lang/MATLAB/0DESCRIPTION @@ -0,0 +1,5 @@ +{{stub}}{{language +|site=http://www.mathworks.com/products/matlab/ +|checking=dynamic}} + +[[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/MATLAB/100-doors b/Lang/MATLAB/100-doors new file mode 120000 index 0000000000..af6b18858f --- /dev/null +++ b/Lang/MATLAB/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/24-game b/Lang/MATLAB/24-game new file mode 120000 index 0000000000..abe58b42ae --- /dev/null +++ b/Lang/MATLAB/24-game @@ -0,0 +1 @@ +../../Task/24-game/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/99-Bottles-of-Beer b/Lang/MATLAB/99-Bottles-of-Beer new file mode 120000 index 0000000000..a1d0d4b4f8 --- /dev/null +++ b/Lang/MATLAB/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/A+B b/Lang/MATLAB/A+B new file mode 120000 index 0000000000..9bce3965f2 --- /dev/null +++ b/Lang/MATLAB/A+B @@ -0,0 +1 @@ +../../Task/A+B/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Ackermann-function b/Lang/MATLAB/Ackermann-function new file mode 120000 index 0000000000..00d83f76b3 --- /dev/null +++ b/Lang/MATLAB/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Animate-a-pendulum b/Lang/MATLAB/Animate-a-pendulum new file mode 120000 index 0000000000..b85682475e --- /dev/null +++ b/Lang/MATLAB/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Apply-a-callback-to-an-array b/Lang/MATLAB/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..0b0b60fd3c --- /dev/null +++ b/Lang/MATLAB/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Arbitrary-precision-integers-(included) b/Lang/MATLAB/Arbitrary-precision-integers-(included) new file mode 120000 index 0000000000..7730047f9d --- /dev/null +++ b/Lang/MATLAB/Arbitrary-precision-integers-(included) @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-(included)/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Arithmetic-Complex b/Lang/MATLAB/Arithmetic-Complex new file mode 120000 index 0000000000..46752b90b1 --- /dev/null +++ b/Lang/MATLAB/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Arithmetic-Integer b/Lang/MATLAB/Arithmetic-Integer new file mode 120000 index 0000000000..0b9fb0ed06 --- /dev/null +++ b/Lang/MATLAB/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Array-concatenation b/Lang/MATLAB/Array-concatenation new file mode 120000 index 0000000000..d42baacc1d --- /dev/null +++ b/Lang/MATLAB/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Arrays b/Lang/MATLAB/Arrays new file mode 120000 index 0000000000..73acd009b2 --- /dev/null +++ b/Lang/MATLAB/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Assertions b/Lang/MATLAB/Assertions new file mode 120000 index 0000000000..33f5cbf319 --- /dev/null +++ b/Lang/MATLAB/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Associative-array-Creation b/Lang/MATLAB/Associative-array-Creation new file mode 120000 index 0000000000..5c4e6becf9 --- /dev/null +++ b/Lang/MATLAB/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Associative-array-Iteration b/Lang/MATLAB/Associative-array-Iteration new file mode 120000 index 0000000000..dcd18e1dc2 --- /dev/null +++ b/Lang/MATLAB/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Arithmetic-mean b/Lang/MATLAB/Averages-Arithmetic-mean new file mode 120000 index 0000000000..089065cc78 --- /dev/null +++ b/Lang/MATLAB/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Median b/Lang/MATLAB/Averages-Median new file mode 120000 index 0000000000..1cfcee5ae0 --- /dev/null +++ b/Lang/MATLAB/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Mode b/Lang/MATLAB/Averages-Mode new file mode 120000 index 0000000000..49b743a164 --- /dev/null +++ b/Lang/MATLAB/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Pythagorean-means b/Lang/MATLAB/Averages-Pythagorean-means new file mode 120000 index 0000000000..048678ca01 --- /dev/null +++ b/Lang/MATLAB/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Root-mean-square b/Lang/MATLAB/Averages-Root-mean-square new file mode 120000 index 0000000000..6d0f872c32 --- /dev/null +++ b/Lang/MATLAB/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Averages-Simple-moving-average b/Lang/MATLAB/Averages-Simple-moving-average new file mode 120000 index 0000000000..af2a161ef1 --- /dev/null +++ b/Lang/MATLAB/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Balanced-brackets b/Lang/MATLAB/Balanced-brackets new file mode 120000 index 0000000000..8be7648d13 --- /dev/null +++ b/Lang/MATLAB/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Binary-search b/Lang/MATLAB/Binary-search new file mode 120000 index 0000000000..d7a4a15949 --- /dev/null +++ b/Lang/MATLAB/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Caesar-cipher b/Lang/MATLAB/Caesar-cipher new file mode 120000 index 0000000000..7dc7b46002 --- /dev/null +++ b/Lang/MATLAB/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Check-that-file-exists b/Lang/MATLAB/Check-that-file-exists new file mode 120000 index 0000000000..c505355ae5 --- /dev/null +++ b/Lang/MATLAB/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Classes b/Lang/MATLAB/Classes new file mode 120000 index 0000000000..8a07405db3 --- /dev/null +++ b/Lang/MATLAB/Classes @@ -0,0 +1 @@ +../../Task/Classes/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Closest-pair-problem b/Lang/MATLAB/Closest-pair-problem new file mode 120000 index 0000000000..28dc366be5 --- /dev/null +++ b/Lang/MATLAB/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Collections b/Lang/MATLAB/Collections new file mode 120000 index 0000000000..81f3d65b32 --- /dev/null +++ b/Lang/MATLAB/Collections @@ -0,0 +1 @@ +../../Task/Collections/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Comments b/Lang/MATLAB/Comments new file mode 120000 index 0000000000..43b8df79d5 --- /dev/null +++ b/Lang/MATLAB/Comments @@ -0,0 +1 @@ +../../Task/Comments/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Define-a-primitive-data-type b/Lang/MATLAB/Define-a-primitive-data-type new file mode 120000 index 0000000000..053e0956a7 --- /dev/null +++ b/Lang/MATLAB/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Delete-a-file b/Lang/MATLAB/Delete-a-file new file mode 120000 index 0000000000..d2c7ba75fa --- /dev/null +++ b/Lang/MATLAB/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Detect-division-by-zero b/Lang/MATLAB/Detect-division-by-zero new file mode 120000 index 0000000000..2ce11c91c0 --- /dev/null +++ b/Lang/MATLAB/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Determine-if-a-string-is-numeric b/Lang/MATLAB/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..437a0d1086 --- /dev/null +++ b/Lang/MATLAB/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/FizzBuzz b/Lang/MATLAB/FizzBuzz new file mode 120000 index 0000000000..ea5c3d8ffb --- /dev/null +++ b/Lang/MATLAB/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Infinity b/Lang/MATLAB/Infinity new file mode 120000 index 0000000000..bbc56fb69d --- /dev/null +++ b/Lang/MATLAB/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Knuth-shuffle b/Lang/MATLAB/Knuth-shuffle new file mode 120000 index 0000000000..78f879e5f2 --- /dev/null +++ b/Lang/MATLAB/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Ordered-words b/Lang/MATLAB/Ordered-words new file mode 120000 index 0000000000..5ef3eb2231 --- /dev/null +++ b/Lang/MATLAB/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Pi b/Lang/MATLAB/Pi new file mode 120000 index 0000000000..a26247f5c3 --- /dev/null +++ b/Lang/MATLAB/Pi @@ -0,0 +1 @@ +../../Task/Pi/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Quine b/Lang/MATLAB/Quine new file mode 120000 index 0000000000..fc0236ee6a --- /dev/null +++ b/Lang/MATLAB/Quine @@ -0,0 +1 @@ +../../Task/Quine/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Search-a-list b/Lang/MATLAB/Search-a-list new file mode 120000 index 0000000000..df5551eda9 --- /dev/null +++ b/Lang/MATLAB/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/MATLAB \ No newline at end of file diff --git a/Lang/PHP/Arithmetic-Integer b/Lang/PHP/Arithmetic-Integer new file mode 120000 index 0000000000..11782b8f16 --- /dev/null +++ b/Lang/PHP/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/PHP \ No newline at end of file diff --git a/Lang/PHP/Averages-Mode b/Lang/PHP/Averages-Mode new file mode 120000 index 0000000000..e7465789fe --- /dev/null +++ b/Lang/PHP/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/PHP \ No newline at end of file diff --git a/Lang/Perl/Animate-a-pendulum b/Lang/Perl/Animate-a-pendulum new file mode 120000 index 0000000000..5c30f58a81 --- /dev/null +++ b/Lang/Perl/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Perl \ No newline at end of file diff --git a/Lang/Perl/Arithmetic-Integer b/Lang/Perl/Arithmetic-Integer new file mode 120000 index 0000000000..4d5d3e8938 --- /dev/null +++ b/Lang/Perl/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Perl \ No newline at end of file diff --git a/Lang/Perl/Averages-Mode b/Lang/Perl/Averages-Mode new file mode 120000 index 0000000000..42fd4c459a --- /dev/null +++ b/Lang/Perl/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Perl \ No newline at end of file diff --git a/Lang/PicoLisp/Animate-a-pendulum b/Lang/PicoLisp/Animate-a-pendulum new file mode 120000 index 0000000000..11ec6130c4 --- /dev/null +++ b/Lang/PicoLisp/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Arithmetic-Integer b/Lang/PicoLisp/Arithmetic-Integer new file mode 120000 index 0000000000..41281693a5 --- /dev/null +++ b/Lang/PicoLisp/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Averages-Mode b/Lang/PicoLisp/Averages-Mode new file mode 120000 index 0000000000..a8c65ac016 --- /dev/null +++ b/Lang/PicoLisp/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/PicoLisp \ No newline at end of file diff --git a/Lang/Prolog/Animate-a-pendulum b/Lang/Prolog/Animate-a-pendulum new file mode 120000 index 0000000000..e17a54693e --- /dev/null +++ b/Lang/Prolog/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Prolog \ No newline at end of file diff --git a/Lang/Python/Animate-a-pendulum b/Lang/Python/Animate-a-pendulum new file mode 120000 index 0000000000..3cf0423f81 --- /dev/null +++ b/Lang/Python/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Python \ No newline at end of file diff --git a/Lang/Python/Arithmetic-Integer b/Lang/Python/Arithmetic-Integer new file mode 120000 index 0000000000..23a22aaf2f --- /dev/null +++ b/Lang/Python/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Python \ No newline at end of file diff --git a/Lang/Python/Averages-Mode b/Lang/Python/Averages-Mode new file mode 120000 index 0000000000..b87335c017 --- /dev/null +++ b/Lang/Python/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Python \ No newline at end of file diff --git a/Lang/R/Arithmetic-Integer b/Lang/R/Arithmetic-Integer new file mode 120000 index 0000000000..ae0e31e558 --- /dev/null +++ b/Lang/R/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/R \ No newline at end of file diff --git a/Lang/R/Averages-Mode b/Lang/R/Averages-Mode new file mode 120000 index 0000000000..dfd6d17149 --- /dev/null +++ b/Lang/R/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/R \ No newline at end of file diff --git a/Lang/REXX/Arithmetic-Integer b/Lang/REXX/Arithmetic-Integer new file mode 120000 index 0000000000..cdcb78fde4 --- /dev/null +++ b/Lang/REXX/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/REXX \ No newline at end of file diff --git a/Lang/REXX/Averages-Mode b/Lang/REXX/Averages-Mode new file mode 120000 index 0000000000..5eccc25f2f --- /dev/null +++ b/Lang/REXX/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/REXX \ No newline at end of file diff --git a/Lang/Racket/Animate-a-pendulum b/Lang/Racket/Animate-a-pendulum new file mode 120000 index 0000000000..46a55b32b4 --- /dev/null +++ b/Lang/Racket/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Racket \ No newline at end of file diff --git a/Lang/Racket/Arithmetic-Integer b/Lang/Racket/Arithmetic-Integer new file mode 120000 index 0000000000..cbc207cf51 --- /dev/null +++ b/Lang/Racket/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Racket \ No newline at end of file diff --git a/Lang/Ruby/Animate-a-pendulum b/Lang/Ruby/Animate-a-pendulum new file mode 120000 index 0000000000..00f4d1e9c2 --- /dev/null +++ b/Lang/Ruby/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Arithmetic-Integer b/Lang/Ruby/Arithmetic-Integer new file mode 120000 index 0000000000..2a84332343 --- /dev/null +++ b/Lang/Ruby/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Averages-Mode b/Lang/Ruby/Averages-Mode new file mode 120000 index 0000000000..17367c789d --- /dev/null +++ b/Lang/Ruby/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Ruby \ No newline at end of file diff --git a/Lang/SNUSP/Arithmetic-Integer b/Lang/SNUSP/Arithmetic-Integer new file mode 120000 index 0000000000..fae3f10a21 --- /dev/null +++ b/Lang/SNUSP/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/SNUSP \ No newline at end of file diff --git a/Lang/Scala/Animate-a-pendulum b/Lang/Scala/Animate-a-pendulum new file mode 120000 index 0000000000..27c089a488 --- /dev/null +++ b/Lang/Scala/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Scala \ No newline at end of file diff --git a/Lang/Scala/Arithmetic-Integer b/Lang/Scala/Arithmetic-Integer new file mode 120000 index 0000000000..6985d8ca71 --- /dev/null +++ b/Lang/Scala/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Scala \ No newline at end of file diff --git a/Lang/Scala/Averages-Mode b/Lang/Scala/Averages-Mode new file mode 120000 index 0000000000..de36782b73 --- /dev/null +++ b/Lang/Scala/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Scala \ No newline at end of file diff --git a/Lang/Scheme/Animate-a-pendulum b/Lang/Scheme/Animate-a-pendulum new file mode 120000 index 0000000000..e763b98eb4 --- /dev/null +++ b/Lang/Scheme/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Arithmetic-Integer b/Lang/Scheme/Arithmetic-Integer new file mode 120000 index 0000000000..9dc04a055d --- /dev/null +++ b/Lang/Scheme/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Averages-Mode b/Lang/Scheme/Averages-Mode new file mode 120000 index 0000000000..6807b0dcae --- /dev/null +++ b/Lang/Scheme/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Scheme \ No newline at end of file diff --git a/Lang/Smalltalk/Arithmetic-Integer b/Lang/Smalltalk/Arithmetic-Integer new file mode 120000 index 0000000000..95d0d37de9 --- /dev/null +++ b/Lang/Smalltalk/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Averages-Mode b/Lang/Smalltalk/Averages-Mode new file mode 120000 index 0000000000..ee40277901 --- /dev/null +++ b/Lang/Smalltalk/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Smalltalk \ No newline at end of file diff --git a/Lang/Tcl/Animate-a-pendulum b/Lang/Tcl/Animate-a-pendulum new file mode 120000 index 0000000000..85d75ea5ea --- /dev/null +++ b/Lang/Tcl/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Arithmetic-Integer b/Lang/Tcl/Arithmetic-Integer new file mode 120000 index 0000000000..c9c7f8dadb --- /dev/null +++ b/Lang/Tcl/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Averages-Mode b/Lang/Tcl/Averages-Mode new file mode 120000 index 0000000000..74ae4acc6c --- /dev/null +++ b/Lang/Tcl/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Tcl \ No newline at end of file diff --git a/Meta/00Langs.yaml b/Meta/00Langs.yaml index b6a144c478..f961496fbb 100644 --- a/Meta/00Langs.yaml +++ b/Meta/00Langs.yaml @@ -344,6 +344,11 @@ Lua: name: Lua path: Lua url: Lua +MATLAB: + ext: m + name: MATLAB + path: MATLAB + url: MATLAB PHP: ext: php name: PHP diff --git a/Meta/00Tasks.yaml b/Meta/00Tasks.yaml index c432ca2484..20f7fd76b3 100644 --- a/Meta/00Tasks.yaml +++ b/Meta/00Tasks.yaml @@ -59,6 +59,10 @@ Anagrams/Deranged anagrams: name: Anagrams/Deranged anagrams path: Anagrams-Deranged-anagrams url: Anagrams/Deranged_anagrams +Animate a pendulum: + name: Animate a pendulum + path: Animate-a-pendulum + url: Animate_a_pendulum Animation: name: Animation path: Animation @@ -91,6 +95,10 @@ Arithmetic/Complex: name: Arithmetic/Complex path: Arithmetic-Complex url: Arithmetic/Complex +Arithmetic/Integer: + name: Arithmetic/Integer + path: Arithmetic-Integer + url: Arithmetic/Integer Arithmetic/Rational: name: Arithmetic/Rational path: Arithmetic-Rational @@ -139,6 +147,10 @@ Averages/Median: name: Averages/Median path: Averages-Median url: Averages/Median +Averages/Mode: + name: Averages/Mode + path: Averages-Mode + url: Averages/Mode Averages/Pythagorean means: name: Averages/Pythagorean means path: Averages-Pythagorean-means diff --git a/Task/100-doors/MATLAB/100-doors-1.m b/Task/100-doors/MATLAB/100-doors-1.m new file mode 100644 index 0000000000..3e87d2a41f --- /dev/null +++ b/Task/100-doors/MATLAB/100-doors-1.m @@ -0,0 +1,11 @@ +a=zeros(1,100); +for b=1:100; +for i=b:b:100; + if a(i)==1 + a(i)=0; + else + a(i)=1; + end +end +end +a diff --git a/Task/100-doors/MATLAB/100-doors-2.m b/Task/100-doors/MATLAB/100-doors-2.m new file mode 100644 index 0000000000..cec46e77b6 --- /dev/null +++ b/Task/100-doors/MATLAB/100-doors-2.m @@ -0,0 +1,6 @@ +for x=1:100; + if sqrt(x) == floor(sqrt(x)) + a(i)=1; + end +end +a diff --git a/Task/100-doors/MATLAB/100-doors-3.m b/Task/100-doors/MATLAB/100-doors-3.m new file mode 100644 index 0000000000..e1e5c60067 --- /dev/null +++ b/Task/100-doors/MATLAB/100-doors-3.m @@ -0,0 +1,5 @@ +a = zeros(100,1); +for counter = 1:sqrt(100); + a(counter^2) = 1; +end +a diff --git a/Task/100-doors/MATLAB/100-doors-4.m b/Task/100-doors/MATLAB/100-doors-4.m new file mode 100644 index 0000000000..4e7da60177 --- /dev/null +++ b/Task/100-doors/MATLAB/100-doors-4.m @@ -0,0 +1,15 @@ +function [doors,opened,closed] = hundredDoors() + + %Initialize the doors, make them booleans for easy vectorization + doors = logical( (1:1:100) ); + + %Go through the flipping process, ignore the 1 case because the doors + %array is already initialized to all open + for initialPosition = (2:100) + doors(initialPosition:initialPosition:100) = not( doors(initialPosition:initialPosition:100) ); + end + + opened = find(doors); %Stores the numbers of the open doors + closed = find( not(doors) ); %Stores the numbers of the closed doors + +end diff --git a/Task/100-doors/MATLAB/100-doors-5.m b/Task/100-doors/MATLAB/100-doors-5.m new file mode 100644 index 0000000000..cbe97b4f9b --- /dev/null +++ b/Task/100-doors/MATLAB/100-doors-5.m @@ -0,0 +1,3 @@ +doors((1:10).^2) = 1; + +doors diff --git a/Task/24-game/MATLAB/24-game.m b/Task/24-game/MATLAB/24-game.m new file mode 100644 index 0000000000..c97ac421dd --- /dev/null +++ b/Task/24-game/MATLAB/24-game.m @@ -0,0 +1,27 @@ + function twentyfour() + N = 4; + n = ceil(rand(1,N)*9); + printf('Generate a equation with the numbers %i, %i, %i, %i and +, -, *, /, () operators ! \n',n); + s = input(': ','s'); + t = s; + for k = 1:N, + [x,t] = strtok(t,'+-*/() \t'); + if length(x)~=1, + error('invalid sign %s\n',x); + end; + y = x-'0'; + if ~(0 < y & y < 10) + error('invalid sign %s\n',x); + end; + z(1,k) = y; + end; + if any(sort(z)-sort(n)) + error('numbers do not match.\n'); + end; + + val = eval(s); + if val==24, + fprintf('expression "%s" results in %i.\n',s,val); + else + fprintf('expression "%s" does not result in 24 but %i.\n',s,val); + end; diff --git a/Task/99-Bottles-of-Beer/MATLAB/99-bottles-of-beer.m b/Task/99-Bottles-of-Beer/MATLAB/99-bottles-of-beer.m new file mode 100644 index 0000000000..237f4c62b7 --- /dev/null +++ b/Task/99-Bottles-of-Beer/MATLAB/99-bottles-of-beer.m @@ -0,0 +1,11 @@ +function ninetyNineBottlesOfBeer() + + disp( [ sprintf(['%d bottles of beer on the wall, %d bottles of beer.\n'... + 'Take one down, pass it around...\n'],[(99:-1:2);(99:-1:2)])... + sprintf(['1 bottle of beer on the wall, 1 bottle of beer.\nTake'... + 'one down, pass it around;\nNo more bottles of beer on the wall.']) ] ); + + %The end of this song makes me sad. The shelf should always have more + %beer...like college. + +end diff --git a/Task/A+B/MATLAB/a+b.m b/Task/A+B/MATLAB/a+b.m new file mode 100644 index 0000000000..f6336cff75 --- /dev/null +++ b/Task/A+B/MATLAB/a+b.m @@ -0,0 +1,8 @@ +function sumOfInputs = APlusB() + inputStream = input('Enter two numbers, separated by a space: ', 's'); + numbers = str2num(inputStream); %#ok + if any(numbers < -1000 | numbers > 1000) + warning('APlusB:OutOfRange', 'Some numbers are outside the range'); + end + sumOfInputs = sum(numbers); +end diff --git a/Task/Ackermann-function/MATLAB/ackermann-function.m b/Task/Ackermann-function/MATLAB/ackermann-function.m new file mode 100644 index 0000000000..e16f7e131c --- /dev/null +++ b/Task/Ackermann-function/MATLAB/ackermann-function.m @@ -0,0 +1,9 @@ +function A = ackermannFunction(m,n) + if m == 0 + A = n+1; + elseif (m > 0) && (n == 0) + A = ackermannFunction(m-1,1); + else + A = ackermannFunction( m-1,ackermannFunction(m,n-1) ); + end +end diff --git a/Task/Animate-a-pendulum/0DESCRIPTION b/Task/Animate-a-pendulum/0DESCRIPTION new file mode 100644 index 0000000000..75f411c684 --- /dev/null +++ b/Task/Animate-a-pendulum/0DESCRIPTION @@ -0,0 +1,3 @@ +One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a [[wp:Pendulum|simple gravity pendulum]]. + +For this task, create a simple physical model of a pendulum and animate it. diff --git a/Task/Animate-a-pendulum/1META.yaml b/Task/Animate-a-pendulum/1META.yaml new file mode 100644 index 0000000000..76abc113c0 --- /dev/null +++ b/Task/Animate-a-pendulum/1META.yaml @@ -0,0 +1,4 @@ +--- +note: Temporal media +requires: +- Graphics diff --git a/Task/Animate-a-pendulum/Ada/animate-a-pendulum-1.ada b/Task/Animate-a-pendulum/Ada/animate-a-pendulum-1.ada new file mode 100644 index 0000000000..2c0083d9ca --- /dev/null +++ b/Task/Animate-a-pendulum/Ada/animate-a-pendulum-1.ada @@ -0,0 +1,19 @@ +generic + type Float_Type is digits <>; + Gravitation : Float_Type; +package Pendulums is + type Pendulum is private; + function New_Pendulum (Length : Float_Type; + Theta0 : Float_Type) return Pendulum; + function Get_X (From : Pendulum) return Float_Type; + function Get_Y (From : Pendulum) return Float_Type; + procedure Update_Pendulum (Item : in out Pendulum; Time : in Duration); +private + type Pendulum is record + Length : Float_Type; + Theta : Float_Type; + X : Float_Type; + Y : Float_Type; + Velocity : Float_Type; + end record; +end Pendulums; diff --git a/Task/Animate-a-pendulum/Ada/animate-a-pendulum-2.ada b/Task/Animate-a-pendulum/Ada/animate-a-pendulum-2.ada new file mode 100644 index 0000000000..7eeca0e834 --- /dev/null +++ b/Task/Animate-a-pendulum/Ada/animate-a-pendulum-2.ada @@ -0,0 +1,38 @@ +with Ada.Numerics.Generic_Elementary_Functions; +package body Pendulums is + package Math is new Ada.Numerics.Generic_Elementary_Functions (Float_Type); + + function New_Pendulum (Length : Float_Type; + Theta0 : Float_Type) return Pendulum is + Result : Pendulum; + begin + Result.Length := Length; + Result.Theta := Theta0 / 180.0 * Ada.Numerics.Pi; + Result.X := Math.Sin (Theta0) * Length; + Result.Y := Math.Cos (Theta0) * Length; + Result.Velocity := 0.0; + return Result; + end New_Pendulum; + + function Get_X (From : Pendulum) return Float_Type is + begin + return From.X; + end Get_X; + + function Get_Y (From : Pendulum) return Float_Type is + begin + return From.Y; + end Get_Y; + + procedure Update_Pendulum (Item : in out Pendulum; Time : in Duration) is + Acceleration : constant Float_Type := Gravitation / Item.Length * + Math.Sin (Item.Theta); + begin + Item.X := Math.Sin (Item.Theta) * Item.Length; + Item.Y := Math.Cos (Item.Theta) * Item.Length; + Item.Velocity := Item.Velocity + + Acceleration * Float_Type (Time); + Item.Theta := Item.Theta + + Item.Velocity * Float_Type (Time); + end Update_Pendulum; +end Pendulums; diff --git a/Task/Animate-a-pendulum/Ada/animate-a-pendulum-3.ada b/Task/Animate-a-pendulum/Ada/animate-a-pendulum-3.ada new file mode 100644 index 0000000000..8ffa9cda0a --- /dev/null +++ b/Task/Animate-a-pendulum/Ada/animate-a-pendulum-3.ada @@ -0,0 +1,24 @@ +with Ada.Text_IO; +with Ada.Calendar; +with Pendulums; + +procedure Main is + package Float_Pendulum is new Pendulums (Float, -9.81); + use Float_Pendulum; + use type Ada.Calendar.Time; + + My_Pendulum : Pendulum := New_Pendulum (10.0, 30.0); + Now, Before : Ada.Calendar.Time; +begin + Before := Ada.Calendar.Clock; + loop + Delay 0.1; + Now := Ada.Calendar.Clock; + Update_Pendulum (My_Pendulum, Now - Before); + Before := Now; + -- output positions relative to origin + -- replace with graphical output if wanted + Ada.Text_IO.Put_Line (" X: " & Float'Image (Get_X (My_Pendulum)) & + " Y: " & Float'Image (Get_Y (My_Pendulum))); + end loop; +end Main; diff --git a/Task/Animate-a-pendulum/C/animate-a-pendulum.c b/Task/Animate-a-pendulum/C/animate-a-pendulum.c new file mode 100644 index 0000000000..a3b3273043 --- /dev/null +++ b/Task/Animate-a-pendulum/C/animate-a-pendulum.c @@ -0,0 +1,77 @@ +#include +#include +#include +#include +#include + +#define length 5 +#define g 9.8 +double alpha, accl, omega = 0, E; +struct timeval tv; + +double elappsed() { + struct timeval now; + gettimeofday(&now, 0); + int ret = (now.tv_sec - tv.tv_sec) * 1000000 + + now.tv_usec - tv.tv_usec; + tv = now; + return ret / 1.e6; +} + +void resize(int w, int h) +{ + glViewport(0, 0, w, h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glOrtho(0, w, h, 0, -1, 1); +} + +void render() +{ + double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha); + resize(640, 320); + glClear(GL_COLOR_BUFFER_BIT); + + glBegin(GL_LINES); + glVertex2d(320, 0); + glVertex2d(x, y); + glEnd(); + glFlush(); + + double us = elappsed(); + alpha += (omega + us * accl / 2) * us; + omega += accl * us; + + /* don't let precision error go out of hand */ + if (length * g * (1 - cos(alpha)) >= E) { + alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g); + omega = 0; + } + accl = -g / length * sin(alpha); +} + +void init_gfx(int *c, char **v) +{ + glutInit(c, v); + glutInitDisplayMode(GLUT_RGB); + glutInitWindowSize(640, 320); + glutIdleFunc(render); + glutCreateWindow("Pendulum"); +} + +int main(int c, char **v) +{ + alpha = 4 * atan2(1, 1) / 2.1; + E = length * g * (1 - cos(alpha)); + + accl = -g / length * sin(alpha); + omega = 0; + + gettimeofday(&tv, 0); + init_gfx(&c, v); + glutMainLoop(); + return 0; +} diff --git a/Task/Animate-a-pendulum/Clojure/animate-a-pendulum.clj b/Task/Animate-a-pendulum/Clojure/animate-a-pendulum.clj new file mode 100644 index 0000000000..2cad4a0af2 --- /dev/null +++ b/Task/Animate-a-pendulum/Clojure/animate-a-pendulum.clj @@ -0,0 +1,63 @@ +(ns pendulum + (:import + (javax.swing JFrame) + (java.awt Canvas Graphics Color))) + +(def length 200) +(def width (* 2 (+ 50 length))) +(def height (* 3 (/ length 2))) +(def dt 0.1) +(def g 9.812) +(def k (- (/ g length))) +(def anchor-x (/ width 2)) +(def anchor-y (/ height 8)) +(def angle (atom (/ (Math/PI) 2))) + +(defn draw [#^Canvas canvas angle] + (let [buffer (.getBufferStrategy canvas) + g (.getDrawGraphics buffer) + ball-x (+ anchor-x (* (Math/sin angle) length)) + ball-y (+ anchor-y (* (Math/cos angle) length))] + (try + (doto g + (.setColor Color/BLACK) + (.fillRect 0 0 width height) + (.setColor Color/RED) + (.drawLine anchor-x anchor-y ball-x ball-y) + (.setColor Color/YELLOW) + (.fillOval (- anchor-x 3) (- anchor-y 4) 7 7) + (.fillOval (- ball-x 7) (- ball-y 7) 14 14)) + (finally (.dispose g))) + (if-not (.contentsLost buffer) + (.show buffer)) )) + +(defn start-renderer [canvas] + (->> + (fn [] (draw canvas @angle) (recur)) + (new Thread) + (.start))) + +(defn -main [& args] + (let [frame (JFrame. "Pendulum") + canvas (Canvas.)] + + (doto frame + (.setSize width height) + (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) + (.setResizable false) + (.add canvas) + (.setVisible true)) + + (doto canvas + (.createBufferStrategy 2) + (.setVisible true) + (.requestFocus)) + + (start-renderer canvas) + + (loop [v 0] + (swap! angle #(+ % (* v dt))) + (Thread/sleep 15) + (recur (+ v (* k (Math/sin @angle) dt)))) )) + +(-main) diff --git a/Task/Animate-a-pendulum/Haskell/animate-a-pendulum.hs b/Task/Animate-a-pendulum/Haskell/animate-a-pendulum.hs new file mode 100644 index 0000000000..14b08cff1b --- /dev/null +++ b/Task/Animate-a-pendulum/Haskell/animate-a-pendulum.hs @@ -0,0 +1,28 @@ +import Graphics.HGL.Draw.Monad (Graphic, ) +import Graphics.HGL.Draw.Picture +import Graphics.HGL.Utils +import Graphics.HGL.Window +import Graphics.HGL.Run + +import Control.Exception (bracket, ) +import Control.Arrow + +toInt = fromIntegral.round + +pendulum = runGraphics $ + bracket + (openWindowEx "Pendulum animation task" Nothing (600,400) DoubleBuffered (Just 30)) + closeWindow + (\w -> mapM_ ((\ g -> setGraphic w g >> getWindowTick w). + (\ (x, y) -> overGraphic (line (300, 0) (x, y)) + (ellipse (x - 12, y + 12) (x + 12, y - 12)) )) pts) + where + dt = 1/30 + t = - pi/4 + l = 1 + g = 9.812 + nextAVT (a,v,t) = (a', v', t + v' * dt) where + a' = - (g / l) * sin t + v' = v + a' * dt + pts = map (\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi/2+0.6*t) ) + $ iterate nextAVT (- (g / l) * sin t, t, 0) diff --git a/Task/Animate-a-pendulum/Java/animate-a-pendulum.java b/Task/Animate-a-pendulum/Java/animate-a-pendulum.java new file mode 100644 index 0000000000..0e00783bff --- /dev/null +++ b/Task/Animate-a-pendulum/Java/animate-a-pendulum.java @@ -0,0 +1,52 @@ +import java.awt.*; +import javax.swing.*; + +public class Pendulum extends JPanel implements Runnable { + + private double angle = Math.PI / 2; + private int length; + + public Pendulum(int length) { + this.length = length; + setDoubleBuffered(true); + } + + @Override + public void paint(Graphics g) { + g.setColor(Color.WHITE); + g.fillRect(0, 0, getWidth(), getHeight()); + g.setColor(Color.BLACK); + int anchorX = getWidth() / 2, anchorY = getHeight() / 4; + int ballX = anchorX + (int) (Math.sin(angle) * length); + int ballY = anchorY + (int) (Math.cos(angle) * length); + g.drawLine(anchorX, anchorY, ballX, ballY); + g.fillOval(anchorX - 3, anchorY - 4, 7, 7); + g.fillOval(ballX - 7, ballY - 7, 14, 14); + } + + public void run() { + double angleAccel, angleVelocity = 0, dt = 0.1; + while (true) { + angleAccel = -9.81 / length * Math.sin(angle); + angleVelocity += angleAccel * dt; + angle += angleVelocity * dt; + repaint(); + try { Thread.sleep(15); } catch (InterruptedException ex) {} + } + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(2 * length + 50, length / 2 * 3); + } + + public static void main(String[] args) { + JFrame f = new JFrame("Pendulum"); + Pendulum p = new Pendulum(200); + f.add(p); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.pack(); + f.setVisible(true); + new Thread(p).start(); + } +} diff --git a/Task/Animate-a-pendulum/JavaScript/animate-a-pendulum.js b/Task/Animate-a-pendulum/JavaScript/animate-a-pendulum.js new file mode 100644 index 0000000000..9a63b39964 --- /dev/null +++ b/Task/Animate-a-pendulum/JavaScript/animate-a-pendulum.js @@ -0,0 +1,58 @@ + + Pendulum + + + +

Sorry, your browser does not support the <canvas> used to display the pendulum animation.

+
+ + + diff --git a/Task/Animate-a-pendulum/MATLAB/animate-a-pendulum.m b/Task/Animate-a-pendulum/MATLAB/animate-a-pendulum.m new file mode 100644 index 0000000000..2e4bcba455 --- /dev/null +++ b/Task/Animate-a-pendulum/MATLAB/animate-a-pendulum.m @@ -0,0 +1,66 @@ +%This is a numerical simulation of a pendulum with a massless pivot arm. + +%% User Defined Parameters +%Define external parameters +g = -9.8; +deltaTime = 1/50; %Decreasing this will increase simulation accuracy +endTime = 16; + +%Define pendulum +rodPivotPoint = [2 2]; %rectangular coordinates +rodLength = 1; +mass = 1; %of the bob +radius = .2; %of the bob +theta = 45; %degrees, defines initial position of the bob +velocity = [0 0]; %cylindrical coordinates; first entry is radial velocity, + %second entry is angular velocity + +%% Simulation +assert(radius < rodLength,'Pendulum bob radius must be less than the length of the rod.'); + +position = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]); %in rectangular coordinates + +%Generate graphics, render pendulum +figure; +axesHandle = gca; +xlim(axesHandle, [(rodPivotPoint(1) - rodLength - radius) (rodPivotPoint(1) + rodLength + radius)] ); +ylim(axesHandle, [(rodPivotPoint(2) - rodLength - radius) (rodPivotPoint(2) + rodLength + radius)] ); + +rectHandle = rectangle('Position',[(position - radius/2) radius radius],... + 'Curvature',[1,1],'FaceColor','g'); %Pendulum bob +hold on +plot(rodPivotPoint(1),rodPivotPoint(2),'^'); %pendulum pivot +lineHandle = line([rodPivotPoint(1) position(1)],... + [rodPivotPoint(2) position(2)]); %pendulum rod +hold off + +%Run simulation, all calculations are performed in cylindrical coordinates +for time = (deltaTime:deltaTime:endTime) + + drawnow; %Forces MATLAB to render the pendulum + + %Find total force + gravitationalForceCylindrical = [mass*g*cosd(theta) mass*g*sind(theta)]; + + %This code is just incase you want to add more forces,e.g friction + totalForce = gravitationalForceCylindrical; + + %If the rod isn't massless or is a spring, etc., modify this line + %accordingly + rodForce = [-totalForce(1) 0]; %cylindrical coordinates + + totalForce = totalForce + rodForce; + + acceleration = totalForce / mass; %F = ma + velocity = velocity + acceleration * deltaTime; + rodLength = rodLength + velocity(1) * deltaTime; + theta = theta + velocity(2) * deltaTime; + + position = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]); + + %Update figure with new position info + set(rectHandle,'Position',[(position - radius/2) radius radius]); + set(lineHandle,'XData',[rodPivotPoint(1) position(1)],'YData',... + [rodPivotPoint(2) position(2)]); + +end diff --git a/Task/Animate-a-pendulum/Perl/animate-a-pendulum.pl b/Task/Animate-a-pendulum/Perl/animate-a-pendulum.pl new file mode 100644 index 0000000000..598d5f5955 --- /dev/null +++ b/Task/Animate-a-pendulum/Perl/animate-a-pendulum.pl @@ -0,0 +1,66 @@ +use strict; +use warnings; +use Tk; +use Math::Trig qw/:pi/; + +my $root = new MainWindow( -title => 'Pendulum Animation' ); +my $canvas = $root->Canvas(-width => 320, -height => 200); +my $after_id; + +for ($canvas) { + $_->createLine( 0, 25, 320, 25, -tags => [qw/plate/], -width => 2, -fill => 'grey50' ); + $_->createOval( 155, 20, 165, 30, -tags => [qw/pivot outline/], -fill => 'grey50' ); + $_->createLine( 1, 1, 1, 1, -tags => [qw/rod width/], -width => 3, -fill => 'black' ); + $_->createOval( 1, 1, 2, 2, -tags => [qw/bob outline/], -fill => 'yellow' ); +} + +$canvas->raise('pivot'); +$canvas->pack(-fill => 'both', -expand => 1); +my ($Theta, $dTheta, $length, $homeX, $homeY) = + (45, 0, 150, 160, 25); + +sub show_pendulum { + my $angle = $Theta * pi() / 180; + my $x = $homeX + $length * sin($angle); + my $y = $homeY + $length * cos($angle); + $canvas->coords('rod', $homeX, $homeY, $x, $y); + $canvas->coords('bob', $x-15, $y-15, $x+15, $y+15); +} + + + +sub recompute_angle { + my $scaling = 3000.0 / ($length ** 2); + # first estimate + my $firstDDTheta = -sin($Theta * pi / 180) * $scaling; + my $midDTheta = $dTheta + $firstDDTheta; + my $midTheta = $Theta + ($dTheta + $midDTheta)/2; + # second estimate + my $midDDTheta = -sin($midTheta * pi/ 180) * $scaling; + $midDTheta = $dTheta + ($firstDDTheta + $midDDTheta)/2; + $midTheta = $Theta + ($dTheta + $midDTheta)/2; + # again, first + $midDDTheta = -sin($midTheta * pi/ 180) * $scaling; + my $lastDTheta = $midDTheta + $midDDTheta; + my $lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2; + # again, second + my $lastDDTheta = -sin($lastTheta * pi/180) * $scaling; + $lastDTheta = $midDTheta + ($midDDTheta + $lastDDTheta)/2; + $lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2; + # Now put the values back in our globals + $dTheta = $lastDTheta; + $Theta = $lastTheta; +} + + +sub animate { + recompute_angle; + show_pendulum; + $after_id = $root->after(15 => sub {animate() }); +} + +show_pendulum; +$after_id = $root->after(500 => sub {animate}); + +$canvas->bind('' => sub {$after_id->cancel}); +MainLoop; diff --git a/Task/Animate-a-pendulum/PicoLisp/animate-a-pendulum-1.l b/Task/Animate-a-pendulum/PicoLisp/animate-a-pendulum-1.l new file mode 100644 index 0000000000..18915b8df9 --- /dev/null +++ b/Task/Animate-a-pendulum/PicoLisp/animate-a-pendulum-1.l @@ -0,0 +1,15 @@ +(load "@lib/math.l") + +(de pendulum (X Y Len) + (let (Angle pi/2 V 0) + (call 'clear) + (call 'tput "cup" Y X) + (prin '+) + (call 'tput "cup" 1 (+ X Len)) + (until (key 25) # 25 ms + (let A (*/ (sin Angle) -9.81 1.0) + (inc 'V (*/ A 40)) # DT = 25 ms = 1/40 sec + (inc 'Angle (*/ V 40)) ) + (call 'tput "cup" + (+ Y (*/ Len (cos Angle) 2.2)) # Compensate for aspect ratio + (+ X (*/ Len (sin Angle) 1.0)) ) ) ) ) diff --git a/Task/Animate-a-pendulum/PicoLisp/animate-a-pendulum-2.l b/Task/Animate-a-pendulum/PicoLisp/animate-a-pendulum-2.l new file mode 100644 index 0000000000..8cb16a17bc --- /dev/null +++ b/Task/Animate-a-pendulum/PicoLisp/animate-a-pendulum-2.l @@ -0,0 +1 @@ +(pendulum 40 1 36) diff --git a/Task/Animate-a-pendulum/Prolog/animate-a-pendulum.pro b/Task/Animate-a-pendulum/Prolog/animate-a-pendulum.pro new file mode 100644 index 0000000000..a97c48257d --- /dev/null +++ b/Task/Animate-a-pendulum/Prolog/animate-a-pendulum.pro @@ -0,0 +1,80 @@ +:- use_module(library(pce)). + +pendulum :- + new(D, window('Pendulum')), + send(D, size, size(560, 300)), + new(Line, line(80, 50, 480, 50)), + send(D, display, Line), + new(Circle, circle(20)), + send(Circle, fill_pattern, colour(@default, 0, 0, 0)), + new(Boule, circle(60)), + send(Boule, fill_pattern, colour(@default, 0, 0, 0)), + send(D, display, Circle, point(270,40)), + send(Circle, handle, handle(h/2, w/2, in)), + send(Boule, handle, handle(h/2, w/2, out)), + send(Circle, connect, Boule, link(in, out, line(0,0,0,0,none))), + new(Anim, animation(D, 0.0, Boule, 200.0)), + send(D, done_message, and(message(Anim, free), + message(Boule, free), + message(Circle, free), + message(@receiver,destroy))), + send(Anim?mytimer, start), + send(D, open). + + + + +:- pce_begin_class(animation(window, angle, boule, len_pendulum), object). +variable(window, object, both, "Display window"). +variable(boule, object, both, "bowl of the pendulum"). +variable(len_pendulum, object, both, "len of the pendulum"). +variable(angle, object, both, "angle with the horizontal"). +variable(delta, object, both, "increment of the angle"). +variable(mytimer, timer, both, "timer of the animation"). + +initialise(P, W:object, A:object, B : object, L:object) :-> + "Creation of the object":: + send(P, window, W), + send(P, angle, A), + send(P, boule, B), + send(P, len_pendulum, L), + send(P, delta, 0.01), + send(P, mytimer, new(_, timer(0.01,message(P, anim_message)))). + +% method called when the object is destroyed +% first the timer is stopped +% then all the resources are freed +unlink(P) :-> + send(P?mytimer, stop), + send(P, send_super, unlink). + + +% message processed by the timer +anim_message(P) :-> + get(P, angle, A), + get(P, len_pendulum, L), + calc(A, L, X, Y), + get(P, window, W), + get(P, boule, B), + send(W, display, B, point(X,Y)), + % computation of the next position + get(P, delta, D), + next_Angle(A, D, NA, ND), + send(P, angle, NA), + send(P, delta, ND). + +:- pce_end_class. + +% computation of the position of the bowl. +calc(Ang, Len, X, Y) :- + X is Len * cos(Ang)+ 250, + Y is Len * sin(Ang) + 20. + + +% computation of the next angle +% if we reach 0 or pi, delta change. +next_Angle(A, D, NA, ND) :- + NA is D + A, + (((D > 0, abs(pi-NA) < 0.01); (D < 0, abs(NA) < 0.01))-> + ND = - D; + ND = D). diff --git a/Task/Animate-a-pendulum/Python/animate-a-pendulum.py b/Task/Animate-a-pendulum/Python/animate-a-pendulum.py new file mode 100644 index 0000000000..3afd423359 --- /dev/null +++ b/Task/Animate-a-pendulum/Python/animate-a-pendulum.py @@ -0,0 +1,82 @@ +import pygame, sys +from pygame.locals import * +from math import sin, cos, radians + +pygame.init() + +WINDOWSIZE = 250 +TIMETICK = 100 +BOBSIZE = 15 + +window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) +pygame.display.set_caption("Pendulum") + +screen = pygame.display.get_surface() +screen.fill((255,255,255)) + +PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) +SWINGLENGTH = PIVOT[1]*4 + +class BobMass(pygame.sprite.Sprite): + def __init__(self): + pygame.sprite.Sprite.__init__(self) + self.theta = 45 + self.dtheta = 0 + self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), + PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), + 1,1) + self.draw() + + def recomputeAngle(self): + scaling = 3000.0/(SWINGLENGTH**2) + + firstDDtheta = -sin(radians(self.theta))*scaling + midDtheta = self.dtheta + firstDDtheta + midtheta = self.theta + (self.dtheta + midDtheta)/2.0 + + midDDtheta = -sin(radians(midtheta))*scaling + midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 + midtheta = self.theta + (self.dtheta + midDtheta)/2 + + midDDtheta = -sin(radians(midtheta)) * scaling + lastDtheta = midDtheta + midDDtheta + lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 + + lastDDtheta = -sin(radians(lasttheta)) * scaling + lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 + lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 + + self.dtheta = lastDtheta + self.theta = lasttheta + self.rect = pygame.Rect(PIVOT[0]- + SWINGLENGTH*sin(radians(self.theta)), + PIVOT[1]+ + SWINGLENGTH*cos(radians(self.theta)),1,1) + + + def draw(self): + pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) + pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) + pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) + pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) + + def update(self): + self.recomputeAngle() + screen.fill((255,255,255)) + self.draw() + +bob = BobMass() + +TICK = USEREVENT + 2 +pygame.time.set_timer(TICK, TIMETICK) + +def input(events): + for event in events: + if event.type == QUIT: + sys.exit(0) + elif event.type == TICK: + bob.update() + +while True: + input(pygame.event.get()) + pygame.display.flip() diff --git a/Task/Animate-a-pendulum/Racket/animate-a-pendulum.rkt b/Task/Animate-a-pendulum/Racket/animate-a-pendulum.rkt new file mode 100644 index 0000000000..9db707cf40 --- /dev/null +++ b/Task/Animate-a-pendulum/Racket/animate-a-pendulum.rkt @@ -0,0 +1,20 @@ +#lang racket + +(require 2htdp/image + 2htdp/universe) + +(define (pendulum) + (define (accel θ) (- (sin θ))) + (define θ (/ pi 2.5)) + (define θ′ 0) + (define θ′′ (accel (/ pi 2.5))) + (define (x θ) (+ 200 (* 150 (sin θ)))) + (define (y θ) (* 150 (cos θ))) + (λ (n) + (define p-image (underlay/xy (add-line (empty-scene 400 200) 200 0 (x θ) (y θ) "black") + (- (x θ) 5) (- (y θ) 5) (circle 5 "solid" "blue"))) + (set! θ (+ θ (* θ′ 0.04))) + (set! θ′ (+ θ′ (* (accel θ) 0.04))) + p-image)) + +(animate (pendulum)) diff --git a/Task/Animate-a-pendulum/Ruby/animate-a-pendulum-1.rb b/Task/Animate-a-pendulum/Ruby/animate-a-pendulum-1.rb new file mode 100644 index 0000000000..d868672ba8 --- /dev/null +++ b/Task/Animate-a-pendulum/Ruby/animate-a-pendulum-1.rb @@ -0,0 +1,63 @@ +require 'tk' + +$root = TkRoot.new("title" => "Pendulum Animation") +$canvas = TkCanvas.new($root) do + width 320 + height 200 + create TkcLine, 0,25,320,25, 'tags' => 'plate', 'width' => 2, 'fill' => 'grey50' + create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => "", 'fill' => 'grey50' + create TkcLine, 1,1,1,1, 'tags' => 'rod', 'width' => 3, 'fill' => 'black' + create TkcOval, 1,1,2,2, 'tags' => 'bob', 'outline' => 'black', 'fill' => 'yellow' +end +$canvas.raise('pivot') +$canvas.pack('fill' => 'both', 'expand' => true) + +$Theta = 45.0 +$dTheta = 0.0 +$length = 150 +$homeX = 160 +$homeY = 25 + +def show_pendulum + angle = $Theta * Math::PI / 180 + x = $homeX + $length * Math.sin(angle) + y = $homeY + $length * Math.cos(angle) + $canvas.coords('rod', $homeX, $homeY, x, y) + $canvas.coords('bob', x-15, y-15, x+15, y+15) +end + +def recompute_angle + scaling = 3000.0 / ($length ** 2) + # first estimate + firstDDTheta = -Math.sin($Theta * Math::PI / 180) * scaling + midDTheta = $dTheta + firstDDTheta + midTheta = $Theta + ($dTheta + midDTheta)/2 + # second estimate + midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling + midDTheta = $dTheta + (firstDDTheta + midDDTheta)/2 + midTheta = $Theta + ($dTheta + midDTheta)/2 + # again, first + midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling + lastDTheta = midDTheta + midDDTheta + lastTheta = midTheta + (midDTheta + lastDTheta)/2 + # again, second + lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling + lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2 + lastTheta = midTheta + (midDTheta + lastDTheta)/2 + # Now put the values back in our globals + $dTheta = lastDTheta + $Theta = lastTheta +end + +def animate + recompute_angle + show_pendulum + $after_id = $root.after(15) {animate} +end + +show_pendulum +$after_id = $root.after(500) {animate} + +$canvas.bind('') {$root.after_cancel($after_id)} + +Tk.mainloop diff --git a/Task/Animate-a-pendulum/Ruby/animate-a-pendulum-2.rb b/Task/Animate-a-pendulum/Ruby/animate-a-pendulum-2.rb new file mode 100644 index 0000000000..524aa42701 --- /dev/null +++ b/Task/Animate-a-pendulum/Ruby/animate-a-pendulum-2.rb @@ -0,0 +1,57 @@ +Shoes.app(:width => 320, :height => 200) do + @centerX = 160 + @centerY = 25 + @length = 150 + @diameter = 15 + + @Theta = 45.0 + @dTheta = 0.0 + + stroke gray + strokewidth 3 + line 0,25,320,25 + oval 155,20,10 + + stroke black + @rod = line(@centerX, @centerY, @centerX, @centerY + @length) + @bob = oval(@centerX - @diameter, @centerY + @length - @diameter, 2*@diameter) + + animate(24) do |i| + recompute_angle + show_pendulum + end + + def show_pendulum + angle = (90 + @Theta) * Math::PI / 180 + x = @centerX + (Math.cos(angle) * @length).to_i + y = @centerY + (Math.sin(angle) * @length).to_i + + @rod.remove + strokewidth 3 + @rod = line(@centerX, @centerY, x, y) + @bob.move(x-@diameter, y-@diameter) + end + + def recompute_angle + scaling = 3000.0 / (@length **2) + # first estimate + firstDDTheta = -Math.sin(@Theta * Math::PI / 180) * scaling + midDTheta = @dTheta + firstDDTheta + midTheta = @Theta + (@dTheta + midDTheta)/2 + # second estimate + midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling + midDTheta = @dTheta + (firstDDTheta + midDDTheta)/2 + midTheta = @Theta + (@dTheta + midDTheta)/2 + # again, first + midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling + lastDTheta = midDTheta + midDDTheta + lastTheta = midTheta + (midDTheta + lastDTheta)/2 + # again, second + lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling + lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2 + lastTheta = midTheta + (midDTheta + lastDTheta)/2 + # Now put the values back in our globals + @dTheta = lastDTheta + @Theta = lastTheta + end +end diff --git a/Task/Animate-a-pendulum/Scala/animate-a-pendulum.scala b/Task/Animate-a-pendulum/Scala/animate-a-pendulum.scala new file mode 100644 index 0000000000..292f77aa72 --- /dev/null +++ b/Task/Animate-a-pendulum/Scala/animate-a-pendulum.scala @@ -0,0 +1,64 @@ +import scala.swing._ +import scala.swing.Swing._ +import scala.actors._ +import scala.actors.Actor._ + +import java.awt.{Color, Graphics} + +object Pendulum extends SimpleSwingApplication { + + val length = 100 + + val prefSizeX = 2*length+50 + val prefSizeY = length/2*3 + + lazy val ui = new Panel { + import math._ + background = Color.white + preferredSize = (prefSizeX, prefSizeY) + peer.setDoubleBuffered(true) + + var angle: Double = Pi/2; + + def pendular = new Actor { + var angleAccel, angleVelocity = 0.0; + var dt = 0.1 + + def act() { + while (true) { + angleAccel = -9.81 / length * sin(angle) + angleVelocity += angleAccel * dt + angle += angleVelocity * dt + repaint() + Thread.sleep(15) + } + } + } + + override def paintComponent(g: Graphics2D) = { + super.paintComponent(g) + + g.setColor(Color.white); + g.fillRect(0, 0, size.width, size.height); + val anchorX = size.width / 2 + val anchorY = size.height / 4 + val ballX = anchorX + (sin(angle) * length).toInt + val ballY = anchorY + (cos(angle) * length).toInt + g.setColor(Color.lightGray) + g.drawLine(anchorX-2*length, anchorY, anchorX+2*length, anchorY) + g.setColor(Color.black) + g.drawLine(anchorX, anchorY, ballX, ballY) + g.fillOval(anchorX - 3, anchorY - 4, 7, 7) + g.drawOval(ballX - 7, ballY - 7, 14, 14) + g.setColor(Color.yellow) + g.fillOval(ballX - 7, ballY - 7, 14, 14) + } + } + + def top = new MainFrame { + title = "Rosetta Code >>> Task: Animate a pendulum | Language: Scala" + contents = ui + ui.pendular.start + } + +} diff --git a/Task/Animate-a-pendulum/Scheme/animate-a-pendulum.ss b/Task/Animate-a-pendulum/Scheme/animate-a-pendulum.ss new file mode 100644 index 0000000000..d3adf9423d --- /dev/null +++ b/Task/Animate-a-pendulum/Scheme/animate-a-pendulum.ss @@ -0,0 +1,71 @@ +#!r6rs + +;;; R6RS implementation of Pendulum Animation + +(import (rnrs) + (lib pstk main) ; change this for your pstk installation + ) + +(define PI 3.14159) +(define *conv-radians* (/ PI 180)) +(define *theta* 45.0) +(define *d-theta* 0.0) +(define *length* 150) +(define *home-x* 160) +(define *home-y* 25) + +;;; estimates new angle of pendulum +(define (recompute-angle) + (define (avg a b) (/ (+ a b) 2)) + (let* ((scaling (/ 3000.0 (* *length* *length*))) + ; first estimate + (first-dd-theta (- (* (sin (* *theta* *conv-radians*)) scaling))) + (mid-d-theta (+ *d-theta* first-dd-theta)) + (mid-theta (+ *theta* (avg *d-theta* mid-d-theta))) + ; second estimate + (mid-dd-theta (- (* (sin (* mid-theta *conv-radians*)) scaling))) + (mid-d-theta-2 (+ *d-theta* (avg first-dd-theta mid-dd-theta))) + (mid-theta-2 (+ *theta* (avg *d-theta* mid-d-theta-2))) + ; again first + (mid-dd-theta-2 (- (* (sin (* mid-theta-2 *conv-radians*)) scaling))) + (last-d-theta (+ mid-d-theta-2 mid-dd-theta-2)) + (last-theta (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta))) + ; again second + (last-dd-theta (- (* (sin (* last-theta *conv-radians*)) scaling))) + (last-d-theta-2 (+ mid-d-theta-2 (avg mid-dd-theta-2 last-dd-theta))) + (last-theta-2 (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta-2)))) + ; put values back in globals + (set! *d-theta* last-d-theta-2) + (set! *theta* last-theta-2))) + +;;; The main event loop and graphics context +(let ((tk (tk-start))) + (tk/wm 'title tk "Pendulum Animation") + (let ((canvas (tk 'create-widget 'canvas))) + + ;;; redraw the pendulum on canvas + ;;; - uses angle and length to compute new (x,y) position of bob + (define (show-pendulum canvas) + (let* ((pendulum-angle (* *conv-radians* *theta*)) + (x (+ *home-x* (* *length* (sin pendulum-angle)))) + (y (+ *home-y* (* *length* (cos pendulum-angle))))) + (canvas 'coords 'rod *home-x* *home-y* x y) + (canvas 'coords 'bob (- x 15) (- y 15) (+ x 15) (+ y 15)))) + + ;;; move the pendulum and repeat after 20ms + (define (animate) + (recompute-angle) + (show-pendulum canvas) + (tk/after 20 animate)) + + ;; layout the canvas + (tk/grid canvas 'column: 0 'row: 0) + (canvas 'create 'line 0 25 320 25 'tags: 'plate 'width: 2 'fill: 'grey50) + (canvas 'create 'oval 155 20 165 30 'tags: 'pivot 'outline: "" 'fill: 'grey50) + (canvas 'create 'line 1 1 1 1 'tags: 'rod 'width: 3 'fill: 'black) + (canvas 'create 'oval 1 1 2 2 'tags: 'bob 'outline: 'black 'fill: 'yellow) + + ;; get everything started + (show-pendulum canvas) + (tk/after 500 animate) + (tk-event-loop tk))) diff --git a/Task/Animate-a-pendulum/Tcl/animate-a-pendulum.tcl b/Task/Animate-a-pendulum/Tcl/animate-a-pendulum.tcl new file mode 100644 index 0000000000..1d15c8775e --- /dev/null +++ b/Task/Animate-a-pendulum/Tcl/animate-a-pendulum.tcl @@ -0,0 +1,80 @@ +package require Tcl 8.5 +package require Tk + +# Make the graphical entities +pack [canvas .c -width 320 -height 200] -fill both -expand 1 +.c create line 0 25 320 25 -width 2 -fill grey50 -tags plate +.c create line 1 1 1 1 -tags rod -width 3 -fill black +.c create oval 1 1 2 2 -tags bob -fill yellow -outline black +.c create oval 155 20 165 30 -fill grey50 -outline {} -tags pivot + +# Set some vars +set points {} +set Theta 45.0 +set dTheta 0.0 +set pi 3.1415926535897933 +set length 150 +set homeX 160 + +# How to respond to a changing in size of the window +proc resized {width} { + global homeX + .c coords plate 0 25 $width 25 + set homeX [expr {$width / 2}] + .c coords pivot [expr {$homeX-5}] 20 [expr {$homeX+5}] 30 + showPendulum +} + +# How to actually arrange the pendulum, mapping the model to the display +proc showPendulum {} { + global Theta dTheta pi length homeX + set angle [expr {$Theta * $pi/180}] + set x [expr {$homeX + $length*sin($angle)}] + set y [expr {25 + $length*cos($angle)}] + .c coords rod $homeX 25 $x $y + .c coords bob [expr {$x-15}] [expr {$y-15}] [expr {$x+15}] [expr {$y+15}] +} + +# The dynamic part of the display +proc recomputeAngle {} { + global Theta dTheta pi length + set scaling [expr {3000.0/$length**2}] + + # first estimate + set firstDDTheta [expr {-sin($Theta * $pi/180)*$scaling}] + set midDTheta [expr {$dTheta + $firstDDTheta}] + set midTheta [expr {$Theta + ($dTheta + $midDTheta)/2}] + # second estimate + set midDDTheta [expr {-sin($midTheta * $pi/180)*$scaling}] + set midDTheta [expr {$dTheta + ($firstDDTheta + $midDDTheta)/2}] + set midTheta [expr {$Theta + ($dTheta + $midDTheta)/2}] + # Now we do a double-estimate approach for getting the final value + # first estimate + set midDDTheta [expr {-sin($midTheta * $pi/180)*$scaling}] + set lastDTheta [expr {$midDTheta + $midDDTheta}] + set lastTheta [expr {$midTheta + ($midDTheta + $lastDTheta)/2}] + # second estimate + set lastDDTheta [expr {-sin($lastTheta * $pi/180)*$scaling}] + set lastDTheta [expr {$midDTheta + ($midDDTheta + $lastDDTheta)/2}] + set lastTheta [expr {$midTheta + ($midDTheta + $lastDTheta)/2}] + # Now put the values back in our globals + set dTheta $lastDTheta + set Theta $lastTheta +} + +# Run the animation by updating the physical model then the display +proc animate {} { + global animation + + recomputeAngle + showPendulum + + # Reschedule + set animation [after 15 animate] +} +set animation [after 500 animate]; # Extra initial delay is visually pleasing + +# Callback to handle resizing of the canvas +bind .c {resized %w} +# Callback to stop the animation cleanly when the GUI goes away +bind .c {after cancel $animation} diff --git a/Task/Apply-a-callback-to-an-array/MATLAB/apply-a-callback-to-an-array.m b/Task/Apply-a-callback-to-an-array/MATLAB/apply-a-callback-to-an-array.m new file mode 100644 index 0000000000..1285926742 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/MATLAB/apply-a-callback-to-an-array.m @@ -0,0 +1,35 @@ +>> array = [1 2 3 4 5] + +array = + + 1 2 3 4 5 + +>> arrayfun(@sin,array) + +ans = + + Columns 1 through 4 + + 0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928 + + Column 5 + + -0.958924274663138 + +>> cellarray = {1,2,3,4,5} + +cellarray = + + [1] [2] [3] [4] [5] + +>> cellfun(@tan,cellarray) + +ans = + + Columns 1 through 4 + + 1.557407724654902 -2.185039863261519 -0.142546543074278 1.157821282349578 + + Column 5 + + -3.380515006246586 diff --git a/Task/Arbitrary-precision-integers-(included)/MATLAB/arbitrary-precision-integers-(included).m b/Task/Arbitrary-precision-integers-(included)/MATLAB/arbitrary-precision-integers-(included).m new file mode 100644 index 0000000000..4dec511994 --- /dev/null +++ b/Task/Arbitrary-precision-integers-(included)/MATLAB/arbitrary-precision-integers-(included).m @@ -0,0 +1,13 @@ +>> answer = vpi(5)^(vpi(4)^(vpi(3)^vpi(2))); +>> numDigits = order(answer) + 1 + +numDigits = + + 183231 + +>> [sprintf('%d',leadingdigit(answer,20)) '...' sprintf('%d',trailingdigit(answer,20))] +%First and Last 20 Digits + +ans = + +62060698786608744707...92256259918212890625 diff --git a/Task/Arithmetic-Complex/MATLAB/arithmetic-complex.m b/Task/Arithmetic-Complex/MATLAB/arithmetic-complex.m new file mode 100644 index 0000000000..55d2261625 --- /dev/null +++ b/Task/Arithmetic-Complex/MATLAB/arithmetic-complex.m @@ -0,0 +1,59 @@ +>> a = 1+i + +a = + + 1.000000000000000 + 1.000000000000000i + +>> b = 3+7i + +b = + + 3.000000000000000 + 7.000000000000000i + +>> a+b + +ans = + + 4.000000000000000 + 8.000000000000000i + +>> a-b + +ans = + + -2.000000000000000 - 6.000000000000000i + +>> a*b + +ans = + + -4.000000000000000 +10.000000000000000i + +>> a/b + +ans = + + 0.172413793103448 - 0.068965517241379i + +>> -a + +ans = + + -1.000000000000000 - 1.000000000000000i + +>> a' + +ans = + + 1.000000000000000 - 1.000000000000000i + +>> a^b + +ans = + + 0.000808197112874 - 0.011556516327187i + +>> norm(a) + +ans = + + 1.414213562373095 diff --git a/Task/Arithmetic-Integer/0815/arithmetic-integer.0815 b/Task/Arithmetic-Integer/0815/arithmetic-integer.0815 new file mode 100644 index 0000000000..16b1ab9acc --- /dev/null +++ b/Task/Arithmetic-Integer/0815/arithmetic-integer.0815 @@ -0,0 +1,13 @@ +|~>|~#:end:> +<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$ +<:62:x<:3d:=<:20:$==$~$=${~>%<:a:~$$ +<:61:x<:2b:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~+%<:a:~$ +<:61:x<:2d:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~-%<:a:~$ +<:61:x<:2a:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~*%<:a:~$ +<:61:x<:2f:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/%<:a:~$ +<:61:x<:25:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/=%<:a:~$ +{~>>{x<:1:-^:u: +<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%#:end: +}:u:=>{x{=>~*>{x<:2:-#:ter: +}:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml: +}:ter:<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~% diff --git a/Task/Arithmetic-Integer/0DESCRIPTION b/Task/Arithmetic-Integer/0DESCRIPTION new file mode 100644 index 0000000000..d99ae33ac0 --- /dev/null +++ b/Task/Arithmetic-Integer/0DESCRIPTION @@ -0,0 +1,3 @@ +{{basic data operation}}Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. Don't include error handling. For quotient, indicate how it rounds (e.g. towards 0, towards negative infinity, etc.). For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different. + +Also include the exponentiation operator if one exists. diff --git a/Task/Arithmetic-Integer/1META.yaml b/Task/Arithmetic-Integer/1META.yaml new file mode 100644 index 0000000000..a4efa5b7bb --- /dev/null +++ b/Task/Arithmetic-Integer/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Arithmetic operations +note: Basic language learning diff --git a/Task/Arithmetic-Integer/6502-Assembly/arithmetic-integer.6502 b/Task/Arithmetic-Integer/6502-Assembly/arithmetic-integer.6502 new file mode 100644 index 0000000000..e444e5862a --- /dev/null +++ b/Task/Arithmetic-Integer/6502-Assembly/arithmetic-integer.6502 @@ -0,0 +1,48 @@ +Arithmetic: PHA ;push accumulator and X register onto stack + TXA + PHA + JSR GetUserInput ;routine not implemented + ;two integers now in memory locations A and B + ;addition + LDA A + CLC + ADC B + JSR DisplayAddition ;routine not implemented + + ;subtraction + LDA A + SEC + SBC B + JSR DisplaySubtraction ;routine not implemented + + ;multiplication - overflow not handled + LDA A + LDX B +Multiply: CLC + ADC A + DEX + BNE Multiply + JSR DisplayMultiply ;routine not implemented + + ;division - rounds up + LDA A + LDX #0 + SEC +Divide: INX + SBC B + BCS Divide + TXA ;get result into accumulator + JSR DisplayDivide ;routine not implemented + + ;modulus + LDA A + SEC +Modulus: SBC B + BCS Modulus + ADC B + JSR DisplayModulus ;routine not implemented + + PLA ;restore accumulator and X register from stack + TAX + PLA + RTS ;return from subroutine diff --git a/Task/Arithmetic-Integer/ABAP/arithmetic-integer.abap b/Task/Arithmetic-Integer/ABAP/arithmetic-integer.abap new file mode 100644 index 0000000000..d27a05dac2 --- /dev/null +++ b/Task/Arithmetic-Integer/ABAP/arithmetic-integer.abap @@ -0,0 +1,25 @@ +report zz_arithmetic no standard page heading. + +" Read in the two numbers from the user. +selection-screen begin of block input. + parameters: p_first type i, + p_second type i. +selection-screen end of block input. + +" Set the text value that is displayed on input request. +at selection-screen output. + %_p_first_%_app_%-text = 'First Number: '. + %_p_second_%_app_%-text = 'Second Number: '. + +end-of-selection. + data: lv_result type i. + lv_result = p_first + p_second. + write: / 'Addition:', lv_result. + lv_result = p_first - p_second. + write: / 'Substraction:', lv_result. + lv_result = p_first * p_second. + write: / 'Multiplication:', lv_result. + lv_result = p_first div p_second. + write: / 'Integer quotient:', lv_result. " Truncated towards zero. + lv_result = p_first mod p_second. + write: / 'Remainder:', lv_result. diff --git a/Task/Arithmetic-Integer/ACL2/arithmetic-integer.acl2 b/Task/Arithmetic-Integer/ACL2/arithmetic-integer.acl2 new file mode 100644 index 0000000000..4759916407 --- /dev/null +++ b/Task/Arithmetic-Integer/ACL2/arithmetic-integer.acl2 @@ -0,0 +1,20 @@ +:set-state-ok t + +(defun get-two-nums (state) + (mv-let (_ a state) + (read-object *standard-oi* state) + (declare (ignore _)) + (mv-let (_ b state) + (read-object *standard-oi* state) + (declare (ignore _)) + (mv a b state)))) + +(defun integer-arithmetic (state) + (mv-let (a b state) + (get-two-nums state) + (mv state + (progn$ (cw "Sum: ~x0~%" (+ a b)) + (cw "Difference: ~x0~%" (- a b)) + (cw "Product: ~x0~%" (* a b)) + (cw "Quotient: ~x0~%" (floor a b)) + (cw "Remainder: ~x0~%" (mod a b)))))) diff --git a/Task/Arithmetic-Integer/ALGOL-68/arithmetic-integer.alg b/Task/Arithmetic-Integer/ALGOL-68/arithmetic-integer.alg new file mode 100644 index 0000000000..8e69c54124 --- /dev/null +++ b/Task/Arithmetic-Integer/ALGOL-68/arithmetic-integer.alg @@ -0,0 +1,10 @@ +main:( + LONG INT a=355, b=113; + printf(($"a+b = "gl$, a + b)); + printf(($"a-b = "gl$, a - b)); + printf(($"a*b = a×b = "gl$, a * b)); + printf(($"a/b = "gl$, a / b)); + printf(($"a OVER b = a%b = a÷b = "gl$, a % b)); + printf(($"a MOD b = a%*b = a%×b = a÷×b = a÷*b = "gl$, a %* b)); + printf(($"a UP b = a**b = a↑b = "gl$, a ** b)) +) diff --git a/Task/Arithmetic-Integer/AWK/arithmetic-integer.awk b/Task/Arithmetic-Integer/AWK/arithmetic-integer.awk new file mode 100644 index 0000000000..a2de689f50 --- /dev/null +++ b/Task/Arithmetic-Integer/AWK/arithmetic-integer.awk @@ -0,0 +1,8 @@ +/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ { + print "add:", $1 + $2 + print "sub:", $1 - $2 + print "mul:", $1 * $2 + print "div:", int($1 / $2) # truncates toward zero + print "mod:", $1 % $2 # same sign as first operand + print "exp:", $1 ^ $2 + exit } diff --git a/Task/Arithmetic-Integer/Ada/arithmetic-integer.ada b/Task/Arithmetic-Integer/Ada/arithmetic-integer.ada new file mode 100644 index 0000000000..9eb691c312 --- /dev/null +++ b/Task/Arithmetic-Integer/Ada/arithmetic-integer.ada @@ -0,0 +1,18 @@ +with Ada.Text_Io; +with Ada.Integer_Text_IO; + +procedure Integer_Arithmetic is + use Ada.Text_IO; + use Ada.Integer_Text_Io; + + A, B : Integer; +begin + Get(A); + Get(B); + Put_Line("a+b = " & Integer'Image(A + B)); + Put_Line("a-b = " & Integer'Image(A - B)); + Put_Line("a*b = " & Integer'Image(A * B)); + Put_Line("a/b = " & Integer'Image(A / B) & ", remainder " & Integer'Image(A mod B)); + Put_Line("a**b = " & Integer'Image(A ** B)); + +end Integer_Arithmetic; diff --git a/Task/Arithmetic-Integer/Aikido/arithmetic-integer.aikido b/Task/Arithmetic-Integer/Aikido/arithmetic-integer.aikido new file mode 100644 index 0000000000..1b5883b941 --- /dev/null +++ b/Task/Arithmetic-Integer/Aikido/arithmetic-integer.aikido @@ -0,0 +1,10 @@ +var a = 0 +var b = 0 +stdin -> a // read int from stdin +stdin -> b // read int from stdin + +println ("a+b=" + (a + b)) +println ("a-b=" + (a - b)) +println ("a*b=" + (a * b)) +println ("a/b=" + (a / b)) +println ("a%b=" + (a % b)) diff --git a/Task/Arithmetic-Integer/AmigaE/arithmetic-integer.amiga b/Task/Arithmetic-Integer/AmigaE/arithmetic-integer.amiga new file mode 100644 index 0000000000..f5ef6fbdb1 --- /dev/null +++ b/Task/Arithmetic-Integer/AmigaE/arithmetic-integer.amiga @@ -0,0 +1,14 @@ +PROC main() + DEF a, b, t + WriteF('A = ') + ReadStr(stdin, t) + a := Val(t) + WriteF('B = ') + ReadStr(stdin, t) + b := Val(t) + WriteF('A+B=\d\nA-B=\d\n', a+b, a-b) + WriteF('A*B=\d\nA/B=\d\n', a*b, a/b) + /* * and / are 16 bit ops; Mul and Div are 32bit ops */ + WriteF('A*B=\d\nA/B=\d\n', Mul(a,b), Div(a,b)) + WriteF('A mod B =\d\n', Mod(a,b)) +ENDPROC diff --git a/Task/Arithmetic-Integer/AutoHotkey/arithmetic-integer.ahk b/Task/Arithmetic-Integer/AutoHotkey/arithmetic-integer.ahk new file mode 100644 index 0000000000..417d5ffe75 --- /dev/null +++ b/Task/Arithmetic-Integer/AutoHotkey/arithmetic-integer.ahk @@ -0,0 +1,19 @@ +Gui, Add, Edit, va, 5 +Gui, Add, Edit, vb, -3 +Gui, Add, Button, Default, Compute +Gui, Show +Return + +ButtonCompute: + Gui, Submit + MsgBox,% + (Join`s"`n" + a "+" b " = " a+b + a "-" b " = " a-b + a "*" b " = " a*b + a "//" b " = " a//b " remainder " Mod(a,b) + a "**" b " = " a**b + ) +; fallthrough +GuiClose: + ExitApp diff --git a/Task/Arithmetic-Integer/BASIC/arithmetic-integer.bas b/Task/Arithmetic-Integer/BASIC/arithmetic-integer.bas new file mode 100644 index 0000000000..3ec66077d9 --- /dev/null +++ b/Task/Arithmetic-Integer/BASIC/arithmetic-integer.bas @@ -0,0 +1,7 @@ +function math(a!, b!) + print a + b + print a - b + print a * b + print a / b + print a mod b +end function diff --git a/Task/Arithmetic-Integer/Befunge/arithmetic-integer.bf b/Task/Arithmetic-Integer/Befunge/arithmetic-integer.bf new file mode 100644 index 0000000000..769c01f520 --- /dev/null +++ b/Task/Arithmetic-Integer/Befunge/arithmetic-integer.bf @@ -0,0 +1,6 @@ +&&00p"=A",,:."=B ",,,00g.55+,v + v,+55.+g00:,,,,"A+B="< + >"=B-A",,,,:00g-.55+,v + v,+55.*g00:,,,,"A*B="< + >"=B/A",,,,:00g/.55+,v + @,+55.%g00,,,,"A%B="< diff --git a/Task/Arithmetic-Integer/C/arithmetic-integer.c b/Task/Arithmetic-Integer/C/arithmetic-integer.c new file mode 100644 index 0000000000..43facd7b4d --- /dev/null +++ b/Task/Arithmetic-Integer/C/arithmetic-integer.c @@ -0,0 +1,17 @@ +#include +#include + +int main(int argc, char *argv[]) +{ + int a, b; + if (argc < 3) exit(1); + b = atoi(argv[--argc]); + if (b == 0) exit(2); + a = atoi(argv[--argc]); + printf("a+b = %d\n", a+b); + printf("a-b = %d\n", a-b); + printf("a*b = %d\n", a*b); + printf("a/b = %d\n", a/b); /* truncates towards 0 (in C99) */ + printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */ + return 0; +} diff --git a/Task/Arithmetic-Integer/Clojure/arithmetic-integer.clj b/Task/Arithmetic-Integer/Clojure/arithmetic-integer.clj new file mode 100644 index 0000000000..05482af908 --- /dev/null +++ b/Task/Arithmetic-Integer/Clojure/arithmetic-integer.clj @@ -0,0 +1,6 @@ +(defn myfunc [] + (println "Enter x and y") + (let [x (read), y (read)] + (doseq [op '(+ - * / Math/pow rem)] + (let [exp (list op x y)] + (printf "%s=%s\n" exp (eval exp)))))) diff --git a/Task/Arithmetic-Integer/Eiffel/arithmetic-integer.e b/Task/Arithmetic-Integer/Eiffel/arithmetic-integer.e new file mode 100644 index 0000000000..3af7bb5211 --- /dev/null +++ b/Task/Arithmetic-Integer/Eiffel/arithmetic-integer.e @@ -0,0 +1,29 @@ +class MAIN + creation make + feature make is + local + a, b: REAL; + do + print("a = "); + io.read_real; + a := io.last_real; + + print("b = "); + io.read_real; + b := io.last_real; + + print("a + b = "); + io.put_real(a + b); + print("%Na - b = "); + io.put_real(a - b); + print("%Na * b = "); + io.put_real(a * b); + print("%Na / b = "); + io.put_real(a / b); + print("%Na %% b = "); + io.put_real(((a / b) - (a / b).floor) * b); + print("%Na ^ b = "); + io.put_real(a.pow(b)); + print("%N"); + end +end diff --git a/Task/Arithmetic-Integer/Forth/arithmetic-integer-1.fth b/Task/Arithmetic-Integer/Forth/arithmetic-integer-1.fth new file mode 100644 index 0000000000..19bd13b1ab --- /dev/null +++ b/Task/Arithmetic-Integer/Forth/arithmetic-integer-1.fth @@ -0,0 +1,7 @@ +: arithmetic ( a b -- ) + cr ." a=" over . ." b=" dup . + cr ." a+b=" 2dup + . + cr ." a-b=" 2dup - . + cr ." a*b=" 2dup * . + cr ." a/b=" /mod . + cr ." a mod b = " . cr ; diff --git a/Task/Arithmetic-Integer/Forth/arithmetic-integer-2.fth b/Task/Arithmetic-Integer/Forth/arithmetic-integer-2.fth new file mode 100644 index 0000000000..3ddd39d5b9 --- /dev/null +++ b/Task/Arithmetic-Integer/Forth/arithmetic-integer-2.fth @@ -0,0 +1,3 @@ +FM/MOD ( d n -- mod div ) \ floored +SM/REM ( d n -- rem div ) \ symmetric +M* ( n n -- d ) diff --git a/Task/Arithmetic-Integer/Forth/arithmetic-integer-3.fth b/Task/Arithmetic-Integer/Forth/arithmetic-integer-3.fth new file mode 100644 index 0000000000..f3deef6076 --- /dev/null +++ b/Task/Arithmetic-Integer/Forth/arithmetic-integer-3.fth @@ -0,0 +1,2 @@ +UM/MOD ( ud u -- umod udiv ) +UM* ( u u -- ud ) diff --git a/Task/Arithmetic-Integer/Fortran/arithmetic-integer.f b/Task/Arithmetic-Integer/Fortran/arithmetic-integer.f new file mode 100644 index 0000000000..d6eeba0f1e --- /dev/null +++ b/Task/Arithmetic-Integer/Fortran/arithmetic-integer.f @@ -0,0 +1,14 @@ + INTEGER A, B + PRINT *, 'Type in two integer numbers separated by white space', ++ ' and press ENTER' + READ *, A, B + PRINT *, ' A + B = ', (A + B) + PRINT *, ' A - B = ', (A - B) + PRINT *, ' A * B = ', (A * B) + PRINT *, ' A / B = ', (A / B) + PRINT *, 'MOD(A,B) = ', MOD(A,B) + PRINT * + PRINT *, 'Even though you did not ask, ', ++ 'exponentiation is an intrinsic op in Fortran, so...' + PRINT *, ' A ** B = ', (A ** B) + END diff --git a/Task/Arithmetic-Integer/Go/arithmetic-integer.go b/Task/Arithmetic-Integer/Go/arithmetic-integer.go new file mode 100644 index 0000000000..61d6b72f6a --- /dev/null +++ b/Task/Arithmetic-Integer/Go/arithmetic-integer.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func main() { + var a, b int + fmt.Print("enter two integers: ") + fmt.Scanln(&a, &b) + fmt.Printf("%d + %d = %d\n", a, b, a+b) + fmt.Printf("%d - %d = %d\n", a, b, a-b) + fmt.Printf("%d * %d = %d\n", a, b, a*b) + fmt.Printf("%d / %d = %d\n", a, b, a/b) // truncates towards 0 + fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand + // no exponentiation operator +} diff --git a/Task/Arithmetic-Integer/Haskell/arithmetic-integer.hs b/Task/Arithmetic-Integer/Haskell/arithmetic-integer.hs new file mode 100644 index 0000000000..a013012700 --- /dev/null +++ b/Task/Arithmetic-Integer/Haskell/arithmetic-integer.hs @@ -0,0 +1,15 @@ +main = do + a <- readLn :: IO Integer + b <- readLn :: IO Integer + putStrLn $ "a + b = " ++ show (a + b) + putStrLn $ "a - b = " ++ show (a - b) + putStrLn $ "a * b = " ++ show (a * b) + putStrLn $ "a to the power of b = " ++ show (a ** b) + putStrLn $ "a to the power of b = " ++ show (a ^ b) + putStrLn $ "a to the power of b = " ++ show (a ^^ b) + putStrLn $ "a `div` b = " ++ show (a `div` b) -- truncates towards negative infinity + putStrLn $ "a `mod` b = " ++ show (a `mod` b) -- same sign as second operand + putStrLn $ "a `divMod` b = " ++ show (a `divMod` b) + putStrLn $ "a `quot` b = " ++ show (a `quot` b) -- truncates towards 0 + putStrLn $ "a `rem` b = " ++ show (a `rem` b) -- same sign as first operand + putStrLn $ "a `quotRem` b = " ++ show (a `quotRem` b) diff --git a/Task/Arithmetic-Integer/Java/arithmetic-integer.java b/Task/Arithmetic-Integer/Java/arithmetic-integer.java new file mode 100644 index 0000000000..5be83bda97 --- /dev/null +++ b/Task/Arithmetic-Integer/Java/arithmetic-integer.java @@ -0,0 +1,15 @@ +import java.util.Scanner; +public class Int{ + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + int a = sc.nextInt(); + int b = sc.nextInt(); + + int sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation + System.out.println("a + b = " + sum); + System.out.println("a - b = " + (a - b)); + System.out.println("a * b = " + (a * b)); + System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0 + System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand + } +} diff --git a/Task/Arithmetic-Integer/JavaScript/arithmetic-integer.js b/Task/Arithmetic-Integer/JavaScript/arithmetic-integer.js new file mode 100644 index 0000000000..4be323d6b3 --- /dev/null +++ b/Task/Arithmetic-Integer/JavaScript/arithmetic-integer.js @@ -0,0 +1,26 @@ +var a = parseInt(get_input("Enter an integer"), 10); +var b = parseInt(get_input("Enter an integer"), 10); + +WScript.Echo("a = " + a); +WScript.Echo("b = " + b); +WScript.Echo("sum: a + b = " + (a + b)); +WScript.Echo("difference: a - b = " + (a - b)); +WScript.Echo("product: a * b = " + (a * b)); +WScript.Echo("quotient: a / b = " + (a / b | 0)); // "| 0" casts it to an integer +WScript.Echo("remainder: a % b = " + (a % b)); + +function get_input(prompt) { + output(prompt); + try { + return WScript.StdIn.readLine(); + } catch(e) { + return readline(); + } +} +function output(prompt) { + try { + WScript.Echo(prompt); + } catch(e) { + print(prompt); + } +} diff --git a/Task/Arithmetic-Integer/Lua/arithmetic-integer.lua b/Task/Arithmetic-Integer/Lua/arithmetic-integer.lua new file mode 100644 index 0000000000..6eebeea842 --- /dev/null +++ b/Task/Arithmetic-Integer/Lua/arithmetic-integer.lua @@ -0,0 +1,9 @@ +local x = io.read() +local y = io.read() + +print ("Sum: " , (x + y)) +print ("Difference: ", (x - y)) +print ("Product: " , (x * y)) +print ("Quotient: " , (x / y)) -- Does not truncate +print ("Remainder: " , (x % y)) -- Result has sign of right operand +print ("Exponent: " , (x ^ y)) diff --git a/Task/Arithmetic-Integer/MATLAB/arithmetic-integer.m b/Task/Arithmetic-Integer/MATLAB/arithmetic-integer.m new file mode 100644 index 0000000000..c4a04c6352 --- /dev/null +++ b/Task/Arithmetic-Integer/MATLAB/arithmetic-integer.m @@ -0,0 +1,8 @@ +disp("integer a: "); a = scanf("%d", 1); +disp("integer b: "); b = scanf("%d", 1); +a+b +a-b +a*b +floor(a/b) +mod(a,b) +a^b diff --git a/Task/Arithmetic-Integer/PHP/arithmetic-integer.php b/Task/Arithmetic-Integer/PHP/arithmetic-integer.php new file mode 100644 index 0000000000..fbf4bb2185 --- /dev/null +++ b/Task/Arithmetic-Integer/PHP/arithmetic-integer.php @@ -0,0 +1,12 @@ + diff --git a/Task/Arithmetic-Integer/Perl/arithmetic-integer.pl b/Task/Arithmetic-Integer/Perl/arithmetic-integer.pl new file mode 100644 index 0000000000..ce1c38abd9 --- /dev/null +++ b/Task/Arithmetic-Integer/Perl/arithmetic-integer.pl @@ -0,0 +1,11 @@ +my $a = <>; +my $b = <>; + +print + "sum: ", $a + $b, "\n", + "difference: ", $a - $b, "\n", + "product: ", $a * $b, "\n", + "integer quotient: ", int($a / $b), "\n", + "remainder: ", $a % $b, "\n", + "exponent: ", $a ** $b, "\n" + ; diff --git a/Task/Arithmetic-Integer/PicoLisp/arithmetic-integer.l b/Task/Arithmetic-Integer/PicoLisp/arithmetic-integer.l new file mode 100644 index 0000000000..adaf98e537 --- /dev/null +++ b/Task/Arithmetic-Integer/PicoLisp/arithmetic-integer.l @@ -0,0 +1,8 @@ +(de math (A B) + (prinl "Add " (+ A B)) + (prinl "Subtract " (- A B)) + (prinl "Multiply " (* A B)) + (prinl "Divide " (/ A B)) # Trucates towards zero + (prinl "Div/rnd " (*/ A B)) # Rounds to next integer + (prinl "Modulus " (% A B)) # Sign of the first operand + (prinl "Power " (** A B)) ) diff --git a/Task/Arithmetic-Integer/Python/arithmetic-integer-1.py b/Task/Arithmetic-Integer/Python/arithmetic-integer-1.py new file mode 100644 index 0000000000..e8ffbb0d53 --- /dev/null +++ b/Task/Arithmetic-Integer/Python/arithmetic-integer-1.py @@ -0,0 +1,14 @@ +x = int(raw_input("Number 1: ")) +y = int(raw_input("Number 2: ")) + +print "Sum: %d" % (x + y) +print "Difference: %d" % (x - y) +print "Product: %d" % (x * y) +print "Quotient: %d" % (x / y) # or x // y for newer python versions. + # truncates towards negative infinity +print "Remainder: %d" % (x % y) # same sign as second operand +print "Quotient: %d with Remainder: %d" % divmod(x, y) +print "Power: %d" % x**y + +## Only used to keep the display up when the program ends +raw_input( ) diff --git a/Task/Arithmetic-Integer/Python/arithmetic-integer-2.py b/Task/Arithmetic-Integer/Python/arithmetic-integer-2.py new file mode 100644 index 0000000000..18287e73d9 --- /dev/null +++ b/Task/Arithmetic-Integer/Python/arithmetic-integer-2.py @@ -0,0 +1,13 @@ +def getnum(prompt): + while True: # retrying ... + try: + n = int(raw_input(prompt)) + except ValueError: + print "Input could not be parsed as an integer. Please try again."\ + continue + break + return n + +x = getnum("Number1: ") +y = getnum("Number2: ") +... diff --git a/Task/Arithmetic-Integer/Python/arithmetic-integer-3.py b/Task/Arithmetic-Integer/Python/arithmetic-integer-3.py new file mode 100644 index 0000000000..a89d6294e7 --- /dev/null +++ b/Task/Arithmetic-Integer/Python/arithmetic-integer-3.py @@ -0,0 +1,8 @@ +def arithmetic(x, y): + for op in "+ - * // % **".split(): + expr = "%(x)s %(op)s %(y)s" % vars() + print("%s\t=> %s" % (expr, eval(expr))) + + +arithmetic(12, 8) +arithmetic(input("Number 1: "), input("Number 2: ")) diff --git a/Task/Arithmetic-Integer/R/arithmetic-integer.r b/Task/Arithmetic-Integer/R/arithmetic-integer.r new file mode 100644 index 0000000000..656028fc5a --- /dev/null +++ b/Task/Arithmetic-Integer/R/arithmetic-integer.r @@ -0,0 +1,10 @@ +cat("insert number ") +a <- scan(nmax=1, quiet=TRUE) +cat("insert number ") +b <- scan(nmax=1, quiet=TRUE) +print(paste('a+b=', a+b)) +print(paste('a-b=', a-b)) +print(paste('a*b=', a*b)) +print(paste('a%/%b=', a%/%b)) +print(paste('a%%b=', a%%b)) +print(paste('a^b=', a^b)) diff --git a/Task/Arithmetic-Integer/REXX/arithmetic-integer.rexx b/Task/Arithmetic-Integer/REXX/arithmetic-integer.rexx new file mode 100644 index 0000000000..8b734b7286 --- /dev/null +++ b/Task/Arithmetic-Integer/REXX/arithmetic-integer.rexx @@ -0,0 +1,26 @@ +/*REXX pgm gets 2 integers from the C.L. or via prompt, shows some opers*/ +numeric digits 20 /*all numbers are rounded at ··· */ + /*··· the 20th significant digit.*/ +parse arg x y . /*maybe the integers are on C.L.?*/ +if y=='' then do /*nope, then prompt user for 'em.*/ + say "─────Enter two integer values (separated by blanks):" + parse pull x y . + end + do 2 /*show A with B, then B with A.*/ + say /*show blank line for eyeballing.*/ + + call show 'addition' , "+", x+y + call show 'subtraction' , "-", x-y + call show 'multiplication', "*", x*y + call show 'int division' , "%", x%y, ' [rounds down]' + call show 'real division' , "/", x/y + call show 'div remainder' , "//", x//y, ' [sign from 1st operand]' + call show 'power' , "**", x**y + + parse value x y with y x /*swap the two values & do again.*/ + end /*2*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SHOW subroutine─────────────────────*/ +show: parse arg what,oper,value,comment +say right(what,25)' ' x center(oper,4) y ' ───► ' value comment +return diff --git a/Task/Arithmetic-Integer/Racket/arithmetic-integer.rkt b/Task/Arithmetic-Integer/Racket/arithmetic-integer.rkt new file mode 100644 index 0000000000..02c4003d95 --- /dev/null +++ b/Task/Arithmetic-Integer/Racket/arithmetic-integer.rkt @@ -0,0 +1,7 @@ +#lang racket +(define (arithmetic x y) + (for ([op '(+ - * / quotient remainder modulo max min gcd lcm)]) + (displayln (~a (list op x y) " => " + ((eval op (make-base-namespace)) x y))))) + +(arithmetic 8 12) diff --git a/Task/Arithmetic-Integer/Ruby/arithmetic-integer.rb b/Task/Arithmetic-Integer/Ruby/arithmetic-integer.rb new file mode 100644 index 0000000000..c9644f4b27 --- /dev/null +++ b/Task/Arithmetic-Integer/Ruby/arithmetic-integer.rb @@ -0,0 +1,10 @@ +puts 'Enter x and y' +x=gets.to_i # to check errors, use x=Integer(gets) +y=gets.to_i + +puts "Sum: #{x+y}", + "Difference: #{x-y}", + "Product: #{x*y}", + "Quotient: #{x/y}", # truncates towards negative infinity + "Remainder: #{x%y}", # same sign as second operand + "Exponentiation: #{x**y}" diff --git a/Task/Arithmetic-Integer/SNUSP/arithmetic-integer.snusp b/Task/Arithmetic-Integer/SNUSP/arithmetic-integer.snusp new file mode 100644 index 0000000000..a2d4b3557d --- /dev/null +++ b/Task/Arithmetic-Integer/SNUSP/arithmetic-integer.snusp @@ -0,0 +1,58 @@ +$\ + , + @ + \=@@@-@-----# atoi + > + , + @ + \=@@@-@-----# + < + @ # 4 copies + \=!/?!/->>+>>+>>+>>+<<<<<<< | #\?<<<<<<<<+>>+>>+>>+>>-/ + @ | + \==/ + \>>>>\ + />>>>/ + @ + \==!/===?\# add + < \>+<-/ + @ + \=@@@+@+++++# itoa + . + < + @ + \==!/===?\# subtract + < \>-<-/ + @ + \=@@@+@+++++# + . + ! + /\ + ?- multiply + \/ #/?<<+>+>-==\ /==-<+<+>>?\# /==-<<+>>?\# + < \->+>+<>+<+<-/ #\?\!>>+<<-/ + @ /==|=========|=====\ /-\ | + \======@/<-?!\>>>@/<<<-?\=>!\?/>!/@/<# + < \=======|==========/ /-\ | + @ \done======>>>!\?/<=/ + \=@@@+@+++++# + . + ! + /\ + ?- zero + \/ + < divmod + @ /-\ + \?\@\>>!/?!/=!\?/<<# + | | | #\->->+>+<>-/ + \=@@@+@+++++# + . + < + @ + \=@@@+@+++++# + . + # diff --git a/Task/Arithmetic-Integer/Scala/arithmetic-integer.scala b/Task/Arithmetic-Integer/Scala/arithmetic-integer.scala new file mode 100644 index 0000000000..aaaaa50d93 --- /dev/null +++ b/Task/Arithmetic-Integer/Scala/arithmetic-integer.scala @@ -0,0 +1,9 @@ +val a = Console.readInt +val b = Console.readInt + +val sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation +println("a + b = " + sum); +println("a - b = " + (a - b)); +println("a * b = " + (a * b)); +println("quotient of a / b = " + (a / b)); // truncates towards 0 +println("remainder of a / b = " + (a % b)); // same sign as first operand diff --git a/Task/Arithmetic-Integer/Scheme/arithmetic-integer.ss b/Task/Arithmetic-Integer/Scheme/arithmetic-integer.ss new file mode 100644 index 0000000000..e1780ae351 --- /dev/null +++ b/Task/Arithmetic-Integer/Scheme/arithmetic-integer.ss @@ -0,0 +1,9 @@ +(define (arithmetic x y) + (for-each (lambda (op) + (write (list op x y)) + (display " => ") + (write ((eval op) x y)) + (newline)) + '(+ - * / quotient remainder modulo max min gcd lcm))) + +(arithmetic 8 12) diff --git a/Task/Arithmetic-Integer/Smalltalk/arithmetic-integer.st b/Task/Arithmetic-Integer/Smalltalk/arithmetic-integer.st new file mode 100644 index 0000000000..97da178dbf --- /dev/null +++ b/Task/Arithmetic-Integer/Smalltalk/arithmetic-integer.st @@ -0,0 +1,10 @@ +| a b | +'Input number a: ' display. +a := (stdin nextLine) asInteger. +'Input number b: ' display. +b := (stdin nextLine) asInteger. +('a+b=%1' % { a + b }) displayNl. +('a-b=%1' % { a - b }) displayNl. +('a*b=%1' % { a * b }) displayNl. +('a/b=%1' % { a // b }) displayNl. +('a%%b=%1' % { a \\ b }) displayNl. diff --git a/Task/Arithmetic-Integer/Tcl/arithmetic-integer-1.tcl b/Task/Arithmetic-Integer/Tcl/arithmetic-integer-1.tcl new file mode 100644 index 0000000000..b68102e307 --- /dev/null +++ b/Task/Arithmetic-Integer/Tcl/arithmetic-integer-1.tcl @@ -0,0 +1,11 @@ +puts "Please enter two numbers:" + +set x [expr {int([gets stdin])}]; # Force integer interpretation +set y [expr {int([gets stdin])}]; # Force integer interpretation + +puts "$x + $y = [expr {$x + $y}]" +puts "$x - $y = [expr {$x - $y}]" +puts "$x * $y = [expr {$x * $y}]" +puts "$x / $y = [expr {$x / $y}]" +puts "$x mod $y = [expr {$x % $y}]" +puts "$x 'to the' $y = [expr {$x ** $y}]" diff --git a/Task/Arithmetic-Integer/Tcl/arithmetic-integer-2.tcl b/Task/Arithmetic-Integer/Tcl/arithmetic-integer-2.tcl new file mode 100644 index 0000000000..bf9a6364e4 --- /dev/null +++ b/Task/Arithmetic-Integer/Tcl/arithmetic-integer-2.tcl @@ -0,0 +1 @@ +incr x $y diff --git a/Task/Array-concatenation/MATLAB/array-concatenation-1.m b/Task/Array-concatenation/MATLAB/array-concatenation-1.m new file mode 100644 index 0000000000..214e74ec52 --- /dev/null +++ b/Task/Array-concatenation/MATLAB/array-concatenation-1.m @@ -0,0 +1,24 @@ +>> a = [1 2 3] + +a = + + 1 2 3 + +>> b = [4 5 6] + +b = + + 4 5 6 + +>> concat = [a b] + +concat = + + 1 2 3 4 5 6 + +>> concat = [a;b] + +concat = + + 1 2 3 + 4 5 6 diff --git a/Task/Array-concatenation/MATLAB/array-concatenation-2.m b/Task/Array-concatenation/MATLAB/array-concatenation-2.m new file mode 100644 index 0000000000..b889895e3a --- /dev/null +++ b/Task/Array-concatenation/MATLAB/array-concatenation-2.m @@ -0,0 +1,7 @@ +>> c = randn([3,4,5]); +>> d = randn([3,4,7]); +>> e = cat(3,c,d); +>> size(e) + ans = + + 3 4 12 diff --git a/Task/Arrays/MATLAB/arrays.m b/Task/Arrays/MATLAB/arrays.m new file mode 100644 index 0000000000..817996811c --- /dev/null +++ b/Task/Arrays/MATLAB/arrays.m @@ -0,0 +1,61 @@ +>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array) + +a = + + 1 2 35 + +>> a = [1 2 35;5 7 9] % Declaring a matrix (i.e. two-dimensional array) + +a = + + 1 2 35 + 5 7 9 + +>> a3 = reshape(1:2*3*4,[2,3,4]); % declaring a three-dimensional array of size 2x3x4 + +a3 = + +ans(:,:,1) = + + 1 3 5 + 2 4 6 + +ans(:,:,2) = + + 7 9 11 + 8 10 12 + +ans(:,:,3) = + + 13 15 17 + 14 16 18 + +ans(:,:,4) = + + 19 21 23 + 20 22 24 + + +>> a(2,3) %Retrieving value using row and column indicies + + 9 + +>> a(6) %Retrieving value using array subscript + +ans = + + 9 + +>> a = [a [10;42]] %Added a column vector to the array + +a = + + 1 2 35 10 + 5 7 9 42 + +>> a(:,1) = [] %Deleting array elements + +a = + + 2 35 10 + 7 9 42 diff --git a/Task/Assertions/MATLAB/assertions-1.m b/Task/Assertions/MATLAB/assertions-1.m new file mode 100644 index 0000000000..c41dce925e --- /dev/null +++ b/Task/Assertions/MATLAB/assertions-1.m @@ -0,0 +1 @@ +assert(x == 42,'x = %d, not 42.',x); diff --git a/Task/Assertions/MATLAB/assertions-2.m b/Task/Assertions/MATLAB/assertions-2.m new file mode 100644 index 0000000000..f946c67aa7 --- /dev/null +++ b/Task/Assertions/MATLAB/assertions-2.m @@ -0,0 +1,3 @@ +x = 3; +assert(x == 42,'Assertion Failed: x = %d, not 42.',x); +??? Assertion Failed: x = 3, not 42. diff --git a/Task/Associative-array-Creation/MATLAB/associative-array-creation-1.m b/Task/Associative-array-Creation/MATLAB/associative-array-creation-1.m new file mode 100644 index 0000000000..1aa39dbe5c --- /dev/null +++ b/Task/Associative-array-Creation/MATLAB/associative-array-creation-1.m @@ -0,0 +1,3 @@ + hash.a = 1; + hash.b = 2; + hash.C = [3,4,5]; diff --git a/Task/Associative-array-Creation/MATLAB/associative-array-creation-2.m b/Task/Associative-array-Creation/MATLAB/associative-array-creation-2.m new file mode 100644 index 0000000000..dce3eb4188 --- /dev/null +++ b/Task/Associative-array-Creation/MATLAB/associative-array-creation-2.m @@ -0,0 +1,4 @@ + hash = []; + hash = setfield(hash,'a',1); + hash = setfield(hash,'b',2); + hash = setfield(hash,'C',[3,4,5]); diff --git a/Task/Associative-array-Creation/MATLAB/associative-array-creation-3.m b/Task/Associative-array-Creation/MATLAB/associative-array-creation-3.m new file mode 100644 index 0000000000..b118e1f226 --- /dev/null +++ b/Task/Associative-array-Creation/MATLAB/associative-array-creation-3.m @@ -0,0 +1,3 @@ + hash.('a') = 1; + hash.('b') = 2; + hash.('C') = [3,4,5]; diff --git a/Task/Associative-array-Iteration/MATLAB/associative-array-iteration-1.m b/Task/Associative-array-Iteration/MATLAB/associative-array-iteration-1.m new file mode 100644 index 0000000000..4bee9f67c3 --- /dev/null +++ b/Task/Associative-array-Iteration/MATLAB/associative-array-iteration-1.m @@ -0,0 +1,6 @@ + keys = fieldnames(hash); + for k=1:length(keys), + key = keys{k}; + value = getfield(hash,key); % get value of key + hash = setfield(hash,key,-value); % set value of key + end; diff --git a/Task/Associative-array-Iteration/MATLAB/associative-array-iteration-2.m b/Task/Associative-array-Iteration/MATLAB/associative-array-iteration-2.m new file mode 100644 index 0000000000..3567544c0d --- /dev/null +++ b/Task/Associative-array-Iteration/MATLAB/associative-array-iteration-2.m @@ -0,0 +1,6 @@ + keys = fieldnames(hash); + for k=1:length(keys), + key = keys{k}; + value = hash.(key); % get value of key + hash.(key) = -value; % set value of key + end; diff --git a/Task/Averages-Arithmetic-mean/MATLAB/averages-arithmetic-mean.m b/Task/Averages-Arithmetic-mean/MATLAB/averages-arithmetic-mean.m new file mode 100644 index 0000000000..3ecd313cad --- /dev/null +++ b/Task/Averages-Arithmetic-mean/MATLAB/averages-arithmetic-mean.m @@ -0,0 +1,3 @@ +function meanValue = findmean(setOfValues) + meanValue = mean(setOfValues); +end diff --git a/Task/Averages-Median/MATLAB/averages-median.m b/Task/Averages-Median/MATLAB/averages-median.m new file mode 100644 index 0000000000..e159c1e5d6 --- /dev/null +++ b/Task/Averages-Median/MATLAB/averages-median.m @@ -0,0 +1,3 @@ +function medianValue = findmedian(setOfValues) + medianValue = median(setOfValues); +end diff --git a/Task/Averages-Mode/AWK/averages-mode.awk b/Task/Averages-Mode/AWK/averages-mode.awk new file mode 100644 index 0000000000..c6047dcd84 --- /dev/null +++ b/Task/Averages-Mode/AWK/averages-mode.awk @@ -0,0 +1,30 @@ +#!/usr/bin/gawk -f +{ + # compute histogram + histo[$1] += 1; +}; + +function mode(HIS) { + # Computes the mode from Histogram A + max = 0; + n = 0; + for (k in HIS) { + val = HIS[k]; + if (HIS[k] > max) { + max = HIS[k]; + n = 1; + List[n] = k; + } else if (HIS[k] == max) { + List[++n] = k; + } + } + + for (k=1; k<=n; k++) { + o = o""OFS""List[k]; + } + return o; +} + +END { + print mode(histo); +}; diff --git a/Task/Averages-Mode/ActionScript/averages-mode.as b/Task/Averages-Mode/ActionScript/averages-mode.as new file mode 100644 index 0000000000..da01064428 --- /dev/null +++ b/Task/Averages-Mode/ActionScript/averages-mode.as @@ -0,0 +1,28 @@ +function Mode(arr:Array):Array { + //Create an associative array to count how many times each element occurs, + //an array to contain the modes, and a variable to store how many times each mode appears. + var count:Array = new Array(); + var modeList:Array; + var maxCount:uint=0; + for (var i:String in arr) { + //Record how many times an element has occurred. Note that each element in the cuont array + //has to be initialized explicitly, since it is an associative array. + if (count[arr[i]]==undefined) { + count[arr[i]]=1; + } else { + count[arr[i]]++; + } + //If this is now the most common element, clear the list of modes, and add this element. + if(count[arr[i]] > maxCount) + { + maxCount=count[arr[i]]; + modeList = new Array(); + modeList.push(arr[i]); + } + //If this is a mode, add it to the list. + else if(count[arr[i]] == maxCount){ + modeList.push(arr[i]); + } + } + return modeList; +} diff --git a/Task/Averages-Mode/Ada/averages-mode-1.ada b/Task/Averages-Mode/Ada/averages-mode-1.ada new file mode 100644 index 0000000000..0757dcc331 --- /dev/null +++ b/Task/Averages-Mode/Ada/averages-mode-1.ada @@ -0,0 +1,8 @@ +generic + type Element_Type is private; + type Element_Array is array (Positive range <>) of Element_Type; +package Mode is + + function Get_Mode (Set : Element_Array) return Element_Array; + +end Mode; diff --git a/Task/Averages-Mode/Ada/averages-mode-2.ada b/Task/Averages-Mode/Ada/averages-mode-2.ada new file mode 100644 index 0000000000..08dee1b804 --- /dev/null +++ b/Task/Averages-Mode/Ada/averages-mode-2.ada @@ -0,0 +1,102 @@ +with Ada.Containers.Indefinite_Vectors; + +package body Mode is + + -- map Count to Elements + package Count_Vectors is new Ada.Containers.Indefinite_Vectors + (Element_Type => Element_Array, + Index_Type => Positive); + + procedure Add (To : in out Count_Vectors.Vector; Item : Element_Type) is + use type Count_Vectors.Cursor; + Position : Count_Vectors.Cursor := To.First; + Found : Boolean := False; + begin + while not Found and then Position /= Count_Vectors.No_Element loop + declare + Elements : Element_Array := Count_Vectors.Element (Position); + begin + for I in Elements'Range loop + if Elements (I) = Item then + Found := True; + end if; + end loop; + end; + if not Found then + Position := Count_Vectors.Next (Position); + end if; + end loop; + if Position /= Count_Vectors.No_Element then + -- element found, remove it and insert to next count + declare + New_Position : Count_Vectors.Cursor := + Count_Vectors.Next (Position); + begin + -- remove from old position + declare + Old_Elements : Element_Array := + Count_Vectors.Element (Position); + New_Elements : Element_Array (1 .. Old_Elements'Length - 1); + New_Index : Positive := New_Elements'First; + begin + for I in Old_Elements'Range loop + if Old_Elements (I) /= Item then + New_Elements (New_Index) := Old_Elements (I); + New_Index := New_Index + 1; + end if; + end loop; + To.Replace_Element (Position, New_Elements); + end; + -- new position not already there? + if New_Position = Count_Vectors.No_Element then + declare + New_Array : Element_Array (1 .. 1) := (1 => Item); + begin + To.Append (New_Array); + end; + else + -- add to new position + declare + Old_Elements : Element_Array := + Count_Vectors.Element (New_Position); + New_Elements : Element_Array (1 .. Old_Elements'Length + 1); + begin + New_Elements (1 .. Old_Elements'Length) := Old_Elements; + New_Elements (New_Elements'Last) := Item; + To.Replace_Element (New_Position, New_Elements); + end; + end if; + end; + else + -- element not found, add to count 1 + Position := To.First; + if Position = Count_Vectors.No_Element then + declare + New_Array : Element_Array (1 .. 1) := (1 => Item); + begin + To.Append (New_Array); + end; + else + declare + Old_Elements : Element_Array := + Count_Vectors.Element (Position); + New_Elements : Element_Array (1 .. Old_Elements'Length + 1); + begin + New_Elements (1 .. Old_Elements'Length) := Old_Elements; + New_Elements (New_Elements'Last) := Item; + To.Replace_Element (Position, New_Elements); + end; + end if; + end if; + end Add; + + function Get_Mode (Set : Element_Array) return Element_Array is + Counts : Count_Vectors.Vector; + begin + for I in Set'Range loop + Add (Counts, Set (I)); + end loop; + return Counts.Last_Element; + end Get_Mode; + +end Mode; diff --git a/Task/Averages-Mode/Ada/averages-mode-3.ada b/Task/Averages-Mode/Ada/averages-mode-3.ada new file mode 100644 index 0000000000..514d0078ec --- /dev/null +++ b/Task/Averages-Mode/Ada/averages-mode-3.ada @@ -0,0 +1,26 @@ +with Ada.Text_IO; +with Mode; +procedure Main is + type Int_Array is array (Positive range <>) of Integer; + package Int_Mode is new Mode (Integer, Int_Array); + + Test_1 : Int_Array := (1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6); + Result : Int_Array := Int_Mode.Get_Mode (Test_1); +begin + Ada.Text_IO.Put ("Input: "); + for I in Test_1'Range loop + Ada.Text_IO.Put (Integer'Image (Test_1 (I))); + if I /= Test_1'Last then + Ada.Text_IO.Put (","); + end if; + end loop; + Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("Result:"); + for I in Result'Range loop + Ada.Text_IO.Put (Integer'Image (Result (I))); + if I /= Result'Last then + Ada.Text_IO.Put (","); + end if; + end loop; + Ada.Text_IO.New_Line; +end Main; diff --git a/Task/Averages-Mode/AutoHotkey/averages-mode.ahk b/Task/Averages-Mode/AutoHotkey/averages-mode.ahk new file mode 100644 index 0000000000..02da416b20 --- /dev/null +++ b/Task/Averages-Mode/AutoHotkey/averages-mode.ahk @@ -0,0 +1,15 @@ +MsgBox % Mode("1 2 3") +MsgBox % Mode("1 2 0 3 0.0") +MsgBox % Mode("0.1 2.2 -0.1 0.22e1 2.20 0.1") + +Mode(a, d=" ") { ; the number that occurs most frequently in a list delimited by d (space) + Sort a, ND%d% + Loop Parse, a, %d% + If (V != A_LoopField) { + If (Ct > MxCt) + MxV := V, MxCt := Ct + V := A_LoopField, Ct := 1 + } + Else Ct++ + Return Ct>MxCt ? V : MxV +} diff --git a/Task/Averages-Mode/C/averages-mode.c b/Task/Averages-Mode/C/averages-mode.c new file mode 100644 index 0000000000..159463683e --- /dev/null +++ b/Task/Averages-Mode/C/averages-mode.c @@ -0,0 +1,59 @@ +#include +#include + +typedef struct { double v; int c; } vcount; + +int cmp_dbl(const void *a, const void *b) +{ + double x = *(double*)a - *(double*)b; + return x < 0 ? -1 : x > 0; +} + +int vc_cmp(const void *a, const void *b) +{ + return ((vcount*)b)->c - ((vcount*)a)->c; +} + +int get_mode(double* x, int len, vcount **list) +{ + int i, j; + vcount *vc; + + /* sort values */ + qsort(x, len, sizeof(double), cmp_dbl); + + /* count occurence of each value */ + for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1])); + + *list = vc = malloc(sizeof(vcount) * j); + vc[0].v = x[0]; + vc[0].c = 1; + + /* generate list value-count pairs */ + for (i = j = 0; i < len - 1; i++, vc[j].c++) + if (x[i] != x[i + 1]) vc[++j].v = x[i + 1]; + + /* sort that by count in descending order */ + qsort(vc, j + 1, sizeof(vcount), vc_cmp); + + /* the number of entries with same count as the highest */ + for (i = 0; i <= j && vc[i].c == vc[0].c; i++); + + return i; +} + +int main() +{ + double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 }; +# define len sizeof(values)/sizeof(double) + vcount *vc; + + int i, n_modes = get_mode(values, len, &vc); + + printf("got %d modes:\n", n_modes); + for (i = 0; i < n_modes; i++) + printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c); + + free(vc); + return 0; +} diff --git a/Task/Averages-Mode/Clojure/averages-mode-1.clj b/Task/Averages-Mode/Clojure/averages-mode-1.clj new file mode 100644 index 0000000000..52c56e7bcb --- /dev/null +++ b/Task/Averages-Mode/Clojure/averages-mode-1.clj @@ -0,0 +1,6 @@ +(defn modes [coll] + (let [distrib (frequencies coll) + [value freq] [first second] ; name the key/value pairs in the distrib (map) entries + sorted (sort-by (comp - freq) distrib) + maxfq (freq (first sorted))] + (map value (take-while #(= maxfq (freq %)) sorted)))) diff --git a/Task/Averages-Mode/Clojure/averages-mode-2.clj b/Task/Averages-Mode/Clojure/averages-mode-2.clj new file mode 100644 index 0000000000..389c1fea61 --- /dev/null +++ b/Task/Averages-Mode/Clojure/averages-mode-2.clj @@ -0,0 +1,13 @@ +mode = (arr) -> + # returns an array with the modes of arr, i.e. the + # elements that appear most often in arr + counts = {} + for elem in arr + counts[elem] ||= 0 + counts[elem] += 1 + max = 0 + for key, cnt of counts + max = cnt if cnt > max + (key for key, cnt of counts when cnt == max) + +console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4] diff --git a/Task/Averages-Mode/Clojure/averages-mode-3.clj b/Task/Averages-Mode/Clojure/averages-mode-3.clj new file mode 100644 index 0000000000..bbd2de4d73 --- /dev/null +++ b/Task/Averages-Mode/Clojure/averages-mode-3.clj @@ -0,0 +1,15 @@ +(defun mode (sequence &rest hash-table-options) + (let ((frequencies (apply #'make-hash-table hash-table-options))) + (map nil (lambda (element) + (incf (gethash element frequencies 0))) + sequence) + (let ((modes '()) + (hifreq 0 )) + (maphash (lambda (element frequency) + (cond ((> frequency hifreq) + (setf hifreq frequency + modes (list element))) + ((= frequency hifreq) + (push element modes)))) + frequencies) + (values modes hifreq)))) diff --git a/Task/Averages-Mode/Fortran/averages-mode.f b/Task/Averages-Mode/Fortran/averages-mode.f new file mode 100644 index 0000000000..b64bd1be5e --- /dev/null +++ b/Task/Averages-Mode/Fortran/averages-mode.f @@ -0,0 +1,98 @@ +program mode_test + use Qsort_Module only Qsort => sort + implicit none + + integer, parameter :: S = 10 + integer, dimension(S) :: a1 = (/ -1, 7, 7, 2, 2, 2, -1, 7, -3, -3 /) + integer, dimension(S) :: a2 = (/ 1, 1, 1, 1, 1, 0, 2, 2, 2, 2 /) + integer, dimension(S) :: a3 = (/ 0, 0, -1, -1, 9, 9, 3, 3, 7, 7 /) + + integer, dimension(S) :: o + integer :: l, trash + + print *, stat_mode(a1) + + trash = stat_mode(a1, o, l) + print *, o(1:l) + trash = stat_mode(a2, o, l) + print *, o(1:l) + trash = stat_mode(a3, o, l) + print *, o(1:l) + +contains + + ! stat_mode returns the lowest (if not unique) mode + ! others can hold other modes, if the mode is not unique + ! if others is provided, otherslen should be provided too, and + ! it says how many other modes are there. + ! ok can be used to know if the return value has a meaning + ! or the mode can't be found (void arrays) + integer function stat_mode(a, others, otherslen, ok) + integer, dimension(:), intent(in) :: a + logical, optional, intent(out) :: ok + integer, dimension(size(a,1)), optional, intent(out) :: others + integer, optional, intent(out) :: otherslen + + ! ta is a copy of a, we sort ta modifying it, freq + ! holds the frequencies and idx the index (for ta) so that + ! the value appearing freq(i)-time is ta(idx(i)) + integer, dimension(size(a, 1)) :: ta, freq, idx + integer :: rs, i, tm, ml, tf + + if ( present(ok) ) ok = .false. + + select case ( size(a, 1) ) + case (0) ! no mode... ok is false + return + case (1) + if ( present(ok) ) ok = .true. + stat_mode = a(1) + return + case default + if ( present(ok) ) ok = .true. + ta = a ! copy the array + call sort(ta) ! sort it in place (cfr. sort algos on RC) + freq = 1 + idx = 0 + rs = 1 ! rs will be the number of different values + + do i = 2, size(ta, 1) + if ( ta(i-1) == ta(i) ) then + freq(rs) = freq(rs) + 1 + else + idx(rs) = i-1 + rs = rs + 1 + end if + end do + idx(rs) = i-1 + + ml = maxloc(freq(1:rs), 1) ! index of the max value of freq + tf = freq(ml) ! the max frequency + tm = ta(idx(ml)) ! the value with that freq + + ! if we want all the possible modes, we provide others + if ( present(others) ) then + i = 1 + others(1) = tm + do + freq(ml) = 0 + ml = maxloc(freq(1:rs), 1) + if ( tf == freq(ml) ) then ! the same freq + i = i + 1 ! as the max one + others(i) = ta(idx(ml)) + else + exit + end if + end do + + if ( present(otherslen) ) then + otherslen = i + end if + + end if + stat_mode = tm + end select + + end function stat_mode + +end program mode_test diff --git a/Task/Averages-Mode/Go/averages-mode-1.go b/Task/Averages-Mode/Go/averages-mode-1.go new file mode 100644 index 0000000000..8a3748de4b --- /dev/null +++ b/Task/Averages-Mode/Go/averages-mode-1.go @@ -0,0 +1,28 @@ +package main + +import "fmt" + +func main() { + fmt.Println(mode([]int{2, 7, 1, 8, 2})) + fmt.Println(mode([]int{2, 7, 1, 8, 2, 8})) +} + +func mode(a []int) []int { + m := make(map[int]int) + for _, v := range a { + m[v]++ + } + var mode []int + var n int + for k, v := range m { + switch { + case v < n: + case v > n: + n = v + mode = append(mode[:0], k) + default: + mode = append(mode, k) + } + } + return mode +} diff --git a/Task/Averages-Mode/Go/averages-mode-2.go b/Task/Averages-Mode/Go/averages-mode-2.go new file mode 100644 index 0000000000..ac9e4cdd86 --- /dev/null +++ b/Task/Averages-Mode/Go/averages-mode-2.go @@ -0,0 +1,28 @@ +package main + +import "fmt" + +func main() { + fmt.Println(mode([]interface{}{.2, .7, .1, .8, .2})) + fmt.Println(mode([]interface{}{"two", 7, 1, 8, "two", 8})) +} + +func mode(a []interface{}) []interface{} { + m := make(map[interface{}]int) + for _, v := range a { + m[v]++ + } + var mode []interface{} + var n int + for k, v := range m { + switch { + case v < n: + case v > n: + n = v + mode = append(mode[:0], k) + default: + mode = append(mode, k) + } + } + return mode +} diff --git a/Task/Averages-Mode/Go/averages-mode-3.go b/Task/Averages-Mode/Go/averages-mode-3.go new file mode 100644 index 0000000000..18f0331086 --- /dev/null +++ b/Task/Averages-Mode/Go/averages-mode-3.go @@ -0,0 +1,57 @@ +package main + +import "fmt" + +// interface type +type intCollection interface { + iterator() func() (int, bool) +} + +// concrete type implements interface +type intSlice []int + +// method on concrete type satisfies interface method +func (s intSlice) iterator() func() (int, bool) { + i := 0 + return func() (int, bool) { + if i >= len(s) { + return 0, false + } + v := s[i] + i++ + return v, true + } +} + +func main() { + fmt.Println(mode(intSlice{2, 7, 1, 8, 2})) + fmt.Println(mode(intSlice{2, 7, 1, 8, 2, 8})) +} + +// mode is now a generic function, in a sense. +// It knows what to do with an intCollection, +// but does not know the underlying concrete type. +func mode(a intCollection) []int { + m := make(map[int]int) + i := a.iterator() + for { + v, ok := i() + if !ok { + break + } + m[v]++ + } + var mode []int + var n int + for k, v := range m { + switch { + case v < n: + case v > n: + n = v + mode = append(mode[:0], k) + default: + mode = append(mode, k) + } + } + return mode +} diff --git a/Task/Averages-Mode/Go/averages-mode-4.go b/Task/Averages-Mode/Go/averages-mode-4.go new file mode 100644 index 0000000000..88d64fa6f3 --- /dev/null +++ b/Task/Averages-Mode/Go/averages-mode-4.go @@ -0,0 +1,67 @@ +package main + +import "fmt" + +type collection interface { + iterator() func() (interface{}, bool) +} + +type intSlice []int + +func (s intSlice) iterator() func() (interface{}, bool) { + i := 0 + return func() (interface{}, bool) { + if i >= len(s) { + return 0, false + } + v := s[i] + i++ + return v, true + } +} + +type runeList string + +func (s runeList) iterator() func() (interface{}, bool) { + c := make(chan rune) + go func() { + for _, r := range s { + c <- r + } + close(c) + }() + return func() (interface{}, bool) { + r, ok := <-c + return string(r), ok + } +} + +func main() { + fmt.Println(mode(intSlice{2, 7, 1, 8, 2})) + fmt.Println(mode(runeList("Enzyklopädie"))) +} + +func mode(a collection) []interface{} { + m := make(map[interface{}]int) + i := a.iterator() + for { + v, ok := i() + if !ok { + break + } + m[v]++ + } + var mode []interface{} + var n int + for k, v := range m { + switch { + case v < n: + case v > n: + n = v + mode = append(mode[:0], k) + default: + mode = append(mode, k) + } + } + return mode +} diff --git a/Task/Averages-Mode/Haskell/averages-mode-1.hs b/Task/Averages-Mode/Haskell/averages-mode-1.hs new file mode 100644 index 0000000000..d25e2a2507 --- /dev/null +++ b/Task/Averages-Mode/Haskell/averages-mode-1.hs @@ -0,0 +1,6 @@ +import Prelude (foldr, maximum, (==), (+)) +import Data.Map (insertWith', empty, filter, elems, keys) + +mode :: (Ord a) => [a] -> [a] +mode xs = keys (filter (== maximum (elems counts)) counts) + where counts = foldr (\x -> insertWith' (+) x 1) empty xs diff --git a/Task/Averages-Mode/Haskell/averages-mode-2.hs b/Task/Averages-Mode/Haskell/averages-mode-2.hs new file mode 100644 index 0000000000..958b64c4bd --- /dev/null +++ b/Task/Averages-Mode/Haskell/averages-mode-2.hs @@ -0,0 +1,6 @@ +import Data.List (group, sort) + +mode :: (Ord a) => [a] -> [a] +mode xs = map fst $ filter ((==best).snd) counts + where counts = map (\l -> (head l, length l)) . group . sort $ xs + best = maximum (map snd counts) diff --git a/Task/Averages-Mode/Haskell/averages-mode-3.hs b/Task/Averages-Mode/Haskell/averages-mode-3.hs new file mode 100644 index 0000000000..c990ddc95e --- /dev/null +++ b/Task/Averages-Mode/Haskell/averages-mode-3.hs @@ -0,0 +1,11 @@ +import Data.List (partition) + +mode :: (Eq a) => [a] -> [a] +mode = snd . modesWithCount + where modesWithCount :: (Eq a) => [a] -> (Int, [a]) + modesWithCount [] = (0,[]) + modesWithCount l@(x:_) | length xs > best = (length xs, [x]) + | length xs < best = (best, modes) + | otherwise = (best, x:modes) + where (xs, notxs) = partition (== x) l + (best, modes) = modesWithCount notxs diff --git a/Task/Averages-Mode/Java/averages-mode.java b/Task/Averages-Mode/Java/averages-mode.java new file mode 100644 index 0000000000..c51fc2c7bf --- /dev/null +++ b/Task/Averages-Mode/Java/averages-mode.java @@ -0,0 +1,28 @@ +import java.util.*; + +public class Mode { + public static List mode(List coll) { + Map seen = new HashMap(); + int max = 0; + List maxElems = new ArrayList(); + for (T value : coll) { + if (seen.containsKey(value)) + seen.put(value, seen.get(value) + 1); + else + seen.put(value, 1); + if (seen.get(value) > max) { + max = seen.get(value); + maxElems.clear(); + maxElems.add(value); + } else if (seen.get(value) == max) { + maxElems.add(value); + } + } + return maxElems; + } + + public static void main(String[] args) { + System.out.println(mode(Arrays.asList(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); // prints [6] + System.out.println(mode(Arrays.asList(1, 1, 2, 4, 4))); // prints [1, 4] + } +} diff --git a/Task/Averages-Mode/JavaScript/averages-mode.js b/Task/Averages-Mode/JavaScript/averages-mode.js new file mode 100644 index 0000000000..ffd01a0173 --- /dev/null +++ b/Task/Averages-Mode/JavaScript/averages-mode.js @@ -0,0 +1,21 @@ +function mode(ary) { + var counter = {}; + var mode = []; + var max = 0; + for (var i in ary) { + if (!(ary[i] in counter)) + counter[ary[i]] = 0; + counter[ary[i]]++; + + if (counter[ary[i]] == max) + mode.push(ary[i]); + else if (counter[ary[i]] > max) { + max = counter[ary[i]]; + mode = [ary[i]]; + } + } + return mode; +} + +mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]); // [6] +mode([1, 2, 4, 4, 1]); // [1,4] diff --git a/Task/Averages-Mode/Lua/averages-mode.lua b/Task/Averages-Mode/Lua/averages-mode.lua new file mode 100644 index 0000000000..2f09196d49 --- /dev/null +++ b/Task/Averages-Mode/Lua/averages-mode.lua @@ -0,0 +1,30 @@ +function mode (numlist) + if type(numlist) ~= 'table' then return numlist end + local sets = {} + local mode + local modeValue = 0 + table.foreach(numlist,function(i,v) if sets[v] then sets[v] = sets[v] + 1 else sets[v] = 1 end end) + for i,v in next,sets do + if v > modeValue then + modeValue = v + mode = i + else + if v == modeValue then + if type(mode) == 'table' then + table.insert(mode,i) + else + mode = {mode,i} + end + end + end + end + return mode +end + +result = mode({1,3,6,6,6,6,7,7,12,12,17}) +print(result) +result = mode({1, 1, 2, 4, 4}) +if type(result) == 'table' then + for i,v in next,result do io.write(v..' ') end + print () +end diff --git a/Task/Averages-Mode/MATLAB/averages-mode.m b/Task/Averages-Mode/MATLAB/averages-mode.m new file mode 100644 index 0000000000..a456fb68fa --- /dev/null +++ b/Task/Averages-Mode/MATLAB/averages-mode.m @@ -0,0 +1,3 @@ +function modeValue = findmode(setOfValues) + modeValue = mode(setOfValues); +end diff --git a/Task/Averages-Mode/PHP/averages-mode.php b/Task/Averages-Mode/PHP/averages-mode.php new file mode 100644 index 0000000000..5bfcb12bf1 --- /dev/null +++ b/Task/Averages-Mode/PHP/averages-mode.php @@ -0,0 +1,10 @@ + diff --git a/Task/Averages-Mode/Perl/averages-mode-1.pl b/Task/Averages-Mode/Perl/averages-mode-1.pl new file mode 100644 index 0000000000..c9dea6ea2b --- /dev/null +++ b/Task/Averages-Mode/Perl/averages-mode-1.pl @@ -0,0 +1,12 @@ +use strict; +use List::Util qw(max); + +sub mode +{ + my %c; + foreach my $e ( @_ ) { + $c{$e}++; + } + my $best = max(values %c); + return grep { $c{$_} == $best } keys %c; +} diff --git a/Task/Averages-Mode/Perl/averages-mode-2.pl b/Task/Averages-Mode/Perl/averages-mode-2.pl new file mode 100644 index 0000000000..0aeb0292f4 --- /dev/null +++ b/Task/Averages-Mode/Perl/averages-mode-2.pl @@ -0,0 +1,4 @@ +print "$_ " foreach mode(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17); +print "\n"; +print "$_ " foreach mode(1, 1, 2, 4, 4); +print "\n"; diff --git a/Task/Averages-Mode/PicoLisp/averages-mode.l b/Task/Averages-Mode/PicoLisp/averages-mode.l new file mode 100644 index 0000000000..14650aa66e --- /dev/null +++ b/Task/Averages-Mode/PicoLisp/averages-mode.l @@ -0,0 +1,7 @@ +(de modes (Lst) + (let A NIL + (for X Lst + (accu 'A X 1) ) + (mapcar car + (maxi cdar + (by cdr group A) ) ) ) ) diff --git a/Task/Averages-Mode/Python/averages-mode-1.py b/Task/Averages-Mode/Python/averages-mode-1.py new file mode 100644 index 0000000000..d75086acf2 --- /dev/null +++ b/Task/Averages-Mode/Python/averages-mode-1.py @@ -0,0 +1,12 @@ +>>> from collections import defaultdict +>>> def modes(values): + count = defaultdict(int) + for v in values: + count[v] +=1 + best = max(count.values()) + return [k for k,v in count.items() if v == best] + +>>> modes([1,3,6,6,6,6,7,7,12,12,17]) +[6] +>>> modes((1,1,2,4,4)) +[1, 4] diff --git a/Task/Averages-Mode/Python/averages-mode-2.py b/Task/Averages-Mode/Python/averages-mode-2.py new file mode 100644 index 0000000000..839c4c1b5f --- /dev/null +++ b/Task/Averages-Mode/Python/averages-mode-2.py @@ -0,0 +1,10 @@ +>>> from collections import Counter +>>> def modes(values): + count = Counter(values) + best = max(count.values()) + return [k for k,v in count.items() if v == best] + +>>> modes([1,3,6,6,6,6,7,7,12,12,17]) +[6] +>>> modes((1,1,2,4,4)) +[1, 4] diff --git a/Task/Averages-Mode/Python/averages-mode-3.py b/Task/Averages-Mode/Python/averages-mode-3.py new file mode 100644 index 0000000000..30f4bebe8b --- /dev/null +++ b/Task/Averages-Mode/Python/averages-mode-3.py @@ -0,0 +1,2 @@ +def onemode(values): + return max(set(values), key=values.count) diff --git a/Task/Averages-Mode/R/averages-mode.r b/Task/Averages-Mode/R/averages-mode.r new file mode 100644 index 0000000000..7fc91a2496 --- /dev/null +++ b/Task/Averages-Mode/R/averages-mode.r @@ -0,0 +1,14 @@ +statmode <- function(v) { + a <- sort(table(v), decreasing=TRUE) + r <- c() + for(i in 1:length(a)) { + if ( a[[1]] == a[[i]] ) { + r <- c(r, as.integer(names(a)[i])) + } else break; # since it's sorted, once we find + # a different value, we can stop + } + r +} + +print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))) +print(statmode(c(1, 1, 2, 4, 4))) diff --git a/Task/Averages-Mode/REXX/averages-mode-1.rexx b/Task/Averages-Mode/REXX/averages-mode-1.rexx new file mode 100644 index 0000000000..1df655d058 --- /dev/null +++ b/Task/Averages-Mode/REXX/averages-mode-1.rexx @@ -0,0 +1,34 @@ +/*REXX program finds the mode (most occurring element) of a vector. */ + +/*────────vector────────── ───show vector─── ────show result────── */ +v='1 8 6 0 1 9 4 6 1 9 9 9' ; say 'vector='v; say 'mode='mode(v); say +v='1 2 3 4 5 6 7 8 9 10 11' ; say 'vector='v; say 'mode='mode(v); say +v='8 8 8 2 2 2' ; say 'vector='v; say 'mode='mode(v); say +v='cat kat Cat emu emu Kat' ; say 'vector='v; say 'mode='mode(v); say + +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────MAKEARRAY subroutine────────────────*/ +makeArray: procedure expose @.; parse arg v; @.0=words(v) /*make array*/ + do k=1 for @.0; @.k=word(v,k); end /*k*/ +return +/*──────────────────────────────────ESORT subroutine────────────────────*/ +esort: procedure expose @.; h=@.0 /*exchange sort.*/ + do while h>1; h=h%2 + do i=1 for @.0-h; j=i; k=h+i + do while @.k<@.j;t=@.j;@.j=@.k;@.k=t;if h>=j then leave;j=j-h;k=k-h;end + end /*i*/ + end /*while h>1*/ +return +/*──────────────────────────────────MODE subroutine─────────────────────*/ +mode: procedure expose @.; parse arg x /*finds the MODE of a vector. */ +call makeArray x /*make an array out of the vector*/ +call esort @.0 /*sort the array elements. */ +?=@.1 /*assume 1st element is the mode.*/ +freq=1 /*the frequency of the occurance.*/ + do j=1 for @.0; _=j-freq + if @.j==@._ then do + freq=freq+1 /*bump the frequency count. */ + ?=@.j /*this is the one. */ + end + end /*j*/ +return ? diff --git a/Task/Averages-Mode/REXX/averages-mode-2.rexx b/Task/Averages-Mode/REXX/averages-mode-2.rexx new file mode 100644 index 0000000000..63242f526f --- /dev/null +++ b/Task/Averages-Mode/REXX/averages-mode-2.rexx @@ -0,0 +1,92 @@ +/* Rexx */ +-- ~~ main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +call run_samples +return +exit + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- returns a comma separated string of mode values from a comma separated input vector string +mode: + procedure + parse arg lvector + drop vector. + vector. = '' + call makeStem lvector -- this call creates the "vector." stem from the input string + seen. = 0 + modes. = '' + modeMax = 0 + do v_ = 1 to vector.0 + mv = vector.v_ + seen.mv = seen.mv + 1 + select + when seen.mv > modeMax then do + modeMax = seen.mv + drop modes. + modes. = '' + nx = 1 + modes.0 = nx + modes.nx = mv + end + when seen.mv = modeMax then do + nx = modes.0 + 1 + modes.0 = nx + modes.nx = mv + end + otherwise do + nop + end + end + end v_ + + lmodes = '' + do e_ = 1 to modes.0 + lmodes = lmodes modes.e_ + end e_ + lmodes = strip(space(lmodes, 1, ',')) + + return lmodes + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- pretty-print +show_mode: + procedure + parse arg lvector + lmodes = mode(lvector) + say 'Vector: ['space(lvector, 0)'], Mode(s): ['space(lmodes, 0)']' + return modes + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- load the "vector." stem from the comma separated input vector string +makeStem: + procedure expose vector. + vector.0 = 0 + parse arg lvector + do v_ = 1 while lvector \= '' + parse var lvector val ',' lvector + vector.0 = v_ + vector.v_ = strip(val) + vector = strip(lvector) + end v_ + return vector.0 + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +run_samples: + procedure + call show_mode '10, 9, 8, 7, 6, 5, 4, 3, 2, 1' -- 10 9 8 7 6 5 4 3 2 1 + call show_mode '10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11' -- 0 + call show_mode '30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2' -- 30 + call show_mode '30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2, -11e+2' -- 30 -11e2 + call show_mode '1, 8, 6, 0, 1, 9, 4, 6, 1, 9, 9, 9' -- 9 + call show_mode '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11' -- 1 2 3 4 5 6 7 8 9 10 11 + call show_mode '8, 8, 8, 2, 2, 2' -- 8 2 + call show_mode 'cat, kat, Cat, emu, emu, Kat' -- emu + call show_mode '0, 1, 2, 3, 3, 3, 4, 4, 4, 4, 1, 0' -- 4 + call show_mode '2, 7, 1, 8, 2' -- 2 + call show_mode '2, 7, 1, 8, 2, 8' -- 8 2 + call show_mode 'E, n, z, y, k, l, o, p, ä, d, i, e' -- E n z y k l o p ä d i e + call show_mode 'E, n, z, y, k, l, o, p, ä, d, i, e, ä' -- ä + call show_mode '3, 1, 4, 1, 5, 9, 7, 6' -- 1 + call show_mode '3, 1, 4, 1, 5, 9, 7, 6, 3' -- 3, 1 + call show_mode '1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17' -- 6 + call show_mode '1, 1, 2, 4, 4' -- 4 1 + return diff --git a/Task/Averages-Mode/Ruby/averages-mode-1.rb b/Task/Averages-Mode/Ruby/averages-mode-1.rb new file mode 100644 index 0000000000..2a490a7f82 --- /dev/null +++ b/Task/Averages-Mode/Ruby/averages-mode-1.rb @@ -0,0 +1,27 @@ +def mode(ary) + seen = Hash.new(0) + ary.each {|value| seen[value] += 1} + max = seen.values.max + seen.find_all {|key,value| value == max}.map {|key,value| key} +end + +def mode_one_pass(ary) + seen = Hash.new(0) + max = 0 + max_elems = [] + ary.each do |value| + seen[value] += 1 + if seen[value] > max + max = seen[value] + max_elems = [value] + elsif seen[value] == max + max_elems << value + end + end + max_elems +end + +p mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) # => [6] +p mode([1, 1, 2, 4, 4]) # => [1, 4] +p mode_one_pass([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) # => [6] +p mode_one_pass([1, 1, 2, 4, 4]) # => [1, 4] diff --git a/Task/Averages-Mode/Ruby/averages-mode-2.rb b/Task/Averages-Mode/Ruby/averages-mode-2.rb new file mode 100644 index 0000000000..b6089a97a6 --- /dev/null +++ b/Task/Averages-Mode/Ruby/averages-mode-2.rb @@ -0,0 +1,3 @@ +def one_mode(ary) + ary.max_by { |x| ary.count(x) } +end diff --git a/Task/Averages-Mode/Scala/averages-mode.scala b/Task/Averages-Mode/Scala/averages-mode.scala new file mode 100644 index 0000000000..cc5e3ef1e6 --- /dev/null +++ b/Task/Averages-Mode/Scala/averages-mode.scala @@ -0,0 +1,10 @@ +import scala.collection.breakOut +import scala.collection.generic.CanBuildFrom +def mode + [T, CC[X] <: Seq[X]](coll: CC[T]) + (implicit o: T => Ordered[T], cbf: CanBuildFrom[Nothing, T, CC[T]]) + : CC[T] = { + val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq + val max = grouped.map(_._2).max + grouped.filter(_._2 == max).map(_._1)(breakOut) +} diff --git a/Task/Averages-Mode/Scheme/averages-mode.ss b/Task/Averages-Mode/Scheme/averages-mode.ss new file mode 100644 index 0000000000..65333e4534 --- /dev/null +++ b/Task/Averages-Mode/Scheme/averages-mode.ss @@ -0,0 +1,10 @@ +(define (mode collection) + (define (helper collection counts) + (if (null? collection) + counts + (helper (remove (car collection) collection) + (cons (cons (car collection) + (appearances (car collection) collection)) counts)))) + (map car + (filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '()))))) + (helper collection '()))) diff --git a/Task/Averages-Mode/Smalltalk/averages-mode.st b/Task/Averages-Mode/Smalltalk/averages-mode.st new file mode 100644 index 0000000000..d2de1651f1 --- /dev/null +++ b/Task/Averages-Mode/Smalltalk/averages-mode.st @@ -0,0 +1,11 @@ +OrderedCollection extend [ + mode [ |s| + s := self asBag sortedByCount. + ^ (s select: [ :k | ((s at: 1) key) = (k key) ]) collect: [:k| k value] + ] +]. + +#( 1 3 6 6 6 6 7 7 12 12 17 ) asOrderedCollection + mode displayNl. +#( 1 1 2 4 4) asOrderedCollection + mode displayNl. diff --git a/Task/Averages-Mode/Tcl/averages-mode.tcl b/Task/Averages-Mode/Tcl/averages-mode.tcl new file mode 100644 index 0000000000..e6a59eba9e --- /dev/null +++ b/Task/Averages-Mode/Tcl/averages-mode.tcl @@ -0,0 +1,18 @@ +# Can find the modal value of any vector of values +proc mode {n args} { + foreach n [list $n {*}$args] { + dict incr counter $n + } + set counts [lsort -stride 2 -index 1 -decreasing $counter] + set best {} + foreach {n count} $counts { + if {[lindex $counts 1] == $count} { + lappend best $n + } else break + } + return $best +} + +# Testing +puts [mode 1 3 6 6 6 6 7 7 12 12 17]; # --> 6 +puts [mode 1 1 2 4 4]; # --> 1 4 diff --git a/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-1.m b/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-1.m new file mode 100644 index 0000000000..6054a63417 --- /dev/null +++ b/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-1.m @@ -0,0 +1,7 @@ +function [A,G,H] = pythagoreanMeans(list) + + A = mean(list); + G = geomean(list); + H = harmmean(list); + +end diff --git a/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-2.m b/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-2.m new file mode 100644 index 0000000000..d73097df2e --- /dev/null +++ b/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-2.m @@ -0,0 +1,5 @@ +function [A,G,H] = pythagoreanMeans(list) + A = mean(list); % arithmetic mean + G = exp(mean(log(list))); % geometric mean + H = 1./mean(1./list); % harmonic mean +end diff --git a/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-3.m b/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-3.m new file mode 100644 index 0000000000..eb26c9ff2e --- /dev/null +++ b/Task/Averages-Pythagorean-means/MATLAB/averages-pythagorean-means-3.m @@ -0,0 +1,15 @@ +>> [A,G,H]=pythagoreanMeans((1:10)) + +A = + + 5.500000000000000 + + +G = + + 4.528728688116765 + + +H = + + 3.414171521474055 diff --git a/Task/Averages-Root-mean-square/MATLAB/averages-root-mean-square-1.m b/Task/Averages-Root-mean-square/MATLAB/averages-root-mean-square-1.m new file mode 100644 index 0000000000..5c3b8b6d43 --- /dev/null +++ b/Task/Averages-Root-mean-square/MATLAB/averages-root-mean-square-1.m @@ -0,0 +1,3 @@ +function rms = quadraticMean(list) + rms = sqrt(mean(list.^2)); +end diff --git a/Task/Averages-Root-mean-square/MATLAB/averages-root-mean-square-2.m b/Task/Averages-Root-mean-square/MATLAB/averages-root-mean-square-2.m new file mode 100644 index 0000000000..df86cd6909 --- /dev/null +++ b/Task/Averages-Root-mean-square/MATLAB/averages-root-mean-square-2.m @@ -0,0 +1,5 @@ +>> quadraticMean((1:10)) + +ans = + + 6.204836822995429 diff --git a/Task/Averages-Simple-moving-average/MATLAB/averages-simple-moving-average-1.m b/Task/Averages-Simple-moving-average/MATLAB/averages-simple-moving-average-1.m new file mode 100644 index 0000000000..73f17dd37f --- /dev/null +++ b/Task/Averages-Simple-moving-average/MATLAB/averages-simple-moving-average-1.m @@ -0,0 +1 @@ + [m,z] = filter(ones(1,P),P,x); diff --git a/Task/Averages-Simple-moving-average/MATLAB/averages-simple-moving-average-2.m b/Task/Averages-Simple-moving-average/MATLAB/averages-simple-moving-average-2.m new file mode 100644 index 0000000000..8b6034ebcc --- /dev/null +++ b/Task/Averages-Simple-moving-average/MATLAB/averages-simple-moving-average-2.m @@ -0,0 +1 @@ + [m,z] = filter(ones(1,P),P,x,z); diff --git a/Task/Balanced-brackets/MATLAB/balanced-brackets.m b/Task/Balanced-brackets/MATLAB/balanced-brackets.m new file mode 100644 index 0000000000..22f2015cb2 --- /dev/null +++ b/Task/Balanced-brackets/MATLAB/balanced-brackets.m @@ -0,0 +1,4 @@ +function x = isbb(s) + t = cumsum((s=='[') - (s==']')); + x = all(t>=0) && (t(end)==0); +end; diff --git a/Task/Binary-search/MATLAB/binary-search-1.m b/Task/Binary-search/MATLAB/binary-search-1.m new file mode 100644 index 0000000000..1621fabdd6 --- /dev/null +++ b/Task/Binary-search/MATLAB/binary-search-1.m @@ -0,0 +1,20 @@ +function mid = binarySearchRec(list,value,low,high) + + if( high < low ) + mid = []; + return + end + + mid = floor((low + high)/2); + + if( list(mid) > value ) + mid = binarySearchRec(list,value,low,mid-1); + return + elseif( list(mid) < value ) + mid = binarySearchRec(list,value,mid+1,high); + return + else + return + end + +end diff --git a/Task/Binary-search/MATLAB/binary-search-2.m b/Task/Binary-search/MATLAB/binary-search-2.m new file mode 100644 index 0000000000..0be82de615 --- /dev/null +++ b/Task/Binary-search/MATLAB/binary-search-2.m @@ -0,0 +1,5 @@ +>> binarySearchRec([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5,1,numel([1 2 3 4 5 6 6.5 7 8 9 11 18])) + +ans = + + 7 diff --git a/Task/Binary-search/MATLAB/binary-search-3.m b/Task/Binary-search/MATLAB/binary-search-3.m new file mode 100644 index 0000000000..a8252d9248 --- /dev/null +++ b/Task/Binary-search/MATLAB/binary-search-3.m @@ -0,0 +1,20 @@ +function mid = binarySearchIter(list,value) + + low = 0; + high = numel(list) - 1; + + while( low <= high ) + mid = floor((low + high)/2); + + if( list(mid) > value ) + high = mid - 1; + elseif( list(mid) < value ) + low = mid + 1; + else + return + end + end + + mid = []; + +end diff --git a/Task/Binary-search/MATLAB/binary-search-4.m b/Task/Binary-search/MATLAB/binary-search-4.m new file mode 100644 index 0000000000..6986458a73 --- /dev/null +++ b/Task/Binary-search/MATLAB/binary-search-4.m @@ -0,0 +1,5 @@ +>> binarySearchIter([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5) + +ans = + + 7 diff --git a/Task/Caesar-cipher/MATLAB/caesar-cipher-1.m b/Task/Caesar-cipher/MATLAB/caesar-cipher-1.m new file mode 100644 index 0000000000..ba19440994 --- /dev/null +++ b/Task/Caesar-cipher/MATLAB/caesar-cipher-1.m @@ -0,0 +1,6 @@ + function s = cipherCaesar(s, key) + s = char( mod(s - 'A' + key, 25 ) + 'A'); + end; + function s = decipherCaesar(s, key) + s = char( mod(s - 'A' - key, 25 ) + 'A'); + end; diff --git a/Task/Caesar-cipher/MATLAB/caesar-cipher-2.m b/Task/Caesar-cipher/MATLAB/caesar-cipher-2.m new file mode 100644 index 0000000000..d3330822b4 --- /dev/null +++ b/Task/Caesar-cipher/MATLAB/caesar-cipher-2.m @@ -0,0 +1,2 @@ + decipherCaesar(cipherCaesar('ABC',4),4) + ans = ABC diff --git a/Task/Check-that-file-exists/MATLAB/check-that-file-exists.m b/Task/Check-that-file-exists/MATLAB/check-that-file-exists.m new file mode 100644 index 0000000000..83dcca45e2 --- /dev/null +++ b/Task/Check-that-file-exists/MATLAB/check-that-file-exists.m @@ -0,0 +1,4 @@ + exist('input.txt','file') + exist('/input.txt','file') + exist('docs','dir') + exist('/docs','dir') diff --git a/Task/Classes/MATLAB/classes-1.m b/Task/Classes/MATLAB/classes-1.m new file mode 100644 index 0000000000..aa88a7a811 --- /dev/null +++ b/Task/Classes/MATLAB/classes-1.m @@ -0,0 +1,12 @@ +function GenericClassInstance = GenericClass(varargin) + + if isempty(varargin) %No input arguments + GenericClassInstance.classVariable = 0; %Generates a struct + else + GenericClassInstance.classVariable = varargin{1}; %Generates a struct + end + + %Converts the struct to a class of type GenericClass + GenericClassInstance = class(GenericClassInstance,'GenericClass'); + +end diff --git a/Task/Classes/MATLAB/classes-2.m b/Task/Classes/MATLAB/classes-2.m new file mode 100644 index 0000000000..f1ebd1f927 --- /dev/null +++ b/Task/Classes/MATLAB/classes-2.m @@ -0,0 +1,4 @@ +%Get function +function value = getValue(GenericClassInstance) + value = GenericClassInstance.classVariable; +end diff --git a/Task/Classes/MATLAB/classes-3.m b/Task/Classes/MATLAB/classes-3.m new file mode 100644 index 0000000000..8ec1c41052 --- /dev/null +++ b/Task/Classes/MATLAB/classes-3.m @@ -0,0 +1,4 @@ +%Set function +function GenericClassInstance = setValue(GenericClassInstance,newValue) + GenericClassInstance.classVariable = newValue; +end diff --git a/Task/Classes/MATLAB/classes-4.m b/Task/Classes/MATLAB/classes-4.m new file mode 100644 index 0000000000..fee7fde8f6 --- /dev/null +++ b/Task/Classes/MATLAB/classes-4.m @@ -0,0 +1,3 @@ +function display(GenericClassInstance) + disp(sprintf('%f',GenericClassInstance.classVariable)); +end diff --git a/Task/Classes/MATLAB/classes-5.m b/Task/Classes/MATLAB/classes-5.m new file mode 100644 index 0000000000..87f435a0ff --- /dev/null +++ b/Task/Classes/MATLAB/classes-5.m @@ -0,0 +1,9 @@ +>> myClass = GenericClass(3) +3.000000 +>> myClass = setValue(myClass,pi) +3.141593 +>> getValue(myClass) + +ans = + + 3.141592653589793 diff --git a/Task/Classes/MATLAB/classes-6.m b/Task/Classes/MATLAB/classes-6.m new file mode 100644 index 0000000000..2aab034cdf --- /dev/null +++ b/Task/Classes/MATLAB/classes-6.m @@ -0,0 +1,28 @@ +classdef GenericClass2 + + properties + classVariable + end %properties + + methods + + %Class constructor + function objectInstance = GenericClass2(varargin) + if isempty(varargin) %No input arguments + objectInstance.classVariable = 0; + else + objectInstance.classVariable = varargin{1}; + end + end + + %Set function + function setValue(GenericClassInstance,newValue) + GenericClassInstance.classVariable = newValue; + + %MATLAB magic that changes the object in the scope that called + %this set function. + assignin('caller',inputname(1),GenericClassInstance); + end + + end %methods +end diff --git a/Task/Classes/MATLAB/classes-7.m b/Task/Classes/MATLAB/classes-7.m new file mode 100644 index 0000000000..f1ebd1f927 --- /dev/null +++ b/Task/Classes/MATLAB/classes-7.m @@ -0,0 +1,4 @@ +%Get function +function value = getValue(GenericClassInstance) + value = GenericClassInstance.classVariable; +end diff --git a/Task/Classes/MATLAB/classes-8.m b/Task/Classes/MATLAB/classes-8.m new file mode 100644 index 0000000000..fee7fde8f6 --- /dev/null +++ b/Task/Classes/MATLAB/classes-8.m @@ -0,0 +1,3 @@ +function display(GenericClassInstance) + disp(sprintf('%f',GenericClassInstance.classVariable)); +end diff --git a/Task/Classes/MATLAB/classes-9.m b/Task/Classes/MATLAB/classes-9.m new file mode 100644 index 0000000000..865db98d40 --- /dev/null +++ b/Task/Classes/MATLAB/classes-9.m @@ -0,0 +1,8 @@ +>> myClass = GenericClass2(3) +3.000000 +>> setValue(myClass,pi) +>> getValue(myClass) + +ans = + + 3.141592653589793 diff --git a/Task/Closest-pair-problem/MATLAB/closest-pair-problem-1.m b/Task/Closest-pair-problem/MATLAB/closest-pair-problem-1.m new file mode 100644 index 0000000000..dabeddeb30 --- /dev/null +++ b/Task/Closest-pair-problem/MATLAB/closest-pair-problem-1.m @@ -0,0 +1,71 @@ +function [closest,closestpair] = closestPair(xP,yP) + + N = numel(xP); + + if(N <= 3) + + %Brute force closestpair + if(N < 2) + closest = +Inf; + closestpair = {}; + else + closest = norm(xP{1}-xP{2}); + closestpair = {xP{1},xP{2}}; + + for i = ( 1:N-1 ) + for j = ( (i+1):N ) + if ( norm(xP{i} - xP{j}) < closest ) + closest = norm(xP{i}-xP{j}); + closestpair = {xP{i},xP{j}}; + end %if + end %for + end %for + end %if (N < 2) + else + + halfN = ceil(N/2); + + xL = { xP{1:halfN} }; + xR = { xP{halfN+1:N} }; + xm = xP{halfN}(1); + + %cellfun( @(p)le(p(1),xm),yP ) is the same as { p ∈ yP : px ≤ xm } + yLIndicies = cellfun( @(p)le(p(1),xm),yP ); + + yL = { yP{yLIndicies} }; + yR = { yP{~yLIndicies} }; + + [dL,pairL] = closestPair(xL,yL); + [dR,pairR] = closestPair(xR,yR); + + if dL < dR + dmin = dL; + pairMin = pairL; + else + dmin = dR; + pairMin = pairR; + end + + %cellfun( @(p)lt(norm(xm-p(1)),dmin),yP ) is the same as + %{ p ∈ yP : |xm - px| < dmin } + yS = {yP{ cellfun( @(p)lt(norm(xm-p(1)),dmin),yP ) }}; + nS = numel(yS); + + closest = dmin; + closestpair = pairMin; + + for i = (1:nS-1) + k = i+1; + + while( (k<=nS) && (yS{k}(2)-yS{i}(2) < dmin) ) + + if norm(yS{k}-yS{i}) < closest + closest = norm(yS{k}-yS{i}); + closestpair = {yS{k},yS{i}}; + end + + k = k+1; + end %while + end %for + end %if (N <= 3) +end %closestPair diff --git a/Task/Closest-pair-problem/MATLAB/closest-pair-problem-2.m b/Task/Closest-pair-problem/MATLAB/closest-pair-problem-2.m new file mode 100644 index 0000000000..60e2f198d7 --- /dev/null +++ b/Task/Closest-pair-problem/MATLAB/closest-pair-problem-2.m @@ -0,0 +1,10 @@ +[distance,pair]=closestPair({[0 -.3],[1 1],[1.5 2],[2 2],[3 3]},{[0 -.3],[1 1],[1.5 2],[2 2],[3 3]}) + +distance = + + 0.500000000000000 + + +pair = + + [1x2 double] [1x2 double] %The pair is [1.5 2] and [2 2] which is correct diff --git a/Task/Collections/MATLAB/collections.m b/Task/Collections/MATLAB/collections.m new file mode 100644 index 0000000000..828a92d4ab --- /dev/null +++ b/Task/Collections/MATLAB/collections.m @@ -0,0 +1,24 @@ +>> A = {2,'TPS Report'} %Declare cell-array and initialize + +A = + + [2] 'TPS Report' + +>> A{2} = struct('make','honda','year',2003) + +A = + + [2] [1x1 struct] + +>> A{3} = {3,'HOVA'} %Create and assign A{3} + +A = + + [2] [1x1 struct] {1x2 cell} + +>> A{2} %Get A{2} + +ans = + + make: 'honda' + year: 2003 diff --git a/Task/Comments/MATLAB/comments.m b/Task/Comments/MATLAB/comments.m new file mode 100644 index 0000000000..f22d4c1d92 --- /dev/null +++ b/Task/Comments/MATLAB/comments.m @@ -0,0 +1,2 @@ +%This is a comment +%% Two percent signs and a space are called a cell divider diff --git a/Task/Define-a-primitive-data-type/MATLAB/define-a-primitive-data-type-1.m b/Task/Define-a-primitive-data-type/MATLAB/define-a-primitive-data-type-1.m new file mode 100644 index 0000000000..3f20abc86f --- /dev/null +++ b/Task/Define-a-primitive-data-type/MATLAB/define-a-primitive-data-type-1.m @@ -0,0 +1,86 @@ +classdef RingInt + + properties + value + end + + methods + + %RingInt constructor + function theInt = RingInt(varargin) + if numel(varargin) == 0 + theInt.value = 1; + elseif numel(varargin) > 1 + error 'The RingInt constructor can''''t take more than 1 argument.'; + else + + %Makes sure any doubles are coerced to ints + if not(isinteger(varargin{1})) + varargin{1} = int32(varargin{1}); + end + + %Maps out of bound values to the proper range + if varargin{1} > 10 + theInt.value = varargin{1} - (10 * (idivide(varargin{1},10,'ceil') - 1)); + elseif varargin{1} < 1 + theInt.value = varargin{1} + (10 * (idivide(abs(varargin{1}),10,'floor') + 1)); + else + theInt.value = varargin{1}; + end + end + end %constructor + + %Overload the "+" operator + function sum = plus(firstNumber,secondNumber) + + if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt') + sum = firstNumber.value + secondNumber.value; + elseif isa(firstNumber,'RingInt') && not(isa(secondNumber,'RingInt')) + sum = firstNumber.value + secondNumber; + else + sum = secondNumber.value + firstNumber; + end + + sum = RingInt(sum); + + end %+ + + %Overload the "-" operator + function difference = minus(firstNumber,secondNumber) + + if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt') + difference = firstNumber.value - secondNumber.value; + elseif isa(firstNumber,'RingInt') && not(isa(secondNumber,'RingInt')) + difference = firstNumber.value - secondNumber; + else + difference = firstNumber - secondNumber.value; + end + + difference = RingInt(difference); + + end %- + + %Overload the "==" operator + function trueFalse = eq(firstNumber,secondNumber) + + if isa(firstNumber,'RingInt') && isa(secondNumber,'RingInt') + trueFalse = firstNumber.value == secondNumber.value; + else + error 'You can only compare a RingInt to another RingInt'; + end + + end %== + + + %Overload the display() function + function display(ringInt) + disp(ringInt); + end + + %Overload the disp() function + function disp(ringInt) + disp(sprintf('\nans =\n\n\t %d\n',ringInt.value)); + end + + end %methods +end %classdef diff --git a/Task/Define-a-primitive-data-type/MATLAB/define-a-primitive-data-type-2.m b/Task/Define-a-primitive-data-type/MATLAB/define-a-primitive-data-type-2.m new file mode 100644 index 0000000000..88b9b05b72 --- /dev/null +++ b/Task/Define-a-primitive-data-type/MATLAB/define-a-primitive-data-type-2.m @@ -0,0 +1,23 @@ +>> RingInt(10) + 1 + +ans = + + 1 + +>> RingInt(5) - 20 + +ans = + + 5 + +>> a = RingInt(3) + +ans = + + 3 + +>> a == RingInt(3) + +ans = + + 1 diff --git a/Task/Delete-a-file/MATLAB/delete-a-file-1.m b/Task/Delete-a-file/MATLAB/delete-a-file-1.m new file mode 100644 index 0000000000..d970d040d7 --- /dev/null +++ b/Task/Delete-a-file/MATLAB/delete-a-file-1.m @@ -0,0 +1,4 @@ + delete('input.txt'); % delete local file input.txt + delete('/input.txt'); % delete file /input.txt + rmdir('docs'); % remove local directory docs + rmdir('/docs'); % remove directory /docs diff --git a/Task/Delete-a-file/MATLAB/delete-a-file-2.m b/Task/Delete-a-file/MATLAB/delete-a-file-2.m new file mode 100644 index 0000000000..d508b3973f --- /dev/null +++ b/Task/Delete-a-file/MATLAB/delete-a-file-2.m @@ -0,0 +1,12 @@ +if system('rm input.txt') == 0 + disp('input.txt removed') +end +if system('rm /input.txt') == 0 + disp('/input.txt removed') +end +if system('rmdir docs') == 0 + disp('docs removed') +end +if system('rmdir /docs') == 0 + disp('/docs removed') +end diff --git a/Task/Detect-division-by-zero/MATLAB/detect-division-by-zero.m b/Task/Detect-division-by-zero/MATLAB/detect-division-by-zero.m new file mode 100644 index 0000000000..d19d197546 --- /dev/null +++ b/Task/Detect-division-by-zero/MATLAB/detect-division-by-zero.m @@ -0,0 +1,3 @@ +function [isDividedByZero] = dividebyzero(numerator, denomenator) + isDividedByZero = isinf( numerator/denomenator ); + % If isDividedByZero equals 1, divide by zero occured. diff --git a/Task/Determine-if-a-string-is-numeric/MATLAB/determine-if-a-string-is-numeric.m b/Task/Determine-if-a-string-is-numeric/MATLAB/determine-if-a-string-is-numeric.m new file mode 100644 index 0000000000..d743374033 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/MATLAB/determine-if-a-string-is-numeric.m @@ -0,0 +1,20 @@ +% Is string numeric? + +function [out] = str_isnumeric(string) + + if ~ischar(string) + error('str_isnumeric:NonCharacterArray','not a string input'); + end + + Nd = sum(isstrprop(string,'digit')); + Nc = length(string); + + dN = Nc - Nd; + + switch dN + case 0 + out = 1; + otherwise + out = 0; + end +end diff --git a/Task/FizzBuzz/MATLAB/fizzbuzz-1.m b/Task/FizzBuzz/MATLAB/fizzbuzz-1.m new file mode 100644 index 0000000000..166e91cff5 --- /dev/null +++ b/Task/FizzBuzz/MATLAB/fizzbuzz-1.m @@ -0,0 +1,14 @@ +function fizzBuzz() + for i = (1:100) + if mod(i,15) == 0 + fprintf('FizzBuzz ') + elseif mod(i,3) == 0 + fprintf('Fizz ') + elseif mod(i,5) == 0 + fprintf('Buzz ') + else + fprintf('%i ',i)) + end + end + fprintf('\n'); +end diff --git a/Task/FizzBuzz/MATLAB/fizzbuzz-2.m b/Task/FizzBuzz/MATLAB/fizzbuzz-2.m new file mode 100644 index 0000000000..a57570b108 --- /dev/null +++ b/Task/FizzBuzz/MATLAB/fizzbuzz-2.m @@ -0,0 +1,17 @@ +function out = fizzbuzzS() + nums = [3, 5]; + words = {'fizz', 'buzz'}; + for (n=1:100) + tempstr = ''; + for (i = 1:2) + if mod(n,nums(i))==0 + tempstr = [tempstr, words{i}]; + end + end + if length(tempstr) == 0 + disp(n); + else + disp(tempstr); + end + end +end diff --git a/Task/Infinity/MATLAB/infinity.m b/Task/Infinity/MATLAB/infinity.m new file mode 100644 index 0000000000..2fba8b8482 --- /dev/null +++ b/Task/Infinity/MATLAB/infinity.m @@ -0,0 +1,2 @@ +a = +Inf; +isinf(a) diff --git a/Task/Knuth-shuffle/MATLAB/knuth-shuffle-1.m b/Task/Knuth-shuffle/MATLAB/knuth-shuffle-1.m new file mode 100644 index 0000000000..673f260ee6 --- /dev/null +++ b/Task/Knuth-shuffle/MATLAB/knuth-shuffle-1.m @@ -0,0 +1,10 @@ +function list = knuthShuffle(list) + + for i = (numel(list):-1:2) + + j = floor(i*rand(1) + 1); %Generate random int between 1 and i + + %Swap element i with element j. + list([j i]) = list([i j]); + end +end diff --git a/Task/Knuth-shuffle/MATLAB/knuth-shuffle-2.m b/Task/Knuth-shuffle/MATLAB/knuth-shuffle-2.m new file mode 100644 index 0000000000..09200177bb --- /dev/null +++ b/Task/Knuth-shuffle/MATLAB/knuth-shuffle-2.m @@ -0,0 +1,5 @@ +function list = randSort(list) + + list = list( randperm(numel(list)) ); + +end diff --git a/Task/Ordered-words/MATLAB/ordered-words.m b/Task/Ordered-words/MATLAB/ordered-words.m new file mode 100644 index 0000000000..47159339fb --- /dev/null +++ b/Task/Ordered-words/MATLAB/ordered-words.m @@ -0,0 +1,16 @@ +maxlen = 0; +listlen= 0; +fid = fopen('unixdict.txt','r'); +while ~feof(fid) + str = fgetl(fid); + if any(diff(abs(str))<0) continue; end; + + if length(str)>maxlen, + list = {str}; + maxlen = length(str); + elseif length(str)==maxlen, + list{end+1} = str; + end; +end +fclose(fid); +printf('%s\n',list{:}); diff --git a/Task/Pi/MATLAB/pi.m b/Task/Pi/MATLAB/pi.m new file mode 100644 index 0000000000..4656f872b7 --- /dev/null +++ b/Task/Pi/MATLAB/pi.m @@ -0,0 +1 @@ +pi diff --git a/Task/Quine/MATLAB/quine-1.m b/Task/Quine/MATLAB/quine-1.m new file mode 100644 index 0000000000..34101a0b09 --- /dev/null +++ b/Task/Quine/MATLAB/quine-1.m @@ -0,0 +1,7 @@ + function quine() + fid = fopen([mfilename,'.m']); + while ~feof(fid) + printf('%s\n',fgetl(fid)); + end; + fclose(fid); + end; diff --git a/Task/Quine/MATLAB/quine-2.m b/Task/Quine/MATLAB/quine-2.m new file mode 100644 index 0000000000..529019bee9 --- /dev/null +++ b/Task/Quine/MATLAB/quine-2.m @@ -0,0 +1,3 @@ + function quine() + type(mfilename); + end; diff --git a/Task/Quine/MATLAB/quine-3.m b/Task/Quine/MATLAB/quine-3.m new file mode 100644 index 0000000000..4d40eecced --- /dev/null +++ b/Task/Quine/MATLAB/quine-3.m @@ -0,0 +1 @@ +function quine; y = 'function quine; y = %c%s%c; fprintf(1, y, 39, y, 39)\n'; fprintf(1, y, 39, y, 39) diff --git a/Task/Search-a-list/MATLAB/search-a-list-1.m b/Task/Search-a-list/MATLAB/search-a-list-1.m new file mode 100644 index 0000000000..a827e40f93 --- /dev/null +++ b/Task/Search-a-list/MATLAB/search-a-list-1.m @@ -0,0 +1 @@ +stringCollection = {'string1','string2',...,'stringN'} diff --git a/Task/Search-a-list/MATLAB/search-a-list-2.m b/Task/Search-a-list/MATLAB/search-a-list-2.m new file mode 100644 index 0000000000..e953e4d30a --- /dev/null +++ b/Task/Search-a-list/MATLAB/search-a-list-2.m @@ -0,0 +1 @@ +stringCollection = {{'string1'},{'string2'},{...},{'stringN'}} diff --git a/Task/Search-a-list/MATLAB/search-a-list-3.m b/Task/Search-a-list/MATLAB/search-a-list-3.m new file mode 100644 index 0000000000..9700163887 --- /dev/null +++ b/Task/Search-a-list/MATLAB/search-a-list-3.m @@ -0,0 +1,13 @@ +function index = searchCollection(list,searchItem,firstLast) + + %firstLast is a string containing either 'first' or 'last'. The 'first' + %flag will cause searchCollection to return the index of the first + %instance of the item being searched. 'last' will cause + %searchCollection to return the index of the last instance of the item + %being searched. + + indicies = cellfun(@(x)x==searchItem,list); + index = find(indicies,1,firstLast); + assert(~isempty(index),['The string ''' searchItem ''' does not exist in this collection of strings.']); + +end diff --git a/Task/Search-a-list/MATLAB/search-a-list-4.m b/Task/Search-a-list/MATLAB/search-a-list-4.m new file mode 100644 index 0000000000..5c335f1855 --- /dev/null +++ b/Task/Search-a-list/MATLAB/search-a-list-4.m @@ -0,0 +1,16 @@ +>> list = {'a','b','c','d','e','c','f','c'}; +>> searchCollection(list,'c','first') + +ans = + + 3 + +>> searchCollection(list,'c','last') + +ans = + + 8 + +>> searchCollection(list,'g','last') +??? Error using ==> searchCollection at 11 +The string 'g' does not exist in this collection of strings.