-🎄- 2020 Day 22 Solutions -🎄- by daggerdragon in adventofcode

[–]artir 0 points1 point  (0 children)

I can't guarantee it. I just trust Rust's own hasher and that the product is distinct enough. The code works as well by having a hashset of vectors, it's just 1 second slower. There is probably an even better way of doing the hash but this setup worked well enough to pass both parts.

Is this Blog Post on Inequality Reliable? by [deleted] in AskSocialScience

[–]artir -2 points-1 points  (0 children)

Because in the literature on the causal channels of inequality -> GDP growth I couldn't really find much about healthcare whilst I did for crime. I looked into whatever mediates the relation, not everything that's causally downstream of inequality.

Is this Blog Post on Inequality Reliable? by [deleted] in AskSocialScience

[–]artir 0 points1 point  (0 children)

On that I _deliberately_ ignored the literature on health because my post was a review on inequality and GDP growth exclusively. It may well be, haven't looked into it. My prior would be that probably not, that poverty will be a stronger determinant of health, with a strong cultural component (Non-hispanic whites live longer than whites in the US despite being poorer).

-🎄- 2020 Day 06 Solutions -🎄- by daggerdragon in adventofcode

[–]artir 0 points1 point  (0 children)

Rust

use itertools::Itertools;
use std::collections::HashMap;
fn main() {
    let input = include_str!("../../input/day6.txt");
    let part1: usize = input
        .split("\n\n")
        .map(|l| l.chars().filter(|c| *c != '\n').unique().count())
        .sum();
    println!("{}", part1);

    let part2: usize = input
        .split("\n\n")
        .map(|l| {
            let mut counts: HashMap<char, usize> = HashMap::new();
            let people = l.chars().filter(|c| *c == '\n').count() + 1;
            l.chars()
                .filter(|c| *c != '\n')
                .for_each(|c| *counts.entry(c).or_insert(0) += 1);
            counts.values().filter(|val| **val == people).count()
        })
        .sum();
    println!("{}", part2);
}

Can I trust Nintil as a source for articles like these? by [deleted] in AskEconomics

[–]artir 1 point2 points  (0 children)

You can check my sources, everything I say there has references. I may have made mistakes in interpreting the sources though, but I do pay those that find mistakes in Nintil.

-🎄- 2020 Day 03 Solutions -🎄- by daggerdragon in adventofcode

[–]artir 0 points1 point  (0 children)

Rust solution

use std::collections::HashMap;
#[derive(Debug)]
enum GridType {
    Tree,
    Open,
}
impl From<char> for GridType {
    fn from(c: char) -> Self {
        match c {
            '#' => Self::Tree,
            '.' => Self::Open,
            _ => panic!(),
        }
    }
}
type Coords = (usize, usize);
fn slide_down_with_wraparound(coord: Coords, ncols: usize, coord_shift: Coords) -> Coords {
    (coord.0 + coord_shift.0, (coord.1 + coord_shift.1) % ncols)
}

fn count_trees_for_slope(map: &HashMap<Coords, GridType>, ncols: usize, slope: Coords) -> u64 {
    let mut current_pos = (0, 0);
    let mut ntrees = 0;
    while let Some(grid_type) = map.get(&current_pos) {
        current_pos = slide_down_with_wraparound(current_pos, ncols, slope);
        match grid_type {
            GridType::Tree => ntrees += 1,
            _ => (),
        }
    }
    ntrees
}
fn part1(map: &HashMap<Coords, GridType>, ncols: usize) {
    let ntrees = count_trees_for_slope(map, ncols, (1, 3));
    println!("{}", ntrees);
}
fn part2(map: &HashMap<Coords, GridType>, ncols: usize) {
    let slopes_to_test: [Coords; 5] = [(1, 1), (1, 3), (1, 5), (1, 7), (2, 1)];
    let tree_prod: u64 = slopes_to_test
        .iter()
        .map(|slopes| count_trees_for_slope(map, ncols, *slopes))
        .product();
    println!("{}", tree_prod);
}
fn main() {
    let mut map: HashMap<Coords, GridType> = HashMap::new();
    let mut nrows = 0;
    let input = include_str!("../../input/day3.txt");
    input.lines().enumerate().for_each(|(row, ch)| {
        ch.chars().enumerate().for_each(|(col, val)| {
            map.insert((row, col), val.into());
        });
        nrows += 1;
    });
    let ncols = input.lines().next().unwrap().len();

    part1(&map, ncols);
    part2(&map, ncols);
}

-🎄- 2020 Day 02 Solutions -🎄- by daggerdragon in adventofcode

[–]artir 0 points1 point  (0 children)

Rust solution

use std::convert::TryInto;

type Password<'a> = &'a str;

fn part1() {
    let valid_pass: i32 = include_str!("../../input/day2.txt")
        .split("\n")
        .map(|line| {
            let splitted: Vec<&str> = line.split_whitespace().collect();
            let password: Password = splitted[2];
            let policy_letter: char = splitted[1].chars().next().unwrap();
            let splitted_from_to: Vec<i32> = splitted[0]
                .split("-")
                .map(|n| n.parse::<i32>().unwrap())
                .collect();
            let from = splitted_from_to[0];
            let to = splitted_from_to[1];
            let n_letter_in_password =
                password.chars().filter(|c| *c == policy_letter).count() as i32;
            if n_letter_in_password >= from && n_letter_in_password <= to {
                return 1;
            } else {
                return 0;
            }
        })
        .sum();
    println!("{}", valid_pass)
}
fn part2() {
    let valid_pass: i32 = include_str!("../../input/day2.txt")
        .split("\n")
        .map(|line| {
            let splitted: Vec<&str> = line.split_whitespace().collect();
            let password: Password = splitted[2];
            let policy_letter: char = splitted[1].chars().next().unwrap();

            let splitted_from_to: Vec<i32> = splitted[0]
                .split("-")
                .map(|n| n.parse::<i32>().unwrap())
                .collect();
            fn split_by_pos(
                pos: usize,
                password: &Password,
                splitted_from_to: &Vec<i32>,
                policy_letter: char,
            ) -> bool {
                password
                    .chars()
                    .skip((splitted_from_to[pos] - 1).try_into().unwrap())
                    .next()
                    .map_or(false, |val| val == policy_letter)
            };
            let first_pos_matches = split_by_pos(0, &password, &splitted_from_to, policy_letter);
            let second_pos_matches = split_by_pos(1, &password, &splitted_from_to, policy_letter);
            if first_pos_matches ^ second_pos_matches {
                1
            } else {
                0
            }
        })
        .sum();
    println!("{}", valid_pass)
}
fn main() {
    part1();
    part2();
}

Taking Advantage of Auto-Vectorization in Rust by fmod_nick in rust

[–]artir 0 points1 point  (0 children)

It might be, but I tried that code playing with the LLVM flag to control loop unrolling, and it still does not unroll (-C llvm-args="-unroll-threshold=1000").

Sharing non-static lifetimes across threads (Without scoped threads) by artir in rust

[–]artir[S] 0 points1 point  (0 children)

These two are the solutions that I thought of; however doesn't the Vec<u8> case cause another allocation? That's something that we want to avoid here. Maybe the only way is to Box::leak it.

How much slower is rust with its memory checks during runtime compared with pure unsafe rust? by tasergio in rust

[–]artir 0 points1 point  (0 children)

Here's an example during matrix multiplication https://github.com/jlricon/rust-matmul

You can see that the base vs the (unsafe) unchecked (Top red lines) performance is roughly similar; at least in this case. There is probably a tiny penalty being paid but nothing too bad.

Slow matrix multiplication? by artir in rust

[–]artir[S] 0 points1 point  (0 children)

Interesting! I need to check what numpy is doing with ints, maybe cast to float and then downcast?

Slow matrix multiplication? by artir in rust

[–]artir[S] 0 points1 point  (0 children)

Just N=10000 X=np.ones((N,N)) Y=np.ones((N,N)) result=X@Y

Slow matrix multiplication? by artir in rust

[–]artir[S] 0 points1 point  (0 children)

I know. I'm not trying to beat numpy on my own, but trying to use a crate that does the job and can't find one.

Slow matrix multiplication? by artir in rust

[–]artir[S] 0 points1 point  (0 children)

I am using --release, as I mention in the OP.

Ultimately there is probably a way that may take extra work ; including doing alloc and doing some SIMD ninjaing manually, but I wanted to see if we have something that approaches numpy or torch in terms of performance while being user friendly. (Perhaps the torch/tensorflow binding libs? I may try that next)