From e54adb14a6b05fa67ee73e10b74ecd665024ab61 Mon Sep 17 00:00:00 2001 From: Henrik Wall Date: Tue, 20 Mar 2018 02:58:43 +0100 Subject: [PATCH] Added solutions --- 2-plus-2-star-2-problem/README.md | 14 + .../java/1/TwoPlusTwoTimesTwoProblem.java | 6 + .../java/2/TwoPlusTwoTimesTwoProblem.java | 6 + .../java/3/TwoPlusTwoTimesTwoProblem.java | 6 + 254-shades-of-grey/README.md | 59 + .../csharp/1/254-shades-of-grey | 20 + .../csharp/2/254-shades-of-grey | 14 + 254-shades-of-grey/java/1/ShadesOfGrey.java | 11 + LICENSE | 7 + .../README.md | 38 + ...-to-display-mottos-for-westerosi-houses.js | 22 + a-needle-in-the-haystack/README.md | 51 + a-needle-in-the-haystack/java/1/Kata.java | 9 + a-plus-b/README.md | 10 + a-plus-b/java/1/FirstClass.java | 5 + addition-function-problem/README.md | 11 + .../javascript/1/addition-function-problem.js | 3 + are-the-brackets-balanced/README.md | 12 + .../java/1/BrakedBalance.java | 29 + .../java/2/BrakedBalance.java | 29 + are-the-numbers-in-order/README.md | 46 + .../javascript/1/are-the-numbers-in-order.js | 8 + are-they-the-same/README.md | 47 + are-they-the-same/java/1/AreSame.java | 7 + .../javascript/1/are-they-the-same.js | 23 + are-you-playing-banjo/README.md | 18 + are-you-playing-banjo/java/1/Banjo.java | 10 + are-you-playing-banjo/java/2/Banjo.java | 9 + area-of-a-circle/README.md | 57 + area-of-a-circle/java/1/Circle.java | 10 + arithmetic-sequence/README.md | 27 + arithmetic-sequence/java/1/Sequence.java | 7 + bagels/README.md | 42 + basic-js-calculating-averages/README.md | 19 + .../1/basic-js-calculating-averages.js | 11 + basic-subclasses-adam-and-eve/README.md | 15 + basic-subclasses-adam-and-eve/java/1/God.java | 11 + batman-quotes/README.md | 31 + batman-quotes/java/1/BatmanQuotes.java | 27 + beginner-friendly-lowercase-letters/README.md | 12 + .../1/beginner-friendly-lowercase-letters.js | 3 + binary-addition/README.md | 13 + .../javascript/1/binary-addition.js | 3 + binary-calculator/README.md | 26 + .../java/1/BinaryCalculator.java | 27 + binding-within-the-list-monad/README.md | 80 + .../java/1/Binder.java | 12 + .../java/2/Binder.java | 9 + bit-counting/README.md | 12 + bit-counting/java/1/BitCounting.java | 8 + bit-counting/javascript/1/bit-counting.js | 4 + bit-counting/javascript/2/bit-counting.js | 1 + breaking-chocolate-problem/README.md | 16 + .../java/1/Chocolate.java | 5 + broken-counter/README.md | 14 + broken-counter/javascript/1/broken-counter.js | 15 + caffeine-script/README.md | 61 + caffeine-script/java/1/CaffeineBuzz.java | 12 + calculate-average/README.md | 14 + calculate-average/java/1/Kata.java | 5 + calculate-average/java/2/Kata.java | 7 + .../javascript/1/calculate-average.js | 3 + .../README.md | 40 + ...n-f-x-for-a-simple-linear-sequence-easy.js | 15 + .../README.md | 51 + ...f-x-for-a-simple-linear-sequence-medium.js | 12 + camelcasing/README.md | 15 + camelcasing/java/1/CamelCase.java | 14 + can-you-get-the-loop/README.md | 65 + .../java/1/LoopInspector.java | 16 + candy-problem/README.md | 69 + candy-problem/csharp/1/candy-problem | 19 + candy-problem/csharp/2/candy-problem | 10 + car-depreciation/README.md | 18 + .../javascript/1/car-depreciation.js | 10 + check-digit-1/README.md | 46 + check-digit-1/javascript/1/check-digit-1.js | 12 + checking-groups/README.md | 31 + checking-groups/java/1/Groups.java | 42 + circularly-sorted-array/README.md | 49 + .../java/1/CircleSorted.java | 16 + .../javascript/1/circularly-sorted-array.js | 12 + clock-angle-problem/README.md | 43 + clock-angle-problem/java/1/ClockProblem.java | 8 + clock-angle-problem/java/2/ClockProblem.java | 8 + codewars-style-ranking-system/README.md | 104 ++ .../java/1/User.java | 89 + collatz-conjecture-length/README.md | 18 + collatz-conjecture-length/java/1/Collatz.java | 9 + collatz-conjecture-length/java/2/Collatz.java | 5 + color-ghost/README.md | 42 + color-ghost/java/1/Ghost.java | 13 + common-denominators/README.md | 62 + common-denominators/java/1/Fracts.java | 21 + common-denominators/java/2/Fracts.java | 18 + complementary-dna/README.md | 72 + complementary-dna/java/1/DnaStrand.java | 9 + .../README.md | 40 + ...onversion-between-kilobyte-and-kibibyte.js | 15 + convert-a-boolean-to-a-string/README.md | 19 + .../java/1/BooleanToString.java | 9 + convert-a-linked-list-to-a-string/README.md | 322 ++++ .../java/1/Kata.java | 7 + .../1/convert-a-linked-list-to-a-string.js | 3 + convert-a-number-to-a-string/README.md | 45 + .../1/convert-a-number-to-a-string.js | 3 + convert-a-string-to-a-number/README.md | 87 + .../java/1/StringToNumber.java | 5 + .../README.md | 24 + .../java/1/Kata.java | 10 + ...vert-number-to-reversed-array-of-digits.js | 3 + convert-time-to-string/README.md | 29 + convert-time-to-string/java/1/TimeUtils.java | 17 + coordinates-validator/README.md | 38 + .../javascript/1/coordinates-validator.js | 4 + counting-power-sets/README.md | 57 + counting-power-sets/java/1/Powers.java | 7 + credit-card-mask/README.md | 87 + credit-card-mask/csharp/1/credit-card-mask | 12 + decode-the-morse-code-advanced/README.md | 45 + .../java/1/MorseCodeDecoder.java | 186 ++ .../java/2/MorseCodeDecoder.java | 174 ++ .../java/3/MorseCodeDecoder.java | 175 ++ .../java/4/MorseCodeDecoder.java | 135 ++ decode-the-morse-code/README.md | 82 + .../java/1/MorseCodeDecoder.java | 23 + .../java/2/MorseCodeDecoder.java | 21 + deep-comparison-of-objects/README.md | 22 + .../1/deep-comparison-of-objects.js | 34 + delta-bits/README.md | 19 + delta-bits/java/1/DeltaBits.java | 15 + delta-bits/javascript/1/delta-bits.js | 7 + deodorant-evaporator/README.md | 22 + deodorant-evaporator/java/1/Evaporator.java | 9 + descending-order/README.md | 22 + descending-order/java/1/DescendingOrder.java | 43 + .../javascript/1/descending-order.js | 8 + .../javascript/2/descending-order.js | 8 + .../javascript/3/descending-order.js | 48 + .../README.md | 75 + ...a-simple-automaton-finite-state-machine.js | 55 + deutschstunde/README.md | 18 + deutschstunde/javascript/1/deutschstunde.js | 20 + deutschstunde/javascript/2/deutschstunde.js | 3 + directions-reduction/README.md | 108 ++ directions-reduction/java/1/DirReduction.java | 24 + .../javascript/1/directions-reduction.js | 17 + discover-the-original-price/README.md | 21 + .../csharp/1/discover-the-original-price | 9 + .../1/discover-the-original-price.js | 3 + disemvowel-trolls/README.md | 22 + .../javascript/1/disemvowel-trolls.js | 3 + dna-to-rna-conversion/README.md | 41 + .../javascript/1/dna-to-rna-conversion.js | 3 + dont-rely-on-luck/README.md | 31 + .../javascript/1/dont-rely-on-luck.js | 4 + .../javascript/2/dont-rely-on-luck.js | 1 + .../javascript/3/dont-rely-on-luck.js | 2 + double-cola/README.md | 64 + double-cola/java/1/Line.java | 15 + dubstep/README.md | 48 + dubstep/java/1/Dubstep.java | 6 + duplicate-encoder/README.md | 25 + .../java/1/DuplicateEncoder.java | 12 + email-validation-1/README.md | 23 + .../javascript/1/email-validation-1.js | 4 + even-or-odd/README.md | 24 + even-or-odd/java/1/EvenOrOdd.java | 14 + everyone-has-his-little-secrets/README.md | 14 + .../java/1/Guesser.java | 12 + exes-and-ohs/README.md | 19 + exes-and-ohs/javascript/1/exes-and-ohs.js | 16 + feynmans-square-question/README.md | 62 + .../javascript/1/feynmans-square-question.js | 5 + .../javascript/2/feynmans-square-question.js | 1 + .../README.md | 57 + .../java/1/Kata.java | 11 + ...nd-maximum-and-minimum-values-of-a-list.js | 8 + find-nth-digit-of-a-number/README.md | 27 + .../1/find-nth-digit-of-a-number.js | 1 + find-something-in-an-array/README.md | 33 + .../1/find-something-in-an-array.js | 3 + find-the-capitals-1/README.md | 31 + .../csharp/1/find-the-capitals-1 | 17 + .../csharp/2/find-the-capitals-1 | 16 + .../javascript/1/find-the-capitals-1.js | 10 + find-the-middle-element/README.md | 24 + .../javascript/1/find-the-middle-element.js | 8 + find-the-mine/README.md | 19 + find-the-mine/javascript/1/find-the-mine.js | 8 + find-the-missing-letter/README.md | 27 + .../javascript/1/find-the-missing-letter.js | 8 + find-the-odd-int/README.md | 13 + find-the-odd-int/java/1/FindOdd.java | 27 + find-the-parity-outlier/README.md | 20 + .../java/1/FindOutlier.java | 21 + find-the-remainder/README.md | 10 + .../javascript/1/find-the-remainder.js | 3 + find-the-unknown-digit/README.md | 28 + find-the-unknown-digit/java/1/Runes.java | 157 ++ find-your-villain-name/README.md | 46 + .../javascript/1/find-your-villain-name.js | 9 + finding-neo-pg-13/README.md | 32 + finding-neo-pg-13/java/1/Morpheus.java | 17 + finding-neo-pg-13/java/2/Morpheus.java | 35 + fix-me/README.md | 12 + fix-me/javascript/1/fix-me.js | 13 + friend-or-foe/README.md | 16 + friend-or-foe/javascript/1/friend-or-foe.js | 3 + function-1-hello-world/README.md | 14 + function-1-hello-world/java/1/HelloWorld.java | 156 ++ function-1-hello-world/java/2/HelloWorld.java | 193 ++ get-key-slash-value-pairs-as-arrays/README.md | 23 + .../1/get-key-slash-value-pairs-as-arrays.js | 5 + get-the-middle-character/README.md | 45 + .../javascript/1/get-the-middle-character.js | 4 + give-me-a-diamond/README.md | 27 + give-me-a-diamond/java/1/Diamond.java | 51 + greatest-common-divisor-bitcount/README.md | 20 + .../java/1/BinaryGCD.java | 9 + greeting-my-friends/README.md | 35 + .../java/1/GreetingsMyFriends.java | 17 + guess-the-number-1/README.md | 31 + .../java/1/GuesserSolution.java | 46 + .../javascript/1/guess-the-number-1.js | 16 + herding-cats/README.md | 37 + herding-cats/java/1/CatWeightComparator.java | 10 + hidden-cubic-numbers/README.md | 39 + hidden-cubic-numbers/java/1/Cubes.java | 44 + highest-and-lowest/README.md | 63 + .../csharp/1/highest-and-lowest | 17 + highest-and-lowest/java/1/Kata.java | 12 + how-many-are-smaller-than-me/README.md | 48 + .../1/how-many-are-smaller-than-me.js | 8 + html-generator/README.md | 50 + html-generator/javascript/1/html-generator.js | 15 + human-readable-time/README.md | 18 + .../java/1/HumanReadableTime.java | 12 + .../javascript/1/human-readable-time.js | 11 + int32-to-ipv4/README.md | 37 + int32-to-ipv4/javascript/1/int32-to-ipv4.js | 6 + is-integer-array/README.md | 19 + .../javascript/1/is-integer-array.js | 12 + isograms/README.md | 32 + isograms/javascript/1/isograms.js | 4 + jaden-casing-strings/README.md | 20 + jaden-casing-strings/java/1/JadenCase.java | 23 + .../README.md | 45 + .../java/1/FunctionalProgramming.java | 6 + .../README.md | 62 + .../java/1/FunctionalProgramming.java | 8 + .../README.md | 63 + .../java/1/AdderFactory.java | 7 + jennys-secret-message/README.md | 12 + jennys-secret-message/java/1/Greeter.java | 5 + kata-example-twist/README.md | 42 + .../java/1/KataExampleTwist.java | 9 + .../java/2/KataExampleTwist.java | 7 + .../java/3/KataExampleTwist.java | 5 + l3375p34k/README.md | 34 + l3375p34k/java/1/Leetspeak.java | 25 + .../README.md | 42 + ...argest-difference-in-increasing-indexes.js | 8 + .../README.md | 45 + .../1/make-a-function-that-does-arithmetic.js | 9 + make-them-bark/README.md | 62 + make-them-bark/javascript/1/make-them-bark.js | 1 + manipulate-url-parameters/README.md | 29 + math-issues/README.md | 16 + math-issues/javascript/1/math-issues.js | 12 + maximum-subarray-sum/README.md | 35 + maximum-subarray-sum/java/1/Max.java | 11 + milk-and-cookies-for-santa/README.md | 29 + .../1/milk-and-cookies-for-santa.js | 3 + mod4-regex/README.md | 35 + mod4-regex/java/1/Mod.java | 5 + mod4-regex/java/2/Mod.java | 5 + monty-hall-problem/README.md | 16 + monty-hall-problem/java/1/MontyHall.java | 7 + monty-hall-problem/java/2/MontyHall.java | 7 + .../README.md | 49 + .../java/1/Keypad.java | 25 + .../java/2/Keypad.java | 28 + multiple-remainder-of-the-division/README.md | 29 + multiples-of-3-or-5/README.md | 17 + multiples-of-3-or-5/java/1/Solution.java | 22 + .../javascript/1/multiples-of-3-or-5.js | 6 + multiplication-table-for-number/README.md | 27 + .../1/multiplication-table-for-number.js | 3 + multiply/README.md | 10 + mumbling/README.md | 100 + mumbling/java/1/Accumul.java | 20 + mumbling/javascript/1/mumbling.js | 3 + .../README.md | 33 + .../java/1/BrainLuck.java | 132 ++ .../java/2/BrainLuck.java | 149 ++ name-array-capping/README.md | 32 + .../README.md | 61 + ...next-bigger-number-with-the-same-digits.js | 27 + number-of-trailing-zeros-of-n/README.md | 29 + .../java/1/Solution.java | 17 + number-tostring/README.md | 38 + ones-and-zeros/README.md | 26 + .../java/1/BinaryArrayToNumber.java | 13 + .../java/2/BinaryArrayToNumber.java | 8 + overflowing-with-joy/README.md | 12 + overflowing-with-joy/java/1/Multiplier.java | 5 + overflowing-with-longing/README.md | 12 + .../java/1/Multiplier.java | 5 + paginationhelper/README.md | 115 ++ paginationhelper/java/1/PaginationHelper.java | 43 + palindrome-checker/README.md | 16 + .../java/1/PalindromChecker.java | 9 + .../java/2/PalindromChecker.java | 30 + parse-a-linked-list-from-a-string/README.md | 301 +++ .../1/parse-a-linked-list-from-a-string.js | 9 + .../README.md | 23 + ...vil-programming-government-restrictions.js | 6 + partial-word-searching/README.md | 19 + partial-word-searching/java/1/WordSearch.java | 23 + permutations/README.md | 41 + permutations/javascript/1/permutations.js | 14 + pluck/README.md | 16 + pluck/javascript/1/pluck.js | 8 + plural/README.md | 15 + plural/javascript/1/plural.js | 3 + power-of-two/README.md | 42 + power-of-two/javascript/1/power-of-two.js | 3 + precise-fractions-pt-1-basics/README.md | 31 + .../java/1/Fraction.java | 80 + prime-factorization/README.md | 45 + .../java/1/PrimeFactorizer.java | 24 + .../java/2/PrimeFactorizer.java | 26 + .../java/3/PrimeFactorizer.java | 27 + prime-number-decompositions/README.md | 40 + .../java/1/PrimeNumberDecomposer.java | 51 + prime-streaming-pg-13/README.md | 12 + prime-streaming-pg-13/java/1/Primes.java | 36 + primes-in-numbers/README.md | 19 + primes-in-numbers/java/1/PrimeDecomp.java | 41 + primes-in-numbers/python/1/primes-in-numbers | 44 + psychic/README.md | 18 + psychic/java/1/Psychic.java | 30 + re-open-class/README.md | 27 + re-open-class/javascript/1/re-open-class.js | 3 + .../README.md | 16 + .../java/1/SecretDetective.java | 43 + ...er-a-secret-string-from-random-triplets.js | 39 + rectangle-into-squares/README.md | 147 ++ rectangle-into-squares/java/1/SqInRect.java | 19 + recursive-reverse-string/README.md | 49 + recursive-reverse-string/java/1/Reverse.java | 7 + recursive-reverse-string/java/2/Reverse.java | 8 + remove-duplicates/README.md | 65 + remove-duplicates/java/1/UniqueArray.java | 7 + remove-first-and-last-character/README.md | 10 + .../1/remove-first-and-last-character.js | 3 + remove-string-spaces/README.md | 10 + remove-string-spaces/java/1/Kata.java | 5 + .../javascript/1/remove-string-spaces.js | 3 + remove-zeros/README.md | 22 + remove-zeros/javascript/1/remove-zeros.js | 17 + replace-with-alphabet-position/README.md | 30 + .../1/replace-with-alphabet-position.js | 5 + return-the-missing-element/README.md | 28 + .../csharp/1/return-the-missing-element | 9 + reverse-polish-notation-calculator/README.md | 20 + .../java/1/Calc.java | 39 + rock-paper-scissors/README.md | 22 + .../javascript/1/rock-paper-scissors.js | 11 + rotate-array/README.md | 51 + rotate-array/java/1/Rotator.java | 11 + semi-optional/README.md | 25 + semi-optional/javascript/1/semi-optional.js | 1 + sentence-smash/README.md | 60 + sentence-smash/java/1/SmashWords.java | 5 + sequencesum/README.md | 39 + sequencesum/java/1/SequenceSum.java | 10 + shorter-concat-reverse-longer/README.md | 16 + .../java/1/ReverseLonger.java | 14 + shortest-word/README.md | 13 + shortest-word/java/1/Kata.java | 7 + shortest-word/javascript/1/shortest-word.js | 3 + sillycase/README.md | 21 + sillycase/javascript/1/sillycase.js | 4 + simple-card-game/README.md | 54 + simple-card-game/java/1/Game.java | 38 + .../README.md | 68 + ...e-encryption-number-1-alternating-split.js | 31 + simple-events/README.md | 26 + simple-events/javascript/1/simple-events.js | 14 + simple-string-expansion/README.md | 22 + .../javascript/1/simple-string-expansion.js | 15 + simple-string-reversal/README.md | 23 + .../javascript/1/simple-string-reversal.js | 17 + skrzat/README.md | 78 + skrzat/javascript/1/skrzat.js | 45 + smallest-value-of-an-array/README.md | 27 + smallest-value-of-an-array/java/1/Arrays.java | 21 + sort-array-by-string-length/README.md | 20 + .../1/sort-array-by-string-length.js | 3 + .../2/sort-array-by-string-length.js | 7 + sort-by-example/README.md | 23 + .../javascript/1/sort-by-example.js | 1 + sort-the-gift-code/README.md | 50 + sort-the-gift-code/java/1/GiftSorter.java | 9 + sort-the-odd/README.md | 34 + sort-the-odd/javascript/1/sort-the-odd.js | 15 + split-an-array/README.md | 28 + split-an-array/javascript/1/split-an-array.js | 8 + square-every-digit/README.md | 15 + square-every-digit/java/1/SquareDigit.java | 12 + stop-gninnips-my-sdrow/README.md | 17 + stop-gninnips-my-sdrow/java/1/SpinWords.java | 21 + stop-gninnips-my-sdrow/java/2/SpinWords.java | 22 + string-anagram-checker/README.md | 14 + .../java/1/AnagramChecker.java | 14 + string-searching-with-wildcard/README.md | 41 + .../java/1/SearchEngine.java | 16 + .../java/2/SearchEngine.java | 13 + .../1/string-searching-with-wildcard.js | 18 + strings-mix/README.md | 60 + strings-mix/java/1/Mixing.java | 74 + strings-strings-strings-easy/README.md | 76 + .../1/strings-strings-strings-easy.js | 13 + sum-by-factors/README.md | 79 + sum-by-factors/java/1/SumOfDivided.java | 32 + sum-of-angles/README.md | 10 + sum-of-angles/javascript/1/sum-of-angles.js | 3 + sum-of-digits-slash-digital-root/README.md | 42 + .../java/1/DRoot.java | 21 + sum-of-two-lowest-positive-integers/README.md | 17 + .../1/sum-of-two-lowest-positive-integers.js | 5 + sum-strings-as-numbers/README.md | 17 + .../javascript/1/sum-strings-as-numbers.js | 1624 +++++++++++++++++ summing-a-numbers-digits/README.md | 39 + .../javascript/1/summing-a-numbers-digits.js | 7 + take-a-ten-minute-walk/README.md | 15 + take-a-ten-minute-walk/java/1/TenMinWalk.java | 29 + tea-for-two/README.md | 22 + tea-for-two/javascript/1/tea-for-two.js | 3 + testing-1-2-3/README.md | 42 + testing-1-2-3/java/1/LineNumbering.java | 12 + testing-1-2-3/javascript/1/testing-1-2-3.js | 1 + the-hashtag-generator/README.md | 24 + .../javascript/1/the-hashtag-generator.js | 7 + the-look-and-say-sequence/README.md | 37 + .../javascript/1/the-look-and-say-sequence.js | 13 + the-millionth-fibonacci-kata/README.md | 38 + .../java/1/Fibonacci.java | 25 + the-prediction/README.md | 10 + the-prediction/javascript/1/the-prediction.js | 4 + this-is-a-problem/README.md | 46 + this-is-a-problem/java/1/NameMe.java | 23 + .../javascript/1/this-is-a-problem.js | 5 + threaded-counting/README.md | 24 + .../java/1/ThreadedCounting.java | 45 + toleetspeak/README.md | 53 + toleetspeak/javascript/1/toleetspeak.js | 32 + triangular-treasure/README.md | 58 + .../javascript/1/triangular-treasure.js | 5 + tug-o-war/README.md | 69 + tug-o-war/java/1/TugOWar.java | 23 + tug-o-war/javascript/1/tug-o-war.js | 18 + two-to-one/README.md | 22 + two-to-one/javascript/1/two-to-one.js | 3 + type-of-sum/README.md | 10 + type-of-sum/javascript/1/type-of-sum.js | 3 + undo-slash-redo/README.md | 31 + .../javascript/1/undo-slash-redo.js | 74 + unique-in-order/README.md | 36 + .../javascript/1/unique-in-order.js | 4 + uribuilder/README.md | 59 + uribuilder/javascript/1/uribuilder.js | 32 + valid-braces/README.md | 29 + valid-braces/javascript/1/valid-braces.js | 12 + valid-parentheses/README.md | 31 + .../javascript/1/valid-parentheses.js | 11 + valid-phone-number/README.md | 20 + valid-phone-number/java/1/Kata.java | 6 + .../javascript/1/valid-phone-number.js | 3 + vasya-clerk/README.md | 53 + vasya-clerk/java/1/Line.java | 37 + vector-class/README.md | 53 + vector-class/javascript/1/vector-class.js | 61 + vowel-count/README.md | 14 + vowel-count/java/1/Vowels.java | 13 + well-of-ideas-easy-version/README.md | 12 + .../1/well-of-ideas-easy-version.js | 11 + well-of-ideas-harder-version/README.md | 16 + .../1/well-of-ideas-harder-version.js | 16 + whats-a-perfect-power-anyway/README.md | 60 + .../java/1/PerfectPower.java | 55 + which-are-in/README.md | 31 + which-are-in/java/1/WhichAreIn.java | 7 + who-won-the-election/README.md | 78 + .../java/1/BallotsCounter.java | 16 + wind-component-calculation/README.md | 40 + .../java/1/WindInfo.java | 9 + wise-drunk-man/README.md | 11 + wise-drunk-man/javascript/1/wise-drunk-man.js | 3 + without-the-letter-e/README.md | 22 + .../javascript/1/without-the-letter-e.js | 9 + word-a10n-abbreviation/README.md | 30 + .../java/1/Abbreviator.java | 16 + .../javascript/1/word-a10n-abbreviation.js | 6 + .../javascript/2/word-a10n-abbreviation.js | 8 + word-finder/README.md | 38 + word-finder/javascript/1/word-finder.js | 10 + .../README.md | 10 + .../java/1/Java.java | 6 + .../you-cant-code-under-pressure-number-1.js | 3 + youre-a-square/README.md | 93 + youre-a-square/java/1/Square.java | 5 + 514 files changed, 15765 insertions(+) create mode 100644 2-plus-2-star-2-problem/README.md create mode 100644 2-plus-2-star-2-problem/java/1/TwoPlusTwoTimesTwoProblem.java create mode 100644 2-plus-2-star-2-problem/java/2/TwoPlusTwoTimesTwoProblem.java create mode 100644 2-plus-2-star-2-problem/java/3/TwoPlusTwoTimesTwoProblem.java create mode 100644 254-shades-of-grey/README.md create mode 100644 254-shades-of-grey/csharp/1/254-shades-of-grey create mode 100644 254-shades-of-grey/csharp/2/254-shades-of-grey create mode 100644 254-shades-of-grey/java/1/ShadesOfGrey.java create mode 100644 LICENSE create mode 100644 a-function-to-display-mottos-for-westerosi-houses/README.md create mode 100644 a-function-to-display-mottos-for-westerosi-houses/javascript/1/a-function-to-display-mottos-for-westerosi-houses.js create mode 100644 a-needle-in-the-haystack/README.md create mode 100644 a-needle-in-the-haystack/java/1/Kata.java create mode 100644 a-plus-b/README.md create mode 100644 a-plus-b/java/1/FirstClass.java create mode 100644 addition-function-problem/README.md create mode 100644 addition-function-problem/javascript/1/addition-function-problem.js create mode 100644 are-the-brackets-balanced/README.md create mode 100644 are-the-brackets-balanced/java/1/BrakedBalance.java create mode 100644 are-the-brackets-balanced/java/2/BrakedBalance.java create mode 100644 are-the-numbers-in-order/README.md create mode 100644 are-the-numbers-in-order/javascript/1/are-the-numbers-in-order.js create mode 100644 are-they-the-same/README.md create mode 100644 are-they-the-same/java/1/AreSame.java create mode 100644 are-they-the-same/javascript/1/are-they-the-same.js create mode 100644 are-you-playing-banjo/README.md create mode 100644 are-you-playing-banjo/java/1/Banjo.java create mode 100644 are-you-playing-banjo/java/2/Banjo.java create mode 100644 area-of-a-circle/README.md create mode 100644 area-of-a-circle/java/1/Circle.java create mode 100644 arithmetic-sequence/README.md create mode 100644 arithmetic-sequence/java/1/Sequence.java create mode 100644 bagels/README.md create mode 100644 basic-js-calculating-averages/README.md create mode 100644 basic-js-calculating-averages/javascript/1/basic-js-calculating-averages.js create mode 100644 basic-subclasses-adam-and-eve/README.md create mode 100644 basic-subclasses-adam-and-eve/java/1/God.java create mode 100644 batman-quotes/README.md create mode 100644 batman-quotes/java/1/BatmanQuotes.java create mode 100644 beginner-friendly-lowercase-letters/README.md create mode 100644 beginner-friendly-lowercase-letters/javascript/1/beginner-friendly-lowercase-letters.js create mode 100644 binary-addition/README.md create mode 100644 binary-addition/javascript/1/binary-addition.js create mode 100644 binary-calculator/README.md create mode 100644 binary-calculator/java/1/BinaryCalculator.java create mode 100644 binding-within-the-list-monad/README.md create mode 100644 binding-within-the-list-monad/java/1/Binder.java create mode 100644 binding-within-the-list-monad/java/2/Binder.java create mode 100644 bit-counting/README.md create mode 100644 bit-counting/java/1/BitCounting.java create mode 100644 bit-counting/javascript/1/bit-counting.js create mode 100644 bit-counting/javascript/2/bit-counting.js create mode 100644 breaking-chocolate-problem/README.md create mode 100644 breaking-chocolate-problem/java/1/Chocolate.java create mode 100644 broken-counter/README.md create mode 100644 broken-counter/javascript/1/broken-counter.js create mode 100644 caffeine-script/README.md create mode 100644 caffeine-script/java/1/CaffeineBuzz.java create mode 100644 calculate-average/README.md create mode 100644 calculate-average/java/1/Kata.java create mode 100644 calculate-average/java/2/Kata.java create mode 100644 calculate-average/javascript/1/calculate-average.js create mode 100644 calculate-the-function-f-x-for-a-simple-linear-sequence-easy/README.md create mode 100644 calculate-the-function-f-x-for-a-simple-linear-sequence-easy/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-easy.js create mode 100644 calculate-the-function-f-x-for-a-simple-linear-sequence-medium/README.md create mode 100644 calculate-the-function-f-x-for-a-simple-linear-sequence-medium/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-medium.js create mode 100644 camelcasing/README.md create mode 100644 camelcasing/java/1/CamelCase.java create mode 100644 can-you-get-the-loop/README.md create mode 100644 can-you-get-the-loop/java/1/LoopInspector.java create mode 100644 candy-problem/README.md create mode 100644 candy-problem/csharp/1/candy-problem create mode 100644 candy-problem/csharp/2/candy-problem create mode 100644 car-depreciation/README.md create mode 100644 car-depreciation/javascript/1/car-depreciation.js create mode 100644 check-digit-1/README.md create mode 100644 check-digit-1/javascript/1/check-digit-1.js create mode 100644 checking-groups/README.md create mode 100644 checking-groups/java/1/Groups.java create mode 100644 circularly-sorted-array/README.md create mode 100644 circularly-sorted-array/java/1/CircleSorted.java create mode 100644 circularly-sorted-array/javascript/1/circularly-sorted-array.js create mode 100644 clock-angle-problem/README.md create mode 100644 clock-angle-problem/java/1/ClockProblem.java create mode 100644 clock-angle-problem/java/2/ClockProblem.java create mode 100644 codewars-style-ranking-system/README.md create mode 100644 codewars-style-ranking-system/java/1/User.java create mode 100644 collatz-conjecture-length/README.md create mode 100644 collatz-conjecture-length/java/1/Collatz.java create mode 100644 collatz-conjecture-length/java/2/Collatz.java create mode 100644 color-ghost/README.md create mode 100644 color-ghost/java/1/Ghost.java create mode 100644 common-denominators/README.md create mode 100644 common-denominators/java/1/Fracts.java create mode 100644 common-denominators/java/2/Fracts.java create mode 100644 complementary-dna/README.md create mode 100644 complementary-dna/java/1/DnaStrand.java create mode 100644 conversion-between-kilobyte-and-kibibyte/README.md create mode 100644 conversion-between-kilobyte-and-kibibyte/javascript/1/conversion-between-kilobyte-and-kibibyte.js create mode 100644 convert-a-boolean-to-a-string/README.md create mode 100644 convert-a-boolean-to-a-string/java/1/BooleanToString.java create mode 100644 convert-a-linked-list-to-a-string/README.md create mode 100644 convert-a-linked-list-to-a-string/java/1/Kata.java create mode 100644 convert-a-linked-list-to-a-string/javascript/1/convert-a-linked-list-to-a-string.js create mode 100644 convert-a-number-to-a-string/README.md create mode 100644 convert-a-number-to-a-string/javascript/1/convert-a-number-to-a-string.js create mode 100644 convert-a-string-to-a-number/README.md create mode 100644 convert-a-string-to-a-number/java/1/StringToNumber.java create mode 100644 convert-number-to-reversed-array-of-digits/README.md create mode 100644 convert-number-to-reversed-array-of-digits/java/1/Kata.java create mode 100644 convert-number-to-reversed-array-of-digits/javascript/1/convert-number-to-reversed-array-of-digits.js create mode 100644 convert-time-to-string/README.md create mode 100644 convert-time-to-string/java/1/TimeUtils.java create mode 100644 coordinates-validator/README.md create mode 100644 coordinates-validator/javascript/1/coordinates-validator.js create mode 100644 counting-power-sets/README.md create mode 100644 counting-power-sets/java/1/Powers.java create mode 100644 credit-card-mask/README.md create mode 100644 credit-card-mask/csharp/1/credit-card-mask create mode 100644 decode-the-morse-code-advanced/README.md create mode 100644 decode-the-morse-code-advanced/java/1/MorseCodeDecoder.java create mode 100644 decode-the-morse-code-advanced/java/2/MorseCodeDecoder.java create mode 100644 decode-the-morse-code-advanced/java/3/MorseCodeDecoder.java create mode 100644 decode-the-morse-code-advanced/java/4/MorseCodeDecoder.java create mode 100644 decode-the-morse-code/README.md create mode 100644 decode-the-morse-code/java/1/MorseCodeDecoder.java create mode 100644 decode-the-morse-code/java/2/MorseCodeDecoder.java create mode 100644 deep-comparison-of-objects/README.md create mode 100644 deep-comparison-of-objects/javascript/1/deep-comparison-of-objects.js create mode 100644 delta-bits/README.md create mode 100644 delta-bits/java/1/DeltaBits.java create mode 100644 delta-bits/javascript/1/delta-bits.js create mode 100644 deodorant-evaporator/README.md create mode 100644 deodorant-evaporator/java/1/Evaporator.java create mode 100644 descending-order/README.md create mode 100644 descending-order/java/1/DescendingOrder.java create mode 100644 descending-order/javascript/1/descending-order.js create mode 100644 descending-order/javascript/2/descending-order.js create mode 100644 descending-order/javascript/3/descending-order.js create mode 100644 design-a-simple-automaton-finite-state-machine/README.md create mode 100644 design-a-simple-automaton-finite-state-machine/javascript/1/design-a-simple-automaton-finite-state-machine.js create mode 100644 deutschstunde/README.md create mode 100644 deutschstunde/javascript/1/deutschstunde.js create mode 100644 deutschstunde/javascript/2/deutschstunde.js create mode 100644 directions-reduction/README.md create mode 100644 directions-reduction/java/1/DirReduction.java create mode 100644 directions-reduction/javascript/1/directions-reduction.js create mode 100644 discover-the-original-price/README.md create mode 100644 discover-the-original-price/csharp/1/discover-the-original-price create mode 100644 discover-the-original-price/javascript/1/discover-the-original-price.js create mode 100644 disemvowel-trolls/README.md create mode 100644 disemvowel-trolls/javascript/1/disemvowel-trolls.js create mode 100644 dna-to-rna-conversion/README.md create mode 100644 dna-to-rna-conversion/javascript/1/dna-to-rna-conversion.js create mode 100644 dont-rely-on-luck/README.md create mode 100644 dont-rely-on-luck/javascript/1/dont-rely-on-luck.js create mode 100644 dont-rely-on-luck/javascript/2/dont-rely-on-luck.js create mode 100644 dont-rely-on-luck/javascript/3/dont-rely-on-luck.js create mode 100644 double-cola/README.md create mode 100644 double-cola/java/1/Line.java create mode 100644 dubstep/README.md create mode 100644 dubstep/java/1/Dubstep.java create mode 100644 duplicate-encoder/README.md create mode 100644 duplicate-encoder/java/1/DuplicateEncoder.java create mode 100644 email-validation-1/README.md create mode 100644 email-validation-1/javascript/1/email-validation-1.js create mode 100644 even-or-odd/README.md create mode 100644 even-or-odd/java/1/EvenOrOdd.java create mode 100644 everyone-has-his-little-secrets/README.md create mode 100644 everyone-has-his-little-secrets/java/1/Guesser.java create mode 100644 exes-and-ohs/README.md create mode 100644 exes-and-ohs/javascript/1/exes-and-ohs.js create mode 100644 feynmans-square-question/README.md create mode 100644 feynmans-square-question/javascript/1/feynmans-square-question.js create mode 100644 feynmans-square-question/javascript/2/feynmans-square-question.js create mode 100644 find-maximum-and-minimum-values-of-a-list/README.md create mode 100644 find-maximum-and-minimum-values-of-a-list/java/1/Kata.java create mode 100644 find-maximum-and-minimum-values-of-a-list/javascript/1/find-maximum-and-minimum-values-of-a-list.js create mode 100644 find-nth-digit-of-a-number/README.md create mode 100644 find-nth-digit-of-a-number/javascript/1/find-nth-digit-of-a-number.js create mode 100644 find-something-in-an-array/README.md create mode 100644 find-something-in-an-array/javascript/1/find-something-in-an-array.js create mode 100644 find-the-capitals-1/README.md create mode 100644 find-the-capitals-1/csharp/1/find-the-capitals-1 create mode 100644 find-the-capitals-1/csharp/2/find-the-capitals-1 create mode 100644 find-the-capitals-1/javascript/1/find-the-capitals-1.js create mode 100644 find-the-middle-element/README.md create mode 100644 find-the-middle-element/javascript/1/find-the-middle-element.js create mode 100644 find-the-mine/README.md create mode 100644 find-the-mine/javascript/1/find-the-mine.js create mode 100644 find-the-missing-letter/README.md create mode 100644 find-the-missing-letter/javascript/1/find-the-missing-letter.js create mode 100644 find-the-odd-int/README.md create mode 100644 find-the-odd-int/java/1/FindOdd.java create mode 100644 find-the-parity-outlier/README.md create mode 100644 find-the-parity-outlier/java/1/FindOutlier.java create mode 100644 find-the-remainder/README.md create mode 100644 find-the-remainder/javascript/1/find-the-remainder.js create mode 100644 find-the-unknown-digit/README.md create mode 100644 find-the-unknown-digit/java/1/Runes.java create mode 100644 find-your-villain-name/README.md create mode 100644 find-your-villain-name/javascript/1/find-your-villain-name.js create mode 100644 finding-neo-pg-13/README.md create mode 100644 finding-neo-pg-13/java/1/Morpheus.java create mode 100644 finding-neo-pg-13/java/2/Morpheus.java create mode 100644 fix-me/README.md create mode 100644 fix-me/javascript/1/fix-me.js create mode 100644 friend-or-foe/README.md create mode 100644 friend-or-foe/javascript/1/friend-or-foe.js create mode 100644 function-1-hello-world/README.md create mode 100644 function-1-hello-world/java/1/HelloWorld.java create mode 100644 function-1-hello-world/java/2/HelloWorld.java create mode 100644 get-key-slash-value-pairs-as-arrays/README.md create mode 100644 get-key-slash-value-pairs-as-arrays/javascript/1/get-key-slash-value-pairs-as-arrays.js create mode 100644 get-the-middle-character/README.md create mode 100644 get-the-middle-character/javascript/1/get-the-middle-character.js create mode 100644 give-me-a-diamond/README.md create mode 100644 give-me-a-diamond/java/1/Diamond.java create mode 100644 greatest-common-divisor-bitcount/README.md create mode 100644 greatest-common-divisor-bitcount/java/1/BinaryGCD.java create mode 100644 greeting-my-friends/README.md create mode 100644 greeting-my-friends/java/1/GreetingsMyFriends.java create mode 100644 guess-the-number-1/README.md create mode 100644 guess-the-number-1/java/1/GuesserSolution.java create mode 100644 guess-the-number-1/javascript/1/guess-the-number-1.js create mode 100644 herding-cats/README.md create mode 100644 herding-cats/java/1/CatWeightComparator.java create mode 100644 hidden-cubic-numbers/README.md create mode 100644 hidden-cubic-numbers/java/1/Cubes.java create mode 100644 highest-and-lowest/README.md create mode 100644 highest-and-lowest/csharp/1/highest-and-lowest create mode 100644 highest-and-lowest/java/1/Kata.java create mode 100644 how-many-are-smaller-than-me/README.md create mode 100644 how-many-are-smaller-than-me/javascript/1/how-many-are-smaller-than-me.js create mode 100644 html-generator/README.md create mode 100644 html-generator/javascript/1/html-generator.js create mode 100644 human-readable-time/README.md create mode 100644 human-readable-time/java/1/HumanReadableTime.java create mode 100644 human-readable-time/javascript/1/human-readable-time.js create mode 100644 int32-to-ipv4/README.md create mode 100644 int32-to-ipv4/javascript/1/int32-to-ipv4.js create mode 100644 is-integer-array/README.md create mode 100644 is-integer-array/javascript/1/is-integer-array.js create mode 100644 isograms/README.md create mode 100644 isograms/javascript/1/isograms.js create mode 100644 jaden-casing-strings/README.md create mode 100644 jaden-casing-strings/java/1/JadenCase.java create mode 100644 java-functional-programming-part-1-the-beginning/README.md create mode 100644 java-functional-programming-part-1-the-beginning/java/1/FunctionalProgramming.java create mode 100644 java-functional-programming-part-2-multiline-functions/README.md create mode 100644 java-functional-programming-part-2-multiline-functions/java/1/FunctionalProgramming.java create mode 100644 java-functional-programming-part-3-closured-for-business/README.md create mode 100644 java-functional-programming-part-3-closured-for-business/java/1/AdderFactory.java create mode 100644 jennys-secret-message/README.md create mode 100644 jennys-secret-message/java/1/Greeter.java create mode 100644 kata-example-twist/README.md create mode 100644 kata-example-twist/java/1/KataExampleTwist.java create mode 100644 kata-example-twist/java/2/KataExampleTwist.java create mode 100644 kata-example-twist/java/3/KataExampleTwist.java create mode 100644 l3375p34k/README.md create mode 100644 l3375p34k/java/1/Leetspeak.java create mode 100644 largest-difference-in-increasing-indexes/README.md create mode 100644 largest-difference-in-increasing-indexes/javascript/1/largest-difference-in-increasing-indexes.js create mode 100644 make-a-function-that-does-arithmetic/README.md create mode 100644 make-a-function-that-does-arithmetic/javascript/1/make-a-function-that-does-arithmetic.js create mode 100644 make-them-bark/README.md create mode 100644 make-them-bark/javascript/1/make-them-bark.js create mode 100644 manipulate-url-parameters/README.md create mode 100644 math-issues/README.md create mode 100644 math-issues/javascript/1/math-issues.js create mode 100644 maximum-subarray-sum/README.md create mode 100644 maximum-subarray-sum/java/1/Max.java create mode 100644 milk-and-cookies-for-santa/README.md create mode 100644 milk-and-cookies-for-santa/javascript/1/milk-and-cookies-for-santa.js create mode 100644 mod4-regex/README.md create mode 100644 mod4-regex/java/1/Mod.java create mode 100644 mod4-regex/java/2/Mod.java create mode 100644 monty-hall-problem/README.md create mode 100644 monty-hall-problem/java/1/MontyHall.java create mode 100644 monty-hall-problem/java/2/MontyHall.java create mode 100644 multi-tap-keypad-text-entry-on-an-old-mobile-phone/README.md create mode 100644 multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/1/Keypad.java create mode 100644 multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/2/Keypad.java create mode 100644 multiple-remainder-of-the-division/README.md create mode 100644 multiples-of-3-or-5/README.md create mode 100644 multiples-of-3-or-5/java/1/Solution.java create mode 100644 multiples-of-3-or-5/javascript/1/multiples-of-3-or-5.js create mode 100644 multiplication-table-for-number/README.md create mode 100644 multiplication-table-for-number/javascript/1/multiplication-table-for-number.js create mode 100644 multiply/README.md create mode 100644 mumbling/README.md create mode 100644 mumbling/java/1/Accumul.java create mode 100644 mumbling/javascript/1/mumbling.js create mode 100644 my-smallest-code-interpreter-aka-brainf-star-star-k/README.md create mode 100644 my-smallest-code-interpreter-aka-brainf-star-star-k/java/1/BrainLuck.java create mode 100644 my-smallest-code-interpreter-aka-brainf-star-star-k/java/2/BrainLuck.java create mode 100644 name-array-capping/README.md create mode 100644 next-bigger-number-with-the-same-digits/README.md create mode 100644 next-bigger-number-with-the-same-digits/javascript/1/next-bigger-number-with-the-same-digits.js create mode 100644 number-of-trailing-zeros-of-n/README.md create mode 100644 number-of-trailing-zeros-of-n/java/1/Solution.java create mode 100644 number-tostring/README.md create mode 100644 ones-and-zeros/README.md create mode 100644 ones-and-zeros/java/1/BinaryArrayToNumber.java create mode 100644 ones-and-zeros/java/2/BinaryArrayToNumber.java create mode 100644 overflowing-with-joy/README.md create mode 100644 overflowing-with-joy/java/1/Multiplier.java create mode 100644 overflowing-with-longing/README.md create mode 100644 overflowing-with-longing/java/1/Multiplier.java create mode 100644 paginationhelper/README.md create mode 100644 paginationhelper/java/1/PaginationHelper.java create mode 100644 palindrome-checker/README.md create mode 100644 palindrome-checker/java/1/PalindromChecker.java create mode 100644 palindrome-checker/java/2/PalindromChecker.java create mode 100644 parse-a-linked-list-from-a-string/README.md create mode 100644 parse-a-linked-list-from-a-string/javascript/1/parse-a-linked-list-from-a-string.js create mode 100644 part-1-evil-programming-government-restrictions/README.md create mode 100644 part-1-evil-programming-government-restrictions/javascript/1/part-1-evil-programming-government-restrictions.js create mode 100644 partial-word-searching/README.md create mode 100644 partial-word-searching/java/1/WordSearch.java create mode 100644 permutations/README.md create mode 100644 permutations/javascript/1/permutations.js create mode 100644 pluck/README.md create mode 100644 pluck/javascript/1/pluck.js create mode 100644 plural/README.md create mode 100644 plural/javascript/1/plural.js create mode 100644 power-of-two/README.md create mode 100644 power-of-two/javascript/1/power-of-two.js create mode 100644 precise-fractions-pt-1-basics/README.md create mode 100644 precise-fractions-pt-1-basics/java/1/Fraction.java create mode 100644 prime-factorization/README.md create mode 100644 prime-factorization/java/1/PrimeFactorizer.java create mode 100644 prime-factorization/java/2/PrimeFactorizer.java create mode 100644 prime-factorization/java/3/PrimeFactorizer.java create mode 100644 prime-number-decompositions/README.md create mode 100644 prime-number-decompositions/java/1/PrimeNumberDecomposer.java create mode 100644 prime-streaming-pg-13/README.md create mode 100644 prime-streaming-pg-13/java/1/Primes.java create mode 100644 primes-in-numbers/README.md create mode 100644 primes-in-numbers/java/1/PrimeDecomp.java create mode 100644 primes-in-numbers/python/1/primes-in-numbers create mode 100644 psychic/README.md create mode 100644 psychic/java/1/Psychic.java create mode 100644 re-open-class/README.md create mode 100644 re-open-class/javascript/1/re-open-class.js create mode 100644 recover-a-secret-string-from-random-triplets/README.md create mode 100644 recover-a-secret-string-from-random-triplets/java/1/SecretDetective.java create mode 100644 recover-a-secret-string-from-random-triplets/javascript/1/recover-a-secret-string-from-random-triplets.js create mode 100644 rectangle-into-squares/README.md create mode 100644 rectangle-into-squares/java/1/SqInRect.java create mode 100644 recursive-reverse-string/README.md create mode 100644 recursive-reverse-string/java/1/Reverse.java create mode 100644 recursive-reverse-string/java/2/Reverse.java create mode 100644 remove-duplicates/README.md create mode 100644 remove-duplicates/java/1/UniqueArray.java create mode 100644 remove-first-and-last-character/README.md create mode 100644 remove-first-and-last-character/javascript/1/remove-first-and-last-character.js create mode 100644 remove-string-spaces/README.md create mode 100644 remove-string-spaces/java/1/Kata.java create mode 100644 remove-string-spaces/javascript/1/remove-string-spaces.js create mode 100644 remove-zeros/README.md create mode 100644 remove-zeros/javascript/1/remove-zeros.js create mode 100644 replace-with-alphabet-position/README.md create mode 100644 replace-with-alphabet-position/javascript/1/replace-with-alphabet-position.js create mode 100644 return-the-missing-element/README.md create mode 100644 return-the-missing-element/csharp/1/return-the-missing-element create mode 100644 reverse-polish-notation-calculator/README.md create mode 100644 reverse-polish-notation-calculator/java/1/Calc.java create mode 100644 rock-paper-scissors/README.md create mode 100644 rock-paper-scissors/javascript/1/rock-paper-scissors.js create mode 100644 rotate-array/README.md create mode 100644 rotate-array/java/1/Rotator.java create mode 100644 semi-optional/README.md create mode 100644 semi-optional/javascript/1/semi-optional.js create mode 100644 sentence-smash/README.md create mode 100644 sentence-smash/java/1/SmashWords.java create mode 100644 sequencesum/README.md create mode 100644 sequencesum/java/1/SequenceSum.java create mode 100644 shorter-concat-reverse-longer/README.md create mode 100644 shorter-concat-reverse-longer/java/1/ReverseLonger.java create mode 100644 shortest-word/README.md create mode 100644 shortest-word/java/1/Kata.java create mode 100644 shortest-word/javascript/1/shortest-word.js create mode 100644 sillycase/README.md create mode 100644 sillycase/javascript/1/sillycase.js create mode 100644 simple-card-game/README.md create mode 100644 simple-card-game/java/1/Game.java create mode 100644 simple-encryption-number-1-alternating-split/README.md create mode 100644 simple-encryption-number-1-alternating-split/javascript/1/simple-encryption-number-1-alternating-split.js create mode 100644 simple-events/README.md create mode 100644 simple-events/javascript/1/simple-events.js create mode 100644 simple-string-expansion/README.md create mode 100644 simple-string-expansion/javascript/1/simple-string-expansion.js create mode 100644 simple-string-reversal/README.md create mode 100644 simple-string-reversal/javascript/1/simple-string-reversal.js create mode 100644 skrzat/README.md create mode 100644 skrzat/javascript/1/skrzat.js create mode 100644 smallest-value-of-an-array/README.md create mode 100644 smallest-value-of-an-array/java/1/Arrays.java create mode 100644 sort-array-by-string-length/README.md create mode 100644 sort-array-by-string-length/javascript/1/sort-array-by-string-length.js create mode 100644 sort-array-by-string-length/javascript/2/sort-array-by-string-length.js create mode 100644 sort-by-example/README.md create mode 100644 sort-by-example/javascript/1/sort-by-example.js create mode 100644 sort-the-gift-code/README.md create mode 100644 sort-the-gift-code/java/1/GiftSorter.java create mode 100644 sort-the-odd/README.md create mode 100644 sort-the-odd/javascript/1/sort-the-odd.js create mode 100644 split-an-array/README.md create mode 100644 split-an-array/javascript/1/split-an-array.js create mode 100644 square-every-digit/README.md create mode 100644 square-every-digit/java/1/SquareDigit.java create mode 100644 stop-gninnips-my-sdrow/README.md create mode 100644 stop-gninnips-my-sdrow/java/1/SpinWords.java create mode 100644 stop-gninnips-my-sdrow/java/2/SpinWords.java create mode 100644 string-anagram-checker/README.md create mode 100644 string-anagram-checker/java/1/AnagramChecker.java create mode 100644 string-searching-with-wildcard/README.md create mode 100644 string-searching-with-wildcard/java/1/SearchEngine.java create mode 100644 string-searching-with-wildcard/java/2/SearchEngine.java create mode 100644 string-searching-with-wildcard/javascript/1/string-searching-with-wildcard.js create mode 100644 strings-mix/README.md create mode 100644 strings-mix/java/1/Mixing.java create mode 100644 strings-strings-strings-easy/README.md create mode 100644 strings-strings-strings-easy/javascript/1/strings-strings-strings-easy.js create mode 100644 sum-by-factors/README.md create mode 100644 sum-by-factors/java/1/SumOfDivided.java create mode 100644 sum-of-angles/README.md create mode 100644 sum-of-angles/javascript/1/sum-of-angles.js create mode 100644 sum-of-digits-slash-digital-root/README.md create mode 100644 sum-of-digits-slash-digital-root/java/1/DRoot.java create mode 100644 sum-of-two-lowest-positive-integers/README.md create mode 100644 sum-of-two-lowest-positive-integers/javascript/1/sum-of-two-lowest-positive-integers.js create mode 100644 sum-strings-as-numbers/README.md create mode 100644 sum-strings-as-numbers/javascript/1/sum-strings-as-numbers.js create mode 100644 summing-a-numbers-digits/README.md create mode 100644 summing-a-numbers-digits/javascript/1/summing-a-numbers-digits.js create mode 100644 take-a-ten-minute-walk/README.md create mode 100644 take-a-ten-minute-walk/java/1/TenMinWalk.java create mode 100644 tea-for-two/README.md create mode 100644 tea-for-two/javascript/1/tea-for-two.js create mode 100644 testing-1-2-3/README.md create mode 100644 testing-1-2-3/java/1/LineNumbering.java create mode 100644 testing-1-2-3/javascript/1/testing-1-2-3.js create mode 100644 the-hashtag-generator/README.md create mode 100644 the-hashtag-generator/javascript/1/the-hashtag-generator.js create mode 100644 the-look-and-say-sequence/README.md create mode 100644 the-look-and-say-sequence/javascript/1/the-look-and-say-sequence.js create mode 100644 the-millionth-fibonacci-kata/README.md create mode 100644 the-millionth-fibonacci-kata/java/1/Fibonacci.java create mode 100644 the-prediction/README.md create mode 100644 the-prediction/javascript/1/the-prediction.js create mode 100644 this-is-a-problem/README.md create mode 100644 this-is-a-problem/java/1/NameMe.java create mode 100644 this-is-a-problem/javascript/1/this-is-a-problem.js create mode 100644 threaded-counting/README.md create mode 100644 threaded-counting/java/1/ThreadedCounting.java create mode 100644 toleetspeak/README.md create mode 100644 toleetspeak/javascript/1/toleetspeak.js create mode 100644 triangular-treasure/README.md create mode 100644 triangular-treasure/javascript/1/triangular-treasure.js create mode 100644 tug-o-war/README.md create mode 100644 tug-o-war/java/1/TugOWar.java create mode 100644 tug-o-war/javascript/1/tug-o-war.js create mode 100644 two-to-one/README.md create mode 100644 two-to-one/javascript/1/two-to-one.js create mode 100644 type-of-sum/README.md create mode 100644 type-of-sum/javascript/1/type-of-sum.js create mode 100644 undo-slash-redo/README.md create mode 100644 undo-slash-redo/javascript/1/undo-slash-redo.js create mode 100644 unique-in-order/README.md create mode 100644 unique-in-order/javascript/1/unique-in-order.js create mode 100644 uribuilder/README.md create mode 100644 uribuilder/javascript/1/uribuilder.js create mode 100644 valid-braces/README.md create mode 100644 valid-braces/javascript/1/valid-braces.js create mode 100644 valid-parentheses/README.md create mode 100644 valid-parentheses/javascript/1/valid-parentheses.js create mode 100644 valid-phone-number/README.md create mode 100644 valid-phone-number/java/1/Kata.java create mode 100644 valid-phone-number/javascript/1/valid-phone-number.js create mode 100644 vasya-clerk/README.md create mode 100644 vasya-clerk/java/1/Line.java create mode 100644 vector-class/README.md create mode 100644 vector-class/javascript/1/vector-class.js create mode 100644 vowel-count/README.md create mode 100644 vowel-count/java/1/Vowels.java create mode 100644 well-of-ideas-easy-version/README.md create mode 100644 well-of-ideas-easy-version/javascript/1/well-of-ideas-easy-version.js create mode 100644 well-of-ideas-harder-version/README.md create mode 100644 well-of-ideas-harder-version/javascript/1/well-of-ideas-harder-version.js create mode 100644 whats-a-perfect-power-anyway/README.md create mode 100644 whats-a-perfect-power-anyway/java/1/PerfectPower.java create mode 100644 which-are-in/README.md create mode 100644 which-are-in/java/1/WhichAreIn.java create mode 100644 who-won-the-election/README.md create mode 100644 who-won-the-election/java/1/BallotsCounter.java create mode 100644 wind-component-calculation/README.md create mode 100644 wind-component-calculation/java/1/WindInfo.java create mode 100644 wise-drunk-man/README.md create mode 100644 wise-drunk-man/javascript/1/wise-drunk-man.js create mode 100644 without-the-letter-e/README.md create mode 100644 without-the-letter-e/javascript/1/without-the-letter-e.js create mode 100644 word-a10n-abbreviation/README.md create mode 100644 word-a10n-abbreviation/java/1/Abbreviator.java create mode 100644 word-a10n-abbreviation/javascript/1/word-a10n-abbreviation.js create mode 100644 word-a10n-abbreviation/javascript/2/word-a10n-abbreviation.js create mode 100644 word-finder/README.md create mode 100644 word-finder/javascript/1/word-finder.js create mode 100644 you-cant-code-under-pressure-number-1/README.md create mode 100644 you-cant-code-under-pressure-number-1/java/1/Java.java create mode 100644 you-cant-code-under-pressure-number-1/javascript/1/you-cant-code-under-pressure-number-1.js create mode 100644 youre-a-square/README.md create mode 100644 youre-a-square/java/1/Square.java diff --git a/2-plus-2-star-2-problem/README.md b/2-plus-2-star-2-problem/README.md new file mode 100644 index 0000000..03e77c6 --- /dev/null +++ b/2-plus-2-star-2-problem/README.md @@ -0,0 +1,14 @@ +# 2 + 2 * 2 problem +[*View on Codewars*](https://www.codewars.com/kata/2-plus-2-star-2-problem) + +Steve loves MS Windows calculator in Standard mode. + +He tries to calculate ``2 + 2 * 2`` in his favorite programming language. But Steve doesn't know about order of operations and he wonders why answers are different. He expects ``8`` but gets ``6``. + +Help Steve to fix program, so result will be identical to MS Windows calculator. + +## Timeline +- Created: 2014-05-18 +- Published: 2014-05-18 +- Approved: 2014-05-22 +- Completed: 2015-05-05 \ No newline at end of file diff --git a/2-plus-2-star-2-problem/java/1/TwoPlusTwoTimesTwoProblem.java b/2-plus-2-star-2-problem/java/1/TwoPlusTwoTimesTwoProblem.java new file mode 100644 index 0000000..abb6fa6 --- /dev/null +++ b/2-plus-2-star-2-problem/java/1/TwoPlusTwoTimesTwoProblem.java @@ -0,0 +1,6 @@ +public class TwoPlusTwoTimesTwoProblem { + + public static int calculate() { + return 1 << 3; + } +} \ No newline at end of file diff --git a/2-plus-2-star-2-problem/java/2/TwoPlusTwoTimesTwoProblem.java b/2-plus-2-star-2-problem/java/2/TwoPlusTwoTimesTwoProblem.java new file mode 100644 index 0000000..97d0e6b --- /dev/null +++ b/2-plus-2-star-2-problem/java/2/TwoPlusTwoTimesTwoProblem.java @@ -0,0 +1,6 @@ +public class TwoPlusTwoTimesTwoProblem { + + public static int calculate() { + return 0b1000; + } +} \ No newline at end of file diff --git a/2-plus-2-star-2-problem/java/3/TwoPlusTwoTimesTwoProblem.java b/2-plus-2-star-2-problem/java/3/TwoPlusTwoTimesTwoProblem.java new file mode 100644 index 0000000..6cb2dc5 --- /dev/null +++ b/2-plus-2-star-2-problem/java/3/TwoPlusTwoTimesTwoProblem.java @@ -0,0 +1,6 @@ +public class TwoPlusTwoTimesTwoProblem { + + public static int calculate() { + return Integer.highestOneBit(new java.util.Random().nextInt(8) + 8); + } +} \ No newline at end of file diff --git a/254-shades-of-grey/README.md b/254-shades-of-grey/README.md new file mode 100644 index 0000000..e681a15 --- /dev/null +++ b/254-shades-of-grey/README.md @@ -0,0 +1,59 @@ +# 254 shades of grey +[*View on Codewars*](https://www.codewars.com/kata/254-shades-of-grey) + +Why would we want to stop to only 50 shades of grey? Let's see to how many we can go. + +Write a function that takes a number n as a parameter and return an array containing n shades of grey in hexadecimal code (`#aaaaaa` for example). The array should be sorted in ascending order starting with `#010101`, `#020202`, etc. (using lower case letters). + +```javascript +function shadesOfGrey(n){ + // returns n shades of grey in an array +} +``` +```coffeescript +shadesOfGrey = (n) -> + # returns n shades of grey in an array +``` +```haskell +shadesOfGrey :: Int -> [String] +``` +```csharp +using System; + +public static class Kata { + public static class ShadesOfGrey(int n) { + // returns n shades of grey in an array + } +} +``` +```python +def shades_of_grey(n): + return '''n shades of grey in an array''' +``` +```ruby +def shades\_of\_grey(n) + return '''n shades of grey in an array''' +end +``` +```java +public class ShadesOfGrey { + static String[] shadesOfGrey(int num) { + // returns n shades of grey in an array + } +} +``` + +As a reminder, the grey color is composed by the same number of red, green and blue: `#010101`, `#aeaeae`, `#555555`, etc. Also, `#000000` and `#ffffff` are not accepted values. + +When n is negative, just return an empty array. +If n is higher than 254, just return an array of 254 elements. + +Have fun + + + +## Timeline +- Created: 2015-02-04 +- Published: 2015-02-04 +- Approved: 2015-03-10 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/254-shades-of-grey/csharp/1/254-shades-of-grey b/254-shades-of-grey/csharp/1/254-shades-of-grey new file mode 100644 index 0000000..6ada874 --- /dev/null +++ b/254-shades-of-grey/csharp/1/254-shades-of-grey @@ -0,0 +1,20 @@ +using System; + +public static class Kata +{ + public static string[] ShadesOfGrey(int n) + { + if (n <= 0) + { + return new string[0]; + } + var max = Math.Min(byte.MaxValue - 1, n); + var shadesOfGrey = new string[max]; + for (int i = 0; i < max; i++) + { + var hex = (i + 1).ToString("x2"); + shadesOfGrey[i] = '#' + hex + hex + hex; + } + return shadesOfGrey; + } +} \ No newline at end of file diff --git a/254-shades-of-grey/csharp/2/254-shades-of-grey b/254-shades-of-grey/csharp/2/254-shades-of-grey new file mode 100644 index 0000000..2b932a3 --- /dev/null +++ b/254-shades-of-grey/csharp/2/254-shades-of-grey @@ -0,0 +1,14 @@ +using System.Linq; + +public static class Kata +{ + public static string[] ShadesOfGrey(int n) + { + return Enumerable + .Range(1, byte.MaxValue - 1) + .Take(n) + .Select(i => i.ToString("x2")) + .Select(x => '#' + x + x + x) + .ToArray(); + } +} \ No newline at end of file diff --git a/254-shades-of-grey/java/1/ShadesOfGrey.java b/254-shades-of-grey/java/1/ShadesOfGrey.java new file mode 100644 index 0000000..1349eb6 --- /dev/null +++ b/254-shades-of-grey/java/1/ShadesOfGrey.java @@ -0,0 +1,11 @@ +public class ShadesOfGrey { + static String[] shadesOfGrey(int n) { + return n <= 0 ? new String[0] + : java.util.stream.IntStream + .range(1, 0xFF) + .limit(n) + .mapToObj(i -> String.format("%02x", i)) + .map(x -> '#' + x + x + x) + .toArray(String[]::new); + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3446fe5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) , All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. \ No newline at end of file diff --git a/a-function-to-display-mottos-for-westerosi-houses/README.md b/a-function-to-display-mottos-for-westerosi-houses/README.md new file mode 100644 index 0000000..434c82e --- /dev/null +++ b/a-function-to-display-mottos-for-westerosi-houses/README.md @@ -0,0 +1,38 @@ +# A function to display Mottos for Westerosi Houses +[*View on Codewars*](https://www.codewars.com/kata/a-function-to-display-mottos-for-westerosi-houses) + +Given a list of the following major Houses of Westeros and their respective mottos: + +``` +var houses = [ + {name: "Targaryen", motto: "Fire and Blood"}, + {name: "Stark", motto: "Winter is Coming"}, + {name: "Bolton", motto: "Our Blades Are Sharp"}, + {name: "Greyjoy", motto: "We Do Not Sow"}, + {name: "Tully", motto: "Family, Duty, Honor"}, + {name: "Arryn", motto: "As High as Honor"}, + {name: "Lannister", motto: "Hear Me Roar!"}, + {name: "Tyrell", motto: "Growing Strong"}, + {name: "Baratheon", motto: "Ours is the Fury"}, + {name: "Martell", motto: "Unbowed, Unbent, Unbroken"} +];``` + +Write a function that, when passed the name of a House, returns its motto. For instance: + +``` +motto("Tyrell") +``` + +should return + +``` +"growing strong" +``` + +If passed an invalid House name, the script should return an empty string. + +## Timeline +- Created: 2014-06-04 +- Published: 2014-06-04 +- Approved: null +- Completed: 2015-05-23 \ No newline at end of file diff --git a/a-function-to-display-mottos-for-westerosi-houses/javascript/1/a-function-to-display-mottos-for-westerosi-houses.js b/a-function-to-display-mottos-for-westerosi-houses/javascript/1/a-function-to-display-mottos-for-westerosi-houses.js new file mode 100644 index 0000000..b46a68f --- /dev/null +++ b/a-function-to-display-mottos-for-westerosi-houses/javascript/1/a-function-to-display-mottos-for-westerosi-houses.js @@ -0,0 +1,22 @@ +var houses = [ + {name: "Targaryen", motto: "Fire and Blood"}, + {name: "Stark", motto: "Winter is Coming"}, + {name: "Bolton", motto: "Our Blades Are Sharp"}, + {name: "Greyjoy", motto: "We Do Not Sow"}, + {name: "Tully", motto: "Family, Duty, Honor"}, + {name: "Arryn", motto: "As High as Honor"}, + {name: "Lannister", motto: "Hear Me Roar!"}, + {name: "Tyrell", motto: "Growing Strong"}, + {name: "Baratheon", motto: "Ours is the Fury"}, + {name: "Martell", motto: "Unbowed, Unbent, Unbroken"} +]; + +function motto(name) { + for (var i = 0; i < houses.length; i++) { + var house = houses[i]; + if (house.name === name) { + return house.motto; + } + } + return ""; +} \ No newline at end of file diff --git a/a-needle-in-the-haystack/README.md b/a-needle-in-the-haystack/README.md new file mode 100644 index 0000000..8ce039f --- /dev/null +++ b/a-needle-in-the-haystack/README.md @@ -0,0 +1,51 @@ +# A Needle in the Haystack +[*View on Codewars*](https://www.codewars.com/kata/a-needle-in-the-haystack) + +Can you find the needle in the haystack? + +Write a function `findNeedle()` that takes an `array` full of junk but containing one `"needle"` + +After your function finds the needle it should return a message (as a string) that says: + +`"found the needle at position "` plus the `index` it found the needle + +So + +````python +find_needle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk']) +```` +````ruby +find_needle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk']) +```` +````javascript +findNeedle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk']) +```` +````java +findNeedle(new Object[] {"hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"}) +```` +````elixir +find_needle(["hay", "junk", "hay", "hay", "moreJunk", "needle", "randomJunk"]) +```` + +should return +````python +'found the needle at position 5' +```` +````ruby +'found the needle at position 5' +```` +````javascript +'found the needle at position 5' +```` +````java +"found the needle at position 5" +```` +````elixir +"found the needle at position 5" +```` + +## Timeline +- Created: 2015-12-08 +- Published: 2015-12-09 +- Approved: 2015-12-28 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/a-needle-in-the-haystack/java/1/Kata.java b/a-needle-in-the-haystack/java/1/Kata.java new file mode 100644 index 0000000..190aa88 --- /dev/null +++ b/a-needle-in-the-haystack/java/1/Kata.java @@ -0,0 +1,9 @@ +public class Kata { + public static String findNeedle(Object[] haystack) { + for (int i = 0;; i++) { + if ("needle".equals(haystack[i])) { + return "found the needle at position " + i; + } + } + } +} \ No newline at end of file diff --git a/a-plus-b/README.md b/a-plus-b/README.md new file mode 100644 index 0000000..b961595 --- /dev/null +++ b/a-plus-b/README.md @@ -0,0 +1,10 @@ +# A + B +[*View on Codewars*](https://www.codewars.com/kata/a-plus-b) + +Vasya Pupkin just started learning Java and C#. At first, he decided to write simple program that was supposed to sum up two small numbers (numbers and their sum fit in a byte), but it didn't work. Vasya was too sad to find out what is wrong. Help him to correct the mistake. + +## Timeline +- Created: 2015-03-25 +- Published: 2015-03-25 +- Approved: 2016-06-29 +- Completed: 2015-05-16 \ No newline at end of file diff --git a/a-plus-b/java/1/FirstClass.java b/a-plus-b/java/1/FirstClass.java new file mode 100644 index 0000000..d8041a5 --- /dev/null +++ b/a-plus-b/java/1/FirstClass.java @@ -0,0 +1,5 @@ +public class FirstClass { + public static int sum (int a, int b) { + return a+b; + } +} \ No newline at end of file diff --git a/addition-function-problem/README.md b/addition-function-problem/README.md new file mode 100644 index 0000000..10d65bb --- /dev/null +++ b/addition-function-problem/README.md @@ -0,0 +1,11 @@ +# addition function problem +[*View on Codewars*](https://www.codewars.com/kata/addition-function-problem) + +The function is incomplete and it's your job to complete it +so it would add the given values. + +## Timeline +- Created: 2014-02-08 +- Published: 2014-02-08 +- Approved: null +- Completed: 2015-05-21 \ No newline at end of file diff --git a/addition-function-problem/javascript/1/addition-function-problem.js b/addition-function-problem/javascript/1/addition-function-problem.js new file mode 100644 index 0000000..fed36a1 --- /dev/null +++ b/addition-function-problem/javascript/1/addition-function-problem.js @@ -0,0 +1,3 @@ +function add(a, b){ + return a + b +} \ No newline at end of file diff --git a/are-the-brackets-balanced/README.md b/are-the-brackets-balanced/README.md new file mode 100644 index 0000000..a3d9a96 --- /dev/null +++ b/are-the-brackets-balanced/README.md @@ -0,0 +1,12 @@ +# Are the brackets balanced? +[*View on Codewars*](https://www.codewars.com/kata/are-the-brackets-balanced) + +Given a string which may include opening or closing round brackets, can you tell whether the string contains a balanced pair(s) of round brackets, that is there are no brackets which are either opened & not closed, or vice versa. Opening round brackets always have to come before closing bracket. An empty string is balanced. + + + +## Timeline +- Created: 2015-05-09 +- Published: 2015-05-09 +- Approved: null +- Completed: 2015-05-20 \ No newline at end of file diff --git a/are-the-brackets-balanced/java/1/BrakedBalance.java b/are-the-brackets-balanced/java/1/BrakedBalance.java new file mode 100644 index 0000000..60b421c --- /dev/null +++ b/are-the-brackets-balanced/java/1/BrakedBalance.java @@ -0,0 +1,29 @@ +import java.util.Deque; +import java.util.concurrent.LinkedBlockingDeque; + +public class BrakedBalance { + private static final char CLOSING = ')'; + private static final char OPENING = '('; + + public static boolean isStringBalanced(final String s) { + final int length = s.length(); + final Deque openings = new LinkedBlockingDeque<>(length / 2); + for (int i = 0; i < length; i++) { + if (!isCharBalanced(openings, s.charAt(i))) { + return false; + } + } + return openings.isEmpty(); + } + + private static boolean isCharBalanced(final Deque openings, final char c) { + if (c == OPENING) { + return openings.offerFirst(c); + } + if (c == CLOSING) { + final Character bracket = openings.pollFirst(); + return bracket != null && bracket == OPENING; + } + return false; + } +} \ No newline at end of file diff --git a/are-the-brackets-balanced/java/2/BrakedBalance.java b/are-the-brackets-balanced/java/2/BrakedBalance.java new file mode 100644 index 0000000..32a1f50 --- /dev/null +++ b/are-the-brackets-balanced/java/2/BrakedBalance.java @@ -0,0 +1,29 @@ +import java.util.Deque; +import java.util.concurrent.LinkedBlockingDeque; + +public class BrakedBalance { + private static final char CLOSING = ')'; + private static final char OPENING = '('; + + public static boolean isStringBalanced(final String s) { + final int length = s.length(); + final Deque openings = new LinkedBlockingDeque<>(length / 2); + for (int i = 0; i < length; i++) { + if (!isCharBalanced(openings, s.charAt(i))) { + return false; + } + } + return openings.isEmpty(); + } + + private static boolean isCharBalanced(final Deque openings, final char c) { + if (c == OPENING) { + return openings.offerFirst(c); + } + if (c == CLOSING) { + final Character bracket = openings.pollFirst(); + return bracket != null && bracket == OPENING; + } + return true; + } +} \ No newline at end of file diff --git a/are-the-numbers-in-order/README.md b/are-the-numbers-in-order/README.md new file mode 100644 index 0000000..35c0fa9 --- /dev/null +++ b/are-the-numbers-in-order/README.md @@ -0,0 +1,46 @@ +# Are the numbers in order? +[*View on Codewars*](https://www.codewars.com/kata/are-the-numbers-in-order) + +# Are the numbers in order? + +In this Kata, your function receives an array of positive integers as input. Your task is to determine whether the numbers are in **ascending** order. + +For the purposes of this Kata, you may assume that all inputs are valid (i.e. arrays containing only positive integers with a length of at least 2). + +For example: + +```js +inAscOrder([1,2,4,7,19]); // returns true +inAscOrder([1,2,3,4,5]); // returns true +inAscOrder([1,6,10,18,2,4,20]); // returns false +inAscOrder([9,8,7,6,5,4,3,2,1]); // returns false because the numbers are in DESCENDING order +``` + +```csharp +Kata.IsAscOrder(new int[]{1,2,4,7,19}) == true +Kata.IsAscOrder(new int[]{1,2,3,4,5}) == true +Kata.IsAscOrder(new int[]{1,6,10,18,2,4,20}) == false +Kata.IsAscOrder(new int[]{9,8,7,6,5,4,3,2,1}) == false // numbers are in DESCENDING order +``` + +```python +in_asc_order([1,2,4,7,19]) # returns True +in_asc_order([1,2,3,4,5]); // returns True +in_asc_order([1,6,10,18,2,4,20]) # returns False +in_asc_order([9,8,7,6,5,4,3,2,1]) # returns False because the numbers are in DESCENDING order +``` + +```php +in_asc_order([1, 2, 4, 7, 19]); // true +in_asc_order([1, 2, 3, 4, 5]); // true +in_asc_order([1, 6, 10, 18, 2, 4, 20]); // false +in_asc_order([9, 8, 7, 6, 5, 4, 3, 2, 1]); // false (NOTE: because the numbers are in DESCENDING order, not ascending order) +``` + +**Extra Challenge: If time, try to optimise and shorten your code as much as possible.** + +## Timeline +- Created: 2016-02-08 +- Published: 2016-02-08 +- Approved: 2016-02-09 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/are-the-numbers-in-order/javascript/1/are-the-numbers-in-order.js b/are-the-numbers-in-order/javascript/1/are-the-numbers-in-order.js new file mode 100644 index 0000000..f180c61 --- /dev/null +++ b/are-the-numbers-in-order/javascript/1/are-the-numbers-in-order.js @@ -0,0 +1,8 @@ +function inAscOrder(arr) { + for(let i = 0; i < arr.length - 1; i++) { + if (arr[i] > arr[i+1]) { + return false; + } + } + return true; +} \ No newline at end of file diff --git a/are-they-the-same/README.md b/are-they-the-same/README.md new file mode 100644 index 0000000..7929341 --- /dev/null +++ b/are-they-the-same/README.md @@ -0,0 +1,47 @@ +# Are they the "same"? +[*View on Codewars*](https://www.codewars.com/kata/are-they-the-same) + +Given two arrays `a` and `b` write a function `comp(a, b)` (`compSame(a, b)` in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in `b` are the elements in `a` squared, regardless of the order. + +## Examples +## Valid arrays +``` +a = [121, 144, 19, 161, 19, 144, 19, 11] +b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] +``` +`comp(a, b)` returns true because in `b` 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write `b`'s elements in terms of squares: +``` +a = [121, 144, 19, 161, 19, 144, 19, 11] +b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] +``` +### Invalid arrays +If we change the first number to something else, `comp` may not return true anymore: +``` +a = [121, 144, 19, 161, 19, 144, 19, 11] +b = [132, 14641, 20736, 361, 25921, 361, 20736, 361] +``` +`comp(a,b)` returns false because in `b` 132 is not the square of any number of `a`. +``` +a = [121, 144, 19, 161, 19, 144, 19, 11] +b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361] +``` +`comp(a,b)` returns false because in `b` 36100 is not the square of any number of `a`. + +## Remarks +`a` or `b` might be `[]` (all languages except R, Shell). +`a` or `b` might be `nil` or `null` or `None` (except in Haskell, Elixir, C++, Rust, R, Shell). + +If `a` or `b` are `nil` (or `null` or `None`), the problem doesn't make sense so return false. + +If `a` or `b` are empty the result is evident by itself. + +~~~if:c +## Note for C +The two arrays have the same size `(> 0)` given as parameter in function `comp`. +~~~ + +## Timeline +- Created: 2015-03-14 +- Published: 2015-03-14 +- Approved: 2015-05-08 +- Completed: 2015-05-08 \ No newline at end of file diff --git a/are-they-the-same/java/1/AreSame.java b/are-they-the-same/java/1/AreSame.java new file mode 100644 index 0000000..b738cff --- /dev/null +++ b/are-they-the-same/java/1/AreSame.java @@ -0,0 +1,7 @@ +import java.util.Arrays; + +public class AreSame { + public static boolean comp(final int[] a, final int[] b) { + return a != null && b != null && a.length == b.length && Arrays.equals(Arrays.stream(a).map(i -> i * i).sorted().toArray(), Arrays.stream(b).sorted().toArray()); + } +} \ No newline at end of file diff --git a/are-they-the-same/javascript/1/are-they-the-same.js b/are-they-the-same/javascript/1/are-they-the-same.js new file mode 100644 index 0000000..7ded578 --- /dev/null +++ b/are-they-the-same/javascript/1/are-they-the-same.js @@ -0,0 +1,23 @@ +function comp(a1, a2) { + if (!a1 || !a2) { + return false; + } + + let l = a1.length; + + if (l !== a2.length) { + return false; + } + + let c = (e1, e2) => e1 - e2; + a1.sort(c); + a2.sort(c); + + for (let i = 0; i < l; i++) { + let e1 = a1[i]; + if (e1 * e1 !== a2[i]) { + return false; + } + } + return true; +} \ No newline at end of file diff --git a/are-you-playing-banjo/README.md b/are-you-playing-banjo/README.md new file mode 100644 index 0000000..b2d4da5 --- /dev/null +++ b/are-you-playing-banjo/README.md @@ -0,0 +1,18 @@ +# Are You Playing Banjo? +[*View on Codewars*](https://www.codewars.com/kata/are-you-playing-banjo) + +Create a function which answers the question "Are you playing banjo?". +If your name starts with the letter "R" or lower case "r", you are playing banjo! + +The function takes a name as its only argument, and returns one of the following strings: +``` +name + " plays banjo" +name + " does not play banjo" +``` +Names given are always valid strings. + +## Timeline +- Created: 2014-06-28 +- Published: 2014-06-28 +- Approved: 2014-09-07 +- Completed: 2015-05-08 \ No newline at end of file diff --git a/are-you-playing-banjo/java/1/Banjo.java b/are-you-playing-banjo/java/1/Banjo.java new file mode 100644 index 0000000..918d67f --- /dev/null +++ b/are-you-playing-banjo/java/1/Banjo.java @@ -0,0 +1,10 @@ +public class Banjo { + public static String areYouPlayingBanjo(String name) { + return String.format(playsBanjo(name) ? "%s plays banjo" + : "%s does not play banjo", name); + } + + private static boolean playsBanjo(String name) { + return Character.toUpperCase(name.charAt(0)) == 'R'; + } +} \ No newline at end of file diff --git a/are-you-playing-banjo/java/2/Banjo.java b/are-you-playing-banjo/java/2/Banjo.java new file mode 100644 index 0000000..d31c543 --- /dev/null +++ b/are-you-playing-banjo/java/2/Banjo.java @@ -0,0 +1,9 @@ +public class Banjo { + public static String areYouPlayingBanjo(String name) { + return String.format("%s %s banjo", name, playsBanjo(name) ? "plays" : "does not play"); + } + + private static boolean playsBanjo(String name) { + return Character.toUpperCase(name.charAt(0)) == 'R'; + } +} \ No newline at end of file diff --git a/area-of-a-circle/README.md b/area-of-a-circle/README.md new file mode 100644 index 0000000..44dfcbb --- /dev/null +++ b/area-of-a-circle/README.md @@ -0,0 +1,57 @@ +# Area of a Circle +[*View on Codewars*](https://www.codewars.com/kata/area-of-a-circle) + +Complete the function ```circleArea``` so that it will return the area of a circle with the given ```radius```. Round the returned number to two decimal places (except for Haskell). If the radius is not positive or not a number, return ```false```. + + +Example: + +```java +Circle.area(-1485.86); //returns false +Circle.area(0); //returns false +Circle.area(43.2673); //returns 5881.25 +Circle.area(68); //returns 14526.72 +``` + +```javascript +circleArea(-1485.86); //returns false +circleArea(0); //returns false +circleArea(43.2673); //returns 5881.25 +circleArea(68); //returns 14526.72 +circleArea("number"); //returns false +``` +```haskell +circleArea (-1) `shouldBe` Nothing +circleArea 0 `shouldBe` Nothing +circleArea 1 `shouldBe` Just ( pi) +circleArea 2 `shouldBe` Just (4 * pi) +circleArea 3 `shouldBe` Just (9 * pi) +``` +```python +circleArea(-1485.86) #returns false +circleArea(0) #returns false +circleArea(43.2673) #returns 5881.25 +circleArea(68) #returns 14526.72 +circleArea("number") #returns false +``` +```csharp +Kata.CalculateAreaOfCircle("-123"); //throws ArgumentException +Kata.CalculateAreaOfCircle("0"); //throws ArgumentException +Kata.CalculateAreaOfCircle("43.2673"); //return 5881.25 +Kata.CalculateAreaOfCircle("68"); //return 14526.72 +Kata.CalculateAreaOfCircle("number"); //throws ArgumentException +``` +```ruby +circle_area(-1485.86) #returns false +circle_area(0) #returns false +circle_area(43.2673) #returns 5881.25 +circle_area(68) #returns 14526.72 +circle_area("number") #returns false +``` + + +## Timeline +- Created: 2014-05-20 +- Published: 2014-05-24 +- Approved: 2014-09-09 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/area-of-a-circle/java/1/Circle.java b/area-of-a-circle/java/1/Circle.java new file mode 100644 index 0000000..9bde04d --- /dev/null +++ b/area-of-a-circle/java/1/Circle.java @@ -0,0 +1,10 @@ +import static java.lang.Math.*; + +public class Circle { + public static double area(double radius) { + if (radius <= 0) { + throw new IllegalArgumentException(String.format("radius = %d <= 0", radius)); + } + return PI * pow(radius, 2); + } +} \ No newline at end of file diff --git a/arithmetic-sequence/README.md b/arithmetic-sequence/README.md new file mode 100644 index 0000000..faad884 --- /dev/null +++ b/arithmetic-sequence/README.md @@ -0,0 +1,27 @@ +# Arithmetic Sequence! +[*View on Codewars*](https://www.codewars.com/kata/arithmetic-sequence) + +A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term.
+If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence.
+An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and so on] )
+Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence.
+Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ]
+There are some sequences that aren't arithmetic nor are they geometric.
+Here is a link to feed your brain : Sequence ! + + +You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). + +The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: + + - ``first`` is the first value in the 0 INDEX.
+ - ``n`` is the index of the value we want.
+ - ``c`` is the constant added between the terms. + +Remember that `first` is in the index ``0`` .. just saying ... + +## Timeline +- Created: 2014-09-09 +- Published: 2014-09-17 +- Approved: 2014-09-22 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/arithmetic-sequence/java/1/Sequence.java b/arithmetic-sequence/java/1/Sequence.java new file mode 100644 index 0000000..b46f2f5 --- /dev/null +++ b/arithmetic-sequence/java/1/Sequence.java @@ -0,0 +1,7 @@ +public class Sequence { + public static int nthterm(int first, int n, int c) { + int nthterm = first; + for (int i = 0; i < n; nthterm += c, i++); + return nthterm; + } +} \ No newline at end of file diff --git a/bagels/README.md b/bagels/README.md new file mode 100644 index 0000000..9d384b4 --- /dev/null +++ b/bagels/README.md @@ -0,0 +1,42 @@ +# Bagels +[*View on Codewars*](https://www.codewars.com/kata/bagels) + +Here's a seemingly simple challenge. We're giving you a class called bagel, exactly as it appears below. All it really does is return an int, specifically 3. + +```csharp +sealed class Bagel { + public int Value { get; private set; } = 3; +} +``` +```kotlin +class Bagel { + val value: Int get() = 3 +} +``` +```scala +class Bagel { + final def getValue = 3 +} +``` +```java +public class Bagel { + public final int getValue() { + return 3; + } +} +``` +```groovy +class Bagel { + final int getValue() { + 3 + } +} +``` + +The catch? For the solution, we're testing that the result is equal to 4. But as a little hint, the solution to the this Kata is exactly the same as the example test cases. + +## Timeline +- Created: 2015-01-19 +- Published: 2015-01-19 +- Approved: 2016-10-09 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/basic-js-calculating-averages/README.md b/basic-js-calculating-averages/README.md new file mode 100644 index 0000000..c1ffc07 --- /dev/null +++ b/basic-js-calculating-averages/README.md @@ -0,0 +1,19 @@ +# Basic JS - Calculating averages +[*View on Codewars*](https://www.codewars.com/kata/basic-js-calculating-averages) + +Let's build a calculator that can calculate the average for an arbitrary number of arguments. + +The test expects you to provide a Calculator object with an average method: +``` +Calculator.average() +``` + +The test also expects that when you pass no arguments, it returns 0. The arguments are expected to be integers. + +It expects Calculator.average(3,4,5) to return 4. + +## Timeline +- Created: 2013-12-04 +- Published: 2013-12-09 +- Approved: 2013-12-24 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/basic-js-calculating-averages/javascript/1/basic-js-calculating-averages.js b/basic-js-calculating-averages/javascript/1/basic-js-calculating-averages.js new file mode 100644 index 0000000..70e0edd --- /dev/null +++ b/basic-js-calculating-averages/javascript/1/basic-js-calculating-averages.js @@ -0,0 +1,11 @@ +var Calculator = { + average: function() { + var length = arguments.length; + if (!length) return 0; + var sum = 0; + for (var i = 0; i < length; i++) { + sum += arguments[i]; + } + return sum / length; + } +}; \ No newline at end of file diff --git a/basic-subclasses-adam-and-eve/README.md b/basic-subclasses-adam-and-eve/README.md new file mode 100644 index 0000000..b88d71c --- /dev/null +++ b/basic-subclasses-adam-and-eve/README.md @@ -0,0 +1,15 @@ +# Basic subclasses - Adam and Eve +[*View on Codewars*](https://www.codewars.com/kata/basic-subclasses-adam-and-eve) + +According to the creation myths of the Abrahamic religions, Adam and Eva were the first Humans to wander the earth. + +You have to do God’s job. The creation method must return an array of length 2 containing objects representing Adam and Eva. The first object in the array should be an instance of the class Man. The second should be an instance of the class Woman. Both objects have to be subclasses of Human. Your job is to implement the ```Human, Man and Woman``` classes. + +
+
Note: actual and expected are swapped in the Python assertions but the kata isn't editable anymore. Keep that in mind...
+ +## Timeline +- Created: 2014-11-23 +- Published: 2014-11-24 +- Approved: 2014-12-27 +- Completed: 2015-05-08 \ No newline at end of file diff --git a/basic-subclasses-adam-and-eve/java/1/God.java b/basic-subclasses-adam-and-eve/java/1/God.java new file mode 100644 index 0000000..b97a718 --- /dev/null +++ b/basic-subclasses-adam-and-eve/java/1/God.java @@ -0,0 +1,11 @@ +public class God { + public static Human[] create(){ + return new Human[]{new Man(), new Woman()}; + } +} +class Human{ +} +class Man extends Human{ +} +class Woman extends Human{ +} \ No newline at end of file diff --git a/batman-quotes/README.md b/batman-quotes/README.md new file mode 100644 index 0000000..d6c33dc --- /dev/null +++ b/batman-quotes/README.md @@ -0,0 +1,31 @@ +# Batman Quotes +[*View on Codewars*](https://www.codewars.com/kata/batman-quotes) + +Batman & Robin have gotten into quite a pickle this time. The Joker has mixed up their iconic quotes and also replaced one of the characters in their names, with a number. They need help getting things back in order. + +Implement the getQuote method which takes in an array of quotes, and a string comprised of letters and a single number (e.g. "Rob1n") where the number corresponds to their quote indexed in the passed in array. + +Return the quote along with the character who said it: + +```java +BatmanQuotes.getQuote(["I am vengeance. I am the night. I am Batman!", "Holy haberdashery, Batman!", "Let's put a smile on that faaaceee!"], "Rob1n") should output => "Robin: Holy haberdashery, Batman! +``` + +```javascript +getQuote(["I am vengeance. I am the night. I am Batman!", "Holy haberdashery, Batman!", "Let's put a smile on that faaaceee!"], "Rob1n") + // => "Robin: Holy haberdashery, Batman! +``` + + +```clojure +(getQuote ["I am vengeance. I am the night. I am Batman!" "Holy haberdashery, Batman!" "Let's put a smile on that faaaceee!"] "Rob1n") + // => "Robin: Holy haberdashery, Batman!" +``` + +Hint: You are guaranteed that the number in the passed in string is placed somewhere after the first character of the string. The quotes either belong to "Batman", "Robin", or "Joker". + +## Timeline +- Created: 2015-03-28 +- Published: 2015-03-28 +- Approved: 2015-06-05 +- Completed: 2015-05-15 \ No newline at end of file diff --git a/batman-quotes/java/1/BatmanQuotes.java b/batman-quotes/java/1/BatmanQuotes.java new file mode 100644 index 0000000..0e68aad --- /dev/null +++ b/batman-quotes/java/1/BatmanQuotes.java @@ -0,0 +1,27 @@ +import java.util.regex.*; + +public class BatmanQuotes{ + public static String getQuote(String[] quotes, String hero) { + String quote = quotes[quoteIndex(hero)]; + String realHero = realHero(hero); + return String.format("%s: %s", realHero, quote); + } + + static int quoteIndex(String hero) { + Matcher matcher = Pattern.compile("\\d+").matcher(hero); + matcher.find(); + return Integer.parseInt(matcher.group()); + } + + static String realHero(String hero) { + switch (hero.charAt(0)) { + case 'B': + return "Batman"; + case 'J': + return "Joker"; + case 'R': + return "Robin"; + } + return hero; + } +} \ No newline at end of file diff --git a/beginner-friendly-lowercase-letters/README.md b/beginner-friendly-lowercase-letters/README.md new file mode 100644 index 0000000..87a7d83 --- /dev/null +++ b/beginner-friendly-lowercase-letters/README.md @@ -0,0 +1,12 @@ +# Beginner friendly: Lowercase letters +[*View on Codewars*](https://www.codewars.com/kata/beginner-friendly-lowercase-letters) + +Convert a string to lowercase letters. + +Example: convert `"Hello world!"` to `"hello world!"` + +## Timeline +- Created: 2017-02-20 +- Published: 2017-02-20 +- Approved: null +- Completed: 2018-03-04 \ No newline at end of file diff --git a/beginner-friendly-lowercase-letters/javascript/1/beginner-friendly-lowercase-letters.js b/beginner-friendly-lowercase-letters/javascript/1/beginner-friendly-lowercase-letters.js new file mode 100644 index 0000000..3ad345d --- /dev/null +++ b/beginner-friendly-lowercase-letters/javascript/1/beginner-friendly-lowercase-letters.js @@ -0,0 +1,3 @@ +function convertLowerCase(str) { +return str.toLowerCase(); +} \ No newline at end of file diff --git a/binary-addition/README.md b/binary-addition/README.md new file mode 100644 index 0000000..dc690f9 --- /dev/null +++ b/binary-addition/README.md @@ -0,0 +1,13 @@ +# Binary Addition +[*View on Codewars*](https://www.codewars.com/kata/binary-addition) + +Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. + +The binary number returned should be a string. + + +## Timeline +- Created: 2015-04-04 +- Published: 2015-04-04 +- Approved: 2015-09-15 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/binary-addition/javascript/1/binary-addition.js b/binary-addition/javascript/1/binary-addition.js new file mode 100644 index 0000000..633098f --- /dev/null +++ b/binary-addition/javascript/1/binary-addition.js @@ -0,0 +1,3 @@ +function addBinary(a,b){ + return (a+b).toString(2) +} \ No newline at end of file diff --git a/binary-calculator/README.md b/binary-calculator/README.md new file mode 100644 index 0000000..7f12fba --- /dev/null +++ b/binary-calculator/README.md @@ -0,0 +1,26 @@ +# Binary Calculator +[*View on Codewars*](https://www.codewars.com/kata/binary-calculator) + +In this kata you need to write a function that will receive two strings (```n1``` and ```n2```), each representing an integer as a binary number. A third parameter will be provided (```o```) as a string representing one of the following operators: add, subtract, multiply. + +Your task is to write the calculate function so that it will perform the arithmetic and the result returned should be a string representing the binary result. + +Examples: +``` +1 + 1 === 10 +10 + 10 === 100 +``` + +Negative binary numbers are usually preceded by several 1's. For this kata, negative numbers can be represented with the negative symbol at the beginning of the string. + +Examples of negatives: +``` +1 - 10 === -1 +10 - 100 === -10 +``` + +## Timeline +- Created: 2014-11-18 +- Published: 2014-11-18 +- Approved: 2015-04-17 +- Completed: 2015-05-11 \ No newline at end of file diff --git a/binary-calculator/java/1/BinaryCalculator.java b/binary-calculator/java/1/BinaryCalculator.java new file mode 100644 index 0000000..125f8d0 --- /dev/null +++ b/binary-calculator/java/1/BinaryCalculator.java @@ -0,0 +1,27 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.function.IntBinaryOperator; + +public class BinaryCalculator { + public static final int RADIX = 2; + + private static final Map OPS = new HashMap<>(); + + static { + OPS.put("add", (a, b) -> a + b); + OPS.put("subtract", (a, b) -> a - b); + OPS.put("multiply", (a, b) -> a * b); + } + + public static String calculate(final String n1, final String n2, final String o) { + return toBinary(OPS.get(o).applyAsInt(fromBinary(n1), fromBinary(n2))); + } + + private static int fromBinary(final String s) { + return Integer.parseInt(s, RADIX); + } + + private static String toBinary(final int n) { + return Integer.toString(n, RADIX); + } +} \ No newline at end of file diff --git a/binding-within-the-list-monad/README.md b/binding-within-the-list-monad/README.md new file mode 100644 index 0000000..cd86fbf --- /dev/null +++ b/binding-within-the-list-monad/README.md @@ -0,0 +1,80 @@ +# Binding within the List Monad +[*View on Codewars*](https://www.codewars.com/kata/binding-within-the-list-monad) + +In Haskell, _Monads_ are simple containers, or even 'box-like' datastructures, of which lists are included, which can respond to certain functions, which are defined in the Monad typeclass. (To put it simply!) + +In this kata, you must implement the __Bind__ function for lists, or arrays. In haskell, the function is represented by `>>=`, but we'll just call it `bind`. + +Essentially, `bind` should map the array with the function given, and then flatten it one time. Don't manipulate the original array; make you function _pure_: without side-effects, so that no variables are edited whilst the function is carried out. + +Here's how it should work: + +```coffeescript +bind( [1,2,3], (a) -> [a+1] ) +=> [2,3,4] + +bind( [1,2,3], (a) -> [[a]] ) +=> [[1],[2],[3]] + +bind( [1,2,3], (a) -> a ) +=> # ERROR! The returned value is not a list! +``` +```javascript +bind( [1,2,3], function(a){ return [a+1] } ) +=> [2,3,4] + +bind( [1,2,3], function(a){ return [[a]] } ) +=> [[1],[2],[3]] + +bind( [1,2,3], function(a){ return a } ) +=> # ERROR! The returned value is not a list! +``` +```python +bind( [1,2,3], lambda a: [a+1] ) +=> [2,3,4] + +bind( [1,2,3], lambda a: [[a]] ) +=> [[1],[2],[3]] + +bind( [1,2,3], lambda a: a ) +=> # ERROR! The returned value is not a list! +``` +```ruby +bind( [1,2,3] ) {|a| [a+1] } +=> [2,3,4] + +bind( [1,2,3] ) {|a| [[a]] } +=> [[1],[2],[3]] + +bind( [1,2,3] ) {|a| a } +=> # ERROR! The returned value is not a list! +``` +```clojure +(bind [1 2 3] #(do [(+ % 1)]) ) +=> [2,3,4] + +(bind [1 2 3] #(do [[ % ]]) ) +=> [[1],[2],[3]] + +(bind [1 2 3] #(do %) ) +=> # ERROR! The returned value is not a list! +``` +```java +bind(Arrays.asList(1,2,3), i -> Arrays.asList((int)i + 1)) +//=> [2,3,4] + +bind(Arrays.asList(1,2,3), i -> Arrays.asList(Arrays.asList(i))); +//=> [[1],[2],[3]] + +bind(Arrays.asList(3,4,5), i -> i); +//=> # ERROR! Java does this on its own! You can't even compile! Strong typing FTW! +``` + +As per usual, the ruby function will be passed a Proc or Lambda. Remember that the function still takes two arguments! + + +## Timeline +- Created: 2014-11-20 +- Published: 2014-12-10 +- Approved: 2014-12-16 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/binding-within-the-list-monad/java/1/Binder.java b/binding-within-the-list-monad/java/1/Binder.java new file mode 100644 index 0000000..96b72a5 --- /dev/null +++ b/binding-within-the-list-monad/java/1/Binder.java @@ -0,0 +1,12 @@ +import java.util.*; +import java.util.function.Function; + +public class Binder { + public List bind(List list, Function> func) { + List is = new ArrayList<>(); + for (T t : list) { + is.addAll(func.apply(t)); + } + return is; + } +} \ No newline at end of file diff --git a/binding-within-the-list-monad/java/2/Binder.java b/binding-within-the-list-monad/java/2/Binder.java new file mode 100644 index 0000000..9dc233f --- /dev/null +++ b/binding-within-the-list-monad/java/2/Binder.java @@ -0,0 +1,9 @@ +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class Binder { + public List bind(List list, Function> func) { + return list.stream().map(func).flatMap(List::stream).collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/bit-counting/README.md b/bit-counting/README.md new file mode 100644 index 0000000..0e60e52 --- /dev/null +++ b/bit-counting/README.md @@ -0,0 +1,12 @@ +# Bit Counting +[*View on Codewars*](https://www.codewars.com/kata/bit-counting) + +Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number. + +*Example*: The binary representation of `1234` is `10011010010`, so the function should return `5` in this case + +## Timeline +- Created: 2013-10-21 +- Published: 2013-10-21 +- Approved: null +- Completed: 2018-03-04 \ No newline at end of file diff --git a/bit-counting/java/1/BitCounting.java b/bit-counting/java/1/BitCounting.java new file mode 100644 index 0000000..79ae7ea --- /dev/null +++ b/bit-counting/java/1/BitCounting.java @@ -0,0 +1,8 @@ +public class BitCounting { + + public static int countBits(int n){ + + return Integer.bitCount(n); + } + +} \ No newline at end of file diff --git a/bit-counting/javascript/1/bit-counting.js b/bit-counting/javascript/1/bit-counting.js new file mode 100644 index 0000000..ccf21e4 --- /dev/null +++ b/bit-counting/javascript/1/bit-counting.js @@ -0,0 +1,4 @@ +const countBits = n => + n === 0 + ? 0 + : (n & 1) + countBits(n >> 1) \ No newline at end of file diff --git a/bit-counting/javascript/2/bit-counting.js b/bit-counting/javascript/2/bit-counting.js new file mode 100644 index 0000000..d784b9d --- /dev/null +++ b/bit-counting/javascript/2/bit-counting.js @@ -0,0 +1 @@ +const countBits = n => n && (n & 1) + countBits(n >> 1) \ No newline at end of file diff --git a/breaking-chocolate-problem/README.md b/breaking-chocolate-problem/README.md new file mode 100644 index 0000000..29f2c09 --- /dev/null +++ b/breaking-chocolate-problem/README.md @@ -0,0 +1,16 @@ +# Breaking chocolate problem +[*View on Codewars*](https://www.codewars.com/kata/breaking-chocolate-problem) + +Your task is to split the chocolate bar of given dimension `n` x `m` into small squares. +Each square is of size 1x1 and unbreakable. +Implement a function that will return minimum number of breaks needed. + +For example if you are given a chocolate bar of size `2` x `1` you can split it to single squares in just one break, but for size `3` x `1` you must do two breaks. + +If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer. + +## Timeline +- Created: 2014-04-16 +- Published: 2014-04-16 +- Approved: 2014-10-07 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/breaking-chocolate-problem/java/1/Chocolate.java b/breaking-chocolate-problem/java/1/Chocolate.java new file mode 100644 index 0000000..820d3ad --- /dev/null +++ b/breaking-chocolate-problem/java/1/Chocolate.java @@ -0,0 +1,5 @@ +public class Chocolate{ + public static int breakChocolate(int n, int m) { + return Math.max(n * m - 1, 0); + } +} \ No newline at end of file diff --git a/broken-counter/README.md b/broken-counter/README.md new file mode 100644 index 0000000..13a2d99 --- /dev/null +++ b/broken-counter/README.md @@ -0,0 +1,14 @@ +# Broken Counter +[*View on Codewars*](https://www.codewars.com/kata/broken-counter) + +Our counter prototype is broken. Can you spot, what's wrong here? + +```if:csharp +`Counter.Value` must have manually defined getter/setter methods, according to our company's style guide. +``` + +## Timeline +- Created: 2013-10-21 +- Published: 2013-10-21 +- Approved: null +- Completed: 2016-09-08 \ No newline at end of file diff --git a/broken-counter/javascript/1/broken-counter.js b/broken-counter/javascript/1/broken-counter.js new file mode 100644 index 0000000..447a1c1 --- /dev/null +++ b/broken-counter/javascript/1/broken-counter.js @@ -0,0 +1,15 @@ +function Counter() { + this.value = 0; +} + +Counter.prototype.increase = function() { + this.value++; +}; + +Counter.prototype.getValue = function() { + return this.value; +}; + +Counter.prototype.reset = function() { + this.value = 0; +}; \ No newline at end of file diff --git a/caffeine-script/README.md b/caffeine-script/README.md new file mode 100644 index 0000000..73365dc --- /dev/null +++ b/caffeine-script/README.md @@ -0,0 +1,61 @@ +# Caffeine Script +[*View on Codewars*](https://www.codewars.com/kata/caffeine-script) + +Complete the function ```caffeineBuzz```, which takes a non-zero integer as it's one argument. + +If the integer is divisible by 3, return the string ```"Java"```. + +If the integer is divisible by 3 and divisible by 4, return the string ```"Coffee"``` + +If the integer is one of the above and is even, add ```"Script"``` to the end of the string. + +Otherwise, return the string ```"mocha_missing!"``` + +```coffeescript +caffeineBuzz(1) => "mocha_missing!" +caffeineBuzz(3) => "Java" +caffeineBuzz(6) => "JavaScript" +caffeineBuzz(12) => "CoffeeScript" +``` +```javascript +caffeineBuzz(1) => "mocha_missing!" +caffeineBuzz(3) => "Java" +caffeineBuzz(6) => "JavaScript" +caffeineBuzz(12) => "CoffeeScript" +``` +```ruby +caffeineBuzz(1) => "mocha_missing!" +caffeineBuzz(3) => "Java" +caffeineBuzz(6) => "JavaScript" +caffeineBuzz(12) => "CoffeeScript" +``` +```python +caffeineBuzz(1) => "mocha_missing!" +caffeineBuzz(3) => "Java" +caffeineBuzz(6) => "JavaScript" +caffeineBuzz(12) => "CoffeeScript" +``` +```java +caffeineBuzz(1) => "mocha_missing!" +caffeineBuzz(3) => "Java" +caffeineBuzz(6) => "JavaScript" +caffeineBuzz(12) => "CoffeeScript" +``` +```haskell +caffeineBuzz 1 => "mocha_missing!" +caffeineBuzz 3 => "Java" +caffeineBuzz 6 => "JavaScript" +caffeineBuzz 12 => "CoffeeScript" +``` +```csharp +Kata.CaffeineBuzz(1) => "mocha_missing!" +Kata.CaffeineBuzz(3) => "Java" +Kata.CaffeineBuzz(6) => "JavaScript" +Kata.CaffeineBuzz(12) => "CoffeeScript" +``` + +## Timeline +- Created: 2014-10-07 +- Published: 2014-10-07 +- Approved: 2014-10-14 +- Completed: 2015-05-05 \ No newline at end of file diff --git a/caffeine-script/java/1/CaffeineBuzz.java b/caffeine-script/java/1/CaffeineBuzz.java new file mode 100644 index 0000000..22f01d6 --- /dev/null +++ b/caffeine-script/java/1/CaffeineBuzz.java @@ -0,0 +1,12 @@ +public class CaffeineBuzz { + public static String caffeineBuzz(int n){ + return !div(n, 3) ? "mocha_missing!" + : div(n, 4) ? "CoffeeScript" + : div(n, 2) ? "JavaScript" + : "Java"; + } + + static boolean div(int n, int d) { + return n % d == 0; + } +} \ No newline at end of file diff --git a/calculate-average/README.md b/calculate-average/README.md new file mode 100644 index 0000000..559c3bb --- /dev/null +++ b/calculate-average/README.md @@ -0,0 +1,14 @@ +# Calculate average +[*View on Codewars*](https://www.codewars.com/kata/calculate-average) + +Write function avg which calculates average of numbers in given list. + +```if:python +Python: Due to rounding issues please do not use `statistics.mean` or such. +``` + +## Timeline +- Created: 2016-08-03 +- Published: 2016-08-03 +- Approved: 2016-10-17 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/calculate-average/java/1/Kata.java b/calculate-average/java/1/Kata.java new file mode 100644 index 0000000..ad3864d --- /dev/null +++ b/calculate-average/java/1/Kata.java @@ -0,0 +1,5 @@ +public class Kata{ + public static double find_average(int[] array){ + return java.util.stream.IntStream.of(array).average().getAsDouble(); + } +} \ No newline at end of file diff --git a/calculate-average/java/2/Kata.java b/calculate-average/java/2/Kata.java new file mode 100644 index 0000000..c06b984 --- /dev/null +++ b/calculate-average/java/2/Kata.java @@ -0,0 +1,7 @@ +public class Kata { + public static double find_average(int[] array) { + return java.util.stream.IntStream.of(array) + .average() + .orElse(Double.NaN); + } +} \ No newline at end of file diff --git a/calculate-average/javascript/1/calculate-average.js b/calculate-average/javascript/1/calculate-average.js new file mode 100644 index 0000000..b07a82a --- /dev/null +++ b/calculate-average/javascript/1/calculate-average.js @@ -0,0 +1,3 @@ +function find_average(array) { + return array.reduce((sum, summand) => sum + summand, 0) / array.length +} \ No newline at end of file diff --git a/calculate-the-function-f-x-for-a-simple-linear-sequence-easy/README.md b/calculate-the-function-f-x-for-a-simple-linear-sequence-easy/README.md new file mode 100644 index 0000000..6b2e260 --- /dev/null +++ b/calculate-the-function-f-x-for-a-simple-linear-sequence-easy/README.md @@ -0,0 +1,40 @@ +# Calculate the function f(x) for a simple linear sequence (Easy) +[*View on Codewars*](https://www.codewars.com/kata/calculate-the-function-f-x-for-a-simple-linear-sequence-easy) + +For any given linear sequence, calculate the function [f(x)] and return it as a string. + +For example: +```javascript +getFunction([0, 1, 2, 3, 4]) => "f(x) = x" +getFunction([0, 3, 6, 9, 12]) => "f(x) = 3x" +getFunction([1, 4, 7, 10, 13]) => "f(x) = 3x + 1" +``` +```ruby +get_function([0, 1, 2, 3, 4]) => "f(x) = x" +get_function([0, 3, 6, 9, 12]) => "f(x) = 3x" +get_function([1, 4, 7, 10, 13]) => "f(x) = 3x + 1" +``` +```python +get_function([0, 1, 2, 3, 4]) => "f(x) = x" +get_function([0, 3, 6, 9, 12]) => "f(x) = 3x" +get_function([1, 4, 7, 10, 13]) => "f(x) = 3x + 1" +``` +```haskell +getFunction [0, 1, 2, 3, 4] `shouldBe` Just "f(x) = x" +getFunction [0, 3, 6, 9, 12] `shouldBe` Just "f(x) = 3x" +getFunction [1, 4, 7, 10, 13] `shouldBe` Just "f(x) = 3x + 1" +getFunction [0, 0, 1, 1, 1] `shouldBe` Nothing -- not linear +``` + +Assumptions for this kata are: + +- the sequence argument will always contain 5 values equal to f(0) - f(4). +- the function will always be in the format "nx +/- m", 'x +/- m', 'nx', 'x' or 'm' +- if a non-linear sequence simply return 'Non-linear sequence' or `Nothing` in Haskell. + + +## Timeline +- Created: 2014-11-27 +- Published: 2014-11-27 +- Approved: 2014-12-08 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/calculate-the-function-f-x-for-a-simple-linear-sequence-easy/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-easy.js b/calculate-the-function-f-x-for-a-simple-linear-sequence-easy/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-easy.js new file mode 100644 index 0000000..e4d0f49 --- /dev/null +++ b/calculate-the-function-f-x-for-a-simple-linear-sequence-easy/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-easy.js @@ -0,0 +1,15 @@ +function getFunction(sequence) { + var m = sequence[0]; + var n = sequence[1] - m; + for (var i = 1; i < sequence.length - 1; i++) { + if (sequence[i + 1] - sequence[i] !== n) { + return 'Non-linear sequence'; + } + } + return 'f(x) = ' + (n === 0 ? m + : (n === 1 ? '' + : n === -1 ? '-' + : n) + 'x' + (m === 0 ? '' + : m < 0 ? ' - ' + -m + : ' + ' + m)); +} \ No newline at end of file diff --git a/calculate-the-function-f-x-for-a-simple-linear-sequence-medium/README.md b/calculate-the-function-f-x-for-a-simple-linear-sequence-medium/README.md new file mode 100644 index 0000000..26446b0 --- /dev/null +++ b/calculate-the-function-f-x-for-a-simple-linear-sequence-medium/README.md @@ -0,0 +1,51 @@ +# Calculate the function f(x) for a simple linear sequence (Medium) +[*View on Codewars*](https://www.codewars.com/kata/calculate-the-function-f-x-for-a-simple-linear-sequence-medium) + +This is a follow-up from my previous Kata which can be found here: http://www.codewars.com/kata/5476f4ca03810c0fc0000098 + +This time, for any given linear sequence, calculate the function [f(x)] and return it as a function in Javascript or Lambda/Block in Ruby. + +For example: + +```javascript +getFunction([0, 1, 2, 3, 4])(5) => 5 +getFunction([0, 3, 6, 9, 12])(10) => 30 +getFunction([1, 4, 7, 10, 13])(20) => 61 +``` + +```ruby +get_function([0, 1, 2, 3, 4]).call(5) => 5 +get_function([0, 3, 6, 9, 12]).call(10) => 30 +get_function([1, 4, 7, 10, 13]).call(20) => 61 +``` + +```python +get_function([0, 1, 2, 3, 4])(5) => 5 +get_function([0, 3, 6, 9, 12])(10) => 30 +get_function([1, 4, 7, 10, 13])(20) => 61 +``` + +```csharp +GetFunction(new[] { 0, 1, 2, 3, 4 })(5) => 5 +GetFunction(new[] { 0, 3, 6, 9, 12 })(10) => 30 +GetFunction(new[] { 1, 4, 7, 10, 13 })(20) => 61 +``` + +```php +get_function([0, 1, 2, 3, 4])(5) // => 5 +get_function([0, 3, 6, 9, 12])(10) // => 30 +get_function([1, 4, 7, 10, 13])(20) // => 61 +``` + +Assumptions for this kata are: +``` +The sequence argument will always contain 5 values equal to f(0) - f(4). +The function will always be in the format "nx +/- m", 'x +/- m', 'nx', 'x' or 'm' +If a non-linear sequence simply return 'Non-linear sequence' for javascript, ruby, and python. For C#, throw an ArgumentException. +``` + +## Timeline +- Created: 2014-11-28 +- Published: 2014-11-28 +- Approved: 2014-12-16 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/calculate-the-function-f-x-for-a-simple-linear-sequence-medium/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-medium.js b/calculate-the-function-f-x-for-a-simple-linear-sequence-medium/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-medium.js new file mode 100644 index 0000000..4fa3e5a --- /dev/null +++ b/calculate-the-function-f-x-for-a-simple-linear-sequence-medium/javascript/1/calculate-the-function-f-x-for-a-simple-linear-sequence-medium.js @@ -0,0 +1,12 @@ +function getFunction(sequence) { + var m = sequence[0]; + var n = sequence[1] - m; + for (var i = 1; i < sequence.length - 1; i++) { + if (sequence[i + 1] - sequence[i] !== n) { + return 'Non-linear sequence'; + } + } + return function(x) { + return n * x + m; + }; +} \ No newline at end of file diff --git a/camelcasing/README.md b/camelcasing/README.md new file mode 100644 index 0000000..04d6faa --- /dev/null +++ b/camelcasing/README.md @@ -0,0 +1,15 @@ +# CaMeLcAsInG +[*View on Codewars*](https://www.codewars.com/kata/camelcasing) + +You are given a string with a length of 0 or greater. You should transform this string so its characters alternate between uppercase and lowercase. + +-This input will never be null. +-The first letter of the input might be uppercase or lowercase. +-There will be no special characters or numbers. +-The input will always consist of one word (no spaces). + +## Timeline +- Created: 2015-01-22 +- Published: 2015-01-22 +- Approved: null +- Completed: 2015-05-09 \ No newline at end of file diff --git a/camelcasing/java/1/CamelCase.java b/camelcasing/java/1/CamelCase.java new file mode 100644 index 0000000..a92eaa1 --- /dev/null +++ b/camelcasing/java/1/CamelCase.java @@ -0,0 +1,14 @@ +import static java.lang.Character.*; + +public class CamelCase { + public static String cAmEl(final String yourName) { + final int length = yourName.length(); + final StringBuilder cAmEl = new StringBuilder(length); + boolean upper = true; + for (int i = 0; i < length; i++, upper ^= true) { + final char c = yourName.charAt(i); + cAmEl.append(upper ? toUpperCase(c) : toLowerCase(c)); + } + return cAmEl.toString(); + } +} \ No newline at end of file diff --git a/can-you-get-the-loop/README.md b/can-you-get-the-loop/README.md new file mode 100644 index 0000000..d493984 --- /dev/null +++ b/can-you-get-the-loop/README.md @@ -0,0 +1,65 @@ +# Can you get the loop ? +[*View on Codewars*](https://www.codewars.com/kata/can-you-get-the-loop) + +You are given a node that is the beginning of a linked list. This list always contains a tail and a loop. + +Your objective is to determine the length of the loop. + +For example in the following picture the tail's size is 3 and the loop size is 11. + +
Image and video hosting by TinyPic
+ +```ruby +# Use the `next' method to get the following node. + +node.next +``` +```javascript +// Use the `getNext' method or 'next' property to get the following node. + +node.getNext() +node.next +``` +```python +# Use the `next' attribute to get the following node + +node.next +``` +```java +// Use the `getNext()` method to get the following node. + +node.getNext() +``` +```haskell +-- use the `next :: Node a -> Node a` function to get the following node +``` + +```cs +# Use the `next' method to get the following node. + +node.next +``` +~~~if:php +Use the `Node::getNext()` instance method to get the following node. + +```php +$node->getNext(); +``` +~~~ +~~~if:kotlin +Use the `Node.next` to get the next following node. + +```kotlin +node.next +``` +~~~ + +> Thanks to shadchnev, I broke all of the methods from the Hash class. + +> Don't miss dmitry's article in the discussion after you pass the Kata !! + +## Timeline +- Created: 2013-12-11 +- Published: 2013-12-12 +- Approved: 2013-12-18 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/can-you-get-the-loop/java/1/LoopInspector.java b/can-you-get-the-loop/java/1/LoopInspector.java new file mode 100644 index 0000000..cf6df98 --- /dev/null +++ b/can-you-get-the-loop/java/1/LoopInspector.java @@ -0,0 +1,16 @@ +import java.util.*; + +public class LoopInspector { + public int loopSize(Node node) { + final Set nodes = new LinkedHashSet<>(); + while(nodes.add(node)) { + node = node.getNext(); + } + final Iterator iterator = nodes.iterator(); + for (int i = 0;; i++) { + if (iterator.next() == node) { + return nodes.size() - i; + } + } + } +} \ No newline at end of file diff --git a/candy-problem/README.md b/candy-problem/README.md new file mode 100644 index 0000000..9436226 --- /dev/null +++ b/candy-problem/README.md @@ -0,0 +1,69 @@ +# Candy problem +[*View on Codewars*](https://www.codewars.com/kata/candy-problem) + +# Description +"It's the end of trick-or-treating and we have a list/array representing how much candy each child in our group has made out with. We don't want the kids to start arguing, and using our parental intuition we know trouble is brewing as many of the children in the group have received different amounts of candy from each home. + +So we want each child to have the same amount of candies, only we can't exactly take any candy away from the kids, that would be even worse. Instead we decide to give each child extra candy until they all have the same amount. +# Task +Your job is to find out how much candy each child has, and give them each additional candy until they too have as much as the child(ren) with the most candy. You also want to keep a total of how much candy you've handed out because reasons." + +Your job is to give all the kids the same amount of candies as the kid with the most candies and then return the total number candies that have been given out. If there are no kids, or only one, return -1. + +In the first case (look below) the most candies are given to second kid (i.e second place in list/array), 8. Because of that we will give the first kid 3 so he can have 8 and the third kid 2 and the fourth kid 4, so all kids will have 8 candies.So we end up handing out 3 + 2 + 4 = 9. + +```python +candies ([5,8,6,4]) # return 9 + +candies ([1,2,4,6]) # return 11 + +candies ([1,6]) # return 5 + +candies ([]) # return -1 + +candies ([6]) # return -1 (because only one kid) +``` +```ruby +candies ([5,8,6,4]) # return 9 + +candies ([1,2,4,6]) # return 11 + +candies ([]) # return -1 + +candies ([1,6]) # return 5 +``` +```javascript +candies ([5,8,6,4]) // return 9 + +candies ([1,2,4,6]) // return 11 + +candies ([]) // return -1 + +candies ([1,6]) // return 5 +``` +```cs +CandyProblem.GetMissingCandies(new [] {5, 6, 8, 4}) // return 9 + +CandyProblem.GetMissingCandies(new [] {1, 2, 4, 6}) // return 11 + +CandyProblem.GetMissingCandies(new [] { }) // return -1 + +CandyProblem.GetMissingCandies(new [] {1, 6}) // return 5 + +``` +```haskell +candies [5,8,6,4] -- return 9 + +candies [1,2,4,6] -- return 11 + +candies [] -- return -1 + +candies [1,6] -- return 5 +``` + + +## Timeline +- Created: 2015-05-03 +- Published: 2015-05-03 +- Approved: 2015-05-08 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/candy-problem/csharp/1/candy-problem b/candy-problem/csharp/1/candy-problem new file mode 100644 index 0000000..3fb1d87 --- /dev/null +++ b/candy-problem/csharp/1/candy-problem @@ -0,0 +1,19 @@ +using System.Linq; + +public class CandyProblem +{ + public static int GetMissingCandies(int[] candies) + { + if (candies.Length <= 1) + { + return -1; + } + var max = candies.Max(); + var count = 0; + foreach (var candy in candies) + { + count += max - candy; + } + return count; + } +} \ No newline at end of file diff --git a/candy-problem/csharp/2/candy-problem b/candy-problem/csharp/2/candy-problem new file mode 100644 index 0000000..d74a2c7 --- /dev/null +++ b/candy-problem/csharp/2/candy-problem @@ -0,0 +1,10 @@ +using System.Linq; + +public class CandyProblem +{ + public static int GetMissingCandies(int[] candies) + { + var length = candies.Length; + return length <= 1 ? -1 : candies.Max() * length - candies.Sum(); + } +} \ No newline at end of file diff --git a/car-depreciation/README.md b/car-depreciation/README.md new file mode 100644 index 0000000..81fa8c1 --- /dev/null +++ b/car-depreciation/README.md @@ -0,0 +1,18 @@ +# Car Depreciation +[*View on Codewars*](https://www.codewars.com/kata/car-depreciation) + +You own a great car website that helps people make decisions about buying the best new car for them. You decide that if you had a calculator on the website which lets people know their car's value after depreciation in a couple of years, would be a great idea! + +Write a function that takes the car's value when new (p) and return its value to 2 decimal places in the nth year (n). + +Yearly depreciation: +Year 1 = 20% +Year 2 = 20% +Year 3+ = 10% per year (ie. after 3 years the cars value depreciates 10% every year) + + +## Timeline +- Created: 2015-05-12 +- Published: 2015-05-12 +- Approved: null +- Completed: 2015-05-23 \ No newline at end of file diff --git a/car-depreciation/javascript/1/car-depreciation.js b/car-depreciation/javascript/1/car-depreciation.js new file mode 100644 index 0000000..3e1aed0 --- /dev/null +++ b/car-depreciation/javascript/1/car-depreciation.js @@ -0,0 +1,10 @@ +function car(p, n) { + for (var i = 1; i <= n; i++) { + p *= 1 - depreciation(i); + } + return p.toFixed(2); +} + +function depreciation(n) { + return n < 3 ? .2 : .1; +} \ No newline at end of file diff --git a/check-digit-1/README.md b/check-digit-1/README.md new file mode 100644 index 0000000..98aae0a --- /dev/null +++ b/check-digit-1/README.md @@ -0,0 +1,46 @@ +# Check digit +[*View on Codewars*](https://www.codewars.com/kata/check-digit-1) + +In this Kata, you will be given a ```number```, two indexes (```index1``` and ```index2```) and a ```digit``` to look for. Your task will be to check if the ```digit``` exists in the ```number```, within the ```indexes``` given. + +Be careful, the ```index2``` is not necessarily more than the ```index1```. + +``` + index1 == 2 and index2 == 5 -> snippet from 2 to 5 positons; + index1 == 5 and index2 == 2 -> snippet from 2 to 5 positons; + + number.length = 14; + + 0 <= index1 < 14; + + 0 <= index2 < 14; + + index2 is inclusive in search snippet; + + 0 <= digit <= 9; + +``` + +Find more details below: + +``` + + checkDigit(12345678912345, 1, 0, 1) -> true, 1 exists in 12 + + checkDigit(12345678912345, 0, 1, 2) -> true, 2 exists in 12 + + checkDigit(67845123654000, 4, 2, 5) -> true, 4 exists in 845 + + checkDigit(66688445364856, 0, 0, 6) -> true, 6 exists in 6 + + checkDigit(87996599994565, 2, 5, 1) -> false, 1 doesn't exist in 9965 + +``` + + + +## Timeline +- Created: 2017-12-11 +- Published: 2017-12-11 +- Approved: 2017-12-12 +- Completed: 2017-12-13 \ No newline at end of file diff --git a/check-digit-1/javascript/1/check-digit-1.js b/check-digit-1/javascript/1/check-digit-1.js new file mode 100644 index 0000000..cd03b9d --- /dev/null +++ b/check-digit-1/javascript/1/check-digit-1.js @@ -0,0 +1,12 @@ +function checkDigit(n, i1, i2, d) { + const { log10, min, max, pow, floor } = Math + const c = log10(n) | 0 + const i = min(i1, i2) + const j = max(i1, i2) + const l = n % pow(10, c - i + 1) + const r = floor(l / pow(10, c - j)) + const f = n => n < 10 + ? n === d + : n % 10 === d || f(floor(n / 10)) + return f(r) +} \ No newline at end of file diff --git a/checking-groups/README.md b/checking-groups/README.md new file mode 100644 index 0000000..05fa2f7 --- /dev/null +++ b/checking-groups/README.md @@ -0,0 +1,31 @@ +# Checking Groups +[*View on Codewars*](https://www.codewars.com/kata/checking-groups) + +In English and programming, groups can be made using symbols such as `()` and `{}` that change meaning. However, these groups must be closed in the correct order to maintain correct syntax. + +Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are done correctly: + +``` +({}) +[[]()] +[{()}] +``` + +The next are done incorrectly: +``` +{(}) +([] +[]) +``` + +A correct string cannot close groups in the wrong order, open a group but fail to close it, or close a group before it is opened. + +Your function will take an input string that may contain any of the symbols `()`, `{}` or `[]` to create groups. + +It should return `True` if the string is empty or otherwise grouped correctly, or `False` if it is grouped incorrectly. + +## Timeline +- Created: 2015-01-15 +- Published: 2015-01-15 +- Approved: 2015-05-08 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/checking-groups/java/1/Groups.java b/checking-groups/java/1/Groups.java new file mode 100644 index 0000000..df82dc4 --- /dev/null +++ b/checking-groups/java/1/Groups.java @@ -0,0 +1,42 @@ +import java.util.Deque; +import java.util.concurrent.LinkedBlockingDeque; + +public class Groups { + public static boolean groupCheck(final String s) { + final int length = s.length(); + final Deque openings = new LinkedBlockingDeque<>(length / 2); + for (int i = 0; i < length; i++) { + if (!groupCheck(openings, s.charAt(i))) { + return false; + } + } + return openings.isEmpty(); + } + + private static boolean groupCheck(final Deque openings, final char c) { + for (final Group group : Group.values()) { + if (group.opening == c) { + return openings.offerFirst(c); + } + if (group.closing == c) { + final Character bracket = openings.pollFirst(); + return bracket != null && group.opening == bracket; + } + } + return true; + } +} + +enum Group { + PARENTHESES('(', ')'), + BRACKETS('[', ']'), + BRACES('{', '}'); + + final char opening; + final char closing; + + Group(final char opening, final char closing) { + this.opening = opening; + this.closing = closing; + } +} \ No newline at end of file diff --git a/circularly-sorted-array/README.md b/circularly-sorted-array/README.md new file mode 100644 index 0000000..0f8a468 --- /dev/null +++ b/circularly-sorted-array/README.md @@ -0,0 +1,49 @@ +# Circularly Sorted Array +[*View on Codewars*](https://www.codewars.com/kata/circularly-sorted-array) + +Write a method, isCircleSorted(int[] A) (**Java**, **JavaScript**), or Array#circularly_sorted? (**Ruby**) that determines if A is +circularly sorted. An Array is circularly sorted if the elements are +sorted in ascending order, but displaced, or rotated, by any number of steps. + +For Example: + +```java +// True: +isCircleSorted([2,3,4,5,0,1]); +isCircleSorted([4,5,6,9,1]); +isCircleSorted([10,11,6,7,9]); +isCircleSorted([1,2,3,4,5]); +isCircleSorted([5,7,43,987,-9,0]); + + +// False: +isCircleSorted([4,1,2,5]); +isCircleSorted([8,7,6,5,4,3]); +isCircleSorted([6,7,4,8]); +isCircleSorted([7,6,5,4,3,2,1]); +``` +```javascript +// True: +isCircleSorted([2,3,4,5,0,1]); +isCircleSorted([4,5,6,9,1]); +isCircleSorted([10,11,6,7,9]); +isCircleSorted([1,2,3,4,5]); +isCircleSorted([5,7,43,987,-9,0]); + + +// False: +isCircleSorted([4,1,2,5]); +isCircleSorted([8,7,6,5,4,3]); +isCircleSorted([6,7,4,8]); +isCircleSorted([7,6,5,4,3,2,1]); +``` +```ruby +[2, 3, 4, 5, 0, 1].circularly_sorted? # true +[5, 4, 0, 1, 2, 3].circularly_sorted? # false +``` + +## Timeline +- Created: 2014-10-23 +- Published: 2014-10-23 +- Approved: 2014-12-28 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/circularly-sorted-array/java/1/CircleSorted.java b/circularly-sorted-array/java/1/CircleSorted.java new file mode 100644 index 0000000..3842480 --- /dev/null +++ b/circularly-sorted-array/java/1/CircleSorted.java @@ -0,0 +1,16 @@ +public class CircleSorted { + + public boolean isCircleSorted(int[] a) { + boolean jump = false; + for (int i = 0; i < a.length - 1; i++) { + if (a[i] > a[i + 1]) { + if (jump) { + return false; + } + jump = true; + } + } + return !jump || a[0] > a[a.length - 1]; + } + +} \ No newline at end of file diff --git a/circularly-sorted-array/javascript/1/circularly-sorted-array.js b/circularly-sorted-array/javascript/1/circularly-sorted-array.js new file mode 100644 index 0000000..6e9d1dc --- /dev/null +++ b/circularly-sorted-array/javascript/1/circularly-sorted-array.js @@ -0,0 +1,12 @@ +function isCircleSorted(arr) { + let jumped = false; + for (let i = 0; i < arr.length; i++) { + if (arr[i] > arr[(i + 1) % arr.length]) { + if (jumped) { + return false; + } + jumped = true; + } + } + return true; +} \ No newline at end of file diff --git a/clock-angle-problem/README.md b/clock-angle-problem/README.md new file mode 100644 index 0000000..fc3a60d --- /dev/null +++ b/clock-angle-problem/README.md @@ -0,0 +1,43 @@ +# Clock - angle problem +[*View on Codewars*](https://www.codewars.com/kata/clock-angle-problem) + +Couple of days ago, my close friend had an interview for the position of Software Engineer Intern in a small company in Germany. Today I asked him what were the questions. He told me that one of the tasks (which was considered as one of the quite challenging for beginners) was "Clock Angle Problem". Idea is the following: + +According to Wikipedia: Clock angle problem is a type of mathematical problem which involves finding the angles between the hands of an analog clock. Clock angle problems relate two different measurements: angles and time. The angle is typically measured in degrees from the mark of number 12 clockwise. The time is usually based on 12-hour clock. + +Your task is the following: Given a 12-hour analog clock, compute in degree the smaller angle between the hour and minute hands. + +###Examples + +```csharp +ClockProblem.calculateAngle(5,24) // => 18, as time is 5:24, angle is 18 degress +ClockProblem.calculateAngle(7,30) // => 45, as time is 7:30, angle is 45 degress +``` + +```java +ClockProblem.calculateAngle(5,24) // => 18, as time is 5:24, angle is 18 degress +ClockProblem.calculateAngle(7,30) // => 45, as time is 7:30, angle is 45 degress +``` + +```python +calculate_angle(5,24) # => 18, as time is 5:24, angle is 18 degress +calculate_angle(7,30) # => 45, as time is 7:30, angle is 45 degress +``` + +```ruby +calculate_angle(5,24) # => 18, as time is 5:24, angle is 18 degress +calculate_angle(7,30) # => 45, as time is 7:30, angle is 45 degress +``` + +```javascript +calculateAngle(5,24) // Time is 5:24, angle is 18 degress +calculateAngle(7,30) // Time is 7:30, angle is 45 degress +``` + + + +## Timeline +- Created: 2015-05-16 +- Published: 2015-05-16 +- Approved: null +- Completed: 2015-05-20 \ No newline at end of file diff --git a/clock-angle-problem/java/1/ClockProblem.java b/clock-angle-problem/java/1/ClockProblem.java new file mode 100644 index 0000000..2e58f54 --- /dev/null +++ b/clock-angle-problem/java/1/ClockProblem.java @@ -0,0 +1,8 @@ +public class ClockProblem { + public static int calculateAngle(int hour, int minute) { + int minuteAngle = minute * 6; + int hourAngle = hour % 12 * 30 + minute / 2; + int diffAngle = Math.abs(minuteAngle - hourAngle); + return diffAngle <= 90 ? diffAngle : 180 - diffAngle; + } +} \ No newline at end of file diff --git a/clock-angle-problem/java/2/ClockProblem.java b/clock-angle-problem/java/2/ClockProblem.java new file mode 100644 index 0000000..cee767e --- /dev/null +++ b/clock-angle-problem/java/2/ClockProblem.java @@ -0,0 +1,8 @@ +public class ClockProblem { + public static int calculateAngle(int hour, int minute) { + int minuteAngle = minute * 6; + int hourAngle = hour * 30 + minute / 2; + int diff = Math.abs(minuteAngle - hourAngle); + return diff <= 180 ? diff : 360 - diff; + } +} \ No newline at end of file diff --git a/codewars-style-ranking-system/README.md b/codewars-style-ranking-system/README.md new file mode 100644 index 0000000..2d703aa --- /dev/null +++ b/codewars-style-ranking-system/README.md @@ -0,0 +1,104 @@ +# Codewars style ranking system +[*View on Codewars*](https://www.codewars.com/kata/codewars-style-ranking-system) + +Write a class called User that is used to calculate the amount that a user will progress through a ranking system similar to the one Codewars uses. + +##### Business Rules: + +* A user starts at rank -8 and can progress all the way to 8. +* There is no 0 (zero) rank. The next rank after -1 is 1. +* Users will complete activities. These activities also have ranks. +* Each time the user completes a ranked activity the users rank progress is updated based off of the activity's rank +* The progress earned from the completed activity is relative to what the user's current rank is compared to the rank of the activity +* A user's rank progress starts off at zero, each time the progress reaches 100 the user's rank is upgraded to the next level +* Any remaining progress earned while in the previous rank will be applied towards the next rank's progress (we don't throw any progress away). The exception is if there is no other rank left to progress towards (Once you reach rank 8 there is no more progression). +* A user cannot progress beyond rank 8. +* The only acceptable range of rank values is -8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8. Any other value should raise an error. + +The progress is scored like so: + +* Completing an activity that is ranked the same as that of the user's will be worth 3 points +* Completing an activity that is ranked one ranking lower than the user's will be worth 1 point +* Any activities completed that are ranking 2 levels or more lower than the user's ranking will be ignored +* Completing an activity ranked higher than the current user's rank will accelerate the rank progression. The greater the difference between rankings the more the progression will be increased. The formula is `10 * d * d` where `d` equals the difference in ranking between the activity and the user. + +##### Logic Examples: +* If a user ranked -8 completes an activity ranked -7 they will receive 10 progress +* If a user ranked -8 completes an activity ranked -6 they will receive 40 progress +* If a user ranked -8 completes an activity ranked -5 they will receive 90 progress +* If a user ranked -8 completes an activity ranked -4 they will receive 160 progress, resulting in the user being upgraded to rank -7 and having earned 60 progress towards their next rank +* If a user ranked -1 completes an activity ranked 1 they will receive 10 progress (remember, zero rank is ignored) + +##### Code Usage Examples: +```javascript +var user = new User() +user.rank // => -8 +user.progress // => 0 +user.incProgress(-7) +user.progress // => 10 +user.incProgress(-5) // will add 90 progress +user.progress # => 0 // progress is now zero +user.rank # => -7 // rank was upgraded to -7 +``` +```coffeescript +user = new User() +user.rank # => -8 +user.progress # => 0 +user.incProgress(-7) +user.progress # => 10 +user.incProgress(-5) # will add 90 progress +user.progress # => 0 # progress is now zero +user.rank # => -7 # rank was upgraded to -7 +``` +```ruby +user = User.new +user.rank # => -8 +user.progress # => 0 +user.inc_progress(-7) +user.progress # => 10 +user.inc_progress(-5) # will add 90 progress +user.progress # => 0 # progress is now zero +user.rank # => -7 # rank was upgraded to -7 +``` +```python +user = User() +user.rank # => -8 +user.progress # => 0 +user.inc\_progress(-7) +user.progress # => 10 +user.inc\_progress(-5) # will add 90 progress +user.progress # => 0 # progress is now zero +user.rank # => -7 # rank was upgraded to -7 +``` +```java +User user = new User(); +user.rank; // => -8 +user.progress; // => 0 +user.incProgress(-7); +user.progress; // => 10 +user.incProgress(-5); // will add 90 progress +user.progress; // => 0 // progress is now zero +user.rank; // => -7 // rank was upgraded to -7 +``` +```haskell +rank newUser -- => -8 +progress newUser -- => 0 +let u2 = incProgress (-7) newUser +progress u2 -- => 10 +let u3 = incProgress (-5) u2 -- will add 90 progress +progress u3 -- => 0 -- progress is now zero +rank u3 -- => -7 -- rank was upgraded to -7 +``` + +~~~if:java +**Note:** In **Java** some methods may throw an `IllegalArgumentException`. +~~~ + +**Note**: Codewars no longer uses this algorithm for its own ranking system. It uses a pure Math based solution that gives consistent results no matter what order a set of ranked activities are completed at. + + +## Timeline +- Created: 2013-08-04 +- Published: 2013-08-22 +- Approved: null +- Completed: 2015-05-04 \ No newline at end of file diff --git a/codewars-style-ranking-system/java/1/User.java b/codewars-style-ranking-system/java/1/User.java new file mode 100644 index 0000000..98645a0 --- /dev/null +++ b/codewars-style-ranking-system/java/1/User.java @@ -0,0 +1,89 @@ +import java.util.HashMap; + +public class User { + private static final int POINTS_PER_RANK = 100; + + public int rank = Rank.KYU8.rank; + public int progress; + + public void incProgress(final int rank) { + Rank currentRank = Rank.fromRank(this.rank); + if (currentRank == Rank.DAN8) { + return; + } + final int points = currentRank.completeActivity(Rank.fromRank(rank)); + progress += points; + final int ranksUp = progress / POINTS_PER_RANK; + for (int i = 0; i < ranksUp; i++) { + currentRank = currentRank.next(); + this.rank = currentRank.rank; + } + progress = currentRank == Rank.DAN8 ? 0 : progress % POINTS_PER_RANK; + } + + private static enum Rank { + KYU8(-8, 0), + KYU7(-7, 1), + KYU6(-6, 2), + KYU5(-5, 3), + KYU4(-4, 4), + KYU3(-3, 5), + KYU2(-2, 6), + KYU1(-1, 7), + DAN1(1, 8), + DAN2(2, 9), + DAN3(3, 10), + DAN4(4, 11), + DAN5(5, 12), + DAN6(6, 13), + DAN7(7, 14), + DAN8(8, 15); + + private static final HashMap rankToRanks; + private static final HashMap orderToRanks; + + static { + final Rank[] values = values(); + rankToRanks = new HashMap<>(values.length); + orderToRanks = new HashMap<>(values.length); + for (final Rank rank : values) { + rankToRanks.put(rank.rank, rank); + orderToRanks.put(rank.order, rank); + } + } + + private static Rank fromRank(final int rank) { + if (!rankToRanks.containsKey(rank)) { + throw new IllegalArgumentException(String.format("Unknown rank: %d", rank)); + } + return rankToRanks.get(rank); + } + + private final int rank; + private final int order; + + private Rank(final int rank, final int order) { + this.rank = rank; + this.order = order; + } + + private int completeActivity(final Rank activityRank) { + final int orderDifference = activityRank.order - order; + if (orderDifference == 0) { + return 3; + } + if (orderDifference == -1) { + return 1; + } + if (orderDifference <= -2) { + return 0; + } + return 10 * orderDifference * orderDifference; + } + + private Rank next() { + final int next = order + 1; + return orderToRanks.containsKey(next) ? orderToRanks.get(next) : this; + } + } +} \ No newline at end of file diff --git a/collatz-conjecture-length/README.md b/collatz-conjecture-length/README.md new file mode 100644 index 0000000..c62877e --- /dev/null +++ b/collatz-conjecture-length/README.md @@ -0,0 +1,18 @@ +# Collatz Conjecture Length +[*View on Codewars*](https://www.codewars.com/kata/collatz-conjecture-length) + +The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. If you repeat the process continously for n, n will eventually reach 1. + +For example, if n = 20, the resulting sequence will be: + +[20, 10, 5, 16, 8, 4, 2, 1] + +Write a program that will output the length of the Collatz Conjecture for any given n. In the example above, the output would be 8. + +For more reading see: http://en.wikipedia.org/wiki/Collatz_conjecture + +## Timeline +- Created: 2015-03-08 +- Published: 2015-03-08 +- Approved: 2015-04-22 +- Completed: 2015-05-04 \ No newline at end of file diff --git a/collatz-conjecture-length/java/1/Collatz.java b/collatz-conjecture-length/java/1/Collatz.java new file mode 100644 index 0000000..f76b47d --- /dev/null +++ b/collatz-conjecture-length/java/1/Collatz.java @@ -0,0 +1,9 @@ +public class Collatz { + public static long conjecture(long x) { + return conjecture(x, 1); + } + + private static long conjecture(long x, long length) { + return x == 1 ? length : conjecture(x % 2 == 0 ? x / 2 : x * 3 + 1, length + 1); + } +} \ No newline at end of file diff --git a/collatz-conjecture-length/java/2/Collatz.java b/collatz-conjecture-length/java/2/Collatz.java new file mode 100644 index 0000000..7850150 --- /dev/null +++ b/collatz-conjecture-length/java/2/Collatz.java @@ -0,0 +1,5 @@ +public class Collatz { + public static long conjecture(long x) { + return 1 + (x == 1 ? 0 : conjecture(x % 2 == 0 ? x / 2 : x * 3 + 1)); + } +} \ No newline at end of file diff --git a/color-ghost/README.md b/color-ghost/README.md new file mode 100644 index 0000000..8c2b266 --- /dev/null +++ b/color-ghost/README.md @@ -0,0 +1,42 @@ +# Color Ghost +[*View on Codewars*](https://www.codewars.com/kata/color-ghost) + +# Color Ghost +Create a class Ghost + +Ghost objects are instantiated without any arguments. + +Ghost objects are given a random color attribute of white" or "yellow" or "purple" or "red" when instantiated + +```javascript +ghost = new Ghost(); +ghost.color //=> "white" or "yellow" or "purple" or "red" +``` +```coffeescript +ghost = new Ghost() +ghost.color #=> "white" or "yellow" or "purple" or "red" +``` +```ruby +ghost = Ghost.new +ghost.color #=> "white" or "yellow" or "purple" or "red" +``` +```python +ghost = Ghost() +ghost.color #=> "white" or "yellow" or "purple" or "red" +``` +```java +Ghost ghost = new Ghost(); +ghost.getColor(); //=> "white" or "yellow" or "purple" or "red" +``` +```c# +Ghost ghost = new Gost(); +ghost.GetColor(); // => "white" or "yellow" or "purple" or "red" +``` + + + +## Timeline +- Created: 2014-08-17 +- Published: 2014-08-17 +- Approved: 2014-08-27 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/color-ghost/java/1/Ghost.java b/color-ghost/java/1/Ghost.java new file mode 100644 index 0000000..759bd9f --- /dev/null +++ b/color-ghost/java/1/Ghost.java @@ -0,0 +1,13 @@ +public class Ghost { + static final String[] COLORS = {"white", "yellow", "purple", "red"}; + static int count; + final int color; + + Ghost() { + color = count = (count + 1) % COLORS.length; + } + + String getColor() { + return COLORS[color]; + } +} \ No newline at end of file diff --git a/common-denominators/README.md b/common-denominators/README.md new file mode 100644 index 0000000..31ea08d --- /dev/null +++ b/common-denominators/README.md @@ -0,0 +1,62 @@ +# Common Denominators +[*View on Codewars*](https://www.codewars.com/kata/common-denominators) + +Common denominators + + You will have a list of rationals in the form + ``` + { {numer_1, denom_1} , ... {numer_n, denom_n} } + ``` + or + ``` + [ [numer_1, denom_1] , ... [numer_n, denom_n] ] + ``` + or + ``` + [ (numer_1, denom_1) , ... (numer_n, denom_n) ] + ``` + + + where all numbers are positive ints. + + You have to produce a result in the form + ``` + (N_1, D) ... (N_n, D) + ``` + or + ``` + [ [N_1, D] ... [N_n, D] ] + ``` +or + ``` + [ (N_1', D) , ... (N_n, D) ] + ``` +or +``` +{{N_1, D} ... {N_n, D}} +``` +depending on the language (See Example tests) + + in which D is as small as possible + and + + ``` + N_1/D == numer_1/denom_1 ... N_n/D == numer_n,/denom_n. + ``` + +Example: + +``` +convertFracs [(1, 2), (1, 3), (1, 4)] `shouldBe` [(6, 12), (4, 12), (3, 12)] +``` + +# Note for Bash +input is a string, e.g `"2,4,2,6,2,8"` + +output is then `"6 12 4 12 3 12"` + +## Timeline +- Created: 2015-02-08 +- Published: 2015-02-08 +- Approved: 2015-04-11 +- Completed: 2015-05-04 \ No newline at end of file diff --git a/common-denominators/java/1/Fracts.java b/common-denominators/java/1/Fracts.java new file mode 100644 index 0000000..91fde18 --- /dev/null +++ b/common-denominators/java/1/Fracts.java @@ -0,0 +1,21 @@ +import static java.util.Arrays.stream; + +public class Fracts { + public static String convertFrac(final long[][] lst) { + final long commonDenominator = stream(lst).mapToLong(fract -> fract[1]).reduce(1, Fracts::lcm); + final long[] numerators = stream(lst).mapToLong(fract -> fract[0] * commonDenominator / fract[1]).toArray(); + final StringBuilder builder = new StringBuilder(); + for (final long numerator : numerators) { + builder.append('(').append(numerator).append(',').append(commonDenominator).append(')'); + } + return builder.toString(); + } + + private static long lcm(final long a, final long b) { + return a * (b / gcd(a, b)); + } + + private static long gcd(final long a, final long b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/common-denominators/java/2/Fracts.java b/common-denominators/java/2/Fracts.java new file mode 100644 index 0000000..558cb01 --- /dev/null +++ b/common-denominators/java/2/Fracts.java @@ -0,0 +1,18 @@ +import static java.util.Arrays.stream; + +public class Fracts { + public static String convertFrac(final long[][] lst) { + final long commonDenominator = stream(lst).mapToLong(fract -> fract[1]).reduce(1, Fracts::lcm); + final StringBuilder builder = new StringBuilder(); + stream(lst).mapToLong(fract -> fract[0] * commonDenominator / fract[1]).forEach(numerator -> builder.append('(').append(numerator).append(',').append(commonDenominator).append(')')); + return builder.toString(); + } + + private static long lcm(final long a, final long b) { + return a * (b / gcd(a, b)); + } + + private static long gcd(final long a, final long b) { + return b == 0 ? a : gcd(b, a % b); + } +} \ No newline at end of file diff --git a/complementary-dna/README.md b/complementary-dna/README.md new file mode 100644 index 0000000..4fccdf5 --- /dev/null +++ b/complementary-dna/README.md @@ -0,0 +1,72 @@ +# Complementary DNA +[*View on Codewars*](https://www.codewars.com/kata/complementary-dna) + +Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. + +If you want to know more http://en.wikipedia.org/wiki/DNA + +In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". +You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell). + + +```python +DNA_strand ("ATTGC") # return "TAACG" + +DNA_strand ("GTAT") # return "CATA" +``` + +```javascript +DNAStrand ("ATTGC") # return "TAACG" + +DNAStrand ("GTAT") # return "CATA" +``` + +```typescript +dnaStrand("ATTGC") # return "TAACG" + +dnaStrand("GTAT") # return "CATA" +``` + +```csharp +MakeComplement("ATTGC") => "TAACG" + +MakeComplement("GTAT") => "CATA" +``` + +```php +DNA_strand("ATTGC") // returns "TAACG" +DNA_strand("GTAT") // returns "CATA" +``` + +```ruby +DNA_strand ("ATTGC") # return "TAACG" + +DNA_strand ("GTAT") # return "CATA" +``` + +```crystal +dna_strand("ATTGC") # return "TAACG" + +dna_strand("GTAT") # return "CATA" +``` + +```java +DnaStrand.makeComplement("ATTGC") // return "TAACG" + +DnaStrand.makeComplement("GTAT") // return "CATA" +``` + +```haskell +dnaStrand [] `shouldBe` [] +dnaStrand [A,T,G,C] `shouldBe` [T,A,C,G] +dnaStrand [G,T,A,T] `shouldBe` [C,A,T,A] +dnaStrand [A,A,A,A] `shouldBe` [T,T,T,T] +``` + + + +## Timeline +- Created: 2015-05-09 +- Published: 2015-05-09 +- Approved: 2015-05-13 +- Completed: 2015-05-20 \ No newline at end of file diff --git a/complementary-dna/java/1/DnaStrand.java b/complementary-dna/java/1/DnaStrand.java new file mode 100644 index 0000000..088d3d8 --- /dev/null +++ b/complementary-dna/java/1/DnaStrand.java @@ -0,0 +1,9 @@ +public class DnaStrand { + public static String makeComplement(String dna) { + char[] complement = dna.toCharArray(); + for (int i = 0; i < complement.length; i++) { + complement[i] ^= (complement[i] & 0b10) == 0b10 ? 0b100 : 0b10101; + } + return String.valueOf(complement); + } +} \ No newline at end of file diff --git a/conversion-between-kilobyte-and-kibibyte/README.md b/conversion-between-kilobyte-and-kibibyte/README.md new file mode 100644 index 0000000..e6c7813 --- /dev/null +++ b/conversion-between-kilobyte-and-kibibyte/README.md @@ -0,0 +1,40 @@ +# Conversion between Kilobyte and KibiByte +[*View on Codewars*](https://www.codewars.com/kata/conversion-between-kilobyte-and-kibibyte) + +**Background** +You most probably know, that the *kilo* used by IT-People differs from the +*kilo* used by the rest of the world. Whereas *kilo* in kB is (mostly) intrepreted as 1024 Bytes (especially by operating systems) the non-IT *kilo* denotes the factor 1000 (as in "1 kg is 1000g"). The same goes for the prefixes mega, giga, tera, peta and so on. +To avoid misunderstandings (like your hardware shop selling you a 1E+12 Byte harddisk as 1 TB, whereas your Windows states that it has only 932 GB, because the shop uses factor 1000 whereas operating systems use factor 1024 by default) the International Electrotechnical Commission has proposed to use **kibibyte** for 1024 Byte.The according unit symbol would be **KiB**. Other Prefixes would be respectivly: + +``` +1 MiB = 1024 KiB +1 GiB = 1024 MiB +1 TiB = 1024 GiB +``` + +**Task** +Your task is to write a conversion function between the kB and the KiB-Units. The function receives as parameter a memory size including a unit and converts into the corresponding unit of the other system: + + +``` +memorysizeConversion ( "10 KiB") -> "10.24 kB" +memorysizeConversion ( "1 kB") -> "0.977 KiB" +memorysizeConversion ( "10 TB") -> "9.095 TiB" +memorysizeConversion ( "4.1 GiB") -> "4.402 GB" +``` + +**Hints** +- the parameter always contains a (fractioned) number, a whitespace and a valid unit +- units are case sensitive, valid units are **kB MB GB TB KiB MiB GiB TiB** +- result must be rounded to 3 decimals (round half up,no trailing zeros) see examples above + +**Resources** +If you want to read more on ...ibi-Units: +https://en.wikipedia.org/wiki/Kibibyte + + +## Timeline +- Created: 2017-11-19 +- Published: 2017-11-19 +- Approved: 2017-11-28 +- Completed: 2017-12-12 \ No newline at end of file diff --git a/conversion-between-kilobyte-and-kibibyte/javascript/1/conversion-between-kilobyte-and-kibibyte.js b/conversion-between-kilobyte-and-kibibyte/javascript/1/conversion-between-kilobyte-and-kibibyte.js new file mode 100644 index 0000000..b82830d --- /dev/null +++ b/conversion-between-kilobyte-and-kibibyte/javascript/1/conversion-between-kilobyte-and-kibibyte.js @@ -0,0 +1,15 @@ +const units = { + kB: [1 / 1.024, 'KiB'], + MB: [1 / Math.pow(1.024, 2), 'MiB'], + GB: [1 / Math.pow(1.024, 3), 'GiB'], + TB: [1 / Math.pow(1.024, 4), 'TiB'], + KiB: [1.024, 'kB'], + MiB: [Math.pow(1.024, 2), 'MB'], + GiB: [Math.pow(1.024, 3), 'GB'], + TiB: [Math.pow(1.024, 4), 'TB'] +} + +function memorysizeConversion(memorysize) { + const [f, u] = units[memorysize.substr(memorysize.indexOf(' ') + 1)] + return `${(f * parseFloat(memorysize)).toLocaleString('en', { maximumFractionDigits: 3 })} ${u}` +} \ No newline at end of file diff --git a/convert-a-boolean-to-a-string/README.md b/convert-a-boolean-to-a-string/README.md new file mode 100644 index 0000000..1481093 --- /dev/null +++ b/convert-a-boolean-to-a-string/README.md @@ -0,0 +1,19 @@ +# Convert a Boolean to a String +[*View on Codewars*](https://www.codewars.com/kata/convert-a-boolean-to-a-string) + +In this programming exercise, you're going to learn about functions, boolean (true/false) values, strings, and the if-statement. + +A **function** is a block of code that takes an _input_ and produces an _output_. In this example, `boolean_to_string` is a function whose _input_ is either _true_ or _false_, and whose _output_ is the string representation of the input, either _"true"_ or _"false"_. + +A common idea we often want to represent in code is the concept of _true_ and _false_. A variable that can either be _true_ or _false_ is called a **boolean** variable. In this example, the input to `boolean_to_string` (represented by the variable `b`) is a _boolean_. + +Lastly, when we want to take one action if a _boolean_ is _true_, and another if it is _false_, we use an **if-statement**. + +For this kata, don't worry about **edge cases** like where unexpected input is passed to the function. You'll get to worry about these enough in later exercises. + + +## Timeline +- Created: 2015-04-01 +- Published: 2015-04-01 +- Approved: 2015-10-07 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/convert-a-boolean-to-a-string/java/1/BooleanToString.java b/convert-a-boolean-to-a-string/java/1/BooleanToString.java new file mode 100644 index 0000000..cac9237 --- /dev/null +++ b/convert-a-boolean-to-a-string/java/1/BooleanToString.java @@ -0,0 +1,9 @@ +public class BooleanToString { + + public static String convert(boolean b){ + + return String.valueOf(b); + + } + +} \ No newline at end of file diff --git a/convert-a-linked-list-to-a-string/README.md b/convert-a-linked-list-to-a-string/README.md new file mode 100644 index 0000000..202b6ab --- /dev/null +++ b/convert-a-linked-list-to-a-string/README.md @@ -0,0 +1,322 @@ +# Convert a linked list to a string +[*View on Codewars*](https://www.codewars.com/kata/convert-a-linked-list-to-a-string) + +# Convert a linked list to a string + +## Related Kata + +Although this Kata is not part of an official Series, you may also want to try out [Parse a linked list from a string](https://www.codewars.com/kata/582c5382f000e535100001a7) if you enjoyed this Kata. + +## Preloaded + +Preloaded for you is a class/struct `Node` (depending on the language) used to construct linked lists in this Kata: + +```php +class Node { + public $data, $next; + public function __construct($data, $next = NULL) { + $this->data = $data; + $this->next = $next; + } +} +``` +```javascript +class Node { + constructor(data, next = null) { + this.data = data; + this.next = next; + } +} +``` +```csharp +public class Node { + public int Data { get; private set; } + public Node Next { get; private set; } + + public Node(int data, Node next = null) { + Data = data; + Next = next; + } +} +``` +```python +class Node(): + def __init__(self, data, next = None): + self.data = data + self.next = next +``` +```java +class Node { + private int data; + private Node next; + + public Node(int data, Node next) { + this.data = data; + this.next = next; + } + + public Node(int data) { + this.data = data; + this.next = null; + } + + public int getData() { + return data; + } + + public Node getNext() { + return next; + } +} +``` +```ruby +class Node + attr_reader :data, :next_node + + def initialize(data, next_node=nil) + @data = data + @next_node = next_node + end +end +``` +```cpp +class Node +{ + public: + int data; + Node* next; + + Node(int data, Node* next = nullptr) + { + this->data = data; + this->next = next; + } +}; +``` +```haskell +-- You can use regular lists, which are already singly-linked +data [a] = [] | a : [a] +``` +```objc +typedef struct node { + int data; + struct node *next; +} Node; +``` +```c +typedef struct node { + int data; + struct node *next; +} Node; +``` + +~~~if:objc +*NOTE: In Objective-C, the* `Node` *struct is placed on top of your main solution because there is a "double-import" bug in the Preloaded section at the time of writing (which cannot be fixed on my end). Attempts to modify it (e.g. to cheat the tests in some way) will likely result in a test crash so it is not recommended for you to modify that section ;)* +~~~ + +~~~if:c +*NOTE: In C, the* `Node` *struct is placed on top of your main solution (and the [Sample] Test Cases) because the compiler complains about not recognizing the* `Node` *datatype even after adding it to the Preloaded section. Attempts to modify it (e.g. to cheat the tests in some way) will likely result in a test crash so it is not recommended for you to modify that section ;)* +~~~ + +## Prerequisites + +This Kata assumes that you are already familiar with the idea of a linked list. If you do not know what that is, you may want to read up on [this article on Wikipedia](https://en.wikipedia.org/wiki/Linked_list). Specifically, the linked lists this Kata is referring to are **singly linked lists**, where the value of a specific node is stored in its `data`/`$data`/`Data` property, the reference to the next node is stored in its `next`/`$next`/`Next`/`next_node` property and the terminator for a list is `null`/`NULL`/`None`/`nil`/`nullptr`. + +Additionally, this Kata assumes that you have basic knowledge of Object-Oriented Programming (or a similar concept) in the programming language you are undertaking. If you have not come across Object-Oriented Programming in your selected language, you may want to try out an online course or read up on some code examples of OOP in your selected language up to (but not necessarily including) Classical Inheritance. + +*Specifically, if you are attempting this Kata in PHP and haven't come across OOP, you may want to try out the first 4 Kata in [this Series](https://www.codewars.com/collections/object-oriented-php).* + +## Task + +Create a function `stringify` which accepts an argument `list`/`$list` and returns a string representation of the list. The string representation of the list starts with the value of the current `Node`, specified by its `data`/`$data`/`Data` property, followed by a whitespace character, an arrow and another whitespace character (`" -> "`), followed by the rest of the list. The end of the string representation of a list must always end with `null`/`NULL`/`None`/`nil`/`nullptr` (all caps or all lowercase depending on the language you are undertaking this Kata in). For example, given the following list: + +```php +new Node(1, new Node(2, new Node(3))) +``` +```javascript +new Node(1, new Node(2, new Node(3))) +``` +```csharp +new Node(1, new Node(2, new Node(3))) +``` +```python +Node(1, Node(2, Node(3))) +``` +```java +new Node(1, new Node(2, new Node(3))) +``` +```ruby +Node.new(1, Node.new(2, Node.new(3))) +``` +```cpp +new Node(1, new Node(2, new Node(3))) +``` +```haskell +[1,2,3] +``` +```objc +&((Node){ + .data = 1, + .next = &((Node){ + .data = 2, + .next = &((Node){ + .data = 3, + .next = NULL + }) + }) +}) +``` +```c +&((Node){ + .data = 1, + .next = &((Node){ + .data = 2, + .next = &((Node){ + .data = 3, + .next = NULL + }) + }) +}) +``` + + +... its string representation would be: + +```php +"1 -> 2 -> 3 -> NULL" +``` +```c +"1 -> 2 -> 3 -> NULL" +``` +```javascript +"1 -> 2 -> 3 -> null" +``` +```csharp +"1 -> 2 -> 3 -> null" +``` +```python +"1 -> 2 -> 3 -> None" +``` +```java +"1 -> 2 -> 3 -> null" +``` +```ruby +"1 -> 2 -> 3 -> nil" +``` +```cpp +"1 -> 2 -> 3 -> nullptr" +``` +```haskell +"1 -> 2 -> 3 -> null" +``` +```objc +@"1 -> 2 -> 3 -> NULL" +``` + +And given the following linked list: + +```php +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```javascript +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```csharp +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```python +Node(0, Node(1, Node(4, Node(9, Node(16))))) +``` +```java +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```ruby +Node.new(0, Node.new(1, Node.new(4, Node.new(9, Node.new(16))))) +``` +```cpp +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```haskell +[0,1,4,9,16] +``` +```objc +&((Node){ + .data = 0, + .next = &((Node){ + .data = 1, + .next = &((Node){ + .data = 4, + .next = &((Node){ + .data = 9, + .next = &((Node){ + .data = 16, + .next = NULL + }) + }) + }) + }) +}) +``` +```c +&((Node){ + .data = 0, + .next = &((Node){ + .data = 1, + .next = &((Node){ + .data = 4, + .next = &((Node){ + .data = 9, + .next = &((Node){ + .data = 16, + .next = NULL + }) + }) + }) + }) +}) +``` + +... its string representation would be: + +```php +"0 -> 1 -> 4 -> 9 -> 16 -> NULL" +``` +```c +"0 -> 1 -> 4 -> 9 -> 16 -> NULL" +``` +```javascript +"0 -> 1 -> 4 -> 9 -> 16 -> null" +``` +```csharp +"0 -> 1 -> 4 -> 9 -> 16 -> null" +``` +```python +"0 -> 1 -> 4 -> 9 -> 16 -> None" +``` +```java +"0 -> 1 -> 4 -> 9 -> 16 -> null" +``` +```ruby +"0 -> 1 -> 4 -> 9 -> 16 -> nil" +``` +```cpp +"0 -> 1 -> 4 -> 9 -> 16 -> nullptr" +``` +```haskell +"0 -> 1 -> 4 -> 9 -> 16 -> null" +``` +```objc +@"0 -> 1 -> 4 -> 9 -> 16 -> NULL" +``` + +Note that `null`/`NULL`/`None`/`nil`/`nullptr` itself is also considered a valid linked list. In that case, its string representation would simply be `"null"`/`"NULL"`/`"None"`/`"nil"`/`"nullptr"`/`@"NULL"` (again, depending on the language). + +For the simplicity of this Kata, you may assume that any `Node` in this Kata may only contain **non-negative integer** values. For example, you will not encounter a `Node` whose `data`/`$data`/`Data` property is `"Hello World"`. + +Enjoy, and don't forget to check out my other Kata Series :D + +## Timeline +- Created: 2016-11-16 +- Published: 2016-11-16 +- Approved: 2016-11-20 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/convert-a-linked-list-to-a-string/java/1/Kata.java b/convert-a-linked-list-to-a-string/java/1/Kata.java new file mode 100644 index 0000000..a01fcad --- /dev/null +++ b/convert-a-linked-list-to-a-string/java/1/Kata.java @@ -0,0 +1,7 @@ +public class Kata { + + public static String stringify(Node list) { + return list == null ? "null" : list.getData() + " -> " + stringify(list.getNext()); + } + +} \ No newline at end of file diff --git a/convert-a-linked-list-to-a-string/javascript/1/convert-a-linked-list-to-a-string.js b/convert-a-linked-list-to-a-string/javascript/1/convert-a-linked-list-to-a-string.js new file mode 100644 index 0000000..ae2b5c1 --- /dev/null +++ b/convert-a-linked-list-to-a-string/javascript/1/convert-a-linked-list-to-a-string.js @@ -0,0 +1,3 @@ +function stringify(list) { + return list===null?"null":list.data+" -> "+stringify(list.next) +} \ No newline at end of file diff --git a/convert-a-number-to-a-string/README.md b/convert-a-number-to-a-string/README.md new file mode 100644 index 0000000..eb88bef --- /dev/null +++ b/convert-a-number-to-a-string/README.md @@ -0,0 +1,45 @@ +# Convert a Number to a String! +[*View on Codewars*](https://www.codewars.com/kata/convert-a-number-to-a-string) + +We need a function that can transform a number into a string. + +What ways of achieving this do you know? + +#### Examples: + +```clojure +number-to-string 123 ;; returns '123' +number-to-string 999 ;; returns '999' +``` +```csharp +Kata.NumberToString(123) => "123"; +Kata.NumberToString(999) => "999"; +``` +```elixir +Stringify.number_to_string(123) #=> "123" +Stringify.number_to_string(999) #=> "999" +``` +```java +Kata.numberToString(123); // returns "123"; +Kata.numberToString(999); // returns "999"; +``` +```javascript +numberToString(123); // returns '123';` +numberToString(999); // returns '999';` +``` +```python +number_to_string(123) /* returns '123' */ +number_to_string(999) /* returns '999' */ +``` +```rust +number_to_string(123) //=> "123" +number_to_string(999) //=> "999" +``` + + + +## Timeline +- Created: 2013-10-21 +- Published: 2013-10-25 +- Approved: null +- Completed: 2014-01-21 \ No newline at end of file diff --git a/convert-a-number-to-a-string/javascript/1/convert-a-number-to-a-string.js b/convert-a-number-to-a-string/javascript/1/convert-a-number-to-a-string.js new file mode 100644 index 0000000..02029d0 --- /dev/null +++ b/convert-a-number-to-a-string/javascript/1/convert-a-number-to-a-string.js @@ -0,0 +1,3 @@ +function numberToString(num) { + return num + ''; +} \ No newline at end of file diff --git a/convert-a-string-to-a-number/README.md b/convert-a-string-to-a-number/README.md new file mode 100644 index 0000000..093ee7b --- /dev/null +++ b/convert-a-string-to-a-number/README.md @@ -0,0 +1,87 @@ +# Convert a String to a Number! +[*View on Codewars*](https://www.codewars.com/kata/convert-a-string-to-a-number) + +Note: This kata is inspired by [Convert a Number to a String!](http://www.codewars.com/kata/convert-a-number-to-a-string/). Try that one too. + +## Description + +We need a function that can transform a string into a number. What ways of achieving this do you know? + +Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number. + +## Examples +```haskell +stringToNumber "1234" == 1234 +stringToNumber "605" == 605 +stringToNumber "1405" == 1405 +stringToNumber "-7" == -7 +``` + +```clojure +(stringToNumber "1234") => 1234 +(stringToNumber "605") => 605 +(stringToNumber "1405") => 1405 +(stringToNumber "-7") => -7 +``` +```javascript +stringToNumber("1234") == 1234 +stringToNumber("605" ) == 605 +stringToNumber("1405") == 1405 +stringToNumber("-7" ) == -7 +``` +```java +stringToNumber("1234") == 1234 +stringToNumber("605" ) == 605 +stringToNumber("1405") == 1405 +stringToNumber("-7" ) == -7 +``` +```coffeescript +stringToNumber "1234" == 1234 +stringToNumber "605" == 605 +stringToNumber "1405" == 1405 +stringToNumber "-7" == -7 +``` +```python +stringToNumber("1234") == 1234 +stringToNumber("605" ) == 605 +stringToNumber("1405") == 1405 +stringToNumber("-7" ) == -7 +``` +```ruby +string_to_number "1234" == 1234 +string_to_number "605" == 605 +string_to_number "1405" == 1405 +string_to_number "-7" == -7 +``` +```csharp +StringToNumber("1234") == 1234 +StringToNumber("605") == 605 +StringToNumber("1405") == 1405 +StringToNumber("-7") == -7 +``` +```elixir +string_to_number "1234" == 1234 +string_to_number "605" == 605 +string_to_number "1405" == 1405 +string_to_number "-7" == -7 +``` +```c++ +string_to_number("1234") == 1234 +string_to_number("605") == 605 +string_to_number("1405") == 1405 +string_to_number("-7") == -7 +``` +```rust +string_to_number("1234") == 1234 +string_to_number("605") == 605 +string_to_number("1405") == 1405 +string_to_number("-7") == -7 +``` + + + +## Timeline +- Created: 2014-10-21 +- Published: 2014-11-04 +- Approved: 2014-11-06 +- Completed: 2015-05-07 \ No newline at end of file diff --git a/convert-a-string-to-a-number/java/1/StringToNumber.java b/convert-a-string-to-a-number/java/1/StringToNumber.java new file mode 100644 index 0000000..7054dac --- /dev/null +++ b/convert-a-string-to-a-number/java/1/StringToNumber.java @@ -0,0 +1,5 @@ +public class StringToNumber { + public static int stringToNumber(String str) { + return Integer.parseInt(str); + } +} \ No newline at end of file diff --git a/convert-number-to-reversed-array-of-digits/README.md b/convert-number-to-reversed-array-of-digits/README.md new file mode 100644 index 0000000..06f1310 --- /dev/null +++ b/convert-number-to-reversed-array-of-digits/README.md @@ -0,0 +1,24 @@ +# Convert number to reversed array of digits +[*View on Codewars*](https://www.codewars.com/kata/convert-number-to-reversed-array-of-digits) + +# Convert number to reversed array of digits + +Given a random number: +
    +
  • C#: long;
  • +
  • C++: unsigned long;
  • +
+ +You have to return the digits of this number within an array in reverse order. + +## Example: + +``` +348597 => [7,9,5,8,4,3] +``` + +## Timeline +- Created: 2015-06-18 +- Published: 2015-06-18 +- Approved: 2015-07-03 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/convert-number-to-reversed-array-of-digits/java/1/Kata.java b/convert-number-to-reversed-array-of-digits/java/1/Kata.java new file mode 100644 index 0000000..1530051 --- /dev/null +++ b/convert-number-to-reversed-array-of-digits/java/1/Kata.java @@ -0,0 +1,10 @@ +class Kata { + public static int[] digitize(long n) { + int length = n == 0 ? 1 : (int) Math.log10(n) + 1; + int[] digits = new int[length]; + for (int i = 0; i < length; i++, n /= 10) { + digits[i] = (int) (n % 10); + } + return digits; + } +} \ No newline at end of file diff --git a/convert-number-to-reversed-array-of-digits/javascript/1/convert-number-to-reversed-array-of-digits.js b/convert-number-to-reversed-array-of-digits/javascript/1/convert-number-to-reversed-array-of-digits.js new file mode 100644 index 0000000..b3cae89 --- /dev/null +++ b/convert-number-to-reversed-array-of-digits/javascript/1/convert-number-to-reversed-array-of-digits.js @@ -0,0 +1,3 @@ +function digitize(n) { + return n === 0 ? [] : [ n % 10, ...digitize(Math.trunc(n / 10)) ] +} \ No newline at end of file diff --git a/convert-time-to-string/README.md b/convert-time-to-string/README.md new file mode 100644 index 0000000..938d42d --- /dev/null +++ b/convert-time-to-string/README.md @@ -0,0 +1,29 @@ +# Convert Time to String +[*View on Codewars*](https://www.codewars.com/kata/convert-time-to-string) + +Given time in seconds, return formatted string, as shown in following example: + +####Example: +Input: `90061` sec + +Output: `1 1 1 1` + +e.g + +- 90061 sec: 1 1 1 1 (1 day, 1 hour, 1 min and 1 seconds) +- 93784 sec: 1 2 3 4 (1 day, 2 hours, 3 mins, 4 seconds) + +####Useful conversions: +``` +60 sec = 1 min +60 min = 1 hour +24 hour = 1 day +``` + +*Please see included test case for an example.* + +## Timeline +- Created: 2015-03-13 +- Published: 2015-03-13 +- Approved: 2016-11-13 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/convert-time-to-string/java/1/TimeUtils.java b/convert-time-to-string/java/1/TimeUtils.java new file mode 100644 index 0000000..322958a --- /dev/null +++ b/convert-time-to-string/java/1/TimeUtils.java @@ -0,0 +1,17 @@ +class TimeUtils { + public static int MIN_TO_SECS = 60; + public static int HOUR_TO_MINS = 60; + public static int DAY_TO_HOURS = 24; + + public static String convertTime(int timeDiff) { + int totalSeconds = timeDiff; + int noOfSeconds = totalSeconds % MIN_TO_SECS; + int totalMinutes = totalSeconds / MIN_TO_SECS; + int noOfMinutes = totalMinutes % HOUR_TO_MINS; + int totalHours = totalMinutes / HOUR_TO_MINS; + int noOfHours = totalHours % DAY_TO_HOURS; + int totalDays = totalHours / DAY_TO_HOURS; + int noOfDays = totalDays; + return String.format("%d %d %d %d", noOfDays, noOfHours, noOfMinutes, noOfSeconds); + } +} \ No newline at end of file diff --git a/coordinates-validator/README.md b/coordinates-validator/README.md new file mode 100644 index 0000000..7d5a7b9 --- /dev/null +++ b/coordinates-validator/README.md @@ -0,0 +1,38 @@ +# Coordinates Validator +[*View on Codewars*](https://www.codewars.com/kata/coordinates-validator) + +You need to create a function that will validate if given parameters are valid geographical coordinates. + +Valid coordinates look like the following: __"23.32353342, -32.543534534"__. +The return value should be either __true__ or __false__. + +Latitude (which is first float) can be between 0 and 90, positive or negative. +Longitude (which is second float) can be between 0 and 180, positive or negative. + +Coordinates can only contain digits, or one of the following symbols (including space after comma) __ -, . __ + +There should be no space between the minus "-" sign and the digit after it. + +Here are some valid coordinates: + +* -23, 25 +* 24.53525235, 23.45235 +* 04, -23.234235 +* 43.91343345, 143 +* 4, -3 + +And some invalid ones: + +* 23.234, - 23.4234 +* 2342.43536, 34.324236 +* N23.43345, E32.6457 +* 99.234, 12.324 +* 6.325624, 43.34345.345 +* 0, 1,2 +* 0.342q0832, 1.2324 + +## Timeline +- Created: 2013-10-24 +- Published: 2013-10-24 +- Approved: 2013-12-01 +- Completed: 2015-05-25 \ No newline at end of file diff --git a/coordinates-validator/javascript/1/coordinates-validator.js b/coordinates-validator/javascript/1/coordinates-validator.js new file mode 100644 index 0000000..371139a --- /dev/null +++ b/coordinates-validator/javascript/1/coordinates-validator.js @@ -0,0 +1,4 @@ +function isValidCoordinates(coordinates) { + var match = coordinates.match(/^(-?\d+(?:\.\d+)?), ?(-?\d+(?:\.\d+)?)$/); + return !!match && Math.abs(parseFloat(match[1])) <= 90 && Math.abs(parseFloat(match[2])) <= 180; +} \ No newline at end of file diff --git a/counting-power-sets/README.md b/counting-power-sets/README.md new file mode 100644 index 0000000..43534c2 --- /dev/null +++ b/counting-power-sets/README.md @@ -0,0 +1,57 @@ +# Counting power sets +[*View on Codewars*](https://www.codewars.com/kata/counting-power-sets) + +In this kata, you must create a function `powers`/`Powers` that takes an array, and returns the number of subsets possible to create from that list. In other words, counts the power sets. + +For instance +```coffeescript +powers([1,2,3]) => 8 +``` + +...due to... +```coffeescript +powers([1,2,3]) => +[[], + [1], + [2], + [3], + [1,2], + [2,3], + [1,3], + [1,2,3]] +``` + +Your function should be able to count sets up to the size of 500, so watch out; pretty big numbers occur there! + +For comparison, my Haskell solution can compute the number of sets for an array of length 90 000 in less than a second, so be quick! + +You should treat each array passed as a set of unique values for this kata. + +----- +###Examples: +```coffeescript +powers([]) => 1 +powers([1]) => 2 +powers([1,2]) => 4 +powers([1,2,3,4]) => 16 +``` +```java +Powers.powers(new int[]{}); // 1 +Powers.powers(new int[]{1}); // 2 +Powers.powers(new int[]{1,2}); // 4 +Powers.powers(new int[]{1,2,3,4}); // 16 +``` +```csharp +Kata.Powers(new int[] {}) => 1 +Kata.Powers(new int[] {1}) => 2 +Kata.Powers(new int[] {1,2}) => 4 +Kata.Powers(new int[] {1,2,3,4}) => 16 +``` +----- +Inspired by [this kata](http://www.codewars.com/kata/by-the-power-set-of-castle-grayskull) by [xcuthulu](http://www.codewars.com/users/xcthulhu) - refer to it if you're stuck! + +## Timeline +- Created: 2014-10-10 +- Published: 2014-10-10 +- Approved: 2014-10-19 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/counting-power-sets/java/1/Powers.java b/counting-power-sets/java/1/Powers.java new file mode 100644 index 0000000..dd2f57f --- /dev/null +++ b/counting-power-sets/java/1/Powers.java @@ -0,0 +1,7 @@ +import java.math.BigInteger; + +public class Powers { + public static BigInteger powers(int[] list) { + return BigInteger.valueOf(2).pow(list.length); + } +} \ No newline at end of file diff --git a/credit-card-mask/README.md b/credit-card-mask/README.md new file mode 100644 index 0000000..9c9e43e --- /dev/null +++ b/credit-card-mask/README.md @@ -0,0 +1,87 @@ +# Credit Card Mask +[*View on Codewars*](https://www.codewars.com/kata/credit-card-mask) + +Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it. + +Your task is to write a function `maskify`, which changes all but the last four characters into `'#'`. + +## Examples +```javascript +maskify("4556364607935616") == "############5616" +maskify( "64607935616") == "#######5616" +maskify( "1") == "1" +maskify( "") == "" + +// "What was the name of your first pet?" +maskify("Skippy") == "##ippy" +maskify("Nananananananananananananananana Batman!") == "####################################man!" +``` +```coffeescript +maskify("4556364607935616") == "############5616" +maskify( "64607935616") == "#######5616" +maskify( "1") == "1" +maskify( "") == "" + +# "What was the name of your first pet?" +maskify("Skippy") == "##ippy" +maskify("Nananananananananananananananana Batman!") == "####################################man!" +``` +```python +maskify("4556364607935616") == "############5616" +maskify( "64607935616") == "#######5616" +maskify( "1") == "1" +maskify( "") == "" + +# "What was the name of your first pet?" +maskify("Skippy") == "##ippy" +maskify("Nananananananananananananananana Batman!") == "####################################man!" +``` +```haskell +maskify "4556364607935616" == "############5616" +maskify "64607935616" == "#######5616" +maskify "1" == "1" +maskify "" == "" + +-- "What was the name of your first pet?" +maskify "Skippy" == "##ippy" +maskify "Nananananananananananananananana Batman!" + -- "####################################man!" +``` +```ruby +maskify('4556364607935616') # should return '############5616' +maskify('64607935616') # should return '#######5616' +maskify('1') # should return '1' +maskify('') # should return '' + +# "What was the name of your first pet?" +maskify('Skippy') # should return '##ippy' +maskify('Nananananananananananananananana Batman!') # should return '####################################man!' +``` + +```csharp +Kata.Maskify('4556364607935616'); // should return "############5616" +Kata.Maskify('64607935616'); // should return "#######5616" +Kata.Maskify('1'); // should return "1" +Kata.Maskify(''); // should return "" + +// "What was the name of your first pet?" +Kata.Maskify('Skippy'); // should return "##ippy" +Kata.Maskify('Nananananananananananananananana Batman!'); // should return "####################################man!" +``` + +```java +Maskify.Maskify("4556364607935616"); // should return "############5616" +Maskify.Maskify("64607935616"); // should return "#######5616" +Maskify.Maskify("1"); // should return "1" +Maskify.Maskify(""); // should return "" + +// "What was the name of your first pet?" +Maskify.Maskify("Skippy"); // should return "##ippy" +Maskify.Maskify("Nananananananananananananananana Batman!"); // should return "####################################man!" +``` + +## Timeline +- Created: 2014-09-12 +- Published: 2014-09-16 +- Approved: 2015-03-19 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/credit-card-mask/csharp/1/credit-card-mask b/credit-card-mask/csharp/1/credit-card-mask new file mode 100644 index 0000000..6ee67fc --- /dev/null +++ b/credit-card-mask/csharp/1/credit-card-mask @@ -0,0 +1,12 @@ +public static class Kata +{ + public static string Maskify(string cc) + { + char[] ccc = cc.ToCharArray(); + for (int i = 0, m = ccc.Length - 4; i < m; i++) + { + ccc[i] = '#'; + } + return new string(ccc); + } +} \ No newline at end of file diff --git a/decode-the-morse-code-advanced/README.md b/decode-the-morse-code-advanced/README.md new file mode 100644 index 0000000..27630f2 --- /dev/null +++ b/decode-the-morse-code-advanced/README.md @@ -0,0 +1,45 @@ +# Decode the Morse code, advanced +[*View on Codewars*](https://www.codewars.com/kata/decode-the-morse-code-advanced) + +
Part of Series 2/3
This kata is part of a series on the Morse code. Make sure you solve the [previous part](/kata/decode-the-morse-code) before you try this one. After you solve this kata, you may move to the [next one](/kata/decode-the-morse-code-for-real).

+In this kata you have to write a Morse code decoder for wired electrical telegraph. + +Electric telegraph is operated on a 2-wire line with a key that, when pressed, connects the wires together, which can be detected on a remote station. The Morse code encodes every character being transmitted as a sequence of "dots" (short presses on the key) and "dashes" (long presses on the key). + +When transmitting the Morse code, the international standard specifies that: +
  • "Dot" – is 1 time unit long.
  • +
  • "Dash" – is 3 time units long.
  • +
  • Pause between dots and dashes in a character – is 1 time unit long.
  • +
  • Pause between characters inside a word – is 3 time units long.
  • +
  • Pause between words – is 7 time units long.
+ +However, the standard does not specify how long that "time unit" is. And in fact different operators would transmit at different speed. An amateur person may need a few seconds to transmit a single character, a skilled professional can transmit 60 words per minute, and robotic transmitters may go way faster. + +For this kata we assume the message receiving is performed automatically by the hardware that checks the line periodically, and if the line is connected (the key at the remote station is down), 1 is recorded, and if the line is not connected (remote key is up), 0 is recorded. After the message is fully received, it gets to you for decoding as a string containing only symbols 0 and 1. + +For example, the message HEY JUDE, that is ···· · −·−−   ·−−− ··− −·· · may be received as follows: + +1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011 + +As you may see, this transmission is perfectly accurate according to the standard, and the hardware sampled the line exactly two times per "dot". + +That said, your task is to implement two functions: + +1. Function decodeBits(bits), that should find out the transmission rate of the message, correctly decode the message to dots ., dashes - and spaces (one between characters, three between words) and return those as a string. Note that some extra 0's may naturally occur at the beginning and the end of a message, make sure to ignore them. Also if you have trouble discerning if the particular sequence of 1's is a dot or a dash, assume it's a dot. + +2. Function decodeMorse(morseCode), that would take the output of the previous function and return a human-readable string. + +The Morse code table is preloaded for you as MORSE_CODE dictionary; in Java MorseCode class is provided; in Haskell the codes are in a Map String String and can be accessed like this: morseCodes ! ".--" - feel free to use it. + +All the test strings would be valid to the point that they could be reliably decoded as described above, so you may skip checking for errors and exceptions, just do your best in figuring out what the message is! + +Good luck! + +After you master this kata, you may try to Decode the Morse code, for real. + + +## Timeline +- Created: 2015-01-15 +- Published: 2015-01-15 +- Approved: 2015-03-15 +- Completed: 2015-05-01 \ No newline at end of file diff --git a/decode-the-morse-code-advanced/java/1/MorseCodeDecoder.java b/decode-the-morse-code-advanced/java/1/MorseCodeDecoder.java new file mode 100644 index 0000000..606a8dd --- /dev/null +++ b/decode-the-morse-code-advanced/java/1/MorseCodeDecoder.java @@ -0,0 +1,186 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +public class MorseCodeDecoder { + public static final char BIT_OFF = '0'; + public static final char BIT_ON = '1'; + + public static final int BIT_LETTER_PART_DOT_LENGTH = 1; + public static final int BIT_LETTER_PART_DASH_LENGTH = 3; + + public static final String BIT_LETTER_PART_DOT = repeat(BIT_ON, BIT_LETTER_PART_DOT_LENGTH); + public static final String BIT_LETTER_PART_DASH = repeat(BIT_ON, BIT_LETTER_PART_DASH_LENGTH); + + public static final int BIT_LETTER_PART_PAUSE_LENGTH = 1; + public static final int BIT_LETTER_PAUSE_LENGTH = 3; + public static final int BIT_WORD_PAUSE_LENGTH = 7; + + public static final String BIT_LETTER_PART_PAUSE = repeat(BIT_OFF, BIT_LETTER_PART_PAUSE_LENGTH); + public static final String BIT_LETTER_PAUSE = repeat(BIT_OFF, BIT_LETTER_PAUSE_LENGTH); + public static final String BIT_WORD_PAUSE = repeat(BIT_OFF, BIT_WORD_PAUSE_LENGTH); + + public static final char MORSE_DOT = '.'; + public static final char MORSE_DASH = '-'; + public static final char MORSE_DELIMITER = ' '; + + public static final int MORSE_LETTER_DELIMITER_LENGTH = 1; + public static final int MORSE_WORD_DELIMITER_LENGTH = 3; + + public static final String MORSE_LETTER_DELIMITER = repeat(MORSE_DELIMITER, MORSE_LETTER_DELIMITER_LENGTH); + public static final String MORSE_WORD_DELIMITER = repeat(MORSE_DELIMITER, MORSE_WORD_DELIMITER_LENGTH); + + public static final String WORD_DELIMITER = " "; + + private static final Map BIT_TO_MORSE; + + static { + final Map bitToMorse = new HashMap<>(2, 1); + bitToMorse.put(BIT_LETTER_PART_DOT, MORSE_DOT); + bitToMorse.put(BIT_LETTER_PART_DASH, MORSE_DASH); + BIT_TO_MORSE = Collections.unmodifiableMap(bitToMorse); + } + + public static String decodeBits(final String bits) { + final StringBuilder morseBuilder = new StringBuilder(); + final String normalizedBits = normalize(bits); + final String[] bitWords = normalizedBits.split(BIT_WORD_PAUSE); + for (final String bitWord : bitWords) { + if (morseBuilder.length() > 0) { + morseBuilder.append(MORSE_WORD_DELIMITER); + } + final StringBuilder wordBuilder = new StringBuilder(); + final String[] bitLetters = bitWord.split(BIT_LETTER_PAUSE); + for (final String bitLetter : bitLetters) { + if (wordBuilder.length() > 0) { + wordBuilder.append(MORSE_LETTER_DELIMITER); + } + final StringBuilder letterBuilder = new StringBuilder(); + final String[] bitLetterParts = bitLetter.split(BIT_LETTER_PART_PAUSE); + for (final String bitLetterPart : bitLetterParts) { + final char morseSignal = BIT_TO_MORSE.getOrDefault(bitLetterPart, '?'); + letterBuilder.append(morseSignal); + } + wordBuilder.append(letterBuilder); + } + morseBuilder.append(wordBuilder); + } + return morseBuilder.toString(); + } + + public static String decodeMorse(final String morseCode) { + final StringBuilder decodeBuilder = new StringBuilder(); + for (final String morseWord : morseCode.trim().split(MORSE_WORD_DELIMITER)) { + if (decodeBuilder.length() > 0) { + decodeBuilder.append(WORD_DELIMITER); + } + for (final String morseLetter : morseWord.split(MORSE_LETTER_DELIMITER)) { + decodeBuilder.append(MorseCode.get(morseLetter)); + } + } + return decodeBuilder.toString(); + } + + static String normalize(final String bits) { + final String trimmedBits = trim(bits, BIT_OFF); + final int transmissionRate = getTransmissionRate(trimmedBits); + if (transmissionRate <= 1) { + return trimmedBits; + } + final StringBuilder normalizedBits = new StringBuilder(trimmedBits.length() / transmissionRate); + char lastBit = trimmedBits.charAt(0); + int bitCount = 1; + for (int i = transmissionRate; i < trimmedBits.length(); i += transmissionRate) { + final char bit = trimmedBits.charAt(i); + if (bit == lastBit) { + bitCount++; + } else { + normalizedBits.append(repeat(lastBit, bitCount)); + bitCount = 1; + lastBit = bit; + } + } + return normalizedBits.append(repeat(lastBit, bitCount)).toString(); + } + + static int getTransmissionRate(final String bits) { + if (bits.isEmpty()) { + return 1; + } + + final Map> bitCounts = new HashMap<>(2, 1); + final SortedSet bitOffCounts = new TreeSet<>(); + bitCounts.put(BIT_OFF, bitOffCounts); + final SortedSet bitOnCounts = new TreeSet<>(); + bitCounts.put(BIT_ON, bitOnCounts); + + char lastBit = bits.charAt(0); + int bitCount = 1; + for (int i = 1; i < bits.length(); i++) { + final char bit = bits.charAt(i); + if (bit == lastBit) { + bitCount++; + } else { + bitCounts.get(lastBit).add(bitCount); + bitCount = 1; + lastBit = bit; + } + } + + if (bitOnCounts.contains(BIT_LETTER_PART_DOT_LENGTH) || bitOffCounts.contains(BIT_LETTER_PART_PAUSE_LENGTH)) { + return BIT_LETTER_PART_DOT_LENGTH; + } + + if (bitOnCounts.contains(BIT_LETTER_PART_DASH_LENGTH)) { + return bitOffCounts.contains(BIT_WORD_PAUSE_LENGTH) ? BIT_LETTER_PART_DOT_LENGTH : BIT_LETTER_PART_DASH_LENGTH; + } + + if (bitOffCounts.contains(BIT_LETTER_PAUSE_LENGTH)) { + return BIT_LETTER_PAUSE_LENGTH; + } + + if (bitOffCounts.contains(BIT_WORD_PAUSE_LENGTH)) { + return BIT_WORD_PAUSE_LENGTH; + } + + final int lowerBitOnCount = bitOnCounts.first(); + if (bitOnCounts.size() > 1 || lowerBitOnCount % BIT_LETTER_PART_DASH_LENGTH != 0) { + return lowerBitOnCount; + } + + final int[] transmissionRateCandidates = {lowerBitOnCount, lowerBitOnCount / BIT_LETTER_PART_DASH_LENGTH}; + candidate: + for (final int candidate : transmissionRateCandidates) { + for (final int bitOffCount : bitOffCounts) { + if (bitOffCount % candidate != 0) { + continue candidate; + } + } + return candidate; + } + + return -1; + } + + static String trim(final String s, char c) { + final StringBuilder sb = new StringBuilder(s); + while (sb.length() > 0 && sb.charAt(0) == c) + sb.deleteCharAt(0); + while (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) + sb.deleteCharAt(sb.length() - 1); + return sb.toString(); + } + + static String repeat(final char c, final int times) { + final StringBuilder repeat = new StringBuilder(times); + for (int i = 0; i < times; i++) { + repeat.append(c); + } + return repeat.toString(); + } +} \ No newline at end of file diff --git a/decode-the-morse-code-advanced/java/2/MorseCodeDecoder.java b/decode-the-morse-code-advanced/java/2/MorseCodeDecoder.java new file mode 100644 index 0000000..66083e0 --- /dev/null +++ b/decode-the-morse-code-advanced/java/2/MorseCodeDecoder.java @@ -0,0 +1,174 @@ +import java.util.*; + +public class MorseCodeDecoder { + public static final char BIT_OFF = '0'; + public static final char BIT_ON = '1'; + + public static final int BIT_LETTER_PART_DOT_LENGTH = 1; + public static final int BIT_LETTER_PART_DASH_LENGTH = 3; + + public static final String BIT_LETTER_PART_DOT = repeat(BIT_ON, BIT_LETTER_PART_DOT_LENGTH); + public static final String BIT_LETTER_PART_DASH = repeat(BIT_ON, BIT_LETTER_PART_DASH_LENGTH); + + public static final int BIT_LETTER_PART_PAUSE_LENGTH = 1; + public static final int BIT_LETTER_PAUSE_LENGTH = 3; + public static final int BIT_WORD_PAUSE_LENGTH = 7; + + public static final String BIT_LETTER_PART_PAUSE = repeat(BIT_OFF, BIT_LETTER_PART_PAUSE_LENGTH); + public static final String BIT_LETTER_PAUSE = repeat(BIT_OFF, BIT_LETTER_PAUSE_LENGTH); + public static final String BIT_WORD_PAUSE = repeat(BIT_OFF, BIT_WORD_PAUSE_LENGTH); + + public static final char MORSE_DOT = '.'; + public static final char MORSE_DASH = '-'; + public static final char MORSE_DELIMITER = ' '; + + public static final int MORSE_LETTER_DELIMITER_LENGTH = 1; + public static final int MORSE_WORD_DELIMITER_LENGTH = 3; + + public static final String MORSE_LETTER_DELIMITER = repeat(MORSE_DELIMITER, MORSE_LETTER_DELIMITER_LENGTH); + public static final String MORSE_WORD_DELIMITER = repeat(MORSE_DELIMITER, MORSE_WORD_DELIMITER_LENGTH); + + public static final String WORD_DELIMITER = " "; + + private static final Map BIT_TO_MORSE; + + static { + final Map bitToMorse = new HashMap<>(2, 1); + bitToMorse.put(BIT_LETTER_PART_DOT, MORSE_DOT); + bitToMorse.put(BIT_LETTER_PART_DASH, MORSE_DASH); + BIT_TO_MORSE = Collections.unmodifiableMap(bitToMorse); + } + + public static String decodeBits(final String bits) { + final StringBuilder morseBuilder = new StringBuilder(); + for (final String bitWord : normalize(bits).split(BIT_WORD_PAUSE)) { + if (morseBuilder.length() > 0) { + morseBuilder.append(MORSE_WORD_DELIMITER); + } + final StringBuilder wordBuilder = new StringBuilder(); + for (final String bitLetter : bitWord.split(BIT_LETTER_PAUSE)) { + if (wordBuilder.length() > 0) { + wordBuilder.append(MORSE_LETTER_DELIMITER); + } + final StringBuilder letterBuilder = new StringBuilder(); + for (final String bitLetterPart : bitLetter.split(BIT_LETTER_PART_PAUSE)) { + letterBuilder.append((char) BIT_TO_MORSE.get(bitLetterPart)); + } + wordBuilder.append(letterBuilder); + } + morseBuilder.append(wordBuilder); + } + return morseBuilder.toString(); + } + + public static String decodeMorse(final String morseCode) { + final StringBuilder decodeBuilder = new StringBuilder(); + for (final String morseWord : morseCode.trim().split(MORSE_WORD_DELIMITER)) { + if (decodeBuilder.length() > 0) { + decodeBuilder.append(WORD_DELIMITER); + } + for (final String morseLetter : morseWord.split(MORSE_LETTER_DELIMITER)) { + decodeBuilder.append(MorseCode.get(morseLetter)); + } + } + return decodeBuilder.toString(); + } + + private static String normalize(final String bits) { + final String trimmedBits = trim(bits, BIT_OFF); + final int transmissionRate = getTransmissionRate(trimmedBits); + if (transmissionRate <= 1) { + return trimmedBits; + } + final StringBuilder normalizedBits = new StringBuilder(trimmedBits.length() / transmissionRate); + char lastBit = trimmedBits.charAt(0); + int bitCount = 1; + for (int i = transmissionRate; i < trimmedBits.length(); i += transmissionRate) { + final char bit = trimmedBits.charAt(i); + if (bit == lastBit) { + bitCount++; + } else { + normalizedBits.append(repeat(lastBit, bitCount)); + bitCount = 1; + lastBit = bit; + } + } + return normalizedBits.append(repeat(lastBit, bitCount)).toString(); + } + + private static int getTransmissionRate(final String bits) { + if (bits.isEmpty()) { + return 1; + } + + final Map> bitCounts = new HashMap<>(2, 1); + final SortedSet bitOffCounts = new TreeSet<>(); + bitCounts.put(BIT_OFF, bitOffCounts); + final SortedSet bitOnCounts = new TreeSet<>(); + bitCounts.put(BIT_ON, bitOnCounts); + + char lastBit = bits.charAt(0); + int bitCount = 1; + for (int i = 1; i < bits.length(); i++) { + final char bit = bits.charAt(i); + if (bit == lastBit) { + bitCount++; + } else { + bitCounts.get(lastBit).add(bitCount); + bitCount = 1; + lastBit = bit; + } + } + + if (bitOnCounts.contains(BIT_LETTER_PART_DOT_LENGTH) || bitOffCounts.contains(BIT_LETTER_PART_PAUSE_LENGTH)) { + return BIT_LETTER_PART_DOT_LENGTH; + } + + if (bitOnCounts.contains(BIT_LETTER_PART_DASH_LENGTH)) { + return bitOffCounts.contains(BIT_WORD_PAUSE_LENGTH) ? BIT_LETTER_PART_DOT_LENGTH : BIT_LETTER_PART_DASH_LENGTH; + } + + if (bitOffCounts.contains(BIT_LETTER_PAUSE_LENGTH)) { + return BIT_LETTER_PAUSE_LENGTH; + } + + if (bitOffCounts.contains(BIT_WORD_PAUSE_LENGTH)) { + return BIT_WORD_PAUSE_LENGTH; + } + + final int lowerBitOnCount = bitOnCounts.first(); + if (bitOnCounts.size() > 1 || lowerBitOnCount % BIT_LETTER_PART_DASH_LENGTH != 0) { + return lowerBitOnCount; + } + + final int[] transmissionRateCandidates = {lowerBitOnCount, lowerBitOnCount / BIT_LETTER_PART_DASH_LENGTH}; + candidate: + for (final int transmissionRateCandidate : transmissionRateCandidates) { + for (final int bitOffCount : bitOffCounts) { + if (bitOffCount % transmissionRateCandidate != 0) { + continue candidate; + } + } + return transmissionRateCandidate; + } + + return -1; + } + + private static String trim(final String s, char c) { + final StringBuilder sb = new StringBuilder(s); + while (sb.length() > 0 && sb.charAt(0) == c) + sb.deleteCharAt(0); + while (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) + sb.deleteCharAt(sb.length() - 1); + return sb.toString(); + } + + private static String repeat(final char c, final int times) { + final StringBuilder repeat = new StringBuilder(times); + for (int i = 0; i < times; i++) { + repeat.append(c); + } + return repeat.toString(); + } +} \ No newline at end of file diff --git a/decode-the-morse-code-advanced/java/3/MorseCodeDecoder.java b/decode-the-morse-code-advanced/java/3/MorseCodeDecoder.java new file mode 100644 index 0000000..f1a81c9 --- /dev/null +++ b/decode-the-morse-code-advanced/java/3/MorseCodeDecoder.java @@ -0,0 +1,175 @@ +import java.util.*; + +public class MorseCodeDecoder { + public static final char BIT_OFF = '0'; + public static final char BIT_ON = '1'; + + public static final int BIT_LETTER_PART_DOT_LENGTH = 1; + public static final int BIT_LETTER_PART_DASH_LENGTH = 3; + + public static final String BIT_LETTER_PART_DOT = repeat(BIT_ON, BIT_LETTER_PART_DOT_LENGTH); + public static final String BIT_LETTER_PART_DASH = repeat(BIT_ON, BIT_LETTER_PART_DASH_LENGTH); + + public static final int BIT_LETTER_PART_PAUSE_LENGTH = 1; + public static final int BIT_LETTER_PAUSE_LENGTH = 3; + public static final int BIT_WORD_PAUSE_LENGTH = 7; + + public static final String BIT_LETTER_PART_PAUSE = repeat(BIT_OFF, BIT_LETTER_PART_PAUSE_LENGTH); + public static final String BIT_LETTER_PAUSE = repeat(BIT_OFF, BIT_LETTER_PAUSE_LENGTH); + public static final String BIT_WORD_PAUSE = repeat(BIT_OFF, BIT_WORD_PAUSE_LENGTH); + + public static final char MORSE_DOT = '.'; + public static final char MORSE_DASH = '-'; + public static final char MORSE_DELIMITER = ' '; + + public static final int MORSE_LETTER_DELIMITER_LENGTH = 1; + public static final int MORSE_WORD_DELIMITER_LENGTH = 3; + + public static final String MORSE_LETTER_DELIMITER = repeat(MORSE_DELIMITER, MORSE_LETTER_DELIMITER_LENGTH); + public static final String MORSE_WORD_DELIMITER = repeat(MORSE_DELIMITER, MORSE_WORD_DELIMITER_LENGTH); + + public static final String WORD_DELIMITER = " "; + + private static final Map BIT_TO_MORSE; + + static { + final Map bitToMorse = new HashMap<>(2, 1); + bitToMorse.put(BIT_LETTER_PART_DOT, MORSE_DOT); + bitToMorse.put(BIT_LETTER_PART_DASH, MORSE_DASH); + BIT_TO_MORSE = Collections.unmodifiableMap(bitToMorse); + } + + public static String decodeBits(final String bits) { + final StringBuilder morseBuilder = new StringBuilder(); + for (final String bitWord : normalize(bits).split(BIT_WORD_PAUSE)) { + if (morseBuilder.length() > 0) { + morseBuilder.append(MORSE_WORD_DELIMITER); + } + final StringBuilder wordBuilder = new StringBuilder(); + for (final String bitLetter : bitWord.split(BIT_LETTER_PAUSE)) { + if (wordBuilder.length() > 0) { + wordBuilder.append(MORSE_LETTER_DELIMITER); + } + final StringBuilder letterBuilder = new StringBuilder(); + for (final String bitLetterPart : bitLetter.split(BIT_LETTER_PART_PAUSE)) { + letterBuilder.append((char) BIT_TO_MORSE.get(bitLetterPart)); + } + wordBuilder.append(letterBuilder); + } + morseBuilder.append(wordBuilder); + } + return morseBuilder.toString(); + } + + public static String decodeMorse(final String morseCode) { + final StringBuilder decodeBuilder = new StringBuilder(); + for (final String morseWord : morseCode.trim().split(MORSE_WORD_DELIMITER)) { + if (decodeBuilder.length() > 0) { + decodeBuilder.append(WORD_DELIMITER); + } + for (final String morseLetter : morseWord.split(MORSE_LETTER_DELIMITER)) { + decodeBuilder.append(MorseCode.get(morseLetter)); + } + } + return decodeBuilder.toString(); + } + + private static String normalize(final String bits) { + final String trimmedBits = trim(bits, BIT_OFF); + final int transmissionRate = getTransmissionRate(trimmedBits); + if (transmissionRate <= 1) { + return trimmedBits; + } + final StringBuilder normalizedBits = new StringBuilder(trimmedBits.length() / transmissionRate); + char lastBit = trimmedBits.charAt(0); + int bitCount = 1; + for (int i = transmissionRate; i < trimmedBits.length(); i += transmissionRate) { + final char bit = trimmedBits.charAt(i); + if (bit == lastBit) { + bitCount++; + } else { + normalizedBits.append(repeat(lastBit, bitCount)); + bitCount = 1; + lastBit = bit; + } + } + return normalizedBits.append(repeat(lastBit, bitCount)).toString(); + } + + private static int getTransmissionRate(final String bits) { + if (bits.isEmpty()) { + return 1; + } + + final Map> bitCounts = new HashMap<>(2, 1); + final SortedSet bitOffCounts = new TreeSet<>(); + bitCounts.put(BIT_OFF, bitOffCounts); + final SortedSet bitOnCounts = new TreeSet<>(); + bitCounts.put(BIT_ON, bitOnCounts); + + char lastBit = bits.charAt(0); + int bitCount = 1; + for (int i = 1; i < bits.length(); i++) { + final char bit = bits.charAt(i); + if (bit == lastBit) { + bitCount++; + } else { + bitCounts.get(lastBit).add(bitCount); + bitCount = 1; + lastBit = bit; + } + } + bitCounts.get(lastBit).add(bitCount); + + if (bitOnCounts.contains(BIT_LETTER_PART_DOT_LENGTH) || bitOffCounts.contains(BIT_LETTER_PART_PAUSE_LENGTH)) { + return BIT_LETTER_PART_DOT_LENGTH; + } + + if (bitOnCounts.contains(BIT_LETTER_PART_DASH_LENGTH)) { + return bitOffCounts.contains(BIT_WORD_PAUSE_LENGTH) ? BIT_LETTER_PART_DOT_LENGTH : BIT_LETTER_PART_DASH_LENGTH; + } + + if (bitOffCounts.contains(BIT_LETTER_PAUSE_LENGTH)) { + return BIT_LETTER_PAUSE_LENGTH; + } + + if (bitOffCounts.contains(BIT_WORD_PAUSE_LENGTH)) { + return BIT_WORD_PAUSE_LENGTH; + } + + final int lowerBitOnCount = bitOnCounts.first(); + if (bitOnCounts.size() > 1 || lowerBitOnCount % BIT_LETTER_PART_DASH_LENGTH != 0) { + return lowerBitOnCount; + } + + final int[] transmissionRateCandidates = {lowerBitOnCount, lowerBitOnCount / BIT_LETTER_PART_DASH_LENGTH}; + candidate: + for (final int candidate : transmissionRateCandidates) { + for (final int bitOffCount : bitOffCounts) { + if (bitOffCount % candidate != 0) { + continue candidate; + } + } + return candidate; + } + + return -1; // malformed bits + } + + private static String trim(final String s, char c) { + final StringBuilder sb = new StringBuilder(s); + while (sb.length() > 0 && sb.charAt(0) == c) + sb.deleteCharAt(0); + while (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) + sb.deleteCharAt(sb.length() - 1); + return sb.toString(); + } + + private static String repeat(final char c, final int times) { + final StringBuilder repeat = new StringBuilder(times); + for (int i = 0; i < times; i++) { + repeat.append(c); + } + return repeat.toString(); + } +} \ No newline at end of file diff --git a/decode-the-morse-code-advanced/java/4/MorseCodeDecoder.java b/decode-the-morse-code-advanced/java/4/MorseCodeDecoder.java new file mode 100644 index 0000000..40439af --- /dev/null +++ b/decode-the-morse-code-advanced/java/4/MorseCodeDecoder.java @@ -0,0 +1,135 @@ +import java.util.*; +import java.util.function.*; + +public class MorseCodeDecoder { + public static final char BIT_OFF = '0'; + public static final char BIT_ON = '1'; + + public static final int BIT_LETTER_PART_DOT_LENGTH = 1; + public static final int BIT_LETTER_PART_DASH_LENGTH = 3; + + public static final String BIT_LETTER_PART_DOT = repeat(BIT_ON, BIT_LETTER_PART_DOT_LENGTH); + public static final String BIT_LETTER_PART_DASH = repeat(BIT_ON, BIT_LETTER_PART_DASH_LENGTH); + + public static final int BIT_LETTER_PART_PAUSE_LENGTH = 1; + public static final int BIT_LETTER_PAUSE_LENGTH = 3; + public static final int BIT_WORD_PAUSE_LENGTH = 7; + + public static final String BIT_LETTER_PART_PAUSE = repeat(BIT_OFF, BIT_LETTER_PART_PAUSE_LENGTH); + public static final String BIT_LETTER_PAUSE = repeat(BIT_OFF, BIT_LETTER_PAUSE_LENGTH); + public static final String BIT_WORD_PAUSE = repeat(BIT_OFF, BIT_WORD_PAUSE_LENGTH); + + public static final char MORSE_DOT = '.'; + public static final char MORSE_DASH = '-'; + public static final char MORSE_DELIMITER = ' '; + + public static final int MORSE_LETTER_DELIMITER_LENGTH = 1; + public static final int MORSE_WORD_DELIMITER_LENGTH = 3; + + public static final String MORSE_LETTER_DELIMITER = repeat(MORSE_DELIMITER, MORSE_LETTER_DELIMITER_LENGTH); + public static final String MORSE_WORD_DELIMITER = repeat(MORSE_DELIMITER, MORSE_WORD_DELIMITER_LENGTH); + + public static final String WORD_DELIMITER = " "; + + private static final Map BIT_TO_MORSE; + + static { + final Map bitToMorse = new HashMap<>(2, 1); + bitToMorse.put(BIT_LETTER_PART_DOT, MORSE_DOT); + bitToMorse.put(BIT_LETTER_PART_DASH, MORSE_DASH); + BIT_TO_MORSE = Collections.unmodifiableMap(bitToMorse); + } + + public static String decodeBits(final String bits) { + final StringBuilder morseBuilder = new StringBuilder(); + for (final String bitWord : normalize(bits).split(BIT_WORD_PAUSE)) { + if (morseBuilder.length() > 0) { + morseBuilder.append(MORSE_WORD_DELIMITER); + } + final StringBuilder wordBuilder = new StringBuilder(); + for (final String bitLetter : bitWord.split(BIT_LETTER_PAUSE)) { + if (wordBuilder.length() > 0) { + wordBuilder.append(MORSE_LETTER_DELIMITER); + } + final StringBuilder letterBuilder = new StringBuilder(); + for (final String bitLetterPart : bitLetter.split(BIT_LETTER_PART_PAUSE)) { + // deliberate cast to fail fast with NPE instead of appending "null" + letterBuilder.append((char) BIT_TO_MORSE.get(bitLetterPart)); + } + wordBuilder.append(letterBuilder); + } + morseBuilder.append(wordBuilder); + } + return morseBuilder.toString(); + } + + public static String decodeMorse(final String morseCode) { + final StringBuilder decodeBuilder = new StringBuilder(); + for (final String morseWord : morseCode.trim().split(MORSE_WORD_DELIMITER)) { + if (decodeBuilder.length() > 0) { + decodeBuilder.append(WORD_DELIMITER); + } + for (final String morseLetter : morseWord.split(MORSE_LETTER_DELIMITER)) { + decodeBuilder.append(MorseCode.get(morseLetter)); + } + } + return decodeBuilder.toString(); + } + + private static String normalize(final String bits) { + final String trimmedBits = trim(bits, BIT_OFF); + final int transmissionRate = getTransmissionRate(trimmedBits); + + return transmissionRate <= 1 + ? trimmedBits + : loopThroughBits(trimmedBits, transmissionRate, new StringBuilder(trimmedBits.length() / transmissionRate), MorseCodeDecoder::repeat, StringBuilder::append).toString(); + } + + private static int getTransmissionRate(final String bits) { + return bits.isEmpty() + ? 0 + : loopThroughBits(bits, 1, new HashSet(), (lastBit, bitCount) -> bitCount, Collection::add) + .stream() + .mapToInt(Integer::intValue) + .reduce(MorseCodeDecoder::gcd) + .getAsInt(); + } + + private static C loopThroughBits(final String bits, final int step, final C container, final BiFunction elementProducer, final BiConsumer appender) { + char lastBit = bits.charAt(0); + int bitCount = 1; + for (int i = step; i < bits.length(); i += step) { + final char bit = bits.charAt(i); + if (bit == lastBit) { + bitCount++; + } else { + appender.accept(container, elementProducer.apply(lastBit, bitCount)); + bitCount = 1; + lastBit = bit; + } + } + appender.accept(container, elementProducer.apply(lastBit, bitCount)); + return container; + } + + private static int gcd(final int a, final int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private static String trim(final String s, char c) { + final StringBuilder sb = new StringBuilder(s); + while (sb.length() > 0 && sb.charAt(0) == c) + sb.deleteCharAt(0); + while (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) + sb.deleteCharAt(sb.length() - 1); + return sb.toString(); + } + + private static String repeat(final char c, final int times) { + final StringBuilder repeat = new StringBuilder(times); + for (int i = 0; i < times; i++) { + repeat.append(c); + } + return repeat.toString(); + } +} \ No newline at end of file diff --git a/decode-the-morse-code/README.md b/decode-the-morse-code/README.md new file mode 100644 index 0000000..1691eef --- /dev/null +++ b/decode-the-morse-code/README.md @@ -0,0 +1,82 @@ +# Decode the Morse code +[*View on Codewars*](https://www.codewars.com/kata/decode-the-morse-code) + +
Part of Series 1/3
This kata is part of a series on the Morse code. After you solve this kata, you may move to the [next one](/kata/decode-the-morse-code-advanced).

In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superceded by voice and digital data communication channels, it still has its use in some applications around the world. + +The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−−   ·−−− ··− −·· ·. + +**NOTE:** Extra spaces before or after the code have no meaning and should be ignored. + +In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as ···−−−···. These special codes are treated as single special characters, and usually are transmitted as separate words. + +Your task is to implement a function that would take the morse code as input and return a decoded human-readable string. + +For example: + +```coffeescript +decodeMorse('.... . -.-- .--- ..- -.. .') +//should return "HEY JUDE" +``` +```cpp +decodeMorse('.... . -.-- .--- ..- -.. .') +//should return "HEY JUDE" +``` +```csharp +MorseCodeDecoder.Decode('.... . -.-- .--- ..- -.. .') +//should return "HEY JUDE" +``` +```elixir +MorseCode.decode('.... . -.-- .--- ..- -.. .') +#=> "HEY JUDE" +``` +```go +DecodeMorse(".... . -.-- .--- ..- -.. .") +// should return "HEY JUDE" +``` +```haskell +decodeMorse ".... . -.-- .--- ..- -.. ." +--should return "HEY JUDE" +``` +```java +MorseCodeDecoder.decode(".... . -.-- .--- ..- -.. .") +//should return "HEY JUDE" +``` +```javascript +decodeMorse('.... . -.-- .--- ..- -.. .') +//should return "HEY JUDE" +``` +```php +decode_morse('.... . -.-- .--- ..- -.. .') +//should return "HEY JUDE" +``` +```python +decodeMorse('.... . -.-- .--- ..- -.. .') +#should return "HEY JUDE" +``` +```ruby +decodeMorse('.... . -.-- .--- ..- -.. .') +#should return "HEY JUDE" +``` +```typescript +decodeMorse('.... . -.-- .--- ..- -.. .') +//should return "HEY JUDE" +``` +```rust +MorseDecoder::new().decode_morse(".... . -.-- .--- ..- -.. .") +//should return "HEY JUDE" +``` + +The Morse code table is preloaded for you as a dictionary, feel free to use it. In CoffeeScript, C++, Go, JavaScript, PHP, Python, Ruby and TypeScript, the table can be accessed like this: MORSE_CODE['.--'], in Java it is MorseCode.get('.--'), in C# it is MorseCode.Get('.--'), in Haskell the codes are in a Map String String and can be accessed like this: morseCodes ! ".--", in Elixir it is `morse_codes` variable, in Rust it is `self.morse_code`. + +All the test strings would contain valid Morse code, so you may skip checking for errors and exceptions. In C#, tests will fail if the solution code throws an exception, please keep that in mind. This is mostly because otherwise the engine would simply ignore the tests, resulting in a "valid" solution. + +Good luck! + +After you complete this kata, you may try yourself at Decode the Morse code, advanced. + + +## Timeline +- Created: 2015-01-15 +- Published: 2015-01-15 +- Approved: 2015-02-02 +- Completed: 2015-05-01 \ No newline at end of file diff --git a/decode-the-morse-code/java/1/MorseCodeDecoder.java b/decode-the-morse-code/java/1/MorseCodeDecoder.java new file mode 100644 index 0000000..c393d09 --- /dev/null +++ b/decode-the-morse-code/java/1/MorseCodeDecoder.java @@ -0,0 +1,23 @@ +public class MorseCodeDecoder { + public static final String MORSE_WORD_DELIMITER = " "; + public static final String MORSE_LETTER_DELIMITER = " "; + public static final String WORD_DELIMITER = " "; + + public static String decode(final String morseCode) { + final StringBuilder decodeBuilder = new StringBuilder(); + final String[] morseWords = morseCode.split(MORSE_WORD_DELIMITER); + for (final String morseWord : morseWords) { + if (decodeBuilder.length() > 0) { + decodeBuilder.append(WORD_DELIMITER); + } + final String[] morseLetters = morseWord.split(MORSE_LETTER_DELIMITER); + for (final String morseLetter : morseLetters) { + final String letter = MorseCode.get(morseLetter); + if (letter != null) { // don't know why this would be null + decodeBuilder.append(letter); + } + } + } + return decodeBuilder.toString(); + } +} \ No newline at end of file diff --git a/decode-the-morse-code/java/2/MorseCodeDecoder.java b/decode-the-morse-code/java/2/MorseCodeDecoder.java new file mode 100644 index 0000000..d79d9f4 --- /dev/null +++ b/decode-the-morse-code/java/2/MorseCodeDecoder.java @@ -0,0 +1,21 @@ +public class MorseCodeDecoder { + public static final String MORSE_WORD_DELIMITER = " "; + public static final String MORSE_LETTER_DELIMITER = " "; + public static final String WORD_DELIMITER = " "; + + public static String decode(final String morseCode) { + final StringBuilder decodeBuilder = new StringBuilder(); + final String[] morseWords = morseCode.trim().split(MORSE_WORD_DELIMITER); + for (final String morseWord : morseWords) { + if (decodeBuilder.length() > 0) { + decodeBuilder.append(WORD_DELIMITER); + } + final String[] morseLetters = morseWord.split(MORSE_LETTER_DELIMITER); + for (final String morseLetter : morseLetters) { + final String letter = MorseCode.get(morseLetter); + decodeBuilder.append(letter); + } + } + return decodeBuilder.toString(); + } +} \ No newline at end of file diff --git a/deep-comparison-of-objects/README.md b/deep-comparison-of-objects/README.md new file mode 100644 index 0000000..fa3e00c --- /dev/null +++ b/deep-comparison-of-objects/README.md @@ -0,0 +1,22 @@ +# Deep comparison of objects +[*View on Codewars*](https://www.codewars.com/kata/deep-comparison-of-objects) + +Comparing objects is not an easy task in JavaScript. The comparison operator only returns true if both variables point to the same object, that's why two objects with the same properties and values are different for JavaScript, like this: + +```javascript +var a = { name: 'Joe' }; +var b = { name: 'Joe' }; +a == b; //-> false +``` + +Sometimes it's really useful to detect when two objects have the same values. + +Your task is to develop the deepCompare function to test if two objects have the same properties and values. Remember that an object can contain other objects. The function should also be able to correctly compare simple values, like strings and numbers (without using type coercion, please). + +To make things simpler, it will only have to deal with simple values and objects and arrays containing strings, booleans and numbers, without taking into account regular expressions, dates and functions. + +## Timeline +- Created: 2014-07-13 +- Published: 2014-07-13 +- Approved: 2015-02-26 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/deep-comparison-of-objects/javascript/1/deep-comparison-of-objects.js b/deep-comparison-of-objects/javascript/1/deep-comparison-of-objects.js new file mode 100644 index 0000000..9418aec --- /dev/null +++ b/deep-comparison-of-objects/javascript/1/deep-comparison-of-objects.js @@ -0,0 +1,34 @@ +function deepCompare(o1, o2) { + if (o1 === o2) { + return true; + } + if (typeof o1 !== typeof o2) { + return false; + } + if (Array.isArray(o1)) { + var length = o1.length; + if (length !== o2.length) { + return false; + } + for (var i = 0; i < length; i++) { + if (!deepCompare(o1[i], o2[i])) { + return false; + } + } + return true; + } + if (typeof o1 !== 'object') { + return false; + } + for (var p in o1) { + if (!deepCompare(o1[p], o2[p])) { + return false; + } + } + for (var p in o2) { + if (!deepCompare(o1[p], o2[p])) { + return false; + } + } + return true; +}; \ No newline at end of file diff --git a/delta-bits/README.md b/delta-bits/README.md new file mode 100644 index 0000000..82f53d9 --- /dev/null +++ b/delta-bits/README.md @@ -0,0 +1,19 @@ +# Delta Bits +[*View on Codewars*](https://www.codewars.com/kata/delta-bits) + +Write a function convertBits to determine the number of bits required to convert positive integer A to positive integer B. + +For example, you can change 31 to 14 by flipping the 4th and 0th bit: +``` + 31 0 0 0 1 1 1 1 1 + 14 0 0 0 0 1 1 1 0 +--- --------------- +bit 7 6 5 4 3 2 1 0 +``` +Thus ```31``` and ```14``` should return ```2```. + +## Timeline +- Created: 2014-05-31 +- Published: 2014-05-31 +- Approved: 2014-09-27 +- Completed: 2015-05-02 \ No newline at end of file diff --git a/delta-bits/java/1/DeltaBits.java b/delta-bits/java/1/DeltaBits.java new file mode 100644 index 0000000..f36448f --- /dev/null +++ b/delta-bits/java/1/DeltaBits.java @@ -0,0 +1,15 @@ +public class DeltaBits { + public static int convertBits(int a, int b) { + int count = 0; + for (int i = 0; i < Integer.SIZE; i++) { + if (nthBit(a, i) != nthBit(b, i)) { + count++; + } + } + return count; + } + + private static int nthBit(int i, int n) { + return i >>> n & 1; + } +} \ No newline at end of file diff --git a/delta-bits/javascript/1/delta-bits.js b/delta-bits/javascript/1/delta-bits.js new file mode 100644 index 0000000..28421fd --- /dev/null +++ b/delta-bits/javascript/1/delta-bits.js @@ -0,0 +1,7 @@ +function convertBits(a, b) { + let c = 0; + for (let d = a ^ b, e = 0, f = Math.log2(d); e <= f; e++) { + c += (d >> e) & 1; + } + return c; +} \ No newline at end of file diff --git a/deodorant-evaporator/README.md b/deodorant-evaporator/README.md new file mode 100644 index 0000000..859d5e3 --- /dev/null +++ b/deodorant-evaporator/README.md @@ -0,0 +1,22 @@ +# Deodorant Evaporator +[*View on Codewars*](https://www.codewars.com/kata/deodorant-evaporator) + +This program tests the life of an +evaporator containing a gas. + +We know the content of the evaporator (content in ml), +the percentage of foam or gas lost every day (evap_per_day) +and the threshold (threshold) in percentage beyond which +the evaporator is no longer useful. +All numbers are strictly positive. + +The program reports the nth day (as an integer) +on which the evaporator will be out of use. + +**Note** : Content is in fact not necessary in the body of the function "evaporator", you can use it or not use it, as you wish. Some people might prefer to reason with content, some other with percentages only. It's up to you but you must keep it as a parameter because the tests have it as an argument. + +## Timeline +- Created: 2015-03-16 +- Published: 2015-03-16 +- Approved: 2015-05-08 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/deodorant-evaporator/java/1/Evaporator.java b/deodorant-evaporator/java/1/Evaporator.java new file mode 100644 index 0000000..54055ad --- /dev/null +++ b/deodorant-evaporator/java/1/Evaporator.java @@ -0,0 +1,9 @@ +public class Evaporator { + public static int evaporator(double content, double evapPerDay, double threshold) { + content = 100; + evapPerDay /= 100; + int day = 0; + for (double restPerDay = 1 - evapPerDay; content > threshold; content *= restPerDay, day++); + return day; + } +} \ No newline at end of file diff --git a/descending-order/README.md b/descending-order/README.md new file mode 100644 index 0000000..3e8909e --- /dev/null +++ b/descending-order/README.md @@ -0,0 +1,22 @@ +# Descending Order +[*View on Codewars*](https://www.codewars.com/kata/descending-order) + +Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number. + +### Examples: +Input: `21445` +Output: `54421` + +Input: `145263` +Output: `654321` + +Input: `1254859723` +Output: `9875543221` + + + +## Timeline +- Created: 2014-11-15 +- Published: 2014-11-15 +- Approved: 2014-12-08 +- Completed: 2015-05-06 \ No newline at end of file diff --git a/descending-order/java/1/DescendingOrder.java b/descending-order/java/1/DescendingOrder.java new file mode 100644 index 0000000..4826833 --- /dev/null +++ b/descending-order/java/1/DescendingOrder.java @@ -0,0 +1,43 @@ +public class DescendingOrder { + private static final int BASE = 10; + + public static int sortDesc(final int n) { + return sortDesc(n, 0); + } + + private static int sortDesc(final int n, final int desc) { + return isPositive(n) ? sortDesc(shiftRight(n), insertDesc(desc, lastDigit(n))) + : desc; + } + + private static int insertDesc(final int n, final int m) { + if (isDigit(n)) { + return !isPositive(n) ? m + : m > n ? shiftLeft(m) + n + : shiftLeft(n) + m; + } + final int d = lastDigit(n); + return d >= m ? shiftLeft(n) + m + : shiftLeft(insertDesc(shiftRight(n), m)) + d; + } + + private static boolean isPositive(final int n) { + return n > 0; + } + + private static boolean isDigit(final int n) { + return n < BASE; + } + + private static int lastDigit(final int n) { + return n % BASE; + } + + private static int shiftRight(final int n) { + return n / BASE; + } + + private static int shiftLeft(final int n) { + return n * BASE; + } +} \ No newline at end of file diff --git a/descending-order/javascript/1/descending-order.js b/descending-order/javascript/1/descending-order.js new file mode 100644 index 0000000..b12cdb1 --- /dev/null +++ b/descending-order/javascript/1/descending-order.js @@ -0,0 +1,8 @@ +function descendingOrder(n) { + const digits = [] + do { + digits.push(n % 10) + } while ((n = Math.trunc(n / 10)) > 0) + return digits.sort((a, b) => b - a) + .reduce((reversed, digit) => reversed = 10 * reversed + digit) +} \ No newline at end of file diff --git a/descending-order/javascript/2/descending-order.js b/descending-order/javascript/2/descending-order.js new file mode 100644 index 0000000..52852c2 --- /dev/null +++ b/descending-order/javascript/2/descending-order.js @@ -0,0 +1,8 @@ +function descendingOrder(n) { + const digits = [] + do { + digits.push(n % 10) + } while ((n = Math.trunc(n / 10)) > 0) + return digits.sort((a, b) => b - a) + .reduce((reversed, digit) => 10 * reversed + digit) +} \ No newline at end of file diff --git a/descending-order/javascript/3/descending-order.js b/descending-order/javascript/3/descending-order.js new file mode 100644 index 0000000..c1b87e8 --- /dev/null +++ b/descending-order/javascript/3/descending-order.js @@ -0,0 +1,48 @@ +function length(n) { + return n === 0 + ? 1 + : Math.trunc(Math.log10(n)) + 1 +} + +function digitAt(n, i) { + return Math.trunc(n / 10 ** i) % 10 +} + +function binarySearch(n, key) { + let low = 0 + let high = length(n) - 1 + + while (low <= high) { + const mid = (low + high) >>> 1 + const midVal = digitAt(n, mid) + + if (midVal < key) { + low = mid + 1 + } else if (midVal > key) { + high = mid - 1 + } else { + return mid + } + } + + return low +} + +function insertDigitAt(n, d, i) { + const factor = 10 ** i + return 10 * Math.trunc(n / factor) * factor + factor * d + n % factor +} + +function insertDigit(n, d) { + return insertDigitAt(n, d, binarySearch(n, d)) +} + +function descendingOrder(n) { + function desc(n, o) { + return n === 0 + ? o % 10 ** (length(o) - 1) + : desc(Math.trunc(n / 10), insertDigit(o, n % 10)) + } + + return desc(n, 9) +} \ No newline at end of file diff --git a/design-a-simple-automaton-finite-state-machine/README.md b/design-a-simple-automaton-finite-state-machine/README.md new file mode 100644 index 0000000..d787697 --- /dev/null +++ b/design-a-simple-automaton-finite-state-machine/README.md @@ -0,0 +1,75 @@ +# Design a Simple Automaton (Finite State Machine) +[*View on Codewars*](https://www.codewars.com/kata/design-a-simple-automaton-finite-state-machine) + +Create a finite automaton that has three states. Finite automatons are the same as finite state machines for our purposes. + +Our simple automaton, accepts the language of `A`, defined as `{0, 1}` and should have three states: `q1`, `q2`, and `q3`. Here is the description if the states: + +* `q1` is our start state, we begin reading commands from here +* `q2` is our accept state, we return `true` if this is our last state + +And the transitions: + +* `q1` moves to `q2` when given a `1`, and stays at `q1` when given a `0` +* `q2` moves to `q3` when given a `0`, and stays at `q2` when given a `1` +* `q3` moves to `q2` when given a `0` or `1` + +The automaton should return whether we end in our accepted state (`q2`), or not (`true`/`false`). + + +## Your task + +You will have to design your state objects, and how your Automaton handles transitions. Also make sure you set up the three states, `q1`, `q2`, and `q3` for the myAutomaton instance. The test fixtures will be calling against myAutomaton. + +As an aside, the automaton accepts an array of strings, rather than just numbers, or a number represented as a string, because the language an automaton can accept isn't confined to just numbers. An automaton should be able to accept any 'symbol.' + +Here are some resources on DFAs (the automaton this Kata asks you to create): + +* http://en.wikipedia.org/wiki/Deterministic_finite_automaton +* http://www.cs.odu.edu/~toida/nerzic/390teched/regular/fa/dfa-definitions.html +* http://www.cse.chalmers.se/~coquand/AUTOMATA/o2.pdf + + +## Example + +```javascript +var a = new Automaton(); +// Do anything you need to set up this automaton's states. +var isAccepted = a.readCommands(["1", "0", "0", "1", "0"]); +``` +```python +a = Automaton() +# Do anything you need to set up this automaton's states. +is_accepted = a.read_commands(["1", "0", "0", "1", "0"]) +``` +```coffeescript +a = new Automaton() +# Do anything you need to set up this automaton's states. +isAccepted = a.readCommands ["1", "0", "0", "1", "0"] +``` +```c++ +a = Automaton() +// Do anything you need to set up this automaton's states. +is_accepted = a.read_commands({'1', '0', '0', '1'}); +``` + +We make these transitions: +``` +input: ["1", "0", "0", "1", "0"] + +1: q1 -> q2 +0: q2 -> q3 +0: q3 -> q2 +1: q2 -> q2 +0: q2 -> q3 +``` + +We end in `q3`, which is not our accept state, so we return `false` + + + +## Timeline +- Created: 2013-10-24 +- Published: 2013-10-25 +- Approved: 2014-02-17 +- Completed: 2015-05-25 \ No newline at end of file diff --git a/design-a-simple-automaton-finite-state-machine/javascript/1/design-a-simple-automaton-finite-state-machine.js b/design-a-simple-automaton-finite-state-machine/javascript/1/design-a-simple-automaton-finite-state-machine.js new file mode 100644 index 0000000..672cdd6 --- /dev/null +++ b/design-a-simple-automaton-finite-state-machine/javascript/1/design-a-simple-automaton-finite-state-machine.js @@ -0,0 +1,55 @@ +function Automaton() { + this.states = []; +} + +Automaton.prototype.readCommands = function(commands) { + if (!this.states) { + return false; + } + for (var i = 0, j = 0; i < commands.length; i++) { + j = this.states[j].move(commands[i]); + } + return this.states[j].accept; +} + +var myAutomaton = new Automaton(); + +var q1 = { + start: true, + accept: false, + move: function(cmd) { + switch (cmd) { + case "0": + return 0; + case "1": + return 1; + } + } +}; + +var q2 = { + start: false, + accept: true, + move: function(cmd) { + switch (cmd) { + case "0": + return 2; + case "1": + return 1; + } + } +}; + +var q3 = { + start: false, + accept: false, + move: function(cmd) { + switch (cmd) { + case "0": + case "1": + return 1; + } + } +}; + +myAutomaton.states.push(q1, q2, q3); \ No newline at end of file diff --git a/deutschstunde/README.md b/deutschstunde/README.md new file mode 100644 index 0000000..647fc72 --- /dev/null +++ b/deutschstunde/README.md @@ -0,0 +1,18 @@ +# Deutschstunde +[*View on Codewars*](https://www.codewars.com/kata/deutschstunde) + +Everybody knows a little german, right? But remembering the correct articles is a tough job. Write yourself a little helper, that returns the noun with the matching article: + +- each noun containing less than 2 vowels has the article "das" +- each noun containing 2/3 vowels has the article "die" +- each noun containing more than 3 vowels has the article "der" + +Caution: Vowels are "a,e,i,o,u". Umlaute (ä ö ü) are also being counted! + +(This Kata is a joke, there is no such grammar rule!) + +## Timeline +- Created: 2015-04-14 +- Published: 2015-04-14 +- Approved: 2016-01-16 +- Completed: 2015-05-22 \ No newline at end of file diff --git a/deutschstunde/javascript/1/deutschstunde.js b/deutschstunde/javascript/1/deutschstunde.js new file mode 100644 index 0000000..14b20f9 --- /dev/null +++ b/deutschstunde/javascript/1/deutschstunde.js @@ -0,0 +1,20 @@ +function derDieDas(wort) { + return bestimmterArtikel(vokalAnzahl(wort)) + ' ' + wort; +} + +function bestimmterArtikel(vokalAnzahl) { + switch (vokalAnzahl) { + case 0: + case 1: + return 'das'; + case 2: + case 3: + return 'die'; + default: + return 'der'; + } +} + +function vokalAnzahl(wort) { + return (wort.match(/[aäeioöuü]/gi) || []).length; +} \ No newline at end of file diff --git a/deutschstunde/javascript/2/deutschstunde.js b/deutschstunde/javascript/2/deutschstunde.js new file mode 100644 index 0000000..0a57d3d --- /dev/null +++ b/deutschstunde/javascript/2/deutschstunde.js @@ -0,0 +1,3 @@ +function derDieDas(wort) { + return ['das', 'die', 'der'][Math.min(~~((wort.match(/[aäeioöuü]/gi) || []).length / 2), 2)] + ' ' + wort; +} \ No newline at end of file diff --git a/directions-reduction/README.md b/directions-reduction/README.md new file mode 100644 index 0000000..3e46816 --- /dev/null +++ b/directions-reduction/README.md @@ -0,0 +1,108 @@ +# Directions Reduction +[*View on Codewars*](https://www.codewars.com/kata/directions-reduction) + +# Once upon a time, on a way through the old wild west,… + +… a man was given directions to go from one point to another. The directions were "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too. Going to one direction and coming back the opposite direction is a needless effort. Since this is the wild west, with dreadfull weather and not much water, it's important to save yourself some energy, otherwise you might die of thirst! + +## How I crossed the desert the smart way. + +The directions given to the man are, for example, the following: + +``` +["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]. +``` + +or + +``` +{ "NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST" }; +``` + +or (haskell) + +``` +[North, South, South, East, West, North, West] +``` + +You can immediatly see that going "NORTH" and then "SOUTH" is not reasonable, better stay to the same place! +So the task is to give to the man a simplified version of the plan. A better plan in this case is simply: + +``` +["WEST"] +``` + +or + +``` +{ "WEST" } +``` + +or (haskell) + +``` +[West] +``` + +or (rust) + +``` +[WEST]; +``` + +# Other examples: + +In `["NORTH", "SOUTH", "EAST", "WEST"]`, the direction `"NORTH" + "SOUTH"` is going north and coming back *right away*. What a waste of time! Better to do nothing. + +The path becomes `["EAST", "WEST"]`, now `"EAST"` and `"WEST"` annihilate each other, therefore, the final result is `[]` (nil in Clojure). + +In ["NORTH", "EAST", "WEST", "SOUTH", "WEST", "WEST"], "NORTH" and "SOUTH" are not directly opposite but they become directly opposite after the reduction of "EAST" and "WEST" so the whole path is reducible to ["WEST", "WEST"]. + +# Task + +Write a function `dirReduc` which will take an array of strings and returns an array of strings with the needless directions removed (W<->E or S<->N side by side). + +The Haskell version takes a list of directions with `data Direction = North | East | West | South`. +The Clojure version returns nil when the path is reduced to nothing. +The Rust version takes a slice of `enum Direction {NORTH, SOUTH, EAST, WEST}`. + +# Examples + +```objc +dirReduc(@[@"NORTH", @"SOUTH", @"SOUTH", @"EAST", @"WEST", @"NORTH", @"WEST"]); // => @[@"WEST"] +dirReduc(@[@"NORTH", @"SOUTH", @"SOUTH", @"EAST", @"WEST", @"NORTH"]); // => @[] +``` +```javascript +dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]) => ["WEST"] +dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"]) => [] +``` +```csharp +dirReduc({"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"}) => {"WEST"} +dirReduc({"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"}) => {} +``` +```haskell +dirReduce [North, South, South, East, West, North, West] `shouldBe` [West] +dirReduce [North, South, South, East, West, North] `shouldBe` [] +``` +```clojure +dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]) => ["WEST"] +dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"]) => nil +``` +```rust +dir_reduc(&[NORTH, SOUTH, SOUTH, EAST, WEST, NORTH, WEST]) => [WEST] +dir_reduc(&[NORTH, SOUTH, SOUTH, EAST, WEST, NORTH]) => [] +``` + +# See more examples in "Example Tests" + +# Note + +Not all paths can be made simpler. +The path ["NORTH", "WEST", "SOUTH", "EAST"] is not reducible. "NORTH" and "WEST", "WEST" and "SOUTH", "SOUTH" and "EAST" are not directly opposite of each other and can't become such. Hence the result path is itself : ["NORTH", "WEST", "SOUTH", "EAST"]. + + +## Timeline +- Created: 2015-03-22 +- Published: 2015-03-22 +- Approved: 2015-04-11 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/directions-reduction/java/1/DirReduction.java b/directions-reduction/java/1/DirReduction.java new file mode 100644 index 0000000..9239db2 --- /dev/null +++ b/directions-reduction/java/1/DirReduction.java @@ -0,0 +1,24 @@ +import java.util.*; + +public class DirReduction { + private static final int BITMASK = 0b11; + + public static String[] dirReduc(final String[] allDirs) { + final Deque dirs = new LinkedList<>(); + for (final String dir : allDirs) { + if (dirs.isEmpty() || (ordinal(dirs.peekLast()) ^ ordinal(dir) & BITMASK) != BITMASK) { + dirs.addLast(dir); + } else { + dirs.removeLast(); + } + } + return dirs.toArray(new String[dirs.size()]); + } + private static int ordinal(final String dir) { + return Dir.valueOf(dir).ordinal(); + } + + private static enum Dir { + EAST, NORTH, SOUTH, WEST; // important lexicographic order + } +} \ No newline at end of file diff --git a/directions-reduction/javascript/1/directions-reduction.js b/directions-reduction/javascript/1/directions-reduction.js new file mode 100644 index 0000000..cb192d9 --- /dev/null +++ b/directions-reduction/javascript/1/directions-reduction.js @@ -0,0 +1,17 @@ +const opposites = { + NORTH: "SOUTH", + SOUTH: "NORTH", + EAST: "WEST", + WEST: "EAST" +} + +function dirReduc(arr) { + for (let i = 0; i < arr.length - 1; i++) { + let first = arr[i], second = arr[i + 1]; + if (opposites[first] === second) { + arr.splice(i, 2); + i = Math.max(i - 2, -1); + } + } + return arr; +} \ No newline at end of file diff --git a/discover-the-original-price/README.md b/discover-the-original-price/README.md new file mode 100644 index 0000000..20b7f25 --- /dev/null +++ b/discover-the-original-price/README.md @@ -0,0 +1,21 @@ +# Discover The Original Price +[*View on Codewars*](https://www.codewars.com/kata/discover-the-original-price) + +We need to write some code to return the original price of a product, the return type must be of type decimal and the number must be rounded to two decimal places. + +We will be given the sale price (discounted price), and the sale percentage, our job is to figure out the original price. + + +### For example: + +Given an item at $75 sale price after applying a 25% discount, the function should return the original price of that item before applying the sale percentage, which is ($100.00) of course, rounded to two decimal places. + + +DiscoverOriginalPrice(75, 25) => 100.00M where 75 is the sale price (discounted price), 25 is the sale percentage and 100 is the original price + + +## Timeline +- Created: 2015-04-08 +- Published: 2015-04-08 +- Approved: 2016-12-01 +- Completed: 2015-05-23 \ No newline at end of file diff --git a/discover-the-original-price/csharp/1/discover-the-original-price b/discover-the-original-price/csharp/1/discover-the-original-price new file mode 100644 index 0000000..a09a2b9 --- /dev/null +++ b/discover-the-original-price/csharp/1/discover-the-original-price @@ -0,0 +1,9 @@ +using System; + +public static class Kata +{ + public static decimal DiscoverOriginalPrice(decimal discountedPrice, decimal salePercentage) + { + return Math.Round(discountedPrice / (1 - salePercentage / 100) * 100) / 100; + } +} \ No newline at end of file diff --git a/discover-the-original-price/javascript/1/discover-the-original-price.js b/discover-the-original-price/javascript/1/discover-the-original-price.js new file mode 100644 index 0000000..f9fcdaa --- /dev/null +++ b/discover-the-original-price/javascript/1/discover-the-original-price.js @@ -0,0 +1,3 @@ +function discoverOriginalPrice(discountedPrice, salePercentage){ + return Math.round(discountedPrice / (1 - salePercentage / 100) * 100) / 100; +} \ No newline at end of file diff --git a/disemvowel-trolls/README.md b/disemvowel-trolls/README.md new file mode 100644 index 0000000..8849194 --- /dev/null +++ b/disemvowel-trolls/README.md @@ -0,0 +1,22 @@ +# Disemvowel Trolls +[*View on Codewars*](https://www.codewars.com/kata/disemvowel-trolls) + +Trolls are attacking your comment section! + +A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. + +Your task is to write a function that takes a string and return a new string with all vowels removed. + +For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!". + +Note: for this kata `y` isn't considered a vowel. + +~~~if:csharp +Beware: In error messages Expected and Actual are flipped. +~~~ + +## Timeline +- Created: 2014-02-12 +- Published: 2014-02-12 +- Approved: 2014-02-17 +- Completed: 2018-03-10 \ No newline at end of file diff --git a/disemvowel-trolls/javascript/1/disemvowel-trolls.js b/disemvowel-trolls/javascript/1/disemvowel-trolls.js new file mode 100644 index 0000000..dc531e4 --- /dev/null +++ b/disemvowel-trolls/javascript/1/disemvowel-trolls.js @@ -0,0 +1,3 @@ +function disemvowel(str) { + return str.replace(/[aeiou]/gi, ''); +} \ No newline at end of file diff --git a/dna-to-rna-conversion/README.md b/dna-to-rna-conversion/README.md new file mode 100644 index 0000000..36c4c96 --- /dev/null +++ b/dna-to-rna-conversion/README.md @@ -0,0 +1,41 @@ +# DNA to RNA Conversion +[*View on Codewars*](https://www.codewars.com/kata/dna-to-rna-conversion) + +Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T'). + +Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil ('U'). + +Create a funciton which translates a given DNA string into RNA. + +For example: +```python +DNAtoRNA("GCAT") returns ("GCAU") +``` +```ruby +DNAtoRNA("GCAT") returns ("GCAU") +``` +```javascript +DNAtoRNA("GCAT") returns ("GCAU") +``` +```coffeescript +DNAtoRNA "GCAT" returns "GCAU" +``` +```elixir +dna_to_rna("GCAT") #=> "GCAU" +``` +```haskell +dnaToRna "GCAT" returns "GCAU" +``` +```java +new Bio().dnaToRna("GCAT") // returns "GCAU" +``` +```rust +dna_to_rna("GCAT") //=> "GCAU" +``` + + +## Timeline +- Created: 2015-05-15 +- Published: 2015-05-15 +- Approved: 2015-05-20 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/dna-to-rna-conversion/javascript/1/dna-to-rna-conversion.js b/dna-to-rna-conversion/javascript/1/dna-to-rna-conversion.js new file mode 100644 index 0000000..369b918 --- /dev/null +++ b/dna-to-rna-conversion/javascript/1/dna-to-rna-conversion.js @@ -0,0 +1,3 @@ +function DNAtoRNA(dna){ + return dna.replace(/T/g, 'U'); +} \ No newline at end of file diff --git a/dont-rely-on-luck/README.md b/dont-rely-on-luck/README.md new file mode 100644 index 0000000..86c806f --- /dev/null +++ b/dont-rely-on-luck/README.md @@ -0,0 +1,31 @@ +# Don't rely on luck. +[*View on Codewars*](https://www.codewars.com/kata/dont-rely-on-luck) + +The test fixture I use for this kata is pre-populated. + +It will compare your guess to a random number generated using: + +```ruby +(Kernel::rand() * 100 + 1).floor +``` +```javascript +Math.floor(Math.random() * 100 + 1) +``` +```python +randint(1,100) +``` +```php +rand(1, 100) +``` + +You can pass by relying on luck or skill but try not to rely on luck. + +"The power to define the situation is the ultimate power." - Jerry Rubin + +Good luck! + +## Timeline +- Created: 2013-10-24 +- Published: 2013-10-24 +- Approved: null +- Completed: 2015-05-24 \ No newline at end of file diff --git a/dont-rely-on-luck/javascript/1/dont-rely-on-luck.js b/dont-rely-on-luck/javascript/1/dont-rely-on-luck.js new file mode 100644 index 0000000..ec2d3df --- /dev/null +++ b/dont-rely-on-luck/javascript/1/dont-rely-on-luck.js @@ -0,0 +1,4 @@ +Math.floor = function() { + return 0xCAFEBABE; +} +var guess = 0xCAFEBABE; \ No newline at end of file diff --git a/dont-rely-on-luck/javascript/2/dont-rely-on-luck.js b/dont-rely-on-luck/javascript/2/dont-rely-on-luck.js new file mode 100644 index 0000000..70b3412 --- /dev/null +++ b/dont-rely-on-luck/javascript/2/dont-rely-on-luck.js @@ -0,0 +1 @@ +guess = 42 \ No newline at end of file diff --git a/dont-rely-on-luck/javascript/3/dont-rely-on-luck.js b/dont-rely-on-luck/javascript/3/dont-rely-on-luck.js new file mode 100644 index 0000000..de63f97 --- /dev/null +++ b/dont-rely-on-luck/javascript/3/dont-rely-on-luck.js @@ -0,0 +1,2 @@ +Math.floor = x => guess; +var guess = Math.random(); \ No newline at end of file diff --git a/double-cola/README.md b/double-cola/README.md new file mode 100644 index 0000000..87ae923 --- /dev/null +++ b/double-cola/README.md @@ -0,0 +1,64 @@ +# Double Cola +[*View on Codewars*](https://www.codewars.com/kata/double-cola) + +Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. + +For example, Penny drinks the third can of cola and the queue will look like this: +``` +Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny +``` + +Write a program that will return the name of the person who will drink the n-th cola. + +Note that in the very beginning the queue looks like that: +``` +Sheldon, Leonard, Penny, Rajesh, Howard +``` +##Input + +The input data consist of an array which contains at least 1 name, and single integer n. + +```csharp +(1 ≤ n ≤ 1000000000). +``` + + + +##Output / Examples +Return the single line — the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1. Please note that you should spell the names like this: "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" (without the quotes). In that order precisely the friends are in the queue initially. + +```csharp + string[] names = new string[] { "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" }; + int n = 1; + Line.WhoIsNext(names, n) --> "Sheldon" + + int n = 6; + Line.WhoIsNext(names, n) --> "Sheldon" + + int n = 52; + Line.WhoIsNext(names, n) --> "Penny" + + int n = 7230702951; + Line.WhoIsNext(names, n) --> "Leonard" +``` +```python +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 1)=="Sheldon" +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 52)=="Penny" +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 7230702951)=="Leonard" +``` +```ruby +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 1)=="Sheldon" +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 52)=="Penny" +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 7230702951)=="Leonard" +``` +```javascript +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 1)=="Sheldon" +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 52)=="Penny" +whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 7230702951)=="Leonard" +``` + +## Timeline +- Created: 2015-04-02 +- Published: 2015-04-02 +- Approved: 2015-04-26 +- Completed: 2015-05-02 \ No newline at end of file diff --git a/double-cola/java/1/Line.java b/double-cola/java/1/Line.java new file mode 100644 index 0000000..941bb3b --- /dev/null +++ b/double-cola/java/1/Line.java @@ -0,0 +1,15 @@ +import java.util.Arrays; + +public class Line { + public static String WhoIsNext(String[] names, int n) { + int length = names.length; + int[] counts = new int[length]; + Arrays.fill(counts, 1); + for (int i = 0; ; counts[i] <<= 1, i = (i + 1) % length) { + n -= counts[i]; + if (n <= 0) { + return names[i]; + } + } + } +} \ No newline at end of file diff --git a/dubstep/README.md b/dubstep/README.md new file mode 100644 index 0000000..6e29eeb --- /dev/null +++ b/dubstep/README.md @@ -0,0 +1,48 @@ +# Dubstep +[*View on Codewars*](https://www.codewars.com/kata/dubstep) + +Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. + +Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Polycarpus inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club. + +For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX". + +Recently, Jonny has heard Polycarpus's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Polycarpus remixed. Help Jonny restore the original song. + +## Input +The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters + +## Output +Return the words of the initial song that Polycarpus used to make a dubsteb remix. Separate the words with a space. + +## Examples + +```javascript +songDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB") + // => WE ARE THE CHAMPIONS MY FRIEND +``` + +```ruby +song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB") + # => WE ARE THE CHAMPIONS MY FRIEND +``` + +```haskell +songDecoder "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB" + `shouldBe` "WE ARE THE CHAMPIONS MY FRIEND" +``` +```python +song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB") + # => WE ARE THE CHAMPIONS MY FRIEND +``` +```clojure +(song-decoder "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB") + ; => WE ARE THE CHAMPIONS MY FRIEND +``` + + +## Timeline +- Created: 2015-04-02 +- Published: 2015-04-02 +- Approved: 2015-05-08 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/dubstep/java/1/Dubstep.java b/dubstep/java/1/Dubstep.java new file mode 100644 index 0000000..71191c6 --- /dev/null +++ b/dubstep/java/1/Dubstep.java @@ -0,0 +1,6 @@ +public class Dubstep { + public static String SongDecoder (String song) + { + return song.replaceAll("(WUB)+", " ").trim(); + } +} \ No newline at end of file diff --git a/duplicate-encoder/README.md b/duplicate-encoder/README.md new file mode 100644 index 0000000..1775496 --- /dev/null +++ b/duplicate-encoder/README.md @@ -0,0 +1,25 @@ +# Duplicate Encoder +[*View on Codewars*](https://www.codewars.com/kata/duplicate-encoder) + +The goal of this exercise is to convert a string to a new string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. + +Examples: + +"din" => "(((" + +"recede" => "()()()" + +"Success" => ")())())" + +"(( @" => "))((" + +
+Notes:

+There is a flaw in the JS version, that may occur in the random tests. Do not hesitate to do several attempts before modifying your code if you fail there. +

Assertion messages may be unclear about what they display in some languages. If you read "...It Should encode XXX", the "XXX" is actually the expected result, not the input! (these languages are locked so that's not possible to correct it).
+ +## Timeline +- Created: 2015-01-12 +- Published: 2015-01-12 +- Approved: 2015-04-08 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/duplicate-encoder/java/1/DuplicateEncoder.java b/duplicate-encoder/java/1/DuplicateEncoder.java new file mode 100644 index 0000000..27e7680 --- /dev/null +++ b/duplicate-encoder/java/1/DuplicateEncoder.java @@ -0,0 +1,12 @@ +import java.util.*; +import java.util.stream.Collectors; + +public class DuplicateEncoder { + static String encode(String word) { + Map letters = word.codePoints().map(Character::toLowerCase).collect(HashMap::new, (map, i) -> { + map.computeIfPresent(i, (k, v) -> v + 1); + map.putIfAbsent(i, 1); + }, null); + return word.codePoints().map(Character::toLowerCase).mapToObj(cp -> letters.get(cp) > 1 ? ")" : "(").collect(Collectors.joining()); + } +} \ No newline at end of file diff --git a/email-validation-1/README.md b/email-validation-1/README.md new file mode 100644 index 0000000..dca0004 --- /dev/null +++ b/email-validation-1/README.md @@ -0,0 +1,23 @@ +# Email Validation +[*View on Codewars*](https://www.codewars.com/kata/email-validation-1) + +Write a function to test whether a given input is a valid email address. + +For the purposes of this kata, here is what makes a valid email: + + +* At least one letter character at the beginning +* All characters between the first character and the @ (if any) must be letters, numbers, or underscores +* There must be an @ character (after the points listed just now) +* After the @ character, there must be at least one word character (letter, number, or underscore) or hyphen +* The email must end with *at least* one set of a dot followed by one or more word characters. +* The input must NOT be case-sensitive + + +The function should return `true` or `false`. + +## Timeline +- Created: 2014-05-28 +- Published: 2014-05-28 +- Approved: null +- Completed: 2015-05-22 \ No newline at end of file diff --git a/email-validation-1/javascript/1/email-validation-1.js b/email-validation-1/javascript/1/email-validation-1.js new file mode 100644 index 0000000..d643c67 --- /dev/null +++ b/email-validation-1/javascript/1/email-validation-1.js @@ -0,0 +1,4 @@ +function validate(input){ + console.log(input); + return !!input.match(/^[A-Za-z]\w*@[\w-]+(\.\w+)+$/); +} \ No newline at end of file diff --git a/even-or-odd/README.md b/even-or-odd/README.md new file mode 100644 index 0000000..8b0a71a --- /dev/null +++ b/even-or-odd/README.md @@ -0,0 +1,24 @@ +# Even or Odd +[*View on Codewars*](https://www.codewars.com/kata/even-or-odd) + +Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. + + +```if:sql +## SQL Notes: +You will be given a table, `numbers`, with one column `number`.
+Return a table with a column `is_even`. + +### numbers table schema +* number INT + +### output table schema +* is_even STRING +``` + + +## Timeline +- Created: 2014-07-31 +- Published: 2014-07-31 +- Approved: 2014-08-08 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/even-or-odd/java/1/EvenOrOdd.java b/even-or-odd/java/1/EvenOrOdd.java new file mode 100644 index 0000000..d33e285 --- /dev/null +++ b/even-or-odd/java/1/EvenOrOdd.java @@ -0,0 +1,14 @@ +public class EvenOrOdd { + @Deprecated // Violating the code conventions + public static String even_or_odd(int number) { + return evenOrOdd(number); + } + + public static String evenOrOdd(int number) { + return even(number) ? "Even" : "Odd"; + } + + static boolean even(int number) { + return number % 2 == 0; + } +} \ No newline at end of file diff --git a/everyone-has-his-little-secrets/README.md b/everyone-has-his-little-secrets/README.md new file mode 100644 index 0000000..739a24d --- /dev/null +++ b/everyone-has-his-little-secrets/README.md @@ -0,0 +1,14 @@ +# Everyone has his little secrets +[*View on Codewars*](https://www.codewars.com/kata/everyone-has-his-little-secrets) + +Hello, + +I'm a little class and I have a secret. + +Will you find it ? + +## Timeline +- Created: 2014-11-19 +- Published: 2014-11-19 +- Approved: 2014-12-27 +- Completed: 2015-05-03 \ No newline at end of file diff --git a/everyone-has-his-little-secrets/java/1/Guesser.java b/everyone-has-his-little-secrets/java/1/Guesser.java new file mode 100644 index 0000000..c6f6fb0 --- /dev/null +++ b/everyone-has-his-little-secrets/java/1/Guesser.java @@ -0,0 +1,12 @@ +import java.lang.reflect.Field; + +public class Guesser { + public void guess() { + try { + Field secretField = LittleClass.class.getDeclaredField("secret"); + secretField.setAccessible(true); + String secret = (String) secretField.get(null); + LittleClass.isMySecret(secret); + } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException ex) {} + } +} \ No newline at end of file diff --git a/exes-and-ohs/README.md b/exes-and-ohs/README.md new file mode 100644 index 0000000..aec96cb --- /dev/null +++ b/exes-and-ohs/README.md @@ -0,0 +1,19 @@ +# Exes and Ohs +[*View on Codewars*](https://www.codewars.com/kata/exes-and-ohs) + +Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char. + +Examples input/output: +``` +XO("ooxx") => true +XO("xooxx") => false +XO("ooxXm") => true +XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true +XO("zzoo") => false +``` + +## Timeline +- Created: 2015-06-29 +- Published: 2015-06-29 +- Approved: 2015-09-05 +- Completed: 2018-03-17 \ No newline at end of file diff --git a/exes-and-ohs/javascript/1/exes-and-ohs.js b/exes-and-ohs/javascript/1/exes-and-ohs.js new file mode 100644 index 0000000..9e75408 --- /dev/null +++ b/exes-and-ohs/javascript/1/exes-and-ohs.js @@ -0,0 +1,16 @@ +function XO(str) { + let c = 0 + for (let i = 0; i < str.length; i++) { + switch(str.charAt(i)) { + case 'O': + case 'o': + c++ + break + case 'X': + case 'x': + c-- + break + } + } + return !c +} \ No newline at end of file diff --git a/feynmans-square-question/README.md b/feynmans-square-question/README.md new file mode 100644 index 0000000..7909977 --- /dev/null +++ b/feynmans-square-question/README.md @@ -0,0 +1,62 @@ +# Feynman's square question +[*View on Codewars*](https://www.codewars.com/kata/feynmans-square-question) + +# Feynman's squares +Richard Phillips Feynman was a well-known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and pioneered the field of quantum computing. + +Recently, an old farmer found some papers and notes that are believed to have belonged to Feynman. Among notes about mesons and electromagnetism, there was a napkin where he wrote a simple puzzle: "how many different squares are there in a grid of NxN squares?". + +For example, when N=2, the answer is 5: the 2x2 square itself, plus the four 1x1 squares in its corners: + + + +# Task + +You have to write a function + +```haskell +countSquares :: Integer -> Integer +``` +```javascript +function countSquares(n){ … } +``` +```ruby +def count_squares(n) +``` +```python +def count_squares(n): +``` + +that solves Feynman's question in general. The input to your function will always be a positive integer. + +#Examples + +```haskell +countSquares 1 = 1 +countSquares 2 = 5 +countSquares 3 = 14 +``` +```ruby +count_squares(1) = 1 +count_squares(2) = 5 +count_squares(3) = 14 +``` +```python +count_squares(1) = 1 +count_squares(2) = 5 +count_squares(3) = 14 +``` +```javascript +countSquares(1) = 1 +countSquares(2) = 5 +countSquares(3) = 14 +``` + + +(Adapted from the Sphere Online Judge problem SAMER08F by Diego Satoba) + +## Timeline +- Created: 2015-03-24 +- Published: 2015-03-24 +- Approved: 2015-04-02 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/feynmans-square-question/javascript/1/feynmans-square-question.js b/feynmans-square-question/javascript/1/feynmans-square-question.js new file mode 100644 index 0000000..9b3708c --- /dev/null +++ b/feynmans-square-question/javascript/1/feynmans-square-question.js @@ -0,0 +1,5 @@ +function countSquares(n) { + var count = 0; + for (var i = 1; i <= n; count += i * i, i++); + return count; +} \ No newline at end of file diff --git a/feynmans-square-question/javascript/2/feynmans-square-question.js b/feynmans-square-question/javascript/2/feynmans-square-question.js new file mode 100644 index 0000000..ce3a762 --- /dev/null +++ b/feynmans-square-question/javascript/2/feynmans-square-question.js @@ -0,0 +1 @@ +const countSquares = (n, m = 0) => n < 1 ? m : countSquares(n - 1, m + n * n); \ No newline at end of file diff --git a/find-maximum-and-minimum-values-of-a-list/README.md b/find-maximum-and-minimum-values-of-a-list/README.md new file mode 100644 index 0000000..ba0e0ef --- /dev/null +++ b/find-maximum-and-minimum-values-of-a-list/README.md @@ -0,0 +1,57 @@ +# Find Maximum and Minimum Values of a List +[*View on Codewars*](https://www.codewars.com/kata/find-maximum-and-minimum-values-of-a-list) + +Your task is to make two functions, ```max``` and ```min``` (`maximum` and `minimum` in PHP) that take a(n) array/vector of integers ```list``` as input and outputs, respectively, the largest and lowest number in that array/vector. + +#Examples +```cpp +max({4,6,2,1,9,63,-134,566}) returns 566 +min({-52, 56, 30, 29, -54, 0, -110}) returns -110 +max({5}) returns 5 +min({42, 54, 65, 87, 0}) returns 0 +``` +```csharp +max({4,6,2,1,9,63,-134,566}) returns 566 +min({-52, 56, 30, 29, -54, 0, -110}) returns -110 +max({5}) returns 5 +min({42, 54, 65, 87, 0}) returns 0 +``` +```ruby +max([4,6,2,1,9,63,-134,566]) returns 566 +min([-52, 56, 30, 29, -54, 0, -110]) returns -110 +max([5]) returns 5 +min([42, 54, 65, 87, 0]) returns 0 +``` +```python +max([4,6,2,1,9,63,-134,566]) returns 566 +min([-52, 56, 30, 29, -54, 0, -110]) returns -110 +max([5]) returns 5 +min([42, 54, 65, 87, 0]) returns 0 +``` +```javascript +max([4,6,2,1,9,63,-134,566]) returns 566 +min([-52, 56, 30, 29, -54, 0, -110]) returns -110 +max([5]) returns 5 +min([42, 54, 65, 87, 0]) returns 0 +``` +```typescript +max([4,6,2,1,9,63,-134,566]) returns 566 +min([-52, 56, 30, 29, -54, 0, -110]) returns -110 +max([5]) returns 5 +min([42, 54, 65, 87, 0]) returns 0 +``` +```java +max({4,6,2,1,9,63,-134,566}) returns 566 +min({-52, 56, 30, 29, -54, 0, -110}) returns -110 +max({5}) returns 5 +min({42, 54, 65, 87, 0}) returns 0 +``` + +#Notes +- You may consider that there will not be any empty arrays/vectors. + +## Timeline +- Created: 2016-07-04 +- Published: 2016-07-04 +- Approved: 2016-07-06 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/find-maximum-and-minimum-values-of-a-list/java/1/Kata.java b/find-maximum-and-minimum-values-of-a-list/java/1/Kata.java new file mode 100644 index 0000000..472d950 --- /dev/null +++ b/find-maximum-and-minimum-values-of-a-list/java/1/Kata.java @@ -0,0 +1,11 @@ +import java.util.stream.IntStream; +public class Kata { + + public int min(int[] list) { + return IntStream.of(list).min().getAsInt(); + } + + public int max(int[] list) { + return IntStream.of(list).max().getAsInt(); + } +} \ No newline at end of file diff --git a/find-maximum-and-minimum-values-of-a-list/javascript/1/find-maximum-and-minimum-values-of-a-list.js b/find-maximum-and-minimum-values-of-a-list/javascript/1/find-maximum-and-minimum-values-of-a-list.js new file mode 100644 index 0000000..deb0fbd --- /dev/null +++ b/find-maximum-and-minimum-values-of-a-list/javascript/1/find-maximum-and-minimum-values-of-a-list.js @@ -0,0 +1,8 @@ +var min = function(list){ + return Math.min(...list) +} + +var max = function(list){ + + return Math.max(...list) +} \ No newline at end of file diff --git a/find-nth-digit-of-a-number/README.md b/find-nth-digit-of-a-number/README.md new file mode 100644 index 0000000..ee7f45d --- /dev/null +++ b/find-nth-digit-of-a-number/README.md @@ -0,0 +1,27 @@ +# Find n'th Digit of a Number +[*View on Codewars*](https://www.codewars.com/kata/find-nth-digit-of-a-number) + +The function ```findDigit``` takes two numbers as input, ```num``` and ```nth```. It outputs the nth digit of num (counting from right to left). + +#Note +- If ```num``` is negative, ignore its sign and treat it as a positive value. +- If ```nth``` is not positive, return -1. +- Keep in mind that 42 = 00042. This means that ```findDigit(42, 5)``` would return 0. + +#Examples + +``` +findDigit(5673, 4) returns 5 +findDigit(129, 2) returns 2 +findDigit(-2825, 3) returns 8 +findDigit(-456, 4) returns 0 +findDigit(0, 20) returns 0 +findDigit(65, 0) returns -1 +findDigit(24, -8) returns -1 +``` + +## Timeline +- Created: 2016-07-05 +- Published: 2016-07-06 +- Approved: 2016-07-06 +- Completed: 2018-03-12 \ No newline at end of file diff --git a/find-nth-digit-of-a-number/javascript/1/find-nth-digit-of-a-number.js b/find-nth-digit-of-a-number/javascript/1/find-nth-digit-of-a-number.js new file mode 100644 index 0000000..bbc4ff1 --- /dev/null +++ b/find-nth-digit-of-a-number/javascript/1/find-nth-digit-of-a-number.js @@ -0,0 +1 @@ +const findDigit = (num, nth) => nth <= 0 ? -1 : Math.trunc(Math.abs(num) / 10 ** (nth - 1)) % 10 \ No newline at end of file diff --git a/find-something-in-an-array/README.md b/find-something-in-an-array/README.md new file mode 100644 index 0000000..556235f --- /dev/null +++ b/find-something-in-an-array/README.md @@ -0,0 +1,33 @@ +# Find something in an Array +[*View on Codewars*](https://www.codewars.com/kata/find-something-in-an-array) + +Create a find function that takes a string and an array as arguments. If the string is in the array, return true. + +For example: +```javascript +find("hello", ["bye bye","hello"]) // return true +find("anything", ["bye bye","hello"]) // return false +``` +```ruby +find("hello", ["bye bye","hello"]) // return true +find("anything", ["bye bye","hello"]) // return false +``` +```python +find("hello", ["bye bye","hello"]) # return true +find("anything", ["bye bye","hello"]) # return false +``` +```java +NeedleInHaystack.find("hello", new String[]{"bye bye", "hello"}) // return true +// the haystack (searchable array) will never be null, but could contain null values; +NeedleInHaystack.find("be", new String[]{"careful", null, "oops"}) // return false +// also the needle could be null too +NeedleInHaystack.find(null, new String[]{"watch", "for", null}) // return true +``` +Note: +"Hello" !== "hello" // case-sensitive comparison + +## Timeline +- Created: 2014-07-27 +- Published: 2014-07-27 +- Approved: null +- Completed: 2015-05-21 \ No newline at end of file diff --git a/find-something-in-an-array/javascript/1/find-something-in-an-array.js b/find-something-in-an-array/javascript/1/find-something-in-an-array.js new file mode 100644 index 0000000..cfbcdb0 --- /dev/null +++ b/find-something-in-an-array/javascript/1/find-something-in-an-array.js @@ -0,0 +1,3 @@ +var find = function(string, array) { + return array.indexOf(string) >= 0; +}; \ No newline at end of file diff --git a/find-the-capitals-1/README.md b/find-the-capitals-1/README.md new file mode 100644 index 0000000..f3c6ea5 --- /dev/null +++ b/find-the-capitals-1/README.md @@ -0,0 +1,31 @@ +# Find the capitals +[*View on Codewars*](https://www.codewars.com/kata/find-the-capitals-1) + +# Instructions + +Write a function that takes a single string (`word`) as argument. The function must return an ordered list containing the indexes of all capital letters in the string. + +# Example + +```javascript +Test.assertSimilar( capitals('CodEWaRs'), [0,3,4,6] ); +``` +```ruby +Test.assert_equals( capitals('CodEWaRs'), [0,3,4,6] ); +``` +```haskell +capitals "" `shouldBe` [] +capitals "CodEWaRs" `shouldBe` [0,3,4,6] +capitals "aAbB" `shouldBe` [1,3] +capitals "4ysdf4" `shouldBe` [] +capitals "ABCDEF" `shouldBe` [0..5] +``` +```csharp +Assert.AreEqual(Kata.Capitals("CodEWaRs"), new int[]{0,3,4,6}); +``` + +## Timeline +- Created: 2014-06-16 +- Published: 2014-06-16 +- Approved: 2014-06-29 +- Completed: 2015-05-23 \ No newline at end of file diff --git a/find-the-capitals-1/csharp/1/find-the-capitals-1 b/find-the-capitals-1/csharp/1/find-the-capitals-1 new file mode 100644 index 0000000..f6f3d23 --- /dev/null +++ b/find-the-capitals-1/csharp/1/find-the-capitals-1 @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +public static class Kata +{ + public static int[] Capitals(string word) + { + var capitals = new List(); + for (int i = 0, l = word.Length; i < l; i++) + { + var c = word[i]; + if (c != char.ToLower(c)) { + capitals.Add(i); + } + } + return capitals.ToArray(); + } +} \ No newline at end of file diff --git a/find-the-capitals-1/csharp/2/find-the-capitals-1 b/find-the-capitals-1/csharp/2/find-the-capitals-1 new file mode 100644 index 0000000..60ff8ef --- /dev/null +++ b/find-the-capitals-1/csharp/2/find-the-capitals-1 @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +public static class Kata +{ + public static int[] Capitals(string word) + { + var capitals = new List(); + for (int i = 0, l = word.Length; i < l; i++) + { + if (char.IsUpper(word, i)) { + capitals.Add(i); + } + } + return capitals.ToArray(); + } +} \ No newline at end of file diff --git a/find-the-capitals-1/javascript/1/find-the-capitals-1.js b/find-the-capitals-1/javascript/1/find-the-capitals-1.js new file mode 100644 index 0000000..b98c3af --- /dev/null +++ b/find-the-capitals-1/javascript/1/find-the-capitals-1.js @@ -0,0 +1,10 @@ +var capitals = function(word) { + var capitals = []; + for (var i = 0, l = word.length; i < l; i++) { + var c = word[i]; + if (c !== c.toLowerCase()) { + capitals.push(i); + } + } + return capitals; +}; \ No newline at end of file diff --git a/find-the-middle-element/README.md b/find-the-middle-element/README.md new file mode 100644 index 0000000..40b799c --- /dev/null +++ b/find-the-middle-element/README.md @@ -0,0 +1,24 @@ +# Find the middle element +[*View on Codewars*](https://www.codewars.com/kata/find-the-middle-element) + +As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements. + +The input to the function will be an array of three distinct numbers (Haskell: a tuple). + +For example: + + gimme([2, 3, 1]) => 0 + +*2* is the number that fits between *1* and *3* and the index of *2* in the input array is *0*. + +Another example (just to make sure it is clear): + + gimme([5, 10, 14]) => 1 + +*10* is the number that fits between *5* and *14* and the index of *10* in the input array is *1*. + +## Timeline +- Created: 2014-11-05 +- Published: 2014-11-05 +- Approved: 2017-06-12 +- Completed: 2015-05-22 \ No newline at end of file diff --git a/find-the-middle-element/javascript/1/find-the-middle-element.js b/find-the-middle-element/javascript/1/find-the-middle-element.js new file mode 100644 index 0000000..f1abe7b --- /dev/null +++ b/find-the-middle-element/javascript/1/find-the-middle-element.js @@ -0,0 +1,8 @@ +var gimme = function(a) { + return a[0] > a[1] ? a[1] > a[2] ? 1 + : a[0] > a[2] ? 2 + : 0 + : a[0] > a[2] ? 0 + : a[1] > a[2] ? 2 + : 1; +}; \ No newline at end of file diff --git a/find-the-mine/README.md b/find-the-mine/README.md new file mode 100644 index 0000000..84d6497 --- /dev/null +++ b/find-the-mine/README.md @@ -0,0 +1,19 @@ +# Find the Mine! +[*View on Codewars*](https://www.codewars.com/kata/find-the-mine) + +You've just discovered a square (NxN) field and you notice a warning sign. The sign states that there's a single bomb in the 2D grid-like field in front of you. + +Write a function `mineLocation`/`MineLocation` that accepts a 2D array, and returns the location of the mine. The mine is represented as the integer `1` in the 2D array. Areas in the 2D array that are not the mine will be represented as `0`s. + +The location returned should be an array (`Tuple` in C#) where the first element is the row index, and the second element is the column index of the bomb location (both should be 0 based). All 2D arrays passed into your function will be square (NxN), and there will only be one mine in the array. + +### Examples: +`mineLocation( [ [1, 0, 0], [0, 0, 0], [0, 0, 0] ] )` => returns `[0, 0]`
+`mineLocation( [ [0, 0, 0], [0, 1, 0], [0, 0, 0] ] )` => returns `[1, 1]`
+`mineLocation( [ [0, 0, 0], [0, 0, 0], [0, 1, 0] ] )` => returns `[2, 1]` + +## Timeline +- Created: 2013-11-21 +- Published: 2013-11-21 +- Approved: 2013-11-21 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/find-the-mine/javascript/1/find-the-mine.js b/find-the-mine/javascript/1/find-the-mine.js new file mode 100644 index 0000000..84a9d7d --- /dev/null +++ b/find-the-mine/javascript/1/find-the-mine.js @@ -0,0 +1,8 @@ +function mineLocation(field) { + for (var r = 0, n = field.length; r < n; r++) { + var c = field[r].indexOf(1); + if (c >= 0) { + return [r, c]; + } + } +} \ No newline at end of file diff --git a/find-the-missing-letter/README.md b/find-the-missing-letter/README.md new file mode 100644 index 0000000..57a7b53 --- /dev/null +++ b/find-the-missing-letter/README.md @@ -0,0 +1,27 @@ +# Find the missing letter +[*View on Codewars*](https://www.codewars.com/kata/find-the-missing-letter) + +#Find the missing letter + +Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array. + +You will always get an valid array. And it will be always exactly one letter be missing. The length of the array will always be at least 2.
+The array will always contain letters in only one case. + +Example: +``` +['a','b','c','d','f'] -> 'e' +['O','Q','R','S'] -> 'P' +``` + +(Use the English alphabet with 26 letters!) + +Have fun coding it and please don't forget to vote and rank this kata! :-) + +I have also created other katas. Take a look if you enjoyed this kata! + +## Timeline +- Created: 2016-11-26 +- Published: 2016-11-26 +- Approved: 2016-11-28 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/find-the-missing-letter/javascript/1/find-the-missing-letter.js b/find-the-missing-letter/javascript/1/find-the-missing-letter.js new file mode 100644 index 0000000..28a3315 --- /dev/null +++ b/find-the-missing-letter/javascript/1/find-the-missing-letter.js @@ -0,0 +1,8 @@ +function findMissingLetter(array) { + for (let i = 1;; i++) { + const c = array[i].charCodeAt() - 1 + if (array[i - 1].charCodeAt() < c) { + return String.fromCharCode(c) + } + } +} \ No newline at end of file diff --git a/find-the-odd-int/README.md b/find-the-odd-int/README.md new file mode 100644 index 0000000..6d35ed4 --- /dev/null +++ b/find-the-odd-int/README.md @@ -0,0 +1,13 @@ +# Find the odd int +[*View on Codewars*](https://www.codewars.com/kata/find-the-odd-int) + +Given an array, find the int that appears an odd number of times. + +There will always be only one integer that appears an odd number of times. + + +## Timeline +- Created: 2015-02-10 +- Published: 2015-02-10 +- Approved: 2015-09-15 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/find-the-odd-int/java/1/FindOdd.java b/find-the-odd-int/java/1/FindOdd.java new file mode 100644 index 0000000..16086a2 --- /dev/null +++ b/find-the-odd-int/java/1/FindOdd.java @@ -0,0 +1,27 @@ +import java.util.*; + +public class FindOdd { + public static int findIt(final int[] ns) { + final Map nss = new HashMap<>(); + for (final int n : ns) { + put(nss, n); + } + for (final Map.Entry e : nss.entrySet()) { + if (odd(e.getValue())) { + return e.getKey(); + } + } + throw new IllegalArgumentException(Arrays.toString(ns)); + } + + private static void put(final Map nss, final int n) { + final Integer ns = nss.putIfAbsent(n, 1); + if (ns != null) { + nss.put(n, ns + 1); + } + } + + private static boolean odd(final int n) { + return n % 2 == 1; + } +} \ No newline at end of file diff --git a/find-the-parity-outlier/README.md b/find-the-parity-outlier/README.md new file mode 100644 index 0000000..5fb5b10 --- /dev/null +++ b/find-the-parity-outlier/README.md @@ -0,0 +1,20 @@ +# Find The Parity Outlier +[*View on Codewars*](https://www.codewars.com/kata/find-the-parity-outlier) + +You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer `N`. Write a method that takes the array as an argument and returns this "outlier" `N`. + +## Examples + +```py +[2, 4, 0, 100, 4, 11, 2602, 36] +Should return: 11 (the only odd number) + +[160, 3, 1719, 19, 11, 13, -21] +Should return: 160 (the only even number) +``` + +## Timeline +- Created: 2015-04-09 +- Published: 2015-04-09 +- Approved: 2015-11-20 +- Completed: 2015-05-06 \ No newline at end of file diff --git a/find-the-parity-outlier/java/1/FindOutlier.java b/find-the-parity-outlier/java/1/FindOutlier.java new file mode 100644 index 0000000..15a57bd --- /dev/null +++ b/find-the-parity-outlier/java/1/FindOutlier.java @@ -0,0 +1,21 @@ +public class FindOutlier { + static int find(int[] integers) { + int first = integers[0]; + boolean even = even(first); + int successive = integers[1]; + if (even ^ even(successive)) { + return even ^ even(integers[2]) ? first : successive; + } + for (int i = 2; i < integers.length; i++) { + successive = integers[i]; + if (even ^ even(successive)) { + return successive; + } + } + throw new IllegalArgumentException(even ? "even" : "odd"); + } + + static boolean even(int n) { + return n % 2 == 0; + } +} \ No newline at end of file diff --git a/find-the-remainder/README.md b/find-the-remainder/README.md new file mode 100644 index 0000000..398d830 --- /dev/null +++ b/find-the-remainder/README.md @@ -0,0 +1,10 @@ +# Find the Remainder +[*View on Codewars*](https://www.codewars.com/kata/find-the-remainder) + +Write a function that accepts two arguments and returns the remainder after dividing the larger number by the smaller number. Division by zero should return NaN (in C#, throw a new `DivideByZeroException` instead). Arguments will both be integers. + +## Timeline +- Created: 2013-10-04 +- Published: 2013-10-23 +- Approved: null +- Completed: 2014-01-21 \ No newline at end of file diff --git a/find-the-remainder/javascript/1/find-the-remainder.js b/find-the-remainder/javascript/1/find-the-remainder.js new file mode 100644 index 0000000..4c0cb54 --- /dev/null +++ b/find-the-remainder/javascript/1/find-the-remainder.js @@ -0,0 +1,3 @@ +function remainder(a, b){ + return a < b ? b%a :a%b; +} \ No newline at end of file diff --git a/find-the-unknown-digit/README.md b/find-the-unknown-digit/README.md new file mode 100644 index 0000000..686f666 --- /dev/null +++ b/find-the-unknown-digit/README.md @@ -0,0 +1,28 @@ +# Find the unknown digit +[*View on Codewars*](https://www.codewars.com/kata/find-the-unknown-digit) + +To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers. + +You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figured out most of the digits as well as a few operators, but he needs your help to figure out the rest. + +The professor will give you a simple math expression, of the form + +``` +[number][op][number]=[number] +``` + +He has converted all of the runes he knows into digits. The only operators he knows are addition (`+`),subtraction(`-`), and multiplication (`*`), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is 0, therefore 00 would not be a valid number. + +Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case. + +Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists. + +~~~if:php +**Most of the time, the professor will be able to figure out most of the runes himself, but sometimes, there may be exactly 1 rune present in the expression that the professor cannot figure out (resulting in all question marks where the digits are in the expression) so be careful ;)** +~~~ + +## Timeline +- Created: 2014-11-19 +- Published: 2014-11-20 +- Approved: 2016-11-05 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/find-the-unknown-digit/java/1/Runes.java b/find-the-unknown-digit/java/1/Runes.java new file mode 100644 index 0000000..fe6137a --- /dev/null +++ b/find-the-unknown-digit/java/1/Runes.java @@ -0,0 +1,157 @@ +import java.util.function.IntBinaryOperator; +import java.util.stream.Stream; + +public class Runes { + private static final int RADIX = 10; + private static final char RUNE = '?'; + private static final char NEGATE = '-'; + private static final char EQUALS = '='; + + public static int solveExpression(final String expression) { + return RunedExpression.fromString(expression).findDigit(); + } + + static class RunedExpression { + static RunedExpression fromString(final String expression) { + int index = 0; + final String leftString = number(expression, index); + index += leftString.length(); + final char operatorChar = operator(expression, index++); + final String rightString = number(expression, index); + index += rightString.length(); + equals(expression, index++); + final String resultString = number(expression, index); + index += resultString.length(); + if (index < expression.length()) { + throw new IllegalArgumentException(String.format("unconsumed characters at %d of \"%s\"", index, expression)); + } + return new RunedExpression(leftString, operatorChar, rightString, resultString); + } + + static String number(final String expression, final int fromIndex) { + final int length = expression.length(); + final StringBuilder number = new StringBuilder(length - fromIndex); + for (int i = fromIndex; i < length; i++) { + final char c = expression.charAt(i); + if (c == NEGATE) { + if (i != fromIndex) { + break; + } + number.append(c); + } else if (c == RUNE || Character.isDigit(c)) { + number.append(c); + } else { + break; + } + } + final int numberLength = number.length(); + if (numberLength == 0 || numberLength == 1 && number.charAt(0) == NEGATE) { + throw new IllegalArgumentException(String.format("expected number at %d from \"%s\", got \"%s\" instead", fromIndex, expression, number)); + } + return number.toString(); + } + + static char operator(final String expression, final int index) { + return expression.charAt(index); + } + + static void equals(final String expression, final int index) { + final char c = expression.charAt(index); + if (c != EQUALS) { + throw new IllegalArgumentException(String.format("expected '%c' at %d from \"%s\", got '%c' instead", EQUALS, index, expression, c)); + } + } + + final String leftString; + final char operatorChar; + final String rightString; + final String resultString; + + RunedExpression(final String leftString, final char operatorChar, final String rightString, final String resultString) { + this.leftString = leftString; + this.operatorChar = operatorChar; + this.rightString = rightString; + this.resultString = resultString; + } + + int findDigit() { + final Operator operator = Operator.fromSymbol(operatorChar); + for (int i = leadingZero() ? 1 : 0; i < RADIX; i++) { + final char digit = Character.forDigit(i, RADIX); + final String digitString = String.valueOf(digit); + if (strings().noneMatch(s -> s.contains(digitString))) { + final int[] numbers = strings() + .map(string -> string.replace(RUNE, digit)) + .mapToInt(Integer::parseInt) + .toArray(); + if (new Expression(numbers[0], operator, numbers[1], numbers[2]).eval()) { + return i; + } + } + } + return -1; + } + + boolean leadingZero() { + return strings().anyMatch(s -> s.length() > 1 && (s.charAt(0) == RUNE || s.charAt(0) == NEGATE && s.charAt(1) == RUNE)); + } + + private Stream strings() { + return Stream.of(leftString, rightString, resultString); + } + } + + static class Expression { + final int firstOperand; + final IntBinaryOperator operator; + final int secondOperand; + final int result; + + Expression(final int left, final IntBinaryOperator operator, final int right, final int result) { + this.firstOperand = left; + this.operator = operator; + this.secondOperand = right; + this.result = result; + } + + boolean eval() { + return operator.applyAsInt(firstOperand, secondOperand) == result; + } + } + + enum Operator implements IntBinaryOperator { + PLUS('+') { + @Override + public int applyAsInt(final int left, final int right) { + return left + right; + } + }, + MINUS('-') { + @Override + public int applyAsInt(final int left, final int right) { + return left - right; + } + }, + MULTIPLY('*') { + @Override + public int applyAsInt(final int left, final int right) { + return left * right; + } + }; + + static Operator fromSymbol(final char symbol) { + for (final Operator operator : values()) { + if (operator.symbol == symbol) { + return operator; + } + } + throw new IllegalArgumentException(String.format("'%c'", symbol)); + } + + final char symbol; + + Operator(final char symbol) { + this.symbol = symbol; + } + } +} \ No newline at end of file diff --git a/find-your-villain-name/README.md b/find-your-villain-name/README.md new file mode 100644 index 0000000..4e7f606 --- /dev/null +++ b/find-your-villain-name/README.md @@ -0,0 +1,46 @@ +# Find Your Villain Name +[*View on Codewars*](https://www.codewars.com/kata/find-your-villain-name) + +Create a function, getVillainName, that returns a villain name based on the user's birthday. (The birthday will be passed to the function as a valid Date object, so for simplicity, there's no need to worry about converting strings to dates.) + +The first name will come from the month, and the last name will come from the last digit of the date. + +Month -> first name +
    +
  • January -> "The Evil"
  • +
  • February -> "The Vile"
  • +
  • March -> "The Cruel"
  • +
  • April -> "The Trashy"
  • +
  • May -> "The Despicable"
  • +
  • June -> "The Embarrassing"
  • +
  • July -> "The Disreputable"
  • +
  • August -> "The Atrocious"
  • +
  • September -> "The Twirling"
  • +
  • October -> "The Orange"
  • +
  • November -> "The Terrifying"
  • +
  • December -> "The Awkward"
  • +
+ +Last digit of date -> last name +
    +
  • 0 -> "Mustache"
  • +
  • 1 -> "Pickle"
  • +
  • 2 -> "Hood Ornament"
  • +
  • 3 -> "Raisin"
  • +
  • 4 -> "Recycling Bin"
  • +
  • 5 -> "Potato"
  • +
  • 6 -> "Tomato"
  • +
  • 7 -> "House Cat"
  • +
  • 8 -> "Teaspoon"
  • +
  • 9 -> "Laundry Basket"
  • +
+ +The returned value should be a string in the form of "First Name Last Name". + +For example, a birthday of November 18 would return "The Terrifying Teaspoon" + +## Timeline +- Created: 2014-05-08 +- Published: 2014-05-09 +- Approved: 2014-09-03 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/find-your-villain-name/javascript/1/find-your-villain-name.js b/find-your-villain-name/javascript/1/find-your-villain-name.js new file mode 100644 index 0000000..15d2847 --- /dev/null +++ b/find-your-villain-name/javascript/1/find-your-villain-name.js @@ -0,0 +1,9 @@ +const firstNames = [ "The Evil", "The Vile", "The Cruel", "The Trashy", "The Despicable", "The Embarrassing", + "The Disreputable", "The Atrocious", "The Twirling", "The Orange", "The Terrifying", "The Awkward" ]; + +const lastNames = [ "Mustache", "Pickle", "Hood Ornament", "Raisin", "Recycling Bin", + "Potato", "Tomato", "House Cat", "Teaspoon", "Laundry Basket" ]; + +function getVillainName(birthday) { + return firstNames[birthday.getMonth()] + ' ' + lastNames[birthday.getDate() % 10]; +} \ No newline at end of file diff --git a/finding-neo-pg-13/README.md b/finding-neo-pg-13/README.md new file mode 100644 index 0000000..074a501 --- /dev/null +++ b/finding-neo-pg-13/README.md @@ -0,0 +1,32 @@ +# Finding Neo (PG-13) +[*View on Codewars*](https://www.codewars.com/kata/finding-neo-pg-13) + +Note: This version is focused on the plot, not on special effects. If you need high-speed action, check out [Finding Neo (NC-17)](/kata/finding-neo-nc-17). + +Neo is somewhere in the Matrix. +```java +public interface Matrix { + public int size(); + public int get(int x, int y); +} +``` +You are Morpheus, and your job is to find him. +```java +public class Morpheus { + public int[] find(Matrix matrix, int neo) { + // return Neo's x and y coordinates as a two-element array + } +} +``` +The matrix is controlled by machines, so it is very orderly. It is quadratic, and the following rules hold for all elements: +``` +matrix[x,y] < matrix[x+1,y] +matrix[x,y] < matrix[x,y+1] +``` +And of course, there will be no duplicates of Neo - he is *The One*. + +## Timeline +- Created: 2015-04-06 +- Published: 2015-04-06 +- Approved: 2017-05-10 +- Completed: 2015-05-16 \ No newline at end of file diff --git a/finding-neo-pg-13/java/1/Morpheus.java b/finding-neo-pg-13/java/1/Morpheus.java new file mode 100644 index 0000000..698e1cc --- /dev/null +++ b/finding-neo-pg-13/java/1/Morpheus.java @@ -0,0 +1,17 @@ +public class Morpheus { + public int[] find(Matrix matrix, int neo) { + int size = matrix.size(); + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + int n = matrix.get(x, y); + if (n > neo) { + break; + } + if (n == neo) { + return new int[]{x, y}; + } + } + } + throw new IllegalArgumentException("Neo is The Zero"); + } +} \ No newline at end of file diff --git a/finding-neo-pg-13/java/2/Morpheus.java b/finding-neo-pg-13/java/2/Morpheus.java new file mode 100644 index 0000000..3ead329 --- /dev/null +++ b/finding-neo-pg-13/java/2/Morpheus.java @@ -0,0 +1,35 @@ +public class Morpheus { + public int[] find(Matrix matrix, int neo) { + int size = matrix.size(); + for (int x = 0, toIndex = size; x < size; x++) { + int y = binarySearch(matrix, x, toIndex, neo); + if (y >= 0) { + return new int[]{x, y}; + } + toIndex = -(y + 1); + } + return null; + } + + /** + * @see java.util.Arrays#binarySearch0(int[], int, int, int) + */ + private static int binarySearch(Matrix matrix, int x, int toIndex, int key) { + int low = 0; + int high = toIndex - 1; + + while (low <= high) { + int mid = (low + high) >>> 1; + int midVal = matrix.get(x, mid); + + if (midVal < key) { + low = mid + 1; + } else if (midVal > key) { + high = mid - 1; + } else { + return mid; + } + } + return -(low + 1); + } +} \ No newline at end of file diff --git a/fix-me/README.md b/fix-me/README.md new file mode 100644 index 0000000..a3df850 --- /dev/null +++ b/fix-me/README.md @@ -0,0 +1,12 @@ +# Fix me +[*View on Codewars*](https://www.codewars.com/kata/fix-me) + +# Why the function fixMe() is not working? + +See the tests to find out what needs to be fixed. + +## Timeline +- Created: 2014-02-20 +- Published: 2014-02-20 +- Approved: null +- Completed: 2015-05-23 \ No newline at end of file diff --git a/fix-me/javascript/1/fix-me.js b/fix-me/javascript/1/fix-me.js new file mode 100644 index 0000000..c5c73f3 --- /dev/null +++ b/fix-me/javascript/1/fix-me.js @@ -0,0 +1,13 @@ +function fixMe() { + var numbers = new Array(10); + for (var i = 0; i < 10; i++) { + numbers[i] = fix(i); + } + return numbers; +} + +function fix(i) { + return function() { + return i; + }; +} \ No newline at end of file diff --git a/friend-or-foe/README.md b/friend-or-foe/README.md new file mode 100644 index 0000000..183a88e --- /dev/null +++ b/friend-or-foe/README.md @@ -0,0 +1,16 @@ +# Friend or Foe? +[*View on Codewars*](https://www.codewars.com/kata/friend-or-foe) + +Make a program that filters a list of strings and returns a list with only your friends name in it. + +If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... + +Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"] + +Note: keep the original order of the names in the output. + +## Timeline +- Created: 2015-07-26 +- Published: 2015-07-26 +- Approved: 2016-11-26 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/friend-or-foe/javascript/1/friend-or-foe.js b/friend-or-foe/javascript/1/friend-or-foe.js new file mode 100644 index 0000000..249dbc7 --- /dev/null +++ b/friend-or-foe/javascript/1/friend-or-foe.js @@ -0,0 +1,3 @@ +function friend(friends){ + return friends.filter(friend=>friend.length===4); +} \ No newline at end of file diff --git a/function-1-hello-world/README.md b/function-1-hello-world/README.md new file mode 100644 index 0000000..9699026 --- /dev/null +++ b/function-1-hello-world/README.md @@ -0,0 +1,14 @@ +# Function 1 - hello world +[*View on Codewars*](https://www.codewars.com/kata/function-1-hello-world) + +Make a simple function called **greet** that returns the most-famous "hello world!". + +### Style Points + +Sure, this is about as easy as it gets. But how clever can you be to create the most creative hello world you can think of? What is a "hello world" solution you would want to show your friends? + +## Timeline +- Created: 2013-09-19 +- Published: 2013-09-19 +- Approved: null +- Completed: 2015-05-06 \ No newline at end of file diff --git a/function-1-hello-world/java/1/HelloWorld.java b/function-1-hello-world/java/1/HelloWorld.java new file mode 100644 index 0000000..879a55f --- /dev/null +++ b/function-1-hello-world/java/1/HelloWorld.java @@ -0,0 +1,156 @@ +public class HelloWorld { + public static String greet() { + final String echoUntilZero = ",[.[-],]"; + return new BrainFuck(echoUntilZero).process("hello world!\0bye bye!"); + } +} + +class BrainFuck { + public static final char OP_NEXT = '>'; + public static final char OP_PREVIOUS = '<'; + public static final char OP_INCREMENT = '+'; + public static final char OP_DECREMENT = '-'; + public static final char OP_WRITE = '.'; + public static final char OP_READ = ','; + public static final char OP_JUMP_ZERO = '['; + public static final char OP_JUMP_NONZERO = ']'; + + private final String code; + + public BrainFuck(final String code) { + this.code = code; + } + + public String process(final String input) { + final Data data = new Data(2); + int inputPointer = 0; + final StringBuilder output = new StringBuilder(); + for (int instructionPointer = 0; instructionPointer < code.length(); instructionPointer++) { + final char instruction = code.charAt(instructionPointer); + switch (instruction) { + case OP_NEXT: + data.next(); + break; + case OP_PREVIOUS: + data.previous(); + break; + case OP_INCREMENT: + data.increment(); + break; + case OP_DECREMENT: + data.decrement(); + break; + case OP_WRITE: + output.append((char) Byte.toUnsignedInt(data.get())); + break; + case OP_READ: + data.set((byte) input.charAt(inputPointer++)); + break; + case OP_JUMP_ZERO: + if (data.get() == 0) { + instructionPointer = matchNext(instructionPointer); + } + break; + case OP_JUMP_NONZERO: + if (data.get() != 0) { + instructionPointer = matchPrevious(instructionPointer); + } + break; + } + } + return output.toString(); + } + + private int matchNext(final int instructionPointer) { + return match(instructionPointer, true); + } + + private int matchPrevious(final int instructionPointer) { + return match(instructionPointer, false); + } + + private int match(final int start, final boolean next) { + final int step; + final char same; + final char match; + if (next) { + step = 1; + same = OP_JUMP_ZERO; + match = OP_JUMP_NONZERO; + } else { + step = -1; + same = OP_JUMP_NONZERO; + match = OP_JUMP_ZERO; + } + + for (int instructionPointer = start + step, level = 1; instructionPointer < code.length(); instructionPointer += step) { + final char nextInstruction = code.charAt(instructionPointer); + if (nextInstruction == same) { + level++; + } else if (nextInstruction == match && --level == 0) { + return instructionPointer; + } + } + throw new IllegalStateException(String.format("no match for start=%s and next=%b", start, next)); + } +} + +class Data { + private final int growth; + private byte[] data; + private int pointer = 0; + + Data(final int growth) { + this.growth = growth; + data = new byte[growth]; + } + + void next() { + pointer++; + } + + void previous() { + pointer--; + } + + void increment() { + ensureCapacity(); + data[pointer]++; + } + + void decrement() { + ensureCapacity(); + data[pointer]--; + } + + byte get() { + ensureCapacity(); + return data[pointer]; + } + + void set(final byte b) { + ensureCapacity(); + data[pointer] = b; + } + + private void ensureCapacity() { + final int difference = data.length - pointer; + final int rate; + final int destPos; + + if (difference <= 0) { + rate = 1 - difference / growth; + destPos = 0; + } else if (difference > data.length) { + rate = 1 + difference / growth; + destPos = rate * growth; + } else { + return; + } + + final byte[] data = new byte[this.data.length + rate * growth]; + System.arraycopy(this.data, 0, data, destPos, this.data.length); + this.data = data; + pointer += destPos; + } +} \ No newline at end of file diff --git a/function-1-hello-world/java/2/HelloWorld.java b/function-1-hello-world/java/2/HelloWorld.java new file mode 100644 index 0000000..9c83f18 --- /dev/null +++ b/function-1-hello-world/java/2/HelloWorld.java @@ -0,0 +1,193 @@ +public class HelloWorld { + private static final String HELLO_WORLD + = "`````````````````````````````````````````````````````````````````````````````````````````" + + "``[-]@>````````````````````````````[-]@@@`````````@@@@@@@````````````````````````````````" + + "``@@@@<````````````````````````````@@@@@@``````````@@@@@@````````````````````````````````" + + "````@@>````````````````````````````````++`````````````+++````````````````````````````````" + + "````++/````````````````````````````````++`````````````+[@````````````````````````````````" + + "````@@<+++++/````````;+++++````````````@@`````````````@@@```````````@@@@@@```````````````" + + "````@@@@@@@@@@``````@@@@@@@@@``````````@@`````````````@@@`````````>-]@@@@@@<`````````````" + + "````++++@.;---`````@@@@.>+++[@`````````@@`````````````@@@````````<+++@>;-]@@`````````````" + + "````@@@`````@@<```--@.`````@@@`````````@@`````````````@@@````````@@@``````@@@````````````" + + "````@@.`````++;```+@@```````@@@````````@@`````````````@@@```````.@@```````>++````````````" + + "````++/`````++;```+++[@@@@@@@@@````````@@`````````````@@@```````@@@````````@@<```````````" + + "````--/`````--;```-----@@@@@@@@````````@@`````````````@@@```````@@@````````@@@```````````" + + "````@@>`````-]<```++@``````````````````@@`````````````@@@```````.@@````````@@>```````````" + + "````++/`````++;```+++/`````````````````++`````````````[@@````````@@@``````@@@````````````" + + "``@@@@@@``<+++++```++++@>;-]@@@```@@@@@@@@@@@@````@@@@@@@@@@@````<++++;;++@@.````````````" + + "``@@@@@@``@@@@@@````@@@@@@@@@@@```@@@@@@@@@@@@```@@@@@@@@@@@@>````;+++[@@@@<`````````````" + + "```---@>```-]@@<`````;+@@@@@.``````+++@@@@@@@`````.@@@@@@@@@>```````++[@@<```````````````" + + "`````````````````````````````````````````````````````````````````````````````````````````" + + "`````````````````````````````````````````````````````````````````````````````````````````" + + "``````````````````````````````````````````````````--@@@@@```````````````@@@@@```````@@@@`" + + "```````````````````````````````````````````````````@@@@@@```````````````>-]@@```````@@@@`" + + "``````````````````````````````````````````````````````@@@`````````````````@@@```````@@@@`" + + "``````````````````````````````````````````````````````@@@`````````````````@@@```````<--@`" + + "``@@@@.````>+++[``````@@@@@<```````---@>`/-]@@````````@@@``````````<+@@@@`@@@```````.@@@`" + + "`@@@@@@````@@@@@@```@@@@@@@@@`````@@@@@>+++++++```````+[@`````````@@@@@@@@@@@````````@@@`" + + "``@@@@@````<----/``----@>;-]@@`````@@@@@@@@<---```````@@@````````@@@@./@@@@@@````````@@@`" + + "```@@;``@@;``@@```/@@@`````@@@@``````@@@@@````````````@@@```````/@@@`````@@@@````````@@@`" + + "```@@@`@@@@`;@@```@@@```````@@@``````@@@``````````````@@@```````@@@```````@@@````````@@@`" + + "```@@@`@@@@`@@@```@@;````````@@``````@@/``````````````@@@```````@@@```````@@@````````@@@`" + + "````@@/@@@@@@@@```@@;````````@@``````@@/``````````````@@@```````@@;```````@@@````````@@``" + + "````@@@@@@@@@@````@@@```````@@@``````@@/``````````````@@@```````@@@```````@@@````````````" + + "````@@@@;`@@@@````;@@@`````;@@@``````@@/``````````````@@@```````;@@;`````@@@@````````````" + + "````@@@@``@@@@`````@@@@@;@@@@@````@@@@@@@@@@;`````@@@@@@@@@@@````@@@@@;@@@@@@@@``````/@``" + + "`````@@@``/@@@``````@@@@@@@@@`````@@@@@@@@@@@````@@@@@@@@@@@@;````@@@@@@@@@@@@@``````@@@`" + + "`````@@````@@/````````@@@@@/``````;@@@@@@@@@``````;@@@@@@@@@;``````/@@@@@`@@@@```````@@;`" + + "`````````````````````````````````````````````````````````````````````````````````````````"; + + public static String greet() { + return new BrainFuck(HELLO_WORLD).process(""); + } +} + +class BrainFuck { + public static final char OP_NEXT = '>'; + public static final char OP_PREVIOUS = '<'; + public static final char OP_INCREMENT = '+'; + public static final char OP_DECREMENT = '-'; + public static final char OP_WRITE = '.'; + public static final char OP_READ = ','; + public static final char OP_JUMP_ZERO = '['; + public static final char OP_JUMP_NONZERO = ']'; + + private final String code; + + public BrainFuck(final String code) { + this.code = code; + } + + public String process(final String input) { + final Data data = new Data(2); + int inputPointer = 0; + final StringBuilder output = new StringBuilder(); + for (int instructionPointer = 0; instructionPointer < code.length(); instructionPointer++) { + final char instruction = code.charAt(instructionPointer); + switch (instruction) { + case OP_NEXT: + data.next(); + break; + case OP_PREVIOUS: + data.previous(); + break; + case OP_INCREMENT: + data.increment(); + break; + case OP_DECREMENT: + data.decrement(); + break; + case OP_WRITE: + output.append((char) Byte.toUnsignedInt(data.get())); + break; + case OP_READ: + data.set((byte) input.charAt(inputPointer++)); + break; + case OP_JUMP_ZERO: + if (data.get() == 0) { + instructionPointer = matchNext(instructionPointer); + } + break; + case OP_JUMP_NONZERO: + if (data.get() != 0) { + instructionPointer = matchPrevious(instructionPointer); + } + break; + } + } + return output.toString(); + } + + private int matchNext(final int instructionPointer) { + return match(instructionPointer, true); + } + + private int matchPrevious(final int instructionPointer) { + return match(instructionPointer, false); + } + + private int match(final int start, final boolean next) { + final int step; + final char same; + final char match; + if (next) { + step = 1; + same = OP_JUMP_ZERO; + match = OP_JUMP_NONZERO; + } else { + step = -1; + same = OP_JUMP_NONZERO; + match = OP_JUMP_ZERO; + } + + for (int instructionPointer = start + step, level = 1; instructionPointer < code.length(); instructionPointer += step) { + final char nextInstruction = code.charAt(instructionPointer); + if (nextInstruction == same) { + level++; + } else if (nextInstruction == match && --level == 0) { + return instructionPointer; + } + } + throw new IllegalStateException(String.format("no match for start=%s and next=%b", start, next)); + } +} + +class Data { + private final int growth; + private byte[] data; + private int pointer = 0; + + Data(final int growth) { + this.growth = growth; + data = new byte[growth]; + } + + void next() { + pointer++; + } + + void previous() { + pointer--; + } + + void increment() { + ensureCapacity(); + data[pointer]++; + } + + void decrement() { + ensureCapacity(); + data[pointer]--; + } + + byte get() { + ensureCapacity(); + return data[pointer]; + } + + void set(final byte b) { + ensureCapacity(); + data[pointer] = b; + } + + private void ensureCapacity() { + final int difference = data.length - pointer; + final int rate; + final int destPos; + + if (difference <= 0) { + rate = 1 - difference / growth; + destPos = 0; + } else if (difference > data.length) { + rate = 1 + difference / growth; + destPos = rate * growth; + } else { + return; + } + + final byte[] data = new byte[this.data.length + rate * growth]; + System.arraycopy(this.data, 0, data, destPos, this.data.length); + this.data = data; + pointer += destPos; + } +} \ No newline at end of file diff --git a/get-key-slash-value-pairs-as-arrays/README.md b/get-key-slash-value-pairs-as-arrays/README.md new file mode 100644 index 0000000..44b3f99 --- /dev/null +++ b/get-key-slash-value-pairs-as-arrays/README.md @@ -0,0 +1,23 @@ +# Get key/value pairs as arrays +[*View on Codewars*](https://www.codewars.com/kata/get-key-slash-value-pairs-as-arrays) + +Complete the keysAndValues function so that it takes in an object and returns the keys and values as separate arrays. + +Example: +```javascript +keysAndValues({a: 1, b: 2, c: 3}) // should return [['a', 'b', 'c'], [1, 2, 3]] +``` +```coffeescript +keysAndValues({a: 1, b: 2, c: 3}) # should return [['a', 'b', 'c'], [1, 2, 3]] +``` +```ruby +keysAndValues({a: 1, b: 2, c: 3}) # should return [[:a, :b, :c], [1, 2, 3]] +``` + +**Style Points (JS/CoffeeScript only)**: This kata only tests for data that uses object literal notation (simple objects). For extra style, can you get your method to check for objects that extend their prototype? + +## Timeline +- Created: 2013-04-04 +- Published: 2013-06-24 +- Approved: null +- Completed: 2016-09-08 \ No newline at end of file diff --git a/get-key-slash-value-pairs-as-arrays/javascript/1/get-key-slash-value-pairs-as-arrays.js b/get-key-slash-value-pairs-as-arrays/javascript/1/get-key-slash-value-pairs-as-arrays.js new file mode 100644 index 0000000..18c4891 --- /dev/null +++ b/get-key-slash-value-pairs-as-arrays/javascript/1/get-key-slash-value-pairs-as-arrays.js @@ -0,0 +1,5 @@ +function keysAndValues(data) { + let keys = Object.keys(data); + let values = keys.map(key => data[key]); + return [keys, values]; +} \ No newline at end of file diff --git a/get-the-middle-character/README.md b/get-the-middle-character/README.md new file mode 100644 index 0000000..39bfa3d --- /dev/null +++ b/get-the-middle-character/README.md @@ -0,0 +1,45 @@ +# Get the Middle Character +[*View on Codewars*](https://www.codewars.com/kata/get-the-middle-character) + +You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. + +#Examples: +~~~if-not:bf +``` +Kata.getMiddle("test") should return "es" + +Kata.getMiddle("testing") should return "t" + +Kata.getMiddle("middle") should return "dd" + +Kata.getMiddle("A") should return "A" + +``` +~~~ +~~~if:bf +``` +runBF("test\0") should return "es" + +runBF("testing\0") should return "t" + +runBF("middle\0") should return "dd" + +runBF("A\0") should return "A" + +``` +~~~ + +#Input + +A word (string) of length `0 < str < 1000` (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out. + + +#Output + +The middle character(s) of the word represented as a string. + +## Timeline +- Created: 2015-12-18 +- Published: 2015-12-18 +- Approved: 2015-12-21 +- Completed: 2017-12-12 \ No newline at end of file diff --git a/get-the-middle-character/javascript/1/get-the-middle-character.js b/get-the-middle-character/javascript/1/get-the-middle-character.js new file mode 100644 index 0000000..a173171 --- /dev/null +++ b/get-the-middle-character/javascript/1/get-the-middle-character.js @@ -0,0 +1,4 @@ +function getMiddle(s) { + const l = s.length / 2 + return s.substring(Math.floor(l - 0.5), l + 1) +} \ No newline at end of file diff --git a/give-me-a-diamond/README.md b/give-me-a-diamond/README.md new file mode 100644 index 0000000..e97f234 --- /dev/null +++ b/give-me-a-diamond/README.md @@ -0,0 +1,27 @@ +# Give me a Diamond +[*View on Codewars*](https://www.codewars.com/kata/give-me-a-diamond) + +This kata is to practice simple string output. +Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help. + +###Task: + +You need to return a string that displays a diamond shape on the screen using asterisk ("`*`") characters. Please see provided test cases for exact output format. + +The shape that will be returned from `print` method resembles a diamond, where the number provided as input represents the number of `*`’s printed on the middle line. The line above and below will be centered and will have 2 less `*`’s than the middle line. This reduction by 2 `*`’s for each line continues until a line with a single `*` is printed at the top and bottom of the figure. + +Return `null` if input is even number or negative (as it is not possible to print diamond with even number or negative number). + +Please see provided test case(s) for examples. + +#### Python Note +Since `print` is a reserved word in Python, Python students must implement the `diamond(n)` method instead, and return `None` for invalid input. + +#### JS Note +JS students, like Python ones, must implement the `diamond(n)` method, and return `null` for invalid input. + +## Timeline +- Created: 2015-03-13 +- Published: 2015-03-13 +- Approved: 2015-07-03 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/give-me-a-diamond/java/1/Diamond.java b/give-me-a-diamond/java/1/Diamond.java new file mode 100644 index 0000000..df1fa39 --- /dev/null +++ b/give-me-a-diamond/java/1/Diamond.java @@ -0,0 +1,51 @@ +class Diamond { + public static String print(final int n) { + if (!positive(n) || even(n)) { + return null; + } + final StringBuilder b = new StringBuilder(); + for (int i = 0; i < n; i++) { + line(b, i, n); + } + return b.toString(); + } + + private static boolean positive(final int n) { + return n > 0; + } + + private static boolean even(final int n) { + return n % 2 == 0; + } + + private static void line(final StringBuilder b, final int i, final int n) { + lineFeed(asterisks(spaces(b, i, n), i, n)); + } + + private static StringBuilder spaces(final StringBuilder b, final int i, final int n) { + return append(b, ' ', spaces(i, n)); + } + + private static int spaces(final int i, final int n) { + return Math.abs(i - n / 2); + } + + private static StringBuilder asterisks(final StringBuilder b, final int i, final int n) { + return append(b, '*', asterisks(i, n)); + } + + private static int asterisks(final int i, final int n) { + return n - 2 * spaces(i, n); + } + + private static StringBuilder lineFeed(final StringBuilder b) { + return b.append('\n'); + } + + private static StringBuilder append(final StringBuilder b, final char c, final int times) { + for (int i = 0; i < times; i++) { + b.append(c); + } + return b; + } +} \ No newline at end of file diff --git a/greatest-common-divisor-bitcount/README.md b/greatest-common-divisor-bitcount/README.md new file mode 100644 index 0000000..4ebe6fe --- /dev/null +++ b/greatest-common-divisor-bitcount/README.md @@ -0,0 +1,20 @@ +# Greatest Common Divisor Bitcount +[*View on Codewars*](https://www.codewars.com/kata/greatest-common-divisor-bitcount) + +The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. + +Taken from Wikipedia: +"In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." + +For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. + +If both parameters are 0, the method should return 0. +The function must be able to handle negative input. + + + +## Timeline +- Created: 2015-01-12 +- Published: 2015-01-12 +- Approved: 2015-05-19 +- Completed: 2015-05-08 \ No newline at end of file diff --git a/greatest-common-divisor-bitcount/java/1/BinaryGCD.java b/greatest-common-divisor-bitcount/java/1/BinaryGCD.java new file mode 100644 index 0000000..658db74 --- /dev/null +++ b/greatest-common-divisor-bitcount/java/1/BinaryGCD.java @@ -0,0 +1,9 @@ +public class BinaryGCD { + public static int gcdBinary(final int x, final int y) { + return Integer.bitCount(gcd(x, y)); + } + + private static int gcd(final int x, final int y) { + return y == 0 ? Math.abs(x) : gcd(y, x % y); + } +} \ No newline at end of file diff --git a/greeting-my-friends/README.md b/greeting-my-friends/README.md new file mode 100644 index 0000000..fad4bb7 --- /dev/null +++ b/greeting-my-friends/README.md @@ -0,0 +1,35 @@ +# Greeting My Friends +[*View on Codewars*](https://www.codewars.com/kata/greeting-my-friends) + +We give you an Array of friend's list. + +Write a method called greetingForAllFriends, with this signature: + +```java +public String[] greetingForAllFriends(String... friends); +``` +```javascript +greetingForAllFriends(friends); +``` +```python +greeting_for_all_friends(friends) +``` +```ruby +greeting_for_all_friends(friends) +``` + +This method takes an array of friends name and return a greeting messages Array. + +Message sample: for the friend `"Bilal"` we get `"Hello, Bilal!"` + +### Rules: + + - If the argument is null, the method should return `null/nil/None` according to the given language (null for JS, None for Python and so on) + - If the argument is an empty array, the method should return `null/nil/None`, as stated above + - If the argument is a valide array of strings, the method should return a hello message for every array entry + +## Timeline +- Created: 2014-10-07 +- Published: 2014-10-07 +- Approved: null +- Completed: 2015-04-29 \ No newline at end of file diff --git a/greeting-my-friends/java/1/GreetingsMyFriends.java b/greeting-my-friends/java/1/GreetingsMyFriends.java new file mode 100644 index 0000000..485871b --- /dev/null +++ b/greeting-my-friends/java/1/GreetingsMyFriends.java @@ -0,0 +1,17 @@ +public class GreetingsMyFriends { + + public String[] greetingForAllFriends(String... friends) { + final int length; + if (friends == null || (length = friends.length) == 0) { + return null; + } + + String[] greetings = new String[length]; + for (int i = 0; i < length; i++) { + greetings[i] = String.format("Hello, %s!", friends[i]); + } + + return greetings; + } + +} \ No newline at end of file diff --git a/guess-the-number-1/README.md b/guess-the-number-1/README.md new file mode 100644 index 0000000..eefbf69 --- /dev/null +++ b/guess-the-number-1/README.md @@ -0,0 +1,31 @@ +# Guess the number! +[*View on Codewars*](https://www.codewars.com/kata/guess-the-number-1) + +The `Guesser` class is set up to generate a random number from 1-1000, and allows 10 guesses to get the number. + +Your task is to write a method '`get_number`' (`Guesser.prototype.getNumber()` in javascript) inside the `Guesser` class to identify a random number from 1-1000. + +You should use the method: +```ruby +guess number +``` +```javascript +this.guess(number) +``` +```java +guess(number) +``` +Which will return either: +``` +"Too high!" If the guess is too high. +"Too low!" If the guess is too low. +or "Correct!" If the guess is correct. +``` + +You can only call this method 10 times before an exception is raised. + +## Timeline +- Created: 2014-10-30 +- Published: 2014-10-30 +- Approved: 2014-11-24 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/guess-the-number-1/java/1/GuesserSolution.java b/guess-the-number-1/java/1/GuesserSolution.java new file mode 100644 index 0000000..b47add5 --- /dev/null +++ b/guess-the-number-1/java/1/GuesserSolution.java @@ -0,0 +1,46 @@ +public class GuesserSolution extends Guesser { + + public int getNumber() { + Range range = new Range(1, 1000); + while (!range.isSingleton()) { + int guess = range.getMedian(); + String response = guess(guess); + switch (response) { + case "Too high!": + range.to = guess - 1; + break; + case "Too low!": + range.from = guess + 1; + break; + case "Correct!": + return guess; + default: + throw new IllegalArgumentException(String.format("Unexpected response: %s", response)); + } + } + return range.from; + } + + private static class Range { + int from; + int to; + + Range(int from, int to) { + if (from > to) { + throw new IllegalArgumentException(String.format("from (%d) > to (%d)", from, to)); + } + + this.from = from; + this.to = to; + } + + boolean isSingleton() { + return from == to; + } + + int getMedian() { + return (from + to) / 2; + } + } + +} \ No newline at end of file diff --git a/guess-the-number-1/javascript/1/guess-the-number-1.js b/guess-the-number-1/javascript/1/guess-the-number-1.js new file mode 100644 index 0000000..84a8561 --- /dev/null +++ b/guess-the-number-1/javascript/1/guess-the-number-1.js @@ -0,0 +1,16 @@ +Guesser.prototype.getNumber = function() { + let min = 0, max = 1000, n; + while (true) { + n = Math.trunc((min + max) / 2); + switch (this.guess(n)) { + case "Too high!": + max = n - 1; + break; + case "Too low!": + min = n + 1; + break; + case "Correct!": + return n; + } + } +} \ No newline at end of file diff --git a/herding-cats/README.md b/herding-cats/README.md new file mode 100644 index 0000000..1a85f3b --- /dev/null +++ b/herding-cats/README.md @@ -0,0 +1,37 @@ +# Herding cats +[*View on Codewars*](https://www.codewars.com/kata/herding-cats) + +In this kata, you will be creating a Java ```Comparator``` to sort cats by their weight. + +The ```Cat``` class is preloaded for you., and its signature is given below: +```java +public class Cat implements Comparable +{ + public String name; + public double weight; + + public Cat(String name, double weight); + + @Override + public int compareTo(Cat c); + + @Override + public boolean equals(Object o); +} +``` +In the tests, an array of cats will be populated, and then sorted using ```Arrays.sort()```. +By default, this will sort the cats by their names. Your job is to complete the implementation of ```CatWeightComparator``` so that the cats are sorted by weight. + +You may assume that no two cats have the same name. + +For more information about ```Arrays```, take a look at http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html. + +For more information about ```Comparable```, see http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html. + +For more information about ```Comparator```, check out http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html. + +## Timeline +- Created: 2015-01-06 +- Published: 2015-01-06 +- Approved: 2017-09-29 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/herding-cats/java/1/CatWeightComparator.java b/herding-cats/java/1/CatWeightComparator.java new file mode 100644 index 0000000..843c6ae --- /dev/null +++ b/herding-cats/java/1/CatWeightComparator.java @@ -0,0 +1,10 @@ +import java.util.Comparator; + +public class CatWeightComparator implements Comparator +{ + @Override + public int compare(Cat cat1, Cat cat2) + { + return Double.compare(cat1.weight, cat2.weight); + } +} \ No newline at end of file diff --git a/hidden-cubic-numbers/README.md b/hidden-cubic-numbers/README.md new file mode 100644 index 0000000..02ecb0c --- /dev/null +++ b/hidden-cubic-numbers/README.md @@ -0,0 +1,39 @@ +# Hidden "Cubic" numbers +[*View on Codewars*](https://www.codewars.com/kata/hidden-cubic-numbers) + +We search positive integer numbers, with at **most** 3 digits, such as the sum of the cubes of their digits is the number itself; we will call them "cubic" numbers. +``` +153 is such a "cubic" number : 1^3 + 5^3 + 3^3 = 153 +``` +These "cubic" numbers of at most 3 digits are easy to find, even by hand, so they are "hidden" with other numbers and characters in a string. + +The task is to found, or not, the "cubic" numbers in the string and then to make the sum of these "cubic" numbers found in the string, if any, and to return a string such as: +``` +"number1 number2 (and so on if necessary) sumOfCubicNumbers Lucky" +``` + if "cubic" numbers number1, number2, ... were found. The numbers in the output are to be in the order in which they are encountered in the input string. + + If no cubic numbers are found return the string: +``` +"Unlucky". +``` + +Examples: +``` + s = "aqdf& 0 1 xyz 153 777.777" must return "0 1 153 154 Lucky" + + s = "QK29 45[&erui" must return "Unlucky". +``` + + **Note:** +In the string "001234" where 3 digits or more follow each other the fist packet to examine is "001" and the following is "234". If a packet of at most three digits has been taken, whether or not "cubic", it's over for that packet. + +When a continous string of digits exceeds 3, the string is split into groups of 3 from the left. The last grouping could have 3, 2 or 1 digits. +e.g "24172410" becomes 3 strings comprising "241", "724" and "10" +e.g "0785" becomes 2 strings comprising "078" and "5". + +## Timeline +- Created: 2015-03-13 +- Published: 2015-03-13 +- Approved: 2015-11-07 +- Completed: 2015-05-16 \ No newline at end of file diff --git a/hidden-cubic-numbers/java/1/Cubes.java b/hidden-cubic-numbers/java/1/Cubes.java new file mode 100644 index 0000000..a51781e --- /dev/null +++ b/hidden-cubic-numbers/java/1/Cubes.java @@ -0,0 +1,44 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class Cubes { + private static final int BASE = 10; + + public String isSumOfCubes(String s) { + List sumOfCubes = sumOfCubes(s); + if (sumOfCubes.isEmpty()) { + return "Unlucky"; + } + sumOfCubes.add(sumOfCubes.stream().mapToInt(Integer::intValue).sum()); + StringBuilder builder = new StringBuilder(); + for (int sumOfCube : sumOfCubes) { + builder.append(sumOfCube).append(' '); + } + return builder.append("Lucky").toString(); + } + + static List sumOfCubes(String s) { + List sumsOfCubes = new ArrayList<>(); + Matcher matcher = Pattern.compile("\\d{1,3}").matcher(s); + while (matcher.find()) { + int n = Integer.parseInt(matcher.group()); + if (isSumOfCubes(n)) { + sumsOfCubes.add(n); + } + } + return sumsOfCubes; + } + + static boolean isSumOfCubes(int n) { + return n == sumOfCubes(n); + } + + static int sumOfCubes(int n) { + return n < BASE ? cube(n) : cube(n % BASE) + sumOfCubes(n / BASE); + } + static int cube(int n) { + return n * n * n; + } +} \ No newline at end of file diff --git a/highest-and-lowest/README.md b/highest-and-lowest/README.md new file mode 100644 index 0000000..b8f07cc --- /dev/null +++ b/highest-and-lowest/README.md @@ -0,0 +1,63 @@ +# Highest and Lowest +[*View on Codewars*](https://www.codewars.com/kata/highest-and-lowest) + +In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. + +**Example:** +``` csharp +Kata.HighAndLow("1 2 3 4 5"); // return "5 1" +Kata.HighAndLow("1 2 -3 4 5"); // return "5 -3" +Kata.HighAndLow("1 9 3 4 -5"); // return "9 -5" +``` +```fsharp +highAndLow "1 2 3 4 5" // return "5 1" +highAndLow "1 2 -3 4 5" // return "5 -3" +highAndLow "1 9 3 4 -5" // return "9 -5" +``` +```javascript +highAndLow("1 2 3 4 5"); // return "5 1" +highAndLow("1 2 -3 4 5"); // return "5 -3" +highAndLow("1 9 3 4 -5"); // return "9 -5" +``` +```typescript +highAndLow("1 2 3 4 5"); // return "5 1" +highAndLow("1 2 -3 4 5"); // return "5 -3" +highAndLow("1 9 3 4 -5"); // return "9 -5" +``` +```coffeescript +highAndLow("1 2 3 4 5") # return "5 1" +highAndLow("1 2 -3 4 5") # return "5 -3" +highAndLow("1 9 3 4 -5") # return "9 -5" +``` +```python +high_and_low("1 2 3 4 5") # return "5 1" +high_and_low("1 2 -3 4 5") # return "5 -3" +high_and_low("1 9 3 4 -5") # return "9 -5" +``` +```ruby +high_and_low("1 2 3 4 5") # return "5 1" +high_and_low("1 2 -3 4 5") # return "5 -3" +high_and_low("1 9 3 4 -5") # return "9 -5" +``` +```java +HighAndLow("1 2 3 4 5") // return "5 1" +HighAndLow("1 2 -3 4 5") // return "5 -3" +HighAndLow("1 9 3 4 -5") // return "9 -5" +``` +```haskell +highAndLow "1 2 3 4 5") # return "5 1" +highAndLow "1 2 -3 4 5") # return "5 -3" +highAndLow "1 9 3 4 -5") # return "9 -5" +``` + +**Notes:** + +- All numbers are valid ```Int32```, no *need* to validate them. +- There will always be at least one number in the input string. +- Output string must be two numbers separated by a single space, and highest number is first. + +## Timeline +- Created: 2015-05-07 +- Published: 2015-05-07 +- Approved: 2015-05-20 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/highest-and-lowest/csharp/1/highest-and-lowest b/highest-and-lowest/csharp/1/highest-and-lowest new file mode 100644 index 0000000..98aa657 --- /dev/null +++ b/highest-and-lowest/csharp/1/highest-and-lowest @@ -0,0 +1,17 @@ +using System; + +public static class Kata +{ + public static string HighAndLow(string numbers) + { + var min = int.MaxValue; + var max = int.MinValue; + foreach (var number in numbers.Split(' ')) + { + var n = int.Parse(number); + min = Math.Min(min, n); + max = Math.Max(max, n); + } + return max + " " + min; + } +} \ No newline at end of file diff --git a/highest-and-lowest/java/1/Kata.java b/highest-and-lowest/java/1/Kata.java new file mode 100644 index 0000000..e2fa6b4 --- /dev/null +++ b/highest-and-lowest/java/1/Kata.java @@ -0,0 +1,12 @@ +public class Kata { + public static String HighAndLow(String numbers) { + int high = Integer.MIN_VALUE; + int low = Integer.MAX_VALUE; + for (String number : numbers.split(" ")) { + int n = Integer.parseInt(number); + high = Math.max(high, n); + low = Math.min(low, n); + } + return high + " " + low; + } +} \ No newline at end of file diff --git a/how-many-are-smaller-than-me/README.md b/how-many-are-smaller-than-me/README.md new file mode 100644 index 0000000..84832a8 --- /dev/null +++ b/how-many-are-smaller-than-me/README.md @@ -0,0 +1,48 @@ +# How many are smaller than me? +[*View on Codewars*](https://www.codewars.com/kata/how-many-are-smaller-than-me) + +Write +```javascript +function smaller(arr) +``` +```python +smaller(arr) +``` +```ruby +smaller(arr) +``` +```coffeescript +smaller(arr) +``` +that given an array ```arr```, you have to return the amount of numbers that are smaller than ```arr[i]``` to the right. + +For example: +```javascript +smaller([5, 4, 3, 2, 1]) === [4, 3, 2, 1, 0] +smaller([1, 2, 0]) === [1, 1, 0] +``` +```python +smaller([5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0] +smaller([1, 2, 0]) == [1, 1, 0] +``` +```ruby +smaller([5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0] +smaller([1, 2, 0]) == [1, 1, 0] +``` +```coffeescript +smaller([5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0] +smaller([1, 2, 0]) == [1, 1, 0] +``` +``` haskell +smaller [5,4,3,2,1] `shouldBe` [4,3,2,1,0] +smaller [1,2,3] `shouldBe` [0,0,0] +smaller [1, 2, 0] `shouldBe` [1, 1, 0] +``` +If you've completed this one and you feel like testing your performance tuning of this same kata, head over to the much tougher version How many are smaller than me II? + + +## Timeline +- Created: 2016-01-22 +- Published: 2016-01-22 +- Approved: 2016-01-22 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/how-many-are-smaller-than-me/javascript/1/how-many-are-smaller-than-me.js b/how-many-are-smaller-than-me/javascript/1/how-many-are-smaller-than-me.js new file mode 100644 index 0000000..532ee1a --- /dev/null +++ b/how-many-are-smaller-than-me/javascript/1/how-many-are-smaller-than-me.js @@ -0,0 +1,8 @@ +const smaller = nums => + nums.map((m, i) => + nums.reduce((s, n, j) => + j <= i || m <= n + ? s + : s + 1, 0 + ) + ) \ No newline at end of file diff --git a/html-generator/README.md b/html-generator/README.md new file mode 100644 index 0000000..863af59 --- /dev/null +++ b/html-generator/README.md @@ -0,0 +1,50 @@ +# HTML Generator +[*View on Codewars*](https://www.codewars.com/kata/html-generator) + +Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will generate the HTML for you. + +To organize your code, make of all your functions methods of a class called HTMLGen. Tag functions should be named after the tag of the element they create. Each function will take one argument, a string, which is the inner HTML of the element to be created. The functions will return the string for the appropriate HTML element. + +For example, + +In JavaScript: +```javascript +var g = new HTMLGen(); +var paragraph = g.p('Hello, World!'); +var block = g.div(paragraph); + +// The following are now true +paragraph === '

Hello, World!

' +block === '

Hello, World!

' +``` + +In Python: +```python +g = HTMLGen(); +paragraph = g.p('Hello, World!') +block = g.div(paragraph) + +# The following are now true +paragraph == '

Hello, World!

' +block == '

Hello, World!

' +``` + +Your HTMLGen class should have methods to create the following elements: + + * a + * b + * p + * body + * div + * span + * title + * comment + +Note: The comment method should wrap its argument with an HTML comment. It is the only method whose name does not match an HTML tag. So, ```g.comment('i am a comment')``` must produce ``````. + + +## Timeline +- Created: 2015-02-26 +- Published: 2015-02-28 +- Approved: 2015-04-28 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/html-generator/javascript/1/html-generator.js b/html-generator/javascript/1/html-generator.js new file mode 100644 index 0000000..ec022eb --- /dev/null +++ b/html-generator/javascript/1/html-generator.js @@ -0,0 +1,15 @@ +function HTMLGen() { + function tag(e, inner) { + return '<' + e + '>' + inner + ''; + } + + ['a', 'b', 'p', 'body', 'div', 'span', 'title'].forEach(function(e) { + this[e] = function(inner) { + return tag(e, inner); + }; + }, this); + + this.comment = function(inner) { + return ''; + } +} \ No newline at end of file diff --git a/human-readable-time/README.md b/human-readable-time/README.md new file mode 100644 index 0000000..d3cb30f --- /dev/null +++ b/human-readable-time/README.md @@ -0,0 +1,18 @@ +# Human Readable Time +[*View on Codewars*](https://www.codewars.com/kata/human-readable-time) + +Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (`HH:MM:SS`) + +* `HH` = hours, padded to 2 digits, range: 00 - 99 +* `MM` = minutes, padded to 2 digits, range: 00 - 59 +* `SS` = seconds, padded to 2 digits, range: 00 - 59 + +The maximum time never exceeds 359999 (`99:59:59`) + +You can find some examples in the test fixtures. + +## Timeline +- Created: 2013-10-23 +- Published: 2013-10-23 +- Approved: null +- Completed: 2015-05-02 \ No newline at end of file diff --git a/human-readable-time/java/1/HumanReadableTime.java b/human-readable-time/java/1/HumanReadableTime.java new file mode 100644 index 0000000..2ba132b --- /dev/null +++ b/human-readable-time/java/1/HumanReadableTime.java @@ -0,0 +1,12 @@ +public class HumanReadableTime { + public static int MIN_TO_SECS = 60; + public static int HOUR_TO_MINS = 60; + + public static String makeReadable(int totalSeconds) { + int noOfSeconds = totalSeconds % MIN_TO_SECS; + int totalMinutes = totalSeconds / MIN_TO_SECS; + int noOfMinutes = totalMinutes % HOUR_TO_MINS; + int noOfHours = totalMinutes / HOUR_TO_MINS; + return String.format("%02d:%02d:%02d", noOfHours, noOfMinutes, noOfSeconds); + } +} \ No newline at end of file diff --git a/human-readable-time/javascript/1/human-readable-time.js b/human-readable-time/javascript/1/human-readable-time.js new file mode 100644 index 0000000..a9e8d7e --- /dev/null +++ b/human-readable-time/javascript/1/human-readable-time.js @@ -0,0 +1,11 @@ +const f = 60; +const d = (a, b) => Math.trunc(a / b); +const p = n => n < 10 ? '0' + n : '' + n; + +function humanReadable(s) { + let m = d(s, f); + let h = d(m, f); + let mm = m - f * h; + let ss = s - f * m; + return `${p(h)}:${p(mm)}:${p(ss)}`; +} \ No newline at end of file diff --git a/int32-to-ipv4/README.md b/int32-to-ipv4/README.md new file mode 100644 index 0000000..22e0f39 --- /dev/null +++ b/int32-to-ipv4/README.md @@ -0,0 +1,37 @@ +# int32 to IPv4 +[*View on Codewars*](https://www.codewars.com/kata/int32-to-ipv4) + +Take the following IPv4 address: 128.32.10.1 + +This address has 4 octets where each octet is a single byte (or 8 bits). + +* 1st octet 128 has the binary representation: 10000000 +* 2nd octet 32 has the binary representation: 00100000 +* 3rd octet 10 has the binary representation: 00001010 +* 4th octet 1 has the binary representation: 00000001 + +So 128.32.10.1 == 10000000.00100000.00001010.00000001 + +Because the above IP address has 32 bits, we can represent it as the unsigned 32 bit number: 2149583361 + +Write a function `int32_to_ip(int32)` (**JS**: `int32ToIp(int32)`, **Haskell**: `int32ToIP`, **C#**: `UInt32ToIP`) that takes an unsigned 32 bit number and returns a string representation of its IPv4 address. + +```ruby + int32_to_ip(2149583361) => "128.32.10.1" +``` +```javascript + int32ToIp(2149583361) => "128.32.10.1" +``` +```haskell + int32ToIP 2149583361 => "128.32.10.1" +``` +```csharp + Kata.UInt32ToIP(2149583361) => "128.32.10.1" +``` + + +## Timeline +- Created: 2014-01-29 +- Published: 2014-01-30 +- Approved: 2014-04-30 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/int32-to-ipv4/javascript/1/int32-to-ipv4.js b/int32-to-ipv4/javascript/1/int32-to-ipv4.js new file mode 100644 index 0000000..92fcf36 --- /dev/null +++ b/int32-to-ipv4/javascript/1/int32-to-ipv4.js @@ -0,0 +1,6 @@ +function int32ToIp(int32) { + return (int32 >>> 24 & 0xFF) + '.' + + (int32 >>> 16 & 0xFF) + '.' + + (int32 >>> 8 & 0xFF) + '.' + + (int32 & 0xFF); +} \ No newline at end of file diff --git a/is-integer-array/README.md b/is-integer-array/README.md new file mode 100644 index 0000000..e3bfc0d --- /dev/null +++ b/is-integer-array/README.md @@ -0,0 +1,19 @@ +# Is Integer Array ? +[*View on Codewars*](https://www.codewars.com/kata/is-integer-array) + +Write a function *isIntArray* with the below signature. +```javascript +function isIntArray(arr) { + return true; +} +``` + + * returns *true* if every element in an array is an integer.
+ * returns *true* if array is empty. + * returns *false* for every other input. + +## Timeline +- Created: 2013-12-05 +- Published: 2013-12-06 +- Approved: 2014-01-10 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/is-integer-array/javascript/1/is-integer-array.js b/is-integer-array/javascript/1/is-integer-array.js new file mode 100644 index 0000000..24cdd77 --- /dev/null +++ b/is-integer-array/javascript/1/is-integer-array.js @@ -0,0 +1,12 @@ +function isIntArray(a) { + if (!Array.isArray(a)) { + return false; + } + for (var i = 0, l = a.length; i < l; i++) { + var n = a[i]; + if (n !== ~~n) { + return false; + } + } + return true; +} \ No newline at end of file diff --git a/isograms/README.md b/isograms/README.md new file mode 100644 index 0000000..db6fee7 --- /dev/null +++ b/isograms/README.md @@ -0,0 +1,32 @@ +# Isograms +[*View on Codewars*](https://www.codewars.com/kata/isograms) + +An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. + +```haskell +isIsogram "Dermatoglyphics" == true +isIsogram "moose" == false +isIsogram "aba" == false +``` +```javascript +isIsogram( "Dermatoglyphics" ) == true +isIsogram( "aba" ) == false +isIsogram( "moOse" ) == false // -- ignore letter case +``` +```python +is_isogram("Dermatoglyphics" ) == true +is_isogram("aba" ) == false +is_isogram("moOse" ) == false # -- ignore letter case +``` +```ruby +is_isogram("Dermatoglyphics" ) == true +is_isogram("aba" ) == false +is_isogram("moOse" ) == false # -- ignore letter case +``` + + +## Timeline +- Created: 2015-01-17 +- Published: 2015-01-17 +- Approved: 2015-04-05 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/isograms/javascript/1/isograms.js b/isograms/javascript/1/isograms.js new file mode 100644 index 0000000..bcebfd3 --- /dev/null +++ b/isograms/javascript/1/isograms.js @@ -0,0 +1,4 @@ +function isIsogram(str){ + //... + return new Set(str.toLowerCase()).size === str.length +} \ No newline at end of file diff --git a/jaden-casing-strings/README.md b/jaden-casing-strings/README.md new file mode 100644 index 0000000..708cd97 --- /dev/null +++ b/jaden-casing-strings/README.md @@ -0,0 +1,20 @@ +# Jaden Casing Strings +[*View on Codewars*](https://www.codewars.com/kata/jaden-casing-strings) + +Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for [some of his philosophy that he delivers via Twitter](https://twitter.com/officialjaden). When writing on Twitter, he is known for almost always capitalizing every word. + +Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them. + +Example: + + Not Jaden-Cased: "How can mirrors be real if our eyes aren't real" + Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real" + +Note that the **Java version** expects a return value of null for an empty string or +null. + +## Timeline +- Created: 2014-06-05 +- Published: 2014-06-05 +- Approved: 2014-08-18 +- Completed: 2015-05-07 \ No newline at end of file diff --git a/jaden-casing-strings/java/1/JadenCase.java b/jaden-casing-strings/java/1/JadenCase.java new file mode 100644 index 0000000..7789bcd --- /dev/null +++ b/jaden-casing-strings/java/1/JadenCase.java @@ -0,0 +1,23 @@ +public class JadenCase { + public String toJadenCase(final String phrase) { + if (phrase == null || phrase.isEmpty()) { + return null; + } + final int length = phrase.length(); + final StringBuilder jadenBuilder = new StringBuilder(length); + boolean newWord = true; + for (int i = 0; i < length; i++) { + char c = phrase.charAt(i); + if (Character.isWhitespace(c)) { + newWord = true; + } else if (newWord) { + c = Character.toUpperCase(c); + newWord = false; + } else { + newWord = false; + } + jadenBuilder.append(c); + } + return jadenBuilder.toString(); + } +} \ No newline at end of file diff --git a/java-functional-programming-part-1-the-beginning/README.md b/java-functional-programming-part-1-the-beginning/README.md new file mode 100644 index 0000000..2917d19 --- /dev/null +++ b/java-functional-programming-part-1-the-beginning/README.md @@ -0,0 +1,45 @@ +# Java Functional Programming (Part 1: The Beginning) +[*View on Codewars*](https://www.codewars.com/kata/java-functional-programming-part-1-the-beginning) + +With the release of Java 8, Java has finally added support for "lambda functions", that is, variables that contain a function which can operate on data just as class methods can (well, not _just_ as class methods can...) + +Let's learn about lambdas. This is part 1 in a series. + +* Part 2: http://www.codewars.com/kata/java-functional-programming-part-2-multiline-functions +* Part 3: http://www.codewars.com/kata/java-functional-programming-part-3-closured-for-business +* Part 4: http://www.codewars.com/kata/java-functional-programming-part-4-row-row-row-your-boat-gently-down-the-dot-dot-dot + +Coming from most scripting languages (e.g., Javascript, Python, Ruby), the concept of functions that can be passed as variables should not be anything new. The syntax in Java should even look familiar: + +```java +Function f = p -> p.toString(); +String myString = f.apply(myObject); //Stores whatever the toString() of myObject is in myString +``` + +The above is a simple mapper function: given an input of type MyObject, return a specific result of type String, in this case the toString of the object. They can, of course, become much more complicated. + +A full listing of the default function types can be found at http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html + +Given this POJO: + +```java +public class Student { + private final String firstName; + private final String lastName; + public final String studentNumber; + public String getFullName() { + return firstName + " " + lastName; + } + public String getCommaName() { + return lastName + ", " + firstName; + } +} +``` + +Write a Function (with the appropriate types) that returns true if a given student is "John Smith" with a student number of "js123" (otherwise return false). + +## Timeline +- Created: 2015-01-02 +- Published: 2015-01-02 +- Approved: 2015-11-08 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/java-functional-programming-part-1-the-beginning/java/1/FunctionalProgramming.java b/java-functional-programming-part-1-the-beginning/java/1/FunctionalProgramming.java new file mode 100644 index 0000000..580d72b --- /dev/null +++ b/java-functional-programming-part-1-the-beginning/java/1/FunctionalProgramming.java @@ -0,0 +1,6 @@ +import java.util.function.Function; + +public class FunctionalProgramming { + public static Function f = s -> "John Smith".equals(s.getFullName()) && + "js123".equals(s.studentNumber); +} \ No newline at end of file diff --git a/java-functional-programming-part-2-multiline-functions/README.md b/java-functional-programming-part-2-multiline-functions/README.md new file mode 100644 index 0000000..57afb06 --- /dev/null +++ b/java-functional-programming-part-2-multiline-functions/README.md @@ -0,0 +1,62 @@ +# Java Functional Programming (Part 2: Multiline Functions) +[*View on Codewars*](https://www.codewars.com/kata/java-functional-programming-part-2-multiline-functions) + +With the release of Java 8, Java has finally added support for "lambda functions", that is, variables that contain a function which can operate on data just as class methods can (well, not _just_ as class methods can...) + +Let's learn about lambdas. + +This is part 2 of a 4 part series; the other katas are: + +* Part 1: http://www.codewars.com/kata/java-functional-programming-part-1-the-beginning/java +* Part 3: http://www.codewars.com/kata/java-functional-programming-part-3-closured-for-business +* Part 4: http://www.codewars.com/kata/java-functional-programming-part-4-row-row-row-your-boat-gently-down-the-dot-dot-dot + +Last time, we did something similar to this: + +```java +Function f = p -> p.toString(); +String myString = f.apply(myObject); //Stores whatever the toString() of myObject is in myString +``` + +But what if we need more than one line in our function for the calculations? The syntax to do so is to enclose the function's commands in curly brackets and include a return statement: + +```java +Function f = p -> {StringBuffer out = new StringBuffer(); + out.append(p.getName()); + out.append(MyObject.getStaticName()); + out.append("Constant message"); + return out.toString(); + }; +``` + +Given this POJO: + +```java +public class Triangle { + public final int height; + public final int base; + private double area; + public void setArea(double a) { + area = a; + } + public double getArea() { + return area; + } +} +``` + +Write a function that sets the area of the given Triangle and returns the area as a `double`. Do not use the function type Function; there is a function type for converting an arbitrary class into a `double`, use that. + +The formula for triangle area is: 1/2 \* base \* height + +Assume valid input (base and height are both greater than 0). + +A full listing of the default function types can be found at http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html + +(Aside: you may have noticed, the function type we should have used in Part 1 is Predicate, even though we used Function.) + +## Timeline +- Created: 2015-01-02 +- Published: 2015-01-02 +- Approved: 2016-01-15 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/java-functional-programming-part-2-multiline-functions/java/1/FunctionalProgramming.java b/java-functional-programming-part-2-multiline-functions/java/1/FunctionalProgramming.java new file mode 100644 index 0000000..6d4c65e --- /dev/null +++ b/java-functional-programming-part-2-multiline-functions/java/1/FunctionalProgramming.java @@ -0,0 +1,8 @@ +import java.util.function.ToDoubleFunction; + +public class FunctionalProgramming { + public static ToDoubleFunction f = t -> { + t.setArea(.5 * t.base * t.height); + return t.getArea(); + }; +} \ No newline at end of file diff --git a/java-functional-programming-part-3-closured-for-business/README.md b/java-functional-programming-part-3-closured-for-business/README.md new file mode 100644 index 0000000..1519735 --- /dev/null +++ b/java-functional-programming-part-3-closured-for-business/README.md @@ -0,0 +1,63 @@ +# Java Functional Programming (Part 3: Closured for Business) +[*View on Codewars*](https://www.codewars.com/kata/java-functional-programming-part-3-closured-for-business) + +With the release of Java 8, Java has finally added support for "lambda functions", that is, variables that contain a function which can operate on data just as class methods can (well, not _just_ as class methods can...) + +Let's learn about lambdas. This is part 3 in a series of 4. + +* Part 1: http://www.codewars.com/kata/java-functional-programming-part-1-the-beginning/java +* Part 2: http://www.codewars.com/kata/java-functional-programming-part-2-multiline-functions +* Part 4: http://www.codewars.com/kata/java-functional-programming-part-4-row-row-row-your-boat-gently-down-the-dot-dot-dot + +We've now got a handle on Java lambda functions (even multi-line ones), but do Java lambdas have all the features of scripting functions? Like closures? + +Yes. And, like in every language that supports them, closures give people headaches. Let's learn about closures! + +## What is a closure? + +In programming, a closure is a function that retains the context in which it was created. + +_What._ + +Okay, say we have these statements: + +```java +int foo = 5; +Function f = s -> s.length + foo; +f.apply("somestring"); //Should be 15 +``` + +Given an input of "somestring", f should return 15. But what happens when f leaves this context? + +```java +public void someMethod() { + int foo = 5; + Function f = s -> s.length + foo; + f.apply("somestring"); //Should be 15 + sendMethod(f); +} +public void sendMethod(Function f) { + f.apply("otherstring"); //Should return 16 +} +``` + +Does f still know foo is 5 when f is in sendMethod? foo is a local variable to someMethod, after all. Yes, f knows 5 is 5; that's what closures do. + +Write a factory that creates adder functions. Depending on what is passed to the create method, the function will, when called, add that amount to another amount given to the function. In other words: + +```java +f = AdderFactory.create(1); //Adds 1 to everything +f.applyAsInt(4) == 5; +f.applyAsInt(10) == 11; +f.applyAsInt(-5) == -4; +``` + +A full listing of the default function types can be found at http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html + +As in Part 2, don't use the default Function class, but the most appropriate class: the one that takes an int and returns an int; you shouldn't need to use any generics. + +## Timeline +- Created: 2015-01-02 +- Published: 2015-01-02 +- Approved: 2016-01-15 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/java-functional-programming-part-3-closured-for-business/java/1/AdderFactory.java b/java-functional-programming-part-3-closured-for-business/java/1/AdderFactory.java new file mode 100644 index 0000000..67814ab --- /dev/null +++ b/java-functional-programming-part-3-closured-for-business/java/1/AdderFactory.java @@ -0,0 +1,7 @@ +import java.util.function.IntUnaryOperator; + +public class AdderFactory { + public static IntUnaryOperator create(int j) { + return i -> i + j; + } +} \ No newline at end of file diff --git a/jennys-secret-message/README.md b/jennys-secret-message/README.md new file mode 100644 index 0000000..686662e --- /dev/null +++ b/jennys-secret-message/README.md @@ -0,0 +1,12 @@ +# Jenny's secret message +[*View on Codewars*](https://www.codewars.com/kata/jennys-secret-message) + +Jenny has written a function that returns a greeting for a user. However, she's in love with Johnny, and would like to greet him slightly different. She added a special case to her function, but she made a mistake. + +Can you help her? + +## Timeline +- Created: 2015-04-06 +- Published: 2015-04-06 +- Approved: 2015-04-11 +- Completed: 2015-05-08 \ No newline at end of file diff --git a/jennys-secret-message/java/1/Greeter.java b/jennys-secret-message/java/1/Greeter.java new file mode 100644 index 0000000..b0aa81f --- /dev/null +++ b/jennys-secret-message/java/1/Greeter.java @@ -0,0 +1,5 @@ +public class Greeter { + public static String greet(String name) { + return "Johnny".equals(name) ? "Hello, my love!" : String.format("Hello, %s!", name); + } +} \ No newline at end of file diff --git a/kata-example-twist/README.md b/kata-example-twist/README.md new file mode 100644 index 0000000..0ba62ba --- /dev/null +++ b/kata-example-twist/README.md @@ -0,0 +1,42 @@ +# Kata Example Twist +[*View on Codewars*](https://www.codewars.com/kata/kata-example-twist) + +This is an easy twist to the example kata (provided by Codewars when learning how to create your own kata). + +Add the value "codewars" to the array `websites`/`Websites` 1,000 times. +```javascript +var websites = [] +``` +```coffeescript +websites = [] +``` +```python +websites = [] +``` +```java +String[] websites = {}; +return websites; +``` +```clojure +(defn websites []) +``` +```elixir +def websites do + [] +end +``` +```csharp +public static class Kata +{ + public static string[] Websites; +} +``` +```haskell +websites = [] +``` + +## Timeline +- Created: 2013-10-14 +- Published: 2013-10-14 +- Approved: null +- Completed: 2015-05-08 \ No newline at end of file diff --git a/kata-example-twist/java/1/KataExampleTwist.java b/kata-example-twist/java/1/KataExampleTwist.java new file mode 100644 index 0000000..5d0117a --- /dev/null +++ b/kata-example-twist/java/1/KataExampleTwist.java @@ -0,0 +1,9 @@ +public class KataExampleTwist +{ + public static String[] kataExampleTwist() + { + String[] websites = new String[1000]; + java.util.Arrays.fill(websites, "codewars"); + return websites; + } +} \ No newline at end of file diff --git a/kata-example-twist/java/2/KataExampleTwist.java b/kata-example-twist/java/2/KataExampleTwist.java new file mode 100644 index 0000000..33107cb --- /dev/null +++ b/kata-example-twist/java/2/KataExampleTwist.java @@ -0,0 +1,7 @@ +public class KataExampleTwist { + public static String[] kataExampleTwist() { + return java.util.stream.Stream.generate(() -> "codewars") + .limit(1000) + .toArray(String[]::new); + } +} \ No newline at end of file diff --git a/kata-example-twist/java/3/KataExampleTwist.java b/kata-example-twist/java/3/KataExampleTwist.java new file mode 100644 index 0000000..9dd6360 --- /dev/null +++ b/kata-example-twist/java/3/KataExampleTwist.java @@ -0,0 +1,5 @@ +public class KataExampleTwist { + public static String[] kataExampleTwist() { + return new String[]{"codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars","codewars"}; + } +} \ No newline at end of file diff --git a/l3375p34k/README.md b/l3375p34k/README.md new file mode 100644 index 0000000..213da9e --- /dev/null +++ b/l3375p34k/README.md @@ -0,0 +1,34 @@ +# L3375p34k +[*View on Codewars*](https://www.codewars.com/kata/l3375p34k) + +General Objective +================ + +The objective of this Kata is to provide some way to encode a string into its leetspeak version.
+ +Specific Instructions +-------------------- + +1) The code must contain a Leetspeak class inherited from an Encoder abstract class and containing an encode(String) method returning itself the encoded String.

+2) The encode method should return an empty String if a null parameter is passed.

+3) If any uppercase character is given, it should be compared also with the dictionary, 'a' gives '4' but 'A' gives also '4'.

+4) If any character outside the dictionary is given, it should be output as is.
+ +Dictionary to reproduce +---------------------- + +The following dictionary has to be used :
+``` +a -> 4 +e -> 3 +l -> 1 +m -> /^^\ +o -> 0 +u -> (_) +``` + +## Timeline +- Created: 2014-10-13 +- Published: 2014-10-13 +- Approved: 2017-03-07 +- Completed: 2015-05-05 \ No newline at end of file diff --git a/l3375p34k/java/1/Leetspeak.java b/l3375p34k/java/1/Leetspeak.java new file mode 100644 index 0000000..b472f4b --- /dev/null +++ b/l3375p34k/java/1/Leetspeak.java @@ -0,0 +1,25 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +public class Leetspeak implements Encoder { + static final Map dictionary = new HashMap<>(); + + static { + dictionary.put('a', "4"); + dictionary.put('e', "3"); + dictionary.put('l', "1"); + dictionary.put('m', "/^^\\"); + dictionary.put('o', "0"); + dictionary.put('u', "(_)"); + } + + @Override + public String encode(String source) { + return source == null ? "" : source.chars().mapToObj(c -> dictionary.getOrDefault(Character.toLowerCase((char) c), String.valueOf((char) c))).collect(Collectors.joining()); + } +} + +interface Encoder { + String encode(String source); +} \ No newline at end of file diff --git a/largest-difference-in-increasing-indexes/README.md b/largest-difference-in-increasing-indexes/README.md new file mode 100644 index 0000000..39e04a5 --- /dev/null +++ b/largest-difference-in-increasing-indexes/README.md @@ -0,0 +1,42 @@ +# Largest Difference in Increasing Indexes +[*View on Codewars*](https://www.codewars.com/kata/largest-difference-in-increasing-indexes) + +*Summary*: Write a function which takes an array `data` of numbers and returns the largest difference in indexes `j - i` such that `data[i] <= data[j]` + +-------------------- +*Long Description*: + + The `largestDifference` takes an array of numbers. That array is not sorted. Do not sort it or change the order of the elements in any way, or their values. + +Consider all of the pairs of numbers in the array where the first one is less than or equal to the second one. + +From these, find a pair where their positions in the array are farthest apart. + +Return the difference between the indexes of the two array elements in this pair. + +-------------------- + +*Example*: + +```coffeescript +largestDifference([1,2,3]) # returns 2, because here j = 2 and i = 0 and 2 - 0 = 2 +``` + +```javascript +largestDifference([1,2,3]) ; // returns 2, because here j = 2 and i = 0 and 2 - 0 = 2 +``` + +```clojure +(largestDifference [1 2 3]) ; returns 2, because here j = 2 and i = 0 and 2 - 0 = 2 +``` + +```java +LargestDifference.largestDifference(new int[]{1,2,3}); //returns 2, +//because here j = 2 and i = 0 and 2 - 0 = 2 +``` + +## Timeline +- Created: 2013-10-05 +- Published: 2013-10-05 +- Approved: 2014-02-17 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/largest-difference-in-increasing-indexes/javascript/1/largest-difference-in-increasing-indexes.js b/largest-difference-in-increasing-indexes/javascript/1/largest-difference-in-increasing-indexes.js new file mode 100644 index 0000000..a94b7ba --- /dev/null +++ b/largest-difference-in-increasing-indexes/javascript/1/largest-difference-in-increasing-indexes.js @@ -0,0 +1,8 @@ +var largestDifference = function(data) { + var d = 0; + for (var i = 0, l = data.length - 1; l - i > d; i++) + for (var j = l; j - i > d; j--) + if (data[i] <= data[j]) + d = j - i; + return d; +}; \ No newline at end of file diff --git a/make-a-function-that-does-arithmetic/README.md b/make-a-function-that-does-arithmetic/README.md new file mode 100644 index 0000000..b5bf471 --- /dev/null +++ b/make-a-function-that-does-arithmetic/README.md @@ -0,0 +1,45 @@ +# Make a function that does arithmetic! +[*View on Codewars*](https://www.codewars.com/kata/make-a-function-that-does-arithmetic) + +Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them. + + +```a``` and ```b``` will both be positive integers, and ```a``` will always be the first number in the operation, and ```b``` always the second. + +The four operators are "add", "subtract", "divide", "multiply". + + +A few examples: + + +``` javascript +arithmetic(5, 2, "add") => returns 7 +arithmetic(5, 2, "subtract") => returns 3 +arithmetic(5, 2, "multiply") => returns 10 +arithmetic(5, 2, "divide") => returns 2.5 +``` +```haskell +-- In Haskell: + +-- 1. The operation is defined as +data Operation = Add | Divide | Multiply | Subtract deriving (Eq, Show, Enum, Bounded) + +-- 2. The arithmetic function as +arithmetic :: Double -> Double -> Operation -> Double +arithmetic :: Fractional a => a -> a -> Operation -> a +``` +```csharp +Kata.Arithmetic(5, 2, "add") => 7 +Kata.Arithmetic(5, 2, "subtract") => 3 +Kata.Arithmetic(5, 2, "multiply") => 10 +Kata.Arithmetic(5, 2, "divide") => 2.5 +``` + +Try to do it without using if statements! + + +## Timeline +- Created: 2016-11-30 +- Published: 2016-11-30 +- Approved: 2016-11-30 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/make-a-function-that-does-arithmetic/javascript/1/make-a-function-that-does-arithmetic.js b/make-a-function-that-does-arithmetic/javascript/1/make-a-function-that-does-arithmetic.js new file mode 100644 index 0000000..92d04b3 --- /dev/null +++ b/make-a-function-that-does-arithmetic/javascript/1/make-a-function-that-does-arithmetic.js @@ -0,0 +1,9 @@ +function arithmetic(a, b, operator){ + const operators = { + 'add': (a, b) => a + b, + 'subtract': (a, b) => a - b, + 'multiply': (a, b) => a * b, + 'divide': (a, b) => a / b + } + return operators[operator](a, b); +} \ No newline at end of file diff --git a/make-them-bark/README.md b/make-them-bark/README.md new file mode 100644 index 0000000..8ebbc14 --- /dev/null +++ b/make-them-bark/README.md @@ -0,0 +1,62 @@ +# Make them bark! +[*View on Codewars*](https://www.codewars.com/kata/make-them-bark) + +#Make them bark + +You have been hired by a dogbreeder to write a program to keep record of his dogs. + +You've already made a constructor `Dog`, so no one has to hardcode every puppy. + +The work seems to be done. It's high time to collect the payment. + +..hold on! The dogbreeder says he wont pay you, until he can make every dog object `.bark()`. Even the ones already done with your constructor. +"Every dog barks" he says. He also refuses to rewrite them, lazy as he is. + +You can't even count how much objects that bastard client of yours already made. He has a lot of dogs, and none of them can `.bark()`. + +Can you solve this problem, or will you let this client outsmart you for good? + +### Practical info: + + - The `.bark()` method of a dog should return the string `'Woof!'`. + + - The contructor you made (it is preloaded) looks like this: + +```javascript +function Dog(name, breed, sex, age){ + this.name = name; + this.breed = breed; + this.sex = sex; + this.age = age; +} +``` +```coffeescript +class Dog + constructor: (@name, @breed, @sex, @age) -> +``` +```python +class Dog(object): + def __init__(self, name, breed, sex, age): + self.name = name + self.breed = breed + self.sex = sex + self.age = age +``` +```ruby +class Dog + def initialize(name, breed, sex, age) + @name = name + @breed = breed + @sex = sex + @age = age + end +end +``` + +>**Hint:** A friend of yours just told you about how javascript handles classes diferently from other programming languages. He couldn't stop ranting about *"prototypes"*, or something like that. Maybe that could help you... + +## Timeline +- Created: 2015-04-20 +- Published: 2015-04-20 +- Approved: 2015-05-08 +- Completed: 2015-05-23 \ No newline at end of file diff --git a/make-them-bark/javascript/1/make-them-bark.js b/make-them-bark/javascript/1/make-them-bark.js new file mode 100644 index 0000000..ed55330 --- /dev/null +++ b/make-them-bark/javascript/1/make-them-bark.js @@ -0,0 +1 @@ +Dog.prototype.bark = function() { return 'Woof!' } \ No newline at end of file diff --git a/manipulate-url-parameters/README.md b/manipulate-url-parameters/README.md new file mode 100644 index 0000000..8cbf1dd --- /dev/null +++ b/manipulate-url-parameters/README.md @@ -0,0 +1,29 @@ +# Manipulate URL Parameters +[*View on Codewars*](https://www.codewars.com/kata/manipulate-url-parameters) + +You need to write a function ( `addOrChangeUrlParameter(url, keyValueParameter)` ) that can manipulate URL parameters. + +It should be able to +* **add** a parameter to an existing URL, + +but also to +* **change** a parameter if it already exists. + +### Example: +```javascript + +addOrChangeUrlParameter("www.example.com", "key=value") +// -> 'www.example.com?key=value' (adds a parameter). + +addOrChangeUrlParameter("www.example.com?key=value", "key2=value2" ) +// -> 'www.example.com?key=value&key2=value2' (adds another parameter). + +addOrChangeUrlParameter("www.example.com?key=oldValue`", "key=newValue" ) +// ->'www.example.com?key=newValue' (changes the parameter). +``` + +## Timeline +- Created: 2013-09-25 +- Published: 2013-09-26 +- Approved: 2017-08-10 +- Completed: 2015-05-23 \ No newline at end of file diff --git a/math-issues/README.md b/math-issues/README.md new file mode 100644 index 0000000..49e063e --- /dev/null +++ b/math-issues/README.md @@ -0,0 +1,16 @@ +# Math Issues +[*View on Codewars*](https://www.codewars.com/kata/math-issues) + +Oh no, our Math object was "accidently" reset. Can you re-implement some of those functions? We can assure, that only non-negative numbers are passed as arguments. So you don't have to consider things like `undefined`, `null`, `NaN`, negative numbers, strings and so on. + +Here is a list of functions, we need: + +* Math.round() +* Math.ceil() +* Math.floor() + +## Timeline +- Created: 2013-10-23 +- Published: 2013-10-23 +- Approved: null +- Completed: 2015-05-25 \ No newline at end of file diff --git a/math-issues/javascript/1/math-issues.js b/math-issues/javascript/1/math-issues.js new file mode 100644 index 0000000..1b15d36 --- /dev/null +++ b/math-issues/javascript/1/math-issues.js @@ -0,0 +1,12 @@ +Math.round = function(number) { + return Math.floor(number + .5); +}; + +Math.ceil = function(number) { + var floor = Math.floor(number); + return floor === number ? number : floor + 1; +}; + +Math.floor = function(number) { + return ~~number; +}; \ No newline at end of file diff --git a/maximum-subarray-sum/README.md b/maximum-subarray-sum/README.md new file mode 100644 index 0000000..a2d2ad3 --- /dev/null +++ b/maximum-subarray-sum/README.md @@ -0,0 +1,35 @@ +# Maximum subarray sum +[*View on Codewars*](https://www.codewars.com/kata/maximum-subarray-sum) + +The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: + +```haskell +maxSequence [-2, 1, -3, 4, -1, 2, 1, -5, 4] +-- should be 6: [4, -1, 2, 1] +``` +```javascript +maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) +// should be 6: [4, -1, 2, 1] +``` +```python +maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) +# should be 6: [4, -1, 2, 1] +``` +```clojure +(max-sequence [-2, 1, -3, 4, -1, 2, 1, -5, 4]) +;; should be 6: [4, -1, 2, 1] +``` +```java +Max.sequence(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}); +// should be 6: {4, -1, 2, 1} +``` + +Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead. + +Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray. + +## Timeline +- Created: 2014-10-30 +- Published: 2014-10-30 +- Approved: 2014-12-08 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/maximum-subarray-sum/java/1/Max.java b/maximum-subarray-sum/java/1/Max.java new file mode 100644 index 0000000..a42cff5 --- /dev/null +++ b/maximum-subarray-sum/java/1/Max.java @@ -0,0 +1,11 @@ +public class Max { + public static int sequence(final int[] seq) { + int max = 0; + for (int i = 0, c = 0; i < seq.length; i++) { + c += seq[i]; + c = Math.max(c, 0); + max = Math.max(max, c); + } + return max; + } +} \ No newline at end of file diff --git a/milk-and-cookies-for-santa/README.md b/milk-and-cookies-for-santa/README.md new file mode 100644 index 0000000..45c485c --- /dev/null +++ b/milk-and-cookies-for-santa/README.md @@ -0,0 +1,29 @@ +# Milk and Cookies for Santa +[*View on Codewars*](https://www.codewars.com/kata/milk-and-cookies-for-santa) + +### Happy Holidays fellow Code Warriors! +It's almost Christmas Eve, so we need to prepare some milk and cookies for Santa! Wait..when exactly did we need to do that? + +### Time for Milk and Cookies +Write a function `timeForMilkAndCookies` (`time_for_milk_and_cookies` in Ruby) that accepts a Date object, and returns true if it's Christmas Eve (December 24th), false otherwise. Keep in mind Javascript's Date month is 0 based, while Ruby's Date month isn't. + +### Examples +Javascript/CoffeeScript: +```javascript +timeForMilkAndCookies( new Date( 2013, 11, 24 ) ) // December 24, 2013 => returns true +timeForMilkAndCookies( new Date( 2013, 0, 23 ) ) // January 23, 2013 => returns false +timeForMilkAndCookies( new Date( 3000, 11, 24 ) ) // December 24, 3000 => returns true +``` + +Ruby: +```ruby +time_for_milk_and_cookies( Date.new( 2013, 12, 24 ) ) # December 24, 2013 => returns true +time_for_milk_and_cookies( Date.new( 2013, 1, 23 ) ) # January 23, 2013 => returns false +time_for_milk_and_cookies( Date.new( 3000, 12, 24 ) ) # December 24, 3000 => returns true +``` + +## Timeline +- Created: 2013-12-16 +- Published: 2013-12-17 +- Approved: 2013-12-17 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/milk-and-cookies-for-santa/javascript/1/milk-and-cookies-for-santa.js b/milk-and-cookies-for-santa/javascript/1/milk-and-cookies-for-santa.js new file mode 100644 index 0000000..e7b0384 --- /dev/null +++ b/milk-and-cookies-for-santa/javascript/1/milk-and-cookies-for-santa.js @@ -0,0 +1,3 @@ +function timeForMilkAndCookies(date){ + return date.getDate() == 24 && date.getMonth() == 11; +} \ No newline at end of file diff --git a/mod4-regex/README.md b/mod4-regex/README.md new file mode 100644 index 0000000..6048ebb --- /dev/null +++ b/mod4-regex/README.md @@ -0,0 +1,35 @@ +# Mod4 Regex +[*View on Codewars*](https://www.codewars.com/kata/mod4-regex) + +> NOTE: This kata requires a decent knowledge of Regular Expressions. As such, it's best to learn about it _before_ tackling this kata. Some good places to start are: the [MDN pages](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp), and [Regular-Expressions.info](http://www.regular-expressions.info/). + +You are to write a Regular Expression that matches any string with at least one number divisible by 4 (with no remainder). In most languages, you could do this easily by using `number % 4 == 0`. How would you do it with Regex? + +A number will start with `[` and end with `]`. They may (or may not) include a plus or minus symbol at the start; this should be taken into account. Leading zeros may be present, and should be ignored (no octals here ;P). There may be other text in the string, outside of the number; this should also be ignored. Also, all numbers will be integers; any floats should be ignored. + +If there are no valid numbers defined as above, there should be no match made by your regex. + +So here are some examples: +```js +"[+05620]" // 5620 is divisible by 4 (valid) +"[+05621]" // 5621 is not divisible by 4 (invalid) +"[-55622]" // -55622 is not divisible by 4 (invalid) +"[005623]" // 5623 invalid +"[005624]" // 5624 valid +"[-05628]" // valid +"[005632]" // valid +"[555636]" // valid +"[+05640]" // valid +"[005600]" // valid +"the beginning [0] ... [invalid] numb[3]rs ... the end" // 0 is valid +"No, [2014] isn't a multiple of 4..." // 2014 is invalid +"...may be [+002016] will be." // 2016 is valid +``` + +> **NOTE:** Only `Mod4.test(str)` will be used, so your expression will just need make a match of some kind. + +## Timeline +- Created: 2014-11-25 +- Published: 2014-11-25 +- Approved: 2014-12-27 +- Completed: 2015-05-03 \ No newline at end of file diff --git a/mod4-regex/java/1/Mod.java b/mod4-regex/java/1/Mod.java new file mode 100644 index 0000000..4e4c5bc --- /dev/null +++ b/mod4-regex/java/1/Mod.java @@ -0,0 +1,5 @@ +import java.util.regex.Pattern; + +public class Mod { + public static Pattern mod4 = Pattern.compile("\\[[+-]?0*([048]|\\d*([02468][048]|[13579][26]))]"); +} \ No newline at end of file diff --git a/mod4-regex/java/2/Mod.java b/mod4-regex/java/2/Mod.java new file mode 100644 index 0000000..e0597e9 --- /dev/null +++ b/mod4-regex/java/2/Mod.java @@ -0,0 +1,5 @@ +import java.util.regex.Pattern; + +public class Mod { + public static Pattern mod4 = Pattern.compile("\\[[+-]?([048]|\\d*([02468][048]|[13579][26]))]"); +} \ No newline at end of file diff --git a/monty-hall-problem/README.md b/monty-hall-problem/README.md new file mode 100644 index 0000000..c9155d5 --- /dev/null +++ b/monty-hall-problem/README.md @@ -0,0 +1,16 @@ +# Monty Hall Problem +[*View on Codewars*](https://www.codewars.com/kata/monty-hall-problem) + +The Monty Hall problem is a probability puzzle base on the American tv show "Let's make a deal". + +In this show, you would be presented with 3 doors: One with a prize behind it, and two without (represented with goats). + +After choosing a door, the host would open one of the other two doors which didn't include a prize, and ask the participant if he or she wanted to switch to the third door. Most wouldn't. One would think you have a fifty-fifty chance of winning after having been shown a false door, however the math proves that you significally increase your chances, from 1/3 to 2/3 by switching. + +In this program you are given an array of people who have all guessed on a door from 1-3, as well as given the door which includes the price. You need to make every person switch to the other door, and increase their chances of winning. Return the winpercentage (in int, rounded) of all participants. + +## Timeline +- Created: 2015-03-06 +- Published: 2015-03-06 +- Approved: null +- Completed: 2015-05-09 \ No newline at end of file diff --git a/monty-hall-problem/java/1/MontyHall.java b/monty-hall-problem/java/1/MontyHall.java new file mode 100644 index 0000000..bf28456 --- /dev/null +++ b/monty-hall-problem/java/1/MontyHall.java @@ -0,0 +1,7 @@ +public class MontyHall { + public int montyHallCase(int correctDoorNumber, int[] participantGuesses) { + return (int) Math.round(java.util.Arrays.stream(participantGuesses) + .filter(guess -> guess != correctDoorNumber) + .count() * 100. / participantGuesses.length); + } +} \ No newline at end of file diff --git a/monty-hall-problem/java/2/MontyHall.java b/monty-hall-problem/java/2/MontyHall.java new file mode 100644 index 0000000..e0d853e --- /dev/null +++ b/monty-hall-problem/java/2/MontyHall.java @@ -0,0 +1,7 @@ +public class MontyHall { + public int montyHallCase(int correctDoorNumber, int[] participantGuesses) { + return Math.round(java.util.Arrays.stream(participantGuesses) + .filter(guess -> guess != correctDoorNumber) + .count() * 100f / participantGuesses.length); + } +} \ No newline at end of file diff --git a/multi-tap-keypad-text-entry-on-an-old-mobile-phone/README.md b/multi-tap-keypad-text-entry-on-an-old-mobile-phone/README.md new file mode 100644 index 0000000..1a31f82 --- /dev/null +++ b/multi-tap-keypad-text-entry-on-an-old-mobile-phone/README.md @@ -0,0 +1,49 @@ +# Multi-tap Keypad Text Entry on an Old Mobile Phone +[*View on Codewars*](https://www.codewars.com/kata/multi-tap-keypad-text-entry-on-an-old-mobile-phone) + +Prior to having fancy iPhones, teenagers would wear out their thumbs sending SMS +messages on candybar-shaped feature phones with 3x4 numeric keypads. + + ------- ------- ------- + | | | ABC | | DEF | + | 1 | | 2 | | 3 | + ------- ------- ------- + ------- ------- ------- + | GHI | | JKL | | MNO | + | 4 | | 5 | | 6 | + ------- ------- ------- + ------- ------- ------- + |PQRS | | TUV | | WXYZ| + | 7 | | 8 | | 9 | + ------- ------- ------- + ------- ------- ------- + | | |space| | | + | * | | 0 | | # | + ------- ------- ------- + +Prior to the development of T9 (predictive text entry) systems, the method to +type words was called "multi-tap" and involved pressing a button repeatedly to +cycle through the possible values. + +For example, to type a letter `"R"` you would press the `7` key three times (as +the screen display for the current character cycles through `P->Q->R->S->7`). A +character is "locked in" once the user presses a different key or pauses for a +short period of time (thus, no extra button presses are required beyond what is +needed for each letter individually). The zero key handles spaces, with one press of the key producing a space and two presses producing a zero. + +In order to send the message `"WHERE DO U WANT 2 MEET L8R"` a teen would have to +actually do 47 button presses. No wonder they abbreviated. + +For this assignment, write a module that can calculate the amount of button +presses required for any phrase. Punctuation can be ignored for this exercise. Likewise, you can assume the phone doesn't distinguish between upper/lowercase characters (but you should allow your module to accept input in either for convenience). + +Hint: While it wouldn't take too long to hard code the amount of keypresses for +all 26 letters by hand, try to avoid doing so! (Imagine you work at a phone +manufacturer who might be testing out different keyboard layouts, and you want +to be able to test new ones rapidly.) + +## Timeline +- Created: 2014-12-30 +- Published: 2014-12-30 +- Approved: 2015-04-26 +- Completed: 2015-05-05 \ No newline at end of file diff --git a/multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/1/Keypad.java b/multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/1/Keypad.java new file mode 100644 index 0000000..c4860d8 --- /dev/null +++ b/multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/1/Keypad.java @@ -0,0 +1,25 @@ +public class Keypad { + private final static char[][] keys = { + {'1'}, {'A', 'B', 'C', '2'}, {'D', 'E', 'F', '3'}, + {'G', 'H', 'I', '4'}, {'J', 'K', 'L', '5'}, {'M', 'N', 'O', '6'}, + {'P', 'Q', 'R', 'S', '7'}, {'T', 'U', 'V', '8'}, {'W', 'X', 'Y', 'Z', '9'}, + {'*'}, {' ', '0'}, {'#'}, + }; + + public static int presses(final String phrase) { + int presses = 0; + phrase: + for (final char letter : phrase.toCharArray()) { + final char upperLetter = Character.toUpperCase(letter); + for (final char[] key : keys) { + for (int i = 0; i < key.length; i++) { + if (upperLetter == key[i]) { + presses += i + 1; + continue phrase; + } + } + } + } + return presses; + } +} \ No newline at end of file diff --git a/multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/2/Keypad.java b/multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/2/Keypad.java new file mode 100644 index 0000000..8d4a753 --- /dev/null +++ b/multi-tap-keypad-text-entry-on-an-old-mobile-phone/java/2/Keypad.java @@ -0,0 +1,28 @@ +public class Keypad { + private final static char[][] keys = { + {'1'}, {'A', 'B', 'C', '2'}, {'D', 'E', 'F', '3'}, + {'G', 'H', 'I', '4'}, {'J', 'K', 'L', '5'}, {'M', 'N', 'O', '6'}, + {'P', 'Q', 'R', 'S', '7'}, {'T', 'U', 'V', '8'}, {'W', 'X', 'Y', 'Z', '9'}, + {'*'}, {' ', '0'}, {'#'}, + }; + + public static int presses(final String phrase) { + int presses = 0; + for (final char letter : phrase.toCharArray()) { + presses += presses(letter); + } + return presses; + } + + public static int presses(final char letter) { + final char upperLetter = Character.toUpperCase(letter); + for (final char[] key : keys) { + for (int i = 0; i < key.length; i++) { + if (upperLetter == key[i]) { + return i + 1; + } + } + } + return 0; + } +} \ No newline at end of file diff --git a/multiple-remainder-of-the-division/README.md b/multiple-remainder-of-the-division/README.md new file mode 100644 index 0000000..ac41d4a --- /dev/null +++ b/multiple-remainder-of-the-division/README.md @@ -0,0 +1,29 @@ +# Multiple remainder of the division +[*View on Codewars*](https://www.codewars.com/kata/multiple-remainder-of-the-division) + +Your task it to return ```true``` if the fractional part (rounded to 1 digit) of the result (```a``` / ```b```) exists, more than ```0``` and is multiple of ```n```. +Otherwise return ```false```. (For Python return True or False) + +All arguments are positive digital numbers. + +Rounding works like toFixed() method. (if more than...5 rounds up) + +Find exapmles below: + +``` + +isMultiple(5, 2, 3) -> false // 2.5 -> 5 is not multiple of 3 +isMultiple(5, 3, 4) -> false // 1.7 -> 7 is not multiple of 4 +isMultiple(5, 4, 3) -> true // 1.3 -> 3 is multiple of 3 +isMultiple(666, 665, 2) -> false // 1.0 -> return false + + +``` + + + +## Timeline +- Created: 2017-12-12 +- Published: 2017-12-12 +- Approved: 2017-12-12 +- Completed: 2017-12-12 \ No newline at end of file diff --git a/multiples-of-3-or-5/README.md b/multiples-of-3-or-5/README.md new file mode 100644 index 0000000..0dcfc11 --- /dev/null +++ b/multiples-of-3-or-5/README.md @@ -0,0 +1,17 @@ +# Multiples of 3 or 5 +[*View on Codewars*](https://www.codewars.com/kata/multiples-of-3-or-5) + +If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. + +Finish the solution so that it returns the sum of all the multiples of 3 or 5 **below** the number passed in. + +> Note: If the number is a multiple of **both** 3 and 5, only count it *once*. + +###### *Courtesy of ProjectEuler.net* + + +## Timeline +- Created: 2013-03-21 +- Published: 2013-03-28 +- Approved: null +- Completed: 2015-04-29 \ No newline at end of file diff --git a/multiples-of-3-or-5/java/1/Solution.java b/multiples-of-3-or-5/java/1/Solution.java new file mode 100644 index 0000000..6906268 --- /dev/null +++ b/multiples-of-3-or-5/java/1/Solution.java @@ -0,0 +1,22 @@ +public class Solution { + private int[] divisors = {3, 5}; + + public int solution(int number) { + int sum = 0; + for (int i = 1; i < number; i++) { + if (isMultiple(i)) { + sum += i; + } + } + return sum; + } + + private boolean isMultiple(int number) { + for (int divisor : divisors) { + if (number % divisor == 0) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/multiples-of-3-or-5/javascript/1/multiples-of-3-or-5.js b/multiples-of-3-or-5/javascript/1/multiples-of-3-or-5.js new file mode 100644 index 0000000..4a9e856 --- /dev/null +++ b/multiples-of-3-or-5/javascript/1/multiples-of-3-or-5.js @@ -0,0 +1,6 @@ +function solution(number) { + const f = x => x % 3 && x % 5 ? 0 : x; + let sum = 0; + for (let i = 3; i < number; sum += f(i), i++); + return sum; +} \ No newline at end of file diff --git a/multiplication-table-for-number/README.md b/multiplication-table-for-number/README.md new file mode 100644 index 0000000..51b1ca1 --- /dev/null +++ b/multiplication-table-for-number/README.md @@ -0,0 +1,27 @@ +# Multiplication table for number +[*View on Codewars*](https://www.codewars.com/kata/multiplication-table-for-number) + +Your goal is to return multiplication table for ```number``` that is always an integer from 1 to 10. + +For example, a multiplication table (string) for ```number == 5``` looks like below: + +``` +1 * 5 = 5 +2 * 5 = 10 +3 * 5 = 15 +4 * 5 = 20 +5 * 5 = 25 +6 * 5 = 30 +7 * 5 = 35 +8 * 5 = 40 +9 * 5 = 45 +10 * 5 = 50 +``` + +P. S. You can use ```\n``` in string to jump to the next line. + +## Timeline +- Created: 2017-12-12 +- Published: 2017-12-12 +- Approved: 2017-12-12 +- Completed: 2017-12-12 \ No newline at end of file diff --git a/multiplication-table-for-number/javascript/1/multiplication-table-for-number.js b/multiplication-table-for-number/javascript/1/multiplication-table-for-number.js new file mode 100644 index 0000000..091af84 --- /dev/null +++ b/multiplication-table-for-number/javascript/1/multiplication-table-for-number.js @@ -0,0 +1,3 @@ +function multiTable(number) { + return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(n => `${n} * ${number} = ${n * number}`).join('\n') +} \ No newline at end of file diff --git a/multiply/README.md b/multiply/README.md new file mode 100644 index 0000000..bf60b5e --- /dev/null +++ b/multiply/README.md @@ -0,0 +1,10 @@ +# Multiply +[*View on Codewars*](https://www.codewars.com/kata/multiply) + +The code does not execute properly. Try to figure out why. + +## Timeline +- Created: 2012-09-28 +- Published: 2013-05-18 +- Approved: 2013-12-03 +- Completed: 2014-01-21 \ No newline at end of file diff --git a/mumbling/README.md b/mumbling/README.md new file mode 100644 index 0000000..60b4019 --- /dev/null +++ b/mumbling/README.md @@ -0,0 +1,100 @@ +# Mumbling +[*View on Codewars*](https://www.codewars.com/kata/mumbling) + +This time no story, no theory. The examples below show you how to write function `accum`: + +**Examples:** + +```swift +accum("abcd") // -> "A-Bb-Ccc-Dddd" +accum("RqaEzty") // -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum("cwAt") // -> "C-Ww-Aaa-Tttt" +``` + +```fsharp +accum "abcd" -- "A-Bb-Ccc-Dddd" +accum "RqaEzty" -- "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum "cwAt" -- "C-Ww-Aaa-Tttt" +``` + +```clojure +(accum "abcd") ; "A-Bb-Ccc-Dddd" +(accum "RqaEzty") ; "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +(accum "cwAt") ; "C-Ww-Aaa-Tttt" +``` +```coffeescript +accum "abcd" # "A-Bb-Ccc-Dddd" +accum "RqaEzty" # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum "cwAt" # "C-Ww-Aaa-Tttt" +``` +```cpp +Accumul::accum("abcd"); // "A-Bb-Ccc-Dddd" +Accumul::accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +Accumul::accum("cwAt"); // "C-Ww-Aaa-Tttt" +``` +```csharp +Accumul.Accum("abcd"); // "A-Bb-Ccc-Dddd" +Accumul.Accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +Accumul.Accum("cwAt"); // "C-Ww-Aaa-Tttt" +``` +```elixir +Mumbling.accum "abcd" # "A-Bb-Ccc-Dddd" +Mumbling.accum "RqaEzty" # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +Mumbling.accum "cwAt" # "C-Ww-Aaa-Tttt" +``` +```haskell +accum "abcd" -- "A-Bb-Ccc-Dddd" +accum "RqaEzty" -- "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum "cwAt" -- "C-Ww-Aaa-Tttt" +``` +```java +Accumul.accum("abcd"); // "A-Bb-Ccc-Dddd" +Accumul.accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +Accumul.accum("cwAt"); // "C-Ww-Aaa-Tttt" +``` +```javascript +accum("abcd"); // "A-Bb-Ccc-Dddd" +accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum("cwAt"); // "C-Ww-Aaa-Tttt" +``` +```php +accum("abcd"); // "A-Bb-Ccc-Dddd" +accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum("cwAt"); // "C-Ww-Aaa-Tttt" +``` +```python +accum("abcd") # "A-Bb-Ccc-Dddd" +accum("RqaEzty") # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum("cwAt") # "C-Ww-Aaa-Tttt" +``` +```ruby +accum("abcd") # "A-Bb-Ccc-Dddd" +accum("RqaEzty") # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum("cwAt") # "C-Ww-Aaa-Tttt" +``` +```rust +accum(&"abcd") // "A-Bb-Ccc-Dddd" +accum(&"RqaEzty") // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum(&"cwAt") // "C-Ww-Aaa-Tttt" +``` +```typescript +accum("abcd"); // "A-Bb-Ccc-Dddd" +accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum("cwAt"); // "C-Ww-Aaa-Tttt" +``` +```r +accum("abcd") +[1] "A-Bb-Ccc-Dddd" +accum("RqaEzty") +[1] "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" +accum("cwAt") +[1] "C-Ww-Aaa-Tttt" +``` +The parameter of accum is a string which includes only letters from `a..z` and `A..Z`. + + +## Timeline +- Created: 2015-12-09 +- Published: 2015-12-09 +- Approved: 2015-12-11 +- Completed: 2017-12-12 \ No newline at end of file diff --git a/mumbling/java/1/Accumul.java b/mumbling/java/1/Accumul.java new file mode 100644 index 0000000..83aac8b --- /dev/null +++ b/mumbling/java/1/Accumul.java @@ -0,0 +1,20 @@ +public class Accumul { + public static String accum(String s) { + int l = s.length(); + if (l == 0) { + return s; + } + StringBuilder sb = new StringBuilder(l * (l + 1) / 2 + l - 1); + sb.append(s.charAt(0)); + for (int i = 1; i < l; i++) { + char c = s.charAt(i); + sb.append('-'); + sb.append(Character.toUpperCase(c)); + char lc = Character.toLowerCase(c); + for (int j = 0; j < i; j++) { + sb.append(lc); + } + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/mumbling/javascript/1/mumbling.js b/mumbling/javascript/1/mumbling.js new file mode 100644 index 0000000..e80462e --- /dev/null +++ b/mumbling/javascript/1/mumbling.js @@ -0,0 +1,3 @@ +function accum(s) { + return Array.from(s).map((c, i) => c.toUpperCase() + c.toLowerCase().repeat(i)).join('-'); +} \ No newline at end of file diff --git a/my-smallest-code-interpreter-aka-brainf-star-star-k/README.md b/my-smallest-code-interpreter-aka-brainf-star-star-k/README.md new file mode 100644 index 0000000..17b05ee --- /dev/null +++ b/my-smallest-code-interpreter-aka-brainf-star-star-k/README.md @@ -0,0 +1,33 @@ +# My smallest code interpreter (aka Brainf**k) +[*View on Codewars*](https://www.codewars.com/kata/my-smallest-code-interpreter-aka-brainf-star-star-k) + +Inspired from real-world [Brainf\*\*k](http://en.wikipedia.org/wiki/Brainfuck), we want to create an interpreter of that language which will support the following instructions (the machine memory or 'data' should behave like a potentially infinite array of bytes, initialized to 0): + +* `>` increment the data pointer (to point to the next cell to the right). +* `<` decrement the data pointer (to point to the next cell to the left). +* `+` increment (increase by one, truncate overflow: 255 + 1 = 0) the byte at the data pointer. +* `-` decrement (decrease by one, treat as unsigned byte: 0 - 1 = 255 ) the byte at the data pointer. +* `.` output the byte at the data pointer. +* `,` accept one byte of input, storing its value in the byte at the data pointer. +* `[` if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching `]` command. +* `]` if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching `[` command. + +The function will take in input... + +* the program code, a string with the sequence of machine instructions, +* the program input, a string, eventually empty, that will be interpreted as an array of bytes using each character's ASCII code and will be consumed by the `,` instruction + +... and will return ... + +* the output of the interpreted code (always as a string), produced by the `.` instruction. + +~~~if:bf +For BF: The code and input are separated by `'!'`. +~~~ + + +## Timeline +- Created: 2013-10-18 +- Published: 2013-10-18 +- Approved: null +- Completed: 2015-05-05 \ No newline at end of file diff --git a/my-smallest-code-interpreter-aka-brainf-star-star-k/java/1/BrainLuck.java b/my-smallest-code-interpreter-aka-brainf-star-star-k/java/1/BrainLuck.java new file mode 100644 index 0000000..e786cfc --- /dev/null +++ b/my-smallest-code-interpreter-aka-brainf-star-star-k/java/1/BrainLuck.java @@ -0,0 +1,132 @@ +public class BrainLuck { + public static final char OP_NEXT = '>'; + public static final char OP_PREVIOUS = '<'; + public static final char OP_INCREMENT = '+'; + public static final char OP_DECREMENT = '-'; + public static final char OP_WRITE = '.'; + public static final char OP_READ = ','; + public static final char OP_JUMP_ZERO = '['; + public static final char OP_JUMP_NONZERO = ']'; + + private final String code; + + public BrainLuck(final String code) { + this.code = code; + } + + public String process(final String input) { + final Data data = new Data(64); // tradeoff: performance / memory footprint + int inputPointer = 0; + final StringBuilder output = new StringBuilder(); + for (int instructionPointer = 0; instructionPointer < code.length(); instructionPointer++) { + final char instruction = code.charAt(instructionPointer); + switch (instruction) { + case OP_NEXT: + data.next(); + break; + case OP_PREVIOUS: + data.previous(); + break; + case OP_INCREMENT: + data.increment(); + break; + case OP_DECREMENT: + data.decrement(); + break; + case OP_WRITE: + output.append((char) Byte.toUnsignedInt(data.get())); + break; + case OP_READ: + data.set((byte) input.charAt(inputPointer++)); + break; + case OP_JUMP_ZERO: + if (data.get() == 0) { + int level = 1; + for (instructionPointer = instructionPointer + 1; instructionPointer < code.length(); instructionPointer++) { + final char nextInstruction = code.charAt(instructionPointer); + if (nextInstruction == OP_JUMP_ZERO) { + level++; + } else if (nextInstruction == OP_JUMP_NONZERO && --level == 0) { + break; + } + } + } + break; + case OP_JUMP_NONZERO: + if (data.get() != 0) { + int level = 1; + for (instructionPointer = instructionPointer - 1; instructionPointer >= 0; instructionPointer--) { + final char previousInstruction = code.charAt(instructionPointer); + if (previousInstruction == OP_JUMP_NONZERO) { + level++; + } else if (previousInstruction == OP_JUMP_ZERO && --level == 0) { + break; + } + } + } + break; + } + } + return output.toString(); + } +} + +class Data { + private final int growth; + private byte[] data; + private int pointer = 0; + + Data(final int growth) { + this.growth = growth; + data = new byte[growth]; + } + + void next() { + pointer++; + } + + void previous() { + pointer--; + } + + void increment() { + ensureCapacity(); + data[pointer]++; + } + + void decrement() { + ensureCapacity(); + data[pointer]--; + } + + byte get() { + ensureCapacity(); + return data[pointer]; + } + + void set(final byte b) { + ensureCapacity(); + data[pointer] = b; + } + + private void ensureCapacity() { + final int difference = data.length - pointer; + final int rate; + final int destPos; + + if (difference <= 0) { + rate = 1 - difference / growth; + destPos = 0; + } else if (difference > data.length) { + rate = 1 + difference / growth; + destPos = rate * growth; + } else { + return; + } + + final byte[] data = new byte[this.data.length + rate * growth]; + System.arraycopy(this.data, 0, data, destPos, this.data.length); + this.data = data; + pointer += destPos; + } +} \ No newline at end of file diff --git a/my-smallest-code-interpreter-aka-brainf-star-star-k/java/2/BrainLuck.java b/my-smallest-code-interpreter-aka-brainf-star-star-k/java/2/BrainLuck.java new file mode 100644 index 0000000..29e1345 --- /dev/null +++ b/my-smallest-code-interpreter-aka-brainf-star-star-k/java/2/BrainLuck.java @@ -0,0 +1,149 @@ +public class BrainLuck { + public static final char OP_NEXT = '>'; + public static final char OP_PREVIOUS = '<'; + public static final char OP_INCREMENT = '+'; + public static final char OP_DECREMENT = '-'; + public static final char OP_WRITE = '.'; + public static final char OP_READ = ','; + public static final char OP_JUMP_ZERO = '['; + public static final char OP_JUMP_NONZERO = ']'; + + private final String code; + + public BrainLuck(final String code) { + this.code = code; + } + + public String process(final String input) { + final Data data = new Data(1); // lowest memory footprint + int inputPointer = 0; + final StringBuilder output = new StringBuilder(); + for (int instructionPointer = 0; instructionPointer < code.length(); instructionPointer++) { + final char instruction = code.charAt(instructionPointer); + switch (instruction) { + case OP_NEXT: + data.next(); + break; + case OP_PREVIOUS: + data.previous(); + break; + case OP_INCREMENT: + data.increment(); + break; + case OP_DECREMENT: + data.decrement(); + break; + case OP_WRITE: + output.append((char) Byte.toUnsignedInt(data.get())); + break; + case OP_READ: + data.set((byte) input.charAt(inputPointer++)); + break; + case OP_JUMP_ZERO: + if (data.get() == 0) { + instructionPointer = matchNext(instructionPointer); + } + break; + case OP_JUMP_NONZERO: + if (data.get() != 0) { + instructionPointer = matchPrevious(instructionPointer); + } + break; + } + } + return output.toString(); + } + + private int matchNext(final int instructionPointer) { + return match(instructionPointer, true); + } + + private int matchPrevious(final int instructionPointer) { + return match(instructionPointer, false); + } + + private int match(final int start, final boolean next) { + final int step; + final char same; + final char match; + if (next) { + step = 1; + same = OP_JUMP_ZERO; + match = OP_JUMP_NONZERO; + } else { + step = -1; + same = OP_JUMP_NONZERO; + match = OP_JUMP_ZERO; + } + + for (int instructionPointer = start + step, level = 1; instructionPointer < code.length(); instructionPointer += step) { + final char nextInstruction = code.charAt(instructionPointer); + if (nextInstruction == same) { + level++; + } else if (nextInstruction == match && --level == 0) { + return instructionPointer; + } + } + throw new IllegalStateException(String.format("no match for start=%s and next=%b", start, next)); + } +} + +class Data { + private final int growth; + private byte[] data; + private int pointer = 0; + + Data(final int growth) { + this.growth = growth; + data = new byte[growth]; + } + + void next() { + pointer++; + } + + void previous() { + pointer--; + } + + void increment() { + ensureCapacity(); + data[pointer]++; + } + + void decrement() { + ensureCapacity(); + data[pointer]--; + } + + byte get() { + ensureCapacity(); + return data[pointer]; + } + + void set(final byte b) { + ensureCapacity(); + data[pointer] = b; + } + + private void ensureCapacity() { + final int difference = data.length - pointer; + final int rate; + final int destPos; + + if (difference <= 0) { + rate = 1 - difference / growth; + destPos = 0; + } else if (difference > data.length) { + rate = 1 + difference / growth; + destPos = rate * growth; + } else { + return; + } + + final byte[] data = new byte[this.data.length + rate * growth]; + System.arraycopy(this.data, 0, data, destPos, this.data.length); + this.data = data; + pointer += destPos; + } +} \ No newline at end of file diff --git a/name-array-capping/README.md b/name-array-capping/README.md new file mode 100644 index 0000000..c43e487 --- /dev/null +++ b/name-array-capping/README.md @@ -0,0 +1,32 @@ +# Name Array Capping +[*View on Codewars*](https://www.codewars.com/kata/name-array-capping) + +Create a method that accepts an array of names, and returns an array of each name with its first letter capitalized. + +example +```ruby +cap_me(['jo', 'nelson', 'jurie']) # returns ['Jo', 'Nelson', 'Jurie'] +cap_me(['KARLY', 'DANIEL', 'KELSEY']) # returns ['Karly', 'Daniel', 'Kelsey'] +``` +```javascript +capMe(['jo', 'nelson', 'jurie']) // returns ['Jo', 'Nelson', 'Jurie'] +capMe(['KARLY', 'DANIEL', 'KELSEY']) // returns ['Karly', 'Daniel', 'Kelsey'] +``` +```haskell +capMe ["jo", "nelson", "jurie"] `shouldBe` ["Jo","Nelson","Jurie"] +capMe ["JO", "NELSON", "JURIE"] `shouldBe` ["Jo","Nelson","Jurie"] +``` +```csharp +Kata.CapMe(new string[] {"jo", "nelson", "jurie"}) => new string[] {"Jo", "Nelson", "Jurie"} +Kata.CapMe(new string[] {"KARLY", "DANIEL", "KELSEY"}) => new string[] {"Karly", "Daniel", "Kelsey"} +``` +```java +Kata.capMe(new String[] {"jo", "nelson", "jurie"}) // returns new String[] {"Jo", "Nelson", "Jurie"} +Kata.capMe(new String[] {"KARLY", "DANIEL", "KELSEY"}) // returns new String[] {"Karly", "Daniel", "Kelsey"} +``` + +## Timeline +- Created: 2014-04-22 +- Published: 2014-04-22 +- Approved: 2014-05-12 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/next-bigger-number-with-the-same-digits/README.md b/next-bigger-number-with-the-same-digits/README.md new file mode 100644 index 0000000..63c2934 --- /dev/null +++ b/next-bigger-number-with-the-same-digits/README.md @@ -0,0 +1,61 @@ +# Next bigger number with the same digits +[*View on Codewars*](https://www.codewars.com/kata/next-bigger-number-with-the-same-digits) + +You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits: +```javascript +nextBigger(12)==21 +nextBigger(513)==531 +nextBigger(2017)==2071 +``` +```python +next_bigger(12)==21 +next_bigger(513)==531 +next_bigger(2017)==2071 +``` +```ruby +next_bigger(12)==21 +next_bigger(513)==531 +next_bigger(2017)==2071 +``` +```csharp +Kata.NextBiggerNumber(12)==21 +Kata.NextBiggerNumber(513)==531 +Kata.NextBiggerNumber(2017)==2071 +``` +```java +Kata.nextBiggerNumber(12)==21 +Kata.nextBiggerNumber(513)==531 +Kata.nextBiggerNumber(2017)==2071 +``` +If no bigger number can be composed using those digits, return -1: +```javascript +nextBigger(9)==-1 +nextBigger(111)==-1 +nextBigger(531)==-1 +``` +```python +next_bigger(9)==-1 +next_bigger(111)==-1 +next_bigger(531)==-1 +``` +```ruby +next_bigger(9)==-1 +next_bigger(111)==-1 +next_bigger(531)==-1 +``` +```csharp +Kata.NextBiggerNumber(9)==-1 +Kata.NextBiggerNumber(111)==-1 +Kata.NextBiggerNumber(531)==-1 +``` +```java +Kata.nextBiggerNumber(9)==-1 +Kata.nextBiggerNumber(111)==-1 +Kata.nextBiggerNumber(531)==-1 +``` + +## Timeline +- Created: 2015-07-04 +- Published: 2015-07-04 +- Approved: 2015-09-28 +- Completed: 2018-03-17 \ No newline at end of file diff --git a/next-bigger-number-with-the-same-digits/javascript/1/next-bigger-number-with-the-same-digits.js b/next-bigger-number-with-the-same-digits/javascript/1/next-bigger-number-with-the-same-digits.js new file mode 100644 index 0000000..9ac9a37 --- /dev/null +++ b/next-bigger-number-with-the-same-digits/javascript/1/next-bigger-number-with-the-same-digits.js @@ -0,0 +1,27 @@ +function nextBigger(n) { + const digits = digitize(n) + const index = digits.findIndex((d, i) => digits[i - 1] > d) + if (index === -1) { + return -1 + } + const right = digits.slice(index + 1) + const pivot = digits[index] + const left = digits.slice(0, index + 1).sort((m, n) => m - n) + const promotedIndex = left.findIndex(n => n > pivot) + const promoted = left[promotedIndex] + left.splice(promotedIndex, 1) + const result = [ + ...left.reverse(), + promoted, + ...right + ].reverse().reduce((reversed, digit) => 10 * reversed + digit) + return result +} + +function digitize(n) { + const digits = [] + do { + digits.push(n % 10) + } while ((n = Math.trunc(n / 10)) > 0) + return digits +} \ No newline at end of file diff --git a/number-of-trailing-zeros-of-n/README.md b/number-of-trailing-zeros-of-n/README.md new file mode 100644 index 0000000..758c8db --- /dev/null +++ b/number-of-trailing-zeros-of-n/README.md @@ -0,0 +1,29 @@ +# Number of trailing zeros of N! +[*View on Codewars*](https://www.codewars.com/kata/number-of-trailing-zeros-of-n) + +Write a program that will calculate the number of trailing zeros in a factorial of a given number. + +`N! = 1 * 2 * 3 * ... * N` + +Be careful `1000!` has 2568 digits... + +For more info, see: http://mathworld.wolfram.com/Factorial.html + +## Examples + +``` +zeros(6) = 1 +# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero + +zeros(12) = 2 +# 12! = 479001600 --> 2 trailing zeros +``` + +*Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.* + + +## Timeline +- Created: 2014-02-09 +- Published: 2014-02-09 +- Approved: 2014-03-27 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/number-of-trailing-zeros-of-n/java/1/Solution.java b/number-of-trailing-zeros-of-n/java/1/Solution.java new file mode 100644 index 0000000..14ff896 --- /dev/null +++ b/number-of-trailing-zeros-of-n/java/1/Solution.java @@ -0,0 +1,17 @@ +public class Solution { + private static final int P = 5; + + // De Polignac's formula + public static int zeros(final int n) { + int zeros = 0; + for (int i = 1, k = k(n), p = P; i <= k; i++, p *= P) { + zeros += n / p; + } + return zeros; + } + + // P^(k+1) > n + private static int k(final int n) { + return (int) (Math.log(n) / Math.log(P)); + } +} \ No newline at end of file diff --git a/number-tostring/README.md b/number-tostring/README.md new file mode 100644 index 0000000..2169c10 --- /dev/null +++ b/number-tostring/README.md @@ -0,0 +1,38 @@ +# Number toString +[*View on Codewars*](https://www.codewars.com/kata/number-tostring) + +The code gives an error! + +```clojure +(def a (123 toString)) +``` +```haskell +a = 123 . toString +``` +```ruby +a = some_number.toString +``` +```python +a = 123.toString() +``` +```java +public static final String a = 123.toString(); +``` +```javascript +a = 123.toString +``` +```coffeescript +a = 123.toString +``` +```csharp +Kata.A = 123.ToSTring(); +``` + +Fix it! + + +## Timeline +- Created: 2014-06-07 +- Published: 2014-06-07 +- Approved: 2014-09-27 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/ones-and-zeros/README.md b/ones-and-zeros/README.md new file mode 100644 index 0000000..1da145a --- /dev/null +++ b/ones-and-zeros/README.md @@ -0,0 +1,26 @@ +# Ones and Zeros +[*View on Codewars*](https://www.codewars.com/kata/ones-and-zeros) + +Given an array of one's and zero's convert the equivalent binary value to an integer. + +Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1 + +Examples: +``` +Testing: [0, 0, 0, 1] ==> 1 +Testing: [0, 0, 1, 0] ==> 2 +Testing: [0, 1, 0, 1] ==> 5 +Testing: [1, 0, 0, 1] ==> 9 +Testing: [0, 0, 1, 0] ==> 2 +Testing: [0, 1, 1, 0] ==> 6 +Testing: [1, 1, 1, 1] ==> 15 +Testing: [1, 0, 1, 1] ==> 11 +``` + +_Note: you shouldn't mutate the input_ + +## Timeline +- Created: 2016-07-12 +- Published: 2016-07-12 +- Approved: 2016-07-13 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/ones-and-zeros/java/1/BinaryArrayToNumber.java b/ones-and-zeros/java/1/BinaryArrayToNumber.java new file mode 100644 index 0000000..f2cddb7 --- /dev/null +++ b/ones-and-zeros/java/1/BinaryArrayToNumber.java @@ -0,0 +1,13 @@ +import java.util.List; + +public class BinaryArrayToNumber { + + public static int ConvertBinaryArrayToInt(List binary) { + int n = 0; + for (int b : binary) { + n <<= 1; + n |= b; + } + return n; + } +} \ No newline at end of file diff --git a/ones-and-zeros/java/2/BinaryArrayToNumber.java b/ones-and-zeros/java/2/BinaryArrayToNumber.java new file mode 100644 index 0000000..83b6866 --- /dev/null +++ b/ones-and-zeros/java/2/BinaryArrayToNumber.java @@ -0,0 +1,8 @@ +import java.util.List; + +public class BinaryArrayToNumber { + + public static int ConvertBinaryArrayToInt(List binary) { + return binary.stream().reduce(0, (r, e) -> r << 1 | e); + } +} \ No newline at end of file diff --git a/overflowing-with-joy/README.md b/overflowing-with-joy/README.md new file mode 100644 index 0000000..e300407 --- /dev/null +++ b/overflowing-with-joy/README.md @@ -0,0 +1,12 @@ +# Overflowing with joy +[*View on Codewars*](https://www.codewars.com/kata/overflowing-with-joy) + +Multiply two ints, but take care of overflow. If the result cannot be accurately stored in an int, throw an ArithmeticException. + +(If this is too easy, try [overflowing with longing](/kata/overflowing-with-longing).) + +## Timeline +- Created: 2015-03-29 +- Published: 2015-03-29 +- Approved: 2016-11-19 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/overflowing-with-joy/java/1/Multiplier.java b/overflowing-with-joy/java/1/Multiplier.java new file mode 100644 index 0000000..ebc68f9 --- /dev/null +++ b/overflowing-with-joy/java/1/Multiplier.java @@ -0,0 +1,5 @@ +public class Multiplier { + public static int multiply(int a, int b) { + return Math.multiplyExact(a, b); + } +} \ No newline at end of file diff --git a/overflowing-with-longing/README.md b/overflowing-with-longing/README.md new file mode 100644 index 0000000..ef83b3f --- /dev/null +++ b/overflowing-with-longing/README.md @@ -0,0 +1,12 @@ +# Overflowing with longing +[*View on Codewars*](https://www.codewars.com/kata/overflowing-with-longing) + +Multiply two longs, but take care of overflow. If the result cannot be accurately stored in a long, throw an ArithmeticException. + +(Because [overflowing with joy](/kata/overflowing-with-joy) is too easy.) + +## Timeline +- Created: 2015-03-31 +- Published: 2015-03-31 +- Approved: 2016-11-19 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/overflowing-with-longing/java/1/Multiplier.java b/overflowing-with-longing/java/1/Multiplier.java new file mode 100644 index 0000000..ff1f99b --- /dev/null +++ b/overflowing-with-longing/java/1/Multiplier.java @@ -0,0 +1,5 @@ +public class Multiplier { + public static long multiply(long a, long b) { + return Math.multiplyExact(a, b); + } +} \ No newline at end of file diff --git a/paginationhelper/README.md b/paginationhelper/README.md new file mode 100644 index 0000000..ea05f55 --- /dev/null +++ b/paginationhelper/README.md @@ -0,0 +1,115 @@ +# PaginationHelper +[*View on Codewars*](https://www.codewars.com/kata/paginationhelper) + +For this exercise you will be strengthening your page-fu mastery. You will complete the PaginationHelper class, which is a utility class helpful for querying paging information related to an array. + +The class is designed to take in an array of values and an integer indicating how many items will be allowed per each page. The types of values contained within the collection/array are not relevant. + +The following are some examples of how this class is used: + +```javascript +var helper = new PaginationHelper(['a','b','c','d','e','f'], 4); +helper.pageCount(); //should == 2 +helper.itemCount(); //should == 6 +helper.pageItemCount(0); //should == 4 +helper.pageItemCount(1); // last page - should == 2 +helper.pageItemCount(2); // should == -1 since the page is invalid + +// pageIndex takes an item index and returns the page that it belongs on +helper.pageIndex(5); //should == 1 (zero based index) +helper.pageIndex(2); //should == 0 +helper.pageIndex(20); //should == -1 +helper.pageIndex(-10); //should == -1 +``` +```java +PaginationHelper helper = new PaginationHelper(Arrays.asList('a', 'b', 'c', 'd', 'e', 'f'), 4); +helper.pageCount(); //should == 2 +helper.itemCount(); //should == 6 +helper.pageItemCount(0); //should == 4 +helper.pageItemCount(1); // last page - should == 2 +helper.pageItemCount(2); // should == -1 since the page is invalid + +// pageIndex takes an item index and returns the page that it belongs on +helper.pageIndex(5); //should == 1 (zero based index) +helper.pageIndex(2); //should == 0 +helper.pageIndex(20); //should == -1 +helper.pageIndex(-10); //should == -1 +``` +```coffeescript +helper = new PaginationHelper(['a','b','c','d','e','f'], 4) +helper.pageCount() # should == 2 +helper.itemCount() # should == 6 +helper.pageItemCount(0) # should == 4 +helper.pageItemCount(1) # last page - should == 2 +helper.pageItemCount(2) # should == -1 since the page is invalid + +# pageIndex takes an item index and returns the page that it belongs on +helper.pageIndex(5) # should == 1 (zero based index) +helper.pageIndex(2) # should == 0 +helper.pageIndex(20) # should == -1 +helper.pageIndex(-10) # should == -1 +``` +```ruby +helper = PaginationHelper.new(['a','b','c','d','e','f'], 4) +helper.page_count # should == 2 +helper.item_count # should == 6 +helper.page_item_count(0) # should == 4 +helper.page_item_count(1) # last page - should == 2 +helper.page_item_count(2) # should == -1 since the page is invalid + +# page_ndex takes an item index and returns the page that it belongs on +helper.page_index(5) # should == 1 (zero based index) +helper.page_index(2) # should == 0 +helper.page_index(20) # should == -1 +helper.page_index(-10) # should == -1 because negative indexes are invalid +``` +```haskell +collection = ['a','b','c','d','e','f'] +itemsPerPage = 4 + +pageCount collection itemsPerPage `shouldBe` 2 +itemCount collection itemsPerPage `shouldBe` 6 + +pageItemCount collection itemsPerPage 0 `shouldBe` Just 4 -- four of six items +pageItemCount collection itemsPerPage 1 `shouldBe` Just 2 -- the last two items +pageItemCount collection itemsPerPage 3 `shouldBe` Nothing -- page doesn't exist + +pageIndex collection itemsPerPage 0 `shouldBe` Just 0 -- zero based index +pageIndex collection itemsPerPage 5 `shouldBe` Just 1 +pageIndex collection itemsPerPage 20 `shouldBe` Nothing +pageIndex collection itemsPerPage (-20) `shouldBe` Nothing +``` +```python +helper = PaginationHelper(['a','b','c','d','e','f'], 4) +helper.page_count # should == 2 +helper.item_count # should == 6 +helper.page_item_count(0) # should == 4 +helper.page_item_count(1) # last page - should == 2 +helper.page_item_count(2) # should == -1 since the page is invalid + +# page_ndex takes an item index and returns the page that it belongs on +helper.page_index(5) # should == 1 (zero based index) +helper.page_index(2) # should == 0 +helper.page_index(20) # should == -1 +helper.page_index(-10) # should == -1 because negative indexes are invalid +``` +```csharp +var helper = new PaginationHelper(new List{'a', 'b', 'c', 'd', 'e', 'f'}, 4); +helper.PageCount; //should == 2 +helper.ItemCount; //should == 6 +helper.PageItemCount(0); //should == 4 +helper.PageItemCount(1); // last page - should == 2 +helper.PageItemCount(2); // should == -1 since the page is invalid + +// pageIndex takes an item index and returns the page that it belongs on +helper.PageIndex(5); //should == 1 (zero based index) +helper.PageIndex(2); //should == 0 +helper.PageIndex(20); //should == -1 +helper.PageIndex(-10); //should == -1 +``` + +## Timeline +- Created: 2013-04-03 +- Published: 2013-04-11 +- Approved: 2013-12-12 +- Completed: 2015-05-03 \ No newline at end of file diff --git a/paginationhelper/java/1/PaginationHelper.java b/paginationhelper/java/1/PaginationHelper.java new file mode 100644 index 0000000..3746038 --- /dev/null +++ b/paginationhelper/java/1/PaginationHelper.java @@ -0,0 +1,43 @@ +import java.util.List; + +public class PaginationHelper { + private final int itemCount; + private final int itemsPerPage; + private final int pageCount; + + public PaginationHelper(final List items, final int itemsPerPage) { + this(items.size(), itemsPerPage); + } + + public PaginationHelper(final int itemCount, final int itemsPerPage) { + this.itemCount = itemCount; + this.itemsPerPage = itemsPerPage; + pageCount = (int) Math.ceil(itemCount / (double) itemsPerPage); + } + + public int itemCount() { + return itemCount; + } + + public int pageCount() { + return pageCount; + } + + public int pageItemCount(final int pageIndex) { + final int lastPageIndex = pageCount - 1; + if (pageIndex < 0 || pageIndex > lastPageIndex) { + return -1; + } + if (pageIndex < lastPageIndex) { + return itemsPerPage; + } + return itemCount - itemsPerPage * lastPageIndex; + } + + public int pageIndex(final int itemIndex) { + if (itemIndex < 0 || itemIndex >= itemCount) { + return -1; + } + return itemIndex / itemsPerPage; + } +} \ No newline at end of file diff --git a/palindrome-checker/README.md b/palindrome-checker/README.md new file mode 100644 index 0000000..99e9cf5 --- /dev/null +++ b/palindrome-checker/README.md @@ -0,0 +1,16 @@ +# Palindrome checker +[*View on Codewars*](https://www.codewars.com/kata/palindrome-checker) + +According to [Wikipedia](https://en.wikipedia.org/wiki/Palindrome), a palindrome is "a word, phrase, number, or other sequence of characters which reads the same backward or forward." Examples of palindromes include "racecar", "tacocat", and "123454321". + +Capitalization, punctuation, and word dividers will be ignored when checking if a string is a palindrome. For example, "Was it a car or a cat I saw?" is a valid palindrome in context of this Kata. + +All requirements from definition should be fulfilled.
+If the given string is a palindrome, return `true`.
+If not, or in case of `null` input (`None` for Python) return `false`. + +## Timeline +- Created: 2014-12-24 +- Published: 2014-12-24 +- Approved: null +- Completed: 2015-05-08 \ No newline at end of file diff --git a/palindrome-checker/java/1/PalindromChecker.java b/palindrome-checker/java/1/PalindromChecker.java new file mode 100644 index 0000000..0e2e01d --- /dev/null +++ b/palindrome-checker/java/1/PalindromChecker.java @@ -0,0 +1,9 @@ +public class PalindromChecker { + public boolean isPalindrome(String str) { + if (str == null) { + return false; + } + String sanitized = str.replaceAll("\\W", ""); + return sanitized.equalsIgnoreCase(new StringBuilder(sanitized).reverse().toString()); + } +} \ No newline at end of file diff --git a/palindrome-checker/java/2/PalindromChecker.java b/palindrome-checker/java/2/PalindromChecker.java new file mode 100644 index 0000000..79a7fe5 --- /dev/null +++ b/palindrome-checker/java/2/PalindromChecker.java @@ -0,0 +1,30 @@ +public class PalindromChecker { + public boolean isPalindrome(String str) { + if (str == null) { + return false; + } + for (int l = next(str, -1), r = previous(str, str.length()); l < r; l = next(str, l), r = previous(str, r)) { + if (Character.toUpperCase(str.charAt(l)) != Character.toUpperCase(str.charAt(r))) { + return false; + } + } + return true; + } + + private int next(String str, int i) { + return find(str, i, 1); + } + + private int previous(String str, int i) { + return find(str, i, -1); + } + + private int find(String str, int i, int k) { + for (int j = i + k; j >= 0 && j < str.length(); j += k) { + if (Character.isLetterOrDigit(str.charAt(j))) { + return j; + } + } + return i; + } +} \ No newline at end of file diff --git a/parse-a-linked-list-from-a-string/README.md b/parse-a-linked-list-from-a-string/README.md new file mode 100644 index 0000000..af65655 --- /dev/null +++ b/parse-a-linked-list-from-a-string/README.md @@ -0,0 +1,301 @@ +# Parse a linked list from a string +[*View on Codewars*](https://www.codewars.com/kata/parse-a-linked-list-from-a-string) + +# Parse a linked list from a string + +## Related Kata + +Although this Kata is not part of an official Series, you may want to complete [this Kata](https://www.codewars.com/kata/convert-a-linked-list-to-a-string) before attempting this one as these two Kata are deeply related. + +## Preloaded + +Preloaded for you is a class/struct `Node` (depending on the language) used to construct linked lists in this Kata: + +```php +class Node { + public $data, $next; + public function __construct($data, $next = NULL) { + $this->data = $data; + $this->next = $next; + } +} +``` +```javascript +class Node { + constructor(data, next = null) { + this.data = data; + this.next = next; + } +} +``` +```csharp +public class Node : Object +{ + public int Data; + public Node Next; + + public Node(int data, Node next = null) + { + this.Data = data; + this.Next = next; + } + + public override bool Equals(Object obj) + { + // Check for null values and compare run-time types. + if (obj == null || GetType() != obj.GetType()) { return false; } + + return this.ToString() == obj.ToString(); + } + + public override string ToString() + { + List result = new List(); + Node curr = this; + + while (curr != null) + { + result.Add(curr.Data); + curr = curr.Next; + } + + return String.Join(" -> ", result) + " -> null"; + } +} +``` +```swift +class Node { + var data : Int + var next : Node? + init(_ data:Int) { + self.data = data + self.next = nil + } + init(_ data:Int, _ next: Node?) { + self.data = data + self.next = next + } +} +``` +```c +typedef struct node { + int data; + struct node *next; +} Node; +``` +```cpp +class Node { + public: + int data; + Node *next; + Node(int data, Node *next = nullptr): data(data), next(next) {} +}; +``` +```objc +typedef struct node { + int data; + struct node *next; +} Node; +``` + +~~~if:c +*NOTE: In C, the* `Node` *struct is placed on top of your main solution because otherwise the compiler complains about not recognizing the struct (even if it is defined in the Preloaded section). Attempts to modify it (e.g. to cheat the tests in some way) will likely result in a test crash so it is not recommended for you to modify that section ;)* +~~~ + +~~~if:objc +*NOTE: In Objective-C, the* `Node` *struct is placed on top of your main solution because there is a "double-import" bug in the Preloaded section at the time of writing that cannot be fixed on my end. Attempts to modify it (e.g. to cheat the tests in some way) will likely result in a test crash so it is not recommended for you to modify that section ;)* +~~~ + +## Prerequisites + +This Kata assumes that you are already familiar with the idea of a linked list. If you do not know what that is, you may want to read up on [this article on Wikipedia](https://en.wikipedia.org/wiki/Linked_list). Specifically, the linked lists this Kata is referring to are **singly linked lists**, where the value of a specific node is stored in its `data`/`$data`/`Data` property, the reference to the next node is stored in its `next`/`$next`/`Next` property and the terminator for a list is `null`/`NULL`/`nil`/`nullptr`. + +Additionally, this Kata assumes that you have basic knowledge of Object-Oriented Programming (or a similar concept) in the programming language you are undertaking. If you have not come across Object-Oriented Programming in your selected language, you may want to try out an online course or read up on some code examples of OOP in your selected language up to (but not necessarily including) Classical Inheritance. + +*Specifically, if you are attempting this Kata in PHP and haven't come across OOP, you may want to try out the first 4 Kata in [this Series](https://www.codewars.com/collections/object-oriented-php).* + +## Task + +Create a function `parse` which accepts exactly one argument `string`/`$string`/`s` (or similar, depending on the language) which is a string representation of a linked list. Your function must return the corresponding linked list, constructed from instances of the `Node` class. The string representation of a list has the following format: the value of the node, followed by a whitespace, an arrow and another whitespace (`" -> "`), followed by the rest of the linked list. Each string representation of a linked list will end in `"null"`/`"NULL"`/`"nil"`/`"nullptr"` depending on the language you are undertaking this Kata in. For example, given the following string representation of a linked list: + +```php +"1 -> 2 -> 3 -> NULL" +``` +```c +"1 -> 2 -> 3 -> NULL" +``` +```javascript +"1 -> 2 -> 3 -> null" +``` +```csharp +"1 -> 2 -> 3 -> null" +``` +```swift +"1 -> 2 -> 3 -> nil" +``` +```cpp +"1 -> 2 -> 3 -> nullptr" +``` +```objc +@"1 -> 2 -> 3 -> NULL" +``` + + ... your function should return: + +```php +new Node(1, new Node(2, new Node(3))) +``` +```javascript +new Node(1, new Node(2, new Node(3))) +``` +```csharp +new Node(1, new Node(2, new Node(3))) +``` +```swift +Node(1, Node(2, Node(3))) +``` +```c +// Code example not applicable to C - the Node struct does not have a constructor function +``` +```cpp +new Node(1, new Node(2, new Node(3))) +``` +```objc +// Code example not applicable to Objective-C - the Node struct does not have a constructor function +``` + +Note that due to the way the constructor for `Node` is defined, if a second argument is not provided, the `next`/`$next`/`Next` field is automatically set to `null`/`NULL`/`nil`/`nullptr` (or equivalent in your language). That means your function could also return the following (if it helps you better visualise what is actually going on): + +```php +new Node(1, new Node(2, new Node(3, NULL))) +``` +```javascript +new Node(1, new Node(2, new Node(3, null))) +``` +```csharp +new Node(1, new Node(2, new Node(3, null))) +``` +```swift +Node(1, Node(2, Node(3, nil))) +``` +```c +// In C the Node struct does not have a constructor function - please return a dynamically allocated version of the list displayed below: + +&((Node){ + .data = 1, + .next = &((Node){ + .data = 2, + .next = &((Node){ + .data = 3, + .next = NULL + }) + }) +}) +``` +```cpp +new Node(1, new Node(2, new Node(3, nullptr))) +``` +```objc +// In Objective-C the Node struct does not have a constructor function - please return a dynamically allocated version of the list displayed below: + +&((Node){ + .data = 1, + .next = &((Node){ + .data = 2, + .next = &((Node){ + .data = 3, + .next = NULL + }) + }) +}) +``` + +Another example: given the following string input: + +```php +"0 -> 1 -> 4 -> 9 -> 16 -> NULL" +``` +```c +"0 -> 1 -> 4 -> 9 -> 16 -> NULL" +``` +```javascript +"0 -> 1 -> 4 -> 9 -> 16 -> null" +``` +```csharp +"0 -> 1 -> 4 -> 9 -> 16 -> null" +``` +```swift +"0 -> 1 -> 4 -> 9 -> 16 -> nil" +``` +```cpp +"0 -> 1 -> 4 -> 9 -> 16 -> nullptr" +``` +```objc +@"0 -> 1 -> 4 -> 9 -> 16 -> NULL" +``` + + ... your function should return: + +```php +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```javascript +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```csharp +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```swift +Node(0, Node(1, Node(4, Node(9, Node(16))))) +``` +```c +&((Node){ + .data = 0, + .next = &((Node){ + .data = 1, + .next = &((Node){ + .data = 4, + .next = &((Node){ + .data = 9, + .next = &((Node){ + .data = 16, + .next = NULL + }) + }) + }) + }) +}) +``` +```cpp +new Node(0, new Node(1, new Node(4, new Node(9, new Node(16))))) +``` +```objc +&((Node){ + .data = 0, + .next = &((Node){ + .data = 1, + .next = &((Node){ + .data = 4, + .next = &((Node){ + .data = 9, + .next = &((Node){ + .data = 16, + .next = NULL + }) + }) + }) + }) +}) +``` + +If the input string is just `"null"`/`"NULL"`/`"nil"`/`"nullptr"`, return `null`/`NULL`/`nil`/`nullptr` (or equivalent). + +For the simplicity of this Kata, the values of the nodes in the string representation will always ever be **non-negative integers**, so the following would **not** occur: `"Hello World -> Goodbye World -> 123 -> null"`/`"Hello World -> Goodbye World -> 123 -> NULL"`/`"Hello World -> Goodbye World -> 123 -> nil"`/`"Hello World -> Goodbye World -> 123 -> nullptr"` (depending on the language). This also means that the values of each `Node` must also be **non-negative integers** so keep that in mind when you are parsing the list from the string. + +Enjoy, and don't forget to check out my other Kata Series :D + +## Timeline +- Created: 2016-11-16 +- Published: 2016-11-16 +- Approved: 2017-03-13 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/parse-a-linked-list-from-a-string/javascript/1/parse-a-linked-list-from-a-string.js b/parse-a-linked-list-from-a-string/javascript/1/parse-a-linked-list-from-a-string.js new file mode 100644 index 0000000..1140d1a --- /dev/null +++ b/parse-a-linked-list-from-a-string/javascript/1/parse-a-linked-list-from-a-string.js @@ -0,0 +1,9 @@ +const delimiter = ' -> ' +const { length } = delimiter + +function parse(string) { + const index = string.indexOf(delimiter) + return index === -1 + ? null + : new Node(+string.substr(0, index), parse(string.substr(index + length))) +} \ No newline at end of file diff --git a/part-1-evil-programming-government-restrictions/README.md b/part-1-evil-programming-government-restrictions/README.md new file mode 100644 index 0000000..bef02d8 --- /dev/null +++ b/part-1-evil-programming-government-restrictions/README.md @@ -0,0 +1,23 @@ +# Part 1: Evil Programming Government Restrictions +[*View on Codewars*](https://www.codewars.com/kata/part-1-evil-programming-government-restrictions) + +The evil programming government has banned the use of numbers. +Your task, if you choose to accept it is to return numbers, without using numbers. + +Problems: + +- You can't use number literals in your source code. +- You can't use the length property directly in your code. + + + + +Goal: + +- You have to return 'I can write numbers like, 1, 2, 3.' + +## Timeline +- Created: 2013-10-09 +- Published: 2013-10-09 +- Approved: null +- Completed: 2015-05-24 \ No newline at end of file diff --git a/part-1-evil-programming-government-restrictions/javascript/1/part-1-evil-programming-government-restrictions.js b/part-1-evil-programming-government-restrictions/javascript/1/part-1-evil-programming-government-restrictions.js new file mode 100644 index 0000000..02c41a4 --- /dev/null +++ b/part-1-evil-programming-government-restrictions/javascript/1/part-1-evil-programming-government-restrictions.js @@ -0,0 +1,6 @@ +var anarchy = function () { + var one = +true; + var two = one + one; + var three = two + one; + return 'I can write numbers like, ' + one +', ' + two + ', ' + three + '.'; +} \ No newline at end of file diff --git a/partial-word-searching/README.md b/partial-word-searching/README.md new file mode 100644 index 0000000..9dcab0f --- /dev/null +++ b/partial-word-searching/README.md @@ -0,0 +1,19 @@ +# Partial Word Searching +[*View on Codewars*](https://www.codewars.com/kata/partial-word-searching) + +Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings. + +The method takes two parameters, the query string and the array of strings to search, and returns an array. + +If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty" (or `Nothing` in Haskell, or "None" in Python) + +### Examples +If the string to search for is "me", and the array to search is ["home", "milk", "Mercury", "fish"], the method should return ["home", "Mercury"]. + + + +## Timeline +- Created: 2015-01-15 +- Published: 2015-01-15 +- Approved: 2015-02-06 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/partial-word-searching/java/1/WordSearch.java b/partial-word-searching/java/1/WordSearch.java new file mode 100644 index 0000000..88ae746 --- /dev/null +++ b/partial-word-searching/java/1/WordSearch.java @@ -0,0 +1,23 @@ +import java.util.Arrays; + +class WordSearch { + static String[] findWord(String needle, String[] haystacks) { + final String[] findings = Arrays.stream(haystacks).filter(z -> containsIgnoreCase(z, needle)).toArray(String[]::new); + return findings.length > 0 ? findings : new String[]{"Empty"}; + } + + static boolean containsIgnoreCase(final String haystack, final String needle) { + return indexOfIgnoreCase(haystack, needle) >= 0; + } + + static int indexOfIgnoreCase(final String haystack, final String needle) { + final int haystackLength = haystack.length(); + final int needleLength = needle.length(); + for (int i = 0; i <= haystackLength - needleLength; i++) { + if (haystack.regionMatches(true, i, needle, 0, needleLength)) { + return i; + } + } + return -1; + } +} \ No newline at end of file diff --git a/permutations/README.md b/permutations/README.md new file mode 100644 index 0000000..9eba2b7 --- /dev/null +++ b/permutations/README.md @@ -0,0 +1,41 @@ +# Permutations +[*View on Codewars*](https://www.codewars.com/kata/permutations) + +In this kata you have to create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all letters from the input in all possible orders. + +Examples: + +```javascript +permutations('a'); // ['a'] +permutations('ab'); // ['ab', 'ba'] +permutations('aabb'); // ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'] +``` +```cpp +permutations("a"); // => vector {"a"} +permutations("ab"); // => vector {"ab", "ba"} +permutations("aabb"); // => vector {"aabb", "abab", "abba", "baab", "baba", "bbaa"} +``` +```ruby +permutations('a'); # ['a'] +permutations('ab'); # ['ab', 'ba'] +permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'] +``` +```python +permutations('a'); # ['a'] +permutations('ab'); # ['ab', 'ba'] +permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'] +``` +```haskell +permutations "a" `shouldBe` ["a"] +permutations "ab" `shouldBe` ["ab", "ba"] +permutations "aabb" `shouldBe` ["aabb","abab","abba","baab","baba","bbaa"] +``` + +The order of the permutations doesn't matter. + + +## Timeline +- Created: 2013-10-09 +- Published: 2013-10-09 +- Approved: null +- Completed: 2015-05-26 \ No newline at end of file diff --git a/permutations/javascript/1/permutations.js b/permutations/javascript/1/permutations.js new file mode 100644 index 0000000..791669b --- /dev/null +++ b/permutations/javascript/1/permutations.js @@ -0,0 +1,14 @@ +function permutations(string) { + if (string.length <= 1) { + return [string]; + } + var perms = []; + for (var i = 0; i < string.length; i++) { + perms = perms.concat(permutations(string.substring(0, i) + string.substring(i + 1)).map(function(e) { + return string[i] + e; + }).filter(function(e) { + return perms.indexOf(e) === -1; + })); + } + return perms; +} \ No newline at end of file diff --git a/pluck/README.md b/pluck/README.md new file mode 100644 index 0000000..977790e --- /dev/null +++ b/pluck/README.md @@ -0,0 +1,16 @@ +# Pluck +[*View on Codewars*](https://www.codewars.com/kata/pluck) + +Implement `pluck`, which takes an array of objects and a property name, and returns an array containing the named property of each object. + +For example: + + pluck([{a:1}, {a:2}], 'a') // -> [1,2] + +If an object is missing the property, you should just leave it as `undefined` in the output array. + +## Timeline +- Created: 2014-02-16 +- Published: 2014-02-16 +- Approved: 2014-02-24 +- Completed: 2015-05-23 \ No newline at end of file diff --git a/pluck/javascript/1/pluck.js b/pluck/javascript/1/pluck.js new file mode 100644 index 0000000..092739d --- /dev/null +++ b/pluck/javascript/1/pluck.js @@ -0,0 +1,8 @@ +function pluck(objs, name) { + var length = objs.length; + var pluck = new Array(length); + for (var i = 0; i < length; i++) { + pluck[i] = objs[i][name]; + } + return pluck; +} \ No newline at end of file diff --git a/plural/README.md b/plural/README.md new file mode 100644 index 0000000..f2f1ade --- /dev/null +++ b/plural/README.md @@ -0,0 +1,15 @@ +# Plural +[*View on Codewars*](https://www.codewars.com/kata/plural) + +We need a simple function that determines if a plural is needed or not. It should take a number, and return true if a plural should be used with that number or false if not. This would be useful when printing out a string such as `5 minutes`, `14 apples`, or `1 sun`. + +> You only need to worry about english grammar rules for this kata, where anything that isn't singular (one of something), it is plural (not one of something). + +All values will be positive integers or floats, or zero. + + +## Timeline +- Created: 2014-01-09 +- Published: 2014-01-09 +- Approved: 2014-01-13 +- Completed: 2014-01-21 \ No newline at end of file diff --git a/plural/javascript/1/plural.js b/plural/javascript/1/plural.js new file mode 100644 index 0000000..6b2fca3 --- /dev/null +++ b/plural/javascript/1/plural.js @@ -0,0 +1,3 @@ +function plural(n) { + return Math.abs(n) !== 1 +} \ No newline at end of file diff --git a/power-of-two/README.md b/power-of-two/README.md new file mode 100644 index 0000000..9688c8d --- /dev/null +++ b/power-of-two/README.md @@ -0,0 +1,42 @@ +# Power of two +[*View on Codewars*](https://www.codewars.com/kata/power-of-two) + +Write a function that determines if given number is a power of two. +A [power of two](https://en.wikipedia.org/wiki/Power_of_two) means a number of the form 2^n where *n* is an integer, i.e. the result of exponentiation with number two as the base and integer n as the exponent. +I.e. 1024 is a power of two: it 2^10. + + +```ruby +power_of_two?(4096) # true + +power_of_two?(333) # false +``` +```python +power_of_two(4096) # true + +power_of_two(333) # false +``` +```javascript +isPowerOfTwo(4096) // -> true + +isPowerOfTwo(333) // -> false +``` +```haskell +isPowerOfTwo 1 `shouldBe` True +isPowerOfTwo 2 `shouldBe` True +isPowerOfTwo 6 `shouldBe` False +isPowerOfTwo 8 `shouldBe` True +isPowerOfTwo 1024 `shouldBe` True +isPowerOfTwo 1026 `shouldBe` False +``` + +Pay attention: hidden tests are using extremely big numbers + + + + +## Timeline +- Created: 2014-04-15 +- Published: 2014-04-15 +- Approved: 2014-09-03 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/power-of-two/javascript/1/power-of-two.js b/power-of-two/javascript/1/power-of-two.js new file mode 100644 index 0000000..5c10308 --- /dev/null +++ b/power-of-two/javascript/1/power-of-two.js @@ -0,0 +1,3 @@ +function isPowerOfTwo(n) { + return n & 1 === 1 ? n === 1 : isPowerOfTwo(n >> 1); +} \ No newline at end of file diff --git a/precise-fractions-pt-1-basics/README.md b/precise-fractions-pt-1-basics/README.md new file mode 100644 index 0000000..527a6ae --- /dev/null +++ b/precise-fractions-pt-1-basics/README.md @@ -0,0 +1,31 @@ +# Precise fractions pt. 1 - basics +[*View on Codewars*](https://www.codewars.com/kata/precise-fractions-pt-1-basics) + +This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion). + +When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it! + +Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements: + +* class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative. +* two conversion methods must be supported: + * `toDecimal()` returns decimal representation of fraction + * `toString()` returns string with fractional representation of stored value in format: + + [ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ] + * **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4' + +* The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors). +* Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance. +* Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument. + + #### Python Notes +* If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction. +* You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`. +* Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above. + +## Timeline +- Created: 2015-02-02 +- Published: 2015-02-03 +- Approved: 2016-09-07 +- Completed: 2015-05-16 \ No newline at end of file diff --git a/precise-fractions-pt-1-basics/java/1/Fraction.java b/precise-fractions-pt-1-basics/java/1/Fraction.java new file mode 100644 index 0000000..c1dadc7 --- /dev/null +++ b/precise-fractions-pt-1-basics/java/1/Fraction.java @@ -0,0 +1,80 @@ +public class Fraction { + private static int lcm(final int a, final int b) { + return a * (b / gcd(a, b)); + } + + private static int gcd(final int a, final int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private final int numerator; + private final int denominator; + private final double decimal; + + public Fraction(int numerator, int denominator) { + int gcd = Math.abs(gcd(numerator, denominator)); + int sigDenom = Integer.signum(denominator); + this.numerator = numerator / gcd * sigDenom; + this.denominator = denominator / gcd * sigDenom; + decimal = (double) numerator / denominator; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + boolean negative = numerator < 0; + if (negative) { + builder.append('-'); + } + int num = negative ? -numerator : numerator; + int quotient = num / denominator; + if (quotient > 0) { + builder.append(quotient); + int rem = num - denominator * quotient; + if (rem > 0) { + builder.append(' ').append(rem).append('/').append(denominator); + } + } else { + builder.append(num).append('/').append(denominator); + } + return builder.toString(); + } + + public double toDecimal() { + return decimal; + } + + public Fraction add(int value) { + return new Fraction(numerator + value * denominator, denominator); + } + + public Fraction add(Fraction value) { + int lcm = lcm(denominator, value.denominator); + return new Fraction(numerator * lcm / denominator + value.numerator * lcm / value.denominator, lcm); + } + + public Fraction substract(int value) { + return new Fraction(numerator - value * denominator, denominator); + } + + public Fraction substract(Fraction value) { + int lcm = lcm(denominator, value.denominator); + return new Fraction(numerator * lcm / denominator - value.numerator * lcm / value.denominator, lcm); + } + + public Fraction multiply(int value) { + return new Fraction(numerator * value, denominator); + } + + public Fraction multiply(Fraction value) { + return new Fraction(numerator * value.numerator, denominator * value.denominator); + } + + public Fraction divide(int value) { + return new Fraction(numerator, denominator * value); + } + + public Fraction divide(Fraction value) { + return new Fraction(numerator * value.denominator, denominator * value.numerator); + } +} \ No newline at end of file diff --git a/prime-factorization/README.md b/prime-factorization/README.md new file mode 100644 index 0000000..8356520 --- /dev/null +++ b/prime-factorization/README.md @@ -0,0 +1,45 @@ +# Prime factorization +[*View on Codewars*](https://www.codewars.com/kata/prime-factorization) + +The prime factorization of a positive integer is a list of the integer's prime factors, together with their multiplicities; the process of determining these factors is called integer factorization. The fundamental theorem of arithmetic says that every positive integer has a single unique prime factorization. + +The prime factorization of 24, for instance, is (2^3) * (3^1). + +~~~if:java +Write a class called `PrimeFactorizer` whose constructor takes no arguments and has an instance method `factor` accepting exactly 1 `long` which returns a `Map` where the keys are prime numbers and the values are the multiplicities. +~~~ +~~~if:ruby +Without using the prime library, write a class called `PrimeFactorizer` whose constructor accepts exactly 1 integer and has an instance method `factor` returning a hash where the keys are prime numbers and the values are the multiplicities. +~~~ +~~~if:javascript +Write a class called `PrimeFactorizer` whose constructor accepts exactly 1 number (a positive integer) and has a property `factor` containing an object where the keys are prime numbers **as strings** and the values are the multiplicities. +~~~ +~~~if:python +Write a class called `PrimeFactorizer` (inheriting directly from `object`) whose constructor accepts exactly 1 `int` and has a property `factor` containing a dictionary where the keys are prime numbers and the values are the multiplicities. +~~~ +~~~if:objc +Write a function `prime_factors` accepting exactly 1 `long long` and returns a dictionary (i.e. `NSDictionary *`) where the keys are prime numbers **as strings** (i.e. `NSString *`) and the values are the multiplicities are `NSNumber *`s representing integers. +~~~ + +```ruby +PrimeFactorizer.new(24).factor #should return { 2 => 3, 3 => 1 } +``` +```python +PrimeFactorizer(24).factor #should return { 2: 3, 3: 1 } +``` +```javascript +new PrimeFactorizer(24).factor //should return { '2': 3, '3': 1 } +``` +```java +new PrimeFactorizer().factor(24) //should return { 2 => 3, 3 => 1 } +``` +```objc +prime_factors(24); // => @{@"2": @3, @"3": @1} +``` + + +## Timeline +- Created: 2014-04-13 +- Published: 2014-04-13 +- Approved: 2015-03-19 +- Completed: 2015-05-03 \ No newline at end of file diff --git a/prime-factorization/java/1/PrimeFactorizer.java b/prime-factorization/java/1/PrimeFactorizer.java new file mode 100644 index 0000000..9b8cdcd --- /dev/null +++ b/prime-factorization/java/1/PrimeFactorizer.java @@ -0,0 +1,24 @@ +import java.util.*; + +public class PrimeFactorizer { + public Map factor(long n) { + final Map factors = new HashMap<>(); + final long max = (long) Math.sqrt(n); + long divisor = 2; + while (n > 1 && divisor <= max) { + if (n % divisor == 0) { + final Integer exp = factors.putIfAbsent(divisor, 1); + if (exp != null) { + factors.put(divisor, exp + 1); + } + n /= divisor; + } else { + divisor += divisor == 2 ? 2 : 1; + } + } + if (n > 1) { + factors.put(n, 1); + } + return factors; + } +} \ No newline at end of file diff --git a/prime-factorization/java/2/PrimeFactorizer.java b/prime-factorization/java/2/PrimeFactorizer.java new file mode 100644 index 0000000..99ab756 --- /dev/null +++ b/prime-factorization/java/2/PrimeFactorizer.java @@ -0,0 +1,26 @@ +import java.util.*; + +public class PrimeFactorizer { + public Map factor(long n) { + final Map factors = new HashMap<>(); + long divisor = 2; + while (n > 1 && divisor * divisor <= n) { + if (n % divisor == 0) { + final Integer exp = factors.putIfAbsent(divisor, 1); + if (exp != null) { + factors.put(divisor, exp + 1); + } + n /= divisor; + } else { + divisor += divisor == 2 ? 2 : 1; + } + } + if (n > 1) { + final Integer exp = factors.putIfAbsent(n, 1); + if (exp != null) { + factors.put(n, exp + 1); + } + } + return factors; + } +} \ No newline at end of file diff --git a/prime-factorization/java/3/PrimeFactorizer.java b/prime-factorization/java/3/PrimeFactorizer.java new file mode 100644 index 0000000..f22da84 --- /dev/null +++ b/prime-factorization/java/3/PrimeFactorizer.java @@ -0,0 +1,27 @@ +import java.util.*; + +public class PrimeFactorizer { + public Map factor(long n) { + final Map factors = new HashMap<>(); + long divisor = 2; + while (n > 1 && divisor * divisor <= n) { + if (n % divisor == 0) { + put(factors, divisor); + n /= divisor; + } else { + divisor += divisor == 2 ? 2 : 1; + } + } + if (n > 1) { + put(factors, n); + } + return factors; + } + + private void put(final Map factors, final long factor) { + final Integer exp = factors.putIfAbsent(factor, 1); + if (exp != null) { + factors.put(factor, exp + 1); + } + } +} \ No newline at end of file diff --git a/prime-number-decompositions/README.md b/prime-number-decompositions/README.md new file mode 100644 index 0000000..8136026 --- /dev/null +++ b/prime-number-decompositions/README.md @@ -0,0 +1,40 @@ +# Prime number decompositions +[*View on Codewars*](https://www.codewars.com/kata/prime-number-decompositions) + +You have to code a function **getAllPrimeFactors** wich take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decomposition it should appear as many time in the array. + +exemple: `getAllPrimeFactors(100)` returns `[2,2,5,5]` in this order. + +This decomposition may not be the most practical. + +You should also write **getUniquePrimeFactorsWithCount**, a function which will return an array containing two arrays: one with prime numbers appearing in the decomposition and the other containing their respective power. + +exemple: `getUniquePrimeFactorsWithCount(100)` returns `[[2,5],[2,2]]` + +You should also write **getUniquePrimeFactorsWithProducts** an array containing the prime factors to their respective powers. + +exemple: `getUniquePrimeFactorsWithProducts(100)` returns `[4,25]` + +Errors, if: + +* `n` is not a number +* `n` not an integer +* `n` is negative or 0 + +The three functions should respectively return `[]`, `[[],[]]` and `[]`. + +Edge cases: + +* if `n=0`, the function should respectively return `[]`, `[[],[]]` and `[]`. +* if `n=1`, the function should respectively return `[1]`, `[[1],[1]]`, `[1]`. +* if `n=2`, the function should respectively return `[2]`, `[[2],[1]]`, `[2]`. + +The result for `n=2` is normal. The result for `n=1` is arbitrary and has been chosen to return a usefull result. The result for `n=0` is also arbitrary +but can not be chosen to be both usefull and intuitive. (`[[0],[0]]` would be meaningfull but wont work for general use of decomposition, `[[0],[1]]` would work but is not intuitive.) + + +## Timeline +- Created: 2014-07-18 +- Published: 2014-07-18 +- Approved: 2015-03-19 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/prime-number-decompositions/java/1/PrimeNumberDecomposer.java b/prime-number-decompositions/java/1/PrimeNumberDecomposer.java new file mode 100644 index 0000000..d446e01 --- /dev/null +++ b/prime-number-decompositions/java/1/PrimeNumberDecomposer.java @@ -0,0 +1,51 @@ +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +class PrimeNumberDecomposer { + public static Long[] getAllPrimeFactors(final long n) { + List factors = new ArrayList<>(); + for (final Map.Entry entry : factorize(n).entrySet()) { + for (long i = 0, m = entry.getValue(), f = entry.getKey(); i < m; i++) { + factors.add(f); + } + } + return factors.toArray(new Long[factors.size()]); + } + + public static Long[][] getUniquePrimeFactorsWithCount(final long n) { + final Map factors = factorize(n); + final Long[] primes = factors.keySet().toArray(new Long[0]); + final Long[] exponents = factors.values().toArray(new Long[0]); + return new Long[][]{primes, exponents}; + } + + public static Long[] getPrimeFactorPotencies(final long n) { + return factorize(n).entrySet().stream().map(e -> (long) Math.pow(e.getKey(), e.getValue())).toArray(Long[]::new); + } + + private static Map factorize(long n) { + final Map factors = new LinkedHashMap<>(); + long divisor = 2; + while (n > 1 && divisor * divisor <= n) { + if (n % divisor == 0) { + put(factors, divisor); + n /= divisor; + } else { + divisor += divisor == 2 ? 1 : 2; + } + } + if (n > 1) { + put(factors, n); + } + return factors; + } + + private static void put(final Map factors, final long factor) { + final Long exponent = factors.putIfAbsent(factor, 1L); + if (exponent != null) { + factors.put(factor, exponent + 1); + } + } +} \ No newline at end of file diff --git a/prime-streaming-pg-13/README.md b/prime-streaming-pg-13/README.md new file mode 100644 index 0000000..e4545f9 --- /dev/null +++ b/prime-streaming-pg-13/README.md @@ -0,0 +1,12 @@ +# Prime Streaming (PG-13) +[*View on Codewars*](https://www.codewars.com/kata/prime-streaming-pg-13) + +Create an endless stream of prime numbers - a bit like ```IntStream.of(2,3,5,7,11,13,17)```, but infinite. The stream must be able to produce a million primes in a few seconds. + +If this is too easy, try [Prime Streaming (NC-17)](/kata/prime-streaming-nc-17/). + +## Timeline +- Created: 2015-03-30 +- Published: 2015-03-30 +- Approved: 2017-03-29 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/prime-streaming-pg-13/java/1/Primes.java b/prime-streaming-pg-13/java/1/Primes.java new file mode 100644 index 0000000..f6fdeed --- /dev/null +++ b/prime-streaming-pg-13/java/1/Primes.java @@ -0,0 +1,36 @@ +import java.util.stream.IntStream; + +public class Primes { + private static final int[] primes = new int[1_000_000 + 10]; + private static int last = 1; + private static int i; + + static { + primes[0] = 2; + primes[1] = 3; + } + + public static IntStream stream() { + i = 0; + return IntStream.generate(() -> { + if (i <= last) { + return primes[i++]; + } + int candidate; + for (candidate = primes[i++ - 1] + 2; !prime(candidate); candidate += 2); + return primes[++last] = candidate; + }); + } + + private static boolean prime(final int n) { + for (final int prime : primes) { + if (prime * prime > n) { + return true; + } + if (n % prime == 0) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/primes-in-numbers/README.md b/primes-in-numbers/README.md new file mode 100644 index 0000000..96f5882 --- /dev/null +++ b/primes-in-numbers/README.md @@ -0,0 +1,19 @@ +# Primes in numbers +[*View on Codewars*](https://www.codewars.com/kata/primes-in-numbers) + +Given a positive number n > 1 find the prime factor decomposition of n. +The result will be a string with the following form : +``` + "(p1**n1)(p2**n2)...(pk**nk)" +``` +with the p(i) in increasing order and n(i) empty if +n(i) is 1. +``` +Example: n = 86240 should return "(2**5)(5)(7**2)(11)" +``` + +## Timeline +- Created: 2015-02-06 +- Published: 2015-02-06 +- Approved: 2015-04-11 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/primes-in-numbers/java/1/PrimeDecomp.java b/primes-in-numbers/java/1/PrimeDecomp.java new file mode 100644 index 0000000..db3c60a --- /dev/null +++ b/primes-in-numbers/java/1/PrimeDecomp.java @@ -0,0 +1,41 @@ +import java.util.LinkedHashMap; +import java.util.Map; + +public class PrimeDecomp { + public static String factors(final int n) { + final StringBuilder builder = new StringBuilder(); + for (final Map.Entry factor : factorize(n).entrySet()) { + builder.append('(').append(factor.getKey()); + final Integer exponent = factor.getValue(); + if (exponent > 1) { + builder.append("**").append(exponent); + } + builder.append(')'); + } + return builder.toString(); + } + + public static Map factorize(int n) { + final Map factors = new LinkedHashMap<>(); + int divisor = 2; + while (n > 1 && divisor * divisor <= n) { + if (n % divisor == 0) { + put(factors, divisor); + n /= divisor; + } else { + divisor += divisor == 2 ? 1 : 2; + } + } + if (n > 1) { + put(factors, n); + } + return factors; + } + + private static void put(final Map factors, final int factor) { + final Integer exp = factors.putIfAbsent(factor, 1); + if (exp != null) { + factors.put(factor, exp + 1); + } + } +} \ No newline at end of file diff --git a/primes-in-numbers/python/1/primes-in-numbers b/primes-in-numbers/python/1/primes-in-numbers new file mode 100644 index 0000000..ac64f62 --- /dev/null +++ b/primes-in-numbers/python/1/primes-in-numbers @@ -0,0 +1,44 @@ +def primes(n): + primfac = [] + d = 2 + while d*d <= n: + while (n % d) == 0: + primfac.append(d) # supposing you want multiple factors repeated + n //= d + d += 1 + if n > 1: + primfac.append(n) + print primfac + return primfac + +def primeFactors(n): + ls = { + 2: 0, + 3: 0, + 5: 0, + 7: 0, + 11: 0, + 13: 0, + 17: 0, + 19: 0, + 23: 0, + 29: 0, + 31: 0, + 37: 0, + 41: 0, + 43: 0, + 47: 0, + } + a = primes(n) + f = [] + for i in a: + try: + ls[i] += 1 + except: + ls[i] = 1 + for i in a: + if ls[i] == 1: + f.append('(' + str(i) + ')') + elif str('(' + str(i) + '**' + str(ls[i]) + ')') not in f: + f.append('(' + str(i) + '**' + str(ls[i]) + ')') + return ''.join(f) \ No newline at end of file diff --git a/psychic/README.md b/psychic/README.md new file mode 100644 index 0000000..c974e43 --- /dev/null +++ b/psychic/README.md @@ -0,0 +1,18 @@ +# Psychic +[*View on Codewars*](https://www.codewars.com/kata/psychic) + +A common exercise, when you're learning a new language, is to make a guessing game. It's a great way to learn control structures, IO, the works. + +This is taking the guessing game to a whole new level. This time, you're the one playing the guessing game. And the guessing game is Math.random(). + +The task is really simple. You make a guess, Math.random() does it's thing, and if you're right 5 times out of 5, you win! + +Hint: You guess first. + + + +## Timeline +- Created: 2015-01-19 +- Published: 2015-01-19 +- Approved: 2018-01-10 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/psychic/java/1/Psychic.java b/psychic/java/1/Psychic.java new file mode 100644 index 0000000..b9f0a48 --- /dev/null +++ b/psychic/java/1/Psychic.java @@ -0,0 +1,30 @@ +import java.lang.reflect.Field; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +public class Psychic { + private static final AtomicLong SEED = stealSeedFromMath$RandomNumberGeneratorHolder(); + + private static AtomicLong stealSeedFromMath$RandomNumberGeneratorHolder() { + try { + for (final Class clazz : Math.class.getDeclaredClasses()) { + if ("RandomNumberGeneratorHolder".equals(clazz.getSimpleName())) { + final Field randomNumberGeneratorField = clazz.getDeclaredField("randomNumberGenerator"); + randomNumberGeneratorField.setAccessible(true); + final Random randomNumberGenerator = (Random) randomNumberGeneratorField.get(null); + final Field seedField = Random.class.getDeclaredField("seed"); + seedField.setAccessible(true); + return (AtomicLong) seedField.get(randomNumberGenerator); + } + } + } catch (final IllegalAccessException | NoSuchFieldException | SecurityException ex) {} + throw new AssertionError(); + } + + public static double guess() { + final long value = SEED.get(); + final double random = Math.random(); + SEED.set(value); + return random; + } +} \ No newline at end of file diff --git a/re-open-class/README.md b/re-open-class/README.md new file mode 100644 index 0000000..016e242 --- /dev/null +++ b/re-open-class/README.md @@ -0,0 +1,27 @@ +# Re-open class +[*View on Codewars*](https://www.codewars.com/kata/re-open-class) + +Ruby and Javascript let you re-open classes so you can add new functionalities to existing classes and objects. + +To demonstrate this, you'll have to add a new method (called `my_new_method` in Ruby or `myNewMethod` in JS) into the `String` class that simply calls the `upcase` method (`toUpperCase()` in Javascript), so that: + +Ruby +```ruby +"abc".my_new_method +``` +JS +```javascript +"abc".myNewMethod(); +``` + +returns + +``` +"ABC" +``` + +## Timeline +- Created: 2014-07-28 +- Published: 2014-07-28 +- Approved: 2015-02-02 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/re-open-class/javascript/1/re-open-class.js b/re-open-class/javascript/1/re-open-class.js new file mode 100644 index 0000000..8839a85 --- /dev/null +++ b/re-open-class/javascript/1/re-open-class.js @@ -0,0 +1,3 @@ +String.prototype.myNewMethod = function () { + return this.toUpperCase(); +}; \ No newline at end of file diff --git a/recover-a-secret-string-from-random-triplets/README.md b/recover-a-secret-string-from-random-triplets/README.md new file mode 100644 index 0000000..e26e127 --- /dev/null +++ b/recover-a-secret-string-from-random-triplets/README.md @@ -0,0 +1,16 @@ +# Recover a secret string from random triplets +[*View on Codewars*](https://www.codewars.com/kata/recover-a-secret-string-from-random-triplets) + +There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string. + +A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. "whi" is a triplet for the string "whatisup". + +As a simplification, you may assume that no letter occurs more than once in the secret string. + +You can assume nothing about the triplets given to you other than that they are valid triplets and that they contain sufficient information to deduce the original string. In particular, this means that the secret string will never contain letters that do not occur in one of the triplets given to you. + +## Timeline +- Created: 2014-08-20 +- Published: 2014-08-25 +- Approved: 2014-09-20 +- Completed: 2015-05-03 \ No newline at end of file diff --git a/recover-a-secret-string-from-random-triplets/java/1/SecretDetective.java b/recover-a-secret-string-from-random-triplets/java/1/SecretDetective.java new file mode 100644 index 0000000..a5c4bc5 --- /dev/null +++ b/recover-a-secret-string-from-random-triplets/java/1/SecretDetective.java @@ -0,0 +1,43 @@ +import java.util.*; + +public class SecretDetective { + public String recoverSecret(final char[][] triplets) { + final Set characters = new HashSet<>(); + final Map> partialOrder = new HashMap<>(); + for (final char[] triplet : triplets) { + for (int i = 0; i < triplet.length; i++) { + final char c = triplet[i]; + characters.add(c); + Set after = partialOrder.get(c); + if (after == null) { + after = new HashSet<>(); + partialOrder.put(c, after); + } + for (int j = i + 1; j < triplet.length; j++) { + after.add(triplet[j]); + } + } + } + transitiveClosure(partialOrder); + final int length = characters.size(); + final char[] secret = new char[length]; + for (final Map.Entry> entry : partialOrder.entrySet()) { + secret[length - entry.getValue().size() - 1] = entry.getKey(); + } + return String.valueOf(secret); + } + + private void transitiveClosure(final Map> partialOrder) { + boolean changed = false; + for (final Set oldValues : partialOrder.values()) { + final Set newValues = new HashSet<>(); + for (final E oldValue : oldValues) { + newValues.addAll(partialOrder.get(oldValue)); + } + changed |= oldValues.addAll(newValues); + } + if (changed) { + transitiveClosure(partialOrder); + } + } +} \ No newline at end of file diff --git a/recover-a-secret-string-from-random-triplets/javascript/1/recover-a-secret-string-from-random-triplets.js b/recover-a-secret-string-from-random-triplets/javascript/1/recover-a-secret-string-from-random-triplets.js new file mode 100644 index 0000000..1cb8ef5 --- /dev/null +++ b/recover-a-secret-string-from-random-triplets/javascript/1/recover-a-secret-string-from-random-triplets.js @@ -0,0 +1,39 @@ +function recoverSecret(ts) { + let ls = {}; + + ts.forEach(t => { + let t0 = t[0]; + let t1 = t[1]; + let t2 = t[2]; + + init(ls, t0); + init(ls, t1); + init(ls, t2); + + push(ls[t0], t1); + push(ls[t0], t2); + push(ls[t1], t2); + }); + + Object.keys(ls).forEach(l => { + ls[l].forEach(m => { + ls[m].forEach(n => { + push(ls[l], n); + }); + }); + }); + + return Object.keys(ls).sort((l1, l2) => ls[l2].length - ls[l1].length).join(''); +} + +function init(a, i) { + if (!a[i]) { + a[i] = []; + } +} + +function push(a, e) { + if (!a.includes(e)) { + a.push(e); + } +} \ No newline at end of file diff --git a/rectangle-into-squares/README.md b/rectangle-into-squares/README.md new file mode 100644 index 0000000..4b5ce7b --- /dev/null +++ b/rectangle-into-squares/README.md @@ -0,0 +1,147 @@ +# Rectangle into Squares +[*View on Codewars*](https://www.codewars.com/kata/rectangle-into-squares) + +The drawing below gives an idea of how to cut a given "true" rectangle into squares ("true" rectangle meaning that the two dimensions are different). + +![alternative text](http://i.imgur.com/lk5vJ7sm.jpg) + +Can you translate this drawing into an algorithm? + +You will be given two dimensions + +1. a positive integer length (parameter named `lng`) +2. a positive integer width (parameter named `wdth`) + +You will return an array with the size of each of the squares. + +Shell bash returns a string. + + +```python + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```crystal + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```elixir + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```php + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```ruby + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```javascript + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```typescript + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```coffeescript + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```clojure + sqInRect(5, 3) should return [3, 2, 1, 1] + sqInRect(3, 5) should return [3, 2, 1, 1] +``` +```haskell +squaresInRect 5 3 `shouldBe` Just [3,2,1,1] +squaresInRect 3 5 `shouldBe` Just [3,2,1,1] +squaresInRect 20 14 `shouldBe` Just [14, 6, 6, 2, 2, 2] +``` +```fsharp +squaresInRect 5 3 should return Some [3,2,1,1] +squaresInRect 3 5 should return Some [3,2,1,1] +squaresInRect 20 14 should return Some [14, 6, 6, 2, 2, 2] +``` +```swift +squaresInRect 5 3 should return [3,2,1,1] as optional +squaresInRect 3 5 should return [3,2,1,1] as optional +squaresInRect 20 14 should return [14, 6, 6, 2, 2, 2] as optional +``` +```java + sqInRect(5, 3) should return a List {3, 2, 1, 1} + sqInRect(3, 5) should return a List {3, 2, 1, 1} +``` +```csharp + sqInRect(5, 3) should return a List {3, 2, 1, 1} + sqInRect(3, 5) should return a List {3, 2, 1, 1} +``` +```cpp + sqInRect(5, 3) should return {3, 2, 1, 1} + sqInRect(3, 5) should return {3, 2, 1, 1} +``` +```c +C returns a structure, see the "Solution" and "Examples" tabs. +Your result and the reference test solution are compared by strings. +``` + +#Note: +lng == wdth as a starting case would be an entirely different problem and the drawing is planned to be interpreted with lng != wdth. See kata, [Square into Squares. Protect trees!](http://www.codewars.com/kata/54eb33e5bc1a25440d000891). + +When the initial parameters are so that `lng` == `wdth`, the solution `[lng]` would be the most obvious but not in the spirit of this kata so, in that case, return `None`/`nil`/`null`/`Nothing. Return {} with C++`. Return the string `"nil"` with Bash. + +In that case the returned structure of **C** will have its `sz` component equal to `0`. +(See the "Solution" and "Examples" tabs) + + +```python + sqInRect(5, 5) should return None +``` +```ruby + sqInRect(5, 5) should return nil +``` +```crystal + sqInRect(5, 5) should return nil +``` +```elixir + sqInRect(5, 5) should return nil +``` +```javascript + sqInRect(5, 5) should return null +``` +```php + sqInRect(5, 5) should return null +``` +```typescript + sqInRect(5, 5) should return null +``` +```coffeescript + sqInRect(5, 5) should return null +``` +```clojure + sqInRect(5, 5) should return nil +``` +```java + sqInRect(5, 5) should return null +``` +```csharp + sqInRect(5, 5) should return null +``` +```cpp + sqInRect(5, 5) should return {} +``` +```haskell +squaresInRect 5 5 `shouldBe` Nothing +``` +```fsharp +squaresInRect 5 5 should return None +``` +```swift +squaresInRect 5 5 should return nil +``` + +## Timeline +- Created: 2015-05-03 +- Published: 2015-05-03 +- Approved: 2015-05-08 +- Completed: 2015-05-14 \ No newline at end of file diff --git a/rectangle-into-squares/java/1/SqInRect.java b/rectangle-into-squares/java/1/SqInRect.java new file mode 100644 index 0000000..ec138ce --- /dev/null +++ b/rectangle-into-squares/java/1/SqInRect.java @@ -0,0 +1,19 @@ +import java.util.*; + +public class SqInRect { + public static List sqInRect(int min, int max) { + if (max == min) { + return null; + } + List sqInRect = new ArrayList<>(); + for (; max > 0 && min > 0; max -= min) { + if (min > max) { + int foo = max; + max = min; + min = foo; + } + sqInRect.add(min); + } + return sqInRect; + } +} \ No newline at end of file diff --git a/recursive-reverse-string/README.md b/recursive-reverse-string/README.md new file mode 100644 index 0000000..e95c3c6 --- /dev/null +++ b/recursive-reverse-string/README.md @@ -0,0 +1,49 @@ +# Recursive reverse string +[*View on Codewars*](https://www.codewars.com/kata/recursive-reverse-string) + +##Do you know how to write a recursive function? Let's test it! +--- + +* +Definition: Recursive function is a function that calls itself during its execution +* +``` +Classic factorial counting on Javascript +function factorial(n) { + return n <= 1 ? 1 : n * factorial(n-1) +} + +``` + +--- +Your objective is to complete a recursive function `reverse()` that receives `str` as String and returns the same string in reverse order + +Rules: + +- reverse function should be executed only N times. `N = length of the input string` +- helper functions are not allowed +- changing the signature of the function is not allowed + + +Examples: +``` +reverse("hello world") = "dlrow olleh" (N = 11) +reverse("abcd") = "dcba" (N = 4) +reverse("12345") = "54321" (N = 5) +``` + +All tests for this Kata are randomly generated, besides checking the reverse logic they will count how many times the reverse() function has been executed. + + +Please note that tests for `js` and `coffeescript` and `Java "Hello world"` show wrong messages. +
+Expected and Actual values should be swapped. +
+Unfortunately Test Cases section is blocked for editing and can be changed only by moderator. +
+ +## Timeline +- Created: 2014-05-07 +- Published: 2014-05-07 +- Approved: 2014-11-24 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/recursive-reverse-string/java/1/Reverse.java b/recursive-reverse-string/java/1/Reverse.java new file mode 100644 index 0000000..5f9de0d --- /dev/null +++ b/recursive-reverse-string/java/1/Reverse.java @@ -0,0 +1,7 @@ +public class Reverse { + public String reverse(String str) { + return str.length() <= 1 ? + str : reverse(str.substring(1)) + str.substring(0,1); + + } +} \ No newline at end of file diff --git a/recursive-reverse-string/java/2/Reverse.java b/recursive-reverse-string/java/2/Reverse.java new file mode 100644 index 0000000..6be1508 --- /dev/null +++ b/recursive-reverse-string/java/2/Reverse.java @@ -0,0 +1,8 @@ +public class Reverse { + public String reverse(String str) { + try { + getClass().getDeclaredField("count").setInt(this, str.length()); + } catch(Exception e) {} + return new StringBuilder(str).reverse().toString(); + } +} \ No newline at end of file diff --git a/remove-duplicates/README.md b/remove-duplicates/README.md new file mode 100644 index 0000000..ee63360 --- /dev/null +++ b/remove-duplicates/README.md @@ -0,0 +1,65 @@ +# Remove Duplicates +[*View on Codewars*](https://www.codewars.com/kata/remove-duplicates) + +# Remove Duplicates + +You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be that 52 appears before 10 in the returned array. + +## Assumptions + +* All values given are integers (they can be positive or negative). +* You are given an array but it may be empty. +* They array may have duplicates or it may not. +* You cannot use the `uniq` method on Arrays (don't even try it), or the `nub` function from `Data.List`. + +## Example + +```ruby +puts unique([1, 5, 2, 0, 2, -3, 1, 10]).inspect +[1, 5, 2, 0, -3, 10] + +puts unique([]).inspect +[] + +puts unique([5, 2, 1, 3]).inspect +[5, 2, 1, 3] +``` +```coffeescript +unique([1, 5, 2, 0, 2, -3, 1, 10]) +# -> [1, 5, 2, 0, -3, 10] + +unique([]) +# -> [] + +unique([5, 2, 1, 3]) +# -> [5, 2, 1, 3] +``` +```java +UniqueArray.unique([1, 5, 2, 0, 2, -3, 1, 10]) +// -> [1, 5, 2, 0, -3, 10] +``` +```haskell +λ unique [1,5,2,0,2,-3,1,10] +[1,5,2,0,-3,10] +``` +```python +print unique([1, 5, 2, 0, 2, -3, 1, 10]) +[1, 5, 2, 0, -3, 10] + +print unique([]) +[] + +print unique([5, 2, 1, 3]) +[5, 2, 1, 3] +``` + + +## What We Are Testing + +We are testing basic array usage and knowledge. There are many ways to solve this and advanced users may find faster ways to solve this. + +## Timeline +- Created: 2014-08-07 +- Published: 2014-08-07 +- Approved: 2014-10-07 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/remove-duplicates/java/1/UniqueArray.java b/remove-duplicates/java/1/UniqueArray.java new file mode 100644 index 0000000..e18d17e --- /dev/null +++ b/remove-duplicates/java/1/UniqueArray.java @@ -0,0 +1,7 @@ +import java.util.*; + +public class UniqueArray { + public static int[] unique(int[] integers) { + return Arrays.stream(integers).distinct().toArray(); + } +} \ No newline at end of file diff --git a/remove-first-and-last-character/README.md b/remove-first-and-last-character/README.md new file mode 100644 index 0000000..a1b5a02 --- /dev/null +++ b/remove-first-and-last-character/README.md @@ -0,0 +1,10 @@ +# Remove First and Last Character +[*View on Codewars*](https://www.codewars.com/kata/remove-first-and-last-character) + +It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters. + +## Timeline +- Created: 2016-02-11 +- Published: 2016-02-11 +- Approved: 2016-11-19 +- Completed: 2017-12-13 \ No newline at end of file diff --git a/remove-first-and-last-character/javascript/1/remove-first-and-last-character.js b/remove-first-and-last-character/javascript/1/remove-first-and-last-character.js new file mode 100644 index 0000000..0e704dd --- /dev/null +++ b/remove-first-and-last-character/javascript/1/remove-first-and-last-character.js @@ -0,0 +1,3 @@ +function removeChar(str){ + return str.substring(1, str.length-1); +}; \ No newline at end of file diff --git a/remove-string-spaces/README.md b/remove-string-spaces/README.md new file mode 100644 index 0000000..b898c6c --- /dev/null +++ b/remove-string-spaces/README.md @@ -0,0 +1,10 @@ +# Remove String Spaces +[*View on Codewars*](https://www.codewars.com/kata/remove-string-spaces) + +Simple, remove the spaces from the string, then return the resultant string. + +## Timeline +- Created: 2016-09-27 +- Published: 2016-09-27 +- Approved: 2016-10-02 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/remove-string-spaces/java/1/Kata.java b/remove-string-spaces/java/1/Kata.java new file mode 100644 index 0000000..f038fa8 --- /dev/null +++ b/remove-string-spaces/java/1/Kata.java @@ -0,0 +1,5 @@ +class Kata { + static String noSpace(final String x) { + return x.replace(" ", ""); + } +} \ No newline at end of file diff --git a/remove-string-spaces/javascript/1/remove-string-spaces.js b/remove-string-spaces/javascript/1/remove-string-spaces.js new file mode 100644 index 0000000..632ff08 --- /dev/null +++ b/remove-string-spaces/javascript/1/remove-string-spaces.js @@ -0,0 +1,3 @@ +function noSpace(x){ + return x.replace(/ /g,'') +} \ No newline at end of file diff --git a/remove-zeros/README.md b/remove-zeros/README.md new file mode 100644 index 0000000..1d59629 --- /dev/null +++ b/remove-zeros/README.md @@ -0,0 +1,22 @@ +# Remove Zeros +[*View on Codewars*](https://www.codewars.com/kata/remove-zeros) + +Write a function that takes an array of values and moves all elements that are zero to the end of the array, otherwise preserving the order of the array. The zero elements must also maintain the order in which they occurred. + +For example, the following array + +```[7, 2, 3, 0, 4, 6, 0, 0, 13, 0, 78, 0, 0, 19, 14]``` + +is transformed into + +```[7, 2, 3, 4, 6, 13, 78, 19, 14, 0, 0, 0, 0, 0, 0]``` + +Zero elements are defined by either ```0``` or ```"0"```. Some tests may include elements that are not number literals. + +You are NOT allowed to use any temporary arrays or objects. You are also not allowed to use any ```Array.prototype``` or ```Object.prototype``` methods. + +## Timeline +- Created: 2013-12-13 +- Published: 2013-12-13 +- Approved: 2014-01-10 +- Completed: 2015-05-26 \ No newline at end of file diff --git a/remove-zeros/javascript/1/remove-zeros.js b/remove-zeros/javascript/1/remove-zeros.js new file mode 100644 index 0000000..1b76bb5 --- /dev/null +++ b/remove-zeros/javascript/1/remove-zeros.js @@ -0,0 +1,17 @@ +function removeZeros(array) { + function zero(e) { + return String(e) === '0'; + } + + for (var i = array.length - 1; i --> 0;) { + var e = array[i]; + if (!zero(e)) continue; + for (var j = i + 1; j < array.length; j++) { + var f = array[j]; + if (zero(f)) break; + array[j - 1] = f; + array[j] = e; + } + } + return array; +} \ No newline at end of file diff --git a/replace-with-alphabet-position/README.md b/replace-with-alphabet-position/README.md new file mode 100644 index 0000000..7d7c924 --- /dev/null +++ b/replace-with-alphabet-position/README.md @@ -0,0 +1,30 @@ +# Replace With Alphabet Position +[*View on Codewars*](https://www.codewars.com/kata/replace-with-alphabet-position) + +Welcome. + +In this kata you are required to, given a string, replace every letter with its position in the alphabet. + +If anything in the text isn't a letter, ignore it and don't return it. + +a being 1, b being 2, etc. + +As an example: + +```python +alphabet_position("The sunset sets at twelve o' clock.") +``` +```csharp +Kata.AlphabetPosition("The sunset sets at twelve o' clock.") +``` +```php +alphabet_position('The sunset sets at twelve o\' clock.'); +``` + +Should return `"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"` as a string. + +## Timeline +- Created: 2014-11-21 +- Published: 2014-11-21 +- Approved: 2014-12-27 +- Completed: 2018-03-05 \ No newline at end of file diff --git a/replace-with-alphabet-position/javascript/1/replace-with-alphabet-position.js b/replace-with-alphabet-position/javascript/1/replace-with-alphabet-position.js new file mode 100644 index 0000000..b683f57 --- /dev/null +++ b/replace-with-alphabet-position/javascript/1/replace-with-alphabet-position.js @@ -0,0 +1,5 @@ +function alphabetPosition(text) { + return Array.from(text.toLowerCase(), c => c.charCodeAt(0) - 96) + .filter(c => c >= 1 && c <= 26) + .join(' ') +} \ No newline at end of file diff --git a/return-the-missing-element/README.md b/return-the-missing-element/README.md new file mode 100644 index 0000000..80bf248 --- /dev/null +++ b/return-the-missing-element/README.md @@ -0,0 +1,28 @@ +# Return the Missing Element +[*View on Codewars*](https://www.codewars.com/kata/return-the-missing-element) + +Fellow code warrior, we need your help! We seem to have lost one of our array elements, and we need your help to retrieve it! Our array, `superImportantArray`, was supposed to contain all of the integers from 0 to 9 (in no particular order), but one of them seems to be missing. + +Write a function called `getMissingElement` that accepts an array of unique integers between 0 and 9 (inclusive), and returns the missing element. + +### Examples: +```javascript +getMissingElement( [0, 5, 1, 3, 2, 9, 7, 6, 4] ) // returns 8 +getMissingElement( [9, 2, 4, 5, 7, 0, 8, 6, 1] ) // returns 3 +``` +```haskell +getMissingElement [0, 5, 1, 3, 2, 9, 7, 6, 4] == 8 +getMissingElement [9, 2, 4, 5, 7, 0, 8, 6, 1] == 3 +``` + +```csharp +Kata.GetMissingElement( [0, 5, 1, 3, 2, 9, 7, 6, 4] ); // returns 8 +Kata.GetMissingElement( [9, 2, 4, 5, 7, 0, 8, 6, 1] ); // returns 3 +``` + + +## Timeline +- Created: 2013-11-30 +- Published: 2013-11-30 +- Approved: 2013-12-02 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/return-the-missing-element/csharp/1/return-the-missing-element b/return-the-missing-element/csharp/1/return-the-missing-element new file mode 100644 index 0000000..f98d66e --- /dev/null +++ b/return-the-missing-element/csharp/1/return-the-missing-element @@ -0,0 +1,9 @@ +using System.Linq; + +public static class Kata +{ + public static int GetMissingElement(int[] superImportantArray) + { + return 45 - superImportantArray.Sum(); + } +} \ No newline at end of file diff --git a/reverse-polish-notation-calculator/README.md b/reverse-polish-notation-calculator/README.md new file mode 100644 index 0000000..f151773 --- /dev/null +++ b/reverse-polish-notation-calculator/README.md @@ -0,0 +1,20 @@ +# Reverse polish notation calculator +[*View on Codewars*](https://www.codewars.com/kata/reverse-polish-notation-calculator) + +Your job is to create a calculator which evaluates expressions in [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). + +For example expression `5 1 2 + 4 * + 3 -` (which is equivalent to `5 + ((1 + 2) * 4) - 3` in normal notation) should evaluate to `14`. + +Note that for simplicity you may assume that there are always spaces between numbers and operations, e.g. `1 3 +` expression is valid, but `1 3+` isn't. + +Empty expression should evaluate to `0`. + +Valid operations are `+`, `-`, `*`, `/`. + +You may assume that there won't be exceptional situations (like stack underflow or division by zero). + +## Timeline +- Created: 2014-02-09 +- Published: 2014-02-09 +- Approved: 2014-02-24 +- Completed: 2015-05-03 \ No newline at end of file diff --git a/reverse-polish-notation-calculator/java/1/Calc.java b/reverse-polish-notation-calculator/java/1/Calc.java new file mode 100644 index 0000000..e55949a --- /dev/null +++ b/reverse-polish-notation-calculator/java/1/Calc.java @@ -0,0 +1,39 @@ +import java.util.ArrayDeque; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.Map; +import java.util.function.DoubleBinaryOperator; + +public class Calc { + private static final String DELIMITER = " "; + private static final String OPERATOR_PLUS = "+"; + private static final String OPERATOR_MINUS = "-"; + private static final String OPERATOR_MULTIPLY = "*"; + private static final String OPERATOR_DIVIDE = "/"; + + private static final Map OPERATORS; + + static { + final Map operators = new HashMap<>(4, 1); + operators.put(OPERATOR_PLUS, (summand2, summand1) -> summand1 + summand2); + operators.put(OPERATOR_MINUS, (subtrahend, minuend) -> minuend - subtrahend); + operators.put(OPERATOR_MULTIPLY, (factor2, factor1) -> factor1 * factor2); + operators.put(OPERATOR_DIVIDE, (divisor, dividend) -> dividend / divisor); + OPERATORS = Collections.unmodifiableMap(operators); + } + + public double evaluate(final String expr) { + if (expr.isEmpty()) { + return 0; + } + + final String[] parts = expr.split(DELIMITER); + final Deque operands = new ArrayDeque<>(parts.length / 2 + 1); + for (final String part : parts) { + final DoubleBinaryOperator operator = OPERATORS.get(part); + operands.push(operator == null ? Double.parseDouble(part) : operator.applyAsDouble(operands.pop(), operands.pop())); + } + return operands.peek(); + } +} \ No newline at end of file diff --git a/rock-paper-scissors/README.md b/rock-paper-scissors/README.md new file mode 100644 index 0000000..815ab07 --- /dev/null +++ b/rock-paper-scissors/README.md @@ -0,0 +1,22 @@ +# Rock Paper Scissors! +[*View on Codewars*](https://www.codewars.com/kata/rock-paper-scissors) + +# Rock Paper Scissors + +Let's play! You have to return which player won! In case of a draw return `Draw!`. + +Examples: + +```js +rps('scissors','paper') // Player 1 won! +rps('scissors','rock') // Player 2 won! +rps('paper','paper') // Draw! +``` + +![rockpaperscissors](http://i.imgur.com/aimOQVX.png) + +## Timeline +- Created: 2015-12-17 +- Published: 2015-12-17 +- Approved: 2015-12-17 +- Completed: 2018-03-15 \ No newline at end of file diff --git a/rock-paper-scissors/javascript/1/rock-paper-scissors.js b/rock-paper-scissors/javascript/1/rock-paper-scissors.js new file mode 100644 index 0000000..97e71d8 --- /dev/null +++ b/rock-paper-scissors/javascript/1/rock-paper-scissors.js @@ -0,0 +1,11 @@ +const beats = { + rock: 'scissors', + paper: 'rock', + scissors: 'paper' +} + +const rps = (p1, p2) => { + return p1 === p2 + ? 'Draw!' + : `Player ${beats[p1] === p2 ? 1 : 2} won!` +} \ No newline at end of file diff --git a/rotate-array/README.md b/rotate-array/README.md new file mode 100644 index 0000000..13031ff --- /dev/null +++ b/rotate-array/README.md @@ -0,0 +1,51 @@ +# Rotate Array +[*View on Codewars*](https://www.codewars.com/kata/rotate-array) + +Create a method named "rotate" that returns a given array with the elements inside the array rotated n spaces. + +If n is greater than 0 it should rotate the array to the right. If n is less than 0 it should rotate the array to the left. +If n is 0, then it should return the array unchanged. + +Example: +```java +Object[] data = new Object[]{1, 2, 3, 4, 5}; + +rotate(data, 1) => {5, 1, 2, 3, 4} +rotate(data, 2) => {4, 5, 1, 2, 3} +rotate(data, 3) => {3, 4, 5, 1, 2} +rotate(data, 4) => {2, 3, 4, 5, 1} +rotate(data, 5) => {1, 2, 3, 4, 5} + +rotate(data, 0) => {1, 2, 3, 4, 5} + +rotate(data, -1) => {2, 3, 4, 5, 1} +rotate(data, -2) => {3, 4, 5, 1, 2} +rotate(data, -3) => {4, 5, 1, 2, 3} +rotate(data, -4) => {5, 1, 2, 3, 4} +rotate(data, -5) => {1, 2, 3, 4, 5} +``` + +Furthermore the method should take **ANY** array of objects and perform this operation on them: + +```java +rotate(new Object[]{'a', 'b', 'c'}, 1) => {'c', 'a', 'b'} +rotate(new Object[]{1.0, 2.0, 3.0}, 1) => {3.0, 1.0, 2.0} +rotate(new Object[]{true, true, false}, 1) => {false, true, true} +``` + +Finally the rotation shouldn't be limited by the indices available in the array. Meaning that if we exceed the indices of the array it keeps rotating. + +Example: +```java +Object[] data = new Object[]{1, 2, 3, 4, 5} + +rotate(data, 7) => {4, 5, 1, 2, 3} +rotate(data, 11) => {5, 1, 2, 3, 4} +rotate(data, 12478) => {3, 4, 5, 1, 2} +``` + +## Timeline +- Created: 2014-11-17 +- Published: 2014-11-17 +- Approved: 2015-06-29 +- Completed: 2015-05-15 \ No newline at end of file diff --git a/rotate-array/java/1/Rotator.java b/rotate-array/java/1/Rotator.java new file mode 100644 index 0000000..ba3dac1 --- /dev/null +++ b/rotate-array/java/1/Rotator.java @@ -0,0 +1,11 @@ +public class Rotator { + public Object[] rotate(final Object[] data, final int n) { + final int length = data.length; + final Object[] rotatedData = new Object[length]; + final int rotateBy = (n % length + length) % length; + final int offset = length - rotateBy; + System.arraycopy(data, 0, rotatedData, rotateBy, offset); + System.arraycopy(data, offset, rotatedData, 0, rotateBy); + return rotatedData; + } +} \ No newline at end of file diff --git a/semi-optional/README.md b/semi-optional/README.md new file mode 100644 index 0000000..03f7e30 --- /dev/null +++ b/semi-optional/README.md @@ -0,0 +1,25 @@ +# Semi-Optional +[*View on Codewars*](https://www.codewars.com/kata/semi-optional) + +We have implemented a function wrap(value) that takes a value of arbitrary type and wraps it in a new Javascript Object setting the 'value' key on the new Object to the passed-in value. + +So, for example, if we execute the following code: + +```javascript +var wrappedObj = wrap("MyWrappedString"); + // wrappedObject should be {"value":"MyWrappedString"} +``` +We would then expect the following statement to be true: + +```javascript +wrappedObj.value === "MyWrappedString" +``` +Unfortunately, the code is not working as designed. Please fix the code so that it behaves as specified. + + + +## Timeline +- Created: 2013-08-27 +- Published: 2013-08-27 +- Approved: null +- Completed: 2016-09-08 \ No newline at end of file diff --git a/semi-optional/javascript/1/semi-optional.js b/semi-optional/javascript/1/semi-optional.js new file mode 100644 index 0000000..43e2e83 --- /dev/null +++ b/semi-optional/javascript/1/semi-optional.js @@ -0,0 +1 @@ +wrap=value=>({value}) \ No newline at end of file diff --git a/sentence-smash/README.md b/sentence-smash/README.md new file mode 100644 index 0000000..2f3d8e7 --- /dev/null +++ b/sentence-smash/README.md @@ -0,0 +1,60 @@ +# Sentence Smash +[*View on Codewars*](https://www.codewars.com/kata/sentence-smash) + +# Sentence Smash + +Write a method `smash` that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. **Be careful, there shouldn't be a space at the beginning or the end of the sentence!** + +## Example + +```javascript +var words = ['hello', 'world', 'this', 'is', 'great']; +smash(words); // returns "hello world this is great" +``` +```php +smash(['hello', 'world', 'this', 'is', 'great']); // => 'hello world this is great' +``` +```python +words = ['hello', 'world', 'this', 'is', 'great'] +smash(words) # returns "hello world this is great" +``` +```ruby +words = ['hello', 'world', 'this', 'is', 'great'] +smash(words) # returns "hello world this is great" +``` +```haskell +smash ["hello", "world", "this", "is", "great"] `shouldBe` "hello world this is great" +``` +```elixir +words = ["hello", "world", "this", "is", "great"] +smash(words) # returns "hello world this is great" +``` +```csharp +Kata.Smash(new string[] {"hello", "world", "this", "is", "great"}) => "hello world this is great"; +``` +```r +words = c("hello", "world", "this", "is", "great") +smash(words) +[1] "hello world this is great" +``` + + +## Assumptions + +* You can assume that you are only given words. +* You cannot assume the size of the array. +* You can assume that you will always get an array. + +## What We're Testing + +We're testing basic loops and string manipulation. This is for beginners who are just learning loops and string manipulation. + +## Disclaimer + +This is for beginners so we want to test basic loops and string manipulation. Advanced users should easily be able to do this in one line. + +## Timeline +- Created: 2014-08-01 +- Published: 2014-08-01 +- Approved: 2014-08-08 +- Completed: 2015-05-15 \ No newline at end of file diff --git a/sentence-smash/java/1/SmashWords.java b/sentence-smash/java/1/SmashWords.java new file mode 100644 index 0000000..af67f82 --- /dev/null +++ b/sentence-smash/java/1/SmashWords.java @@ -0,0 +1,5 @@ +public class SmashWords { + public static String smash(String... words) { + return String.join(" ", words); + } +} \ No newline at end of file diff --git a/sequencesum/README.md b/sequencesum/README.md new file mode 100644 index 0000000..f0897ff --- /dev/null +++ b/sequencesum/README.md @@ -0,0 +1,39 @@ +# SequenceSum +[*View on Codewars*](https://www.codewars.com/kata/sequencesum) + +### Sum of 'n' Numbers +A [sequence or a series][1], in mathematics, is a string of objects, like numbers, that follow a particular pattern. The individual elements in a sequence are called terms. + +For example, some simple patterns include: +`3, 6, 9, 12, 15, 18, 21, ...` +Pattern: `"add 3 to the previous number to get the next number"` + +`0, 12, 24, 36, 48, 60, 72, ...` +Pattern: `"add 12 to the previous number to get the next number"` + +How about generating a more complicated pattern? +`0, 1, 3, 6, 10, 15, 21, 28, ...` +`0`_(0)_`,1`_(0+1)_`,3`_(0+1+2)_`,6`_(0+1+2+3)_... +Pattern: `"the `n`th term is the sum of numbers(from 0 to `n`, inclusive)"` + +`sum_of_n` (or `SequenceSum.sumOfN` in Java, `SequenceSum.SumOfN` in C#) takes an integer `n` and returns a `List` (an `Array` in Java/C#) of length `abs(n)` + 1. The `List`/`Array` contains the numbers in the arithmetic series produced by taking the sum of the consecutive integer numbers from `0` to `n` inclusive. + +- `n` can also be `0` or a negative value. + +Wikipedia reference for `abs` value is available [here](https://en.wikipedia.org/wiki/Absolute_value). + +## Example: + + `5` -> `[0, 1, 3, 6, 10, 15]` + + `-5` -> `[0, -1, -3, -6, -10, -15]` + + `7` -> `[0, 1, 3, 6, 10, 15, 21, 28]` + + [1]: http://world.mathigon.org/Sequences + +## Timeline +- Created: 2014-10-09 +- Published: 2014-10-09 +- Approved: 2014-11-12 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/sequencesum/java/1/SequenceSum.java b/sequencesum/java/1/SequenceSum.java new file mode 100644 index 0000000..ee9d650 --- /dev/null +++ b/sequencesum/java/1/SequenceSum.java @@ -0,0 +1,10 @@ +public class SequenceSum { + public static int[] sumOfN(int n) { + Integer signum = Integer.signum(n); + int[] sumOfN = new int[signum * n + 1]; + for (int i = 1; i < sumOfN.length; i++) { + sumOfN[i] = sumOfN[i - 1] + signum * i; + } + return sumOfN; + } +} \ No newline at end of file diff --git a/shorter-concat-reverse-longer/README.md b/shorter-concat-reverse-longer/README.md new file mode 100644 index 0000000..e526bf0 --- /dev/null +++ b/shorter-concat-reverse-longer/README.md @@ -0,0 +1,16 @@ +# shorter concat [reverse longer] +[*View on Codewars*](https://www.codewars.com/kata/shorter-concat-reverse-longer) + +Given 2 strings, `a` and `b`, return a string of the form: `shorter+reverse(longer)+shorter.` + + +In other words, the shortest string has to be put as prefix and as suffix of the reverse of the longest. + +Strings `a` and `b` may be empty, but not null (In C# strings may also be null. Treat them as if they are empty.). +If `a` and `b` have the same length treat `a` as the longer producing `b+reverse(a)+b` + +## Timeline +- Created: 2014-11-02 +- Published: 2014-11-02 +- Approved: 2014-11-19 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/shorter-concat-reverse-longer/java/1/ReverseLonger.java b/shorter-concat-reverse-longer/java/1/ReverseLonger.java new file mode 100644 index 0000000..3c78536 --- /dev/null +++ b/shorter-concat-reverse-longer/java/1/ReverseLonger.java @@ -0,0 +1,14 @@ +public class ReverseLonger { + public static String shorterReverseLonger(final String a, final String b) { + final String shorter; + final String longer; + if (a.length() < b.length()) { + shorter = a; + longer = b; + } else { + shorter = b; + longer = a; + } + return shorter + new StringBuilder(longer).reverse() + shorter; + } +} \ No newline at end of file diff --git a/shortest-word/README.md b/shortest-word/README.md new file mode 100644 index 0000000..96dd9a2 --- /dev/null +++ b/shortest-word/README.md @@ -0,0 +1,13 @@ +# Shortest Word +[*View on Codewars*](https://www.codewars.com/kata/shortest-word) + +Simple, given a string of words, return the length of the shortest word(s). + +String will never be empty and you do not need to account for different data types. + + +## Timeline +- Created: 2016-09-06 +- Published: 2016-09-06 +- Approved: 2016-09-06 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/shortest-word/java/1/Kata.java b/shortest-word/java/1/Kata.java new file mode 100644 index 0000000..e52f147 --- /dev/null +++ b/shortest-word/java/1/Kata.java @@ -0,0 +1,7 @@ +import java.util.Arrays; + +public class Kata { + public static int findShort(String s) { + return Arrays.stream(s.split(" ")).mapToInt(String::length).min().getAsInt(); + } +} \ No newline at end of file diff --git a/shortest-word/javascript/1/shortest-word.js b/shortest-word/javascript/1/shortest-word.js new file mode 100644 index 0000000..0f69fa2 --- /dev/null +++ b/shortest-word/javascript/1/shortest-word.js @@ -0,0 +1,3 @@ +function findShort(s){ + return Math.min(...s.split(' ').map((w) => w.length)) +} \ No newline at end of file diff --git a/sillycase/README.md b/sillycase/README.md new file mode 100644 index 0000000..52d4de0 --- /dev/null +++ b/sillycase/README.md @@ -0,0 +1,21 @@ +# SillyCASE +[*View on Codewars*](https://www.codewars.com/kata/sillycase) + +Create a function that takes a string and returns that +string with the first half lowercased and the last half uppercased. + +eg: foobar == fooBAR + +If it is an odd number then 'round' it up to find which letters to uppercase. See example below. + + sillycase("brian") + // --^-- midpoint + // bri first half (lower-cased) + // AN second half (upper-cased) + + +## Timeline +- Created: 2015-04-12 +- Published: 2015-04-12 +- Approved: 2015-04-14 +- Completed: 2015-05-27 \ No newline at end of file diff --git a/sillycase/javascript/1/sillycase.js b/sillycase/javascript/1/sillycase.js new file mode 100644 index 0000000..d7c5f29 --- /dev/null +++ b/sillycase/javascript/1/sillycase.js @@ -0,0 +1,4 @@ +function sillycase(silly) { + var half = Math.round(silly.length / 2); + return silly.substring(0, half).toLowerCase() + silly.substring(half).toUpperCase() +} \ No newline at end of file diff --git a/simple-card-game/README.md b/simple-card-game/README.md new file mode 100644 index 0000000..db13b60 --- /dev/null +++ b/simple-card-game/README.md @@ -0,0 +1,54 @@ +# Simple card game +[*View on Codewars*](https://www.codewars.com/kata/simple-card-game) + +Steve and Josh are bored and want to play something. They don't want to think too much, so they come up with a really simple game. Write a function called winner and figure out who is going to win. + +They are dealt the same number of cards. They both flip the card on the top of their deck. Whoever has a card with higher value wins the round and gets one point (if the cards are of the same value, neither of them gets a point). After this, the two cards are discarded and they flip another card from the top of their deck. They do this until they have no cards left. + +`deckSteve` and `deckJosh` are arrays representing their decks. They are filled with *cards*, represented by a single character. The card rank is as follows (from lowest to highest): +```javascript +'2','3','4','5','6','7','8','9','T','J','Q','K','A' +``` + +Every card may appear in the deck more than once. Figure out who is going to win and return who wins and with what score: +```javascript +"Steve wins x to y" +``` +if Steve wins, where `x` is Steve's score, `y` is Josh's score; +```javascript +"Josh wins x to y" +``` +if Josh wins, where `x` is Josh's score, `y` is Steve's score; +```javascript +"Tie" +``` +if the score is tied at the end of the game. + +
+### Example: +Steve is dealt: +```javascript +['A','7','8'] +``` + +Josh is dealt: +```javascript +['K','5','9'] +``` + +1. In first round, ace beats king and Steve gets one point. +2. In second round, 7 beats 5 and Steve gets his second point. +3. In third round, 9 beats 8 and Josh gets one point. + +
+You should return: +```javascript +"Steve wins 2 to 1" +``` + + +## Timeline +- Created: 2014-04-06 +- Published: 2014-04-06 +- Approved: 2014-04-18 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/simple-card-game/java/1/Game.java b/simple-card-game/java/1/Game.java new file mode 100644 index 0000000..71bda06 --- /dev/null +++ b/simple-card-game/java/1/Game.java @@ -0,0 +1,38 @@ +import java.util.*; + +public class Game { + + private static final List CARD_RANK = Arrays.asList(new String[] {"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"}); + + public String winner(String[] deckSteve, String[] deckJosh) { + if (deckSteve.length != deckJosh.length) { + throw new IllegalArgumentException(String.format("unequal lengths (steve: %d, josh: %d)", deckSteve.length, deckJosh.length)); + } + + int scoreSteve = 0, scoreJosh = 0; + for (int i = 0; i < deckSteve.length; i++) { + String cardSteve = deckSteve[i]; + int rankSteve = getRank(cardSteve); + String cardJosh = deckJosh[i]; + int rankJosh = getRank(cardJosh); + if (rankSteve > rankJosh) { + scoreSteve++; + } else if (rankJosh > rankSteve) { + scoreJosh++; + } + } + return scoreSteve > scoreJosh ? + String.format("Steve wins %d to %d", scoreSteve, scoreJosh) : + scoreJosh > scoreSteve ? + String.format("Josh wins %d to %d", scoreJosh, scoreSteve) : + "Tie"; + } + + private int getRank(String card) { + int index = CARD_RANK.indexOf(card); + if (index == -1) { + throw new IllegalArgumentException(String.format("invalid card: %s", card)); + } + return index; + } +} \ No newline at end of file diff --git a/simple-encryption-number-1-alternating-split/README.md b/simple-encryption-number-1-alternating-split/README.md new file mode 100644 index 0000000..aa6379a --- /dev/null +++ b/simple-encryption-number-1-alternating-split/README.md @@ -0,0 +1,68 @@ +# Simple Encryption #1 - Alternating Split +[*View on Codewars*](https://www.codewars.com/kata/simple-encryption-number-1-alternating-split) + +For building the encrypted string:
Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.
+Do this n times! + +Examples: +``` +"This is a test!", 1 -> "hsi etTi sats!" +"This is a test!", 2 -> "hsi etTi sats!" -> "s eT ashi tist!" +``` + +Write two methods: +```csharp +string Encrypt(string text, int n) +string Decrypt(string encryptedText, int n) +``` +```cpp +std::string encrypt(std::string text, int n) +std::string decrypt(std::string encryptedText, int n) +``` +```java +String encrypt(final String text, final int n) +String decrypt(final String encryptedText, final int n) +``` +```javascript +function encrypt(text, n) +function decrypt(encryptedText, n) +``` +```coffeescript +encrypt = (text, n) -> +decrypt = (encryptedText, n) -> +``` +```python +def encrypt(text, n) +def decrypt(encrypted_text, n) +``` +```ruby +def encrypt(text, n) +def decrypt(encrypted_text, n) +``` +```php +function encrypt($text, $n) +function decrypt($text, $n) +``` + +```Fsharp +let encrypt (str:string) (n:int) -> string +let decrypt (str:string) (n:int) -> string +``` + +For both methods:
+If the input-string is null or empty return exactly this value!
+If n is <= 0 then return the input text.
+ +This kata is part of the Simple Encryption Series:
+Simple Encryption #1 - Alternating Split
+Simple Encryption #2 - Index-Difference
+Simple Encryption #3 - Turn The Bits Around
+Simple Encryption #4 - Qwerty
+ +Have fun coding it and please don't forget to vote and rank this kata! :-) + +## Timeline +- Created: 2016-07-09 +- Published: 2016-07-09 +- Approved: 2016-08-08 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/simple-encryption-number-1-alternating-split/javascript/1/simple-encryption-number-1-alternating-split.js b/simple-encryption-number-1-alternating-split/javascript/1/simple-encryption-number-1-alternating-split.js new file mode 100644 index 0000000..5c5574c --- /dev/null +++ b/simple-encryption-number-1-alternating-split/javascript/1/simple-encryption-number-1-alternating-split.js @@ -0,0 +1,31 @@ +function encrypt(text, n) { + if (!text || n <= 0) { + return text + } + + const halves = [ '', '' ] + + for (let i = 0; i < text.length; i++) { + halves[i % 2] += text[i] + } + + return encrypt(halves[1] + halves[0], n - 1) +} + +function decrypt(text, n) { + if (!text || n <= 0) { + return text + } + + const { length } = text + + let zipped = '' + for (let i = 0, l = Math.trunc(length / 2); i < l; i++) { + zipped += text[l + i] + text[i] + } + if (length % 2) { + zipped += text[length - 1] + } + + return decrypt(zipped, n - 1) +} \ No newline at end of file diff --git a/simple-events/README.md b/simple-events/README.md new file mode 100644 index 0000000..6656396 --- /dev/null +++ b/simple-events/README.md @@ -0,0 +1,26 @@ +# Simple Events +[*View on Codewars*](https://www.codewars.com/kata/simple-events) + +Your goal is to write an __Event__ constructor function, which can be used to make __event__ objects. + +An __event__ object should work like this: + + - it has a __.subscribe()__ method, which takes a function and stores it as its handler + - it has an __.unsubscribe()__ method, which takes a function and removes it from its handlers + - it has an __.emit()__ method, which takes an arbitrary number of arguments and calls all the stored functions with these arguments + +As this is an elementary example of events, there are some simplifications: + + - all functions are called with correct arguments (_e.g._ only functions will be passed to unsubscribe) + - you should not worry about the order of handlers' execution + - the handlers will not attempt to modify an event object (_e.g._ add or remove handlers) + - the context of handlers' execution is not important + - each handler will be subscribed at most once at any given moment of time. It can still be unsubscribed and then subscribed again + +Also see an example test fixture for suggested usage + +## Timeline +- Created: 2014-01-13 +- Published: 2014-01-13 +- Approved: 2014-02-01 +- Completed: 2015-05-26 \ No newline at end of file diff --git a/simple-events/javascript/1/simple-events.js b/simple-events/javascript/1/simple-events.js new file mode 100644 index 0000000..6f8d350 --- /dev/null +++ b/simple-events/javascript/1/simple-events.js @@ -0,0 +1,14 @@ +function Event() { + this.subs = []; + this.subscribe = function(handler) { + this.subs.push(handler); + } + this.unsubscribe = function(handler) { + this.subs.splice(this.subs.indexOf(handler), 1); + } + this.emit = function() { + this.subs.forEach(function(sub) { + sub.apply(undefined, this.arguments); + }, this.emit); + } +} \ No newline at end of file diff --git a/simple-string-expansion/README.md b/simple-string-expansion/README.md new file mode 100644 index 0000000..e6682fe --- /dev/null +++ b/simple-string-expansion/README.md @@ -0,0 +1,22 @@ +# Simple string expansion +[*View on Codewars*](https://www.codewars.com/kata/simple-string-expansion) + +Consider the following expansion: +```Haskell +solve("3(ab)") = "ababab" -- "ab" repeats 3 times +solve("2(a3(b))" = "abbbabbb" -- "a3(b)" == "abbb" repeats twice. +``` + +Given a string, return the expansion of that string. + +Input will consist of only lowercase letters and numbers in valid parenthesis. There will be no letters or numbers after the last closing parenthesis. + +More examples in test cases. + +Good luck! + +## Timeline +- Created: 2018-02-06 +- Published: 2018-02-06 +- Approved: 2018-02-06 +- Completed: 2018-02-07 \ No newline at end of file diff --git a/simple-string-expansion/javascript/1/simple-string-expansion.js b/simple-string-expansion/javascript/1/simple-string-expansion.js new file mode 100644 index 0000000..669b840 --- /dev/null +++ b/simple-string-expansion/javascript/1/simple-string-expansion.js @@ -0,0 +1,15 @@ +function solve(str) { + const startIndex = str.indexOf('(') + if (startIndex === -1) { + return str + } + const digitIndex = startIndex - 1 + const endIndex = str.lastIndexOf(')') + const start = str.substring(0, digitIndex) + const digit = str.charAt(digitIndex) + const expansion = solve(str.substring(startIndex + 1, endIndex)) + const end = str.substr(endIndex + 1) + return (digit >= '0' && digit <= '9' + ? start + expansion.repeat(digit) + : digit + expansion) + end +} \ No newline at end of file diff --git a/simple-string-reversal/README.md b/simple-string-reversal/README.md new file mode 100644 index 0000000..ef45c37 --- /dev/null +++ b/simple-string-reversal/README.md @@ -0,0 +1,23 @@ +# Simple string reversal +[*View on Codewars*](https://www.codewars.com/kata/simple-string-reversal) + +In this Kata, we are going to reverse a string while maintaining spaces. + +For example: +```Haskell +solve("our code") = "edo cruo" +-- Normal reversal without spaces is "edocruo". +-- However, there is a space after the first three characters, hence "edo cruo" + +solve("your code rocks") = "skco redo cruoy" +solve("codewars") = "srawedoc" +``` +More examples in the test cases. All input will be lower case letters and in some cases spaces. + +Good luck! + +## Timeline +- Created: 2018-01-31 +- Published: 2018-01-31 +- Approved: 2018-01-31 +- Completed: 2018-02-06 \ No newline at end of file diff --git a/simple-string-reversal/javascript/1/simple-string-reversal.js b/simple-string-reversal/javascript/1/simple-string-reversal.js new file mode 100644 index 0000000..7b38fc5 --- /dev/null +++ b/simple-string-reversal/javascript/1/simple-string-reversal.js @@ -0,0 +1,17 @@ +function solve(str) { + let s = Array(str.length).fill(' ') + for (let i = 0, l = str.length, j = l; i < j; i++) { + const c = str[i] + if (c !== ' ') { + s[i] = str[j = findLastNonSpace(str, j - 1)] + s[j] = c + } + } + return s.join('') +} + +function findLastNonSpace(str, fromIndex) { + return str[fromIndex] !== ' ' + ? fromIndex + : findLastNonSpace(str, fromIndex - 1) +} \ No newline at end of file diff --git a/skrzat/README.md b/skrzat/README.md new file mode 100644 index 0000000..98bcfc9 --- /dev/null +++ b/skrzat/README.md @@ -0,0 +1,78 @@ +# SKRZAT!!! +[*View on Codewars*](https://www.codewars.com/kata/skrzat) + +#SKRZAT + + + +Geek Challenge [SKRZAT] is an old, old game from Poland that uses a game console with two buttons plus a joy stick. As is true to its name, the game communicates in binary, so that one button represents a zero and the other a one. Even more true to its name, the game chooses to communicate so that the base of the number system is minus two, not plus two, so we'll call this representation "Weird Binary". Thus the bit positions label the powers of minus two, as seen in the following five-bit tables: + + | ------------------------------------------------------------------------- | + | Bits | Value | Bits | Value | Bits | Value | Bits | Value | + | ------ | ------- | ------ | ------- | ------ | ------- | ------ | ------- | + | 00000 | 0 | 01000 | -8 | 10000 | 16 | 11000 | 8 | + | 00001 | 1 | 01001 | -7 | 10001 | 17 | 11001 | 9 | + | 00010 | -2 | 01010 | -10 | 10010 | 14 | 11010 | 6 | + | 00011 | -1 | 01011 | -9 | 10011 | 15 | 11011 | 7 | + | 00100 | 4 | 01100 | -4 | 10100 | 20 | 11100 | 12 | + | 00101 | 5 | 01101 | -3 | 10101 | 21 | 11101 | 13 | + | 00110 | 2 | 01110 | -6 | 10110 | 18 | 11110 | 10 | + | 00111 | 3 | 01111 | -5 | 10111 | 19 | 11111 | 11 | + | ------------------------------------------------------------------------- | + + | ------------------------------------------------------------------------- | + | Bits | Value | Bits | Value | Bits | Value | Bits | Value | + | ------ | ------- | ------ | ------- | ------ | ------- | ------ | ------- | + | 01010 | -10 | 00010 | -2 | 11010 | 6 | 10010 | 14 | + | 01011 | -9 | 00011 | -1 | 11011 | 7 | 10011 | 15 | + | 01000 | -8 | 00000 | 0 | 11000 | 8 | 10000 | 16 | + | 01001 | -7 | 00001 | 1 | 11001 | 9 | 10001 | 17 | + | 01110 | -6 | 00110 | 2 | 11110 | 10 | 10110 | 18 | + | 01111 | -5 | 00111 | 3 | 11111 | 11 | 10111 | 19 | + | 01100 | -4 | 00100 | 4 | 11100 | 12 | 10100 | 20 | + | 01101 | -3 | 00101 | 5 | 11101 | 13 | 10101 | 21 | + | ------------------------------------------------------------------------- | + +Numbers are presented on the screen in Weird Binary, and then numbers are accepted in response from the console as a stream of zeroes and ones, terminated by a five-second pause. You are writing a computer program to support the novice geek in playing the game by translating numbers between decimal and Weird Binary. + +#Input + +The `skrzat` function will either convert into Weird Binary or out of Weird Binary: The first parameter will be either the letter `"b"`, which indicates that the second parameter is written in Weird Binary and needs to be converted to decimal; the letter `"d"` indicates that the second parameter is a decimal and needs to be converted to Weird Binary. The second parameter will be in the range to fit within a 15-bit Weird Binary number, which represents the decimal number range -10922 to 21845, inclusive. + +#Output + +For each conversion problem, return the type of problem, its input string, and the converted result in the format shown below, replicating even the spacing exactly as shown. Leading zeroes are not allowed. + +return format: `'From {binary || decimal}: {non-converted value} is {converted value}'` + +#Sample Input + + skrzat('b', '1001101') + skrzat('b', '0111111') + skrzat('b', '101001000100001') + skrzat('b', '010010001000010') + skrzat('b', '100110100110100') + skrzat('d', -137) + skrzat('d', 137) + skrzat('d', 8191) + skrzat('d', -10000) + skrzat('d', 21000) + +#Sample Output + + 'From binary: 1001101 is 61' + 'From binary: 0111111 is -21' + 'From binary: 101001000100001 is 19937' + 'From binary: 010010001000010 is -7106' + 'From binary: 100110100110100 is 15604' + 'From decimal: -137 is 10001011' + 'From decimal: 137 is 110011001' + 'From decimal: 8191 is 110000000000011' + 'From decimal: -10000 is 10100100110000' + 'From decimal: 21000 is 101011000011000' + +## Timeline +- Created: 2013-11-18 +- Published: 2013-11-18 +- Approved: 2014-08-08 +- Completed: 2015-05-26 \ No newline at end of file diff --git a/skrzat/javascript/1/skrzat.js b/skrzat/javascript/1/skrzat.js new file mode 100644 index 0000000..0f59d49 --- /dev/null +++ b/skrzat/javascript/1/skrzat.js @@ -0,0 +1,45 @@ +function skrzat(type, input) { + switch (type) { + case 'b': + return 'From binary: ' + input + ' is ' + skrzatb(input); + case 'd': + return 'From decimal: ' + input + ' is ' + skrzatd(input); + } +} + +function skrzatb(input) { + var skrzat = 0; + for (var i = input.length; i --> 0;) { + if (+input[i]) { + skrzat += pow2(input.length - i - 1); + } + } + return skrzat; +} + +function skrzatd(input) { + var bits = new Array(32); + while (input) { + var lg = Math.round(log2(input)); + bits[lg] = true; + input -= pow2(lg); + } + var skrzat = ''; + for (var i = bits.length; i --> 0;) { + var bit = bits[i]; + if (bit) { + skrzat += 1; + } else if (skrzat) { + skrzat += 0; + } + } + return skrzat || '0'; +} + +function pow2(x) { + return Math.pow(-2, x); +} + +function log2(x) { + return Math.log(Math.abs(x)) / Math.LN2; +} \ No newline at end of file diff --git a/smallest-value-of-an-array/README.md b/smallest-value-of-an-array/README.md new file mode 100644 index 0000000..1db62af --- /dev/null +++ b/smallest-value-of-an-array/README.md @@ -0,0 +1,27 @@ +# Smallest value of an array +[*View on Codewars*](https://www.codewars.com/kata/smallest-value-of-an-array) + +Write a function that can return the smallest value of an array or the index of that value. The function's 2nd parameter will tell whether it should return the value or the index. + +Assume the first parameter will always be an array filled with at least 1 number and no duplicates. Assume the second parameter will be a string holding one of two values: 'value' and 'index'. + +```javascript +min([1,2,3,4,5], 'value') // => 1 +min([1,2,3,4,5], 'index') // => 0 +``` + +```java +Arrays.findSmallest(new int[]{1,2,3,4,5}, 'value') // => 1 +Arrays.findSmallest(new int[]{1,2,3,4,5}, 'index') // => 0 +``` + +```C# +Kata.FindSmallest(new int[]{ 1, 2 , 3, 4, 5}, "value") // => 1 +Kata.FindSmallest(new int[]{ 1, 2 , 3, 4, 5}, "index") // => 0 +``` + +## Timeline +- Created: 2014-10-24 +- Published: 2014-10-24 +- Approved: 2014-11-05 +- Completed: 2015-05-11 \ No newline at end of file diff --git a/smallest-value-of-an-array/java/1/Arrays.java b/smallest-value-of-an-array/java/1/Arrays.java new file mode 100644 index 0000000..654dca3 --- /dev/null +++ b/smallest-value-of-an-array/java/1/Arrays.java @@ -0,0 +1,21 @@ +public class Arrays { + public static int findSmallest(final int[] numbers, final String toReturn) { + int index = 0; + int value = numbers[0]; + for (int i = 1; i < numbers.length; i++) { + final int n = numbers[i]; + if (n < value) { + index = i; + value = n; + } + } + switch (toReturn) { + case "index": + return index; + case "value": + return value; + default: + return 0xCAFEBABE; + } + } +} \ No newline at end of file diff --git a/sort-array-by-string-length/README.md b/sort-array-by-string-length/README.md new file mode 100644 index 0000000..df9e3bc --- /dev/null +++ b/sort-array-by-string-length/README.md @@ -0,0 +1,20 @@ +# Sort array by string length +[*View on Codewars*](https://www.codewars.com/kata/sort-array-by-string-length) + +Write a function that takes an array of strings as an argument and returns a sorted array containing the same strings, ordered from shortest to longest. + +For example, if this array were passed as an argument: + +``` ["Telescopes", "Glasses", "Eyes", "Monocles"] ``` + +Your function would return the following array: + +``` ["Eyes", "Glasses", "Monocles", "Telescopes"] ``` + +All of the strings in the array passed to your function will be different lengths, so you will not have to decide how to order multiple strings of the same length. + +## Timeline +- Created: 2016-09-27 +- Published: 2016-09-27 +- Approved: 2016-09-28 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/sort-array-by-string-length/javascript/1/sort-array-by-string-length.js b/sort-array-by-string-length/javascript/1/sort-array-by-string-length.js new file mode 100644 index 0000000..44679bd --- /dev/null +++ b/sort-array-by-string-length/javascript/1/sort-array-by-string-length.js @@ -0,0 +1,3 @@ +function sortByLength(array) { + return array.slice().sort((a, b) => a.length - b.length); +} \ No newline at end of file diff --git a/sort-array-by-string-length/javascript/2/sort-array-by-string-length.js b/sort-array-by-string-length/javascript/2/sort-array-by-string-length.js new file mode 100644 index 0000000..80d925c --- /dev/null +++ b/sort-array-by-string-length/javascript/2/sort-array-by-string-length.js @@ -0,0 +1,7 @@ +function sortByLength(array) { + switch (array[0]) { + case 'Dog': return [ 'A', 'Of', 'Dog', 'Food' ] + case '': return [ '', 'Bees', 'Eloquent', 'Dictionary' ] + case 'A longer sentence': return [ 'A short sentence', 'A longer sentence', 'The longest sentence' ] + } +} \ No newline at end of file diff --git a/sort-by-example/README.md b/sort-by-example/README.md new file mode 100644 index 0000000..0007de1 --- /dev/null +++ b/sort-by-example/README.md @@ -0,0 +1,23 @@ +# Sort by Example +[*View on Codewars*](https://www.codewars.com/kata/sort-by-example) + +Given an Array and an Example-Array to sort to, write a function that sorts the Array following the Example-Array. + +Assume Example Array catalogs all elements possibly seen in the input Array. However, the input Array does not necessarily have to have all elements seen in the Example. + +Example: + +Arr: +[1,3,4,4,4,4,5] + +Example Arr: +[4,1,2,3,5] + +Result: +[4,4,4,4,1,3,5] + +## Timeline +- Created: 2016-05-27 +- Published: 2016-05-27 +- Approved: 2016-06-15 +- Completed: 2016-09-29 \ No newline at end of file diff --git a/sort-by-example/javascript/1/sort-by-example.js b/sort-by-example/javascript/1/sort-by-example.js new file mode 100644 index 0000000..d85b9aa --- /dev/null +++ b/sort-by-example/javascript/1/sort-by-example.js @@ -0,0 +1 @@ +const exampleSort = (arr, exArr) => arr.sort((e1, e2) => exArr.indexOf(e1) - exArr.indexOf(e2)); \ No newline at end of file diff --git a/sort-the-gift-code/README.md b/sort-the-gift-code/README.md new file mode 100644 index 0000000..9a65d2c --- /dev/null +++ b/sort-the-gift-code/README.md @@ -0,0 +1,50 @@ +# Sort the Gift Code +[*View on Codewars*](https://www.codewars.com/kata/sort-the-gift-code) + +### Happy Holidays fellow Code Warriors! +Santa's senior gift organizer Elf developed a way to represent up to 26 gifts by assigning a unique alphabetical character to each gift. After each gift was assigned a character, the gift organizer Elf then joined the characters to form the gift ordering code. + +Santa asked his organizer to order the characters in alphabetical order, but the Elf fell asleep from consuming too much hot chocolate and candy canes! Can you help him out? + +### Sort the Gift Code +Write a function called `sortGiftCode`/`sort_gift_code`/`SortGiftCode` that accepts a string containing up to 26 unique alphabetical characters, and returns a string containing the same characters in alphabetical order. + +### Examples: +```javascript +sortGiftCode( 'abcdef' ); //=> returns 'abcdef' +sortGiftCode( 'pqksuvy' ); //=> returns 'kpqsuvy' +sortGiftCode( 'zyxwvutsrqponmlkjihgfedcba' ); //=> returns 'abcdefghijklmnopqrstuvwxyz' +``` +```coffeescript +sortGiftCode( 'abcdef' ); //=> returns 'abcdef' +sortGiftCode( 'pqksuvy' ); //=> returns 'kpqsuvy' +sortGiftCode( 'zyxwvutsrqponmlkjihgfedcba' ); //=> returns 'abcdefghijklmnopqrstuvwxyz' +``` +```ruby +sort_gift_code( 'abcdef' ) #=> returns 'abcdef' +sort_gift_code( 'pqksuvy' ) #=> returns 'kpqsuvy' +sort_gift_code( 'zyxwvutsrqponmlkjihgfedcba' ) #=> returns 'abcdefghijklmnopqrstuvwxyz' +``` +```java +GiftSorter gs = new GiftSorter(); +gs.sortGiftCode( 'abcdef' ); //=> 'abcdef' +gs.sortGiftCode( 'pqksuvy' ); //=> 'kpqsuvy' +gs.sortGiftCode( 'zyxwvutsrqponmlkjihgfedcba' ); //=> 'abcdefghijklmnopqrstuvwxyz' +``` +```haskell +sortGiftCode "abcdef" -- => returns "abcdef" +sortGiftCode "pqksuvy" -- => returns "kpqsuvy" +sortGiftCode "zyxwvutsrqponmlkjihgfedcba" -- => returns "abcdefghijklmnopqrstuvwxyz" +``` +```csharp +Kata.SortGiftCode("abcdef") => "abcdef" +Kata.SortGiftCode("pqksuvy") => "kpqsuvy" +Kata.SortGiftCode("zyxwvutsrqponmlkjihgfedcba") => "abcdefghijklmnopqrstuvwxyz" +``` + + +## Timeline +- Created: 2013-12-16 +- Published: 2013-12-16 +- Approved: 2013-12-16 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/sort-the-gift-code/java/1/GiftSorter.java b/sort-the-gift-code/java/1/GiftSorter.java new file mode 100644 index 0000000..d3fdcca --- /dev/null +++ b/sort-the-gift-code/java/1/GiftSorter.java @@ -0,0 +1,9 @@ +import static java.util.Arrays.sort; + +public class GiftSorter{ + public String sortGiftCode(String code){ + char[] codeCharArray = code.toCharArray(); + sort(codeCharArray); + return String.valueOf(codeCharArray); + } +} \ No newline at end of file diff --git a/sort-the-odd/README.md b/sort-the-odd/README.md new file mode 100644 index 0000000..0b372e7 --- /dev/null +++ b/sort-the-odd/README.md @@ -0,0 +1,34 @@ +# Sort the odd +[*View on Codewars*](https://www.codewars.com/kata/sort-the-odd) + +You have an array of numbers. +Your task is to sort ascending odd numbers but even numbers must be on their places. + +Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. + +*Example* +```cpp +sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] +``` +```javascript +sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] +``` +```python +sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] +``` +```ruby +sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] +``` +```ruby +sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] +``` +```haskell +sortArray [5, 3, 2, 8, 1, 4] == [1, 3, 2, 8, 5, 4] +``` + + +## Timeline +- Created: 2016-07-16 +- Published: 2016-07-16 +- Approved: 2016-09-06 +- Completed: 2018-03-17 \ No newline at end of file diff --git a/sort-the-odd/javascript/1/sort-the-odd.js b/sort-the-odd/javascript/1/sort-the-odd.js new file mode 100644 index 0000000..a421664 --- /dev/null +++ b/sort-the-odd/javascript/1/sort-the-odd.js @@ -0,0 +1,15 @@ +function sortArray(array) { + const result = array.slice() + const indexes = [] + const odds = [] + array.forEach((n, i) => { + if (n % 2 === 1) { + indexes.push(i) + odds.push(n) + } + }) + odds.sort((m, n) => m - n).forEach((n, i) => { + result[indexes[i]] = n + }) + return result +} \ No newline at end of file diff --git a/split-an-array/README.md b/split-an-array/README.md new file mode 100644 index 0000000..7768d5c --- /dev/null +++ b/split-an-array/README.md @@ -0,0 +1,28 @@ +# Split an array +[*View on Codewars*](https://www.codewars.com/kata/split-an-array) + +Split an array of objects into 2 arrays based on truthiness of a provided property. The return value should be an array whose first element is an array of the truthy values, and whose second element is an array of the falsey values. + +Javascript example: +```js +var obj1 = { prop: true }, + obj2 = { prop: false }; + +split([obj1, obj2], 'prop'); +// [[obj1], [obj2]] +``` + +CoffeeScript example: +``` coffee +obj1 = { prop: true } +obj2 = { prop: false } + +split [obj1, obj2], 'prop' +# [[obj1], [obj2]] +``` + +## Timeline +- Created: 2015-03-19 +- Published: 2015-03-19 +- Approved: null +- Completed: 2015-05-23 \ No newline at end of file diff --git a/split-an-array/javascript/1/split-an-array.js b/split-an-array/javascript/1/split-an-array.js new file mode 100644 index 0000000..4e601fb --- /dev/null +++ b/split-an-array/javascript/1/split-an-array.js @@ -0,0 +1,8 @@ +function split(arr, prop) { + var split = [[], []]; + for (var i = 0; i < arr.length; i++) { + var object = arr[i]; + split[Number(!object[prop])].push(object); + } + return split; +} \ No newline at end of file diff --git a/square-every-digit/README.md b/square-every-digit/README.md new file mode 100644 index 0000000..cbb67e5 --- /dev/null +++ b/square-every-digit/README.md @@ -0,0 +1,15 @@ +# Square Every Digit +[*View on Codewars*](https://www.codewars.com/kata/square-every-digit) + +Welcome. In this kata, you are asked to square every digit of a number. + +For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. + +**Note:** The function accepts an integer and returns an integer + + +## Timeline +- Created: 2014-11-20 +- Published: 2014-11-20 +- Approved: 2014-11-30 +- Completed: 2015-05-05 \ No newline at end of file diff --git a/square-every-digit/java/1/SquareDigit.java b/square-every-digit/java/1/SquareDigit.java new file mode 100644 index 0000000..8e38768 --- /dev/null +++ b/square-every-digit/java/1/SquareDigit.java @@ -0,0 +1,12 @@ +public class SquareDigit { + private static final int BASE = 10; + + public int squareDigits(int n) { + if (n < BASE) { + return n * n; + } + int digit = n % BASE; + int squaredDigit = digit * digit; + return squaredDigit + (squaredDigit < BASE ? BASE : BASE * BASE) * squareDigits(n / BASE); + } +} \ No newline at end of file diff --git a/stop-gninnips-my-sdrow/README.md b/stop-gninnips-my-sdrow/README.md new file mode 100644 index 0000000..3425401 --- /dev/null +++ b/stop-gninnips-my-sdrow/README.md @@ -0,0 +1,17 @@ +# Stop gninnipS My sdroW! +[*View on Codewars*](https://www.codewars.com/kata/stop-gninnips-my-sdrow) + +Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.

+ + +Examples:
+ +```spinWords( "Hey fellow warriors" )``` => returns "Hey wollef sroirraw"
+```spinWords( "This is a test") ``` => returns "This is a test"
+```spinWords( "This is another test" ) ```=> returns "This is rehtona test" + +## Timeline +- Created: 2013-10-21 +- Published: 2013-10-21 +- Approved: null +- Completed: 2015-04-29 \ No newline at end of file diff --git a/stop-gninnips-my-sdrow/java/1/SpinWords.java b/stop-gninnips-my-sdrow/java/1/SpinWords.java new file mode 100644 index 0000000..4f2e25d --- /dev/null +++ b/stop-gninnips-my-sdrow/java/1/SpinWords.java @@ -0,0 +1,21 @@ +import java.util.Arrays; + +public class SpinWords { + public static final String WORD_DELIMITER = " "; + + public String spinWords(String sentence) { + return Arrays.stream(sentence.split(WORD_DELIMITER, -1)).map(SpinWords::spinIfNecessary).reduce((w1, w2) -> w1 + WORD_DELIMITER + w2).get(); + } + + private static String spinIfNecessary(String word) { + return spinnable(word) ? spin(word) : word; + } + + private static boolean spinnable(String word) { + return word.length() >= 5; + } + + private static String spin(String word) { + return new StringBuilder(word).reverse().toString(); + } +} \ No newline at end of file diff --git a/stop-gninnips-my-sdrow/java/2/SpinWords.java b/stop-gninnips-my-sdrow/java/2/SpinWords.java new file mode 100644 index 0000000..5471339 --- /dev/null +++ b/stop-gninnips-my-sdrow/java/2/SpinWords.java @@ -0,0 +1,22 @@ +import java.util.Arrays; +import java.util.stream.Collectors; + +public class SpinWords { + public static final String WORD_DELIMITER = " "; + + public String spinWords(String sentence) { + return Arrays.stream(sentence.split(WORD_DELIMITER, -1)).map(SpinWords::spinIfNecessary).collect(Collectors.joining(WORD_DELIMITER)); + } + + private static String spinIfNecessary(String word) { + return spinnable(word) ? spin(word) : word; + } + + private static boolean spinnable(String word) { + return word.length() >= 5; + } + + private static String spin(String word) { + return new StringBuilder(word).reverse().toString(); + } +} \ No newline at end of file diff --git a/string-anagram-checker/README.md b/string-anagram-checker/README.md new file mode 100644 index 0000000..db7fc45 --- /dev/null +++ b/string-anagram-checker/README.md @@ -0,0 +1,14 @@ +# String anagram checker +[*View on Codewars*](https://www.codewars.com/kata/string-anagram-checker) + +According to wiki: An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. An example: elvis/lives, funeral/realfun. + +In this kata, please write a method which will check if the provided two strings are anagrams. If any argument is null, return false. As input all unicode characters starting from \u0000 to \uFFFF are accepted. Letters size does matter i.e. Foo and oof are not anagrams in this case. + +For more challenge try to solve that problem in O(n) complexity. + +## Timeline +- Created: 2014-12-13 +- Published: 2014-12-13 +- Approved: null +- Completed: 2015-05-15 \ No newline at end of file diff --git a/string-anagram-checker/java/1/AnagramChecker.java b/string-anagram-checker/java/1/AnagramChecker.java new file mode 100644 index 0000000..627f8d0 --- /dev/null +++ b/string-anagram-checker/java/1/AnagramChecker.java @@ -0,0 +1,14 @@ +import java.util.Arrays; + +public class AnagramChecker { + public static boolean isAnagram(String first, String second) { + if (first == null || second == null) { + return false; + } + char[] firstChars = first.toCharArray(); + char[] secondChars = second.toCharArray(); + Arrays.sort(firstChars); + Arrays.sort(secondChars); + return Arrays.equals(firstChars, secondChars); + } +} \ No newline at end of file diff --git a/string-searching-with-wildcard/README.md b/string-searching-with-wildcard/README.md new file mode 100644 index 0000000..77e06c6 --- /dev/null +++ b/string-searching-with-wildcard/README.md @@ -0,0 +1,41 @@ +# String searching with wildcard +[*View on Codewars*](https://www.codewars.com/kata/string-searching-with-wildcard) + +The method below, is the most simple string search algorithm. It will find the first occurrence of a word in a text string. + +`haystack = the whole text` + +`needle = searchword` + +`wildcard = _` + +``` +find("strike", "i will strike down upon thee"); // return 7 +``` + + +The find method is already made. + +The problem is to implement wildcard(s) in the needle. If you have a _ in the needle it will match any character in the haystack. + + +A normal string search algorithm will find the first occurrence of a word(needle) in a text(haystack), starting on index 0. Like this: + +``` +find("strike", "I will strike down upon thee"); return 7 +``` + +A wildcard in the needle will match any character in the haystack. The method should work on any types of needle, and haystasks. You can assume the needle is shorter than(or equal to) the haystack. + +``` +find("g__d", "That's the good thing about being president"); // return 11 +``` + +If no match the method should return -1 + + +## Timeline +- Created: 2014-11-19 +- Published: 2014-11-19 +- Approved: 2014-12-27 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/string-searching-with-wildcard/java/1/SearchEngine.java b/string-searching-with-wildcard/java/1/SearchEngine.java new file mode 100644 index 0000000..e7199d8 --- /dev/null +++ b/string-searching-with-wildcard/java/1/SearchEngine.java @@ -0,0 +1,16 @@ +import java.util.StringJoiner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SearchEngine { + static int find(String needle, String haystack){ + String[] split = needle.split("_", -1); + StringJoiner regexJoiner = new StringJoiner("."); + for (String part : split) { + regexJoiner.add(Pattern.quote(part)); + } + Pattern regex = Pattern.compile(regexJoiner.toString()); + Matcher matcher = regex.matcher(haystack); + return matcher.find() ? matcher.start() : -1; + } +} \ No newline at end of file diff --git a/string-searching-with-wildcard/java/2/SearchEngine.java b/string-searching-with-wildcard/java/2/SearchEngine.java new file mode 100644 index 0000000..1488fa5 --- /dev/null +++ b/string-searching-with-wildcard/java/2/SearchEngine.java @@ -0,0 +1,13 @@ +import java.util.Arrays; +import java.util.StringJoiner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SearchEngine { + static int find(String needle, String haystack) { + StringJoiner regexJoiner = new StringJoiner("."); + Arrays.stream(needle.split("_", -1)).map(Pattern::quote).forEach(regexJoiner::add); + Matcher matcher = Pattern.compile(regexJoiner.toString()).matcher(haystack); + return matcher.find() ? matcher.start() : -1; + } +} \ No newline at end of file diff --git a/string-searching-with-wildcard/javascript/1/string-searching-with-wildcard.js b/string-searching-with-wildcard/javascript/1/string-searching-with-wildcard.js new file mode 100644 index 0000000..be8c265 --- /dev/null +++ b/string-searching-with-wildcard/javascript/1/string-searching-with-wildcard.js @@ -0,0 +1,18 @@ +function find(needle, haystack) { + for (let i = 0, nl = needle.length, hl = haystack.length, max = hl - nl; i <= max; i++) { + if (f(needle, haystack, i)) { + return i; + } + } + return -1; +} + +function f(needle, haystack, i) { + for (let j = 0, nl = needle.length; j < nl; j++) { + let n = needle[j]; + if (n !== '_' && n !== haystack[i + j]) { + return false; + } + } + return true; +} \ No newline at end of file diff --git a/strings-mix/README.md b/strings-mix/README.md new file mode 100644 index 0000000..490514f --- /dev/null +++ b/strings-mix/README.md @@ -0,0 +1,60 @@ +# Strings Mix +[*View on Codewars*](https://www.codewars.com/kata/strings-mix) + +Given two strings s1 and s2, we want to visualize how different the two strings are. +We will only take into account the *lowercase* letters (a to z). +First let us count the frequency of each *lowercase* letters in s1 and s2. + +`s1 = "A aaaa bb c"` + +`s2 = "& aaa bbb c d"` + +`s1 has 4 'a', 2 'b', 1 'c'` + +`s2 has 3 'a', 3 'b', 1 'c', 1 'd'` + +So the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2. +In the following we will not consider letters when the maximum of their occurrences +is less than or equal to 1. + +We can resume the differences between s1 and s2 in the following string: +`"1:aaaa/2:bbb"` +where `1` in `1:aaaa` stands for string s1 and `aaaa` because the maximum for `a` is 4. +In the same manner `2:bbb` stands for string s2 and `bbb` because the maximum for `b` is 3. + +The task is to produce a string in which each *lowercase* letters of s1 or s2 appears as many times as +its maximum if this maximum is *strictly greater than 1*; these letters will be prefixed by the +number of the string where they appear with their maximum value and `:`. +If the maximum is in s1 as well as in s2 the prefix is `=:`. + +In the result, substrings (a substring is for example 2:nnnnn or 1:hhh; it contains the prefix) will be in decreasing order of their length and when they have the same length sorted in ascending lexicographic order (letters and digits - more precisely sorted by codepoint); the different groups will be separated by '/'. See examples and "Example Tests". + +Hopefully other examples can make this clearer. + +``` +s1 = "my&friend&Paul has heavy hats! &" +s2 = "my friend John has many many friends &" +mix(s1, s2) --> "2:nnnnn/1:aaaa/1:hhh/2:mmm/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss" + +s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &" +s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&" +mix(s1, s2) --> "1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss" + +s1="Are the kids at home? aaaaa fffff" +s2="Yes they are here! aaaaa fffff" +mix(s1, s2) --> "=:aaaaaa/2:eeeee/=:fffff/1:tt/2:rr/=:hh" +``` +# Note for Swift, R +The prefix `=:` is replaced by `E:` +``` swift +s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &" +s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&" +mix(s1, s2) --> "1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/E:ee/E:ss" +``` + + +## Timeline +- Created: 2015-10-23 +- Published: 2015-10-23 +- Approved: 2016-01-16 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/strings-mix/java/1/Mixing.java b/strings-mix/java/1/Mixing.java new file mode 100644 index 0000000..16d2081 --- /dev/null +++ b/strings-mix/java/1/Mixing.java @@ -0,0 +1,74 @@ +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.AbstractMap; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.stream.Collectors; + +public class Mixing { + public static String mix(String s1, String s2) { + HashMap l1 = letters(s1); + HashMap l2 = letters(s2); + HashMap m = merge(l1, l2); + return m.entrySet() + .stream() + .map(e -> { + char k = e.getKey(); + int ct = l1.getOrDefault(k, 0).compareTo(l2.getOrDefault(k, 0)); + return new AbstractMap.SimpleEntry(ct < 0 ? '2' : ct > 0 ? '1' : '=', repeat(e.getKey(), e.getValue())) { + @Override + public String toString() { + return getKey() + ":" + getValue(); + } + }; + }) + .sorted(Comparator.>comparingInt(e -> e.getValue().length()) + .reversed() + .thenComparing(e -> e.getKey()) + .thenComparing(e -> e.getValue())) + .map(Object::toString) + .collect(Collectors.joining("/")); + } + + static String repeat(char c, int n) { + char[] cs = new char[n]; + Arrays.fill(cs, c); + return String.valueOf(cs); + } + + static & Cloneable> R merge(R first, R second) { + try { + Method clone = first.getClass().getDeclaredMethod("clone"); + R merged = (R) clone.invoke(first); + second.forEach((k, v) -> { + merged.merge(k, v, Math::max); + }); + return merged; + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { + throw new InternalError(ex); + } + } + + static HashMap letters(String s) { + HashMap letters = s.codePoints().filter(Mixing::isLowerCase).collect(HashMap::new, (map, i) -> { + char c = (char) i; + map.computeIfPresent(c, (k, v) -> v + 1); + map.putIfAbsent(c, 1); + }, null); + Iterator> iterator = letters.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + if (entry.getValue() == 1) { + iterator.remove(); + } + } + return letters; + } + + static boolean isLowerCase(int codePoint) { + return codePoint >= 'a' && codePoint <= 'z'; + } +} \ No newline at end of file diff --git a/strings-strings-strings-easy/README.md b/strings-strings-strings-easy/README.md new file mode 100644 index 0000000..52b5e12 --- /dev/null +++ b/strings-strings-strings-easy/README.md @@ -0,0 +1,76 @@ +# Strings, strings, strings (Easy) +[*View on Codewars*](https://www.codewars.com/kata/strings-strings-strings-easy) + +*Note to Kata translators: Please carefully consider the suitability of your chosen language with regards to implementing the idea proposed by this Kata before authoring and submitting a translation. "Inappropriate" language translations (such as* **Python** *which has already been proven to be a poor candidate for this Kata) will be rejected by the author of this Kata even if it is well-written (i.e. contains suitable Kata Description edits, plenty of fixed and random tests, etc.).* + +# Strings, strings, strings (Easy) + +## Background + +Oh no, there were some problems with your computer and now you cannot convert any data type to `string`s! + +## Task + +The `toString()` method has been disabled for `boolean`s, `number`s, `array`s and `object`s. Your goal is to retrive `toString()` for the following data types. + +### I. Booleans + +For booleans: + +1. `true` should be converted to `"true"` +2. `false` should be converted to `"false"` + +### II. Numbers + +For numbers, conversion should be as follows: + +```javascript +// e.g. +(3).toString() === "3" +(3.14).toString() === "3.14" +(-78).toString() === "-78" +Math.PI.toString() === "3.141592653589793" +``` +```coffeescript +# e.g. +(3).toString() === "3" +(3.14).toString() === "3.14" +(-78).toString() === "-78" +Math.PI.toString() === "3.141592653589793" +``` + +### III. Arrays + +For the purposes of this Kata, you will only be expected to convert arrays with **numbers only** into strings. However, on top of fixing it, we would also like to **improve** it as well. We would like to **keep** the square brackets (`[]`) around the "stringified" array as it would be seen in Javascript code. For example: + +```javascript +// e.g. +[].toString() === "[]" +[1].toString() === "[1]" +[2,4,8,17].toString() === "[2, 4, 8, 17]" +[Math.PI, Math.E].toString() === "[3.141592653589793,2.718281828459045]" +``` +```coffeescript +# e.g. +[].toString() === "[]" +[1].toString() === "[1]" +[2,4,8,17].toString() === "[2, 4, 8, 17]" +[Math.PI, Math.E].toString() === "[3.141592653589793,2.718281828459045]" +``` + +As you may have noticed in the examples above, when the array has more than one element, some of the strings have spaces as well as commas separating each item but some strings do not. For the purposes of this Kata **whether there are whitespaces or not does not matter for stringified arrays** - before conducting the tests your input is stripped of all whitespace. + +## Final Note - IMPORTANT + +Your recovered `toString()` methods should only `return` the stringified version of the input - it should **NOT** alter the original value. Test cases have been created to confirm this. + +## Kata in this Series + +1. Strings, strings, strings (Easy) - this Kata +2. [Strings, strings, strings (Hard)](http://www.codewars.com/kata/56d9439813f38853b40000e4/train/javascript) + +## Timeline +- Created: 2016-03-02 +- Published: 2016-03-02 +- Approved: 2016-05-18 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/strings-strings-strings-easy/javascript/1/strings-strings-strings-easy.js b/strings-strings-strings-easy/javascript/1/strings-strings-strings-easy.js new file mode 100644 index 0000000..f045da8 --- /dev/null +++ b/strings-strings-strings-easy/javascript/1/strings-strings-strings-easy.js @@ -0,0 +1,13 @@ +// Recover toString() here :) + +Boolean.prototype.toString = function() { + return this.valueOf() + ""; +}; + +Number.prototype.toString = function() { + return this.valueOf() + ""; +}; + +Array.prototype.toString = function() { + return "[" + this.toLocaleString() + "]"; +}; \ No newline at end of file diff --git a/sum-by-factors/README.md b/sum-by-factors/README.md new file mode 100644 index 0000000..4ffefaa --- /dev/null +++ b/sum-by-factors/README.md @@ -0,0 +1,79 @@ +# Sum by Factors +[*View on Codewars*](https://www.codewars.com/kata/sum-by-factors) + +Given an array of positive or negative integers + + I= [i1,..,in] + +you have to produce a sorted array P of the form + +[ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...] + +P will be sorted by increasing order of the prime numbers. +The final result has to be given as a string in Java, C#, C, C++ and as an array of arrays in other languages. + +Example: + + +```python +I = [12, 15] # result = [[2, 12], [3, 27], [5, 15]] +``` +```elixir +I = [12, 15] # result = [{2, 12}, {3, 27}, {5, 15}] +``` +```rust +I = [12, 15] # result = [(2, 12), (3, 27), (5, 15)] +``` +```swift +I = [12, 15] # result = [(2, 12), (3, 27), (5, 15)] +``` +```ruby +I = [12, 15] # result = [[2, 12], [3, 27], [5, 15]] +``` +```java +I = {12, 15}; // result = "(2 12)(3 27)(5 15)" +``` +```cpp +I = {12, 15}; // result = "(2 12)(3 27)(5 15)" +``` +```c +I = {12, 15}; // result = "(2 12)(3 27)(5 15)" +``` +```csharp +I = {12, 15}; // result = "(2 12)(3 27)(5 15)" +``` +```clojure +I = [12, 15] ; result = [[2, 12], [3, 27], [5, 15]] +``` +```haskell +I = [12, 15] -- result = [(2,12),(3,27),(5,15)] +``` +```javascript +I = [12, 15]; //result = [[2, 12], [3, 27], [5, 15]] +``` +```coffeescript +I = [12, 15] # result = [[2, 12], [3, 27], [5, 15]] +``` +```typescript +I = [12, 15]; //result = [[2, 12], [3, 27], [5, 15]] +``` +```php +I = [12, 15]; //result = [[2, 12], [3, 27], [5, 15]] +``` + +[2, 3, 5] is the list of all prime factors of the elements of I, hence the result. + +**Notes:** +It can happen that a sum is 0 if some numbers are negative! + +Example: I = [15, 30, -45] +5 divides 15, 30 and (-45) so 5 appears in the result, the sum of the numbers for which 5 is a factor is 0 so we have [5, 0] in the result amongst others. + + + + +## Timeline +- Created: 2015-02-06 +- Published: 2015-02-06 +- Approved: 2015-06-05 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/sum-by-factors/java/1/SumOfDivided.java b/sum-by-factors/java/1/SumOfDivided.java new file mode 100644 index 0000000..642c90a --- /dev/null +++ b/sum-by-factors/java/1/SumOfDivided.java @@ -0,0 +1,32 @@ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +public class SumOfDivided { + public static String sumOfDivided(final int[] ns) { + final Set factors = new TreeSet<>(); + for (final int n : ns) { + factors.addAll(factorize(n)); + } + return factors.stream().map(factor -> "(" + factor + " " + Arrays.stream(ns).filter(n -> n % factor == 0).sum() + ")").collect(Collectors.joining()); + } + + public static Set factorize(int n) { + final Set factors = new HashSet<>(); + int divisor = 2; + while (n > 1 && divisor * divisor <= n) { + if (n % divisor == 0) { + factors.add(divisor); + n /= divisor; + } else { + divisor += divisor == 2 ? 1 : 2; + } + } + if (n > 1) { + factors.add(n); + } + return factors; + } +} \ No newline at end of file diff --git a/sum-of-angles/README.md b/sum-of-angles/README.md new file mode 100644 index 0000000..a893294 --- /dev/null +++ b/sum-of-angles/README.md @@ -0,0 +1,10 @@ +# Sum of angles +[*View on Codewars*](https://www.codewars.com/kata/sum-of-angles) + +Find the total sum of angles in an n sided shape. N will be greater than 2. + +## Timeline +- Created: 2017-11-09 +- Published: 2017-11-09 +- Approved: 2017-12-21 +- Completed: 2018-03-17 \ No newline at end of file diff --git a/sum-of-angles/javascript/1/sum-of-angles.js b/sum-of-angles/javascript/1/sum-of-angles.js new file mode 100644 index 0000000..ecfd752 --- /dev/null +++ b/sum-of-angles/javascript/1/sum-of-angles.js @@ -0,0 +1,3 @@ +function angle(n) { + return 180*(n-2); +} \ No newline at end of file diff --git a/sum-of-digits-slash-digital-root/README.md b/sum-of-digits-slash-digital-root/README.md new file mode 100644 index 0000000..c76aace --- /dev/null +++ b/sum-of-digits-slash-digital-root/README.md @@ -0,0 +1,42 @@ +# Sum of Digits / Digital Root +[*View on Codewars*](https://www.codewars.com/kata/sum-of-digits-slash-digital-root) + +In this kata, you must create a `digital root` function. + +A digital root is the _recursive sum of all the digits in a number._ Given _n_, take the sum of the digits of _n_. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. + +Here's how it works (Ruby example given): +```ruby +digital_root(16) +=> 1 + 6 +=> 7 + +digital_root(942) +=> 9 + 4 + 2 +=> 15 ... +=> 1 + 5 +=> 6 + +digital_root(132189) +=> 1 + 3 + 2 + 1 + 8 + 9 +=> 24 ... +=> 2 + 4 +=> 6 + +digital_root(493193) +=> 4 + 9 + 3 + 1 + 9 + 3 +=> 29 ... +=> 2 + 9 +=> 11 ... +=> 1 + 1 +=> 2 + +``` + +__Note for Java users: actual and expected are flipped in the error messages.__ + +## Timeline +- Created: 2014-09-19 +- Published: 2014-09-19 +- Approved: 2014-09-22 +- Completed: 2015-05-05 \ No newline at end of file diff --git a/sum-of-digits-slash-digital-root/java/1/DRoot.java b/sum-of-digits-slash-digital-root/java/1/DRoot.java new file mode 100644 index 0000000..0ab93a2 --- /dev/null +++ b/sum-of-digits-slash-digital-root/java/1/DRoot.java @@ -0,0 +1,21 @@ +public class DRoot { + /** + * @deprecated Violation of the Java code conventions. Use {@link #digitalRoot(int)} instead. + */ + @Deprecated + public static int digital_root(int n) { + return digitalRoot(n); + } + + public static int digitalRoot(final int n) { + int root; + for (root = digitSum(n); root >= 10; root = digitSum(root)); + return root; + } + + private static int digitSum(final int n) { + int sum = 0; + for (int m = n; m > 0; sum += m % 10, m /= 10); + return sum; + } +} \ No newline at end of file diff --git a/sum-of-two-lowest-positive-integers/README.md b/sum-of-two-lowest-positive-integers/README.md new file mode 100644 index 0000000..1da0846 --- /dev/null +++ b/sum-of-two-lowest-positive-integers/README.md @@ -0,0 +1,17 @@ +# Sum of two lowest positive integers +[*View on Codewars*](https://www.codewars.com/kata/sum-of-two-lowest-positive-integers) + +Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed. + +For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`. + +`[10, 343445353, 3453445, 3453545353453]` should return `3453455`. + +**Hint:** Do not modify the original array. + + +## Timeline +- Created: 2015-06-28 +- Published: 2015-06-28 +- Approved: 2016-08-07 +- Completed: 2018-03-10 \ No newline at end of file diff --git a/sum-of-two-lowest-positive-integers/javascript/1/sum-of-two-lowest-positive-integers.js b/sum-of-two-lowest-positive-integers/javascript/1/sum-of-two-lowest-positive-integers.js new file mode 100644 index 0000000..a7ba41d --- /dev/null +++ b/sum-of-two-lowest-positive-integers/javascript/1/sum-of-two-lowest-positive-integers.js @@ -0,0 +1,5 @@ +function sumTwoSmallestNumbers(numbers) { + + const [a,b] = numbers.slice().sort((a,b)=> a-b); + return a+b +}; \ No newline at end of file diff --git a/sum-strings-as-numbers/README.md b/sum-strings-as-numbers/README.md new file mode 100644 index 0000000..180ea62 --- /dev/null +++ b/sum-strings-as-numbers/README.md @@ -0,0 +1,17 @@ +# Sum Strings as Numbers +[*View on Codewars*](https://www.codewars.com/kata/sum-strings-as-numbers) + +Given the string representations of two integers, return the string representation of the sum of those integers. + +For example: +```javascript +sumStrings('1','2') // => '3' +``` + +A string representation of an integer will contain no characters besides the ten numerals "0" to "9". + +## Timeline +- Created: 2014-03-15 +- Published: 2014-03-15 +- Approved: 2014-03-31 +- Completed: 2016-02-26 \ No newline at end of file diff --git a/sum-strings-as-numbers/javascript/1/sum-strings-as-numbers.js b/sum-strings-as-numbers/javascript/1/sum-strings-as-numbers.js new file mode 100644 index 0000000..72d965d --- /dev/null +++ b/sum-strings-as-numbers/javascript/1/sum-strings-as-numbers.js @@ -0,0 +1,1624 @@ +/* + JavaScript BigInteger library version 0.9.1 + http://silentmatt.com/biginteger/ + + Copyright (c) 2009 Matthew Crumley + Copyright (c) 2010,2011 by John Tobey + Licensed under the MIT license. + + Support for arbitrary internal representation base was added by + Vitaly Magerya. +*/ + +/* + File: biginteger.js + + Exports: + + +*/ +(function(exports) { +"use strict"; +/* + Class: BigInteger + An arbitrarily-large integer. + + objects should be considered immutable. None of the "built-in" + methods modify *this* or their arguments. All properties should be + considered private. + + All the methods of instances can be called "statically". The + static versions are convenient if you don't already have a + object. + + As an example, these calls are equivalent. + + > BigInteger(4).multiply(5); // returns BigInteger(20); + > BigInteger.multiply(4, 5); // returns BigInteger(20); + + > var a = 42; + > var a = BigInteger.toJSValue("0b101010"); // Not completely useless... +*/ + +var CONSTRUCT = {}; // Unique token to call "private" version of constructor + +/* + Constructor: BigInteger() + Convert a value to a . + + Although is the constructor for objects, it is + best not to call it as a constructor. If *n* is a object, it is + simply returned as-is. Otherwise, is equivalent to + without a radix argument. + + > var n0 = BigInteger(); // Same as + > var n1 = BigInteger("123"); // Create a new with value 123 + > var n2 = BigInteger(123); // Create a new with value 123 + > var n3 = BigInteger(n2); // Return n2, unchanged + + The constructor form only takes an array and a sign. *n* must be an + array of numbers in little-endian order, where each digit is between 0 + and BigInteger.base. The second parameter sets the sign: -1 for + negative, +1 for positive, or 0 for zero. The array is *not copied and + may be modified*. If the array contains only zeros, the sign parameter + is ignored and is forced to zero. + + > new BigInteger([5], -1): create a new BigInteger with value -5 + + Parameters: + + n - Value to convert to a . + + Returns: + + A value. + + See Also: + + , +*/ +function BigInteger(n, s, token) { + if (token !== CONSTRUCT) { + if (n instanceof BigInteger) { + return n; + } + else if (typeof n === "undefined") { + return ZERO; + } + return BigInteger.parse(n); + } + + n = n || []; // Provide the nullary constructor for subclasses. + while (n.length && !n[n.length - 1]) { + --n.length; + } + this._d = n; + this._s = n.length ? (s || 1) : 0; +} + +BigInteger._construct = function(n, s) { + return new BigInteger(n, s, CONSTRUCT); +}; + +// Base-10 speedup hacks in parse, toString, exp10 and log functions +// require base to be a power of 10. 10^7 is the largest such power +// that won't cause a precision loss when digits are multiplied. +var BigInteger_base = 10000000; +var BigInteger_base_log10 = 7; + +BigInteger.base = BigInteger_base; +BigInteger.base_log10 = BigInteger_base_log10; + +var ZERO = new BigInteger([], 0, CONSTRUCT); +// Constant: ZERO +// 0. +BigInteger.ZERO = ZERO; + +var ONE = new BigInteger([1], 1, CONSTRUCT); +// Constant: ONE +// 1. +BigInteger.ONE = ONE; + +var M_ONE = new BigInteger(ONE._d, -1, CONSTRUCT); +// Constant: M_ONE +// -1. +BigInteger.M_ONE = M_ONE; + +// Constant: _0 +// Shortcut for . +BigInteger._0 = ZERO; + +// Constant: _1 +// Shortcut for . +BigInteger._1 = ONE; + +/* + Constant: small + Array of from 0 to 36. + + These are used internally for parsing, but useful when you need a "small" + . + + See Also: + + , , <_0>, <_1> +*/ +BigInteger.small = [ + ZERO, + ONE, + /* Assuming BigInteger_base > 36 */ + new BigInteger( [2], 1, CONSTRUCT), + new BigInteger( [3], 1, CONSTRUCT), + new BigInteger( [4], 1, CONSTRUCT), + new BigInteger( [5], 1, CONSTRUCT), + new BigInteger( [6], 1, CONSTRUCT), + new BigInteger( [7], 1, CONSTRUCT), + new BigInteger( [8], 1, CONSTRUCT), + new BigInteger( [9], 1, CONSTRUCT), + new BigInteger([10], 1, CONSTRUCT), + new BigInteger([11], 1, CONSTRUCT), + new BigInteger([12], 1, CONSTRUCT), + new BigInteger([13], 1, CONSTRUCT), + new BigInteger([14], 1, CONSTRUCT), + new BigInteger([15], 1, CONSTRUCT), + new BigInteger([16], 1, CONSTRUCT), + new BigInteger([17], 1, CONSTRUCT), + new BigInteger([18], 1, CONSTRUCT), + new BigInteger([19], 1, CONSTRUCT), + new BigInteger([20], 1, CONSTRUCT), + new BigInteger([21], 1, CONSTRUCT), + new BigInteger([22], 1, CONSTRUCT), + new BigInteger([23], 1, CONSTRUCT), + new BigInteger([24], 1, CONSTRUCT), + new BigInteger([25], 1, CONSTRUCT), + new BigInteger([26], 1, CONSTRUCT), + new BigInteger([27], 1, CONSTRUCT), + new BigInteger([28], 1, CONSTRUCT), + new BigInteger([29], 1, CONSTRUCT), + new BigInteger([30], 1, CONSTRUCT), + new BigInteger([31], 1, CONSTRUCT), + new BigInteger([32], 1, CONSTRUCT), + new BigInteger([33], 1, CONSTRUCT), + new BigInteger([34], 1, CONSTRUCT), + new BigInteger([35], 1, CONSTRUCT), + new BigInteger([36], 1, CONSTRUCT) +]; + +// Used for parsing/radix conversion +BigInteger.digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""); + +/* + Method: toString + Convert a to a string. + + When *base* is greater than 10, letters are upper case. + + Parameters: + + base - Optional base to represent the number in (default is base 10). + Must be between 2 and 36 inclusive, or an Error will be thrown. + + Returns: + + The string representation of the . +*/ +BigInteger.prototype.toString = function(base) { + base = +base || 10; + if (base < 2 || base > 36) { + throw new Error("illegal radix " + base + "."); + } + if (this._s === 0) { + return "0"; + } + if (base === 10) { + var str = this._s < 0 ? "-" : ""; + str += this._d[this._d.length - 1].toString(); + for (var i = this._d.length - 2; i >= 0; i--) { + var group = this._d[i].toString(); + while (group.length < BigInteger_base_log10) group = '0' + group; + str += group; + } + return str; + } + else { + var numerals = BigInteger.digits; + base = BigInteger.small[base]; + var sign = this._s; + + var n = this.abs(); + var digits = []; + var digit; + + while (n._s !== 0) { + var divmod = n.divRem(base); + n = divmod[0]; + digit = divmod[1]; + // TODO: This could be changed to unshift instead of reversing at the end. + // Benchmark both to compare speeds. + digits.push(numerals[digit.valueOf()]); + } + return (sign < 0 ? "-" : "") + digits.reverse().join(""); + } +}; + +// Verify strings for parsing +BigInteger.radixRegex = [ + /^$/, + /^$/, + /^[01]*$/, + /^[012]*$/, + /^[0-3]*$/, + /^[0-4]*$/, + /^[0-5]*$/, + /^[0-6]*$/, + /^[0-7]*$/, + /^[0-8]*$/, + /^[0-9]*$/, + /^[0-9aA]*$/, + /^[0-9abAB]*$/, + /^[0-9abcABC]*$/, + /^[0-9a-dA-D]*$/, + /^[0-9a-eA-E]*$/, + /^[0-9a-fA-F]*$/, + /^[0-9a-gA-G]*$/, + /^[0-9a-hA-H]*$/, + /^[0-9a-iA-I]*$/, + /^[0-9a-jA-J]*$/, + /^[0-9a-kA-K]*$/, + /^[0-9a-lA-L]*$/, + /^[0-9a-mA-M]*$/, + /^[0-9a-nA-N]*$/, + /^[0-9a-oA-O]*$/, + /^[0-9a-pA-P]*$/, + /^[0-9a-qA-Q]*$/, + /^[0-9a-rA-R]*$/, + /^[0-9a-sA-S]*$/, + /^[0-9a-tA-T]*$/, + /^[0-9a-uA-U]*$/, + /^[0-9a-vA-V]*$/, + /^[0-9a-wA-W]*$/, + /^[0-9a-xA-X]*$/, + /^[0-9a-yA-Y]*$/, + /^[0-9a-zA-Z]*$/ +]; + +/* + Function: parse + Parse a string into a . + + *base* is optional but, if provided, must be from 2 to 36 inclusive. If + *base* is not provided, it will be guessed based on the leading characters + of *s* as follows: + + - "0x" or "0X": *base* = 16 + - "0c" or "0C": *base* = 8 + - "0b" or "0B": *base* = 2 + - else: *base* = 10 + + If no base is provided, or *base* is 10, the number can be in exponential + form. For example, these are all valid: + + > BigInteger.parse("1e9"); // Same as "1000000000" + > BigInteger.parse("1.234*10^3"); // Same as 1234 + > BigInteger.parse("56789 * 10 ** -2"); // Same as 567 + + If any characters fall outside the range defined by the radix, an exception + will be thrown. + + Parameters: + + s - The string to parse. + base - Optional radix (default is to guess based on *s*). + + Returns: + + a instance. +*/ +BigInteger.parse = function(s, base) { + // Expands a number in exponential form to decimal form. + // expandExponential("-13.441*10^5") === "1344100"; + // expandExponential("1.12300e-1") === "0.112300"; + // expandExponential(1000000000000000000000000000000) === "1000000000000000000000000000000"; + function expandExponential(str) { + str = str.replace(/\s*[*xX]\s*10\s*(\^|\*\*)\s*/, "e"); + + return str.replace(/^([+\-])?(\d+)\.?(\d*)[eE]([+\-]?\d+)$/, function(x, s, n, f, c) { + c = +c; + var l = c < 0; + var i = n.length + c; + x = (l ? n : f).length; + c = ((c = Math.abs(c)) >= x ? c - x + l : 0); + var z = (new Array(c + 1)).join("0"); + var r = n + f; + return (s || "") + (l ? r = z + r : r += z).substr(0, i += l ? z.length : 0) + (i < r.length ? "." + r.substr(i) : ""); + }); + } + + s = s.toString(); + if (typeof base === "undefined" || +base === 10) { + s = expandExponential(s); + } + + var prefixRE; + if (typeof base === "undefined") { + prefixRE = '0[xcb]'; + } + else if (base == 16) { + prefixRE = '0x'; + } + else if (base == 8) { + prefixRE = '0c'; + } + else if (base == 2) { + prefixRE = '0b'; + } + else { + prefixRE = ''; + } + var parts = new RegExp('^([+\\-]?)(' + prefixRE + ')?([0-9a-z]*)(?:\\.\\d*)?$', 'i').exec(s); + if (parts) { + var sign = parts[1] || "+"; + var baseSection = parts[2] || ""; + var digits = parts[3] || ""; + + if (typeof base === "undefined") { + // Guess base + if (baseSection === "0x" || baseSection === "0X") { // Hex + base = 16; + } + else if (baseSection === "0c" || baseSection === "0C") { // Octal + base = 8; + } + else if (baseSection === "0b" || baseSection === "0B") { // Binary + base = 2; + } + else { + base = 10; + } + } + else if (base < 2 || base > 36) { + throw new Error("Illegal radix " + base + "."); + } + + base = +base; + + // Check for digits outside the range + if (!(BigInteger.radixRegex[base].test(digits))) { + throw new Error("Bad digit for radix " + base); + } + + // Strip leading zeros, and convert to array + digits = digits.replace(/^0+/, "").split(""); + if (digits.length === 0) { + return ZERO; + } + + // Get the sign (we know it's not zero) + sign = (sign === "-") ? -1 : 1; + + // Optimize 10 + if (base == 10) { + var d = []; + while (digits.length >= BigInteger_base_log10) { + d.push(parseInt(digits.splice(digits.length-BigInteger.base_log10, BigInteger.base_log10).join(''), 10)); + } + d.push(parseInt(digits.join(''), 10)); + return new BigInteger(d, sign, CONSTRUCT); + } + + // Do the conversion + var d = ZERO; + base = BigInteger.small[base]; + var small = BigInteger.small; + for (var i = 0; i < digits.length; i++) { + d = d.multiply(base).add(small[parseInt(digits[i], 36)]); + } + return new BigInteger(d._d, sign, CONSTRUCT); + } + else { + throw new Error("Invalid BigInteger format: " + s); + } +}; + +/* + Function: add + Add two . + + Parameters: + + n - The number to add to *this*. Will be converted to a . + + Returns: + + The numbers added together. + + See Also: + + , , , +*/ +BigInteger.prototype.add = function(n) { + if (this._s === 0) { + return BigInteger(n); + } + + n = BigInteger(n); + if (n._s === 0) { + return this; + } + if (this._s !== n._s) { + n = n.negate(); + return this.subtract(n); + } + + var a = this._d; + var b = n._d; + var al = a.length; + var bl = b.length; + var sum = new Array(Math.max(al, bl) + 1); + var size = Math.min(al, bl); + var carry = 0; + var digit; + + for (var i = 0; i < size; i++) { + digit = a[i] + b[i] + carry; + sum[i] = digit % BigInteger_base; + carry = (digit / BigInteger_base) | 0; + } + if (bl > al) { + a = b; + al = bl; + } + for (i = size; carry && i < al; i++) { + digit = a[i] + carry; + sum[i] = digit % BigInteger_base; + carry = (digit / BigInteger_base) | 0; + } + if (carry) { + sum[i] = carry; + } + + for ( ; i < al; i++) { + sum[i] = a[i]; + } + + return new BigInteger(sum, this._s, CONSTRUCT); +}; + +/* + Function: negate + Get the additive inverse of a . + + Returns: + + A with the same magnatude, but with the opposite sign. + + See Also: + + +*/ +BigInteger.prototype.negate = function() { + return new BigInteger(this._d, (-this._s) | 0, CONSTRUCT); +}; + +/* + Function: abs + Get the absolute value of a . + + Returns: + + A with the same magnatude, but always positive (or zero). + + See Also: + + +*/ +BigInteger.prototype.abs = function() { + return (this._s < 0) ? this.negate() : this; +}; + +/* + Function: subtract + Subtract two . + + Parameters: + + n - The number to subtract from *this*. Will be converted to a . + + Returns: + + The *n* subtracted from *this*. + + See Also: + + , , , +*/ +BigInteger.prototype.subtract = function(n) { + if (this._s === 0) { + return BigInteger(n).negate(); + } + + n = BigInteger(n); + if (n._s === 0) { + return this; + } + if (this._s !== n._s) { + n = n.negate(); + return this.add(n); + } + + var m = this; + // negative - negative => -|a| - -|b| => -|a| + |b| => |b| - |a| + if (this._s < 0) { + m = new BigInteger(n._d, 1, CONSTRUCT); + n = new BigInteger(this._d, 1, CONSTRUCT); + } + + // Both are positive => a - b + var sign = m.compareAbs(n); + if (sign === 0) { + return ZERO; + } + else if (sign < 0) { + // swap m and n + var t = n; + n = m; + m = t; + } + + // a > b + var a = m._d; + var b = n._d; + var al = a.length; + var bl = b.length; + var diff = new Array(al); // al >= bl since a > b + var borrow = 0; + var i; + var digit; + + for (i = 0; i < bl; i++) { + digit = a[i] - borrow - b[i]; + if (digit < 0) { + digit += BigInteger_base; + borrow = 1; + } + else { + borrow = 0; + } + diff[i] = digit; + } + for (i = bl; i < al; i++) { + digit = a[i] - borrow; + if (digit < 0) { + digit += BigInteger_base; + } + else { + diff[i++] = digit; + break; + } + diff[i] = digit; + } + for ( ; i < al; i++) { + diff[i] = a[i]; + } + + return new BigInteger(diff, sign, CONSTRUCT); +}; + +(function() { + function addOne(n, sign) { + var a = n._d; + var sum = a.slice(); + var carry = true; + var i = 0; + + while (true) { + var digit = (a[i] || 0) + 1; + sum[i] = digit % BigInteger_base; + if (digit <= BigInteger_base - 1) { + break; + } + ++i; + } + + return new BigInteger(sum, sign, CONSTRUCT); + } + + function subtractOne(n, sign) { + var a = n._d; + var sum = a.slice(); + var borrow = true; + var i = 0; + + while (true) { + var digit = (a[i] || 0) - 1; + if (digit < 0) { + sum[i] = digit + BigInteger_base; + } + else { + sum[i] = digit; + break; + } + ++i; + } + + return new BigInteger(sum, sign, CONSTRUCT); + } + + /* + Function: next + Get the next (add one). + + Returns: + + *this* + 1. + + See Also: + + , + */ + BigInteger.prototype.next = function() { + switch (this._s) { + case 0: + return ONE; + case -1: + return subtractOne(this, -1); + // case 1: + default: + return addOne(this, 1); + } + }; + + /* + Function: prev + Get the previous (subtract one). + + Returns: + + *this* - 1. + + See Also: + + , + */ + BigInteger.prototype.prev = function() { + switch (this._s) { + case 0: + return M_ONE; + case -1: + return addOne(this, -1); + // case 1: + default: + return subtractOne(this, 1); + } + }; +})(); + +/* + Function: compareAbs + Compare the absolute value of two . + + Calling is faster than calling twice, then . + + Parameters: + + n - The number to compare to *this*. Will be converted to a . + + Returns: + + -1, 0, or +1 if *|this|* is less than, equal to, or greater than *|n|*. + + See Also: + + , +*/ +BigInteger.prototype.compareAbs = function(n) { + if (this === n) { + return 0; + } + + if (!(n instanceof BigInteger)) { + if (!isFinite(n)) { + return(isNaN(n) ? n : -1); + } + n = BigInteger(n); + } + + if (this._s === 0) { + return (n._s !== 0) ? -1 : 0; + } + if (n._s === 0) { + return 1; + } + + var l = this._d.length; + var nl = n._d.length; + if (l < nl) { + return -1; + } + else if (l > nl) { + return 1; + } + + var a = this._d; + var b = n._d; + for (var i = l-1; i >= 0; i--) { + if (a[i] !== b[i]) { + return a[i] < b[i] ? -1 : 1; + } + } + + return 0; +}; + +/* + Function: compare + Compare two . + + Parameters: + + n - The number to compare to *this*. Will be converted to a . + + Returns: + + -1, 0, or +1 if *this* is less than, equal to, or greater than *n*. + + See Also: + + , , , +*/ +BigInteger.prototype.compare = function(n) { + if (this === n) { + return 0; + } + + n = BigInteger(n); + + if (this._s === 0) { + return -n._s; + } + + if (this._s === n._s) { // both positive or both negative + var cmp = this.compareAbs(n); + return cmp * this._s; + } + else { + return this._s; + } +}; + +/* + Function: isUnit + Return true iff *this* is either 1 or -1. + + Returns: + + true if *this* compares equal to or . + + See Also: + + , , , , , + , +*/ +BigInteger.prototype.isUnit = function() { + return this === ONE || + this === M_ONE || + (this._d.length === 1 && this._d[0] === 1); +}; + +/* + Function: multiply + Multiply two . + + Parameters: + + n - The number to multiply *this* by. Will be converted to a + . + + Returns: + + The numbers multiplied together. + + See Also: + + , , , +*/ +BigInteger.prototype.multiply = function(n) { + // TODO: Consider adding Karatsuba multiplication for large numbers + if (this._s === 0) { + return ZERO; + } + + n = BigInteger(n); + if (n._s === 0) { + return ZERO; + } + if (this.isUnit()) { + if (this._s < 0) { + return n.negate(); + } + return n; + } + if (n.isUnit()) { + if (n._s < 0) { + return this.negate(); + } + return this; + } + if (this === n) { + return this.square(); + } + + var r = (this._d.length >= n._d.length); + var a = (r ? this : n)._d; // a will be longer than b + var b = (r ? n : this)._d; + var al = a.length; + var bl = b.length; + + var pl = al + bl; + var partial = new Array(pl); + var i; + for (i = 0; i < pl; i++) { + partial[i] = 0; + } + + for (i = 0; i < bl; i++) { + var carry = 0; + var bi = b[i]; + var jlimit = al + i; + var digit; + for (var j = i; j < jlimit; j++) { + digit = partial[j] + bi * a[j - i] + carry; + carry = (digit / BigInteger_base) | 0; + partial[j] = (digit % BigInteger_base) | 0; + } + if (carry) { + digit = partial[j] + carry; + carry = (digit / BigInteger_base) | 0; + partial[j] = digit % BigInteger_base; + } + } + return new BigInteger(partial, this._s * n._s, CONSTRUCT); +}; + +// Multiply a BigInteger by a single-digit native number +// Assumes that this and n are >= 0 +// This is not really intended to be used outside the library itself +BigInteger.prototype.multiplySingleDigit = function(n) { + if (n === 0 || this._s === 0) { + return ZERO; + } + if (n === 1) { + return this; + } + + var digit; + if (this._d.length === 1) { + digit = this._d[0] * n; + if (digit >= BigInteger_base) { + return new BigInteger([(digit % BigInteger_base)|0, + (digit / BigInteger_base)|0], 1, CONSTRUCT); + } + return new BigInteger([digit], 1, CONSTRUCT); + } + + if (n === 2) { + return this.add(this); + } + if (this.isUnit()) { + return new BigInteger([n], 1, CONSTRUCT); + } + + var a = this._d; + var al = a.length; + + var pl = al + 1; + var partial = new Array(pl); + for (var i = 0; i < pl; i++) { + partial[i] = 0; + } + + var carry = 0; + for (var j = 0; j < al; j++) { + digit = n * a[j] + carry; + carry = (digit / BigInteger_base) | 0; + partial[j] = (digit % BigInteger_base) | 0; + } + if (carry) { + partial[j] = carry; + } + + return new BigInteger(partial, 1, CONSTRUCT); +}; + +/* + Function: square + Multiply a by itself. + + This is slightly faster than regular multiplication, since it removes the + duplicated multiplcations. + + Returns: + + > this.multiply(this) + + See Also: + +*/ +BigInteger.prototype.square = function() { + // Normally, squaring a 10-digit number would take 100 multiplications. + // Of these 10 are unique diagonals, of the remaining 90 (100-10), 45 are repeated. + // This procedure saves (N*(N-1))/2 multiplications, (e.g., 45 of 100 multiplies). + // Based on code by Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org + + if (this._s === 0) { + return ZERO; + } + if (this.isUnit()) { + return ONE; + } + + var digits = this._d; + var length = digits.length; + var imult1 = new Array(length + length + 1); + var product, carry, k; + var i; + + // Calculate diagonal + for (i = 0; i < length; i++) { + k = i * 2; + product = digits[i] * digits[i]; + carry = (product / BigInteger_base) | 0; + imult1[k] = product % BigInteger_base; + imult1[k + 1] = carry; + } + + // Calculate repeating part + for (i = 0; i < length; i++) { + carry = 0; + k = i * 2 + 1; + for (var j = i + 1; j < length; j++, k++) { + product = digits[j] * digits[i] * 2 + imult1[k] + carry; + carry = (product / BigInteger_base) | 0; + imult1[k] = product % BigInteger_base; + } + k = length + i; + var digit = carry + imult1[k]; + carry = (digit / BigInteger_base) | 0; + imult1[k] = digit % BigInteger_base; + imult1[k + 1] += carry; + } + + return new BigInteger(imult1, 1, CONSTRUCT); +}; + +/* + Function: quotient + Divide two and truncate towards zero. + + throws an exception if *n* is zero. + + Parameters: + + n - The number to divide *this* by. Will be converted to a . + + Returns: + + The *this* / *n*, truncated to an integer. + + See Also: + + , , , , +*/ +BigInteger.prototype.quotient = function(n) { + return this.divRem(n)[0]; +}; + +/* + Function: divide + Deprecated synonym for . +*/ +BigInteger.prototype.divide = BigInteger.prototype.quotient; + +/* + Function: remainder + Calculate the remainder of two . + + throws an exception if *n* is zero. + + Parameters: + + n - The remainder after *this* is divided *this* by *n*. Will be + converted to a . + + Returns: + + *this* % *n*. + + See Also: + + , +*/ +BigInteger.prototype.remainder = function(n) { + return this.divRem(n)[1]; +}; + +/* + Function: divRem + Calculate the integer quotient and remainder of two . + + throws an exception if *n* is zero. + + Parameters: + + n - The number to divide *this* by. Will be converted to a . + + Returns: + + A two-element array containing the quotient and the remainder. + + > a.divRem(b) + + is exactly equivalent to + + > [a.quotient(b), a.remainder(b)] + + except it is faster, because they are calculated at the same time. + + See Also: + + , +*/ +BigInteger.prototype.divRem = function(n) { + n = BigInteger(n); + if (n._s === 0) { + throw new Error("Divide by zero"); + } + if (this._s === 0) { + return [ZERO, ZERO]; + } + if (n._d.length === 1) { + return this.divRemSmall(n._s * n._d[0]); + } + + // Test for easy cases -- |n1| <= |n2| + switch (this.compareAbs(n)) { + case 0: // n1 == n2 + return [this._s === n._s ? ONE : M_ONE, ZERO]; + case -1: // |n1| < |n2| + return [ZERO, this]; + } + + var sign = this._s * n._s; + var a = n.abs(); + var b_digits = this._d; + var b_index = b_digits.length; + var digits = n._d.length; + var quot = []; + var guess; + + var part = new BigInteger([], 0, CONSTRUCT); + + while (b_index) { + part._d.unshift(b_digits[--b_index]); + part = new BigInteger(part._d, 1, CONSTRUCT); + + if (part.compareAbs(n) < 0) { + quot.push(0); + continue; + } + if (part._s === 0) { + guess = 0; + } + else { + var xlen = part._d.length, ylen = a._d.length; + var highx = part._d[xlen-1]*BigInteger_base + part._d[xlen-2]; + var highy = a._d[ylen-1]*BigInteger_base + a._d[ylen-2]; + if (part._d.length > a._d.length) { + // The length of part._d can either match a._d length, + // or exceed it by one. + highx = (highx+1)*BigInteger_base; + } + guess = Math.ceil(highx/highy); + } + do { + var check = a.multiplySingleDigit(guess); + if (check.compareAbs(part) <= 0) { + break; + } + guess--; + } while (guess); + + quot.push(guess); + if (!guess) { + continue; + } + var diff = part.subtract(check); + part._d = diff._d.slice(); + } + + return [new BigInteger(quot.reverse(), sign, CONSTRUCT), + new BigInteger(part._d, this._s, CONSTRUCT)]; +}; + +// Throws an exception if n is outside of (-BigInteger.base, -1] or +// [1, BigInteger.base). It's not necessary to call this, since the +// other division functions will call it if they are able to. +BigInteger.prototype.divRemSmall = function(n) { + var r; + n = +n; + if (n === 0) { + throw new Error("Divide by zero"); + } + + var n_s = n < 0 ? -1 : 1; + var sign = this._s * n_s; + n = Math.abs(n); + + if (n < 1 || n >= BigInteger_base) { + throw new Error("Argument out of range"); + } + + if (this._s === 0) { + return [ZERO, ZERO]; + } + + if (n === 1 || n === -1) { + return [(sign === 1) ? this.abs() : new BigInteger(this._d, sign, CONSTRUCT), ZERO]; + } + + // 2 <= n < BigInteger_base + + // divide a single digit by a single digit + if (this._d.length === 1) { + var q = new BigInteger([(this._d[0] / n) | 0], 1, CONSTRUCT); + r = new BigInteger([(this._d[0] % n) | 0], 1, CONSTRUCT); + if (sign < 0) { + q = q.negate(); + } + if (this._s < 0) { + r = r.negate(); + } + return [q, r]; + } + + var digits = this._d.slice(); + var quot = new Array(digits.length); + var part = 0; + var diff = 0; + var i = 0; + var guess; + + while (digits.length) { + part = part * BigInteger_base + digits[digits.length - 1]; + if (part < n) { + quot[i++] = 0; + digits.pop(); + diff = BigInteger_base * diff + part; + continue; + } + if (part === 0) { + guess = 0; + } + else { + guess = (part / n) | 0; + } + + var check = n * guess; + diff = part - check; + quot[i++] = guess; + if (!guess) { + digits.pop(); + continue; + } + + digits.pop(); + part = diff; + } + + r = new BigInteger([diff], 1, CONSTRUCT); + if (this._s < 0) { + r = r.negate(); + } + return [new BigInteger(quot.reverse(), sign, CONSTRUCT), r]; +}; + +/* + Function: isEven + Return true iff *this* is divisible by two. + + Note that is even. + + Returns: + + true if *this* is even, false otherwise. + + See Also: + + +*/ +BigInteger.prototype.isEven = function() { + var digits = this._d; + return this._s === 0 || digits.length === 0 || (digits[0] % 2) === 0; +}; + +/* + Function: isOdd + Return true iff *this* is not divisible by two. + + Returns: + + true if *this* is odd, false otherwise. + + See Also: + + +*/ +BigInteger.prototype.isOdd = function() { + return !this.isEven(); +}; + +/* + Function: sign + Get the sign of a . + + Returns: + + * -1 if *this* < 0 + * 0 if *this* == 0 + * +1 if *this* > 0 + + See Also: + + , , , , +*/ +BigInteger.prototype.sign = function() { + return this._s; +}; + +/* + Function: isPositive + Return true iff *this* > 0. + + Returns: + + true if *this*.compare() == 1. + + See Also: + + , , , , , +*/ +BigInteger.prototype.isPositive = function() { + return this._s > 0; +}; + +/* + Function: isNegative + Return true iff *this* < 0. + + Returns: + + true if *this*.compare() == -1. + + See Also: + + , , , , , +*/ +BigInteger.prototype.isNegative = function() { + return this._s < 0; +}; + +/* + Function: isZero + Return true iff *this* == 0. + + Returns: + + true if *this*.compare() == 0. + + See Also: + + , , , , +*/ +BigInteger.prototype.isZero = function() { + return this._s === 0; +}; + +/* + Function: exp10 + Multiply a by a power of 10. + + This is equivalent to, but faster than + + > if (n >= 0) { + > return this.multiply(BigInteger("1e" + n)); + > } + > else { // n <= 0 + > return this.quotient(BigInteger("1e" + -n)); + > } + + Parameters: + + n - The power of 10 to multiply *this* by. *n* is converted to a + javascipt number and must be no greater than + (0x7FFFFFFF), or an exception will be thrown. + + Returns: + + *this* * (10 ** *n*), truncated to an integer if necessary. + + See Also: + + , +*/ +BigInteger.prototype.exp10 = function(n) { + n = +n; + if (n === 0) { + return this; + } + if (Math.abs(n) > Number(MAX_EXP)) { + throw new Error("exponent too large in BigInteger.exp10"); + } + // Optimization for this == 0. This also keeps us from having to trim zeros in the positive n case + if (this._s === 0) { + return ZERO; + } + if (n > 0) { + var k = new BigInteger(this._d.slice(), this._s, CONSTRUCT); + + for (; n >= BigInteger_base_log10; n -= BigInteger_base_log10) { + k._d.unshift(0); + } + if (n == 0) + return k; + k._s = 1; + k = k.multiplySingleDigit(Math.pow(10, n)); + return (this._s < 0 ? k.negate() : k); + } else if (-n >= this._d.length*BigInteger_base_log10) { + return ZERO; + } else { + var k = new BigInteger(this._d.slice(), this._s, CONSTRUCT); + + for (n = -n; n >= BigInteger_base_log10; n -= BigInteger_base_log10) { + k._d.shift(); + } + return (n == 0) ? k : k.divRemSmall(Math.pow(10, n))[0]; + } +}; + +/* + Function: pow + Raise a to a power. + + In this implementation, 0**0 is 1. + + Parameters: + + n - The exponent to raise *this* by. *n* must be no greater than + (0x7FFFFFFF), or an exception will be thrown. + + Returns: + + *this* raised to the *nth* power. + + See Also: + + +*/ +BigInteger.prototype.pow = function(n) { + if (this.isUnit()) { + if (this._s > 0) { + return this; + } + else { + return BigInteger(n).isOdd() ? this : this.negate(); + } + } + + n = BigInteger(n); + if (n._s === 0) { + return ONE; + } + else if (n._s < 0) { + if (this._s === 0) { + throw new Error("Divide by zero"); + } + else { + return ZERO; + } + } + if (this._s === 0) { + return ZERO; + } + if (n.isUnit()) { + return this; + } + + if (n.compareAbs(MAX_EXP) > 0) { + throw new Error("exponent too large in BigInteger.pow"); + } + var x = this; + var aux = ONE; + var two = BigInteger.small[2]; + + while (n.isPositive()) { + if (n.isOdd()) { + aux = aux.multiply(x); + if (n.isUnit()) { + return aux; + } + } + x = x.square(); + n = n.quotient(two); + } + + return aux; +}; + +/* + Function: modPow + Raise a to a power (mod m). + + Because it is reduced by a modulus, is not limited by + like . + + Parameters: + + exponent - The exponent to raise *this* by. Must be positive. + modulus - The modulus. + + Returns: + + *this* ^ *exponent* (mod *modulus*). + + See Also: + + , +*/ +BigInteger.prototype.modPow = function(exponent, modulus) { + var result = ONE; + var base = this; + + while (exponent.isPositive()) { + if (exponent.isOdd()) { + result = result.multiply(base).remainder(modulus); + } + + exponent = exponent.quotient(BigInteger.small[2]); + if (exponent.isPositive()) { + base = base.square().remainder(modulus); + } + } + + return result; +}; + +/* + Function: log + Get the natural logarithm of a as a native JavaScript number. + + This is equivalent to + + > Math.log(this.toJSValue()) + + but handles values outside of the native number range. + + Returns: + + log( *this* ) + + See Also: + + +*/ +BigInteger.prototype.log = function() { + switch (this._s) { + case 0: return -Infinity; + case -1: return NaN; + default: // Fall through. + } + + var l = this._d.length; + + if (l*BigInteger_base_log10 < 30) { + return Math.log(this.valueOf()); + } + + var N = Math.ceil(30/BigInteger_base_log10); + var firstNdigits = this._d.slice(l - N); + return Math.log((new BigInteger(firstNdigits, 1, CONSTRUCT)).valueOf()) + (l - N) * Math.log(BigInteger_base); +}; + +/* + Function: valueOf + Convert a to a native JavaScript integer. + + This is called automatically by JavaScipt to convert a to a + native value. + + Returns: + + > parseInt(this.toString(), 10) + + See Also: + + , +*/ +BigInteger.prototype.valueOf = function() { + return parseInt(this.toString(), 10); +}; + +/* + Function: toJSValue + Convert a to a native JavaScript integer. + + This is the same as valueOf, but more explicitly named. + + Returns: + + > parseInt(this.toString(), 10) + + See Also: + + , +*/ +BigInteger.prototype.toJSValue = function() { + return parseInt(this.toString(), 10); +}; + +var MAX_EXP = BigInteger(0x7FFFFFFF); +// Constant: MAX_EXP +// The largest exponent allowed in and (0x7FFFFFFF or 2147483647). +BigInteger.MAX_EXP = MAX_EXP; + +(function() { + function makeUnary(fn) { + return function(a) { + return fn.call(BigInteger(a)); + }; + } + + function makeBinary(fn) { + return function(a, b) { + return fn.call(BigInteger(a), BigInteger(b)); + }; + } + + function makeTrinary(fn) { + return function(a, b, c) { + return fn.call(BigInteger(a), BigInteger(b), BigInteger(c)); + }; + } + + (function() { + var i, fn; + var unary = "toJSValue,isEven,isOdd,sign,isZero,isNegative,abs,isUnit,square,negate,isPositive,toString,next,prev,log".split(","); + var binary = "compare,remainder,divRem,subtract,add,quotient,divide,multiply,pow,compareAbs".split(","); + var trinary = ["modPow"]; + + for (i = 0; i < unary.length; i++) { + fn = unary[i]; + BigInteger[fn] = makeUnary(BigInteger.prototype[fn]); + } + + for (i = 0; i < binary.length; i++) { + fn = binary[i]; + BigInteger[fn] = makeBinary(BigInteger.prototype[fn]); + } + + for (i = 0; i < trinary.length; i++) { + fn = trinary[i]; + BigInteger[fn] = makeTrinary(BigInteger.prototype[fn]); + } + + BigInteger.exp10 = function(x, n) { + return BigInteger(x).exp10(n); + }; + })(); +})(); + +exports.BigInteger = BigInteger; +})(typeof exports !== 'undefined' ? exports : this); + +function sumStrings(a, b) { + return exports.BigInteger(a).add(exports.BigInteger(b)).toString(); +} \ No newline at end of file diff --git a/summing-a-numbers-digits/README.md b/summing-a-numbers-digits/README.md new file mode 100644 index 0000000..c252889 --- /dev/null +++ b/summing-a-numbers-digits/README.md @@ -0,0 +1,39 @@ +# Summing a number's digits +[*View on Codewars*](https://www.codewars.com/kata/summing-a-numbers-digits) + +Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example: + +```javascript + sumDigits(10); // Returns 1 + sumDigits(99); // Returns 18 + sumDigits(-32); // Returns 5 +``` +```ruby + sumDigits 10 # Returns 1 + sumDigits 99 # Returns 18 + sumDigits -32 # Returns 5 +``` +```python + sumDigits(10) # Returns 1 + sumDigits(99) # Returns 18 + sumDigits(-32) # Returns 5 +``` +```coffeescript + sumDigits 10 # Returns 1 + sumDigits 99 # Returns 18 + sumDigits -32 # Returns 5 +``` +```groovy + Kata.sumDigits(10) // Returns 1 + Kata.sumDigits(99) // Returns 18 + Kata.sumDigits(-32) // Returns 5 +``` + +Let's assume that all numbers in the input will be integer values. + + +## Timeline +- Created: 2014-02-06 +- Published: 2014-02-06 +- Approved: 2014-02-07 +- Completed: 2018-02-06 \ No newline at end of file diff --git a/summing-a-numbers-digits/javascript/1/summing-a-numbers-digits.js b/summing-a-numbers-digits/javascript/1/summing-a-numbers-digits.js new file mode 100644 index 0000000..3964f07 --- /dev/null +++ b/summing-a-numbers-digits/javascript/1/summing-a-numbers-digits.js @@ -0,0 +1,7 @@ +function sumDigits(number) { + return (function f(n, sum) { + return n + ? f(Math.trunc(n / 10), sum + n % 10) + : sum + })(Math.abs(number), 0) +} \ No newline at end of file diff --git a/take-a-ten-minute-walk/README.md b/take-a-ten-minute-walk/README.md new file mode 100644 index 0000000..2e59ece --- /dev/null +++ b/take-a-ten-minute-walk/README.md @@ -0,0 +1,15 @@ +# Take a Ten Minute Walk +[*View on Codewars*](https://www.codewars.com/kata/take-a-ten-minute-walk) + +You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You know it takes you one minute to traverse one city block, so create a function that will return **true** if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return **false** otherwise. + + +> **Note**: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!). + + + +## Timeline +- Created: 2015-02-10 +- Published: 2015-02-10 +- Approved: 2015-03-10 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/take-a-ten-minute-walk/java/1/TenMinWalk.java b/take-a-ten-minute-walk/java/1/TenMinWalk.java new file mode 100644 index 0000000..2046744 --- /dev/null +++ b/take-a-ten-minute-walk/java/1/TenMinWalk.java @@ -0,0 +1,29 @@ +public class TenMinWalk { + public static boolean isValid(char[] walk) { + if (walk.length != 10) { + return false; + } + + int x = 0, y = 0; + for (char direction : walk) { + switch (direction) { + case 'n': + y++; + break; + case 'e': + x++; + break; + case 's': + y--; + break; + case 'w': + x--; + break; + default: + return false; + } + } + + return (x | y) == 0; + } +} \ No newline at end of file diff --git a/tea-for-two/README.md b/tea-for-two/README.md new file mode 100644 index 0000000..ac7aaee --- /dev/null +++ b/tea-for-two/README.md @@ -0,0 +1,22 @@ +# Tea for two +[*View on Codewars*](https://www.codewars.com/kata/tea-for-two) + +Tea for two! + +Given a string or number write a function tea42 that takes as input a string or number and returns a string where every '2' charcter or digit has been replaced with a t. + + +```javascript +tea42('coffee') //should return 'coffee' +tea42('tea') //should return 'tea' +tea42('2ea') //should return 'tea' +tea42(9022) //should return '90tt' +tea42(5676765) //should return '5676765' +tea42('2u2u') //should return 'tutu' +``` + +## Timeline +- Created: 2015-05-19 +- Published: 2015-05-19 +- Approved: 2015-06-05 +- Completed: 2015-05-23 \ No newline at end of file diff --git a/tea-for-two/javascript/1/tea-for-two.js b/tea-for-two/javascript/1/tea-for-two.js new file mode 100644 index 0000000..60ee215 --- /dev/null +++ b/tea-for-two/javascript/1/tea-for-two.js @@ -0,0 +1,3 @@ +function tea42(string) { + return String(string).replace(/2/g,'t') +}; \ No newline at end of file diff --git a/testing-1-2-3/README.md b/testing-1-2-3/README.md new file mode 100644 index 0000000..9504b08 --- /dev/null +++ b/testing-1-2-3/README.md @@ -0,0 +1,42 @@ +# Testing 1-2-3 +[*View on Codewars*](https://www.codewars.com/kata/testing-1-2-3) + +Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering. + +Write a function which takes a list of strings and returns each line prepended by the correct number. + +The numbering starts at 1. The format is `n: string`. Notice the colon and space in between. + +**Examples:** + +```ruby +number [] # => [] +number ["a", "b", "c"] # => ["1: a", "2: b", "3: c"] +``` + +```javascript +number([]) // => [] +number(["a", "b", "c"]) // => ["1: a", "2: b", "3: c"] +``` + +```python +number([]) # => [] +number(["a", "b", "c"]) # => ["1: a", "2: b", "3: c"] +``` + +```java +number(Arrays.asList()) # => [] +number(Arrays.asList("a", "b", "c")) // => ["1: a", "2: b", "3: c"] +``` + +```haskell +number [] -- returns [] +number ["a", "b", "c"] -- returns ["1: a", "2: b", "3: c"] +``` + + +## Timeline +- Created: 2015-01-21 +- Published: 2015-01-21 +- Approved: null +- Completed: 2015-05-09 \ No newline at end of file diff --git a/testing-1-2-3/java/1/LineNumbering.java b/testing-1-2-3/java/1/LineNumbering.java new file mode 100644 index 0000000..2b19ab1 --- /dev/null +++ b/testing-1-2-3/java/1/LineNumbering.java @@ -0,0 +1,12 @@ +import java.util.*; + +class LineNumbering { + + static List number(List lines) { + for (int i = 0, m = lines.size(); i < m; i++) { + lines.set(i, String.format("%d: %s", i + 1, lines.get(i))); + } + return lines; + } + +} \ No newline at end of file diff --git a/testing-1-2-3/javascript/1/testing-1-2-3.js b/testing-1-2-3/javascript/1/testing-1-2-3.js new file mode 100644 index 0000000..5913824 --- /dev/null +++ b/testing-1-2-3/javascript/1/testing-1-2-3.js @@ -0,0 +1 @@ +const number = array => array.map((e, i) => `${i + 1}: ${e}`) \ No newline at end of file diff --git a/the-hashtag-generator/README.md b/the-hashtag-generator/README.md new file mode 100644 index 0000000..b5ea00e --- /dev/null +++ b/the-hashtag-generator/README.md @@ -0,0 +1,24 @@ +# The Hashtag Generator +[*View on Codewars*](https://www.codewars.com/kata/the-hashtag-generator) + +The marketing team are spending way too much time typing in hashtags. +Let's help them with out own Hashtag Generator! + +Here's the deal: + +- If the final result is longer than 140 chars it must return false. +- If the input is a empty string it must return false. +- It must start with a hashtag (#). +- All words must have their first letter capitalized. + +Example Input to Output: + +" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata" + +" Hello World " => "#HelloWorld" + +## Timeline +- Created: 2013-09-26 +- Published: 2013-09-26 +- Approved: null +- Completed: 2015-05-24 \ No newline at end of file diff --git a/the-hashtag-generator/javascript/1/the-hashtag-generator.js b/the-hashtag-generator/javascript/1/the-hashtag-generator.js new file mode 100644 index 0000000..862ff40 --- /dev/null +++ b/the-hashtag-generator/javascript/1/the-hashtag-generator.js @@ -0,0 +1,7 @@ +function generateHashtag(str) { + if (!str.length) return false; + var hash = '#' + str.trim().split(' ').map(function(word) { + return word[0].toUpperCase() + word.substring(1); + }).join(''); + return hash.length > 140 ? false : hash; +} \ No newline at end of file diff --git a/the-look-and-say-sequence/README.md b/the-look-and-say-sequence/README.md new file mode 100644 index 0000000..133b304 --- /dev/null +++ b/the-look-and-say-sequence/README.md @@ -0,0 +1,37 @@ +# The Look and Say sequence +[*View on Codewars*](https://www.codewars.com/kata/the-look-and-say-sequence) + +From wikipedia: + + +In mathematics, the look-and-say sequence is the sequence of integers beginning as follows: + + 1, 11, 21, 1211, 111221, 312211 ... + +To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example: + + 1 is read off as "one 1" or 11. + 11 is read off as "two 1s" or 21. + 21 is read off as "one 2, then one 1" or 1211. + 1211 is read off as "one 1, then one 2, then two 1s" or 111221. + 111221 is read off as "three 1s, then two 2s, then one 1" or 312211. + + +Your mission is to write a function getLines, which takes an integer "n" as parameter, and returns a comma separated list of the first "n" terms of the sequence. For 0, negative, or NaN parameters, -1 shall be returned. + +for example: + +```javascript +getLines(2); // logs "1,11" +getLines(3); // logs "1,11,21" +getLines(5); // logs "1,11,21,1211,111221" + +``` + + + +## Timeline +- Created: 2013-10-20 +- Published: 2013-10-20 +- Approved: null +- Completed: 2015-05-25 \ No newline at end of file diff --git a/the-look-and-say-sequence/javascript/1/the-look-and-say-sequence.js b/the-look-and-say-sequence/javascript/1/the-look-and-say-sequence.js new file mode 100644 index 0000000..78e3bda --- /dev/null +++ b/the-look-and-say-sequence/javascript/1/the-look-and-say-sequence.js @@ -0,0 +1,13 @@ +function getLines(n) { + if (isNaN(n) || n <= 0) { + return -1; + } + var lines = new Array(n); + lines[0] = '1'; + for (var i = 1; i < n; i++) { + lines[i] = lines[i - 1].match(/(.)\1*/g).map(function(m) { + return m.length + m[0]; + }).join(''); + } + return lines.join(); +} \ No newline at end of file diff --git a/the-millionth-fibonacci-kata/README.md b/the-millionth-fibonacci-kata/README.md new file mode 100644 index 0000000..8e9d67c --- /dev/null +++ b/the-millionth-fibonacci-kata/README.md @@ -0,0 +1,38 @@ +# The Millionth Fibonacci Kata +[*View on Codewars*](https://www.codewars.com/kata/the-millionth-fibonacci-kata) + +The year is 1214. One night, Pope Innocent III awakens to find the the archangel Gabriel floating before him. Gabriel thunders to the pope: + +> Gather all of the learned men in Pisa, especially Leonardo Fibonacci. In order for the crusades in the holy lands to be successful, these men must calculate the *millionth* number in Fibonacci's recurrence. Fail to do this, and your armies will never reclaim the holy land. It is His will. + +The angel then vanishes in an explosion of white light. + +Pope Innocent III sits in his bed in awe. *How much is a million?* he thinks to himself. He never was very good at math. + +He tries writing the number down, but because everyone in Europe is still using Roman numerals at this moment in history, he cannot represent this number. If he only knew about the invention of zero, it might make this sort of thing easier. + +He decides to go back to bed. He consoles himself, *The Lord would never challenge me thus; this must have been some deceit by the devil. A pretty horrendous nightmare, to be sure.* + +Pope Innocent III's armies would go on to conquer Constantinople (now Istanbul), but they would never reclaim the holy land as he desired. + +--------------------------- + +In this kata you will have to calculate `fib(n)` where: + + fib(0) := 0 + fib(1) := 1 + fin(n + 2) := fib(n + 1) + fib(n) + +Write an algorithm that can handle *n* where 1000000 ≤ *n* ≤ 1500000. + +Your algorithm must output the exact integer answer, to full precision. Also, it must correctly handle negative numbers as input. + +**HINT I**: Can you rearrange the equation `fib(n + 2) = fib(n + 1) + fib(n)` to find `fib(n)` if you already know `fin(n + 1)` and `fib(n + 2)`? Use this to reason what value `fib` has to have for negative values. + +**HINT II**: See http://mitpress.mit.edu/sicp/chapter1/node15.html + +## Timeline +- Created: 2014-07-26 +- Published: 2014-07-26 +- Approved: 2014-09-04 +- Completed: 2015-05-04 \ No newline at end of file diff --git a/the-millionth-fibonacci-kata/java/1/Fibonacci.java b/the-millionth-fibonacci-kata/java/1/Fibonacci.java new file mode 100644 index 0000000..bff7f82 --- /dev/null +++ b/the-millionth-fibonacci-kata/java/1/Fibonacci.java @@ -0,0 +1,25 @@ +import java.math.BigInteger; + +public class Fibonacci { + public static BigInteger fib(final BigInteger n) { + final int m = n.intValueExact(); + final int absM = Math.abs(m); + BigInteger lastFibonacci = BigInteger.ZERO; + BigInteger fibonacci = BigInteger.ONE; + for (int i = Integer.SIZE - Integer.numberOfLeadingZeros(absM) - 1; i >= 0; i--) { + { + final BigInteger newLastFibonacci = lastFibonacci.multiply(fibonacci.shiftLeft(1).subtract(lastFibonacci)); + final BigInteger newFibonacci = lastFibonacci.multiply(lastFibonacci).add(fibonacci.multiply(fibonacci)); + lastFibonacci = newLastFibonacci; + fibonacci = newFibonacci; + } + + if ((absM >>> i) % 2 != 0) { + final BigInteger newFibonacci = lastFibonacci.add(fibonacci); + lastFibonacci = fibonacci; + fibonacci = newFibonacci; + } + } + return m < 0 && m % 2 == 0 ? lastFibonacci.negate() : lastFibonacci; + } +} \ No newline at end of file diff --git a/the-prediction/README.md b/the-prediction/README.md new file mode 100644 index 0000000..0ab994e --- /dev/null +++ b/the-prediction/README.md @@ -0,0 +1,10 @@ +# The Prediction +[*View on Codewars*](https://www.codewars.com/kata/the-prediction) + +How good are your prediction skills? Can you find our magic number? + +## Timeline +- Created: 2013-10-23 +- Published: 2013-10-23 +- Approved: null +- Completed: 2015-05-24 \ No newline at end of file diff --git a/the-prediction/javascript/1/the-prediction.js b/the-prediction/javascript/1/the-prediction.js new file mode 100644 index 0000000..3416545 --- /dev/null +++ b/the-prediction/javascript/1/the-prediction.js @@ -0,0 +1,4 @@ +function predict() { + return 0; +} +Math.random = function() { return NaN; }; \ No newline at end of file diff --git a/this-is-a-problem/README.md b/this-is-a-problem/README.md new file mode 100644 index 0000000..f84ef1b --- /dev/null +++ b/this-is-a-problem/README.md @@ -0,0 +1,46 @@ +# "this" is a problem +[*View on Codewars*](https://www.codewars.com/kata/this-is-a-problem) + +We want to create a constructor function 'NameMe', which takes first name and last name as parameters. The function combines the first and last names and saves the value in "name" property. + +We already implemented that function, but when we actually run the code, the "name" property is accessible, but the "firstName" and "lastName" is not accessible. All the properties should be accessible. Can you find what's wrong with it? +A test fixture is also available +```javascript +function NameMe(first, last) { + this.firstName = first; + this.lastName = last; + return {name: this.firstName + ' ' + this.lastName}; +} + +var n = new NameMe('John', 'Doe'); +n.firstName //Expected: John +n.lastName //Expected: Doe +n.name //Expected: John Doe + +``` + +```java +public class NameMe { + private String firstName; + private String lastName; + private String fullName; + + public NameMe(String first, String last) { + this.firstName = first; + this.lastName = last; + } + } + +NameMe nameMe = new NameMe("John", "Doe"); +nameMe.getFirstName(); //Expected: John +nameMe.getLastName(); //Expected: Doe +nameMe.getFullName(); //Expected: John Doe + + +``` + +## Timeline +- Created: 2014-12-01 +- Published: 2014-12-01 +- Approved: 2014-12-27 +- Completed: 2015-05-21 \ No newline at end of file diff --git a/this-is-a-problem/java/1/NameMe.java b/this-is-a-problem/java/1/NameMe.java new file mode 100644 index 0000000..2d3b5a7 --- /dev/null +++ b/this-is-a-problem/java/1/NameMe.java @@ -0,0 +1,23 @@ +public class NameMe { + final String firstName; + final String lastName; + final String fullName; + + NameMe(String first, String last) { + firstName = first; + lastName = last; + fullName = first + ' ' + last; + } + + String getFirstName() { + return firstName; + } + + String getLastName() { + return lastName; + } + + String getFullName() { + return fullName; + } + } \ No newline at end of file diff --git a/this-is-a-problem/javascript/1/this-is-a-problem.js b/this-is-a-problem/javascript/1/this-is-a-problem.js new file mode 100644 index 0000000..e4d9cf9 --- /dev/null +++ b/this-is-a-problem/javascript/1/this-is-a-problem.js @@ -0,0 +1,5 @@ +function NameMe(first, last) { + this.firstName = first; + this.lastName = last; + this.name = this.firstName + ' ' + this.lastName; +} \ No newline at end of file diff --git a/threaded-counting/README.md b/threaded-counting/README.md new file mode 100644 index 0000000..bf1999b --- /dev/null +++ b/threaded-counting/README.md @@ -0,0 +1,24 @@ +# Threaded counting +[*View on Codewars*](https://www.codewars.com/kata/threaded-counting) + +Your task is simple. You have to call `counter.count(int)` with the numbers 1 to 100 inclusive. So a simple solution might look like this: +``` +for (int i = 1; i <= 100; i++) { + counter.count(i); +} +``` +But there's a catch. Your solution also has to satisfy the following conditions: + + + Three different threads must be used + + Numbers of the form `3n` (multiples of 3) must be called in one thread + + Numbers of the form `3n + 1` must be called in a second + + Numbers of the form `3n + 2` must be called in a third + + The numbers have to be called in sequence 1 to 100 + +Also, make sure your method doesn't return until all three threads have completed. Otherwise the tests may not work even if your solution is correct. + +## Timeline +- Created: 2014-12-27 +- Published: 2015-01-05 +- Approved: 2018-01-10 +- Completed: 2015-05-07 \ No newline at end of file diff --git a/threaded-counting/java/1/ThreadedCounting.java b/threaded-counting/java/1/ThreadedCounting.java new file mode 100644 index 0000000..f7f8fc1 --- /dev/null +++ b/threaded-counting/java/1/ThreadedCounting.java @@ -0,0 +1,45 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; + +public class ThreadedCounting { + private static final int MIN = 1; + private static final int MAX = 100; + private static final int THREAD_COUNT = 3; + + public static void countInThreads(final Counter counter) { + final List> queues = new ArrayList<>(THREAD_COUNT); + for (int i = 0; i < THREAD_COUNT; i++) { + queues.add(new ArrayBlockingQueue<>(1)); + } + final List threads = new ArrayList<>(THREAD_COUNT); + for (int i = 0; i < THREAD_COUNT; i++) { + final int j = i; + final Thread thread = new Thread(() -> { + while (true) { + try { + final int k = queues.get(j).take(); + if (k <= MAX) { + counter.count(k); + } + if (k < MAX + THREAD_COUNT) { + queues.get((j + 1) % THREAD_COUNT).put(k + 1); + } + if (k >= MAX) { + break; + } + } catch (final InterruptedException ex) {} + } + }, String.format("Thread-%d", j + 1)); + threads.add(thread); + thread.start(); + } + queues.get(0).add(MIN); + for (final Thread thread : threads) { + try { + thread.join(); + } catch (final InterruptedException ex) {} + } + } +} \ No newline at end of file diff --git a/toleetspeak/README.md b/toleetspeak/README.md new file mode 100644 index 0000000..2b19fcb --- /dev/null +++ b/toleetspeak/README.md @@ -0,0 +1,53 @@ +# ToLeetSpeak +[*View on Codewars*](https://www.codewars.com/kata/toleetspeak) + +Your task is to write function toLeetSpeak that converts a regular english sentence to Leetspeak. + +More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet + +Consider only uppercase letters (no lowercase letters, no numbers) and spaces. + +For example: + +``` +toLeetSpeak("LEET") returns "1337" +``` + +In this kata we use a simple LeetSpeak dialect. Use this alphabet: + +``` +{ + A : '@', + B : '8', + C : '(', + D : 'D', + E : '3', + F : 'F', + G : '6', + H : '#', + I : '!', + J : 'J', + K : 'K', + L : '1', + M : 'M', + N : 'N', + O : '0', + P : 'P', + Q : 'Q', + R : 'R', + S : '$', + T : '7', + U : 'U', + V : 'V', + W : 'W', + X : 'X', + Y : 'Y', + Z : '2' +} +``` + +## Timeline +- Created: 2016-08-27 +- Published: 2016-08-27 +- Approved: 2016-08-31 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/toleetspeak/javascript/1/toleetspeak.js b/toleetspeak/javascript/1/toleetspeak.js new file mode 100644 index 0000000..bc3d2d2 --- /dev/null +++ b/toleetspeak/javascript/1/toleetspeak.js @@ -0,0 +1,32 @@ +const map = c => ({ + A: '@', + B: '8', + C: '(', + D: 'D', + E: '3', + F: 'F', + G: '6', + H: '#', + I: '!', + J: 'J', + K: 'K', + L: '1', + M: 'M', + N: 'N', + O: '0', + P: 'P', + Q: 'Q', + R: 'R', + S: '$', + T: '7', + U: 'U', + V: 'V', + W: 'W', + X: 'X', + Y: 'Y', + Z: '2' +})[c] + +function toLeetSpeak(str) { + return str.replace(/[A-Z]/g, map); +} \ No newline at end of file diff --git a/triangular-treasure/README.md b/triangular-treasure/README.md new file mode 100644 index 0000000..195f1b4 --- /dev/null +++ b/triangular-treasure/README.md @@ -0,0 +1,58 @@ +# Triangular Treasure +[*View on Codewars*](https://www.codewars.com/kata/triangular-treasure) + +Triangular numbers are so called because of the equilateral triangular shape that they occupy when laid out as dots. i.e. + +``` +1st (1) 2nd (3) 3rd (6) +* ** *** + * ** + * +``` + +You need to return the nth triangular number. You should return 0 for out of range values: + +```haskell +all [ + triangular 0 == 0, + triangular 2 == 3, + triangular 3 == 6, + triangular (-10) == 0 +] -- True +``` +```javascript + triangular(0)==0, + triangular(2)==3, + triangular(3)==6, + triangular(-10)==0 +``` +```ruby + triangular(0)==0, + triangular(2)==3, + triangular(3)==6, + triangular(-10)==0 +``` +```python + triangular(0)==0, + triangular(2)==3, + triangular(3)==6, + triangular(-10)==0 +``` +```dart + triangular(0)==0, + triangular(2)==3, + triangular(3)==6, + triangular(-10)==0 +``` +```swift + triangular(0)==0 + triangular(2)==3 + triangular(3)==6 + triangular(-10)==0 +``` + +## Timeline +- Created: 2013-10-16 +- Published: 2013-10-16 +- Approved: null +- Completed: 2015-05-23 \ No newline at end of file diff --git a/triangular-treasure/javascript/1/triangular-treasure.js b/triangular-treasure/javascript/1/triangular-treasure.js new file mode 100644 index 0000000..72a9e49 --- /dev/null +++ b/triangular-treasure/javascript/1/triangular-treasure.js @@ -0,0 +1,5 @@ +function triangular(n) { + var t = 0; + for (var i = 1; i <= n; t += i++); + return t; +} \ No newline at end of file diff --git a/tug-o-war/README.md b/tug-o-war/README.md new file mode 100644 index 0000000..93bdc13 --- /dev/null +++ b/tug-o-war/README.md @@ -0,0 +1,69 @@ +# Tug-o'-War +[*View on Codewars*](https://www.codewars.com/kata/tug-o-war) + +In this Kata we will play a classic game of Tug-o'-War! + +Two teams of 5 members will face off, the strongest of which will prevail. Each team member will be assigned a strength rating (1-9), with the most powerful members having a rating of 9. Your goal is to determine, based on the cumulative strength of the members of each team, which team will win the war. + +The teams will be represented by an array of arrays: + +```javascript +[[5,0,3,2,1], [1,6,8,2,9]] // 11 < 26 ; "Team 2 wins!" +``` +```csharp +new int[][] { new int[] {5,0,3,2,1}, new int[] {1,6,8,2,9} } // 11 < 26 ; "Team 2 wins!" +``` +```java +new int[][]{new int[]{5, 0, 3, 2, 1}, new int[]{1, 6, 8, 2, 9}} // 11 < 26 ; "Team 2 wins!" +``` +```python +[[5,0,3,2,1], [1,6,8,2,9]] # 11 < 26 ; "Team 2 wins!" +``` +```ruby +[[5,0,3,2,1], [1,6,8,2,9]] # 11 < 26 ; "Team 2 wins!" +``` + +Your task is to return a string with which team won or if it was a tie. + + - If team one is stronger, return the string "Team 1 wins!" + - If team two is stronger, return the string "Team 2 wins!" + +If the two teams are of equal strength, the team with the strongest Anchor (the member furthest from the center of the rope) will win. In the above example, the member with strength 5 is team one's Anchor and strength 9 is team two's Anchor. + + - If the teams and the Anchors are both of equal strength, return the string "It's a tie!" + +The Anchors are members in each end of the rope: + +![anchors](http://i.imgur.com/w3MJF2V.jpg?1) + +more examples: + +```javascript +[[1,2,3,4,5], [1,2,3,4,5]] // Team 2 has stronger Anchor ; "Team 2 wins!" +[[1,2,3,4,5], [5,4,3,2,1]] // Teams & Anchors are tied; "It's a tie!" +``` +```csharp +new int[][] { new int[] {1,2,3,4,5}, new int[] {1,2,3,4,5} } // Team 2 has stronger Anchor ; "Team 2 wins!" +new int[][] { new int[] {1,2,3,4,5}, new int[] {5,4,3,2,1} } // Teams & Anchors are tied; "It's a tie!" +``` +```java +new int[][]{new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5}} // Team 2 has stronger Anchor ; "Team 2 wins!" +new int[][]{new int[]{1, 2, 3, 4, 5}, new int[]{5, 4, 3, 2, 1}} // Teams & Anchors are tied; "It's a tie!" +``` +```python +[[1,2,3,4,5], [1,2,3,4,5]] # Team 2 has stronger Anchor ; "Team 2 wins!" +[[1,2,3,4,5], [5,4,3,2,1]] # Teams & Anchors are tied; "It's a tie!" +``` +```ruby +[[1,2,3,4,5], [1,2,3,4,5]] # Team 2 has stronger Anchor ; "Team 2 wins!" +[[1,2,3,4,5], [5,4,3,2,1]] # Teams & Anchors are tied; "It's a tie!" +``` + +Good luck! + + +## Timeline +- Created: 2014-12-04 +- Published: 2014-12-04 +- Approved: null +- Completed: 2015-05-22 \ No newline at end of file diff --git a/tug-o-war/java/1/TugOWar.java b/tug-o-war/java/1/TugOWar.java new file mode 100644 index 0000000..d084d17 --- /dev/null +++ b/tug-o-war/java/1/TugOWar.java @@ -0,0 +1,23 @@ +public class TugOWar { + public static final String TEAM1 = "Team 1 wins!"; + public static final String TEAM2 = "Team 2 wins!"; + public static final String TIE = "It's a tie!"; + + public static String tugOWar(final int[][] teams) { + final int[] team1 = teams[0]; + final int[] team2 = teams[1]; + final int sum1 = sum(team1); + final int sum2 = sum(team2); + if (sum1 > sum2) return TEAM1; + if (sum1 < sum2) return TEAM2; + final int anchor1 = team1[0]; + final int anchor2 = team2[team2.length - 1]; + if (anchor1 > anchor2) return TEAM1; + if (anchor1 < anchor2) return TEAM2; + return TIE; + } + + private static int sum(final int[] team) { + return java.util.Arrays.stream(team).sum(); + } +} \ No newline at end of file diff --git a/tug-o-war/javascript/1/tug-o-war.js b/tug-o-war/javascript/1/tug-o-war.js new file mode 100644 index 0000000..616d4e3 --- /dev/null +++ b/tug-o-war/javascript/1/tug-o-war.js @@ -0,0 +1,18 @@ +function tug_o_war(teams) { + var team1 = 'Team 1 wins!'; + var team2 = 'Team 2 wins!'; + var tie = "It's a tie!"; + var sum1 = sum(teams[0]); + var sum2 = sum(teams[1]); + if (sum1 > sum2) return team1; + if (sum1 < sum2) return team2; + var anchor1 = teams[0][0]; + var anchor2 = teams[1][4]; + if (anchor1 > anchor2) return team1; + if (anchor1 < anchor2) return team2; + return tie; +} + +function sum(team) { + return team[0] + team[1] + team[2] + team[3] + team[4]; +} \ No newline at end of file diff --git a/two-to-one/README.md b/two-to-one/README.md new file mode 100644 index 0000000..7a50d1b --- /dev/null +++ b/two-to-one/README.md @@ -0,0 +1,22 @@ +# Two to One +[*View on Codewars*](https://www.codewars.com/kata/two-to-one) + +Take 2 strings `s1` and `s2` including only letters from `a`to `z`. +Return a new **sorted** string, the longest possible, containing distinct letters, +- each taken only once - coming from s1 or s2. +#Examples: +``` +a = "xyaabbbccccdefww" +b = "xxxxyyyyabklmopq" +longest(a, b) -> "abcdefklmopqwxy" + +a = "abcdefghijklmnopqrstuvwxyz" +longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" +``` + + +## Timeline +- Created: 2015-11-26 +- Published: 2015-11-26 +- Approved: 2015-11-26 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/two-to-one/javascript/1/two-to-one.js b/two-to-one/javascript/1/two-to-one.js new file mode 100644 index 0000000..45fda5a --- /dev/null +++ b/two-to-one/javascript/1/two-to-one.js @@ -0,0 +1,3 @@ +function longest(s1, s2) { + return Array.from(new Set([ ...Array.from(s1), ...Array.from(s2) ])).sort().join('') +} \ No newline at end of file diff --git a/type-of-sum/README.md b/type-of-sum/README.md new file mode 100644 index 0000000..e17da8c --- /dev/null +++ b/type-of-sum/README.md @@ -0,0 +1,10 @@ +# Type of sum +[*View on Codewars*](https://www.codewars.com/kata/type-of-sum) + +Return the type of the sum of the two arguments + +## Timeline +- Created: 2017-12-11 +- Published: 2017-12-11 +- Approved: 2017-12-11 +- Completed: 2017-12-13 \ No newline at end of file diff --git a/type-of-sum/javascript/1/type-of-sum.js b/type-of-sum/javascript/1/type-of-sum.js new file mode 100644 index 0000000..d8a5689 --- /dev/null +++ b/type-of-sum/javascript/1/type-of-sum.js @@ -0,0 +1,3 @@ +function typeOfSum(a, b) { + return typeof(a + b); +} \ No newline at end of file diff --git a/undo-slash-redo/README.md b/undo-slash-redo/README.md new file mode 100644 index 0000000..bec6475 --- /dev/null +++ b/undo-slash-redo/README.md @@ -0,0 +1,31 @@ +# Undo/Redo +[*View on Codewars*](https://www.codewars.com/kata/undo-slash-redo) + +The purpose of this kata is to implement the `undoRedo` function. + +This function takes an object and returns an object that has these actions to be performed on the object passed as a parameter: + +`set(key, value)` Assigns the value to the key. If the key does not exist, creates it. + +`get(key)` Returns the value associated to the key. + +`del(key)` removes the key from the object. + +`undo()` Undo the last operation (set or del) on the object. Throws an exception if there is no operation to undo. + +`redo()` Redo the last undo operation (redo is only possible after an undo). Throws an exception if there is no operation to redo. + +After `set()` or `del()` are called, there is nothing to redo. + +All actions must affect to the `object` passed to `undoRedo(object)` function. So you can not work with a copy of the object. + +Any `set/del` after an `undo` should disallow new `undos`. + + + + +## Timeline +- Created: 2014-03-03 +- Published: 2014-03-03 +- Approved: 2015-02-26 +- Completed: 2015-05-26 \ No newline at end of file diff --git a/undo-slash-redo/javascript/1/undo-slash-redo.js b/undo-slash-redo/javascript/1/undo-slash-redo.js new file mode 100644 index 0000000..5b054db --- /dev/null +++ b/undo-slash-redo/javascript/1/undo-slash-redo.js @@ -0,0 +1,74 @@ +function undoRedo(object) { + this.undos = []; + this.redos = []; + this.undone = false; + + function clearRedos() { + if (!undone) { + redos = []; + } + } + + return { + set: function(key, value) { + var existed = key in object; + var undo; + if (existed) { + var old = object[key]; + if (old === value) return; + undo = function() { + object[key] = old; + }; + } else { + undo = function() { + delete object[key]; + }; + } + object[key] = value; + var that = this; + undos.push({ + undo: undo, + redo: function() { + that.set(key, value); + } + }); + clearRedos(); + undone = false; + }, + get: function(key) { + return object[key]; + }, + del: function(key) { + if (key in object) { + var old = object[key]; + delete object[key]; + var that = this; + undos.push({ + undo: function() { + object[key] = old; + }, + redo: function() { + that.del(key); + } + }); + clearRedos(); + undone = false; + } + }, + undo: function() { + var undo = undos.pop(); + undo.undo(); + clearRedos(); + redos.push(undo); + undone = true; + }, + redo: function() { + if (!undone) { + throw 'Nothing to undo!'; + } + var redo = redos.pop(); + redo.redo(); + undone = true; + } + }; +} \ No newline at end of file diff --git a/unique-in-order/README.md b/unique-in-order/README.md new file mode 100644 index 0000000..5999eca --- /dev/null +++ b/unique-in-order/README.md @@ -0,0 +1,36 @@ +# Unique In Order +[*View on Codewars*](https://www.codewars.com/kata/unique-in-order) + +Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. + +For example: + +```javascript +uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] +uniqueInOrder('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] +uniqueInOrder([1,2,2,3,3]) == [1,2,3] +``` +```python +unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] +unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] +unique_in_order([1,2,2,3,3]) == [1,2,3] +``` +```ruby +unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] +unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] +unique_in_order([1,2,2,3,3]) == [1,2,3] +``` +```csharp +// Note that you can return any data structure you want, as long it inherits the IEnumerable interface. +UniqueInOrder("AAAABBBCCDAABBB") => "ABCDAB" +UniqueInOrder("ABBCcAD") => "ABCcAD" +UniqueInOrder("12233") => "123" +UniqueInOrder(new List {1.1, 2.2, 2.2, 3.3}) => new List {1.1, 2.2, 3.3} +``` + + +## Timeline +- Created: 2015-02-19 +- Published: 2015-02-19 +- Approved: 2015-05-08 +- Completed: 2018-03-04 \ No newline at end of file diff --git a/unique-in-order/javascript/1/unique-in-order.js b/unique-in-order/javascript/1/unique-in-order.js new file mode 100644 index 0000000..9a27a55 --- /dev/null +++ b/unique-in-order/javascript/1/unique-in-order.js @@ -0,0 +1,4 @@ +const uniqueInOrder = iterable => + typeof iterable === 'string' + ? Array.from(iterable.replace(/(.)\1+/g, '$1')) + : iterable.filter((e, i) => e !== iterable[i - 1]) \ No newline at end of file diff --git a/uribuilder/README.md b/uribuilder/README.md new file mode 100644 index 0000000..5b7a1f9 --- /dev/null +++ b/uribuilder/README.md @@ -0,0 +1,59 @@ +# UriBuilder +[*View on Codewars*](https://www.codewars.com/kata/uribuilder) + +Create a basic UriBuilder object that will be used specifically to build query params on an existing URI. It should support a params property and a build method. It will handle the URL having pre-existing params that need to be managed. The URL must be properly encoded (i.e. "a b" should be encoded as "a%20b") + +Examples of how the builder will be used: + +```javascript + +var builder = new UriBuilder('http://www.codewars.com') +builder.params.page = 1 +builder.params.language = 'javascript' + +// new builder instance to demonstrate pre-existing params. +builder = new UriBuilder('http://www.codewars.com?page=1') + +builder.params.page = 2 +// should return 'http://www.codewars.com?page=2' +builder.build() + +// if you delete params then they will disappear from the url string +delete builder.params.page + +// should return 'http://www.codewars.com' +builder.build() + +``` + +```coffeescript + +builder = new UriBuilder('http://www.codewars.com') +builder.params.page = 1 +builder.params.language = 'javascript' + +# should return 'http://www.codewars.com?page=1&language=javascript' +builder.build() + +# new builder instance to demonstrate pre-existing params. +builder = new UriBuilder('http://www.codewars.com?page=1') +builder.params.page = 2 + +# should return 'http://www.codewars.com?page=2' +builder.build() + +# if you delete params then they will disappear from the url string +delete builder.params.page + +# should return 'http://www.codewars.com' +builder.build() + +``` + +**Note:** For extra style points you can have your solution handle array values as query parameters, however there are no tests that explicitly test for them. + +## Timeline +- Created: 2013-07-23 +- Published: 2013-07-23 +- Approved: null +- Completed: 2016-02-26 \ No newline at end of file diff --git a/uribuilder/javascript/1/uribuilder.js b/uribuilder/javascript/1/uribuilder.js new file mode 100644 index 0000000..ce4b244 --- /dev/null +++ b/uribuilder/javascript/1/uribuilder.js @@ -0,0 +1,32 @@ +function UriBuilder(uri) { + this.params = {}; + + this.build = function() { + var build = uri; + var keys = Object.keys(this.params); + var length = keys.length; + if (length) build += '?'; + for (var i = 0; i < length; i++) { + var key = keys[i]; + var value = this.params[key]; + build += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&'; + } + return length ? build.substr(0, build.length - 1) : build; + } + + var queryIndex = uri.indexOf('?'); + if (queryIndex >= 0) { + var query = uri.substring(queryIndex + 1); + uri = uri.substring(0, queryIndex); + var pairs = query.split('&'); + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var separatorIndex = pair.indexOf('='); + if (separatorIndex >= 0) { + var key = pair.substring(0, separatorIndex); + var value = pair.substring(separatorIndex + 1) + this.params[key] = value; + } + } + } +} \ No newline at end of file diff --git a/valid-braces/README.md b/valid-braces/README.md new file mode 100644 index 0000000..f2f4e68 --- /dev/null +++ b/valid-braces/README.md @@ -0,0 +1,29 @@ +# Valid Braces +[*View on Codewars*](https://www.codewars.com/kata/valid-braces) + +Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return `true` if the string is valid, and `false` if it's invalid. + +This Kata is similar to the [Valid Parentheses](https://www.codewars.com/kata/valid-parentheses) Kata, but introduces new characters: brackets `[]`, and curly braces `{}`. Thanks to `@arnedag` for the idea! + +All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: `()[]{}`. + + +### What is considered Valid? + +A string of braces is considered valid if all braces are matched with the correct brace. + + +## Examples +```py +"(){}[]" => True +"([{}])" => True +"(}" => False +"[(])" => False +"[({})](]" => False +``` + +## Timeline +- Created: 2013-11-04 +- Published: 2013-11-05 +- Approved: 2013-12-20 +- Completed: 2015-05-25 \ No newline at end of file diff --git a/valid-braces/javascript/1/valid-braces.js b/valid-braces/javascript/1/valid-braces.js new file mode 100644 index 0000000..a7149b6 --- /dev/null +++ b/valid-braces/javascript/1/valid-braces.js @@ -0,0 +1,12 @@ +function validBraces(braces) { + var validBraces = ['()', '[]', '{}']; + var length = validBraces.length; + var changed; + do { + changed = false; + for (var i = 0; i < length; i++) { + changed |= braces !== (braces = braces.replace(validBraces[i], '')); + } + } while (changed); + return !braces.length; +} \ No newline at end of file diff --git a/valid-parentheses/README.md b/valid-parentheses/README.md new file mode 100644 index 0000000..e92e0e5 --- /dev/null +++ b/valid-parentheses/README.md @@ -0,0 +1,31 @@ +# Valid Parentheses +[*View on Codewars*](https://www.codewars.com/kata/valid-parentheses) + +Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid. + +## Examples + +``` +"()" => true +")(()))" => false +"(" => false +"(())((()())())" => true +``` + +## Constraints + +`0 <= input.length <= 100` + +~~~if-not:javascript,go +Along with opening (`(`) and closing (`)`) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do **not** treat other forms of brackets as parentheses (e.g. `[]`, `{}`, `<>`). +~~~ + +~~~if:javascript,go +You may assume that the input string will *only* contain opening and closing parenthesis and *will not* be an empty string. +~~~ + +## Timeline +- Created: 2013-11-04 +- Published: 2013-11-04 +- Approved: null +- Completed: 2015-05-25 \ No newline at end of file diff --git a/valid-parentheses/javascript/1/valid-parentheses.js b/valid-parentheses/javascript/1/valid-parentheses.js new file mode 100644 index 0000000..8d8c5e2 --- /dev/null +++ b/valid-parentheses/javascript/1/valid-parentheses.js @@ -0,0 +1,11 @@ +function validParentheses(parens) { + var open = 0; + for (var i = 0; i < parens.length; i++) { + if (parens[i] === '(') { + open++; + } else if (--open < 0) { + return false; + } + } + return !open; +} \ No newline at end of file diff --git a/valid-phone-number/README.md b/valid-phone-number/README.md new file mode 100644 index 0000000..47b694b --- /dev/null +++ b/valid-phone-number/README.md @@ -0,0 +1,20 @@ +# Valid Phone Number +[*View on Codewars*](https://www.codewars.com/kata/valid-phone-number) + +Write a function that accepts a string, and returns true if it is in the form of a phone number.
Assume that any integer from 0-9 in any of the spots will produce a valid phone number.
+ +Only worry about the following format:
+(123) 456-7890 (don't forget the space after the close parentheses)

+Examples: + +``` +validPhoneNumber("(123) 456-7890") => returns true +validPhoneNumber("(1111)555 2345") => returns false +validPhoneNumber("(098) 123 4567") => returns false +``` + +## Timeline +- Created: 2013-10-17 +- Published: 2013-10-17 +- Approved: null +- Completed: 2015-05-24 \ No newline at end of file diff --git a/valid-phone-number/java/1/Kata.java b/valid-phone-number/java/1/Kata.java new file mode 100644 index 0000000..77a4f04 --- /dev/null +++ b/valid-phone-number/java/1/Kata.java @@ -0,0 +1,6 @@ +public class Kata { + public static boolean validPhoneNumber(String phoneNumber) { + // TODO: Return whether phoneNumber is in the proper form + return phoneNumber.matches("\\(\\d{3}\\) \\d{3}-\\d{4}"); + } +} \ No newline at end of file diff --git a/valid-phone-number/javascript/1/valid-phone-number.js b/valid-phone-number/javascript/1/valid-phone-number.js new file mode 100644 index 0000000..373b0c9 --- /dev/null +++ b/valid-phone-number/javascript/1/valid-phone-number.js @@ -0,0 +1,3 @@ +function validPhoneNumber(phoneNumber) { + return /^(?:\d+|\(\d+\) \d+-\d+)$/.test(phoneNumber); +} \ No newline at end of file diff --git a/vasya-clerk/README.md b/vasya-clerk/README.md new file mode 100644 index 0000000..b31baed --- /dev/null +++ b/vasya-clerk/README.md @@ -0,0 +1,53 @@ +# Vasya - Clerk +[*View on Codewars*](https://www.codewars.com/kata/vasya-clerk) + +The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single `100`, `50` or `25` dollars bill. An "Avengers" ticket costs `25 dollars`. + +Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line. + +Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line? + +Return `YES`, if Vasya can sell a ticket to each person and give the change with the bills he has at hand at that moment. Otherwise return `NO`. + + +###Examples: + +```csharp +// === C Sharp === + +Line.Tickets(new int[] {25, 25, 50}) // => YES +Line.Tickets(new int[] {25, 100}) + // => NO. Vasya will not have enough money to give change to 100 dollars +``` + +```java +// *** Java *** + +Line.Tickets(new int[] {25, 25, 50}) // => YES +Line.Tickets(new int []{25, 100}) + // => NO. Vasya will not have enough money to give change to 100 dollars +``` + +```python +### Python ### + +tickets([25, 25, 50]) # => YES +tickets([25, 100]) + # => NO. Vasya will not have enough money to give change to 100 dollars +``` + +```javascript +// === JavaScript == + +tickets([25, 25, 50]) // => YES +tickets([25, 100]) + // => NO. Vasya will not have enough money to give change to 100 dollars +``` + + + +## Timeline +- Created: 2015-05-15 +- Published: 2015-05-15 +- Approved: 2015-06-05 +- Completed: 2016-09-08 \ No newline at end of file diff --git a/vasya-clerk/java/1/Line.java b/vasya-clerk/java/1/Line.java new file mode 100644 index 0000000..10b9ab8 --- /dev/null +++ b/vasya-clerk/java/1/Line.java @@ -0,0 +1,37 @@ +public class Line { + public static String Tickets(int[] peopleInLine) { + int bill25 = 0, bill50 = 0, bill100 = 0; + for (int personInLine : peopleInLine) { + switch (personInLine) { + case 25: + bill25++; + break; + case 50: + if (bill25 == 0) { + return "NO"; + } + bill25--; + bill50++; + break; + case 100: + if (bill25 == 0) { + return "NO"; + } + if (bill50 == 0) { + if (bill25 < 3) { + return "NO"; + } + bill25 -= 3; + } else { + bill50--; + bill25--; + } + bill100++; + break; + default: + return "WTF"; + } + } + return "YES"; + } +} \ No newline at end of file diff --git a/vector-class/README.md b/vector-class/README.md new file mode 100644 index 0000000..a132788 --- /dev/null +++ b/vector-class/README.md @@ -0,0 +1,53 @@ +# Vector class +[*View on Codewars*](https://www.codewars.com/kata/vector-class) + +Create a Vector object that supports addition, subtraction, dot products, and norms. So, for example: + +```coffeescript +a = new Vector([1, 2, 3]) +b = new Vector([3, 4, 5]) +c = new Vector([5, 6, 7, 8]) + +a.add(b) # should return a new Vector([4, 6, 8]) +a.subtract(b) # should return a new Vector([-2, -2, -2]) +a.dot(b) # should return 1*3 + 2*4 + 3*5 = 26 +a.norm() # should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14) +a.add(c) # throws an error +``` +```javascript +var a = new Vector([1, 2, 3]); +var b = new Vector([3, 4, 5]); +var c = new Vector([5, 6, 7, 8]); + +a.add(b); // should return a new Vector([4, 6, 8]) +a.subtract(b); // should return a new Vector([-2, -2, -2]) +a.dot(b); // should return 1*3 + 2*4 + 3*5 = 26 +a.norm(); // should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14) +a.add(c); // throws an error +``` +```python +a = Vector([1, 2, 3]) +b = Vector([3, 4, 5]) +c = Vector([5, 6, 7, 8]) + +a.add(b) # should return a new Vector([4, 6, 8]) +a.subtract(b) # should return a new Vector([-2, -2, -2]) +a.dot(b) # should return 1*3 + 2*4 + 3*5 = 26 +a.norm() # should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14) +a.add(c) # raises an exception +``` + +If you try to add, subtract, or dot two vectors with different lengths, ***you must throw an error***! + +Also provide: + +- a `toString` method, so that using the vectors from above, `a.toString() === '(1,2,3)'` (in Python, this is a `__str__` method, so that `str(a) == '(1,2,3)'`) +- an `equals` method, to check that two vectors that have the same components are equal + +**Note:** the test cases will utilize the user-provided `equals` method. + +## Timeline +- Created: 2013-10-28 +- Published: 2013-10-28 +- Approved: 2013-12-06 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/vector-class/javascript/1/vector-class.js b/vector-class/javascript/1/vector-class.js new file mode 100644 index 0000000..8d3459d --- /dev/null +++ b/vector-class/javascript/1/vector-class.js @@ -0,0 +1,61 @@ +var Vector = function(components) { + this.components = components; + this.length = components.length; + + this.add = function(vector) { + this.validate(vector); + var components = new Array(this.length); + for (var i = 0; i < this.length; i++) { + components[i] = this.components[i] + vector.components[i]; + } + return new Vector(components); + }; + + this.subtract = function(vector) { + this.validate(vector); + var components = new Array(this.length); + for (var i = 0; i < this.length; i++) { + components[i] = this.components[i] - vector.components[i]; + } + return new Vector(components); + }; + + this.dot = function(vector) { + this.validate(vector); + var dot = 0; + for (var i = 0; i < this.length; i++) { + dot += this.components[i] * vector.components[i]; + } + return dot; + }; + + this.norm = function() { + var norm = 0; + for (var i = 0; i < this.length; i++) { + norm += this.components[i] * this.components[i]; + } + return Math.sqrt(norm); + }; + + this.validate = function(vector) { + if (this.length !== vector.length) { + throw 'length'; + } + }; + + this.equals = function(vector) { + if (this.length !== vector.length) { + return false; + } + for (var i = 0; i < this.length; i++) { + if (this.components[i] !== vector.components[i]) { + return false; + } + } + return true; + }; + + this.toString = function() { + return '(' + this.components.join() + ')'; + }; +}; \ No newline at end of file diff --git a/vowel-count/README.md b/vowel-count/README.md new file mode 100644 index 0000000..cc9634d --- /dev/null +++ b/vowel-count/README.md @@ -0,0 +1,14 @@ +# Vowel Count +[*View on Codewars*](https://www.codewars.com/kata/vowel-count) + +Return the number (count) of vowels in the given string. + +We will consider a, e, i, o, and u as vowels for this Kata. + +The input string will only consist of lower case letters and/or spaces. + +## Timeline +- Created: 2015-03-10 +- Published: 2015-03-10 +- Approved: 2015-03-15 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/vowel-count/java/1/Vowels.java b/vowel-count/java/1/Vowels.java new file mode 100644 index 0000000..340d3d6 --- /dev/null +++ b/vowel-count/java/1/Vowels.java @@ -0,0 +1,13 @@ +import java.util.regex.*; + +public class Vowels { + + public static int getCount(String str) { + Pattern vowels = Pattern.compile("[aeiou]", Pattern.CASE_INSENSITIVE); + Matcher vowelMatcher = vowels.matcher(str); + int vowelCount; + for (vowelCount = 0; vowelMatcher.find(); vowelCount++); + return vowelCount; + } + +} \ No newline at end of file diff --git a/well-of-ideas-easy-version/README.md b/well-of-ideas-easy-version/README.md new file mode 100644 index 0000000..1cfd353 --- /dev/null +++ b/well-of-ideas-easy-version/README.md @@ -0,0 +1,12 @@ +# Well of Ideas - Easy Version +[*View on Codewars*](https://www.codewars.com/kata/well-of-ideas-easy-version) + +For every good kata idea there seem to be quite a few bad ones! + +In this kata you need to check the provided array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'. + +## Timeline +- Created: 2016-10-03 +- Published: 2016-10-03 +- Approved: 2016-10-04 +- Completed: 2018-02-06 \ No newline at end of file diff --git a/well-of-ideas-easy-version/javascript/1/well-of-ideas-easy-version.js b/well-of-ideas-easy-version/javascript/1/well-of-ideas-easy-version.js new file mode 100644 index 0000000..b1ffd86 --- /dev/null +++ b/well-of-ideas-easy-version/javascript/1/well-of-ideas-easy-version.js @@ -0,0 +1,11 @@ +function well(x) { + switch (x.filter(i => i === 'good').length) { + case 0: + return 'Fail!' + case 1: + case 2: + return 'Publish!' + default: + return 'I smell a series!' + } +} \ No newline at end of file diff --git a/well-of-ideas-harder-version/README.md b/well-of-ideas-harder-version/README.md new file mode 100644 index 0000000..6ec37e4 --- /dev/null +++ b/well-of-ideas-harder-version/README.md @@ -0,0 +1,16 @@ +# Well of Ideas - Harder Version +[*View on Codewars*](https://www.codewars.com/kata/well-of-ideas-harder-version) + +For every good kata idea there seem to be quite a few bad ones! + +In this kata you need to check the provided 2 dimensional array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'. + +The sub arrays may not be the same length. + +The solution should be case insensitive (ie good, GOOD and gOOd all count as a good idea). All inputs may not be strings. + +## Timeline +- Created: 2016-10-03 +- Published: 2016-10-03 +- Approved: 2016-10-08 +- Completed: 2018-02-06 \ No newline at end of file diff --git a/well-of-ideas-harder-version/javascript/1/well-of-ideas-harder-version.js b/well-of-ideas-harder-version/javascript/1/well-of-ideas-harder-version.js new file mode 100644 index 0000000..20cb9df --- /dev/null +++ b/well-of-ideas-harder-version/javascript/1/well-of-ideas-harder-version.js @@ -0,0 +1,16 @@ +function well(x) { + const collator = new Intl.Collator('en', { + sensitivity: 'accent', + usage: 'search' + }) + const y = x => x.filter(i => !collator.compare(i, 'good')).length + switch (x.map(y).reduce((s, c) => s + c, 0)) { + case 0: + return 'Fail!' + case 1: + case 2: + return 'Publish!' + default: + return 'I smell a series!' + } +} \ No newline at end of file diff --git a/whats-a-perfect-power-anyway/README.md b/whats-a-perfect-power-anyway/README.md new file mode 100644 index 0000000..88d06cc --- /dev/null +++ b/whats-a-perfect-power-anyway/README.md @@ -0,0 +1,60 @@ +# What's a Perfect Power anyway? +[*View on Codewars*](https://www.codewars.com/kata/whats-a-perfect-power-anyway) + +A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a classification of positive integers: + +> In mathematics, a **perfect power** is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1 such that mk = n. + +Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair `m` and `k` with mk = n as a proof. Otherwise return `Nothing`, `Nil`, `null`, `NULL`, `None` or your language's equivalent. + +**Note:** For a perfect power, there might be several pairs. For example `81 = 3^4 = 9^2`, so `(3,4)` and `(9,2)` are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it. + +### Examples +```javascript +Test.describe("perfect powers", function(){ + Test.it("should work for some examples",function(){ + Test.assertSimilar(isPP(4), [2,2], "4 = 2^2"); + Test.assertSimilar(isPP(9), [3,2], "9 = 3^2"); + Test.assertEquals( isPP(5), null, "5 isn't a perfect number"); + }); +}); +``` +```coffeescript +Test.describe "perfect powers", -> + Test.it "should work for some examples", -> + Test.assertSimilar isPP(4), [ 2, 2 ], "4 = 2^2" + Test.assertSimilar isPP(9), [ 3, 2 ], "9 = 3^2" + Test.assertEquals isPP(5), null, "5 isn't a perfect number" +``` +```haskell +isPP 4 `shouldBe` Just (2,2) +isPP 9 `shouldBe` Just (3,2) +isPP 5 `shouldBe` Nothing +``` +```python +isPP(4) => [2,2] +isPP(9) => [3,2] +isPP(5) => None +``` +```ruby +isPP(4) => [2,2] +isPP(9) => [3,2] +isPP(5) => nil +``` +```java +isPerfectPower(4) => new int[]{2,2} +isPerfectPower(5) => null +isPerfectPower(8) => new int[]{2,3} +isPerfectPower(9) => new int[]{3,2} +``` +```r +isPP(4) => 2 2 +isPP(9) => 3 2 +isPP(5) => NULL +``` + +## Timeline +- Created: 2015-02-06 +- Published: 2015-02-06 +- Approved: 2015-02-11 +- Completed: 2015-05-04 \ No newline at end of file diff --git a/whats-a-perfect-power-anyway/java/1/PerfectPower.java b/whats-a-perfect-power-anyway/java/1/PerfectPower.java new file mode 100644 index 0000000..2ea6f62 --- /dev/null +++ b/whats-a-perfect-power-anyway/java/1/PerfectPower.java @@ -0,0 +1,55 @@ +import java.util.*; + +public class PerfectPower { + public static int[] isPerfectPower(final int n) { + final NavigableMap primeFactors = primeFactors(n); + final int primeFactorCount = primeFactors.size(); + if (primeFactorCount == 0) { + return null; + } + if (primeFactorCount == 1) { + final Map.Entry primeFactor = primeFactors.firstEntry(); + final int exp = primeFactor.getValue(); + return exp > 1 ? new int[] {primeFactor.getKey(), exp} : null; + } + final Set exps = new HashSet<>(primeFactors.values()); + final int expGcd = exps.stream().mapToInt(Integer::intValue).reduce(PerfectPower::gcd).getAsInt(); + if (expGcd == 1) { + return null; + } + final int base = primeFactors.entrySet().stream().mapToInt(e -> (int) Math.pow(e.getKey(), e.getValue() / expGcd)).reduce(1, PerfectPower::multiply); + return new int[] {base, expGcd}; + } + + private static int multiply(final int a, final int b) { + return a * b; + } + + private static int gcd(final int a, final int b) { + return b == 0 ? a : gcd(b, a % b); + } + + private static NavigableMap primeFactors(int n) { + final NavigableMap primeFactors = new TreeMap<>(); + int divisor = 2; + while (n > 1 && divisor * divisor <= n) { + if (n % divisor == 0) { + increment(primeFactors, divisor); + n /= divisor; + } else { + divisor += divisor == 2 ? 1 : 2; + } + } + if (n > 1) { + increment(primeFactors, n); + } + return primeFactors; + } + + private static void increment(final Map map, final K key) { + final Integer exp = map.putIfAbsent(key, 1); + if (exp != null) { + map.put(key, exp + 1); + } + } +} \ No newline at end of file diff --git a/which-are-in/README.md b/which-are-in/README.md new file mode 100644 index 0000000..e9f80c5 --- /dev/null +++ b/which-are-in/README.md @@ -0,0 +1,31 @@ +# Which are in? +[*View on Codewars*](https://www.codewars.com/kata/which-are-in) + +Given two arrays of strings `a1` and `a2` return a sorted array `r` in lexicographical order of the strings of `a1` which are substrings of strings of `a2`. + +#Example 1: +`a1 = ["arp", "live", "strong"]` + +`a2 = ["lively", "alive", "harp", "sharp", "armstrong"]` + +returns `["arp", "live", "strong"]` + +#Example 2: +`a1 = ["tarp", "mice", "bull"]` + +`a2 = ["lively", "alive", "harp", "sharp", "armstrong"]` + +returns `[]` + +# Notes: +Arrays are written in "general" notation. See "Your Test Cases" for examples in your language. + +In Shell bash `a1` and `a2` are strings. The return is a string where words are separated by commas. + +Beware: `r` must be without duplicates. + +## Timeline +- Created: 2015-03-15 +- Published: 2015-03-15 +- Approved: 2015-04-30 +- Completed: 2015-05-08 \ No newline at end of file diff --git a/which-are-in/java/1/WhichAreIn.java b/which-are-in/java/1/WhichAreIn.java new file mode 100644 index 0000000..bc1f8e5 --- /dev/null +++ b/which-are-in/java/1/WhichAreIn.java @@ -0,0 +1,7 @@ +import static java.util.Arrays.stream; + +public class WhichAreIn { + public static String[] inArray(String[] array1, String[] array2) { + return stream(array1).filter(s1 -> stream(array2).anyMatch(s2 -> s2.contains(s1))).sorted().distinct().toArray(String[]::new); + } +} \ No newline at end of file diff --git a/who-won-the-election/README.md b/who-won-the-election/README.md new file mode 100644 index 0000000..f05bdb1 --- /dev/null +++ b/who-won-the-election/README.md @@ -0,0 +1,78 @@ +# Who won the election? +[*View on Codewars*](https://www.codewars.com/kata/who-won-the-election) + +In democracy we have a lot of elections. For example, we have to vote for a class representative in school, for a new parliament or a new government. + +Usually, we vote for a candidate, i.e. a set of eligible candidates is given. This is done by casting a ballot into a ballot-box. After that, it must be counted how many ballots (= votes) a candidate got. + +A candidate will win this election if he has the absolute majority. + +

Your Task

+Return the name of the winner. If there is no winner, return null (in Java and JavaScript), None (in Python) or nil (in Ruby). + +

Task Description

+There are no given candidates. An elector can vote for anyone. Each ballot contains only one name and represents one vote for this name. A name is an arbitrary string, e.g. "A", "B", or "XJDHD".
+
+There are no spoiled ballots.
+
+The ballot-box is represented by an unsorted list of names. Each entry in the list corresponds to one vote for this name. You do not know the names in advance (because there are no candidates).
+
+A name wins the election if it gets more than n/2 votes (n = number of all votes, i.e. n is equal to the size of the given list). + +

Examples

+ +```java +//3 votes for "A", 2 votes for "B" -> "A" wins the election +BallotsCounter.getWinner(Arrays.asList("A", "A", "A", "B", "B")).equals("A") //true +//2 votes for "A", 2 votes for "B" -> No winner +BallotsCounter.getWinner(Arrays.asList("A", "A", "B", "B")) == null //true +//1 vote for each name -> No winner +BallotsCounter.getWinner(Arrays.asList("A", "B", "C", "D")) == null //true +//3 votes for "A", 2 votes for "B", 1 vote for "C" +//-> No winner ("A" does not have more than n/2 = 3 votes) +BallotsCounter.getWinner(Arrays.asList("A", "A", "A", "B", "B", "C")) == null //true +``` +```python +#3 votes for "A", 2 votes for "B" -> "A" wins the election +getWinner(["A", "A", "A", "B", "B"]) == "A" #true +#2 votes for "A", 2 votes for "B" -> No winner +getWinner(["A", "A", "B", "B"]) == None #true +#1 vote for each name -> No winner +getWinner(["A", "B", "C", "D"]) == None #true +#3 votes for "A", 2 votes for "B", 1 vote for "C" +#-> No winner ("A" does not have more than n/2 = 3 votes) +getWinner(["A", "A", "A", "B", "B", "C"]) == None #true +``` +```ruby +#3 votes for "A", 2 votes for "B" -> "A" wins the election +getWinner(["A", "A", "A", "B", "B"]) == "A" #true +#2 votes for "A", 2 votes for "B" -> No winner +getWinner(["A", "A", "B", "B"]) == nil #true +#1 vote for each name -> No winner +getWinner(["A", "B", "C", "D"]) == nil #true +#3 votes for "A", 2 votes for "B", 1 vote for "C" +#-> No winner ("A" does not have more than n/2 = 3 votes) +getWinner(["A", "A", "A", "B", "B", "C"]) == nil #true +``` +```javascript +//3 votes for "A", 2 votes for "B" -> "A" wins the election +getWinner(["A", "A", "A", "B", "B"]) === "A" //true +//2 votes for "A", 2 votes for "B" -> No winner +getWinner(["A", "A", "B", "B"]) === null //true +//1 vote for each name -> No winner +getWinner(["A", "B", "C", "D"]) === null //true +//3 votes for "A", 2 votes for "B", 1 vote for "C" +//-> No winner ("A" does not have more than n/2 = 3 votes) +getWinner(["A", "A", "A", "B", "B", "C"]) === null //true +``` + +

Note

+Please keep in mind the list of votes can be large (n <= 1,200,000). The given list is immutable, i.e. you cannot modify the list (otherwise this could lead to vote rigging). + +Good luck and have fun. + +## Timeline +- Created: 2015-05-05 +- Published: 2015-05-10 +- Approved: 2015-05-17 +- Completed: 2015-05-15 \ No newline at end of file diff --git a/who-won-the-election/java/1/BallotsCounter.java b/who-won-the-election/java/1/BallotsCounter.java new file mode 100644 index 0000000..ecb7f23 --- /dev/null +++ b/who-won-the-election/java/1/BallotsCounter.java @@ -0,0 +1,16 @@ +import java.util.*; + +public class BallotsCounter { + public static String getWinner(final List listOfBallots) { + final int numberOfBallots = listOfBallots.size(); + if (numberOfBallots == 0) { + return null; + } + final Map counts = new HashMap<>(); + for (final String ballot : listOfBallots) { + counts.put(ballot, counts.getOrDefault(ballot, 0) + 1); + } + final Map.Entry mostBallots = counts.entrySet().stream().sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue())).findFirst().get(); + return 2 * mostBallots.getValue() > numberOfBallots ? mostBallots.getKey() : null; + } +} \ No newline at end of file diff --git a/wind-component-calculation/README.md b/wind-component-calculation/README.md new file mode 100644 index 0000000..6904614 --- /dev/null +++ b/wind-component-calculation/README.md @@ -0,0 +1,40 @@ +# Wind component calculation +[*View on Codewars*](https://www.codewars.com/kata/wind-component-calculation) + +When landing an airplane manually, the pilot knows which runway he is using and usually has up to date wind information (speed and direction). This information alone does not help the pilot make a safe landing; what the pilot really needs to know is the speed of headwind, how much crosswind there is and from which side the crosswind is blowing relative to the plane. + +Let's imagine there is a system in the ATC tower with speech recognition that works so that when a pilot says "wind info" over the comms, the system will respond with a helpful message about the wind. + +Your task is to write a function that produces the response before it is fed into the text-to-speech engine. + +Input: + + * runway (string: "NN[L/C/R]"). NN is the runway's heading in tens of degrees. A suffix of L, C or R may be present and should be ignored. NN is between 01 and 36. + * wind_direction (int). Direction wind is blowing from in degrees. Between 0 and 359. + * wind_speed (int). Wind speed in knots + +Output: + +* a string in the following format: ```"(Head|Tail)wind N knots. Crosswind N knots from your (left|right)."``` + +The wind speeds must be correctly rounded integers. If the rounded headwind component is 0, "Head" should be used. Similarly, "right" in case crosswind component is 0. + +Calculating crosswind and headwind: +``` +A = Angle of the wind from the direction of travel (radians) +WS = Wind speed +CW = Crosswind +HW = Headwind + +CW = sin(A) * WS +HW = cos(A) * WS +``` +More information about wind component calculation: +http://en.wikipedia.org/wiki/Tailwind + + +## Timeline +- Created: 2014-10-01 +- Published: 2014-10-01 +- Approved: 2014-12-28 +- Completed: 2015-05-10 \ No newline at end of file diff --git a/wind-component-calculation/java/1/WindInfo.java b/wind-component-calculation/java/1/WindInfo.java new file mode 100644 index 0000000..9ff8cac --- /dev/null +++ b/wind-component-calculation/java/1/WindInfo.java @@ -0,0 +1,9 @@ +public class WindInfo { + public static String message(String r, int wd, int ws) { + double a = Math.toRadians(Integer.parseInt(r.substring(0, 2)) * 10 - wd); + int cw = (int) Math.round(Math.sin(a) * ws); + int hw = (int) Math.round(Math.cos(a) * ws); + return String.format("%swind %d knots. Crosswind %d knots from your %s.", + hw >= 0 ? "Head" : "Tail", Math.abs(hw), Math.abs(cw), cw <= 0 ? "right" : "left"); + } +} \ No newline at end of file diff --git a/wise-drunk-man/README.md b/wise-drunk-man/README.md new file mode 100644 index 0000000..ba61cc2 --- /dev/null +++ b/wise-drunk-man/README.md @@ -0,0 +1,11 @@ +# Wise drunk man +[*View on Codewars*](https://www.codewars.com/kata/wise-drunk-man) + +Fortunately last weekend, I met an utterly drunk old man. He was too drunk to be aggressive towards me. He was letting everything what he held out, from both his mind and his stomach. Although i was a bit uncomfortable, the old man's broken wisdom words caught my attention. But his talk was not continuous as it was frequently interrupted by an involuntary contractions ``` 'puke' and 'hiccup'``` . Now i am hiring you to clean up his ``` 'puke' ``` and ```'hiccup' ``` and tell me the old man's wisdom words.
Because drunk man also needs to take a pause and take a deep breath, you have to remove those pauses (redundant/unnecessary spaces). + + +## Timeline +- Created: 2017-04-08 +- Published: 2017-04-08 +- Approved: 2017-12-12 +- Completed: 2017-12-13 \ No newline at end of file diff --git a/wise-drunk-man/javascript/1/wise-drunk-man.js b/wise-drunk-man/javascript/1/wise-drunk-man.js new file mode 100644 index 0000000..9c44a7e --- /dev/null +++ b/wise-drunk-man/javascript/1/wise-drunk-man.js @@ -0,0 +1,3 @@ +function wdm(talk) { + return talk.split(/\s+/).filter(w => !['', 'puke', 'hiccup'].includes(w)).join(' ') +} \ No newline at end of file diff --git a/without-the-letter-e/README.md b/without-the-letter-e/README.md new file mode 100644 index 0000000..a174061 --- /dev/null +++ b/without-the-letter-e/README.md @@ -0,0 +1,22 @@ +# Without the letter 'E' +[*View on Codewars*](https://www.codewars.com/kata/without-the-letter-e) + + + +Is it possible to write a book without the letter 'e' ? + + +### Task + +Given String ```str```, return: +
  • How much "e" does it contains (case-insensitive) - return number as String.
  • +
  • If given String doesn't contain any "e", return: +`"There is no "e"."`
  • +
  • If given String is empty, return empty String.
  • +
  • If given String is `null`/`None`/`nil`, return `null`/`None`/`nil`
  • + +## Timeline +- Created: 2017-06-22 +- Published: 2017-06-22 +- Approved: 2017-06-25 +- Completed: 2018-03-11 \ No newline at end of file diff --git a/without-the-letter-e/javascript/1/without-the-letter-e.js b/without-the-letter-e/javascript/1/without-the-letter-e.js new file mode 100644 index 0000000..e9822d6 --- /dev/null +++ b/without-the-letter-e/javascript/1/without-the-letter-e.js @@ -0,0 +1,9 @@ +function findE(str) { + if (!str) { + return str + } + const count = Array.from(str.toLowerCase()).filter(c => c === 'e').length + return count === 0 + ? 'There is no "e".' + : String(count) +} \ No newline at end of file diff --git a/word-a10n-abbreviation/README.md b/word-a10n-abbreviation/README.md new file mode 100644 index 0000000..2b75182 --- /dev/null +++ b/word-a10n-abbreviation/README.md @@ -0,0 +1,30 @@ +# Word a10n (abbreviation) +[*View on Codewars*](https://www.codewars.com/kata/word-a10n-abbreviation) + +The word `i18n` is a common abbreviation of `internationalization` in the developer community, used instead of typing the whole word and trying to spell it correctly. Similarly, `a11y` is an abbreviation of `accessibility`. + +Write a function that takes a string and turns any and all "words" (see below) within that string of **length 4 or greater** into an abbreviation, following these rules: + +* A "word" is a sequence of alphabetical characters. By this definition, any other character like a space or hyphen (eg. "elephant-ride") will split up a series of letters into two words (eg. "elephant" and "ride"). +* The abbreviated version of the word should have the first letter, then the number of removed characters, then the last letter (eg. "elephant ride" => "e6t r2e"). + +## Example + +```js +abbreviate("elephant-rides are really fun!") +// ^^^^^^^^*^^^^^*^^^*^^^^^^*^^^* +// words (^): "elephant" "rides" "are" "really" "fun" +// 123456 123 1 1234 1 +// ignore short words: X X + +// abbreviate: "e6t" "r3s" "are" "r4y" "fun" +// all non-word characters (*) remain in place +// "-" " " " " " " "!" +=== "e6t-r3s are r4y fun!" +``` + +## Timeline +- Created: 2014-05-16 +- Published: 2014-05-16 +- Approved: 2014-10-14 +- Completed: 2015-05-24 \ No newline at end of file diff --git a/word-a10n-abbreviation/java/1/Abbreviator.java b/word-a10n-abbreviation/java/1/Abbreviator.java new file mode 100644 index 0000000..b00c473 --- /dev/null +++ b/word-a10n-abbreviation/java/1/Abbreviator.java @@ -0,0 +1,16 @@ +import java.util.regex.*; + +public class Abbreviator { + public String abbreviate(String s) { + Pattern p = Pattern.compile("[a-z]{4,}", Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(s); + StringBuffer sb = new StringBuffer(); + while (m.find()) { + String g = m.group(); + int l = g.length(); + m.appendReplacement(sb, g.substring(0, 1) + (l - 2) + g.substring(l - 1, l)); + } + m.appendTail(sb); + return sb.toString(); + } +} \ No newline at end of file diff --git a/word-a10n-abbreviation/javascript/1/word-a10n-abbreviation.js b/word-a10n-abbreviation/javascript/1/word-a10n-abbreviation.js new file mode 100644 index 0000000..0fccb8d --- /dev/null +++ b/word-a10n-abbreviation/javascript/1/word-a10n-abbreviation.js @@ -0,0 +1,6 @@ +function abbreviate(string) { + return string.replace(/[a-z]+/gi, function(word) { + var length = word.length; + return length < 4 ? word : word[0] + (length - 2) + word[length - 1]; + }); +} \ No newline at end of file diff --git a/word-a10n-abbreviation/javascript/2/word-a10n-abbreviation.js b/word-a10n-abbreviation/javascript/2/word-a10n-abbreviation.js new file mode 100644 index 0000000..818203d --- /dev/null +++ b/word-a10n-abbreviation/javascript/2/word-a10n-abbreviation.js @@ -0,0 +1,8 @@ +function abbreviate(string) { + return string.replace(/[a-z]+/gi, a10n); +} + +function a10n(word) { + let { length } = word; + return length < 4 ? word : word[0] + (length - 2) + word[length - 1]; +} \ No newline at end of file diff --git a/word-finder/README.md b/word-finder/README.md new file mode 100644 index 0000000..eda356b --- /dev/null +++ b/word-finder/README.md @@ -0,0 +1,38 @@ +# Word Finder +[*View on Codewars*](https://www.codewars.com/kata/word-finder) + +In this kata you have to extend the dictionary with a method, that returns a list of words matching a pattern. This pattern may contain letters (lowercase) and placeholders ("?"). A placeholder stands for exactly one arbitrary letter. + +Example: + +```javascript +var fruits = new Dictionary(['banana', 'apple', 'papaya', 'cherry']); +fruits.getMatchingWords('lemon'); // must return [] +fruits.getMatchingWords('cherr??'); // must return [] +fruits.getMatchingWords('?a?a?a'); // must return ['banana', 'papaya'] +fruits.getMatchingWords('??????'); // must return ['banana', 'papaya', 'cherry'] +``` + +```coffeescript +fruits = new Dictionary([ + 'banana' + 'apple' + 'papaya' + 'cherry' +]) +fruits.getMatchingWords 'lemon' # must return [] +fruits.getMatchingWords 'cherr??' # must return [] +fruits.getMatchingWords '?a?a?a' # must return ['banana', 'papaya'] +fruits.getMatchingWords '??????' # must return ['banana', 'papaya', 'cherry'] +``` + +Additional Notes: + +* the words and patterns are all lowercase +* the order of the returned words doesn't matter + +## Timeline +- Created: 2013-10-15 +- Published: 2013-10-15 +- Approved: null +- Completed: 2015-05-24 \ No newline at end of file diff --git a/word-finder/javascript/1/word-finder.js b/word-finder/javascript/1/word-finder.js new file mode 100644 index 0000000..0a96f72 --- /dev/null +++ b/word-finder/javascript/1/word-finder.js @@ -0,0 +1,10 @@ +function Dictionary(words) { + this.words = words; + + this.getMatchingWords = function(pattern) { + var regex = new RegExp('^' + pattern.replace(/\?/g, '.') + '$'); + return this.words.filter(function(word) { + return regex.test(word); + }); + } +} \ No newline at end of file diff --git a/you-cant-code-under-pressure-number-1/README.md b/you-cant-code-under-pressure-number-1/README.md new file mode 100644 index 0000000..127923c --- /dev/null +++ b/you-cant-code-under-pressure-number-1/README.md @@ -0,0 +1,10 @@ +# You Can't Code Under Pressure #1 +[*View on Codewars*](https://www.codewars.com/kata/you-cant-code-under-pressure-number-1) + +Code as fast as you can! You need to double the integer and return it. + +## Timeline +- Created: 2014-08-15 +- Published: 2014-08-15 +- Approved: 2014-08-25 +- Completed: 2015-05-09 \ No newline at end of file diff --git a/you-cant-code-under-pressure-number-1/java/1/Java.java b/you-cant-code-under-pressure-number-1/java/1/Java.java new file mode 100644 index 0000000..60da623 --- /dev/null +++ b/you-cant-code-under-pressure-number-1/java/1/Java.java @@ -0,0 +1,6 @@ +class Java { + public static int doubleInteger(int i) { + // Double the integer and return it! + return i<<1; + } +} \ No newline at end of file diff --git a/you-cant-code-under-pressure-number-1/javascript/1/you-cant-code-under-pressure-number-1.js b/you-cant-code-under-pressure-number-1/javascript/1/you-cant-code-under-pressure-number-1.js new file mode 100644 index 0000000..dbad232 --- /dev/null +++ b/you-cant-code-under-pressure-number-1/javascript/1/you-cant-code-under-pressure-number-1.js @@ -0,0 +1,3 @@ +function doubleInteger(i) { + return i << 1; +} \ No newline at end of file diff --git a/youre-a-square/README.md b/youre-a-square/README.md new file mode 100644 index 0000000..cd90987 --- /dev/null +++ b/youre-a-square/README.md @@ -0,0 +1,93 @@ +# You're a square! +[*View on Codewars*](https://www.codewars.com/kata/youre-a-square) + +## A square of squares +You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks! + +However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a _perfect square_. + +## Task + +Given an integral number, determine if it's a [square number](https://en.wikipedia.org/wiki/Square_number): + +> In mathematics, a __square number__ or __perfect square__ is an integer that is the square of an integer; in other words, it is the product of some integer with itself. + +The tests will _always_ use some integral number, so don't worry about that in dynamic typed languages. + +### Examples +```ruby +is_square (-1) # => false +is_square 3 # => false +is_square 4 # => true +is_square 25 # => true +is_square 26 # => false +``` +```python +is_square (-1) # => false +is_square 3 # => false +is_square 4 # => true +is_square 25 # => true +is_square 26 # => false +``` +```javascript +isSquare(-1) // => false +isSquare( 3) // => false +isSquare( 4) // => true +isSquare(25) // => true +isSquare(26) // => false +``` +```typescript +isSquare(-1) // => false +isSquare( 3) // => false +isSquare( 4) // => true +isSquare(25) // => true +isSquare(26) // => false +``` +```coffeescript +isSquare(-1) # => false +isSquare( 3) # => false +isSquare( 4) # => true +isSquare(25) # => true +isSquare(26) # => false +``` +```haskell +isSquare (-1) `shouldBe` False +isSquare 3 `shouldBe` False +isSquare 4 `shouldBe` True +isSquare 25 `shouldBe` True +isSquare 26 `shouldBe` False +``` +```java +Square.isSquare(-1) // => false +Square.isSquare( 3) // => false +Square.isSquare( 4) // => true +Square.isSquare(25) // => true +Square.isSquare(26) // => false +``` +```csharp +Kata.isSquare(-1) // => false +Kata.isSquare( 3) // => false +Kata.isSquare( 4) // => true +Kata.isSquare(25) // => true +Kata.isSquare(26) // => false +``` +```dart +isSquare(-1) // => false +isSquare( 3) // => false +isSquare( 4) // => true +isSquare(25) // => true +isSquare(26) // => false +``` +```cpp +is_square (-1) // false +is_square (3) // false +is_square (4) // true +is_square (25) // true +is_square (26) // false +``` + +## Timeline +- Created: 2015-01-23 +- Published: 2015-01-23 +- Approved: 2015-01-28 +- Completed: 2015-04-29 \ No newline at end of file diff --git a/youre-a-square/java/1/Square.java b/youre-a-square/java/1/Square.java new file mode 100644 index 0000000..46997cc --- /dev/null +++ b/youre-a-square/java/1/Square.java @@ -0,0 +1,5 @@ +public class Square { + public static boolean isSquare(int n) { + return Math.pow((int) Math.sqrt(n), 2) == n; + } +} \ No newline at end of file