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 |
---|---|---|---|---|---|---|---|
In this kata you have to write a method to verify the validity of IPv4 addresses.
Example of valid inputs:
"1.1.1.1"
"127.0.0.1"
"255.255.255.255"
Example of invalid input:
"1444.23.9"
"153.500.234.444"
"-12.344.43.11" | bug_fixes | from ipaddress import ip_address
def ipValidator(address):
try:
ip_address(address)
return True
except ValueError:
return False
| IPv4 Validator | 57193694938fcdfe3a001dd7 | [
"Fundamentals",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/57193694938fcdfe3a001dd7 | 7 kyu |
# Fix the bug in Filtering method
The method is supposed to remove even numbers from the list and return a list that contains the odd numbers.
However, there is a bug in the method that needs to be resolved. | bug_fixes | def kata_13_december(lst):
return [item for item in lst if item & 1]
| Filtering even numbers (Bug Fixes) | 566dc566f6ea9a14b500007b | [
"Fundamentals",
"Debugging"
] | https://www.codewars.com/kata/566dc566f6ea9a14b500007b | 8 kyu |
# The museum of incredibly dull things
The museum of incredibly dull things wants to get rid of some exhibits. Miriam, the interior architect, comes up with a plan to remove the most boring exhibits. She gives them a rating, and then removes the one with the lowest rating.
However, just as she finished rating all exhibits, she's off to an important fair, so she asks you to write a program that tells her the ratings of the exhibits after removing the lowest one. Fair enough.
# Task
Given an array of integers, remove the smallest value. **<span style="color:red">Do not mutate the original array/list.</span>** If there are multiple elements with the same value, remove the one with the lowest index. If you get an empty array/list, return an empty array/list.
Don't change the order of the elements that are left.
### Examples
```
* Input: [1,2,3,4,5], output = [2,3,4,5]
* Input: [5,3,2,1,4], output = [5,3,2,4]
* Input: [2,2,1,2,1], output = [2,2,2,1]
``` | reference | def remove_smallest(numbers):
a = numbers[:]
if a:
a . remove(min(a))
return a
| Remove the minimum | 563cf89eb4747c5fb100001b | [
"Lists",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/563cf89eb4747c5fb100001b | 7 kyu |
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`.
`[10, 343445353, 3453445, 3453545353453]` should return `3453455`.
| reference | def sum_two_smallest_numbers(numbers):
return sum(sorted(numbers)[: 2])
| Sum of two lowest positive integers | 558fc85d8fd1938afb000014 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/558fc85d8fd1938afb000014 | 7 kyu |
You are given an array(list) `strarr` of strings and an integer `k`. Your task is to return the **first** longest string
consisting of k **consecutive** strings taken in the array.
#### Examples:
```
strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2
Concatenate the consecutive strings of strarr by 2, we get:
treefoling (length 10) concatenation of strarr[0] and strarr[1]
folingtrashy (" 12) concatenation of strarr[1] and strarr[2]
trashyblue (" 10) concatenation of strarr[2] and strarr[3]
blueabcdef (" 10) concatenation of strarr[3] and strarr[4]
abcdefuvwxyz (" 12) concatenation of strarr[4] and strarr[5]
Two strings are the longest: "folingtrashy" and "abcdefuvwxyz".
The first that came is "folingtrashy" so
longest_consec(strarr, 2) should return "folingtrashy".
In the same way:
longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"
```
n being the length of the string array, if `n = 0` or `k > n` or `k <= 0` return "" (return `Nothing` in Elm, "nothing" in Erlang).
#### Note
consecutive strings : follow one after another without an interruption | reference | def longest_consec(strarr, k):
result = ""
if k > 0 and len(strarr) >= k:
for index in range(len(strarr) - k + 1):
s = '' . join(strarr[index: index + k])
if len(s) > len(result):
result = s
return result
| Consecutive strings | 56a5d994ac971f1ac500003e | [
"Fundamentals"
] | https://www.codewars.com/kata/56a5d994ac971f1ac500003e | 6 kyu |
Be u(n) a sequence beginning with:
```
u[1] = 1, u[2] = 1, u[3] = 2, u[4] = 3, u[5] = 3, u[6] = 4,
u[7] = 5, u[8] = 5, u[9] = 6, u[10] = 6, u[11] = 6, u[12] = 8,
u[13] = 8, u[14] = 8, u[15] = 10, u[16] = 9, u[17] = 10, u[18] = 11,
u[19] = 11, u[20] = 12, u[21] = 12, u[22] = 12, u[23] = 12 etc...
```
- How is`u[8]` calculated?
We have `u[7] = 5` and `u[6] = 4`. These numbers tell us that we have to go backwards from index `8` to index `8 - 5 = 3` and to index `8 - 4 = 4` so to index `3` and `4`.
``` u[3] = 2``` and ```u[4] = 3``` hence ```u[8] = u[3] + u[4] = 2 + 3 = 5```.
- Another example: let us calculate `u[13]`. At indexes `12` and `11` we have `8` and `6`. Going backwards of `8` and `6` from `13` we get indexes `13 - 8 = 5` and `13 - 6 = 7`.
``` u[5] = 3``` and ``` u[7] = 5``` so ``` u[13] = u[5] + u[7] = 3 + 5 = 8``` .
#### Task
- 0) Express u(n) as a function of n, u[n - 1], u[n - 2]. (not tested).
- 1) Given two numbers `n, k (integers > 2)` write the function `length_sup_u_k(n, k) or lengthSupUK or length-sup-u-k` returning the number of terms `u[i] >= k` with `1 <= i <= n`.
If we look above we can see that between `u[1]` and `u[23]` we have four `u[i]` greater or equal to `12`: `length_sup_u_k(23, 12) => 4`
- 2) Given `n (integer > 2)` write the function `comp(n)` (`cmp` in COBOL) returning the number of times where a term of `u` is less than its **predecessor** up to and including u[n].
#### Examples:
```
u(900) => 455 (not tested)
u(90000) => 44337 (not tested)
length_sup_u_k(23, 12) => 4
length_sup_u_k(50, 10) => 35
length_sup_u_k(500, 100) => 304
comp(23) => 1 (since only u(16) < u(15))
comp(100) => 22
comp(200) => 63
```
#### Note: Shell
Shell tests only `lengthSupUk` | reference | from itertools import islice, count
def u1():
a = {1: 1, 2: 1}
yield a[1]
yield a[2]
for n in count(3):
a[n] = a[n - a[n - 1]] + a[n - a[n - 2]]
yield a[n]
def length_sup_u_k(n, k):
return len(list(filter(lambda x: x >= k, islice(u1(), 1, n))))
def comp(n):
return sum(k1 < k0 for k0, k1 in zip(list(islice(u1(), 1, n)), list(islice(u1(), 2, n))))
| Fibo akin | 5772382d509c65de7e000982 | [
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5772382d509c65de7e000982 | 5 kyu |
You are given an array of integers. Implement a function which creates a complete binary tree from the array (*complete* meaning that every level of the tree, except possibly the last, is completely filled).
The elements of the array are to be taken left-to-right, and put into the tree top-to-bottom, left-to-right.
For example, given the array `[17, 0, -4, 3, 15]` you should create the following tree:
```
17
/ \
0 -4
/ \
3 15
```
A tree node type is preloaded for you:
```java
class TreeNode {
TreeNode left;
TreeNode right;
int value;
TreeNode(int value, TreeNode left, TreeNode right) {
this.value = value;
this.left = left;
this.right = right;
}
TreeNode(int value) {
this(value, null, null);
}
@Override
public boolean equals(Object other) {
... // Already implemented for you and used in test cases
}
...
}
```
```csharp
class TreeNode {
public TreeNode left;
public TreeNode right;
public int value;
public TreeNode(int value, TreeNode left, TreeNode right)
{
this.value = value;
this.left = left;
this.right = right;
}
public TreeNode(int value)
{
this.value = value;
}
public override bool Equals(Object other)
{
... // Already implemented for you and used in test cases
}
...
}
```
```cpp
class TreeNode
{
public:
int value;
TreeNode* left;
TreeNode* right;
TreeNode(int value, TreeNode* left = nullptr, TreeNode* right = nullptr)
: value{ value }, left{ left }, right{ right } {}
bool operator==(const TreeNode& rhs) const
{
... // Already implemented for you and used in test cases
}
... // You may assume the destructor is implemented.
};
```
```javascript
var TreeNode = function(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
};
```
```c
typedef struct TreeNode {
struct TreeNode *left, *right;
int value;
} TreeNode;
```
```python
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
```
```haskell
data TreeNode = None | Node TreeNode Int TreeNode
```
```rust
#[derive(Debug, PartialEq)]
pub struct TreeNode {
pub value: i32,
pub left: Option<Box<TreeNode>>,
pub right: Option<Box<TreeNode>>,
}
impl TreeNode {
// This is just convenience so you don't have to `Box` everywhere.
pub fn new(value: i32, left: Option<TreeNode>, right: Option<TreeNode>) -> Self {
Self {
value,
left: left.map(|n| Box::new(n)),
right: right.map(|n| Box::new(n)),
}
}
}
// Note: you can pretty-print TreeNode with {:#?}
```
This kata is part of [fun with trees](https://www.codewars.com/collections/fun-with-trees) series:
* [Fun with trees: max sum](https://www.codewars.com/kata/57e5279b7cf1aea5cf000359)
* [Fun with trees: array to tree](https://www.codewars.com/kata/57e5a6a67fbcc9ba900021cd)
* [Fun with trees: is perfect](https://www.codewars.com/kata/57dd79bff6df9b103b00010f) | algorithms | from preloaded import Node
def array_to_tree(arr, i=0):
if i >= len(arr):
return None
return Node(arr[i], array_to_tree(arr, 2 * i + 1), array_to_tree(arr, 2 * i + 2))
| Fun with trees: array to tree | 57e5a6a67fbcc9ba900021cd | [
"Trees",
"Arrays",
"Binary Trees",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/57e5a6a67fbcc9ba900021cd | 5 kyu |
John and his wife Ann have decided to go to Codewars. On the first day Ann will do one kata and John - he wants to know how it is working - 0 kata.
Let us call `a(n)` - and `j(n)` - the number of katas done by Ann - and John - at day `n`. We have `a(0) = 1` and in the same manner `j(0) = 0`.
They have chosen the following rules:
- On day `n` the number of katas done by Ann should be `n` minus the number of katas done by John at day `t`, `t` being equal to the number of katas done
by Ann herself at day `n - 1`
- On day `n` the number of katas done by John should be `n` minus the number of katas done by Ann at day `t`, `t` being equal to the number of katas done
by John himself at day `n - 1`
Whoops! I think they need to lay out a little clearer exactly what there're getting themselves into!
## Could you write:
- functions `ann(n)` and `john(n)` that return the **list** of the number of katas Ann/John does on the first `n` days;
- functions `sum_ann(n)` and `sum_john(n)` that return the **total** number of katas done by Ann/John on the first `n` days
```if:shell,fortran
#### Note:
functions `ann` and `john` are not tested
```
## Examples:
```
john(11) --> [0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6]
ann(6) --> [1, 1, 2, 2, 3, 3]
sum_john(75) --> 1720
sum_ann(150) --> 6930
```
```if:shell
shell: sumJohnAndAnn has two parameters ->
- first one : n (number of days, $1)
- second one : which($2) ->
- 1 for getting John's sum
- 2 for getting Ann's sum.
See "Sample Tests"
```
#### Note:
Keep an eye on performance. | algorithms | def j_n(n):
j = [0]
a = [1]
for i in range(1, n):
j . append((i - a[j[i - 1]]))
a . append((i - j[a[i - 1]]))
return j, a
def john(n):
return j_n(n)[0]
def ann(n):
return j_n(n)[1]
def sum_john(n):
return sum(john(n))
def sum_ann(n):
return sum(ann(n))
| John and Ann sign up for Codewars | 57591ef494aba64d14000526 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/57591ef494aba64d14000526 | 5 kyu |
A **perfect binary tree** is a binary tree in which all interior nodes have two children and all leaves have the same depth or same level.
You are given a class called TreeNode.
Implement the method `isPerfect` which determines if a given tree denoted by its root node is perfect.
Note: **TreeNode** class contains helper methods for tree creation, which might be handy for your solution. Feel free to update those methods, but make sure you keep their signatures intact (since they are used from within test cases).
**You can (and should) add more tests to validate your solution, since not all cases are covered in the example test cases.**
This kata is part of [fun with trees](https://www.codewars.com/collections/fun-with-trees) series:
* [Fun with trees: max sum](https://www.codewars.com/kata/57e5279b7cf1aea5cf000359)
* [Fun with trees: array to tree](https://www.codewars.com/kata/57e5a6a67fbcc9ba900021cd)
* [Fun with trees: is perfect](https://www.codewars.com/kata/57dd79bff6df9b103b00010f) | algorithms | from preloaded import TreeNode
def is_perfect(tree: TreeNode) - > bool:
def check_lvl(n: int, lvl: list[TreeNode]):
return not lvl or len(lvl) == n and check_lvl(
2 * n, [x for node in lvl for x in (node . left, node . right) if x]
)
return check_lvl(1, [tree] if tree else [])
| Fun with trees: is perfect | 57dd79bff6df9b103b00010f | [
"Trees",
"Recursion",
"Binary Trees",
"Binary Search Trees",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/57dd79bff6df9b103b00010f | 5 kyu |
You are given a binary tree. Implement a function that returns the maximum sum of a route from root to leaf.
For example, given the following tree:
```
17
/ \
3 -10
/ / \
2 16 1
/
13
```
The function should return `23`, since `17 -> -10 -> 16` is the route from root to leaf with the maximum sum.
Return `0` if the tree is empty.
Please note that you are not to find the best possible *route* in the tree, but the best possible route *from root to leaf*, e.g. for the following tree, you cannot skip the leaves and return `5 + 10 = 15`: the expected answer is `5 + 4 + -60 = -51`
```
5
/ \
4 10
/ \ /
-80 -60 -90
```
A tree node type is preloaded for you:
```java
class TreeNode {
TreeNode left;
TreeNode right;
int value;
...
}
```
```csharp
class TreeNode
{
public TreeNode left;
public TreeNode right;
public int value;
...
}
```
```cpp
class TreeNode
{
public:
TreeNode* left;
TreeNode* right;
int value;
...
};
```
```c
typedef struct TreeNode {
int value;
struct TreeNode *left, *right;
} TreeNode;
```
```javascript
class TreeNode {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
```
```haskell
data TreeNode = None | Node TreeNode Int TreeNode
```
```scala
case class TreeNode(
value: Int,
left: Option[TreeNode] = None,
right: Option[TreeNode] = None
)
```
```python
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
```
```rust
#[derive(Debug)]
pub struct TreeNode {
pub value: i32,
pub left: Option<Box<TreeNode>>,
pub right: Option<Box<TreeNode>>,
}
// Note: you can pretty-print trees with {:#?}
```
This kata is part of [fun with trees](https://www.codewars.com/collections/fun-with-trees) series:
* [Fun with trees: max sum](https://www.codewars.com/kata/57e5279b7cf1aea5cf000359)
* [Fun with trees: array to tree](https://www.codewars.com/kata/57e5a6a67fbcc9ba900021cd)
* [Fun with trees: is perfect](https://www.codewars.com/kata/57dd79bff6df9b103b00010f) | algorithms | from preloaded import TreeNode
def max_sum(root: TreeNode) - > int:
if root is None:
return 0
elif root . left is None:
return root . value + max_sum(root . right)
elif root . right is None:
return root . value + max_sum(root . left)
else:
return root . value + max(max_sum(root . left), max_sum(root . right))
| Fun with trees: max sum | 57e5279b7cf1aea5cf000359 | [
"Trees",
"Recursion",
"Binary Trees",
"Binary Search Trees",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/57e5279b7cf1aea5cf000359 | 6 kyu |
The Mormons are trying to find new followers and in order to do that they embark on missions.
Each time they go on a mission, each Mormon converts a fixed number of people (`reach`) into followers. This continues and every freshly converted Mormon as well as every original Mormon go on another mission and convert the same fixed number of people each. The process continues until they reach a predefined target number of followers (`target`).
Converted Mormons are unique so that there's no duplication amongst them.
Complete the function that calculates how many missions Mormons need to embark on, in order to reach their target. While each correct solution will pass, for more fun try to make a recursive function.
All inputs are valid positive integers.
## Examples
```python
starting_number = 10, reach = 3, target = 9 --> 0
# No missions needed because the number of followers already exceeds target
starting_number = 40, reach = 2, target = 120 --> 1
# Every mormon converts 2 people, so after 1 mission there are 40 + 80 = 120 mormons
starting_number = 20_000, reach = 2, target = 7_000_000_000 --> 12
# Mormons dominate the world after only 12 missions!
``` | reference | def mormons(starting_number, reach, target):
missions = 0
while starting_number < target:
starting_number += starting_number * reach
missions += 1
return missions
# def mormons(start, reach, target, missions=0):
# if start >= target:
# return missions
# return mormons(start + (start * reach), reach, target, missions + 1)
| The Book of Mormon | 58373ba351e3b615de0001c3 | [
"Fundamentals",
"Mathematics",
"Recursion"
] | https://www.codewars.com/kata/58373ba351e3b615de0001c3 | 6 kyu |
Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2:
```
1+1+1+1, 1+1+2, 2+2.
```
The order of coins does not matter:
```
1+1+2 == 2+1+1
```
Also, assume that you have an infinite amount of coins.
Your function should take an amount to change and an array of unique denominations for the coins:
```javascript
countChange(4, [1,2]) // => 3
countChange(10, [5,2,3]) // => 4
countChange(11, [5,7]) // => 0
```
```python
count_change(4, [1,2]) # => 3
count_change(10, [5,2,3]) # => 4
count_change(11, [5,7]) # => 0
```
```cpp
count_change(4, {1,2}) // => 3
count_change(10, {5,2,3}) // => 4
count_change(11, {5,7}) // => 0
```
```haskell
countChange 4 [1,2] -- => 3
countChange 10 [5,2,3] -- => 4
countChange 11 [5,7] -- => 0
```
```coffeescript
countChange(4, [1,2]) # => 3
countChange(10, [5,2,3]) # => 4
countChange(11, [5,7]) # => 0
```
```clojure
(count-change 4 [1,2]) ; => 3
(count-change 10 [5,2,3]) ; => 4
(count-change 11 [5,7]) ; => 0
```
```csharp
CountCombinations(4, new[] {1,2}) // => 3
CountCombinations(10, new[] {5,2,3}) // => 4
CountCombinations(11, new[] {5,7}) // => 0
``` | games | def count_change(money, coins):
if money < 0:
return 0
if money == 0:
return 1
if money > 0 and not coins:
return 0
return count_change(money - coins[- 1], coins) + count_change(money, coins[: - 1])
| Counting Change Combinations | 541af676b589989aed0009e7 | [
"Puzzles",
"Recursion"
] | https://www.codewars.com/kata/541af676b589989aed0009e7 | 4 kyu |
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
```javascript
sumStrings('1','2') // => '3'
```
```c
strsum("1", "2") /* => 3 */
```
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
I have removed the use of `BigInteger` and `BigDecimal` in java
Python:
your solution need to work with huge numbers (about a milion digits), converting to int will not work. | algorithms | def sum_strings(x, y):
l, res, carry = max(len(x), len(y)), "", 0
x, y = x . zfill(l), y . zfill(l)
for i in range(l - 1, - 1, - 1):
carry, d = divmod(int(x[i]) + int(y[i]) + carry, 10)
res += str(d)
return ("1" * carry + res[:: - 1]). lstrip("0") or "0"
| Sum Strings as Numbers | 5324945e2ece5e1f32000370 | [
"Strings",
"Big Integers",
"Algorithms"
] | https://www.codewars.com/kata/5324945e2ece5e1f32000370 | 4 kyu |
If you have completed the <a href="http://www.codewars.com/kata/tribonacci-sequence" target="_blank" title="Tribonacci sequence">Tribonacci sequence kata</a>, you would know by now that mister Fibonacci has at least a bigger brother. If not, give it a quick look to get how things work.
Well, time to expand the family a little more: think of a Quadribonacci starting with a signature of 4 elements and each following element is the sum of the 4 previous, a Pentabonacci (well *Cinquebonacci* would probably sound a bit more italian, but it would also sound really awful) with a signature of 5 elements and each following element is the sum of the 5 previous, and so on.
Well, guess what? You have to build a Xbonacci function that takes a **signature** of X elements *- and remember each next element is the sum of the last X elements -* and returns the first **n** elements of the so seeded sequence.
```
xbonacci {1,1,1,1} 10 = {1,1,1,1,4,7,13,25,49,94}
xbonacci {0,0,0,0,1} 10 = {0,0,0,0,1,1,2,4,8,16}
xbonacci {1,0,0,0,0,0,1} 10 = {1,0,0,0,0,0,1,2,3,6}
xbonacci {1,1} produces the Fibonacci sequence
``` | reference | def Xbonacci(signature, n):
output, x = signature[: n], len(signature)
while len(output) < n:
output . append(sum(output[- x:]))
return output
| Fibonacci, Tribonacci and friends | 556e0fccc392c527f20000c5 | [
"Arrays",
"Lists",
"Number Theory",
"Fundamentals"
] | https://www.codewars.com/kata/556e0fccc392c527f20000c5 | 6 kyu |
Well met with Fibonacci bigger brother, AKA Tribonacci.
As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(
So, if we are to start our Tribonacci sequence with `[1, 1, 1]` as a starting input (AKA *signature*), we have this sequence:
```
[1, 1 ,1, 3, 5, 9, 17, 31, ...]
```
But what if we started with `[0, 0, 1]` as a signature? As starting with `[0, 1]` instead of `[1, 1]` basically *shifts* the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get:
```
[0, 0, 1, 1, 2, 4, 7, 13, 24, ...]
```
Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a **signature** array/list, returns **the first n elements - signature included** of the so seeded sequence.
Signature will always contain 3 numbers; n will always be a non-negative number; if `n == 0`, then return an empty array (except in C return NULL) and be ready for anything else which is not clearly specified ;)
If you enjoyed this kata more advanced and generalized version of it can be found in the <a href="http://www.codewars.com/kata/fibonacci-tribonacci-and-friends" target="_blank" title="Xbonacci sequence">Xbonacci kata</a>
*[Personal thanks to Professor <a href="https://www.coursera.org/instructor/jimfowler" target="_blank" title="Jim Fowler">Jim Fowler</a> on Coursera for his awesome classes that I really recommend to any math enthusiast and for showing me this mathematical curiosity too with his usual contagious passion :)]* | reference | def tribonacci(signature, n):
res = signature[: n]
for i in range(n - 3):
res . append(sum(res[- 3:]))
return res
| Tribonacci Sequence | 556deca17c58da83c00002db | [
"Number Theory",
"Arrays",
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/556deca17c58da83c00002db | 6 kyu |
Removed due to copyright infringement.
<!----
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single `100`, `50` or `25` dollar bill. An "Avengers" ticket costs `25 dollars`.
Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.
Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue?
Return `YES`, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return `NO`.
### Examples:
```csharp
Line.Tickets(new int[] {25, 25, 50}) // => YES
Line.Tickets(new int[] {25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
Line.Tickets(new int[] {25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```java
Line.Tickets(new int[] {25, 25, 50}) // => YES
Line.Tickets(new int[] {25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
Line.Tickets(new int[] {25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```python
tickets([25, 25, 50]) # => YES
tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```javascript
tickets([25, 25, 50]) // => YES
tickets([25, 100]) // => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```haskell
tickets [25, 25, 50] -- -> YES
tickets [25, 100] -- -> NO. Vasya will not have enough money to give change to 100 dollars
tickets [25, 25, 50, 50, 100] -- -> NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```cpp
tickets({25, 25, 50}) // => YES
tickets({25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
tickets({25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```go
Tickets([]int{25, 25, 50}) // => YES
Tickets([]int{25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
Tickets([]int{25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```fsharp
tickets [25; 25; 50] // => YES
tickets [25; 100] // => NO. Vasya will not have enough money to give change to 100 dollars
tickets [25; 25; 50; 50; 100] // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```ruby
tickets([25, 25, 50]) # => YES
tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```c
tickets(3, {25, 25, 50}) // => true
tickets(2, {25, 100}) // => false. Vasya will not have enough money to give change to 100 dollars
tickets(5, {25, 25, 50, 50, 100}) // => false. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
---> | reference | def tickets(people):
till = {100.0: 0, 50.0: 0, 25.0: 0}
for paid in people:
till[paid] += 1
change = paid - 25.0
for bill in (50, 25):
while (bill <= change and till[bill] > 0):
till[bill] -= 1
change -= bill
if change != 0:
return 'NO'
return 'YES'
| Vasya - Clerk | 555615a77ebc7c2c8a0000b8 | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Logic",
"Numbers",
"Games"
] | https://www.codewars.com/kata/555615a77ebc7c2c8a0000b8 | 6 kyu |
We've got a message from the **Librarian**. As usual there're many `o` and `k` in it and, as all codewarriors don't know "Ook" language we need that you translate this message.
**tip** : it seems traditional "Hello World!" would look like :
`Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk? Ok, Ooooo? Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!`
Your task is to implement a function `okkOokOo(okkOookk)`, that would take the `okkOookk` message as input and return a decoded human-readable string.
*eg*:
```javascript
okkOokOo('Ok, Ook, Ooo!') // -> 'H'
okkOokOo('Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!') // -> 'Hello'
okkOokOo('Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!') // -> 'World!'
```
```python
okkOokOo('Ok, Ook, Ooo!') # -> 'H'
okkOokOo('Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!') # -> 'Hello'
okkOokOo('Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!') # -> 'World!'
```
```coffeescript
okkOokOo('Ok, Ook, Ooo!') # -> 'H'
okkOokOo('Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!') # -> 'Hello'
okkOokOo('Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!') # -> 'World!'
```
```csharp
Kata.OkkOokOo("Ok, Ook, Ooo!"); // -> "H"
Kata.OkkOokOo("Ok, Ook, Ooo? Okk, Ook, Ok? Okk, Okk, Oo? Okk, Okk, Oo? Okk, Okkkk!"); // -> "Hello"
Kata.OkkOokOo("Ok, Ok, Okkk? Okk, Okkkk? Okkk, Ook, O? Okk, Okk, Oo? Okk, Ook, Oo? Ook, Ooook!"); // -> "World!"
``` | games | SCORE = {'O': '0', 'o': '0', 'k': '1'}
def okkOokOo(s):
return '' . join(chr(int('' . join(SCORE . get(a, '') for a in word), 2))
for word in s . split('?'))
| Ookkk, Ok, O? Ook, Ok, Ooo! | 55035eb47451fb61c0000288 | [
"Strings",
"Binary",
"Puzzles"
] | https://www.codewars.com/kata/55035eb47451fb61c0000288 | 5 kyu |
Coding decimal numbers with factorials is a way of writing out numbers
in a base system that depends on factorials, rather than powers of numbers.
In this system, the last digit is always `0` and is in base 0!. The digit before that is either `0 or 1` and is in base 1!. The digit before that is either `0, 1, or 2` and is in base 2!, etc.
More generally, the nth-to-last digit is always `0, 1, 2, ..., n` and is in base n!.
Read more about it at: http://en.wikipedia.org/wiki/Factorial_number_system
#### Example
The decimal number `463` is encoded as `"341010"`, because:
463 = 3Γ5! + 4Γ4! + 1Γ3! + 0Γ2! + 1Γ1! + 0Γ0!
If we are limited to digits `0..9`, the biggest number we can encode is 10!-1 (= 3628799). So we extend `0..9` with letters `A..Z`. With these 36 digits we can now encode numbers up to 36!-1 (= 3.72 Γ 10<sup>41</sup>)
#### Task
We will need two functions. The first one will receive a decimal number and return a string with the factorial representation.
~~~if:java
**Note:** the input number is at most a long.
~~~
The second one will receive a string with a factorial representation and produce the decimal representation.
Given numbers will always be positive.
| algorithms | from math import factorial
from itertools import dropwhile
DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
BASIS = [factorial(n) for n in range(len(DIGITS))]
def dec2FactString(nb):
representation = []
for b in reversed(BASIS):
representation . append(DIGITS[nb / / b])
nb %= b
return "" . join(dropwhile(lambda x: x == "0", representation))
def factString2Dec(string):
return sum(BASIS[i] * DIGITS . index(d) for i, d in enumerate(reversed(string)))
| Decimal to Factorial and Back | 54e320dcebe1e583250008fd | [
"Algorithms"
] | https://www.codewars.com/kata/54e320dcebe1e583250008fd | 5 kyu |
Removed due to copyright infringement.
<!---
Bob is preparing to pass IQ test. The most frequent task in this test is `to find out which one of the given numbers differs from the others`. Bob observed that one number usually differs from the others in **evenness**. Help Bob β to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.
`!` Keep in mind that your task is to help Bob solve a `real IQ test`, which means indexes of the elements start from `1 (not 0)`
## Examples:
```csharp
IQ.Test("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even
IQ.Test("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd
```
```javascript
iqTest("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even
iqTest("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd
```
```typescript
iqTest("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even
iqTest("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd
```
```ruby
iq_test("2 4 7 8 10") => 3 # Third number is odd, while the rest of the numbers are even
iq_test("1 2 1 1") => 2 # Second number is even, while the rest of the numbers are odd
```
```python
iq_test("2 4 7 8 10") => 3 # Third number is odd, while the rest of the numbers are even
iq_test("1 2 1 1") => 2 # Second number is even, while the rest of the numbers are odd
```
```rust
iq_test("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even
iq_test("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd
```
---> | reference | def iq_test(numbers):
e = [int(i) % 2 == 0 for i in numbers . split()]
return e . index(True) + 1 if e . count(True) == 1 else e . index(False) + 1
| IQ Test | 552c028c030765286c00007d | [
"Fundamentals",
"Logic"
] | https://www.codewars.com/kata/552c028c030765286c00007d | 6 kyu |
#### Once upon a time, on a way through the old wild *mountainous* west,β¦
β¦ a man was given directions to go from one point to another. The directions were "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too.
Going to one direction and coming back the opposite direction *right away* is a needless effort. Since this is the wild west, with dreadful weather and not much water, it's important to save yourself some energy, otherwise you might die of thirst!
#### How I crossed a *mountainous* desert the smart way.
The directions given to the man are, for example, the following (depending on the language):
```
["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"].
or
{ "NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST" };
or
[North, South, South, East, West, North, West]
```
You can immediately see that going "NORTH" and *immediately* "SOUTH" is not reasonable, better stay to the same place!
So the task is to give to the man a simplified version of the plan. A better plan in this case is simply:
```
["WEST"]
or
{ "WEST" }
or
[West]
```
#### Other examples:
In `["NORTH", "SOUTH", "EAST", "WEST"]`, the direction `"NORTH" + "SOUTH"` is going north and coming back *right away*.
The path becomes `["EAST", "WEST"]`, now `"EAST"` and `"WEST"` annihilate each other, therefore, the final result is `[]` (nil in Clojure).
In ["NORTH", "EAST", "WEST", "SOUTH", "WEST", "WEST"], "NORTH" and "SOUTH" are *not* directly opposite but they become directly opposite after the reduction of "EAST" and "WEST" so the whole path is reducible to ["WEST", "WEST"].
#### Task
Write a function `dirReduc` which will take an array of strings and returns an array of strings with the needless directions removed (W<->E or S<->N *side by side*).
- The Haskell version takes a list of directions with `data Direction = North | East | West | South`.
- The Clojure version returns nil when the path is reduced to nothing.
- The Rust version takes a slice of `enum Direction {North, East, West, South}`.
#### See more examples in "Sample Tests:"
#### Notes
- Not all paths can be made simpler.
The path ["NORTH", "WEST", "SOUTH", "EAST"] is not reducible. "NORTH" and "WEST", "WEST" and "SOUTH", "SOUTH" and "EAST" are not *directly* opposite of each other and can't become such. Hence the result path is itself : ["NORTH", "WEST", "SOUTH", "EAST"].
- if you want to translate, please ask before translating.
| reference | opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'}
def dirReduc(plan):
new_plan = []
for d in plan:
if new_plan and new_plan[- 1] == opposite[d]:
new_plan . pop()
else:
new_plan . append(d)
return new_plan
| Directions Reduction | 550f22f4d758534c1100025a | [
"Fundamentals"
] | https://www.codewars.com/kata/550f22f4d758534c1100025a | 5 kyu |
From Wikipedia:
"A divisibility rule is a shorthand way of determining whether a given integer is divisible by a fixed divisor without performing the division, usually by examining its digits."
When you divide the successive powers of `10` by `13` you get the following remainders of the integer divisions:
`1, 10, 9, 12, 3, 4` because:
```
10 ^ 0 -> 1 (mod 13)
10 ^ 1 -> 10 (mod 13)
10 ^ 2 -> 9 (mod 13)
10 ^ 3 -> 12 (mod 13)
10 ^ 4 -> 3 (mod 13)
10 ^ 5 -> 4 (mod 13)
```
(For "mod" you can see:
<https://en.wikipedia.org/wiki/Modulo_operation>)
Then the whole pattern repeats. Hence the following method:
Multiply
- the *right* most digit of the number with the *left* most number
in the sequence shown above,
- the second *right* most digit with the second *left* most digit of the number in the sequence.
The cycle goes on and you sum all these products. Repeat this process until the sequence of sums is **stationary**.
#### Example:
What is the remainder when `1234567` is divided by `13`?
```
7 6 5 4 3 2 1 (digits of 1234567 from the right)
Γ Γ Γ Γ Γ Γ Γ (multiplication)
1 10 9 12 3 4 1 (the repeating sequence)
```
Therefore following the method we get:
``` 7Γ1 + 6Γ10 + 5Γ9 + 4Γ12 + 3Γ3 + 2Γ4 + 1Γ1 = 178```
We repeat the process with the number 178:
`8x1 + 7x10 + 1x9 = 87`
and again with 87:
`7x1 + 8x10 = 87`
From now on the sequence is **stationary** (we always get `87`) and the remainder of `1234567` by `13` is
the same as the remainder of `87` by `13` ( i.e `9`).
#### Task:
Call `thirt` the function which processes this sequence of operations on an integer `n (>=0)`. `thirt` will return the **stationary** number.
`thirt(1234567)` calculates 178, then 87, then 87 and returns `87`.
`thirt(321)` calculates 48, 48 and returns `48`
| reference | array = [1, 10, 9, 12, 3, 4]
def thirt(n):
total = sum([int(c) * array[i % 6]
for i, c in enumerate(reversed(str(n)))])
if n == total:
return total
return thirt(total)
| A Rule of Divisibility by 13 | 564057bc348c7200bd0000ff | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/564057bc348c7200bd0000ff | 6 kyu |
Consider the following numbers (where `n!` is `factorial(n)`):
```
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
```
Which will win: `1 / n!` or `(1! + 2! + 3! + ... + n!)`?
Are these numbers going to `0` because of `1/n!` or to infinity due
to the sum of factorials or to another number?
## Task
Calculate `(1 / n!) * (1! + 2! + 3! + ... + n!)`
for a given `n`, where `n` is an integer greater or equal to `1`.
Your result should be within 10^-6 of the expected one.
## Remark
Keep in mind that factorials grow rather rapidly, and you need to handle large inputs.
## Hint
You could try to simplify the expression. | algorithms | def going(n):
s = 1.0
for i in range(2, n + 1):
s = s / i + 1
return int(s * 1e6) / 1e6
| Going to zero or to infinity? | 55a29405bc7d2efaff00007c | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/55a29405bc7d2efaff00007c | 5 kyu |
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infected `(i)`, those who have recovered `(r)`, and
those who are still susceptible `(s)` to get the disease.
We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations:
```
(1) s'(t) = -b * s(t) * i(t)
(2) i'(t) = b * s(t) * i(t) - a * i(t)
(3) r'(t) = a * i(t)
```
where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and
`s'(t), i'(t), r'(t)` the corresponding derivatives.
`b` and `a` are constants:
`b` is representing a number of contacts which can spread the disease and
`a` is a fraction of the infected that will recover.
We can transform equations `(1), (2), (3)` in finite differences
(https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation)
(http://www.codewars.com/kata/56347fcfd086de8f11000014)
```
(I) S[k+1] = S[k] - dt * b * S[k] * I[k]
(II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k])
(III) R[k+1] = R[k] + dt * I[k] *a
```
The interval `[0, tm]` will be divided in `n` small intervals of length `dt = tm/n`.
Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0`
Whatever S0 and I0, R0 (number of recovered at time 0) is always 0.
The function `epidemic` will return the maximum number of infected
as an *integer* (truncate to integer the result of max(I)).
#### Example:
```
tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41
epidemic(tm, n, s0, i0, b, a) --> 483
```
#### Notes:
- Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot.
![alternative text](http://i.imgur.com/xB6VSqzm.png)
| reference | def epidemic(tm, n, s, i, b, a):
def f(s, i, r):
dt = tm / n
for t in range(n):
s, i, r = s - dt * b * s * i, i + dt * (b * s * i - a * i), r + dt * i * a
yield i
return int(max(f(s, i, 0)))
| Disease Spread | 566543703c72200f0b0000c9 | [
"Fundamentals"
] | https://www.codewars.com/kata/566543703c72200f0b0000c9 | 6 kyu |
This is a follow-up from my previous Kata which can be found here: http://www.codewars.com/kata/5476f4ca03810c0fc0000098
This time, for any given linear sequence, calculate the function [f(x)] and return it as a function in Javascript or Lambda/Block in Ruby.
For example:
```javascript
getFunction([0, 1, 2, 3, 4])(5) => 5
getFunction([0, 3, 6, 9, 12])(10) => 30
getFunction([1, 4, 7, 10, 13])(20) => 61
```
```ruby
get_function([0, 1, 2, 3, 4]).call(5) => 5
get_function([0, 3, 6, 9, 12]).call(10) => 30
get_function([1, 4, 7, 10, 13]).call(20) => 61
```
```python
get_function([0, 1, 2, 3, 4])(5) => 5
get_function([0, 3, 6, 9, 12])(10) => 30
get_function([1, 4, 7, 10, 13])(20) => 61
```
```csharp
GetFunction(new[] { 0, 1, 2, 3, 4 })(5) => 5
GetFunction(new[] { 0, 3, 6, 9, 12 })(10) => 30
GetFunction(new[] { 1, 4, 7, 10, 13 })(20) => 61
```
```php
get_function([0, 1, 2, 3, 4])(5) // => 5
get_function([0, 3, 6, 9, 12])(10) // => 30
get_function([1, 4, 7, 10, 13])(20) // => 61
```
Assumptions for this kata are:
```
The sequence argument will always contain 5 values equal to f(0) - f(4).
The function will always be in the format "nx +/- m", 'x +/- m', 'nx', 'x' or 'm'
If a non-linear sequence simply return 'Non-linear sequence' for javascript, ruby, and python. For C#, throw an ArgumentException.
``` | reference | def get_function(sequence):
slope = sequence[1] - sequence[0]
for x in range(1, 5):
if sequence[x] - sequence[x - 1] != slope:
return "Non-linear sequence"
return lambda a: slope * a + sequence[0]
| Calculate the function f(x) for a simple linear sequence (Medium) | 54784a99b5339e1eaf000807 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/54784a99b5339e1eaf000807 | 6 kyu |
Write a method, that will get an integer array as parameter and will process every number from this array.
Return a new array with processing every number of the input-array like this:
If the number has an integer square root, take this, otherwise square the number.
#### Example
```
[4,3,9,7,2,1] -> [2,9,3,49,4,1]
```
#### Notes
The input array will always contain only positive numbers, and will never be empty or null.
~~~if:lambdacalc
#### Encodings
purity: `LetRec`
numEncoding: `Scott`
export constructors `Nil, Cons` and deconstructor `foldr` for your `List` encoding
~~~ | algorithms | def square_or_square_root(arr):
result = []
for x in arr:
root = x * * 0.5
if root . is_integer():
result . append(root)
else:
result . append(x * x)
return result
| To square(root) or not to square(root) | 57f6ad55cca6e045d2000627 | [
"Mathematics",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/57f6ad55cca6e045d2000627 | 8 kyu |
You need to write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:
As the input may have trailing spaces, you will also need to ignore unneccesary whitespace.
Example (**Input** --> **Output**)
```
"Hello World" --> "World Hello"
"Hi There." --> "There. Hi"
```
Happy coding!
| reference | def reverse(st):
# Your Code Here
return " " . join(st . split()[:: - 1])
| Reversing Words in a String | 57a55c8b72292d057b000594 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57a55c8b72292d057b000594 | 8 kyu |
You were given a string of integer temperature values. Create a function `lowest_temp(t)` and return the lowest value or `None/null/Nothing` if the string is empty. | reference | def lowest_temp(t):
return min((int(x) for x in t . split()), default=None)
| Temperature analysis I | 588e0f11b7b4a5b373000041 | [
"Fundamentals"
] | https://www.codewars.com/kata/588e0f11b7b4a5b373000041 | 7 kyu |
The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8.
It's easy to see that the sum of the perimeters of these squares is :
` 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80 `
Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:
![alternative text](http://i.imgur.com/EYcuB1wm.jpg)
#### Hint:
See Fibonacci sequence
#### Ref:
http://oeis.org/A000045
The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.
```
perimeter(5) should return 80
perimeter(7) should return 216
```
| algorithms | def fib(n):
a, b = 0, 1
for i in range(n + 1):
if i == 0:
yield b
else:
a, b = b, a + b
yield b
def perimeter(n):
return sum(fib(n)) * 4
| Perimeter of squares in a rectangle | 559a28007caad2ac4e000083 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/559a28007caad2ac4e000083 | 5 kyu |
The action of a Caesar cipher is to replace each plaintext letter (plaintext letters are from 'a' to 'z' or from 'A' to 'Z') with a different one a fixed number of places up or down the alphabet.
This program performs a variation of the Caesar shift. The shift increases by 1 for each **character** (on each iteration).
If the shift is initially 1, the first character of the message to be
encoded will be shifted by 1, the second character will be
shifted by 2, etc...
#### Coding: Parameters and return of function "movingShift"
param s: a string to be coded
param shift: an integer giving the initial shift
The function "movingShift" *first* codes the entire string and *then* returns an array of strings
containing the coded string in 5 parts (five parts
because, to avoid more risks, the coded message will be given to five
runners, one piece for each runner).
If possible the message will be equally divided by message length between the five runners. If this is not possible, parts 1 to 5 will have subsequently non-increasing lengths, such that parts 1 to 4 are at least as long as when evenly divided, but at most 1 longer. If the last part is the empty string this empty string must be shown in the resulting array.
For example, if the coded message has a length of 17 the five parts will have lengths of 4, 4, 4, 4, 1. The parts 1, 2, 3, 4 are evenly split and the last part of length 1 is shorter. If the length is 16 the parts will be of lengths 4, 4, 4, 4, 0. Parts 1, 2, 3, 4 are evenly split and the fifth runner will stay at home since his part is the empty string. If the length is 11, equal parts would be of length 2.2, hence parts will be of lengths 3, 3, 3, 2, 0.
You will also implement a "demovingShift" function with two parameters
#### Decoding: parameters and return of function "demovingShift"
1) an array of strings: s (possibly resulting from "movingShift", with 5 strings)
2) an int shift
"demovingShift" returns a string.
#### Example:
u = "I should have known that you would have a perfect answer for me!!!"
`movingShift(u, 1)` returns :
v = ["J vltasl rlhr ", "zdfog odxr ypw", " atasl rlhr p ", "gwkzzyq zntyhv", " lvz wp!!!"]
(quotes added in order to see the strings and the spaces, your program won't write these quotes, see Example Test Cases)
and `demovingShift(v, 1)` returns u.
#Ref:
Caesar Cipher : http://en.wikipedia.org/wiki/Caesar_cipher
| reference | from string import ascii_lowercase as abc, ascii_uppercase as ABC
from math import ceil
def _code(string, shift, mode):
return '' . join(
abc[(abc . index(c) + i * mode + shift) % len(abc)] if c in abc else
ABC[(ABC . index(c) + i * mode + shift) % len(ABC)] if c in ABC else c
for i, c in enumerate(string))
def moving_shift(string, shift):
encoded = _code(string, shift, 1)
cut = int(ceil(len(encoded) / 5.0))
return [encoded[i: i + cut] for i in range(0, 5 * cut, cut)]
def demoving_shift(arr, shift):
return _code('' . join(arr), - shift, - 1)
| First Variation on Caesar Cipher | 5508249a98b3234f420000fb | [
"Fundamentals",
"Ciphers",
"Strings"
] | https://www.codewars.com/kata/5508249a98b3234f420000fb | 5 kyu |
At a job interview, you are challenged to write an algorithm to check if a given string, `s`, can be formed from two other strings, `part1` and `part2`.
The restriction is that the characters in `part1` and `part2` should be in the same order as in `s`.
The interviewer gives you the following example and tells you to figure out the rest from the given test cases.
For example:
```
'codewars' is a merge from 'cdw' and 'oears':
s: c o d e w a r s = codewars
part1: c d w = cdw
part2: o e a r s = oears
``` | algorithms | def is_merge(s, part1, part2):
if not part1:
return s == part2
if not part2:
return s == part1
if not s:
return part1 + part2 == ''
if s[0] == part1[0] and is_merge(s[1:], part1[1:], part2):
return True
if s[0] == part2[0] and is_merge(s[1:], part1, part2[1:]):
return True
return False
| Merged String Checker | 54c9fcad28ec4c6e680011aa | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/54c9fcad28ec4c6e680011aa | 5 kyu |
In this kata you have to implement a base converter, which converts **positive integers** between arbitrary bases / alphabets. Here are some pre-defined alphabets:
```javascript
var Alphabet = {
BINARY: '01',
OCTAL: '01234567',
DECIMAL: '0123456789',
HEXA_DECIMAL: '0123456789abcdef',
ALPHA_LOWER: 'abcdefghijklmnopqrstuvwxyz',
ALPHA_UPPER: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
ALPHA: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
ALPHA_NUMERIC: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
};
```
```csharp
public class Alphabet
{
public const string BINARY = "01";
public const string OCTAL = "01234567";
public const string DECIMAL = "0123456789";
public const string HEXA_DECIMAL = "0123456789abcdef";
public const string ALPHA_LOWER = "abcdefghijklmnopqrstuvwxyz";
public const string ALPHA_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string ALPHA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string ALPHA_NUMERIC = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
```
```python
bin = '01'
oct = '01234567'
dec = '0123456789'
hex = '0123456789abcdef'
allow = 'abcdefghijklmnopqrstuvwxyz'
allup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
alphanum = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
```
```ruby
bin = '01'
oct = '01234567'
dec = '0123456789'
hex = '0123456789abcdef'
allow = 'abcdefghijklmnopqrstuvwxyz'
allup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
alphanum = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
```
```haskell
newtype Alphabet = Alphabet { getDigits :: [Char] } deriving (Show)
bin, oct, dec, hex, alphaLower, alphaUpper, alpha, alphaNumeric :: Alphabet
bin = Alphabet $ "01"
oct = Alphabet $ ['0'..'7']
dec = Alphabet $ ['0'..'9']
hex = Alphabet $ ['0'..'9'] ++ ['a'..'f']
alphaLower = Alphabet $ ['a'..'z']
alphaUpper = Alphabet $ ['A'..'Z']
alpha = Alphabet $ ['a'..'z'] ++ ['A'..'Z']
alphaNumeric = Alphabet $ ['0'..'9'] ++ ['a'..'z'] ++ ['A'..'Z']
```
```c
const char * bin = "01";
const char * oct = "01234567";
const char * dec = "0123456789";
const char * hex = "0123456789abcdef";
const char * allow = "abcdefghijklmnopqrstuvwxyz";
const char * alup = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char * alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char * alnum = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
```
The function `convert()` should take an input (string), the source alphabet (string) and the target alphabet (string). You can assume that the input value always consists of characters from the source alphabet. You don't need to validate it.
### Examples
```javascript
// convert between numeral systems
convert("15", Alphabet.DECIMAL, Alphabet.BINARY); // should return "1111"
convert("15", Alphabet.DECIMAL, Alphabet.OCTAL); // should return "17"
convert("1010", Alphabet.BINARY, Alphabet.DECIMAL); // should return "10"
convert("1010", Alphabet.BINARY, Alphabet.HEXA_DECIMAL); // should return "a"
// other bases
convert("0", Alphabet.DECIMAL, Alphabet.ALPHA); // should return "a"
convert("27", Alphabet.DECIMAL, Alphabet.ALPHA_LOWER); // should return "bb"
convert("hello", Alphabet.ALPHA_LOWER, Alphabet.HEXA_DECIMAL); // should return "320048"
convert("SAME", Alphabet.ALPHA_UPPER, Alphabet.ALPHA_UPPER); // should return "SAME"
```
```csharp
// convert between numeral systems
Convert("15", Alphabet.DECIMAL, Alphabet.BINARY); // should return "1111"
Convert("15", Alphabet.DECIMAL, Alphabet.OCTAL); // should return "17"
Convert("1010", Alphabet.BINARY, Alphabet.DECIMAL); // should return "10"
Convert("1010", Alphabet.BINARY, Alphabet.HEXA_DECIMAL); // should return "a"
// other bases
Convert("0", Alphabet.DECIMAL, Alphabet.ALPHA); // should return "a"
Convert("27", Alphabet.DECIMAL, Alphabet.ALPHA_LOWER); // should return "bb"
Convert("hello", Alphabet.ALPHA_LOWER, Alphabet.HEXA_DECIMAL); // should return "320048"
Convert("SAME", Alphabet.ALPHA_UPPER, Alphabet.ALPHA_UPPER); // should return "SAME"
```
```python
convert("15", dec, bin) ==> "1111"
convert("15", dec, oct) ==> "17"
convert("1010", bin, dec) ==> "10"
convert("1010", bin, hex) ==> "a"
convert("0", dec, alpha) ==> "a"
convert("27", dec, allow) ==> "bb"
convert("hello", allow, hex) ==> "320048"
```
```ruby
convert("15", dec, bin) # should return "1111"
convert("15", dec, oct) # should return "17"
convert("1010", bin, dec) # should return "10"
convert("1010", bin, hex) # should return "a"
convert("0", dec, alpha) # should return "a"
convert("27", dec, allow) # should return "bb"
convert("hello", allow, hex) # should return "320048"
```
```haskell
convert dec bin "15" `shouldBe` "1111"
convert dec oct "15" `shouldBe` "17"
convert bin dec "1010" `shouldBe` "10"
convert bin hex "1010" `shouldBe` "a"
convert dec alpha "0" `shouldBe` "a"
convert dec alphaLower "27" `shouldBe` "bb"
convert alphaLower hex "hello" `shouldBe` "320048"
```
```c
convert("15", dec, bin) // should return "1111"
convert("15", dec, oct) // should return "17"
convert("1010", bin, dec) // should return "10"
convert("1010", bin, hex) // should return "a"
convert("0", dec, alpha) // should return "a"
convert("27", dec, allow) // should return "bb"
convert("hello", allow, hex) // should return "320048"
```
Additional Notes:
* The maximum input value can always be encoded in a number without loss of precision in JavaScript. In Haskell, intermediate results will probably be too large for `Int`.
* The function must work for any arbitrary alphabets, not only the pre-defined ones
* You don't have to consider negative numbers | algorithms | def convert(input, source, target):
base_in = len(source)
base_out = len(target)
acc = 0
out = ''
for d in input:
acc *= base_in
acc += source . index(d)
while acc != 0:
d = target[acc % base_out]
acc = acc / base_out
out = d + out
return out if out else target[0]
| Base Conversion | 526a569ca578d7e6e300034e | [
"Strings",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/526a569ca578d7e6e300034e | 6 kyu |
# Task
Given a string representing a simple fraction `x/y`, your function must return a string representing the corresponding [mixed fraction](http://en.wikipedia.org/wiki/Fraction_%28mathematics%29#Mixed_numbers) in the following format:
```[sign]a b/c```
where `a` is integer part and `b/c` is irreducible proper fraction. There must be exactly one space between `a` and `b/c`. Provide `[sign]` only if negative (and non zero) and only at the beginning of the number (both integer part and fractional part must be provided absolute).
If the `x/y` equals the integer part, return integer part only. If integer part is zero, return the irreducible proper fraction only. In both of these cases, the resulting string must not contain any spaces.
Division by zero should raise an error (preferably, the standard zero division error of your language).
# Value ranges
* -10 000 000 < ```x``` < 10 000 000
* -10 000 000 < ```y``` < 10 000 000
# Examples
* Input: `42/9`, expected result: `4 2/3`.
* Input: `6/3`, expedted result: `2`.
* Input: `4/6`, expected result: `2/3`.
* Input: `0/18891`, expected result: `0`.
* Input: `-10/7`, expected result: `-1 3/7`.
* Inputs `0/0` or `3/0` must raise a zero division error.
# Note
Make sure not to modify the input of your function in-place, it is a bad practice. | reference | def gcd(a, b): return b if not a else gcd(b % a, a)
def sign(a): return a if a == 0 else abs(a) / a
def mixed_fraction(s):
a, b = [int(x) for x in s . split("/")]
if int(b) == 0:
raise ZeroDivisionError
d, m = divmod(abs(a), abs(b))
g = gcd(m, b)
s = "-" if sign(a) * sign(b) == - 1 else ""
a = str(d) if d != 0 else ""
b = "%i/%i" % (m / g, abs(b) / g) if m != 0 else ""
return s + " " . join([a, b]). strip() or "0"
| Simple fraction to mixed number converter | 556b85b433fb5e899200003f | [
"Fundamentals"
] | https://www.codewars.com/kata/556b85b433fb5e899200003f | 5 kyu |
Write a function named `first_non_repeating_letter`<sup>β </sup> that takes a string input, and returns the first character that is not repeated anywhere in the string.
For example, if given the input `'stress'`, the function should return `'t'`, since the letter *t* only occurs once in the string, and occurs first in the string.
As an added challenge, upper- and lowercase letters are considered the **same character**, but the function should return the correct case for the initial letter. For example, the input `'sTreSS'` should return `'T'`.
If a string contains *all repeating characters*, it should return an empty string (`""`);
<sup>β </sup> Note: the function is called `firstNonRepeatingLetter` for historical reasons, but your function should handle any Unicode character. | algorithms | def first_non_repeating_letter(string):
string_lower = string . lower()
for i, letter in enumerate(string_lower):
if string_lower . count(letter) == 1:
return string[i]
return ""
| First non-repeating character | 52bc74d4ac05d0945d00054e | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52bc74d4ac05d0945d00054e | 5 kyu |
The drawing below gives an idea of how to cut a given "true" rectangle into squares ("true" rectangle meaning that the two dimensions are different).
![alternative text](https://i.imgur.com/lk5vJ7sm.jpg)
Can you translate this drawing into an algorithm?
You will be given two dimensions
1. a positive integer length
2. a positive integer width
You will return a collection or a string (depending on the language; Shell bash, PowerShell, Pascal and Fortran return a string) with the size of each of the squares.
#### Examples in general form:
(depending on the language)
```
sqInRect(5, 3) should return [3, 2, 1, 1]
sqInRect(3, 5) should return [3, 2, 1, 1]
You can see examples for your language in **"SAMPLE TESTS".**
```
#### Notes:
- `lng == wdth` as a starting case would be an entirely different problem and the drawing is planned to be interpreted with `lng != wdth`. (See kata, Square into Squares. Protect trees! http://www.codewars.com/kata/54eb33e5bc1a25440d000891 for this problem).
When the initial parameters are so that `lng` == `wdth`, the solution `[lng]` would be the most obvious but not in the spirit of this kata so, in that case, return `None`/`nil`/`null`/`Nothing` **or**
return `{}` with C++, `Array()` with Scala, `[]` with Perl, Raku.
- In that case the returned structure of **C** will have its `sz` component equal to `0`.
- Return the string `"nil"` with Bash, PowerShell, Pascal and Fortran.
| games | def sqInRect(lng, wdth):
if lng == wdth:
return None
if lng < wdth:
wdth, lng = lng, wdth
res = []
while lng != wdth:
res . append(wdth)
lng = lng - wdth
if lng < wdth:
wdth, lng = lng, wdth
res . append(wdth)
return res
| Rectangle into Squares | 55466989aeecab5aac00003e | [
"Fundamentals",
"Geometry",
"Puzzles"
] | https://www.codewars.com/kata/55466989aeecab5aac00003e | 6 kyu |
Build Tower
---
Build a pyramid-shaped tower, as an array/list of strings, given a positive integer `number of floors`. A tower block is represented with `"*"` character.
For example, a tower with `3` floors looks like this:
```
[
" * ",
" *** ",
"*****"
]
```
And a tower with `6` floors looks like this:
```
[
" * ",
" *** ",
" ***** ",
" ******* ",
" ********* ",
"***********"
]
```
___
Go challenge [Build Tower Advanced](https://www.codewars.com/kata/57675f3dedc6f728ee000256) once you have finished this :)
| reference | def tower_builder(n):
return [("*" * (i * 2 - 1)). center(n * 2 - 1) for i in range(1, n + 1)]
| Build Tower | 576757b1df89ecf5bd00073b | [
"Strings",
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/576757b1df89ecf5bd00073b | 6 kyu |
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.
## Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (`*`) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (`\n`).
Return `null/nil/None/...` if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.
## Examples
A size 3 diamond:
```
*
***
*
```
...which would appear as a string of `" *\n***\n *\n"`
A size 5 diamond:
```
*
***
*****
***
*
```
...that is:
```
" *\n ***\n*****\n ***\n *\n"
```
| reference | def diamond(n):
if n < 0 or n % 2 == 0:
return None
result = "*" * n + "\n"
spaces = 1
n = n - 2
while n > 0:
current = " " * spaces + "*" * n + "\n"
spaces = spaces + 1
n = n - 2
result = current + result + current
return result
| Give me a Diamond | 5503013e34137eeeaa001648 | [
"Strings",
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/5503013e34137eeeaa001648 | 6 kyu |
Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently
they can be guessed due to common cultural references.
You can get your passphrases stronger by different means. One is the following:
choose a text in capital letters including or not digits and non alphabetic characters,
1. shift each letter by a given number but the transformed letter must be a letter (circular shift),
2. replace each digit by its complement to 9,
3. keep such as non alphabetic and non digit characters,
4. downcase each letter in odd position, upcase each letter in even position (the first character is in position 0),
5. reverse the whole result.
#### Example:
your text: "BORN IN 2015!", shift 1
1 + 2 + 3 -> "CPSO JO 7984!"
4 "CpSo jO 7984!"
5 "!4897 Oj oSpC"
With longer passphrases it's better to have a small and easy program.
Would you write it?
https://en.wikipedia.org/wiki/Passphrase | algorithms | def play_pass(s, n):
# Step 1, 2, 3
shiftText = ""
for char in s:
if char . isdigit():
shiftText += str(9 - int(char))
elif char . isalpha():
shifted = ord(char . lower()) + n
shiftText += chr(shifted) if shifted <= ord('z') else chr(shifted - 26)
else:
shiftText += char
# Step 4
caseText = ""
for i in range(len(shiftText)):
caseText += shiftText[i]. upper() if i % 2 == 0 else shiftText[i]. lower()
# Step 5
return caseText[:: - 1]
| Playing with passphrases | 559536379512a64472000053 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/559536379512a64472000053 | 6 kyu |
# Description
Middle Earth is about to go to war. The forces of good will have many battles with the forces of evil. Different races will certainly be involved. Each race has a certain `worth` when battling against others. On the side of good we have the following races, with their associated `worth`:
* Hobbits: 1
* Men: 2
* Elves: 3
* Dwarves: 3
* Eagles: 4
* Wizards: 10
On the side of evil we have:
* Orcs: 1
* Men: 2
* Wargs: 2
* Goblins: 2
* Uruk Hai: 3
* Trolls: 5
* Wizards: 10
Although weather, location, supplies and valor play a part in any battle, if you add up the worth of the side of good and compare it with the worth of the side of evil, the side with the larger worth will tend to win.
Thus, given the count of each of the races on the side of good, followed by the count of each of the races on the side of evil, determine which side wins.
# Input:
The function will be given two parameters. Each parameter will be a string of multiple integers separated by a single space. Each string will contain the count of each race on the side of good and evil.
The first parameter will contain the count of each race on the side of good in the following order:
* Hobbits, Men, Elves, Dwarves, Eagles, Wizards.
The second parameter will contain the count of each race on the side of evil in the following order:
* Orcs, Men, Wargs, Goblins, Uruk Hai, Trolls, Wizards.
All values are non-negative integers. The resulting sum of the worth for each side will not exceed the limit of a 32-bit integer.
# Output:
Return `"Battle Result: Good triumphs over Evil"` if good wins, `"Battle Result: Evil eradicates all trace of Good"` if evil wins, or `"Battle Result: No victor on this battle field"` if it ends in a tie.
| algorithms | def goodVsEvil(good, evil):
points_good = [1, 2, 3, 3, 4, 10]
points_evil = [1, 2, 2, 2, 3, 5, 10]
good = sum([int(x) * y for x, y in zip(good . split(), points_good)])
evil = sum([int(x) * y for x, y in zip(evil . split(), points_evil)])
result = 'Battle Result: '
if good < evil:
return result + 'Evil eradicates all trace of Good'
elif good > evil:
return result + 'Good triumphs over Evil'
else:
return result + 'No victor on this battle field'
| Good vs Evil | 52761ee4cffbc69732000738 | [
"Algorithms"
] | https://www.codewars.com/kata/52761ee4cffbc69732000738 | 6 kyu |
Common denominators
You will have a list of rationals in the form
```
{ {numer_1, denom_1} , ... {numer_n, denom_n} }
or
[ [numer_1, denom_1] , ... [numer_n, denom_n] ]
or
[ (numer_1, denom_1) , ... (numer_n, denom_n) ]
```
where all numbers are positive ints.
You have to produce a result in the form:
```
(N_1, D) ... (N_n, D)
or
[ [N_1, D] ... [N_n, D] ]
or
[ (N_1', D) , ... (N_n, D) ]
or
{{N_1, D} ... {N_n, D}}
or
"(N_1, D) ... (N_n, D)"
```
depending on the language (See Example tests) in which D is as small as possible and
```
N_1/D == numer_1/denom_1 ... N_n/D == numer_n,/denom_n.
```
#### Example:
```
convertFracs [(1, 2), (1, 3), (1, 4)] `shouldBe` [(6, 12), (4, 12), (3, 12)]
```
#### Note:
Due to the fact that the first translations were written long ago - more than 6 years - these first translations have only irreducible fractions.
Newer translations have some reducible fractions. To be on the safe side it is better to do a bit more work by simplifying fractions even if they don't have to be.
#### Note for Bash:
input is a string, e.g `"2,4,2,6,2,8"`
output is then `"6 12 4 12 3 12"` | reference | import math
import functools
def convertFracts(lst):
def lcm(a, b): return abs(a * b) / / math . gcd(a, b)
tmp_list = list(map(lambda x: x[1], list(lst)))
lcm_num = functools . reduce(lcm, tmp_list)
return list(map(lambda x: [x[0] * lcm_num / / x[1], lcm_num], list(lst)))
| Common Denominators | 54d7660d2daf68c619000d95 | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/54d7660d2daf68c619000d95 | 5 kyu |
There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!
### input
```if-not:c
* customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* n: a positive integer, the number of checkout tills.
```
```if:c
* customers: a pointer to an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* customers_length: the length of the array that `customers` points to.
* n: a positive integer, the number of checkout tills.
```
### output
The function should return an integer, the total time required.
-------------------------------------------
## Important
**Please look at the examples and clarifications below, to ensure you understand the task correctly :)**
-------
### Examples
```javascript
queueTime([5,3,4], 1)
// should return 12
// because when there is 1 till, the total time is just the sum of the times
queueTime([10,2,3,3], 2)
// should return 10
// because here n=2 and the 2nd, 3rd, and 4th people in the
// queue finish before the 1st person has finished.
queueTime([2,3,10], 2)
// should return 12
```
```haskell
queueTime [5,3,4] 1
-- should return 12
-- because when there is 1 till, the total time is just the sum of the times
queueTime [10,2,3,3] 2
-- should return 10
-- because here n=2 and the 2nd, 3rd, and 4th people in the
-- queue finish before the 1st person has finished.
queueTime [2,3,10] 2
-- should return 12
```
```python
queue_time([5,3,4], 1)
# should return 12
# because when n=1, the total time is just the sum of the times
queue_time([10,2,3,3], 2)
# should return 10
# because here n=2 and the 2nd, 3rd, and 4th people in the
# queue finish before the 1st person has finished.
queue_time([2,3,10], 2)
# should return 12
```
```ruby
queue_time([5,3,4], 1)
# should return 12
# because when n=1, the total time is just the sum of the times
queue_time([10,2,3,3], 2)
# should return 10
# because here n=2 and the 2nd, 3rd, and 4th people in the
# queue finish before the 1st person has finished.
queue_time([2,3,10], 2)
# should return 12
```
```cpp
queueTime(std::vector<int>{5,3,4}, 1)
// should return 12
// because when n=1, the total time is just the sum of the times
queueTime(std::vector<int>{10,2,3,3}, 2)
// should return 10
// because here n=2 and the 2nd, 3rd, and 4th people in the
// queue finish before the 1st person has finished.
queueTime(std::vector<int>{2,3,10}, 2)
// should return 12
```
```fsharp
queueTime [5;3;4] 1
// should return 12
// because when there is 1 till, the total time is just the sum of the times
queueTime [10;2;3;3] 2
// should return 10
// because here n=2 and the 2nd, 3rd, and 4th people in the
// queue finish before the 1st person has finished.
queueTime [2;3;10] 2
// should return 12
```
```c
int customers1[] = {5, 3, 4};
int customers1_length = 3;
int n1 = 1;
queueTime(customers1, customers1_length, n1)
// should return 12
// because when n=1, the total time is just the sum of the times
int customers2[] = {10, 2, 3, 3};
int customers2_length = 4;
int n2 = 2;
queueTime(customers2, customers2_length, n2)
// should return 10
// because here n=2 and the 2nd, 3rd, and 4th people in the
// queue finish before the 1st person has finished.
int customers3[] = {2, 3, 10};
int customers3_length = 3;
int n3 = 2;
queueTime(customers3, customers3_length, n3)
// should return 12
```
```cobol
QueueTime [5,3,4] 1 => 12
* because when there is 1 till, the total time is just the sum of the times
QueueTime [10,2,3,3] 2 => 10
* because here n=2 and the 2nd, 3rd, and 4th people in the
* queue finish before the 1st person has finished.
QueueTime [2,3,10] 2 => 12
```
### Clarifications
* There is only ONE queue serving many tills, and
* The order of the queue NEVER changes, and
* The front person in the queue (i.e. the first element in the array/list) proceeds to a till as soon as it becomes free.
N.B. You should assume that all the test input will be valid, as specified above.
P.S. The situation in this kata can be likened to the more-computer-science-related idea of a thread pool, with relation to running multiple processes at the same time: https://en.wikipedia.org/wiki/Thread_pool
| reference | def queue_time(customers, n):
l = [0] * n
for i in customers:
l[l . index(min(l))] += i
return max(l)
| The Supermarket Queue | 57b06f90e298a7b53d000a86 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57b06f90e298a7b53d000a86 | 6 kyu |
You might know some pretty large perfect squares. But what about the NEXT one?
Complete the `findNextSquare` method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer.
If the argument is itself not a perfect square then return either `-1` or an empty value like `None` or `null`, depending on your language. You may assume the argument is non-negative.
**Examples:(Input --> Output)**
```
121 --> 144
625 --> 676
114 --> -1 since 114 is not a perfect square
```
| reference | def find_next_square(sq):
root = sq ** 0.5
if root.is_integer():
return (root + 1)**2
return -1 | Find the next perfect square! | 56269eb78ad2e4ced1000013 | [
"Algebra",
"Fundamentals"
] | https://www.codewars.com/kata/56269eb78ad2e4ced1000013 | 7 kyu |
Implement a function that accepts 3 integer values a, b, c. The function should return true if a triangle can be built with the sides of given length and false in any other case.
(In this case, all triangles must have surface greater than 0 to be accepted).
Examples:
```
Input -> Output
1,2,2 -> true
4,2,3 -> true
2,2,2 -> true
1,2,3 -> false
-5,1,3 -> false
0,2,3 -> false
1,2,9 -> false
```
| reference | def is_triangle(a, b, c):
return (a<b+c) and (b<a+c) and (c<a+b) | Is this a triangle? | 56606694ec01347ce800001b | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/56606694ec01347ce800001b | 7 kyu |
You throw a ball vertically upwards with an initial speed `v (in km per hour)`. The height `h` of the ball at each time `t`
is given by `h = v*t - 0.5*g*t*t` where `g` is Earth's gravity `(g ~ 9.81 m/s**2)`. A device is recording at every **tenth of second** the height of the ball.
For example with `v = 15 km/h` the device gets something of the following form:
`(0, 0.0), (1, 0.367...), (2, 0.637...), (3, 0.808...), (4, 0.881..) ...`
where the first number is the time in tenth of second and the second number the height in meter.
#### Task
Write a function `max_ball` with parameter `v (in km per hour)` that returns the `time in tenth of second`
of the maximum height recorded by the device.
#### Examples:
`max_ball(15) should return 4`
`max_ball(25) should return 7`
#### Notes
- Remember to convert the velocity from km/h to m/s or from m/s in km/h when necessary.
- The maximum height recorded by the device is not necessarily the maximum height reached by the ball. | reference | """
h = vt-0.5gt^2
let h = 0 [that is, when the ball has returned to the ground]
=> 0 = vt-0.5gt^2
=> 0.5gt^2 = vt
=> 0.5gt = v
=> t = 2v/g - the total time the ball is in the air.
=> t at max height = v/g
"""
def max_ball(v0):
return round(10*v0/9.81/3.6) | Ball Upwards | 566be96bb3174e155300001b | [
"Fundamentals"
] | https://www.codewars.com/kata/566be96bb3174e155300001b | 6 kyu |
Remember all those quadratic equations you had to solve by hand in highschool? Well, no more! You're going to solve all the quadratic equations you might ever[1] have to wrangle with in the future once and for all by coding up the [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula) to handle them automatically.
Write a function `quadratic_formula()` that takes three arguments, `a`, `b`, and `c` that represent the coefficients in a formula of the form ax^2 + bx + c = 0. Your function shoud return a list with two elements where each element is one of the two roots. If the formula produces a double root the result should be a list where both elements are that value.
~~~if:python
For example, `quadratic_formula(2, 16, 1)` should return the list `[-0.06299606299409444, -7.937003937005906]`.
~~~
~~~if:javascript
For example, `quadraticFormula(2, 16, 1)` should return the list `[-0.06299606299409444, -7.937003937005906]`.
~~~
The order of the roots is not important.
[1] Well, not _ever_ ever. You don't need to worry about getting quadratic equations with complex roots where you need the square root of a negative number. All the test cases will be for equations with real roots. | reference | from math import sqrt
def quadratic_formula(a, b, c):
delta = b * b - 4 * a *c
root1 = (-b - sqrt(delta)) / (2 * a)
root2 = (-b + sqrt(delta)) / (2 * a)
return [root1, root2] | Thinkful - Number Drills: Quadratic formula | 58635f1b2489549be50003f1 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/58635f1b2489549be50003f1 | 7 kyu |
John has some amount of money of which he wants to deposit a part `f0` to the bank at the beginning
of year `1`. He wants to withdraw each year for his living an amount `c0`.
Here is his banker plan:
- deposit `f0` at beginning of year 1
- his bank account has an interest rate of `p` percent per year, constant over the years
- John can withdraw each year `c0`, taking it whenever he wants in the year; he must take account of an inflation of `i` percent per year in order to keep his quality of living. `i` is supposed to stay constant over the years.
- all amounts <code>f<sub>0</sub></code>..<code>f<sub>n-1</sub></code>, <code>c<sub>0</sub></code>..<code>c<sub>n-1</sub></code> are truncated by the bank to their integral part
- Given <code>f<sub>0</sub></code>, `p`, <code>c<sub>0</sub></code>, `i`
the banker guarantees that John will be able to go on that way until the `nth` year.
#### Example:
```
f0 = 100000, p = 1 percent, c0 = 2000, n = 15, i = 1 percent
beginning of year 2 -> f1 = 100000 + 0.01*100000 - 2000 = 99000; c1 = c0 + c0*0.01 = 2020 (with inflation of previous year)
beginning of year 3 -> f2 = 99000 + 0.01*99000 - 2020 = 97970; c2 = c1 + c1*0.01 = 2040.20
(with inflation of previous year, truncated to 2040)
beginning of year 4 -> f3 = 97970 + 0.01*97970 - 2040 = 96909.7 (truncated to 96909);
c3 = c2 + c2*0.01 = 2060.4 (with inflation of previous year, truncated to 2060)
```
and so on...
John wants to know if the banker's plan is right or wrong.
Given parameters `f0, p, c0, n, i` build a function `fortune` which returns `true` if John can make a living until the `nth` year
and `false` if it is not possible.
#### Some cases:
```
fortune(100000, 1, 2000, 15, 1) -> True
fortune(100000, 1, 10000, 10, 1) -> True
fortune(100000, 1, 9185, 12, 1) -> False
For the last case you can find below the amounts of his account at the beginning of each year:
100000, 91815, 83457, 74923, 66211, 57318, 48241, 38977, 29523, 19877, 10035, -5
```
<pre><code>f<sub>11</sub> = -5 so he has no way to withdraw something for his living in year 12.</code></pre>
#### Note:
Don't forget to convert the percent parameters as percentages in the body of your function: if a parameter percent is 2 you have to convert it to 0.02. | algorithms | def fortune(f, p, c, n, i):
for _ in range(n - 1):
f = int(f * (100 + p) / 100 - c)
c = int(c * (100 + i) / 100)
if f < 0:
return False
return True
| Banker's Plan | 56445c4755d0e45b8c00010a | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/56445c4755d0e45b8c00010a | 6 kyu |
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
~~~if-not:factor
Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]
~~~
~~~if:factor
Ex: Input = `{ "Ryan" "Kieran" "Jason" "Yous" }`, Output = `{ "Ryan" "Yous" }`
~~~
i.e.
```haskell
friend ["Ryan", "Kieran", "Mark"] `shouldBe` ["Ryan", "Mark"]
```
```factor
{ "Ryan" "Kieran" "Mark" } friend -> { "Ryan" "Mark" }
```
Note: keep the original order of the names in the output. | reference | def friend(x):
return [f for f in x if len(f) == 4]
| Friend or Foe? | 55b42574ff091733d900002f | [
"Fundamentals"
] | https://www.codewars.com/kata/55b42574ff091733d900002f | 7 kyu |
This code does not execute properly. Try to figure out why. | bug_fixes | def multiply(a, b):
return a * b
| Multiply | 50654ddff44f800200000004 | [
"Debugging",
"Fundamentals"
] | https://www.codewars.com/kata/50654ddff44f800200000004 | 8 kyu |
#### Task
Allocate customers to hotel rooms based on their arrival and departure days. Each customer wants their own room, so two customers can stay in the same room only if the departure day of the first customer is earlier than the arrival day of the second customer. The number of rooms used should be minimized.
#### Input
A list of **n** customers, 1 <= **n** <= 1000. Each customer is represented by (arrival_day, departure_day), which are positive integers satisfying arrival_day <= departure_day.
#### Output
A list of size **n**, where element **i** indicates the room that customer **i** was allocated. Rooms are numbered **1,2, ..., k** for some **1 <= k <= n**. Any allocation that minimizes the number of rooms **k** is a valid solution.
#### Example:
Suppose customers is [(1,5), (2,4), (6,8), (7,7)]. <br>
Clearly customers 1 and 2 cannot get the same room. Customer 3 can use the some room as either of them, because they both leave before customer 3 arrives. Then customer 4 can be given the other room. <br>
So any of [1,2,1,2], [1,2,2,1], [2,1,2,1], [2,1,1,2] is a valid solution.
NOTE: The list of customers is not necessarily ordered by arrival_time.
##### Source: [CSES](https://cses.fi/problemset/task/1164)
##### Related kata:
[The Hotel with Infinite Rooms](https://www.codewars.com/kata/5b9cf881d6b09fc9ee0002b1) <br>
[Is room reserved?](https://www.codewars.com/kata/5ca8cb15d7f22c002a805b29)
| algorithms | def allocate_rooms(customers):
res = [0] * len(customers)
dep = [0] * len(customers)
for i, (a, d) in sorted(enumerate(customers), key=lambda x: x[1]):
n = next(r for r, d in enumerate(dep) if d < a)
dep[n] = d
res[i] = n + 1
return res
| Allocating Hotel Rooms | 6638277786032a014d3e0072 | [
"Sorting"
] | https://www.codewars.com/kata/6638277786032a014d3e0072 | 6 kyu |
This kata was created as a contender for the EPIC Challenge 2024.
## Background
It's your dream to have a magical wedding day, and you're willing to spend *every last penny on it* β while simultaneously planning for a stable retirement income.
## Task
Your monthly surplus income (i.e., income after all taxes and mandatory monthly costs) is `C` dollars (e.g., `C = $2,500`), and will remain so until your retirement. At the end of each month, you will invest the surplus income in your savings account with a certain rate of monthly return `r > 0` given in percentage (e.g., `r = 0.5` percent per month), growing with compound interest. Your savings account is initially empty.
You are planning to retire in `T` years (e.g., `T = 35`), and have calculated that upon retirement, you need minimum `S` dollars of savings to finance a stable retirement (e.g., `S = $3,000,000`).
You are also planning to have a wedding in `W` years (e.g., `W = 5`), with `1 <= W <= T`. *What is the largest amount of savings you can spend on the wedding while ensuring that you will also have enough money for your retirement?*
Notice that the savings spent on the wedding no longer produce investment returns at rate `r` per month. Also, you cannot finance the wedding on debt β you can only use the savings up to the wedding date!
## Example 1
Let's say the function `max_wedding_cost(C, r, S, T, W)` gets the above inputs `C = 2_500` (dollars per month), `r = 0.5` (percent per month), `S = 3_000_000` (dollars), `T = 35` (years) and `W = 5` (years).
If you spend zero dollars on your wedding, you will have approximately `3_561_775.75` dollars in your savings account upon your retirement, or `561_775.75` dollars over the required `S = 3_000_000` dollars.
It turns out that the maximum amount you can spend on your wedding day is approximately `93_278.33` dollars. Your answer should be within `0.01%` of the reference answer. See notes for further details on accuracy.
## Example 2
Suppose in the above example `S = 2_000_000`, i.e., you need a million dollars less for your retirement.
In this case it turns out that you can blow all your savings up to wedding day β a total of approximately `174_425.08` dollars β on your wedding. Even though you have to re-start saving from scratch, you can still reach your two-million-dollar retirement goal.
## Notes
Your magical savings account operates on double-precision floating point arithmetic, so you don't have to deal with rounding numbers to cents. Just return the final result as a floating point number without any rounding; it only needs to be within 0.01% of the reference solution.
It is guaranteed that with zero wedding costs, you will reach your retirement goal `S`. Parameters will have the following ranges: `100 <= C <= 3_000`, `0.1 <= r <= 1.0`, `100_000 <= S <= 3_000_000`, `10 <= T <= 40`, and `1 <= W <= T`. | reference | def max_wedding_cost(C, r, S, T, W):
p = 1 + r / 100
curr, req = 0, S
for _ in range(12 * (T - W)):
req = max((req - C) / p, 0)
for _ in range(12 * W):
curr = curr * p + C
return curr - req
| Plan Your Dream Wedding | 66314d6b7cb7030393dddf8a | [
"Mathematics"
] | https://www.codewars.com/kata/66314d6b7cb7030393dddf8a | 7 kyu |
This is an extreme version of [Chain Reaction - Minimum Bombs Needed]( https://www.codewars.com/kata/64c8a9b8f7c1b7000fdcdafb). You will be given a string that represents a 2D "map" such as this:
```
0+000x000xx
++000++000+
00x0x00000x
0+000000x+0
```
The string consists of three different characters (in addition to newlines that separate the rows):
* "+" bombs: when activated, their explosion activates any bombs directly above, below, left, or right of the "+" bomb.
* "x" bombs: when activated, their explosion activates any bombs placed in any of the four diagonal directions next to the "x" bomb.
* Empty spaces "0".
The goal is simple: given a map, return the minimum number of bombs that need to be set off for all bombs to be destroyed by the chain reaction. In the above example, the answer is `3` (can you see why?).
# Performance requirement
Given a map of size `N = width x height`, your algorithm should run in time `O(N log N)`. `O(N)` is possible but not required. Map sizes tested will be:
* 10 fixed maps (up to 5 x 5) to get your feet wet
* 100 small random maps (10 x 10) to test your robustness
* 50 medium random maps (50 x 50) to test your performance
* 10 large random maps (100 x 100) to ensure you're only blowing up the *bombs*
* 2 giant random maps (250 x 250) to make you cry
The reference solution runs in around 6-7 seconds. With a smart algorithm, there's no need for micro-optimizations.
*Disabled libraries: sys, math, numpy, scipy, and sklearn* | algorithms | def min_bombs_needed(grid):
G = grid_to_graph(grid)
order = topologic_sort_with_scc(G)
return count_roots(G, order)
NEIGHS = {
'+': [(- 1, 0), (1, 0), (0, - 1), (0, 1)],
'x': [(- 1, 1), (1, 1), (- 1, - 1), (1, - 1)],
}
def grid_to_graph(grid):
grid = grid . splitlines()
H, W = len(grid), len(grid[0])
G = {}
for i, r in enumerate(grid):
for j, c in enumerate(r):
if c == '0':
continue
k = i * W + j
if not k in G:
G[k] = set()
for di, dj in NEIGHS[c]:
a, b = i + di, j + dj
if 0 <= a < H and 0 <= b < W and grid[a][b] != '0':
G[k]. add(a * W + b)
return G
def topologic_sort_with_scc(G):
out = []
seen = set()
for node in G:
if node in seen:
continue
prefix, stk = [], [node]
while stk:
node = stk . pop()
seen . add(node)
prefix . append(node)
stk . extend(succ for succ in G[node] if succ not in seen)
out . extend(reversed(prefix))
return out
def count_roots(G, order):
cnt = 0
for node in reversed(order):
if node not in G:
continue
cnt += 1
stk = [node]
while stk:
node = stk . pop()
stk . extend(succ for succ in G . pop(node, ()) if succ in G)
return cnt
| Chain Reaction - Minimum Bombs Needed (Extreme Version) | 65c420173817127b06ff7ea7 | [
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/65c420173817127b06ff7ea7 | 2 kyu |
### Disclaimer
This kata is in accordance with the EPIC challenge in relation to Andela's 10 year anniversary celebration. You can find more info [here](https://www.codewars.com/post/introducing-the-epic-challenge-2024)
### Story
ejiniζη₯ has recently quit his programming job and is now opting in for a career change. He has decided to settle in the baking industry and is now a worker of a cake franchise designated for wedding celebrations. He has come up with a creative wedding cake model and a unique box that can modify the cake in a certain way that can blow away all the attendees!!! (*How cool is that~ π*)
## Task
Given the **cake model**, your job is to help ejiniζη₯ write a program that can instantly display the final visualization of the cake model after the unique box has been unfolded.
Initial cake model below:
```
/|\
\/ \/
\ | | \
/\/\/\/
/ \
/|||||||||\
```
The final visualization:
```
/|\
\ | /
\ | \
/ | /
/ | \
/ | \
```
More examples:
* ```
\ \
// |||||||||\\/
\\\\\\\\\\\\\\\\\
/ /| \ /\|\ /| |/
/||||||||\/| /\||||||\\
```
becomes
```
\ | \
/ | /
\ | \
/ | /
/ | \
```
* ```
/ \
/ \
/ \
/ \
/ \
/ \
```
becomes
```
/ | \
/ | \
/ | \
/ | \
/ | \
/ | \
```
**Notes**
* Each cake model will have at least 1 layer (row), separated by a newline character (`\n`)
* Each layer will only consist of **odd number of filling space**
* The lower layer will have **equal or more filling space** than the upper ones
* Each layer will always start and end with `/` or `\` fillings
* Starting and ending position of each layer **will not overlap**
* Inner fillings of the cake may be `/`, `\` or `|`
* Some part of the cake do not have fillings (*due to the semi-functional cake creation model...*)
* Trailing and leading spaces for the visualization above **will not be included** in the cake model's input and final output.
* `\\` for **visualization above only** is considered as 2 fillings rather than 1.
* Output should be the same as the given input except with all fillings of each layer centralized whilst leaving a starting and ending filling to prevent it from overflow ^^. (Refer to examples above)
| reference | def cake_visualizer(s):
return '\n' . join(r[0] + ' ' * (len(r) - 3 >> 1) + '|' + ' ' * (len(r) - 3 >> 1) + r[- 1] for r in s . split('\n'))
| Visualization of Wedding Cakes | 662f64adf925ebceb6c5a4e4 | [
"Strings"
] | https://www.codewars.com/kata/662f64adf925ebceb6c5a4e4 | 7 kyu |
# Background
Today is the special day you've been waiting for β it's your birthday! It's 8 AM and you're setting up your birthday cake for the party. It's time to put the candles on top.
You take out all the candles you've bought. As you are about to put them on the cake, you just realize that there are numbers on each candles. What are these numbers?! After searching about it on the internet, turns out these are special candles. These candles need to be blown a certain number of times before they're finally extinguished, and those numbers on the candles are the required times to blow them.
Being one who plans meticulously, you want to determine the total number of blows you need to extinguish all the candles once you've put them on the cake.
# Task
Given a string containing digits (representing the strength of the candles), calculate the number of blows you need to extinguish all the candles.
Starting at the beginning of the string, each blow can only reach 3 candles, reducing their strength by one each. You can only reach more candles once those directly in front of you are extinguished.
~~~if:lambdacalc
# Encodings
String of digits will be encoded as lists of numbers ( for `"1321"` in the examples, read `[1,3,2,1]` )
purity: `LetRec`
numEncoding: `Scott`
export constructors `nil, cons` for your `List` encoding
~~~
# Examples
```
Input: "1321"
Move 1 | "(132)1" -> "0211"
Move 2 | "0(211)" -> "0100"
Move 3 | "0(100)" -> "0000"
This should return 3.
```
```
Input: "0323456"
Move 1 | "0(323)456" -> "0212456"
Move 2 | "0(212)456" -> "0101456"
Move 3 | "0(101)456" -> "0000456"
Move 4 | "0000(456)" -> "0000345"
Move 5 | "0000(345)" -> "0000234"
Move 6 | "0000(234)" -> "0000123"
Move 7 | "0000(123)" -> "0000012"
Move 8 | "00000(12)" -> "0000001"
Move 9 | "000000(1)" -> "0000000"
This should return 9.
```
```
Input: "2113"
Move 1 | "(211)3" -> "1003"
Move 2 | "(100)3" -> "0003"
Move 3 | "000(3)" -> "0002"
Move 4 | "000(2)" -> "0001"
Move 5 | "000(1)" -> "0000"
This should return 5.
```
Good luck blowing all those candles ;-)
This kata is created for [The EPIC Challenge](https://www.codewars.com/post/introducing-the-epic-challenge-2024) in honor of Andela's 10-year anniversary.
<p style="font-size:xx-small;">This kata is also created on my birthday π₯³</p> | algorithms | def blow_candles(st):
blow2 = blow1 = blows = 0
for candle in map(int, st):
blow0 = max(0, candle - blow1 - blow2)
blows += blow0
blow2, blow1 = blow1, blow0
return blows
| Blowing Birthday Candles | 6630da20f925eb3007c5a498 | [
"Algorithms"
] | https://www.codewars.com/kata/6630da20f925eb3007c5a498 | 7 kyu |
*Inspired by the emojify custom Python module.*
You are given a string made up of chains of emotes separated by **1** space each, with chains having **2** spaces in-between each.
Each emote represents a digit:
```
:) | 0
:D | 1
>( | 2
>:C | 3
:/ | 4
:| | 5
:O | 6
;) | 7
^.^ | 8
:( | 9
```
Each emote chain represents the digits of the ASCII/Unicode code for a character, e.g. ``:( ;)`` is ``97``, which is the ASCII code for ``'a'``.
Given a such string of emotes, find the string it represents. Example:
``':D :) :/ :D :) :|'`` is 2 chains: ``':D :) :/'`` and ``':D :) :|'``.
These represent ASCII codes 104 and 105 respectively, translating to ``'hi'``.
Input will always be valid. Chains may start with leading zeroes; these are valid and do not change the chain's value.
<sub><sup>hobovsky if you're reading this, you're welcome for the emoji kata idea</sup></sub> | games | def deemojify(string):
digits = {
':)': '0',
':D': '1',
'>(': '2',
'>:C': '3',
':/': '4',
':|': '5',
':O': '6',
';)': '7',
'^.^': '8',
':(': '9',
}
result = ''
for group in string . split(' '):
number = ''
for emoji in group . split(' '):
number += digits[emoji]
result += chr(int(number))
return result
| De-Emojify | 6627696c86b953001280675e | [
"Strings"
] | https://www.codewars.com/kata/6627696c86b953001280675e | 7 kyu |
Based off the game Counter-Strike
The bomb has been planted and you are the last CT (Counter Terrorist) alive
You need to defuse the bomb in time!
___
__Task:__
Given a matrix m and an integer time representing the seconds left before the bomb detonates, determine if it is possible to defuse the bomb in time. The time limit is inclusive.
In the matrix m:
* "CT" represents the counter terrorist
* "B" represents the bomb
* "K" represents the kit
* "0" represents empty space
```if:c
NOTE: C lang uses chars, not strings, so "CT" is represented as 'C'
```
The defuse kit may or may not be present in the matrix
You can defuse the bomb in 2 ways:
* If you defuse the bomb without the defuse kit, it will cost 10 seconds
* If you defuse the bomb with the defuse kit, it will cost only 5 seconds
Each move the CT makes in any direction costs 1 second
The CT can move diagonally, horizontally and vertically.
**Example 1**
```
time = 14
m =
[
["0", "0", "0", "0", "B"],
["0", "0", "0", "0", "CT"],
["0", "0", "0", "0", "0"],
["0", "K", "0", "0", "0"],
]
```
returns true
**Explanation:**
The CT moves upwards and gets to the bomb with 13 seconds left
The CT defuses the bomb without a kit which costs 10 seconds
The bomb is succesfully defused
__Alternative__
The CT picks up the kit which costs 3 seconds
The CT moves to the bomb which costs 3 seconds
The CT defuses with a kit which costs 5 seconds
The bomb is succesfully defused
**Example 2**
```
time = 10
m =
[
["CT", "0", "0", "0", "0", "0", "0"],
[ "0", "0", "0", "0", "0", "0", "0"],
[ "0", "0", "0", "0", "0", "0", "0"],
[ "0", "0", "0", "0", "0", "0", "0"],
[ "0", "0", "0", "0", "0", "0", "0"],
[ "0", "0", "0", "0", "0", "0", "0"],
[ "0", "0", "0", "0", "0", "0", "0"],
[ "0", "0", "0", "0", "0", "0", "B"]
]
```
returns false
**Explanation:**
There is no kit present so the CT has to defuse without it
The CT takes 7 seconds to get to the bomb but there are only 10 seconds remaining
The bomb detonates!
Good luck!
> Bingo bango bongo bish bash bosh.
| reference | def bomb_has_been_planted(m, time):
def dist(p1, p2): return max(abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
p_ct = next((x, y) for x, row in enumerate(m)
for y, el in enumerate(row) if el == 'CT')
p_b = next((x, y) for x, row in enumerate(m)
for y, el in enumerate(row) if el == 'B')
p_k = next(((x, y) for x, row in enumerate(m)
for y, el in enumerate(row) if el == 'K'), None)
res = dist(p_ct, p_b) + 10
if p_k:
res = min(res, dist(p_ct, p_k) + dist(p_k, p_b) + 5)
return res <= time
| Bomb has been planted! | 6621b92d6d4e8800178449f5 | [
"Arrays",
"Games"
] | https://www.codewars.com/kata/6621b92d6d4e8800178449f5 | 6 kyu |
# Task
Given a string `s` representing a 2D rectangular grid with rows separated by `'\n'`, empty tiles as `'.'`, the starting point `'p'` and a path from this point using arrows in <a href="https://en.wikipedia.org/wiki/Moore_neighborhood">Moore neighborhood</a> `'ββββββββ'`, return a string depicting that **same path**, but with the following transformation:
- the initial path has starting point `'p'` and for each next tile an arrow showing the **in-bound** direction
- the transformed path must show the **out-bound** direction instead, and the final position as `'q'`
Constraints:
- There's at least 1 element in the path
- Since the initial path shows in-bound direction, `'p'` is always shown, `'q'` never
- Since the expected path shows out-bound direction, `'p'` is never shown, `'q'` always
- A path is deterministic, no forks, joins or conflicts are possible
- A path can cross with itself as long no tile is visited more than once (see third example below)
---
## Examples
```
test input output
----------------------------------
1 p q
2 ...pβββ... ...βββq...
3 ββ βq
βp ββ
4 βp qβ
ββ ββ
ββ ββ
5 .β. .β.
pββ βββ
βββ qββ
6 .....ββββ.. .....ββββ..
.pβ.ββ..β.. .ββ.βq..β..
...ββ.ββ... ...ββ.ββ...
```
---
Good luck, have fun! | algorithms | d = {'β': (0, - 1), 'β': (- 1, 0), 'β': (0, 1), 'β': (1, 0),
'β': (- 1, - 1), 'β': (- 1, 1), 'β': (1, 1), 'β': (1, - 1)}
def transform(s):
s = s . splitlines()
t = [['q.' [c == '.'] for c in r] for r in s]
for y, r in enumerate(s):
for x, c in enumerate(r):
try:
dy, dx = d[c]
except KeyError:
pass
else:
t[y - dy][x - dx] = c
return '\n' . join('' . join(r) for r in t)
| Arrow in/out transformation | 661bb565f54fde005b8e3d6c | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/661bb565f54fde005b8e3d6c | 6 kyu |
This kata is a generalization of the ["A Man And His Umbrellas"](https://www.codewars.com/kata/58298e19c983caf4ba000c8d) kata by [mattlub](https://www.codewars.com/users/mattlub). If you haven't completed that kata, you may wish to do so before attempting this one.
A man travels to different locations. If it is rainy, he will take an umbrella with him, from wherever he's coming from to wherever he's going. If it is sunny, he will not.
Your function will receive, as an argument, an array of objects containing each of the locations the man travels to, and the weather during the trip to that location, for example:
```javascript
[
["work", "sunny"],
["shop", "rainy"],
["work", "rainy"],
["home", "sunny"],
["work", "rainy"],
["gym", "sunny"],
["work", "sunny"],
["home", "rainy"]
]
```
Before his travels start, the man is at `"home"`, and therefore `"home"` will always be present in the returned list of locations. The locations can be arbitrary strings, not just the ones shown in these examples. The weather is always either `"sunny"` or `"rainy"`.
Your function must return an object where the keys are the different locations that the man visited, and the values are the minimum number of umbrellas that must be at each of those locations before the man starts the sequence of travels, so that he never finds himself missing an umbrella when travelling somewhere. For example, for the above example:
```javascript
[
["work", "sunny"],
["shop", "rainy"], // there needs to be an umbrella at work
["work", "rainy"], // he can re-use the umbrella he took to the shop
["home", "sunny"],
["work", "rainy"], // there needs to be an umbrella at home
["gym", "sunny"],
["work", "sunny"],
["home", "rainy"] // he can re-use one of the umbrellas he took to work
]
```
The correct return value for your function would then be:
```javascript
{
"work": 1,
"home": 1,
"gym": 0,
"shop": 0
}
```
Note that the man can travel from his current location to his current location. In this situation, the man still leaves the location, wanders around under a rainy or sunny sky for a bit (potentially needing, or not needing, an umbrella) and returns to the location.
| algorithms | def required_umbrellas(travels: list[tuple[str, str]]) - > dict[str, int]:
res = {place: 0 for place, _ in travels} | {'home': 0}
cur_state, cur_place = {k: 0 for k in res}, 'home'
for place, state in travels:
if state == 'rainy':
if cur_state[cur_place] == 0:
res[cur_place] += 1
cur_state[cur_place] += 1
cur_state[cur_place] -= 1
cur_state[place] += 1
cur_place = place
return res
| A Wandering Man and his Umbrellas | 661aa2008fa7ab015ee33529 | [
"Logic",
"Arrays"
] | https://www.codewars.com/kata/661aa2008fa7ab015ee33529 | 6 kyu |
<h2> Description: </h2>
Jury has a list called `lis` consisting of <b>integers</b> that you have to guess. Your function is passed two arguments: `n - length of lis` and `guess - the function that takes three arguments a, b and c`, and returns:
```python
min(lis[a],lis[b]) if c = "min"
max(lis[a],lis[b]) if c = "max"
# a can't be equal to b.
# a and b should be between 0 and n-1.
```
for example: if `lis = [4,3,5,2,7]`,<br>
```python
guess(0,1,"min") would return min(lis[0],lis[1]) = min(4,3) = 3
guess(4,2,"max") would return max(lis[4],lis[2]) = max(7,5) = 7
```
Guess and return the array `lis`. You can call the function `guess` at most `1.5*n+5` times per test. If you call `guess` wrongly, or more times than allowed, it will `raise an exception`.
<h2> Constraints: </h2>
<b>3 ≤ length(lis) ≤ 1000</b><br>
<b>1 ≤ lis[i] ≤ 10000</b>
Note: this is called an interactive problem. | algorithms | def guesser(n, guess):
A, B = {guess(0, 1, "min"), guess(0, 1, "max")}, {
guess(1, 2, "min"), guess(1, 2, "max")}
if len(A) == len(B) == 1:
res = [A . pop()] * 3
elif len(A) == 1:
c = (B - A). pop()
res = [A . pop()] * 2 + [c]
elif len(B) == 1:
res = [(A - B). pop()] + [B . pop()] * 2
elif A == B:
a = guess(0, 2, "max")
res = [a, (A - {a}). pop(), a]
else:
b = (A & B). pop()
res = [(A - {b}). pop(), b, (B - {b}). pop()]
for k in range(3, n, 2):
if k < n - 1:
mn, mx = guess(k, k + 1, "min"), guess(k, k + 1, "max")
if mn >= res[- 1]:
d = guess(k - 1, k, "max")
res . extend([d, mx if mn == d else mn])
elif mx <= res[- 1]:
d = guess(k - 1, k, "min")
res . extend([d, mx if mn == d else mn])
else:
d = guess(k - 1, k, "min")
res . extend([mx, mn] if d == res[- 1] else [mn, mx])
else:
d = guess(k - 1, k, "min")
res . append(d if d != res[- 1] else guess(k - 1, k, "max"))
return res
| Guess the array with min and max | 66124f9efe0da490adb4afb6 | [
"Arrays"
] | https://www.codewars.com/kata/66124f9efe0da490adb4afb6 | 5 kyu |
Thanks for checking out my kata - in the below problem - the highest n can be is 200.
Example summation of a number -
summation of the number 5
1+2+3+4+5 = 15
summation of the number 6
1+2+3+4+5+6 = 21
You are sat with two frogs on a log, Chris and Tom. They are arguing about who ate the most flies (Poor flies, but what you going to do!). Chris says "I ate the summation of n number of flies!".
Tom replies "Take half the number you ate then round it down and work out the summation of that, that is how many I ate"!
Cat then hops onto the log looking pleased with herself "Well, I ate the summation of both your dinners combined." Loz who came late to this meeting of amphibians is very confused, he asks "So how many did each of you eat?"
Write a function called frogContest which returns a string "Chris ate {number} flies, Tom ate {number} flies and Cat ate {number} flies"
{number} is the integer value of the amount of flies eaten by each. | algorithms | def frog_contest(x):
def f(n): return n * (n + 1) / / 2
a = f(x)
b = f(a / / 2)
c = f(a + b)
return f"Chris ate { a } flies, Tom ate { b } flies and Cat ate { c } flies"
| Frog's Dinner | 65f361be2b30ec19b78d758f | [
"Mathematics",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/65f361be2b30ec19b78d758f | 7 kyu |
### Description
A centrifuge is a laboratory device used to separate fluids based on density. This is achieved through centrifugal force by spinning a collection of test tubes at high speeds. All holes on the centrifuge are equally distanced from their neighbouring holes and have the same distance to the center.
<image width=400px src="https://vetlabsupplies.co.uk/assets/Veterinary-Centrifuge.jpg"></image>
---
Kata Series:
- Balanced centrifuge verification (this kata)
</a>
- <a href="https://www.codewars.com/kata/65ff184fe827ae00631d1b18">Balanced centrifuge configurator</a>
---
# Task
Given a centrifuge, return whether it's balanced. A centrifuge is called balanced if the center of mass of the collection of test tubes coincides with the center of mass of the centrifuge itself. Test tubes in this kata all look the same and have the same weight.
#### Input
An array containing <code>n</code> elements representing a <code>n</code>-hole centrifuge. Elements can either be <code>0</code> (hole) or <code>1</code> (tube inserted).
#### Output
Return a boolean indicating whether the centrifuge is balanced.
---
### Examples
Examples of 6-hole centrifuges with holes <code>o</code> and tubes <code>x</code>. Direction and starting point don't matter. In these examples, we start at the top hole/tube and move in clockwise direction.
```
balanced balanced unbalanced
[1,0,1,0,1,0] [0,1,0,0,1,0] [0,1,0,0,1,1]
x o o
o o o x x x
. . .
x x x o x o
o o o
```
---
### Constraints
100 random tests with:
- centrifuges of size <code>[2 - 55]</code>
- tubes <code>[1 - n]</code> with <code>n</code> being the size
- given the low sizes, you have the freedom of choice to either pick an exact algorithm or a good approximator algorithm that is accurate in the low ranges
---
Good luck, have fun! | reference | def remove_symmetry(storage: list, divisor: int):
pattern_size = len(storage) / / divisor
for i in range(pattern_size):
temp_storage = []
for sub_i in range(divisor):
temp_storage . append(storage[i + sub_i * pattern_size])
if len(set(temp_storage)) == 1:
for sub_i in range(divisor):
storage[i + sub_i * pattern_size] = 0
def check_if_uniform(storage: list):
return len(set(storage)) == 1
def is_prime(n):
for i in range(2, n):
if (n % i) == 0:
return False
return True
def prime_factors(n):
result = []
primzahlen_to_number = [i for i in range(2, n + 1) if is_prime(i)]
if n in primzahlen_to_number:
result . append(n)
return result
while n >= 2:
for x in primzahlen_to_number:
if n % x == 0:
n = n / / x
result . append(x)
result . sort()
return set(result)
def balanced(storage: list):
storage_size = len(storage)
# here goes primefactor-analysis (uses sets)
divisors = prime_factors(storage_size)
for divisor in divisors:
if not check_if_uniform(storage):
remove_symmetry(storage, divisor)
else:
break
return check_if_uniform(storage)
| Balanced centrifuge verification | 65d8f6b9e3a87b313c76d807 | [
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/65d8f6b9e3a87b313c76d807 | 6 kyu |
### Introduction
This is the start of a series of kata's concerning sudoku strategies available for human (as opposed to computer) players. Before we move on to implementing actual strategies, we'll introduce you to the concept of **Pencil Marks**.
Sudoku players often use pencil marks to visualise all remaining candidates for each sudoku cell. **In this kata we'll be focusing on drawing pencil marks for any given sudoku board.** We can use this visualisation for upcoming kata's concerning sudoku strategies.
<image src="https://www.learn-sudoku.com/images/pencil_marks_sample.gif"></image>
More info and examples of sudoku strategies can be found at <a href="https://www.sudokuwiki.org/sudoku.htm">sudokuwiki</a>. If you are new to Sudoku, you may find <a href="https://en.wikipedia.org/wiki/Glossary_of_Sudoku">the glossary of Sudoku</a> useful.
### Sudoku Kata Series
Introduction Kata:
- Sudoku Strategies - Pencil Marks (this kata)
Beginner Level:
- <a href="https://www.codewars.com/kata/65c796c193e1c20c1ae67209">Sudoku Strategies - Naked Single</a>
- <a href="https://www.codewars.com/kata/65cd01dda11df609386d6ef9/">Sudoku Strategies - Hidden Single</a>
---
# Task
As a warmup for implementing sudoku strategies, in this kata you'll be asked to render pencil marks given a sudoku board.
#### What are pencil marks?
Pencil marks keep track of the remaining candidates for each cell. These form a visual aid for people solving sudoku puzzles.
Each cell starts with the full set of candidates of <code>1 - 9</code> on a <code>9x9</code> sudoku board. All clues are then filled in on the board, after which you:
- clear all remaining candidates from that cell
- clear that candidate from peer cells of that cell (cells that share same row/col/box)
The candidates set will shrink further if you apply specific strategies, such as Naked Singles, Hidden Singles, and more advanced strategies to come. Every time a deduction is made, the candidates set becomes smaller. We don't know what the candidates set should be until it is clear what deductions have been made.
In this kata, you're expected to **render the pencil marks after all initial clues are filled in**.
#### Input
- The input is given as a 2d board (string), rows separated by a new line char <code>'\n'</code>
- Clues are inserted on the board, or char <code>'.'</code> if no clue is available for a given cell
- Sudoku bands are separated by an extra row containing chars <code>'-'</code> and <code>'+'</code>
- Sudoku stacks are separated by an extra col containing chars <code>'|'</code> and <code>'+'</code>
- There is whitespace margin and padding around the clues.
```
Example input:
. 3 5 | . . 1 | 6 . 7
6 7 8 | 5 . 3 | 2 9 .
2 1 9 | 7 8 6 | 5 3 4
------+-------+------
. 9 2 | 6 3 5 | . 7 8
3 8 . | 2 1 . | . 6 5
7 5 6 | 8 9 4 | 3 . 2
------+-------+------
8 6 . | . 5 2 | 7 4 9
. . 3 | 1 7 9 | . 2 6
. 2 7 | . 6 8 | . 5 3
```
#### Output
- The output is expected as a 2d board (string), rows separated by a new line char <code>'\n'</code>
- Each cell has room to display the 9 possible candidates, or the clue
- If no clue is given in the input for the cell:
- Candidates are inserted on the board, or char <code>'-'</code> if the candidate is no longer available
- Notice how candidates go from top to bottom, from left to right
- otherwise:
- The candidates are not rendered, instead the clue is rendered in the middle of the cell, surrounded by whitespace padding
- Sudoku rows are separated by an extra row containing chars <code>'-'</code> and <code>'+'</code>
- Sudoku bands are separated by an extra row containing chars <code>'='</code> and <code>'+'</code>
- Sudoku cols are separated by an extra col containing chars <code>'|'</code> and <code>'+'</code>
- Sudoku stacks are separated by an extra col containing chars <code>'|'</code> and <code>'+'</code>
- Notice that soduko band separators replace sudoku row separators, and sudoku stack separators are added alongside sudoku col separators
- There is whitespace margin and padding around the clues and candidates.
```
Example output:
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| - - - | | || - - - | - 2 - | || | - - - | |
| 4 - - | 3 | 5 || 4 - - | 4 - - | 1 || 6 | - - - | 7 |
| - - - | | || - - 9 | - - - | || | - 8 - | |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| | | || | - - - | || | | 1 - - |
| 6 | 7 | 8 || 5 | 4 - - | 3 || 2 | 9 | - - - |
| | | || | - - - | || | | - - - |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| | | || | | || | | |
| 2 | 1 | 9 || 7 | 8 | 6 || 5 | 3 | 4 |
| | | || | | || | | |
+=======+=======+=======++=======+=======+=======++=======+=======+=======+
| 1 - - | | || | | || 1 - - | | |
| 4 - - | 9 | 2 || 6 | 3 | 5 || 4 - - | 7 | 8 |
| - - - | | || | | || - - - | | |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| | | - - - || | | - - - || - - - | | |
| 3 | 8 | 4 - - || 2 | 1 | - - - || 4 - - | 6 | 5 |
| | | - - - || | | 7 - - || - - 9 | | |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| | | || | | || | 1 - - | |
| 7 | 5 | 6 || 8 | 9 | 4 || 3 | - - - | 2 |
| | | || | | || | - - - | |
+=======+=======+=======++=======+=======+=======++=======+=======+=======+
| | | 1 - - || - - 3 | | || | | |
| 8 | 6 | - - - || - - - | 5 | 2 || 7 | 4 | 9 |
| | | - - - || - - - | | || | | |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| - - - | - - - | || | | || - - - | | |
| 4 5 - | 4 - - | 3 || 1 | 7 | 9 || - - - | 2 | 6 |
| - - - | - - - | || | | || - 8 - | | |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| 1 - - | | || - - - | | || 1 - - | | |
| 4 - - | 2 | 7 || 4 - - | 6 | 8 || - - - | 5 | 3 |
| - - 9 | | || - - - | | || - - - | | |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
```
> Note that pencil marks can also be used as a tool to search for naked and hidden singles. In the output above there is (amongst several others) a cell <code>R1C1</code> where you can easily spot only one remaining candidate <code>4</code>. This is a naked single.
Good luck, have fun!
| algorithms | from re import sub as S
def draw_pencil_marks(board):
grid = [[int(s) if s in "123456789" else set(range(1, 10)) for s in r]
for r in S(r"[^\.\d\n]", "", board . strip()). splitlines() if r]
for r in range(9):
for c in range(9):
if isinstance(grid[r][c], int):
n = grid[r][c]
for i in range(9):
if isinstance(grid[r][i], set):
grid[r][i]. discard(n)
if isinstance(grid[i][c], set):
grid[i][c]. discard(n)
if isinstance(grid[r / / 3 * 3 + i / / 3][c / / 3 * 3 + i % 3], set):
grid[r / / 3 * 3 + i / / 3][c / / 3 * 3 + i % 3]. discard(n)
def g(r, c, n): return grid[r][c] if isinstance(grid[r][c], int) and n == 5 else " " if isinstance(
grid[r][c], int) else n if n in grid[r][c] else "-"
return f"""+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| { g ( 0 , 0 , 1 )} { g ( 0 , 0 , 2 )} { g ( 0 , 0 , 3 )} | { g ( 0 , 1 , 1 )} { g ( 0 , 1 , 2 )} { g ( 0 , 1 , 3 )} | { g ( 0 , 2 , 1 )} { g ( 0 , 2 , 2 )} { g ( 0 , 2 , 3 )} || { g ( 0 , 3 , 1 )} { g ( 0 , 3 , 2 )} { g ( 0 , 3 , 3 )} | { g ( 0 , 4 , 1 )} { g ( 0 , 4 , 2 )} { g ( 0 , 4 , 3 )} | { g ( 0 , 5 , 1 )} { g ( 0 , 5 , 2 )} { g ( 0 , 5 , 3 )} || { g ( 0 , 6 , 1 )} { g ( 0 , 6 , 2 )} { g ( 0 , 6 , 3 )} | { g ( 0 , 7 , 1 )} { g ( 0 , 7 , 2 )} { g ( 0 , 7 , 3 )} | { g ( 0 , 8 , 1 )} { g ( 0 , 8 , 2 )} { g ( 0 , 8 , 3 )} |
| { g ( 0 , 0 , 4 )} { g ( 0 , 0 , 5 )} { g ( 0 , 0 , 6 )} | { g ( 0 , 1 , 4 )} { g ( 0 , 1 , 5 )} { g ( 0 , 1 , 6 )} | { g ( 0 , 2 , 4 )} { g ( 0 , 2 , 5 )} { g ( 0 , 2 , 6 )} || { g ( 0 , 3 , 4 )} { g ( 0 , 3 , 5 )} { g ( 0 , 3 , 6 )} | { g ( 0 , 4 , 4 )} { g ( 0 , 4 , 5 )} { g ( 0 , 4 , 6 )} | { g ( 0 , 5 , 4 )} { g ( 0 , 5 , 5 )} { g ( 0 , 5 , 6 )} || { g ( 0 , 6 , 4 )} { g ( 0 , 6 , 5 )} { g ( 0 , 6 , 6 )} | { g ( 0 , 7 , 4 )} { g ( 0 , 7 , 5 )} { g ( 0 , 7 , 6 )} | { g ( 0 , 8 , 4 )} { g ( 0 , 8 , 5 )} { g ( 0 , 8 , 6 )} |
| { g ( 0 , 0 , 7 )} { g ( 0 , 0 , 8 )} { g ( 0 , 0 , 9 )} | { g ( 0 , 1 , 7 )} { g ( 0 , 1 , 8 )} { g ( 0 , 1 , 9 )} | { g ( 0 , 2 , 7 )} { g ( 0 , 2 , 8 )} { g ( 0 , 2 , 9 )} || { g ( 0 , 3 , 7 )} { g ( 0 , 3 , 8 )} { g ( 0 , 3 , 9 )} | { g ( 0 , 4 , 7 )} { g ( 0 , 4 , 8 )} { g ( 0 , 4 , 9 )} | { g ( 0 , 5 , 7 )} { g ( 0 , 5 , 8 )} { g ( 0 , 5 , 9 )} || { g ( 0 , 6 , 7 )} { g ( 0 , 6 , 8 )} { g ( 0 , 6 , 9 )} | { g ( 0 , 7 , 7 )} { g ( 0 , 7 , 8 )} { g ( 0 , 7 , 9 )} | { g ( 0 , 8 , 7 )} { g ( 0 , 8 , 8 )} { g ( 0 , 8 , 9 )} |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| { g ( 1 , 0 , 1 )} { g ( 1 , 0 , 2 )} { g ( 1 , 0 , 3 )} | { g ( 1 , 1 , 1 )} { g ( 1 , 1 , 2 )} { g ( 1 , 1 , 3 )} | { g ( 1 , 2 , 1 )} { g ( 1 , 2 , 2 )} { g ( 1 , 2 , 3 )} || { g ( 1 , 3 , 1 )} { g ( 1 , 3 , 2 )} { g ( 1 , 3 , 3 )} | { g ( 1 , 4 , 1 )} { g ( 1 , 4 , 2 )} { g ( 1 , 4 , 3 )} | { g ( 1 , 5 , 1 )} { g ( 1 , 5 , 2 )} { g ( 1 , 5 , 3 )} || { g ( 1 , 6 , 1 )} { g ( 1 , 6 , 2 )} { g ( 1 , 6 , 3 )} | { g ( 1 , 7 , 1 )} { g ( 1 , 7 , 2 )} { g ( 1 , 7 , 3 )} | { g ( 1 , 8 , 1 )} { g ( 1 , 8 , 2 )} { g ( 1 , 8 , 3 )} |
| { g ( 1 , 0 , 4 )} { g ( 1 , 0 , 5 )} { g ( 1 , 0 , 6 )} | { g ( 1 , 1 , 4 )} { g ( 1 , 1 , 5 )} { g ( 1 , 1 , 6 )} | { g ( 1 , 2 , 4 )} { g ( 1 , 2 , 5 )} { g ( 1 , 2 , 6 )} || { g ( 1 , 3 , 4 )} { g ( 1 , 3 , 5 )} { g ( 1 , 3 , 6 )} | { g ( 1 , 4 , 4 )} { g ( 1 , 4 , 5 )} { g ( 1 , 4 , 6 )} | { g ( 1 , 5 , 4 )} { g ( 1 , 5 , 5 )} { g ( 1 , 5 , 6 )} || { g ( 1 , 6 , 4 )} { g ( 1 , 6 , 5 )} { g ( 1 , 6 , 6 )} | { g ( 1 , 7 , 4 )} { g ( 1 , 7 , 5 )} { g ( 1 , 7 , 6 )} | { g ( 1 , 8 , 4 )} { g ( 1 , 8 , 5 )} { g ( 1 , 8 , 6 )} |
| { g ( 1 , 0 , 7 )} { g ( 1 , 0 , 8 )} { g ( 1 , 0 , 9 )} | { g ( 1 , 1 , 7 )} { g ( 1 , 1 , 8 )} { g ( 1 , 1 , 9 )} | { g ( 1 , 2 , 7 )} { g ( 1 , 2 , 8 )} { g ( 1 , 2 , 9 )} || { g ( 1 , 3 , 7 )} { g ( 1 , 3 , 8 )} { g ( 1 , 3 , 9 )} | { g ( 1 , 4 , 7 )} { g ( 1 , 4 , 8 )} { g ( 1 , 4 , 9 )} | { g ( 1 , 5 , 7 )} { g ( 1 , 5 , 8 )} { g ( 1 , 5 , 9 )} || { g ( 1 , 6 , 7 )} { g ( 1 , 6 , 8 )} { g ( 1 , 6 , 9 )} | { g ( 1 , 7 , 7 )} { g ( 1 , 7 , 8 )} { g ( 1 , 7 , 9 )} | { g ( 1 , 8 , 7 )} { g ( 1 , 8 , 8 )} { g ( 1 , 8 , 9 )} |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| { g ( 2 , 0 , 1 )} { g ( 2 , 0 , 2 )} { g ( 2 , 0 , 3 )} | { g ( 2 , 1 , 1 )} { g ( 2 , 1 , 2 )} { g ( 2 , 1 , 3 )} | { g ( 2 , 2 , 1 )} { g ( 2 , 2 , 2 )} { g ( 2 , 2 , 3 )} || { g ( 2 , 3 , 1 )} { g ( 2 , 3 , 2 )} { g ( 2 , 3 , 3 )} | { g ( 2 , 4 , 1 )} { g ( 2 , 4 , 2 )} { g ( 2 , 4 , 3 )} | { g ( 2 , 5 , 1 )} { g ( 2 , 5 , 2 )} { g ( 2 , 5 , 3 )} || { g ( 2 , 6 , 1 )} { g ( 2 , 6 , 2 )} { g ( 2 , 6 , 3 )} | { g ( 2 , 7 , 1 )} { g ( 2 , 7 , 2 )} { g ( 2 , 7 , 3 )} | { g ( 2 , 8 , 1 )} { g ( 2 , 8 , 2 )} { g ( 2 , 8 , 3 )} |
| { g ( 2 , 0 , 4 )} { g ( 2 , 0 , 5 )} { g ( 2 , 0 , 6 )} | { g ( 2 , 1 , 4 )} { g ( 2 , 1 , 5 )} { g ( 2 , 1 , 6 )} | { g ( 2 , 2 , 4 )} { g ( 2 , 2 , 5 )} { g ( 2 , 2 , 6 )} || { g ( 2 , 3 , 4 )} { g ( 2 , 3 , 5 )} { g ( 2 , 3 , 6 )} | { g ( 2 , 4 , 4 )} { g ( 2 , 4 , 5 )} { g ( 2 , 4 , 6 )} | { g ( 2 , 5 , 4 )} { g ( 2 , 5 , 5 )} { g ( 2 , 5 , 6 )} || { g ( 2 , 6 , 4 )} { g ( 2 , 6 , 5 )} { g ( 2 , 6 , 6 )} | { g ( 2 , 7 , 4 )} { g ( 2 , 7 , 5 )} { g ( 2 , 7 , 6 )} | { g ( 2 , 8 , 4 )} { g ( 2 , 8 , 5 )} { g ( 2 , 8 , 6 )} |
| { g ( 2 , 0 , 7 )} { g ( 2 , 0 , 8 )} { g ( 2 , 0 , 9 )} | { g ( 2 , 1 , 7 )} { g ( 2 , 1 , 8 )} { g ( 2 , 1 , 9 )} | { g ( 2 , 2 , 7 )} { g ( 2 , 2 , 8 )} { g ( 2 , 2 , 9 )} || { g ( 2 , 3 , 7 )} { g ( 2 , 3 , 8 )} { g ( 2 , 3 , 9 )} | { g ( 2 , 4 , 7 )} { g ( 2 , 4 , 8 )} { g ( 2 , 4 , 9 )} | { g ( 2 , 5 , 7 )} { g ( 2 , 5 , 8 )} { g ( 2 , 5 , 9 )} || { g ( 2 , 6 , 7 )} { g ( 2 , 6 , 8 )} { g ( 2 , 6 , 9 )} | { g ( 2 , 7 , 7 )} { g ( 2 , 7 , 8 )} { g ( 2 , 7 , 9 )} | { g ( 2 , 8 , 7 )} { g ( 2 , 8 , 8 )} { g ( 2 , 8 , 9 )} |
+=======+=======+=======++=======+=======+=======++=======+=======+=======+
| { g ( 3 , 0 , 1 )} { g ( 3 , 0 , 2 )} { g ( 3 , 0 , 3 )} | { g ( 3 , 1 , 1 )} { g ( 3 , 1 , 2 )} { g ( 3 , 1 , 3 )} | { g ( 3 , 2 , 1 )} { g ( 3 , 2 , 2 )} { g ( 3 , 2 , 3 )} || { g ( 3 , 3 , 1 )} { g ( 3 , 3 , 2 )} { g ( 3 , 3 , 3 )} | { g ( 3 , 4 , 1 )} { g ( 3 , 4 , 2 )} { g ( 3 , 4 , 3 )} | { g ( 3 , 5 , 1 )} { g ( 3 , 5 , 2 )} { g ( 3 , 5 , 3 )} || { g ( 3 , 6 , 1 )} { g ( 3 , 6 , 2 )} { g ( 3 , 6 , 3 )} | { g ( 3 , 7 , 1 )} { g ( 3 , 7 , 2 )} { g ( 3 , 7 , 3 )} | { g ( 3 , 8 , 1 )} { g ( 3 , 8 , 2 )} { g ( 3 , 8 , 3 )} |
| { g ( 3 , 0 , 4 )} { g ( 3 , 0 , 5 )} { g ( 3 , 0 , 6 )} | { g ( 3 , 1 , 4 )} { g ( 3 , 1 , 5 )} { g ( 3 , 1 , 6 )} | { g ( 3 , 2 , 4 )} { g ( 3 , 2 , 5 )} { g ( 3 , 2 , 6 )} || { g ( 3 , 3 , 4 )} { g ( 3 , 3 , 5 )} { g ( 3 , 3 , 6 )} | { g ( 3 , 4 , 4 )} { g ( 3 , 4 , 5 )} { g ( 3 , 4 , 6 )} | { g ( 3 , 5 , 4 )} { g ( 3 , 5 , 5 )} { g ( 3 , 5 , 6 )} || { g ( 3 , 6 , 4 )} { g ( 3 , 6 , 5 )} { g ( 3 , 6 , 6 )} | { g ( 3 , 7 , 4 )} { g ( 3 , 7 , 5 )} { g ( 3 , 7 , 6 )} | { g ( 3 , 8 , 4 )} { g ( 3 , 8 , 5 )} { g ( 3 , 8 , 6 )} |
| { g ( 3 , 0 , 7 )} { g ( 3 , 0 , 8 )} { g ( 3 , 0 , 9 )} | { g ( 3 , 1 , 7 )} { g ( 3 , 1 , 8 )} { g ( 3 , 1 , 9 )} | { g ( 3 , 2 , 7 )} { g ( 3 , 2 , 8 )} { g ( 3 , 2 , 9 )} || { g ( 3 , 3 , 7 )} { g ( 3 , 3 , 8 )} { g ( 3 , 3 , 9 )} | { g ( 3 , 4 , 7 )} { g ( 3 , 4 , 8 )} { g ( 3 , 4 , 9 )} | { g ( 3 , 5 , 7 )} { g ( 3 , 5 , 8 )} { g ( 3 , 5 , 9 )} || { g ( 3 , 6 , 7 )} { g ( 3 , 6 , 8 )} { g ( 3 , 6 , 9 )} | { g ( 3 , 7 , 7 )} { g ( 3 , 7 , 8 )} { g ( 3 , 7 , 9 )} | { g ( 3 , 8 , 7 )} { g ( 3 , 8 , 8 )} { g ( 3 , 8 , 9 )} |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| { g ( 4 , 0 , 1 )} { g ( 4 , 0 , 2 )} { g ( 4 , 0 , 3 )} | { g ( 4 , 1 , 1 )} { g ( 4 , 1 , 2 )} { g ( 4 , 1 , 3 )} | { g ( 4 , 2 , 1 )} { g ( 4 , 2 , 2 )} { g ( 4 , 2 , 3 )} || { g ( 4 , 3 , 1 )} { g ( 4 , 3 , 2 )} { g ( 4 , 3 , 3 )} | { g ( 4 , 4 , 1 )} { g ( 4 , 4 , 2 )} { g ( 4 , 4 , 3 )} | { g ( 4 , 5 , 1 )} { g ( 4 , 5 , 2 )} { g ( 4 , 5 , 3 )} || { g ( 4 , 6 , 1 )} { g ( 4 , 6 , 2 )} { g ( 4 , 6 , 3 )} | { g ( 4 , 7 , 1 )} { g ( 4 , 7 , 2 )} { g ( 4 , 7 , 3 )} | { g ( 4 , 8 , 1 )} { g ( 4 , 8 , 2 )} { g ( 4 , 8 , 3 )} |
| { g ( 4 , 0 , 4 )} { g ( 4 , 0 , 5 )} { g ( 4 , 0 , 6 )} | { g ( 4 , 1 , 4 )} { g ( 4 , 1 , 5 )} { g ( 4 , 1 , 6 )} | { g ( 4 , 2 , 4 )} { g ( 4 , 2 , 5 )} { g ( 4 , 2 , 6 )} || { g ( 4 , 3 , 4 )} { g ( 4 , 3 , 5 )} { g ( 4 , 3 , 6 )} | { g ( 4 , 4 , 4 )} { g ( 4 , 4 , 5 )} { g ( 4 , 4 , 6 )} | { g ( 4 , 5 , 4 )} { g ( 4 , 5 , 5 )} { g ( 4 , 5 , 6 )} || { g ( 4 , 6 , 4 )} { g ( 4 , 6 , 5 )} { g ( 4 , 6 , 6 )} | { g ( 4 , 7 , 4 )} { g ( 4 , 7 , 5 )} { g ( 4 , 7 , 6 )} | { g ( 4 , 8 , 4 )} { g ( 4 , 8 , 5 )} { g ( 4 , 8 , 6 )} |
| { g ( 4 , 0 , 7 )} { g ( 4 , 0 , 8 )} { g ( 4 , 0 , 9 )} | { g ( 4 , 1 , 7 )} { g ( 4 , 1 , 8 )} { g ( 4 , 1 , 9 )} | { g ( 4 , 2 , 7 )} { g ( 4 , 2 , 8 )} { g ( 4 , 2 , 9 )} || { g ( 4 , 3 , 7 )} { g ( 4 , 3 , 8 )} { g ( 4 , 3 , 9 )} | { g ( 4 , 4 , 7 )} { g ( 4 , 4 , 8 )} { g ( 4 , 4 , 9 )} | { g ( 4 , 5 , 7 )} { g ( 4 , 5 , 8 )} { g ( 4 , 5 , 9 )} || { g ( 4 , 6 , 7 )} { g ( 4 , 6 , 8 )} { g ( 4 , 6 , 9 )} | { g ( 4 , 7 , 7 )} { g ( 4 , 7 , 8 )} { g ( 4 , 7 , 9 )} | { g ( 4 , 8 , 7 )} { g ( 4 , 8 , 8 )} { g ( 4 , 8 , 9 )} |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| { g ( 5 , 0 , 1 )} { g ( 5 , 0 , 2 )} { g ( 5 , 0 , 3 )} | { g ( 5 , 1 , 1 )} { g ( 5 , 1 , 2 )} { g ( 5 , 1 , 3 )} | { g ( 5 , 2 , 1 )} { g ( 5 , 2 , 2 )} { g ( 5 , 2 , 3 )} || { g ( 5 , 3 , 1 )} { g ( 5 , 3 , 2 )} { g ( 5 , 3 , 3 )} | { g ( 5 , 4 , 1 )} { g ( 5 , 4 , 2 )} { g ( 5 , 4 , 3 )} | { g ( 5 , 5 , 1 )} { g ( 5 , 5 , 2 )} { g ( 5 , 5 , 3 )} || { g ( 5 , 6 , 1 )} { g ( 5 , 6 , 2 )} { g ( 5 , 6 , 3 )} | { g ( 5 , 7 , 1 )} { g ( 5 , 7 , 2 )} { g ( 5 , 7 , 3 )} | { g ( 5 , 8 , 1 )} { g ( 5 , 8 , 2 )} { g ( 5 , 8 , 3 )} |
| { g ( 5 , 0 , 4 )} { g ( 5 , 0 , 5 )} { g ( 5 , 0 , 6 )} | { g ( 5 , 1 , 4 )} { g ( 5 , 1 , 5 )} { g ( 5 , 1 , 6 )} | { g ( 5 , 2 , 4 )} { g ( 5 , 2 , 5 )} { g ( 5 , 2 , 6 )} || { g ( 5 , 3 , 4 )} { g ( 5 , 3 , 5 )} { g ( 5 , 3 , 6 )} | { g ( 5 , 4 , 4 )} { g ( 5 , 4 , 5 )} { g ( 5 , 4 , 6 )} | { g ( 5 , 5 , 4 )} { g ( 5 , 5 , 5 )} { g ( 5 , 5 , 6 )} || { g ( 5 , 6 , 4 )} { g ( 5 , 6 , 5 )} { g ( 5 , 6 , 6 )} | { g ( 5 , 7 , 4 )} { g ( 5 , 7 , 5 )} { g ( 5 , 7 , 6 )} | { g ( 5 , 8 , 4 )} { g ( 5 , 8 , 5 )} { g ( 5 , 8 , 6 )} |
| { g ( 5 , 0 , 7 )} { g ( 5 , 0 , 8 )} { g ( 5 , 0 , 9 )} | { g ( 5 , 1 , 7 )} { g ( 5 , 1 , 8 )} { g ( 5 , 1 , 9 )} | { g ( 5 , 2 , 7 )} { g ( 5 , 2 , 8 )} { g ( 5 , 2 , 9 )} || { g ( 5 , 3 , 7 )} { g ( 5 , 3 , 8 )} { g ( 5 , 3 , 9 )} | { g ( 5 , 4 , 7 )} { g ( 5 , 4 , 8 )} { g ( 5 , 4 , 9 )} | { g ( 5 , 5 , 7 )} { g ( 5 , 5 , 8 )} { g ( 5 , 5 , 9 )} || { g ( 5 , 6 , 7 )} { g ( 5 , 6 , 8 )} { g ( 5 , 6 , 9 )} | { g ( 5 , 7 , 7 )} { g ( 5 , 7 , 8 )} { g ( 5 , 7 , 9 )} | { g ( 5 , 8 , 7 )} { g ( 5 , 8 , 8 )} { g ( 5 , 8 , 9 )} |
+=======+=======+=======++=======+=======+=======++=======+=======+=======+
| { g ( 6 , 0 , 1 )} { g ( 6 , 0 , 2 )} { g ( 6 , 0 , 3 )} | { g ( 6 , 1 , 1 )} { g ( 6 , 1 , 2 )} { g ( 6 , 1 , 3 )} | { g ( 6 , 2 , 1 )} { g ( 6 , 2 , 2 )} { g ( 6 , 2 , 3 )} || { g ( 6 , 3 , 1 )} { g ( 6 , 3 , 2 )} { g ( 6 , 3 , 3 )} | { g ( 6 , 4 , 1 )} { g ( 6 , 4 , 2 )} { g ( 6 , 4 , 3 )} | { g ( 6 , 5 , 1 )} { g ( 6 , 5 , 2 )} { g ( 6 , 5 , 3 )} || { g ( 6 , 6 , 1 )} { g ( 6 , 6 , 2 )} { g ( 6 , 6 , 3 )} | { g ( 6 , 7 , 1 )} { g ( 6 , 7 , 2 )} { g ( 6 , 7 , 3 )} | { g ( 6 , 8 , 1 )} { g ( 6 , 8 , 2 )} { g ( 6 , 8 , 3 )} |
| { g ( 6 , 0 , 4 )} { g ( 6 , 0 , 5 )} { g ( 6 , 0 , 6 )} | { g ( 6 , 1 , 4 )} { g ( 6 , 1 , 5 )} { g ( 6 , 1 , 6 )} | { g ( 6 , 2 , 4 )} { g ( 6 , 2 , 5 )} { g ( 6 , 2 , 6 )} || { g ( 6 , 3 , 4 )} { g ( 6 , 3 , 5 )} { g ( 6 , 3 , 6 )} | { g ( 6 , 4 , 4 )} { g ( 6 , 4 , 5 )} { g ( 6 , 4 , 6 )} | { g ( 6 , 5 , 4 )} { g ( 6 , 5 , 5 )} { g ( 6 , 5 , 6 )} || { g ( 6 , 6 , 4 )} { g ( 6 , 6 , 5 )} { g ( 6 , 6 , 6 )} | { g ( 6 , 7 , 4 )} { g ( 6 , 7 , 5 )} { g ( 6 , 7 , 6 )} | { g ( 6 , 8 , 4 )} { g ( 6 , 8 , 5 )} { g ( 6 , 8 , 6 )} |
| { g ( 6 , 0 , 7 )} { g ( 6 , 0 , 8 )} { g ( 6 , 0 , 9 )} | { g ( 6 , 1 , 7 )} { g ( 6 , 1 , 8 )} { g ( 6 , 1 , 9 )} | { g ( 6 , 2 , 7 )} { g ( 6 , 2 , 8 )} { g ( 6 , 2 , 9 )} || { g ( 6 , 3 , 7 )} { g ( 6 , 3 , 8 )} { g ( 6 , 3 , 9 )} | { g ( 6 , 4 , 7 )} { g ( 6 , 4 , 8 )} { g ( 6 , 4 , 9 )} | { g ( 6 , 5 , 7 )} { g ( 6 , 5 , 8 )} { g ( 6 , 5 , 9 )} || { g ( 6 , 6 , 7 )} { g ( 6 , 6 , 8 )} { g ( 6 , 6 , 9 )} | { g ( 6 , 7 , 7 )} { g ( 6 , 7 , 8 )} { g ( 6 , 7 , 9 )} | { g ( 6 , 8 , 7 )} { g ( 6 , 8 , 8 )} { g ( 6 , 8 , 9 )} |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| { g ( 7 , 0 , 1 )} { g ( 7 , 0 , 2 )} { g ( 7 , 0 , 3 )} | { g ( 7 , 1 , 1 )} { g ( 7 , 1 , 2 )} { g ( 7 , 1 , 3 )} | { g ( 7 , 2 , 1 )} { g ( 7 , 2 , 2 )} { g ( 7 , 2 , 3 )} || { g ( 7 , 3 , 1 )} { g ( 7 , 3 , 2 )} { g ( 7 , 3 , 3 )} | { g ( 7 , 4 , 1 )} { g ( 7 , 4 , 2 )} { g ( 7 , 4 , 3 )} | { g ( 7 , 5 , 1 )} { g ( 7 , 5 , 2 )} { g ( 7 , 5 , 3 )} || { g ( 7 , 6 , 1 )} { g ( 7 , 6 , 2 )} { g ( 7 , 6 , 3 )} | { g ( 7 , 7 , 1 )} { g ( 7 , 7 , 2 )} { g ( 7 , 7 , 3 )} | { g ( 7 , 8 , 1 )} { g ( 7 , 8 , 2 )} { g ( 7 , 8 , 3 )} |
| { g ( 7 , 0 , 4 )} { g ( 7 , 0 , 5 )} { g ( 7 , 0 , 6 )} | { g ( 7 , 1 , 4 )} { g ( 7 , 1 , 5 )} { g ( 7 , 1 , 6 )} | { g ( 7 , 2 , 4 )} { g ( 7 , 2 , 5 )} { g ( 7 , 2 , 6 )} || { g ( 7 , 3 , 4 )} { g ( 7 , 3 , 5 )} { g ( 7 , 3 , 6 )} | { g ( 7 , 4 , 4 )} { g ( 7 , 4 , 5 )} { g ( 7 , 4 , 6 )} | { g ( 7 , 5 , 4 )} { g ( 7 , 5 , 5 )} { g ( 7 , 5 , 6 )} || { g ( 7 , 6 , 4 )} { g ( 7 , 6 , 5 )} { g ( 7 , 6 , 6 )} | { g ( 7 , 7 , 4 )} { g ( 7 , 7 , 5 )} { g ( 7 , 7 , 6 )} | { g ( 7 , 8 , 4 )} { g ( 7 , 8 , 5 )} { g ( 7 , 8 , 6 )} |
| { g ( 7 , 0 , 7 )} { g ( 7 , 0 , 8 )} { g ( 7 , 0 , 9 )} | { g ( 7 , 1 , 7 )} { g ( 7 , 1 , 8 )} { g ( 7 , 1 , 9 )} | { g ( 7 , 2 , 7 )} { g ( 7 , 2 , 8 )} { g ( 7 , 2 , 9 )} || { g ( 7 , 3 , 7 )} { g ( 7 , 3 , 8 )} { g ( 7 , 3 , 9 )} | { g ( 7 , 4 , 7 )} { g ( 7 , 4 , 8 )} { g ( 7 , 4 , 9 )} | { g ( 7 , 5 , 7 )} { g ( 7 , 5 , 8 )} { g ( 7 , 5 , 9 )} || { g ( 7 , 6 , 7 )} { g ( 7 , 6 , 8 )} { g ( 7 , 6 , 9 )} | { g ( 7 , 7 , 7 )} { g ( 7 , 7 , 8 )} { g ( 7 , 7 , 9 )} | { g ( 7 , 8 , 7 )} { g ( 7 , 8 , 8 )} { g ( 7 , 8 , 9 )} |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+
| { g ( 8 , 0 , 1 )} { g ( 8 , 0 , 2 )} { g ( 8 , 0 , 3 )} | { g ( 8 , 1 , 1 )} { g ( 8 , 1 , 2 )} { g ( 8 , 1 , 3 )} | { g ( 8 , 2 , 1 )} { g ( 8 , 2 , 2 )} { g ( 8 , 2 , 3 )} || { g ( 8 , 3 , 1 )} { g ( 8 , 3 , 2 )} { g ( 8 , 3 , 3 )} | { g ( 8 , 4 , 1 )} { g ( 8 , 4 , 2 )} { g ( 8 , 4 , 3 )} | { g ( 8 , 5 , 1 )} { g ( 8 , 5 , 2 )} { g ( 8 , 5 , 3 )} || { g ( 8 , 6 , 1 )} { g ( 8 , 6 , 2 )} { g ( 8 , 6 , 3 )} | { g ( 8 , 7 , 1 )} { g ( 8 , 7 , 2 )} { g ( 8 , 7 , 3 )} | { g ( 8 , 8 , 1 )} { g ( 8 , 8 , 2 )} { g ( 8 , 8 , 3 )} |
| { g ( 8 , 0 , 4 )} { g ( 8 , 0 , 5 )} { g ( 8 , 0 , 6 )} | { g ( 8 , 1 , 4 )} { g ( 8 , 1 , 5 )} { g ( 8 , 1 , 6 )} | { g ( 8 , 2 , 4 )} { g ( 8 , 2 , 5 )} { g ( 8 , 2 , 6 )} || { g ( 8 , 3 , 4 )} { g ( 8 , 3 , 5 )} { g ( 8 , 3 , 6 )} | { g ( 8 , 4 , 4 )} { g ( 8 , 4 , 5 )} { g ( 8 , 4 , 6 )} | { g ( 8 , 5 , 4 )} { g ( 8 , 5 , 5 )} { g ( 8 , 5 , 6 )} || { g ( 8 , 6 , 4 )} { g ( 8 , 6 , 5 )} { g ( 8 , 6 , 6 )} | { g ( 8 , 7 , 4 )} { g ( 8 , 7 , 5 )} { g ( 8 , 7 , 6 )} | { g ( 8 , 8 , 4 )} { g ( 8 , 8 , 5 )} { g ( 8 , 8 , 6 )} |
| { g ( 8 , 0 , 7 )} { g ( 8 , 0 , 8 )} { g ( 8 , 0 , 9 )} | { g ( 8 , 1 , 7 )} { g ( 8 , 1 , 8 )} { g ( 8 , 1 , 9 )} | { g ( 8 , 2 , 7 )} { g ( 8 , 2 , 8 )} { g ( 8 , 2 , 9 )} || { g ( 8 , 3 , 7 )} { g ( 8 , 3 , 8 )} { g ( 8 , 3 , 9 )} | { g ( 8 , 4 , 7 )} { g ( 8 , 4 , 8 )} { g ( 8 , 4 , 9 )} | { g ( 8 , 5 , 7 )} { g ( 8 , 5 , 8 )} { g ( 8 , 5 , 9 )} || { g ( 8 , 6 , 7 )} { g ( 8 , 6 , 8 )} { g ( 8 , 6 , 9 )} | { g ( 8 , 7 , 7 )} { g ( 8 , 7 , 8 )} { g ( 8 , 7 , 9 )} | { g ( 8 , 8 , 7 )} { g ( 8 , 8 , 8 )} { g ( 8 , 8 , 9 )} |
+-------+-------+-------++-------+-------+-------++-------+-------+-------+"""
| Sudoku Strategies - Pencil Marks | 65ec2fd162762513a643b2e6 | [
"Algorithms",
"Puzzles",
"Set Theory",
"Strings"
] | https://www.codewars.com/kata/65ec2fd162762513a643b2e6 | 5 kyu |
## Task
> Can you save the damsel (young lady) in distress?
Given a string depicting the road ahead for our warrior (you) to get to the young lady, return a boolean indicating whether you succeed or not.
## Specification
### Game
- The world exists of surface <code>'.'</code>, obstacles <code>'#'</code> and water <code>'~'</code>.
- The warrior <code>'w'</code> starts on the left-most tile and is able to run, jump or swim.
- The warrior can only move from left to right.
- The young lady <code>'p'</code> is trapped on an isle. An isle is an area of surface surrounded from both sides by either obstacles or water. Note that she cannot swim.
- The warrior is <b>successful</b> if <b>the isle can be reached without causing harm to the young lady</b>. It does not matter whether you reach the isle on the left or right side of her, as long you don't jump right on top of her. You may assume once the isle is reached, both the lady and warrior are free to move towards eachother.
```python
'w...#...~~..p..##' # jump over one obstacle and swim through two tiles of water
```
### Stats
- The warrior can initially jump over one tile.
- The jumping distance is extended by one tile each time a jumping booster <code>'j'</code> is picked up. A booster is always located on the surface, but never on the isle you want to reach.
```python
'w...#..' # can jump over one obstacle
'w..##..' # can not jump over two obstacles
'w.j##..' # can jump over two obstacles with a booster
```
- The warrior can initially swim two tiles.
- The swimming distance is extended by one tile each time an oxygen pack <code>'o'</code> is picked up. A pack is always located on the surface, but never on the isle you want to reach.
```python
'w...~..' # can swim one tile
'w..~~..' # can swim two tiles
'w.~~~..' # can not swim three tiles
'wo~~~..' # can swim three tiles with oxygen pack
```
### Behavior
#### Running
- The warrior can only run from left to right
- The warrior always runs to the next tile, if that tile is a surface tile.
- If the next tile holds an item (jumping booster, oxygen pack), that item is automatically picked up, when reaching that tile. Warrior stats get updated as well.
```python
'w...#..' # runs 3 tiles, before reaching obstacle
'w...~..' # runs 3 tiles, before reaching water
'w.jo#..' # runs 3 tiles, picking up jumping booster and oxygen pack along the way
```
#### Swimming
- The warrior can only swim from left to right
- The warrior can swim any distance from one tile upto the oxygen capacity.
- The warrior decides to swim only if all these conditions are met:
- the warrior did not decide to run
- the next tile is water
- there are no obstacles in the water or at the end of the water (the warrior needs to be able to swim to the next surface tile without obstacles in the way)
- the warrior has sufficient oxygen to swim the distance
```python
'w~..' # swims one tile
'w~~..' # swims two tiles
'w~~~..' # will not swim (see jumping section)
'wo~~~..' # swims three tiles, after picking up an oxygen pack
'w~p.' # swims one tile, and can resurface to meet the young lady
```
#### Jumping
- The warrior can only jump from left to right
- The warrior can only jump the exact jumping distance as depicted in the stats.
- The warrior decides to jump only if all these conditions are met:
- the warrior did not decide to run or swim
- the next tile is either water or an obstacle
- the warrior does not jump onto another obstacle
- in case the tile jumped on is a surface tile:
- the warrior does not jump right on top of the young lady (this would cause harm to her)
- in case the tile jumped on is a water tile:
- there are no obstacles in the water ahead or at the end of the water (the warrior needs to be able to swim to the next surface tile without obstacles in the way)
- the warrior has sufficient oxygen to swim the distance
```python
'w#..' # jumps over one tile
'wj##..' # jumps over two tiles, after picking up a jumping booster
'wj#...' # jumps over two tiles (eventhough only one obstacle), after picking up a jumping booster
'wj~#..' # jumps over two tiles (swimming not an option here), after picking up a jumping booster
'w~~~..' # jump over one tile (not enough oxygen to immediately start swimming), then continue swimming two tiles
'w#~~..' # jump over one obstacle, then continue swimming two tiles
```
#### Staying on the current tile
- If none of the conditions above were met to either run, swim or jump, the warrior just stays on the current tile.
- In this case, the warrior is not able to reach the young lady.
```python
'w~~~~..' # too far to swim, even if jumping into the water first
'w##..' # too far to jump
'w..j#.#..' # would jump onto another obstacle
'w..j.~#~~~..' # too far to swim after jumping over two tiles
'w.jjj#.p#..' # jump over the isle of the young lady
'w.jjj#.p~~.' # jump over the isle of the young lady into the water, but can't swim in other direction
'wj#.p#' # jump right on top of the young lady
```
| algorithms | def solve(game: str) - > bool:
n, target = len(game), game . index('p')
def try_jump(pos, jump, oxygen):
j = pos + jump
if j >= n:
return n
if game[j] == '~':
return try_swim(j, 0, oxygen)
return j if game[j] not in 'p#' else n
def try_swim(pos, jump, oxygen):
i = pos
while i < n and game[i] == '~':
i += 1
if i >= n:
return n
if game[i] != '#' and pos + oxygen >= i:
return i
return try_jump(pos, jump, oxygen) if jump else n
pos, jump, oxygen = 0, 1, 2
while pos < target:
if game[pos] == 'o':
oxygen += 1
if game[pos] == 'j':
jump += 1
pos += 1
if game[pos] == '#':
pos = try_jump(pos, jump, oxygen)
elif game[pos] == '~':
pos = try_swim(pos, jump, oxygen)
return pos < n and all(x not in '#~' for x in game[target: pos])
| Damsel in Distress | 65b65ef7b5154156604ed782 | [
"Algorithms",
"Simulation"
] | https://www.codewars.com/kata/65b65ef7b5154156604ed782 | 5 kyu |
You will be given a rectangular array representing a "map" with three types of spaces:
- "+" bombs: when activated, their explosion activates any bombs directly above, below, left, or right of the "+" bomb.
- "x" bombs: when activated, their explosion activates any bombs placed in any of the four diagonal directions next to the "x" bomb.
- Empty spaces "0".
The goal is simple: **given a map, return the minimum number of bombs that need to be set off for all bombs to be destroyed by the chain reaction**.
Let's look at some examples:
```
[
["+", "+", "+", "0", "+", "+", "+"],
["+", "+", "+", "0", "0", "+", "+"]
]
```
For the map above, the answer is `2`; to explode all bombs you just need to set off one "+" bomb in the right cluster and one in the left cluster.
```
[
["x", "0", "x"],
["x", "x", "x"]
]
```
For the map above, the answer is `3`; clearly setting off the three bottom "x" bombs is enough, and no less than three bombs suffice.
```
[
["x", "x", "x", "0", "x"],
["x", "x", "x", "x", "x"],
["x", "x", "x", "0", "x"]
]
```
For the map above, the answer is `3`; setting off the three rightmost bombs in the middle row will do the trick.
### Examples
```
min_bombs_needed([
["+", "+", "+", "0", "+", "+", "+"],
["+", "+", "+", "0", "0", "+", "+"]
]) β 2
min_bombs_needed([
["x", "0", "x"],
["x", "x", "x"]
]) β 3
min_bombs_needed([
["x", "x", "x", "0", "x"],
["x", "x", "x", "x", "x"],
["x", "x", "x", "0", "x"]
]) β 3
```
### Notes
- Note that both "+" and "x" bombs have an "explosion range" of 1.
- 100 random tests with grids from 3x3 to 7x7 | reference | def min_bombs_needed(grid):
def flood(i, j):
seen = set()
bag = {(i, j)}
while bag:
seen |= bag
bag = {(x, y) for i, j in bag for x, y in neighs_of(i, j)
if (x, y) not in seen and is_ok(x, y)}
return seen
def is_ok(x, y): return 0 <= x < X and 0 <= y < Y and grid[x][y] in '+x'
def neighs_of(x, y):
match grid[x][y]:
case '+': return (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)
case 'x': return (x + 1, y + 1), (x - 1, y - 1), (x - 1, y + 1), (x + 1, y - 1)
X = len(grid)
Y = X and len(grid[0])
gs = set()
for i, r in enumerate(grid):
for j, c in enumerate(r):
if c in '+x':
gs . add(frozenset(flood(i, j)))
yup = True
while yup:
yup = next((s for s in gs if any(s < ss for ss in gs)), None)
if yup:
gs . discard(yup)
return len(gs)
| Chain Reaction - Minimum Bombs Needed | 64c8a9b8f7c1b7000fdcdafb | [] | https://www.codewars.com/kata/64c8a9b8f7c1b7000fdcdafb | 5 kyu |
## Introduction
There is a war and nobody knows - the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began.
The battlefield is a complete chaos, riddled with trenches and full of scattered troops. We need a good map of what's going on.
## Task
Write a function that accepts a two-line `battlefield` string that contains letters on the ground and in trenches (could be just ground, just trench, or any amount of both alternating):
```
"pwss s" "\n"
"----|qdd|-"
```
then emulates the fight and returns the final frontline map as string:
```
"LLLL|LLR|L"
```
where `L` means land controlled by the left side letters,
`R` means land controlled by the right side letters,
and the `|`s are preserved.
```if:c
**For C warriors:** returned string must be freeable (i.e. allocated with `malloc` or `calloc`).
```
The left side letters and their power:
```
w - 4
p - 3
b - 2
s - 1
```
The right side letters and their power:
```
m - 4
q - 3
d - 2
z - 1
```
These letters are spread randomly across the battlefield. There are no other letters. The only horizontal gaps in between letters are trench borders (single `'|'`). The top and the bottom line are separated by `'\n'` and padded with `' '` and `'-'` respectively. The battlefield is always valid and non-empty.
**NOTE:** "left side" and "right side" letters don't refer to the literal left and right sides of the battlefield! See about ***Alphabet war collection*** below.
Fight rules:
* Letters act in order, from left to right.
* Their actions are also directed to the right.
* Actions depend on the next letter to the right. If it's an ally, they join forces (adding their fire power together). If it's an enemy, it's attacked.
* If defending letter has less power than the attacking letters, attackers claim the land and their power is reduced by the power of defender. Attackers then continue to attack or join forces with allies.
* If defending letter and attacking letters have equal power, attackers still get the land, but their attack is exhausted. The next letter after the defender starts a new chain of attacks.
* If defending letter has more power than the attacking letters, it keeps the land. Its power is reduced by the power of attackers and then used for attacking.
* The first letter in a trench has double amount of defense power. If it survives and attacks afterwards, it's not allowed to use more points than usual.
* While joining forces or attacking, letters can stay on the same level or go down into a trench, but they never leave trenches. They stop at the right end of the trench, and the next letter on the ground starts a new chain of attacks.
This should be easier to understand by example:
## Example
```
trench_assault("pwss s\n----|qdd|-"); // => "LLLL|LLR|L"
```
Let's make it more visual:
```
// LLLL|LLR|L
"pwss s" "\n"
"----|qdd|-"
```
First, we have 4 left side letters on the ground, with combined power of `3 + 4 + 1 + 1 = 9`. This ground is automatically `LLLL`, cause there's no one to attack them from the left.
Then, the trench starts: `|`.
First, it has a right side letter `q`. Being at the defence line of the trench, it has double defence power of `3 * 2 = 6`. It gets successfully attacked by the left side letters and becomes `L`.
Left side still has `9 - 6 = 3` attack points, so they defeat `d` with `2` points, getting another `L`.
As they have `1` point left, the second `d` with `2` points holds the line, so its square remains `R`.
The trench ends: `|`
`d` still has `2 - 1 = 1` point to attack, but letters never attack the ground from a trench, so `s` gets to keep that ground as `L`.
### There are more examples in the sample tests, showing off individual mechanics one by one. Please look through these!
- - -
## Alphabet war collection
This kata draws direct inspiration from
[dcieslak](https://www.codewars.com/users/dcieslak/)'s
**Alphabet war** series.
You might want to complete the
[originals](https://www.codewars.com/kata/59377c53e66267c8f6000027)
first, so you're familiar with the main concepts and have a few useful pieces of code prepared. | reference | def trench_assault(bf: str) - > str:
power = {c: p for p, c in enumerate('wpbs zdqm', - 4)}
s = '' . join(b if b . isalpha() or b == '|' else a for a,
b in zip(* bf . split('\n')))
out = []
is_up = bf[0]. isalpha()
p, go_trench = 0, 1
for c in s:
if c == '|':
p = is_up and p
go_trench = is_up + 1
is_up ^= 1
else:
q = power[c]
v = p + q * (go_trench if p * q < 0 else 1)
c = 'R' if (v or p) > 0 else 'L'
p = v if p * v >= 0 else min((v, q), key=abs)
go_trench = 1
out . append(c)
return '' . join(out)
| Alphabet wars - trench assault | 60df8c24fe1db50031d04e02 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/60df8c24fe1db50031d04e02 | 4 kyu |
_Note:_
This Kata is intended to be a more difficult version of [Getting the Letter with Tail](https://www.codewars.com/kata/649debb7eee1d126c2dcfe56), finding the pattern for the linked Kata might help this one.
___
### Letter with Tail/Head:
We got a string of letters made up by __`O`s and/or `X`s (or an empty string).__
In this Kata, a `Letter with Tail/Head` can be either one of the following:
1. `O` followed by 1 or more `X`, such as `OX`, `OXX`, `OXXX`, etc.
2. `X` followed by 1 or more `O`, such as `XO`, `XOO`, `XOOO`, etc.
3. 2 or more `O` followed by `X`, such as `OOX`, `OOOX`, etc.
4. 2 or more `X` followed by `O`, such as `XXO`, `XXXO`, etc.
___
### Total Possible Amount:
(We use parentheses to show the `Letter with Tails/Heads`)
In most of the cases, we can find more than 1 `Letter with Tails/Heads` in the input string.
When you search the input string for `Letter with Tails/Heads`, each character can only be used in one of the `Letter with Tails/Heads`(or not used).
(In other words, the `Letter with Tails/Heads` cannot overlap each other.)
For example, input string is `'OXXO'`
```
(OX)XO, (OXX)O, O(XXO), OX(XO), (OX)(XO)
```
There are `5` of them. We call the number `total possible amount`.
___
### Task:
* Input: Getting a string of letters made up by `O`s and/or `X`s (or an empty string).
* Return: Return the `total possible amount` for the input string.
___
### Example:
Input String is `'XOOOXXO'`
```
1 Letter with Tail/Head:
(XO)OOXXO, (XOO)OXXO, (XOOO)XXO, X(OOOX)XO, XO(OOX)XO, XOO(OX)XO,
XOO(OXX)O, XOOO(XXO), XOOOX(XO)
2 Letter with Tails/Heads:
(XO)(OOX)XO, (XO)O(OX)XO, (XO)O(OXX)O, (XO)OO(XXO), (XO)OOX(XO), (XOO)(OX)XO,
(XOO)(OXX)O, (XOO)O(XXO), (XOO)OX(XO), (XOOO)(XXO), (XOOO)X(XO), X(OOOX)(XO),
XO(OOX)(XO), XOO(OX)(XO)
3 Letter with Tails/Heads:
(XO)(OOX)(XO), (XO)O(OX)(XO), (XOO)(OX)(XO)
```
So the answer is `26`.
___
### Sample Tests:
```
Input => Output
'' => 0
'OOO' => 0
'XX' => 0
'OXX' => 2
'OOXOO' => 4
'XXXXO' => 4
'OXXO' => 5
'OXOXOX' => 12
'XOOOXXO' => 26
'XXXOOOXXXOOO' => 110
'XXOOXXOOXXOOXXOOXXOOXXOOXXOOXXOOXXOOXXOO' => 529374875
```
| algorithms | def total_possible_amount(s):
arr = [0, 0]
for j, (c1, c2) in enumerate(zip(s, s[1:])):
i = j - 1
while i >= 0 and s[i] == c1:
i -= 1
acc = j - i + sum(arr[i + 1: j + 1]
) if c1 != c2 else 0 if i == - 1 else arr[i] + 1
arr . append(arr[- 1] + acc)
return arr[- 1]
| Getting the Letter with Tail/Head | 64b59f845cce08157b725b12 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/64b59f845cce08157b725b12 | 5 kyu |
### Letter with Tail
We got a string of letters made up by __`O`s and/or `X`s (or an empty string).__
In this Kata, a `Letter with Tail` can be either one of the following:
1. `O` followed by 1 or more `X`, such as `OX`, `OXX`, `OXXX`, etc.
2. `X` followed by 1 or more `O`, such as `XO`, `XOO`, `XOOO`, etc.
___
### Total Possible Amount
In most of the cases, we can find more than 1 way to get `Letter with Tails`.
And we are looking for the cases: Every single character from the input cannot occur in two or more different `Letter with Tails`.
For example, input string is `'OXXO'`
(We use parentheses to show the `Letter with Tails` we got in the example)
```
(OX)XO, (OXX)O, OX(XO), (OX)(XO)
```
There are `4` of them. We call the number `total possible amount`.
___
### Task
* Input: Getting a string of letters made up by `O`s and/or `X`s (or an empty string).
* Return: Return the `total possible amount` for the input string.
`0` <= string length <= `90`
With the string length limit, the answer will not be bigger than _2^64_.
___
### Example:
Input String is `'XOOOXXO'`
```
1 Letter with Tail:
(XO)OOXXO, (XOO)OXXO, (XOOO)XXO, XOO(OX)XO, XOO(OXX)O, XOOOX(XO)
2 Letter with Tails:
(XO)O(OX)XO, (XO)O(OXX)O, (XO)OOX(XO), (XOO)(OX)XO, (XOO)(OXX)O, (XOO)OX(XO), (XOOO)X(XO), XOO(OX)(XO)
3 Letter with Tails:
(XO)O(OX)(XO), (XOO)(OX)(XO)
```
So the answer is `16`.
___
### Sample Tests:
```
Input => Output
'' => 0
'OOO' => 0
'XX' => 0
'XXXXO' => 1
'OXX' => 2
'OXOX' => 4
'OXXO' => 4
'XOXOX' => 7
'XOOOXXO' => 16
'XOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXOXO' => 63245985
```
| algorithms | import re
def total_possible_amount(s):
x = y = 1
for i in map(len, reversed(re . findall('O+|X+', s . lstrip(s[: 1])))):
x, y = x * i + y, x
return x - 1
| Getting the Letter with Tail | 649debb7eee1d126c2dcfe56 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/649debb7eee1d126c2dcfe56 | 5 kyu |
<h1 style="color:#74f"> Task </h1>
Can you decide whether or not some `walls` divide a rectangular `room` into two or more
partitions?
<br>
<h1 style="color:#74f"> Input </h1>
`width` - The width of the room
`height` - The height of the room
`walls` - A list of line segments
<br>
<h1 style="color:#74f"> Output </h1>
`true` if the walls divide the room into two or more partitions, otherwise `false`.
<br>
<h1 style="color:#74f"> Examples </h1>
![oops, please raise an issue about this broken image](https://raw.githubusercontent.com/JomoPipi/codewars-images/main/images/extrue.png)
![oops, please raise an issue about this broken image](https://raw.githubusercontent.com/JomoPipi/codewars-images/main/images/extrue2.png)
![oops, please raise an issue about this broken image](https://raw.githubusercontent.com/JomoPipi/codewars-images/main/images/exfalse.png)
<hr>
## Notes:
- line segments are given as pairs of points
### Tests:
- 50 fixed tests
- 100 random testests with up to 8 walls
- 100 random with up to 15 walls
- 100 randrom with up to 100 walls
- points and walls may exist outside of boundary walls. But any partitions formed outside do NOT count.
- the coordinate (`width`, `height`) is a corner of the room, and so is (`0`, `0`).
- reading the pictures: origin in the top left corner, x axis going to the right, and y axis going down.
- tests have up to 100 walls
- make sure your arithmetic avoids floating point errors.
- there may be duplicate line segments
<br>
<center>
Enjoy!
</center> | algorithms | from fractions import Fraction
from collections import namedtuple
Point = namedtuple("Point", "x y")
def delete_dots(lines):
return [line for line in lines if line . p1 != line . p2]
class Line:
def __init__(self, p1, p2, width, height) - > None:
self . p1, self . p2 = sorted([p1, p2])
self . intersections = {}
self . formula = []
self . special = ""
if self . p1 . x == self . p2 . x:
self . special = "V"
if self . p1 . y == self . p2 . y:
self . special = "H"
self . find_formula()
self . cut_points(width, height)
def __repr__(self) - > str:
return f"| { self . p1 , self . p2 , self . formula } |"
def find_formula(self):
if self . special:
return
slope = Fraction(self . p1 . y - self . p2 . y,
self . p1 . x - self . p2 . x)
self . formula = [slope, - (slope * self . p1 . x), self . p1 . y]
def calculate_point_by_x(self, x):
return Point(x, self . formula[0] * x + self . formula[1] + self . formula[2])
def calculate_point_by_y(self, y) - > Point:
right = y - self . formula[2] - self . formula[1]
return Point(Fraction(self . formula[0]. denominator, self . formula[0]. numerator) * right, y)
def handle_special_horizontal_cut_points(self, width):
self . p1, self . p2 = max(self . p1, Point(0, self . p1 . y)), min(
self . p2, Point(width, self . p2 . y))
def handle_special_vertical_cut_points(self, height):
self . p1, self . p2 = max(self . p1, Point(self . p1 . x, 0)), min(
self . p2, Point(self . p2 . x, height))
def handle_normal_cut_points(self, width, height):
if self . p1 . x < 0:
self . p1 = self . calculate_point_by_x(0)
if self . p2 . x > width:
self . p2 = self . calculate_point_by_x(width)
if (self . p1 . y < 0 and self . p2 . y < 0) or (self . p1 . y > height and self . p2 . y > height):
self . p1, self . p2 = Point(0, 0), Point(0, 0)
return
if self . p1 . y < 0:
self . p1 = self . calculate_point_by_y(0)
elif self . p1 . y > height:
self . p1 = self . calculate_point_by_y(height)
if self . p2 . y < 0:
self . p2 = self . calculate_point_by_y(0)
elif self . p2 . y > height:
self . p2 = self . calculate_point_by_y(height)
def cut_points(self, width, height):
if self . p2 . x < 0 or self . p1 . x > width or (self . p1 . y < 0 and self . p2 . y < 0) or (self . p1 . y > height and self . p2 . y > height):
self . p1, self . p2 = Point(0, 0), Point(0, 0)
elif self . special == "H":
self . handle_special_horizontal_cut_points(width)
elif self . special == "V":
self . handle_special_vertical_cut_points(height)
else:
self . handle_normal_cut_points(width, height)
def add_intersection(line1: Line, line2: Line, key):
if key not in line1 . intersections:
line1 . intersections[key] = set([line1])
if key not in line2 . intersections:
line2 . intersections[key] = set([line2])
line1 . intersections[key]. add(line2)
line2 . intersections[key]. add(line1)
def handle_vertical_intersection(line1: Line, line2: Line):
if line2 . special == "V":
return
elif line2 . special == "H":
if line2 . p1 . x <= line1 . p1 . x <= line2 . p2 . x and line1 . p1 . y <= line2 . p1 . y <= line1 . p2 . y:
add_intersection(line1, line2, Point(line1 . p1 . x, line2 . p1 . y))
else:
res = line2 . calculate_point_by_x(line1 . p1 . x)
if line1 . p1 . y <= res . y <= line1 . p2 . y and line2 . p1 . x <= res . x <= line2 . p2 . x:
add_intersection(line1, line2, res)
def handle_horizontal_intersection(line1: Line, line2: Line):
if line2 . special == "H":
return
res = line2 . calculate_point_by_y(line1 . p1 . y)
if line1 . p1 . x <= res . x <= line1 . p2 . x and line2 . p1 . x <= res . x <= line2 . p2 . x:
add_intersection(line1, line2, res)
def handle_normal_intersection(line1: Line, line2: Line):
if line1 . formula[0] == line2 . formula[0]:
return
left: Fraction = line1 . formula[0] - line2 . formula[0]
right = line2 . formula[1] + line2 . formula[2] - \
line1 . formula[1] - line1 . formula[2]
res = line1 . calculate_point_by_x(
Fraction(left . denominator, left . numerator) * right)
if line1 . p1 . x <= res . x <= line1 . p2 . x and line2 . p1 . x <= res . x <= line2 . p2 . x:
add_intersection(line1, line2, res)
def find_intersections(lines):
for i in range(len(lines) - 1):
for j in range(i + 1, len(lines)):
line1, line2 = sorted([lines[i], lines[j]],
key=lambda x: x . special, reverse=True)
if line1 . special == "V":
handle_vertical_intersection(line1, line2)
elif line1 . special == "H":
handle_horizontal_intersection(line1, line2)
else:
handle_normal_intersection(line1, line2)
def handle_vertical_add_slop(line1: Line, line2: Line, used: set):
if line1 . p1 . x == line2 . p1 . x and line1 . p2 . y >= line2 . p1 . y:
line1 . p2 = max(line1 . p2, line2 . p2)
used . add(line2)
def handle_horizontal_add_slop(line1: Line, line2: Line, used: set):
if line1 . p1 . y == line2 . p1 . y and line1 . p2 . x >= line2 . p1 . x:
line1 . p2 = max(line1 . p2, line2 . p2)
used . add(line2)
def handle_normal_add_slop(line1: Line, line2: Line, used: set):
if line1 . formula[0] != line2 . formula[0] or line1 . calculate_point_by_x(0) != line2 . calculate_point_by_x(0):
return
if line1 . p2 . x >= line2 . p1 . x:
used . add(line2)
line1 . p2 = max(line1 . p2, line2 . p2)
def added_same_slop(lines):
used = set()
for i in range(len(lines) - 1):
line1: Line = lines[i]
if line1 in used:
continue
for j in range(i + 1, len(lines)):
line2: Line = lines[j]
if line2 in used or line1 . special != line2 . special:
continue
if line1 . special == "V":
handle_vertical_add_slop(line1, line2, used)
elif line1 . special == "H":
handle_horizontal_add_slop(line1, line2, used)
else:
handle_normal_add_slop(line1, line2, used)
return [line for line in lines if line not in used]
def create_lines(w, h, walls):
specials = [Line(Point(0, 0), Point(w, 0), w, h), Line(Point(0, 0), Point(0, h), w, h), Line(
Point(0, h), Point(w, h), w, h), Line(Point(w, 0), Point(w, h), w, h)]
others = [Line(wall[0], wall[1], w, h)
for wall in walls if wall[0] != wall[1]]
others = [line for line in others if not ((line . special == "H" and (line . p1 . y == 0 or line . p1 . y == h)) or (
line . special == "V" and (line . p1 . x == 0 or line . p1 . x == w)))]
return (sorted(others + specials, key=lambda x: (x . p1, x . p2)), set(specials))
def delete_specials_intersections(specials):
for spe in specials:
spe . intersections . clear()
def solve(lines, specials):
current_used, used, special_check = set(), set(), set()
lines = [line for line in lines if line not in specials]
def dfs(parents, line: Line):
for key, next_parents in line . intersections . items():
for next_line in next_parents:
if next_line in parents:
continue
if next_line in current_used:
return True
current_used . add(next_line)
if next_line in specials:
special_check . add(key)
if len(special_check) == 2:
return True
if dfs(next_parents, next_line):
return True
for line in lines:
if line in used:
continue
current_used . add(line)
if dfs(set([line]), line):
return True
used |= current_used
current_used . clear()
special_check . clear()
return False
def has_partitions(width, height, walls):
lines, specials = create_lines(width, height, walls)
lines = delete_dots(lines)
lines = added_same_slop(lines)
find_intersections(lines)
delete_specials_intersections(specials)
return solve(lines, specials)
| Partition Detection | 60f5868c7fda34000d556f30 | [
"Geometry"
] | https://www.codewars.com/kata/60f5868c7fda34000d556f30 | 2 kyu |
# Background
This kata is inspired by [Don't give me five! Really! by zappa78](https://www.codewars.com/kata/621f89cc94d4e3001bb99ef4), which is a step-up from the original [Don't give me five by user5036852](https://www.codewars.com/kata/5813d19765d81c592200001a).
The current kata is much harder than both of those. If you are having trouble with this kata, it is recommended that you try one of the above.
# Problem Description
In this kata, you are required to build a function that receives two arguments, `a` and `b`, and returns the number of integers between `a` and `b` inclusive that:
* Do __not__ contain the digit `5`.
* The following numbers contain the digit 5: `57`, `512`.
* Are __not__ divisible by `5`.
* The following numbers are divisible by 5: `100`, `420`.
* Do __not__ have exactly `5` digits.
* The following numbers have 5 digits: `12345`, `32767`.
* Are __not__ perfect 5th powers.
* The following numbers are 5th powers: `1`, `32`, `243`, `1024`.
Here are the first 10 __positive__ numbers that should be counted: `2`, `3`, `4`, `6`, `7`, `8`, `9`, `11`, `12`, `13`. Negative numbers also count if they are in range.
# Input Constraints
* Fixed test cases: `-100` β€Β `a, b`Β β€Β `100` (one hundred)
* Fixed test cases: `-10^5` β€Β `a, b`Β β€Β `10^5` (one hundred thousand)
* Fixed test cases: `-10^10` β€Β `a, b`Β β€Β `10^10` (ten billion)
* Fixed test cases: `-10^15` β€Β `a, b`Β β€Β `10^15` (one quadrillion)
# Edge Cases
* `0` is a multiple of `5` and a 5th power.
* Note that 5th powers can be negative.
* If `a` is greater than `b`, return 0. | algorithms | from bisect import bisect_left
def not_has_or_div_by_5_up_to(n_as_str): # n >= 0; inclusive of n
if len(n_as_str) == 0 or n_as_str == "0":
return 0
if n_as_str[0] == '0':
return not_has_or_div_by_5_up_to(n_as_str[1:])
i = int(n_as_str[0])
if len(n_as_str) == 1:
return i if i < 5 else i - 1
count = 8 * (9 * * (len(n_as_str) - 2))
count *= i if i <= 5 else i - 1
if i != 5:
count += not_has_or_div_by_5_up_to(n_as_str[1:])
return count
def not_has_or_div_by_5_between(a, b): # inclusive; 0 <= a <= b
res = not_has_or_div_by_5_up_to(str(b))
if a > 0:
res -= not_has_or_div_by_5_up_to(str(a - 1))
return res
# powers of 5 not (5 digits or containing 5 or div by 5)
power5_not_5s = [1, 32, 243, 1024, 7776]
for i in range(10, 1101):
x = i * * 5
if '5' in str(x) or x % 5 == 0:
continue
power5_not_5s . append(x)
def num_power5_not_5s_between(a, b): # inclusive
if a < 0:
if b < 0:
a, b = - b, - a
else:
return num_power5_not_5s_between(0, - a) + num_power5_not_5s_between(0, b)
# a, b >= 0
i_a = bisect_left(power5_not_5s, a)
i_b = bisect_left(power5_not_5s, b, i_a)
if power5_not_5s[i_b] == b:
i_b += 1
return i_b - i_a
not_has_or_div_by_5_below_10000 = not_has_or_div_by_5_up_to("10000")
diff_5digits = not_has_or_div_by_5_up_to(
"100000") - not_has_or_div_by_5_below_10000
def no_5s_ignore_power5(a, b): # 0 <= a <= b
if a == 0:
if 10000 <= b and b <= 100000:
return not_has_or_div_by_5_below_10000
count = not_has_or_div_by_5_up_to(str(b))
if b > 100000:
count -= diff_5digits
return count
return no_5s_ignore_power5(0, b) - no_5s_ignore_power5(0, a - 1)
def no_5s(a, b):
if a > b:
return 0
if a < 0:
if b <= 0:
a, b = - b, - a
else:
return no_5s(0, - a) + no_5s(0, b)
return no_5s_ignore_power5(a, b) - num_power5_not_5s_between(a, b)
| No More 5's, Ever | 6465e051c6ec5c000f3e67c4 | [
"Number Theory",
"Mathematics",
"Memoization"
] | https://www.codewars.com/kata/6465e051c6ec5c000f3e67c4 | 3 kyu |
This kata is a variation of [Cody Block's Pro Skater](https://www.codewars.com/kata/5ba0adafd6b09fd23c000255). Again, you are given a list of `N` possible skateboarding tricks, and you need to design a run where each trick `i` is performed `t_i` times (`i = 1, ..., N`), optimally chosen to amaze your judges.
Performing trick `i` for the first time will score `s_i` points, where `s_i > 0`. Because judges dislike repetition, each successive performance of trick `i` will score `m_i` times the previous performance, where `0 < m_i < 1`. The total score of a run is obtained by summing the score of all `N` tricks, each performed `t_i` times.
Finally, each time trick `i` is performed, it only succeeds with probability `p_i` such that `0 < p_i < 1`. If even a single failure occurs, the total score of the run is set to zero.
Your goal is to choose `t_1, ..., t_N` such that the expected score of the run is maximized. **In this "continuum version" of the kata, each `t_i` can be real number, i.e., we allow for fractional and negative number of repetitions of each trick.** Extend the expected score to real numbers using the most straightforward mathematical approach.
## Input
You are given three parameters `s`, `m`, and `p`, each a list of `N` real numbers. Following the above notation, the base score of each trick is given by `s`; the score multiplier by `m`; and the success probability by `p`.
The number of tricks `N` will range from `1` to `1000`, so a fast solution is required.
## Output
Output a list of `N` numbers `t_1, ..., t_N`, corresponding to the optimal number of each trick performed.
In example tests, each `t_i` should be within `1e-4` of the true value, relative or absolute. In main tests, the logarithm of expected score produced by your solution should be within `1e-4` of the optimum, relative or absolute.
## Example 1 (Single trick)
Hint: It's a good idea to start your implementation by considering the case `N = 1`. The following is from the examples tests:
`s = [100]`
`m = [0.8]`
`p = [0.85]`
This trick scores 100 points on its first performance, with each successive performance scoring 20% less. The success rate of a single performance is 85%, and with each successive repetition the chance of making no mistakes becomes exponentially smaller.
The optimal solution is `t = [3.87270031161023]` with an expected score of `154.172745`. That is, the trick is performed nearly four times.
## Example 2 (Multiple tricks)
Here is a three-trick (`N=3`) case from the example tests:
`s = [100, 50, 250]`
`m = [0.8, 0.75, 0.825]`
`p = [0.95, 0.995, 0.9]`
The optimal solution is `t = [2.71866386359579, 7.89072156869921, 4.09759268102673]` with an expected score of `643.862231`. | games | from math import fsum, log
def continuum(ss, ms, ps):
xs = [s / (1 - m) for s, m in zip(ss, ms)]
ys = [log(p, m) for m, p in zip(ms, ps)]
t = fsum(xs) / (fsum(ys) + 1)
return [log(y * t / x, m) for m, x, y in zip(ms, xs, ys)]
| Cody Block's Continuum | 5fe24a97c1fc140017920a7f | [
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5fe24a97c1fc140017920a7f | 5 kyu |
# Description:
You are playing a simple slot machine that only contains exclamation marks and question marks. Every time the slot machine is started, a string of 5 length is obtained. If you're lucky enough to get a Special permutation, you'll win the bonus.
Give you a string `s`, return the highest bonus.
Bouns list:
```
Five-of-a-Kind: ---- 1000
"!!!!!" or "?????"
Four-of-a-Kind: ---- 800
The string contains a "!!!!" or "????"
"!!!!?","?!!!!","????!","!????"
Full House: ----500
such as "!!!??" or "???!!"...
Three-of-a-Kind: ---- 300
The string contains a "!!!" or "???"
such as "!!!?!","!???!"...
Two pair: ---- 200
The string contains two "!!" or "??"
such as "??!!?","!!?!!"
A Pair: ---- 100
The string contains a "!!" or "??"
such as "?!??!","!!?!?"
Others ---- 0
such as "?!?!?","!?!?!"
```
# Examples
```
slot("!!!!!") === 1000
slot("!!!!?") === 800
slot("!!!??") === 500
slot("!!!?!") === 300
slot("!!?!!") === 200
slot("!!?!?") === 100
slot("!?!?!") === 0
```
| reference | from itertools import groupby
def slot(st):
arr = [len(list(v)) for _, v in groupby(st)]
match arr:
case[_]: return 1000
case[4, _] | [_, 4]: return 800
case[3, 2] | [2, 3]: return 500
case[3, _, _] | [_, 3, _] | [_, _, 3]: return 300
case[2, 2, _] | [_, 2, 2] | [2, _, 2]: return 200
case[2, _, _, _] | [_, 2, _, _] | [_, _, 2, _] | [_, _, _, 2]: return 100
case _: return 0
| Exclamation marks series #18: a simple slot machine that only contains exclamation marks and question marks | 57fb4b289610ce39f70000de | [
"Fundamentals"
] | https://www.codewars.com/kata/57fb4b289610ce39f70000de | 7 kyu |
---
# Wrapping a paper net onto a cube
This Kata is about wrapping a net **onto** a cube, not folding one **into** a cube. There is another kata for that task.
Think about how you would fold a net into a cube. You would fold at the creases of the net at a 90 degree angle and make a cube. Wrapping a net onto a cube is simalar to folding one.
For example the grey net can cover a cube entirely when folded, with one square on each face.
![](https://github.com/GaryDoooo/public_codewar_info/blob/main/1.png?raw=true)
However things are not always perfect. If we use the red net, we still can entirely wrap the net around a cube. But there is one face of the cube having two squares overlaping each other, i.e. squares A and E.
The green and blue nets can't fully cover a cube, but it still can wrap onto a cube. All the folding is 90 degree along edges of the squares. In the 3D demontration of the green net below, squares A, F, E, and G overlap.
![](https://github.com/GaryDoooo/public_codewar_info/blob/main/exs.jpg?raw=true)
But some nets can't be wrapped around a cube without folding inside a square or cutting an edge open, like the yellow net.
## Task
Create function `wrap_cube` that uses a net, given as a string, to determine which squares of the net overlap when folded onto a cube. If the net cannot be folded onto a cube without being changed, return `None`.
The input net will be a string. Spaces are empty parts, each char (case sensitive, including numbers) represents one square on the net.
```
Ex.1 | Ex.2 | Ex.3
| |
E | A F | 0 9
ABCDE | BCD | 8AB
G | E G | a b
```
The red net above could be inputed as a string of Example 1. The green net can be represented as example 2 or 3.
If a net can't be wrapped onto a cube without being cut, return `None`. If it can, return a list of overlapping squares. For example the output of Example 1 above is `[['A', 'E']].` The output of the Example 2 could be ``[["A", "F"], ["E", "G"]]``. Your final asnswer does not have to be sorted, it can be in any order. You may find out more in the example test code.
#### Notes:
* Use common sense to fold the net, only at 90 degree angles along the edges;
* No 180 degree folding, no cutting, no folding inside a square;
* For some huge nets, ignore the thickness of paper...
* All the input chars will be connected; but some trailing spaces may be stripped;
* There will be 500 large random nets in the test, each of which has >60 squares; but there are some easier tests too
* Not all 6 faces of the cube need be covered
* There are no repeating chars in a net, and only one char is only one square
* The sequence of the chars and lists is not important; test code will sort your answer.
## One more example:
The input string could like this:
```
"""
ABCDE
"""
```
It's a stripe of paper with 5 squares side by side. If wrap this stripe around a cube, four faces will be covered. Two faces on the cube won't be covered, which is fine in this kata. The squares at the very two ends, A and E, will overlap. So the expected output of this net is [ [ "A" , "E" ] ]
---
*Beta Note: I "manually" checked not-so-large nets with my code. It should be able to handle huge nets. But if you found any erros in my expected answers, please let me know. thanks.*
---
Here is the kata of folding cubes:
https://www.codewars.com/kata/5f2ef12bfb6eb40019cc003e
There is also a harder version of the one above:
https://www.codewars.com/kata/5f3b561bc4a71f000f191ef7 | games | # number the cube faces like a dice 1-6
from random import shuffle
WIDTH = 0
HEIGHT = 0
def folding(
grid,
face,
list_on_face,
remain_list,
faces_done
# ,faces_done_on_cube
):
faces = [(list_on_face, face)]
dirs = [1, - 1, WIDTH, - WIDTH]
if list_on_face % WIDTH == 0:
dirs . remove(- 1)
if list_on_face % WIDTH == WIDTH - 1:
dirs . remove(1)
if list_on_face < WIDTH:
dirs . remove(- WIDTH)
if list_on_face >= WIDTH * (HEIGHT - 1):
dirs . remove(WIDTH)
goto_dirs = []
for direction in dirs:
goto_cell = direction + list_on_face
if goto_cell in remain_list:
if goto_cell in faces_done:
# if faces_done_on_cube[faces_done.index(
# goto_cell)] != new_face(grid, direction):
if goto_cell != faces_done[- 1]:
return "F"
else:
goto_dirs . append(direction)
# print(faces_done, list_on_face, goto_dirs)
for direction in goto_dirs:
faces . extend(folding(
grid=new_grid(face, direction, grid),
face=new_face(grid, direction),
list_on_face=list_on_face + direction,
remain_list=remain_list,
faces_done=faces_done + [list_on_face]
# faces_done_on_cube=faces_done_on_cube + [face]
))
return faces
def new_face(grid, direction):
return grid[[1, - 1, WIDTH, - WIDTH]. index(direction)]
def new_grid(face, direction, grid):
opposite_face = {1: 6, 2: 4, 6: 1, 4: 2, 5: 3, 3: 5}
dir_index = {1: 0, - 1: 1, WIDTH: 2, - WIDTH: 3}
newgrid = grid . copy()
newgrid[dir_index[- direction]] = face
newgrid[dir_index[direction]] = opposite_face[face]
return newgrid
def wrap_cube(shape):
global WIDTH, HEIGHT
shape_list = shape . split('\n')
WIDTH = max([len(x) for x in shape_list]) + 1
HEIGHT = len(shape_list)
number_list = []
char_list = []
for y in range(HEIGHT):
for x in range(len(shape_list[y])):
if shape_list[y][x] != " ":
char_list . append(shape_list[y][x])
number_list . append(x + y * WIDTH)
# print(WIDTH, HEIGHT, char_list, number_list)
faces = folding(grid=[3, 5, 2, 4], # in dir [1,-1,5,-5]
face=1,
list_on_face=number_list[0],
remain_list=number_list, faces_done=[]) # , faces_done_on_cube=[])
# print(faces)
if "F" in faces:
return None
# return sorted(faces) == list(range(1, 7))
# return True or False
res = []
for i in range(1, 7):
r = [char_list[number_list . index(p[0])] for p in faces if p[1] == i]
shuffle(r)
if len(r) > 1:
res . append(r)
shuffle(res)
return res
if __name__ == "__main__":
print(wrap_cube("a\nb\nc"))
| Wrap a cube with paper nets | 5f4af9c169f1cd0001ae764d | [
"Geometry",
"Puzzles"
] | https://www.codewars.com/kata/5f4af9c169f1cd0001ae764d | 3 kyu |
# Task Overview
Reversi is a game with black and white pieces where you attempt to capture your opponents pieces by trapping them between two of your own.
The purpose of this kata is to take a transcript (list of moves, as a `string`) and determine the state of the game after all those moves have been played. To do that, you'll implement the class method `ReversiBoard.interpret_transcript(moves)`, that will return the final state of the game as a `tuple` (_see below_).
<img src="https://upload.wikimedia.org/wikipedia/commons/2/20/Othello-Standard-Board.jpg">
<font size=2>_Wikipedia: https://en.wikipedia.org/wiki/Reversi_</font>
<hr>
# Reversi's Rules
### _Playing:_
* A Reversi board is an 8x8 board, whose the rows are described by an integer (`1-8`) and the columns by a letter (`A-H` or `a-h`).
* At the beginning of the game, 4 pieces are already placed on the board: `White` on `D4` and `E5` ; `Black` on `E4` and `D5`.
* In the present version of the game, `Black` plays first.
* A player can play only if he has a valid move. Valid moves are those in which an opposing piece is trapped (horizontally, vertically, or diagonally) between one already on the board, and the piece being placed. Any pieces between will be flipped (could be more than one!).
* The two players take turns alternatively, unless a player has no valid move. In that case, he passes his turn. Note that, after passing, __the other player can move again if a legal move exists__. It is not unheard for a player to be passing, then the other player doing 2 or 3 moves in a row before the first player being able to move again.
* If none of the players have a valid move, the game is over.
### _Counting points:_
When the game is over, if no errors occurred, the winner is the player with the most pieces.
If there are still empty spaces on the board, those are automatically added to the number of pieces of the winner, unless the game is a draw. Then both players win 32-32 points.
<br>
<hr>
<br>
# Input
You'll receive the transcript of a game as a string, describing where the pieces land on the board. For example: `"f5d6c5f6f7b6b5b4"`
* The transcript is case insensitive.
* You cannot assume that the transcript will be valid (see ___output___ part)
* Reminder: black always plays first.
# Output
Your class method will have to return a tuple of 5 elements: `(state, turn, winner, black score, white score)`
* <u>State:</u> indicates the state of the game after interpreting the transcript. Values can be:
- `"C"` for a complete game: neither of the players have a valid move.
- `"I"` for an incomplete game: one player (at least) still has a valid move.
- `"E"` if an error of any kind occured during the interpretation (invalid input or invalid move required)
<br>
* <u>Turn:</u>
- When the game is incomplete, indicates the color of the next player who would be able to play at the next turn, using `"B"` for black or `"W"` for white.
- If an error or a complete game, return `None` for the turn.
<br>
* <u>Winner:</u>
- `None` for an error
- `"I"` if the game is incomplete
- And if the game is complete, `"D"` for a draw, or the color of the winner, using `"B"` or `"W"`, once again.
<br>
* <u>Black & white scores:</u>
- For a complete or incomplete game, gives the number of points each player scored
- Or use `None` if an error occured.
<br>
<hr>
<br>
# Tests & Time constraint
* You'll deal with approximately 140 fixed tests and 400 random tests.
* Be aware that you'll have to make an efficient enough code: the execution time of your implementation will be compared with the reference solution and will have to fit in the constraint of `worst case, 3.5 times slower than the reference solution` (_why 3.5? well you know: "using a fair dice", and all..._ ;) ). No need for fancy<font size=2>/_hacky_</font><font size=1>/_dirty_</font> optimizations: you just have to avoid extra work in your implementation.
<br>
<hr>
<br>
## Examples:
```python
ReversiBoard.interpret_transcript('d3c5F6F5e6e3d6f7g6') # output: ('I', 'W', 'I', 10, 3)
ReversiBoard.interpret_transcript('d3c5f6 f5e6e3d6f7g6') # output: ('E', None, None, None, None)
trans1 = 'f5d6c3f3d7g6e3c6f4e6c5b4b6g3c7c4d3b5a3a4f6e7f7d8g4c8a5e8a6h3g5h4f2e1h6e2d2b3f1g1h5g2h1h2d1c2f8g8g7b7a2b2a1b1c1h8h7a8b8a7'
ReversiBoard.interpret_transcript(trans1) # output: ('C', None, 'B', 45, 19) -> black wins
trans2 = 'E6F4C3C4D3D6C5C6D7B5B6F7A6A5B4A7F3C8E8C7F6E7G8G6F8F5G4E3D2H3G5G3H4H5H7D8B8A4B3D1C1B1C2E1E2A3B7F2F1G1B2A2G2H6H2G7'
ReversiBoard.interpret_transcript(trans1) # output: ('C', None, 'D', 32, 32) -> draw!
```
_Good luck!_
| algorithms | import re
# A small space to manage the symbols used in the reversi game
class ReversiSymbol:
FREE_SPACE = ' '
WHITE_TILE = 'W'
BLACK_TILE = 'B'
WHITE_PLAYER = WHITE_TILE
BLACK_PLAYER = BLACK_TILE
WHITE_PLAYER_WINS = WHITE_TILE
BLACK_PLAYER_WINS = BLACK_TILE
DRAW_GAME = 'D'
GAME_COMPLETE = 'C'
GAME_INCOMPLETE = 'I'
GAME_ERROR = 'E'
# ---end
# booleans used to easily swap between players using logic
class Player:
WHITE = False
BLACK = True
# ---end class
# A small class to manage the status of the game
# Game Status: (state, turn, winner, black score, white score)
class Status:
COMPLETE = 0
INCOMPLETE = 1
DRAW = 2
INVALID_MOVE_FORMAT = 3
PLAYER_PASSED = 4
ALL_MOVES_DONE = 5
ILLEGAL_MOVE = 6
def __init__(self):
self . state = None
self . turn = ReversiSymbol . BLACK_TILE
self . winner = None
self . blackScore = 0
self . whiteScore = 0
# ---end function
def __str__(self):
return "(\'{}\', \'{}\', \'{}\', {}, {})" . format(self . state,
self . turn,
self . winner,
self . blackScore,
self . whiteScore)
def getStatusAsTuple(self):
return tuple([self . state,
self . turn, self . winner,
self . blackScore,
self . whiteScore])
# Invalid move or invalid input (e.g. '3d' ) occured
def setErrorStatus(self):
self . state = ReversiSymbol . GAME_ERROR
self . turn = None
self . winner = None
self . blackScore = None
self . whiteScore = None
# ---end function
# The game was played to its entirity
def setCompleteStatus(self, whiteScore, blackScore):
maxScore = 64
self . state = ReversiSymbol . GAME_COMPLETE
self . turn = None
if whiteScore > blackScore:
winnerColor = ReversiSymbol . WHITE_PLAYER_WINS
whiteScore = maxScore - blackScore
elif blackScore > whiteScore:
winnerColor = ReversiSymbol . BLACK_PLAYER_WINS
blackScore = maxScore - whiteScore
else: # Draw
whiteScore, blackScore = maxScore / 2, maxScore / 2
winnerColor = ReversiSymbol . DRAW_GAME
self . winner = winnerColor
self . blackScore = blackScore
self . whiteScore = whiteScore
# ---end function
# The game has been abandoned while there are still moves that can be played
# e.g. no more moves provided, as if one of the players popped off
def setIncompleteStatus(self, nextPlayer, whiteScore, blackScore):
self . state = ReversiSymbol . GAME_INCOMPLETE
self . turn = nextPlayer
self . winner = ReversiSymbol . GAME_INCOMPLETE
self . blackScore = blackScore
self . whiteScore = whiteScore
# ---end class
# Main-Brain of the Reversi Game
class ReversiGame (object):
N = 8 # Dimensions of square board
# tokeninze by 2 (or at least by 1)
tokenPattern = re . compile("\s*.{1,2}")
# Cols defined as a, b, c,....
__legalCols = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
# Rows defined as 1, 2, 3,....
__legalRows = ['1', '2', '3', '4', '5', '6', '7', '8']
# To convert a move (e.g. 'b3') to row/col index (row 1, col 4)
__rowLookup = dict(zip(__legalRows, range(N)))
# To convert a move (e.g. 'b3') to row/col index (row 1, col 4)
__colLookup = dict(zip(__legalCols, range(N)))
__rowLabelLookup = dict(zip(range(N), __legalRows)
) # For drawing the board
__tileLookup = {Player . WHITE: ReversiSymbol . WHITE_TILE, # Easy access to current players tile symbol
Player . BLACK: ReversiSymbol . BLACK_TILE}
def __init__(self):
self . board = self . initializeBoard()
self . gameStatus = Status()
self . currentPlayer = Player . BLACK # Black is defined to play first
# ---end function
def isFreeSpace(self, curMove):
i, j = curMove[0], curMove[1]
return self . board[i][j] == ReversiSymbol . FREE_SPACE
# ---end function
def changePlayers(self):
self . currentPlayer = not self . currentPlayer
# ---end function
def getOtherPlayer(self):
return not self . currentPlayer
# ---end function
def getCurrentPlayersTile(self):
return self . __tileLookup[self . currentPlayer]
# --end function
def getOpponentsTile(self):
return self . __tileLookup[self . getOtherPlayer()]
# --end function
def initializeBoard(self):
board = [[ReversiSymbol . FREE_SPACE for _ in range(
self . N)] for _ in range(self . N)]
board[3][3] = ReversiSymbol . WHITE_TILE
board[4][4] = ReversiSymbol . WHITE_TILE
board[3][4] = ReversiSymbol . BLACK_TILE
board[4][3] = ReversiSymbol . BLACK_TILE
return board
# ---end function
# Manage the move format stype for the game e.g. d3 (valid) vs 3d or 39 (invalid)
# Pre: move has been made lowercase already
def isValidMoveFormt(self, move):
col, row = move[0], move[1]
return (row in self . __legalRows and col in self . __legalCols)
# ---end function
# Convert a letter-number move (e.g. f7) into row column format (f7 is row 5, col 8)
def getMove(self, move):
col, row = move[0], move[1]
return [self . __rowLookup[row], self . __colLookup[col]]
# ---end function
def isOnBoard(self, i, j):
return i in range(self . N) and j in range(self . N)
# ---end function
# determines all tiles to flip based on the current move
# playersTile: The tile being played (e.g. players tile is white, so we are looking
# for black tiles to flip)
# curMove: The place the playerTile is being played
def getTilesToFlip(self, curMove, playersTile):
tilesToFlip = []
iRoot, jRoot = curMove[0], curMove[1]
if self . board[iRoot][jRoot] != ReversiSymbol . FREE_SPACE:
return tilesToFlip
di = [0, 0, 1, 1, 1, - 1, - 1, - 1]
dj = [1, - 1, 0, 1, - 1, 0, 1, - 1]
numSearchDirs = 8
if playersTile == ReversiSymbol . WHITE_PLAYER:
opponentsTile = ReversiSymbol . BLACK_PLAYER
else:
opponentsTile = ReversiSymbol . WHITE_PLAYER
# search-ray in all eight directions: Note that iRoot, jRoot is garanteed
# to be a FreeSpace (i.e. no tile is there)--see innermost while loop (the while True one)
for s in range(numSearchDirs):
iSearch = iRoot + di[s]
jSearch = jRoot + dj[s]
while self . isOnBoard(iSearch, jSearch) and self . board[iSearch][jSearch] == opponentsTile:
iSearch += di[s]
jSearch += dj[s]
if self . isOnBoard(iSearch, jSearch) and self . board[iSearch][jSearch] == playersTile:
# we have hit our tile, now the tiles to flip are those we have gone over
while True: # loop breaks when we get back to the freespace (garanteed)
iSearch -= di[s] # go back the way we came along the row
jSearch -= dj[s] # go back the way we came along the col
if iSearch == iRoot and jSearch == jRoot:
break
tilesToFlip . append([iSearch, jSearch])
return tilesToFlip
# ---end function
# desiredTile is the tile that represents the player moves we want
# e.g. 'W' means we want all possible moves for the white player :)
# Returns a dictionary of all possible moves, and the tiles each move flips
def getAllPossibleMoves(self, desiredTile):
possibleMovesLookup = {}
for i in range(self . N):
for j in range(self . N):
flippedTiles = self . getTilesToFlip([i, j], desiredTile)
if flippedTiles:
possibleMovesLookup[tuple([i, j])] = flippedTiles
return possibleMovesLookup
# ---end function
# A move has been played that flips at least one tile (legally of course)
def updateBoard(self, curMove, tilesToFlip):
currentPlayersTile = self . getCurrentPlayersTile()
for tile in tilesToFlip:
i, j = tile[0], tile[1]
self . board[i][j] = currentPlayersTile
i, j = curMove[0], curMove[1]
self . board[i][j] = currentPlayersTile
# ---end function
def calculateScore(self):
whiteScore = 0
blackScore = 0
for i in range(self . N):
for j in range(self . N):
curTile = self . board[i][j]
if curTile == ReversiSymbol . WHITE_TILE:
whiteScore += 1
elif curTile == ReversiSymbol . BLACK_TILE:
blackScore += 1
return whiteScore, blackScore
# ---end function
# Help to debug the game
def debugReadout(self, curMove, possibleMoves={}, didMove=False):
if didMove:
print("Player ", self . getCurrentPlayersTile(),
" is attempting move ", curMove)
else:
print("Player ", self . getCurrentPlayersTile(),
" has played move ", curMove)
self . drawBoard(possibleMoves)
# ---end function
# To help in debuging the game :)
def drawBoard(self, possibleMoves):
print(" a b c d e f g h")
print(" =================")
for i in range(self . N):
print('%s|' % self . __rowLabelLookup[i], end='')
for j in range(self . N):
if possibleMoves and tuple([i, j]) in possibleMoves:
print('*', end='|')
else:
print(self . board[i][j], end='|')
print('%s' % self . __rowLabelLookup[i])
print(" =================")
print(" a b c d e f g h")
# ---end function
# Either an error occured, or all moves have been played
def finalizeGameStatus(self, currentStatus):
if currentStatus == Status . INVALID_MOVE_FORMAT or currentStatus == Status . ILLEGAL_MOVE:
self . gameStatus . setErrorStatus()
return
# Have a valid game: Determine Complete, or incomplete
whiteScore, blackScore = self . calculateScore()
# we have a complete game (neither have a move less)
if currentStatus == Status . ALL_MOVES_DONE:
self . gameStatus . setCompleteStatus(whiteScore, blackScore)
else:
curPlayerPossibleMoves = self . getAllPossibleMoves(
self . getCurrentPlayersTile())
opponentsPossibleMoves = self . getAllPossibleMoves(
self . getOpponentsTile())
if curPlayerPossibleMoves or opponentsPossibleMoves: # incomplete
if not curPlayerPossibleMoves: # game stopped at a pass; determone which player's turn
# self.gameStatus.setIncompleteStatus(self.getOpponentsTile(), whiteScore, blackScore)
tile = self . getOpponentsTile()
else:
# self.gameStatus.setIncompleteStatus(self.getCurrentPlayersTile(), whiteScore, blackScore)
tile = self . getCurrentPlayersTile()
self . gameStatus . setIncompleteStatus(tile, whiteScore, blackScore)
else: # corner case when last move completes game; game is complete
self . gameStatus . setCompleteStatus(whiteScore, blackScore)
# ---end function
# Given a list of moves (e.g. 'd3c3c4') play out the moves
def playMoveList(self, moveStr):
currentStatus = None
for move in self . tokenPattern . findall(moveStr):
move = move . lower()
if self . isValidMoveFormt(move):
curMove = self . getMove(move)
else:
currentStatus = Status . ILLEGAL_MOVE
break
desiredTile = self . getCurrentPlayersTile()
tilesToFlip = self . getTilesToFlip(curMove, desiredTile)
if not tilesToFlip: # current player doesn't have a move...
# Check if the current player has any moves; if so we have an error
curPlayerPossibleMoves = self . getAllPossibleMoves(
self . getCurrentPlayersTile())
if curPlayerPossibleMoves:
currentStatus = Status . ILLEGAL_MOVE
break
# Scenario: Current player didn't have any moves, so we pass to other player
self . changePlayers()
desiredTile = self . getCurrentPlayersTile()
tilesToFlip = self . getTilesToFlip(curMove, desiredTile)
if not tilesToFlip: # the other player doesn't have a move either: We check game end or illegal move
try:
curPlayerPossibleMoves = self . getAllPossibleMoves(
self . getCurrentPlayersTile())
tilesToFlip = curPlayerPossibleMoves[tuple(curMove)]
opponentsPossibleMoves = self . getAllPossibleMoves(
self . getOpponentsTile())
tilesToFlip = opponentsPossibleMoves[tuple(curMove)]
except KeyError:
currentStatus = Status . ILLEGAL_MOVE
break
else: # the other player can move
desiredTile = self . getCurrentPlayersTile()
tilesToFlip = self . getTilesToFlip(curMove, desiredTile)
self . updateBoard(curMove, tilesToFlip)
else: # current player has a move
self . updateBoard(curMove, tilesToFlip)
# pass the play to the other player
self . changePlayers()
# ---end game loop
self . finalizeGameStatus(currentStatus)
return self . gameStatus . getStatusAsTuple()
# ---end function
# ---end class
# Kata: Call the reversi game class
class ReversiBoard (object):
@ classmethod
def interpret_transcript(cls, move_str):
r = ReversiGame()
gameResult = r . playMoveList(move_str)
return gameResult
# ---end class
| Reversi Win Checker | 5b035bb186d0754b5a00008e | [
"Puzzles",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/5b035bb186d0754b5a00008e | 3 kyu |
## Welcome to the world of toroids!
You find yourself in a **toroid maze** with a treasure and **three lives**. This maze is given as an array of strings of the same length:
```python
maze = [
'#### #####',
'# #E#T#',
'###### # #',
' S## H E #',
'#### #####'
]
```
Here you can see that mazes can have different tiles:
- ```' '``` => **Space**, you can walk through here freely
- ```'#'``` => **Wall**, you cannot pass through here
- ```'E'``` => **Enemy**, you can pass through here at the cost of one life
- ```'H'``` => **Health**, you can pass through here and gain a life
- ```'S'``` => **Spring**, once you are over it, the next movement will be a jump over a tile (any tile, even a wall or an empty space). The effect of the tile that you jumped over will not be activated.
- ```'T'``` => **Treasure**, this is what you are looking for!
Given a starting row and column index (i and j, respectively and starting from 0), can you get the treasure by moving straight up, down, left and right (not diagonally)? Note that there are no restrictions on the starting coordinates (you might be asked to start from a wall!).
You have to take note of three things:
- Once you fight an enemy or pass through a health tile, it **dissapears**.
- If you run out of lives it's **game over**.
- If you are asked to start from an invalid position (i.e. a wall), then it's an automatic game over too. You will never be asked to start from an invalid row or column index.
### But, what about the toroid part?
The maze behaves as usual, but the coordinates **wrap on both the x and y axis**. This means that this treasure is obtainable from any empty tile in this particular maze:
```python
maze = [
'## ## ####',
' ## #',
'######## #',
'## ##T#',
'## ## ####'
]
```
To be more clear, imagine an empty 3x3 maze like this one:
```python
maze = [
' ',
' ',
' ',
]
```
Here, you can go from the '1' tile to the '2' tile by walking upwards and from the '3' tile to the '4' tile by walking left:
```python
maze = [
' 1 ',
'3 4',
' 2 ',
]
```
Of course, this also works in the opposite directions.
# Your task
Write a function ```treasure(maze, i, j, n)``` that returns True only when it is possible to take the treasure when you start walking from the tile with coordinates ```(i, j)``` and take a maximum of ```n``` steps.
Your function will be tested against many random 6x6 mazes with a maximum of 10 steps, so performance is important, but not essential :)
## Do u even golf?
The task is not very difficul to program by itself, the real challenge is that this has to be solved in ```240 characters or fewer```. The best I managed to program was 229 characters long.
```if:python
_<u>IMPORTANT:</u> this kata has been created before the walrus operator was a thing, so you aren't allowed to use it in your solution._
```
## Some examples
```python
maze1 = [
'##########',
' # T#', # Not obtainable from (1, 0)
'##########',
]
maze2 = [
'##########',
' S# T#', # Obtainable from (1, 0)
'##########',
]
maze3 = [
'##########',
' # T ', # Obtainable from (1, 0)
'##########',
]
maze4 = [
'##########',
' EEET#', # Not obtainable from (1, 0)
'##########',
]
maze5 = [
'##########',
' EHEET#', # Obtainable from (1, 0)
'##########',
]
``` | games | def treasure(m, i, j, n, H=3, s={0}): c = m[i][j]; d = 1 + (c == 'S'); t = (i, j); return H * n * (c != '#') and (c == 'T' or any(treasure(m, a % len(
m), b % len(m[0]), n - 1, H + ((c == 'H') - (c == 'E')) * (t not in s), s | {t}) for a, b in ((i + d, j), (i - d, j), (i, j + d), (i, j - d))))
| The treasure in the Toroid [Code Golf] | 5e5d1e4dd8e2eb002dd73649 | [
"Restricted",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5e5d1e4dd8e2eb002dd73649 | 3 kyu |
This challenge was inspired by [this kata](https://www.codewars.com/kata/63306fdffa185d004a987b8e). You should solve it before trying this harder version.
# The room
The situation regarding the lights and the switches is exactly is the same as in the original kata. Here is what you should know :
You are in a room with `n` lights indexed from `0` to `n-1` and `m` light switches indexed from `0` to `m-1`. All of the lights are initially off. Each of the switches is linked to some (or none) of the lights. When you toggle a switch, each of the lights to which it is linked changes its state from on to off or off to on.
The links between the switches and the lights are described by an array `corresponding_lights_list` of size `m`, whose element of index `i` is the list of the lights the switch `i` is linked to.
Here is an example :
```
[
[0, 1, 2], // switch 0 controls lights 0, 1, 2
[1, 2], // switch 1 controls lights 1, 2
[1, 2, 3, 4], // switch 2 controls lights 1, 2, 3, 4
[1, 4] // switch 3 controls lights 1, 4
]
```
In this example toggling the switch `0` will turn on the lights `0`, `1`, and `2`. After this toggling the switch `3` will turn off the light `1` and turn on the light `4`
## Your task
Your new goal in this kata is, given the relationships between lights and switches, and a choice of lights that you want to turn on, to check if it possible to turn <u>only</u> those lights on, and when it is, to find which switches should be toggled to do so.
Better yet, you will implement this by writing a function that as an input takes the two-dimensional array representing relationships between lights and switches, and creates a controller object that can quickly tell if any choice of lights is possible and which switches to toggle.
More precisely:
You have to implement the type `LightController` with the constructor
```rust
new(n: usize, corresponding_lights_list: &[Vec<usize>]) -> Self
```
```python
__init__(self, n: int, corresponding_lights_list: list[list[int]]) -> None
```
and the solve method
```rust
solve(&self, lights: &Vec<usize>) -> Option<Vec<usize>>
```
```python
solve(self, lights: list[int]) -> list[int] | None
```
where:
- `n` and `corresponding_lights_list` are defined as above
- `lights` is the sorted list of the indices of the lights that you want to turn on
- `solve` returns `None` if the choice of lights is impossible to reach, and when possible the list of the indices of the switches to toggle.
During the tests, about a dozen of controllers of significant size will be instanciated. `n` and `m` will grow up to ~500 depending on the language. For each of those controllers up to 3000 lights choices can be provided for solving. Make sure the redundant computations are done at the creation of the controller!
Your controller should also be able to handle all the possible cases. A light may be linked to no switch, a switch may be linked to no light, there may be no switches or even no lights. You may also just want to be in the dark and let all the lights off...
| games | class LightController:
def __init__(self, n, switches):
self . n, m = n, len(switches)
if n == 0 or m == 0:
self . dimensional_edge_case = True
return
else:
self . dimensional_edge_case = False
mat = [1 << (m + i) for i in range(n)]
for c, row in enumerate(switches):
for r in row:
mat[r] += 1 << c
i, j, refs = 0, 0, []
while i < n and j < m:
try:
pivot = next(k for k in range(i, n) if mat[k] >> j & 1)
except StopIteration:
j += 1
continue
mat[i], mat[pivot] = mat[pivot], mat[i]
refs . append(j)
for k, row in enumerate(mat):
if i != k and row >> j & 1:
mat[k] ^= mat[i]
i += 1
j += 1
self . mat = [row >> m for row in mat]
self . refs = refs
def solve(self, lights):
if self . dimensional_edge_case:
return None if self . n and lights else []
toggle = sum(1 << i for i in lights)
if any((row & toggle). bit_count() & 1 for row in self . mat[len(self . refs):]):
return None
return [self . refs[i] for i, row in enumerate(self . mat) if (row & toggle). bit_count() & 1]
| Can you control the lights? | 633cb47c1ec6ac0064ec242d | [
"Algorithms",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/633cb47c1ec6ac0064ec242d | 2 kyu |
So I have a few Snafooz puzzles at home (which are basically jigsaw puzzles that are 3d)
https://www.youtube.com/watch?v=ZTuL9O_gQpk
and it's a nice and fun puzzle. The only issue is, well, I'm not very good at it... Or should I say not better than my dad.
As you can see this is a big problem which only has one sensible solution... I need to cheat.
The puzzle is made of 6 pieces (each piece is 6x6 array which represents a jigsaw like puzzle piece), each one a side of a cube, and all you need to do is construct the cube by attaching the pieces together kinda like a 3d jigsaw puzzle.
You may rotate, flip and\or reorganize the pieces but not change their shape.
**Example:**
Let's say these are our pieces-
1:
xx x
xxxxxx
xxxxx
xxxxxx
xxxxxx
x xx
2:
x
xxxxx
xxxxx
xxxxxx
xxxx
xxx
3:
xx x
xxxxx
xxxxxx
xxxxx
xxxxxx
x xx
4:
xxxx
xxxxx
xxxx
xxxx
x x
5:
x xx
xxxxx
xxxxxx
xxxx
xxxxx
xxx
6:
x x
xxxxxx
xxxxx
xxxx
xxxxxx
x xx
Our solution would look something like this:
----------
| xx x |
| xxxxxx |
| xxxxx |
| xxxxxx |
| xxxxxx |
| xx x |
-----------------------------
| x | xx x | |
| xxxxx | xxxxx | xxxx |
| xxxxx | xxxxxx | xxxxx |
| xxxxxx | xxxxx | xxxx |
| xxxx | xxxxxx | xxxx |
| xxx | x xx | x x |
-----------------------------
| x xx |
| xxxxx |
| xxxxxx |
| xxxx |
| xxxxx |
| xxx |
----------
| x x |
| xxxxxx |
| xxxxx |
| xxxx |
| xxxxxx |
| x xx |
----------
(this is just a flattened cube)
Here is a pic describing which edges are touching, and need to match (marked by letters), and the matching corners (marked with numbers):
5aaaa6
i....h
i....h
i....h
i....h
1bbbb2
5iiii1 1bbbb2 2hhhh6
g....f f....e e....l
g....f f....e e....l
g....f f....e e....l
g....f f....e e....l
7jjjj4 4cccc3 3kkkk8
4cccc3
j....k
j....k
j....k
j....k
7dddd8
7dddd8
g....l
g....l
g....l
g....l
5aaaa6
**Bad Example:**
Having two pieces next to each other that don't fit-
xxxxxx xxxxx
xxxxxx xxxxxx
xxxxxx xxxxx
xxxxx xxxxx
xxxxxx xxxxx
xxxxxx xxxxxx
or
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx
x xx
x x x
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx
The right way would be like this -
xxxxxx xxxxx
xxxxx xxxxxx
xxxxxx xxxxx
xxxxx xxxxxx
xxxxx xxxxxx
xxxxxx xxxxx
or
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx
x x xx
x x
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx
Now all you need to do is use the input which will be a 3d array (6x6x6) where arr[0] is the first piece (which will be a 6 by 6 matrix) arr[1] is the second and so onβ¦
And you will return the answer in a new 6x6x6 matrix in which the pieces are all in the right orientation in this order->
0
1 2 3
4
5
***NOTES***
1. Each piece is represented by a 6x6 array of numbers: ``1``s indicate the piece, ``0``s indicate empty space.
2. All cases will be solvable
3. Don't be too conncerned about optimizations (after all my dad isn't THAT fast)
Good Luck!
| games | def solve_snafooz(pieces):
def reverse(xs): return [v[:: - 1] for v in xs]
def rotate(xs): return [[xs[5 - i][j] for i in range(6)] for j in range(6)]
def rotateall(xs): return [xs, rotate(xs), rotate(
rotate(xs)), rotate(rotate(rotate(xs)))]
def combs(xs): return rotateall(xs) + rotateall(reverse(xs))
def check_x(a, b): return all(a[i][- 1] ^ b[i][0] for i in range(
1, 5)) and not a[0][- 1] & b[0][0] and not a[- 1][- 1] & b[- 1][0]
def check_y(a, b): return all(a[- 1][i] ^ b[0][i] for i in range(
1, 5)) and not a[- 1][0] & b[0][0] and not a[- 1][- 1] & b[0][- 1]
def recurse(c, todo):
if not todo:
return c
n = len(c)
for i, v in enumerate(todo):
for p in combs(v):
two = n < 3 and check_y(c[- 1], p)
three = n == 3 and check_y(c[- 1], p) and check_y(p, c[0])
four = n == 4 and ( # Left
check_x(p, c[1]) and
check_x(rotate(p), c[0]) and
check_x(rotate(rotate(p)), c[3]) and
check_x(rotate(rotate(rotate(p))), c[2]))
five = n == 5 and ( # Right
check_x(c[1], p) and
check_x(c[2], rotate(p)) and
check_x(c[3], rotate(rotate(p))) and
check_x(c[0], rotate(rotate(rotate(p)))))
if two or three or four or five:
if (res := recurse(c + [p], todo[: i] + todo[i + 1:])) is not None:
return res
a, b, c, d, e, f = recurse([pieces[0]], pieces[1:])
return [a, e, b, f, c, d]
| Snafooz solver | 6108f2fa3e38e900070b818c | [
"Games",
"Puzzles",
"Logic",
"Arrays",
"Game Solvers"
] | https://www.codewars.com/kata/6108f2fa3e38e900070b818c | 4 kyu |
<!--Queue Battle-->
<blockquote style="max-width:400px;min-width:200px;border-color:#777;background-color:#111;font-family:Tahoma,Verdana,serif"><strong>β"Forward!", he cried from the rear<br/>
And the front rank died<br/>
The general sat and the lines on the map<br/>
Moved from side to sideβ</strong><br/><p style="text-align:right;font-family:serif"><i>Us and Them</i> -- Pink Floyd</p></blockquote>
<p>A few army battalions from warring nations have met on an even battlefield. Each nation has one battalion present and all battalions have an equal number of soldiers. Every soldier is armed with one rifle and unlimited ammunition. Every soldier also has perfect shooting accuracy. And all armies follow the rules of engagement below.</p>
<h2 style='color:#f88'>Rules of Engagement</h2>
<p><b>1.</b> Each army battalion forms its own straight line queue<br/>
<b>2.</b> Each line is formed such that the head of each queue faces the head of the opposing army queue to its left (or when there are only two remaining armies, both queues face toward each other)<br/>
<b>3.</b> All queue heads maintain equal distance from their respective targets<br/>
<span style='color:#0c0'><b>4.</b></span> There is a <code>1</code> second delay for each queue head to fire his weapon (time taken to lift weapon, aim, then fire)<br/>
<span style='color:#0c0'><b>5.</b></span> If a queue head gets hit by any bullets during that 1 second delay (including at the exact moment the head is expected to shoot), he falls before he can fire his rifle. Otherwise, he shoots his rifle and immediately walks back to the end of his queue.<br/>
<span style='color:#8df;'>Note that the head will receive all bullets that reach his position during that round.</span><br/>
<span style='color:#0c0'><b>6.</b></span> The next soldier in queue then takes his place as head at the start of the next round. If there is only one soldier remaining in a queue, he will stand in place and shoot his rifle every round until he falls or emerges victorious<br/>
<b>7.</b> An army is eliminated when all its soldiers have fallen. When an elimination occurs, the eliminator changes their target to the next army queue in sequence at the start of the next round.<br/>
<span style='color:#d84'>
<b>8.A.</b></span> If an elimination occurs during the round, then all remaining armies reposition themselves at the start of the next round and repeat the cycle from step <code>2</code>. <span style='color:#8df;'>All bullets still in flight at the end of the round will miss all their targets when the repositioning occurs.</span><br/>
<span style='color:#d84'>
<b>8.B</b></span> If no elimination occurs in the round, start again from step <code>4</code>.<br/><br/>
The Rules of Engagement are followed until there are <code>0</code> or <code>1</code> surviving armies.<br/>
Each round (i.e. queue shift) has a one second duration and the heads of each queue shoot at the same time<br/>
<h2 style='color:#f88'>Weapons</h2>
All nations purchase their munitions from the same supplier, Discount Rifles and Bullets, Inc. (aka DRABI)<br/>
All DRABI rifles have perfect firing accuracy. However, because many different machines are used to manufacture the rifles, rifles may or may not have different bullet speeds.
You have a master list of bullet speeds for each rifle and you also know the initial arrangement of all queues in battle. With those resources, you seek to find out which, if any, army survives.
<h2 style='color:#f88'>Input</h2>
Your function will receive anywhere from `3` to `9` arguments:
- The first argument will always be positive integer representing the `distance` between each queue head and his target
- Any additional arguments will each be given as an array/tuple of positive integers; these arrays each represent an army battalion. Each `i`th value in a given array represents the bullet speed for the `i`th soldier's rifle in that battalion's queue. The bullet speed is measured as `distance / second`.
<h2 style='color:#f88'>Output</h2>
<p>Return the number of the surviving army, given as its argument position.
Also return an array/tuple of that army's surviving soldiers, by index position from its original list. This list should be sorted in queue order, starting with the queue head at time of victory.<br/>
If all battalions are wiped out and there are no survivors, return <code>-1</code> and an empty array/tuple.</p>
<h2 style='color:#f88'>Test Example</h2>
<img src='https://i.imgur.com/RFWZ83d.png'>
The image above references the example given below.
In our example, we are given `3` armies that form their respective queues. Each head (green pointed indicators) faces and fires at the opponent head to the left.
In the tests, each queue head shoots at the head of the next queue that follows, and completes the loop with the last queue shooting at the first.
The image below represents the queues after army `C` is eliminated. Note they change formation and face each other while always maintaining the same distance.
<img src='https://i.imgur.com/pVClMJl.png'>
```go
// in Go the first argument is given as a uint32 value
// subsequent arguments are given as arrays of uint32 values
var A = []uint32{98,112,121,95,63}
var B = []uint32{120,94,90,88,30}
var C = []uint32{116,144,45,200,32}
// the function should return two values: an int and an array of uint32 values
// In our example, the first army emerges as the sole survivor, and the remaining queue for that army consists of only the 3rd soldier
QueueBattle(300,A,B,C) // returns 0,[]uint32{2}
```
```python
# in Python the first argument is given as a positive int
# subsequent arguments are given as tuples of positive ints
A = (98,112,121,95,63)
B = (120,94,90,88,30)
C = (116,144,45,200,32)
# the function should return a tuple of two elements: an integer and a tuple of integers
# In our example, the first army emerges as the sole survivor, and the remaining queue for that army consists of only the 3rd soldier
queue_battle(300,A,B,C) # returns the tuple (0,(2,))
```
```javascript
// in JavaScript the first argument is given as a positive integer
// subsequent arguments are given as arrays of positive integers
const A = [98,112,121,95,63];
const B = [120,94,90,88,30];
const C = [116,144,45,200,32];
// the function should return an array of two elements: an integer and an array of integers
// In our example, the first army emerges as the sole survivor, and the remaining queue for that army consists of only the 3rd soldier
queueBattle(300,A,B,C); // returns the array [0,[2]]
```
```kotlin
// in Kotlin the first argument is given as a positive int
// subsequent arguments are given as IntArrays of equal size
val a = intArrayOf(98,112,121,95,63)
val b = intArrayOf(120,94,90,88,30)
val c = intArrayOf(116,144,45,200,32)
// the function should return a Pair containing an int and an IntArray
// In our example, the first army emerges as the sole survivor, and the remaining queue for that army consists of only the 3rd soldier
queueBattle(300,a,b,c) // returns Pair(0, intArrayOf(2))
```
<details style='background:#111'>
<summary style='color:#8df'><strong>Click here for a step-by-step of the first four rounds of our example test</strong></summary><p>
We'll refer to units of distance as DU (distance units)<br/>
<strong style='color:#cc0'>Round 1</strong><br/>
After initial 1 second delay, each queue head fires, then goes to the back of their respective queue.
<strong style='color:#cc0'>Round 2</strong><br/>
The next soldier for each queue fires their weapon after a 1 second delay. At the moment each soldier fires, there are already 3 bullets in flight:<br/>
- Bullet <code>0</code>: traveling at <code>98</code> DU per second, it has already traveled for 1 second and is now <code>202</code> DU away from its target (the head of queue <code>B</code>)
- Bullet <code>1</code>: traveling at <code>120</code> DU per second, it is <code>180</code> DU away from its target.
- Bullet <code>2</code>: traveling at <code>116</code> DU per second, it is <code>184</code> DU away from its target.
<strong style='color:#cc0'>Round 3</strong><br/>
At the moment when the next queue heads fire, there are 6 bullets in flight (not including the bullets fired this round).<br/>
The 1st round of bullets have now traveled <code>196</code>, <code>240</code>, and <code>232</code> DU, respectively.<br/>
The 2nd round of bullets have traveled <code>112</code>, <code>94</code>, and <code>144</code> DU, respectively.<br/>
<strong style='color:#cc0'>Round 4</strong><br/>
First blood is drawn during this round.<br/>
Before the head of queue <code>C</code> can fire, he is hit by the first bullet shot by queue <code>B</code>. The head of queue <code>A</code> is also shot before he can fire.<br/>
The only head that fires his rifle is from queue <code>B</code>.<br/>
At this point, there are 7 bullets in flight, excluding the bullet shot this round.<br/>
The first bullet shot by queue <code>A</code> has now traveled <code>294</code> DU, and is therefore <code>6</code> DU away from its target. It will reach its target in round 5, before the queue head can fire.
</p>
</details>
<p>In our example, we saw the new positioning when going from <code>3</code> to <code>2</code> queues. Other tests will have a random number of queues (up to a max of <code>8</code>).<br/>
The following diagrams serve as a visual guide to show other battle positions formed depending on the number of active queues.</p>
<img src='https://i.imgur.com/qk791nn.png'>
<img src='https://i.imgur.com/XuMmBzt.png'>
<h2 style='color:#f88'>Technical Details</h2>
- All tests will be valid
- Test constraints:
- `2 <= number of queues <= 8`
- `8 <= bullet speed < 2e6`
- `80 <= distance < 1e6`
- `bullet speed >= distance/10`
- `5 <= queue length < 2000`
- Use Python 3.6+ for the Python translation
- In JavaScript, `module` and `require` are disabled
- Full Test Suite: `10` fixed tests and `150` random tests
<p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p> | algorithms | from heapq import *
from itertools import starmap
from collections import deque, namedtuple
Army = namedtuple('Army', 'i,q')
Soldier = namedtuple('Soldier', 'i,speed')
def queue_battle(d, * args):
armies = [Army(i, deque(starmap(Soldier, enumerate(q))))
for i, q in enumerate(args)]
# bullet[i] shoots at armies[i+1]
bullets = [[] for _ in range(len(armies))]
t = 0
while len(armies) > 1:
t += 1
alives = [1] * len(armies)
for i, q in enumerate(bullets):
if q and q[0] <= t:
alives[(i + 1) % len(armies)] = 0
while q and q[0] <= t:
heappop(q)
emptyArmies = False
for i, alive in enumerate(alives):
if alive:
heappush(bullets[i], t + d / armies[i]. q[0]. speed)
armies[i]. q . rotate(- 1)
else:
armies[i]. q . popleft()
emptyArmies |= not armies[i]. q
if emptyArmies:
armies = [army for army in armies if army . q]
bullets = [[] for _ in range(len(armies))]
if not armies:
return (- 1, ())
win = armies . pop()
return (win . i, tuple(soldier . i for soldier in win . q))
| Queue Battle | 5d617c2fa5e6a2001a369da2 | [
"Arrays",
"Puzzles",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/5d617c2fa5e6a2001a369da2 | 4 kyu |
# Overview
Your task is to encode a QR code. You get a string, of at most seven characters and it contains at least one letter. <br>
You should return a QR code as a 2 dimensional array, filled with numbers, 1 is for a black field and 0 for a white field. We are limiting ourself to ```version 1```, always use```byte mode```, ```mask 0```, and ```Error Correction Lvl H```.
The way to encode a QR code is explained below.
# Input/output
- Input: string of at most 7 characters.
- Output: 2 dimensional array, according to the process described below.
```javascript
const text = "Hi";
return [[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1 ],
[ 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0 ],
[ 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0 ],
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0 ],
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1 ]];
```
```java
String text = "Hi";
return new int[][]{ {1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1},
{1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0},
{1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0},
{1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1},
{1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1},
{1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0},
{1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0},
{1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1}};
```
```python
text = "Hi"
return = [[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1 ],
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1 ],
[ 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0 ],
[ 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0 ],
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0 ],
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1 ],
[ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0 ],
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1 ]]
```
```csharp
string text = "Hi";
return new int[][]{ new int[]{1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1},
new int[]{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1},
new int[]{1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1},
new int[]{1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1},
new int[]{1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1},
new int[]{1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1},
new int[]{1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1},
new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0},
new int[]{0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1},
new int[]{1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1},
new int[]{1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1},
new int[]{1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0},
new int[]{1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0},
new int[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0},
new int[]{1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1},
new int[]{1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1},
new int[]{1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1},
new int[]{1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0},
new int[]{1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1},
new int[]{1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0},
new int[]{1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1}};
```
# Debugging
It can be quite frustrating to find a mistake in a 21x21 matrix. Therefore you can use the preloaded function ```htmlize()```, which takes a 2 dimensional array and returns a html graphical view, that you can print to the console.
```javascript
console.log(htmlize(arr));
```
```java
System.out.println(Preloaded.htmlize(arr));
```
```python
print(htmlize(arr))
```
```csharp
Console.WriteLine(Preloaded.htmlize(arr));
```
<b>Note:</b> ```htmlize()``` will throw an error if you don't pass a 21x21 matrix or if there is an invalid character in your matrix (anything other than 0 and 1).
# Encoding a QR-code
Here comes the explaination on how to encode a QR code. You can skip it if you already know how it works. <br>
As an example, we are going to encode the string "Hi".
## Data encoding
We have to build a binary sequence which represents the data of the QR code.
First of all, we add ```0100``` to our bit sequence because that stands for ```byte mode```.
```
bits = "0100";
```
Now we have to convert the length of our string to a 8 bit binary string:<br>
The length of ```Hi``` is ```2``` which is ```00000010``` as a 8 bit binary string.
Now we append that binary string to our bit sequence:
```
bits = "010000000010"
```
Now we convert the ascii value of every char of our string to a 8 bit binary string and append it to our bit sequence:
```H``` --> ```72``` <br>
```72``` --> ```01001000```
```
bits = "01000000001001001000"
```
```i``` --> ```105``` <br>
```105``` --> ```01101001```
```
bits = "0100000000100100100001101001"
```
Now we have to append ```0000``` as a terminator to our bit sequence, but our sequence must not be longer than 72 bits!<br>
Some examples:
- code length: 50 --> add ```0000```
- code length: 70 --> add ```00```
- code length: 71 --> add ```0```
- code length: 72 --> add nothing
In our example the bit sequence is 28 long, so we add ```0000```.
```
bits = "01000000001001001000011010010000"
```
As long as the length of our sequence isn't 72, we alternately append ```11101100``` and ```00010001```:
```
Append 11101100
bits = "0100000000100100100001101001000011101100"
Append 00010001
bits = "010000000010010010000110100100001110110000010001"
Append 11101100
bits = "01000000001001001000011010010000111011000001000111101100"
etc..
```
Now we've got our bit sequence!
```
bits = "010000000010010010000110100100001110110000010001111011000001000111101100"
```
## Error Correction
It often happens that a QR Code was not scanned nicely or it is no longer recognizable in some places; therefore we need error corection bits. QR codes use the Reed-Solomon algorithm to calculate those error correction bits.
This algorithm is very complex; that's the reason why this kata is blue.
For version 1, and Error Correction Lvl H, we need 17 Error Correction numbers.
First of all we have to create a message polynomial, it is structured like this:
```math
\text{messagePolynomial} = ax^8+bx^7+cx^6+dx^5+ex^4+fx^3+gx^2+hx^1+ix^0.
```
We have to multiply this by ```x``` to the power of the number of Error Correction numbers.<br>
We need 17 so we multiply it by ```x**17``` to get:
```math
\text{messagePolynomial} = ax^{25}+bx^{24}+cx^{23}+dx^{22}+ex^{21}+fx^{20}+gx^{19}+hx^{18}+ix^{17}.
```
Now we split the bit sequence in groups of 8 and convert it to a decimal number:
```
group1 = 01000000 --> 64
group2 = 00100100 --> 36
etc..
```
For ```a```,```b```,```c```,```d```,```e```,```f```,```g```,```h```,```i``` insert the decimal numbers. <br>
We get:
```math
\text{messagePolynomial} = 64x^{25}+36x^{24}+134x^{23}+144x^{22}+236x^{21}+17x^{20}+236x^{19}+17x^{18}+236x^{17}.
```
We also need a generator polynomial. If you want to know how to create a generator polynomial, read <a href="https://www.thonky.com/qr-code-tutorial/generator-polynomial-tool" target="_blank">this</a>.<br>
In this kata we will use the following as generator polynomial because we are limiting ourselfs to ```vesion 1```:
```math
\text{g} = \alpha^{0}x^{25}+\alpha^{43}x^{24}+\alpha^{139}x^{23}+\alpha^{206}x^{22}+\alpha^{78}x^{21}+\alpha^{43}x^{20}+\alpha^{239}x^{19}+\alpha^{123}x^{18}+\alpha^{206}x^{17}+\alpha^{214}x^{16}+\alpha^{147}x^{15}+\alpha^{24}x^{14}+\alpha^{99}x^{13}+\alpha^{150}x^{12}+\alpha^{39}x^{11}+\alpha^{243}x^{10}+\alpha^{163}x^{9}+\alpha^{136}x^{8}.
```
Now we have to multiply the generator polynomial with the lead term of the message polynomial.<br>
The lead term of the message polynomial is ```64x**25```. We need to convert the integer ```64``` to alpha notation by looking it up in <a href="https://www.thonky.com/qr-code-tutorial/log-antilog-table" target="_blank">this table</a>. <br>
This table is already ```preloaded``` as a const array ```alphaTable```. Use the integer as index and it returns the alpha exponent. For example:
```javascript
let alphaExponent = alphaTable[64]; // Returns 6
```
```java
int alphaExponent = Preloaded.alphaTable[64] // Returns 6
```
```python
alphaExponent = alphaTable[64] # Returns 6
```
According to the table we can say:
```math
\alpha^{6} = 64
```
We multiply the generator polynomial by adding the alpha exponents together. <br>
We get:
```math
\alpha^{6}x^{25}+\alpha^{49}x^{24}+\alpha^{145}x^{23}+\alpha^{212}x^{22}+\alpha^{84}x^{21}+\alpha^{49}x^{20}+\alpha^{245}x^{19}+\alpha^{129}x^{18}+\alpha^{212}x^{17}+\alpha^{220}x^{16}+\alpha^{153}x^{15}+\alpha^{30}x^{14}+\alpha^{105}x^{13}+\alpha^{156}x^{12}+\alpha^{45}x^{11}+\alpha^{249}x^{10}+\alpha^{169}x^{9}+\alpha^{142}x^{8}.
```
<b>IMPORTANT NOTE:</b> it can happen that the exponent becomes bigger than 254. If that happens modulo the exponent with 255!
Now we can convert all alpha exponents back to integers. Again, we are using <a href="https://www.thonky.com/qr-code-tutorial/log-antilog-table" target="_blank">this table</a> to do that and we get:
```math
64x^{25}+140x^{24}+77x^{23}+121x^{22}+107x^{21}+140x^{20}+233x^{19}+23x^{18}+121x^{17}+172x^{16}+146x^{15}+96x^{14}+26x^{13}+228x^{12}+193x^{11}+54x^{10}+229x^{9}+42x^{8}.
```
Now XOR these integer coefficients with the coefficients of the message polynomial. We get:
```math
0x^{25}+168x^{24}+203x^{23}+233x^{22}+135x^{21}+157x^{20}+5x^{19}+6x^{18}+149x^{17}+172x^{16}+146x^{15}+96x^{14}+26x^{13}+228x^{12}+193x^{11}+54x^{10}+229x^{9}+42x^{8}.
```
If we did everything correct, the lead term has a ```0``` as coefficient. We can discard the lead term to get the following smaller polynomial which <b> is our new message polynomial</b>:
```math
168x^{24}+203x^{23}+233x^{22}+135x^{21}+157x^{20}+5x^{19}+6x^{18}+149x^{17}+172x^{16}+146x^{15}+96x^{14}+26x^{13}+228x^{12}+193x^{11}+54x^{10}+229x^{9}+42x^{8}.
```
<b>Note:</b> Very rarely it can happen that the new lead term is also ```0```, in that case you also have to discard the second term/new lead term. This will affect how many times you repeat the next step.
<b>The generator polynomial is still (and always) the same:</b>
```math
\alpha^{0}x^{25}+\alpha^{43}x^{24}+\alpha^{139}x^{23}+\alpha^{206}x^{22}+\alpha^{78}x^{21}+\alpha^{43}x^{20}+\alpha^{239}x^{19}+\alpha^{123}x^{18}+\alpha^{206}x^{17}+\alpha^{214}x^{16}+\alpha^{147}x^{15}+\alpha^{24}x^{14}+\alpha^{99}x^{13}+\alpha^{150}x^{12}+\alpha^{39}x^{11}+\alpha^{243}x^{10}+\alpha^{163}x^{9}+\alpha^{136}x^{8}.
```
Now perform these steps 8 more times <br>
If you are wondering why 8 times, the length of our initial message polynomial was 9, we did it already once, eight times to go.<br>
Be careful with the case where you had to discard two lead terms.
If it is still hard to undestand you can follow each step very precisely <a href="https://www.thonky.com/qr-code-tutorial/show-division-steps?msg_coeff=64%2C+36%2C+134%2C+144%2C+++236%2C+17%2C+236%2C++17%2C+++236&num_ecc_blocks=17" target="_blank">here</a>. You can also input a custom message polynomial but always use 17 error blocks.
The coefficients will be our Error Correction numbers:<br>
```250``` ```255``` ```60``` ```175``` ```138``` ```205``` ```169``` ```12``` ```87``` ```238``` ```222``` ```39``` ```87``` ```58``` ```213``` ```84``` ```70```.
<b>Note:</b> Like I told you before very rarely both lead terms can be ```0``` in the discard lead term step. In that case you didn't get 17 error correction numbers, but less. So always check if you got 17 numbers, if not you have to append ```0``` at the <b>front</b> of our error correction numbers.
We convert all of these numbers to 8 bit binary strings and append it to our bit sequence from the <b>Data Encoding</b> step. Our finished sequence is now:
```
bits = "0100000000100100100001101001000011101100000100011110110000010001111011001111101011111111001111001010111110001010110011011010100100001100010101111110111011011110001001110101011100111010110101010101010001000110".
```
## Matrix placement, Format and Version Information
Every QR code has three big positioning field to enable the scanner to detect the orientation. These fields are located in the upper two and the lower left corner. They always have the same size so they should be hardcoded.
<img src="https://i.ibb.co/99YtbCj/qrmatrixpkf2.jpg" alt="qrmatrixpkf2" border="0">
Also, the connections between the position fields are always the same.
Now we have to add the information about version, mask, and error correction level. In this kata we always use ```version 1 ```, ```mask 0``` and ```error correction lvl H```. Therfore you can also hardcode this information; every Qr code should look like this, before we even start to place in our data:
<img src="https://i.ibb.co/7jzjQy5/qrmatrixti2.jpg" alt="qrmatrixti2" border="0">
## Insert Data
Now we start to insert our bit sequence into the QR matrix. The way we go through the matrix is very important.
We start in the lower right corner, then we go one to the left, then one to the top and one to the right, then left again and so on. It's easier to follow the red arrow on the following picture.<br>
<b>Important</b>: We have to skip the positioning fields and the information about version, mask and EC lvl. Just skip everything which is in a blue box in this picture:
<img src="https://i.ibb.co/zsqr5JZ/dcode-image-v3.png" alt="dcode-image-v3" border="0">
Here is one more picture, that shows us how to go through the matrix:
<img src="https://i.ibb.co/rFk5Dc5/1920px-QR-Character-Placement-svg.png" alt="1920px-QR_Character_Placement.svg" border="0">
Now that we know how to go through the matrix we can start to insert our data. <br>
Now another important thing comes into play: <b>the mask</b>
Normally every ```1``` in our bit sequence represents a black square and every ```0``` represents a white square but if the condition ```(x+y)%2==0``` is true, we have to invert the color. ```1``` becomes a white square and ```0``` becomes a black square. <br>
```x``` is the line counter of the 21x21 matrix. <br>
```y``` is the column counter of the 21x21 matrix. <br>
Ok, let's start:
- First bit of our sequence is ```0```
- We start in the lower right corner, therefore x is 20 and y is 20 (matrix is 0-based)
- ```(x+y)%2==0``` is true, therefore instead of a white square we place a black square in the lower right corner
<img src="https://i.ibb.co/sW2wnLr/black-Corner.png" alt="black-Corner" border="0">
- Let's take the next bit, which is ```1```
- Now x is still 20 but y is now 19, because we went one to the left
- ```(x+y)%2==0``` is false, so we we insert a black square
etc...
Finally we get the following QR-code, which is the representation of the string "Hi":
<img src="https://i.ibb.co/wBQQsgp/finished-Qr-Code.png" alt="finished-Qr-Code" border="0"> | algorithms | from preloaded import htmlize, alphaTable
byte = "{:08b}" . format
fill = "1110110000010001" * 9
gen = [0, 43, 139, 206, 78, 43, 239, 123, 206,
214, 147, 24, 99, 150, 39, 243, 163, 136]
alphaReverse = {x: i for i, x in enumerate(alphaTable)}
def create_qr_code(text):
code = "0100"
code += byte(len(text))
code += '' . join(map(byte, map(ord, text)))
code += "0000"
code += fill[: 72 - len(code)]
msg = [int(code[i: i + 8], 2) for i in range(0, 72, 8)]
for _ in range(9):
if msg[0]:
x = alphaTable[msg[0]]
tmp = [alphaReverse[(x + y) % 255] for y in gen]
tmp = [y ^ (msg[i] if i < len(msg) else 0) for i, y in enumerate(tmp)]
msg = tmp[1:]
else:
msg = msg[1:]
if len(msg) < 17:
msg = [0] * (17 - len(msg)) + msg
code += '' . join(map(byte, msg))
result = [
[1, 1, 1, 1, 1, 1, 1, 0, 1, 2, 2, 2, 2, 0, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 2, 2, 2, 0, 1, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 2, 2, 2, 2, 0, 1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 1, 2, 2, 2, 2, 0, 1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 2, 2, 2, 2, 0, 1, 0, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 2, 2, 2, 0, 1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 1, 0, 1, 2, 2, 2, 2, 1, 0, 0, 0, 1, 0, 0, 1],
[2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[1, 0, 0, 0, 0, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[1, 0, 1, 1, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[1, 0, 1, 1, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]]
it, down = map(int, code), list(range(21))
up = down[:: - 1]
for x in range(20, 0, - 2):
if x <= 6:
x -= 1
for y in (up if x % 4 in (0, 3) else down):
if result[y][x] == 2:
if (x + y) % 2 == 0:
result[y][x] = 1 - next(it)
result[y][x - 1] = next(it)
else:
result[y][x] = next(it)
result[y][x - 1] = 1 - next(it)
return result
| Create the QR-Code | 5fa50a5def5ecf0014debd73 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5fa50a5def5ecf0014debd73 | 4 kyu |
## Strongly connected components
Let `$V$` be the set of vertices of the graph.
A strongly connected component `$S$` of a directed graph is a maximal subset of its vertices `$S β V$`, so that there is an oriented path from any vertex `$v β S$` to any other vertex `$u \in S$`.
### Example
<center>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/5/5c/Scc.png"></p></center>
In this graph, strongly connected components are
```
[{a, b, e}, {f, g}, {c, d ,h}]
```
## Task
Write a function `strongly_connected_components` which accepts a graph represented as an adjacency list, and returns a list containing set of connected components.
#### Examples:
```python
# Graph from the image
# The vertexes are numbered as follows:
# (0, 1, 2, 3, 4, 5, 6, 7) = (a, b, e, f, c, g, d, h).
# The list in the i-th position of the adjacency list
# contains vertices that have an incoming edge from vertex i.
# For example, from vertex 1 <=> (b), you can get to vertices
# [2, 3, 4] <=> (e, f, c).
>>> graph = [[1], [2, 3, 4], [0, 3], [5],
[5, 6], [3], [4, 7], [5, 6]]
>>> strongly_connected_components(graph)
[{3, 5}, {4, 6, 7}, {0, 1, 2}]
# One more sample
>>> graph = [[1], [2], [3, 4], [0], [5], [6], [4, 7], []]
>>> strongly_connected_components(graph)
[{7}, {4, 5, 6}, {0, 1, 2, 3}]
```
<p>Note: in python scipy is disabled.</p>
| algorithms | # Tarjan's Algorithm
def strongly_connected_components(graph):
def dfs(cur_node, stack, low, disc, in_stack):
nonlocal level
stack . append(cur_node)
checked . add(cur_node)
in_stack[cur_node] = 1
disc[cur_node] = low[cur_node] = (level := level + 1)
for el in graph[cur_node]:
if el not in checked:
dfs(el, stack, low, disc, in_stack)
if in_stack[el]:
low[cur_node] = min(low[cur_node], low[el])
if disc[cur_node] == low[cur_node]:
while True:
in_stack[(el := stack . pop())] = 0
low[el] = low[cur_node]
if el == cur_node:
break
low, disc, level, checked = dict(), dict(), - 1, set()
for i in range(len(graph)):
if i not in checked:
dfs(i, list(), low, disc, __import__('collections'). defaultdict(int))
return [set(j) for _, j in __import__('itertools'). groupby(sorted(low, key=lambda x: low[x]), key=lambda x: low[x])]
| Strongly connected components | 5f74a3b1acfbb20033e5b7d9 | [
"Algorithms",
"Data Structures",
"Performance",
"Graph Theory"
] | https://www.codewars.com/kata/5f74a3b1acfbb20033e5b7d9 | 4 kyu |
# Task
IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges.
A simple edge detection algorithm sets an output pixel's value to be the maximum absolute value of the differences between it and all its surrounding pixels in the input image. Consider the input image below:
![image](https://i.ibb.co/QKQ3wkj/1009-1.jpg)
The upper left pixel in the output image is the maximum of the values |15-15|,|15-100|, and |15-100|, which is 85. The pixel in the 4th row, 2nd column is computed as the maximum of |175-100|, |175-100|, |175-100|, |175-175|, |175-25|, |175-175|,|175-175|, and |175-25|, which is 150.
Images contain 2 to 1,000,000,000 (10^9) pixels. All images are encoded using run length encoding (RLE). This is a sequence of pairs, containing pixel value (0-255) and run length (1-10^9). Input images have at most 1,000 of these pairs. Successive pairs have different pixel values. All lines in an image contain the same number of pixels.
For the iamge as the example above, the RLE encoding string is `"7 15 4 100 15 25 2 175 2 25 5 175 2 25 5"`
```
Each image starts with the width, in pixels(means the first number 7)
This is followed by the RLE pairs(two number is a pair).
7 ----> image width
15 4 ----> a pair(color value + number of pixel)
100 15 ...........ALL.......................
25 2 ..........THESE......................
175 2 ...........ARE.......................
25 5 ..........PAIRS......................
175 2 ...........LIKE......................
25 5 ..........ABOVE......................
```
Your task is to calculate the result by using the edge detection algorithm above. Returns a encoding string in the same format as the input string.
# Exaple
`Please see examples in the example test block.`
# Input/Output
- `[input]` string `image`
A RLE string of image.
- `[output]` a string
A RLE string calculate by using the edge detection algorithm. | algorithms | from collections import deque
class Board:
def __init__(self, nums: list, row_length: int, compressed_runs: list = None):
self . row_length = row_length
self . rows = [nums[i: i + row_length]
for i in range(0, len(nums), row_length)]
if len(self . rows[- 1]) < row_length:
self . rows . pop()
self . column_length = len(self . rows)
self . pixel_value = None
# if compressed_runs:
# for run in compressed_runs:
# print(run.__dict__)
# self.columns = []
# for i in range(0, row_length):
# col = []
# for row in self.rows:
# col.append(row[i])
# self.columns.append(col)
@ staticmethod
def _get_row_length(image: str):
return int(image . split()[0])
@ staticmethod
def _get_nums(zipped_image: list[tuple], row_length: int) - > list:
nums = []
for tup in zipped_image:
new_nums = [int(tup[0])] * int(tup[1])
nums . extend(new_nums)
return nums
def to_rle(self) - > str:
new_nums = []
for row in self . rows:
for num in row:
new_nums . append(num)
rle_list = []
prev_num = new_nums[0]
prev_index = 0
for i, num in enumerate(new_nums):
if num == prev_num and i + 1 < len(new_nums):
continue
rle_list . append(prev_num)
rle_list . append(i - prev_index)
if i + 1 == len(new_nums):
if num != prev_num:
rle_list . append(num)
rle_list . append(1)
else:
rle_list[- 1] += 1
prev_index = i
prev_num = num
rle_list = [str(num) for num in rle_list]
return f" { self . row_length } { ' ' . join ( rle_list )} "
def highest_value(self, values: list) - > int:
return max([abs(self . pixel_value - value) for value in values])
def upper_row(self, i: int, j: int) - > tuple:
if i == 0:
return self . pixel_value, self . pixel_value, self . pixel_value
center = self . rows[i - 1][j]
if j > 0:
left = self . rows[i - 1][j - 1]
else:
left = self . pixel_value
if j < self . row_length - 1:
right = self . rows[i - 1][j + 1]
else:
right = self . pixel_value
return left, center, right
def in_row(self, i: int, j: int) - > tuple:
if j > 0:
left = self . rows[i][j - 1]
else:
left = self . pixel_value
if j < self . row_length - 1:
right = self . rows[i][j + 1]
else:
right = self . pixel_value
return left, right
def lower_row(self, i: int, j: int) - > tuple:
# print(i, j)
if i == self . column_length - 1:
return self . pixel_value, self . pixel_value, self . pixel_value
center = self . rows[i + 1][j]
if j > 0:
left = self . rows[i + 1][j - 1]
else:
left = self . pixel_value
if j < self . row_length - 1:
right = self . rows[i + 1][j + 1]
else:
right = self . pixel_value
return left, center, right
class CompressedRun:
"""run_length is the amount of pixels we chop off."""
def __init__(self, num: int, qty: int, row_length: int):
self . num = num
self . run_length = self . _run_length(qty, row_length)
self . remaining_pixels = qty - self . run_length
# print('quantity\t', qty)
# print('run length\t', self.run_length)
# print('remaining\t', self.remaining_pixels)
# print()
def _run_length(self, qty, row_length) - > int:
return (int(qty / row_length) - 5) * row_length
# return (int(qty / row_length) * row_length - row_length*2)
def compress_tup(self, tup: tuple) - > tuple:
return (tup[0], str(self . remaining_pixels))
# print(tup[0], str(row_length*2 + int(tup[1]) % row_length))
# print(int(tup[1]) % row_length)
# return (tup[0], str(row_length*2 + int(tup[1]) % row_length))
def edge_detection(image: str):
# print()
print('image: ', image)
# print()
row_length = int(image . split()[0])
zipped_image = list(zip(image . split()[1:: 2], image . split()[2:: 2]))
compressed_runs = deque()
for i, tup in enumerate(zipped_image):
# if int(tup[1]) >= row_length * 5 and int(tup[1]) > 1000:
if int(tup[1]) >= row_length * 100:
# print(tup)
run = CompressedRun(num=int(tup[0]), qty=int(
tup[1]), row_length=row_length)
# print(run.__dict__)
compressed_runs . append(run)
tup = run . compress_tup(tup)
zipped_image[i] = tup
# print(tup)
board = Board(Board . _get_nums(zipped_image, row_length),
row_length, list(compressed_runs))
# for row in board.rows:
# print(row)
new_nums = []
for i, row in enumerate(board . rows):
for j in range(0, len(row)):
board . pixel_value = board . rows[i][j]
left, right = board . in_row(i, j)
uleft, ucenter, uright = board . upper_row(i, j)
lleft, lcenter, lright = board . lower_row(i, j)
new_value = board . highest_value(
[left, right, uleft, ucenter, uright, lleft, lcenter, lright])
new_nums . append(new_value)
new_board = Board(new_nums, board . row_length)
# for row in new_board.rows:
# print(row)
rle_encoded = new_board . to_rle()
rle_zipped = list(
zip(rle_encoded . split()[1:: 2], rle_encoded . split()[2:: 2]))
rle_zipped = [list(tup) for tup in rle_zipped]
# for run in compressed_runs:
# print(run.__dict__)
if len(compressed_runs) > 0:
for i, tup in enumerate(rle_zipped):
# TODO i think this following line can fail....
if tup[0] == '0' and int(tup[1]) >= row_length * 3:
# print(tup)
try:
rle_zipped[i] = [
'0', str(int(tup[1]) + compressed_runs . popleft(). run_length)]
except IndexError:
pass
if len(compressed_runs) > 0:
largest = max([int(tup[1]) for tup in rle_zipped])
for i, tup in enumerate(rle_zipped):
if tup[0] == '0' and tup[1] == str(largest):
try:
extra_run = compressed_runs . popleft()
except IndexError:
pass
else:
rle_zipped[i][1] = str(int(largest) + extra_run . run_length)
return f" { row_length } " + ' ' . join([f" { tup [ 0 ]} { tup [ 1 ]} " for tup in rle_zipped])
| Challenge Fun #20: Edge Detection | 58bfa40c43fadb4edb0000b5 | [
"Algorithms"
] | https://www.codewars.com/kata/58bfa40c43fadb4edb0000b5 | 4 kyu |
# 'Magic' recursion call depth number
This Kata was designed as a Fork to the one from donaldsebleung Roboscript series with a reference to:
https://www.codewars.com/collections/roboscript
It is not more than an extension of Roboscript infinite "single-" mutual recursion handling to a "multiple-" case.
One can suppose that you have a machine that works through a specific language. It uses the script, which consists of 3 major commands:
- `F` - Move forward by 1 step in the direction that it is currently pointing.
- `L` - Turn "left" (i.e. rotate 90 degrees anticlockwise).
- `R` - Turn "right" (i.e. rotate 90 degrees clockwise).
The number n afterwards enforces the command to execute n times.
To improve its efficiency machine language is enriched by patterns that are containers to pack and unpack the script.
The basic syntax for defining a pattern is as follows:
`pn<CODE_HERE>q`
Where:
- `p` is a "keyword" that declares the beginning of a pattern definition
- `n` is a non-negative integer, which acts as a unique identifier for the pattern (pay attention, it may contain several digits).
- `<CODE_HERE>` is a valid RoboScript code (without the angled brackets)
- `q` is a "keyword" that marks the end of a pattern definition
For example, if you want to define `F2LF2` as a pattern and reuse it later:
```
p333F2LF2q
```
To invoke a pattern, a capital `P` followed by the pattern identifier `(n)` is used:
```
P333
```
It doesn't matter whether the invocation of the pattern or the pattern definition comes first. Pattern definitions should always be parsed first.
```
P333p333P11F2LF2qP333p11FR5Lq
```
<br>
# ___Infinite recursion___
As we don't want a robot to be damaged or damaging someone else by becoming uncontrolable when stuck in an infinite loop, it's good to consider this possibility in the programs and to build a compiler that can detect such potential troubles before they actually happen.
* ### Single pattern recursion infinite loop
This is the simplest case, that occurs when the pattern is invoked inside its definition:
p333P333qP333 => depth = 1: P333 -> (P333)
* ### Single mutual recursion infinite loop
Occurs when a pattern calls to unpack the mutual one, which contains a callback to the first:
p1P2qp2P1qP2 => depth = 2: P2 -> P1 -> (P2)
* ### Multiple mutual recursion infinite loop
Occurs within the combo set of mutual callbacks without termination:
p1P2qp2P3qp3P1qP3 => depth = 3: P3 -> P1 -> P2 -> (P3)
* ### No infinite recursion: terminating branch
This happens when the program can finish without encountering an infinite loop. Meaning the depth will be considered 0. Some examples below:
P4p4FLRq => depth = 0
p1P2qp2R5qP1 => depth = 0
p1P2qp2P1q => depth = 0 (no call)
<br>
# Task
Your interpreter should be able to analyse infinite recursion profiles in the input program, including multi-mutual cases.
Though, rather than to analyse only the first encountered infinite loop and get stuck in it like the robot would be, your code will have continue deeper in the calls to find the depth of any infinite recursion or terminating call. Then it should return the minimal and the maximal depths encountered, as an array `[min, max]`.
### About the exploration of the different possible branches of the program:
* Consider only patterns that are to be executed:
```
p1P1q => should return [0, 0], there is no execution
p1P2P3qp2P1qp3P1q => similarly [0, 0]
p1P1qP1 => returns [1, 1]
```
* All patterns need to be executed, strictly left to right. Meaning that you may encounter several branches:
```
p1P2P3qp2P1qp3P1qP3 => should return [2, 3]
P3 -> P1 -> P2 -> (P1) depth = 3 (max)
\-> (P3) depth = 2 (min)
```
<br>
# Input
* A valid RoboScript program, as string.
* Nested definitions of patterns, such as `p1...p2***q...q` will not be tested, even if that could be of interest as a Roboscript improvement.
* All patterns will have a unique identifier.
* Since the program is valid, you won't encounter calls to undefined pattern either.
# Output
* An array `[min, max]`, giving what are the minimal and the maximal recursion depths encountered.
### Examples
```
p1F2RF2LqP1 => should return [0, 0], no infinite recursion detected
p1F2RP1F2LqP1 => should return [1, 1], infinite recursion detection case
P2p1P2qp2P1q => should return [2, 2], single mutual infinite recursion case
p1P2qP3p2P3qp3P1q => should return [3, 3], twice mutual infinite recursion case
p1P2P1qp2P3qp3P1qP1 => should return [1, 3], mixed infinite recursion case
```
| algorithms | from collections import defaultdict
from itertools import chain
import re
PARSE = re . compile(r'[pP]\d+|q')
def magic_call_depth_number(prog):
def parse(it, p=''):
for m in it:
if m[0]. startswith('p'):
parse(it, m[0])
elif m[0] == 'q':
return
else:
pCmds[p]. append(m[0]. lower())
def travel(p, seen, d=1):
if not pCmds[p]:
yield 0
else:
for n in pCmds[p]:
if n in seen:
yield d
else:
yield from travel(n, seen | {n}, d + 1)
pCmds = defaultdict(list)
parse(PARSE . finditer(prog))
inf = list(chain . from_iterable(travel(p, {p}) for p in pCmds['']))
return [min(inf, default=0), max(inf, default=0)]
| 'Magic' recursion call depth number | 5c1b23aa34fb628f2e000043 | [
"Algorithms",
"Recursion"
] | https://www.codewars.com/kata/5c1b23aa34fb628f2e000043 | 4 kyu |
## Description
Beggar Thy Neighbour is a card game taught to me by my parents when I was a small child, and is a game I like to play with my young kids today.
In this kata you will be given two player hands to be played. And must return the **index** of the player who will win.
## Rules of the game
- Special cards are: Jacks, Queens, Kings and Aces
- The object of the game is to win all the cards.
- Any player that cannot play a card is out of the game.
To start:
- The 52 cards in a standard deck are shuffled.
- The cards are dealt equally between all players.
To play:
- The first player turns over and plays the top card from their hand into a common pile.
- If the card is not special - then the second player plays their next card onto the pile, and play continues back to the first player.
- If the card is a Jack, Queen, King or Ace, the other player must play 1, 2, 3 or 4 penalty cards respectively.
- If no special cards are played during a penalty, then the player that played the special card, takes the common pile.
- If a special card is played during a penalty, then the penalty moves back to the previous player immediately with the size of the new penalty defined by the new special card. It is possible for this process to repeat several times in one play. Whoever played the last special card, wins the common pile.
- The winner of the common pile, places it on the bottom of their hand, and then starts the next common pile.
It is theorised that an initial deal may never end, though so far all of my games have ended! For that reason, if 10,000 cards are played and no one has won, return `None`.
## Card Encoding
Cards are represented with a two character code. The first characater will be one of A23456789TJQK representing Ace, 2 though 9, Ten, Jack, Queen, King respectively. The second character is the suit, 'S', 'H', 'C', or 'D' representing Spades, Hearts, Clubs and Diamonds respectively.
For example a hand of `["TD", "AC", "5H"]` would represent 10 of Diamonds, Ace of Clubs, and 5 of hearts.
## Mini Example Game
Given the following hands:
`Player 1: [9C, JC, 2H, QC], Player 2: [TD, JH, 6H, 9S]`
Play would flow as follows:
```
Start - P1: [9C, JC, 2H, QC], P2: [TD, JH, 6H, 9S], Common: []
Turn 1 - P1: [JC, 2H, QC], P2: [TD, JH, 6H, 9S], Common: [9C]
Turn 2 - P1: [JC, 2H, QC], P2: [JH, 6H, 9S], Common: [9C, TD]
Turn 3 - P1: [2H, QC], P2: [JH, 6H, 9S], Common: [9C, TD, JC]
```
Player 1 plays a Jack, player 2 pays 1 penalty
```
Turn 4 - P1: [2H, QC], P2: [6H, 9S], Common: [9C, TD, JC, JH]
```
Player 2 plays a Jack, player 1 pays 1 penalty
```
Turn 5 - P1: [QC], P2: [6H, 9S], Common: [9C, TD, JC, JH, 2H]
```
Player 2 wins the common pool and starts the next game
```
Turn 6 - P1: [QC], P2: [9S, 9C, TD, JC, JH, 2H], Common: [6H]
Turn 7 - P1: [], P2: [9S, 9C, TD, JC, JH, 2H], Common: [6H, QC]
```
Player 1 plays a Queen, player 2 pays 2 penalties
```
Turn 8 - P1: [], P2: [9C, TD, JC, JH, 2H], Common: [6H, QC, 9S]
Turn 9 - P1: [], P2: [TD, JC, JH, 2H], Common: [6H, QC, 9S, 9C]
```
Player 1 wins the common pool and starts the next game
```
Turn 10 - P1: [QC, 9S, 9C], P2: [TD, JC, JH, 2H], Common: [6H]
```
And so on... with player 2 eventually winning.
Good luck! | algorithms | def who_wins_beggar_thy_neighbour(* hands, special_cards='JQKA'):
hands = [list(reversed(hand)) for hand in hands]
player, deck_length = 0, sum(map(len, hands))
deal_start, deal_value, common = None, 0, []
while len(hands[player]) < deck_length:
# Deal ends and current player wins common pile
if deal_start == player:
hands[player] = common[:: - 1] + hands[player]
deal_start, deal_value, common = None, 0, []
continue
# Cards are drawn and deal begins if penalty occurs
for _ in range(min(deal_value or 1, len(hands[player]))):
card = hands[player]. pop()
common . append(card)
if card[0] in special_cards:
deal_start, deal_value = player, special_cards . index(card[0]) + 1
break
player = (player + 1) % len(hands)
return player
| Beggar Thy Neighbour | 58dbea57d6f8f53fec0000fb | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/58dbea57d6f8f53fec0000fb | 4 kyu |
# Task
We call letter `x` a counterpart of letter `y`, if `x` is the `i`th letter of the English alphabet, and `y` is the `(27 - i)`th for each valid `i` (1-based). For example, `'z'` is the counterpart of `'a'` and vice versa, `'y'` is the counterpart of `'b'`, and so on.
A properly closed bracket word (`PCBW`) is such a `word` that its first letter is the counterpart of its last letter, its second letter is the counterpart of its last by one letter, and so on.
Determine if the given `word` is a `PCBW` or not.
# Input/Output
- `[input]` string `word`
A string consisting of lowercase letters.
`0 < word.length β€ 30`
- `[output]` a boolean value
`true` if word is a `PCBW`, `false` otherwise.
# Example
For `word = "abiryz"`, the output should be `true`.
`'a' is the counterpart of 'z';`
`'b' <-> 'y'`
`'i' <-> 'r'`
For `word = "aibryz"`, the output should be `false`.
For `word = "abitryz"`, the output should be `false`. | reference | def closed_bracket_word(st):
return len(st) % 2 == 0 and all(ord(st[i]) + ord(st[- i - 1]) == 219 for i in range(len(st) / / 2))
| Simple Fun #215: Properly Closed Bracket Word | 59000d6c13b00151720000d5 | [
"Fundamentals"
] | https://www.codewars.com/kata/59000d6c13b00151720000d5 | 7 kyu |
> The Wumpus world is a simple world example to illustrate the worth of a knowledge-based agent and to represent knowledge representation.
## Wumpus world rules
The Wumpus world is a cave consisting of 16 rooms (in a 4x4 layout) with passageways between each pair of neighboring rooms. This cave contains:
* `1` agent - always starts from room `(0, 0)`
* `1` wumpus, a monster who eats anybody entering his room - inside random empty room
* `1` treasure - inside random empty room
* `1-3` bottomless pits - each inside a random empty room
(The original rules for valid cave layouts are slightly different, but they were changed for the sake of this kata.)
Initially the agent doesn't know the contents of each room. He navigates the cave blindly having only 2 sources of information:
* a smell sensor which signals about the presence of Wumpus in any of the neighboring rooms
* a wind sensor which signals about the presence of a bottomless pit in any of the neighboring rooms
The agent's goal is to find the hidden treasure while avoiding the bottomless pits and avoiding or killing the Wumpus - if the Wumpus's exact location can be determined, the agent can throw a spear in his direction, across a horizontal/vertical row of rooms, and kill the monster (original rules don't require knowing Wumpus's exact location: instead you can take a guess when throwing the spear and an additional sound sensor will tell you whether it hit the monster, but this was also changed for the sake of this kata).
## Task
Implement a function which receives a matrix representing a configuration of the Wumpus world and returns a boolean value signifying whether it's possible to find the treasure safely.
**Note**: the matrix is provided to you for simplicity, so that there would be no need in an oracle-function/oracle-object which would have to be queried for the smell and wind sensors' states in the given room; although, you can print the matrix and see where everything is located for yourself, the agent doesn't know the cave layout, and all his actions must be based on the information that he has gathered, i.e. "I can move here because I know that there will be no bottomless pit in this room" and "I can throw the spear in this direction because I know that Wumpus is located across this row/column". **At the same time, your agent does know how many bottomless pits there are** - this is the only piece of information that both you and your agent share, and it will not be provided as a separate function argument since the input matrix already encodes this information.
### Input matrix format
The input will always be a 4x4 matrix filled with following characters:
* `'W'` - Wumpus
* `'G'` - treasure (gold)
* `'P'` - bottomless pit
* `'_'` - empty space
### Visual example
Additional legend:
* `Agent` - agent's initial location
* `s` - smell from Wumpus
* `w` - wind from bottomless pits
```
|------------|------------|------------|------------|
| | | | |
| | | | |
| Agent |
| | | | wwwwwwww |
| | | | wwwwwwww |
|----- -----|----- -----|----- -----|----- -----|
| | | | |
| | | ww | |
| ww Pit |
| ssssssss | | wwwwwwwww | |
| ssssssss | | wwwwwwww | |
|----- -----|----- -----|----- -----|----- -----|
| | | | wwwwwwww |
| | ss ww | | wwwwwwwww |
| Wumpus ss Gold ww Pit ww |
| | ss ww | | ww |
| | | | |
|----- -----|----- -----|----- -----|----- -----|
| ssssssss | | wwwwwwww | |
| ssssssss | | wwwwwwww | |
| |
| | | | |
| | | | |
|------------|------------|------------|------------|
``` | algorithms | from itertools import combinations
def wumpus_world(cave):
n_pits = sum(v == 'P' for r in cave for v in r)
def neighbors(y, x): return {(y + dy, x + dx) for dy, dx in (
(1, 0), (- 1, 0), (0, 1), (0, - 1)) if 0 <= y + dy < 4 and 0 <= x + dx < 4}
smells = {(i, j): [] for i in range(4) for j in range(4)}
for i, r in enumerate(cave):
for j, v in enumerate(r):
if v in "PW":
for di, dj in ((- 1, 0), (1, 0), (0, - 1), (0, 1)):
if (i + di, j + dj) in smells:
smells[(i + di, j + dj)]. append(v)
unexplored = {(0, 0)}
seen = set()
w_smells, p_smells, pits = [], [], set()
while unexplored:
y, x = unexplored . pop()
if cave[y][x] == "G":
return True
seen . add((y, x))
if "W" in smells[(y, x)]:
w_smells . append((y, x))
if "P" in smells[(y, x)]:
p_smells . append((y, x))
if not smells[(y, x)]:
unexplored |= neighbors(y, x) - seen
w_opts = set . intersection(* ([neighbors(* a) for a in w_smells] or [set()])) - \
seen - set(). union(* (neighbors(* a) for a in (seen - set(w_smells))))
if len(w_opts) == 1:
unexplored . add(w_opts . pop())
unexplored |= set(w_smells)
w_smells . clear()
smells = {k: ['P'] if 'P' in v else [] for k, v in smells . items()}
non_windy = set(). union(* (neighbors(* a)
for a in (seen - set(p_smells))))
for windy in p_smells:
potentials = neighbors(* windy) - seen - non_windy
if len(potentials) == 1:
pits |= potentials
def satisfies(t): return set(p_smells) == set(). union(
* (neighbors(* a) for a in t)) & seen
all_opts = set(). union(* (neighbors(* a) for a in p_smells)) - seen
p_opts = list(filter(satisfies, combinations(all_opts, n_pits)))
p_lt_opts = list(
filter(satisfies, combinations(all_opts, max(0, n_pits - 1))))
if len(p_opts) == 1 and len(p_lt_opts) == 0:
pits = set(p_opts[0])
elif len(p_opts) > 1:
proven_safe = ({(y, x) for y in range(4) for x in range(4) if any(a in seen and 'W' not in smells[a] for a in neighbors(y, x))}
- {x for opt in p_opts for x in opt}
- seen)
unexplored |= proven_safe
if len(pits) == n_pits:
smells = {k: ['W'] if 'W' in v else [] for k, v in smells . items()}
unexplored |= set(p_smells)
p_smells . clear()
unexplored -= pits # make sure not to die
return False
| Wumpus world | 625c70f8a071210030c8e22a | [
"Artificial Intelligence",
"Algorithms",
"Game Solvers"
] | https://www.codewars.com/kata/625c70f8a071210030c8e22a | 2 kyu |
For this kata, you have to compute the distance between two points, A and B, in a two-dimensional plane.
We don't want to make this *too* simple though, so there will also be points C[1], C[2], ... C[n] which must be avoided. Each point C[i] is surrounded by a forbidden zone of radius r[i] through which the route from A to B may not pass.
A picture may help:
![Picture of shortest path through circular obstacles](http://www.stat.auckland.ac.nz/~geoff/codewars/tiptoepic1.png)
The blue curve is the shortest route from A to B that does not pass through the yellow forbidden zones. The grey curves show alternative routes that also avoid the forbidden zones, but are not the shortest possible.
Your function should return the length of the shortest possible route from A to B. It does not need to return the route itself. If the problem is infeasible (there is no route from A to B that doesn't pass through a forbidden zone), return -1.0 .
Some more examples (these are typical of what to expect from the test cases):
![Example 2](http://www.stat.auckland.ac.nz/~geoff/codewars/tiptoepic2.png)
![Example 3](http://www.stat.auckland.ac.nz/~geoff/codewars/tiptoepic3.png)
**Hint.** If you don't know where to begin, try reading up on [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra's_algorithm). That will get you started, but it's not the whole story; you also have to incorporate the plane geometry calculations.
**Additional notes.** A couple of simple structures are already defined for you, and are used to specify the problem:
```cpp
struct Point
{
double x,y;
Point() : x(0.0), y(0.0) {}
Point(double x, double y) : x(x), y(y) {}
};
struct Circle
{
Point ctr;
double r;
Circle() : ctr(), r(1.0) {}
Circle(Point c, double r) : ctr(c), r(r) {}
Circle(double cx, double cy, double r) : ctr(cx,cy), r(r) {}
};
```
```python
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
class Circle(NamedTuple):
ctr: Point
r: float
```
**Tests** include
```if:python
- a few small fixed tests,
- 20 random tests with no more than 40 circles and
- 10 random tests with 62 circles in a grid.
```
```if:cpp
- a few small fixed tests,
- 64 random tests with no more than 40 circles and
- 64 random tests with 119 circles in a grid.
``` | algorithms | import numpy as np
from heapq import *
np . seterr(all='ignore')
np . set_printoptions(precision=3)
def shortest_path_length(a, b, cs):
center = np . array([a . x + a . y * 1j] + [c . ctr . x +
c . ctr . y * 1j for c in cs] + [b . x + b . y * 1j])
radius = np . array([0] + [c . r for c in cs] + [0])
crange = np . arange(len(center))
diff = - np . subtract . outer(center, center)
dist, phase = np . abs(diff), np . angle(diff)
np . fill_diagonal(dist, np . nan)
np . fill_diagonal(phase, np . nan)
lower = 2 * np . tri(len(radius)) - 1
beta = np . arccos(np . subtract . outer(radius, radius) / dist)
gamma = np . arccos(np . add . outer(radius, radius) / dist)
phases = np . stack((phase + beta * lower, phase - beta * lower,
phase + gamma, phase - gamma), axis=- 1) % (2 * np . pi)
blocked = phase % (2 * np . pi)
blocked[~ np . isnan(gamma)] = np . nan
inside = np . nonzero(np . any(np . less . outer(radius, radius) &
np . all(np . isnan(phases), axis=- 1), axis=- 1))
blocked[:, inside] = blocked[inside, :] = np . nan
phases[:, inside, :] = phases[inside, :, :] = np . nan
points = center[:, None, None] + \
np . exp(1j * phases) * radius[:, None, None]
inside = np . abs(points[..., None] - center[None,
None, None, :]) < radius[None, None, None, :]
inside[crange, :, :, crange] = inside[:, crange, :, crange] = False
inside = np . any(inside, 3)
inside = inside | inside . swapaxes(0, 1)
phases[inside] = points[inside] = np . nan
vector = (points . swapaxes(0, 1) - points)[..., None]
delta = np . imag(np . conjugate(vector) *
(center[None, None, None, :] - points[..., None])) / np . abs(vector)
delta[crange, :, :, crange] = delta[:, crange, :, crange] = np . nan
ortho = center[None, None, None, :] - \
vector / np . abs(vector) * 1j * delta
reals = np . stack((points, points . swapaxes(0, 1)), axis=- 1)
reals, imags = np . sort(np . real(reals))[:, :, :, None, :], np . sort(
np . imag(reals))[:, :, :, None, :]
inside = (np . abs(delta) <= radius[None, None, None, :]) \
& (reals[..., 0] <= np . real(ortho)) & (np . real(ortho) <= reals[..., 1]) \
& (imags[..., 0] <= np . imag(ortho)) & (np . imag(ortho) <= imags[..., 1])
inside[crange, :, :, crange] = inside[:, crange, :, crange] = False
inside = np . any(inside, 3)
inside |= inside . swapaxes(0, 1)
phases[inside] = points[inside] = np . nan
def dijkstra(neighbors, start):
seen, queue = set(), [(0, (start, None))]
while queue:
cost, (pos, path) = heappop(queue)
if pos in seen:
continue
seen . add(pos)
yield cost, (pos, path)
for cost1, pos1 in neighbors(pos):
heappush(queue, (cost + cost1, (pos1, (pos, path))))
def neighbors(posn):
posn1 = posn[1], posn[0], posn[2]
if not np . isnan(cost := np . abs(points[posn] - points[posn1])):
yield cost, posn1
block, phase0 = blocks[posn[0]], phases[posn]
phase0 = 0 if np . isnan(phase0) else phase0
for posn2 in angles[posn[0]]:
posn2 = posn[0], posn2[0], posn2[1]
phase1, phase2 = sorted((phase0, phases[posn2]))
if not np . any((phase1 < block) & (block < phase2)):
yield radius[posn[0]] * (phase2 - phase1), posn2
if not np . any((block < phase1) | (phase2 < block)):
yield radius[posn[0]] * (phase1 + 2 * np . pi - phase2), posn2
blocks = [xs[~ np . isnan(xs)] for xs in blocked]
angles = [list(zip(* np . nonzero(~ np . isnan(xs)))) for xs in phases]
for cost, (posn, _) in dijkstra(neighbors, (len(center) - 1, 0, 0)):
if posn[0] == 0:
return cost
return - 1
| Tiptoe through the circles | 58b617f15705ae68cc0000a9 | [
"Algorithms",
"Geometry",
"Mathematics",
"Graph Theory"
] | https://www.codewars.com/kata/58b617f15705ae68cc0000a9 | 1 kyu |
<!-- Assorted Rectangular Pieces Puzzle -->
<p>You are given an assortment of rectangular pieces and a square board with holes in it. You need to arrange the pieces on the board so that all the pieces fill up the holes in the board with no overlap.</p>
<h2 style='color:#f88'>Input</h2>
<p>Your function will receive two arguments:</p>
<ul>
<li><code style='color:#8df'>board</code> : an array/list of length <code>n</code> where each element is a string of length <code>n</code> consisting of <code>0</code>s and/or spaces. Each contiguous cluster of <code>0</code>s represents a hole in the board.</li>
<li><code style='color:#8df'>pieces</code> : an array/list where each element is in the form <code>[h,w]</code> where <code>h</code> and <code>w</code> represent the height and width of each piece, respectively.
</ul>
<h2 style='color:#f88'>Output</h2>
<p>An array with the position of each piece to solve the puzzle. Each element should be an array in the form <code>[x,y,z]</code> where:</p>
<ul>
<li><code>x</code> and <code>y</code> represents the piece's top-left corner position, as illustrated in the example below</li>
<li><code>z</code> represents the orientation of the piece -- normal or rotated <code>90</code> degrees. If rotated, <code>z</code> is <code>1</code>, otherwise it's <code>0</code></li>
<li>Each piece corresponds to the element from <code>pieces</code> with the same index position</li>
</ul>
<h2 style='color:#f88'>Test Example</h2>
<p>Figure <code style='color:#f66'>A</code>: initial state of the puzzle board.<br/>Figure <code style='color:#f66'>B</code>: one possible configuration. Note that the number in each rectangle indicates its index in the input array.</p>
<img src="https://i.imgur.com/NCHwdqW.png" alt="example image"><br/>
```javascript
let board = [
' ',
' 00000 ',
' 00000 ',
' 00000 00 ',
' 000 ',
' 00 000 ',
' 0000 00 ',
' 0000 00 ',
' 00 000 0 ',
' 000 0 ',
' 0 0 ',
'000 '
];
let pieces = [[1,1], [1,1], [1,2], [1,2], [1,2], [1,3], [1,3], [1,4], [1,4], [2,2], [2,2], [2,3], [2,3], [2,5]];
solve_puzzle(board,pieces); // [[11,0,0],[11,1,0],[1,1,0],[3,9,0],[10,2,1],[1,3,0],[8,10,1],[4,7,1],[6,6,1],[4,8,0],[8,7,0],[5,3,1],[6,1,1],[2,1,0]]
```
```python
board = [
' ',
' 00000 ',
' 00000 ',
' 00000 00 ',
' 000 ',
' 00 000 ',
' 0000 00 ',
' 0000 00 ',
' 00 000 0 ',
' 000 0 ',
' 0 0 ',
'000 '
]
pieces = [[1,1], [1,1], [1,2], [1,2], [1,2], [1,3], [1,3], [1,4], [1,4], [2,2], [2,2], [2,3], [2,3], [2,5]]
solve_puzzle(board,pieces); # [[11,0,0],[11,1,0],[1,1,0],[3,9,0],[10,2,1],[1,3,0],[8,10,1],[4,7,1],[6,6,1],[4,8,0],[8,7,0],[5,3,1],[6,1,1],[2,1,0]]
```
<h2 style='color:#f88'>Technical Constraints</h2>
<ul>
<li>Each test will have one or more possible solutions</li>
<li>Every piece must be used to solve the puzzle</li>
<li>Every piece is a rectangle with height and width in the range: <code>12 >= x >= 1</code></li>
<li>Number of pieces: <code>70 >= pieces >= 1</code></li>
<li><code>n</code> x <code>n</code> board dimensions: <code>24 >= n >= 4</code></li>
<li>Full Test Suite: <code>15</code> fixed tests, <code>60</code> random tests</li>
<li>Efficiency is necessary to pass</li>
<li>JavaScript: prototypes have been frozen and <code>require</code> has been disabled</li>
</ul>
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored). | algorithms | def ck(p, i, j, b, X, Y):
for k1 in range(i, i + p[0]):
for k2 in range(j, j + p[1]):
if not (0 <= k1 < X and 0 <= k2 < Y and b[k1][k2] == "0"):
return frozenset()
return frozenset((k1, k2) for k1 in range(i, i + p[0]) for k2 in range(j, j + p[1]))
from itertools import combinations
from collections import deque
class Piece:
def __init__(self, n, p, z, b, X, Y):
self . n, self . piece, self . total_area = n, p, n * p[0] * p[1]
self . poses = {res: (i, j, k) for i, j in z for k in range(2) if (
res := ck(p, i, j, b, X, Y) if k == 0 else ck((p[1], p[0]), i, j, b, X, Y))}
self . stack = deque([])
self . answer = set()
def valid_moves(self):
for move in combinations(self . poses, self . n):
res = set(j for i in move for j in i)
if len(res) == self . total_area:
self . answer = set(self . poses[i] for i in move)
yield res
def delete_moves(self, res):
my_dict = {}
for move in list(self . poses):
if move & res:
my_dict[move] = self . poses[move]
del self . poses[move]
self . stack . append(my_dict)
def add_moves(self):
my_dict = self . stack . pop()
for key, value in my_dict . items():
self . poses[key] = value
def search(data, i, X):
if i == X:
return True
piece: Piece = data[i]
for res in piece . valid_moves():
for j in range(i + 1, X):
data[j]. delete_moves(res)
if search(data, i + 1, X):
return True
for j in range(i + 1, X):
data[j]. add_moves()
def solve_puzzle(b, pieces):
pieces = tuple(tuple(x) for x in pieces)
X, Y = len(b), len(b[0])
up = set(p for p in pieces if not (p[0] == 1 and p[1] == 1))
z = set((i, j) for i in range(X) for j in range(Y) if b[i][j] == "0")
data = sorted([Piece(pieces . count(p), p, z, b, X, Y)
for p in up], key=lambda x: x . piece, reverse=True)
search(data, 0, len(data))
z = z - set(el for x in data for i, j, k in x . answer for el in (ck(x . piece,
i, j, b, X, Y) if k == 0 else ck((x . piece[1], x . piece[0]), i, j, b, X, Y)))
answers = {x . piece: x . answer for x in data} | {
(1, 1): set((i, j, 0) for i, j in z)}
return [list(answers[p]. pop()) for p in pieces]
| Assorted Rectangular Pieces Puzzle | 5a8f42da5084d7dca2000255 | [
"Puzzles",
"Performance",
"Algorithms",
"Game Solvers"
] | https://www.codewars.com/kata/5a8f42da5084d7dca2000255 | 2 kyu |
<style>
.game-title-pre{
width: fit-content;
background: black;
color: red;
font-weight: bold;
line-height: 1.25;
margin: auto;
padding-left: 1em;
padding-right: 1em;
}
.game-title-separator{
background: red !important;
}
.reminder-details{
border: 2px solid var(--color-ui-border);
border-radius: 0.25em;
padding: 0.75em;
}
.reminder-summary{
font-weight: bold;
outline: none;
}
</style>
> This is the second part of the **RPG Simulator** series. I recomend trying out the [first part](https://www.codewars.com/kata/5e95b6e90663180028f2329d/python) before this one. It is highly unlikely that you will be able to solve the second part without knowing the mechanics that are explained in the previous part.
# Let's play some games!
<pre class="game-title-pre">
______ _ _
| _ \ | | | |
| | | |___ _ __ ___ ___ _ __ | | | | __ _ _ __ ___
| | | / _ \ '_ ` _ \ / _ \| '_ \ | |/\| |/ _` | '__/ __|
| |/ / __/ | | | | | (_) | | | | \ /\ / (_| | | \__ \
|___/ \___|_| |_| |_|\___/|_| |_| \/ \/ \__,_|_| |___/
<hr class="game-title-separator"> A turn-based role-playing game
</pre>
Since you succeded in the task of programming a simulator for **_Demon Wars_**, you want to try and build a full artificial intelligence on top of it. It will work by analyzing the map *as is* (i.e. no extra information), so start up by building some intuition for the game!
------------
<details class="reminder-details">
<summary class="reminder-summary">Reminder from the previous part</summary>
# The basics
This game features procedurally generated stages like this one:
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:green">Health:</span> <span style="color:red">β₯οΈ β₯οΈ β₯οΈ</span> <span style="color:green">Atk:</span> 1 <span style="color:green">Def:</span> 1 <span style="color:green">Bag:</span> []
<hr style="margin:0; border: none; height: 1px; background: gray"><span style="color:lightgreen">K</span> <span style="color:crimson">E</span> | <span style="color:lightgreen">X</span># <span style="color:lightgreen">C</span> <span style="color:crimson">E</span> <span style="color:lightgreen">S</span># <span style="color:red">D</span>
<span style="color:crimson">E</span> ####### ###### <span style="color:crimson">E</span> <span style="color:crimson">E</span>
##### ##### ###-##
<span style="color:orangered">M</span> <span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span>
### ###
# ##<span style="color:crimson">E</span>##<span style="color:crimson">E</span>##
<span style="color:teal">^</span> # <span style="color:lightgreen">C</span> <span style="color:lightgreen">K</span>#
<span style="color:lightgreen">C</span> # <span style="color:lightgreen">H</span> ##<span style="color:crimson">E</span>##<span style="color:crimson">E</span>##
</pre>
<br>
As you can see in the upper status bar, your player starts with **three Health Points**, **1 Attack**, **1 Defense** and an empty **Bag**. These are the only stats that you have to care about for the game. As for the map, we can see many different things, so let's explain every tile one by one:
* `^` or `v` or `<` or `>` => **Player** (you). It can face any of four directions.
* `#` => **Wall**. You cannot pass through here.
* `C` => **Coin _[object]_**.
* `M` => **Merchant**. They will go away if you give them **three coins**.
* `K` => **Key _[object]_**. They can open a door, after which they break _(yes, like in horror games)_.
* `-` and `|` => **Doors** _(there are two doors in the map above)_.
* `H` => **Health Potion _[object]_**. It refuels your life to three hearts.
* `S` => **Shield**. It gives **+1 defense** permanently.
* `X` => **Dual Swords**. It gives **+1 attack** permanently.
* `E` => **Enemy**. Has **1 Health Point** and **2 Attack**.
* `D` => **Demon Lord**. Has **10 Health Points** and **3 Attack**. You win the game if you kill him.
Now, _Demon Wars_ is a turn based game with tank controls. Each turn you can either:
* Move forward.
* Change direction.
* Use an item.
* Attack the enemy you have in front of you.
------------
# Attack mechanics and enemies
When you use the attack command, you will attack the enemy right in front of you and deal **the same amount of damage as your attack stat**:
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:crimson">E</span> <span style="color:crimson">E</span>
<span style="color:teal">></span><span style="color:crimson">E</span> <span style="color:darkgray">=== [Attack] ==></span> <span style="color:teal">></span>
<span style="color:crimson">E</span> <span style="color:crimson">E</span>
</pre>
<br>
**However**, an enemy can attack you (whatever your orientation is), as long as you are on an adjacent cell to the enemy (vertically or horizontally, not diagonally) and if one of those conditions is fullfilled:
* If you turn your character during the turn.
* If you move away from them (_D&D's opportunity attack_ :D).
* If you use a potion. You will still recover your life points, but then you will be attacked.
The damage formula is `max(0, (Enemy's attack stat) - (Your defense stat))`. Just remember that you attack and use objects **before** the enemies besides you attack. Here is an example where two enemies would attack you:
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span> <span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span>
<span style="color:teal">></span><span style="color:crimson">E</span> <span style="color:darkgray">=== [Attack] ==></span> <span style="color:teal">></span>
<span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span> <span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span>
</pre>
But enemies are more than obstacles, each time you defeat three of them (demon lord not included), you level up! This level increase will give you **+1 attack** permanently.
------------
# Object usage mechanics
There are only three cases where it is acceptable to use objects:
* When you use a key in front of a closed door.
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
# #
<span style="color:teal">></span>| <span style="color:darkgray">=== [Use Key] ==></span> <span style="color:teal">></span>
# #
</pre>
<br>
* When you use a coin in front of a merchant (repeat three times for them to go away).
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:teal">></span><span style="color:orangered">M</span> <span style="color:darkgray">=== [Use Coin] ==></span> <span style="color:teal">></span><span style="color:orangered">M</span> <span style="color:darkgray">=== [Use Coin] ==></span> <span style="color:teal">></span><span style="color:orangered">M</span> <span style="color:darkgray">=== [Use Coin] ==></span> <span style="color:teal">></span>
</pre>
<br>
* When you refuel your life using a potion (you must have suffered some damage).
Any other object usage is considered **invalid**. Also, this is more or less standard, but you have to walk over an object to pick it up automatically.
</details>
------------
# Your task
Write a function `rpg(field: List[List[str]]) -> List[str]` that takes a map as input and returns a list of actions. This sequence of actions will be fed to a simulator and it will have to return a state where you are alive and there is **no Demon Lord**.
The syntax of the actions is the same as in the first part:
* `F` to move forward.
* `^`, `>`, `v` and `<`to rotate the player.
* `A` to attack the enemy you have in front of you.
* `C`, `K` and `H` to use a coin, a key and a health potion, respectively.
**Technical notes:**
* You **can** mutate the input (and probably should), but it is not necessary.
* There will only be one Demon Lord per map, but every other tile may be repeated two or even more times.
* Only the tiles marked as **[object]** will be stored in your bag (i.e. keys, coins and potions).
* Only valid inputs will be given.
# Preloaded code
You are given two functions for debugging purposes:
* `only_show_wrong()`: disable the map print of the test cases that you solved successfully. Use this only once at the beginning or your code.
* `print_map(map)`: this function prints a map in a human-readable format for debugging purposes. It is done by default in every test case unless it is disabled.
------------
# Building intuition - An example
You might have programmed the simulator without worrying too much about strategies, so let's take a look at the map from the previous part and try to solve it.
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:green">Health:</span> <span style="color:red">β₯οΈ β₯οΈ β₯οΈ</span> <span style="color:green">Atk:</span> 1 <span style="color:green">Def:</span> 1 <span style="color:green">Bag:</span> []
<hr style="margin:0; border: none; height: 1px; background: gray"><span style="color:lightgreen">K</span> <span style="color:crimson">E</span> | <span style="color:lightgreen">X</span># <span style="color:lightgreen">C</span> <span style="color:crimson">E</span> <span style="color:lightgreen">S</span># <span style="color:red">D</span>
<span style="color:crimson">E</span> ####### ###### <span style="color:crimson">E</span> <span style="color:crimson">E</span>
##### ##### ###-##
<span style="color:orangered">M</span> <span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span>
### ###
# ##<span style="color:crimson">E</span>##<span style="color:crimson">E</span>##
<span style="color:teal">^</span> # <span style="color:lightgreen">C</span> <span style="color:lightgreen">K</span>#
<span style="color:lightgreen">C</span> # <span style="color:lightgreen">H</span> ##<span style="color:crimson">E</span>##<span style="color:crimson">E</span>##
</pre>
<br>
There are multiple ways of solving this, but this can be a valid sequence of actions:
1. Kill the enemy at the top-right and taking the shield to increase your defense.
2. Take the coins and make the merchant go away.
3. Clear the room at the top-left.
4. Go kill the demon when you have a high enough level.
There are multiple ways to clear this level, but this is just a way to do it. Is there a *dominant strategy*?
# Bonus challenge for fame and glory
You have an unbounded number of actions you can take to clear each map, but the **mean number of actions** will be calculated at the end of the tests. How low can you go?
**_My solution:_** about 100 actions per map (this should be kind of a maximum. I haven't tried to optimize this at all)
----------------
<h3 style="text-align: center"><i>As always, I hope you have fun with this kata :)</i></h3> | algorithms | from typing import List
DIRS = {'^': (- 1, 0), 'v': (1, 0), '<': (0, - 1), '>': (0, 1)}
def rpg(field: List[List[str]]) - > List[str]:
# print('\n'.join(map(''.join, field)))
nx, ny = len(field), len(field[0])
def next_object(x, y, dir, health):
queue = [(x, y, dir, health, 0, bag['H'], 10, '')]
visited = set([(x, y, health)])
min_damage, result = float('inf'), (x, y, dir, health, '')
while queue:
new_queue = []
for x, y, dir, health, total_damage, potion, demon, moves in queue:
if health <= 0:
continue
# damage form all enemies except front
damage = sum(max(0, (3 if field[i][j] == 'D' else 2 if d != dir else 0) - defense) for d, (dx, dy) in DIRS . items()
if 0 <= (i := x + dx) < nx and 0 <= (j := y + dy) < ny and field[i][j] in "ED")
health -= damage
total_damage += damage
if min_damage < total_damage:
continue
visited . add((x, y, health))
if health < 3 and potion > 0: # try used health potion
new_queue . append((x, y, dir, 3 - damage, total_damage,
potion - 1, demon, moves + 'H'))
if field[x][y] in "CKHSX": # coin, key, health potion, shield or dual swords found
res = x, y, dir, health, moves
if total_damage == 0:
return res
if total_damage < min_damage:
min_damage, result = total_damage, res
# turns
# skip if prev action is rotation
if health > 0 and not moves or moves[- 1] not in DIRS:
# do not run from demon
if not (0 <= i < nx and 0 <= j < ny) or field[i][j] != 'D':
for d in DIRS:
if d != dir:
new_queue . append(
(x, y, d, health, total_damage, potion, demon, moves + d))
# front
dx, dy = DIRS[dir]
i, j = x + dx, y + dy
if 0 <= i < nx and 0 <= j < ny and field[i][j] != '#' and (i, j, health) not in visited:
v = field[i][j]
if v in ' CKHSX': # empty or item
new_queue . append((i, j, dir, health, total_damage,
potion, demon, moves + 'F'))
elif v == 'D': # demon
demon -= attack
moves += 'A'
if demon <= 0:
return x, y, dir, health, moves
queue . append((x, y, dir, health, total_damage,
potion, demon, moves)) # same queue
elif health > 0:
res = None
if v == 'M': # merchant
if bag['C'] >= 3 and damage == 0:
res = x, y, dir, health, moves + 'CCC'
if total_damage == 0:
return res
elif v in '-|': # door
if bag['K'] > 0:
res = x, y, dir, health, moves + 'K'
# priority to door with key behind it
total_damage -= has_key_behind_door(i, j, dir)
elif v == 'E': # enemy
res = x, y, dir, health, moves + 'A'
if total_damage == 0:
return res
if res and total_damage < min_damage:
min_damage, result = total_damage, res
queue = new_queue
return result
def has_key_behind_door(x, y, dir):
visited = set([(x, y)])
dx, dy = DIRS[dir]
x += dx
y += dy
queue = [(x, y)]
for x, y in queue:
if field[x][y] == 'K':
return True
for dx, dy in DIRS . values():
if 0 <= (i := x + dx) < nx and 0 <= (j := y + dy) < ny and field[i][j] not in '#-|D' and (i, j) not in visited:
visited . add((i, j))
queue . append((i, j))
return False
x, y = next((x, y) for x, r in enumerate(field)
for y, v in enumerate(r) if v in DIRS)
dir, field[x][y] = field[x][y], ' '
health, attack, defense, bag = 3, 1, 1, {'C': 0, 'K': 0, 'H': 0}
enemies, demon, moves = 0, 10, ''
while True:
x, y, dir, health, move = next_object(x, y, dir, health)
if not move:
break # no solution?
moves += move
bag['H'] -= move . count('H')
t = move[- 1]
if t == 'F':
v = field[x][y]
if v == 'S':
defense += 1 # shield
elif v == 'X':
attack += 1 # dual swords
elif v in "CKH":
bag[v] += 1 # object
field[x][y] = ' '
else:
dx, dy = DIRS[dir]
i, j = x + dx, y + dy
if t == 'C':
bag['C'] -= 3 # give coins to merchant
elif t == 'K':
bag['K'] -= 1 # use key
elif t == 'A': # attack
if field[i][j] == 'D':
return list(moves) # demon defeated
enemies += 1
if enemies % 3 == 0:
attack += 1
field[i][j] = ' '
| RPG Simulator - Defeat the Demon Lord! [Part 2] | 5ea806698dbd1a001af955f3 | [
"Games",
"Game Solvers",
"Algorithms"
] | https://www.codewars.com/kata/5ea806698dbd1a001af955f3 | 2 kyu |
# Let's play some games!
A new RPG called **_Demon Wars_** just came out! Imagine the surprise when you buy it after work, go home, start you _GameStation X_ and it happens to be too difficult for you. Fortunately, you consider yourself a computer connoisseur, so you want to build an AI that tells you every step you have to make to **defeat the evil Demon Lord** and win the game. For now, let's program a simulator.
This game features procedurally generated stages like this one:
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:green">Health:</span> <span style="color:red">β₯οΈ β₯οΈ β₯οΈ</span> <span style="color:green">Atk:</span> 1 <span style="color:green">Def:</span> 1 <span style="color:green">Bag:</span> []
<hr style="margin:0; border: none; height: 1px; background: gray"><span style="color:lightgreen">K</span> <span style="color:crimson">E</span> | <span style="color:lightgreen">X</span># <span style="color:lightgreen">C</span> <span style="color:crimson">E</span> <span style="color:lightgreen">S</span># <span style="color:red">D</span>
<span style="color:crimson">E</span> ####### ###### <span style="color:crimson">E</span> <span style="color:crimson">E</span>
##### ##### ###-##
<span style="color:orangered">M</span> <span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span>
### ###
# ##<span style="color:crimson">E</span>##<span style="color:crimson">E</span>##
<span style="color:teal">^</span> # <span style="color:lightgreen">C</span> <span style="color:lightgreen">K</span>#
<span style="color:lightgreen">C</span> # <span style="color:lightgreen">H</span> ##<span style="color:crimson">E</span>##<span style="color:crimson">E</span>##
</pre>
<br>
As you can see in the upper status bar, your player starts with **three Health Points**, **1 Attack**, **1 Defense** and an empty **Bag**. These are the only stats that you have to care about for the game. As for the map, we can see many different things, so let's explain every tile one by one:
* `^` or `v` or `<` or `>` => **Player** (you). It can face any of four directions.
* `#` => **Wall**. You cannot pass through here.
* `C` => **Coin _[object]_**.
* `M` => **Merchant**. They will go away if you give them **three coins**.
* `K` => **Key _[object]_**. They can open a door, after which they break _(yes, like in horror games)_.
* `-` and `|` => **Doors** _(there are two doors in the map above)_.
* `H` => **Health Potion _[object]_**. It refuels your life to three hearts.
* `S` => **Shield**. It gives **+1 defense** permanently.
* `X` => **Dual Swords**. It gives **+1 attack** permanently.
* `E` => **Enemy**. Has **1 Health Point** and **2 Attack**.
* `D` => **Demon Lord**. Has **10 Health Points** and **3 Attack**. You win the game if you kill him.
Now, _Demon Wars_ is a turn based game with tank controls. Each turn you can either:
* Move forward.
* Change direction.
* Use an item.
* Attack the enemy you have in front of you.
<br>
<p style="text-align: center"><i>Will you be able to defeat your foe and save us all?</i></p>
---------------------
# Attack mechanics and enemies
When you use the attack command, you will attack the enemy right in front of you and deal **the same amount of damage as your attack stat**:
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:crimson">E</span> <span style="color:crimson">E</span>
<span style="color:teal">></span><span style="color:crimson">E</span> <span style="color:darkgray">=== [Attack] ==></span> <span style="color:teal">></span>
<span style="color:crimson">E</span> <span style="color:crimson">E</span>
</pre>
<br>
**However**, an enemy can attack you (whatever your orientation is), as long as you are on an adjacent cell to the enemy (vertically or horizontally, not diagonally) and if one of those conditions is fullfilled:
* If you turn your character during the turn.
* If you move away from them (_D&D's opportunity attack_ :D).
* If you use a potion. You will still recover your life points, but then you will be attacked.
The damage formula is `max(0, (Enemy's attack stat) - (Your defense stat))`. Just remember that you attack and use objects **before** the enemies besides you attack. Here is an example where two enemies would attack you:
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span> <span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span>
<span style="color:teal">></span><span style="color:crimson">E</span> <span style="color:darkgray">=== [Attack] ==></span> <span style="color:teal">></span>
<span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span> <span style="color:crimson">E</span><span style="color:crimson">E</span><span style="color:crimson">E</span>
</pre>
But enemies are more than obstacles, each time you defeat three of them (demon lord not included), you level up! This level increase will give you **+1 attack** permanently.
# Object usage mechanics
There are only three cases where it is acceptable to use objects:
* When you use a key in front of a closed door.
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
# #
<span style="color:teal">></span>| <span style="color:darkgray">=== [Use Key] ==></span> <span style="color:teal">></span>
# #
</pre>
<br>
* When you use a coin in front of a merchant (repeat three times for them to go away).
<pre style="text-align: center; background:black; width: fit-content; margin: auto; border: 1px solid gray; line-height: 1.25">
<span style="color:teal">></span><span style="color:orangered">M</span> <span style="color:darkgray">=== [Use Coin] ==></span> <span style="color:teal">></span><span style="color:orangered">M</span> <span style="color:darkgray">=== [Use Coin] ==></span> <span style="color:teal">></span><span style="color:orangered">M</span> <span style="color:darkgray">=== [Use Coin] ==></span> <span style="color:teal">></span>
</pre>
<br>
* When you refuel your life using a potion (you must have suffered some damage).
Any other object usage is considered **invalid**. Also, this is more or less standard, but you have to walk over an object to pick it up automatically.
---------------------
# Your task
Write a function `rpg(field: List[List[str]], actions: List[str]) -> Tuple[List[List[str]], int, int, int, List[str]]` that takes the initial state of the game map and a list of actions and returns the new state of the map and the player after executing them in order. All these actions must be valid (no using objects in invalid spots, attacking thin air, going out of bounds, etc), so if any of them turns out not to be valid, return `None`. **Dying counts as an invalid state**.
The order of the elements of the output tuple is: (`new map state`, `health`, `attack`, `defense`, `sorted bag`)
The syntax of the actions is as follows:
* `F` to move forward.
* `^`, `>`, `v` and `<`to rotate the player.
* `A` to attack the enemy you have in front of you.
* `C`, `K` and `H` to use a coin, a key and a health potion, respectively.
**Technical notes:**
* You **can** mutate the input (and probably should), but it is not necessary.
* There will only be one Demon Lord per map, but every other tile may be repeated two or even more times.
* Only the tiles marked as **[object]** will be stored in your bag (i.e. keys, coins and potions).
* Only valid inputs will be given.
----------------
<h3 style="text-align: center"><i>As always, I hope you have fun with this kata :)</i></h3> | algorithms | def rpg(field, actions):
p = Player(field)
try:
for m in actions:
if m == 'A':
p . attack()
elif m in 'HCK':
p . use(m)
elif m in '<^>v':
p . rotate(m)
p . checkDmgsAndAlive()
if m == 'F':
p . move()
except Exception as e:
return None
return p . state()
class Player:
DIRS = dict(zip('<>^v', ((0, - 1), (0, 1), (- 1, 0), (1, 0))))
def __init__(self, field):
self . h, self . atk, self . d, self . bag, self . xps = 3, 1, 1, [], 0
self . field = field
self . pngs = {}
for x, r in enumerate(self . field):
for y, c in enumerate(r):
if c in self . DIRS:
self . x, self . y, self . c = x, y, c
self . dx, self . dy = self . DIRS[c]
elif c == 'D':
self . pngs[(x, y)] = {'h': 10, 'atk': 3}
elif c == 'E':
self . pngs[(x, y)] = {'h': 1, 'atk': 2}
elif c == 'M':
self . pngs['M'] = {'coins': 3}
def state(self): return self . field, self . h, self . atk, self . d, sorted(
self . bag)
def rotate(self, c):
self . dx, self . dy = self . DIRS[c]
self . c = self . field[self . x][self . y] = c
def move(self):
self . field[self . x][self . y] = ' '
self . x += self . dx
self . y += self . dy
c = self . field[self . x][self . y]
assert c not in '#ED-|M' and self . x >= 0 and self . y >= 0
if c != ' ':
self . takeThis(c)
self . field[self . x][self . y] = self . c
def checkAhead(self, what):
x, y = self . x + self . dx, self . y + self . dy
assert self . field[x][y] in what
return x, y
def takeThis(self, c):
if c not in 'SX':
self . bag . append(c)
if c == 'S':
self . d += 1
elif c == 'X':
self . atk += 1
def use(self, c):
self . bag . remove(c)
if c == 'C':
x, y = self . checkAhead('M')
self . pngs['M']['coins'] -= 1
if not self . pngs['M']['coins']:
self . field[x][y] = ' '
elif c == 'H':
assert self . h < 3
self . h = 3
elif c == 'K':
x, y = self . checkAhead('|-')
self . field[x][y] = ' '
def attack(self):
x, y = nmy = self . checkAhead('ED')
self . pngs[nmy]['h'] -= self . atk
if self . pngs[nmy]['h'] < 1:
del self . pngs[nmy]
self . field[x][y] = ' '
lvlUp, self . xps = divmod(self . xps + 1, 3)
self . atk += lvlUp
def checkDmgsAndAlive(self):
for dx, dy in self . DIRS . values():
nmy = self . x + dx, self . y + dy
if nmy in self . pngs:
self . h -= max(0, self . pngs[nmy]['atk'] - self . d)
assert self . h > 0
| RPG Simulator - Defeat the Demon Lord! [Part 1] | 5e95b6e90663180028f2329d | [
"Games",
"Game Solvers",
"Algorithms"
] | https://www.codewars.com/kata/5e95b6e90663180028f2329d | 4 kyu |
## Knights
In the kingdom of Logres, knights gather around a round table. Each knight is proud of his victories, so he makes scratches on his armor according to the number of defeated opponents. The knight's rank is determined by the number of scratches. Knights are very proud and the one, whose rank is lower, must pay homage to the one, whose rank is higher. If suddenly there is a situation when knights with the same rank sit in a row, then they arrange a tournament between them, according to the results of which one winner is determined. He puts new scratches on his armor (if `k` knights participated in the tournament, the winner will put `k-1` new scratch) and returns to his place at the table. The rest of the tournament participants go away to heal their wounds and bruised ego. If after that a similar situation arises again, a new tournament is held, and so on.
There were `n` knights gathered at the round table, and they prudently arranged so that the ranks of their neighbors were different. But a late Galahad spoiled everything. He sat down on a randomly chosen place, and the merry-go-round of tournaments started again.
The ranks of all `n` knights originally seated at the table are known. Also know the rank of Galahad and the seat he sat on. Write a program to determine the number of knights that will remain at the table after all the tournaments are over.
### Input:
Three parameters will be given as input:
* `ranks` - array with ranks of knights (except Galahad)
* `p` - position in which Galahad sat
* `r` - rank of Galahad
### Examples:
```python
knights([1,2,3,4,5], 0, 1) # 1
knights([1,3,5,7,9], 0, 1) # 5
knights([9,7,5,3,1], 0, 1) # 5
knights([6,4,2,1,2,4,8], 3, 1) # 2
knights([7,5,6,8,9,10,12,10,8], 2, 5) # 4
```
```javascript
knights([1,2,3,4,5], 0, 1) // 1
knights([1,3,5,7,9], 0, 1) // 5
knights([9,7,5,3,1], 0, 1) // 5
knights([6,4,2,1,2,4,8], 3, 1) // 2
knights([7,5,6,8,9,10,12,10,8], 2, 5) // 4
```
#### Short Explanation:
1. After Galahad sits at the table after the 2nd knight, the ranks of knights at the table will be `[7 5 5 6 8 9 10 12 10 8]`.
2. Two knights with rank 5 will hold a tournament, one of them will remain, whose rank will increase to 6 `[7 6 6 8 9 10 12 10 8]`.
3. Two knights of Rank 6 will again leave 1 with Rank 7 `[7 7 8 9 10 12 10 8]`.
4. After the next tournament we get `[8 8 9 10 12 10 8]`.
5. Keeping in mind that the table is round, we see 3 Knights of Rank 8 sitting in a row. One of them will remain with rank 10 `[10 9 10 12 10]`.
7. There will be one more tournament, after which the remaining 4 knights will not have neighbors with the same rank `[11 9 10 12]`
*P.s. The number of ranks in an array can reach up to 300,000* | algorithms | def knights(A, p, r):
i, j = p - 1, p
g, d = r, 1
while d:
d = 0
while j - i <= len(A) and A[i % len(A)] == g:
i -= 1
d += 1
while j - i <= len(A) and A[j % len(A)] == g:
j += 1
d += 1
g += d
return len(A) - g + r + (g != A[i % len(A)] or g != A[j % len(A)])
| Knights | 616ee43a919fae003291d18f | [
"Algorithms",
"Logic",
"Puzzles"
] | https://www.codewars.com/kata/616ee43a919fae003291d18f | 5 kyu |
# Task
Given a binary number, we are about to do some operations on the number. Two types of operations can be here:
* <b>['I', i, j] : Which means invert the bit from i to j (inclusive).</b>
* <b>['Q', i] : Answer whether the i'th bit is 0 or 1.</b>
The MSB (most significant bit) is the first bit (i.e. i = `1`). The binary number can contain leading zeroes.
## Example
```javascript
binarySimulation("0011001100", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '1', '1', '0' ];
binarySimulation("1011110111", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '0', '0', '1' ];
binarySimulation("1011110111", [['I', 1, 10], ['I', 2, 7]]) === [];
binarySimulation("0000000000", [['I', 1, 10], ['Q', 2]]) === ['1'];
```
```python
binary_simulation("0011001100", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '1', '1', '0' ];
binary_simulation("1011110111", [['I', 1, 10], ['I', 2, 7], ['Q', 2], ['Q', 1], ['Q', 7], ['Q', 5]]) === [ '0', '0', '0', '1' ];
binary_simulation("1011110111", [['I', 1, 10], ['I', 2, 7]]) === [];
binary_simulation("0000000000", [['I', 1, 10], ['Q', 2]]) === ['1'];
```
## Note
* All inputs are valid.
* Please optimize your algorithm to avoid time out.
| algorithms | def binary_simulation(s, q):
out, n, s = [], int(s, 2), len(s)
for cmd, * i in q:
if cmd == 'I':
a, b = i
n ^= (1 << b - a + 1) - 1 << s - b
else:
out . append(str(int(0 < 1 << s - i[0] & n)))
return out
| Binary Simulation | 5cb9f138b5c9080019683864 | [
"Performance",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5cb9f138b5c9080019683864 | 5 kyu |
The professional Russian, Dmitri, from the popular youtube channel <a href="https://www.youtube.com/user/FPSRussia">FPSRussia</a> has hired you to help him move his arms cache between locations without detection by the authorities. Your job is to write a Shortest Path First (SPF) algorithm that will provide a route with the shortest possible travel time between waypoints, which will minimize the chances of detection. One exception is that you can't travel through the same waypoint twice. Once you've been seen there is a higher chance of detection if you travel through that waypoint a second time.
Your function shortestPath will take three inputs, a topology/map of the environment, along with a starting point, and an ending point. The topology will be a dictionary with the keys being the different waypoints. The values of each entry will be another dictionary with the keys being the adjacent waypoints, and the values being the time it takes to travel to that waypoint.
Take the following topology as an example:
topology = {'a' : {'b': 10, 'c': 20},
'b' : {'a': 10, 'c': 20},
'c' : {'a': 10, 'b': 20} }
In this example, waypoint 'a' has two adjacent waypoints, 'b' and 'c'. And the time it takes to travel from 'a' to 'b' is 10 minutes, and from 'a' to 'c' is 20 minutes. It's important to note that the time between these waypoints is one way travel time and can be different in opposite directions. This is highlighted in the example above where a->c takes 20 minutes, but c->a takes 10 minutes.
The starting and ending points will passed to your function as single character strings such as 'a' or 'b', which will match a key in your topology.
The return value should be in the form of a list of lists of waypoints that make up the shortest travel time. If there multiple paths that have equal travel time, then you should choose the path with the least number of waypoints. If there are still multiple paths with equal travel time and number of waypoints, then you should return a list of lists with the multiple options. For multiple solutions, the list of paths should be sorted in lexicographic (alphabetical) order. If there is only one shortest path, you should still return a list of that list.
Here are a few examples:
```python
'''
Topology
b--d--g
/ | \
/ | \
a-----e h
\ \ /
\ \ /
c-----f
'''
topology = {'a' : {'b': 10, 'c': 20, 'e':20},
'b' : {'a': 10, 'd': 20},
'c' : {'a': 10, 'f': 20},
'd' : {'b': 10, 'e': 20, 'g': 20},
'e' : {'a': 10, 'd': 20, 'f': 20},
'f' : {'c': 10, 'e': 20, 'h': 20},
'g' : {'d': 10, 'h': 20},
'h' : {'g': 10, 'f': 20},
}
#Two solutions with a time of 40:
shortestPath(topology, 'a', 'f') == [['a', 'c', 'f'], ['a', 'e', 'f']]
#One solution with a time of 20:
shortestPath(topology, 'a', 'e') == [['a', 'e']]
| algorithms | from heapq import *
def shortest_path(topology, start, end):
q, ans = [(0, 1, 1, start)], []
while q[0][- 1][- 1] != end:
time, _, _, path = heappop(q)
for nextPt, dt in topology[path[- 1]]. items():
heappush(q, (time + dt, len(path) + 1, nextPt != end, path + nextPt))
minTime = q[0][0]
while q[0][0] == minTime and q[0][- 1][- 1] == end:
ans . append(heappop(q))
ans = [list(path) for _, _, _, path in ans]
return ans
| SPF Russia | 5709aa85fe2d012f1d00169c | [
"Algorithms"
] | https://www.codewars.com/kata/5709aa85fe2d012f1d00169c | 4 kyu |
<p style='font-size:0.9em'><i>This kata is inspired by <a href="https://en.wikipedia.org/wiki/Space_Invaders" style="color:#9f9;text-decoration:none"><b>Space Invaders</b></a> (Japanese: γΉγγΌγΉγ€γ³γγΌγγΌ), an arcade video game created by Tomohiro Nishikado and released in 1978.</i></p>
<p>Alien invaders are attacking Earth and you've been conscripted to defend.<br>
<span style='color:#8df'>The Bad News:</span> You performed poorly in the manual training. As a result, you're ranked low priority and you're piloting a space jalopy.<br>
<span style='color:#8df'>The Good News:</span> Your coding skill is better than your piloting and you know the movement pattern of the alien spaceships.</p>
<p>You're going to program an algorithm that aids in shooting down the incoming alien wave despite your limitations.</p>
<h2 style='color:#f88'>Input</h2>
<p>The action takes place on an <code>m</code> x <code>n</code> matrix. Your function will receive two arguments:</p>
<ul>
<li>a 2-D array where each subarray represents a row of alien ships. Subarrays consist of integers that represent each alien ship. Zero values (<code>0</code>) are empty spaces.
</li>
<li>your <code>[row,column]</code> coordinates</li>
</ul>
<p>The width (<code>n</code>) of a row is equal to the length of a subarray in the first argument and all rows are of the same length.<br>
Your <code>row</code> coordinate will be the last row of the matrix (<code>m - 1</code>).</p>
<p><span style='color:#f88'><b>Alien Ship Movement Pattern</b></span><br>
<ul>
<li>Each alien ship is given in the form of an integer that represents its movement speed and direction.</li>
<li><b>Alien ships move left or right.</b> A positive integer means an alien moves right, a negative integer means an alien moves left. The absolute value of the integer is the distance the alien moves in <code>1</code> turn.</li>
<li>When an alien reaches an edge, it moves down one position and reverses lateral (left/right) direction.</li>
</ul>
<p><span style='color:#f88'><b>Your Ship's Limitations</b></span><br>
<ul>
<li>Your position is fixed.</li>
<li>Your pulse cannon has a time delay of <code>1</code> turn. After the delay, your cannon blasts the first target in its path.</li>
<li>You can fire up to one shot per turn.</li>
</ul>
</p>
<h2 style='color:#f88'>Output</h2>
<p>Your function should return an array of integers. Each integer represents the turn for each shot fired from your ship's cannon. If it is not possible to destroy all alien ships before they reach the last row, return <code>null</code> or <code>None</code>.</p>
<h2 style='color:#f88'>Test Example</h2>
<div style="background:#262729"><img src="https://i.imgur.com/S4qYQQ0.png" alt="state 0"></div>
<p><span style='color:#9f9'><b>Above:</b></span> Turn 0 (Initial State)<br>
<span style='color:#9f9'><b>Below:</b></span> Turn 1</p>
<div style="background:#262729"><img src="https://i.imgur.com/Iah7dQc.png" alt="state 1"></div>
<p>The images above represent the matrix states at Turn <code>0</code> and Turn <code>1</code> for the test example below. Note the following:</p>
<ul>
<li><b>Multiple alien ships can occupy the same space concurrently.</b> The red alien at <code>[0,2]</code> and the light blue alien at <code>[0,7]</code> at turn <code>0</code> will both end up at position <code>[0,4]</code> at turn <code>1</code>.</li>
<li>The pink alien (<code>1</code>) at <code>[0,9]</code> at turn <code>0</code> is already at the right edge, so it moves one space down and changes direction from right to left.</li>
<li>The yellow alien (<code>6</code>) at <code>[0,6]</code> at turn <code>0</code> ends up at <code>[1,7]</code> at turn <code>1</code>.</li>
<li>The green alien (<code>7</code>) at <code>[0,8]</code> at turn <code>0</code> ends up at <code>[1,4]</code> (white alien) and gets shot down by your cannon at turn <code>1</code>. Therefore, the time of registering your first shot is at turn <code>0</code>.</li>
</ul>
<p>In the test example, there is only one subarray in the first argument, meaning only the top row (row <code>0</code>) of the matrix is occupied at the initial state.</p>
```javascript
const alienWave = [[3,1,2,-2,2,3,6,-3,7,1]];
const position = [6,4];
blastSequence(alienWave,position);// [0, 2, 3, 4, 5, 9, 10, 13, 19, 22]
```
```python
alien_wave = [[3,1,2,-2,2,3,6,-3,7,1]]
position = [6,4]
blast_sequence(alien_wave,position)# [0, 2, 3, 4, 5, 9, 10, 13, 19, 22]
```
```java
int[][] alien_wave = {{3,1,2,-2,2,3,6,-3,7,1}};
int[] position = {6,4};
new SpaceInvaders(alien_wave,position).blastSequence(); # [0, 2, 3, 4, 5, 9, 10, 13, 19, 22]
```
<h3 style='color:#f88'>Other Technical Details</h3>
<ul>
<li>In the event where multiple alien ships occupy the same position and the position is the target of your cannon fire, the fastest alien ship will be destroyed. If two ships are going at the same speed in opposite directions, the ship moving to the right will be destroyed.</li>
<li>All alien ship movement speeds will be less than the width of the matrix.</li>
<li>Alien count upper bound is <code>228</code></li>
<li>Inputs will always be valid</li>
</ul>
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored). | algorithms | def blast_sequence(aliensStart, position):
def moveAliens(aliens, furthest):
lst, shootPath = [], []
for x, y, s in aliens:
y += s
if not (0 <= y < N): # Out of the grid: move down and reverse
x, s = x + 1, - s
y = - y - 1 if y < 0 else 2 * N - y - 1
(shootPath if y == Y else lst). append((x, y, s))
if x > furthest:
furthest = x
return lst, shootPath, furthest
def shootTarget(shootPath):
if shootPath:
# Furthest, fastest, going right is considered the highest
z = max(shootPath, key=lambda a: (a[0], abs(a[2]), a[2]))
shootPath . remove(z) # MUTATION
shots . append(turn) # MUTATION
(X, Y), N = position, len(aliensStart[0])
aliens = [(x, y, s) for x, r in enumerate(aliensStart)
for y, s in enumerate(r) if s]
shots, furthest, turn = [], 0, - 1
while aliens and furthest < X:
turn += 1
# Move all the aliens, splitting them in 2 groups: those facing "my" ship (shootPath) and the others
aliens, shootPath, furthest = moveAliens(aliens, furthest)
# Extract the target in shootPath and pop it if possible (mutation). Mutate 'shots' list at the same time
shootTarget(shootPath)
aliens += shootPath # Put the remaining aliens in the list
return shots if not aliens else None
| Space Invaders Underdog | 59fabc2406d5b638f200004a | [
"Logic",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/59fabc2406d5b638f200004a | 4 kyu |
<p>Spider-Man ("Spidey") needs to get across town for a date with Mary Jane and his web-shooter is low on web fluid. He travels by slinging his web rope to latch onto a building rooftop, allowing him to swing to the opposite end of the latch point.</p>
<p>Write a function that, when given a list of buildings, returns a list of optimal rooftop latch points for minimal web expenditure.</p>
<h2 style='color:#f88'>Input</h2>
<p>Your function will receive an array whose elements are subarrays in the form <code>[h,w]</code> where <code>h</code> and <code>w</code> represent the height and width, respectively, of each building in sequence</p>
<h2 style='color:#f88'>Output</h2>
<p>An array of latch points (integers) to get from <code>0</code> to the end of the last building in the input list</p>
<h2 style='color:#f88'>Technical Details</h2>
<ul>
<li>An optimal latch point is one that yields the greatest horizontal distance gain relative to length of web rope used. Specifically, the highest horizontal distance yield per length unit of web rope used. Give this value rounded down to the nearest integer as a distance from Spidey's origin point (<code>0</code>)</li>
<li>At the start of each swing, Spidey selects a latch point based on his current position.</li>
<li>At the end of each swing, Spidey ends up on the opposite side of the latch point equal to his distance from the latch point before swing.</li>
<li>Spidey's initial altitude is <code>50</code>, and will always be the same at the start and end of each swing. His initial horizontal position is <code>0</code>.</li>
<li>To avoid collision with people/traffic below, Spidey must maintain a minimum altitude of <code>20</code> at all times.</li>
<li>Building height (<code>h</code>) range limits: <code>125 <= h < 250</code></li>
<li>Building width (<code>w</code>) range limits: <code>50 <= w <= 100</code></li>
<li>Inputs will always be valid.</li>
</ul>
<h2 style='color:#f88'>Test Example</h2>
![test example image](https://i.imgur.com/Z2hAWPn.png)
- Spidey's initial position is at `0`, marked by the Spidey icon on the left. His first latch point is marked by the green circle at `76` (horizontal position) on `buildings[0]`.
- At the end of the swing, Spidey's position is at the point marked `B` with a horizontal position of `152`. The green arc represents Spidey's path during swing.
- The orange circle on the 3rd building and the orange arc going from point `B` to point `C` represent the latch point (`258`) and arc path for the next swing.
```javascript
let buildings = [[162,76], [205,96], [244,86], [212,68], [174,57], [180,89], [208,70], [214,82], [181,69], [203,67]];
spideySwings(buildings); //[76,258,457,643,748]
```
```python
buildings = [[162,76], [205,96], [244,86], [212,68], [174,57], [180,89], [208,70], [214,82], [181,69], [203,67]]
spidey_swings(buildings)# [76,258,457,643,748]
```
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored). | algorithms | from math import sqrt, ceil
REST_HEIGHT = 50
MIN_HEIGHT = 20
def optimal_one_building(pos, building, building_start):
h, w = building
theoretical = int(pos + sqrt(MIN_HEIGHT * * 2 - REST_HEIGHT * * 2 + 2 * h * (REST_HEIGHT - MIN_HEIGHT)))
if max(pos, building_start) <= theoretical <= building_start + w:
return theoretical, sqrt((theoretical - pos) * * 2 + (h - REST_HEIGHT) * * 2)
rope_length = sqrt((building_start + w - pos) * * 2 + (h - REST_HEIGHT) * * 2)
if rope_length <= h - MIN_HEIGHT:
return building_start + w, rope_length
def final_latch(pos, buildings, w_start, w_end):
options = {}
for h, w in buildings:
mid = ceil(pos + (w_end - pos) / 2)
if mid > w_start + w:
w_start += w
continue
if mid >= w_start:
rope = sqrt((mid - pos) * * 2 + (h - REST_HEIGHT) * * 2)
if rope > h - MIN_HEIGHT:
w_start += w
continue
options[mid] = (w_end - pos) / rope
else:
rope = sqrt((w_start - pos) * * 2 + (h - REST_HEIGHT) * * 2)
if rope > h - MIN_HEIGHT:
w_start += w
continue
options[w_start] = (w_end - pos) / rope
w_start += w
if options:
return max(options, key=options . get)
def spidey_swings(buildings):
print(buildings)
w_total = sum(w for h, w in buildings)
latchpoints = []
pos = 0
i_building = l_building = 0
while True:
final = final_latch(pos, buildings[i_building:], l_building, w_total)
if final is not None:
return [int(l) for l in latchpoints + [final]]
candidates = {}
building_start = l_building
for h, w in buildings[i_building:]:
if (latchrope := optimal_one_building(pos, (h, w), building_start)) is not None:
latch, rope = latchrope
candidates[latch] = (latch - pos) / rope
building_start += w
latchpoints . append(max(candidates, key=candidates . get))
pos = 2 * latchpoints[- 1] - pos
for h, w in buildings[i_building:]:
if pos < l_building + w:
break
i_building += 1
l_building += w
| Spidey Swings Across Town | 59cda1eda25c8c4ffd000081 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/59cda1eda25c8c4ffd000081 | 4 kyu |
<p>This kata is inspired by <a href="https://en.wikipedia.org/wiki/Tower_defense" style="color:#9f9;text-decoration:none"><b>Tower Defense</b></a> (TD), a subgenre of strategy video games where the goal is to defend a player's territories or possessions by obstructing enemy attackers, usually by placing defensive structures on or along their path of attack.</p>
<!--<p style="color:#fdd">If you enjoyed this kata, check out its little sibling, <a href="blank"><b><i>Plants vs Zombies: Risk Assessment</i></b></a></p>-->
<h2 style='color:#f66'>Objective</h2>
<p>It's the future, and hostile aliens are attacking our planet. We've set up a defense system in the planet's outer perimeter. You're tasked with calculating the severity of a breach.</p>
<h2 style='color:#f66'>Input</h2>
<p>Your function will receive three arguments:</p>
<ul>
<li><b>Battle Area Map:</b> An array/list of strings representing an <code>n</code> x <code>n</code> battle area.<br/>
Each string will consist of any of the following characters:<br/>
<ul>
<li><code>0</code>: entrance point (starting position on alien path)</li>
<li><code>1</code>: alien path</li>
<li><code>" "</code>(space character): not alien path</li>
<li><code>A - Z</code>: turret positions</li>
</ul>
</li>
<li><b>Turret Stats:</b> An object/dict where keys are upper-case characters from the English alphabet (<code>A - Z</code>) and the values are subarrays in the following format:<br/>
<code>[n,m]</code> - where <code>n</code> is the attack range of a turret, and <code>m</code> is its shot frequency per move</li>
<li><b>Alien Wave Stats:</b> An array of integers representing each individual alien in sequence. Each value is an integer representing the health points of each alien; health points are the number of turret shots required to take down a given alien. Integer zero (<code>0</code>) counts as a gap in sequence.</li>
</ul>
<h2 style='color:#f66'>Output</h2>
<p>Return the integer sum of total health points of all aliens that successfully penetrate our defense.</p></br>
<div style="height:330px;width:666px;background:#111;padding:5px">
<img src="https://i.imgur.com/etQx7I8.png" alt="example image" style="position:relative;top:-10%">
</div>
<p><b>The image above shows the game state for the test example (below) at the </b><code>11</code><b>th move.</b></p>
<p>The green square in the north-west quadrant represents the starting position of the alien wave, and the red square in the south-east quadrant represents the last position before breaching the defensive perimeter.<br/>
The blue circles represent the turret positions and are labeled <code>A</code>,<code>B</code>,<code>C</code>, and <code>D</code>.<br/>
The red alien is the first alien in the sequence.</p>
<h2 style='color:#f66'>Technical Details</h2>
<ul>
<li>There is only one path and it maintains a width of <code>1</code>.</li>
<li>Aliens move one square per turn</li>
<li><b>Turrets only fire toward enemies in range.</b><br/>
In the image above, the turret labeled <code>A</code> has the value <code>[3,2]</code>, meaning it can fire at aliens that occupy any position within <code>3</code> squares' length in Euclidean distance (the pink squares). Turret <code>A</code> will fire <code>2</code> times per move.<br/>
The turret labeled <code>D</code> with the value <code>[1,3]</code> can fire at targets that enter the square above it and the square to the right of it (the blue shaded squares) at a rate of <code>3</code> times per move.</li>
<li><b>Turret target priority is toward the enemy within shooting range that is furthest along on the path.</b><br/>
In the image above, turret <code>A</code> will target the red alien because it is the alien furthest along the path that is also within shooting range. This reduces the alien's health from <code>8</code> to <code>6</code>.<br/>
The next alien will die from damage taken from turret <code>B</code>, which reduced its health from <code>4</code> to <code>0</code>.
</li>
<li><b>Turret shooting timing:</b> All turrets with a target will fire their first shot in alphabetical order. The remaining turrets that still have more shots available will fire their next shot in alphabetical order once again. This repeats until there are no more shots to fire. This marks the end of the move.</li>
<li>Matrix size: <code>n</code> x <code>n</code> where <code>20 >= n >= 7</code></li>
<li>Alien list max length: <code>80</code></li>
<li>Full Test Suite: <code>10</code> Fixed Tests, <code>100</code> Random Tests</li>
<li>Input will always be valid.</li>
</ul>
<h2 style='color:#f66'>Test Example</h2>
```javascript
let battlefield = [
'0111111',
' A B1',
' 111111',
' 1 ',
' 1C1111',
' 111 D1',
' 1'
];
let turrets = {A:[3,2],B:[1,4],C:[2,2],D:[1,3]},
let wave = [30,14,27,21,13,0,15,17,0,18,26];
towerDefense(battlefield,turrets,wave); //10
/*
The aliens that survive are the alien at wave[7] with an ending health of 2
and the alien at wave[8] with an ending health of 8.
*/
```
```python
battlefield = [
'0111111',
' A B1',
' 111111',
' 1 ',
' 1C1111',
' 111 D1',
' 1'
]
turrets = {'A':[3,2],'B':[1,4],'C':[2,2],'D':[1,3]}
wave = [30,14,27,21,13,0,15,17,0,18,26]
tower_defense(battlefield,turrets,wave); #10
'''
The aliens that survive are the alien at wave[7] with an ending health of 2
and the alien at wave[8] with an ending health of 8.'''
```
```kotlin
val battlefield = arrayOf(
"0111111",
" A B1",
" 111111",
" 1 ",
" 1C1111",
" 111 D1",
" 1"
)
val turrets = mapOf('A' to Pair(3,2), 'B' to Pair(1,4), 'C' to Pair(2,2), 'D' to (1,3))
val wave = intArrayOf(30,14,27,21,13,0,15,17,0,18,26)
towerDefense(battlefield,turrets,wave) // 10
/*
The aliens that survive are the alien at wave[7] with an ending health of 2
and the alien at wave[8] with an ending health of 8.
*/
```
<p>For another Tower Defense-style challenge, check out <a href='https://www.codewars.com/kata/5a5db0f580eba84589000979' style="color:#aff;text-decoration:none"><b>Plants and Zombies</b></a></p>
<!--<p style="color:#8ff">If the Description is unclear or if you find a bug, feel free to make a comment in the Discourse section.</p>-->
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored). | algorithms | from math import dist
from typing import Dict, List, Tuple
DIRECTIONS = (0, 1, - 1)
def tower_defense(
grid: List[str], turrets: Dict[str, List[int]], aliens: List[int]
) - > int:
def find_start_point() - > Tuple[int, int]:
for index_row, row in enumerate(grid):
if '0' in row:
return index_row, row . find('0')
def find_next_point() - > Tuple[int, int]:
for i in range(3):
for direction in DIRECTIONS:
if (path := roadmap . get(start + direction)) and DIRECTIONS[i] + finish in path:
return start + direction, DIRECTIONS[i] + finish
return 0, 0
def find_targets_turrets() - > Dict[Tuple[Tuple[int, int], ...], int]:
turret_positions = {item: (row, col) for row in range(len(grid))
for col, item in enumerate(grid[row]) if item . isalpha()}
return {tuple(point for point in alien_path
if dist(pos, point) <= turrets[turret][0]): turrets[turret][1]
for turret, pos in turret_positions . items()}
roadmap = {row: [col for col, item in enumerate(grid[row]) if item . isdigit()]
for row in range(len(grid))}
start, finish = find_start_point()
alien_path = []
while any(roadmap[row] for row in roadmap . keys()):
point_index = roadmap[start]. index(finish)
alien_path . append((start, roadmap[start]. pop(point_index)))
start, finish = find_next_point()
alien_killer = AlienKiller(alien_path, find_targets_turrets(), aliens)
alien_survivors_hp = sum(
alien_killer . get_aliens_survivor_health_points())
return alien_survivors_hp
class AlienKiller:
def __init__(
self,
path: List[Tuple[int, int]],
turrets: Dict[Tuple[Tuple[int, int], ...], int],
aliens: List[int]
) - > None:
self . turrets = turrets
self . total_turrets_shots = [shot for shot in turrets . values()]
self . alien_path = path
self . number_movements = len(aliens) + len(path)
self . aliens = [0] * len(path) + aliens[:: - 1]
self . target_list: List[Tuple[int, List[int]], ...] = []
self . alien_survivors: List[int] = []
def get_aliens_survivor_health_points(self) - > List[int]:
for num in range(1, self . number_movements):
target_list: Dict[int, List[int]] = {}
self . alien_survivors . append(self . aliens[- num])
for position, alien in enumerate(self . aliens[- num:][: len(self . alien_path)], 1):
for turret_number, targets in enumerate(self . turrets):
if alien and self . alien_path[position - 1] in targets:
target_list[turret_number] = target_list . get(
turret_number, []) + [- position]
self . target_list = sorted(target_list . items(), key=lambda x: x[0])
self . _open_fire_from_turrets()
return self . alien_survivors
def _open_fire_from_turrets(self) - > None:
alien_positions = [pos for _, pos in self . target_list]
shots = [self . total_turrets_shots[turret_queue]
for turret_queue, _ in self . target_list]
for _ in range(max(shots) if shots else 0):
for i, shot in enumerate(shots):
if shot and (targets := [pos for pos in alien_positions[i]
if self . alien_survivors[pos]]):
self . alien_survivors[min(targets)] -= 1
shots[i] -= 1
| Tower Defense: Risk Analysis | 5a57faad880385f3b60000d0 | [
"Logic",
"Games",
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5a57faad880385f3b60000d0 | 4 kyu |
Your task is to write a **class decorator** named `change_detection` that traces the changes of the attributes of the defined class. When referred on an object, each attribute - defined either on object level or class level - should interpret an additional property called `get_change` which returns one of the following strings:
```
'' - if the attribute isn't defined
'INIT' - if the attribute was just created
'MOD' - if the value of the attribute was changed from its initial value at least once
'DEL' - if the attribute gets deleted on the object
```
We can assume that each attribute has its copy constructor implemented.
# Example
As an example, after the following class definition, the python terminal output should show as follows.
```
@change_detection
class Struct:
x = 42
def __init__(self, y=0):
self.y = y
a = Struct(11)
Struct.x == 42
# Struct.x.get_change - will not be tested
a.x, a.y == 42, 11
a.x.get_change == a.y.get_change == 'INIT'
a.z.get_change == ''
a.y = 11
a.y.get_change == 'INIT'
a.y = 12
a.y.get_change == 'MOD'
a.x = '42'
a.x.get_change == 'MOD'
del a.y
a.y.get_change == 'DEL'
```
Note that the behaviour in case of any other operation on an undefined attribute is up to you: `AttributeError` might be raised or just a `None`, `NONE` or `NO_SUCH` might be returned.
For your convenience, two objects: `NO_SUCH` and `NONE` are predefined, which has copy constructor. Also, the envelope class `Bool` of the nonsubclassable `bool` is predefined in case you might need it...
Good luck! | algorithms | def change_detection(cls):
class attr_cls ():
def __init__(self, value, get_change='INIT'):
self . value = value
self . get_change = get_change
def __getattr__(self, name):
return getattr(self . value, name)
def __repr__(self):
return str(self . value)
def __bool__(self):
return bool(self . value)
def __call__(self):
return self . value()
def __eq__(self, other):
return self . value == other
def __add__(self, other):
return self . value + other
def __sub__(self, other):
return self . value - other
def __mul__(self, other):
return self . value * other
def __truediv__(self, other):
return self . value / other
def __radd__(self, other):
return other + self . value
def __rsub__(self, other):
return other - self . value
def __rmul__(self, other):
return other * self . value
def __rtruediv__(self, other):
return other / self . value
def __getattribute__(self, name):
try:
attr = super(cls, self). __getattribute__(name)
if type(attr) != attr_cls:
new_attr = attr_cls(attr)
super(cls, self). __setattr__(name, new_attr)
return new_attr
return attr
except:
return attr_cls(None, '')
def __setattr__(self, name, value):
target = getattr(self, name, None)
if type(target) != attr_cls or not target . get_change:
super(cls, self). __setattr__(name, attr_cls(value))
elif target . value != value or type(target . value) != type(value):
target . value = value
target . get_change = 'MOD'
def __delattr__(self, name):
target = getattr(self, name)
target . value = None
target . get_change = 'DEL'
setattr(cls, '__setattr__', __setattr__)
setattr(cls, '__getattribute__', __getattribute__)
setattr(cls, '__delattr__', __delattr__)
return cls
| Change detection decorator | 56e02d5f2ebcd50083001300 | [
"Decorator",
"Algorithms",
"Metaprogramming"
] | https://www.codewars.com/kata/56e02d5f2ebcd50083001300 | 2 kyu |
If you haven't already done so, you should do the [5x5](https://www.codewars.com/kata/5x5-nonogram-solver/) and [15x15](https://www.codewars.com/kata/15x15-nonogram-solver/) Nonogram solvers first.
In this kata, you have to solve nonograms from any size up to one with an average side length of 50. The nonograms are not all square. However, they all will be valid and should only have one solution.
I highly recommend not to try and use a brute force solution as some of the grids are very big. Also, you may not be able to solve all the grids by deduction alone so may have to guess one or two squares. :P
You will be given three arguments: The clues, the width, and the height:
```python
# clues is given in the same format as the previous two nonogram katas:
clues = (tuple((column_clues,) for column_clues in column),
tuple((row_clues,) for row_clues in row))
# width is the width of the puzzle (distance from left to right)
width = width_of_puzzle
# height is the height of the puzzle (distance from top to bottom)
height = height_of_puzzle
```
```javascript
// The clues are made up of the horizontal and vertical clues
let horizontalClues = Array.from(`all the clues given from left to right with the uppermost clue given first`),
verticalClues = Array.from(`all the clues given from top to bottom with the leftmost clue given first`);
// clues is given in the same format as the previous two nonogram katas:
var clues = [horizontalClues, verticalClues],
// width is the width of the puzzle (distance from left to right)
width = `width of puzzle`,
// height is the height of the puzzle (distance from top to bottom)
height = `height of puzzle`;
```
and you will have to finish the function:
```python
def solve(clues, width, height):
pass
```
```javascript
function solve(clues, width, height) {
}
```
You should return either a tuple of tuples for Python or an array of array for JS of the solved grid.
For example, the second example test case looks like:
![Img](http://static.nonograms.org/files/nonograms/large/voprositelniy_znak_12_1_1p.png)
Therefore, you would be given the arguments:
```python
clues = (((3,), (4,), (2, 2, 2), (2, 4, 2), (6,), (3,)),
((4,), (6,), (2, 2), (2, 2), (2,), (2,), (2,), (2,), (), (2,), (2,)))
width = 6
height = 11
```
```javascript
clues = [ [[3], [4], [2, 2, 2], [2, 4, 2], [6], [3]],
[[4], [6], [2, 2], [2, 2], [2], [2], [2], [2], [], [2], [2]] ]
width = 6
height = 11
```
Zero will be given as an empty tuple in python, or empty array in JS.
# Test sizes:
You will be given 60 random tests in total. There will be:
1. 35 small tests: 3 < the average of the side lengths <= 25
2. 15 medium tests: 25 < the average of the side lengths <= 35
3. 10 big tests: 40 <= the average of the side lengths <= 50
Good luck :) | algorithms | from itertools import repeat, groupby, count, chain
import random
def solve(* args):
return tuple(map(tuple, Nonogram(* args). solve()))
class Memo:
def __init__(self, func):
self . func = func
self . cache = {}
def __call__(self, * args):
if args in self . cache:
return self . cache[args]
else:
ans = self . func(* args)
self . cache[args] = ans
return ans
class Nonogram:
__slots__ = ['W', 'H', 'no_of_lines', 'col_clues', 'row_clues',
'grid', 'to_linesolve', 'grid_changed', 'solved_lines',
'prev_states']
def __init__(self, clues, width, height):
self . W, self . H = width, height
self . no_of_lines = width + height
self . col_clues, self . row_clues = clues
self . grid = [[- 1 for _ in range(width)] for _ in range(height)]
self . to_linesolve = sorted(list(zip(repeat('C'), count(), self . col_clues))
+ list(zip(repeat('R'), count(),
self . row_clues)),
key=lambda x: sum(x[2]), reverse=True)
self . solved_lines = set() # set of all the solved lines for lookup
self . prev_states = [] # list of states in case it needs to guess and backtrack
def solve(self):
"""Generates the furthest left, and furthest right possible permutation of a row
and takes the intersection of the points that are the same (line-solving).
If no more points can be deduced, then it takes a random guess and repeats.
If the grid becomes invalid, it just backtracks to the last guess."""
line_solve = self . line_solve
while len(self . solved_lines) < self . no_of_lines:
self . grid_changed = False
try:
line_solve()
except InvalidGridError:
# Resets the grid back to the old state.
old_grid, old_guess, guess_pos, old_solved_lines = self . prev_states . pop()
self . grid = [l[:] for l in old_grid]
self . grid[guess_pos[0]][guess_pos[1]] = old_guess ^ 1 # Swaps the guess
self . solved_lines = old_solved_lines . copy()
continue
if not self . grid_changed and len(self . solved_lines) < self . no_of_lines:
# Guesses if no extra blocks/gaps have been deduced
self . guess()
return self . grid
def line_solve(self):
"""This method should line solve all the clues in self.line_solve
using the furthest left, and furthest right to compare which blocks are valid/invalid.
It may miss a small amount though (limitations of alg), but 'should' be fast(ish)"""
solved_lines = self . solved_lines
get_line = self . get_line
linesolve_helper = self . linesolve_helper
change_grid = self . change_grid
for vert, pos, clue in self . to_linesolve:
if (vert, pos, clue) in solved_lines:
# If the line is already solved
continue
line = get_line(vert, pos) # The current line so far
solved = linesolve_helper(line, clue)
if solved is True:
# The line must be solved
solved_lines . add((vert, pos, clue))
elif solved:
# Changes the grid if the line changed
change_grid(solved, vert, pos)
self . grid_changed = True
def guess(self):
"""Guesses a random choice if nothing can be deduced from linesolving"""
guess = random . choice((0, 1))
target = self . find_guess_target()
# Incase the guess is wrong and needs to backtrack
self . prev_states . append(([l[:] for l in self . grid],
guess, target,
self . solved_lines . copy()))
self . grid[target[0]][target[1]] = guess
def find_guess_target(self):
"""Finds the first unkown square sorted by the length of the sum of the clue,
and therefore should be more likely to lead to a guess with more impact"""
for vert, pos, clue in self . to_linesolve:
if (vert, pos, clue) not in self . solved_lines:
if vert == 'R':
for i, b in enumerate(self . grid[pos]):
if b == - 1:
return (pos, i)
elif vert == 'C':
for i, r in enumerate(self . grid):
if r[pos] == - 1:
return i, pos
def get_line(self, vert, pos):
"""Gets the specified line"""
if vert == 'R':
return tuple(self . grid[pos])
elif vert == 'C':
return tuple(row[pos] for row in self . grid)
def change_grid(self, line, vert, pos):
"""Changes the line in the grid"""
if vert == 'R':
self . grid[pos] = list(line)
elif vert == 'C':
for i, val in enumerate(line):
self . grid[i][pos] = val
@ staticmethod
@ Memo
def linesolve_helper(line, clue):
"""This method first calculates the leftmost and
rightmost possible permutations of the line.
Then it find the intersection where there is a overlap of the same colour."""
length = len(line)
leftmost = Nonogram . get_leftmost(clue, length, line)
rightmost = Nonogram . get_leftmost(
clue[:: - 1], length, line[:: - 1])[:: - 1]
solved = Nonogram . find_intersection(leftmost, rightmost, line, length)
return solved if solved != line else not - 1 in line
@ staticmethod
@ Memo
def get_leftmost(clue, length, filled_line):
"""This method should get the leftmost valid arrangement of all the clues."""
# List of all blocks in order of clues given.
# block is [start_pos, end_pos, length]
blocks = tuple([0, c, c] for c in clue)
for i, block in enumerate(blocks):
# Moves the blocks up until they are all in valid positions,
# but not necessarily covering all the blocked spots.
if i != 0:
# Teleports the block to the end of the previous block
diff = blocks[i - 1][1] - block[0] + 1
block[0] += diff
block[1] += diff
while 0 in filled_line[block[0]: block[1]]:
# If the block is in an invalid position, then it moves it along 1 square
block[0] += 1
block[1] += 1
while True:
# Moves the blocks until all the blocked spots are covered.
line = [0] * length
# Fills in the line if a block is there.
for block in blocks:
line[block[0]: block[1]] = [1] * block[2]
changed = False
for i, c in enumerate(filled_line):
# If a block should be covering a filled square but isn't
if c == 1 and line[i] == 0:
changed = True
for block in reversed(blocks):
# Finds the first block to the left of the square,
# and teleports the right end of the block to the square
if block[1] <= i:
diff = i - block[1] + 1
block[0] += diff
block[1] += diff
break
else:
# If no block was found, then the grid must be invalid.
raise InvalidGridError('Invalid grid')
if not changed:
break
for i, block in enumerate(blocks):
# Moves the blocks up until they are not covering any zeros,
# but not necessarily covering all the blocked spots,
while 0 in filled_line[block[0]: block[1]]:
# If the block is in an invalid spot
block[0] += 1
block[1] += 1
if i != 0:
# If any block is in an invalid position compared to the previous block
if block[0] <= blocks[i - 1][1]:
# Teleports the block to 1 square past the end of the previous block
diff = blocks[i - 1][1] - block[0] + 1
block[0] += diff
block[1] += diff
return tuple(line)
@ staticmethod
def find_intersection(left, right, line, length):
"""Groups the same blocks together then takes the intersection."""
leftmost = list(
chain . from_iterable([i] * len(list(g[1]))
for i, g in enumerate(groupby((0,) + left))))[1:]
rightmost = list(
chain . from_iterable([i] * len(list(g[1]))
for i, g in enumerate(groupby((0,) + right))))[1:]
solved = tuple(line[i] if line[i] != - 1 else - 1 if leftmost[i] != rightmost[i]
else leftmost[i] % 2 for i in range(length))
return solved
class InvalidGridError (Exception):
"""Custom Exception for an invalid grid."""
| Multisize Nonogram Solver | 5a5519858803853691000069 | [
"Algorithms",
"Logic",
"Games",
"Game Solvers"
] | https://www.codewars.com/kata/5a5519858803853691000069 | 1 kyu |
# Task
Given a string `s` of lowercase letters ('a' - 'z'), get the maximum distance between two same letters, and return this distance along with the letter that formed it.
If there is more than one letter with the same maximum distance, return the one that appears in `s` first.
# Input/Output
- `[input]` string `s`
A string of lowercase Latin letters, where at least one letter appears twice.
- `[output]` a string
The letter that formed the maximum distance and the distance itself.
# Example
For `s = "fffffahhhhhhaaahhhhbhhahhhhabxx"`, the output should be `"a23"`.
The maximum distance is formed by the character 'a' from index `5` to index `27` (0-based). Therefore, the answer is `"a23"`. | reference | def dist_same_letter(st):
dist_dict = {}
for k, x in enumerate(st):
dist_dict[x] = dist_dict . get(x, []) + [k]
lt = max(dist_dict, key=lambda k: dist_dict[k][- 1] - dist_dict[k][0])
return f' { lt }{ dist_dict [ lt ][ - 1 ] - dist_dict [ lt ][ 0 ] + 1 } '
| Simple Fun #221: Furthest Distance Of Same Letter | 5902bc48378a926538000044 | [
"Fundamentals"
] | https://www.codewars.com/kata/5902bc48378a926538000044 | 6 kyu |
_This kata is a harder version of [A Bubbly Programming Language](https://www.codewars.com/kata/5f7a715f6c1f810017c3eb07). If you haven't done that, I would suggest doing it first._
You are going to make yet another interpreter similar to [A Bubbly Programming Language](https://www.codewars.com/kata/5f7a715f6c1f810017c3eb07), but with completely different syntax.
Your goal is to create an interpreter for a programming language (bubbly language) with the following tokens:
~~~if:python,
- `start`: marks the start of a program
- `return_` (`return_ <value>`): marks the end of a program, and returns the given `<value>`
- `let` (`let <var_name> <value>`): sets the variable `<var_name>` to the given `<value>`
- `add` (`add <value> <value>`) returns the sum of the two `<value>`
- `sub` (`sub <value> <value>`) returns the result of the first `<value>` minus the second `<value>`
- `mul` (`mul <value> <value>`) returns the product of the two `<value>`
- `div` (`div <value> <value>`) returns the result of the first `<value>` divided by the second `<value>` (integer division)
~~~
~~~if:javascript,
- `start`: marks the start of a program
- `return_` (`return_ <value>`): marks the end of a program, and returns the given `<value>`
- `let_` (`let_ <var_name> <value>`): sets the variable `<var_name>` to the given `<value>`
- `add` (`add <value> <value>`) returns the sum of the two `<value>`
- `sub` (`sub <value> <value>`) returns the result of the first `<value>` minus the second `<value>`
- `mul` (`mul <value> <value>`) returns the product of the two `<value>`
- `div` (`div <value> <value>`) returns the result of the first `<value>` divided by the second `<value>` (integer division )
~~~
Each `<value>` can either be an integer (immediate value), a string (value of the variable), or an operator (`add`, `sub`, etc) (return value of the operator).
An example code in the bubbly language (but without the bubbles) looks like:
```python
start
let 'my_var' add 5 8
let 'banana' mul 'my_var' 2
return_ 'banana'
```
```javascript
start
let_ 'my_var' add 5 8
let_ 'banana' mul 'my_var' 2
return_ 'banana'
```
and is equivalent to this pseudo code:
```
let my_var = 5 + 8
let banana = my_var * 2
return banana
```
and should return `26`.
Just like the easier counterpart of this kata, each token must be engulfed by a bubble (parenthesis)!
So the above code should look like:
```python
(start)(let)('my_var')(add)(5)(8)(let)('banana')(mul)('my_var')(2)(return_)('banana')
```
```javascript
(start)(let_)('my_var')(add)(5)(8)(let_)('banana')(mul)('my_var')(2)(return_)('banana')
```
and returns `26`.
~~~if:python,
Your goal is to create appropiate definitions for `start`, `let`, `return_`, `add`, `sub`, `mul`, `div` so that the bubbly language is valid Python syntax.
~~~
~~~if:javascript,
Your goal is to create appropiate definitions for `start`, `let_`, `return_`, `add`, `sub`, `mul`, `div` so that the bubbly language is valid JavaScript syntax.
~~~
More examples:
```python
>>> (start)(let)('x')(20)(return_)(sub)(10)('x')
-10
>>> (start)(return_)(mul)(10)(15)
150
```
```javascript
>>> (start)(let_)('x')(20)(return_)(sub)(10)('x')
-10
>>> (start)(return_)(mul)(10)(15)
150
```
## Extra Requirements
~~~if:python,
___Custom classes are not allowed in the solution___, as Python's \_\_call\_\_ overloading makes this problem too trivial. Your solution must use functions and lambdas to achieve this instead (the `class` and `type` keywords are banned! _Muhahahahahaha!_).
~~~
~~~if:javascript,
_**`Proxy`s are not allowed as solutions**_, as `call` overloading makes this problem too trivial. Your solution must use functions to achieve this instead ( `start`, `let_`, `return_`, `add`, `sub`, `mul` and `div` will be tested to be actual functions ).
~~~
___In addition, your interpreter should allow nested operators___. Since each operator takes in exactly `2` parameters, it is possible to deduce the hierarchy of the nested structure.
This:
```
add add 5 add 3 2 5
```
has this structure:
```
add(add(5, add(3, 2)), 5)
```
And therefore this should be valid syntax:
```python
>>> (start)(return_)(add)(add)(5)(add)(3)(2)(5)
15
```
__Lastly, there will be partial code__.
```python
>>> f = (start)(let)('a')(20)(return_)(add)('a')
>>> (f)(10)
30
>>> (f)(5)
25
```
## Notes
- There will be no indication of line-breaks (or end of statement) in bubbly language. You will need to deduce that from the tokens yourself.
- You may assume that all inputs are valid.
~~~if:python,
- `eval` and `exec` are also not allowed.
~~~
~~~if:javascript,
- Division is _integer division._ Truncate results, instead of rounding up or down, and assume full JS safe integer range! so `x | 0` won't work; you'll have to use `Math.trunc(x)`.
~~~ | games | def get(x): return x if callable(x) else lambda s, c: c(
s, s[x] if isinstance(x, str) else x)
def start(x): return x({}, None)
def return_(s, c): return lambda x: get(x)(s, lambda _s, x: x)
def let(s, c): return lambda x: lambda y: get(y)(s, lambda s, y: lambda z: z({* * s, x: y}, None))
def add(s, c): return lambda x: get(x)(s, lambda s,
x: lambda y: get(y)(s, lambda s, y: c(s, x + y)))
def sub(s, c): return lambda x: get(x)(s, lambda s,
x: lambda y: get(y)(s, lambda s, y: c(s, x - y)))
def mul(s, c): return lambda x: get(x)(s, lambda s,
x: lambda y: get(y)(s, lambda s, y: c(s, x * y)))
def div(s, c): return lambda x: get(x)(s, lambda s, x: lambda y: get(y)(s, lambda s, y: c(s, x / / y)))
| The Bubbly Interpreter | 5fad08d083d5600032d9edd7 | [
"Functional Programming",
"Puzzles"
] | https://www.codewars.com/kata/5fad08d083d5600032d9edd7 | 4 kyu |
<div style="width:504px;height:262px;background:#ddd;">
<img src="https://i.imgur.com/XbW4CRw.jpg" alt="Super Puzzle Fighter II Turbo screenshot">
</div>
<p>This kata is inspired by the arcade puzzle game <a href="https://en.wikipedia.org/wiki/Super_Puzzle_Fighter_II_Turbo" style="color:#9f9;text-decoration:none"><b>Super Puzzle Fighter II Turbo</b></a> (seen above).</p>
<p>In the game <i>Super Puzzle Fighter II Turbo</i>, the player controls pairs of blocks (referred to as "Gems") that drop into a pit-like playfield.</p>
<p>In this kata, your objective is to write a function that, given a sequence of Gem pairs and movement instructions, will return the ending game state.</p>
<h2 style='color:#f66'>Game Mechanics</h2>
<div style="width:402px;height:402px;background:#000;">
<img src="https://i.imgur.com/iKwTYr3.png" alt="gems1">
</div>
<ul>
<li>The playfield is a matrix with <code>12</code> rows and <code>6</code> columns; it begins empty.</li>
<li>Gems come in four different colors β red, blue, green, and yellow.</li>
<li>Similar in style to other <a href="https://en.wikipedia.org/wiki/Tile-matching_video_game">tile-matching video games</a>, a pair of adjacent Gems will descend into the playfield. This pair can be moved left and right, and can be rotated clockwise and counter-clockwise. Once it lands onto an obstacle, the process repeats.<br/>
If the pair lands on an obstacle, but one of the Gems has empty space below it, the pair will disjoint and the unsupported Gem will continue to descend until it lands onto an obstacle.<br/>
In the image above (left), the green-blue Gem pair inside the white rectangular outline will disjoint, with the green Gem merging with the green Power Gem and the blue Gem landing on the yellow Gem, if allowed to drop straight down as is.
</li>
<li><strong style='color:#95c4ffff'>Power Gems:</strong> Adjacent clusters of same-colored Gems in rectangular shapes, that are <code>2 x 2</code> or greater in width and height, will merge into one larger solid Gem, known as a <b>Power Gem</b>. In the image above (left), the larger blue Gem located at the bottom left is a <code>4 x 4</code> Power Gem. The green Gem just above it is a <code>2 x 3</code> Power Gem. In the image to the right, the green Gem that falls merges with the green Power Gem, transforming it into a <code>2 x 4</code> Power Gem.</li>
<li>Each Gem pair descends from the <b>Drop Alley</b>, which is the top of the fourth column from the left, as shown above with the Gem pair inside the white dashed rectangle.</li>
<li><strong style='color:#95c4ffff'>Crash Gems</strong> are special Gems that, upon contact with a same-colored Gem, will destroy all connected Gems of the same color, including other Crash Gems of the same color. In the process, the Crash Gem will self-destruct.<br/>
In the image above (left), a yellow Crash Gem (the yellow circle) is part of a descending Gem pair. If left to fall straight down as is, it will destroy all the connected yellow Gems, resulting in the image to the right. The blue Crash Gem remains until a blue Gem comes in contact with it.</li>
<li><strong style='color:#95c4ffff'>Rainbow Gems</strong> are a rare type of special Gem that destroy all Gems that match the color of the Gem it lands on, while self-destructing in the process. If it lands on the floor of the playfield, no other Gems will be destroyed.</li>
<li>When rotating a Gem pair, the 2nd Gem will rotate around the 1st Gem. In the image above (left), the yellow Crash Gem will rotate around the red Gem. Note that a rotation may cause a shift in lateral position if a Gem pair is touching the left or right wall (to keep the Gems within the boundaries of the playfield).</li>
<li>All movements for a Gem pair occur above the playfield before being dropped.</li>
<li>There is only one descending Gem pair in play at any given time.<br/>
In the image above (left), the red-yellow Gem pair (inside the dashed-rectangle) would appear <b>after</b> the green-blue Gem pair (inside the solid rectangle) has already settled.</li>
</ul>
<h3 style='color:#f66'>Power Gem Formation Priority</h3>
<div style="width:402px;height:192px;background:#000">
<img src="https://i.imgur.com/AlihfOm.png" alt="gems4"></div>
<div style="width:402px;height:140px;background:#000">
<img src="https://i.imgur.com/A4rQKjU.png" alt="gems4a"></div>
<p><strong>When a cluster of same-colored individual gems are set to form a Power Gem, but there is more than one possible configuration, priority goes to the potential Power Gem that is higher in elevation.</strong><br/>
In the first image above, after the green gems shatter, one of two possible Power Gems (that share resources) can be formed: a <code>2 x 2</code> block as shown in the image to the right, or a <code>2 x 2</code> block resting on the playfield floor. The Power Gem in the image to the right is the end result because it is higher in elevation.<br/>
In the second image above, the individual red gems fall after the green gems (left image) have been cleared (middle image). The resulting Power Gem is shown on the right side, where the <code>2 x 3</code> forms due to its higher elevation.</p>
<div style="width:402px;height:140px;background:#000">
<img src="https://i.imgur.com/eAAoGlg.png" alt="gems4b"></div>
<p><strong>If two possible Power Gems with the same elevation can be formed, priority goes to the Power Gem that expands horizontally</strong><br/>
Above, a Rainbow Gem will land on the green gem (left), thereby destroying all green gems and allowing the individual red gems to fall (middle). Two possible Power Gems can form as a result, both having the same elevation. In this case, the result is the Power Gem on the right (as opposed to a <code>2 x 3</code> "vertical" Power Gem that occupies the 4th and 5th columns).</p>
<div style="width:402px;height:192px;background:#000">
<img src="https://i.imgur.com/selVttM.png" alt="gems3">
</div>
<p><strong>When a cluster of unmerged same-colored Gems drops and results in a merge, the individual Gems will combine before combining with Power Gems.</strong><br/>
In the image above (left), the green Crash Gem is about to eliminate the group of green Gems, allowing the 3 red Gems and 1 blue Gem to drop. The 3 red Gems will join the other 3 red Gems below, and form a <code>2 x 3</code> Power Gem before merging with the other <code>2 x 3</code> red Power Gem to its right, to finally become a <code>4 x 3</code> Power Gem. The result is the image to the right.</p>
<div style="width:402px;height:162px;background:#000">
<img src="https://i.imgur.com/fx1v67s.png" alt="gems2">
</div>
<p><strong>In the case where an existing Power Gem can expand by increasing vertically or horizontally, priority goes to horizontal growth.</strong><br/>
In the image above (left), a green Crash Gem is about to eliminate a cluster of green Gems, allowing the Gems above to drop and land on the remaining Gems below.<br/>
Since priority goes to horizontal growth, the <code>2 x 2</code> red Power Gem will become a <code>3 x 2</code> Power Gem instead of a <code>2 x 3</code> Power Gem. The result is shown on the right.</p>
<h3 style='color:#f66'>How Moves Work:</h3>
<ol style="padding-left:10px">
<li>At the start of a move, a Gem pair appears above the playfield.</li>
<li>The pair falls, and each Gem in the pair land on another Gem or the playfield floor.</li>
<li>All effects (eg. Power Gem formation, gem shattering due to Crash Gems or Rainbow Gems) initiated by any Gems will occur simultaneously.</li>
<li>If any Gems are cleared (by Crash Gems or Rainbow Gems) in the process leaving some Gems suspended in air, all suspended Gems fall and land together.</li>
<li>While step 4 makes an effect, repeat steps 3 and 4</li>
</ol>
<!-- <p>NOTE: In the case where the effects of both a Rainbow gem and a Crash gem occur at the same time, the effects of the Rainbow gem occur before the Crash gem</p> -->
<p>Below, the green Gem will combine with other adjacent ones to form a Power Gem, and at the same time the blue Crash Gem will shatter along with the two blue Gems below. The result is the middle frame, rather than the last frame.</p>
<div style="width:404px;height:252px;background:#000">
<img src="https://i.imgur.com/OLKTmLc.png" alt="gems5">
</div>
<h2 style='color:#f66'>Input</h2>
<p>Your function will receive a 2-D array/list. Each subarray has a length of <code>2</code> and consists of:</p>
<ul>
<li>a 2-character string representing a Gem pair</li>
<li>a string of instructions for the Gem pair</li>
</ul>
<p>Each Gem is represented by the first letter of its color in uppercase β <code>R</code>, <code>B</code>, <code>G</code>, or <code>Y</code>.<br/>
Crash Gems are represented by the first letter of its color in lowercase.<br/>
A Rainbow Gem is represented as <code>0</code>.
</p>
<p>Movement Instructions are as follows:</p>
<ul>
<li><code>L</code>: move left</li>
<li><code>R</code>: move right</li>
<li><code>A</code>: rotate counter-clockwise</li>
<li><code>B</code>: rotate clockwise</li>
</ul>
<h2 style='color:#f66'>Output</h2>
<p>Your function will return the ending game state in the form of a string. The string should consist of all <code>12</code> rows joined by newline characters.<br/>
If at any point in the game a stack of Gems goes above the top row, terminate the process and return the game state before the last move. This applies to Crash Gems and Rainbow Gems as well; their position is taken into account before their effect.
</p>
<h2 style='color:#f66'>Test Example</h2>
```javascript
let instructions = [
['BR','LLL'],
['BY','LL'],
['BG','ALL'],
['BY','BRR'],
['RR','AR'],
['GY','A'],
['BB','AALLL'],
['GR','A'],
['RY','LL'],
['GG','L'],
['GY','BB'],
['bR','ALLL'],
['gy','AAL']
];
let gameState = [
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' R ',
' R YR',
'RR RB'
].join('\n');
puzzleFighter(instructions) === gameState; //true
/* STEP-BY-STEP MOVES SEQUENCE
(GAME STATE at end of each of the first 5 moves)
MOVE 1 MOVE 2 MOVE 3 MOVE 4 MOVE 5
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β B β β B β β B β
βB β βBB β βBB β βBB β βBB RRβ
βR β βRY β βRYG β βRYG YBβ βRYG YBβ
*/
```
```python
instructions = [
['BR','LLL'],
['BY','LL'],
['BG','ALL'],
['BY','BRR'],
['RR','AR'],
['GY','A'],
['BB','AALLL'],
['GR','A'],
['RY','LL'],
['GG','L'],
['GY','BB'],
['bR','ALLL'],
['gy','AAL']
]
game_state = '\n'.join([
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' R ',
' R YR',
'RR RB'
])
puzzle_fighter(instructions) == game_state #True
''' STEP-BY-STEP MOVES SEQUENCE
(GAME STATE at end of each of the first 5 moves)
MOVE 1 MOVE 2 MOVE 3 MOVE 4 MOVE 5
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β B β β B β β B β
βB β βBB β βBB β βBB β βBB RRβ
βR β βRY β βRYG β βRYG YBβ βRYG YBβ
'''
```
```ruby
instructions = [
['BR','LLL'],
['BY','LL'],
['BG','ALL'],
['BY','BRR'],
['RR','AR'],
['GY','A'],
['BB','AALLL'],
['GR','A'],
['RY','LL'],
['GG','L'],
['GY','BB'],
['bR','ALLL'],
['gy','AAL']
]
game_state = [
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' R ',
' R YR',
'RR RB'
].join("\n")
puzzle_fighter(instructions) == game_state # true
''' STEP-BY-STEP MOVES SEQUENCE
(GAME STATE at end of each of the first 5 moves)
MOVE 1 MOVE 2 MOVE 3 MOVE 4 MOVE 5
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β B β β B β β B β
βB β βBB β βBB β βBB β βBB RRβ
βR β βRY β βRYG β βRYG YBβ βRYG YBβ
'''
```
```java
String[][] instructions = {
{'BR','LLL'},
{'BY','LL'},
{'BG','ALL'},
{'BY','BRR'},
{'RR','AR'},
{'GY','A'},
{'BB','AALLL'},
{'GR','A'},
{'RY','LL'},
{'GG','L'},
{'GY','BB'},
{'bR','ALLL'},
{'gy','AAL'}
};
String[] gameState = {
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' R ',
' R YR',
'RR RB'
};
PuzzleFighter.play(instructions)
.equals( String.join("\n", gameState) ); // -> true
/* STEP-BY-STEP MOVES SEQUENCE
(GAME STATE at end of each of the first 5 moves)
MOVE 1 MOVE 2 MOVE 3 MOVE 4 MOVE 5
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β β β β β β
β β β β β B β β B β β B β
βB β βBB β βBB β βBB β βBB RRβ
βR β βRY β βRYG β βRYG YBβ βRYG YBβ
*/
```
<h2 style='color:#f66'>Technical Details</h2>
- Input will always be valid.
- Full Test Suite: `10` fixed tests and `200` random tests
- The maximum number of moves in any given test is `100`
- Use Python 3+ for the Python translation
- For JavaScript, most built-in prototypes are frozen, except `Array` and `Function`
<p>Special thanks goes out to <a href='https://www.codewars.com/users/Blind4Basics' style='color:#9f9;text-decoration:none' target='_blank'>@Blind4Basics</a> for his contributions to this kata</p>
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored). | algorithms | from collections import defaultdict
from itertools import chain, count, cycle
from operator import itemgetter
from heapq import *
def puzzle_fighter(arrMoves):
def getStartPoses(moves, c1, c2):
x,y,iR = start
for m in moves:
y += m in 'RL' and (-1)**(m=='L')
iR = (iR + (m in 'AB' and (-1)**(m=='A'))) % 4
dy = ROTATIONS[iR][1]
if y>=lY or y+dy>=lY: y = min(lY-1,lY-1-dy) # move it back into the board (out on right side)
elif y<0 or y+dy<0: y = max(0,-dy) # move it back into the board (out on left side)
dx,dy = ROTATIONS[iR]
x += dx<0 # move it in the board (too high)
return (x,y,c1), (x+dx,y+dy,c2)
def moveGem(x0,y0, x,y):
c,_,_,h,w,s = g = board[x0][y0]
g[X],g[Y] = x,y
dctSet = gemsByColors[c]
dctSet.discard((x0,y0))
dctSet.add((x,y))
for dx in reversed(range(h)):
for dy in reversed(range(w)):
board[x0+dx][y0+dy] = None # erase THEN restore/move
board[x+dx][y+dy] = g
def couldFallFromAbove(x,y,w): # Extract only the position of the root of the gems above (x,y)
if not x: return set()
else: x -= 1
return { tuple(board[x][yy][X:Y+1]) for yy in range(y,y+w) if board[x][yy] }
def drop(posToDrop):
movedGems = set() # Archive all the moved gems: only those ones are candidates to create power gems (and explosions, but taht's not needed here)
toDrop = [(-x,y) for x,y in posToDrop] # "max heap", to drop all gems from bottom to top of the board
heapify(toDrop)
while toDrop:
x,y = heappop(toDrop)
x *= -1
if board[x][y] is None: continue
c,x0,y0,h,w,_ = board[x][y]
moved = 0
while x+h<lX and not any(board[x+h][yy] for yy in range(y,y+w)):
x += 1; moved = 1
if moved or x==x0:
moveGem(x0,y0, x,y)
movedGems.add((x,y))
for x,y in couldFallFromAbove(x0,y0,w):
heappush(toDrop, (-x,y))
return movedGems
def explode(movedGems):
colorsToExplode = {'0'} | { f(board[x+1][y][C]) for x,y in gemsByColors['0'] if x<lX-1
for f in (str.lower,str.upper) }
posToExplode = { pos for c in colorsToExplode for pos in gemsByColors[c] } # from rainbow gems
posToExplode |= set(chain.from_iterable(
flood(x,y,c) for c in 'rgby' for x,y in gemsByColors[c] )) # from crash gems
toDropNext = set()
for x,y in posToExplode:
c,_,_,h,w,_ = board[x][y]
toDropNext |= couldFallFromAbove(x,y,w)
gemsByColors[c].discard( (x,y) )
for xx in range(x,x+h):
for yy in range(y,y+w): board[xx][yy] = None
movedGems -= posToExplode # remove exploded gems to "save" some computations later
toDropNext -= posToExplode
return movedGems, toDropNext
def flood(x,y, what): # flood the area whatever the sizes of the encountered gems (single/powa)
what += what.swapcase() # to flood gems and related crash gems indifferently
bag, seen = {(x,y)}, {(x,y)}
while bag:
bag = { (a,b) for a,b in ((x+dx,y+dy) for x,y in bag for dx,dy in ROTATIONS)
if 0<=a<lX and 0<=b<lY and board[a][b] is not None
and board[a][b][C] in what and (a,b) not in seen
and (seen.add((a,b)) or 1) } # update seen on the fly
seen = { tuple(board[a][b][X:Y+1]) for a,b in seen }
return seen if len(seen)>1 else set() # Don't return crash gems only (they do not explode / this doesn't affect the behavior of power gems creations if not returned!)
def makePowa(movedGems, toDropNext):
gemAreasByCols = defaultdict(set)
for x,y in movedGems:
c,_,_,h,w,_ = board[x][y]
gemAreasByCols[c] |= flood(x,y,c)
q = list(gemAreasByCols.items())
while q:
c,areas = q.pop()
freshPows,removedPows = iGotThePowa(areas, toDropNext)
gemsByColors[c] -= removedPows
if freshPows: q.insert(0,(c,freshPows)) # brand new powaGems could merge later with larger ones
return toDropNext # WARNING: toDropNext is mutated from "iGotThePowa()"
def iGotThePowa(areas, toDropNext): # ... XD https://www.youtube.com/watch?v=_BRv9wGf5pk#t=45
ones = [ board[x][y] for x,y in areas if board[x][y][S]==1 ]
powaG = [ board[x][y] for x,y in areas if board[x][y][S]!=1 ]
fresh, removed = set(), set()
for i,grp in enumerate((ones,powaG)):
grp.sort()
isSingle = not i
for g in grp:
c,x,y,h,w,s = g
if g is not board[x][y] or x==lX-1 or y==lY-1: continue
expanded = expand(DIRS_SINGLE if isSingle else DIRS_POWA, isSingle, c,x,y,h,w,s)
if expanded:
x,y,h,w,s = g[1:] = expanded
if isSingle: powaG.append(g)
fresh.add((x,y))
toRemove = { (xx,yy) for xx in range(x,x+h) for yy in range(y,y+w)
if board[xx].__setitem__(yy,g) or 1 } # (update the board at the same time... x) )
toRemove.remove((x,y))
removed |= toRemove
if toDropNext & toRemove: # previous candidates to drop, when merged in a power gem,...
toDropNext.add((x,y)) # ...means the power gem could need to drop too
toDropNext -= toRemove
return fresh,removed
def expand(dirs, isSingle, c,x,y,h,w,s):
data = start = x,y,h,w
if isSingle: # enforce/check the minimum 2x2 power gem for singles
triad = [board[x+dx][y+dy] for dx,dy in ((0,1),(1,0),(1,1))] # (no need to check x and y on border: already excluded before)
if None in triad or not all(g[C]==c and g[S]==1 for g in triad): return None
data = x,y,2,2
for dx,dy in dirs:
x,y,h,w = data # restore data of the last valid expansion (see goodAlignment)
for _ in count(0):
rngX = tuple(range(x,x+h)) if not dx else [x+dx + (h-1 if dx==1 else 0)]
rngY = tuple(range(y,y+w)) if not dy else [y+dy + (w-1 if dy==1 else 0)]
collect = collectNextLine(rngX,rngY, dx,dy,isSingle, c,x,y,h,w,s)
if not collect: break
if dx: x,h = (x, h+1) if dx==1 else (x-1,h+1) # update x,y,h,w according to the current expansion
if dy: y,w = (y, w+1) if dy==1 else (y-1,w+1)
if isSingle or goodAlignment(collect, dx,dy, x,y,h,w): # Do not update data if there are some jagged power gems in there
data = x,y,h,w # but keep the expansion going (in case its good further...)
if start!=data:
x,y,h,w = data
return (x,y,h,w,h*w)
def collectNextLine(rngX,rngY, dx,dy,isSingle, c,x,y,h,w,s):
collect = []
for a in rngX:
for b in rngY:
if 0<=a<lX and 0<=b<lY:
g = board[a][b]
if (g is None or g[C]!=c or isSingle and g[S]>1
or dx and not (y<=g[Y]<y+w and y<g[Y]+g[W]<=y+w)
or dy and not (x<=g[X]<x+h and x<g[X]+g[H]<=x+h)):
return []
collect.append(g)
return collect
def goodAlignment(collect, dx,dy, x,y,h,w):
return ( all(g[Y] ==y for g in collect) if dy==-1 else # may happen that a combination of powa holds a "jagged" front
all(g[Y]+g[W]==y+w for g in collect) if dy== 1 else # (in the direction of expansion) => invalid, to update data
all(g[X] ==x for g in collect) if dx==-1 else
all(g[X]+g[H]==x+h for g in collect) )
#------------------------------------------------------------------
ROTATIONS = ((1,0), (0,-1), (-1,0), (0,1)) # clockwise
DIRS_POWA = ((0,-1), (0,1), (1,0), (-1,0)) # horizontal first
DIRS_SINGLE = ((0,1), (1,0)) # horizontal first
C,X,Y,H,W,S = range(6) # indexes in the gems reprΓΒ©sentations as: [color, xTopLeft, yTopLeft, h, w, size]
lX,lY = 12,6 # dimensions of the board
start = 0,3,0 # starting config for the drops (x and y of center, and idx of ROTATIONS)
board = [ [None]*lY for _ in range(lX)]
gemsByColors = defaultdict(set)
for n,(pair,moves) in enumerate(arrMoves):
gemsPair = getStartPoses(moves, *pair) # apply the moves to the pair
if any(board[x][y] is not None for x,y,_ in gemsPair):
break # board already filled, end of game...
for x,y,c in gemsPair:
board[x][y] = [c,x,y,1,1,1]
gemsByColors[c].add((x,y))
toDrop = { (x,y) for x,y,_ in gemsPair }
while toDrop:
movedGems = drop(toDrop)
powaAndDrop = explode(movedGems)
toDrop = makePowa(*powaAndDrop)
return '
'.join( ''.join(gem and gem[C] or ' ' for gem in r) for r in board)
| Puzzle Fighter | 5a3cbf29ee1aae06160000c9 | [
"Games",
"Logic",
"Game Solvers",
"Algorithms"
] | https://www.codewars.com/kata/5a3cbf29ee1aae06160000c9 | 1 kyu |
<!--Blobservation-->
<p>Blobs of various sizes are situated in a room. Each blob will move toward the nearest smaller blob until it reaches it and engulfs it. After consumption, the larger blob grows in size.</p>
<p>Your task is to create a class <code>Blobservation</code> (a portmanteau of blob and observation) and methods that give information about each blob after an arbitrary number of moves.</p>
<h2 style='color:#f88'>Class Details</h2>
<p>A <code>Blobservation</code> class instance is instantiated with two integer values, <code>h</code> and <code>w</code>, that represent the dimensions of the room. The instance methods are as follows:</p>
<h3 style='color:#8df'>populate</h3>
<p>The <code>populate</code> method is called with an array/list representing a list of blobs.</p>
<ul>
<li>Each element is an object/dict (<code>Map<String,Integer></code> in Java) with the following properties:<br/>
<ul>
<li><code>x</code>: vertical position</li>
<li><code>y</code>: horizontal position</li>
<li><code>size</code>: size of the blob</li>
</ul></li>
<li>This method may be called multiple times on the same class instance</li>
<li>If a new blob's position is already occupied by an existing blob, the two fuse into a single blob</li>
<li>If the list input contains any invalid values, discard it entirely and throw an error (do not update/modify the instance)</li>
</ul>
```if:kotlin
For Kotlin, a preloaded data class `Blob` will be used to define blobs.
~~~kotlin
data class Blob(var x: Int, var y: Int, var size: Int)
~~~
```
<h3 style='color:#8df'>move</h3>
<p>The <code>move</code> method may be called with up to one argument β a positive integer representing the number of move iterations (ie. turns) to process. If no argument is given, the integer value defaults to <code>1</code>.</p>
<h3 style='color:#8df'>print_state</h3>
<p>The <code>print_state</code> method is a nullary function that returns an array of the positions and sizes of each blob at the current state (Java: a <code>List<List<Integer>></code> ), sorted in ascending order by <code>x</code> position, then by <code>y</code>. If there are no blobs, return an empty array.</p>
<h2 style='color:#f88'>Blob Movement Behavior</h2>
<p>With each turn, every blob whose <code>size</code> is larger than the smallest blob <code>size</code> value will move to one of the 8 spaces immediately surrounding it (<a href='https://en.wikipedia.org/wiki/Moore_neighborhood' style='color:#9f9;text-decoration:none'>Moore neighborhood</a>) in the direction of the nearest target blob with a lower relative <code>size</code>.</p>
<ul>
<li>If a target's coordinates differ on both axes, the predatory blob will move diagonally. Otherwise, it will move in the cardinal direction of its target</li>
<li>If multiple targets are at the same movement distance, the blob with the largest <code>size</code> is focused</li>
<li>If there are multiple targets that have both the largest <code>size</code> and shortest movement distance, priority is set in clockwise rotation, starting from the <code>12</code> position</li>
<li>If two blobs pass each other (e.g. swap positions as a result of their movement), they will not fuse</li>
<li>Blobs of the smallest size remain stationary</li>
</ul>
<h2 style='color:#f88'>Additional Technical Details</h2>
<ul>
<li>A blob's initial <code>size</code> will range between <code>1</code> and <code>20</code></li>
<li>Multiple blobs occupying the same space will automatically fuse into one</li>
<li>When a blob consumes another blob, or when two blobs fuse, the remaining blob's <code>size</code> becomes the sum of the two</li>
<li>The 2nd argument for the class constructor is optional; if omitted, the room defaults to a square, where <code>w == h</code>.</li>
<li>Room dimensions (<code>h</code> and <code>w</code>) will range between <code>8</code> and <code>50</code></li>
<li>Class instances will always be instantiated with valid arguments</li>
<li>Methods should throw an error if called with invalid arguments</li>
<li>Boolean values are not to be regarded as valid integers</li>
<li>Python translation: Use Python 3 only</li>
</ul>
<h2 style='color:#f88'>Test Example</h2>
<img src='https://i.imgur.com/4Moyo7t.png'>
<p>The image above shows the state at turn 0 (the initial state), turn 1, and turn 2.</p>
<ul>
<li>At <code>T:0</code>, the orange blob at <code>[4,3]</code> with a size of <code>4</code> has four different targets of equal movement distance β the blobs occupying the green, yellow, and red spaces. The adjacent matching-color spaces are the positions it would initially move to in pursuit of each respective target. Here it targets the size <code>3</code> blob at <code>[7,0]</code>.</li>
<li>At <code>T:1</code>, the size <code>2</code> blob that was in the yellow space has consumed the size <code>1</code> blob at <code>[6,7]</code> and now has a size of <code>3</code></li>
<li>At <code>T:2</code>, the size <code>3</code> blob in the green space has consumed the size <code>1</code> blob to become the size <code>4</code> blob at <code>[7,2]</code>. At this point, the two orange blobs will both target the green blob at <code>[4,2]</code> and all size <code>2</code> blobs will remain stationary</li>
</ul>
<p></p>
```javascript
const generation0 = [
{x:0,y:4,size:3},
{x:0,y:7,size:5},
{x:2,y:0,size:2},
{x:3,y:7,size:2},
{x:4,y:3,size:4},
{x:5,y:6,size:2},
{x:6,y:7,size:1},
{x:7,y:0,size:3},
{x:7,y:2,size:1}
];
const blobs = new Blobservation(8);
blobs.populate(generation0);
blobs.move();
blobs.print_state(); //[[0,6,5],[1,5,3],[3,1,2],[4,7,2],[5,2,4],[6,7,3],[7,1,3],[7,2,1]]
blobs.move();
blobs.print_state(); //[[1,5,5],[2,6,3],[4,2,2],[5,6,2],[5,7,3],[6,1,4],[7,2,4]]
blobs.move(1000);
blobs.print_state(); //[[4,3,23]]
```
```python
generation0 = [
{'x':0,'y':4,'size':3},
{'x':0,'y':7,'size':5},
{'x':2,'y':0,'size':2},
{'x':3,'y':7,'size':2},
{'x':4,'y':3,'size':4},
{'x':5,'y':6,'size':2},
{'x':6,'y':7,'size':1},
{'x':7,'y':0,'size':3},
{'x':7,'y':2,'size':1}
]
blobs = Blobservation(8)
blobs.populate(generation0)
blobs.move()
blobs.print_state() #[[0,6,5],[1,5,3],[3,1,2],[4,7,2],[5,2,4],[6,7,3],[7,1,3],[7,2,1]]
blobs.move()
blobs.print_state() #[[1,5,5],[2,6,3],[4,2,2],[5,6,2],[5,7,3],[6,1,4],[7,2,4]]
blobs.move(1000)
blobs.print_state() #[[4,3,23]]
```
```java
List<Map<String,Integer>> generation0 = Arrays.asList(
new HashMap<String,Integer>() {{ put("x", 0); put("y", 4); put("size", 3); }},
new HashMap<String,Integer>() {{ put("x", 0); put("y", 7); put("size", 5); }},
new HashMap<String,Integer>() {{ put("x", 2); put("y", 0); put("size", 2); }},
new HashMap<String,Integer>() {{ put("x", 3); put("y", 7); put("size", 2); }},
new HashMap<String,Integer>() {{ put("x", 4); put("y", 3); put("size", 4); }},
new HashMap<String,Integer>() {{ put("x", 5); put("y", 6); put("size", 2); }},
new HashMap<String,Integer>() {{ put("x", 6); put("y", 7); put("size", 1); }},
new HashMap<String,Integer>() {{ put("x", 7); put("y", 0); put("size", 3); }},
new HashMap<String,Integer>() {{ put("x", 7); put("y", 2); put("size", 1); }}
);
Blobservation blobs = new Blobservation(8);
blobs.populate(generation0);
blobs.move();
blobs.printState(); // [[0,6,5],[1,5,3],[3,1,2],[4,7,2],[5,2,4],[6,7,3],[7,1,3],[7,2,1]]
blobs.move();
blobs.printState(); // [[1,5,5],[2,6,3],[4,2,2],[5,6,2],[5,7,3],[6,1,4],[7,2,4]]
blobs.move(1000);
blobs.printState(); // [[4,3,23]]
```
```kotlin
val generation0 = arrayOf(
Blob(0,4,3),
Blob(0,7,5),
Blob(2,0,2),
Blob(3,7,2),
Blob(4,3,4),
Blob(5,6,2),
Blob(6,7,1),
Blob(7,0,3),
Blob(7,2,1)
)
val blobs = Blobservation(8)
blobs.populate(generation0)
blobs.move()
blobs.printState() // [[0,6,5],[1,5,3],[3,1,2],[4,7,2],[5,2,4],[6,7,3],[7,1,3],[7,2,1]]
blobs.move()
blobs.printState() // [[1,5,5],[2,6,3],[4,2,2],[5,6,2],[5,7,3],[6,1,4],[7,2,4]]
blobs.move(1000)
blobs.printState() // [[4,3,23]]
```
<p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p> | algorithms | import math
class Blobservation:
def __init__(self, height, width=None):
self . height = height
self . width = width or height
self . blobs = {} # {(x, y): size}
def populate(self, blobs):
for blob in blobs:
assert type(blob['x']) == type(blob['y']) == type(blob['size']) == int
assert 0 <= blob['x'] <= self . height and 0 <= blob['y'] <= self . width and blob['size'] > 0
for blob in blobs:
pos, size = (blob['x'], blob['y']), blob['size']
self . blobs[pos] = self . blobs . get(pos, 0) + size
def move(self, generations=1):
assert generations >= 1 and type(generations) == int
_total_size = sum(self . blobs . values())
for _ in range(generations):
if len(self . blobs) == 1:
break
new_blobs = {}
for pos, size in self . blobs . items():
target = min((p for p, s in self . blobs . items() if s < size),
key=lambda p: (self . _calc_dist(pos, p),
- self . blobs[p],
self . _calc_angle(pos, p)),
default=pos)
dx, dy = target[0] - pos[0], target[1] - pos[1]
new_pos = pos[0] + (dx and dx / / abs(dx)), pos[1] + (dy and dy / / abs(dy))
new_blobs[new_pos] = new_blobs . get(new_pos, 0) + size
self . blobs = new_blobs
def print_state(self):
return sorted([* p, s] for p, s in self . blobs . items())
@ staticmethod
def _calc_dist(p1, p2):
return max(abs(p2[0] - p1[0]), abs(p2[1] - p1[1]))
@ staticmethod
def _calc_angle(p1, p2):
dx, dy = p2[0] - p1[0], p2[1] - p1[1]
raw_angle = math . atan(- dy / dx) if dx != 0 else math . pi / \
2 if dy > 0 else - math . pi / 2
angle = raw_angle + (0 if dy >= 0 and dx <=
0 else math . pi if dy >= 0 or dx > 0 else 2 * math . pi)
return angle
| Blobservation | 5abab55b20746bc32e000008 | [
"Logic",
"Games",
"Object-oriented Programming",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5abab55b20746bc32e000008 | 3 kyu |
<p>This kata is inspired by <a href="http://plantsvszombies.wikia.com/wiki/Main_Page" style="color:#9f9;text-decoration:none"><b>Plants vs. Zombies</b></a>, a tower defense video game developed and originally published by PopCap Games.</p>
<p>The battlefield is the front lawn and the zombies are coming. Our defenses (consisting of pea-shooters) are in place and we've got the stats of each attacking zombie. Your job is to figure out how long it takes for them to penetrate our defenses.</p>
<h2 style='color:#f66'>Mechanics</h2>
<p>The two images below represent the lawn (for the test example below) at separate stages in the game.<br/>
<b>Left:</b> state at move <code>3</code>, before shooters fire. <b>Right:</b>state at move <code>5</code>, after shooters fire. (Moves are <code>0</code>-based)</p>
<div style="background:#262729"><img src="https://i.imgur.com/1wSbnMC.png" alt="example image"></div>
<ul>
<li><strong style='color:#95c4ff'>Moves:</strong> During a move, new zombies appear and/or existing ones move forward one space to the left. Then the shooters fire. This two-step process repeats.<br/>
If a zombie reaches a shooter's position, it destroys that shooter. In the example image above, the zombie at <code>[4,4]</code> on the left reaches the shooter at <code>[4,2]</code> and destroys it. The zombie has <code>1</code> health point remaining and is eliminated in the same move by the shooter at <code>[4,0]</code>.</li>
<li><strong style='color:#95c4ff'>Numbered shooters</strong> shoot straight (to the right) a given number of times per move. In the example image, the green numbered shooter at <code>[0,0]</code> fires <code>2</code> times per move.</li>
<li><strong style='color:#95c4ff'>S-shooters</strong> shoot straight, and diagonally upward and downward (ie. three directions simultaneously) once per move. In the example image, the blue and orange S-shooters can attack zombies in any of the blue and orange squares, respectively (if not blocked by other zombies).<br/>
At move <code>3</code> the blue shooter can only hit the zombie at <code>[1,5]</code> while the orange shooter hits each of the zombies at <code>[1,5]</code>, <code>[2,7]</code>, and <code>[4,6]</code> once for that move.</li>
<li><strong style='color:#95c4ff'>Shooting Priority</strong>: The numbered shooters fire all their shots in a cluster, then the S-shooters fire their shots in order from right to left, then top to bottom. Note that once a zombie's health reaches <code>0</code> it drops immediately and does not absorb any additional shooter pellets.<br/>
In the example image, the orange S-shooter fires before the blue one.</li>
</ul>
<h2 style='color:#f66'>Input</h2>
<p>Your function will receive two arguments:</p>
<ul>
<li><strong style='color:#95c4ff'>Lawn Map:</strong> An array/list consisting of strings, where each string represents a row of the map. Each string will consist of either <code>" "</code> (space character) which represents empty space, a numeric digit (<code>0-9</code>) representing a numbered shooter, or the letter <code>S</code> representing an S-shooter.</li>
<li><strong style='color:#95c4ff'>Zombie Stats:</strong> An array of subarrays representing each zombie, in the following format:<br/>
<code>[i,row,hp]</code> - where <code>i</code> is the move number (0-based) when it appears, <code>row</code> is the row the zombie walks down, and <code>hp</code> is the initial health point value of the zombie.<br/>
When new zombies appear, they start at the farthest right column of their row.</li>
</ul>
<p>Input will always be valid.</p>
<h2 style='color:#f66'>Output</h2>
<p>Return the number of moves before the first zombie penetrates our defenses (by getting past column <code>0</code>), or <code>null</code>/<code>None</code> if all zombies are eliminated.</p>
<h2 style='color:#f66'>Test Example</h2>
```javascript
let lawn = [
'2 ',
' S ',
'21 S ',
'13 ',
'2 3 '
];
let zombies = [[0,4,28],[1,1,6],[2,0,10],[2,4,15],[3,2,16],[3,3,13]];
plantsAndZombies(lawn,zombies); //10
```
```python
lawn = [
'2 ',
' S ',
'21 S ',
'13 ',
'2 3 '
]
zombies = [[0,4,28],[1,1,6],[2,0,10],[2,4,15],[3,2,16],[3,3,13]]
plants_and_zombies(lawn,zombies); #10
```
```kotlin
val lawn = arrayOf(
"2 ",
" S ",
"21 S ",
"13 ",
"2 3 "
)
val zombies = arrayOf(
intArray(0,4,28),
intArray(1,1,6),
intArray(2,0,10),
intArray(2,4,15),
intArray(3,2,16),
intArray(3,3,13))
plantsAndZombies(lawn,zombies) == 10 // true
```
```rust
let lawn = vec![
"2 ",
" S ",
"21 S ",
"13 ",
"2 3 "
];
let zombies = vec![
vec![0,4,28],
vec![1,1,6],
vec![2,0,10],
vec![2,4,15],
vec![3,2,16],
vec![3,3,13]
];
assert_eq!(plants_and_zombies(&lawn, &zombies), 10);// OK
```
<p>For another Tower Defense-style challenge, check out <a href='https://www.codewars.com/kata/5a57faad880385f3b60000d0' style="color:#aff;text-decoration:none"><b>Tower Defense: Risk Analysis</b></a></p>
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored). | algorithms | from itertools import chain
def plants_and_zombies(lawn, zProvider):
DEBUG = False
X, Y = len(lawn), len(lawn[0])
class Stuff (object): # Shooters and Zombies instances
def __init__(self, x, y, typ, h=0):
self . x, self . y = x, y
self . isS = typ == 'S'
self . fire = int(typ) if typ not in 'SZ' else 1
self . h = h
def __str__(self): return 'S' if self . isS else str(
self . h) if self . h else chr(self . fire + 64)
def __repr__(self): return "({},{})" . format(self . x, self . y)
def __bool__(self): return bool(self . h) # Behave as "isZomby()"
def __eq__(
self, other): return self . x == other . x and self . y == other . y
# The hash method reflects only the position in the board, so that a zomby and a shooter at the same position will have the same hash value
def __hash__(self): return self . x * X + self . y
def move(self): self . y -= 1 # for zombies
def damage(self, d): self . h -= d # for zombies
def display():
if DEBUG:
print('' . join("{: >2d}" . format(y)
for y in range(Y)), "\n" + "-" * (2 * Y))
board = [[' '] * Y for _ in range(X)]
for s in chain(sS, sN, * zombiesRows):
board[s . x][s . y] = "{: >2}" . format(str(s))
print('\n' . join(map('' . join, board)), "\n" + "-" * (2 * Y) + "\n")
def makeFire(s, dir=0): # dir = -1: diag up / 0: straight / 1: diag down
# Initiate a fake zombie at the shooter position (allow to continue the exploration of the current direction at the last found zombie)
nFire, z = s . fire, s
while nFire:
if not dir:
# Shoot straight = easy target
z = zombiesRows[z . x] and zombiesRows[z . x][0] or None
else:
z, x, y = None, z . x, z . y
# Shoot diag: seek a matching position in each row...
while z is None and 0 <= x + dir < X and y + 1 < Y:
x += dir
y += 1
if not zombiesRows[x]:
continue
z = next((z for z in zombiesRows[x] if z . x == x and z . y == y), None)
if z is None:
break # Not any zomby ahead... So sad...
d = min(nFire, z . h)
nFire -= d # Update the number of shots
z . damage(d) # Damage the current zomby...
if not z . h:
zombiesRows[z . x]. remove(z) # ...and "kill" it if necessary
pZ, round = 0, - 1 # Initiate the pointer to zProvider index and the round number
sN, sS = set(), set() # Sets of numbered and S shooters
for x, line in enumerate(lawn):
for y, c in enumerate(line):
if c != ' ':
(sS if c == 'S' else sN). add(Stuff(x, y, c))
# List of all the S shooters, in required order
sSlst = sorted(sS, key=lambda s: (- s . y, s . x))
# List of rows of zomby objects (to identify easily thos at the front, facing the shooters)
zombiesRows = [[] for _ in range(X)]
# Continue while zombies have to enter the lawn or while some aren't destroyed yet
while pZ < len(zProvider) or any(map(bool, zombiesRows)):
round += 1
# New zombies (outside of the map, will move into just after)
while pZ < len(zProvider) and zProvider[pZ][0] == round:
row, h = zProvider[pZ][1:]
zombiesRows[row]. append(Stuff(row, Y, 'Z', h))
pZ += 1
for row in zombiesRows:
for z in row:
if not z . y:
return round # End of game: crushed defenses...
else: # ...or move forward and destroy shooters if needed
z . move()
if z in sS:
sS . remove(z)
if z in sN:
sN . remove(z)
for s in sN:
makeFire(s) # Numbered shooters firing first
for s in sSlst: # S shooters firing in order...
if s in sS: # ...only if the S shooter hasn't been destroyed yet...
for d in [- 1, 0, 1]:
makeFire(s, d) # Shoot in the 3 directions
if DEBUG:
print(round, sum(map(len, zombiesRows)))
display()
| Plants and Zombies | 5a5db0f580eba84589000979 | [
"Logic",
"Games",
"Game Solvers",
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5a5db0f580eba84589000979 | 3 kyu |
<div style="font-size:13px;font-style:italic;color:gray">
This is the performance version of ALowVerus' kata, <a href="https://www.codewars.com/kata/5f5bef3534d5ad00232c0fa8">Topology #0: Converging Coins.</a> You should solve it first, before trying this one.
</div>
## Task
Let `$G$` be an undirected graph. Suppose we start with some coins on some arbitrarily chosen vertices of `$G$`, and we want to move the coins so that they finally end up on the very same vertex, using as few moves as possible. Knowing that each coin has to move across an edge at every step, your goal is to find and return the minimum number of moves required to do so or None if it's impossible.
## Input
The function `converge(g, coins)` takes 2 parameters:
* `g`: the undirected graph as a dictionary of sets of neighbours, of size `N`. All vertices are integers.
* `coins` as a tuple of vertices of size `C`. Those are the starting vertices of the coins, which might not be distinct.
## Output
Return the minimum number of steps possible to converge to any vertex, or `None` if no convergence is possible.
## Constraints
Watch out for performance: the original kata expects a quadratic solution but here, nothing less performant than linear in number of vertices will pass the tests... (And don't forget about the dependencies in number of coins!)
The reference solution running against the tests generally passes in 5-7s, and occasionnally up to 8,5s.
## Tests setup:
```if:python
Fixed tests:
* 20 tests: `N < 10 ; 1 < C < 8`
Random tests:
* 200 small tests: `5 <= N <= 15 ; 2 <= C < 6`
* 200 medium tests: `700 <= N <= 800 ; 2 <= C <= 8`
* 20 max coins tests: `700 <= N <= 800 ; 180 <= C <= 200`
* 40 huge tests: `8000 <= N <= 8100 ; 2 <= C <= 8`
```
### _Notes:_
* _There is only one visible assertion per group of random test._
* _The reference solution is run separately from your function (in a different `it` block), so you can compare easily the performances_
* _Don't mutate the input... You cannot use that to cheat anyway, but you'll run into trouble if you do so._ | reference | from itertools import count
from collections import deque, defaultdict
def converge(g, us):
us = set(us)
cnts = (defaultdict(int), defaultdict(int))
floods = [[[u], ({u}, set())] for u in us]
tic, N = 0, len(us)
for u in us:
cnts[tic][u] += 1
if cnts[tic][u] == N:
return 0
for step in count(1):
tic ^= 1
for i, (bag, seens) in enumerate(floods):
if not bag:
return None
tmp = []
for node in bag:
for neigh in g[node]:
if neigh in seens[tic]:
continue
seens[tic]. add(neigh)
cnts[tic][neigh] += 1
if cnts[tic][neigh] == N:
return step
tmp . append(neigh)
else:
floods[i][0] = tmp
| Topology #0.1: Converging Coins (Performance edition) | 60d0fd89efbd700055f491c4 | [
"Mathematics",
"Graph Theory"
] | https://www.codewars.com/kata/60d0fd89efbd700055f491c4 | 3 kyu |