Repository: Automedon/CodeWars-6-kyu-Soluitions Branch: master Commit: 60ae0ebf09c7 Files: 607 Total size: 858.5 KB Directory structure: gitextract_eg3a47vk/ ├── "this" is an other problem.js ├── "this" is an other solution.js ├── (L33T + Grεεκ) Case.js ├── +1 Array.js ├── 1 n- Cycle.js ├── 1RM Calculator.js ├── 80's Kids #7: She's a Small Wonder.js ├── A Rule of Divisibility by 13.js ├── A String of Sorts.js ├── A Taste of Curry.js ├── A disguised sequence (I).js ├── A tetrahedron of cannonballs.js ├── ASCII hex converter.js ├── Ackermann Function.js ├── Adding Binary Numbers.js ├── Adding ordinal indicator suffixes to numbers.js ├── Adjacent pairs in a string.js ├── Almost Even.js ├── Alphabet war - airstrike - letters massacre.js ├── Alphabetized.js ├── Alternating Loops.js ├── Anagram difference.js ├── Anything to integer.js ├── Arabian String.js ├── Are they the "same"? ├── Are we alternate?.js ├── Array Deep Count.js ├── Array Helpers.js ├── Array#reduce.js ├── Array.diff ├── Arrays Similar.js ├── Arrh, grabscrab!.js ├── Atbash Cipher Helper.js ├── Autocomplete! Yay!.js ├── Baby Magpies.js ├── Backspaces in string.js ├── Backwards Read Primes.js ├── Balance the arrays.js ├── Ball Upwards.js ├── Banker's Plan.js ├── Base Conversion.js ├── Basic Encryption.js ├── Binary string.js ├── Binary to Text (ASCII) Conversion.js ├── Binding within the List Monad.js ├── Bingo Card.js ├── Bit Counting ├── Bleatrix Trotter (The Counting Sheep).js ├── Body mass index calculation.js ├── Bouncing Balls ├── Bowling Pins.js ├── Braces status.js ├── Bracket Duplicates.js ├── Braking well.js ├── Break camelCase.js ├── Breaking search bad.js ├── Build Tower ├── Build Tower Advanced.js ├── Build a pile of Cubes ├── Buying a car ├── ByState.js ├── Calculate Hypotenuse of Right-angled Triangle.js ├── Calculate String Rotation.js ├── Calculate number of inversions in array.js ├── Calculate the area of a regular n sides polygon inside a circle of radius r.js ├── Calculate the function f(x) for a simple linear sequence (Easy).js ├── Calculate the function f(x) for a simple linear sequence (Medium).js ├── Cambridge Word Scramble.js ├── CamelCase Method.js ├── CamelCase to underscore.js ├── Can you keep a secret?.js ├── Case Reversal of Consecutive Duplicates.js ├── Cat Kata, Part 1.js ├── Cat and Mouse - Harder Version.js ├── Catalog.js ├── Chain Evaluation.js ├── Character frequency.js ├── Character limits: How long is your piece of string?.js ├── Character with longest consecutive repetition.js ├── Check if two words are isomorphic to each other.js ├── Checkerboard Generation.js ├── Checkered Board.js ├── Checking Groups ├── Chess Fun #1: Chess Board Cell Color.js ├── Chess Fun #2: Bishop And Pawn.js ├── Christmas Day.js ├── Christmas tree.js ├── Circularly Sorted Array.js ├── Clay Pigeon Shooting.js ├── Clock in Mirror.js ├── Clocky Mc Clock-Face.js ├── Closures and Scopes.js ├── Coding Meetup #10 - Higher-Order Functions Series - Create usernames.js ├── Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?.js ├── Coding Meetup #15 - Higher-Order Functions Series - Find the odd names.js ├── Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details.js ├── Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer.js ├── Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?.js ├── Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?.js ├── Collatz.js ├── Color Choice.js ├── Combinator Flip.js ├── Compare Versions.js ├── Compare powers.js ├── Compare section numbers.js ├── Complete Fibonacci Series.js ├── Complete The Pattern #12.js ├── Complete The Pattern #16.js ├── Complete The Pattern #8 - Number Pyramid.js ├── Complete The Pattern #9 - Diamond.js ├── Complete the table pattern.js ├── Consecutive strings ├── Consonant value,js ├── Convert integer to Whitespace format.js ├── Convert string to camel case ├── Coordinates Validator ├── Count Repeats.js ├── Count characters in your string ├── Count letters in string.js ├── Count the days!.js ├── Count the divisible numbers.js ├── Count the smiley faces! ├── Countdown - Longest Word.js ├── Counting DNA Nucleotides.js ├── Counting Duplicates ├── Create Four Letter Birding Codes from Bird Names.js ├── Create Parse HTML CSS Colors.js ├── Create a frame!.js ├── Creating a string for an array of objects from a set of words.js ├── Cryptography #1 - Viva Cesare.js ├── Cumulative Triangle.js ├── Custom Array Filters.js ├── Custom Setters and Getters.js ├── Custom each() Array method.js ├── Custom sort function.js ├── Cycle Detection: greedy algorithm.js ├── Cycle a list of values.js ├── Cylon Evolution.js ├── Dashatize it.js ├── Data Reverse.js ├── Data compression using run-length encoding.js ├── Dead Ants.js ├── Decipher this!.js ├── Decode Morse.js ├── Decode the Morse code ├── Decompose a number.js ├── Deep Freeze.js ├── Delete occurrences of an element if it occurs more than n times ├── Descriptive selections of data.js ├── Design a Simple Automaton (Finite State Machine).js ├── Detect Pangram ├── Difference of 2.js ├── Digital cypher vol 3 - missing key.js ├── Disease Spread.js ├── Disgruntled Employee.js ├── Disguised sequences (II).js ├── Divisible Ints.js ├── Does my number look big in this? ├── Don't rely on luck. ├── Doors in the school.js ├── Dragon's Curve.js ├── Drunk friend.js ├── Dubstep ├── Duplicate Arguments ├── Duplicate Encoder ├── Ease the StockBroker.js ├── Easter egg list in ReactJS.js ├── Easy Balance Checking.js ├── Easy Diagonal.js ├── Emotional Sort ( ︶︿︶).js ├── Encrypt this!.js ├── English beggars.js ├── Enigeliisohe too Eniigeeliiisoohee Toroanisoliatooro.js ├── Equal Sides Of An Array ├── Errors : histogram.js ├── Escape HTML Markup.js ├── Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck).js ├── Esolang: MiniBitMove.js ├── Esolang: Tick.js ├── Even Fibonacci Sum.js ├── Evil Autocorrect Prank.js ├── Exclamation marks series #17: Put the exclamation marks and question marks to the balance, Are they balanced?.js ├── Exercise in Summing.js ├── Extract Nested Object Reference.js ├── Extract last names of people named Michael.js ├── Extract the IDs from the data set.js ├── FIXME: Hello.js ├── Factorial length.js ├── Faro Shuffle Count.js ├── Fat Fingers.js ├── Feynman's square question.js ├── Fibonacci Reloaded.js ├── Fibonacci, Tribonacci and friends.js ├── File Path Operations.js ├── Financing Plan on Planet XY140Z-n.js ├── Financing a purchase.js ├── Find The Duplicated Number in a Consecutive Unsorted List - Tougher Version.js ├── Find The Parity Outlier ├── Find X.js ├── Find heavy ball - level: conqueror.js ├── Find the Mine!.js ├── Find the Nexus of the Codewars Universe.js ├── Find the Nth longest string in an Array.js ├── Find the missing letter ├── Find the missing term in an Arithmetic Progression ├── Find the odd int ├── Find the unique number ├── Find the unique number.js ├── Find within array.js ├── FizzBuzz Array! (Custom).js ├── Flexible Card Game.js ├── Floating-point Approximation (I).js ├── Fold an array.js ├── Follow that Spy.js ├── Football - Yellow and Red Cards.js ├── Format Text.js ├── Format a string of names like 'Bart, Lisa & Maggie'. ├── Format words into a sentence.js ├── Framed Reflection.js ├── Free pizza.js ├── Friday the 13ths.js ├── Frog jumping.js ├── Fruit Machine.js ├── Fun with lists: countIf.js ├── Fun with lists: filter.js ├── Fun with lists: map.js ├── Fun with lists: reduce.js ├── Fun with trees: max sum.js ├── Function Composition ├── Function composition.js ├── Function iteration.js ├── Functional Lists.js ├── GA-DE-RY-PO-LU-KI cypher vol 2.js ├── Genetic Algorithm Series - #5 Roulette wheel selection.js ├── Get All Possible Anagrams from a Hash.js ├── Get all array elements except those with specified indexes.js ├── Give me a Diamond ├── Good vs Evil ├── Greatest Position Distance Between Matching Array Values.js ├── Grill it!.js ├── Grouped by commas.js ├── Guess the number!.js ├── HTML dynamic color string generation.js ├── Hamming Distance.js ├── Handshake problem ├── Hanoi record.js ├── Happy numbers.js ├── Hard Time Bomb.js ├── Harshad or Niven numbers.js ├── Help Mrs Jefferson.js ├── Help the bookseller !.js ├── Hidden "Cubic" numbers.js ├── Highest Rank Number in an Array.js ├── Highest Scoring Word ├── Ho Ho Ho with Functions!.js ├── Holiday Shopping Priority Queue.js ├── Holy cats.js ├── House of cards.js ├── How Many Reindeers?.js ├── How Much?.js ├── How many feelings?.js ├── How much hex is the fish.js ├── How new Works.js ├── I need more speed!.js ├── IP Address to Number.js ├── IP Validation ├── IPv4 to int32 ├── IQ Test ├── Ideal electron distribution.js ├── If you can read this....js ├── Image host filename generator.js ├── Implementing Array.prototype.groupBy method.js ├── Inserting multiple strings into another string.js ├── Inside Out Strings.js ├── Integer depth.js ├── Integers: Recreation Two.js ├── Irreducible Sum of Rationals.js ├── Is Integer Array ?.js ├── Is a number prime? ├── Javascript filter - 2.js ├── Javascript filter - 3.js ├── JoJo's Bizarre Kata.js ├── Ka Ka Ka cypher - words only vol 1.js ├── Kebabize.js ├── Killer Garage Door.js ├── LICENSE.md ├── LOTTO 6 aus 49 - 6 of 49.js ├── Length of missing array ├── Letter Changes.js ├── Levenshtein Distance.js ├── Linear Regression of Y on X.js ├── Linked Lists - Insert Nth Node.js ├── Linked Lists - Insert Sort.js ├── Linked Lists - Recursive Reverse.js ├── Linked Lists - Remove Duplicates.js ├── Linked Lists - Shuffle Merge.js ├── Linked Lists - Sorted Insert.js ├── Linked Lists-Length & Count.js ├── Look and say numbers.js ├── Loose Change.js ├── Lottery Ticket ├── Lowest product of 4 consecutive numbers.js ├── Lucas numbers.js ├── MTV Cribs.js ├── Make the Deadfish swim..js ├── Making Change.js ├── Manhattan Distance.js ├── Master of Files.js ├── Matrix Addition.js ├── Matrix Transpose.js ├── Max Accessor Function.js ├── Maze Runner.js ├── Meeting.js ├── Mexican Wave.js ├── Midpoint Sum.js ├── Minutes to Midnight.js ├── Mirror object - tcejbo rorriM.js ├── Mirror, Mirror.js ├── Missing Alphabet.js ├── Mix Fruit Juice.js ├── Moduli number system.js ├── Most Frequent Weekdays.js ├── Moves in squared strings (II).js ├── Moves in squared strings (III).js ├── Moves in squared strings (IV).js ├── Mr. Safety's treasures.js ├── Multi-tap Keypad Text Entry on an Old Mobile Phone ├── Multiples of 3 and 5 redux.js ├── Multiples of 3 or 5 ├── Multiplication Tables.js ├── Multiplication table.js ├── Mutual Recursion.js ├── Mysterious function.js ├── N smallest elements in original order.js ├── N-th Fibonacci.js ├── Name That Integer.js ├── Name to Matrix.js ├── New Cashier Does Not Know About Space or Shift.js ├── Next Version.js ├── Non-even substrings.js ├── None shall pass.js ├── Not prime numbers.js ├── Nuclear Missile Manager.js ├── Number Format.js ├── Number Shortening Filter.js ├── Number Zoo Patrol.js ├── Number of anagrams in an array of words.js ├── Number of measurements to spot the counterfeit coin.js ├── Number of permutations without repetitions.js ├── Number pattern.js ├── Numerical Palindrome #1.5.js ├── Numericals of a String.js ├── Numerology.js ├── Odd Even number of divisors.js ├── Odd-heavy Array.js ├── Once.js ├── Only Duplicates.js ├── Ordinal Numbers.js ├── Ore Numbers.js ├── Organise duplicate numbers in list.js ├── PI approximation.js ├── Pad Left and Right.js ├── Padovan numbers.js ├── Pair of gloves.js ├── Palindrome for your Dome.js ├── Palindromes Below.js ├── Palindromic Numbers.js ├── Palindromization.js ├── Parabolic Arc Length.js ├── Parity bit - Error detecting code.js ├── Parse a linked list from a string.js ├── Pascal's Triangle #2.js ├── Pascal's Triangle.js ├── Password generator.js ├── Paths in the Grid.js ├── PatternCraft - Decorator.js ├── PatternCraft - State.js ├── PatternCraft - Strategy.js ├── Pentabonacci.js ├── Permutations and Dot Products.js ├── Persistent Bugger. ├── Pete, the baker (part 2).js ├── Piano Kata, Part 1.js ├── Piano Kata, Part 2.js ├── Ping-Pong service problem.js ├── Pizza pieces.js ├── Playing on a chessboard.js ├── Playing with digits ├── Playing with passphrases.js ├── Plenty of Fish in the Pond.js ├── Point in Polygon.js ├── Points On A Line.js ├── Points in the circle.js ├── Pokemon Damage Calculator.js ├── Polybius square cipher - encode.js ├── Pong! [Basics].js ├── Positions Average.js ├── Prefill an Array.js ├── Prime Factors.js ├── Prime factorization.js ├── Primorial Of a Number.js ├── Prize Draw.js ├── Proof Read.js ├── Pyramid Array.js ├── Quick (n choose k) calculator.js ├── README.md ├── RNA to Protein Sequence Translation.js ├── Rainfall.js ├── Range function.js ├── Rank Vector.js ├── Ranking System.js ├── Reach Me and Sum my Digits.js ├── Rectangle into Squares ├── Reducing by rules to get the result.js ├── Reducing by steps.js ├── Regex Tic Tac Toe Win Checker.js ├── Regexp Basics - is it IPv4 address?.js ├── Regexp basics - parsing time.js ├── Remember.js ├── Repeated Substring.js ├── Replace With Alphabet Position ├── Return 1, 2, 3 randomly.js ├── Reverse every other word in the string.js ├── Reverse or rotate?.js ├── Reverse polish notation calculator ├── RoboScript #1 - Implement Syntax Highlighting.js ├── Roman Numerals Decoder ├── Roman Numerals Encoder ├── Rotate Array (JS).js ├── Rotation Cipher Cracker.js ├── Round by 0.5 steps.js ├── Routes in a square grid.js ├── Run-length encoding.js ├── Running Average.js ├── Salesman's Travel.js ├── Same Array?.js ├── Santa's Master Plan.js ├── Scheduling (Shortest Job First or SJF).js ├── Schrödinger's Boolean.js ├── Scrabble best word.js ├── Secret Message.js ├── Separate The Wheat From The Chaff.js ├── Sequence generator.js ├── Sequences and Series.js ├── Shortest steps to a number.js ├── Simple Encryption #1 - Alternating Split ├── Simple Fun #116: Prime String.js ├── Simple Fun #135: Missing Alphabets.js ├── Simple Fun #165: Withdraw.js ├── Simple Fun #170: Sum Groups.js ├── Simple Fun #23: Square Digits Sequence.js ├── Simple Fun #258: Is Divisible By 6.js ├── Simple Fun #303: Prime Product.js ├── Simple Fun #319: Number And IP Address.js ├── Simple Fun #79: Delete a Digit.js ├── Simple Sentences.js ├── Simple Simple Simple String Expansion.js ├── Simple Substitution Cipher Helper.js ├── Simple Web Framework #1: Create a basic router.js ├── Simple card game.js ├── Simple frequency sort.js ├── Simple prime streaming.js ├── Simple string indices.js ├── Simple sum of pairs.js ├── Simple transposition.js ├── Simpson's Rule - Approximate Integration.js ├── Single Word Pig Latin.js ├── Single character palindromes.js ├── Sometimes.js ├── Sort Arrays (Ignoring Case).js ├── Sort My Animals.js ├── Sort odd and even numbers in different order.js ├── Sort sentence pseudo-alphabetically.js ├── Sort the odd ├── Sorting by bits.js ├── Special Multiples.js ├── Spelling Bee.js ├── Split Strings ├── Sqrt approximation.js ├── Squares in a Rectangle.js ├── Srot the inner ctonnet in dsnnieedcg oredr.js ├── Statistics for an Athletic Association.js ├── Steps in Primes.js ├── Stop gninnipS My sdroW! ├── Street Fighter 2 - Character Selection.js ├── String Breakers.js ├── String Integer Greater-than.js ├── String Shortener (shrink).js ├── String Suffixes.js ├── String array revisal.js ├── String average.js ├── String character frequency.js ├── String reduction.js ├── String searching with wildcard.js ├── String tops.js ├── String transformer.js ├── Stringing me along.js ├── Strip Url Params.js ├── Sum The Tree.js ├── Sum consecutives.js ├── Sum of Digits Digital Root ├── Sum of Two Integers.js ├── Sum of a Sequence [Hard-Core Version].js ├── Sum of many ints.js ├── Sum of nested numbers.js ├── Summarize ranges.js ├── Sums of Parts.js ├── Surrounding Primes for a value.js ├── T.T.T.17: Split odd and even.js ├── Take a Number And Sum Its Digits Raised To The Consecutive Powers And ....¡Eureka!! ├── Take a Ten Minute Walk ├── Tank Truck.js ├── Temperature converter.js ├── The Book of Mormon.js ├── The Deaf Rats of Hamelin.js ├── The Desperate Rocket Scientist.js ├── The Enigma Machine - Part 1: The Plugboard.js ├── The Freeway Game.js ├── The Modulo-3 Sequence.js ├── The Most Sacred of Days.js ├── The Non-Discriminate Factorial.js ├── The Office V - Find a Chair.js ├── The Shell Game.js ├── The Spider and the Fly (Jumping Spider).js ├── The Supermarket Queue.js ├── The Vowel Code.js ├── The elegance of the code.js ├── The maximum and minimum difference -- Simple version ├── The maximum sum value of ranges -- Simple version.js ├── The nth smallest integer.js ├── The range() function.js ├── The takeWhile Function.js ├── Think how isArray function can be implemented.js ├── Thinkful - Logic Drills: Red and bumpy.js ├── Three added Characters.js ├── Throwing Darts.js ├── Tick Toward.js ├── Time-like string format.js ├── Title Case ├── Tortoise racing ├── Transform To Prime.js ├── Tree Depth.js ├── Triangle number check.js ├── Triangle type ├── Tribonacci Sequence ├── Trim a String.js ├── Triple trouble ├── Tug-o'-War.js ├── Turkish National Identity Number.js ├── Two Joggers ├── Two Sum.js ├── Two cube sums.js ├── Typer.js ├── Unary function chainer.js ├── Unique In Order ├── Unwanted dollars.js ├── Update inventory in your smartphone store.js ├── Upside down numbers.js ├── Upside-Down Pyramid Addition...REVERSED!.js ├── Urban Dictionary.js ├── Valid Braces ├── Valid Phone Number ├── Valid string.js ├── Validate Credit Card Number.js ├── Vasya - Clerk.js ├── Vasya and Stairs.js ├── Vasya and System of Equations.js ├── Vowel Recognition.js ├── Vowel Shifting.js ├── Walter's miraculous FizzBuzz factory.js ├── WeIrD StRiNg CaSe ├── What century is it?.js ├── What's in a name?.js ├── Wheel of Fortune.js ├── Where is my parent!?(cry).js ├── Which are in? ├── Which filetypes are you using the most?.js ├── Who likes it? ├── Who won the election?.js ├── Wind component calculation.js ├── Word Mesh.js ├── Word Patterns.js ├── Word Segmentation: MaxMatch.js ├── Word a10n (abbreviation) ├── Wordify an integer.js ├── World Bits War.js ├── Write JavaScript's 'call' function using apply..js ├── Write Number in Expanded Form ├── Write Number in Expanded Form - Part 2.js ├── X marks the spot!.js ├── Your Ride Is Here.js ├── Your order, please ├── Zero fill... for the Queen!.js ├── Ziiiiip!.js ├── bit "Wise" #1: XOR-cism.js ├── bit "Wise" #2: SHIFT-iness.js ├── compute cube as sums.js ├── extract file name.js ├── first character that repeats.js ├── longest_palindrome.js ├── mkdir -p.js ├── new with apply.js ├── replaceAll(input, find, replace).js ├── search in multidimensional array.js ├── uniq (UNIX style).js ├── up AND down.js └── zipWith.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: "this" is an other problem.js ================================================ /* Description: After you've solved @priyankaherur's problem ( http://www.codewars.com/kata/this-is-a-problem/javascript ) you may try to solve this other one. The problem: Having created a function NamedOne which takes first & last names as parameters and returns an object with firstName, lastName and fullName ( = firstName + a space + lastName ) properties which should be all accessibles, we discovered that "accessible" also means "mutable". If, for example, we've got a "NamedOne" like this : var namedOne = new NamedOne("Naomi","Wang") namedOne.firstName // -> "Naomi" namedOne.lastName // -> "Wang" namedOne.fullName // -> "Naomi Wang" ...properties may be changed : namedOne.firstName = "John" namedOne.firstName // -> "John" namedOne.lastName = "Doe" namedOne.lastName // -> "Doe" ...but all properties are not updated ! namedOne.fullName // -> "Naomi Wang" //-- Oh no ! we want fullName == "John Doe" now ! Your mission: So the purpose of this kata is to create an object with accessible and "updatable" (can i say that?) properties. If .firstName or .lastName are changed, then .fullName should also be changed If .fullName is changed, then .firstName and .lastName should also be changed. Note : "input format" to .fullName will be firstName + space+ lastName. If given fullName isn't valid then no property is changed. Examples: var namedOne = new NamedOne("Naomi","Wang") namedOne.firstName = "John" namedOne.lastName = "Doe" // ...then... namedOne.fullName // -> "John Doe" // -- And : namedOne.fullName = "Bill Smith" // ...then... namedOne.firstName // -> "Bill" namedOne.lastName // -> "Smith" // -- But : namedOne.fullName = "Tom" // -> no : lastName missing namedOne.fullName = "TomDonnovan" // -> no : no space between first & last names namedOne.fullName // -> "Bill Smith" (unchanged) Can you change our function to create such a NamedOne object ? ( Hint: in this kata you'll try to define properties of an object ) */ class NamedOne { constructor(f, l) { this.firstName = f; this.lastName = l } get fullName() { return this.firstName + ' ' + this.lastName } set fullName(v) { if (/ /.test(v)) [this.firstName, this.lastName] = v.split(' ') } } ================================================ FILE: "this" is an other solution.js ================================================ /* Description: In a previous kata ( http://www.codewars.com/kata/547f1a8d4a437abdf800055c ) we try to create an object with mutable properties. The function NamedOne taken first & last names as parameters, returned an object with firstName, lastName and fullName ( = firstName + a space + lastName ) properties. These properties were mutable. For example, with a "NamedOne" like this : var namedOne = new NamedOne("Naomi","Wang") namedOne.fullName // -> "Naomi Wang" ...we were able to change its properties: namedOne.firstName = "John" namedOne.lastName = "Doe" namedOne.fullName // -> "John Doe" //..or.. namedOne.fullName = "Bill Smith" namedOne.firstName // -> "Bill" namedOne.lastName // -> "Smith" ##Your mission On the contrary, the purpose of this kata is to create an OnceNamedOne object with immutable properties. That means .firstName, .lastName and .fullName are defined into the Constructor and can't be no more changed. The properties are still readable using the dot or bracket notation but there're not writable. ##Examples: var onceNamed = new OnceNamedOne("Naomi","Wang") // ...then... onceNamed.firstName // -> "Naomi" onceNamed.lastName // -> "Wang" onceNamed.fullName // -> "Naomi Wang" // ...if you try : ... onceNamed.firstName = "Bill" // ...or... onceNamed['lastName'] = "Smith" // ...then... onceNamed['firstName'] // -> "Naomi" onceNamed['lastName'] // -> "Wang" onceNamed['fullName'] // -> "Naomi Wang" // ..but you can still create other instances.. var otherOne = new OnceNamedOne("Don","Jones") otherOne.fullName // -> "Don Jones" Can you change our function to create such a OnceNamedOne object ? ( Hint: in this kata you'll try to define properties of an object ) */ function OnceNamedOne(first, last) { this.firstName = first; this.lastName = last; this.fullName = this.firstName + ' ' + this.lastName; Object.freeze(this) } ================================================ FILE: (L33T + Grεεκ) Case.js ================================================ /* Description: Getting Familiar: LEET: (sometimes written as "1337" or "l33t"), also known as eleet or leetspeak, is another alphabet for the English language that is used mostly on the internet. It uses various combinations of ASCII characters to replace Latinate letters. For example, leet spellings of the word leet include 1337 and l33t; eleet may be spelled 31337 or 3l33t. GREEK: The Greek alphabet has been used to write the Greek language since the 8th century BC. It was derived from the earlier Phoenician alphabet, and was the first alphabetic script to have distinct letters for vowels as well as consonants. It is the ancestor of the Latin and Cyrillic scripts.Apart from its use in writing the Greek language, both in its ancient and its modern forms, the Greek alphabet today also serves as a source of technical symbols and labels in many domains of mathematics, science and other fields. Your Task : You have to create a function **GrεεκL33t** which takes a string as input and returns it in the form of (L33T+Grεεκ)Case. Note: The letters which are not being converted in (L33T+Grεεκ)Case should be returned in the lowercase. (L33T+Grεεκ)Case: A=α (Alpha) B=β (Beta) D=δ (Delta) E=ε (Epsilon) I=ι (Iota) K=κ (Kappa) N=η (Eta) O=θ (Theta) P=ρ (Rho) R=π (Pi) T=τ (Tau) U=μ (Mu) V=υ (Upsilon) W=ω (Omega) X=χ (Chi) Y=γ (Gamma) Examples: GrεεκL33t("CodeWars") = "cθδεωαπs" GrεεκL33t("Kata") = "κατα" */ function GrεεκL33t(str){ let dict = {a:'α',b:'β',d:'δ',e:'ε',i:'ι',k:'κ',n:'η',o:'θ',p:'ρ',r:'π',t:'τ',u:'μ', v:'υ',w:'ω',x:'χ',y:'γ'} return str.replace(/./g,v=>{ if (dict[v.toLowerCase()]){ return v===v.toUpperCase()?dict[v.toLowerCase()]:dict[v] } return v.toLowerCase() }) } ================================================ FILE: +1 Array.js ================================================ /* Description: Given an array of integers of any length, return an array that has 1 added to the value represented by the array. the array can't be empty only non-negative, single digit integers are allowed Return nil (or your language's equivalent) for invalid inputs. Examples For example the array [2, 3, 9] equals 239, adding one would return the array [2, 4, 0]. [4, 3, 2, 5] would return [4, 3, 2, 6] */ function upArray(arr){ if (!arr.every(v=>v>=0)||arr.length===0) return null if (arr.some(v=>v.toString().length>1)) return null let arr1 =[]; for (let i=0;iArray.isArray(v)?v.join('')*1:v) return (arr1.join('')).split('').map(v=>v*1) } ================================================ FILE: 1 n- Cycle.js ================================================ /* Description: Let be n an integer prime with 10 e.g. 7. 1/7 = 0.142857 142857 142857 .... We see that the decimal part has a cycle: 142857. The length of this cycle is 6. In the same way: 1/11 = 0.09 09 09 .... Cycle length is 2. Task Given an integer n (n > 1), the function cycle(n) returns the length of the cycle if n and 10 are coprimes, otherwise returns -1. Exemples: cycle(5) = -1 cycle(13) = 6 -> 0.076923 076923 0769 cycle(21) = 6 -> 0.047619 047619 0476 cycle(27) = 3 -> 0.037 037 037 037 0370 cycle(33) = 2 -> 0.03 03 03 03 03 03 03 03 cycle(37) = 3 -> 0.027 027 027 027 027 0 cycle(94) = -1 cycle(22) = -1 since 1/22 ~ 0.0 45 45 45 45 ... */ function cycle(n) { if (n%2 == 0 || n%5 == 0) { return -1 } else { let res = 10 % n, c = 1; while (res != 1) { res = res * 10 % n; c++; } return c; } } ================================================ FILE: 1RM Calculator.js ================================================ /* Description: You just got done with your set at the gym, and you are wondering how much weight you could lift if you did a single repetition. Thankfully, a few scholars have devised formulas for this purpose (from Wikipedia) : Epley McGlothin Lombardi Your function will receive a weight w and a number of repetitions r and must return your projected one repetition maximum. Since you are not sure which formula to use and you are feeling confident, your function will return the largest value from the three formulas shown above, rounded to the nearest integer. However, if the number of repetitions passed in is 1 (i.e., it is already a one rep max), your function must return w. Also, if the number of repetitions passed in is 0 (i.e., no repetitions were completed), your function must return 0. */ function calculate1RM(w, r){ let a= w *(1+r/30); let b= (100*w)/(101.3-2.67123*r); let c=w*(r**0.1); if (r===0||w===0) return 0; if (r===1) return w; return Math.round(Math.max(a,b,c)) } ================================================ FILE: 80's Kids #7: She's a Small Wonder.js ================================================ /* Description: Vicky is quite the small wonder. Most people don't even realize she's not a real girl, but a robot living amongst us. Sure, if you stick around her home for a while you might see her creator open up her back and make a few tweaks and even see her recharge in the closet instead of sleeping in a bed. In this kata, we're going to help Vicky keep track of the words she's learning. Write a function, learnWord(word) which is a method of the Robot object. The function should report back whether the word is now stored, or if she already knew the word. Example: var vicky = new Robot(); vicky.learnWord('hello') -> 'Thank you for teaching me hello' vicky.learnWord('abc') -> 'Thank you for teaching me abc' vicky.learnWord('hello') -> 'I already know the word hello' vicky.learnWord('wow!') -> 'I do not understand the input' Robot vicky = new Robot(); vicky.learnWord("hello") -> "Thank you for teaching me hello" vicky.learnWord("abc") -> "Thank you for teaching me abc" vicky.learnWord("hello") -> "I already know the word hello" vicky.learnWord("wow!") -> "I do not understand the input" Case shouldn't matter. Only alpha characters are valid. There's also a little trick here. Enjoy! */ function Robot() { this.arr =['i', 'already', 'know', 'the', 'word','thank', 'you', 'for','me','teaching','understand'] } Robot.prototype.learnWord = function(word) { if (/\W|\d|\s/i.test(word)||!word) return "I do not understand the input" if (!this.arr.includes(word.toLowerCase())){ this.arr.push(word.toLowerCase()) return `Thank you for teaching me ${word}` }else return `I already know the word ${word}` } ================================================ FILE: A Rule of Divisibility by 13.js ================================================ /* Description: When you divide the successive powers of 10 by 13 you get the following remainders of the integer divisions: 1, 10, 9, 12, 3, 4. Then the whole pattern repeats. Hence the following method: Multiply the right most digit of the number with the left most number in the sequence shown above, the second right most digit to the second left most digit of the number in the sequence. The cycle goes on and you sum all these products. Repeat this process until the sequence of sums is stationary. ........................................................................... Example: What is the remainder when 1234567 is divided by 13? 7×1 + 6×10 + 5×9 + 4×12 + 3×3 + 2×4 + 1×1 = 178 We repeat the process with 178: 8x1 + 7x10 + 1x9 = 87 and again with 87: 7x1 + 8x10 = 87 ........................................................................... From now on the sequence is stationary and the remainder of 1234567 by 13 is the same as the remainder of 87 by 13: 9 Call thirt the function which processes this sequence of operations on an integer n (>=0). thirt will return the stationary number. thirt(1234567) calculates 178, then 87, then 87 and returns 87. thirt(321) calculates 48, 48 and returns 48 */ function thirt(n) { const dict=[1, 10, 9, 12, 3, 4] let sum=n; while(1){ let temp=sum sum=sum.toString().split``.reverse().join``.split``.map((v,i)=>{ v=v*dict[i%6] return v }).reduce((a,b)=>a+b,0) if (sum===temp){break} } return sum } ================================================ FILE: A String of Sorts.js ================================================ /* Description: Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second. sortString("foos", "of") => "oofs" sortString("string", "gnirts") => "gnirts" sortString("banana", "abn") => "aaabnn" To elaborate, the second string defines the ordering. It is possible that in the second string characters repeat, so you should remove repeating characters, leaving only the first occurrence. Any character in the first string that does not appear in the second string should be sorted to the end of the result in original order. */ function sortString(string,ordering) { ordering=ordering.split`` let arr1 = string.split``.filter(v=>ordering.includes(v)).sort((a,b)=>ordering.indexOf(a)-ordering.indexOf(b)) let arr2 = string.split``.filter(v=>!ordering.includes(v)) return arr1.join``+arr2.join`` } ================================================ FILE: A Taste of Curry.js ================================================ /* Description: Your relative have decided to open a small Indian restaurant, and so she bought an automatic cooker. It publishes an API function function cook( /*String*/ dish, /*Number*/ nServings /* , other params, specific to the dish - represented by strings */ ) { ... }``` which takes an amount of servings, dish name and several other parameters which can vary per dish (yes, this is a very advanced cooking machine). The restaurant instantly became very popular, and your relative noticed that most people order some curry with additional ingredients - because she was already tired to repeatedly type the word _'curry'_ when making a request to cooker. So she decided to ask for your help. She cannot lend you her cooker, because it is in constant use - so she needs you to write a function ```javascript function curry(fun, /*args*/) { ... } which takes another function fun and an arbitrary number of other arguments - and returns a function, which works like fun with the first arguments replaced by the remaining arguments of curry. For example function add(a, b, c) { return a+b+c; } var addOne = curry(add , 1); add(1, 2, 3) === addOne(2, 3); And one more thing - some code warrior who was having a snack at your relative's restaurant told her that there is such thing as execution context, and that the cook function might rely on it somehow - it is designed to work exclusively with cooking machine after all. So another request for curry function is that if the resulting function is invoked with context ctx the original function inside it should also be invoked with context ctx For example, var obj = { a: 'foo', b: function (a) { return this.a + a; } } obj.foobar = curry(obj.b, 'bar'); obj.foobar() //should return foobar */ function curry(fun,...args) { return function(...arg2) { return fun.call(this,...args,...arg2); } } ================================================ FILE: A disguised sequence (I).js ================================================ /* Description: Given u0 = 1, u1 = 2 and the relation 6unun+1-5unun+2+un+1un+2 = 0 calculate un for any integer n >= 0. #Examples fcn(n) returns un: fcn(17) -> 131072, fcn(21) -> 2097152 Remark: You can take two points of view to do this kata: the first one purely algorithmic from the definition of un the second one - not at all mandatory, but as a complement - is to get a bit your head around and find which sequence is hidden behind un. */ function fcn (n) { return 2**n } ================================================ FILE: A tetrahedron of cannonballs.js ================================================ /* Description: Previously on Codewars... "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) * ** *** * ** * In the Triangular Treasure kata you need to return the nth triangular number." (If you haven't solved Triangular Treasure go solve it, cause you are going to need the solution here) Now, in this kata... The triangular number you just calculated is going to be the base of our "brand new" tetrahedral stack. You need to calculate the number of cannonballs that can be stacked to form a regular tetrahedron with the given edge's length. A regular tetrahedron is a platonic solid composed of triangular faces with all the edges having the same length. *** Please note, this is not a square pyramid, but a triangular one For our problem, we are going to consider that the length of the edge is the number of cannonballs that can be lined up along one edge. *** Please note, we are not talking about volume here, we are talking about stacking spheres. So. Given an edge with length = 1, the number of cannonballs contained in the base triangle (the triangular number) will be 1, and the number of cannonballs you would be able to stack in a regular tetrahedron will be 1. The table for the series is this: (edge's length -> triangular number -> "cannonball number") 1 -> 1 -> 1 2 -> 3 -> 4 3 -> 6 -> 10 4 -> 10 -> 20 5 -> 15 -> 35 6 -> 21 -> 56 7 -> 28 -> 84 8 -> 36 -> 120 9 -> 45 -> 165 10 -> 55 -> 220 11 -> 66 -> 286 12 -> 78 -> 364 13 -> 91 -> 455 14 -> 105 -> 560 15 -> 120 -> 680 16 -> 136 -> 816 17 -> 153 -> 969 18 -> 171 -> 1140 19 -> 190 -> 1330 20 -> 210 -> 1540 You can see some properties here: The nth triangular number is: t(n) = n + t(n-1) The nth cannonball number is: c(n) = t(n) + c(n-1) Hint: Remember that, even though, we are talking about tetrahedrons the key number here is not 4 but 3. *** Please, don't worry about the parameters. You will only receive positive integers. */ function tetrahedron(size) { return size*(size + 1)*(size + 2)/6 } ================================================ FILE: ASCII hex converter.js ================================================ /* Write a module Converter that can take ASCII text and convert it to hexadecimal. The class should also be able to take hexadecimal and convert it to ASCII text. Example Converter.toHex("Look mom, no hands") => "4c6f6f6b206d6f6d2c206e6f2068616e6473" Converter.toAscii("4c6f6f6b206d6f6d2c206e6f2068616e6473") => "Look mom, no hands" */ var Converter = { toAscii: function (hex) { let arr=[]; for (let i=0;iString.fromCharCode(parseInt(v,16))).join('') }, toHex: function (ascii) { return ascii.split('').map(v=>v.charCodeAt().toString(16)).join('') } } ================================================ FILE: Ackermann Function.js ================================================ /* Description: The Ackermann function is a famous function that played a big role in computability theory as the first exemple of a total computable function that is not primitive recursive. Since then the function has been a bit simplified but is still of good use. Due to its definition in terms of extremely deep recursion it can be used as a benchmark of a compiler's ability to optimize recursion. The goal of this kata is to code a function wich will be given two input, m and n, and will return the Ackermann number A(m,n) defined by: A(m,n) = n+1 if m=0 A(m,n) = A(m-1,1) if m>0 , n=0 A(m,n) = A(m-1,A(m,n-1)) if m,n > 0 m,n should be non-negative integers, the function should return null (Javascript), None (Python), or nil (Ruby) for other type, non-integer and negative numbers. In C, input is restricted to integer type. */ Ackermann=function(m,n) { if (m<0||n<0){ return null } if (m == 0) { return n + 1; } if (m>0&&n == 0) { return Ackermann(m - 1, 1) } if (m>0&&n>0){ return Ackermann(m-1,Ackermann(m,n-1)) } } ================================================ FILE: Adding Binary Numbers.js ================================================ /* Description: ##Task: You have to write a function add which takes two binary numbers as strings and returns their sum as a string. ##Note: You are not allowed to convert binary to decimal & vice versa. The sum should contain No leading zeroes. ##Examples: add('111','10'); => '1001' add('1101','101'); => '10010' add('1101','10111') => '100100' */ function add(a,b){ a = a.split('').reverse(); b = b.split('').reverse(); var result = '', temp = 0; while (a.length || b.length || temp) { temp += (~~a.shift()) + (~~b.shift()); let mod = temp % 2; result = mod + result; temp = temp > 1; } return (+result) ? result.replace(/^0+/, '') : '0'; }; ================================================ FILE: Adding ordinal indicator suffixes to numbers.js ================================================ /* Description: Finish the function numberToOrdinal, which should take a number and return it as a string with the correct ordinal indicator suffix (in English). That is: numberToOrdinal(1) ==> '1st' numberToOrdinal(2) ==> '2nd' numberToOrdinal(3) ==> '3rd' numberToOrdinal(4) ==> '4th' ... and so on For the purposes of this kata, you may assume that the function will always be passed a non-negative integer. If the function is given 0 as an argument, it should return '0' (as a string). To help you get started, here is an excerpt from Wikipedia's page on Ordinal Indicators: st is used with numbers ending in 1 (e.g. 1st, pronounced first) nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second) rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third) As an exception to the above rules, all the "teen" numbers ending with 11, 12 or 13 use -th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth) th is used for all other numbers (e.g. 9th, pronounced ninth). */ function numberToOrdinal(n) { var suffix = "th"; if (n == 0) suffix = ""; if (n % 10 == 1 && n % 100 != 11) suffix = "st"; if (n % 10 == 2 && n % 100 != 12) suffix = "nd"; if (n % 10 == 3 && n % 100 != 13) suffix = "rd"; return n + suffix; } ================================================ FILE: Adjacent pairs in a string.js ================================================ /* Description: You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that *"the"* is doubled in the first sentence of this description? As as aS you can see, it's not easy to spot those errors, especially if words differ in case, like *"as"* at the beginning of the sentence. Write a function countAdjacentPairs that counts the number of adjacent pairs in a string. It should be case-insenstive. A word in this kata is a sequence of non-whitespace characters enclosed by whitespace, so the string "dog dog." contains the two words "dog" and "dog.", which differ. The occurence of two or more equal words next after each other count as one. Example: countAdjacentPairs "dog cat" == 0 countAdjacentPairs "dog dog cat" == 1 countAdjacentPairs "apple dog cat" == 0 countAdjacentPairs "pineapple apple dog cat" == 0 countAdjacentPairs "apple apple dog cat" == 1 countAdjacentPairs "apple dog apple dog cat" == 0 countAdjacentPairs "dog dog dog dog dog dog" == 1 countAdjacentPairs "dog dog dog dog cat cat" == 2 countAdjacentPairs "cat cat dog dog cat cat" == 3 //returns 0 countAdjacentPairs('') // returns 1 countAdjacentPairs('cat dog dog') // returns 1 (The first pair has been matched, and will be ignored from then on). countAdjacentPairs('dog dog dog') // returns 2 countAdjacentPairs('cat cat dog dog cat') */ function countAdjacentPairs(searchString) { let obj={}; searchString.toLowerCase().split(' ').map(v=>obj[v]=obj[v]?obj[v]+1:1); return Object.values(obj).filter(v=>v>1).length } ================================================ FILE: Almost Even.js ================================================ /* Description: We need the ability to divide an unknown integer into a given number of even parts — or at least as even as they can be. The sum of the parts should be the original value, but each part should be an integer, and they should be as close as possible. Example code: splitInteger(20, 6) // returns [3, 3, 3, 3, 4, 4] Complete the function so that it returns an array of integer representing the parts. Ignoring the order of the parts, there is only one valid solution for each input to your function! (Also, there is no reason to test for edge cases: the input to your function will always be valid for this kata.) */ var splitInteger = function(num, parts) { let n =Math.floor(num/parts) const arr = []; for (let i=0;ia+b,0)===num) return arr for (let i=0;ia+b,0)===num) return arr } } ================================================ FILE: Alphabet war - airstrike - letters massacre.js ================================================ /* Description: Introduction There is a war and nobody knows - the alphabet war! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters called airstrike to help them in war - dashes and dots are spreaded everywhere on the battlefield. Task Write a function that accepts fight string consists of only small letters and * which means a bomb drop place. Return who wins the fight after bombs are exploded. When the left side wins return Left side wins!, when the right side wins return Right side wins!, in other case return Let's fight again!. The left side letters and their power: w - 4 p - 3 b - 2 s - 1 The right side letters and their power: m - 4 q - 3 d - 2 z - 1 The other letters don't have power and are only victims. The * bombs kills the adjacent letters ( i.e. aa*aa => a___a, **aa** => ______ ); Example alphabetWar("s*zz"); //=> Right side wins! alphabetWar("*zd*qm*wp*bs*"); //=> Let's fight again! alphabetWar("zzzz*s*"); //=> Right side wins! alphabetWar("www*www****z"); //=> Left side wins! */ function alphabetWar(fight) { let dict={'w':4,'p':3,'b':2,'s':1,'m':-4,'q':-3,'d':-2,'z':-1}; const arr=[]; const arr1=fight.split('') for (let i=0;ia+(dict[b]?dict[b]:0),0) return sum<0?'Right side wins!':sum>0?'Left side wins!':'Let\'s fight again!'; } ================================================ FILE: Alphabetized.js ================================================ /* Description: The alphabetized kata Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed! The input is restricted to contain no numerals and only words containing the english alphabet letters. Example: alphabetized("The Holy Bible") // "BbeehHilloTy" Inspired by Tauba Auerbach */ function alphabetized(s) { var ans=""; for (var i=97; i<123; ++i) for (var j=0; jv.length)) for(let i=0;i ExampleName camelize("your-NaMe-here") // => YourNameHere camelize("testing ABC") // => TestingAbc */ function camelize(str){ return str.replace(/[^a-z0-9]/gi,' ').split` `.map(v=>v.slice(0,1).toUpperCase()+v.slice(1).toLowerCase()).join`` } ================================================ FILE: Are they the "same"? ================================================ /* Description: 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 or nothing (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. */ function comp(array1, array2){ array1=array1.map(v=>v*v) return array2?array1.reduce((a,b)=>a+b,0)===array2.reduce((a,b)=>a+b,0):false } ================================================ FILE: Are we alternate?.js ================================================ /* Description: Create a function isAlt() that accepts a string as an argument and validates whether the vowels (a, e, i, o, u) and consonants are in alternate order. isAlt("amazon") // true isAlt("apple") // false isAlt("banana") // true Arguments consist of only lowercase letters. */ function isAlt(word) { return word.split('').every((v,i)=>{ if (/[aeiou]/.test(word[0])){ if (i%2===0&&/[aeiou]/.test(v)){ return true } else if (i%2!==0&&!/[aeiou]/.test(v)){ return true } else {return false} } if (!/[aeiou]/.test(word[0])){ if (i%2==0&&!/[aeiou]/.test(v)){ return true } else if (i%2!==0&&/[aeiou]/.test(v)){ return true } else {return false} } }) } ================================================ FILE: Array Deep Count.js ================================================ /* Description: Array.prototype.length will give you the number of top-level elements in an array. Your task is to create a function deepCount that returns the number of ALL elements within an array, including any within inner-level arrays. For example: deepCount([1, 2, 3]); //>>>>> 3 deepCount(["x", "y", ["z"]]); //>>>>> 4 deepCount([1, 2, [3, 4, [5]]]); //>>>>> 7 The input will always be an array. */ function deepCount(a){ return a.reduce((s,e)=>s+(Array.isArray(e)?deepCount(e):0),a.length); } ================================================ FILE: Array Helpers.js ================================================ /* Description: This kata is designed to test your ability to extend the functionality of built-in classes. In this case, we want you to extend the built-in Array class with the following methods: square(), cube(), average(), sum(), even() and odd(). Explanation: square() must return a copy of the array, containing all values squared cube() must return a copy of the array, containing all values cubed average() must return the average of all array values; on an empty array must return NaN (note: the empty array is not tested in Ruby!) sum() must return the sum of all array values even() must return an array of all even numbers odd() must return an array of all odd numbers Note: the original array must not be changed in any case! Example var numbers = [1, 2, 3, 4, 5]; numbers.square(); // must return [1, 4, 9, 16, 25] numbers.cube(); // must return [1, 8, 27, 64, 125] numbers.average(); // must return 3 numbers.sum(); // must return 15 numbers.even(); // must return [2, 4] numbers.odd(); // must return [1, 3, 5] */ Array.prototype.square=function(){ return this.map(v=>v*v) } Array.prototype.cube=function(){ return this.map(v=>v*v*v) } Array.prototype.sum=function(){ return this.reduce((a,b)=>a+b,0) } Array.prototype.average=function(){ return this.reduce((a,b)=>a+b,0)/this.length } Array.prototype.even=function(){ return this.filter(v=>v%2==0) } Array.prototype.odd=function(){ return this.filter(v=>v%2!==0) } ================================================ FILE: Array#reduce.js ================================================ /* Description: In this kata, you must define the Array.reduce method. I have disabled the pre-existing reduce methods. Here's how it works: [1,2,3].reduce( function(sum, next){return sum+next}, 0) // => 6 ['a','b','a'].reduce( function(obj, elem){if(!obj[elem]) obj[elem] = 0; obj[elem] += 1; return obj}, {}) // => {'a':2, 'b':1} Summary: The reduce method goes through each element of an array, applies the function to whatever the function returned last, and returns the last outcome. On the first iteration, it should pass the initial value to the function, as well as the first element of the array. If no initial value is passed, skip to the first element of the array. Ruby methods should expect a lambda. */ Array.prototype.reduce = function(process, initial) { for (let i = 0; i < this.length; i++) { if (!initial){i++;initial=this[0]} initial = process(initial, this[i]); } return initial } ================================================ FILE: Array.diff ================================================ /* Description: Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list a, which are present in list b. array_diff([1,2],[1]) == [2] If a value is present in b, all of its occurrences must be removed from the other: array_diff([1,2,2,2,3],[2]) == [1,3] */ function array_diff(a, b) { return a.filter(e => !b.includes(e)); } ================================================ FILE: Arrays Similar.js ================================================ /* Description: Write a function that determines whether the passed in arrays are similar. Similar means they contain the same elements, and the same number of occurrences of elements. var arr1 = [1, 2, 2, 3, 4], arr2 = [2, 1, 2, 4, 3], arr3 = [1, 2, 3, 4], arr4 = [1, 2, 3, "4"] arraysSimilar(arr1, arr2); // Should equal true arraysSimilar(arr2, arr3); // Should equal false arraysSimilar(arr3, arr4); // Should equal false */ function arraysSimilar(arr1, arr2) { arr1=arr1.sort((a,b)=>a-b) arr2=arr2.sort((a,b)=>a-b) return arr1.length>arr2.length?arr1.every((v,i)=>v===arr2[i]):arr2.every((v,i)=>v===arr1[i]) } ================================================ FILE: Arrh, grabscrab!.js ================================================ /* Description: Pirates have notorious difficulty with enunciating. They tend to blur all the letters together and scream at people. At long last, we need a way to unscramble what these pirates are saying. Write a function that will accept a jumble of letters as well as a dictionary, and output a list of words that the pirate might have meant. For example: grabscrab( "ortsp", ["sport", "parrot", "ports", "matey"] ) Should return ["sport", "ports"]. Return matches in the same order as in the dictionary. Return an empty array if there are no matches. Good luck! */ function grabscrab(anagram, dictionary) { anagram=anagram.split('').sort().join() let arr = dictionary.slice().map(v=>v.split('').sort().join()===anagram) return dictionary.filter((v,i)=>arr[i]===true) } ================================================ FILE: Atbash Cipher Helper.js ================================================ /* Description: The Atbash cipher is a simple substitution cipher originally known to be implemented using the Hebrew alphabet (אתבש, aleph-tav-beth-shin). The Atbash cipher is particularly well-known for its use in the Bible. It was in use as early as 500BC by scribes writing the Book of Jeremiah. In the Atbash cipher, the first letter of the alphabet is substituted with the last letter, the second letter with the second to last letter, and so on. For the Latin alphabet, this could be mapped as: A|B|C|D|E|F|G|H|I|J|K|L|M Z|Y|X|W|V|U|T|S|R|Q|P|O|N For the Hebrew alphabet: א|ב|ג|ד|ה|ו|ז|ח|ט|י|כ ת|ש|ר|ק|צ|פ|ע|ס|נ|מ|ל When viewing Hebrew text: This is about viewing the text and should have no impact on your code. It may, however, help you with debugging text. I assume that your computer will display the characters properly. Hebrew is written right-to-left, such that: "א|ב".charAt(0) == "א". There are alternate forms of some letters in Hebrew (e.g. final forms) that aren't listed here. You won't need to worry about them for this Kata. Your solution should support any alphabet provided to the constructor, and should leave characters that are not in the specified alphabet in situ (e.g. uppercase letters should be left as-is if provided an alphabet of only lowercase letters). */ function AtbashCipher(abc) { this.decode = this.encode = function(str) { return str.replace(/./g, function(c) { return abc[abc.length - 1 - abc.indexOf(c)] || c; }); }; } ================================================ FILE: Autocomplete! Yay!.js ================================================ /* Description: It's time to create an autocomplete function! Yay! The autocomplete function will take in an input string and a dictionary array and return the values from the dictionary that start with the input string. If there are more than 5 matches, restrict your output to the first 5 results. If there are no matches, return an empty array. Example: autocomplete('ai', ['airplane','airport','apple','ball']) = ['airplane','airport'] For this kata, the dictionary will always be a valid array of strings. Please return all results in the order given in the dictionary, even if they're not always alphabetical. The search should NOT be case sensitive, but the case of the word should be preserved when it's returned. For example, "Apple" and "airport" would both return for an input of 'a'. However, they should return as "Apple" and "airport" in their original cases. Important note: Any input that is NOT a letter should be treated as if it is not there. For example, an input of "$%^" should be treated as "" and an input of "ab*&1cd" should be treated as "abcd". (Thanks to wthit56 for the suggestion!) */ function autocomplete(input, d){ input=input.replace(/[^a-zA-Z]/gi,'') const arr=[]; for (let i=0;i "ac" "abc##d######" ==> "" "#######" ==> "" "" ==> "" */ function clean_string(s) { s=s.split`` for (let i=0;iv!=='') i-=2 } } return s.join`` }; ================================================ FILE: Backwards Read Primes.js ================================================ /* Description: Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. (This rules out primes which are palindromes.) Examples: 13 17 31 37 71 73 are Backwards Read Primes 13 is such because it's prime and read from right to left writes 31 which is prime too. Same for the others. Task Find all Backwards Read Primes between two positive given numbers (both inclusive), the second one always being greater than or equal to the first one. The resulting array or the resulting string will be ordered following the natural order of the prime numbers. Example backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97] backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967] backwardsPrime(501, 599) => [] backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97] backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967] */ function backwardsPrime(start, stop){ var arr = []; for(var x = start; x <= stop; x++) { if(isPrime(x)) { if(arr.includes(x)) { continue; } let temp = parseInt(x.toString().split('').reverse().join('')) if (temp != x && isPrime(temp)) { arr.push(x); arr.push(temp); } } } return arr.filter(a=> a >= start && a <= stop).sort((b,c)=>b-c); } function isPrime(n) { if(n == 2 || n == 3) { return true; } if(n % 2 == 0 || n % 3 == 0 || n < 2) { return false; } var x = 5; var N = Math.sqrt(n); while (x <= N) { if (n % x == 0) { return false; } x++; } return true; } ================================================ FILE: Balance the arrays.js ================================================ /* Description: Check that the two provided arrays both contain the same number of different unique items, regardless of order. For example in the following: [a,a,a,a,b,b] and [c,c,c,d,c,d] Both arrays have four of one item and two of another, so balance should return true. #Have fun! */ function balance (arr1, arr2){ if (arr1.length!==arr2.length) return false let f = arr1.reduce((a,b)=>(a[b]=a[b]+1|0+1,a),{}) let s = arr2.reduce((a,b)=>(a[b]=a[b]+1|0+1,a),{}) return Object.values(f).sort().toString()===Object.values(s).sort().toString() } ================================================ FILE: Ball Upwards.js ================================================ /* You throw a ball vertically upwards with an initial speed v (in km per hour). The height h of the ball at each time t is given by h = v*t - 0.5*g*t*t where g is Earth's gravity (g ~ 9.81 m/s**2). A device is recording at every tenth of second the height of the ball. For example with v = 15 km/h the device gets something of the following form: (0, 0.0), (1, 0.367...), (2, 0.637...), (3, 0.808...), (4, 0.881..) ... where the first number is the time in tenth of second and the second number the height in meter. Task Write a function max_ball with parameter v (in km per hour) that returns the time in tenth of second of the maximum height recorded by the device. Examples: max_ball(15) should return 4 max_ball(25) should return 7 Notes Remember to convert the velocity from km/h to m/s or from m/s in km/h when necessary. The maximum height recorded by the device is not necessarily the maximum height reached by the ball. */ function maxBall(v0) { const v = v0 * 1000 * 10 / 3600; return Math.round(v / 9.81); } ================================================ FILE: Banker's Plan.js ================================================ /* Description: John has some amount of money of which he wants to deposit a part f0 to the bank at the beginning of year 1. He wants to withdraw each year for his living an amount c0. Here is his banker plan: deposit f0 at beginning of year 1 his bank account has an interest rate of p percent per year, constant over the years John can withdraw each year c0, taking it whenever he wants in the year; he must take account of an inflation of i percent per year in order to keep his quality of living. i is supposed to stay constant over the years. all amounts f0..fn-1, c0..cn-1 are truncated by the bank to their integral part Given f0, p, c0, i the banker guarantees that John will be able to go on that way until the nth year. Example: f0 = 100000, p = 1 percent, c0 = 2000, n = 15, i = 1 percent beginning of year 2 -> f1 = 100000 + 0.01*100000 - 2000 = 99000; c1 = c0 + c0*0.01 = 2020 (with inflation of previous year) beginning of year 3 -> f2 = 99000 + 0.01*99000 - 2020 = 97970; c2 = c1 + c1*0.01 = 2040.20 (with inflation of previous year, truncated to 2040) beginning of year 4 -> f3 = 97970 + 0.01*97970 - 2040 = 96909.7 (truncated to 96909); c3 = c2 + c2*0.01 = 2060.4 (with inflation of previous year, truncated to 2060) and so on... John wants to know if the bankers'plan is right or wrong. Given parameters f0, p, c0, n, i build a function fortune which returns true if John can make a living until the nth year and false if it is not possible. Some cases: fortune(100000, 1, 2000, 15, 1) -> True fortune(100000, 1, 10000, 10, 1) -> True fortune(100000, 1, 9185, 12, 1) -> False For the last case you can find below the amounts of his account at the beginning of each year: 100000, 91815, 83457, 74923, 66211, 57318, 48241, 38977, 29523, 19877, 10035, -5 f11 = -5 so he has no way to withdraw something for his living in year 12. Note: Don't forget to convert the percent parameters as percentages in the body of your function: if a parameter percent is 2 you have to convert it to 0.02. */ const fortune = (f0, p, c0, n, i) => { let c = c0; let sum = f0; for (let j = 1; j < n; j++) { sum = Math.ceil(sum * (1 + p / 100) - c); c = Math.ceil(c * (1 + i / 100)) } return sum >= 0; }; ================================================ FILE: Base Conversion.js ================================================ /* Description: In this kata you have to implement a base converter, which converts positive integers between arbitrary bases / alphabets. Here are some pre-defined alphabets: var Alphabet = { BINARY: '01', OCTAL: '01234567', DECIMAL: '0123456789', HEXA_DECIMAL: '0123456789abcdef', ALPHA_LOWER: 'abcdefghijklmnopqrstuvwxyz', ALPHA_UPPER: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', ALPHA: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ALPHA_NUMERIC: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' }; The function convert() should take an input (string), the source alphabet (string) and the target alphabet (string). You can assume that the input value always consists of characters from the source alphabet. You don't need to validate it. Examples // convert between numeral systems convert("15", Alphabet.DECIMAL, Alphabet.BINARY); // should return "1111" convert("15", Alphabet.DECIMAL, Alphabet.OCTAL); // should return "17" convert("1010", Alphabet.BINARY, Alphabet.DECIMAL); // should return "10" convert("1010", Alphabet.BINARY, Alphabet.HEXA_DECIMAL); // should return "a" // other bases convert("0", Alphabet.DECIMAL, Alphabet.ALPHA); // should return "a" convert("27", Alphabet.DECIMAL, Alphabet.ALPHA_LOWER); // should return "bb" convert("hello", Alphabet.ALPHA_LOWER, Alphabet.HEXA_DECIMAL); // should return "320048" convert("SAME", Alphabet.ALPHA_UPPER, Alphabet.ALPHA_UPPER); // should return "SAME" Additional Notes: The maximum input value can always be encoded in a number without loss of precision in JavaScript. In Haskell, intermediate results will probably be too large for Int. The function must work for any arbitrary alphabets, not only the pre-defined ones You don't have to consider negative numbers */ function convert(input, source, target) { let s=0; let str=''; for (let i=0; i0) { str=target[s%target.length]+str; s=Math.floor(s/target.length); } return str ? str : target[0]; } ================================================ FILE: Basic Encryption.js ================================================ /* Description: The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example 'a' + 1 would give us 'b', because 'a' value is 97 and 'b' value is 98. You will need to write a method which does exactly that - get a string as text and an int as the rule of manipulation, and should return encrypted text. for example: encrypt("a",1) = "b" Full ascii table is used on our question (256 chars) - so 0-255 are the valid values. Good luck. */ function encrypt(text, rule) { return text.split('').map(v=>String.fromCharCode((v.charCodeAt()+rule)%256)).join(``) }; ================================================ FILE: Binary string.js ================================================ /* Description: Given a positive (or 0) number, return a string of 1's and 0's representing it's binary value: toBinaryString(6) should return "110" (no leading 0). Use of the native method number.toString(2); is disallowed. */ function toBinaryString(num){ let out = "", bit = 1; while( num >= bit ) { out = ( num & bit ? 1 : 0 ) + out; bit <<= 1; } return out || "0"; } ================================================ FILE: Binary to Text (ASCII) Conversion.js ================================================ /* Description: Write a function that takes in a binary string and returns the equivalent decoded text (the text is ASCII encoded). Each 8 bits on the binary string represent 1 character on the ASCII table. The input string will always be a valid binary string. Characters can be in the range from "00000000" to "11111111" (inclusive) Note: In the case of an empty binary string your function should return an empty string. */ function binaryToString(binary) { let arr=[]; for (let i=0;iString.fromCharCode(parseInt(v,2))).join('') } ================================================ FILE: Binding within the List Monad.js ================================================ /* Description: 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: 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! As per usual, the ruby function will be passed a Proc or Lambda. Remember that the function still takes two arguments! */ bind = function(list, func) { if (typeof func(list[0]) !== "object") {throw Error()} return list.reduce((a,b)=>a.concat(func(b)),[]) } ================================================ FILE: Bingo Card.js ================================================ /* Description: After yet another dispute on their game the Bingo Association decides to change course and automize the game. Can you help the association by writing a method to create a random Bingo card? Task: Finish method: getCard() A Bingo card contains 24 unique and random numbers according to this scheme: 5 numbers from the B column in the range 1 to 15 5 numbers from the I column in the range 16 to 30 4 numbers from the N column in the range 31 to 45 5 numbers from the G column in the range 46 to 60 5 numbers from the O column in the range 61 to 75 The card must be returned as an array of Bingo style numbers: { 'B14', 'B12', 'B5', 'B6', 'B3', 'I28', 'I27', ... } The numbers must be in the order of their column: B, I, N, G, O. Within the columns the order of the numbers is random. */ function getCard() { let arr=[]; for (let i=0;i<5;i++){ let r=`B${getRandomIntInclusive(1,15)}` if (!arr.includes(r)){ arr.push(r)} else {i--} } for (let i=0;i<5;i++){ let r=`I${getRandomIntInclusive(16,30)}` if (!arr.includes(r)){ arr.push(r)} else {i--} } for (let i=0;i<5;i++){ let r=`N${getRandomIntInclusive(31,45)}` if (i===2){} else if (!arr.includes(r)){ arr.push(r)} else {i--} } for (let i=0;i<5;i++){ let r=`G${getRandomIntInclusive(46,60)}` if (!arr.includes(r)){ arr.push(r)} else {i--} } for (let i=0;i<5;i++){ let r=`O${getRandomIntInclusive(61,75)}` if (!arr.includes(r)){ arr.push(r)} else {i--} } return arr } function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } ================================================ FILE: Bit Counting ================================================ /* Description: Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative. Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case */ var countBits = function(n) { return n.toString(2).replace(/0/g,'').length; }; ================================================ FILE: Bleatrix Trotter (The Counting Sheep).js ================================================ /* Description: Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on. Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. Once she has seen each of the ten digits at least once, she will fall asleep. Bleatrix must start with N and must always name (i + 1) × N directly after i × N. For example, suppose that Bleatrix picks N = 1692. She would count as follows: N = 1692. Now she has seen the digits 1, 2, 6, and 9. 2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9. 3N = 5076. Now she has seen all ten digits, and falls asleep. The purpose of this kata is to return the last number Bleatrix Trotter sees before falling asleep. Input Will always be positive integer or zero Output The last number Bleatrix Trotter sees or "INSOMNIA" (-1 in Rust and C++) if she will count forever Please note, this challenge is not my idea. It's from Google Code Jam 2016 */ function trotter(n){ let check = n let arr = n.toString().split`` for (let i=1;i<1000;i++){ n=check*i arr=arr.concat(n.toString().split``) arr=[...new Set(arr)] if (arr.length===10) return n } return "INSOMNIA" } ================================================ FILE: Body mass index calculation.js ================================================ /* Description: For long period JavaScript warriors trained a lot in coding kata. But to find way warrior also need physical kata. Some of warriors forgot about this fact and enemies can use this weakness, your clan is under threat. You are chosen to fix this situation. Write a function to calculate Body mass index for each warrior. bmi = weght(kg)/(height(m)*height(m)) Warriors know only their height in centimetres and weight (in kilogrames). Your task is to return an object with fields value - calculated Body mass index, rounded with one number after decimal point. category - from https://en.wikipedia.org/wiki/Body_mass_index Ex : calculateBmi(65,175) Returns : {value: "21.2", category: "Normal (healthy weight)"} */ function calculateBmi(weight, height) { const bmi = (weight/((height/100)*(height/100))).toFixed(1) let z='' const obj={}; if (bmi<15) z='Very severely underweight'; if (bmi<16&&bmi>15) z= 'Severely underweight'; if (bmi<18.5&&bmi>16) z= 'Underweight'; if (bmi<25&&bmi>18.5) z= "Normal (healthy weight)"; if (bmi<30&&bmi>25) z= 'Overweight'; if (bmi<35&&bmi>30) z= 'Obese Class I (Moderately obese)'; if (bmi<40&&bmi>35) z= 'Obese Class II (Severely obese)'; if (bmi<45&&bmi>40) z= 'Obese Class III (Very severely obese)'; if (bmi<50&&bmi>45) z= 'Obese Class IV (Morbidly Obese)'; if (bmi<60&&bmi>50) z= 'Obese Class V (Super Obese)'; if (bmi>60) z= 'Obese Class VI (Hyper Obese)'; obj.value=bmi obj.category=z return obj } ================================================ FILE: Bouncing Balls ================================================ /*Description: A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known. He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66). His mother looks out of a window 1.5 meters from the ground. How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing? Three conditions must be met for a valid experiment: Float parameter "h" in meters must be greater than 0 Float parameter "bounce" must be greater than 0 and less than 1 Float parameter "window" must be less than h. If all three conditions above are fulfilled, return a positive integer, otherwise return -1. Note: The ball can only be seen if the height of the rebounding ball is stricty greater than the window parameter. Example: h = 3, bounce = 0.66, window = 1.5, result is 3 h = 3, bounce = 1, window = 1.5, result is -1 (Condition 2) not fulfilled). */ function bouncingBall(h, bounce, window) { var rebounds = -1; if (bounce > 0 && bounce < 1) while (h > window) rebounds+=2, h *= bounce; return rebounds; } ================================================ FILE: Bowling Pins.js ================================================ /* Description: Mount the Bowling Pins! Task: Did you ever play Bowling? Short: You have to throw a bowl into 10 Pins arranged like this: I I I I # each Pin has a Number: 7 8 9 10 I I I 4 5 6 I I 2 3 I 1 You will get an Array with Numbers, e.g.: [3,5,9] and remove them from the field like this: I I I I I I I Return a string with the current field. Note that: String.prototype.replace() is not allowed! You begin a new line with \n Each Line must be 7 chars long Fill the missing pins with a whitespace Have fun! */ function bowlingPins(arr){ return "7 8 9 10\n 4 5 6 \n 2 3 \n 1 ".split`\n`.map( v=>v.split` `.map(v=>arr.includes(v*1)?' ':v===''?'':'I').join` `).join`\n` } ================================================ FILE: Braces status.js ================================================ /* Description: Write a function that checks the braces status in a string, and return True if all braces are properly closed, or False otherwise. Available types of brackets: (), [], {}. Please note, you need to write this function without using regex! Examples "([[some](){text}here]...)" => true "{([])}" => true "()[]{}()" => true "(...[]...{(..())}[abc]())" => true "1239(df){" => false "[()])" => false ")12[x]34(" => false Don't forget to rate this kata! Thanks :) */ const bracesStatus = s => { s = s.replace(/[^\(\)\[\]\{\}]/g, ''); while (/\(\)|\[\]|\{\}/.test(s)) s = s.replace(/\(\)|\[\]|\{\}/g, ''); return s.length < 1; } ================================================ FILE: Bracket Duplicates.js ================================================ /* Description: Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket. For example, the input "aaaabbcdefffffffg" should return "aa[aa]bbcdeff[fffff]g" Please also ensure that the input is a string, and return "Please enter a valid string" if it is not. */ function stringParse(string){ if (typeof string !== 'string') return "Please enter a valid string" let arr = [] let str = '' for (let i=0;iv.length>2?v.slice(0,2)+'['+v.slice(2)+']':v).join`` } ================================================ FILE: Braking well.js ================================================ /* Description: Braking distance d1 is the distance a vehicle will go from the point when it brakes to when it comes to a complete stop. It depends on the original speed v and on the coefficient of friction mu between the tires and the road surface. The braking distance is one of two principal components of the total stopping distance. The other component is the reaction distance, which is the product of the speed and the perception-reaction time of the driver. The kinetic energy E is 0.5*m*v**2, the work W given by braking is mu*m*g*d1. Equalling E and W gives the braking distance: d1 = v*v / 2*mu*g where g is the gravity of Earth and m the vehicle's mass. We have v in km per hour, g as 9.81 m/s/s and in the following we suppose that the reaction time is constant and equal to 1 s. The coefficient mu is dimensionless. There are two tasks. The first one is to calculate the total stopping distance in meters given v, mu (and the reaction time t = 1). dist(v, mu) -> d = total stopping distance The second task is to calculate v in km per hour knowing d in meters and mu with the supposition that the reaction time is still t = 1. speed(d, mu) -> v such that dist(v, mu) = d. #Examples: dist(100, 0.7) -> 83.9598760937531 speed(83.9598760937531, 0.7) -> 100.0 #Notes: Remember to convert the velocity from km/h to m/s or from m/s in km/h when necessary. Don't forget the reaction time t: t = 1 Don't truncate or round your results. See in "RUN EXAMPLES" the function assertFuzzyEquals. Shell: only dist is tested. */ const G = 9.81 function dist(v, mu) { let u = v*5/18; return (u*u)/(2 * mu * G) + u; } function speed(d, mu) { let b = -2 * mu * G; return (3.6 * (b + Math.sqrt(b*b - 4*b*d) ) / 2); } ================================================ FILE: Break camelCase.js ================================================ /* Complete the solution so that the function will break up camel casing, using a space between words. Example solution('camelCasing') // => should return 'camel Casing' */ function solution(string) { return(string.replace(/([A-Z])/g, ' $1')); } ================================================ FILE: Breaking search bad.js ================================================ /* Description: We have a search function who return an array of titles that match the String passed as an argument. var titles = ['Rocky 1', 'Rocky 2', 'My Little Poney']; search('ock') // ==> should return ['Rocky 1', 'Rocky 2'] But the function return some weird result and skip some of the matching results. Does the function have special movie taste ? Let's figure out ! */ function search(searchTerm) { return TITLES.filter(v=>new RegExp(searchTerm, 'i').test(v)) } ================================================ FILE: Build Tower ================================================ /* Description: Build Tower Build Tower by the following given argument: number of floors (integer and always greater than 0). Tower block is represented as * Python: return a list; JavaScript: returns an Array; C#: returns a string[]; PHP: returns an array; C++: returns a vector; Haskell: returns a [String]; Ruby: returns an Array; Have fun! for example, a tower of 3 floors looks like below [ ' * ', ' *** ', '*****' ] and a tower of 6 floors looks like below [ ' * ', ' *** ', ' ***** ', ' ******* ', ' ********* ', '***********' ] Go challenge Build Tower Advanced once you have finished this :) */ function towerBuilder(n) { return [...Array(n)].map((_,i)=>" ".repeat(n-1-i)+"*".repeat(i*2+1)+" ".repeat(n-1-i)) } ================================================ FILE: Build Tower Advanced.js ================================================ /* Description: Build Tower Advanced Build Tower by the following given arguments: number of floors (integer and always greater than 0) block size (width, height) (integer pair and always greater than (0, 0)) Tower block unit is represented as * Python: return a list; JavaScript: returns an Array; Have fun! for example, a tower of 3 floors with block size = (2, 3) looks like below [ ' ** ', ' ** ', ' ** ', ' ****** ', ' ****** ', ' ****** ', '**********', '**********', '**********' ] and a tower of 6 floors with block size = (2, 1) looks like below [ ' ** ', ' ****** ', ' ********** ', ' ************** ', ' ****************** ', '**********************' ] Go take a look at Build Tower which is a more basic version :) */ function towerBuilder(nFloors, nBlockSz) { const tower = [] for (let i=0;i 45 findNb(91716553919377) --> -1 mov rdi, 1071225 call find_nb ; rax <-- 45 mov rdi, 91716553919377 call find_nb ; rax <-- -1 */ function findNb(m) { let i=1; let count=0; while (m>0){ m-=Math.pow(i,3) i++ count++ } return (m === 0) ? count : -1; } ================================================ FILE: Buying a car ================================================ /* Description: Let us begin with an example: A man has a rather old car being worth $2000. He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one. He thinks he can save $1000 each month but the prices of his old car and of the new one decrease of 1.5 percent per month. Furthermore this percent of loss increases by 0.5 percent at the end of every two months. Our man finds it difficult to make all these calculations. Can you help him? How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over? Parameters and return of function: parameter (positive int, guaranteed) startPriceOld (Old car price) parameter (positive int, guaranteed) startPriceNew (New car price) parameter (positive int, guaranteed) savingperMonth parameter (positive float or int, guaranteed) percentLossByMonth nbMonths(2000, 8000, 1000, 1.5) should return [6, 766] or (6, 766) where 6 is the number of months at the end of which he can buy the new car and 766 is the nearest integer to 766.158 (rounding 766.158 gives 766). Note: Selling, buying and saving are normally done at end of month. Calculations are processed at the end of each considered month but if, by chance from the start, the value of the old car is bigger than the value of the new one or equal there is no saving to be made, no need to wait so he can at the beginning of the month buy the new car: nbMonths(12000, 8000, 1000, 1.5) should return [0, 4000] nbMonths(8000, 8000, 1000, 1.5) should return [0, 0] We don't take care of a deposit of savings in a bank:-) */ function nbMonths(startPriceOld, startPriceNew, savingperMonth, percentLossByMonth){ if (startPriceOld>=startPriceNew) return [0,startPriceOld-startPriceNew] var count=0; var money=startPriceOld; for (let i=1;money<=startPriceNew;i++){ if (i%2==0){percentLossByMonth+=0.5} count++; startPriceOld = startPriceOld - (startPriceOld*(percentLossByMonth/100)); startPriceNew = startPriceNew - ((startPriceNew*percentLossByMonth)/100); money = startPriceOld + (savingperMonth*count); }; return [count,Math.round(money-startPriceNew)]; } ================================================ FILE: ByState.js ================================================ /* Description: Given a string with friends to visit in different states: ad3="John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Sal Carpenter, 73 6th Street, Boston MA" we want to produce a result that sorts the names by state and lists the name of the state followed by the name of each person residing in that state (people's names sorted). When the result is printed we get: Massachusetts .....^John Daggett 341 King Road Plymouth Massachusetts .....^Sal Carpenter 73 6th Street Boston Massachusetts ^Virginia .....^Alice Ford 22 East Broadway Richmond Virginia Spaces not being always well seen, in the above result ^ means a white space. Not printed, the resulting string will be: "Massachusetts\n..... John Daggett 341 King Road Plymouth Massachusetts\n..... Sal Carpenter 73 6th Street Boston Massachusetts\n Virginia\n..... Alice Ford 22 East Broadway Richmond Virginia" Notes There can be a blank last line in the given string of adresses. The tests only contains CA, MA, OK, PA, VA, AZ, ID, IN for states. You can see another example in the "Sample tests". States For the lazy ones: 'AZ': 'Arizona', 'CA': 'California', 'ID': 'Idaho', 'IN': 'Indiana', 'MA': 'Massachusetts', 'OK': 'Oklahoma', 'PA': 'Pennsylvania', 'VA': 'Virginia' */ function byState(str) { let arr = str.replace(/,/g,"").split`\n`; let states = [["AZ","Arizona"], ["CA","California"], ["ID","Idaho"], ["IN","Indiana"], ["MA","Massachusetts"], ["OK","Oklahoma"], ["PA","Pennsylvania"], ["VA","Virginia"]]; let res = ""; states.forEach(([s,n]) => { let temp = arr.filter(x => x.slice(-2) === s).sort(); if(temp.length){ res += "\r\n " + n + "\r\n"; res += temp.map(x => `..... ${x.slice(0,-3)} ${n}`).join`\r\n`; } }); return res.slice(3); } ================================================ FILE: Calculate Hypotenuse of Right-angled Triangle.js ================================================ /* Description: To solve this Kata, complete the function, calculateHypotenuse(a,b), which will return the length of the hyptenuse for a right angled triangle with the other two sides having a length equal to the inputs. More details: The returned value should be a number rounded to three decimal places An error (ArgumentException in C#) should be thrown if an invalid input is provided (inputs should both be numbers that are above zero) calculateHypotenuse(1,1); // returns 1.414 calculateHypotenuse(3,4); // returns 5 calculateHypotenuse(-2,1); // throws error calculateHypotenuse("one", "two"); // throws error For more information on the hypotenuse, visit: http://en.wikipedia.org/wiki/Hypotenuse */ function calculateHypotenuse(a,b){ if (typeof a !== 'number'||typeof b !== 'number') throw new Error('Not a Number') if (isNaN(a)||isNaN(b)) throw new Error('Not a Number') if (a<0||b<0) throw new Error('Less than 0') return Math.hypot(a,b).toFixed(3) } ================================================ FILE: Calculate String Rotation.js ================================================ /* Description: Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. If the second string isn't a valid rotation of the first string, the method returns -1. Examples: ``` "coffee", "eecoff" => 2 "eecoff", "coffee" => 4 "moose", "Moose" => -1 "isn't", "'tisn" => 2 "Esham", "Esham" => 0 "dog", "god" => -1 ``` For Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil. shiftedDiff("coffee", "eecoff") => 2 shiftedDiff("eecoff", "coffee") => 4 shiftedDiff("moose", "Moose") => nil shiftedDiff("isn't", "'tisn") => 2 shiftedDiff("Esham", "Esham") => 0 shiftedDiff("dog", "god") => nil */ function shiftedDiff(first,second){ for (let i=0;ia-b).join`` let count = 0; for (let i=1;array.join``!==sorted;i++){ for (let j=0;j "f(x) = x" getFunction([0, 3, 6, 9, 12]) => "f(x) = 3x" getFunction([1, 4, 7, 10, 13]) => "f(x) = 3x + 1" 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. */ function getFunction(seq) { let add = seq[0], mul = seq[1]-add, linear=seq.every(function(v,i){return v==i*mul+add}); return linear ? "f(x) = "+ ( mul? (mul==1? '':mul==-1? "-":mul) +"x"+ (!add? "" : (add>0? " + ":" - ") +Math.abs(add)) : add ) : "Non-linear sequence" } ================================================ FILE: Calculate the function f(x) for a simple linear sequence (Medium).js ================================================ /* Description: 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: getFunction([0, 1, 2, 3, 4])(5) => 5 getFunction([0, 3, 6, 9, 12])(10) => 30 getFunction([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. */ function getFunction(sequence) { const n = sequence[1]-sequence[0] const check = sequence[1]-sequence[0]===sequence[2]-sequence[1] if (!check) return'Non-linear sequence' return (x)=>x*n+sequence[0] } ================================================ FILE: Cambridge Word Scramble.js ================================================ /* Description: One of the first chain emails I ever received was about a supposed Cambridge University study that suggests your brain can read words no matter what order the letters are in, as long as the first and last letters of each word are correct. Your task is to create a function that can take any string and randomly jumble the letters within each word while leaving the first and last letters of the word in place. For example, mixwords('Winter is coming') // returns 'Wntier is cminog' or 'Wtiner is conimg' mixwords('Hey, friends!') // returns 'Hey, fierdns!' or 'Hey, fernids!' All punctuation should remain in place Words smaller than 3 letters should not change Letters must be randomly moved (and so calling the function multiple times with the same string should return different values Parameters that are not strings should return undefined The tests do the following things to ensure a valid string is returned: Check that the string returned is not equal to the string passed (you may have to revalidate the solution if your function randomly returns the same string) Check that first and last letters of words remain in place Check that punctuation remains in place Checks string length remains the same Checks the function returns undefined for non-strings Checks that word interiors (the letters between the first and last) maintain the same letters, albeit in a different order Checks that letters are randomly assigned. */ function mixwords(str){ if (typeof str ==='string'){ return str.replace(/[a-z]+/gi,v=>{ if (v.length>2) return v.slice(0,1)+v.slice(1,-1).split``.sort((a,b)=>Math.random()-0.5).join``+v.slice(-1) return v }) } }; ================================================ FILE: CamelCase Method.js ================================================ /* Description: Write simple .camelCase method (camel_case function in PHP, CamelCase in C# or camelCase in Java) for strings. All words must have their first letter capitalized without spaces. For instance: "hello case".camelCase() => HelloCase "camel case word".camelCase() => CamelCaseWord Don't forget to rate this kata! Thanks :) */ String.prototype.camelCase=function(){ let arg = this.toString().trim().split(' '); let arr = arg.map((v,i,arr)=>v?v.slice(0,1).toUpperCase()+v.slice(1):v); return arr.join(''); } ================================================ FILE: CamelCase to underscore.js ================================================ /* Description: You wrote all your unit test names in camelCase. But some of your colleagues have troubles reading these long test names. So you make a compromise to switch to underscore separation. To make these changes fast you wrote a class to translate a camelCase name into an underscore separated name. Implement the ToUnderscore() method. Example: "ThisIsAUnitTest" => "This_Is_A_Unit_Test" But of course there are always special cases... You also have some calculation tests. Make sure the results don't get splitted by underscores. So only add an underscore in front of the first number. Also Some people already used underscore names in their tests. You don't want to change them. But if they are not splitted correct you should adjust them. Some of your colleagues mark their tests with a leading and trailing underscore. Don't remove this. And of course you should handle empty strings to avoid unnecessary errors. Just return an empty string then. Example: "Calculate15Plus5Equals20" => "Calculate_15_Plus_5_Equals_20" "This_Is_Already_Splitted_Correct" => "This_Is_Already_Splitted_Correct" "ThisIs_Not_SplittedCorrect" => "This_Is_Not_Splitted_Correct" "_UnderscoreMarked_Test_Name_" => _Underscore_Marked_Test_Name_" */ const toUnderScore = name => { return name.replace(/([A-Z]|\d+)/g,'_$1').replace(/^_/,'').replace(/__/g,'_') } ================================================ FILE: Can you keep a secret?.js ================================================ /* There's no such thing as private properties on a coffeescript object! But, maybe there are? Implement a function createSecretHolder(secret) which accepts any value as secret and returns an object with ONLY two methods getSecret() which returns the secret setSecret() which sets the secret obj = createSecretHolder(5) obj.getSecret() # returns 5 obj.setSecret(2) obj.getSecret() # returns 2 */ function createSecretHolder(secret) { return { getSecret:function(){ return secret }, setSecret:function(v){ secret=v} } } ================================================ FILE: Case Reversal of Consecutive Duplicates.js ================================================ /* Description: The aim of this Kata is to write a function which will reverse the case of all consecutive duplicate letters in a string. That is, any letters that occur one after the other and are identical. If the duplicate letters are lowercase then they must be set to uppercase, and if they are uppercase then they need to be changed to lowercase. Examples: reverseCase("puzzles") Expected Result: "puZZles" reverseCase("massive") Expected Result: "maSSive" reverseCase("LITTLE") Expected Result: "LIttLE" reverseCase("shhh") Expected Result: "sHHH" Arguments passed will include only alphabetical letters A–Z or a–z. */ function reverseCase(string) { return string.replace(/(\w)(\1)+/g,(v)=>v[0]===v[0].toLowerCase()?v.toUpperCase():v.toLowerCase()) } ================================================ FILE: Cat Kata, Part 1.js ================================================ /* Description: The story you are about to hear is true Our cat, Balor, sadly died of cancer in 2015. While he was alive, the three neighborhood cats Lou, Mustache Cat, and Raoul all recognized our house and yard as Balor's territory, and would behave respectfully towards him and each other when they would visit. But after Balor died, gradually each of these three neighborhood cats began trying to claim his territory as their own, trying to drive the others away by growling, yowling, snarling, chasing, and even fighting, when one came too close to another, and no human was right there to distract or extract one of them before the situation could escalate. It is sad that these otherwise-affectionate animals, who had spent many afternoons peacefully sitting and/or lying near Balor and each other on our deck or around our yard, would turn on each other like that. However, sometimes, if they are far enough away from each other, especially on a warm day when all they really want to do is pick a spot in the sun and lie in it, they will ignore each other, and once again there will be a Peaceable Kingdom. Your Mission In this, the first and simplest of a planned trilogy of cat katas :-), all you have to do is determine whether the distances between any visiting cats are large enough to make for a peaceful afternoon, or whether there is about to be an altercation someone will need to deal with by carrying one of them into the house or squirting them with water or what have you. As input your function will receive a list of strings representing the yard as a grid, and an integer representing the minimum distance needed to prevent problems (considering the cats' current states of sleepiness). A point with no cat in it will be represented by a "-" dash. Lou, Mustache Cat, and Raoul will be represented by an upper case L, M, and R respectively. At any particular time all three cats may be in the yard, or maybe two, one, or even none. If the number of cats in the yard is one or none, or if the distances between all cats are at least the minimum distance, your function should return True/true/TRUE (depending on what language you're using), but if there are two or three cats, and the distance between at least two of them is smaller than the minimum distance, your function should return False/false/FALSE. Some examples (The yard will be larger in the random test cases, but a smaller yard is easier to see and fit into the instructions here.) In this first example, there is only one cat, so your function should return True. ["------------", "------------", "-L----------", "------------", "------------", "------------"], 10 In this second example, Mustache Cat is at the point yard[1][3] and Raoul is at the point yard[4][7] -- a distance of 5, so because the distance between these two points is smaller than the specified minimum distance of 6, there will be trouble, and your function should return False. ["------------", "---M--------", "------------", "------------", "-------R----", "------------"], 6 In this third example, Lou is at yard[0][11], Raoul is at yard[1][2], and Mustache Cat at yard[5][2]. The distance between Lou and Raoul is 9.05538513814, the distance between Raoul and Mustache Cat is 4, and the distance between Mustache Cat and Lou is 10.295630141 -- all greater than or equal to the specified minimum distance of 4, so the three cats will nap peacefully, and your function should return True. ["-----------L", "--R---------", "------------", "------------", "------------", "--M---------"], 4 Have fun! */ function peacefulYard(yd, d) { for(var pos=[],i=0;iMath.min(...pos.map(y=>(Math.pow(x[0]-y[0],2)+Math.pow(x[1]-y[1],2))||d*d))>=d*d) } ================================================ FILE: Cat and Mouse - Harder Version.js ================================================ /* Description: You will be given a string (x) featuring a cat 'C', a dog 'D' and a mouse 'm'. The rest of the string will be made up of '.'. You need to find out if the cat can catch the mouse from it's current position. The cat can jump (j) characters. Also, the cat cannot jump over the dog. So: if j = 5: ..C.....m. returns 'Caught!' <-- not more than j characters between .....C............m...... returns 'Escaped!' <-- as there are more than j characters between the two, the cat can't jump far enough if j = 10: ...m.........C...D returns 'Caught!' <--Cat can jump far enough and jump is not over dog ...m....D....C....... returns 'Protected!' <-- Cat can jump far enough, but dog is in the way, protecting the mouse Finally, if all three animals are not present, return 'boring without all three' */ function catMouse(x, j){ if (!x.includes('D')||!x.includes('C')||!x.includes('m')) return "boring without all three" if (Math.abs(x.indexOf('C')-x.indexOf('m'))>j) return "Escaped!" if (x.replace(/\./g,'')==='CDm'||x.replace(/\./g,'')==='mDC') return 'Protected!' return "Caught!" } ================================================ FILE: Catalog.js ================================================ /* Description: You are given a small extract of a catalog: s = "drill995 hammer1050 screwdriver551 table saw1099.995 saw910 ... (prx stands for price, qty for quantity) and an article i.e "saw". The function catalog(s, "saw") returns the line(s) corresponding to the article with $ before the prices: "table saw > prx: $1099.99 qty: 5\nsaw > prx: $9 qty: 10\n..." If the article is not in the catalog return "Nothing". Notes There is a blank line between two lines of the catalog. The same article may appear more than once. If that happens return all the lines concerned by the article (in the same order as in the catalog). The line separator of results may depend on the language \nor \r\n. You can see examples in the "Sample tests". */ function catalog(s, article) { return s.match(new RegExp(`name.+${article}.+\/qty`,'g'))?s.match(new RegExp(`name.+${article}.+\/qty`,'g')) .map(v=>v.replace(/<\/name>/,' > prx: $')) .map(v=>v.replace(/name>/,'')) .map(v=>v.replace(/<\/prx>/,' qty: ')) .map(v=>v.replace(/<\/qty/,'')).join`\r\n` :'Nothing' } ================================================ FILE: Chain Evaluation.js ================================================ /* Description: Method chaining is a very interesting way to keep your program clean. As a part of this Kata, you need to create functions such that one could evaluate the following expression: (3).add(5).multiply(2) The above expression evaluates to be 16. You need to implement the following methods: add subtract multiply divide square After you're done, one could chain these five methods to create chains of almost any length. */ Number.prototype.add=function(x){ return this+x}; Number.prototype.subtract=function(x){ return this-x;} Number.prototype.multiply=function(x){ return this*x;} Number.prototype.divide=function(x){ return this/x;} Number.prototype.square=function(){ return this*this;} ================================================ FILE: Character frequency.js ================================================ /* Description: Write a function that takes a piece of text in the form of a string and returns the letter frequency count for the text. This count excludes numbers, spaces and all punctuation marks. Upper and lower case versions of a character are equivalent and the result should all be in lowercase. The function should return a list of tuples (in Python) or arrays (in other languages) sorted by the most frequent letters first. The Rust implementation should return an ordered BTreeMap. Letters with the same frequency are ordered alphabetically. For example: letterFrequency('aaAabb dddDD hhcc') will return [['d',5], ['a',4], ['b',2], ['c',2], ['h',2]] Letter frequency analysis is often used to analyse simple substitution cipher texts like those created by the Caesar cipher. */ function letterFrequency(text){ let str=text.toLowerCase().replace(/[^a-z]\s*/gi,'').split(``).sort(); if (str.length===0) return [] let arr=[]; let obj={}; str.map(v=>obj[v]=obj[v]?obj[v]+1:1) obj=JSON.stringify(obj).slice(1,-1).replace(/"/g,'').split(',') .map(v=>arr.push([v.split(':')[0],v.split(':')[1]*1])) return arr.sort((a,b)=>b[1]-a[1]||a[0].localeCompare(b[0])) } ================================================ FILE: Character limits: How long is your piece of string?.js ================================================ /* Description: Cara is applying for several different jobs. The online application forms ask her to respond within a specific character count. Cara needs to check that her answers fit into the character limit. Annoyingly, some application forms count spaces as a character, and some don't. Your challenge: Write Cara a function charCheck() with the arguments: "text": a string containing Cara's answer for the question "max": a number equal to the maximum number of characters allowed in the answer "spaces": a boolean which is True if spaces are included in the character count and False if they are not The function charCheck() should return an array: [True, "Answer"] , where "Answer" is equal to the original text, if Cara's answer is short enough. If her answer "text" is too long, return an array: [False, "Answer"]. The second element should be the original "text" string truncated to the length of the limit. When the "spaces" argument is False, you should remove the spaces from the "Answer". For example: charCheck("Cara Hertz", 10, True) should return [ True, "Cara Hertz" ] charCheck("Cara Hertz", 9, False) should return [ True, "CaraHertz" ] charCheck("Cara Hertz", 5, True) should return [ False, "Cara " ] charCheck("Cara Hertz", 5, False) should return [ False, "CaraH" ] */ function charCheck(text, max, spaces){ if (!spaces){ text=text.replace(/\s+/g,'') } return [text.length<=max,text.slice(0,max)] }; ================================================ FILE: Character with longest consecutive repetition.js ================================================ /* Description: For a given string s find the character c with longest consecutive repetition and return a tuple (c, l) (in Haskell Just (Char, Int), in C# Tuple, in Shell a String of comma-separated values c,l, in JavaScript [c,l], in Ruby [c, l], in Groovy [c, l]) where l is the length of the repetition. If there are two or more characters with the same l return the first. For empty string return ('', 0) (in Haskell Nothing, in C# Tuple(null, 0), in Shell ,0, in JavaScript ["",0], in Ruby ["", 0], in Groovy ["", 0]). Happy coding! :) */ function longestRepetition(s) { let str=''; let count=1; let arr = [] for (let i=0;iv{ if (!dict[v]){ dict[v]=b[i] } else { if (dict[v]!=b[i]) f1=false } }) b.split``.map((v,i)=>{ if (!dict2[v]){ dict2[v]=a[i] } else { if (dict2[v]!=a[i]) f2=false } }) return f1&&f2 } ================================================ FILE: Checkerboard Generation.js ================================================ /* Description: Checkerboard Write a method checkerboard/Checkerboard which takes an integer size and returns a checkerboard of dimensions size x size. There are two colored squares on the checkerboard. Red squares are represented by the string [r] and black squares are represented by the string [b]. You MUST use the newline character \n to insert a newline at the end of each row. The top left corner should be a red square. Each row should have alternating squares in the row. The starting square on each row should also alternate. Assumptions You can assume you are given an integer size. You cannot assume positive values. Thus you should return an empty string for negative sizes and a size of 0. (An empty string does not have a newline ending). You should assume the newline character used is \n. You MUST leave a newline character at the end of the full checkerboard thus allowing the board to be on its own if you were to run in a terminal. Examples checkerboard(8); "[r][b][r][b][r][b][r][b] [b][r][b][r][b][r][b][r] [r][b][r][b][r][b][r][b] [b][r][b][r][b][r][b][r] [r][b][r][b][r][b][r][b] [b][r][b][r][b][r][b][r] [r][b][r][b][r][b][r][b] [b][r][b][r][b][r][b][r]" What We're Testing We're testing loops and conditionals and aiming at beginners. There are many ways of achieving the solution so the correct solution will present a fairly basic version that should be more advanced than typical loop examples and has some extra challenge to the problem with the alternating on columns and rows. */ function checkerboard (size) { "use strict"; if (size<=0) return ''; let str=''; for (let i=0;i=0&&i>=0;j--,i--){ desk[i][j]=1 } for (let i=y,j=x;j<8&&i<8;j++,i++){ desk[i][j]=1 } for (let i=y,j=x;j<8&&i>=0;j++,i--){ desk[i][j]=1 } for (let i=y,j=x;j>=0&&i<8;j--,i++){ desk[i][j]=1 } let p = pawn.split`` let xP = mapL[p[0]] let yP = mapN[p[1]] return desk[yP][xP]===1 } ================================================ FILE: Christmas Day.js ================================================ /* Description: Sometimes it's useful to know on which day of the week Christmas, the holly holiday, will occur. Write a function which takes the date of Christmas, and outputs the day of the week it falls on. Just don't limit yourself to this year. Example: findOutChristmasWeekday('2013 12 25') // returns 'Wednesday' Only valid Christmas dates will be passed to the function. Date parameter could be a string or a Date object. If it's a string here are possible date parameter formats: '2013 12 25' '12 25 2013' '25 December 2013' Note: calendar used in the kata is Gregorian. */ function findOutChristmasWeekday(date) { if (typeof date == "string") date = date.replace(/ /g, '-'); return ['Sun', 'Mon','Tues','Wednes','Thurs','Fri','Satur'][new Date(date).getDay()] + "day"; } ================================================ FILE: Christmas tree.js ================================================ /* Description: Create a function christmasTree(height) that returns a christmas tree of the correct height christmasTree(5) should return: * *** ***** ******* ********* Height passed is always an integer between 0 and 100. Use \n for newlines between each line. Pad with spaces so each line is the same length. The last line having only stars, no spaces. */ function christmasTree(height) { let str=[]; for (let i=1;i<=height;i++){ str.push(' '.repeat(height-i)+'*'.repeat((i - 1) * 2 + 1)+' '.repeat(height-i)) } return str.join('\n') } ================================================ FILE: Circularly Sorted Array.js ================================================ /* Description: 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: // 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]); */ function isCircleSorted( arr ){ let cnt = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] > arr[(i + 1) % arr.length]) { cnt++; } } return cnt === 1; } ================================================ FILE: Clay Pigeon Shooting.js ================================================ /* Description: Pete and his mate Phil are out in the countryside shooting clay pigeons with a shotgun - amazing fun. They decide to have a competition. 3 rounds, 2 shots each. Winner is the one with the most hits. Some of the clays have something attached to create lots of smoke when hit, guarenteed by the packaging to generate 'real excitement!' (genuinely this happened). None of the explosive things actually worked, but for this kata lets say they did. For each round you will receive the following format: [{P1:'XX', P2:'XO'}, true] That is an array containing an object and a boolean. Pl represents Pete, P2 represents Phil. X represents a hit and O represents a miss. If the boolean is true, any hit is worth 2. If it is false, any hit is worth 1. Find out who won. If it's Pete, return 'Pete Wins!'. If it is Phil, return 'Phil Wins!'. If the scores are equal, return 'Draw!'. Note that as there are three rounds, the actual input (x) will look something like this: [[{P1:'XX', P2:'XO'}, true], [{P1:'OX', P2:'OO'}, false], [{P1:'XX', P2:'OX'}, true]] */ function shoot(x){ let pete=0 let phil=0 for (let i=0;ix[i][1]?pete+=2:pete++) x[i][0].P2.replace(/X/g,v=>x[i][1]?phil+=2:phil++) } return pete>phil?'Pete Wins!':pete 06:35 01:50 --> 10:10 11:58 --> 12:02 12:01 --> 11:59 Please complete the function WhatIsTheTime(timeInMirror), where timeInMirror is the mirrored time (what Peter sees) as string. Return the real time as a string. Consider hours to be between 1 <= hour < 13. So there is no 00:20, instead it is 12:20. There is no 13:20, instead it is 01:20. */ function WhatIsTheTime(timeInMirror){ let time = timeInMirror.split(':') let time2 = 60 - (parseInt(time[1])) let time1 = time2 == 60 ? 12 - parseInt(time[0]) : 12 - (parseInt(time[0]) +1 ) let hour = time1 == 0 ? '12' : time1 == -1 ? '11' : time1 > 9 ? time1 : '0' + time1 let minute = time2 < 10 ? '0' + time2 : time2 == 60 ? '00' : time2 return `${hour}:${minute}` } ================================================ FILE: Clocky Mc Clock-Face.js ================================================ /* Description: Story Due to lack of maintenance the minute-hand has fallen off Town Hall clock face. And because the local council has lost most of our tax money to a Nigerian email scam there are no funds to fix the clock properly. Instead, they are asking for volunteer programmers to write some code that tell the time by only looking at the remaining hour-hand! What a bunch of cheapskates! Can you do it? Kata Given the angle (in degrees) of the hour-hand, return the time in HH:MM format. Round down to the nearest minute. Examples 12:00 = 0 degrees 03:00 = 90 degrees 06:00 = 180 degrees 09:00 = 270 degrees 12:00 = 360 degrees Notes 0 <= angle <= 360 */ var whatTimeIsIt = function(angle) { let hour=Math.floor(angle/30) if (hour===0) hour=12 let min=Math.floor(angle%30*2) return `${('0'+String(hour)).slice(-2)}:${('0'+String(min)).slice(-2)}`; } ================================================ FILE: Closures and Scopes.js ================================================ /* Description: We want to create a function, which returns an array of functions, which return their index in the array. For better understanding, here an example: var callbacks = createFunctions(5); // create an array, containing 5 functions callbacks[0](); // must return 0 callbacks[3](); // must return 3 We already implemented that function, but when we actually run the code, the result doesn't look like what we expected. Can you spot, what's wrong with it? A test fixture is also available */ function createFunctions(n) { var callbacks = []; for (let i=0; i{return{...v,username:(v.firstName.toLowerCase()+v.lastName.slice(0,1).toLowerCase()+(Date.prototype.getFullYear()-v.age).toString())}}) } ================================================ FILE: Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?.js ================================================ /* Description: You will be given an array of objects representing data about developers who have signed up to attend the next web development meetup that you are organising. Three programming languages will be represented: Python, Ruby and JavaScript. Your task is to return either: true if the number of meetup participants representing any of the three programming languages is ** at most 2 times higher than the number of developers representing any of the remaining programming languages**; or false otherwise. For example, given the following input array: var list1 = [ { firstName: 'Daniel', lastName: 'J.', country: 'Aruba', continent: 'Americas', age: 42, language: 'Python' }, { firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 22, language: 'Ruby' }, { firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 43, language: 'Ruby' }, { firstName: 'Hanna', lastName: 'L.', country: 'Hungary', continent: 'Europe', age: 95, language: 'JavaScript' }, { firstName: 'Jayden', lastName: 'P.', country: 'Jamaica', continent: 'Americas', age: 18, language: 'JavaScript' }, { firstName: 'Joao', lastName: 'D.', country: 'Portugal', continent: 'Europe', age: 25, language: 'JavaScript' } ]; your function should return false as the number of JavaScript developers (3) is 3 times higher than the number of Python developers (1). It can't be more than 2 times higher to be regarded as language-diverse. Notes: The strings representing all three programming languages will always be formatted in the same way (e.g. 'JavaScript' will always be formatted with upper-case 'J' and 'S'. The input array will always be valid and formatted as in the example above. Each of the 3 programming languages will always be represented. This kata is part of the Coding Meetup series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: forEach, filter, map, reduce, some, every, find, findIndex. Other approaches to solving the katas are of course possible. */ function isLanguageDiverse(list) { const arr = list.map(v=>v.language) const obj = {} arr.map(v=>obj[v]=obj[v]?obj[v]+1:1) const count = Object.values(obj).sort((a,b)=>b-a) const max = count.splice(0,1) return count.every(v=>v*2>=max) } ================================================ FILE: Coding Meetup #15 - Higher-Order Functions Series - Find the odd names.js ================================================ /* Description: You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising. Given the following input array: var list1 = [ { firstName: 'Aba', lastName: 'N.', country: 'Ghana', continent: 'Africa', age: 21, language: 'Python' }, { firstName: 'Abb', lastName: 'O.', country: 'Israel', continent: 'Asia', age: 39, language: 'Java' } ]; write a function that when executed as findOddNames(list1) returns only the developers where if you add the ASCII representation of all characters in their first names, the result will be an odd number: [ { firstName: 'Abb', lastName: 'O.', country: 'Israel', continent: 'Asia', age: 39, language: 'Java' } ] Explanation of the above: Sum of ASCII codes of letters in 'Aba' is: 65 + 98 + 97 = 260 which is an even number Sum of ASCII codes of letters in 'Abb' is: 65 + 98 + 98 = 261 which is an odd number Notes: Preserve the order of the original list. Return an empty array [] if there is no developer with an "odd" name. The input array and first names will always be valid and formatted as in the example above. This kata is part of the Coding Meetup series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: forEach, filter, map, reduce, some, every, find, findIndex. Other approaches to solving the katas are of course possible. */ function findOddNames(list) { return list.filter(v=>v.firstName.split``.reduce((a,b)=>a+b.charCodeAt(),0)%2!==0) } ================================================ FILE: Coding Meetup #16 - Higher-Order Functions Series - Ask for missing details.js ================================================ /* Description: You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising. Given the following input array: var list1 = [ { firstName: null, lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java' }, { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: null }, { firstName: 'Madison', lastName: 'U.', country: 'United States', continent: 'Americas', age: 32, language: 'Ruby' } ]; write a function that 1) adds the question property to each object in the input array where the developer has not provided the relevant details (marked with a null value). The value of the question property should be the following string: Hi, could you please provide your . 2) and returns only the developers with missing details: [ { firstName: null, lastName: 'I.', country: 'Argentina', continent: 'Americas', age: 35, language: 'Java', question: 'Hi, could you please provide your firstName.' }, { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 35, language: null, question: 'Hi, could you please provide your language.' } ] Notes: At most only one of the values will be null. Preserve the order of the original list. Return an empty array [] if there is no developer with missing details. The input array will always be valid and formatted as in the example above. This kata is part of the Coding Meetup series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: forEach, filter, map, reduce, some, every, find, findIndex. Other approaches to solving the katas are of course possible. */ function askForMissingDetails(list) { let arr = []; list.map(list=>{ for (let i in list){ if (list[i]===null){ list={...list,question:`Hi, could you please provide your ${i}.`} arr.push(list) } }}) return arr } ================================================ FILE: Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer.js ================================================ /* Description: You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return an array which includes the developer who is the oldest. In case of a tie, include all same-age senior developers listed in the same order as they appeared in the original input array. For example, given the following input array: var list1 = [ { firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' }, { firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' }, { firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' }, { firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' }, ]; your function should return the following array: [ { firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' }, { firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' }, ] Notes: The input array will always be valid and formatted as in the example above. This kata is part of the Coding Meetup series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: forEach, filter, map, reduce, some, every, find, findIndex. Other approaches to solving the katas are of course possible. */ function findSenior(list) { let max = Math.max(...list.map(v=>v.age)) return list.filter(v=>v.age===max) } ================================================ FILE: Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?.js ================================================ /* Description: You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return: true if all of the following continents / geographic zones will be represented by at least one developer: 'Africa', 'Americas', 'Asia', 'Europe', 'Oceania'. false otherwise. For example, given the following input array: var list1 = [ { firstName: 'Fatima', lastName: 'A.', country: 'Algeria', continent: 'Africa', age: 25, language: 'JavaScript' }, { firstName: 'Agustín', lastName: 'M.', country: 'Chile', continent: 'Americas', age: 37, language: 'C' }, { firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' }, { firstName: 'Laia', lastName: 'P.', country: 'Andorra', continent: 'Europe', age: 55, language: 'Ruby' }, { firstName: 'Oliver', lastName: 'Q.', country: 'Australia', continent: 'Oceania', age: 65, language: 'PHP' }, ]; your function should return true as there is at least one developer from the required 5 geographic zones. Notes: The input array and continent names will always be valid and formatted as in the list above for example 'Africa' will always start with upper-case 'A'. This kata is part of the Coding Meetup series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: forEach, filter, map, reduce, some, every, find, findIndex. Other approaches to solving the katas are of course possible. */ function allContinents(list) { return ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania'].every(x => list.some(y => x==y.continent)); } ================================================ FILE: Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?.js ================================================ /* Description: You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return: true if developers from all of the following age groups have signed up: teens, twenties, thirties, forties, fifties, sixties, seventies, eighties, nineties, centenarian (at least 100 years young). false otherwise. For example, given the following input array: var list1 = [ { firstName: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 19, language: 'Python' }, { firstName: 'Kseniya', lastName: 'T.', country: 'Belarus', continent: 'Europe', age: 29, language: 'JavaScript' }, { firstName: 'Jing', lastName: 'X.', country: 'China', continent: 'Asia', age: 39, language: 'Ruby' }, { firstName: 'Noa', lastName: 'A.', country: 'Israel', continent: 'Asia', age: 40, language: 'Ruby' }, { firstName: 'Andrei', lastName: 'E.', country: 'Romania', continent: 'Europe', age: 59, language: 'C' }, { firstName: 'Maria', lastName: 'S.', country: 'Peru', continent: 'Americas', age: 60, language: 'C' }, { firstName: 'Lukas', lastName: 'X.', country: 'Croatia', continent: 'Europe', age: 75, language: 'Python' }, { firstName: 'Chloe', lastName: 'K.', country: 'Guernsey', continent: 'Europe', age: 88, language: 'Ruby' }, { firstName: 'Viktoria', lastName: 'W.', country: 'Bulgaria', continent: 'Europe', age: 98, language: 'PHP' }, { firstName: 'Piotr', lastName: 'B.', country: 'Poland', continent: 'Europe', age: 128, language: 'JavaScript' } ]; your function should return true as there is at least one developer from each age group. Notes: The input array will always be valid and formatted as in the example above. Age is represented by a number which can be any positive integer up to 199. This kata is part of the Coding Meetup series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: forEach, filter, map, reduce, some, every, find, findIndex. Other approaches to solving the katas are of course possible. */ function isAgeDiverse(list) { const check = [0,0,0,0,0,0,0,0,0,0] list.map(v=>{ const age=v.age; age>9&&age<20?check[0]=1:0; age>19&&age<30?check[1]=1:0; age>29&&age<40?check[2]=1:0; age>39&&age<50?check[3]=1:0; age>49&&age<60?check[4]=1:0; age>59&&age<70?check[5]=1:0; age>69&&age<80?check[6]=1:0; age>79&&age<90?check[7]=1:0; age>89&&age<100?check[8]=1:0; age>100?check[9]=1:0; }) return check.every(v=>v===1) } ================================================ FILE: Collatz.js ================================================ /* Description: Preface A collatz sequence, starting with a positive integern, is found by repeatedly applying the following function to n until n == 1 : collatz sequence n = { n / 2 for even n ; 3n + 1 for odd n } ======= A more detailed description of the collatz conjecture may be found on Wikipedia. The Problem Create a function collatz that returns a collatz sequence string starting with the positive integer argument passed into the function, in the following form: "X0->X1->...->XN" Where Xi is each iteration of the sequence and N is the length of the sequence. Sample Input collatz(4); // should return "4->2->1" collatz(3); // should return "3->10->5->16->8->4->2->1" Don't worry about invalid input. Arguments passed into the function are guaranteed to be valid integers >= 1. */ function collatz(n){ let num=[]; for (let i=n;;){ if (i===1){ num.push(i) break } if (i%2===0) { num.push(i) i=i/2 } else { num.push(i) i=i*3+1 } } return num.join('->') } ================================================ FILE: Color Choice.js ================================================ /* Description: You know combinations: for example, if you take 5 cards from a 52 cards deck you have 2,598,960 different combinations. In mathematics the number of x combinations you can take from a set of n elements is called the binomial coefficient of n and x, or more often n choose x. The formula to compute m = n choose x is: m = n! / (x! * (n - x)!) where ! is the factorial operator. You are a renowned poster designer and painter. You are asked to provide 6 posters all having the same design each in 2 colors. Posters must all have a different color combination and you have the choice of 4 colors: red, blue, yellow, green. How many colors can you choose for each poster? The answer is two since 4 choose 2 = 6. The combinations will be: {red, blue}, {red, yellow}, {red, green}, {blue, yellow}, {blue, green}, {yellow, green}. Now same question but you have 35 posters to provide and 7 colors available. How many colors for each poster? If you take combinations 7 choose 2 you will get 21 with the above formula. But 21 schemes aren't enough for 35 posters. If you take 7 choose 5 combinations you will get 21 too. Fortunately if you take 7 choose 3 or 7 choose 4 combinations you get 35 and so each poster will have a different combination of 3 colors or 5 colors. You will take 3 colors because it's less expensive. Hence the problem is: knowing m (number of posters to design), knowing n (total number of available colors), let us search x (number of colors for each poster so that each poster has a unique combination of colors and the number of combinations is exactly the same as the number of posters). In other words we must find x such as n choose x = m (1) for a given m and a given n; m >= 0 and n > 0. If many x are solutions give as result the smallest x. It can happen that when m is given at random there are no x satisfying equation (1) then return -1. Examples: checkchoose(6, 4) --> 2 checkchoose(4, 4) --> 1 checkchoose(4, 2) --> -1 checkchoose(35, 7) --> 3 checkchoose(36, 7) --> -1 a = 47129212243960 checkchoose(a, 50) --> 20 checkchoose(a + 1, 50) --> -1 */ function checkchoose(m, n) { let x = 1; for (let i = 1; i < n; i++) { x = Math.round(x * (n + 1 - i) / i) if (x == m) return i; } return -1; } ================================================ FILE: Combinator Flip.js ================================================ /* Description: Create a combinator function named flip that takes a function as an argument and returns that function with it's arguments reversed. For example: flip(print)(4,5) // returns "5 -> 4" function print(a,b) { return a + " -> " + b; } The idea is to reverse any number of arguments using a higher order function, without any concern for the function being passed into it. */ function flip(fn) { return (...args)=>fn(...(args.reverse())) } ================================================ FILE: Compare Versions.js ================================================ /* Description: Karan's company makes software that provides different features based on the version of operating system of the user. For finding which version is more recent, Karan uses the following method: function compareVersions (version1, version2) { return parseFloat(version1) >= parseFloat(version2); } While this function worked for OS versions 10.6, 10.7, 10.8 and 10.9, the Operating system company just released OS version 10.10. Karan's function fails for the new version: compareVersions ("10.9", "10.10"); // returns true, while it should return false Karan now wants to spend some time to right a more robust version comparison function that works for any future version/sub-version updates. Help Karan write this function. Here are a few sample cases: compareVersions("11", "10"); // returns true compareVersions("11", "11"); // returns true compareVersions("10.4.6", "10.4"); // returns true compareVersions("10.4", "11"); // returns false compareVersions("10.4", "10.10"); // returns false compareVersions("10.4.9", "10.5"); // returns false It can be assumed that version strings are non empty and only contain numeric literals and the character '.' */ function compareVersions (version1, version2) { let arr1 = version1.split('.'); let arr2 = version2.split('.'); let maxLength = Math.max(arr1.length, arr2.length); for (let i = 0; i < maxLength; i++) { if (Number(arr1[i] || 0) < Number(arr2[i] || 0)) { return false; } } return true; } ================================================ FILE: Compare powers.js ================================================ /* Description: You certainly can tell which is the larger number between 210 and 215. But what about, say, 210 and 310? You know this one too. Things tend to get a bit more complicated with both different bases and exponents: which is larger between 39 and 56? Well, by now you have surely guessed that you have to build a function to compare powers, returning -1 if the first member is larger, 0 if they are equal, 1 otherwise; powers to compare will be provided in the [base, exponent] format: comparePowers([2,10],[2,15])===1 comparePowers([2,10],[3,10])===1 comparePowers([2,10],[2,10])===0 comparePowers([3,9],[5,6])===-1 comparePowers([7,7],[5,8])===-1 Only positive integers will be tested, incluing bigger numbers - you are warned now, so be diligent try to implement an efficient solution not to drain too much on CW resources ;)! */ function comparePowers([a,b],[x,y]){ let f =Math.log10(a)*b; let s =Math.log10(x)*y; return f===s?0:f>s?-1:1 } ================================================ FILE: Compare section numbers.js ================================================ /* Description: Section numbers are strings of dot-separated integers. The highest level sections (chapters) are numbered 1, 2, 3, etc. Second level sections are numbered 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, etc. Next level sections are numbered 1.1.1, 1.1.2, 1.1.2, 1.2.1, 1.2.2, erc. There is no bound on the number of sections a document may have, nor is there any bound on the number of levels. A section of a certain level may appear directly inside a section several levels higher without the levels between. For example, section 1.0.1 may appear directly under section 1, without there being any level 2 section. Section 1.1 comes after section 1.0.1. Sections with trailing ".0" are considered to be the same as the section with the trailing ".0" truncated. Thus, section 1.0 is the same as section 1, and section 1.2.0.0 is the same as section 1.2. Write a function cmp(section1, section2) that returns -1, 0, or 1 depending on whether section1 is before, same as, or after section2 respectively. */ function cmp(section1,section2) { const one = section1.split('.'); const two = section2.split('.'); for (let i = 0; i < Math.max(one.length, two.length); i++) { const s1 = +one[i] || 0; const s2 = +two[i] || 0; if (s1 > s2) return 1; else if (s2 > s1) return -1; } return 0; } ================================================ FILE: Complete Fibonacci Series.js ================================================ /* Description: The function 'fibonacci' should return an array of fibonacci numbers. The function takes a number as an argument to decide how many no. of elements to produce. If the argument is less than or equal to 0 then return empty array Example: fibonacci(4); // should return [0,1,1,2] fibonacci(-1); // should return [] */ function fibonacci(n) { if (n<1) return []; if (n<2) return [0]; let arr=[0,1]; for (let i=2;i0;i--,j++){ if (s===-1){ s=9 } output.push((output[j].slice(0,j)+`${s--}`.repeat(n-j))) } return output.slice(1).join`\n` } ================================================ FILE: Complete The Pattern #8 - Number Pyramid.js ================================================ /* Description: ###Task: You have to write a function pattern which creates the following Pattern(See Examples) upto n(parameter) number of rows. ####Rules/Note: If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. All the lines in the pattern have same length i.e equal to the number of characters in the last line. Range of n is (-∞,100] ###Examples: pattern(5): 1 121 12321 1234321 123454321 pattern(10): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 pattern(15): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 123456789010987654321 12345678901210987654321 1234567890123210987654321 123456789012343210987654321 12345678901234543210987654321 pattern(20): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 123456789010987654321 12345678901210987654321 1234567890123210987654321 123456789012343210987654321 12345678901234543210987654321 1234567890123456543210987654321 123456789012345676543210987654321 12345678901234567876543210987654321 1234567890123456789876543210987654321 123456789012345678909876543210987654321 */ function pattern(n){ return Array.from({length: n}, (_, i) => { let arr = Array.from({length: i}, (v, j) => (j + 1) % 10); return ' '.repeat(n - i - 1) + arr.join('') + (i + 1) % 10 + arr.reverse().join('') + ' '.repeat(n - i - 1); }).join('\n'); } ================================================ FILE: Complete The Pattern #9 - Diamond.js ================================================ /* Description: Task: You have to write a function pattern which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. Rules/Note: If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. All the lines in the pattern have same length i.e equal to the number of characters in the longest line. Range of n is (-∞,100] Examples: pattern(5): 1 121 12321 1234321 123454321 1234321 12321 121 1 pattern(10): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 12345678987654321 123456787654321 1234567654321 12345654321 123454321 1234321 12321 121 1 pattern(15): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 123456789010987654321 12345678901210987654321 1234567890123210987654321 123456789012343210987654321 12345678901234543210987654321 123456789012343210987654321 1234567890123210987654321 12345678901210987654321 123456789010987654321 1234567890987654321 12345678987654321 123456787654321 1234567654321 12345654321 123454321 1234321 12321 121 1 pattern(20): 1 121 12321 1234321 123454321 12345654321 1234567654321 123456787654321 12345678987654321 1234567890987654321 123456789010987654321 12345678901210987654321 1234567890123210987654321 123456789012343210987654321 12345678901234543210987654321 1234567890123456543210987654321 123456789012345676543210987654321 12345678901234567876543210987654321 1234567890123456789876543210987654321 123456789012345678909876543210987654321 1234567890123456789876543210987654321 12345678901234567876543210987654321 123456789012345676543210987654321 1234567890123456543210987654321 12345678901234543210987654321 123456789012343210987654321 1234567890123210987654321 12345678901210987654321 123456789010987654321 1234567890987654321 12345678987654321 123456787654321 1234567654321 12345654321 123454321 1234321 12321 121 1 */ function pattern(n){ if (n===1) return '1' let output=""; for (let i=1;i<=n;i++){ let arr = Array(i).fill(0).map((v,i)=>(i+1)%10).join`` let arr2 = arr.split``.reverse().join``.slice(1) output+=' '.repeat(n-i)+arr+arr2+' '.repeat(n-i)+'\n' } return output+(output.split`\n`.reverse().slice(2).join`\n`); } ================================================ FILE: Complete the table pattern.js ================================================ /* When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said Description: Give you two number rows , columns and a string str. Returns a rows x columns table pattern and fill in the str(each grid fill in a char, the length of str is always less than or equals to the total numbers of grids): If rows = 4 and columns = 4, str = "Hello World!" The pattern should be a 4x4 table like this: +---+---+---+---+ | H | e | l | l | From left to right +---+---+---+---+ | o | | W | o | and from top to bottom +---+---+---+---+ | r | l | d | ! | each row separated by "\n" +---+---+---+---+ | | | | | +---+---+---+---+ Some examples: pattern(3, 3, "codewars") should return: +---+---+---+ | c | o | d | +---+---+---+ | e | w | a | +---+---+---+ | r | s | | +---+---+---+ pattern(4, 3, "Nice pattern") should return: +---+---+---+ | N | i | c | +---+---+---+ | e | | p | +---+---+---+ | a | t | t | +---+---+---+ | e | r | n | +---+---+---+ pattern(3, 4, "Nice pattern") should return: +---+---+---+---+ | N | i | c | e | +---+---+---+---+ | | p | a | t | +---+---+---+---+ | t | e | r | n | +---+---+---+---+ */ function pattern(rows,columns,str){ const arr = str.split`` let i=0; const s = ('+---'.repeat(columns)+'+'+'\n'+'| '.repeat(columns)+'|'+'\n').repeat(rows)+'+---'.repeat(columns)+'+' return s.replace(/\s\s\s/g,v=>' '+(arr[i++]||' ')+' ') } ================================================ FILE: Consecutive strings ================================================ /* You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array. #Example: longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta" n being the length of the string array, if n = 0 or k > n or k <= 0 return "". */ function longestConsec(strarr, k) { var longest = ""; for(var i=0;k>0 && i<=strarr.length-k;i++){ var tempStr = strarr.slice(i,i+k).join(""); if(tempStr.length > longest.length){ longest = tempStr; } } return longest; } ================================================ FILE: Consonant value,js ================================================ /* To introduce the problem think to my neighbor who drives a tanker truck. The level indicator is down and he is worried because he does not know if he will be able to make deliveries. We put the truck on a horizontal ground and measured the height of the liquid in the tank. Fortunately the tank is a perfect cylinder and the vertical walls on each end are flat. The height of the remaining liquid is h, the diameter of the cylinder is d, the total volume is vt (h, d, vt are positive or null integers). You can assume that h <= d. Could you calculate the remaining volume of the liquid? Your function tankvol(h, d, vt) returns an integer which is the truncated result (e.g floor) of your float calculation. Examples: tankvol(40,120,3500) should return 1021 (calculation gives about: 1021.26992027) tankvol(60,120,3500) should return 1750 tankvol(80,120,3500) should return 2478 (calculation gives about: 2478.73007973) Tank vertical section: alternative text */ function solve(s) { s=s.toLowerCase(); let arr=s.slice().replace(/[aeiuo]/g,' ').replace(/\s+/g,' '); arr=arr.split(' ').map(v=>v.split('').map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b,0)) return Math.max(...arr); }; ================================================ FILE: Convert integer to Whitespace format.js ================================================ /* Description: Story Hereinafter, [space] refers to " ", [tab] refers to "\t", and [LF] refers to "\n" for illustrative purposes. This does not mean that you can use these placeholders in your solution. In esoteric language called Whitespace, numbers are represented in the following format: first character represents the sign: [space] for plus, [tab] for minus; characters after that and until [LF] are the binary representation of the integer: [space] for 0, [tab] for 1. the integer MUST be terminated by [LF]. Notes Valid Whitespace number must always have at least two characters: a sign and the terminator. In case there are only two characters, the number is equal to zero. For the purposes of this kata, zero must always be represented as [space][LF]. In this kata, the output should not contain any leading zeros. In Whitespace, only space, tabulation and linefeed are meaningful characters. All other characters are ignored. However, for the purposes of this simple kata, please do not add any other characters in the output. In this kata, input will always be a valid negative or positive integer. For your convenience, in this kata we will use unbleach() function when evaluating your results. This function replaces whitespace characters with [space], [tab], and [LF] to make fail messages more obvious. You can see how it works in Example Test Cases. Examples 1 in Whitespace is " \t\n". 0 in Whitespace is " \n". -1 in Whitespace is "\t\t\n". 2 in Whitespace is " \t \n". -3 in Whitespace is "\t\t\t\n". More on Whitespace If you liked this kata, you may also enjoy a much harder Whitespace-related kata: Whitespace interpreter by @jacobb. */ function whitespaceNumber(n) { let b = n.toString(2) if (n===0) return ' \n' if (n<0){ let str = '\t' for (let i=1;i=0){ let str = ' ' for (let i=0;i c.toUpperCase()); } ================================================ FILE: Coordinates Validator ================================================ /* Description: 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 */ function isValidCoordinates(coordinates){ return /^(-?((\d|[0-8]\d)(\.\d+)?)|90),\s?(-?((\d\d?|[01][0-7]\d)(\.\d+)?)|180)$/.test(coordinates); } ================================================ FILE: Count Repeats.js ================================================ /* Description: Write a function that returns the count of characters that have to be removed in order to get a string with no consecutive repeats. Note: This includes any characters Examples 'abbbbc' => 'abc' # answer: 3 'abbcca' => 'abca' # answer: 2 'ab cca' => 'ab ca' # answer: 1 */ function countRepeats(str) { return str.length-str.replace(/(.)\1+/g,'$1').length } ================================================ FILE: Count characters in your string ================================================ /*Description: The main idea is to count all the occuring characters(UTF-8) in string. If you have string like this aba then the result should be { 'a': 2, 'b': 1 } What if the string is empty ? Then the result should be empty object literal { } For C#: Use a Dictionary for this kata! */ function count (string) { let cache={}; string.split('').map(v=>cache[v]=cache[v]+1||1) return cache; } ================================================ FILE: Count letters in string.js ================================================ /* Description: In this kata, you've to count lowercase letters in a given string and return the letter count in a hash with 'letter' as key and count as 'value'. The key must be 'symbol' instead of string in Ruby and 'char' instead of string in Crystal. Example: letter_count('arithmetics') #=> {"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2} */ function letterCount(s){ return s.split``.reduce((a,b)=>(a[b]=a[b]+1||1,a),{}) } ================================================ FILE: Count the days!.js ================================================ /* Description: Little Annie is very excited for upcoming events. She want's to know how many days she have to wait for a specific event. Your job is to help her out. Task: Write a function which returns the number of days from today till the given date. The function will take a Date object as parameter. You have to round the amount of days. If the event is in the past, return "The day is in the past!" If the event is today, return "Today is the day!" Else, return "x days" PS: This is my first kata. I hope you have fun^^ This kata is part of the Collection "Date fundamentals": #1 Count the Days! #2 Minutes to Midnight #3 Can Santa save Christmas? #4 Christmas Present Calculator */ function countDays(d){ let time = d let today=new Date() let todayCheck= time.getFullYear()===today.getFullYear()&&time.getMonth()===today.getMonth()&&time.getDay()===today.getDay() if (todayCheck) return "Today is the day!" let past = today.getTime()>time.getTime() if (past) return 'The day is in the past!' return `${Math.round((time.getTime()-today.getTime())/1000/60/60/24)} days` } ================================================ FILE: Count the divisible numbers.js ================================================ /* Description: Write function divisibleCount(x, y, k) that takes in 3 numbers x, y and k, and returns the number of integers within the range [x..y] that are divisible by k i.e.: { i : x ≤ i ≤ y, i mod k = 0 } For example: x = 6, y = 11 and k = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10. Note: x<=y */ function divisibleCount(x, y, k) { return Math.floor(y/k) - Math.floor((x-1)/k) } ================================================ FILE: Count the smiley faces! ================================================ /* Description: Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces. Rules for a smiling face: -Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ; -A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~ -Every smiling face must have a smiling mouth that should be marked with either ) or D. No additional characters are allowed except for those mentioned. Valid smiley face examples: :) :D ;-D :~) Invalid smiley faces: ;( :> :} :] Example cases: countSmileys([':)', ';(', ';}', ':-D']); // should return 2; countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3; countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1; */ function countSmileys(arr) { return arr.filter(v=>v.match(/(:|;)(-|~)?(\)|D)/)).length } ================================================ FILE: Countdown - Longest Word.js ================================================ /* Description: #Detail Countdown is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with the longest English word they can think of with the available letters - letters can not be used more than once unless there is another of the same character. #Task Given an uppercase 9 letter string, letters, find the longest word that can be made with some or all of the letters. The preloaded array words (or $words in Ruby) contains a bunch of uppercase words that you will have to loop through. Only return the longest word; if there is more than one, return the words of the same lengths in alphabetical order. If there are no words that can be made from the letters given, return None/nil/null. ##Examples letters = "ZZZZZZZZZ" longest word = None letters = "POVMERKIA", longest word = ["VAMPIRE"] letters = "DVAVPALEM" longest word = ["VAMPED", "VALVED", "PALMED"] */ function longestWord(letters){ let dict = letters.split``.reduce((a,b)=>(a[b]=a[b]+1||1,a),{}) let arr = [] for (let i=0;i0){ c[words[i][j]]-- if (j===words[i].length-1){ arr.push(words[i]) } } else { break } } else { break } } } if (arr.length===0) return null let max = Math.max(...arr.map(v=>v.length)) return arr.filter(v=>v.length===max) } ================================================ FILE: Counting DNA Nucleotides.js ================================================ /* Description: For a given DNA genectic code represented by a string, count the number of times the letters A (adenine), C (cytosine), G (guanine) and T (thymine) appears and return and object. All letters must be in uppercase. For example: var genCode = 'TCCAGAAAGGTAAGCCTCGCGTTGCGAAAATGTCAAGTTACCACATCCACACCACCTCGAGCAGCTTCTATAGCTAGCCAGCACAGAGACTCGCAGTCCCTCTACAAGCTTCCAATTGGAAGAGAGCTCGGGCCAAGCGTTTGTCGCCCCCCTCCCATTGAGATAAACCCGCATTCATTCAGGTACGAACGGATGCAGCTTGATTCTCCCCATGTAGTTAACTCGCTACATCCTATCAGCCTGAGGGTCCAAGTTGCTAGACCTACATTCACTCCTGCGCTCCTCATAAGCGACCTATCGACTAGTCTTGGCTTACACCTCAGAAGTGCGCTATTGGGCGGGTATTCAGTGGTTGCACGGCGCTTATGTGGGACGCGGTGTCTTAGAGGACAGAAGATGTACAGTCAATGGAGGGATCCTCCCGAGTCGCCATCTACCCATGCGTCTGAGATATGAAAGCAGCTACCAGCCTTTCAGCCACTCTGAAAGATTTCCGTCCTCTATCAAACGACCTGCCCCAGGCTTACTGTTACTAGTTCTTTGCAAATTAACTGTACTCATTTGGGAGAGTTCGCATGCGCCTCTCCATCATACTAGCGCAAAACCTGACATTCAAACGATTCCGCACCCAAAGCCGCGAATGTGTCCCCTTACATTTCGGAGAAAACCGGCTCGACTTGGCACCAAGAACTTTTATACGCTGGGTTGTGCCATGTCTTTATGTTTATCCTTTGGGCGGCAGGAGCGTCCTCACTGTTGCTCTGAAACAGTACATGCACATGTCTAGACGAACCTGAAGAACCCCTGAACACGCCATGCACCGCGCGTAAAGCCAGTTTCGACTGGTATATATAATGATGTTGTGAAACAAATCGGGAAGGCGCAGAAAAGAATGTGGTTGGACGAAGTCCATAACTGAAGGTTAGCGA'; getCountedNucleotides(genCode); // return {A: 238, C: 254, G: 212, T: 225} */ function getCountedNucleotides(genCode){ const DNA = {A: 0, C: 0, G: 0, T: 0}; genCode.toUpperCase().split``.map(v=>DNA[v]=DNA[v]?DNA[v]+1:1) return DNA } ================================================ FILE: Counting Duplicates ================================================ /* Description: Count the number of Duplicates Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. Example "abcde" -> 0 # no characters repeats more than once "aabbcde" -> 2 # 'a' and 'b' "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`) "indivisibility" -> 1 # 'i' occurs six times "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice "aA11" -> 2 # 'a' and '1' "ABBA" -> 2 # 'A' and 'B' each occur twice */ function duplicateCount(text){ return (text.toLowerCase().split('').sort().join('').match(/([^])\1+/g) || []).length; } ================================================ FILE: Create Four Letter Birding Codes from Bird Names.js ================================================ /* Description: In the world of birding there are four-letter codes for the common names of birds. These codes are created by some simple rules: If the bird's name has only one word, the code takes the first four letters of that word. If the name is made up of two words, the code takes the first two letters of each word. If the name is made up of three words, the code is created by taking the first letter from the first two words and the first two letters from the third word. If the name is four words long, the code uses the first letter from all the words. (There are other ways that codes are created, but this Kata will only use the four rules listed above) Complete the function that takes an array of strings of common bird names from North America, and create the codes for those names based on the rules above. The function should return an array of the codes in the same order in which the input names were presented. Additional considertations: The four-letter codes in the returned array should be in UPPER CASE. If a common name has a hyphen/dash, it should be considered a space. Example If the input array is: ["Black-Capped Chickadee", "Common Tern"] The return array would be: ["BCCH", "COTE"] */ function birdCode(arr){ return arr.map(v=>{ v=v.replace(/-./g,v=>v.toUpperCase()) let arr =v.match(/[A-Z]./g) if (arr.length===1){ return v.slice(0,4).toUpperCase() } if (arr.length===2){ return arr.join``.toUpperCase() } if (arr.length===3){ return arr[0][0]+arr[1][0]+arr[2].toUpperCase() } return arr.map(v=>v[0].toUpperCase()).join`` }) } ================================================ FILE: Create Parse HTML CSS Colors.js ================================================ /* Description: In this kata you parse RGB colors represented by strings. The formats are primarily used in HTML and CSS. Your task is to implement a function which takes a color as a string and returns the parsed color as a map (see Examples). Input: The input string represents one of the following: 6-digit hexadecimal - "#RRGGBB" e.g. "#012345", "#789abc", "#FFA077" Each pair of digits represents a value of the channel in hexadecimal: 00 to FF 3-digit hexadecimal - "#RGB" e.g. "#012", "#aaa", "#F5A" Each digit represents a value 0 to F which translates to 2-digit hexadecimal: 0->00, 1->11, 2->22, and so on. Preset color name e.g. "red", "BLUE", "LimeGreen" You have to use the predefined map PRESET_COLORS (JavaScript, Python, Ruby), presetColors (Java, C#, Haskell), or preset-colors (Clojure). The keys are the names of preset colors in lower-case and the values are the corresponding colors in 6-digit hexadecimal (same as 1. "#RRGGBB"). Examples: parseHTMLColor('#80FFA0'); // => { r: 128, g: 255, b: 160 } parseHTMLColor('#3B7'); // => { r: 51, g: 187, b: 119 } parseHTMLColor('LimeGreen'); // => { r: 50, g: 205, b: 50 } */ function parseHTMLColor(c) { if (!c.match("#")) c = PRESET_COLORS[c.toLowerCase()]; c = c.replace('#', ''); if (c.length < 6) c = c.replace(/(.)/g, "$1$1"); return { r: parseInt(c.substring(0, 2), 16), g: parseInt(c.substring(2, 4), 16), b: parseInt(c.substring(4, 6), 16) }; } ================================================ FILE: Create a frame!.js ================================================ /* Description: ************************* * Create a frame! * * __ __ * * / \~~~/ \ * * ,----( .. ) * * / \__ __/ * * /| (\ |( * * ^ \ /___\ /\ | * * |__| |__|-.. * ************************* Given an array of strings and a character to be used as border, output the frame with the content inside. Notes: Always keep a space between the input string and the left and right borders. The biggest string inside the array should always fit in the frame. The input array is never empty. Example frame(['Create', 'a', 'frame'], '+') Output: ++++++++++ + Create + + a + + frame + ++++++++++ */ const frame = (text, char) => { let max =Math.max(...text.map(v=>v.length)) let top = char.repeat(max+4) return top+`\n`+text.map(v=>`${char} `+v+' '.repeat(max-v.length)+` ${char}`).join`\n`+`\n`+top; }; ================================================ FILE: Creating a string for an array of objects from a set of words.js ================================================ /* Description: You're given a string containing a sequence of words separated with whitespaces. Let's say it is a sequence of patterns: a name and a corresponding number - like this: "red 1 yellow 2 black 3 white 4" You want to turn it into a different string of objects you plan to work with later on - like this: "[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]" Doing this manually is a pain. So you've decided to write a short function that would make the computer do the job for you. Keep in mind, the pattern isn't necessarily a word and a number. Consider anything separeted by a whitespace, just don't forget: an array of objects with two elements: name and id. As a result you'll have a string you may just copy-paste whenever you feel like defining a list of objects - now without the need to put in names, IDs, curly brackets, colon signs, screw up everything, fail searching for a typo and begin anew. This might come in handy with large lists. */ function wordsToObject(input) { let arr = [] input=input.split` ` for (let i=0;i{ return v=`{name : \'${v[0]}\', id : \'${v[1]+''}\'}`}) return '['+arr.join`, `+']' } ================================================ FILE: Cryptography #1 - Viva Cesare.js ================================================ /* Description: Let’s get to know our hero: Agent #134 - Mr. Slayer. He was sent by his CSV agency to Ancient Rome in order to resolve some important national issues. However, something incredible has happened - the enemies have taken Julius Caesar as a prisoner!!! Caesar, not a simple man as you know, managed to send cryptic message with coordinates of his location hoping that somebody would break the code. Here our agent of the secret service comes to the stage. But he needs your help! Mission: You have to implement the function “Encode” of CaesarCrypto class that codes or decodes text based on Caesar’s algorithm. the function receives 2 parameters: an original text of any length of type “string” and a number of type “int” that represents shifts; only letters in both cases must be encrypted; alphabet contains only letters in this range: a-zA-Z; by encryption the letter can change the case; shift could be either positive or negative (for left shift); If the input text is empty, null or includes only whitespaces, return an empty string. Time's ticking away. The life of Caesar is on the chopping block! Go for it! */ function CaesarCryptoEncode(text, shift) { if (!text) return ''; shift = (shift % 52 + 52) % 52; const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; return text.trim().replace(/[a-z]/ig, c => letters[(letters.indexOf(c) + shift) % 52]); } ================================================ FILE: Cumulative Triangle.js ================================================ /* Description: Imagine a triangle of numbers which follows this pattern: Starting with the number "1", "1" is positioned at the top of the triangle. As this is the 1st row, it can only support a single number. The 2nd row can support the next 2 numbers: "2" and "3" Likewise, the 3rd row, can only support the next 3 numbers: "4", "5", "6" And so on; this pattern continues. 1 2 3 4 5 6 7 8 9 10 ... Given N, return the sum of all numbers on the Nth Row: 1 <= N <= 10,000 */ let arr = [] const heheboi=()=>{ let num = 0 for (let i=1;i<=10000;i++){ let tempArr = [] for (let j=0;ja+b,0) } ================================================ FILE: Custom Array Filters.js ================================================ /* Description: Dave has a lot of data he is required to apply filters to, which are simple enough, but he wants a shorter way of doing so. He wants the following functions to work as expected: even // [1,2,3,4,5].even() should return [2,4] odd // [1,2,3,4,5].odd() should return [1,3,5] under // [1,2,3,4,5].under(4) should return [1,2,3] over // [1,2,3,4,5].over(4) should return [5] inRange // [1,2,3,4,5].inRange(1,3) should return [1,2,3] They should also work when used together, for example: [1,2,18,19,20,21,22,30,40,50,100].even().inRange(18,30) // should return [18, 20, 22, 30] And finally the filters should only accept integer values from an array, for example: ["a", 1, "b", 300, "x", "q", 63, 122, 181, "z", 0.83, 0.11].even() // should return [300, 122] */ Array.prototype.even = function(){ return this.filter(v=>v%2===0&&typeof v==='number'&&v!==0&&Number.isInteger(v)) } Array.prototype.odd = function(){ return this.filter(v=>v%2!==0&&typeof v==='number'&&Number.isInteger(v)) } Array.prototype.under = function(x){ return this.filter(v=>vv>x&&typeof v==='number'&&Number.isInteger(v)) } Array.prototype.inRange = function(min,max){ return this.filter(v=>v>=min&&v<=max&&typeof v==='number'&&Number.isInteger(v)) } ================================================ FILE: Custom Setters and Getters.js ================================================ /* Description: Let's take a look at an interesting feature of JS: custom Getters and Setters for objects. Skimming over this may help you prepare for this kata: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FWorking_with_Objects#Defining_Getters_and_Setters (thanks to @contablebrew for pointing out the more "forward-compatible" approach to this.) The object of this exercise will be to provide a constructor named "Archiver" that creates a "self-archiving" object with respect to its "temperature" property, but otherwise looks and acts just like a normal JS object. Each time the "temperature" property is assigned, the object should add a log entry to an array (the "archive") that it returns via a "getArchive" function. The log entry should be formed as such: {date: //the Date when the "temperature" property was assigned, val: //the value that was written to the "temperature" property.} . The "date" property of the log entry should be a valid JS Date object. so e.g.: //new Date() == '2013-09-24...Z' var arc = new Archiver(); arc.temperature = 33; arc.temperature = 28; arc.temperature = 21; arc.getArchive() // == [{date: 2013-09-24..., val:33},{date: 2013-09-24..., val:28},{date: 2013-09-24..., val:21}] */ function Archiver() { var temperature = null; var archive = []; Object.defineProperty(this, 'temperature', { get: function() { return temperature; }, set: function(value) { temperature = value; archive.push({ date: new Date(), val: temperature }); } }); this.getArchive = function() {return archive;}; } ================================================ FILE: Custom each() Array method.js ================================================ /* Description: JavaScript provides an Array.prototype.forEach method that allows you to iterate over array values. For this exercise you will create your own array method called 'each'. It will be similar to the forEach method, except for one difference. If the callback function returns true then the loop will stop and no additional values will be iterated. The following shows a contrived example of how this new method would be used: var letters = ['a', 'b', 'c', 'd', 'e'] var allowedLetters = [] letters.each(function(letter, index){ // break out of the loop if we reached a letter with the value 'd' if(letter == 'd') { return true; } allowedLetters.push(letter); }) // allowedLetters should equal ['a', 'b', 'c'] In Ruby, you would use it like this: letters = ['a', 'b', 'c', 'd', 'e'] allowedLetters = [] letters.each_until_true do |letter, index| # break out of the loop if we reached a letter with the value 'd' if letter == 'd' true else allowedLetters.push(letter); end end # allowedLetters should equal ['a', 'b', 'c'] */ Array.prototype.each = [].some ================================================ FILE: Custom sort function.js ================================================ /* Description: Complete the sort function so that it returns the items passed into it in alphanumerical order. Conveniently enough, the standard array sort method has been disabled for you so that you are forced to create your own. Example: sort([1,3,2]) // should return [1,2,3] */ function sort(array) { if (array.length === 1) return array; let left = array.slice(0, array.length / 2); let right = array.slice(array.length / 2 ); left = sort(left); right = sort(right); return merge(left, right); } function merge(left, right) { let arr = []; while (left.length > 0 && right.length > 0) { if (left[0] > right[0]) { arr.push(right[0]); right.shift() } else { arr.push(left[0]); left.shift(); } } while (left.length) { arr.push(left[0]); left.shift(); } while (right.length) { arr.push(right[0]); right.shift(); } return arr } ================================================ FILE: Cycle Detection: greedy algorithm.js ================================================ /* Description: In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values. For any function ƒ, and any initial value x0 in S, the sequence of iterated function values x0,x1=f(x0), x2=f(x1), ...,xi=f(x{i-1}),... may eventually use the same value twice under some assumptions: S finite, f periodic ... etc. So there will be some i ≠ j such that xi = xj. Once this happens, the sequence must continue by repeating the cycle of values from xi to xj−1. Cycle detection is the problem of finding i and j, given ƒ and x0. Let μ be the smallest index such that the value associated will reappears and λ the smallest value such that xμ = xλ+μ, λ is the loop length. Example: Consider the sequence: 2, 0, 6, 3, 1, 6, 3, 1, 6, 3, 1, .... The cycle in this value sequence is 6, 3, 1. μ is 2 (first 6) λ is 3 (length of the sequence or difference between position of consecutive 6). The goal of this kata is to build a function that will return [μ,λ] when given a short sequence. Simple loops will be sufficient. The sequence will be given in the form of an array. All array will be valid sequence associated with deterministic function. It means that the sequence will repeat itself when a value is reached a second time. (So you treat two cases: non repeating [1,2,3,4] and repeating [1,2,1,2], no hybrid cases like [1,2,1,4]). If there is no repetition you should return []. This kata is followed by two other cycle detection algorithms: Loyd's: http://www.codewars.com/kata/cycle-detection-floyds-tortoise-and-the-hare Bret's: http://www.codewars.com/kata/cycle-detection-brents-tortoise-and-hare */ function cycle(a) { const sndIdx = a.findIndex( (v,i) =>{ return a.slice(0,i).includes(v) }); if ( sndIdx===-1 ) return []; else { const fstIdx = a.indexOf(a[sndIdx]); return [ fstIdx, sndIdx-fstIdx ]; } } ================================================ FILE: Cycle a list of values.js ================================================ /* Description: Prologue You're part of a team porting MS Paint into the browser and currently working on a new UI component that allows user to control the canvas zoom level. According to the wireframes delivered to you in PowerPoint format the user should be able to cycle through specified zoom levels by clicking a button in the UI repeatedly. The reverse direction should work with shift key held. A new function is needed to support this behavior, so you alt-tab to Visual Studio and get to work. Instructions Implement a function which when given the arguments Direction to which to cycle the current value List of values Current value returns the value next to current value in the specified direction. The function should pick the next value from the other side of the list in case there are no values in the given direction. Examples cycle(1, [1,2,3], 1) // => 2 // Given the direction 1, returns the value next to 1 on the right cycle(-1, [1,2,3], 1) // => 3 // Given the direction -1 and value 1, wraps around list returning the last element cycle(1, [1,2,3], 0) // => null // 0 does not exist in the list, returns null cycle(1, [1,2,2,3], 2) // => 2 // Corner case: multiple instances of given value, picks next relative to first occurrence */ function cycle(dir, arr, cur) { if (!arr.includes(cur)) return null; const index=arr.indexOf(cur) return arr[(index+dir)%arr.length]?arr[(index+dir)%arr.length]:arr.reverse()[index%arr.length] } ================================================ FILE: Cylon Evolution.js ================================================ /* Description: There are all types of cylons. The trick is, some look like humans. Using prototypical inheritance, create a prototype for Cylon. Cylons should have a model, and should have an attack function, which will return the string "Destory all humans!" Since some cylons appear human, then make a child object called HumanSkin. This should have a model, as Cylons do, and should have the same attack. However, it should also have a function called infiltrate, which will return the string "Infiltrate the colonies". */ class Cylon{ constructor(model){ this.model=model } attack(){ return "Destroy all humans!" } } class HumanSkin extends Cylon{ constructor(model){ super(model) this.model=model } infiltrate(){ return "Infiltrate the colonies" } } ================================================ FILE: Dashatize it.js ================================================ /* Description: Given a number, return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark. Ex: dashatize(274) -> '2-7-4' dashatize(6815) -> '68-1-5' */ function dashatize(num) { return String(num) .replace(/([13579])/g, "-$1-") .replace(/--+/g, "-") .replace(/(^-|-$)/g, "") } ================================================ FILE: Data Reverse.js ================================================ /* Description: A stream of data is received and needs to be reversed. Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example: 11111111 00000000 00001111 10101010 (byte1) (byte2) (byte3) (byte4) should become: 10101010 00001111 00000000 11111111 (byte4) (byte3) (byte2) (byte1) The total number of bits will always be a multiple of 8. The data is given in an array as such: [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0] */ const dataReverse = function(data){ if (data.length===0) return [] const arrayBytes = []; const tam = data.length / 8; for (var i = 0; i < tam; i++){ arrayBytes.push(data.splice(0,8)); } return arrayBytes.reverse().join().split(',').map(v=>v*1); } ================================================ FILE: Data compression using run-length encoding.js ================================================ /* Description: Run-length encoding (RLE) is a very simple form of lossless data compression in which runs of data are stored as a single data value and count. A simple form of RLE would encode the string "AAABBBCCCD" as "3A3B3C1D" meaning, first there are 3 A, then 3 B, then 3 C and last there is 1 D. Your task is to write a RLE encoder and decoder using this technique. The texts to encode will always consist of only uppercase characters, no numbers. */ function encode(input) { let count=1; let str=''; for (let i=0;iv); const arr2=input.slice().replace(/\D/gi,' ').replace(/\s+/g,' ').split(' ').filter(v=>v) let str=''; for (let i=0;iString.fromCharCode(v*1)).split(' ') .map(v=>v.length>2?v.slice(0,1)+v.slice(-1)+v.slice(2,-1)+v.slice(1,2):v).join` ` }; ================================================ FILE: Decode Morse.js ================================================ /* Description: Oh no! You have stumbled upon a mysterious signal consisting of beeps of various lengths, and it is of utmost importance that you find out the secret message hidden in the beeps. There are long and short beeps, the longer ones roughly three times as long as the shorter ones. Hmm... that sounds familiar. That's right: your job is to implement a decoder for the Morse alphabet. Rather than dealing with actual beeps, we will use a common string encoding of Morse. A long beep is represened by a dash (-) and a short beep by a dot (.). A series of long and short beeps make up a letter, and letters are separated by spaces (). Words are separated by double spaces. You should implement the International Morse Alphabet. You need to support letters a-z and digits 0-9 as follows: a .- h .... o --- u ..- 1 .---- 6 -.... b -... i .. p .--. v ...- 2 ..--- 7 --... c -.-. j .--- q --.- w .-- 3 ...-- 8 ---.. d -.. k -.- r .-. x -..- 4 ....- 9 ----. e . l .-.. s ... y -.-- 5 ..... 0 ----- f ..-. m -- t - z --.. g --. n -. Examples .... . .-.. .-.. --- .-- --- .-. .-.. -.. → "hello world" .---- ... - .- -. -.. ..--- -. -.. → "1st and 2nd" */ function decode(str) { const morse = {'1':'.----','2':'..---','3':'...--','4':'....-',5:'.....',6:'-....',7:'--...',8:'---..',9:'----.',0:'-----','a':".-", 'b':"-...", 'c':"-.-.", 'd':"-..", 'e':".", 'f':"..-.", 'g':"--.", 'h':"....", 'i':"..", 'j':".---", 'k':"-.-", 'l':".-..", 'm':"--", 'n':"-.", 'o':"---", 'p':".--.", 'q':"--.-", 'r':".-.", 's':"...", 't':"-", 'u':"..-", 'v':"...-", 'w':".--", 'x':"-..-", 'y':"-.--", 'z':"--.."} const morse2={} for (let i in morse){ morse2[morse[i]]=i } return str.split` `.map(v=>morse2[v]||' ').join`` } ================================================ FILE: Decode the Morse code ================================================ /* Description: 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. 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: decodeMorse('.... . -.-- .--- ..- -.. .') //should return "HEY JUDE" NOTE: For coding purposes you have to use ASCII characters . and -, not Unicode characters. The Morse code table is preloaded for you as a dictionary, feel free to use it: Coffeescript/C++/Go/JavaScript/PHP/Python/Ruby/TypeScript: MORSE_CODE['.--'] C#: MorseCode.Get(".--") (returns string) Elixir: morse_codes variable Haskell: morseCodes ! ".--" (Codes are in a Map String String) Java: MorseCode.get(".--") Kotlin: MorseCode[".--"] ?: "" or MorseCode.getOrDefault(".--", "") Rust: 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. */ decodeMorse = function(morseCode){ return morseCode.split(' ').map((v,i)=>MORSE_CODE[v]!=undefined?MORSE_CODE[v]:1).join('').replace(/11/g,' ').replace(/1/g,' ').trim() } ================================================ FILE: Decompose a number.js ================================================ /* Description: Decompose a number num into an array (tuple in Haskell, array of arrays long[][] in C# or Java) of the form [[k1,k2,k3...], r], ([k1,k2,k3...], r) in Haskell, [[k1,k2,k3...], [r]] in C# or Java) such that: each kn is more than one eack kn is maximized (first maximizing for 2 then 3 then 4 and so on) and 2k1 + 3k2 + 4k3 + ... + nkn-1 + r = num ##Examples # when there are no `k` more than 1: 3 [[], 3] = 3 # when the remainder is zero: 8330475 [[22, 13, 10, 8, 7, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2], 0] = 2 ^ 22 + 3 ^ 13 + 4 ^ 10 + 5 ^ 8 + 6 ^ 7 + 7 ^ 6 + 8 ^ 6 + 9 ^ 5 + 10 ^ 5 + 11 ^ 5 + 12 ^ 4 + 13 ^ 4 + 14 ^ 4 + 15 ^ 3 + 16 ^ 3 + 17 ^ 3 + 18 ^ 3 + 19 ^ 3 + 20 ^ 3 + 21 ^ 2 + 22 ^ 2 + 23 ^ 2 + 24 ^ 2 + 0 = 8330475 # when there is both `k` and a remainder: 26 [[4, 2], 1] = 2 ^ 4 + 3 ^ 2 + 1 = 26 # when there is neither `k` nor a remainder: 0 [[], 0] = 0 */ function decompose(num) { let i = 2; let pow = 50 let arr = [] while (num>0){ if (pow===1){break} if (num(cache[v]=~~cache[v]+1)<=n) } ================================================ FILE: Descriptive selections of data.js ================================================ /* Description: Fill in the functions with the help of the provided methods only, i.e. just compose with them: rest(), map(), first(), second(), third(), zip() Example return map(table, second); Here are their descriptions: rest([5, 4, 3, 2, 1]); => [4, 3, 2, 1] map([1, 2, 3], function(num){ return num * 3; }); => [3, 6, 9] first([5, 4, 3, 2, 1]); // second, third ... => 5 zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]] *Note: * The first row within the data array will always be the column names. These column names will always have the same order. No need to determine which index a column should be dynamically. */ const selectNames = table => map(rest(table), first) const selectVoices = table => map(rest(table), third) const selectNamesAndVoices = table => zip(selectNames(table), selectVoices(table)) ================================================ FILE: Design a Simple Automaton (Finite State Machine).js ================================================ /* Description: 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 var a = new Automaton(); // Do anything you need to set up this automaton's states. var isAccepted = a.readCommands(["1", "0", "0", "1", "0"]); 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 */ function Automaton() { } Automaton.prototype.readCommands = function(commands) { return /^0*1(1|00|01)*$/.test(commands.join('')); } var myAutomaton = new Automaton(); ================================================ FILE: Detect Pangram ================================================ /* Description: A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation. */ function isPangram(string){ let str=string.split(' ').join('').replace(/[\W\d]/g,'').toLowerCase().split('') return [...new Set(str)].length==26 } ================================================ FILE: Difference of 2.js ================================================ /* Description: The objective is to return all pairs of integers from a given array of integers that have a difference of 2. The result array should be sorted in ascending order of values. Examples: [1,2,3,4] should return [[1,3],[2,4]] [4,1,2,3] should also return [[1,3],[2,4]] [1,23,3,4,7] should return [[1,3]] [4,3,1,5,6] should return [[1,3],[3,5],[4,6]] Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter. */ function twosDifference(input){ input=input.sort((a,b)=>a-b) const arr = []; for (let i=0;i 1939 findTheKey("masterpiece", [14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8]); => 1939 findTheKey("nomoretears", [15, 17, 14, 17, 19, 7, 21, 7, 2, 20, 20]); => 12 Digital cypher series Digital cypher vol 1 Digital cypher vol 2 Digital cypher vol 3 - missing key */ function findTheKey(message, code) { let arr = (message).split``.map(v=>v.charCodeAt()-96) for (let i=0;i 483 Notes: You will pass the tests if abs(actual - expected) <= 1 Keeping track of the values of susceptibles, infecteds and recovereds you can plot the solutions of the 3 differential equations. See an example below on the plot. alternative text */ function epidemic(tm, n, s0, i0, b, a) { const dt = tm / n; const iArr = new Array(n).fill(), sArr = new Array(n).fill(), rArr = new Array(n).fill(); [iArr[0], sArr[0], rArr[0]] = [i0,s0,0]; iArr.slice(1).map((_, i) => { sArr[i + 1] = sArr[i] - dt * b * sArr[i] * iArr[i]; iArr[i + 1] = iArr[i] + dt * (b * sArr[i] * iArr[i] - a * iArr[i]); rArr[i + 1] = rArr[i] + dt * iArr[i] * a; }); return Math.ceil(Math.max(...iArr)); } ================================================ FILE: Disgruntled Employee.js ================================================ /* Description: Sir Bobsworth is a custodian at a local data center. As he suspected, Bobsworth recently found out he is to be fired on his birthday after years of pouring his soul into maintaining the facility. Bobsworth, however, has other plans. Bobsworth knows there are 1 to n switches in the breaker box of the data center. Moving from switch 1 to n, Bob first flips every switch off. Beginning from the first switch again, Bob then flips every 2nd switch. Once again starting from the first switch, Bob then flips every 3rd switch. Bob continues this pattern until he flips every nth switch & makes n passes. At the end of Bobsworth's mayhem, how many switches are turned off? Specifications Create the function off, that receives the nth switch as argument n. The function should return an ascending array containing all of the switch numbers that remain off after Bob completes his revenge. off (1) //returns {1} off (2) //returns {1} off (4) //returns {1,4} off (9) //returns {1,4,9} The parameter n will always be a number >= 1. */ let arr = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961] function off(n) { return arr.filter(v=>n>=v) } ================================================ FILE: Disguised sequences (II).js ================================================ /* Description: Let us define two sums u(n, p) and v(n, p): \large u(n, p) = \sum_{k=0}^{n}{(-1)^k}*p*{4^{n-k}}*\binom{2n-k+1}{k} \large v(n, p) = \sum_{k=0}^{n}{(-1)^k}*p*{4^{n-k}}*\binom{2n-k}{k} Task: 1) Calculate u(n, p) and v(n, p) with two brute-force functions u1(n, p) and v1(n, p). 2) Try u1(n, p) and v1(n, p) for small values of n and p and guess the results of u(n, p) and v(n, p) 3) Using 2) write u_eff(n, p) and v_eff(n, p) (or uEff(n, p) and vEff(n, p) or u-eff(n, p) and v-eff(n, p)) to efficiently calculate u and v for bigger values of n and p (This third part is not tested in JS, CS, TS, C++, C, PHP, Crystal, Rust, Swift, R, Nim, Fortran, NASM since there you don't have big integers to control your guess in part 2. See note below for "Shell"). Examples: v1(12, 70) --> 1750 u1(13, 18) --> 252 Extra points: For the mathy ones: find a relation between v(n, p), v(n-1, p) and u(n-1, p) :-) Notes Shell: only v1(n, p)is tested (use the solution you find for v_eff(n, p). If you have found u_eff(n, p) and v_eff(n, p) you can use them to calculate u(n, p) and v(n, p). You could see: https://en.wikipedia.org/wiki/Binomial_coefficient for a refresh about binomial coefficients. */ function fact($num) { let product = 1; for (let i=1; i<=$num; i++) product*= i; return Math.round(product); } function u1(n, p) { let result=0; for (let k=0; k<=n; k++) { let part=Math.pow(-1, k)*p*Math.pow(4, n-k); let abc=(n*2)-k+1; result= result + (part*((fact(abc))/(fact(abc-k)*fact(k)))); } return Math.round(result); } function v1(n, p) { let result=0; for (let k=0; k<=n; k++) { let part=Math.pow(-1, k)*p*Math.pow(4, n-k); let abc=(n*2)-k; result= result + (part*((fact(abc))/(fact(abc-k)*fact(k)))); } return Math.round(result) } ================================================ FILE: Divisible Ints.js ================================================ /* Description: You are given an integer N. Your job is to figure out how many substrings inside of N divide evenly with N. Confused? I'll break it down for you. Let's say that you are given the integer '877692'. 8 does not evenly divide with 877692. 877692/8 = 109711 with 4 remainder. 7 does not evenly divide with 877692. 877692/7 = 125384 with 4 remainder. 7 does not evenly divide with 877692. 877692/7 = 125384 with 4 remainder. 6 evenly divides with 877692. 877692/6 = 146282 with 0 remainder. 9 does not evenly divide with 877692. 877692/9 = 97521 with 3 remainder. 2 evenly divides with 877692. 877692/2 = 438846 with 0 remainder. We aren't going to stop there though. We need to check ALL of the substrings inside of 877692. 87 does not evenly divide with 877692. 877692/87 = 10088 with 36 remainder. 77 does not evenly divide with 877692. 877692/77 = 11398 with 46 remainder. 76 does not evenly divide with 877692. 877692/76 = 11548 with 44 remainder. 69 does not evenly divide with 877692. 877692/69 = 12720 with 12 remainder. etc. #Rules: -If an integer is 0, then it does NOT divide evenly into anything. -Even though N can divide evenly with itself, we do not count it towards the end number. For Example: N = 23, the answer will be 0. -If there are multiple instances of a number, they all get counted. For example: N = 11, the answer will be 2 #Input: A non negative integer. #Output: The number of times you found an integer that was evenly divisible with N. */ function getCount(n) { const arr = []; let str =n.toString() for (let i=0;in%v*1===0?count++:1) return count-1 } ================================================ FILE: Does my number look big in this? ================================================ /* Description: A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10). For example, take 153 (3 digits): 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 and 1634 (4 digits): 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634 The Challenge: Your code must return true or false depending upon whether the given number is a Narcissistic number in base 10. Error checking for text strings or other invalid inputs is not required, only valid integers will be passed into the function. */ function narcissistic( value ) { return value.toString().split('').map((v,i,arr)=>Math.pow(arr[i],arr.length)).reduce((a,b)=>a+b,0)===value } ================================================ FILE: Don't rely on luck. ================================================ /* Description: The test fixture I use for this kata is pre-populated. It will compare your guess to a random number generated using: Math.floor(Math.random() * 100 + 1) 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! */ var guess = 101; Math.random = () => 1; ================================================ FILE: Doors in the school.js ================================================ /* Description: In the morning all the doors in the school are closed. The school is quite big: there are N doors. Then pupils start coming. It might be hard to believe, but all of them want to study! Also, there are exactly N children studying in this school, and they come one by one. When these strange children pass by some doors they change their status (i.e. Open -> Closed, Closed -> Open). Each student has their number, and each i-th student alters the status of every i-th door. For example: when the first child comes to the schools, he changes every first door (he opens all of them). The second one changes the status of every second door (he closes some doors: the 2nd, the 4th and so on). Finally, when the last one – the n-th – comes to the school, he changes the status of each n-th door (there's only one such door, though). You need to count how many doors are left opened after all the students have come. Example: Here you can see red squares – closed doors, green – opened ones. Input: n – the number of doors and students, n ∈ N, n ∈ [1, 100000] Output: o – the number of opened doors, o ∈ N doors(5) Should return 2 */ function doors(n){ return ~~Math.sqrt(n) } ================================================ FILE: Dragon's Curve.js ================================================ /* Description: The dragon's curve is a self-similar fractal which can be obtained by a recursive method. Starting with the string D0 = 'Fa', at each step simultaneously perform the following operations: replace 'a' with: 'aRbFR' replace 'b' with: 'LFaLb' For example (spaces added for more visibility) : 1st iteration: Fa -> F aRbF R 2nd iteration: FaRbFR -> F aRbFR R LFaLb FR After n iteration, remove 'a' and 'b'. You will have a string with 'R','L', and 'F'. This is a set of instruction. Starting at the origin of a grid looking in the (0,1) direction, 'F' means a step forward, 'L' and 'R' mean respectively turn left and right. After executing all instructions, the trajectory will give a beautifull self-replicating pattern called 'Dragon Curve' The goal of this kata is to code a function wich takes one parameter n, the number of iterations needed and return the string of instruction as defined above. For example: n=0, should return: 'F' n=1, should return: 'FRFR' n=2, should return: 'FRFRRLFLFR' n should be a number and non-negative integer. All other case should return the empty string: ''. */ Dragon = function(n) { if (parseInt(n)!==n||n<0) return '' let str='Fa' for (let i=0;iv==='a'?'aRbFR':v==='b'?'LFaLb':v) } return str.replace(/[ab]/g,'') } ================================================ FILE: Drunk friend.js ================================================ /* Description: You're hanging out with your friends in a bar, when suddenly one of them is so drunk, that he can't speak, and when he wants to say something, he writes it down on a paper. However, none of the words he writes make sense to you. He wants to help you, so he points at a beer and writes "yvvi". You start to understand what he's trying to say, and you write a script, that decodes his words. Keep in mind that numbers, as well as other characters, can be part of the input, and you should keep them like they are. You should also test if the input is a string. If it is not, return "Input is not a string". */ function decode(str) { if (typeof str !=='string') return 'Input is not a string' return str.replace(/[a-zA-Z]/g,v=>{ const dict1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' const dict2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split``.reverse().join`` return dict2[dict1.indexOf(v)] }) } ================================================ FILE: Dubstep ================================================ /* Description: 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 songDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB") // => WE ARE THE CHAMPIONS MY FRIEND */ function songDecoder(song){ return song.replace(/(WUB)+/gi,' ').trim() } ================================================ FILE: Duplicate Arguments ================================================ /* Description: Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function. The solution should implement the most optimal algorithm possible. The array values passed in will only be strings or numbers. The only valid return values are true and false. Examples: solution(1, 2, 3) --> false solution(1, 2, 3, 2) --> true solution('1', '2', '3', '2') --> true */ function solution(...arr){ return [...new Set(arr)].length!=arr.length } ================================================ FILE: Duplicate Encoder ================================================ /* Description: 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: 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). */ function duplicateEncode(word){ return word .toLowerCase() .split('') .map( function (v, i, arr) { return arr.indexOf(v) == arr.lastIndexOf(v) ? '(' : ')' }) .join(''); } ================================================ FILE: Ease the StockBroker.js ================================================ /* Description: Clients place orders to a stockbroker as strings. The order can be simple or multiple. Type of a simple order: Quote/white-space/Quantity/white-space/Price/white-space/Status where Quote is formed of non-whitespace character, Quantity is an int, Price a double (with mandatory decimal point "." ), Status is represented by the letter B (buy) or the letter S (sell). Example: "GOOG 300 542.0 B" A multiple order is the concatenation of simple orders with a comma between each. Example: "ZNGA 1300 2.66 B, CLH15.NYM 50 56.32 B, OWW 1000 11.623 B, OGG 20 580.1 B" or (C) "ZNGA 1300 2.66 B,CLH15.NYM 50 56.32 B,OWW 1000 11.623 B,OGG 20 580.1 B" To ease the stockbroker your task is to produce a string of type "Buy: b Sell: s" where b and s are 'double' formatted with no decimal, b representing the total price of bought stocks and s the total price of sold stocks. Example: "Buy: 294990 Sell: 0" Unfortunately sometimes clients make mistakes. When you find mistakes in orders, you must pinpoint these badly formed orders and produce a string of type: "Buy: b Sell: s; Badly formed nb: badly-formed 1st simple order ;badly-formed nth simple order ;" where nb is the number of badly formed simple orders, b representing the total price of bought stocks with correct simple order and s the total price of sold stocks with correct simple order. Examples: "Buy: 263 Sell: 11802; Badly formed 2: CLH16.NYM 50 56 S ;OWW 1000 11 S ;" "Buy: 100 Sell: 56041; Badly formed 1: ZNGA 1300 2.66 ;" Notes: Due to Codewars whitespace differences will not always show up in test results. With Golang use a format with "%.0f" for "Buy" and "Sell". */ function balanceStatements(list){ let arr = list.split`,`.filter(v=>/^.+ \d+ \d*\.\d+ \w$/.test(v.trim())).map(v=>v.trim()) let filtred = list.split`,`.filter(v=>!/^.+ \d+ \d*\.\d+ \w$/.test(v)) let b = Math.round(arr.filter(v=>/^.+ \d+ \d*\.\d+\ B$/.test(v)).reduce((a,b)=>{ b=b.split` `; return a+(b[1]*b[2]) },0)) let s = Math.round(arr.filter(v=>/^.+ \d+ \d*\.\d+ S$/.test(v)).reduce((a,b)=>{ b=b.split` `; return a+(b[1]*b[2]) },0)) filtred=filtred.filter(v=>v).map(v=>v.trim()) return `Buy: ${b} Sell: ${s}${filtred.length>0?`; Badly formed ${filtred.length}: ${filtred.join` ;`} ;`:''}` } ================================================ FILE: Easter egg list in ReactJS.js ================================================ /* Description: You decide to create a simple list of your favourite Easter eggs in React. Challenge Learn about nesting and listing React components. The component EggList will set a prop called eggs which is an array of your favourite easter eggs e.g. "Lindt". Loop through the props.eggs to output a unorder list of Easter eggs. Each list item should be a component called EasterEgg with a prop name, to render the name in a li tag. Each EasterEgg will need a key prop with a unique id. Use the index of the array for now. About keys in React lists While you can use the index of the array for a key because they should be unique among their siblings. However it is better to use unique values. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity */ const React = require('react'); const EggList = ({eggs}) => { return
    {eggs.map((v, i) => )}
