Esempio n. 1
0
def second_part(instructions):
    earliest_timestamp, bus_ids = instructions
    all_bus_cycles = {
        int(bus): -i % int(bus)
        for i, bus in enumerate(bus_ids) if bus != "x"
    }
    # un bus a une vitesse (son numéro) et une vitesse de cycle son numéro -i (le temps de départ)... mais comme on veux un cycle c'est un modulo : -i%int(bus)
    sorted_bus_by_relative_speed = list(reversed(sorted(all_bus_cycles)))
    print(sorted_bus_by_relative_speed)
    bus_synchro_cycle = all_bus_cycles[sorted_bus_by_relative_speed[
        0]]  # optim on choisi le bus au cycle le plus rapide
    lcm = math.lcm(sorted_bus_by_relative_speed[0])
    for bus_index, bus_cycle in enumerate(sorted_bus_by_relative_speed[1:]):
        while (
                bus_synchro_cycle % bus_cycle != all_bus_cycles[bus_cycle]
        ):  # on s'attend a ce que le temps de sychro / cycle du bus/superbus courrant soit égale au temps de syncro du bus vis à vis de l'ensemble des bus
            bus_synchro_cycle += lcm  # on bouge a la vitesse la plus "rapide" de l'ensemble des bus (superbus) déjà traité , hormis celui à sychroniser
        # at the end of this loop n bus are in sync at bus_synchro_cycle according to their cycle
        # for loop 1 :
        # bus_synchro_cycle % bus_1_relative_speed == bus_1_cycle
        # bus_synchro_cycle % bus_2_relavive_speed == bus_2_cycle
        # so each bus is at the start point at bus_synchro_cycle
        # let's move faster using the lcm! PPCM en francais didious!
        lcm = math.lcm(
            lcm, bus_cycle
        )  # on recalcul la vitesse la plus "rapide" de l'ensemble des bus avec le bus courrant pour le suivant

    print(bus_synchro_cycle)
Esempio n. 2
0
def find_smallest_sequence_departures(departures: dict):

    previous = None
    offset = 0
    lcm_previous = None
    lcm_current = None
    departure_offset = None
    departure_offset_previous = 0

    for current in departures:
        if not previous:
            previous = current
        elif current == 'x':
            pass
        elif not lcm_current:
            lcm_current = math.lcm(previous, current)
            departure_offset = arrow_alignment(previous, current, -offset)
            previous = current
        else:
            lcm_previous = lcm_current
            departure_offset_previous += departure_offset
            lcm_current = math.lcm(lcm_current, current)
            departure_offset = arrow_alignment(
                lcm_previous, current, -departure_offset_previous - offset)
            previous = current

        offset += 1

    print(
        f"The definite answer is here: {departure_offset + departure_offset_previous}\n\n\n"
    )
Esempio n. 3
0
def lcm(*integers):
    '''Return least common multiple of a and b'''
    try:
        _math.lcm(*integers)
    except Exception:
        pass
    return _reduce(_lcm1, integers)
Esempio n. 4
0
def part2() -> int:
    # It assumes that the first step will be the one to repeat.
    # It's a heuristic, but works for this problem.
    x_cords = [(moon.position[0], 0) for moon in moons_list]
    y_cords = [(moon.position[1], 0) for moon in moons_list]
    z_cords = [(moon.position[2], 0) for moon in moons_list]

    return lcm(get_repeat_steps(x_cords),
               lcm(get_repeat_steps(y_cords), get_repeat_steps(z_cords)))
Esempio n. 5
0
    def part2(self):
        lcms = []
        for axis in reversed(range(3)):
            moons = self.get_moons2(axis)

            while not all([moon.stabilised for moon in moons]):
                for moon, other_moon in itertools.permutations(moons, 2):
                    moon.add_velocity(other_moon)

                for moon in moons:
                    moon.apply_velocity()

            lcms.append(lcm(*[moon.steps for moon in moons]))

        return lcm(*lcms)
