Skip to content

Instantly share code, notes, and snippets.

View fancellu's full-sized avatar

Dino Fancellu fancellu

View GitHub Profile
@fancellu
fancellu / rascii_demo.rs
Created February 12, 2024 19:23
Rust demo of rasciigraph, which plots simple ascii graphs, quite nice
use rand::Rng;
use rasciigraph::{plot, Config};
fn main() {
let vec = (0..70)
.map(|_| rand::thread_rng().gen::<f64>() * 13.0 - 3.0)
.collect::<Vec<_>>();
let plot = plot(
vec,
@fancellu
fancellu / flexi_data_parse.rs
Created February 9, 2024 22:31
Rust code to parse dates flexibly with several formats
use chrono::prelude::*;
fn flexi_data_parse(text: &str) -> Option<NaiveDate> {
let text = text.replace(['.', '/'], "-");
let fmts = ["%Y-%m-%d", "%Y-%b-%d", "%d-%b-%Y", "%b-%d-%Y", "%d-%m-%Y"];
for fmt in fmts {
let parser = NaiveDate::parse_from_str(text.as_str(), fmt);
if parser.is_ok() {
return parser.ok();
@fancellu
fancellu / run_length_encoding.rs
Created February 8, 2024 22:24
Rust run length encoding
use std::fmt::Display;
use std::str::FromStr;
#[derive(Debug)]
struct Rle {
data: Vec<u8>,
}
impl Rle {
fn decode(&self) -> String {
@fancellu
fancellu / hex_colours.rs
Created February 8, 2024 15:26
Rust conversion of hex rgb strings to their components
use crate::RGBError::WrongLength;
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug)]
struct RGB {
red: u8,
green: u8,
blue: u8,
}
@fancellu
fancellu / isbn.rs
Last active February 15, 2024 11:20
Rust check digit calculation for ISBN-13
use crate::InvalidIsbn::{BadChecksum, TooLong, TooShort};
use std::str::FromStr;
// check digit calculation for ISBN-13
#[derive(Debug)]
struct Isbn {
raw: String,
}
@fancellu
fancellu / sum_missing.rs
Created February 6, 2024 19:14
Sum up a vector of optional numbers
use std::iter::Sum;
fn sum_with_missing<T: Sum + Copy>(vec: &Vec<Option<T>>) -> T {
vec.into_iter().filter_map(|x| *x).sum()
}
fn main() {
let mut v = vec![Some(1), Some(2), Some(3), None, Some(5)];
println!("{}", sum_with_missing(&v));
@fancellu
fancellu / blackjack.rs
Created February 5, 2024 23:01
Rust application to total up a hand of cards
use lazy_static::lazy_static;
use std::collections::HashMap;
// Ace is worth 11, except if total >21, then it is equal to 1
#[derive(Debug, PartialEq, Eq, Hash)]
enum Card {
SmallAce,
Ace,
Two,
@fancellu
fancellu / morse.rs
Created February 5, 2024 18:09
Rust application to translate into morse code
use std::fmt::Formatter;
trait MorseCode {
fn to_morse_code(&self) -> Message;
}
impl MorseCode for String {
fn to_morse_code(&self) -> Message {
self.chars()
.flat_map(|c| c.to_ascii_lowercase().to_morse_code())
@fancellu
fancellu / insensitive_sort.rs
Created February 4, 2024 00:01
Rust sort Vec of &str or String, in place, case insensitive
fn insensitive_sort<T: AsRef<str>>(users: &mut Vec<T>) {
users.sort_by_cached_key(|a: &T| a.as_ref().to_lowercase());
}
fn main() {
let mut users: Vec<String> = vec![String::from("zzz"), String::from("xxx")];
insensitive_sort(&mut users);
println!("{:?}", users);
let mut users: Vec<&str> = vec!["Todd", "amy"];
@fancellu
fancellu / unique_keep_order.rs
Last active February 15, 2024 11:20
Rust dedupe Vec<T> without changing order
use std::collections::HashSet;
use std::hash::Hash;
fn unique_keep_order<T: Eq + Hash + Clone>(vec: Vec<T>) -> Vec<T> {
let mut seen = HashSet::new();
let mut output = Vec::with_capacity(vec.len());
for x in vec.into_iter() {
if seen.insert(x.clone()) {
output.push(x); // Use the original x