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 |
---|---|---|---|---|---|---|---|
An architect wants to construct a vaulted building supported by a family of arches C<sub>n</sub>.
f<sub>n</sub>(x) = -nx - xlog(x) is the equation of the arch C<sub>n</sub> where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let f<sub>n</sub>(0) = 0.
Be A<sub>n</sub> the point of C<sub>n</sub> where the tangent to C<sub>n</sub> is horizontal and B<sub>n+1</sub> the orthogonal projection of A<sub>n</sub> on the x-axis (it means that A<sub>n</sub> and B<sub>n+1</sub> have the same x -coordinate).
K<sub>n</sub> is the intersection of C<sub>n</sub> with the x-axis.
The figure shows C<sub>0</sub>, A<sub>0</sub>, B<sub>1</sub>, K<sub>0</sub> as C(0), A0, B1, K0.

The architect wants to support each arch C<sub>n</sub> with a wall of glass filling the **curved** surface A<sub>n</sub> B<sub>n+1</sub> K<sub>n</sub> under the curve C<sub>n</sub>.
On the drawing you can see the surface `A0 B1 K0` in blue.
He asks if we could calculate the weight of the surface of glass he needs to support all arches C<sub>0</sub>...C<sub>n</sub> where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface.
He gives us the absolute value of A<sub>0</sub> B<sub>1</sub> K<sub>0</sub> area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units.
#### Task
Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness.
This function should return the weight of n glass walls as described above.
#### Examples
```
weight(10, 700) -> 120.21882500408238
weight(8, 1108) -> 190.28922301858418
```
#### Hint:
There is no integral to calculate. You can plot C<sub>1</sub> and try to see the relationship between the different C<sub>n</sub> and then use `i0`.
#### Notes:
- don't round or truncate your result
- please ask before translating | reference | weight = lambda n, w, e = __import__('math'). exp(- 2): (1 - 3 * e) / (1 - e) / 4 * (1 - e * * n) * w
| Architect's Dream: drawing curves, observing, thinking | 5db19d503ec3790012690c11 | [
"Fundamentals"
] | https://www.codewars.com/kata/5db19d503ec3790012690c11 | 6 kyu |
Story:
In the realm of numbers, the apocalypse has arrived. Hordes of zombie numbers have infiltrated and are ready to turn everything into undead. The properties of zombies are truly apocalyptic: they reproduce themselves unlimitedly and freely interact with each other. Anyone who equals them is doomed. Out of an infinite number of natural numbers, only a few remain. This world needs a hero who leads remaining numbers in hope for survival: The highest number to lead those who still remain.
Briefing:
There is a list of positive natural numbers. Find the largest number that cannot be represented as the sum of this numbers, given that each number can be added unlimited times. Return this number, either 0 if there are no such numbers, or -1 if there are an infinite number of them.
Example:
```
Let's say [3,4] are given numbers. Lets check each number one by one:
1 - (no solution) - good
2 - (no solution) - good
3 = 3 won't go
4 = 4 won't go
5 - (no solution) - good
6 = 3+3 won't go
7 = 3+4 won't go
8 = 4+4 won't go
9 = 3+3+3 won't go
10 = 3+3+4 won't go
11 = 3+4+4 won't go
13 = 3+3+3+4 won't go
```
...and so on. So 5 is the biggest 'good'. return 5
Test specs:
Random cases will input up to 10 numbers with up to 1000 value
Special thanks:
Thanks to <a href=https://www.codewars.com/users/Voile>Voile-sama</a>, <a href=https://www.codewars.com/users/mathsisfun>mathsisfun-sama</a>, and <a href=https://www.codewars.com/users/Avanta>Avanta-sama</a> for heavy assistance. And to everyone who tried and beaten the kata ^_^
| algorithms | def gcd(a, b): # Just a simple Euclidean algorithm to compute gcd
while (b != 0):
a, b = b, a % b
return a
def survivor(zombies):
if (len(zombies) == 0): # First let's deal with lists of length == 0
return - 1
zombies . sort() # Then let's sort the list
if zombies[0] == 1: # If zombie[0] is 1, we know every number will be biten
return 0
####################################################################
# Let's check if there is an infinity of solutions. #
# It is equivalent to see if gcd of all numbers is different from 1.#
####################################################################
zombies_gcd = 0
for z in zombies:
zombies_gcd = gcd(z, zombies_gcd)
if zombies_gcd != 1:
return - 1
####################################################################
# Now let's list every number to see who's the last one to be bitten#
####################################################################
length = zombies[- 1] + 1
who_is_bitten = [False for i in range(length)]
for z in zombies: # Of courses zombies are considered as bitten
who_is_bitten[z] = True
# We know that zombies[0]-1 is a survivor so we can begin by that number
i = zombies[0] - 1
# We keep track of the number of consecutive zombies
consecutive_zombies = 0
# we know if there are zombies[0] consecutive zombies in a row,
while (consecutive_zombies < zombies[0]):
# then there won't be any survivor after that
# If the number is not bitten, then it becomes the new last survivor
if not (who_is_bitten[i]):
result = i
consecutive_zombies = 0
else: # Otherwise, it bites other numbers which are at range
consecutive_zombies += 1
# if the list is too short we have to add new numbers
while (i + zombies[- 1] >= len(who_is_bitten)):
who_is_bitten . append(False)
for z in zombies:
# Then number i bites numbers that are at its range
who_is_bitten[i + z] = True
i += 1
return result
| Zombie Apocalypse: the Last Number Standing | 5d9b52214a336600216bbd0e | [
"Algorithms"
] | https://www.codewars.com/kata/5d9b52214a336600216bbd0e | 4 kyu |
Positive integers have so many gorgeous features.
Some of them could be expressed as a sum of two or more consecutive positive numbers.
___
### Consider an Example :
* `10` could be expressed as the sum of `1 + 2 + 3 + 4 `.
___
## Task
**_Given_** *Positive integer*, N , return true if it could be expressed as a sum of two or more consecutive positive numbers , otherwise return false .
___
### Notes
~~~if-not:clojure,csharp,java,scala
* Guaranteed constraint : **_2 β€ N β€ (2^32) -1_** .
~~~
~~~if:clojure,csharp,java,scala
* Guaranteed constraint : **_2 β€ N β€ (2^31) -1_** .
~~~
___
### Input >> Output Examples:
```cpp
* consecutiveDucks(9) ==> return (true) // 9 , could be expressed as a sum of ( 2 + 3 + 4 ) or ( 4 + 5 ) .
* consecutiveDucks(64) ==> return (false)
* consecutiveDucks(42) ==> return (true) // 42 , could be expressed as a sum of ( 9 + 10 + 11 + 12 ) .
```
```prolog
* consecutive_ducks(9) ==> true % 9 could be expressed as a sum of (2 + 3 + 4) or (4 + 5).
* consecutive_ducks(64) ==> false
* consecutive_ducks(42) ==> true % 42 could be expressed as a sum of (9 + 10 + 11 + 12).
```
#### [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
#### [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
#### [Bizarre Sorting-katas](https://www.codewars.com/collections/bizarre-sorting-katas)
#### [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
##### ALL translations are welcomed
#### Enjoy Learning !!
##### Zizou | games | from math import log2
def consecutive_ducks(n):
return not log2(n). is_integer()
| Consecutive Digits To Form Sum | 5dae2599a8f7d90025d2f15f | [
"Fundamentals",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5dae2599a8f7d90025d2f15f | 7 kyu |
Suppose we know the process by which a string `s` was encoded to a string `r` (see explanation below). The aim of the kata is to decode this string `r` to get back the original string `s`.
#### Explanation of the encoding process:
- input: a string `s` composed of lowercase letters from "a" to "z", and a positive integer `num`
- we know there is a correspondence between `abcde...uvwxyz`and `0, 1, 2 ..., 23, 24, 25` : `0 <-> a, 1 <-> b ...`
- if `c` is a character of `s` whose corresponding number is `x`, apply to `x` the function `f: x-> f(x) = num * x % 26`, then find `ch` the corresponding character of `f(x)`
- Accumulate all these `ch` in a string `r`
- concatenate `num` and `r` and return the result
For example:
```
encode("mer", 6015) --> "6015ekx"
m --> 12, 12 * 6015 % 26 = 4, 4 --> e
e --> 4, 4 * 6015 % 26 = 10, 10 --> k
r --> 17, 17 * 6015 % 26 = 23, 23 --> x
So we get "ekx", hence the output is "6015ekx"
```
#### Task
A string `s` was encoded to string `r` by the above process. complete the function to get back `s` *whenever it is possible*.
Indeed it can happen that the decoding is impossible for strings composed of whatever letters from "a" to "z" when positive integer num has not been correctly chosen. In that case return `"Impossible to decode"`.
#### Examples
```
decode "6015ekx" -> "mer"
decode "5057aan" -> "Impossible to decode"
```
| reference | from string import ascii_lowercase as aLow
def decode(r):
i = next(i for i, c in enumerate(r) if c . isalpha())
n, r = int(r[: i]), r[i:]
maps = {chr(97 + n * i % 26): c for i, c in enumerate(aLow)}
return "Impossible to decode" if len(maps) != 26 else '' . join(maps[c] for c in r)
| Reversing a Process | 5dad6e5264e25a001918a1fc | [
"Fundamentals"
] | https://www.codewars.com/kata/5dad6e5264e25a001918a1fc | 6 kyu |
You need count how many valleys you will pass.
Start is always from zero level.
Every time you go down below 0 level counts as an entry of a valley, and as you go up to 0 level from valley counts as an exit of a valley.
One passed valley is equal one entry and one exit of a valley.
```
s='FUFFDDFDUDFUFUF'
U=UP
F=FORWARD
D=DOWN
```
To represent string above
```
(level 1) __
(level 0)_/ \ _(exit we are again on level 0)
(entry-1) \_ _/
(level-2) \/\_/
```
So here we passed one valley | algorithms | def counting_valleys(s):
level, valleys = 0, 0
for step in s:
if step == 'U' and level == - 1:
valleys += 1
level += {'U': 1, 'F': 0, 'D': - 1}[step]
return valleys
| Counting Valleys | 5da9973d06119a000e604cb6 | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/5da9973d06119a000e604cb6 | 7 kyu |
<h3>Introduction</h3>
Imagine a function that maps a number from a given range, to another, desired one. If this is too vague - let me explain a little bit further: let's take an arbitrary number - `2` for instance - and map it with this function from range `0-5` to, let's say - `10-20`. Our number lies in `2/5` of the way in it's original range, so in order to map it to the desired one we need to find a number that lies exactly in the same place, but in our new range. This number, in this case, is `14`. You can visualize this as taking a 5cm piece of rubber, putting it next to the ruler, marking the dot on the second centimeter, then stretching the rubber between 10th and 20th centimeter and reading the value next to the dot.
<h3>Task</h3>
The task in this kata is, unfortunately, a little bit more complex. We will take the same idea, but apply it to the 2-dimensional plane, so instead of single numbers, we will consider vectors with their x-position and y-position, instead of ranges, we will look at the circles with given centers and radii.
You need to write a function called `map_vector` (or `mapVector`) that takes 3 arguments - `vector`, `circle1`, `circle2` and returns a tuple/array/slice of x, y positions of the mapped vector. All three arguments will be tuples (arrays), the first one with x, y positions of a base vector, the second and third with x, y positions of the center of a circle and it's radius. The base vector will always be within the first circle and you need to map it from the first circle to the second. The coordinates should be precise up to second decimal place.
<h3>Examples</h3>
Let's take a look at a simple example:
```
vector = 5, 5
circle1 = 10, 20, 42
circle2 = -100, -42, 69
```
As we see, the vector's cartesian coordinates are x=5, y=5, first's circle's center is in x=10, y=20, it's radius is 42, and so on. Let's visualize it:<br />
<img src="https://i.ibb.co/nnfjCt4/ex1.png" /><br />
The red dot is our given vector. After running our function we should get our new, mapped vector with coordinates x=-108.21, y=-66.64. Take a look at the light-blue dot here:<br />
<img src="https://i.ibb.co/Gx6dgxT/ex2.png" /><br />
So, to represent this with code:
```python
map_vector((5, 5), (10, 20, 42), (-100, -42, 69)) == (-108.21, -66.64)
```
```java
mapVector([5, 5], [10, 20, 42], [-100, -42, 69]) == [-108.21, -66.64]
```
```javascript
mapVector([5, 5], [10, 20, 42], [-100, -42, 69]) === [-108.21, -66.64]
```
```typescript
mapVector([5, 5], [10, 20, 42], [-100, -42, 69]) === [-108.21, -66.64]
```
```julia
mapvector([5, 5], [10, 20, 42], [-100, -42, 69]) == [-108.21, -66.64]
```
```go
MapVector([5, 5], [10, 20, 42], [-100, -42, 69]) == [-108.21, -66.64]
```
Two, very important things to notice here are:
<ul>
<li>The distance between a vector and a circle's center is scaled accordingly to the second circle's radius</li>
<li>The angle between the vector and the line x=c1.x is preserved (c1.x == first circle's center's x position)</li>
</ul>
It is also worth to mention, that when both circles' radii are equal, this is equivalent of just translating the vector by the distance between them, and when the circles are concentric this is roughly equivalent to the mapping function mentioned in the introduction.
<h3>Notes</h3>
Although it is not really a problem, but for simplicity the given vector will always be contained within the first circle. The plane in random tests is a square with sides ranging between `-400` to `400`.
<h3>Tip</h3>
It may not be necessary, but if you're stuck, think about the most iconic animal that pops to mind when thinking about the negative influence of the climate changes on our planet's habitat.
Enjoy, and don't hesitate to comment on any mistakes or problems with this kata.
| algorithms | def map_vector(vector, circle1, circle2):
(vx, vy), (x1, y1, r1), (x2, y2, r2) = vector, circle1, circle2
v = (complex(vx, vy) - complex(x1, y1)) / r1 * r2 + complex(x2, y2)
return v . real, v . imag
| 2D Vector Mapping | 5da995d583326300293ce4cb | [
"Mathematics",
"Algorithms",
"Geometry"
] | https://www.codewars.com/kata/5da995d583326300293ce4cb | 7 kyu |
# A History Lesson
Tetris is a puzzle video game originally designed and programmed by Soviet Russian software engineer Alexey Pajitnov. The first playable version was completed on June 6, 1984. Pajitnov derived its name from combining the Greek numerical prefix tetra- (the falling pieces contain 4 segments) and tennis, Pajitnov's favorite sport.
# About scoring system
The scoring formula is built on the idea that more difficult line clears should be awarded more points. For example, a single line clear is worth `40` points, clearing four lines at once (known as a Tetris) is worth `1200`.
A level multiplier is also used. The game starts at level `0`. The level increases every ten lines you clear. Note that after increasing the level, the total number of cleared lines is not reset.
For our task you can use this table:
<style>
.demo {
width:70%;
border:1px solid #C0C0C0;
border-collapse:collapse;
padding:5px;
}
.demo th {
border:1px solid #C0C0C0;
padding:5px;
}
.demo td {
border:1px solid #C0C0C0;
padding:5px;
}
</style>
<table class="demo">
<tr>
<th>Level</th>
<th>Points for 1 line<br></th>
<th>Points for 2 lines</th>
<th>Points for 3 lines</th>
<th>Points for 4 lines</th>
</tr>
<tr>
<td>0</td>
<td>40</td>
<td>100<br></td>
<td>300</td>
<td>1200</td>
</tr>
<tr>
<td>1</td>
<td>80</td>
<td>200</td>
<td>600</td>
<td>2400</td>
</tr>
<tr>
<td>2</td>
<td>120</td>
<td>300</td>
<td>900</td>
<td>3600</td>
</tr>
<tr>
<td>3</td>
<td>160</td>
<td>400</td>
<td>1200</td>
<td>4800</td>
</tr>
<tr>
<td>...</td>
</tr>
<tr>
<td>7</td>
<td>320</td>
<td>800</td>
<td>2400</td>
<td>9600</td>
</tr>
<tr>
<td>...</td>
<td colspan = "4">For level n you must determine the formula by yourself using given examples from the table.</td>
</tr>
</table>
# Task
Calculate the final score of the game using original Nintendo scoring system
# Input
Array with cleaned lines.
Example: `[4, 2, 2, 3, 3, 4, 2]`
Input will always be valid: array of random length (from `0` to `5000`) with numbers from `0` to `4`.
# Ouput
Calculated final score.
`def get_score(arr) -> int: return 0`
# Example
```c
get_score({4, 2, 2, 3, 3, 4, 2}); // returns 4900
```
```javascript
getScore([4, 2, 2, 3, 3, 4, 2]); // returns 4900
```
```julia
getscore([4, 2, 2, 3, 3, 4, 2]); # returns 4900
```
```python
get_score([4, 2, 2, 3, 3, 4, 2]); # returns 4900
```
```typescript
getScore([4, 2, 2, 3, 3, 4, 2]); // returns 4900
```
<b>Step 1:</b> `+1200` points for 4 lines (current level `0`). Score: `0+1200=1200`;\
<b>Step 2:</b> `+100` for 2 lines. Score: `1200+100=1300`;\
<b>Step 3:</b> `+100`. Score: `1300+100=1400`;\
<b>Step 4:</b> `+300` for 3 lines (current level still `0`). Score: `1400+300=1700`.\
Total number of cleaned lines 11 (`4 + 2 + 2 + 3`), so level goes up to `1` (level ups each 10 lines);\
<b>Step 5:</b> `+600` for 3 lines (current level `1`). Score: `1700+600=2300`;\
<b>Step 6:</b> `+2400`. Score: `2300+2400=4700`;\
<b>Step 7:</b> `+200`. Total score: `4700+200=4900` points.
# Other
If you like the idea: leave feedback, and there will be more katas in the Tetris series.
* <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-white-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>7 kyu</span></div></div><a href="/kata/5da9af1142d7910001815d32">Tetris Series #1 β Scoring System</a></div>
* <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-yellow-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>6 kyu</span></div></div><a href="/kata/5db8a241b8d7260011746407">Tetris Series #2 β Primitive Gameplay</a></div>
* <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-yellow-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>6 kyu</span></div></div>Tetris Series #3 β Adding Rotation (TBA)</div>
* <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-yellow-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>5 kyu</span></div></div>Tetris Series #4 β New Block Types (TBA)</div>
* <div class="item-title"><div class="small-hex is-extra-wide is-inline mrm is-blue-rank" border="false"><div class="inner-small-hex is-extra-wide "><span>4 kyu</span></div></div>Tetris Series #5 β Complex Block Types (TBA?)</div> | reference | points = [0, 40, 100, 300, 1200]
def get_score(arr) - > int:
cleared = 0
score = 0
for lines in arr:
level = cleared / / 10
score += (level + 1) * points[lines]
cleared += lines
return score
| Tetris Series #1 β Scoring System | 5da9af1142d7910001815d32 | [
"Fundamentals",
"Games",
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/5da9af1142d7910001815d32 | 7 kyu |
Rotate a 2D array by 1 / 8<sup>th</sup> of a full turn
### Example
```haskell
rotateCW,rotateCCW :: [[a]] -> [[a]]
rotateCW [ "ab"
, "cd"
]
-> [ "a"
, "cb"
, "d"
]
rotateCCW [ "ab"
, "cd"
]
-> [ "b"
, "ad"
, "c"
]
```
```python
rotate_cw([ "ab",
"cd"])
== [ "a",
"cb",
"d"]
rotate_ccw([ "ab",
"cd"])
== [ "b",
"ad",
"c"]
```
### Notes
* Input will be rectangular, and may be square
* Input may be empty in either dimension
* Result elements need no leading or trailing padding
* ( where applicable ) Do not mutate the input
~~~if:python
#### Python
* Inputs and outputs will be iterables of iterables (eg. `list` of `list` or `list` of `str`)
~~~ | algorithms | def rotate_cw(seq, cw=1):
if not seq or not seq[0]:
return []
lst = [[] for i in range(len(seq) + len(seq[0]) - 1)]
for i in range(len(seq)):
for j in range(len(seq[0])):
lst[i + j * cw + int(cw / 2 - 0.5) * (- len(seq[0]) + 1)
]. append(seq[i][j])
return ["" . join(i)[:: - cw] for i in lst] if type(lst[0][0]) is str else [i[:: - cw] for i in lst]
def rotate_ccw(seq): return rotate_cw(seq, cw=- 1)
| Rotate 1 / 8th | 5da74bf201735a001180def7 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5da74bf201735a001180def7 | 6 kyu |
You have inherited some Python code related to high school physics. The previous coder is obviously on cracks since the codebase has this kind of pattern all over the place:
```python
LENGTH_UNITS = type('LENGTH_UNITS', (object,), {})
LENGTH_UNITS.pc = 3.08567758149137e16
LENGTH_UNITS.AU = 149597870700
LENGTH_UNITS.km = 10**3
LENGTH_UNITS.mm = 10**-3
LENGTH_UNITS.Β΅m = 10**-6
LENGTH_UNITS.nm = 10**-9
EM_LABELS = type('EM_LABELS', (object,), {})
EM_LABELS.A = 'current'
EM_LABELS.V = 'voltage'
EM_LABELS.β¦ = 'resistance'
EM_LABELS.W = 'power'
```
The enhancement you're tasked to do is to refactor these code to use [collections.namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple) which is better suited for usages like this. It looks very easy, or so it seems... after you finished writing your code, there are some weird, headscratching errors when you run your unit test code. Looks like it's not as simple as you might think.
---
Note: If you understand the point of this kata, there are cases where ambiguities could arise: such cases will not appear in the tests. Also, attribute names passed in will not contain duplicates or invalid attributes (e.g `obj.def` or `obj.123`). | bug_fixes | from collections import namedtuple
from unicodedata import normalize
def create_namedtuple_cls(cls_name, fields):
d = {normalize('NFKC', f): f for f in fields}
class Data (namedtuple(cls_name, fields)):
def __getattr__(self, item):
return self . __getattribute__(d[item]) if item in d else None
Data . __name__ = cls_name
return Data
| The Doppelganger Enigma | 5da558c930187300114d874e | [
"Debugging"
] | https://www.codewars.com/kata/5da558c930187300114d874e | 5 kyu |
_This Kata is a variation of **Histogram - V1**_
**Kata in this series**
* [Histogram - H1](https://www.codewars.com/kata/histogram-h1/)
* [Histogram - H2](https://www.codewars.com/kata/histogram-h2/)
* [Histogram - V1](https://www.codewars.com/kata/histogram-v1/)
* [Histogram - V2](https://www.codewars.com/kata/histogram-v2/)
---
## Background
A 6-sided die is rolled a number of times and the results are plotted as percentages in a character-based vertical histogram.
### Example
Data: `[14, 6, 140, 30, 0, 10]`
<pre style='font-family:monospace;color:orange;line-height:20px;font-size:16px;'>
70%
ββ
ββ
ββ
ββ
ββ
ββ
ββ
ββ 15%
7% ββ ββ
ββ 3% ββ ββ 5%
------------------
1 2 3 4 5 6
</pre>
# Kata Task
You will be passed the dice value frequencies, and your task is to write the code to return a string representing a histogram, so that when it is printed it has the same format as the example.
## Notes
* There are no trailing spaces on the lines
* All lines (including the last) end with a newline ```\n```
* The percentage is displayed above each bar except when it is 0%
* When displaying percentages always floor/truncate to the nearest integer
* Less than 1% (but not zero) should be written as `<1%`
* The total number of rolls varies, but won't exceed 1,000
* The bar lengths are scaled so that 100% = 15 x bar characters
* When calculating bar lengths always floor/truncate to the nearest integer
* The bar character is `β`, which is the Unicode U+2588 char
| reference | def histogram(results):
r = []
m = max(results)
s = sum(results)
if s != 0:
for i in range(m * 15 / / s, - 1, - 1):
l = []
for j in range(6):
c = []
a = results[j] * 15 / / s
b = results[j] * 100 / / s
if a == i:
if b != 0:
c += f' { b } %'
elif b == 0 and results[j] != 0:
c += '<1%'
elif i < a:
c += 'ββ'
else:
c += ' '
if len(c) < 3:
c += ' ' * (3 - len(c))
l += c
line = '' . join(l). rstrip(' ')
if len(line):
r += line + '\n'
r += "------------------\n"
r += " 1 2 3 4 5 6\n"
return '' . join(r)
| Histogram - V2 | 5d5f5f25f8bdd3001d6ff70a | [
"Fundamentals"
] | https://www.codewars.com/kata/5d5f5f25f8bdd3001d6ff70a | 5 kyu |
# The Challenge
Write a function that returns the number of significant figures in a given number. You can read about significant figures below.
## Helpful information
* the type of the given number will be string
* you must return the number of significant figures as type int
* no blank strings will be given
## Significant Figures
### What are they?
Significant Figures are the meaningful digits in a measured or computed value.
# Counting significant figures
### All non-zero digits are significant
* 4.357 has 4 significant figures
* 152.63 has 5 significant figures
### Zeroes at the beginning of a number are *not* significant
* 0215 has 3 significant figures
* 0.6 has 1 significant figure
### Trailing zeroes in a number with a decimal point are significant
* 78.200 has 5 significant figures
* 20.0 has 3 significant figures
### Trailing zeroes in a number without a decimal point are *not* significant
* 1200 has 2 significant figures
* 345000 has 3 significant figures
### All zeroes between significant figures are significant
* 90.09 has 4 significant figures
* 5050 has 3 significant figures
| algorithms | def number_of_sigfigs(number):
s = number . lstrip("0")
if "." in s:
if s[0] == ".":
return len(s[1:]. lstrip("0")) or 1
return len(s) - 1
return len(s . rstrip("0"))
| Significant Figures | 5d9fe0ace0aad7001290acb7 | [
"Mathematics",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5d9fe0ace0aad7001290acb7 | 7 kyu |
# Description
Given a number `n`, you should find a set of numbers for which the sum equals `n`. This set must consist exclusively of values that are a power of `2` (eg: `2^0 => 1, 2^1 => 2, 2^2 => 4, ...`).
The function `powers` takes a single parameter, the number `n`, and should return an array of unique numbers.
## Criteria
The function will always receive a valid input: any positive integer between `1` and the max integer value for your language (eg: for JavaScript this would be `9007199254740991` otherwise known as `Number.MAX_SAFE_INTEGER`).
The function should return an array of numbers that are a **power of 2** (`2^x = y`).
Each member of the returned array should be **unique**. (eg: the valid answer for `powers(2)` is `[2]`, not `[1, 1]`)
Members should be sorted in **ascending order** (small -> large). (eg: the valid answer for `powers(6)` is `[2, 4]`, not `[4, 2]`) | algorithms | def powers(n):
return [1 << i for i, x in enumerate(reversed(bin(n))) if x == "1"]
| Sum of powers of 2 | 5d9f95424a336600278a9632 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5d9f95424a336600278a9632 | 7 kyu |
# Background
Different sites have different password requirements.
You have grown tired of having to think up new passwords to meet all the different rules, so you write a small piece of code to do all the thinking for you.
# Kata Task
Return any valid password which matches the requirements.
Input:
```if:python
* `length` = password must be this length
```
```if-not:python
* `len` = password must be this length
```
* `flagUpper` = must (or must not) contain UPPERCASE alpha
* `flagLower` = must (or must not) contain lowercase alpha
* `flagDigit` = must (or must not) contain digit
# Notes
* Only alpha-numeric characters are permitted
* The same character cannot occur more than once in the password!
* All test cases guarantee that a valid password is possible | reference | import re
def make_password(length, flagUpper, flagLower, flagDigit):
password = "1aA2bB3cC4dD5eE6fF7gG8hH9iI0jJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"
if not flagUpper:
password = re . sub('[A-Z]', '', password)
if not flagLower:
password = re . sub('[a-z]', '', password)
if not flagDigit:
password = re . sub('[0-9]', '', password)
return password[: length]
| Password Maker | 5b3d5ad43da310743c000056 | [
"Fundamentals"
] | https://www.codewars.com/kata/5b3d5ad43da310743c000056 | 6 kyu |
_This Kata is a variation of **Histogram - H1**_
**Kata in this series**
* [Histogram - H1](https://www.codewars.com/kata/histogram-h1/)
* [Histogram - H2](https://www.codewars.com/kata/histogram-h2/)
* [Histogram - V1](https://www.codewars.com/kata/histogram-v1/)
* [Histogram - V2](https://www.codewars.com/kata/histogram-v2/)
---
## Background
A 6-sided die is rolled a number of times and the results are plotted as percentages of the total in a character-based horizontal histogram.
Example:
```
6|ββ 5%
5|
4|βββββββ 15%
3|βββββββββββββββββββββββββββββββββββ 70%
2|β 3%
1|βββ 7%
```
## Task
You will be passed the dice value frequencies, and your task is to write the code to return a string representing a histogram, so that when it is printed it has the same format as the example.
## Notes
* There are no trailing spaces on the lines
* All lines (including the last) end with a newline ```\n```
* The percentage is displayed beside each bar except where it is 0%
* The total number of rolls varies, but won't exceed 10,000
* The bar lengths are scaled so that 100% = 50 x bar characters
* The bar character is `β`, which is the Unicode U+2588 char
* When calculating percentages and bar lengths always floor/truncate to the nearest integer
| reference | def histogram(results):
t = sum(results)
return "" . join(f' { i + 1 } | { "β" * ( 50 * results [ i ] / / t )} { 100 * results [ i ] / / t } %\n' if results[i] else f' { i + 1 } |\n' for i in range(len(results) - 1, - 1, - 1))
| Histogram - H2 | 5d5f5ea8e3d37b001dfd630a | [
"Fundamentals"
] | https://www.codewars.com/kata/5d5f5ea8e3d37b001dfd630a | 7 kyu |
Given an integer perimeter, `0 < p <= 1 000 000`, find all right-angled triangles with perimeter `p` that have integral side lengths.
#### Your Task
- Complete the `integerRightTriangles` (or `integer_right_triangles`) function.
- Each element of the solution array should contain the integer side lengths of a valid triangle in increasing order.
#### Examples
````
integerRightTriangles(4); // []
integerRightTriangles(12); // [[3,4,5]]
integerRightTriangles(120); // [[20,48,52], [24,45,51], [30,40,50]]
```` | algorithms | LENGTHS = {12: [3, 4, 5], 30: [5, 12, 13], 70: [20, 21, 29], 40: [8, 15, 17], 56: [7, 24, 25], 176: [48, 55, 73], 126: [28, 45, 53], 208: [39, 80, 89], 408: [119, 120, 169], 198: [36, 77, 85], 154: [33, 56, 65], 234: [65, 72, 97], 84: [12, 35, 37], 90: [9, 40, 41], 330: [88, 105, 137], 260: [60, 91, 109], 546: [105, 208, 233], 1026: [297, 304, 425], 476: [84, 187, 205], 456: [95, 168, 193], 736: [207, 224, 305], 286: [44, 117, 125], 418: [57, 176, 185], 1218: [336, 377, 505], 828: [180, 299, 349], 1178: [217, 456, 505], 2378: [696, 697, 985], 1188: [220, 459, 509], 800: [175, 288, 337], 1160: [319, 360, 481], 390: [52, 165, 173], 340: [51, 140, 149], 900: [252, 275, 373], 570: [120, 209, 241], 644: [115, 252, 277], 1364: [396, 403, 565], 714: [136, 273, 305], 374: [85, 132, 157], 494: [133, 156, 205], 144: [16, 63, 65], 132: [11, 60, 61], 532: [140, 171, 221], 442: [104, 153, 185], 1044: [203, 396, 445], 1924: [555, 572, 797], 874: [152, 345, 377], 918: [189, 340, 389], 1518: [429, 460, 629], 608: [96, 247, 265], 1116: [155, 468, 493], 2146: [464, 777, 905], 1950: [429, 700, 821], 920: [120, 391, 409], 986: [145, 408, 433], 1716: [195, 748, 773], 2050: [369, 800, 881], 2220: [420, 851, 949], 1240: [279, 440, 521], 1680: [455, 528, 697], 510: [60, 221, 229], 700: [75, 308, 317], 1890: [432, 665, 793], 1848: [280, 759, 809], 1794: [273, 736, 785], 1776: [407, 624, 745], 2296: [615, 728, 953], 646: [68, 285, 293], 598: [69, 260, 269], 1998: [540, 629, 829], 1488: [336, 527, 625], 2132: [451, 780, 901], 1242: [184, 513, 545], 1254: [165, 532, 557], 1450: [200, 609, 641], 864: [135, 352, 377], 2184: [616, 663, 905], 1334: [276, 493, 565], 1320: [231, 520, 569], 1550: [300, 589, 661], 690: [
161, 240, 289], 850: [225, 272, 353], 220: [20, 99, 101], 182: [13, 84, 85], 782: [204, 253, 325], 672: [160, 231, 281], 1702: [333, 644, 725], 1392: [240, 551, 601], 1540: [315, 572, 653], 1050: [168, 425, 457], 2150: [301, 900, 949], 1674: [216, 713, 745], 1968: [287, 816, 865], 1100: [132, 475, 493], 1886: [205, 828, 853], 1508: [156, 667, 685], 798: [76, 357, 365], 1054: [93, 476, 485], 966: [84, 437, 445], 928: [87, 416, 425], 2170: [248, 945, 977], 2064: [215, 912, 937], 1554: [185, 672, 697], 1628: [259, 660, 709], 2236: [387, 884, 965], 1102: [261, 380, 461], 1302: [341, 420, 541], 312: [24, 143, 145], 240: [15, 112, 113], 1080: [280, 351, 449], 950: [228, 325, 397], 2030: [348, 805, 877], 2322: [473, 864, 985], 1612: [260, 651, 701], 1914: [232, 825, 857], 1736: [168, 775, 793], 1150: [92, 525, 533], 1480: [111, 680, 689], 1350: [100, 621, 629], 1330: [105, 608, 617], 1610: [385, 552, 673], 1850: [481, 600, 769], 420: [28, 195, 197], 306: [17, 144, 145], 1426: [368, 465, 593], 1276: [308, 435, 533], 2294: [372, 925, 997], 1566: [108, 725, 733], 1978: [129, 920, 929], 1798: [116, 837, 845], 1804: [123, 836, 845], 2214: [533, 756, 925], 544: [32, 255, 257], 380: [19, 180, 181], 1820: [468, 595, 757], 1650: [400, 561, 689], 2046: [124, 957, 965], 684: [36, 323, 325], 462: [21, 220, 221], 2262: [580, 741, 941], 2072: [504, 703, 865], 840: [40, 399, 401], 552: [23, 264, 265], 1012: [44, 483, 485], 650: [25, 312, 313], 1200: [48, 575, 577], 756: [27, 364, 365], 1404: [52, 675, 677], 870: [29, 420, 421], 1624: [56, 783, 785], 992: [31, 480, 481], 1860: [60, 899, 901], 1122: [33, 544, 545], 1260: [35, 612, 613], 1406: [37, 684, 685], 1560: [39, 760, 761], 1722: [41, 840, 841], 1892: [43, 924, 925]}
def integer_right_triangles(p):
out = []
for length in LENGTHS:
d, m = divmod(p, length)
if not m:
out.append([x*d for x in LENGTHS[length]])
return sorted(out, key=lambda x: x[0])
| Integer Right Triangles | 562c94ed7549014148000069 | [
"Algorithms"
] | https://www.codewars.com/kata/562c94ed7549014148000069 | 5 kyu |
### Story
You just returned from a car trip, and you are curious about your fuel consumption during the trip. Unfortunately, you didn't reset the counter before you started, but you have written down the average consumption of the car and the previous distance travelled at that time. Looking at the dashboard, you note the current data...
### Task
Complete the function that receives two pairs of input (`before, after`), and return the *calculated* average fuel consumption of your car during your trip, rounded to 1 decimal.
Both pairs consist of 2 valid numbers:
* the average consumption of the car (`l/100km`, float)
* the previous distance travelled (`km`, integer)
<!--
**NOTE:** To avoid floating point issues, **use rounding only in the very last step!**
-->
### Examples
```
BEFORE AFTER DURING
avg. cons, distance avg. cons, distance avg. cons
[l/100km] [km] [l/100km] [km] [l/100km]
[ 7.9 , 100 ] , [ 7.0 , 200 ] --> 6.1
[ 7.9 , 500 ] , [ 7.0 , 600 ] --> 2.5
[ 7.9 , 100 ] , [ 7.0 , 600 ] --> 6.8
```
---
### My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-)
#### *Translations are welcome!* | algorithms | def solve(before, after):
(avg1, dist1), (avg2, dist2) = before, after
return round((avg2 * dist2 - avg1 * dist1) / (dist2 - dist1), 1)
| Average Fuel Consumption | 5d96030e4a3366001d24b3b7 | [
"Algorithms"
] | https://www.codewars.com/kata/5d96030e4a3366001d24b3b7 | 7 kyu |
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.
We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...
Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?
The function `crusoe` has parameters;
- n : numbers of steps in the process
- d : initial chosen distance
- ang : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult : constant multiplier of the previous angle
`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.
#### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->
The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)
The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)
and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
#### A drawing:

Successive points:
- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`
#### Note
Please could you ask before translating? | reference | from math import cos, sin, radians
def crusoe(n, d, ang, dist_mult, ang_mult):
x, y, a = 0, 0, radians(ang)
for i in range(n):
x += d * cos(a)
y += d * sin(a)
d *= dist_mult
a *= ang_mult
return x, y
| Robinson Crusoe | 5d95b7644a336600271f52ba | [
"Fundamentals"
] | https://www.codewars.com/kata/5d95b7644a336600271f52ba | 7 kyu |
Imagine an `n x n` grid where each box contains a number. The top left box always contains 1 and each box in a clockwise spiral from there will contain the next natural number. (see below)
```
1 - 2 - 3 - 4
|
12 - 13 - 14 5
| | |
11 16 - 15 6
| |
10 - 9 - 8 - 7
```
**Task**
Given `n` and a value `col` where `1 <= col <= n`, return the sum of the values in column `col` (i.e. column 1 is the left-most column, column 2 is the second from the left, etc.)
**Examples**
```
spiralColumn(4,1) === 34 // 1 + 12 + 11 + 10
spiralColumn(4,2) === 40 // 2 + 13 + 16 + 9
```
**Notes**
Tests will involve large inputs where `1e5 <= n <= 1e6`. Some consideration for performance needs to be given. | games | # Special cases for first and last column are possible but not needed
# Rule nΒ°1 of those katas, there's ALWAYS a formula
def spiral_column(n, c):
n2, n3, c2, c3 = n * * 2, n * * 3, c * * 2, c * * 3
nc, nc2, n2c = n * c, n * c2, n2 * c
if 2 * c <= n:
return (24 * n2c - 3 * n2 - 48 * nc2 + 6 * nc + 3 * n + 32 * c3 - 6 * c2 - 2 * c) / / 6
return (8 * n3 - 24 * n2c + 9 * n2 + 48 * nc2 - 42 * nc + 7 * n - 32 * c3 + 42 * c2 - 10 * c) / / 6
| Spiral Column Addition | 5d95118fdb5c3c0001a55c9b | [
"Mathematics",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5d95118fdb5c3c0001a55c9b | 6 kyu |
This kata is a follow-up of **[Domino Tiling - 2 x N Board](https://www.codewars.com/kata/domino-tiling-2-x-n-board)**. If you haven't already done so, you might want to solve that one first.
Did you find a nice solution to that kata using some type of memoization? Well then...
# Memoization won't save you this time!
The previous kata asked you to calculate the number of ways you can fill a `2 x N` grid with dominoes of `K` different colors, under the constraint that dominoes sharing an edge must not be of the same color. You can find a detailed description with examples in the previous kata.
**Here is your next challenge:** Solve the exact same problem as before, but for **much larger N**.
# Constraints
`1 <= N <= 1000000000000000000`
`1 <= K <= 100`
Since the answer will be very large, please give your answer **modulo 12345787**.
Are you up for the challenge? | games | class Modular (int):
def __new__(cls, n):
return super(). __new__(cls, n % 12345787)
def __add__(self, other):
return Modular(super(). __add__(other))
def __mul__(self, other):
return Modular(super(). __mul__(other))
@ staticmethod
def asmatrix(matrix):
from numpy import mat
return mat([[Modular(n) for n in row] for row in matrix], dtype=Modular)
def two_by_n(n, k):
b = [[k], [2 * k * (k - 1)]]
m = [[0, 1], [(k - 1) * * 2, k - 2]]
m = Modular . asmatrix(m)
return (m * * (n - 1) * b)[0]
| Domino Tiling - 2 x N Board -- Challenge Edition! | 5c1905cc16537c7782000783 | [
"Puzzles",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5c1905cc16537c7782000783 | 4 kyu |
# Kata Task
Connect the dots in order to make a picture!
# Notes
* There are 2-26 dots labelled `a` `b` `c` ...
* Make lines to connect the dots `a` -> `b`, `b` -> `c`, etc
* The line char is `*`
* Use only straight lines - vertical, horizontal, or diagonals of a square
* The paper is rectangular - `\n` terminates every line
* All input is valid
# Examples
<table border='1' style='width:50%'>
<tr><th style='width:50%'>Input</th><th>Expected</th></tr>
<tr><td>
<pre style='background:black;font-size:20px;line-height:20px;font-family:monospace;'>
a b
d c
</pre>
</td>
<td>
<pre style='background:black;font-size:20px;line-height:20px;font-family:monospace;'>
*********
*
*
*********
</pre></td></tr>
</table>
<table border='1' style='width:50%;'>
<tr><th style='width:50%'>Input</th><th>Expected</th></tr>
<tr><td>
<pre style='background:black;font-size:20px;line-height:20px;font-family:monospace;'>
a
e
d b
c
</pre></td><td>
<pre style='background:black;font-size:20px;line-height:20px;font-family:monospace;'>
*
* *
* *
* *
* *
* *
*
</pre></td></tr>
</table> | reference | def connect_the_dots(paper):
Y = paper . find("\n") + 1
lst = list(paper)
pts = {c: i for i, c in enumerate(paper) if c . isalpha()}
chrs = sorted(pts)
for i in range(len(pts) - 1):
a, b = sorted((pts[chrs[i]], pts[chrs[i + 1]]))
(x, y), (u, v) = divmod(a, Y), divmod(b, Y)
dx, dy = Y * ((u > x) - (u < x)), (v > y) - (v < y)
for j in range(a, b + 1, dx + dy):
lst[j] = '*'
return '' . join(lst)
| Connect the Dots | 5d6a11ab2a1ef8001dd1e817 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d6a11ab2a1ef8001dd1e817 | 6 kyu |
Given a string `s` of uppercase letters, your task is to determine how many strings `t` (also uppercase) with length equal to that of `s` satisfy the followng conditions:
* `t` is lexicographical larger than `s`, and
* when you write both `s` and `t` in reverse order, `t` is still lexicographical larger than `s`.
```Haskell
For example:
solve('XYZ') = 5. They are: YYZ, ZYZ, XZZ, YZZ, ZZZ
```
String lengths are less than `5000`. Return you answer `modulo 10^9+7 (= 1000000007)`.
More examples in test cases. Good luck! | reference | def solve(s):
r, l = 0, 0
for c in s:
m = ord('Z') - ord(c)
r, l = r + m + l * m, m + l * 26
return r % 1000000007
| String counting | 5cfd36ea4c60c3001884ed42 | [
"Fundamentals"
] | https://www.codewars.com/kata/5cfd36ea4c60c3001884ed42 | 6 kyu |
A system is transmitting messages in binary, however it is not a perfect transmission, and sometimes errors will occur which result in a single bit flipping from 0 to 1, or from 1 to 0.
To resolve this, A 2-dimensional Parity Bit Code is used: https://en.wikipedia.org/wiki/Multidimensional_parity-check_code
In this system, a message is arrayed out on a M x N grid. A 24-bit message could be put on a 4x6 grid like so:
<br>
<i>
>1 0 1 0 0 1<br>
>1 0 0 1 0 0<br>
>0 1 1 1 0 1<br>
>1 0 0 0 0 1</i>
Then, Parity bits are computed for each row and for each column, equal to 1 if there is an odd number of 1s in the row of column, and 0 if it is an even number. The result for the above message looks like:
<br>
<i>
>1 0 1 0 0 1 <b>1</b><br>
>1 0 0 1 0 0 <b>0</b><br>
>0 1 1 1 0 1 <b>0</b><br>
>1 0 0 0 0 1 <b>0</b><br>
><b>1 1 0 0 0 1</b></i>
Since the 1st row, and 1st, 2nd and 6th column each have an odd number of 1s in them, and the others all do not.
Then the whole message is sent, including the parity bits. This is arranged as:
> message + row_parities + column_parities<br>
> 101001100100011101100001 + 1000 + 110001<br>
> 1010011001000111011000011000110001
If an error occurs in transmission, the parity bit for a column and row will be incorrect, which can be used to identify and correct the error. If a row parity bit is incorrect, but all column bits are correct, then we can assume the row parity bit was the one flipped, and likewise if a column is wrong but all rows are correct.
<h2> Your Task: </h2>
Create a function <code>correct</code>, which takes in integers M and N, and a string of bits where the first M\*N represent the content of the message, the next M represent the parity bits for the rows, and the final N represent the parity bits for the columns. A single-bit error may or may not have appeared in the bit array.
The function should check to see if there is a single-bit error in the coded message, correct it if it exists, and return the corrected string of bits.
| algorithms | def correct(m, n, bits):
l = m * n
row = next((i for i in range(
m) if f" { bits [ i * n :( i + 1 ) * n ]}{ bits [ l + i ]} " . count("1") % 2), None)
col = next((i for i in range(
n) if f" { bits [ i : l : n ]}{ bits [ l + m + i ]} " . count("1") % 2), None)
if row is col is None:
return bits
err = (l + row) if col is None else (l + m +
col) if row is None else (row * n + col)
return f" { bits [: err ]}{ int ( bits [ err ]) ^ 1 }{ bits [ err + 1 :]} "
| Error Correction Codes | 5d870ff1dc2362000ddff90b | [
"Algorithms"
] | https://www.codewars.com/kata/5d870ff1dc2362000ddff90b | 6 kyu |
Your job is to fix the parentheses so that all opening and closing parentheses (brackets) have matching counterparts. You will do this by appending parenthesis to the beginning or end of the string. The result should be of minimum length. Don't add unnecessary parenthesis.
The input will be a string of varying length, only containing '(' and/or ')'.
For example:
```
Input: ")("
Output: "()()"
Input: "))))(()("
Output: "(((())))(()())"
```
Enjoy! | refactoring | def fix_parentheses(stg):
original, o, c = stg, "(", ")"
while "()" in stg:
stg = stg . replace("()", "")
opening, closing = o * stg . count(c), c * stg . count(o)
return f" { opening }{ original }{ closing } "
| Balance the parentheses | 5d8365b570a6f6001519ecc8 | [
"Refactoring"
] | https://www.codewars.com/kata/5d8365b570a6f6001519ecc8 | 7 kyu |
At the start of each season, every player in a football team is assigned their own unique squad number. Due to superstition or their history certain numbers are more desirable than others.
Write a function generateNumber() that takes two arguments, an array of the current squad numbers (squad) and the new player's desired number (n). If the new player's desired number is not already taken, return n, else if the desired number can be formed by adding two digits between 1 and 9, return the number formed by joining these two digits together. E.g. If 2 is taken, return 11 because 1 + 1 = 2. Otherwise return null.
Note: Often there will be several different ways to form a replacement number. In these cases the number with lowest first digit should be given priority. E.g. If n = 15, but squad already contains 15, return 69, not 78.
| algorithms | def generate_number(squad, n):
if n not in squad:
return n
for i in range(1, 10):
for j in range(1, 10):
if i + j == n and i * 10 + j not in squad:
return i * 10 + j
| Squad number generator | 5d62961d18198b000e2f22b3 | [
"Algorithms"
] | https://www.codewars.com/kata/5d62961d18198b000e2f22b3 | 7 kyu |
You are writing a password validator for a website. You want to discourage users from using their username as part of their password, or vice-versa, because it is insecure. Since it is unreasonable to simply not allow them to have any letters in common, you come up with this rule:
**For any password and username pair, the length of the longest common substring should be less than half the length of the shortest of the two.**
In other words, you won't allow users to have half their password repeated in their username, or half their username repeated in their password.
Write a function `validate(username, password)` which returns `true` if your rule is followed, `false` otherwise.
Assume:
* Both the username and the password may contain uppercase letters, lowercase letters, numbers, spaces, and the following special/punctation characters: `!@#$%^&*()_+{}:"<>?[];',.`
* The username and password will each be less than 100 characters.
| reference | from difflib import SequenceMatcher
def validate(username, password):
l1, l2 = len(username), len(password)
match = SequenceMatcher(
None, username, password). find_longest_match(0, l1, 0, l2)
return match . size < min(l1, l2) / 2
| Password should not contain any part of your username. | 5c511d8877c0070e2c195faf | [
"Regular Expressions",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5c511d8877c0070e2c195faf | 7 kyu |
If the first day of the month is a Friday, it is likely that the month will have an `Extended Weekend`. That is, it could have five Fridays, five Saturdays and five Sundays.
In this Kata, you will be given a start year and an end year. Your task will be to find months that have extended weekends and return:
```
- The first and last month in the range that has an extended weekend
- The number of months that have extended weekends in the range, inclusive of start year and end year.
```
For example:
```python
solve(2016,2020) = ("Jan","May",5). #The months are: Jan 2016, Jul 2016, Dec 2017, Mar 2019, May 2020
```
```haskell
solve 2016 2020 = ("Jan","May",5). -- The months are: Jan 2016, Jul 2016, Dec 2017, Mar 2019, May 2020
```
```ruby
solve(2016,2020) = ["Jan","May",5]. #The months are: Jan 2016, Jul 2016, Dec 2017, Mar 2019, May 2020
```
```javascript
solve(2016,2020) = ["Jan","May",5]. //The months are: Jan 2016, Jul 2016, Dec 2017, Mar 2019 and May 2020
```
```java
solve(2016,2020) = ["JANUARY","MAY","5"]. //The months are: Jan 2016, Jul 2016, Dec 2017, Mar 2019 and May 2020
```
```cpp
solve(2016,2020) = ["Jan","May","5"]. //The months are: Jan 2016, Jul 2016, Dec 2017, Mar 2019 and May 2020
```
More examples in test cases. Good luck!
If you found this Kata easy, please try [myjinxin2015](https://www.codewars.com/users/myjinxin2015) challenge version [here](https://www.codewars.com/kata/extended-weekends-challenge-edition) | reference | from calendar import month_abbr
from datetime import datetime
def solve(a, b):
res = [month_abbr[month]
for year in range(a, b + 1)
for month in [1, 3, 5, 7, 8, 10, 12]
if datetime(year, month, 1). weekday() == 4]
return (res[0], res[- 1], len(res))
| Extended weekends | 5be7f613f59e0355ee00000f | [
"Fundamentals"
] | https://www.codewars.com/kata/5be7f613f59e0355ee00000f | 7 kyu |
# Task
In 10 years of studying, Alex has received a lot of diplomas. He wants to hang them on his wall, but unfortunately it's made of stone and it would be too difficult to hammer so many nails in it.
Alex decided to buy a square desk to hang on the wall, on which he is going to hang his diplomas. Your task is to find the smallest possible size of the desk he needs.
Alex doesn't want to rotated his diplomas, and they shouldn't overlap.
Given the height `h` and the width `w` of each diploma, as well as their number `n`, find the minimum desk size.
# Input/Output
`[input]` integer `h`
The height of each diploma, `1 β€ h β€ 10000`.
`[input]` integer `w`
The width of each diploma, `1 β€ w β€ 10000`.
`[input]` integer `n`
The number of diplomas, `0 β€ n β€ 10000`.
`[output]` an integer
The minimum desk size.
# Example
For `h = 2, w = 3 and n = 10`, the output should be `9`.
A `9 x 9` square desk can hang all 10 diplomas.
For `h = 1, w = 1 and n = 1`, the output should be `1`.
A `1 x 1` square desk can hang a `1 x 1` diploma.
For `h = 17, w = 21 and n = 0`, the output should be `0`.
Alex has no diploma, so he doesn't need a desk ;-) | games | def diplomas(h, w, n):
x = int((h * w * n) * * .5)
while (x / / h) * (x / / w) < n:
x += 1
return x
| Simple Fun #274: Diplomas | 591592b0f05d9a3019000087 | [
"Puzzles"
] | https://www.codewars.com/kata/591592b0f05d9a3019000087 | 7 kyu |
In this kata you will try to recreate a simple code-breaking game. It is called "Bulls and Cows". The rules are quite simple:
The computer generates a secret number consisting of 4 distinct digits. Then the player, in 8 turns, tries to guess the number. As a result he receives from the computer the number of matches. If the matching digits are in their right positions, they are "bulls", if in different positions, they are "cows".
To implement this you will use:
1)a constructor (int) - initiates the game, receives a number and then sets it as the secret number.
2)and a function "compare with (int)" - compares the given and the secret numbers and then returns a String formated as "X bull/bulls and Y cow/cows".
However, there are some notes:
1)if the given number matches the secret number instead of returning "4 bulls and 0 cows", return "You win!". Any next attempts to play the game (even with invalid numbers) should return "You already won!"
2)if the amount of turns in this game is more than 8 (invalid turns are not counted) the returned String should be "Sorry, you're out of turns!".
3)After checking the turns you should validate the given number. If it does not correspond to the conditions you should throw an exception :
``` java
IllegalArgumentException
```
``` python
ValueError```
E.g.:
``` java
Game starts with the secret number 9041
compare with : 8091
result : "2 bulls and 1 cow" //The bulls are "0" and "1", the cow is "9"
compare with : -15555
result : Exception //A number should be positive and contain 4 distinct digits.
//This turn is not counted
compare with : 8237
result : "0 bulls and 0 cows"
compare with : 9041
result : "You win!"
//new comparations (even with invalid numbers) will result in : "You already won!"
//the same logic applies to being out of turns
```
```python
Game starts with the secret number 9041
compare with : 8091
result : "2 bulls and 1 cow" # The bulls are "0" and "1", the cow is "9"
compare with : -15555
result : Exception # A number should be positive and contain 4 distinct digits.
# This turn is not counted
compare with : 8237
result : "0 bulls and 0 cows"
compare with : 9041
result : "You win!"
# new comparations (even with invalid numbers) will result in : "You already won!"
# the same logic applies to being out of turns
``` | reference | class BullsAndCows:
def __init__(self, n):
if not self . allowed(n):
raise ValueError()
self . n, self . turns, self . solved = str(n), 0, False
def plural(self, n): return 's' if n != 1 else ''
def allowed(self, n): return 1234 <= n <= 9876 and len(
set(c for c in str(n))) == 4
def compare_with(self, n):
if self . solved:
return 'You already won!'
if self . turns >= 8:
return 'Sorry, you\'re out of turns!'
if self . n == str(n):
self . solved = True
return 'You win!'
if not self . allowed(n):
raise ValueError()
self . turns += 1
bulls = sum(a == b for a, b in zip(self . n, str(n)))
cows = max(len({e for e in self . n} & {e for e in str(n)}) - bulls, 0)
return f' { bulls } bull { self . plural ( bulls )} and { cows } cow { self . plural ( cows )} '
| Bulls and Cows | 5be1a950d2055d589500005b | [
"Games",
"Fundamentals",
"Strings",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5be1a950d2055d589500005b | 7 kyu |
You are the rock paper scissors oracle.
Famed throughout the land, you have the incredible ability to predict which hand gestures your opponent will choose out of rock, paper and scissors.
Unfortunately you're no longer a youngster, and have trouble moving your hands between rounds. For this reason, you can only pick a single gesture for each opponent.
If it's possible for you to win, you will, but you're also happy to tie.
Given an array of gestures β for example `["paper", "scissors", "scissors"]` β return the winning gesture/s in the order in which they appear in the title, separated by a forward slash. For example, if rock and scissors could both be used to win you would return:
`"rock/scissors"`
If it's not possible for you to win then return:
`"tie"`
See https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors if you're not familiar with rock paper scissors.
Second attempt at my first Kata... | reference | from collections import Counter
def oracle(gestures):
res, C = [], Counter(gestures)
if C["scissors"] > C["paper"]:
res . append("rock")
if C["rock"] > C["scissors"]:
res . append("paper")
if C["paper"] > C["rock"]:
res . append("scissors")
return "/" . join(res) or "tie"
| Rock Paper Scissors Oracle | 580535462e7b330bd300003d | [
"Fundamentals"
] | https://www.codewars.com/kata/580535462e7b330bd300003d | 7 kyu |
# I'm already Tracer
*Note*: this is an easy Kata, but requires a bit of knowledge about the game Overwatch. Feel free to skip the background section if you are familiar with the game!
# Background
Overwatch is a team-based online First Person Shooter. Teams are made up of 6 **unique** heroes. No team can have 2 of the same hero. e.g. You can't play Tracer if I'm already Tracer.
Heroes belong to **1 of 3 categories**:
- **Tank**
- Tank heroes soak up damage, create space for your team, and break apart fortified positions, like closely-grouped enemies and narrow choke-points. If youβre a tank, you lead the charge.
- **Damage**
- Damage heroes are responsible for seeking out, engaging, and defeating the enemy using their varied tools and abilities. Playing a damage hero means it is your duty to secure kills.
- **Support**
- Support heroes empower their allies by healing them, boosting their damage, and providing vital utility. As support, youβre the backbone of your teamβs survival.
https://overwatch.gamepedia.com/Template:Heroes
# Challenge:
```javascript
teamComp()
```
```python
team_comp()
```
Your goal is to write a function that will tell you your team "comp" (composition, i.e. balance of hero categories).
## Input:
Array of hero names.
Example:
```javascript
['Reinhardt', 'TorbjΓΆrn', 'Mei', 'Pharah', 'Ana', 'Brigitte']
```
## Output:
Array showing # of counts for each hero category. (Team Composition)
Example:
```javascript
[1, 3, 2] // [(tank), (damage), (support)]
```
# Helpers
Feel free to use `TANK`, `DAMAGE`, and `SUPPORT` - preloaded arrays of hero names in alphabetical order. Examples:
```javascript
TANK[0] // D.Va
DAMAGE[1] // Bastion
SUPPORT[2] // LΓΊcio
```
# Invalid Team Composition
In the case of an invalid team comp:
- Fewer or greater than 6 heroes
- A hero appears more than once on the team
...
```javascript
throw new Error('GG');
```
```python
raise InvalidTeam()
# Note: this exception is defined in the preloaded section,
# no need to define it yourself!
``` | reference | ALL_SETS = tuple(map(set, (TANK, DAMAGE, SUPPORT)))
def team_comp(heroes):
s = set(heroes)
if len(heroes) != 6 or len(s) != 6:
raise InvalidTeam()
return [len(s & ss) for ss in ALL_SETS]
| I'm already Tracer | 5c15dd0fb48e91d81b0000c6 | [
"Games",
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5c15dd0fb48e91d81b0000c6 | 7 kyu |
_This kata is based on [Project Euler Problem 546](https://projecteuler.net/problem=546)_
# Objective
Given the recursive sequence
```math
f_k(n) = \sum_{i=1}^n f_k(\text{floor}(i/k)), \text{where} f_k(0)=1
```
Define a function `f` that takes arguments `k` and `n` and returns the nth term in the sequence f<sub>k</sub>
## Examples
`f(2, 3)` = f<sub>2</sub>(3) = 6
`f(2, 200)` = f<sub>2</sub>(200) = 7389572
`f(7, 500)` = f<sub>7</sub>(500) = 74845
`f(1000, 0)` = f<sub>1000</sub>(0) = 1
**Note:**
No error checking is needed, `k` ranges from 2 to 100 and `n` ranges between 0 and 500000 (mostly small and medium values with a few large ones)
As always any feedback would be much appreciated | algorithms | from math import floor
def f(k, n):
num = [1]
if n == 0:
return num[0]
for i in range(1, k):
num . append(i + 1)
for j in range(k, n + 1):
num . append(num[floor(j / k)] + num[j - 1])
if k > n:
return num[n]
return num[- 1]
| Recursive Floor Sequence | 56b85fc4f18876abf0000877 | [
"Algorithms"
] | https://www.codewars.com/kata/56b85fc4f18876abf0000877 | 5 kyu |
# Task
John won the championship of a TV show. He can get some bonuses.
He needs to play a game to determine the amount of his bonus.
Here are some cards in a row. A number is written on each card.
In each turn, John can take a card, but only from the beginning or the end of the row. Then multiply the number on the card by an coefficient 2<sup>i</sup>(i means the i<sub>th</sub> turn). The product is John's bonus of current turn.
After all the cards are taken away, the game is over. John's final bonus is the sum of all rounds of bonuses.
Obviously, the order in which John takes the cards will affect the amount of John's final bonus.
Your task is to help John calculate the maximum amount of bonuses he can get.
# Input
- `cards`: An integer array. Each element represents the number on the card.
- `1 <= cards.length <= 30`
- `1 <= cards[i] <= 100`
- All inputs are valid.
# Output
An integer. the maximum amount of bonuses John can get.
# Eaxmple
For `cards=[1,2,5]`, the output should be `50`.
```
All possible orders are:
1->2->5 bonus:1x2+2*4+5*8=50
1->5->2 bonus:1x2+5*4+2*8=38
5->1->2 bonus:5*2+1*4+2*8=30
5->2->1 bonus:5*2+2*4+1*8=26
The maximum amount of bonus is 50.
```
| algorithms | def calc(a):
res = [0] * (len(a) + 1)
for k in range(len(a)):
res = [2 * max(a[i] + res[i + 1], a[i + k] + res[i])
for i in range(len(a) - k)]
return res[0]
| Kata 2019: Bonus Game I | 5c2d5de69611562191289041 | [
"Algorithms",
"Dynamic Programming"
] | https://www.codewars.com/kata/5c2d5de69611562191289041 | 5 kyu |
Traditionally, all programming languages implement the 3 most common boolean operations: `and`, `or`, `not`. These three form the complete boolean algebra, i.e. every possible boolean function from `N` arguments can be decomposed into combination of arguments and `and`, `or`, `not`.
In the school we have learned, that only 2 operations (`not` and 1 of remaining) is enough to form a complete algebra, and the last one can be expressed as a combination of the former. A great kata to test that: https://www.codewars.com/kata/boolean-logic-from-scratch/python
Several other operations may form a complete boolean algebra, i.e. `xor`, `1` and `and`. However, we are interested in an operation, which forms boolean algebra all by itself: Sheffer stroke (another operation with such a property is Peirce's arrow).
Sheffer stroke is defined as follows:
```
sheffer(False, False) = True
sheffer(False, True) = True
sheffer(True, False) = True
sheffer(True, True) = False
```
# The task:
Implement functions `and`, `not` and `or` by only using the preloaded `sheffer` function. Using built-in boolean primitives is disallowed.
`Note`: for reasons of banning strange solutions, using anonymous functions is also disallowed.
| reference | # sheffer of same thing twice returns opposite
def NOT(a):
return sheffer(a, a)
# return true only if a and b are true, which is NOT sheffer
def AND(a, b):
return NOT(sheffer(a, b))
# sheffer of each variable's NOT flip's sheffer's truth table
def OR(a, b):
return sheffer(NOT(a), NOT(b))
| Sheffer stroke | 5d82344d687f21002c71296e | [
"Fundamentals"
] | https://www.codewars.com/kata/5d82344d687f21002c71296e | 7 kyu |
## What is a Catalan number?
In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects. They are named after the Belgian mathematician EugΓ¨ne Charles Catalan (1814β1894).
Using zero-based numbering, the nth Catalan number is given directly in terms of binomial coefficients by:
<img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/dbc424e9c15a763d9bdd8b096cec7138993dad4a" style="background: white;"/>
You can read more on Catalan numbers [Here](https://en.wikipedia.org/wiki/Catalan_number).
## Task:
Implement a function which calculates the Nth Catalan number.
```
0 => 1
3 => 5
7 => 429
9 => 4862
```
*Hint: avoid the use of floats*
Have fun :) | algorithms | from math import factorial
def nth_catalan_number(n):
return factorial(2 * n) / / factorial(n + 1) / / factorial(n)
| Find the Nth Catalan number | 579637b41ace7f92ae000282 | [
"Big Integers",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/579637b41ace7f92ae000282 | 6 kyu |
# Task
Follow the instructions in each failing test case to write logic that calculates the total price when ringing items up at a cash register.
# Purpose
Practice writing maintainable and extendable code.
# Intent
This kata is meant to emulate the real world where requirements change over time. This kata does not provide a specification for the final end-state up front. Instead, it walks you through a series of requirements, modifying and extending them via test cases as you go. This kata is about the journey, not the destination. Your ability to write maintainable and extendable code will affect how difficult this kata is.
# Provided Utility Function
You may use the following preloaded function:
```python
get_price(item)
"""Accepts a str specifying an item. Returns the price of
the item (float) or raises a KeyError if no price is available.
Example:
>>> get_price(apple)
0.4
"""
```
# Acknowledgement
Inspired by http://codekata.com/kata/kata01-supermarket-pricing/. To get the most benefit from this kata, I would recommend visiting that page only after completing, not before. | algorithms | import re
class Checkout (object):
def __init__(self, d={}):
self . pricing, self . total, self . fruits, self . free = d, 0, {}, {}
def scan(self, n, qty=1):
item = get_price(n)
for i in range(qty):
if not self . free . get(n, 0):
self . total += item
self . fruits[n] = self . fruits . get(n, 0) + 1
else:
self . free[n] -= 1
continue
if n in self . pricing:
m = self . pricing[n]
if 'for' in m:
how, f = m . split("for")
if not self . fruits[n] % int(how):
self . total = self . total - item * int(how) + float(f)
elif 'buy' in m:
how, f = re . sub(r'buy|get', ' ', m). strip(). split()
if not self . fruits[n] % int(how):
self . free[n] = int(f)
elif 'off' in m:
how, f = re . sub(r'off|ormore', ' ', m). strip(). split()
if self . fruits[n] == int(f):
self . total -= float(how)
self . total = round(self . total, 2)
| Checkout Line Pricing | 57c8d7f8484cf9c1550000ff | [
"Algorithms"
] | https://www.codewars.com/kata/57c8d7f8484cf9c1550000ff | 5 kyu |
We will represent complex numbers in either cartesian or polar form as an array/list, using the first element as a type tag; the **normal** tags are `"cart"` (for cartesian) and `"polar"`. The forms of the tags depend on the language.
- ['cart', 3, 4]`represents the complex number `3+4i
- ['polar', 2, 3]` represents the complex number with modulus (or magnitude) `2` and angle `3
In the same way:
- `['cart', 1, 2, 3, 4, 5, 6]`includes the three complex numbers `1+2i, 3+4i, 5+6i`
- `['polar', 2, 1, 2, 2, 2, 3]` represents the complex numbers `(2, 1), (2, 2), (2, 3)`
in polar form where the magnitudes are `2, 2, 2` and the angles `1, 2, 3`
#### Note:
- The polar form of a complex number `z = a+bi` is `z = (r, ΞΈ) = r(cosΞΈ+isinΞΈ)`, where `r = |z| = the (non-negative) square-root of a^2+b^2` is the modulus.
- In the arrays/lists beginning by a tag all terms after the tag must be `integers` (no floats, no strings).
#### Task
Given a sequence of complex numbers `z` in one of the previous forms we first calculate the `sum` `s` of the `squared modulus` of
all complex elements of `z` if `z` is in correct form.
Our function `sqr-modulus` returns an array/list of three elements; the form of the list will depend on the language:
- the first element is a boolean:
`#t` or `True` or `true` if z is in correct form as defined previously (correct type of numbers, correct tag)
`#f` or `False` or `false` if z is not in correct form.
- the second element is the sum `s` of the *squared* modulus of all complex numbers in `z` if the returned boolean is true,
`-1` if it is false.
- the third element is the greatest number got by rearranging the digits of `s`. We will admit that the greatest number got from`-1` is `1`.
#### Examples (in general form):
See the exact form of the return for your language in "RUN SAMPLE TESTS"
```
sqr_modulus(['cart', 3, 4]) -> (True , 25, 52)
sqr_modulus(['cart', 3, 4, 3, 4]) -> (True , 50, 50)
sqr_modulus(['polar', 2531, 3261]) -> (True , 6405961, 9665410)
sqr_modulus(['polar', 2, 3, 2, 4]) -> (True , 8, 8)
sqr_modulus(['polar', "2", 3]) -> (False , -1, 1)
sqr_modulus(['polara', 2, 3]) -> (False , -1, 1)
sqr_modulus(['cart', 3, 4.1]) -> (False , -1, 1)
```
#### Notes:
- Racket: in Racket `(integer? 2.0)` returns `#t`
- Pascal: The given input is a string; the first substring is the tag; other substrings represent integers or floats or strings. The first element of return is `-1` for 'false' or `1` for true.
- Shell: in this kata an object will be an integer if it contains only **digits**.
- Perl see "Template Solution".
| reference | def sqr_modulus(z):
if not (z[0] in ('cart', 'polar') and all(isinstance(x, int) for x in z[1:])):
return (False, - 1, 1)
sm = sum(
(re * * 2 + im * * 2 for re, im in zip(z[1:: 2], z[2:: 2]))
if z[0] == 'cart' else
(r * * 2 for r in z[1:: 2]))
return (True, sm, int('' . join(sorted(str(sm), reverse=True))))
| Magnitude | 5cc70653658d6f002ab170b5 | [
"Fundamentals"
] | https://www.codewars.com/kata/5cc70653658d6f002ab170b5 | 6 kyu |
## Introduction

Each chemical element in its neutral state has a specific number of electrons associated with it. This is represented by the **atomic number** which is noted by an integer number next to or above each element of the periodic table (as highlighted in the image above).
As we move from left to right, starting from the top row of the periodic table, each element differs from its predecessor by 1 unit (electron). Electrons fill in different orbitals sets according to a specific order. Each set of orbitals, when full, contains an even number of electrons.
The orbital sets are:
* The _**s** orbital_ - a single orbital that can hold a maximum of 2 electrons.
* The _**p** orbital set_ - can hold 6 electrons.
* The _**d** orbital set_ - can hold 10 electrons.
* The _**f** orbital set_ - can hold 14 electrons.

The order in which electrons are filling the different set of orbitals is shown in the picture above. First electrons will occupy the **1s** orbital, then the **2s**, then the **2p** set, **3s** and so on.
Electron configurations show how the number of electrons of an element is distributed across each orbital set. Each orbital is written as a sequence that follows the order in the picture, joined by the number of electrons contained in that orbital set. The final electron configuration is a single string of orbital names and number of electrons per orbital set where the first 2 digits of each substring represent the orbital name followed by a number that states the number of electrons that the orbital set contains.
For example, a string that demonstrates an electron configuration of a chemical element that contains 10 electrons is: `1s2 2s2 2p6`. This configuration shows that there are two electrons in the `1s` orbital set, two electrons in the `2s` orbital set, and six electrons in the `2p` orbital set. `2 + 2 + 6 = 10` electrons total.
You can find out more about the topic of *electron configuration* at [this link](https://en.wikipedia.org/wiki/Electron_configuration).
___
# Task
Your task is to write a function that displays the electron configuration built according to the Madelung rule of all chemical elements of the periodic table. The argument will be the symbol of a chemical element, as displayed in the periodic table.
**Note**: There will be a preloaded array called `ELEMENTS` with chemical elements sorted by their atomic number.
For example, when the element "O" is fed into the function the output should look like:
`"O -> 1s2 2s2 2p4"`
However, there are some exceptions! The electron configurations of the elements below should end as:
```
Cr -> ...3d5 4s1
Cu -> ...3d10 4s1
Nb -> ...4d4 5s1
Mo -> ...4d5 5s1
Ru -> ...4d7 5s1
Rh -> ...4d8 5s1
Pd -> ...4d10 5s0
Ag -> ...4d10 5s1
La -> ...4f0 5d1
Ce -> ...4f1 5d1
Gd -> ...4f7 5d1 6s2
Pt -> ...4f14 5d9 6s1
Au -> ...4f14 5d10 6s1
Ac -> ...5f0 6d1 7s2
Th -> ...5f0 6d2 7s2
Pa -> ...5f2 6d1 7s2
U -> ...5f3 6d1 7s2
Np -> ...5f4 6d1 7s2
Cm -> ...5f7 6d1 7s2
```
**Note**: for `Ni` the electron configuration should be `3d8 4s2` instead of `3d9 4s1`. | reference | EXCEPTIONS = {
'Cr': ['Ar', '4s1 3d5'],
'Cu': ['Ar', '4s1 3d10'],
'Nb': ['Kr', '5s1 4d4'],
'Mo': ['Kr', '5s1 4d5'],
'Ru': ['Kr', '5s1 4d7'],
'Rh': ['Kr', '5s1 4d8'],
'Pd': ['Kr', '5s0 4d10'],
'Ag': ['Kr', '5s1 4d10'],
'La': ['Xe', '6s2 4f0 5d1'],
'Ce': ['Xe', '6s2 4f1 5d1'],
'Gd': ['Xe', '6s2 4f7 5d1'],
'Pt': ['Xe', '6s1 4f14 5d9'],
'Au': ['Xe', '6s1 4f14 5d10'],
'Ac': ['Rn', '7s2 5f0 6d1'],
'Th': ['Rn', '7s2 5f0 6d2'],
'Pa': ['Rn', '7s2 5f2 6d1'],
'U': ['Rn', '7s2 5f3 6d1'],
'Np': ['Rn', '7s2 5f4 6d1'],
'Cm': ['Rn', '7s2 5f7 6d1'],
}
ORBITALS = "spdfg"
ELT_TO_Z = {elt: i for i, elt in enumerate(ELEMENTS, 1)}
for arr in EXCEPTIONS . values():
arr[1] = [(int(s[0]), ORBITALS . find(s[1]), s[2:])
for s in arr[1]. split(' ')]
def get_electron_configuration(element):
elt, repl = EXCEPTIONS . get(element, (element, []))
# n: principal quantum number / l: secondary qunatum number (minus 1) / nl: n+l
z, nl, config = ELT_TO_Z[elt], 0, {}
while z:
nl += 1
for l in range(nl - 1 >> 1, - 1, - 1):
nE = min(z, 2 + l * 4)
config[(nl - l, l)] = nE
z -= nE
if not z:
break
for a, b, n in repl:
config[(a, b)] = n
s = " " . join(f' { k [ 0 ] }{ ORBITALS [ k [ 1 ]] }{ n } ' for k, n in sorted(
config . items()))
return f' { element } -> { s } '
| Electron configuration of chemical elements | 597737709e2c45882700009a | [
"Arrays",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/597737709e2c45882700009a | 5 kyu |
In a far away country called AlgoLandia, there are `N` islands numbered `1` to `N`. Each island is denoted by `k[i]`. King Algolas, king of AlgoLandia, built `N - 1` bridges in the country. A bridge is built between islands `k[i]` and `k[i+1]`. Bridges are two-ways and are expensive to build.
The problem is that there are gangs who wants to destroy the bridges. In order to protect the bridges, the king wants to assign elite guards to the bridges. A bridge between islands `k[i]` and `k[i+1]` is safe when there is an elite guard in island `k[i]` or `k[i+1]`. There are already elite guards assigned in some islands.
Your task now is to determine the minimum number of additional elite guards that needs to be hired to guard all the bridges.
### Note:
You are given a sequence `k` with `N` length.
`k[i] = true`, means that there is an elite guard in that island; `k[i] = false` means no elite guard. It is guaranteed that AlgoLandia have at least `2` islands.
### Sample Input 1
```
k = [true, true, false, true, false]
```
### Sample Output 1
```
0
```
### Sample Input 2
```
k = [false, false, true, false, false]
```
### Sample Output 2
```
2
``` | algorithms | def find_needed_guards(k):
b = '' . join('1' if g else '0' for g in k)
return sum(len(ng) / / 2 for ng in b . split("1"))
| Guarding the AlgoLandia | 5d0d1c14c843440026d7958e | [
"Algorithms",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5d0d1c14c843440026d7958e | 7 kyu |
You will be given an array of non-negative integers and positive integer bin width.
Your task is to create the Histogram method that will return histogram data corresponding to the input array. The histogram data is an array that stores under index i the count of numbers that belong to bin i. The first bin always starts with zero.
On empty input you should return empty output.
Examples:
<ul>
<li>For input data [1, 1, 0, 1, 3, 2, 6] and binWidth=1 the result will be [1, 3, 1, 1, 0, 0, 1] as the data contains single element "0", 3 elements "1" etc.</li>
<li>For the same data and binWidth=2 the result will be [4, 2, 0, 1]</li>
<li>For input data [7] and binWidth=1 the result will be [0, 0, 0, 0, 0, 0, 0, 1]</li>
</ul> | algorithms | def histogram(lst, w):
lst = [n / / w for n in lst]
m = max(lst, default=- 1) + 1
return [lst . count(n) for n in range(m)]
| Histogram data | 5704bf9b38428f1446000a9d | [
"Fundamentals",
"Algorithms",
"Arrays",
"Data Science"
] | https://www.codewars.com/kata/5704bf9b38428f1446000a9d | 7 kyu |
This Kata is based on an old riddle.
A group of gnomes have been captured by an evil wizard who plans on transforming them into dolls for his collection.
He presents the gnomes with this challenge:
* At dawn of the next day he will place the gnomes in a straight line.
* He will place on the head of each gnome a red or blue hat without them seeing it.
* He will then walk the line and ask each gnome the color of their hat
* * If the gnome answers correctly they are warped out of the castle
* * If the gnome asnwers incorrectly they are turned into a doll that instant
Tonight the gnomes are allowed to make some plan to deal with this situation.
The wizard can use magic to hear their plans so he can always use that information to place
hats in such a way that the most gnomes will be transformed.
Even so there exists a plan which can save all but one of the gnomes. Can you guess it?
---
* Each gnome can hear the responses of the gnomes before them, but they are not allowed to turn around.
* Each gnome is allowed to look ahead and see the hats of the gnome in front of them, but not look back at the hats behind him.
Design a plan for the gnomes. This should be a function without any global state as wizards
are known to do tricky things if you don't follow the rules!
```
def guessMyHat(previous_guesses, hats_in_front):
#... figure out what to say ...
return "red" or "blue"
```
which returns either `red` or `blue` depending on what that gnome's response will be.
*At most 1 gnome is allowed to answer incorrectly.
All other gnomes must state only the color of their hat.* | games | def my_hat_guess(p, f):
return 'red' if (p . count('blue') + f . count('blue')) % 2 == 0 else 'blue'
| Gnomes and Hats: A Horror Story | 57c4f4ac0fe1438e630007c6 | [
"Puzzles"
] | https://www.codewars.com/kata/57c4f4ac0fe1438e630007c6 | 5 kyu |
Given an array of ones and zero(e)s that represents a positive binary number, convert the number to two's complement value.
Two's complement is the way most computers represent positive or negative integers. The most significant bit is `1` if the number is negative, and `0` otherwise.
Examples:
[1,1,1,1] = -1
[1,0,0,0] = -8
[1,1,0,1] = -3
To get the two's complement negative notation of an integer, you take the number in binary.
You then flip the bits, and add one (with carry) to the result.
For example:
[0,0,1,0] = 2 in base 10
[1,1,0,1] <- Flip the bits
Add 1 (with carry):
[1,1,1,0] = -2
The output array must have the same length as the input array. | reference | def positive_to_negative(arr):
flip = [0 if n == 1 else 1 for n in arr]
for i in range(len(flip)):
if flip[- (i + 1)] == 1:
flip[- (i + 1)] = 0
else:
flip[- (i + 1)] = 1
break
return flip
| Positive to negative binary numbers | 5becace7063291bebf0001d5 | [
"Binary",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5becace7063291bebf0001d5 | 7 kyu |
**Can you compute a cube as a sum?**
In this Kata, you will be given a number `n` (where `n >= 1`) and your task is to find `n` consecutive odd numbers whose sum is exactly the cube of `n`.
Mathematically:
```math
n^3 = a_1 + a_2 + a_3 + \ldots + a_n \\
a_2 = a_1 + 2, \quad a_3 = a_2 + 2, \quad \ldots, \quad a_n = a_{n-1} + 2 \\
a_1, a_2, \ldots, a_n \text{ are all odds} \\
```
For example:
```
n = 3, result = [7, 9, 11], because 7 + 9 + 11 = 27, the cube of 3. Note that there are only n = 3 elements in the array.
```
Write a function that when given `n`, will return an array of `n` consecutive odd numbers with the sum equal to the cube of n `(n*n*n)`. | games | def find_summands(n):
return list(range(n * n - n + 1, n * n + n + 1, 2))
| compute cube as sums | 58af1bb7ac7e31b192000020 | [
"Puzzles"
] | https://www.codewars.com/kata/58af1bb7ac7e31b192000020 | 6 kyu |
Create methods to convert between Bijective Binary strings and integers and back.
A bijective binary number is represented by a string composed only of the characters 1 and 2. Positions have the same value as in binary numbers, a string of repeated 1's has the same value in binary and bijective binary.
As there is no symbol for zero it is represented by an empty string.
Every non negative integer has a unique representation unlike binary where 1 = 0001.
https://en.wikipedia.org/wiki/Bijective_numeration
```
0 = ""
1 = "1"
2 = "2"
3 = "11"
4 = "12"
5 = "21"
6 = "22"
``` | algorithms | def bijective_to_int(b):
return sum(2 * * i * int(d) for i, d in enumerate(b[:: - 1]))
def int_to_bijective(n):
b = ""
while n:
b += "21" [n % 2]
n = (n - 1) / / 2
return b[:: - 1]
| Bijective Binary | 58f5e53e663082f9aa000060 | [
"Algorithms"
] | https://www.codewars.com/kata/58f5e53e663082f9aa000060 | 6 kyu |
The objective is to disambiguate two given names: the original with another
This kata is slightly more evolved than the previous one: [Author Disambiguation: to the point!](https://www.codewars.com/kata/580a429e1cb4028481000019).
The function ```could_be``` is still given the original name and another one to test
against.
```python
# should return True even with 'light' variations (more details in section below)
> could_be("Chuck Norris", u"chΓΌck!")
True
# should False otherwise (whatever you may personnaly think)
> could_be("Chuck Norris", "superman")
False
```
**Watch out**: When accents comes into the game, they will enter through **UTF-8 unicodes. **
The function should be tolerant with regards to:
* upper and lower cases: ```could_be(A, a) : True```
* accents: ```could_be(E, Γ©) : True```
* dots: ```could_be(E., E) : True```
* same for other ending punctuations in [!,;:?]: ```could_be(A, A!) : True```
On the other hand, more consideration needs to be given to *composed names*...
Let's be bold about it: if you have any, they will be considered as a whole :
```python
# We still have:
> could_be("Carlos Ray Norris", "Carlos Ray Norris")
True
> could_be("Carlos-Ray Norris", "Carlos-Ray Norris")
True
# But:
> could_be("Carlos Ray Norris", "Carlos-Ray Norris")
False
> could_be("Carlos-Ray Norris", "Carlos Ray Norris")
False
> could_be("Carlos-Ray Norris", "Carlos Ray-Norris")
False
```
Among the valid combinaisons of the fullname "Carlos Ray Norris", you will find
```python
could_be("Carlos Ray Norris", "carlos ray") : True
could_be("Carlos Ray Norris", "Carlos. Ray, Norris;") : True
could_be("Carlos Ray Norris", u"CarlΓ²s! Norris") : True
```
Too easy ? Try the next step: [Author Disambiguation: Signatures worth it](https://www.codewars.com/kata/author-disambiguation-signatures-worth-it) | algorithms | import re
def could_be(original, another):
a, b = [re . findall('[^ !.,;:?]+', x . lower(). strip())
for x in (original, another)]
return a != [] and b != [] and all(c in a for c in b)
| Author Disambiguation: a name is a Name! | 580a8f039a90a3654b000032 | [
"Puzzles",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/580a8f039a90a3654b000032 | 6 kyu |
Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> random.randint(0, 100)
93
```
Modules `random` and `os` are forbidden.
Dont forget to give feedback and your opinion on this kata even if you didn't solve it! | algorithms | class Random:
def __init__(self, seed: int = 0) - > None:
self . seed = seed
def randint(self, start: int, stop: int) - > int:
return start + int(self . random() * (stop - start + 1))
def random(self) - > float:
x = self . seed & 0xFFFFFFFF
x ^= x << 13 & 0xFFFFFFFF
x ^= x >> 17 & 0xFFFFFFFF
x ^= x << 5 & 0xFFFFFFFF
self . seed = x & 0xFFFFFFFF
return x / (1 << 32)
| Write your own pseudorandom number generator! | 5872a121056584c25400011d | [
"Algorithms"
] | https://www.codewars.com/kata/5872a121056584c25400011d | 6 kyu |
Everyone Knows AdFly and their Sister Sites.
If we see the Page Source of an ad.fly site we can see this perticular line:
```javascript
var ysmm = 'M=z=dQoPdZH5RWwTc0zIolvaLj2hFmkRZUi95ksMeFSR9VnWbuyF5zwVajHlAX/Od6Tx1EhdS5FIITwWY10VRVvbdjkBwnzWZXDlNFkceSTdVl0W';
```
Believe it or not This is actually the Encoded url which you would skip to.
The Algorithm is as Follows:
```
1) The ysmm value is broken like this
ysmm = 0 1 2 3 4 5 6 7 8 9 = "0123456789"
code1 = 0 2 4 6 8 = "02468"
code2 = 9 7 5 3 1 = "97531"
2) code1+code2 is base64 Decoded
3) The result will be of this form :
<int><int>https://adf.ly/go.php?u=<base64 encoded url>
4) <base64 encoded url> has to be further decoded and the result is to be returned
```
Your Task:
```
Make a function to Encode text to ysmm value.
and a function to Decode ysmm value.
```
Note: Take random values for The first 2 int values.
I personally hate trivial error checking like giving integer input in place of string.
```
Input For Decoder & Encoder: Strings
Return "Invalid" for invalid Strings
``` | algorithms | from base64 import b64decode, b64encode
from random import randint
def adFly_decoder(sc):
return b64decode(b64decode(sc[:: 2] + sc[:: - 2])[26:]) or "Invalid"
def adFly_encoder(url):
temp = b64encode(
"{:02d}https://adf.ly/go.php?u={}" . format(randint(0, 99), b64encode(url)))
return '' . join(x + y for x, y in zip(temp[: len(temp) / / 2 + 1], temp[: len(temp) / / 2 - 1: - 1]))
| AdFly Encoder and Decoder | 56896d1d6ba4e91b8c00000d | [
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/56896d1d6ba4e91b8c00000d | 5 kyu |
A `bouncy number` is a positive integer whose digits neither increase nor decrease. For example, 1235 is an increasing number, 5321 is a decreasing number, and 2351 is a bouncy number. By definition, all numbers under 100 are non-bouncy, and 101 is the first bouncy number.
Determining if a number is bouncy is easy, but counting all bouncy numbers with N digits can be challenging for large values of N. To complete this kata, you must write a function that takes a number N and return the count of bouncy numbers with N digits. For example, a "4 digit" number includes zero-padded, smaller numbers, such as 0001, 0002, up to 9999.
For clarification, the bouncy numbers between 100 and 125 are: 101, 102, 103, 104, 105, 106, 107, 108, 109, 120, and 121. | reference | def bouncy_count(m):
num = den = 1
for i in range(1, 11):
num *= m + i + i * (i == 10)
den *= i
return 10 * * m - num / / den + 10 * m + 1
| Bouncy Numbers with N Digits | 5769ac186f2dea6304000172 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5769ac186f2dea6304000172 | 5 kyu |
<h1>Castle of Cubes:</h1>
You've been hired by a castle building company.<br>
Their procedure is very simple : In their castles, all the rooms are the same cube.<br>
They build thousands of the same square stone panels, and assemble them (ground,walls,ceiling).<br>
Neighboring rooms share one same panel between them.<br>
Business is growing fast, so they need your help:<br>
the customer has only one variable: 'n', the number of rooms.<br>
For energy saving reasons, the surface of the castle must be minimum for any given 'n'.<br>
Multiple floors are possible.<br>
<br>
You must write a code to find the number of panels that will be needed for a 'n' castle.<br>
(Optimised solution is needed: there are 100 000+ tests, in a range from 0 to 10^18)
ex:<br>
n - pannels:<br>
0 - 0<br>
1 - 6<br>
2 - 11<br>
36 - 141<br>
37 - 146<br>
| algorithms | def panel_count(n, dim=3):
res = n * dim
for k in range(dim, 0, - 1):
if n:
p, d, l = 1, n, []
for r in range(dim, 0, - 1):
s = k < r or round(d * * (1 / r))
l . append(s)
d / /= s
p *= s
for r, s in zip(range(dim, 0, - 1), l):
res += k >= r and p / / s
n -= p
return res
| Castle of Cubes | 5cbcf4d4a0dcd2001e28fc79 | [
"Algorithms"
] | https://www.codewars.com/kata/5cbcf4d4a0dcd2001e28fc79 | 5 kyu |
Help prepare for the entrance exams to art school.
It is known in advance that this year, the school chose the symmetric letter βWβ as the object for the image, and the only condition for its image is only the size that is not known in advance, so as training, you need to come up with a way that accurately depicts the object.
Write a function that takes an integer and returns a list of strings with a line-by-line image of the object.
Below is an example function:
```
get_w(3) # should return:
[
'* * *',
' * * * * ',
' * * '
]
get_w(5) # should return:
[
'* * *',
' * * * * ',
' * * * * ',
' * * * * ',
' * * '
]
```
Return an empty list for `height < 2`. | reference | def get_w(h):
return [(' ' * w + '*' + ' ' * (2 * (h - w) - 3) + '*' + ' ' * (2 * w - 1) + '*' + ' ' * (2 * (h - w) - 3) + '*' + ' ' * w). replace('**', '*') for w in range(h)] if h > 1 else []
| IntroToArt | 5d7d05d070a6f60015c436d1 | [
"Arrays",
"Strings",
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/5d7d05d070a6f60015c436d1 | 6 kyu |
Time to build a crontab parser... https://en.wikipedia.org/wiki/Cron
A crontab command is made up of 5 fields in a space separated string:
```
minute: 0-59
hour: 0-23
day of month: 1-31
month: 1-12
day of week: 0-6 (0 == Sunday)
```
Each field can be a combination of the following values:
* a wildcard `*` which equates to all valid values.
* a range `1-10` which equates to all valid values between start-end inclusive.
* a step `*/2` which equates to every second value starting at 0, or 1 for day of month and month.
* a single value `2` which would be 2.
* a combination of the above separated by a `,`
Note: In the case of multiple values in a single field, the resulting values should be sorted.
Note: Steps and ranges can also be combined `1-10/2` would be every second value in the `1-10` range `1 3 5 7 9`.
For an added challenge day of week and month will both support shortened iso formats:
```
SUN MON TUE ...
JAN FEB MAR ...
```
Examples
========
`*` should output every valid value `0 1 2 3 4 5 6 ...`
`1` should output the value `1`.
`1,20,31` should output the values `1 20 31`.
`1-10` should output the values `1 2 3 4 5 6 7 8 9 10`.
`*/2` should output every second value `0 2 4 6 8 10 ...`.
`*/2` should output `1 3 5 7 9 ...` in the cases, day of month and month.
`1-10/2` should output `1 3 5 7 9`.
`*/15,3-5` should output the values `0 3 4 5 15 30 45` when applied to the minute field.
Output
======
The purpose of this kata is to take in a crontab command, and render it in a nice human readable format.
The output format should be in the format `field_name values`. The field name should be left justified and
padded to 15 characters. The values should be a space separated string of the returned values.
For example the crontab `*/15 0 1,15 * 1-5` would have the following output:
```
minute 0 15 30 45
hour 0
day of month 1 15
month 1 2 3 4 5 6 7 8 9 10 11 12
day of week 1 2 3 4 5
```
All test cases will receive a valid crontab, there is no need to handle an incorrect number of values.
Super handy resource for playing with different values to find their outputs: https://crontab.guru/ | reference | RANGES = {
'minute': (0, 59),
'hour': (0, 23),
'day of month': (1, 31),
'month': (1, 12),
'day of week': (0, 6),
}
ALIASES = {
'month': ' JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC' . split(' '),
'day of week': 'SUN MON TUE WED THU FRI SAT' . split(),
}
def get_alias(field, value):
try:
return ALIASES[field]. index(value)
except:
return int(value)
def parse(crontab):
def parse_field(field, value):
values = set()
for part in value . split(','):
part, * end = part . split('/')
step = int(end[0]) if end else 1
if part == '*':
start, stop = RANGES[field]
else:
part, * end = part . split('-')
start = get_alias(field, part)
stop = get_alias(field, end[0]) if end else start
values . update(range(start, stop + 1, step))
return ' ' . join(map(str, sorted(values)))
return '\n' . join(f' { field : < 15 }{ parse_field ( field , value )} '
for field, value in zip(RANGES, crontab . split()))
| Crontab Parser | 5d7b9ed14cd01b000e7ebb41 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d7b9ed14cd01b000e7ebb41 | 5 kyu |
Fibonacci sequence is defined as follows: `F(n+1) = F(n) + F(n-1)`, where `F(0) = 0, F(1) = 1`.
There are many generalizations, including Tribonacci numbers, Padovan numbers, Lucas numbers, etc. Many of there have their respective katas in codewars, including:
- Fibonacci: https://www.codewars.com/kata/fibonacci-number
- Tribonacci: https://www.codewars.com/kata/tribonacci-sequence
- Padovan: https://www.codewars.com/kata/padovan-numbers
- Lucas: https://www.codewars.com/kata/lucas-numbers
And some of the performance versions:
- Millionth Fibonacci kata: https://www.codewars.com/kata/the-millionth-fibonacci-kata
- Big Big Big Padovan Number: https://www.codewars.com/kata/big-big-big-padovan-number
This kata is aimed at evaluating both generalization ability and complexity of the algorithm.
# The task:
You are given two lists of integers `A` and `B` of same size, and a positive integer `n`.
- List `A` represents first values of the sequence, namely `F(0) == A(0), F(1) == A(1), ..., F(len(A)-1) = A(len(A)-1)`
- List `B` represents coefficients of recurrent equation `F(n) = B(0)*F(n-1) + B(1)*F(n-2) + ... + B(len(B)-1)*F(n-len(B))`
- `n` is the index of number in the sequence, which you need to return.
`Hint`: solution must have `O(log n)` complexity to pass the tests.
### Range of numbers:
There are `100` random tests. `2 <= len(A) == len(B) <= 5, 0 <= n <= 100000`. Initial values are in range `[-5; 5]`, and the coefficients are in range `[-2; 2]` | algorithms | import numpy as np
def generalized_fibonacchi(a, b, n):
return np . dot(np . matrix(np . vstack((np . eye(len(b) - 1, len(b), 1), b[:: - 1])). astype(int), dtype=object) * * n, a)[0, 0]
| Big Generalized Fibonacci numbers | 5d7bb3eda58b36000fcc0bbb | [
"Performance",
"Algorithms",
"Mathematics",
"Big Integers"
] | https://www.codewars.com/kata/5d7bb3eda58b36000fcc0bbb | 4 kyu |
Speedcubing is the hobby involving solving a variety of twisty puzzles, the most famous being the 3x3x3 puzzle or Rubik's Cube, as quickly as possible.
In the majority of Speedcubing competitions, a Cuber solves a scrambled cube 5 times, and their result is found by taking the average of the middle 3 solves (ie. the slowest and fastest times are disregarded, and an average is taken of the remaining times).
In some competitions, the unlikely event of a tie situation is resolved by comparing Cuber's fastest times.
Write a function ```cube_times(times)``` that, given an array of floats ```times``` returns an array / tuple with the Cuber's result (to 2 decimal places) AND their fastest solve.
For example:
```python
cube_times([9.5, 7.6, 11.4, 10.5, 8.1]) = (9.37, 7.6)
# Because (9.5 + 10.5 + 8.1) / 3 = 9.37 and 7.6 was the fastest solve.
```
```ruby
cube_times([9.5, 7.6, 11.4, 10.5, 8.1]) = [9.37, 7.6]
# Because (9.5 + 10.5 + 8.1) / 3 = 9.37 and 7.6 was the fastest solve.
```
```javascript
cubeTimes([9.5, 7.6, 11.4, 10.5, 8.1]) = [9.37, 7.6]
// Because (9.5 + 10.5 + 8.1) / 3 = 9.37 and 7.6 was the fastest solve.
```
```typescript
cubeTimes([9.5, 7.6, 11.4, 10.5, 8.1]) = [9.37, 7.6]
// Because (9.5 + 10.5 + 8.1) / 3 = 9.37 and 7.6 was the fastest solve.
```
```julia
cubetimes([9.5, 7.6, 11.4, 10.5, 8.1]) = (9.37, 7.6)
# Because (9.5 + 10.5 + 8.1) / 3 = 9.37 and 7.6 was the fastest solve.
```
Note: ```times``` will always be a valid array of 5 positive floats (representing seconds) | reference | def cube_times(times):
return (round((sum(times) - (min(times) + max(times))) / 3, 2), min(times))
| Find the Speedcuber's times! | 5d7c7697e8ad48001e642964 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d7c7697e8ad48001e642964 | 7 kyu |
I don't like writing classes like this:
```javascript
function Animal(name,species,age,health,weight,color) {
this.name = name;
this.species = species;
this.age = age;
this.health = health;
this.weight = weight;
this.color = color;
}
```
```coffeescript
Animal = (@name, @species, @age, @health, @weight, @color) ->
```
```python
class Animal:
def __init__(self, name, species, age, health, weight, color):
self.name = name
self.species = species
self.age = age
self.health = health
self.weight = weight
self.color = color
```
Give me the power to create a similar class like this:
```javascript
const Animal = makeClass("name","species","age","health","weight","color")
```
```coffeescript
Animal = makeClass "name", "species", "age", "health", "weight", "color"
```
```python
Animal = make_class("name", "species", "age", "health", "weight", "color")
``` | algorithms | def make_class(* args):
class MyClass:
def __init__(self, * vals):
self . __dict__ = {x: y for x, y in zip(args, vals)}
return MyClass
| Make Class | 5d774cfde98179002a7cb3c8 | [
"Object-oriented Programming",
"Algorithms"
] | https://www.codewars.com/kata/5d774cfde98179002a7cb3c8 | 7 kyu |
Some integral numbers are odd. All are more odd, or less odd, than others.
Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are always less odd than odd numbers, but they also can be more, or less, odd than other even numbers, by the same mechanism.
# Task
Given a _non-empty_ finite list of _unique_ integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_.
Given the constraints, there will always be exactly one such number.
# Examples
```haskell
oddest [1,2] -> 1
oddest [1,3] -> 3
oddest [1,5] -> 5
```
```javascript
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => 5
```
```python
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => 5
```
~~~if:lambdacalc
# Encodings
purity: `LetRec`
numEncoding: `NegaBinaryScott` ( custom )
`NegaBinaryScott` is just like `BinaryScott`, but the base is `-2` instead of `2`.
export constructors `nil, cons` for your `List` encoding.
~~~
# Hint
<details>
<summary>Click here.</summary>
How odd is <code>-1</code> ?
</details> | algorithms | def more_odd(a, b):
if a % 2 == b % 2:
return more_odd(a / / 2, b / / 2)
return - 1 if a % 2 else 1
def oddest(a):
return sorted(a, cmp=more_odd)[0]
| Odder than the rest - 2 | 5d72704499ee62001a7068c7 | [
"Puzzles",
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5d72704499ee62001a7068c7 | 7 kyu |
Integral numbers can be even or odd.
Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are just not odd.
# Task
Given a finite list of integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_.
If there is no single such number, no number is odder than the rest; return `Nothing`, `null` or a similar empty value.
# Examples
```haskell
oddest [1,2] -> Just 1
oddest [1,3] -> Just 3
oddest [1,5] -> Nothing
```
```javascript
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => null
```
```factor
{ 1 2 } oddest -> 1
{ 1 3 } oddest -> 3
{ 1 5 } oddest -> f
```
```julia
oddest([1, 2]) => 1
oddest([1, 3]) => 3
oddest([1, 5]) => nothing
```
```csharp
Kata.Oddest(new int[] { 1, 2 }) => 1
Kata.Oddest(new int[] { 1, 3 }) => 3
Kata.Oddest(new int[] { 1, 5 }) => null
```
```typescript
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => null
```
```dart
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => null
```
```crystal
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => nil
```
```coffeescript
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => null
```
```ruby
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => nil
```
```python
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => None
```
```lambdacalc
oddest [1,2] -> Some 1
oddest [1,3] -> Some 3
oddest [1,5] -> None
```
~~~if:lambdacalc
# Encodings
purity: `LetRec`
numEncoding: `NegaBinaryScott` ( custom )
Export constructors `nil, cons` for your `List` encoding, and deconstructor `option` for your `Option` encoding ( see `Initial Code` for signatures ).
`NegaBinaryScott` is just like `BinaryScott`, but the base is `-2` instead of `2`. So in `01$` the `0` means `0 * (-2)^0 = 0 * 1` and the `1` means `1 * (-2)^1 = 1 * -2`, for a total of `-2`. The invariant that the MSB, if present, must be `1` is unchanged ( and, by default, enforced ). Negative number literals can be used.
~~~
# Hint
<details>
<summary>Click here.</summary>
How odd is <code>-1</code> ?
</details> | algorithms | def oddest(numbers):
most_odd = 0 # The current most odd number in the list
max_oddity = - 1 # The current greatest oddity rate, starts at -1 so that even an even number can be the unique most odd
is_unique = True # If the current most odd number is really the most, so if there is no unique oddest number, it will return None
for num in numbers: # Loop through all the numbers
oddity = 0 # The oddity rate starts at 0
print(num)
insider = num # The coefficient of the number 2, so in 2n + 1, the insider is n
while insider % 2 == 1: # While that coefficient is odd
if insider == - 1:
# Since the oddity rate of a number is NEVER greater than the absolute value of the number, this garantees that the current number is the most odd one
oddity = 1 + max([abs(n) for n in numbers])
break
else:
oddity += 1 # Add the oddity rate of the total number
# So if in 2n + 1, n is odd, represent it as 2(2m + 1) + 1, and set the value to m
insider = (insider - 1) / 2
if oddity > max_oddity: # If the current number's oddity rate is greater than the current max oddity,
is_unique = True # Set it to unique
max_oddity = oddity # Set the max oddity to the current oddity
most_odd = num # Set the most odd number to the current number
elif oddity == max_oddity: # Otherwise, if it's the same rate
is_unique = False # It's not unique
if is_unique and max_oddity >= 0: # If the current most odd number is REALLY the most odd number and the list isn't empty
return most_odd # Return it
return None # Otherwise, return None
| Odder than the rest | 5d6ee508aa004c0019723c1c | [
"Puzzles",
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5d6ee508aa004c0019723c1c | 6 kyu |
A **Seven Segment Display** is an electronic display device, used to display decimal or hexadecimal numerals. It involves seven led segments that are lit in specific combinations to represent a specific numeral. An example of each combination is shown below:

For this Kata, you must accept an integer in the range `0 - 999999` and print it as a string (in decimal format), with each digit being represented as its own seven segment display (6x seven segment displays in total). Each of the individual led segments per display should be represented by three hashes `###`. Vertical bars `|` (ASCII 124) represent the edges of each display, with a single whitespace on either side between the edge and the area of the led segments. An example of the expected output is shown below:
```
segment_display(123456) =
| | ### | ### | | ### | ### |
| # | # | # | # # | # | # |
| # | # | # | # # | # | # |
| # | # | # | # # | # | # |
| | ### | ### | ### | ### | ### |
| # | # | # | # | # | # # |
| # | # | # | # | # | # # |
| # | # | # | # | # | # # |
| | ### | ### | | ### | ### |
```
For clarity, the entire set of required combinations is provided below:
```
| ### | | ### | ### | | ### | ### | ### | ### | ### |
| # # | # | # | # | # # | # | # | # | # # | # # |
| # # | # | # | # | # # | # | # | # | # # | # # |
| # # | # | # | # | # # | # | # | # | # # | # # |
| | | ### | ### | ### | ### | ### | | ### | ### |
| # # | # | # | # | # | # | # # | # | # # | # |
| # # | # | # | # | # | # | # # | # | # # | # |
| # # | # | # | # | # | # | # # | # | # # | # |
| ### | | ### | ### | | ### | ### | | ### | ### |
```
If the number is smaller than 6 digits, the result should be justified to the right, with the unused segments being blank (as they are not turned on). Refer to the sample test for an example.
**Note:** There should not be any trailing whitespace for any line.
Please rate and enjoy! | reference | BASE = [r . split('|') for r in '''\
### | | ### | ### | | ### | ### | ### | ### | ### |
# # | # | # | # | # # | # | # | # | # # | # # |
# # | # | # | # | # # | # | # | # | # # | # # |
# # | # | # | # | # # | # | # | # | # # | # # |
| | ### | ### | ### | ### | ### | | ### | ### |
# # | # | # | # | # | # | # # | # | # # | # |
# # | # | # | # | # | # | # # | # | # # | # |
# # | # | # | # | # | # | # # | # | # # | # |
### | | ### | ### | | ### | ### | | ### | ### | ''' . split('\n')]
def segment_display(n):
digs = [int(d, 16) for d in f' { n : A > 6 } ']
return '\n' . join(f'| { "|" . join ( BASE [ x ][ d ] for d in digs ) } |'
for x in range(len(BASE)))
| Seven Segment Display | 5d7091aa7bf8d0001200c133 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5d7091aa7bf8d0001200c133 | 6 kyu |
~~~if-not:ruby,python
Return `1` when *any* odd bit of `x` equals 1; `0` otherwise.
~~~
~~~if:ruby,python
Return `true` when *any* odd bit of `x` equals 1; `false` otherwise.
~~~
Assume that:
* `x` is an unsigned, 32-bit integer;
* the bits are zero-indexed (the least significant bit is position 0)
## Examples
```
2 --> 1 (true) because at least one odd bit is 1 (2 = 0b10)
5 --> 0 (false) because none of the odd bits are 1 (5 = 0b101)
170 --> 1 (true) because all of the odd bits are 1 (170 = 0b10101010)
``` | reference | def any_odd(n):
return 1 if '1' in bin(n)[2:][- 2:: - 2] else 0
| Is There an Odd Bit? | 5d6f49d85e45290016bf4718 | [
"Bits",
"Fundamentals"
] | https://www.codewars.com/kata/5d6f49d85e45290016bf4718 | 7 kyu |
John wants to give a total bonus of `$851` to his three employees taking *fairly as possible* into account their number of days of absence during the period under consideration.
Employee A was absent `18` days, B `15` days, and C `12` days.
**The more absences, the lower the bonus** ...
How much should each employee receive?
John thinks A should receive `$230`, B `$276`, C `$345` since `230 * 18 = 276 * 15 = 345 * 12` and `230 + 276 + 345 = 851`.
#### Task:
Given an array `arr` (numbers of days of absence for each employee) and a number `s` (total bonus) the function `bonus(arr, s)` will follow John's way and return an array of the *fair* bonuses of all employees in the same order as their numbers of days of absences.
`s` and all elements of `arr` are positive integers.
#### Examples:
```
bonus([18, 15, 12], 851) -> [230, 276, 345]
bonus([30, 27, 8, 14, 7], 34067) -> [2772, 3080, 10395, 5940, 11880]
```
#### Notes
- See Example Test Cases for more examples.
- Please ask before translating.
- In some tests the number of elements of `arr` can be big.
| reference | def bonus(arr, s):
# ΠΠΠ―Π’Π¬, Π½ΠΈΡ
ΡΡ Π½Π΅ Π½Π°ΠΏΠΈΡΠ°Π½ΠΎ ΠΊΠ°ΠΊ ΠΏΠΎΠ»ΡΡΠΈΡΡ ΡΡΠΎΡ ΡΠ±Π°Π½ΡΠΉ Π±ΠΎΠ½ΡΡ!!!!!!
# Π― Π±Π»ΡΡΡ Π½Π° ΡΠ°ΠΉΡ ΠΏΠΎ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΠΈΡΠΎΠ²Π°Π½ΠΈΡ Π·Π°ΡΡΠ» ΠΈΠ»ΠΈ Π½Π° ΡΠ°ΠΉΡ ΡΠΊΡΡΡΠ°ΡΠ΅Π½ΠΎΡΠΎΠ² ΠΠΠ₯Π£Π?!?!?!?!
print("ΠΠΈΡ
ΡΡ Π½Π΅ ΠΏΠΎΠ½ΡΠ», Π½ΠΎ ΠΎΡΠ΅Π½Ρ ΠΈΠ½ΡΠ΅ΡΠ΅ΡΠ½ΠΎ!!!!")
s = s / (sum(1 / n for n in arr))
return [round(s / n) for n in arr]
| Bonuses | 5d68d05e7a60ba002b0053f6 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d68d05e7a60ba002b0053f6 | 6 kyu |
It's your best friend's birthday! You already bought a box for the present. Now you want to pack the present in the box. You want to decorate the box with a ribbon and a bow.
But how much cm of ribbon do you need?
Write the method ```wrap``` that calculates that!
A box has a ```height```, a ```width``` and a ```length``` (in cm). The ribbon is crossed on the side with the largest area. Opposite this side (also the side with the largest area) the loop is bound, calculate with ```20``` cm more tape.
```java
wrap(17,32,11) => 162
wrap(13,13,13) => 124
wrap(1,3,1) => 32
```
```go
wrap(17,32,11) => 162
wrap(13,13,13) => 124
wrap(1,3,1) => 32
```
```python
wrap(17,32,11) => 162
wrap(13,13,13) => 124
wrap(1,3,1) => 32
```
```factor
17 32 11 wrap -> 162
13 13 13 wrap -> 124
1 3 1 wrap -> 32
```
```c
wrap(17, 32, 11) => 162
wrap(13, 13, 13) => 124
wrap( 1, 3, 1) => 32
```
```javascript
wrap(17,32,11) => 162
wrap(13,13,13) => 124
wrap(1,3,1) => 32
```
Notes: </br>
```height```, ```width``` and ```length``` will always be ```>0``` </br>
The ribbon and the bow on the present looks like this:
<img src="https://i.imgur.com/30HbqCZ.png"/> | reference | def wrap(height, width, length):
a, b, c = sorted([height, width, length])
return 4 * a + 2 * c + 2 * b + 20
| Happy Birthday | 5d65fbdfb96e1800282b5ee0 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d65fbdfb96e1800282b5ee0 | 7 kyu |
Given an array `A` and an integer `x`, map each element in the array to `F(A[i],x)` then return the xor sum of the resulting array.
where F(n,x) is defined as follows:
F(n, x) = <sup>x</sup>C<sub>x</sub> **+** <sup>x+1</sup>C<sub>x</sub> **+** <sup>x+2</sup>C<sub>x</sub> **+** ... **+** <sup>n</sup>C<sub>x</sub>
and <sup>n</sup>C<sub>x</sub> represents [Combination](https://en.m.wikipedia.org/wiki/Combination) in mathematics
### Example
```python
a = [7, 4, 11, 6, 5]
x = 3
# after mapping, `a` becomes [F(7,3), F(4,3), F(11,3), F(6,3), F(5,3)]
return F(7,3) ^ F(4,3) ^ F(11,3) ^ F(6,3) ^ F(5,3)
#=> 384
```
##### e.g
F(7, 3) = <sup>3</sup>C<sub>3</sub> + <sup>4</sup>C<sub>3</sub> + <sup>5</sup>C<sub>3</sub> + <sup>6</sup>C<sub>3</sub> + <sup>7</sup>C<sub>3</sub>
<br>
## Constraints
**1 <= x <= 10**
**x <= A[i] <= 10<sup>4</sup>**
**5 <= |A| <= 10<sup>3</sup>**
| algorithms | from functools import reduce
from gmpy2 import comb
from operator import xor
def transform(a, x):
return reduce(xor, (comb(n + 1, x + 1) for n in a))
| Combinations xor sum | 5bb9053a528b29a970000113 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5bb9053a528b29a970000113 | 6 kyu |
In this kata, you are given a list containing the times that employees have clocked in and clocked out of work.
Your job is to convert that list into a list of the hours that employee has worked for each sublist
e.g.:
clock = [ ["2:00pm", "8:00pm"], ["8:00am", "4:30pm"] ] == [6.0, 8.5]
Convert the time into a floating point number where:
```15 min == .25```
```30 min == .5```
```45 min == .75```
```60 min == 1.```
Also, you MUST round each number to the nearest .25. At this worksite, you pay by intervals of 15 minutes.
So if someone worked 9.21 hours exactly, round it to 9.25.
If the start time and the end time are exactly the same, that person would have worked 0.0 hours
Sometimes an employee will start work in the afternoon and clock out in the am. Your code will need to be able to handle this. | reference | def get_hours(shifts):
return [clockToDelta(s) for s in shifts]
def clockToDelta(shift):
start, end = map(convert, shift)
return round(4 * (end - start)) / 4 % 24
def convert(clock):
h, m = map(int, clock[: - 2]. split(':'))
return h % 12 + 12 * (clock[- 2] == 'p') + m / 60
| On the clock | 5d629a6c65c7010022e3b226 | [
"Date Time",
"Fundamentals"
] | https://www.codewars.com/kata/5d629a6c65c7010022e3b226 | 6 kyu |
Given a 2D ( nested ) list ( array, vector, .. ) of size `m * n`, your task is to find the sum of the minimum values in each row.
For Example:
```text
[ [ 1, 2, 3, 4, 5 ] # minimum value of row is 1
, [ 5, 6, 7, 8, 9 ] # minimum value of row is 5
, [ 20, 21, 34, 56, 100 ] # minimum value of row is 20
]
```
So the function should return `26` because the sum of the minimums is `1 + 5 + 20 = 26`.
Note: You will always be given a non-empty list containing positive values.
ENJOY CODING :) | reference | def sum_of_minimums(numbers):
return sum(map(min, numbers))
| Sum of Minimums! | 5d5ee4c35162d9001af7d699 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5d5ee4c35162d9001af7d699 | 7 kyu |
## Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they play simple word games for fun. This is one of those days!
## Today's Game
Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word (made up of four unique letters) that is identical to the prior word except for only one letter. They just keep on going until their memories fail out.
## Their Words
Alice and Bob have memories of the same size, each able to recall `10` to `2000` different four-letter words. Memory words and initial game word are randomly taken from the same list of `4000` (unique, four-letter, lowercased) words, any of which may appear in both memories.
The expression to "think up" a new word means that for their turn, the player must submit as their response word the first valid, unused word that appears in their memory (by lowest array index), as their memories are ordered from the most "memorable" words to the least.
## The Rules
* a valid response word must contain four _unique_ letters
* `1` letter is replaced while the other `3` stay in position
* it must be the lowest indexed valid word in that memory
* this word cannot have already been used during the game
* the final player to provide a valid word will win the game
* if `1st` player fails `1st` turn, `2nd` can win with one word
* when _both_ players fail the initial word, there is no winner
## Your Task
To determine the winner!
## Some Examples
`alice = plat,rend,bear,soar,mare,pare,flap,neat,clan,pore`
`bob = boar,clap,farm,lend,near,peat,pure,more,plan,soap`
1) In the case of `word = "send"` and `first = 0`:
* Alice responds to `send` with `rend`
* Bob responds to `rend` with `lend`
* Alice has no valid response to `lend`
* Bob wins the game.
2) In the case of `word = "flip"` and `first = 1`:
* Bob has no valid response to `flip`
* Alice responds to `flip` with `flap`
* Alice wins the game.
3) In the case of `word = "calm"` and `first = 1`:
* Bob has no valid response to `calm`
* Alice has no valid response to `calm`
* Neither wins the game.
4) In the case of `word = "more"` and `first = 1`:
* Bob has no valid response to `more` **
* Alice responds to `more` with `mare`
* Alice wins the game.
5) In the case of `word = "maze"` and `first = 0`:
* Alice responds to `maze` with `mare`
* Bob responds to `mare` with `more` **
* Alice responds to `more` with `pore`
* Bob responds to `pore` with `pure`
* Alice responds to `pure` with `pare`
* Bob has no valid response to `pare`
* Alice wins the game.
\** Note that in these last two cases, Bob cannot use `mere` because it has two `e`'s.
## Input
```c
size_t n; // number of words (10 <= n <= 2000)
const char *const alice[n]; // Alice's memory of four-letter words
const char *const bob[n]; // Bob's memory of four-letter words
const char* word; // initial challenge word of the game
int first; // whom begins: 0 for Alice, 1 for Bob
```
```cpp
const std::vector<std::string> &alice // Alice's memory of four-letter words
const std::vector<std::string> &bob // Bob's memory of four-letter words
std::string word // initial challenge word of the game
int first // whom begins: 0 for Alice, 1 for Bob
```
```csharp
string[] alice // Alice's memory (10 <= n <= 2000)
string[] bob // Bob's memory (same size as alice)
string word // initial challenge word of the game
int first // whom begins: 0 for Alice, 1 for Bob
```
```python
alice # list of words in Alice's memory (10 <= n <= 2000)
bob # list of words in Bob's memory (same size as alice)
word # string of the initial challenge word of the game
first # integer of whom begins: 0 for Alice, 1 for Bob
```
```javascript
let alice; // array of words in Alice's memory (10 <= n <= 2000)
let bob; // array of words in Bob's memory (same size as alice)
let word; // string of the initial challenge word
let first; // integer of whom begins: 0 for Alice, 1 for Bob
```
```java
String[] alice; // array of words in Alice's memory (10 <= n <= 2000)
String[] bob; // array of words in Bob's memory (same size as alice)
String word; // string of the initial challenge word
int first; // integer of whom begins: 0 for Alice, 1 for Bob
```
## Output
```c
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
```cpp
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
```csharp
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
```python
return 0 # if Alice wins
return 1 # if Bob wins
return -1 # if both fail
```
```javascript
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
```java
return 0 // if Alice wins
return 1 // if Bob wins
return -1 // if both fail
```
## Enjoy!
You may consider one of the following kata to solve next:
* [Playing With Toy Blocks ~ Can you build a 4x4 square?](https://www.codewars.com/kata/5cab471da732b30018968071)
* [Crossword Puzzle! (2x2)](https://www.codewars.com/kata/5c658c2dd1574532507da30b)
* [Interlocking Binary Pairs](https://www.codewars.com/kata/628e3ee2e1daf90030239e8a)
* [Is Sator Square?](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) | algorithms | def mutations(alice, bob, word, first):
seen = {word}
mapping = {0: alice, 1: bob}
prev_state, state = - 1, - 1
def foo(word, first):
nonlocal state, prev_state
foo . counter += 1
if foo . counter > 2 and state < 0 or foo . counter > 2 and prev_state < 0:
return
for a_word in mapping[first]:
counter = 0
for i, x in enumerate(a_word):
if a_word[i] == word[i]:
counter += 1
if counter == 3 and len(set(a_word)) == 4 and a_word not in seen:
seen . add(a_word)
prev_state = state
state = first
word = a_word
break
if counter == 3 or state < 0:
return foo(word, first ^ 1)
foo . counter = 0
foo(word, first)
return state
| Four Letter Words ~ Mutations | 5cb5eb1f03c3ff4778402099 | [
"Strings",
"Arrays",
"Games",
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/5cb5eb1f03c3ff4778402099 | 5 kyu |
Given a triangle of consecutive odd numbers:
```
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
```
find the triangle's row knowing its index (the rows are 1-indexed), e.g.:
```
odd_row(1) == [1]
odd_row(2) == [3, 5]
odd_row(3) == [7, 9, 11]
```
**Note**: your code should be optimized to handle big inputs.
___
The idea for this kata was taken from this kata: [Sum of odd numbers](https://www.codewars.com/kata/sum-of-odd-numbers) | algorithms | def odd_row(n): return list(range(n * (n - 1) + 1, n * (n + 1), 2))
| Row of the odd triangle | 5d5a7525207a674b71aa25b5 | [
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/5d5a7525207a674b71aa25b5 | 6 kyu |
In this Kata you are expected to find the coefficients of quadratic equation of the given two roots (`x1` and `x2`).
Equation will be the form of ```ax^2 + bx + c = 0```
<b>Return type</b> is a Vector (tuple in Rust, Array in Ruby) containing coefficients of the equations in the order `(a, b, c)`.
Since there are infinitely many solutions to this problem, we fix `a = 1`.
Remember, the roots can be written like `(x-x1) * (x-x2) = 0`
### Example
quadratic(1,2) = (1, -3, 2)
This means `(x-1) * (x-2) = 0`; when we do the multiplication this becomes `x^2 - 3x + 2 = 0`
### Example 2
quadratic(0,1) = (1, -1, 0)
This means `(x-0) * (x-1) = 0`; when we do the multiplication this becomes `x^2 - x + 0 = 0`
### Notes
* Inputs will be integers.
* When `x1 == x2`, this means the root has the multiplicity of two
| reference | def quadratic(x1, x2):
return (1, - x1 - x2, x1 * x2)
| Quadratic Coefficients Solver | 5d59576768ba810001f1f8d6 | [
"Fundamentals",
"Mathematics",
"Algebra"
] | https://www.codewars.com/kata/5d59576768ba810001f1f8d6 | 8 kyu |
You are an aerial firefighter (someone who drops water on fires from above in order to extinguish them) and your goal is to work out the minimum amount of bombs you need to drop in order to fully extinguish the fire (the fire department has budgeting concerns and you can't just be dropping tons of bombs, they need that money for the annual christmas party).
The given string is a 2D plane of random length consisting of two characters:
* `x` representing fire
* `Y` representing buildings.
Water that you drop cannot go through buildings and therefore individual sections of fire must be addressed separately.
Your water bombs can only extinguish contiguous sections of fire up to a width (parameter `w`).
You must return the minimum number of waterbombs it would take to extinguish the fire in the string.
**Note:** all inputs will be valid.
## Examples
```
"xxYxx" and w = 3 --> 2 waterbombs needed
"xxYxx" and w = 1 --> 4
"xxxxYxYx" and w = 5 --> 3
"xxxxxYxYx" and w = 2 --> 5
```
<!--
## Inputs and Output
Inputs:
'fire' = the string.
W = an integer representing the width of exinguishable contiguous section per waterbomb.
Outputs:
An integer representing the number of waterbombs it would take to extinguish all the fires in the given string.
Assume all strings can be extinguished. Assume all inputs are valid and that the strings will only contain the symbols `x` or `Y`.
--> | algorithms | from math import ceil
def waterbombs(fire, w):
return sum(ceil(len(l) / w) for l in fire . split('Y'))
| Aerial Firefighting | 5d10d53a4b67bb00211ca8af | [
"Strings",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5d10d53a4b67bb00211ca8af | 7 kyu |
## Intro:
Imagine that you are given a task to hang a curtain of known length `(length)` on a window using curtain hooks. _**It is required**_ of you that the spacing (distance) between each hook is _**uniform**_ throughout the whole curtain and is lower than or equal to provided distance `(max_hook_dist)`. _**However you are NOT allowed to use any measuring device or method**_. How should you do it? How many curtain hooks would you need?
## Shorthand:
Given the length of the curtain `length` and a maximum uniform distance between curtain hooks `max_hook_dist` write a function that returns the number of curtain hooks required in order to hang a curtain in a described way.
## Definitions:
`length` - The length of the curtain. Always positive.
`max_hook_dist` - Maximum uniform distance between curtain hooks `[1,100]` (assume that curtain hooks have no thickness and can be fixed anywhere throughout the curtain). Can be higher than the length of the curtain.
`Measuring device/method` - Any measuring method or type of a meter (ruler, fingers, etc.) which could be used to measure the distance between the hooks is not allowed. Use maths instead.
#### P.S. I hope this kata will change the number of curtain hooks you use when hanging your own curtains :) | games | from math import *
def number_of_hooks(length, maxHook):
return length and 2 * * ceil(max(0, log2(length / maxHook))) + 1
| Hanging the curtains | 5d532b1893309000125cc43d | [
"Puzzles",
"Mathematics",
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/5d532b1893309000125cc43d | 7 kyu |
Your task is to add up letters to one letter.
```if-not:haskell,crystal,cpp,dart,elixir,reason,c,r,factor,java,swift,racket,bf,go,clojure,csharp,elm,lua,nim,kotlin,groovy,scala,sql,fortran,rust,fsharp,objc,powershell,vb,erlang,cfml,prolog,shell,haxe
The function will be given a variable amount of arguments, each one being a letter to add.
```
```if:crystal,reason,factor,lua,cfml,haxe
The function will be given an array of letters, each one being a letter to add.
```
```if:sql
In SQL, you will be given a table `letters`, with a string column `letter`. Return the sum of the letters in a column `letter`.
```
```if:csharp
The function will be given an array of letters (`char`s), each one being a letter to add. Return a `char`.
```
```if:shell
The script will be given a string of letters, each character being a letter to add.
```
```if:vb
The function will be given a `Char()`, each one being a letter to add. Return a `Char`.
```
```if:purescript
The function will be given an `Array Char` each one being a letter to add. Return a `Char`.
```
```if:fsharp
The function will be given a `List<char>` of letters, each one being a letter to add. Return a `char`.
```
```if:racket,elm
The function will be given a list of letters (chars), each one being a letter to add. Return a char.
```
```if:groovy
The function will be given a list of letters (strings), each one being a letter to add.
```
```if:nim
The function will be given a sequence of letters (chars), each one being a letter to add. Return a char.
```
```if:go
The function will be given a slice of letters (runes), each one being a letter to add. Return a rune.
```
```if:haskell,dart,elixir,prolog
The function will be given a list of letters, each one being a letter to add.
```
```if:erlang
The function will be given a character list (that's actually a string in Erlang, technically :D) of letters, each one being a letter to add.
```
```if:clojure,cpp
The function will be given a vector of letters, each one being a letter (chars) to add. Return a char.
```
```if:r
The function will be given a vector of letters, each one being a letter to add.
```
```if:c,objc
The function will be given the array size, and an array of characters, each one being a letter to add.
```
```if:java
The function will be given an array of single character Strings, each one being a letter to add.
```
```if:swift
The function will be given an `Array<Character>`, each one being a letter to add, and the function will return a Character.
```
```if:kotlin
The function will be given a `List<Char>`, each one being a letter to add, and the function will return a Char.
```
```if:powershell
The function will be given a `char[]`, each one being a letter to add, and the function will return a `char`.
```
```if:rust
The function will be given a `Vec<char>`, each one being a letter to add, and the function will return a char.
```
```if:scala
The function will be given a `List[Char]`, each one being a letter to add, and the function will return a Char.
```
```if:bf
The input will be a zero-terminated string containing letters.
```
```if:fortran
The function will be given fortran character array variable (`CHARACTER(len=1), DIMENSION(:)`) composed of lowercase letters to add together. Return a `CHARACTER(len=1)`.
```
## Notes:
* Letters will always be lowercase.
* Letters can overflow (see second to last example of the description)
* If no letters are given, the function should return `'z'`
```if:fortran
"No Letters" in Fortran is represented as a blank space, such as `[' ']` or `CHARACTER,DIMENSION(1):: X = ' '`.
```
## Examples:
```javascript
addLetters('a', 'b', 'c') = 'f'
addLetters('a', 'b') = 'c'
addLetters('z') = 'z'
addLetters('z', 'a') = 'a'
addLetters('y', 'c', 'b') = 'd' // notice the letters overflowing
addLetters() = 'z'
```
```php
addLetters('a', 'b', 'c') = 'f'
addLetters('a', 'b') = 'c'
addLetters('z') = 'z'
addLetters('z', 'a') = 'a'
addLetters('y', 'c', 'b') = 'd' // notice the letters overflowing
addLetters() = 'z'
```
```typescript
addLetters('a', 'b', 'c') = 'f'
addLetters('a', 'b') = 'c'
addLetters('z') = 'z'
addLetters('z', 'a') = 'a'
addLetters('y', 'c', 'b') = 'd' // notice the letters overflowing
addLetters() = 'z'
```
```coffeescript
addLetters('a', 'b', 'c') = 'f'
addLetters('a', 'b') = 'c'
addLetters('z') = 'z'
addLetters('z', 'a') = 'a'
addLetters('y', 'c', 'b') = 'd' # notice the letters overflowing
addLetters() = 'z'
```
```ruby
add_letters('a', 'b', 'c') = 'f'
add_letters('a', 'b') = 'c'
add_letters('z') = 'z'
add_letters('z', 'a') = 'a'
add_letters('y', 'c', 'b') = 'd' # notice the letters overflowing
add_letters() = 'z'
```
```r
add_letters(c('a', 'b', 'c')) = 'f'
add_letters(c('a', 'b')) = 'c'
add_letters(c('z')) = 'z'
add_letters(c('z', 'a')) = 'a'
add_letters(c('y', 'c', 'b')) = 'd' # notice the letters overflowing
add_letters(c()) = 'z'
```
```python
add_letters('a', 'b', 'c') = 'f'
add_letters('a', 'b') = 'c'
add_letters('z') = 'z'
add_letters('z', 'a') = 'a'
add_letters('y', 'c', 'b') = 'd' # notice the letters overflowing
add_letters() = 'z'
```
```factor
{ "a" "b" "c" } add-letters ! "f"
{ "a" "b" } add-letters ! "c"
{ "z" } add-letters ! "z"
{ "z" "a" } add-letters ! "a"
{ "y" "c" "b" } add-letters ! "d" ! notice the letters overflowing
{ } add-letters ! "z"
```
```cpp
add_letters({'a', 'b', 'c'}) = 'f'
add_letters({'a', 'b'}) = 'c'
add_letters({'z'}) = 'z'
add_letters({'z', 'a'}) = 'a'
add_letters({'y', 'c', 'b'}) = 'd' // notice the letters overflowing
add_letters({}) = 'z'
```
```lua
addLetters({'a', 'b', 'c'}) = 'f'
addLetters({'a', 'b'}) = 'c'
addLetters({'z'}) = 'z'
addLetters({'z', 'a'}) = 'a'
addLetters({'y', 'c', 'b'}) = 'd' -- notice the letters overflowing
addLetters({}) = 'z'
```
```nim
addLetters(@['a', 'b', 'c']) = 'f'
addLetters(@['a', 'b']) = 'c'
addLetters(@['z']) = 'z'
addLetters(@['z', 'a']) = 'a'
addLetters(@['y', 'c', 'b']) = 'd' # notice the letters overflowing
addLetters(@[]) = 'z'
```
```powershell
AddLetters(@('a', 'b', 'c')) = 'f'
AddLetters(@('a', 'b')) = 'c'
AddLetters(@('z')) = 'z'
AddLetters(@('z', 'a')) = 'a'
AddLetters(@('y', 'c', 'b')) = 'd' # notice the letters overflowing
AddLetters(@()) = 'z'
```
```rust
add_letters(vec!['a', 'b', 'c']) = 'f'
add_letters(vec!['a', 'b']) = 'c'
add_letters(vec!['z']) = 'z'
add_letters(vec!['z', 'a']) = 'a'
add_letters(vec!['y', 'c', 'b']) = 'd' // notice the letters overflowing
add_letters(vec![]) = 'z'
```
```csharp
AddLetters(new char[] {'a', 'b', 'c'}) = 'f'
AddLetters(new char[] {'a', 'b'}) = 'c'
AddLetters(new char[] {'z'}) = 'z'
AddLetters(new char[] {'z', 'a'}) = 'a'
AddLetters(new char[] {'y', 'c', 'b'}) = 'd' // notice the letters overflowing
AddLetters(new char[] {}) = 'z'
```
```vb
AddLetters(New Char() {"a"C, "b"C, "c"C}) = "f"C
AddLetters(New Char() {"a"C, "b"C}) = "c"C
AddLetters(New Char() {"z"C}) = "z"C
AddLetters(New Char() {"z"C, "a"C}) = "a"C
AddLetters(New Char() {"y"C, "c"C, "b"C}) = "d"C ' notice the letters overflowing
AddLetters(New Char() {}) = "z"C
```
```go
AddLetters([]rune{'a', 'b', 'c'}) = 'f'
AddLetters([]rune{'a', 'b'}) = 'c'
AddLetters([]rune{'z'}) = 'z'
AddLetters([]rune{'z', 'a'}) = 'a'
AddLetters([]rune{'y', 'c', 'b'}) = 'd' // notice the letters overflowing
AddLetters([]rune{}) = 'z'
```
```crystal
add_letters(['a', 'b', 'c']) = 'f'
add_letters(['a', 'b']) = 'c'
add_letters(['z']) = 'z'
add_letters(['z', 'a']) = 'a' # note single quotes, we work with Chars
add_letters(['y', 'c', 'b']) = 'd' # notice the letters overflowing
add_letters([] of Char) = 'z'
```
```elixir
add_letters(["a", "b", "c"]) = "f"
add_letters(["a", "b"]) = "c"
add_letters(["z"]) = "z"
add_letters(["z", "a"]) = "a"
add_letters(["y", "c", "b"]) = "d" # notice the letters overflowing
add_letters([]) = "z"
```
```cfml
addLetters(["a", "b", "c"]) = "f"
addLetters(["a", "b"]) = "c"
addLetters(["z"]) = "z"
addLetters(["z", "a"]) = "a"
addLetters(["y", "c", "b"]) = "d" // notice the letters overflowing
addLetters([]) = "z"
```
```prolog
add_letters([a, b, c]) = f
add_letters([a, b]) = c
add_letters([z]) = z
add_letters([z, a]) = a
add_letters([y, c, b]) = d % notice the letters overflowing
add_letters([]) = z
```
```dart
addLetters(['a', 'b', 'c']) = 'f'
addLetters(['a', 'b']) = 'c'
addLetters(['z']) = 'z'
addLetters(['z', 'a']) = 'a'
addLetters(['y', 'c', 'b']) = 'd' // notice the letters overflowing
addLetters(<String>[]) = 'z'
```
```reason
addLetters([|"a", "b", "c"|]) = "f"
addLetters([|"a", "b"|]) = "c"
addLetters([|"z"|]) = "z"
addLetters([|"z", "a"|]) = "a"
addLetters([|"y", "c", "b"|]) = "d" /* notice the letters overflowing */
addLetters([||]) = "z"
```
```julia
addletters('a', 'b', 'c') = 'f'
addletters('a', 'b') = 'c'
addletters('z') = 'z'
addletters('z', 'a') = 'a' # note single quotes, we work with Chars
addletters('y', 'c', 'b') = 'd' # notice the letters overflowing
addletters() = 'z'
```
```haskell
addLetters ['a', 'b', 'c'] = 'f'
addLetters ['a', 'b'] = 'c'
addLetters ['z'] = 'z'
addLetters ['z', 'a'] = 'a'
addLetters ['y', 'c', 'b'] = 'd' -- notice the letters overflowing
addLetters [] = 'z'
```
```purescript
addLetters ['a', 'b', 'c'] = 'f'
addLetters ['a', 'b'] = 'c'
addLetters ['z'] = 'z'
addLetters ['z', 'a'] = 'a'
addLetters ['y', 'c', 'b'] = 'd' -- notice the letters overflowing
addLetters [] = 'z'
```
```elm
addLetters ['a', 'b', 'c'] = 'f'
addLetters ['a', 'b'] = 'c'
addLetters ['z'] = 'z'
addLetters ['z', 'a'] = 'a'
addLetters ['y', 'c', 'b'] = 'd' -- notice the letters overflowing
addLetters [] = 'z'
```
```c
add_letters(3, {'a', 'b', 'c'}) == 'f'
add_letters(2, {'a', 'b'}) == 'c'
add_letters(1, {'z'}) == 'z'
add_letters(2, {'z', 'a'}) == 'a'
add_letters(3, {'y', 'c', 'b'}) == 'd' // notice letters overflowing
add_letters(0, {}) == 'z'
```
```java
addLetters("a", "b", "c") = "f"
addLetters("a", "b") = "c"
addLetters("z") = "z"
addLetters("z", "a") = "a"
addLetters("y", "c", "b") = "d" // notice the letters overflowing
addLetters() = "z"
```
```kotlin
addLetters(listOf("a", "b", "c")) = "f"
addLetters(listOf("a", "b")) = "c"
addLetters(listOf("z")) = "z"
addLetters(listOf("z", "a")) = "a"
addLetters(listOf("y", "c", "b")) = "d" // notice the letters overflowing
addLetters(listOf()) = "z"
```
```scala
addLetters(List('a', 'b', 'c')) = 'f'
addLetters(List('a', 'b')) = 'c'
addLetters(List('z')) = 'z'
addLetters(List('z', 'a')) = 'a'
addLetters(List('y', 'c', 'b')) = 'd' // notice the letters overflowing
addLetters(List()) = 'z'
```
```swift
addLetters(["a", "b", "c"]) = "f"
addLetters(["a", "b"]) = "c"
addLetters(["z"]) = "z"
addLetters(["z", "a"]) = "a"
addLetters(["y", "c", "b"]) = "d" // notice the letters overflowing
addLetters([]) = "z"
```
```fsharp
addLetters(['a', 'b', 'c']) = 'f'
addLetters(['a', 'b']) = 'c'
addLetters(['z']) = 'z'
addLetters(['z', 'a']) = 'a'
addLetters(['y', 'c', 'b']) = 'd' // notice the letters overflowing
addLetters([]) = 'z'
```
```objc
addLetters({'a', 'b', 'c'}, 3) = 'f'
addLetters({'a', 'b'}, 2) = 'c'
addLetters({'z'}, 1) = 'z'
addLetters({'z', 'a'}, 2) = 'a'
addLetters({'y', 'c', 'b'}, 3) = 'd' // notice the letters overflowing
addLetters({}, 0) = 'z'
```
```sql
table(letter: ["a", "b", "c"]) = "f"
table(letter: ["a", "b"]) = "c"
table(letter: ["z"]) = "z"
table(letter: ["z", "a"]) = "a"
table(letter: ["y", "c", "b"]) = "d" -- notice the letters overflowing
table(letter: []) = "z"
```
```groovy
addLetters(["a", "b", "c"]) = "f"
addLetters(["a", "b"]) = "c"
addLetters(["z"]) = "z"
addLetters(["z", "a"]) = "a"
addLetters(["y", "c", "b"]) = "d" // notice the letters overflowing
addLetters([]) = "z"
```
```shell
run_shell(args: ['abc']) = "f"
run_shell(args: ['ab']) = "c"
run_shell(args: ['z']) = "z"
run_shell(args: ['za']) = "a"
run_shell(args: ['ycb']) = "d" # notice the letters overflowing
run_shell(args: ['']) = "z"
```
```racket
(add-letters '(#\a #\b #\c)) ; #\f
(add-letters '(#\z)) ; #\z
(add-letters '(#\a #\b)) ; #\c
(add-letters '(#\c)) ; #\c
(add-letters '(#\z #\a)) ; #\a
(add-letters '(#\y #\c #\b)) ; #\d ; notice the letters overflowing
(add-letters '()) ; #\z
```
```clojure
(add-letters [\a \b \c]) ;; \f
(add-letters [\z]) ;; \z
(add-letters [\a \b]) ;; \c
(add-letters [\c]) ;; \c
(add-letters [\z \a]) ;; \a
(add-letters [\y \c \b]) ;; \d ;; notice the letters overflowing
(add-letters []) ;; \z
```
```bf
runBF('abc\0') == 'f'
runBF('ab\0') == 'c'
runBF('z\0') == 'z'
runBF('za\0') == 'a'
runBF('ycb\0') == 'd' // notice the letters overflowing
runBF('\0') == 'z'
```
```fortran
addLetters(['a', 'b', 'c'] = 'f'
addLetters(['a', 'b']) = 'c'
addLetters(['z']) = 'z'
addLetters(['z', 'a']) = 'a'
addLetters(['y', 'c', 'b']) = 'd' // notice the letters overflowing
addLetters([' ']) = 'z'
```
```haxe
addLetters(["a", "b", "c"]) = "f"
addLetters(["a", "b"]) = "c"
addLetters(["z"]) = "z"
addLetters(["z", "a"]) = "a"
addLetters(["y", "c", "b"]) = "d" // notice the letters overflowing
addLetters([]) = "z"
```
Confused? Roll your mouse/tap over <abbr title="Start by converting the letters to numbers, a => 1, b => 2, etc. Add them up. Think about the overflow yourself. Once that's done, convert it back to a letter.">here</abbr> | algorithms | def add_letters(* letters):
return chr((sum(ord(c) - 96 for c in letters) - 1) % 26 + 97)
| Alphabetical Addition | 5d50e3914861a500121e1958 | [
"Algorithms"
] | https://www.codewars.com/kata/5d50e3914861a500121e1958 | 7 kyu |
Your task is to determine how much time will take to download all the files in your Torrent and the order of completion. All downloads are started and done in parallel like in real life. In the event of a tie you should list alphabeticaly.
### Help:
* GB: Giga Byte
* Mbps: Mega bits per second
* G = 1000 M
* Byte = 8 bits
* https://en.wikipedia.org/wiki/Byte
* https://en.wikipedia.org/wiki/Bandwidth_(computing)
### Input:
* Array of files
* File example: {"name": "alien", "size_GB": 38.0, "speed_Mbps": 38}
### Output:
* List of files in the order of completed download
* Time in seconds to download last file
### Examples:
1. Basic
```
file_1 = {"name": "alien", "size_GB": 38, "speed_Mbps": 38}
file_2 = {"name": "predator", "size_GB": 38, "speed_Mbps": 2}
file_3 = {"name": "terminator", "size_GB": 5, "speed_Mbps": 25}
torrent([file_1, file_2, file_3]) -> ["terminator", "alien", "predator"], 152000
```
2. Order by name in case of a tie.
```
file_4 = {"name": "zombieland", "size_GB": 38, "speed_Mbps": 38}
file_1 = {"name": "alien", "size_GB": 38, "speed_Mbps": 38}
torrent([file_1, file_4]) -> ["alien", "zombieland"], 8000
```
Do not expect any invalid inputs. | reference | def torrent(files):
files = sorted(files, key=lambda f: (
f['size_GB'] / f['speed_Mbps'], f['name']))
last = files[- 1]
return [f['name'] for f in files], 8000 * last['size_GB'] / last['speed_Mbps']
| Computer problem series #2: Torrent download | 5d4c6809089c6e5031f189ed | [
"Fundamentals"
] | https://www.codewars.com/kata/5d4c6809089c6e5031f189ed | 7 kyu |
Two fishing vessels are sailing the open ocean, both on a joint ops fishing mission.
On a high stakes, high reward expidition - the ships have adopted the strategy of hanging a net between the two ships.
The net is **40 miles long**. Once the straight-line distance between the ships is greater than 40 miles, the net will tear, and their valuable sea harvest will be lost! We need to know how long it will take for this to happen.
Given the bearing of each ship, find the time **in minutes** at which the straight-line distance between the two ships reaches **40 miles**. Both ships travel at **90 miles per hour**. At time 0, assume the ships have the same location.
Bearings are defined as **degrees from north, counting clockwise**.
These will be passed to your function as integers between **0 and 359** degrees.
Round your result to **2 decmal places**.
If the net never breaks, return <code>float('inf')</code>
Happy sailing! | algorithms | from math import sin, radians
def find_time_to_break(bearing_A, bearing_B):
a = radians(abs(bearing_A - bearing_B) / 2)
return 40 / (3 * sin(a)) if a else float("inf")
| Time until distance between moving ships | 5d4dd5c9af0c4c0019247110 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5d4dd5c9af0c4c0019247110 | 7 kyu |
# Task
Given the birthdates of two people, find the date when the younger one is exactly half the age of the other.
# Notes
* The dates are given in the format YYYY-MM-DD and are not sorted in any particular order
* Round **down** to the nearest day
* Return the result as a string, like the input dates | reference | from dateutil . parser import parse
def half_life(* persons):
p1, p2 = sorted(map(parse, persons))
return str(p2 + (p2 - p1))[: 10]
| Half Life | 5d472159d4f8c3001d81b1f8 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5d472159d4f8c3001d81b1f8 | 7 kyu |
Inside of the city there are many gangs, each with differing numbers of members wielding different weapons and possessing different strength levels. The gangs do not really want to fight one another, and so the "If you can't beat 'em, join 'em" rule applies. The gangs start combining with the most powerful gangs being joined by the weaker gangs until there is one gang left.
Challenge:
~~~if:python,dart,haskell
You are given a list of lists. Inside of the interior lists are numbers. Join the lists together by descending total list value ending up with one final list.
~~~
~~~if-not:python,dart,haskell
You are given an array of arrays. Inside of the interior arrays are numbers. Join the arrays together by descending total array value ending up with one final array.
~~~
Simple example:
~~~if:python,ruby,crystal
```
cant_beat_so_join([[1,2], [3,4], [5,6], [7,8], [9]]) -> [7, 8, 5, 6, 9, 3, 4, 1, 2]
```
~~~
~~~if:javascript,typescript,coffeescript,dart,php
```
cantBeatSoJoin([[1,2], [3,4], [5,6], [7,8], [9]]) -> [7, 8, 5, 6, 9, 3, 4, 1, 2]
```
~~~
~~~if:haskell
```
cantBeatSoJoin [[1,2], [3,4], [5,6], [7,8], [9]] -> [7, 8, 5, 6, 9, 3, 4, 1, 2]
```
~~~
~~~if:python,dart,haskell
- In the example above, `[7, 8]` are the first in the list because they have the highest value
~~~
~~~if-not:python,dart,haskell
- In the example above, `[7, 8]` are the first in the array because they have the highest value
~~~
- They are followed by `[5, 6]`
- That is followed by `[9]` which comes before `[3, 4]` because the list of `[9]` is greater
- It ends with `[1, 2]` which has the least amount of value
More examples:
~~~if:python,ruby,crystal
```
cant_beat_so_join([[5, 1],[9, 14],[17, 23],[4, 1],[0, 1]]) -> [17, 23, 9, 14, 5, 1, 4, 1, 0, 1]
cant_beat_so_join([[13, 37], [43, 17], [2,3], [45,64], [1,9]]) -> [45, 64, 43, 17, 13, 37, 1, 9, 2, 3]
cant_beat_so_join([[], [], [], []]) -> []
cant_beat_so_join([[], [], [0], []]) -> [0]
cant_beat_so_join([[1,0,1,0,1,0], [0,1,0,0,1,0,0,1], [0], []]) -> [1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]
```
~~~
~~~if:javascript,typescript,dart,coffeescript,php
```
cantBeatSoJoin([[5, 1],[9, 14],[17, 23],[4, 1],[0, 1]]) -> [17, 23, 9, 14, 5, 1, 4, 1, 0, 1]
cantBeatSoJoin([[13, 37], [43, 17], [2,3], [45,64], [1,9]]) -> [45, 64, 43, 17, 13, 37, 1, 9, 2, 3]
cantBeatSoJoin([[], [], [], []]) -> []
cantBeatSoJoin([[], [], [0], []]) -> [0]
cantBeatSoJoin([[1,0,1,0,1,0], [0,1,0,0,1,0,0,1], [0], []]) -> [1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]
```
~~~
~~~if:haskell
```
cantBeatSoJoin [[5, 1],[9, 14],[17, 23],[4, 1],[0, 1]] -> [17, 23, 9, 14, 5, 1, 4, 1, 0, 1]
cantBeatSoJoin [[13, 37], [43, 17], [2,3], [45,64], [1,9]] -> [45, 64, 43, 17, 13, 37, 1, 9, 2, 3]
cantBeatSoJoin [[], [], [], []] -> []
cantBeatSoJoin [[], [], [0], []] -> [0]
cantBeatSoJoin [[1,0,1,0,1,0], [0,1,0,0,1,0,0,1], [0], []] -> [1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]
```
~~~
~~~if:python,dart,haskell
In the case of more than one list sharing the same sum, place them in the same order that they were in the argument:
~~~
~~~if-not:python,dart,haskell
In the case of more than one array sharing the same sum, place them in the same order that they were in the argument:
~~~
~~~if:python,ruby,crystal
```
cant_beat_so_join([[0,1,1,1], [1,0,1,1], [1,1,0,1], [3]]) -> [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 3]
```
~~~
~~~if:javascript,typescript,coffeescript,dart,php
```
cantBeatSoJoin([[0,1,1,1], [1,0,1,1], [1,1,0,1], [3]]) -> [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 3]
```
~~~
~~~if:haskell
```
cantBeatSoJoin [[0,1,1,1], [1,0,1,1], [1,1,0,1], [3]] -> [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 3]
```
~~~ | algorithms | from itertools import chain
def cant_beat_so_join(lsts):
return list(chain . from_iterable(sorted(lsts, key=sum, reverse=True)))
| If you can't beat 'em, join 'em! | 5d37899a3b34c6002df273ee | [
"Fundamentals",
"Arrays",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5d37899a3b34c6002df273ee | 7 kyu |
Create a __moreZeros__ function which will __receive a string__ for input, and __return an array__ (or null terminated string in C) containing only the characters from that string whose __binary representation of its ASCII value__ consists of _more zeros than ones_.
You should __remove any duplicate characters__, keeping the __first occurrence__ of any such duplicates, so they are in the __same order__ in the final array as they first appeared in the input string.
Examples
```javascript
'abcde' === ["1100001", "1100010", "1100011", "1100100", "1100101"]
True True False True False
--> ['a','b','d']
'DIGEST'--> ['D','I','E','T']
```
```c
"abcde" == {0b1100001, 0b1100010, 0b1100011, 0b1100100, 0b1100101}
True True False True False
--> "abd"
"DIGEST" --> "DIET"
```
All input will be valid strings of length > 0. Leading zeros in binary should not be counted.
| reference | def more_zeros(s):
results = []
for letter in s:
dec_repr = bin(ord(letter))[2:]
if (dec_repr . count("0") > dec_repr . count("1")) and (letter not in results):
results . append(letter)
return results
| More Zeros than Ones | 5d41e16d8bad42002208fe1a | [
"Fundamentals"
] | https://www.codewars.com/kata/5d41e16d8bad42002208fe1a | 6 kyu |
The town sheriff dislikes odd numbers and wants all odd numbered families out of town! In town crowds can form and individuals are often mixed with other people and families. However you can distinguish the family they belong to by the number on the shirts they wear. As the sheriff's assistant it's your job to find all the odd numbered families and remove them from the town!
~~~if-not:cpp
Challenge: You are given a list of numbers. The numbers each repeat a certain number of times. Remove all numbers that repeat an odd number of times while keeping everything else the same.
~~~
~~~if:cpp
Challenge: You are given a vector of numbers. The numbers each repeat a certain number of times. Remove all numbers that repeat an odd number of times while keeping everything else the same.
~~~
```python
odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```julia
odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```php
odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```ruby
odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```crystal
odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```elixir
odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```javascript
oddOnesOut([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```typescript
oddOnesOut([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```dart
oddOnesOut([1, 2, 3, 1, 3, 3]) = [1, 1]
```
```reason
oddOnesOut([| 1, 2, 3, 1, 3, 3 |]) = [| 1, 1 |]
```
```haskell
oddOnesOut [1, 2, 3, 1, 3, 3] = [1, 1]
```
```r
oddOnesOut(c(1, 2, 3, 1, 3, 3)) = c(1, 1)
```
```racket
(odd-ones-out '(1 2 3 1 3 3)) ; '(1 1)
```
```factor
{ 1 2 3 1 3 3 } odd-ones-out ! { 1 1 }
```
```cpp
oddOnesOut({1, 2, 3, 1, 3, 3}) = {1, 1}
```
In the above example:
- the number 1 appears twice
- the number 2 appears once
- the number 3 appears three times
`2` and `3` both appear an odd number of times, so they are removed from the list. The final result is: `[1,1]`
Here are more examples:
```cpp
oddOnesOut({1, 1, 2, 2, 3, 3, 3}) = {1, 1, 2, 2}
oddOnesOut({26, 23, 24, 17, 23, 24, 23, 26}) = {26, 24, 24, 26}
oddOnesOut({1, 2, 3}) = {}
oddOnesOut({1}) = {}
```
```python
odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
odd_ones_out([1, 2, 3]) = []
odd_ones_out([1]) = []
```
```ruby
odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
odd_ones_out([1, 2, 3]) = []
odd_ones_out([1]) = []
```
```elixir
odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
odd_ones_out([1, 2, 3]) = []
odd_ones_out([1]) = []
```
```crystal
odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
odd_ones_out([1, 2, 3]) = []
odd_ones_out([1]) = []
```
```julia
odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
odd_ones_out([1, 2, 3]) = []
odd_ones_out([1]) = []
```
```php
odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
odd_ones_out([1, 2, 3]) = []
odd_ones_out([1]) = []
```
```javascript
oddOnesOut([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
oddOnesOut([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
oddOnesOut([1, 2, 3]) = []
oddOnesOut([1]) = []
```
```reason
oddOnesOut([| 1, 1, 2, 2, 3, 3, 3 |]) = [| 1, 1, 2, 2 |]
oddOnesOut([| 26, 23, 24, 17, 23, 24, 23, 26 |]) = [| 26, 24, 24, 26 |]
oddOnesOut([| 1, 2, 3 |]) = [| |]
oddOnesOut([| 1 |]) = [| |]
```
```typescript
oddOnesOut([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
oddOnesOut([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
oddOnesOut([1, 2, 3]) = []
oddOnesOut([1]) = []
```
```dart
oddOnesOut([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2]
oddOnesOut([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26]
oddOnesOut([1, 2, 3]) = []
oddOnesOut([1]) = []
```
```haskell
oddOnesOut [1, 1, 2, 2, 3, 3, 3] = [1, 1, 2, 2]
oddOnesOut [26, 23, 24, 17, 23, 24, 23, 26] = [26, 24, 24, 26]
oddOnesOut [1, 2, 3] = []
oddOnesOut [1] = []
```
```r
oddOnesOut(c(1, 1, 2, 2, 3, 3, 3)) = c(1, 1, 2, 2)
oddOnesOut(c(26, 23, 24, 17, 23, 24, 23, 26)) = c(26, 24, 24, 26)
oddOnesOut(c(1, 2, 3)) = c()
oddOnesOut(c(1)) = c()
```
```racket
(odd-ones-out '(1 1 2 2 3 3 3)) ; '(1 1 2 2)
(odd-ones-out '(26 23 24 17 23 24 23 26)) ; '(26 24 24 26)
(odd-ones-out '(1 2 3)) ; '()
(odd-ones-out '(1)) ; '()
```
```factor
{ 1 1 2 2 3 3 3 } odd-ones-out ! { 1 1 2 2 }
{ 26 23 24 17 23 24 23 26 } odd-ones-out ! { 26 24 24 26 }
{ 1 2 3 } odd-ones-out ! { }
{ 1 } odd-ones-out ! { }
```
Are you up to the challenge?
| reference | def odd_ones_out(numbers):
return [i for i in numbers if numbers . count(i) % 2 == 0]
| Odd Ones Out! | 5d376cdc9bcee7001fcb84c0 | [
"Fundamentals",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5d376cdc9bcee7001fcb84c0 | 7 kyu |
This kata is the part two version of the [Find X](https://www.codewars.com/kata/find-x) kata, if you haven't solved it you should try solving it, it's pretty easy.
In this version you're given the following function
```python
def find_x(n):
if n == 0: return 0
x = 0
for i in range(1, n+1):
x += find_x(i-1) + 3*i
return x
```
```go
func FindX(n int) int {
if n == 0 {
return 0
}
x := 0
for i:=1; i<=n; i++ {
x += FindX(i-1) + 3*i
}
return x
}
```
```javascript
function findX(n) {
if (n == 0) return 0;
let x = 0;
for (let i=1; i<=n; ++i)
x += findX(i-1) + 3*i;
return x;
}
```
```haskell
findX :: Int -> Int
findX 0 = 0
findX n = sum $ map ( \ i -> findX (i-1) + 3 * i ) [1..n]
```
```factor
: find-x ( n -- x ) [ 0 ] [
[1,b] [ [ 1 - find-x ] [ 3 * ] bi + ] map-sum
] if-zero ;
```
```java
public static int findX(int n) {
if (n == 0) return 0;
int x = 0;
for (int i = 1; i <= n; ++i)
x += findX(i - 1) + 3 * i;
return x;
}
```
Since this computation is exponential, it gets very slow quickly as n increases, your task is to optimize the function so it works well for large numbers.
```python
find_x(2) #=> 12
find_x(3) #=> 33
find_x(5) #=> 171
```
```go
FindX(2) //=> 12
FindX(3) //=> 33
FindX(5) //=> 171
```
```javascript
findX(2) //=> 12
findX(3) //=> 33
findX(5) //=> 171
```
```haskell
findX 2 -- -> 12
findX 3 -- -> 33
findX 5 -- -> 171
```
```factor
2 find-x ! --> 12
3 find-x ! --> 33
5 find-x ! --> 171
```
```java
findX(2) //=> 12
findX(3) //=> 33
findX(5) //=> 171
```
The result gets pretty large even for small inputs, so you should return the **result % (10<sup>9</sup>+7)**
### Input Range
**1 <= n <= 10<sup>6</sup>** | reference | M = 10 * * 9 + 7
def find_x(n):
return 3 * (pow(2, n + 1, M) - n - 2) % M
| Find X β
‘ | 5d339b01496f8d001054887f | [
"Fundamentals"
] | https://www.codewars.com/kata/5d339b01496f8d001054887f | 6 kyu |
The goal of this Kata is to write a function that will receive an array of strings as its single argument, then the strings are each processed and sorted (in desending order) based on the length of the single longest sub-string of contiguous vowels ( `aeiouAEIOU` ) that may be contained within the string. The strings may contain letters, numbers, special characters, uppercase, lowercase, whitespace, and there may be (often will be) multiple sub-strings of contiguous vowels. We are only interested in the single longest sub-string of vowels within each string, in the input array.
Example:
str1 = "what a beautiful day today"
str2 = "it's okay, but very breezy"
When the strings are sorted, `str1` will be first as its longest sub-string of contiguous vowels `"eau"` is of length `3`, while `str2` has as its longest sub-string of contiguous vowels `"ee"`, which is of length `2`.
If two or more strings in the array have maximum sub-strings of the same length, then the strings should remain in the order in which they were found in the orginal array. | reference | import re
def sort_strings_by_vowels(seq):
return sorted(seq, reverse=True, key=lambda x: max((len(i) for i in re . findall(r'[aeiouAEIOU]+', x)), default=0))
| Sort Strings by Most Contiguous Vowels | 5d2d0d34bceae80027bffddb | [
"Fundamentals",
"Strings",
"Sorting"
] | https://www.codewars.com/kata/5d2d0d34bceae80027bffddb | 6 kyu |
## An Invitation
Most of us played with toy blocks growing up. It was fun and you learned stuff. So what else can you do but rise to the challenge when a 3-year old exclaims, "Look, I made a square!", then pointing to a pile of blocks, "Can _you_ do it?"
## Our Blocks
Just to play along, of course we'll be viewing these blocks in two dimensions. Depth now being disregarded, it turns out the pile has four different sizes of block: `1x1`, `1x2`, `1x3`, and `1x4`. The smallest one represents the area of a square, the other three are rectangular, and all differ by their width. Integers matching these four widths are used to represent the blocks in the input.
## The Square
Well, the kid made a `4x4` square from this pile, so you'll have to match that. Noticing the way they fit together, you realize the structure must be built in fours rows, one row at a time, where the blocks must be placed horizontally. With the known types of block, there are five types of row you could build:
1) 1 four-unit block
2) 1 three-unit block plus 1 one-unit bock (in either order)
3) 2 two-unit blocks
4) 1 two-unit block plus 2 one-unit blocks (in any order)
5) 4 one-unit blocks
## Some Notes
* Amounts for all four block sizes will each vary from `0` to `16`.
* The total size of the pile will also vary from `0` to `16`.
* A valid square doesn't have to use all given blocks.
* The order of rows is irrelevant.
## Some Examples
Given `1, 3, 2, 2, 4, 1, 1, 3, 1, 4, 2` there are many ways you could construct a square. Here are three possibilities, as described by their four rows:
* 1 four-unit block
* 2 two-unit blocks
* 1 four-unit block
* 4 one-unit blocks
>
* 1 three-unit block plus 1 one-unit block
* 2 two-unit blocks
* 1 four-unit block
* 1 one-unit block plus 1 three-unit block
>
* 2 two-unit blocks
* 1 three-unit block plus 1 one-unit block
* 1 four-unit block
* 2 one-unit blocks plus 1 two-unit block
Given `1, 3, 2, 4, 3, 3, 2` there is no way to complete the task, as you could only build three rows of the correct length. The kid will not be impressed.
* 1 four-unit block
* 2 two-unit blocks
* 1 three-unit block plus 1 one-unit block
* (here only sadness)
## Input
```
blocks ~ array of random integers (1 <= x <= 4)
```
## Output
```
true or false ~ whether you can build a square
```
## Enjoy!
You may consider one of the following kata to solve next:
* [Four Letter Words ~ Mutations](https://www.codewars.com/kata/5cb5eb1f03c3ff4778402099)
* [Crossword Puzzle! (2x2)](https://www.codewars.com/kata/5c658c2dd1574532507da30b)
* [Interlocking Binary Pairs](https://www.codewars.com/kata/628e3ee2e1daf90030239e8a)
* [Is Sator Square?](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) | algorithms | def build_square(blocks):
for x in range(4):
if 4 in blocks:
blocks . remove(4)
elif 3 in blocks and 1 in blocks:
blocks . remove(3)
blocks . remove(1)
elif blocks . count(2) >= 2:
blocks . remove(2)
blocks . remove(2)
elif 2 in blocks and blocks . count(1) >= 2:
blocks . remove(2)
blocks . remove(1)
blocks . remove(1)
elif blocks . count(1) >= 4:
blocks . remove(1)
blocks . remove(1)
blocks . remove(1)
blocks . remove(1)
else:
return False
return True
| Playing With Toy Blocks ~ Can you build a 4x4 square? | 5cab471da732b30018968071 | [
"Logic",
"Arrays",
"Games",
"Puzzles",
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/5cab471da732b30018968071 | 6 kyu |
# Inner join
In SQL, an inner join query joins two tables by selecting records which satisfy the join predicates and combining column values of the two tables.
# Task
Write a function to mimic an SQL inner join. The function should take two 2D arrays and two index values, which specifies the column to perform the join in each array, as parameters.
For example, the following code illustrates an example to join two arrays `arrA` and `arrB` using the first column (column index = 0) of each array.
```python
arrA = [
[1, 10],
[2, 20],
[3, 30]
]
arrB = [
[1, 100],
[2, 200],
[4, 400]
]
indA = 0
indB = 0
innerJoin(arrA, arrB, indA, indB)
# [
# [1, 10, 1, 100],
# [2, 20, 2, 200]
# ]
```
```javascript
let arrA = [
[1, 10],
[2, 20],
[3, 30]
];
let arrB = [
[1, 100],
[2, 200],
[4, 400]
];
let indA = 0;
let indB = 0;
innerJoin(arrA, arrB, indA, indB);
// [
// [1, 10, 1, 100],
// [2, 20, 2, 200]
// ]
```
```haskell
arrA = [ [ Just 1, Just 10 ]
, [ Just 2, Just 20 ]
, [ Just 3, Just 30 ]
]
arrB = [ [ Just 1, Just 100 ]
, [ Just 2, Just 200 ]
, [ Just 4, Just 400 ]
]
indA = 0
indB = 0
innerJoin arrA arrB indA indB
-- [ [ Just 1, Just 10, Just 1, Just 100 ]
-- , [ Just 2, Just 20, Just 2, Just 200 ]
-- ]
```
```if:python
Assume that each 2D array contains only primitive data types (`int`, `string`, `bool`, `NoneType`), but `None` does not match to any values in the join.
```
```if:javascript
Assume that each 2D array contains only primitive data types (`number`, `string`, `boolean`, `null` and `undefined`), but `null` and `undefined` do not match to any values in the join.
```
```if:haskell
Assume that each 2D array contains only `Maybe a`s ( `forall a. (Eq a) => [[ Maybe a ]]` ), but `Nothing` does not match to any values in the join.
```
# Further explanation about inner join
For those who are not familiar with SQL, some more examples are shown below to help you understand what joins are.
Assume that we have tables `T1` and `T2 ` as shown below:
`T1`
```
| COL1 | COL2 |
| ---- | ---- |
| 1 | A |
| 2 | B |
| 3 | C |
```
`T2`
```
| COL1 | COL2 |
| ---- | ---- |
| 1 | X |
| 2 | Y |
| 4 | Z |
```
The result of an inner join using the predicate `T1.COL1 = T2.COL1` is:
```
| T1.COL1 | T1.COL2 | T2.COl1 | T2.COL2 |
| ------- | ------- | ------- | ------- |
| 1 | A | 1 | X |
| 2 | B | 2 | Y |
```
When performing a join, each row from the first table needs to be compared with each row from the second table. For example, assume that we have tables `T1` and `T2 ` as shown below:
`T1`
```
| COL1 | COL2 |
| ---- | ---- |
| 1 | A |
| 2 | B |
| 2 | C |
```
`T2`
```
| COL1 | COL2 |
| ---- | ---- |
| 1 | X |
| 1 | Y |
| 2 | Z |
```
The result of an inner join using the predicate `T1.COL1 = T2.COL1` is:
```
| T1.COL1 | T1.COL2 | T2.COl1 | T2.COL2 |
| ------- | ------- | ------- | ------- |
| 1 | A | 1 | X |
| 1 | A | 1 | Y |
| 2 | B | 2 | Z |
| 2 | C | 2 | Z |
```
For more details: https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join | reference | def inner_join(arrA, arrB, indA, indB):
return [[* x, * y]
for x in arrA if x[indA] is not None
for y in arrB if y[indB] == x[indA]]
| 2D array inner join | 56b7a75cbd06e6237000138b | [
"Fundamentals",
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/56b7a75cbd06e6237000138b | 6 kyu |
[Wikipedia](https://en.wikipedia.org/wiki/Baum%E2%80%93Sweet_sequence): The BaumβSweet sequence is an infinite automatic sequence of `0`s and `1`s defined by the rule:
b<sub>n</sub> = `1` if the binary representation of `n` contains no block of consecutive `0`s of odd length;
b<sub>n</sub> = `0` otherwise;
for `n β₯ 0`.
~~~if:javascript,php,coffeescript,typescript,
Define a generator function `baumSweet` that sequentially generates the values of this sequence.
~~~
~~~if:go,
Define a generator function `BaumSweet` that sequentially generates the values of this sequence.
~~~
~~~if:kotlin,
Define an iterator function `baumSweet` that sequentially generates the values of this sequence.
~~~
~~~if:haskell,
Define a list `baumSweet` that contains the values of this sequence.
~~~
~~~if:lambdacalc,
Define a stream `baumSweet` that contains the values of this sequence.
~~~
~~~if:fsharp,
Define a lazy sequence `baumSweet` that contains the values of this sequence.
~~~
~~~if:python,
Define a generator function `baum_sweet` that sequentially generates the values of this sequence.
~~~
~~~if:csharp,
Define an iterator `BaumSweet` that sequentially generates the values of this sequence.
~~~
~~~if:ruby,
Define a class `BaumSweet`, instantiating to an `Enumerator` that sequentially generates the values of this sequence.
~~~
~~~if:julia,
Define a function `baumsweet` that returns a `Generator` that sequentially generates the values of this sequence.
~~~
~~~if:lua,
Define an iterator `baumsweet` that sequentially generates each n and the n<sup>th</sup> value of this sequence.
~~~
~~~if-not:lambdacalc,
It will be tested for up to `1 000 000` values.
~~~
~~~if:lambdacalc,
It will be tested for up to `32k` values.
~~~
Note that the binary representation of `0` used here is not `0` but the empty string ( which does not contain any blocks of consecutive `0`s ).
~~~if:lambdacalc
---
#### Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export deconstructors `head, tail` for your `Stream` encoding ( a `Stream` is just an infinite `List`, without a `Nil` constructor )
~~~
| algorithms | from itertools import count
def baum_sweet():
yield 1
for i in count(1):
yield not any(map(lambda x: len(x) % 2, bin(i). split('1')))
| The Baum-Sweet sequence | 5d2659626c7aec0022cb8006 | [
"Algorithms"
] | https://www.codewars.com/kata/5d2659626c7aec0022cb8006 | 7 kyu |
[Wikipedia](https://en.wikipedia.org/wiki/Regular_paperfolding_sequence): The **regular paperfolding sequence**, also known as the **dragon curve sequence**, is an infinite automatic sequence of `0`s and `1`s defined as the **limit** of inserting an alternating sequence of `1`s and `0`s around and between the terms of the previous sequence:
<span style="color:red">1</span>
<span style="color:royalblue">1</span>
<span style="color:red">1</span>
<span style="color:royalblue">0</span>
1
<span style="color:royalblue">1</span>
0
<span style="color:red">1</span>
1
<span style="color:royalblue">0</span>
0
<span style="color:mediumpurple">1</span>
1
<span style="color:mediumpurple">0</span>
<span style="color:royalblue">1</span>
<span style="color:mediumpurple">1</span>
0
<span style="color:mediumpurple">0</span>
<span style="color:red">1</span>
<span style="color:mediumpurple">1</span>
1
<span style="color:mediumpurple">0</span>
<span style="color:royalblue">0</span>
<span style="color:mediumpurple">1</span>
0
<span style="color:mediumpurple">0</span>
...
Note how each intermediate sequence is a prefix of the next.
```if:javascript,coffeescript,typescript,php,
Define a generator function `paperFold` that sequentially generates the values of this sequence:
```
```if:python,
Define a generator function `paper_fold` that sequentially generates the values of this sequence:
```
```if:ruby,
Define a class `PaperFold`, instantiating an `Enumerator`, which yields the values of this sequence:
```
```if:haskell,
Define a list `paperFold` that contains the values of this sequence:
```
```if:lambdacalc,
Define a stream `paperFold` that contains the values of this sequence:
```
```if:fsharp,
Define a lazy sequence `paperFold` that contains the values of this sequence:
```
```if:clojure,
Define a sequence `paper-fold` that contains the values of this sequence:
```
```if:java,go,csharp,
Define a generator `PaperFold` that sequentially generates the values of this sequence:
```
```if:kotlin,
Define a generator `paperFold` that sequentially generates the values of this sequence:
```
<span style="color:green">1</span>
<span style="color:mediumpurple">1</span>
<span style="color:green">0</span>
1
<span style="color:green">1</span>
<span style="color:mediumpurple">0</span>
<span style="color:green">0</span>
<span style="color:royalblue">1</span>
<span style="color:green">1</span>
<span style="color:mediumpurple">1</span>
<span style="color:green">0</span>
0
<span style="color:green">1</span>
<span style="color:mediumpurple">0</span>
<span style="color:green">0</span>
<span style="color:red">1</span>
<span style="color:green">1</span>
<span style="color:mediumpurple">1</span>
<span style="color:green">0</span>
1
<span style="color:green">1</span>
<span style="color:mediumpurple">0</span>
<span style="color:green">0</span>
<span style="color:royalblue">0</span>
<span style="color:green">1</span>
<span style="color:mediumpurple">1</span>
<span style="color:green">0</span>
0
<span style="color:green">1</span>
<span style="color:mediumpurple">0</span>
<span style="color:green">0</span>
...
It will be tested for up to `1 000 000` values.
~~~if:lambdacalc
( Actually, in Lambda Calculus, it will not be tested beyond `10 000` values. )
### Encodings
Use `numEncoding Church`. Define your own `Stream` ( infinite list ); provide deconstructors
`head : Stream a -> a` and `tail : Stream a -> Stream a`.
~~~ | algorithms | def paper_fold():
gen = paper_fold()
while True:
yield 1
yield next(gen)
yield 0
yield next(gen)
| The PaperFold sequence | 5d26721d48430e0016914faa | [
"Algorithms"
] | https://www.codewars.com/kata/5d26721d48430e0016914faa | 6 kyu |
The Takeuchi function is defined as:
```python
def T(x,y,z):
if x β€ y:
return y
else:
return T(T(x-1,y,z),T(y-1,z,x),T(z-1,x,y))
```
```javascript
function T(x,y,z){
if (x β€ y)
return y;
else
return T(T(x-1,y,z),T(y-1,z,x),T(z-1,x,y));
}
```
```haskell
t :: Int -> Int -> Int -> Int
t x y z = if x <= y then
y
else
t (t (x-1) y z) (t (y-1) z x) (t (z-1) x y)
```
```ruby
def T(x,y,z)
if x β€ y
return y
else
return T(T(x-1,y,z),T(y-1,z,x),T(z-1,x,y))
end
end
```
Let us define function `U` as:
```python
U(n) = T(n,0,n+1)
```
```javascript
U(n) = T(n,0,n+1)
```
```haskell
u :: Int -> Int
u n = t n 0 (n+1)
```
```ruby
U(n) = T(n,0,n+1)
```
Let `E(n)` be the number of times the `else` clause in the `T` function is invoked when computing `U(n)` (no memoization or laziness). We get:
```python
E(5) = 223 # for n = 5, the else clause is invoked 223 times in the T function
E(10) = 1029803
```
```javascript
E(5) = 223 // for n = 5, the else clause is invoked 223 times in the T function
E(10) = 1029803
```
```haskell
e 5 = 223 -- for n = 5, the else clause is invoked 223 times in the t function
e 10 = 1029803
```
```ruby
E(5) = 223 # for n = 5, the else clause is invoked 223 times in the T function
E(10) = 1029803
```
You will be given a number `n` and your task is to return the digital sum of `E(n)`:
```python
solve(5) = 7 # E(5) = 223 and the sum of digits in 223 = 7 because 223 => 2 + 2 + 3 = 7
solve(10) = 23, # E(10) = 1029803 and the sum of digits in 1029803 is 23
```
```javascript
solve(5) = 7 // E(5) = 223 and the sum of digits in 223 = 7 because 223 => 2 + 2 + 3 = 7
solve(10) = 23, // E(10) = 1029803 and the sum of digits in 1029803 is 23
```
```haskell
solve 5 = 7 -- e 5 = 223 and the sum of digits in 223 = 7 because 223 -> 2 + 2 + 3 = 7
solve 10 = 23 -- e 10 = 1029803 and the sum of digits in 1029803 is 23
```
```ruby
solve(5) = 7 # E(5) = 223 and the sum of digits in 223 = 7 because 223 => 2 + 2 + 3 = 7
solve(10) = 23, # E(10) = 1029803 and the sum of digits in 1029803 is 23
```
`n` will not exceed `165`. More examples in test cases. Good luck!
[Takeuchi Function on wikipedia](https://en.wikipedia.org/wiki/Tak_(function)) | reference | from functools import lru_cache
@ lru_cache(maxsize=None)
def T(x, y, z):
if x <= y:
return y, 0
else:
(a, ac), (b, bc), (c, cc) = T(x - 1, y, z), T(y - 1, z, x), T(z - 1, x, y)
d, dc = T(a, b, c)
return d, 1 + ac + bc + cc + dc
def solve(n):
count = T(n, 0, n + 1)[1]
return sum(map(int, str(count)))
| The Takeuchi function | 5d2477487c046b0011b45254 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d2477487c046b0011b45254 | 6 kyu |
Some new cashiers started to work at your restaurant.
They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
All the orders they create look something like this:
`"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"`
The kitchen staff are threatening to quit, because of how difficult it is to read the orders.
Their preference is to get the orders as a nice clean string with spaces and capitals like so:
`"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"`
The kitchen staff expect the items to be in the same order as they appear in the menu.
The menu items are fairly simple, there is no overlap in the names of the items:
```
1. Burger
2. Fries
3. Chicken
4. Pizza
5. Sandwich
6. Onionrings
7. Milkshake
8. Coke
```
| reference | def get_order(order):
menu = ['burger', 'fries', 'chicken', 'pizza',
'sandwich', 'onionrings', 'milkshake', 'coke']
clean_order = ''
for i in menu:
clean_order += (i . capitalize() + ' ') * order . count(i)
return clean_order[: - 1]
| New Cashier Does Not Know About Space or Shift | 5d23d89906f92a00267bb83d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5d23d89906f92a00267bb83d | 6 kyu |
In an infinite array with two rows, the numbers in the top row are denoted
`. . . , A[β2], A[β1], A[0], A[1], A[2], . . .`
and the numbers in the bottom row are denoted
`. . . , B[β2], B[β1], B[0], B[1], B[2], . . .`
For each integer `k`, the entry `A[k]` is directly above
the entry `B[k]` in the array, as shown:
<table style="width:auto;">
<tr><td>...</td><td>|</td><td>A[-2]</td><td>|</td><td>A[-1]</td><td>|</td><td>A[0]</td><td>|</td><td>A[1]</td><td>|</td><td>A[2]</td><td>|</td><td>...</td></tr>
<tr><td>...</td><td>|</td><td>B[-2]</td><td>|</td><td>B[-1]</td><td>|</td><td>B[0]</td><td>|</td><td>B[1]</td><td>|</td><td>B[2]</td><td>|</td><td>...</td></tr>
<tr><td></td></tr><tr><td></td></tr>
</table>
For each integer `k`, `A[k]` is the average of the entry to its left, the entry to its right,
and the entry below it; similarly, each entry `B[k]` is the average of the entry to its
left, the entry to its right, and the entry above it.
Given `A[0], A[1], A[2] and A[3]`, determine the value of `A[n]`. (Where range of n is -1000<n<1000)
**Test Cases are called as an array of `([A[0], A[1], A[2], A[3]], n)`**
Hint: Calculate `B[k]`
**FOR JS Node v10.x -> Inputs and Outputs in BigInt!**
Adapted from 2018 Euclid Mathematics Contest.
https://www.cemc.uwaterloo.ca/contests/past_contests/2018/2018EuclidContest.pdf | algorithms | def find_a(lst, n):
if n < 0:
return find_a(lst[:: - 1], 3 - n)
if n < 4:
return lst[n]
a, b, c, d = lst
for _ in range(n - 3):
a, b, c, d = b, c, d, 6 * d - 10 * c + 6 * b - a
return d
| Averaging in an Infinite Array | 5d1eb2db874bdf9bf6a4b2aa | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5d1eb2db874bdf9bf6a4b2aa | 6 kyu |
Given an array of integers `a` and integers `t` and `x`, count how many elements in the array you can make equal to `t` by **increasing** / **decreasing** it by `x` (or doing nothing).
*EASY!*
```python
# ex 1
a = [11, 5, 3]
t = 7
x = 2
count(a, t, x) # => 3
```
- you can make 11 equal to 7 by subtracting 2 twice
- you can make 5 equal to 7 by adding 2
- you can make 3 equal to 7 by adding 2 twice
```python
# ex 2
a = [-4,6,8]
t = -7
x = -3
count(a, t, x) # => 2
```
## Constraints
**-10<sup>18</sup> <= a[i],t,x <= 10<sup>18</sup>**
**3 <= |a| <= 10<sup>4</sup>**
| reference | def count(a, t, x):
return sum(not (t - v) % x if x else t == v for v in a)
| Make Equal | 5d1e1560c193ae0015b601a2 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d1e1560c193ae0015b601a2 | 7 kyu |
A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n.
For example, if n = 12, then
* 12 / 2 = 6
* 6 / 2 = 3
So we divided successively 2 times and we reached 3, so the strongness of 12 is `2`.
If n = 16 then
* 16 / 2 = 8
* 8 / 2 = 4
* 4 / 2 = 2
* 2 / 2 = 1
we divided successively 4 times and we reached 1, so the strongness of 16 is `4`
# Task
Given a closed interval `[n, m]`, return the even number that is the strongest in the interval. If multiple solutions exist return the smallest strongest even number.
Note that programs must run within the allotted server time; a naive solution will probably time out.
# Constraints
```if-not:ruby
1 <= n < m <= INT_MAX
```
```if:ruby
1 <= n < m <= 2^64
```
# Examples
```
[1, 2] --> 2 # 1 has strongness 0, 2 has strongness 1
[5, 10] --> 8 # 5, 7, 9 have strongness 0; 6, 10 have strongness 1; 8 has strongness 3
[48, 56] --> 48
| algorithms | """Strongest even number in an interval kata
Defines strongest_even(n, m) which returns the strongest even number in the set
of integers on the interval [n, m].
Constraints:
1. 1 <= n < m < MAX_INT
Note:
1. The evenness of zero is need not be defined given the constraints.
2. In Python 3, the int type is unbounded. In Python 2, MAX_INT is
determined by the platform.
Definition:
A number is said to be more strongly even than another number if the
multiplicity of 2 in its prime factorization is higher than in the prime
factorization of the other number.
"""
from math import log2
def strongest_even(n, m):
"""Returns the strongest even number in the set of integers on interval
[n, m].
"""
# It can be shown that the largest power of 2 on an interval [n, m] will
# necessarily be the strongest even number. Check first if the interval
# contains a power of 2, by comparing the log2 of the endpoints.
if int(log2(m)) > int(log2(n)):
return 2 * * int(log2(m))
# Modify the endpoints exclude any odd numbers. If the two endpoints are
# equal, the original interval contains only a single even number. Return it.
n += n % 2
m -= m % 2
if n == m:
return n
# All optimizations and edge cases are exhausted. Recurse with the
# modified endpoints halved, and multiply the result by 2.
return 2 * strongest_even(n / / 2, m / / 2)
| Strongest even number in an interval | 5d16af632cf48200254a6244 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5d16af632cf48200254a6244 | 6 kyu |
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array.
```
Examples:
solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4
solve( [[10,-15],[-1,-3]] ) = 45, given by (-15) * (-3)
solve( [[1,-1],[2,3],[10,-100]] ) = 300, given by (-1) * 3 * (-100)
```
More examples in test cases. Good luck!
| reference | def solve(arr):
p, q = 1, 1
for k in arr:
x, y = max(k), min(k)
a = p * x
b = q * x
c = p * y
d = q * y
p = max(a, b, c, d)
q = min(a, b, c, d)
return max(p, q)
| Simple array product | 5d0365accfd09600130a00c9 | [
"Fundamentals"
] | https://www.codewars.com/kata/5d0365accfd09600130a00c9 | 7 kyu |
## Baby Shark Lyrics

Create a function, as short as possible, that returns this lyrics.
Your code should be less than `300` characters.
Watch out for the three points at the end of the song.
```
Baby shark, doo doo doo doo doo doo
Baby shark, doo doo doo doo doo doo
Baby shark, doo doo doo doo doo doo
Baby shark!
Mommy shark, doo doo doo doo doo doo
Mommy shark, doo doo doo doo doo doo
Mommy shark, doo doo doo doo doo doo
Mommy shark!
Daddy shark, doo doo doo doo doo doo
Daddy shark, doo doo doo doo doo doo
Daddy shark, doo doo doo doo doo doo
Daddy shark!
Grandma shark, doo doo doo doo doo doo
Grandma shark, doo doo doo doo doo doo
Grandma shark, doo doo doo doo doo doo
Grandma shark!
Grandpa shark, doo doo doo doo doo doo
Grandpa shark, doo doo doo doo doo doo
Grandpa shark, doo doo doo doo doo doo
Grandpa shark!
Let's go hunt, doo doo doo doo doo doo
Let's go hunt, doo doo doo doo doo doo
Let's go hunt, doo doo doo doo doo doo
Let's go hunt!
Run away,β¦
```
Good Luck!
```if:haskell,go
Haskell and Go: A trailing newline `\n` is expected in the result.
```
```if:cpp
C++: `<string>` is preloaded, you don't need to `#include` it.
```
```if:c
C: The result string can be static or heap-allocated, it doesn't matter. Use whatever allows you to write the shortest solution.
``` | reference | def baby_shark_lyrics(): return "\n" . join(f" { y } , { ' doo' * 6 } \n" * 3 + y + "!" for y in [
x + " shark" for x in "Baby Mommy Daddy Grandma Grandpa" . split()] + ["Let's go hunt"]) + "\nRun away,β¦"
| Baby shark lyrics generator | 5d076515e102162ac0dc514e | [
"Strings",
"Lists",
"Fundamentals",
"Restricted"
] | https://www.codewars.com/kata/5d076515e102162ac0dc514e | 7 kyu |
`Lithium_3` has the electron configuration: `2)1)`, meaning it has 2 electrons in the first shell, 1 in the second shell.
Electrons are always torn from the last shell when an ionization occurs. In the `Li` atom above, if we tear one electron apart from it, it becomes `2)`.
This ionization as a cost in energy, which depends on the radius of the atom/ion and the number of protons its nucleus holds:
`Energy = nProtons / radius^2` (no units, in the current context)
<h1> Task </h1>
In this kata you are expected to compute the <b>total_energy</b> of the ionization of a certain number of electrons from an atom, according to the following rules:
* Number of protons of a nucleus is equal to its initial number of electrons (see `inputs`)
* Cost in energy to remove one single electron is computed accordingly to the formula above
* Electrons are always removed from the outer shell still containing electrons.
* When a shell is emptied, the radius of the atom/ion decreases. To keep things simple, we will considere that radii of the shells, counting from the nucleus, are increasing with a regular step. For example if the most inner shell has a radius `r`, second shell is `2r`, then `3r`, ...
<h1> Inputs </h1>
You will be given:
* A list `electrons`, with the initial partition of the electrons in the shells (inner->outer). We do not follow the real chemistry here, therefore any shell of the atom can contain between 1 and 8 electrons.
* The number of electrons to ionize, `remove_count`. It will not be negative, however it can be more than the number of electrons of the atom. In this case you should just remove all the electrons.
* The `total_radius`, which will be the initial radius of the atom, from core to last shell.
<h1> Output </h1>
The total energy needed to remove the required number of electrons.
<h1> Example </h1>
```electron_ionization([2,3,4], 5, 2.4) == 9.765625```
Last 4 electrons with 9 protons and the distance 2.4 require an energy of `6.25`.
We need to remove one more from the remaining electrons, `[2,3]`, with now the distance 1.6 and so a cost of `3.515625`.
Hence: `total = 9.765625`
| reference | def electron_ionization(electrons, rc, arad):
res, el, rd, prot = 0, electrons[:], arad / len(electrons), sum(electrons)
while rc and el:
res += min(rc, el[- 1]) * prot / (rd * len(el)) * * 2
rc -= min(rc, el[- 1])
el . pop()
return res
| Extract the Electrons | 5d023b69ac68b82dd2cdf70b | [
"Fundamentals"
] | https://www.codewars.com/kata/5d023b69ac68b82dd2cdf70b | 6 kyu |
Let us consider this example (array written in general format):
`ls = [0, 1, 3, 6, 10]`
Its following parts:
```
ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []
```
The corresponding sums are (put together in a list):
`[20, 20, 19, 16, 10, 0]`
The function `parts_sums` (or its variants in other languages) will take as parameter a list `ls`
and return a list of the sums of its parts as defined above.
#### Other Examples:
```
ls = [1, 2, 3, 4, 5, 6]
parts_sums(ls) -> [21, 20, 18, 15, 11, 6, 0]
ls = [744125, 935, 407, 454, 430, 90, 144, 6710213, 889, 810, 2579358]
parts_sums(ls) -> [10037855, 9293730, 9292795, 9292388, 9291934, 9291504, 9291414, 9291270, 2581057, 2580168, 2579358, 0]
```
#### Notes
- Take a look at performance: some lists have thousands of elements.
- Please ask before translating.
| algorithms | def parts_sums(ls):
result = [sum(ls)]
for item in ls:
result . append(result[- 1] - item)
return result
| Sums of Parts | 5ce399e0047a45001c853c2b | [
"Fundamentals",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5ce399e0047a45001c853c2b | 6 kyu |
The principle of spiral permutation consists in concatenating the different characters of a string in a spiral manner starting with the last character (last character, first character, character before last character, second character, etc.).
This principle is illustrated by the example below, which for a starting string "ABCDE" formed of 5 letters and after 4 spiral permutations, the string "BDECA" is obtained. The 5th spiral permutation allows to find the starting string.
# Task
Write a function that given a string s return an array of all the distinct possible permutations.
The elements of the resulting array are ordered and added sequentially, meaning ```arr[1]``` is generated from ```arr[0]```, ```arr[2]``` is generated from ```arr[1]``` and so on.
# Examples
```Javascript
spiralPermutations("ABCDE")
//=> ["ABCDE","EADBC","CEBAD","DCAEB","BDECA"]
// given "ABCDE" we can generate fellowing permutation by concatenating the following letters
// "E" + "A" (last char + first)
// "D" + "B" (4th char + 2nd char)
// "C" (middle or 3rd char)
// ==> "EADBC"
```
```Javascript
spiralPermutations("ABABA")
//=> ["ABABA","AABBA","AABAB","BAAAB","BBAAA"]
```
```Javascript
spiralPermutations('HLORRSGXRV')
//=> ['HLORRSGXRV','VHRLXOGRSR','RVSHRRGLOX','XROVLSGHRR','RXRRHOGVSL','LRSXVRGROH' ]
```
```Javascript
spiralPermutations('MAAMAAA')
//=> ["MAAMAAA","AMAAAAM"]
```
```Javascript
spiralPermutations('XXXXX')
//=> ['XXXXX']
```
# Test cases
It will be the following test cases :
* One static test case
* One with a fixed odd/even number of chars test cases
* Five random odd/even number of chars test cases
It will be garanteed that the s parameters will have three or more chars as input. | games | def sp(s):
ln = len(s)
res = [''] * ln
res[:: 2] = s[ln / / 2:][:: - 1]
res[1:: 2] = s[: ln / / 2]
return '' . join(res)
def spiral_permutations(s):
seen, cur, res = {s}, s, [s]
while True:
cur = sp(cur)
if cur in seen:
return res
else:
seen . add(cur)
res . append(cur)
| Word Spiral Permutations Generator | 5cfca6670310c20001286bc8 | [
"Puzzles"
] | https://www.codewars.com/kata/5cfca6670310c20001286bc8 | 6 kyu |
In this Kata, you will be given a string and your task will be to return the length of the longest prefix that is also a suffix. A prefix is the start of a string while the suffix is the end of a string. For instance, the prefixes of the string `"abcd"` are `["a","ab","abc"]`. The suffixes are `["bcd", "cd", "d"]`. You should not overlap the prefix and suffix.
```Haskell
for example:
solve("abcd") = 0, because no prefix == suffix.
solve("abcda") = 1, because the longest prefix which == suffix is "a".
solve("abcdabc") = 3. Longest prefix which == suffix is "abc".
solve("aaaa") = 2. Longest prefix which == suffix is "aa". You should not overlap the prefix and suffix
solve("aa") = 1. You should not overlap the prefix and suffix.
solve("a") = 0. You should not overlap the prefix and suffix.
```
All strings will be lowercase and string lengths are `1 <= length <= 500`
More examples in test cases. Good luck! | reference | def solve(st):
return next((n for n in range(len(st) / / 2, 0, - 1) if st[: n] == st[- n:]), 0)
| String prefix and suffix | 5ce969ab07d4b7002dcaa7a1 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ce969ab07d4b7002dcaa7a1 | 7 kyu |
# Summary
In this kata, you have to make a function named `uglify_word` (`uglifyWord` in Java and Javascript). It accepts a string parameter.
# What does the uglify_word do?
It checks the char in the given string from the front with an iteration, in the iteration it does these steps:
1. There is a flag and it will be started from `1`.
2. Check the current char in the iteration index.
- If it is an alphabet character `[a-zA-Z]` and the flag value is equal to `1`, then change this character to upper case.
- If it is an alphabet character `[a-zA-Z]` and the flag value is equal to `0`, then change this character to lower case.
- Otherwise, if it is not an alphabet character, then set the flag value to `1`.
3. If the current char is an alphabet character, do a boolean not operation to the flag.
After the iteration has done, return the fixed string that might have been changed in such iteration.
# Examples
```
uglify_word("aaa") === "AaA"
uglify_word("AAA") === "AaA"
uglify_word("BbB") === "BbB"
uglify_word("aaa-bbb-ccc") === "AaA-BbB-CcC"
uglify_word("AaA-BbB-CcC") === "AaA-BbB-CcC"
uglify_word("eeee-ffff-gggg") === "EeEe-FfFf-GgGg"
uglify_word("EeEe-FfFf-GgGg") === "EeEe-FfFf-GgGg"
uglify_word("qwe123asdf456zxc") === "QwE123AsDf456ZxC"
uglify_word("Hello World") === "HeLlO WoRlD"
```
| algorithms | def uglify_word(s):
flag = 1
ugly = []
for c in s:
ugly . append(c . upper() if flag else c . lower())
flag = not flag or not c . isalpha()
return '' . join(ugly)
| Uglify Word | 5ce6cf94cb83dc0020da1929 | [
"Algorithms"
] | https://www.codewars.com/kata/5ce6cf94cb83dc0020da1929 | 7 kyu |
In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each letter occurs only once.
```haskell
Rules are: (1) the letters are adjacent in the English alphabet, and (2) each letter occurs only once.
For example:
solve("abc") = True, because it contains a,b,c
solve("abd") = False, because a, b, d are not consecutive/adjacent in the alphabet, and c is missing.
solve("dabc") = True, because it contains a, b, c, d
solve("abbc") = False, because b does not occur once.
solve("v") = True
```
All inputs will be lowercase letters.
More examples in test cases. Good luck! | reference | import string
def solve(st):
return '' . join(sorted(st)) in string . ascii_letters
| Consecutive letters | 5ce6728c939bf80029988b57 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ce6728c939bf80029988b57 | 7 kyu |
Your job is to list all of the numbers up to 2 ** `n` - 1 that contain a 1 at the same places/bits as the binary representation of b.`b` will be 1,2,4,8,etc.</br>
For example:
`solution(4,2)` would return [2,3,6,7,10,11,14,15].</br>
The binary numbers from 1 to 16 are:</br>
8 4 2 1 (place)</br>
0 0 0 1</br>
0 0 1 0</br>
0 0 1 1</br>
0 1 0 0</br>
0 1 0 1</br>
0 1 1 0</br>
0 1 1 1</br>
1 0 0 0</br>
1 0 0 1</br>
1 0 1 0</br>
1 0 1 1</br>
1 1 0 0</br>
1 1 0 1</br>
1 1 1 0</br>
1 1 1 1</br>
The numbers with a 1 in the 2's place are 2,3,6,7,10,11,14,and 15</br>
Other examples:</br>
`solution(0,1)` = []</br>
`solution(6,8)` = [8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 56, 57, 58, 59, 60, 61, 62, 63]</br>
If b = 0,return empty list. | reference | def solution(n, b):
return [x for x in range(1 << n) if x & b]
| Fun with binary numbers | 5ce04eadd103f4001edd8986 | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5ce04eadd103f4001edd8986 | 7 kyu |
Most football fans love it for the goals and excitement. Well, this Kata doesn't.
You are to handle the referee's little notebook and count the players who were sent off for fouls and misbehavior.
The rules:
Two teams, named "A" and "B" have 11 players each; players on each team are numbered from 1 to 11.
Any player may be sent off the field by being given a red card.
A player can also receive a yellow warning card, which is fine, but if he receives another yellow card, he is sent off immediately (no need for a red card in that case).
If one of the teams has less than 7 players remaining, the game is stopped immediately by the referee, and the team with less than 7 players loses.
A `card` is a string with the team's letter ('A' or 'B'), player's number, and card's color ('Y' or 'R') - all concatenated and capitalized.
e.g the card `'B7Y'` means player #7 from team B received a yellow card.
The task: Given a list of cards (could be empty), return the number of remaining players on each team at the end of the game (as a tuple of 2 integers, team "A" first).
If the game was terminated by the referee for insufficient number of players, you are to stop the game immediately, and ignore any further possible cards.
Note for the random tests: If a player that has already been sent off receives another card - ignore it. | reference | def men_still_standing(cards):
# generate teams
A = {k: 0 for k in range(1, 12)}
B = A . copy()
for card in cards:
# parse card
team = A if card[0] == "A" else B
player = int(card[1: - 1])
color = card[- 1]
if player not in team:
continue
# record penalty
team[player] += 1 if color == "Y" else 2
if team[player] >= 2:
del team[player]
if len(team) < 7:
break
return len(A), len(B)
| Football - Yellow and Red Cards | 5cde4e3f52910d00130dc92c | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5cde4e3f52910d00130dc92c | 6 kyu |
In this Kata you are a game developer and have programmed the #1 MMORPG(Massively Multiplayer Online Role Playing Game) worldwide!!! Many suggestions came across you to make the game better, one of which you are interested in and will start working on at once.
Players in the game have levels from 1 to 170, XP(short for experience) is required to increase the player's level and is obtained by doing all sorts of things in the game, a new player starts at level 1 with 0 XP. You want to add a feature that would enable the player to input a target level and the output would be how much XP the player must obtain in order for him/her to reach the target level...simple huh.
Create a function called ```xp_to_target_lvl``` that takes 2 arguments(```current_xp``` and ```target_lvl```, both as integer) and returns the remaining XP for the player to reach the ```target_lvl``` formatted as a rounded down integer.
Leveling up from level 1 to level 2 requires 314 XP, at first each level up requires 25% XP more than the previous level up, every 10 levels the percentage increase reduces by 1. See the examples for a better understanding.
Keep in mind that when players reach level 170 they stop leveling up but they continue gaining experience.
If one or both of the arguments are invalid(not given, not in correct format, not in range...etc) return "Input is invalid.".
If the player has already reached the ```target_lvl``` return ```"You have already reached level target_lvl."```.
Examples:
```
xp_to_target_lvl(0,5) => XP from lvl1 to lvl2 = 314
XP from lvl2 to lvl3 = 314 + (314*0.25) = 392
XP from lvl3 to lvl4 = 392 + (392*0.25) = 490
XP from lvl4 to lvl5 = 490 + (490*0.25) = 612
XP from lvl1 to target_lvl = 314 + 392 + 490 + 612 = 1808
XP from current_xp to target_lvl = 1808 - 0 = 1808
xp_to_target_lvl(12345,17) => XP from lvl1 to lvl2 = 314
XP from lvl2 to lvl3 = 314 + (314*0.25) = 392
XP from lvl3 to lvl4 = 392 + (392*0.25) = 490
...
XP from lvl9 to lvl10 = 1493 + (1493*0.25) = 1866
XP from lvl10 to lvl11 = 1866 + (1866*0.24) = 2313 << percentage increase is
... reduced by 1 (25 - 1 = 24)
XP from lvl16 to lvl17 = 6779 + (6779*0.24) = 8405
XP from lvl1 to target_lvl = 314 + 392 + 490 + 612 + ... + 8405 = 41880
XP from current_xp to target_lvl = 41880 - 12345 = 29535
xp_to_target_lvl() => "Input is invalid." }
xp_to_target_lvl(-31428.7,'47') => "Input is invalid." }> Invalid input
xp_to_target_lvl(83749,0) => "Input is invalid." }
xp_to_target_lvl(2017,4) => "You have already reached level 4."
xp_to_target_lvl(0,1) => 'You have already reached level 1.'
```
Make sure you round down the XP required for each level up, rounding up will result in the output being slightly wrong. | algorithms | def xp_to_target_lvl(* args):
if len(args) < 2:
return 'Input is invalid.'
current_xp, target_lvl = args
if not isinstance(target_lvl, int):
return 'Input is invalid.'
if not (0 < target_lvl < 171):
return 'Input is invalid.'
if current_xp < 0:
return 'Input is invalid.'
level = 1
xp = 314
xp_bump = 25
sum_ = 0
while level < target_lvl:
sum_ += xp
level += 1
xp_bump_reduction = level / / 10
xp += int(xp * (xp_bump - xp_bump_reduction) / 100)
diff = sum_ - current_xp
if diff <= 0:
return 'You have already reached level {}.' . format(target_lvl)
else:
return diff
| Level Up! | 593dbaccdf1adef94100006c | [
"Iterators",
"Algorithms"
] | https://www.codewars.com/kata/593dbaccdf1adef94100006c | 6 kyu |
We want to define the location `x`, `y` of a `point` on a two-dimensional plane where `x` and `y` are positive integers.
Our definition of such a `point` will return a function (procedure). There are several possible functions to do that.
Possible form of `point`:
```if:racket
~~~
(define (point a b)
(lambda ...))
(procedure? (point 3 4)) -> #t
~~~
```
```if:python
~~~
def point(a, b):
return lambda ...
callable(point(3,4)) -> True
~~~
```
```if:javascript
~~~
const point = (a, b) => {
// your code
};
typeof(point(a, b)) === "function"
~~~
```
```if:scala
~~~
point(a: Int, b: Int): ... complete ... {
// your code
};
The type of point(a, b) is "scala.Function..."
~~~
```
```if:fsharp
~~~
point(a: int, b: int): ... complete ... =
// your code
The type of point(a, b) is "System.Func..."
~~~
```
```if:csharp
~~~
... complete with the type of your function ... point(int a, int b) {
// your code
}
The type of point(a, b) is "System.Func..."
~~~
```
```if:vb
~~~
Point(ByVal a As Integer, ByVal b As Integer) As ... complete ...
' your code
The type of point(a, b) is "System.Func..."
~~~
```
```if:java
~~~
... complete with the type of your function ... point(int a, int b) {
// your code
}
The return type of point(a, b) is "java.util.function.Function"
~~~
```
Of course we need to be able to extract from our `point` the two coordinates `x` and `y`.
The function `fst` must return the first element `x` and our function `snd` must return the second element `y`.
We will also write a function `sqr-dist` which returns the square of the distance between two points `point1` and `point2`.
Last function to write `line`:
Given two `points` `foo` and `bar` this function return a list `(l m n)` or `[l, m, n]` where `l, m, n` are the coefficients in
the general equation `l*x + m*y + n = 0 (1)` of the straight line through the points `foo` and `bar`.
Equation `k*l*x + k*m*y + k*n = 0` is equivalent to (1) and the tests consider that they define the "same" line.
### Examples: See "Sample Tests".
```if:racket
~~~
(define foo (point 3 5))
(procedure? (point 3 5)) -> #t
(fst foo) -> 3
(snd foo) -> 5
(sqr-dist (point 22 55) (point 75 66)) -> 2930
(line (point 20 22) (point 29 10)) -> '(12 9 -438) ['(4 3 -146) is a good answer too]
~~~
```
```if:python
~~~
foo = point(3, 5)
callable(point(3, 5)) -> True
fst(foo) -> 3
snd(foo) -> 5
sqr-dist(point(22, 55), point(75, 66)) -> 2930
line(point(20, 22), point(29, 10)) -> [12, 9, -438] ([4, 3, -146] is a good answer too)
~~~
```
```if:javascript
~~~
foo = point(3, 5)
typeof(point(3, 5)) === "function" -> true
fst(foo) -> 3
snd(foo) -> 5
sqr-dist(point(22, 55), point(75, 66)) -> 2930
line(point(20, 22), point(29, 10)) -> [12, 9, -438] ([4, 3, -146] is a good answer too)
~~~
```
## Note:
- Please ask before translating: some translations are already written and published when/if the kata is approved.
| reference | def point(a, b):
def f(): return (a, b)
f . x = a
f . y = b
return f
def fst(pt):
return pt . x
def snd(pt):
return pt . y
def sqr_dist(pt1, pt2):
return (pt2 . x - pt1 . x) * * 2 + (pt2 . y - pt1 . y) * * 2
def line(pt1, pt2):
a = pt1 . y - pt2 . y
b = pt2 . x - pt1 . x
c = pt1 . x * pt2 . y - pt2 . x * pt1 . y
return [a, b, c]
| Change your Points of View | 5ca3ae9bb7de3a0025c5c740 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ca3ae9bb7de3a0025c5c740 | 6 kyu |
Your job is to implement a function which returns the last `D` digits of an integer `N` as a list.
### Special cases:
* If `D > (the number of digits of N)`, return all the digits.
* If `D <= 0`, return an empty list.
## Examples:
```
N = 1
D = 1
result = [1]
N = 1234
D = 2
result = [3, 4]
N = 637547
D = 6
result = [6, 3, 7, 5, 4, 7]
``` | reference | def solution(n, d):
return [int(c) for c in str(n)[- d:]] if d > 0 else []
| last digits of a number | 5cd5ba1ce4471a00256930c0 | [
"Fundamentals"
] | https://www.codewars.com/kata/5cd5ba1ce4471a00256930c0 | 7 kyu |
# Summary:
Given a number, `num`, return the shortest amount of `steps` it would take from 1, to land exactly on that number.
# Description:
A `step` is defined as either:
- Adding 1 to the number: `num += 1`
- Doubling the number: `num *= 2`
You will always start from the number `1` and you will have to return the shortest count of steps it would take to land exactly on that number.
`1 <= num <= 10000`
Examples:
`num == 3` would return `2` steps:
```
1 -- +1 --> 2: 1 step
2 -- +1 --> 3: 2 steps
2 steps
```
`num == 12` would return `4` steps:
```
1 -- +1 --> 2: 1 step
2 -- +1 --> 3: 2 steps
3 -- x2 --> 6: 3 steps
6 -- x2 --> 12: 4 steps
4 steps
```
`num == 16` would return `4` steps:
```
1 -- +1 --> 2: 1 step
2 -- x2 --> 4: 2 steps
4 -- x2 --> 8: 3 steps
8 -- x2 --> 16: 4 steps
4 steps
```
~~~if:lambdacalc
# Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
~~~ | games | def shortest_steps_to_num(num):
steps = 0
while num != 1:
if num % 2:
num -= 1
else:
num / /= 2
steps += 1
return steps
| Shortest steps to a number | 5cd4aec6abc7260028dcd942 | [
"Puzzles",
"Mathematics",
"Fundamentals",
"Games"
] | https://www.codewars.com/kata/5cd4aec6abc7260028dcd942 | 6 kyu |
Everybody loves **pi**, but what if **pi** were a square? Given a number of digits ```digits```, find the smallest integer whose square is greater or equal to the sum of the squares of the first ```digits``` digits of pi, including the ```3``` before the decimal point.
**Note:** Test cases will not extend beyond 100 digits; the first 100 digits of pi are pasted here for your convenience:
```
31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
```
## Examples
```
digits = 1 # [3]
expected = 3 # sqrt(3^2) = 3
digits = 3 # [3, 1, 4]
expected = 6 # sqrt(3^2 + 1^2 + 4^2) = 5.099 --> 6
``` | algorithms | from math import ceil
PI_DIGITS_SQUARED = [int(d) * * 2 for d in "31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"]
def square_pi(n):
return ceil(sum(PI_DIGITS_SQUARED[: n]) * * 0.5)
| Square Pi's | 5cd12646cf44af0020c727dd | [
"Algorithms"
] | https://www.codewars.com/kata/5cd12646cf44af0020c727dd | 7 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.