From db3a26f53b5b64106bee88086b9007586d8d4262 Mon Sep 17 00:00:00 2001 From: Oyasumi Gitea Date: Sun, 11 Jan 2026 18:15:22 +0800 Subject: [PATCH] content: update content --- content/Learn Rust/Phantom Data.md | 52 +++ rust_code/test.rs | 9 + test.cpp | 498 +++++++++-------------------- 3 files changed, 209 insertions(+), 350 deletions(-) create mode 100644 content/Learn Rust/Phantom Data.md create mode 100644 rust_code/test.rs diff --git a/content/Learn Rust/Phantom Data.md b/content/Learn Rust/Phantom Data.md new file mode 100644 index 0000000..49df42a --- /dev/null +++ b/content/Learn Rust/Phantom Data.md @@ -0,0 +1,52 @@ + +Official docs about [Phantom Type & Data](https://doc.rust-lang.org/rust-by-example/generics/phantom/testcase_units.html) +# Example + +```rust +#![allow(unused)] + +use std::marker::PhantomData; +use std::fmt::{Display, Formatter, Result}; +use std::any::type_name; + +enum Sec {} +enum Min {} + +struct Duration { + value: i32, + unit: PhantomData, +} + +impl Duration { + fn new(value: i32) -> Duration { + Duration { + value: value, + unit: PhantomData + } + } +} + +impl Display for Duration { + fn fmt(&self, f: &mut Formatter) -> Result { + write!( + f, + "{} {}", + self.value, type_name::(), + ) + } +} + +fn print_second(sec: Duration) { + println!("Printed: {}", sec); +} + +fn main() { + // ok, rust compiler will imply that + // Duration::new(1) is with unit sec + print_second(Duration::new(1)); + + let duration_min = Duration::::new(10); + // compile time error! type mismatch + // print_second(duration_min); +} +``` diff --git a/rust_code/test.rs b/rust_code/test.rs new file mode 100644 index 0000000..f1e4787 --- /dev/null +++ b/rust_code/test.rs @@ -0,0 +1,9 @@ +use std::io; + +fn main() { + let mut test = 1; +} + +fn call_function(func: CbFunc, data: i32) { + func(data); +} diff --git a/test.cpp b/test.cpp index e9a726a..af4d108 100644 --- a/test.cpp +++ b/test.cpp @@ -1,373 +1,183 @@ -#include -#include +// https://leetcode.com/problems/last-day-where-you-can-still-cross + #include -#include -#include -#include -#include +#include #include using std::cout, std::endl; using std::format; -using std::vector, std::string; +using std::vector; -bool debug = false; +const bool debug = true; -/** - * Data structure to store pattern in question - * - * Init: - * - Use 3-char string to init (based on questoni definition) - * - Use three different char parameter to init - * - * Method: - * - Equal comparator - * - hash() function - */ -struct Pattern +class UnionFind2D { - char top; - char left; - char right; - // 123123 - Pattern(const string &data) +private: // private class + class UnionFindNode { - top = data[2]; - left = data[0]; - right = data[1]; + public: + // record the rank of this node + int rank = 0; + + // row, col work together as the parent pointer of this node + short row = 0; + short col = 0; + + // special metadata for this node + bool valid = false; + bool top = false; + bool bottom = false; + + bool isRoot() + { + return valid && (col == 0); + } + + // merge this node to another node + // need to provide parent and its position + // will skip if parent is not valid + void mergeTo(UnionFindNode &parent, short r, short c) + { + // validate + if (!isRoot() || !parent.isRoot()) + { + return; + } + + // update pointer, pointing to parent + row = r; + col = c; + + // update parent rank + parent.rank += rank; + + // update parent metadata + if (top) + { + parent.top = 1; + } + if (bottom) + { + parent.bottom = 1; + } + } + }; + +private: // private variables + // mCount * mCount represents the total size + int mCount = 0; + UnionFindNode mNodes[20010][20010]; + +private: // private methods + /** + * Get root node of a position + * + * Return invalid node if original node invalid, + * else, return root node + */ + UnionFindNode &getRoot(short r1, short c1) + { + UnionFindNode &curNode = mNodes[r1][c1]; + + if (!curNode.valid) + { + return curNode; + } + + while (!curNode.isRoot()) + { + curNode = mNodes[curNode.row][curNode.col]; + } + + return curNode; } - Pattern(char top, char left, char right) - : top(top), left(left), right(right) {} - - bool operator==(const Pattern &other) const + // if an idx is valid as a position pointer + bool validRange(short idx) { - return top == other.top && left == other.left && right == other.right; - } - - size_t hash() const - { - return std::hash()(top) + std::hash()(left) + - std::hash()(right); - } -}; - -struct PatternHash -{ - size_t operator()(const Pattern &p) const { return p.hash(); } -}; - -class PatternManager -{ -private: - std::unordered_set mPatterns; - bool mPairs[6][6]; - -public: - PatternManager() - { - clear(); - } - - void add(const Pattern &p) - { - mPatterns.insert(p); - mPairs[p.left - 'A'][p.right - 'A'] = 1; - } - - bool exists(const Pattern &p) - { - if (!mPairs[p.left - 'A'][p.right - 'A']) + if (idx < 1 || idx > mCount) { return false; } - return mPatterns.find(p) != mPatterns.end(); + return true; } - void clear() + /** + * Connect r1, c1 to r2, c2 + * Ignore if one of those are not exists + */ + void connect(short r1, short c1, short r2, short c2) { - mPatterns.clear(); - for (int i = 0; i < 6; ++i) - { - for (int j = 0; j < 6; ++j) - { - mPairs[i][j] = 0; - } - } - } -}; + // validate range + bool allValid = validRange(r1) && validRange(c1) && validRange(r2) && validRange(c2); -// global variables -// statistics -unsigned bottomSize = 0; -string bottomString; -char pyramid[6][6]; // 0: not searched, A-F: searching, 1: finished -PatternManager pMgr; -// search temp -unsigned curR, curC; -bool found, finished; - -class AnswerCache -{ -private: - std::unordered_map mAllowedBottomcache; - unsigned long long cacheHit, cacheWrite, cacheRead; - -private: - string wholeRowToString(unsigned rowIdx) - { - string s = ""; - for (int i = 0; i <= rowIdx; ++i) - { - s.push_back(pyramid[rowIdx][i]); - } - - return s; - } - -public: - AnswerCache() {} - - void setCache() - { - mAllowedBottomcache[wholeRowToString(curR)] = false; - } - - // false: not in cache, true: hit - int getCache(int rowIdx) - { - ++cacheRead; - string rowStr = wholeRowToString(rowIdx); - return mAllowedBottomcache.contains(rowStr); - } - - void showCacheStatus() - { - cout << format("cache R/W: {}/{}, cache hit:{}\n", cacheRead, cacheWrite, cacheHit); - } - - void clear() - { - mAllowedBottomcache.clear(); - cacheHit = 0; - cacheRead = 0; - cacheWrite = 0; - } -}; - -AnswerCache ansCache; - -class Initializer -{ -public: - // init variables and clear mMgr - void initVariables() - { - // init temp - curR = bottomSize - 2; - curC = bottomSize - 2; - found = 0; - finished = 0; - - // clear manager - pMgr.clear(); - - // clear answer cache - ansCache.clear(); - - // init pyramid - for (int i = 0; i < 6; ++i) - { - for (int j = 0; j < 6; ++j) - { - pyramid[i][j] = '0'; - } - } - } - - // init bottomString and the pyramid array - void initPyramidBottom(const string &data) - { - bottomString = data; - - for (int i = 0; i < bottomSize; ++i) - { - pyramid[bottomSize - 1][i] = data[i]; - } - } - - // fill data to mMgr - void initPattern(const vector &allowed) - { - for (const auto &s : allowed) - { - pMgr.add(Pattern(s)); - } - } -}; - -class Searcher -{ -private: - bool deltaSearchpointer(bool forward) - { - // forward - if (forward) - { - if (curR <= 0 && curC <= 0) - { - return false; - } - - if (curC > 0) - { - --curC; - } - else - { - --curR; - curC = curR; - } - return true; - } - // backward - else - { - if (curC >= bottomSize - 2 && curR >= bottomSize - 2) - { - return false; - } - - if (curC < curR) - { - ++curC; - } - else - { - ++curR; - curC = 0; - } - return true; - } - } - - char &curChar() { return pyramid[curR][curC]; } - - char &leftChar() { return pyramid[curR + 1][curC]; } - - char &rightChar() { return pyramid[curR + 1][curC + 1]; } - - bool atTop() { return curR == curC && curC == 0; } - - bool curValid() - { - return pMgr.exists(Pattern(curChar(), leftChar(), rightChar())); - } - - void setToNextPossibleChar() - { - bool firstMove = (curChar() == '0'); - - // search end - if (curChar() == '1') + if (!allValid) { return; } - // search not begin - if (curChar() == '0') + // get nodes + UnionFindNode &n1 = getRoot(r1, c1); + UnionFindNode &n2 = getRoot(r2, c2); + + // merge nodes + if (n1.rank > n2.rank) { - curChar() = 'A'; - if (curValid()) - { - return; - } - } - - ++curChar(); - - while (curChar() <= 'F' && !curValid()) - { - ++curChar(); - } - - if (curChar() > 'F') - { - curChar() = '1'; - } - } - - void _search() - { - if (debug) - { - cout << "enter _search()" << endl; - } - - // already found answer - if (found || finished) - { - cout << "found or finished" << endl; - return; - } - - // try use cache to check if we could skip current layer - // before we are about to start a new upper layer - if (curC == curR && curChar() == '0') - { - if (ansCache.getCache(curR + 1)) - { - deltaSearchpointer(0); - return; - } - } - - setToNextPossibleChar(); - - bool isDelta; - - // this position finished - if (curChar() == '1') - { - isDelta = deltaSearchpointer(0); - - // finished - if (!isDelta) - { - finished = 1; - } - - // back to lower layer - if (curC == 0) - { - // remember this layer of pattern doesn't work - ansCache.setCache(); - } - return; - } - - // this position not finish searching - isDelta = deltaSearchpointer(1); - if (!isDelta) - { - found = 1; + n2.mergeTo(n1, r1, c1); } else { - curChar() = '0'; + n1.mergeTo(n2, r2, c2); } - return; } -public: - void search() +public: // public method + UnionFind2D(int count) : mCount(count) { - while (!found && !finished) + clear(count); + } + + /** + * Mark a position as land, then connect it to other land block around if exists + * Note: r, c should be 1-indexed + */ + void add(int r, int c) + { + UnionFindNode &curNode = mNodes[r][c]; + + // create new node and init data if not added before (invalid) + if (!curNode.valid) { - _search(); - if (debug) + curNode.valid = 1; + curNode.rank = 1; + + if (r == 1) { - cout << format("found={}, finished={}\n", found, finished); + curNode.top = 1; + } + if (r == mCount) + { + curNode.bottom = 1; + } + } + + // connect to nodes around + connect(r, c, r, c + 1); + connect(r, c, r, c - 1); + connect(r, c, r + 1, c); + connect(r, c, r - 1, c); + } + + void clear(int mCount) + { + mCount = mCount; + + // note: better init method? + for (int i = 0; i < mCount; ++i) + { + for (int j = 0; j < mCount; ++j) + { + mNodes[i][j] = UnionFindNode(); } } } @@ -376,19 +186,7 @@ public: class Solution { public: - bool pyramidTransition(string bottom, vector &allowed) + int latestDayToCross(int row, int col, vector> &cells) { - // initialization - bottomSize = bottom.size(); - auto initer = Initializer(); - initer.initVariables(); - initer.initPyramidBottom(bottom); - initer.initPattern(allowed); - - // search the answer - auto searcher = Searcher(); - searcher.search(); - ansCache.showCacheStatus(); - return found; } }; \ No newline at end of file