Skip to content

Instantly share code, notes, and snippets.

@Rudxain
Last active July 21, 2024 05:49
Show Gist options
  • Save Rudxain/2565b4f187d6af228b22674d83174fe6 to your computer and use it in GitHub Desktop.
Save Rudxain/2565b4f187d6af228b22674d83174fe6 to your computer and use it in GitHub Desktop.
list all words of the form "_i_e" where "_" is a consonant and "e" is optional, using 2 paradigms
use core::array;
use std::fmt::Write as _;
const CONSONANTS: [u8; 21] = *b"bcdfghjklmnpqrstvwxyz";
const W_COUNT: usize = CONSONANTS.len().pow(2) * 2;
fn main() {
// procedural / imperative
let mut imp = array::from_fn::<_, W_COUNT, _>(|_| String::with_capacity(4));
let mut i: usize = 0;
for pre in CONSONANTS {
for c in CONSONANTS {
let pre = pre as char;
let c = c as char;
let _ = write!(imp[i], "{pre}i{c}");
i += 1;
let _ = write!(imp[i], "{pre}i{c}e");
i += 1;
}
}
let imp = imp.join("\n");
println!("{}", imp);
// declarative / functional
let fun = array::from_fn::<_, W_COUNT, _>(|i| {
format!(
"{}i{}{}",
CONSONANTS[i / (2 * CONSONANTS.len())] as char,
CONSONANTS[(i / 2) % CONSONANTS.len()] as char,
if i % 2 != 0 { "e" } else { "" }
)
})
.join("\n");
println!("{}", fun);
assert_eq!(imp, fun);
}
const divTrunc = (n: number, d: number) => Math.trunc(n / d)
const createArray = <T,>(length: number, filler: (i: number) => T) =>
Array.from({ length }, (_, i) => filler(i))
const CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
/** imperative */
function procedural() {
const out: string[] = []
for (const pre of CONSONANTS)
for (const c of CONSONANTS) {
const tmp = pre + 'i' + c
// for simplicity, we're using dynamic allocation
out.push(tmp)
out.push(tmp + 'e')
}
return out
}
const proc = procedural()
console.log(proc)
/** declarative */
const functional = () => createArray(CONSONANTS.length ** 2 * 2, i =>
// for the sake of optimization,
// we precompute the length,
// instead of doing recursion with dynamic array allocation
CONSONANTS[divTrunc(i, 2 * CONSONANTS.length)]
+ 'i'
+ CONSONANTS[divTrunc(i, 2) % CONSONANTS.length]
+ (i % 2 ? 'e' : '')
)
const fn = functional()
console.log(fn)
const del = ' '
console.assert(proc.join(del) === fn.join(del))
@Rudxain
Copy link
Author

Rudxain commented Aug 16, 2023

I wrote this code to check if english is phonetically consistent with respect to the pronunciation of these words, lol. So far, I haven't found any inconsistency, it seems there's a pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment