init: 初始化rust项目

This commit is contained in:
2023-12-12 18:40:24 +08:00
commit 21276cc6d4
16 changed files with 2676 additions and 0 deletions

231
src/fetcher.rs Normal file
View File

@@ -0,0 +1,231 @@
extern crate reqwest;
extern crate serde_json;
use serde_json::Value;
use std::fmt::{Display, Error, Formatter};
const PROBLEMS_URL: &str = "https://leetcode.cn/api/problems/algorithms/";
const GRAPHQL_URL: &str = "https://leetcode.cn/graphql";
const QUESTION_QUERY_STRING: &str = r#"
query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
content
stats
codeDefinition
sampleTestCase
metaData
}
}"#;
const QUESTION_QUERY_OPERATION: &str = "questionData";
pub async fn get_problem(frontend_question_id: u32) -> Option<Problem> {
let problems = get_problems().await.unwrap();
for problem in problems.stat_status_pairs.iter() {
match problem.stat.frontend_question_id.parse::<u32>() {
Ok(id) => {
if id == frontend_question_id {
if problem.paid_only {
return None;
}
let client = reqwest::Client::new();
let resp: RawProblem = client
.post(GRAPHQL_URL)
.json(&Query::question_query(
problem.stat.question_title_slug.as_ref().unwrap(),
))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
return Some(Problem {
title: problem.stat.question_title.clone().unwrap(),
title_slug: problem.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.difficulty.to_string(),
question_id: id,
return_type: {
let v: Value = serde_json::from_str(&resp.data.question.meta_data).unwrap();
v["return"]["type"].to_string().replace("\"", "")
},
});
}
}
_ => {}
}
}
None
}
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();
match problem_stat.stat.frontend_question_id.parse::<u32>() {
Ok(id) => {
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: id,
return_type: {
let v: Value = serde_json::from_str(&resp.data.question.meta_data).unwrap();
v["return"]["type"].to_string().replace("\"", "")
},
});
}
_ => {
None
}
}
}
pub async fn get_problems() -> Option<Problems> {
reqwest::get(PROBLEMS_URL).await.unwrap().json().await.unwrap()
}
#[derive(Serialize, Deserialize)]
pub struct Problem {
pub title: String,
pub title_slug: String,
pub content: String,
#[serde(rename = "codeDefinition")]
pub code_definition: Vec<CodeDefinition>,
#[serde(rename = "sampleTestCase")]
pub sample_test_case: String,
pub difficulty: String,
pub question_id: u32,
pub return_type: String,
}
#[derive(Serialize, Deserialize)]
pub struct CodeDefinition {
pub value: String,
pub text: String,
#[serde(rename = "defaultCode")]
pub default_code: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Query {
#[serde(rename = "operationName")]
operation_name: String,
variables: serde_json::Value,
query: String,
}
impl Query {
fn question_query(title_slug: &str) -> Query {
Query {
operation_name: QUESTION_QUERY_OPERATION.to_owned(),
variables: json!({ "titleSlug": title_slug }),
query: QUESTION_QUERY_STRING.to_owned(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct RawProblem {
data: Data,
}
#[derive(Debug, Serialize, Deserialize)]
struct Data {
question: Question,
}
#[derive(Debug, Serialize, Deserialize)]
struct Question {
content: String,
stats: String,
#[serde(rename = "codeDefinition")]
code_definition: String,
#[serde(rename = "sampleTestCase")]
sample_test_case: String,
#[serde(rename = "metaData")]
meta_data: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Problems {
user_name: String,
num_solved: u32,
num_total: u32,
ac_easy: u32,
ac_medium: u32,
ac_hard: u32,
pub stat_status_pairs: Vec<StatWithStatus>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StatWithStatus {
pub stat: Stat,
difficulty: Difficulty,
paid_only: bool,
is_favor: bool,
frequency: u32,
progress: u32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Stat {
question_id: u32,
#[serde(rename = "question__article__slug")]
question_article_slug: Option<String>,
#[serde(rename = "question__title")]
question_title: Option<String>,
#[serde(rename = "question__title_slug")]
question_title_slug: Option<String>,
#[serde(rename = "question__hide")]
question_hide: bool,
total_acs: u32,
total_submitted: u32,
pub frontend_question_id: String,
is_new_question: bool,
}
#[derive(Debug, Serialize, Deserialize)]
struct Difficulty {
level: u32,
}
impl Display for Difficulty {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self.level {
1 => f.write_str("Easy"),
2 => f.write_str("Medium"),
3 => f.write_str("Hard"),
_ => f.write_str("Unknown"),
}
}
}

5
src/lib.rs Normal file
View File

@@ -0,0 +1,5 @@
#[macro_use]
pub mod util;
pub mod solution;
pub mod problem;

368
src/main.rs Normal file
View File

@@ -0,0 +1,368 @@
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
mod fetcher;
use crate::fetcher::{CodeDefinition, Problem};
use regex::Regex;
use std::env;
use std::fs;
use std::fs::File;
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
#[tokio::main]
async fn main() {
println!("Welcome to leetcode-rust system.\n");
let mut initialized_ids = get_initialized_ids();
loop {
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;
let mut id_arg = String::new();
io::stdin()
.read_line(&mut id_arg)
.expect("Failed to read line");
let id_arg = id_arg.trim();
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.");
id = generate_random_id(&initialized_ids);
is_random = true;
println!("Generate random problem: {}", &id);
} else if solving_pattern.is_match(id_arg) {
// solve a problem
// move it from problem/ to solution/
is_solving = true;
id = solving_pattern
.captures(id_arg)
.unwrap()
.get(1)
.unwrap()
.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().await.unwrap();
let mut mod_file_addon = Arc::new(Mutex::new(vec![]));
for problem_stat in problems.stat_status_pairs {
match problem_stat.stat.frontend_question_id.parse::<u32>() {
Ok(id) => {
if initialized_ids.contains(&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>()
.unwrap_or_else(|_| panic!("not a number: {}", id_arg));
if initialized_ids.contains(&id) {
println!("The problem you chose has been initialized in problem/");
continue;
}
}
let problem = fetcher::get_problem(id).await.unwrap_or_else(|| {
panic!(
"Error: failed to get problem #{} \
(The problem may be paid-only or may not be exist).",
id
)
});
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();
deal_problem(&problem, &code, true);
break;
}
}
fn generate_random_id(except_ids: &[u32]) -> u32 {
use rand::Rng;
use std::fs;
let mut rng = rand::thread_rng();
loop {
let res: u32 = rng.gen_range(1, 1106);
if !except_ids.contains(&res) {
return res;
}
println!(
"Generate a random num ({}), but it is invalid (the problem may have been solved \
or may have no rust version). Regenerate..",
res
);
}
}
fn get_initialized_ids() -> Vec<u32> {
let content = fs::read_to_string("./src/problem/mod.rs").unwrap();
let id_pattern = Regex::new(r"p(\d{4})_").unwrap();
id_pattern
.captures_iter(&content)
.map(|x| x.get(1).unwrap().as_str().parse().unwrap())
.collect()
}
fn parse_extra_use(code: &str) -> String {
let mut extra_use_line = String::new();
// a linked-list problem
if code.contains("pub struct ListNode") {
extra_use_line.push_str("\nuse crate::util::linked_list::{ListNode, to_list};")
}
if code.contains("pub struct TreeNode") {
extra_use_line.push_str("\nuse crate::util::tree::{TreeNode, to_tree};")
}
if code.contains("pub struct Point") {
extra_use_line.push_str("\nuse crate::util::point::Point;")
}
extra_use_line
}
fn parse_problem_link(problem: &Problem) -> String {
format!("https://leetcode.cn/problems/{}/", problem.title_slug)
}
fn parse_discuss_link(problem: &Problem) -> String {
format!(
"https://leetcode.cn/problems/{}/discuss/?currentPage=1&orderBy=most_votes&query=",
problem.title_slug
)
}
fn insert_return_in_code(return_type: &str, code: &str) -> String {
let re = Regex::new(r"\{[ \n]+}").unwrap();
match return_type {
"ListNode" => re
.replace(&code, "{\n Some(Box::new(ListNode::new(0)))\n }")
.to_string(),
"ListNode[]" => re.replace(&code, "{\n vec![]\n }").to_string(),
"TreeNode" => re
.replace(
&code,
"{\n Some(Rc::new(RefCell::new(TreeNode::new(0))))\n }",
)
.to_string(),
"boolean" => re.replace(&code, "{\n false\n }").to_string(),
"character" => re.replace(&code, "{\n '0'\n }").to_string(),
"character[][]" => re.replace(&code, "{\n vec![]\n }").to_string(),
"double" => re.replace(&code, "{\n 0f64\n }").to_string(),
"double[]" => re.replace(&code, "{\n vec![]\n }").to_string(),
"int[]" => re.replace(&code, "{\n vec![]\n }").to_string(),
"integer" => re.replace(&code, "{\n 0\n }").to_string(),
"integer[]" => re.replace(&code, "{\n vec![]\n }").to_string(),
"integer[][]" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<String>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<TreeNode>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<boolean>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<double>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<integer>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<list<integer>>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<list<string>>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"list<string>" => re.replace(&code, "{\n vec![]\n }").to_string(),
"null" => code.to_string(),
"string" => re
.replace(&code, "{\n String::new()\n }")
.to_string(),
"string[]" => re.replace(&code, "{\n vec![]\n }").to_string(),
"void" => code.to_string(),
"NestedInteger" => code.to_string(),
"Node" => code.to_string(),
_ => code.to_string(),
}
}
fn build_desc(content: &str) -> String {
// TODO: fix this shit
content
.replace("<strong>", "")
.replace("</strong>", "")
.replace("<em>", "")
.replace("</em>", "")
.replace("</p>", "")
.replace("<p>", "")
.replace("<b>", "")
.replace("</b>", "")
.replace("<pre>", "")
.replace("</pre>", "")
.replace("<ul>", "")
.replace("</ul>", "")
.replace("<li>", "")
.replace("</li>", "")
.replace("<code>", "")
.replace("</code>", "")
.replace("<i>", "")
.replace("</i>", "")
.replace("<sub>", "")
.replace("</sub>", "")
.replace("</sup>", "")
.replace("<sup>", "^")
.replace("&nbsp;", " ")
.replace("&gt;", ">")
.replace("&lt;", "<")
.replace("&quot;", "\"")
.replace("&minus;", "-")
.replace("&#39;", "'")
.replace("\n\n", "\n")
.replace("\n", "\n * ")
}
async fn deal_solving(id: &u32) {
let problem = fetcher::get_problem(*id).await.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))
.replace("__PROBLEM_LINK__", &parse_problem_link(problem))
.replace("__DISCUSS_LINK__", &parse_discuss_link(problem));
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);
}
}

29
src/util/linked_list.rs Normal file
View File

@@ -0,0 +1,29 @@
#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
pub fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
// helper function for test
pub fn to_list(vec: Vec<i32>) -> Option<Box<ListNode>> {
let mut current = None;
for &v in vec.iter().rev() {
let mut node = ListNode::new(v);
node.next = current;
current = Some(Box::new(node));
}
current
}
#[macro_export]
macro_rules! linked {
($($e:expr),*) => {to_list(vec![$($e.to_owned()), *])};
($($e:expr,)*) => {to_list(vec![$($e.to_owned()), *])};
}

8
src/util/mod.rs Normal file
View File

@@ -0,0 +1,8 @@
#[macro_use]
pub mod linked_list;
#[macro_use]
pub mod vec_string;
#[macro_use]
pub mod tree;
#[macro_use]
pub mod point;

23
src/util/point.rs Normal file
View File

@@ -0,0 +1,23 @@
#[derive(Debug, PartialEq, Eq)]
pub struct Point {
pub x: i32,
pub y: i32,
}
impl Point {
#[inline]
pub fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
}
#[macro_export]
macro_rules! point {
($($e:expr),*) => {
{
let vec = vec![$($e.to_owned()), *];
Point::new(vec[0], vec[1])
}
};
($($e:expr,)*) => (point![$($x),*])
}

1
src/util/testing.rs Normal file
View File

@@ -0,0 +1 @@

57
src/util/tree.rs Normal file
View File

@@ -0,0 +1,57 @@
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
pub fn to_tree(vec: Vec<Option<i32>>) -> Option<Rc<RefCell<TreeNode>>> {
use std::collections::VecDeque;
let head = Some(Rc::new(RefCell::new(TreeNode::new(vec[0].unwrap()))));
let mut queue = VecDeque::new();
queue.push_back(head.as_ref().unwrap().clone());
for children in vec[1..].chunks(2) {
let parent = queue.pop_front().unwrap();
if let Some(v) = children[0] {
parent.borrow_mut().left = Some(Rc::new(RefCell::new(TreeNode::new(v))));
queue.push_back(parent.borrow().left.as_ref().unwrap().clone());
}
if children.len() > 1 {
if let Some(v) = children[1] {
parent.borrow_mut().right = Some(Rc::new(RefCell::new(TreeNode::new(v))));
queue.push_back(parent.borrow().right.as_ref().unwrap().clone());
}
}
}
head
}
#[macro_export]
macro_rules! tree {
() => {
None
};
($($e:expr),*) => {
{
let vec = vec![$(stringify!($e)), *];
let vec = vec.into_iter().map(|v| v.parse::<i32>().ok()).collect::<Vec<_>>();
to_tree(vec)
}
};
($($e:expr,)*) => {(tree![$($e),*])};
}

5
src/util/vec_string.rs Normal file
View File

@@ -0,0 +1,5 @@
#[macro_export]
macro_rules! vec_string {
($($e:expr),*) => {vec![$($e.to_owned()), *]};
($($e:expr,)*) => {vec![$($e.to_owned()), *]};
}