content: update content
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped
This commit is contained in:
52
content/Learn Rust/Phantom Data.md
Normal file
52
content/Learn Rust/Phantom Data.md
Normal 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
9
rust_code/test.rs
Normal 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);
|
||||
}
|
||||
488
test.cpp
488
test.cpp
@@ -1,373 +1,183 @@
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
// https://leetcode.com/problems/last-day-where-you-can-still-cross
|
||||
|
||||
#include <iostream>
|
||||
#include <numeric>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <unordered_map>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
using std::cout, std::endl;
|
||||
using std::format;
|
||||
using std::vector, std::string;
|
||||
using std::vector;
|
||||
|
||||
bool debug = false;
|
||||
const bool debug = true;
|
||||
|
||||
class UnionFind2D
|
||||
{
|
||||
private: // private class
|
||||
class UnionFindNode
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
// if an idx is valid as a position pointer
|
||||
bool validRange(short idx)
|
||||
{
|
||||
if (idx < 1 || idx > mCount)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return 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
|
||||
* Connect r1, c1 to r2, c2
|
||||
* Ignore if one of those are not exists
|
||||
*/
|
||||
struct Pattern
|
||||
void connect(short r1, short c1, short r2, short c2)
|
||||
{
|
||||
char top;
|
||||
char left;
|
||||
char right;
|
||||
// 123123
|
||||
Pattern(const string &data)
|
||||
// validate range
|
||||
bool allValid = validRange(r1) && validRange(c1) && validRange(r2) && validRange(c2);
|
||||
|
||||
if (!allValid)
|
||||
{
|
||||
top = data[2];
|
||||
left = data[0];
|
||||
right = data[1];
|
||||
return;
|
||||
}
|
||||
|
||||
Pattern(char top, char left, char right)
|
||||
: top(top), left(left), right(right) {}
|
||||
// get nodes
|
||||
UnionFindNode &n1 = getRoot(r1, c1);
|
||||
UnionFindNode &n2 = getRoot(r2, c2);
|
||||
|
||||
bool operator==(const Pattern &other) const
|
||||
// merge nodes
|
||||
if (n1.rank > n2.rank)
|
||||
{
|
||||
return top == other.top && left == other.left && right == other.right;
|
||||
}
|
||||
|
||||
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 mPatterns.find(p) != mPatterns.end();
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
mPatterns.clear();
|
||||
for (int i = 0; i < 6; ++i)
|
||||
{
|
||||
for (int j = 0; j < 6; ++j)
|
||||
{
|
||||
mPairs[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 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<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;
|
||||
n2.mergeTo(n1, r1, c1);
|
||||
}
|
||||
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;
|
||||
n1.mergeTo(n2, r2, c2);
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
public: // public method
|
||||
UnionFind2D(int count) : mCount(count)
|
||||
{
|
||||
return pMgr.exists(Pattern(curChar(), leftChar(), rightChar()));
|
||||
clear(count);
|
||||
}
|
||||
|
||||
void setToNextPossibleChar()
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
bool firstMove = (curChar() == '0');
|
||||
UnionFindNode &curNode = mNodes[r][c];
|
||||
|
||||
// search end
|
||||
if (curChar() == '1')
|
||||
// create new node and init data if not added before (invalid)
|
||||
if (!curNode.valid)
|
||||
{
|
||||
return;
|
||||
curNode.valid = 1;
|
||||
curNode.rank = 1;
|
||||
|
||||
if (r == 1)
|
||||
{
|
||||
curNode.top = 1;
|
||||
}
|
||||
|
||||
// search not begin
|
||||
if (curChar() == '0')
|
||||
if (r == mCount)
|
||||
{
|
||||
curChar() = 'A';
|
||||
if (curValid())
|
||||
{
|
||||
return;
|
||||
curNode.bottom = 1;
|
||||
}
|
||||
}
|
||||
|
||||
++curChar();
|
||||
|
||||
while (curChar() <= 'F' && !curValid())
|
||||
{
|
||||
++curChar();
|
||||
// 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);
|
||||
}
|
||||
|
||||
if (curChar() > 'F')
|
||||
void clear(int mCount)
|
||||
{
|
||||
curChar() = '1';
|
||||
}
|
||||
}
|
||||
mCount = mCount;
|
||||
|
||||
void _search()
|
||||
// note: better init method?
|
||||
for (int i = 0; i < mCount; ++i)
|
||||
{
|
||||
if (debug)
|
||||
for (int j = 0; j < mCount; ++j)
|
||||
{
|
||||
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
|
||||
{
|
||||
curChar() = '0';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
public:
|
||||
void search()
|
||||
{
|
||||
while (!found && !finished)
|
||||
{
|
||||
_search();
|
||||
if (debug)
|
||||
{
|
||||
cout << format("found={}, finished={}\n", found, finished);
|
||||
mNodes[i][j] = UnionFindNode();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -376,19 +186,7 @@ public:
|
||||
class Solution
|
||||
{
|
||||
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;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user