Skip to content

Instantly share code, notes, and snippets.

@pathikrit
pathikrit / SudokuSolver.scala
Last active April 12, 2024 15:00
Sudoku Solver in Scala
val n = 9
val s = Math.sqrt(n).toInt
type Board = IndexedSeq[IndexedSeq[Int]]
def solve(board: Board, cell: Int = 0): Option[Board] = (cell%n, cell/n) match {
case (r, `n`) => Some(board)
case (r, c) if board(r)(c) > 0 => solve(board, cell + 1)
case (r, c) =>
def guess(x: Int) = solve(board.updated(r, board(r).updated(c, x)), cell + 1)
val used = board.indices.flatMap(i => Seq(board(r)(i), board(i)(c), board(s*(r/s) + i/s)(s*(c/s) + i%s)))
@pathikrit
pathikrit / ask_gpt.js
Created September 26, 2023 18:56
Minimal node.js code to ask ChatGPT
import {ChatCompletionRequestMessageRoleEnum as Role, OpenAIApi} from "openai";
import {Configuration as OpenAIConfig} from "openai/dist/configuration.js";
const OPENAI_API_KEY = 'XXXXXXXXXXXXXX'
const openai = new OpenAIApi(new OpenAIConfig({apiKey: OPENAI_API_KEY}))
const ask = (query) => {
return openai.createChatCompletion({
model: 'gpt-3.5-turbo',
max_tokens: 2048,
@pathikrit
pathikrit / NorvigSpellChecker.scala
Last active May 1, 2023 17:41
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 / 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 / sudoku-1.coffee
Created October 10, 2012 07:04
1-liner CoffeeScript Sudoku Solver
solve = (s, c = 0) -> if c is 81 then s else if s[x = c/9|0][y = c%9] isnt 0 then solve s, c+1 else (([1..9].filter (g) -> ![0...9].some (i) -> g in [s[x][i], s[i][y], s[3*(x/3|0) + i/3|0][3*(y/3|0) + i%3]]).some (g) -> s[x][y] = g; solve s, c+1) or s[x][y] = 0
@pathikrit
pathikrit / chron.scala
Last active June 25, 2022 21:52
Chron.scala
// A simply port of Google Task's recurring task scheduler to Scala 3 ADT:
// https://tasks.google.com/embed/?origin=https://calendar.google.com&fullWidth=1
import java.time._
enum Cadence:
case Daily
case Weekly(on: Set[DayOfWeek] = Set(DayOfWeek.SUNDAY))
case Monthly(on: Set[DayOfMonth] = Set(DayOfMonth.Day(1)))
case Yearly(on: Set[MonthDay] = Set(MonthDay.of(1, 1)))
@pathikrit
pathikrit / Library.java
Last active May 6, 2022 23:51
Java Algorithms
import java.awt.*;
import java.math.*;
import java.util.regex.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Integer.parseInt;
import static java.util.AbstractMap.*;
import static java.lang.System.*;
import static java.lang.Math.*;
@pathikrit
pathikrit / Node.scala
Last active September 17, 2021 02:02
Reverse a LinkedList in Scala
case class Node(value: Int, next: Option[Node])
def reverse(node: Node, prev: Option[Node] = None): Node = {
val reversed = node.copy(next = prev)
node.next map {reverse(_, Some(reversed))} getOrElse reversed
}
/****************************************************************/
val one = Node(1,Some(Node(2,Some(Node(3,None)))))
println(s"$one\n${reverse(one)}")
@pathikrit
pathikrit / Fees.scala
Last active August 27, 2021 15:08
Incur Credit Card Fees or Not?
import squants.Dimensionless
import squants.DimensionlessConversions._
import squants.market._, MoneyConversions._
case class CreditCard(name: String, points: Dimensionless, checkingAPR: Dimensionless) {
def charge(amount: Money, fee: Dimensionless = 0 percent, flatFee: Money = 0 dollars): String = {
val fees = amount*fee + flatFee
val interestEarned = amount * checkingAPR/12
val cashBack = (amount + fees)*points
val saved = cashBack - interestEarned - fees
@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