Menu

  • Home
  • Archives
  • Tags
  • RSS
August 10, 2018

Using Clojure for simple math

Someone I respect recommended Brilliant to me, and it turned out to be fun indeed; wish I had encountered it sooner.

Lots of little examples, to play with, and to learn from. I was stuck at something else today, so wrote a tiny program for one of these.

The problem is extremely simple (this post is more about using a flexible programming language recreationally, nothing else):

Are there basic arithmetic operators (one of +, -, *, /) that can be inserted into the blanks to get the desired result?

10 __ 10 __ 10 __ 10 = 100

So, a simple, brute-force solution:

(ns clj-playground.core
  (:require [clojure.math.combinatorics :as combo]))

(def n 10)
(def ops [+ - * /])

;; Evaluate a given set of operators.
(defn compute
  [n opv]
  (reduce (fn [v op] (op v n))
		  n
		  opv))

;; Generate all possible 3-tuples of operators
(defn all-variations
  []
  (mapcat identity
   (map clojure.math.combinatorics/permutations 
		(clojure.math.combinatorics/combinations ops 3))))

(defn find-values [val]
  []
  (->> (all-variations)
	   (map #(vec [% (compute n %)]))
	   (filter (fn [[o v]] (= v val)))
	   (clojure.pprint/pprint)))

And to use it:

user> (clj-playground.core/find-values 100)
([(#function[clojure.core/+]
   #function[clojure.core/-]
   #function[clojure.core/*])
  100]
 [(#function[clojure.core/-]
   #function[clojure.core/+]
   #function[clojure.core/*])
  100]
 [(#function[clojure.core/*]
   #function[clojure.core/+]
   #function[clojure.core/-])
  100]
 [(#function[clojure.core/*]
   #function[clojure.core/-]
   #function[clojure.core/+])
  100])

So, there are ways to get there, and here they are.

I know, I know, toy example, but still.


Tags: clojure

« Clojure's incredibly frustrating lack of debugging Monthly Curations: July 2018 »

Copyright © 2020 Agam Brahma

Powered by Cryogen