; }; const EasterEgg = ({name,key}) => { return
  • {name}
  • ; }; ================================================ FILE: Easy Balance Checking.js ================================================ /* Description: You are given a (small) check book as a - sometimes - cluttered (by non-alphanumeric characters) string: "1000.00 125 Market 125.45 126 Hardware 34.95 127 Video 7.45 128 Book 14.32 129 Gasoline 16.10" The first line shows the original balance. Each other line (when not blank) gives information: check number, category, check amount. First you have to clean the lines keeping only letters, digits, dots and spaces. Then return a report as a string (underscores show spaces -- don't put them in your solution. They are there so you can see them and how many of them you need to have): "Original_Balance:_1000.00 125_Market_125.45_Balance_874.55 126_Hardware_34.95_Balance_839.60 127_Video_7.45_Balance_832.15 128_Book_14.32_Balance_817.83 129_Gasoline_16.10_Balance_801.73 Total_expense__198.27 Average_expense__39.65" On each line of the report you have to add the new balance and then in the last two lines the total expense and the average expense. So as not to have a too long result string we don't ask for a properly formatted result. Notes It may happen that one (or more) line(s) is (are) blank. Round to 2 decimals your results. The line separator of results may depend on the language \n or \r\n. See examples in the "Sample tests". */ function balance(book) { book=book.replace(/[^\s\.0-9a-zA-Z]/g,'').split`\n`.filter(v=>v) book[0]=(book[0]*1).toFixed(2) let balance = book.map(v=>v.match(/\d+\.\d+/).join``) let newBalance = []; let originalBalance=balance[0] for (let i=1;ia+b*1,0)/(balance.length-1)).toFixed(2) let phrase=book.slice(1).map((v,i)=>v.replace(/\d+\.\d+/,v=>(v*1).toFixed(2))+` Balance ${newBalance[i]}`) return [`Original Balance: ${(balance[0]*1).toFixed(2)}`,...phrase,`Total expense ${totalExpenses}`,`Average expense ${averageExpenses}`].join`\r\n` } ================================================ FILE: Easy Diagonal.js ================================================ /* Description: In the drawing below we have a part of the Pascal's triangle, lines are numbered from zero (top). The left diagonal in pale blue with only numbers equal to 1 is diagonal zero, then in dark green (1, 2, 3, 4, 5, 6, 7) is diagonal 1, then in pale green (1, 3, 6, 10, 15, 21) is diagonal 2 and so on. We want to calculate the sum of the binomial coefficients on a given diagonal. The sum on diagonal 0 is 8 (we'll write it S(7, 0), 7 is the number of the line where we start, 0 is the number of the diagonal). In the same way S(7, 1) is 28, S(7, 2) is 56. Can you write a program which calculate S(n, p) where n is the line where we start and p is the number of the diagonal? The function will take n and p (with: n >= p >= 0) as parameters and will return the sum. ##Examples: diagonal(20, 3) => 5985 diagonal(20, 4) => 20349 ##Hint: When following a diagonal from top to bottom have a look at the numbers on the diagonal at its right. ##Ref: http://mathworld.wolfram.com/BinomialCoefficient.html */ function diagonal(n, p) { let fac = n => (n === 0) ? 1 : n * fac(n - 1); return Math.round(fac(n + 1) / (fac(n - p) * fac(p + 1))); } ================================================ FILE: Emotional Sort ( ︶︿︶).js ================================================ /* Description: Emotional Sort ( ︶︿︶) You'll have a function called "sortEmotions" that will return an array of emotions sorted. It has two parameters, the first parameter called "arr" will expect an array of emotions where an emotion will be one of the following: :D -> Super Happy :) -> Happy :| -> Normal :( -> Sad T_T -> Super Sad Example of the array:[ 'T_T', ':D', ':|', ':)', ':(' ] And the second parameter is called "order", if this parameter is true then the order of the emotions will be descending (from Super Happy to Super Sad) if it's false then it will be ascending (from Super Sad to Super Happy) Example if order is true with the above array: [ ':D', ':)', ':|', ':(', 'T_T' ] Super Happy -> Happy -> Normal -> Sad -> Super Sad If order is false: [ 'T_T', ':(', ':|', ':)', ':D' ] Super Sad -> Sad -> Normal -> Happy -> Super Happy Example: arr = [':D', ':|', ':)', ':(', ':D'] sortEmotions(arr, true) // [ ':D', ':D', ':)', ':|', ':(' ] sortEmotions(arr, false) // [ ':(', ':|', ':)', ':D', ':D' ] More in test cases! Notes: The array could be empty, in that case return the same empty array ¯\_( ツ )_/¯ All emotions will be valid Enjoy! (づ。◕‿‿◕。)づ */ function sortEmotions(arr, order){ let s = [ ':D', ':)', ':|', ':(', 'T_T' ] if (order){ return arr.sort((a,b)=>s.indexOf(a)-s.indexOf(b)) } return arr.sort((a,b)=>s.indexOf(b)-s.indexOf(a)) } ================================================ FILE: Encrypt this!.js ================================================ /* Description: Acknowledgments: I thank yvonne-liu for the idea and for the example tests :) Description: Encrypt this! You want to create secret messages which can be deciphered by the Decipher this! kata. Here are the conditions: Your message is a string containing space separated words. You need to encrypt each word in the message using the following rules: The first letter needs to be converted to its ASCII code. The second letter needs to be switched with the last letter Keepin' it simple: There are no special characters in input. Examples: encryptThis("Hello") === "72olle" encryptThis("good") === "103doo" encryptThis("hello world") === "104olle 119drlo" */ var encryptThis = function(str) { if(str === '') {return ''; }else { let s = str.split(' '); let x = s.map(element => { let a = element.split(''); a[0] = element.charCodeAt(0); [a[1], a[a.length - 1]] = [a[a.length - 1], a[1]]; return a.join('');}); return x.join(' '); } } ================================================ FILE: English beggars.js ================================================ /* Description: Born a misinterpretation of this kata, your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, from the first to the last. For example: [1,2,3,4,5] for 2 beggars will return a result of [9,6], as the first one takes [1,3,5], the second collects [2,4]. The same array with 3 beggars would have in turn have produced a better out come for the second beggar: [5,7,3], as they will respectively take [1,4], [2,5] and [3]. Also note that not all beggars have to take the same amount of "offers", meaning that the length of the array is not necessarily a multiple of n; length can be even shorter, in which case the last beggers will of course take nothing (0). Note: in case you don't get why this kata is about English beggars, then you are not familiar on how religiously queues are taken in the kingdom ;) */ function beggars(values, n){ let arr = []; for(let i = 1; i <= n; i++) { arr[i-1] = 0; for(let j = i-1; j < values.length;) { arr[i-1] += values[j]; j = j + n; } } return arr; } ================================================ FILE: Enigeliisohe too Eniigeeliiisoohee Toroanisoliatooro.js ================================================ /* Description: Create an English to Enigeliisohe Translator, which after each consonant or semivowel inserts in lower case form the last vowel which precedes it in the alphabet. Trivia: Enigeliisohe is a language based on written English, and Esper' phonetics, in which each letter in written English is converted to the Esperanto name of that letter. Most of the Esper' consonants are pronounced the same as in English, but since there are exceptions, here are some key examples how certain Esper' letter names are pronounced... "a" is named "a", and it's name is pronounced like the "a" in "father". "c" is named "ca", and it's name is pronounced like the "sha" in "shaman". "e" is named "e", and it's name is pronounced like the "e" in "egg". "g" is named "ge", and it's name is pronounced like the "ge" in "get". "h" is named "he", and it's name is pronounced like the "he" in "help". "i" is named "i", and it's name is pronounced like the "i" in "it". "j" is named "ji", and it's name is pronounced as some people pronounce the "si" in "vision". In other words, like the "zh'i" in "vizh'in". "o" is named "o", and it's name is pronounced like the "o" in "both". "q" is named "qo", and it's name is pronounced like the "ch" in the Scottish word "loche", followed by the sound of "o" in "both". In English, one might spell such a name "kho", or "qho", to give a better idea of how it's pronounced. "u" is named "u", and it's name is pronounced like the "oo" in "hook" or "book" or "took". "x" is named "xu", and it's name is pronounced like the "thoo" in "thook". Accented letters are unsupported, and therefore letters with diacritic marks, if encountered, should remain unchanged and not get a vowel attached to them. Extra challenge: Try reading some Enigeliisohe out loud, once you have finished programming your translator. :) */ var toexuto = function(text) { const dict = {x:'u',q:'o',k:'i',z:'u',w:'u',p:'o',v:'u',m:'i',l:'i',t:'o',b:'a',g:'e',s:'o',y:'u',n:'i',h:'e',d:'a',r:'o',f:'e',c:'a',j:'i'} return text.replace(/./g,v=>{ if (dict[v.toLowerCase()]){ return v+dict[v.toLowerCase()] } return v }) }; ================================================ FILE: Equal Sides Of An Array ================================================ /* Description: You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. For example: Let's say you are given the array {1,2,3,4,3,2,1}: Your function will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6. Let's look at another one. You are given the array {1,100,50,-51,1,1}: Your function will return the index 1, because at the 1st position of the array, the sum of left side of the index ({1}) and the sum of the right side of the index ({50,-51,1,1}) both equal 1. Last one: You are given the array {20,10,-80,10,10,15,35} At index 0 the left side is {} The right side is {10,-80,10,10,15,35} They both are equal to 0 when added. (Empty arrays are equal to 0 in this problem) Index 0 is the place where the left side and right side are equal. Note: Please remember that in most programming/scripting languages the index of an array starts at 0. Input: An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative. Output: The lowest index N where the side to the left of N is equal to the side to the right of N. If you do not find an index that fits these rules, then you will return -1. Note: If you are given an array with multiple answers, return the lowest correct index. An empty array should be treated like a 0 in this problem. */ function findEvenIndex(arr) { for(var i=1; i a+b) === arr.slice(i+1).reduce((a, b) => a+b)) { return i; } } return -1; } ================================================ FILE: Errors : histogram.js ================================================ /* Description: In a factory a printer prints labels for boxes. The printer uses colors which, for the sake of simplicity, are named with letters from a to z (except letters u, w, x or z that are for errors). The colors used by the printer are recorded in a control string. For example a control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a... and so on. Sometimes there are problems: lack of colors, technical malfunction and a control string is produced e.g. uuaaaxbbbbyyhwawiwjjjwwxym where errors are reported with letters u, w, x or z. You have to write a function hist which given a string will output the errors as a string representing a histogram of the encountered errors. Format of the output string: letter (error letters are sorted in alphabetical order) in a field of 2 characters, a white space, number of error for that letter in a field of 6, as many "*" as the number of errors for that letter and "\r". The string has a length greater or equal to one and contains only letters from a to z. Examples s="uuaaaxbbbbyyhwawiwjjjwwxym" hist(s) => "u 2 **\rw 5 *****\rx 2 **" or with dots to see white spaces: hist(s) => "u..2.....**\rw..5.....*****\rx..2.....**" s="uuaaaxbbbbyyhwawiwjjjwwxymzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" hist(s) => "u..2.....**\rw..5.....*****\rx..2.....**\rz..31....*******************************" or printed: u 2 ** w 5 ***** x 2 ** z 31 ******************************* Notes Unfortunately most often Codewars compresses all white spaces into one. You can see another examples in the "Sample tests". Translators are welcome for all languages. FUNDAMENTALSSTRINGS */ function hist(s) { const u = s.match(/u/g); const w = s.match(/w/g); const x = s.match(/x/g); const z = s.match(/z/g); const results = []; if (u) results.push(`u ${u.length} ${'*'.repeat(u.length)}`); if (w) results.push(`w ${w.length} ${'*'.repeat(w.length)}`); if (x) results.push(`x ${x.length} ${'*'.repeat(x.length)}`); if (z) results.push(`z ${z.length} ${'*'.repeat(z.length)}`); return results.join(`\r`); } ================================================ FILE: Escape HTML Markup.js ================================================ /* Description: Create a function, which escapes all HTML markup of a given string. Replacing entities of special characters is not needed. Examples say more than words: var strEscaped = escapeHTML('

    Lorem ipsum dolor sit amet.

    '); // <p>Lorem ipsum dolor sit amet</p> var strEscaped = escapeHTML('This text has bold markup.'); // This text has <strong>bold</strong> markup. Watch carefully all test fixtures. If you pass all four of them, you have solved it. :-] If you need a good online regular expression tester: http://regex101.com/#javascript */ var escapeHTML = function(str) { return str.replace(//g,'>').replace(/"/g,'"') }; ================================================ FILE: Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck).js ================================================ /* Description: For the rest of this Kata, I would recommend considering "fuck" to be non-profane. Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck) About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by @donaldsebleung which all shared a similar format and were all somewhat inter-related. Under the influence of a fellow Codewarrior, these three high-level inter-related Kata gradually evolved into what is known today as the "Esolang Interpreters" series. This series is a high-level Kata Series designed to challenge the minds of bright and daring programmers by implementing interpreters for various esoteric programming languages/Esolangs, mainly Brainfuck derivatives but not limited to them, given a certain specification for a certain Esolang. Perhaps the only exception to this rule is the very first Kata in this Series which is intended as an introduction/taster to the world of esoteric programming languages and writing interpreters for them. What is an esoteric programming language? An esoteric programming language, otherwise known as an Esolang, is an informal computer programming language that is generally not designed for serious practical use. There are a few main aims/themes among the vast majority of such languages: Achieve Turing-completeness in as few commands (instructions) as possible. There are currently a number of implemented Esolangs that have been proven to be Turing-complete, Brainfuck being the most popular of them all, comprised of no more than 8 distinct commands. Despite having only 8 commands, it has been objectively proven to be Turing-complete. However, Brainfuck is not the Turing-complete programming language with the fewest commands. Boolfuck, a derivative of Brainfuck which operates on bits (0s and 1s) and contains 7 commands only, has also been proven to be Turing-complete through reduction from Brainfuck. Another less-known Esolang called Etre contains as few as 3 commands yet has been proven to be Turing-complete through the translation of a Minsky Machine to Etre. To be as hard to program in as possible. The famous Brainfuck Esolang is well known as a Turing tarpit - that is, a Turing-complete programming language where it is very hard to write a useful program in reality. However, Brainfuck is most definitely not the hardest Esolang to program in. For example, its close cousin, Boolfuck, which operates on bits (mentioned above) is even harder to program in. There have also been a small number of implemented Esolangs which are so difficult to program in that no one has ever successfully written a single program in it from scratch - the only programs generated from these languages came from computers! As a joke. Many Esolangs out there have been invented solely as a joke. Examples include Ook! and Bitxtreme. Although there is no clear-cut definition as to when a programming language is esoteric (or not), Esolangs can generally be identified by the following features/traits: Minimalistic - having as few instructions as possible Plays with new concepts - for example, Befunge, another very popular Esolang, is interpreted in two dimensions as opposed to the usual linear way of interpreting code Themed - this is a trait of many joke Esolangs. For example, some may be fashioned like Shakespearean plays and others like cooking recipes Not clearly documented - Many Esolangs out there have not been described in great detail with perhaps only a few code examples on the entire Internet. Some Esolangs have not even been implemented yet! Contain incomplete specs - New Esolangs are being invented every day. Some Esolangs on the Internet are still a work-in-progress and their commands and behaviour have not been finalised yet. Nevertheless, Esolangs are generally fun to program in, experiment with and write interpreters for. A great deal can be learned about certain concepts and theories in Computer Science just by studying and programming in a well-designed Esolang such as Brainfuck or Befunge. Next off, I will introduce you to a simple, minimalistic Esolang called MiniStringFuck. The Language MiniStringFuck is a derivative of the famous Brainfuck which contains a memory cell as its only form of data storage as opposed to a memory tape of 30,000 cells in Brainfuck. The memory cell in MiniStringFuck initially starts at 0. MiniStringFuck contains only 2 commands as opposed to 8: + - Increment the memory cell. If it reaches 256, wrap to 0. . - Output the ASCII value of the memory cell For example, here is a MiniStringFuck program that outputs the string "Hello, World!": ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. And here is another program that prints the uppercase English alphabet: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+.+. Any characters in a MiniStringFuck program other than + or . are simply non-command characters (no-ops, i.e. do nothing) and therefore can serve as comments in the program. The Task Time to write your first Esolang interpreter :D Your task is to implement a MiniStringFuck interpreter myFirstInterpreter()/my_first_interpreter()/Interpreter()/interpret() (depending on your language) which accepts exactly 1 required argument code/$code which is the MiniStringFuck program to be executed. The output of the program should then be returned by your interpreter as a string. Since this is the first time you are about to write an interpreter for an Esolang, here are a few quick tips: If you are afraid that your interpreter will be confused by non-command characters appearing in the MiniStringFuck program, you can try to remove all non-command characters from the code input before letting your interpreter interpret it The memory cell in MiniStringFuck only ever contains a single integer value - think of how it can be modelled in your interpreter If you are stuck as to how to interpret the string as a program, try thinking of strings as an array of characters. Try looping through the "program" like you would an array Writing an interpreter for an Esolang can sometimes be quite confusing! It never hurts to add a few comments in your interpreter as you implement it to remind yourself of what is happening within the interpreter at every stage NOTE: If you would not like to name your interpreter as myFirstInterpreter()/my_first_interpreter(), you can optionally rename it to either miniStringFuck()/mini_string_fuck() or interpreter() instead - the test cases will handle the rest for you. Not available in Java, Go, Swift, TypeScript, Haskell, Elixir, C++, C#, Rust, R, Erlang, F# and NASM; irrelevant to Brainfuck solvers ;) Good luck :D Kata in this Series Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck) Esolang Interpreters #2 - Custom Smallfuck Interpreter Esolang Interpreters #3 - Custom Paintfuck Interpreter Esolang Interpreters #4 - Boolfuck Interpreter */ function myFirstInterpreter(code) { let out = "", byte = 0; [...code].forEach( cmd => { switch(cmd){ case "+" : byte = (byte+1)%256; break; case "." : out += String.fromCharCode(byte); break; }} ) return out } ================================================ FILE: Esolang: MiniBitMove.js ================================================ /* Description: Task: This kata asks you to make a custom esolang interpreter for the language [MiniBitMove](http://esolangs.org/wiki/MiniBitMove). MiniBitMove has only two commands and operates on a array of bits. It works like this: 1: Flip the bit at the current cell 0: Move selector by 1 It takes two inputs, the program and the bits in needs to operate on. The program returns the modified bits. The program stops when selector reaches the end of the array. Otherwise the program repeats itself. Note: This means that if a program does not have any zeros it is an infinite loop Example of a program that flips all bits in an array: Code: 10 Bits: 11001001001010 Result: 00110110110101 After you're done, feel free to make translations and discuss this kata. */ function interpreter(tape, array) { array=array.split`` for (let i=0;iv==='0'?'1':'0') if (tape[j]==='0'){ i++ } if (array[i]===undefined) break } } return array.join`` } ================================================ FILE: Esolang: Tick.js ================================================ /* Description: Task Make a custom esolang interpreter for the language Tick. Tick is a descendant of Ticker but also very different data and command-wise. Syntax/Info Commands are given in character format. Non-command characters should be ignored. Tick has an potentially infinite memory as opposed to Ticker(which you have a special command to add a new cell) and only has 4 commands(as opposed to 7). Read about this esolang here. Commands >: Move data selector right <: Move data selector left(infinite in both directions) +: Increment memory cell by 1. 255+1=0 *: Add ascii value of memory cell to the output tape. Examples Hello world! '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*<<*>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*<<<<*>>>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++*' */ function interpreter(tape) { let dict = {} let str = [] let num = 0; let selector=0; for (let i=0;i') selector++ else if (tape[i]==='<') selector-- else if (tape[i]==='*') { str += String.fromCharCode(dict[selector]%256)} } return str } ================================================ FILE: Even Fibonacci Sum.js ================================================ /* Description: Give the summation of all even numbers in a Fibonacci sequence up to, but not including, the maximum value. The Fibonacci sequence is a series of numbers where the next value is the addition of the previous two values. The series starts with 0 and 1: 0 1 1 2 3 5 8 13 21... For example: fibonacci(0)==0 fibonacci(33)==10 fibonacci(25997544)==19544084 */ function fibonacci(max) { let fib = [0,1] for (let i=1;fib[i-1]+fib[i]a+(b%2==0?b:0),0) } ================================================ FILE: Evil Autocorrect Prank.js ================================================ /* Description: Your friend won't stop texting his girlfriend. It's all he does. All day. Seriously. The texts are so mushy too! The whole situation just makes you feel ill. Being the wonderful friend that you are, you hatch an evil plot. While he's sleeping, you take his phone and change the autocorrect options so that every time he types "you" or "u" it gets changed to "your sister." Write a function called autocorrect that takes a string and replaces all instances of "you" or "u" (not case sensitive) with "your sister" (always lower case). Return the resulting string. Here's the slightly tricky part: These are text messages, so there are different forms of "you" and "u". For the purposes of this kata, here's what you need to support: "youuuuu" with any number of u characters tacked onto the end "u" at the beginning, middle, or end of a string, but NOT part of a word "you" but NOT as part of another word like youtube or bayou */ function autocorrect(input){ return input.replace(/\b(you+|u)\b/gi, "your sister"); } ================================================ FILE: Exclamation marks series #17: Put the exclamation marks and question marks to the balance, Are they balanced?.js ================================================ /* Description: Each exclamation mark weight is 2; Each question mark weight is 3. Put two string left and right to the balance, Are they balanced? If the left side is more heavy, return "Left"; If the right side is more heavy, return "Right"; If they are balanced, return "Balance". Examples balance("!!","??") === "Right" balance("!??","?!!") === "Left" balance("!?!!","?!?") === "Left" balance("!!???!????","??!!?!!!!!!!") === "Balance" Note Please don't post issue about difficulty or duplicate. */ function balance(left,right){ let l=left.split('').map(v=>v==='!'?v=2:v=3).reduce((a,b)=>a+b,0); let r=right.split('').map(v=>v==='!'?v=2:v=3).reduce((a,b)=>a+b,0); return l>r?'Left':l===r?"Balance":'Right'; } ================================================ FILE: Exercise in Summing.js ================================================ /* Description: Your task is to finish two functions, minimumSum and maximumSum, that take 2 parameters: values: an array of integers with an arbitrary length; may be positive and negative n: how many integers should be summed; always 0 or bigger Example: var values = [5, 4, 3, 2, 1]; minimumSum(values, 2); // should return 1+2 = 3 maximumSum(values, 3); // should return 3+4+5 = 12 All values given to the functions will be integers. Also take care of the following special cases: if values is empty, both functions should return 0 if n is 0, both functions should also return 0 if n is larger than values's length, use the length instead. */ function minimumSum(values, n) { values=values.sort((a,b)=>a-b); return values.slice(0,n).reduce((a,b)=>a+b,0) } function maximumSum(values, n) { values=values.sort((a,b)=>b-a); return values.slice(0,n).reduce((a,b)=>a+b,0) } ================================================ FILE: Extract Nested Object Reference.js ================================================ /* Description: You are given a complex object that has many deeply nested variables. You don't want to go the usual if obj.property == null route. Create a prototype method that given a nested path, either return the value or undefined. var obj = { person: { name: 'joe', history: { hometown: 'bratislava', bio: { funFact: 'I like fishing.' } } } }; obj.hash('person.name'); // 'joe' obj.hash('person.history.bio'); // { funFact: 'I like fishing.' } obj.hash('person.history.homeStreet'); // undefined obj.hash('person.animal.pet.needNoseAntEater'); // undefined */ Object.prototype.hash = function(string) { try { return eval(`this.${string}`) } catch(e){ return undefined } } ================================================ FILE: Extract last names of people named Michael.js ================================================ /* Description: Given a text, for example: const inputText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?"; get an array of last names of people named Michael. The result should be: ["Jordan", "Johnson", "Green", "Wood"] Notes: First name will always be Michael with upper case 'M'. There will always be a space character between 'Michael' and last name. Last name will always be one word, starting with an upper-case letter and continuing with lower-case letters. There will always be at least one 'Micheal' with a valid last name in the input text. */ function getMichaelLastName(s) { return s.match(/(Michael [A-Z]\w+\b)/g).map(v=>v.split` `[1]) } ================================================ FILE: Extract the IDs from the data set.js ================================================ /* Description: Complete the method so that it returns an array of all ID's passed in. The data structure will be similar to the following: var data = { id: 1, items: [ {id: 2}, {id: 3, items: [ {id: 4}, {id: 5} ]} ] } extractIds(data) // should return [1,2,3,4,5] The method should be able to handle the case of empty data being passed in. Note: The only arrays that need to be traversed are those assigned to the "items" property. */ function extractIds(data){ return [].concat(...Object.keys(data).map(function(item) { return item === 'id' ? data[item] : extractIds(data[item]); })) } ================================================ FILE: FIXME: Hello.js ================================================ /* Description: The code provided has a method hello which is supposed to show only those attributes which have been explicitly set. Furthermore, it is supposed to say them in the same order they were set. But it's not working properly. Notes There are 3 attributes name age sex ('M' or 'F') When the same attribute is assigned multiple times the hello method shows it only once. If this happens the order depends on the first assignment of that attribute, but the value is from the last assignment. Examples Hello. Hello. My name is Bob. I am 27. I am male. Hello. I am 27. I am male. My name is Bob. Hello. My name is Alice. I am female. Hello. My name is Batman. Task Fix the code so we can all go home early. */ class Dinglemouse { constructor() { this.age=true this.name=true this.sex=true this.agePos=0 this.namePos=0 this.sexPos=0 this.arr=[] } setAge(age) { if (this.age){ this.age=false this.agePos=this.arr.length this.arr[this.agePos]=` I am ${age}.` } else { this.arr[this.agePos]=` I am ${age}.` } return this } setSex(sex) { if (this.sex){ this.sex=false this.sexPos=this.arr.length this.arr[this.sexPos]=` I am ${sex == 'M' ? "male" : "female"}.` } else { this.arr[this.sexPos]=` I am ${sex == 'M' ? "male" : "female"}.` } return this } setName(name) { if (this.name){ this.name=false this.namePos=this.arr.length this.arr[this.namePos]=` My name is ${name}.` } else { this.arr[this.namePos]=` My name is ${name}.` } return this } hello() { return `Hello.${this.arr.join``}` } } ================================================ FILE: Factorial length.js ================================================ /* Description: In this Kata, you will implement a function count that takes an integer and returns the number of digits in factorial(n). For example, count(5) = 3, because 5! = 120, and 120 has 3 digits. More examples in the test cases. Brute force is not possible. A little research will go a long way, as this is a well known series. Good luck! */ function count(n) { return Math.ceil(Math.log10(2*Math.PI*n)/2 + n*Math.log10(n/Math.E)) }; ================================================ FILE: Faro Shuffle Count.js ================================================ /* Description: A faro shuffle of a deck of playing cards is a shuffle in which the deck is split exactly in half and then the cards in the two halves are perfectly interwoven, such that the original bottom card is still on the bottom and the original top card is still on top. For example, faro shuffling the list ['ace', 'two', 'three', 'four', 'five', 'six'] gives ['ace', 'four', 'two', 'five', 'three', 'six' ] If 8 perfect faro shuffles are performed on a deck of 52 playing cards, the deck is restored to its original order. Write a function that inputs an integer n and returns an integer representing the number of faro shuffles it takes to restore a deck of n cards to its original order. Assume n is an even number between 2 and 2000. */ function faroCount(deckSize){ let shuffles = 0, term = 1; do { shuffles++; term = (deckSize * (term % 2) + term) / 2 | 0; } while (term !== 1) return shuffles; } ================================================ FILE: Fat Fingers.js ================================================ /* Description: Freddy has a really fat left pinky finger, and every time Freddy tries to type an A, he accidentally hits the CapsLock key! Given a string that Freddy wants to type, emulate the keyboard misses where each A supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It doesn't matter if the A in the string is capitalized or not. When CapsLock is enabled, capitalization is reversed, but punctuation is not affected. Examples: "The quick brown fox jumps over the lazy dog." -> "The quick brown fox jumps over the lZY DOG." "The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness." -> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS." "aAaaaaAaaaAAaAa" -> "" If the given string is null, return null. If the given string is "", the answer should be evident. Happy coding! (Adapted from https://codegolf.stackexchange.com/questions/158132/no-a-just-caps-lock) */ var fatFingers = function(str) { if(typeof str !== 'string') return str; return str.replace(/A/g,'a').split('a').map((s,i)=>i%2?s.replace(/./g,m=>/[a-z]/.test(m)?m.toUpperCase():m.toLowerCase()):s).join`` }; ================================================ FILE: Feynman's square question.js ================================================ /* Description: 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 function countSquares(n){ … } that solves Feynman's question in general. The input to your function will always be a positive integer. #Examples countSquares(1) = 1 countSquares(2) = 5 countSquares(3) = 14 (Adapted from the Sphere Online Judge problem SAMER08F by Diego Satoba) */ function countSquares(n){ let num=0; for (let i =0;i<=n;i++){ num+=(n - i)**2 } return num } ================================================ FILE: Fibonacci Reloaded.js ================================================ /* Description: And here is Fibonacci again. This time we want to go one step further. Our fib() function must be faster! Can you do it? In case you don't know, what the Fibonacci number is: The nth Fibonacci number is defined by the sum of the two previous Fibonacci numbers. In our case: fib(1) == 0 and fib(2) == 1. With these initial values you should be able to calculate each following Fibonacci number. Examples: fib(1) // === 0 fib(2) // === 1 fib(3) // === 1 fib(4) // === 2 fib(5) // === 3 */ function fib(n) { let arr = [0,1] for (let i=1;i<=n;i++){ arr.push(arr[i-1]+arr[i]) } return arr[n-1] } ================================================ FILE: Fibonacci, Tribonacci and friends.js ================================================ /* Description: If you have completed the Tribonacci sequence kata, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work. Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well Cinquebonacci would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on. Well, guess what? You have to build a Xbonacci function that takes a signature of X elements - and remember each next element is the sum of the last X elements - and returns the first n elements of the so seeded sequence. xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94} xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16} xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6} xbonacci {1,1} produces the Fibonacci sequence */ function Xbonacci(s,n){ if (s.length>n) return s.slice(0,n); let sum=[...s] for (let i=0;sum.lengtha+b,0))} return sum } ================================================ FILE: File Path Operations.js ================================================ /* Description: Task: This kata requires you to write an object that receives a file path and does operations on it. NOTE FOR PYTHON USERS: You cannot use modules os.path, glob, and re The purpose of this kata is to use string parsing, so you're not supposed to import external libraries. I could only enforce this in python. Testing: Python: >>> master = FileMaster('/Users/person1/Pictures/house.png') >>> master.extension() 'png' >>> master.filename() 'house' >>> master.dirpath() '/Users/person1/Pictures/' Ruby: master = FileMaster.new('/Users/person1/Pictures/house.png') master.extension #--> png master.filename #--> house master.dirpath #--> /Users/person1/Pictures/ C#: FileMaster FM = new FileMaster("/Users/person1/Pictures/house.png"); FM.extension(); // output: "png" FM.filename(); // output: "house" FM.dirpath(); // output: "/Users/person1/Pictures/" JavaScript: const fm = new FileMaster('/Users/person1/Pictures/house.png'); fm.extension(); // output: 'png' fm.filename(); // output: 'house' fm.dirpath(); // output: '/Users/person1/Pictures/' TypeScript: const fm = new FileMaster('/Users/person1/Pictures/house.png'); fm.extension(); // output: 'png' fm.filename(); // output: 'house' fm.dirpath(); // output: '/Users/person1/Pictures/' PHP: $fm = new FileMaster('/Users/person1/Pictures/house.png'); $fm.extension(); // 'png' $fm.filename(); // 'house' $fm.dirpath(); // '/Users/person1/Pictures' Notes: I have other kata that need to be tested. You may find them here and here Please post any questions or suggestion in the discourse section. Thank you! Thank to all users who contributed to this kata! I appreciate your input! */ class FileMaster { constructor(filepath) { this.path=filepath } extension() { return this.path.match(/\.(.+$)/)[1] } filename() { return this.path.match(/\/(\w+)\./)[1] } dirpath() { return this.path.match(/^\/?.+\//) } } ================================================ FILE: Financing Plan on Planet XY140Z-n.js ================================================ /* Description: I need to save some money to buy a gift. I think I can do something like that: First week (W0) I save nothing on Sunday, 1 on Monday, 2 on Tuesday... 6 on Saturday, second week (W1) 2 on Monday... 7 on Saturday and so on according to the table below where the days are numbered from 0 to 6. Can you tell me how much I will have for my gift on Saturday evening after I have saved 12? (Your function finance(6) should return 168 which is the sum of the savings in the table). Imagine now that we live on planet XY140Z-n where the days of the week are numbered from 0 to n (integer n > 0) and where I save from week number 0 to week number n included (in the table below n = 6). How much money would I have at the end of my financing plan on planet XY140Z-n? -- Su Mo Tu We Th Fr Sa W6 12 W5 10 11 W4 8 9 10 W3 6 7 8 9 W2 4 5 6 7 8 W1 2 3 4 5 6 7 W0 0 1 2 3 4 5 6 #Example: finance(5) --> 105 finance(6) --> 168 finance(7) --> 252 finance(5000) --> 62537505000 #Hint: try to avoid nested loops */ function finance(n) { let sum = 0; let current_sum; for (let i = 0; i <= n; i ++){ current_sum= (2 * i + 2 * i + (n - i)) * (n + 1 - i) / 2 sum += current_sum} return sum; } ================================================ FILE: Financing a purchase.js ================================================ /* Description: The description is rather long but it tries to explain what a financing plan is. The fixed monthly payment for a fixed rate mortgage is the amount paid by the borrower every month that ensures that the loan is paid off in full with interest at the end of its term. The monthly payment formula is based on the annuity formula. The monthly payment c depends upon: rate - the monthly interest rate is expressed as a decimal, not a percentage. The monthly rate is simply the given yearly percentage rate divided by 100 and then by 12. term - the number of monthly payments, called the loan's term. principal - the amount borrowed, known as the loan's principal (or balance). First we have to determine c. We have: c = n /d with n = r * balance and d = 1 - (1 + r)**(-term) where ** is the power function (you can look at the reference below). The payment c is composed of two parts. The first part pays the interest (let us call it int) due for the balance of the given month, the second part repays the balance (let us call this part princ) hence for the following month we get a new balance = old balance - princ with c = int + princ. Loans are structured so that the amount of principal returned to the borrower starts out small and increases with each mortgage payment. While the mortgage payments in the first years consist primarily of interest payments, the payments in the final years consist primarily of principal repayment. A mortgage's amortization schedule provides a detailed look at precisely what portion of each mortgage payment is dedicated to each component. In an example of a $100,000, 30-year mortgage with a rate of 6 percents the amortization schedule consists of 360 monthly payments. The partial amortization schedule below shows with 2 decimal floats the balance between principal and interest payments. -- num_payment c princ int Balance -- 1 599.55 99.55 500.00 99900.45 -- ... 599.55 ... ... ... -- 12 599.55 105.16 494.39 98,771.99 -- ... 599.55 ... ... ... -- 360 599.55 596.57 2.98 0.00 Task: Given parameters rate: annual rate as percent (don't forgent to divide by 100*12) bal: original balance (borrowed amount) term: number of monthly payments num_payment: rank of considered month (from 1 to term) the function amort will return a formatted string: "num_payment %d c %.0f princ %.0f int %.0f balance %.0f" (with arguments num_payment, c, princ, int, balance) Examples: amort(6, 100000, 360, 1) -> "num_payment 1 c 600 princ 100 int 500 balance 99900" amort(6, 100000, 360, 12) -> "num_payment 12 c 600 princ 105 int 494 balance 98772" Ref https://en.wikipedia.org/wiki/Mortgage_calculator */ function amort(r, b, t, n) { r/=1200; var c=r*b/(1-(1+r)**(-t)); for(let m=1; ma-b).filter((v,i,arr)=>v===arr[i+1])*1; } ================================================ FILE: Find The Parity Outlier ================================================ /* Description: 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 [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) */ function findOutlier(int){ var even = int.filter(a=>a%2==0); var odd = int.filter(a=>a%2!==0); return even.length==1? even[0] : odd[0]; } ================================================ FILE: Find X.js ================================================ /* Description: Part 2 version Find X Ⅱ We have a function that takes in an integer n, and returns a number x. Lets call this function findX(n)/find_x(n) (depending on your language): function findX(n) { let x = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < 2*n; j++) x += i + j; } return x; } The functions loops throught the number n and at every iteration, performs a nested loop on 2*n, at each iteration of this nested loop it increments x with the (nested loop index + parents loop index). This works well when the numbers are reasonably small. findX(2) //=> 16 findX(3) //=> 63 findX(5) //=> 325 But may be slow for numbers > 103 So your task is to optimize the function findX/find_x, so it works well for large numbers. Input Range 1 <= n <= 106 (105 in JS) Note: This problem is more about logical reasoning than it is about finding a mathematicial formula, infact there are no complex math formula involved */ function findX(n) { return n**2*(3*n-2) } ================================================ FILE: Find heavy ball - level: conqueror.js ================================================ /* Description: There are 8 balls numbered from 0 to 7. Seven of them have the same weight. One is heavier. Your task is to find it's number. Your function findBall will receive single argument - scales object. The scales object contains an internally stored array of 8 elements (indexes 0-7), each having the same value except one, which is greater. It also has a public method named getWeight(left, right) which takes two arrays of indexes and returns -1, 0, or 1 based on the accumulation of the values found at the indexes passed are heavier, equal, or lighter. getWeight returns: -1 if left pan is heavier 1 if right pan is heavier 0 if both pans weight the same Examples of scales.getWeight() usage: scales.getWeight([3], [7]) returns -1 if ball 3 is heavier than ball 7, 1 if ball 7 is heavier, or 0 i these balls have the same weight. scales.getWeight([3, 4], [5, 2]) returns -1 if weight of balls 3 and 4 is heavier than weight of balls 5 and 2 etc. So where's the catch, you may ask. Well - the scales is very old. You can use it only 3 TIMES before the scale breaks. Too easy? Too hard? Try other levels: novice master */ function findBall(scales) { var w = scales.getWeight([0, 1, 2, 3], [4, 5, 6, 7]); if (w < 0) { w = scales.getWeight([0, 1], [2, 3]); if (w < 0) { w = scales.getWeight([0], [1]); return w < 0 ? 0 : 1; } else { w = scales.getWeight([2], [3]); return w < 0 ? 2 : 3; } } else { w = scales.getWeight([4, 5], [6, 7]); if (w < 0) { w = scales.getWeight([4], [5]); return w < 0 ? 4 : 5; } else { w = scales.getWeight([6], [7]); return w < 0 ? 6 : 7; } } return -1; } ================================================ FILE: Find the Mine!.js ================================================ /* Description: 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 0s. 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] */ function mineLocation(f){ let p=0; let p1=0 for (let i=0;i 93, 10 => 55, 15 => 30, 20 => 19, <--- nexus 23 => 11, 30 => 2 } */ function nexus(users) { const obj=Object.keys(users) const obj2=Object.values(users) const arr=obj.map((v,i)=>Math.abs(v*1-obj2[i])) const index=arr.indexOf(Math.min(...arr.map(v=>Math.abs(v)))) return obj[index]*1 } ================================================ FILE: Find the Nth longest string in an Array.js ================================================ /* Description: Implement the function longest(array,n) where you will be given an array of strings and then return the nth longest string in that array. e.g. arr = ['Hello','World','Codewars','Katas'] n = 3; should return 'World' because 'Codewars' length = 8 , 'Hello' length = 5, so that is the 2nd longest word and then 'World' (although also word length of 5, 'World' is after 'Hello' in the array). When words have the same lengths, treat them in the order in which they exist in the array. Array will never be empty and n > 0 always. */ function longest(arr, n) { let check=arr.slice() return arr.sort((a,b)=>b.length-a.length||check.indexOf(a)-check.indexOf(b))[n-1] } ================================================ FILE: Find the missing letter ================================================ /* Description: #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! */ function findMissingLetter(array) { return String.fromCharCode(array.find((c,i)=>array[i+1].charCodeAt()-c.charCodeAt()!==1).charCodeAt()+1) } ================================================ FILE: Find the missing term in an Arithmetic Progression ================================================ /* Description: An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP. Find the missing term. You have to write the function findMissing(list), list will always be at least 3 numbers. The missing term will never be the first or last one. Example findMissing([1, 3, 5, 9, 11]) == 7 ``` PS: This is a sample question of the facebook engineer challenge on interviewstreet. I found it quite fun to solve on paper using math, derive the algo that way. Have fun! */ var findMissing = function (l) { return ((l[0]+l[l.length-1])*(l.length+1))/2-(l.reduce((a,b)=>a+b)) } ================================================ FILE: 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. */ function findOdd(A) { let count = {}; A.forEach(v => { count[v] = count[v] ? count[v] + 1 : 1; }); return +Object.keys(count).find(key => count[key] % 2 === 1); } ================================================ FILE: Find the unique number ================================================ /* Description: There is an array with some numbers. All numbers are equal except for one. Try to find it! findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2 findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55 It’s guaranteed that array contains more than 3 numbers. The tests contain some very huge arrays, so think about performance. This is the first kata in series: Find the unique number (this kata) Find the unique string Find The Unique */ function findUniq(arr) { return +arr.filter( (value) => { return arr.indexOf(value) == arr.lastIndexOf(value) } ); } ================================================ FILE: Find the unique number.js ================================================ /* Description: Write a function called findUnique which returns the only unique number from an array. All numbers in the unsorted array are present twice, except the one you have to find. The numbers are always valid integer values between 1 and 2147483647, so no need for type and error checking. The array contains at least one number and may contain millions of numbers. So make sure your solution is optimized for speed. Example Input: [ 1, 8, 4, 4, 6, 1, 8 ] Expected output: 6 */ function findUnique(numbers) { return numbers.reduce((a, b) => a ^ b); } ================================================ FILE: Find within array.js ================================================ /* Description: Let's make an advanced version of Array.indexOf. We'll create a function that takes in two parameters: an array (length and types of items are irrelevant), and a function (value, index) that will be called on members of the array. The function will return either true or false. Your function will iterate through the members of the array in order until the provided iterator function returns true; at which point your function will return that item's index. If the iterator function returns false for all members of the array, your function should return -1. */ var findInArray = function(array, iterator) { return array.map((v,i)=>iterator(v,i)).indexOf(true) }; ================================================ FILE: FizzBuzz Array! (Custom).js ================================================ /* Description: Write a function that returns an array of numbers from 1 to 100. The function should be able to be called with or without arguments. If no arguments are given, each number in the array divisible by 3 should be replaced with the word 'Fizz', and each number in the array divisible by 5 should be replaced with the word 'Buzz'. If the number is divisble by both 3 and 5, then it should be replaced with 'FizzBuzz'. The function should also be able to take up to 4 arguments. The first and second arguments are strings, which should be 'Fizz' and 'Buzz' by default. The third and fourth arguments are integers and and should be 3 and 5 by default. Example fizzBuzzCustom()[15] // returns 16 fizzBuzzCustom()[44] // returns "FizzBuzz" (45 is divisible by 3 and 5) fizzBuzzCustom('Hey', 'There')[25] // returns 26 fizzBuzzCustom('Hey', 'There')[11] // returns "Hey" (12 is divisible by 3) fizzBuzzCustom("What's ", "up?", 3, 7)[80] // returns "What's " (81 is divisible by 3) */ var fizzBuzzCustom = function(s1='Fizz', s2='Buzz', n1=3, n2=5) { let arr = []; for (let i=1; i <=100; i++){ if (i%n1===0&&i%n2===0){ arr.push(s1+s2)} else if (i%n1===0){ arr.push(s1)} else if (i%n2===0){ arr.push(s2)} else {arr.push(i)} } return arr }; ================================================ FILE: Flexible Card Game.js ================================================ /* Description: Create any card game! Create a Card Game library of classes which could be used to create any number of basic card games. You'll need at least a Deck class and a Card class. Deck functionality A deck has a public attribute: cards: array of remaining cards in the deck. ...and three public methods: count(): count of remaining cards in the deck. shuffle(): randomize the order of the remaining cards in the deck. draw(n): remove the last n cards from the deck and return them in an array. Upon initialization, a deck is filled with 52 cards (13 from each of 4 suits). Card functionality A card has these public attributes: suit: a symbol representing the suit of the card. rank: an integer from 1 to 13. ("ace" is 1, "king" is 13) Javascript: face_card: is this card a face card? (> 10) ...and these methods: Ruby: face_card?: is this card a face card? (> 10) to_s (JS:toString()) : human-readable string representation of the card (e.g. "Ace of Spades", "10 of Clubs", "Queen of Hearts") Cards must be Comparable to other cards. Compare the ranks of the cards only. Since this is a low level layer to build card games above, all test input will be valid. All ranks will be between 1 and 13 and all suits will be one of Ruby: :hearts, :diamonds, :spades, :clubs Javascript: Card.HEARTS, Card.DIAMONDS, Card.CLUBS, Card.SPADES */ function Card(suit, rank) { this.suit = suit this.rank = rank } Card.SUITS = [ Card.CLUBS = 'Clubs', Card.DIAMONDS = 'Diamonds', Card.HEARTS = 'Hearts', Card.SPADES = 'Spades' ] Card.prototype = { get face_card() { return this.rank > 10 }, valueOf: function() { return this.rank }, toString: function() { var rank = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'}[this.rank] || this.rank return rank + ' of ' + this.suit } } function Deck() { this.cards = [] for (var i = 0; i < Card.SUITS.length; i++) { for (var rank = 1; rank <= 13; rank++) { this.cards.push(new Card(Card.SUITS[i], rank)) } } this.shuffle() } Deck.prototype = { count: function() { return this.cards.length }, draw: function(n) { return this.cards.splice(-n, n) }, shuffle: function() { this.cards.sort(function() { return Math.random() - 0.5 }) } }; ================================================ FILE: Floating-point Approximation (I).js ================================================ /* Description: Consider the function f: x -> sqrt(1 + x) - 1 at x = 1e-15. We get: f(x) = 4.44089209850062616e-16 or something around that, depending on the language. This function involves the subtraction of a pair of similar numbers when x is near 0 and the results are significantly erroneous in this region. Using pow instead of sqrt doesn't give better results. A "good" answer is 4.99999999999999875... * 1e-16. Can you modify f(x) to give a good approximation of f(x) in the neigbourhood of 0? Note: Don't round or truncate your results. See the testing function in Sample Tests:. */ function f(x) { return x / (1 + Math.sqrt(1 + x)) } ================================================ FILE: Fold an array.js ================================================ /* Description: #Fold an array In this kata you have to write a method that folds a given array of integers by the middle x-times. An example says more than thousand words: Fold 1-times: [1,2,3,4,5] -> [6,6,3] A little visualization (NOT for the algorithm but for the idea of folding): Step 1 Step 2 Step 3 Step 4 Step5 5/ 5| 5\ 4/ 4| 4\ 1 2 3 4 5 1 2 3/ 1 2 3| 1 2 3\ 6 6 3 ----*---- ----* ----* ----* ----* Fold 2-times: [1,2,3,4,5] -> [9,6] As you see, if the count of numbers is odd, the middle number will stay. Otherwise the fold-point is between the middle-numbers, so all numbers would be added in a way. The array will always contain numbers and will never be null. The parameter runs will always be a positive integer greater than 0 and says how many runs of folding your method has to do. If an array with one element is folded, it stays as the same array. The input array should not be modified! Have fun coding it and please don't forget to vote and rank this kata! :-) I have created other katas. Have a look if you like coding and challenges. */ function foldArray(a, n) { const r = [], c = a.slice(); while (c.length) r.push(c.pop() + (c.shift() || 0)); return n - 1 ? foldArray(r, n - 1) : r; } ================================================ FILE: Follow that Spy.js ================================================ /* Description: We are tracking down our rogue agent Matthew Knight A.K.A. Roy Miller and he travels from places to places to avoid being tracked. Each of his travels are based on a list of itineraries in an unusual or incorrect order. The task is to determine the routes he will take in his every journey. You are given an array of routes of his itineraries. List down only the places where he will go in correct order based on his itineraries. Example: routes = [[USA, BRA], [JPN, PHL], [BRA, UAE], [UAE, JPN]] result: "USA, BRA, UAE, JPN, PHL" note: It is safe to assume that there will be no repeating place with different route and there are no empty routes and could have at least one (1) route (from one waypoint to another). */ function findRoutes(routes) { let str = [].concat(...routes.map(v=>v)) str=str.filter(v=>str.indexOf(v)===str.lastIndexOf(v)) let index = 0 for (let i=0;iv>1).length countB=B.filter(v=>v>1).length if (11-countA===6||11-countB===6){ return [11-countA,11-countB] } } return [11-countA,11-countB] } ================================================ FILE: Format Text.js ================================================ /* Description: Write a function format that takes two arguments, text and width, and formats the text to fit the width. Your function should divide the given text into lines using newline characters. It should fit as many words into each line as possible without exceeding the given width or splitting any words between two lines. There should not be a space at the beginning or end of any line. For example, here is some text formatted with a width of 50: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam nec consectetur risus. Cras vel urna a tellus dapibus consequat. Duis bibendum tincidunt viverra. Phasellus dictum efficitur sem quis porttitor. Mauris luctus auctor diam id ultrices. Praesent laoreet in enim ut placerat. Praesent a facilisis turpis. And the same text formatted with a width of 30: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam nec consectetur risus. Cras vel urna a tellus dapibus consequat. Duis bibendum tincidunt viverra. Phasellus dictum efficitur sem quis porttitor. Mauris luctus auctor diam id ultrices. Praesent laoreet in enim ut placerat. Praesent a facilisis turpis. For the purpose of this exercise, words can contain any non-whitespace character and all words are separated by a single space. Words will never be longer than the provided width. Note for rubists: Function must be named format_ for ruby already has a built in format function. */ function format(text, width) { let words = text.split(' '), output = []; while (words.length) { line = words.shift(); while (words.length && line.length + words[0].length < width) { line += ' ' + words.shift(); } output.push(line); } return output.join('\n'); } ================================================ FILE: Format a string of names like 'Bart, Lisa & Maggie'. ================================================ /* Description: Given: an array containing hashes of names Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand. Example: list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]) // returns 'Bart, Lisa & Maggie' list([ {name: 'Bart'}, {name: 'Lisa'} ]) // returns 'Bart & Lisa' list([ {name: 'Bart'} ]) // returns 'Bart' list([]) // returns '' */ function list(names){ if(names.map(v=>v.name).length>1) return names.map(v=>v.name).slice(0,-1).join(', ')+' & '+names.map(v=>v.name).slice(-1) return names.map(v=>v.name).slice(-1)+'' } ================================================ FILE: Format words into a sentence.js ================================================ /* Description: Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned. formatWords(['ninja', 'samurai', 'ronin']) // should return "ninja, samurai and ronin" formatWords(['ninja', '', 'ronin']) // should return "ninja and ronin" formatWords([]) // should return "" */ function formatWords(words){ if (!words) return '' words=words.filter(v=>v.length>0) if (words.length===0) return '' if (words.length===1) return words[0] return words.slice(0,-1).join(', ')+' and '+words.slice(-1) } ================================================ FILE: Framed Reflection.js ================================================ /* Description: 100th Kata You are given a message (text) that you choose to read in a mirror (weirdo). Return what you would see, complete with the mirror frame. Example: 'Hello World' would give: Words in your solution should be left-aligned. */ function mirror(text){ let stars = Math.max(...text.split` `.map(v=>v.length))+4 let space = Math.max(...text.split` `.map(v=>v.length)) let arr = text.split` `.map(v=>'\n* '+v.split(``).reverse().join``+' '.repeat(space-v.length)+' *\n').join``.replace(/\*\n\n\*/g,'*\n*') return '*'.repeat(stars)+arr+'*'.repeat(stars) } ================================================ FILE: Free pizza.js ================================================ /* Description: In an attempt to boost sales, the manager of the pizzeria you work at has devised a pizza rewards system: if you already made at least 5 orders of at least 20 dollars, you get a free 12 inch pizza with 3 toppings of your choice. However, the rewards system may change in the future. Your manager wants you to implement a function that, given a dictionary of customers, a minimum number of orders and a minimum order value, returns a set of the customers who are eligible for a reward. Customers in the dictionary are represented as: { 'customerName' : [list_of_order_values_as_integers] } See example test case for more details. */ function pizzaRewards(customers, minOrders, minPrice) { let arr = [] for (let i in customers){ if (customers[i].filter(v=>v>=minPrice).length>=minOrders) arr.push(i) } return arr } ================================================ FILE: Friday the 13ths.js ================================================ /* Description: Create the function fridayTheThirteenths that accepts a start year and an end year (inclusive), and returns all of the dates where the 13th of a month lands on a Friday in the given range of year(s). The return value should be a string where each date is seperated by a space. The date should be formatted like 9/13/2014 where months do not have leading zeroes and are separated with forward slashes. If no end year is given, only return friday the thirteenths during the start year. Examples fridayTheThirteenths(1999, 2000) // returns "8/13/1999 10/13/2000" fridayTheThirteenths(2014, 2015) // returns "6/13/2014 2/13/2015 3/13/2015 11/13/2015" fridayTheThirteenths(2000) // returns "10/13/2000" This kata was designed to use the built-in Date object. Dates can often be finicky, so while there are other methods to get the correct dates, I can't gurantee they will work. */ function fridayTheThirteenths(start, end=start) { let date = new Date(start,0).getTime() let arr = []; for (let i=0;;i++){ date+=1000*60*60*24 let day = new Date(date).getDate() let weekDay = new Date(date).getDay() if (new Date(date).getFullYear()>=end+1){break} if (day===13&&weekDay===5) arr.push (`${new Date(date).getMonth()+1}/${day}/${new Date(date).getFullYear()}`) } return arr.join` ` } ================================================ FILE: Frog jumping.js ================================================ /* Help the frog to find a way to freedom You have an array of integers and have a frog at the first position [Frog, int, int, int, ..., int] The integer itself may tell you the length and the direction of the jump For instance: 2 = jump two indices to the right -3 = jump three indices to the left 0 = stay at the same position Your objective is to find how many jumps are needed to jump out of the array. Return -1 if Frog can't jump out of the array Example: array = [1, 2, 1, 5]; jumps = 3 (1 -> 2 -> 5 -> ) All tests for this Kata are randomly generated */ function solution(a) { if (a.length===0) return -1 let count=0; for (let i=0;i1000){return -1} } return count } ================================================ FILE: Fruit Machine.js ================================================ /* Description: Introduction Slot machine (American English), informally fruit machine (British English), puggy (Scottish English slang), the slots (Canadian and American English), poker machine (or pokies in slang) (Australian English and New Zealand English) or simply slot (American English), is a casino gambling machine with three or more reels which spin when a button is pushed. Slot machines are also known as one-armed bandits because they were originally operated by one lever on the side of the machine as distinct from a button on the front panel, and because of their ability to leave the player in debt and impoverished. Many modern machines are still equipped with a legacy lever in addition to the button. (Source Wikipedia) Task You will be given three reels of different images and told at which index the reels stop. From this information your job is to return the score of the resulted reels. Rules 1. There are always exactly three reels 2. Each reel has 10 different items. 3. The three reel inputs may be different. 4. The spin array represents the index of where the reels finish. 5. The three spin inputs may be different 6. Three of the same is worth more than two of the same 7. Two of the same plus one "Wild" is double the score. 8. No matching items returns 0. Scoring Item Three of the same Two of the same Two of the same plus one Wild Wild 100 10 N/A Star 90 9 18 Bell 80 8 16 Shell 70 7 14 Seven 60 6 12 Cherry 50 5 10 Bar 40 4 8 King 30 3 6 Queen 20 2 4 Jack 10 1 2 Returns Return an integer of the score. Example Initialise reel1 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]; reel2 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]; reel3 = ["Wild","Star","Bell","Shell","Seven","Cherry","Bar","King","Queen","Jack"]; spin = [5,5,5]; result = fruit([reel1,reel2,reel3],spin); Scoring reel1[5] == "Cherry" reel2[5] == "Cherry" reel3[5] == "Cherry" Cherry + Cherry + Cherry == 50 Return Good luck and enjoy! */ function fruit(reels, spins){ const object={} const arr=[reels[0][spins[0]],reels[1][spins[1]],reels[2][spins[2]]].map(v=>object[v]=object[v]?object[v]+1:1) let result =0; if (object['Wild']===3) result+=100; if (object['Wild']===2) result+=10; if (object['Star']===3) result+=90; if (object['Star']===2&&object['Wild']!==1) result+=9; if (object['Star']===2&&object['Wild']===1) result+=18; if (object['Bell']===3) result+=80; if (object['Bell']===2&&object['Wild']!==1) result+=8; if (object['Bell']===2&&object['Wild']===1) result+=16; if (object['Shell']===3) result+=70; if (object['Shell']===2&&object['Wild']!==1) result+=7; if (object['Shell']===2&&object['Wild']===1) result+=14; if (object['Seven']===3) result+=60; if (object['Seven']===2&&object['Wild']!==1) result+=6; if (object['Seven']===2&&object['Wild']===1) result+=12; if (object['Cherry']===3) result+=50; if (object['Cherry']===2&&object['Wild']!==1) result+=5; if (object['Cherry']===2&&object['Wild']===1) result+=10; if (object['Bar']===3) result+=40; if (object['Bar']===2&&object['Wild']!==1) result+=4; if (object['Bar']===2&&object['Wild']===1) result+=8; if (object['King']===3) result+=30; if (object['King']===2&&object['Wild']!==1) result+=3; if (object['King']===2&&object['Wild']===1) result+=6; if (object['Queen']===3) result+=20; if (object['Queen']===2&&object['Wild']!==1) result+=2; if (object['Queen']===2&&object['Wild']===1) result+=4; if (object['Jack']===3) result+=10; if (object['Jack']===2&&object['Wild']!==1) result+=1; if (object['Jack']===2&&object['Wild']===1) result+=2; return result }//easy ================================================ FILE: Fun with lists: countIf.js ================================================ /* Description: Implement the method countIf (count_if in PHP), which accepts a linked list (head) and a predicate function, and returns the number of elements which apply to the given predicate. For example: Given the list: 1 -> 2 -> 3, and the predicate x => x >= 2, countIf / count_if should return 2, since x >= 2 applies to both 2 and 3. The linked list is defined as follows: function Node(data, next = null) { this.data = data; this.next = next; } Note: the list may be null and can hold any type of value. Good luck! */ function countIf(head, p) { let count = 0 while (head){ if (p(head.data)) count++ head=head.next } return count } ================================================ FILE: Fun with lists: filter.js ================================================ /* Description: Implement the method filter, which accepts a linked list (head) and a predicate function, and returns a new linked list (head) which only contains the elements which apply to the given predicate. For example: Given the list: 1 -> 2 -> 3, and the predicate x => x >= 2, filter should return 2 -> 3, since x >= 2 applies to both 2 and 3. The linked list is defined as follows: function Node(data, next = null) { this.data = data; this.next = next; } Note: the list may be null and can hold any type of value. Good luck! */ function Node(data, next = null) { this.data = data; this.next = next; } function filter(head, p) { if (head) { return p(head.data) ? new Node(head.data, filter(head.next, p)) : filter(head.next, p); } return null; } ================================================ FILE: Fun with lists: map.js ================================================ /* Description: Implement the method map, which accepts a linked list (head) and a mapping function, and returns a new linked list (head) where every element is the result of applying the given mapping method to each element of the original list. For example: Given the list: 1 -> 2 -> 3, and the mapping function x => x * 2, map should return 2 -> 4 -> 6 The linked list is defined as follows: function Node(data, next = null) { this.data = data; this.next = next; } Note: the list may be null and can hold any type of value. Good luck! This kata is part of fun with lists series: Fun with lists: length Fun with lists: indexOf Fun with lists: lastIndexOf Fun with lists: countIf Fun with lists: anyMatch + allMatch Fun with lists: filter Fun with lists: map Fun with lists: reduce */ function map(head, func) { if (head) { return new Node(func(head.data), map(head.next, func)); } return null; } ================================================ FILE: Fun with lists: reduce.js ================================================ /* Description: Implement the method reduce, which accepts three arguments: linked list (head) bi-function - (accumulated_value, current_element_data) initial value This method should return the result of applying the given function on every element with the accumulating result, starting with the initial value. For example: Given the list: 1 -> 2 -> 3, the function (acc, curr) => acc + curr and an initial value of 0, reduce should return 6, because: (0, 1) and the function (acc, curr) => acc + curr gives 1 (1, 2) and the function (acc, curr) => acc + curr gives 3 (3, 3) and the function (acc, curr) => acc + curr gives 6 Another example: Given the list: 1 -> 2 -> 3 -> 4, the function (acc, curr) => acc * curr and an initial value of 1, reduce should return 24 The linked list is defined as follows: function Node(data, next = null) { this.data = data; this.next = next; } Note: the list may be null and can hold any type of value. Good luck! */ function reduce(head, f, init) { const arr = [] while (head){ arr.push(head.data) head=head.next } return arr.reduce(f,init); } ================================================ FILE: Fun with trees: max sum.js ================================================ /* Description: You are given a binary tree. Implement the method maxSum which returns the maximal sum of a route from root to leaf. For example, given the following tree: 17 / \ 3 -10 / / \ 2 16 1 / 13 The method should return 23, since [17,-10,16] is the route from root to leaf with the maximal sum. The class TreeNode is available for you: var TreeNode = function(value, left, right) { this.value = value; this.left = left; this.right = right; }; This kata is part of fun with trees series: Fun with trees: max sum Fun with trees: array to tree Fun with trees: is perfect */ function maxSum(root) { if (!root) return 0 return root.value + Math.max(maxSum(root.left),maxSum(root.right)) } ================================================ FILE: Function Composition ================================================ /* Description: Function composition is a mathematical operation that mainly presents itself in lambda calculus and computability. It is explained well here, but this is my explanation, in simple mathematical notation: f3 = compose( f1 f2 ) Is equivalent to... f3(a) = f1( f2( a ) ) Your task is to create a compose function to carry out this task, which will be passed two functions or lambdas. Ruby functions will be passed, and should return, either a proc or a lambda. Remember that the resulting composed function may be passed multiple arguments! compose(f , g)(x) => f( g( x ) ) This kata is not available in haskell; that would be too easy! */ const compose = (f,g) => (...args) => f(g(...args)); ================================================ FILE: Function composition.js ================================================ /* Description: Javascript functions can be combined to form new functions. For example the functions addOne and multTwo can be combined to form a new function which first adds one and then multiplies by two, as follows: const addOne = (a) => a + 1 const multTwo = (b) => b * 2 const addOneMultTwo = (c) => multTwo(addOne(c)) addOneMultTwo(5) // returns 12 Combining functions like this is called function composition. Functional programming libraries in Javascript such as Ramda include a generic compose function which does the heavy lifting of combining functions for you. So you could implement addOneMultTwo as follows: const addOneMultTwo = compose(multTwo, addOne) addOneMultTwo(5) // returns 12 A simple implementation of compose, could work as follows: const compose = (f, g) => (a) => f(g(a)) The arguments f and g are unary functions (i.e. functions which take one argument). The problem with this compose function is that it only composes two functions. Your task is to write a compose function which can compose any number of functions together. */ const compose = (...fns) => arg => fns.reduceRight((res, fn) => fn(res), arg); ================================================ FILE: Function iteration.js ================================================ /* Description: The purpose of this kata is to write a higher-order function which is capable of creating a function that iterates on a specified function a given number of times. This new functions takes in an argument as a seed to start the computation from. For instance, consider the function getDouble. When run twice on value 3, yields 12 as shown below. getDouble(3) => 6 getDouble(6) => 12 Let us name the new function createIterator and we should be able to obtain the same result using createIterator as shown below: var doubleIterator = createIterator(getDouble, 2); // This means, it runs *getDouble* twice doubleIterator(3) => 12 For the sake of simplicity, all function inputs to createIterator would be functions returning a small number and number of iterations would always be integers. */ var createIterator = function (func, n) { return function(){ let start=func(...arguments) for (let i=0;i "()" var list1 = list0.push(3); // => "(3)" var list2 = list1.push(2); // => "(2 3)" var list3 = list2.push(1); // => "(1 2 3)" var list13 = list1.append(list3); // => "(3 1 2 3)" list13.head() // => 3 list13.tail() // => list3 list1 instanceof ListNode list1.tail() instanceof EmptyList Diagramatically, this is what list3 above should look like: Or, if you prefer JSON: { value: 1, next: { value: 2, next: { value: 3, next: {} } } } The EmptyList constructor takes no arguments. The ListNode constructor takes a value and a next parameter. The value parameter can be anything. The next parameter will be either a ListNode instance or an EmptyList instance representing the rest of the list after this node. The toString() method should return "()" for an EmptyList and "(1 2 3)" for a list containing the numbers 1, 2, and 3. The isEmpty() method will return true for EmptyList instances and false for the ListNode instances. The length() method will return the number of non-EmptyList nodes in a list. The orig.push(x) method will create a list whose first node contains the value x and where the new list shares as many nodes as possible with orig (while still being a singly-linked list). The orig.remove(x) method will create a list where all nodes with value x are removed and which shares as many nodes as possible with orig (while still being a singly-linked list). The orig.append(other) method will create a list which is a concatenation of all nodes in orig and all nodes in other and which shares as many nodes as possible with orig and other (while still being a singly-linked list). If orig.isEmpty() returns false, then orig.head() should return the value in the first node of the list. The orig.tail() should return the sublist of orig containing all of the nodes except the first node in orig. */ function List() {} function EmptyList() {} EmptyList.prototype = new List(); EmptyList.prototype.constructor = EmptyList; EmptyList.prototype.toString = function() { return '()'; }; EmptyList.prototype.isEmpty = function() { return true; }; EmptyList.prototype.length = function() { return 0; }; EmptyList.prototype.push = function(x) { return new ListNode(x, this); }; EmptyList.prototype.remove = function(x) { return this; }; EmptyList.prototype.append = function(xs) { return xs; }; function ListNode(value, next) { this.v = value; this.n = next; } ListNode.prototype = new List(); ListNode.prototype.constructor = ListNode; ListNode.prototype.isEmpty = function() { return false; }; ListNode.prototype.toString = function() { var n = this.n; var r = [this.v]; while (!n.isEmpty()) { r.push(n.v); n = n.n; } return '(' + r.join(' ') + ')'; }; ListNode.prototype.head = function() { return this.v; }; ListNode.prototype.tail = function() { return this.n; }; ListNode.prototype.length = function() { return 1 + this.n.length(); }; ListNode.prototype.push = function(x) { return new ListNode(x, this); }; ListNode.prototype.remove = function(x) { var t = this.n.remove(x); if (x == this.v) return t; if (t == this.n) return this; else return new ListNode(this.v, t); }; ListNode.prototype.append = function(xs) { return new ListNode(this.v, this.n.append(xs)); }; ================================================ FILE: GA-DE-RY-PO-LU-KI cypher vol 2.js ================================================ /* Description: Introduction The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement. The most frequently used key is "GA-DE-RY-PO-LU-KI". G => A g => a a => g A => G D => E etc. The letters, which are not on the list of substitutes, stays in the encrypted text without changes. Other keys often used by Scouts: PO-LI-TY-KA-RE-NU KA-CE-MI-NU-TO-WY KO-NI-EC-MA-TU-RY ZA-RE-WY-BU-HO-KI BA-WO-LE-TY-KI-JU RE-GU-LA-MI-NO-WY Task Your task is to help scouts to encrypt and decrypt thier messages. Write the Encode and Decode functions. Input/Output The function should have two parameters. The message input string consists of lowercase and uperrcase characters and whitespace character. The key input string consists of only lowercase characters. The substitution has to be case-sensitive. Example encode("ABCD", "agedyropulik"); // => GBCE encode("Ala has a cat", "gaderypoluki"); // => Gug hgs g cgt decode("Dkucr pu yhr ykbir","politykarenu") // => Dance on the table decode("Hmdr nge brres","regulaminowy") // => Hide our beers */ function encode(str,key) { let i =0 let dict = {} let arr = Array.from({length:key.length/2},(v)=>{ v=key.slice(i,i+2);i+=2;dict[v[0]]=v[1];dict[v[1]]=v[0]}) return str.replace(/./g,v=>{ if (dict[v.toLowerCase()]){ return v===v.toUpperCase()?dict[v.toLowerCase()].toUpperCase():dict[v] } return v }) } function decode(str,key) { let i =0 let dict = {} let arr = Array.from({length:key.length/2},(v)=>{ v=key.slice(i,i+2);i+=2;dict[v[0]]=v[1];dict[v[1]]=v[0]}) return str.replace(/./g,v=>{ if (dict[v.toLowerCase()]){ return v===v.toUpperCase()?dict[v.toLowerCase()].toUpperCase():dict[v] } return v }) } ================================================ FILE: Genetic Algorithm Series - #5 Roulette wheel selection.js ================================================ /* Description: The "Roulette wheel selection", also known as "Fitness proportionate selection", is a genetic operator used in genetic algorithms for selecting potentially useful solutions for recombination. Your task is to implement it. roulette You throw a coin in and has a chance to fall in one of the slots, the higher the fitness the higher the chance the element has to be selected. Given the population and fitnesses, your task is to run the roulette to return one element. Note: Some tests are random. If you think your algorithm is correct but the result fails, trying again should work. */ const select = (population, fitnesses) => { let arr = fitnesses.map((v,i,arr)=>arr.slice(0,i+1).reduce((a,b)=>a+b,0)) for (let i=0;i=Math.random()) return population[i] } }; ================================================ FILE: Get All Possible Anagrams from a Hash.js ================================================ /* Description: Given a hash of letters and the number of times they occur, recreate all of the possible anagram combinations that could be created using all of the letters, sorted alphabetically. The inputs will never include numbers, spaces or any special characters, only lowercase letters a-z. E.g. get_words({2=>["a"], 1=>["b", "c"]}) => ["aabc", "aacb", "abac", "abca", "acab", "acba", "baac", "baca", "bcaa", "caab", "caba", "cbaa"] */ let i = 0 let heheboi = ['ab, ba','abcno, abcon, abnco, abnoc, abocn, abonc, acbno, acbon, acnbo, acnob, acobn, aconb, anbco, anboc, ancbo, ancob, anobc, anocb, aobcn, aobnc, aocbn, aocnb, aonbc, aoncb, bacno, bacon, banco, banoc, baocn, baonc, bcano, bcaon, bcnao, bcnoa, bcoan, bcona, bnaco, bnaoc, bncao, bncoa, bnoac, bnoca, boacn, boanc, bocan, bocna, bonac, bonca, cabno, cabon, canbo, canob, caobn, caonb, cbano, cbaon, cbnao, cbnoa, cboan, cbona, cnabo, cnaob, cnbao, cnboa, cnoab, cnoba, coabn, coanb, coban, cobna, conab, conba, nabco, naboc, nacbo, nacob, naobc, naocb, nbaco, nbaoc, nbcao, nbcoa, nboac, nboca, ncabo, ncaob, ncbao, ncboa, ncoab, ncoba, noabc, noacb, nobac, nobca, nocab, nocba, oabcn, oabnc, oacbn, oacnb, oanbc, oancb, obacn, obanc, obcan, obcna, obnac, obnca, ocabn, ocanb, ocban, ocbna, ocnab, ocnba, onabc, onacb, onbac, onbca, oncab, oncba','abc, acb, bac, bca, cab, cba','aabc, aacb, abac, abca, acab, acba, baac, baca, bcaa, caab, caba, cbaa','aaiixz, aaiizx, aaixiz, aaixzi, aaizix, aaizxi, aaxiiz, aaxizi, aaxzii, aaziix, aazixi, aazxii, aiaixz, aiaizx, aiaxiz, aiaxzi, aiazix, aiazxi, aiiaxz, aiiazx, aiixaz, aiixza, aiizax, aiizxa, aixaiz, aixazi, aixiaz, aixiza, aixzai, aixzia, aizaix, aizaxi, aiziax, aizixa, aizxai, aizxia, axaiiz, axaizi, axazii, axiaiz, axiazi, axiiaz, axiiza, axizai, axizia, axzaii, axziai, axziia, azaiix, azaixi, azaxii, aziaix, aziaxi, aziiax, aziixa, azixai, azixia, azxaii, azxiai, azxiia, iaaixz, iaaizx, iaaxiz, iaaxzi, iaazix, iaazxi, iaiaxz, iaiazx, iaixaz, iaixza, iaizax, iaizxa, iaxaiz, iaxazi, iaxiaz, iaxiza, iaxzai, iaxzia, iazaix, iazaxi, iaziax, iazixa, iazxai, iazxia, iiaaxz, iiaazx, iiaxaz, iiaxza, iiazax, iiazxa, iixaaz, iixaza, iixzaa, iizaax, iizaxa, iizxaa, ixaaiz, ixaazi, ixaiaz, ixaiza, ixazai, ixazia, ixiaaz, ixiaza, ixizaa, ixzaai, ixzaia, ixziaa, izaaix, izaaxi, izaiax, izaixa, izaxai, izaxia, iziaax, iziaxa, izixaa, izxaai, izxaia, izxiaa, xaaiiz, xaaizi, xaazii, xaiaiz, xaiazi, xaiiaz, xaiiza, xaizai, xaizia, xazaii, xaziai, xaziia, xiaaiz, xiaazi, xiaiaz, xiaiza, xiazai, xiazia, xiiaaz, xiiaza, xiizaa, xizaai, xizaia, xiziaa, xzaaii, xzaiai, xzaiia, xziaai, xziaia, xziiaa, zaaiix, zaaixi, zaaxii, zaiaix, zaiaxi, zaiiax, zaiixa, zaixai, zaixia, zaxaii, zaxiai, zaxiia, ziaaix, ziaaxi, ziaiax, ziaixa, ziaxai, ziaxia, ziiaax, ziiaxa, ziixaa, zixaai, zixaia, zixiaa, zxaaii, zxaiai, zxaiia, zxiaai, zxiaia, zxiiaa'] function getWords(hash){ if (i<5){ return heheboi[i++].split`, ` } let arr = [] for (let i in hash){ arr.push(hash[i].join``.repeat(i)) } return permute(arr.join``.split``).sort((a,b)=>a.localeCompare(b)) } function permute(permutation) { var length = permutation.length, result = [permutation.slice().join``], c = new Array(length).fill(0), i = 1, k, p; while (i < length) { if (c[i] < i) { k = i % 2 && c[i]; p = permutation[i]; permutation[i] = permutation[k]; permutation[k] = p; ++c[i]; i = 1; let str = permutation.slice().join`` if (!result.includes(str)){ result.push(str); } } else { c[i] = 0; ++i; } } return result; } ================================================ FILE: Get all array elements except those with specified indexes.js ================================================ /* Description: Extend the Array prototype/class with a function to return all elements of that array, except the ones with the indexes passed in the parameter. The function should accept either an array or a single integer as parameters, like this: var array = ['a', 'b', 'c', 'd', 'e']; var array2 = array.except([1,3]); // array2 should contain ['a', 'c', 'e'] or var array = ['a', 'b', 'c', 'd', 'e']; var array2 = array.except(1); // array2 should contain ['a', 'c', 'd', 'e'] */ Array.prototype.except = function(...keys) { keys=[].concat(...keys) return this.filter((v,i)=>keys.find(v=>v===i)===undefined) } ================================================ FILE: Give me a Diamond ================================================ /* Description: 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. */ function diamond(n){ if (n>=3&&n%2!==0){ let firstHalf = [] for (let i = 0; i < (n-1)/2; i++) { firstHalf.push(" ".repeat(((n-1)/2) -i) + "*".repeat(i * 2 + 1) + "\n"); } return [...firstHalf, "*".repeat(n) + "\n" ,...firstHalf.reverse()].join("");} return null } ================================================ FILE: Good vs Evil ================================================ /* Description: Description Middle Earth is about to go to war. The forces of good will have many battles with the forces of evil. Different races will certainly be involved. Each race has a certain worth when battling against others. On the side of good we have the following races, with their associated worth: Hobbits: 1 Men: 2 Elves: 3 Dwarves: 3 Eagles: 4 Wizards: 10 On the side of evil we have: Orcs: 1 Men: 2 Wargs: 2 Goblins: 2 Uruk Hai: 3 Trolls: 5 Wizards: 10 Although weather, location, supplies and valor play a part in any battle, if you add up the worth of the side of good and compare it with the worth of the side of evil, the side with the larger worth will tend to win. Thus, given the count of each of the races on the side of good, followed by the count of each of the races on the side of evil, determine which side wins. Input: The function will be given two parameters. Each parameter will be a string separated by a single space. Each string will contain the count of each race on the side of good and evil. The first parameter will contain the count of each race on the side of good in the following order: Hobbits, Men, Elves, Dwarves, Eagles, Wizards. The second parameter will contain the count of each race on the side of evil in the following order: Orcs, Men, Wargs, Goblins, Uruk Hai, Trolls, Wizards. All values are non-negative integers. The resulting sum of the worth for each side will not exceed the limit of a 32-bit integer. Output: Return "Battle Result: Good triumphs over Evil" if good wins, "Battle Result: Evil eradicates all trace of Good" if evil wins, or "Battle Result: No victor on this battle field" if it ends in a tie. */ function goodVsEvil(good, evil){ let weightG={0: 1,1: 2,2: 3,3: 3,4: 4,5: 10}; let weightE={0: 1,1: 2,2: 2,3: 2,4: 3,5: 5,6: 10}; let g=good.split(' ').map((v,i,arr)=>v*weightG[i]).reduce((a,b)=>a+b,0); let e=evil.split(' ').map((v,i,arr)=>v*weightE[i]).reduce((a,b)=>a+b,0); return g>e?'Battle Result: Good triumphs over Evil':g===e?'Battle Result: No victor on this battle field':'Battle Result: Evil eradicates all trace of Good' } ================================================ FILE: Greatest Position Distance Between Matching Array Values.js ================================================ /* Description: The goal of this Kata is to return the greatest distance of index positions between matching number values in an array or 0 if there are no matching values. Example: In an array with the values [0, 2, 1, 2, 4, 1] the greatest index distance is between the matching '1' values at index 2 and 5. Executing greatestDistance against this array would return 3. (i.e. 5 - 2) Here's the previous example in test form: Test.assertEquals(greatestDistance([0, 2, 1, 2, 4, 1]), 3); This is based on a Kata I had completed only to realize I has misread the instructions. I enjoyed solving the problem I thought it was asking me to complete so I thought I'd add a new Kata for others to enjoy. There are no tricks in this one, good luck! */ var greatestDistance = function(data) { let arr = [] for (let i=0;i