Mapping two integers to one, in a unique and deterministic way

Cantor pairing function is really one of the better ones out there considering its simple, fast and space efficient, but there is something even better published at Wolfram by Matthew Szudzik, here. The limitation of Cantor pairing function (relatively) is that the range of encoded results doesn’t always stay within the limits of a 2N … Read more

Determine font color based on background color

I encountered similar problem. I had to find a good method of selecting contrastive font color to display text labels on colorscales/heatmaps. It had to be universal method and generated color had to be “good looking”, which means that simple generating complementary color was not good solution – sometimes it generated strange, very intensive colors … Read more

What algorithm can be used for packing rectangles of different sizes into the smallest rectangle possible in a fairly optimal way?

See this page on the ARC project for a survey of solutions, there is a trade-off between implementation complexity/time and optimality, but there is a wide range of algorithms to choose from. Here’s an extract of the algorithms: First-Fit Decreasing Height (FFDH) algorithm FFDH packs the next item R (in non-increasing height) on the first … Read more

Finding all possible combinations of numbers to reach a given sum

This problem can be solved with a recursive combinations of all possible sums filtering out those that reach the target. Here is the algorithm in Python: def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print “sum(%s)=%s” % (partial, target) if s >= … Read more

Write a program to find 100 largest numbers out of an array of 1 billion numbers

You can keep a priority queue of the 100 biggest numbers, iterate through the 1 billion numbers. Whenever you encounter a number greater than the smallest number in the queue (the head of the queue), remove the head of the queue and add the new number to the queue. A priority queue implemented with a … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)