def get_change(m): #m==money
    #write your code here
    LCM = lcm(1,3,4) #LCM of denominations available
    ''' Safe whole number and it's least coins is with biggest denomination'''
    safeCoins = (m//LCM)*3
    print(f'safeCoins {safeCoins} of [Rs.4]')
    remaining = m%LCM #remaining < LCM
    print('FillingCoins')
    coins = [0,0]
    for i in [0,1]:
        r = remaining
        if i==0:
            add4 = r//4
            rem = r%4
            add3 = rem//3 if rem%3==0 else 0
            add1 = rem%3
            coins[i] = add4+add3+add1
            print(f'<1> {add4}[Rs.4] + {add3}[Rs.3] + {add1}[Rs.1] = {coins[i]} Coins')
        else:
            add3 = r//3
            add1 = r%3
            add4 = 0
            while add1>0 and add3>0:
                for j in range(1,add1+1):
                    add4 = add4 + 1
                    add3 = add3 - 1
                    add1 = add1 - 1
            coins[i] = add4 + add3 + add1
            print(f'<2> {add4}[Rs.4] + {add3}[Rs.3] + {add1}[Rs.1] = {coins[i]} Coins')
    print('Best Choice is Minimum of',coins)
    return safeCoins + min(coins)
Esempio n. 7
0
    def get_period(self):
        """
        Return a number P such that G(x*exp(I*P)) == G(x).

        >>> meijerg([1], [], [], [], z).get_period()
        2*pi
        >>> meijerg([pi], [], [], [], z).get_period()
        oo
        >>> meijerg([1, 2], [], [], [], z).get_period()
        oo
        >>> meijerg([1, 1], [2], [1, Rational(1, 2), Rational(1, 3)], [1], z).get_period()
        12*pi

        """
        # This follows from slater's theorem.
        def compute(l):
            # first check that no two differ by an integer
            for i, b in enumerate(l):
                if not b.is_Rational:
                    return oo
                for j in range(i + 1, len(l)):
                    if not Mod((b - l[j]).simplify(), 1):
                        return oo
            return functools.reduce(math.lcm, (x.denominator for x in l), 1)
        beta = compute(self.bm)
        alpha = compute(self.an)
        p, q = len(self.ap), len(self.bq)
        if p == q:
            if oo in (beta, alpha):
                return oo
            return 2*pi*math.lcm(alpha, beta)
        elif p < q:
            return 2*pi*beta
        else:
            return 2*pi*alpha
Esempio n. 8
0
def func():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))

    # a -> a'
    for av in a:
        if av % 2 == 1:
            print(0)
            return
        av /= 2

    # a -> a''
    t = f(a[0])
    for av in a:
        if f(av) != t:
            print(0)
            return
        av >>= t  # 2でT回割る   av /= 2^t
    m >>= t

    l = 1
    for av in a:
        l = math.lcm(l, av)
        if l > m:
            print(0)
            return

    m /= l
    ans = (m + 1) / 2
    print(ans)
    return
Esempio n. 9
0
def part1(moons, velos):
    og_moons = [[x for x in row] for row in moons]
    og_velos = [[x for x in row] for row in velos]
    dones = [0,0,0]
    print(moons, og_moons)
    iterations = 3000
    ret = 1
    while 0 in dones:
        for index, m in enumerate(moons):
            for m2 in moons:
                for i in range(3):
                    if m[i] < m2[i]:
                        velos[index][i] += 1
                    elif m[i] > m2[i]:
                        velos[index][i] -= 1
        for i, m in enumerate(moons):
            for j in range(3):
                m[j] += velos[i][j]
        for axis in range(3):
            if dones[axis] != 0: continue
            if compare_og(axis, moons, og_moons) and sum([velos[k][axis] for k in range(3)]) == 0:
                print(dones)
                dones[axis] = ret

        if ret % 100000 == 0:
            print("GOLYY")
        ret += 1 
    print("Res: ",dones)
    print(math.lcm(dones))
    return "this is part one"
