Skip to content

Instantly share code, notes, and snippets.

@craftybones
Last active March 27, 2021 18:01
Show Gist options
  • Save craftybones/8c11f4c7c5d42d65088cc7e2a71dc1fc to your computer and use it in GitHub Desktop.
Save craftybones/8c11f4c7c5d42d65088cc7e2a71dc1fc to your computer and use it in GitHub Desktop.
(require '[clojure.string :as cstr])
(defn pendulum [from to step]
(concat (range from to step) (range to (dec from) (- step))))
(defn rev-pendulum [from to step]
(concat (range to from (- step)) (range from (inc to) step)))
(defn line [max-size size]
(rev-pendulum (inc (- max-size size)) max-size 1))
(defn to-str (comp char (partial + 96)))
(defn diamond [size]
(map (partial line size) (pendulum 1 size 1)))
(defn justify [size char content]
(let [padding (/ (- size (count content)) 2)]
(concat (repeat padding char) content (repeat padding char))))
(defn rangoli [size]
(->> size
diamond
(map (partial map to-str))
(map (partial cstr/join \-))
(map (partial justify (- (* 4 size) 3) \-))
(map (partial apply str))))
;; A simpler approach
(def dashes (repeat \-))
(def alphabets (map char (range (int \a) (inc (int \z)))))
(defn stitch [a b c]
(take (dec (* 2 c)) (concat (drop (* 2 b) a) dashes)))
(defn lower-right-quadrant [n]
(let [alpha (interpose \- (take n alphabets))]
(map #(stitch alpha % n) (range n))))
(defn mirror [x] (concat (reverse (rest x)) x))
(defn rangoli [x]
(map (partial apply str) (mirror (map mirror (quadrant x)))))
const posRange = function(from, to, step) {
let result = [];
for (let i = from; i < to; i += step) {
result.push(i);
}
return result;
};
const negRange = function(from, to, step) {
let result = [];
for (let i = from; i > to; i += step) {
result.push(i);
}
return result;
};
const range = function(from, to, step) {
return step < 0 ? negRange(from, to, step) : posRange(from, to, step);
};
const toAlphabet = function(num) {
return String.fromCharCode(num + 96);
};
const line = function(maxWidth, width) {
let leftSide = range(maxWidth, maxWidth - width + 1, -1);
let rightSide = range(maxWidth - width + 1, maxWidth + 1, 1);
return leftSide.concat(rightSide);
};
const diamond = function(size) {
let topHalf = range(1, size, 1);
let bottomHalf = range(size, 0, -1);
let lineGenerator = line.bind(null, size);
return topHalf.concat(bottomHalf).map(lineGenerator);
};
const repeat = function(character, times) {
return new Array(times).fill(character).join('');
};
const justify = function(content, size, character) {
let paddingSize = (size - content.length) / 2;
let padding = repeat(character, paddingSize);
return padding + content + padding;
};
const lineToString = line => line.map(toAlphabet).join('-');
const rangoli = function(size) {
let totalWidthOfString = 4 * size - 3;
let justifier = justify.bind(null, totalWidthOfString, '-');
return diamond(size)
.map(lineToString)
.map(justifier);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment