Skip to content

Instantly share code, notes, and snippets.

@xiaq
xiaq / parser.java
Last active November 11, 2017 20:44
import java.lang.Exception;
import java.util.List;
import java.util.ArrayList;
class Parser {
static public class ParseException extends Exception {
}
static public class Edge {
public Edge(char src, char dst, int weight) {
@xiaq
xiaq / compiler.go
Created September 15, 2017 14:17
An illustration of compiling-to-closure
// Suppose you have a simple language with three possible tokens: + - p. The runtime of your language keeps a counter.
// The command + increments the counter, - decrements, and p prints.
type Runtime struct {
Counter int
}
// An interpreter.
func interprete(r *Runtime, program string) {
for _, r := range program {
@xiaq
xiaq / rc.elv
Last active July 6, 2017 21:09
fn c { clear; tmux clear }
fn ls { e:ls -G $@ }
if (eq $E:ELVISH_PATH "") {
E:ELVISH_PATH = 1
paths = [~/Library/Python/*/bin ~/.cargo/bin ~/on/*[nomatch-ok]/bin $@paths]
}
edit:binding[insert][Down] = $&nop
edit:binding[insert][Alt-b] = $edit:&move-dot-left-word
public class Solution {
public double myPow(double x, int n) {
if (n < 0 && -n < 0) {
n /= 2;
x *= x;
}
if (n < 0) {
n = -n;
x = 1 / x;
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
@xiaq
xiaq / q12.cc
Created February 16, 2017 23:36
template <int i>
void f(int& num, string& roman, const char *s) {
while (num >= i) {
roman += s;
num -= i;
}
}
class Solution {
public:
@xiaq
xiaq / fib-memo.py
Last active February 16, 2017 22:09
memo = {0: 0, 1: 1}
def fib(n):
if n in memo:
return memo[n]
result = fib(n-1) + fib(n-2)
memo[n] = result
return result
# Or, a slightly cleaner way to write it:
memo = {}
def isCharMatch(s, p):
return p in ('.', s)
def isMatch(s, p):
if (s, p) not in memo:
memo[(s, p)] = isMatchInner(s, p)
return memo[(s, p)]
@xiaq
xiaq / q10-rec.py
Last active February 15, 2017 22:34
def isCharMatch(s, p):
return p in ('.', s)
def isMatch(s, p):
if p == '':
return s == ''
elif len(p) == 1:
return len(s) == 1 and isCharMatch(s, p)
if p[-1] != '*':
public class Solution {
private Map<String, Map<String, boolean>> memo = new HashMap<String, HashMap<String, boolean>>();
public boolean hasMemo(String s, String p) {
return memo.containsKey(s) && memo.get(s).containsKey(p);
}
public boolean getMemo(String s, String p) {
return memo.get(s).get(p);
}