Skip to content

Bob-chemist/codewars

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Binary Addition (7 kyu)

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string.

Growth of a Population (7 kyu)

In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?

At the end of the first year there will be: 1000 + 1000 * 0.02 + 50 => 1070 inhabitants

At the end of the 2nd year there will be: 1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)

At the end of the 3rd year there will be: 1141 + 1141 * 0.02 + 50 => 1213

It will need 3 entire years. More generally given parameters:

p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass)

the function nb_year should return n number of entire years needed to get a population greater or equal to p.

aug is an integer, percent a positive or null number, p0 and p are positive integers (> 0)

Examples: nb_year(1500, 5, 100, 5000) -> 15 nb_year(1500000, 2.5, 10000, 2000000) -> 10 Note: Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.

Counting sheep... (8 kyu)

Consider an array of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).

For example,

[true, true, true, false, true, true, true, true , true, false, true, false, true, false, false, true , true, true, true, true , false, false, true, true] The correct answer would be 17.

Hint: Don't forget to check for bad values like null/undefined

Highest and Lowest (7 kyu) In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

Example:

highAndLow("1 2 3 4 5"); // return "5 1" highAndLow("1 2 -3 4 5"); // return "5 -3" highAndLow("1 9 3 4 -5"); // return "9 -5" Notes:

All numbers are valid Int32, no need to validate them. There will always be at least one number in the input string. Output string must be two numbers separated by a single space, and highest number is first.

Build Tower (6 kyu)

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

[ ' * ', ' *** ', ' ***** ', ' ******* ', ' ********* ', '***********' ]

Friend or Foe? (7 kyu)

Make a program that filters a list of strings and returns a list with only your friends name in it. If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"] Note: keep the original order of the names in the output.

Find the odd int (6 kyu)

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.

Equal Sides Of An Array (6 kyu)

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.

Vasya - Clerk (6 kyu)

The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 dollars bill. An "Avengers" ticket costs 25 dollars.

Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.

Can Vasya sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

Return YES, if Vasya can sell a ticket to each person and give the change with the bills he has at hand at that moment. Otherwise return NO.

Examples: tickets([25, 25, 50]) // => YES tickets([25, 100]) // => NO. Vasya will not have enough money to give change to 100 dollars tickets([25, 25, 50, 50, 100]) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)

Shortest Word (7 kyu)

Simple, given a string of words, return the length of the shortest word(s). String will never be empty and you do not need to account for different data types.

Ones and Zeros (7 kyu)

Given an array of one's and zero's convert the equivalent binary value to an integer. Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1. Examples: Testing: [0, 0, 0, 1] ==> 1 Testing: [0, 0, 1, 0] ==> 2 Testing: [0, 1, 0, 1] ==> 5 Testing: [1, 0, 0, 1] ==> 9 Testing: [0, 0, 1, 0] ==> 2 Testing: [0, 1, 1, 0] ==> 6 Testing: [1, 1, 1, 1] ==> 15 Testing: [1, 0, 1, 1] ==> 11 However, the arrays can have varying lengths, not just limited to 4.

Get the Middle Character (7 kyu)

You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. #Examples: Kata.getMiddle("test") should return "es" Kata.getMiddle("testing") should return "t" Kata.getMiddle("middle") should return "dd" Kata.getMiddle("A") should return "A" #Input A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out. #Output The middle character(s) of the word represented as a string.

Sum of two lowest positive integers (7 kyu)

Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed. For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7. [10, 343445353, 3453445, 3453545353453] should return 3453455.

What's a Perfect Power anyway? (5 kyu)

A perfect power is a classification of positive integers: In mathematics, a perfect power is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1 such that mk = n. Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair m and k with mk = n as a proof. Otherwise return Nothing, Nil, null, NULL, None or your language's equivalent. Note: For a perfect power, there might be several pairs. For example 81 = 3^4 = 9^2, so (3,4) and (9,2) are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it. Examples Test.describe("perfect powers", function(){ Test.it("should work for some examples",function(){ Test.assertSimilar(isPP(4), [2,2], "4 = 2^2"); Test.assertSimilar(isPP(9), [3,2], "9 = 3^2"); Test.assertEquals( isPP(5), null, "5 isn't a perfect number"); }); });

Gap in Primes (5 kyu)

The prime numbers are not regularly spaced. For example from 2 to 3 the gap is 1. From 3 to 5 the gap is 2. From 7 to 11 it is 4. Between 2 and 50 we have the following pairs of 2-gaps primes: 3-5, 5-7, 11-13, 17-19, 29-31, 41-43

A prime gap of length n is a run of n-1 consecutive composite numbers between two successive primes (see: http://mathworld.wolfram.com/PrimeGaps.html).

We will write a function gap with parameters:

g (integer >= 2) which indicates the gap we are looking for

m (integer > 2) which gives the start of the search (m inclusive)

n (integer >= m) which gives the end of the search (n inclusive)

In the example above gap(2, 3, 50) will return [3, 5] or (3, 5) or {3, 5} which is the first pair between 3 and 50 with a 2-gap.

So this function should return the first pair of two prime numbers spaced with a gap of g between the limits m, n if these numbers exist otherwise nil or null or None or Nothing (depending on the language).

In C++ return in such a case {0, 0}. In F# return [||]. In Kotlin return []

#Examples: gap(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7}

gap(2, 5, 5) --> nil. In C++ {0, 0}.

gap(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}

([193, 197] is also such a 4-gap primes between 130 and 200 but it's not the first pair)

gap(6,100,110) --> nil or {0, 0} : between 100 and 110 we have 101, 103, 107, 109 but 101-107is not a 6-gap because there is 103in between and 103-109is not a 6-gap because there is 107in between.

Note for Go For Go: nil slice is expected when there are no gap between m and n. Example: gap(11,30000,100000) --> nil

Unique In Order (6 kyu)

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] uniqueInOrder('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] uniqueInOrder([1,2,2,3,3]) == [1,2,3]

Word a10n (abbreviation) (6 kyu)

The word i18n is a common abbreviation of internationalization in the developer community, used instead of typing the whole word and trying to spell it correctly. Similarly, a11y is an abbreviation of accessibility. Write a function that takes a string and turns any and all "words" (see below) within that string of length 4 or greater into an abbreviation, following these rules: A "word" is a sequence of alphabetical characters. By this definition, any other character like a space or hyphen (eg. "elephant-ride") will split up a series of letters into two words (eg. "elephant" and "ride"). The abbreviated version of the word should have the first letter, then the number of removed characters, then the last letter (eg. "elephant ride" => "e6t r2e"). Example abbreviate("elephant-rides are really fun!") // ^^^^^^^^^^^^^^^^^^^^^^^^^* // words (^): "elephant" "rides" "are" "really" "fun" // 123456 123 1 1234 1 // ignore short words: X X // abbreviate: "e6t" "r3s" "are" "r4y" "fun" // all non-word characters (*) remain in place // "-" " " " " " " "!" === "e6t-r3s are r4y fun!"

Write Number in Expanded Form (6 kyu)

You will be given a number and you will need to return it as a string in Expanded Form. For example:

expandedForm(12); // Should return '10 + 2' expandedForm(42); // Should return '40 + 2' expandedForm(70304); // Should return '70000 + 300 + 4' NOTE: All numbers will be whole numbers greater than 0.

Help the bookseller!

A bookseller has lots of books classified in 26 categories labeled A, B, ... Z. Each book has a code c of 3, 4, 5 or more capitals letters. The 1st letter of a code is the capital letter of the book category. In the bookseller's stocklist each code c is followed by a space and by a positive integer n (int n >= 0) which indicates the quantity of books of this code in stock.

For example an extract of one of the stocklists could be:

L = {"ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"}. or

L = ["ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60"] or .... You will be given a stocklist (e.g. : L) and a list of categories in capital letters e.g :

M = {"A", "B", "C", "W"} or

M = ["A", "B", "C", "W"] or ... and your task is to find all the books of L with codes belonging to each category of M and to sum their quantity according to each category.

For the lists L and M of example you have to return the string (in Haskell/Clojure a list of pairs):

(A : 20) - (B : 114) - (C : 50) - (W : 0) where A, B, C, W are the categories, 20 is the sum of the unique book of category A, 114 the sum corresponding to "BKWRK" and "BTSQZ", 50 corresponding to "CDXEF" and 0 to category 'W' since there are no code beginning with W.

If L or M are empty return string is "" (Clojure should return an empty array instead).

Note: In the result codes and their values are in the same order as in M.

Count the smiley faces! (6 kyu)

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;

Note: In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same

Happy coding!

Two Sum (6 kyu)

Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in an array like so: [index1, index2].

For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.

The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).

Take a Ten Minute Walk (6 kyu)

You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block in a direction and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

Note: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!).

