Tag Archives: Algorithm

Weight your toys

I decide to write this post because this post reminds something about my weakness when dealing with algorithm problems.

Here’s the problem, I put it to gist.


 

How to abstract reality problems to sort problems, and how to take advantage of sort to find out things that interest us?

The code above, I want to use observer design pattern ( compare_event ). Yes that’s the part to emphasise that we always want to search things interest us, if not, why we search things? So that is the pattern of human beings, and I always decouple things when I find a point that fit normal brains.

Here is the steps that I always follow to create a solution:

  1. Understand them, feel them, and try to measure them. We always have a way to quantify things, though most people die here or find a really bad way to measure things.
  2. So we have convert states to numbers in the first step. We can use the numbers to compare two things.
  3. If I want to search something, I always search things while sort them. You always do the two things together, think about it when you are paring the socks from your washing machine. Even school child does it without thinking.
  4. I interpolate tasks while each comparison. Searching itself is also a task. Each task can access the current comparison result and process state.
  5. Choose a sort algorithm which fit the situation best
  6. Launch the whole process.

 

The better way to combine hashcodes

For example, two int numbers x and y. A simple way is like below:

But it’ll be easily result in collision. To avoid this, Joshua Bloch performed an elegant way to combine two hashcodes:

The usage of the prime numbers are the most brilliant part of the algorithm.