├── .gitattributes ├── Python ├── mars-lander-episode-2.py ├── onboarding.py ├── the-river-i-.py ├── whats-so-complex-about-mandelbrot.py ├── the-river-ii-.py ├── horse-racing-duals.py ├── the-descent.py ├── credit-card-verifier-luhns-algorithm.py ├── addem-up.py ├── stock-exchange-losses.py ├── temperatures.py ├── count-as-i-count.py ├── horse-racing-hyperduals.py ├── mars-lander-episode-1.py ├── smooth.py ├── brackets-extreme-edition.py ├── brick-in-the-wall.py ├── telephone-numbers.py ├── rugby-score.py ├── are-the-clumps-normal.py ├── mime-type.py ├── bank-robbers.py ├── how-time-flies.py ├── jack-silver-the-casino.py ├── shadows-of-the-knight-episode-1.py ├── may-the-triforce-be-with-you.py ├── rectangular-block-spinner.py ├── detective-pikaptcha-ep1.py ├── ascii-art.py ├── conway-sequence.py ├── balanced-ternary-computer-encode.py ├── there-is-no-spoon-episode-1.py ├── self-driving-car-testing.py ├── 111-rubiks-cube-movements.py ├── simple-awale.py ├── xml-mdf-2016.py ├── hunger-games.py ├── guessing-n-cheating.py ├── the-frog-jump.py ├── chuck-norris.py ├── dead-mens-shot.py ├── power-of-thor-episode-1.py ├── blowing-fuse.py ├── don't-panic-episode-1.py ├── bulk-email-generator.py ├── defibrillators.py ├── plague-jr.py ├── organic-compounds.py ├── isbn-check-digit.py ├── text-formatting.py ├── skynet-revolution-episode-1.py ├── scrabble.py ├── stall-tilt.py ├── ghost-legs.py ├── the-traveling-salesman-problem.py ├── hooch-clash.py ├── winamax-battle.py ├── the-last-crusade-episode-1.py ├── order-of-succession.py ├── pirates-treasure.py ├── morellets-random-lines.py ├── lumen.py ├── encryptiondecryption-of-enigma-machine.py ├── darts.py ├── the-dart-101.py ├── nature-of-quadrilateral.py ├── detective-pikaptcha-ep2.py ├── rooks-movements.py └── 1d-spreadsheet.py ├── .gitignore ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /Python/mars-lander-episode-2.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/mars-lander-episode-2 2 | 3 | 4 | -------------------------------------------------------------------------------- /Python/onboarding.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/onboarding 2 | 3 | 4 | def solution(): 5 | while True: 6 | enemy1, dist1 = input(), int(input()) 7 | enemy2, dist2 = input(), int(input()) 8 | print(enemy1 if dist1 < dist2 else enemy2) 9 | 10 | 11 | solution() 12 | -------------------------------------------------------------------------------- /Python/the-river-i-.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/the-river-i- 2 | 3 | 4 | def solution(): 5 | r1, r2 = int(input()), int(input()) 6 | while r1 != r2: 7 | if r1 < r2: 8 | r1 += sum(map(int, str(r1))) 9 | else: 10 | r2 += sum(map(int, str(r2))) 11 | print(r1) 12 | 13 | 14 | solution() 15 | -------------------------------------------------------------------------------- /Python/whats-so-complex-about-mandelbrot.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/whats-so-complex-about-mandelbrot 2 | 3 | 4 | def solution(): 5 | c = complex(input().replace('i', 'j')) 6 | fn = 0 7 | for i in range(1, int(input()) + 1): 8 | fn = fn**2 + c 9 | if abs(fn) > 2: break 10 | print(i) 11 | 12 | 13 | solution() 14 | -------------------------------------------------------------------------------- /Python/the-river-ii-.py: -------------------------------------------------------------------------------- 1 | def meets_digital_river(r1, r2): 2 | return r1 == r2 + sum(map(int, str(r2))) 3 | 4 | 5 | def solution(): 6 | r1 = int(input()) 7 | for r2 in range(max(1, r1 - 50), r1): 8 | if meets_digital_river(r1, r2): 9 | print('YES') 10 | break 11 | else: 12 | print('NO') 13 | 14 | 15 | solution() 16 | -------------------------------------------------------------------------------- /Python/horse-racing-duals.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/horse-racing-duals 2 | 3 | 4 | def solution(): 5 | num_horses = int(input()) 6 | horses = sorted([int(input()) for _ in range(num_horses)]) 7 | 8 | d = float('inf') 9 | for i in range(1, num_horses): 10 | d = min(d, horses[i] - horses[i - 1]) 11 | 12 | print(d) 13 | 14 | 15 | solution() 16 | -------------------------------------------------------------------------------- /Python/the-descent.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/the-descent 2 | 3 | 4 | def solution(): 5 | while True: 6 | max_height = 0 7 | max_mountain = 0 8 | for i in range(8): 9 | height = int(input()) 10 | if height > max_height: 11 | max_height = height 12 | max_mountain = i 13 | 14 | print(max_mountain) 15 | 16 | 17 | solution() 18 | -------------------------------------------------------------------------------- /Python/credit-card-verifier-luhns-algorithm.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/credit-card-verifier-luhns-algorithm 2 | 3 | 4 | def solution(): 5 | for _ in range(int(input())): 6 | card = [int(x) for x in input() if x != ' '] 7 | doubling = sum(x * 2 - 9 if x * 2 > 9 else x * 2 for x in card[-2::-2]) 8 | odds = sum(card[-1::-2]) 9 | print('YES' if (doubling + odds) % 10 == 0 else 'NO') 10 | 11 | 12 | solution() 13 | -------------------------------------------------------------------------------- /Python/addem-up.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/addem-up 2 | 3 | from heapq import * 4 | 5 | 6 | def solution(): 7 | num_cards = int(input()) 8 | cards = list(map(int, input().split())) 9 | heapify(cards) 10 | 11 | cost = 0 12 | while len(cards) > 1: 13 | card1 = heappop(cards) 14 | card2 = heappop(cards) 15 | cost += card1 + card2 16 | heappush(cards, card1 + card2) 17 | 18 | print(cost) 19 | 20 | 21 | solution() 22 | -------------------------------------------------------------------------------- /Python/stock-exchange-losses.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/stock-exchange-losses 2 | 3 | 4 | def solution(): 5 | num_stock_values = int(input()) 6 | max_loss = 0 7 | buy_price = -1 8 | 9 | for stock in map(int, input().split()): 10 | if buy_price == -1 or stock > buy_price: 11 | buy_price = stock 12 | else: 13 | max_loss = min(max_loss, stock - buy_price) 14 | 15 | print(max_loss) 16 | 17 | 18 | solution() 19 | -------------------------------------------------------------------------------- /Python/temperatures.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/temperatures 2 | 3 | 4 | def solution(): 5 | num_temps = int(input()) 6 | closest_temp = float('inf') 7 | 8 | for temp in map(int, input().split()): 9 | if abs(temp) < abs(closest_temp): 10 | closest_temp = temp 11 | elif temp == -closest_temp: 12 | closest_temp = abs(closest_temp) 13 | 14 | print(closest_temp if num_temps != 0 else 0) 15 | 16 | 17 | solution() 18 | -------------------------------------------------------------------------------- /Python/count-as-i-count.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/count-as-i-count 2 | 3 | 4 | def solution(): 5 | initial_score = int(input()) 6 | combs = [[1, 0, 0, 0, 0]] + [[0, 0, 0, 0, 0] for _ in range(50 - initial_score)] 7 | 8 | for i in range(1, len(combs)): 9 | for j in range(max(0, i - 12), i): 10 | for k in range(1, 5): 11 | combs[i][k] += combs[j][k - 1] * (2 - (j == i - 1)) 12 | print(sum(combs[i][1:])) 13 | 14 | 15 | solution() 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # Distribution / packaging 7 | .Python 8 | build/ 9 | develop-eggs/ 10 | dist/ 11 | downloads/ 12 | eggs/ 13 | .eggs/ 14 | lib/ 15 | lib64/ 16 | parts/ 17 | sdist/ 18 | var/ 19 | wheels/ 20 | *.egg-info/ 21 | .installed.cfg 22 | *.egg 23 | MANIFEST 24 | 25 | # pyenv 26 | .python-version 27 | 28 | # Environments 29 | .env 30 | .venv 31 | env/ 32 | venv/ 33 | ENV/ 34 | env.bak/ 35 | venv.bak/ 36 | .idea 37 | -------------------------------------------------------------------------------- /Python/horse-racing-hyperduals.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/horse-racing-hyperduals 2 | 3 | 4 | def solution(): 5 | num_horses = int(input()) 6 | horses = [list(map(int, input().split())) for _ in range(num_horses)] 7 | closest = float('inf') 8 | 9 | for i in range(1, len(horses)): 10 | for j in range(i): 11 | closest = min(closest, abs(horses[j][0] - horses[i][0]) + abs(horses[j][1] - horses[i][1])) 12 | 13 | print(closest) 14 | 15 | 16 | solution() 17 | -------------------------------------------------------------------------------- /Python/mars-lander-episode-1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/mars-lander-episode-1 2 | 3 | 4 | def solution(): 5 | surface_n = int(input()) 6 | for i in range(surface_n): 7 | land_x, land_y = map(int, input().split()) 8 | 9 | while True: 10 | x, y, h_speed, v_speed, fuel, rotate, power = list(map(int, input().split())) 11 | if abs(v_speed) > 36: 12 | print(0, min(4, power + 1)) 13 | else: 14 | print(0, max(0, power - 1)) 15 | 16 | 17 | solution() 18 | -------------------------------------------------------------------------------- /Python/smooth.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/smooth 2 | 3 | 4 | def solution(): 5 | for _ in range(int(input())): 6 | f = int(input()) 7 | while f > 1: 8 | if f % 5 == 0: 9 | f //= 5 10 | elif f % 3 == 0: 11 | f //= 3 12 | elif f % 2 == 0: 13 | f //= 2 14 | else: 15 | print('DEFEAT') 16 | break 17 | else: 18 | print('VICTORY') 19 | 20 | 21 | solution() 22 | -------------------------------------------------------------------------------- /Python/brackets-extreme-edition.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/brackets-extreme-edition 2 | 3 | 4 | def solution(): 5 | pairs = {'(': ')', '[': ']', '{': '}'} 6 | stack = [] 7 | for c in input(): 8 | if c in '([{': 9 | stack.append(pairs[c]) 10 | elif c in ')]}': 11 | if not stack or stack[-1] != c: 12 | print('false') 13 | return 14 | 15 | stack.pop() 16 | 17 | print('true' if not stack else 'false') 18 | 19 | 20 | solution() 21 | -------------------------------------------------------------------------------- /Python/brick-in-the-wall.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/brick-in-the-wall 2 | 3 | 4 | def solution(): 5 | max_row_bricks = int(input()) 6 | num_bricks = int(input()) 7 | bricks = map(int, input().split()) 8 | 9 | work = 0 10 | row, row_bricks = 1, 0 11 | for brick in sorted(bricks, reverse=True): 12 | work += ((row - 1) * 6.5 / 100) * 10 * brick 13 | row_bricks += 1 14 | if row_bricks == max_row_bricks: 15 | row_bricks = 0 16 | row += 1 17 | 18 | print('{0:.3f}'.format(work)) 19 | 20 | 21 | solution() 22 | -------------------------------------------------------------------------------- /Python/telephone-numbers.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/telephone-numbers 2 | 3 | 4 | def add_number(number, directory): 5 | elements = 0 6 | for digit in number: 7 | if digit not in directory: 8 | directory[digit] = {} 9 | elements += 1 10 | directory = directory[digit] 11 | 12 | return elements 13 | 14 | 15 | def solution(): 16 | elements = 0 17 | directory = {} 18 | for _ in range(int(input())): 19 | elements += add_number(input(), directory) 20 | 21 | print(elements) 22 | 23 | 24 | solution() 25 | -------------------------------------------------------------------------------- /Python/rugby-score.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/rugby-score 2 | 3 | 4 | def solution(): 5 | score = int(input()) 6 | for tries in range(score // 5 + 1): 7 | if tries * 5 == score: 8 | print('{} 0 0'.format(tries)) 9 | continue 10 | 11 | for trans in range(tries + 1): 12 | if tries * 5 + trans * 2 > score: break 13 | if (score - tries * 5 - trans * 2) % 3 == 0: 14 | penalty = (score - tries * 5 - trans * 2) // 3 15 | print('{} {} {}'.format(tries, trans, penalty)) 16 | 17 | 18 | solution() 19 | -------------------------------------------------------------------------------- /Python/are-the-clumps-normal.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/are-the-clumps-normal 2 | 3 | 4 | def solution(): 5 | n = input() 6 | 7 | prev_num_clumps = 0 8 | for b in range(2, 10): 9 | num_clumps = 0 10 | prev_clump = -1 11 | for d in n: 12 | if int(d) % b != prev_clump: 13 | num_clumps += 1 14 | prev_clump = int(d) % b 15 | 16 | if num_clumps < prev_num_clumps: 17 | print(b) 18 | return 19 | 20 | prev_num_clumps = num_clumps 21 | 22 | print('Normal') 23 | 24 | 25 | solution() 26 | -------------------------------------------------------------------------------- /Python/mime-type.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/mime-type 2 | 3 | 4 | def solution(): 5 | num_elements = int(input()) 6 | num_files = int(input()) 7 | 8 | association_table = {} 9 | 10 | for _ in range(num_elements): 11 | ext, mt = input().split() 12 | association_table[ext.lower()] = mt 13 | 14 | for _ in range(num_files): 15 | fileparts = input().split('.') 16 | if len(fileparts) == 1: 17 | print('UNKNOWN') 18 | continue 19 | 20 | ext = fileparts[-1].lower() 21 | if ext in association_table: 22 | print(association_table[ext]) 23 | else: 24 | print('UNKNOWN') 25 | 26 | 27 | solution() 28 | -------------------------------------------------------------------------------- /Python/bank-robbers.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/bank-robbers 2 | 3 | 4 | from heapq import * 5 | 6 | 7 | def calc_vault_time(c, n): 8 | return 10**n * 5**(c - n) 9 | 10 | 11 | def solution(): 12 | robbers = int(input()) 13 | vault = int(input()) 14 | vault_times = [] 15 | for i in range(vault): 16 | c, n = map(int, input().split()) 17 | vault_times.append(calc_vault_time(c, n)) 18 | 19 | active_robbers = [] 20 | for vt in vault_times: 21 | if len(active_robbers) < robbers: 22 | heappush(active_robbers, vt) 23 | else: 24 | heappush(active_robbers, vt + heappop(active_robbers)) 25 | 26 | print(max(active_robbers)) 27 | 28 | solution() 29 | -------------------------------------------------------------------------------- /Python/how-time-flies.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/how-time-flies 2 | 3 | 4 | from datetime import datetime 5 | from dateutil.relativedelta import relativedelta 6 | 7 | 8 | def solution(): 9 | begin = datetime.strptime(input(), '%d.%m.%Y') 10 | end = datetime.strptime(input(), '%d.%m.%Y') 11 | 12 | delta = relativedelta(end, begin) 13 | years = delta.years 14 | months = delta.months 15 | days = (end - begin).days 16 | 17 | f = lambda x: 's' if x != 1 else '' 18 | if years > 0: print('{} year{}, '.format(years, f(years)), end='') 19 | if months > 0: print('{} month{}, '.format(months, f(months)), end='') 20 | print('total {} day{}'.format(days, f(days)), end='') 21 | 22 | 23 | solution() 24 | -------------------------------------------------------------------------------- /Python/jack-silver-the-casino.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/jack-silver-the-casino 2 | 3 | 4 | import math 5 | 6 | 7 | def solution(): 8 | rounds = int(input()) 9 | cash = int(input()) 10 | for _ in range(rounds): 11 | play = input().split() 12 | bet = math.ceil(cash / 4) 13 | cash -= bet 14 | 15 | if play[1] == 'ODD': 16 | if int(play[0]) % 2 == 1: 17 | cash += bet * 2 18 | elif play[1] == 'EVEN': 19 | if int(play[0]) % 2 == 0 and int(play[0]) != 0: 20 | cash += bet * 2 21 | else: 22 | if int(play[0]) == int(play[2]): 23 | cash += 36 * bet 24 | 25 | print(cash) 26 | 27 | 28 | solution() 29 | -------------------------------------------------------------------------------- /Python/shadows-of-the-knight-episode-1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/shadows-of-the-knight-episode-1 2 | 3 | 4 | def solution(): 5 | width, height = map(int, input().split()) 6 | num_turns = int(input()) 7 | x, y = map(int, input().split()) 8 | l, r, u, d = 0, width - 1, 0, height - 1 9 | 10 | while True: 11 | bomb_dir = input() 12 | if bomb_dir[0] == 'D': 13 | u = y + 1 14 | elif bomb_dir[0] == 'U': 15 | d = y - 1 16 | if bomb_dir[-1] == 'L': 17 | r = x - 1 18 | elif bomb_dir[-1] == 'R': 19 | l = x + 1 20 | 21 | x = (l + r) // 2 22 | y = (u + d) // 2 23 | print('{} {}'.format(x, y)) 24 | 25 | 26 | solution() 27 | -------------------------------------------------------------------------------- /Python/may-the-triforce-be-with-you.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/may-the-triforce-be-with-you 2 | 3 | 4 | def draw_top(size): 5 | for i in range(1, size + 1): 6 | if i == 1: 7 | print('.' + ' ' * (size * 2 - i - 1), end='') 8 | else: 9 | print(' ' * (size * 2 - i), end='') 10 | print('*' * (i * 2 - 1)) 11 | 12 | 13 | def draw_bottom(size): 14 | for i in range(1, size + 1): 15 | print(' ' * (size - i), end='') 16 | print('*' * (i * 2 - 1), end='') 17 | print(' ' * ((size - i) * 2 + 1), end='') 18 | print('*' * (i * 2 - 1)) 19 | 20 | 21 | def solution(): 22 | size = int(input()) 23 | draw_top(size) 24 | draw_bottom(size) 25 | 26 | 27 | solution() 28 | -------------------------------------------------------------------------------- /Python/rectangular-block-spinner.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/rectangular-block-spinner 2 | 3 | 4 | def solution(): 5 | size = int(input()) 6 | angle = int(input()) 7 | ascii = [input()[::2] for _ in range(size)] 8 | 9 | for _ in range(4 - ((angle % 360 // 90 + 1) % 4)): 10 | ascii = list(zip(*reversed(ascii))) 11 | 12 | for i in range(size): 13 | print('{0}{1}{0}'.format( 14 | ' ' * (size - i - 1), 15 | ' '.join([ascii[i - j][j] for j in range(i + 1)]) 16 | )) 17 | 18 | for i in range(1, size): 19 | print('{0}{1}{0}'.format( 20 | ' ' * i, 21 | ' '.join([ascii[size - j - 1][i + j] for j in range(size - i)]) 22 | )) 23 | 24 | 25 | solution() 26 | -------------------------------------------------------------------------------- /Python/detective-pikaptcha-ep1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/detective-pikaptcha-ep1 2 | 3 | 4 | def get_neighbors(row, col, grid): 5 | if row > 0: yield row - 1, col 6 | if row < len(grid) - 1: yield row + 1, col 7 | if col > 0: yield row, col - 1 8 | if col < len(grid[row]) - 1: yield row, col + 1 9 | 10 | 11 | def solution(): 12 | width, height = [int(i) for i in input().split()] 13 | grid = [list(input()) for _ in range(height)] 14 | 15 | for row in range(height): 16 | for col in range(width): 17 | if grid[row][col] == '#': continue 18 | grid[row][col] = str(sum(grid[r][c] != '#' for r, c in get_neighbors(row, col, grid))) 19 | 20 | for row in grid: 21 | print(''.join(row)) 22 | 23 | 24 | solution() 25 | -------------------------------------------------------------------------------- /Python/ascii-art.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/ascii-art 2 | 3 | 4 | def get_ascii_map_index(char): 5 | if char not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': 6 | return 26 7 | 8 | return ord(char) - ord('A') 9 | 10 | 11 | def solution(): 12 | width = int(input()) 13 | height = int(input()) 14 | text = input() 15 | 16 | ascii_map = [[] for _ in range(27)] 17 | 18 | for _ in range(height): 19 | line = input() 20 | for i in range(27): 21 | ascii_map[i].append(line[i * width:i * width + width]) 22 | 23 | for col in range(height): 24 | for char in text.upper(): 25 | part = ascii_map[get_ascii_map_index(char)][col] 26 | print('{}'.format(part), end='') 27 | print() 28 | 29 | 30 | solution() 31 | -------------------------------------------------------------------------------- /Python/conway-sequence.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/conway-sequence 2 | 3 | 4 | def solution(): 5 | sequence = [int(input())] 6 | 7 | for _ in range(int(input()) - 1): 8 | prev_c, num_c = 0, 0 9 | new_sequence = [] 10 | for c in sequence: 11 | if prev_c == 0: 12 | prev_c = c 13 | num_c = 1 14 | elif c == prev_c: 15 | num_c += 1 16 | else: 17 | new_sequence.append(num_c) 18 | new_sequence.append(prev_c) 19 | prev_c = c 20 | num_c = 1 21 | 22 | new_sequence.append(num_c) 23 | new_sequence.append(prev_c) 24 | sequence = new_sequence 25 | 26 | print(' '.join(map(str, sequence))) 27 | 28 | 29 | solution() 30 | -------------------------------------------------------------------------------- /Python/balanced-ternary-computer-encode.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/balanced-ternary-computer-encode 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | def convert_system(num): 8 | if num in (0, 1): 9 | return str(num) 10 | return 'T' 11 | 12 | 13 | def solution(): 14 | n = int(input()) 15 | 16 | if n in (0, 1, -1): 17 | print(convert_system(n)) 18 | return 19 | 20 | queue = deque([(0, '0'), (1, '1'), (-1, 'T')]) 21 | 22 | while True: 23 | val, bt = queue.popleft() 24 | 25 | for x in (0, 1, -1): 26 | nval = x * 3 ** len(bt) + val 27 | nbt = convert_system(x) + bt 28 | if nval == n: 29 | print(nbt) 30 | return 31 | queue.append((nval, nbt)) 32 | 33 | 34 | solution() 35 | -------------------------------------------------------------------------------- /Python/there-is-no-spoon-episode-1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/there-is-no-spoon-episode-1 2 | 3 | 4 | def solution(): 5 | width = int(input()) 6 | height = int(input()) 7 | grid = [input() for _ in range(height)] 8 | 9 | for x in range(width): 10 | for y in range(height): 11 | if grid[y][x] == '.': continue 12 | rx = ry = bx = by = -1 13 | 14 | for i in range(x + 1, width): 15 | if grid[y][i] == '.': continue 16 | rx, ry = i, y 17 | break 18 | 19 | for i in range(y + 1, height): 20 | if grid[i][x] == '.': continue 21 | bx, by = x, i 22 | break 23 | 24 | print('{} {} {} {} {} {}'.format(x, y, rx, ry, bx, by)) 25 | 26 | 27 | solution() 28 | -------------------------------------------------------------------------------- /Python/self-driving-car-testing.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/self-driving-car-testing 2 | 3 | 4 | def get_next_pos(pos, commands): 5 | for command in commands: 6 | n, d = int(command[:-1]), command[-1] 7 | for _ in range(n): 8 | if d == 'L': 9 | pos -= 1 10 | elif d == 'R': 11 | pos += 1 12 | yield pos 13 | 14 | 15 | def solution(): 16 | n = int(input()) 17 | pos, *commands = input().split(';') 18 | pos = int(pos) 19 | pos_iter = get_next_pos(pos, commands) 20 | 21 | for _ in range(n): 22 | rep, pattern = input().split(';') 23 | for _ in range(int(rep)): 24 | road = list(pattern) 25 | road[next(pos_iter) - 1] = '#' 26 | print(''.join(road)) 27 | 28 | 29 | solution() 30 | -------------------------------------------------------------------------------- /Python/111-rubiks-cube-movements.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/111-rubiks-cube-movements 2 | 3 | 4 | def solution(): 5 | rotations = input().split() 6 | face1, face2 = input(), input() 7 | F, B, U, D, L, R = 'FBUDLR' 8 | 9 | for rotation in rotations: 10 | if rotation[0] == 'x': 11 | if "'" in rotation: F, B, U, D = U, D, B, F 12 | else: F, B, U, D = D, U, F, B 13 | elif rotation[0] == 'y': 14 | if "'" in rotation: F, B, L, R = L, R, B, F 15 | else: F, B, L, R = R, L, F, B 16 | else: 17 | if "'" in rotation: U, D, L, R = R, L, U, D 18 | else: U, D, L, R = L, R, D, U 19 | 20 | loc = locals() 21 | print([x for x in loc if loc[x] == face1][0]) 22 | print([x for x in loc if loc[x] == face2][0]) 23 | 24 | 25 | solution() 26 | -------------------------------------------------------------------------------- /Python/simple-awale.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/simple-awale 2 | 3 | 4 | def solution(): 5 | op_bowls = list(map(int, input().split())) 6 | my_bowls = list(map(int, input().split())) 7 | bowl_index = int(input()) 8 | 9 | grains = my_bowls[bowl_index] 10 | my_bowls[bowl_index] = 0 11 | bowl_index += 1 12 | while grains > 0: 13 | if bowl_index % 14 < 7: 14 | my_bowls[bowl_index % 7] += 1 15 | grains -= 1 16 | elif bowl_index % 14 < 13: 17 | op_bowls[bowl_index % 7] += 1 18 | grains -= 1 19 | bowl_index += 1 20 | 21 | print('{} [{}]'.format(' '.join(map(str, op_bowls[:-1])), op_bowls[-1])) 22 | print('{} [{}]'.format(' '.join(map(str, my_bowls[:-1])), my_bowls[-1])) 23 | if bowl_index == 7: print('REPLAY') 24 | 25 | 26 | solution() 27 | -------------------------------------------------------------------------------- /Python/xml-mdf-2016.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/xml-mdf-2016 2 | 3 | 4 | def solution(): 5 | depth = 1 6 | tag_weights = {} 7 | skip = False 8 | 9 | for c in input(): 10 | if skip: 11 | skip = False 12 | elif c == '-': 13 | depth -= 1 14 | skip = True 15 | else: 16 | if c not in tag_weights: 17 | tag_weights[c] = 0 18 | tag_weights[c] += 1 / depth 19 | depth += 1 20 | 21 | max_tag = '' 22 | max_weight = 0 23 | 24 | for tw in tag_weights: 25 | if tag_weights[tw] > max_weight: 26 | max_weight = tag_weights[tw] 27 | max_tag = tw 28 | elif tag_weights[tw] == max_weight and tw < max_tag: 29 | max_weight = tag_weights[tw] 30 | max_tag = tw 31 | 32 | print(max_tag) 33 | 34 | 35 | solution() 36 | -------------------------------------------------------------------------------- /Python/hunger-games.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/ide/puzzle/hunger-games 2 | 3 | 4 | def solution(): 5 | num_tributes = int(input()) 6 | tributes = {input(): {'killer': 'Winner', 'killed': []} for _ in range(num_tributes)} 7 | turns = int(input()) 8 | for _ in range(turns): 9 | name, _, *victims = input().split() 10 | for victim in [v.replace(',', '') for v in victims]: 11 | tributes[name]['killed'].append(victim) 12 | tributes[victim]['killer'] = name 13 | 14 | for i, tribute in enumerate(sorted(tributes)): 15 | if i != 0: print() 16 | print('Name: {}'.format(tribute)) 17 | victims = tributes[tribute]['killed'] 18 | if not victims: print('Killed: None') 19 | else: print('Killed: {}'.format(', '.join(sorted(victims)))) 20 | print('Killer: {}'.format(tributes[tribute]['killer'])) 21 | 22 | 23 | solution() 24 | -------------------------------------------------------------------------------- /Python/guessing-n-cheating.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/guessing-n-cheating 2 | 3 | 4 | def solution(): 5 | num_rounds = int(input()) 6 | rounds = [input().split() for _ in range(num_rounds)] 7 | answer = int(rounds[-1][0]) 8 | l, r = 1, 100 9 | 10 | for n, rnd in enumerate(rounds): 11 | guess = int(rnd[0]) 12 | reply = ' '.join(rnd[1:]) 13 | 14 | if reply == 'too high': 15 | r = min(r, guess - 1) 16 | elif reply == 'too low': 17 | l = max(l, guess + 1) 18 | else: 19 | continue 20 | 21 | if l > r: 22 | print('Alice cheated in round {}'.format(n + 1)) 23 | break 24 | 25 | else: 26 | if l <= answer <= r: 27 | print('No evidence of cheating') 28 | else: 29 | print('Alice cheated in round {}'.format(num_rounds)) 30 | 31 | 32 | solution() 33 | -------------------------------------------------------------------------------- /Python/the-frog-jump.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/the-frog-jump-1 2 | 3 | 4 | import math 5 | 6 | 7 | def solution(): 8 | frog_number = int(input()) 9 | distances = list(map(float, input().split())) 10 | 11 | x, y = map(int, input().split()) 12 | mass = int(input()) 13 | alpha = math.radians(int(input())) 14 | speed = float(input()) 15 | a, b = map(float, input().split()) 16 | 17 | speed_x = math.cos(alpha) * speed 18 | speed_y = math.sin(alpha) * speed 19 | 20 | delta = speed_y ** 2 - 4 * (b / 2) * y 21 | time = (-speed_y - delta ** 0.5) / b 22 | dist = (a / 2 * time ** 2) + (speed_x * time) + x 23 | dist = round(dist, 2) 24 | 25 | distances.append(dist) 26 | distances = sorted(distances, reverse=True) 27 | 28 | for i, distance in enumerate(distances): 29 | if distance == dist: 30 | break 31 | 32 | print(i + 1) 33 | 34 | 35 | solution() 36 | -------------------------------------------------------------------------------- /Python/chuck-norris.py: -------------------------------------------------------------------------------- 1 | def print_conversion(prev_char, cur_count, first_char): 2 | space = '' if first_char else ' ' 3 | 4 | if prev_char == '0': 5 | print('{}00 {}'.format(space, '0' * cur_count), end='') 6 | else: 7 | print('{}0 {}'.format(space, '0' * cur_count), end='') 8 | 9 | 10 | def solution(): 11 | binary = [] 12 | for char in input(): 13 | binary.extend('{:b}'.format(ord(char)).zfill(7)) 14 | 15 | prev_char = None 16 | cur_count = 0 17 | first_char = True 18 | for x in binary: 19 | if prev_char is None: 20 | prev_char = x 21 | cur_count += 1 22 | elif prev_char == x: 23 | cur_count += 1 24 | else: 25 | print_conversion(prev_char, cur_count, first_char) 26 | first_char = False 27 | prev_char = x 28 | cur_count = 1 29 | 30 | print_conversion(prev_char, cur_count, first_char) 31 | 32 | 33 | solution() 34 | -------------------------------------------------------------------------------- /Python/dead-mens-shot.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/dead-mens-shot 2 | 3 | 4 | def within_polygon(x, y, points, num_corners): 5 | pos, neg = False, False 6 | 7 | for i in range(num_corners): 8 | x1, y1 = points[i] 9 | x2, y2 = points[(i + 1) % num_corners] 10 | d = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1) 11 | 12 | if d > 0: 13 | pos = True 14 | else: 15 | neg = True 16 | 17 | if pos == neg: return False 18 | return True 19 | 20 | 21 | def solution(): 22 | points = [] 23 | 24 | num_corners = int(input()) 25 | for _ in range(num_corners): 26 | points.append(list(map(int, input().split()))) 27 | 28 | num_shots = int(input()) 29 | for _ in range(num_shots): 30 | x, y = map(int, input().split()) 31 | if within_polygon(x, y, points, num_corners): 32 | print('hit') 33 | else: 34 | print('miss') 35 | 36 | 37 | solution() 38 | -------------------------------------------------------------------------------- /Python/power-of-thor-episode-1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/power-of-thor-episode-1 2 | 3 | 4 | def find_move(light_x, light_y, thor_x, thor_y): 5 | direction = '' 6 | change_x, change_y = 0, 0 7 | 8 | if thor_y < light_y: 9 | direction += 'S' 10 | change_y += 1 11 | elif thor_y > light_y: 12 | direction += 'N' 13 | change_y -= 1 14 | 15 | if thor_x < light_x: 16 | direction += 'E' 17 | change_x += 1 18 | elif thor_x > light_x: 19 | direction += 'W' 20 | change_x -= 1 21 | 22 | return direction, change_x, change_y 23 | 24 | 25 | def solution(): 26 | light_x, light_y, thor_x, thor_y = map(int, input().split()) 27 | 28 | while True: 29 | remaining_turns = int(input()) 30 | direction, change_x, change_y = find_move(light_x, light_y, thor_x, thor_y) 31 | thor_x, thor_y = thor_x + change_x, thor_y + change_y 32 | print(direction) 33 | 34 | 35 | solution() 36 | -------------------------------------------------------------------------------- /Python/blowing-fuse.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/blowing-fuse 2 | 3 | 4 | def solution(): 5 | num_devices, num_clicks, main_fuse_capacity = map(int, input().split()) 6 | device_capacities = [0] + list(map(int, input().split())) 7 | device_state = [False] * (num_devices + 1) 8 | max_consumption = 0 9 | current_consumption = 0 10 | 11 | for device in map(int, input().split()): 12 | device_state[device] = not device_state[device] 13 | if device_state[device]: 14 | current_consumption += device_capacities[device] 15 | else: 16 | current_consumption -= device_capacities[device] 17 | 18 | if current_consumption > main_fuse_capacity: 19 | print('Fuse was blown.') 20 | return 21 | 22 | max_consumption = max(max_consumption, current_consumption) 23 | 24 | print('Fuse was not blown.') 25 | print('Maximal consumed current was {} A.'.format(max_consumption)) 26 | 27 | 28 | solution() 29 | -------------------------------------------------------------------------------- /Python/don't-panic-episode-1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/don't-panic-episode-1 2 | 3 | 4 | def solution(): 5 | num_floors, width, num_rounds, exit_floor, exit_pos, total_clones, _, num_elevators = map(int, input().split()) 6 | 7 | elevators = [0] * num_floors 8 | for _ in range(num_elevators): 9 | floor, pos = map(int, input().split()) 10 | elevators[floor] = pos 11 | 12 | elevators[exit_floor] = exit_pos 13 | 14 | while True: 15 | floor, pos, direction = input().split() 16 | floor, pos = int(floor), int(pos) 17 | 18 | if direction == 'LEFT': 19 | if pos >= elevators[floor]: 20 | print('WAIT') 21 | else: 22 | print('BLOCK') 23 | elif direction == 'RIGHT': 24 | if pos <= elevators[floor]: 25 | print('WAIT') 26 | else: 27 | print('BLOCK') 28 | else: 29 | print('BLOCK') 30 | 31 | 32 | solution() 33 | -------------------------------------------------------------------------------- /Python/bulk-email-generator.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/bulk-email-generator 2 | 3 | 4 | def solution(): 5 | text = '\n'.join(input() for _ in range(int(input()))) 6 | 7 | clause_choice = 0 8 | output = [] 9 | index = 0 10 | clause_index = 0 11 | in_clause = False 12 | 13 | while index < len(text): 14 | c = text[index] 15 | if c == '(': 16 | in_clause = True 17 | clause_index = index 18 | elif c == ')': 19 | in_clause = False 20 | if clause_index + 1 == index: 21 | index += 1 22 | continue 23 | 24 | clauses = text[clause_index + 1:index].split('|') 25 | output.append(clauses[clause_choice % len(clauses)]) 26 | clause_choice += 1 27 | elif in_clause: 28 | index += 1 29 | continue 30 | else: 31 | output.append(c) 32 | index += 1 33 | 34 | print(''.join(output)) 35 | 36 | 37 | solution() 38 | -------------------------------------------------------------------------------- /Python/defibrillators.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/defibrillators 2 | 3 | 4 | import math 5 | 6 | 7 | def distance_between(longitudeA, latitudeA, longitudeB, latitudeB): 8 | x = (longitudeB - longitudeA) * math.cos((latitudeA + latitudeB) / 2) 9 | y = (latitudeB - latitudeA) 10 | return (x ** 2 + y ** 2) ** 0.5 * 6371 11 | 12 | 13 | def solution(): 14 | longitude = float(input().replace(',', '.')) 15 | latitude = float(input().replace(',', '.')) 16 | num_defibrillators = int(input()) 17 | 18 | min_dist = float('inf') 19 | min_defib_name = None 20 | for _ in range(num_defibrillators): 21 | line = input().split(';') 22 | defib_longitude = float(line[4].replace(',', '.')) 23 | defib_latitude = float(line[5].replace(',', '.')) 24 | 25 | dist = distance_between(longitude, latitude, defib_longitude, defib_latitude) 26 | if dist < min_dist: 27 | min_dist = dist 28 | min_defib_name = line[1] 29 | 30 | print(min_defib_name) 31 | 32 | 33 | solution() 34 | -------------------------------------------------------------------------------- /Python/plague-jr.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/plague-jr 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | def simulate(node, edges, current_min): 8 | queue = deque([(node, 0)]) 9 | visited = {node} 10 | 11 | while queue: 12 | node, night = queue.popleft() 13 | if night >= current_min: 14 | return current_min 15 | 16 | for o in edges[node]: 17 | if o not in visited: 18 | queue.append((o, night + 1)) 19 | visited.add(o) 20 | 21 | return night 22 | 23 | 24 | def solution(): 25 | num_rods = int(input()) 26 | edges = {} 27 | 28 | for _ in range(num_rods): 29 | a, b = map(int, input().split()) 30 | if a not in edges: edges[a] = [] 31 | if b not in edges: edges[b] = [] 32 | edges[a].append(b) 33 | edges[b].append(a) 34 | 35 | current_min = float('inf') 36 | for node in edges: 37 | current_min = simulate(node, edges, current_min) 38 | 39 | print(current_min) 40 | 41 | 42 | solution() 43 | -------------------------------------------------------------------------------- /Python/organic-compounds.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/organic-compounds 2 | 3 | 4 | def check_for_bond(row, col, formula): 5 | if row < 0 or row >= len(formula): return 0 6 | if col < 0 or col >= len(formula[row]): return 0 7 | return int(formula[row][col]) if formula[row][col] in '0123' else 0 8 | 9 | 10 | def sum_bonds(row, col, formula): 11 | return check_for_bond(row, col - 2, formula) + \ 12 | check_for_bond(row, col + 4, formula) + \ 13 | check_for_bond(row - 1, col + 1, formula) + \ 14 | check_for_bond(row + 1, col + 1, formula) 15 | 16 | 17 | def solution(): 18 | formula = [input() for _ in range(int(input()))] 19 | 20 | for row in range(len(formula)): 21 | for col in range(len(formula[row])): 22 | if formula[row][col] == 'C': 23 | carbon_units = int(formula[row][col + 2]) 24 | bonds = sum_bonds(row, col, formula) 25 | if carbon_units + bonds != 4: 26 | print('INVALID') 27 | return 28 | 29 | print('VALID') 30 | 31 | 32 | solution() 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Jared Gillespie 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Python/isbn-check-digit.py: -------------------------------------------------------------------------------- 1 | def is_valid_isbn(isbn): 2 | if len(isbn) not in (10, 13): return False 3 | if 'X' in isbn[:-1]: return False 4 | if len(isbn) == 10: return is_valid_isbn10(isbn) 5 | return is_valid_isbn13(isbn) 6 | 7 | 8 | def is_valid_isbn10(isbn): 9 | w = 10 10 | s = 0 11 | for d in isbn[:-1]: 12 | s += w * int(d) 13 | w -= 1 14 | 15 | if s % 11 == 0: return isbn[-1] == '0' 16 | if s % 11 == 1: return isbn[-1] == 'X' 17 | if isbn[-1] == 'X': return False 18 | return int(isbn[-1]) == 11 - s % 11 19 | 20 | 21 | def is_valid_isbn13(isbn): 22 | w = 1 23 | s = 0 24 | for d in isbn[:-1]: 25 | s += w * int(d) 26 | w ^= 2 27 | 28 | if s % 10 == 0: return isbn[-1] == '0' 29 | if isbn[-1] == 'X': return False 30 | return int(isbn[-1]) == 10 - s % 10 31 | 32 | 33 | def solution(): 34 | num_isbns = int(input()) 35 | invalid_isbns = [] 36 | 37 | for _ in range(num_isbns): 38 | isbn = input() 39 | if not is_valid_isbn(isbn): 40 | invalid_isbns.append(isbn) 41 | 42 | print('{} invalid:'.format(len(invalid_isbns))) 43 | for isbn in invalid_isbns: 44 | print(isbn) 45 | 46 | 47 | solution() 48 | -------------------------------------------------------------------------------- /Python/text-formatting.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/text-formatting 2 | 3 | 4 | import string 5 | 6 | VALID_CHARACTERS = set(string.ascii_letters + string.digits) 7 | 8 | 9 | def parse(text): 10 | prev_char = '' 11 | for c in text.lower(): 12 | if prev_char == '': 13 | if c in VALID_CHARACTERS: 14 | prev_char = c.upper() 15 | 16 | elif c in VALID_CHARACTERS: 17 | if prev_char in VALID_CHARACTERS or prev_char == ' ': 18 | yield prev_char 19 | prev_char = c 20 | elif prev_char in ',;': 21 | yield prev_char + ' ' 22 | prev_char = c 23 | else: 24 | yield prev_char + ' ' 25 | prev_char = c.upper() 26 | 27 | elif c == ' ': 28 | if prev_char in VALID_CHARACTERS: 29 | yield prev_char 30 | prev_char = c 31 | 32 | else: 33 | if prev_char in VALID_CHARACTERS: 34 | yield prev_char 35 | prev_char = c 36 | 37 | if prev_char != ' ': 38 | yield prev_char 39 | 40 | 41 | def solution(): 42 | print(''.join(parse(input()))) 43 | 44 | 45 | solution() 46 | -------------------------------------------------------------------------------- /Python/skynet-revolution-episode-1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/skynet-revolution-episode-1 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | def find_closest_exit_link(start_node, links, exit_nodes): 8 | visited = {start_node} 9 | queue = deque([(None, start_node)]) 10 | 11 | while queue: 12 | prev_node, node = queue.popleft() 13 | 14 | if node in exit_nodes: 15 | return prev_node, node 16 | 17 | for neighbor in links[node]: 18 | if neighbor in visited: continue 19 | queue.append((node, neighbor)) 20 | 21 | 22 | def solution(): 23 | num_nodes, num_links, num_exits = map(int, input().split()) 24 | links = {l: set() for l in range(num_nodes)} 25 | for _ in range(num_links): 26 | node_1, node_2 = map(int, input().split()) 27 | links[node_1].add(node_2) 28 | links[node_2].add(node_1) 29 | 30 | exit_nodes = {int(input()) for _ in range(num_exits)} 31 | 32 | while True: 33 | skynet_node = int(input()) 34 | node_1, node_2 = find_closest_exit_link(skynet_node, links, exit_nodes) 35 | links[node_1].remove(node_2) 36 | links[node_2].remove(node_1) 37 | print('{} {}'.format(node_1, node_2)) 38 | 39 | 40 | solution() 41 | -------------------------------------------------------------------------------- /Python/scrabble.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/scrabble 2 | 3 | 4 | from collections import Counter 5 | 6 | letter_weights = { 7 | 'e': 1, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'r': 1, 't': 1, 'l': 1, 's': 1, 'u': 1, 8 | 'd': 2, 'g': 2, 9 | 'b': 3, 'c': 3, 'm': 3, 'p': 3, 10 | 'f': 4, 'h': 4, 'v': 4, 'w': 4, 'y': 4, 11 | 'k': 5, 12 | 'j': 8, 'x': 8, 13 | 'q': 10, 'z': 10 14 | } 15 | 16 | 17 | def can_make_word(word, letters): 18 | word_counter, letters_counter = Counter(word), Counter(letters) 19 | if any(c for c in word if c not in letters): return False 20 | for c in word_counter: 21 | if c not in letters_counter: return False 22 | if word_counter[c] > letters_counter[c]: return False 23 | return True 24 | 25 | 26 | def get_word_score(word): 27 | return sum(letter_weights[c] for c in word) 28 | 29 | 30 | def solution(): 31 | words = [input() for _ in range(int(input()))] 32 | letters = input() 33 | max_word_score = 0 34 | max_word = '' 35 | 36 | for word in words: 37 | if not can_make_word(word, letters): continue 38 | word_score = get_word_score(word) 39 | if word_score > max_word_score: 40 | max_word_score = word_score 41 | max_word = word 42 | 43 | print(max_word) 44 | 45 | 46 | solution() 47 | -------------------------------------------------------------------------------- /Python/stall-tilt.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/stall-tilt 2 | 3 | 4 | import math 5 | 6 | STALL_ANGLE = 30 7 | 8 | 9 | def min_bend_speed(bend): 10 | return int((math.tan(math.radians(90 - STALL_ANGLE)) * bend * 9.81) ** 0.5) 11 | 12 | 13 | def find_optimal_speed(bends): 14 | return min(min_bend_speed(b) for b in bends) 15 | 16 | 17 | def find_rankings(speeds, bends): 18 | active_racers = set(range(len(speeds))) 19 | min_bend_speeds = [min_bend_speed(b) for b in bends] 20 | rankings = [] 21 | 22 | for mbs in min_bend_speeds: 23 | failed_racers = [r for r in active_racers if speeds[r] > mbs] 24 | for racer in sorted(failed_racers, key=lambda x: speeds[x]): 25 | active_racers.remove(racer) 26 | rankings.append(racer) 27 | 28 | for racer in sorted(active_racers, key=lambda x: speeds[x]): 29 | rankings.append(racer) 30 | 31 | return reversed(rankings) 32 | 33 | 34 | def solution(): 35 | num_motorcycles = int(input()) 36 | num_curves = int(input()) 37 | speeds = [int(input()) for _ in range(num_motorcycles)] 38 | bends = [int(input()) for _ in range(num_curves)] 39 | 40 | print(find_optimal_speed(bends)) 41 | print('y') 42 | for m in find_rankings(speeds, bends): 43 | print(chr(m + ord('a'))) 44 | 45 | 46 | solution() 47 | -------------------------------------------------------------------------------- /Python/ghost-legs.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/ghost-legs 2 | 3 | 4 | def find_path(current_index, levels, h, w): 5 | for level_index in range(h - 2): 6 | level = levels[level_index] 7 | if current_index == 0: 8 | if level[current_index + 1] == '-': 9 | current_index += 3 10 | elif current_index == w - 1: 11 | if level[current_index - 1] == '-': 12 | current_index -= 3 13 | else: 14 | if level[current_index + 1] == '-': 15 | current_index += 3 16 | elif level[current_index - 1] == '-': 17 | current_index -= 3 18 | return current_index 19 | 20 | 21 | def solution(): 22 | w, h = map(int, input().split()) 23 | 24 | top_labels = None 25 | bottom_labels = None 26 | levels = [] 27 | 28 | for i in range(h): 29 | if i == 0: 30 | top_labels = input().split() 31 | elif i == h - 1: 32 | bottom_labels = input().split() 33 | else: 34 | levels.append(list(input())) 35 | 36 | for top_index, top_label in enumerate(top_labels): 37 | bottom_index = find_path(top_index * 3, levels, h, w) // 3 38 | bottom_label = bottom_labels[bottom_index] 39 | print('{}{}'.format(top_label, bottom_label)) 40 | 41 | 42 | solution() 43 | -------------------------------------------------------------------------------- /Python/the-traveling-salesman-problem.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/the-travelling-salesman-problem 2 | 3 | 4 | def dist_between(p1, p2): 5 | x1, y1 = p1 6 | x2, y2 = p2 7 | return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 8 | 9 | 10 | def find_closest(cur_point, points, used_points): 11 | closest_dist = float('inf') 12 | closest_point_index = -1 13 | for i, point in enumerate(points): 14 | if used_points[i]: continue 15 | dist = dist_between(cur_point, point) 16 | if dist < closest_dist: 17 | closest_dist = dist 18 | closest_point_index = i 19 | 20 | used_points[closest_point_index] = True 21 | return points[closest_point_index], closest_dist 22 | 23 | 24 | def solution(): 25 | num_points = int(input()) 26 | points = [] 27 | used_points = [False] * num_points 28 | first_point = None 29 | 30 | for i in range(num_points): 31 | x, y = map(int, input().split()) 32 | if i == 0: 33 | first_point = (x, y) 34 | else: 35 | points.append((x, y)) 36 | 37 | cur_point = first_point 38 | total_dist = 0 39 | for _ in range(num_points - 1): 40 | cur_point, dist = find_closest(cur_point, points, used_points) 41 | total_dist += dist 42 | 43 | total_dist += dist_between(cur_point, first_point) 44 | print(round(total_dist)) 45 | 46 | 47 | solution() 48 | -------------------------------------------------------------------------------- /Python/hooch-clash.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/hooch-clash 2 | 3 | 4 | import math 5 | 6 | 7 | ERROR = 0.001 8 | 9 | 10 | def volume(diameter): 11 | return (4 / 3) * math.pi * (diameter / 2)**3 12 | 13 | 14 | def volume_equal(v1, v2): 15 | return v1 - ERROR <= v2 <= v1 + ERROR 16 | 17 | 18 | def solution(): 19 | orb_size_min, orb_size_max = map(int, input().split()) 20 | glowing_size_1, glowing_size_2 = map(int, input().split()) 21 | 22 | target_volume = volume(glowing_size_1) + volume(glowing_size_2) 23 | sparkling_size_1 = glowing_size_1 24 | sparkling_size_2 = glowing_size_2 25 | sparkling_difference = glowing_size_2 - glowing_size_1 26 | 27 | for o1 in range(orb_size_min, orb_size_max + 1): 28 | v1 = volume(o1) 29 | 30 | for o2 in range(o1, orb_size_max + 1): 31 | v2 = volume(o2) 32 | if volume_equal(v1 + v2, target_volume): 33 | if sparkling_size_1 == glowing_size_1 or o2 - o1 > sparkling_difference: 34 | sparkling_size_1 = o1 35 | sparkling_size_2 = o2 36 | sparkling_difference = o2 - o1 37 | break 38 | 39 | if v1 + v2 > target_volume: 40 | break 41 | 42 | if sparkling_size_1 == glowing_size_1: 43 | print('VALID') 44 | else: 45 | print('{} {}'.format(sparkling_size_1, sparkling_size_2)) 46 | 47 | 48 | solution() 49 | -------------------------------------------------------------------------------- /Python/winamax-battle.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/winamax-battle 2 | 3 | 4 | from collections import deque 5 | 6 | card_values = {c: v for v, c in enumerate(['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'])} 7 | 8 | 9 | def solution(): 10 | cards_1 = deque([input()[:-1] for _ in range(int(input()))]) 11 | cards_2 = deque([input()[:-1] for _ in range(int(input()))]) 12 | game_rounds = 0 13 | 14 | while cards_1 and cards_2: 15 | game_rounds += 1 16 | war_cards_1 = [cards_1.popleft()] 17 | war_cards_2 = [cards_2.popleft()] 18 | 19 | while card_values[war_cards_1[-1]] == card_values[war_cards_2[-1]]: 20 | for _ in range(4): 21 | if cards_1: 22 | war_cards_1.append(cards_1.popleft()) 23 | else: 24 | print('PAT'); return 25 | if cards_2: 26 | war_cards_2.append(cards_2.popleft()) 27 | else: 28 | print('PAT'); return 29 | 30 | if card_values[war_cards_1[-1]] > card_values[war_cards_2[-1]]: 31 | winner_cards = cards_1 32 | else: 33 | winner_cards = cards_2 34 | 35 | for card in war_cards_1 + war_cards_2: 36 | winner_cards.append(card) 37 | 38 | if cards_1: 39 | print('1 {}'.format(game_rounds)) 40 | else: 41 | print('2 {}'.format(game_rounds)) 42 | 43 | 44 | solution() 45 | -------------------------------------------------------------------------------- /Python/the-last-crusade-episode-1.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/medium/the-last-crusade-episode-1 2 | 3 | 4 | def solution(): 5 | w, h = map(int, input().split()) 6 | grid = [input().split() for _ in range(h)] 7 | ex = int(input()) 8 | 9 | while True: 10 | xi, yi, pos = input().split() 11 | xi, yi = int(xi), int(yi) 12 | room = int(grid[yi][xi]) 13 | if room == 0: print('{} {}'.format(xi, yi)) 14 | elif room in (1, 3, 7, 8, 9): print('{} {}'.format(xi, yi + 1)) 15 | elif room == 2: 16 | if pos == 'LEFT': print('{} {}'.format(xi + 1, yi)) 17 | elif pos == 'RIGHT': print('{} {}'.format(xi - 1, yi)) 18 | else: print('{} {}'.format(xi, yi)) 19 | elif room == 4: 20 | if pos == 'TOP': print('{} {}'.format(xi - 1, yi)) 21 | elif pos == 'RIGHT': print('{} {}'.format(xi, yi + 1)) 22 | else: print('{} {}'.format(xi, yi)) 23 | elif room == 5: 24 | if pos == 'TOP': print('{} {}'.format(xi + 1, yi)) 25 | elif pos == 'LEFT': print('{} {}'.format(xi, yi + 1)) 26 | else: print('{} {}'.format(xi, yi)) 27 | elif room == 6: 28 | if pos == 'LEFT': print('{} {}'.format(xi + 1, yi)) 29 | else: print('{} {}'.format(xi - 1, yi)) 30 | elif room == 10: print('{} {}'.format(xi - 1, yi)) 31 | elif room == 11: print('{} {}'.format(xi + 1, yi)) 32 | else: print('{} {}'.format(xi, yi + 1)) 33 | 34 | 35 | solution() 36 | -------------------------------------------------------------------------------- /Python/order-of-succession.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/order-of-succession 2 | 3 | 4 | class Person: 5 | def __init__(self, name, parent, birth, death, religion, gender): 6 | self.name = name 7 | self.parent = parent 8 | self.birth = birth 9 | self.death = death 10 | self.religion = religion 11 | self.gender = gender 12 | 13 | @classmethod 14 | def new(cls, text): 15 | name, parent, birth, death, religion, gender = text.split() 16 | if parent == '-': parent = None 17 | if death == '-': death = None 18 | return cls(name, parent, birth, death, religion, gender) 19 | 20 | 21 | def person_sort_key(person): 22 | return ( 23 | 0 if person.gender == 'M' else 1, # Males come first 24 | person.birth 25 | ) 26 | 27 | 28 | def traverse(person, relations): 29 | if person.death is None and person.religion != 'Catholic': 30 | print(person.name) 31 | 32 | if person.name not in relations: return 33 | 34 | for p in sorted(relations[person.name], key=person_sort_key): 35 | traverse(p, relations) 36 | 37 | 38 | def solution(): 39 | num_people = int(input()) 40 | relations = {} 41 | queen = None 42 | 43 | for i in range(num_people): 44 | person = Person.new(input()) 45 | if i == 0: queen = person 46 | 47 | if person.parent not in relations: 48 | relations[person.parent] = [] 49 | 50 | relations[person.parent].append(person) 51 | 52 | traverse(queen, relations) 53 | 54 | 55 | solution() 56 | -------------------------------------------------------------------------------- /Python/pirates-treasure.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/pirates-treasure 2 | 3 | 4 | def get_neighbors(x, y, width, height): 5 | if x > 0: 6 | yield x - 1, y 7 | if y > 0: yield x - 1, y - 1 8 | if y < height - 1: yield x - 1, y + 1 9 | 10 | if x < width - 1: 11 | yield x + 1, y 12 | if y > 0: yield x + 1, y - 1 13 | if y < height - 1: yield x + 1, y + 1 14 | 15 | if y > 0: yield x, y - 1 16 | if y < height - 1: yield x, y + 1 17 | 18 | 19 | def count_land_neighbors(x, y, width, height, treasure_map): 20 | return sum(treasure_map[ny][nx] for nx, ny in get_neighbors(x, y, width, height)) 21 | 22 | 23 | def is_treasure(x, y, width, height, treasure_map): 24 | if treasure_map[y][x] == 1: return False 25 | land_neighbors = count_land_neighbors(x, y, width, height, treasure_map) 26 | 27 | if land_neighbors == 3: 28 | return (x, y) in [(0, 0), (0, height - 1), (width - 1, 0), (width - 1, height - 1)] 29 | elif land_neighbors == 5: 30 | return x in (0, width - 1) or y in (0, height - 1) 31 | elif land_neighbors == 8: 32 | return x not in (0, width - 1) and y not in (0, height - 1) 33 | 34 | return False 35 | 36 | 37 | def solution(): 38 | width = int(input()) 39 | height = int(input()) 40 | 41 | treasure_map = [] 42 | for _ in range(height): 43 | treasure_map.append(list(map(int, input().split()))) 44 | 45 | for y in range(height): 46 | for x in range(width): 47 | if is_treasure(x, y, width, height, treasure_map): 48 | print('{} {}'.format(x, y)) 49 | 50 | 51 | solution() 52 | -------------------------------------------------------------------------------- /Python/morellets-random-lines.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/morellets-random-lines 2 | 3 | 4 | def gcd(a, b): 5 | while b: 6 | a, b = b, a % b 7 | return a 8 | 9 | 10 | def is_point_on_line(x, y, line): 11 | return line[0] * x + line[1] * y + line[2] == 0 12 | 13 | 14 | def reduce_equation(a, b, c): 15 | g = gcd(gcd(a, b), c) 16 | return a // g, b // g, c // g 17 | 18 | 19 | def get_line(x1, y1, x2, y2): 20 | m = (y1 - y2) / (x1 - x2) 21 | b = (x1 * y2 - x2 * y1) / (x1 - x2) 22 | return m, b 23 | 24 | 25 | def get_intersection_point_between_lines(sm, sb, la, lb, lc): 26 | x = (-lb * sb - lc) / (la + lb * sm) 27 | y = sm * x + sb 28 | return x, y 29 | 30 | 31 | def does_segment_intersect_line(sm, sb, la, lb, lc, xa, ya, xb, yb): 32 | px, py = get_intersection_point_between_lines(sm, sb, la, lb, lc) 33 | return min(xa, xb) <= px <= max(xa, xb) and min(ya, yb) <= py <= max(ya, yb) 34 | 35 | 36 | def solution(): 37 | xa, ya, xb, yb = map(int, input().split()) 38 | num_lines = int(input()) 39 | equations = {reduce_equation(*map(int, input().split())) 40 | for _ in range(num_lines)} 41 | 42 | for x, y in ((xa, ya), (xb, yb)): 43 | if any(is_point_on_line(x, y, line) for line in equations): 44 | print('ON A LINE') 45 | return 46 | 47 | sm, sb = get_line(xa, ya, xb, yb) 48 | num_crossed_lines = sum( 49 | does_segment_intersect_line(sm, sb, a, b, c, xa, ya, xb, yb) 50 | for a, b, c in equations 51 | ) 52 | 53 | print('YES' if num_crossed_lines % 2 == 0 else 'NO') 54 | 55 | 56 | solution() 57 | 58 | -------------------------------------------------------------------------------- /Python/lumen.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/lumen 2 | 3 | 4 | def get_neighbors(col, row, room_size): 5 | if room_size == 1: return 6 | 7 | if row > 0: 8 | yield col, row - 1 9 | if col > 0: yield col - 1, row - 1 10 | if col < room_size - 1: yield col + 1, row - 1 11 | 12 | if row < room_size - 1: 13 | yield col, row + 1 14 | if col > 0: yield col - 1, row + 1 15 | if col < room_size - 1: yield col + 1, row + 1 16 | 17 | if col > 0: yield col - 1, row 18 | if col < room_size - 1: yield col + 1, row 19 | 20 | 21 | def fill_light(col, row, light_level, room, room_size): 22 | if light_level == 0: return 23 | if room[col][row] in ('X', 'C'): 24 | room[col][row] = light_level 25 | elif room[col][row] >= light_level: 26 | return 27 | 28 | room[col][row] = light_level 29 | 30 | for nc, nr in get_neighbors(col, row, room_size): 31 | fill_light(nc, nr, light_level - 1, room, room_size) 32 | 33 | 34 | def count_dark_spots(room, room_size): 35 | ret = 0 36 | for col in range(room_size): 37 | for row in range(room_size): 38 | if room[col][row] in ('X', 0): 39 | ret += 1 40 | return ret 41 | 42 | 43 | def solution(): 44 | room_size = int(input()) 45 | base_light = int(input()) 46 | candles = [] 47 | 48 | room = [] 49 | for col in range(room_size): 50 | room.append(input().split()) 51 | for row, c in enumerate(room[-1]): 52 | if c == 'C': 53 | candles.append((col, row)) 54 | 55 | for col, row in candles: 56 | fill_light(col, row, base_light, room, room_size) 57 | 58 | dark_spots = count_dark_spots(room, room_size) 59 | print(dark_spots) 60 | 61 | 62 | solution() 63 | -------------------------------------------------------------------------------- /Python/encryptiondecryption-of-enigma-machine.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/encryptiondecryption-of-enigma-machine 2 | 3 | 4 | def forward_ceasar(ceasar_shift, message): 5 | ret = [] 6 | for c in message: 7 | ret.append(chr((ord(c) - ord('A') + ceasar_shift) % 26 + ord('A'))) 8 | ceasar_shift = (ceasar_shift + 1) % 26 9 | return ''.join(ret) 10 | 11 | 12 | def reverse_ceasar(ceasar_shift, message): 13 | ceasar_shift = (ceasar_shift + len(message) - 1) % 26 14 | ret = [] 15 | for c in reversed(message): 16 | ret.append(chr((ord(c) - ord('A') - ceasar_shift) % 26 + ord('A'))) 17 | ceasar_shift = (ceasar_shift - 1) % 26 18 | return ''.join(reversed(ret)) 19 | 20 | 21 | def forward_rotor(rotor, message): 22 | return ''.join(rotor[ord(c) - ord('A')] for c in message) 23 | 24 | 25 | def reverse_rotor(rotor, message): 26 | reverse_map = {c: i for i, c in enumerate(rotor)} 27 | return ''.join(chr(reverse_map[c] + ord('A')) for c in message) 28 | 29 | 30 | def encode(ceasar_shift, rotors, message): 31 | message = forward_ceasar(ceasar_shift, message) 32 | for rotor in rotors: 33 | message = forward_rotor(rotor, message) 34 | return message 35 | 36 | 37 | def decode(ceasar_shift, rotors, message): 38 | for rotor in reversed(rotors): 39 | message = reverse_rotor(rotor, message) 40 | message = reverse_ceasar(ceasar_shift, message) 41 | return message 42 | 43 | 44 | def solution(): 45 | operation = input() 46 | ceasar_shift = int(input()) 47 | rotors = [input() for _ in range(3)] 48 | message = input() 49 | 50 | if operation == 'ENCODE': 51 | print(encode(ceasar_shift, rotors, message)) 52 | else: 53 | print(decode(ceasar_shift, rotors, message)) 54 | 55 | 56 | solution() 57 | -------------------------------------------------------------------------------- /Python/darts.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/darts 2 | 3 | 4 | def within_polygon(x, y, points): 5 | pos, neg = False, False 6 | 7 | for i in range(len(points)): 8 | x1, y1 = points[i] 9 | x2, y2 = points[(i + 1) % len(points)] 10 | d = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1) 11 | 12 | if d > 0: 13 | pos = True 14 | else: 15 | neg = True 16 | 17 | if pos == neg: return False 18 | return True 19 | 20 | 21 | def within_square(x, y, size): 22 | l = size / 2 + 0.0001 23 | square_points = [(l, l), (l, -l), (-l, -l), (-l, l)] 24 | return within_polygon(x, y, square_points) 25 | 26 | 27 | def within_diamond(x, y, size): 28 | l = size / 2 + 0.0001 29 | diamond_points = [(0, l), (l, 0), (0, -l), (-l, 0)] 30 | return within_polygon(x, y, diamond_points) 31 | 32 | 33 | def within_circle(x, y, size): 34 | l = size / 2 + 0.0001 35 | return ((x ** 2) + (y ** 2)) ** 0.5 <= l 36 | 37 | 38 | def solution(): 39 | size = int(input()) 40 | num_competitors = int(input()) 41 | competitors = {} 42 | competitor_order = {} 43 | 44 | for i in range(num_competitors): 45 | name = input() 46 | competitors[name] = 0 47 | competitor_order[name] = i 48 | 49 | num_throws = int(input()) 50 | 51 | for _ in range(num_throws): 52 | name, x, y = input().split() 53 | x = int(x) 54 | y = int(y) 55 | competitors[name] += 5 * ( 56 | within_circle(x, y, size) + 57 | within_square(x, y, size) + 58 | within_diamond(x, y, size) 59 | ) 60 | 61 | for name in sorted(competitors, key=lambda x: (-competitors[x], competitor_order[x])): 62 | print('{} {}'.format(name, competitors[name])) 63 | 64 | 65 | solution() 66 | -------------------------------------------------------------------------------- /Python/the-dart-101.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/the-dart-101 2 | 3 | 4 | TARGET_SCORE = 101 5 | 6 | 7 | def simulate(shoots): 8 | rounds, throws, misses, score = 1, 0, 0, 0 9 | prev_round_score = 0 10 | prev_shot = '' 11 | for shot in shoots.split(): 12 | throws += 1 13 | 14 | if 'X' in shot: 15 | misses += 1 16 | score -= 20 17 | if prev_shot == 'X': score -= 10 18 | if misses == 3: score = 0 19 | if throws == 3: 20 | throws = 0 21 | rounds += 1 22 | misses = 0 23 | prev_shot = '' 24 | prev_round_score = score 25 | else: 26 | prev_shot = shot 27 | else: 28 | if '*' in shot: 29 | a, b = map(int, shot.split('*')) 30 | points = a * b 31 | else: 32 | points = int(shot) 33 | 34 | if score + points == TARGET_SCORE: 35 | return rounds 36 | elif score + points > TARGET_SCORE: 37 | throws = 3 38 | score = prev_round_score 39 | else: 40 | score += points 41 | 42 | if throws == 3: 43 | throws = 0 44 | rounds += 1 45 | misses = 0 46 | prev_shot = '' 47 | prev_round_score = score 48 | else: 49 | prev_shot = shot 50 | 51 | return -1 52 | 53 | 54 | def solution(): 55 | num_players = int(input()) 56 | player_names = [input() for _ in range(num_players)] 57 | shortest_rounds = float('inf') 58 | winner = '' 59 | 60 | for i in range(num_players): 61 | shoots = input() 62 | rounds = simulate(shoots) 63 | if rounds != -1 and rounds < shortest_rounds: 64 | shortest_rounds = rounds 65 | winner = player_names[i] 66 | 67 | print(winner) 68 | 69 | solution() 70 | -------------------------------------------------------------------------------- /Python/nature-of-quadrilateral.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/nature-of-quadrilaterals 2 | 3 | 4 | import math 5 | 6 | 7 | def get_length(x1, y1, x2, y2): 8 | return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) 9 | 10 | 11 | def get_angle(x1, y1, x2, y2, x3, y3): 12 | ang = math.degrees(math.atan2(y3 - y2, x3 - x2) - math.atan2(y1 - y2, x1 - x2)) 13 | return ang + 360 if ang < 0 else ang 14 | 15 | 16 | def print_answer(a, b, c, d, shape): 17 | print('{}{}{}{} is a {}.'.format(a, b, c, d, shape)) 18 | 19 | 20 | def get_lengths(ax, ay, bx, by, cx, cy, dx, dy): 21 | return [get_length(ax, ay, bx, by), 22 | get_length(bx, by, cx, cy), 23 | get_length(cx, cy, dx, dy), 24 | get_length(dx, dy, ax, ay)] 25 | 26 | 27 | def get_angles(ax, ay, bx, by, cx, cy, dx, dy): 28 | return [get_angle(ax, ay, bx, by, cx, cy), 29 | get_angle(bx, by, cx, cy, dx, dy), 30 | get_angle(cx, cy, dx, dy, ax, ay), 31 | get_angle(dx, dy, ax, ay, bx, by)] 32 | 33 | 34 | def solution(): 35 | num_quads = int(input()) 36 | for _ in range(num_quads): 37 | text = input().split() 38 | a, b, c, d = text[0], text[3], text[6], text[9] 39 | ax, ay = map(int, text[1:3]) 40 | bx, by = map(int, text[4:6]) 41 | cx, cy = map(int, text[7:9]) 42 | dx, dy = map(int, text[10:12]) 43 | 44 | lengths = get_lengths(ax, ay, bx, by, cx, cy, dx, dy) 45 | angles = get_angles(ax, ay, bx, by, cx, cy, dx, dy) 46 | 47 | if len(set(angles)) == 1: 48 | if len(set(lengths)) == 1: 49 | print_answer(a, b, c, d, 'square') 50 | else: 51 | print_answer(a, b, c, d, 'rectangle') 52 | elif len(set(lengths)) == 1: 53 | print_answer(a, b, c, d, 'rhombus') 54 | elif lengths[0] == lengths[2] and lengths[1] == lengths[3]: 55 | print_answer(a, b, c, d, 'parallelogram') 56 | else: 57 | print_answer(a, b, c, d, 'quadrilateral') 58 | 59 | 60 | solution() 61 | -------------------------------------------------------------------------------- /Python/detective-pikaptcha-ep2.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/detective-pikaptcha-ep2 2 | 3 | 4 | def get_next_passage(row, col, directions, grid): 5 | direction_pos_offsets = {'>': (0, 1), 'v': (1, 0), '<': (0, -1), '^': (-1, 0)} 6 | for direction in directions: 7 | dpo = direction_pos_offsets[direction] 8 | if is_passage(row + dpo[0], col + dpo[1], grid): 9 | return (row + dpo[0], col + dpo[1]), direction 10 | return (-1, -1), '' 11 | 12 | 13 | def get_next_pos(row, col, direction, side, grid): 14 | if direction == '^': 15 | if side == 'L': return get_next_passage(row, col, '<^>v', grid) 16 | else: return get_next_passage(row, col, '>^': 18 | if side == 'L': return get_next_passage(row, col, '^>v<', grid) 19 | else: return get_next_passage(row, col, 'v>^<', grid) 20 | elif direction == 'v': 21 | if side == 'L': return get_next_passage(row, col, '>v<^', grid) 22 | else: return get_next_passage(row, col, '^', grid) 23 | else: 24 | if side == 'L': return get_next_passage(row, col, 'v<^>', grid) 25 | else: return get_next_passage(row, col, '^', grid) 26 | 27 | 28 | def is_passage(row, col, grid): 29 | if row < 0 or row > len(grid) - 1: return False 30 | if col < 0 or col > len(grid[row]) - 1: return False 31 | return grid[row][col] != '#' 32 | 33 | 34 | def solution(): 35 | width, height = map(int, input().split()) 36 | grid = [list(input()) for _ in range(height)] 37 | side = input() 38 | 39 | opos = pos = [(r, c) for r in range(height) for c in range(width) if grid[r][c] in '>v<^'][0] 40 | direction = grid[pos[0]][pos[1]] 41 | grid[pos[0]][pos[1]] = 0 42 | left_original_pos = False 43 | 44 | while pos != opos or not left_original_pos: 45 | left_original_pos = True 46 | pos, direction = get_next_pos(pos[0], pos[1], direction, side, grid) 47 | if pos == (-1, -1): break 48 | grid[pos[0]][pos[1]] = int(grid[pos[0]][pos[1]]) + 1 49 | 50 | for row in grid: 51 | print(''.join(map(str, row))) 52 | 53 | 54 | solution() 55 | -------------------------------------------------------------------------------- /Python/rooks-movements.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/rooks-movements 2 | 3 | 4 | BOARD_SIZE = 8 5 | BOARD_TRANS = {-1: '-', 1: 'x'} 6 | 7 | 8 | def pos_trans(a): 9 | return ord(a[0]) - ord('a'), int(a[1]) - 1 10 | 11 | 12 | def pos_trans_rev(a): 13 | return chr(a[0] + ord('a')), str(a[1] + 1) 14 | 15 | 16 | def check_horizontal(board, ipos, ix, y): 17 | moves = [] 18 | for x in range(ix - 1, -1, -1): 19 | px, py = pos_trans_rev((x, y)) 20 | m = board[y][x] 21 | if m == 0: 22 | break 23 | else: 24 | moves.append('R{}{}{}{}'.format(ipos, BOARD_TRANS[m], px, py)) 25 | if m == 1: break 26 | 27 | for x in range(ix + 1, BOARD_SIZE): 28 | px, py = pos_trans_rev((x, y)) 29 | m = board[y][x] 30 | if m == 0: 31 | break 32 | else: 33 | moves.append('R{}{}{}{}'.format(ipos, BOARD_TRANS[m], px, py)) 34 | if m == 1: break 35 | 36 | return moves 37 | 38 | 39 | def check_vertical(board, ipos, x, iy): 40 | moves = [] 41 | for y in range(iy - 1, -1, -1): 42 | px, py = pos_trans_rev((x, y)) 43 | m = board[y][x] 44 | if m == 0: 45 | break 46 | else: 47 | moves.append('R{}{}{}{}'.format(ipos, BOARD_TRANS[m], px, py)) 48 | if m == 1: break 49 | 50 | for y in range(iy + 1, BOARD_SIZE): 51 | px, py = pos_trans_rev((x, y)) 52 | m = board[y][x] 53 | if m == 0: 54 | break 55 | else: 56 | moves.append('R{}{}{}{}'.format(ipos, BOARD_TRANS[m], px, py)) 57 | if m == 1: break 58 | 59 | return moves 60 | 61 | 62 | def solution(): 63 | ipos = input() 64 | ix, iy = pos_trans(ipos) 65 | num_pieces = int(input()) 66 | 67 | board = [[-1] * BOARD_SIZE for _ in range(8)] 68 | for _ in range(num_pieces): 69 | color, position = input().split() 70 | px, py = pos_trans(position) 71 | board[py][px] = int(color) 72 | 73 | moves = [] 74 | moves.extend(check_horizontal(board, ipos, ix, iy)) 75 | moves.extend(check_vertical(board, ipos, ix, iy)) 76 | 77 | for move in sorted(moves): 78 | print(move) 79 | 80 | 81 | solution() 82 | -------------------------------------------------------------------------------- /Python/1d-spreadsheet.py: -------------------------------------------------------------------------------- 1 | # https://www.codingame.com/training/easy/1d-spreadsheet 2 | 3 | 4 | def add_dependency(cell, arg_cell, in_deps, out_deps): 5 | if cell not in out_deps: out_deps[cell] = set() 6 | out_deps[cell].add(arg_cell) 7 | 8 | if arg_cell not in in_deps: in_deps[arg_cell] = set() 9 | in_deps[arg_cell].add(cell) 10 | 11 | 12 | def remove_dependency(cell, in_deps, out_deps): 13 | rc = [] 14 | if cell not in in_deps: return rc 15 | for o in in_deps[cell]: 16 | if cell in out_deps[o]: 17 | out_deps[o].remove(cell) 18 | 19 | if not out_deps[o]: 20 | rc.append(o) 21 | 22 | return rc 23 | 24 | 25 | def evaluate_dependencies(cells, in_deps, out_deps, cell_operations): 26 | ready_cells = set() 27 | evaluated_cells = set() 28 | 29 | for cell in out_deps: 30 | if not out_deps[cell]: 31 | ready_cells.add(cell) 32 | 33 | while ready_cells: 34 | cell = ready_cells.pop() 35 | evaluated_cells.add(cell) 36 | perform_operation(cell=cell, **cell_operations[cell], cells=cells) 37 | rc = remove_dependency(cell, in_deps, out_deps) 38 | 39 | ready_cells.update([o for o in rc if o not in evaluated_cells]) 40 | 41 | for cell in cells: 42 | print(cell) 43 | 44 | 45 | def get_arg_val(arg, cells): 46 | if '$' in arg: 47 | return cells[int(arg[1:])] 48 | elif '_' in arg: 49 | return 0 50 | else: 51 | return int(arg) 52 | 53 | 54 | def perform_operation(cell, operation, arg1, arg2, cells): 55 | val1 = get_arg_val(arg1, cells) 56 | val2 = get_arg_val(arg2, cells) 57 | 58 | if operation == 'VALUE': 59 | cells[cell] = val1 60 | elif operation == 'ADD': 61 | cells[cell] = val1 + val2 62 | elif operation == 'SUB': 63 | cells[cell] = val1 - val2 64 | else: 65 | cells[cell] = val1 * val2 66 | 67 | 68 | def solution(): 69 | num_cells = int(input()) 70 | in_deps = {} 71 | out_deps = {} 72 | cells = [0] * num_cells 73 | cell_operations = [{} for _ in range(num_cells)] 74 | 75 | for cell in range(num_cells): 76 | operation, arg1, arg2 = input().split() 77 | cell_operations[cell] = { 78 | 'operation': operation, 79 | 'arg1': arg1, 80 | 'arg2': arg2 81 | } 82 | 83 | if cell not in out_deps: out_deps[cell] = set() 84 | if '$' in arg1: add_dependency(cell, int(arg1[1:]), in_deps, out_deps) 85 | if '$' in arg2: add_dependency(cell, int(arg2[1:]), in_deps, out_deps) 86 | 87 | evaluate_dependencies(cells, in_deps, out_deps, cell_operations) 88 | 89 | 90 | solution() 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [CodinGame](https://www.codingame.com/) 2 | 3 | ![Github](https://img.shields.io/badge/languages-python-green.svg?longCache=true&style=for-the-badge) 4 | ![GitHub](https://img.shields.io/github/license/mashape/apistatus.svg?style=for-the-badge) 5 | 6 | ## [Training](https://www.codingame.com/training/) 7 | 8 | | Problem | Difficulty | Category | Solution | 9 | |---------|------------|----------|----------| 10 | [1×1×1 Rubik's Cube Movements](https://www.codingame.com/training/easy/111-rubiks-cube-movements) | Easy | | [Python](./Python/111-rubiks-cube-movements.py) 11 | [1D Spreadsheet](https://www.codingame.com/training/easy/1d-spreadsheet) | Easy | Lazy Evaluation, Dependency Graph | [Python](./Python/1d-spreadsheet.py) 12 | [Add'em Up](https://www.codingame.com/training/easy/addem-up) | Easy | Greedy Algorithms, Sorting | [Python](./Python/addem-up.py) 13 | [Are The Clumps Normal](https://www.codingame.com/training/easy/are-the-clumps-normal) | Easy | Number Theory | [Python](Python/are-the-clumps-normal.py) 14 | [ASCII Art](https://www.codingame.com/training/easy/ascii-art) | Easy | Loops, Arrays, Strings | [Python](./Python/ascii-art.py) 15 | [Balanced Ternary Computer Encode](https://www.codingame.com/training/easy/balanced-ternary-computer-encode) | Easy | | [Python](./Python/balanced-ternary-computer-encode.py) 16 | [Bank Robbers](https://www.codingame.com/training/easy/bank-robbers) | Easy | Loops, Mathematics | [Python](./Python/bank-robbers.py) 17 | [Blowing Fuse](https://www.codingame.com/training/easy/blowing-fuse) | Easy | Conditions | [Python](./Python/blowing-fuse.py) 18 | [Brackets Extreme Edition](https://www.codingame.com/training/easy/brackets-extreme-edition) | Easy | | [Python](./Python/brackets-extreme-edition.py) 19 | [Brick in the Wall](https://www.codingame.com/training/easy/brick-in-the-wall) | Easy | Greedy Algorithms, Mathematics | [Python](./Python/brick-in-the-wall.py) 20 | [Bulk Email Generator](https://www.codingame.com/training/easy/bulk-email-generator) | Easy | | [Python](./Python/bulk-email-generator.py) 21 | [Chuck Norris](https://www.codingame.com/training/easy/chuck-norris) | Easy | Conditions, Loops, Strings, Encoding | [Python](./Python/chuck-norris.py) 22 | [Count as I Count](https://www.codingame.com/training/easy/count-as-i-count) | Easy | Combinatorics | [Python](./Python/count-as-i-count.py) 23 | [Credit Card Verifier (Luhn's Algorithm)](https://www.codingame.com/training/easy/credit-card-verifier-luhns-algorithm) | Easy | | [Python](./Python/credit-card-verifier-luhns-algorithm.py) 24 | [Darts](https://www.codingame.com/training/easy/darts) | Easy | Geometry, Collision Detection | [Python](./Python/darts.py) 25 | [Defibrillators](https://www.codingame.com/training/easy/defibrillators) | Easy | Loops, Distances, Trigonometry | [Python](./Python/defibrillators.py) 26 | [Encryption/Decryption of Enigma Machine](https://www.codingame.com/training/easy/encryptiondecryption-of-enigma-machine) | Easy | Encoding, Strings, Cryptography, String Manipulation | [Python](./Python/encryptiondecryption-of-enigma-machine.py) 27 | [Ghost Legs](https://www.codingame.com/training/easy/ghost-legs) | Easy | Ascii Art, Loops, Conditions | [Python](./Python/ghost-legs.py) 28 | [Guessing N Cheating](https://www.codingame.com/training/easy/guessing-n-cheating) | Easy | Conditions, Sets, Logic | [Python](./Python/guessing-n-cheating.py) 29 | [Hooch Clash](https://www.codingame.com/training/easy/hooch-clash) | Brute-Force, Number Theory, Hooch, Diophantine Equation, Reading Comprehension | [Python](./Python/hooch-clash.py) 30 | [Horse-Racing Duals](https://www.codingame.com/training/easy/horse-racing-duals) | Easy | Loops | [Python](./Python/horse-racing-duals.py) 31 | [Horse-Racing Hyperduals](https://www.codingame.com/training/easy/horse-racing-hyperduals) | Easy | Loops | [Python](./Python/horse-racing-hyperduals.py) 32 | [How Time Flies](https://www.codingame.com/training/easy/how-time-flies) | Easy | | [Python](./Python/how-time-flies.py) 33 | [ISBN Check Digit](https://www.codingame.com/training/easy/isbn-check-digit) | Easy | Arithmetics, Check-Digit | [Python](./Python/isbn-check-digit.py) 34 | [Jack Silver: The Casino](https://www.codingame.com/training/easy/jack-silver-the-casino) | Easy | | [Python](./Python/jack-silver-the-casino.py) 35 | [Lumen](https://www.codingame.com/training/easy/lumen) | Easy | Loops, 2D Array | [Python](./Python/lumen.py) 36 | [Mars Lander - Episode 1](https://www.codingame.com/training/easy/mars-lander-episode-1) | Easy | Conditions | [Python](./Python/conditions.py) 37 | [May the Triforce Be With You](https://www.codingame.com/training/easy/may-the-triforce-be-with-you) | Easy | Loops, ASCII Art | [Python](./Python/may-the-triforce-be-with-you.py) 38 | [Mime Type](https://www.codingame.com/training/easy/mime-type) | Easy | Conditions, Loops, Hash Tables, Strings | [Python](./Python/mime-type.py) 39 | [Morellet's Random Lines](https://www.codingame.com/training/easy/morellets-random-lines) | Easy | Conditions, Mathematics, Geometry | [Python](./Python/morellets-random-lines.py) 40 | [Nature of Quadrilateral](https://www.codingame.com/training/easy/nature-of-quadrilaterals) | Easy | Strings, Trigonometry, Mathematics, Geometry | [Python](./Python/nature-of-quadrilateral.py) 41 | [Onboarding](https://www.codingame.com/training/easy/onboarding) | Easy | Conditions | [Python](./Python/onboarding.py) 42 | [Order of Succession](https://www.codingame.com/training/easy/order-of-succession) | Easy | Graphs, Path Finding, Depth First Search | [Python](./Python/order-of-succession.py) 43 | [Organic Compounds](https://www.codingame.com/training/easy/organic-compounds) | Easy | String Manipulation | [Python](./Python/organic-compounds.py) 44 | [Pirate's Treasure](https://www.codingame.com/training/easy/pirates-treasure) | Easy | Conditions, Loops, Arrays | [Python](./Python/pirates-treasure.py) 45 | [Plague, Jr](https://www.codingame.com/training/easy/plague-jr) | Easy | Graph Theory, Trees | [Python](./Python/plague-jr.py) 46 | [Power of Thor - Episode 1](https://www.codingame.com/training/easy/power-of-thor-episode-1) | Easy | Conditions | [Python](./Python/power-of-thor-episode-1.py) 47 | [Rectangular Block Spinner](https://www.codingame.com/training/easy/rectangular-block-spinner) | Easy | | [Python](./Python/rectangular-block-spinner.py) 48 | [Rooks Movements](https://www.codingame.com/training/easy/rooks-movements) | Easy | Loops, Classic Board Games, Condition, Chess | [Python](./Python/rooks-movements.py) 49 | [Rugby Score](https://www.codingame.com/training/easy/rugby-score) | Easy | | [Python](./Python/rugby-score.py) 50 | [Self-Driving Car Testing](https://www.codingame.com/training/easy/self-driving-car-testing) | Easy | | [Python](./Python/self-driving-car-testing.py) 51 | [Simple Awalé](https://www.codingame.com/training/easy/simple-awale) | Easy | | [Python](./Python/simple-awale.py) 52 | [Smooth!](https://www.codingame.com/training/easy/smooth) | Easy | Brute-Force, Number Theory, Reading Comprehension, Smooth, Fruit | [Python](./Python/smooth.py) 53 | [Stall Tilt](https://www.codingame.com/training/easy/stall-tilt) | Easy | Physics | [Python](./Python/stall-tilt.py) 54 | [Temperatures](https://www.codingame.com/training/easy/temperatures) | Easy | Conditions, Loops, Arrays | [Python](./Python/temperatures.py) 55 | [Text Formatting](https://www.codingame.com/training/easy/text-formatting) | Easy | | [Python](./Python/text-formatting.py) 56 | [The Dart 101](https://www.codingame.com/training/easy/the-dart-101) | Easy | Conditions | [Python](./Python/the-dart-101.py) 57 | [The Descent](https://www.codingame.com/training/easy/the-descent) | Easy | Loops | [Python](./Python/the-descent.py) 58 | [The Frog Jump I](https://www.codingame.com/training/easy/the-frog-jump-1) | Easy | Physics | [Python](./Python/the-frog-jump.py) 59 | [The River I.](https://www.codingame.com/training/easy/the-river-i-) | Easy | | [Python](./Python/the-river-i-.py) 60 | [The River II.](https://www.codingame.com/training/easy/the-river-ii-) | Easy | | [Python](./Python/the-river-ii-.py) 61 | [The Traveling Salesman Problem](https://www.codingame.com/training/easy/the-travelling-salesman-problem) | Easy | | [Python](./Python/the-traveling-salesman-problem.py) 62 | [There is no Spoon - Episode 1](https://www.codingame.com/training/medium/there-is-no-spoon-episode-1) | Medium | Lists | [Python](./Python/there-is-no-spoon-episode-1.py) 63 | [What's so complex about Mandelbrot?](https://www.codingame.com/training/easy/whats-so-complex-about-mandelbrot) | Easy | | [Python](./Python/whats-so-complex-about-mandelbrot.py) 64 | [XML MDF-2016](https://www.codingame.com/training/easy/xml-mdf-2016) | Easy | | [Python](./Python/xml-mdf-2016.py) 65 | --------------------------------------------------------------------------------