IPv4 to int32 (6 kyu)

Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits).

1st octet 128 has the binary representation: 10000000 2nd octet 32 has the binary representation: 00100000 3rd octet 10 has the binary representation: 00001010 4th octet 1 has the binary representation: 00000001 So 128.32.10.1 == 10000000.00100000.00001010.00000001

Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361.

Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes an IPv4 address and returns a 32 bit number.

ipToInt32("128.32.10.1") => 2149583361

Sort the odd (6 kyu)

You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places.

Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.

Example

sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]

Simple Encryption #1 - Alternating Split (6 kyu)

For building the encrypted string: Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String. Do this n times!

Examples:

"This is a test!", 1 -> "hsi etTi sats!" "This is a test!", 2 -> "hsi etTi sats!" -> "s eT ashi tist!" Write two methods:

function encrypt(text, n) function decrypt(encryptedText, n) For both methods: If the input-string is null or empty return exactly this value! If n is <= 0 then return the input text.

Simplifying multilinear polynomials (4 kyu)

When we attended middle school were asked to simplify mathematical expressions like "3x-yx+2xy-x" (or usually bigger), and that was easy-peasy ("2x+xy"). But tell that to your pc and we'll see!

Write a function: simplify, that takes a string in input, representing a multilinear non-constant polynomial in integers coefficients (like "3x-zx+2xy-x"), and returns another string as output where the same expression has been simplified in the following way ( -> means application of simplify):

All possible sums and subtraction of equivalent monomials ("xy==yx") has been done, e.g.: "cb+cba" -> "bc+abc", "2xy-yx" -> "xy", "-a+5ab+3a-c-2a" -> "-c+5ab"

All monomials appears in order of increasing number of variables, e.g.: "-abc+3a+2ac" -> "3a+2ac-abc", "xyz-xz" -> "-xz+xyz"

If two monomials have the same number of variables, they appears in lexicographic order, e.g.: "a+ca-ab" -> "a-ab+ac", "xzy+zby" ->"byz+xyz"

There is no leading + sign if the first coefficient is positive, e.g.: "-y+x" -> "x-y", but no restrictions for -: "y-x" ->"-x+y"

N.B. to keep it simplest, the string in input is restricted to represent only multilinear non-constant polynomials, so you won't find something like `-3+yx^2'. Multilinear means in this context: of degree 1 on each variable.

Warning: the string in input can contain arbitrary variables represented by lowercase characters in the english alphabet.

Beeramid (5 kyu)

Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too.

A beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25...

Complete the beeramid function to return the number of complete levels of a beer can pyramid you can make, given the parameters of:

  1. your referral bonus, and

  2. the price of a beer can

For example:

beeramid(1500, 2); // should === 12 beeramid(5000, 3); // should === 16

Street Fighter 2 - Character Selection (6 kyu)

