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 task you are required to determine an expression consisting of variables and operators. * The variables are all single lower-case alphabetic characters * Each variable occurs only once in the expression * The operators are either `+` or `-` * There are no parentheses. For example: `"x-y+z"` or `"-d-b-c+w"` You must implement a function `plus_or_minus` which will be passed two parameters: * `variables` : a string consisting of just the variables in the order that they appear in the expression. For example: `"xyz"` or `"dbcw"` (The length of the input string will be between `1` and `26` inclusive.) * `test` : a test function which takes as its parameter a list of numeric values to be substituted for the variables in `variables`. The function will return the result of evaluation the expression. You must return the expression with the variables in the same order as the input and with the correct operators inserted. Omit any leading `+` from the start of the expression. Example 1: ``` expression = "x-y+z" variables = "xyz" test([1, 2, 3]) = 2 ``` Example 2: ``` expression = "-d-c-b+w" variables = "dbcw" test([3, 0, -1, 0.5]) = -1.5 ``` Here's the catch: In each test case you may only call `test` once. Subsequent calls will return `None`
algorithms
def plus_or_minus(vs, test): d = (test([2 * * i for i, _ in enumerate(vs)]) + (2 * * len(vs) - 1)) / / 2 return '' . join('-+' [d >> i & 1] + c for i, c in enumerate(vs)). lstrip('+')
Plus or Minus
65f8279c265f42003ffbd931
[ "Mathematics" ]
https://www.codewars.com/kata/65f8279c265f42003ffbd931
6 kyu
# Task Write a function that takes an array containing numbers and functions. The output of the function should be an array of only numbers. So how are we to remove the functions from the array? All functions must be applied to the number before it prior to the function being discarded from the array. It is as if the functions are collapsing left in the array modifying the first number to the left of the function. The functions should apply in order of index in the array. After a function has been applied to the number before it, it should be "removed" from the array to allow any following functions to also modify that new number. # Example ```javascript [ 3, f(x) = x + 2, f(x) = x * 5, 4, f(x) = x - 1 ] => [ 25, 3 ] ``` because ```javascript [ (3 + 2) * 5, 4 - 1 ] ``` Note how all functions collapsed into the closest number to the left; they did not produce new numbers into the array, but modified existing ones. # Notes - If a function comes first in the array, it should behave as if it were passed in `0`: `[ f(x) = x + 2, 4 ] => [0 + 2, 4]` - An empty array passed in must return an empty array. - Functions will always take exactly one, number, parameter. - If an array only contains numbers, the array should be returned without any modifications.
games
def operation_arguments(arr): result = [] for val in arr: if callable(val): result . append(val(result . pop() if result else 0)) else: result . append(val) return result
Collapse Left
65f1c009e44a0f0777c9fa06
[ "Arrays" ]
https://www.codewars.com/kata/65f1c009e44a0f0777c9fa06
6 kyu
There is a row of ants. An ant can be represented by letter "R" - facing right, and "L" - facing left. Every ant is moving with constant speed. When ants collide, they are changing their direction to opposite. Our task is to count collisions for each ant. There is a starting gap between ants, lets say that it is 2 meters. Example: "RL" Should return "1 1" Because they collide each other once, and then they never collide, because earth is flat. You will have to count bumps up to 1 000 000 ants. I am not a real author of this great algorithm challenge. I cant name the author though. Here is the only source i could have find https://sio2.mimuw.edu.pl/c/pa-2024-1/p/mro/ , it is in polish.
algorithms
def bump_counter(ants): res = [] n, c = ants . count("L"), 0 for i, d in enumerate(ants): t = (i < n) - (d == "L") res . append(2 * c + t) c += t return " " . join(map(str, res))
Disorganized ants
65ee024f99785f0906e65bee
[ "Performance" ]
https://www.codewars.com/kata/65ee024f99785f0906e65bee
5 kyu
You stumble upon a genie who offers you a single wish. Being a food enthusiast, you wish for the opportunity to experience all the food at your favorite tapas restaurant. However, the genie has a twist in store and traps you in a time loop, destined to repeat the same evening until you've experienced every possible combination of dishes within a specified price range. Objective: Calculate how many iterations of the time loop you'll endure before you've tasted all the meal variations that meet these conditions. ## Details #### Meal Composition - A meal consists of one or more dishes. - Each dish can be ordered no more than once per meal. - Dishes are served simultaneously, meaning the meal's composition does not depend on the order in which dishes are selected. - The total cost of a meal must be at least `a` and no more than `b`. #### Inputs - `menu`: A list containing the cost of each dish on the menu. - `a`, `b`: The minimum and maximum cost of a meal. #### Outputs - The minimum number of iterations of the time loop you'll endure (may be zero or very large). #### Additional Constraints - The cost of each dish is a whole, non-negative number. - Some dishes may cost the same as others. - The menu can contain any number of dishes from `1` to `1000`. - `a` and `b` are positive integers with `1 <= a <= b <= 1000`. #### Efficiency Efficiency is important in this problem. An inefficient solution will not pass the tests. #### Sample Input/Output Input: Menu prices = [2, 3, 5]; a = 5; b = 10 The combinations are `[2,3]`, `[5]`, `[2,3,5]`, `[2,5]`, and `[3,5]`, so you'll need to endure `5` iterations of the time loop to try every meal. Expected Output: 5
algorithms
def count_time_loops(menu, a, b): # Initialize a dynamic programming table dp = [0] * (b + 1) dp[0] = 1 # Base case: 1 way to achieve cost 0 (empty meal) # Iterate over each dish cost in the menu for cost in menu: # Update the dynamic programming table from right to left for i in range(b, cost - 1, - 1): dp[i] += dp[i - cost] # Calculate the total combinations within the specified cost range total_combinations = sum(dp[a: b + 1]) return total_combinations
Too many meals
65ee35959c3c7a2b4f8d79c1
[ "Combinatorics", "Performance", "Mathematics", "Dynamic Programming" ]
https://www.codewars.com/kata/65ee35959c3c7a2b4f8d79c1
5 kyu
# Will The DVD Logo Hit The Corner You've probably seen the meme where people want the DVD logo to hit the corner. But it won't always hit it. When will it? ![DVD Logo Gif](https://user-images.githubusercontent.com/19642322/66207589-d054c500-e6bb-11e9-9d84-a0fbb5d2ef93.gif) To simplify the problem, instead of a rectangular logo, it's a singular point on a graph. If at any point it hits the corners of a rectangular grid, it counts as "hitting the corner" The logo will only move in 45° angles, changing direction similarly to the gif above. Given the size of the "TV screen", the starting position of the "logo", and its direction, determine if it will hit the corner or not. ## Input The parameters are: * w and h: The size of the screen (positive integers) * x and y: The position of the logo (non negative integers), bottom left is (0, 0) * d: The direction the logo will initially go in ("NE", "SE", "SW", or "NW") * All inputs are valid ## Output * True if it will hit the corner (at any point) * False if it will not hit the corner * If it starts in a corner, that counts as a "hit" ## Efficiency Efficiency is a must. You must be able to complete inputs up to w or h being 1e30 without timing out. *Hint: Don't just simulate the entire process, find a smarter solution ;)* If the perfect algorithm is found, it can be completed in under 10ms, with no significant increase in time from small to huge numbers. ## Examples #### w = 12, h = 8, x = 5, y = 3, d = "NE" --> False <img src='https://i.postimg.cc/1twVSFLq/Screenshot-2024-03-06-7-23-38-PM.png' width='463'> #### w = 12, h = 8, x = 5, y = 3, d = "SE" --> True <img src='https://i.postimg.cc/vmpxChSy/Screenshot-2024-03-06-7-30-54-PM.png' width='463'> Have fun!
algorithms
# Just imagine a straight line on a lattice of infinite copies of the TV. from math import gcd def will_hit_corner(w, h, x, y, dir): if dir == "NE" or dir == "SW": slope = 1 else: slope = - 1 return (y - slope * x) % gcd(w, h) == 0
Will The DVD Logo Hit The Corner? - Efficiency Version
65e8b02a9e79a010e5210b6c
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/65e8b02a9e79a010e5210b6c
6 kyu
## Task You are given a big cube, made up of several little cubes. You paint the outside of the big cube and are now supposed to find out how many of the little cubes have zero faces painted, one face painted, two faces painted, etc. Write a function which accepts two parameters: 1) `length`: the side length of the big cube (in little cubes), `0 <= length <= 50` 2) `n`: the number of faces painted, `0 <= n <= 7` **You have to figure out how many of the little cubes have `n` faces painted.** ## Example ```haskell paintedFaces(4,3) => result: 8 -- Only the vertices of the big cube will have three faces painted ``` ```c painted_faces(4,3) => result: 8 // Only the vertices of the big cube will have three faces painted ``` ```python painted_faces(4,3) => result: 8 # Only the vertices of the big cube will have three faces painted ``` ```javascript paintedFaces(4,3) => result: 8 // Only the vertices of the big cube will have three faces painted ``` If `n > 3` then return `0` as it is not possible for a painted cube to have more than `3` sides painted (unless `s == 1`, in that case it will have `6` faces painted).
games
def painted_faces(sides, n): if sides == 0: return 0 elif sides == 1: if n == 6: return 1 else: return 0 else: if n == 0: return (sides - 2) * * 3 # inside cubes elif n == 1: return 6 * (sides - 2) * * 2 # face cubes elif n == 2: return 12 * (sides - 2) # rib cubes elif n == 3: return 8 # corner cubes else: return 0
Painted Sides
65e594c5a93ef700294ced80
[ "Mathematics", "Logic", "Puzzles" ]
https://www.codewars.com/kata/65e594c5a93ef700294ced80
7 kyu
You're in a competition with another guy. You take turns hammering the nail. Whoever hits the last blow wins. The last blow means that the nail will be completely hammered. Your input is the length of the nail (`0 < l < 100`). You can hit with different strengths: `1, 2 or 3` units of nail length at a time. Your opponent is stronger than you, and his hitting strength can be `2, 3 or 4` units, but you have a friend in judging who has excluded all hopeless initial `l` values for you. You make the first strike. Return the strength of your current strike (`1, 2 or 3`), depending on the remaining length of the nail. The tests will invoke your and your opponent's solutions with the remaining length of the nail, as long as `l > 0`. Then, if `l <= 0` after your hit, you win the contest and pass the kata.
games
def hit(l): return l % 5
The Nail
65e2df8302b29a005831eace
[ "Puzzles" ]
https://www.codewars.com/kata/65e2df8302b29a005831eace
7 kyu
##### Disclaimer If you're not into math, you might want to skip this kata. ### Property Some rectangles have a recurring ratio of side lengths (the most famous example is A-series paper). For some of them, when removing a number of inner squares (each such square must have the side length of the smallest side of the rectangle), the ratio <code>a / b</code> is the same as <code>b / c</code>. Example (n = 1) <svg fill="none" height="137" width="391" xmlns="http://www.w3.org/2000/svg"><path d="M38.5 37.5h161v99h-161z" stroke="#000" fill="red"></path><path fill="#05c505" d="M38 19l10 5.773V13.227L38 19zm162 0l-10-5.773v11.547L200 19zM47 20h144v-2H47v2zM18 37l-5.773 10h11.547L18 37zm0 100l5.773-10H12.227L18 137zm-1-91v82h2V46h-2z"></path><g stroke="#000"><path d="M38.5 37.5h99v99h-99z" fill="#010bff"></path><path d="M288.5 37.5h61v99h-61z" fill="red"></path></g><path fill="#05c505" d="M288 19l10 5.773V13.227L288 19zm62 0l-10-5.773v11.547L350 19zm-53 1h44v-2h-44v2zm76 17l-5.774 10h11.548L373 37zm0 100l5.774-10h-11.548L373 137zm-1-91v82h2V46h-2zM2.254 81.368l1.092-.084c.084 0 .14.033.168.098.009.037-.145.695-.462 1.974l-.49 1.946c0 .019.047-.005.14-.07.299-.187.597-.317.896-.392.271-.037.523-.033.756.014a1.92 1.92 0 0 1 .98.518 2.02 2.02 0 0 1 .504.854c.159.467.182.975.07 1.526-.187 1.017-.667 1.862-1.442 2.534-.14.121-.28.229-.42.322-.289.187-.56.322-.812.406-.607.196-1.143.182-1.61-.042C.98 90.664.607 90.09.504 89.25c-.028-.159-.028-.425 0-.798.028-.187.285-1.246.77-3.178l.644-2.94c-.065-.065-.266-.103-.602-.112-.224 0-.35-.033-.378-.098-.019-.028-.005-.135.042-.322.047-.196.084-.303.112-.322.028-.028.056-.042.084-.042l1.078-.07zm1.848 4.144c-.196-.056-.42-.047-.672.028-.383.159-.751.462-1.106.91l-.07.098-.238.98c-.243.961-.364 1.582-.364 1.862 0 .392.098.686.294.882.233.233.537.289.91.168.364-.121.667-.369.91-.742.14-.215.289-.574.448-1.078l.336-1.414c.121-.56.131-.971.028-1.232-.093-.233-.252-.387-.476-.462zm382.152-8.144l1.092-.084c.084 0 .14.033.168.098.009.037-.145.695-.462 1.974l-.49 1.946c0 .019.047-.005.14-.07.299-.187.597-.317.896-.392.271-.037.523-.033.756.014a1.92 1.92 0 0 1 .98.518c.233.233.401.518.504.854.159.467.182.975.07 1.526-.187 1.017-.667 1.862-1.442 2.534-.14.121-.28.229-.42.322-.289.187-.56.322-.812.406-.607.196-1.143.182-1.61-.042-.644-.308-1.017-.882-1.12-1.722-.028-.159-.028-.425 0-.798.028-.187.285-1.246.77-3.178l.644-2.94c-.065-.065-.266-.103-.602-.112-.224 0-.35-.033-.378-.098-.019-.028-.005-.135.042-.322.047-.196.084-.303.112-.322.028-.028.056-.042.084-.042l1.078-.07zm1.848 4.144c-.196-.056-.42-.047-.672.028-.383.159-.751.462-1.106.91l-.07.098-.238.98c-.243.961-.364 1.582-.364 1.862 0 .392.098.686.294.882.233.233.537.289.91.168.364-.121.667-.369.91-.742.14-.215.289-.574.448-1.078l.336-1.414c.121-.56.131-.971.028-1.232-.093-.233-.252-.387-.476-.462zM115.724.826c.009-.009.093-.014.252-.014l.35.042a1.59 1.59 0 0 1 .756.476l.07.098.098-.098c.252-.233.513-.299.784-.196a.42.42 0 0 1 .28.266c.037.112.014.345-.07.7l-.392 1.582-.518 2.114c-.037.205-.033.373.014.504.056.149.163.215.322.196.112-.009.229-.098.35-.266.131-.196.266-.56.406-1.092.037-.159.079-.247.126-.266.028-.009.117-.014.266-.014.177 0 .275.009.294.028.056.037.056.145 0 .322-.243.868-.555 1.442-.938 1.722-.149.112-.299.182-.448.21-.196.028-.406.014-.63-.042-.42-.093-.719-.313-.896-.658l-.042-.098-.084.07c-.737.635-1.465.859-2.184.672-.205-.056-.397-.14-.574-.252-.532-.373-.835-.929-.91-1.666a2.65 2.65 0 0 1 .014-.812c.121-.784.443-1.503.966-2.156a4.3 4.3 0 0 1 .588-.588c.532-.439 1.069-.695 1.61-.77.037-.009.084-.014.14-.014zm.406.686c-.187-.047-.341-.056-.462-.028-.289.056-.569.219-.84.49-.271.289-.509.803-.714 1.54l-.154.588c-.159.635-.238 1.106-.238 1.414 0 .289.061.518.182.686.177.233.425.327.742.28.355-.037.719-.243 1.092-.616a2.5 2.5 0 0 0 .378-.462c0 .028.126-.462.378-1.47l.35-1.442-.014-.098c-.121-.467-.355-.761-.7-.882zM320.074.826h.574c.681.103 1.106.387 1.274.854a1.1 1.1 0 0 1-.07.854 1.16 1.16 0 0 1-.182.266c-.252.233-.523.327-.812.28a.71.71 0 0 1-.364-.154.58.58 0 0 1-.168-.336c-.047-.28.047-.546.28-.798a.8.8 0 0 1 .21-.154l.056-.042c0-.028-.126-.065-.378-.112-.616-.084-1.171.126-1.666.63-.327.355-.588.905-.784 1.652a1.37 1.37 0 0 1-.042.196c-.187.747-.261 1.269-.224 1.568.065.495.331.803.798.924.196.056.485.056.868 0 .588-.084 1.087-.285 1.498-.602a1.7 1.7 0 0 0 .448-.406c.103-.121.187-.159.252-.112.028.019.079.065.154.14.131.14.191.229.182.266-.037.103-.201.275-.49.518l-.126.098c-.663.504-1.461.77-2.394.798-.616.009-1.139-.131-1.568-.42-.215-.131-.406-.317-.574-.56-.177-.261-.299-.551-.364-.868-.177-.868.033-1.745.63-2.632a3.21 3.21 0 0 1 .21-.294 4.6 4.6 0 0 1 .672-.672c.663-.532 1.363-.826 2.1-.882z"></path></svg> ### Task Given the number of inner squares to remove from such rectangle <code>n</code>, what is value of the ratio of the longer side over the smaller side? Don't round your result. - <code>1 &le; n &le; 1000</code>
games
import math def get_rectangle_ratio(n): return (n + math . sqrt(n * n + 4)) / 2
Recurring Rectangle Ratio
65e0fa45446dba00143d3744
[ "Puzzles", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/65e0fa45446dba00143d3744
7 kyu
Well known Fibonacci sequence have interesting property - if you take every Fibonacci number modulo n, eventually they will form cycle. For example, if n = 5, {F_k mod 5} is ```C# 0, 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4, 3, 2, 0, 2, 2, 4, 1, 0, 1, ... ``` Length of this cycle called Pisano period. You can read more about it properties on [Wiki](https://en.wikipedia.org/wiki/Pisano_period) and [here](https://sites.math.rutgers.edu/~zeilberg/essays683/renault.html). Your task is to calculate Pisano period for given number n. Size of numbers will not exceed 64 bits. Note, that naive approach will definitely fail on this one. There is also [easier version](https://www.codewars.com/kata/5f1360c4bc96870019803ae2) of same task. ```if:python Restrictions : gmp2, numpy, scipy, os, pip are not allowed. ``` ```if:javascript Restrictions : require is disabled. ``` ```if:cpp Note : as C++ lacks big integers, you are provided with two utility functions `uint64_t addmod(uint64_t a, uint64_t b, uint64_t m)` and `uint64_t mulmod(uint64_t a, uint64_t b, uint64_t m)` that compute respectively `(a+b)%m` and `(a*b)%m` without overflows. ```
algorithms
from collections import Counter from random import randrange from math import gcd, lcm, log, log2 def miller_rabin_test(n): if n < 2 or not n % 2 or not n % 3: return n in (2, 3) k, r, d = 5, 0, n - 1 while d % 2 == 0: d / /= 2 r += 1 while k >= 1: k -= 1 a = randrange(2, n - 1) x = pow(a, d, n) if x == 1 or x == n - 1: continue m = r - 1 while m >= 1: m -= 1 x = pow(x, 2, n) if x == n - 1: break else: return False return True def is_prime(n): return miller_rabin_test(n) def pollard_rho(n): while True: x, c = randrange(1, n), randrange(1, n) def f(x): return (x * x + c) % n y = f(x) while (d := gcd(abs(x - y), n)) == 1: x, y = f(x), f(f(y)) if d != n: return d def factor(n): if is_prime(n): return Counter([n]) return factor(r := pollard_rho(n)) + factor(n / / r) def divisor(n, psm): ps = [] for p, k in psm . items(): for i in range(k): ps . append(p) ds = set([1, n]) def go(i, d): if i < len(ps): ds . add(d * ps[i]) go(i + 1, d) go(i + 1, d * ps[i]) go(0, 1) return sorted(list(ds)) def binary_raise(n, p): r = 1 while p > 0: if (p & 1) == 1: r *= n p >>= 1 n *= n return r def ext_euclidean(a, b): x, y, u, v = 0, 1, 1, 0 while a != 0: q, r = b / / a, b % a m, n = x - u * q, y - v * q a, b, x, y, u, v = r, a, u, v, m, n return b, x, y def fast_mul(a, b, p): q, r = a s, t = b x = q * s + 5 * r * t y = q * t + r * s return (x % p, y % p) def fast_plus(a, n, p): r = (1, 0) while n > 0: if (n & 1) == 1: r = fast_mul(r, a, p) n >>= 1 a = fast_mul(a, a, p) return r def fib_mod(n, p): _, q, _ = ext_euclidean(pow(2, n, p), p) q %= p ns = fast_plus((1, 1), n, p) return fast_mul(ns, (q, 0), p) def prime_pisano(n): if n == 2: return 3 r = n % 5 q = 4 * n if not r else n - 1 if r in (1, 4) else 2 * (n + 1) if not r: return q ps = factor(q) ds = divisor(q, ps) for d in ds: if fib_mod(d, n) == (1, 0): return d def composite_pisano(n): ps, m = factor(n), 1 for p, k in ps . items(): m = lcm(m, binary_raise(p, k - 1) * prime_pisano(p)) return m def pisano_period(n): if n == 1: return 1 eps, p2, p5 = 1e-9, log2(n), log(n) / log(5) if p2 % 1 < eps: return 3 * (2 * * (round(p2) - 1)) if p5 % 1 < eps: return 4 * (5 * * round(p5)) return composite_pisano(n) # initial method name of the kata PisanoPeriod = pisano_period
Pisano Period - Performance Edition
65de16794ccda6356de32bfa
[ "Performance", "Mathematics", "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/65de16794ccda6356de32bfa
2 kyu
You order a shirt for your friend that has a word written in sign language on it, you would like to fool your friend into thinking it says something other than what it actually says. Your friend is smart, but he can't know what he doesn't already know, he only knows a certain amount of letters in sign language. Given the word on the shirt, the word you are attempting to make your friend believe is on the shirt, and the letters in sign language your friends knows, figure out if he can tell that you are fooling him. Return true if your friend can figure out you are fooling him, otherwise return false. **It is guaranteed that both words will be the same length and will be in lowercase letters (a-z)** ``` Example 1: Word on shirt: snack Word you said: snake Letters your friend knows: [c] return true Your friend knows the 4th letter is a c rather than a k. ``` **If the word on the shirt and the word you told your friend is the same then you aren't fooling your friend, so you should return false** ``` Example 2: Word on shirt: snack Word you said: snack Letters your friend knows: [s, n, a, c, k] return false Since you are not fooling your friend ``` ``` Example 3: Word on shirt: snake Word you said: snack Letters your friend knows: [c] return true Your friend knows that the 4th letter is not a c ``` ``` Example 4: Word on shirt: smile Word you said: smirk Letters your friend knows: [s, m, i] return false Your friend doesn't know what the letters l and e from smi(le) look like in sign language. So he cannot say that those letters are not r or k from smi(rk) because he wouldn't know So your friend cannot figure out if you are fooling him. ```
reference
def gaslighting(s, y, f): return any(a != b and (a in f or b in f) for a, b in zip(s, y))
Misleading Signs
65dd5b414ccda60a4be32c2a
[ "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/65dd5b414ccda60a4be32c2a
7 kyu
## Task Write a function create_compound which gives the **chemical formula** of a compound when given its **name**. For example, ``` create_compound('Lead Nitrate') -> 'Pb(NO₃)₂' create_compound('Aluminium Sulphate') -> 'Al₂(SO₄)₃' create_compound('Sodium Carbonate') -> 'Na₂CO₃' create_compound('Magnesium Oxide') -> 'MgO' ``` ## Notes Whenever a compound molecule has a "subscript" greater than 1, the compound should be put in brackets, like so: (SO₄)₂ (see examples below) All required elements (with their symbols) and valencies are preloaded in the dictionaries **symbols** and **valency**. To get the proper subscripts, you can copy and paste these: ``` ₁ ₂ ₃ ₄ ``` ## Examples ``` Sodium Carbonate Symbol Na CO₃ Valency 1 2 So, we get the formula: => Na₂CO₃ ``` ``` Magnesium Oxide Symbol Mg O Valency 2 2 So, we get the formula: => MgO # the 2s cancel out ``` ``` Lead Nitrate Symbol Pb NO₃ Valency 2 1 So, we get the formula: => PbNO₃₂ => Pb(NO₃)₂ #As nitrate is a compound molecule, it goes in brackets ```
reference
from preloaded import symbols, valency from math import gcd def create_compound(name): ind = {1: '', 2: '₂', 3: '₃', 4: '₄'} cmps = name . split() s1, s2 = map(symbols . get, cmps) v1, v2 = map(valency . get, cmps) g = gcd(v1, v2) v1, v2 = v1 / / g, v2 / / g def comp(s, v): return f' { s }{ v } ' if sum(x . isupper() for x in s) < 2 or v == '' else f'( { s } ) { v } ' return f' { comp ( s1 , ind [ v2 ])}{ comp ( s2 , ind [ v1 ])} '
Deriving Compounds
65dc66fc48727d28ac00db5c
[ "Logic" ]
https://www.codewars.com/kata/65dc66fc48727d28ac00db5c
6 kyu
## Trilingual democracy Switzerland has [four official languages](https://www.fedlex.admin.ch/eli/cc/2009/821/en#art_5): German, French, Italian, and Romansh.<sup>1</sup> When native speakers of one or more of these languages meet, they follow certain [regulations](https://www.fedlex.admin.ch/eli/cc/2010/355/en) to choose a language for the group.<sup>2</sup> Here are the rules for groups of exactly three<sup>3</sup> people:<sup>4</sup> * When all three are native speakers of the same language, it also becomes their group's language.<sup>5a</sup> * When two are native speakers of the same language, but the third person speaks a different language, all three will converse in the minority language.<sup>5b</sup> * When native speakers of three different languages meet, they eschew these three languages and instead use the remaining of the four official languages.<sup>5c</sup> The languages are encoded by the letters `D` for *Deutsch*, `F` for *Français*, `I` for *Italiano*, and `K` for *Rumantsch*.<sup>6</sup> Your task is to write a function that takes a list of three languages and returns the language the group should use.<sup>7 8</sup> Examples:<sup>9</sup> * The language for a group of three native French speakers is French: `FFF` &rarr; `F` * A group of two native Italian speakers and a Romansh speaker converses in Romansh: `IIK` &rarr; `K` * When three people meet whose native languages are German, French, and Romansh, the group language is Italian: `DFK` &rarr; `I` --- <sup>1</sup> The first sentence of the description and the first sentence of this footnote are true. Almost all other sentences in the description and the footnotes are complete hogwash. <sup>2</sup> This footnote has no useful content. It was inserted solely to make the next footnote &ndash;&nbsp;at least in some sense&nbsp;&ndash; [self-referential](https://en.wikipedia.org/wiki/Self-reference). <sup>3</sup> Thou shalt count to three, no more, no less. Four shalt thou not count, neither count thou two, excepting that thou then proceed to three. Five is right out. <sup>4</sup> These rules were carefully designed with a focus on practices that could be perceived as exclusive or discriminatory. <sup>5a</sup> The first rule is based on pragmatics and aesthetics: choosing a language other than the one spoken by all three would introduce gratuitous friction and asymmetry. <sup>5b</sup> The second rule is inspired by a strong sense of politeness and modesty: it would feel arrogant for the majority to impose its language upon the minority. <sup>5c</sup> The third rule originates from a deep belief in fairness: picking one of the languages spoken in the group would arbitrarily privilege one member and disadvantage the two others. <sup>6</sup> The choice of the letter `K` for *Rumantsch* was an accident &ndash; during the linguistic rule standardization process in 1964 a typist at the *Bundesamt für Organisation* misread a hand-written `R` as `K`. Unfortunately, correcting this mistake would break backwards compatibility. <sup>7</sup> The input argument of your function will always be a string (or an array, depending on programming language) of exactly three upper-case characters from the set `D`, `F`, `I` and `K`, and the return value of your function must be a single upper-case character from this set. <sup>8</sup> This footnote is a deceptive [non sequitur](https://en.wikipedia.org/wiki/Non_sequitur_(literary_device)), as it erroneously claims that the multilingual people of Switzerland are united by a shared fondness for [watchmaking](https://en.wikipedia.org/wiki/Watchmaking), [bit twiddling](https://en.wikipedia.org/wiki/Bit_twiddling), the [*Basic Latin*](https://en.wikipedia.org/wiki/Basic_Latin_(Unicode_block)) Unicode block, and [Gruyère cheese](https://en.wikipedia.org/wiki/Gruyère_cheese). <sup>9</sup> This is footnote 9, and it's just as nonsensical as footnotes 2, 3, and 8, since it merely observes that 9 happens to be the [bitwise exclusive-or](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of 2, 3, and 8.
games
def trilingual_democracy(group: str) - > str: _set = set(group) if len(_set) == 1: return group[0] if len(_set) == 3: return next(iter(set('DFIK') - _set)) return min(group, key=group . count)
Trilingual democracy
62f17be8356b63006a9899dc
[ "Fundamentals", "Puzzles", "Strings" ]
https://www.codewars.com/kata/62f17be8356b63006a9899dc
7 kyu
## Introduction In a parallel universe not too distant from our own, *Julius Caesar* finds himself locked in a fierce conflict with *Genghis Khan*. Legend has it that Khan's armies were renowned for their mastery of horseback archery, a formidable advantage in battle. To level the playing field, divine intervention granted Caesar a helping hand. With divine assistance, *Big Jul* gained the ability to impart his knowledge to his troops, a boon bestowed upon **all of his men**. He could impart any skill he possessed to those who lacked it. Skills, in this universe, are represented by the binary representation of an integer. Each bit corresponds to a specific skill, with `1` denoting proficiency and `0` representing ignorance. Using his wisdom, Caesar could transform any `0` to a `1` if he himself possessed the corresponding skill. Armed with the value `n`, representing his own skills, Caesar sets out to enhance the abilities of his troops, numbering from `1` to `n`. Time is of the essence as the threat of the approaching Asian cavalry looms ever closer. ## Task Given a **positive integer** `n`, return the sum of the **Bitwise OR** operation between `n` and **all integers** from `1` to `n` (both inclusive). In fancy math terms: `$\sum_{i=1}^{n}n|i$`, where `|` is the **Bitwise OR** operation. ## Performance **Brute force** solutions, yielding a time complexity of `O(n)`, won't work. The **expected** time complexity is `O(logn)`. Most solutions with a time complexity **equal or close** to that should pass **with ease**. ```python Random Tests: 100 Integer Size: 1 to 10 ** 100 ``` ## Examples ```python 1 -> 1 2 -> 5 3 -> 9 4 -> 22 10 -> 121 100 -> 11302 ```
algorithms
def or_sum(n: int) - > int: return n * * 2 + sum(n >> i + 1 << 2 * i for i in range(n . bit_length()) if not 1 << i & n)
The OR sum
65d81be5ac0d2ade3a6c637b
[ "Mathematics", "Bits", "Performance" ]
https://www.codewars.com/kata/65d81be5ac0d2ade3a6c637b
6 kyu
## Overview Jack's chemistry teacher gave him piles of homework to complete in just ONE day and he just can't seem to get it done! All the questions are of the same type, making the homework both tedious and time-consuming. He has been given the chemical formula of an element and is required to find out how many moles will be there in a given mass of that element. Will you help him write out a function to help him finish his homework? ## Task Write a function **count_the_moles** which returns the number of moles present in a given mass of a substance. You will be given: 1) The mass of substance taken (in grams) 2) The chemical formula of that substance ## Important Notes 1) The chemical formulas will not be written with subscript: i.e, Carbon dioxide = CO2 2) The substances will be very simple. The no. of atoms of each element will not exceed 9 i.e, substances like sugar (C12H22O11) will not be given, but substances like carbon dioxide (CO2) will be given 3) The only elements in the substance will be Carbon (atomic mass = **12u**) , Hydrogen (atomic mass = **1u**) , Nitrogen (atomic mass = **14u**) , Oxygen (atomic mass = **16u**) , Potassium (atomic mass = **39u**) , Phosphorus (atomic mass = **31u**) , Sulphur (atomic mass = **32u**) and Fluorine (atomic mass = **19u**) **All these elements are preloaded in the dictionary named atomic_masses** ## Good Luck!
games
from preloaded import atomic_masses def count_the_moles(mass_of_substance: float, chemical_formula: str): mole_mass = 0 for i, x in enumerate(chemical_formula): if x . isalpha(): if i + 1 <= len(chemical_formula) - 1 and chemical_formula[i + 1]. isdigit(): mole_mass += atomic_masses[x] * int(chemical_formula[i + 1]) else: mole_mass += atomic_masses[x] return mass_of_substance / mole_mass
Count the moles!
65d5cf1eac0d2a6c4f6c60e6
[ "Logic", "Mathematics" ]
https://www.codewars.com/kata/65d5cf1eac0d2a6c4f6c60e6
7 kyu
You are given a positive integer **n** greater than one. How many ways are there to represent it as a product of some **Fibonacci numbers** greater than one? *(Fibonacci sequence: 1, 1, 2, 3, 5, 8...).* For example, there are two ways for **n = 40**: 1) 2 * 2 * 2 * 5 2) 5 * 8 But you can't represent **n = 7** in an aforementioned way. Note that n may be really big (**up to 10^36**). Good luck!
algorithms
def fibs(limit): a, b, res = 2, 3, [] while a <= limit: res . append(a) a, b = b, a + b return res FIB = fibs(10 * * 36) from functools import cache @ cache def fib_prod(n: int, m: int = 1) - > int: return 1 if n == 1 else sum(fib_prod(n / / d, d) for d in FIB if d >= m and n % d == 0)
Fibonacci's Product
65d4d2c4e2b49c3d1f3c3aec
[ "Recursion", "Performance" ]
https://www.codewars.com/kata/65d4d2c4e2b49c3d1f3c3aec
5 kyu
You are given a string "strng" Perform the following operation until "strng" becomes empty: For every alphabet character from 'a' to 'z', remove the first occurrence of that character in "strng" (if it exists). Example, let initially strng = "aabcbbca". We do the following operations: Remove the underlined characters strng = "(a)a(b)(c)bbca". The resulting string is strng = "abbca". Remove the underlined characters strng = "(a)(b)b(c)a". The resulting string is strng = "ba". Remove the underlined characters strng = "(b)(a)". The resulting string is strng = "". Return the value of the string strng right before applying the last operation. In the example above, answer is "ba". You can assume on next: strng will never be empty strng.length <= 5 * 10**5 strng will contains only of lowercase English letters.
algorithms
from collections import Counter def last_non_empty_string(s: str) - > str: x = Counter(s) l = max(x . values()) - 1 for w in x: s = s . replace(w, '', l) return s
Perform operation to make string empty
65d2460f512ea70058594a3d
[ "Algorithms", "Logic", "Puzzles", "Fundamentals", "Strings", "Performance" ]
https://www.codewars.com/kata/65d2460f512ea70058594a3d
6 kyu
You are given a positive integer *n*. The task is to calculate how many binary numbers without leading zeros (such that their length is *n* and they do *not* contain two zeros in a row) there are. Note that zero itself ("0") *meets* the conditions (for n = 1). For example, there are three eligible binary numbers of length 3: 1) *101* 2) *110* 3) *111* *100 is not suitable.* Remember that *n* may be fairly big (up to 10^4). Good luck!
algorithms
def zeros(n: int) - > int: a, b = 1, 1 for _ in range(n - 2): a, b = a + b, a return a + b
Without two zeros in a row
65cf8417e2b49c2ecd3c3aee
[ "Dynamic Programming" ]
https://www.codewars.com/kata/65cf8417e2b49c2ecd3c3aee
6 kyu
**<center><big>Big thanks to @dfhwze for the approval.</big></center>** *<center>This kata is inspired by @Voile's <a href="https://www.codewars.com/kata/65cdd06eac0d2ad8ee6c6067">One Line Task: Hard Fibonacci Numbers</a>.</center>* # Task Write a function that takes two **non-negative integers** `n` and `k`, and computes the [mathematical combination](https://en.wikipedia.org/wiki/Combination) `$\binom{n}{k}$`. --- # Examples - `$\binom{1}{0} = 1,\ \binom{1}{1} = 1,\ \binom{1}{2} = 0$` - `$\binom{6}{3} = 20,\ \binom{6}{4} = 15,\ \binom{6}{9} = 0$` --- # Note - `$\forall\ n \in \mathbb{N} \cup \{ 0 \} \implies \binom{n}{0} = \binom{n}{n} = 1$`. - `$\forall\ n,k \in \mathbb{N} \cup \{ 0 \} \land k \gt n \implies \binom{n}{k} = 0$`. - **Lines** of your code must **not exceed** `1`. ```if:python - **Length** of your code must **not exceed** `44`. (Record: @monadius's `41` characters) - Disabled modules are `numpy`, `scipy`, `sklearn`, `gmpy2`, `math` and `sys`. - Disabled built-in functions are `open`, `exec`, `eval`, `globals`, `locals` and `exit`. - Credits to @Blind4Basics's module forbidder. ``` --- # Tests - For all tests, `$n,k \in \mathbb{N} \cup \{ 0 \} \land k \lt \max (n+2, 2n)$`. ```if:python - `108` fixed tests, including `6` example tests, `93` mini tests and `9` big tests. - `300` small random tests, `$n \in [100, 200)$`. - `20` big random tests, `$n \in [1100, 1200)$`. - `One Last Test`, `$n \in [4990, 5000) \land k \in \left[\lfloor \frac{49n}{100} \rfloor, \lfloor \frac{51n}{100} \rfloor \right)$`. ``` --- *<center>I hope you enjoy the tests. I had fun writing them. ;)</center>*
games
def comb(n, k): return (b: = 2 << n | 1) * * n >> n * k + k & b - 2
One Line Task: Mathematical Combination
65d06e5ae2b49c47ee3c3fec
[ "Restricted", "Performance", "Mathematics" ]
https://www.codewars.com/kata/65d06e5ae2b49c47ee3c3fec
4 kyu
Laurence is on vacation at the tropics and wants to impress Juliet and her friends by making them the best cocktail he can from the island's bountiful fruits. ## Taste and flavour - Each ingredient has a unique integer **taste** representing its **sweetness** (if positive) or **bitterness** (if negative). - The tastes of the ingredients sum up to the **flavour** of the cocktail. - Cocktails will also have a non-negative integer **bittersweetness**. Each unit of bittersweetness is given by a unit of sweetness in contrast with a unit of bitterness (i.e. it's the *lowest* between the total sweetness and the total bitterness of the ingredients). The same ingredient *may be added multiple times* to the same cocktail. Well balanced drinks are made with exactly **five ingredients**. Use no more and no less for any cocktails you prepare. Repeated ingredients are counted as much as the quantity added. ## Example cocktails ``` TASTE Liquor -4 Vodka -2 FLAVOUR: 2 Mint 1 -----> BITTERSW: 6 Pineapple 3 Watermelon 4 Mormodica -6 Vodka -2 FLAVOUR: -2 Mint 1 -----> BITTERSW: 6 Orange 2 Pineapple 3 ``` ## Input and output Your solution will be called once per cocktail with the following parameters: - The ingredients and their tastes as a dictionary of integers. - The friend's desired flavour as an integer. - The friend's desired bittersweetness as a non-negative integer. Return an array of the ingredients used to make the cocktail. Order is irrelevant. Any answer respecting the criteria is valid. If it's impossible to make the cocktail you should return an empty array. ## Test cases Example test cases should be *enough to confirm your output is correct*. The real test cases will consist of the example test cases plus some randomized **performance tests**. These tests include datasets of size `26^2` and `26^4`. The maximum sweetness/bitterness of ingredients is `26^5`.
algorithms
def find_n(d, t, l): if l == 1: r = d . get(t) return [r] if r else [] for k, v in d . items(): if k >= t: continue r = find_n(d, t - k, l - 1) if r: return r + [v] return [] def make_cocktail(ingr: dict[int], flav: int, bittersw: int) - > list[str]: if not isinstance(ingr, dict): return [] pos = {} min = {} for k, v in ingr . items(): if v < 0: min[- v] = k else: pos[v] = k for i in range(6): f = find_n(pos, bittersw + (flav >= 0 and flav), i) if i else [] m = find_n(min, bittersw - (flav < 0 and flav), 5 - i) if i else [] if len(f) == i and len(m) == 5 - i: return f + m return []
Prepare the Cocktails
65c9562f4e43b28c4c426c93
[ "Algorithms", "Functional Programming", "Performance", "Recursion", "Set Theory" ]
https://www.codewars.com/kata/65c9562f4e43b28c4c426c93
4 kyu
# Task Compute the `n`-th Fibonacci number, where ```math F(0) = 0\newline F(1) = 1\newline F(n) = F(n-1) + F(n-2) ``` . # The Catch 1. Your solution will be tested against all inputs in range `0 - 49`, and `50` inputs in range `50000 - 100000`. 1. The function name to be implemented is `nth_term_of_the_fibonacci_sequence`. 1. Most `import`s have been disabled. 1. Code length must not be longer than `69` characters.
reference
def nth_term_of_the_fibonacci_sequence(n): return pow(m: = 2 << n, n, m * m + ~ m) / / m
One Line Task: Hard Fibonacci Numbers
65cdd06eac0d2ad8ee6c6067
[ "Restricted", "Performance", "Mathematics" ]
https://www.codewars.com/kata/65cdd06eac0d2ad8ee6c6067
3 kyu
Want to play some solitaire? Welcome to 52 card pick up. I always wondered why they never made an online version of the game. So I made one, [try it](https://sagefirellc.net/solitaire/). However, I feel it's time for you to enjoy the pain as well. I have "thrown" your deck of cards into a "pile" (a list with rows of varying length). You need to find all of the cards on the "ground". Problem, they might not all be there and you might find some "garbage" as well. ``` pile = [ ['GB', 'N', 'N', 'N', 'S2', 'SJ', 'SQ', 'N', 'CJ', 'H4', 'N', 'N', 'GB'], ['S3', 'N', 'S4', 'D4', 'N', 'D2', 'N', 'N', 'C2', 'N'], ['N', 'D7', 'N', 'C9', 'N', 'N', 'S1', 'C8', 'D3'], ['N', 'N', 'HQ', 'N', 'N', 'N', 'H6', 'N', 'H3', 'S9', 'N'], ['D9', 'CK', 'H5', 'D6', 'D8', 'N', 'N', 'N', 'N', 'C4'], ['N', 'N', 'H8', 'N', 'N', 'N', 'C5', 'D5', 'C7', 'H2'], ['N', 'N', 'N', 'HJ', 'S7', 'S6', 'C10', 'S10', 'N', 'H9'], ['H7', 'N', 'N', 'S5', 'N', 'HK', 'C1', 'N', 'D1', 'C6'], ['SK', 'N', 'N', 'N', 'N', 'C3', 'N', 'DK', 'N', "Na", 'N'], ['DQ', 'DJ', 'S8', 'CQ', 'N', 'D10', 'N', 'H1', 'N', 'H10', 'N', 'H1a'] ] ``` Cards are represented by the first letter of their suit and then either the number or the first letter of the royalty. Examples, Queen of Hearts = HQ, Queen of Spades = SQ, Queen of Diamonds = DQ, Queen of Clubs = CQ, Ace of Hearts = H1, 2 of Hearts = H2, and so on and so on. Rules: - Empty space on the "ground" is indicated with a 'N' and should be ignored. - All real cards will be uppercase. - There may be multiple of the same card, ignore the extras. - Ignore "garbage" (GB/Na) and "fake" cards (S3 is a real card S3a is not). - Aces value are 1. You need to determine if the pile on the "ground" has all of the cards in deck. If it does, return True, else, return False. Reminder, there can be "fake" and extra cards. You just need to determine if there is one complete decks worth of cards on the "ground".
games
A = {x + y for y in "1 2 3 4 5 6 7 8 9 10 J Q K" . split() for x in "HSDC"} def pick_em_up(pile): p = {y for x in pile for y in x} return all(c in p for c in A)
52 Card Pick Up
65cb9ddfac0d2a5d6e6c6150
[ "Puzzles" ]
https://www.codewars.com/kata/65cb9ddfac0d2a5d6e6c6150
6 kyu
# Task You are given a **target word** and a **collection of strings**. Your task is to **count in how many ways you can build up a target word from the strings in the collection.** You can use any string in the collection _**as many times**_ as needed, but you need to use that string **as it is** (meaning you can't remove characters from it). Either use all of it or don't use it. If it doesn't fully match your needs, see if another string in the collection does. # Examples 1. For target word `"example"` and collection of words `["exa", "exam", "ple"]` there is just `1` option of how you can use the strings in the collection to create the word `"example"`: taking strings `"exam"` and `"ple"`. So you should return `1` for this case. 2. For target word `"example"` and collection of words `["exa", "exam", "ple", "mple"]` we now have `2` options: - `"exa"` + `"mple"` - `"exam"` + `"ple"` So you should return `2` for this case. 3. For target word `"example"` and collection of words `["exa", "ple"]` we **cannot** construct the target word. So you should return `0` for this case. # Input For input, you will receive: 1. **`target`** - target word as a string ```if-not:python 2. **`arr`** - an array of unique strings ``` ```if:python 2. **`words`** - a `tuple` of unique strings ``` All strings will be lowercase. All inputs are valid. # Output You should return the number of ways you can build up a target word from the strings in the given collection. - Return `0` if this is **impossible**. - Return `1` if the target is an **empty string**. # Tests Total number of tests is `300`. You need to come up with an efficient approach so your solution doesn't time out. #### Good luck!
reference
def get_options_count(target, arr): options = [1] for n in range(1, len(target) + 1): options . append(sum(options[- len(s)] for s in arr if target[- n:]. startswith(s))) return options[- 1]
Number of options to build up a word
65cb0451ac0d2a381c6c617f
[ "Dynamic Programming" ]
https://www.codewars.com/kata/65cb0451ac0d2a381c6c617f
5 kyu
# Background This exercise assumes basic knowledge of generators, including passing familiarity with the `yield` keyword. ## Catching You Up on Generators While it is obvious that you can obtain items from generators, it is less known that you can also **send** data into generators in languages like Python and JavaScript. We are going to explore the very basics of that today. First, we need to establish a couple of concepts: ~~~if:python 1. [**Sending**](https://docs.python.org/3/reference/expressions.html#generator.send): To send something to a generator, you call the `.send` method on it. It’s a general form of `next`. In fact, `next(generator)` is the same as `generator.send(None)`. Both functions allow you to access the next item of the generator, but `.send` also lets you send a non-`None` message. ```python yielded_value = my_generator.send('howdy from the outside world!') ``` 2. [**Receiving**](https://docs.python.org/3/reference/expressions.html#yield-expressions): By assigning the yield expression to a variable, you are able to access whatever was _**sent to**_ the generator. So, the following line inside a generator ```python msg = yield 5 ``` yields 5, pauses the generator, and gives control back to the caller. If the caller sends a msg (or calls `next`, which sends a `None` message), the generator stores that in `msg` and resumes until it yields another element. 3. **Priming a Generator**: You can only send a message to a generator if you had primed it by calling `next` (or `.send(None)`) on it first. This is to ensure the generator actually gets to the part of its body that yields. ~~~ ~~~if:javascript 1. [**Sending**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next): To send something to a generator, you call the `.next` method on it with an argument - this argument will be the message. It hence follows that calling `.next()` with no arguments sends the generator a message of `undefined`. ```javascript const yieldedValue = myGenerator.next('howdy from the outside world!').value ``` 2. [**Receiving**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield): By assigning the yield expression to a variable, you are able to access whatever was _**sent to**_ the generator. So, the following line inside a generator ```javascript const msg = yield 5 ``` yields 5, pauses the generator, and gives control back to the caller. If the caller sends a msg (or calls `next()` without arguments, which sends a message of `undefined`), the generator stores that in the variable `msg`, does what it needs to do with this, and resumes until it yields another element. 3. **Priming a Generator**: To be able to send a message to a generator, you must have consumed at least one element from it (i.e., called `next` on it at some point previously). This is to ensure the generator actually gets to the part of its body that yields. ~~~ --- Since this an introductory Kata, you may want to look at a sample example that puts all these concepts together: <details> <summary> View example </summary> Here’s a generator that infinitely repeats the last message sent to it. ```python def echo_echo(): thing_to_repeat = None # Initialize. while True: new_thing = yield thing_to_repeat # If the user actually sent something instead of just calling next. if new_thing is not None: thing_to_repeat = new_thing # Else, it means the user just called next, so keep repeating the old thing. # Usage echo = echo_echo() next(echo) # As previously discussed, this first call to next is mandatory before sending. print('Setting echo to ', echo.send('hi')) # Prints 'Setting echo to hi'. for i in range(5): print(next(echo)) # Prints 'hi' 5 times. print('Setting echo to ', echo.send('bye')) # Prints 'Setting echo to bye'. for i in range(5): print(next(echo)) # Prints 'bye' 5 times. ``` ```javascript function* echoEcho() { let thingToRepeat = null while (true) { const newThing = yield thingToRepeat // If the user actually sent something with next, instead of no-args which just sends undefined. if (newThing !== undefined) thingToRepeat = newThing // Else, it means the user just called next with no message, so keep repeating the old thing. } } const echo = echoEcho() echo.next() // As previously discussed, this first call to next is needed before sending. console.log('Setting echo to', echo.next('hi').value) // Prints 'Setting echo to hi' console.log(echo.next().value) // Prints 'hi'. console.log(echo.next().value) // Prints 'hi'. // ... console.log('Setting echo to', echo.next('bye').value) // Prints 'Setting echo to bye' console.log(echo.next().value) // Prints 'bye'. console.log(echo.next().value) // Prints 'bye'. // ... ``` </details> --- # Task Imagine you run a very tiny production line with two "worker" generators, `gen1` and `gen2`, that generate data for you. Your task is to create a new generator function, `round_robin` (or `roundRobin` in JS), that will allow you to collect items from these two generators in a round-robin fashion. ```python def round_robin(gen1, gen2): # ... ``` ```javascript function* roundRobin(gen1, gen2) { // ... } ``` The term “round-robin” is often used to describe a process where participants take turns in a cyclic order. In this case, your generator function should yield one item from `gen1`, then one item from `gen2`, then one item again from `gen1` and so forth, continuing this alternating pattern. ~~~if:python Moreover, you may want to provide feedback to these generators based on their output. Your `round_robin` generator should be open to being sent messages by calling the `.send()` method on it. When `round_robin` receives a message, it should forward this message to the next generator in the sequence. For example, if `round_robin` has just yielded an item from `gen2`, and you send a message to `round_robin`, that message should internally be forwarded directly to `gen1`. Here is sample usage: ```python factory = round_robin(gen1, gen2) print(next(factory)) # Yields one item from gen1. print(next(factory)) # Yields one item from gen2. print(next(factory)) # Yields one item from gen1. print(factory.send(32)) # Yields one item from gen2 after sending 32 to it. print(factory.send(6)) # Yields one item from gen1 after sending 6 to it. ``` Note that `.send`, like `next`, consumes one element. It's easy to accidentally miss out this item, so don't. ~~~ ~~~if:javascript Moreover, you may want to provide feedback to these generators based on their output. Your `roundRobin` generator should be open to being sent messages by calling the `next` method on it with a potential argument. When `roundRobin` receives a message, it should forward this message to the next generator in the sequence. For example, if `roundRobin` has just yielded an item from `gen2`, and you send a message to `roundRobin`, that message should internally be forwarded directly to `gen1`. ```javascript const factory = roundRobin(gen1, gen2) console.log(factory.next().value) // Yields one item from gen1. console.log(factory.next().value) // Yields one item from gen2. console.log(factory.next().value) // Yields one item from gen1. console.log(factory.next(32).value) // Yields one item from gen2 after sending 32 to it. console.log(factory.next(6).value) // Yields one item from gen1 after sending 6 to it. ``` Note that calling `next` with a message consumes one element (just like `next` without arguments). It may be easy to accidentally miss out this item, so don't. The generators provided to your function will use `undefined` as the sentinel value, not `null`. Beware! ~~~ # Assumptions - You do **NOT** need to worry about priming the generators before sending. By the time you need to send messages to the generators, the testing process will have ensured that the generators are already in a state where they are ready to receive. - Both generators are infinite - neither of them gets exhausted, so you don't need to handle that. - In the random tests, the generators that will be fed into your function will exclusively be among a pool of four generators I wrote. This is to make debugging easier and more sane from your side. <details> <summary> View provided generators </summary> 1. **`count_up`** or **`countUp`** _(also included in the fixed tests)_: Infinitely counts up from whatever number sent to it (or 0 by default). For example, if you send `3` to it, it will yield back `3 4 5 6 7 8 9 ...`. 2. **`gen_multiples`** or **`genMultiples`**: Infinitely yields from the multiplication table of the number sent to it (0's table, by default). For example, if you send `3` to it, it will yield back `0 3 6 9 12 15 ...`. 3. **`split_string`** or **`splitString`** _(also included in the fixed tests)_: Infinitely yields characters from a string sent to it, and loops back when finished. If sent nothing, loops `''`. For example, if you send `'hey'` to it, it will yield back `'h' 'e' 'y' 'h' 'e' 'y' ...`. 4. **`repeat_string`** or **`repeatString`**: Infinitely repeats a string sent to it. For example, if you send `'hey'` to it, it will yield back `'hey' 'hey' 'hey' 'hey' ...`. </details>
reference
from itertools import cycle def round_robin(* gens): msg = None for gen in cycle(gens): msg = yield gen . send(msg)
Sending Data into Generators: The Basics
65c8e72d63fd290058026075
[ "Fundamentals", "Language Features" ]
https://www.codewars.com/kata/65c8e72d63fd290058026075
6 kyu
A digital, 24-hour clock is hung on my classrooms wall, displaying, well, the time in `hh:mm:ss` format. There are multiple types of `good times`. It could be if ... 1. `[hh, mm, ss]` is an arithmetic progression where the difference of consecutive numbers is 0, 1, or 2. e.g. `(11:12:13, 13:15:17)` but NOT `23:21:19` 2. `[hh, mm, ss]` is an arithmetic progression where the numbers end with the same last digit. e.g. `(00:20:40, 23:13:03)` 3. `[0, hh, mm, ss]` is an arithmetic progression 3. `hhmmss` is a palindrome and only two types of digits are in the time. e.g. `(11:55:11, 05:55:50)` 4. the time is `12:34:56` Task is to return the `next good time`, excluding the current time. Note that time can loop to the next day. Examples: ``` 00:00:00 -> 00:01:02 (1) 10:59:23 -> 11:00:11 (4) 09:18:27 -> 09:19:29 (2) 23:52:18 -> 00:00:00 (1,2,3) 08:10:12 -> 08:16:24 (3) 12:33:56 -> 12:34:56 (4) ```
reference
import datetime def next_good_time(current_time): d = datetime . datetime . strptime(current_time, "%H:%M:%S") while True: d += datetime . timedelta(seconds=1) if any([ d . minute * 2 == d . hour + d . second and d . minute - d . hour in [1, 2], d . minute * 2 == d . hour + d . second and d . minute % 10 == d . hour % 10, d . minute * 2 == d . hour + d . second and 2 * d . hour == d . minute, d . time(). isoformat() == d . time(). isoformat()[ :: - 1] and len(set(d . time(). isoformat())) == 3, d . time(). isoformat() == "12:34:56", ]): return d . time(). isoformat()
Next good time
65c6fa8551327e0ac12a191d
[]
https://www.codewars.com/kata/65c6fa8551327e0ac12a191d
6 kyu
# Task Imagine you have a 3D matrix with the size given as 3 integers: width, depth, height (x,y,z). You start at a corner point `(1,1,1)` and in each step you can move just in one direction: * x -> x+1 * or y -> y+1 * or z -> z+1. You **can not** go diagonally or backwards. Your task is to calculate in **how many ways** you can go from point `(1,1,1)` to the point `(x,y,z)`. ## Example For a simple example we can check a flat matrix with size: `width=3`, `depth=3`, `height=1`. <div> <div style="display: flex; justify-content: center;"> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; background-color: green; " > <span style="margin: auto">1</span> </div> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; " > <span style="margin: auto">1</span> </div> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; " > <span style="margin: auto">1</span> </div> </div> <div style="display: flex; justify-content: center;"> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; " > <span style="margin: auto">1</span> </div> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; background-color: darkorange; " > <span style="margin: auto">2</span> </div> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; background-color: blue; " > <span style="margin: auto">3</span> </div> </div> <div style="display: flex; justify-content: center;"> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; " > <span style="margin: auto">1</span> </div> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; background-color: blue; " > <span style="margin: auto">3</span> </div> <div style=" border: 1px solid grey; height: 30px; width: 30px; display: flex; background-color: red; " > <span style="margin: auto">6</span> </div> </div> </div> 1. We start at the <span style="color:green">green top left cell</span>.</br> 2. To get to the <span style="color:darkorange">orange cell</span> we have 2 possible ways: go from top or from left.</br> 3. To get to <span style="color:blue">blue cells</span> we have 3 possible ways: go from cell with 1 or from cell with 2 options which gives 3 possible options in total.</br> 4. And finally to get to the <span style="color:red">red cell</span> we have 6 possible options for how we can get there.</br> But our matrix will not always have height of 1. ## Input * As input you will receive `3` integers `(x,y,z)` from `1` to `100`, which describes the size of the matrix: width, depth, height. * All inputs will be valid. ## Output * As output you should return the number of ways you can go from the starting point `(1,1,1)` to the opposite point `(x,y,z)`. * Output should be returned as a **BigInt** number for Javascript and a regular **int** for Python. ## **Good luck!**
reference
from itertools import accumulate def ways_in_3d_matrix(x, y, z): x, y, z = sorted((x, y, z)) layer = [[int(j == 0 or k == 0) for k in range(z)] for j in range(y)] for j in range(1, y): for k in range(1, z): layer[j][k] = layer[j - 1][k] + layer[j][k - 1] seq = [1] * (y + z - 1) for _ in range(x - 1): seq = [* accumulate(seq)] return layer[- 1][- 1] * seq[- 1]
Number of ways to go in 3D matrix
65c6836293e1c2b881e67f33
[ "Dynamic Programming" ]
https://www.codewars.com/kata/65c6836293e1c2b881e67f33
6 kyu
*Inspired by https://www.youtube.com/watch?v=eW_bMqcJXv0/* You are speedrunning a game with `N` successive levels. For each level `i = 1,...,N`, you have a target time `t_i` based on the "strats" you're going for, and a success probability `p_i` of achieving the respective target time (i.e., pulling off the strats). (More precisely, the times `t_i` are the target *durations* of each level, not the "split" times. For example, if `t_1 = 30` and `t_2 = 20`, you aim to finish level 1 in 30 seconds and level 2 in 20 seconds, i.e., you aim to finish level 2 at the 50-second mark from the start.) The target time of each level is strict. You will either finish the level in exact time `t_i` (with probability `p_i`) or fail the level (with probability `1 - p_i`). If you finish the level successfully, you move on to the next level if `i < N` or beat the game if `i = N`. If you fail the level, *the failure occurs at the midpoint of the level in expectation*, and you restart from level `1`. Taking into account all failures and restarts, how long will it take you to complete all `N` levels in their target times from start to finish, in expectation? In other words, how long will it take you to complete your speedrunning goal, in expectation? # Input Your solution function `expected_speedrun_time` receives two arguments: `times` and `probs`. Argument `times` is a list of `N` elements corresponding to the level target times `t_i`, in seconds. Argument `probs` is a list of `N` elements corresponding to the level success probabilities `p_i`. # Output The expected time in seconds until you complete all levels within their target times from start to finish, taking into account all failures and restarts. # Example From the above video, Niftski's new SMB1 world record consists of `N = 8` levels with target times `times = [29.35, 33.60, 34.56, 28.64, 50.75, 35.67, 34.95, 47.12]` and estimated success probabilities `probs = [0.80, 0.70, 0.85, 0.05, 0.50, 0.35, 0.80, 0.80]`. The correct answer is about `28431.47` seconds, or just under eight hours, which is roughly as long as it took for Niftski to achieve the record.
reference
def expected_speedrun_time(times, probs): tot_prob, tot_time, expected = 1, 0, 0 for t, p in zip(times, probs): expected += (tot_time + t / 2) * (tot_prob) * (1 - p) tot_time += t tot_prob *= p expected /= tot_prob expected += tot_time return expected
Speedrunning: Expected time until completion
65c06522275fa5b2169e9998
[ "Mathematics", "Probability", "Statistics" ]
https://www.codewars.com/kata/65c06522275fa5b2169e9998
6 kyu
You are given two integers `x` and `y`, each an integer from `0` through `9`. You want to get from `x` to `y` by adding an integer `z` to `x`. Addition will be modulo 10, i.e., adding `1` to `9` results in `0`; and adding a `-1` to `0` results in `9`. Create a function `f` that, given the `x` and `y` defined above, returns the `z` such that its absolute value `|z|` is the smallest. If the answer is ambiguous, return the negative `z`. Examples: ```javascript f(1,3) == 2 f(5,2) == -3 f(7,2) == -5 f(9,1) == 2 f(1,9) == -2 ``` ```if:javascript Code length limit: no more than 22 characters. ``` ```if:python Code length limit: no more than 25 characters. ```
reference
def f(x, y): return (y - x + 5) % 10 - 5
[Code Golf] Rotate The Dial
6590b70c3109bcf9c12624a5
[ "Mathematics", "Restricted" ]
https://www.codewars.com/kata/6590b70c3109bcf9c12624a5
6 kyu
Note: Based off Minecraft, hopefully you at least know the game! Story: You want to create a giant mine shaft, but you're a little stingy with your iron and diamonds and would not mine out all of the stone with iron or diamond pickaxes. Instead, you rely on less durable but cheaper stone pickaxes! You will need a lot of stone pickaxes though as they break faster than diamond or iron ones, so you need to find out how many stone pickaxes you can craft before you run out of sticks and cobblestones. Unfortunately, you're not an organized person, and you leave all of your materials in a single chest with random junk that you need to filter. Task: Given an array, return the maximum amount of stone pickaxes you can craft before you run out of sticks and cobblestones. Within the array would be a series of strings with the exact names of the materials listed below. A single stone pickaxe is made of 3 "Cobblestone" and 2 "Sticks", check if your given array contains enough "Sticks" and "Cobblestone" to craft a single stone pickaxe or even more. Do not count any materials apart from "Cobblestones", "Sticks" and "Wood". Wood can be converted into 4 sticks! Here are the materials you would expect in an array: ``` Sticks Cobblestone Stone (These are different from cobblestone and cannot be used to make a stone pickaxe.) Wool Dirt Wood (Can be treated as sticks, typically 4 sticks for 1 wood) Diamond ``` Array sizes are randomized and range from 1 - 200 with randomized contents. Examples: ``` Array: ["Sticks", "Sticks", "Cobblestone", "Cobblestone", "Cobblestone"] Returned: 1 Array: ["Wood", "Cobblestone", "Cobblestone", "Cobblestone"] Returned: 1 Array: [] Returned: 0 Array: ["Sticks", "Wool", "Cobblestone"] Returned: 0 Array: ["Cobblestone", "Cobblestone", "Cobblestone", "Cobblestone", "Cobblestone", "Cobblestone", "Wood"] Returned: 2 ``` Good Luck :D Made by miggycoder, this is my first kata I ever created.
reference
def stone_pick(arr): stick = arr . count('Sticks') + arr . count('Wood') * 4 cobble = arr . count('Cobblestone') return (min(cobble / / 3, stick / / 2))
Stone Pickaxe Crafting
65c0161a2380ae78052e5731
[ "Fundamentals" ]
https://www.codewars.com/kata/65c0161a2380ae78052e5731
7 kyu
## Theoretical Material You are given two vectors starting from the origin (x=0, y=0) with coordinates (x1,y1) and (x2,y2). Your task is to find out if these vectors are collinear. Collinear vectors are vectors that lie on the same straight line. They can be directed in the same or opposite directions. One vector can be obtained from another by multiplying it by a certain number. In terms of coordinates, vectors (x1, y1) and (x2, y2) are collinear if (x1, y1) = (k\*x2, k\*y2) , where k is any number acting as a coefficient. <img src=https://d138zd1ktt9iqe.cloudfront.net/media/seo_landing_files/collinear-vectors-1627481628.png style="background:rgba(255,255,255,0.85)"/> For more information, check out this [article on collinearity](https://www.cuemath.com/geometry/collinear-vectors/). ## Problem Description Write the function `collinearity(x1, y1, x2, y2)`, which returns a Boolean type depending on whether the vectors are collinear or not. ``` all coordinates are integers -1000 <= any coordinate <= 1000 ``` ## Notes - All vectors start from the origin (x=0, y=0). - Be careful when handling cases where x1, x2, y1, or y2 are zero to avoid division by zero errors. - A vector with coordinates (0, 0) is collinear to all vectors. ## Examples ``` (1,1,1,1) ➞ true (1,2,2,4) ➞ true (1,1,6,1) ➞ false (1,2,-1,-2) ➞ true (1,2,1,-2) ➞ false (4,0,11,0) ➞ true (0,1,6,0) ➞ false (4,4,0,4) ➞ false (0,0,0,0) ➞ true (0,0,1,0) ➞ true (5,7,0,0) ➞ true ```
reference
def collinearity(x1, y1, x2, y2): return x1 * y2 == x2 * y1
Collinearity
65ba420888906c1f86e1e680
[ "Fundamentals", "Geometry", "Mathematics", "Data Science", "Games" ]
https://www.codewars.com/kata/65ba420888906c1f86e1e680
8 kyu
## The Challenge > This kata is inspired by one of Shortcat's (*Mario Kart* YouTuber) most recent videos. If anyone's interested, here's the [video](https://www.youtube.com/watch?v=BKSG9NieybE). **Boot up** whichever your latest *Nintendo* console was, be it the *Wii* for the OG's or *Switch* for the bourgois! We're doing a *Mario Kart* challenge. > Get all of `1st` to `12th` placements, in **any order** and **without repetition**, in `12` consecutive Mario Kart races. The **interesting** part of this ordeal is that, should one **blunder** and get a repeated position, not all placements will be lost, but merely the ones previous to the last instance of that same placement. For example, should we be in a **streak** of `1st`, `7th`, `5th`, `4th`, and `11th` and get `7th` again, there's no need to start over, as we can pick up from `5th` and begin a new streak of `5th`, `4th`, `11th`, and `7th`, losing only `1st` (and technically `7th`, which is instantly regained). ## Task The **task** is a mere extension of the Mario Kart challenge, **extrapolated** to more **possibilities of placements**. Thus, reading *The Challenge* is actually **important** for understanding the *Task*, so please do. I kept it **brief** for this reason. Given an **ordered** `Iterator` (**finite** or **infinite**) of **positive integers**, representing the **placements** achieved in various consecutive races, and a **positive integer**, representing the **total** number of possible placements `[1, 2, ..., total]`, return the **index** of the **last race** of the **first instance** of a **win**. #### Notes - Placements will **always** be **between** `1` and `total` (inclusive), where `total` is the total number of placements. - Indexation starts at `0`. - If **no win** is achieved, return `None`. - If **multiple wins** are achieved, consider only the **first one**. - **Infinite** iterables will **always** have a win. ~~~if:python ### Helper Function Due to the **infinite** nature of some iterators, the **logs** they produce tend to not be super helpful, as their **type** and **memory location** don't help much with deciphering the problem. For this reason, a **helper function** has been implemented in the **preloaded** section, which takes an `Iterable` and **returns** its first `n` (second **argument** set to `100` by default), **or less** if there aren't enough, elements. You can then **print** these to the **console** or do whatever helps you. ~~~ ### Performance The tests are designed around `O(n)` solutions; these **shouldn't have trouble passing**. `O(nlogn)` and `O(nloglogn)` solutions, if you can **somehow** come up with them, **may** pass as well. There's very little tolerance for `O(n ^ 2)` and `O(n * total)` solutions; thus, these are **very unlikely to pass**. ``` - Random Tests: 60 Tests - Maximum "win" index: 200_000 - Maximum "total" (placements): 2000 ``` ## Examples ``` ([1, 2, 3], 3) ==> 2 ([2, 1, 2], 3) ==> None ([1, 2, 2, 3, 4, 1, 2], 4) ==> 5 # [2, 3, 4, 1] happens before [3, 4, 1, 2]. ([2, 1, 2, 1, 2, 1, ...], 2) ==> 1 # Though infinite, a win can be detected. ([1, 7, 5, 4, 11, 7, 2, 8, 7, 9, 3, 8, 2, 10, 1, 4, 6, 11, 12, 5], 12) ==> 19 ```
algorithms
from collections import deque def find_win(placements, total): c, t, q = 0, ((1 << total) - 1) << 1, deque(maxlen=total) for i, v in enumerate(placements): c += 1 << v if i >= total: c -= 1 << q[0] if c == t: return i q . append(v)
N in a row
65b745d697eea38e8bcfb470
[ "Iterators", "Performance" ]
https://www.codewars.com/kata/65b745d697eea38e8bcfb470
6 kyu
Write a function `cube_matrix_sum` that calculates the sum of the elements of a 3-dimensional array. The function should be one line long and less than 48 characters long. Imports are prohibited Example ``` cube_matrix = [ [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10,11,12],[13,14,15],[16,17,18]], [[19,20,21],[22,23,24],[25,26,27]] ] cube_matrix_sum(cube_matrix) == 378 ``` All elements of an array of type int or float. There may be negative elements. This is my first kata and I hope you'll enjoy it :). Best of luck!
algorithms
def cube_matrix_sum(x): return sum(sum(sum(x, []), []))
One Line Task: The sum of a 3-dimensional array
65b3fdc2df771d0010b9c3d0
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/65b3fdc2df771d0010b9c3d0
6 kyu
## Introduction It's **Christmas** (a bit late, I know), and you finally decide to do something nice for once in your life. As you're going to meet up with your family, you think to give them a little something, and what's a better gift than **money**? I mean, it's kind of hard to find something that both a **geriatric** and **tiktok child** would enjoy. However, there's a little **problem**: you don't remember **how many people** there are in the family anymore. Among so much **breeding** and **unaliving**, it's just impossible to keep track of the **exact count**. Also, who knows if that **8th degree** cousin will show up—is that even family anymore? Well, you're at least sure of one thing. There will be, **at max**, `n` people at the gathering (excluding you). God only knows how you came up with that **upper bound**, but you did. Now, you must be sure that **everyone receives the same** amount of money; politics brings about enough discussion already. Furthermore, **no money can be left over**; they would notice and call you **greedy**. Thus, you decide to bring the smallest amount of **one dollar bills**, such that **no matter how many people** show up, within your estimated range, **everyone gets the same** and **no money is left over**. ## Task Given a positive integer `n`, return the **smallest possible integer**, such that it is a multiple of all numbers from `1` to `n`, both **inclusive**. As the results tend to get **very big**, return your answer **modulus** `1_000_000_007`, i.e., `answer % 1_000_000_007`. ## Performance The performance requirements are **relatively high** for this one, so just taking the **lowest common multiple** from `1` to `n`, **won't work**. On the random tests: ```python - Random Tests: 100 tests - Integer Size: 1 to 3_000_000 ``` ```haskell - Random Tests: 100 tests - Integer Size: 1 to 3_000_000 ``` ```scala - Random tests: 150 tests - Integer Size: 1 to 3_000_000 ``` ```javascript - Random Tests: 100 tests - Integer Size: 1 to 9_000_000 ``` ## Examples ```javascript 1 -> 1 2 -> 2 6 -> 60 10 -> 2_520 20 -> 232_792_560 81 -> 853_087_536 243 -> 309_031_427 ```
algorithms
from gmpy2 import is_prime M, L = 1000000007, 3000000 PRIMES = [n for n in range(L) if is_prime(n)] def smallest_multiple(n): t = 1 for p in PRIMES: if p > n: break for q in range(1, n + 1): if p * * q > n: t = (t * pow(p, q - 1, M)) % M break return t
Smallest Multiple of 1 to n
65ad9094c5a34200245f3a8f
[ "Mathematics", "Performance", "Number Theory" ]
https://www.codewars.com/kata/65ad9094c5a34200245f3a8f
5 kyu
# Balanced? Usually when we talk about converting between bases, we assume that the value assigned to the *characters* within the base are always the same; '3' in base 7 is the same as '3' in base 16. However, we could just as easily pick a different selection of values. So, in balanced base nine, the characters will be as follows: - 0-4 will map onto 0-4 as you would expect - £, $, %, ^ will map onto -1, -2, -3, and -4 respectively This leads to some interesting conversions. For example, `6 = 1%` because it is equal to `9 - 3`. Notice that all negative numbers can be represented without a negative sign as well. ## The Goal You must program a function that takes in a number and converts it to a string representing its *balanced base nine* form. For example, the number `26` as an input should return `3£`, and `-14` should return `$4`. Of course, your algorithm will have to cope with much bigger numbers. ~~~if:javascript For JS, input numbers will be `BigInt`s, to cope with values up to `10**120`. ( If operations on negative numbers do not give the results you expect, please consult documentation. ) ~~~
algorithms
def balanced_base_nine(num): base_nine = [] while num: d = num % 9 base_nine . append('01234^%$£' [d]) num = num / / 9 + (d > 4) return '' . join(reversed(base_nine)) or '0'
Base Nine But Balanced
65a1cc718041f7000f928457
[ "Mathematics" ]
https://www.codewars.com/kata/65a1cc718041f7000f928457
6 kyu
## Description Three-cushion billiards, also called three-cushion carom, is a form of carom billiards. The object of the game is to carom the cue ball off both object balls while contacting the rail cushions at least three times before contacting the second object ball. - The table consists of 4 cushions (north, east, south and west) - There are 3 balls (white, yellow, red) - The cue ball is the ball that the player starts with (white and yellow are allowed to be picked) - The object balls are the 2 remaining balls that the player did not pick to start with (red is always one of these balls) - <a href="https://en.wikipedia.org/wiki/Three-cushion_billiards">wiki link</a> #### The billiards table ``` n +----------------+ | | | | | R | | | w | | e | | | | | | | W Y | | | +----------------+ s ``` --- ## Task Given an encoded string representing the collisions of the cue ball with object balls and cushions, return a boolean indicating whether a point was scored. You may assert the player hits a valid cue ball (white or yellow). #### Input The input consists of a combination of zero, one or more occurences of the following chars: - <code>'w', 'e', 'n', 's'</code> - west, east, north and south cushion - <code>'W', 'Y', 'R'</code> - white, yellow and red ball #### Output - return a boolean indicating whether a point is scored #### Conditions to score a point - The cue ball must have made contact with the cushions at least three times before contacting the second object ball for the first time. - Both object balls must be hit at least once. #### Additional info - The cue ball may contact the cushions before or after hitting the first object ball. - The cue ball does not have to contact three different cushions as long as it has been in contact with any cushion at least three times in total. - Using a specific technique (a massé shot), it is possible to hit the same cushion multiple times in succession, curving the cue ball. - It is allowed that both object balls collide a number of times, this is not encoded in the input and can be ignored altogether ---- ### Examples #### Scoring a point ``` input description ------------------------------------------------------------------------------ "YnesR" white ball is cue ball, first hits yellow ball, then 3 cushions, finally red ball "RnesY" white ball is cue ball, first hits red ball, then 3 cushions, finally yellow ball "WnesR" yellow ball is cue ball, first hits white ball, then 3 cushions, finally red ball "wWnsR" yellow ball is cue ball, first hits a cushion, then white ball, 2 more cushions, finally red ball "wnWsR" yellow ball is cue ball, first hits 2 cushions, then white ball, 1 more cushion, finally red ball "wnsWR" yellow ball is cue ball, first hits 3 cushions, then white ball, finally red ball "YneswR" white ball is cue ball, first hits yellow ball, then 4 cushions, finally red ball "YnesRs" white ball is cue ball, first hits yellow ball, then 3 cushions, then red ball, finally another cushion "YnesYR" white ball is cue ball, first hits yellow ball, then 3 cushions, then yellow ball again, finally red ball "wnwYR" white ball is cue ball, first hits 3 cushions (one cushion twice), then white ball, finally red ball "wwwYR" white ball is cue ball, first hits 3 cushions (one cushion trice), then white ball, finally red ball ``` #### No score ``` input description ------------------------------------------------------------------------------ "YneRw" there are only 2 cushions hit before hitting the second object ball (red) "wYnwY" the yellow ball is hit twice, but the red ball was not hit "neR" only the red ball was hit, no other object ball "" a total miscue, causing no collisions after hitting the cue ball "YRnnenRY" more than 3 cushions were hit, but not before hitting the second object ball for the first time (red) "eRWewsnW" more than 3 cushions were hit, but not before hitting the second object ball for the first time (white) ``` --- Good luck, have fun
reference
def has_scored(s): balls = sorted(s . find(b) for b in 'RWY') return balls[1] >= 0 and sum(c in 'nesw' for c in s[: balls[2]]) >= 3
Three-cushion billiards
65a024af6063fb0ac8c0f0b5
[ "Fundamentals", "Games" ]
https://www.codewars.com/kata/65a024af6063fb0ac8c0f0b5
7 kyu
### Problem Statement You're given a string of digits representing a sequence of consecutive natural numbers concatenated together. Your task is to find the smallest possible first number in the sequence. The sequence starts with a single or multi-digit number and continues with numbers each incremented by 1. If multiple sequences can be formed, choose the one that starts with the smallest number. ### Examples - "123" -> [1, 2, 3] -> 1 - "91011" -> [9, 10, 11] -> 9 - "17181920" -> [17, 18, 19, 20] -> 17 - "9899100" -> [98, 99, 100] -> 98 - "91" -> [91] -> 91 - "121122123" -> [121, 122, 123] -> 121 - "1235" -> [1235] -> 1235 - "101" -> [101] -> 101 ### Constraints - Input string length: 1 - 200 characters. - Smallest possible first number: 1 - 1,000,000,000. Remember, the key is to form a sequence of **consecutive natural numbers**. If the sequence matches the input string, you've found the smallest possible first number. Experiment with different lengths for the first number until you find a match or exhaust all possibilities. ~~~if:lambdacalc ### Encodings The input sequence will be encoded as a `List` of single digit `Number`s ( but shown in test failure messages as a `String` ); the output number must be encoded as a `List` of single digit `Number`s ( but shown in test failure messages as a `Number` ). purity: `LetRec` numEncoding: `Scott` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding. ~~~
algorithms
def find(string): num = int(string[0]) ans = num i = 1 test = str(num) while test != string: if test == string[: len(test)]: num += 1 test += str(num) else: i += 1 num = int(string[: i]) ans = num test = str(num) return ans
The lost beginning
659af96994b858db10e1675f
[ "Fundamentals", "Algorithms", "Strings", "Mathematics" ]
https://www.codewars.com/kata/659af96994b858db10e1675f
6 kyu
## Introduction It's finally the day for the *314th* edition of the **International Integer Sequences Olimpiad**, where various sequences of integers compete for the number one spot by trying to reach the **highest score**. However, the **old scoring system** of merely **adding up the numbers** for the score has been heavily criticized in the past edition due to a **boring sequence** such as the first 100 **powers of 2** beating the previous champion, the first 100 terms of the **Fibonacci Sequence**. Thus, the scoring committee decided to implement a **new scoring system**, that abides by the following rule: Each list's score is equal to the **sum of the mapping of product to each and every pair of integers that can be formed from its numbers** (more on *Task*). Funnily enough, this new system **doesn't solve the original problem** at all. Well, it's good enough to distract the masses, which you'd expect to have a better grasp of mathematics, given the target demographic. You, as the competition organizer, are tasked with creating an **algorithm for scoring** the lists. However, it must be **quick**; we can't spend all day on a single list after all. ## Task Consider a `list` of `integers` of size `n`. Take all the `nCr(n, 2) == n * (n - 1) / 2` possible **pairs of integers** that can be formed from the list. Map each of them to their **product**, i.e., `(a, b) -> a * b` and **return their sum**. This is the list's **score**, you're tasked with creating an efficient algorithm to return this value. We are not taking **repetition** into account, so **equal pairs may be considered more than once**; see *Examples*. Given a list of size `0` or `1`, return `0` as **no pairs can be formed**. #### Performance The performance requirements are **relatively high** for this one, thus going over each and **every pair** will **not work**. An algorithm that runs on **linear time** is recommended, i.e., `O(n)`. On the random tests: - Random Tests: `100` tests - List Size: `0` to `20_000` - Integer Size: `- 2 ** 100` to `2 ** 100` #### Examples ```python score([1, 2, 3]) => 11 pairs: [(1, 2), (1, 3), (2, 3)] values: [2, 3, 6] -> 11 score([1, 1, 2, 2]) => 13 pairs: [(1, 1), (1, 2), (1, 2), (1, 2), (1, 2), (2, 2)] values: [1, 2, 2, 2, 2, 4] -> 13 ``` ```python score([]) -> 0 score([69]) -> 0 score([69, -420]) -> -28980 score([1, -2, 3, -4, 5, -6]) -> -41 ```
algorithms
def score(numbers): sn = sum(numbers) return sum(x * (sn - x) for x in numbers) / / 2
Add 'Em Pairs!
658fb5effbfb3ad68ab0951d
[ "Mathematics", "Combinatorics", "Performance" ]
https://www.codewars.com/kata/658fb5effbfb3ad68ab0951d
6 kyu
You are given a `string` of lowercase letters and spaces that you need to type out. However, there are some arrow keys inside. What do you do then? Here are a few examples: ``` abcdefgh<<xyz -> abcdefxyzgh Walkthrough: v type this: abcdefgh go back two characters such that the pointer is right in front of 'f' then continue typing v abcdefxyzgh ``` Try it yourself by typing on your keyboard! Ok, lets see more examples. ``` 'extra large<<<<<< extra>>>>>> pizza' -> 'extra extra large pizza' Walkthrough: type this: extra large go back six characters. the pointer is now right in front of 'a' v extra large v extra extra large go forward six characters. the pointer is now at the front again v extra extra large v extra extra large pizza ``` Now lets add a new function: multiplication. It's quite straightforward. Example: `>*6` = `>>>>>>` Examples: ``` 'completing on <*3kata >*3codewars' -> 'completing kata on codewars' ' thstorm<*100>>>*1under' -> ' thunderstorm' ``` Okay, that second example might not have been the most obvious, however you can always try typing it out yourself on a text editor to check some cases. Notes: - In the function `>*n`, n is always a positive integer (1, 2, 3, ...) - `>>>*5` = `>>(>*5)` = `>*7` - Although mentioned before, if the command tells you to go left but the pointer is at the start, it doesn't move. Same for the right command. Good luck! ______ Check out <a href="https://www.codewars.com/collections/65abaddba4b9f2013327dd3d">the rest of the kata in this series</a>!
algorithms
def type_out(s): res, pointer, i = [], 0, 0 while i < len(s): if s[i] in '<>': func = s[i] i += 1 times = 1 if i < len(s) and s[i] == '*': i += 1 times = 0 while i < len(s) and s[i]. isdigit(): times = times * 10 + int(s[i]) i += 1 if func == '<': pointer = max(0, pointer - times) else: pointer = min(len(res), pointer + times) else: res . insert(pointer, s[i]) pointer += 1 i += 1 return '' . join(res)
Typing series #4 --> left and right arrow keys
6582ce1afbfb3a604cb0b798
[]
https://www.codewars.com/kata/6582ce1afbfb3a604cb0b798
6 kyu
# Converging Journeys In the domain of **converging journeys**, numbers progress based on a unique formula. Specifically, following `n` is `n` plus the sum of its digits. For example, `12345` is followed by `12360`, since `1+2+3+4+5 = 15`. If the first number is `k` we will call it journey `k`. For example, journey `480` is the sequence beginning `{480, 492, 507, 519, ...}` and journey `483` is the sequence beginning `{483, 498, 519, ...}`. People may cross paths in their lives, and this happens when two journeys share some of the same values. For example: `journey 480` meets `journey 483` at `519`, meets `journey 507` at `507`, and never meets `journey 481`. Every journey will eventually meet `journey 1`, `journey 3` or `journey 9`. Write a program which inputs a single integer `n` _(1 ≤ n ≤ 16384)_, and outputs the value where journey `n` first meets one of these three journeys. ``` Note: Smaller journeys have higher priority, so if journey 1 and journey 3 were to intersect simultaneously, journey 1 would be returned. ``` ### Example: ```python 86 # Journey (1, 101) # First meets journey 1 at 101 ``` # Input/Output - `[input]` integer `n` representing the journey `86` - Constraints: `1 ≤ n ≤ 16384` - `[output]` tuple representing the journey number and the value where they meet `(1, 101)` _Source: [1999 British Informatics Olympiad](https://www.olympiad.org.uk/papers/1999/bio/bio99ex.pdf)_
reference
def converging_journeys(n): j = {1: 1, 3: 3, 9: 9} while n: for k in j: while j[k] < n: j[k] += sum(map(int, str(j[k]))) if j[k] == n: return (k, n) n += sum(map(int, str(n)))
Converging Journeys
6585960dfbfb3afd22b0a1fe
[]
https://www.codewars.com/kata/6585960dfbfb3afd22b0a1fe
6 kyu
# Lojban Numbers Counting in **Lojban**, an artificial language developed over the last forty years, is easier than in most languages. The numbers from `zero` to `nine` are: ```javascript 1 pa 4 vo 7 ze 2 re 5 mu 8 bi 0 no 3 ci 6 xa 9 so ``` Larger numbers are created by gluing the digits together. For example, `123` is `pareci`. Write a program that reads in a Lojban string _(representing a number less than or equal to `1,000,000`)_ and outputs it in numbers. ### Example: ```python renonore # Lojban string 2002 # Number ``` # Input/Output - `[input]` string representing the number in Lojban `pareci` - Constraints: Lojban number ≤ 1,000,000 - `[output]` integer representing the Lojban number `123` _Source: [2002 British Informatics Olympiad](https://www.olympiad.org.uk/papers/2002/bio/bio02ex.pdf)_
reference
def convert_lojban(lojban): return int(lojban . translate(str . maketrans('nprcvmxzbs', '0123456789', 'aeiou')))
Lojban Numbers
6584b7cac29ca91dd9124009
[]
https://www.codewars.com/kata/6584b7cac29ca91dd9124009
7 kyu
# ISBN An **ISBN** (International Standard Book Number) is a `ten digit` code which uniquely identifies a book. The first nine digits represent the book and the last digit is used to make sure the ISBN is correct. To verify an ISBN you calculate `10` times the first digit, plus `9` times the second digit, plus `8` times the third... all the way until you add `1` times the last digit. If the final number leaves no remainder when divided by `11` the code is a valid ISBN. For example `0201103311` is a valid ISBN, since `10*0 + 9*2 + 8*0 + 7*1 + 6*1 + 5*0 + 4*3 + 3*3 + 2*1 + 1*1 = 55.` Each of the first nine digits can take a value between `0` and `9`. Sometimes it is necessary to make the last digit equal to ten; this is done by writing the last digit as `X`. For example, `156881111X`. Write a program that reads in an ISBN code (will always be valid) with a single missing digit, marked with a `?`, and outputs the correct value for the missing digit. ### Example: ``` 15688?111X => "1" 020161586? => "X" ``` # Input/Output - `[input]` string representing the 10-digit ISBN code `15688?111X` - `[output]` string representing the missing digit `'1'` _Source: [2003 British Informatics Olympiad](https://www.olympiad.org.uk/papers/2003/bio/bio03ex.pdf)_
reference
def checksum(isbn): # calculate checksum return sum((10 - i) * (10 if d == "X" else int(d)) for i, d in enumerate(isbn)) def fix_code(isbn): # try all possible digits for digit in "0123456789X": fixed_isbn = isbn . replace("?", digit) if checksum(fixed_isbn) % 11 == 0: return digit
ISBN Corruption
6582206efbfb3a604cb0a6fe
[]
https://www.codewars.com/kata/6582206efbfb3a604cb0a6fe
7 kyu
# Mayan Calendar The Mayan civilisation used three different calendars. In their long count calendar there were `20` days (called kins) in a uinal, `18` uinals in a tun, `20` tuns in a katun and `20` katuns in a baktun. In our calendar, we specify a date by giving the day, then month, and finally the year. The Maya specified dates in reverse, giving the baktun (1-20), then katun (1-20), then tun (1-20), then uinal (1-18) and finally the kin (1-20). The Mayan date `13 20 7 16 3` corresponds to the date `1 January 2000` (which was a Saturday). Write a program which, given a Mayan date (between `13 20 7 16 3` and `14 1 15 12 3` inclusive), outputs the corresponding date in our calendar. You should output the month as a number. ### Example: ```python 13 20 9 2 9 # Mayan date 22 March 2001 22 3 2001 # Gregorian date 22 March 2001 ``` You are reminded that, in our calendar, the number of days in each month is: ``` 1 January 31 2 February 28 / 29 (leap year) 3 March 31 4 April 30 5 May 31 6 June 30 7 July 31 8 August 31 9 September 30 10 October 31 11 November 30 12 December 31 ``` # Input/Output - `[input]` string representing the Mayan date in the form `baktun katun tun uinal kin` - `[output]` string representing the Gregorian date in the form `dd mm yyyy` _Source: [2004 British Informatics Olympiad](https://www.olympiad.org.uk/papers/2004/bio/q1.html)_
algorithms
from datetime import datetime, timedelta REF = datetime(2000, 1, 1) def convert_mayan(date): baktun, katun, tun, uinal, kin = [int(x) for x in date . split()] return (REF + timedelta(days=kin + 20 * (uinal + 18 * (tun + 20 * (katun + 20 * baktun))) - 2018843)). strftime('%-d %-m %Y')
Mayan Calendar
657e2e36fbfb3ac3c3b0a1fb
[ "Date Time" ]
https://www.codewars.com/kata/657e2e36fbfb3ac3c3b0a1fb
6 kyu
## Task Write a function that takes the string and finds a repeating character in this string (there may or may not be several of them), returns the minimum difference between the indices of these characters and the character itself. > For example, in the string “aabcba” the minimum position difference of repeated characters will be equal to 1, since for the character “a” the position difference will be equal to 1. The output should be a tuple. - If there are no duplicate characters in the line, it should output None. - The string can only lowercase ones, and nothing else!!!(there cannot be an empty line) - If the difference between repeated characters is the same, print the first character encountered. Examples of outputs: ```Python "aa" => (1, 'a') "aabbca" => (1, 'a') "abka" => (3, 'a') "abcded" => (2, 'd') "abbbbbc" => (1, 'b') "abc" => None ```
reference
def min_repeating_character_difference(text): for i in range(1, len(text)): for a, b in zip(text, text[i:]): if a == b: return i, a
Minimum difference in duplicate characters
6574d1bde7484b5a56ec8f29
[ "Strings" ]
https://www.codewars.com/kata/6574d1bde7484b5a56ec8f29
6 kyu
## Introduction In some societies, you receive a name around your birth and people use it to refer to you while you don't have any children. Once you have at least one child, people give you a [teknonym](https://en.wikipedia.org/wiki/Teknonymy). A teknonym is a way to refer to someone according to some of its descendants, like the '__mother of Joe__', the '__great-grandfather of Jane__', etc. In this kata, you will receive some kind of family tree and your task will be to give the correct teknonym to the members of the tree, according to the rules specified in the next section. ## Rules - If X doesn't have any direct descendant : they don't have a teknonym. - A direct descendant of X is any member, but X, of the subtree rooted at X. - If X has some direct descendants : the teknonym is built according to the sex of X and the name of the elder among its direct descendants of the most distant generation from X. - The 'generation distance' between X and one of its descendant, say Y, is the number of levels between X and Y. - So you have to : 1) Find the most distant generation 2) Find the elder of that generation 3) Build the teknonym of X according to the two previous informations. - __There won't be any ambiguity to determine who is the elder between two direct descendants of someone.__ - The possible teknonyms are (all __lower case__): - 'father of Y', 'grandfather of Y', 'great-grandfather of Y', 'great-great-grandfather of Y', and so on ; - 'mother of Y', 'grandmother of Y', 'great-grandmother of Y', 'great-great-grandmother of Y', and so on ; ## Example <?xml version="1.0" encoding="us-ascii" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" contentStyleType="text/css" height="362px" preserveAspectRatio="none" style="width:663px;height:362px;" version="1.1" viewBox="0 0 663 362" width="663px" zoomAndPan="magnify"><defs/><g><g id="elem_a"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="194" x="170.5" y="7"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="8" x="263.5" y="22.1318">a</text><line style="stroke:#181818;stroke-width:0.5;" x1="171.5" x2="363.5" y1="27.0986" y2="27.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="176.5" y="44.2305">dob : 1000/01/01</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="52" x="176.5" y="60.3291">sex : 'm'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="182" x="176.5" y="76.4277">teknonym : 'grandfather of e'</text></g><g id="elem_b"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="165" x="7" y="143"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="8" x="85.5" y="158.1318">b</text><line style="stroke:#181818;stroke-width:0.5;" x1="8" x2="171" y1="163.0986" y2="163.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="13" y="180.2305">dob : 1020/01/01</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="44" x="13" y="196.3291">sex : 'f'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="153" x="13" y="212.4277">teknonym : 'mother of h'</text></g><g id="elem_c"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="120" x="207.5" y="143"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="7" x="264" y="158.1318">c</text><line style="stroke:#181818;stroke-width:0.5;" x1="208.5" x2="326.5" y1="163.0986" y2="163.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="213.5" y="180.2305">dob : 1021/02/01</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="52" x="213.5" y="196.3291">sex : 'm'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="80" x="213.5" y="212.4277">teknonym : ''</text></g><g id="elem_d"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="157" x="363" y="143"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="8" x="437.5" y="158.1318">d</text><line style="stroke:#181818;stroke-width:0.5;" x1="364" x2="519" y1="163.0986" y2="163.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="369" y="180.2305">dob : 1023/11/28</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="52" x="369" y="196.3291">sex : 'm'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="145" x="369" y="212.4277">teknonym : 'father of e'</text></g><g id="elem_g"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="120" x="226.5" y="279"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="8" x="282.5" y="294.1318">g</text><line style="stroke:#181818;stroke-width:0.5;" x1="227.5" x2="345.5" y1="299.0986" y2="299.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="232.5" y="316.2305">dob : 1046/01/01</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="52" x="232.5" y="332.3291">sex : 'm'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="80" x="232.5" y="348.4277">teknonym : ''</text></g><g id="elem_f"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="120" x="381.5" y="279"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="4" x="439.5" y="294.1318">f</text><line style="stroke:#181818;stroke-width:0.5;" x1="382.5" x2="500.5" y1="299.0986" y2="299.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="387.5" y="316.2305">dob : 1045/01/01</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="44" x="387.5" y="332.3291">sex : 'f'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="80" x="387.5" y="348.4277">teknonym : ''</text></g><g id="elem_e"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="120" x="536.5" y="279"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="8" x="592.5" y="294.1318">e</text><line style="stroke:#181818;stroke-width:0.5;" x1="537.5" x2="655.5" y1="299.0986" y2="299.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="542.5" y="316.2305">dob : 1043/11/01</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="44" x="542.5" y="332.3291">sex : 'f'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="80" x="542.5" y="348.4277">teknonym : ''</text></g><g id="elem_h"><rect fill="#F1F1F1" height="76.3945" style="stroke:#181818;stroke-width:0.5;" width="120" x="29.5" y="279"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="8" x="85.5" y="294.1318">h</text><line style="stroke:#181818;stroke-width:0.5;" x1="30.5" x2="148.5" y1="299.0986" y2="299.0986"/><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="108" x="35.5" y="316.2305">dob : 1047/01/01</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="44" x="35.5" y="332.3291">sex : 'f'</text><text fill="#000000" font-family="sans-serif" font-size="14" lengthAdjust="spacing" textLength="80" x="35.5" y="348.4277">teknonym : ''</text></g><!--link a to b--><g id="link_a_b"><path codeLine="54" d="M217.92,83.33 C193.23,101.91 163.47,124.32 138.82,142.87 " fill="none" id="a-b" style="stroke:#FF0000;stroke-width:1.0;"/></g><!--link a to c--><g id="link_a_c"><path codeLine="55" d="M267.5,83.33 C267.5,101.91 267.5,124.32 267.5,142.87 " fill="none" id="a-c" style="stroke:#FF0000;stroke-width:1.0;"/></g><!--link a to d--><g id="link_a_d"><path codeLine="56" d="M315.97,83.33 C340.1,101.91 369.19,124.32 393.29,142.87 " fill="none" id="a-d" style="stroke:#FF0000;stroke-width:1.0;"/></g><!--link b to h--><g id="link_b_h"><path codeLine="57" d="M89.5,219.33 C89.5,237.91 89.5,260.32 89.5,278.87 " fill="none" id="b-h" style="stroke:#FF0000;stroke-width:1.0;"/></g><!--link d to e--><g id="link_d_e"><path codeLine="58" d="M484.68,219.33 C506.17,237.91 532.09,260.32 553.56,278.87 " fill="none" id="d-e" style="stroke:#FF0000;stroke-width:1.0;"/></g><!--link d to f--><g id="link_d_f"><path codeLine="59" d="M441.5,219.33 C441.5,237.91 441.5,260.32 441.5,278.87 " fill="none" id="d-f" style="stroke:#FF0000;stroke-width:1.0;"/></g><!--link d to g--><g id="link_d_g"><path codeLine="60" d="M398.32,219.33 C376.83,237.91 350.91,260.32 329.44,278.87 " fill="none" id="d-g" style="stroke:#FF0000;stroke-width:1.0;"/></g><!--SRC=[bT1BQiCm40RW_PnYTbuPFz97o2xq1hs17YExTQmfaafQIkzUsSR6KGfnXE178_5f9D-zsG_XH8zIgAvn_6cruXCx34vO7xV81l3BgQDpV7uP3xoI1c3vJYgW-06CGxF40rPbMHPb5UTOzFGLYrcVZQj0dMNxtG-b9bwXZGWjEMI3bC7l8agy9Ej_I7DDzZnhxLfJgHQf-dQ3QqAdnAweggBUto3IvyrSat0FJvk-RDsHIOd7JL-q9YWbnaVTHRGfyRoz2n2OvoYdK5Dea4Eqe8UWASmK3S0V]--></g></svg> __dob__ : date of birth Here we have three generations: - first generation : a - second generation : b, c, d - third generation : h, e, f, g. The direct descendants of: - a are b, c, d, e, f, g, h ; - b is h ; - d are e, f, g ; - c, e, f, g and h haven't any descendant. Teknonyms : - for a : the last generation, and the most distant one from __a__, is the third generation, the elder of that generation is __e__ and there is two generations between __a__ and __e__, so the teknonym of a is '__grandfather of e__'; - for b : __b__ has only one direct descendant, __h__, in the third generation, and there is one generation between __b__ and __h__, so the teknonym of b is '__mother of h__' ; - for d : __d__ has three direct descendants in the third generation, namely e, f, g, and e is the elder, so the teknonym of d is '__father of e__' ; - c, h, e, f and g haven't any descendant, so they don't have a teknonym. ## Input A structure representing a kind of family tree. Each node of the tree is a structure representing a person and containing: - their name - their date of birth - their sex, either 'm' for male and 'f' for female - their teknonym, an empty string you should mutate if it's relevant to do so - a sequence of children. Each child is a person, the sequence can be empty and not necessarily sorted. ```if:python In Python, the structure is a dictionnary. Each node has the following keys: ```python date_of_birth : datetime.datetime name : str teknonym : str # that's the field you should mutate if it's relevant to do so sex : str children : list[dict] # list of children, possibly empty ``` ```if:javascript In JS, the structure is an object. Each node has the following properties: ```javascript dateOfBirth : Date name : string teknonym : string // that's the field you should mutate if it's relevant to do so sex : string children : Array // possibly empty ``` ```if:commonlisp In Common Lisp, the structure is a structure (define by `defstruct`). Each node is a person structure and has the following fields: - `birth-utime` : Universal Time, number of seconds that have elapsed since 00:00 of January 1, 1900 in the GMT time zone ; - `name` : string ; - `teknonym` : string, that's the field you should mutate if it's relevant to do so ; - `sex` : character, either `#\m` or `#\f` ; - `children` : a list of person structure, possibly empty. The implicitely defined following functions to access the fields are preloaded : `person-name`, `person-sex`, `person-teknonym`, `person-birth-utime`, `person-children`. ``` ````if:java In Java, the structure is a class Person. Each node is a Person with the following fields: ```java public class Person{ public Person parent; public final String name; public final Character sex; public final Person[] children; public final LocalDateTime dateOfBirth; public String teknonym = ""; // that's the field you should mutate } ``` ```` ~~~if:rust In Rust, the following struct is preloaded for you: ```rust #[derive(Clone, Debug, Eq, PartialEq, Default)] pub struct Person { pub name: String, pub sex: char, pub date_of_birth: chrono::NaiveDate, // the field you should modify, if applicable pub teknonym: String, pub children: Vec<Person>, } ``` ~~~ ## Output Nothing. You should mutate the input in this kata. __But you have to mutate only the teknonym field, and only if it's relevant.__ ## Errors and messages If any errors occur, you will receive three JSON strings, the initial input, the actual and the expected values. There are a lot of tools to pretty display JSON strings, one of them is [jsonhero.io](https://jsonhero.io/) (available at the moment -- 12/12/23 -- and quite popular on Github). ```if:rust ### Rust: On failure, sample tests display the Debug output of the entire tree (no JSON). Due to the size of the trees, the full test suite displays only the first mismatched person. ``` ## End note The idea came from this article by [Clifford Geertz](https://en.wikipedia.org/wiki/Clifford_Geertz) : [Teknonymy in Bali](http://hypergeertz.jku.at/GeertzTexts/Teknonymy_Bali.htm). Happy coding !
algorithms
def teknonymize(t) - > None: if t['children']: g, d = min([teknonymize(c) for c in t['children']], key=lambda a: (- a[0], a[1]['date_of_birth'])) t['teknonym'] = 'great-' * (g - 2) + 'grand' * (g > 1) + \ ['mother', 'father'][t['sex'] == 'm'] + ' of ' + d['name'] return g + 1, d else: return 1, t
Teknonymy
65781071e16df9dcbded1520
[ "Trees", "Data Structures", "Recursion" ]
https://www.codewars.com/kata/65781071e16df9dcbded1520
5 kyu
You are given a ```string``` of lowercase letters and spaces that you need to type out. You may notice some square brackets inside the string. - If it contains letters, type out the text inside then copy it. - If it is empty, paste the copied text - If it contains a number, paste the copied text that number of times. Here are a few examples. `[ten ]ten [3]` -> `ten ten ten ten ten ` `[one hundred and ]one, []two, []three` -> `one hundred and one, one hundred and two, one hundred and three` `[100][repeat me][2]` -> `repeat merepeat merepeat me` (pasting nothing 100 times is still nothing) Notes: - Although it is possible, nested loops will not be tested. - The number inside the bracket will always be a positive integer (1, 2, 3...). - All inputs will be valid (no unclosed brackets, etc) More examples in the smaple tests. Good luck! ______ Check out <a href="https://www.codewars.com/collections/65abaddba4b9f2013327dd3d">the rest of the kata in this series</a>!
reference
import re def type_out(s): clipboard = "" def paste(m): nonlocal clipboard copy = m[1] if not copy: return clipboard if copy . isdigit(): return int(copy) * clipboard return (clipboard := copy) return re . sub(r'\[([^]]*)\]', paste, s)
Typing series #3 --> copy and paste
6573331997727a18c8f82030
[ "Regular Expressions" ]
https://www.codewars.com/kata/6573331997727a18c8f82030
6 kyu
The cuckoo bird pops out of the cuckoo clock and chimes once on the quarter hour, half hour, and three-quarter hour. At the beginning of each hour (1-12), it chimes out the hour. Given the current time and a number *n*, determine the time when the cuckoo bird has chimed *n*&nbsp; times. Input Parameters: <br> *initial_time* - a string in the format "HH:MM", where 1 ≤ HH ≤ 12 and 0 ≤ MM ≤ 59, with leading 0’s if necessary. <br> *n* - an integer representing the target number of chimes, with 1 <= *n* <= 200. Return Value: The time when the cuckoo bird has chimed *n*&nbsp; times - a string in the same format as *initial_time*. If the cuckoo bird chimes at *initial_time*, include those chimes in the count. If the *n*th chime is reached on the hour, report the time at the start of that hour (i.e. assume the cuckoo finishes chiming before the minute is up). Example: *"03:38", 19* &nbsp; should return *"06:00"*. <br> Explanation: It chimes once at *"03:45"*, 4 times at *"04:00"*, once each at *"04:15", "04:30", "04:45"*, 5 times at *"05:00"*, and once each at *"05:15", "05:30", "05:45"*. At this point it has chimed 16 times, so the 19th chime occurs when it chimes 6 times at *"06:00"*. Source: International Collegiate Programming Contest, North Central North American Regional, 2023. Related Kata: [Fizz Buzz Cuckoo Clock](https://www.codewars.com/kata/58485a43d750d23bad0000e6)
reference
def cuckoo_clock(t, n): # around-the-clock optimization (=> O(1) runtime) n = n % 114 if n > 114 + 15 else n h, m = map(int, t . split(':')) t = h % 12 * 60 + m while True: k = t / / 60 or 12 if t % 60 == 0 else t % 15 == 0 if n <= k: return f" { t / / 60 or 12 :0 2 d } : { t % 60 :0 2 d } " n, t = n - k, (t + 1) % (12 * 60)
Cuckoo Clock
656e4602ee72af0017e37e82
[ "Strings", "Date Time" ]
https://www.codewars.com/kata/656e4602ee72af0017e37e82
6 kyu
## Introduction In the land of *Mathtopia*, *King Euler I* embarks on his inaugural **crusade** to purge the holy soil of *NerdLand* from the unworthy scholars of humanities, reinstating its former glory in STEM. Yet, **only honorable knights** may join this esteemed quest. Thus, he must devise a scheme to discern which loyal subjects shall partake in the honor of battle. Amidst his restless nights, gazing at the stars, and pondering the likelihood of his plan's fruition, a glint of hope emerges. Beholding the night's embrace through his casement, he encounters **divine intervention**. > Only those who possess qualities akin to those of your greatest knight shall aid you; the others shall betray you. Perplexed yet invigorated, the king endeavors to **decipher** the celestial entity's words. Arranging his `n` men in sequence with his most valiant placed at the end, he assigns a **numerical worth** to each, spanning from `1` to `n`. Thus, he determines that **only those whose value divides evenly into that of his foremost man** shall partake in this grand endeavor. ## Task Given a **positive integer** `n`, return **it's divisors**, sorted in **ascending order**, **without repetition** (`1` and `n` also count). ## Performance This kata's focus is to test numbers with **many of the same smaller prime factors**, such as `2 ^ 12345` or `3 ^ 420 * 7 ^ 69`, rather than numbers with **few very big prime factors**, such as `1,000,000,007` and `500,000,003`. Thus, giving a **max value for** `n` would be **misleading**. However, I can assure you of a few things. - The **length of the output** will **always be smaller or equal to** `1,000,000`. - The given number will **never have a prime factor greater that** `1000`. - In addition to the fixed tests, there will be `100` random tests, following the **aforementioned restrictions**. Also, **the answer won't be shown in the full tests**; this isn't to avoid cheating but rather to allow big inputs; otherwise, the string conversion for the message would **take too long**, **limiting the possible inputs**. ### Length Test Your code shouldn't be longer than `10,000` characters. Unless you're trying to hardcode some of the answers, this **really shouldn't be a problem** (reference solution is `476` characters long). This is just to stop anyone from **hardcoding some of the slower inputs**. ### Examples ```python divisors(6) -> [1, 2, 3, 6] divisors(25) -> [1, 5, 25] divisors(101) -> [1, 101] divisors(250) -> [1, 2, 5, 10, 25, 50, 125, 250] # It's just the powers of 3 to 100; I ain't putting them all here, but you have to return them all. divisors(3 ** 100) -> [1, 3, 9, 27, 81, 243, ..., 515377520732011331036461129765621272702107522001] ``` #### Other Katas Check out https://www.codewars.com/kata/544aed4c4a30184e960010f4, for a **less performant** version of the same problem (`O(n)` works there). Check out https://www.codewars.com/kata/5bd5607c1c730fe99400000f, for a **more big-primes-focused** version. It has a **lower upper bound**, but **greater individual factors** (the description is also `10%` of this one, lol). If you're looking for some other **dumb math stories**, take a look at **my other katas**, though **regarding quality**, the introduction is the only certainty at best.
algorithms
def divisors(n: int) - > list[int]: solution: list[int] = [1] currentDivisor: int = 2 while n > 1: index: int = 0 while not n % currentDivisor: n / /= currentDivisor length: int = len(solution) for i in range(index, length): index = length solution . append(currentDivisor * solution[i]) currentDivisor += 1 # the list is already close to sorted so this isnt very expensive return sorted(solution) # this second solution is very close to the first, and doest reliably speed up the kata tests # def divisors(n: int) -> list[int]: # solution: list[int] = [1] # # doing multiples of two first allows skipping current divisor by 2 later # i:int = 1 # while not n % 2: # n //= 2 # solution.append(2**i) # i+=1 # currentDivisor: int = 3 # while n > 1: # index: int = 0 # while not n % currentDivisor: # n //= currentDivisor # length: int = len(solution) # for i in range(index, length): # index = length # solution.append(currentDivisor * solution[i]) # currentDivisor += 2 # the advantage of skipping current divisor by 2 is offset by having slower sorting since it is further from the sorted solution # return sorted(solution)
Divisors Of Really Big Numbers
656f6f96db71be286d8f5c6b
[ "Mathematics", "Number Theory", "Performance" ]
https://www.codewars.com/kata/656f6f96db71be286d8f5c6b
5 kyu
In this kata you are given two integers: `initial number`, `target number` two arrays and fixed set of instructions: 1. Add 3 to the number 2. Add the sum of its digits to a number, if number is not 0 3. Add the number reduced modulo 4 to the number, if the modulus is not 0 Your task is to find amount of ways you can get from the `initial number` to the `target number`, performing these instructions Also, there's some limitations, which are `must include` and `must avoid` arrays. Both should be set to `None` by default * `must include`: A list of numbers that must be included in the sequence of transformations from the initial number to the target number. * `must avoid`: A list of numbers that must be avoided in this sequence. For example, you're given **1** as `initial number` and **7** as `target number`, There are **5** ways to get from 1 to 7. You can perform instructions in following orders: * 1, 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(1 -> 4 -> 7) * 2, 2, 1 (1 -> 2 -> 4 -> 7) * 2, 3, 1 (1 -> 2 -> 4 -> 7) * 3, 2, 1 (1 -> 2 -> 4 -> 7) * 3, 3, 1 (1 -> 2 -> 4 -> 7) However, if there will be 2 in `must avoid` there is only 2 (first) way left Or if there will be 2 in `must include` we can perform any of these, except first Notes: * `initial number` and `target number` may be negative * `target number` always greater than `insital number` * If there isn't any numbers that should be included or avoided, corresponding argument may be set to empty list, None or not passed at all * Values in `must include` and `must avoid` in tests are always valid (beetween `initial number` and `target number`) * Ranges for `initial number` and `target number` are [-10; 28] and [initial_num + 1; 30] * `must include` and `must avoid` arrays never intersect in tests
algorithms
from collections import Counter from itertools import pairwise from math import prod def find_ways(initial_num, target_num, must_include=None, must_avoid=None): numbers = [initial_num, * sorted(must_include or []), target_num] must_avoid = {* must_avoid} if must_avoid else set() return prod(ways(start, stop, must_avoid) for start, stop in pairwise(numbers)) def ways(start, stop, must_avoid): numbers = Counter((start,)) while numbers: n = min(numbers) k = numbers . pop(n) if n == stop: return k for m in n + 3, n + sum(map(int, str(abs(n)))), n + n % 4: if n < m <= stop and m not in must_avoid: numbers[m] += k return 0
Ways from one number to another
6565070e98e6731c13882aa0
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/6565070e98e6731c13882aa0
5 kyu
As you sit in your university math lecture, your professor introduces the Gauss-Seidel method, an iterative technique for solving systems of linear equations. The method itself was quite elegant, but the idea of manually solving equations repeatedly until convergence was daunting. That's when you decided to take matters into your own hands – or rather, your computer's. You set out to write a program that would automate the Gauss-Seidel method, making those late-night assignment sessions a bit less tedious. # Gauss-Seidel Method The Gauss-Seidel method is an iterative technique for solving a system of linear equations. In this kata, your task is to write a function that takes a system of three linear equations in the form of a matrix and return the solution vector with an accuracy of 4 decimal places # The iterative process 1. **Initialization**. Start with an initial guess vector, in this case, a vector of all zeros. `(x=y=z=0)` 2. **Iteration**. For this method to work (i.e., to converge at a solution), the coefficient matrix should be diagonally dominant. That is, the elements on the leading diagonal of the matrix should dominate the sum of all other coefficients in that row. For the sake of simplicity, the given coefficient will be diagonally dominant. Use the first equation to calculate the value of *x*, the second to calculate the value of *y*, and the third to calculate the value of *z*. For each equation in turn, calculate the updated value for the corresponding variable using the latest values of the other variables. This involves substituting the current values into the corresponding equation and solving for the variable in question. 3. **Convergence Check** After each iteration, compare the current values of the variables to their values from the previous iteration. If the difference between corresponding elements in the vectors is less than 0.0001 for all variables, the solution has converged. 4. **Repeat** If the solution has not converged, repeat steps 2 and 3 until convergence is achieved. # Example Consider the system of equations: ``` 8x - 3y + 2z = 20 4x + 11y - z = 33 6x + 3y + 12z = 35 ``` Here, observe that the the coefficient matrix is diagonally dominant. Use the first equation to obtain a formula for x, the second for a formula of y, and the third for a formula of z. ``` x = 1/8 * (20 + 3y − 2z) y = 1/11 * (33 − 4x + z) z = 1/12 * (35 − 6x − 3y) ``` Use 0 as the initial guess for `x,y,z`. Calculate the values of `x,y,z` (in that order) using the last updated values for the other two variables. #### Iteration 1: * Calculate `x` using the last updated values of `y` and `z` (both 0), to get `x=2.5`. * Calculate `y` using the last updated values of `x` and `z` (2.5, 0 respectively), to get `y=2.0909`. * Calculate `z` using the last updated values of `x` and `y` (2.5, 2.0909 respectively), to get `z=1.1439`. #### Iteration 2: * Calculate `x` using the last updated values of `y` and `z` (from above), and repeat for `y` and `z`. Continue repeating this process until succesive updates of the variable are within 0.0001 of each other. Set the cap for the number of iterations as 100. If the solution has not converged in the first 100 iterations, return the last updated values and the number of iterations in the above format. ## Input: * The input will be in the form of a 3X4 matrix where the first three columns represent the x,y,z values in that order and the last column represents the right side of the equation. The example above is hence represented as, `[[8, -3, 2, 20], [4, 11, -1, 33], [6, 3, 12, 35]]` * You can assume that the given system of equations is diagonally dominant and has only one solution. ## Output: * Return the answer as a two element tuple, where the first element is a list of the `x,y,z` values in that order, and the second element is the number of iterations conducted. i.e., in the form `([x,y,z],iterations) * Do not round any of the values of the variables whilst returning.
algorithms
def gauss_seidel(c): x = y = z = i = 0 while i == 0 or any(abs(d) > 0.0001 for d in (x - ox, y - oy, z - oz)): ox, oy, oz = x, y, z x = (c[0][3] - c[0][1] * y - c[0][2] * z) / c[0][0] y = (c[1][3] - c[1][0] * x - c[1][2] * z) / c[1][1] z = (c[2][3] - c[2][0] * x - c[2][1] * y) / c[2][2] i += 1 return [x, y, z], i
Gauss-Seidel Method
6562d61a9b55884c720e2556
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/6562d61a9b55884c720e2556
6 kyu
### Background Consider a 8-by-8 chessboard containing only a knight and a king. The knight wants to check the king. The king wants to avoid this. The knight has a cloaking shield, so it moves invisibly. Help the king escape the knight! ### Task You are given the initial king position, initial knight position, and the number of moves **n** that the titanic struggle will last. Return a list (or array) of length **n** containing the king's moves. The first move must be a legal king move from the initial king position, and each subsequent move must be a legal king move from the king's previous position. Your goal is for the king to make all the moves in sequence without ever getting checked by the knight, no matter which moves the knight makes. ### Details (1) Squares on the chessboard are specified as strings giving the horizontal coordinate first (a letter from a to h), followed by the vertical coordinate (a number from 1 to 8). Example: On the board below, the knight N is on "d4" and the king K is on "g7". ``` 8 ........ 7 ......K. 6 ........ 5 ........ 4 ...N.... 3 ........ 2 ........ 1 ........ abcdefgh ``` (2) The king moves one square in any direction. For example, the king on g7 can move to any of the following squares: f8, f7, f6, g8, g6, h8, h7, h6, as shown below. ``` 8 .....*** 7 .....*K* 6 .....*** 5 ........ 4 ........ 3 ........ 2 ........ 1 ........ abcdefgh ``` (3) The knight moves one square horizontally and two squares vertically, or two squares horizontally and one square vertically. For example, the knight on d4 can move to any of the following squares: b3, c2, e2, f3, f5, e6, c6, b5, as shown below. ``` 8 ........ 7 ........ 6 ..*.*... 5 .*...*.. 4 ...N.... 3 .*...*.. 2 ..*.*... 1 ........ abcdefgh ``` (4) The knight and king move *simultaneously*. The knight wins if it ever checks the king (or if the king moves illegally). The king (and you) win if it survives the specified number of moves without ever being checked. ### Example Given input ("g7", "d4", 6), suppose your function returns ["f8", "e7", "f6", "e7", "d7", "d6"] as the king's moves. If the knight happened to move ["c6", "e5", "g4, "f2", "d1", "e3"], then the knight wins, because after move 3 the knight at g4 checks the king at f6. ### Things to Note (1) The number of moves **n** satisfies 1 <= **n** <= 50. (2) The initial position of the king is always a different square from the initial position of the knight. (3) It's possible that the knight could be checking the king in the initial position. This is ignored. It's also possible that the same position could occur three times in succession. This is also ignored. (In regular chess this allows a draw to be declared.) (4) In order to make sure that it never moves to the same square as the king, the knight can access the move-list returned by your function. This means it can use this information when picking its move. (We didn't say this was a fair fight!) ### Related Kata This kata was motivited by [Red Knight](https://www.codewars.com/kata/5fc4349ddb878a0017838d0f) and [Knight vs King](https://www.codewars.com/kata/564e1d90c41a8423230000bc).
games
def choose_king_moves(king, knight, n): c = king[0]. translate(str . maketrans('abcdefgh', 'babcdefg')) r = (int(king[1]) - 1) & 6 | (ord(c) ^ ord(knight[0]) ^ ord(knight[1])) & 1 return [f' { c }{( r ^ ( k & 1 )) + 1 } ' for k in range(n)]
Escape the knight!
653888111746620b77a3ccd5
[ "Games" ]
https://www.codewars.com/kata/653888111746620b77a3ccd5
6 kyu
# Background Three-valued logic is a multiple-valued logic system in which there are three truth values; for this kata they will be `True`, `False` and `Unknown`. In this kata, `T` stands for `True`, `F` stands for `False` and `U` stands for `Unknown`. They are also represented as `1`, `-1` and `0` respectively. This is the basic truth table: ``` *---+---+-------+---------+--------+---------* | P | Q | not P | P and Q | P or Q | P xor Q | | T | T | F | T | T | F | | T | U | F | U | T | U | | T | F | F | F | T | T | | U | T | U | U | T | U | | U | U | U | U | U | U | | U | F | U | F | U | U | | F | T | T | F | T | T | | F | U | T | F | U | U | | F | F | T | F | F | F | *---+---+-------+---------+--------+---------* ``` Commutativity holds in this three-valued logic. For example: ``` T and U is equal to U and T. In general: p and q is equal to q and p. ``` Moreover, for identical operators, associativity holds in this three-valued logic. For example: ``` (U or T) or F is equal to U or (T or F). ((T xor F) xor U) xor T is equal to (T xor (F xor U)) xor T, T xor ((F xor U) xor T), T xor (F xor (U xor T)), (T xor F) xor (U xor T). ``` Note that the law of the excluded middle and the law of non-contradiction do not hold in this three-valued logic. For example: ``` U and not U is not equal to F. not U or U is not equal to T. ``` Read more about three-valued logic [on Wikipedia](https://en.wikipedia.org/wiki/Three-valued_logic). # Task Write a function `threevl` that accepts an expression ( as a string ) and returns its value ( as `1`, `0`, or `-1` ). For example: ```python "not T or U" -> 0 "not (T or U)" -> -1 "U and not U" -> 0 "not (F and (U xor T))" -> 1 ``` # Notes - Always evaluate expressions inside brackets first. - This kata only uses 4 operators `not, and, xor, or`. - Their priorities, from highest to lowest, are: `not, and, xor, or`. Hence, `not T or F xor U` should equal `(not T) or (F xor U)`. # Input - `0` <= the number of operators < `59` - There will be no invalid inputs. There are `300` random tests. Good luck and happy coding!
algorithms
from functools import reduce from collections import deque import re OPS = { 'not': lambda x: 'T' if x == 'F' else 'F' if x == 'T' else 'U', 'xor': lambda a, b: 'U' if 'U' in (a, b) else 'F' if a == b else 'T', 'and': lambda a, b: 'T' if 'T' == a == b else 'F' if 'F' in (a, b) else 'U', 'or': lambda a, b: 'T' if 'T' in (a, b) else 'F' if 'F' == a == b else 'U', } VALUES = dict(zip('TUF', (1, 0, - 1))) def bin_op(op, next_op): def parser(q): elt = next_op(q) while q and q[0] == op: q . popleft() v = next_op(q) elt = OPS[op](elt, v) return elt return parser def parse_term(q): elt = q . popleft() match elt: case '(': elt = expression(q) assert q . popleft() == ')' return elt case 'not': v = parse_term(q) out = OPS[elt](v) return out case _: return elt expression = reduce(lambda f, op: bin_op( op, f), 'and xor or' . split(), parse_term) tokenizer = re . compile(r'|' . join(OPS) + r'|\S') def threevl(s): lst = tokenizer . findall(s) q = deque(lst) out = expression(q) return VALUES[out]
Three-valued logic
65579292e361e60e202906f4
[ "Interpreters", "Logic" ]
https://www.codewars.com/kata/65579292e361e60e202906f4
5 kyu
# Task Sorting is one of the most basic computational devices used in Computer Science. Given a sequence (length ≤ 1000) of 3 different key values (7, 8, 9), your task is to find the minimum number of exchange operations necessary to make the sequence sorted. One operation is the switching of 2 key values in the sequence. # Example For `sequence = [7, 7, 8, 8, 9, 9]`, the result should be `0`. It's already a sorted sequence. For `sequence = [9, 7, 8, 8, 9, 7]`, the result should be `1`. We can switching `sequence[0]` and `sequence[5]`. For `sequence = [8, 8, 7, 9, 9, 9, 8, 9, 7]`, the result should be `4`. We can: ``` [8, 8, 7, 9, 9, 9, 8, 9, 7] switching sequence[0] and sequence[3] --> [9, 8, 7, 8, 9, 9, 8, 9, 7] switching sequence[0] and sequence[8] --> [7, 8, 7, 8, 9, 9, 8, 9, 9] switching sequence[1] and sequence[2] --> [7, 7, 8, 8, 9, 9, 8, 9, 9] switching sequence[5] and sequence[7] --> [7, 7, 8, 8, 8, 9, 9, 9, 9] ``` So `4` is the minimum number of operations for the sequence to become sorted. # Input/Output - `[input]` integer array `sequence` The Sequence. - `[output]` an integer the minimum number of operations.
algorithms
def exchange_sort(sequence): x = 0 y = 0 for f, g in zip(sequence, sorted(sequence)): if f < g: x += 1 elif f > g: y += 1 return max(x, y)
Simple Fun #148: Exchange Sort
58aa8b0538cf2eced5000115
[ "Algorithms", "Sorting" ]
https://www.codewars.com/kata/58aa8b0538cf2eced5000115
4 kyu
A Golomb-type sequence describes itself: based on a given infinite subsequence of the natural numbers, every number in the resulting sequence is the number of times the corresponding number from the given sequence appears, and it is the _least possible_ such number. An example: ```haskell input sequence : 1 2 3 4 5 .. output sequence : 1 2 2 3 3 4 4 4 5 5 5 .. ``` That is `1` one, `2` twos, `2` threes, `3` fours, `3` fives; next would be `4` .. probably sixes. The task: ```haskell golomb :: [Int] -> [Int] -- both are infinite ``` ```javascript golomb( « infinite » Iterable « of Integers », Integer ) => « finite » Iterable « of Integers » ; ``` ```lambdacalc golomb : Stream Number -> Stream Number ``` ```python golomb( « infinite » Iterable « of Integers », Integer ) => « finite » Iterable « of Integers » ; ``` Notes: ```if:javascript * The input sequence is infinite, and is encoded as an `iterable Object`<sup>[MDN](http://mdn.io/Iteration+protocols)</sup>. It is reusable. If you want a ( single-use ) `iterator`, you can extract `argument[Symbol.iterator]()`. * The output sequence <span style="color:aqua">must be finite</span>, and must be encoded as an `iterable Object`, e.g. an `Array`, a `Generator Object` or a "plain" `iterable Object`. Tests will be performed on `Array.from(result)` ( `Array.from()` is a no-op for `Array`s ). Your result value need not be reusable. No more than `10 000` elements of output will be tested. ``` ```if:haskell * Testing can only be performed on a finite part of the infinite sequence. No more than `10 000` elements of output will be tested, but try to avoid the temptation to approximate `Infinity` with `10 000`. ``` ```if:lambdacalc * Testing can only be performed on a finite part of the infinite sequence. No more than `1 000` elements of output will be tested, but try to avoid the temptation to approximate `Infinity` with `1 000`. ``` ```if:python * The input sequence is infinite, and is encoded as an `iterable object`<sup>[docs](https://docs.python.org/3/glossary.html#term-iterable)</sup>. It is reusable. If you want a ( single-use ) `iterator`, you can extract `iter(argument)`. * The output sequence <span style="color:aqua">must be finite</span>, and must be encoded as an `iterable object`, e.g. a `list`, a `tuple`, a `generator object` or an object of a class that implements `__iter__`. Tests will be performed on `tuple(result)`. Your result value need not be reusable. No more than `10 000` elements of output will be tested. ``` * The input sequence is a subsequence of the natural numbers, which means it is strictly ascending and all elements will be non-negative ( it may or may not start at `0` ). * The output sequence must contain only values that are in the input sequence, and must be keyed to the values in the input sequence, in order ( the actual keys are not in the result value, but they can be inferred from the input sequence ). * [Wikipedia](https://en.wikipedia.org/wiki/Golomb_sequence) and the [OEIS](https://oeis.org/A001462) have entries on Golomb ( -type ) sequence(s). Note that this kata uses generalised Golomb-type sequences; some descriptions and assumptions may not be pertinent to this kata. Specifically, for this kata it is not necessary to specify the starting element of the resulting sequence; it ( the element ) follows from the specification. Also, result sequences may not be non-decreasing. ~~~if:lambdacalc Encodings: purity: `LetRec` numEncoding: `BinaryScott` export constructor `cons` and deconstructors `head, tail` for your `Stream` encoding. Note that because JS uses strict evaluation, `cons`, as exported, has to accept a lazy tail. Also note that LC uses lazy evaluation, and compilation is in order. Variables can be redefined; only the _last_ definition of a variable is exported, but definitions always use the current value of any free variable. ~~~
algorithms
def golomb(given, n): res, idx, seq = [], 0, iter(given) if (x := next(seq)) != 0: res, idx = [x] * x, 1 elif (x := next(seq)) != 1: res, idx = [x] * 2 + [0] * x + [x] * (x - 2), 2 else: res, idx = [1, (x := next(seq)), 1, 0] + [1] * (x - 2), 3 while len(res) < n and (x := next(seq)): if idx < len(res): res += [x] * res[idx] else: res += [x] * x idx += 1 return res[: n]
Golomb-type sequences
5d06938fcac0a5001307ce57
[ "Algorithms" ]
https://www.codewars.com/kata/5d06938fcac0a5001307ce57
3 kyu
**Translations Welcome!** --- Most fonts nowadays, including the one you are reading now, stores each glyph in the form of a [Scalable Vector Format](https://www.w3schools.com/graphics/svg_intro.asp). Each line, curve, and shape are plotted out with corrdinates that are then traced using complex math formulas we won't go over in this kata¹. ![Svg Infographic](https://designlooter.com/images/path-svg-7.png) This is great for everyone, since these kinds of images can be scaled infinitely, and never lose resolution. SVG's are a 21st century invention though. Before vectors, the .bmp (bitmap) format was a popular choice for graphical interfaces. While not nearly as sophisticated, it can be extremely concise at representing data when used correctly². One good example of this is [Unifont](http://unifoundry.com/unifont/index.html), a massive font which contains "glyphs for every printable code point in the Unicode Basic Multilingual Plane"³. Let's discuss why Unifont's founders were able to put so much infomation in a single font by looking at an example. This is "A": ``` 0041:0000000018242442427E424242420000 ``` On the left is the unicode number for A (U+0041) and on the right is the hexadecimal value for a binary representation of that glyph. Each number corresponds to four bits⁴, and each 32 number sequence forms an 8x16 grid of 1's and 0's. Finally, all of this is later rendered as an "on" pixel or "off" pixel. Here is a graphical representation of A: ``` hex | binary | visual ----|----------|--------- 00 | 00000000 | ──────── 00 | 00000000 | ──────── 00 | 00000000 | ──────── 00 | 00000000 | ──────── 18 | 00011000 | ───██─── 24 | 00100100 | ──█──█── 24 | 00100100 | ──█──█── 42 | 01000010 | ─█────█─ 42 | 01000010 | ─█────█─ 7E | 01111110 | ─██████─ 42 | 01000010 | ─█────█─ 42 | 01000010 | ─█────█─ 42 | 01000010 | ─█────█─ 42 | 01000010 | ─█────█─ 00 | 00000000 | ──────── 00 | 00000000 | ──────── ``` Cool, right? That is what you will do for this kata. You will craft a function that, given a hexadecimal input as a string, output a 16 line string of 8 bits that correctly shows the corresponding character⁵. --- ### Footnotes: 1: If you are curious about the math used, read up on the [Bézier curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) 2: Of course, the average .bmp file isn't something you can just manipulate...that would be crazy. 3: Quoted from the site. By the way, when I say unifont is massive, I mean it. It has over 60,000+ different glyphs! 4: 4 bits is called a "nibble" 5: I considered having you give the graphical representation, but I didn't want this kata to have potential encoding issues (using normal characters doesn't work, since they all have different widths.)
algorithms
from textwrap import fill def hex_to_bitmap(h): return fill(f' { int ( h , 16 ):0 128 b } ', 8)
Bitmap Glyph Forger
65553172219a8c8e263b58ff
[ "Strings" ]
https://www.codewars.com/kata/65553172219a8c8e263b58ff
7 kyu
# Task You are given a `chessBoard`, a 2d integer array that contains only `0` or `1`. `0` represents a chess piece and `1` represents a empty grid. It's always square shape. Your task is to count the number of squares made of empty grids. The smallest size of the square is `2 x 2`. The biggest size of the square is `n x n`, where `n` is the size of chess board. A square can overlap the part of other squares. For example: If ``` chessBoard=[ [1,1,1], [1,1,1], [1,1,1] ] ``` ...there are four 2 x 2 squares in the chess board: ``` [1,1, ] [ ,1,1] [ , , ] [ , , ] [1,1, ] [ ,1,1] [1,1, ] [ ,1,1] [ , , ] [ , , ] [1,1, ] [ ,1,1] ``` And one 3 x 3 square: ``` [1,1,1] [1,1,1] [1,1,1] ``` Your output should be an object/dict. Each item in it should be: `size:number`, where size is the square's size, and number is the number of squares. For example, if there are four `2 x 2` squares and one `3 x 3` square in the chess board, the output should be: `{2:4,3:1}` (or any equivalent hash structure in your language). The order of items is not important, `{3:1,2:4}` is also a valid output. If there is no square in the chess board, just return `{}`. # Note ```if:javascript - `2 <= chessBoard.length <= 400` ``` ```if:python - `2 <= chessBoard.length <= 120` ``` ```if:ruby - `2 <= chessBoard.length <= 130` ``` ```if:java - `2 <= chessBoard.length <= 250` ``` ```if:haskell - `2 <= chessBoard.length <= 120` ``` ```if:csharp - `2 <= chessBoard.Length <= 220` ``` - `5` fixed testcases - `100` random testcases, testing for correctness of solution - `100` random testcases, testing for performance of code - All inputs are valid. - Pay attention to code performance. - If my reference solution gives the wrong result in the random tests, please let me know(post an issue). # Example For ``` chessBoard = [ [1,1], [1,1] ] ``` the output should be `{2:1}`. For ``` chessBoard = [ [0,1], [1,1] ] ``` the output should be `{}`. For ``` chessBoard = [ [1,1,1], [1,1,1], [1,1,1] ] ``` the output should be `{2:4,3:1}`. For ``` chessBoard = [ [1,1,1], [1,0,1], [1,1,1] ] ``` the output should be `{}`.
algorithms
from collections import defaultdict def count(chessBoard): # Initialize: board = chessBoard . copy() tally = defaultdict(int) # Compute Longest square ending in bottom right corner of each element and tally up: for i, row in enumerate(board): for j, element in enumerate(row): # Edge detection: if i == 0 or j == 0: continue # Compute & Tally: if element: n = board[i][j] = min(board[i - 1][j], board[i] [j - 1], board[i - 1][j - 1]) + 1 for x in range(n, 1, - 1): tally[x] += 1 return tally
Count Squares In the Chess Board
5bc6f9110ca59325c1000254
[ "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/5bc6f9110ca59325c1000254
4 kyu
_yet another easy kata!_ _Bored of usual python katas? me too;_ <hr> ## Overview &ensp;&ensp;&ensp;&ensp; As you have guessed from the title of the kata you are going to implement a class that supports ***function overloading***. You might be thinking python doesn't support that thing... Of course python doesn't support that! So you have to implement that missing functionality. &ensp;&ensp;&ensp;&ensp; To achieve that You have to implement the `Meta` class which will be the metaclass of `Overload` class (see sample tests) and class that use `Meta` should work as usual at other things. <hr> ## The Goal ```python class Overload(metaclass=Meta): CLS_VAR = 42 def __init__(self): self.a = 1 self.no = 'This is "No parameter" function.' self.single = 'This is "Single parameter" function' self.two = 'This is "Two parameter" function' self.three = 'This is "Three parameter" function' def foo(self): return self.no def foo(self, x): return self.single + ':' + str(x) def foo(self, x, y): return self.two + ':' + str(x) + ',' + str(y) def foo(self, x, y, z): return self.three + ':' + str(x) + ',' + str(y) + ',' + str(z) def extra(self): return 'This is extra method.' obj = Overload() Overload.foo=lambda self,a,b,c,d: 'from outside!' obj.foo() # 'This is "No parameter" function.' obj.foo(1, 2) # 'This is "Two parameter" function:1,2' obj.foo(1, 2, 3) # 'This is "Three parameter" function:1,2,3' obj.foo(1, 2, 3, 4) # 'from outside!' ``` <hr> ## Specifications * The Overload base class will always be the same as above. It will be regenerated different times in the tests, for testing purpose. * All the other methods will be added and tested **after instanciation** the class like shown in the example above (***Focus on this point; you will need this***). * Only instance methods will be tested, no static or class level methods. * There is no testing for either `*varargs` or `**kwargs`. * Aside from overloading, the class should behave just like usual. Talking here about variable assginment or reassignment, at class or instance level, reassigning a method to a var or the opposite, ... * If there is neither a method (overloaded or not) which satisfies the expected number of arguments nor a property or class level property that cn be found when calling for an attribute, raise an exception of type `AttributeError` ("just like usual", as said above...) * Last but not least, different classes must not share overloaded method. Hence: ```python Cls1 = generate_Overload() obj = Cls1() Cls1.foo=lambda self,a,b,c,d: 'from Cls1' Cls2 = generate_Overload() obj2 = Cls2() Cls2.foo=lambda self,a,b,c,d: 'from Cls2' obj.foo(1,2,3,4) # -> 'from Cls1' obj2.foo(1,2,3,4) # -> 'from Cls2' Cls2.foo=lambda self: 'updated' obj.foo() # -> 'This is "No parameter" function.' obj2.foo() # -> 'updated' ``` ## Notes * If there are any flaw in testing then report me. * If you need some hints then ping me in discourse. _Enjoy!_ _Thanks to B4B for his contribution._ _I can assure you that this can be done without using any library/modules._
reference
from collections import defaultdict def setter(prep, k, v, supSetter): if callable(v): def wrap(* args): f = prep . d[k][len(args)] if isinstance(f, int): raise AttributeError() return f(* args) prep . d[k][v . __code__ . co_argcount] = v v = wrap supSetter(k, v) class Prep (dict): def __init__(self): self . d = defaultdict(lambda: defaultdict(int)) def __setitem__(self, k, v): setter(self, k, v, super(). __setitem__) class Meta (type): @ classmethod def __prepare__(cls, * args, * * kwds): return Prep() def __new__(metacls, name, bases, prep, * * kwargs): prep['_Meta__DCT'] = prep return super(). __new__(metacls, name, bases, prep, * * kwargs) def __setattr__(self, k, v): setter( self . __DCT, k, v, super(). __setattr__)
Python Recipes #1 : Function Overloading
5f24315eff32c4002efcfc6a
[ "Metaprogramming" ]
https://www.codewars.com/kata/5f24315eff32c4002efcfc6a
4 kyu
<details open> <summary style=" padding: 3px; width: 100%; border: none; font-size: 18px; box-shadow: 1px 1px 2px #bbbbbb; cursor: pointer;"> Task</summary> ##### "Given an array of queues, how many times must you perform dequeueing operations, for each number to end up in its associated queue?" ``` queues perfect [[0, 1], [2], [1, 1]] -> [[0], [1, 1, 1], [2]] ``` ### Input ##### queues - an array of zero, one or more queues - each queue is an array containing zero, one or more non-negative integers - each number is within the range: <code>0 ≤ n < number of queues</code> - the head of a queue is the right-most item - the tail of a queue is the left-most item - dequeueing an element from a queue is taking the head - enqueueing an element to a queue is prepending it to the tail ### Output - return a non-negative integer representing the number of dequeueing operations to get each number to end up in its associated queue - the associated queue for a number <code>n</code> is the queue at 0-based index <code>n</code> of the input array of queues - empty is a valid terminal state for any queue - empty is a valid terminal state for the array of queues ~~~if:javascript ### Method Signature - <code>dequeueCount(queues)</code> - <code>popCount(queues)</code> (allowed for backward compatibility) ~~~ </details> <details open> <summary style=" padding: 3px; width: 100%; border: none; font-size: 18px; box-shadow: 1px 1px 2px #bbbbbb; cursor: pointer;"> Algorithm</summary> Your code should yield the same outcome as the algorithm described below, but should be more efficient than this naive approach, and you can use <b>any algorithm you want</b> to get the job done. - start at queue 0 - keep performing the following actions until all queues have entered a terminal state - if the current queue has reached a terminal state, move to next queue - moving from the last queue to the next, takes you back to the first queue - otherwise dequeue a number of the current queue and enqueue it to the associated queue of that number; that queue becomes the new current queue - keep track of each time you dequeue a number and return the total amount of dequeueing operations </details> <details open> <summary style=" padding: 3px; width: 100%; border: none; font-size: 18px; box-shadow: 1px 1px 2px #bbbbbb; cursor: pointer;"> Examples</summary> ``` ----------------------------------------------------- Example 1 ----------------------------------------------------- queues dequeueCount [ [0, 0], 0 [1, 1], [2, 2] ] steps - all numbers are already in their associated queue ----------------------------------------------------- Example 2 ----------------------------------------------------- queues dequeueCount [ [], 2 [0, 2], [] ] steps - queue 0 is empty - a valid terminal state -, so move to queue 1 - cnt #1: dequeue number 2 from queue 1 and enqueue to queue 2 [ [], [0], [2] ] - queue 2 only has elements with value 2 - a valid terminal state -, so move to queue 0 - queue 0 is empty - a valid terminal state -, so move to queue 1 - cnt #2: dequeue number 0 from queue 1 and enqueue to queue 0 [ [0], [], [2] ] ----------------------------------------------------- Example 3 ----------------------------------------------------- queues dequeueCount [ [0, 1, 2], 5 [1, 1, 2], [2, 0, 0] ] steps - cnt #1: dequeue number 2 from queue 0 and enqueue to queue 2 [ [0, 1], [1, 1, 2], [2, 2, 0, 0] ] - cnt #2 dequeue number 0 from queue 2 and enqueue to queue 0 [ [0, 0, 1], [1, 1, 2], [2, 2, 0] ] - cnt #3 dequeue number 1 from queue 0 and enqueue to queue 1 [ [0, 0], [1, 1, 1, 2], [2, 2, 0] ] - cnt #4 dequeue number 2 from queue 1 and enqueue to queue 2 [ [0, 0], [1, 1, 1], [2, 2, 2, 0] ] - cnt #5 dequeue number 0 from queue 2 and enqueue to queue 0 [ [0, 0, 0], [1, 1, 1], [2, 2, 2] ] ``` </details> <details open> <summary style=" padding: 3px; width: 100%; border: none; font-size: 18px; box-shadow: 1px 1px 2px #bbbbbb; cursor: pointer;"> Input Constraints</summary> - some optimisation is required, naive solutions will time out - <code>500</code> random tests with <code>5 ≤ queues ≤ 10</code> - <code>500</code> random tests with <code>80 ≤ queues ≤ 100</code> - <code>100</code> random tests with <code>800 ≤ queues ≤ 1000</code> - the number of elements in each queue: <code>0 ≤ queue length ≤ number of queues</code> </details>
algorithms
def dequeue_count(queues): return sum(len(q) - next((j for j, v in enumerate(q) if v != i), len(q)) for i, q in enumerate(queues))
Perfect Queues
63cb1c38f1504e1deca0f282
[ "Algorithms", "Arrays", "Puzzles", "Performance" ]
https://www.codewars.com/kata/63cb1c38f1504e1deca0f282
6 kyu
This Kata is the first in the [Rubiks Cube collection](https://www.codewars.com/collections/rubiks-party). [This](https://ruwix.com/the-rubiks-cube/notation/) or [this](https://ruwix.com/the-rubiks-cube/notation/advanced/) websites will be very usefull for this kata, if there will be some lack of understanding after the description. There are plenty of examples and a 3D model that can perform all needed rotations. In this Kata you will give the cube the ability to rotate. The Rubik's Cube is made of six faces. F(ront), L(eft), R(ight), B(ack), U(p), D(own) Below a two dimensional representation of the cube. ``` +-----+ | | | U | | | +-----+-----+-----+-----+ | | | | | | L | F | R | B | | | | | | +-----+-----+-----+-----+ | | | D | | | +-----+ ``` On every face you can see nine stickers. Every sticker can be one of the six colors: Yellow, Blue, Red, Green, Orange, White. In this Kata they are represented with according small letters (y, b, r, g, o, w,). A solved cube has on every face only one color: ``` +-----+ |y y y| |y y y| |y y y| +-----+-----+-----+-----+ |b b b|r r r|g g g|o o o| |b b b|r r r|g g g|o o o| |b b b|r r r|g g g|o o o| +-----+-----+-----+-----+ |w w w| |w w w| |w w w| +-----+ ``` Every sticker on a face in this Kata has a positional number ``` +-----+ |1 2 3| |4 5 6| |7 8 9| +-----+ ``` So the state of the face could be represented in a 9 character string consisting of the possible colors. ``` +-----+ |y r b| |o o w| state == "yrboowygb" |y g b| +-----+ ``` So a state of the cube is a 54 character long string consisting of the state of every face in this order: U L F R B D ``` +-----+ |y y y| |y y y| state == "yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww" |y y y| +-----+-----+-----+-----+ |b b b|r r r|g g g|o o o| |b b b|r r r|g g g|o o o| |b b b|r r r|g g g|o o o| +-----+-----+-----+-----+ |w w w| |w w w| |w w w| +-----+ ``` # Rotations To make things easier I have preloded the `state_representation(state)` function that can visialise a state. ## basic rotations Every face can rotate. - The direction of a rotation is always defined on your "axis of sight" when your looking at a face of the cube. - A rotation of a face is written with an uppercase letter: `F`, `B`, ... - Clockwise and counterclockwise rotations are distinguished by an apostroph, added to the letter for the counterclockwise rotations. Examples: - `F` rotates the front face clockwise. - `F'` rotates the front face conterclockwise. You can rotate a face twice with a `2` after the letter. E.g. `F2` rotates the front face clockwise twice. ## slice rotations There is a possibility to rotate only a middle layer of the cube. These are called slice turns. There are three: `M, E, S`. There is no obvious clockwise or counterclockwise directions, so the are some special standarts: `M`(idle) the layer between `L` and `R`, turn direction as `L` `E`(quator) the layer between `D` and `U`, turn direction as `D` `S`(tanding) the layer between `F` and `B`, turn direction as `F` ``` After a "M" turn +-----+ |y o y| |y o y| state == "yoyyoyyoybbbbbbbbbryrryrryrgggggggggowoowoowowrwwrwwrw" |y o y| +-----+-----+-----+-----+ |b b b|r y r|g g g|o w o| |b b b|r y r|g g g|o w o| |b b b|r y r|g g g|o w o| +-----+-----+-----+-----+ |w r w| |w r w| |w r w| +-----+ ``` ## whole cube rotations There are three more letters you should consider: `X, Y, Z`. This are basically rotating the whole cube along one of the 3D axis. ## double layer rotations This are some kind of combined rotations. There are 6: `f, r, u, l, d, b`. Yes, like the 'basic rotations' but lowercase. A `f` means that you rotate the `F` face and the next slice layer with it IN THE SAME DIRECTION (in the F case its `S`). This is the whole list of possible rotations that the cube should perform: ``` F R U L D B F' R' U' L' D' B' F2 R2 U2 L2 D2 B2 M E S M' E' S' M2 E2 S2 f r u l d b f' r' u' l' d' b' f2 r2 u2 l2 d2 b2 X Y Z X' Y' Z' X2 Y2 Z2 ``` I have preloded a dictionary `single_rotations` that includes every single state to mentioned rotations. `single_rotations["F2"] == "yyyyyywwwbbgbbgbbgrrrrrrrrrbggbggbggoooooooooyyywwwwww"` # Task implement the `perform(sequence)` function that takes a string with space separeted values witha sequence of rotations. E.g. `F R2 f X M2 L' U2 d' Z M' B` The cube always starts in a solved state ("yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww") The function should return the changed state of the cube after the sequence. ``` perform("F U") == "byybyybyyrrrbbwbbwyggrrrrrroooyggyggbbwoooooogggwwwwww" ``` Enjoy ^_^
games
''' WARNING: EXTREMELY BAD PRACTICE ALERT DO NOT DO THIS IF YOU ARE WORKING ON A PROJECT ALTHOUGH HARD CODING CAN SOMETIMES MAKE CODE RUN FASTER, IT MAKES IT MESSY AND UNREADABLE ''' rotate_face_idx = [* zip(range(1, 10), [7, 4, 1, 8, 5, 2, 9, 6, 3])] def increase_idx(idx, n): return [ (start + n, changed + n) for start, changed in idx] U_turn_idx = rotate_face_idx + [(10, 19), (11, 20), (12, 21), (19, 28), (20, 29), (21, 30), (28, 37), (29, 38), (30, 39), (37, 10), (38, 11), (39, 12)] L_turn_idx = increase_idx(rotate_face_idx, 9) + [(1, 45), (4, 42), (7, 39), ( 19, 1), (22, 4), (25, 7), (39, 52), (42, 49), (45, 46), (46, 19), (49, 22), (52, 25)] F_turn_idx = increase_idx(rotate_face_idx, 18) + [(7, 18), (8, 15), (9, 12), ( 12, 46), (15, 47), (18, 48), (28, 7), (31, 8), (34, 9), (46, 34), (47, 31), (48, 28)] R_turn_idx = increase_idx(rotate_face_idx, 27) + [(3, 21), (6, 24), (9, 27), ( 21, 48), (24, 51), (27, 54), (37, 9), (40, 6), (43, 3), (48, 43), (51, 40), (54, 37)] B_turn_idx = increase_idx(rotate_face_idx, 36) + [(1, 30), (2, 33), (3, 36), ( 10, 3), (13, 2), (16, 1), (30, 54), (33, 53), (36, 52), (52, 10), (53, 13), (54, 16)] D_turn_idx = increase_idx(rotate_face_idx, 45) + [(16, 43), (17, 44), (18, 45), ( 25, 16), (26, 17), (27, 18), (34, 25), (35, 26), (36, 27), (43, 34), (44, 35), (45, 36)] M_turn_idx = [(2, 44), (5, 41), (8, 38), (20, 2), (23, 5), (26, 8), (38, 53), (41, 50), (44, 47), (47, 20), (50, 23), (53, 26)] E_turn_idx = [(13, 40), (14, 41), (15, 42), (22, 13), (23, 14), (24, 15), (31, 22), (32, 23), (33, 24), (40, 31), (41, 32), (42, 33)] S_turn_idx = [(4, 17), (5, 14), (6, 11), (11, 49), (14, 50), (17, 51), (51, 29), (50, 32), (49, 35), (29, 4), (32, 5), (35, 6)] def make_turn(pos, idx): copied = pos . copy() for start, changed in idx: pos[start] = copied[changed] def perform(seq): # idea is you only need to use moves in the set {U, L, F, R, B, D, M, E, S} to get any position # it is possible to do it with the moves {U, L, F, X, Y, Z} only, but it makes things a bit harder # this method is quite inefficient, but it makes things easier and this isn't a performance-based kata anyway for move in 'ULFRBDulfrbdMESXYZ': for times, char in enumerate('2\''): seq = seq . replace(move + char, move * (times + 2)) for comb in [('XYZ', 'rLLL uDDD fBBB' . split()), ('ulfrbd', 'UEEE LM FS RMMM BSSS DE' . split())]: for move in zip(* comb): seq = seq . replace(* move) seq = seq . replace(' ', '') position = {idx + 1: colour for idx, colour in enumerate('' . join(c * 9 for c in 'ybrgow'))} for move in seq: exec(f'make_turn(position, { move } _turn_idx)') return '' . join(position . values())
The Rubik's Cube
5b3bec086be5d8893000002e
[ "Puzzles", "Algorithms", "Geometry" ]
https://www.codewars.com/kata/5b3bec086be5d8893000002e
5 kyu
# What is a happy number? A happy number is defined as an integer in which the following sequence ends with the number 1. - Calculate the sum of the square of each individual digit. - If the sum is equal to 1, then the number is `happy`. - If the sum is not equal to 1, then repeat from steps 1. - A number is considered `unhappy` once the same number occurs multiple times in a sequence because this means there is a loop and it will never reach 1. For example, the number 7 is a "happy" number: 7² = 49 --> 4² + 9² = 97 --> 9² + 7² = 130 --> 1² + 3² + 0² = 10 --> 1² + 0² = 1 On the other hand, the number 6 is not a happy number as the sequence that is generated is the following: 6, 36, 45, 41, 17, 50, 25, 29, 85, **89**, 145, 42, 20, 4, 16, 37, 58, **89** Once the same number occurs twice in the sequence, the sequence is guaranteed to go on infinitely, never hitting the number 1, since it repeat this cycle. ---- # Your task: Write a function `perf_happy(n)` that returns a list of all happy numbers from 1 to `n` inclusive. ``` perf_happy(100) => [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100] ``` # The challenge: - you are going to be challenged for 30 tests up to `n = 10_000_000` - you are not allowed to hardcode the sequence: you'll have to compute it (max length of the code: 1700 characters) # Credits This kata is based on a [variation](https://www.codewars.com/kata/happy-numbers-5) of Happy Numbers by TySlothrop. It's a different view of [Happy Numbers (performance edition)](https://www.codewars.com/kata/happy-numbers-performance-edition) by FArekkusu. (ok, ok, I've copied a lot from them)
bug_fixes
happy = {1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97} sums = {0: [0]} for _ in range(7): new_sums = {} for x, terms in sums . items(): for d in range(10): new_sums . setdefault(x + d * d, []). extend(term * 10 + d for term in terms) sums = new_sums for x, terms in sums . items(): # order matters if x in happy: happy . update(terms) from bisect import bisect def perf_happy(n, happy_list=sorted(happy) ): return happy_list[: bisect(happy_list, n)]
Happy Numbers. Another performance edition.
5ecef4a6640dbb0032bc176d
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/5ecef4a6640dbb0032bc176d
4 kyu
Description: Write a method that takes a field for well-known board game "Battleship" as an argument and returns true if it has a valid disposition of ships, false otherwise. Argument is guaranteed to be 10*10 two-dimension array. Elements in the array are numbers, 0 if the cell is free and 1 if occupied by ship. Battleship (also Battleships or Sea Battle) is a guessing game for two players. Each player has a 10x10 grid containing several "ships" and objective is to destroy enemy's forces by targetting individual cells on his field. The ship occupies one or more cells in the grid. Size and number of ships may differ from version to version. In this kata we will use Soviet/Russian version of the game. Before the game begins, players set up the board and place the ships accordingly to the following rules: - There must be single battleship (size of 4 cells), 2 cruisers (size 3), 3 destroyers (size 2) and 4 submarines (size 1). Any additional ships are not allowed, as well as missing ships. - Each ship must be a straight line, except for submarines, which are just single cell. - The ship cannot overlap, but can be contact with any other ship. The description likes [Battleship field validator Kata](http://www.codewars.com/kata/battleship-field-validator), the only difference is the rule 3. This is all you need to solve this kata. If you're interested in more information about the game, visit [this link][1]. [1]: https://en.wikipedia.org/wiki/Battleship_(game)
algorithms
import numpy as np from itertools import combinations def validate_battlefield(field): return validate(np . array(field), [(1, 4), (2, 3), (3, 2)], 20) def validate(field, ships, expected): if field . sum() != expected: return False elif not ships: return True # single-unit ships can be anywhere, so we can shortcut # We are looking for (n) ships of length (size). (n, size), remaining = ships[0], ships[1:] # Find horizontal/vertical slices of the appropriate length containing all ones ... slices = filter(all, (f[i, j: j + size] for f in (field, field . T) for (i, j) in zip(* np . where(f)))) # ... and try zeroing-out (n) of them at a time to find a valid combination. # If the recursive check fails, we backtrack by setting the slices back to one. return any( assign(s, 0) or validate(field, remaining, expected - n * size) or assign(s, 1) for s in combinations(slices, n) ) def assign(slices, x): # Set the value of all array slices in a collection for arr in slices: arr[:] = x
Battleship field validator II
571ec81d7e8954ce1400014f
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/571ec81d7e8954ce1400014f
3 kyu
_Yet another easy kata!_ # Task: - Let's write a sequence starting with `seq = [0, 1, 2, 2]` in which - 0 and 1 occurs 1 time - 2 occurs 2 time and sequence advances with adding next natural number `seq[natural number]` times so now, 3 appears 2 times and so on. ### Input - You are given input `n` and return nth(0-based) value of this list. let;s take example: seq = [0, 1, 2, 2]\ i = 3 and as seq[i]=2, seq = [0, 1, 2, 2, 3, 3]\ i = 4 and as seq[i]=3, seq = [0, 1, 2, 2, 3, 3, 4, 4, 4]\ i = 5 and as seq[i]=3, seq = [0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5] and so on. Some elements of list: ``` [0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21] ``` <hr> # Constraint : * Python - 0 <= n <= `$2^{41}$` * Javascript - 0 <= n <= `$2^{49}$` <hr> ##### Have fun! _tip: you can solve this using smart brute-force._
reference
idx, n, seq = 2, 6, [1, 2, 4, 6] while n < 2 * * 41: idx += 1 seq . extend(range(n + idx, n + (seq[idx] - seq[idx - 1]) * idx + 1, idx)) n += (seq[idx] - seq[idx - 1]) * idx from bisect import bisect def find(n): return bisect(seq, n)
Repetitive Sequence - Easy Version
5f134651bc9687000f8022c4
[ "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/5f134651bc9687000f8022c4
4 kyu
# Task Write a function `three_powers()` to accept a number, to check can it represent as sum of 3 powers of 2.(`n == 2**i + 2**j + 2**k, i, j, k >= 0`) For example: ```python three_powers(2) # False three_powers(3) # True, 3 = 2**0 + 2**0 + 2**0 three_powers(5) # True, 5 = 2**0 + 2**1 + 2**1 three_powers(15) # False ``` # Input ```c - `n` must be an integer. - `1` <= `n` <= `2 ** 64 - 1` ``` ```python - `n` must be an integer. - `1` <= `n` <= `2 ** 100 - 1` ``` There are 2000 random tests for the speed test, good luck and happy coding.
algorithms
def three_powers(n): return n > 2 and n . bit_count() <= 3
3 powers of 2
6545283611df271da7f8418c
[ "Mathematics" ]
https://www.codewars.com/kata/6545283611df271da7f8418c
7 kyu
## Problem statement Packing multiple rectangles of varying widths and heights in an enclosing rectangle of minimum area. Given 3 rectangular boxes, find minimal area that they can be placed. Boxes can not overlap, these can only be placed on the floor. ## Input 3 pairs of numbers come to the input - the lengths(a1, b1, a2, b2, a3, b3) of the sides of the boxes. (1 ⩽ ai, bi ⩽ 10^4) ## Output Return a number equal to the minimum occupied area. ## Example Input example: ```python packing_rectangles(4,10,5,11,12,3) ``` Output example: ```python 144 ```
algorithms
from itertools import permutations def packing_rectangles(* args): result, inputs = float("inf"), { args[: 2], args[2: 4], args[4:], args[1:: - 1], args[3: 1: - 1], args[: 3: - 1]} for a, b, c, d, e, f in permutations(args): if (a, b) in inputs and (c, d) in inputs and (e, f) in inputs: result = min(result, (a + c + e) * max(b, d, f), (a + max(c, e)) * max(b, d + f)) return result
packing rectangles
5eee6c930514550026cefe9e
[ "Algorithms" ]
https://www.codewars.com/kata/5eee6c930514550026cefe9e
6 kyu
Given the lists with suppliers' production, consumers' demand, and the matrix of supplier-to-consumer transportation costs, calculate the minimum cost of the products transportation which satisfied all the demand. ## Notes * Costs-matrix legend: `costs[i][j]` is the cost of transporting 1 unit of produce from `suppliers[i]` to `consumers[j]` * The produce is identical - multiple suppliers can be the source for one consumer, and multiple consumers can be the target of one supplier * The produce is not important - it can be anything and have any price, we're only interested in transporting it efficiently * Total supply will always equal total demand * Your solution should pass `12` cases with matrices of size `150x150` as a performance test (the reference solution itself takes `~8500 ms` to do so) * For all tests, `0 <= costs[i][j] <= 100` * In performance tests, `1 <= suppliers[i], consumers[j] <= 10000` * Disabled modules are `scipy` and `sklearn` * Disabled built-in functions are `open`, `exec`, `eval`, `globals`, `locals` and `exit` ## Example Given these inputs: ``` suppliers = [10, 20, 20] consumers = [5, 25, 10, 10] costs = [2 5 3 0] [3 4 1 4] [2 6 5 2] ``` The shipments can be arranged the following way: ``` [ 10] | 10 [ 10 10 ] | 20 [ 5 15 ] | 20 ------------------+--- 5 25 10 10 | ``` By multiplying each element of this matrix by the corresponding element of the costs matrix, we get the result: ``` [ 0] [ 40 10 ] => 0 + 40 + 10 + 10 + 90 = 150 [10 90 ] ```
algorithms
import numpy as np class Basis: # stores the active basis def __init__(self, A, basis_list, Binv): self . A = np . copy(A) self . Binv = np . copy(Binv) self . basis_list = np . copy(basis_list) self . is_basis = np . array([False] * A . shape[1]) self . is_basis[basis_list] = True self . not_basis_list = np . where(~ self . is_basis)[0] self . indexes = np . array([0] * A . shape[1]) self . indexes[basis_list] = np . arange(len(basis_list)) self . indexes[self . not_basis_list] = np . arange( len(self . not_basis_list)) def update(self, oldcol, newcol): # updates efficiently the inverse of the basis at every step Y = self . Binv @ self . A[:, newcol] i = self . indexes[oldcol] self . Binv[i, :] *= 1 / Y[i] Y[i] = 0.0 self . Binv -= np . outer(Y, self . Binv[i, :]) oldindex, newindex = self . indexes[oldcol], self . indexes[newcol] self . basis_list[oldindex], self . not_basis_list[newindex] = newcol, oldcol self . indexes[oldcol], self . indexes[newcol] = newindex, oldindex self . is_basis[oldcol] = False self . is_basis[newcol] = True class OTSimplexSolver: # Optimal transport solver based on the simplex method def __init__(self, src, dst, cost): self . src, self . dst, self . cost = src, dst, cost self . n_src, self . n_dst = len(src), len(dst) self . rank = self . n_src + self . n_dst - 1 self . n_params = self . n_src * self . n_dst # We create a corresponding linear programming problem self . A = np . zeros((self . rank, self . n_params)) for i in range(self . n_src): for j in range(self . n_dst): self . A[i, self . n_dst * i + j] = 1.0 if j < self . n_dst - 1: self . A[self . n_src + j, self . n_dst * i + j] = 1.0 self . b = np . concatenate((src, dst[: - 1])) self . c = np . array(cost). flatten() self . basis = None def init_basis(self): # creates the initial basis basis_list = np . array(list(range(self . n_dst - 1)) + list( range(self . n_dst - 1, self . n_dst * self . n_src, self . n_dst))) Binv = np . zeros((self . rank, self . rank)) Binv[self . n_dst - 1:, : self . n_src] = np . identity(self . n_src) Binv[: self . n_dst - 1, self . n_src:] = np . identity(self . n_dst - 1) Binv[self . n_dst - 1, self . n_src:] = - 1.0 return Basis(self . A, basis_list, Binv) # finds initial basic feasible solution using the least-cost method def find_initial_solution_lcm(self): x = np . zeros(self . n_params) basis = self . init_basis() src_remaining, dst_remaining = self . src[:], self . dst[:] used = np . full(self . n_params, False) allowed = np . full(self . n_params, False) basis_size = 0 indexes = np . argsort(self . c) for k in indexes: i, j, loc_cost = k / / self . n_dst, k % self . n_dst, self . c[k] transported = min(src_remaining[i], dst_remaining[j]) if (transported == 0): continue used[k] = True basis_size += 1 x[k] += transported src_remaining[i] -= transported dst_remaining[j] -= transported if not basis . is_basis[k]: allowed[:] = False allowed[basis . basis_list[np . abs( basis . Binv @ self . A[:, k]) > 0.01]] = True allowed[used] = False basis . update(np . where(allowed)[0][0], k) if basis_size == self . rank: break return x, basis def simplex_step(self): lambd = self . c[self . basis . basis_list] @ self . basis . Binv lambd = np . concatenate((lambd, [0.0])) # faster computation of s = c - A^T \lambda s = self . c - (lambd[None, self . n_src:] + lambd[: self . n_src, None]). flatten() # nonbasic variables with s < 0 indexes_pivots = np . where((s < - 0.01) & ~ self . basis . is_basis)[0] if len(indexes_pivots) == 0: # if there is none, solution is optimal return True pivot = indexes_pivots[np . argmin(s[indexes_pivots])] d = self . basis . Binv @ self . A[:, pivot] # In OT, no need to worry about unboundedness cond = d > 0.01 indexes = np . where(cond)[0] xb = self . x[self . basis . basis_list] j = indexes[np . argmin(xb[cond] / d[cond])] oldcol = self . basis . basis_list[j] xi = xb[j] / d[j] self . x[self . basis . basis_list] -= d * xi self . x[pivot] = xi self . basis . update(oldcol, pivot) return False def solve(self): self . x, self . basis = self . find_initial_solution_lcm() res = False while not res: res = self . simplex_step() return self . x @ self . c, self . x def minimum_transportation_price(suppliers, consumers, costs): solver = OTSimplexSolver(suppliers, consumers, costs) return solver . solve()[0]
Optimal Transportation
5e90f0544af7f400102675ca
[ "Algorithms", "Mathematics", "Performance" ]
https://www.codewars.com/kata/5e90f0544af7f400102675ca
1 kyu
_NOTE: Unlike other Kata in the series, this one is not a golfing Kata._ ### Number Pyramid: Image a number pyramid starts with `1`, and the numbers increasing by `1`. Today, it has total `n` levels. For example, the top 5 levels of the pyramid looks like: ``` Pyramid with 5 levels: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 ``` ___ ### Vertical Sum: Now we devide the pyramid into vertical lines and give them indices. The index of middle line is `0`, it increases to the right, decreases to the left. In the above example, it will become: ``` Index: -4 -3 -2 -1 0 1 2 3 4 | | | | | | | | | | | |01| | | | | | |02| |03| | | | |04| |05| |06| | |07| |08| |09| |10| 11| |12| |13| |14| |15 ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ 11 7 16 10 19 12 20 10 15 The above are the vertical sums. ``` And the vertical sum is the sum of all number for the index. ___ ### Task: You will be given a number `n` for `n` levels, a number `i` for the index. You need to return the `vertical sum`. __Examples:__ vertical_sum(n, i) --> vertical sum ``` vertical_sum(4, -3) --> 7 vertical_sum(4, -1) --> 10 vertical_sum(4, 0) --> 6 vertical_sum(4, 2) --> 6 vertical_sum(4, 3) --> 10 vertical_sum(5, -3) --> 7 vertical_sum(5, -1) --> 10 vertical_sum(5, 0) --> 19 vertical_sum(5, 2) --> 20 vertical_sum(5, 4) --> 15 ``` ___ ### Not Highly-Performance Required * n <= 100000 * -n < i < n With the above, solution that directly generates all numbers of a vertical line should pass, non-`O(1)` solution can still pass. For sample tests and small random input, the numbers for the vertical line are also provided for debug purpose. ___ If you like this Kata, welcome to do [other kata](https://www.codewars.com/collections/code-golf-number-pyramid-series) relating to it.
games
def vertical_sum(n, i): idx = abs(i) + 1 top = idx * (idx + 1) / / 2 if i < 0: top += i hgt = (n - idx) / / 2 return hgt * (hgt + 1) * (n - 1 - (n + idx) % 2) - hgt * (hgt + 1) * (hgt - 1) * 4 / / 3 + (hgt + 1) * top
Number Pyramid Series 7 - Vertical Sum
65382cfc5396a5bc37d19395
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/65382cfc5396a5bc37d19395
6 kyu
## Background Let `$G$` be an undirected graph. Suppose we start with three coins on three arbitrarily chosen vertices of `$G$`, and we want to move the coins so that they lie on the same vertex using as few moves as possible. At every step, each coin must move across an edge. ## Task Write a function `converge(g, u1, u2, u3)` ### Input 1. Graph `G`, as a dictionary with vertices as keys and its neighbours in set as values. 2. Vertices `u1, u2, u3`, which might not be distinct, at which three coins are initially located ### Output Return the minimum number of steps possible to converge to any vertex P, or, if no convergence is possible, return `None`. Expected time complexity is `$O(n^2)$`
algorithms
from itertools import count from functools import reduce def converge(g, * us): floods = [frozenset({u}) for u in us] vus = set() for step in count(0): if all(s in vus for s in floods): break vus . update(floods) overlap = reduce(set . intersection, floods[1:], set(floods[0])) if overlap: return step floods = [frozenset(neigh for u in f for neigh in g[u]) for f in floods]
Topology #0: Converging Coins
5f5bef3534d5ad00232c0fa8
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5f5bef3534d5ad00232c0fa8
4 kyu
<div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> - If you like cryptography and playing cards, have also a look at [Card-Chameleon, a Cipher with Playing cards](https://www.codewars.com/kata/59c2ff946bddd2a2fd00009e). - And if you just like playing cards, have a look at [Playing Cards Draw Order](https://www.codewars.com/kata/630647be37f67000363dff04). <div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> As a secret agent, you need a method to transmit a message to another secret agent. But an encrypted text written on a notebook will be suspicious if you get caught. A simple deck of playing cards, however, is everything but suspicious... With a deck of 52 playing cards, there are `52!` different possible permutations to order it. And `52!` is equal to `80658175170943878571660636856403766975289505440883277824000000000000`. That's a number with [68 digits](https://www.wolframalpha.com/input/?i=52!)!</a> There are so many different possible permutations, we can affirm that if you shuffle the cards well and put them back together to form a deck, you are the first one in history to get this particular order. The number of possible permutations in a deck of cards is higher than the estimated number of atoms in planet Earth (which is a number with about [50 digits](https://www.wolframalpha.com/input/?i=number+of+atoms+in+earth)). With a way to associate a permutation of the cards to a sequence of characters, we can hide a message in the deck by ordering it correctly. # Correspondence between message and permutation ## Message To compose our message, we will use an alphabet containing 27 characters: the space and the letters from A to Z. We give them the following values: - `space = 0` - `A = 1` - `B = 2` - ... - `Z = 26` We now have a [numeral system](https://en.wikipedia.org/wiki/Numeral_system) with a base equal to 27. We can compute a numeric value corresponding to any message: - `"A " = 27` - `"AA" = 28` - `"AB" = 29` - `"ABC" = 786` - etc. Note: an empty message is considered equal to `0`. ## Permutation Now we need a way to attribute a unique number to each of the possible [permutations](https://en.wikipedia.org/wiki/Permutation) of our deck of playing cards. There are few methods to [enumerate permutations](https://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations) and [assign a number](https://en.wikipedia.org/wiki/Permutation#Numbering_permutations) to each of them, we will use the [lexicographical order](https://en.wikipedia.org/wiki/Lexicographical_order). With three cards, A, B, and C, as an example, it gives: - `ABC = 0` - `ACB = 1` - `BAC = 2` - `BCA = 3` - `CAB = 4` - `CBA = 5` So the first arrangement is ABC, and the last one is CBA. With our 52 playing cards – ranks sorted from the Ace to the King, and suits in alphabetical order (Clubs, Diamonds, Hearts, Spades) – the first arrangement (number `0`) is: <img alt="Ace of Clubs to King of Clubs, then Ace of Diamonds to King of Diamonds, then Ace of Hearts to King of Hearts, then Ace of Spades to King of Spades." src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWsAAACYCAIAAACtVV8sAAAACXBIWXMAAAsTAAALEwEAmpwYAAAgAElEQVR42u2deVBTWb7HbwKyd4hEEJAt2Owg4Dp5xSAWSdAWo63QLO0wuKC+bhRBSog8lAJlFQrRZrS6XLrpRkRbHHw60oqKUEDbMCzRhzpA2oTFPMgCYUkISd4fdyaVYgk398bX4pzvX8lN+HDuzTnf8zvnnnt+OFc3DwgICAgIlfDgEgABAQEHAQICAg4CBAQEHAQICAg4CBAQEBBwECAgIOAgQEBAwEGAgIA+KunPay04Jbg6QEBAsBRKnHYOohKZTPby8jIyMlrwm0qlcmhoqLm5eWpqCgABEAA/euDCDkKj0TIyMkZHRyUSCRKjIpFIXC43NjZWJpMBIAAC4EcMROQgn3/+eU1NTWZmJsJQZ8WKFTdv3vT19W1paUECxOFwSqXyQwbq/JTfBxCHw8H9xodcQg2/y4cAVNds+O9+DT/Aio3IQSwsLOrq6lRvw8PDw8LCvvvuu/v378/5/f7+/vHxcRKJpBloYWERHx+/evVqS0tLsVjc2Nj4zTff8Pl81EAIgoqLi11cXIhEokQi6ezsPH/+fG9vLxagShs3bvzqq6/a29tzcnKwAIuKilasWKE6Xl9ff+HCBYwl3LBhw/79+z08PCAI4nA4ycnJAwMD6IDe3t7p6ekzPioqKvrll19Ql9DOzi4hIcHPz09fX18gEPz000/l5eVYTtnKyurw4cPr1683MjLq6ekpLi7u7OxEDbS2tj548KC7u3t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7u1taWnp6elStFGMJh4aGVC1KoVB0dXVZWFicPXsWBVAqlfL5/Nn2gbGEk5OT7e3thYWFt27dsra2xgKUSqV9fX3qPcTQ0FB/f39QUBA6IPqpBysrq+PHjy9btiwlJUUnMRUAAiAAalZFRUVTU9MHVUKUDqKvr3/69Gk4oRaNRtu1axfGcwBAAATAxQhE6SAJCQnqaxkSEhK8vb0xTjQAIAAC4KIDonEQGo0WFhamfmTJkiXZ2dmoF/ABIAAC4CIFau0g+vr6R48enX3c0tIS3Y1lAARAAFy8QK0dxMrKar5nXj09PdHN4gAgAALgIgVq7SACgQC+eQ5BEIvFevjwoeotukV4AAiAALh4gVo7iEQi+ctf/jI5Odnf33/69Om3b98WFxfLZDIul6t6MhoAARAA/02A+ij+cXl5+fXr15VK5dKlS728vJKSkm7fvo1lDS8AAiAALlLgAjGIQqGY83l2+H84OjpOTk7q6emp/0scDjff3oIACIAA+NEAETkIj8dbs2bNfAkm2tvb09LS1PfI8fPzMzU11fCwEwACIAB+HMB/uoyrm8fc1oJTQhC0du3a/Px8+JFqhGpubk5KSpovEAJAAATAxQhUKHFoHASCIAKB4OzsjDDP1fDwcE9Pj+avASAAAuCiA6J3ECAgIKD5HARk3gYCAkIv4CBAQEDopa9t0AIEBAQEYhAgICDgIEBAQMBBgICAgIMAAQEBBwECAgICDgIEBPT/oP8DitrXM0jth+MAAAAASUVORK5CYII=" /> and the last one (number `52! - 1`) is: <img alt="King of Spades to Ace of Spades, then King of Hearts to Ace of Hearts, then King of Diamonds to Ace of Diamonds, then King of Clubs to Ace of Clubs." src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWsAAACZCAIAAABmCYyJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAgAElEQVR42u2deVQTWdr/bwKyd4iJKDsEmk1QcJ+8h0E8JKgtRlqhWdpxcEF9u1EEOULkRTmgrMLBpRk9fVy66UZEWxx8daQVNcIBtHGARF+XAdImLKYhC4QlMQu/P2o6JwchJFWxf+rc71+VSvh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enZR6c9WqVchAo7u7e1lZGQRCIAT+5wAN68UEBwfryNyL4rkUCIRACPyggYY5CPJSmUadnZ2vX7/WfETx4jYEQiAEftBAwxzk7t27mhWr7t+/39TUVFBQgLxjNjY2pv3YHARCIAT+JwANGwdRKBQpKSk+Pj5yuZzL5ebm5v7973/fsGGDm5tbT08PsgYiBEIgBP7nAGdwELVaPelN54mJCeSROxwOp1AonJ2dHz169OTJE80PcDjcdGu6QSAEQuBHA9SrFyMQCJYsWTJlgomJiYmcnJxJS04FBQVZW1vreGEMAiEQAj8O4L9dxtvHb2prwU0AAJYuXVpUVKRjzPZttbS0pKamTjeZDIEQCIEfIlA9gUPjIAAAAoHg4eGhZ56rwcHBrq4u3T+DQAiEwA8OiN5BoKCgoKZzEJh5GwoKCr2gg0BBQaGXqaFBCxQUFBSMQaCgoKCDQEFBQQeBgoKCDgIFBQUdBAoKCgo6CBQU1B+g/wdK89c1tOekNAAAAABJRU5ErkJggg==" /> To transmit a message, we will compute the permutation for which the unique number is the numeric value of the message. # Your task Write two functions: ```elixir encode(message) ``` ```java public String[] encode(String message) ``` ```javascript const encode = (message) => { ``` ```python encode(message) ``` ```typescript export const encode = (message: string): string[] => { ``` ```if:elixir Which takes a string containing a message, and returns a list of strings representing a deck of playing cards ordered to hide the message. ``` ```if:java,javascript,typescript Which takes a message (as a string) as argument and returns a deck of playing cards (an array of strings) ordered to hide the message. ``` ```if:python Which takes a String containing a message, and returns an array of Strings representing a deck of playing cards ordered to hide the message. ``` ```elixir decode(deck) ``` ```java public String decode(String[] deck) ``` ```javascript const decode = (deck) => { ``` ```python decode(deck) ``` ```typescript export const decode = (deck: string[]): string => { ``` ```if:elixir Which takes a list of strings representing a deck of playing cards, and returns the message that is hidden inside. ``` ```if:java,javascript,typescript Which takes a deck of playing cards (as an array of strings) as argument and returns the message (as a string) hidden inside. ``` ```if:python Which takes an array of Strings representing a deck of playing cards, and returns the message that is hidden inside. ``` Passed data will always be valid, you don't have to check it. Each card name, in a deck, is written with a two characters String: the rank followed by the suit. So the first arrangement of the deck is represented like: `AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC` for the Clubs `AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD` for the Diamonds `AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH` for the Hearts `AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS` for the Spades A preloaded function allows to easily print a deck to the console: ```elixir Preload.print_deck(deck,unicode) ``` ```java PlayingCardsOutput.printDeck(String[] deck, boolean unicode); ``` ```javascript printDeck(deck, unicode); ``` ```python printDeck(deck, unicode) ``` ```typescript import { printDeck } from "./preloaded"; printDeck(deck, unicode); ``` The first argument is the deck to print, the second one is a boolean value allowing the selection of the character set: regular or Unicode (for which a font containing the playing cards characters needs to be installed on your system). # Examples ## Encoding ```elixir PlayingCards.encode("ATTACK TONIGHT ON CODEWARS") ``` ```java playingCards.encode("ATTACK TONIGHT ON CODEWARS"); ``` ```javascript encode("ATTACK TONIGHT ON CODEWARS"); ``` ```python playingCards.encode("ATTACK TONIGHT ON CODEWARS") ``` ```typescript encode("ATTACK TONIGHT ON CODEWARS"); ``` should return this array of 52 strings: ```elixir [ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "JD", "9D", "7S", "9S", "QD", "5S", "TH", "7D", "TS", "QS", "2H", "JS", "6H", "3S", "6S", "TD", "8S", "2S", "8H", "7H", "4S", "4H", "3H", "5H", "AS", "KH", "QH", "9H", "KD", "KS", "JH", "8D", "AH" ] ``` ```java { "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "JD", "9D", "7S", "9S", "QD", "5S", "TH", "7D", "TS", "QS", "2H", "JS", "6H", "3S", "6S", "TD", "8S", "2S", "8H", "7H", "4S", "4H", "3H", "5H", "AS", "KH", "QH", "9H", "KD", "KS", "JH", "8D", "AH" } ``` <!-- prettier-ignore --> ```javascript [ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "JD", "9D", "7S", "9S", "QD", "5S", "TH", "7D", "TS", "QS", "2H", "JS", "6H", "3S", "6S", "TD", "8S", "2S", "8H", "7H", "4S", "4H", "3H", "5H", "AS", "KH", "QH", "9H", "KD", "KS", "JH", "8D", "AH" ]; ``` ```python [ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "JD", "9D", "7S", "9S", "QD", "5S", "TH", "7D", "TS", "QS", "2H", "JS", "6H", "3S", "6S", "TD", "8S", "2S", "8H", "7H", "4S", "4H", "3H", "5H", "AS", "KH", "QH", "9H", "KD", "KS", "JH", "8D", "AH" ] ``` <!-- prettier-ignore --> ```typescript [ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "JD", "9D", "7S", "9S", "QD", "5S", "TH", "7D", "TS", "QS", "2H", "JS", "6H", "3S", "6S", "TD", "8S", "2S", "8H", "7H", "4S", "4H", "3H", "5H", "AS", "KH", "QH", "9H", "KD", "KS", "JH", "8D", "AH" ]; ``` ## Decoding ```elixir PlayingCards.decode([ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "8H", "9S", "3S", "2S", "8S", "TS", "QS", "9H", "7H", "KH", "AS", "JH", "4S", "KS", "JS", "5S", "TH", "7S", "6S", "5H", "QH", "6H" ]) ``` ```java playingCards.decode(new String[] { "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "8H", "9S", "3S", "2S", "8S", "TS", "QS", "9H", "7H", "KH", "AS", "JH", "4S", "KS", "JS", "5S", "TH", "7S", "6S", "5H", "QH", "6H" }); ``` <!-- prettier-ignore --> ```javascript decode([ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "8H", "9S", "3S", "2S", "8S", "TS", "QS", "9H", "7H", "KH", "AS", "JH", "4S", "KS", "JS", "5S", "TH", "7S", "6S", "5H", "QH", "6H" ]); ``` ```python playingCards.decode([ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "8H", "9S", "3S", "2S", "8S", "TS", "QS", "9H", "7H", "KH", "AS", "JH", "4S", "KS", "JS", "5S", "TH", "7S", "6S", "5H", "QH", "6H" ]) ``` <!-- prettier-ignore --> ```typescript decode([ "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "8H", "9S", "3S", "2S", "8S", "TS", "QS", "9H", "7H", "KH", "AS", "JH", "4S", "KS", "JS", "5S", "TH", "7S", "6S", "5H", "QH", "6H" ]); ``` should return the string: ```elixir "ATTACK APPROVED" ``` ```java "ATTACK APPROVED" ``` ```javascript "ATTACK APPROVED"; ``` ```python "ATTACK APPROVED" ``` ```typescript "ATTACK APPROVED"; ``` # Have fun! I hope you will enjoy this kata! Feedbacks and translations are very welcome. # Further readings ## Logarithm With the logarithm function, we can know how many digits, in a numeral system of a certain base, are needed to represent a number. For example, [`log2(52!) = 225.58`](https://www.wolframalpha.com/input?i=log2%2852%21%29), so we can store `225` bits of information in a deck of cards (and `226` bits are needed to represent the value of `52!`). Also, [`log27(52!) = 47.44`](https://www.wolframalpha.com/input?i=log27%2852%21%29), so we can store `47` characters of our alphabet in a deck of cards (and some message with `48` characters, but not all of them).
algorithms
import math import string from functools import cached_property from itertools import count class Deck: def __init__(self): self . suits = tuple('CDHS') self . ranks = tuple('A23456789TJQK') self . cards = tuple(r + s for s in self . suits for r in self . ranks) def __len__(self) - > int: return len(self . cards) def find_nth_permutation(self, n: int) - > list[str]: cards, result = [* self . cards], [] for i in range(len(self) - 1, - 1, - 1): index, n = divmod(n, math . factorial(i)) result . append(cards . pop(index)) return result def find_ordinal_number_of_permutation(self, state: list[str]) - > int: cards, num_of_perm = [* self . cards], 0 for i, card in zip(count(len(self) - 1, - 1), state): index = cards . index(card) num_of_perm += index * math . factorial(i) _ = cards . pop(index) return num_of_perm class ValidAlphabet: def __init__(self): self . valid_symbols = tuple(' ' + string . ascii_uppercase) def __len__(self) - > int: return len(self . valid_symbols) @ cached_property def symbols_table(self) - > dict[str, int]: return {s: i for i, s in enumerate(self . valid_symbols)} @ cached_property def indexes_table(self) - > dict[int, str]: return {i: s for s, i in self . symbols_table . items()} class PlayingCards: ALPHA = ValidAlphabet() DECK = Deck() @ classmethod def encode(cls, message: str) - > list[str]: k, rm = len(cls . ALPHA), reversed(message) perm_n = sum( cls . ALPHA . symbols_table[s] * k * * i for i, s in enumerate(rm) ) return cls . DECK . find_nth_permutation(perm_n) @ classmethod def decode(cls, deck: list[str]) - > str: n = cls . DECK . find_ordinal_number_of_permutation(deck) result = [] while n: n, index = divmod(n, len(cls . ALPHA)) result . append(cls . ALPHA . indexes_table[index]) return '' . join(reversed(result))
Hide a message in a deck of playing cards
59b9a92a6236547247000110
[ "Cryptography", "Mathematics", "Games", "Permutations", "Algorithms" ]
https://www.codewars.com/kata/59b9a92a6236547247000110
4 kyu
<div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> - If you like cryptography and playing cards, have also a look at [Hide a message in a deck of playing cards](https://www.codewars.com/kata/59b9a92a6236547247000110). - And if you just like playing cards, have a look at [Playing Cards Draw Order](https://www.codewars.com/kata/630647be37f67000363dff04). <div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> As a secret agent, you need an effective and discrete hand cipher. Also called field cipher, this kind of encryption methods are designed to be executed by hand, without the help of a computer. The chosen method should not need any item that can be suspicious if discovered. So, no codebook, no one-time pad, etc. But a simple deck of playing cards, however, is everything but suspicious... Playing cards ciphers are recent and not common, but their level of security could be higher than we think. Cryptographer Bruce Schneier invented the [Solitaire](https://en.wikipedia.org/wiki/Solitaire_%28cipher%29) algorithm in 1999, and other playing cards ciphers have been created since. We will implement the **Card-Chameleon** cipher, created by Matthew McKague and presented in [his thesis](https://uwspace.uwaterloo.ca/bitstream/handle/10012/1141/memckagu2005.pdf) (page 74). Why do we write a _software implementation_ of a _hand_ cypher? Because if either the recipient or the sender has access to a computer, he will be able to encrypt/decrypt the message much faster. A message encrypted by hand can be decrypted with a computer, and vice versa. # Algorithm ## Characters Assignment We will use a classic deck of 52 cards, plus two Jokers, one black, on red. Each of the 26 letters of the alphabet, plus the Space character, is assigned to two cards in the deck, a black card and a red card, as shown in the table below: ``` Clubs & Diamonds Hearts & Spades Jokers A 2 3 4 5 6 7 8 9 T J Q K A 2 3 4 5 6 7 8 9 T J Q K B & R A B C D E F G H I J K L M N O P Q R S T U V W X Y Z " " ``` So, the letter A is assigned to the Ace of Clubs (black) and the Ace of Diamonds (red); the letter Z is assigned to the King of Hearts (red) and the King of Spades (black); the space is assigned to the black Joker and the red Joker. ## Key The cryptographic key is represented by the order of the cards in the deck. To communicate with each other, the sender and the recipient must start the process with the same key, so the same deck order. ## Prepare the deck Before the encryption/decryption process, the key deck has to be prepared in order to have 27 black/red pairs of cards. The procedure is as follow: 1. Take the deck face up. Deal out two piles face up, placing each black card on one pile and each red card on the other. Be sure to preserve the order exactly (do not place down groups of colours together). 2. Make a new pile, face up, by interleaving the two piles. This is done starting with the first black card (the one on the top of the black deck face up), then the first red card, the second black card, second red, and so on. The new pile should have a red card on top and alternate between red and black cards. ## Encryption The procedure to encrypt each character of the message is as follow: 1. Find the black card in the deck corresponding to the character in the assignment table. 2. Look at the red card above this black card. Interpret it as a character in the assignment table. 3. Find the black card in the deck corresponding to this new character. 4. Look at the red card above this black card. Interpret it as a character and write it down as the ciphertext. 5. Exchange this red card with the one on the top of the deck (also red). 6. Move the top two cards (one red, one black) to the bottom. ## Decryption The procedure to decrypt each character for the ciphertext is as follow: 1. Find the red card in the deck corresponding to the character in the assignment table. 2. Look at the black card below this red card. Interpret it as a character in the assignment table. 3. Find the red card in the deck corresponding to this new character. 4. Look at the black card below this red card. Interpret it as a character and write it down as the message. 5. Exchange the red card corresponding to the ciphertext character (the one found at step 1) with the one on the top of the deck (also red). 6. Move the top two cards (one red, one black) to the bottom. # Your task Write two functions: ```java public String encrypt(String message, String[] deck) ``` ```javascript encrypt(message, deck); ``` ```python CardChameleon(message, deck).encrypt() ``` ```typescript public encrypt(message: string, deck: string[]): string ``` Which takes a message and a key deck of cards as argument, and returns the encrypted text. ```java public String decrypt(String encrypted, String[] deck) ``` ```javascript decrypt(encrypted, deck); ``` ```python CardChameleon(message, deck).decrypt() ``` ```typescript public decrypt(encrypted: string, deck: string[]): string ``` Which takes a encrypted message and a key deck of cards as argument, and returns the decrypted message. Passed data will always be valid, you don't have to check it. Each card name, in a deck, is written with a two characters String (the rank followed by the suit), and the first String (`deck[0]`) is the top card of the deck, face up: `AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC` for the Clubs<br /> `AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD` for the Diamonds<br /> `AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH` for the Hearts<br /> `AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS` for the Spades<br /> `XB XR` for the Jokers, one black, one red A preloaded function allows to easily print a deck to the console: ```java CardChameleonOutput.printDeck(String[] deck, boolean withUnicode); CardChameleonOutput.printDeck(List<String> deck, boolean withUnicode); ``` ```javascript CardChameleonOutput.printDeck(deck, unicode); ``` ```python print_deck(deck, with_unicode) ``` ```typescript CardChameleonOutput.printDeck(deck, unicode); ``` The first argument is the deck to print, the second one is a boolean value allowing you to choose between simple text or Unicode display. (For Unicode, you need to have a font, on your system, that contains the playing cards Unicode characters.) # Examples ## Encryption ```java String message = "ATTACK TONIGHT ON CODEWARS"; String[] deck = new String[] { "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" }; cardChameleon.encrypt(message, deck); ``` <!-- prettier-ignore --> ```javascript const message = "ATTACK TONIGHT ON CODEWARS"; const deck = [ "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" ]; cardChameleon.encrypt(message, deck); ``` ```python message = "ATTACK TONIGHT ON CODEWARS" eck = [ "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" ] CardChameleon(message, deck).encrypt() ``` <!-- prettier-ignore --> ```typescript const message = "ATTACK TONIGHT ON CODEWARS"; const deck = [ "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" ]; cardChameleon.encrypt(message, deck); ``` should first prepare the deck in order to have 27 pairs as follow: ```java // Deck, face up, Six of Hearts (red) on top, Nine of Spades (black) on bottom { "6H", "2C", "2D", "5S", "3D", "7S", "8D", "JS", "7D", "8C", "TD", "7C", "AH", "3C", "TH", "KS", "9H", "QS", "6D", "2S", "7H", "QC", "5H", "TS", "3H", "5C", "4D", "XB", "8H", "AC", "KH", "4C", "5D", "3S", "9D", "KC", "2H", "6C", "4H", "8S", "QD", "JC", "JH", "TC", "QH", "9C", "XR", "4S", "JD", "AS", "AD", "6S", "KD", "9S" } ``` <!-- prettier-ignore --> ```javascript // Deck, face up, Six of Hearts (red) on top, Nine of Spades (black) on bottom [ "6H", "2C", "2D", "5S", "3D", "7S", "8D", "JS", "7D", "8C", "TD", "7C", "AH", "3C", "TH", "KS", "9H", "QS", "6D", "2S", "7H", "QC", "5H", "TS", "3H", "5C", "4D", "XB", "8H", "AC", "KH", "4C", "5D", "3S", "9D", "KC", "2H", "6C", "4H", "8S", "QD", "JC", "JH", "TC", "QH", "9C", "XR", "4S", "JD", "AS", "AD", "6S", "KD", "9S" ] ``` ```python # Deck, face up, Six of Hearts (red) on top, Nine of Spades (black) on bottom [ "6H", "2C", "2D", "5S", "3D", "7S", "8D", "JS", "7D", "8C", "TD", "7C", "AH", "3C", "TH", "KS", "9H", "QS", "6D", "2S", "7H", "QC", "5H", "TS", "3H", "5C", "4D", "XB", "8H", "AC", "KH", "4C", "5D", "3S", "9D", "KC", "2H", "6C", "4H", "8S", "QD", "JC", "JH", "TC", "QH", "9C", "XR", "4S", "JD", "AS", "AD", "6S", "KD", "9S" ] ``` <!-- prettier-ignore --> ```typescript // Deck, face up, Six of Hearts (red) on top, Nine of Spades (black) on bottom [ "6H", "2C", "2D", "5S", "3D", "7S", "8D", "JS", "7D", "8C", "TD", "7C", "AH", "3C", "TH", "KS", "9H", "QS", "6D", "2S", "7H", "QC", "5H", "TS", "3H", "5C", "4D", "XB", "8H", "AC", "KH", "4C", "5D", "3S", "9D", "KC", "2H", "6C", "4H", "8S", "QD", "JC", "JH", "TC", "QH", "9C", "XR", "4S", "JD", "AS", "AD", "6S", "KD", "9S" ] ``` then return: ```java "QNBSCTZQOLOBZNKOHUHGLQWLOK" ``` ```javascript "QNBSCTZQOLOBZNKOHUHGLQWLOK"; ``` ```python "QNBSCTZQOLOBZNKOHUHGLQWLOK" ``` ```typescript "QNBSCTZQOLOBZNKOHUHGLQWLOK"; ``` ## Decoding ```java String encrypted = "QNBSCTZQOLOBZNKOHUHGLQWLOK"; String[] deck = new String[] { "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" }; cardChameleon.decrypt(encrypted, deck); ``` <!-- prettier-ignore --> ```javascript const encrypted = "QNBSCTZQOLOBZNKOHUHGLQWLOK"; const deck = new [ "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" ]; cardChameleon.decrypt(encrypted, deck); ``` ```python encrypted = "QNBSCTZQOLOBZNKOHUHGLQWLOK" deck = [ "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" ] CardChameleon(message, deck).encrypt() ``` <!-- prettier-ignore --> ```typescript const encrypted = "QNBSCTZQOLOBZNKOHUHGLQWLOK"; const deck = new [ "2C", "6H", "5S", "7S", "JS", "8C", "7C", "2D", "3D", "8D", "3C", "KS", "QS", "2S", "7D", "TD", "QC", "TS", "AH", "5C", "XB", "TH", "AC", "9H", "6D", "4C", "7H", "3S", "5H", "KC", "3H", "6C", "4D", "8H", "KH", "8S", "JC", "5D", "TC", "9D", "2H", "9C", "4S", "4H", "QD", "AS", "JH", "6S", "QH", "9S", "XR", "JD", "AD", "KD" ]; cardChameleon.decrypt(encrypted, deck); ``` should return: ```java "ATTACK TONIGHT ON CODEWARS" ``` ```javascript "ATTACK TONIGHT ON CODEWARS"; ``` ```python "ATTACK TONIGHT ON CODEWARS" ``` ```typescript "ATTACK TONIGHT ON CODEWARS"; ``` # Have fun! I hope you will enjoy this kata! Feedbacks and translations are very welcome. # Further readings ## Key Length There are `54!` different possible permutations to order a deck of 54 cards, this is approximately equal to 2.3 x 10<sup>71</sup>, or [2<sup>237</sup>](https://www.wolframalpha.com/input/?i=log+base+2+of+54!) (so 237 bits of information). But different keys can lead to the same deck, once prepared. So the number of non-equivalent keys is equal to the number of possible pairs (`27!`) multiplied by the number of possible pairs permutations (`27!`). `(27!)²` is approximately equal to 1.2 x 10<sup>56</sup>, or 2<sup>186</sup>, so the real key length is **186 bits**. ## Initialization Vector _This is not implemented in this kata, and is here for information only._ In order to be secured, if the same key deck is used more than one time, a [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector) has to be generated every time and used to initialize the prepared deck before the encryption/decryption process. The IV contains each of the 27 characters arranged in a random order, and is transmitted as is with the encrypted text. The procedure to initialize the deck is as follow, with each character of the IV: 1. Find the black card in the deck corresponding to the character in the assignment table. 2. Look at the red card above this black card. Interpret it as a character in the assignment table. 3. Find the black card in the deck corresponding to this new character. 4. Exchange the red card above this black card with the one on the top of the deck. 5. Move the black card found at step 3 and the red card above it to the bottom. 6. Move the top two cards to the bottom. For more information, consult the Matthew McKague's [thesis](https://uwspace.uwaterloo.ca/bitstream/handle/10012/1141/memckagu2005.pdf).
algorithms
from string import ascii_uppercase class CardChameleon: __slots__ = ('deck', 'is_valid', 'text') ALPHABET = ascii_uppercase + ' ' BLACK_CARDS = [ rank + suit for suit in 'CS' for rank in 'A23456789TJQK'] + ['XB'] RED_CARDS = [ rank + suit for suit in 'DH' for rank in 'A23456789TJQK'] + ['XR'] TO_BLACK = dict(zip(ALPHABET, BLACK_CARDS)) FROM_BLACK = dict(zip(BLACK_CARDS, ALPHABET)) TO_RED = dict(zip(ALPHABET, RED_CARDS)) FROM_RED = dict(zip(RED_CARDS, ALPHABET)) def __init__(self, text: str, deck: list) - > None: self . is_valid = set(deck) == self . FROM_BLACK . keys( ) | self . FROM_RED . keys() and set(text) <= set(self . ALPHABET) self . deck = self . prepare(deck) if self . is_valid else deck self . text = text def prepare(self, deck) - > list: res = [''] * len(deck) black, red = [], [] for card in deck: (black if card in self . FROM_BLACK else red). append(card) res[0:: 2] = red res[1:: 2] = black return res def swap(self, i: int, j: int) - > None: self . deck[i], self . deck[j] = self . deck[j], self . deck[i] def shift(self, n: int) - > None: self . deck = self . deck[n:] + self . deck[: n] def encrypt(self) - > str or None: return self . __cipher(self . TO_BLACK, self . FROM_RED, mode=0) def decrypt(self) - > str or None: return self . __cipher(self . TO_RED, self . FROM_BLACK, mode=1) def __cipher(self, to_card: dict, from_card: dict, mode: int) - > str or None: if not self . is_valid: return None res = [] for char in self . text: swap_index = 0 for i in range(2): card = to_card[char] index = self . deck . index(card) + mode - 1 if i ^ mode: swap_index = index card = self . deck[index + mode] char = from_card[card] self . swap(0, swap_index), self . shift(2) res . append(char) return '' . join(res)
Card-Chameleon, a Cipher with Playing Cards
59c2ff946bddd2a2fd00009e
[ "Cryptography", "Games", "Algorithms" ]
https://www.codewars.com/kata/59c2ff946bddd2a2fd00009e
5 kyu
__Introduction__ We live in the woods. In the autumn, we have many leaves to rake... while the leaves keep falling... and we keep raking, over and over. In fact, we just keep raking until the first snow falls. The only reasonable way to dispose of these leaves is by burning them. We have limited space for the burn pile. So when the pile gets full of raked leaves -- and ONLY when it is full -- we have to burn the pile before we can continue to rake. Your task is to determine _how many times we can clear the entire yard of leaves before the first snow falls_. Sounds easy enough, but you have to take the weather into account: precipitation, wind speed, and wind direction. __Details__ You will complete the function rake_and_burn, which receives a list of lists as input. Each sublist represents a new day and contains the following parameters: - precipitation: This string will be either 'rain', 'snow', 'mist', or an empty string. - wind speed (in mph): This integer will have a random value between 0 and 16. - wind direction: This string represents the direction from which the wind is blowing. Possible values are 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', and 'NW'. When the burn pile is full (and ONLY when it is full), _raking stops_ until conditions are right for burning the pile. Those conditions: - It is not raining today and it did not rain yesterday. - The wind speed is less than or equal to 10 mph. - The wind is not blowing from the SW, S, or SE. (I have a close neighbor to the north with respiratory problems, so I don't want to blow smoke towards him.) When the pile is burned, it has the following effects: - The pile is burned down to nothing. (It becomes completely empty.) - Aside from tending the fire, I have enough time to rake one quarter of the yard. (These leaves do not add to the pile contents, because they are consumed immediately in the burning fire.) On a day when the pile is not burned, I will rake leaves, if the following conditions are met: - The burn pile is not full. - It is not raining today and it did not rain yesterday. - The wind speed is less than or equal to 12 mph. On days when I only rake: - I rake one third of the yard. - One half of the pile's capacity is added to its content. (In other words, the pile either goes from empty to half-full, or from half-full to full.) When the precipitation is 'snow', that marks the end of the season of raking and burning leaves. At this point, return the total number of times that the yard has been completely cleared of leaves, rounded down to an integer. There's no need to validate input; all input is valid. Fixed tests involve relatively short input (between 5 and 30 days), while random tests can include up to 60 days. The following example is admittedly lengthy, but not nearly as long as the actual raking/burning season! Don't feel obliged to read the whole thing if you don't need to; just read as much as necessary to see how the rules above are applied. __Example__ Here's a relatively short sample run of the program, with explanations. Day 1 ['rain', 2, 'N'] Precipitation is: rain Wind speed (mph) is: 2 Wind is out of the N No raking or burning today because of rain At end of day: Portion of yard currently completed: 0 /12 Portion of pile currently filled: 0 /12 Day 2 ['', 13, 'S'] No precipitation today Wind speed (mph) is: 13 Wind is out of the S No raking or burning today, because it rained yesterday and wind is too strong anyway. At end of day: Portion of yard currently completed: 0 /12 Portion of pile currently filled: 0 /12 Day 3 ['', 2, 'S'] No precipitation today Wind speed (mph) is: 2 Wind is out of the S Raking 1/3 of yard This increases the pile by 1/2 of its capacity At end of day: Portion of yard currently completed: 4 /12 Portion of pile currently filled: 6 /12 Day 4 ['', 0, 'NW'] No precipitation today Wind speed (mph) is: 0 Wind is out of the NW Raking 1/3 of yard This increases the pile by 1/2 of its capacity At end of day: Portion of yard currently completed: 8 /12 Portion of pile currently filled: 12 /12 Day 5 ['', 7, 'NW'] No precipitation today Wind speed (mph) is: 7 Wind is out of the NW Pile is FULL and conditions are right for burning Also raking 1/4 of yard At end of day: Portion of yard currently completed: 11 /12 Portion of pile currently filled: 0 /12 Day 6 ['rain', 10, 'S'] Precipitation is: rain Wind speed (mph) is: 10 Wind is out of the S No raking or burning today because of rain At end of day: Portion of yard currently completed: 11 /12 Portion of pile currently filled: 0 /12 Day 7 ['', 2, 'E'] No precipitation today Wind speed (mph) is: 2 Wind is out of the E No raking or burning today, because it rained yesterday At end of day: Portion of yard currently completed: 11 /12 Portion of pile currently filled: 0 /12 Day 8 ['', 9, 'NE'] No precipitation today Wind speed (mph) is: 9 Wind is out of the NE Raking 1/3 of yard This increases the pile by 1/2 of its capacity Raked the whole yard, so increment the result value At end of day: Portion of yard currently completed: 3 /12 (because 15/12 - 12/12 = 3/12) Portion of pile currently filled: 6 /12 Day 9 ['', 0, 'SE'] No precipitation today Wind speed (mph) is: 0 Wind is out of the SE Raking 1/3 of yard This increases the pile by 1/2 of its capacity At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 10 ['', 12, 'N'] No precipitation today Wind speed (mph) is: 12 Wind is out of the N Wind is too strong for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 11 ['', 5, 'S'] No precipitation today Wind speed (mph) is: 5 Wind is out of the S Wind is from wrong direction for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 12 ['', 11, 'E'] No precipitation today Wind speed (mph) is: 11 Wind is out of the E Wind is too strong for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 13 ['', 16, 'W'] No precipitation today Wind speed (mph) is: 16 Wind is out of the W Wind is too strong for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 14 ['rain', 16, 'SE'] Precipitation is: rain Wind speed (mph) is: 16 Wind is out of the SE No raking or burning today because of rain At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 15 ['', 0, 'S'] No precipitation today Wind speed (mph) is: 0 Wind is out of the S No raking or burning today, because it rained yesterday At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 16 ['', 11, 'S'] No precipitation today Wind speed (mph) is: 11 Wind is out of the S Wind is from wrong direction for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 12 /12 Day 17 ['', 4, 'NE'] No precipitation today Wind speed (mph) is: 4 Wind is out of the NE Pile is FULL and conditions are right for burning Also raking 1/4 of yard At end of day: Portion of yard currently completed: 10 /12 Portion of pile currently filled: 0 /12 Day 18 ['', 14, 'W'] No precipitation today Wind speed (mph) is: 14 Wind is out of the W Wind is too strong for raking At end of day: Portion of yard currently completed: 10 /12 Portion of pile currently filled: 0 /12 Day 19 ['', 12, 'E'] No precipitation today Wind speed (mph) is: 12 Wind is out of the E Raking 1/3 of yard This increases the pile by 1/2 of its capacity Raked the whole yard, so increment the result value At end of day: Portion of yard currently completed: 2 /12 (because 14/12 - 12/12 = 2/12) Portion of pile currently filled: 6 /12 Day 20 ['', 12, 'SE'] No precipitation today Wind speed (mph) is: 12 Wind is out of the SE Raking 1/3 of yard This increases the pile by 1/2 of its capacity At end of day: Portion of yard currently completed: 6 /12 Portion of pile currently filled: 12 /12 Day 21 ['', 8, 'SW'] No precipitation today Wind speed (mph) is: 8 Wind is out of the SW Wind is from wrong direction for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 6 /12 Portion of pile currently filled: 12 /12 Day 22 ['', 3, 'SE'] No precipitation today Wind speed (mph) is: 3 Wind is out of the SE Wind is from wrong direction for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 6 /12 Portion of pile currently filled: 12 /12 Day 23 ['', 11, 'NE'] No precipitation today Wind speed (mph) is: 11 Wind is out of the NE Wind is too strong for burning, and raking can not proceed until burning At end of day: Portion of yard currently completed: 6 /12 Portion of pile currently filled: 12 /12 Day 24 ['', 9, 'W'] No precipitation today Wind speed (mph) is: 9 Wind is out of the W Pile is FULL and conditions are right for burning Also raking 1/4 of yard At end of day: Portion of yard currently completed: 9 /12 Portion of pile currently filled: 0 /12 Day 25 ['', 15, 'W'] No precipitation today Wind speed (mph) is: 15 Wind is out of the W Wind is too strong for raking At end of day: Portion of yard currently completed: 9 /12 Portion of pile currently filled: 0 /12 Day 26 ['', 15, 'NW'] No precipitation today Wind speed (mph) is: 15 Wind is out of the NW Wind is too strong for raking At end of day: Portion of yard currently completed: 9 /12 Portion of pile currently filled: 0 /12 Day 27 ['', 7, 'SW'] No precipitation today Wind speed (mph) is: 7 Wind is out of the SW Raking 1/3 of yard This increases the pile by 1/2 of its capacity Raked the whole yard, so increment the result value At end of day: Portion of yard currently completed: 1 /12 (because 13/12 - 12/12 = 1/12) Portion of pile currently filled: 6 /12 Day 28 ['', 6, 'E'] No precipitation today Wind speed (mph) is: 6 Wind is out of the E Raking 1/3 of yard This increases the pile by 1/2 of its capacity At end of day: Portion of yard currently completed: 5 /12 Portion of pile currently filled: 12 /12 Day 29 ['', 3, 'N'] No precipitation today Wind speed (mph) is: 3 Wind is out of the N Pile is FULL and conditions are right for burning Also raking 1/4 of yard At end of day: Portion of yard currently completed: 8 /12 Portion of pile currently filled: 0 /12 Day 30 ['', 14, 'NE'] No precipitation today Wind speed (mph) is: 14 Wind is out of the NE Wind is too strong for raking At end of day: Portion of yard currently completed: 8 /12 Portion of pile currently filled: 0 /12 Day 31 ['', 3, 'NW'] No precipitation today Wind speed (mph) is: 3 Wind is out of the NW Raking 1/3 of yard This increases the pile by 1/2 of its capacity Raked the whole yard, so increment the result value At end of day: Portion of yard currently completed: 0 /12 (because 12/12 - 12/12 = 0/12) Portion of pile currently filled: 6 /12 Day 32 ['', 1, 'NW'] No precipitation today Wind speed (mph) is: 1 Wind is out of the NW Raking 1/3 of yard This increases the pile by 1/2 of its capacity At end of day: Portion of yard currently completed: 4 /12 Portion of pile currently filled: 12 /12 Day 33 ['', 4, 'N'] No precipitation today Wind speed (mph) is: 4 Wind is out of the N Pile is FULL and conditions are right for burning Also raking 1/4 of yard At end of day: Portion of yard currently completed: 7 /12 Portion of pile currently filled: 0 /12 Day 34 ['', 6, 'SE'] No precipitation today Wind speed (mph) is: 6 Wind is out of the SE Raking 1/3 of yard This increases the pile by 1/2 of its capacity At end of day: Portion of yard currently completed: 11 /12 Portion of pile currently filled: 6 /12 Day 35 ['snow', 11, 'N'] Precipitation is: snow Wind speed (mph) is: 11 Wind is out of the N First snow! Whole yard was cleaned up 4 times! <-- Return this value
reference
def rake_and_burn(days): rain = yard = pile = 0 for p, ws, wd in days: if p == 'snow': return yard / / 12 if p != 'rain' and not rain: if pile == 2 and ws <= 10 and 'S' not in wd: pile = 0 yard += 3 elif pile < 2 and ws <= 12: pile += 1 yard += 4 rain = p == 'rain'
Autumn Ritual: Rake and Burn
653db02b1eca91b474817307
[]
https://www.codewars.com/kata/653db02b1eca91b474817307
7 kyu
Crazy rabbit is in a coffee field with boundries in an initial given cell (`pos = 0` in example). Each field cell might have coffee beans. ```bash | | |R____________| 2 2 4 1 5 2 7 # Crazy rabbit at the start" ``` Crazy rabbit eats all coffee beans that available in the cell. And his jump power increases. Total jump power is equal to the number of **total** beans eaten ```bash | | |R____________| 0 2 4 1 5 2 7 # Crazy rabbit eat coffee beans and his jump power is now 2 ``` Crazy rabbit jumps (initially to the right) if he has a jump power. ```bash _ | / \ | |R___↓________| 0 2 4 1 5 2 7 #Crazy rabbit jumps to next position ``` Crazy rabbit bounces back from a boundries if he jumps too strong ```bash ___ | / \ | | / \| | / / | |____R_____↓__| 0 2 0 1 5 2 7 # next jump will have power of 6, because he ate 4 more coffee beans) ``` Crazy rabbit position in a field cell is always in the middle. That means that if Crazy rabbit stays right next to the border and have power of jump `= 1` then he will be bounced back to the same positon. After hitting a boundry Crazy rabbit jumps in an opposite direction. You will be given: - a field as a list (linear array) of numbers Can Crazy rabbit eat all the beans? return `boolean`
reference
import copy # Modifica el poder de salto y el arreglo según la dirección de salto e índice dado def Jump(): global jumpPower, array, index, direction, length global indexSequense, jumpPowerSequense, arraySequense, directionSequense global contador jumpPower += array[index] array[index] = 0 jumpPowerSequense . append(jumpPower) directionSequense . append(direction) if direction < 0: array . reverse() arraySequense . append(copy . deepcopy(array)) array . reverse() indexSequense . append(length - index - 1) else: arraySequense . append(copy . deepcopy(array)) indexSequense . append(index) # Calcula el próximo índice y dirección (izq o der), según el poder de salto e índice actual def NextIndex(): global jumpPower, array, index, direction, length, contador index += jumpPower q = index / / length if q > 0: direction *= (- 1) * * q if q % 2 == 1: array . reverse() index = index % length else: index = index % length contador += 1 # print(f"\nEstado # {contador}: {newState}\n{arraySequense}") # Personaliza las condiciones iniciales def InitialConditions(ARRAY, START): global jumpPower, array, index, direction, length global indexSequense, jumpPowerSequense, arraySequense, directionSequense global states, newState, contador array = ARRAY length = len(array) # indice inicial (cualquier índice positivo y menor que length) index = START jumpPower = 0 # poder de salto inicial (cualquier entero positivo) # dirección inicial (1 si coienza hacia la derecha y -1 si comienza hacia la izquierda) direction = 1 indexSequense = [index] jumpPowerSequense = [jumpPower] arraySequense = [copy . deepcopy(array)] directionSequense = [direction] states = set() contador = 0 newState = (indexSequense[0], jumpPowerSequense[0], directionSequense[0]) # print(f"\nEstado # {contador}: {newState}\n{arraySequense}") # Determina si el conejo termina o se queda estancado (funciona para arrays solo con naturales) # el primer argumento es el campo o arreglo y el segundo será la posición inicial del conejo def crazy_rabbit(field, cr): global jumpPower, array, index, direction, length global indexSequense, jumpPowerSequense, arraySequense, directionSequense global states, newState InitialConditions(field, cr) while newState not in states: states . add(newState) Jump() newState = (indexSequense[- 1], jumpPowerSequense[- 1], directionSequense[- 1]) NextIndex() # Aplica solo para un arreglo de naturales if sum(array) == 0: return True else: return False
Crazy rabbit
6532414794f1d24774f190ae
[]
https://www.codewars.com/kata/6532414794f1d24774f190ae
5 kyu
The musical scales are constructed by a series of whole tones (W) and half tones (H). Between each two notes we have a whole tone, except for E to F and B to C that we have a half tone. For the major scale with key (root note) in C (C D E F G A B) we have the following mode (distances formula): W W H W W W H If we want to change the key we must to keep the same distances pattern, then we should use accidentals bemols or sharps (b or #) in order to decrease o increase a note by half tone, for example if we change the root of the major scale to D the result is D E F# G A B C# that keeps the W W H W W W H notes distances pattern. In this kata you have to code a function that allow us to get a scale given a mode and a key note. For example for ```get_scale('W W H W W W H', 'C')``` we should get as result ```['C', 'D', 'E', 'F', 'G', 'A', 'B']``` . If we change the key, for example ```get_scale('W W H W W W H', 'D')``` we should get as result ```['D', 'E', 'F#', 'G', 'A', 'B', 'C#']```, that follows the same distances pattern but starting with the D note. ![alt text](https://preview.ibb.co/niXKWk/Captura_de_pantalla_2017_08_28_a_las_19_53_59.png) If we change the pattern , for example ```get_scale('W H W W H W W', 'C')``` whe should get as result ```['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb']```, that is a different scale in the case the Aeolian or minor scale. [In this link you have additional information on how circle of fifths works!](http://randscullard.com/CircleOfFifths/) To get the same distances we also can provide a solution applying the opposite accidental over the previous or following note, for example an alternative solution for ```['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb']``` is ```['C', 'D', 'D#', 'F', 'G', 'G#', 'A#']```, that is Eb = D# , Ab = G# and Bb = A#. But in this kata we want to mantain the notes notation sequence.
algorithms
steps_up = { 'Cb': ('Dbb', 'Db'), 'C': ('Db', 'D'), 'C#': ('D', 'D#'), 'Db': ('Ebb', 'Eb'), 'D': ('Eb', 'E'), 'D#': ('E', 'E#'), 'Eb': ('Fb', 'F'), 'E': ('F', 'F#'), 'E#': ('F#', 'FX'), 'Fb': ('Gbb', 'Gb'), 'F': ('Gb', 'G'), 'F#': ('G', 'G#'), 'Gb': ('Abb', 'Ab'), 'G': ('Ab', 'A'), 'G#': ('A', 'A#'), 'Ab': ('Bbb', 'Bb'), 'A': ('Bb', 'B'), 'A#': ('B', 'B#'), 'Bb': ('Cb', 'C'), 'B': ('C', 'C#'), 'B#': ('C#', 'CX') } def get_scale(mode, note): return [ note] + [(note := steps_up[note][step == 'W']) for step in mode . split()[: - 1]]
Musical Scales and Modes
59a07c8810963911ca000090
[ "Algorithms" ]
https://www.codewars.com/kata/59a07c8810963911ca000090
6 kyu
Consider the following array: ``` [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...] ``` If we join these blocks of numbers, we come up with an infinite sequence which starts with `112123123412345123456...`. The list is infinite. You will be given an number (`n`) and your task will be to return the element at that index in the sequence, where `1 ≤ n ≤ 10^18`. Assume the indexes start with `1`, not `0`. For example: ``` solve(1) = 1, because the first character in the sequence is 1. There is no index 0. solve(2) = 1, because the second character is also 1. solve(3) = 2, because the third character is 2. ``` More examples in the test cases. Good luck!
reference
def solve(n): def length(n): s = 0 for i in range(20): o = 10 * * i - 1 if o > n: break s += (n - o) * (n - o + 1) / / 2 return s def binary_search(k): n = 0 for p in range(63, - 1, - 1): if length(n + 2 * * p) < k: n += 2 * * p return n def sequence(n): if n < 10: return n for i in range(1, 19): segment = i * 9 * 10 * * (i - 1) if n <= segment: return str(10 * * (i - 1) + (n - 1) / / i)[(n - 1) % i] else: n -= segment return int(sequence(n - length(binary_search(n))))
Block sequence
5e1ab1b9fe268c0033680e5f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5e1ab1b9fe268c0033680e5f
4 kyu
### Tim's Fruit Shop Challenge Tim runs a fruit shop, and he has a unique way of processing orders. Customers send orders in a specific format: they specify the number of fruit units they want, followed by a lowercase letter (a-z) representing the fruit itself. For example, '30a4b' means 30 apples and 4 bananas. Tim's task is to organize these orders into packages. Here's how he does it: Every 10 units of a fruit go into a box, represented by {a}. Every 5 boxes are stacked into a pallet, represented by [a]. Any remaining units are put into a bag, enclosed by (). Then he prepares every order in a 3 tier shelf (list) with the pallets on the lower tier, the boxes on medium tier and the bags on the upper tier. the items will be pushed to the right and the empy space filled with '-' ### Explained example: '63a21b' = '63a' : 50 * 1 + 10 * 1 + 3 -> '[a]{a}(aaa)' + '21b' : 50 * 0 + 10 * 2 + 1 -> '{b}{b}(b)' '63a21b' -> '[a]{a}(aaa){b}{b}(b)' Then the products should be stored in the shelf as follows: ['-(aaa)(b)', '{a}{b}{b}', '------[a]'] You will help Tim prepare or the daily orders in shelves. ### Input A list containing all the orders for the day. It will be a list of strings. Each order(string) containing maximun one repetition of each fruit (letter from a to z) preceded by the corresponding amount. The list will contain at least one amount item combination ### output A list containing a list for each shelf containing a list for each tier ### Examples: [['-(aaa)(b)', ["63a21b"] -> '{a}{b}{b}', '------[a]']] [['---', ['10a'] -> '{a}', '---']] [['(bbb)', '--{a}', ['10a3b', '64j1k92i'] -> '-----'], ['--(jjjj)(k)(ii)', '{j}{i}{i}{i}{i}', '---------[j][i]']]
reference
import re def fruit_pack(orders): arr = [] for order in orders: shelf = ['', '', ''] for num, fruit in re . findall('(\d+)(\D)', order): pallet, box, bag = int(num) / / 50, (int(num) % 50) / / 10, int(num) % 10 if pallet: shelf[2] += ('[' + fruit + ']') * pallet if box: shelf[1] += ('{' + fruit + '}') * box if bag: shelf[0] += ('(' + fruit * bag + ')') m = max(map(len, shelf)) arr . append([x . rjust(m, '-') for x in shelf]) return arr
Tim's Fruit Shop Challenge
652643925c042100247fffc6
[ "Algorithms" ]
https://www.codewars.com/kata/652643925c042100247fffc6
6 kyu
You are running a race on a circular race track against the ghost of your past self. Each time you lap your ghost, you get a confidence boost because you realize how much faster you got. Given your speed (km/h), your ghosts speed (km/h), the length of the circular race track (km) and the time you run (h), predict how often you will lap your ghost. Lapping your ghost means going from being behind your ghost to being in front of your ghost.
games
from math import ceil def number_lappings(my_speed, ghost_speed, time, round_length): if my_speed <= ghost_speed: return 0 return ceil((my_speed - ghost_speed) * time / round_length) - 1
Outrun your past self
6525caefd77c582baf678ddf
[ "Puzzles", "Mathematics" ]
https://www.codewars.com/kata/6525caefd77c582baf678ddf
7 kyu
A number is Esthetic if, in any base from `base2` up to `base10`, the absolute difference between every pair of its adjacent digits is constantly equal to `1`. ``` num = 441 (base10) // Adjacent pairs of digits: // |4, 4|, |4, 1| // The absolute difference is not constant // 441 is not Esthetic in base10 441 in base4 = 12321 // Adjacent pairs of digits: // |1, 2|, |2, 3|, |3, 2|, |2, 1| // The absolute difference is constant and is equal to 1 // 441 is Esthetic in base4 ``` Given a positive integer `num`, implement a function that returns an array containing the bases (as integers from 2 up to 10) in which `num` results to be Esthetic, or an empty array `[]` if no base makes `num` Esthetic. ### Examples ``` 10 ➞ [2, 3, 8, 10] // 10 in base2 = 1010 // 10 in base3 = 101 // 10 in base8 = 12 // 10 in base10 = 10 23 ➞ [3, 5, 7, 10] // 23 in base3 = 212 // 23 in base5 = 43 // 23 in base7 = 32 // 23 in base10 = 23 666 ➞ [8] // 666 in base8 = 1232 ```
reference
from gmpy2 import digits def esthetic(num, max_base=10): return [base for base in range(2, max_base + 1) if (dig := digits(num, base)) and all(abs(int(a) - int(b)) == 1 for a, b in zip(dig, dig[1:]))]
Esthetic Numbers
6523a71df7666800170a1954
[]
https://www.codewars.com/kata/6523a71df7666800170a1954
7 kyu
The principle is pretty simple: - Given a integer (n) - Find the next palindromic number after (excluding) n Implement this in the function nextPalin However, due to some constraints, the implementation is not: - 0 < n < 10^1000 - 0 < t < 0.175s <h3>A.K.A</h3> - n is between 1 and 1001 digits - total time for all test cases should be less than 0.175s (175ms) This means that you cannot do: ~~~if:python ```python def next_palin(n): while not is_palin(n): #is_palin() defined elsewhere n += 1 return n ``` ~~~ ~~~if:cpp ```cpp int nextPalin(int n) { for (;!isPalin(n);++n); return n; } ``` ~~~ ```javascript function nextPalin(n) { while (!isPalin(n)) n += 1n; // isPalin(n) is defined elsewhere return n; } ``` For example: ``` 12345 -> 12421 11 -> 22 134 -> 141 9876543219123456789 -> 9876543220223456789 ``` There are 322 test cases (excluding time constraint, which is not included in assertion), so optimization is very important ~~~if:javascript **JS: The input and output will be in the form of BigInt** ~~~
algorithms
def next_palin(n): s = str(n) l = len(s) h = l / / 2 r = l % 2 t = s[: h + r] + s[: h][:: - 1] if t > s: return int(t) elif t == '9' * l: return 10 * * l + 1 else: m = str(int(s[: h + r]) + 1) return int(m + m[: h][:: - 1])
Next Palindrome (Large Numbers 0 - 10^1000)
6521bbf23256e8e5801d64f1
[ "Algorithms", "Mathematics", "Performance" ]
https://www.codewars.com/kata/6521bbf23256e8e5801d64f1
6 kyu
Given a set of integers _S_, the _closure of S under multiplication_ is the smallest set that contains _S_ and such that for any _x, y_ in the closure of _S_, the product _x * y_ is also in the closure of _S_. Example 1: Given `S = {2}`, the closure of `S` is the set `{2, 4, 8, 16, 32, 64, ... }`. Example 2: Given `S = {1, 2, 3}`, the closure of `S` is the set `{1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 27, 32, 36, ...}`. This set contains, e.g, `6` because `6 = 2 * 3`. It further contains `12` and `18` because `12 = 2 * 6` and `18 = 3 * 6`. Etc. Example 3: Given `S` the set of prime numbers, the closure of `S` is the set of all positive integers greater than or equal to `2`. Your task is two write a generator function that generates the members of the closure of any given _finite_ set of positive numbers `S` in _ascending order_.
algorithms
from heapq import heappush, heappop def closure_gen(* s): q = sorted(s) m = set(s) while q: curr = heappop(q) yield curr for i in s: t = curr * i if t not in m: heappush(q, t) m . add(t)
Set Closure Generator
58febc23627d2f48de000060
[ "Streams", "Algorithms" ]
https://www.codewars.com/kata/58febc23627d2f48de000060
4 kyu
To solve this kata, you need to create a character class that can be used for a roguelike game. Instances of this class must have the characteristics strength, dexterity and intelligence and can call some test-generated methods that will change these characteristics or give the character a new weapon. The Character class must have 2 mandatory instance methods - one will display character information and the other will display the event log. Only these output methods will be checked by tests The names of the properties or how the user stores any values is entirely up to the user and individual properties will not be checked. Character - The character has a `name` and 3 main characteristics: `strength`, `dexterity`, `intelligence`. Name and characteristics are set randomly when creating a character; if some characteristic is not specified, then the default value is taken equal to `10`, name default value is `'Hero'`. Initially, the character is armed only with his `'limbs'`(lowercase), the damage from which is equal to the sum of his characteristics. ```ruby ch = Character.new(name: 'Kroker', strength: 15, intelligence: 7) ``` ```javascript const ch = new Character({name: 'Kroker', strength: 15, intelligence: 7}); ``` ```python ch = Character(name='Kroker', strength=15, intelligence=7) ``` ```dart dynamic ch = Character(name: 'Kroker', strength: 15, intelligence: 7); ``` The method giving the character's info returns a multiline string. Let's check, the missing characteristic will be equal to 10, and the weapon will be `'limbs'` ```ruby puts ch.character_info #=> "Kroker\nstr 15\ndex 10\nint 7\nlimbs 32 dmg" ``` ```javascript console.log(ch.characterInfo()); //=> `Kroker\nstr 15\ndex 10\nint 7\nlimbs 32 dmg` ``` ```python print(ch.character_info()) #=> "Kroker\nstr 15\ndex 10\nint 7\nlimbs 32 dmg" ``` ```dart print(ch.characterInfo()); //=> "Kroker\nstr 15\ndex 10\nint 7\nlimbs 32 dmg" ``` ``` Kroker str 15 dex 10 int 7 limbs 32 dmg ``` The character finds a weapon - Weapons can be found using an instance method, the name of which is the name of the weapon. The name of the weapon method can be anything, but always consists of 3 words: the type of weapon (for example, "axe"), the word "of" and the property of the weapon (for example, "fire"). ```ruby ch.axe_of_fire(3, 1, 0, 20) # weapon method name can be anything as long as it matches weapon_of_something ``` ```javascript ch.axeOfFire(3, 1, 0, 20); // weapon method name can be anything as long as it matches weaponOfSomething ``` ```python ch.axe_of_fire(3, 1, 0, 20) # weapon method name can be anything as long as it matches weapon_of_something ``` ```dart ch.axeOfFire(3, 1, 0, 20); // weapon method name can be anything as long as it matches weaponOfSomething ``` Weapon damage is set by parameters passed to the method, which give damage depending on characteristics and additional damage.(always the order: strength, dexterity, intellect, extra damage), the number of parameters are always 4. In this case, the Axe of fire has parameters `3, 1, 0, 20`. This means that the damage from this weapon will be calculated according to the formula ```math 3 \times strength + 1 \times dexterity + 0 \times intelligence + 20 = 3 \times 15 + 1 \times 10 + 0 \times 7 + 20 = 75 ``` The weapon and its total damage should appear in the character info output. Damage computation calculation, hence the output of the character info thing is done with the stats of the Character at call time. Since the `'Axe of fire'`, unlike the `'limbs'`, is a name, it must be capitalized ``` Kroker str 15 dex 10 int 7 Axe of fire 75 dmg ``` All events with found weapons go into the event log ```ruby puts ch.event_log ``` ```javascript console.log(ch.eventLog()); ``` ```python print(ch.event_log()) ``` ```dart print(ch.eventLog()); ``` ``` Kroker finds 'Axe of fire' ``` The character finds another weapon that will do more damage - The character should always choose the weapon with the highest damage, if he received a stronger weapon, If 2 weapons have the same damage, then choose the first one in alphabetical order. ```ruby ch.staff_of_water(1, 0, 2, 60) ``` ```javascript ch.staffOfWater(1, 0, 2, 60); ``` ```python ch.staff_of_water(1, 0, 2, 60) ``` ```dart ch.staffOfWater(1, 0, 2, 60); ``` Staff of water has 89 damage`(1 * 15 + 0 * 10 + 7 * 2 + 60)` this is more than the 'Axe of fire', which means we need to change weapons. ``` Kroker str 15 dex 10 int 7 Staff of water 89 dmg ``` The character retains all the weapons found, that is, although we replaced the 'Axe of fire' with the 'Staff of water', the 'Axe of fire' will remain in the character’s inventory Enhancement - If a character has 2 weapons with the same name, then he enhances one of them and destroys the other. ```ruby ch.axe_of_fire(1, 2, 1, 10) ``` ```javascript ch.axeOfFire(1, 2, 1, 10); ``` ```python ch.axe_of_fire(1, 2, 1, 10) ``` ```dart ch.axeOfFire(1, 2, 1, 10); ``` Now there are 2 'Axe of fire', so let’s enhance one of them by destroying the other one. The enhancement will make each damage parameter maximum from those of the 2 original weapons. ```math (3, 1, 0, 20) and (1, 2, 1, 10) \Rightarrow (max(3,1), max(1,2), max(0,1), max(20,10)) \Rightarrow (3, 2, 1, 20) ``` The character info output shows enhanced weapons. In the output, `'(enhanced)'` is added to the name of the improved weapon ``` Kroker str 15 dex 10 int 7 Axe of fire(enhanced) 92 dmg ``` For the new enhancement, an `'(enhanced)'` weapon is considered the same as a non-enhanced weapon with the same name. For example: from `'Axe of fire(enhanced)'` and new `'Axe of fire'` we will make an enhancement and get new `'Axe of fire(enhanced)'` Random events that changes characteristics - Character characteristics can be affected by random events. An event occurs using an instance method, the name of which is the name of the event, and the parameters (the order is always: strength, dexterity, intelligence; quantity is always 3) are stat modifiers ```ruby ch.strange_fruit(-2, 0, 2) ``` ```javascript ch.strangeFruit(-2, 0, 2); ``` ```python ch.strange_fruit(-2, 0, 2) ``` ```dart ch.strangeFruit(-2, 0, 2); ``` The 'Strange fruit' does not change dexterity, as the 2nd coefficient is 0, but it adds -2 strength and +2 intelligence. The character should always choose the weapon with the highest damage; if a random event changed characteristics so that some weapon from the previously found one became stronger than the one equipped, then you need to change to a stronger one from the inventory. Accordingly, we change the 'Axe of fire(enhanced)' back to the 'Staff of water' ``` Kroker str 13 dex 10 int 9 Staff of water 91 dmg ``` All random events end up in the event log. For random events, you do not need to specify modifiers equal to 0, but only those that changed the character's characteristics. Event log displays all events in order - Event log method returns all events as a string. Each event on a new line. ```ruby puts ch.event_log ``` ```javascript console.log(ch.eventLog()); ``` ```python print(ch.event_log()) ``` ```dart print(ch.eventLog()); ``` ``` Kroker finds 'Axe of fire' Kroker finds 'Staff of water' Kroker finds 'Axe of fire' Strange fruit: strength -2, intelligence +2 ```
games
class Weapon: def __init__(self, factors): self . factors = factors self . enhanced = False def enhance(self, factors): self . factors = [max(a, b) for a, b in zip(self . factors, factors)] self . enhanced = True def damage(self, characteristics): return sum(c * f for c, f in zip(characteristics, self . factors)) + self . factors[3] class Character: def __init__(self, name='Hero', strength=10, dexterity=10, intelligence=10): self . name = name self . characteristics = [strength, dexterity, intelligence] self . weapons = {'limbs': Weapon([1, 1, 1, 0])} self . _best_weapon = None self . log = [] def __getattr__(self, method): def wrapper(* args): name = method . replace('_', ' '). capitalize() if len(args) == 4: self . find_weapon(name, args) else: self . manage_event(name, args) return wrapper def character_info(self) - > str: weapon = self . weapons[self . best_weapon] return '\n' . join([self . name, * [f' { c } { v } ' for c, v in zip(['str', 'dex', 'int'], self . characteristics)], f' { self . best_weapon }{[ "" , "(enhanced)" ][ weapon . enhanced ]} { weapon . damage ( self . characteristics )} dmg']) def event_log(self) - > str: return '\n' . join(self . log) def find_weapon(self, name, factors): if name in self . weapons: self . weapons[name]. enhance(factors) else: self . weapons[name] = Weapon(factors) self . _best_weapon = None self . log . append(f" { self . name } finds ' { name } '") @ property def best_weapon(self): if self . _best_weapon is None: self . _best_weapon = min(self . weapons . keys( ), key=lambda n: (- self . weapons[n]. damage(self . characteristics), n)) return self . _best_weapon def manage_event(self, name, modifiers): self . characteristics = [c + m for c, m in zip(self . characteristics, modifiers)] self . _best_weapon = None self . log . append(f' { name } : ' + ', ' . join(f' { c } { m : + } ' for c, m in zip(['strength', 'dexterity', 'intelligence'], modifiers) if m))
Roguelike game 1 - stats and weapon
651bfcbd409ea1001ef2c3cb
[ "Puzzles", "Games", "Object-oriented Programming", "Metaprogramming" ]
https://www.codewars.com/kata/651bfcbd409ea1001ef2c3cb
5 kyu
When two blocks of the same "type" are adjacent to each other, the entire contiguous block disappears (pops off). If this occurs, this can allow previously separated blocks to be in contact with each other, setting off a chain reaction. After each pop, the remaining items get pushed back before popping the next consecutive items. This will continue until each block is surrounded by a different block. If the first round has multiple poppable blocks, **pop starting from the left**. Here's a demonstration: ``` ["A", "B", "C", "C", "B", "D", "A"] // The two adjacent Cs pop off ["A", "B", "B", "D", "A"] // Two adjacent Bs pop off ["A", "D", "A"] // No more blocks can be popped off ``` Another demonstration: ``` ["A", "B", "A", "A", "A", "B", "B"] # The three adjacent As will pop off # (before the two adjacent Bs) ["A", "B", "B", "B"] # 3 adjacent Bs pop off ["A"] # Final result ``` ### Examples ``` ["B", "B", "A", "C", "A", "A", "C"] ➞ ["A"] ["B", "B", "C", "C", "A", "A", "A"] ➞ [] ["C", "A", "C"] ➞ ["C", "A", "C"] ['ab', 'ab', 'cd', 'cx', 'B'], ['cd', 'cx', 'B'] [] ➞ [] ``` ### Notes - 0 <= len(lst) <= 500 - Blocks may consist of several characters.
reference
def pop_blocks(lst): stk, popping = [], None for v in lst: if v == popping: continue if stk and stk[- 1] == v: popping = stk . pop() else: stk . append(v) popping = None return stk
Popping Blocks
651bfcbcdb0e8b104175b97e
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/651bfcbcdb0e8b104175b97e
6 kyu
You are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. There won't be any `0` in the given list. Find out the state of the `asteroids` after all collisions. If two `asteroids` meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. ### Examples ``` ([-2, -1, 1, 2]) ➞ [-2, -1, 1, 2] ([-2, 1, 1, -2]) ➞ [-2, -2] ([1, 1, -2, -2]) ➞ [-2, -2] ([10, 2, -5]) ➞ [10] ([8, -8]) ➞ [] ([]) ➞ [] ``` ### Notes - 0 <= len(asteroids) <= 200
reference
def asteroid_collision(asteroids): i = 0 while i < len(asteroids): if asteroids[i] > 0: if i + 1 < len(asteroids) and asteroids[i + 1] < 0: s = asteroids[i] + asteroids[i + 1] if s > 0: asteroids . pop(i + 1) else: asteroids . pop(i) if s == 0: asteroids . pop(i) i -= 1 if i >= 0: continue i += 1 return asteroids
Asteroid Collision
651ab89e80f7c46fc482ba12
[]
https://www.codewars.com/kata/651ab89e80f7c46fc482ba12
6 kyu
### Finding a Binary Tree from Traversals A binary tree is a tree where each node has either 0, 1 or 2 children. Such a tree is usually represented recursively using a class where each node has a value and left and right subtrees (either of which can be None). ``` class TreeNode: def __init__(self, value, left = None, right = None): self.value = value self.left = left self.right = right ``` For example, *TreeNode(1, TreeNode(2, TreeNode(4), None), TreeNode(3, TreeNode(5, None, None), TreeNode(6, None, None)))* represents the tree below. The *None*'s can be omitted, as in *TreeNode(4)*. ``` 1 / \ 2 3 / / \ 4 5 6 ``` ### Traversals A tree can be traversed in various ways. The **in-order traversal** visits the left child of each node, then the node itself, then its right child. For example, the in-order traversal of the tree above is 4 2 1 5 3 6. Different trees can have the same in-order traversal. For example, the in-order traversal of the tree below is also 4 2 1 5 3 6. ``` 3 / \ 1 6 / \ 2 5 / 4 ``` The **post-order traversal** visits the left child first, then the right child, then the node itself. For example, the post-order traversal of the first tree is 4 2 5 6 3 1, while the post-order traversal of the second tree is 4 2 5 1 6 3. Different trees can have the same post-order traversal. Although neither the in-order traversal nor the post-order traversal identify the tree, the combination of the two does. ### Task Reconstruct a tree from its in-order and post-order traversals. Input: Two lists of integers, the first containing the in-order traversal and the second the post-order traversal of a particular tree. Each list will have no duplicate values, so each node is identifiable. Output: Return the tree whose in-order and post-order traversals match the given values. Subtrees that are *None* can be omitted or included. ### Examples *build_tree([4, 2, 1, 5, 3, 6], [4, 2, 5, 6, 3, 1])* should return *TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3, TreeNode(5), TreeNode(6)))*, or an equivalent representation of the first tree above. *build_tree([4, 2, 1, 5, 3, 6], [4, 2, 5, 1, 6, 3])* should return *TreeNode(3, TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(5)), TreeNode(6))*, the second tree above. ### Random Tests There are 2 types of random tests: (1) 100 random trees containing from 0 to 15 nodes. (2) Five random trees of 150,000 nodes. To avoid timing out, the solution must be faster than O(n^2). (The tests set the recursion limit high, so recursive solutions are fine.) Thanks to Blind4Basics for his work on this. ### Other Thoughts There is also a **pre-order traversal**: Visit the node before visiting its left child and then its right child. One might wonder whether the in-order and pre-order traversals determine the tree. How about the pre-order and post-order traversals? Other kata related to binary tree traversals include [Perfect Binary Tree Traversal: BFS to DFS](https://www.codewars.com/kata/64ebbfc4f1294ff0504352be), [Binary Tree Traversal](https://www.codewars.com/kata/5268956c10342831a8000135), and [Binary Tree Serpentine Traversal](https://www.codewars.com/kata/5268988a1034287628000156).
algorithms
from preloaded import TreeNode def build_tree(inorder, postorder): if not inorder or not postorder: return None # Create a hashmap to store the indices of elements in the inorder list idx_map = {val: idx for idx, val in enumerate(inorder)} def helper(in_start, in_end, post_start, post_end): if in_start > in_end or post_start > post_end: return None root_val = postorder[post_end] root = TreeNode(root_val) root_index = idx_map[root_val] left_size = root_index - in_start root . left = helper(in_start, root_index - 1, post_start, post_start + left_size - 1) root . right = helper(root_index + 1, in_end, post_start + left_size, post_end - 1) return root return helper(0, len(inorder) - 1, 0, len(postorder) - 1)
From Traversals to Tree
651478c7ba373c338a173de6
[ "Trees", "Recursion" ]
https://www.codewars.com/kata/651478c7ba373c338a173de6
5 kyu
_This Kata is intend to introduce one of the basic Python Golfing skill._ # Task: In this Golfing Kata, you are going to receive 2 positive integers `a` and `b`, you need to return the result of `math.ceil(a/b)`. But `import math` is too long, your code has to be as short as possible. Can you avoid the `math.ceil`? Here are some limit: * Same as the `math.ceil`, your code has to return an `integer`, not `float`. * The length limit is 23, your code has to be equal or shorter than that. ``` input --> output f(1, 1) --> 1 f(2, 4) --> 1 f(3, 3) --> 1 f(4, 2) --> 2 f(5, 3) --> 2 ```
games
def f(a, b): return 0 - - a / / b
[Code Golf] Avoid the math.ceil
6515e6788f32503cd5b1ee51
[ "Mathematics", "Restricted" ]
https://www.codewars.com/kata/6515e6788f32503cd5b1ee51
7 kyu
Given a string indicating a range of letters, return a string which includes all the letters in that range, *including* the last letter. Note that if the range is given in *capital letters*, return the string in capitals also! ### Examples ``` "a-z" ➞ "abcdefghijklmnopqrstuvwxyz" "h-o" ➞ "hijklmno" "Q-Z" ➞ "QRSTUVWXYZ" "J-J" ➞ "J" ``` ### Notes - A *hyphen* will separate the two letters in the string. - You don't need to worry about error handling in this kata (i.e. both letters will be the same case and the second letter will not be before the first alphabetically).
reference
def gimme_the_letters(rng): a, b = map(ord, rng . split('-')) return '' . join(map(chr, range(a, b + 1)))
From A to Z
6512b3775bf8500baea77663
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/6512b3775bf8500baea77663
7 kyu
You have a pack of 5 randomly numbered cards, which can range from 0-9. You can win if you can produce a higher **two-digit** number from your cards, than your opponent. Return `True` if your cards win that round. ### Worked Example ``` ([2, 5, 2, 6, 9], [3, 7, 3, 1, 2]) ➞ True # Your cards can make the number 96 # Your opponent can make the number 73 # You win the round since 96 > 73 ``` ### Examples ``` ([2, 5, 2, 6, 9], [3, 7, 3, 1, 2]) ➞ True ([1, 2, 3, 4, 5], [9, 8, 7, 6, 5]) ➞ False ([4, 3, 4, 4, 5], [3, 2, 5, 4, 1]) ➞ False ``` ### Notes Return `False` if you and your opponent reach the same maximum number (see example #3).
reference
def win_round(you, opp): return sorted(you)[: 2: - 1] > sorted(opp)[: 2: - 1]
Numbered Cards
65128d27a5de2b3539408d83
[]
https://www.codewars.com/kata/65128d27a5de2b3539408d83
7 kyu
Given two strings comprised of `+` and `-`, return a new string which shows how the two strings interact in the following way: - When positives and positives interact, they *remain positive*. - When negatives and negatives interact, they *remain negative*. - But when negatives and positives interact, they *become neutral*, and are shown as the number `0`. ### Worked Example ``` ("+-+", "+--") ➞ "+-0" # Compare the first characters of each string, then the next in turn. # "+" against a "+" returns another "+". # "-" against a "-" returns another "-". # "+" against a "-" returns "0". # Return the string of characters. ``` ### Examples ``` ("--++--", "++--++") ➞ "000000" ("-+-+-+", "-+-+-+") ➞ "-+-+-+" ("-++-", "-+-+") ➞ "-+00" ``` ### Notes The two strings will be the same length.
reference
def neutralise(s1, s2): return '' . join('0' if i != j else i for i, j in zip(s1, s2))
Neutralisation
65128732b5aff40032a3d8f0
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/65128732b5aff40032a3d8f0
8 kyu
Two players draw a pair of numbered cards so that both players can form a *2 digit number*. A winner can be decided if one player's number is larger than the other. However, there is a rule where a player can swap any one of their cards with any one of the other player's cards in a gamble to get a higher number! Note that it is illegal to swap the order of **your own cards**. That means if you draw a `1` then a `9`, you **cannot** swap them to get `91`. ![Numbered Cards](https://i.imgur.com/IuZGhB0.png) Paul's strategy is to always swap his **lowest** number with the opponent's **ten's digit**. Return whether this results in Paul winning the round. - `n1` is Paul's number - `n2` is his opponent's number ### Worked Example ``` (41, 79) ➞ true # Paul's lowest number is 1 # The opponent's ten's digit is 7 # After the swap: 47 > 19 # Paul wins the round ``` ### Examples ``` (41, 98) ➞ true (12, 28) ➞ true (67, 53) ➞ false (77, 54) ➞ false ``` ### Notes - If both of Paul's digits are the same, swap the ten's digit with the opponent's (paul likes to live riskily). - The cards don't include the number **0**. - 11 <= All numbers <= 99 (excluding numbers containing 0)
reference
def swap_cards(a, b): p, q = a / / 10, a % 10 r, s = b / / 10, b % 10 return p > q or (r, q) > (p, s)
Swapping Cards
65127302a5de2b11c940973d
[]
https://www.codewars.com/kata/65127302a5de2b11c940973d
7 kyu
Given a list of directions to spin, `"left"` or `"right"`, return an integer of how many full **360°** rotations were made. Note that each word in the array counts as a **90°** rotation in that direction. ### Worked Example ``` ["right", "right", "right", "right", "left", "right"] ➞ 1 # You spun right 4 times (90 * 4 = 360) # You spun left once (360 - 90 = 270) # But you spun right once more to make a full rotation (270 + 90 = 360) ``` ### Examples ``` ["left", "right", "left", "right"] ➞ 0 ["right", "right", "right", "right", "right", "right", "right", "right"] ➞ 2 ["left", "left", "left", "left"] ➞ 1 ``` ### Notes - Return a positive number. - All tests will only include the words `"right"` and `"left"`.
reference
def spin_around(lst): return abs(2 * lst . count("left") - len(lst)) / / 4
Spin Around, Touch the Ground
65127141a5de2b1dcb40927e
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/65127141a5de2b1dcb40927e
7 kyu
Create a function that returns the sum of the digits formed from the first and last digits, all the way to the center of the number. ### Worked Example ``` 2520 ➞ 72 # The first and last digits are 2 and 0. # 2 and 0 form 20. # The second digit is 5 and the second to last digit is 2. # 5 and 2 form 52. # 20 + 52 = 72 ``` ### Examples ``` 121 ➞ 13 # 11 + 2 1039 ➞ 22 # 19 + 3 22225555 ➞ 100 # 25 + 25 + 25 + 25 ``` ### Notes - If the number has an **odd** number of digits, simply add on the single-digit number in the center (see example #1). - Any number which is **zero-padded** counts as a single digit (see example #2).
reference
def closing_in_sum(n): n_str = str(n) left = 0 right = len(n_str) - 1 total = 0 while left <= right: left_number = n_str[left] right_number = n_str[right] if left_number == right_number and left == right: total += int(f" { right_number } ") else: total += int(f" { left_number }{ right_number } ") left += 1 right -= 1 return total
Closing in Sum
65126d52a5de2b11c94096d2
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/65126d52a5de2b11c94096d2
7 kyu
Given a number, insert duplicate digits on both sides of all digits which appear in a group of 1. ### Worked Example ``` 22733 ➞ 2277733 # The number can be split into groups 22, 7, and 33. # 7 appears on its own. # Put 7s on both sides to create 777. # Put the numbers together and return the result. ``` ### Examples ``` 123 ➞ 111222333 56657 ➞ 55566555777 33 ➞ 33 ``` ### Notes All tests will include positive integers.
reference
import re def numbers_need_friends_too(n): return int(re . sub(r'(.)\1*+(?<!\1.)', r'\1' * 3, str(n)))
Lonely Numbers
65126a26597b8597d809de48
[]
https://www.codewars.com/kata/65126a26597b8597d809de48
7 kyu
# Minimum number of moves There're two list: * [5, 1, 3, 2, 4] * [4, 5, 2, 1, 3] Your goal is to change the first list to the second list Each modification consists of choosing a single number and moving it some number of positions to the left. Your task is to write a function `min_move`, which has 2 argument `a` and `b`(list) and calculate the minimum moves to change the first list to the second list. ## Example ```python min_move([1, 3, 5, 2, 4], [1, 2, 3, 4, 5]) = 2 1, 3, 5, 2, 4 --> 1, 3, 4, 5, 2 # The position of 4 is changed --> 1, 2, 3, 4, 5 # The position of 2 is changed, and now it's in correct order. ``` ## Notes * Numbers in the list are numbered from 1 to len(A). * Numbers will never repeat in the two list, all lists are valid * Test range: ___5 <= len(a), len(b) <= 50000___, you may need to consider the performance.
algorithms
def min_move(a, b): count = 0 seen = set() i = 0 j = 0 while j < len(b): if a[i] == b[j]: i += 1 j += 1 elif a[i] in seen: i += 1 else: seen . add(b[j]) j += 1 count += 1 return count
Minimum number of moves
622e4b5028bf330017cd772f
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/622e4b5028bf330017cd772f
5 kyu
Due to a huge scandal about the Laddersons Ladder Factory creating faulty ladders, the Occupational Safety and Health Administration require your help in determining whether a ladder is safe enough for use in the work place! It is vital that a ladder passes all criterea: - There will be exactly one character space with no rung at the top and bottom of every ladder. - The ladder must be at least 5 characters wide. - The ladder mustn't have more than a 2 character gap between rungs. - Rungs must be evenly spaced apart. - Each part of the ladder must have equal width - Rungs should not be broken (i.e. no gaps, a broken rung always has at least one piece still attached to the poles). - There should be atleast one rung. Given a ladder (drawn as a list of strings) return `True` if it passes all of OSHA's criterea, `False` otherwise. **Examples** ``` ([ "# #", "#####", "# #", "# #", "#####", "# #", "# #", "#####", "# #" ]) ➞ True ([ "# #", "#####", "# #", "# #", "######", "# #", "# #", "#######", "# #" ]) ➞ False #Each part of the ladder must have equal width ([ "# #", "#####", "# #", "#####", "# #", "# #", "#####", "# #" ]) ➞ False # Uneven spaces between rungs. ([ "# #", "####", "# #", "# #", "####", "# #", "# #", "####", "# #" ]) ➞ False # Ladder is too narrow, should be at least 5 characters wide. ([ "# #", "#####", "# #", "# #", "# #", "# #", "#####", "# #", "# #", "# #", "# #", "#####", "# #" ]), ➞ False # Gap between rungs is too wide, should be less than 3. ([ "# #", "# ##", "# #", "# #", "#####", "# #", "# #", "#####", "# #" ]) ➞ False # The top rung is broken. ```
reference
import re def is_ladder_safe(ldr): s = ldr[0] base = f'# { " " * ( len ( s ) - 2 ) } #' full = "#" * len(s) O, C = '{}' reg = rf" { base } o { full } o((?: { base } o) { O } ,2 { C }{ full } o)\1* { base } " return len(s) > 4 and bool(re . fullmatch(reg, 'o' . join(ldr)))
An OSHA Approved Ladder?
65116501a5de2bc51f409c1a
[]
https://www.codewars.com/kata/65116501a5de2bc51f409c1a
6 kyu
Matryoshka dolls are traditionally wooden dolls that can be nested by fitting smaller dolls into larger ones. Similarly, we can nest lists by placing smaller lists into larger ones, following specific rules. **Rules for Nesting:** - List A can be nested inside List B if: - The minimum value in List A is greater than the minimum value in List B. - The maximum value in List A is smaller than the maximum value in List B. **Example 1:** - List A: [2, 3, 9, 5] - List B: [10, 2, 1] - Explanation: - min(A) = 2 > 1 = min(B) - max(A) = 9 < 10 = max(B) - Result: A can be nested inside B. **Example 2:** - List A: [4, 5] - List B: [6, 3] - Explanation: - min(A) = 4 > 3 = min(B) - max(A) = 5 < 6 = max(B) - Result: A can be nested inside B. **Example 3:** - List A: [7, 1] - List B: [7, 6, 5, 4, 3, 2] - Explanation: - Both lists share the same maximum value (7). - Result: A cannot be nested properly inside B. **Example 4:** - List A: [1, 5] - List B: [2, 6] - Explanation: - Elements in the lists overlap, making nesting impossible. - Result: A cannot be nested inside B. **Example 5:** - List A: [1,2,3,4] - List B: [0,3,5] - List C: [2,2,3]] - Explanation: - List C and List A meet the criteria because 2 > 1 and 3 < 4. - List A and List B also meet the criteria because 1 > 0 and 4 < 5. - Result: List B can be nested inside List A, and List A can be nested inside List C. **Additional Notes:** - Sublists can be nested in either ascending (smallest to largest) or descending (largest to smallest) order. - Strict nesting is required; no two lists can share the same maximum or minimum values.
games
from itertools import pairwise def matryoshka(ls): return all(a[0] < b[0] and a[- 1] > b[- 1] for a, b in pairwise(sorted(map(sorted, ls), key=lambda l: (l[0], - l[- 1]))))
Matryoshka Dolls
6510238b4840140017234427
[]
https://www.codewars.com/kata/6510238b4840140017234427
7 kyu
# Weird Sequence This weird sequence is an expansion of the integer sequence (`1,2,3,..`). It starts with `1` and it is expanded (an infinite number of times) by adding the number `k` before every `k`<sup>th</sup> (`1`-based) term of this weird sequence. For example: ```python [ 1] # Have not expanded [ 1, 1] # Expanded once [ 1, 1, 2, 1] # Expanded twice [ 1, 1, 2, 1, 3, 2, 4, 1] # Expanded three times [1, 1, 2, 1, 3, 2, 4, 1, 5, 3, 6, 2, 7, 4, 8, 1] # Expanded four times ``` If you watch the example vertically, you can notice that we add numbers in front of the numbers of the previous sequence each time when we are going to expand. And those numbers we added are the ascending integer sequence. However, the weird thing is after expansion, the existing terms did not change! But every expansion makes the sequence longer, and ultimately infinite. # Task Given an integer index `n`, where `0` <= `n` <= `10**12 - 1`, return that term of this weird sequence. There will be no invalid inputs. # Example ``` weird(0) # Output: 1 weird(10) # Output: 6 weird(23) # Output: 2 ``` There are 1600 random tests. Good luck.
algorithms
def weird(n): return weird(n / / 2) if n % 2 else (n / / 2 + 1)
Weird Sequence
650c7503a5de2be5b74094bf
[ "Mathematics" ]
https://www.codewars.com/kata/650c7503a5de2be5b74094bf
6 kyu
Your task is to implement a function that examines a given string composed of binary digits (0s and 1s). The function should return `True` if: - Every consecutive sequence of ones is immediately followed by an equal-length consecutive sequence of zeroes, and the number of ones is equal to the number of zeroes. - A leading zero always results in a `False` outcome. Here are some examples to illustrate the expected behavior of the function: **Examples** ``` - For the input "110011100010," the function should return True because every consecutive sequence of ones (e.g., "11," "111," "1") is followed by an equal-length consecutive sequence of zeroes. - For the input "101010110," the function should return False because the sequence of ones ("11") is not followed by an equal-length consecutive sequence of zeroes. - "111100001100" # True - "111" # False - "00110100001111 # False, although the number of zeroes and ones is equal, the consecutive sequence of ones (e.g., "11," "1," "1111") is not followed by an equal-length consecutive sequence of zeroes. ``` **Notes** - The input string will only contain digits `0` or `1`. - The length of the input string (`txt`) will be greater than zero.
reference
from re import compile REGEX = compile(r"(1*)(0*)"). findall def same_length(txt): return all(len(x) == len(y) for x, y in REGEX(txt))
Ones and Zeroes
650a86e8404241005fc744ca
[]
https://www.codewars.com/kata/650a86e8404241005fc744ca
7 kyu
**Problem Description** Find how many reflective prime pairs exist in a given range for each base in a given range. You'll be given two integers as parameters — ceiling range for primes and ceiling range for bases **(ranges include the parameters)**. By "reflective" I mean two distinct numbers who are each other's reflection in the same base (e.g. 37 and 73). Palindromic numbers like 101 don't count as reflective pairs with themselves — their pair must be distinct. Return a dictionary where ascending bases are keys and the count of reflective pairs within each are the values. e.g. ``` { base : count of reflective pairs for base, ... } ``` **Input** - Two integers: `max_prime_range` and `max_base_range`, where: - 2 <= `max_prime_range` <= 10^4 - 3 <= `max_base_range` <= 50 **Output** - A dictionary where the keys are ascending bases within the range [2, `max_base_range`] (inclusive), and the values are the counts of reflective prime pairs for each base. **Examples** ``` Input: `(100, 5)` Output: `{2: 6, 3: 6, 4: 4, 5: 6}` Prime numbers in the range (inclusive) [2, 100]: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] For base 2: {('101011', '110101'), ('10111', '11101'), ('1000011', '1100001'), ('100101', '101001'), ('1011', '1101'), ('101111', '111101')} For base 3: {('102', '201'), ('1112', '2111'), ('1011', '1101'), ('1202', '2021'), ('12', '21'), ('1222', '2221')} For base 4: {('1021', '1201'), ('133', '331'), ('113', '311'), ('13', '31')} For base 5: {('243', '342'), ('23', '32'), ('142', '241'), ('122', '221'), ('12', '21'), ('34', '43')}} ```
reference
PRIMES = {n for n in range(2, 10 * * 4 + 1) if all(n % p for p in range(2, int(n * * .5) + 1))} def rev(n, b): r = 0 while n: r, n = r * b + n % b, n / / b return r def prime_reflections(mp, mb): return {b: sum(rev(p, b) < p <= mp and rev( p, b) in PRIMES for p in PRIMES) for b in range(2, mb + 1)}
Reflective Prime Pairs for a Range of Bases
650850aa0b700930130c7981
[]
https://www.codewars.com/kata/650850aa0b700930130c7981
6 kyu
One of the basic [chess endgames](https://en.wikipedia.org/wiki/Chess_endgame) is where only three pieces remain on the board: the two kings and one rook. By 1970 it was proved that the player having the rook can win the game in at most 16 moves. Can you write code that plays this endgame that well? # Short Overview Your code will play as white and the testing code will play as black. Each test case provides you with an initial game setup, consisting of the positions of three pieces: the white king, the white rook, and the black king. Then you will get a valid move for the black king, to which you must reply with a move with a white piece. You will then get another black move for which you should reply with the next white move, ...etc. The testing code will stop this exchange of moves once the game ends, the rook is lost, or an invalid move is made. Your code must be able to give a checkmate within 16 moves. At the end of this description you'll find the relevant rules of chess. # Details of the Task Write a class `WhitePlayer` with: * A constructor taking a string as argument, listing the positions of the three pieces in the format `Kxy,Rxy - Kxy` where `xy` are coordinates in [algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess%29) and the other characters are literal. Examples of such strings are `Kf8,Rd5 - Ke3` and `Kb6,Rc5 - Kb3`. The coordinates will always appear in this order and format, and will always be valid. They define the positions of the white king, the white rook, and the black king in that order. In all provided positions it is black's turn to play a move.<p> * A method `play`, which takes a string as argument and returns a string. The testing code will call this method to pass as argument a legal black king move. Examples are `Kf3`, `Kb2`, ... always starting with `K` followed by the new position of the black king. The method should return the move that white will make in response to this black move. It should have the same format. For example: `Rd7`, or `Kb5`. The method should update the state of the game, reflecting that both the given black move and the produced white move have been played. The next call of this method will provide a black move applicable to that modified game state. The testing code will keep calling the method with a next black move until one of the following happens (assuming no exceptions are raised): - the method returns a value that does not represent a valid move (e.g. wrong data type, wrong format, or violating chess rules): the test fails. - black can capture the rook: the test fails. The capturing move is mentioned in the failure message with an additional "x", like `Kxb4`. - black cannot make a valid move. There are three possibilities: - Checkmate after at most 16 white moves: the test succeeds. - Checkmate after more than 16 white moves: the test fails. Note that the test is not interrupted after 16 white moves so at least you can see how many moves it took. - Stalemate: the test fails. - The [threefold position](https://en.wikipedia.org/wiki/Threefold_repetition) or [50-move](https://en.wikipedia.org/wiki/Fifty-move_rule) rule applies: the test fails. ### Tests The *example* test cases can be finished with one move. If somehow your code takes up to 16 moves for a mate, the tests will pass. But it seems reasonable that your code should detect mate-in-one positions. The full tests include around 40 fixed tests with differing levels of difficulty. ```if:javascript There are 1 000 random tests. ``` ```if:python There are 500 random tests. ``` # Example Here is an example position: <table style="width: 340px; margin: 0 auto;border-collapse: collapse;font-size: 20px;text-align: center;border-width:0"> <tbody> <tr><td style="height: 40px; width: 20px;border-right:1px solid;">8</td><td style="border-top: 1px solid;background: #cc6; width: 40px;"></td><td style="border-top: 1px solid;background: brown; width: 40px;"></td><td style="border-top: 1px solid #ddd;background: #cc6; width: 40px; font-size: 40px; padding: 0px; line-height:100%;color: #333; text-shadow: -1px 0 #ddd, 0 1px #ddd, 1px 0 #ddd, 0 -1px #ddd;">♚</td><td style="border-top: 1px solid;background: brown; width: 40px;"></td><td style="border-top: 1px solid;background: #cc6; width: 40px; font-size: 40px; padding: 0px; line-height:100%;color: #eee; text-shadow: -1px 0 #333, 0 1px #333, 1px 0 #333, 0 -1px #333;">♚</td><td style="border-top: 1px solid;background: brown; width: 40px;"></td><td style="border-top: 1px solid;background: #cc6; width: 40px;"></td><td style="border-top: 1px solid;border-right:1px solid;background: brown; width: 40px;"></td></tr> <tr><td style="height: 40px;border-right:1px solid;">7</td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;font-size: 40px; padding: 0px; line-height:100%;border-right:1px solid;color: #eee; text-shadow: -1px 0 #333, 0 1px #333, 1px 0 #333, 0 -1px #333;">♜</td></tr> <tr><td style="height: 40px;border-right:1px solid;">6</td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;border-right:1px solid;"></td></tr> <tr><td style="height: 40px;border-right:1px solid;">5</td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;border-right:1px solid;"></td></tr> <tr><td style="height: 40px;border-right:1px solid;">4</td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;border-right:1px solid;"></td></tr> <tr><td style="height: 40px;border-right:1px solid;">3</td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;border-right:1px solid;"></td></tr> <tr><td style="height: 40px;border-right:1px solid;">2</td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;border-right:1px solid;"></td></tr> <tr><td style="height: 40px;border-right:1px solid;">1</td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;"></td><td style="background: brown;"></td><td style="background: #cc6;border-right:1px solid;"></td></tr> </tbody> <tfoot> <tr><td style="height: 20px;"></td><td style="border-top:1px solid;text-align:center">a</td><td style="border-top:1px solid;text-align:center">b</td><td style="border-top:1px solid;text-align:center">c</td><td style="border-top:1px solid;text-align:center">d</td><td style="border-top:1px solid;text-align:center">e</td><td style="border-top:1px solid;text-align:center">f</td><td style="border-top:1px solid;text-align:center">g</td><td style="border-top:1px solid;text-align:center">h</td></tr> </tfoot> </table> This position would be passed to the constructor as `Ke8,Rh7 - Kc8`. Black has only one valid move here, `Kb8`, so that is what the testing code will call your method with. The game could proceed like this: ```javascript const whitePlayer = new WhitePlayer("Ke8,Rh7 - Kc8"); const whiteMove = whitePlayer.play("Kb8"); // Your code will determine what the return value is, let's assume it's "Kd8"; // then black has again only one possible move: whiteMove = whitePlayer.play("Ka8"); // Maybe you decided to return "Kc7"? Good choice! whiteMove = whitePlayer.play("Ka7"); // Maybe you returned "Rh6" so that black can only return back to square a8 whiteMove = whitePlayer.play("Ka8"); // If your code is good, it will certainly return "Ra6" here, // at which moment you pass the test... it is a checkmate. ``` ```python whiteplayer = WhitePlayer("Ke8,Rh7 - Kc8") whitemove = whiteplayer.play("Kb8") # Your code will determine what the return value is, let's assume it's "Kd8"; # then black has again only one possible move: whitemove = whiteplayer.play("Ka8") # Maybe you decided to return "Kc7"? Good choice! whitemove = whiteplayer.play("Ka7") # Maybe you returned "Rh6" so that black can only return back to square a8 whitemove = whiteplayer.play("Ka8") # If your code is good, it will certainly return "Ra6" here, # at which moment you pass the test... it is a checkmate. ``` # The real challenge: not more than 16 moves The black king must be checkmated *in 16 white moves* or less. The black king will use some simple (imperfect) [heuristic](https://en.wikipedia.org/wiki/Heuristic) to delay that fate for as long as possible. The last bunch of tests generate positions that are known to need 16 white moves with perfect play. Although black does not always play the best move, the random nature of the tests and their number provide a high probability that black will happen to play a perfect defense in a few tests. Consequently your code must aim to play the best moves for white as well. Often there are multiple best moves in one position, so there is a little leeway. Several possibilities are in front of you: maybe you can think of a smart [evaluation function](https://en.wikipedia.org/wiki/Evaluation_function), [alpha beta pruning](https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning), [killer moves](https://en.wikipedia.org/wiki/Killer_heuristic), and some other optimisations. Or, maybe you'll go for a purely data driven approach by first building a comprehensive [tablebase](https://en.wikipedia.org/wiki/Endgame_tablebase) or a variation on that. Or maybe you'll go for a combination of these approaches. There is probably more than one good way to go about this; just be prepared that there are many random tests and you only have 12 seconds to finish all those games with checkmate, each within 16 moves. There are also resources online that will provide you the best move in any given position of these three pieces. See for example [this Chess Endgame Database](https://www.shredderchess.com/online/endgame-database.html). Good luck! # Appendix ## 1. Chess Rules Chess is played on a 8x8 board, with two players: one plays with the white pieces, the other with the black ones. They take turns in playing a move. The pieces we need for this kata are: * **King**: a [king](https://en.wikipedia.org/wiki/King_(chess%29) can move to an adjacent square, either horizontally, vertically or diagonally, in any direction. There are always two kings in a game: a white one and a black one. They may never come within eachother's reach. There must be at least one empty square between them. The king may never move to a square where it could be captured by an opponent piece. Therefore, kings can never be captured. * **Rook**: a [rook](https://en.wikipedia.org/wiki/Rook_(chess%29) may only move horizontally or vertically, but possibly more than one square at a time, so it can even go from one side of the board to the other end. It may however not jump over another piece, nor occupy a square with a piece of the same color. In this kata there will only be one, white rook. The rook should be placed carefully, as the black king can potentially capture it when it is right next to it. In that case the rook is taken off the board, and the black king takes its position. If after white's move the rook attacks the black king, the black king is ["in check"](https://en.wikipedia.org/wiki/Check_(chess%29). In that case, the black king must move away. If there is no place for the king to go where it is no longer attacked, then it is a [checkmate](https://en.wikipedia.org/wiki/Checkmate): white wins. If the black king is not attacked, but it cannot move anywhere, black is in a so-called ["stalemate"](https://en.wikipedia.org/wiki/Stalemate). In that case the game ends without a winner; it is a draw. In this kata you should avoid bringing black into stalemate; you must win! A player can claim a draw when: * both players played 50 moves without capturing a piece or without pawn move (there are no pawns in this kata). This is the [50-move](https://en.wikipedia.org/wiki/Fifty-move_rule) rule. * a position is arrived at that already occurred twice before. This is the [threefold repetition](https://en.wikipedia.org/wiki/Threefold_repetition) rule. In this kata the black player (the testing code) will claim a draw when possible. ## 2. Algabraic Notation See [Wikipedia](https://en.wikipedia.org/wiki/Algebraic_notation_(chess%29): The letter part (a-h) determines the column and the number part (1-8) the row as depicted in the image above. "K" refers to the king, and "R" to the rook. "Rh1" means the rook moves to the bottom-right square of the board. ## 3. Strategy A common strategy in this particular endgame, is to use the rook to confine the black king to a box as it cannot cross the vertical and horizontal lines of the rook's attack, and to reduce that box as the game progresses. Defend the rook with the king, or when that is not possible, move the rook into safety without giving up (too much of) that space restriction. The king is necessary to assist in forcing the black king backwards and to defend the rook. Eventually the black king is pressed against the edge of the board, and once the white king is moved straight in front of it (with one square in between), the rook can give the checkmate. For more about strategies for this endgame see for example the articles on [WikiBooks](https://en.wikibooks.org/wiki/Chess/The_Endgame/King_and_Rook_vs._King), [Chess.StackExchange](https://chess.stackexchange.com/questions/4886/how-do-you-checkmate-with-a-rook), [Chess Corner](http://www.chesscorner.com/tutorial/basic/r_k_mate/r_k_mate.htm), or [Regency Chess](https://www.regencychess.co.uk/blog/2012/10/chess-noob-17-mating-with-a-king-and-rook/). Be aware though that such strategies may lead to a move sequence that is longer than accepted in this kata.
algorithms
import csv import shutil import urllib . request from collections import defaultdict from enum import Enum from zipfile import ZipFile # constants and helper functions FILES = 'abcdefgh' RANKS = '12345678' ALPHA_NUMS = 'zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen draw' TEXT_TO_DIGIT = {w: i for i, w in enumerate(ALPHA_NUMS . split())} # tablebase fetching and processing logic def prepare_tablebase(url): fn = "endgame.zip" tablebase = {} with urllib . request . urlopen(url) as response, open(fn, 'wb') as out_file: shutil . copyfileobj(response, out_file) with ZipFile(fn) as zf: file = zf . extract('krkopt.data') with open(file) as file: reader = csv . reader(file) for row in reader: keys = row[: 6] # First 6 elements are the positions dtm = TEXT_TO_DIGIT . get(row[6], None) if dtm is not None: tablebase[tuple(keys)] = dtm return tablebase KRK_TABLEBASE = prepare_tablebase( "https://archive.ics.uci.edu/static/public/23/chess+king+rook+vs+king.zip") # board symmetry and translation logic class Scenario (Enum): BASE = 1 ROT90 = 2 ROT180 = 3 ROT270 = 4 REFLECT1 = 5 REFLECT2 = 6 REFLECT3 = 7 REFLECT4 = 8 def rotate90(pos): f, r = pos return FILES[RANKS . index(r)] + RANKS[7 - FILES . index(f)] def rotate180(pos): f, r = pos return FILES[7 - FILES . index(f)] + RANKS[7 - RANKS . index(r)] def rotate270(pos): f, r = pos return FILES[7 - RANKS . index(r)] + RANKS[FILES . index(f)] def reflect1(pos): f, r = pos return FILES[7 - RANKS . index(r)] + RANKS[7 - FILES . index(f)] def reflect2(pos): f, r = pos return f + RANKS[7 - RANKS . index(r)] def reflect3(pos): f, r = pos return FILES[RANKS . index(r)] + RANKS[FILES . index(f)] def reflect4(pos): f, r = pos return FILES[7 - FILES . index(f)] + r # Maps for each scenario scenario_maps_actual_to_base = { Scenario . BASE: {f' { f }{ r } ': f' { f }{ r } ' for f in FILES for r in RANKS}, Scenario . ROT90: {f' { f }{ r } ': rotate90(f' { f }{ r } ') for f in FILES for r in RANKS}, Scenario . ROT180: {f' { f }{ r } ': rotate180(f' { f }{ r } ') for f in FILES for r in RANKS}, Scenario . ROT270: {f' { f }{ r } ': rotate270(f' { f }{ r } ') for f in FILES for r in RANKS}, Scenario . REFLECT1: {f' { f }{ r } ': reflect1(f' { f }{ r } ') for f in FILES for r in RANKS}, Scenario . REFLECT2: {f' { f }{ r } ': reflect2(f' { f }{ r } ') for f in FILES for r in RANKS}, Scenario . REFLECT3: {f' { f }{ r } ': reflect3(f' { f }{ r } ') for f in FILES for r in RANKS}, Scenario . REFLECT4: {f' { f }{ r } ': reflect4(f' { f }{ r } ') for f in FILES for r in RANKS}, } scenario_maps_actual_to_base scenario_maps_base_to_actual = { s: {v: k for k, v in scenario_maps_actual_to_base[s]. items()} for s in scenario_maps_actual_to_base } king_to_scenario_iter = [ (('a1', 'b1', 'b2', 'c1', 'c2', 'c3', 'd1', 'd2', 'd3', 'd4'), Scenario . BASE), (('a8', 'a7', 'b7', 'a6', 'b6', 'c6', 'a5', 'b5', 'c5', 'd5'), Scenario . ROT90), (('h8', 'g8', 'g7', 'f8', 'f7', 'f6', 'e8', 'e7', 'e6', 'e5'), Scenario . ROT180), (('h1', 'h2', 'g2', 'h3', 'g3', 'f3', 'h4', 'g4', 'f4', 'e4'), Scenario . ROT270), (('h8', 'h7', 'g7', 'h6', 'g6', 'f6', 'h5', 'g5', 'f5', 'e5'), Scenario . REFLECT1), (('a8', 'b8', 'b7', 'c8', 'c7', 'c6', 'd8', 'd7', 'd6', 'd5'), Scenario . REFLECT2), (('a1', 'a2', 'b2', 'a3', 'b3', 'c3', 'a4', 'b4', 'c4', 'd4'), Scenario . REFLECT3), (('h1', 'g1', 'g2', 'f1', 'f2', 'f3', 'e1', 'e2', 'e3', 'e4'), Scenario . REFLECT4), ] king_to_scenarios_map = defaultdict(set) for kps, s in king_to_scenario_iter: for kp in kps: king_to_scenarios_map[kp]. add(s) class Position: def __init__(self, file, rank): self . file = file self . rank = rank @ classmethod def from_algebraic(cls, pos_str): return cls(pos_str[0], pos_str[1]) @ classmethod def from_indices(cls, fi, ri): return cls(FILES[fi], RANKS[ri]) def to_algebraic(self): return f' { self . file }{ self . rank } ' def to_tuple(self): return self . file, self . rank def is_immediately_adjacent(self, other): fi, ri = FILES . index(self . file), RANKS . index(self . rank) foi, roi = FILES . index(other . file), RANKS . index(other . rank) return max(abs(fi - foi), abs(ri - roi)) <= 1 def __repr__(self): return self . to_algebraic() def __hash__(self): return hash(str(self)) def __eq__(self, other): return hash(self) == hash(other) def translate_to_base_position(self, scenario): return scenario_maps_base_to_actual[scenario][self] class PieceType (Enum): K = 1 R = 2 k = 3 class ChessPosition: def __init__(self, king_pos, rook_pos, opponent_king_pos): self . king_pos = Position . from_algebraic(king_pos) self . rook_pos = Position . from_algebraic(rook_pos) self . opponent_king_pos = Position . from_algebraic(opponent_king_pos) self . scenario = None self . base_king_pos = None self . base_rook_pos = None self . base_opponent_king_pos = None self . dtm = None self . set_scenario() if self . dtm is None: raise ValueError('Chess position created with no DTM.', king_pos, rook_pos, opponent_king_pos) def __repr__(self): return f'K { self . king_pos } , R { self . rook_pos } , k { self . opponent_king_pos } ' def __hash__(self): return hash(str(self)) @ classmethod def from_existing(cls, chess_position, piece_type=None, new_position=None): king_pos = chess_position . king_pos . to_algebraic() rook_pos = chess_position . rook_pos . to_algebraic() opponent_king_pos = chess_position . opponent_king_pos . to_algebraic() if piece_type is not None: if isinstance(new_position, Position): pos = new_position . to_algebraic() else: pos = new_position if piece_type . value == 1: king_pos = pos elif piece_type . value == 2: rook_pos = pos elif piece_type . value == 3: opponent_king_pos = pos else: raise ValueError( 'Invalid piece type for new chess position from existing.') return cls(king_pos, rook_pos, opponent_king_pos) def set_scenario(self): for scenario in king_to_scenarios_map[self . king_pos . to_algebraic()]: nKf, nKr = self . king_pos . translate_to_base_position(scenario) nRf, nRr = self . rook_pos . translate_to_base_position(scenario) nkf, nkr = self . opponent_king_pos . translate_to_base_position(scenario) dtm = KRK_TABLEBASE . get((nKf, nKr, nRf, nRr, nkf, nkr), None) if dtm is not None: self . scenario = scenario self . base_king_pos = Position(nKf, nKr) self . base_rook_pos = Position(nRf, nRr) self . base_opponent_king_pos = Position(nkf, nkr) self . dtm = dtm break def translate_position(self): if self . scenario: return ChessPosition( self . base_king_pos . to_algebraic(), self . base_rook_pos . to_algebraic(), self . base_opponent_king_pos . to_algebraic() ) else: raise ValueError('Position does not have an assigned scenario') def get_king_moves(self): f, r = self . king_pos . to_tuple() fi, ri = FILES . index(f), RANKS . index(r) Rf, Rr = self . rook_pos . to_tuple() Rfi, Rri = FILES . index(Rf), RANKS . index(Rr) kf, kr = self . opponent_king_pos . to_tuple() kfi, kri = FILES . index(kf), RANKS . index(kr) for df in (- 1, 0, 1): for dr in (- 1, 0, 1): if df or dr: fn = fi + df rn = ri + dr if ( 0 <= fn < 8 and 0 <= rn < 8 and (fn, rn) not in ((Rfi, Rri), (kfi, kri)) and not Position . from_indices( fn, rn). is_immediately_adjacent(self . opponent_king_pos) ): yield Position . from_indices(fn, rn) def get_rook_moves(self): f, r = self . rook_pos . to_tuple() fi, ri = FILES . index(f), RANKS . index(r) Kf, Kr = self . king_pos . to_tuple() Kfi, Kri = FILES . index(Kf), RANKS . index(Kr) kf, kr = self . opponent_king_pos . to_tuple() kfi, kri = FILES . index(kf), RANKS . index(kr) for i in range(1, 8): if (fi - i, ri) in ((Kfi, Kri), (kfi, kri)) or (fi - i < 0): break yield Position . from_indices(fi - i, ri) for i in range(1, 8): if (fi + i, ri) in ((Kfi, Kri), (kfi, kri)) or (fi + i > 7): break yield Position . from_indices(fi + i, ri) for i in range(1, 8): if (fi, ri - i) in ((Kfi, Kri), (kfi, kri)) or (ri - i < 0): break yield Position . from_indices(fi, ri - i) for i in range(1, 8): if (fi, ri + i) in ((Kfi, Kri), (kfi, kri)) or (ri + i > 7): break yield Position . from_indices(fi, ri + i) def get_all_possible_moves(self): for move in self . get_king_moves(): yield PieceType(1), move for move in self . get_rook_moves(): yield PieceType(2), move def _generate_valid_moves(self, strict=True): res = [] for piece_type, pos in self . get_all_possible_moves(): new_chess_position = ChessPosition . from_existing(self, piece_type, pos) if new_chess_position . dtm is not None and self . dtm is not None and ( ((new_chess_position . dtm < self . dtm + 1) and strict) or new_chess_position . dtm <= self . dtm + 1): res . append(new_chess_position) return sorted(res, key=lambda pn: pn . dtm) def generate_valid_moves(self): return vm if (vm := self . _generate_valid_moves()) else self . _generate_valid_moves(False) class WhitePlayer: def __init__(self, position): self . chess_position = None self . position_history = [] self . set_position(ChessPosition( * self . parse_initial_position(position))) def parse_initial_position(self, position): pieces = position . split('-') wk_pos, wr_pos = pieces[0]. split(',') bk_pos = pieces[1]. strip() return wk_pos[1:]. strip(), wr_pos[1:]. strip(), bk_pos[1:]. strip() def set_position(self, chess_position): self . position_history . append(chess_position) self . chess_position = chess_position @ property def dtm(self): return self . chess_position . dtm def play(self, black_move): new_black_pos_str = black_move[1:] self . set_position(ChessPosition . from_existing( self . chess_position, PieceType(3), new_black_pos_str)) for new_position in self . chess_position . generate_valid_moves(): if new_position . dtm is not None and new_position not in self . position_history[ max(0, len(self . position_history) - 2):]: str_to_return = ( f'K { new_position . king_pos . to_algebraic ()} ' if new_position . king_pos != self . chess_position . king_pos else f'R { new_position . rook_pos . to_algebraic ()} ' ) self . set_position(new_position) return str_to_return
Chess - checkmate with rook in 16 moves
5b9ecec33c5b95e2b00000ba
[ "Games", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5b9ecec33c5b95e2b00000ba
2 kyu
Create a function that takes two times of day (hours, minutes, seconds) and returns the number of occurences of palindrome timestamps within that range, inclusive. A palindrome timestamp should be read the same hours : minutes : seconds as seconds : minutes : hours, keeping in mind the seconds and hours digits will reverse. For example, _20 : 11 : 02_ is a palindrome timestamp. Each part should be padded to 2 digits. `20:11:02` is a palindrome but `20:11:2` is not. Similarly, `11:1:11` is a palindrome while `11:01:11` is not. ### Examples ``` (2, 12, 22, 4, 35, 10) ➞ 14 (12, 12, 12, 13, 13, 13) ➞ 6 (6, 33, 15, 9, 55, 10) ➞ 0 ``` ### Notes - Expect military time. - Include the given time parameters if they happen to be palendromes. - The parameter timestamps are chronological.
reference
from bisect import bisect_left, bisect_right # Only 96 total memo = [t for t in range(24 * 3600) if (s := f" { t / / 3600 :0 2 d } : { t / / 60 % 60 :0 2 d } : { t % 60 :0 2 d } ") == s[:: - 1]] def palindrome_time(lst): h1, m1, s1, h2, m2, s2 = lst t1, t2 = 3600 * h1 + 60 * m1 + s1, 3600 * h2 + 60 * m2 + s2 return bisect_right(memo, t2) - bisect_left(memo, t1)
Palindrome Timestamps
65080590b6b5ee01db990ca1
[]
https://www.codewars.com/kata/65080590b6b5ee01db990ca1
7 kyu
A prison can be represented as an array of cells, where each cell contains exactly one prisoner. A 'True' represents an unlocked cell, and 'False' represents a locked cell. ``` [True, True, False, False, False, True, False] ``` Starting inside the leftmost cell, you are tasked with determining how many prisoners you can set free, with a catch. You are the prisoner in the first cell. If the first cell is locked (denoted as 'False'), you cannot free anyone. Each time you free a prisoner, the locked cells become unlocked, and the unlocked cells become locked again. So, if we use the example above: ``` [True, True, False, False, False, True, False] // You free the prisoner in the 1st cell. [False, False, True, True, True, False, True] // You free the prisoner in the 3rd cell (the 2nd one is locked). [True, True, False, False, False, True, False] // You free the prisoner in the 6th cell (the 3rd, 4th, and 5th cells are locked). [False, False, True, True, True, False, True] // You free the prisoner in the 7th cell - and you are done! ``` Here, we have set free '4' prisoners in total. Create a function that, given this unique prison arrangement, returns the number of freed prisoners. ### Examples ``` ([True, True, False, False, False, True, False]) ➞ 4 ([True, True, True]) ➞ 1 ([False, False, False]) ➞ 0 ([False, True, True, True]) ➞ 0 ``` ### Notes - **You are the prisoner in the first cell. You must be freed to free anyone else.** - You must free a prisoner to change the locks. So in the second example where the input is `[True, True, True]`, after you release the first prisoner, the locks change to `[False, False, False]`. Since all cells are locked, you can release no more prisoners. - You always start with the leftmost element in the array (the first prison cell). If all the prison cells to your right are 'False', you cannot free any more prisoners.
games
def freed_prisoners(prison): unlocked, freed = prison[0], 0 if unlocked: for cell in prison: if cell is unlocked: freed += 1 unlocked = not unlocked return freed
Prison Break
6507e3170b7009117e0c7865
[]
https://www.codewars.com/kata/6507e3170b7009117e0c7865
7 kyu
Jack and Jill are twins. When they are 10 years of age, Jack leaves earth in his spaceship bound for Altair IV, some 17 light-years distant. Though not equipped with warp drive, Jack's ship is still capable of attaining near light speed. When he returns to earth he finds that Jill has grown to adulthood while he, Jack, remains a young boy. Albert Einstein had predicted this strange quirk of time in his 1905 paper **"On the Electrodynamics of Moving Bodies"** aka The Theory of Special Relativity. It has been verified experimentally many times. Implement a function that has as its arguments: The twins' age at the time of Jack's departure, the distance in light-years to the destination star, and the speed of Jack's ship as a fraction of the speed of light. The function will return Jack's age and Jill's age at the time of Jack's return to earth, to the nearest of a year. The math is simple enough for 10-year-old Jack to understand. ### Examples ``` (20, 10, 0.4) ➞ (65.8, 70) # Jack's age is 65.8, Jill's age is 70.0 (20, 10, 0.8) ➞ (35, 45) # Jack's age is 35.0, Jill's age is 45.0" (10, 16.73, 0.999) ➞ (11.5, 43.5) # Jack's age is 11.5, Jill's age is 43.5" // The Altair IV trip. ``` ### Notes - We are assuming for the sake of simplicity that Jack's periods of acceleration and deceleration are negligibly brief. That is a huge assumption but, nevertheless, it doesn't invalidate the age calculations. - See [this](https://en.wikipedia.org/wiki/Twin_paradox) for help.
reference
def twins(age, distance, velocity): α = (1 - velocity * * 2) * * 0.5 t = 2 * distance / velocity return age + α * t, age + t
The Twins Paradox
6502ea6bd504f305f3badbe3
[ "Physics" ]
https://www.codewars.com/kata/6502ea6bd504f305f3badbe3
7 kyu
Traditional safes use a three-wheel locking mechanism, with the safe combination entered using a dial on the door of the safe. The dial is marked with clockwise increments between 0 and 99. The three-number combination is entered by first dialling to the right (clockwise), then to the left (anti-clockwise), and then to the right (clockwise) again. Combination numbers are read from the top of the dial: ![](https://i.imgur.com/m9fy8a6.png) Given the starting (top) position of the dial and the increments used for each turn of the dial, return a tuple containing the *combination* of the safe. ### Step-By-Step Example ``` (0, (3, 10, 5)) ➞ (97, 7, 2) Starting dial position of 0 (same as the diagram above). First turn (rightward) of 3 increments: 0 -> 99, 98, 97 First number of combination = 97 Second turn (leftward) of 10 increments: 97 -> 98, 99, 0, 1, 2, 3, 4, 5, 6, 7 Second number of combination = 7 Third turn (rightward) of 5 increments: 7 -> 6, 5, 4, 3, 2 Third number of combination = 2 The final combination is (97, 7, 2) ``` ### Other Examples ``` (96, (54, 48, 77)) ➞ (42, 90, 13) (43, (51, 38, 46)) ➞ (92, 30, 84) (4, (69, 88, 55)) ➞ (35, 23, 68) ``` ### Notes - Two consecutive numbers will equal - Values greater than 100 may be provided
algorithms
def safecracker(start, incs): a = (start - incs[0]) % 100 b = (a + incs[1]) % 100 c = (b - incs[2]) % 100 return (a, b, c)
Safecracker
6501aa820038a6b0bd098afb
[]
https://www.codewars.com/kata/6501aa820038a6b0bd098afb
7 kyu
Ava, Mark, Sheila, and Pete are at a party. However, Ava and Sheila are only staying if there are at least 4 people, Pete is only staying if there's at least 1 person, and Mark is only staying if there are at least 5 people. Therefore, Mark leaves, which makes Ava and Sheila leave, and Pete is left alone. Given an array with the preferences of every person at a party for the minimum number of people present, determine how many people will stay. ### Examples ``` [4, 5, 4, 1] ➞ 1 # Ava's minimum number is 4, Mark's is 5, Sheila's is 4, and Pete's is 1. # Only 1 person (Pete) stays. [10, 12, 15, 15, 5] ➞ 0 [2, 1, 2, 0] ➞ 4 ``` ### Notes - All attendees are included in the array. - Any person's count includes themself. - Expect valid input only. - 0 <= len(lst) <= 10^5 ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `BinaryScott` export constructors `nil, cons` for your `List` encoding ~~~
reference
def party_people(lst): lst = sorted(lst) while lst and lst[- 1] > len(lst): lst . pop() return len(lst)
Party People
65013fc50038a68939098dcf
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/65013fc50038a68939098dcf
7 kyu