Posts tagged code

Binary Tree Rebuilder

Imagine you have a Binary Tree, with those characteristics:

  • Nodes do not respect any order relation – In other words: it’s not a Binary Search Tree of any kind
  • Every node appears once and only once within the tree
A nice Binary Tree
A nice Binary Tree

Then, your little brother passes by your desk and, to upset you, deletes the tree from your computer memory/HD (yeah, I know, I’m pathetic at inventing hypothetical situations :-P ).

Fortunately though, you previously did a Pre-Order and an In-Order visit of your tree, and stored the result in an 2 nice array.

Can you rebuild the original tree structure out of this 2 array?

How are you going to rebuild it?

Yes, you can! (Sorry, I couldn’t resist). And it’s quite easy as well. What you have to do, is the following:

  • Take the first element of the PreOrder Array and use it as root of a new tree
  • Find the position of this New Node in the InOrder Array, scanning it from 0 to n-1 (n is the number of Nodes)
  • IF next element in the PreOrder Array is on the left of the New Node in the InOrder array: call RECURSIVELY this procedure, this time taking into account the portion of InOrder array that goes from 0 to the position of the New Node in the InOrder Array -1.
  • IF next element in the PreOrder Array is on the right of the New Node in the InOrder array: call RECURSIVELY this procedure, this time taking into account the portion of InOrder array that goes from the position of the New Node in the InOrder Array +1 to n-1.
  • Return the New Node

By the way, this doesn’t work. To fix it we should be more generic, specifying things a little bit better. Things like:

  • Every recursive calls takes into account a portion of the InOrder array; in the case of the first call it’s the entire array
  • There is going to be as much recursive calls as the number of elements in the PreOrder array

Of course, is a tree what we are talking about here: recursion is a MUST. More >

Prime Numbers Generator

I believe I don’t have to describe what primes are, what are their properties and what not. This post is more a tribute to geek-ness of 2 friends-and-colleagues (@lucabox) that have fun thinking of algorithms to solve stupid (or less stupid), and always useless problems ;-) .

Optimus Prime
Optimus Prime :-P – yeah yeah, a stupid joke

Briefing

This code is based on the assumption that we want to generate very very large primes, so it uses unsigned long long to store the values, instead of classical unsigned int. Live with that.

Also, give that there is nothing much better then a “try-dividing-by-every-previous-prime” out there (there are alternatives, but I’m not aware of more complex ones), I took a look to some properties of Primes, and putted into the algorithm those properties as conditions for early stop:

  1. Say P[i] are the previously calculated Primes; If trying dividing value V by every P[i] we find that P[i] > sqrt(V), stop dividing and classify V as a newly found prime
  2. No need to check any even number: they are divisible by 2, so no primes by definition
  3. No need to allocate more space then an array of the size of the requested prime ordinality: everything can be done in place

More >

“Bidirectionally multiplied” array

Another small problem before I go to sleep tonight:

There is an array A[N] of N numbers.
You have to compose an array Output[N] such that Output[i] will be equal
to multiplication of all the elements of A[N] except A[i].

For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1]
will be multiplication of A[0] and from A[2] to A[N-1].

Solve it without division operator and in O(n).

What is funny of the problem, is the fact that the O(n) constraint, makes it sound like is going to be hard to solve. Doesn’t it? Well, it’s not.

The solution is quite simple, so I suggest you take your 10 minutes to think about it, then continue to see the code. More >

Use Backtracking to print all Subsets

I’m “studying” this algorithmic technique: Backtracking. This is an algorithmic approach to problem solution that I trust every good Computer Scientist already uses; but taking a good theo-practical look at it is something better.

A Backtracking Tree
A Backtracking Tree

I believe you can find enough informations about it online (the 2 links I provided are more than enough), so I’ll go straight to the problem.

Problem definition

Given an integer n, and the set S = { 1 ... n }, calculate (print) all the possible subsets of S. For example, for n = 1, all the possible subsets are { 1 } and { } (empty set). For n = 2, all the possible subsets are: { 1 2 } { 1 } { 2 } { }. In general, for the set made of the first n Integers, the number of possible subsets is 2n.

Approaching the problem

A way to describe a possible subset is an array of n elements, one for every integers; every element in the array will have value TRUE if the correspondent integers is part of the subset, FALSE otherwise.

Why the Backtracking then? Because the backtracking technique is designed to generate every possible “candidate solution” once. If we design the algorithm smartly, we can get the backtracking logic to work for us and generate all the possible subsets.

Are you are asking yourself: “isn’t this a bit of a stretching of the backtracking approach?”. I believe it is: the code could be made way smaller, even though it would have the same complexity. We are going to execute the backtracking, designing the algorithm so it will never stop until it tried every possible solution. No “intermediate stopping condition” then.

More >

Money change problem: Greedy vs. Dyn.Pro.

This is a classical problem of Computer Science: it’s used to study both Greedy and Dynamic Programming algorithmic techniques.

Coins
I hate having my pocket full of copper!!! -_-

Definition

Given:

  • A set of n Denominations D[0...n-1] in ascending order, representing a Monetary Coin System
  • An money amount A, as input

calculate a solution:

  • S[0...n-1], with 0 <= S[i] <= (A/S[i]) and 0 < i < n-1

where:

  • A = Sum[i=0 -> n-1] { D[i] * S[i] }
  • Min{ Sum[i=0 -> n-1] { S[i] } }

In other words

Find the smallest amount of coins to make the given amount. More >

Calculate abs(int) without branching

For this you need someone to teach it to you: if you made it yourself, then you are a very good Comp-Sci, and you should send your CV to Google ASAP. ;)

Without branching O_o?

Yes, without using any “if ( a < 0 )...". To do that, you need to refresh how Two's Complement works, then come back.

What we really need to focus on is that, given a signed int A, the negative of that number is: B = ~A + 1. BUT, we are trying to calculate the Absolute Value, not the negative. So, something like:

RESULT =
    (INPUT, if positive, or NEGATE_INPUT, if negative)
    +
    (0, if positive, or 1, if negative)

Does it makes sense to you? To me it didn’t for the first 10 minutes. More >