Short Intro Some of you might remember spending afternoons playing Street Fighter 2 in some Arcade back in the 90s or emulating it nowadays with the numerous emulators for retro consoles. Can you solve this kata? Suuure-You-Can! UPDATE: a new kata's harder version is available here. The Kata You'll have to simulate the video game's character selection screen behaviour, more specifically the selection grid. Such screen looks like this: https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.fightersgeneration.com%2Fnp5%2Fgm%2Fsf2ce-s2.jpg&f=1

Street Fighter 2 - Character Selection - Part 2 (5 kyu)

This is the rightful continuation to this easier Kata here and some rules are the same with few substantial alterations. This time we have to deal with a situation like Super Street Fighter 2 Selection Screen: https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.vizzed.com%2Fvizzedboard%2Fretro%2Fuser_screenshots%2Fsaves40%2F409292%2FGENESIS--Super%2520Street%2520Fighter%2520II%2520%2520The%2520New%2520Challengers_Jul2%252019_26_37.png&f=1

As you may see, we now have 16 characters on 3 rows. You might think: let's make an array of 3 arrays! But that's not enough.

EMPTY SPACE The first character of the first row (Ryu) is not aligned with the first of the second row (Balrog) but with the second (Ken) and the same goes with the other side; therefore we need to introduce something new, like an offset: the Empty Space. The empty space, represented as empty string "", will allow us to keep the grid aligned and rectangular, with spaces that won't be selectable. In this case we need 2 empty spaces (3 rows x 6 columns = 18 slots, 18 slots - 16 characters = 2 empty spaces). Like this: | | Ryu | E.Honda | Blanka | Guile | | | Balrog | Ken | Chun Li | Zangief | Dhalsim | Sagat | | Vega | T.Hawk | Fei Long | Deejay | Cammy | M.Bison | The moves of the selection cursor are the same as before: rotate horizontally but stop vertically. When you find empty spaces (1 or more) you need to skip them if you approach them horizontally and get to the next selectable slot with the next fighter on the left or right; and if you approach them vertically you need to just stop and stay where you are. Example: if you are on Ryu and move left, you must get to Guile; if you are on Balrog and move up, you must stay on Balrog. Notice: I might put empty spaces right in the middle and the rectangular grids can be any size, not only 3x6, deal with this too.

WHAT'S NEW So, let's resume what are the new issues in this harder version of the Kata: The initial position might be any non-empty slot in the grid (given as input). The characters grid (also given as input) might have any rectangular layout, not only 3 rows. The grid might contain empty spaces, both on the borders or right in the middle.

INPUT Fighters grid; Initial position; List of moves. The third input parameter is still the list of moves (all valid ones: left, right, up or down).

OUTPUT The output is the same as before: the list of characters that have been hovered by the selection cursor after each move, successful or not.

Hopefully test cases will complete my explanation.

Last digit of a large number (5 kyu)

Define a function that takes in two numbers a and b and returns the last decimal digit of a^b. Note that a and b may be very large!

For example, the last decimal digit of 9^7 is 9, since 9^7 = 4782969. The last decimal digit of (2^200)^(2^300), which has over 10^92 decimal digits, is 6.

The inputs to your function will always be non-negative integers.

Examples lastDigit("4", "1") // returns 4 lastDigit("4", "2") // returns 6 lastDigit("9", "7") // returns 9
lastDigit("10","10000000000") // returns 0 Remarks JavaScript, C++, R Since these languages don't have native arbitrarily large integers, your arguments are going to be strings representing non-negative integers.

Compose functions (T Combinator) (5 kyu)

Let's make a function called compose that accepts a value as a parameter, as well as any number of functions as additional parameters.

The function will return the value that results from the first parameter being used as a parameter for all of the accepted function parameters in turn. So:

var doubleTheValue = function(val) { return val * 2; } var addOneToTheValue = function(val) { return val + 1; }

compose(5, doubleTheValue) // should === 10 compose(5, doubleTheValue, addOneToTheValue) // should === 11 If only a single parameter is passed in, return that parameter.

Maximum subarray sum (5 kyu)

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) // should be 6: [4, -1, 2, 1] Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.


About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published