Skip to content

Instantly share code, notes, and snippets.

Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@kamalbanga
kamalbanga / monte_carlo.py
Last active March 1, 2020 17:40
Monte Carlo simulations of some problems; to estimate probabilities
from random import choices, sample
from statistics import mean
def common_birthday(k):
'''Generate k independent uniformly random birthdays & check if there are any repeats'''
birthdays = choices(range(1, 366), k=k)
return len(set(birthdays)) != k
>>> mean(common_birthday(23) for _ in range(10000))
0.4979
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@kamalbanga
kamalbanga / compress.scala
Last active May 8, 2019 07:28
Zlib Compression in Scala
import scala.io._
import java.util.zip.{Inflater, Deflater}
import java.io.{File, FileOutputStream}
object App {
def compress(inData: Array[Byte]): Array[Byte] = {
var deflater: Deflater = new Deflater()
deflater.setInput(inData)
deflater.finish
@kamalbanga
kamalbanga / LegoBlocks.cpp
Last active March 10, 2019 17:37
A dynamic programming/recursive solution to Hackerrank's "Lego Blocks" problem.
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
#define MOD 1000000007
unsigned long long power(unsigned long long num, int p) {
@kamalbanga
kamalbanga / ACO.py
Last active March 29, 2017 10:23
To find TSP through Ant Colony Optimization
import random
import math
seed = 1
boost = 5
iter = 3
numCities = 4
maxDistance = 40000
upperX = 24000
upperY = 32000
@kamalbanga
kamalbanga / setup.sh
Last active May 17, 2016 12:48
Setup Dataproc
sudo apt-get install python-pip python-dev build-essential
sudo pip install --upgrade pip
sudo pip install --upgrade gensim
@kamalbanga
kamalbanga / ctmdata.py
Last active May 12, 2016 09:43
Generate random data for input to CTM algorithm. Run as "python2.7 ctmdata.py".
from random import randint
from random import uniform, gauss
def gaussian(mu, sigma = 0.1):
prob = gauss(mu, sigma)
if prob < 0:
return 0.0
elif prob > 1:
return 1.0
else:
@kamalbanga
kamalbanga / postorder.c
Last active December 27, 2015 11:59
Create Binary Tree from it's PostOrder when leaf nodes are differentiable from internal nodes and internal nodes have exactly two children.
#include <stdio.h>
#include <stdlib.h>
struct node
{
char c;
struct node* left, *right;
};
struct node* createNode(char c)
@kamalbanga
kamalbanga / numberofOnes.c
Last active December 26, 2015 03:19
Total no. of 1's in 2's complement representation between A and B, inclusive. Hackerrank's "2's complement" problem.
#include <stdio.h>
#include <math.h>
#include <limits.h>
unsigned int prevTwo(unsigned int x) // bit twiddling
{
unsigned int y = x;
x--;
x |= x >> 1;
x |= x >> 2;