Skip to content

Instantly share code, notes, and snippets.

View kghost's full-sized avatar
🎯
Focusing

Zang MingJie kghost

🎯
Focusing
View GitHub Profile
@kghost
kghost / fiber.cpp
Created August 2, 2019 03:28
coroutine
#include <iterator>
#include <iostream>
#include <future>
#include <experimental/coroutine>
std::function<void()> resume;
template <typename _Ty, typename _Alloc = std::allocator<char>>
class future {
public:
val s = Array("A", "B", "C")
val lock = new java.util.concurrent.locks.ReentrantLock()
val total = s.length
var token: Int = 0
val cvs = s.map(i => lock.newCondition())
val threads = for (t <- 0 until 3) yield {
val thread = new Thread {
override def run {
lock.lock()
function unfold(p, f, g, seed, reduce, tailgen) {
function recursive(iter) {
if (p(iter)) return tailgen(iter);
return reduce(f(iter), recursive(g(iter)));
}
return recursive(seed);
}
function sum(a) {
function unfold(p, f, g, seed, reduce, tailgen) {
function recursive(iter) {
if (p(iter)) return tailgen(iter);
return reduce(f(iter), recursive(g(iter)));
}
return recursive(seed);
}
@kghost
kghost / echo server
Created November 2, 2010 06:04
echo server using scala continuation
package info.kghost.test
import java.net.InetSocketAddress
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.nio.ByteBuffer
import scala.collection.JavaConversions.collectionAsScalaIterable
#!/bin/bash
#
# This file echoes a bunch of color codes to the
# terminal to demonstrate what's available. Each
# line is the color code of one forground color,
# out of 17 (default + 16 escapes), followed by a
# test use of that color on all nine background
# colors (default + 8 escapes).
#
@kghost
kghost / cpu-time-profile.cpp
Created January 8, 2016 08:41
Profile CPU time usage
#include <stdio.h>
#if defined(__i386__)
static __inline__ unsigned long long rdtsc(void)
{
unsigned long long int x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
}
@kghost
kghost / gist:7065653
Last active December 26, 2015 00:39
number of partitions of n into at most m parts
// use dp to speed up
def Count(n: Int, m: Int) = {
def Loop(n: Int, m: Int, max: Int): Int = {
if (m == 0) {
if (n == 0) 1 else 0
} else {
(0 to Math.min(max, n)).map({ x => Loop(n - x, m - 1, x) }).sum
}
}
def Conbination(n: Int, m: Int) {
def Loop(n: Int, m: Int, prefix: List[Int]) {
if (m == 0)
println(prefix)
else
for (x <- m to n)
Loop(x - 1, m - 1, x :: prefix)
}
Loop(n, m, Nil)
}
case class BinaryTree(left: BinaryTree, right: BinaryTree)
def isFull(tree: BinaryTree): Boolean = {
def FullWithHeight(tree: BinaryTree): Int = {
if (tree == null) 0 else {
val l = FullWithHeight(tree.left)
val r = FullWithHeight(tree.right)
if (l >= 0 && l == r) l+1 else -1
}
}