Skip to content
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

Solve problems #25

Closed
wants to merge 19 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
486 changes: 486 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -11,6 +11,8 @@ serde_json = "1.0"
serde_derive = "1.0"
rand = "0.6.5"
regex = "1.3.4"
futures = { version = "0.3.3", features = ["thread-pool"] }
surf = "1.0.3"

[lib]
doctest = false
56 changes: 49 additions & 7 deletions src/fetcher.rs
Original file line number Diff line number Diff line change
@@ -54,7 +54,49 @@ pub fn get_problem(frontend_question_id: u32) -> Option<Problem> {
None
}

fn get_problems() -> Option<Problems> {
pub async fn get_problem_async(problem_stat: StatWithStatus) -> Option<Problem> {
if problem_stat.paid_only {
println!(
"Problem {} is paid-only",
&problem_stat.stat.frontend_question_id
);
return None;
}
let resp = surf::post(GRAPHQL_URL).body_json(&Query::question_query(
problem_stat.stat.question_title_slug.as_ref().unwrap(),
));
if resp.is_err() {
println!(
"Problem {} not initialized due to some error",
&problem_stat.stat.frontend_question_id
);
return None;
}
let resp = resp.unwrap().recv_json().await;
if resp.is_err() {
println!(
"Problem {} not initialized due to some error",
&problem_stat.stat.frontend_question_id
);
return None;
}
let resp: RawProblem = resp.unwrap();
return Some(Problem {
title: problem_stat.stat.question_title.clone().unwrap(),
title_slug: problem_stat.stat.question_title_slug.clone().unwrap(),
code_definition: serde_json::from_str(&resp.data.question.code_definition).unwrap(),
content: resp.data.question.content,
sample_test_case: resp.data.question.sample_test_case,
difficulty: problem_stat.difficulty.to_string(),
question_id: problem_stat.stat.frontend_question_id,
return_type: {
let v: Value = serde_json::from_str(&resp.data.question.meta_data).unwrap();
v["return"]["type"].to_string().replace("\"", "")
},
});
}

pub fn get_problems() -> Option<Problems> {
reqwest::get(PROBLEMS_URL).unwrap().json().unwrap()
}

@@ -121,19 +163,19 @@ struct Question {
}

#[derive(Debug, Serialize, Deserialize)]
struct Problems {
pub struct Problems {
user_name: String,
num_solved: u32,
num_total: u32,
ac_easy: u32,
ac_medium: u32,
ac_hard: u32,
stat_status_pairs: Vec<StatWithStatus>,
pub stat_status_pairs: Vec<StatWithStatus>,
}

#[derive(Debug, Serialize, Deserialize)]
struct StatWithStatus {
stat: Stat,
pub struct StatWithStatus {
pub stat: Stat,
difficulty: Difficulty,
paid_only: bool,
is_favor: bool,
@@ -142,7 +184,7 @@ struct StatWithStatus {
}

#[derive(Debug, Serialize, Deserialize)]
struct Stat {
pub struct Stat {
question_id: u32,
#[serde(rename = "question__article__slug")]
question_article_slug: Option<String>,
@@ -154,7 +196,7 @@ struct Stat {
question_hide: bool,
total_acs: u32,
total_submitted: u32,
frontend_question_id: u32,
pub frontend_question_id: u32,
is_new_question: bool,
}

232 changes: 157 additions & 75 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@ extern crate serde_json;

mod fetcher;

use crate::fetcher::{CodeDefinition, Problem};
use regex::Regex;
use std::env;
use std::fs;
@@ -13,12 +14,24 @@ use std::io;
use std::io::{BufRead, Write};
use std::path::Path;

use futures::executor::block_on;
use futures::executor::ThreadPool;
use futures::future::join_all;
use futures::stream::StreamExt;
use futures::task::SpawnExt;
use std::sync::{Arc, Mutex};

/// main() helps to generate the submission template .rs
fn main() {
println!("Welcome to leetcode-rust system.");
println!("Welcome to leetcode-rust system.\n");
let mut initialized_ids = get_initialized_ids();
loop {
println!("Please enter a frontend problem id, or \"random\" to generate a random one, or \"solve $i\" to move problem to solution/");
println!(
"Please enter a frontend problem id, \n\
or \"random\" to generate a random one, \n\
or \"solve $i\" to move problem to solution/, \n\
or \"all\" to initialize all problems \n"
);
let mut is_random = false;
let mut is_solving = false;
let mut id: u32 = 0;
@@ -30,6 +43,7 @@ fn main() {

let random_pattern = Regex::new(r"^random$").unwrap();
let solving_pattern = Regex::new(r"^solve (\d+)$").unwrap();
let all_pattern = Regex::new(r"^all$").unwrap();

if random_pattern.is_match(id_arg) {
println!("You select random mode.");
@@ -48,6 +62,59 @@ fn main() {
.as_str()
.parse()
.unwrap();
deal_solving(&id);
break;
} else if all_pattern.is_match(id_arg) {
// deal all problems
let pool = ThreadPool::new().unwrap();
let mut tasks = vec![];
let problems = fetcher::get_problems().unwrap();
let mut mod_file_addon = Arc::new(Mutex::new(vec![]));
for problem_stat in problems.stat_status_pairs {
if initialized_ids.contains(&problem_stat.stat.frontend_question_id) {
continue;
}
let mod_file_addon = mod_file_addon.clone();
tasks.push(
pool.spawn_with_handle(async move {
let problem = fetcher::get_problem_async(problem_stat).await;
if problem.is_none() {
return;
}
let problem = problem.unwrap();
let code = problem
.code_definition
.iter()
.find(|&d| d.value == "rust".to_string());
if code.is_none() {
println!("Problem {} has no rust version.", problem.question_id);
return;
}
// not sure this can be async
async {
mod_file_addon.lock().unwrap().push(format!(
"mod p{:04}_{};",
problem.question_id,
problem.title_slug.replace("-", "_")
));
}
.await;
let code = code.unwrap();
// not sure this can be async
// maybe should use async-std io
async { deal_problem(&problem, &code, false) }.await
})
.unwrap(),
);
}
block_on(join_all(tasks));
let mut lib_file = fs::OpenOptions::new()
.write(true)
.append(true)
.open("./src/problem/mod.rs")
.unwrap();
writeln!(lib_file, "{}", mod_file_addon.lock().unwrap().join("\n"));
break;
} else {
id = id_arg
.parse::<u32>()
@@ -65,85 +132,17 @@ fn main() {
id
)
});
let code = problem.code_definition.iter().find(|&d| d.value == "rust");
let code = problem
.code_definition
.iter()
.find(|&d| d.value == "rust".to_string());
if code.is_none() {
println!("Problem {} has no rust version.", &id);
initialized_ids.push(problem.question_id);
continue;
}
let code = code.unwrap();

let file_name = format!(
"p{:04}_{}",
problem.question_id,
problem.title_slug.replace("-", "_")
);
let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name));
if is_solving {
// check problem/ existence
if !file_path.exists() {
panic!("problem does not exist");
}
// check solution/ no existence
let solution_name = format!(
"s{:04}_{}",
problem.question_id,
problem.title_slug.replace("-", "_")
);
let solution_path = Path::new("./src/solution").join(format!("{}.rs", solution_name));
if solution_path.exists() {
panic!("solution exists");
}
// rename/move file
fs::rename(file_path, solution_path).unwrap();
// remove from problem/mod.rs
let mod_file = "./src/problem/mod.rs";
let target_line = format!("mod {};", file_name);
let lines: Vec<String> = io::BufReader::new(File::open(mod_file).unwrap())
.lines()
.map(|x| x.unwrap())
.filter(|x| *x != target_line)
.collect();
fs::write(mod_file, lines.join("\n"));
// insert into solution/mod.rs
let mut lib_file = fs::OpenOptions::new()
.append(true)
.open("./src/solution/mod.rs")
.unwrap();
writeln!(lib_file, "mod {};", solution_name);
break;
}
if file_path.exists() {
panic!("problem already initialized");
}

let template = fs::read_to_string("./template.rs").unwrap();
let source = template
.replace("__PROBLEM_TITLE__", &problem.title)
.replace("__PROBLEM_DESC__", &build_desc(&problem.content))
.replace(
"__PROBLEM_DEFAULT_CODE__",
&insert_return_in_code(&problem.return_type, &code.default_code),
)
.replace("__PROBLEM_ID__", &format!("{}", problem.question_id))
.replace("__EXTRA_USE__", &parse_extra_use(&code.default_code));

let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&file_path)
.unwrap();

file.write_all(source.as_bytes()).unwrap();
drop(file);

let mut lib_file = fs::OpenOptions::new()
.write(true)
.append(true)
.open("./src/problem/mod.rs")
.unwrap();
writeln!(lib_file, "mod {};", file_name);
deal_problem(&problem, &code, true);
break;
}
}
@@ -265,3 +264,86 @@ fn build_desc(content: &str) -> String {
.replace("\n\n", "\n")
.replace("\n", "\n * ")
}

fn deal_solving(id: &u32) {
let problem = fetcher::get_problem(*id).unwrap();
let file_name = format!(
"p{:04}_{}",
problem.question_id,
problem.title_slug.replace("-", "_")
);
let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name));
// check problem/ existence
if !file_path.exists() {
panic!("problem does not exist");
}
// check solution/ no existence
let solution_name = format!(
"s{:04}_{}",
problem.question_id,
problem.title_slug.replace("-", "_")
);
let solution_path = Path::new("./src/solution").join(format!("{}.rs", solution_name));
if solution_path.exists() {
panic!("solution exists");
}
// rename/move file
fs::rename(file_path, solution_path).unwrap();
// remove from problem/mod.rs
let mod_file = "./src/problem/mod.rs";
let target_line = format!("mod {};", file_name);
let lines: Vec<String> = io::BufReader::new(File::open(mod_file).unwrap())
.lines()
.map(|x| x.unwrap())
.filter(|x| *x != target_line)
.collect();
fs::write(mod_file, lines.join("\n"));
// insert into solution/mod.rs
let mut lib_file = fs::OpenOptions::new()
.append(true)
.open("./src/solution/mod.rs")
.unwrap();
writeln!(lib_file, "mod {};", solution_name);
}

fn deal_problem(problem: &Problem, code: &CodeDefinition, write_mod_file: bool) {
let file_name = format!(
"p{:04}_{}",
problem.question_id,
problem.title_slug.replace("-", "_")
);
let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name));
if file_path.exists() {
panic!("problem already initialized");
}

let template = fs::read_to_string("./template.rs").unwrap();
let source = template
.replace("__PROBLEM_TITLE__", &problem.title)
.replace("__PROBLEM_DESC__", &build_desc(&problem.content))
.replace(
"__PROBLEM_DEFAULT_CODE__",
&insert_return_in_code(&problem.return_type, &code.default_code),
)
.replace("__PROBLEM_ID__", &format!("{}", problem.question_id))
.replace("__EXTRA_USE__", &parse_extra_use(&code.default_code));

let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&file_path)
.unwrap();

file.write_all(source.as_bytes()).unwrap();
drop(file);

if write_mod_file {
let mut lib_file = fs::OpenOptions::new()
.write(true)
.append(true)
.open("./src/problem/mod.rs")
.unwrap();
writeln!(lib_file, "mod {};", file_name);
}
}
Loading
Oops, something went wrong.