Skip to content

Instantly share code, notes, and snippets.

@quadrupleslap
Last active October 29, 2019 10:33
Show Gist options
  • Save quadrupleslap/467a0103fc162c3a488ddcde63cc3ef8 to your computer and use it in GitHub Desktop.
Save quadrupleslap/467a0103fc162c3a488ddcde63cc3ef8 to your computer and use it in GitHub Desktop.
Making ten from four digits.
use std::fmt;
enum Op<'a> {
Base(f64),
Add(&'a Op<'a>, &'a Op<'a>),
Sub(&'a Op<'a>, &'a Op<'a>),
Mul(&'a Op<'a>, &'a Op<'a>),
Div(&'a Op<'a>, &'a Op<'a>),
Sbi(&'a Op<'a>, &'a Op<'a>),
Dvi(&'a Op<'a>, &'a Op<'a>),
}
impl<'a> fmt::Display for Op<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use Op::*;
match self {
&Base(x) => write!(f, "{}", x),
&Add(x, y) => write!(f, "({} + {})", x, y),
&Sub(x, y) => write!(f, "({} - {})", x, y),
&Mul(x, y) => write!(f, "({} * {})", x, y),
&Div(x, y) => write!(f, "({} / {})", x, y),
&Sbi(x, y) => write!(f, "({} - {})", y, x),
&Dvi(x, y) => write!(f, "({} / {})", y, x),
}
}
}
fn all<'a>(x: &'a Op<'a>, y: &'a Op<'a>) -> [Op<'a>; 6] {
use Op::*;
[
Add(x, y),
Sub(x, y),
Mul(x, y),
Div(x, y),
Sbi(x, y),
Dvi(x, y),
]
}
fn compute<'a>(op: &Op<'a>) -> f64 {
use Op::*;
match op {
&Base(x) => x,
&Add(x, y) => compute(x) + compute(y),
&Sub(x, y) => compute(x) - compute(y),
&Mul(x, y) => compute(x) * compute(y),
&Div(x, y) => compute(x) / compute(y),
&Sbi(x, y) => compute(y) - compute(x),
&Dvi(x, y) => compute(y) / compute(x),
}
}
fn pairs<I: Into<f64>>(a: I, b: I, c: I, d: I) -> [(f64, f64, f64, f64); 3] {
let (a, b, c, d) = (a.into(), b.into(), c.into(), d.into());
[(a, b, c, d), (a, c, b, d), (a, d, b, c)]
}
fn main() {
use Op::Base;
for a in 0..10 {
for b in 0..10 {
for c in 0..10 {
'a:
for d in 0..10 {
for &(a, b, c, d) in &pairs(a, b, c, d) {
let (a, b, c, d) = (Base(a), Base(b), Base(c), Base(d));
for op1 in &all(&a, &b) {
for op2 in &all(&c, &d) {
for op3 in &all(op1, op2) {
if compute(op3) == 10.0 {
println!("{}{}{}{}: {} = 10", a, b, c, d, op3);
continue 'a;
}
}}}
}
println!("{}{}{}{}: Impossible.", a, b, c, d);
}}}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment