description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
Given a `Date` (in JS and Ruby) or `hours` and `minutes` (in C and Python), return the angle between the two hands of a 12-hour analog clock in **radians**. ### Notes: * The minute hand always points to the exact minute (there is no seconds hand). * The hour hand does not "snap" to the tick marks: e.g. at `6:30` the angle is not `0` because the hour hand is already half way between `6` and `7`. * Return the smaller of the angles ( <= π ). * Return `π` if the hands are opposite. ## Examples * at noon the angle is: `0` * at `3:00` the angle is: `π/2` (90 degrees) * at `6:00` the angle is: `π` (180 degrees) * at `9:00` the angle is: `π/2` (90 degrees)
algorithms
from math import radians def hand_angle(hours, minutes): angle = abs(hours * 30 - 11 * minutes / 2) return radians(min(angle, 360 - angle))
Angle Between Clock Hands
543ddf69386034670d000c7d
[ "Mathematics", "Date Time", "Algorithms" ]
https://www.codewars.com/kata/543ddf69386034670d000c7d
6 kyu
Your job is to group the words in anagrams. ## What is an anagram ? `star` and `tsar` are anagram of each other because you can rearrange the letters for *star* to obtain *tsar*. ## Example A typical test could be : ```javascript // input ["tsar", "rat", "tar", "star", "tars", "cheese"] // output [ ["tsar", "star", "tars"], ["rat", "tar"], ["cheese"] ] ``` Hvae unf ! > I'd advise you to find an efficient way for grouping the words in anagrams otherwise you'll probably won't pass the *heavy superhero* test cases
algorithms
def group_anagrams(words): groups = dict() for word in words: key = tuple(sorted(word)) try: groups[key]. append(word) except: groups[key] = [word] return [v for v in groups . values()]
Group Anagrams
537400e773076324ab000262
[ "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/537400e773076324ab000262
6 kyu
Write a function that takes an integer `n` and returns the `n`th iteration of the fractal known as [*Sierpinski's Gasket*](http://en.wikipedia.org/wiki/Sierpinski_triangle). Here are the first few iterations. The fractal is composed entirely of `L` and white-space characters; each character has one space between it and the next (or a newline). ### 0 ``` L ``` ### 1 ``` L L L ``` ### 2 ``` L L L L L L L L L ``` ### 3 ``` L L L L L L L L L L L L L L L L L L L L L L L L L L L ```
algorithms
def sierpinskiRows(n): if not n: return ['L'] last = sierpinskiRows(n - 1) return last + [row . ljust(2 * * n) + row for row in last] def sierpinski(n): """Returns a string containing the nth iteration of the Sierpinsky Gasket fractal""" return '\n' . join(sierpinskiRows(n))
Sierpinski's Gasket
53ea3ad17b5dfe1946000278
[ "Mathematics", "ASCII Art" ]
https://www.codewars.com/kata/53ea3ad17b5dfe1946000278
5 kyu
In this task you have to code process planner. You will be given initial thing, target thing and a set of processes to turn one thing into another (in the form of _[process\_name, start\_thing, end\_thing]_). You must return names of shortest sequence of processes to turn initial thing into target thing, or empty sequence if it's impossible. If start already equals end, return [], since no path is required. Example: ```javascript var test_processes = [ ['gather', 'field', 'wheat'], ['bake', 'flour', 'bread'], ['mill', 'wheat', 'flour'] ]; processes('field', 'bread', test_processes); // should return ['gather', 'mill', 'bake'] processes('field', 'ferrari', test_processes); // should return [] processes('field', 'field', test_processes); // should return [], since no processes are needed ``` ```python test_processes = [ ['gather', 'field', 'wheat'], ['bake', 'flour', 'bread'], ['mill', 'wheat', 'flour'] ]; processes('field', 'bread', test_processes) # should return ['gather', 'mill', 'bake'] processes('field', 'ferrari', test_processes) # should return [] processes('field', 'field', test_processes) # should return [], since no processes are needed ``` ```coffeescript test_processes = [ ['gather', 'field', 'wheat'] ['bake', 'flour', 'bread'] ['mill', 'wheat', 'flour'] ] processes 'field', 'bread', test_processes # should return ['gather', 'mill', 'bake'] processes 'field', 'ferrari', test_processes # should return [] processes 'field', 'field', test_processes # should return [], since no processes are needed ``` Good luck!
algorithms
def processes(start, end, processes): '''Dijkstra's shortest path algorithm''' q = [(start, [])] visited = set() while q: s, path = q . pop(0) if s == end: return path visited . add(s) for p in filter(lambda x: x[1] == s, processes): if not p[2] in visited: q . append((p[2], path + [p[0]])) return []
Processes
542ea700734f7daff80007fc
[ "Algorithms" ]
https://www.codewars.com/kata/542ea700734f7daff80007fc
5 kyu
The AKS algorithm for testing whether a number is prime is a polynomial-time test based on the following theorem: A number p is prime if and only if all the coefficients of the polynomial expansion of `(x − 1)^p − (x^p − 1)` are divisible by `p`. For example, trying `p = 3`: (x − 1)^3 − (x^3 − 1) = (x^3 − 3x^2 + 3x − 1) − (x^3 − 1) = − 3x^2 + 3x And all the coefficients are divisible by 3, so 3 is prime. Your task is to code the test function, wich will be given an integer and should return true or false based on the above theorem. You should efficiently calculate every coefficient one by one and stop when a coefficient is not divisible by p to avoid pointless calculations. The easiest way to calculate coefficients is to take advantage of binomial coefficients: http://en.wikipedia.org/wiki/Binomial_coefficient and pascal triangle: http://en.wikipedia.org/wiki/Pascal%27s_triangle . You should also take advantage of the symmetry of binomial coefficients. You can look at these kata: http://www.codewars.com/kata/pascals-triangle and http://www.codewars.com/kata/pascals-triangle-number-2 The kata here only use the simple theorem. The general AKS test is way more complex. The simple approach is a good exercie but impractical. The general AKS test will be the subject of another kata as it is one of the best performing primality test algorithms. The main problem of this algorithm is the big numbers emerging from binomial coefficients in the polynomial expansion. As usual Javascript reach its limit on big integer very fast. (This simple algorithm is far less performing than a trivial algorithm here). You can compare the results with those of this kata: http://www.codewars.com/kata/lucas-lehmer-test-for-mersenne-primes Here, javascript can barely treat numbers bigger than 50, python can treat M13 but not M17.
reference
def aks_test(p): coeff = 1 for i in xrange(p / 2): coeff = coeff * (p - i) / (i + 1) if coeff % p: return False return p > 1
Simple AKS Primality Test
5416d02d932c1df3a3000492
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5416d02d932c1df3a3000492
5 kyu
Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps. Here is an exemple of what the code look like: ``` 0: 0000 1: 0001 2: 0011 3: 0010 4: 0110 5: 0111 6: 0101 7: 0100 8: 1100 ``` The goal of this kata is to build two function bin2gray and gray2bin wich will convert natural binary to Gray Code and vice-versa. We will use the "binary reflected Gray code". The input and output will be arrays of 0 and 1, MSB at index 0. There are "simple" formula to implement these functions. It is a very interesting exercise to find them by yourself. Otherwise you can look here: http://mathworld.wolfram.com/GrayCode.html for formula and more informations. All input will be correct binary arrays.
algorithms
def bin2gray(bits): bits . reverse() return list(reversed([x if i >= len(bits) - 1 or bits[i + 1] == 0 else 1 - x for i, x in enumerate(bits)])) def gray2bin(bits): for i, x in enumerate(bits): if i > 0 and bits[i - 1] != 0: bits[i] = 1 - x return bits
Gray Code
5416ce834c2460b4d300042d
[ "Algorithms" ]
https://www.codewars.com/kata/5416ce834c2460b4d300042d
6 kyu
Imagine the following situations: - A truck loading cargo - A shopper on a budget - A thief stealing from a house using a large bag - A child eating candy very quickly All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with you. The Problem === Given a container with a certain capacity and an assortment of discrete items with various sizes and values (and an infinite supply of each item), determine the combination of items that fits within the container and maximizes the value of the collection. However, **DO NOT** attempt to solve the problem **EXACTLY!** (we will do that in Part 2) The Simplification === Because the optimal collection of items is **MUCH** more difficult to determine than a nearly-optimal collection, this kata will only focus on one specific nearly-optimal solution: the greedy solution. The greedy solution is that which always adds an item to the collection if it has the highest value-to-size ratio. For example, if a "greedy thief" with a 10-Liter knapsack sees two types of items - a 6-Liter item worth $9 (1.5 $/L) - a 5-Liter item worth $5 (1.0 $/L) the thief will take 1 of the 6-Liter items instead of 2 of the 5-Liter items. Although this means the thief will only profit $9 instead of $10, the decision algorithm is much simpler. Maybe the thief is bad at math. Now, go be bad at math! The Kata === Write the function `knapsack` that takes two parameters, `capacity` and `items`, and returns a list of quantities. `capacity` will be a positive number `items` will be an array of arrays of positive numbers that gives the items' sizes and values in the form [[size 1, value 1], [size 2, value 2], ...] `knapsack` will return an array of integers that specifies the quantity of each item to take according to the greedy solution (the order of the quantities must match the order of `items`)
algorithms
def knapsack(capacity, items): ratios = [float(item[1]) / item[0] for item in items] collection = [0] * len(items) space = capacity while any(ratios): best_index = ratios . index(max(ratios)) if items[best_index][0] <= space: collection[best_index] += 1 space -= items[best_index][0] else: ratios[best_index] = 0 return collection
Knapsack Part 1 - The Greedy Solution
53ffbba24e9e1408ee0008fd
[ "Algorithms", "Mathematics", "Sorting" ]
https://www.codewars.com/kata/53ffbba24e9e1408ee0008fd
5 kyu
Write a synchronous function that makes a directory and recursively makes all of its parent directories as necessary. A directory is specified via a sequence of arguments which specify the path. For example: ```javascript mkdirp('/','tmp','made','some','dir') ``` ```coffeescript mkdirp '/','tmp','made','some','dir' ``` ```python mkdirp('/','tmp','made','some','dir') ``` ...will make the directory `/tmp/made/some/dir`. Like the shell command `mkdir -p`, the function you program should be idempotent if the directory already exists. HINT: - In javascript/coffescript, you will want to `require('fs')` and use functions in that library. - [Documentation on <tt>fs</tt>](http://nodejs.org/api/fs.html). - In python, you will want to use the `os` module and `os.path` - [Documentation on <tt>os</tt> module](https://docs.python.org/2/library/os.html) - [Documentation on <tt>os.path</tt> module](https://docs.python.org/2/library/os.path.html)
reference
import os def mkdirp(* directories): """Recursively create all directories as necessary""" try: os . makedirs(os . path . join(* directories)) except OSError: pass
mkdir -p
53e248c9af0d91a45b000e71
[ "Fundamentals" ]
https://www.codewars.com/kata/53e248c9af0d91a45b000e71
6 kyu
### Overview Write a helper function that accepts an argument (Ruby: a Time object / Others: number of seconds) and converts it to a more human-readable format. You need only go up to '_ weeks ago'. ```python to_pretty(0) => "just now" to_pretty(40000) => "11 hours ago" ``` ```ruby to_pretty(Time.now) => "just now" to_pretty(Time.now - 40000) => "11 hours ago" ``` ```javascript toPretty(0) => "just now" toPretty(40000) => "11 hours ago" ``` ### Specifics - The output will be an amount of time, t, included in one of the following phrases: "just now", "[t] seconds ago", "[t] minutes ago", "[t] hours ago", "[t] days ago", "[t] weeks ago". - You will have to handle the singular cases. That is, when t = 1, the phrasing will be one of "a second ago", "a minute ago", "an hour ago", "a day ago", "a week ago". - The amount of time is always rounded down to the nearest integer. For example, if the amount of time is actually 11.73 hours ago, the return value will be "11 hours ago". - Only times in the past will be given, with the range "just now" to "52 weeks ago"
reference
def to_pretty(seconds): if seconds == 0: return "just now" elif seconds == 1: return "a second ago" elif seconds == 60: return f"a minute ago" # 59 elif seconds == 3600: return f"an hour ago" elif seconds == 86400: return f"a day ago" elif seconds == 604800: return f"a week ago" elif seconds < 60: return f" { seconds } seconds ago" # 59 elif seconds < 3600 and seconds > 60: # mini x = seconds / 60 if int(x) == 1: return f"a minute ago" return f" { int ( x )} minutes ago" elif seconds > 3600 and seconds < 86400: # hours x = seconds / 3600 if int(x) == 1: return f"an hour ago" return f" { int ( x )} hours ago" elif seconds > 86400 and seconds < 604800: # days x = seconds / 86400 if int(x) == 1: return f"a day ago" return f" { int ( x )} days ago" elif seconds > 604800: # weeks x = seconds / 604800 if int(x) == 1: return f"a week ago" return f" { int ( x )} weeks ago"
Pretty date
53988ee02c2414dbad000baa
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/53988ee02c2414dbad000baa
6 kyu
[Goldbach's conjecture](http://en.wikipedia.org/wiki/Goldbach%27s_conjecture) is amongst the oldest and well-known unsolved mathematical problems out there. In correspondence with [Leonhard Euler](http://en.wikipedia.org/wiki/Leonhard_Euler) in 1742, German mathematician [Christian Goldbach](http://en.wikipedia.org/wiki/Christian_Goldbach) made a conjecture stating that: *"Every even integer greater than 2 can be written as the sum of two primes"* which is known today as the (strong) Goldbach's conjecture. Even though it's been thoroughly tested and analyzed and seems to be true, it hasn't been proved yet (thus, remaining a conjecture.) Your task is to implement the function in the starter code, taking into account the following: 1. If the argument isn't even and greater than two, return an empty array/tuple. 2. For arguments even and greater than two, return a two-element array/tuple with two prime numbers whose sum is the given input. 3. The two prime numbers must be the farthest ones (the ones with the greatest difference) 4. The first prime number must be the smallest one. A few sample test cases: `checkGoldbach(2)`/`check_goldbach(2)` should return `[]` `checkGoldbach(5)`/`check_goldbach(5)` should return `[]` `checkGoldbach(4)`/`check_goldbach(4)` should return `[2, 2]` `checkGoldbach(6)`/`check_goldbach(6)` should return `[3, 3]` `checkGoldbach(14)`/`check_goldbach(14)` should return `[3, 11]`
algorithms
def isprime(n): # True if n is prime. This is a pretty efficient implementation for i in range(2, int(n * * 0.5) + 1): if n % i == 0: return False return True def check_goldbach(n): if n <= 2: return [] if n % 2: return [] for i in range(2, n / / 2 + 1): if isprime(i) and isprime(n - i): return [i, n - i] return []
Goldbach's Conjecture
537ba77315ddd92659000fec
[ "Algorithms", "Number Theory" ]
https://www.codewars.com/kata/537ba77315ddd92659000fec
6 kyu
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a declaration block. Selector describes which element it matches. Sometimes element is matched to multiple selectors. In this case, element inherits multiple styles, from each rule it matches. Rules can override each other. To solve this problem, each selector has it's own 'specificity' - e.g. weight. The selector with greater specificity overrides the other selector. Your task is to calculate the weights of two selectors and determine which of them will beat the other one. # Examples ``` "body p", "div" ---> return "body p" ".class", "#id" ---> return "#id" "div.big", ".small" ---> return "div.big" ".big", ".small" ---> return ".small" (because it appears later) ``` For simplicity, all selectors in test cases are CSS1-compatible, test cases don't include pseudoclasses, pseudoelements, attribute selectors, etc. Below is an explanation on how to weight two selectors. You can read more about specificity [here](https://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/). The simplest selector type is `tagname` selector. It writes as a simple alphanumeric identifier: eg `body`, `div`, `h1`, etc. It has the least weight. If selectors have multiple elements - the selector with more elements win. For example, `body p` beats `div`, because it refers to 2 (nested) elements rather than 1. Another simple selector is `.class` selector. It begins with dot and refer to element with specific `class` attribute. Class selectors can also be applied to tagname selectors, so `div.red` refer to `<div class="red">` element. They can be grouped, for example, `.red.striped`. Class selector beats tagname selector. The most weighted selector type in stylesheet is `#id` selector. It begins with hash sign and refer to element with specific `id` attribute. It can also be standalone, or applied to an element. Id selector beats both selector types. And the least weighted selector is `*`, which has no specificity and can be beat by any other selector. Selectors can be combined, for example, `body #menu ul li.active` refers to `li` element with `class="active"`, placed inside `ul` element, placed inside element width `id="menu"`, placed inside `body`. Specificity calculation is simple. - Selector with more #id selectors wins. - If both are same, the winner is selector with more .class selectors. - If both are same, selector with more elements wins. - If all of above values are same, the winner is selector that appear last. For example, let's represent the number of ``#id`` , ``.class``, ``tagname`` selectors as array (in order from worst to best): |Selector|Specificity (#id,.class,tagname)| |--------|--------------------------------| | * |0, 0, 0| | span | 0, 0, 1 | | body p | 0, 0, 2 | | .green | 0, 1, 0 | | apple.yellow | 0, 1, 1 | | div.menu li | 0, 1, 2 | | .red .orange | 0, 2, 0 | | div.big .first | 0, 2, 1 | | #john | 1, 0, 0 | | div#john | 1, 0, 1 | | body #john span | 1, 0, 2 | | menu .item #checkout.active | 1, 2, 1 | | #foo div#bar.red .none | 2, 2, 1 |
algorithms
import re def compare(a, b): return a if specificity(a) > specificity(b) else b def specificity(s): return [len(re . findall(r, s)) for r in (r'#\w+', r'\.\w+', r'(^| )\w+')]
Simple CSS selector comparison
5379fdfad08fab63c6000a63
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5379fdfad08fab63c6000a63
5 kyu
For a general presentation of Cycle detection Problem see this kata: http://www.codewars.com/kata/5416f1834c24604c46000696 The greedy algorithm for cycle detection is trivial but ask for storing at least `$\mu + \lambda$` values and perform a comparison on each pair of values, resulting in an overall quadratic complexity. We want to reduce space and time complexity to use cycle detection efficiently. Floyd's develloped a pointer algorithm for cycle detection: Tortoise and the Hare. This algorithm uses only two pointers, which move through the sequence at different speeds. Like the tortoise and the hare in Aesop's Fable. We will now work directly with `$x_0$` and `$f$`. There is 3 phases for the algorithm: 1) Main phase of algorithm: starting with tortoise = `$x_1$`, hare = `$x_2$`, move the tortoise by one `$tortoise=f(tortoise)$` and the hare by two `$hare=f(f(hare))$`. They will eventually be both in the loop and as the distance between them is increasing it will reach a multiple of `$\lambda$` and they will get the same value. 2) At this point the tortoise position has walked `$\nu$` , the hare `$2\nu$`, the distance between them is both `$\nu$` and `$k\lambda$`. So hare starting at his last position moving in cycle one step at a time and tortoise at `$x_0$` moving towards the cycle will intersect at the beginning of the cycle. This is how to find `$\mu$`. 3) Now that they are in the same position, tortoise stay still and hare move in the circle one step at a time, lambda is incremented at each step. So when they meet again we will have `$\lambda$`. You will build a function that take `$f$` and `$x_0$` as parameters and return an array [mu,lambda]. All the function will be periodic after some point. We can find an application of this algorithm for greater purpose, as for exemple Pollard Rho Algorithm for integer factorisation. This kata is followed by: http://www.codewars.com/kata/cycle-detection-brents-tortoise-and-hare
algorithms
def floyd(f, x0): tortoise = f(x0) hare = f(f(x0)) while tortoise != hare: tortoise = f(tortoise) hare = f(f(hare)) mu = 0 tortoise = x0 while tortoise != hare: tortoise = f(tortoise) hare = f(hare) mu += 1 lam = 1 hare = f(tortoise) while tortoise != hare: hare = f(hare) lam += 1 return [mu, lam]
Cycle Detection: Floyd's The Tortoise and the The Hare
5416f1b54c24607e4c00069f
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5416f1b54c24607e4c00069f
5 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Fish are an integral part of any ecosystem. Unfortunately, fish are often seen as high maintenance. Contrary to popular belief, fish actually reduce pond maintenance as they graze on string algae and bottom feed from the pond floor. They also make very enjoyable pets, providing hours of natural entertainment. </pre> <center><img src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/fish.jpg" alt="Driving"></center> # Task <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> In this Kata you are fish in a pond that needs to survive by eating other fish. You can only eat fish that are the same size or smaller than yourself. You must create a function called <font color="#A1A85E">fish</font> that takes a shoal of fish as an input string. From this you must work out how many fish you can eat and ultimately the size you will grow to. </pre> # Rules <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> 1.&nbsp; Your size starts at <font color="#A1A85E">1</font> 2.&nbsp; The shoal string will contain fish integers between <font color="#A1A85E">0-9</font> 3.&nbsp; <font color="#A1A85E">0</font> = algae and wont help you feed. 4.&nbsp; The fish integer represents the size of the fish <font color="#A1A85E">(1-9)</font>. 5.&nbsp; You can only eat fish the <font color="#A1A85E">same</font> size or <font color="#A1A85E">less</font> than yourself. 6.&nbsp; You can eat the fish in any order you choose to maximize your size. 7 &nbsp; You can and only eat each fish once. 8.&nbsp; The bigger fish you eat, the faster you grow. A size 2 fish equals two size 1 fish, size 3 fish equals three size 1 fish, and so on. 9.&nbsp; Your size increments by one each time you reach the amounts below. </pre> # Increase your size Your size will increase depending how many fish you eat and on the size of the fish. This chart shows the amount of size 1 fish you have to eat in order to increase your size. <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="400"><table width="400" border="1" cellspacing="0" cellpadding="0"> <tr> <td width="100" height="40" align="center" valign="middle" bgcolor="#181818"><center>Current size</center></td> <td width="100" align="center" valign="middle" bgcolor="#181818"><center>Amount extra needed for next size</center></td> <td width="100" align="center" valign="middle" bgcolor="#181818"><center>Total size 1 fish</center></td> <td width="100" align="center" valign="middle" bgcolor="#181818"><center>Increase to size</center></td> </tr> <tr> <td width="100" bgcolor="#181818"><center>1</center></td> <td width="100" bgcolor="#181818"><center>4</center></td> <td width="100" bgcolor="#181818"><center>4</center></td> <td width="100" bgcolor="#181818"><center>2</center></td> </tr> <tr> <td width="100" bgcolor="#181818"><center>2</center></td> <td width="100" bgcolor="#181818"><center>8</center></td> <td width="100" bgcolor="#181818"><center>12</center></td> <td width="100" bgcolor="#181818"><center>3</center></td> </tr> <tr> <td width="100" bgcolor="#181818"><center>3</center></td> <td width="100" bgcolor="#181818"><center>12</center></td> <td width="100" bgcolor="#181818"><center>24</center></td> <td width="100" bgcolor="#181818"><center>4</center></td> </tr> <tr> <td width="100" bgcolor="#181818"><center>4</center></td> <td width="100" bgcolor="#181818"><center>16</center></td> <td width="100" bgcolor="#181818"><center>40</center></td> <td width="100" bgcolor="#181818"><center>5</center></td> </tr> <tr> <td width="100" bgcolor="#181818"><center>5</center></td> <td width="100" bgcolor="#181818"><center>20</center></td> <td width="100" bgcolor="#181818"><center>60</center></td> <td width="100" bgcolor="#181818"><center>6</center></td> </tr> <tr> <td width="100" bgcolor="#181818"><center>6</center></td> <td width="100" bgcolor="#181818"><center>24</center></td> <td width="100" bgcolor="#181818"><center>84</center></td> <td width="100" bgcolor="#181818"><center>7</center></td> </tr> </table></td> <td>&nbsp;</td> </tr> </table> Please note: The chart represents fish of size 1<br> # Returns <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Return an integer of the maximum size you could be. </pre> # Example 1 ```c shoal = "11112222" => 4 fish of size 1 => 4 fish of size 2 ``` <li>You eat the 4 fish of size 1 (4 * 1 = 4) which increases your size to 2<br> <li>Now that you are size 2 you can eat the fish that are sized 1 or 2. <li>You then eat the 4 fish of size 2 (4 * 2 = 8) which increases your size to 3 <br> ```ruby fish("11112222") => 3 ``` ```python fish("11112222") => 3 ``` ```javascript fish("11112222") => 3 ``` ```csharp fish("11112222") => 3 ``` ```vb Fish.Play("11112222") => 3 ``` # Example 2 ```c shoal = "111111111111" => 12 fish of size 1 ``` <li>You eat the 4 fish of size 1 (4 * 1 = 4) which increases your size to 2<br> <li>You then eat the remainding 8 fish of size 1 (8 * 1 = 8) which increases your size to 3 ```ruby fish("111111111111") => 3 ``` ```python fish("111111111111") => 3 ``` ```javascript fish("111111111111") => 3 ``` ```csharp fish("111111111111") => 3 ``` ```vb Fish.Play("111111111111") => 3 ``` Good luck and enjoy!<br> # Kata Series If you enjoyed this, then please try one of my other Katas. Any feedback, translations and grading of beta Katas are greatly appreciated. Thank you. <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58663693b359c4a6560001d6" target="_blank">Maze Runner</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58693bbfd7da144164000d05" target="_blank">Scooby Doo Puzzle</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/7KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/586a1af1c66d18ad81000134" target="_blank">Driving License</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/586c0909c1923fdb89002031" target="_blank">Connect 4</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/586e6d4cb98de09e3800014f" target="_blank">Vending Machine</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/587136ba2eefcb92a9000027" target="_blank">Snakes and Ladders</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58a848258a6909dd35000003" target="_blank">Mastermind</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58b2c5de4cf8b90723000051" target="_blank">Guess Who?</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58f5c63f1e26ecda7e000029" target="_blank">Am I safe to drive?</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58f5c63f1e26ecda7e000029" target="_blank">Mexican Wave</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/58fdcc51b4f81a0b1e00003e" target="_blank">Pigs in a Pen</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/590300eb378a9282ba000095" target="_blank">Hungry Hippos</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/5904be220881cb68be00007d" target="_blank">Plenty of Fish in the Pond</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/590adadea658017d90000039" target="_blank">Fruit Machine</a></span> <span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/>&nbsp;<a href="https://www.codewars.com/kata/591eab1d192fe0435e000014" target="_blank">Car Park Escape</a></span>
reference
def fish(shoal): eaten, size, target = 0, 1, 4 for f in sorted(map(int, shoal)): if f > size: break eaten += f if eaten >= target: size += 1 target += 4 * size return size
Plenty of Fish in the Pond
5904be220881cb68be00007d
[ "Fundamentals" ]
https://www.codewars.com/kata/5904be220881cb68be00007d
6 kyu
Well here you are again, still staring blankly at the same arrivals/departures flap display... <div style="width:75%"><img src="http://www.airport-arrivals-departures.com/img/meta/1200_630_arrivals-departures.png"></div> # Kata Task ## Part #1 In <a style="color:green" href="https://www.codewars.com/kata/57feb00f08d102352400026e">Part #1 of this series</a> you already figured out how the flap display mechanism works. You now know what the updated display will look like after applying a set of rotor moves. *If you haven't already completed Part 1, then now is a good time to do it!* ## Part #2 Now in this current Kata your task is the opposite. It's the same board with the same rules... But this time you are required to return the set of ```rotor``` moves needed to transform the display from the ```before``` to the ```after``` state. Look at the example tests for guidance. And good luck! <span style='color:red'>:-)</span> # Notes * For ```Java``` and ```C#```, a convenient String of the rotor characters provided in ```Preloaded.ALPHABET```
algorithms
def flat_rotors(lines_before, lines_after): ln = len(ALPHABET) def nxt_rotor(wb, wa): rot = [] for lb, la in zip(wb, wa): rot . append((ALPHABET . index(la) - ALPHABET . index(lb) - sum(rot)) % ln) return rot return [nxt_rotor(lnb, lna) for lnb, lna in zip(lines_before, lines_after)]
Airport Arrivals/Departures - #2
584cfd7e2609c8ab4d0000e3
[ "Algorithms" ]
https://www.codewars.com/kata/584cfd7e2609c8ab4d0000e3
6 kyu
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, `134468`. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, `66420`. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, `155349`. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (`525`) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is `538`. Surprisingly, bouncy numbers become more and more common and by the time we reach `21780` the proportion of bouncy numbers is equal to 90%. #### Your Task Complete the `bouncyRatio` function. The input will be the target ratio. The output should be the smallest number such that the proportion of bouncy numbers reaches the target ratio. You should throw an `Error` for a ratio less than 0% or greater than 99%. **Source** - https://projecteuler.net/problem=112 **Updates** - 26/10/2015: Added a higher precision test case.
games
def inc(x): return all(str(x)[p] <= str(x)[p + 1] for p in range(len(str(x)) - 1)) def dec(x): return all(str(x)[p] >= str(x)[p + 1] for p in range(len(str(x)) - 1)) def bouncy(x): return not (inc(x) or dec(x)) def bouncy_ratio(percent): n, bouncy_count = 99, 0 while bouncy_count < percent * n: n += 1 bouncy_count += bouncy(n) return n
Ratio of Bouncy Numbers
562b099becfe844f3800000a
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/562b099becfe844f3800000a
5 kyu
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death. Each robot will be represented by an object. You will be given two robot objects, and an object of battle tactics and how much damage they produce. Each robot will have a name, hit points, speed, and then a list of battle tactics they are to perform in order. Whichever robot has the best speed, will attack first with one battle tactic. Your job is to decide who wins. Example: ```javascript robot1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot1, robot2, tactics) -> "Missile Bob has won the fight." ``` ```coffeescript robot1 = name: "Rocky" health: 100 speed: 20 tactics: [ "punch", "punch", "laser", "missile" ] robot2 = name: "Missile Bob" health: 100 speed: 21 tactics: [ "missile", "missile", "missile", "missile" ] tactics = punch: 20 laser: 30 missile: 35 fight(robot1, robot2, tactics) # "Missile Bob has won the fight." ``` ```ruby robot1 = { "name" => "Rocky", "health" => 100, "speed" => 20, "tactics" => ["punch", "punch", "laser", "missile"] } robot2 = { "name" => "Missile Bob", "health" => 100, "speed" => 21, "tactics" => ["missile", "missile", "missile", "missile"] } tactics = { "punch" => 20, "laser" => 30, "missile" => 35 } fight(robot1, robot2, tactics) # "Missile Bob has won the fight." ``` ```java robot1.getName() => "Rocky" robot1.getHealth() => 100 robot1.getSpeed() => 20 robot1.getTactics() => ["punch", "punch", "laser", "missile"] robot2.getName() => "Missile Bob" robot2.getHealth() => 100 robot2.getSpeed() => 21 robot2.getTactics() => ["missile", "missile", "missile", "missile"] tactics = { "punch" => 20, "laser" => 30, "missile" => 35 } fight(Robot robot1, Robot robot2, Map<String, Integer> tactics) -> "Missile Bob has won the fight." ``` ```python robot_1 = { "name": "Rocky", "health": 100, "speed": 20, "tactics": ["punch", "punch", "laser", "missile"] } robot_2 = { "name": "Missile Bob", "health": 100, "speed": 21, "tactics": ["missile", "missile", "missile", "missile"] } tactics = { "punch": 20, "laser": 30, "missile": 35 } fight(robot_1, robot_2, tactics) -> "Missile Bob has won the fight." ``` robot2 uses the first tactic, "missile" because he has the most speed. This reduces robot1's health by 35. Now robot1 uses a punch, and so on. **Rules** - A robot with the most speed attacks first. If they are tied, the first robot passed in attacks first. - Robots alternate turns attacking. Tactics are used in order. - A fight is over when a robot has 0 or less health or both robots have run out of tactics. - A robot who has no tactics left does no more damage, but the other robot may use the rest of his tactics. - If both robots run out of tactics, whoever has the most health wins. If one robot has 0 health, the other wins. Return the message "{Name} has won the fight." - If both robots run out of tactics and are tied for health, the fight is a draw. Return "The fight was a draw." **To Java warriors** `Robot` class is immutable. <div style="width: 320px; text-align: center; color: white; border: white 1px solid;"> Check out my other 80's Kids Katas: </div> <div> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-1-how-many-licks-does-it-take'><span style='color:#00C5CD'>80's Kids #1:</span> How Many Licks Does It Take</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-2-help-alf-find-his-spaceship'><span style='color:#00C5CD'>80's Kids #2:</span> Help Alf Find His Spaceship</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-3-punky-brewsters-socks'><span style='color:#00C5CD'>80's Kids #3:</span> Punky Brewster's Socks</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-4-legends-of-the-hidden-temple'><span style='color:#00C5CD'>80's Kids #4:</span> Legends of the Hidden Temple</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-5-you-cant-do-that-on-television'><span style='color:#00C5CD'>80's Kids #5:</span> You Can't Do That on Television</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-6-rock-em-sock-em-robots'><span style='color:#00C5CD'>80's Kids #6:</span> Rock 'Em, Sock 'Em Robots</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-7-shes-a-small-wonder'><span style='color:#00C5CD'>80's Kids #7:</span> She's a Small Wonder</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-8-the-secret-world-of-alex-mack'><span style='color:#00C5CD'>80's Kids #8:</span> The Secret World of Alex Mack</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-9-down-in-fraggle-rock'><span style='color:#00C5CD'>80's Kids #9:</span> Down in Fraggle Rock </a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/80-s-kids-number-10-captain-planet'><span style='color:#00C5CD'>80's Kids #10:</span> Captain Planet </a><br /> </div>
reference
def fight(robot_1, robot_2, tactics): attack, defend = (robot_1, robot_2) if robot_1['speed'] >= robot_2['speed'] else ( robot_2, robot_1) while attack['health'] > 0: if attack['tactics']: defend['health'] -= tactics[attack['tactics']. pop()] elif not defend['tactics']: break attack, defend = defend, attack if attack['health'] == defend['health']: return "The fight was a draw." return "{} has won the fight." . format((defend if attack['health'] < defend['health'] else attack)['name'])
80's Kids #6: Rock 'Em, Sock 'Em Robots
566b490c8b164e03f8000002
[ "Fundamentals" ]
https://www.codewars.com/kata/566b490c8b164e03f8000002
5 kyu
Don't Drink the Water Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom. ``` ====================== | Density Chart | ====================== | Honey | H | 1.36 | | Water | W | 1.00 | | Alcohol | A | 0.87 | | Oil | O | 0.80 | ---------------------- { { { 'H', 'H', 'W', 'O' }, { 'O','O','O','O' }, { 'W', 'W', 'O', 'W' }, => { 'W','W','W','W' }, { 'H', 'H', 'O', 'O' } { 'H','H','H','H' } } } ``` The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.
algorithms
def separate_liquids(glass): chain = sorted(sum(glass, []), key='HWAO' . index) return [[chain . pop() for c in ro] for ro in glass]
Don't Drink the Water
562e6df5cf2d3908ad00019e
[ "Algorithms", "Arrays", "Sorting", "Lists" ]
https://www.codewars.com/kata/562e6df5cf2d3908ad00019e
5 kyu
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. ## Example: (Input --> Output) ``` 1 --> [1] 2 --> [1] 4 --> [1, 4] ``` The parameter `n` will always be a `number >= 1`.
games
def off(n): return [i * i for i in range(1, int(n * * 0.5) + 1)]
Disgruntled Employee
541103f0a0e736c8e40011d5
[ "Logic", "Mathematics", "Sorting", "Arrays", "Puzzles" ]
https://www.codewars.com/kata/541103f0a0e736c8e40011d5
6 kyu
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 ```javascript 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" ``` ```coffeescript 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" ``` ```csharp Kata.FridayTheThirteenths(1999, 2000) # returns "8/13/1999 10/13/2000" Kata.FridayTheThirteenths(2014, 2015) # returns "6/13/2014 2/13/2015 3/13/2015 11/13/2015" Kata.FridayTheThirteenths(2000) # returns "10/13/2000" ``` ```cobol FridayTheThirteenths(1999, 2000) => result = "8/13/1999 10/13/2000" FridayTheThirteenths(2014, 2015) => result = "6/13/2014 2/13/2015 3/13/2015 11/13/2015" FridayTheThirteenths(2000, 0000) => returns = "10/13/2000" ```
reference
from datetime import date def friday_the_thirteenths(start, end=None): return ' ' . join(f' { m } /13/ { y } ' for y in range(start, 1 + (end or start)) for m in range(1, 13) if date(y, m, 13). weekday() == 4)
Friday the 13ths
540954232a3259755d000039
[ "Date Time", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/540954232a3259755d000039
6 kyu
# Making Change Complete the method that will determine the minimum number of coins needed to make change for a given amount in American currency. Coins used will be half-dollars, quarters, dimes, nickels, and pennies, worth 50¢, 25¢, 10¢, 5¢ and 1¢, respectively. They'll be represented by the symbols `H`, `Q`, `D`, `N` and `P` (symbols in Ruby, strings in in other languages) The argument passed in will be an integer representing the value in cents. The return value should be a hash/dictionary/object with the symbols as keys, and the numbers of coins as values. Coins that are not used should not be included in the hash. If the argument passed in is 0, then the method should return an empty hash. ## Examples ```ruby make_change(0) #--> {} make_change(1) #--> {:P=>1} make_change(43) #--> {:Q=>1, :D=>1, :N=>1, :P=>3} make_change(91) #--> {:H=>1, :Q=>1, :D=>1, :N=>1, :P=>1} ``` ```python make_change(0) #--> {} make_change(1) #--> {"P":1} make_change(43) #--> {"Q":1, "D":1, "N":1, "P":3} make_change(91) #--> {"H":1, "Q":1, "D":1, "N":1, "P":1} ``` ```javascript makeChange(0) //--> {} makeChange(1) //--> {"P":1} makeChange(43) //--> {"Q":1, "D":1, "N":1, "P":3} makeChange(91) //--> {"H":1, "Q":1, "D":1, "N":1, "P":1} ``` ```elixir Currency.make_change(0) #--> %{} Currency.make_change(1) #--> %{:P=>1} Currency.make_change(43) #--> %{:Q=>1, :D=>1, :N=>1, :P=>3} Currency.make_change(91) #--> %{:H=>1, :Q=>1, :D=>1, :N=>1, :P=>1} ``` #### **If you liked this kata, check out [Part 2](https://www.codewars.com/kata/making-change-part-2/ruby).**
algorithms
BASE = {"H": 50, "Q": 25, "D": 10, "N": 5, "P": 1} def make_change(n): r = {} for x, y in BASE . items(): if n >= y: r[x], n = divmod(n, y) return r
Making Change
5365bb5d5d0266cd010009be
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5365bb5d5d0266cd010009be
6 kyu
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](http://en.wikipedia.org/wiki/Ordinal_indicator#English): * 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).
algorithms
def numberToOrdinal(n): if not (11 <= n % 100 <= 13): if n % 10 == 1: return f' { n } st' elif n % 10 == 2: return f' { n } nd' elif n % 10 == 3: return f' { n } rd' return f' { n } th' if n else '0'
Adding ordinal indicator suffixes to numbers
52dca71390c32d8fb900002b
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52dca71390c32d8fb900002b
6 kyu
A [Word Square](https://en.wikipedia.org/wiki/Word_square) is a set of words written out in a square grid, such that the same words can be read both horizontally and vertically. The number of words, equal to the number of letters in each word, is known as the *order* of the square. For example, this is an *order* `5` square found in the ruins of Herculaneum: ![](https://i.gyazo.com/e226262e3ada421d4323369fb6cf66a6.jpg) Given a string of various uppercase `letters`, check whether a *Word Square* can be formed from it. Note that you should use each letter from `letters` the exact number of times it occurs in the string. If a *Word Square* can be formed, return `true`, otherwise return `false`. __Example__ * For `letters = "SATORAREPOTENETOPERAROTAS"`, the output should be `WordSquare(letters) = true`. It is possible to form a *word square* in the example above. * For `letters = "AAAAEEEENOOOOPPRRRRSSTTTT"`, (which is sorted form of `"SATORAREPOTENETOPERAROTAS"`), the output should also be `WordSquare(letters) = true`. * For `letters = "NOTSQUARE"`, the output should be `WordSquare(letters) = false`. __Input/Output__ * [input] string letters A string of uppercase English letters. Constraints: `3 ≤ letters.length ≤ 100`. * [output] boolean `true`, if a Word Square can be formed; `false`, if a Word Square cannot be formed.
games
from collections import Counter def word_square(ls): n = int(len(ls) * * 0.5) return n * n == len(ls) and sum(i % 2 for i in Counter(ls). values()) <= n
WordSquare
578e07d590f2bb8d3300001d
[ "Puzzles" ]
https://www.codewars.com/kata/578e07d590f2bb8d3300001d
5 kyu
# Introduction: Reversi is a game usually played by 2 people on a 8x8 board. Here we're only going to consider a single 8x1 row. Players take turns placing pieces, which are black on one side and white on the other, onto the board with their colour facing up. If one or more of the opponents pieces are sandwiched by the piece just played and another piece of the current player's colour, the opponents pieces are flipped to the current players colour. Note that the flipping stops when the first piece of the player's colour is reached. # Task: Your task is to take an array of moves and convert this into a string representing the state of the board after all those moves have been played. # Input: The input to your function will be an array of moves. Moves are represented by integers from 0 to 7 corresponding to the 8 squares on the board. Black plays first, and black and white alternate turns. Input is guaranteed to be valid. (No duplicates, all moves in range, but array may be empty) # Output: 8 character long string representing the final state of the board. Use '*' for black and 'O' for white and '.' for empty. # Examples: ```ruby reversi_row([]) # '........' reversi_row([3]) # '...*....' reversi_row([3,4]) # '...*O...' reversi_row([3,4,5]) # '...***..' ``` ```python reversi_row([]) # '........' reversi_row([3]) # '...*....' reversi_row([3,4]) # '...*O...' reversi_row([3,4,5]) # '...***..' ``` ```javascript reversiRow([]) // '........' reversiRow([3]) // '...*....' reversiRow([3,4]) // '...*O...' reversiRow([3,4,5]) // '...***..' ``` ```coffeescript reversiRow([]) # '........' reversiRow([3]) # '...*....' reversiRow([3,4]) # '...*O...' reversiRow([3,4,5]) # '...***..' ```
algorithms
from re import sub def reversi_row(moves): current = '.' * 8 for i, x in enumerate(moves): c1, c2 = "Ox" if i & 1 else "xO" left = sub(r"(?<={}){}+$" . format(c1, c2), lambda r: c1 * len(r . group()), current[: x]) right = sub(r"^{}+(?={})" . format(c2, c1), lambda r: c1 * len(r . group()), current[x + 1:]) current = left + c1 + right return current . replace('x', '*')
Reversi row rudiments
55aa92a66f9adfb2da00009a
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/55aa92a66f9adfb2da00009a
5 kyu
Rule 30 is a one-dimensional binary cellular automaton. You can have some information here: https://en.wikipedia.org/wiki/Rule_30 Complete the function that takes as input an array of `0`s and `1`s and a non-negative integer `n` that represents the number of iterations. This function has to perform the n<sup>th</sup> iteration of **Rule 30** with the given input. The rule to derive a cell from itself and its neigbour is: Current cell | 000 | 001 | 010 | 011 | 100 | 101 | 110 | 111 :-------------|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---: **New cell** | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 As you can see the new state of a certain cell depends on his neighborhood. In *Current cell* you have the *nth* cell with its left and right neighbor, for example the first configuration is **000**: * left neighbor = 0 * current cell = 0 * right neighbor = 0 The result for the current cell is **0**, as reported in the **New cell** row. You also have to pay attention to the following things: * the borders of the list are always 0 * you have to return an array of 0 and 1 Here a small example step by step, starting from the list **[1]** and iterating 5 times: * We have only one element so first of all we have to follow the rules adding the border, so the result will be **[0, 1, 0]** * Now we can apply the rule 30 to all the elements and the result will be **[1, 1, 1]** (first iteration) * Then, after continuing this way for 4 times, the result will be **[1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1]** ~~~if:python In Python you can also use a support function to print the sequence named `printRule30`. This function takes as parameters the current list of 0 and 1 to print, the max level that you can reach (number of iterations) and the length of initial array. ```python def printRule30(list_, maxLvl, startLen): ... ``` The last two parameters are optional and are useful if you are printing each line of the iteration to center the result like this: ░░▓░░ -> step 1 ░▓▓▓░ -> step 2 ▓▓░░▓ -> step 3 If you pass only the array of 0 and 1 the previous result for each line will be like this: ▓ -> step 1 ▓▓▓ -> step 2 ▓▓░░▓ -> step 3 **Note:** the function can print only the current list that you pass to it, so you have to use it in the proper way during the interactions of the rule 30. ~~~ ~~~if:lambdacalc #### Encodings `purity: LetRec` `numEncoding: Scott` export constructors `nil, cons` and deconstructor `foldr` for your `List` encoding ~~~
games
def rule30(a, n): for _ in range(n): a = [int(0 < 4 * x + 2 * y + z < 5) for x, y, z in zip([0, 0] + a, [0] + a + [0], a + [0, 0])] return a
Rule 30
5581e52ac76ffdea700000c1
[ "Lists", "Arrays", "Binary", "Puzzles" ]
https://www.codewars.com/kata/5581e52ac76ffdea700000c1
5 kyu
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: ```javascript var values = [5, 4, 3, 2, 1]; minimumSum(values, 2); // should return 1+2 = 3 maximumSum(values, 3); // should return 3+4+5 = 12 ``` ```coffeescript values = [5, 4, 3, 2, 1] minimumSum values, 2 # should return 1+2 = 3 maximumSum values, 3 # should return 3+4+5 = 12 ``` ```python values = [5, 4, 3, 2, 1]; minimum_sum(values, 2) #should return 1 + 2 = 3 maximum_sum(values, 3) #should return 3 + 4 + 5 = 12 ``` ```haskell minimumSum [1..5] 2 `shouldBe` 1 + 2 minimumSum [1..5] 3 `shouldBe` 1 + 2 + 3 maximumSum [1..5] 2 `shouldBe` 4 + 5 maximumSum [1..5] 3 `shouldBe` 3 + 4 + 5 ``` 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.
reference
def minimum_sum(values, n): '''sum the n smallest integers in the array values (not necessarily ordered)''' return sum(sorted(values)[: n]) def maximum_sum(values, n): '''sum the n largest integers in the array values (not necessarily ordered)''' return sum(sorted(values, reverse=True)[: n])
Exercise in Summing
52cd0d600707d0abcd0003eb
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/52cd0d600707d0abcd0003eb
6 kyu
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 <code>autocorrect</code> that takes a string and replaces all instances of <code>"you"</code> or <code>"u"</code> (not case sensitive) with <code>"your sister"</code> (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: <ul> <li>"youuuuu" with any number of u characters tacked onto the end</li> <li>"u" at the beginning, middle, or end of a string, but NOT part of a word</li> <li>"you" but NOT as part of another word like youtube or bayou</li> </ul> <p>
algorithms
import re def autocorrect(input): return re . sub(r'(?i)\b(u|you+)\b', "your sister", input)
Evil Autocorrect Prank
538ae2eb7a4ba8c99b000439
[ "Strings", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/538ae2eb7a4ba8c99b000439
6 kyu
It's a Pokemon battle! Your task is to calculate the damage that a particular move would do using the following formula (not the actual one from the game): ```javascript damage = 50 * (attack / defense) * effectiveness ``` Where: * attack = your attack power * defense = the opponent's defense * effectiveness = the effectiveness of the attack based on the matchup (see explanation below) Effectiveness: Attacks can be super effective, neutral, or not very effective depending on the matchup. For example, water would be super effective against fire, but not very effective against grass. * Super effective: 2x damage * Neutral: 1x damage * Not very effective: 0.5x damage To prevent this kata from being tedious, you'll only be dealing with four types: `fire`, `water`, `grass`, and `electric`. Here is the effectiveness of each matchup: * `fire > grass` * `fire < water` * `fire = electric` * `water < grass` * `water < electric` * `grass = electric` For this kata, any type against itself is not very effective. Also, assume that the relationships between different types are symmetric (if `A` is super effective against `B`, then `B` is not very effective against `A`). The function you must implement takes in: 1. your type 2. the opponent's type 3. your attack power 4. the opponent's defense
games
import math effectiveness = { "electric": { "electric": 0.5, "fire": 1, "grass": 1, "water": 2 }, "fire": { "electric": 1, "fire": 0.5, "grass": 2, "water": 0.5 }, "grass": { "electric": 1, "fire": 0.5, "grass": 0.5, "water": 2 }, "water": { "electric": 0.5, "fire": 2, "grass": 0.5, "water": 0.5 } } def calculate_damage(your_type, opponent_type, attack, defense): return math . ceil(50 * (attack / defense) * effectiveness[your_type][opponent_type])
Pokemon Damage Calculator
536e9a7973130a06eb000e9f
[ "Arrays", "Games", "Strings", "Puzzles" ]
https://www.codewars.com/kata/536e9a7973130a06eb000e9f
6 kyu
Previously on Codewars... "[Triangular numbers](http://en.wikipedia.org/wiki/Triangular_number) 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](http://www.codewars.com/dojo/katas/525e5a1cb735154b320002c8) 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: 1. The nth triangular number is: ```t(n) = n + t(n-1)``` 2. 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.
reference
def tetrahedron(size): return size * (size + 1) * (size + 2) / / 6
A tetrahedron of cannonballs
530e259c7bc88a4ab9000754
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/530e259c7bc88a4ab9000754
6 kyu
You are given a sequence of valid words and a string. Test if the string is made up by one or more words from the array. <h3>Task</h3> Test if the string can be entirely formed by consecutively concatenating words of the dictionary. For example: ``` dictionary: ["code", "wars"] s1: "codewars" => true -> match 'code', 'wars' s2: "codewar" => false -> match 'code', unmatched 'war' ``` One word from the dictionary can be used several times.
algorithms
def valid_word(seq, word): return not word or any(valid_word(seq, word[len(x):]) for x in seq if word . startswith(x))
Valid string
52f3bb2095d6bfeac2002196
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52f3bb2095d6bfeac2002196
6 kyu
## 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 -> <jump out>) ``` *All tests for this Kata are randomly generated.*
algorithms
def solution(a): if (len(a) == 0): return - 1 pos = 0 jump = 0 while pos >= 0 and pos < len ( a ): if ( a [ pos ] == 0 ): return - 1 step = a [ pos ] a [ pos ] = 0 pos += step jump += 1 return jump
Frog jumping
536950ffc8a5ca9982001371
[ "Fundamentals", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/536950ffc8a5ca9982001371
6 kyu
**Step 1:** Create a function called `encode()` to replace all the lowercase vowels in a given string with numbers according to the following pattern: ``` a -> 1 e -> 2 i -> 3 o -> 4 u -> 5 ``` For example, `encode("hello")` would return `"h2ll4"`. There is no need to worry about uppercase vowels in this kata. **Step 2:** Now create a function called `decode()` to turn the numbers back into vowels according to the same pattern shown above. For example, `decode("h3 th2r2")` would return `"hi there"`. For the sake of simplicity, you can assume that any numbers passed into the function will correspond to vowels.
reference
def encode(s, t=str . maketrans("aeiou", "12345")): return s . translate(t) def decode(s, t=str . maketrans("12345", "aeiou")): return s . translate(t)
The Vowel Code
53697be005f803751e0015aa
[ "Arrays", "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/53697be005f803751e0015aa
6 kyu
A prime number is an integer greater than 1 that is only evenly divisible by itself and 1. Write your own Primes class with class method <code>Primes.first(n)</code> that returns an array of the first n prime numbers. For example: <pre><code>Primes.first(1) # => [2] Primes.first(2) # => [2, 3] Primes.first(5) # => [2, 3, 5, 7, 11] Primes.first(20).last(5) # => [53, 59, 61, 67, 71]</code></pre> Note: An inefficient algorithm will time out. **[<font color="cyan">Memoization</font>](https://en.wikipedia.org/wiki/Memoization)** may help. More info on primes [here](http://en.wikipedia.org/wiki/Prime_number).
algorithms
def rwh_primes2(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n % 6 > 1) n = {0: n, 1: n - 1, 2: n + 4, 3: n + 3, 4: n + 2, 5: n + 1}[n % 6] sieve = [True] * (n / 3) sieve[0] = False for i in xrange(int(n * * 0.5) / 3 + 1): if sieve[i]: k = 3 * i + 1 | 1 sieve[((k * k) / 3):: 2 * k] = [False] * \ ((n / 6 - (k * k) / 6 - 1) / k + 1) sieve[(k * k + 4 * k - 2 * k * (i & 1)) / 3:: 2 * k] = [False] * \ ((n / 6 - (k * k + 4 * k - 2 * k * (i & 1)) / 6 - 1) / k + 1) return [2, 3] + [3 * i + 1 | 1 for i in xrange(1, n / 3 - correction) if sieve[i]] class Primes: @ classmethod def first(self, n): return rwh_primes2(20 * n)[: n]
First n Prime Numbers
535bfa2ccdbf509be8000113
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/535bfa2ccdbf509be8000113
5 kyu
### The task Your task, is to calculate the minimal number of moves to win the game "Towers of Hanoi", with given number of disks. ### What is "Towers of Hanoi"? Towers of Hanoi is a simple game consisting of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1. Only one disk can be moved at a time. 2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3. No disk may be placed on top of a smaller disk.
games
def hanoi(disks): return 2 * * disks - 1
Hanoi record
534eb5ad704a49dcfa000ba6
[ "Fundamentals", "Algorithms", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/534eb5ad704a49dcfa000ba6
6 kyu
Write a function that returns a (custom) [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) sequence of the numbers `1 to 100`. The function should be able to take up to 4 arguments: * The 1st and 2nd arguments are strings, `"Fizz"` and `"Buzz"` by default; * The 3rd and 4th arguments are integers, `3` and `5` by default. Thus, when the function is called without arguments, it will return the classic FizzBuzz sequence up to 100: ``` [ 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, ... 14, "FizzBuzz", 16, 17, ... 98, "Fizz", "Buzz" ] ``` When the function is called with (up to 4) arguments, it should return a custom FizzBuzz sequence, for example: ``` ('Hey', 'There') --> [ 1, 2, "Hey", 4, "There", "Hey", ... ] ('Foo', 'Bar', 2, 3) --> [ 1, "Foo", "Bar", "Foo", 5, "FooBar", 7, ... ] ``` ## Examples ```ruby fizz_buzz_custom[15] # returns 16 fizz_buzz_custom[44] # returns "FizzBuzz" (45 is divisible by 3 and 5) fizz_buzz_custom('Hey', 'There')[25] # returns 26 fizz_buzz_custom('Hey', 'There')[11] # returns "Hey" (12 is divisible by 3) fizz_buzz_custom("What's ", "up?", 3, 7)[80] # returns "What's " (81 is divisible by 3) ``` ```javascript 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) ``` ```python fizz_buzz_custom()[15] # returns 16 fizz_buzz_custom()[44] # returns "FizzBuzz" (45 is divisible by 3 and 5) fizz_buzz_custom('Hey', 'There')[25] # returns 26 fizz_buzz_custom('Hey', 'There')[11] # returns "Hey" (12 is divisible by 3) fizz_buzz_custom("What's ", "up?", 3, 7)[80] # returns "What's " (81 is divisible by 3) ``` ```if:python The function must return the sequence as a `list`. ```
reference
def fizz_buzz_custom(string_one="Fizz", string_two="Buzz", num_one=3, num_two=5): result = [] for i in range(1, 101): x = "" if i % num_one == 0: x += string_one if i % num_two == 0: x += string_two result . append(x or i) return result
Custom FizzBuzz Array
5355a811a93a501adf000ab7
[ "Arrays", "Logic", "Fundamentals" ]
https://www.codewars.com/kata/5355a811a93a501adf000ab7
6 kyu
We want to approximate the `sqrt` function. Usually this function takes a floating point number and returns another floating point number, but in this kata we're going to work with _integral_ numbers instead. Your task is to write a function that takes an integer `n` and returns either - an integer `k` if `n` is a square number, such that `k * k == n` or - a range `(k, k+1)`, such that `k * k < n` and `n < (k+1) * (k+1)`. ### Examples ```python sqrt_approximation(4) --> 2 sqrt_approximation(5) --> [2,3] ``` ```javascript assert.deepEqual( sqrtApproximation(4), 2 ); assert.deepEqual( sqrtApproximation(5), [2,3] ); ``` ```haskell sqrtInt :: Integral n => n -> Either (n,n) n sqrtInt 4 `shouldBe` Right 2 sqrtInt 5 `shouldBe` Left (2,3) ``` ```csharp Assert.AreEqual(2, Kata.SqrtApproximation(4)); Assert.AreEqual(new int[] { 2,3 }, Kata.SqrtApproximation(5)); ``` ```cpp Assert::That(sqrtApproximation(4), Equals(std::vector<int>{2})); Assert::That(sqrtApproximation(5), Equals(std::vector<int>{2,3})); ``` Note : `pow` and `sqrt` functions are disabled. ### Remarks In dynamic languages, return either a single value or an array/list. In Haskell, use `Either`.
algorithms
def sqrt_approximation(number): i = 0 while i * i < number: i += 1 return i if i * i == number else [i - 1, i]
Sqrt approximation
52ecde1244751a799b00018a
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/52ecde1244751a799b00018a
6 kyu
Write a function that outputs the transpose of a matrix - a new matrix where the columns and rows of the original are swapped. For example, the transpose of: | 1 2 3 | | 4 5 6 | is | 1 4 | | 2 5 | | 3 6 | The input to your function will be an array of matrix rows. You can assume that each row has the same length, and that the height and width of the matrix are both positive. ~~~if:lambdacalc #### Encodings purity: `LetRec` numEncoding: `None` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding ~~~
algorithms
def transpose(matrix): return list(map(list, zip(* matrix)))
Matrix Transpose
52fba2a9adcd10b34300094c
[ "Mathematics", "Algebra", "Matrix", "Algorithms" ]
https://www.codewars.com/kata/52fba2a9adcd10b34300094c
6 kyu
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it: * All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted in ascending order. * All words that begin with an upper case letter should come after that, and should be sorted in descending order. If a word appears multiple times in the sentence, it should be returned multiple times in the sorted sentence. Any punctuation must be discarded. ## Example For example, given the input string `"Land of the Old Thirteen! Massachusetts land! land of Vermont and Connecticut!"`, your method should return `"and land land of of the Vermont Thirteen Old Massachusetts Land Connecticut"`. Lower case letters are sorted `a -> l -> l -> o -> o -> t` and upper case letters are sorted `V -> T -> O -> M -> L -> C`.
algorithms
from string import punctuation t = str . maketrans("", "", punctuation) def pseudo_sort(s): a = s . translate(t). split() b = sorted(x for x in a if x[0]. islower()) c = sorted((x for x in a if x[0]. isupper()), reverse=True) return " " . join(b + c)
Sort sentence pseudo-alphabetically
52dffa05467ee54b93000712
[ "Sorting", "Strings", "Algorithms" ]
https://www.codewars.com/kata/52dffa05467ee54b93000712
6 kyu
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 a function that receives a list, list size will always be at least 3 numbers. The missing term will never be the first or last one. ## Example ```php findMissing([1, 3, 5, 9, 11]) == 7 ``` ```csharp Kata.FindMissing(new List<int> {1, 3, 5, 9, 11}) => 7 ``` ```fsharp findMissing [| 1; 3; 5; 9; 11 |] = 7 ``` ```python find_missing([1, 3, 5, 9, 11]) == 7 ``` ```swift find_missing([1, 3, 5, 9, 11]) == 7 ``` ```ruby findMissing([1, 3, 5, 9, 11]) == 7 ``` ```c find_missing((const int[]){1,3,5,9,11}, 5) => 7 ``` ```nasm nums: dw 1,3,5,9,11 mov rdi, nums mov rsi, 5 call find_missing ; EAX <- 7 ``` ```factor { 1 3 5 9 11 } find-missing ! => 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!
algorithms
def find_missing(sequence): t = sequence return (t[0] + t[- 1]) * (len(t) + 1) / 2 - sum(t)
Find the missing term in an Arithmetic Progression
52de553ebb55d1fca3000371
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/52de553ebb55d1fca3000371
6 kyu
**Introduction** Ordinal numbers are used to tell the position of something in a list. Unlike regular numbers, they have a special suffix added to the end of them. **Task** Your task is to write the `ordinal(number, brief)` function. `number` will be an integer. You need to find the ordinal suffix of said number. `brief` is an optional parameter and defaults to `false`. When using brief notation, `nd` and `rd` use `d` instead. All others are the same. `ordinal(number, brief)` should return a string containing those two characters (or one character) that would be tagged onto the end of the number. The last two digits determine the ordinal suffix. **Notation for general notation** <pre> 0 1 2 3 4 5 6 7 8 9 th st nd rd th th th th th th </pre> **Notation for brief notation** <pre> 0 1 2 3 4 5 6 7 8 9 th st d d th th th th th th </pre> **However, when the last two digits of the number are 11, 12, or 13, `th` is used instead of `st`,`nd`,`rd` respectively.** **Examples** <pre> *General 1 - 1st 2 - 2nd 3 - 3rd 5 - 5th 11- 11th 149 - 149th 903 - 903rd </pre> <pre> *Brief 1 - 1st 2 - 2d 3 - 3d 5 - 5th 11- 11th 149 - 149th 903 - 903d </pre> **Notes** - Numbers might be passed in replacement of booleans, so `false` may be passed in as `0` and true may be passed in as `1`.
algorithms
def ordinal(n, brief=False): n %= 100 if 9 < n < 20: return "th" n %= 10 if n == 1: return "st" if n == 2: return "nd" [brief:] if n == 3: return "rd" [brief:] return "th"
Ordinal Numbers
52dda52d4a88b5708f000024
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52dda52d4a88b5708f000024
6 kyu
We will use the Flesch–Kincaid Grade Level to evaluate the readability of a piece of text. This grade level is an approximation for what schoolchildren are able to understand a piece of text. For example, a piece of text with a grade level of 7 can be read by seventh-graders and beyond. The way to calculate the grade level is as follows: (0.39 * average number of words per sentence) + (11.8 * average number of syllables per word) - 15.59 Write a function that will calculate the Flesch–Kincaid grade level for any given string. Return the grade level rounded to two decimal points. Ignore hyphens, dashes, apostrophes, parentheses, ellipses and abbreviations. Remember that the text can contain more than one sentence: code accordingly! **HINT**: Count the number of vowels as an approximation for the number of syllables, but count groups of vowels as one (e.g. `deal` is one syllable). **Do not** count `y` as a vowel! ## Example ```python "The turtle is leaving." ==> 3.67 ``` The average number of words per sentence is `4` and the average number of syllables per word is `1.5`. The score is then `(0.39 * 4) + (11.8 * 1.5) - 15.59` = `3.67`
algorithms
from re import compile as reCompile SENTENCE = reCompile(r'[.!?]') SYLLABLE = reCompile(r'(?i)[aeiou]+') def count(string, pattern): return len(pattern . findall(string)) def flesch_kincaid(text): nWords = text . count(' ') + 1 return round(0.39 * nWords / count(text, SENTENCE) + 11.8 * count(text, SYLLABLE) / nWords - 15.59, 2)
Readability is King
52b2cf1386b31630870005d4
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/52b2cf1386b31630870005d4
5 kyu
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!
algorithms
def grabscrab(said, possible_words): return [word for word in possible_words if sorted(word) == sorted(said)]
Arrh, grabscrab!
52b305bec65ea40fe90007a7
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52b305bec65ea40fe90007a7
6 kyu
Write a method that takes an array of signed integers, and returns the longest contiguous subsequence of this array that has a total sum of elements of exactly `0`. If more than one equally long subsequences have a zero sum, return the one starting at the highest index. For example: `maxZeroSequenceLength([25, -35, 12, 6, 92, -115, 17, 2, 2, 2, -7, 2, -9, 16, 2, -11])` should return `[92, -115, 17, 2, 2, 2]`, because this is the longest zero-sum sequence in the array.
algorithms
from itertools import accumulate def max_zero_sequence(arr): memo, start, stop = {0: 0}, 0, 0 for i, x in enumerate(accumulate(arr), 1): if x in memo: if start + i > stop + memo[x]: start, stop = memo[x], i else: memo[x] = i return arr[start: stop]
Longest sequence with zero sum
52b4d1be990d6a2dac0002ab
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/52b4d1be990d6a2dac0002ab
5 kyu
In elementary arithmetic a "carry" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm. This Kata is about determining the number of carries performed during the addition of multi-digit numbers. You will receive an input string containing a set of pairs of numbers formatted as follows: ``` 123 456 555 555 123 594 ``` And your output should be a string formatted as follows: ``` No carry operation 3 carry operations 1 carry operations ``` ### Some Assumptions - Assume that numbers can be of any length. - But both numbers in the pair will be of the same length. - Although not all the numbers in the set need to be of the same length. - If a number is shorter, it will be zero-padded. - The input may contain any arbitrary number of pairs.
algorithms
def ok(s): a, b = s . split() a, b = a[:: - 1], b[:: - 1] d = 0 c = 0 for i, j in zip(a, b): if (int(i) + int(j) + c) > 9: c = 1 d += 1 else: c = 0 return "{} carry operations" . format(d) if d > 0 else "No carry operation" def solve(s): return '\n' . join(ok(i) for i in s . split('\n'))
Elementary Arithmetic - Carries Count
529fdef7488f509b81000061
[ "Algorithms" ]
https://www.codewars.com/kata/529fdef7488f509b81000061
5 kyu
Create a darkroom function that when first called takes an integer (no need to protect yourself in this kata), this is the master screaming where the crotch kick is going to come from (or possibly to tell the attacker where to kick from, no one really knows). Then a 1 will be used as an argument to one of the chaining function calls, this is to indicate which direction the student blocks. If the 1 was inserted into the right function call, 'BLOCK' should be returned for an .end function call, all other blocks should return "CROTCH KICK": ```javascript darkRoom(2)()(1)()()()()()().end() -> 'BLOCK' darkRoom(3)()()(1)()()()()().end() -> 'BLOCK' darkRoom(2)(1)()()()()()()().end() -> 'CROTCH KICK' darkRoom(2)()()(1)()()()()().end() -> 'CROTCH KICK' darkRoom(2)()()()()()()()().end() -> 'CROTCH KICK' ``` ```python dark_room(2)()(1)()()()()()().end() -> 'BLOCK' dark_room(3)()()(1)()()()()().end() -> 'BLOCK' dark_room(2)(1)()()()()()()().end() -> 'CROTCH KICK' dark_room(2)()()(1)()()()()().end() -> 'CROTCH KICK' dark_room(2)()()()()()()()().end() -> 'CROTCH KICK' ``` I know I said you would not have to protect yourself in this kata, but as all great tutors I lied. You must protect yourself against cheating students that try to block in more than one direction at a time, even if they blocked, they deserve a crotch kick for cheating. ```javascript darkRoom(2)(1)(1)()()()()()().end() -> 'CROTCH KICK' darkRoom(2)()(1)(1)()()()()().end() -> 'CROTCH KICK' darkRoom(2)(1)(1)(1)(1)(1)(1)(1)(1).end() -> 'CROTCH KICK' ``` ```python dark_room(2)(1)(1)()()()()()().end() -> 'CROTCH KICK' dark_room(2)()(1)(1)()()()()().end() -> 'CROTCH KICK' dark_room(2)(1)(1)(1)(1)(1)(1)(1)(1).end() -> 'CROTCH KICK' ``` As we all know there are endless directions that you can be attacked from so you must be able to continue calling the chain for however long. Good luck Grasshopper
algorithms
class dark_room: def __init__(self, direction): self . d = direction self . blocked = False def __call__(self, n=0): self . d -= 1 if n: self . blocked = not self . d self . d = - 1 return self def end(self): return ('CROTCH KICK', 'BLOCK')[self . blocked]
The "CROTCH KICK OR BLOCK" kata
528aa29bd8a0399fc5000cae
[ "Algorithms" ]
https://www.codewars.com/kata/528aa29bd8a0399fc5000cae
5 kyu
Two Joggers === Description --- Bob and Charles are meeting for their weekly jogging tour. They both start at the same spot called "Start" and they each run a different lap, which may (or may not) vary in length. Since they know each other for a long time already, they both run at the exact same speed. Illustration --- Example where Charles (dashed line) runs a shorter lap than Bob: ![Example laps](http://www.haan.lu/files/7713/8338/6140/jogging.png "Example laps") Task --- Your job is to complete the function **nbrOfLaps(x, y)** that, given the length of the laps for Bob and Charles, finds the number of laps that each jogger has to complete before they meet each other again, at the same time, at the start. The function takes two arguments: 1. The length of Bob's lap (larger than 0) 2. The length of Charles' lap (larger than 0) <br/>The function should return an array (`Tuple<int, int>` in C#) containing exactly two numbers: 1. The first number is the number of laps that Bob has to run 2. The second number is the number of laps that Charles has to run </br><b>Examples:</b> ```javascript nbrOfLaps(5, 3); // returns [3, 5] nbrOfLaps(4, 6); // returns [3, 2] ``` ```coffeescript nbrOfLaps(5, 3); # returns [3, 5] nbrOfLaps(4, 6); # returns [3, 2] ``` ```crystal nbr_of_laps(5, 3) # returns {3, 5} nbr_of_laps(4, 6) # returns {3, 2} ``` ```julia nbroflaps(5, 3) # returns (3, 5) nbroflaps(4, 6) # returns (3, 2) ``` ```python nbr_of_laps(5, 3) # returns (3, 5) nbr_of_laps(4, 6) # returns (3, 2) ``` ```ruby nbr_of_laps(5, 3) # returns [3, 5] nbr_of_laps(4, 6) # returns [3, 2] ``` ```haskell nbrOfLaps 5 3 -- should be (3, 5) nbrOfLaps 4 6 -- should be (3, 2) ``` ```csharp Kata.NbrOfLaps(5, 3) => new Tuple<int, int>(3, 5); Kata.NbrOfLaps(4, 6) => new Tuple<int, int>(3, 2); ``` ```c nbr_of_laps(5, 3); // returns {3, 5} nbr_of_laps(4, 6); // returns {3, 2} ```
algorithms
from fractions import gcd def nbr_of_laps(x, y): return (y / gcd(x, y), x / gcd(x, y))
Two Joggers
5274d9d3ebc3030802000165
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5274d9d3ebc3030802000165
6 kyu
Consider a deck of 52 cards, which are represented by a string containing their suit and face value. Your task is to write two functions ```encode``` and ```decode``` that translate an array of cards to/from an array of integer codes. * function ```encode``` : input : array of strings (symbols) output : array of integers (codes) sorted in ascending order * function ```decode``` : input : array of integers (codes) output : array of strings (symbols) sorted by code values ``` javascript ['Ac', 'Ks', '5h', 'Td', '3c'] -> [0, 2 ,22, 30, 51] //encoding [0, 51, 30, 22, 2] -> ['Ac', '3c', 'Td', '5h', 'Ks'] //decoding ``` The returned array must be sorted from lowest to highest priority (value or precedence order, see below). ## Card suits: ``` name | symbol | precedence --------------------------------- club c 0 diamond d 1 heart h 2 spade s 3 ``` ## 52-card deck: ``` c | d | h | s ---------------------------------------- 0: A 13: A 26: A 39: A 1: 2 14: 2 27: 2 40: 2 2: 3 15: 3 28: 3 41: 3 3: 4 16: 4 29: 4 42: 4 4: 5 17: 5 30: 5 43: 5 5: 6 18: 6 31: 6 44: 6 6: 7 19: 7 32: 7 45: 7 7: 8 20: 8 33: 8 46: 8 8: 9 21: 9 34: 9 47: 9 9: T 22: T 35: T 48: T 10: J 23: J 36: J 49: J 11: Q 24: Q 37: Q 50: Q 12: K 25: K 38: K 51: K ``` ## My other kata about poker : <a href="/dojo/katas/52ef1c60a863b919ef00025f">Poker cards reducer</a>
reference
str = "A23456789TJQK" card = "cdhs" def encode(cards): return sorted([card . index(x[1]) * 13 + str . index(x[0]) for x in cards]) def decode(cards): return [f" { str [ x % 13 ]}{ card [ x / / 13 ]} " for x in sorted(cards)]
Poker cards encoder/decoder
52ebe4608567ade7d700044a
[ "Strings", "Games", "Algorithms" ]
https://www.codewars.com/kata/52ebe4608567ade7d700044a
5 kyu
#SKRZAT Geek Challenge [SKRZAT] is an old, old game from Poland that uses a game console with two buttons plus a joy stick. As is true to its name, the game communicates in binary, so that one button represents a zero and the other a one. Even more true to its name, the game chooses to communicate so that the base of the number system is minus two, not plus two, so we'll call this representation "Weird Binary". Thus the bit positions label the powers of minus two, as seen in the following five-bit tables: | ------------------------------------------------------------------------- | | Bits | Value | Bits | Value | Bits | Value | Bits | Value | | ------ | ------- | ------ | ------- | ------ | ------- | ------ | ------- | | 00000 | 0 | 01000 | -8 | 10000 | 16 | 11000 | 8 | | 00001 | 1 | 01001 | -7 | 10001 | 17 | 11001 | 9 | | 00010 | -2 | 01010 | -10 | 10010 | 14 | 11010 | 6 | | 00011 | -1 | 01011 | -9 | 10011 | 15 | 11011 | 7 | | 00100 | 4 | 01100 | -4 | 10100 | 20 | 11100 | 12 | | 00101 | 5 | 01101 | -3 | 10101 | 21 | 11101 | 13 | | 00110 | 2 | 01110 | -6 | 10110 | 18 | 11110 | 10 | | 00111 | 3 | 01111 | -5 | 10111 | 19 | 11111 | 11 | | ------------------------------------------------------------------------- | | ------------------------------------------------------------------------- | | Bits | Value | Bits | Value | Bits | Value | Bits | Value | | ------ | ------- | ------ | ------- | ------ | ------- | ------ | ------- | | 01010 | -10 | 00010 | -2 | 11010 | 6 | 10010 | 14 | | 01011 | -9 | 00011 | -1 | 11011 | 7 | 10011 | 15 | | 01000 | -8 | 00000 | 0 | 11000 | 8 | 10000 | 16 | | 01001 | -7 | 00001 | 1 | 11001 | 9 | 10001 | 17 | | 01110 | -6 | 00110 | 2 | 11110 | 10 | 10110 | 18 | | 01111 | -5 | 00111 | 3 | 11111 | 11 | 10111 | 19 | | 01100 | -4 | 00100 | 4 | 11100 | 12 | 10100 | 20 | | 01101 | -3 | 00101 | 5 | 11101 | 13 | 10101 | 21 | | ------------------------------------------------------------------------- | Numbers are presented on the screen in Weird Binary, and then numbers are accepted in response from the console as a stream of zeroes and ones, terminated by a five-second pause. You are writing a computer program to support the novice geek in playing the game by translating numbers between decimal and Weird Binary. #Input The `skrzat` function will either convert into Weird Binary or out of Weird Binary: The first parameter will be either the letter `"b"`, which indicates that the second parameter is written in Weird Binary and needs to be converted to decimal; the letter `"d"` indicates that the second parameter is a decimal and needs to be converted to Weird Binary. The second parameter will be in the range to fit within a 15-bit Weird Binary number, which represents the decimal number range -10922 to 21845, inclusive. #Output For each conversion problem, return the type of problem, its input string, and the converted result in the format shown below, replicating even the spacing exactly as shown. Leading zeroes are not allowed. return format: `'From {binary || decimal}: {non-converted value} is {converted value}'` #Sample Input skrzat('b', '1001101') skrzat('b', '0111111') skrzat('b', '101001000100001') skrzat('b', '010010001000010') skrzat('b', '100110100110100') skrzat('d', -137) skrzat('d', 137) skrzat('d', 8191) skrzat('d', -10000) skrzat('d', 21000) #Sample Output 'From binary: 1001101 is 61' 'From binary: 0111111 is -21' 'From binary: 101001000100001 is 19937' 'From binary: 010010001000010 is -7106' 'From binary: 100110100110100 is 15604' 'From decimal: -137 is 10001011' 'From decimal: 137 is 110011001' 'From decimal: 8191 is 110000000000011' 'From decimal: -10000 is 10100100110000' 'From decimal: 21000 is 101011000011000'
algorithms
from math import log from math import ceil def skrzat(base, number): if base == 'b': return 'From binary: ' + number + ' is ' + str(toDecimal(number)) if base == 'd': return 'From decimal: ' + str(number) + ' is ' + toWBinary(number) def toDecimal(number): if len(number) == 1: return int(number) # e.g (A) 1 -> 1 # e.g (B) 10 -> ( (1) * (-2) + 0 ) # e.g (C) 101 -> ( (1) * (-2) + 0 ) * (-2) + 1 = B * (-2) + 1 # e.g (D) 1010 -> C * (-2) + 0 # ... return toDecimal(number[: - 1]) * (- 2) + int(number[- 1]) # posCurrentOne is the position (0 is position of the right digit) of # the last 1 knew (left to right) # at the begining we don't know this position so we arbitrarily initialize # this to -1. It is useful for insert the zerros after def toWBinary(number, posCurrentOne=int(- 1)): s = '' if not (number): if posCurrentOne == - 1: return '0' # if we know the last 1 is in position 2, and the number is egal to 0, # then we can complete with 2 zerros after and return the result s += '0' * posCurrentOne return s # We begin by calculate the number of digit necessary # if number is egal to 1 we need 1 digits # if number is egal to 2 we need 3 digits # if number is egal to -1 we need 2 digits # ... # if the number is > 0, we need odd digits # if the number is < 0, we need even digits # if number is > 0, if the number of digits usefull is N, then the greatest # number possible is : # (-2 ** 0) = 1 for 1 digit # (-2 ** 0) + (-2 ** 2) = 5 for 3 digits # (-2 ** 0) + (-2 ** 2) + (-2 ** 4) = 21 for 4 digits # so with S the max number with N digits we have: # S = sum(i=1,(N+1)/2) [(-2) ** (2 * (i - 1))] # it is egal to # S = sum(i=0,(N-1)/2) [4 ** i] # so # S = 1 + 4 + ... + 4 ** ((N-1)/2) # in multiply per 4 # 4S = 4 + ... + 4 ** ((N-1)/2) + 4 ** ((N+1)/2) # with substraction # 4S - S = 4 ** ((N+1)/2) - 1 # S = (4 ** ((N+1)/2) - 1) / 3 # with x the decimal number to convert, # whe surch N so that # S >= x # 4 ** ((N+1)/2) - 1 / 3 >= x # 4 ** ((N+1)/2) >= 3x + 1 # we use the log # ((N+1) / 2) log(4) >= log(3x + 1) # but log(4) = log(2*2) = 2log(2) so # (N+1) log(2) >= log(3x + 1) # N >= (log(3x + 1) / log(2)) - 1 # # and we must have N integer and odd # so we use ceil and if the result is even we add 1 # we have also N the number of digit necessary. And so we know # the digit in position N-1 is egal to 1 if number > 0: N = int(ceil(log(3 * number + 1, 2)) - 1) if not (N % 2): N += 1 # by the same way we calculate N if number is > 0 else: N = int(ceil(log((- 3) * number + 2, 2)) - 1) if (N % 2): N += 1 # if the last one calculate is in position 2 and we need 1 digit # we insert 2 - 1 = 1 zerro and one 1 s += '0' * (posCurrentOne - N) s += '1' # if we have N digits, the digit in position N-1 is to one # and correspond to (-2) ** (N-1). So we can substract this value # and iterate. We indicate so the position N -1 return s + toWBinary(number - ((- 2) * * (N - 1)), N - 1)
SKRZAT!!!
528a0762f51e7a4f1800072a
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/528a0762f51e7a4f1800072a
4 kyu
Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings. Example: multiplication_table(3,3) 1 2 3 2 4 6 3 6 9 -->[[1,2,3],[2,4,6],[3,6,9]] Each value on the table should be equal to the value of multiplying the number in its first row times the number in its first column.
reference
def multiplication_table(row, col): return [[(i + 1) * (j + 1) for j in range(col)] for i in range(row)]
Multiplication Tables
5432fd1c913a65b28f000342
[ "Fundamentals", "Mathematics", "Algorithms", "Logic", "Numbers", "Data Types" ]
https://www.codewars.com/kata/5432fd1c913a65b28f000342
6 kyu
Sam is an avid collector of numbers. Every time he finds a new number he throws it on the top of his number-pile. Help Sam organise his collection so he can take it to the International Number Collectors Conference in Cologne. Given an array of numbers, your function should return an array of arrays, where each subarray contains all the duplicates of a particular number. Subarrays should be in the same order as the first occurence of the number they contain: ```javascript group([3, 2, 6, 2, 1, 3]) >>> [[3, 3], [2, 2], [6], [1]] ``` Assume the input is always going to be an array of numbers. If the input is an empty array, an empty array should be returned.
reference
def group(arr): return [[n] * arr . count(n) for n in sorted(set(arr), key=arr . index)]
Organise duplicate numbers in list
5884b6550785f7c58f000047
[ "Arrays", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/5884b6550785f7c58f000047
6 kyu
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. Complete the function so that it returns an array of integers representing the parts. If the input number is too small to split it into requested amount of parts, the additional parts should have value 0. Ignoring the order of the parts, there is only one valid solution for each input to your function! ### Example: ```text 20 split into 6 parts should return [3, 3, 3, 3, 4, 4], in any order. ``` ```c split_integer(20, 6, *parts) // fills parts with 3, 3, 3, 3, 4, 4 ``` ```python split_integer(20, 6) # returns [3, 3, 3, 3, 4, 4] ``` ```ruby splitInteger(20, 6) # returns [3, 3, 3, 3, 4, 4] ``` ```javascript splitInteger(20, 6) // returns [3, 3, 3, 3, 4, 4] ``` ```haskell splitInteger 20 6 -- returns [3, 3, 3, 3, 4, 4] ``` ```scala splitInteger(20, 6) // returns Seq(3, 3, 3, 3, 4, 4) ``` ### Inputs ~~~if:c,cpp,crystal,julia,php ```math 0 \leqslant num \leqslant 1\,000\,000\,000 \\ 1 \leqslant parts \leqslant 1000 ``` ~~~ ~~~if-not:c,cpp,crystal,julia,php The input to your function will always be valid for this kata. ~~~
algorithms
def splitInteger(n, pp): p, bb = divmod(n, pp) return (pp - bb) * [p] + bb * [p + 1]
Almost Even
529e2e1f16cb0fcccb000a6b
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/529e2e1f16cb0fcccb000a6b
6 kyu
Complete the function/method so that it takes a `PascalCase` string and returns the string in `snake_case` notation. Lowercase characters can be numbers. If the method gets a number as input, it should return a string. ## Examples ``` "TestController" --> "test_controller" "MoviesAndBooks" --> "movies_and_books" "App7Test" --> "app7_test" 1 --> "1" ```
algorithms
import re def to_underscore(string): return re . sub(r'(.)([A-Z])', r'\1_\2', str(string)). lower()
Convert PascalCase string into snake_case
529b418d533b76924600085d
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/529b418d533b76924600085d
5 kyu
Here you will create the classic [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle). Your function will be passed the depth of the triangle and your code has to return the corresponding Pascal's triangle up to that depth. The triangle should be returned as a nested array. For example: pascal(5) -> [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] To build the triangle, start with a single `1` at the top, for each number in the next row you just take the two numbers above it and add them together, except for the edges, which are all `1`. e.g.: 1 1 1 1 2 1 1 3 3 1 ~~~if:lambdacalc ### Encodings `purity: LetRec` `numEncoding: BinaryScott` export `foldr` for your `List` encoding ### Performance `20` tests with inputs up to `40` ~~~
algorithms
def pascal(p): t = [[1]] for _ in range(2, p + 1): t . append([1] + [a + b for a, b in zip(t[- 1][: - 1], t[- 1][1:])] + [1]) return t
Pascal's Triangle #2
52945ce49bb38560fe0001d9
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/52945ce49bb38560fe0001d9
6 kyu
Complete the `greatestProduct` method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: the greatest product of five consecutive digits in the string `"123834539327238239583"` is 3240. The input string always has more than five digits. Adapted from Project Euler.
algorithms
from itertools import islice from functools import reduce def greatest_product(n): numbers = [int(value) for value in n] result = [reduce(lambda x, y: x * y, islice(numbers, i, i + 5), 1) for i in range(len(numbers) - 4)] return max(result)
Largest product in a series
529872bdd0f550a06b00026e
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/529872bdd0f550a06b00026e
5 kyu
Implement a function that normalizes out of range sequence indexes (converts them to 'in range' indexes) by making them repeatedly 'loop' around the array. The function should then return the value at that index. Indexes that are not out of range should be handled normally and indexes to empty sequences should return undefined/None depending on the language. For positive numbers that are out of range, they loop around starting at the beginning, so ```javascript normIndex(arr, arr.length); //Returns first element normIndex(arr, arr.length + 1); //Returns second element normIndex(arr, arr.length + 2); //Returns third element //And so on... normIndex(arr, arr.length * 2); //Returns first element ``` ```csharp Kata.NormIndex(arr, arr.Length); //Returns first element Kata.NormIndex(arr, arr.Length + 1); //Returns second element Kata.NormIndex(arr, arr.Length + 2); //Returns third element //And so on... Kata.NormIndex(arr, arr.Length * 2); //Returns first element ``` ```python norm_index_test(seq, len(seq)) # Returns first element norm_index_test(seq, len(seq) + 1) # Returns second element norm_index_test(seq, len(seq) + 2) # Returns third element # And so on... norm_index_test(seq, len(seq) * 2) # Returns first element ``` For negative numbers, they loop starting from the end, so ```javascript normIndex(arr, -1); //Returns last element normIndex(arr, -2); //Returns second to last element normIndex(arr, -3); //Returns third to last element //And so on... normIndex(arr, -arr.length); //Returns first element ``` ```csharp Kata.NormIndex(arr, -1); //Returns last element Kata.NormIndex(arr, -2); //Returns second to last element Kata.NormIndex(arr, -3); //Returns third to last element //And so on... Kata.NormIndex(arr, -arr.Length); //Returns first element ``` ```python norm_index_test(seq, len(seq)) norm_index_test(seq, -1) # Returns last element norm_index_test(seq, -2) # Returns second to last element norm_index_test(seq, -3) # Returns third to last element # And so on... norm_index_test(seq, -len(seq)) # Returns first element ```
algorithms
def norm_index_test(a, n): if a: return a[n % len(a)]
Normalizing Out of Range Array Indexes
5285bf61f8fc1b181700024c
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5285bf61f8fc1b181700024c
6 kyu
Write a function that gets a sequence and value and returns `true/false` depending on whether the variable exists in a multidimentional sequence. Example: ``` locate(['a','b',['c','d',['e']]],'e'); // should return true locate(['a','b',['c','d',['e']]],'a'); // should return true locate(['a','b',['c','d',['e']]],'f'); // should return false ```
algorithms
def locate(seq, value): for s in seq: if s == value or (isinstance(s, list) and locate(s, value)): return True return False
search in multidimensional array
52840d2b27e9c932ff0016ae
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/52840d2b27e9c932ff0016ae
6 kyu
Finish the solution so that it takes an input `n` (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits. Assume: `0 <= n < 2147483647` ## Examples ``` 1 -> "1" 10 -> "10" 100 -> "100" 1000 -> "1,000" 10000 -> "10,000" 100000 -> "100,000" 1000000 -> "1,000,000" 35235235 -> "35,235,235" ```
algorithms
def group_by_commas(n): return '{:,}' . format(n)
Grouped by commas
5274e122fc75c0943d000148
[ "Algorithms" ]
https://www.codewars.com/kata/5274e122fc75c0943d000148
6 kyu
Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars. Your task is to write a simple function that takes a number of meters, and outputs it using metric prefixes. In practice, meters are only measured in "mm" (thousandths of a meter), "cm" (hundredths of a meter), "m" (meters) and "km" (kilometers, or clicks for the US military). For this exercise we just want units bigger than a meter, from meters up to yottameters, excluding decameters and hectometers. All values passed in will be positive integers. e.g. ```javascript meters(5); // returns "5m" meters(51500); // returns "51.5km" meters(5000000); // returns "5Mm" ``` ```ruby meters(5); // returns "5m" meters(51500); // returns "51.5km" meters(5000000); // returns "5Mm" ``` ```python meters(5); // returns "5m" meters(51500); // returns "51.5km" meters(5000000); // returns "5Mm" ``` ```haskell meters 5 -- returns "5m" meters 51500 -- returns "51.5km" meters 5000000 -- returns "5Mm" ``` See http://en.wikipedia.org/wiki/SI_prefix for a full list of prefixes
algorithms
def meters(x): # your code here arr = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] count = 0 while x >= 1000: x /= 1000.00 count += 1 if int(x) == x: x = int(x) return str(x) + arr[count] + 'm'
Metric Units - 1
5264f5685fda8ed370000265
[ "Algorithms" ]
https://www.codewars.com/kata/5264f5685fda8ed370000265
5 kyu
> NOTE: This kata requires a decent knowledge of Regular Expressions. As such, it's best to learn about it _before_ tackling this kata. Some good places to start are: the [MDN pages](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp), and [Regular-Expressions.info](http://www.regular-expressions.info/). You are to write a Regular Expression that matches any string with at least one number divisible by 4 (with no remainder). In most languages, you could do this easily by using `number % 4 == 0`. How would you do it with Regex? A number will start with `[` and end with `]`. They may (or may not) include a plus or minus symbol at the start; this should be taken into account. Leading zeros may be present, and should be ignored (no octals here ;P). There may be other text in the string, outside of the number; this should also be ignored. Also, all numbers will be integers; any floats should be ignored. If there are no valid numbers defined as above, there should be no match made by your regex. So here are some examples: ``` "[+05620]" // 5620 is divisible by 4 (valid) "[+05621]" // 5621 is not divisible by 4 (invalid) "[-55622]" // -55622 is not divisible by 4 (invalid) "[005623]" // 5623 invalid "[005624]" // 5624 valid "[-05628]" // valid "[005632]" // valid "[555636]" // valid "[+05640]" // valid "[005600]" // valid "the beginning [0] ... [invalid] numb[3]rs ... the end" // 0 is valid "No, [2014] isn't a multiple of 4..." // 2014 is invalid "...may be [+002016] will be." // 2016 is valid ``` > **NOTE:** Only `Mod4.test(str)` will be used, so your expression will just need make a match of some kind.
reference
import re class Mod: mod4 = re . compile('.*\[[+-]?([048]|\d*([02468][048]|[13579][26]))\]')
Mod4 Regex
54746b7ab2bc2868a0000acf
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/54746b7ab2bc2868a0000acf
5 kyu
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]]
reference
def shoot(results): pete = phil = 0 for shots, double in results: pete += shots["P1"]. count("X") * (1 + double) phil += shots["P2"]. count("X") * (1 + double) return "Pete Wins!" if pete > phil else "Phil Wins!" if phil > pete else "Draw!"
Clay Pigeon Shooting
57fa9bc99610ce206f000330
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/57fa9bc99610ce206f000330
6 kyu
# Task You have two sorted arrays `a` and `b`, merge them to form new array of unique items. If an item is present in both arrays, it should be part of the resulting array if and only if it appears in both arrays the same number of times. # Example For `a = [1, 3, 40, 40, 50, 60, 60, 60]` and `b = [2, 40, 40, 50, 50, 65]`, the result should be `[1, 2, 3, 40, 60, 65]`. ``` Number 40 appears 2 times in both arrays, thus it is in the resulting array. Number 50 appears once in array a and twice in array b, therefore it is not part of the resulting array.``` # Input/Output - `[input]` integer array `a` A sorted array. 1 ≤ a.length ≤ 500000 - `[input]` integer array `b` A sorted array. `1 ≤ b.length ≤ 500000` - `[output]` an integer array The resulting sorted array.
algorithms
def merge_arrays(a, b): out = [] for n in a + b: if n in a and n in b: if a . count(n) == b . count(n): out . append(n) else: out . append(n) return sorted(set(out))
Challenge Fun #17: Merge Arrays
58b665c891e710a3ec00003f
[ "Algorithms" ]
https://www.codewars.com/kata/58b665c891e710a3ec00003f
6 kyu
Each element in the periodic table has a symbol associated with it. For instance, the symbol for the element Yttrium is `Y`. A fun thing to do is see if we can form words using symbols of elements strung together. The symbol for Einsteinium is `Es`, so the symbols for Yttrium and Einsteinium together form: `Y + Es = YEs` Yes! Ignoring capitalization, we can think of any string of letters formed by the concatenation of one or more element symbols as an *elemental word* -- per the above,`yes` is an elemental word. There is only one combination of element symbols that can form `yes`, but in general, there may be more than one combination of element symbols that can form a given elemental word. Let's call each different combination of element symbols that can form a given elemental word `word` an *elemental form* of `word`. Your task is to implement the function `elementalForms(word)`, which takes one parameter (the string `word`), and returns an array (which we'll call `forms`). If `word` can be formed by combining element symbols from the periodic table, then `forms` should contain one or more sub-arrays, each consisting of strings of the form `'elementName (elementSymbol)'`, *for each unique combination of elements that can form* `word`. ### Example The word `'snack'` can be formed by concatenating the symbols of 3 different combinations of elements: ``` ---------------------------------------------------- | 1 | 2 | 3 | |--------------------------------------------------- | Sulfur (S) | Sulfur (S) | Tin (Sn) | | Nitrogen (N) | Sodium (Na) | Actinium (Ac) | | Actinium (Ac) | Carbon (C) | Potassium (K) | | Potassium (K) | Potassium (K) | | ---------------------------------------------------- ``` So `elementalForms('snack')` should return the following array: ```javascript [ ['Sulfur (S)', 'Nitrogen (N)', 'Actinium (Ac)', 'Potassium (K)'], ['Sulfur (S)', 'Sodium (Na)', 'Carbon (C)', 'Potassium (K)'], ['Tin (Sn)', 'Actinium (Ac)', 'Potassium (K)'] ] ``` ```python [ ['Sulfur (S)', 'Nitrogen (N)', 'Actinium (Ac)', 'Potassium (K)'], ['Sulfur (S)', 'Sodium (Na)', 'Carbon (C)', 'Potassium (K)'], ['Tin (Sn)', 'Actinium (Ac)', 'Potassium (K)'] ] ``` ```csharp { {"Sulfur (S)", "Nitrogen (N)", "Actinium (Ac)", "Potassium (K)"}, {"Sulfur (S)", "Sodium (Na)", "Carbon (C)", "Potassium (K)"}, {"Tin (Sn)", "Actinium (Ac)", "Potassium (K)"} } ``` ```rust vec![ vec!['Sulfur (S)', 'Nitrogen (N)', 'Actinium (Ac)', 'Potassium (K)'], vec!['Sulfur (S)', 'Sodium (Na)', 'Carbon (C)', 'Potassium (K)'], vec!['Tin (Sn)', 'Actinium (Ac)', 'Potassium (K)'] ] ``` ### Guidelines - Symbols can have length `1`, `2` or `3` (this kata uses pre-2016 temporary symbols for elements 113, 115, 117 and 118). - Capitalization does not matter: ```javascript elementalForms('beach') // => [ ['Beryllium (Be)', 'Actinium (Ac)', 'Hydrogen (H)'] ] elementalForms('BEACH') // => [ ['Beryllium (Be)', 'Actinium (Ac)', 'Hydrogen (H)'] ] ``` ```python elemental_forms('beach') // => [ ['Beryllium (Be)', 'Actinium (Ac)', 'Hydrogen (H)'] ] elemental_forms('BEACH') // => [ ['Beryllium (Be)', 'Actinium (Ac)', 'Hydrogen (H)'] ] ``` ```csharp ElementalForms("beach") // { {"Beryllium (Be)", "Actinium (Ac)", "Hydrogen (H)"} } ElementalForms("BEACH") // { {"Beryllium (Be)", "Actinium (Ac)", "Hydrogen (H)"} } ``` ```rust elemental_forms('beach') // => vec![ vec!['Beryllium (Be)', 'Actinium (Ac)', 'Hydrogen (H)'] ] elemental_forms('BEACH') // => vec![ vec!['Beryllium (Be)', 'Actinium (Ac)', 'Hydrogen (H)'] ] ``` - The order of the returned sub-arrays does not matter, but the order of the strings within each sub-array *does* matter -- they should be in the order that "spells out" `word`. - If `word` is not an elemental word (that is, no combination of **one or more** element symbols can form `word`), return an empty array. - You do not need to check the type of `word`. It will always be a (possibly empty) string. ```if:javascript Finally, the helper object `ELEMENTS` has been provided, which is a map from each element symbol to its corresponding full name (e.g. `ELEMENTS['Na'] === 'Sodium'`). ``` ```if:python Finally, a dict `ELEMENTS` has been preloaded and is accessible from your code, which is a map from each element symbol to its corresponding full name (e.g. `ELEMENTS['Na'] == 'Sodium'`). ``` ```if:csharp Finally, a dictionary `ELEMENTS` has been preloaded and is accessible from your code, which is a mapping from each element symbol to its corresponding full name (e.g. `ELEMENTS["Na"] == "Sodium"`). ``` ```if:rust Finally, a hashmap `ELEMENTS` has been preloaded and is accessible from your code, which is a `HashMap<&str, &str>` from each element symbol to its corresponding full name (e.g. `ELEMENTS["Na"] == "Sodium"`). ``` Have fun!
algorithms
def elemental_forms(word): return list(get_elem_form(word . lower())) def get_elem_form(word, parents=[]): if word == '': yield parents for elem, name in ELEMENTS . items(): if word . startswith(elem . lower()): yield from get_elem_form(word[len(elem):], parents + [f' { name } ( { elem } )'])
Elemental Words
56fa9cd6da8ca623f9001233
[ "Strings", "Algorithms", "Recursion", "Arrays" ]
https://www.codewars.com/kata/56fa9cd6da8ca623f9001233
4 kyu
For a new 3D game that will be released, a team of programmers needs an easy function. (Then it will be processed as a method in a Class, forget this concept for Ruby) We have an sphere with center <b>O</b>, having in the space the coordinates `[α, β, γ]` and radius `r` and a list of points, `points_list`, each one with coordinates `[x, y, z]`. Select the biggest triangle (or triangles) that has (have) all its (their) 3 vertice(s) as interior points of the sphere (not even in the sphere contour). You should consider that a point P is interior if its distance to center O, d, is such that: <code> d < r </code> <span style="margin: 0 5px 0 10px">and </span> <code> |(d - r) / r| > 10<sup>-10</sup> </code> Let's see the situation with the following points in the image posted below: ```python A = [1,2,-4]; B = [-3, 2, 4]; C = [7, 8, -4]; D = [2, 3, 5]; E = [-2, -1, 1] ``` The sphere has the following features: ``` O = [1, 2, -2] (Center of the sphere) radius = 8 ``` <a href="http://imgur.com/dtZGfIN"><img src="http://i.imgur.com/dtZGfIN.gif" title="source: imgur.com" /></a> As C is the only exterior point of the sphere, the possible triangles that have their vertices interior to the sphere are: ``` ABD, ABE, ADE, BDE ``` Let's see which is the biggest one: ```python Triangle Triangle with its points Area ABD [[1,2,-4],[-3,2,4],[2,3,5]] 22.44994432064 ABE [[1,2,-4],[-3,2,4],[-2,-1,1]] 13.56465996625 ADE [[1,2,-4],[2,3,5],[-2,-1,1]] 22.62741699796 <---- biggest triangle BDE [[-3,2,4],[2,3,5],[-2,-1,1]] 11.31370849898 ``` ~~~if:javascript Our function `biggestTriangInt()` should output for this case: ```javascript pointsList = [[1,2,-4], [-3, 2, 4], [7, 8, -4], [2, 3, 5], [-2, -1, 1]] center = [1, 2, -2] radius = 8 biggestTriangInt(pointsList, center, radius) == [4, 22.62741699796, [[1,2,-4],[2,3,5],[-2,-1,1]]] ``` ~~~ ~~~if-not:javascript Our function `biggest_triang_int()` should output for this case: ```python points_list = [[1,2,-4], [-3, 2, 4], [7, 8, -4], [2, 3, 5], [-2, -1, 1]] center = [1, 2, -2] radius = 8 biggest_triang_int(points_list, center, radius) == [4, 22.62741699796, [[1,2,-4],[2,3,5],[-2,-1,1]]] ``` ~~~ That means that with the given points list we may generate 4 triangles with all their vertices as interior points of the sphere, the biggest triangle has an area of 22.62741699796 (the units does not matter and the values for the area should not be rounded) and finally, there is only one triangle with this maximum value. Every triangle should be output having the same order of its vertices than in the given list of points. B = [-3,2,4], comes before than D =[2,3,5] and the last one E = [-2,-1,1] If in the result we have only one triangle, the function should output a list of three points. Let'see the next case: ```python points_list = [[1,2,-4], [-3, 2, 4], [7, 8, -4], [2, 3, 5], [-2, -1, 1], [3, 2, 6], [1, 4, 0], [-4, -5, -6], [4, 5, 6], [-2, -3, -5], [-1, -2, 4], [-3, -2, -6], [-1, -4, 0], [2, 1, -1]] sphere_center = [0, 0, 0] radius = 8 biggest_triang_int(points_list, sphere_center, radius) == [165, 33.645207682521445, [[[1, 2, -4], [3, 2, 6], [-1, -4, 0]], [[1, 4, 0], [-1, -2, 4], [-3, -2, -6]]]] ``` Now there are a total of 165 triangles with their vertices in the sphere, the biggest triangle has an area of 33.645207682521445 but we have two triangles with this area value. The vertices of each triangle respect the order of the points list as we expressed before but the additional detail is that the triangles are sorted by the values of the coordinates of their points. Let's compare the coordinates of the first point ``` First point x y z Triangle1 1 2 -4 <--- this triangle is first in the result Triangle2 1 4 0 | | | y1 < y2 (2, 4) | x1 = x2 (1 = 1) ``` In the case that all the given points are exterior to the sphere the function should output the empty list. The points in the list are all valid and each one occurs once. Remember that if three points are collinear do not form a triangle. For practical purposes you may consider that if the area of a triangle is lower than 10<sup>-8</sup>, the points are aligned. Enjoy it!
reference
from collections import defaultdict from itertools import combinations def norme(vect): return sum(v * * 2 for v in vect) * * .5 def vectorize(pt1, pt2): return [b - a for a, b in zip(pt1, pt2)] def isInCircle(d, r): return d < r and (r - d) / r > 1e-10 def crossProd(v1, v2): return [v1[0] * v2[1] - v1[1] * v2[0], v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2]] def biggest_triang_int(point_list, center, radius): filteredPts = [pt for pt in point_list if isInCircle( norme(vectorize(pt, center)), radius)] dctTriangles = defaultdict(list) for threePts in combinations(filteredPts, 3): area = abs( norme(crossProd(vectorize(* threePts[: 2]), vectorize(* threePts[1:]))) / 2.0) if area > 1e-8: dctTriangles[area]. append(list(threePts)) maxArea = max(dctTriangles . keys()) if dctTriangles else 0 return [] if not dctTriangles else [sum(map(len, dctTriangles . values())), maxArea, sorted(dctTriangles[maxArea]) if len(dctTriangles[maxArea]) > 1 else dctTriangles[maxArea][0]]
Helpers For a 3DGame I: Biggest Triangle in a Sphere
57deba2e8a8b8db0a4000ad6
[ "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings", "Geometry", "Games" ]
https://www.codewars.com/kata/57deba2e8a8b8db0a4000ad6
4 kyu
Once upon a time, a CodeWarrior, after reading a [discussion on what can be the plural](http://www.codewars.com/kata/plural/discuss/javascript), took a look at [this page](http://en.wikipedia.org/wiki/Grammatical_number#Types_of_number ) and discovered that **more than 1** "kind of plural" may exist. For example [Sursurunga Language](http://en.wikipedia.org/wiki/Sursurunga_language) distinguishes 5 types of numbers: **singular** (1 thing), **dual** (2 things), '**trial**' or '**lesser paucal**' (3 or 4), '**greater paucal**' (more than 4) and **plural** (many). In this kata, you'll have to handle only four types of numbers: - **singular**: 0 or 1 thing - **dual**: 2 things - **paucal**: 3 to 9 things - **plural**: more than 9 things To add some flavor the **number-marker** will not be added in same places: - **singular**, no marker : `1 cat` - **dual**, prefixed "`bu`" : `2 cats -> 2 bucat` - **paucal**, suffixed "`zo`" : `4 cats -> 4 catzo` - **plural**, "circumfixed `ga`" : `100 cats -> 100 gacatga` As you all ("hawk eyes") have seen, the final `s` of english plural **disappears**. ( btw these markers, of course, have absolutely nothing to do with true sursurunga language, we're just talking about "**pig**-sursurunga" with **pig** as **pig** in "**pig latin**" ) ## Your Job . . . . . . if you accept it, will be to write a `sursurungal` function which get a `string` as argument and returns this string with words in it eventually converted to their "pig-sursurunga number type". If a `number` ( *ie* 1 or more digit ) + a `space` + a `word` ( letters ) are found then the word should be converted. **Each** group of `number+space+word` found in the string should be evaluated. ### Examples : ```javascript sursurungal('1 tiger') // -> '1 tiger' (singular, nothing to change) sursurungal('2 tigers') // -> '2 butiger' (dual) sursurungal('3 tigers') // -> '3 tigerzo' (paucal) sursurungal('13 tigers') // -> '13 gatigerga' (plural) sursurungal('5 lions and 15 zebras') // -> '5 lionzo and 15 gazebraga' (paucal and plural) ``` You may assume at least 1 `number+space+word` group will be provided. **Beware** `s` of english plural should be removed, not ending `s` of some singular words ( *eg* "kiss" ) ```javascript sursurungal("7 kisses") // -> '7 kissezo' sursurungal("1 kiss") // -> '1 kiss' ``` Good luck!
reference
import re def sursurungal(txt): txt = re . sub(r'\b2\s(\S+)s', r'2 bu\1', txt) txt = re . sub(r'\b([3-9])\s(\S+)s', r'\1 \2zo', txt) return re . sub(r'(\d+\d)\s(\S+)s', r'\1 ga\2ga', txt)
Pig Sursurunga
5536aba6e4609cc6a600003d
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5536aba6e4609cc6a600003d
6 kyu
Implement `String#parse_mana_cost`, which parses [Magic: the Gathering mana costs](http://mtgsalvation.gamepedia.com/Mana_cost) expressed as a string and returns a `Hash` with keys being kinds of mana, and values being the numbers. Don't include any mana types equal to zero. Format is: * optionally natural number representing total amount of generic mana (use key `*`) * optionally followed by any combination of `w`, `u`, `b`, `r`, `g` (case insensitive in input, return lower case in output), each representing one mana of specific color. If case of Strings not following specified format, return `nil/null/None`.
reference
import re def parse_mana_cost(mana): retval = {} mana = mana . lower() m = re . match(r'\A(\d*)([wubrg]*)\Z', mana) if m: if m . group(1) and int(m . group(1)) > 0: retval['*'] = int(m . group(1)) if m . group(2): l = list(m . group(2)) print l if l . count('w') > 0: retval['w'] = l . count('w') if l . count('u') > 0: retval['u'] = l . count('u') if l . count('b') > 0: retval['b'] = l . count('b') if l . count('r') > 0: retval['r'] = l . count('r') if l . count('g') > 0: retval['g'] = l . count('g') return retval
Regexp basics - parsing mana cost
5686004a2c7fade6b500002d
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5686004a2c7fade6b500002d
6 kyu
Magic The Gathering is a collectible card game that features wizards battling against each other with spells and creature summons. The game itself can be quite complicated to learn. In this series of katas, we'll be solving some of the situations that arise during gameplay. You won't need any prior knowledge of the game to solve these contrived problems, as I will provide you with enough information. ## Creatures Each creature has a power and toughness. We will represent this in an array. [2, 3] means this creature has a power of 2 and a toughness of 3. When two creatures square off, they each deal damage equal to their power to each other at the same time. This only happens once. If a creature takes on damage greater than or equal to their toughness, they die. Examples: - Creature 1 - [2, 3] - Creature 2 - [3, 3] - Creature 3 - [1, 4] - Creature 4 - [4, 1] If creature 1 battles creature 2, creature 1 dies, while 2 survives. If creature 3 battles creature 4, they both die, as 3 deals 1 damage to 4, but creature 4 only has a toughness of 1. Write a function `battle(player1, player2)` that takes in 2 arrays of creatures. Each players' creatures battle each other in order (player1[0] battles the creature in player2[0]) and so on. If one list of creatures is longer than the other, those creatures are considered unblocked, and do not battle. Your function should return an object (a hash in Ruby) with the keys player1 and player2 that contain the power and toughness of the surviving creatures. Example: ````javascript player1 = [[1, 1], [2, 1], [2, 2], [5, 5]]; player2 = [[1, 2], [1, 2], [3, 3]]; battle(player1, player2) -> { 'player1': [[5, 5]], 'player2': [[1, 2], [3, 3]] } ```` ````coffeescript player1 = [[1, 1], [2, 1], [2, 2], [5, 5]] player2 = [[1, 2], [1, 2], [3, 3]] battle(player1, player2) # { 'player1': [[5, 5]], 'player2': [[1, 2], [3, 3]] } ```` ````ruby player1 = [[1, 1], [2, 1], [2, 2], [5, 5]]; player2 = [[1, 2], [1, 2], [3, 3]]; battle(player1, player2) # { player1: [[5, 5]], player2: [[1, 2], [3, 3]] } ```` Good luck with your battles! <div style="width: 320px; text-align: center; color: white; border: white 1px solid;"> Check out my other Magic The Gathering katas: </div> <div> <a style='text-decoration:none' href='http://www.codewars.com/kata/magic-the-gathering-number-1-creatures'><span style='color:#00C5CD'>Magic The Gathering #1:</span> Creatures</a><br /> <a style='text-decoration:none' href='http://www.codewars.com/kata/magic-the-gathering-number-2-mana'><span style='color:#00C5CD'>Magic The Gathering #2:</span> Mana</a><br /> </div>
algorithms
def battle(player1, player2): l1 = [] l2 = [] x = min(len(player1), len(player2)) for i in range(x): if player1[i][0] < player2[i][1]: l2 . append(player2[i]) if player2[i][0] < player1[i][1]: l1 . append(player1[i]) l1 += player1[x:] l2 += player2[x:] return {'player1': l1, 'player2': l2}
Magic The Gathering #1: Creatures
567af2c8b46252f78400004d
[ "Algorithms", "Fundamentals", "Arrays", "Games" ]
https://www.codewars.com/kata/567af2c8b46252f78400004d
6 kyu
For any given linear sequence, calculate the function [f(x)] and return it as a string. 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. ### Examples (input -> output): ``` [0, 1, 2, 3, 4] -> "f(x) = x" [0, 3, 6, 9, 12] -> "f(x) = 3x" [1, 4, 7, 10, 13] -> "f(x) = 3x + 1" [0, 0, 1, 1, 1] -> "Non-linear sequence" ```
reference
def get_function(seq): m = seq[0] n = seq[1] - m if any(s != n * x + m for x, s in enumerate(seq)): return "Non-linear sequence" return "f(x) = {}{}{}{}{}{}" . format( "-" * (n < 0), str(abs(n)) * (abs(n) > 1), "x" * (n != 0), " + " * (m > 0 and n != 0), " - " * (m < 0), str(abs(m)) * (m != 0 or n == 0) )
Calculate the function f(x) for a simple linear sequence (Easy)
5476f4ca03810c0fc0000098
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5476f4ca03810c0fc0000098
6 kyu
The Collatz conjecture is one of the most famous one. Take any positive integer n, if it is even divide it by 2, if it is odd multiply it by 3 and add 1 and continue indefinitely.The conjecture is that whatever is n the sequence will reach 1. There is many ways to approach this problem, each one of them had given beautifull graphs and impressive display of calculation power. The simplest approach can be found in this kata: http://www.codewars.com/kata/5286b2e162056fd0cb000c20 You look at the Collatz sequence of a number and see when it reaches 1. In this kata we will take a look at the length of collatz sequences. And how they evolve. Write a function that take a positive integer n and return the number between 1 and n that has the maximum Collatz sequence length and the maximum length. The output has to take the form of an array [number, maxLength] For exemple the Collatz sequence of 4 is [4,2,1], 3 is [3,10,5,16,8,4,2,1], 2 is [2,1], 1 is [1], so `MaxCollatzLength(4)` should return `[3,8]`. If n is not a positive integer, the function have to return []. * As you can see, numbers in Collatz sequences may exceed n. The last tests use random big numbers so you may consider some optimisation in your code: * You may get very unlucky and get only hard numbers: try submitting 2-3 times if it times out; if it still does, probably you need to optimize your code more; * Optimisation 1: when calculating the length of a sequence, if n is odd, what 3n+1 will be ? * Optimisation 2: when looping through 1 to n, take i such that i<n/2, what will be the lenght of the sequence for 2i ?
algorithms
from functools import lru_cache @ lru_cache(maxsize=None) def rec(n): return 1 + (0 if n == 1 else rec(3 * n + 1) if n & 1 else rec(n / / 2)) memo = [[0, None], [1, 1]] def max_collatz_length(n): if not (type(n) == int and n > 0): return [] while n >= len(memo): x = rec(len(memo)) if x > memo[- 1][1]: memo . append([len(memo), x]) else: memo . append(memo[- 1]) return memo[n]
Max Collatz Sequence Length
53a9ee602f150d5d6b000307
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/53a9ee602f150d5d6b000307
5 kyu
Create your own mechanical dartboard that gives back your score based on the coordinates of your dart. <b style='font-size:16px'>Task:</b> <ul> <li>Use the <a href="https://en.wikipedia.org/wiki/Darts#Scoring">scoring rules</a> for a standard dartboard:<br> <img style="height:264px" src="https://upload.wikimedia.org/wikipedia/commons/4/42/Dartboard.svg"></a> </li> <li>Finish method:</li> ```csharp public string GetScore(double x, double y); ``` ```java public String getScore(double x, double y); ``` ```javascript function getDartboardScore(x, y); ``` ```python def get_score(x,y): ``` ```swift func getScore(dart: (x: Double, y: Double)) -> String ``` ```haskell getDartScore :: Double -> Double -> DartScore ``` <li>The coordinates are `(x, y)` are always relative to the center of the board (0, 0). The unit is millimeters. If you throw your dart 5 centimeters to the left and 3 centimeters below, it is written as:</li> ```csharp var score = dartboard.GetScore(-50, -30); ``` ```java String score = dartboard.getScore(-50, -30); ``` ```javascript var score = getDartboardScore(-50, -30); ``` ```python score = get_score(-50, -30) ``` ```swift var score = Dartboard.getScore(dart: (x: -50, y: -30)) ``` ```haskell getDartScore (-50) (-30) ``` <li>Possible scores are:</li><ul><li>Outside of the board: `"X"`</li><li>Bull's eye: `"DB"`</li><li>Bull: `"SB"`</li><li>A single number, example: `"10"`</li><li>A triple number: `"T10"`</li><li>A double number: `"D10"`</li></ul> <li>A throw that ends exactly on the border of two sections results in a bounce out. You can ignore this because all the given coordinates of the tests are within the sections.</li> <li>The diameters of the circles on the dartboard are:</li><ul><li>Bull's eye: `12.70 mm`</li><li>Bull: `31.8 mm`</li><li>Triple ring inner circle: `198 mm`</li><li>Triple ring outer circle: `214 mm`</li><li>Double ring inner circle: `324 mm`</li><li>Double ring outer circle: `340 mm`</li></ul> </ul> <i>If you liked this kata, you can continue with: <a style="color:lightgreen" href="https://www.codewars.com/kata/lets-play-darts-beat-the-power">Let's Play Darts: Beat The Power!</a></i>
algorithms
from math import atan2, degrees def get_score(x, y): r, a = (x * x + y * y) * * 0.5, degrees(atan2(y, x)) + 9 t = str([6, 13, 4, 18, 1, 20, 5, 12, 9, 14, 11, 8, 16, 7, 19, 3, 17, 2, 15, 10][int(a + 360 if a < 0 else a) / / 18]) for l, s in [(6.35, 'DB'), (15.9, 'SB'), (99, t), (107, 'T' + t), (162, t), (170, 'D' + t)]: if r <= l: return s return 'X'
Let's Play Darts!
5870db16056584eab0000006
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/5870db16056584eab0000006
5 kyu
Write a function that given an array of numbers >= 0, will arrange them such that they form the biggest number. <br/> For example: ``` [1, 2, 3] --> "321" (3-2-1) [3, 30, 34, 5, 9] --> "9534330" (9-5-34-3-30) ``` The results will be large so make sure to return a string.
algorithms
from functools import cmp_to_key KEY = cmp_to_key(lambda a, b: int(b + a) - int(a + b)) def biggest(numbers: list) - > str: return '' . join(sorted(map(str, numbers), key=KEY)). lstrip('0') or '0'
I love big nums and I cannot lie
56121f3312baa28c8500005b
[ "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/56121f3312baa28c8500005b
6 kyu
Write a function that will take in any `array` and reverse it. <br/> Sounds simple doesn't it? <br/> <b>NOTES:</b> * Array should be reversed in place! (no need to return it) * Usual builtins have been deactivated. Don't count on them. * You'll have to do it fast enough, so think about performances
algorithms
def reverse(seq): for i in range(len(seq) >> 1): seq[i], seq[- i - 1] = seq[- i - 1], seq[i]
I need more speed!
55de9c184bb732a87f000055
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/55de9c184bb732a87f000055
6 kyu
Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array. In case of multiple appearances to choose from, take the last occurence of the unpaired character. **Notes:** * A wide range of characters is used, and some of them may not render properly in your browser. * Your solution should be linear in terms of string length to pass the last test. ## Examples ``` "Hello World" --> ["H", "e", " ", "W", "r", "l", "d"] "Codewars" --> ["C", "o", "d", "e", "w", "a", "r", "s"] "woowee" --> [] "wwoooowweeee" --> [] "racecar" --> ["e"] "Mamma" --> ["M"] "Mama" --> ["M", "m"] ```
algorithms
from collections import Counter def odd_one_out(s): d = Counter(reversed(s)) return [x for x in d if d[x] % 2][:: - 1]
What will be the odd one out?
55b080eabb080cd6f8000035
[ "Strings", "Arrays", "Performance", "Algorithms" ]
https://www.codewars.com/kata/55b080eabb080cd6f8000035
6 kyu
The <a href="https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee">Spelling Bee</a> bees are back... # How many bees are in the beehive? * bees can be facing UP, DOWN, LEFT, RIGHT, and now also <span style='color:orange'>_diagonally_</span> up/down/left/right * bees can share parts of other bees <hr> ## Examples Ex1 ``` bee.bee .e..e.. .b..eeb ``` _Answer: 5_ Ex2 ``` beee.. eeb.e. ebee.b ``` _Answer: 7_
reference
def how_many_bees(h): if not h: return 0 v = list(zip(* h)) b = [None] * len(h) sf = (b[i:] + l + b[: i] for i, l in enumerate(h)) sb = (b[: i] + l + b[i:] for i, l in enumerate(h)) df = [[n for n in l if n is not None] for l in zip(* sf)] db = [[n for n in l if n is not None] for l in zip(* sb)] inline = '\n' . join(map('' . join, h + v + df + db)) return (inline + inline[:: - 1]). count('bee')
Spelling Bee II
58f290d0b48966547f00014c
[ "Fundamentals" ]
https://www.codewars.com/kata/58f290d0b48966547f00014c
6 kyu
Write ```javascript function wordStep(str) ``` that takes in a string and creates a step with that word. <br/> E.g<br/> ```javascript wordStep('SNAKES SHOE EFFORT TRUMP POTATO') === [['S','N','A','K','E','S',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ','O',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ','E','F','F','O','R','T',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','R',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','U',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','M',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','P','O','T','A','T','O']] ``` Every word will end with the character that the next word will start with. You will start top left of the array and end bottom right. All cells that are not occupied by a letter needs to be a space ```' '```
algorithms
def word_step(s): res = [s[0]] for i, word in enumerate(s . split()): if i % 2: res += [str . rjust(c, len(res[- 1])) for c in word[1:]] else: res[- 1] += word[1:] return [list(str . ljust(line, len(res[- 1]))) for line in res]
Get your steppin' on son
55e00266d494ce5155000032
[ "Algorithms" ]
https://www.codewars.com/kata/55e00266d494ce5155000032
6 kyu
Write ```javascript String.prototype.hashify() ``` that will turn a string into a hash/object. Every character in the string will be the key for the next character. <br/> E.g. <br/> ``` '123456'.hashify() == {"1":"2","2":"3","3":"4","4":"5","5":"6","6":"1"} // The last char will be key for 1st char '11223'.hashify() == {"1":["1","2"],"2":["2","3"],"3":"1"} // when duplicates exist, group them in an array // i.e. 1 is key for next char 1, that 1 is key for next char 2, but 1 is already in the hash, so add 2 to key 1 'Codewars'.hashify() == {"C":"o","o":"d","d":"e","e":"w","w":"a","a":"r","r":"s","s":"C"} ``` <b>Order is not important</b><br/> There is a preloaded ```function equals(x,y)``` that will check if objects are same regardless of property order.
algorithms
def hashify(string): out = dict() for c1, c2 in zip(string, string[1:] + string[0]): try: try: out[c1]. append(c2) except: out[c1] = [out[c1], c2] except: out[c1] = c2 return out
Objectify all the strings
55dd54631827120dd800002b
[ "Algorithms" ]
https://www.codewars.com/kata/55dd54631827120dd800002b
6 kyu
Complete the function that takes 3 numbers `x, y and k` (where `x ≤ y`), and returns the number of integers within the range `[x..y]` (both ends included) that are divisible by `k`. More scientifically: `{ i : x ≤ i ≤ y, i mod k = 0 }` ## Example Given ```x = 6, y = 11, k = 2``` the function should return `3`, because there are three numbers divisible by `2` between `6` and `11`: `6, 8, 10` - **Note**: The test cases are very large. You will need a O(log n) solution or better to pass. (A constant time solution is possible.)
algorithms
def divisible_count(x, y, k): return y / / k - (x - 1) / / k
Count the divisible numbers
55a5c82cd8e9baa49000004c
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/55a5c82cd8e9baa49000004c
6 kyu
Design a data structure that supports the following two operations: * `addWord` (or `add_word`) which adds a word, * `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter You may assume that all given words contain only lowercase letters. ## Examples ```javascript addWord("bad") addWord("dad") addWord("mad") search("pad") === false search("bad") === true search(".ad") === true search("b..") === true ``` ```python wd = WordDictionary() wd.add_word("bad") wd.add_word("dad") wd.add_word("mad") wd.search("pad") == False wd.search("bad") == True wd.search(".ad") == True wd.search("b..") == True ``` ```ruby add_word("bad") add_word("dad") add_word("mad") search("pad") == false search("bad") == true search(".ad") == true search("b..") == true ``` **Note:** the data structure will be initialized multiple times during the tests!
algorithms
import re class WordDictionary: def __init__(self): self . data = [] def add_word(self, x): self . data . append(x) def search(self, x): for word in self . data: if re . match(x + "\Z", word): return True return False
Urban Dictionary
5631ac5139795b281d00007d
[ "Algorithms", "Object-oriented Programming" ]
https://www.codewars.com/kata/5631ac5139795b281d00007d
6 kyu
Write ```javascript function wordPattern(pattern, str) ``` ```csharp WordPattern(string pattern, string str) ``` ```ruby word_pattern(pattern, string) ``` ```python word_pattern(pattern, string) ``` that given a ```pattern``` and a string ```str```, find if ```str``` follows the same sequence as ```pattern```. <br/> For example: ```javascript wordPattern('abab', 'truck car truck car') === true wordPattern('aaaa', 'dog dog dog dog') === true wordPattern('abab', 'apple banana banana apple') === false wordPattern('aaaa', 'cat cat dog cat') === false ``` ```csharp WordPattern("abab', "truck car truck car") == true WordPattern("aaaa", "dog dog dog dog") == true WordPattern("abab", "apple banana banana apple") == false WordPattern("aaaa', "cat cat dog cat") == false ``` ```python word_pattern('abab', 'truck car truck car') == True word_pattern('aaaa', 'dog dog dog dog') == True word_pattern('abab', 'apple banana banana apple') == False word_pattern('aaaa', 'cat cat dog cat') == False ``` ```ruby word_pattern('abab', 'truck car truck car') == true word_pattern('aaaa', 'dog dog dog dog') == true word_pattern('abab', 'apple banana banana apple') == false word_pattern('aaaa', 'cat cat dog cat') == false ``` **Note: Each letter in the pattern stands for a distinct word**
algorithms
def word_pattern(pattern, string): x = list(pattern) y = string . split(" ") return (len(x) == len(y) and len(set(x)) == len(set(y)) == len(set(zip(x, y))) )
Word Patterns
562846dd1f77ab7c00000033
[ "Algorithms" ]
https://www.codewars.com/kata/562846dd1f77ab7c00000033
6 kyu
Given a sorted array of numbers, return the summary of its ranges. ## Examples ```javascript summaryRanges([1, 2, 3, 4]) === ["1->4"] summaryRanges([1, 1, 1, 1, 1]) === ["1"] summaryRanges([0, 1, 2, 5, 6, 9]) === ["0->2", "5->6", "9"] summaryRanges([0, 1, 2, 3, 3, 3, 4, 5, 6, 7]) === ["0->7"] summaryRanges([0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10]) === ["0->7", "9->10"] summaryRanges([-2,0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10, 12]) ===["-2", "0->7", "9->10", "12"] ``` ```python summary_ranges([1, 2, 3, 4]) == ["1->4"] summary_ranges([1, 1, 1, 1, 1]) == ["1"] summary_ranges([0, 1, 2, 5, 6, 9]) == ["0->2", "5->6", "9"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 5, 6, 7]) == ["0->7"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10]) == ["0->7", "9->10"] summary_ranges([-2, 0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10, 12]) == ["-2", "0->7", "9->10", "12"] ``` ```ruby summary_ranges([1, 2, 3, 4]) == ["1->4"] summary_ranges([1, 1, 1, 1, 1]) == ["1"] summary_ranges([0, 1, 2, 5, 6, 9]) == ["0->2", "5->6", "9"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 5, 6, 7]) == ["0->7"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10]) == ["0->7", "9->10"] summary_ranges([-2, 0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10, 12]) == ["-2", "0->7", "9->10", "12"] ```
algorithms
def summary_ranges(nums): ret, s = [], float('-inf') for e, n in zip([s] + nums, nums + [- s]): if n - e > 1: ret . append(['{}', '{}->{}'][s < e]. format(s, e)) s = n return ret[1:]
Summarize ranges
55fb6537544ae06ccc0000dc
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/55fb6537544ae06ccc0000dc
6 kyu
Write ```javascript function repeatingFractions(numerator, denominator) ``` ```python function repeating_fractions(numerator, denominator) ``` ```ruby function repeating_fractions(numerator, denominator) ``` that given two numbers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part has repeated digits, replace those digits with a single digit in parentheses. <br/> For example: ```javascript repeatingFractions(1,1) === '1' repeatingFractions(1,3) === '0.(3)' repeatingFractions(2,888) === '0.(0)(2)5(2)5(2)5(2)5(2)5(2)' ``` ```python repeating_fractions(1,1) === '1' repeating_fractions(1,3) === '0.(3)' repeating_fractions(2,888) === '0.(0)(2)5(2)5(2)5(2)5(2)5(2)' ``` ```ruby repeating_fractions(1,1) === '1' repeating_fractions(1,3) === '0.(3)' repeating_fractions(2,888) === '0.(0)(2)5(2)5(2)5(2)5(2)5(2)' ```
reference
import re def repeating_fractions(n, d): (i, d) = str(n * 1.0 / d). split('.') return i + '.' + re . sub(r'([0-9])\1+', r'(\1)', d)
Group Repeating Fractions
5613475e4778aab4d600004f
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5613475e4778aab4d600004f
6 kyu
Write a function ```x(n)``` that takes in a number ```n``` and returns an ```nxn``` array with an ```X``` in the middle. The ```X``` will be represented by ```1's``` and the rest will be ```0's```. <br/> E.g.<br/> ```javascript x(5) === [[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]; x(6) === [[1, 0, 0, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1]]; ``` ```python x(5) == [[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]; x(6) == [[1, 0, 0, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1]]; ``` ```ruby x(5) == [[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]; x(6) == [[1, 0, 0, 0, 0, 1], [0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1]]; ```
algorithms
def x(n): d = [[0] * n for i in range(n)] for i in range(n): d[i][i] = 1 d[i][- i - 1] = 1 return d
X marks the spot!
55cc20eb943f1d8b11000045
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/55cc20eb943f1d8b11000045
6 kyu
Write a function ```csharp TripleDouble(long num1, long num2) ``` ```java TripleDouble(long num1, long num2) ``` ```javascript tripledouble(num1,num2) ``` ```python triple_double(num1, num2) ``` ```ruby triple_double(num1, num2) ``` ```scala tripleDouble(num1: Long, num2: Long): Int ``` which takes numbers `num1` and `num2` and returns `1` if there is a straight triple of a number at any place in `num1` and also a straight double of the **same** number in `num2`. If this isn't the case, return `0` ## Examples ```javascript tripledouble(451999277, 41177722899) == 1 // num1 has straight triple 999s and // num2 has straight double 99s tripledouble(1222345, 12345) == 0 // num1 has straight triple 2s but num2 has only a single 2 tripledouble(12345, 12345) == 0 tripledouble(666789, 12345667) == 1 ``` ```csharp TripleDouble(451999277, 41177722899) == 1 // num1 has straight triple 999s and // num2 has straight double 99s TripleDouble(1222345, 12345) == 0 // num1 has straight triple 2s but num2 has only a single 2 TripleDouble(12345, 12345) == 0 TripleDouble(666789, 12345667) == 1 ``` ```java TripleDouble(451999277, 41177722899) == 1 // num1 has straight triple 999s and // num2 has straight double 99s TripleDouble(1222345, 12345) == 0 // num1 has straight triple 2s but num2 has only a single 2 TripleDouble(12345, 12345) == 0 TripleDouble(666789, 12345667) == 1 ``` ```python triple_double(451999277, 41177722899) == 1 # num1 has straight triple 999s and num2 has straight double 99s triple_double(1222345, 12345) == 0 # num1 has straight triple 2s but num2 has only a single 2 triple_double(12345, 12345) == 0 triple_double(666789, 12345667) == 1 ``` ```ruby triple_double(451999277, 41177722899) == 1 # num1 has straight triple 999s and num2 has straight double 99s triple_double(1222345, 12345) == 0 # num1 has straight triple 2s but num2 has only a single 2 triple_double(12345, 12345) == 0 triple_double(666789, 12345667) == 1 ``` ```scala // num1 has straight triple 999s and num2 has straight double 99s tripleDouble(451999277, 41177722899) == 1 // num1 has straight triple 2s but num2 has only a single 2: tripleDouble(1222345, 12345) == 0 tripleDouble(12345, 12345) == 0 tripleDouble(666789, 12345667) == 1 ```
algorithms
def triple_double(num1, num2): return any([i * 3 in str(num1) and i * 2 in str(num2) for i in '0123456789'])
Triple trouble
55d5434f269c0c3f1b000058
[ "Algorithms" ]
https://www.codewars.com/kata/55d5434f269c0c3f1b000058
6 kyu
Write ```javascript function combine() ``` ```python function combine() ``` ```ruby function combine() ``` ```haskell combine :: [[a]] -> [a] ``` that combines arrays by alternatingly taking elements passed to it. E.g ```javascript combine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) == ['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5] ``` ```python combine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) == ['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5] ``` ```ruby combine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) == ['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5] ``` ```haskell combine [[1, 2, 3], [1, 2, 3]] == [1, 1, 2, 2, 3, 3] combine [[1, 2, 3], [1, 2, 3, 4, 5]] == [1, 1, 2, 2, 3, 3, 4, 5] combine [[1, 2, 3], [1, 2, 3, 4, 5], [6, 7], [8]] == [1, 1, 6, 8, 2, 2, 7, 3, 3, 4, 5] ``` Arrays can have different lengths.
algorithms
def combine(* args): out = list() for i in range(len(max(args, key=len))): # Sometimes you just have to love python for arr in args: if i < len(arr): out . append(arr[i]) return out
Alternating Loops
55e529bf6c6497394a0000b5
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/55e529bf6c6497394a0000b5
6 kyu
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of polls with weights, into a fixed projection for the result. #### Task: Your job is to convert an array of candidates (variable name `candidates`) and an array of polls (variable name `polls`), each poll with two parts, a result and a weight, into a guess of the result, with each value rounded to one decimal place, through use of a weighted average. Weights can be zero! Don't worry about the sum not totalling 100. The final result should be a hash in Ruby and Crystal, dictionary in Python, or object in JS in the format shown below: ```ruby { "<candidate name 1>" => "<candidate's projected percent, rounded to nearest tenth>", "<candidate name 2>" => "<candidate's projected percent, rounded to nearest tenth>", ... } ``` ```crystal {} of (String | Char) => Float64 { "<candidate name 1>" => "<candidate's projected percent, rounded to nearest tenth>", "<candidate name 2>" => "<candidate's projected percent, rounded to nearest tenth>", ... } ``` ```python { "<candidate name 1>": "<candidate's projected percent, rounded to nearest tenth>", "<candidate name 2>": "<candidate's projected percent, rounded to nearest tenth>", ... } For your convenience, a function named round1 has been defined for you. You can use it to round to the nearest tenth correctly (due to the inaccuracy of round and floats in general). ``` ```javascript { "<candidate name 1>": "<candidate's projected percent, rounded to nearest tenth>", "<candidate name 2>": "<candidate's projected percent, rounded to nearest tenth>", ... } ``` ```coffeescript { "<candidate name 1>": "<candidate's projected percent, rounded to nearest tenth>", "<candidate name 2>": "<candidate's projected percent, rounded to nearest tenth>", ... } ``` _The input should not be modified._ #### Calculation for projections: ``` [(poll1 * weight1) + (poll2 * weight2) + ...] / (weight1 + weight2 + ...) ``` #### An example: ```ruby candidates = ['A', 'B', 'C'] poll1res = [20, 30, 50] poll1wt = 1 poll1 = [poll1res, poll1wt] poll2res = [40, 40, 20] poll2wt = 0.5 poll2 = [poll2res, poll2wt] poll3res = [50, 40, 10] poll3wt = 2 poll3 = [poll3res, poll3wt] polls = [poll1, poll2, poll3] predict(candidates, polls) #=> { 'A' => 40, 'B' => 37.1, 'C' => 22.9 } # because... candidate 'A' weighted average = ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2) = (20 + 20 + 100) / 3.5 = 140 / 3.5 = 40 candidate 'B' weighted average = ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2) = (30 + 20 + 80) / 3.5 = 130 / 3.5 = 37.142857... ≈ 37.1 (round to nearest tenth) candidate 'C' weighted average = ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2) = (50 + 10 + 20) / 3.5 = 80 / 3.5 = 22.857142... ≈ 22.9 (round to nearest tenth) ``` ```python candidates = ['A', 'B', 'C'] poll1res = [20, 30, 50] poll1wt = 1 poll1 = [poll1res, poll1wt] poll2res = [40, 40, 20] poll2wt = 0.5 poll2 = [poll2res, poll2wt] poll3res = [50, 40, 10] poll3wt = 2 poll3 = [poll3res, poll3wt] polls = [poll1, poll2, poll3] predict(candidates, polls) #=> { 'A': 40, 'B': 37.1, 'C': 22.9 } # because... candidate 'A' weighted average = ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2) = (20 + 20 + 100) / 3.5 = 140 / 3.5 = 40 candidate 'B' weighted average = ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2) = (30 + 20 + 80) / 3.5 = 130 / 3.5 = 37.142857... ≈ 37.1 (round to nearest tenth) candidate 'C' weighted average = ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2) = (50 + 10 + 20) / 3.5 = 80 / 3.5 = 22.857142... ≈ 22.9 (round to nearest tenth) ``` ```javascript candidates = ['A', 'B', 'C'] poll1res = [20, 30, 50] poll1wt = 1 poll1 = [poll1res, poll1wt] poll2res = [40, 40, 20] poll2wt = 0.5 poll2 = [poll2res, poll2wt] poll3res = [50, 40, 10] poll3wt = 2 poll3 = [poll3res, poll3wt] polls = [poll1, poll2, poll3] predict(candidates, polls) #=> { 'A': 40, 'B': 37.1, 'C': 22.9 } # because... candidate 'A' weighted average = ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2) = (20 + 20 + 100) / 3.5 = 140 / 3.5 = 40 candidate 'B' weighted average = ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2) = (30 + 20 + 80) / 3.5 = 130 / 3.5 = 37.142857... ≈ 37.1 (round to nearest tenth) candidate 'C' weighted average = ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2) = (50 + 10 + 20) / 3.5 = 80 / 3.5 = 22.857142... ≈ 22.9 (round to nearest tenth) ``` ```coffeescript candidates = ['A', 'B', 'C'] poll1res = [20, 30, 50] poll1wt = 1 poll1 = [poll1res, poll1wt] poll2res = [40, 40, 20] poll2wt = 0.5 poll2 = [poll2res, poll2wt] poll3res = [50, 40, 10] poll3wt = 2 poll3 = [poll3res, poll3wt] polls = [poll1, poll2, poll3] predict(candidates, polls) #=> { 'A': 40, 'B': 37.1, 'C': 22.9 } # because... candidate 'A' weighted average = ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2) = (20 + 20 + 100) / 3.5 = 140 / 3.5 = 40 candidate 'B' weighted average = ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2) = (30 + 20 + 80) / 3.5 = 130 / 3.5 = 37.142857... ≈ 37.1 (round to nearest tenth) candidate 'C' weighted average = ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2) = (50 + 10 + 20) / 3.5 = 80 / 3.5 = 22.857142... ≈ 22.9 (round to nearest tenth) ``` ```crystal candidates = ['A', 'B', 'C'] poll1res = [20, 30, 50] poll1wt = 1 poll1 = [poll1res, poll1wt] poll2res = [40, 40, 20] poll2wt = 0.5 poll2 = [poll2res, poll2wt] poll3res = [50, 40, 10] poll3wt = 2 poll3 = [poll3res, poll3wt] polls = [poll1, poll2, poll3] predict(candidates, polls) #=> { 'A': 40, 'B': 37.1, 'C': 22.9 } # because... candidate 'A' weighted average = ((20 * 1) + (40 * 0.5) + (50 * 2)) / (1 + 0.5 + 2) = (20 + 20 + 100) / 3.5 = 140 / 3.5 = 40 candidate 'B' weighted average = ((30 * 1) + (40 * 0.5) + (40 * 2)) / (1 + 0.5 + 2) = (30 + 20 + 80) / 3.5 = 130 / 3.5 = 37.142857... ≈ 37.1 (round to nearest tenth) candidate 'C' weighted average = ((50 * 1) + (20 * 0.5) + (10 * 2)) / (1 + 0.5 + 2) = (50 + 10 + 20) / 3.5 = 80 / 3.5 = 22.857142... ≈ 22.9 (round to nearest tenth) ``` Also check out my other creations — [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions), [Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2). If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
reference
def predict(candidates, polls): x = zip(* [list(map(lambda i: i * weight, poll)) for poll, weight in polls]) x = list( map(round1, (map(lambda i: sum(i) / sum([i[1] for i in polls]), x)))) return dict(zip(candidates, x))
Elections: Weighted Average
5827d31b86f3b0d9390001d4
[ "Fundamentals" ]
https://www.codewars.com/kata/5827d31b86f3b0d9390001d4
6 kyu
# Explanation It's your first day in the robot factory and your supervisor thinks that you should start with an easy task. So you are responsible for purchasing raw materials needed to produce the robots. A complete robot weights `50` kilogram. Iron is the only material needed to create a robot. All iron is inserted in the first machine; the output of this machine is the input for the next one, and so on. The whole process is sequential. Unfortunately not all machines are first class, so a given percentage of their inputs are destroyed during processing. # Task You need to figure out how many kilograms of iron you need to buy to build the requested number of robots. # Example Three machines are used to create a robot. Each of them produces `10%` scrap. Your target is to deliver `90` robots. The method will be called with the following parameters: ``` CalculateScrap(scrapOfTheUsedMachines, numberOfRobotsToProduce) CalculateScrap(int[] { 10, 10, 10 }, 90) ``` # Assumptions * The scrap is less than `100%`. * The scrap is never negative. * There is at least one machine in the manufacturing line. * Except for scrap there is no material lost during manufacturing. * The number of produced robots is always a positive number. * You can only buy full kilograms of iron.
algorithms
from math import ceil def calculate_scrap(arr, n): x = 50 for i in arr: x /= (1 - i / 100) return ceil(n * x)
Manage the Robot Factory: Day 1
5898a7208b431434e500013b
[ "Algorithms" ]
https://www.codewars.com/kata/5898a7208b431434e500013b
6 kyu
You get an array of arrays.<br> If you sort the arrays by their length, you will see, that their length-values are consecutive.<br> But one array is missing!<br> <br><br> You have to write a method, that return the length of the missing array.<br> ``` Example: [[1, 2], [4, 5, 1, 1], [1], [5, 6, 7, 8, 9]] --> 3 ``` <br> If the array of arrays is null/nil or empty, the method should return 0.<br> When an array in the array is null or empty, the method should return 0 too!<br> There will always be a missing element and its length will be always between the given arrays. <br><br> Have fun coding it and please don't forget to vote and rank this kata! :-)<br> <br> I have created other katas. Have a look if you like coding and challenges.
algorithms
def get_length_of_missing_array(arrays): arrays = [len(a) if a is not None else 0 for a in arrays] arrays . sort() if 0 in arrays or len(arrays) == 0: return 0 for i in range(len(arrays)): if arrays[i + 1] != arrays[i] + 1: return arrays[i] + 1
Length of missing array
57b6f5aadb5b3d0ae3000611
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/57b6f5aadb5b3d0ae3000611
6 kyu
In Germany we have "LOTTO 6 aus 49". That means that 6 of 49 numbers are drawn as winning combination.<br> There is also a "Superzahl", an additional number, which can increase your winning category. In this kata you have to write two methods. ```csharp public static int[] NumberGenerator() public static int CheckForWinningCategory(int[] checkCombination, int[] winningCombination) ``` ```java public static int[] numberGenerator() public static int checkForWinningCategory(int[] checkCombination, int[] winningCombination) ``` ```javascript function numberGenerator() function checkForWinningCategory(checkCombination, winningCombination) ``` ```coffeescript numberGenerator = () -> checkForWinningCategory = (checkCombination, winningCombination) -> ``` ```cpp std::vector<int> numberGenerator() int checkForWinningCategory(std::vector<int> checkCombination, std::vector<int> winningCombination) ``` ```ruby def number_generator def check_for_winning_category(your_numbers, winning_numbers) ``` ```python def number_generator(): def check_for_winning_category(your_numbers, winning_numbers): ``` The first method is for drawing the lottery numbers.<br> You have to create an array with 7 random numbers. 6 from these are from 1 - 49.<br>Of course every number may only occur once.<br>And the 7th number is the "Superzahl". A number from 0 - 9. This number is independent from the first six numbers.<br> The first 6 numbers have to be in ascending order. A result could be:<br> 4, 9, 17, 22, 25, 35, 0<br> Or:<br> 4, 18, 22, 34, 41, 44, 4 The second method should check a given number against the winning combination and have to return the winning category:<br> ``` 1 - 6 numbers and Superzahl match 2 - 6 numbers match 3 - 5 numbers and Superzahl match 4 - 5 numbers match 5 - 4 numbers and Superzahl match 6 - 4 numbers match 7 - 3 numbers and Superzahl match 8 - 3 numbers match 9 - 2 numbers and Superzahl match -1 - if the numbers do not match any of the rules above ``` <br><br> Have fun coding it and please don't forget to vote and rank this kata! :-) <br> <br> I have created other katas. Have a look if you like coding and challenges.
algorithms
def number_generator(): from random import randrange, sample return sorted(sample(range(1, 50), 6)) + [randrange(10)] def check_for_winning_category(your_numbers, winning_numbers): matches = len(set(your_numbers[: - 1]) & set(winning_numbers[: - 1])) category = 14 - 2 * matches - (your_numbers[- 1] == winning_numbers[- 1]) return category if category < 10 else - 1
LOTTO 6 aus 49 - 6 of 49
57a98e8172292d977b000079
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/57a98e8172292d977b000079
6 kyu
You're a programmer in a SEO company. The SEO specialist of your company gets the list of all project keywords everyday, then he looks for the longest keys to analyze them. You will get the list with keywords and must write a simple function that returns the biggest search keywords and sorts them in lexicographical order. For instance you might get: ```ruby 'key1', 'key2', 'key3', 'key n', 'bigkey2', 'bigkey1' ``` ```crystal "key1", "key2", "key3", "key n", "bigkey2", "bigkey1" ``` ```python 'key1', 'key2', 'key3', 'key n', 'bigkey2', 'bigkey1' ``` ```javascript 'key1', 'key2', 'key3', 'key n', 'bigkey2', 'bigkey1' ``` And your function should return: ```ruby "'bigkey1', 'bigkey2'" ``` ```crystal "'bigkey1', 'bigkey2'" ``` ```python "'bigkey1', 'bigkey2'" ``` ```javascript "'bigkey1', 'bigkey2'" ``` Don't forget to rate this kata! Thanks :)
reference
def the_biggest_search_keys(* keys): mx = max(map(len, keys), default=0) return ', ' . join(sorted('\'{}\'' . format(k) for k in keys if len(k) == mx)) if mx else "''"
What The Biggest Search Keys?
58ac1abdff4e78738f000805
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/58ac1abdff4e78738f000805
6 kyu
We want to approximate the length of a curve representing a function `y = f(x)` with ` a <= x <= b`. First, we split the interval `[a, b]` into n sub-intervals with widths <code>h<sub>1</sub>, h<sub>2</sub>, ... , h<sub>n</sub></code> by defining points <code>x<sub>1</sub>, x<sub>2</sub> , ... , x<sub>n-1</sub></code> between a and b. This defines points <code>P<sub>0</sub>, P<sub>1</sub>, P<sub>2</sub>, ... , P<sub>n</sub></code> on the curve whose x-coordinates are <code>a, x<sub>1</sub>, x<sub>2</sub> , ... , x<sub>n-1</sub>, b</code> and y-coordinates <code>f(a), f(x<sub>1</sub>), ..., f(x<sub>n-1</sub>), f(b) </code>. By connecting these points, we obtain a polygonal path approximating the curve. Our task is to approximate the length of a parabolic arc representing the curve `y = x * x` with `x` in the interval `[0, 1]`. We will take a common step `h` between the points <code>x<sub>i</sub>: h<sub>1</sub>, h<sub>2</sub>, ... , h<sub>n</sub> = h = 1/n</code> and we will consider the points <code>P<sub>0</sub>, P<sub>1</sub>, P<sub>2</sub>, ... , P<sub>n</sub></code> on the curve. The coordinates of each <code>P<sub>i</sub></code> are <code>(x<sub>i</sub>, y<sub>i</sub> = x<sub>i</sub> * x<sub>i</sub>)</code>. The function `len_curve` (or similar in other languages) takes `n` as parameter (number of sub-intervals) and returns the length of the curve. ![alternative text](http://i.imgur.com/kyjJcE4.png) #### Note: When you "Attempt" tests are done with a tolerance of 1e-06 (except in PureScript where you must truncate your result to 9 decimal places).
reference
from math import sqrt def len_curve(n): return round(sum(sqrt((2 * k + 1) * * 2 / n / n + 1) for k in range(n)) / n, 9)
Parabolic Arc Length
562e274ceca15ca6e70000d3
[ "Fundamentals" ]
https://www.codewars.com/kata/562e274ceca15ca6e70000d3
6 kyu
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 always: n > 0, p >= 0, n > p) 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 ![alternative text](http://i.imgur.com/eUGaNvIm.jpg)
reference
from math import comb def diagonal(n: int, p: int) - > int: return comb(n + 1, p + 1)
Easy Diagonal
559b8e46fa060b2c6a0000bf
[ "Fundamentals" ]
https://www.codewars.com/kata/559b8e46fa060b2c6a0000bf
6 kyu
In order to prove it's success and gain funding, the wilderness zoo needs to prove to environmentalists that it has x number of mating pairs of bears. ### Task: You must check within a string (s) to find all of the mating pairs, returning a list/array of the string containing valid mating pairs and a boolean indicating whether the ***total*** number of bears is greater than or equal to x. ### Rules for a 'valid' mating pair: 1. Bears are either 'B' (male) or '8' (female), 2. Bears must be together in male/female pairs 'B8' or '8B', 3. Mating pairs must involve two distinct bears each ('B8B' may look fun, but does not count as two pairs). Return an array containing a string of the valid mating pairs available (empty string if there are no pairs), and a boolean indicating whether the ***total*** number of bears is greater than or equal to x. , e.g: (6, 'EvHB8KN8ik8BiyxfeyKBmiCMj') ---> ['B88B', false]; *in this example, the number of bears(=4) is lesser than the given value of x(=6)*
reference
from re import findall def bears(x, s): bears = "" . join(findall("8B|B8", s)) return [bears, len(bears) >= x]
Pairs of Bears
57d165ad95497ea150000020
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57d165ad95497ea150000020
6 kyu
You have to build a pyramid.<br> <br> This pyramid should be built from characters from a given string.<br> <br> You have to create the code for these four methods: ```csharp public static string WatchPyramidFromTheSide(string characters) public static string WatchPyramidFromAbove(string characters) public static int CountVisibleCharactersOfThePyramid(string characters) public static int CountAllCharactersOfThePyramid(string characters) ``` ```java public static String watchPyramidFromTheSide(String characters) public static String watchPyramidFromAbove(String characters) public static int countVisibleCharactersOfThePyramid(String characters) public static int countAllCharactersOfThePyramid(String characters) ``` ```javascript function watchPyramidFromTheSide(characters) function watchPyramidFromAbove(characters) function countVisibleCharactersOfThePyramid(characters) function countAllCharactersOfThePyramid(characters) ``` ```cpp std::string watchPyramidFromTheSide(std::string characters) std::string watchPyramidFromAbove(std::string characters) int countVisibleCharactersOfThePyramid(std::string characters) int countAllCharactersOfThePyramid(std::string characters) ``` ```python watch_pyramid_from_the_side(characters): watch_pyramid_from_above(characters): count_visible_characters_of_the_pyramid(characters): count_all_characters_of_the_pyramid(characters): ``` The first method ("FromTheSide") shows the pyramid as you would see from the side.<br> The second method ("FromAbove") shows the pyramid as you would see from above.<br> The third method ("CountVisibleCharacters") should return the count of all characters, that are visible from outside the pyramid.<br> The forth method ("CountAllCharacters") should count all characters of the pyramid. Consider that the pyramid is completely solid and has no holes or rooms in it.<br> Every character will be used for building one layer of the pyramid. So the length of the given string will be the height of the pyramid. Every layer will be built with stones from the given character. There is no limit of stones.<br> The pyramid should have perfect angles of 45 degrees.<br> <br><br> Example: <b>Given string: "abc"</b><br> <br> Pyramid from the side:<br> ``` c bbb aaaaa ``` Pyramid from above:<br> ``` aaaaa abbba abcba abbba aaaaa ``` Count of visible stones/characters: ``` 25 ``` Count of all used stones/characters: ``` 35 ``` <br> There is no meaning in the order or the choice of the characters. It should work the same for example "aaaaa" or "54321". <br> <b>Hint:</b> Your output for the side must always be a rectangle! So spaces at the end of a line must not be deleted or trimmed! <br> If the string is null or empty, you should exactly return this value for the watch-methods and <b>-1</b> for the count-methods. <br><br> Have fun coding it and please don't forget to vote and rank this kata! :-) <br> I have created other katas. Have a look if you like coding and challenges.<br>
reference
def watch_pyramid_from_the_side(characters): if not characters: return characters baseLen = len(characters) * 2 - 1 return '\n' . join(' ' * (i) + characters[i] * (baseLen - 2 * i) + ' ' * (i) for i in range(len(characters) - 1, - 1, - 1)) def watch_pyramid_from_above(characters): if not characters: return characters baseLen = len(characters) * 2 - 1 return '\n' . join(characters[0: min(i, baseLen - 1 - i)] + characters[min(i, baseLen - 1 - i)] * (baseLen - 2 * min(i, baseLen - 1 - i)) + characters[0: min(i, baseLen - 1 - i)][:: - 1] for i in range(baseLen)) def count_visible_characters_of_the_pyramid(characters): return - 1 if not characters else (len(characters) * 2 - 1) * * 2 def count_all_characters_of_the_pyramid(characters): return - 1 if not characters else sum((2 * i + 1) * * 2 for i in range(len(characters)))
String Pyramid
5797d1a9c38ec2de1f00017b
[ "Mathematics", "Strings", "Algorithms", "ASCII Art" ]
https://www.codewars.com/kata/5797d1a9c38ec2de1f00017b
6 kyu
Frank just bought a new calculator. But, this is no normal calculator. This is a **'Sticky Calculator**. Whenever you add add, subtract, multiply or divide two numbers the two numbers first stick together: For instance: ```javascript 50 + 12 becomes 5012 ``` and then the operation is carried out as usual: ```javascript (5012) + 12 = 5024 ``` ## Task It is your job to create a function which takes 3 parameters: ```javascript stickyCalc(operation, val1, val2) ``` which works just like Frank's sticky calculator ## Some Examples ```javascript stickyCalc('+', 50, 12) // Output: (5012 + 12) = 5024 stickyCalc('-', 7, 5) // Output: (75 - 5) = 70 stickyCalc('*', 13, 20) // Output: (1320 * 20 ) = 26400 stickyCalc('/', 10, 10) // Output: (1010 / 10) = 101 ``` ## Note * The calculator only works for positive integers only. * The calculator rounds any non-integer before operating. * The calculator rounds any output to nearest integer. For example: ```javascript stickyCalc('/', 12.1, 6.8), 18); ``` 12.1 and 6.8 are rounded to 12 and 7 respectively & they 'stick together' to make 127. <br><br> Although 127 / 7 = 18.1428 ; 18 is outputted instead.
reference
def sticky_calc(operation, val1, val2): return round(eval("{0}{1}{2}{1}" . format(round(val1), round(val2), operation)))
Frank's Sticky Calculator
5900750cb7c6172207000054
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5900750cb7c6172207000054
7 kyu
Find the number with the most digits. If two numbers in the argument array have the same number of digits, return the first one in the array.
reference
def find_longest(xs): return max(xs, key=lambda x: len(str(x)))
Most digits
58daa7617332e59593000006
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58daa7617332e59593000006
7 kyu
**This Kata is intended as a small challenge for my students** All Star Code Challenge #23 There is a certain multiplayer game where players are assessed at the end of the game for merit. Players are ranked according to an internal scoring system that players don't see. You've discovered the formula for the scoring system! Create a function called `scoring()` that takes an array of Player objects and returns an array of player names, in order of descending score (highest score is index 0, 2nd highest is index 1, etc.). Each player's score is calculated as follows: 1. Each normal kill is worth 100 points 2. Each assist is worth 50 points 3. Each point of damage done is worth 0.5 points 4. Each point of healing done is worth 1 point 5. The longest kill streak is worth 2^N, where N is the number of kills of the streak 6. Environmental kills are worth 500 points (These are counted separately from normal kills) For each of the above statistic, a Player object contains a respective "key:value" pairing. All values except the 'name' are integers. ```javascript var player1 = { name: "JuanPablo", normKill: 5, assist: 12, damage: 3200, healing: 0, streak: 4, envKill: 1 } var player2 = { name: "ProfX", normKill: 2, assist: 14, damage: 600, healing: 1500, streak: 0, envKill: 0 } scoring([player1, player2]); //["JuanPable","ProfX"] // Scores of 3216 and 2701, respectively. ``` Note: Assume the input array will ALWAYS have a properly constructed Player object (no missing keys or values) Names will not contain unusual characters nor repeat (names are unique) Players with the same score should be sorted by the order they appear in the array For simplicity, for a kill streak of 0 the kill streak calculation will yield 1 (or 2<sup>0</sup>) points
reference
def scoring(array): res = {} for e in array: score = e["norm_kill"] * 100 + e["assist"] * 50 + e["damage"] / / 2 + \ e["healing"] + 2 * * e["streak"] + e["env_kill"] * 500 res[e["name"]] = score return sorted(res, key=res . get, reverse=True)
All Star Code Challenge #23
5865dd726b56998ec4000185
[ "Fundamentals" ]
https://www.codewars.com/kata/5865dd726b56998ec4000185
6 kyu
If you reverse the word "emirp" you will have the word "prime". That idea is related with the purpose of this kata: we should select all the primes that when reversed are a **different** prime (so palindromic primes should be discarded). For example: 13, 17 are prime numbers and the reversed respectively are 31, 71 which are also primes, so 13 and 17 are "emirps". But primes 757, 787, 797 are palindromic primes, meaning that the reversed number is the same as the original, so they are not considered as "emirps" and should be discarded. The emirps sequence is registered in OEIS as [A006567](https://oeis.org/A006567) ## Your task Create a function that receives one argument `n`, as an upper limit, and the return the following array: `[number_of_emirps_below_n, largest_emirp_below_n, sum_of_emirps_below_n]` ## Examples ```python find_emirp(10) [0, 0, 0] ''' no emirps below 10 ''' find_emirp(50) [4, 37, 98] ''' there are 4 emirps below 50: 13, 17, 31, 37; largest = 37; sum = 98 ''' find_emirp(100) [8, 97, 418] ''' there are 8 emirps below 100: 13, 17, 31, 37, 71, 73, 79, 97; largest = 97; sum = 418 ''' ``` Happy coding!! Advise: Do not use a primality test. It will make your code very slow. Create a set of primes using a prime generator or a range of primes producer. Remember that search in a set is faster that in a sorted list or array
algorithms
from gmpy2 import is_prime def find_emirp(n): a = [i for i in range(13, n + 1, 2) if is_prime(i) and is_prime(int(str(i)[:: - 1])) and str(i) != str(i)[:: - 1]] return [0, 0, 0] if not a else [len(a), max(a), sum(a)]
Emirps
55de8eabd9bef5205e0000ba
[ "Fundamentals", "Mathematics", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/55de8eabd9bef5205e0000ba
5 kyu
We need a function ```prime_bef_aft()``` that gives the largest prime below a certain given value ```n```, ```befPrime or bef_prime``` (depending on the language), and the smallest prime larger than this value, ```aftPrime/aft_prime``` (depending on the language). The result should be output in a list like the following: ```python prime_bef_aft(n) == [befPrime, aftPrime] ``` ```ruby prime_bef_aft(n) == [bef_prime, aft_prime] ``` ```javascript primeBefAft == [befPrime, aftPrime] ``` ```coffeescript primeBefAft == [befPrime, aftPrime] ``` ```java primeBefAft == {befPrime, aftPrime} ``` ```csharp PrimeBefAft == {befPrime, aftPrime} ``` ```haskell PrimeBefAft == (befPrime, aftPrime) ``` ```clojure prime-bef-aft == [befPrime, aftPrime] ``` ```cpp primeBefAft == {befPrime, aftPrime} ``` If n is a prime number it will give two primes, n will not be included in the result. Let's see some cases: ```python prime_bef_aft(100) == [97, 101] prime_bef_aft(97) == [89, 101] prime_bef_aft(101) == [97, 103] ``` ```ruby prime_bef_aft(100) == [97, 101] prime_bef_aft(97) == [89, 101] prime_bef_aft(101) == [97, 103] ``` ```javascript primeBefAft(100) == [97, 101] primeBefAft(97) == [89, 101] primeBefAft(101) == [97, 103] ``` ```coffeescript primeBefAft(100) == [97, 101] primeBefAft(97) == [89, 101] primeBefAft(101) == [97, 103] ``` ```java primeBefAft(100) --> {97, 101} primeBefAft(97) --> {89, 101} primeBefAft(101) --> {97, 103} ``` ```csharp PrimeBefAft(100) --> {97, 101} PrimeBefAft(97) --> {89, 101} PrimeBefAft(101) --> {97, 103} ``` ```haskell primeBefAft(100) --> (97, 101) primeBefAft(97) --> (89, 101) primeBefAft(101) --> (97, 103) ``` ```clojure (prime-bef-aft 100) == [97, 101] (prime-bef-aft 97) == [89, 101] (prime-bef-aft 101) == [97, 103] ``` ```cpp PrimeBefAft(100) --> {97, 101} PrimeBefAft(97) --> {89, 101} PrimeBefAft(101) --> {97, 103} ``` Range for the random tests: ```1000 <= n <= 200000``` (The extreme and special case n = 2 will not be considered for the tests. Thanks Blind4Basics) Happy coding!!
reference
def prime(a): if a < 2: return False if a == 2 or a == 3: return True if a % 2 == 0 or a % 3 == 0: return False maxDivisor = a * * 0.5 d, i = 5, 2 while d <= maxDivisor: if a % d == 0: return False d += i i = 6 - i return True def prime_bef_aft(num): res = [] for n in range(num - 1, 1, - 1): if prime(n): res . append(n) break for n in range(num + 1, 3 * num, 1): if prime(n): res . append(n) break return res
Surrounding Primes for a value
560b8d7106ede725dd0000e2
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/560b8d7106ede725dd0000e2
6 kyu
An integral: ```math \int_{a}^{b}f(x)dx ``` can be approximated by the so-called Simpson’s rule: ```math \dfrac{b-a}{3n}(f(a)+f(b)+4\sum_{i=1}^{n/2}f(a+(2i-1)h)+2\sum_{i=1}^{n/2-1}f(a+2ih)) ``` Here `h = (b - a) / n`, `n` being an even integer and `a <= b`. We want to try Simpson's rule with the function f: ```math f(x) = \frac{3}{2}\sin(x)^3 ``` The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...). #### Notes: - Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`. - `n` will always be even. - We know that the exact value of the integral of f on the given interval is `2`. - Please ask before translating. Complement: you can see: <https://www.codewars.com/kata/5562ab5d6dca8009f7000050/> about rectangle method and trapezoidal rule.
reference
def simpson(n): from math import sin, pi a = 0 b = pi h = (b - a) / n def f(x): return (3 / 2) * sin(x) * * 3 integral = 0 integral += f(a) + f(b) integral += 4 * sum(f(a + (2 * i - 1) * h) for i in range(1, n / / 2 + 1)) integral += 2 * sum(f(a + 2 * i * h) for i in range(1, n / / 2)) integral *= h / 3 return integral
Simpson's Rule - Approximate Integration
565abd876ed46506d600000d
[ "Mathematics" ]
https://www.codewars.com/kata/565abd876ed46506d600000d
6 kyu
Given two numbers `x` and `n`, calculate the (positive) nth root of `x`; this means that being `r = result`, `r^n = x` ## Examples ``` x = 4 n = 2 --> 2 # the square root of 4 is 2 2^2 = 4 x = 8 n = 3 --> 2 # the cube root of 8 is 2 2^3 = 8 x = 256 n = 4 --> 4 # the 4th root of 256 is 4 4^4 = 256 x = 9 n = 2 --> 3 # the square root of 9 is 3 3^2 = 9 x = 6.25 n = 2 --> 2.5 # 2.5^2 = 6.25 ``` ### Notes: * `4 <= x < 10 ^ 20` * `4 <= n <= 50` Good luck!
reference
def root(x, n): return x * * (1.0 / n)
Nth Root of a Number
5520714decb43308ea000083
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5520714decb43308ea000083
7 kyu
# Task Given an array of positive integers `a` and an integer `k`, find the first and last index of the longest subarray of a that consists only of `k`. If the array contains multiple subarrays of the same length, return indices of the last one. If `k` doesn't exist in `a`, return `(-1, -1)`. # Input/Output - `[input]` integer array `a` A non-empty array. For each valid i `1 ≤ a[i] ≤ 9`. - `[input]` integer `k` `1 ≤ k ≤ 9.` - `[output]` an integer array The first and the last indices of the longest subarray consisting of `k` only, as an array in the format `(start, end)`, or `(-1, -1)` if `k` is not present in `a`. # Example For `a = [2,1,1,1,1,3,3,4,5,1,1,1] and k = 3`, the output should be `(5, 6)`. The longest subarray of a that contains 3s starts at index 5 and ends at index 6. For `a = [2,1,1,1,1,3,3,4,5,1,1,1,1] and k = 1`, the output should be `(9, 12)`. There are two subarrays of 1, and they have equal length. One goes from index 1 to 4, and another one from index 9 to 12. The answer should be `(9, 12)` as it is the last to occur. For `a = [1, 2, 3] and k = 9`, the output should be `(-1, -1)`.
reference
from itertools import groupby def find_subarray_with_same_element(a, k): return (s := 0) or max((i for x, g in groupby(a) if (i := (s, (s := s + len(list(g))) - 1)) and x == k), key=lambda r: (r[1] - r[0], r), default=(- 1, - 1))
Simple Fun #208: Find Sub Array With Same Element
58feb7ac627d2fdadf000111
[ "Fundamentals" ]
https://www.codewars.com/kata/58feb7ac627d2fdadf000111
6 kyu
# Task Pero has been into robotics recently, so he decided to make a robot that checks whether a deck of poker cards is complete. He’s already done a fair share of work - he wrote a programme that recognizes the suits of the cards. For simplicity’s sake, we can assume that all cards have a suit and a number. The suit of the card is one of the characters `"P", "K", "H", "T"`, and the number of the card is an integer between `1` and `13`. The robot labels each card in the format `TXY` where `T` is the suit and `XY` is the number. If the card’s number consists of one digit, then X = 0. For example, the card of suit `"P"` and number `9` is labelled `"P09"`. A complete deck has `52` cards in total. For each of the four suits there is exactly one card with a number between `1` and `13`. The robot has read the labels of all the cards in the deck and combined them into the string `s`. Your task is to help Pero finish the robot by writing a program that reads the string made out of card labels and returns the number of cards that are missing for each suit. If there are two same cards in the deck, return array with `[-1, -1, -1, -1]` instead. # Input/Output - `[input]` string `s` A correct string of card labels. 0 ≤ |S| ≤ 1000 - `[output]` an integer array Array of four elements, representing the number of missing card of suits `"P", "K", "H", and "T"` respectively. If there are two same cards in the deck, return `[-1, -1, -1, -1]` instead. # Example For `s = "P01K02H03H04"`, the output should be `[12, 12, 11, 13]`. `1` card from `"P"` suit, `1` card from `"K"` suit, `2` cards from `"H"` suit, no card from `"T"` suit. For `s = "H02H10P11H02"`, the output should be `[-1, -1, -1, -1]`. There are two same cards `"H02"` in the string `s`.
reference
from collections import defaultdict def cards_and_pero(s): deck = defaultdict(set) for n in range(0, len(s), 3): card = s[n: n + 3] if card[1:] in deck[card[0]]: return [- 1, - 1, - 1, - 1] deck[card[0]] |= {card[1:]} return [13 - len(deck[suit]) for suit in "PKHT"]
Simple Fun #201: Cards And Pero
58fd4bbe017b2ed4e700001b
[ "Fundamentals" ]
https://www.codewars.com/kata/58fd4bbe017b2ed4e700001b
6 kyu