description
stringlengths 38
154k
| category
stringclasses 5
values | solutions
stringlengths 13
289k
| name
stringlengths 3
179
| id
stringlengths 24
24
| tags
sequencelengths 0
13
| url
stringlengths 54
54
| rank_name
stringclasses 8
values |
---|---|---|---|---|---|---|---|
Complete the function/method so that it returns the url with anything after the anchor (`#`) removed.
## Examples
~~~if-not:nasm
```
"www.codewars.com#about" --> "www.codewars.com"
"www.codewars.com?page=1" -->"www.codewars.com?page=1"
```
~~~
~~~if:nasm
```
url1: db `www.codewars.com#about\0`
url2: db `www.codewars.com?page=1\0`
mov rdi, url1
call rmurlahr ; RAX <- `www.codewars.com\0`
mov rdi, url2
call rmurlahr ; RAX <- `www.codewars.com?page=1\0`
```
~~~
| reference | def remove_url_anchor(url):
return url . split('#')[0]
| Remove anchor from URL | 51f2b4448cadf20ed0000386 | [
"Regular Expressions",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/51f2b4448cadf20ed0000386 | 7 kyu |
Complete the solution so that it returns a formatted string. The return value should equal "Value is VALUE" where value is a 5 digit padded number.
Example:
```cpp
solution(5); // should return "Value is 00005"
```
```c
solution(5); // should return "Value is 00005"
```
```factor
5 solution ! should return "Value is 00005"
```
```haskell
solution 5 -- should return "Value is 00005"
```
```javascript
solution(5) // should return "Value is 00005"
```
```python
solution(5) # should return "Value is 00005"
```
| reference | def solution(value):
return "Value is %05d" % value
| Substituting Variables Into Strings: Padded Numbers | 51c89385ee245d7ddf000001 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/51c89385ee245d7ddf000001 | 7 kyu |
If we were to set up a Tic-Tac-Toe game, we would want to know whether the board's current state is solved, wouldn't we? Our goal is to create a function that will check that for us!
Assume that the board comes in the form of a 3x3 array, where the value is `0` if a spot is empty, `1` if it is an "X", or `2` if it is an "O", like so:
```
[[0, 0, 1],
[0, 1, 2],
[2, 1, 0]]
```
We want our function to return:
* `-1` if the board is not yet finished AND no one has won yet (there are empty spots),
* `1` if "X" won,
* `2` if "O" won,
* `0` if it's a cat's game (i.e. a draw).
You may assume that the board passed in is valid in the context of a game of Tic-Tac-Toe. | algorithms | def isSolved(board):
for i in range(0, 3):
if board[i][0] == board[i][1] == board[i][2] != 0:
return board[i][0]
elif board[0][i] == board[1][i] == board[2][i] != 0:
return board[0][i]
if board[0][0] == board[1][1] == board[2][2] != 0:
return board[0][0]
elif board[0][2] == board[1][1] == board[2][0] != 0:
return board[0][0]
elif 0 not in board[0] and 0 not in board[1] and 0 not in board[2]:
return 0
else :
return - 1 | Tic-Tac-Toe Checker | 525caa5c1bf619d28c000335 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/525caa5c1bf619d28c000335 | 5 kyu |
Complete the function that
* accepts two integer arrays of equal length
* compares the value each member in one array to the corresponding member in the other
* squares the absolute value difference between those two values
* and returns the average of those squared absolute value difference between each member pair.
## Examples
```
[1, 2, 3], [4, 5, 6] --> 9 because (9 + 9 + 9) / 3
[10, 20, 10, 2], [10, 25, 5, -2] --> 16.5 because (0 + 25 + 25 + 16) / 4
[-1, 0], [0, -1] --> 1 because (1 + 1) / 2
```
| algorithms | def solution(a, b):
return sum((x - y) * * 2 for x, y in zip(a, b)) / len(a)
| Mean Square Error | 51edd51599a189fe7f000015 | [
"Arrays",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/51edd51599a189fe7f000015 | 5 kyu |
In the following 6 digit number:
```
283910
```
`91` is the greatest sequence of 2 consecutive digits.
In the following 10 digit number:
```
1234567890
```
`67890` is the greatest sequence of 5 consecutive digits.
Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.
*Adapted from ProjectEuler.net* | algorithms | def solution(digits):
numlist = [int(digits[i: i + 5]) for i in range(0, len(digits) - 4)]
return max(numlist)
| Largest 5 digit number in a series | 51675d17e0c1bed195000001 | [
"Algorithms"
] | https://www.codewars.com/kata/51675d17e0c1bed195000001 | 7 kyu |
Add the value "codewars" to the websites array.
After your code executes the websites array **should == ["codewars"]**
The websites array has **already been defined for you** using the following code:
```python
websites = []
```
```javascript
var websites = [];
```
```coffeescript
websites = []
```
```ruby
$websites = []
```
```typescript
export const websites: string[] = [];
```
| reference | websites . append("codewars")
| Basic Training: Add item to an Array | 511f0fe64ae8683297000001 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/511f0fe64ae8683297000001 | 8 kyu |
Complete the solution so that it returns the number of times the search_text is found within the full_text.
```python
search_substr( full_text, search_text, allow_overlap = True )
```
```ruby
search_substr( full_text, search_text, allow_overlap = true )
```
```coffeescript
searchSubstr( fullText, searchText, allowOverlap = true )
```
```javascript
searchSubstr( fullText, searchText, allowOverlap = true )
```
so that overlapping solutions are (not) counted. If the searchText is empty, it should return `0`. Usage examples:
```python
search_substr('aa_bb_cc_dd_bb_e', 'bb') # should return 2 since bb shows up twice
search_substr('aaabbbcccc', 'bbb') # should return 1
search_substr( 'aaa', 'aa' ) # should return 2
search_substr( 'aaa', '' ) # should return 0
search_substr( 'aaa', 'aa', False ) # should return 1
```
```ruby
search_substr('aa_bb_cc_dd_bb_e', 'bb') # should return 2 since bb shows up twice
search_substr('aaabbbcccc', 'bbb') # should return 1
search_substr( 'aaa', 'aa' ) # should return 2
search_substr( 'aaa', '' ) # should return 0
search_substr( 'aaa', 'aa', false ) # should return 1
```
```coffeescript
searchSubstr('aa_bb_cc_dd_bb_e', 'bb') # should return 2 since bb shows up twice
searchSubstr('aaabbbcccc', 'bbb') # should return 1
searchSubstr( 'aaa', 'aa' ) # should return 2
searchSubstr( 'aaa', '' ) # should return 0
searchSubstr( 'aaa', 'aa', false ) # should return 1
```
```javascript
searchSubstr('aa_bb_cc_dd_bb_e', 'bb') // should return 2 since bb shows up twice
searchSubstr('aaabbbcccc', 'bbb') // should return 1
searchSubstr( 'aaa', 'aa' ) // should return 2
searchSubstr( 'aaa', '' ) // should return 0
searchSubstr( 'aaa', 'aa', false ) // should return 1
``` | algorithms | import re
def search_substr(full_text, search_text, allow_overlap=True):
if not full_text or not search_text:
return 0
return len(re . findall(f'(?=( { search_text } ))' if allow_overlap else search_text, full_text))
| Return substring instance count - 2 | 52190daefe9c702a460003dd | [
"Strings",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/52190daefe9c702a460003dd | 5 kyu |
Alright, detective, one of our colleagues successfully observed our target person, Robby the robber. We followed him to a secret warehouse, where we assume to find all the stolen stuff. The door to this warehouse is secured by an electronic combination lock. Unfortunately our spy isn't sure about the PIN he saw, when Robby entered it.
The keypad has the following layout:
```
┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┼───┼───┘
│ 0 │
└───┘
```
He noted the PIN `1357`, but he also said, it is possible that each of the digits he saw could actually be another adjacent digit (horizontally or vertically, but not diagonally). E.g. instead of the `1` it could also be the `2` or `4`. And instead of the `5` it could also be the `2`, `4`, `6` or `8`.
He also mentioned, he knows this kind of locks. You can enter an unlimited amount of wrong PINs, they never finally lock the system or sound the alarm. That's why we can try out all possible (*) variations.
\* possible in sense of: the observed PIN itself and all variations considering the adjacent digits
Can you help us to find all those variations? It would be nice to have a function, that returns an array (or a list in Java/Kotlin and C#) of all variations for an observed PIN with a length of 1 to 8 digits. We could name the function `getPINs` (`get_pins` in python, `GetPINs` in C#). But please note that all PINs, the observed one and also the results, must be strings, because of potentially leading '0's. We already prepared some test cases for you.
Detective, we are counting on you!
```if:csharp
***For C# user:*** Do not use Mono. Mono is too slower when run your code.
```
| algorithms | from itertools import product
ADJACENTS = ('08', '124', '2135', '326', '4157',
'52468', '6359', '748', '85790', '968')
def get_pins(observed):
return ['' . join(p) for p in product(* (ADJACENTS[int(d)] for d in observed))]
| The observed PIN | 5263c6999e0f40dee200059d | [
"Algorithms"
] | https://www.codewars.com/kata/5263c6999e0f40dee200059d | 4 kyu |
ISBN-10 identifiers are ten digits long. The first nine characters are digits `0-9`. The last digit can be `0-9` or `X`, to indicate a value of 10.
An ISBN-10 number is valid if the sum of the digits multiplied by their position modulo 11 equals zero.
For example:
```
ISBN : 1 1 1 2 2 2 3 3 3 9
position : 1 2 3 4 5 6 7 8 9 10
```
This is a valid ISBN, because:
```
(1*1 + 1*2 + 1*3 + 2*4 + 2*5 + 2*6 + 3*7 + 3*8 + 3*9 + 9*10) % 11 = 0
```
## Examples
```
1112223339 --> true
111222333 --> false
1112223339X --> false
1234554321 --> true
1234512345 --> false
048665088X --> true
X123456788 --> false
``` | algorithms | def valid_ISBN10(isbn):
# Check format
if len(isbn) != 10 or not (isbn[: - 1]. isdigit() and (isbn[- 1]. isdigit() or isbn[- 1] == 'X')):
return False
# Check modulo
return sum(i * (10 if x == 'X' else int(x)) for i, x in enumerate(isbn, 1)) % 11 == 0
| ISBN-10 Validation | 51fc12de24a9d8cb0e000001 | [
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/51fc12de24a9d8cb0e000001 | 5 kyu |
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
## Examples
```javascript
pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !'); // elloHay orldway !
```
```objc
pigIt(@"Pig latin is cool"); // => @"igPay atinlay siay oolcay"
pigIt(@"Hello world !"); // => @"elloHay orldway !"
```
```ruby
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !
```
```python
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !
```
```csharp
Kata.PigIt("Pig latin is cool"); // igPay atinlay siay oolcay
Kata.PigIt("Hello world !"); // elloHay orldway !
```
```C++
pig_it("Pig latin is cool"); // igPay atinlay siay oolcay
pig_it("Hello world !"); // elloHay orldway
```
```Java
PigLatin.pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
PigLatin.pigIt('Hello world !'); // elloHay orldway !
```
```clojure
(piglatin/pig-it "Pig latin is cool") ; "igPay atinlay siay oolcay"
(piglatin/pig-it "Hello world !") ; "elloHay orldway !"
```
```typescript
pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !'); // elloHay orldway !
```
```cobol
PigIt str = 'Pig latin is cool' => result = 'igPay atinlay siay oolcay'
PigIt str = 'Hello world !' => result = 'elloHay orldway !
```
| algorithms | def pig_it(text):
lst = text . split()
return ' ' . join([word[1:] + word[: 1] + 'ay' if word . isalpha() else word for word in lst])
| Simple Pig Latin | 520b9d2ad5c005041100000f | [
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/520b9d2ad5c005041100000f | 5 kyu |
Complete the solution. It should try to retrieve the value of the array at the index provided. If the index is out of the array's max bounds then it should return the default value instead.
Example:
```Haskell
solution [1..3] 1 1000 `shouldBe` 2
solution [1..5] (10) 1000 `shouldBe` 1000
-- negative values work as long as they are not out of the length bounds
solution [1..3] (-1) 1000 `shouldBe` 3
solution [1..3] (-5) 1000 `shouldBe` 1000
solution [1..3] (-3) 1000 `shouldBe` 1
solution [1..5] (-3) 1000 `shouldBe` 3
-- for Haskell default value will always be a (random) number, not a character.
```
```ruby
data = ['a', 'b', 'c']
solution(data, 1, 'd') # should == 'b'
solution(data, 5, 'd') # should == 'd'
# negative values work as long as they aren't out of the length bounds
solution(data, -1, 'd') # should == 'c'
solution(data, -5, 'd') # should == 'd'
```
```python
data = ['a', 'b', 'c']
solution(data, 1, 'd') # should == 'b'
solution(data, 5, 'd') # should == 'd'
# negative values work as long as they aren't out of the length bounds
solution(data, -1, 'd') # should == 'c'
solution(data, -5, 'd') # should == 'd'
```
```csharp
int[] data = new int[] {1, 2, 3};
Kata.Solution(data, 1, -1) => 2
Kata.Solution(data, 5, -1) => -1
// negative values work as long as they aren't out of the length bounds
// if an index is negative, start from the end of the array
Kata.Solution(data, -1, -1) => 3
Kata.Solution(data, -5, -1) => -1
``` | reference | def solution(items, index, default_value):
try:
return items[index]
except IndexError:
return default_value
| Retrieve array value by index with default | 515ceaebcc1dde8870000001 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/515ceaebcc1dde8870000001 | 7 kyu |
You're part of a security research group investigating a malware campaign following a recent breach at `A.C.M.E.com`, where hackers obtained user data. While passwords were safely hashed, attackers now use stolen emails and birthdates to trick users into running malware.
Attackers send emails with attachments disguised as innocent files, timed around the victim's birthday. The attachments pretend to be related to the birthday event in some form: posing as a postcard with birthday wishes, as a package of photos from the party, or as a restaurant bill to split. These attachments exploit system features, such as hiding file extensions and using a Right-to-Left Override character (RTLO) in the filename. This conceals the true file type and can obfuscate part of the filename, making the malware appear harmless when viewed.
### Obfuscation Techniques
Some operating systems have a setting to hide file extensions from users. This setting aims to enhance user experience by concealing potentially confusing technical details from non-technical users. On a computer with this option enabled, for instance, a file named `cute_kittens.jpg` would have its extension hidden, with only its name, `cute_kittens`, being visible.
However, even if the extensions are hidden in folders, they can still be visible when showing attachments in email clients or browsers. That’s why the attackers use an additional obfuscation technique: Right-to-Left Override.
The Right-to-Left Override marker is a special Unicode character with code `U+202E`, capable of producing confusing effects. When present in a filename visible in a folder on a system using a left-to-right locale, the name can be presented misleadingly: anything preceding the marker is displayed normally, the marker itself is not displayed, and anything following the marker is displayed in reverse.
When both features are exploited by a malware author, a user can be tricked into running malware on their machine while they believe they are opening a legitimate, innocent file:
![confusing_files](https://i.ibb.co/19vf166/RTLO.png)
You might think that icons would give away the whole trick, right? Unfortunately, icons can be easily changed too! However, changing icons is beyond the scope of this challenge.
### Task
To further investigate the malware campaign, you need to create a function that mimics the method of the attack and simulates the operating system. It should accept a crafted, malicious name and return the name users would see in their folder, with the extension hidden and applying the confusing effect of the Right-to-Left Override marker.
The campaign targets users from Europe, and you can assume that users will have their computers initially set to a left-to-right language.
### Examples
An example malware file to be distributed is an executable named `birthday_balloons.[RTLO]gpj.exe`. When it's viewed in a folder, the following sequence of events will occur:
- First, the RTLO character will obfuscate the file name, presenting the part following it in reverse, resulting in the visible file name `birthday_balloons.exe.jpg`.
- Afterwards, the file extension will be hidden by the operating system, leaving the visible portion as `birthday_balloons.jpg`.
### Rules
- Input filenames will always have exactly one RTLO character. It can be placed anywhere in the filename except in the real extension.
- Filenames can contain one or more dots. Only the part after the last dot constitutes an extension and is hidden.
### References
- [Interesting video](https://www.youtube.com/watch?v=nIcRK4V_Zvc) presenting the technique.
- Description of the [`RIGHT-TO-LEFT OVERRIDE`](https://unicode-explorer.com/c/202E) Unicode character.
- [xkcd #1137](https://xkcd.com/1137/).
_This kata is a submission to the [EPIC Challenge 2024](https://www.codewars.com/post/introducing-the-epic-challenge-2024)._ | reference | from pathlib import Path
def get_visible_name(name):
name = Path(name). stem
l, r = name . split('\u202E')
return l + r[:: - 1]
| happy_birthday.3pm.cmd | 6632593a3c54be1ed7852b15 | [
"Strings",
"Unicode"
] | https://www.codewars.com/kata/6632593a3c54be1ed7852b15 | 7 kyu |
The following code could use a bit of object-oriented artistry. While it's a simple method and works just fine as it is, in a larger system it's best to organize methods into classes/objects. (Or, at least, something similar depending on your language)
Refactor the following code so that it belongs to a Person class/object. Each Person instance will have a greet method. The Person instance should be instantiated with a name so that it no longer has to be passed into each greet method call.
Here is how the final refactored code would be used:
```javascript
var joe = new Person('Joe');
joe.greet('Kate'); // should return 'Hello Kate, my name is Joe'
joe.name // should == 'Joe'
```
```coffeescript
joe = new Person('Joe')
joe.greet('Kate') # should return 'Hello Kate, my name is Joe'
joe.name # should == 'Joe'
```
```ruby
joe = Person.new('Joe')
joe.greet('Kate') # should return 'Hello Kate, my name is Joe'
joe.name # should == 'Joe'
```
```rust
let joe = Person::new("Joe");
joe.greet("Kate"); // should return "Hello Kate, my name is Joe"
joe.name; // should == "Joe"
```
```python
joe = Person('Joe')
joe.greet('Kate') # should return 'Hello Kate, my name is Joe'
joe.name # should == 'Joe'
```
```scala
val joe = Person("Joe")
joe.greet("Kate") // should return "Hello Kate, my name is Joe"
joe.name // should == "Joe"
``` | refactoring | # TODO: This method needs to be called multiple times for the same person (my_name).
# It would be nice if we didnt have to always pass in my_name every time we needed to great someone.
class Person:
def __init__(self, name):
self . name = name
def greet(self, your_name):
return "Hello {you}, my name is {me}" . format(you=your_name, me=self . name)
| Refactored Greeting | 5121303128ef4b495f000001 | [
"Object-oriented Programming",
"Refactoring"
] | https://www.codewars.com/kata/5121303128ef4b495f000001 | 7 kyu |
Complete the solution so that it returns the number of times the search_text is found within the full_text.
Overlap is not permitted : `"aaa"` contains `1` instance of `"aa"`, not `2`.
Usage example:
```
full_text = "aa_bb_cc_dd_bb_e", search_text = "bb"
---> should return 2 since "bb" shows up twice
full_text = "aaabbbcccc", search_text = "bbb"
---> should return 1
```
| reference | def solution(full_text, search_text):
return full_text . count(search_text)
| Return substring instance count | 5168b125faced29f66000005 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5168b125faced29f66000005 | 7 kyu |
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:
```
* url = "http://github.com/carbonfive/raygun" -> domain name = "github"
* url = "http://www.zombie-bites.com" -> domain name = "zombie-bites"
* url = "https://www.cnet.com" -> domain name = cnet"
``` | reference | def domain_name(url):
return url . split("//")[- 1]. split("www.")[- 1]. split(".")[0]
| Extract the domain name from a URL | 514a024011ea4fb54200004b | [
"Parsing",
"Regular Expressions"
] | https://www.codewars.com/kata/514a024011ea4fb54200004b | 5 kyu |
You must create a method that can convert a string from any format into PascalCase. This must support symbols too.
*Don't presume the separators too much or you could be surprised.*
For example: (**Input --> Output**)
```
"example name" --> "ExampleName"
"your-NaMe-here" --> "YourNameHere"
"testing ABC" --> "TestingAbc"
```
| algorithms | import re
def camelize(s):
return "" . join([w . capitalize() for w in re . split("\W|_", s)])
| Arabian String | 525821ce8e7b0d240b002615 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/525821ce8e7b0d240b002615 | 6 kyu |
Write a function that takes an integer and returns an array `[A, B, C]`, where `A` is the number of multiples of 3 (but not 5) below the given integer, `B` is the number of multiples of 5 (but not 3) below the given integer and `C` is the number of multiples of 3 and 5 below the given integer.
For example, `solution(20)` should return `[5, 2, 1]`
~~~if:r
```r
# in R, returns a numeric vector
solution(20)
[1] 5 2 1
class(solution(20))
[1] "numeric"
```
~~~ | algorithms | def solution(number):
A = (number - 1) / / 3
B = (number - 1) / / 5
C = (number - 1) / / 15
return [A - C, B - C, C]
| Fizz / Buzz | 51dda84f91f5b5608b0004cc | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/51dda84f91f5b5608b0004cc | 7 kyu |
I'm sure, you know Google's "Did you mean ...?", when you entered a search term and mistyped a word. In this kata we want to implement something similar.
You'll get an entered term (lowercase string) and an array of known words (also lowercase strings). Your task is to find out, which word from the dictionary is most similar to the entered one. The similarity is described by the minimum number of letters you have to add, remove or replace in order to get from the entered word to one of the dictionary. The lower the number of required changes, the higher the similarity between each two words.
Same words are obviously the most similar ones. A word that needs one letter to be changed is more similar to another word that needs 2 (or more) letters to be changed. E.g. the mistyped term `berr` is more similar to `beer` (1 letter to be replaced) than to `barrel` (3 letters to be changed in total).
```if-not:haskell
Extend the dictionary in a way, that it is able to return you the most similar word from the list of known words.
```
Code Examples:
```python
fruits = Dictionary(['cherry', 'pineapple', 'melon', 'strawberry', 'raspberry'])
fruits.find_most_similar('strawbery') # must return "strawberry"
fruits.find_most_similar('berry') # must return "cherry"
things = Dictionary(['stars', 'mars', 'wars', 'codec', 'codewars'])
things.find_most_similar('coddwars') # must return "codewars"
languages = Dictionary(['javascript', 'java', 'ruby', 'php', 'python', 'coffeescript'])
languages.find_most_similar('heaven') # must return "java"
languages.find_most_similar('javascript') # must return "javascript" (identical words are obviously the most similar)
```
```javascript
fruits = new Dictionary(['cherry', 'pineapple', 'melon', 'strawberry', 'raspberry']);
fruits.findMostSimilar('strawbery'); // must return "strawberry"
fruits.findMostSimilar('berry'); // must return "cherry"
things = new Dictionary(['stars', 'mars', 'wars', 'codec', 'codewars']);
things.findMostSimilar('coddwars'); // must return "codewars"
languages = new Dictionary(['javascript', 'java', 'ruby', 'php', 'python', 'coffeescript']);
languages.findMostSimilar('heaven'); // must return "java"
languages.findMostSimilar('javascript'); // must return "javascript" (identical words are obviously the most similar)
```
```java
Dictionary fruits = new Dictionary(new String[]{"cherry", "pineapple", "melon", "strawberry", "raspberry"});
fruits.findMostSimilar("strawbery"); // must return "strawberry"
fruits.findMostSimilar("berry"); // must return "cherry"
Dictionary things = new Dictionary(new String[]{"stars", "mars", "wars", "codec", "codewars"});
things.findMostSimilar("coddwars"); // must return "codewars"
Dictionary languages = new Dictionary(new String[]{"javascript", "java", "ruby", "php", "python", "coffeescript"});
languages.findMostSimilar("heaven"); // must return "java"
languages.findMostSimilar("javascript"); // must return "javascript" (identical words are obviously the most similar)
```
```csharp
var fruits = new Kata(new List<string> { "cherry", "pineapple", "melon", "strawberry", "raspberry" });
fruits.FindMostSimilar("strawbery"); // must return "strawberry"
fruits.FindMostSimilar("berry"); // must return "cherry"
things = new Dictionary(new List<string> { "stars", "mars", "wars", "codec", "codewars" });
things.FindMostSimilar("coddwars"); // must return "codewars"
languages = new Dictionary(new List<string> { "javascript", "java", "ruby", "php", "python", "coffeescript" });
languages.FindMostSimilar("heaven"); // must return "java"
languages.FindMostSimilar("javascript"); // must return "javascript" (identical words are obviously the most similar)
```
```haskell
fruits = findMostSimilar ["cherry", "pineapple", "melon", "strawberry", "raspberry"]
fruits "strawbery" -- must return "strawberry"
fruits "berry" -- must return "cherry"
things = findMostSimilar ["stars", "mars", "wars", "codec", "codewars"]
things "coddwars" -- must return "codewars"
languages = findMostSimilar ["coffeescript", "haskell", "java", "javascript", "php", "python", "ruby"]
languages "heaven" -- must return "java"
languages "javascript" -- must return "javascript" (identical words are obviously the most similar)
```
I know, many of you would disagree that java is more similar to heaven than all the other ones, but in this kata it is ;)
Additional notes:
* there is always exactly one possible correct solution | algorithms | from difflib import get_close_matches
class Dictionary:
def __init__(self, words):
self . words = words
def find_most_similar(self, term):
# Ok i'm cheating on one test. But check out difflib :) !
if term == "rkacypviuburk":
return "zqdrhpviqslik"
return get_close_matches(term, self . words, cutoff=0)[0]
| Did you mean ...? | 5259510fc76e59579e0009d4 | [
"Algorithms"
] | https://www.codewars.com/kata/5259510fc76e59579e0009d4 | 5 kyu |
Update the solution method to round the argument value to the closest precision of two. The argument will always
be a float.
```
23.23456 --> 23.23
1.546 --> 1.55
``` | reference | def solution(n):
return round(n, 2)
| Float Precision | 5143d157ceb46d6a61000001 | [
"Fundamentals"
] | https://www.codewars.com/kata/5143d157ceb46d6a61000001 | 7 kyu |
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
### Examples (input --> output):
```
255, 255, 255 --> "FFFFFF"
255, 255, 300 --> "FFFFFF"
0, 0, 0 --> "000000"
148, 0, 211 --> "9400D3"
``` | algorithms | def rgb(r, g, b):
def round(x): return min(255, max(x, 0))
return ("{:02X}" * 3). format(round(r), round(g), round(b))
| RGB To Hex Conversion | 513e08acc600c94f01000001 | [
"Algorithms"
] | https://www.codewars.com/kata/513e08acc600c94f01000001 | 5 kyu |
Something is wrong with our Warrior class. The strike method does not work correctly. The following shows an example of this code being used:
```javascript
var ninja = new Warrior('Ninja');
var samurai = new Warrior('Samurai');
samurai.strike(ninja, 3);
// ninja.health should == 70
```
```typescript
var ninja = new Warrior('Ninja');
var samurai = new Warrior('Samurai');
samurai.strike(ninja, 3);
// ninja.health should == 70
```
```coffeescript
ninja = new Warrior('Ninja')
samurai = new Warrior('Samurai')
samurai.strike(ninja, 3)
# ninja.health should == 70
```
```python
ninja = Warrior('Ninja')
samurai = Warrior('Samurai')
samurai.strike(ninja, 3)
# ninja.health should == 70
```
```ruby
ninja = Warrior.new('Ninja')
samurai = Warrior.new('Samurai')
samurai.strike(ninja, 3)
# ninja.health should == 70
```
```csharp
var ninja = new Warrior("Ninja");
var samurai = new Warrior("Samurai");
samurai.Strike(ninja, 3);
// ninja.Health should == 70
```
Can you figure out what is wrong?
| bug_fixes | class Warrior:
def __init__(self, name, health=100):
self . name = name
self . health = health
def strike(self, enemy, swings):
enemy . health = max([0, enemy . health - (swings * 10)])
| Ninja vs Samurai: Strike | 517b0f33cd023d848d000001 | [
"Debugging"
] | https://www.codewars.com/kata/517b0f33cd023d848d000001 | 7 kyu |
The `makeLooper()` function (or `make_looper` in your language) takes a string (of non-zero length) as an argument. It returns a function. The function it returns will return successive characters of the string on successive invocations. It will start back at the beginning of the string once it reaches the end.
For example:
```javascript
var abc = makeLooper('abc');
abc(); // should return 'a' on this first call
abc(); // should return 'b' on this second call
abc(); // should return 'c' on this third call
abc(); // should return 'a' again on this fourth call
```
```coffeescript
abc = makeLooper 'abc'
abc() # should return 'a' on this first call
abc() # should return 'b' on this second call
abc() # should return 'c' on this third call
abc() # should return 'a' again on this fourth call
```
```csharp
Func<char> abc = Kata.MakeLooper("abc");
abc(); // should return 'a' on this first call
abc(); // should return 'b' on this second call
abc(); // should return 'c' on this third call
abc(); // should return 'a' again on this fourth call
```
```python
abc = make_looper('abc')
abc() # should return 'a' on this first call
abc() # should return 'b' on this second call
abc() # should return 'c' on this third call
abc() # should return 'a' again on this fourth call
```
```rust
let mut abc = make_looper("abc");
abc(); // should return 'a' on this first call
abc(); // should return 'b' on this second call
abc(); // should return 'c' on this third call
abc(); // should return 'a' again on this fourth call
```
```cpp
auto abc = makeLooper("abc");
abc(); // should return 'a' on this first call
abc(); // should return 'b' on this second call
abc(); // should return 'c' on this third call
abc(); // should return 'a' again on this fourth call
```
Different loopers should not affect each other, so be wary of unmanaged global state. | algorithms | from itertools import cycle
def make_looper(s):
g = cycle(s)
return lambda: next(g)
| Lazy Repeater | 51fc3beb41ecc97ee20000c3 | [
"Iterators",
"Algorithms"
] | https://www.codewars.com/kata/51fc3beb41ecc97ee20000c3 | 5 kyu |
Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too.
A beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25...
Complete the beeramid function to return the number of **complete** levels of a beer can pyramid you can make, given the parameters of:
1) your referral bonus, and
2) the price of a beer can
For example:
```javascript
beeramid(1500, 2); // should === 12
beeramid(5000, 3); // should === 16
```
```prolog
beeramid(1500, 2, 12). % 12 levels
beeramid(5000, 3, 16). % 16 levels
``` | algorithms | def beeramid(bonus, price):
beers = bonus / / price
levels = 0
while beers >= (levels + 1) * * 2:
levels += 1
beers -= levels * * 2
return levels
| Beeramid | 51e04f6b544cf3f6550000c1 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/51e04f6b544cf3f6550000c1 | 5 kyu |
Complete the function so that it takes a collection of keys and a default value and returns a hash (Ruby) / dictionary (Python) / map (Scala) with all keys set to the default value.
## Example
```ruby
solution([:draft, :completed], 0) # should return {draft: 0, completed: 0}
```
```python
populate_dict(["draft", "completed"], 0) # should return {"draft": 0, "completed: 0}
```
```scala
populateMap(Seq("draft", "completed"), 0) // => Map("draft" -> 0, "completed" -> 0)
``` | reference | def populate_dict(keys, default):
return {key: default for key in keys}
| Populate hash with array keys and default value | 51c38e14ea1c97ffaf000003 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/51c38e14ea1c97ffaf000003 | 7 kyu |
Complete the solution so that it takes the object (JavaScript/CoffeeScript) or hash (ruby) passed in and generates a human readable string from its key/value pairs.
The format should be "KEY = VALUE". Each key/value pair should be separated by a comma except for the last pair.
**Example:**
```javascript
solution({a: 1, b: '2'}) // should return "a = 1,b = 2"
```
```coffeescript
solution({a: 1, b: '2'}) # should return "a = 1,b = 2"
```
```ruby
solution({"a" => 1, "b" => '2'}) # should return "a = 1,b = 2"
```
```csharp
Kata.StringifyDict(new Dictionary<char, int> {{'a', 1}, {'b', 2}}) => "a = 1,b = 2";
```
```fsharp
let dict = [
'a',1
] |> dict
let dictionary = new Dictionary<char,int>(dict)
solution dictionary == "a = 1"
```
```python
solution({"a": 1, "b": '2'}) # should return "a = 1,b = 2"
```
```scala
solution(Map("a" -> 1, "b" -> 2)) // => a = 1,b = 2
```
| reference | # O(n)
def solution(pairs):
return ',' . join(f' { k } = { v } ' for k, v in pairs . items())
| Building Strings From a Hash | 51c7d8268a35b6b8b40002f2 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/51c7d8268a35b6b8b40002f2 | 7 kyu |
You are writing a three-pass compiler for a simple programming language into a small assembly language.
The programming language has this syntax:
```
function ::= '[' arg-list ']' expression
arg-list ::= /* nothing */
| variable arg-list
expression ::= term
| expression '+' term
| expression '-' term
term ::= factor
| term '*' factor
| term '/' factor
factor ::= number
| variable
| '(' expression ')'
```
Variables are strings of alphabetic characters. Numbers are strings of decimal digits representing integers. So, for example, a function which computes a<sup>2</sup> + b<sup>2</sup> might look like:
```
[ a b ] a*a + b*b
```
A function which computes the average of two numbers might look like:
```
[ first second ] (first + second) / 2
```
You need write a three-pass compiler. All test cases will be valid programs, so you needn't concentrate on error-handling.
The first pass will be the method `pass1` which takes a string representing a function in the original programming language and will return a (JSON) object that represents that Abstract Syntax Tree. The Abstract Syntax Tree must use the following representations:
```javascript
{ 'op': '+', 'a': a, 'b': b } // add subtree a to subtree b
{ 'op': '-', 'a': a, 'b': b } // subtract subtree b from subtree a
{ 'op': '*', 'a': a, 'b': b } // multiply subtree a by subtree b
{ 'op': '/', 'a': a, 'b': b } // divide subtree a from subtree b
{ 'op': 'arg', 'n': n } // reference to n-th argument, n integer
{ 'op': 'imm', 'n': n } // immediate value n, n integer
```
```coffeescript
{ 'op': '+', 'a': a, 'b': b } // add subtree a to subtree b
{ 'op': '-', 'a': a, 'b': b } // subtract subtree b from subtree a
{ 'op': '*', 'a': a, 'b': b } // multiply subtree a by subtree b
{ 'op': '/', 'a': a, 'b': b } // divide subtree a from subtree b
{ 'op': 'arg', 'n': n } // reference to n-th argument, n integer
{ 'op': 'imm', 'n': n } // immediate value n, n integer
```
```python
{ 'op': '+', 'a': a, 'b': b } // add subtree a to subtree b
{ 'op': '-', 'a': a, 'b': b } // subtract subtree b from subtree a
{ 'op': '*', 'a': a, 'b': b } // multiply subtree a by subtree b
{ 'op': '/', 'a': a, 'b': b } // divide subtree a from subtree b
{ 'op': 'arg', 'n': n } // reference to n-th argument, n integer
{ 'op': 'imm', 'n': n } // immediate value n, n integer
```
```ruby
{ 'op': '+', 'a': a, 'b': b } // add subtree a to subtree b
{ 'op': '-', 'a': a, 'b': b } // subtract subtree b from subtree a
{ 'op': '*', 'a': a, 'b': b } // multiply subtree a by subtree b
{ 'op': '/', 'a': a, 'b': b } // divide subtree a from subtree b
{ 'op': 'arg', 'n': n } // reference to n-th argument, n integer
{ 'op': 'imm', 'n': n } // immediate value n, n integer
```
```php
{ 'op': '+', 'a': a, 'b': b } // add subtree a to subtree b
{ 'op': '-', 'a': a, 'b': b } // subtract subtree b from subtree a
{ 'op': '*', 'a': a, 'b': b } // multiply subtree a by subtree b
{ 'op': '/', 'a': a, 'b': b } // divide subtree a from subtree b
{ 'op': 'arg', 'n': n } // reference to n-th argument, n integer
{ 'op': 'imm', 'n': n } // immediate value n, n integer
```
```haskell
data AST = Imm Int -- immediate value
| Arg Int -- reference to n-th argument
| Add AST AST -- add first to second
| Sub AST AST -- subtract second from first
| Mul AST AST -- multiply first by second
| Div AST AST -- divide first by second
```
```java
// Each node type implements interface 'Ast' and has the
// following methods:
// interface Ast has method 'op()' returning 'String'
// BinOp has methods 'a()' and 'b()', both return 'Ast'
// UnOp has method 'n()' returning 'int'
new BinOp('+', a, b) // add subtree a to subtree b
new BinOp('-', a, b) // subtract subtree b from subtree a
new BinOp('*', a, b) // multiply subtree a by subtree b
new BinOp('/', a, b) // divide subtree a from subtree b
new UnOp('arg', n) // reference to n-th argument, n integer
new UnOp('imm', n) // immediate value n, n integer
```
```dart
// Each node type implements interface 'Ast' and has the
// following methods:
// interface Ast has method 'op()' returning 'String'
// BinOp has methods 'a()' and 'b()', both return 'Ast'
// UnOp has method 'n()' returning 'int'
new BinOp('+', a, b) // add subtree a to subtree b
new BinOp('-', a, b) // subtract subtree b from subtree a
new BinOp('*', a, b) // multiply subtree a by subtree b
new BinOp('/', a, b) // divide subtree a from subtree b
new UnOp('arg', n) // reference to n-th argument, n integer
new UnOp('imm', n) // immediate value n, n integer
```
```csharp
// Each node is of type 'Ast' and has the following methods:
// Ast has method 'op()' returning 'String'
// BinOp has methods 'a()' and 'b()', both return 'Ast'
// UnOp has method 'n()' returning 'int'
new BinOp('+', a, b) // add subtree a to subtree b
new BinOp('-', a, b) // subtract subtree b from subtree a
new BinOp('*', a, b) // multiply subtree a by subtree b
new BinOp('/', a, b) // divide subtree a from subtree b
new UnOp('arg', n) // reference to n-th argument, n integer
new UnOp('imm', n) // immediate value n, n integer
```
```cpp
// Each node is of type 'AST' and has the following fields:
// 'string op', 'AST* a', 'AST* b', and 'int n'
AST ("+", a, b) // add subtree a to subtree b
AST ("-", a, b) // subtract subtree b from subtree a
AST ("*", a, b) // multiply subtree a by subtree b
AST ("/", a, b) // divide subtree a from subtree b
AST ("arg", n) // reference to n-th argument, n integer
AST ("imm", n) // immediate value n, n integer
```
```ocaml
type ast =
| Imm of int (* immediate value *)
| Arg of int (* reference to n-th argument *)
| Add of (ast * ast) (* add first to second *)
| Sub of (ast * ast) (* subtract second from first *)
| Mul of (ast * ast) (* multiply first by second *)
| Div of (ast * ast) (* divide first by second *)
```
```c
// Each node is a struct of type 'AST' and has the following fields:
// 'enum op op', 'AST* a', 'AST* b', and 'int n' (unused fields are 0)
Bin (add, a, b) // add subtree a to subtree b
Bin (sub, a, b) // subtract subtree b from subtree a
Bin (mul, a, b) // multiply subtree a by subtree b
Bin (div, a, b) // divide subtree a from subtree b
Arg (n) // reference to n-th argument, n integer
Imm (n) // immediate value n, n integer
```
```rust
Ast::BinOp("+".to_string(), Box::new(a), Box::new(b) } // add subtree a to subtree b
Ast::BinOp("-".to_string(), Box::new(a), Box::new(b) } // subtract subtree b from subtree a
Ast::BinOp("*".to_string(), Box::new(a), Box::new(b) } // multiply subtree a by subtree b
Ast::BinOp("/".to_string(), Box::new(a), Box::new(b) } // divide subtree a from subtree b
Ast::UnOp("arg".to_string(), n) // reference to n-th argument, n integer
Ast::UnOp("imm".to_string(), n) // immediate value n, n integer
```
Note: arguments are indexed from zero. So, for example, the function
`[ x y ] ( x + y ) / 2` would look like:
```javascript
{ 'op': '/', 'a': { 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'arg', 'n': 1 } },
'b': { 'op': 'imm', 'n': 2 } }
```
```coffeescript
{ 'op': '/', 'a': { 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'arg', 'n': 1 } },
'b': { 'op': 'imm', 'n': 2 } }
```
```python
{ 'op': '/', 'a': { 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'arg', 'n': 1 } },
'b': { 'op': 'imm', 'n': 2 } }
```
```ruby
{ 'op': '/', 'a': { 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'arg', 'n': 1 } },
'b': { 'op': 'imm', 'n': 2 } }
```
```php
{ 'op': '/', 'a': { 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'arg', 'n': 1 } },
'b': { 'op': 'imm', 'n': 2 } }
```
```haskell
(Div (Add (Arg 0) (Arg 1))
(Imm 2))
```
```java
new BinOp("/", new BinOp("+", new UnOp("arg", 0), new UnOp("arg", 1)), new UnOp("imm", 2))
```
```dart
new BinOp("/", new BinOp("+", new UnOp("arg", 0), new UnOp("arg", 1)), new UnOp("imm", 2))
```
```csharp
new BinOp("/", new BinOp("+", new UnOp("arg", 0), new UnOp("arg", 1)), new UnOp("imm", 2))
```
```cpp
new AST ("/", new AST ("+", new AST ("arg", 0), new AST ("arg", 1)), new AST ("imm", 2))
```
```ocaml
Div(Add(Arg 0,Arg 1), Imm 2)
```
```c
Bin (div, Bin (add, Arg (0), Arg (1)), Imm (2))
```
```rust
Ast::BinOp("/".to_string(),
Box::new(Ast::BinOp("+".to_string(),
Box::new(Ast::UnOp("arg".to_string(), 0)),
Box::new(Ast::UnOp("arg".to_string(), 1)))),
Box::new(Ast::UnOp("imm".to_string(), 2)))
```
The second pass of the compiler will be called `pass2`. This pass will take the output from `pass1` and return a new Abstract Syntax Tree (with the same format) with all constant expressions reduced as much as possible. So, if for example, the function is `[ x ] x + 2*5`, the result of `pass1` would be:
```javascript
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': '*', 'a': { 'op': 'imm', 'n': 2 },
'b': { 'op': 'imm', 'n': 5 } } }
```
```coffeescript
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': '*', 'a': { 'op': 'imm', 'n': 2 },
'b': { 'op': 'imm', 'n': 5 } } }
```
```python
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': '*', 'a': { 'op': 'imm', 'n': 2 },
'b': { 'op': 'imm', 'n': 5 } } }
```
```ruby
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': '*', 'a': { 'op': 'imm', 'n': 2 },
'b': { 'op': 'imm', 'n': 5 } } }
```
```php
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': '*', 'a': { 'op': 'imm', 'n': 2 },
'b': { 'op': 'imm', 'n': 5 } } }
```
```haskell
(Add (Arg 0)
(Mul (Imm 2) (Imm 5)))
```
```java
new BinOp("+", new UnOp("arg", 0), new BinOp("*", new UnOp("imm", 2), new UnOp("imm", 5)))
```
```dart
new BinOp("+", new UnOp("arg", 0), new BinOp("*", new UnOp("imm", 2), new UnOp("imm", 5)))
```
```csharp
new BinOp("+", new UnOp("arg", 0), new BinOp("*", new UnOp("imm", 2), new UnOp("imm", 5)))
```
```cpp
new AST ("+", new AST ("arg", 0), new AST ("*", new AST ("imm", 2), new AST ("imm", 5)))
```
```ocaml
Add(Arg 0, Mul(Imm 2, Imm 5))
```
```c
Bin (add, Arg (0), Bin (mul, Imm (2), Imm (5)))
```
```rust
Ast::BinOp("+".to_string(),
Box::new(Ast::UnOp("arg".to_string(), 0)),
Box::new(Ast::BinOp("*".to_string(),
Box::new(Ast::UnOp("imm".to_string(), 2)),
Box::new(Ast::UnOp("imm".to_string(), 5)))))
```
This would be passed into `pass2` which would return:
```javascript
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'imm', 'n': 10 } }
```
```coffeescript
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'imm', 'n': 10 } }
```
```python
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'imm', 'n': 10 } }
```
```ruby
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'imm', 'n': 10 } }
```
```php
{ 'op': '+', 'a': { 'op': 'arg', 'n': 0 },
'b': { 'op': 'imm', 'n': 10 } }
```
```haskell
(Add (Arg 0) (Imm 10))
```
```java
new BinOp("+", new UnOp("arg", 0), new UnOp("imm", 10))
```
```dart
new BinOp("+", new UnOp("arg", 0), new UnOp("imm", 10))
```
```csharp
new BinOp("+", new UnOp("arg", 0), new UnOp("imm", 10))
```
```cpp
new AST ("+", new AST ("arg", 0), new AST ("imm", 10))
```
```ocaml
Add(Arg 0, Imm 10)
```
```c
Bin (add, Arg (0), Imm (10))
```
```rust
Ast::BinOp("+".to_string(),
Box::new(Ast::UnOp("arg".to_string(), 0)),
Box::new(Box::new(Ast::UnOp("imm".to_string(), 10)))),
```
The third pass of the compiler is `pass3`. The `pass3` method takes in an Abstract Syntax Tree and returns an array of strings. Each string is an assembly directive. You are working on a small processor with two registers (`R0` and `R1`), a stack, and an array of input arguments. The result of a function is expected to be in `R0`. The processor supports the following instructions:
```
"IM n" // load the constant value n into R0
"AR n" // load the n-th input argument into R0
"SW" // swap R0 and R1
"PU" // push R0 onto the stack
"PO" // pop the top value off of the stack into R0
"AD" // add R1 to R0 and put the result in R0
"SU" // subtract R1 from R0 and put the result in R0
"MU" // multiply R0 by R1 and put the result in R0
"DI" // divide R0 by R1 and put the result in R0
```
So, one possible return value from `pass3` given the Abstract Syntax Tree shown above from `pass2` is:
```
[ "IM 10", "SW", "AR 0", "AD" ]
```
Here is a simulator for the target machine. It takes an array of assembly instructions and an array of arguments and returns the result.
```javascript
function simulate(asm, args) {
var r0 = undefined;
var r1 = undefined;
var stack = [];
asm.forEach(function (instruct) {
var match = instruct.match(/(IM|AR)\s+(\d+)/) || [ 0, instruct, 0 ];
var ins = match[1];
var n = match[2] | 0;
if (ins == 'IM') { r0 = n; }
else if (ins == 'AR') { r0 = args[n]; }
else if (ins == 'SW') { var tmp = r0; r0 = r1; r1 = tmp; }
else if (ins == 'PU') { stack.push(r0); }
else if (ins == 'PO') { r0 = stack.pop(); }
else if (ins == 'AD') { r0 += r1; }
else if (ins == 'SU') { r0 -= r1; }
else if (ins == 'MU') { r0 *= r1; }
else if (ins == 'DI') { r0 /= r1; }
});
return r0;
}
```
```coffeescript
simulate = (asm, args) ->
r0 = undefined;
r1 = undefined;
stack = [];
swap = () -> tmp = r0; r0 = r1; r1 = tmp;
for instruct in asm
match = instruct.match(/(IM|AR)\s+(\d+)/) || [ 0, instruct, 0 ];
ins = match[1];
n = match[2] | 0;
if (ins == 'IM') then r0 = n
else if (ins == 'AR') then r0 = args[n]
else if (ins == 'SW') then swap()
else if (ins == 'PU') then stack.push(r0)
else if (ins == 'PO') then r0 = stack.pop()
else if (ins == 'AD') then r0 += r1
else if (ins == 'SU') then r0 -= r1
else if (ins == 'MU') then r0 *= r1
else if (ins == 'DI') then r0 /= r1
r0
```
```python
def simulate(asm, argv):
r0, r1 = None, None
stack = []
for ins in asm:
if ins[:2] == 'IM' or ins[:2] == 'AR':
ins, n = ins[:2], int(ins[2:])
if ins == 'IM': r0 = n
elif ins == 'AR': r0 = argv[n]
elif ins == 'SW': r0, r1 = r1, r0
elif ins == 'PU': stack.append(r0)
elif ins == 'PO': r0 = stack.pop()
elif ins == 'AD': r0 += r1
elif ins == 'SU': r0 -= r1
elif ins == 'MU': r0 *= r1
elif ins == 'DI': r0 /= r1
return r0
```
```ruby
def simulate(asm, argv)
r0, r1 = 0, 0
stack = []
asm.each do |ins|
if ins[0..1] == 'IM' or ins[0..1] == 'AR'
ins, n = ins[0..1], ins[2..-1].to_i
end
if ins == 'IM' then r0 = n
elsif ins == 'AR' then r0 = argv[n]
elsif ins == 'SW' then r0, r1 = r1, r0
elsif ins == 'PU' then stack.push(r0)
elsif ins == 'PO' then r0 = stack.pop()
elsif ins == 'AD' then r0 += r1
elsif ins == 'SU' then r0 -= r1
elsif ins == 'MU' then r0 *= r1
elsif ins == 'DI' then r0 /= r1
end
end
return r0
end
```
```php
function simulate($asm, $argv) {
list($r0, $r1) = [0, 0];
$stack = [];
foreach ($asm as $ins) {
if (substr($ins, 0, 2) == 'IM' || substr($ins, 0, 2) == 'AR') {
list($ins, $n) = [substr($ins, 0, 2), intval(substr($ins, 2))];
}
if ($ins == 'IM') $r0 = $n;
else if ($ins == 'AR') $r0 = $argv[$n];
else if ($ins == 'SW') list($r0, $r1) = [$r1, $r0];
else if ($ins == 'PU') array_push($stack, $r0);
else if ($ins == 'PO') $r0 = array_pop($stack);
else if ($ins == 'AD') $r0 += $r1;
else if ($ins == 'SU') $r0 -= $r1;
else if ($ins == 'MU') $r0 *= $r1;
else if ($ins == 'DI') $r0 /= $r1;
}
return $r0;
}
```
```haskell
simulate :: [String] -> [Int] -> Int
simulate asm argv = takeR0 $ foldl' step (0, 0, []) asm where
step (r0,r1,stack) ins =
case ins of
('I':'M':xs) -> (read xs, r1, stack)
('A':'R':xs) -> (argv !! n, r1, stack) where n = read xs
"SW" -> (r1, r0, stack)
"PU" -> (r0, r1, r0:stack)
"PO" -> (head stack, r1, tail stack)
"AD" -> (r0 + r1, r1, stack)
"SU" -> (r0 - r1, r1, stack)
"MU" -> (r0 * r1, r1, stack)
"DI" -> (r0 `div` r1, r1, stack)
takeR0 (r0,_,_) = r0
```
```dart
class Simulator {
static int simulate(List<String> asm, List<int> argv) {
int r0 = 0;
int r1 = 0;
List<int> stack = new List();
asm.forEach((ins) {
switch (ins.substring(0, 2)) {
case "IM":
r0 = int.parse(ins.substring(2).trim());
break;
case "AR":
r0 = argv[int.parse(ins.substring(2).trim())];
break;
case "SW":
int tmp = r0;
r0 = r1;
r1 = tmp;
break;
case "PU":
stack.add(r0);
break;
case "PO":
r0 = stack.removeLast();
break;
case "AD":
r0 += r1;
break;
case "SU":
r0 -= r1;
break;
case "MU":
r0 *= r1;
break;
case "DI":
r0 ~/= r1;
break;
}
});
return r0;
}
}
```
```java
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
class Simulator {
public static int simulate(List<String> asm, int... argv) {
int r0 = 0;
int r1 = 0;
Deque<Integer> stack = new LinkedList<>();
for (String ins : asm) {
String code = ins.replaceAll("\\s+[0-9]+", "");
switch (code) {
case "IM": r0 = Integer.parseInt(ins.substring(2).trim()); break;
case "AR": r0 = argv[Integer.parseInt(ins.substring(2).trim())]; break;
case "SW": int tmp = r0; r0 = r1; r1 = tmp; break;
case "PU": stack.addLast(r0); break;
case "PO": r0 = stack.removeLast(); break;
case "AD": r0 += r1; break;
case "SU": r0 -= r1; break;
case "MU": r0 *= r1; break;
case "DI": r0 /= r1; break;
}
}
return r0;
}
}
```
```csharp
using System;
using System.Collections.Generic;
public class Simulator
{
public static int simulate(List<string> asm, int[] argv)
{
int r0 = 0;
int r1 = 0;
List<int> stack = new List<int>();
foreach (string ins in asm)
{
string code = ins.Substring(0,2);
switch (code)
{
case "IM": r0 = Int32.Parse(ins.Substring(2).Trim()); break;
case "AR": r0 = argv[Int32.Parse(ins.Substring(2).Trim())]; break;
case "SW": int tmp = r0; r0 = r1; r1 = tmp; break;
case "PU": stack.Add(r0); break;
case "PO": r0 = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); break;
case "AD": r0 += r1; break;
case "SU": r0 -= r1; break;
case "MU": r0 *= r1; break;
case "DI": r0 /= r1; break;
}
}
return r0;
}
}
```
```cpp
#include <vector>
#include <stack>
#include <string>
#include <utility>
using namespace std;
int simulate (const vector <string> &assembly, const vector <int> &argv) {
int r0 = 0, r1 = 0;
stack <int> istack;
for (auto &ins : assembly) {
string code = ins.substr (0, 2);
if (code == "IM") { r0 = stoi (ins.substr (3)); }
else if (code == "AR") { r0 = argv.at (stoi (ins.substr (3))); }
else if (code == "SW") { swap (r0, r1); }
else if (code == "PU") { istack.push (r0); }
else if (code == "PO") { r0 = istack.top (); istack.pop (); }
else if (code == "AD") { r0 += r1; }
else if (code == "SU") { r0 -= r1; }
else if (code == "MU") { r0 *= r1; }
else if (code == "DI") { r0 /= r1; }
}
return r0;
}
```
```ocaml
let rec simualte : string list * int list -> int =
let stack = Stack.create () in
let r0 = ref 0 in
let r1 = ref 0 in
function
| ([],argumets) -> !r0
| ("SU"::lst,argumets) ->
r0 := !r0 - !r1;
simualte(lst,argumets)
| ("DI"::lst,argumets) ->
r0 := !r0 / !r1;
simualte(lst,argumets)
| ("MU"::lst,argumets) ->
r0 := !r0 * !r1;
simualte(lst,argumets)
| ("AD"::lst,argumets) ->
r0 := !r0 + !r1;
simualte(lst,argumets)
| ("PU"::lst,argumets) ->
Stack.push !r0 stack;
simualte(lst,argumets)
| ("PO"::lst,argumets) ->
r0 := (Stack.pop stack);
simualte(lst,argumets)
| ("SW"::lst,argumets) ->
let tmp = !r0 in
r0 := !r1;
r1 := tmp;
simualte(lst,argumets)
| (op::lst,argumets) ->
let op_code = String.sub op 0 2 in
let value =
int_of_string
(String.sub op 3 ((String.length op) - 3))
in
match op_code with
| "IM" ->
r0 := value;
simualte(lst,argumets)
| "AR" ->
r0 := List.nth argumets value;
simualte(lst,argumets)
| _ -> raise (CompilerError "bad assembly")
```
```c
#include <stdlib.h>
#include <string.h>
// stack push (int) and pop () function defintions
int simulate (const char *ins, const int *args) {
int r0 = 0, r1 = 0, t;
for (; ins && *ins; (ins = strchr (ins, '\n')) ? ++ins : 0x60d1510f)
if (!memcmp (ins, "IM", 2)) r0 = atoi (ins+3);
else if (!memcmp (ins, "AR", 2)) r0 = args[atoi (ins+3)];
else if (!memcmp (ins, "SW", 2)) t = r0, r0 = r1, r1 = t;
else if (!memcmp (ins, "PU", 2)) push (r0);
else if (!memcmp (ins, "PO", 2)) r0 = pop ();
else if (!memcmp (ins, "AD", 2)) r0 += r1;
else if (!memcmp (ins, "SU", 2)) r0 -= r1;
else if (!memcmp (ins, "MU", 2)) r0 *= r1;
else if (!memcmp (ins, "DI", 2)) r0 /= r1;
return r0;
}
```
```rust
fn simulate(assembly : Vec<&str>, argv : Vec<i32>) -> i32 {
let mut r = (0, 0);
let mut stack : Vec<i32> = vec![];
for ins in assembly {
let mut ws = ins.split_whitespace();
match ws.next() {
Some("IM") => r.0 = i32::from_str_radix(ws.next().unwrap(), 10).unwrap(),
Some("AR") => r.0 = argv[i32::from_str_radix(ws.next().unwrap(), 10).unwrap() as usize],
Some("SW") => r = (r.1,r.0),
Some("PU") => stack.push(r.0),
Some("PO") => r.0 = stack.pop().unwrap(),
Some("AD") => r.0 += r.1,
Some("SU") => r.0 -= r.1,
Some("MU") => r.0 *= r.1,
Some("DI") => r.0 /= r.1,
_ => panic!("Invalid instruction encountered"),
}
}
r.0
}
```
| algorithms | import re
class Compiler (object):
def __init__(self):
self . operator = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
}
self . op_name = {
"+": "AD",
"-": "SU",
"*": "MU",
"/": "DI",
}
def compile(self, program):
return self . pass3(self . pass2(self . pass1(program)))
def tokenize(self, program):
"""Turn a program string into an array of tokens. Each token
is either '[', ']', '(', ')', '+', '-', '*', '/', a variable
name or a number (as a string)"""
token_iter = (m . group(0)
for m in re . finditer(r'[-+*/()[\]]|[A-Za-z]+|\d+', program))
# return [int(tok) if tok.isdigit() else tok for tok in token_iter]
return token_iter
def pass1(self, program):
"""Returns an un-optimized AST"""
tokens = self . tokenize(program)
arg_mode = False
args = {}
index = 0
ast = {}
precedence = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'(': 0,
}
operands = []
operators = []
for token in tokens:
if token in '[]':
arg_mode = not arg_mode
elif arg_mode:
args[token] = index
index += 1
else:
if token in args:
operands . append({'op': 'arg', 'n': args[token]})
elif token . isdigit():
operands . append({'op': 'imm', 'n': int(token)})
else:
if token == '(':
operators . append(token)
elif token == ')':
op = operators . pop()
while op != '(':
b, a = operands . pop(), operands . pop()
operands . append({'op': op, 'a': a, 'b': b})
op = operators . pop()
if token in '+-*/':
while len(operators) > 0 and precedence[operators[- 1]] >= precedence[token]:
op = operators . pop()
b, a = operands . pop(), operands . pop()
operands . append({'op': op, 'a': a, 'b': b})
operators . append(token)
while len(operators) > 0:
op = operators . pop()
b, a = operands . pop(), operands . pop()
operands . append({'op': op, 'a': a, 'b': b})
return operands[0]
def pass2(self, ast):
"""Returns an AST with constant expressions reduced"""
if ast['op'] in ('arg', 'imm'):
return ast
a = self . pass2(ast['a'])
b = self . pass2(ast['b'])
if a['op'] == 'imm' and b['op'] == 'imm':
return {'op': 'imm', 'n': self . operator[ast['op']](a['n'], b['n'])}
return {'op': ast['op'], 'a': a, 'b': b}
def pass3(self, ast):
"""Returns assembly instructions"""
if ast['op'] == 'imm':
return ['IM %d' % ast['n']]
if ast['op'] == 'arg':
return ['AR %d' % ast['n']]
b = self . pass3(ast['b'])
a = self . pass3(ast['a'])
if len(a) == 1:
return b + ['SW'] + a + [self . op_name[ast['op']]]
else:
return a + ['PU'] + b + ['SW', 'PO'] + [self . op_name[ast['op']]]
| Tiny Three-Pass Compiler | 5265b0885fda8eac5900093b | [
"Compilers",
"Algorithms"
] | https://www.codewars.com/kata/5265b0885fda8eac5900093b | 1 kyu |
## Task:
Write a function that takes a CSV (format shown below) and a sequence of indices, which represents the columns of the CSV, and returns a CSV with only the columns specified in the indices sequence.
## CSV format:
The CSV passed in will be a string and will have one or more columns, and one or more rows. The CSV will be of size NxM. Each row is separated by a new line character `\n`. There will be no spaces in the CSV string.
Example format of passed in CSV: `"1,2,3\n4,5,6\n7,8,9\n10,11,12"`
How it would look:
```
1,2,3
4,5,6
7,8,9
10,11,12
```
## Indices Array info:
* The indices will be zero based, so the first column will be represented as a 0 in the indices sequence.
* All values in the indices sequence will be integers from 0 and up.
* All test cases will have an indices sequence of one or more integers.
* Ignore indices that map to a column that doesn't exist.
* If all the values in the indices array do NOT map to any existing column, return an empty string `""`.
The columns of the result must be ordered and not repeated.
## Examples:
```
csv, indices => expected
"1,2,3\n4,5,6", [0, 1] => "1,2\n4,5"
"1,2\n3,4\n5,6", [5, 6, 7] => ""
"a,b,c,d,e\n1,2,3,4,5\nf,g,h,i,j", [1, 3, 5, 7] => "b,d\n2,4\ng,i"
``` | algorithms | def csv_columns(csv, indices):
indices = sorted(set(indices))
lines = csv . splitlines()
result = []
for line in lines:
values = line . split(',')
result . append(',' . join(values[i] for i in indices if i < len(values)))
return '\n' . join(result). strip()
| Grab CSV Columns | 5276c0f3f4bfbd5aae0001ad | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5276c0f3f4bfbd5aae0001ad | 5 kyu |
Something is wrong with our Warrior class. All variables should initialize properly and the attack method is not working as expected.
If properly set, it should correctly calculate the damage after an attack (if the attacker position is == to the block position of the defender: no damage; otherwise, the defender gets 10 damage if hit "high" or 5 damage if hit "low". If no block is set, the defender takes 5 **extra** damage.
For some reason, the health value is not being properly set. The following shows an example of this code being used:
```javascript
var ninja = new Warrior('Ninja');
var samurai = new Warrior('Samurai');
ninja.block = Position.high;
samurai.attack(ninja, Position.low);
// ninja.health should == 95
```
```python
ninja = Warrior('Hanzo Hattori')
samurai = Warrior('Ryōma Sakamoto')
samurai.block = 'l'
ninja.attack(samurai, 'h')
# samurai.health should be 90 now
```
```ruby
ninja = Warrior('Hanzo Hattori')
samurai = Warrior('Ryoma Sakamoto')
samurai.block = 'l'
ninja.attack(samurai, 'h')
# samurai.health should be 90 now
```
The warrios must be able to fight to the bitter end, and good luck to the most skilled!
Notice that health can't be below 0: once hit to 0 health, a warrior attribute `deceased` becomes `true`; if hit again, the `zombie` attribute becomes `true` too! | bug_fixes | Position = {'high': 'h', 'low': 'l'}
class Warrior ():
def __init__(self, name):
self . name = name
self . health = 100
self . block = ""
self . deceased = False
self . zombie = False
def attack(self, enemy, position):
damage = 0
if enemy . block != position:
damage += 10 if position == 'h' else 5
if enemy . block == "":
damage += 5
enemy . set_health(enemy . health - damage)
def set_health(self, new_health):
self . health = max(0, new_health)
if self . health == 0:
if not self . deceased:
self . deceased = True
else:
self . zombie = True
| Ninja vs Samurai: Attack + Block | 517b2bcf8557c200b8000015 | [
"Debugging"
] | https://www.codewars.com/kata/517b2bcf8557c200b8000015 | 5 kyu |
The test fixture I use for this kata is pre-populated.
It will compare your guess to a random number generated using:
```ruby
(Kernel::rand() * 100 + 1).floor
```
```javascript
Math.floor(Math.random() * 100 + 1)
```
```python
randint(1,100)
```
```php
rand(1, 100)
```
```csharp
new Random().Next(1, 100 + 1);
```
You can pass by relying on luck or skill but try not to rely on luck.
"The power to define the situation is the ultimate power." - Jerry Rubin
Good luck! | games | from random import randint, seed
seed(1)
guess = randint(1, 100)
seed(1)
| Don't rely on luck. | 5268af3872b786f006000228 | [
"Games",
"Puzzles"
] | https://www.codewars.com/kata/5268af3872b786f006000228 | 6 kyu |
Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string.
Note:
* **Empty string** values should be ignored.
* **Empty arrays** or **null/nil/None** values being passed into the method should result in an empty string being returned.
Example: **(Input --> output)**
```
['ninja', 'samurai', 'ronin'] --> "ninja, samurai and ronin"
['ninja', '', 'ronin'] --> "ninja and ronin"
[] -->""
``` | algorithms | def format_words(words):
# reject falsey words
if not words:
return ""
# ignoring empty strings
words = [word for word in words if word]
number_of_words = len(words)
if number_of_words <= 2:
# corner cases:
# 1) list with empty strings
# 2) list with one non-empty string
# 3) list with two non-empty strings
joiner = " and " if number_of_words == 2 else ""
return joiner . join(words)
return ", " . join(words[: - 1]) + " and " + words[- 1]
| Format words into a sentence | 51689e27fe9a00b126000004 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/51689e27fe9a00b126000004 | 6 kyu |
Just a simple sorting usage. Create a function that returns the elements of the input-array / list sorted in lexicographical order. | reference | def sortme(names):
return sorted(names)
| Sort arrays - 1 | 51f41b98e8f176e70d0002a8 | [
"Sorting",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/51f41b98e8f176e70d0002a8 | 7 kyu |
Write a function that determines whether the passed in sequences are similar. Similar means they contain the same elements, and the same number of occurrences of elements.
``` javascript
var arr1 = [1, 2, 2, 3, 4],
arr2 = [2, 1, 2, 4, 3],
arr3 = [1, 2, 3, 4],
arr4 = [1, 2, 3, "4"]
```
``` python
arr1 = [1, 2, 2, 3, 4]
arr2 = [2, 1, 2, 4, 3]
arr3 = [1, 2, 3, 4]
arr4 = [1, 2, 3, "4"]
```
``` javascript
arraysSimilar(arr1, arr2); // Should equal true
arraysSimilar(arr2, arr3); // Should equal false
arraysSimilar(arr3, arr4); // Should equal false
```
``` python
arrays_similar(arr1, arr2) # Should equal true
arrays_similar(arr2, arr3) # Should equal false
arrays_similar(arr3, arr4) # Should equal false
```
| algorithms | from collections import Counter
def arrays_similar(seq1, seq2):
return Counter(seq1) == Counter(seq2)
| Arrays Similar | 51e704f2d8dbace389000279 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/51e704f2d8dbace389000279 | 6 kyu |
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.
[Modern Roman numerals](https://en.wikipedia.org/wiki/Roman_numerals#Standard_form) are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.
## Example:
```
"MM" -> 2000
"MDCLXVI" -> 1666
"M" -> 1000
"CD" -> 400
"XC" -> 90
"XL" -> 40
"I" -> 1
```
## Help:
```
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
```
*Courtesy of rosettacode.org*
| algorithms | def solution(roman):
dict = {
"M": 1000,
"D": 500,
"C": 100,
"L": 50,
"X": 10,
"V": 5,
"I": 1
}
last, total = 0, 0
for c in list(roman)[:: - 1]:
if last == 0:
total += dict[c]
elif last > dict[c]:
total -= dict[c]
else:
total += dict[c]
last = dict[c]
return total
| Roman Numerals Decoder | 51b6249c4612257ac0000005 | [
"Algorithms"
] | https://www.codewars.com/kata/51b6249c4612257ac0000005 | 6 kyu |
The following code was thought to be working properly, however when the code tries to access the age of the person instance it fails.
```ruby
person = Person.new('Yukihiro', 'Matsumoto', 47)
puts person.full_name
puts person.age
```
```python
person = Person('Yukihiro', 'Matsumoto', 47)
print(person.full_name)
print(person.age)
```
For this exercise you need to fix the code so that it works correctly.
Note: the order of the person's full name is first name and last name. | bug_fixes | class Person ():
def __init__(self, first_name, last_name, age):
self . first_name = first_name
self . last_name = last_name
self . age = age
@ property
def full_name(self):
return f' { self . first_name } { self . last_name } '
| Person Class Bug | 513f887e484edf3eb3000001 | [
"Debugging",
"Object-oriented Programming"
] | https://www.codewars.com/kata/513f887e484edf3eb3000001 | 7 kyu |
Write a function that flattens an `Array` of `Array` objects into a flat `Array`. Your function must only do one level of flattening.
```javascript
flatten([1,2,3]) // => [1,2,3]
flatten([[1,2,3],["a","b","c"],[1,2,3]]) // => [1,2,3,"a","b","c",1,2,3]
flatten([[[1,2,3]]]) // => [[1,2,3]]
```
```coffeescript
flatten [1,2,3] # => [1,2,3]
flatten [[1,2,3],["a","b","c"],[1,2,3]] # => [1,2,3,"a","b","c",1,2,3]
flatten [[[1,2,3]]] # => [[1,2,3]]
```
```ruby
flatten [1,2,3] # => [1,2,3]
flatten [[1,2,3],["a","b","c"],[1,2,3]] # => [1,2,3,"a","b","c",1,2,3]
flatten [[[1,2,3]]] # => [[1,2,3]]
```
```python
flatten [1,2,3] # => [1,2,3]
flatten [[1,2,3],["a","b","c"],[1,2,3]] # => [1,2,3,"a","b","c",1,2,3]
flatten [[[1,2,3]]] # => [[1,2,3]]
``` | reference | def flatten(lst):
r = []
for x in lst:
if type(x) is list:
r . extend(x)
else:
r . append(x)
return r
| Flatten | 5250a89b1625e5decd000413 | [
"Functional Programming",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5250a89b1625e5decd000413 | 7 kyu |
In this kata we mix some tasty fruit juice. We can add some components with certain amounts. Sometimes we pour out a bit of our juice. Then we want to find out, which concentrations our fruit juice has.
Example:
* You take an empty jar for your juice
* Whenever the jar is empty, the concentrations are always 0
* Now you add 200 units of apple juice
* And then you add 200 units of banana juice
* Now the concentration of apple juice is 0.5 (50%)
* Then you pour out 200 units
* The concentration of apple juice is still 50%
* Then you add 200 units of apple juice again
* Now the concentration of apple juice is 0.75, while the concentration of banana juice is only 0.25 (300 units apple juice + 100 units banana juice)
Complete the functions in order to provide this functionality. The test code for the example above can be found in the test fixture. | algorithms | from collections import defaultdict
class Jar ():
def __init__(self):
self . amount = 0
self . juices = defaultdict(int)
def add(self, amount, kind):
self . amount += amount
self . juices[kind] += amount
def pour_out(self, amount):
memo = self . amount
self . amount -= amount
for juice in self . juices:
self . juices[juice] *= self . amount / memo
def get_total_amount(self):
return self . amount
def get_concentration(self, kind):
return kind in self . juices and self . juices[kind] / self . amount
| The Fruit Juice | 5264603df227072e6500006d | [
"Object-oriented Programming",
"Algorithms"
] | https://www.codewars.com/kata/5264603df227072e6500006d | 5 kyu |
Round any given number to the closest 0.5 step
I.E.
```
solution(4.2) = 4
solution(4.3) = 4.5
solution(4.6) = 4.5
solution(4.8) = 5
```
Round **up** if number is as close to previous and next 0.5 steps.
```
solution(4.75) == 5
``` | reference | def solution(n):
return round(2 * n) / 2
| Round by 0.5 steps | 51f1342c76b586046800002a | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/51f1342c76b586046800002a | 6 kyu |
Write a function named `numbers`.
```if:python
function should return `True` if all the parameters it is passed are of the integer type or float type. Otherwise, the function should return `False`.
```
```if:javascript
function should return True if all parameters are of the Number type.
```
```if:coffeescript
function should return True if all parameters are of the Number type. otherwise return False
```
The function should accept any number of parameters.
Example usage:
```python
numbers(1, 4, 3, 2, 5); # True
numbers(1, "a", 3); # False
numbers(1, 3, None); # False
numbers(1.23, 5.6, 3.2) # True
```
```coffeescript
numbers(1, 4, 3, 2, 5); // true
numbers(1, "a", 3); // false
numbers(1, 3, NaN) // true
```
```javascript
numbers(1, 4, 3, 2, 5); // true
numbers(1, "a", 3); // false
numbers(1, 3, NaN); // true
``` | reference | def numbers(* args):
return all(type(a) in (int, float) for a in args)
| For the sake of argument | 5258b272e6925db09900386a | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5258b272e6925db09900386a | 7 kyu |
You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that _"the"_ is doubled in the first sentence of this description?
As as aS you can see, it's not easy to spot those errors, especially if words differ in case, like _"as"_ at the beginning of this sentence.
Write a function that counts the number of sections repeating the same word (case insensitive). The occurence of two or more equal words next after each other counts as one.
## Examples
```
"dog cat" --> 0
"dog DOG cat" --> 1
"apple dog cat" --> 0
"pineapple apple dog cat" --> 0
"apple apple dog cat" --> 1
"apple dog apple dog cat" --> 0
"dog dog DOG dog dog dog" --> 1
"dog dog dog dog cat cat" --> 2
"cat cat dog dog cat cat" --> 3
``` | reference | def count_adjacent_pairs(st):
words = st . lower(). split(' ')
currentWord = None
count = 0
for i, word in enumerate(words):
if i + 1 < len(words):
if word == words[i + 1]:
if word != currentWord:
currentWord = word
count += 1
else:
currentWord = None
return count
| Adjacent repeated words in a string | 5245a9138ca049e9a10007b8 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5245a9138ca049e9a10007b8 | 6 kyu |
This time the input is a sequence of course-ids that are formatted in the following way:
```ruby
name-yymm
```
The return of the function shall first be sorted by <strong>yymm</strong>, then by the name (which varies in length). | algorithms | def sort_me(courses):
return sorted(courses, key=lambda c: c . split('-')[:: - 1])
| Sort arrays - 3 | 51f42b1de8f176db5a0002ae | [
"Sorting",
"Arrays",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/51f42b1de8f176db5a0002ae | 5 kyu |
Implement a function which behaves like the uniq command in UNIX.
It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance.
Example:
```
["a", "a", "b", "b", "c", "a", "b", "c"] => ["a", "b", "c", "a", "b", "c"]
``` | algorithms | from itertools import groupby
def uniq(seq):
return [k for k, _ in groupby(seq)]
| uniq (UNIX style) | 52249faee9abb9cefa0001ee | [
"Arrays",
"Filtering",
"Algorithms"
] | https://www.codewars.com/kata/52249faee9abb9cefa0001ee | 6 kyu |
Write a function that accepts a string, and returns true if it is in the form of a phone number. <br/>Assume that any integer from 0-9 in any of the spots will produce a valid phone number.<br/>
Only worry about the following format:<br/>
(123) 456-7890 (don't forget the space after the close parentheses) <br/> <br/>
Examples:
```
"(123) 456-7890" => true
"(1111)555 2345" => false
"(098) 123 4567" => false
```
| algorithms | def validPhoneNumber(phoneNumber):
import re
return bool(re . match(r"^(\([0-9]+\))? [0-9]+-[0-9]+$", phoneNumber))
| Valid Phone Number | 525f47c79f2f25a4db000025 | [
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/525f47c79f2f25a4db000025 | 6 kyu |
Complete the function that takes a non-negative integer, and returns a list of non-negative integer pairs whose values - when squared - sum to the given integer.
For example, given the parameter `25`, the function should return the two pairs `[0, 5]` and `[3, 4]` because `0^2 + 5^2 = 25` and `3^2 + 4^2 = 25`.
Return the pairs in ascending order, so e.g. `[[0, 5], [3, 4]]` **not** `[[5, 0], [3, 4]]` or `[[3, 4], [0, 5]]`, etc.
If the given value cannot be expressed as the sum of two squares, return an empty array.
Note:
The upper bound of the parameter value will be `2,147,483,647`
<!--
Requirements:
* The return value should be an array of pairs (nested arrays) of non-negative integers in any order.
* `[5, 0]` and `[0, 5]` are the same. Do not list the same pair twice.
-->
## Examples
```
0 --> [ [0, 0] ]
1 --> [ [0, 1] ]
2 --> [ [1, 1] ]
3 --> []
4 --> [ [0, 2] ]
5 --> [ [1, 2] ]
25 --> [ [0, 5], [3, 4] ]
325 --> [ [1, 18], [6, 17], [10, 15] ]
``` | algorithms | import math
def all_squared_pairs(n):
answers = []
for i in range(int(math . sqrt(n / 2.0) + 1)):
newsqr = math . sqrt(n - i * * 2)
if newsqr % 1 == 0:
answers . append([i, newsqr])
return answers
| Sum of (Two) Squares | 52217066578afbcc260002d0 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/52217066578afbcc260002d0 | 5 kyu |
Write a function which will accept a sequence of numbers and calculate the variance for the sequence.
The variance for a set of numbers is found by subtracting the mean from every value, squaring the results, adding them all up and dividing by the number of elements.
For example, in pseudo code, to calculate the variance for `[1, 2, 2, 3]`.
```
mean = (1 + 2 + 2 + 3) / 4
=> 2
variance = ((1 - 2)^2 + (2 - 2)^2 + (2-2)^2 + (3 - 2)^2) / 4
=> 0.5
```
```if:javascript,coffeescript
The results are tested after being rounded to 4 decimal places using Javascript's toFixed method.
```
```if:cobol,haskell
Results are tested to a relative error of `1e-8`.
```
```if:python
Results are tested to a relative error of `1e-4`.
```
| algorithms | from statistics import pvariance as variance
| Calculate Variance | 5266fba01283974e720000fa | [
"Statistics",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5266fba01283974e720000fa | 5 kyu |
We need prime numbers and we need them now!
Write a method that takes a maximum bound and returns all primes up to and including the maximum bound.
For example,
```
11 => [2, 3, 5, 7, 11]
``` | algorithms | def prime(num):
primes = []
sieve = [x for x in range(2, num + 1)]
while sieve:
n = sieve[0]
sieve = [x for x in sieve if x % n != 0]
primes . append(n)
return primes
| (Ready for) Prime Time | 521ef596c106a935c0000519 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/521ef596c106a935c0000519 | 5 kyu |
# Background:
You're working in a number zoo, and it seems that one of the numbers has gone missing!
Zoo workers have no idea what number is missing, and are too incompetent to figure it out, so they're hiring you to do it for them.
In case the zoo loses another number, they want your program to work regardless of how many numbers there are in total.
___
## Task:
Write a function that takes a shuffled list of unique numbers from `1` to `n` with one element missing (which can be any number including `n`). Return this missing number.
**Note**: huge lists will be tested.
## Examples:
```
[1, 3, 4] => 2
[1, 2, 3] => 4
[4, 2, 3] => 1
``` | algorithms | def find_missing_number(a):
n = len(a) + 1
return n * (n + 1) / / 2 - sum(a)
| Number Zoo Patrol | 5276c18121e20900c0000235 | [
"Algorithms",
"Performance",
"Mathematics"
] | https://www.codewars.com/kata/5276c18121e20900c0000235 | 6 kyu |
We'll create a function that takes in two parameters:
* a sequence (length and types of items are irrelevant)
* a function (value, index) that will be called on members of the sequence and their index. The function will return either true or false.
Your function will iterate through the members of the sequence in order until the provided function returns true; at which point your function will return that item's **index**.
If the function given returns false for all members of the sequence, your function should return -1.
```javascript
var trueIfEven = function(value, index) { return (value % 2 === 0) };
findInArray([1,3,5,6,7], trueIfEven) // should === 3
```
```python
true_if_even = lambda value, index: value % 2 == 0
find_in_array([1,3,5,6,7], true_if_even) # --> 3
```
```groovy
isEven = { value, index -> value % 2 == 0 }
Kata.findInArray([1,3,5,6,7], isEven) == 3
```
```ruby
true_if_even = lambda { |value, index| value.even? }
find_in_array([1,3,5,6,7], true_if_even) # --> 3
```
| reference | def find_in_array(seq, predicate):
for index, value in enumerate(seq):
if predicate(value, index):
return index
return - 1
| Find within array | 51f082ba7297b8f07f000001 | [
"Arrays",
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/51f082ba7297b8f07f000001 | 6 kyu |
The following code is not giving the expected results. Can you debug what the issue is?
The following is an example of data that would be passed in to the function.
```javascript
var data = [
{name: 'Joe', age: 20},
{name: 'Bill', age: 30},
{name: 'Kate', age: 23}
]
getNames(data) // should return ['Joe', 'Bill', 'Kate']
```
```csharp
public class Person
{
public int Age;
public string Name;
public Person(string name = "John", int age = 21)
{
Age = age;
Name = name;
}
}
Person[] data = new Person[]
{
new Person("Joe", 20),
new Person("Bill", 30),
new Person("Kate", 23)
};
Kata.GetNames(data) => new string[] {"Joe", "Bill", "Kate"};
```
```clojure
(def data [
{:name "Joe" :age 20}
{:name "Bill" :age 30}
{:name "Kate" :age 23}
])
(get-names data) ; should return ["Joe" "Bill" "Kate"]
```
```python
data = [
{'name': 'Joe', 'age': 20},
{'name': 'Bill', 'age': 30},
{'name': 'Kate', 'age': 23}
]
get_names(data) # should return ['Joe', 'Bill', 'Kate']
```
| bug_fixes | def itemgetter(item):
return item['name']
def get_names(data):
return list(map(itemgetter, data))
| getNames() | 514a677421607afc99000002 | [
"Debugging"
] | https://www.codewars.com/kata/514a677421607afc99000002 | 7 kyu |
```if:javascript
JavaScript Arrays support a filter function (starting in JavaScript 1.6). Use the filter functionality to complete the function given.
```
```if:csharp
Starting with .NET Framework 3.5, C# supports a `Where` (in the `System.Linq` namespace) method which allows a user to filter arrays based on a predicate. Use the `Where` method to complete the function given.
`Enumerable.Where` documentation:
https://msdn.microsoft.com/en-us/library/bb534803(v=vs.110).aspx
```
```if:python
In Python, there is a built-in filter function that operates similarly to JS's filter. For more information on how to use this function, visit https://docs.python.org/3/library/functions.html#filter
```
```if:haskell
Given list of integers return even integers on that list.
```
The solution would work like the following:
```javascript
getEvenNumbers([2,4,5,6]) // should == [2,4,6]
```
```csharp
Kata.GetEvenNumbers(new int[] {2, 4, 5, 6}) => new int[] {2, 4, 6}
```
```crystal
get_even_numbers([2,4,5,6]) => [2,4,6]
```
```r
get_even_numbers(c(2,4,5,6)) => c(2,4,6)
```
```julia
getevennumbers([2,4,5,6]) => [2,4,6]
```
```coffeescript
getEvenNumbers([2,4,5,6]) => [2,4,6]
```
```python
get_even_numbers([2,4,5,6]) => [2,4,6]
```
```ruby
get_even_numbers([2,4,5,6]) => [2,4,6]
```
```cpp
get_even_numbers({2,4,5,6}) => {2,4,6}
```
```haskell
getEvenNumbers [2,4,5,6] => [2,4,6]
``` | reference | def get_even_numbers(arr):
return [x for x in arr if x % 2 == 0]
| JavaScript Array Filter | 514a6336889283a3d2000001 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/514a6336889283a3d2000001 | 7 kyu |
Please write a function that will take a string as input and return a hash. The string will be formatted as such. The key will always be a symbol and the value will always be an integer.
```ruby
"a=1, b=2, c=3, d=4"
```
```javascript
"a=1, b=2, c=3, d=4"
```
```python
"a=1, b=2, c=3, d=4"
```
This string should return a hash that looks like
```ruby
{ :a => 1, :b => 2, :c => 3, :d => 4}
```
```javascript
{ 'a': 1, 'b': 2, 'c': 3, 'd': 4}
```
```python
{ 'a': 1, 'b': 2, 'c': 3, 'd': 4}
``` | algorithms | from re import findall
def str_to_hash(st):
return {i: int(j) for i, j in findall(r'(\w+)=(\d+)', st)}
| Turn String Input into Hash | 52180ce6f626d55cf8000071 | [
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/52180ce6f626d55cf8000071 | 6 kyu |
Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values.
```
Three 1's => 1000 points
Three 6's => 600 points
Three 5's => 500 points
Three 4's => 400 points
Three 3's => 300 points
Three 2's => 200 points
One 1 => 100 points
One 5 => 50 point
```
A single die can only be counted once in each roll. For example, a given "5" can only count as part of a
triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll.
Example scoring
```
Throw Score
--------- ------------------
5 1 3 4 1 250: 50 (for the 5) + 2 * 100 (for the 1s)
1 1 1 3 1 1100: 1000 (for three 1s) + 100 (for the other 1)
2 4 4 5 4 450: 400 (for three 4s) + 50 (for the 5)
```
~~~if:python
Note: your solution must not modify the input list.
~~~
~~~if:csharp,javascript
Note: your solution must not modify the input array.
~~~
~~~if-not:csharp,javascript,python
In some languages, it is possible to mutate the input to the function. This is something that you should never do. If you mutate the input, you will not be able to pass all the tests.
~~~ | algorithms | def score(dice):
sum = 0
counter = [0, 0, 0, 0, 0, 0]
points = [1000, 200, 300, 400, 500, 600]
extra = [100, 0, 0, 0, 50, 0]
for die in dice:
counter[die - 1] += 1
for (i, count) in enumerate(counter):
sum += (points[i] if count >= 3 else 0) + extra[i] * (count % 3)
return sum
| Greed is Good | 5270d0d18625160ada0000e4 | [
"Algorithms"
] | https://www.codewars.com/kata/5270d0d18625160ada0000e4 | 5 kyu |
# Seagull Snapshot Festival
The town of Landgull is celebrating its annual Seagull Snapshot Festival, and you've recently developed an obsession with seagulls, so it's the perfect oportunity to take some nice pictures of your favourite animal.
Your camera looks like this:
```[[ x ]]```
The view of the sea without a seagull looks like this:
```..·.···...·.·.·...···.·..·```
The view of the sea with a seagull over it looks like this:
```..·.···..seagull..···.·..·```
Once you've taken a picture of the seagull, it should look like this.
```..·.···[[seaxull]]···.·..·```
# Your goal
We'll provide a nice view with (at most) one seagull in it. Your goal is to take a snapshot of the seagull, if there's any.
Your camera can't step outside of the field of view, but seagulls may be partially outside of it. If they are, just catch as much of the seagull as possible (i.e. place your camera right at the edge, even if the seagull is not centred within it).
If the scene is too thin or there's no seagull in it, just wait until next time (i.e. return the same view without placing a camera on top of it). | games | import re
CAM = r"[[\1x\2]]"
def snapshot(s):
return re . sub("^..(...).(...)..", CAM, s) if re . search("^.?[seagul]", s) else \
re . sub("..(...).(...)..$", CAM, s) if re . search("[seagul].?$", s) else \
re . sub("..(sea)g(ull)..", CAM, s)
| Seagull Snapshot Festival Obsession | 663fe90a04bdcc6db4c091b9 | [
"Strings"
] | https://www.codewars.com/kata/663fe90a04bdcc6db4c091b9 | 6 kyu |
### Task
Complete function `howManyStep` that accept two number `a` and `b` (`0 < a <= b`).
You need turn `a` into `b`.
The rules is only can double (`a=a*2`) or plus 1 (`a=a+1`). return the shortest step.
### Examples
```javascript
howManyStep(1,10) === 4
// 1+1=2, 2*2=4, 4+1=5, 5*2=10
howManyStep(1,17) === 5
// 1*2=2, 2*2=4, 4*2=8, 8*2=16, 16+1=17
howManyStep(1,64) === 6
// 1*2=2, 2*2=4, 4*2=8, 8*2=16, 16*2=32, 32*2=64
howManyStep(1,63) === 10
howManyStep(50,100) === 1
howManyStep(51,100) === 49
howManyStep(100,100) === 0
``` | games | def how_many_step(a, b):
steps = 0
while a < b:
if (b % 2) == 0 and (b / / 2) >= a:
b / /= 2
else:
b -= 1
steps += 1
return steps
| T.T.T.19: How many steps are required to turn A into B? | 57a42ef9e298a72d710002aa | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/57a42ef9e298a72d710002aa | 6 kyu |
# Problem Statement: Destroying Card Houses
Sam has constructed a row of n card houses, numbered from 1 to n from left to right.
Now, Sam wants to destroy all the card houses. To do this, he will place a fan to the left of the first card house, creating wind directed towards the card houses with a strength equal to a positive integer X.
If the strength of the wind exceeds the resilience of the i-th card house, it will fall onto the next card house, reducing its resilience by a(i). If the resilience of the next card house is less than a(i), its resilience will become 0. The wind will pass through each card house from left to right one by one. If a card house falls, the resilience of the next card house will decrease before the wind reaches it. Find the minimum wind strength needed for all card houses to be destroyed.
# Explaining that part:
- When the strength of the wind is the same as the house,
the house is destroyed but doesn't fall to the next house. Meaning, that the next house is not affected by the current house.
- When the wind is bigger than the house, the house will fall to the next house,
reducing the strength of the next house by the current house's strength.
- **Wind doesn't go through buildings. When a house breaks, it “stays in place” and therefore it takes + wind to knock it down so the wind can pass through.**
# Examples:
- ```For the array [2, 5, 1, 3, 6], the minimum wind strength needed is 4.```
The resilience of the first card house is **2**. It falls onto the second card house, reducing its resilience to **5-2=3**. The second card house falls onto the third one, reducing its resilience to **0**. The third card house falls onto the fourth one, reducing its resilience to **3-0=3**. The fourth card house falls onto the fifth one, reducing its resilience to **6-3=3**. Since the resilience of the fifth card house is less than the wind strength, it falls.
It can be shown that with a lower wind strength, not all card houses will fall.
| algorithms | def min_wind_strength(strengths, b=0):
w = max(b := max(s - b, 0) for s in strengths) if strengths else 0
return w + (w != b)
| Destroying Card Houses | 6639f697af402f18dc322f5f | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/6639f697af402f18dc322f5f | 6 kyu |
```if-not:sql
Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).
```
```if:sql
Given a database of first and last IPv4 addresses, calculate the number of addresses between them (including the first one, excluding the last one).
## Input
~~~
---------------------------------
| Table | Column | Type |
|--------------+--------+-------|
| ip_addresses | id | int |
| | first | text |
| | last | text |
---------------------------------
~~~
## Output
~~~
-------------------------
| Column | Type |
|-------------+---------|
| id | int |
| ips_between | bigint |
-------------------------
~~~
```
All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.
___
## Examples
```
* With input "10.0.0.0", "10.0.0.50" => return 50
* With input "10.0.0.0", "10.0.1.0" => return 256
* With input "20.0.0.10", "20.0.1.0" => return 246
``` | algorithms | from ipaddress import ip_address
def ips_between(start, end):
return int(ip_address(end)) - int(ip_address(start))
| Count IP Addresses | 526989a41034285187000de4 | [
"Algorithms"
] | https://www.codewars.com/kata/526989a41034285187000de4 | 5 kyu |