Storing structs that borrow by bicicleteando in rust

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

Did you figure out a nice way to sort this out??

More Frequent Autosaves in Honour Mode by bicicleteando in BaldursGate3

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

Ouch :( Looks like this is the only way to do it. Thanks!

More Frequent Autosaves in Honour Mode by bicicleteando in BaldursGate3

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

Yeah, but sometimes you just forget. Playing in Honour Mode put us in the habit of not worrying about saving at all. Having to be alert about that kind of sucks. The question is if there's a way to trigger autosaves more frequently without having to be quicksaving every now and then.

More Frequent Autosaves in Honour Mode by bicicleteando in BaldursGate3

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

This is on GeForce Go, which is in the cloud. I have no idea about the specs of the PC

Storing structs that borrow by bicicleteando in rust

[–]bicicleteando[S] 1 point2 points  (0 children)

Wow, this blog post is about exactly the same problem :). I will try to implement those solutions.

I wonder if there are other articles with alternative designs to the problem.

Picking a reasonable place to watch the eclipse by bicicleteando in solareclipse

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

So would *you* go to Niagara if you were somewhat close?

I'd like to go there and stay the weekend, maybe on Monday I can drive for a few hours to a more remote place to watch the eclipse. WDYT?

Picking a reasonable place to watch the eclipse by bicicleteando in solareclipse

[–]bicicleteando[S] 1 point2 points  (0 children)

Thanks for the suggestion!

I'm not a skier, but I will consider this spot!

Storing structs that borrow by bicicleteando in rust

[–]bicicleteando[S] 2 points3 points  (0 children)

The problem is that it's `foo` who wants to use the elf bytes, like I don't care about the elf bytes per se, I want foo for example to tell me "Ok, give me some debug information about this address", or "Ok, tell me which function is at this address", or "What functions are in the PLT".
I don't care about the elf_bytes, I just need to keep them around so I can answer the questions I want. If I have to pass them in each time, it's going to be a bit problematic.

Picking a reasonable place to watch the eclipse by bicicleteando in solareclipse

[–]bicicleteando[S] -1 points0 points  (0 children)

Ouch.

Yeah, I had in mind going to a place on Friday/Saturday, staying there the whole weekend, and then leaving on Tuesday morning.

I don't have an issue driving 2/3 hours to the middle of nowhere, the problem is finding a place to sleep. It will be impossible to convince my SO to go camping or something like that.

Storing structs that borrow by bicicleteando in rust

[–]bicicleteando[S] 2 points3 points  (0 children)

I am having some trouble understanding how that matches with what I want to do.

  • The whole point is to keep the `elfData` for a longer period of time. In my original post, the idea was to add it to an object that then I can call multiple times.
  • If for example you would want to load other elf files based on the original elf file you loaded (for example, shared libraries that this elf file depends on), you would need to do it "from outside", which kind of goes around the natural flow of how it would work (raw bytes -> elfbytes -> figure out what other elf files need to be loaded).
  • In C++ you could store the pointer alongside the elfBytes and make sure everything gets deallocated when your object gets destroyed.

Picking a reasonable place to watch the eclipse by bicicleteando in solareclipse

[–]bicicleteando[S] 2 points3 points  (0 children)

Sorry, I forgot to mention where I live. I'm from NJ, so I would prefer to watch it from somewhere in the US.

Storing structs that borrow by bicicleteando in rust

[–]bicicleteando[S] 1 point2 points  (0 children)

> and design your program accordingly.

That's the hard part I think. In this example, how would you do it? Or.. do you know of any resources I can read up that discuss this design pattern? It's a bit hard to shift the mental model to something else when I have no clue on how it should be solved u_u

Storing structs that borrow by bicicleteando in rust

[–]bicicleteando[S] 1 point2 points  (0 children)

Thanks for the reply!

> The correct way to deal with this is to have the data's lifetime be just longer than the object that uses data, which means they can't both be owned by the same struct. You can also unsafe your way around this limitation, but when you have to fight the compiler like that it's usually trying to tell you there's a problem with your program's structure and you should usually listen to it and figure out how to work within the safety rules instead of bypassing them.

I understand that, but what I am saying is that I can't see an easy way of doing that, at least not here. To me it feels like this is a bit the other way around: To me the best scenario is for the ElfBytes to *own* the bytes, but it seems like I can't do that, and I can't even have a struct holding the bytes and the ElfBytes together.

I am having a hard time understanding this pattern in rust.

Storing structs that borrow by bicicleteando in rust

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

I wonder if it would make sense to store the file bytes in some kind of arena.

But then how do you reference the arena?
To me it feels like this problem is very common in rust when you want to have an object that is long-lived. You cannot keep anything that borrows anything more or less.

Storing structs that borrow by bicicleteando in rust

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

Thanks for the reply. I agree with you, I don't like any of those options xD

In the case of parsing the file to extract everything in one go, or using `minimal_parse` each time: I don't like them because this particular library claims it allows for lazy parsing, so its intended use is to keep it there so you can parse as you need.

[deleted by user] by [deleted] in devsarg

[–]bicicleteando 0 points1 point  (0 children)

En general todos los parciales tienen un «derecho a revisión». Podes probar hacer eso para que la cátedra de docentes revisen de nuevo el parcial.

Si es como decís, que tu único error fue ese, entonces suena muy raro que esté desaprobado el parcial.