Esempio n. 10
0
def find_earliest_timestamp(bus_ids):
    # List buses and their time delta from the first bus
    buses = [(int(bus), delta) for delta, bus in enumerate(bus_ids)
             if bus != 'x']

    i = 1
    max_matches = 1
    bus, delta = max(buses, key=lambda x: x[
        0])  # Start with the largest bus value - can't be any smaller
    t = bus - delta  # Set initial time to first time the very first bus arrives
    increment_size = bus  # Start increments at the largest bus value
    while True:
        t += increment_size
        matches = set(
        )  # Keep track of how many valid matches we have this run
        for bus, delta in buses:
            if int(t + delta) % bus != 0:
                # Not a valid match, jump ahead and try the next time
                i += increment_size
                break
            else:
                matches.add(bus)
                if len(matches) > max_matches:
                    max_matches = len(matches)
                    # We have found the next closest matching interval, set increment size to this interval
                    increment_size = lcm(*matches)
        else:
            # Matched all buses
            return t
Esempio n. 11
0
def part02(lines, verbose=False):
    bus_ids = lines[1].split(',')
    offsets = [(int(bus_ids[0]), 0)]
    for i, x in enumerate(bus_ids[1:]):
        if x == 'x':
            continue
        else:
            offsets.append((int(x), (i + 1) % int(x)))
    offsets = [offsets[0]] + sorted(offsets[1:], key=lambda x: -x[0])
    step_width = offsets[0][0]
    start_pos = 0
    for i in range(1, len(offsets)):
        if verbose:
            print(f'outer iteration {i}: step_width', step_width,
                  ', start pos', start_pos)
        pos = start_pos
        bus, offset = offsets[i]
        while True:
            if get_next_arrival(pos, bus) == offset + pos:
                step_width = lcm(step_width, offsets[i][0])
                start_pos = pos
                break
            else:
                pos += step_width
    print('part 02:', pos)
Esempio n. 12
0
def get_time_and_multiplier(acc, new_bus_info):
    multiplier, time = acc
    bus, offset = new_bus_info
    while (time + offset) % bus:
        time += multiplier
    multiplier = math.lcm(multiplier, bus)
    return multiplier, time
Esempio n. 13
0
def combine(a, b):
    for n in count():
        t = (a.mult * n) - a.offset

        if (t - b.offset) % b.mult == 0:
            mult = lcm(a.mult, b.mult)
            off = mult - t
            return route(mult, off)
Esempio n. 14
0
def find_common_denom_start(num, num_new, offset):
    x = 1
    while True:
        if 0 == ((x * num) + offset) % num_new:
            first_occ = (x * num) + offset
            common_denom = math.lcm(num, num_new)
            return common_denom, first_occ
        x += 1
Esempio n. 15
0
 def execute(self, table, tree):
     super().execute(table, tree)
     exp1 = self.exp1.execute(table, tree)
     exp2 = self.exp2.execute(table, tree)
     try:
         return math.lcm(exp1, exp2)
     except :
         raise(Error(self.line, self.column, ErrorType.SEMANTIC, 'TypeError: Both arguments must be a integral number'))
Esempio n. 16
0
def part2():
    moons = list(values)
    prev_x_states = set()
    prev_y_states = set()
    prev_z_states = set()

    x_period = None
    y_period = None
    z_period = None

    while None in [x_period, y_period, z_period]:

        def check_axis(period, index, prev_states):
            if period is not None:
                return period

            current_state = ''.join(
                [f'{moon[0][index]}{moon[1][index]}' for moon in moons])

            if current_state in prev_states:
                return len(prev_states)
            else:
                prev_states.add(current_state)

        x_period = check_axis(x_period, 0, prev_x_states)
        y_period = check_axis(y_period, 1, prev_y_states)
        z_period = check_axis(z_period, 2, prev_z_states)

        new_moons = []
        for moon in moons:
            x, y, z = moon[0]
            xv, yv, zv = moon[1]

            inner_moons = list(moons)
            inner_moons.remove(moon)
            for inner_moon in inner_moons:
                if x < inner_moon[0][0]:
                    xv += 1
                elif x > inner_moon[0][0]:
                    xv -= 1
                if y < inner_moon[0][1]:
                    yv += 1
                elif y > inner_moon[0][1]:
                    yv -= 1
                if z < inner_moon[0][2]:
                    zv += 1
                elif z > inner_moon[0][2]:
                    zv -= 1

            x += xv
            y += yv
            z += zv

            new_moons.append(((x, y, z), (xv, yv, zv)))

        moons = new_moons

    return lcm(x_period, y_period, z_period)
