content: update content
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped

This commit is contained in:
2026-01-11 18:15:22 +08:00
parent 8ee00c8767
commit db3a26f53b
3 changed files with 209 additions and 350 deletions

View File

@@ -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<Unit> {
value: i32,
unit: PhantomData<Unit>,
}
impl<U> Duration<U> {
fn new(value: i32) -> Duration<U> {
Duration {
value: value,
unit: PhantomData
}
}
}
impl<U> Display for Duration<U> {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(
f,
"{} {}",
self.value, type_name::<U>(),
)
}
}
fn print_second(sec: Duration<Sec>) {
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::<Min>::new(10);
// compile time error! type mismatch
// print_second(duration_min);
}
```

9
rust_code/test.rs Normal file
View File

@@ -0,0 +1,9 @@
use std::io;
fn main() {
let mut test = 1;
}
fn call_function<CbFunc: Fn(i32)>(func: CbFunc, data: i32) {
func(data);
}

498
test.cpp
View File

@@ -1,373 +1,183 @@
#include <algorithm> // https://leetcode.com/problems/last-day-where-you-can-still-cross
#include <format>
#include <iostream> #include <iostream>
#include <numeric> #include <format>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <vector> #include <vector>
using std::cout, std::endl; using std::cout, std::endl;
using std::format; using std::format;
using std::vector, std::string; using std::vector;
bool debug = false; const bool debug = true;
/** class UnionFind2D
* 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
{ {
char top; private: // private class
char left; class UnionFindNode
char right;
// 123123
Pattern(const string &data)
{ {
top = data[2]; public:
left = data[0]; // record the rank of this node
right = data[1]; 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) // if an idx is valid as a position pointer
: top(top), left(left), right(right) {} bool validRange(short idx)
bool operator==(const Pattern &other) const
{ {
return top == other.top && left == other.left && right == other.right; if (idx < 1 || idx > mCount)
}
size_t hash() const
{
return std::hash<char>()(top) + std::hash<char>()(left) +
std::hash<char>()(right);
}
};
struct PatternHash
{
size_t operator()(const Pattern &p) const { return p.hash(); }
};
class PatternManager
{
private:
std::unordered_set<Pattern, PatternHash> 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'])
{ {
return false; 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(); // validate range
for (int i = 0; i < 6; ++i) bool allValid = validRange(r1) && validRange(c1) && validRange(r2) && validRange(c2);
{
for (int j = 0; j < 6; ++j)
{
mPairs[i][j] = 0;
}
}
}
};
// global variables if (!allValid)
// 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<string, bool> 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<string> &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')
{ {
return; return;
} }
// search not begin // get nodes
if (curChar() == '0') UnionFindNode &n1 = getRoot(r1, c1);
UnionFindNode &n2 = getRoot(r2, c2);
// merge nodes
if (n1.rank > n2.rank)
{ {
curChar() = 'A'; n2.mergeTo(n1, r1, c1);
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;
} }
else else
{ {
curChar() = '0'; n1.mergeTo(n2, r2, c2);
} }
return;
} }
public: public: // public method
void search() 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(); curNode.valid = 1;
if (debug) 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 class Solution
{ {
public: public:
bool pyramidTransition(string bottom, vector<string> &allowed) int latestDayToCross(int row, int col, vector<vector<int>> &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;
} }
}; };