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
## Rummy In Rummy game, players must make melds of three or more cards from a hand of seven cards. There are two types of melds: * ___Sets:___ groups of three or more cards of the same face value for example `4♠ 4♥ 4♣`. * ___Runs:___ three or more sequential cards of the same suit such as `A♠ 2♠ 3♠`. We'll play an alternative version where aces can be used as low value or high value, hence you can build `J♥ Q♥ K♥ A♥` as a valid run. Note however that this is valid only for aces, hence `K♣, A♣, 2♣` is not valid. Cards can only be used in one meld at a time. Melded cards score no points at all while unmelded cards score points as follows: `A=1, 2-9=face value, T=10, J=11, Q=12, K=13`. Players' goal is to have the hand with the lowest possible score. ## Task Your task is to create a class `Hand` that handles picking up a card and choosing the discard that gives you the lowest possible score for your hand. ### Sepcifications * `Hand(cards_lst)`: `Hand` instances are created being given a list of seven cards. Be aware that the order of the cards must be kept for this kata. * `hand.get_score()`: return the best score for the current hand. * `hand.get_hand()`: return the current hand as a list. * `hand.add_card(card)`: receive the card to add to the hand, then find the card to eliminate so that the remaining hand scores the lowest possible and returns this card. - The new card must be added at the end of the current hand - The dismissed card is removed from the current hand keeping the order of other cards - If you find several candidates leading to the same lowest possible score, return any of them. ___ ### Example 1 starting hand: ["Q♦", "6♣", "Q♥", "Q♠", "5♣", "8♦", "7♣"] adding card: "J♦" 1 set of Q♦, Q♥, Q♠ 1 run of 5♣, 6♣, 7♣ Unmelded cards: `8♦` (8 points) and `J♦` (11 points), so choose the highest to discard: final hand: ["Q♦", "6♣", "Q♥", "Q♠", "5♣", "8♦", "7♣"] score: 8 ___ ### Example 2 starting hand: ["2♠", "4♠", "5♥", "6♠", "A♠", "5♣", "3♠"] adding card: "5♦" 1 set of 5♥, 5♣, 5♦ 1 run of A♠, 2♠, 3♠, 4♠ `6♠` is the only unmelded card, so discard it. final hand: ["2♠", "4♠", "5♥", "A♠", "5♣", "3♠", "5♦"] score: 0 ___ ### Example 3 starting hand: ["5♠", "K♥", "K♣", "Q♥", "A♠", "T♦", "A♥"] adding card: "J♦" 1 run of Q♥, K♥, A♥ Unmelded cards: * `5♠` = 5 points * `K♣` = 13 points * `T♦` = 10 points * `J♦` = 11 points * `A♠` = 1 point Discard the king, so: final hand: ["5♠", "K♥", "Q♥", "A♠", "T♦", "A♥", "J♦"] score: 27 (= 5♠ + T♦ + J♦ + A♠)
algorithms
class Hand: ORDER = 'A23456789TJQK' PTS = {f: i for i, f in enumerate(ORDER, 1)} def __init__(self, hand): self . h = hand[:] self . score = float('inf') self . discard = None self . study() def get_hand(self): return self . h[:] def get_score(self): return self . score def add_card(self, c): if not self . score: return c self . h . append(c) self . discard = c self . study() return self . discard @ staticmethod def cardScore(c): return Hand . PTS[c[0]] @ staticmethod def buildMeldOf(lst): target = lst[- 1][0] meld = [c for c in lst if c[0] == target] if len(meld) >= 3: yield [c for c in lst if c[0] != target] if len(meld) == 4: for i in range(4): yield [c for c in lst if c[0] != target or c == meld[i]] @ staticmethod def buildRunOf(lst): (face, col), r = lst[- 1], [lst[- 1]] s = {c for c in lst if c[1] == col and face != c[0]} iFace = Hand . cardScore(lst[- 1]) - 1 while iFace: iFace -= 1 nc = Hand . ORDER[iFace] + col if nc not in s: break r . append(nc) s . discard(nc) tailAce = 'A' + col tailing = face == 'K' and tailAce in s sR = set(r) while len(r) + tailing > 2: if tailing and len(r) > 1: yield [c for c in lst if c not in sR and c != tailAce] if len(r) > 2: yield [c for c in lst if c not in sR] sR . discard(r . pop()) def study(self): def dfs(lst): if len(lst) < 3: # end of search... end = sorted(out + lst, key=Hand . cardScore) if isDiscard and not end: return rem = end . pop() if isDiscard else None score = sum(map(Hand . cardScore, end)) if self . score > score: self . score, self . discard = score, rem else: # melds then runs, built on the current last card for genFunc in (self . buildMeldOf, self . buildRunOf): for others in genFunc(lst): dfs(others) out . append(lst[- 1]) # nothing doable with this card... dfs(lst[: - 1]) out . pop() isDiscard, out = len(self . h) == 8, [] dfs(sorted(self . h, key=Hand . cardScore)) if isDiscard: self . h . remove(self . discard)
Rummy: Find Lowest Scoring Hand
5b75aa794eb8801bd0000033
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/5b75aa794eb8801bd0000033
3 kyu
# Task Mr.Right always tell the truth, Mr.Wrong always tell the lies. Some people are queuing to buy movie tickets, and one of them is Mr.Wrong. Everyone else is Mr.Right. Please judge who is Mr.Wrong according to their conversation. [[**Input**]] A string array: `conversation` They always talking about `I'm in ... position.`, `The man behind me is ... .`, `The man in front of me is ... .`, `There are/is ... people in front of me.`, `There are/is ... people behind me.`. Please note that everyone has at least one sentence and only one people is Mr.Wrong ;-) [[**Output**]] A string: The name of Mr.Wrong. If can not judge, return `null` (when several valid solutions are possible). # Examples: ``` conversation=[ "John:I'm in 1st position.", "Peter:I'm in 2nd position.", "Tom:I'm in 1st position.", "Peter:The man behind me is Tom." ] findOutMrWrong(conversation) should return "Tom" conversation=[ "John:I'm in 1st position.", "Peter:I'm in 2nd position.", "Tom:I'm in 1st position.", "Peter:The man in front of me is Tom." ] findOutMrWrong(conversation) should return "John" conversation=[ "John:I'm in 1st position.", "Peter:There is 1 people in front of me.", "Tom:There are 2 people behind me.", "Peter:The man behind me is Tom." ] findOutMrWrong(conversation) should return "Tom" const conversation=[ "John:The man behind me is Peter.", "Peter:There is 1 people in front of me.", "Tom:There are 2 people behind me.", "Peter:The man behind me is Tom." ] findOutMrWrong(conversation) should return null ``` Two solutions are possible in the last example: 1) Peter is Mr.Wrong and the order is Tom, John, Peter; 2) Tom is Mr.Wrong and the order is John, Peter, Tom. In this case, the result is `null`. ## Random Tests `$n$` is the number of people. - 500 tests with `$n = 4$` and with one sentence for each person - 100 tests with `$3 \le n \le 10$` - 100 tests with `$3 \le n \le 10$` where all sentences are in the form `The man behind me is ... .`, `The man in front of me is ... .` - 100 tests with `$10 \le n \le 20$` - 100 tests with `$30 \le n \le 40$` # Series - [#1: Guess a number](https://www.codewars.com/kata/578793c0ba5c4b3585000302) - [#2: Who is Mr.Wrong?](https://www.codewars.com/kata/57a2e0dbe298a7fa4800003c)
algorithms
from collections import deque, defaultdict from functools import cache def parse(s): name, rest = s . split(":") lst = rest . split(" ") if lst[- 1] == "position.": return (name, int("" . join(c for c in lst[- 2] if c . isdigit()))) elif lst[0] == "There": if lst[- 2] == "of": return (name, int(lst[2]) + 1) else: return (name, - int(lst[2])) elif lst[2] == "behind": return (name, lst[- 1][: - 1], 1) else: return (name, lst[- 1][: - 1], - 1) @ cache def validate(blanks, strands): if blanks == strands: return True if strands[- 1] > blanks[- 1]: return False next_blanks = [] next_strands = [] i, j = 0, 0 while i < len(blanks) and j < len(strands): if blanks[i] == strands[j]: i += 1 j += 1 elif blanks[i] > strands[j]: next_strands . append(strands[j]) j += 1 else: next_blanks . append(blanks[i]) i += 1 if i < len(blanks): next_blanks += blanks[i:] if j < len(strands): next_strands += strands[j:] if not next_blanks: return True for x in set(next_blanks): if x < next_strands[- 1]: continue next_blanks . remove(x) next_blanks . append(x - next_strands[- 1]) if validate(tuple(sorted(next_blanks)), tuple(next_strands[: - 1])): return True next_blanks . remove(x - next_strands[- 1]) next_blanks . append(x) return False class FinalDict (dict): def __init__(self, n): self . arr = [""] * (n + 1) self . n = n super(). __init__() def __setitem__(self, key, value): if key in self and self[key] != value: raise ValueError(f" { key } { value } { self } ") if value <= 0 or value > self . n: raise ValueError(f" { key } { value } { self } ") if self . arr[value] == key: return if self . arr[value]: raise ValueError(f" { key } { value } { self } ") self . arr[value] = key super(). __setitem__(key, value) def find_out_mr_wrong(conversation): cond = [parse(s) for s in conversation] cond_by_name = defaultdict(list) for name, * rest in cond: cond_by_name[name]. append(rest) n = len(cond_by_name) # number of people wrong = "" # answer for target, target_cond_lst in cond_by_name . items(): # assume target is Mr.Wrong try: d = FinalDict(n) rem = deque() # fix position for I'm ~ position for true statement for name, cond_lst in cond_by_name . items(): if name == target: continue for c in cond_lst: match c: case(index,): d[name] = index if index > 0 else n + index case(other, rel_pos): if name in d: d[other] = d[name] + rel_pos elif other in d: d[name] = d[other] - rel_pos else: rem . append((name, other, rel_pos)) # fix position (with consideration of relative pos information) for true statement fix_d = None strands = [] # not-fixed chain of people while rem: next_rem = [] for name, other, rel_pos in rem: if name in d: d[other] = d[name] + rel_pos elif other in d: d[name] = d[other] - rel_pos else: next_rem . append((name, other, rel_pos)) if next_rem == rem: if fix_d is None: fix_d = d else: strands . append(d) d = FinalDict(2 * n) # to check statement is consistent d[name] = n rem = next_rem if fix_d is not None: strands . append(d) else: fix_d = d strands_lst = [] # chain of people including target. If target is fixed this value is not used target_strands = [] target_is_fixed = target in fix_d for strand in strands: tmp = [x for x in strand . arr if x] if target in tmp: target_strands = tmp else: strands_lst . append(tmp) if (not target_is_fixed) and (not target_strands): target_strands = [target] # target does not appear in true statement strands_len_lst = sorted(len(x) for x in strands_lst) possible_target_pos = [] if target_is_fixed: possible_target_pos = [fix_d . arr . index(target)] else: l = len(target_strands) target_pos = target_strands . index(target) bef = 0 # check whether target_strand be put. i id last element index of target strand for i in range(1, n + 1): if fix_d . arr[i]: bef = i elif i - bef >= l: possible_target_pos . append(i - l + (target_pos + 1)) for i in possible_target_pos: # when target is position i, check whetehr it is possible to meet the all statement if any(len(c) == 1 and i == c[0] + n * (c[0] <= 0) for c in target_cond_lst): continue # check whether Mr.wrong statement for position is wrong # when we have freedom to left-hand side or right-side of target, try fixing left and right strand and check # when they are fixed, use string indicating the name of left(right)-hand side person of these name instead. left_possible_strands = [] right_possible_strands = [] if i > 1 and (not fix_d . arr[i - 1]) and (target_is_fixed or target_pos == 0): l = 1 while i - l > 0 and not fix_d . arr[i - l]: l += 1 for strand in strands_lst: if len(strand) < l: left_possible_strands . append(strand) else: left_possible_strands . append("" if i == 1 else ( fix_d . arr[i - 1] or target_strands[target_pos - 1])) if i < n and (not fix_d . arr[i + 1]) and (target_is_fixed or target_pos == len(target_strands) - 1): l = 1 while i + l <= n and not fix_d . arr[i + l]: l += 1 for strand in strands_lst: if len(strand) < l: right_possible_strands . append(strand) else: right_possible_strands . append("" if i == n else ( fix_d . arr[i + 1] or target_strands[target_pos + 1])) if not left_possible_strands or not right_possible_strands: continue blanks = [] # strands of the sizes of continuous not-fixed block l = 0 for j in range(1, n + 1): if fix_d . arr[j]: if j - l > 1: blanks . append(j - l - 1) l = j if j == i: target_blank_index = len(blanks) if l != n: blanks . append(n - l) for l_strand in left_possible_strands: for r_strand in right_possible_strands: if l_strand and l_strand == r_strand: continue left = l_strand if isinstance(l_strand, str) else l_strand[- 1] right = r_strand if isinstance(r_strand, str) else r_strand[0] # check whether Mr.wrong statement for relative position is wrong if any(1 <= i + c[1] <= n and [left, right][(c[1] + 1) / / 2] == c[0] for c in target_cond_lst if len(c) == 2): continue temp = blanks[:] strands_len_temp = strands_len_lst[:] if target_is_fixed: if isinstance(l_strand, list): temp[target_blank_index - 1] -= len(l_strand) strands_len_temp . remove(len(l_strand)) if isinstance(r_strand, list): temp[target_blank_index] -= len(r_strand) strands_len_temp . remove(len(r_strand)) else: temp[target_blank_index] -= len(target_strands) if isinstance(l_strand, list): temp[target_blank_index] -= len(l_strand) strands_len_temp . remove(len(l_strand)) if isinstance(r_strand, list): temp[target_blank_index] -= len(r_strand) strands_len_temp . remove(len(r_strand)) temp = tuple(x for x in sorted(temp) if x) # check whether we can put remaining starnds to blanks (in any order) # this method can be cached if validate(temp, tuple(strands_len_temp)): if wrong: return else: wrong = target break else: continue break else: continue break except ValueError as e: # Exception from FinalDict continue return wrong or None
Mr. Right & Mr. Wrong #2: Who is Mr.Wrong?
57a2e0dbe298a7fa4800003c
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/57a2e0dbe298a7fa4800003c
2 kyu
## Preface This is the crazy hard version of the [Prime Ant - Performance Version](https://www.codewars.com/kata/prime-ant-performance-version/) kata. If you did not complete it yet, you should begin there. ## Description, task and examples Everything is exactly the same as in the previous version (see above). You should **really** complete that first, then take your solution here and get started! ## Tests Now this is where we're going crazy! You will have **2000** test cases in the 10<sup>6</sup> to 2 * 10<sup>6</sup> range. Sounds too much? No, it isn't: the reference solution can do almost the double before timing out. Sounds too few? Well, you must leave some room for less optimized solutions :-) Also, CW would choke because of too much output... --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) #### *Translations are welcome!*
algorithms
LIMIT = 10 * * 7 / / 2 minimal_prime_factors = list(range(LIMIT + 1)) minimal_prime_factors[4:: 2] = (LIMIT / / 2 - 1) * [2] for i in range(3, int((LIMIT + 1) * * .5) + 1, 2): if minimal_prime_factors[i] == i: for j in range(i * i, LIMIT + 1, i): if minimal_prime_factors[j] == j: minimal_prime_factors[j] = i from bisect import bisect common_sequence = [0, 1, 2] computed_steps, reached_indexes, tails = [0], [2], [[]] def prime_ant(n): closest_smaller_step = bisect(computed_steps, n) - 1 idx = reached_indexes[closest_smaller_step] seq = common_sequence[: idx + 1] + tails[closest_smaller_step] for step in range(computed_steps[closest_smaller_step], n): m = minimal_prime_factors[seq[idx]] if m == seq[idx]: idx += 1 if idx == len(seq): seq . append(idx) else: seq[idx] / /= m idx -= 1 seq[idx] += m if step >= computed_steps[- 1]: common_sequence[idx:] = seq[idx:] while idx <= reached_indexes[- 1]: computed_steps . pop() reached_indexes . pop() tails . pop() computed_steps . append(step + 1) reached_indexes . append(idx) tails . append(common_sequence[idx + 1:]) return seq[2: idx + 1]
Prime Ant - Crazy Version
5a54e01d80eba8014c000344
[ "Performance", "Memoization", "Algorithms" ]
https://www.codewars.com/kata/5a54e01d80eba8014c000344
3 kyu
Given a base between `2` and `62` ( inclusive ), and a non-negative number in that base, return the next bigger polydivisible number in that base, or an empty value like `null` or `Nothing`. A number is polydivisible if its first digit is cleanly divisible by `1`, its first two digits by `2`, its first three by `3`, and so on. There are finitely many polydivisible numbers in any base. Numbers in a particular base are encoded as `String`s, with digits `['0'..'9'] + ['A'..'Z'] + ['a'..'z']`.
algorithms
from string import digits as d, ascii_uppercase as u, ascii_lowercase as l def next_num(b, n, s=d + u + l): digits = {d: i for i, d in enumerate(s[: b])} nxt, n = False, [s[0]] + list(n) inc, ptr, x = False, 1, 0 while 0 <= ptr < len(n): p = ptr + (ptr == 0 or n[0] > s[0]) inc |= ptr == len(n) - 1 and nxt == False d = (x * b % p + digits[n[ptr]] + inc + p - 1) / / p * p - x * b % p if d >= b: inc, ptr, x = True, ptr - 1, x / / b continue if d > digits[n[ptr]]: nxt, n[ptr:] = True, [s[d]] + [s[0]] * (len(n) - ptr - 1) inc, ptr, x = False, ptr + 1, x * b + d if ptr >= 0: return '' . join(n). lstrip(s[0])
Next polydivisible number in any base
5e4de3b05d0b5f0022501d5b
[ "Algorithms" ]
https://www.codewars.com/kata/5e4de3b05d0b5f0022501d5b
4 kyu
This kata concerns stochastic processes which often have to be repeated many times. We want to be able to randomly sample a long list of weighted outcomes quickly. For instance, with weights `[3, 1, 0, 1, 5]`, it's expected that index `4` occur 50% of the time, on average, and that index `2`, with no weight, never occur. The issue is that the naive method for selecting an index randomly has time complexity on the order of __O(n)__. If the number of weights is very large, this could be a bottleneck in simulation. The fastest method for this process is contant time, on order __O(1)__, assuming random values are __O(1)__ too. It involves making at most one comparison and two random calls in the sampling routine, as demonstrated below: ```python class Distribution: # preloaded def __init__(self, weights): self.weights = list(weights) self.table = make_table(weights) def sample(self): index = random.randrange(len(self.weights)) probability, alias = self.table[index] numerator, denominator = probability chance = random.randrange(denominator) if chance < numerator: return index else: return alias ``` ```python def make_table(weights): # solution return [ ((1, 1), None), ((1, 2), 4), ((0, 1), 4), ((1, 2), 0), ((1, 1), None) ] ``` ```python example = Distribution([3, 1, 0, 1, 5]) # test ``` The solution above for the `make_table` pre-processing step is incomplete since it's hard-coded and entirely ignores its argument `weights`. You can verify that the hard-coded solution works for this one example, though. Your task is to implement this function `make_table` so that its return value respects the input and can be used by the `Distribution` class as written. To be clear, only revisions to `make_table` are within the scope of the problem. In other words, given a list of integer weights, create a table so that the odds of the `sample` method returning each index will correspond with the index's weight. Note how the `sample` method works with the example solution. With probability 0/1, it never allows index `2` to be returned, substituting alias `4` instead. `4` is also substituted 1/2 the time index `1` is selected, and `0` is substituted 1/2 the time index `3` is selected. The overall odds align perfectly. When `make_table` is passed an arbitrary list of `weights`, can your code construct a similarly clever table? It should, and then the `sample` method is already written to be __O(1)__ in randomly sampling it. To pass the largest tests with over a thousand weights, your solution should run in __O(n)__ time for this pre-processing step. The result should be exact and also minimal ideally, meaning that probabilites from 0 to 1 are reduced to lowest terms. You're welcome to substitute any integer value for `None`, whose only purpose above is as an unused placeholder. Best of luck! `:~)` _Hint: The algorithm to accomplish this task is known as the alias method._
algorithms
from fractions import Fraction def make_table(weights): # Normalize probabilities n, den = len(weights), sum(weights) prob = [Fraction(w, den) * n for w in weights] # Initialize groups small, large = [], [] for i in range(len(prob)): (small if prob[i] < 1 else large). append(i) # Distribute aliases and probabilities alias = list(range(n)) while small and large: s, l = small . pop(), large . pop() alias[s] = l prob[l] += prob[s] - 1 (small if prob[l] < 1 else large). append(l) # Treat remaining items for arr in small, large: while arr: prob[arr . pop()] = 1 return [(p . as_integer_ratio(), a) for p, a in zip(prob, alias)]
Random sampling in constant time
604a1de6d117a400159239e5
[ "Algorithms" ]
https://www.codewars.com/kata/604a1de6d117a400159239e5
5 kyu
# Task John won the championship of a TV show. He can get some bonuses. He needs to play a game to determine the amount of his bonus. Here are `n` rows and `m` columns of cards were placed on the ground. A non-negative number is written on each card. The rules of the game are: - Player starts from the top-left coner, walk to the bottom-right coner. - Players can only walk downward or right. - The sum of the numbers collected by the players will be used as the bonus. John has two chances to play this game on a game map. Specifically, when John finishes the game, the card on his path will be removed, and then he can walk again. Your task is to help John calculate the maximum amount of bonuses he can get. # Input - `gameMap/gamemap`: A `n` x `m` integer array. Each element represents the number on the card. - `4 <= n,m <= 40(Pyhon)/100(JS)` - All inputs are valid. # Output An integer. the maximum amount of bonuses John can get. # Eaxmple For ``` gameMap= [ [1, 3, 9], [2, 8, 5], [5, 7, 4] ] ``` The output should be `39`. One of the possible solution is: ``` 1st game: [ [>, >, v], [2, 8, v], [5, 7, v] ] 1+3+9+5+4=22 2nd game: [ [v, 0, 0], [>, v, 0], [5, >, >] ] 0+2+8+7+0=17 Final bonus = 22 + 17 = 39 ```
algorithms
def calc(gamemap): nr, nc = len(gamemap), len(gamemap[0]) def _i(ra, rb): return ra * nr + rb vs, ws = [0] * nr * * 2, [0] * nr * * 2 for s in range(nr + nc - 1): for ra in range(max(0, s - nc + 1), min(s + 1, nr)): for rb in range(ra, min(s + 1, nr)): ws[_i(ra, rb)] = ( gamemap[ra][s - ra] + (gamemap[rb][s - rb] if ra != rb else 0) + max(vs[_i(ra - da, rb - db)] for da in (0, 1) if da <= ra for db in (0, 1) if db <= rb)) vs, ws = ws, vs return vs[- 1]
Kata 2019: Bonus Game II
5c2ef8c3a305ad00139112b7
[ "Algorithms", "Dynamic Programming", "Performance" ]
https://www.codewars.com/kata/5c2ef8c3a305ad00139112b7
5 kyu
# Basic golf rules You find yourself in a rectangular golf field like this one (ignore the borders): ``` +----------+ | ** ***| | ***| |****## | | ** | |* F| +----------+ ``` In these fields you can find empty spaces, bushes (`*`), walls (`#`) and a flag (`F`). You start from a position with coordinates `(i, j)` (row, column), with `(0, 0)` being at the top-left corner. From the position you are on, you can hit the ball in a straight horizontal or vertical line, having it land on any empty space. ``` # P -> Player, B -> Possible ball hit +----------+ | ** B ***| |BBBBPBB***| |****** | | ** | |* B F| +----------+ ``` As you can see, the ball **cannot** land on bushes. Also, **walls stop the ball in mid air**, so it's impossible to throw the ball straight over them: ``` # P -> Player, B -> Possible ball hit +----------+ | ** B ***| | #BPBB***| |****** | | #* | |* F| +----------+ ``` You can assume that the player moves to the position the ball was thrown in inmediately regardless of physical limitations (walking over bushes and stuff like that). # Your task Write a function `golf(field: List[str], i: int, j: int, hits: int)` that returns `True` when it is possible for the ball to reach the flag in `hits` movements or less and `False` in any other case. We define a movement as a hit with the rules mentioned in the previous section. The `field` argument will be given as a list of `str` and **can be mutated**, but it is not necessary to complete this task. # Golf<sup> 2</sup> Again, you have a character limit to complete this task. In this case it's **200 characters or less, and written on one single line**, but I might try to lower it depending on how you guys do ;D # Test data Your function will be tested against many fields that will be of size **12x12** at most with a maximum of **5 hits**, as well as some fixed examples that are a bit more human-readable and exact. Also, you will always start from an empty space somewhere in the map. # Examples ``` Starting from (0, 0) +----------+ |0** 1***| | ***| |****** | => Doable in 3 hits | ** | |* 2 F| +----------+ Starting from (0, 0) +----------+ |0** ***| | ***| |***#### | => Doable in 4 hits |1 2#** | |* 3 F| +----------+ Starting from (0, 0) +----------+ |0** ***| | ***| |***#### | => Impossible (note the walls) | #** | |* # F| +----------+ ``` <hr> ### Hope you have fun and obliterate my char counts as always :D *Marginal note: if you happen to be wondering why this is a code golf kata, the main reason is because I find it funny.*
algorithms
golf = a = lambda f, i, j, h, b = 0: all([i + 1, len(f) > i, j + 1, len(f[0]) > j, h + 1]) and (g := f[i][j]) != '#' and (g == 'F' or any((a(f, c / / 3 + i - 1, c % 3 + j - 1, h - (b != c), c) for c in [1, 3, 5, 7] if b == c or '*' != g)))
Golf [Code Golf]
5e91c0f2b89d48002eee828b
[ "Restricted", "Algorithms" ]
https://www.codewars.com/kata/5e91c0f2b89d48002eee828b
4 kyu
## Background ### Adjacency matrix An adjacency matrix is a way of representing the connections between nodes in a graph. For example, the graph 0 -- 1 / \ 2 - 3 can be represented as ```math \begin{bmatrix} 0 & 1 & 0 & 0\\ 1 & 0 & 1 & 1\\ 0 & 1 & 0 & 1\\ 0 & 1 & 1 & 0 \end{bmatrix} ``` ### Clique A clique is a complete subgraph -- that is, some subset of the nodes in the graph which are all interconnected to each other. In the example above, `[0,1]`, `[1,2]`, and `[1,2,3]` are some (but not all) of the cliques in the graph. `[1,2,3]` is also the *maximum* clique -- that is, the largest clique in the graph. ## Task Write a function that finds the maximum clique for a given adjacency matrix. Output should be a `set` or a `list` of the nodes of the clique. **Notes** - The graph may contain several maximum cliques. Return any one of them. - The graph will always be undirected. - The graph may be disconnected. - Order does not matter (You may also return a set). Also note that the graph might contain self-loops, and the inclusion of self-loops has nothing to do with criteria of cliqueness. ### Performance Consider the performance of your code. Input matrix size will be `n*n` where `0 <= n <= 100`. ## Random Tests Setup Each randomly generated graph `G(n, p)` is characterized by two parameters: `n` is the number of vertices, `p` is the probability of an edge between any two vertices. - 90 tests with `4 <= n <= 8` and `0.2 <= p <= 0.8`. - 90 tests with `8 <= n <= 16` and `0.2 <= p <= 0.8`. - 90 tests with `30 <= n <= 40` and `0.2 <= p <= 0.8`. ~~~if:python - 90 tests with `40 <= n <= 100` and `p = 0.5`. - 90 tests with `40 <= n <= 100`, `p = 0.5` and randomly selected large cliques (a subset of vertices is selected and all vertices in the subset are connected with edges). ~~~ ~~~if:javascript - 100 tests with `40 <= n <= 50` and `p = 0.5`. - 100 tests with `50 <= n <= 60` and `p = 0.5`. - 100 tests with `90 <= n <= 100` and `p = 0.5`. - 100 tests with `40 <= n <= 100`, `p = 0.5` and randomly selected large cliques (a subset of vertices is selected and all vertices in the subset are connected with edges). ~~~
algorithms
def maximum_clique(adjacency): """Maximum clique algorithm by Carraghan and Pardalos""" if not adjacency: return set() graph = {} for a, row in enumerate(adjacency): for b, connected in enumerate(row): if connected: graph . setdefault(a, set()). add(b) if not graph: return {0} def clique_search(subset, clique): nonlocal max_clique if not subset: max_clique = max((max_clique, clique), key=len) return while subset: if len(subset) + len(clique) <= len(max_clique): return x = subset . pop() clique_search(subset & graph[x], clique | {x}) max_clique = set() clique_search(set(graph), set()) return max_clique
Maximum clique
55064222d54715566800043d
[ "Algorithms" ]
https://www.codewars.com/kata/55064222d54715566800043d
4 kyu
Given a height map as a 2D array of integers, return the volume of liquid that it could contain. For example: heightmap: 8 8 8 8 6 6 6 6 8 0 0 8 6 0 0 6 8 0 0 8 6 0 0 6 8 8 8 8 6 6 6 0 filled: 8 8 8 8 6 6 6 6 8 8 8 8 6 6 6 6 8 8 8 8 6 6 6 6 8 8 8 8 6 6 6 0 result: 4*8 + 4*6 = 56 For this heightmap, you would return 56: were you to pour water over it until it couldn't contain any more, it would look like the second heightmap, taking on 56 units of water in the process. Water pours off the edges of the heightmap, even when they are negative. It doesn't flow through diagonal cracks (note the lower-right corner of the example). Heightmaps in the test cases will come in many different sizes, and some will be quite large, but they will always be rectangular. Heights may be negative. ### Performances requirements: Think about the efficiency of your solution: ```if:python * 50 big random tests and maps around 100x100 ``` ```if:rust * 75 large random tests, where `80 <= width|height <= 100` and `-50 <= depth <= 150 ``` ```if:javascript * 100 large random tests, where `120 <= width|height <= 130` and `-50 <= depth <= 150 ```
algorithms
from heapq import heapify, heappop, heappush def volume(heightmap): N, M = len(heightmap), len(heightmap[0]) if N < 3 or M < 3: return 0 heap, seen = [], [[0] * M for _ in range(N)] for x in range(N): for y in range(M): if not x * y or x + 1 == N or y + 1 == M: heap . append((heightmap[x][y], x, y)) seen[x][y] = 1 heapify(heap) water, level = 0, - float('inf') while heap: height, x, y = heappop(heap) level = max(level, height) for i, j in (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1): if N > i >= 0 <= j < M and not seen[i][j]: heappush(heap, (heightmap[i][j], i, j)) water += max(0, level - heightmap[i][j]) seen[i][j] = 1 return water
Fluid Volume of a Heightmap
5b98dfa088d44a8b000001c1
[ "Algorithms" ]
https://www.codewars.com/kata/5b98dfa088d44a8b000001c1
3 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" /> --- # Hint This Kata is an extension of the earlier ones in this series. Completing those first will make this task easier. # Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type words... # Keyboard The screen "keyboard" layouts look like this <style> #tvkb { width : 400px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { color : orange; background-color : black; text-align : center; border: 3px solid gray; border-collapse: collapse; } #legend { width : 400px; border: 1px solid gray; border-collapse: collapse; } #legend td { text-align : center; border: 1px solid gray; border-collapse: collapse; } </style> <table> <tr> <th>Keypad Mode 1 = alpha-numeric (lowercase) <th>Keypad Mode 3 = symbols </tr> <tr> <td> <table id = "tvkb"> <tr><td>a<td>b<td>c<td>d<td>e<td>1<td>2<td>3</tr> <tr><td>f<td>g<td>h<td>i<td>j<td>4<td>5<td>6</tr> <tr><td>k<td>l<td>m<td>n<td>o<td>7<td>8<td>9</tr> <tr><td>p<td>q<td>r<td>s<td>t<td>.<td>@<td>0</tr> <tr><td>u<td>v<td>w<td>x<td>y<td>z<td>&#x005f;<td>/</tr> <tr><td>aA#<td>SP<td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"></tr> </table> </td> <td> <table id = "tvkb"> <tr><td>^<td>~<td>?<td>!<td>'<td>"<td>(<td>)</tr> <tr><td>-<td>:<td>;<td>+<td>&<td>%<td>*<td>=</tr> <tr><td><<td>><td>&#x20ac;<td>&#x00a3;<td>$<td>&#x00a5;<td>&#x00a4;<td>\</tr> <tr><td>[<td>]<td>{<td>}<td>,<td>.<td>@<td>&#x00a7;</tr> <tr><td>#<td>&#x00bf;<td>&#x00a1;<td style="background-color:orange;"><td style="background-color:orange;"><td style="background-color:orange;"><td>&#x005f;<td>/</tr> <tr><td>aA#<td>SP<td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"></tr> </table> </td> </tr> </table> * `aA#` is the SHIFT key. Pressing this key cycles through <span style="color:red">THREE keypad modes.</span> * <span style="color:red">**Mode 1**</span> = alpha-numeric keypad with lowercase alpha (as depicted above) * <span style="color:red">**Mode 2**</span> = alpha-numeric keypad with UPPERCASE alpha * <span style="color:red">**Mode 3**</span> = symbolic keypad (as depicted above) * `SP` is the space character * The other (solid fill) keys in the bottom row have no function ## Special Symbols For your convenience, here are Unicode values for the less obvious symbols of the **Mode 3** keypad <table id="legend"> <tr><td>&#x00a1; = U-00A1<td>&#x00a3; = U-00A3<td>&#x00a4; = U-00A4<td>&#x00a5; = U-00A5</tr> <tr><td>&#x00a7; = U-00A7<td>&#x00bf; = U-00BF<td>&#x20ac; = U-20AC<td></tr> </table> # Kata task How many button presses on my remote are required to type the given `words`? ## Notes * The cursor always starts on the letter `a` (top left) * The inital keypad layout is **Mode 1** * Remember to also press `OK` to "accept" each letter * Take the shortest route from one letter to the next * The cursor wraps, so as it moves off one edge it will reappear on the opposite edge * Although the blank keys have no function, you may navigate through them if you want to * Spaces may occur anywhere in the `words` string * Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before). In other words, do not try to optimize total key presses by pressing SHIFT early. ```if:c,cpp ## C/C++ warriors The standard I/O libraries choke on wide characters beyond the value 255. This kata includes the Euro € (U-20AC). So the function `ws2utf8()` has been preloaded for converting wchar_t strings to UTF-8 for printing. ``` # Example words = `Too Easy?` * T => `a`-`aA#`-OK-`U`-`V`-`W`-`X`-`Y`-`T`-OK = 9 * o => `T`-`Y`-`X`-`W`-`V`-`U`-`aA#`-OK-OK-`a`-`b`-`c`-`d`-`e`-`j`-`o`-OK = 16 * o => `o`-OK = 1 * space => `o`-`n`-`m`-`l`-`q`-`v`-`SP`-OK = 7 * E => `SP`-`aA#`-OK-`A`-`3`-`2`-`1`-`-E`-OK = 8 * a => `E`-`1`-`2`-`3`-`A`-`aA`-OK-OK-`a`-OK = 9 * s => `a`-`b`-`c`-`d`-`i`-`n`-`s`-OK = 7 * y => `s`-`x`-`y`-OK = 3 * ? => `y`-`x`-`w`-`v`-`u`-`aA#`-OK-OK-`^`-`~`-`?`-OK = 11 Answer = 9 + 16 + 1 + 7 + 8 + 9 + 7 + 3 + 11 = 71 <hr style="background-color:orange;height:2px;width:75%;margin-top:30px;margin-bottom:30px;"/> <span style="color:orange;"> *Good Luck!<br/> DM.* </span> <hr> Series * <a href=https://www.codewars.com/kata/tv-remote>TV Remote</a> * <a href=https://www.codewars.com/kata/tv-remote-shift-and-space>TV Remote (shift and space)</a> * <a href=https://www.codewars.com/kata/tv-remote-wrap>TV Remote (wrap)</a> * TV Remote (symbols)
algorithms
H, W = 6, 8 KEYBOARD = ["abcde123fghij456klmno789pqrst.@0uvwxyz_/\u000e ", "ABCDE123FGHIJ456KLMNO789PQRST.@0UVWXYZ_/\u000e ", "^~?!'\"()-:;+&%*=<>€£$¥¤\\[]{},.@§#¿¡\u000e\u000e\u000e_/\u000e "] MAP = [{c: (i / / W, i % W) for i, c in enumerate(KEYBOARD[x])} for x in range(len(KEYBOARD))] def manhattan(* pts): dxy = [abs(z2 - z1) for z1, z2 in zip(* pts)] return 1 + sum(min(dz, Z - dz) for dz, Z in zip(dxy, (H, W))) def tv_remote(words): cnt, mod, was = 0, 0, 'a' for c in words: while c not in KEYBOARD[mod]: cnt += manhattan(MAP[mod][was], MAP[mod]['\u000e']) was = '\u000e' mod = (mod + 1) % 3 cnt += manhattan(MAP[mod][was], MAP[mod][c]) was = c return cnt
TV Remote (symbols)
5b3077019212cbf803000057
[ "Algorithms" ]
https://www.codewars.com/kata/5b3077019212cbf803000057
5 kyu
This kata is similar to [All Balanced Parentheses](https://www.codewars.com/kata/5426d7a2c2c7784365000783). That kata asks for a list of strings representing all of the ways you can balance `n` pairs of parentheses. Imagine that list being sorted alphabetically (where `'(' < ')'`). In this kata we are interested in the string at index `k` in that sorted list. ## Examples ``` balanced_parens(0, 0) => [""][0] = "" balanced_parens(1, 0) => ["()"][0] = "()" balanced_parens(2, 0) => ["(())","()()"][0] = "(())" balanced_parens(2, 1) => ["(())","()()"][1] = "()()" balanced_parens(3, 3) => ["((()))", "(()())", "(())()", "()(())", "()()()"][3] = "()(())" ``` Write a function `balanced_parens(n, k)` that returns the string at index `k` in the sorted list of all strings of `n` balanced parentheses pairs. If `k` is negative or out of bounds, the function shall return `None` (or `null`, `Nil`, etc., depending on language). Input constraints: + `0 <= n <= 200` + `k` can take any integer value. Note that, when `n = 200`, the full list contains more strings than there are atoms in the universe.
reference
from math import factorial dyck = [factorial(2 * i) / / (factorial(i) * factorial(i + 1)) for i in range(201)] def dyck_triangle(n): arr = [[0 for j in range(2 * n + 1)] for i in range(n + 1)] for i in range(n + 1): arr[i][2 * n - i] = 1 for i in range(n + 1): arr[0][2 * (n - i)] = dyck[i] for k in range(1, n): for i in range(1, n - k + 1): arr[i][2 * (n - k) - i] = arr[i + 1][2 * (n - k) - i + 1] + \ arr[i - 1][2 * (n - k) - i + 1] return arr def balanced_parens(m, n): if n < 0 or n > dyck[m] - 1: return None arr = dyck_triangle(m) x, y = 0, 0 if n == 0: return "(" * m + ")" * m st = "" while n > 0: while arr[x + 1][y + 1] > n: x, y = x + 1, y + 1 st += "(" n -= arr[x + 1][y + 1] x, y = x - 1, y + 1 st += ")" if n == 0: st += "(" * (m - (x + y) / / 2) st += ")" * (m - (y - x) / / 2) return st
Balanced parentheses string
60790e04cc9178003077db43
[ "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/60790e04cc9178003077db43
4 kyu
It is a kata to practice knapsack problem. https://en.wikipedia.org/wiki/Knapsack_problem You get a list of items and an integer for the limit of total weights `(w_limit)`. Each item is represented by `(weight, value)` Return the list of maximum total value with the sorted lists of all lists of values that are also sorted. i.e. ` [ max_value, sorted_list( sorted_list A ,sorted_list B, ... ) ]` See example test cases for what is expected for output data.
algorithms
def knapsack(items, w_limit): dpt = {0: [[0, [[]]] for _ in range(w_limit + 1)]} for i in range(len(items)): dpt[i + 1] = [] for j in range(w_limit + 1): if items[i][0] > j or dpt[i][j - items[i][0]][0] + items[i][1] < dpt[i][j][0]: dpt[i + 1]. append(dpt[i][j]) elif dpt[i][j - items[i][0]][0] + items[i][1] == dpt[i][j][0]: dpt[i + 1]. append([dpt[i][j][0], dpt[i][j][1] + [x + [items[i][1]] for x in dpt[i][j - items[i][0]][1]]]) else: dpt[i + 1]. append([dpt[i][j - items[i][0]][0] + items[i][1], [x + [items[i][1]] for x in dpt[i][j - items[i][0]][1]]]) return [dpt[len(items)][- 1][0], sorted(map(list, {tuple(sorted(x)) for x in dpt[len(items)][- 1][1]}))]
Knapsack problem - the max value with the lists of elements
5c2256acb26767ff56000047
[ "Algorithms" ]
https://www.codewars.com/kata/5c2256acb26767ff56000047
4 kyu
## Play game Series #8: Three Dots ### Welcome In this kata, we'll playing with three dots. ### Task You are given a `gamemap`, like this: ``` +------------+ |RGY | +,-,| --> The boundary of game map | | * --> The obstacle | ** | R,G,Y --> Three Dots with different color(red,green,yellow) | ** | r,g,y --> The target position of three dots | | You should move R to r, G to g and Y to y | rgy| +------------+ ``` In the testcase, it displayed like this: <img src=" data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAH0ElEQVR4nO2cPW7b2hZGFyBALQUIcM1WgLq0t0nnwu0F5OY1t4hHkCZNZiBNIs0rnQFoCOIk7AHYAzivEEn9kfGhrv2sc7Q+4GsIZ3nDxMomJUqEv/8brLV5lM8ewFr7fm2F/vLli7U20QKcCA28S/d+iTx58v4PPCBO6BLCEsIGQqi7qY+V5ww8IXBL4IHAz7oP9bHJcF5ZEpZLwmZDCGHbzWZ7rCzTPUHy5A3hAW8LvWIncV+XQwa+ZSdxX2/jeavVTuK+LpdpniB58obwgD8LXfG2zE03MQPvb+S3+vA2r6relnl/Y6d2guTJG8ID+oWO2czHXf1p4JjNfNzbfl7MZj7uapXWCZInbwgP6Ba6ZLjMTcuugScMl7np5JRXlsNlbtrcU6dwguTJG8IDuoU+Zzs3XdEx8DnbuentKe+c7Xy8pVM4QfLkDeEB3UIPuXc+7oaOgYfcOx/34ZQ35N657146hRMkT94QHtAtdPiXPRn457/sEe9cmZumcoLkyRvCAxT6kk+QPHlDeMD7X3JXXQNf0CV3VaVzguTJG8IDfFHskk+QPHlDeIBvW13yCZInbwgP8MGSSz5B8uQN4QHv9+hn1fELTgb+xEc/m3vnlE6QPHlDeMD7fDhj1fMLOgf+hA9n7G/mlE6QPHlDeED8xydXHG7sqj5WnjPwB3x8crU63NhVtT3mxyflXQsP8AsO5MnLhQecCm2tTbMKbW1G7RT6ki8p5MmT188DFFqevFx4gELLk5cLD1BoefJy4QEKLU9eLj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6MDkU/mu5+Fl5dRCGH7b/Z5gELLy59XstvMi1rmu/k8rCeT8DQeh6fxOKwnk3A3n7dSNz9fds03od28jczzv+Zh8jAJ4+/jMP4+DpOHSZj/NW+lbjf1pGO+creZF4t6vrt5WK8n4elpHJ6exmG9noS7u3krdfPzzT21Qsu7Gl6znX/d3LQyN1t4vy+jUSv1Y335veqar97ON/+5aWVut/BeRz9GrdTt5fdtx3z1dv7166aVudnC+315GbVSPz5OD7a0Qsu7Gl5z79xs53VR9L4gti6Kgy296ZqvvndutnPxreh9Qaz4Vhxu6YeO+arD7bxeF70viK3XxcGWbu6lFVre1fBC3ebYa8d2bvo0Hrc/1xw7me/nts2xru3cdPx9x2uPH89Xy9rO93q6nZs+Pe3NVx9reIBCy8ufF4gX+vnChX5+Vmh5V84755J7UV9yV13zXcAl92KxveSuqh0PUGh5+fO6XhTr2tKvF/SiWNeWfn31RTF58vrftiqK8Dweh+fxOKyLopV5cebbVsW3on3bqvhWvMPbVkV4fh6H5+dxWK+LVuZmO/u2lbyr5e0/WLL4w4Mliwt4sKSRunO+hQ+WyJMX4PTRz32xF7NZe5kd2N07/3G+D370c1/sxWLWXmbv3zvv8wCFlnddvJgPZ6wG8D7jwxn7m3mfByi0vOvjlWyl3d/YVX2sPGe+D/j45Gp1uLGranvMj0/Kk3clPMCvILI2l54IjTEm6RwIba1NvwptbUb97KsEY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcZ8Sv4HovzqEfw7xpIAAAAASUVORK5CYII="> Your task is calculate a path to move three dots from the initail position to the target position. The result should be a string. Use `↑↓←→` representing four directions(`up,down,left and right`). ### Moving Rules - When the move command(`↑↓←→`) is executed, the three dots move in the same direction at the same time unless the boundary or barrier is in front of them. - Only the dot blocked by the obstacle will stop moving, and the dots that does not encounter obstacles will continue to move. Like the example above, you can return a `path` like this: ``` "→→→→→→→→→↓↓↓↓↓" ``` After move right x 9: <img src=" data:image/png;base64,iVBORw0K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t7pwvcGUe73D46QEGrZff66iP+bqudL436mO+7q1wvq4+5uuur6kNWm8z3jNX5+sOBe+pq/N1u8L5nrg6j6/SBq23Ga/mtfN4x4JX9dp5vI/C+SpeO0+9ljZovc14/Yu7Od/nixuf78mYr7t6gEHr5ff6F3dzvs8XNz6fQevpxb1XnnKfSudb0VPu0+nbAwxaL7/nH4qt/AOkp1fjdTwfdFc6n//bSk9vWc+/WLLyD5CeXq1X81r6FPCW/Kuf19fOQw8waL1teZEr9aHCW+IfZwyvzEMPMGi97Xkd52iHV+zT5bbumfP9wj+fPBx+XrFPp/Nt/vNJPb2NeIBfgsi5LLsJGt98863ptx9BO+faH8z0PN45t4otfgDn3Hxb/ADOufm2+AGcc/Nt8QM45+bb4gdwzs23xQ/gnJtvix/AOTffFj+Ac26+Vf6Er8sY/HerG74vVry/f88bf394W8RY+tfhQqu489fo27/1ydxAJK2ddSrIaKgG3cwq7lz65B1fsR+Nwv1Lt02FMv6x0uM/sqd+fPzrfHSf0lmW/4AWVwrSK3TKVdz5XmTjb099okejjjz+lPtK1LXnW3HEw42D9Cl32lXcea6gp658cwX9yo8Pz1hrrHg+5d7MKu5876lp5LZ7xtTPjTx+zePWPHOoNVY8g97MKn/C1Gvc6Ovnqfveu730OKXvR84QOeOj20v3gZ/nWtHGf6rtn3Kn3uIHcCvfM78BuMW2+AFcAzPmZrb4AZxz823xAzjnZtp/mNJ7nda3Ge4AAAAASUVORK5CYII="> So easy! right? ;-) Please write a nice solution to solve this kata. I'm waiting for you, code warrior `^_^` ### Note - You can assume that all test cases have at least one possible solution. Of course, usually it has many solutions, and you just need to return one of them. - Somethimes, the obstacle/boundary may be your enemy or your friend ;-) ### Examples Let's see some `harder` examples: For `gameMap = ` ``` +------------+ |R | |G | |Y ** | | ** r| | g| | y| +------------+ ``` The output can be `"→→→→→←↓↓↓↓→→→↑↑→→→→→↓"` Let's see the moving step by step: initial game map: <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCA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K3Jf1utsDLLSe3li8/b4p7d3dPFxfNzeWXF8vwp8/86Md+9QDLLSe3hi8uDM/Pk6Oinya6+tFeHychBAO/6btARZaT++zvbJsdubVqvrC96tl2G5n4f5+Gu7vp2G7nYWrq2Vd6vjz8ZraQuvpjcSLu/Pv3xd1meMu3M7j46Qu9d3d/GiXttB6eiPx4rVz3J2326L3BbHttjjapeO1tIXW0xuJF8sajz09Pd+dY+7vm48giseiB1hoPb3P9t5S6IcHC62nN2rvPafcq9XhlHu/bzzAQuvpfbbX9aJY1y799OSLYnp6o/f637YqwsPDNDw8TMN2W9Rljruzb1vp6Y3Ua99YEkvdldXKG0v09JLwTm/9bBd7tVrUp9nta+e2B1hoPb0xeUMezmjvzG0PsNB6emPzyvJQ2vaOvd8fjvn4pJ7eF/EAP4LImFzyrNA4jpP0HBXaGJN+LLQxGeWzzxIcx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx3Ecx/mU+R9SVuoRxvpVEQAAAABJRU5ErkJggg=="> First we move three dots to the right: `→→→→`, after move right x 4: <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAI+ElEQVR4nO3dMW7bWBuF4RcQoFYCDKRmK8Bd2mnSuUg7gNz8zRTxCtKk8Q6kTaRJ6VmAliBtwi6nsBdw/0IiRcmkTdq64iX1GjiYDEM/vhzl5CMlSkP4+08wxgwjdL0AY8zpUhT669evxpieBuBVoYGTpPRD9PT0zuABFvocXgZhAWENIeyy3m3LElif3jA8wELH9pbsS1yXxYCOV687D7DQMb0N75c5z3oAx6vXrQdY6Fhek8l8nGWPj1evew+w0DG8jPZlzpP18Hj10vAACx3D+8h0zrOs8FI/Xr00PMBCx/DaXDsfZ13hpX68eml4gIWO4YVPpm/Hq5eGB1joGF74ZPp2vHppeICFjuF95pR708Pj1UvDAyx0DM8nxfS68AALHcPL8GUrvfN7gIWO5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kx5/NZcZpdvnYue4CF1tNLyWvy5ozyZC57gIXW00vNy7JtacsTe7PZbvPtk3p6F+IBfgSRMUPJq0Ljl19+9frroNDGmP4HTnQeb4xJIp0vwBhzunS+AGPM6dL5Aowxp0vnCzDGnC6dL8AYc7p0vgBjzOnS+QKMMadL5wswxpwuLb/hzy6U/nmpKf+3SDT//bdP12sxZ0mLnf8c/TrWH+bES9LXtVrqi0iLnav+8B5P7PdCxf5V2+qKcvx7VT//Pbvu94+P8719qtbS/QNamc+W2b8MepMWO79VsuNf1/1Bb1rqJj+/zv1MqduuL+ES52l6yl0+Pa9L18di3k2LnU9V6LrJd6pCf+b3y2tsaySezxTSMvcmLXZ+69S0yba3jLrvbfLz2/zcNmcObY3EYykvIi2/oe4at+n1c92+b22v+jlV/95kDU3W+N72qn3gcF2JxNPli0vnCzDGnC6dL8AYc7p0vgBjzOnS+QKMMSfK/wGQgbZ4N8j5rAAAAABJRU5ErkJggg=="> Then, continue the moving: `→` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAI9UlEQVR4nO3dsXLaWB+G8WeGGVqYYSa1Wmbcpd0mnYu0O4Obr9kivoI0aXwHcBNpUjoXwCXATdhlCvsCzleAhMCSkTBE54jHM+9sVpF/Plry5i+BYAn//grGmH6ErhdgjDlfikJ//vzZGJNoAN4UGjhLSj9ET0/vL3iAhU7RyyDMIawghG1W221ZBOvT68YDLHRq3oJdiesy79Hx6jX3AAudkrfmeJnzrHpwvHrtPMBCp+I1mcyHWSR8vHrtPcBCp+BltC9znizB49U7zQMsdAreKdM5z6LCi/149U7zAAudgtfm2vkwqwov9uPVO80DLHQKXvhgUjtevdM8wEKn4IUPJrXj1TvNAyx0Ct5HTrnXCR6v3mkeYKFT8HxSTK+JB1joFLwMX7bSO+4BFjoVzxtL9I55gIVOyWtzLb1u4MV+vHrtPMBCp+Y1mdSLFl7sx6vX3AMsdIpexqa05Ym93m7LIlifXjceYKH19PriAW8LbY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zBRhjzpfOF2CMOV86X4Ax5nzpfAHGmPOl5Tf82obSP6815f8WkefPn+7XYP5KWuz86+DXl/rDnEhJUlnrnz8W+orSYueqP7yHE/tYqNi/altdUQ5/r+rnH7Prfv/wOI/tU7WW7h/QNzlHof0LIZm02Pm9kh3+uu4PetNSN/n5de5HSt12fZGWOE9exCaFzIv/Xro+HnM0LXY+V6HrJt+5Cv2R3y+vsa0RYc5VSMucTFrs/N6paZNt7xl139vk57f5uW3OHNoaEcdCXk1afkPdNW7T6+e6fd/bXvVzqv69yRqarPHY9qp9YH9dkcVCX006X4Ax5nzpfAHGmPOl8wUYY86XzhdgjDlT/g9sL7hU2vaSKQAAAABJRU5ErkJggg=="> Now, we can see: `Y` was stoped, but `R` and `G` move to right. Hmm.. we should move to left 1 step: `←` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAI7klEQVR4nO2dMW7bWBsABxCgVgIMpGYrwF3abdK5SLuA3PzNFvEJ0qTxDaRLpEnpPYCOIF3CLrewD/D+QiJFyaRN2qL4+DQGBpvQ9PgxzuQjJUpL+PtPEJE0oO8FiMjpKIL++vWriAwUgFdBAyeh9E306dN3Bh9g0OfwZRAWENYQwo71blsWwfr0peEDDLpr35J9xHUsEjpeff35AIPu0rfh/Zhz1gkcr75+fYBBd+VrMpmPWQ74ePX17wMMugtfRvuYc7IBHq++OHyAQXfh+8h0zllW+GI/Xn1x+ACD7sLX5tr5mHWFL/bj1ReHDzDoLnzhkwztePXF4QMMugtf+CRDO159cfgAg+7C95lT7s0Aj1dfHD7AoLvw+aCYvj58gEF34cvwaSt95/cBBt2VzxtL9J3bBxh0l74219KbBr7Yj1dfvz7AoLv2NZnUyxa+2I9XX38+wKDP4cvYRlue2JvdtiyC9elLwwcYtD59qfiA10GLyDAxaJGEqAw65lMKffr01fsAgz6Lb0rghsAdgfsdd7tt0wjWpy8JH2DQnftu2Edcx01Cx6uvNx9g0J36yhP5Pe4SOF59vfoAg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wWO/85+nVXf5kHEslQ1mrIF0WLnav+8h5P7PegYv+qbXWhHH+u6vu/5677/PFxvrdP1Vr6/4G+os10Nv7B02LntyI7/nXdX/SmUTf5/nXez0Tddn2RRlzFe7Hm4b9F38cg79Ji51MFXTf5ThX0Zz5fXmNbR+Q0CdJoB0+Lnd86NW2y7S1H3dc2+f5tvm+bM4e2jsgx1oug5RfUXeM2vX6u2/et7VXfp+r3TdbQZI3vba/aBw7XFQmeLl8cvS9ARE5H7wsQkdPR+wJE5HT0vgARORH/B9H6tJw7skFzAAAAAElFTkSuQmCC"> Then moving the dots downward: `↓↓↓` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAIhklEQVR4nO2dPW7bShtGDyBALQUISK1WgLq0t0nnwu0HyM3X3CJeQZo0dwf2JtKkdBagJVibsMtb2AuYW1iUKZqUSZk0h6Mj4EFsijqaEd/DGf5YIfzvdzDGpBGGboAxprvshf769asxZqQBeCM00EkKbyJPnrxP4AEKLU9eKjxAoeXJS4UHKLQ8eanwAIWWJy8VHqDQ8uSlwgMUWp68VHiAQsuTlwoPUGh58lLhAQotT14qPECh5clLhQcotDx5qfAAhZYnLxUeoNDy5KXCAxRanrxUeIBCy5OXCg9QaHnyUuEBCi1PXio84K3QxphxRqGNSSiVQsc8pZAnT149D1BoefJS4QEKLU9eKjxAoeXJS4UHKLQ8eanwAIWWJy8VHqDQ8uSlwgMUWp68VHiAQsuTlwoPUGh58lLhAQotT14qPECh5clLhQcotDx5qfAAhZYnLxUeoNDy5KXCAxRanrxUeIBCy5OXCg9QaHnyUuEBfgWRMalEoY1JKJVCxzylkCdPXj0PUOgx8DrYc/fKi/3zOxceoNBj4Cm0vCY8QKHHwFNoeU14gEKPgafQ8prwAIUeA0+h5TXhAQo9Bp5Cy2vCAxR6DDyFlteEByj0GHgKLa8JD1DoMfAUWl4THqDQY+AptLwmPEChx8BTaHlNeIBCj4Gn0PKa8ACFHgNPoeU14QEKPQa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91ll8AaYiJLLr9SjzeANMJFFmUedwRtgjOkugzfAGNNR/gM7lbowrtdVJwAAAABJRU5ErkJggg=="> Hmm.. Not enough. Continue to move downward: `↓` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAIq0lEQVR4nO2dv27iyh9Hj4RECxJSalqkdNveZrsUaa9Eml9zi80TbLPNvkHyEttsmX0AHiF5iaS8BXmA+RXBxjg22NhcPMNB+miTwRzG3jl8x39wCH//DsaYNMK5O2CM6S+50F++fDHGRBqAT0IDvaTwJvLkyfsPeIBCy5OXCg9QaHnyUuEBCi1PXio8QKHlyUuFByi0PHmp8ACFlicvFR6g0PLkpcIDFFqevFR4gELLk5cKD1BoefJS4QEKLU9eKjxAoeXJS4UHKLQ8eanwAIWWJy8VHqDQ8uSlwgMUWp68VHiAQsuTlwoP+Cy0MSbOKLQxCaVS6CFPKeTJk1fPAxRanrxUeIBCy5OXCg9QaHnyUuEBCi1PXio8QKHlyUuFByi0PHmp8ACFlicvFR6g0PLkpcIDFFqevFR4gELLk5cKD1BoefJS4QEKLU9eKjxAoeXJS4UHKLQ8eanwAIWWJy8VHqDQ8uSlwgMUWp68VHiAtyAyJpUotDEJpVLoIU8p5MmTV88DFDoGXg+f3CflDX37XQoPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUOgYeAotrwkPUGh58lLhAd6CyJhUotDGJJRKoYc8pZAnT149D1DoGHg9fHKflDf07Rcbbw7hAcIzhLDJ86ZtvocHKHQMPIW+HN4jW4nr8lDDAxQ6Bp5CXwbvha20T7NZuFss8uXuFovwZzbbqdhlHqDQMfAUOn1eVpnXo9GOyOXcLRZhPRqFsHlNkQcodAw8hU6bN2dbmZcbmW+vr8NqOg2v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WM7j457+NanM5dzs4Q18+8nrZ/yt16Mdkcu5u1uE9XpUOf4AhYaP/ZK2MmfJ9ml2+le42L51phW8gW8/ef2Nv+Vy8wffb6/DajUNr6/j8Po6DqvVNNzeXudSV40/QKHhuOpcrtI7/TumOme5qeANfPvJ62f8/fp1lcucVeFi1utRLvXT0+zT+AMUGtrtO9ftS+/0r82+czn3FbyBbz95/Yy/rDqvVpPa8bZaTXaqdHH8AQoNx8uc5VP/fnZMZNtPXj/jL2t7f/9cnbO8vm5vQVQef4BCFzeoQss75/hrIvTbm0If5HWZcr+8VPTPKbe8I8Zfmyn3crn4NP4AhQYPiskbxvgrHhSrqtLv7x4Ua8TztJW8oYy/3dNWk/D2Ng5vb+OwWk1ymbPqXB5/gEJnv3thibwhjL/1epRLXZXl0gtLGvPa7Etn+y57++eln/Ja8MqXfhbFXi4X+TS7bvwBCl1ub1Kpi5+MB/vnlzPkteB1GX+AQlc9N59/bLTiJ+bLy0ebX5+UN9TxByi0PHmp8ABvQWRMKvkkND58+Ij6sSO0MSb+QE/zeGPMIHL2Dhhj+svZO2CM6S9n74Axpr+cvQPGmP5y9g4YY/rL2TtgjOkvZ++AMaa/nL0Dxpj+0vIFvzeh8O+lprgtBpx///1Im+XP3WdzdFos/Lv086kGcwSSxNLXopxNRVXoqNNi4arBW67Yh0LF8lVtdaKUn6t6/0PsuufL63lomaq+nP8/dCcKfXFpsfA+yco/1w30plI3ef86bhep2/ZvgBIXo9AXlxYL9yV0XeXrS+guzxf72JYx0GT70Ap9EWmx8L6paZO2fYy61zZ5/zbv22bm0JYx4HhQ7GLS8gV1+7hN95/rlt3XXvU+Vb836UOTPh5qr1oGdvs1kLQ9wp295tz9Nkfn7B0wA0rb6bkZXM7eATOwKHPUOXsHjDH95ewdMMb0lP8DDGm6MHKHGusAAAAASUVORK5CYII="> Now dots can finally move to the right: `→→→` Hey! Wait, Their shape is incorrect: <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA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U+hJ5Xc6dm86l9/rX5dy5mrsa3sCP32eNR16d1+us8fiv19lelS6PB6DQl8g7VuY87/r388REdvw+azzyttfX99U5z9PT7hFE1fEAFPoSeQo9LF4XoZ+fFVpehXfKlHuzqemfU+5exqPLlHu5nL8bD0ChL5HnRbFh8eouitVV6ddXL4rJq+F522pYvObbVll4fh6H5+dxWK+zQua8OlfHA1DoS+W5sGRYvPLCklzquiyXLiyR18Drci6dn6sd7J9LP3sbj4eH6Z7Yy+W8mGY3jQeg0JfOa1Opy5Xgw/754YyzjQeg0PLezsNWq/0Ksdm8tfnxyXjGA1BoefJS4QE+gsiYVPJOaPzyy6+ov/aENsbEH+hpHm+MGUTO3gFjTH85eweMMf3l7B0wxvSXs3fAGNNfzt4BY0x/OXsHjDH95ewdMMb0l7N3wBjTXzr+wu9tKP33UlM+FgPOv/++5aM2k0Q6bPy78v1nvZkjkCS2vpblbfreJJEOG9e9easV+6NQs31dW5Mo1Z/Vvf5H7KafV/fzo23q+nL+Aa1Nk7inCO0fg0Gmw8aHJKt+3/RGbyt1m9dv4p4iddf+DVjico4VOp+aH8q5983spcPGfQndVPn6EvqUn5f72JUx4NSJd6qMyjzIdNj40NS0TdshRtPvtnn9Lq/bZebQlTHg1F0Uq2s30afjLzSd47Y9f27a9lB73evU/btNH9r08aP2um1gv18DSnV67JQ56Zy9A8aY/nL2Dhhj+svZO2CM6S9n74Axpqf8H9Llyuxz33D/AAAAAElFTkSuQmCC"> So we need some extra steps: `↑↑` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAIvElEQVR4nO2dMW7bSB9HHyBALQUIcK1WgLq026Rz4fYD5OZrtohPkCZNbmBfIk1K5wA6gnUJu9zCPsBsYVGmadIWRXo5M3oCfohDU0/DjJ//Q3I4IfzvdzDG5BHGboAxZrjshf7y5YsxJtEAvBEaGCSVD5EnT95/wAMUWp68XHiAQsuTlwsPUGh58nLhAQotT14uPECh5cnLhQcotDx5ufAA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c6/XyzRpvgELLkzc2r+miWFOVfnryopg8edHz2m9bFeHhYRoeHqZhsyn2MpfV2dtW8uRFyqtOLCmlbsp67cQSefKS4NWnflbFXq+X+2F22xpvgELLkxcTr88ab4BCy5MXG+/YNd4AhZYnLxce4BJExuSSN0Ljy5evpF+vhDbGpB8YaBxvjIkiozfAGDNcRm+AMWa4jN4AY8xwGb0BxpjhMnoDjDHDZfQGGGOGy+gNMMYMl9EbYIwZLh3f8HsXKn+eaqr/FhHnn3+e07S9C2Ps4zAHpcPOv2tff9YPcwKSpNbWupBtkre9t8v+ZtR02Lnph7desT8KDfs3bWsTpf69ps//iN32/fpxfrRPU1vG79DG9BG66f0m2nTY+T3J6l+3/aAfKvUhn9/G7SN11/ZFLHE1VSHLrxU6y3TYeSih2yrfUEL3+X61jV0ZEacudNdhtEInkw47vzc0PWTbe4y29x7y+V0+t8vIoSsj4nhR7GTS8Q1t57iHnj+37fve9qbPafr7IW04pI0fbW/aB163K6K0VWOFzjKjN8AkEIVOJqM3wCQQhU4mozfAGDNcRm+AMWag/AvyPsrs29R9WAAAAABJRU5ErkJggg=="> Now we can move to the right again ;-) `→→→→` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAHUUlEQVR4nO3csW7aahyG8UdCYgUpUmdWpGxdu3TL0PVIyXKWDskVdOmSO0huokvHnAvgEuAmkrFDcgHfGYLBgA0YnNr++4n0qqljfnxN8+b7DLZJ//xOxpgYoekBGGPqy6rQnz9/NsZ0NAA7hQZqSe5J9PT0/oIHWGg9vSgeYKH19KJ4gIXW04viARZaTy+KB1hoPb0oHmCh9fSieICF1tOL4gEWWk8vigdYaD29KB5gofX0oniAhdbTi+IBFlpPL4oHWGg9vSgeYKH19KJ4gIXW04viARZaTy+KB1hoPb0oHrBbaGNMN2OhjQmUwkK3eUmhp6dX7gEWWk8vigdYaD29KB5gofX0oniAhdbTi+IBFlpPL4oHWGg9vSgeYKH19KJ4gIXW04viARZaT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jzDlk5DDUyTlf5LGTIDPyCvmPcY4+f+/b9aHvX83T9/ZgxHDPGQ9u79oG348oo7dnYpXLoTD4AY8x4mXwAxpjxMvkAjDHjZfIBGGNGyn8RnLVQl3T6MwAAAABJRU5ErkJggg=="> `r` is covered by `G`, `g` is covered by `Y`, then `↓` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACQCAYAAAA/SkayAAAFzklEQVR4nO3c/1niShxG8VOCJaQHm7CB7cEy7ADqsBmoZFvI/QOyxJiBGYl3Zr45Ps/7XJfFD1mvxwD+YPzzOTrnYozaB+Cc227/gn59fXXOdTqAb0EDm2x2I3p6ev+DBxi0nl4UDzBoPb0oHmDQenpRPMCg9fSieIBB6+lF8QCD1tOL4gEGracXxQMMWk8vigcYtJ5eFA8waD29KB5g0Hp6UTzAoPX0oniAQevpRfEAg9bTi+IBBq2nF8UDDFpPL4oHGLSeXhQP+B60c67PGbRzgbYadMt3KfT09NIeYNB6elE8wKD19KJ4gEHr6UXxAIPW04viAQatpxfFAwxaTy+KBxi0nl4UDzBoPb0oHmDQenpRPMCg9fSieIBB6+lF8QCD1tOL4gEGracXxQMMWk8vigcYtJ5eFA8waD29KB5g0Hp6UTzAX0HkXJQZtHOBthp0y3cp9PT00h5g0D14G3zm/lWv9fffXjzAoHvwDFovxwMMugfPoPVyPMCge/AMWi/HAwy6B8+g9XI8wKB78AxaL8cDDLoHz6D1cjzAoHvwDFovxwMMugfPoPVyPMCge/AMWi/HAwy6B8+g9XI8wKB78AxaL8cDDLoHz6D1cjzAoHvwDFovxwMMugfPoPVyPMCge/AMWi/HAwxaTy+KB/griJyLMoN2LtBWg275LoWenl7aAwy6B2+Dz9y/6rX+/uvNG2A8wHiCcbzudL1suOMBBt2DZ9D78Y7cIk7tkPAAg+7BM+h9eGcexzzttOIBBt2DZ9DxvZwz83LHhQcYdA+eQcf2BspjnjbMPMCge/AMOrb3k7PztOPMAwy6B8+gY3slj52XO808wKB78Aw6tjc+uckDDLo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voBuA5mzN2s+gE457Zb9QNwzm20/wAsLYTpL4ZB5wAAAABJRU5ErkJggg=="> `r` is covered by `R`, `g` is covered by `G` and `y` is covered by `Y`. You win the game ;-) For `gameMap = ` ``` +------------+ |R | |G ** | |Y ** | | | | ** r| | ** g| | y| +------------+ ``` The output can be `"→→→→↓→↓→↓→↓→↓→→→→→↓"` initial game map: <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACkCAYAAACgoQMJAAAIsklEQVR4nO3dMW7byhqG4RcQoFYCBKRmK8Bd2tOkc5H2AHJzm1PEK0iTJjuQNpHmls4CtARpE/YC7AXMLSRSlELaYx/5mv/o/YGvIezHxgCfh5RImfT3f5Mxpozw0b+AMeZ8aQr9+fNnY0zQAPxRaOAsaf0QPT29/4MH5BW6grSEtIGU9tnsj1WBF0BPryQPeLnQKw4l7ssy6ALo6ZXkAc8XesvLZa6zCbgAenoleUB/oXN25tOsgi2Anl5JHtBd6IrXl7lOFWgB9PRK8oDuQr9ld66z4v1+YT09vX4P6C70a66dT7Ph/X5hPT29fg/oLnT6l4myAHp6JXmAhdbTK8UDzn/KvQ20AHp6JXmAL4rp6ZXiAb5tpadXigd4Y4meXikecL5bP7cdP2DoC6CnV5IHnOfhjFXPDxj6AujpleQB+Y9Prjjesbf7Y1XgBdDTK8kD/IADPb1SPODPQhtjYsZCG1NQOgs95FMKPT29fg/ILPSUxDWJWxI/97ndH5vGXYAo3hn+cr+rN/T1uxQPyCj0NYcS9+U65gJE8Sy0Xo4HvFDo9o78Um7jLUAUz0Lr5XjAM4XO2ZlPc827/sKX6llovRwP6Cn0lNeXuc40zgJE8Sy0Xo4H9BT6Lbtznes4CxDFs9B6OR7QU+jXXDuf5jbOAkTxLLRejgf0FPrnv0yQBYjiWWi9HA+w0BE8C62X4wGeckfwLLRejgf4olgEz0Lr5XiAb1tF8Cy0Xo4HeGNJBM9C6+V4gLd+RvAstF6OB/hwRgTPQuvleICPT0bwLLRejgf4AQd6eqV4gB9B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utULJ+2bKqopx+ruz237KrPn96P99ap2xb2t+hL2KhB5UGK79WstO/V/2g1y11nduvcj9S6qbb19ES58nLaaEHkwYrn6vQVZPvXIX+yOeL29jU6GDy6dxkSlvoXqfByq8dmtZZ9ppR9bV1br/J7TY5cmhqdDhO6MGk4RdUnePWPX+uWve15WW3U/bvOttQZxvfWl62DhxvV8dioQeT1jfAdChND89N59L6BpiOxTL3Oq1vgDHmfGl9A4wxZ8r/AQsIn1jiEG4FAAAAAElFTkSuQmCC"> `→` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACkCAYAAACgoQMJAAAJpklEQVR4nO2dMW7iaBhAn4RECxLS1G6R0k27zXQppl2JNNtsMTnBNNPkBnCJaabMHIAjwCWScovkAP8WYDDEBjvBg//fL9LTznicFzvOy2eDYQl//woikgZcewNE5HLsgv78+bOIRArAm6CBi1D4Ivr06fsDPsCg9elLxQcYtD59qfgAg9anLxUfYND69KXiAwxan75UfIBB69OXig8waH36UvEBBq1PXyo+wKD16UvFBxi0Pn2p+ACD1qcvFR9g0Pr0peIDDFqfvlR8gEHr05eKDzBoffpS8QEGrU9fKj7AoPXpS8UHvA1aROLEoEUSojToLp9S6NOnr9oHGPSf8GUQ5hBWEMKW1XZZVsN3gd/crfpiOx6p+gCDbtu3YB9xFfMzPoPWV8cHGHSbvjXnY85ZnfAZtL46PsCg2/LVmczHLCp8Bq2vjg8w6DZ8Gc1jzslKfAatr44PMOg2fO+ZzjmLEp9B66vjAwy6DV+Ta+djViU+g9ZXxwcYdBu+8EGOfQatr44PMOg2fOGDHPsMWl8dH2DQbfg+csq9LvEZtL46PsCg2/D5oFi3jkdffIBBt+HL8GmrLh2PvvgAg27L540l3ToeffABBt2mr8m19PqEz6D11fEBBt22r86kXpzxGbS+Oj7AoP+EL2MTbXFir7fLsho+g9ZXxwcYtD59qfgA34JIJBUMWiQhSoPu8imFPn36qn2AQf8R35jALYF7Ag9b7rfLxud9F/jN3aovuuORqA8w6NZ9t+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+eYXvn+9TIvFND08jNPDwzgtFtP09evlNupy//Kc2qD16euJr5ydf/36tI25nIWrPD2NtlHf31/szdIGrU9fT3zluXM5Oy8Wk8YnxBaLyd4sXZ5LG7Q+fT3xlbGW256fX87OJQ8Pu1sQldtKH2DQ+vSd29cl6MdHg9anr9e+Y5bc8/l6yb1a7XyAQevTd25f3ZNidbP087NPiunT13tf88tWk/T4OE6Pj+O0WEy2MZezsy9b6dPXU1/1wpIy6jrmcy8s0acvhO/w0s9q2PP5bLvMrp47V32AQevT1ydfmzdnVGfmqg8waH36+uYrinW01Rl7tVpv8+2T+vQNxAd4CyKRXHgRNH744Ufoj72gRSQ+cKJ1vIj0grMPQEROx9kHICKn4+wDEJHTcfYBiMjpOPsAROR0nH0AInI6zj4AETkdZx+AiJyOjp/wewOV/w6V6teix/z775pzj0P+Ezrs/Pvgzx/1zRwgkihjrYZs1IOgw85137yHM/ZbULN/3bamUA7/ru7x33I3/f3hv/OtferGcv4DusepgvaHQRg67PxaZId/bvpGbxt1m8dv8r4n6q7j62HEVboEXS7NX+Pc/x55kw47nyroppnvVEG/5++rY+zq6CmnCNKYw9Bh59eWpm22veZo+tw2j9/lcbusHLo6eoxBDoaOn9B0jtv2/Llp39e21z1O3f+3GUObMb61vW4f2B9XT3CpPDjOPgAROR1nH4CInI6zD0BETsfZByAiJ+L/ziqhNGwzucIAAAAASUVORK5CYII="> `↓` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPQAAACkCAYAAACgoQMJAAAJk0lEQVR4nO2dP27byhpHDyBArQQYSM1WgLu0t0nnIu0D5OY1t4hXkCZNdmBvIk3K3AVoCdIm7PIW9gLmFRYlSqbskUU/8RseAz/EGVNHY9JH3wz/kv7zOxljygjn7oAxprtshP78+bMxJmgAXggNdJLGm8iTJ+//wAMUWp68UniAQsuTVwoPUGh58krhAQotT14pPECh5ckrhQcotDx5pfAAhZYnrxQeoNDy5JXCAxRanrxSeIBCy5NXCg9QaHnySuEBCi1PXik8Q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xj8/YUw8waD29GrySM/N0x+NXDzBoPb29va5bH/Ow4TG1QevpVeL95Ow8PUsbtJ5eJd6ax85Lj6UNWk+vEu+nMQ8bPMCg9fT29gxaTy+R98wl9/l88wCD1tPb2/OTYnp6iTy/bKWnl8zzG0v09JJ5ax5LD4+dxx5g0Hp6NXklZ+rxmXnsAQatp1eb13WXaMdn7PP5cps/Pqmn14gH+CuInMuyb0Hjk08+hX76ErRzLv5go+t451wV2/0AnHPbbfcDcM5tt90PwDm33XY/AOfcdtv9AJxz2233A3DObbfdD8A5t912PwDn3HZb+QKf1zH6b6sbvy0q3t+/lz267ZGx97/DFW3FnT8nz//WO3OASKId6zjIpedLX95VvRV3nnvnnZ6xH42Z+8/dthTK9O/mXv8je+nvp//OR/eZO5b9/4fOzqCb2Yo734ts+vzSO3pp1CWvf8l9Juq1x1dxxON5yd3MVtx5q6CXznxbBf3M34+Pca1R8TxDN7MVd753aVpy2z1j6WVLXv+a17vmymGtUfEMupmtfIGlx7ilj5+X7nvv9rnXM/fnkmMoOcZHt8/dB74eV0UbLq+nIXvJnXK7H4CrfHMfEFy12/0AXIAZc5jtfgDOue22+wE45zbaf801ZlnMX1NeAAAAAElFTkSuQmCC"> ### Recommand You can submit the `example solution`(preloaded in the initail code) to see how it works ;-) ### Play Games Series - [Play Tetris : Shape anastomosis](http://www.codewars.com/kata/56c85eebfd8fc02551000281) - [Play FlappyBird : Advance Bravely](http://www.codewars.com/kata/play-flappybird-advance-bravely) - [Play PingPong : Precise control](http://www.codewars.com/kata/57542b169a4524d7d9000b68) - [Play PacMan : Devour all](https://www.codewars.com/kata/575c29d5fcee86cb8b000136) - [Play PacMan 2: The way home](https://www.codewars.com/kata/575ed46e23891f67d90000d8) - [Ins and Outs](https://www.codewars.com/kata/576bbb41b1abc47b3900015e)
games
from heapq import * import re MOVES = ((0, 1), (0, - 1), (1, 0), (- 1, 0)) BACK = {dxy: c for dxy, c in zip(MOVES, '→←↓↑')} def three_dots(game_map): class Dot: __slots__ = 'rgy h dist' . split() def __init__(self, dct, chars='rgy', d=None): self . rgy = r, g, y = tuple(map(dct . __getitem__, chars)) self . h = r + tuple(v for x, y in (g, y) for v in (x - r[0], y - r[1])) self . dist = sum((a - b) * * 2 for a, b in zip(self . h, TARGET . h)) if d is None else d def __repr__(self): return f'Dot(* { self . rgy } )' def __hash__(self): return hash(self . h) def __eq__(self, o): return self . h == o . h def __lt__(self, o): return self . dist < o . dist def move(self, dx, dy): def closest_to_obstacle_ahead(t): return - (t[0] * dx + t[1] * dy) closest = sorted(((x, y, c) for (x, y), c in zip( self . rgy, 'rgy')), key=closest_to_obstacle_ahead) used, d = [], {} for x, y, c in closest: pos = a, b = x + dx, y + dy if not board[a][b]. isspace() or pos in used: pos = x, y used . append(pos) d[c] = pos return Dot(d) bd = game_map . splitlines() chars = {c: (i, j) for i, r in enumerate(bd) for j, c in enumerate(r) if c . isalpha()} TARGET = Dot(chars, d=0) start = Dot(chars, 'RGY') board = [re . sub(r'\w', ' ', r) for r in bd] seen = {start} prev = {start: (None, None)} h = [start] path = [] while h: node = heappop(h) if node == TARGET: break for dxy in MOVES: new = node . move(* dxy) if new not in seen: prev[new] = (node, dxy) seen . add(new) heappush(h, new) while 1: node, dxy = prev[node] if node is None: break path . append(BACK[dxy]) return '' . join(reversed(path))
Three Dots--Play game Series #8
59a67e34485a4d1ccb0000ae
[ "Puzzles", "Games", "Game Solvers" ]
https://www.codewars.com/kata/59a67e34485a4d1ccb0000ae
2 kyu
A right truncatable prime is a prime with the property that, if you remove the rightmost digit, the result will be prime, and you can repeat this until the number is one digit (by definition, one-digit primes are right-truncatable). An example of this in base 10 is 37397: the number itself is a prime, as is 3739, 373, 37, and 3. But who said we have to be in base 10? This exact same process can happen in any other base, and the process is very similar: in the base-b representation of a number, a number is *base-b right truncatable* if you can repeat the process of removing the last digit of that number, and it remains prime until the last digit. An example in a nonstandard base is the number 211135 in base 8 (70237 in base 10). The process looks like: `211135 (70237) -> 21113 (8779) -> 2111 (1097) -> 211 (137) -> 21 (17) -> 2 (2)` and you can check for yourself using the base 10 representations in parentheses that it is prime at every step. For convenience, we will call each of these descending truncations a *set* of primes, and the largest prime in each set is called the *head* -- to clarify, an example of a set in base 10 is `37397, 3739, 373, 37, 3`, and the head of that set is 37397; an example set in base 8 is `211135, 21113, 2111, 211, 21, 2`, and the head of that set is 211135, which is 70237 in base 10. Your task in this kata is to write a method `get_right_truncatable_primes` that takes a base to work in, and will output a list of every such head in the given base. They can be in any order, so long as they're all represented exactly once. Good luck! I've included a deterministic implementation of the Miller-Rabin primality test (source: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants) called `fast_is_prime(n)` that returns `True` if the input is prime and `False` if composite; given that some primes for the larger bases are of the order of `10^20` and higher, you may want to use this one. Notes: your inputs are guaranteed to be bounded between `2 <= b <= 21`, as beyond 21 the primes get so large that primality test I've included is no longer deterministic. *Hint: something to be mindful of is that a number is independent of its representation in its base; that is to say, if a number is prime in one base, it will be prime in every base, so there's no need to worry about converting between bases; what you want to do is figure out how the base affects the process of truncating a number, and simulating that process without, for example, translating the number to a base and appending the digit to it.*
algorithms
def get_right_truncatable_primes(base): primes, bag = [], list(filter(fast_is_prime, range(2, base))) while bag: leaf, n = True, bag . pop(0) for x in range(base * n, base * (n + 1)): if fast_is_prime(x): leaf = False bag . append(x) if leaf: primes . append(n) return primes
Right truncatable primes in a given base
5f3db6f4c6197b00151ceae8
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5f3db6f4c6197b00151ceae8
4 kyu
__Pick Until Match__ is a pure game of chance featuring several meters with associated point values. A single player picks and removes hidden items until one of the meters tops off, at which point that meter awards and the game ends. This form of entertainment is sometimes seen with bonus rounds on gambling machines, although in those cases the odds can be severely skewed. To give an example that's honest and forthright, suppose there are meters ```A```, ```B```, and ```C``` which take 5, 3, and 2 items to fill up, respectively. On a fair board there would initially be 10 hidden items: 5 ```A```'s, 3 ```B```'s, and 2 ```C```'s. With uniformly random odds, the chances of completing ```A``` before any of the others is 9/56 or approximately 16.07%. This is accomplished when the player uncovers all 5 ```A```'s without uncovering all 3 ```B```'s nor both ```C```'s. The odds of ```B``` are 13/40 (32.5%), and ```C``` is the most likely at 18/35 (about 51.43%). _It's commented how these fractional values seem a bit strange. Intuitively, at least, it makes sense that more items would be more difficult to complete. Picking ```A``` thrice and ```B``` once would balance the remainder with the level of `C`, but even getting that far is unlikely, especially for ```A```. Alternatively, the more items for a meter, the more likely it is that one of that type would be left unpicked at the end._ Suppose the award values are 21, 13, and 7 points for completing ```A```, ```B```, or ```C``` respectively. Then this game averages 11.2 points per play. It's pretty easy to approximate that with a Monte Carlo simulation, but in this kata we're interested in computing exact theoretical values. Calculation is actually the much faster option if done correctly. An entirely brute force method, on the other hand, will fail miserably since the state space blows up exponentially. Your task is to find the award distribution for such a pick game. You will be provided its specification, for instance meter levels of ```{'A': 5, 'B': 3, 'C': 2}``` and point values of ```{'A': 21, 'B': 13, 'C': 7}``` per the example above. Assuming there are as many hidden items as are required for each meter, compute the probability of completing each one, and map that to the award. Then reduce those odds to integer weights. In this example, the correct result would be the distribution ```{21: 45, 13: 91, 7: 144}```, using points awarded as the dictionary keys. To check, the probability for each award amount is just its weight value divided by the total weight of 280. _Note that several of the sample tests are contrived as special cases, which is really just because those are simpler to reason about. Most of the final tests are random, so solve the pattern generally and don't worry just yet about any serendipitous symmetry in the problem setup._ In the hundred or so test cases, the total number of items to pick from will never exceed 30, even though the perfect solution could easily handle thousands with many more than 10 meters. While you do not have to find the ideal formula, be aware that any valid solution will use a mixture of combinatorics with heavy computation. Also be forewarned that floating point will typically not have enough precision to work out the larger scenarios. The use of fractions is strongly advised. Best of luck! ```:~)```
algorithms
from math import factorial, comb, gcd from collections import Counter from functools import reduce def partition(n, xs): if not xs: return 0 if n else 1 h, * t = xs return sum(comb(h, k) * partition(n - k, t) for k in range(min(h, n + 1))) def count(x, xs): n = x + sum(xs) return x * sum(factorial(i - 1) * factorial(n - i) * partition(i - x, xs) for i in range(x, n - len(xs) + 1)) def pick_until_match(meters, points): c = Counter() for m in meters: c[points[m]] += count(meters[m], [x for k, x in meters . items() if k != m]) d = reduce(gcd, c . values()) return {k: v / / d for k, v in c . items()}
Pick Until Match
604064f13daac00013a8ef2a
[ "Algorithms", "Probability", "Combinatorics" ]
https://www.codewars.com/kata/604064f13daac00013a8ef2a
4 kyu
## Theory Binary relation is a system which encodes relationship between elements of 2 sets of elements. If a pair `(x, y)` is present in a binary relation, it means that the element `x` from the first set is related to the element `y` from the second set. One of the spheres where binary relations are used is decision support systems where they define partial ordering between elements of a set. If a pair `(x, y)` is present in a binary relation, it means that the option `x` is better than the option `y`. Binary relation optimization is a process of searching for a set of options which are (in some way) better than other options in that binary relation. ## Task Given a binary relation, you have to perform an optimization on it. In this case, find a list of options which are collectively better than all the other options. Such options satisfy the following 2 criteria: * all the options included in the result are not directly related to each other * for each option not included in the result there must be at least one better option which is included in the result The binary relation will be provided in the form of an adjacency matrix - a matrix `m` where a non-zero element `m[x][y]` means that the option `x` is better than the option `y`. (You can also interpret it as an adjacency matrix of a graph, where the better vertex `x` has a unidirectional connection to the worse vertex `y`). Assume the options are numbered from `0` to `n`, and directly mapped to the adjacency matrix (the first row specifies the relations of the option `0`, the second row specifies the relations of the option `1`, and so on). Your solution should return a sorted list of options which are optimal for the given binary relation. ### Example (as a matrix, and a graph equivalent to it) ``` [ [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0] ] ( 0 ) ---> ( 2 ) ---> ( 4 ) ---------------------- | V ( 1 ) ---> ( 3 ) ---> ( 5 ) ---> ( 6 ) ---> ( 7 ) | ^ | | ---------------------------------------- ``` The optimal options for this binary relation are `[0, 1, 4, 5]`: * The options `0` and `1` are not worse than any other option - included * The options `2`, `3`, and `6` are directly related to `0` and `1` which have been found to be a part of the solution, hence they don't satisfy the first criteria - ignored * The options `4` and `5` are not related to any of the elements of the solution, hence they satisfy the first criteria - included * The option `7` is directly related to `4` which has been found to be a part of the solution, hence it doesn't satisfy the first criteria - ignored This solution also satisfies the second criteria, as options `2`, `3`, `6`, and `7` are all reachable from options `0`, `1`, `4`, or `5`.
algorithms
def find_vertices(adj): opt, todo = set(), {* range(len(adj))} while todo: new = {x for x in todo if not any(adj[y][x] for y in todo)} todo -= new todo -= {x for y in new for x in todo if adj[y][x]} opt |= new return sorted(opt)
Binary relation optimization
603928e6277a4e002bb33d5a
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/603928e6277a4e002bb33d5a
5 kyu
## Task For every Lambda calculus<sup>[wiki](https://en.wikipedia.org/wiki/Lambda_calculus)</sup> combinator, infinitely many equivalent SKI calculus<sup>[wiki](https://en.wikipedia.org/wiki/SKI_combinator_calculus)</sup> combinators exist. Define a function that accepts a Lambda calculus combinator, as a string, and returns an equivalent SKI combinator, as a string. You do not need to return a shortest or simplest possible combinator; any functionally correct combinator is acceptable. ## Lambda calculus Lambda calculus terms will use variable names, abstractions and applications only, and will be in the concise form, e.g. `"λxyz.xz(yz)"`. They will be closed. Variable names will be single lowercase letters only. There will be no empty applications. Strictly speaking, `"λx.x(λy.y)"` does not require the parentheses around `"λy.y"`, but abstractions within applications will always be parenthesised. ## SKI calculus SKI combinators can use `'S'`, `'K'`, `'I'` and any number of balanced, non-empty parentheses `"()"`, and nothing else. Unnecessary parentheses will be gracefully ignored silently. Your SKI combinator does not need to require as many arguments as the Lambda calculus combinator requires, i.e. for `"λxy.xy"`, `"I"` is acceptable, though you may return `"S(SK)"` or equivalent. ## Testing The Submit tests will evaluate your SKI combinator and compare the outcome to the input, so any correct combinator will be accepted. The Example tests, however, simply compare your SKI combinator to a single possible correct value. Your result may be correct but different, and in this case, the Example test will fail. This <span style="color:magenta">does not</span> mean your solution is necessarily incorrect (!!) but complete testing would show parts of a possible solution. This test will fail with a simple test failure. If you are certain your combinator is correct, you can adjust the Example test yourself. Your result will also be tested for being a well-formed SKI combinator; if this test fails, it <span style="color:magenta">does</span> mean your solution is incorrect. This test will fail with an `Error`. All input will be valid.
reference
def parse_term(s, start=0): terms = [] i = start while i < len(s): c = s[i] i += 1 if c == '(': term, end = parse_term(s, i) terms . append(term) i = end elif c == 'λ': fn, end = parse_fn(s, i) terms . append(fn) i = end elif c == ')': break else: terms . append(c) t = terms[0] for term in terms[1:]: t = [t, term] return t, i def parse_fn(s, start=0): i = start args = [] while s[i] != '.': args . append(s[i]) i += 1 i += 1 term, end = parse_term(s, i) for arg in args[:: - 1]: term = (arg, term) return term, end def free(term, var): match term: case str(x): return x == var case tuple((_, e)): return free(e, var) case list([e1, e2]): return free(e1, var) or free(e2, var) def translate(term): match term: case str(x): return x case list([a, b]): return [translate(a), translate(b)] case tuple((str(x), e)) if not free(e, x): return ['K', translate(e)] case tuple((str(x), str(y))) if x == y: return 'I' case tuple((str(x), tuple((str(y), e)))) if free(e, x): return translate((x, translate((y, e)))) case tuple((str(x), list([e1, e2]))): return ([['S', translate((x, e1))], translate((x, e2))]) def repr(tree): if isinstance(tree, list): return f"( { repr ( tree [ 0 ])} )( { repr ( tree [ 1 ])} )" return tree def eliminate(s): fn, _ = parse_fn(s[1:]) print(fn) trans = translate(fn) print(trans) return repr(trans)
Abstraction elimination
601c6f43bee795000d950ed1
[ "Fundamentals" ]
https://www.codewars.com/kata/601c6f43bee795000d950ed1
3 kyu
## Background An old rich man buried many diamonds in a large family farm. He passed a secret map to his son. The map is divided into many small square parcels. The number of diamonds in each parcel is marked on the map. Now the son wants to sell off some land parcels. The buyer knows about the diamonds and wishes to get some buried diamonds. ## Task Given a map of the farm, and the number of diamonds, find out the smallest rectangular region that contains exactly that number of diamonds. If multiple land parcels of the same minimum size meet that requirement, return all of them. ### Input + `diamond_map`: A rectangular matrix in which `diamond_map[i][j]` is a non-negative integer between 0 and 10. The size of the matrix can go upto 50 x 50 + `num_of_diamonds`: A positive integer representing the number of diamonds ### Output A sorted list of rectangles expressed in the form of 2-element lists of tuples of two coordinates: `[ (top_left_row_index, top_left_col_index), (bottom_right_row_index, bottom_right_col_index)]`. The two elements represents the top left corner and the bottom right corner of the rectangle. Each element has two coordinates - the horizontal index and the vertical index, counting from 0. Coordinates are typically expressed in tuples in python, which are immutable and lighter in memory. Sorting criteria: sort from top to bottom, and break the tie by sorting left to right Example on breaking ties: If two rectangles has left corner at same place, then you would have to place the rectangle which has smaller width first and then that of larger width ## Examples (In the pictorial representation, blank represents 0 and diamond represents 10.) ### For example, in the following map, <center> <img src="https://i.imgur.com/snOWIiR.png"> </center> if 3 diamonds are demanded, the answer would be: ``` [ [(1, 1), (1, 2)], [(2, 2), (2, 3)], [(2, 2), (3, 2)] ] ``` Which is: <center><img src="https://i.imgur.com/jxYdDvV.png"></center> Here's an example of a larger map. The diamond icon represents 10 diamonds. <center> <img src="https://i.imgur.com/cMSL2Q4.png"> </center> If 98 diamonds are demanded, the answer would be: ``` [ [(1, 1), (2, 8)], [(1, 8), (8, 9)] ] ``` Your code will be tested by 50 10x10 maps and 10 more larger maps, including one 40x40, one 40x50, and one 50x50. Happy counting diamonds!
games
def count_diamonds(a, q): n = len(a) m = len(a[0]) if q == 0: return [[[i, j], [i, j]] for i in range(n) for j in range(m) if a[i][j] == 0] ans = [] size = n * m for u in range(n): s = [0] * (m) for d in range(u, n): l = 0 cur = 0 for r in range(m): s[r] += a[d][r] cur += s[r] while cur - s[l] >= q: cur -= s[l] l += 1 if cur == q: sz = (d - u + 1) * (r - l + 1) res = [(u, l), (d, r)] if sz < size: size = sz ans = [res] elif sz == size: ans . append(res) return sorted(ans)
Counting diamonds
5ff0fc329e7d0f0010004c03
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/5ff0fc329e7d0f0010004c03
4 kyu
## Task Write a function which accepts a string consisting only of `'A'`, `'B'`, `'X'` and `'Y'`, and returns the maximum possible number of pairwise connections that can be made. ### Rules 1. You can connect `A` with `B` or `B` with `A` or `X` with `Y` or `Y` with `X`. 1. Each letter can participate in such connection only once. 1. You're not allowed to switch directions of connections. 1. Connections must NOT cross. This implies that these types of connections are not allowed: A X B Y |_|_| | |___| Now, you might be thinking you can avoid crossing connections by drawing them like this: _____ | | A X B Y |____| Nope, you're not allowed to switch the directions (Rule 3). ### Example: In both cases, maximum is `3`: B X A B A Y B A | |_| | |_| |_______| or B X A B A Y B A | |_| | |_| |_______| ### Bounds Bounds: `0 < length of string < 690` Expected time complexity: `$O(size(string)^3)$`
games
def match(s, conns=dict(zip('ABXY', 'BAYX'))): dp = [[0]] for j, c in enumerate(s): dp . append([ max([dp[j][i]] + [ dp[k][i] + 1 + dp[j][k + 1] for k in range(i, j) if s[k] == conns[s[j]] ]) for i in range(j + 1)] + [0]) return dp[- 1][0]
Connect Letters
58f5f479bc60c6898d00009e
[ "Algorithms", "Dynamic Programming", "Puzzles" ]
https://www.codewars.com/kata/58f5f479bc60c6898d00009e
4 kyu
### If you like more challenges, here is [a harder verion of this Kata.](https://www.codewars.com/kata/5f70eac4a27e7a002eccf941) --- # Four Color Theorem In mathematics, the four color theorem, or the four color map theorem, states that, given any separation of a plane into contiguous regions, producing a figure called a map, no more than four colors are required to color the regions of the map so that no two adjacent regions have the same color. Adjacent means that two regions share a common boundary curve segment, not merely a corner where three or more regions meet. It was the first major theorem to be proved using a computer. <div align="center"> <img width=600 src='https://upload.wikimedia.org/wikipedia/commons/a/a9/Map_of_United_States_vivid_colors_shown.png'> Fig. 1: A four-coloring of a map of the states of the United States (ignoring lakes). </div> While every planar map can be colored with four colors, it is NP-complete in complexity to decide whether an arbitrary planar map can be colored with just three colors.[1] For some cases, even three colors are not required, for example two colors are enough to distinguish the squares on a chessboard. --- # Task Find the minimum amount of colors needed to fill a map with no neighboring territories having the same color. ### Input The test map will be inputed as a string. For example the map below has 9 different territories. It needs 3 colors to seperate them. Usually there is more than one way to color a map. A possible color pattern for the map below is: * Color 1: A, C, D, H * Color 2: B, b, E * Color 3: F, G ```JS ` AABBCC AABBCC bbDDEF bbDDGH ` ``` #### Input Notes: - The territory names are case sensitive, B and b are different territories; - Territories are considered adjacent only if they share an edge, A is adjacent to B, but Not D; - One territory is always connected, there are no discrete islands; - Chars of ASCII 33~126 will be used (see...no 32) - Inputs are always rectangular, ignore tailing spaces if any ### Output The output should be an `int`, which is the minimum amount of colors needed to fill the map. --- More about the tests: * There are 45 fixed tests and 200 random tests. Fixed tests are not necessarily easier, they include some special cases. **Please do Not Hard Code them;** * Maps can be big. If we call the sample input above a 6x4 = 24 pixel map, a large map in random tests could have about 5,000 pixels; * All tests will have no more than 10 territories; * There are no oceans or seas which need a certain color, i.e. blue; * Some maps have one territory only; * The oldie but goodie: you will find more in sample tests. Here are more examples: ``` Input strings: 1) "ABCD" 2) """ 3) """ AAA AAAA ABC ACCA DBC DBCA """ """ ``` 1. A is adjacent to B; B is adjacent to C; C is adjacent to D; Your code should return `2`; 1. A is adjacent to all the other 3, but C is not touching D; Your code should return `3`; 1. B is not adjacent to A anymore; Your code should return `2`; <div align="center"> <img src='https://github.com/GaryDoooo/public_codewar_info/blob/main/examples2.png?raw=true'> Fig. 2: The minimum amount of colors needed to fill a map </div> --- <sup>[1] Dailey, D. P. (1980), "Uniqueness of colorability and colorability of planar 4-regular graphs are NP-complete", Discrete Mathematics, 30 (3): 289–293</sup>
algorithms
from itertools import product def color(testmap): m = {r: i for i, r in enumerate(set(testmap . replace('\n', '')))} g = testmap . strip(). split('\n') h, w = len(g), len(g[0]) adj = set() for y, x in product(range(h), range(w)): if y + 1 < h and g[y][x] != g[y + 1][x]: adj . add((g[y][x], g[y + 1][x])) if x + 1 < w and g[y][x] != g[y][x + 1]: adj . add((g[y][x], g[y][x + 1])) for s in range(4): for p in product(range(s), repeat=len(m)): if all(p[m[a]] != p[m[b]] for a, b in adj): return s return 4
Four Color Theorem (Easy Version)
5f88a18855c6c100283b3773
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5f88a18855c6c100283b3773
4 kyu
## Removing Internal Vertices A two dimensional mesh can be defined by a list of triangles. These triangles are references (by index) to vertices; positions in 2D space. Here is such a mesh: <center> <img src="https://docs.google.com/uc?id=1Pm2XmPzVIaJ_3RNalIbttr2mn2khswE4"> </center> ## Task For this task, you will be given only the triangles of a mesh as input. This will be a list of items each containing 3 integers (C#: ValueTuples, JavaScript: Array, Python: tuples), where each of the 3 integers is the index of a vertex in the mesh. From this data alone, you must return a list only containing points along the outline of the mesh - any vertex inside the mesh must be removed: <center> <img src="https://docs.google.com/uc?id=1jMAw0tAmfCM1y81FDhxHdWgXmowH-0IK"> </center> The red vertices should be removed, while the green ones should be kept. Thus, the correct output would be: ```{0, 1, 2, 5, 6, 9, 10}``` ### Notes A vertex is considered external if it would lie on the edge of the silhouette of the mesh, so if there is a hole in the middle of the mesh, any vertices around that hole are also considered external. The output should be sorted in ascending order The mesh given in the input can always be arranged without triangles intersecting each other You will never be given an invalid input
algorithms
from typing import List, Tuple, Set from collections import defaultdict def remove_internal(triangles: List[Tuple[int, int, int]]) - > Set[int]: table = defaultdict(int) for i, j, k in triangles: table[(min(i, j), max(i, j))] += 1 table[(min(k, j), max(k, j))] += 1 table[(min(i, k), max(i, k))] += 1 return {k for i, j in table . items() for k in i if j == 1}
Removing Internal Vertices
5da06d425ec4c4001df69c49
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5da06d425ec4c4001df69c49
5 kyu
## TL;DR ~~~if-not:haskell Given a number of vertices `N` and a list of weighted directed edges in a directed acyclic graph (each edge is written as `[start, end, weight]` where `start < end`), compute the weight of the shortest path from vertex `0` to vertex `N - 1`. If there is no such path, return `-1`. ~~~ ~~~if:haskell Given a number of vertices `n` and a list of weighted directed edges in a directed acyclic graph (each edge is written as `(start, end, weight)` where `start < end`), compute the weight of the shortest path from vertex `0` to vertex `n - 1`. If there is no such path, return `Nothing`. ~~~ ## Background A weighted DAG is a directed acyclic graph where each edge has a weight associated with it: <center> <img src="https://user-content.gitter-static.net/620f5472c30df891a57e0277f083a518e7d80ab8/68747470733a2f2f66696c65732e6769747465722e696d2f3535613663643136356530643531626437383762376433362f445948702f7468756d622f696d6167652e706e67"> </center> In this example, the shortest path from A to D is given by A -> B -> D, which has a total weight of 4. Finding shortest distances in DAGs is made easier by the fact that the nodes can be _linearized:_ they can be given an order `A1, A2, ..., An` such that edges only point forward (that is, there are no edges from `Aj` to `Ai` when `j > i`). In the example above, the two possible linear orderings are `A, B, C, D` and `A, C, B, D.` <center> <img src="https://user-content.gitter-static.net/d1a4ab722c19c3f2f644d6ba8562d3f854953ee4/68747470733a2f2f66696c65732e6769747465722e696d2f3535613663643136356530643531626437383762376433362f51726e532f7468756d622f696d6167652e706e67"></center> ## Your Task Given a number `N` (indicating a graph with vertices `0, 1, ..., N-1`) and a list of weighted edges `[start, end, weight]` for a DAG, where `start < end` for each edge, find the weight (a.k.a. length) of the shortest path from node `0` to node `N-1`. For example, if the input is ``` N = 4 edgeList = [ [0, 1, 1], [0, 2, 5], [0, 3, 5], [1, 3, 3], [2, 3, 1] ] ``` then we have the graph depicted above (with `0 = A`, `1 = B`, etc.) and the answer is `4`. If there is no path from node `0` to node `N-1`, return `-1` (or `Nothing`). ## Notes and Warnings **Precondition:** `N` will always be greater than 1, and edge weights will always be positive integers. There may be multiple edges going between two nodes. **Warning:** You will probably need to use a dynamic programming solution if you want your solution to run fast enough not to time out--that's the whole point of this kata! However, a well-written general shortest-path algorithm such as Dijkstra's Algorithm may also be fast enough to past the soak tests. (The reason is that the dividing line between linear and linearithmic time is hard to define and depends on a variety of external factors, so the kata's tests err on the safe side.)
algorithms
def shortest(n, edges): m = [0] + [float('inf')] * (n - 1) for start, end, weight in sorted(edges): if m[start] == float('inf'): continue m[end] = min(m[start] + weight, m[end]) return - 1 if m[- 1] == float('inf') else m[- 1]
Dynamic Programming #1: Shortest Path in a Weighted DAG
5a2c343e8f27f2636c0000c9
[ "Dynamic Programming", "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5a2c343e8f27f2636c0000c9
5 kyu
David wants to travel, but he doesn't like long routes. He wants to decide where he will go, can you tell him the shortest routes to all the cities? Clarifications: - David can go from a city to another crossing more cities - Cities will be represented with numbers - David's city is always the number 0 - If there isn't any route to a city, the distance will be infinite (`float("inf")`) - There's only one road between two cities - Routes are one-way (start city -> end city) The arguments are: `n`: the number of cities (so the cities are numbers from 0 to n-1 inclusive) `routes`: a list of routes (tuples): `(start city, end city, length)` The output is a list of shortest routes (tuples) from David's city to all the others, sorted by city number: `(city number, distance)` Example: ```python shortest_routes(3, [(0, 1, 1), (0, 2, 10), (1, 2, 2)]) # return [(1, 1), (2, 3)] ```
algorithms
# Doesn't work because of paths with 0 weight from scipy . sparse import csr_matrix from scipy . sparse . csgraph import shortest_path def shortest_routes(n, routes): graph = [[0] * n for _ in range(n)] for i, j, x in routes: graph[i][j] = x return list(enumerate(shortest_path(csgraph=csr_matrix(graph), indices=0)))[1:] # Working solution with heapq from collections import defaultdict from heapq import heappush, heappop def shortest_routes(n, routes): graph = defaultdict(lambda: defaultdict(int)) for i, j, x in routes: graph[i][j] = x queue, res = [(0, 0)], [float('inf')] * n while queue: i, d1 = heappop(queue) for j, d2 in graph[i]. items(): if res[j] > d1 + d2: res[j] = d1 + d2 heappush(queue, (j, res[j])) return list(enumerate(res))[1:]
The Shortest Routes
5f60407d1d026a00235d047d
[ "Graphs" ]
https://www.codewars.com/kata/5f60407d1d026a00235d047d
null
The Dynamic Connectivity Problem Given a set of of N objects, is there a path connecting the two objects? Implement an class that implements the following API: * Takes n as input, initializing a data-structure with N objects (0...N-1) * Implements a Union command that adds a connection between point p and point q * Implements a Connected command that returns a boolean and asks is there a connection between point p and point q As a simple example: Imagine you initialize an data structure filled with integers from 0 to 9 (N = 10) ```python results1 = DynamicConnectivity(10) ``` You will receive a series of union commands linking various points ```python results1.union(4,3) results1.union(3,8) results1.union(6,5) results1.union(9,4) results1.union(2,1) ``` This should result in 5 groups of connections: * 3,4,8,9 * 5,6 * 2,1 * 0 * 7 All members of a groups (set) are conected to every other member If you asked is 0 connected to 7, it should return False If you asked is 8 connected to 9 you should return True even if 8,9 wern't directly joined. (8 is connected to 3 which is connected to 4 which is connected to 9) ```python results1.connected(0,7) == False results1.connected(8,9) == True ``` For the purposes of this problem, you do not have to mainatin the order of the connections, you just have to know that the connection is there. Hint: There is a naive implenetation that takes time proportional to O(n^2) (Quadratic Funtion) **This will time out the problem** (Because every time you double the input like from 50 nodes to 100 nodes, the function takes **4** times as long) Test will check that you are able to outrun this naive implementation. If you can't that means that your code is too slow There is a solution that takes linearitmic time or faster O(n * lg n) Hint Two: (Take it or leave it) If you find yourself nesting a loop inside a loop, you are creating a quadratic function Implementation must be able to handle initializing 1 million nodes, and creating connections between those nodes. Full Tests before submission generate random connections to make sure you can't hard code the connections into your class.
algorithms
# 10 times faster than naive class DynamicConnectivity (object): def __init__(self, n): self . items = {i: {i} for i in range(n)} def union(self, p, q): if self . items[p] is not self . items[q]: for x in self . items[q]: self . items[p]. add(x) self . items[x] = self . items[p] def connected(self, p, q): return q in self . items[p]
Dynamic Connectivity
58936eb3d160ee775d000018
[ "Algorithms" ]
https://www.codewars.com/kata/58936eb3d160ee775d000018
4 kyu
# The Kata Your task is to transform an input nested list into an hypercube list, which is a special kind of nested list where each level must have the very same size, This Kata is an exercise on recursion and algorithms. You will need to visualize many aspects of this question to be able to solve it efficiently, as such there is a section on definitions of the terms that will be used in the Kata, make sure to fully understand them before attempting. A naive brute-force-ish answer will most likely fail the tests. There will be tests on nested lists of dimension and size up to 10. Good luck. # Definitions ### Nested List A nested list is a list that may contain either non-list items or more nested lists as items in the list. Here are a few examples of nested lists. [[2, 3], 4, 5, 6, [2, [2, 3, 4, 5], 2, 1, 2], [[[[1]]]], []] [[[]]] [1, 2] [[], []] [4, 5, 6, 7, [], 2] [] - A *basic element* refers to any non-list element of a nested list. - A nested list's *dimension* is defined as the deepest the list goes. - A nested list's *size* is defined as the longest the list or any of its sublists go. For example, the *dimension* and *size* of the above nested lists is as follows. [[2, 3], 4, 5, 6, [2, [2, 3, 4, 5], 2, 1, 2], [[[[1]]]], []] # dimension: 5, size: 7 [[[]]] # dimension: 3, size: 1 [1, 2] # dimension: 1, size: 2 [[], []] # dimension: 2, size: 2 [4, 5, 6, 7, [], 2] # dimension: 2, size: 6 [] # dimension: 1, size: 0 ### Hypercube List - A `1`-dimensional **hypercube list** of size `n` is a nested list of dimension `1` and size `n`. - A `d`-dimensional hypercube list of size `n` is a nested list of dimension `d` and size `n` such that the nested list has `n` elements each of which is a `d - 1`-dimensional hypercube list of size `n`. Here are some examples of hypercube lists. [1] # dimension: 1, size: 1 [[1, 2], [3, 4]] # dimension: 2, size: 2 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # dimension: 2, size: 3 [[0]] # dimension: 2, size: 1 [[[0, 0], [1, 1]], [[2, 2], [3, 3]]] # dimension: 3, size: 2 [1, 2, 3, 4] # dimension: 1, size: 4 [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] # dimension: 2, size: 4 # The Task Your task is to implement `normalize` which converts any given `nested_list` to be in hypercube format with the same dimension and size as the given nested list, extending and growing with the given `growing_value`. The default growing value is the integer `0`. ### The Algorithm In most scenarios you will encounter a nested list that does not have the same size throughout. When working on such a list the algorithm should behave as follows. * If a hypercube list of dimension 1 needs extra elements, append the required number of growing value elements. * If a hypercube list of dimension greater than 1 has a direct basic element as a child, replace it with the required hypercube list with its basic elements all being the replaced item. * If a hypercube list of dimension greater than 1 needs extra elements, append the required hypercube list with its basic elements all being the growing value. Take note of the given example, it will be very helpful in understanding the intricacies of the algorithm. >>> normalize( [ [ [2, 3, 4], [1, 2], 2, [1] ], [ 2, [2, 3], 1, 4, [2, 2, 6, 7] ], 5 ] ) Gives the following result. [ [ [2, 3, 4, 0, 0], [1, 2, 0, 0, 0], [2, 2, 2, 2, 2], [1, 0, 0, 0, 0], [0, 0, 0, 0, 0] ], [ [2, 2, 2, 2, 2], [2, 3, 0, 0, 0], [1, 1, 1, 1, 1], [4, 4, 4, 4, 4], [2, 2, 6, 7, 0] ], [ [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5] ], [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ], [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ] ] Good luck!
algorithms
from itertools import zip_longest def normalize(lst, growing=0): def seeker(lst, d=1): yield len(lst), d for elt in lst: if isinstance(elt, list): yield from seeker(elt, d + 1) def grower(lst, d=1): return [grower(o if isinstance(o, list) else [o] * size, d + 1) if d != depth else o for o, _ in zip_longest(lst, range(size), fillvalue=growing)] size, depth = map(max, zip(* seeker(lst))) return grower(lst)
Hypercube Lists
5aa859ad4a6b3408920002be
[ "Algorithms", "Lists", "Recursion" ]
https://www.codewars.com/kata/5aa859ad4a6b3408920002be
4 kyu
<style> pre.handle{ height: 2em; width: 4em; margin: auto; margin-bottom: 0 !important; background: none !important; border-radius: 0.5em 0.5em 0 0; border-top: 5px solid saddlebrown; border-left: 5px solid saddlebrown; border-right: 5px solid saddlebrown; } table.example-piece{ width: fit-content; height: fit-content; margin: auto; } pre.piece{ font-size: 1.75em; line-height: 1.4; letter-spacing: 0.1em; background: none !important; } pre.bag{ border-radius: 0.5em; border:5px solid saddlebrown; width: fit-content; background: burlywood; font-size: 1.75em; line-height: 1.4; letter-spacing: 0.1em; color: white; text-align: center; margin: auto; padding: 0.2em; } pre b{ padding: 0.1em; } .a{ background: darkolivegreen; } .b{ background: seagreen;} .c{ background: limegreen; } .d{ background: darkgreen; } </style> # On a business trip, again... I love traveling, just like everyone else. If only they were not business trips... They force me to go to places I don't want to go and listen to people that I don't care about. But, by far, the thing I hate the most is **packing my bag**. The thing is, I can only carry one bag in the plane and I **NEED** to bring some important items. Every item is numbered and has a specific shape. Here is an example of a "well-sorted" bag, meaning that all the items fit in the bag, without overlapping each others: <pre class="handle"></pre> <pre class="bag"> <b class="a">1</b><b class="a">1</b><b class="a">1</b><b class="a">1</b><b class="b">2</b><b class="b">2</b><b class="c">3</b><b class="c">3</b> <b class="a">1</b><b class="d">4</b><b class="d">4</b><b class="d">4</b><b class="d">4</b><b class="b">2</b><b class="c">3</b><b class="c">3</b> <b class="a">1</b><b class="d">4</b><b class="d">4</b><b class="d">4</b><b class="b">2</b><b class="b">2</b><b class="b">2</b><b class="c">3</b> </pre> <br> Will I be able to fit all the items I need in the bag? # Your task Write a funtion `fit_bag(height: int, width: int, items: List[List[List[int]]]) -> List[List[int]]` that takes a bag height and width and a list of items and returns a bag with all the items in a correct place. The pieces will be given as a square bidimensional array that represents items as follows: <table class="example-piece" valign="middle" border="0"> <tr> <td> <pre class="piece"><b class="a">1</b><b class="a">1</b><b class="a">1</b><b class="a">1</b> <b class="a">1</b> <b class="a">1</b></pre> </td> <td> <pre style="font-size: 5em; background: none !important;"> → </pre> </td> <td> <pre><code class="language-python">[ [1, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0] ]</code></pre> </td> </tr> <tr> <td> <pre class="piece"><b class="d">4</b><b class="d">4</b><b class="d">4</b><b class="d">4</b> <b class="d">4</b><b class="d">4</b><b class="d">4</b></pre> </td> <td> <pre style="font-size: 5em; background: none !important;"> → </pre> </td> <td> <pre><code class="language-python">[ [4, 4, 4, 4], [4, 4, 4, 0], ]</code></pre> </td> </tr> </table> And, as you may have guessed, the output is represented the same way as the pieces, but it will contain the numbers of all the pieces and zeroes in the case of empty spaces. The thing is, **you cannot rotate the pieces nor flip them**. <table class="example-piece"> <tr> <td> <pre class="piece"><b class="d">4</b><b class="d">4</b><b class="d">4</b><b class="d">4</b> <b class="d">4</b><b class="d">4</b><b class="d">4</b></pre> </td> <td> <pre style="font-size: 5em; background: none !important;"> → </pre> </td> <td> <pre class="piece"><b class="d">4</b> <b class="d">4</b><b class="d">4</b> <b class="d">4</b><b class="d">4</b> <b class="d">4</b><b class="d">4</b></pre> </td> <td> <pre style="font-size: 3em; color: red; background: none !important;"> ✖ </pre> </td> </tr> </table> **Technical notes:** * Items will only contain zeroes (for empty spaces) and another number that identifies the item. * Items will not have rows or columns of zeros at the borders. If an item's matrix is of size *n*x*m*, this means the object has a bounding box of *n*x*m*. * There will be no two items with the same number. * There will never be more than 9 items. * Items do not necessarily have to be one connected component. * The only condition for your solution to be valid is that each requested item is present in the bag at the end. There can be empty spaces (represented by zeroes) or repeated items. * Every test case **is solvable**. # Preloaded code You are given two functions for debugging purposes: * `always_show_bag()`: enable the input/bag print of the test cases that you solved. By default, nothing is printed to the console. * `print_bag(bag)`: this function prints a bag in a human-readable format for debugging purposes. # Tests Here are the tests that will be done: * **Fixed tests (respectively):** bags of sizes 3x8, 3x6, 3x5, 3x7, 3x8 and 5x9. Six tests of each with 4 to 8 items. * **Random tests:** 300 5x9 bags tests with 7 to 9 items.
algorithms
from itertools import chain def fit_bag(H, W, items): def deploy(item): X, Y = len(item), len(item[0]) v = (set(chain . from_iterable(item)) - {0}). pop() deltas = [(x, y) for x, r in enumerate(item) for y, n in enumerate(r) if n] return (len(deltas), X * Y, max(X, Y), min(X, Y), X, Y, deltas, v) def dfs(i=0): if i == len(items): yield bag _, _, _, _, X, Y, deltas, v = items[i] for x in range(H - X + 1): for y in range(W - Y + 1): if all(not bag[x + dx][y + dy] for dx, dy in deltas): for dx, dy in deltas: bag[x + dx][y + dy] = v yield from dfs(i + 1) for dx, dy in deltas: bag[x + dx][y + dy] = 0 bag = [[0] * W for _ in range(H)] items = sorted(map(deploy, items), reverse=True) return next(dfs())
I hate business trips
5e9c8a54ae2b040018f68dd9
[ "Algorithms" ]
https://www.codewars.com/kata/5e9c8a54ae2b040018f68dd9
4 kyu
# Overview The goal here is to solve a puzzle (the "pieces of paper" kind of puzzle). You will receive different pieces of that puzzle as input, and you will have to find in what order you have to rearrange them so that the "picture" of the puzzle is complete. <br> ## Puzzle pieces All the pieces of the puzzle will be represented in the following way: * 4 numbers, grouped in 2 tuples, which are representing the "picture" on the piece. Every piece has a 2x2 size. * 1 id number. All id numbers are unique in a puzzle, but their value may be random. * Note that all numbers will be non-negative integers (except for outer border "picture" numbers in C#) For example, ((1, 2), (3, 4), 1) Puzzle piece id ^ is equivalent the the following square piece of puzzle, having the id number `1`: +---+ |1 2| |3 4| +---+ If the piece is on a border or is a corner, some numbers will be replaced with `None` (`-1` in C#): ```python ((None, None), (1, 2), 10) --> upper border ((9, None), (None, None), 11) --> bottom right corner ``` ```csharp ((-1, -1), (1, 2), 10) --> upper border ((9, -1), (-1, -1), 11) --> bottom right corner ``` <br> Note that you cannot flip or rotate the pieces (_would you like to change the picture!?_) <br> ## Solving the puzzle * You'll get an array of pieces as well as the size of the puzzle (width and height). * Two pieces can be assembled if they share the same pattern on the border where they are in contact (see example below). * Puzzle pieces being unique, you'll never encounter two different pieces that could be assembled with the same third one. So to say: borders are unique. * Once you found the proper arrangment for all the pieces, return the solved puzzle as a list of tuples (height * width) of the id number of the piece at its correct position. (For C#, return the solved puzzle as a 2-dimensional array of integers.) ## Example: Inputs: ```python width, height = 3,3 pieces = [ ((None, 5), (None, None), 3), ((17, None), (None, None), 9), ((None, 4), (None, 5), 8), ((4, 11), (5, 17), 5), ((11, None), (17, None), 2), ((None, None), (None, 4), 7), ((5, 17), (None, None), 1), ((None, None), (11, None), 4), ((None, None), (4, 11), 6) ]` ``` ```csharp int width = 3; int height = 3; ((int,int),(int,int),int)[] pieces = { ((-1, 5), (-1, -1), 3), ((17, -1), (-1, -1), 9), ((-1, 4), (-1, 5), 8), ((4, 11), (5, 17), 5), ((11, -1), (17, -1), 2), ((-1, -1), (-1, 4), 7), ((5, 17), (-1, -1), 1), ((-1, -1), (11, -1), 4), ((-1, -1), (4, 11), 6) }; ``` In this case, the expected output would be: ```python expected = [(7, 6, 4), (8, 5, 2), (3, 1, 9)] ``` ```csharp int[,] expected = new int[,]{{7, 6, 4}, {8, 5, 2}, {3, 1, 9}}; ``` ... the solved puzzle looking like this: ```python Puzzle Solved: Related id numbers: ----------------------------- 7 6 4 |None None|None None|None None| |None 4 | 4 11 | 11 None| 8 5 2 |-----------------------------| |None 4 | 4 11 | 11 None| 3 1 9 |None 5 | 5 17 | 17 None| |-----------------------------| |None 5 | 5 17 | 17 None| |None None|None None|None None| ----------------------------- ``` ```csharp Puzzle Solved: Related id numbers: ------------------------ 7 6 4 |-1 -1 | -1 -1 | -1 -1| |-1 4 | 4 11 | 11 -1| 8 5 2 |------------------------| |-1 4 | 4 11 | 11 -1| 3 1 9 |-1 5 | 5 17 | 17 -1| |------------------------| |-1 5 | 5 17 | 17 -1| |-1 -1 | -1 -1 | -1 -1| ------------------------ ``` ### Notes: * Be careful about performances, you'll have to handle rather big puzzles. * Width and height will be between 2 and 100 (inclusive) * The puzzle may be rectangular too
games
def puzzle_solver(pieces, w, h): memo, D, result = {}, {None: (None, None)}, [[None] * w for _ in range(h)] for (a, b), (c, d), id in pieces: memo[(a, b, c)] = id D[id] = (c, d) for i in range(h): for j in range(w): a, b = D[result[i - 1][j]] _, c = D[result[i][j - 1]] result[i][j] = memo[(a, b, c)] return list(map(tuple, result))
Solving a puzzle by matching four corners
5ef2bc554a7606002a366006
[ "Games", "Performance", "Puzzles" ]
https://www.codewars.com/kata/5ef2bc554a7606002a366006
4 kyu
Your task is to create a change machine. The machine accepts a single coins or notes, and returns change in 20p and 10p coins. The machine will try to avoid returning its exact input, but will otherwise return as few coins as possible. For example, a 50p piece should become two 20p pieces and one 10p piece, but a 20p piece should become two 10p pieces. The machine can exclusively process these coins and notes: £5, £2, £1, 50p, 20p. Any coins and notes which are not accepted by the machine will be returned unprocessed. For example, if you were to put a £20 note into the machine, it would be returned to you and not broken into change. (Note that £1 is worth 100p.) This change machine is programmed to accept and distribute strings rather than numbers. The input will be a string containing the coin or note to be processed, and the change should be returned as one string with the coin names separated by single spaces with no commas. The values of the string should be in descending order. For example, an input of `"50p"` should yield the exact string `"20p 20p 10p"`.
reference
def change_me(money): match money: case "£5": return " " . join(["20p"] * 25) case "£2": return " " . join(["20p"] * 10) case "£1": return " " . join(["20p"] * 5) case "50p": return "20p 20p 10p" case "20p": return "10p 10p" case _: return money
Simple Change Machine
57238766214e4b04b8000011
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57238766214e4b04b8000011
8 kyu
The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column or diagonal. The eight queens puzzle is an example of the more general N queens problem of placing N non-attacking queens on an N×N chessboard. You can read about the problem on its Wikipedia page: [Eight queens puzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle). You will receive a (possibly large) number `N` and have to place N queens on a N×N chessboard, so that no two queens attack each other. This requires that no two queens share the same row, column or diagonal. You will also receive the mandatory position of one queen. This position is given 0-based with `0 <= row < N` and `0 <= col < N`. The coordinates `{0, 0}` are in the top left corner of the board. For many given parameters multiple solutions are possible. You have to find one of the possible solutions, all that fit the requirements will be accepted. You have to return the solution board as a string, indicating empty fields with `'.'` (period) and Queens with `'Q'` (uppercase Q), ending each row with `'\n'`. ```if:cpp If no solution is possible for the given parameters, return an empty string `""`. Notes on C++ version: - input parameters are `size` and `{mandatoryColumn, mandatoryRow}` - there are 8 tests for very small boards (N <= 10) - there are 8 tests for cases without solution - there are 5 tests for small boards (10 < N <= 50) - there are 5 tests for medium boards (100 < N <= 500) - there are 5 tests for large boards (500 < N <= 1000) ``` ```if:javascript If no solution is possible for the given parameters, return an empty string `""`. Notes on JavaScript version: - input parameters are `size` and `{row: mandatoryRow, col: mandatoryColumn}` - there are 8 tests for very small boards (N <= 10) - there are 8 tests for cases without solution - there are 5 tests for small boards (10 < N <= 50) - there are 5 tests for medium boards (100 < N <= 500) - there are 5 tests for large boards (500 < N <= 1000) ``` ```if:rust If no solution is possible for the given parameters, return `None`. Notes on Rust version: - input parameters are `size` and `(mandatory_column, mandatory_row)` - there are 8 tests for very small boards (N <= 10) - there are 8 tests for cases without solution - there are 5 tests for small boards (10 < N <= 50) - there are 5 tests for medium boards (100 < N <= 500) - there are 5 tests for large boards (500 < N <= 1000) ``` ```if:python If no solution is possible for the given parameters, return `None`. Notes on Python version: - input parameters are `size` and `(mandatory_row, mandatory_column)` - there are 8 tests for very small boards (N <= 10) - there are 8 tests for cases without solution - there are 5 tests for small boards (10 < N <= 50) - there are 5 tests for medium boards (100 < N <= 500) - there are 5 tests for large boards (500 < N <= 1000) ``` ---- Example: For input of `size=8`, `mandatory column=3` and `mandatory row=0`, your solution could return: ``` "...Q....\n......Q.\n..Q.....\n.......Q\n.Q......\n....Q...\nQ.......\n.....Q..\n" ``` giving the following board: ``` ...Q.... ......Q. ..Q..... .......Q .Q...... ....Q... Q....... .....Q.. ``` (Other solutions to this example are possible and accepted. The mandatory queen has to be in its position, in the example in the first row at `col=3, row=0`.) ---- Easier variations on the problem: - [N queens problem (with no mandatory queen position)](https://www.codewars.com/kata/52cdc1b015db27c484000031) - [N queens puzzle (with one mandatory queen position)](https://www.codewars.com/kata/561bed6a31daa8df7400000e)
algorithms
from random import choice def no_solution(n, fix): # checks whether it is a no solution case. return True if n == 2 or n == 3 or n == 4 and fix in [(0, 0), (0, 3), (3, 0), (3, 3), (1, 1), (1, 2), (2, 1), (2, 2)] or n == 6 and fix in [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)] else False # returns the solution in the requested format. def format_solution(n, sol): return '\n' . join(['.' * i + 'Q' + '.' * (n - i - 1) for i in sol]) + '\n' def attacks(n, cell): # returns the number of queens that attack a cell. return hor_queens[cell[1]] + up_dia_queens[cell[0] + cell[1]] + down_dia_queens[cell[1] - cell[0] + n - 1] # finds a known solution to the board of size n and changes one queen's position to the fixed cell. def start_with(n, fix): if n % 6 == 2: sol = [i for i in range(1, n, 2)] + [2, 0] + \ [i for i in range(6, n, 2)] + [4] elif n % 6 == 3: sol = [i for i in range(3, n, 2)] + [1] + \ [i for i in range(4, n, 2)] + [0, 2] else: sol = [i for i in range(1, n, 2)] + [i for i in range(0, n, 2)] sol[fix[0]] = fix[1] count_queens(n, sol) return sol # counts the number of queens in each row and diagonal. def count_queens(n, sol): global hor_queens, up_dia_queens, down_dia_queens hor_queens, up_dia_queens, down_dia_queens = [ 0] * n, [0] * (2 * n - 1), [0] * (2 * n - 1) for i in range(n): hor_queens[sol[i]] = hor_queens[sol[i]] + 1 up_dia_queens[sol[i] + i] = up_dia_queens[sol[i] + i] + 1 down_dia_queens[sol[i] - i + n - 1] = down_dia_queens[sol[i] - i + n - 1] + 1 # updates the number of queens in each row and diagonal. def update_queens(n, sol, new_queen): i, j = new_queen hor_queens[sol[i]] -= 1 up_dia_queens[sol[i] + i] -= 1 down_dia_queens[sol[i] - i + n - 1] -= 1 hor_queens[j] += 1 up_dia_queens[j + i] += 1 down_dia_queens[j - i + n - 1] += 1 # applies min conflics algorithm to find a solution starting from a reasonable arrangement. def min_conf(n, sol, fix): while True: confs = [attacks(n, (i, sol[i])) - 3 for i in range(n)] if sum(confs) == 0: return sol col = choice([i for i in range(n) if confs[i] > 0 and i != fix[0]]) col_conf = [attacks(n, (col, i)) for i in range(n)] new_queen = (col, choice( [i for i in range(n) if col_conf[i] == min(col_conf)])) update_queens(n, sol, new_queen) sol[new_queen[0]] = new_queen[1] def solve(n, fix): # uses min conflicts algorithm to find the solution. sol = start_with(n, fix) return min_conf(n, sol, fix) def solve_n_queens(n, fix): if no_solution(n, fix): return None return format_solution(n, solve(n, fix))
N queens problem (with one mandatory queen position) - challenge version
5985ea20695be6079e000003
[ "Algorithms", "Mathematics", "Performance" ]
https://www.codewars.com/kata/5985ea20695be6079e000003
1 kyu
The snake cube is a puzzle consisting of `27` small wooden cubes connected by an elastic string. The challenge is the twist the string of cubes into a complete `3 x 3 x 3` cube. Some of the small cubes are threaded straight through the centre. Others are threaded at a right-angle - this allows the solver to change direction. ![Snake cube](http://web.cecs.pdx.edu/~mpj/snakecube/snake.png) Flattened out, the string of cubes might look like this: ![Flat snake](http://www.mathematische-basteleien.de/snake01.gif) We describe the configuration of the puzzle by a list of `0`s and `1`s where: `0` means a cube which is threaded straight through (or is at either end of the string). `1` means a cube which is threaded at right angles. In the tests, all configurations will be of length 27, and consist only of `0`s and `1`s. ```if:haskell We describe a solution as `Just` a list of 3D cartesian coordinates, `Maybe [(Int, Int, Int)]` describing the position of each cube within the final `3 x 3 x 3` cube. Your task is to produce a valid solution for a given starting configuration. If there are multiple solutions then return any one. If there is no possible solution then return `Nothing`. ``` ```if-not:haskell We describe a solution as a list of 3D cartesian coordinates, `[ [Int, Int, Int] ]` describing the position of each cube within the final `3 x 3 x 3` cube. Your task is to produce a valid solution for a given starting configuration. If there are multiple solutions then return any one. If there is no possible solution then return `null`. ``` For the purposes of this kata, the complete solution occupies a cube with vertices: `(0,0,0) (2,0,0) (0,2,0) (0,0,2) (2,2,0) (2,0,2) (0,2,2) (2,2,2)` and starts with the first cube in the corner position `(0,0,0)`.
games
from itertools import product def solve(config): def get_angles(a, b, c): return (b, c, a), (- b, - c, - a), (c, a, b), (- c, - a, - b) def dfs(pos, d, iC): out . append(pos) cube . remove(pos) if not cube: return True to_check = get_angles(* d) if config[iC] else (d,) for dd in to_check: neigh = tuple(map(sum, zip(pos, dd))) if neigh in cube and dfs(neigh, dd, iC + 1): return True cube . add(pos) out . pop() out, cube = [], set(product(range(3), repeat=3)) return out if dfs((0, 0, 0), (0, 0, 1), 0) else None
Snake Cube Solver
5df653efc6ba5100191e602f
[ "Recursion", "Geometry", "Puzzles", "Algorithms", "Game Solvers", "Graph Theory" ]
https://www.codewars.com/kata/5df653efc6ba5100191e602f
4 kyu
Removed due to copyright infringement. <!--- ### Task An `amazon` (also known as a queen+knight compound) is an imaginary chess piece that can move like a `queen` or a `knight` (or, equivalently, like a `rook`, `bishop`, or `knight`). The diagram below shows all squares which the amazon attacks from e4 (circles represent knight-like moves while crosses correspond to queen-like moves). ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/amazon.png?_tm=1473934566013) Recently you've come across a diagram with only three pieces left on the board: a `white amazon`, `white king` and `black king`. It's black's move. You don't have time to determine whether the game is over or not, but you'd like to figure it out in your head. Unfortunately, the diagram is smudged and you can't see the position of the `black king`, so it looks like you'll have to check them all. Given the positions of white pieces on a standard chessboard, determine the number of possible black king's positions such that: * It's a checkmate (i.e. black's king is under amazon's attack and it cannot make a valid move); * It's a check (i.e. black's king is under amazon's attack but it can reach a safe square in one move); * It's a stalemate (i.e. black's king is on a safe square but it cannot make a valid move); * Black's king is on a safe square and it can make a valid move. Note that two kings cannot be placed on two adjacent squares (including two diagonally adjacent ones). ### Example For `king = "d3" and amazon = "e4"`, the output should be `[5, 21, 0, 29]`. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/example1.png?_tm=1473934566299) `Red crosses` correspond to the `checkmate` positions, `orange pluses` refer to `checks` and `green circles` denote `safe squares`. For `king = "a1" and amazon = "g5"`, the output should be `[0, 29, 1, 29]`. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/amazonCheckmate/img/example2.png?_tm=1473934566670) `Stalemate` position is marked by a `blue square`. ### Input - String `king` Position of white's king in chess notation. - String `amazon` Position of white's amazon in the same notation. Constraints: `amazon ≠ king.` ### Output An array of four integers, each equal to the number of black's king positions corresponding to a specific situation. The integers should be presented in the same order as the situations were described, `i.e. 0 for checkmates, 1 for checks, etc`. --->
games
from itertools import count # Natural directions of moves for king or queen (one step) ALL_MOVES = [(1, 1), (0, 1), (1, 0), (- 1, 0), (0, - 1), (- 1, 1), (1, - 1), (- 1, - 1)] AMA_MOVES = [(1, 2), (2, 1), (- 1, 2), (2, - 1), (1, - 2), (- 2, 1), (- 1, - 2), (- 2, - 1)] # Knight moves for amazon queen def amazon_check_mate(* args): def posInBoard(x, y): return 0 <= x < 8 and 0 <= y < 8 # Working with the amazon queen is king is provided def getCoveredPos(start, king=None): covered = {start} # All "one step" moves (either for queen or king) for m in (AMA_MOVES if king else ALL_MOVES): pos = tuple(z + dz for z, dz in zip(start, m)) if posInBoard(* pos): covered . add(pos) # Get long range moves, for queen only (meaning: if king is provided!) if king: for dx, dy in ALL_MOVES: for n in count(1): pos = (start[0] + dx * n, start[1] + dy * n) if not posInBoard(* pos) or pos == king: break # Abort if not in board or if white king is on the way covered . add(pos) return covered # King and Queen positions as tuples K, Q = map(lambda s: (ord(s[0]) - 97, ord(s[1]) - 49), args) kCover = getCoveredPos(K) # Positions protected by white king # All position protected by white pieces fullCover = getCoveredPos(Q, K) | kCover freeQueen = Q not in kCover # Queen not protected by king # Indexes: 2 * "is not check" + 1 * "safe position available around" counts = [0] * 4 for x in range(8): for y in range(8): black = (x, y) if black in kCover or black == Q: continue # No adjacent kings and no king copulating with an amazon... safePosAround = any(posInBoard(* neigh) and (neigh not in fullCover or neigh == Q and freeQueen) # Neighbour is in board and is a safe place or is the queen and isn't protected by white king for neigh in ((x + dx, y + dy) for dx, dy in ALL_MOVES)) # Update the correct index of "ans" counts[2 * (black not in fullCover) + safePosAround] += 1 return counts
Chess Fun #8: Amazon Checkmate
5897f30d948beb78580000b2
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5897f30d948beb78580000b2
4 kyu
<a href="https://preview.mailerlite.com/d5g0h3/1389145903520025821/l1w0/" target="_blank"><img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com"></a> <a href="https://en.wikipedia.org/wiki/Laura_Bassi">Laura Bassi</a> was the first female professor at a European university. Despite her immense intellect, she was not always allowed to lecture publicly. One day a professor with very strong beliefs against women in academia sent some `agents` to find Bassi and end her career. Help her escape by telling her the safest places in town! <h2>Task</h2> ```if:python,javascript Implement the function `advice(agents, n)` where ``` ```if:haskell Implement the function `advice agents n :: [(Int,Int)] -> Int -> [(Int,Int)]` where ``` ```if:swift Implement the function `advice(agents: [[Int]], n: Int) -> [[Int]]` where ``` - `agents` is an array of agent coordinates. - `n` defines the size of the city that Bassi needs to hide in, in other words the side length of the square grid. The function should return a list of coordinates that are the furthest away (by Manhattan distance) from all agents. As an example, say you have a 6x6 map, and agents at locations ```python [(0, 0), (1, 5), (5, 1)] ``` ```javascript [[0, 0], [1, 5], [5, 1]] ``` ```haskell [(0, 0), (1, 5), (5, 1)] ``` The distances to the nearest agent look like this. <img src="https://github.com/falcowinkler/falcowinkler.github.io/raw/master/resources/codewars/safest.png"></img> The safest spaces are the ones with distance `4`, marked in bright red. So the function should return ```python [(2, 2), (3, 3), (4, 4), (5, 5)] ``` ```javascript [[2, 2], [3, 3], [4, 4], [5, 5]] ``` ```haskell [(2, 2), (3, 3), (4, 4), (5, 5)] ``` in any order. Edge cases: - If there is an agent on every grid cell, there is no safe space, so return an empty list. - If there are no agents, then every cell is a safe spaces, so return all coordinates. - if `n` is `0`, return an empty list. - If agent coordinates are outside of the map, they are simply not considered. - There are no duplicate agents on the same square. <h2>Performance</h2> You will probably not pass the tests if you use a brute-force solution. In other words, you need to do better than `O(agents*n*n)`. This kata is inspired by ThoughtWorks' <a href="https://github.com/Fun-Coding-Challenges/ada-lovelace-coding-challenge">coding challenge</a>
algorithms
def advice(agents, n): frontier = {(x, y) for x, y in agents if 0 <= x < n and 0 <= y < n} bag = {(x, y) for x in range(n) for y in range(n)} if frontier == bag: return [] while frontier and bag > frontier: bag -= frontier frontier = {pos for x, y in frontier for pos in ( (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)) if pos in bag} return sorted(bag)
Find the safest places in town
5dd82b7cd3d6c100109cb4ed
[ "Algorithms" ]
https://www.codewars.com/kata/5dd82b7cd3d6c100109cb4ed
5 kyu
You're stuck in a maze and have to escape. However, the maze is blocked by various doors and you'll need the correct key to get through a door. --- ## Basic instructions You are given a grid as the input and you have to return the positions to go through to escape. To escape, you have to collect every key and then reach the exit (the exit can only be unlocked if you have every key). There are also doors in the way, and you can only get through a door if you have the corresponding key. --- ## More detail The grid is given as a tuple of string representing rows of a grid. The start position is given by `'@'` and the end position is given by `'$'`. Walls are given by `'#'` Doors are represented by an upper case letter eg. `'A'`. And the corresponding key is represented by the lower case letter. For example. the key `'b'` unlocks the door `'B'`. To collect a key, you just have to travel over the position where it is located (it is automatically picked up). You can move in 4 directions: up, down, left or right. You __cannot__ move diagonally. You also cannot move out of the grid or through walls. To escape, you have to return the __shortest path__ to travel through to reach the end. You have to return a list of all the positions you travel through (including the start and end) in the cartesian form `(x, y)`, with `x` being the horizontal position, and `y` being vertical position. `(0, 0)` will be the top left position. The shortest path is defined by the least amount of moves you have to make. If there is no solution, you should return `None`. You will have to deal with up to 8 keys per grid. There will always be as many keys as doors, and you have to collect all the keys to be able to escape through the exit. You can only travel through doors if you have the correct key. However, you __can__ travel over the exit even if you don't have all the keys (imagine that the exit is a trapdoor). You do not need collect the keys in alphabetical order. For example: ``` grid2 in the sample tests is: ( '.a..', '##@#', '$A.#' ) You should return: [(2, 1), (2, 0), (1, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2)] as you have to go upwards to get key `a` before being able to go though door `A` to get to the exit. grid3 in the sample tests is: ( 'aB..', '##@#', '$Ab#' ) You should return: [(2, 1), (2, 2), (2, 1), (2, 0), (1, 0), (0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2)] ``` If no keys are given, then you just have to reach the exit. If there are multiple shortest solutions, you can return any of them. There are 101 tests in total: 8 sample tests and 93 random tests. The largest random tests will have maximum side lengths of 50 x 50 --- ## Remember: - You can only go out the exit if you have collected all the keys. - You can travel over the exit without all the keys, but you __cannot__ travel over doors without the correct key - You have to return the shortest path - The doors may not be in alphabetical order (you may have a `B` door without there being an `A` door) Good luck! :)
algorithms
from collections import deque from itertools import chain, product def escape(grid): nr, nc = len(grid), len(grid[0]) open = {x for x in chain . from_iterable( grid) if x != '#' and not x . isupper()} all_keys = {x . upper() for x in chain . from_iterable(grid) if x . islower()} r0, c0 = next((r, c) for r, c in product( range(nr), range(nc)) if grid[r][c] == '@') prev = {(r0, c0, frozenset(open)): None} queue = deque(prev) while queue: r0, c0, o0 = queue . popleft() for dr, dc in (- 1, 0), (1, 0), (0, - 1), (0, 1): if 0 <= (r := r0 + dr) < nr and 0 <= (c := c0 + dc) < nc: if (x := grid[r][c]) in o0 and (r, c, o := o0 | {x . upper()}) not in prev: prev[r, c, o] = r0, c0, o0 queue . append((r, c, o)) if x == '$' and o >= all_keys: return list(_reconstruct_path(prev, (r, c, o)))[:: - 1] def _reconstruct_path(prev, pos): while pos is not None: yield pos[1], pos[0] pos = prev[pos]
Escape!
5dc49700c6f56800271424a5
[ "Algorithms" ]
https://www.codewars.com/kata/5dc49700c6f56800271424a5
3 kyu
A "graph" consists of "nodes", also known as "vertices". Nodes may or may not be connected with one another. In our definition below the node "A0" is connected with the node "A3", but "A0" is not connected with "A1". The connecting line between two nodes is called an edge. If the edges between the nodes are undirected, the graph is called an undirected graph. A weighted graph is a graph in which a number (the weight) is assigned to each edge. A graph is acyclic if it has no loop. A graph can be represented as a dictionary: `graph = {'A0': [('A3', 1), ('A5', 4)], 'A1': [('A2', 2)], 'A2': [('A1', 1), ('A2', 2), ('A3', 1), ('A4', 1)], 'A3': [('A0', 1), ('A2', 1)], 'A4': [('A2', 1), ('A4', 1)], 'A5': [('A3', 3)] }` Here the nodes are A0...A5; following each nodes is the edges list of linked nodes with their weight. A0 is linked to A3 with a weight of 1 and to A5 with weight 4. A dictionary is not ordered but the list of linked nodes is sorted. So: `'A0': [('A3', 1), ('A5', 4)]`is correct but `'A0': [('A5', 4), ('A3', 1)]`is not. The edges E of a graph G induce a binary relation that is called the adjacency relation of G. One can associate an adjacency matrix: `M = [[0, 0, 0, 1, 0, 4], [0, 0, 2, 0, 0, 0], [0, 1, 2, 1, 1, 0], [1, 0, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0], [0, 0, 0, 3, 0, 0]]` Let us imagine that lines are numbered from A0 to A5 and the same for columns. The first line correspond to A0 and we can see that A0 is connected to A3 with weight 1, A0 is also connected to A5 with weight 4. Another way is to use an adjacency list: An adjacency list representation for a graph associates each vertex in the graph with the collection of its neighboring edges: `L = [['A0', [('A3', 1), ('A5', 4)]], ['A1', [('A2', 2)]], ['A2', [('A1', 1), ('A2', 2), ('A3', 1), ('A4', 1)]], ['A3', [('A0', 1), ('A2', 1)]], ['A4', [('A2', 1), ('A4', 1)]], ['A5', [('A3', 3)]]] ` L is sorted in order A0 to A5 and each sublist is sorted as in a graph dictionary. In the kata nodes will be numbered from A0 to A(n-1) for a graph with n nodes. The task is to go from each represention to each other one and at last to find *all* paths from a node to another node. Below is a skeleton for our class `Graph`. class Graph(): def __init__(self, vertices_num): # number of nodes (an integer) self.v = vertices_num # (maybe not useful here) : list of nodes from "A0", "A1" ... to "A index (vertices_num - 1)" self.nodes = None # from adjacency matrix to dictionary def adjmat_2_graph(self, adjm): # from dictionary to adjacency matrix def graph_2_mat(self, graph): # from dictionary to adjacency list def graph_2_list(self, graph): # from adjacency list to dictionary def list_2_graph(self, lst): # from adjacency matrix to adjacency list def mat_2_list(self, mat): # from adjacency list to adjacency matrix def list_2_mat(self, lst): # find all paths from node start_vertex to node end_vertex def find_all_paths(self, graph, start_vertex, end_vertex): # Examples: - see: graph, M, L above. - finding all paths: `dct = {'A3': [('A0', 1), ('A2', 1)], 'A0': [('A3', 1), ('A2', 1)], 'A4': [('A2', 1)], 'A1': [('A2', 1)], 'A2': [('A1', 1), ('A2', 1), ('A3', 1), ('A4', 1)]}` `g = Graph(5)` `g.find_all_paths(dct, "A0", "A4") return l = ['A0-A2-A4', 'A0-A3-A2-A4']` Note that ['A0-A2-A4', 'A0-A3-A2-A4'] is sorted (hint: sorted(sorted(l, key=str), key=len)) Translators and critics are welcome.
reference
from collections import deque class Graph (): def __init__(self, vertices_num): self . v = vertices_num def adjmat_2_graph(self, adjm): d = {f'A { i } ': [] for i in range(self . v)} for i, j in enumerate(adjm): for k, l in enumerate(j): if l: d[f'A { i } ']. append((f'A { k } ', l)) return d def graph_2_mat(self, graph): mat = [[0 for _ in range(self . v)] for _ in range(self . v)] for i, j in graph . items(): for k, l in j: mat[int(i[1])][int(k[1])] = l return mat def graph_2_list(self, graph): return [[i, j] for i, j in sorted(graph . items())] def list_2_graph(self, lst): return {i: x for i, x in lst} def mat_2_list(self, mat): return self . graph_2_list(self . adjmat_2_graph(mat)) def list_2_mat(self, lst): return self . graph_2_mat(self . list_2_graph(lst)) def find_all_paths(self, graph, start, end): graph = {i: [k[0] for k in j] for i, j in graph . items()} Q, paths = deque([[start, []]]), [] while Q: node, path = Q . popleft() path . append(node) if node == end: paths . append('-' . join(path)) for n in graph[node]: if n not in path: Q . append([n, path[:]]) return sorted(paths, key=len)
Undirected weighted graph
5aaea7a25084d71006000082
[ "Fundamentals", "Lists", "Matrix", "Graph Theory" ]
https://www.codewars.com/kata/5aaea7a25084d71006000082
4 kyu
## Minimal Cost Binary Search Trees The description that follows presumes that you have completed [Binary Search Trees](http://www.codewars.com/kata/binary-search-trees). Before starting on this kata, fill in the code for `Tree`'s `__eq__`, `__ne__`, and `__str__` methods as described and verified by that kata. Imagine you have a binary search tree and after some time you notice that some of the nodes are accessed more frequently than others. The time it takes to access a node depends on how deep the node is in the tree, so ideally you would want nodes that are accessed often placed close to the root. The purpose of the this kata is to "balance" the tree such that the average cost of accessing nodes is minimized. Each node has a `weight` attribute which could represent how often the node is accessed. For each node in a tree, one can associate a cost, which is the weight of the node times its depth. The depth of the root node is defined to be 1, and the depth of a node directly below a node of depth `d` is `d + 1`. The cost of a tree is simply the sum of the costs of its nodes. Your first task is to write a function `cost` that takes a tree as argument and returns the cost of the tree. Now we are getting to the more challenging part of this kata. Your final task is to write a function `make_min_tree` that takes a non-empty list of nodes as argument and returns a tree with minimal cost. The list passed as argument is sorted in ascending order. No two nodes in the list are equal (under the definition of "equal" provided by `__eq__` and `__ne__`). For this last part, your code will be tested with lists up to a length of 100. (Note: My algorithm is quadratic in space and cubic in time, but I am not sure it cannot be done better.)
reference
import math from functools import cache class Tree (object): def __init__(self, root, left=None, right=None): assert root and type(root) == Node if left: assert type(left) == Tree and left . root < root if right: assert type(right) == Tree and root < right . root self . left = left self . root = root self . right = right def is_leaf(self): return not (self . left or self . right) def __str__(self): return f"[ { self . root } ]" if self . is_leaf() else f"[ { self . left or '_' } { self . root } { self . right or '_' } ]" def __eq__(self, other): return self . root == other . root and self . left == other . left and self . right == other . right class Node (object): def __init__(self, value, weight=1): self . value = value self . weight = weight def __str__(self): return '%s:%d' % (self . value, self . weight) def __lt__(self, other): return self . value < other . value def __gt__(self, other): return self . value > other . value def __eq__(self, other): return self . value == other . value def __ne__(self, other): return self . value != other . value def cost(tree, depth=1): ''' Returns the cost of a tree which root is depth deep. ''' return tree . root . weight * depth + cost(tree . left, depth + 1) + cost(tree . right, depth + 1) if tree else 0 def make_min_tree(node_list): ''' node_list is a list of Node objects Pre-cond: len(node_list > 0) and node_list is sorted in ascending order Returns a minimal cost tree of all nodes in node_list. ''' weightsums = {} for i in range(len(node_list)): weightsums[i, i] = node_list[i]. weight for j in range(i + 1, len(node_list)): weightsums[i, j] = weightsums[i, j - 1] + node_list[j]. weight @ cache def rec(i, j): if i > j: return None, 0 mincost = math . inf mintree = None for k in range(i, j + 1): lt, lc = rec(i, k - 1) rt, rc = rec(k + 1, j) cost = lc + rc + weightsums[i, j] if cost < mincost: mincost = cost mintree = Tree(node_list[k], lt, rt) return mintree, mincost return rec(0, len(node_list) - 1)[0]
Minimal Cost Binary Search Trees
571a7c0cf24bdf99a8000df5
[ "Algorithms", "Binary Search Trees", "Fundamentals" ]
https://www.codewars.com/kata/571a7c0cf24bdf99a8000df5
3 kyu
Ever heard about Dijkstra's shallowest path algorithm? Me neither. But I can imagine what it would be. You're hiking in the wilderness of Northern Canada and you must cross a large river. You have a map of one of the safer places to cross the river showing the depths of the water on a rectangular grid. When crossing the river you can only move from a cell to one of the (up to 8) neighboring cells. You can start anywhere along the left river bank, but you have to stay on the map. An example of the depths provided on the map is ``` [[2, 3, 2], [1, 1, 4], [9, 5, 2], [1, 4, 4], [1, 5, 4], [2, 1, 4], [5, 1, 2], [5, 5, 5], [8, 1, 9]] ``` If you study these numbers, you'll see that there is a path accross the river (from left to right) where the depth never exceeds 2. This path can be described by the list of pairs `[(1, 0), (1, 1), (2, 2)]`. There are also other paths of equal maximum depth, e.g., `[(1, 0), (1, 1), (0, 2)]`. The pairs denote the cells on the path where the first element in each pair is the row and the second element is the column of a cell on the path. Your job is to write a function `shallowest_path(river)` that takes a list of lists of positive ints (or array of arrays, depending on language) showing the depths of the river as shown in the example above and returns a shallowest path (i.e., the maximum depth is minimal) as a list of coordinate pairs (represented as tuples, Pairs, or arrays, depending on language) as described above. If there are several paths that are equally shallow, the function shall return a shortest such path. All depths are given as positive integers.
algorithms
from heapq import * MOVES = tuple((dx, dy) for dx in range(- 1, 2) for dy in range(- 1, 2) if dx or dy) def shallowest_path(river): lX, lY = len(river), len(river[0]) pathDct = {} cost = [[(float('inf'), float('inf'))] * lY for _ in range(lX)] for x in range(lX): cost[x][0] = (river[x][0], 1) q = [(river[x][0], lY == 1, 1, (x, 0)) for x in range(lX)] heapify(q) while not q[0][1]: c, _, steps, pos = heappop(q) x, y = pos for dx, dy in MOVES: a, b = new = x + dx, y + dy if 0 <= a < lX and 0 <= b < lY: check = nC, nS = max(c, river[a][b]), steps + 1 if cost[a][b] > check: cost[a][b] = check pathDct[new] = pos heappush(q, (nC, b == lY - 1, nS, new)) path, pos = [], q[0][- 1] while pos: path . append(pos) pos = pathDct . get(pos) return path[:: - 1]
Shallowest path across the river
585cec2471677ee42c000296
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/585cec2471677ee42c000296
4 kyu
<!--Area of House from Path of Mouse--> <img src='https://i.imgur.com/IVdNZe1.png'/><br/> <sup style='color:#ccc'><i>Above: An overhead view of the house in one of the tests. The green outline indicates the path taken by K</i></sup> <p>A mouse named K has found a new home on Ash Tree Lane. K wants to know the size of the interior of the house (which consists of just one room). K is able to measure precise distances in any direction he runs. But K is wary of open spaces and will only run alongside walls, as mice tend to do. In this house the walls always connect at right angles.</p> <p>K's plan is to run alongside the walls, traversing the entire perimeter of the room, starting and ending at K's mousehole. K memorizes the path as an alternating sequence of distance traveled and directional turn. Your task is to write a function that will find the area of the house interior when given K's path.</p> <h2 style='color:#f88'>Input</h2> Your function will receive a string as an argument. The string will consist of turns (`L` or `R`, for `left` and `right`, respectively) and positive integers, in an alternating sequence. `L`/`R` represents the turn direction made by K, and the integers mark the number of distance units to move forward. <h2 style='color:#f88'>Output</h2> Your function should return an integer representing the area of the house, based on K's path. If K's path is not a valid path, return `null` or `None`. <h2 style='color:#f88'>Invalid Paths</h2> A path is <strong>invalid</strong> if it meets any of the following criteria: - the path intersects/overlaps itself (with the exception of the mousehole when completing the loop); see examples of path fragments below - the path doesn't complete the loop back to the mousehole - the mousehole is located along the straight path of a wall (K's mousehole must be located at a convex/concave corner position to be valid) <h3 style='color:#95c4ffff'>Invalidating overlap path fragment examples</h3> <img src='https://i.imgur.com/3oU2dWM.png' style='height:150px'/> <img src='https://i.imgur.com/SWqM8SR.png' style='height:150px'/> <img src='https://i.imgur.com/ET1nCER.png' style='height:150px'/> - Example A: Perpendicular intersection `...5L2L3L4...` - Example B: Point of overlap `...2L2R3R2R3L2...` - Example C: Parallel overlap `...4L2R2R3R4R1L2...` <h2 style='color:#f88'>Test Example</h2> <img src='https://i.imgur.com/GwEydDN.png'/><br/> <sup style='color:#ccc'>The circled K and green arrow indicate the starting position and direction as given in the example test below</sup> ```python mouse_path('4R2L1R5R9R4R4L3') # 49 ``` ```javascript mousePath('4R2L1R5R9R4R4L3') // 49 ``` <h2 style='color:#f88'>Additional Details</h2> - K's path will always consist of fewer than `500` turns - The area of the house (when valid) will always be less than `2**32` - Full Test Suite: `12` fixed tests and `150` random tests - Use Python 3+ for the Python translation - For JavaScript, most built-in prototypes are frozen, except `Array` and `Function` - All inputs will be of valid type and pattern (that is, it will alternate between distance moved and directional turn) - NOTE: the random test generator may, on very rare occasions, throw an error (around 0.01% of the time, based on my observation); if you get an error pointing to the random test function, try running your solution again. - This kata was inspired by [Kafka](https://en.wikipedia.org/wiki/A_Little_Fable) and [Danielewski](https://en.wikipedia.org/wiki/House_of_Leaves) <p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p>
algorithms
def add_point(ori, dis, c): lastPoint = c[- 1] if ori == "N": c . append((lastPoint[0], lastPoint[1] + dis)) elif ori == "S": c . append((lastPoint[0], lastPoint[1] - dis)) elif ori == "E": c . append((lastPoint[0] + dis, lastPoint[1])) else: c . append((lastPoint[0] - dis, lastPoint[1])) def check_corner(l_o): ini = l_o[0] fin = l_o[- 1] if ini == fin: return False if ini == "N" or ini == "S": ini = "V" else: ini = "H" if fin == "N" or fin == "S": fin = "V" else: fin = "H" if ini == fin: return False return True def check_intersect(rectas): u = rectas[- 1] ux = [u[0][0], u[1][0]] ux . sort() uy = [u[0][1], u[1][1]] uy . sort() oriU = "" if ux[0] == ux[1]: oriU = "V" if uy[0] == uy[1]: oriU = "H" for r in rectas[: - 2]: rx = [r[0][0], r[1][0]] rx . sort() ry = [r[0][1], r[1][1]] ry . sort() oriR = "" if rx[0] == rx[1]: oriR = "V" if ry[0] == ry[1]: oriR = "H" if oriU == oriR: if oriU == "V" and ux[0] == rx[0]: if ry[0] <= uy[0] <= ry[1] or ry[0] <= uy[1] <= ry[1]: return True if uy[0] < ry[0] and uy[1] > ry[1]: return True if oriU == "H" and uy[0] == ry[0]: if rx[0] <= ux[0] <= rx[1] or rx[0] <= ux[1] <= rx[1]: return True if ux[0] < rx[0] and ux[1] > rx[1]: return True elif oriU == "V": if uy[0] <= ry[0] <= uy[1]: if rx[0] < ux[0] and rx[1] > ux[0]: return True elif oriU == "H": if ux[0] <= rx[0] <= ux[1]: if ry[0] < uy[0] and ry[1] > uy[0]: return True else: return False def calc_area(camino): parN = camino[- 1][0] * camino[0][1] - camino[- 1][1] * camino[0][0] for p in range(1, len(camino)): par = camino[p - 1][0] * camino[p][1] - camino[p - 1][1] * camino[p][0] parN += par return abs(parN) / 2 def mouse_path(s): camino = [(0, 0)] distancia = 0 listaOrientaciones = ["E"] rectas = [] for c in s: orientacion = listaOrientaciones[- 1] if c . isdigit(): distancia = distancia * 10 + int(c) else: add_point(orientacion, distancia, camino) rectas . append((camino[- 2], camino[- 1])) if check_intersect(rectas): return None if c == "L": if orientacion == "N": listaOrientaciones . append("O") elif orientacion == "S": listaOrientaciones . append("E") elif orientacion == "E": listaOrientaciones . append("N") else: listaOrientaciones . append("S") else: if orientacion == "N": listaOrientaciones . append("E") elif orientacion == "S": listaOrientaciones . append("O") elif orientacion == "E": listaOrientaciones . append("S") else: listaOrientaciones . append("N") distancia = 0 add_point(orientacion, distancia, camino) rectas . append((camino[- 2], camino[- 1])) if check_intersect(rectas): return None if camino[- 1] != (0, 0): return None if not check_corner(listaOrientaciones): return None return calc_area(camino)
Area of House from Path of Mouse
5d2f93da71baf7000fe9f096
[ "Strings", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5d2f93da71baf7000fe9f096
4 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="weekly coding challenge" /> x 3 *I bet you won't ever catch a Lift (a.k.a. elevator) again without thinking of this Kata !* <hr> # Synopsis A multi-floor building has a Lift in it. People are queued on different floors waiting for the Lift. Some people want to go up. Some people want to go down. The floor they want to go to is represented by a number (i.e. when they enter the Lift this is the button they will press) ``` BEFORE (people waiting in queues) AFTER (people at their destinations) +--+ +--+ /----------------| |----------------\ /----------------| |----------------\ 10| | | 1,4,3,2 | 10| 10 | | | |----------------| |----------------| |----------------| |----------------| 9| | | 1,10,2 | 9| | | | |----------------| |----------------| |----------------| |----------------| 8| | | | 8| | | | |----------------| |----------------| |----------------| |----------------| 7| | | 3,6,4,5,6 | 7| | | | |----------------| |----------------| |----------------| |----------------| 6| | | | 6| 6,6,6 | | | |----------------| |----------------| |----------------| |----------------| 5| | | | 5| 5,5 | | | |----------------| |----------------| |----------------| |----------------| 4| | | 0,0,0 | 4| 4,4,4 | | | |----------------| |----------------| |----------------| |----------------| 3| | | | 3| 3,3 | | | |----------------| |----------------| |----------------| |----------------| 2| | | 4 | 2| 2,2,2 | | | |----------------| |----------------| |----------------| |----------------| 1| | | 6,5,2 | 1| 1,1 | | | |----------------| |----------------| |----------------| |----------------| G| | | | G| 0,0,0 | | | |====================================| |====================================| ``` <hr> # Rules #### Lift Rules * The Lift only goes up or down! * Each floor has both UP and DOWN Lift-call buttons (except top and ground floors which have only DOWN and UP respectively) * The Lift never changes direction until there are no more people wanting to get on/off in the direction it is already travelling * When empty the Lift tries to be smart. For example, * If it was going up then it will continue up to collect the highest floor person wanting to go down * If it was going down then it will continue down to collect the lowest floor person wanting to go up * The Lift has a maximum capacity of people * When called, the Lift will stop at a floor **even if it is full**, although unless somebody gets off nobody else can get on! * If the lift is empty, and no people are waiting, then it will return to the ground floor #### People Rules * People are in **"queues"** that represent their order of arrival to wait for the Lift * All people can press the UP/DOWN Lift-call buttons * Only people going the **same direction** as the Lift may enter it * Entry is according to the **"queue" order**, but those unable to enter do not block those behind them that can * If a person is unable to enter a full Lift, they will press the UP/DOWN Lift-call button again after it has departed without them <hr> # Kata Task * Get all the people to the floors they want to go to while obeying the **Lift rules** and the **People rules** * Return a list of all floors that the Lift stopped at (in the order visited!) NOTE: The Lift always starts on the ground floor (and people waiting on the ground floor may enter immediately) <hr> # I/O #### Input * ```queues``` a list of queues of people for all floors of the building. * The height of the building varies * 0 = the ground floor * Not all floors have queues * Queue index [0] is the "head" of the queue * Numbers indicate which floor the person wants go to * ```capacity``` maximum number of people allowed in the lift *Parameter validation* - All input parameters can be assumed OK. No need to check for things like: * People wanting to go to floors that do not exist * People wanting to take the Lift to the floor they are already on * Buildings with < 2 floors * Basements #### Output * A list of all floors that the Lift stopped at (in the order visited!) <hr> # Example Refer to the example test cases. <hr> # Language Notes * Python : The object will be initialized for you in the tests <hr> <span style="color:red"> Good Luck - DM </span>
algorithms
class Dinglemouse (object): def __init__(self, queues, capacity): self . inLift, self . moves = [], [0] self . peopleOnFloorsLists = [list(floor) for floor in queues] self . stage, self . moving = - 1, 1 self . capacity = capacity def theLift(self): while self . areStillPeopleToBeLifted() or not self . liftIsEmpty(): self . stage += self . moving if self . areSomePeopleIn_WannaGoOut() or self . areSomeGuysWaitingSameWay_AtThatFloor(self . stage): self . liftStopAtThisStage() self . somePeopleIn_GoOut() self . takeIn_AllPeopleGoingTheSameWay() """ Decide what the lift has to do now: No change of direction in these cases : - If the lift contains people going in the same direction: They have the priority... - If there are people further that want to go in the same direction... - If the lift is Empty and that some people further want to go in the other direction, the lift goes as far as it can before taking in some people again (who wana go to in the other direction). In other cases, the lift begins to move the other way. For the simplicity of the implementation, the lift is shifted one step backward, so it will be able to managed the presence of people at the current floor (before update) who want to go in the other direction. """ if not (self . anyPeopleIn_GoingSameWay() or self . areSomeGuysFurther_Wanting_(self . areSomeGuysWaitingSameWay_AtThatFloor) or (self . liftIsEmpty() and self . areSomeGuysFurther_Wanting_(self . areSomeGuysWaitingOtherWay_AtThatFloor))): self . moving *= - 1 self . stage -= self . moving self . liftStopAtThatStage(0) # return to the ground if needed return self . moves def areStillPeopleToBeLifted(self): return any( bool(queue) for queue in self . peopleOnFloorsLists) def liftIsEmpty(self): return not self . inLift def areSomePeopleIn_WannaGoOut(self): return self . stage in self . inLift def somePeopleIn_GoOut(self): self . inLift = list( filter(lambda i: i != self . stage, self . inLift)) def anyPeopleIn_GoingSameWay(self): return any( guy * self . moving > self . stage * self . moving for guy in self . inLift) def areSomeGuysWaitingSameWay_AtThatFloor(self, lvl): return any( i * self . moving > lvl * self . moving for i in self . peopleOnFloorsLists[lvl]) def areSomeGuysWaitingOtherWay_AtThatFloor(self, lvl): return any( i * self . moving < lvl * self . moving for i in self . peopleOnFloorsLists[lvl]) def liftStopAtThisStage(self): self . liftStopAtThatStage(self . stage) def liftStopAtThatStage(self, lvl): if self . moves[- 1] != lvl: self . moves . append(lvl) def takeIn_AllPeopleGoingTheSameWay(self): peopleGoingIn, peopleThere = [], self . peopleOnFloorsLists[self . stage] for i in peopleThere: # Get all people who can enter the lift, according to its capacity and the queue order if len(peopleGoingIn) + len(self . inLift) == self . capacity: break if i * self . moving > self . stage * self . moving: peopleGoingIn . append(i) self . inLift += peopleGoingIn # update the lift content while peopleGoingIn: # Remove the new people in the lift from this floor (using mutability of list, passed by reference) peopleThere . remove(peopleGoingIn . pop()) def areSomeGuysFurther_Wanting_(self, func): i = self . stage + self . moving while 0 <= i < len(self . peopleOnFloorsLists): if func(i): return True i += self . moving return False
The Lift
58905bfa1decb981da00009e
[ "Algorithms", "Queues", "Data Structures" ]
https://www.codewars.com/kata/58905bfa1decb981da00009e
3 kyu
# Overview: The idea of this kata is to create two classes, `Molecule` and `Atom`, that will allow you, using a set of methods, to build numerical equivalents of organic compounds and to restitute some of their simplest properties (molecular weight and raw formula, for instance). You will need to implement some Exception classes in the process (_note for Java users: all exceptions will be unchecked and extend_ `RuntimeException` / note for JS users: use classes extending `Error` / note for Rust users: use variants of `ChemError`) ![3D Balls](https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Biotin-3D-balls.png/1024px-Biotin-3D-balls.png) (Biotin. Source: [wikipedia](https://commons.wikimedia.org/wiki/File:Biotin-3D-balls.png)) _Molecules are beautiful things. Especially organic ones..._ <br> <hr> <br> # The Molecule class This is the main object, the "builder of things" ( ;p ), representing the whole molecule, its properties and atoms, and holding all the related methods to build and modify the molecule object. ```if:rust ## Notes for Rustaceans > **The Kata Spec has only changed with respect to names, enums, and errors. Expected behavior is the same!** Rust method signatures are updated to conform to community standards, e.g. using verbs instead of "-er" nouns. To afford chaining as well as standalone mutative calls as per the kata spec, the builder methods take and emit `&mut self`. Additionally, instead of using string literals as the spec suggests, Rustaceans will use variants of the `preloaded::Element` enum. *Wherever the spec mentions an element symbol string, an `Element` will be provided instead.* Lastly, in Rust we use results, not exceptions. Take care to handle interrupts the way exceptions would be used in the other languages of this kata. The errors referenced are encapsulated in the `preloaded::ChemError` enum as part of the preloaded module. *Wherever the spec mentions throwing an Exception, return a `Result<_, ChemResult>` instead.* **Look at the final notes section for more detail on the `preloaded` module!** ### Examples of Syntax Changes: | Original Syntax | Rust Syntax | | ----------------- | ------------- | | `brancher` | `branch` | | `bonder` | `bond` | | `addChaining` | `add_chain` | | `"Cl"` | `Element::Cl` | | `raise InvalidBond()` | `return Err(ChemError::InvalidBond)` | | `m.bounder(..).mutate(..)` | `(&mut m).bond(..)?.mutate(..)?` | ``` ## Required properties/getters: * To get the raw formula of the final molecule as a string (ex: "C4H10", "C5H10O2BrClS", ...; see detailed behaviours and additional information below): ```python self.formula ``` ```ruby self.formula ``` ```java String getFormula() ``` ```javascript this.formula ``` ```rust self.formula() ``` * To get the value of the molecular weight of the final molecule in g/mol, as a double value (see detailed behaviours and additional information below): ```python self.molecular_weight ``` ```ruby self.molecular_weight ``` ```java double getMolecularWeight() ``` ```javascript this.molecularWeight ``` ```rust self.molecular_weight() ``` * To get a list of Atom objects. Atoms are appended to the list in the order of their creation: ```python self.atoms ``` ```ruby self.atoms ``` ```java List<Atom> getAtoms() ``` ```javascript this.atoms ``` ```rust self.atoms() ``` * To get the name of the molecule, as a string of course, if given in the constructor (default: empty string): ```python self.name ``` ```ruby self.name ``` ```java String getName() ``` ```javascript this.name ``` ```rust self.name() ``` <br> ## Required methods: ### Constructor(s): With or without the name of the molecule as argument (as a string): ```python m = Molecule() m = Molecule(name) ``` ```ruby m = Molecule.new() m = Molecule.new(name) ``` ```java Molecule m = new Molecule(); Molecule m = new Molecule(String name); ``` ```javascript let m = new Molecule(); let m = new Molecule(name); ``` ```rust let m = Molecule::default(); let m = Molecule::from("name"); ``` --- ### Modifiers: ```python m.brancher(x, y, z, ...) ``` ```ruby m.brancher(x, y, z, ...) ``` ```java m.brancher(x, y, z, ...) ``` ```javascript m.brancher(x, y, z, ...) ``` ```rust (&mut m).branch(&[x, y, z, ...]) ``` In a Molecule instance, a "branch" represents a chain of atoms bounded together. When a branch is created, all of its atoms are carbons. Each "branch" of the Molecule is identifiable by a number that matches its creation order: first created branch as number 1, second as number 2, ... ```if-not:rust The `brancher` method...: ``` ```if:rust The `branch` method...: ``` * Can take any number of arguments (positive integers). * Adds new "branches" to the current molecule. * Each argument gives the number of carbons of the new branch. --- ```python m.bounder((c1,b1,c2,b2), ...) ``` ```ruby m.bounder([c1,b1,c2,b2], ...) ``` ```java m.bounder( T(c1,b1,c2,b2), ...) (about the T object, see at the end of the description) ``` ```javascript m.bounder([c1,b1,c2,b2], ...) ``` ```rust (&mut m).bond(&[(c1, b1, c2, b2), ...]) ``` ```if-not:rust The `bounder` method...: ``` ```if:rust The `bond` method...: ``` * Creates new bounds between two atoms of existing branches. * Each argument is a tuple (python), array (ruby/JS), or `T` object (java) of four integers giving: - `c1` & `b1`: carbon and branch positions of the first atom - `c2` & `b2`: carbon and branch positions of the second atom * All positions are 1-indexed, meaning (1,1,5,3) will bound the first carbon of the first branch with the fifth of the third branch. * Only positive integers will be used. --- ```python m.mutate((nc,nb,elt), ...) ``` ```ruby m.mutate([nc,nb,elt], ...) ``` ```java m.mutate( T(nc,nb,elt), ...) (about the T object, see at the end of the description) ``` ```javascript m.mutate([nc,nb,elt], ...) ``` ```rust (&mut m).mutate(&[(nc, nb, elt), ...]) ``` The `mutate` method...: * Mutates the carbon `nc` in the branch `nb` to the chemical element `elt`(given as a string). * Don't forget that carbons and branches are 1-indexed. * This is _mutation_: the `id` number of the `Atom` instance stays the same. See the `Atom` class specs about that. --- ```python m.add((nc,nb,elt), ...) ``` ```ruby m.add([nc,nb,elt], ...) ``` ```java m.add( T(nc,nb,elt), ...) (about the T object, see at the end of the description) ``` ```javascript m.add([nc,nb,elt], ...) ``` ```rust (&mut m).add(&[(nc, nb, elt), ...]) ``` The `add` method...: * Adds a new Atom of kind `elt` (string) on the carbon `nc` in the branch `nb`. * Atoms added this way are not considered as being part of the branch they are bounded to and aren't considered a new branch of the molecule. --- ```python m.add_chaining(nc, nb, elt1, elt2, ...) ``` ```ruby m.add_chaining(nc, nb, elt1, elt2, ...) ``` ```java m.addChaining(nc, nb, elt1, elt2, ...) ``` ```javascript m.addChaining(nc, nb, elt1, elt2, ...) ``` ```rust (&mut m).add_chaining(nc, nb, &[elt, ...]) ``` The `add_chaining` method...: * Adds on the carbon `nc` in the branch `nb` a chain with all the provided elements, in the specified order. Meaning: `m.add_chaining(2, 5, "N", "C", "C", "Mg", "Br")` will add the chain `...-N-C-C-Mg-Br` to the atom number 2 in the branch 5. * As for the `add` method, this chain is not considered a new branch of the molecule. --- ```python m.closer() ``` ```ruby m.closer ``` ```java m.closer() ``` ```javascript m.closer() ``` ```rust (&mut m).close() ``` ```if-not:rust The `closer` method...: ``` ```if:rust The `close` method...: ``` * Finalizes the molecule instance, adding missing hydrogens everywhere and locking the object (see _behaviours_ part below). --- ```python m.unlock() ``` ```ruby m.unlock ``` ```java m.unlock() ``` ```javascript m.unlock() ``` ```rust (&mut m).unlock() ``` The `unlock` method...: * Makes the molecule mutable again. * Hydrogens should be removed, as well as any empty branch you might encounter during the process. * After the molecule has been "unlocked", if by any (bad...) luck it does not have any branch left, throw an `EmptyMolecule` exception. * The `id` numbers of the remaining atoms have to be continuous again (beginning at 1), keeping the order they had when the molecule was locked. * After removing hydrogens, if you end up with some atoms that aren't connected in any way to the branches of the unlocked molecule, keep them anyway in the Molecule instance (for the sake of simplicity...). Note that all the branches following removed one are shifted one step back (ex: removing the third branch, the "previously fourth branch" will be considered the third branch of the molecule in subsequent operations). * Once unlocked, the molecule has to be modifiable again, in any manner. <br> ## Related behaviours: ```if-not:rust * Methods that involve building molecule or mutating molecule objects have to be chainable (ex: `molec = Molecule("octane").brancher(8).closer()`). ``` ```if:rust * Methods that involve building molecule or mutating molecule objects have to be chainable (ex: `let ref mut m = Molecule::from("octane"); m.branch(&[8])?.close()?;`). ``` * Building a molecule consists in mutating the original object at each method call. * An `InvalidBond` exception should be thrown each time you encounter a case where an atom exceeds its valence number or is bounded to itself (_about the valence number, see additional information below_). * When a method throws an exception while it still has several arguments/atoms left to handle, the modifications resulting from the valid previous operations must be kept but all the arguments after the error are ignored. * Special case with `add_chaining`: if an error occurs at any point when adding the chain, all its atoms have to be removed from the instance (even the valid ones). * The whole molecule integrity should hold against any error, meaning that it must be possible to correctly work with a molecule object even after it threw an exception. * The fields `formula` and `molecular_weight` or the associated getters (depending on your language) should throw an `UnlockedMolecule` exception if an user tries to access them while the molecule isn't locked (because we do not want the user to catch incomplete/invalid information). * In a similar manner, attempts of modification of a molecule after it has been locked should throw a `LockedMolecule` exception (the `closer` method follows this behavior too). <br> ## Additional information: * ### Raw formula of organic compounds: The raw formula gives the number of each kind of chemical element in the molecule. There are several possible rules when it comes to the order of the atoms in the raw formula. Here we will use the following: `C, H, O, then other elements in alphabetic order`. Examples: `"C4H10"` for C<sub>4</sub>H<sub>10</sub>, `"C5H10O2BrClS"`, ... Note that the ones are not appearing (`Br` and not `Br1`). * ### Valence number of an atom: The valence number of an atom is the number of bounds it can hold. No less, no more. _<div style="size:2;color:gray">(Note to chemists: we will use all atoms at their lowest possible valence when several are possible. Meaning the valence number for S will be 2, for P it will be 3, ... Similarly, impossible bonds due to geometrical criteria such as a quadruple bound between two carbons will be allowed)</div>_ * ### Molecular weight: The molecular weight of a molecule is the sum of the atomic weight of all its atoms. You may find below all the data needed in the kata (symbols, valence numbers, and related atomic weights): Symbol: H B C N O F Mg P S Cl Br Valence number: 1 3 4 3 2 1 2 3 2 1 1 Atomic weight: 1.0 10.8 12.0 14.0 16.0 19.0 24.3 31.0 32.1 35.5 80.0 (in g/mol) <br> ----- <br> # The Atom Spec Values of this type represent atoms in a specific Molecule instance and the bonds they hold with other Atom instances in the same Molecule. ```if:not-rust ## Required properties: ``` ```if:rust ## Required fields: ``` To get the chemical symbol as a string ("C", "Br", "O", ...): ```python self.element ``` ```ruby self.element ``` ```java public String element ``` ```javascript this.element ``` ```rust self.element ``` To get the `id` number of this atom: ```python self.id ``` ```ruby self.id ``` ```java public int id ``` ```javascript this.id ``` ```rust self.id ``` The `id` number is an integer that allows to keep track of all the atoms of the same molecule, beginning with `1` (step of one for any new Atom instance). --- ## Required methods: ```python __hash__ # Provided. Do not modify this method __eq__ # Provided. Do not modify this method ``` ```ruby hash # Provided. Do not modify this method == # Provided. Do not modify this method eql? # Provided. Do not modify this method ``` ```java hashCode // Provided. Do not modify this method equals // Provided. Do not modify this method ``` ```javascript There are not provided methods in JS. ``` ````if:rust Rust has required, provided impls that should not be modified. ```rust impl PartialEq for Atom { fn eq(&self, other: &Self) -> bool { self.id == other.id } } ``` ```rust impl Eq for Atom {} ``` *Unlike other languages, `Hash` is not provided for `Atom` as it is unnecessary for the Rust test suite.* ```` As you will see with the implementations of these methods, all atoms are considered different from each other in a Molecule instance.<br> ```python __str__ ``` ```ruby to_s ``` ```java toString ``` ```javascript toString ``` ```rust format!("{atom}") ``` Return a string formatted like the following: `"Atom(element.id: element1id,element2id,element3id...)"`. * `element`: symbol of the current Atom instance * `id`: id of the current element (beginning at 1 for each Molecule instance) * `element1id`: element1, bonded to the current Atom and its id number. If the bonded atom is a hydrogen, do not display its `id` number, to increase readability. The elements bonded to the current atom must be sorted in the same order as for the raw formula, except that the hydrogens will go to the end, again for better readability. Atoms of the same chemical element are sorted by increasing value of their `id` number. If an atom isn't bonded to any other atom, then just return the `element.id` part: `"Atom(H.12)"`. Examples: `"Atom(C.2: C3,C14,O6,H)"` or `"Atom(C.24: C1,O6,N2,H)"`, or `"Atom(C.1)"` <br> <hr> <br> # Final notes: - You can add any method or field you'd like to the two objects and organize/design the whole thing as you'd prefer as long as the objects comply with the contracts above. ```if:rust - The tests permit adding lifetimes to the Atom and Molecule structs. ``` - The tests will only call for properties/methods described in the present contracts. - Methods will always receive valid arguments, considering carbons or branches numbers, or chemical elements symbols. - Atom instances will never be modified directly during the tests, all is done through the Molecule class. ```if:not-rust - About the required exceptions classes, you can implement subclasses if you want, but their names will have to contain the name of the one originally expected. ``` ```if:java # About the T object: This object is provided for you in the preloaded part. It's a very basic data container and it does only hold the "toString()" method. The very same kind of object will be used for several purposes, as you saw it in the method signatures above. You may find below additional information about the T object: class T { public int c1, c2, b1, b2, nc, nb; public String elt = ""; public T(int a, int b, int c, int d) { c1 = a; b1 = b; c2 = c; b2 = d; } public T(int a, int b, String c) { nc = a; nb = b; elt = c; } @Override public String toString() { return elt.isEmpty() ? String.format("T(%d, %d, %d, %d)", c1, b1, c2, b2) : String.format("T(%d, %d, %s)", nc, nb, elt); } } ``` ````if:rust ## About the `preloaded` module. This is the contents of the module: ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Element { C, H, O, B, Br, Cl, F, Mg, N, P, S, } impl Display for Element { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // str of the element symbol. } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ChemError { EmptyMolecule, LockedMolecule, InvalidBond, UnlockedMolecule, } pub type ChemResult<T> = Result<T, ChemError>; ``` _<div style="size:2;color:gray">Hint: `preloaded` is treated as a submodule of your solution. This means that you can write impls (if not derives) for all types defined there.</div>_ ```` <br> _Enjoy!_ <br> --- ## Example: building the Biotin ```python biotin = Molecule("biotin") biotin.brancher(14,1,1) biotin.bounder((2,1,1,2), (2,1,1,2), (10,1,1,3), (10,1,1,3), (8,1,12,1), (7,1,14,1)) biotin.mutate( (1,1,'O'), (1,2,'O'), (1,3,'O'), (11,1,'N'), (9,1,'N'), (14,1,'S')) biotin.closer() ``` ```java Molecule biotin = new Molecule("biotin"); biotin.brancher(14,1,1); biotin.bounder(new T(2,1,1,2), new T(2,1,1,2), new T(10,1,1,3), new T(10,1,1,3), new T(8,1,12,1), new T(7,1,14,1)); biotin.mutate( new T(1,1,"O"), new T(1,2,"O"), new T(1,3,"O"), new T(11,1,"N"), new T(9,1,"N"), new T(14,1,"S")); biotin.closer(); ``` ```javascript let biotin = new Molecule('biotin') biotin.brancher(14,1,1) biotin.bounder([2,1,1,2], [2,1,1,2], [10,1,1,3], [10,1,1,3], [8,1,12,1], [7,1,14,1]) biotin.mutate( [1,1,'O'], [1,2,'O'], [1,3,'O'], [11,1,'N'], [9,1,'N'], [14,1,'S']) biotin.closer() ``` ```ruby biotin = Molecule.new("biotin") biotin.brancher(14,1,1) biotin.bounder([2,1,1,2 ], [2,1,1,2 ], [10,1,1,3], [10,1,1,3], [8,1,12,1], [7,1,14,1]) biotin.mutate( [1,1,'O'], [1,2,'O'], [1,3,'O'], [11,1,'N'], [9,1,'N'], [14,1,'S']) biotin.closer() ``` ```rust use Element::*; let ref mut biotin = Molecule::from("biotin"); biotin.branch(&[14,1,1])?; biotin.bond(&[(2,1,1,2), (2,1,1,2), (10,1,1,3), (10,1,1,3), (8,1,12,1), (7,1,14,1)])?; biotin.mutate(&[(1,1,O), (1,2,O), (1,3,O), (11,1,N), (9,1,N), (14,1,S)])?; biotin.close()?; ``` ![3D Balls](https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Biotin-3D-balls.png/1024px-Biotin-3D-balls.png) --- [_The Full Metal Chemist collection_](https://www.codewars.com/collections/full-metal-chemist-collection)... <br>
reference
from collections import Counter from functools import wraps class InvalidBond (Exception): pass class UnlockedMolecule (Exception ): pass class LockedMolecule (Exception ): pass class EmptyMolecule (Exception ): pass class Atom (object): __slots__ = ('element', 'id', 'bonds' , 'isLocked' ) # Use slots to reduce memory usage ATOMS = ['C', 'H', 'O' , 'B' , 'Br' , 'Cl' , 'F' , 'Mg' , 'N' , 'P' , 'S' ] # Order consistent with the raw formula VALENCES = [4, 1, 2, 3 , 1 , 1 , 1 , 2 , 3 , 3 , 2 ] WEIGHTS = [12, 1, 16, 10.8 , 80 , 35.5 , 19 , 24.3 , 14 , 31 , 32.1 ] VALENCE = dict (zip (ATOMS, VALENCES )) # Dict to retreive the valence, based on the chemical symbol A_WEIGHT = dict (zip (ATOMS, WEIGHTS )) # Dict to retreive the atomic weight, based on the chemical symbol STR_ORDER = {at: i for i, at in enumerate (ATOMS )} STR_ORDER ['H'] = len (ATOMS ) # Override for ordering in Atom.__str__ def __init__ (self, elt, id_): self . element = elt # Chemical symbol self . id = id_ # id number self . bonds = [] # List of the bond atoms to the current instance # Allow to know if there is need to sort the "bonds" list or not when using __str__ self . isLocked = False """ MAKE THE ATOM CLASS SORTABLE """ def __eq__ (self, other ): return self . id == other . id def __lt__ (self , other ): return (Atom . STR_ORDER [self . element ], self . id ) < (Atom . STR_ORDER [ other . element ], other . id ) def __le__ (self, other): return self < other or self == other def __hash__(self): return self . id def __repr__ (self): return "Atom({}, {})" . format (self . element, self . id ) def __str__(self): if not self . isLocked: self . bonds . sort() # Sort "bonds" only if the molecule isn't locked yet, to ensure the order of the strings in Atom.__str__ s = ',' . join (b . element + str (b . id ) * (not b . isH ()) for b in self . bonds ) # Build the linked atoms string (H at the end and without id number) return "Atom({}.{}{})" . format (self . element, self . id, ": " * bool (s ) + s ) """ UTILITIES """ def isH (self): return self . element == 'H' def getValence (self): return Atom . VALENCE [self . element] def getMW (self): return Atom . A_WEIGHT [self . element] def unlock(self, newId): self . id = newId # affect the new id number self . bonds = [x for x in self . bonds if not x . isH()] # remove hydorgens from the "bonds" self . isLocked = False # unlock... def bondTo(self, other): if len(self . bonds) >= self . getValence(): raise InvalidBond ("Invalid bond creation: the atom would exceed its valence number ({}, {})" . format (self, other)) if self == other: raise InvalidBond("Invalid bond creation: an atom cannot bond to itself: " + str (self)) self . bonds . append(other) def mutate(self, elt): if len (self . bonds) > Atom . VALENCE [elt]: raise InvalidBond ("Cannot mutate {} to {}: too many bonds on the current atom: {}." . format (self, elt , len (self . bonds ))) self . element = elt def cut(self, other): try: self . bonds . remove (other) # remove one and only one 'other' from the list except ValueError: pass class Molecule (object): """ DECORATOR DEFINITION """ def raiseIf_isMutabe_Is(shouldNotBeThat): def decorator(func): @ wraps(func) def wrapper(* args, * * kwargs): if args[0]. isMutable == shouldNotBeThat: if args [0]. isMutable: raise UnlockedMolecule("This molecule isn't finished yet: not reliable information.") else: raise LockedMolecule ("This molecule is locked, create a new one") return func (* args, * * kwargs) return wrapper return decorator """ CONSTRUCTOR & PROPERTIES """ def __init__ (self, name = ''): self . name = name # Molecule name self . _formula = '' # Raw formula ("internal" property) self . _mw = 0 # Molecular weight ("internal" property) self . atoms = [] # List of all the atoms of the molecule, in order of they id number self . branches = [] # List of list of Atoms: branches appended in order to the molecule self . isMutable = True # Tell if the molecule is modifiable or not @ property @ raiseIf_isMutabe_Is(True) def formula (self): return self . _formula # Raise UnlockedMolecule exception if needed @ property @ raiseIf_isMutabe_Is(True) def molecular_weight (self): return self . _mw # Raise UnlockedMolecule exception if needed """ UTILITIES """ def __str__ (self): return "{}, {}" . format (self . name , self . formula ) def getInBranch (self, nc , nb ): return self . branches [nb - 1 ][nc - 1 ] def createBond (self, a1, a2 ): # Create a bond between two atoms (in each "direction") wasBonded = False for a, b in ((a1, a2 ), (a2 , a1 )): try: a . bondTo(b) wasBonded = True except InvalidBond as eIB: if wasBonded: a1 . cut (a2) # If bonding craches while a first bond has been created, remove it raise eIB def createAtom(self, elt): self . atoms . append (Atom (elt , len (self . atoms ) + 1 ) ) # Create a new atom with the required id number, append it the the list of atoms... return self . atoms [- 1] # ... then return it. """ REQUIRED METHODS """ @ raiseIf_isMutabe_Is(False) def brancher(self, * nCargs): for nC in nCargs: lst = [] self . branches . append (lst) # Create the list holding the new branch for n in range(nC): lst . append (self . createAtom ('C') ) # Append a new C atom if len(lst) > 1: self . createBond (lst [- 2 ], lst [- 1 ]) # Link the two last atoms of the branch together return self @ raiseIf_isMutabe_Is(False) def bounder(self, * tupArgs): for c1, b1, c2, b2 in tupArgs: self . createBond (self . getInBranch (c1, b1 ), self . getInBranch (c2 , b2 )) return self @ raiseIf_isMutabe_Is(False) def mutate(self, * args): for nc, nb, elt in args: self . getInBranch (nc, nb). mutate (elt ) return self @ raiseIf_isMutabe_Is(False) def add(self, * args): for nc, nb, elt in args: try: self . createBond (self . getInBranch (nc, nb ), self . createAtom (elt )) except InvalidBond as eIB: # remove the last created atom from the "atoms" list if it hac not been bounded self . atoms . pop() raise eIB # relay the exception outside of the object return self @ raiseIf_isMutabe_Is(False) def add_chaining (self, nc, nb, * elts ): lastAt = self . atoms [- 1] # last existing atom in the list at the start (needed to remove a wrong chain) startAt = at = self . getInBranch (nc, nb) # starting point of the chain (atom in an existing branch) try: for elt in elts: # add successively all the element (if no error): newAt = self . createAtom (elt) # store the new created atom self . createBond (at, newAt) # bond it with the previous one (previous in the chain or "start"!) at = newAt # update the last Atom bonded except InvalidBond as eIB: # If an error occured: while self . atoms [- 1] != lastAt: # remove all the freshly created atoms from the list of "atoms", ... removedAt = self . atoms . pop() # ... archiving them... startAt . cut (removedAt) # ... so that one can cut the bond between "start" and the first atom of the chain raise eIB # relay the exception outside of the object return self @ raiseIf_isMutabe_Is(False) def closer(self): for at in self . atoms: # Add all the missing Hydrogens for nH in range(at . getValence () - len (at . bonds)): self . createBond (at, self . createAtom ('H') ) at . bonds . sort() # Sort at.bonds so that it's ok for printing it ("str(at)") at . isLocked = True # Lock the atom (see Atom description) c = Counter(at . element for at in self . atoms) self . _formula = '' . join (at + (str (c [at ]) if c [ at ] != 1 else '' ) for at in Atom . ATOMS if at in c ) self . _mw = sum(at . getMW() for at in self . atoms) self . isMutable = False return self def unlock(self): self . isMutable = True # Unlock the molecule self . atoms = [at for at in self . atoms if not at . isH()] # Remove Hydrogens for i, at in enumerate (self . atoms, 1 ): at . unlock (i) # Unlock the atoms and reaffect id numbers lst = [] for i, b in enumerate(self . branches): newB = [at for at in b if not at . isH()] # remove mutated hydrogens from the branches if newB: lst . append (newB) # keep only non empty branches if not lst: raise EmptyMolecule () # Forbide a molecule without branches to build on self . branches = lst return self
Full Metal Chemist #1: build me...
5a27ca7ab6cfd70f9300007a
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/5a27ca7ab6cfd70f9300007a
2 kyu
# Disclaimer If you're not yet familiar with the puzzle called Nonogram, I suggest you to solve [5x5 Nonogram Solver](https://www.codewars.com/kata/5x5-nonogram-solver/python) first. # Task Complete the function `solve(clues)` that solves 15-by-15 Nonogram puzzles. Your algorithm has to be clever enough to solve all puzzles in time. As in `5x5 Nonogram Solver`, the input format will look like this: ```python input = tuple(column_clues, row_clues) each of (row_clues, column_clues) = tuple( tuple(num_of_ones_in_a_row, ...), ... ) ``` ```java int[][][] input = {column_clues, row_clues}; each of (row_clues, column_clues) being: int[][] { int[] numOfOnesInARow_col1, int[] numOfOnesInARow_col2, ...} ... ``` # Output ```if:python Output is a 2D-tuple of zeros ans ones, representing the solved grid. ``` ```if:java Output is an int[][] 2D array of zeros ans ones, representing the solved grid. ``` # Example Here is the example puzzle in the Sample Test. ![](https://i.imgur.com/UOEciP1.png) # Notes Some puzzles may have lines with no cells filled. Most Nonogram games show the clues for such lines as a single zero, but the clue for such a line is represented as a **zero-length tuple** for the sake of this Kata.
games
from itertools import groupby from collections import defaultdict POS, B = defaultdict(set), 15 f = "{:0>" + str(B) + "b}" for n in range(1 << B): s = f . format(n) POS[tuple(sum(1 for _ in g) for k, g in groupby(s) if k == '1')]. add(tuple(map(int, s))) def solve(clues): clues = {'V': clues[0], 'H': clues[1]} grid = {(d, z): list(POS[clues[d][z]]) for d in 'VH' for z in range(B)} changed = True while changed: changed = False for x in range(B): for y in range(B): tupH, iH, tupV, iV = ('H', x), y, ('V', y), x if len(grid[tupH]) == 1 and len(grid[tupV]) == 1: continue vH = {v[iH] for v in grid[tupH]} vV = {v[iV] for v in grid[tupV]} target = vH & vV if len(vH) == 2 and len(target) == 1: changed = True grid[tupH] = [t for t in grid[tupH] if t[iH] in target] if len(vV) == 2 and len(target) == 1: changed = True grid[tupV] = [t for t in grid[tupV] if t[iV] in target] return tuple(grid[('H', n)][0] for n in range(B))
15x15 Nonogram Solver
5a5072a6145c46568800004d
[ "Puzzles", "Games", "Performance", "Game Solvers" ]
https://www.codewars.com/kata/5a5072a6145c46568800004d
2 kyu
## Description You are the Navigator on a pirate ship which has just collected a big haul from a raid on an island, but now you need to get home! Your captain has given you an intended course for your passage from the island - but the Royal Navy is on patrol! you need to tell your captain whether you will be able to make it home without being caught. ## Task You are given an array of arrays depicting the path back to your home from the island. Your ship will always start on the left most edge, and your ship will travel one space to the right each turn. The course is true if you can reach the right hand edge. To make things difficult, Royal Navy Ships are patrolling the passage. They start on the bottom and top most edges of the the passage - ones on the top move one space down each turn, and ones on the bottom move one space up each turn. when these ships reach the edge of the map, then on the next turn they reverse their direction and move one space (i.e. the every ship always moves one space each turn). Evaluate the array at the start of each turn once every ship has moved. If any of the adjacent spaces around your ship contain a Royal Navy patrol (including diagonals), then return false as this passage is unsafe! Also, if your ship starts adjacent to a Navy ship then return false. you are given an MxN array (it could be square) which contains: **X** - The location of your ship **N** - The location of a Navy ship **0** - An empty ocean space ### Example Here's an array at turn 0 when you will recieve it. ``` 0,N,0,N,0 0,0,0,0,0 X,0,N,0,0 ``` at the end of turn 1 it looks like: ``` 0,0,0,0,0 0,N,N,N,0 0,X,0,0,0 ``` At this point return false as your ship has been caught!
games
def check_course(sea): def canPassAround(c, isBottom): for dy in range(- 1, 2): y = c + dy if 0 <= y <= mY: turned, actualX = divmod(y, mX) if isBottom ^ turned % 2: actualX = mX - actualX boat, navy = (ship, y), (actualX, c) dist = sum((a - b) * * 2 for a, b in zip(boat, navy)) * * .5 if dist < 1.42: return False return True mX, mY = len(sea) - 1, len(sea[0]) - 1 ship = next(x for x, r in enumerate(sea) if r[0] == 'X') return all(canPassAround(c, bool(x)) for c in range(mY + 1) for x in (0, mX) if sea[x][c] == 'N')
Escape with your booty!
5b0560ef4e44b721850000e8
[ "Puzzles", "Games", "Matrix", "Simulation" ]
https://www.codewars.com/kata/5b0560ef4e44b721850000e8
5 kyu
Given two times in hours, minutes, and seconds (ie '15:04:24'), add or subtract them. This is a 24 hour clock. Output should be two digits for all numbers: hours, minutes, seconds (ie '04:02:09'). ``` timeMath('01:24:31', '+', '02:16:05') === '03:40:36' timeMath('01:24:31', '-', '02:31:41') === '22:52:50' ```
algorithms
from functools import reduce def f(s): return reduce(lambda a, b: a * 60 + int(b), s . split(":"), 0) def time_math(time1, op, time2): t1, t2 = f(time1), f(time2) n = t1 + t2 if op == '+' else t1 - t2 hr, mn, sc = n / / 3600 % 24, n / / 60 % 60, n % 60 return "%02d:%02d:%02d" % (hr, mn, sc)
Time Math
5aceae374d9fd1266f0000f0
[ "Date Time", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5aceae374d9fd1266f0000f0
6 kyu
<!--Gerrymander Solver--> <img src="https://i.imgur.com/8UQHI9E.jpg"> <p><span style='color:#8df'><b><a href='https://en.wikipedia.org/wiki/Gerrymandering' style='color:#9f9;text-decoration:none'>gerrymander</a></b></span> — <i>noun.</i> the dividing of a state, county, etc., into election districts so as to give one political party a majority in many districts while concentrating the voting strength of the other party into as few districts as possible.</p> <h2 style='color:#f88'>Objective</h2> <p>Given a <code>5 x 5</code> region populated by <code>25</code> citizens, your task is to write a function that divides the region into <code>5</code> districts given the following conditions:</p> <ul> <li><code>10</code> citizens will vote for your candidate, while the other <code>15</code> will vote for the opponent</li> <li>Your candidate must win the popular vote for <code>3</code> of the <code>5</code> districts</li> <li>Each district must have an equal number of voters</li> <li>Each district must be one contiguous cluster of voters (i.e. each voter has one or more orthogonally adjacent neighbors from the same district)</li> </ul> <h2 style='color:#f88'>Concept Overview</h2> <img src='https://i.imgur.com/FxmmO8y.png'> <p><code>A</code>: You're given a <code>5 x 5</code> square matrix representing the layout of the region occupied by eligible voters. The following panels show different ways to set boundaries for <code>5</code> districts.</p> <ul> <li><code>B</code>: Proportionate outcome — blue and red win in proportion to their voting</li> <li><code>C</code>: Disproportionate outcome — blue wins all</li> <li><code>D</code>: <span style='background:#600'>Disproportionate outcome — red wins majority despite having fewer total supporters</span></li> </ul> <p>Your function must solve the challenge presented in panel <code>D</code></p> <h2 style='color:#f88'>Input</h2> <p>Your function will receive a newline-separated string consisting of <code>X</code> and <code>O</code> characters. The <code>O</code>s represent the voters in support of your candidate, and the <code>X</code>s represent those in support of the opponent.</p> <h2 style='color:#f88'>Output</h2> <p>Your function should return a <code>5x5</code> newline-separated string comprised of the digits <code>1</code> through <code>5</code> where each group of identical digits represents its own unique district.</p> <p>If a solution does not exist, return <code>null</code>, <code>None</code>, or <code>nil</code></p> <h2 style='color:#f88'>Test Example</h2> <img src='https://i.imgur.com/EFzVwB7.png'> ```javascript let region = [ 'OOXXX', 'OOXXX', 'OOXXX', 'OOXXX', 'OOXXX' ].join('\n'); // one possible solution where regions 1,2, and 3 are won gerrymander(region); // '11114\n12244\n22244\n35555\n33335' ``` ```python region = [ 'OOXXX', 'OOXXX', 'OOXXX', 'OOXXX', 'OOXXX' ] # one possible solution where regions 1,2, and 3 are won gerrymander('\n'.join(region)) # '11114\n12244\n22244\n35555\n33335' ``` ```java String region = String.join("\n", "OOXXX", "OOXXX", "OOXXX", "OOXXX", "OOXXX" ); // one possible solution where regions 1,2, and 3 are won gerrymander(region); // "11114\n12244\n22244\n35555\n33335" ``` <h2 style='color:#f88'>Testing Constraints</h2> ~~~if:javascript - Full Test Suite: `10` fixed tests and `50` randomly-generated tests ~~~ ~~~if:python - Full Test Suite: `10` fixed tests and `10` randomly-generated tests ~~~ ~~~if:java - Full Test Suite: `15` fixed tests and `100` randomly-generated tests ~~~ ~~~if:cpp - Full Test Suite: `10` fixed tests and `100` randomly-generated tests ~~~ ~~~if:ruby - Full Test Suite: `10` fixed tests and `10` randomly-generated tests ~~~ - Zero or more valid solutions will exist for each test - Inputs will always be valid <p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p>
algorithms
def moves(p): if p < 25 and p % 5 != 4: yield p + 1 if p >= 5: yield p - 5 if p >= 0 and p % 5 != 0: yield p - 1 if p < 20: yield p + 5 def gerrymander(s): so = [1 if c == 'O' else 0 for c in s if c != '\n'] mp = [0] * 25 def dfs(pp, p0, k, ko, n, no): if k == 5: n += 1 if ko >= 3: no += 1 if n == 6: return no >= 3 elif (n != 4 or no > 0) and (n != 5 or no > 1): p = mp . index(0) mp[p] = n if dfs(None, p, 1, so[p], n, no): return True mp[p] = 0 return False for p in moves(p0): if mp[p] == 0: mp[p] = n if dfs(p0, p, k + 1, ko + so[p], n, no): return True mp[p] = 0 return pp is not None and dfs(None, pp, k, ko, n, no) mp[0] = 1 return '\n' . join('' . join(map(str, mp[i: i + 5])) for i in range(0, 25, 5)) \ if dfs(None, 0, 1, so[0], 1, 0) else None
Gerrymander Solver
5a70285ab17101627a000024
[ "Puzzles", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5a70285ab17101627a000024
2 kyu
<!--Four Pass Transport--> <p>The eccentric candy-maker, Billy Bonka, is building a new candy factory to produce his new 4-flavor sugar pops. The candy is made by placing a piece of candy base onto a conveyer belt which transports the candy through four separate processing stations in sequential order. Each station adds another layer of flavor.</p> <p>Due to an error in the factory blueprints, the four stations have been constructed in incorrect locations. It's too costly to disassemble the stations, so you've been called in.</p> <p>Arrange the directional path of the conveyer belt so that it passes through each of the stations in sequential order while also traveling the shortest distance possible.</p> <h2 style='color:#f88'>Input</h2> <p>An array consisting of the locations of each station on the factory floor, in order. The factory floor is a <code>10</code> x <code>10</code> matrix (with <code>0</code> starting index).</p> <h2 style='color:#f88'>Output</h2> <p>Your function should return the path of the conveyer belt as an array.</br> If a valid configuration is not possible, return <code>null</code> or <code>None</code>.</p> <p>The position values in the input and output arrays will consist of integers in the range <code>0 - 99</code>, inclusive. These integers represent a position on the factory floor.</br> For example, the position <code>[0,8]</code> is given as <code>8</code>, and <code>[4,6]</code> is given as <code>46</code></p> <h2 style='color:#f88'>Technical Details</h2> <ul> <li>The conveyer belt must run through each station once and in ascending order</li> <li>The conveyer belt must not intersect/overlap itself</li> <li>The distance covered by the conveyer belt must be the minimum necessary to complete the task</li> <li>Full Test Suite: <code>30</code> fixed tests, <code>100</code> random tests (2000 in java)</li> <li>Inputs will always be valid and each test will have zero or more possible solutions..</li> </ul> <h2 style='color:#f88'>Test Example</h2> <img src="https://i.imgur.com/eAofgDs.png" alt="4 stations"> ```javascript //INPUT - reference image A let stations = [0,65,93,36]; fourPass(stations); //OUTPUT #1 - reference image B // [0, 1, 2, 3, 4, 5, 15, 25, 35, 45, 55, 65, 64, 63, 73, 83, 93, 94, 95, 96, 86, 76, 66, 56, 46, 36] //OUTPUT #2 - reference image C // [0, 10, 20, 30, 40, 50, 60, 61, 62, 63, 64, 65, 75, 85, 84, 83, 93, 94, 95, 96, 86, 76, 66, 56, 46, 36] ``` ```python # INPUT - reference image A stations = [0,65,93,36] four_pass(stations) # OUTPUT #1 - reference image B # [0, 1, 2, 3, 4, 5, 15, 25, 35, 45, 55, 65, 64, 63, 73, 83, 93, 94, 95, 96, 86, 76, 66, 56, 46, 36] # OUTPUT #2 - reference image C # [0, 10, 20, 30, 40, 50, 60, 61, 62, 63, 64, 65, 75, 85, 84, 83, 93, 94, 95, 96, 86, 76, 66, 56, 46, 36] ``` ```java // INPUT - reference image A int[] stations = {0,65,93,36}; new FPT(stations).solve(); // OUTPUT #1 - reference image B // [0, 1, 2, 3, 4, 5, 15, 25, 35, 45, 55, 65, 64, 63, 73, 83, 93, 94, 95, 96, 86, 76, 66, 56, 46, 36] // OUTPUT #2 - reference image C // [0, 10, 20, 30, 40, 50, 60, 61, 62, 63, 64, 65, 75, 85, 84, 83, 93, 94, 95, 96, 86, 76, 66, 56, 46, 36] ``` If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
from itertools import permutations, starmap from heapq import * INF = float("inf") MOVES = (((0, 1), (- 1, 0), (0, - 1), (1, 0)), # Turn anticlockwise ((1, 0), (0, - 1), (- 1, 0), (0, 1))) # Turn clockwise def four_pass(stations): print(stations) def dfs(pOrder, paths, n=0): if n == 3: yield paths[:] else: _, p1, p2 = pOrder[n] for moves in MOVES: path = aStar(p1, p2, board, moves) if path is None: continue paths . append(path) updateBoard(board, path) yield from dfs(pOrder, paths, n + 1) updateBoard(board, path, free=1) paths . pop() pts = [divmod(s, 10) for s in stations] segments = [(i, pts[i], pts[i + 1]) for i in range(3)] MIN = 1 + sum(manhattan(p1, p2) for _, p1, p2 in segments) shortestPath = None for pOrder in permutations(segments): board = [[1] * 10 for _ in range(10)] updateBoard(board, pts) for p in dfs(pOrder, []): length = 4 + sum(map(len, p)) if not shortestPath or length < len(shortestPath): shortestPath = rebuildPath(pOrder, p) if len(shortestPath) == MIN: return shortestPath return shortestPath def manhattan(* args): return sum(abs(b - a) for a, b in zip(* args)) def linearize(p): return 10 * p[0] + p[1] def updateBoard(board, inPath, free=0): for x, y in inPath: board[x][y] = free def rebuildPath(pOrder, shortest): fullPath = [] for (i, p1, p2), path in sorted(zip(pOrder, shortest)): fullPath . append(linearize(p1)) fullPath . extend(map(linearize, path)) fullPath . append(linearize(p2)) return fullPath def aStar(p1, p2, board, moves): prev = [[None] * 10 for _ in range(10)] local = [[(INF, 0) if free else (0, 0) for free in r] for r in board] # (heuristic, rotation index) local[p2[0]][p2[1]] = (INF, 0) # queue: (cost+h, rotation index, cost, (x,y)) q = [(manhattan(p1, p2), 0, 0, p1)] while q and not q[0][- 1] == p2: _, _, cost, src = heappop(q) x, y = src for i, a, b in ((i, x + dx, y + dy) for i, (dx, dy) in enumerate(moves) if 0 <= x + dx < 10 and 0 <= y + dy < 10): pos, nCost = (a, b), cost + 1 if (nCost, i) < local[a][b]: prev[a][b], local[a][b] = src, (nCost, i) heappush(q, (nCost + manhattan(pos, p2), i, nCost, pos)) if q: p, (x, y) = [], q[0][- 1] while 1: x, y = pos = prev[x][y] if pos == p1: break p . append(pos) return p[:: - 1]
Four Pass Transport
5aaa1aa8fd577723a3000049
[ "Puzzles", "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5aaa1aa8fd577723a3000049
1 kyu
<!--Alphametics Solver--> <p><span style='color:#8df'><a href='https://en.wikipedia.org/wiki/Verbal_arithmetic' style='color:#9f9;text-decoration:none'>Alphametics</a></span> is a type of cryptarithm in which a set of words is written down in the form of a long addition sum or some other mathematical problem. The objective is to replace the letters of the alphabet with decimal digits to make a valid arithmetic sum.<br><br> For this kata, your objective is to write a function that accepts an alphametic equation in the form of a single-line string and returns a valid arithmetic equation in the form of a single-line string.</p> <h2 style='color:#f88'>Test Examples</h2> ``` INPUT: "SEND + MORE = MONEY" SOLUTION: "9567 + 1085 = 10652" INPUT: "ELEVEN + NINE + FIVE + FIVE = THIRTY" SOLUTION: "797275 + 5057 + 4027 + 4027 = 810386" ``` <p>Some puzzles may have multiple valid solutions; your function only needs to return one</p> ``` BIG + CAT = LION 403 + 679 = 1082 326 + 954 = 1280 304 + 758 = 1062 ...etc. ``` <h2 style='color:#f88'>Technical Details</h2> <ul> <li>All alphabetic letters in the input will be uppercase</li> <li>Each unique letter may only be assigned to one unique digit</li> <li>As a corollary to the above, there will be a maximum of <code>10</code> unique letters in any given test</li> <li>No leading zeroes</li> <li>The equations will only deal with addition with multiple summands on the left side and one term on the right side</li> <li>The number of summands will range between <code>2</code> and <code>7</code>, inclusive</li> <li>The length of each summand will range from <code>2</code> to <code>8</code> characters, inclusive</li> <li>All test cases will be valid and will have one or more possible solutions</li> <li>Full Test Suite: <code>15</code> fixed tests, <code>21</code> random tests for Python and Ruby / <code>18</code> random tests for JavaScript / <code>28</code> random tests for Go and C# / <code>136</code> random tests for Java / <code>72</code> random tests for Kotlin</li> <li>Optimize your code -- a naive, brute-force algorithm may time out before the first test completes</li> <li>For JavaScript, <code>module</code> and <code>require</code> are disabled, and most prototypes are frozen (except Array and Function)</li> <li>For Python, module imports are prohibited</li> <li><b>Python users:</b> Due to the performance of the Python runner, it is advised to attempt solving this kata in another language besides Python.</li> <li>Use Python 3.6+ for the Python translation</li> </ul> <p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p>
algorithms
from itertools import permutations def alphametics(puzzle, base=10, alphabet='0123456789'): def invalidate(digits, mapping, letter, n): if letter in firsts and n == 0: return True if letter in mapping: return mapping[letter] != n elif n not in digits: return True mapping[letter] = n digits . discard(n) def _substituted_sum(digits, mapping, n, carry=0): n -= 1 u = list({t[n] for t in terms} - set(mapping)) for ds in permutations(digits, len(u)): _digits, _mapping = digits . copy(), mapping . copy() if any(invalidate(_digits, _mapping, letter, n) for letter, n in zip(u, ds)): continue c, r = divmod(sum(_mapping[t[n]] for t in terms) + carry, base) if invalidate(_digits, _mapping, result[n], r): continue if n: yield from _substituted_sum(_digits, _mapping, n, c) elif c == 0: yield _mapping nums = puzzle . replace('=', '+'). split(' + ') firsts = {x[0] for x in nums if len(x) > 1} n = len(nums[- 1]) * terms, result = [t . rjust(n, '_') for t in nums] trans = next(_substituted_sum(set(range(base)), {'_': 0}, n)) return '' . join(alphabet[trans[x]] if x in trans else x for x in puzzle)
Alphametics Solver
5b5fe164b88263ad3d00250b
[ "Puzzles", "Performance", "Cryptography", "Algorithms" ]
https://www.codewars.com/kata/5b5fe164b88263ad3d00250b
3 kyu
We need a system that can learn facts about family relationships, check their consistency and answer queries about them. # The task ~~~if:javascript Create a class `Family` with the following methods. All arguments are strings: names of persons. Upon the first use of a name, that name is added to the family. * `male(name)` and `female(name)` returning `boolean` Define the gender (corresponding to the method name) of the given person. Return `false` when these assignments cannot be made because of conflicts with earlier registered information.<p> * `isMale(name)` and `isFemale(name)` returning `boolean` Return `true` when the person has the said gender. When no gender was assigned, both methods should return `false`<p> * `setParent(childName, parentName)` returning `boolean` Defines the child-parent relationship between two persons. Returns `false` when the relationship cannot be made because of conflicts with earlier registered information.<p> * `getParents(name)` and `getChildren(name)` returning `array` of `string` Return the names of the person's parents/children in alphabetical order<p> ~~~ ~~~if:python Create a class `Family` with the following methods. All arguments are strings: names of persons. Upon the first use of a name, that name is added to the family. * `male(name)` and `female(name)` returning `boolean` Define the gender (corresponding to the method name) of the given person. Return `False` when these assignments cannot be made because of conflicts with earlier registered information.<p> * `is_male(name)` and `is_female(name)` returning `boolean` Return `True` when the person has the said gender. When no gender was assigned, both methods should return `False`<p> * `set_parent_of(child_name, parent_name)` returning `boolean` Defines the child-parent relationship between two persons. Returns `False` when the relationship cannot be made because of conflicts with earlier registered information.<p> * `get_parents_of(name)` and `get_children_of(name)` returning `list` of `string` Return the names of the person's parents/children in alphabetical order<p> ~~~ ~~~if:java Create a class `Family` with the following methods. All arguments are names of persons. Upon the first use of a name, that name is added to the family. * `boolean male(String name)` and `boolean female(String name)` Define the gender (corresponding to the method name) of the given person. Return `false` when these assignments cannot be made because of conflicts with earlier registered information.<p> * `boolean isMale(String name)` and `boolean isFemale(String name)` Return `true` when the person has the said gender. When no gender was assigned, both methods should return `false`<p> * `boolean setParent(String childName, String parentName)` Defines the child-parent relationship between two persons. Returns `false` when the relationship cannot be made because of conflicts with earlier registered information.<p> * `List<String> getParents(String name)` and `List<String> getChildren(String name)` Return the names of the person's parents/children in alphabetical order<p> ~~~ ~~~if:php Create a class `Family` with the following methods. All arguments are names of persons. Upon the first use of a name, that name is added to the family. * `male(string $name): bool` and `female(string $name): bool` Define the gender (corresponding to the method name) of the given person. Return `false` when these assignments cannot be made because of conflicts with earlier registered information.<p> * `isMale(string $name): bool` and `isFemale(string $name): bool` Return `true` when the person has the said gender. When no gender was assigned, both methods should return `false`<p> * `setParent(string $child_name, string $parent_name): bool` Defines the child-parent relationship between two persons. Returns `false` when the relationship cannot be made because of conflicts with earlier registered information.<p> * `getParents(string $name): array` and `getChildren(string $name): array` Return the names of the person's parents/children in alphabetical order<p> ~~~ # Deducing information When things can be implied from given information, it should be done. For instance, a parent's gender can be determined as soon as the other parent's gender becomes known: ```javascript const fam = new Family(); fam.setParentOf("Vera", "George"); fam.setParentOf("Vera", "Vanessa"); fam.female("Vanessa"); fam.female("George"); // false, because: fam.isMale("George"); // ...this is true. ``` ```java Family fam = new Family(); fam.setParentOf("Vera", "George"); fam.setParentOf("Vera", "Vanessa"); fam.female("Vanessa"); fam.female("George"); // false, because: fam.isMale("George"); // ...this is true. ``` ```python fam = Family() fam.set_parent_of("Vera", "George") fam.set_parent_of("Vera", "Vanessa") fam.female("Vanessa") fam.female("George"); # False, because: fam.is_male("George"); # ...this is True. ``` ```php $fam = new Family(); $fam->setParentOf("Vera", "George"); $fam->setParentOf("Vera", "Vanessa"); $fam->female("Vanessa"); $fam->female("George"); // false, because: $fam->isMale("George"); // ...this is true. ``` ~~~if:javascript,java,php Also `setParentOf` can return `false`. For example, if the relationship would infer that one becomes their own ancestor: ~~~ ~~~if:python Also `set_parent_of` can return `False`. For example, if the relationship would infer that one becomes their own ancestor: ~~~ ```javascript fam = new Family(); fam.setParentOf("Vera", "George"); fam.setParentOf("George", "Vera"); // false ``` ```java Family fam = new Family(); fam.setParentOf("Vera", "George"); fam.setParentOf("George", "Vera"); // false ``` ```python fam = Family() fam.set_parent_of("Vera", "George") fam.set_parent_of("George", "Vera") # False ``` ```javascript $fam = new Family(); $fam->setParentOf("Vera", "George"); $fam->setParentOf("George", "Vera"); // false ``` # Details, rules, assumptions Although the task relates to genealogy, the rules of this kata are not claimed to be realistic. Several simplifications and rules apply, which may not hold in real life: - Strings are case sensitive, but there are no tests playing around with "Peter", "PETER" and "PeTeR". - People are uniquely identified by their name. For instance, there are no two different people called "Jim" in the same family. - Once a person has an assigned gender, it cannot be changed. - No gender conclusions should be made from personal names: "Bob" could well be a woman and "Susan" a man. - People cannot have more than one mother and one father. - The terms "parents" and "children" refer to the relatives in the immediate previous/next generations only, not to more remote ancestors or descendants. - Incest may occur, so, for example, one's parent may at the same time be their grandparent. - One cannot be their own ancestor. - Age is not accounted for. Even if some incestuous relationships would infer that one's parent is more than 5 generations older, it should be allowed. - In case a name's first occurrence is in a call of one of the two gender querying methods, the return value will always be false, as that new person does not have a known gender. - In case a name's first occurrence is in a call of one of the two relation querying methods, the return value will always be an empty array/list, as there are no relationships known yet in which that new person participates. - For the reasons in the preceding two bullet points it should not matter whether you actually store that name in these cases in your data structure, or not. In the latter case you would only store it at the next occasion when that name is mentioned in a call of one of the three other methods, that actually *add* information. The described interface has no way to query the difference between these two possible implementations, so you can choose freely. # Example Consider the following family graph: <style> .dot { height: 49px; width: 100px; background-color: #666; border-radius: 50%; border: #aaa 1px solid ; display: flex; align-items: center; justify-content: center; } table.tight { border-spacing: 0px; border-collapse: separate; width: 250px} table.tight td { padding: 0px; min-width: 25px; height: 25px; } .up { border-top: #aaa 1px solid; } .right { border-right: #aaa 1px solid; } .red { color: #ea6 } </style> <table class="tight"> <tr> <td rowspan=2 colspan=4><div class="dot">Dylan (m)</div></td> <td colspan=2></td> <td rowspan=2 colspan=4><div class="dot">Morgan&nbsp;<span class="red">(f)</span></div></td> </tr> <tr> <td class="up right"></td><td class="up"></td> </tr> <tr> <td colspan=4></td> <td class="right"></td><td></td> <td></td><td class="right"></td> </tr> <tr> <td></td><td class="right"></td> <td colspan=3 class="up"></td><td></td> <td></td><td class="right"></td> <td colspan=5 class="up"></td><td class="up right"></td> </tr> <tr> <td colspan=4><div class="dot">Frank (m)</div></td> <td colspan=2></td> <td colspan=4><div class="dot">July</div></td> <td colspan=2></td> <td colspan=4><div class="dot">Jennifer</div></td> </tr> <tr> <td></td><td class="right"></td> <td></td><td></td> <td></td><td></td> <td></td><td></td> <td></td><td></td> <td></td><td></td> <td></td><td></td> <td></td><td></td> </tr> <tr> <td colspan=4><div class="dot">Joy</div></td> </tr> </table> <p> It could be created step by step with the following code — the expected return value for each method call is indicated in comments: ```javascript const fam = new Family(); fam.setParentOf("Frank", "Morgan"); // true fam.setParentOf("Frank", "Dylan"); // true fam.male("Dylan"); // true fam.male("Dylan"); // true, no conflict fam.setParentOf("Joy", "Frank"); // true fam.male("Frank"); // true fam.male("Morgan"); // false // (Morgan is a woman because she both is Frank's parent, but not his father) fam.setParentOf("July", "Morgan"); // true // (The preceding assertion was rejected, so there is no conflict) fam.isMale("Joy") || fam.isFemale("Joy"); // false // (We know Joy is Frank's child, but we can't derive Joy's gender) fam.getChildrenOf("Morgan"); // ["Frank", "July"] fam.setParentOf("Jennifer", "Morgan"); // true fam.getChildrenOf("Morgan"); // ["Frank", "Jennifer", "July"] fam.getChildrenOf("Dylan"); // ["Frank"] // (That is all we know for sure) fam.getParentsOf("Frank"); // ["Dylan", "Morgan"] fam.setParentOf("Morgan", "Frank"); // false // (It is impossible to be the parent of your parent) ``` ```java Family fam = new Family(); fam.setParentOf("Frank", "Morgan"); // true fam.setParentOf("Frank", "Dylan"); // true fam.male("Dylan"); // true fam.male("Dylan"); // true, no conflict fam.setParentOf("Joy", "Frank"); // true fam.male("Frank"); // true fam.male("Morgan"); // false // (Morgan is a woman because she both is Frank's parent, but not his father) fam.setParentOf("July", "Morgan"); // true // (The preceding assertion was rejected, so there is no conflict) fam.isMale("Joy") || fam.isFemale("Joy"); // false // (We know Joy is Frank's child, but we can't derive Joy's gender) fam.getChildrenOf("Morgan"); // Arrays.asList("Frank", "July") fam.setParentOf("Jennifer", "Morgan"); // true fam.getChildrenOf("Morgan"); // Arrays.asList("Frank", "Jennifer", "July") fam.getChildrenOf("Dylan"); // Arrays.asList("Frank") // (That is all we know for sure) fam.getParentsOf("Frank"); // Arrays.asList("Dylan", "Morgan") fam.setParentOf("Morgan", "Frank"); // false // (It is impossible to be the parent of your parent) ``` ```python fam = Family() fam.set_parent_of("Frank", "Morgan") # True fam.set_parent_of("Frank", "Dylan") # True fam.male("Dylan") # True fam.male("Dylan") # True, no conflict fam.set_parent_of("Joy", "Frank") # True fam.male("Frank") # True fam.male("Morgan") # False # (Morgan is a woman because she both is Frank's parent, but not his father) fam.set_parent_of("July", "Morgan") # True # (The preceding assertion was rejected, so there is no conflict) fam.is_male("Joy") or fam.is_female("Joy") # False # (We know Joy is Frank's child, but we can't derive Joy's gender) fam.get_children_of("Morgan") # ["Frank", "July"] fam.set_parent_of("Jennifer", "Morgan") # True fam.get_children_of("Morgan") # ["Frank", "Jennifer", "July"] fam.get_children_of("Dylan") # ["Frank"] # (That is all we know for sure) fam.get_parents_of("Frank") # ["Dylan", "Morgan"] fam.set_parent_of("Morgan", "Frank") # False # (It is impossible to be the parent of your parent) ``` ```php $fam = new Family(); $fam->setParentOf("Frank", "Morgan"); // true $fam->setParentOf("Frank", "Dylan"); // true $fam->male("Dylan"); // true $fam->male("Dylan"); // true, no conflict $fam->setParentOf("Joy", "Frank"); // true $fam->male("Frank"); // true $fam->male("Morgan"); // false // (Morgan is a woman because she both is Frank's parent, but not his father) $fam->setParentOf("July", "Morgan"); // true // (The preceding assertion was rejected, so there is no conflict) $fam->isMale("Joy") || $fam.isFemale("Joy"); // false // (We know Joy is Frank's child, but we can't derive Joy's gender) $fam->getChildrenOf("Morgan"); // ["Frank", "July"] $fam->setParentOf("Jennifer", "Morgan"); // true $fam->getChildrenOf("Morgan"); // ["Frank", "Jennifer", "July"] $fam->getChildrenOf("Dylan"); // ["Frank"] // (That is all we know for sure) $fam->getParentsOf("Frank"); // ["Dylan", "Morgan"] $fam->setParentOf("Morgan", "Frank"); // false // (It is impossible to be the parent of your parent) ``` Have fun!
algorithms
from copy import deepcopy class Person: def __init__(self, name="", gender=None): self . name = name self . gender = gender self . parents = [] self . children = [] class Family: def __init__(self): self . members = {} def male(self, name): if name not in self . members: person = Person(name, gender="male") self . members[name] = person return True if self . members[name]. gender is "female": return False elif self . members[name]. gender is None: self . members[name]. gender = "male" self . deduce() return True def is_male(self, name): return name in self . members and self . members[name]. gender == "male" def female(self, name): if name not in self . members: person = Person(name, gender="female") self . members[name] = person return True if self . members[name]. gender is "male": return False elif self . members[name]. gender is None: self . members[name]. gender = "female" self . deduce() return True def is_female(self, name): return name in self . members and self . members[name]. gender == "female" def set_parent_of(self, child_name, parent_name): if child_name == parent_name: return False if child_name not in self . members: self . members[child_name] = Person(child_name) if parent_name not in self . members: self . members[parent_name] = Person(parent_name) child = self . members[child_name] parent = self . members[parent_name] if parent in child . parents: return True if len(child . parents) > 1 or child_name in self . get_ancestors_of(parent_name): return False elif child . parents: other_parent = child . parents[0] child . parents . append(parent) parent . children . append(child) if not self . test(parent . name): child . parents . pop() parent . children . pop() return False self . deduce() return True def get_children_of(self, name): if name in self . members: names = [child . name for child in self . members[name]. children] names . sort() return names return [] def get_parents_of(self, name): if name in self . members: names = [parent . name for parent in self . members[name]. parents] names . sort() return names return [] def get_ancestors_of(self, name): if name in self . members: me = self . members[name] names = sum([self . get_ancestors_of(p . name) for p in me . parents], [p . name for p in me . parents]) return names return [] def deduce(self): while True: update_count = 0 for member in self . members . values(): if len(member . parents) == 2: p1, p2 = member . parents if p1 . gender is None and p2 . gender is not None: update_count += 1 p1 . gender = "male" if p2 . gender == "female" else "female" elif p2 . gender is None and p1 . gender is not None: update_count += 1 p2 . gender = "male" if p1 . gender == "female" else "female" if not update_count: break def test(self, name, gender="male"): if name not in self . members: return True test_family = deepcopy(self) test_family . deduce() if test_family . members[name]. gender is None: test_family . members[name]. gender = gender test_family . deduce() for member in test_family . members . values(): if len(member . parents) == 2: p1, p2 = member . parents if p1 . gender == p2 . gender and p1 . gender is not None: return False return True
We are Family
5b602842146a2862d9000085
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5b602842146a2862d9000085
4 kyu
# Task Given an array of roots of a polynomial equation, you should reconstruct this equation. ___ ## Output details: * If the power equals `1`, omit it: `x = 0` instead of `x^1 = 0` * If the power equals `0`, omit the `x`: `x - 2 = 0` instead of `x - 2x^0 = 0` * There should be no 2 signs in a row: `x - 1 = 0` instead of `x + -1 = 0` * If the coefficient equals `0`, skip it: `x^2 - 1 = 0` instead of `x^2 + 0x - 1 = 0` * Repeating roots should not be filtered out: `x^2 - 4x + 4 = 0` instead of `x - 2 = 0` * The coefficient before `q^n` is always `1`: `x^n + ... = 0` instead of `Ax^n + ... = 0` ___ ## Example: ``` polynomialize([0]) => "x = 0" polynomialize([1]) => "x - 1 = 0" polynomialize([1, -1]) => "x^2 - 1 = 0" polynomialize([0, 2, 3]) => "x^3 - 5x^2 + 6x = 0" ``` ___ ## Tests: ```python Main suite: Edge cases: (Reference - 4000 ms) (Reference - 30 ms) N of roots | N of tests N of roots | N of tests ----------------------- ----------------------- 1-10 | 100 20-40 | 125 700-750 | 25 2-20 | 125 ``` ```ruby Main suite: Edge cases: (Reference - 4000 ms) (Reference - 20 ms) N of roots | N of tests N of roots | N of tests ----------------------- ----------------------- 1-10 | 100 20-40 | 125 500-550 | 20 2-20 | 125 ``` ```javascript Main suite: Edge cases: (Reference - 4000 ms) (Reference - 20 ms) N of roots | N of tests N of roots | N of tests ----------------------- ----------------------- 1-10 | 100 20-40 | 125 625-675 | 25 2-20 | 125 ```
reference
import re def polynomialize(roots): def deploy(roots): r = - roots[0] if len(roots) == 1: return [r, 1] sub = deploy(roots[1:]) + [0] return [c * r + sub[i - 1] for i, c in enumerate(sub)] coefs = deploy(roots) poly = ' + ' . join(["{}x^{}" . format(c, i) for i, c in enumerate(coefs) if c][:: - 1]) poly = re . sub(r'x\^0|\^1\b|\b1(?=x)(?!x\^0)', '', poly). replace("+ -", "- ") + ' = 0' return poly
Constructing polynomials
5b2d5be2dddf0be5b00000c4
[ "Mathematics", "Performance", "Fundamentals" ]
https://www.codewars.com/kata/5b2d5be2dddf0be5b00000c4
5 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" /> --- <span style="font-weight:bold;font-size:1.5em;color:red">*Blaine is a pain, and that is the truth</span>&nbsp;- Jake Chambers* # <span style='color:orange'>Background</span> Blaine likes to deliberately crash toy trains! ## <span style='color:orange'>*Trains*</span> Trains look like this * `Aaaaaaaaaa` * `bbbB` The engine and carriages use the same character, but because the only engine is uppercase you can tell which way the train is going. Trains can be any alphabetic character * An "Express" train uses `X` * Normal suburban trains are all other letters ## <span style='color:orange'>*Tracks*</span> Track pieces are characters `-` `|` `/` `\` `+` `X` and they can be joined together like this <table> <tr> <td><i>Straights</i> <td width = "20%"> <pre style='background:black'> ---------- </pre> <td width = "20%"> <pre style='background:black'> | | | </pre> <td width = "20%"> <pre style='background:black'> \ \ \ </pre> <td width = "20%"> <pre style='background:black'> / / / </pre> </tr> <tr> <td><i>Corners</i> <td> <pre style='background:black'> | | \----- </pre> <td> <pre style='background:black'> | | -----/ </pre> <td> <pre style='background:black'> /----- | | </pre> <td> <pre style='background:black'> -----\ | | </pre> </tr> <tr> <td><i>Curves</i> <td> <pre style='background:black'> -----\ \----- </pre> <td> <pre style='background:black'> /----- -----/ </pre> <td> <pre style='background:black'> | / / | </pre> <td> <pre style='background:black'> | \ \ | </pre> </tr> <tr> <td rowspan=2><i>Crossings</i> <td> <pre style='background:black'> | ---+--- | </pre> <td> <pre style='background:black'> \ / X / \ </pre> <tr> <td> The <span style='background:black'>&nbsp;&nbsp;+&nbsp;&nbsp;</span> is like a combined <span style='background:black'>&nbsp;&nbsp;-&nbsp;&nbsp;</span> and <span style='background:black'>&nbsp;&nbsp;|&nbsp;&nbsp;</span>, so if those separate curves/corners are valid then the combined crossing is also valid. e.g. <td> <pre style='background:black'> / ---+--- | </pre> <td> <pre style='background:black'> / ---+--- / </pre> <td> <pre style='background:black'> | / /+/ / | </pre></tr> </table> ## <span style='color:orange'>*Describing where a train is on the line*</span> The track "zero position" is defined as the leftmost piece of track of the top row. Other <u>track positions</u> are just distances from this *zero position* (following the line beginning clockwise). A <u>train position</u> is the track position of the train *engine*. ## <span style='color:orange'>*Stations*</span> Train stations are represented by a letter `S`. Stations can be on straight sections of track, or crossings, like this <table> <tr> <td rowspan=2><i>Stations</i> <td width = "20%"> <pre style='background:black'> ----S----- </pre> <td width = "20%"> <pre style='background:black'> | S | </pre> <td width = "20%"> <pre style='background:black'> \ S \ </pre> <td width = "20%"> <pre style='background:black'> / S / </pre> </tr> <tr> <td width = "20%"> <pre style='background:black'> | ----S---- | </pre> <td width = "20%"> <pre style='background:black'> \ / S / \ </pre> </tr> </table> <br/> When a train arrives at a station it stops there for a period of time determined by the length of the train! The time **T** that a train will remain at the station is same as the number of *carriages* it has. For example * `bbbB` - will stop at a station for 3 time units * `Aa` - will stop at a station for 1 time unit Exception to the rule: The "Express" trains never stop at any station. ## <span style='color:orange'>*Collisions*</span> There are lots of ways to crash trains. Here are a few of Blaine's favorites... * *The Chicken-Run* - Train chicken. Maximum impact. * *The T-Bone* - Two trains and one crossing * *The Self-Destruct* - Nobody else to blame here * *The Cabooser* - Run up the tail of a stopped train * *The Kamikaze* - Crash head-on into a stopped train # <span style='color:orange'>Kata Task</span> Blaine has a variety of *continuous loop* train lines. Two trains are then placed onto the line, and both start moving at the same time. How long (how many iterations) before the trains collide? ## <span style='color:orange'>*Input*</span> * `track` - string representation of the entire train line (`\n` separators - maybe jagged, maybe not trailing) * `a` - train A * `aPos` - train A start position * `b` - train B * `bPos` - train B start position * `limit` - how long before Blaine tires of waiting for a crash and gives up ## <span style='color:orange'>*Output*</span> * Return how long before the trains collide, or * Return `-1` if they have not crashed before `limit` time has elapsed, or * Return `0` if the trains were already crashed in their start positions. Blaine is sneaky sometimes. # <span style='color:orange'>Notes</span> Trains * Speed... * All trains (even the "Express" ones) move at the same constant speed of 1 track piece / time unit * Length... * Trains can be any length, but there will always be at least one carriage * Stations... * Suburban trains stop at every station * "Express" trains don't stop at any station * If the start position happens to be at a station then the train leaves at the next move * Directions... * Trains can travel in either direction * A train that looks like `zzzzzZ` is travelling *clockwise* as it passed the track "zero position" * A train that looks like `Zzzzzz` is traveliing *anti-clockwise* as it passes the track "zero position" Tracks * All tracks are single continuous loops * There are no ambiguous corners / junctions in Blaine's track layouts All input is valid # <span style='color:orange'>Example</span> In the following track layout: * The "zero position" is <span style='background:orange'>/</span> * Train A is <span style='background:green'>Aaaa</span> and is at position `147` * Train B is <span style='background:red'>Bbbbbbbbbbb</span> and is at position `288` * There are 3 stations denoted by <span style='background:blue'>S</span> <pre style='background:black'> <span style='background:orange'>/</span>------------\ /-----<span style='background:green'>Aaaa</span>----\ / | | | / <span style='background:blue'>S</span> | | / | | /----+--------------+------\ | \ / | | | | \ | \ | | | | | \-------------+------+--------+---\ | | | | | | \------+------<span style='background:blue'>S</span>-------------+------/ / | | | / | \--------------------+-------------/ | | | /-------------\ | | | | | /-----+----\ | | | | | \ \-------------+--------------+-----<span style='background:blue'>S</span>-------+-----/ \ | | | \ | | | | | \-------------+-------------/ | | \---------<span style='background:red'>Bbbbbbbbbbb</span>--------/ </pre> <br> <hr> Good Luck! DM<br><span style='color:red'>:-)</span>
reference
import re train_crash = lambda * args: BlaimHim(* args). crash() class BlaimHim (object): MOVES = {'/': ([[(0, - 1, '-'), (1, - 1, '/'), (1, 0, '|')], # up-right => down-left: (dx, dy, expected char) [(- 1, 0, '|'), (- 1, 1, '/'), (0, 1, '-')]], # down-left => up-right lambda x, y: x - y <= 0), # matching list index fct (retrun 0 for up-right => down-left, 1 otherwise) '\\': ([[(0, 1, '-'), (1, 1, '\\'), (1, 0, '|')], # up-left => down-right [(- 1, 0, '|'), (- 1, - 1, '\\'), (0, - 1, '-')]], # down-right => up-left lambda x, y: x + y <= 0)} # matching list index fct (retrun 0 for up-right => down-left, 1 otherwise) def __init__(self, track, aTrain, aPos, bTrain, bPos, limit): self . aPos, self . bPos = aPos, bPos self . trackArr = track . split('\n') # Max number of rounds waiting before Blain becomes too much impatient... self . limit = limit # Build the list of Track objects (linear verison of the path) self . tracks = self . trackBuilder() self . trains = [Train(aPos, aTrain, self . tracks), Train( bPos, bTrain, self . tracks)] # Build the trains list def trackBuilder(self): # tracks = list output / toLink: dct of redundant positions tracks, toLink, arr = [], {}, self . trackArr dx, dy, x, y = 0, 1, 0, next(j for j, c in enumerate( arr[0]) if c != ' ') # Initial direction and position x0, y0 = x, y # Store initial position to check the looping in the track while True: c = arr[x][y] # Character at the current position on the track t = Track(x, y, c) # Fresh Track instance to store (if not a crossing) pos = (x, y) # Tuple version of the current position # Reaching those, there will be (could be, for a station) a second pass on the same position... if c in '+XS': if pos in toLink: # If already found, archive the same Track instance at both positions on the linear path t = toLink[pos] else: toLink[pos] = t # Archive... tracks . append(t) # Might need a change of direction reaching those characters: if c in "/\\" and (x != x0 or y != y0): # ...check the chars ahead on the track and choose the right one, then update the direction accordingly dirToCheck, func = self . MOVES[c] dx, dy = next((di, dj) for di, dj, targetChar in dirToCheck[func(dx, dy)] if 0 <= x + di < len(arr) and 0 <= y + dj < len(arr[x + di]) and arr[x + di][y + dj] in targetChar + '+XS') x, y = x + dx, y + dy if x == x0 and y == y0: break # Made a loop, exit... return tracks def crash(self): # print(self.genTrackStr()) # debugging... for rnd in range(self . limit + 1): if (any(t . checkEatItself() for t in self . trains) or self . trains[0]. checkCrashWith(self . trains[1])): return rnd for t in self . trains: t . move() return - 1 # DEBUGGING stuff: generate a printable version of the track, with the trains on it def genTrackStr(self): lst = list(map(list, self . trackArr)) for t in self . trains: # Display both the positions occupied by both trains t . updateOccupy() # Enforce the update to always have a display... well... up to date! for i, tile in enumerate(t . occupy): lst[tile . pos[0]][tile . pos[1]] = ( str . lower if i else str . upper)(t . c) # Handle overlapping display (of different trains only) for tile in self . trains[0]. occupy & self . trains[1]. occupy: lst[tile . pos[0]][tile . pos[1]] = '*' return '\n' . join(map('' . join, lst)) class Train (object): def __init__(self, pos, s, tracks): self . c = s[0]. upper() # Representation of the engine of the train self . delay = 0 # Number of turns to do without moving (at a station) self . dir = (- 1) * * s[0]. isupper() # Moving direction self . isXpress = self . c == 'X' self . len = len(s) # Number of parts, engine included self . pos = pos # Integer: index of the engine in the tracks list # Set of Track instances: all the Track positions that are covered by the train at one moment self . occupy = set() self . tracks = tracks # Reference self . updateOccupy() # Compute self.occupy def checkEatItself(self): return len(self . occupy) != self . len def checkCrashWith(self, other): return bool( self . occupy & other . occupy) def __repr__(self): return "Train({},{},{})" . format( self . c, self . pos, self . delay) # Not actual repr... (used to ease the debugging) def updateOccupy(self): self . occupy = {self . tracks[(self . pos - self . dir * x) % len(self . tracks)] for x in range(self . len)} def move(self): if self . delay: self . delay -= 1 else: # Update the position, making sure that the index stays positive self . pos = (self . pos + self . dir) % len(self . tracks) # Station check self . delay = ( self . tracks[self . pos]. isStation and not self . isXpress) * (self . len - 1) self . updateOccupy() # Update the set of covered tracks class Track (object): def __init__(self, x, y, c): self . pos = (x, y) self . c = c self . isStation = c == 'S' self . linkedTo = None def __repr__(self): return "Track({},{},{})" . format( self . x, self . y, self . c) def __str__(self): return self . c # Behaves like a tuple for hashing def __hash__(self): return hash(self . pos)
Blaine is a pain
59b47ff18bcb77a4d1000076
[ "Fundamentals" ]
https://www.codewars.com/kata/59b47ff18bcb77a4d1000076
2 kyu
*You should be familiar with the "Find the shortest path" problem. But what if moving to a neighboring coordinate counted not as* `1` *step but as* `N` *steps? * ___ **INSTRUCTIONS** Your task is to find the path through the *field* which has the lowest *cost* to go through. As input you will receive: 1) a `toll_map` matrix (as variable `t`) which holds data about how *expensive* it is to go through the given field coordinates 2) a `start` coordinate (tuple) which holds information about your starting position 3) a `finish` coordinate (tuple) which holds information about the position you have to get to As output you should return: 1) the directions list ___ **EXAMPLE** ``` INPUT: toll_map | start | finish | | [ | | [1,9,1], | (0,0) | (0,2) [2,9,1], | | [2,1,1], | | ] | | OUTPUT: ["down", "down", "right", "right", "up", "up"] ``` ___ **CLARIFICATIONS** 1) the `start` and `finish` tuples represent `(row, col)` indices 2) the total *cost* is increased after **leaving** the matrix coordinate, not **entering** it 3) the *field* will be rectangular, not necessarily a square 4) the *field* will always be of correct shape 5) the actual tests will check `total_cost` based on your returned directions list, not the directions themselves, so you shouldn't worry about having multiple possible solutions
algorithms
from heapq import * MOVES = [(1, 0), (0, 1), (0, - 1), (- 1, 0)] BACK = {(1, 0): "down", (0, 1): "right", (0, - 1): "left", (- 1, 0): "up"} DEFAULT = (float("inf"), 0, 0) def cheapest_path(t, start, finish): # heapq structure: (total cost, isEnd, position tuple) lX, lY = len(t), len(t[0]) # seen structure: seen[pos] = (cost, delta x, delta y) q, seen = [(0, 0, start)], {start: (0, 0, 0)} while q and q[0][- 1] != finish: cost, _, pos = heappop(q) x, y = pos for dx, dy in MOVES: xx, yy = nextPos = (x + dx, y + dy) nextCost = cost + t[x][y] if not (0 <= xx < lX and 0 <= yy < lY) or seen . get(nextPos, DEFAULT)[0] <= nextCost: continue seen[nextPos] = (nextCost, dx, dy) heappush(q, (nextCost, nextPos == finish, nextPos)) path, finalCost, pos = [], seen[finish][0], finish while pos != start: _, dx, dy = seen[pos] path . append(BACK[(dx, dy)]) pos = (pos[0] - dx, pos[1] - dy) return path[:: - 1]
Find the cheapest path
5abeaf0fee5c575ff20000e4
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/5abeaf0fee5c575ff20000e4
3 kyu
Your task is to solve <font size="+1">N x M Systems of Linear Equations (LS)</font> and to determine the <b>complete solution space</b>.<br>&nbsp;<br>Normally an endless amount of solutions exist, not only one or none like for N x N. You have to handle <b>N</b> unkowns and <b>M</b> equations (<b>N>=1</b>, <b>M>=1</b>) and your result has to display all numbers in <b>'reduced fraction representation'</b> too (perhaps first you can try my <a href="http://www.codewars.com/kata/solving-linear-equations-n-x-n-gauss-part-1-slash-2" target=_blank>N x N kata</a>). More about LS you can find <a href="https://en.m.wikipedia.org/wiki/System_of_linear_equations" target=_blank><b>here</b></a> or perhaps is already known.<br>&nbsp;<br> <b>First of all two easy examples:</b><br> <li><code>1&#42;x1 + 2&#42;x2 + 0&#42;x3 + 0&#42;x4 = 7</code></li> <li><code>0&#42;x1 + 3&#42;x2 + 4&#42;x3 + 0&#42;x4 = 8</code></li> <li><code>0&#42;x1 + 0&#42;x2 + 5&#42;x3 + 6&#42;x4 = 9</code></li> <br><code>SOL=(97/15; 4/15; 9/5; 0) + q1&#42; (-16/5; 8/5; -6/5; 1)</code><br>&nbsp;<br> You can see the dimension of solution space is 1 (it's a line) and q1 is any real number, so we have endless solutions. You can insert every single solution into every equation and all are correctly solved (1&#42;97/15 + 2&#42;4/15 + 0 + 0 =7 for q1=0).<br>&nbsp;<br> Second example:<br> <li><code>1&#42;x1 + 5/2&#42;x2 + 1/2&#42;x3 + 0&#42;x4 + 4&#42;x5 = 1/8</code></li> <li><code>0&#42;x1 + 5&#42;x2 + 2&#42;x3 - 5/2&#42;x4 + 6&#42;x5 = 2</code></li> <br><code>SOL=(-7/8; 2/5; 0; 0; 0) + q1 &#42; (1/2; -2/5; 1; 0; 0) + q2 &#42; (-5/4; 1/2; 0; 1; 0) + q3 &#42; (-1; -6/5; 0; 0; 1)</code> <br>&nbsp;<br> Here you can see the dimension of the solution is 3, q1, q2 and q3 are arbitrary real numbers. You can see all resulting numbers are in <b>fraction representation</b> (which is easier to read and handle for pupils/students), whatever the input was.<br>&nbsp;<br> <b>So what is missing?</b><br>&nbsp;<br> You have to build a function <code>"Solve(input)"</code> (or <code>"solve(input)"</code>) which takes the equations as an input string and returns the solution as a string. "\n" (LF) separates equations, "&nbsp;" (SPACE) separates the numbers (like <b>3</b> or <b>4/5</b>, only the coefficients not the <b>xi</b>'s), each last number per line is the number behind the &#61; (the equation result, see examples). The result of the function is the solution given as a string. All test examples will be syntactically correct, so you don't need to take care of it. <br>&nbsp;<br>So for the first example you have to call: <code>Solve ("1 2 0 0 7\n0 3 4 0 8\n0 0 5 6 9")</code>. The result of Solve is <code>"SOL=(97/15; 4/15; 9/5; 0) + q1 &#42; (-16/5; 8/5; -6/5; 1)"</code>, exactly in this form/syntax. (97/15; 4/15; 9/5; 0) + q1 &#42; <i>(16/5; -8/5; 6/5; -1)</i> is ok too because it produces same solutions.<br>&nbsp;<br>Spaces in your result are allowed, but not necessary. You have to use '<b>q</b>i' (i from 1 to dimension) standing for the real numbers (the first starting solution- point/vector has no q). If the dimension of the solution is greater than 1, the order of the qi- vectors isn't important (but all indices should be in order, that is, 'q1' first then 'q2', etc.). The fractions have to be <b>reduced as much as possible</b> (but not 4/3 to 1&nbsp;1/3). If there exists no solution you have to respond with <code>"SOL=NONE"</code>. If only one solution exists the response should contain no 'qi'-vectors (e.g.,<code>"SOL=(1; 2; 3)"</code>).<br>&nbsp;<br> <b>One last word to the tests:</b><br> The test function checks the syntax of your output, uses some rules for different verifications and after all checks the given equations with your solution and verifies that all equations are satisfied for arbitrary values of qi's. If all things fit together, your solution is accepted! If not, you will get a hint 'why not'... <br>&nbsp;</br> <b>Hint:</b> don't rely on floating-point numbers to solve this kata. Use exact rational arithmetic. <br>&nbsp;<br> <h2><font color="red">Hope you have fun:-)!</font></h2>
algorithms
from fractions import Fraction import re def gauss(matrix): n, m = len(matrix), len(matrix[0]) - 1 refs = [- 1] * m r = 0 for c in range(m): k = next((i for i in range(r, n) if matrix[i][c] != 0), - 1) if k < 0: continue refs[c] = r row = matrix[k] if r != k: matrix[k], matrix[r] = matrix[r], row for j in range(c + 1, m + 1): row[j] /= row[c] for i in range(n): if i == r: continue row2 = matrix[i] if row2[c] == 0: continue for j in range(c + 1, m + 1): row2[j] -= row2[c] * row[j] r += 1 if r >= n: break if any(matrix[i][m] != 0 for i in range(r, n)): return None sol0 = [0] * m sol = [sol0] for i in range(m): k = refs[i] if k >= 0: sol0[i] = matrix[k][m] else: sol1 = [- matrix[refs[j]][i] if refs[j] >= 0 else 0 for j in range(m)] sol1[i] = 1 sol . append(sol1) return sol def solve(input): matrix = [[Fraction(n) for n in re . split(r'\s+', row)] for row in input . replace(',', '.'). split('\n')] sol = gauss(matrix) if not sol: return 'SOL=NONE' s = ' + ' . join((f'q { i } * ' if i > 0 else '') + '(' + '; ' . join(str(f) for f in x) + ')' for i, x in enumerate(sol)) return 'SOL=' + s
Linear equations N x M, complete solution space, fraction representation
56464cf3f982b2e10d000015
[ "Algorithms", "Linear Algebra", "Algebra", "Mathematics" ]
https://www.codewars.com/kata/56464cf3f982b2e10d000015
2 kyu
You are given a ASCII diagram, comprised of minus signs `-`, plus signs `+`, vertical bars `|` and whitespaces ` `. Your task is to write a function which breaks the diagram in the minimal pieces it is made of. For example, if the input for your function is this diagram: ``` +------------+ | | | | | | +------+-----+ | | | | | | +------+-----+ ``` the returned value should be the list of: ``` +------------+ | | | | | | +------------+ ``` (note how it lost a `+` sign in the extraction) as well as ``` +------+ | | | | +------+ ``` and ``` +-----+ | | | | +-----+ ``` The diagram is given as an ordinary multiline string. There are no borders touching each others. The pieces should not have trailing spaces at the end of the lines. However, it could have leading spaces if the figure is not a rectangle. For instance: ``` +---+ | | +---+ | | | +-------+ ``` However, it is not allowed to use more leading spaces than necessary. It is to say, the first character of some of the lines should be different than a space. Finally, note that only the explicitly closed pieces are considered. Spaces "outside" of the shape are part of the background . Therefore the diagram above has a single piece. Have fun! Note : in C++ you are provided with two utility functions : ```cpp std::string join(const std::string &sep, const std::vector<std::string> &to_join); // Returns the concatenation of all the strings in the vector, separated with sep std::vector<std::string> split_lines(const std::string &to_split); // Splits a string, using separator '\n' ``` ###### _Harder version of the kata available here:_ [_Break the Pieces (evilized edition)_](https://www.codewars.com/kata/break-the-pieces-evilized-edition) =======
algorithms
from typing import List, Tuple import random class FrameCoordinate: def __init__(self, x: int, y: int, adjacency_ops: List[Tuple[int, int]] = [(1, 0), (0, 1), (- 1, 0), (0, - 1)]) - > None: self . x = x self . y = y self . adjacency_ops = adjacency_ops self . cur_op = 0 def __str__(self) - > str: return "(x: {0}, y: {1})" . format(self . x, self . y) def nextAdjacent(self) - > 'FrameCoordinate': if self . cur_op >= len(self . adjacency_ops): return None next_x = self . x + self . adjacency_ops[self . cur_op][0] next_y = self . y + self . adjacency_ops[self . cur_op][1] self . cur_op += 1 return FrameCoordinate(next_x, next_y) def left(self) - > 'FrameCoordinate': return FrameCoordinate(self . x, self . y - 1) def right(self) - > 'FrameCoordinate': return FrameCoordinate(self . x, self . y + 1) def up(self) - > 'FrameCoordinate': return FrameCoordinate(self . x - 1, self . y) def down(self) - > 'FrameCoordinate': return FrameCoordinate(self . x + 1, self . y) def isAdjacent(self, other: 'FrameCoordinate') - > bool: if self . y == other . y: if self . x - 1 == other . x or self . x + 1 == other . x: return True if self . x == other . x: if self . y - 1 == other . y or self . y + 1 == other . y: return True return False def isHorizontalTo(self, other: 'FrameCoordinate') - > bool: return self . x == other . x def isVerticalTo(self, other: 'FrameCoordinate') - > bool: return self . y == other . y class Frame: def __init__(self, initial_frame: str, edges: List[str] = ['-', '|', '+']) - > None: self . frame = initial_frame if self . frame[0] == '\n': self . frame = self . frame[1: len(self . frame)] self . edges = edges self . line_len = - 1 self . fillInWhitespace() def fillInWhitespace(self) - > None: lines = self . frame . split("\n") for i in range(0, len(lines)): line = lines[i] filled_in_line = line if len(line) < self . findLineLength(): filled_in_line += ' ' * (self . findLineLength() - len(line) - 1) lines[i] = filled_in_line self . frame = '\n' . join(lines) def __str__(self) - > str: return self . frame def injectFilling(self, cord: FrameCoordinate, filling: str) - > None: mutable_frame = list(self . frame) filling_pos = self . translateCoordinateToFramePos(cord) if test_debug: print(f"Line length: { self . findLineLength ()} ") print(f"Filling in pos { cord } , resulting frame pos: { filling_pos } ") mutable_frame[filling_pos] = filling self . frame = '' . join([str(char) for char in mutable_frame]) def findLineLength(self) - > int: if self . line_len == - 1: max_len = 0 for line in self . frame . split("\n"): if len(line) > max_len: max_len = len(line) self . line_len = max_len + 1 return self . line_len # + 1 for \n in each line def translateCoordinateToFramePos(self, cord: FrameCoordinate): return cord . x * self . findLineLength() + cord . y def getCharAt(self, cord: FrameCoordinate) - > str: pos = self . translateCoordinateToFramePos(cord) if pos < 0 or pos >= self . len(): return '-' return self . frame[pos] def isEdge(self, cord: FrameCoordinate) - > bool: return self . getCharAt(cord) in self . edges def hasWhiteSpace(self) - > bool: for c in self . frame: if c == ' ': return True return False def isValidCoordinate(self, cord: FrameCoordinate) - > bool: return self . getCharAt(cord) == ' ' def isInBounds(self, cord: FrameCoordinate) - > bool: return 0 <= cord . x < self . numLines() and 0 <= cord . y < (self . findLineLength() - 1) # - 1 for \n def len(self) - > int: return len(self . frame) def numLines(self) - > int: return len(self . frame . split("\n")) def pickRandomCoordinate(self) - > FrameCoordinate: rand_x = random . randrange(0, self . numLines()) rand_y = random . randrange(0, self . findLineLength()) return FrameCoordinate(rand_x, rand_y) def stringPosToCoordinate(self, pos: int) - > FrameCoordinate: line_len = self . findLineLength() # The y substraction is for '\n' if test_debug: print(f"Translating pos: { pos } , line_len: { line_len } ") return FrameCoordinate(pos / / line_len, pos % line_len) def pickRandomWhitespace(self) - > FrameCoordinate: choice = self . frame . find(' ') return self . stringPosToCoordinate(choice) def getPlusCoords(self) - > list: plus_coords = [] for i in range(0, len(self . frame)): if self . frame[i] == '+': plus_coords . append(self . stringPosToCoordinate(i)) return plus_coords class Edge: def __init__(self, cord: FrameCoordinate, char: str) - > None: self . cord = cord self . char = char self . x = cord . x self . y = cord . y def __str__(self) - > str: return "(x: {0}, y: {1}, char: {2})" . format(self . cord . x, self . cord . y, self . char) class Box: def __init__(self, initial_frame: Frame, filling: int) - > None: self . edges = set() self . frames = [initial_frame] self . filling = str(filling) self . isValid = True def addEdge(self, cord: FrameCoordinate, char: str) - > None: self . edges . add(Edge(cord, char)) def __str__(self) - > str: just_x, just_y = self . justify() lines = self . genWhitespaceBox() for edge in self . edges: x = edge . cord . x y = edge . cord . y lines[x][y] = edge . char self . addPluses(lines, just_x, just_y) self . smoothEdges(lines) res = [] for line in lines: res . append(('' . join(line)). rstrip()) return '\n' . join(res) def smoothEdges(self, lines: list) - > None: pluses = self . getPluses(lines) for i in range(0, len(pluses)): for j in range(i + 1, len(pluses)): isHorizontal = pluses[i]. isHorizontalTo(pluses[j]) between_cords = self . between(pluses[i], pluses[j]) valid = True for cord in between_cords: if lines[cord . x][cord . y] == ' ': valid = False if not valid: continue for cord in between_cords: if lines[cord . x][cord . y] == '+' and not self . isIntersection(lines, cord): lines[cord . x][cord . y] = '-' if isHorizontal else '|' def isIntersection(self, lines: list, cord: FrameCoordinate) - > bool: next_cord = cord . nextAdjacent() edges = ['-', '|', '+'] num_edges = 0 while next_cord is not None: if self . isValidCoordinate(next_cord, lines): if lines[next_cord . x][next_cord . y] in edges: num_edges += 1 next_cord = cord . nextAdjacent() return num_edges >= 3 def getPluses(self, lines: list) - > list: pluses = [] for x in range(0, len(lines)): for y in range(0, len(lines[x])): if lines[x][y] == '+': pluses . append(FrameCoordinate(x, y)) return pluses def between(self, first: FrameCoordinate, second: FrameCoordinate) - > list: isVertical = first . isVerticalTo(second) isHorizontal = first . isHorizontalTo(second) if not isVertical and not isHorizontal: # it's diagonal return [] if isVertical and first . x > second . x: tmp = first first = second second = tmp if isHorizontal and first . y > second . y: tmp = first first = second second = first between_cords = [] if isVertical: for x in range(first . x + 1, second . x): between_cords . append(FrameCoordinate(x, first . y)) elif isHorizontal: for y in range(first . y + 1, second . y): between_cords . append(FrameCoordinate(first . x, y)) return between_cords def addPluses(self, lines, just_x: int, just_y: int) - > None: last_frame = self . getLatestFrame() for x in range(0, len(lines)): for y in range(0, len(lines[x])): unjustified_cord = FrameCoordinate(x + just_x, y + just_y) if last_frame . getCharAt(unjustified_cord) == '+' and self . sharesEdges(FrameCoordinate(x, y), 2): lines[x][y] = '+' def sharesEdges(self, cord: FrameCoordinate, num_edges: int) - > bool: shared_edges = 0 for edge in self . edges: if cord . isAdjacent(edge . cord): shared_edges += 1 return shared_edges >= num_edges def getLatestFrame(self) - > Frame: return self . frames[len(self . frames) - 1] def justify(self) - > tuple: min_x, min_y = self . findMin() for edge in self . edges: edge . cord . x -= min_x edge . cord . y -= min_y return (min_x, min_y) def isValidCoordinate(self, side: FrameCoordinate, lines: list) - > bool: return 0 <= side . x < len(lines) and 0 <= side . y < len(lines[side . x]) def findMax(self) - > tuple: max_x = 0 max_y = 0 for edge in self . edges: x = edge . cord . x y = edge . cord . y if x > max_x: max_x = x if y > max_y: max_y = y return (max_x, max_y) def findMin(self) - > tuple: min_x = 9999999 min_y = 9999999 for edge in self . edges: x = edge . cord . x y = edge . cord . y if x < min_x: min_x = x if y < min_y: min_y = y return (min_x, min_y) def genWhitespaceBox(self) - > list: max_x, max_y = self . findMax() res = [] for _ in range(0, max_x + 1): res . append([' '] * (max_y + 1)) return res def dfs(self, start: FrameCoordinate) - > 'Box': frame = self . getLatestFrame() if not frame . isInBounds(start): if test_debug: print(f"Found invalid cord { start } ") self . isValid = False self . filling = 'X' return self elif frame . isEdge(start): self . addEdge(start, frame . getCharAt(start)) return self elif not frame . isValidCoordinate(start): return self if test_debug: print(f"char at: { frame . getCharAt ( start )} ") print("DFSing at cord: {}" . format(start)) print(f"Frame length: { len ( self . frames )} ") tmp = frame . getCharAt(start) frame . injectFilling(start, '@') print(frame) frame . injectFilling(start, tmp) # sleep(0.1) frame . injectFilling(start, self . filling) self . frames . append(frame) next_cord = start . nextAdjacent() while next_cord is not None: self = self . dfs(next_cord) next_cord = start . nextAdjacent() return self def break_pieces(shape): global test_debug test_debug = False board = Frame(shape) boxes = [] filling = 0 print(shape) # print(repr(shape)) while board . hasWhiteSpace(): starting_cord = board . pickRandomWhitespace() box_around_cord = Box(board, filling) box_around_cord = box_around_cord . dfs(starting_cord) if box_around_cord . isValid: boxes . append(box_around_cord) filling = (filling + 1) % 10 ans = [] for box in boxes: str_box = str(box) if test_debug: print(str_box) ans . append(str_box) return ans
Break the pieces
527fde8d24b9309d9b000c4e
[ "Algorithms" ]
https://www.codewars.com/kata/527fde8d24b9309d9b000c4e
2 kyu
Task ======= Given a string representing a quadratic equation, return its roots in either order. 1. The coefficients and constants are [Gaussian Integers](https://en.wikipedia.org/wiki/Gaussian_integer) 2. You might need to rearrange and / or simplify the equation by collecting terms and expanding brackets ___ __Example 1:__ ``` "x^2+2ix+2=-1" ``` ```math x^2 + 2ix + 2 = -1 ``` Moving everything to the left hand side: ```math x^2 + 2ix + 3 = 0 ``` Using the [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula) <br> ```math \frac{- 2i \pm \sqrt{{(2i)}^2 - (4)(1)(3)}}{2(1)} ``` <br> This simplifies to the roots i and -3i so we would return either of these results: ``` [1j, -3j] or [-3j, 1j] ``` <p>&nbsp;</p> __Example 2:__ ``` "ix^2+(3i-3)x+i=2i+3-3x" ``` ```math ix^2+(3i-3)x+i=2i+3-3x ``` Expanding the brackets: ```math ix^2+3ix-3x+i=2i+3-3x ``` Moving everything to the left hand side: ```math ix^2+3ix-i-3=0 ``` Substituting into the quadratic formula: <br> ```math \frac{- 3i \pm \sqrt{{(3i)}^2 - (4)(i)(-i-3)}}{2(i)} ``` <p>&nbsp;</p> This simplifies to the roots to: ``` [(0.45869235757412063-0.7658170483994637j), (-3.4586923575741206+0.7658170483994637j)] ``` So we return these roots in either the given order or the reverse order. ___ The brackets are there to let coefficients of x and x^2 have real and imaginary parts as shown in example 2 and in the example test cases
games
import re def complex_quadratics(eq): eq = re.sub(r'(i|\d|\))(x)', lambda g: g.group(1) + '*' + g.group(2), eq) eq = re.sub(r'(\d|\))(i)', lambda g: g.group(1) + '*' + g.group(2), eq) eq = re.sub(r'(^|\D)(i)', lambda g: g.group(1) + '1' + g.group(2), eq) eq = eq.replace('i', 'j').replace('^', '**') l, r = eq.split('=') eq = f'{l}-({r})' c = eval(eq, {'x': 0j}) b = (eval(eq, {'x': 1+0j}) - eval(eq, {'x': -1+0j})) / 2 a = (eval(eq, {'x': 1+0j}) + eval(eq, {'x': -1+0j})) / 2 - c d = (b*b - 4*a*c) ** 0.5 return [(-b-d)/(2*a), (-b+d)/(2*a)]
Complex Quadratics
66291436acf94b67ea835b0f
[ "Regular Expressions", "Mathematics", "Strings", "Algebra" ]
https://www.codewars.com/kata/66291436acf94b67ea835b0f
5 kyu
You are in charge of a squad of robots in a row. At some time, an order to fire is given to the first of these robots, and your goal is to make sure all of the robots will fire simultaneously. To do that you will have to manage the communication between them, but they are very limited. The robots are basically cells of a 1D cellular automaton that can have different states, and at each time step they will simultaneously transition to a new state. They have no memory and the only thing they know is their own current state and that of their direct neighbours: the next state is a function of those three states. You need to find a finite set of states and transition rules such that all of the robots switch to the firing state on the same time step. All robots follow the same set of rules (edge robots will see missing neighbours as in ```None``` state). Your solution will have to work for any squad of at least one robot, without changing the number of states or the rules. You can choose what type of object will represent these states, as well the initial state (the same for all robots), the state of the first robot after he receives the order to fire, and the firing state. The constants ```INITIAL_STATE```, ```TRIGGER_STATE``` and ````FIRING_STATE```` should contain the objects of your choice to represent those states. The function ```transition_rule``` will be called to update the states of the robots. The arguments ```previous```, ```target```, and ```following``` will repectively be the state of the previous robot in the row, the state of the robot for which next state is computed, and the state of the next robot. When updating the first or last robot, the arguments ```previous``` or ```following``` will be ```None```, respectively. The function should return the updated state for the target robot. To ensure that you use a finite number of states, you will be limited to 50 states — more than enough — and the objects that represent those states should be hashable. This problem is known as the <a href="https://en.wikipedia.org/wiki/Firing_squad_synchronization_problem">Firing squad synchronization problem</a>.
games
INITIAL_STATE = 'L' TRIGGER_STATE = 'G' FIRING_STATE = 'F' rules = { 'A': 'ABCBAF, GCCGC,A A , CC C,ALG ,F G ', 'B': 'BBL G ,ABCBG ,A LLL,C BGCG,GBLB , ', 'C': ' B BBB, CGCG,ABCBC , B BBB,AGCGC , ', 'L': 'LLLCGC,LLLLLL,LLLGAG,LLLACA, LLLLL, L ', 'G': ' GG B , GGGBG, GGAAA, GGFBF,GGG , GGFA '} def transition_rule(prv, tgt, nxt): prv = 'ABCGLX'.index(prv or 'X') nxt = 'ABCGLX'.index(nxt or 'X') rule = rules[tgt] return rule[prv * 7 + nxt]
Firing squad synchronisation
61aba5e564cd720008ed3bf3
[ "Cellular Automata", "Puzzles" ]
https://www.codewars.com/kata/61aba5e564cd720008ed3bf3
5 kyu
In this challenge, you have to create two functions to convert an emoji string to the "emojicode" format, and back. **Emoji strings** consist solely of Unicode emojis, and each of the emojis can be represented with a single Unicode code point. There is no combining characters, variant selectors, joiners, direction modifiers, color modifiers, groups of people, or any other emojis which consist of more than a single code point. **Emojicode** string is a string of space separated code points of Unicode emojis. Every code point is formatted as its **decimal** value, stringified into a sequence of **Unicode emoji keycap digits**. ### Examples The emoji **"SMILING FACE WITH SMILING EYES"** 😊 is encoded as `U+1F60A`. The decimal value of its code point is `128522`. After converting the value to a string and using emoji keycaps for digits, the emojicode is `"1️⃣2️⃣8️⃣5️⃣2️⃣2️⃣"`. The three emojis **SEE-/HEAR-/SPEAK-NO-EVIL MONKEY** are represented by code points `U+1F648`, `U+1F649`, and `U+1F64A`, which are decimal `128584`, `128585` and `128586`, respectively. Therefore, the string `"🙈🙉🙊"` after conversion to emojicode results in `"1️⃣2️⃣8️⃣5️⃣8️⃣4️⃣ 1️⃣2️⃣8️⃣5️⃣8️⃣5️⃣ 1️⃣2️⃣8️⃣5️⃣8️⃣6️⃣"`. ### Tests size At the moment of the writing, Unicode Emoji Standard includes ~1380 emojis which can be represented with a single Unicode code point (see **References** below). Each of these emojis is tested at least once for conversion in both directions, with fixed tests. Additionally, small random tests check 50 strings of 1-5 emojis and 200 strings of 20-50 emojis, for conversion in both directions. ### References [List of Unicode emojis](https://unicode.org/emoji/charts/full-emoji-list.html)
reference
def to_emojicode(emojis): return ' '.join(''.join(d + '️⃣' for d in str(ord(c))) for c in emojis) def to_emojis(emojicode): return ''.join(chr(int(ds.encode('ascii', 'ignore'))) for ds in emojicode.split())
Emojicode
66279e3bcb95174d2f9cf050
[ "Strings", "Unicode" ]
https://www.codewars.com/kata/66279e3bcb95174d2f9cf050
6 kyu
# Background Congratulations! Your next best-selling novel is finally finished. You cut/paste text fragments from your various notes to build the final manuscript. But you sure are a terrible typist! Often you press the "paste" key multiple times by mistake. You'd better fix those errors before sending it off to the publisher. Fortunately, you can code better than you can type. # Kata Task Detect, and correct accidental cut/paste errors in the given text! # Example ### What you did (the spaces in the text are shown below as `_` for more clarity). 1. `Here_is_some` paste 2. `_piece_of_text` paste <span style='color:orange'>x 2</span> 3. `that` paste 4. `_was` paste <span style='color:orange'>x 2</span> 5. `_accidentally` paste 6. `_double` paste <span style='color:orange'>x 4</span> 7. `_pasted.` paste ### The result *Here is some piece of text <span style='color:orange'>piece of text</span> that was <span style='color:orange'>was</span> accidentally double <span style='color:orange'>double double double</span> pasted.* ### The corrected result *Here is some piece of text that was accidentally double pasted.* # Notes * **words** are groups of alphabetic chars * Non-alphabetic chars are considered to be **punctuation** and **spaces** (there is no distinction) * Repeated **letters** within words are not errors -- `address` is not meant to be `adres` * The cutting never breaks words **words** apart * Fragments of only **punctuation** and/or **spaces** are never double-pasted * repeated punctuation is possible -- `Hey!!!` is not meant to be `Hey!` * repeated spaces is possible -- `abc def` is not meant to be `abc def` * Only detect adjacent double pasting. We don't care if the same cut text might be elsewhere * Your code must treat only **first** repetitions as double pastes. * You want to remove the **longest** repetitions of the shortest sequences (e.g. ` double` in the example, not ` double double`)) * Pasting occurs strictly left-to-right only appending to your current text **Here are some trickier examples:** <table> <tr><td>Input<th>Output<td></tr> <tr><td>A_X_<span style='color:orange'>A_X_</span>O_X_<span style='color:orange'>O_X_</span><td>A_X_O_X_<td>Correct (finds the first repeat)</tr> <tr><td>A_X_A_X_O_<span style='color:orange'>X_O_</span>X_<td>A_X_A_X_O_X_X<td>Wrong</tr> <tr><td>A_<span style='color:orange'>A_</span>B_A_<span style='color:orange'>A_</span>B_<td>A_B_A_B_<td>Correct (finds the first repeat, not the bigger one)</tr> <tr><td>A_A_B_<span style='color:orange'>A_A_B_</span><td>A_A_B_<td>Wrong</tr> </table>
reference
import re def fix_cut_paste(x): return re.sub("([^~]*(?<![~])[~](.*?[~])??(?![~])[^~]*)\\1+".replace("~", "A-Za-z"), r'\\1', x)
Cut/Paste errors
5d6ef1abd6dca5002e723923
[ "Fundamentals" ]
https://www.codewars.com/kata/5d6ef1abd6dca5002e723923
5 kyu
# Overview In this Kata you will be looking at the runs scored by a team in an innings of a game of cricket. <img src="https://i.imgur.com/OBJ6zAQ.png" title="cricket" /> # Rules The rules of <a href="https://en.wikipedia.org/wiki/Cricket">cricket</a> are much too complex to describe here. Some basic things that you need to know for this Kata are: * In cricket, balls are bowled in sets of 6 (overs) * Each over is bowled from a different end of the pitch * There are 2 batsmen on the field at all times (one of them is facing the bowler) * A batsman scores as follows: * score `1` run by hitting the ball and running to other end of the pitch (crossing with partner) * score `2` runs by hitting the ball and running to other end of the pitch and back (crossing twice with partner) * score `3` runs by hitting the ball and running to other end of the pitch and back and back to other end again (crossing three times with partner) * score `4` runs by hitting the ball to the boundary. Batsmen do not change ends. * score `6` runs by hitting the ball over the boundary. Batsmen do not change ends. * When a batsman is "out" (e.g. bowled, stumped, caught, ...) then the next order batsman will take his position * the non-facing batsman at the other end just stays where he is * There are 11 players in a team so the innings finishs when the 10th batsman is out (because there must be 2 batsmen on the field at all times) Confused yet? If none of that made any sense then cricket is not your game, so it is probably best to skip this Kata ... # Scoring Notation * `.` = a dot ball. The batsman faced a ball, but no run was made * `1`, `2`, `3`, `4`, `6` = number of runs made of the ball bowled * `w` = wicket taken. The batsman is "out" and no run is made. # Kata Task Somebody has kindly recorded the result of every ball bowled, but they did not record who scored what. With knowledge of the batting order, your task is to return a simple score card which shows the runs acheived by each batsman. ## Input * `balls` = string of result of all balls bowled so far * e.g. `..12...2...6.....4....2.1.1.1.1..w..61...` * This may be a full innnings (e.g. 10 wickets taken) or just a partial innings * `batsmen` = list of 11 batmen's names in batting order (the order that they go to the field) * The batsman who faces the first ball bowled is first in this list ## Output * A string showing the batsmen names (in batting order) and runs they made (runs are in a 3-digit field) * If batsman has not entered the field yet then say `-` * If batsman is not out then say `not out` * a team `TOTAL` number of runs is shown * All lines except last have a trailing newline `\n` # Example Here is an example showing the format you are required to return ``` A 105 B 37 C 12 D 24 E 9 F 27 not out G 29 not out H - I - J - K - TOTAL 243 ``` # Notes * Scoring `5` off one ball is rare in reality and will not happen in this Kata. * All balls are considered good. There are no "extras" in this Kata. * In this Kata batsmen are only "bowled" out, not caught - this eliminates any possibility of batsmen "crossing" while the ball is in the air. * Batsmen names are unique. For convenience in this Kata their names are just `A`, `B`, `C` .... `K` * All input data is valid - no need to check it.
algorithms
def score_card(balls, batsmen): scores = [0 for _ in range(len(batsmen))] b1, b2, nextIn, tot = 1, 0, 2, 0 # b1,b2 = indexes of the batsmen in the field # b1: side 1, b2: side 2 (reversed when declared because swapped right at the beginning of the game) for i,r in enumerate(balls): if not i%6: b1,b2 = b2,b1 # swap when new over if r == 'w': b1, nextIn = nextIn, nextIn+1 # batman out, new one in the field elif r.isdigit(): # run boys, run! r = int(r) scores[b1] += r tot += r if r%2: b1,b2 = b2,b1 return ' '.join( "{}{: >4}{}".format(batsmen[i], s if i < nextIn else '-', " not out"*(i in (b1,b2)) ) for i,s in enumerate(scores) ) + " TOTAL {}".format(tot)
Cricket Scores
5a5ed3d1e626c5140f00000e
[ "Algorithms" ]
https://www.codewars.com/kata/5a5ed3d1e626c5140f00000e
5 kyu
You're an elevator. People on each floor get on you in the order they are queued as long as you're stopped on their floor. Your doors are one-person wide. No one can board you when someone else is departing or vice versa. You must **stop** at each floor you pass that you can drop off and/or pick up passengers. Conversely, you don't stop if you're not changing passengers. You can't switch directions while holding passengers. People won't get on you if you're not going in the direction they want to go. During a stop, all passengers who can get off gets off BEFORE any new passengers could get on. When you're empty (at any point), you must go TOWARD the next person in the queue, taking anyone going in that direction along your path if you're capable. When you're empty AND you're on the same floor as the next person in the queue, you must now go in the direction they want to go. You must **stop** to open your doors, even if you haven't moved a floor. You begin each day with closed doors. Up to 5 people can be on you at a time. Given a `starting_floor` and a `queue` of people represented by `from` the floor they're on `to` the floor they want to go, return the order of stops you will take this day. ---- ## Example Given this `queue`: ```clojure (def queue [ { :from 3 :to 2 } ;; Al { :from 5 :to 2 } ;; Betty { :from 2 :to 1 } ;; Charles { :from 2 :to 5 } ;; Dan { :from 4 :to 3 } ;; Ed ]) ``` ```go queue := []Person{ {From: 3, To: 2}, // Al {From: 5, To: 2}, // Betty {From: 2, To: 1}, // Charles {From: 2, To: 5}, // Dan {From: 4, To: 3}, // Ed } ``` ```javascript const queue = [ { from: 3, to: 2 }, // Al { from: 5, to: 2 }, // Betty { from: 2, to: 1 }, // Charles { from: 2, to: 5 }, // Dan { from: 4, to: 3 }, // Ed ]; ``` ```python queue = [ { "from": 3, "to": 2 }, # Al { "from": 5, "to": 2 }, # Betty { "from": 2, "to": 1 }, # Charles { "from": 2, "to": 5 }, # Dan { "from": 4, "to": 3 }, # Ed ] ``` ```ruby queue = [ { from: 3, to: 2 }, # Al { from: 5, to: 2 }, # Betty { from: 2, to: 1 }, # Charles { from: 2, to: 5 }, # Dan { from: 4, to: 3 }, # Ed ] ``` then ```clojure (def starting-floor 1) (order starting-floor queue) ``` ```go startingFloor := 1 Order(startingFloor, queue) ``` ```javascript const startingFloor = 1; order(startingFloor, queue); ``` ```python starting_floor = 1 order(starting_floor, queue) ``` ```ruby starting_floor = 1 order(starting_floor, queue) ``` should return: ```clojure [2 5 4 3 2 1] ``` ```go []int{2, 5, 4, 3, 2, 1} ``` ```ruby [2, 5, 4, 3, 2, 1] ``` ```python [2, 5, 4, 3, 2, 1] ``` ```javascript [2, 5, 4, 3, 2, 1] ``` ### Explanation You start on floor 1. Al is the first to queue for the elevator so you make your way toward him traveling **UP**. Going up a floor, you notice Charles and Dan on floor 2, however only Dan wants to go up so your first stop is `2` to pick up Dan. Going up to floor 3, you have now reached Al, but unfortunately for him, he wants to go down, and you can't switch directions until you drop off Dan. You promise to get Al later, so you pass him for now. With no one else going up on your path, your second stop is `5` to drop off Dan. Now that you're empty, you move toward Al again who is now below you. Since you begin traveling **DOWN**, Betty, who's also on floor 5, joins you. You stop on `4` to pick up Ed who is also going down. You stop on `3` to drop off Ed. Meanwhile, you finally pick up Al. You stop on `2` to drop off Al and Betty. You finally pick up Charles. You stop on `1` to drop off Charles, the last person to transport. --- # Final Note The building you operate in may have ANY arbitrarily large number of stories (or basements) that people will want to travel between. For a given day, you should not expect more than 500 people to ride you.
games
def order(level, queue): cargo = [] visited_floors = [] capacity = 5 direction = None cmp = lambda a, b: (a > b) - (a < b) # Each loop is a stop counting the starting level. # Note, we don't mark the first stop if there's no one to pick up. while cargo or queue: # Drop off cargo_length = len(cargo) cargo = [person for person in cargo if person['to'] != level] dropoff = cargo_length != len(cargo) # If empty, reset direction according to first in queue if queue and not cargo: direction = cmp(level, queue[0]['from']) or cmp(queue[0]['from'], queue[0]['to']) # Pickup (must be going in the same direction) queue_length = len(queue) queue = [ person for person in queue if not ( level == person['from'] and cmp(person['from'], person['to']) == direction and len(cargo) < capacity and not cargo.append(person) )] pickup = queue_length != len(queue) # Mark stop if pickup or dropoff: visited_floors.append(level) # Move to the floor of the next pickup or dropoff candidate_floors = [person['to'] for person in cargo] if len(cargo) < capacity: candidate_floors.extend( person['from'] for person in queue if cmp(person['from'], person['to']) == cmp(level, person['from']) == direction or not cargo and person == queue[0] ) if candidate_floors: level = min(candidate_floors, key=lambda p: abs(p - level)) return visited_floors
Elevator Action!
654cdf611d68c91228af27f1
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/654cdf611d68c91228af27f1
4 kyu
Zeckendorf's Theorem<sup>[[wiki]](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem)</sup> states that every positive integer can be represented uniquely as the sum of one or more distinct Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers. This representation can be used for Fibonacci Coding<sup>[[wiki]](https://en.wikipedia.org/wiki/Fibonacci_coding)</sup> of positive integers. The representation and encoding can be extended to use NegaFibonacci numbers<sup>[[wiki]](https://en.wikipedia.org/wiki/NegaFibonacci_coding)</sup>, which would allow us to encode negative numbers as well as positive numbers. `0` Can be represented, but not encoded; this kata will therefore use the representation and not the encoding for its expected value. # Task Define a function that accepts an integer and returns its representation as an array of zero (!) or more non-consecutive NegaFibonacci integers, sorted descending by absolute value. # Examples ```haskell repr 0 -> [] repr 1 -> [1] repr 4 -> [5,-1] repr (-17) -> [-21,5,-1] repr 64 -> [89,-21,-3,-1] ``` ```javascript repr(0) => [] repr(1) => [1] repr(4) => [5,-1] repr(-17) => [-21,5,-1] repr(64) => [89,-21,-3,-1] ``` ```python negative_fibonacci_representation(0) => [] negative_fibonacci_representation(1) => [1] negative_fibonacci_representation(4) => [5,-1] negative_fibonacci_representation(-17) => [-21,5,-1] negative_fibonacci_representation(64) => [89,-21,-3,-1] ``` # Notes * The formula that generates the Fibonacci numbers in one direction also generates the NegaFibonacci numbers in the other direction. The first 12 terms are given in the Example tests, but you'll need more. * This is not intended to be a performance kata, but there will be ~3000 tests over the full range of `Int` ( Python: `abs(n) <= 2^64` ). Your naive Fibonacci implementation _will_ bomb. :] * I take no responsibility for the content of external resources.
algorithms
def negative_fibonacci_representation(n): fibs = [1, -1] sums, res = fibs[:], [] while abs(sums[n < 0]) < abs(n): x = fibs[-2] - fibs[-1] sums[x < 0] += x fibs.append(x) while fibs: x = fibs.pop() sums[x < 0] -= x if abs(sums[n < 0]) < abs(n): n -= x res.append(x) return res
NegaFibonacci representation
5c880b6fc249640012f74cd5
[ "Number Theory", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5c880b6fc249640012f74cd5
5 kyu
<!-- Blobservation 2: Merge Inert Blobs --> <h2 style='color:#f88'>Overview</h2> <p>You have an <code>m</code> x <code>n</code> rectangular matrix (grid) where each index is occupied by a blob.<br/> Each blob is given a positive integer value; let's say it represents its mass.<br/> Each blob is immobile on its own, but when the terrain is tilted downward toward a cardinal direction, all blobs will roll toward that direction.<br/> The grid is a closed environment, so the blobs are confined within the boundaries of the grid.</p> <h2 style='color:#f88'>Objective</h2> <p>You will write a class <code>Blobservation</code>. The class will be given a matrix of positive integers to create an instance. The class should also include two methods: <code>read</code> and <code>state</code>.<br/> The <code>read</code> method will take a string of directions (N,W,S,E representing their respective cardinal directions). This provides the sequence of directional tilts to the grid.<br/> The <code>state</code> method should return the current state of the grid in as small a rectangular matrix as possible. In this grid, empty spaces should be filled with <code>0</code>.</p> <h3 style='color:#8df'>Blob Movement</h3> <p>The grid can tilt in any of the four cardinal directions (ie. north, east, south, west). When tilted, all blobs on the grid will roll in the tilted direction until blocked by another blob or the grid's boundary.</p> <h3 style='color:#8df'>Blob Consumption</h3> <ul> <li><span style='color:#6ed'>If a smaller rolling blob collides with a larger blob, the larger blob will absorb the smaller one only if the smaller one is moving <b><u>toward</u></b> the larger. Otherwise, the blobs simply end up next to each other.</span><br/> In our test example below, during the first read ("E" for east), the <code>6</code> blob in the top row absorbs the <code>4</code> blob on its left, but the <code>9</code> blob in the top left does not absorb the <code>4</code> blob.</li> <li><span style='color:#6ed'>When blobs are consumed in a given move (tilt), all merging occurs concurrently.</span> During the first tilt in our test example below, the blobs in the bottom row merge into one; the "9" absorbs the "6" while the "6" absorbs the "3", resulting in the "18".</li> <li><span style='color:#6ed'>Zeroes are empty spaces between blobs and will have no effect on merges; treat them like they don't exist.</span><br/> Let's say you have the grid: <code>[ [4,0,0,6,0,8] ]</code><br/> If we read the direction "E", we get the following when we call the <code>state</code> method: <code>[ [18] ]</code>.</li> </ul> <h2 style='color:#f88'>Test Example</h2> <pre><code>Below is pseudocode; refer to the initial test setup for your language grid = [ [9,4,6], [8,8,8], [3,6,9] ] <span style='color:#dd9966'>Let's create an instance:</span> blobs = Blobservation(grid) <span style='color:#dd9966'>Then let's call the 'read' method with a string:</span> blobs.read("E") <span style='color:#dd9966'>Now we'll call the 'state' method...</span> blobs.state() <span style='color:#dd9966'>...which should return a matrix like below:</span> [ [0,9,10], [8,8,8], [0,0,18] ] <span style='color:#dd9966'>Now let's read some more directions and print the state with each read:</span> blobs.read("S") blobs.state() == [ [0,9,10], [8,8,26] ] blobs.read("EN") blobs.state() == [ [8,19], [0,34], ] </code></pre> <h2 style='color:#f88'>Test Specifications</h2> <ul> <li>All inputs will be valid</li> <li>Matrix dimensions will range anywhere between 2 x 2 and 50 x 50, inclusive</li> <li><strong>Full Test Suite:</strong> <code>8</code> fixed tests and <code>100</code> random tests</li> <li>For JavaScript, <code>module</code> and <code>require</code> are disabled and <code>Object</code> and <code>Object.prototype</code> are frozen</li> </ul> <p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p>
algorithms
class Blobservation: @staticmethod def _move(L): tmp, res = [L[0]], [] for x in L[1:]: if x == 0: continue if tmp[-1] < x: tmp.append(x) else: res.append(sum(tmp)) tmp = [x] res.append(sum(tmp)) return tuple(res) def __init__(self, matrix): self._matrix = matrix def read(self, instructions): for c in instructions: if c == 'E': res = [Blobservation._move(row) for row in self._matrix] size = max(map(len, res)) self._matrix = tuple((0,)*(size-len(row)) + row for row in res) elif c == 'W': res = [Blobservation._move(row[::-1]) for row in self._matrix] size = max(map(len, res)) self._matrix = tuple(row[::-1] + (0,)*(size-len(row)) for row in res) elif c == 'S': res = [Blobservation._move(col) for col in zip(*self._matrix)] size = max(map(len, res)) self._matrix = tuple(zip(*((0,)*(size-len(col)) + col for col in res))) elif c == 'N': res = [Blobservation._move(col[::-1]) for col in zip(*self._matrix)] size = max(map(len, res)) self._matrix = tuple(zip(*(col[::-1] + (0,)*(size-len(col)) for col in res))) def state(self): return self._matrix
Blobservation 2: Merge Inert Blobs
5f8fb3c06c8f520032c1e091
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5f8fb3c06c8f520032c1e091
5 kyu
# <span style='color:orange'>Background</span> It is the middle of the night. You are jet-lagged from your long cartesian plane trip, and find yourself in a rental car office in an unfamiliar city. You have no idea how to get to your hotel. Oh, and it's raining. Could you be any more miserable? But the friendly rental-car dude behind the desk says not to worry! He kindly pre-programs the car **Sat Nav** system with your destination. He smiles and assures you that the device works OK. What excellent service! What a nice man! Maybe things are not so bad after all. Then he sniggers... # <span style='color:orange'>City streets</span> The city extends as far as the eye can see in all directions, and is laid out as a giant grid where all blocks are `1km` across. Notice that [x,y] coordinates are described with units of `100m` <img src="https://i.imgur.com/6MFbhPO.png" title="satnav city streets" /> # <span style='color:orange'>Kata task</span> Your starting point is `[0,0]` Simply follow the Sat Nav directions! When you arrive at the destination return the final [x,y] coordinates. # <span style='color:orange'>Sat Nav directions</span> The device gives directions as text messages: <span style='color:red'>*The first message*</span> * `Head <NORTH,EAST,SOUTH,WEST>` <span style='color:red'>*The en-route messages*</span> * `Take the <NEXT,2nd,3rd,4th,5th> <LEFT,RIGHT>` * `Go straight on for <100,200,300,...,900>m` * `Go straight on for <1.0,1.1,1.2,...,5.0>km` * `Turn around!` <span style='color:red'>*The last message*</span> * `You have reached your destination!` <span style='color:orange'>NOTES</span> * First and last messages are always present * There may be any number of *en-route* messages * Messages are always formatted corrrectly * A `NEXT` turn message means you must to proceed to the *next* cross-street even if you are currently at an intersection * But `Turn around` does not need to be done at an intersection. Just do a U-turn wherever you are! <br/><br/> <span style='color:gray'>Good Luck!<br/>DM</span>
reference
import re N,S,E,W = "NORTH", "SOUTH", "EAST", "WEST" DIRS = {N: (0,1), S:(0,-1), E: (1,0), W:(-1,0)} TURNS = {"LEFT": { DIRS[N]: DIRS[W], DIRS[S]: DIRS[E], DIRS[E]: DIRS[N], DIRS[W]: DIRS[S]}, "RIGHT": { DIRS[N]: DIRS[E], DIRS[S]: DIRS[W], DIRS[E]: DIRS[S], DIRS[W]: DIRS[N]} } PATTERN = re.compile( r"Head (?P<head>\w+)" + r"|Take the (?P<nTurn>\d*)(?P<isNext>\w+) (?P<turnTo>LEFT|RIGHT)" + r"|Go straight on for (?P<straight>[\d.]+)(?P<unit>k?m)" + r"|(?P<flip>Turn around!)") def sat_nav(directions): def go(d): return x+d*moves[0], y+d*moves[1] x,y, moves = 0,0, (0,0) for i in range(len(directions)-1): d, m = 0, PATTERN.match(directions[i]) if m.group('straight'): # Move forward without rounding d = round(10 * float(m.group('straight'))) if m.group('unit') == 'm': d //= 1000 # Convert "were metters" to hectometers x,y = go(d) # Move elif m.group('turnTo'): # Take next turn: d = 10 * (m.group('isNext') == 'NEXT' or int(m.group('nTurn'))) # will move one complete block forward... x,y = (z - z%(10 if dz > 0 else -10) for z,dz in zip(go(d), moves)) # ...cut the exceeding part (changing the sign of the mod argument handle the direction, thanks to python...!) moves = TURNS[m.group('turnTo')][moves] elif m.group('flip'): moves = -moves[0], -moves[1] # Turn around, in place elif m.group('head'): moves = DIRS[m.group('head')] # Initial direction return [x,y]
Sat Nav directions
5a9b4d104a6b341b42000070
[ "Fundamentals" ]
https://www.codewars.com/kata/5a9b4d104a6b341b42000070
5 kyu
<center> <div style="float:left;width:45%;" > <svg width="301" height="201"> <rect x="0" y="0" width="301" height="201" style="fill:rgb(64,64,64); stroke-width:0" /> <rect x="75" y="75" width="150" height="25" style="fill:rgb(192,192,192); stroke-width:0" /> <rect x="75" y="100" width="50" height="25" style="fill:rgb(192,192,192); stroke-width:0" /> <rect x="75" y="125" width="100" height="25" style="fill:rgb(192,192,192); stroke-width:0" /> <line x1="0" y1="0" x2="301" y2="0" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="25" x2="301" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="50" x2="301" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="75" x2="301" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="100" x2="301" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="125" x2="301" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="150" x2="301" y2="150" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="175" x2="301" y2="175" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="200" x2="301" y2="200" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="0" x2="0" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="25" y1="0" x2="25" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="50" y1="0" x2="50" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="75" y1="0" x2="75" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="100" y1="0" x2="100" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="125" y1="0" x2="125" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="150" y1="0" x2="150" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="175" y1="0" x2="175" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="200" y1="0" x2="200" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="225" y1="0" x2="225" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="250" y1="0" x2="250" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="275" y1="0" x2="275" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="300" y1="0" x2="300" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="55" y1="62" x2="70" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="80" y1="62" x2="95" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="105" y1="62" x2="120" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="130" y1="62" x2="145" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="155" y1="62" x2="170" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="180" y1="62" x2="195" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="205" y1="62" x2="220" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="230" y1="62" x2="245" y2="62" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="130" y1="112" x2="145" y2="112" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="155" y1="112" x2="170" y2="112" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="180" y1="112" x2="195" y2="112" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="205" y1="112" x2="220" y2="112" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="230" y1="112" x2="245" y2="112" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="55" y1="162" x2="70" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="80" y1="162" x2="95" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="105" y1="162" x2="120" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="130" y1="162" x2="145" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="155" y1="162" x2="170" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="180" y1="162" x2="195" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="62" y1="55" x2="62" y2="70" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="62" y1="80" x2="62" y2="95" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="62" y1="105" x2="62" y2="120" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="62" y1="130" x2="62" y2="145" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="62" y1="155" x2="62" y2="170" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="137" y1="105" x2="137" y2="120" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="187" y1="105" x2="187" y2="120" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="187" y1="130" x2="187" y2="145" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="187" y1="155" x2="187" y2="170" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="237" y1="55" x2="237" y2="70" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="237" y1="80" x2="237" y2="95" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="237" y1="105" x2="237" y2="120" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> </svg>  </div></center> <center> <svg width="301" height="201"> <rect x="0" y="0" width="301" height="201" style="fill:rgb(64,64,64); stroke-width:0" /> <rect x="100" y="50" width="100" height="100" style="fill:rgb(192,192,192); stroke-width:0" /> <rect x="125" y="75" width="50" height="50" style="fill:rgb(64,64,64); stroke-width:0" /> <line x1="0" y1="0" x2="301" y2="0" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="25" x2="301" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="50" x2="301" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="75" x2="301" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="100" x2="301" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="125" x2="301" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="150" x2="301" y2="150" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="175" x2="301" y2="175" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="200" x2="301" y2="200" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="0" y1="0" x2="0" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="25" y1="0" x2="25" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="50" y1="0" x2="50" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="75" y1="0" x2="75" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="100" y1="0" x2="100" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="125" y1="0" x2="125" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="150" y1="0" x2="150" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="175" y1="0" x2="175" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="200" y1="0" x2="200" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="225" y1="0" x2="225" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="250" y1="0" x2="250" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="275" y1="0" x2="275" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="300" y1="0" x2="300" y2="201" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="80" y1="37" x2="95" y2="37" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="105" y1="37" x2="120" y2="37" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="130" y1="37" x2="145" y2="37" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="155" y1="37" x2="170" y2="37" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="180" y1="37" x2="195" y2="37" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="205" y1="37" x2="220" y2="37" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="80" y1="162" x2="95" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="105" y1="162" x2="120" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="130" y1="162" x2="145" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="155" y1="162" x2="170" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="180" y1="162" x2="195" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line x1="205" y1="162" x2="220" y2="162" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="30" x1="87" y2="45" x2="87" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="55 " x1="87" y2="70" x2="87" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="80" x1="87" y2="95" x2="87" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="105" x1="87" y2="120" x2="87" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="130" x1="87" y2="145" x2="87" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="155" x1="87" y2="170" x2="87" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="30" x1="212" y2="45" x2="212" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="55 " x1="212" y2="70" x2="212" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="80" x1="212" y2="95" x2="212" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="105" x1="212" y2="120" x2="212" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="130" x1="212" y2="145" x2="212" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> <line y1="155" x1="212" y2="170" x2="212" style="stroke:rgb(255,0,0);stroke-width:4;stroke-linecap:round" /> </svg> </center> ## <span style="color:#0ae">Task</span> Create a function that takes a shape (set of unit squares) and returns the borders of the shape as a multiline string (using `'+'`,`'-'`,`'|'`). ### <span style="color:#0ae">Input</span> - **`shape`** *[set of tuples (int, int)]* The shape is a plane geometric figure formed by joining one or more unit squares edge to edge or corner to corner. The `shape` parameter contains the `(x,y)` coordinates of the unit squares that form the shape. `x` axis is horizontal and oriented to the right, `y` axis is vertical and oriented upwards. ##### Examples A set with one element (e.g. `{(1,1)}`, `{(7,11)}` or `{(50,35)}`) represents a square whose sides have length 1. A set with two elements with the same `y` coord and consecutive `x` coord (e.g. `{(1,1),(2,1)}` or `{(7,5),(8,5)}`) is a rectangle, width: 2, height: 1. A set with two elements with the same `x` coord and consecutive `y` coord (e.g. `{(1,1),(1,2)}` or `{(7,5),(7,6)}`) is a rectangle, width: 1, height: 2. <svg width="600" height="180"> <rect x="0" y="0" width="600" height="180" style="fill:rgb(48,48,48); stroke-width:0" /> <rect x="50" y="75" width="50" height="25" style="fill:rgb(192,192,192); stroke-width:0" /> <line x1="10" y1="25" x2="140" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="50" x2="140" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="75" x2="140" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="100" x2="140" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="125" x2="140" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="25" y1="10" x2="25" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="50" y1="10" x2="50" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="75" y1="10" x2="75" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="100" y1="10" x2="100" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="125" y1="10" x2="125" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <text x="28" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,0</text> <text x="53" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,0</text> <text x="78" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,0</text> <text x="103" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,0</text> <text x="28" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,1</text> <text x="53" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">1,1</text> <text x="78" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">2,1</text> <text x="103" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,1</text> <text x="28" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,2</text> <text x="53" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,2</text> <text x="78" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,2</text> <text x="103" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,2</text> <text x="28" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,3</text> <text x="53" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,3</text> <text x="78" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,3</text> <text x="103" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,3</text> <rect x="225" y="50" width="25" height="50" style="fill:rgb(192,192,192); stroke-width:0" /> <line x1="185" y1="25" x2="315" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="50" x2="315" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="75" x2="315" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="100" x2="315" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="125" x2="315" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="200" y1="10" x2="200" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="225" y1="10" x2="225" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="250" y1="10" x2="250" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="275" y1="10" x2="275" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="300" y1="10" x2="300" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <text x="203" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,4</text> <text x="228" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">7,4</text> <text x="253" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,4</text> <text x="278" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,4</text> <text x="203" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,5</text> <text x="228" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">7,5</text> <text x="253" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,5</text> <text x="278" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,5</text> <text x="203" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,6</text> <text x="228" y="70" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">7,6</text> <text x="253" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,6</text> <text x="278" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,6</text> <text x="203" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,7</text> <text x="228" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">7,7</text> <text x="253" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,7</text> <text x="278" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,7</text> <rect x="400" y="50" width="50" height="50" style="fill:rgb(192,192,192); stroke-width:0" /> <line x1="360" y1="25" x2="490" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="50" x2="490" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="75" x2="490" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="100" x2="490" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="125" x2="490" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="375" y1="10" x2="375" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="400" y1="10" x2="400" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="425" y1="10" x2="425" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="450" y1="10" x2="450" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="475" y1="10" x2="475" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <text x="378" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,0</text> <text x="403" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,0</text> <text x="428" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,0</text> <text x="453" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,0</text> <text x="378" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,1</text> <text x="403" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">1,1</text> <text x="428" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">2,1</text> <text x="453" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,1</text> <text x="378" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,2</text> <text x="403" y="70" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">1,2</text> <text x="428" y="70" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">2,2</text> <text x="453" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,2</text> <text x="378" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,3</text> <text x="403" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,3</text> <text x="428" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,3</text> <text x="453" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,3</text> <text x="25" y="160" fill="rgb(255,255,255)">{(1,1), (2,1)}</text> <text x="200" y="160" fill="rgb(255,255,255)">{(7,5), (7,6)}</text> <text x="350" y="160" fill="rgb(255,255,255)">{(1,1), (2,1), (1,2), (2,2)}</text> </svg> ##### Ranges - Size of shape (`len(shape)`, number of unit squares): 1–1500 - Width/height of shape (`max(coord)-min(coord)+1`): 1–90 - `x`, `y` coordinates: -100–100 ### <span style="color:#0ae">Output *[string]*</span> Multiline string representing the border of the input shape, using **`'+'`** (corners), **`'-'`**, **`'|'`** (edges), **`' '`** and **`'\n'`**. - No trailing spaces - No trailing newline - Minimum leading spaces (at least one line starts with a non-space char) ##### Border drawing There is a 1:1 relationship between chars in output string and unit squares in input shape. Borders are drawn immediately outside the shape, in the squares that have an edge or a corner in common with the shape. The shape may have holes. **Holes must be ignored.** ### <span style="color:#0ae">Examples</span> - 1x1 square => 3 rows, 3 chars per row; a central space (the shape) surrounded by *border* chars: ```python {(1,1)} => '+-+\n| |\n+-+' +-+ | | +-+ ``` - 2x1 rectangle => two adjacent spaces surrounded by *border* chars ```python {(1,1),(2,1)} => '+--+\n| |\n+--+' +--+ | | +--+ ``` - 1x2 rectangle ```python {(1,1),(1,2)} => '+-+\n| |\n| |\n+-+' +-+ | | | | +-+ ``` - 4x4 square with a 2x2 hole => only outer borders are drawn, hole is ignored: ```python {(0,0),(0,1),(0,2),(0,3),(1,0),(1,3),(2,0),(2,3),(3,0),(3,1),(3,2),(3,3)} => '+----+\n| |\n| |\n| |\n| |\n+----+' +----+ | | | | | | | | +----+ ``` ## <span style="color:#0ae">Test constraints</span> There are 150 tests: - 23 fixed tests, with small shapes (1–45 unit suares) - 32 small random tests (~ 25–45 unit squares) - 45 medium random tests (~ 140–360 unit squares) - 50 large random tests (~ 350–1000 unit squares) Performances are **not** important. ## <span style="color:#0ae">"Draw the borders" series</span> ###### Draw the borders I - Simple ascii border (this kata) border drawing: outer squares, `+-|` shapes: simple, one piece other requirements: ignore holes performances: not important ###### [Draw the borders II - Fast and furious](https://www.codewars.com/kata/5ff11422d118f10008d988ea) (6 kyu, beta) border drawing: between squares, `─│┌┐└┘┼` shapes: complex, many pieces and holes performances: very important ###### [Draw the Borders III - Fancy borders](https://www.codewars.com/kata/5ff9ed2485c7ea000e072ae3) (2 kyu ?, beta) border drawing: between squares, `━┃┏┓┗┛╋─│┌┐└┘┼╃╄╅╆` shapes: complex, many pieces and holes other requirements: different pieces/holes borders performances: probably important
algorithms
# Asuuming border printout start top-left, finish top row, then go down # So my thinking is: sort all elements based on y decending, and x accending orders. # Output will initially be a matrix of (' ', '+', '-', '|'). ' ' is padded to the # front of each row to line up with the left-most element. Plan to start to fill the # matrix from top left square, go right till turn, then just follow the border till # read the starting square. def draw_borders(shape): figure = list(shape) #print(figure) # put coordinate to top left corner, so top of shape starts at y=1, left of shape starts at x=1 yarr = [pt[1] for pt in figure] xarr = [pt[0] for pt in figure] tp, bp, lp, rp = max(yarr), min(yarr), min(xarr), max(xarr) figure = [(pt[0]-lp +1, tp - pt[1] +1) for pt in figure] #print(figure) bp = tp-bp +1 tp = 1 rp = rp-lp +1 lp = 1 yarr = range(bp+2) fig_dict = dict.fromkeys(yarr) for y in yarr: fig_dict[y] = sorted( [pt for pt in figure if pt[1] == y], key = lambda pt: pt[0] ) #print(fig_dict) # because the printing, border row number is using y, colomn is using x border = [ [' ' for i in range(rp+2)] for j in range(bp+2) ] # Start top left corner, go righr first: dx=1, dy=0 x0 = fig_dict[1][0][0] border[0][x0-1] = '+' border[0][x0] = '-' y0 = 0 #print("starting pt:", x, y, border) #print("stopping pt: ", x0, y0) if (x0+1, y0+1) in fig_dict[y0+1]: # not blocked & shape continues at same h-level dir = 'R' x = x0+1 y = y0 border[y][x] = '-' else: # no sq in front, no sq at same horizontal level, so must go down border[y0][x0+1] = '+' # so a new corner formed dir = 'D' # now must go down x = x0+1 y = y0+1 border[y][x] = '|' #print("no sq in front & no sq at h-level, turnig down", x, y) # Going clockwise around the shape. start above shape, going 'R'. 4 dir: 'R', 'U', 'D', 'L' # (x,y) is the current border coordinate, (x1,y1) could be next border coordinate while (x != x0 or y != y0): #print("Step: ", dir, x, y) if dir == 'R': # Was going 'R', so above the shape. check if there's sq in front x1 = x+1 y1 = y+1 if (x1, y) in fig_dict[y]: # blocked, go up: border[y][x] = '+' # turning from 'R' to 'U' dir = 'U' #print("going R, got blocked, turning U", x, y) elif (x1, y1) in fig_dict[y1]: # not blocked & shape continues at same h-level #border[y][x] = '-' # keep going 'R' dir = 'R' x = x1 #print("keeping going R", x, y) if border[y][x] != '+': border[y][x] = '-' else: # no sq in front, no sq at same horizontal level, so must go down #border[y][x] = '-' border[y][x1] = '+' # so a new corner formed dir = 'D' # now must go down x = x1 y = y1 if border[y][x] != '+': border[y][x] = '|' #print("no sq in front & no sq at h-level, turnig down", x, y) elif dir == 'D': x1 = x-1 y1 = y+1 if (x, y1) in fig_dict[y1]: # blocked, can only go 'R': border[y][x] = '+' # now we know it's actually a corner dir = 'R' #print("going down, got blocked, turning R", x, y) elif (x1, y1) in fig_dict[y1]: # not blocked & shape continues at same v-level #border[y][x] = '|' # keep going 'D' dir = 'D' y = y1 #print("keeing going D", x, y) if border[y][x] != '+': border[y][x] = '|' else: # no sq in front, no sq at same v-level, so must turn & go 'L' #border[y][x] = '|' border[y1][x] = '+' # a new corner formed dir = 'L' # now must go left x = x1 y = y1 if border[y][x] != '+': border[y][x] = '-' #print("was going D, turning L", x, y) elif dir == 'L': x1 = x-1 y1 = y-1 if (x1, y) in fig_dict[y]: # blocked, can only go 'D': border[y][x] = '+' # now we know it's actually a corner dir = 'D' #print("was going L, got blocked, turning D", x, y) elif (x1, y1) in fig_dict[y1]: # not blocked & shape continues at same h-level #border[y][x] = '-' # keep going 'L' dir = 'L' x = x1 #print("keeping going L", x, y) if border[y][x] != '+': border[y][x] = '-' else: # no sq in front, no sq at same h-level, so must turn & go 'U' #border[y][x] = '-' border[y][x1] = '+' # a new corner formed dir = 'U' # now must go up x = x1 y = y1 if border[y][x] != '+': border[y][x] = '|' #print("was going L, turning U", x, y) else: x1 = x+1 y1 = y-1 if (x, y1) in fig_dict[y1]: # blocked, can only go 'L': border[y][x] = '+' # now we know it's actually a corner dir = 'L' #print("was going U, got blocked, turning L", x, y) elif (x1, y1) in fig_dict[y1]: # not blocked & shape continues at same v-level #border[y][x] = '|' # keep going 'U' dir = 'U' y = y1 #print("keeping going U", x, y) if border[y][x] != '+': border[y][x] = '|' else: # no sq in front & no sq at same v-level, so must turn & go 'R' #border[y][x] = '|' border[y1][x] = '+' # a new corner formed dir = 'R' # now must go up x = x1 y = y1 if border[y][x] != '+': border[y][x] = '-' #print("was going U, missing step, turning R", x, y) # strip trailing ' ', can't use strip() as it strip both head and tail for j in range(bp+2): i = -1 while border[j][i] == ' ': border[j][i] = '' i -= 1 #print("row: ", j, border[j]) return ' '.join([ ''.join([border[j][i] for i in range(rp+2)]) for j in range(bp+2) ])
Draw the borders I - Simple ascii border
5ffcbacca79621000dbe7238
[ "Geometry", "Strings", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/5ffcbacca79621000dbe7238
5 kyu
**See Also** * [Traffic Lights - one car](https://www.codewars.com/kata/5d0ae91acac0a50232e8a547) * [Traffic Lights - multiple cars](.) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = <span style='color:black;background:green'>GREEN</span> traffic light * `O` = <span style='color:black;background:orange'>ORANGE</span> traffic light * `R` = <span style='color:black;background:red'>RED</span> traffic light Something like this: <span style='font-family:monospace;font-size:30px;background:black;'> CCC.<span style='background:green;'>G</span>...<span style='background:red;'>R</span>... </span><p/> # Rules ## Simulation At each iteration: 1. the lights change (according to the traffic light rules), then 2. the car moves, obeying the car rules ## Traffic Light Rules Traffic lights change colour as follows: * <span style='color:black;background:green'>GREEN</span> for `5` time units... then * <span style='color:black;background:orange'>ORANGE</span> for `1` time unit... then * <span style='color:black;background:red'>RED</span> for `5` time units.... * ... and repeat the cycle ## Car Rules * Cars travel left to right on the road, moving 1 character position per time unit * Cars can move freely until they come to a traffic light. Then: * if the light is <span style='color:black;background:green'>GREEN</span> they can move forward (temporarily occupying the same cell as the light) * if the light is <span style='color:black;background:orange'>ORANGE</span> then they must stop (if they have already entered the intersection they can continue through) * if the light is <span style='color:black;background:red'>RED</span> the car must stop until the light turns <span style='color:black;background:green'>GREEN</span> again * It is illegal to queue across an intersection. In other words, DO NOT enter an intersection unless you can see there is safe passage through it and out the other side! # Kata Task Given the initial state of the road, return the states for all iterations of the simiulation. ## Input * `road` = the road array * `n` = how many time units to simulate (n >= 0) ## Output * An array containing the road states at every iteration (including the initial state) * Note: If a car occupies the same position as a traffic light then show only the car ## Notes * There are 1 or more cars * There are 0 or more traffic lights * For the initial road state: * cars can start anywhere except in the middle of intersections * traffic lights are either <span style='color:black;background:green'>GREEN</span> or <span style='color:black;background:red'>RED</span>, and are at the beginning of their countdown cycles * There are no reaction delays - when the lights change the car drivers will react immediately! * If a car goes off the end of the road it just disappears from view * There will always be some road between adjacent traffic lights * If there is a traffic light at the end of the road then its exit is never blocked * You cannot see beyond the car in front of you, so you cannot anticipate a gap that does not yet exist # Example Run simulation for 16 time units **Input** * `road = "CCC.G...R..."` * `n = 16` **Result** ```java [ "CCC.G...R...", // 0 initial state as passed ".CCCG...R...", // 1 "..CCC...R...", // 2 show 1st car, not the green light "..CCGC..R...", // 3 2nd car cannot enter intersection because 1st car blocks the exit "...CC.C.R...", // 4 show 2nd car, not the green light "...COC.CG...", // 5 3rd car stops for the orange light "...CR.C.C...", // 6 "...CR..CGC..", // 7 "...CR...C.C.", // 8 "...CR...GC.C", // 9 "...CR...O.C.", // 10 "....C...R..C", // 11 3rd car can proceed "....GC..R...", // 12 "....G.C.R...", // 13 "....G..CR...", // 14 "....G..CR...", // 15 "....O...C..." // 16 ] ``` --- Good luck! DM
algorithms
class Car: l = None def __init__(self, pos): self.pos = pos def forward(self, lights, cars): move = True for light in lights: if light.pos == self.pos + 1: if light.state != "G": move = False for car in cars: if car.pos == light.pos + 1 and car.pos < Car.l: move = False for car in cars: if self.pos + 1 == car.pos: move = False if move: self.pos += 1 conv = {"G": 0, "O": 5, "R": 6} class Light: def __init__(self, pos, state): self.pos = pos self.state = state self.t = conv[state] def forward(self): self.t = (self.t + 1) % 11 if self.t < 5: self.state = "G" elif self.t < 6: self.state = "O" else: self.state = "R" def traffic_lights(road, n): cars = [] lights = [] for i, v in enumerate(road): if v == "C": cars.append(Car(i)) elif v in "GOR": lights.append(Light(i, v)) cars = cars[::-1] l = len(road) Car.l = l res = [road] blank = "." * l for i in range(n): next = list(blank) for light in lights: light.forward() next[light.pos] = light.state for car in cars: car.forward(lights, cars) if car.pos < l: next[car.pos] = 'C' res.append("".join(next)) return res
Traffic Lights - multiple cars
5d230e119dd9860028167fa5
[ "Algorithms" ]
https://www.codewars.com/kata/5d230e119dd9860028167fa5
5 kyu
<b>You are to write a function to transpose a <a href="https://en.wikipedia.org/wiki/Tablature#Guitar_tablature" target="_blank">guitar tab</a> up or down a number of semitones.</b> The <i>amount</i> to transpose is a number, positive or negative. The <i>tab</i> is given as an array, with six elements for each guitar string (fittingly passed as strings). Output your tab in a similar form. Guitar tablature (or 'tab') is an alternative to sheet music, where notes are replaced by fret numbers and the five lines of the staff are replaced by six lines to represent each of the guitar's strings. It is still read from left to right like sheet music, and notes written directly above each other are played at the same time. For example, Led Zeppelin's <i>Stairway to Heaven</i> begins: ``` e|-------5-7-----7-|-8-----8-2-----2-|-0---------0-----|-----------------| B|-----5-----5-----|---5-------3-----|---1---1-----1---|-0-1-1-----------| G|---5---------5---|-----5-------2---|-----2---------2-|-0-2-2-----------| D|-7-------6-------|-5-------4-------|-3---------------|-----------------| A|-----------------|-----------------|-----------------|-2-0-0---0--/8-7-| E|-----------------|-----------------|-----------------|-----------------| ``` Transposed up two semitones, it would look like this: ``` e|-------7-9-----9-|-10-----10-4-----4-|-2---------2-----|------------------| B|-----7-----7-----|----7--------5-----|---3---3-----3---|-2-3-3------------| G|---7---------7---|------7--------4---|-----4---------4-|-2-4-4------------| D|-9-------8-------|-7---------6-------|-5---------------|------------------| A|-----------------|-------------------|-----------------|-4-2-2---2--/10-9-| E|-----------------|-------------------|-----------------|------------------| ``` Note how when the 8th fret note on the top string in bar 2 gets transposed to the 10th fret, extra '-' are added on the other strings below so as to retain the single '-' that originally separated that beat (i.e. column) from the following note – fret 7 on the B string. Each beat must retain at least one '-' separator before the next, to keep the tab legible. The inputted test tabs all obey this convention. Electric guitars usually have 22 frets, with the 0th fret being an open string. If your fret numbers transpose to either negative values or values over 22, you should return '<b>Out of frets!</b>' (and probably detune your guitar). Tests include some randomly generated guitar tabs, which come with no guarantee of musical quality and/or playability...!
algorithms
from itertools import groupby import re class OutOfFrets(Exception): pass def convert(k,grp,amount): def convertOrRaise(m): v = int(m.group()) + amount if not (0 <= v < 23): raise OutOfFrets() return str(v) lst = list(map(''.join, zip(*grp))) if isinstance(k,str): return lst col = [re.sub(r'\d+', convertOrRaise, l.strip('-')) for l in lst] maxL = max(map(len,col)) return [l.ljust(maxL, '-') for l in col] def transpose(amount, tab): try: lst = [convert(k,g,amount) for k,g in groupby(zip(*tab), key=lambda t: len(set(t))!=1 or t[0])] except OutOfFrets: return "Out of frets!" return list(map(''.join, zip(*lst)))
Transposing Guitar Tabs
5ac62974348c2203a90000c0
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5ac62974348c2203a90000c0
5 kyu
![Gameplay screencap](https://i.imgur.com/mYgmiOz.jpg) <p><a href="https://en.wikipedia.org/wiki/Papers%2C_Please" style='color:#9f9;text-decoration:none'><b>Papers, Please</b></a> is an indie video game where the player takes on a the role of a border crossing immigration officer in the fictional dystopian Eastern Bloc-like country of Arstotzka in the year 1982. As the officer, the player must review each immigrant and returning citizen's passports and other supporting paperwork against a list of ever-increasing rules using a number of tools and guides, allowing in only those with the proper paperwork, rejecting those without all proper forms, and at times detaining those with falsified information.</p> <h2 style='color:#f88'>Objective</h2> <p>Your task is to create a constructor function (or class) and a set of instance methods to perform the tasks of the border checkpoint inspection officer. The methods you will need to create are as follow:</p> <h3>Method: <span style='color:#8df'>receiveBulletin</span></h3> <p>Each morning you are issued an official bulletin from the Ministry of Admission. This bulletin will provide updates to regulations and procedures and the name of a wanted criminal.</p> <p>The bulletin is provided in the form of a <code>string</code>. It may include one or more of the following:</p> - Updates to the list of nations (comma-separated if more than one) whose citizens may enter (begins empty, before the first bulletin): ``` example 1: Allow citizens of Obristan example 2: Deny citizens of Kolechia, Republia ``` - Updates to required documents ``` example 1: Foreigners require access permit example 2: Citizens of Arstotzka require ID card example 3: Workers require work pass ``` - Updates to required vaccinations ``` example 1: Citizens of Antegria, Republia, Obristan require polio vaccination example 2: Entrants no longer require tetanus vaccination ``` - Update to a currently wanted criminal ``` example 1: Wanted by the State: Hubert Popovic ``` <h3>Method: <span style='color:#8df'>inspect</span></h3> <p>Each day, a number of entrants line up outside the checkpoint inspection booth to gain passage into Arstotzka. The <code>inspect</code> method will receive an object representing each entrant's set of identifying documents. This object will contain zero or more properties which represent separate documents. Each property will be a <code>string</code> value. These properties may include the following:</p> <ul> <li>Applies to all entrants: <ul> <li><code>passport</code></li> <li><code>certificate_of_vaccination</code></li> </ul> </li> <li>Applies only to citizens of Arstotzka <ul><li><code>ID_card</code></li></ul> </li> <li>Applies only to foreigners: <ul> <li><code>access_permit</code></li> <li><code>work_pass</code></li> <li><code>grant_of_asylum</code></li> <li><code>diplomatic_authorization</code></li> </ul> </li> </ul> The `inspect` method will return a result based on whether the entrant passes or fails inspection: <p><b>Conditions for passing inspection</b></p> <ul> <li>All required documents are present</li> <li>There is no conflicting information across the provided documents</li> <li>All documents are current (ie. none have expired) -- a document is considered expired if the expiration date is <code>November 22, 1982</code> or earlier</li> <li>The entrant is not a wanted criminal</li> <li>If a <code>certificate_of_vaccination</code> is required and provided, it must list the required vaccination</li> <li>A "worker" is a foreigner entrant who has <code>WORK</code> listed as their purpose on their access permit</li> <li>If entrant is a foreigner, a <code>grant_of_asylum</code> or <code>diplomatic_authorization</code> are acceptable in lieu of an <code>access_permit</code>. In the case where a <code>diplomatic_authorization</code> is used, it must include <code>Arstotzka</code> as one of the list of nations that can be accessed.</li> </ul> <p>If the entrant <span style='color:#0f0'>passes</span> inspection, the method should return one of the following <code>string</code> values:</p> <ul> <li>If the entrant is a citizen of Arstotzka: <code>Glory to Arstotzka.</code></li> <li>If the entrant is a foreigner: <code>Cause no trouble.</code></li> </ul> If the entrant <span style='color:#f66'>fails</span> the inspection due to expired or missing documents, or their <code>certificate_of_vaccination</code> does not include the necessary vaccinations, return <code>Entry denied:</code> with the reason for denial appended. ``` Example 1: Entry denied: passport expired. Example 2: Entry denied: missing required vaccination. Example 3: Entry denied: missing required access permit. ``` <p>If the entrant <span style='color:#f66'>fails</span> the inspection due to mismatching information between documents (causing suspicion of forgery) or if they're a wanted criminal, return <code>Detainment:</code> with the reason for detainment appended.</p> <ul> <li>If due to information mismatch, include the mismatched item. e.g.<code>Detainment: ID number mismatch.</code></li> <li>If the entrant is a wanted criminal: <code>Detainment: Entrant is a wanted criminal.</code></li> <li><b>NOTE:</b> One wanted criminal will be specified in each daily bulletin, and must be detained when received for that day only. For example, if an entrant on Day 20 has the same name as a criminal declared on Day 10, they are not to be detained for being a criminal.</br>Also, if any of an entrant's identifying documents include the name of that day's wanted criminal (in case of mismatched names across multiple documents), they are assumed to be the wanted criminal.</li> </ul> <p>In some cases, there may be multiple reasons for denying or detaining an entrant. For this exercise, you will only need to provide one reason.</p> <ul> <li>If the entrant meets the criteria for both entry denial and detainment, priority goes to detaining.</br> For example, if they are missing a required document and are also a wanted criminal, then they should be detained instead of turned away.</li> <li>In the case where the entrant has mismatching information and is a wanted criminal, detain for being a wanted criminal.</li> </ul> <h2 style='color:#f88'>Test Example</h2> ```javascript const bulletin = `Entrants require passport Allow citizens of Arstotzka, Obristan`; const inspector = new Inspector(); inspector.receiveBulletin(bulletin); const entrant1 = { passport:`ID#: GC07D-FU8AR NATION: Arstotzka NAME: Guyovich, Russian DOB: 1933.11.28 SEX: M ISS: East Grestin EXP: 1983.07.10` }; inspector.inspect(entrant1); //'Glory to Arstotzka.' ``` ```python bulletin = """Entrants require passport Allow citizens of Arstotzka, Obristan""" inspector = Inspector() inspector.receive_bulletin(bulletin) entrant1 = { "passport": """ID#: GC07D-FU8AR NATION: Arstotzka NAME: Guyovich, Russian DOB: 1933.11.28 SEX: M ISS: East Grestin EXP: 1983.07.10""" } inspector.inspect(entrant1) #=> 'Glory to Arstotzka.' ``` ```java String bulletin = "Entrants require passport\n" + "Allow citizens of Arstotzka, Obristan"; Inspector inspector = new Inspector(); inspector.receiveBulletin(bulletin); Map<String, String> entrant1 = new HashMap<>(); entrant1.put("passport", "ID#: GC07D-FU8AR\n" + "NATION: Arstotzka\n" + "NAME: Guyovich, Russian\n" + "DOB: 1933.11.28\n" + "SEX: M\n" + "ISS: East Grestin\n" + "EXP: 1983.07.10\n" ); inspector.inspect(entrant1); // "Glory to Arstotzka." ``` <h2 style='color:#f88'>Additional Notes</h2> - Inputs will always be valid. - There are a total of 7 countries: `Arstotzka`, `Antegria`, `Impor`, `Kolechia`, `Obristan`, `Republia`, and `United Federation`. - Not every single possible case has been listed in this Description; use the test feedback to help you handle all cases. - The concept of this kata is derived from the video game of the same name, but it is not meant to be a direct representation of the game. If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
reference
from itertools import combinations from collections import defaultdict from datetime import date import re EXPIRE_DT = date(1982,11,22) NATION = 'Arstotzka'.lower() COUNTRIES = set(map(str.lower, ('Arstotzka', 'Antegria', 'Impor', 'Kolechia', 'Obristan', 'Republia', 'United Federation'))) ACCESS_SUBSTITUTES = {'grant_of_asylum', 'diplomatic_authorization', 'access_permit'} MISMATCHER = {'NAME': 'name', 'NATION': 'nationality', 'ID#': 'ID number', 'DOB': 'date of birth'} P_PAPERS = re.compile( r'([^:]+): (.+) ?' ) P_CONSTRAINTS = re.compile( r'wanted by the state: (?P<wanted>.+)|' r'(?P<action>allow|deny) citizens of (?P<who>(?:[\w ]+|, )+)|' r'(?:citizens of )?(?P<who2>.+?)(?P<noMore> no longer)? require (?P<piece>[\w ]+)' ) class Inspector(object): def __init__(self): self.allowed = {c: False for c in COUNTRIES} self.docs = defaultdict(set) self.vacs = defaultdict(set) self.wanted = None self.papers = None self.papersSet = None def receive_bulletin(self, b): self.wanted = None for m in P_CONSTRAINTS.finditer(b.lower()): if m["wanted"]: self.wanted = self.getWantedSet(m["wanted"]) continue whos = (m['who'] or m['who2']).split(', ') if whos == ['entrants']: whos = COUNTRIES elif whos == ['foreigners']: whos = COUNTRIES - {NATION} if m["action"]: for country in whos: self.allowed[country] = m["action"] == 'allow' else: toRemove = m['noMore'] piece = m['piece'].replace(' ','_') docType = self.docs if piece.endswith('vaccination'): piece = piece.replace('_vaccination','') docType = self.vacs elif piece=='id_card': piece = 'ID_card' for who in whos: if toRemove: docType[who].discard(piece) else: docType[who].add(piece) def getWantedSet(self,s): return set(s.replace(',','').split()) def isWanted(self): return any(self.getWantedSet(p.get('NAME','')) == self.wanted for _,p in self.papers.items()) def isBanned(self,nation): return not self.allowed.get(nation,0) def needWorkPass(self): return ('work_pass' in self.docs['workers'] and 'work' in self.papers.get('access_permit', {}).get('PURPOSE', set())) def getMismatchedPapers(self): for p1,p2 in combinations(self.papers, 2): p1,p2 = self.papers[p1], self.papers[p2] for k in set(p1) & set(p2) - {'EXP'}: if k in MISMATCHER and p1[k] != p2[k]: return MISMATCHER[k] def getMissingDocs(self,nation): required = set(self.docs.get(nation, {'passport'})) if self.vacs[nation]: required.add('certificate_of_vaccination') if self.needWorkPass(): required.add('work_pass') return required - self.papersSet def inspect(self, papers): self.papers = { k: {x:s.lower() for x,s in P_PAPERS.findall(p)} for k,p in papers.items()} self.papersSet = set(self.papers) mismatched = self.getMismatchedPapers() nation = next((p['NATION'] for k,p in self.papers.items() if 'NATION' in p), '').lower() isForeign = nation != NATION missingDocs = self.getMissingDocs(nation) expiredDocs = next( (k.replace("_", " ") for k,p in self.papers.items() if 'EXP' in p and date(*map(int, p['EXP'].split('.'))) <= EXPIRE_DT), None) vaccines = set(self.papers.get('certificate_of_vaccination', {}).get('VACCINES', '').replace(' ','_').split(',_')) misVaccines = self.vacs[nation] - vaccines isBadDiplo = False if isForeign and 'access_permit' in missingDocs: substitute = ACCESS_SUBSTITUTES & self.papersSet if substitute: missingDocs.discard('access_permit') isBadDiplo = (substitute == {'diplomatic_authorization'} and NATION not in self.papers['diplomatic_authorization']['ACCESS']) if self.isWanted(): return 'Detainment: Entrant is a wanted criminal.' if mismatched: return f'Detainment: {mismatched} mismatch.' if missingDocs: return f'Entry denied: missing required {missingDocs.pop().replace("_", " ")}.' if isBadDiplo: return 'Entry denied: invalid diplomatic authorization.' if self.isBanned(nation): return 'Entry denied: citizen of banned nation.' if expiredDocs: return f'Entry denied: {expiredDocs} expired.' if misVaccines: return 'Entry denied: missing required vaccination.' return "Cause no trouble." if isForeign else 'Glory to Arstotzka.'
Papers, Please
59d582cafbdd0b7ef90000a0
[ "Object-oriented Programming", "Games", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59d582cafbdd0b7ef90000a0
3 kyu
# QR-Code Message Encoding ## Information This kata will only focus on the message encoding, not on error correction or the 2d representation. A message for a QR-Code can be encoded in 5 different modes: - Byte Mode - Alphanumeric Mode - Numeric Mode - (ECI Mode) - (Kanji Mode) To simplify this kata, we will only use the first 3 modes. Each mode has a different set of allowed characters. ### Byte Mode - Encoding: Each character gets encoded into 8 bit by using the char integer value to keep it simple (real QR-Codes use ISO 8859-1 as character set) ### The Alphanumeric Mode - Characters: 45 characters listed at the end of the description (will be provided in the initial solution in the same order as they're listed in the table) - Encoding: Seperate the message string into groups of 2 characters: `"HELLO WORLD" -> "HE", "LL", "O ", "WO", "RL", "D"`. For each group, translate the first character to its corresponding int value and multiply it by `45`. Than add the int value for the second char to this value. Then convert this value into an 11-bit string. `"HE" -> 17*45 + 14 = 779 -> "01100001011"`. If you encode an odd number of chars, convert the last char to its int value and then to a 6-bit string. ### The Numeric Mode - Characters: Digits `0-9` - Encoding: Seperate the message into groups of 3 characters: `"1234567" -> "123", "456", "7"`. For each group, remove the leading zeroes (for example, `"034" -> "34"`). If the group is still three digits long, convert that number into 10 bits. If the group is only two digits long, convert it into 7 bits. Groups with only one remaining digit should be converted into 4 bit. A group containing only 0s should evaluate to `"0000"`. ### Prefix #### Mode Indicator The encoded message starts with 4 bit that indicate the used mode: - Numeric: `"0001"` - Alphanumeric: `"0010"` - Byte: `"0100"` #### Message length Side Note: To simplify we only focus on QR-Codes with Versions <9. Add the character count as binary representation. For the numeric mode, this bit string is 10 bits long. For alphanumeric mode it is 9 bits and for byte mode it is 8 bits long. For example if you use the alphanumeric mode and the message is 14 characters long, the prefix would be `"0010000001110"` (indicator: `"0010"`, length: `"000001110"`). ## Your task The input parameter to your function will be a string. If the string contains only numbers, use the numeric mode. Otherwise, if the string only contains characters from the alphanumeric table, use the alphanumeric mode. Otherwise, use the byte mode. Return the bit representation of the message as 1s and 0s withous spaces. ## Examples In each example, the return value would be prefix + message with spaces removed. - `"HELLO WORLD"` (Alphanumeric Mode): prefix is `"0010 000001011"`, message is `"01100001011 01111000110 10001011100 10110111000 10011010100 001101"` - `"Hello World"` (Byte Mode): prefix is `"0100 00001011"`, message is `"01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100"` - `"9120136"` (Numeric Mode): prefix is `"0001 0000000111"`, message is `"1110010000 0001101 0110"` ## Alphanumeric Character Table (character -> integer value) ``` '0' -> 0 '1' -> 1 ... '8' -> 8 '9' -> 9 'A' -> 10 'B' -> 11 ... 'Y' -> 34 'Z' -> 35 ' ' -> 36 '$' -> 37 '%' -> 38 '*' -> 39 '+' -> 40 '-' -> 41 '.' -> 42 '/' -> 43 ':' -> 44 ``` ### Have fun
reference
CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:" ALPHA = {c:i for i,c in enumerate(CHAR_SET)} NUMS_SET = set('0123456789') def qr_encode(s): n = 3 if set(s) <= NUMS_SET else 2 if all(map(ALPHA.__contains__,s)) else 1 func = (_byte, _alnum, _num)[n-1] msg = ''.join( func(s[i:i+n]) for i in range(0,len(s),n) ) return f'{ "0" * n }1{ len(s) :0>10b}{ msg }' def _byte(s): return f'{ ord(s) :0>8b}' def _alnum(s): v = sum(ALPHA[c] * 45**i for i,c in enumerate(s[::-1])) return f'{ v :0>{ 6 + 5*(len(s)>1) }b}' def _num(s): s = s.lstrip('0') or '0' return f'{ int(s) :0>{ 1+3*len(s) }b}'
QR-Code Message Encoding
605da8dc463d940023f2022e
[ "Fundamentals" ]
https://www.codewars.com/kata/605da8dc463d940023f2022e
5 kyu
## <span style="color:#0ae">Task</span> <svg width="426" height="201"> <rect x="0" y="0" width="426" height="201" style="fill:rgb(48,48,48); stroke-width:0" /> <rect x="50" y="50" width="100" height="25" style="fill:rgb(96,96,96); stroke-width:0" /> <rect x="50" y="125" width="100" height="25" style="fill:rgb(96,96,96); stroke-width:0" /> <rect x="50" y="75" width="25" height="50" style="fill:rgb(96,96,96); stroke-width:0" /> <rect x="125" y="75" width="25" height="50" style="fill:rgb(96,96,96); stroke-width:0" /> <rect x="200" y="75" width="25" height="25" style="fill:rgb(96,96,96); stroke-width:0" /> <rect x="200" y="125" width="50" height="25" style="fill:rgb(96,96,96); stroke-width:0" /> <rect x="275" y="50" width="75" height="75" style="fill:rgb(96,96,96); stroke-width:0" /> <line x1="0" y1="0" x2="426" y2="0" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="25" x2="426" y2="25" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="50" x2="426" y2="50" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="75" x2="426" y2="75" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="100" x2="426" y2="100" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="125" x2="426" y2="125" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="150" x2="426" y2="150" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="175" x2="426" y2="175" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="200" x2="426" y2="200" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="0" y1="0" x2="0" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="25" y1="0" x2="25" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="50" y1="0" x2="50" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="75" y1="0" x2="75" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="100" y1="0" x2="100" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="125" y1="0" x2="125" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="150" y1="0" x2="150" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="175" y1="0" x2="175" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="200" y1="0" x2="200" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="225" y1="0" x2="225" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="250" y1="0" x2="250" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="275" y1="0" x2="275" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="300" y1="0" x2="300" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="325" y1="0" x2="325" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="350" y1="0" x2="350" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="375" y1="0" x2="375" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="400" y1="0" x2="400" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="425" y1="0" x2="425" y2="201" style="stroke:rgb(64,64,64);stroke-width:2" /> <line x1="50" y1="50" x2="60" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="65" y1="50" x2="85" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="90" y1="50" x2="110" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="115" y1="50" x2="135" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="140" y1="50" x2="150" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="50" y1="150" x2="60" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="65" y1="150" x2="85" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="90" y1="150" x2="110" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="115" y1="150" x2="135" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="140" y1="150" x2="150" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="75" y1="75" x2="85" y2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="90" y1="75" x2="110" y2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="115" y1="75" x2="125" y2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="75" y1="125" x2="85" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="90" y1="125" x2="110" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="115" y1="125" x2="125" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="50" x1="50" y2="60" x2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="65" x1="50" y2="85" x2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="90" x1="50" y2="110" x2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="115" x1="50" y2="135" x2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="140" x1="50" y2="150" x2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="50" x1="150" y2="60" x2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="65" x1="150" y2="85" x2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="90" x1="150" y2="110" x2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="115" x1="150" y2="135" x2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="140" x1="150" y2="150" x2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="75" x1="75" y2="85" x2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="90" x1="75" y2="110" x2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="115" x1="75" y2="125" x2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="75" x1="125" y2="85" x2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="90" x1="125" y2="110" x2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line y1="115" x1="125" y2="125" x2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="75" x2="210" y2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="215" y1="75" x2="225" y2="75" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="100" x2="210" y2="100" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="215" y1="100" x2="225" y2="100" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="75" x2="200" y2="85" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="225" y1="75" x2="225" y2="85" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="90" x2="200" y2="100" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="225" y1="90" x2="225" y2="100" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="125" x2="210" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="215" y1="125" x2="235" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="240" y1="125" x2="250" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="150" x2="210" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="215" y1="150" x2="235" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="240" y1="150" x2="250" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="125" x2="200" y2="135" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="250" y1="125" x2="250" y2="135" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="200" y1="140" x2="200" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="250" y1="140" x2="250" y2="150" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="275" y1="50" x2="285" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="290" y1="50" x2="310" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="315" y1="50" x2="335" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="340" y1="50" x2="350" y2="50" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="275" y1="125" x2="285" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="290" y1="125" x2="310" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="315" y1="125" x2="335" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="340" y1="125" x2="350" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="275" y1="50" x2="275" y2="60" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="275" y1="65" x2="275" y2="85" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="275" y1="90" x2="275" y2="110" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="275" y1="115" x2="275" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="350" y1="50" x2="350" y2="60" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="350" y1="65" x2="350" y2="85" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="350" y1="90" x2="350" y2="110" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> <line x1="350" y1="115" x2="350" y2="125" style="stroke:rgb(0,224,255);stroke-width:3;stroke-linecap:round" /> </svg> Create a (fast) function that takes a shape (set of unit squares) and returns the borders of the shape as a multiline string, using box-drawing characters. ### <span style="color:#0ae">Input</span> - **`shape`** *[set of tuples (int, int)]* The shape is a plane geometric figure formed by one or more pieces, each piece is formed by joining one or more unit squares edge to edge. The `shape` parameter contains the `(x,y)` coordinates of the unit squares that form the shape. `x` axis is horizontal and oriented to the right, `y` axis is vertical and oriented upwards. ##### Examples A set with one element (e.g. `{(1,1)}`, `{(7,11)}`, `{(50,35)}`, ...) represents a square whose sides have length 1. A set with two elements with the same `y` coord and consecutive `x` coord (e.g. `{(1,1),(2,1)}` or `{(7,5),(8,5)}`) is a rectangle, width: 2, height: 1. A set with two elements with the same `x` coord and consecutive `y` coord (e.g. `{(1,1),(1,2)}` or `{(7,5),(7,6)}`) is a rectangle, width: 1, height: 2. <svg width="600" height="180"> <rect x="0" y="0" width="600" height="180" style="fill:rgb(48,48,48); stroke-width:0" /> <rect x="50" y="75" width="50" height="25" style="fill:rgb(192,192,192); stroke-width:0" /> <line x1="10" y1="25" x2="140" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="50" x2="140" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="75" x2="140" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="100" x2="140" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="10" y1="125" x2="140" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="25" y1="10" x2="25" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="50" y1="10" x2="50" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="75" y1="10" x2="75" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="100" y1="10" x2="100" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="125" y1="10" x2="125" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <text x="28" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,0</text> <text x="53" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,0</text> <text x="78" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,0</text> <text x="103" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,0</text> <text x="28" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,1</text> <text x="53" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">1,1</text> <text x="78" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">2,1</text> <text x="103" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,1</text> <text x="28" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,2</text> <text x="53" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,2</text> <text x="78" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,2</text> <text x="103" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,2</text> <text x="28" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,3</text> <text x="53" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,3</text> <text x="78" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,3</text> <text x="103" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,3</text> <rect x="225" y="50" width="25" height="50" style="fill:rgb(192,192,192); stroke-width:0" /> <line x1="185" y1="25" x2="315" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="50" x2="315" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="75" x2="315" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="100" x2="315" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="185" y1="125" x2="315" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="200" y1="10" x2="200" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="225" y1="10" x2="225" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="250" y1="10" x2="250" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="275" y1="10" x2="275" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="300" y1="10" x2="300" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <text x="203" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,4</text> <text x="228" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">7,4</text> <text x="253" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,4</text> <text x="278" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,4</text> <text x="203" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,5</text> <text x="228" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">7,5</text> <text x="253" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,5</text> <text x="278" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,5</text> <text x="203" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,6</text> <text x="228" y="70" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">7,6</text> <text x="253" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,6</text> <text x="278" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,6</text> <text x="203" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">6,7</text> <text x="228" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">7,7</text> <text x="253" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">8,7</text> <text x="278" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">9,7</text> <rect x="400" y="50" width="50" height="50" style="fill:rgb(192,192,192); stroke-width:0" /> <line x1="360" y1="25" x2="490" y2="25" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="50" x2="490" y2="50" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="75" x2="490" y2="75" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="100" x2="490" y2="100" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="360" y1="125" x2="490" y2="125" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="375" y1="10" x2="375" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="400" y1="10" x2="400" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="425" y1="10" x2="425" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="450" y1="10" x2="450" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <line x1="475" y1="10" x2="475" y2="140" style="stroke:rgb(96,96,96);stroke-width:2" /> <text x="378" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,0</text> <text x="403" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,0</text> <text x="428" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,0</text> <text x="453" y="120" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,0</text> <text x="378" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,1</text> <text x="403" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">1,1</text> <text x="428" y="95" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">2,1</text> <text x="453" y="95" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,1</text> <text x="378" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,2</text> <text x="403" y="70" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">1,2</text> <text x="428" y="70" fill="rgb(0,0,0)" textLength="19" lengthAdjust="spacingAndGlyphs">2,2</text> <text x="453" y="70" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,2</text> <text x="378" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">0,3</text> <text x="403" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">1,3</text> <text x="428" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">2,3</text> <text x="453" y="45" fill="rgb(160,160,160)" textLength="19" lengthAdjust="spacingAndGlyphs">3,3</text> <text x="25" y="160" fill="rgb(255,255,255)">{(1,1), (2,1)}</text> <text x="200" y="160" fill="rgb(255,255,255)">{(7,5), (7,6)}</text> <text x="350" y="160" fill="rgb(255,255,255)">{(1,1), (2,1), (1,2), (2,2)}</text> </svg> ##### Ranges - Size of shape (`len(shape)`, number of unit squares): 1–5000 - Width/height of shape (`max(coord)-min(coord)+1`): 1–120 - `x`, `y` coordinates: -500–500 ### <span style="color:#0ae">Output *[string]*</span> Multiline string representing the border of the input shape, using [box-drawing characters](https://en.wikipedia.org/wiki/Box-drawing_character). - No trailing spaces - No trailing newline - Minimum leading spaces (at least one line starts with a non-space char) ##### Allowed chars: ``` CHAR CODE NAME 000a newline 0020 space ─ 2500 box drawings light horizontal │ 2502 box drawings light vertical ┌ 250c box drawings light down and right ┐ 2510 box drawings light down and left └ 2514 box drawings light up and right ┘ 2518 box drawings light up and left ┼ 253c box drawings light vertical and horizontal ``` ### <span style="color:#0ae">Border drawing</span> Borders are drawn *between unit squares*, not inside squares. There isn't a 1:1 relationship between chars in output string and `(x,y)` coordinates in input shape. If two borders separated by `n` unit squares (e.g. opposite sides of a `n`x`n` square), the distance of corresponding chars in output string is `n`, i.e. there are `n-1` chars between them (see examples below). ### <span style="color:#0ae">Examples</span> - 1x1 square => four *corner* chars in two rows, without other intermediate chars: ```python {(1,1)} => '┌┐\n└┘' ┌┐ └┘ ``` - 2x1 rectangle => four corners, with horizontal lines (`─`) between left and right corners: ```python {(1,1),(2,1)} => '┌─┐\n└─┘' ┌─┐ └─┘ ``` - 1x2 rectangle => three rows, with vertical lines (`│`) between top and bottom corners: ```python {(1,1),(1,2)} => '┌┐\n││\n└┘' ┌┐ ││ └┘ ``` - 2x2 square => three rows, horizontal/vertical lines between corners and a space (`' '`) in the center: ```python {(1,1),(2,1),(1,2),(2,2)} => '┌─┐\n│ │\n└─┘' ┌─┐ │ │ └─┘ ``` - shapes may have holes, inner borders must be drawn; 4x4 square with a 2x2 hole: ```python {(0,0),(0,1),(0,2),(0,3),(1,0),(1,3),(2,0),(2,3),(3,0),(3,1),(3,2),(3,3)} => '┌───┐\n│┌─┐│\n││ ││\n│└─┘│\n└───┘' ┌───┐ │┌─┐│ ││ ││ │└─┘│ └───┘ ``` - shapes may have multiple separate pieces, all pieces must be drawn; two squares with 1-unit gap: ```python {(x,y) for x in range(3) for y in range(3)} | {(x,y) for x in range(4,7) for y in range(3)} => '┌──┐┌──┐\n│ ││ │\n│ ││ │\n└──┘└──┘' ┌──┐┌──┐ │ ││ │ │ ││ │ └──┘└──┘ ``` - pieces may touch each other at corners, common corners are drawn with `┼`: ```python {(x,y) for x in range(4) for y in range(3)} | {(x,y) for x in range(4,8) for y in range(3,6)} => ' ┌───┐\n │ │\n │ │\n┌───┼───┘\n│ │\n│ │\n└───┘' ....┌───┐ ....│ │ ....│ │ .... = leading spaces ┌───┼───┘ │ │ │ │ └───┘ ``` ## <span style="color:#0ae">Performances and tests</span> The algorithm must be efficient, even with complex shapes, convoluted borders, multiple holes, ... There are 299 tests: - 25 fixed tests, with small shapes; - 54 *normal* random tests, with small shapes; - 220 *performance* tests, with medium/large shapes and timeout. #### Performance tests Typical range (10th–90th percentile) and average values of shapes used in timed tests: **180 tests with medium shapes** - size (unit squares): 800–1600, avg: 1170 - width: 53–70, avg: 61 - height: 45–62, avg: 53 - number of pieces: 18–43, avg: 29 - number of holes: 13–30, avg: 21 - area coverage (squares/(width\*height)): 30%–42%, avg: 36% **40 tests with large shapes** - size (unit squares): 1800–3300, avg: 2500 - width: 69–89, avg: 79 - height: 77–99, avg: 88 - number of pieces: 37–77, avg: 56 - number of holes: 28–56, avg: 41 - area coverage: 30%–42%, avg: 36% Maximum time: **3.0 seconds** *(reference solution: 2.28 ± 0.08 s)* ## <span style="color:#0ae">"Draw the borders" series</span> ###### [Draw the borders I - Simple ascii border](https://www.codewars.com/kata/5ffcbacca79621000dbe7238) (5 kyu) border drawing: outer squares, `+-|` shapes: simple, one piece other requirements: ignore holes performances: not important ###### Draw the borders II - Fast and furious (this kata) border drawing: between squares, `─│┌┐└┘┼` shapes: complex, many pieces and holes performances: very important ###### [Draw the Borders III - Fancy borders](https://www.codewars.com/kata/5ff9ed2485c7ea000e072ae3) (2 kyu ?, beta) border drawing: between squares, `━┃┏┓┗┛╋─│┌┐└┘┼╃╄╅╆` shapes: complex, many pieces and holes other requirements: different pieces/holes borders performances: probably important
algorithms
borders = { (1,0,0,0): '┐', (0,1,0,0): '┘', (0,0,1,0): '┌', (0,0,0,1): '└', (0,1,1,1): '┐', (1,0,1,1): '┘', (1,1,0,1): '┌', (1,1,1,0): '└', (1,1,0,0): '│', (0,0,1,1): '│', (1,0,1,0): '─', (0,1,0,1): '─', (1,0,0,1): '┼', (0,1,1,0): '┼', (0,0,0,0): ' ', (1,1,1,1): ' ', } def draw_borders(shape): x0 = min(x for (x,_) in shape) - 1 x1 = max(x for (x,_) in shape) + 1 y0 = max(y for (_,y) in shape) y1 = min(y for (_,y) in shape) - 2 return ' '.join(''.join(borders[tuple(xy in shape for xy in ((x,y),(x,y+1),(x+1,y),(x+1,y+1)))] for x in range(x0, x1)).rstrip() for y in range(y0, y1, -1))
Draw the borders II - Fast and furious
5ff11422d118f10008d988ea
[ "Strings", "Performance", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/5ff11422d118f10008d988ea
5 kyu
Cluster analysis - Unweighted pair-group average Clustering is a task of grouping a set of objects in such a way that the objects in the same class are similar to each other and the objects in different classes are distinct. Cluster analysis is employed in many fields such as machine learning, pattern recognition, image analysis, etc. In this kata, your task is to implement a simple clustering technique called 'Unweighted pair-group average'. This method takes a set of 2D points and the desired number of final clusters. Initially, each point forms its own cluster. The most similar (least distant) clusters are iteratively merged until the target number of clusters is reached. The distance metric between two clusters is defined as the average distance between all pairs of points from the two clusters. For example: ``` Cluster 1: (0, 0), (0, 1) Cluster 2: (4, 3) Distance = (sqrt((0-4)^2 + (0-3)^2) + sqrt((0-4)^2 + (1-3)^2)) / 2 ``` Input: - `points` - a list of 2D points `[(1, 1), (3, 5), (4, 4), (8, 2), (0, 1)]` - `n` - the desired number of clusters Output: - list of clusters, each cluster is a list of points - points in each cluster should be sorted in ascending order - the list of clusters should also be sorted in ascending order Example: - `cluster([(1, 1), (3, 5), (4, 4), (8, 2), (0, 1)], 3)` - should return ``` [ [(0, 1), (1, 1)], [(3, 5), (4, 4)], [(8, 2)], ] ``` Notes: - the coordinates `(x, y)` are chosen from interval `<0, 1000>` - `0 < len(points) <= 100` - `0 < n <= len(points)` - there is always only one unique solution - there are no duplicate points in the input
algorithms
from itertools import combinations from math import hypot def cluster(points, n): def distGrp(a,b): return sum(hypot(*(z2-z1 for z1,z2 in zip(aa,bb))) for aa in a for bb in b )/ (len(a)*len(b)) g = {(p,) for p in points} while len(g) > n: a,b = min(combinations(g,2), key=lambda pair: distGrp(*pair)) g.remove(a) g.remove(b) g.add( tuple(sum(map(list, (a,b)),[])) ) return sorted( sorted(gg) for gg in g )
Simple cluster analysis
5a99d851fd5777f746000066
[ "Algorithms" ]
https://www.codewars.com/kata/5a99d851fd5777f746000066
5 kyu
# You Bought the Farm! Well, actually you just inherited the farm, after your grandfather bought the farm in darker and more figurative sense. The point is, you now have a farm, and you've decided to abandon your life as a programmer in the city and become a farmer instead. It's a small farm with only a single field. Your grandfather had bought the equipment to irrigate it, but it was never installed, so that's your first order of business! The equipment consists of a single sprinkler gun and a variable-speed pump. When active, the gun will turn, watering a circular area around it. The range of the gun can be controlled by varying the speed of the pump. The problem: where do you position it, and what to do you set the range to, to ensure it covers the largest possible circular area within your farm? # Problem Description The field to be irrigated has 4 sides, and is defined by x,y coordinates of the four corners. The field may be any shape, so long as it is [convex](https://www.mathopenref.com/polygonconvex.html). Your goal is to find largest circlular area that will fit within that quad. Note that your neighbors look unfriendly and all seem to be well-armed, so to be safe, you should be sure not let the circle cross outside the field and into their property! ### Function Header and Arguments Coordinates are passed to your function as a single array of 8 floats, `x` and `y` for corners 0-3, in a clockwise order (on a plane where positive `y` is up and positive `x` is right) ~~~if:go ```go []float64{X1,Y1,X2,Y2,X3,Y3,X4,Y4} ``` ~~~ ~~~if:python,javascript ```python [x0,y0,x1,y1,x2,y2,x3,y3] ``` ~~~ Your main function prototype should be: ~~~if:go ```go func FitBiggestCircle(coords []float64) []float64 { ... } ``` ~~~ ~~~if:python ```python def fit_biggest_circle(coords) : ``` ~~~ ~~~if:javascript ```javascript function fitBiggestCircle(coords) { ... } ``` ~~~ ### Return values ~~~if:go You are expected to return a slice of float64's consisting of the center x, center y, and radius of the circle. ~~~ ~~~if:javascript,python You are expected to return an array consisting of the center x, center y, and radius of the circle. At present only the radius is tested; the position is simply used in the output visualization ~~~ Only the radius will be tested, but both will be used to display a picture of your solution, like those with the examples below. # Examples Squares are trivial, with radius being half the length of a side - of course, you'll have to prove the corners define a square, first! <table><col width="150"> <tr> <td><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAABmJLR0QA/wD/AP+gvaeTAAAOpUlEQVR4nO2deWwc133HPzOzs8td3lxSlCiSkihRNClREiNLim0diQ7IiGK7dlGkiQzLhgPHRtO7RV2gteQCAdqmQRAEbeIYrmU3EQwEvpI2tRVTsmvJkWVdpA6SkcRDBynxWl57zs5M/1hSvPaYGa4kUrsfgBA0+97MW3z3vfd9b977PUgzqx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Om4hF4uuEKTmWRlex3349OEau2Qbx/+yGtZku9Vrj5KGJQR78hCAz6dMGjRQK5eIlERwgx+YB7O5EmKJOxA+4FsmWJBbqOXYBPyvP44D43H1Xk05o/s0FwTGp64Ost9bjC261kv/uCxCFnkIK//gHb8j1syfMIq+e3U1nSqefnDSO7/AiuQKSFAFBEAZ9NwGuT6HXKtBS6OLcgm5ZCF+fnuWgqzOSORP7adEVnc/uPkLW/tJLd3NGrd5ihXPr3wi+BX07rWUZrVkaAWlUXVyqiWB1pBsPlqBoMEaRXl7ihuehGwKMZdoMzwuIs7xizWpC4CHiAkwE4GYm2PqH/1NV83L4K3L4VLPUk1bonxOIs7xizusm6LdzGcRYwI8sLqShIPGYq1gwtL6QFMYaOAJQS2RBViSJWE5JWIbEUe3jhremmEbuDsqEeq5YX0oLMnKliQQCBN+9uodKkSZPmjvD/yjFaPT5yemcAAAAASUVORK5CYII="/></td><td> <b>Square</b><br/> Corners: (-3,4), (4,3), (3,-4), (-4,-3)<br/> Circle:<br/><i>position:</i> (0,0)<br/> <i>radius:</i> 5/sqrt(2) </td> </tr> <tr> <td><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAABmJLR0QA/wD/AP+gvaeTAAAIm0lEQVR4nO2da3AV5RnHf7tnzyWHkxgMGCCIAhOIKIqj6EyhIA3WsdBQepOxdawzHcvQ1rbTtGqHdpziTIvU9kupQzv1CyLaliJoW9pSlZp8KDcbJVwScjENaMJJCJyQnNvu2w8JkoSTnD1nd8+N9/cxc7Lvc+af3+47u8+zAUlOoTi+gkABngB8jq/lHL9HIZiJhTIRSA0XvDs5Vu53fC27mRGC6aEmfPEqFEQmltQcXyGibeZvlX5OTXF8KdvZcCiEL/6DTIUBoDp6dEENIffMvAxjfhBKIh8Br2dyWWcDiWib2T834OgaTlHdFsIbr82kHeBkINKOtHAuEGlHWjgTiLQjbZwJRNqRNvYHIu2whP2BSDssYW8g0g7L2BuItMMy9gUi7b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f6aCrz0zbReNo1agekE8g4ltjKNWoHpNMGNPzsnfkO/Re5AupCTIf0ntUOd6jYXMsQBdhJkgrpBeKUJde4HWClc9EJS65xO8BKIHZbIu0ArPb22mmJtAOwGohdlkg7PsZ6R5wdlkg7PsZ6IFYtkXaMwp6eUSuWSDtGYU8g6Voi7bgK+7qq07FE2nEV9gWSqiXSjoTYO3eQiiXSjoTYG4hZS6Qd42L/ZI4ZS6Qd42J/IMkskXZMiDOzaxNZIu2YEGcCGc8SaUdSnJvuTGSJtCMpzgUy1hJpRw4gWMO5ohDP3CfonnQRQU22S7q2ESgMak0cmS4Y1JoQabQdSWxGUINASDtyCcE2aUcuIQrgvVwSiSQH+D88DzMWmQJy7QAAAABJRU5ErkJggg=="/></td><td> <b>Trapezoid</b><br/> Corners: (0,2), (2,2), (0,-2), (-1,0) <br/> Circle:<br/><i>position:</i> (0,0)<br/> <i>radius:</i> 2/sqrt(5) </td> </tr> <tr> <td><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAABmJLR0QA/wD/AP+gvaeTAAAMCElEQVR4nO2deXCU5R3HP8/77vtuks1J0sQgmsMAgYSgSBDwRg4dpd544F21nY467Yyo7bTqtKPTmVKntZejU8UqOh5V1HZURgQUWkC5EcIRgqAJ5CR3dvc9+oe7uIQcu5v33Sv7mWGGSd59fk/2s+/3fZ/nffZ9IUlMIaLdgVGLSSawEMhE8Pdod2d0YpKJyWJ6HavwSn3oQsNkcbS7NbowScNkIV3q+3ilHg7mdPBuuckzs0y8Uq9vTzmBI1r9TGhM0oDL6FbvQ9PmciRLY3tBBjV54Pa95VXHQJPWoxgdgS9NCrGKYCQEUnW0kxTtxf4/TgoZCaFK8KPqUNSuAP/u/6ukkFAJV0Ig5c0DxhUkhQSHFRICGSSuIClkcKyW4GeIuIKkkJOxS0IgQ8QVJIVERkIgQ8QVjFYhkZbgZ5i4gtEkJFoSAhkmriDRhcSChECGiStIRCGxJsFPEHEFiSI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rACVQLUi801uKvfNLeWjsiDWY8ZIXIENT2nzyoKXzz6NV6YWcMPuJh7+7DCXt/bwlQG7dYNBbuMSNhJQDExSZMpNk/XjMrn1kmLWFGcH10AMxRXY+Ng8QwjerMjnzYp8Stt6uXPrUW7bdpTcHi+1kqDeo/MN390CKZT7f/qf1HaGgLGqg1LN4EBOCi9NH8vrU/JpdIV4BSeG4gr8zw8xeZKDOU9wMMf2guOaNOZs62XBhh6m17gpatFpVwVNMrh18BgmXgMkr4mpCByywClBqgQFXhOnAQfzHayvSmHljDTWVqXQkjmCac8px3op6L4fwavW/ZXh4xcyFwj54SNW4NAQ1V+Qde5mxuS24MzswJnVjlMyEJoDvTMDb+sY+hrz6d14Hq07qmx54NvT0bgYlSRJkiRxzv8BUk0XfpyB72kAAAAASUVORK5CYII="/></td><td> <b>Kite</b><br/> Corners: (-1,1), (2,2), (1,-1), (-1,-1)<br/> Circle: <br/><i>position:</i> (~0.16228, ~0.16228) <br/><i>radius:</i> sqrt(10)-2 </td> </tr> </table>
algorithms
import numpy as np import scipy.optimize as spo def fit_biggest_circle(coords): coords = np.reshape(coords, (4, 2))[::-1] best_p, best_r = None, np.NINF for i in range(4): ps = np.roll(coords, i, axis=0) *p, r = circle_with_tangents(ps) if best_r < r <= distance(ps[3], ps[0], np.array(p)) + EPS: best_p, best_r = p, r return [best_p[0], best_p[1], best_r] EPS = 1e-9 def circle_with_tangents(ps): def h(pr): *p, r = pr return [distance(ps[i], ps[i + 1], p) - r for i in range(3)] return spo.broyden1(h, [ps[0][0], ps[0][1], 0]) def distance(p1, p2, p): return np.cross(p2 - p1, p - p1) / np.linalg.norm(p2 - p1)
Buying the Farm : Irrigation
5af4855c68e6449fbf00015c
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5af4855c68e6449fbf00015c
5 kyu
## Conway's Game of Life ... is a 2d cellular automaton where each cell has 8 neighboors and one of two states: alive or dead.<br> After a generation passes each cell either **stays alive**, **dies** or **is born** according to the following rules:<br> * if a living cell has 2 or 3 neighboors it stays alive * if a dead cell has exactly 3 neighboors it will be born * otherwise a cell will stay dead or die An example: ``` . X . . . . . . . . . . . . X . ---> X . X . ---> . . X . X X X . X = alive . X X . X . X . . . . . . = dead . X . . . X X . ``` ## ... In Reverse? While determining the successor to a given pattern is straight forward, the reverse process is not. There is no simple rule to calculate a predecessor.<br> Also most patterns have multiple predecessors and some have no predecessors at all, so called 'Garden of Edens'. ## The Task You're given a pattern, represented as a list of lists of integers, where 1 = alive and 0 = dead. <br>Write a function that returns one valid predecessor. <br>Since most predecessors have a larger bounding box than their successors, your solution should have dimensions `(m+2) x (n+2)` for an input with dimensions `m x n`. <br>If there is no such predecessor return `None`. <br>Your solution is valid, if it's successor is the goal pattern with only dead cells surrounding it. ```python find_predecessor(goal: List[List[int]]) -> List[List[int]] input_output_format = [[1,0,0,1,0] ,[0,1,1,0,0] ,[1,0,0,1,0] ,[0,0,0,0,1]] ``` ## Notes * For readability the patterns in the description and in the log are displayed with `'.'` and `'X'`, instead of `0` and `1` * The input pattern has dimensions mxn, m rows and n columns, 2 <= m,n < 8 * The world is finite. A corner cell for example has only 3 neighboors ## Examples ``` . . . . X . X goal: . . X X . find_predecessor(goal): . . . . . . . X X X X . . X X . X X . . . X X X X . . X . . . . . X . . . X X . . . . . goal: . . . . find_predecessor(goal): . . X . . . . X X . . . . X . . . X X . . . . X . . . . . . . . X . . . X . . . . X ``` Some inspiration: https://nbickford.wordpress.com/2012/04/15/reversing-the-game-of-life-for-fun-and-profit/
algorithms
def find_predecessor(p): H = len(p)+2 W = len(p[0])+2 Q = [[[] for i in range(W)] for j in range(H)] for i in range(H): for j in range(W): Q[min(H-1,i+1)][min(W-1,j+1)]+=[(i,j)] def valid(i,j,a): for i,j in Q[i][j]: c = p[i-1][j-1] if 0<i<H-1 and 0<j<W-1 else 0 d = sum(a[m][n] if 0<=m<H and 0<=n<W else 0 for m in (i-1,i,i+1) for n in (j-1,j,j+1)) if ((a[i][j],d) in ((0,3),(1,3),(1,4))) != c: return 0 return 1 def dfs(i,j,a): nonlocal A if j == W: i,j = i+1,0 if i == H: A = a for k in (0,1): if A: return a[i][j] = k if valid(i,j,a): dfs(i,j+1,a) A = None dfs(0,0,[[0]*W for e in range(H)]) return A
Game of Life in Reverse
5ea6a8502186ab001427809e
[ "Algorithms", "Cellular Automata" ]
https://www.codewars.com/kata/5ea6a8502186ab001427809e
1 kyu
_Molecules are beautiful things. Especially organic ones..._ <br> <hr> # Overview This time, you will be provided the name of a molecule as a string, and you'll have to convert it to the corresponding raw formula (as a dictionary/mapping). ### Input: ``` "5-methylhexan-2-ol" OH CH3 | | (the representation will be drawn in the console) CH3-CH-CH2-CH2-CH-CH3 ``` ### Output: ```python ParseHer("5-methylhexan-2-ol").parse() == {'C':7, 'H': 16, 'O': 1} ``` ```java new ParseHer("5-methylhexan-2-ol").parse(); Should be equal to the equivalent of that Map<String,Integer>: {"C":7, "H": 16, "O": 1} ``` ```javascript parse('5-methylhexan-2-ol') should be deep equal to {C:7, H: 16, O: 1} ``` <br> To do that, you'll have to accomplish two tasks: 1. Find a way to properly tokenize and then parse the name of the molecule, using the provided information (_you'll have to find out the proper grammar, like I did_ ;-p ). 2. Then build the complete raw formula and return it as a dictionary (key: chemical symbol as a string, value: number of this chemical element in the molecule). All inputs will be valid. <br> To help you in this task, several things are provided: * No chemistry knowledge is required: you'll find all the needed information below. <span style="color:gray; font-size:0.8em">(<i>Note: it's very long, yes, but a large majority of the strings needed are already provided in the solution setup, using different lists. Use them as you want</i> )</span> * To build the raw formula, being a chemist might be of some help, but don't worry if you are not: you'll just have to identify the patterns through the different tests. They are specifically designed so that these patterns can be found easily. <span style="color:gray; font-size:0.8em">(<i>Note: the related academical knowledge is about "degrees of insaturation" of the molecule, if you're interested in it. If you already know that, that will of course be of help, but if you do not, just focus yourself on the pattern recognition work, going through the sample tests, rather than trying to understand the notion with the wiki article (which is pretty bad about that </i>))</span> * All the molecules will be drawn in the console (except for the random tests and the very last fixed tests), so that you can see what it is exactly. <span style="color:gray; font-size:0.8em">(<i>Note: due to the need of escape characters</i> '\'<i> to represent some bounds, the strings in the example tests might not be very readable. Prefer to look at the version printed in the console</i> )</span> <br> ### Specifications of the tests: * 40 sample tests * around 85 fixed tests * 5500 random tests <br> <hr> <br> <div align="center"> <span style="color:orange; font-size:2em"><u><i>Nomenclature rules of organic compounds</i></u></span> <br> <span style="color:gray">(<i>Some of them, at least...</i>)</span> </div> <br> Here is what you need to know about the nomenclature of organic compounds. You'll actually get A LOT of information, here. Keep in mind that you'll get way more than what you actually need to solve the task, to ensure that you'll be able to find your way in the names if an assertion fails. So don't shy away just because of this... ;) _You'll find several summaries of all the information at the end of the description, to help you to find your way in all of this. And don't forget to read the very last section, well named_ "__the pins in the a**__", at the bottom of the description._ <br> <span style="color:gray"><i> <u>Notes to the chemists or those who bother:</u> <ul> <li>The names you'll encounter will always be "well formed", but they won't always be "the good one", especially in the random tests. Meaning, they will always represent an actual molecule/be parsable applying the rules below, but they could not be the real name for that molecule (for example: incorrect choice of the main chain, inversion of the numbering of the positions, ...). Those who know a bit about nomenclature could see them. For the others, don't bother with that, just apply the given rules ;) <li> To make the task manageable, having more consistent strings for the names, the positions of the groups/ramifications will be written following the way of the French nomenclature where the position is right on...the left... </i> XD <i>of the related part. Meaning, expect "butan-2-ol" instead of "2-butanol", and so on. </ul> </i></span> <br> <br> <span style="color:orange; font-size:2em"><b><i>Alkanes</i></b></span> <br> * <span style="color:orange; font-size:1.6em"><b><i>Linear alkanes</i></b></span> The name of linear molecules, such as in the examples below, are simply given by a "radical" representing their number of carbons, followed by the suffix `ane`: `radical + "ane"` ``` methane = meth + ane = 1 carbon -> CH4 ethane = eth + ane = 2 carbons -> CH3-CH3 propane = ... -> CH3-CH2-CH3 butane = ... -> CH3-CH2-CH2-CH3 ... RADICALS = ["meth", "eth", "prop", "but", "pent", "hex", "hept", "oct", "non", "dec", "undec", "dodec", "tridec", "tetradec", "pentadec", "hexadec", "heptadec", "octadec", "nonadec"] ``` You'll find the `RADICALS` list (up to 19 carbons) in the solution setup. <br> * <span style="color:orange; font-size:1.6em"><b><i>Ramified alkanes</i></b></span> If the molecule isn't linear, you can name it by picking a main chain, then add `alkyls` groups at the beginning of the name. You don't have to worry about the way the main chain is chosen or the way the numbering is done. Alkyls groups are defined this way: `positions + "-" + multiplier + radical + "yl"` (where the positions are numbers joined by commas ; multipliers are explained just after) ``` CH3-CH-CH2-CH3 -> main chain: like "butane" | CH3 -> alkyl: like "methane", at position 2 (on the main chain) => "2-methyl" (no multiplier since you have only one methyl group) => 2-methylbutane ``` <br> * <fspan style="color:orange; font-size:1.6em"><b><i>Several ramifications: multipliers</i></b></span> When you have several times the same alkyl group at different places, you add a multiplier: ``` CH3-CH-CH-CH2-CH-CH3 => 2,3,5-trimethylhexane | | | ^^^ CH3 CH3 CH3 CH3-CH-CH-CH2-CH-CH3 => 3-ethyl-2,5-dimethylhexane | | | ^^ CH3 CH2 CH3 | CH3 ``` You do not need to know about the order of the alkyls in the name. Here is the complete list of multipliers (from 2 to 19, provided in the solution setup): ``` MULTIPLIERS = [ "di", "tri", "tetra", "penta", "hexa", "hepta", "octa", "nona", "deca", "undeca", "dodeca", "trideca", "tetradeca", "pentadeca", "hexadeca", "heptadeca", "octadeca", "nonadeca"] ``` <br> <br> <span style="color:orange; font-size:2em"><b><i>Cycles</i></b></span> <br> When a chain or a group has a cyclic shape, you just add the `cyclo` prefix before the radical part (both for the main chain or alkyls): ``` CH2-CH2 | | => cyclobutane CH2-CH2 CH3-CH-CH2-CH2-CH2-CH2-CH-CH3 | | CH CH => 2,7-dicyclobutyloctane / \ / \ ^^^^^ H2C CH2 H2C CH2 \ / \ / CH2 CH2 ``` The `"cyclo"` prefix is considered as part of the radical it is "applied" to. So in case of ramifications, the order of the different parts of the name is: ``` CH2-CH-CH2-CH3 The main chain being the cyclic one: | | => 1-ethylcyclobutane CH2-CH2 ^^^^^ ``` <br> <br> <span style="color:orange; font-size:2em"><b><i>Alkenes & alkynes</i></b></span> <br> * __alkene:__ double bound between carbons. Replace the suffix `ane` by `"-" + positions + "-" + multiplier + "ene"` (only the position of the first carbon holding a double bound is given) * __alkyne:__ triple bound between carbons. Replace the suffix `ane` by `"-" + positions + "-" + multiplier + "yne"` (only the position of the first carbon holding a triple bound is given) * If you have both alkenes and alkynes in the molecule, you replace `ane` with `...en...yne` (double bounds always come first) ``` CH3-CH=CH-CH2-CH2-CH3 => hex-2-ene CH3-CH=CH-CH2-CH=CH2 => hex-1,4-diene (warning: the numbering is reversed, here) CH3-C{=}C-CH2-CH2-CH3 => hex-2-yne ('{=}' used to represent the three bounds) ``` You can mix up the things...: ``` CH3-C{=}C-CH=CH-C{=}C-C{=}C-CH=CH-CH2-CH3 => tridec-4,10-dien-2,6,8-triyne ``` ...or even find those in the alkyl groups: ``` CH3-C{=}C-CH-C{=}C-CH2-CH2-CH=CH-CH3 -> main chain | CH2-CH=CH-CH=CH-CH2-CH3 -> ramification (note: position 1 is always the C bounded to the main chain) => 4-hept-2,4-dienylundec-9-en-2,5-diyne ``` <br> <br> <span style="color:orange; font-size:2em"><b><i>Ramifications of ramifications</i></b></span> <br> Here comes the "funny" work... If a ramification itself is ramified, same rules as above are applied. But to identify the lower level, squared brackets are used around the prefix of lower level, this part being put just before the radical part of the alkyl group at the current level... Well, an example might be better: `positions + "-" + multiplier + "[" + subramification + "]" + radical + "yl"` Examples: ``` No subramifications: CH2-CH-CH2-CH2-CH2-CH2-CH2-CH2-CH3 => 1-heptylcyclobutane | | CH2-CH2 With subramifications: CH2-CH2-CH3 | CH2-CH-CH2-CH2-CH-CH2-CH2-CH2-CH3 => 1-[3-propyl]heptylcyclobutane | | CH2-CH2 CH2-CH2-CH3 | CH2-CH-CH2-CH2-CH-CH2-CH2-CH2-CH3 | | => 1,2-di[3-propyl]heptylcyclobutane CH2-CH-CH2-CH2-CH-CH2-CH2-CH2-CH3 | (Note here: "1,2-di" applies to the whole "[3-propyl]heptyl" part) CH2-CH2-CH3 ``` This goes recursively at any depth: ``` CH3 CH3 | | CH2 CH2-CH-CH3 | | CH2-CH-CH-CH2-CH-CH2-CH2-CH2-CH3 | | => 1,2-di[1-ethyl-3-[2-methyl]propyl]heptylcyclobutane CH2-CH-CH-CH2-CH-CH2-CH2-CH2-CH3 | | CH2 CH2-CH-CH3 | | CH3 CH3 ``` <br> <br> <span style="color:orange; font-size:2em"><b><i>Functions</i></b></span> <br> On the top of that, you can have "functional groups" in the molecule. Such as alcohols, esters, carboxylic acids, and so on. Basically, you can find those functional group at two different places: * <u>At the very end of the name, as suffix:</u> Then, this is called the "main function". The ending `e` of the name is replaced by the appropriate `positions + "-" + multiplier + suffix` corresponding to the function. * <u>Amongst the prefixes of the related carbon chain:</u> It then behaves in the same manner than the alkyl groups: `positions + "-" + multiplier + prefix`, except that most of those functional groups cannot have subramifications (generally... there are some exceptions, see details below). Note that for a same type of functional group, prefix(es) and suffix names are different _<span style="color:gray; font-size:.8em">(The reason of these two naming is that only one type of function can be used as suffix (we won’t see how/why), so all the other ones of the molecule have to show up as prefixes)</span>_. You may find below the information relative to all the functional groups used in the kata. <br> <br> ## ___Simple functions___ <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Halogens:</u></i></b></span> always used as prefixes. ``` F -> prefix = "fluoro" Cl -> prefix = "chloro" Br -> prefix = "bromo" I -> prefix = "iodo" CH3-CH2-CH2-CH2-CH2-F -> "1-fluoropentane" CH3-CH-CH2-CH2-CH3 -> "2-chloropentane" | Cl CH3-CH-CH2-CH2-CHBr2 -> "1,1-dibromo-4-chloropentane" | Cl ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Alcohols:</u></i></b></span> ``` OH -> prefix = "hydroxy" suffix = "ol" OH | CH3-CH-CH2-CH2-CH3 -> "pentan-2-ol" HO CH2-OH | | CH3-CH-CH-CH2-CH2-OH -> "3-[1-hydroxy]methylpentan-1,4-diol" ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Thiols:</u></i></b></span> ``` SH -> prefix = "mercapto" suffix = "thiol" SH | CH3-CH-CH2-CH2-CH3 -> "pentan-2-thiol" HO CH2-CH2-SH | | CH3-CH-CH-CH2-CH2-OH -> "3-[2-mercapto]ethylpentan-1,4-diol" ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Imines:</u></i></b></span> ``` =NH -> prefix = "imino" suffix = "imine" H3C-CH2-CH2-C-CH3 || -> "pentan-2-imine" NH OH | H3C-CH2-CH-C-CH3 || -> "2-iminopentan-3-ol" NH (Note: in this kata, the nitrogen of an imine will never hold a carboned chain, even if it could be possible) ``` <br> <br> ## ___A bit less simple functions___ <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Ketones:</u></i></b></span> They can never be on an extremity of a chain. ``` =O -> prefix = "oxo" suffix = "one" O || -> "pentan-2-one" CH3-C-CH2-CH2-CH3 CH3 | H3C CH2-C=O -> "4-[1-oxo]ethylheptan-2,6-dione" \ | C-CH-CH2-C-CH3 (note that the ethyl ramification is the // || chain of 2 carbons on the very left, here) O O ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Aldehydes:</u></i></b></span> Like ketones, but only present on an extremity. The aldehydes are a bit special about two points: 1. Their prefix: until now, prefixes and suffixes represented always the exact same thing. For the aldehydes, the prefix represents the same kind of functional group, but it holds an extra carbon and its hydrogen. See examples below. 1. Since they always are at an extremity, one are not forced to give their position, when used as suffixes (you can consider this as an _elision:_ see the last part of the description). For the prefix version, one still needs it since the "carbon at the extremity" is already in the `formyl` group and so, it can be anywhere in the molecule. ``` -CH=O -> prefix = "formyl" (anywhere on a chain) =O -> suffix = "al" (as ketones, but only at an extremity) CH3-CH2-CH2-CH2-CH=O -> "pentanal" CH2-CH2-CH=O | HC-CH2-CH-CH2-CH2-CH=O -> "4-[1-formyl]methylheptandial" // O Note about this last example: - The ramification still is the leftmost part (O=CH-CH2-...), but since the formyl group holds the last carbon, the radical used for the ramification has only 1 carbon left and is "methyl". - No positional information for the suffixes, but present for the prefix if no elision (see last section). ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Carboxylic acids:</u></i></b></span> They behave a bit like the aldehydes, having prefix and suffixes that represent the same functional group, but with 1 extra carbon in some cases. Positions are generally omitted when using suffixes too (same as for the aldehydes). ``` Suffix type 1: "oic acid" (note the presence of the space character). OH OH "ethanoic acid" | example: | (the carbon of the function is in the main chain) ...-(C)=O H3C-C=O Suffix type 2: "carboxylic acid" (used in some special cases. Don't bother with the how and the why) OH OH -> "methancarboxylic acid" | example: | ^^^^ ...-C=O H3C-C=O (which is incorrect, but will show you that the carbon of the function isn't considered as a part of the main chain, here) Prefix: "carboxy" OH | -> "4-carboxyheptan-1,7-dioic acid" OH CH2-CH2-C=O | example: | (for this time, let's do this with the positions... ;) ) ...-C=O HO-C-CH-CH2-CH2-C=O // | O OH ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Amides:</u></i></b></span> We will use simple cases only, for the amides, here: their nitrogen atom will never hold a carboned chain. Amides are always at an extremity of a chain. ``` NH2 Suffix: "amide" | Prefix: "amido" ...-(C)=O H2N-CH=O -> "methanamide" O=C-CH2-CH=CH-CH3 -> "pent-3-enamide" | NH2 O=C-CH2-CH2-CH2-C=O -> "5-amidopentanoic acid" | | NH2 OH Note that the carbon isn't part of the function, but is part of the radical. ``` <br> <br> ## ___Complex cases___ <br> The following cases all need auxiliary chains or present some weird behaviors. <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Amines, phosphines, arsines:</u></i></b></span> Those three have the same behavior and a strong particularity: they can be used with two different kinds of nomenclatures, and can hold zero or more carboned chains. Let's review this in details... ``` As suffixes: "amine", "phosphine", "arsine" * WAY 1: The function itself is considered as the main chain, and all carboned chains -------- (up to three of them) around are alkyls. * WAY 2: Not the general case, but they can be used the same way than the previous functions. -------- Examples: WAY 1 WAY 2 H3C-NH2 "methylamine" "methan-1-amine" H3C-PH2 "methylphosphine" "methan-1-phosphine" H3C-AsH2 "methylarsine" "methan-1-arsine" H3C-N-CH2-CH3 "ethyldimethylamine" "ethan-1-[dimethyl]amine" | CH3 Way 2 is actually used in this type of cases: H2N-H2C-CH2-CH2-CH2-CH2-CH2-NH2 hexan-1,6-diamine (the "cadavérine", in French... What a beautiful name... ;p ) ``` Prefixes, on the other side, behaves in the "usual" way only, except that the functions can hold subramifications. ``` Prefixes: "amino", "phosphino", "arsino" OH | -> "1,6-diaminohexan-3-ol" H2N-H2C-CH2-CH-CH2-CH2-CH2-NH2 OH | -> "1-amino-6-[diethyl]arsinohexan-3-ol" H2N-H2C-CH2-CH-CH2-CH2-CH2-As-CH2-CH3 | (there are no position to give for the ethyl groups CH2-CH3 since they are bound to the arsenic atom, not to a chain) ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Ethers:</u></i></b></span> They have a lot in common with the previous ones, but there is only the "way 1" for the suffix. So, no main chain, and (always) two alkyls since ethers are made with oxygen. ``` As suffix: "alkylether" Examples: H3C-CH2-O-CH2-CH3 "diethylether" H3C-O-CH=CH-CH3 "methylprop-1-enylether" Prefix: "alkoxy" Examples: H3C-O-CH2-CH2-CH2-OH "3-methoxypropan-1-ol" ^^^^^ ^^^^^^^ Note that the radical is use "raw". Though, if a multiple bound was in the auxiliary chain: H2C=CH-CH2-O-CH2-CH2-CH2-OH "3-prop-2-enoxypropan-1-ol" ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Esters:</u></i></b></span> They need an auxiliary carboned chain (alkyl). Their general form as suffix is: Suffix: `alkyl alkanoate` ``` O || Main chain, as "alkan": the one beginning with the "(C)", in between the two oxygens. ...-(C)-O-R Auxiliary chain, as "alkyl": the "R", separated from the main chain by the oxygen. ``` Note that: * The carbon of the main chain is... part of the main chain, not of the function. * Here, you have to deal with two separated words again. Examples: ``` O || -> "propyl ethanoate" CH3-C-O-CH2-CH2-CH3 O || -> "methyl butanoate" CH3-O-C-CH2-CH2-CH3 O || -> "eth-1-enyl hept-2-enoate" CH3-CH2-CH2-CH2-CH=CH-C-O-CH=CH2 ``` Due to their structure, esters as prefixes can be in two different form: Prefix type 1: `alkoxycarbonyl` ``` O || Main chain, as "...": the carbon of the function is NOT part of the main chain. ...-C-O-R Auxiliary chain, as "alk": the "R", separated by the oxygen. Example: CH3 vvvvvvvvvvvvvv vvvvvvvvvvv | -> "4-ethoxycarbonylpentanoic acid" CH3-CH2-O-C-CH-CH2-CH2-C=O || | (note the absence of squared brackets, here O OH and the lack of "yl" in the auxiliary chain) ``` Prefix type 2: `alkanoyloxy...` ``` O || Main chain, as "...". ...-O-(C)-R Auxiliary chain, as "alkan": the "R", WITH the carbon in between the two oxygens Example: CH3 vvvvvvvvvvvv vvvvvvvvvvv | -> "4-propanoyloxypentanoic acid" CH3-CH2-C-O-CH-CH2-CH2-C=O || | O OH (note the absence of squared brackets, again) Put a double bound in the auxiliary chain and with this prefix, it would become ""prop-2-enoyloxy..." ``` <br> * <span style="color:orange; font-size:1.4em"><b><i><u>Aromatic cycles:</u></i></b></span> These are actually a special kind of radicals. We will focus our effort on only one simple case: the benzene. ``` * Used as main chain: "benzene", C6Hx (base: C6H6, less H if substituted) HC-CH // \\ HC CH It can of course hold ramifications and functions. \ / HC=CH CH2-CH3 / HC-C // \\ HC C-CH=O -> "2-ethyl-1-formylbenzene" \ / HC=CH * Used as ramification: "phenyl", C6H5 HC-CH OH // \\ | HC C-CH2-CH2-CH2-CH2-C=O -> "5-phenylpentanoic acid" \ / HC=CH ``` _<span style="color:gray; font-size:.8em"><u>To the chemists:</u> to keep the things simpler, we won't consider cases like phenol, benzoyl, ... A phenol, if it should occur, would be called "benzenol" instead, and so on.</span>_ <br> <br> <br> <span style="color:orange; font-size:2em"><b><i>Summaries</i></b></span> <br> * ## _General form of a name_ So, ___out of some exceptions___, the name of an organic compound can be seen as something like that: `[[...]subparts]prefixes + radical + suffixes` With: ``` suffixes = alkenes, alkynes, functional groups prefixes = functional groups (as prefixes), subchains, "cyclo" subchains = [other prefixes] + (cyclo) + radical + (alkenes or alkynes) + "yl" or functional groups as prefixes subparts = subchains ``` _<span style="color:gray">Note: this is NOT a reliable BNF diagram but only some sort of helper around which I hope you'll be able to gather your thoughts.</span>_ <br> * ## _Radicals and multipliers_ ``` Number Radical Multiplier ------ ------- ---------- #1 meth / #2 eth di #3 prop tri #4 but tetra #6 pent penta #6 hex hexa #7 hept hepta #8 oct octa #9 non nona #10 dec deca #11 undec undeca #12 dodec dodeca #13 tridec trideca #14 tetradec tetradeca #15 pentadec pentadeca #16 hexadec hexadeca #17 heptadec heptadeca #18 octadec octadeca #19 nonadec nonadeca ``` <br> * ## _Miscellaneous_ ``` Alkanes ane Alkenes ene Alkynes yne Alkyls yl Cycles cyclo ``` <br> * ## _Functional groups_ ``` Note about the "Chemical group" representations: * When you see "(C)", that means the carbon is already counted in the main chain: you do not have to add a new one to build the function. * Warning with the representations of carboxylic acids, amides or esters: be aware of the double bound with one of the "O" (see details upper) Functional group Prefix Suffix Chemical group Notes ---------------- ------ ------ -------------- ----- halogens fluoro . ...-F chloro . ...-Cl bromo . ...-Br iodo . ...-I alcohol hydroxy ol ...-OH thiol mercapto thiol ...-SH ketone oxo one ...(C)=O Never at an extremity of the chain aldehyde . al ...(C)H=O Only at an extremity of the main chain formyl . ...CH=O 1 extra carbon, here! carboxylic acid . oic acid ...(C)O-OH Only at an extremity of the main chain . carboxylic acid ...-CO-OH 1 extra carbon, here! carboxy . ...-CO-OH 1 extra carbon, here! ester . (alkyl) ...oate ...(C)O-O-R R being a secondary alkyl chain (see details above). Only at an extremity of the main chain (alk)oxycarbonyl . ...(C)-CO-O-R Anywhere on the chain. R being a secondary alkyl chain (see details above) (alkan)oyloxy . ...(C)-O-OR Anywhere on the chain. R being a secondary alkyl chain (see details above) ether (alk)oxy (alkyles)ether R1-O-R2 R1 and R2 being alkyles if suffix, or R2 being the main chain if prefix (see details above) amine (alkyles)amino amine N (various) See details above about the different possibilities amide amido amide ...(C)O-NH2 Only at an extremity imine imino imine ...(C)=NH arsine (alkyles)arsino (alkyles)arsine As (various) See details above about the different possibilities phosphine (alkyles)phosphino (alkyles)phosphine P (various) See details above about the different possibilities aromatic cycle . benzene C6Hx (various) See details above about the different possibilities phenyl . ...-C6H5 ``` <br> * ## _Valence number of all the atoms involved_ The valence number is the number of bounds (understood as number of strokes going away from the atom) that this chemical element makes with other atoms. Any atom has to hold this exact number in any molecule. ``` 1 | 2 | 3 | 4 -----|-----|-----|----- Br | O | As | C Cl | S | N | F | | P | H | | | I | | | ``` <br> <br> <span style="color:orange; font-size:1.6em"><b><i>The "pinS in the a**" section...</i></b></span> <br> Well, yes... Sadly, you're not completely done with it yet... <br> * ## _Elisions of some positions_ Chemists are clearly not computer guys (or at least, those who established the rules of nomenclature). That means... It happens a lot that they suppress some tiny parts of a name if they think about those as not meaningful or cumbersome ones, or even add some if they find that more beautiful or hearable or... For our own sake, we will manage only one of those cases: the elision of the positions of groups or functions on the first carbon of a chain (but exclusively present at this position): "cyclobutan-1-ol" => "cyclobutanol" "cyclobutan-1,1-diol" => "cyclobutandiol" "cyclobutan-1,2-diol" => "cyclobutan-1,2-diol" (no elision because not only "one(s)", here) Note that elision is not systematic, so your code will have to manage both cases. Elision can of course be applied to any kind of part of the name that requires a position number, like in `"chlorocyclobutane"`, for example. <br> * ## _Ambiguous matches when parsing the name of a molecule_ If you encounter some ambiguous cases that aren't clearly identifiable, assume you get the longest possible chain name. But ONLY if the match is ambiguous! Some examples: "2,3,5-tridecyl" => NOT ambiguous: this is three "decyl" chains "2-tridecyl" => NOT ambiguous: this is one "tridecyl" at position 2 "tridecylamine" => AMBIGUOUS, because the amine function could hold up to 3 chains, so assume it is one "tridecyl" chain <br> <hr> <br> <span style="color:orange; font-size:1.4em"><b><i>Good <s>luck!!</s>... work!!</i></b></span> <br> [_The Full Metal Chemist collection_](https://www.codewars.com/collections/full-metal-chemist-collection) <br>
games
from collections import UserDict from enum import Flag, auto import re class TokenType(Flag): POS_MULT, MULT, RAD = auto(), auto(), auto() LS, RS, SPACE, E = auto(), auto(), auto(), auto() AN, EN, YN, YL = auto(), auto(), auto(), auto() CYCLO, BENZEN, PHEN = auto(), auto(), auto() FLUORO, CHLORO, BROMO, IODO = auto(), auto(), auto(), auto() HYDROXY, MERCAPTO = auto(), auto() IMINO, OXO, FORMYL = auto(), auto(), auto() CARBOXY, AMIDO = auto(), auto() AMINO, PHOSPHINO, ARSINO = auto(), auto(), auto() OXY, OXYCARBONYL, OYLOXY = auto(), auto(), auto() OL, THIOL = auto(), auto() IMINE, ONE, AL = auto(), auto(), auto() OIC_ACID, AMIDE = auto(), auto() AMINE, PHOSPHINE, ARSINE = auto(), auto(), auto() ETHER, CARBOXYLIC_ACID, OATE = auto(), auto(), auto() @property def pattern(self): default_pattern = self.name.replace("_", " ").lower() return { TokenType.LS : r"\[", TokenType.RS : r"\]", TokenType.SPACE: r" ", }.get(self, default_pattern) class RawFormula(UserDict): WEIGHTS = { k: v for v, ks in enumerate(( ("DoU",), ("F", "Cl", "Br", "I"), ("O", "S"), ("N", "P", "As"), ("C",) ), -2) for k in ks } def to_molecular_formula(self): atoms, hydrogen = [], 2 for k, v in self.items(): atoms += [(k, v)] * (k != "DoU") hydrogen += v * self.WEIGHTS[k] if hydrogen < 0: raise Exception("Serious violation of octet rule") atoms += [("H", hydrogen)] * (hydrogen > 0) return dict(sorted(atoms)) def __iadd__(self, other): for k, v in other.items(): if k not in self: self[k] = 0 self[k] += v return self def __add__(self, other): raw_formula = self.copy() raw_formula += other return raw_formula def __imul__(self, other): for k, v in self.items(): self[k] = other * v return self def __mul__(self, other): raw_formula = self.copy() raw_formula *= other return raw_formula class Token: MULTIPLIERS = ("di", "tri", "tetra", "penta", "hexa", "hepta", "octa", "nona", "deca", "undeca", "dodeca", "trideca", "tetradeca", "pentadeca", "hexadeca", "heptadeca", "octadeca", "nonadeca") RADICALS = ("meth", "eth", "prop", "but", "pent", "hex", "hept", "oct", "non", "dec", "undec", "dodec", "tridec", "tetradec", "pentadec", "hexadec", "heptadec", "octadec", "nonadec") MULT_DICT = {m: i for i, m in enumerate(("",) + MULTIPLIERS, 1)} RAD_DICT = {m: i for i, m in enumerate(RADICALS, 1)} POS_MULT = (*(fr"-?[1-9]\d*(?:,[1-9]\d*){{{i}}}-{m}" for i, m in enumerate(("",) + MULTIPLIERS)),) RAD_MULT = ( "meth", "prop", "but", "di", "e(?:th(?:er)?|n?)", "(?:pent|hex|hept|oct|non)(?:a(?!n)(?:dec(?:a(?!n))?)?)?", "(?:un|do)?dec(?:a(?!n))?", "t(?:ri|etra)(?:dec(?:a(?!n))?)?", ) FUNCS = ( "oic acid" , "formyl" , "[\[\] ]" , "[ay][nl]" , "(?:ph|benz)en" , "(?:am|phosph|ars|im)in[eo]" , "(?:thi)?ol" , "carboxy(?:lic acid)?" , "o(?:at|n)e" , "amid[eo]" , "(?:flu|chl)oro" , "(?:cycl|brom|iod|mercapt|ox)o", "(?:hydr|oyl)oxy", "oxy(?:carbonyl)?" , ) TOKENIZER = re.compile("|".join(RAD_MULT + FUNCS + POS_MULT)) RAWS = { TokenType.CYCLO : RawFormula(DoU=1) , TokenType.FLUORO : RawFormula(F=1) , TokenType.EN : RawFormula(DoU=1) , TokenType.CHLORO : RawFormula(Cl=1) , TokenType.YN : RawFormula(DoU=2) , TokenType.BROMO : RawFormula(Br=1) , TokenType.IODO : RawFormula(I=1) , TokenType.HYDROXY : RawFormula(O=1) , TokenType.MERCAPTO : RawFormula(S=1) , TokenType.OL : RawFormula(O=1) , TokenType.THIOL : RawFormula(S=1) , TokenType.OXO : RawFormula(O=1, DoU=1) , TokenType.FORMYL : RawFormula(C=1, O=1, DoU=1), TokenType.ONE : RawFormula(O=1, DoU=1) , TokenType.AL : RawFormula(O=1, DoU=1) , TokenType.CARBOXY : RawFormula(C=1, O=2, DoU=1), TokenType.OXYCARBONYL: RawFormula(C=1, O=2, DoU=1), TokenType.OIC_ACID : RawFormula(O=2, DoU=1) , TokenType.OYLOXY : RawFormula(O=2, DoU=1) , TokenType.CARBOXYLIC_ACID: RawFormula(C=1, O=2, DoU=1), TokenType.OATE : RawFormula(O=2, DoU=1) , TokenType.OXY : RawFormula(O=1) , TokenType.AMINO : RawFormula(N=1) , TokenType.ETHER : RawFormula(O=1) , TokenType.AMINE : RawFormula(N=1) , TokenType.AMIDO : RawFormula(O=1, N=1, DoU=1), TokenType.IMINO : RawFormula(N=1, DoU=1) , TokenType.AMIDE : RawFormula(O=1, N=1, DoU=1), TokenType.IMINE : RawFormula(N=1, DoU=1) , TokenType.ARSINO : RawFormula(As=1) , TokenType.PHOSPHINO : RawFormula(P=1) , TokenType.ARSINE : RawFormula(As=1) , TokenType.PHOSPHINE : RawFormula(P=1) , TokenType.PHEN : RawFormula(C=6, DoU=4) , TokenType.BENZEN : RawFormula(C=6, DoU=4) , } REGEXES = dict(( *((v, re.compile(v.pattern)) for v in TokenType.__members__.values()), (TokenType.POS_MULT, re.compile(fr"-?[1-9]\d*(?:,[1-9]\d*)*-((?:{'|'.join(MULTIPLIERS)})?)")), (TokenType.MULT , re.compile("|".join(MULTIPLIERS))), (TokenType.RAD , re.compile("|".join(RADICALS))), )) @classmethod def tokenize(cls, string): unknowns = re.search("\S+", cls.TOKENIZER.sub(" ", string)) if unknowns: raise Exception(f"Unknown token: '{unknowns[0]}'") return tuple(map(Token, cls.TOKENIZER.findall(string))) def __init__(self, token_str): for t, pattern in self.REGEXES.items(): m = pattern.fullmatch(token_str) if m is None: continue self.type_, self.str_ = t, token_str if t == TokenType.POS_MULT: self.values = (token_str[0] != "-", self.MULT_DICT[m[1]]) elif t == TokenType.MULT: self.values = (self.MULT_DICT[token_str],) elif t == TokenType.RAD: self.values = (self.RAD_DICT[token_str],) else: self.values = () return raise Exception(f"Unknown token: '{token_str}'") def __repr__(self): return "Token(type={}, string='{}'{})".format( self.type_, self.str_, f", values={self.values}" if self.values else "" ) @property def raw_formula(self): if self.type_ in self.RAWS: return self.RAWS[self.type_].copy() raise Exception(f"No raw formula for token of type {self.type_}") class ParseHer: SIMPLE_FUNC = TokenType.FLUORO | TokenType.CHLORO | TokenType.BROMO | TokenType.IODO | TokenType.HYDROXY | TokenType.MERCAPTO | TokenType.IMINO | TokenType.OXO | TokenType.FORMYL | TokenType.CARBOXY | TokenType.AMIDO APA_PRE = TokenType.AMINO | TokenType.PHOSPHINO | TokenType.ARSINO APA_SUF = TokenType.AMINE | TokenType.PHOSPHINE | TokenType.ARSINE SIDE_CHAIN = TokenType.YL | SIMPLE_FUNC | APA_PRE | TokenType.OYLOXY | TokenType.OXY | TokenType.OXYCARBONYL NONAR_PRE = TokenType.IMINE | TokenType.ONE | TokenType.AL | TokenType.OIC_ACID | TokenType.AMIDE HYDRO_PRE = TokenType.OL | TokenType.THIOL | TokenType.CARBOXYLIC_ACID def __init__(self, name): self.name = name def parse(self): self.i, self.tokens = 0, Token.tokenize(self.name)[::-1] self.n = len(self.tokens) raw_formula = self._parse_organic_compound() if self.i < self.n: raise Exception(f"There are remaining tokens: {self.tokens[self.i:]}") return raw_formula.to_molecular_formula() def _peek(self, token_type): return self.i < self.n and self.tokens[self.i].type_ in token_type def _eat(self, token_type): if self.i >= self.n: raise Exception(f"Unexpected EOF while expecting token of type {token_type}") token = self.tokens[self.i] if token.type_ not in token_type: raise Exception(f"Token type mismatch, expecting {token_type} instead of {token.type_}") self.i += 1 return token def _parse_organic_compound(self): if self._peek(TokenType.OATE): return self._parse_oate() if self._peek(TokenType.E | self.NONAR_PRE | self.HYDRO_PRE): return self._parse_simple_organic_compound() if self._peek(self.APA_SUF): return self._parse_apa_organic_compound() return self._eat(TokenType.ETHER).raw_formula + self._parse_mult_hydro() def _parse_pos_mult_or_mult(self): try: token = self._eat(TokenType.POS_MULT | TokenType.MULT) return (False,) * (token.type_ == TokenType.MULT) + token.values except: return False, 1 def _parse_radical(self): return RawFormula(C=self._eat(TokenType.RAD).values[0]) def _parse_nonarene_prefix(self, init_flag=True): raw_formula, flag = RawFormula(), init_flag if self._peek(TokenType.YN): raw_formula += self._eat(TokenType.YN).raw_formula * self._parse_pos_mult_or_mult()[1] flag = False if self._peek(TokenType.EN): raw_formula += self._eat(TokenType.EN).raw_formula * self._parse_pos_mult_or_mult()[1] flag = False if flag: self._eat(TokenType.AN) raw_formula += self._parse_radical() if self._peek(TokenType.CYCLO): raw_formula += self._eat(TokenType.CYCLO).raw_formula return raw_formula def _parse_hydrocarbon_prefix(self): if self._peek(TokenType.BENZEN): return self._eat(TokenType.BENZEN).raw_formula return self._parse_nonarene_prefix() def _parse_hydrocarbon_group_prefix(self): if self._peek(TokenType.PHEN): raw_formula = self._eat(TokenType.PHEN).raw_formula else: raw_formula = self._parse_nonarene_prefix(False) if self._peek(TokenType.RS): self._eat(TokenType.RS) raw_formula += self._parse_side_chains() self._eat(TokenType.LS) return raw_formula def _parse_hydrocarbon_group(self): self._eat(TokenType.YL) return self._parse_hydrocarbon_group_prefix() def _parse_mult_hydro(self): raw_formula = RawFormula() while True: raw_formula += self._parse_hydrocarbon_group() * self._parse_pos_mult_or_mult()[1] if not self._peek(TokenType.YL): break return raw_formula def _parse_side_chains(self): raw_formula = RawFormula() while True: tmp_raw_formula = self._parse_side_chain() flag, num = self._parse_pos_mult_or_mult() raw_formula += tmp_raw_formula * num if flag or not self._peek(self.SIDE_CHAIN): break return raw_formula def _parse_side_chain(self): if self._peek(TokenType.YL): return self._parse_hydrocarbon_group() if self._peek(self.SIMPLE_FUNC): return self._eat(self.SIMPLE_FUNC).raw_formula return self._parse_complex_functional_group() def _parse_complex_functional_group(self): if self._peek(TokenType.OYLOXY): return self._parse_oyloxy() if self._peek(TokenType.OXY | TokenType.OXYCARBONYL): return self._eat(TokenType.OXY | TokenType.OXYCARBONYL).raw_formula + self._parse_hydrocarbon_group_prefix() return self._parse_apa(True) def _parse_oyloxy(self): raw_formula = self._eat(TokenType.OYLOXY).raw_formula + self._parse_nonarene_prefix() if self._peek(TokenType.RS): self._eat(TokenType.RS) raw_formula += self._parse_side_chains() self._eat(TokenType.LS) return raw_formula def _parse_apa(self, is_prefix=False): raw_formula = self._eat(self.APA_PRE if is_prefix else self.APA_SUF).raw_formula if self._peek(TokenType.RS): self._eat(TokenType.RS) raw_formula += self._parse_mult_hydro() self._eat(TokenType.LS) return raw_formula def _parse_hydrocarbon_derivative(self): func = self._parse_hydrocarbon_prefix if self._peek(self.NONAR_PRE): raw_formula = self._eat(self.NONAR_PRE).raw_formula func = self._parse_nonarene_prefix elif self._peek(self.HYDRO_PRE): raw_formula = self._eat(self.HYDRO_PRE).raw_formula else: raw_formula = self._parse_apa() raw_formula *= self._parse_pos_mult_or_mult()[1] return raw_formula + func() def _parse_oate(self): raw_formula, tmp_raw_formula = RawFormula(), self._eat(TokenType.OATE).raw_formula _, num = self._parse_pos_mult_or_mult() raw_formula += self._parse_nonarene_prefix() if self._peek(self.SIDE_CHAIN): raw_formula += self._parse_side_chains() self._eat(TokenType.SPACE) tmp_raw_formula += self._parse_hydrocarbon_group() return raw_formula + tmp_raw_formula * num def _parse_simple_organic_compound(self): if self._peek(TokenType.E): self._eat(TokenType.E) raw_formula = self._parse_hydrocarbon_prefix() else: raw_formula = self._parse_hydrocarbon_derivative() if self._peek(self.SIDE_CHAIN): raw_formula += self._parse_side_chains() return raw_formula def _parse_apa_organic_compound(self): raw_formula = self._eat(self.APA_SUF).raw_formula if self._peek(TokenType.YL): return raw_formula + self._parse_mult_hydro() if self.i >= self.n: return raw_formula self.i -= 1 raw_formula = self._parse_hydrocarbon_derivative() if self._peek(self.SIDE_CHAIN): raw_formula += self._parse_side_chains() return raw_formula
Full Metal Chemist #2: parse me...
5a529cced8e145207e000010
[ "Regular Expressions", "Puzzles" ]
https://www.codewars.com/kata/5a529cced8e145207e000010
1 kyu
## Task This kata is about the <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem" target="_blank">travelling salesman problem</a>. You have to visit every city once and return to the starting point. You get an adjacency matrix, which shows the distances between the cities. The total cost of path is defined as the sum of distances to travel from 1st city to the 2nd, from 2nd to 3rd, ..., and, finally, from last city to the 1st. Your task is to write a function, that returns a valid path with `same or smaller cost`, as compared to the reference solution. ```if:javascript,php,ruby Return a valid route as an `array`. ``` ```if:python Return a valid route as a `list`. ``` ```if:csharp Return a valid route as a`List<Int32>`. ``` ```if:java Return a valid route as an `ArrayList<Integer>`. ``` The "names" of the places are the indexes in the array, here is an example for a matrix: ``` 0 1 2 0 0 5 7 1 5 0 4 2 7 4 0 ``` The starting point is always place `0`. The routes are symmetric means the distance from `0` to `1` is always the same as from `1` to `0`. Example: ```js let matrix = [ [0, 9, 5], [9, 0, 4], [5, 4, 0], ]; return [0,1,2,0]; //you could also return [0,2,1,0] ``` ```php $matrix = [ [0, 9, 5], [9, 0, 4], [5, 4, 0], ] return [0,1,2,0]; //you could also return [0,2,1,0] ``` ```java int[][] matrix = new int[][]{ {0, 9, 5}, {9, 0, 4}, {5, 4, 0}, }; return new ArrayList<Integer>(Arrays.asList(0,1,2,0)); //you could also return [0,2,1,0] ``` ```csharp int[][] matrix = new int[][]{ new int[]{0, 9, 5}, new int[]{9, 0, 4}, new int[]{5, 4, 0}, }; return new List<Int32>(){0,1,2,0}; //you could also return [0,2,1,0] ``` ```python matrix = [ [0,176,463], [176,0,125], [463,125,0] ] # Possible outcomes tsp(matrix) in [ [0, 1, 2, 0], [0, 2, 1, 0] ] ``` ```ruby matrix = [ [0,176,463], [176,0,125], [463,125,0] ] return [0,1,2,0]; #you could also return [0,2,1,0] ``` ## Test Cases There are: ```if:javascript,php,java,csharp,ruby - 30 tests with 5 points - 30 tests with 20 points - 30 tests with 100 points ``` ```if:python - 30 tests with 5 points - 30 tests with 20 points - 5 tests with 100 points ``` The total number of all possible routes can be calculated as: ```math \frac{(n-1)!}{2} ``` A naive approach becomes transcomputational at 66 cities. So a bruteforce approach is not a way to go. ## Note about results validation If in the test your path has cost `M`, and reference path has cost `N`, then you get the score `N/M` for that test. You are not obliged to find optimal route in each test, but you have to get enough scores in a series of tests. For example, in a series with 30 tests you have to get 30 points.
algorithms
import numpy as np def sort_and_return_args(input_list): # Enumerate the input list to get index-value pairs enum_list = list(enumerate(input_list)) # Use sorted with a custom key function to sort based on values sorted_enum_list = sorted(enum_list, key=lambda x: x[1]) # Extract the indices from the sorted list sorted_indices = [item[0] for item in sorted_enum_list] return sorted_indices def tsp(matrix): vertex = np.arange(len(matrix)) solutions = [] for start in vertex : used = [] used.append(start) node = start cost = 0 while len(np.setdiff1d(vertex,used)) != 0: for i in sort_and_return_args(matrix[node]) : if i in used or i == node : pass else : cost = cost + matrix[node][i] node = i used.append(node) break used.append(start) cost = cost + matrix[node][start] solutions.append((used , cost)) min_tuple = min(solutions, key=lambda x: x[1]) zero_in = min_tuple[0].index(0) if zero_in == 0 : result = min_tuple[0] else : result = min_tuple[0][zero_in :] + min_tuple[0][1:zero_in] + [0] return result
Approximate Solution of Travelling Salesman Problem
601b1d0c7de207001c81980b
[ "Dynamic Programming", "Algorithms" ]
https://www.codewars.com/kata/601b1d0c7de207001c81980b
5 kyu
Given a 2D array and a number of generations, compute n timesteps of [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). The rules of the game are: 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation. 2. Any live cell with more than three live neighbours dies, as if by overcrowding. 3. Any live cell with two or three live neighbours lives on to the next generation. 4. Any dead cell with exactly three live neighbours becomes a live cell. Each cell's neighborhood is the 8 cells immediately around it (i.e. [Moore Neighborhood](https://en.wikipedia.org/wiki/Moore_neighborhood)). The universe is infinite in both the x and y dimensions and all cells are initially dead - except for those specified in the arguments. The return value should be a 2d array cropped around all of the living cells. (If there are no living cells, then return `[[]]`.) For illustration purposes, 0 and 1 will be represented as `░░` and `▓▓` blocks respectively (PHP: plain black and white squares). You can take advantage of the `htmlize` function to get a text representation of the universe, e.g.: ```javascript console.log(htmlize(cells)); ```` ```coffeescript console.log htmlize(cells) ```` ```python print(htmlize(cells)) ```` ```haskell trace (htmlize cells) ``` ```java System.out.println(LifeDebug.htmlize(cells)); ``` ```swift print(htmlize(cells)) ``` ```php echo htmlize($cells) . "\r\n"; ``` ```c char *universe = htmlize(cells, rows, columns); printf("%s", universe); free(universe); ``` ```csharp Console.WriteLine(ConwayLife.Htmlize(cells)); ``` ~~~if:c In **C**, the initial dimensions of the GoL universe are passed to your function *by reference* via the pointers `rowptr` and `colptr`. You have to update these two variables to report the dimensions of the universe you are returning. ~~~
games
def get_neighbours(x, y): return {(x + i, y + j) for i in range(- 1, 2) for j in range(- 1, 2)} def get_generation(cells, generations): if not cells: return cells xm, ym, xM, yM = 0, 0, len(cells[0]) - 1, len(cells) - 1 cells = {(x, y) for y, l in enumerate(cells) for x, c in enumerate(l) if c} for _ in range(generations): cells = {(x, y) for x in range(xm - 1, xM + 2) for y in range(ym - 1, yM + 2) if 2 < len(cells & get_neighbours(x, y)) < 4 + ((x, y) in cells)} xm, ym = min(x for x, y in cells), min(y for x, y in cells) xM, yM = max(x for x, y in cells), max(y for x, y in cells) return [[int((x, y) in cells) for x in range(xm, xM + 1)] for y in range(ym, yM + 1)]
Conway's Game of Life - Unlimited Edition
52423db9add6f6fc39000354
[ "Games", "Arrays", "Puzzles", "Cellular Automata" ]
https://www.codewars.com/kata/52423db9add6f6fc39000354
4 kyu
Perform the secret knock() to enter...
games
knock(knock)()()
Secret knock
525f00ec798bc53e8e00004c
[ "Puzzles" ]
https://www.codewars.com/kata/525f00ec798bc53e8e00004c
5 kyu
```if-not:ruby Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with empty elements. ``` ```if:ruby Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with `nil`s. ``` Examples: ```groovy Kata.interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"] Kata.interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, null] Kata.interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9] Kata.interleave([]) == [] ``` ```javascript interleave([1, 2, 3], ["c", "d", "e"]) === [1, "c", 2, "d", 3, "e"] interleave([1, 2, 3], [4, 5]) === [1, 4, 2, 5, 3, null] interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) === [1, 4, 7, 2, 5, 8, 3, 6, 9] interleave([]) === [] ``` ```python interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"] interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None] interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9] interleave([]) == [] ``` ```ruby interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"] interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, nil] interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9] interleave([]) == [] ```
algorithms
from itertools import chain, zip_longest def interleave(* args): return list(chain . from_iterable(zip_longest(* args)))
Interleaving Arrays
523d2e964680d1f749000135
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/523d2e964680d1f749000135
5 kyu
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised. Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed. ### Arguments (Haskell) * **First argument**: space-delimited list of minor words that must always be lowercase except for the first word in the string. * **Second argument**: the original string to be converted. ### Arguments (Other languages) * **First argument (required)**: the original string to be converted. * **Second argument (optional)**: space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass `undefined` when this argument is unused. ### Example ```javascript titleCase('a clash of KINGS', 'a an the of') // should return: 'A Clash of Kings' titleCase('THE WIND IN THE WILLOWS', 'The In') // should return: 'The Wind in the Willows' titleCase('the quick brown fox') // should return: 'The Quick Brown Fox' ``` ```coffeescript titleCase('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings' titleCase('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows' titleCase('the quick brown fox') # should return: 'The Quick Brown Fox' ``` ```c titleCase('a clash of KINGS', 'a an the of') // should return: 'A Clash of Kings' titleCase('THE WIND IN THE WILLOWS', 'The In') // should return: 'The Wind in the Willows' titleCase('the quick brown fox') // should return: 'The Quick Brown Fox' ``` ```ruby title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings' title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows' title_case('the quick brown fox') # should return: 'The Quick Brown Fox' ``` ```python title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings' title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows' title_case('the quick brown fox') # should return: 'The Quick Brown Fox' ``` ```haskell titleCase "a an the of" "a clash of KINGS" -- should return: "A Clash of Kings" titleCase "The In" "THE WIND IN THE WILLOWS" -- should return: "The Wind in the Willows" titleCase "" "the quick brown fox" -- should return: "The Quick Brown Fox" ``` ```csharp Kata.TitleCase("a clash of KINGS", "a an the of") => "A Clash of Kings" Kata.TitleCase("THE WIND IN THE WILLOWS", "The In") => "The Wind in the Willows" Kata.TitleCase("the quick brown fox") => "The Quick Brown Fox" ```
reference
def title_case(title, minor_words=''): title = title . capitalize(). split() minor_words = minor_words . lower(). split() return ' ' . join([word if word in minor_words else word . capitalize() for word in title])
Title Case
5202ef17a402dd033c000009
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5202ef17a402dd033c000009
6 kyu
For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nested arrays, no matter how deep, should be flattened into the single array result. The following are examples of how this function would be used and what the expected results would be: ```javascript flatten(1, [2, 3], 4, 5, [6, [7]]) // returns [1, 2, 3, 4, 5, 6, 7] flatten('a', ['b', 2], 3, null, [[4], ['c']]) // returns ['a', 'b', 2, 3, null, 4, 'c'] ``` ```coffeescript flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7] flatten('a', ['b', 2], 3, null, [[4], ['c']]) # returns ['a', 'b', 2, 3, null, 4, 'c'] ``` ```python flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7] flatten('a', ['b', 2], 3, None, [[4], ['c']]) # returns ['a', 'b', 2, 3, None, 4, 'c'] ```
algorithms
def flatten(* a): r = [] for x in a: if isinstance(x, list): r . extend(flatten(* x)) else: r . append(x) return r
flatten()
513fa1d75e4297ba38000003
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/513fa1d75e4297ba38000003
5 kyu
### Tongues Gandalf's writings have long been available for study, but no one has yet figured out what language they are written in. Recently, due to programming work by a hacker known only by the code name ROT13, it has been discovered that Gandalf used nothing but a simple letter substitution scheme, and further, that it is its own inverse|the same operation scrambles the message as unscrambles it. This operation is performed by replacing vowels in the sequence `'a' 'i' 'y' 'e' 'o' 'u'` with the vowel three advanced, cyclicly, while preserving case (i.e., lower or upper). Similarly, consonants are replaced from the sequence `'b' 'k' 'x' 'z' 'n' 'h' 'd' 'c' 'w' 'g' 'p' 'v' 'j' 'q' 't' 's' 'r' 'l' 'm' 'f'` by advancing ten letters. So for instance the phrase `'One ring to rule them all.'` translates to `'Ita dotf ni dyca nsaw ecc.'` The fascinating thing about this transformation is that the resulting language yields pronounceable words. For this problem, you will write code to translate Gandalf's manuscripts into plain text. Your job is to write a function that decodes Gandalf's writings. ### Input The function will be passed a string for the function to decode. Each string will contain up to 100 characters, representing some text written by Gandalf. All characters will be plain ASCII, in the range space (32) to tilde (126). ### Output For each string passed to the decode function return its translation.
algorithms
def tongues(code): import string gandalf = string . maketrans( 'aiyeoubkxznhdcwgpvjqtsrlmfAIYEOUBKXZNHDCWGPVJQTSRLMF', 'eouaiypvjqtsrlmfbkxznhdcwgEOUAIYPVJQTSRLMFBKXZNHDCWG') return string . translate(code, gandalf)
Tongues
52763db7cffbc6fe8c0007f8
[ "Strings", "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/52763db7cffbc6fe8c0007f8
5 kyu
#### Complete the method so that it does the following: - Removes any duplicate query string parameters from the url (the first occurence should be kept) - Removes any query string parameters specified within the 2nd argument (optional array) #### Examples: ```javascript stripUrlParams('www.codewars.com?a=1&b=2&a=2') === 'www.codewars.com?a=1&b=2' stripUrlParams('www.codewars.com?a=1&b=2&a=2', ['b']) === 'www.codewars.com?a=1' stripUrlParams('www.codewars.com', ['b']) === 'www.codewars.com' ``` ```ruby strip_url_params('www.codewars.com?a=1&b=2&a=2') == 'www.codewars.com?a=1&b=2' strip_url_params('www.codewars.com?a=1&b=2&a=2', ['b']) == 'www.codewars.com?a=1' strip_url_params('www.codewars.com', ['b']) == 'www.codewars.com' ``` ```python strip_url_params('www.codewars.com?a=1&b=2&a=2') == 'www.codewars.com?a=1&b=2' strip_url_params('www.codewars.com?a=1&b=2&a=2', ['b']) == 'www.codewars.com?a=1' strip_url_params('www.codewars.com', ['b']) == 'www.codewars.com' ```
algorithms
import urlparse import urllib def strip_url_params(url, strip=None): if not strip: strip = [] parse = urlparse . urlparse(url) query = urlparse . parse_qs(parse . query) query = {k: v[0] for k, v in query . iteritems() if k not in strip} query = urllib . urlencode(query) new = parse . _replace(query=query) return new . geturl()
Strip Url Params
51646de80fd67f442c000013
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/51646de80fd67f442c000013
6 kyu
The businesspeople among you will know that it's often not easy to find an appointment. In this kata we want to find such an appointment automatically. You will be given the calendars of our businessperson and a duration for the meeting. Your task is to find the earliest time, when every businessperson is free for at least that duration. Example Schedule: ``` Person | Meetings -------+----------------------------------------------------------- A | 09:00 - 11:30, 13:30 - 16:00, 16:00 - 17:30, 17:45 - 19:00 B | 09:15 - 12:00, 14:00 - 16:30, 17:00 - 17:30 C | 11:30 - 12:15, 15:00 - 16:30, 17:45 - 19:00 ``` Rules: * All times in the calendars will be given in 24h format "hh:mm", the result must also be in that format * A meeting is represented by its start time (inclusively) and end time (exclusively) -> if a meeting takes place from 09:00 - 11:00, the next possible start time would be 11:00 * The businesspeople work from 09:00 (inclusively) - 19:00 (exclusively), the appointment must start and end within that range * If the meeting does not fit into the schedules, return `null` or `None` as result * The duration of the meeting will be provided as an integer in minutes Following these rules and looking at the example above the earliest time for a 60 minutes meeting would be `12:15`. Data Format: The schedule will be provided as 3-dimensional array. The schedule above would be encoded this way: ``` [ [['09:00', '11:30'], ['13:30', '16:00'], ['16:00', '17:30'], ['17:45', '19:00']], [['09:15', '12:00'], ['14:00', '16:30'], ['17:00', '17:30']], [['11:30', '12:15'], ['15:00', '16:30'], ['17:45', '19:00']] ] ```
algorithms
def get_start_time(schedules, duration): free_minutes = [True] * 60 * 24 for schedule in schedules: for meeting in schedule: for i in range(to_minute(meeting[0]), to_minute(meeting[1])): free_minutes[i] = False for time, available in enumerate(free_minutes): if 540 <= time <= 1140 - duration and free_minutes[time: time + duration] == [True] * duration: return from_minute(time) return None def to_minute(time): times = time . split(':') return int(times[0]) * 60 + int(times[1]) def from_minute(minute): return ':' . join([str(minute / / 60). zfill(2), str(minute % 60). zfill(2)])
Finding an appointment
525f277c7103571f47000147
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/525f277c7103571f47000147
5 kyu
In this kata you should simply determine, whether a given year is a leap year or not. In case you don't know the rules, here they are: * Years divisible by 4 are leap years, * but years divisible by 100 are **not** leap years, * but years divisible by 400 are leap years. Tested years are in range `1600 ≤ year ≤ 4000`. ~~~if:shell Echo out `1` if year passed in is a leap year, or `0` otherwise. ~~~ ~~~if:sql ### Notes - Table `years` has two columns: `id`, and `year`. - Your query has to return rows with two columns: `year`, and `is_leap`. - Returned rows have to be sorted ascending by the year. ~~~
algorithms
def is_leap_year(year): return (year % 100 and not year % 4) or not year % 400 isLeapYear = is_leap_year
Leap Years
526c7363236867513f0005ca
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/526c7363236867513f0005ca
7 kyu
Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes? ~~~if-not:factor,cpp,rust Write a function `cakes()`, which takes the recipe (object) and the available ingredients (also an object) and returns the maximum number of cakes Pete can bake (integer). For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). Ingredients that are not present in the objects, can be considered as 0. ~~~ ~~~if:factor Write a word `cakes`, which takes a recipe (assoc) and the available ingredients (also an assoc) and returns the maximum number of cakes Pete can bake (integer). For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). Ingredients for the recipe that are not present can be considered as 0. ~~~ ~~~if:cpp Write a function `cakes()`, which takes the recipe (unordered_map<string, int>) and the available ingredients (also an unordered_map<string, int>) and returns the maximum number of cakes Pete can bake (integer). For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). Ingredients that are not present in the objects, can be considered as 0. ~~~ ~~~if:rust Write a function `cakes()`, which takes the recipe (HashMap<&str, u32>) and the available ingredients (also a HashMap<&str, u32>) and returns the maximum number of cakes Pete can bake (u32). For simplicity there are no units for the amounts (e.g. 1 lb of flour or 200 g of sugar are simply 1 or 200). Ingredients that are not present in the objects, can be considered as 0. ~~~ Examples: ```javascript // must return 2 cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: 200}); // must return 0 cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: 2000, milk: 2000}); ``` ```coffeescript # must return 2 cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: 200}) # must return 0 cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: 2000, milk: 2000}) ``` ```python # must return 2 cakes({flour: 500, sugar: 200, eggs: 1}, {flour: 1200, sugar: 1200, eggs: 5, milk: 200}) # must return 0 cakes({apples: 3, flour: 300, sugar: 150, milk: 100, oil: 100}, {sugar: 500, flour: 2000, milk: 2000}) ``` ```haskell cakes [("flour",500), ("sugar",200), ("eggs",1)] [("flour",1200), ("sugar",1200), ("eggs",5), ("milk",200)] `shouldBe` 2 cakes [("apples",3), ("flour",300), ("sugar",150), ("milk",100), ("oil",100)] [("sugar",500), ("flour",2000), ("milk",2000)] `shouldBe` 0 ``` ```factor { { "flour" 500 } { "sugar" 200 } { "eggs" 1 } } { { "flour" 1200 } { "sugar" 1200 } { "eggs" 5 } { "milk" 200 } } cakes -> 2 { { "apples" 3 } { "flour" 300 } { "sugar" 150 } { "milk" 100 } { "oil" 100 } } { { "sugar" 500 } { "flour" 2000 } { "milk" 2000 } } cakes -> 0 ``` ```cpp // must return 2 cakes({{"flour", 500}, {"sugar", 200}, {"eggs", 1}}, {{"flour", 1200}, {"sugar", 1200}, {"eggs", 5}, {"milk", 200}}); // must return 0 cakes({{"apples", 3}, {"flour", 300}, {"sugar", 150}, {"milk", 100}, {"oil", 100}}, {{"sugar", 500}, {"flour", 2000}, {"milk", 2000}}); ``` ```rust // must return 2 cakes(HashMap::from([("flour", 500), ("sugar", 200), ("eggs", 1)]), HashMap::from([("flour", 1200), ("sugar", 1200), ("eggs", 5), ("milk", 200)])) // must return 0 cakes(HashMap::from([("apples", 3), ("flour", 300), ("sugar", 150), ("milk", 100), ("oil", 100)]), HashMap::from([("sugar", 500),("flour", 2000), ("milk", 2000)])) ```
algorithms
def cakes(recipe, available): return min(available . get(k, 0) / recipe[k] for k in recipe)
Pete, the baker
525c65e51bf619685c000059
[ "Algorithms" ]
https://www.codewars.com/kata/525c65e51bf619685c000059
5 kyu
Write a class that, when given a string, will return an **uppercase** string with each letter shifted forward in the alphabet by however many spots the cipher was initialized to. For example: ```javascript var c = new CaesarCipher(5); // creates a CipherHelper with a shift of five c.encode('Codewars'); // returns 'HTIJBFWX' c.decode('BFKKQJX'); // returns 'WAFFLES' ``` ```coffeescript c = new CaesarCipher(5) # creates a CipherHelper with a shift of five c.encode('Codewars') # returns 'HTIJBFWX' c.decode('BFKKQJX') # returns 'WAFFLES' ``` ```python c = CaesarCipher(5); # creates a CipherHelper with a shift of five c.encode('Codewars') # returns 'HTIJBFWX' c.decode('BFKKQJX') # returns 'WAFFLES' ``` ```ruby c = CaesarCipher.new(5); # creates a CipherHelper with a shift of five c.encode('Codewars') # returns 'HTIJBFWX' c.decode('BFKKQJX') # returns 'WAFFLES' ``` ```php $c = new CaesarCipher(5); $c->encode('Codewars'); // returns 'HTIJBFWX' $c->decode('BFKKQJX'); // returns 'WAFFLES' ``` If something in the string is not in the alphabet (e.g. punctuation, spaces), simply leave it as is. The shift will always be in range of `[1, 26]`.
algorithms
class CaesarCipher (object): def __init__(self, shift): self . s = shift pass def encode(self, str): return '' . join(chr((ord(i) + self . s - ord('A')) % 26 + ord('A')) if i . isalpha() else i for i in str . upper()) def decode(self, str): return '' . join(chr((ord(i) - self . s + ord('A')) % 26 + ord('A')) if i . isalpha() else i for i in str . upper())
Caesar Cipher Helper
526d42b6526963598d0004db
[ "Ciphers", "Object-oriented Programming", "Strings", "Algorithms" ]
https://www.codewars.com/kata/526d42b6526963598d0004db
5 kyu
Write a function that when given a number >= 0, returns an Array of ascending length subarrays. ``` pyramid(0) => [ ] pyramid(1) => [ [1] ] pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ] ``` **Note:** the subarrays should be filled with `1`s ```if:c Subarrays should not overlap; this will be tested. Do not forget to de-allocate memory in `free_pyramid()`, this will be tested as well. ```
algorithms
def pyramid(n): return [[1] * x for x in range(1, n + 1)]
Pyramid Array
515f51d438015969f7000013
[ "Algorithms" ]
https://www.codewars.com/kata/515f51d438015969f7000013
6 kyu
A format for expressing an ordered list of integers is to use a comma separated list of either * individual integers * or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example "12,13,15-17" Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. **Example:** ```javascript solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]); // returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```coffeescript solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```ruby solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```python solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```java Solution.rangeExtraction(new int[] {-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}) # returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```C# RangeExtraction.Extract(new[] {-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}); # returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```VB RangeExtraction.Extract({-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}); # returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```cpp range_extraction({-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}); // returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```c range_extraction((const []){-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}, 23); /* returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" */ ``` ```nasm nums: dd -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 mov rdi, nums mov rsi, 20 call range_extraction ; RAX <- `-10--8,-6,-3-1,3-5,7-11,14,15,17-20\0` ``` ```julia rangeextraction([-10 -9 -8 -6 -3 -2 -1 0 1 3 4 5 7 8 9 10 11 14 15 17 18 19 20]) # returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```scala solution(List(-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20)) // "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```racket (solution '(-10 -9 -8 -6 -3 -2 -1 0 1 3 4 5 7 8 9 10 11 14 15 17 18 19 20)) ; returns "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` ```php solution([-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) // returns '-10--8,-6,-3-1,3-5,7-11,14,15,17-20' ``` ```cobol Rangeextraction xs = [-10, -9, -8, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20] res = "-10--8,-6,-3-1,3-5,7-11,14,15,17-20" ``` *Courtesy of rosettacode.org*
algorithms
def solution(args): out = [] beg = end = args[0] for n in args[1:] + [""]: if n != end + 1: if end == beg: out . append(str(beg)) elif end == beg + 1: out . extend([str(beg), str(end)]) else: out . append(str(beg) + "-" + str(end)) beg = n end = n return "," . join(out)
Range Extraction
51ba717bb08c1cd60f00002f
[ "Algorithms" ]
https://www.codewars.com/kata/51ba717bb08c1cd60f00002f
4 kyu
Pete is now mixing the cake mixture. He has the recipe, containing the required ingredients for one cake. He also might have added some of the ingredients already, but something is missing. Can you help him to find out, what he has to add to the mixture? Requirements: * Pete only wants to bake whole cakes. And ingredients, that were added once to the mixture, can't be removed from that. That means: if he already added the amount of flour for 2.8 cakes, he needs to add at least the amount of flour for 0.2 cakes, in order to have enough flour for 3 cakes. * If Pete already added all ingredients for an integer amount of cakes, you don't need to add anything, just return an empty hash then. * If Pete didn't add any ingredients at all, you need to add all ingredients for exactly one cake. * For simplicity we ignore all units and just concentrate on the numbers. E.g. 250g of flour is simply 250 (units) of flour and 1 lb of sugar is also simply 1 (unit) of sugar. * Ingredients, which don't have to be added to the mixture (missing amount = 0), must not be present in the result. Examples: ```javascript var recipe = {flour: 200, eggs: 1, sugar: 100}; getMissingIngredients(recipe, {flour: 50, eggs: 1}); // must return {flour: 150, sugar: 100} getMissingIngredients(recipe, {}); // must return {flour: 200, eggs: 1, sugar: 100} getMissingIngredients(recipe, {flour: 500, sugar: 200}); // must return {flour: 100, eggs: 3, sugar: 100} ``` ```coffeescript recipe = {flour: 200, eggs: 1, sugar: 100}; getMissingIngredients(recipe, {flour: 50, eggs: 1}); # must return {flour: 150, sugar: 100} getMissingIngredients(recipe, {}); # must return {flour: 200, eggs: 1, sugar: 100} getMissingIngredients(recipe, {flour: 500, sugar: 200}); # must return {flour: 100, eggs: 3, sugar: 100} ```
algorithms
from math import ceil def get_missing_ingredients(recipe, added): piece = max( ceil(v / recipe[k]) if k in recipe else 1 for k, v in added . items()) return {k: v * piece - added . get(k, 0) for k, v in recipe . items() if (v * piece) > added . get(k, 0)}
Pete, the baker (part 2)
5267e5827526ea15d8000708
[ "Algorithms" ]
https://www.codewars.com/kata/5267e5827526ea15d8000708
6 kyu
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function. The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`. Examples: solution(1, 2, 3) --> false solution(1, 2, 3, 2) --> true solution('1', '2', '3', '2') --> true ~~~if:lambdacalc Encodings: purity: `LetRec` numEncoding: `BinaryScott` Export constructors `nil, cons` for your `List` encoding, and deconstructor `if` for your `Boolean` encoding. ~~~
algorithms
def solution(* args): return len(args) != len(set(args))
Duplicate Arguments
520d9c27e9940532eb00018e
[ "Algorithms" ]
https://www.codewars.com/kata/520d9c27e9940532eb00018e
6 kyu
Write a function that accepts two square matrices (`N x N` two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size `N x N` (square), containing only integers. How to sum two matrices: Take each cell `[n][m]` from the first matrix, and add it with the same `[n][m]` cell from the second matrix. This will be cell `[n][m]` of the solution matrix. (Except for C where solution matrix will be a 1d pseudo-multidimensional array). Visualization: ``` |1 2 3| |2 2 1| |1+2 2+2 3+1| |3 4 4| |3 2 1| + |3 2 3| = |3+3 2+2 1+3| = |6 4 4| |1 1 1| |1 1 3| |1+1 1+1 1+3| |2 2 4| ``` ## Example ```javascript matrixAddition( [ [1, 2, 3], [3, 2, 1], [1, 1, 1] ], // + [ [2, 2, 1], [3, 2, 3], [1, 1, 3] ] ) // returns: [ [3, 4, 4], [6, 4, 4], [2, 2, 4] ] ```
algorithms
import numpy as np def matrix_addition(a, b): return (np . mat(a) + np . mat(b)). tolist()
Matrix Addition
526233aefd4764272800036f
[ "Matrix", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/526233aefd4764272800036f
6 kyu
Sort the given **array of strings** in alphabetical order, case **insensitive**. For example: ``` ["Hello", "there", "I'm", "fine"] --> ["fine", "Hello", "I'm", "there"] ["C", "d", "a", "B"]) --> ["a", "B", "C", "d"] ```
reference
def sortme(words): return sorted(words, key=str . lower)
Sort Arrays (Ignoring Case)
51f41fe7e8f176e70d0002b9
[ "Arrays", "Sorting" ]
https://www.codewars.com/kata/51f41fe7e8f176e70d0002b9
6 kyu
You've just recently been hired to calculate scores for a Dart Board game! Scoring specifications: * 0 points - radius above 10 * 5 points - radius between 5 and 10 inclusive * 10 points - radius less than 5 **If all radii are less than 5, award 100 BONUS POINTS!** Write a function that accepts an array of radii (can be integers and/or floats), and returns a total score using the above specification. An empty array should return 0. ## Examples: ```javascript scoreThrows( [1, 5, 11] ) => 15 scoreThrows( [15, 20, 30] ) => 0 scoreThrows( [1, 2, 3, 4] ) => 140 ```
algorithms
def score_throws(radiuses): score = 0 for r in radiuses: if r < 5: score += 10 elif 5 <= r <= 10: score += 5 if radiuses and max(radiuses) < 5: score += 100 return score
Throwing Darts
525dfedb5b62f6954d000006
[ "Algorithms" ]
https://www.codewars.com/kata/525dfedb5b62f6954d000006
6 kyu
Have a look at the following numbers. ``` n | score ---+------- 1 | 50 2 | 150 3 | 300 4 | 500 5 | 750 ``` Can you find a pattern in it? If so, then write a function `getScore(n)`/`get_score(n)`/`GetScore(n)` which returns the score for any positive number `n`. ___Note___ Real test cases consists of 100 random cases where `1 <= n <= 10000`
games
def get_score(n): return n * (n + 1) * 25
Sequences and Series
5254bd1357d59fbbe90001ec
[ "Mathematics", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/5254bd1357d59fbbe90001ec
6 kyu
Write a simple parser that will parse and run Deadfish. Deadfish has 4 commands, each 1 character long: * `i` increments the value (initially `0`) * `d` decrements the value * `s` squares the value * `o` outputs the value into the return array Invalid characters should be ignored. ```javascript parse("iiisdoso") => [ 8, 64 ] ``` ```csharp Deadfish.Parse("iiisdoso") => new int[] {8, 64}; ``` ```python parse("iiisdoso") ==> [8, 64] ``` ```haskell parse "iiisdoso" -> [ 8, 64 ] ``` ```c parse("iiisdoso") == {8, 64} ``` ```go Parse("iiisdoso") == []int{8, 64} ``` ```ruby parse("iiisdoso") ==> [8, 64] ``` ```java Deadfish.parse("iiisdoso") =- new int[] {8, 64}; ``` ```groovy DeadFish.parse("iiisdoso") ==> [8, 64] ``` ```scala Deadfish.parse("iiisdoso") => List(8, 64) ``` ```typescript parse("iiisdoso") => [8, 64] ``` ```julia deadfish("iiisdoso") --> [8, 64] ``` ```powershell Eval-DeadFish -Data "ooo" --> @(0, 0, 0) # [long[]] ``` ```factor "iiisdoso" deadfish -> { 8 64 } ```
algorithms
def parse(data): value = 0 res = [] for c in data: if c == "i": value += 1 elif c == "d": value -= 1 elif c == "s": value *= value elif c == "o": res . append(value) return res
Make the Deadfish Swim
51e0007c1f9378fa810002a9
[ "Parsing", "Algorithms" ]
https://www.codewars.com/kata/51e0007c1f9378fa810002a9
6 kyu
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). Examples: ``` * 'abc' => ['ab', 'c_'] * 'abcdef' => ['ab', 'cd', 'ef'] ```
algorithms
def solution(s): result = [] if len(s) % 2: s += '_' for i in range(0, len(s), 2): result . append(s[i: i + 2]) return result
Split Strings
515de9ae9dcfc28eb6000001
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/515de9ae9dcfc28eb6000001
6 kyu
Inspired from real-world [Brainf\*\*k](http://en.wikipedia.org/wiki/Brainfuck), we want to create an interpreter of that language which will support the following instructions: * `>` increment the data pointer (to point to the next cell to the right). * `<` decrement the data pointer (to point to the next cell to the left). * `+` increment (increase by one, truncate overflow: 255 + 1 = 0) the byte at the data pointer. * `-` decrement (decrease by one, treat as unsigned byte: 0 - 1 = 255 ) the byte at the data pointer. * `.` output the byte at the data pointer. * `,` accept one byte of input, storing its value in the byte at the data pointer. * `[` if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching `]` command. * `]` if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching `[` command. The function will take in input... * the program code, a string with the sequence of machine instructions, * the program input, a string, possibly empty, that will be interpreted as an array of bytes using each character's ASCII code and will be consumed by the `,` instruction ... and will return ... * the output of the interpreted code (always as a string), produced by the `.` instruction. Implementation-specific details for this Kata: - Your memory tape should be large enough - the original implementation had 30,000 cells but a few thousand should suffice for this Kata - Each cell should hold an unsigned byte with wrapping behavior (i.e. 255 + 1 = 0, 0 - 1 = 255), initialized to 0 - The memory pointer should initially point to a cell in the tape with a sufficient number (e.g. a few thousand or more) of cells to its right. For convenience, you may want to have it point to the leftmost cell initially - You may assume that the `,` command will never be invoked when the input stream is exhausted - Error-handling, e.g. unmatched square brackets and/or memory pointer going past the leftmost cell is not required in this Kata. If you see test cases that require you to perform error-handling then please open an Issue in the Discourse for this Kata (don't forget to state which programming language you are attempting this Kata in). ~~~if:bf For BF: The code and input are separated by `'!'`. ~~~ ~~~if:rust For Rust: Input and output are `Vec<u8>`. ~~~
algorithms
from collections import defaultdict def brain_luck(code, input): p, i = 0, 0 output = [] input = iter(input) data = defaultdict(int) while i < len(code): c = code[i] if c == '+': data[p] = (data[p] + 1) % 256 elif c == '-': data[p] = (data[p] - 1) % 256 elif c == '>': p += 1 elif c == '<': p -= 1 elif c == '.': output . append(chr(data[p])) elif c == ',': data[p] = ord(next(input)) elif c == '[': if not data[p]: depth = 1 while depth > 0: i += 1 c = code[i] if c == '[': depth += 1 elif c == ']': depth -= 1 elif c == ']': if data[p]: depth = 1 while depth > 0: i -= 1 c = code[i] if c == ']': depth += 1 elif c == '[': depth -= 1 i += 1 return '' . join(output)
My smallest code interpreter (aka Brainf**k)
526156943dfe7ce06200063e
[ "Interpreters", "Algorithms" ]
https://www.codewars.com/kata/526156943dfe7ce06200063e
5 kyu
Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between `0` and `255`, inclusive. #### Valid inputs examples: ``` Examples of valid inputs: 1.2.3.4 123.45.67.89 ``` #### Invalid input examples: ``` 1.2.3 1.2.3.4.5 123.456.78.90 123.045.067.089 ``` #### Notes: - Leading zeros (e.g. `01.02.03.04`) are considered invalid - Inputs are guaranteed to be a single string
algorithms
import socket def is_valid_IP(addr): try: socket . inet_pton(socket . AF_INET, addr) return True except socket . error: return False
IP Validation
515decfd9dcfc23bb6000006
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/515decfd9dcfc23bb6000006
6 kyu
Write a function that takes in a string of one or more words, and returns the same string, but with all words that have five or more letters reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. Examples: ``` "Hey fellow warriors" --> "Hey wollef sroirraw" "This is a test --> "This is a test" "This is another test" --> "This is rehtona test" ```
algorithms
def spin_words(sentence): # Your code goes here return " " . join([x[:: - 1] if len(x) >= 5 else x for x in sentence . split(" ")])
Stop gninnipS My sdroW!
5264d2b162488dc400000001
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5264d2b162488dc400000001
6 kyu
In mathematics, Pascal's triangle is a triangular array of the binomial coefficients expressed with formula ```math \lparen {n \atop k} \rparen = \frac {n!} {k!(n-k)!} ``` where `n` denotes a row of the triangle, and `k` is a position of a term in the row. ![Pascal's Triangle](http://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) You can read [Wikipedia article on Pascal's Triangle](http://en.wikipedia.org/wiki/Pascal's_triangle) for more information. ### Task Write a function that, given a depth `n`, returns `n` top rows of Pascal's Triangle flattened into a one-dimensional list/array. ### Example: ``` n = 1: [1] n = 2: [1, 1, 1] n = 4: [1, 1, 1, 1, 2, 1, 1, 3, 3, 1] ``` ```if-not:python,ruby ### Note Beware of overflow. Requested terms of a triangle are guaranteed to fit into the returned type, but depending on seleced method of calculations, intermediate values can be larger. ```
algorithms
def pascals_triangle(n): if n == 1: return [1] prev = pascals_triangle(n - 1) return prev + [1 if i == 0 or i == n - 1 else prev[- i] + prev[- (i + 1)] for i in range(n)]
Pascal's Triangle
5226eb40316b56c8d500030f
[ "Arrays", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5226eb40316b56c8d500030f
6 kyu
Have you heard of the game "electrons around the cores"? I'm not allowed to give you the complete rules of the game, just so much: - the game is played with 4 to 6 ___dice___, so you get an array of 4 to 6 numbers, each 1-6 - the name of the game is important - you have to return the correct number five times in a row and your solution is considered to be correct If you just press "submit", you'll get an array and the expected value! Here are some input/output pairs for you to wrap your mind around: - [ 1, 2, 3, 4, 5 ] -> 6 - [ 2, 2, 3, 3 ] -> 4 - [ 6, 6, 4, 4, 1, 3 ] -> 2 - [ 3, 5, 3, 5, 4, 2 ] -> 12 And yes, it is a shameless copy of a famous game.
games
def electrons_around_the_cores(dice): return dice . count(5) * 4 + dice . count(3) * 2
Game - Electrons around the cores
52210226578afb73bd0000f1
[ "Reverse Engineering", "Games", "Puzzles", "Riddles" ]
https://www.codewars.com/kata/52210226578afb73bd0000f1
5 kyu
How can you tell an extrovert from an introvert at NSA? Va gur ryringbef, gur rkgebireg ybbxf ng gur BGURE thl'f fubrf. I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it? According to Wikipedia, [ROT13](http://en.wikipedia.org/wiki/ROT13) is frequently used to obfuscate jokes on USENET. For this task you're only supposed to substitute characters. Not spaces, punctuation, numbers, etc. Test examples: ``` "EBG13 rknzcyr." -> "ROT13 example." "This is my first ROT13 excercise!" -> "Guvf vf zl svefg EBG13 rkprepvfr!" ```
algorithms
def rot13(message): def decode(c): if 'a' <= c <= 'z': base = 'a' elif 'A' <= c <= 'Z': base = 'A' else: return c return chr((ord(c) - ord(base) + 13) % 26 + ord(base)) return "" . join(decode(c) for c in message)
ROT13
52223df9e8f98c7aa7000062
[ "Strings", "Ciphers", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/52223df9e8f98c7aa7000062
5 kyu
The marketing team is spending way too much time typing in hashtags. Let's help them with our own Hashtag Generator! Here's the deal: - It must start with a hashtag (`#`). - All words must have their first letter capitalized. - If the final result is longer than 140 chars it must return `false`. - If the input or the result is an empty string it must return `false`. ## Examples ``` " Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata" " Hello World " => "#HelloWorld" "" => false ```
algorithms
def generate_hashtag(s): output = "#" for word in s . split(): output += word . capitalize() return False if (len(s) == 0 or len(output) > 140) else output
The Hashtag Generator
52449b062fb80683ec000024
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52449b062fb80683ec000024
5 kyu
Triangular numbers are so called because of the equilateral triangular shape that they occupy when laid out as dots. i.e. ``` 1st (1) 2nd (3) 3rd (6) * ** *** * ** * ``` You need to return the nth triangular number. You should return 0 for out of range values: For example: (**Input --> Output**) ``` 0 --> 0 2 --> 3 3 --> 6 -10 --> 0 ```
algorithms
def triangular(n): return n * (n + 1) / / 2 if n > 0 else 0
Triangular Treasure
525e5a1cb735154b320002c8
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/525e5a1cb735154b320002c8
7 kyu