Esempio n. 17
0
def get_lcm_prob_denominators(probs: Iterable[float]):
    """
    Helper function to compute the LCM of the denominators of the probabilities
    """
    prob_denominators = [
        Fraction(prob).limit_denominator().denominator for prob in probs
    ]
    lcm_prob_denominators = lcm(*prob_denominators)
    return lcm_prob_denominators
Esempio n. 18
0
 def __sub__(self, other):
     the_lcm = math.lcm(self.denominator, other.denominator)
     self_denominator_lcm = the_lcm // self.denominator
     other_denominator_lcm = the_lcm // other.denominator
     return Fraction(
         ((self.num * self_denominator_lcm) -
          (other.num * other_denominator_lcm)),
         (the_lcm + the_lcm),
     )
Esempio n. 19
0
 def __add__(self, other):
     the_lcm = math.lcm(self.denominator, other.denominator)
     self_denominator_lcm = the_lcm // self.denominator
     other_denominator_lcm = the_lcm // other.denominator
     return Fraction(
         numerator=((self.num * self_denominator_lcm) +
                    (other.num * other_denominator_lcm)),
         denominator=(the_lcm + the_lcm),
     )
Esempio n. 20
0
def main():
    answer = 1
    for i in range(1, 21):
        # math.lcm is available in python3.9+
        answer = math.lcm(answer, i)
        # you can use this in python3.x
        # answer *= i // math.gcd(i, answer)

    return answer
Esempio n. 21
0
def alignmenter(inp):
    previous = None

    for xdx, x in enumerate(inp[1:]):
        if x is None:
            continue

        period = lcm(inp[0], x)
        offset = arrow_alignment(inp[0], x, -(xdx + 1))

        if previous:
            inner_offset = arrow_alignment(previous[1], period,
                                           offset - previous[0])
            previous = (previous[0] + inner_offset, lcm(previous[1], period))
        else:
            previous = (offset, period)

    return previous[0]
Esempio n. 22
0
def timestamp_matching_list(bus_ids, bus_positions):
    current_base = 1
    current_num = 0
    for i in range(len(bus_ids)):
        while current_num % bus_ids[i] != (bus_ids[i] -
                                           bus_positions[i]) % bus_ids[i]:
            current_num += current_base
        current_base = math.lcm(current_base, bus_ids[i])
    return current_num
Esempio n. 23
0
def crt(r1, q1, r2, q2):
    q3 = math.lcm(q1, q2)
    t, _, g = egcd(q1 + q2, q3)
    r3 = (r1 * q2 + r2 * q1) * t
    assert not r3 % g
    r3 = r3 // g % q3
    if (r3 < 0) != (q3 < 0):
        r3 += q3
    return r3, q3
Esempio n. 24
0
def solve(a, b):
    a, b = (b, a) if b[1] > a[1] else (a, b)
    rep_a, mod_a = a
    rep_b, mod_b = b
    k = (rep_a - rep_b) // gcd(mod_a, mod_b)
    x, y = euclide(mod_a, mod_b)
    solution = rep_a - k * mod_a * x
    mod_res = lcm(mod_a, mod_b)
    return (solution % mod_res, mod_res)
