Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
MikuroXina / union_find.rs
Last active November 5, 2023 07:22
The implementation of Union Find.
/// It represents index of parent if positive, otherwise size of tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct UnionFindIndex(isize);
impl UnionFindIndex {
fn new(index: usize) -> Self {
debug_assert!(index < (isize::MAX as usize));
Self(index as isize)
}
@MikuroXina
MikuroXina / sieve.rs
Last active September 19, 2021 08:59
The implementation of Sieve of Eratosthenes.
use std::collections::HashMap;
fn sieve(max: usize) -> (Vec<usize>, HashMap<usize, usize>) {
let mut found_primes = vec![];
let mut found_least_factor = HashMap::with_capacity(max + 1);
for n in 2..=max {
let factor = *found_least_factor.entry(n).or_insert_with(|| {
found_primes.push(n);
n
});
let alpha_num_pat = RegExp::pat()
.with_alphabetic()
.with_numeric();
let email_user_chars = RegExp::new().one_of(RegExp::pat().add(
"!#$%&'*+/=?^_`{|}~-"
).with_alphabetic().with_numeric());
let email_num_chars = RegExp::new().or(
RegExp::new().text("25").one_of(RegExp::pat().add('0'..='5')),
RegExp::new().or(
RegExp::new()
@MikuroXina
MikuroXina / lca.rs
Last active December 6, 2021 01:02
The implementation of querying Lowest Common Ancestor.
use std::num::NonZeroUsize;
/// Calculates the lowest common ancestor on given graph.
#[derive(Debug)]
pub struct LowestCommonAncestor {
parents_by_step: Vec<Vec<Option<NonZeroUsize>>>,
distances: Vec<usize>,
}
impl LowestCommonAncestor {
@MikuroXina
MikuroXina / inv_sqrt.rs
Last active July 30, 2022 16:17
Calculates the inverse of square root quickly.
/// Calculates the inverse of square root quickly.
fn inv_sqrt(x: f64) -> f64 {
// x must be positive.
assert!(x.is_sign_positive());
// mu := 0.045
// log(x) ≒ x + mu
// log(a) := log(1 / √x) = - 1/2 log(x)
// 1/2^52 (a_man + 2^52 * a_exp) - 1023 + mu
// = - 1/2 (1/2^52 (x_man + 2^52 * x_exp) - 1023 + mu)
@MikuroXina
MikuroXina / ani2ico.rs
Last active October 26, 2022 12:13
The decomposer, converting the ani file to ico files.
use std::{env, fs, io::Write, path::PathBuf};
const ICON_MAGIC: &[u8] = b"icon";
fn next_partition(buf: &[u8]) -> Option<usize> {
buf.windows(ICON_MAGIC.len())
.position(|win| win == ICON_MAGIC)
}
fn hoge() -> Result<(), Box<dyn std::error::Error + 'static>> {
@MikuroXina
MikuroXina / binary_search.rs
Last active September 9, 2022 12:58
Binary-search with given function in Rust.
use std::cmp::Ordering;
pub fn binary_search(max: usize, mut f: impl FnMut(usize) -> Ordering) -> Result<usize, usize> {
let mut left = 0;
let mut right = max;
while left < right {
let mid = left + (right - left) / 2;
match f(mid) {
Ordering::Less => left = mid + 1,
Ordering::Greater => right = mid - 1,
@MikuroXina
MikuroXina / extract-env.ts
Last active July 27, 2022 14:55
Extraction of environmental variables for Node.js.
/// 必要な環境変数名を可変長引数に渡すと, 環境変数ごとに対応した値が入ったオブジェクトを返す.
///
/// 対応した環境変数が定義されていない場合は `defaults` に設定した値へとフォールバックする.
///
/// # 例外
///
/// 対応した環境変数が定義されておらず `defaults` にも存在しない場合は例外を送出する.
///
/// # 使用例
///
@MikuroXina
MikuroXina / divisors.rs
Created April 24, 2022 06:01
Divisors enumerator
pub fn divisors(with: u64) -> Vec<u64> {
assert_ne!(with, 0, "cannot find divisors with 0");
let at_most = ((with as f64).sqrt() * 2.0).floor() as usize;
let mut divs = Vec::with_capacity(at_most);
for i in (1..)
.filter(|&i| with % i == 0)
.take_while(|&i| i * i <= with)
{
divs.push(i);
if i * i != with {
@MikuroXina
MikuroXina / multi-curry.ts
Last active July 11, 2022 02:35
Currying manipulation for N-ary function.
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;
type Curried<F> = F extends (...args: infer A) => infer R
? Equal<F, () => R> extends true
? () => R
: (A extends [infer F, ...infer S]
? (arg: F) => Curried<(...rest: S) => R>
: R
)
: never;