diff --git a/README.md b/README.md index 51db9da..03be5b8 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,20 @@ Each problem dir contains `main.cpp` plus `.in` / `.out` files (USACO fi ``` Creates `solving//main.cpp` from the template and an empty `.in` file, then opens it in `$EDITOR`. `--url` saves the problem link for `open`. +### Start a LeetCode problem +``` +./usaco new https://leetcode.com/problems/two-sum/ # any problem link (also: usaco from ) +./usaco daily # today's daily question +``` +Fetches the problem from LeetCode's API and writes `solving//`: + +- `problem.md`: the statement. `.url`: the link. +- `main.cpp`: the template's header, then LeetCode's C++ starter code (`class Solution { ... }`). Submit it as-is: the local-only parts sit behind `#ifdef LOCAL`. +- `driver.h`: a generated `main()` (LOCAL builds only) that reads `.in` in LeetCode's testcase format (one argument per line, cases back to back), calls your solution, and prints each answer the way LeetCode does. Design problems (`LRUCache` and similar) work too. Parsing/printing lives in `leetcode.h` at the root, which also defines `ListNode` and `TreeNode`. +- `.in` holds every example, so `usaco run` prints all their answers. `tests/N.in` + `N.out` hold one example each, with the expected output from the statement, so `usaco test` checks them. + +Limits: when the statement says "any order", a correct answer in a different order shows as a failure. Problems with their own node types (`Node` in clone-graph) or a custom checker (`remove-element`) get a stub `driver.h` or no expected outputs; the importer says which. Premium problems can't be fetched. `usaco reset` on a LeetCode problem re-fetches the starter code. + **Prefix matching:** everywhere a command takes a problem name, a unique prefix works — `./usaco e diam` finds `diamond-collector` (ambiguous prefixes list the candidates). ### Build & run @@ -116,7 +130,7 @@ Add to `~/.zshrc`: source ~/Coding/USACO/usaco.zsh ``` This gives you: -- `usaco` as a global command (no `./` needed, works from any directory) +- `usaco` as a global command (no `./` needed, works from any directory), with globbing off for its arguments so a pasted `...?envType=...` link works unquoted - tab completion for commands and problem names (`usaco e diam`) - `ucd ` — cd straight into a problem's directory diff --git a/leetcode.h b/leetcode.h new file mode 100644 index 0000000..61e725b --- /dev/null +++ b/leetcode.h @@ -0,0 +1,278 @@ +// leetcode.h - runs a LeetCode solution (class Solution { ... }) locally. +// LeetCode problems' main.cpp includes this under #ifdef LOCAL only: LeetCode +// already defines ListNode/TreeNode itself, so main.cpp stays submittable. +// The per-problem driver.h that 'usaco new ' writes uses the +// helpers below to read LeetCode's testcase format (one JSON-ish argument per +// line) and print answers the way LeetCode's "Output" box shows them. +#pragma once +#include + +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) + : val(x), left(left), right(right) {} +}; + +namespace lc { +using namespace std; + +[[noreturn]] inline void fail(const string &msg) { + cerr << "leetcode.h: " << msg << '\n'; + exit(1); +} + +// ----- PARSING ----- +// A parsed value. Numbers keep their source text so ints, longs and doubles +// all convert exactly. +struct Val { + enum Kind { NUL, BOOL, NUM, STR, ARR } kind = NUL; + string s; // NUM: as written, STR: decoded text, BOOL: "true"/"false" + vector arr; +}; + +struct Parser { + const string &t; + size_t i = 0; + + void ws() { + while (i < t.size() && isspace((unsigned char)t[i])) + i++; + } + void expect(char c) { + ws(); + if (i >= t.size() || t[i] != c) + fail(string("expected '") + c + "' at column " + to_string(i + 1) + + " of: " + t); + i++; + } + bool word(const char *w) { + size_t n = strlen(w); + if (t.compare(i, n, w) != 0) + return false; + i += n; + return true; + } + Val value() { + ws(); + if (i >= t.size()) + fail("unexpected end of line: " + t); + Val v; + if (t[i] == '[') { + v.kind = Val::ARR; + i++; + ws(); + if (i < t.size() && t[i] == ']') + return i++, v; + for (;;) { + v.arr.push_back(value()); + ws(); + if (i < t.size() && t[i] == ',') { + i++; + continue; + } + expect(']'); + return v; + } + } + if (t[i] == '"') { + v.kind = Val::STR; + for (i++; i < t.size() && t[i] != '"'; i++) { + if (t[i] != '\\' || i + 1 >= t.size()) { + v.s += t[i]; + continue; + } + switch (t[++i]) { + case 'n': v.s += '\n'; break; + case 't': v.s += '\t'; break; + case 'u': v.s += (char)stoi(t.substr(i + 1, 4), nullptr, 16), i += 4; break; + default: v.s += t[i]; + } + } + expect('"'); + return v; + } + if (word("null")) + return v; + for (const char *b : {"true", "false"}) + if (word(b)) { + v.kind = Val::BOOL; + v.s = b; + return v; + } + size_t j = i; + while (j < t.size() && (isdigit((unsigned char)t[j]) || strchr("+-.eE", t[j]))) + j++; + if (j == i) + fail("can't read a value at column " + to_string(i + 1) + " of: " + t); + v.kind = Val::NUM; + v.s = t.substr(i, j - i); + i = j; + return v; + } +}; + +inline Val parse_val(const string &line) { + Parser p{line}; + Val v = p.value(); + p.ws(); + if (p.i != line.size()) + fail("unexpected text after the value: " + line); + return v; +} + +template void from(const Val &v, T &x); + +template T as(const Val &v) { + T x{}; + from(v, x); + return x; +} + +template T parse(const string &line) { return as(parse_val(line)); } + +inline void need(const Val &v, Val::Kind k, const char *what) { + if (v.kind != k) + fail(string("expected ") + what + ", got " + + (v.kind == Val::NUL ? "null" : v.kind == Val::ARR ? "an array" : v.s)); +} + +template void from(const Val &v, T &x) { + if constexpr (is_same_v) { + need(v, Val::BOOL, "true/false"); + x = v.s == "true"; + } else if constexpr (is_same_v) { + need(v, Val::STR, "a character"); + x = v.s.empty() ? '\0' : v.s[0]; + } else if constexpr (is_integral_v) { + need(v, Val::NUM, "an integer"); + x = (T)stoll(v.s); + } else if constexpr (is_floating_point_v) { + need(v, Val::NUM, "a number"); + x = (T)stod(v.s); + } else if constexpr (is_same_v) { + need(v, Val::STR, "a string"); + x = v.s; + } else if constexpr (is_same_v) { + need(v, Val::ARR, "a list"); + ListNode head, *tail = &head; + for (auto &e : v.arr) + tail = tail->next = new ListNode(as(e)); + x = head.next; + } else if constexpr (is_same_v) { + // level order with nulls for missing children: [1,null,2,3] + need(v, Val::ARR, "a tree"); + auto &a = v.arr; + x = nullptr; + if (a.empty() || a[0].kind == Val::NUL) + return; + x = new TreeNode(as(a[0])); + queue q; + q.push(x); + for (size_t i = 1; !q.empty() && i < a.size();) { + TreeNode *n = q.front(); + q.pop(); + for (TreeNode **child : {&n->left, &n->right}) { + if (i < a.size() && a[i].kind != Val::NUL) + q.push(*child = new TreeNode(as(a[i]))); + i++; + } + } + } else { // vector<...> + need(v, Val::ARR, "an array"); + x.clear(); + for (auto &e : v.arr) + x.push_back(as(e)); + } +} + +// One test case = k non-blank lines. False at the end of the input. +inline bool read_case(vector &in, size_t k) { + in.clear(); + string line; + while (in.size() < k && getline(cin, line)) + if (line.find_first_not_of(" \t\r") != string::npos) + in.push_back(line); + if (!in.empty() && in.size() < k) + cerr << "leetcode.h: input ended mid-case (got " << in.size() << " of " << k + << " lines)\n"; + return in.size() == k; +} + +// ----- PRINTING ----- +inline string list(const vector &items) { + string r = "["; + for (size_t i = 0; i < items.size(); i++) + r += (i ? "," : "") + items[i]; + return r + "]"; +} + +inline string quote(const string &s) { + string r = "\""; + for (char c : s) { + if (c == '"' || c == '\\') + r += '\\'; + r += c == '\n' ? string("\\n") : string(1, c); + } + return r + "\""; +} + +template string show(const T &x) { + if constexpr (is_same_v) { + return x ? "true" : "false"; + } else if constexpr (is_same_v) { + return quote(string(1, x)); + } else if constexpr (is_integral_v) { + return to_string(x); + } else if constexpr (is_floating_point_v) { + char buf[64]; // LeetCode shows doubles with 5 decimals + snprintf(buf, sizeof buf, "%.5f", (double)x); + return buf; + } else if constexpr (is_same_v) { + return quote(x); + } else if constexpr (is_same_v) { + vector out; + for (ListNode *n = x; n; n = n->next) + if (out.size() > 1000000) + fail("list has over a million nodes -- is there a cycle?"); + else + out.push_back(to_string(n->val)); + return list(out); + } else if constexpr (is_same_v) { + vector out; + queue q; + q.push(x); + while (!q.empty()) { + TreeNode *n = q.front(); + q.pop(); + out.push_back(n ? to_string(n->val) : "null"); + if (n) + q.push(n->left), q.push(n->right); + } + while (!out.empty() && out.back() == "null") + out.pop_back(); + return list(out); + } else { // vector<...> + using E = typename T::value_type; + vector out; + for (auto &&e : x) + out.push_back(show(static_cast(e))); // static_cast: vector + return list(out); + } +} + +template T prefix(const T &v, size_t k) { + return T(v.begin(), v.begin() + min(k, v.size())); +} +} // namespace lc diff --git a/lib/cmd/interactive.sh b/lib/cmd/interactive.sh index 24a626c..1d6d149 100644 --- a/lib/cmd/interactive.sh +++ b/lib/cmd/interactive.sh @@ -70,7 +70,7 @@ ${DIM}selection${RST} ${DIM}problem commands${RST} ${DIM}(name optional — omit it to use the selection; giving one switches to it)${RST} $WITH_PROBLEM ${DIM}other${RST} - $NO_PROBLEM, new + $NO_PROBLEM, new , new help [] this, or the dispatcher's usage line for !cmd run a shell command in the problem dir q quit @@ -135,8 +135,11 @@ while :; do continue ;; none|-) set_current ""; continue ;; n|new) - [[ ${#args[@]} -ge 1 ]] || { echo "usage: n [io-name] [--url ]" >&2; continue; } - if "$ROOT/usaco" new "${args[@]}"; then set_current "${args[0]}"; fi + [[ ${#args[@]} -ge 1 ]] || { echo "usage: n [io-name] [--url ] | n " >&2; continue; } + # new reports the name it created: a LeetCode link only becomes one after the fetch + created="$(mktemp)" + if USACO_CREATED="$created" "$ROOT/usaco" new "${args[@]}"; then set_current "$(<"$created")"; fi + rm -f "$created" continue ;; esac diff --git a/lib/cmd/new.sh b/lib/cmd/new.sh index 3b9e00a..c9d283c 100644 --- a/lib/cmd/new.sh +++ b/lib/cmd/new.sh @@ -1,4 +1,4 @@ -# usaco new [io-name] [--url ] +# usaco new [io-name] [--url ] | usaco new [[ $# -ge 1 ]] || usage name=""; io=""; url="" while [[ $# -gt 0 ]]; do @@ -8,6 +8,17 @@ while [[ $# -gt 0 ]]; do esac done [[ -n "$name" ]] || usage + +# A LeetCode link (or "daily": today's daily question) imports the problem: +# statement, starter code, a generated driver, and the examples as tests. +if [[ "$name" == daily || "$name" =~ ^(https?://)?(www\.)?leetcode\.com/problems/ ]]; then + name="$(python3 -I "$ROOT/lib/leetcode.py" "$ROOT" "$name")" || exit 1 + [[ -n "${USACO_CREATED:-}" ]] && printf '%s\n' "$name" > "$USACO_CREATED" + echo "Created solving/$name (statement in problem.md; 'usaco t $name' runs the examples)" + (cd "$ROOT/solving/$name" && exec ${EDITOR:-nvim} main.cpp) + exit +fi + io="${io:-$name}" dir="$ROOT/solving/$name" if [[ -d "$dir" || -d "$ROOT/solved/$name" || -d "$ROOT/skipped/$name" ]]; then @@ -17,5 +28,6 @@ mkdir -p "$dir" fresh_main "$dir" "$io" touch "$dir/$io.in" [[ -n "$url" ]] && echo "$url" > "$dir/.url" +[[ -n "${USACO_CREATED:-}" ]] && printf '%s\n' "$name" > "$USACO_CREATED" echo "Created solving/$name (io: $io.in / $io.out)" (cd "$dir" && exec ${EDITOR:-nvim} main.cpp) diff --git a/lib/cmd/reset.sh b/lib/cmd/reset.sh index e437e6f..d681e04 100644 --- a/lib/cmd/reset.sh +++ b/lib/cmd/reset.sh @@ -6,12 +6,20 @@ io="$(detect_io "$dir" || true)" io="${io:-$name}" if [[ "${2:-}" != -y ]]; then echo "This resets ${dir#$ROOT/} to a fresh template:" - echo " main.cpp -> re-created from template (old one saved as main.cpp.bak)" + if [[ -f "$dir/driver.h" ]]; then + echo " main.cpp -> LeetCode's starter code again (old one saved as main.cpp.bak)" + else + echo " main.cpp -> re-created from template (old one saved as main.cpp.bak)" + fi echo " removes compiled binary and $io.out (tests/ and $io.in are kept)" read -r -p "Reset '$name'? [y/N] " ans [[ "$ans" == y || "$ans" == Y ]] || { echo "Aborted."; exit 1; } fi [[ -f "$dir/main.cpp" ]] && cp "$dir/main.cpp" "$dir/main.cpp.bak" -fresh_main "$dir" "$io" +if [[ -f "$dir/driver.h" ]]; then # a LeetCode import: re-fetch its starter code + python3 -I "$ROOT/lib/leetcode.py" "$ROOT" "$dir" --main-only >/dev/null || exit 1 +else + fresh_main "$dir" "$io" +fi rm -f "$dir/main" "$dir/a.out" "$dir/$io.out" echo "Reset $name (old solution in main.cpp.bak)" diff --git a/lib/leetcode.py b/lib/leetcode.py new file mode 100644 index 0000000..52360d1 --- /dev/null +++ b/lib/leetcode.py @@ -0,0 +1,477 @@ +"""leetcode.py - import a LeetCode problem into solving//. + +Usage: python3 -I lib/leetcode.py ROOT [--main-only] + +Asks LeetCode's public GraphQL API (the one the problem page uses) for the +problem and writes: + problem.md the statement as markdown, like the website's statement fetch + .url the problem link + main.cpp template.cpp's header + LeetCode's C++ starter code + driver.h a generated main() (LOCAL builds only) that reads .in in + LeetCode's testcase format, calls the solution, and prints + answers the way LeetCode does -- see leetcode.h + .in every example, back to back (what 'usaco run' feeds it) + tests/N.in/out one example each, expected output taken from the statement + +--main-only rewrites just main.cpp in an existing problem dir (usaco reset). +Progress goes to stderr; the problem's name is the only thing on stdout. +""" + +import html +import json +import re +import sys +import urllib.error +import urllib.request +from html.parser import HTMLParser +from pathlib import Path + +API = "https://leetcode.com/graphql" + +QUESTION = """query($s: String!) { question(titleSlug: $s) { + questionFrontendId title titleSlug content isPaidOnly + exampleTestcaseList metaData codeSnippets { langSlug code } } }""" + +DAILY = "query { activeDailyCodingChallengeQuestion { question { titleSlug } } }" + + +def die(msg): + print(f"Error: {msg}", file=sys.stderr) + sys.exit(1) + + +def graphql(query, variables=None): + body = json.dumps({"query": query, "variables": variables or {}}).encode() + req = urllib.request.Request(API, data=body, headers={ + "Content-Type": "application/json", + "Referer": "https://leetcode.com", + "User-Agent": "Mozilla/5.0 (usaco cli)", + }) + try: + with urllib.request.urlopen(req, timeout=15) as resp: + return json.load(resp)["data"] + except urllib.error.HTTPError as e: + die(f"leetcode.com answered {e.code}") + except (urllib.error.URLError, TimeoutError) as e: + die(f"could not reach leetcode.com ({e})") + + +def slug_of(arg): + if arg == "daily": + q = graphql(DAILY)["activeDailyCodingChallengeQuestion"]["question"] + return q["titleSlug"] + # https://leetcode.com/problems//description/?envType=... + m = re.search(r"leetcode\.com/problems/([\w-]+)", arg) + if m: + return m.group(1) + if re.fullmatch(r"[a-z0-9-]+", arg): + return arg + die(f"not a LeetCode problem link: {arg}") + + +# ----- statement ----- + +class Markdown(HTMLParser): + """LeetCode statements use a small slice of HTML; this covers it.""" + + INLINE = {"strong": "**", "b": "**", "em": "*", "i": "*", "code": "`"} + + def __init__(self): + super().__init__(convert_charrefs=True) + self.bufs = [[]] # one buffer per open inline element + self.pre = False + self.lists = [] # [tag, items so far] per open
    /
      + self.href = None + + def out(self, s): + self.bufs[-1].append(s) + + def block(self): + self.out("\n\n") + + def handle_starttag(self, tag, attrs): + a = dict(attrs) + if tag in self.INLINE or tag == "a": + self.bufs.append([]) + if tag == "a": + self.href = a.get("href") + elif tag in ("p", "div"): + self.block() + elif tag == "pre": + self.block() + self.out("```\n") + self.pre = True + elif tag in ("ul", "ol"): + self.block() + self.lists.append([tag, 0]) + elif tag == "li" and self.lists: + self.lists[-1][1] += 1 + kind, n = self.lists[-1] + indent = " " * (len(self.lists) - 1) + self.out(f"\n{indent}" + ("- " if kind == "ul" else f"{n}. ")) + elif tag == "br": + self.out("\n" if self.pre else " \n") + elif tag == "sup": + self.out("^") + elif tag == "img": + self.out(f"![]({a.get('src', '')})") + + def handle_endtag(self, tag): + if (tag in self.INLINE or tag == "a") and len(self.bufs) > 1: + text = "".join(self.bufs.pop()) + core = text.strip() + if tag == "a": + text = text.replace(core, f"[{core}]({self.href})") if core and self.href else text + elif core and not self.pre: + mark = self.INLINE[tag] + # keep surrounding spaces outside the markers: "** x **" isn't bold + text = text.replace(core, f"{mark}{core}{mark}", 1) + self.out(text) + elif tag == "pre": + body = "".join(self.bufs[-1]) + self.bufs[-1][:] = [body.rstrip() + "\n```"] + self.pre = False + self.block() + elif tag in ("ul", "ol") and self.lists: + self.lists.pop() + self.block() + elif tag in ("p", "div"): + self.block() + + def handle_data(self, data): + if not self.pre: + data = re.sub(r"\s+", " ", data) + self.out(data.replace("\xa0", " ")) + + def text(self): + while len(self.bufs) > 1: # unclosed inline tags + self.handle_endtag("code") + md = "".join(self.bufs[0]) + md = "\n".join(line.rstrip() if not line.endswith(" ") else line for line in md.split("\n")) + parts = md.split("```") # even parts: prose, odd parts: code blocks + for i in range(len(parts)): + if i % 2: # no blank first line in a code block + parts[i] = re.sub(r"^\n\n+", "\n", parts[i]) + else: # no stray space starting a line, at most one blank line + parts[i] = re.sub(r"\n{3,}", "\n\n", re.sub(r"\n (?=\S)", "\n", parts[i])) + return "```".join(parts).strip() + + +def to_markdown(content): + p = Markdown() + p.feed(content) + p.close() + return p.text() + + +def plain_text(content): + """The statement with tags stripped, one line per block.""" + text = re.sub(r"<(br|/p|/div|/pre|/li)\b[^>]*>", "\n", content) + text = html.unescape(re.sub(r"<[^>]+>", "", text)).replace("\xa0", " ") + return text + + +def minify(value): + """Drop whitespace outside string literals: '[null, 1]' -> '[null,1]'.""" + out, in_str, esc = [], False, False + for c in value: + if in_str: + out.append(c) + in_str = not (c == '"' and not esc) + esc = c == "\\" and not esc + elif c == '"': + out.append(c) + in_str = True + elif not c.isspace(): + out.append(c) + return "".join(out) + + +def expected_outputs(content): + """Each example's Output, in order. 'Output: x' or 'Output' then x on the next line.""" + lines = plain_text(content).split("\n") + outs = [] + for i, line in enumerate(lines): + m = re.match(r"\s*Output\s*:?\s*(.*)$", line) + if not m: + continue + value = m.group(1).strip() + if not value: + value = next((l.strip() for l in lines[i + 1:] if l.strip()), "") + outs.append(minify(value)) + return outs + + +# ----- C++ signatures ----- + +SUPPORTED = {"int", "long", "longlong", "unsigned", "unsignedint", "double", "float", + "bool", "char", "string", "ListNode*", "TreeNode*"} + + +def strip_comments(code): + return re.sub(r"//[^\n]*", "", re.sub(r"/\*.*?\*/", "", code, flags=re.S)) + + +def clean_type(t): + t = re.sub(r"\bconst\b", "", t).replace("&", "") + t = re.sub(r"\s+", " ", t).strip() + return re.sub(r"\s*([<>*,])\s*", r"\1", t) + + +def supported(t): + return re.sub(r"vector<|>|\s", "", t) in SUPPORTED + + +def split_params(text): + params, depth, cur = [], 0, "" + for c in text: + depth += (c == "<") - (c == ">") + if c == "," and depth == 0: + params.append(cur) + cur = "" + else: + cur += c + if cur.strip(): + params.append(cur) + out = [] + for p in params: + p = p.split("=")[0].strip() + m = re.match(r"(.*?)\b(\w+)$", p, re.S) + out.append((clean_type(m.group(1)), m.group(2))) + return out + + +def signature(code, name): + """(return type, [(type, name)]) of `name(...)` in the starter code, or None.""" + m = re.search(r"(?:^|[;{}:])\s*([^;{}():]*?)\b" + re.escape(name) + r"\s*\(([^()]*)\)", + code, re.M) + if not m: + return None + return clean_type(m.group(1)), split_params(m.group(2)) + + +# ----- driver.h ----- + +DRIVER_HEAD = """\ +// driver.h - generated by 'usaco new' from LeetCode's metadata (edit freely). +// Reads {io}.in in LeetCode's testcase format, cases back to back: +// {what} +// and writes one answer per case to {io}.out, formatted the way LeetCode +// shows its output. Parsing/printing helpers: leetcode.h. +int main() {{ + freopen("{io}.in", "r", stdin); + freopen("{io}.out", "w", stdout); +""" + + +def function_driver(meta, code, io): + name = meta["name"] + sig = signature(code, name) + if not sig: + return None, f"no {name}(...) in the C++ starter code" + ret, params = sig + n_lines = len(meta.get("params", [])) + if len(params) != n_lines: + return None, (f"the testcases have {n_lines} line(s) per case but {name}() " + f"takes {len(params)} argument(s)") + bad = [t for t, _ in params if not supported(t)] + ([ret] if ret != "void" and not supported(ret) else []) + if bad: + return None, f"leetcode.h can't read/print {', '.join(sorted(set(bad)))}" + + s = DRIVER_HEAD.format(io=io, what="one argument per line") + s += f" for (vector in; lc::read_case(in, {n_lines});) {{\n" + for i, (t, n) in enumerate(params): + s += f" auto {n} = lc::parse<{t}>(in[{i}]);\n" + call = f"Solution().{name}({', '.join(n for _, n in params)})" + output = meta.get("output", {}) + idx = output.get("paramindex") + if idx is not None and output.get("size") == "ret": + # "return k, and the first k elements of nums" -- LeetCode checks it specially + arr = params[idx][1] + s += f" auto k = {call};\n" + s += f' cout << k << ", {arr} = " << lc::show(lc::prefix({arr}, k)) << \'\\n\';\n' + elif ret == "void" and idx is not None: + s += f" {call};\n" + s += f" cout << lc::show({params[idx][1]}) << '\\n';\n" + elif ret == "void": + s += f" {call};\n cout << \"null\\n\";\n" + else: + s += f" cout << lc::show({call}) << '\\n';\n" + s += " }\n}\n" + return s, None + + +def design_driver(meta, code, io): + cls = meta["classname"] + ctor = signature(code, cls) + if not ctor: + return None, f"no {cls}(...) constructor in the C++ starter code" + ops = [(cls, None, ctor[1])] + for m in meta.get("methods", []): + sig = signature(code, m["name"]) + if not sig: + return None, f"no {m['name']}(...) in the C++ starter code" + ops.append((m["name"], sig[0], sig[1])) + bad = sorted({t for _, ret, ps in ops for t in [p[0] for p in ps] + ([ret] if ret and ret != "void" else []) + if not supported(t)}) + if bad: + return None, f"leetcode.h can't read/print {', '.join(bad)}" + + s = DRIVER_HEAD.format(io=io, what="a line of operations, then a line of their arguments") + s += " for (vector in; lc::read_case(in, 2);) {\n" + s += " auto ops = lc::parse>(in[0]);\n" + s += " auto args = lc::parse_val(in[1]).arr;\n" + s += f" {cls} *obj = nullptr;\n" + s += " vector out;\n" + # locals rather than inline lc::as<...>() calls: methods often take + # vector&, which can't bind a temporary + s += " for (size_t i = 0; i < ops.size(); i++) {\n" + s += " auto &a = args.at(i).arr;\n" + for k, (op, ret, params) in enumerate(ops): + s += (" if" if k == 0 else " else if") + f' (ops[i] == "{op}") {{\n' + for j, (t, n) in enumerate(params): + s += f" auto {n} = lc::as<{t}>(a.at({j}));\n" + args = ", ".join(n for _, n in params) + if ret is None: + s += f" obj = new {cls}({args});\n out.push_back(\"null\");\n" + elif ret == "void": + s += f" obj->{op}({args});\n out.push_back(\"null\");\n" + else: + s += f" out.push_back(lc::show(obj->{op}({args})));\n" + s += " }" + s += ' else {\n lc::fail("unknown operation " + ops[i]);\n }\n' + s += " }\n cout << lc::list(out) << '\\n';\n }\n}\n" + return s, None + + +def stub_driver(io, reason): + return f"""\ +// driver.h - 'usaco new' couldn't generate a driver for this problem: +// {reason} +// Write main() yourself: read {io}.in, call your solution, print to {io}.out. +// leetcode.h has parse/show helpers for LeetCode's formats. +int main() {{ + freopen("{io}.in", "r", stdin); + freopen("{io}.out", "w", stdout); + cerr << "driver.h: no generated driver ({reason.replace('"', "'")}) -- write main() in driver.h\\n"; + return 1; +}} +""" + + +# ----- main.cpp ----- + +def custom_types(starter): + """Types the starter only defines in a comment, other than leetcode.h's. + + e.g. clone-graph's "/* class Node { ... }; */": LeetCode defines Node itself, + so main.cpp needs its own copy, but only in LOCAL builds. + """ + defs = [] + for block in re.findall(r"/\*(.*?)\*/", starter, re.S): + lines = block.split("\n") + if all(re.match(r"\s*(\*|$)", l) for l in lines[1:]): # " * struct ..." style + lines = [re.sub(r"^\s*\* ?", "", l) for l in lines] + text = "\n".join(lines) + m = re.search(r"^(class|struct)\s+(\w+)", text, re.M) + if m and m.group(2) not in ("ListNode", "TreeNode"): + defs.append(text[m.start():].strip()) + return defs + + +def main_cpp(root, starter): + """template.cpp up to its main(), with leetcode.h added, then the starter code.""" + tpl = (root / "template.cpp").read_text() + head = tpl.split("\nint main() {", 1)[0].rstrip() + "\n" + head = head.replace('#include "debugging.h"\n', + '#include "debugging.h"\n#include "leetcode.h" // ListNode, TreeNode\n', 1) + for d in custom_types(starter): + head += f"\n#ifdef LOCAL // LeetCode defines this itself\n{d}\n#endif\n" + return (f"{head}\n{starter.rstrip()}\n\n" + "#ifdef LOCAL // runs the examples; see driver.h\n" + '#include "driver.h"\n' + "#endif\n") + + +def fetch(slug): + q = graphql(QUESTION, {"s": slug})["question"] + if q is None: + die(f"LeetCode has no problem '{slug}'") + if not q.get("content"): + die(f"LeetCode returned no statement for '{slug}' (a premium problem?)") + return q + + +def cpp_starter(q): + starter = next((s["code"] for s in q["codeSnippets"] or [] if s["langSlug"] == "cpp"), None) + if starter is None: + die("this problem has no C++ starter code") + return starter + + +def main(): + if len(sys.argv) < 3: + die(__doc__.strip().split("\n")[2]) + root = Path(sys.argv[1]) + + if "--main-only" in sys.argv[3:]: + d = Path(sys.argv[2]) + url = (d / ".url").read_text().strip() if (d / ".url").exists() else "" + q = fetch(slug_of(url)) + (d / "main.cpp").write_text(main_cpp(root, cpp_starter(q))) + print(d.name) + return + + slug = slug_of(sys.argv[2]) + for status in ("solving", "solved", "skipped"): + if (root / status / slug).exists(): + die(f"'{slug}' already exists ({status}/{slug})") + q = fetch(slug) + starter = cpp_starter(q) + meta = json.loads(q["metaData"]) + io = slug + + code = strip_comments(starter) + if meta.get("systemdesign") or "classname" in meta: + driver, why = design_driver(meta, code, io) + else: + driver, why = function_driver(meta, code, io) + if driver is None: + driver = stub_driver(io, why) + + cases = [c.strip() + "\n" for c in q["exampleTestcaseList"] or []] + outs = expected_outputs(q["content"]) + if meta.get("output", {}).get("size") == "ret": + outs, out_note = [], "the answer is checked specially on LeetCode, so no expected outputs" + elif len(outs) != len(cases): + out_note = f"found {len(outs)} Output(s) for {len(cases)} example(s), so no expected outputs" + outs = [] + else: + out_note = None + + d = root / "solving" / slug + (d / "tests").mkdir(parents=True) + title = f"{q['questionFrontendId']}. {q['title']}" + (d / "problem.md").write_text(f"# {title}\n\n{to_markdown(q['content'])}\n") + (d / ".url").write_text(f"https://leetcode.com/problems/{slug}/\n") + (d / "main.cpp").write_text(main_cpp(root, starter)) + (d / "driver.h").write_text(driver) + (d / f"{io}.in").write_text("".join(cases)) + for n, case in enumerate(cases, 1): + (d / "tests" / f"{n}.in").write_text(case) + if outs: + (d / "tests" / f"{n}.out").write_text(outs[n - 1] + "\n") + if not cases: + (d / "tests").rmdir() + + print(f"Fetched {title}: {len(cases)} example(s)" + + (f" with expected outputs" if outs else ""), file=sys.stderr) + if out_note: + print(f"note: {out_note}", file=sys.stderr) + if why: + print(f"note: no driver generated ({why}); write main() in driver.h", file=sys.stderr) + print(slug) + + +if __name__ == "__main__": + main() diff --git a/site/web/src/views/CliPage.vue b/site/web/src/views/CliPage.vue index 65936a7..25e1ce7 100644 --- a/site/web/src/views/CliPage.vue +++ b/site/web/src/views/CliPage.vue @@ -19,6 +19,8 @@ const sections = [ ["usaco new ", "Create solving// with main.cpp from the template and an empty .in file, then open it in $EDITOR."], ["usaco new ", "Same, when the USACO file name differs from the problem name."], ["usaco new --url ", "Also save the problem link, for usaco open."], + ["usaco new ", "Import a LeetCode problem (also usaco from): the statement as problem.md, LeetCode's C++ starter code in main.cpp, a generated driver.h that runs it on LeetCode-format input, and the examples as tests with their expected outputs."], + ["usaco daily", "The same, for today's LeetCode daily question."], ], }, { diff --git a/usaco b/usaco index 5098f30..e3c83e7 100755 --- a/usaco +++ b/usaco @@ -12,6 +12,10 @@ # usaco new [io-name] [--url ] # Create solving/ from template.cpp # (io-name sets freopen filenames, defaults to ) +# usaco new Import a LeetCode problem (alias: from): statement in +# problem.md, C++ starter + generated driver.h, the examples +# as tests/ with expected outputs +# usaco daily Same, for today's LeetCode daily question # usaco run Build main.cpp and run it (in the problem dir) # usaco build Build main.cpp only # usaco done Move solving/ -> solved/ and git commit @@ -52,7 +56,8 @@ usage() { awk 'NR>1 { if (!/^#/) exit; sub(/^# ?/,""); print }' "$0"; exit 1; } cmd="${1:-}"; shift || true case "$cmd" in interactive|i|repl) cmd=interactive ;; - new|n) cmd=new ;; + new|n|from) cmd=new ;; + daily) cmd=new; set -- daily "$@" ;; run|r) cmd=run ;; build|b) cmd=build ;; test|t) cmd=test ;; diff --git a/usaco.zsh b/usaco.zsh index 9b218d3..01c001c 100644 --- a/usaco.zsh +++ b/usaco.zsh @@ -8,6 +8,9 @@ USACO_ROOT="${0:A:h}" usaco() { "$USACO_ROOT/usaco" "$@"; } +# no globbing on usaco's arguments, so a pasted link like .../two-sum/?envType=x +# isn't a "no matches found" error (nothing usaco takes is a glob anyway) +alias usaco='noglob usaco' ucd() { local dir @@ -29,6 +32,8 @@ _usaco() { 'repl:interactive mode (REPL with a current problem)' 'new:create a problem from template' 'n:create a problem from template' + 'from:import a LeetCode problem from its link' + "daily:import today's LeetCode daily question" 'run:build and run main.cpp' 'r:build and run main.cpp' 'build:build main.cpp' @@ -70,7 +75,7 @@ _usaco() { _describe 'command' cmds elif (( CURRENT == 3 )); then case "$words[2]" in - i|interactive|repl|new|n|list|l|ls|stats|st|clean|sync|sy) ;; # no problem-name argument + i|interactive|repl|new|n|from|daily|list|l|ls|stats|st|clean|sync|sy) ;; # no problem-name argument test|t) local -a subs subs=('create:save a new test case' 'add:save a new test case' 'new:save a new test case')