Skip to content

Instantly share code, notes, and snippets.

@AnthonyMikh
AnthonyMikh / variant1.rs
Created May 23, 2020 13:31
Solution to "Interval List Intersections" Leetcode problem
impl Solution {
pub fn interval_intersection(a: Vec<Vec<i32>>, b: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let mut state = State::default();
let mut events = merge_sorted_intervals(intervals(&a), intervals(&b))
.filter_map(|event| state.accept(event));
let mut ret = Vec::new();
while let (Some(start), Some(end)) = (events.next(), events.next()) {
ret.push(vec![start, end]);
}
@AnthonyMikh
AnthonyMikh / lib.rs
Created May 17, 2020 11:20
Solution to "Odd Even Linked List" Leetcode problem
impl Solution {
pub fn odd_even_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut first = head?;
let mut second = match first.next.take() {
Some(node) => node,
None => return Some(first),
};
let mut odd = &mut *first;
let mut even = &mut *second;
while let Some(next_odd) = pluck_second(even) {
@AnthonyMikh
AnthonyMikh / main.rs
Created May 14, 2020 14:25
Solution to "Implement Trie (Prefix Tree)" Leetcode problem
#[derive(Default)]
struct AlphabetMap {
values: [usize; Self::LEN],
flags: u32,
}
impl AlphabetMap {
const LEN: usize = (b'z' - b'a' + 1) as usize;
fn get(&self, idx: u8) -> Option<usize> {
@AnthonyMikh
AnthonyMikh / lib.rs
Created May 9, 2020 15:28
Решение задачи №220 от UniLecs (Маска файла)
#[derive(Debug)]
enum MaskPart<'a> {
Wildcard,
String(&'a str),
}
impl<'a> MaskPart<'a> {
fn parse(mut mask: &'a str) -> impl Iterator<Item = MaskPart<'a>> + 'a {
std::iter::from_fn(move || {
if mask.is_empty() {
@AnthonyMikh
AnthonyMikh / lib.rs
Created May 3, 2020 18:18
Solution to "Data Stream as Disjoint Intervals" Leetcode problem
use std::cell::Cell;
use std::collections::BTreeMap;
struct SummaryRanges {
ranges: BTreeMap<Cell<i32>, i32>,
}
impl SummaryRanges {
fn new() -> Self {
Self { ranges: BTreeMap::new() }
@AnthonyMikh
AnthonyMikh / main.rs
Created May 3, 2020 17:02
Решение задачи с Хабра от @Milein: найти максимальное количество идущих подряд символов для каждого сивола строки
fn cut_repeating_prefix(source: &str) -> Option<(char, usize, &str)> {
let mut chars = source.char_indices();
let first = chars.next()?.1;
let len = chars
.find_map(|(i, ch)| if ch != first { Some(i) } else { None })
.unwrap_or(source.len());
let count = len / first.len_utf8();
let (_pre, post) = source.split_at(len);
Some((first, count, post))
}
@AnthonyMikh
AnthonyMikh / lib.rs
Created April 28, 2020 16:26
Solution to "First unique number" problem on Leetcode
use std::collections::{HashMap, HashSet, BTreeMap};
use std::hash::{Hasher, BuildHasherDefault};
struct FirstUnique {
positions: HashMap<i32, usize, BuildHasherDefault<IdentityHasher>>,
uniqs: BTreeMap<usize, i32>,
new_idx: usize,
}
impl FirstUnique {
@AnthonyMikh
AnthonyMikh / main.rs
Created April 15, 2020 12:53
Extension trait which enables version of `or_insert_with` of Entry API which has access to key stored in entry
// This code is public domain
trait EntryExt<'a, K, V> {
fn or_insert_with_key<F>(self, f: F) -> &'a mut V
where
F: FnOnce(&K) -> V;
}
use std::collections::{btree_map, hash_map};
@AnthonyMikh
AnthonyMikh / main.rs
Created March 9, 2020 19:25
The queens puzzle in Rust
const SIZE: usize = 8;
type Positions = [u8; SIZE];
fn is_valid_for(positions: &Positions, col: usize) -> bool {
let pre = positions[..col].iter().cloned();
let pos = positions[col];
pre.clone().all(|p| p != pos)
&& pre.clone().rev().zip((0..pos).rev()).all(|(a, b)| a != b)
&& pre.rev().zip(pos + 1..).all(|(a, b)| a != b)
@AnthonyMikh
AnthonyMikh / main.rs
Created March 1, 2020 20:38
type suffering take with lowering
pub mod field {
pub trait Field {
type Type;
}
macro_rules! make_field {
($name:ident: $ty:ty) => {
pub struct $name;
impl Field for $name {
type Type = $ty;