Skip to content

Instantly share code, notes, and snippets.

@pathikrit
pathikrit / MortgageMath.md
Created August 16, 2016 19:35
Mortgage Math

Input

p := Original Principal amount
apr := Annual Percentage Rate
t := Number of years of loan

Calcuation:

r := apr/100/12                    # monthly interest rate
@pathikrit
pathikrit / bulk_edit_commit_msgs.sh
Created July 5, 2016 13:24
Script to replace a substring in all new commit messages in your feature branch
#!/usr/bin/env bash
substring=$1
replace=$2
current_branch=$(git name-rev --name-only HEAD)
echo "Replacing ${substring} with ${replace} in all new commits in ${current_branch}"
cd $(git root)
git filter-branch --msg-filter "'sed ""s/${substring}/${replace}/g""'" master..${current_branch}
git push -f
@pathikrit
pathikrit / ValueSortedMap.scala
Last active June 3, 2019 14:36
A sorted map that sorts keys by value
import scala.collection.mutable
type PQ[K, V] = mutable.SortedMap[K, V]
object PQ {
def apply[K, V: Ordering](elems: Seq[(K, V)]): PQ[K, V] =
elems.foldLeft(PQ.empty[K, V])(_ += _)
/**
* A SortedMap which sorts keys by the value
@pathikrit
pathikrit / NQueen.scala
Last active January 19, 2023 21:30
O(n!) solution to the n-Queen puzzle (https://en.wikipedia.org/wiki/Eight_queens_puzzle)
/**
* Solves the n-Queen puzzle in O(n!)
* Let p[r] be the column of the queen on the rth row (must be exactly 1 queen per row)
* There also must be exactly 1 queen per column and hence p must be a permuation of (0 until n)
* There must be n distinct (col + diag) and n distinct (col - diag) for each queen (else bishop attacks)
* @return returns a Iterator of solutions
* Each solution is an array p of length n such that p[i] is the column of the queen on the ith row
*/
def nQueens(n: Int): Iterator[Seq[Int]] =
(0 until n)
@pathikrit
pathikrit / Not.scala
Last active August 3, 2016 16:17
Simple Negation Types in Scala
trait NotSubTypeOf[A, B] // encoding to capture A is not a subtype of B
// Note: We can use infix notation to write `A NotSubTypeOf B` instead of `NotSubTypeOf[A, B]`
// evidence for any two arbitrary types A and B, A is not a subtype of B
implicit def isSub[A, B]: A NotSubTypeOf B = null
// define ambigous implicits to trigger compile error in case A is a subtype of B (or A =:= B)
implicit def iSubAmbig1[A, B >: A]: A NotSubTypeOf B = null
implicit def iSubAmbig2[A, B >: A]: A NotSubTypeOf B = null
@pathikrit
pathikrit / AutoSuggest.scala
Last active March 5, 2016 06:25
Auto suggester
class AutoSuggest(corpus: String, alphabet: Seq[Char] = 'a' to 'z', depth: Int = 2) {
val words = s"[${alphabet.head}-${alphabet.last}]+".r
.findAllIn(corpus.toLowerCase).toSeq
.groupBy(_.toSeq).mapValues(_.size)
.par withDefaultValue 0
def editDistance(a: Seq[Char], b: Seq[Char]) = {
lazy val d: Stream[Stream[Int]] = Stream.tabulate(a.length + 1, b.length + 1) {
case (i, j) if (i - j).abs > depth => Int.MaxValue
case (i, 0) => i
@pathikrit
pathikrit / NorvigSpellChecker.scala
Last active May 25, 2025 15:27
Scala implementation of Peter Norvig's spellchecker (http://norvig.com/spell-correct.html)
class NorvigSpellChecker(corpus: String, alphabet: Seq[Char] = 'a' to 'z', level: Int = 2) {
val words = s"[${alphabet.head}-${alphabet.last}]+".r.findAllIn(corpus.toLowerCase).toSeq
val count = words.groupBy(_.toSeq).mapValues(_.size) withDefaultValue 0
def edit(n: Int)(word: Seq[Char]): Set[Seq[Char]] = n match {
case 0 => Set(word)
case 1 =>
val splits = word.indices map word.splitAt
val deletes = splits collect {case (a, b0 +: b1) => a ++ b1}
@pathikrit
pathikrit / OrderLearner.scala
Last active February 14, 2016 18:18
Infer ordering given sorted collection
class OrderLearner[A](root: A) {
import scala.collection.mutable.{Map => Dict}
private val next = Dict.empty[A, Set[A]] withDefaultValue Set.empty[A]
def learn(words: Seq[A]*) = for {
i <- words.indices
_ = words(i).foreach(u => next(root) += u)
j <- words.indices drop (i+1)
(u, v) <- words(i) zip words(j) find {case (a, b) => a != b}
} next(u) += v
@pathikrit
pathikrit / FastPrependArrayList.java
Last active July 15, 2017 02:24
Data structure that supports O(1) append, prepend, first, last and size
import java.util.ArrayList;
public class FastPrependArrayList<A> {
private ArrayList<A> appends = new ArrayList<A>();
private ArrayList<A> prepends = new ArrayList<A>();
public void append(A element) {
appends.add(element);
}
@pathikrit
pathikrit / Scanner.scala
Last active June 5, 2017 15:47
Scala Scanner
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer
import scala.io.Codec
/**
* Scala implementation of a faster java.util.Scanner
* See: http://codeforces.com/blog/entry/21125
* All next methods throw NoSuchElementException when !hasNext