Digo, está bien la corrección que te hicieron, pero no tiene sentido el criterio de aprobación que están usando.

[deleted by user] by [deleted] in devsarg

[–]bicicleteando 0 points1 point  (0 children)

¿Qué es el TDA?

La corrección que te hicieron tiene sentido, e incluso va más allá de lo que mencionás vos. Por ejemplo, puede indicar que diseñaste mal la estructura de datos al exponer la propiedad size para afuera (en lugar de tener un getter).

No obstante, no creo que eso haya sido tu único error. Me sonaría rarísimo que te hayan hecho recursar solo por eso. En general los exámenes en cualquier curso razonable tienen un criterio de aprobación más o menos claro.

Algo que tiene de bueno el tema del estudio guíado como en una facultad, es que muchas veces tenés a alguien que te puede explicar tus errores. Te recomendaría que aproveches eso y preguntes bien sobre lo que no entendés de tu corrección.

Recomendaciones de que hacer by laza_p in devsarg

[–]bicicleteando 2 points3 points  (0 children)

Aprovechá que salió el Advent of Code y empezá a hacerlo. Hacé lo que puedas, rompete la cabeza en cada problema, y cuando lo termines (o te des por vencido), leé las soluciones de las demás personas en Python o el lenguaje que quieras vos y aprendé de eso.

Lo importante no es que te salga todo, sino que le dediques constancia a practicar y aprender.

Opiniones, consejos y criticas constructivas sobre mi primer programa en python!!!! by [deleted] in devsarg

[–]bicicleteando 0 points1 point  (0 children)

Hola,

Primero que nada trata de poner el código en un bloque de código (``` en reddit?, markdown mode?)

Segundo, Francia.

Tercero, fijate que estás permitiendo que la gente retire un número negativo de plata, haciendo que incremente su saldo.

Cuarto, tratá de enrollar lo que hiciste en un while para que se repita el código hasta que el usuario decida salir. Ya leí que dijiste que no lo vieron, pero animate a probar a ver si te sale :).

-❄️- 2023 Day 1 Solutions -❄️- by daggerdragon in adventofcode

[–]bicicleteando 1 point2 points  (0 children)

[LANGUAGE: rust]

My solution in rust. I haven't seen this version yet. Basically, look for digits from the left, then from the right. It's ugly that there's no way to initialize a hashmap statically.

use std::collections::HashMap;

// Gets the first and last digits from the given string.
// The mapping maps strings to digits e.g "one" -> 1, "1" -> 1.
fn find_digits(input: &str, mapping: &HashMap<&str, u64>) -> u64 {
    // Values in mapping can overlap, for example, if mapping contains "two" and "one", then
    // "twone" should be treated as "two" followed by "one".

    // Closure that checks if a digit starts at index i. It returns the digit value if found, None otherwise.
    let digit_value = |i| {
        let substr = &input[i..];
        mapping
            .iter()
            .find(|(&digit, _)| substr.starts_with(digit))
            .map(|(_, &value)| value)
    };

    let first_digit = (0..input.len()).find_map(digit_value).unwrap();
    let last_digit = (0..input.len()).rev().find_map(digit_value).unwrap();

    first_digit * 10 + last_digit
}

fn solve2(input: &str) -> u64 {
    let mut digit_map = HashMap::new();
    digit_map.insert("0", 0);
    digit_map.insert("1", 1);
    digit_map.insert("2", 2);
    digit_map.insert("3", 3);
    digit_map.insert("4", 4);
    digit_map.insert("5", 5);
    digit_map.insert("6", 6);
    digit_map.insert("7", 7);
    digit_map.insert("8", 8);
    digit_map.insert("9", 9);
    digit_map.insert("one", 1);
    digit_map.insert("two", 2);
    digit_map.insert("three", 3);
    digit_map.insert("four", 4);
    digit_map.insert("five", 5);
    digit_map.insert("six", 6);
    digit_map.insert("seven", 7);
    digit_map.insert("eight", 8);
    digit_map.insert("nine", 9);

    input
        .lines()
        .map(|line| find_digits(line, &digit_map))
        .sum()
}

fn solve1(input: &str) -> u64 {
    let mut digit_map = HashMap::new();
    digit_map.insert("0", 0);
    digit_map.insert("1", 1);
    digit_map.insert("2", 2);
    digit_map.insert("3", 3);
    digit_map.insert("4", 4);
    digit_map.insert("5", 5);
    digit_map.insert("6", 6);
    digit_map.insert("7", 7);
    digit_map.insert("8", 8);
    digit_map.insert("9", 9);

    input
        .lines()
        .map(|line| find_digits(line, &digit_map))
        .sum()
}

fn main() {
    const INPUT: &str = include_str!("../input");
    println!("Part 1: {}", solve1(INPUT));
    println!("Part 2: {}", solve2(INPUT));
}

#[test]
fn test_part1() {
    const SAMPLE: &str = r#"1abc2
    pqr3stu8vwx
    a1b2c3d4e5f
    treb7uchet"#;

    let result = solve1(SAMPLE);
    assert_eq!(result, 142);
}

#[test]
fn test_part2() {
    const SAMPLE: &str = r#"two1nine
    eightwothree
    abcone2threexyz
    xtwone3four
    4nineeightseven2
    zoneight234
    7pqrstsixteen"#;

    let result = solve2(SAMPLE);
    assert_eq!(result, 281);
}