Skip to content

Instantly share code, notes, and snippets.

@caioaao
Last active May 4, 2022 23:09
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caioaao/fbbca6ae89b3c418e77b05ebe5db82cb to your computer and use it in GitHub Desktop.
Save caioaao/fbbca6ae89b3c418e77b05ebe5db82cb to your computer and use it in GitHub Desktop.
Solution to Nubank's collision exercise, in Clojure
(ns collisions.core
(:require [clojure.string :as str])
(:gen-class))
(defn str->edge [s]
(->> (str/split s #" ")
(map #(Integer/parseInt %))))
(defn file-contents->edges [s]
(->> (str/split s #"\n")
(map str->edge)))
(defn edge->adj-list [[u v]]
{u #{v}, v #{u}})
(defn with-new-connections [adj-list new-connections]
(merge-with into adj-list new-connections))
(defn with-new-edge [adj-list edge]
(->> (edge->adj-list edge)
(with-new-connections adj-list)))
(defn edges->adj-list [edges]
(reduce with-new-edge {} edges))
(defn same-network? [a b adj-list]
(loop [[curr & rest] (list a), visited? #{}]
(when curr
(or (= curr b)
(recur (->> (adj-list curr)
(filter (complement visited?))
(into rest))
(conj visited? curr))))))
(defn -main
[file-path a b]
(if (-> (slurp file-path)
file-contents->edges
edges->adj-list
(->> (same-network? (Integer/parseInt a) (Integer/parseInt b))))
(println "yup")
(println "nah")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment