Random algorithm implementation, mostly from TopCoder