init: 初始化rust项目
This commit is contained in:
commit
21276cc6d4
2
.cargo/config
Normal file
2
.cargo/config
Normal file
|
@ -0,0 +1,2 @@
|
|||
[build]
|
||||
rustflags = ["-A", "unused"]
|
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
|
@ -0,0 +1,2 @@
|
|||
target/
|
||||
.idea/
|
1695
Cargo.lock
generated
Normal file
1695
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
20
Cargo.toml
Normal file
20
Cargo.toml
Normal file
|
@ -0,0 +1,20 @@
|
|||
[package]
|
||||
name = "leetcode-rust"
|
||||
version = "0.1.0"
|
||||
authors = ["alei <rayingecho@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
reqwest = { version = "0.11.22", features = ["json"] }
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
serde_derive = "1.0"
|
||||
rand = "0.6.5"
|
||||
regex = "1.3.4"
|
||||
futures = { version = "0.3.11", features = ["thread-pool"] }
|
||||
surf = "1.0.3"
|
||||
tokio = { version = "1.0.0", features = ["rt", "rt-multi-thread", "macros"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
test = true
|
201
LICENSE
Normal file
201
LICENSE
Normal file
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
5
README.md
Normal file
5
README.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
# LeetCode
|
||||
|
||||
运行`cargo run`来初始化题目的模板文件。
|
||||
|
||||
运行`cargo test test_{id}`来运行指定题目的测试。
|
231
src/fetcher.rs
Normal file
231
src/fetcher.rs
Normal 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
5
src/lib.rs
Normal file
|
@ -0,0 +1,5 @@
|
|||
#[macro_use]
|
||||
pub mod util;
|
||||
|
||||
pub mod solution;
|
||||
pub mod problem;
|
368
src/main.rs
Normal file
368
src/main.rs
Normal 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(" ", " ")
|
||||
.replace(">", ">")
|
||||
.replace("<", "<")
|
||||
.replace(""", "\"")
|
||||
.replace("−", "-")
|
||||
.replace("'", "'")
|
||||
.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
29
src/util/linked_list.rs
Normal 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
8
src/util/mod.rs
Normal 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
23
src/util/point.rs
Normal 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
1
src/util/testing.rs
Normal file
|
@ -0,0 +1 @@
|
|||
|
57
src/util/tree.rs
Normal file
57
src/util/tree.rs
Normal 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
5
src/util/vec_string.rs
Normal file
|
@ -0,0 +1,5 @@
|
|||
#[macro_export]
|
||||
macro_rules! vec_string {
|
||||
($($e:expr),*) => {vec![$($e.to_owned()), *]};
|
||||
($($e:expr,)*) => {vec![$($e.to_owned()), *]};
|
||||
}
|
24
template.rs
Normal file
24
template.rs
Normal file
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* [__PROBLEM_ID__] __PROBLEM_TITLE__
|
||||
*
|
||||
* __PROBLEM_DESC__
|
||||
*/
|
||||
pub struct Solution {}__EXTRA_USE__
|
||||
|
||||
// problem: __PROBLEM_LINK__
|
||||
// discuss: __DISCUSS_LINK__
|
||||
|
||||
// submission codes start here
|
||||
|
||||
__PROBLEM_DEFAULT_CODE__
|
||||
|
||||
// submission codes end
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test___PROBLEM_ID__() {
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user