view hard.cc @ 24:b89680a8af68 default tip

graph: detect negative cycles
author Lewin Bormann <lbo@spheniscida.de>
date Sun, 09 Apr 2023 17:27:20 +0200
parents 85a51415f042
children
line wrap: on
line source

#include <iostream>
#include <list>
#include <vector>
#include <random>
#include <ranges>

unsigned add_two_numbers(unsigned a, unsigned b) {
    unsigned i = 0, j = 0;
    unsigned out = 0;
    unsigned carry = 0;
    unsigned mask = 1;
    while (a | b | carry) {
        i = a & 1;
        j = b & 1;
        a >>= 1;
        b >>= 1;
        if (((i^j)^carry) | (i&j&carry)) {
            out |= mask;
            carry = 0;
        }
        if ((j&carry)|(i&carry)|(i&j)) {
            carry = 1;
        }
        mask <<= 1;
    }
    return out;
}

std::vector<int> shuffle_cards(int n=52) {
    auto range = std::ranges::iota_view(1, 52+1);
    std::list<int> deck(range.begin(), range.end());

    std::vector<int> shuffled;
    std::random_device rd;
    std::mt19937 gen(rd());
    for (int i = n; i > 0; i--) {
        std::uniform_int_distribution<> dist(0, i-1);
        int ix = dist(gen);
        auto it = deck.begin();
        for (int j = 0; j < ix; j++)
            it++;
        shuffled.push_back(*it);
        deck.erase(it);
    }

    return shuffled;
}

int pow10(int n) {
    int p = 1;
    for (int i = 0; i < n; i++)
        p *= 10;
    return p;
}

// 18.4
int twos(int n) {
    int count = 0;
    for (int digit = 0; digit < 9; digit++) {
        int d = (n/pow10(digit)) % 10;
        if (d < 2) {
            // Round down.
            int rd = pow10(digit+1) * (n/pow10(digit+1));
            count += rd/10;
        } else if (d == 2) {
            int rd = pow10(digit+1) * (n/pow10(digit+1));
            count += rd/10;
            int rem = n % pow10(digit);
            count += rem + 1;
        } else if (d > 2) {
            // Round up.
            int ru = pow10(digit+1) * (n/pow10(digit+1) + 1);
            count += ru/10;
        }
    }
    return count;
}

int main(void) {
    std::cout << twos(219) << "\n";
    return 0;
}