Esempio n. 25
0
def main():
    text = (Path(__file__).parent /
            "../../input/2019/input_12.txt").read_text()
    moons = parse_moons(text)
    # Part 1
    for _ in range(1000):
        step(moons, range(3))
    print("Part 1:", sum(m.energy for m in moons))
    tx, ty, tz = [find_period(parse_moons(text), dim) for dim in range(3)]
    print("Part 2:", math.lcm(tx, ty, tz))
Esempio n. 26
0
 def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
     high = n * max(a, b)
     low = min(a, b)
     lcmab = lcm(a, b)
     while (high >= low):
         mid = (high + low) // 2
         if mid // a + mid // b - mid // (lcmab) < n:
             low = mid + 1
         else:
             high = mid - 1
     return low % (1000000007)
Esempio n. 27
0
def calc_student_sections(courses: list[Course],
                          course_total_sections: dict[Course, int],
                          courses_info: pd.DataFrame,
                          course_options: pd.DataFrame) -> dict[Course, list[Student]]:
    year_sections = defaultdict(lambda: 1)
    option_sections = defaultdict(int)

    for course_code, total_sections in course_total_sections.items():
        try:
            student_year = courses_info.loc[course_code]['Year']
            year_sections[student_year] = lcm(year_sections[student_year], total_sections)
        except KeyError:
            option = course_options.loc[course_code]['Option']
            option_sections[option] += total_sections

    for option, total_sections in option_sections.items():
        student_year = courses_info.loc[option]['Year']
        year_sections[student_year] = lcm(year_sections[student_year], total_sections)

    section_cnt = defaultdict(lambda: 1)
    res: dict[Course, list[Student]] = {}
    for course_code, section in courses:
        course = Course(course_code, section)
        total_sections = course_total_sections[course_code]
        try:
            student_year = courses_info.loc[course_code]['Year']
            no_of_student_sections = year_sections[student_year] // total_sections
            res[course] = []
            for i in range(no_of_student_sections):
                res[course].append(Student(student_year, section_cnt[course_code]))
                section_cnt[course_code] += 1
        except KeyError:
            option = course_options.loc[course_code]['Option']
            student_year = courses_info.loc[option]['Year']
            no_of_student_sections = year_sections[student_year] // option_sections[option]
            res[course] = []
            for i in range(no_of_student_sections):
                res[course].append(Student(student_year, section_cnt[option]))
                section_cnt[option] += 1

    return res
Esempio n. 28
0
def findTimestamp(fileName):
    ids = readIDs(fileName)
    buses = list(zip(*ids))[0]
    candidate = ids[0][0] - ids[0][1]
    increment = ids[0][0]

    for bus, offset in ids[1:]:
        while -candidate % bus != offset % bus:
            oldOffset = -candidate % bus
            candidate += increment
            newOffset = -candidate % bus
        increment = math.lcm(increment, bus)
    return candidate
Esempio n. 29
0
def find_first(bus_id_list):
    _, step = bus_id_list.pop(0)
    ts = 0
    for offset, bus_id in bus_id_list:
        # now using lcm from https://github.com/alasdairnicol/advent-of-code-2020/blob/master/day13b.py
        # ts, step = find_step(ts, step, offset, bus_id)
        while (ts + offset) % bus_id:
            # print(f'{ts=} {offset=} {bus_id=} {step=}')
            ts += step

        step = lcm(step, bus_id)

    return ts
def key_composer(*keywords: str) -> str:
    keys = [convert_text_to_indices(keyword)
            for keyword in keywords]  # get each key as a list of indices
    key_lengths = [len(key) for key in keys]  # get the length of each key
    new_key_length = lcm(*key_lengths)  # calculate the length of the new key
    long_keys = [
        extend_keyword(keyword, new_key_length) for keyword in keywords
    ]  # make keys the same length
    new_key = long_keys[
        0]  # starting with the first key, encode the keys with each other
    for i in range(len(long_keys) - 1):
        new_key = vigenre_encoder(new_key, long_keys[i + 1])
    return new_key.lower()