R

@RealSaitama

Median of n sorted arrays

Python
6 months ago
from bisect import bisect_right def kth_element(arrs, k): low = min(arr[0] for arr in arrs if len(arr)) high = max(arr[-1] for arr in arrs if len(arr)) while low < high: mid = low + (high - low) // 2 cnt = 0 for arr in arrs:

Between rationals

Python
6 months ago
from math import ceil, floor def between(a, b, c, d): q = 1 while 1: u, v = floor(a * q / b) + 1, ceil(c * q / d) - 1 if u <= v: print(f"{a}/{b} < {v}/{q} < {c}/{d}") return (v, q) q += 1

Product of Fibonacci numbers

Python
6 months ago
# from collections import deque # fib = [2, 3] # while fib[-1] < 1e37: # fib.append(fib[-1] + fib[-2]) # def solve(n): # q = deque([[n, []]]) # ans = []

Round Robin with constraints

Python
6 months ago
n = 4 xs = list(range(1, n)) rot = lambda arr: arr[1:] + [arr[0]] dct = {i: [0, 0] for i in range(n)} rs = [] for _ in range(n - 1): r = [0] + xs[:] rs.append([[r[i], r[n - 1 - i]] for i in range(n // 2)])

Network flow

Python
6 months ago
import networkx as nx G = nx.DiGraph() G.add_node("a", demand=-5) G.add_node("d", demand=5) G.add_edge("a", "b", weight=3, capacity=4) G.add_edge("a", "c", weight=6, capacity=10) G.add_edge("b", "d", weight=1, capacity=9) G.add_edge("c", "d", weight=2, capacity=5) flowCost, flowDict = nx.network_simplex(G)

Parking Lot (Codewars)

NodeJS
6 months ago
const SIZE = 20; let free = [[0, SIZE]]; let hash = {}; function park(size, lic){ let ok = false for(let i = 0; i < free.length; i++){ let [start, end] = free[i]; if(end - start >= size){ // if(start + size > SIZE) return false if(start + size < end){

Subtract digits (ChatGPT)

Python
6 months ago
from typing import Dict, Tuple, List # Tunable parameters: ROOT_LEN = 5 # number of least-significant digits handled directly CELL_LEN = 3 # digits per "cell" above the root # helpers _pow10_cache: List[int] = [] def pow10(k: int) -> int: while len(_pow10_cache) <= k:

Partition

Python
6 months ago
from fractions import Fraction from collections import defaultdict, namedtuple _pt = namedtuple("_pt", "x y") cross = lambda a, b: a.x * b.y - a.y * b.x dot = lambda a, b: a.x * b.x + a.y .b.y orientation = lambda a, b, c: cross(b - a, c - a) def on_segment(self, seg): p, q = seg.p, seg.q

Horner

Python
6 months ago
pol, root = [2,1,-5,2], 1 def horner(pol, root): n = len(pol) row, ans = [' '], [] ans.append(pol[0]) for i in range(1, n): s = root * ans[i - 1] row.append(s) ans.append(s + pol[i])

Sliding Puzzle

Python
6 months ago
from collections import deque def from_hash(st): return [list(map(int, r.split(','))) for r in st.split(';')] def hash(board): return ';'.join(','.join(str(x) for x in r) for r in board) def show(board): return '\n'.join(' '.join(str(x).rjust(2, '0') for x in r) for r in board) + '\n\n'

MORSE

Python
7 months ago
import numpy as np from sklearn.cluster import KMeans from math import log from itertools import groupby bits = "0000000011011010011100000110000001111110100111110011111100000000000111011111111011111011111000000101100011111100000111110011101100000100000" import numpy as np from sklearn.cluster import KMeans

Newtons Sums

Python
7 months ago
a = [4,3,2,1] n = len(a) s = [a[1]] for k in range(1, 10): _s = 0 for i in range(1, k): _s += (a[i] if i < len(a) else 0) * s[k - i] * (1 if i % 2 else -1) _s += (1 if k %2 else -1) * (a[k] if k < len(a) else 0)

Logical Gates

Python
7 months ago
print('#' * 20) print("Premier défi") m1 = "\x58\x6C\x4D\x6C\x64\x6A\x60\x62\x6D" print("Message initial :", m1) def solve(c): b = [int(x) for x in reversed(f"{ord(c):08b}")] s = [b[0] ^ 1, b[0] ^ b[1] ^1, b[2], b[3] ^b[4], b[4], b[5], 1, 0] bi = ''.join(map(str, reversed(s))) return chr(int(bi, 2))

CYTHON

Python
7 months ago
p = """cpdef solve(int[] lst): cdef int n = len(lst) cdef int tot = 0 cdef int i, j, s, current_val # Use a fixed-size array for seen markers # This is faster but assumes values are within 0-9999 cdef int max_size = 10000 cdef bint[10000] seen cdef bint[:] seen_view = seen

Triangle

Python
7 months ago
def other(c1,c2): s=set() s.add('R') s.add('G') s.add('B') s.remove(c1) s.remove(c2) return list(s)[0] def triangle(row):

Set partitions

Python
8 months ago
xs = list('01234') from itertools import combinations def partition(collection): if len(collection) == 1: yield [ collection ] return first = collection[0] for smaller in partition(collection[1:]): # insert `first` in each of the subpartition's subsets

Delaunay Triangulation

Python
8 months ago
import math from typing import List class StandardLine(object): """ A line in a coordinate grid described in standard form (ax + by = c). """ def __init__(self, x_quantifier: float, y_quantifier: float, equates: float): """

Multiply by 2 and Add 1

NodeJS
8 months ago
let n = 13 let s = [...n.toString(2)].map(Number).reverse() function f(n){ if(n == 1) return "1" let m = Math.floor(n/2) return n%2 ? `(2*${f(m)}+1)`: `(2*${f(m)})` }

Hasse Diagram for the product order

Python
8 months ago
def cover_edges(cs): pts = sorted(cs, key=lambda p: p[0], reverse=True) # decreasing x # maintain processed points sorted by y as list of (y,x) tuples import bisect S = [] # sorted by (y, x) edges = [] for x, y in pts: # find first processed point with y' > y idx = bisect.bisect_right(S, (y, float('inf'))) min_x = float('inf')

Calculator: the game

NodeJS
8 months ago
function applyPortal(_x, p){ let sgn = _x >= 0 ? 1 : -1; let x = Math.abs(_x) let dx = [...x.toString()].map(Number); let m = dx.length; let [l, r] = p.map(e => m - Number(e)); if(l < 0 || r >= m) return x; let y = dx[l];