-
Notifications
You must be signed in to change notification settings - Fork 28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Day 4 / Borrowing in loop #6
Comments
I copied your code from your link, but it compiles and runs just fine. Can you show me the exact code you're using that is giving you an error? It's otherwise hard to help. |
I just try to erase my file, and copy paste the file I linked, and I have the compilation error I just past before :( I don't understand how it works on your side!
|
Oh, you must not be using Rust 2018. On Rust 2018, your code compiles because of improvements to the borrow checker. That is, before the improvements, the borrow checker rejected more valid programs. You can use Rust 2018 by adding This is a good example of the nice additions that Rust 2018 brings. I don't see any tiny changes I can make to your code to make it work. Instead, it seems to require some restructuring. e.g., something like this: extern crate chrono;
extern crate regex;
use std::fs;
use regex::Regex;
use std::collections::HashMap;
use chrono::prelude::*;
const FILE_NAME: &str = "./input.txt";
struct Record {
guard_id: String,
date_time: DateTime<Utc>,
fulldate: String,
// date: String,
// hour: String,
minute: String,
description: String,
}
struct Guard {
id: String,
minutes: Vec<(i64, i64)>,
most_minute_asleep: (i64, i64),
total_asleep: i64,
}
fn get_guards() {
let content = fs::read_to_string(FILE_NAME).unwrap();
let re = Regex::new(r"\[(\d+-\d+-\d+) (\d+):(\d+)\]( Guard #)?(\d+)? (.*)").unwrap();
let mut records: Vec<Record> = Vec::new();
for line in content.lines() {
match re.captures(line) {
Some(captures) => {
let date = captures.get(1).unwrap().as_str().to_string();
let hour = captures.get(2).unwrap().as_str().to_string();
let minute = captures.get(3).unwrap().as_str().to_string();
let fulldate = format!("{}T{}:{}:00Z", date, hour, minute);
let description = captures.get(6).unwrap().as_str().to_string();
let guard_id = match captures.get(5) {
Some(matcher) => matcher.as_str().to_string(),
None => String::from("")
};
let date_time = fulldate.parse::<DateTime<Utc>>().unwrap();
records.push(Record {
guard_id,
date_time,
fulldate,
// date,
// hour,
minute,
description,
});
},
None => {}
}
}
records.sort_by(|record_a, record_b| record_a.date_time.cmp(&record_b.date_time));
println!("records size: {}", records.len());
let mut guards: HashMap<String, Guard> = HashMap::new();
// let mut current_guard: &mut Guard = &mut Guard { id: String::from(""), minutes: Vec::new(), most_minute_asleep: (0, 0), total_asleep: 0 };
let mut current_guard_id = String::from("");
let mut last_date_time = Utc::now();
let mut last_minute = String::from("");
let mut minutes: HashMap<i64, i64> = HashMap::new();
let mut sorted_minutes = Vec::new();
for record in records {
let Record { guard_id, date_time, description, minute, .. } = record;
if !guard_id.is_empty() { // empty guard_id means we are changing guard
current_guard_id = guard_id.clone();
}
let mut current_guard = guards
.entry(current_guard_id.clone())
.or_insert(Guard {
id: guard_id.clone(),
minutes: Vec::new(),
most_minute_asleep: (0, 0),
total_asleep: 0,
});
if !guard_id.is_empty() { // empty guard_id means we are changing guard
for (minute, times) in minutes.iter() {
sorted_minutes.push((minute.clone(), times.clone()));
}
sorted_minutes.sort_by(|minute_a, minute_b| minute_b.1.cmp(&minute_a.1));
current_guard.minutes = sorted_minutes.drain(..).collect();
current_guard.most_minute_asleep = match current_guard.minutes.get(0) {
Some(value) => value.clone(),
None => (0, 0)
};
minutes.clear();
sorted_minutes.clear();
}
if description == "falls asleep" {
last_date_time = date_time.clone();
last_minute = minute.clone();
}
if description == "wakes up" {
current_guard.total_asleep += (date_time - last_date_time).num_minutes() + 1;
let num_minutes = (date_time - last_date_time).num_minutes();
for min in 0..num_minutes {
*minutes.entry(last_minute.parse::<i64>().unwrap() + min).or_insert(0) += 1;
}
}
}
}
fn main() {
get_guards();
} |
Thank you! With your review and this thread: https://www.reddit.com/r/rust/comments/5ny09j/tips_to_not_fight_the_borrow_checker/ I have something that works :) I didn't know I have to pass in "2018" version, thank you. I updated my code as described here if you are curious: fabienjuif/advent-of-code-2018@dc8d762 For now I found Rust quite difficult to understand, for example I don't understand why I have to add "Clone" Trait to my structure when I just wanted my vectors to be copied (but not values) 🤔 Thank you (again) for helping me out |
This isn't necessarily Rust that's tripping you up, it's just that such an operation doesn't quite make sense. Vectors store their elements inline, such that a If you're looking to pass many pointers to that |
What I wanted was to copy the vector into part1(), sort in a way into part1() that doesn't mutate the vector that was in main(), and do the same in part2() WITHOUT copying all its values. fn main() {
let vector = get_data(); // 1 000 000 elements
println!("main, index0: {}", vector.get(0).unwrap()); // 1.
part1(vector); // share access by a way I don't know
println!("main, index0 (after): {}", vector.get(0).unwrap()); // 2.
}
fn part1(let vector: Vec::<T>) {
// ... vector.sort_by()
println!("part1, index0: {}", vector.get(0).unwrap()); // 3.
} I wanted to have How would you do that? Thank you a lot for your time 👍 |
Hmm, well, |
I think I understand the misconception that I have:
Thank you @BurntSushi ✨ |
Hi @BurntSushi,
Thank again for your work!
Do you have time to explain why my code is bad, and how I can achieve this in a better way?
HashMap
(key: String [guard_id], value: Guard [values I want to store]) that contains my guards data.But I am stuck with this error and I dunno how I can do this kind of code in a better way
source code (https://github.com/fabienjuif/advent-of-code-2018/blob/borrow/day4/src/main.rs
):
Thank you 👍
The text was updated successfully, but these errors were encountered: