Tuesday, June 15, 2010

Monday, June 14, 2010

Phase 1: bulding a Facebook app

Facebook has a rich documentation site for building Apps. The only problem I had is that there are different layers of API which actually carry out the same operation, and so it is difficult to understand the one you want to use. First step is to register your future app and to edit it. Then, I used the Social plugin for Login, which is a trivial way for remote login and authentication in Facebook. The code is simply

<!-- login in facebook with extended perms -->
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream" faces="true"></fb:login-button>

This will use FB extensions to HTML, which must be activated before with an asynchronous initialization of Facebook javascript library (noticed the appId:, and xfbml:true down below
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '117083285001944', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());

This function uses the FB.UI Api call to publish on your facebook account
function streamPublish(name, description, caption, hrefTitle, hrefLink, userPrompt, thumb, urlThumb){
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: (caption),
description: (description),
href: hrefLink,
media: [{ type: 'image', src: (thumb), href: (urlThumb)}]
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {

});
}
</script>

Sunday, June 13, 2010

Facebook infrastructure and data


Very interesting presentation about Facebook by Aditya Agarwal, Director of Engineering
  • 8 billion minutes spent every day, 5 billion of contents shared per week, 3 billion photos per month
  • 80,000 applications use Facebook connect
  • 500,000 million user
Stack is made up of several components. The front-end is a PHP optimized with mem-cache and asynchronous communication, which has been replaced by a HipHop code transformer in C++. The service components is written in different languages and communicating by using Thrift, Scribe and some in-house components. Memcache is used to store in memory hash table and for caching mysql data or application generated data. Mysql is used to store data (key, value) and with almost no relational model (clearly no local relational join, since "tables" are distributed ;-). All the software they have contributed to the community is here

Saturday, June 12, 2010

Efficient dictionary

Given a dictionary of words D, find out the longest chain of 'ancestors' in it. Ancestors are defined in the following way: A word is said to be the parent of another word if (1) It is a valid word in D, (2) It can be obtained by deleting one character of the word and permuting the remaining characters.

What if we allow to delete k characters?

Friday, June 11, 2010

Where is the point?

Given a polygon and a point give an algorithm to understand where is the point with respect to the polygon

Wednesday, June 9, 2010

Vertices of a polygon

how to find two vertices of a polygon which are farthest from each other in linear time

Monday, June 7, 2010

Apple going OS?

IOS is the historical name of Cisco Routers OS, now Apple licenced it

Sunday, June 6, 2010

HTML5 is damn hot

HTML5 is not just a video player, is an amazing collection of API

HackaTon: 1 week, 1 hour, 1 social experiment with Html5, Bing Maps, Facebook, Geonames.org

Last week I had one week of vacation. So i started a social experiment. Every day, I coded for 1 hour. Time is the key for programming and I believe that 7 hours are a very long release cycle. Those are the rules:
  1. I want to make something social. And I when I say social, I mean sharing on Facebook. Social is a so catchy and meaningless word, these days;
  2. I want to make something with geolocatization. I heard that HTML5 made a great progress on that side and I know that Bing Maps are pretty cool;
  3. KISS mode must be on;
  4. Everything must stay on the client, keep it small keep it fast. Code is public, since is just javascript;
  5. I am starting an Mashup HackAthon, send me your contribution and I will post it.
So the result of my little hackton is an application. It geocalizes you with your HTML5 browser. Then, it accesses geonames.org for getting the name of the place where you are. Then, it gets your position on a 3D Bing Map. Then, it posts your position, your map, your comment on your Facebook profile.

During the next days I will comment the code here. If you want to test it, this is the result after 7 hours of coding. Crisscrossy.com (you must use a browser with geolocalization support)

Saturday, June 5, 2010

Mysql vs Cassandra: or SQL vs NoSQL

A very interesting article here:

A new generation of low-cost, high-performance database software is rapidly emerging to challenge SQL's dominance in distributed processing and Big Data applications. Some companies have already traded SQL's rich functionality for these new options that let them create, work with, and manage large data sets.

A big reason for this movement, dubbed NoSQL, is that different implementations of Web, enterprise, and cloud computing applications have different requirements of their databases. Not every app requires rigid data consistency, for example.

Friday, June 4, 2010

Why I like the Ipad, and why i don't like the App model

So I bought an Ipad. I must confess that I like it. Disclaimer: I don't have any apple stock right now. You know "sell in May...". Disclaimer: I don't have an iphone, at the moment. I bought it, the model 1 in new york city, two days after the first launch -- and I bought also some stocks at that timet. I played a bit with the SDK, and was all but easy to program with a lot of features disabled by choice (e.g. no multi-thread, no video, erghhh!). I never felt in love with the Iphone, but I predicted his amazing success -- at least 20 people can confirm it. I made my money for that prediction and I built some apps just for fun.

Now I tell you, I love the IPad and I predict an amazing success. First at all, the battery lasts for 9-10 hours. Second, there is a pull mode that download content offline. Third, display is amazing: you can read your newspapers, watch your movies, browse the net, email, a keyboard that is working with my big fingers. Still video is not there. And is quite expensive. Anyway, this will be a blast. Apple will release new versions with little additional features just to sell more devices.

Anyone is about Apps right now. Like anyone was about corba, 15 years ago. Like Web 2.0, 5 years ago or The cloud, just yesterday.

Can I say? I don't like the app model. I know you can make a lot of money out of it. And a lot of devs are happy because they can participate to this new golden age. The claim is: "There is an app for that", anything you need to do.

Well my question: "how can i find that app?". You need to find an app for finding things. There is an additional level of indirection to go in a cage.

And it is not easy to find that app. Should we have a search engine for that?

Thursday, June 3, 2010

Unique elements

Take an array and return same array with only unique elements in it in o(n) .

Wednesday, June 2, 2010

Top 1000 Sites on Web

Facebook is 1st with an impressive 540M unique users, then Yahoo, Live (for email), Wikipedia, Microsoft. Google omitted themself from its own list

Tuesday, June 1, 2010

Array Increment Problem

Given an array A consisting of 'n' elements. Do the following both operations in O(log n) time using a data structure.

Increment (A,i,j,x) : This should increment elements from A to A[j] by value x .
Report(A,j) : This should report A[j]

Trivially in an array Increment takes O(j-i) time and report takes O(1) . Now we need to store in a data structure (can be augmented) such that both operations takes O (log n) time.

(Interesting data structure for this one http://en.wikipedia.org/wiki/Segment_tree)

Google goes Ad Mobile

Several days after the Federal Trade Commission closed its investigation into Google's acquisition of AdMob, Google said Thursday that it has also closed its acquisition and is the proud new owner of a mobile ad network.

Saturday, May 29, 2010

Friday, May 28, 2010

Apple beats Microsoft

IPad

The maker of Mac computers, interactive phone and tablet iPhone IPAD beats Microsoft as the most valued technology firm in the world on stock market.

Wednesday, May 26, 2010

Business Model for Facebook

Facebook is one of the most interesting company out of there. They went from few millions of users up to five hundred million in a couple of years. I forecast they break the billion by Q2 2012.

In addition, running the business is not as expensive as search. They need to store user profiles and a lot of images. Video is outsourced to youtube and realtime updates are not so expensive (what is the history they maintain?).

Anyway, running a business requires to make money. So here is my call: What business model do you suggest for facebook to make money?

Content ads never worked for search. Could it work for FB? Or what else?

Tuesday, May 25, 2010

Count numbers

How do you count the number of ways a number can be expressed as a sum
of 2 or more numbers?

For eg. if the number is 5 , count=3 i.e 1+1+1+1+1, 4+1, 3+2
note 2+3 is same as 3+2

Monday, May 24, 2010

Detecting the dominant (>50%) symbol in a stream.

You are given a stream that you cannot hold in memory. At each instant you want to determine the dominant symbol observed in the stream (e.g. appearing more than 50% of times).

Sunday, May 23, 2010

Count in a range in O(1)

Given n integers in the range 0 to k, answers any query about how many of the n integers fall into a range [a b] in O(1) time. Make your own assumptions and build your own indexing data structures.

PS: I was used to ask this question during my interviews. Now no longer ;-)

Saturday, May 22, 2010

Sort a dictionary of variable lenght words

Assume you have a dictionary of k words. They have variable lengths, but the total number of symbols counted if we juxtapose all the words is n. Give an optimal sorting algorithm.

PS: this is a tricky question, with practical implication in information retrieval.

Friday, May 21, 2010

The perfect interview: Make your own assumptions

I am making a lot of interviews these days. So I wonder if there is a way to make the "perfect" interview. I say, probably no. How can I understand how good is a candidate in just one hour? Certain people are good in communication, other people are shy. Certain people are good team workers, other people are good as individual contributors. Certain people are good with numbers and symbolic computations, other people are good in describing methodologies. Certain people can have a bad day, other people prefer to leave for other places. And so on... So you want me to understand all these factors in just one hour? I say: No ways. Give me a couple of weeks to start with.

Anyway, interviews are important and you need to find a solution. So I follow three golden rules:

1) Many judgments are better than one. The candidate should be evaluated by many independent interviewers in a loop. It would be better if the interviewers express no judgment until the loop is closed to avoid influencing each others;

2) I always ask to myself: "Can I work with this candidate? Would (s)he help me in solving the problems we face day by day?"

My interviews are around some problem solving (you read my blog so you know this), a lot of algorithmic questions ;-), a lot of C++ coding and design patterns. In addition, machine learning, retrieval, and data mining are my areas of expertise so do expect to get some questions here. I am not very much impressed if you know all the recent academic papers or the books. I am very much interested about your intuitions. In fact, my third question is the most important one:

3) "How much creative is this candidate? How much can we learn from him in the future?"

The most interesting part of the interview is when we can discuss about hard problems
applied to real life and on very large dataset (up to petabytes of data). I describe the problem with one or two sentences and then tell to the candidate

Make your own assumptions

Wednesday, May 19, 2010

Tuesday, May 18, 2010

Sort again

We have N element array with k distinct keys. sort this array without using any extra memory.

Monday, May 17, 2010

BST

given a bst of n nodes, find two nodes whose sum is equal to a number k in O(n) time and constant space

Sunday, May 16, 2010

Google and the WI-FI Mapping

Interesting posting about Google WI-FI Mapping by the way of Alessio. He suggested that this is due to the need of geo-localize mobile users. I hope that they do not want to make this alternative use found on YouTube

Saturday, May 15, 2010

YourOpenBook

A new UX on the top of Facebook OpenGraph search API -- http://youropenbook.org/

Friday, May 14, 2010

Why Facebook's "Like" buttom is a real game changer?

These are some elements we discussed with a friend of mine in front of a good coffee.

Facebook "Like" is a real game changer for two different reasons:

1) FB enlarged the base of its data sources. Every time a user push the "Like" button on a partner site, they will know.

2) FB enlarged the base of its data sources. Every time a user load an external page in a partner site including the "Like" button, they will know. Even if you do not push the button.

We both agreed that 2) is the most important information, because you know a lot about real-time traffic.

Thursday, May 13, 2010

Partition a set (a bit harder)

Partition a set of numbers into two sets such that the difference between their sum is mininum and they have equal num of elements

Tuesday, May 11, 2010

Common substrings

Find the longest common subsequence of given N strings each having length between 0 to M

Monday, May 10, 2010

Evolution of Search

For a long time I thought that Search was a mature market, with Google and Microsoft the only two players remaining to fight.

Well, I was wrong. Facebook has a lot of data to search and they are the only one who can mine it. Try to search the volcano situation. Strangely enough they are not giving too much emphasis to this feature. So far ...

Sunday, May 9, 2010

Data analysis is the language of this age

Metric, data, numbers. Every theory must start with a measure.

Saturday, May 8, 2010

Friday, May 7, 2010

Minimum in two lists

You are given two sorted lists of size m and n. Give an O(log m+log n) time algorithm for computing the kth smallest element in the union of the two lists

Thursday, May 6, 2010

Optimal merge and operator AND in search

Given k sorted list merge them in optimal time. Assume that the total number of elements is n. Why this is useful for implementing the AND operator for a search engine?

(this is one of that questions that explains why basic algo knowledge is fundamental)

Wednesday, May 5, 2010

What direction is the stack growing?

You are working on a machine / compiler and you want to determine if the stack is growing towards increasing or decreasing addresses. What strategy would you use?

Tuesday, May 4, 2010

Bartz in London

I must confess that I like her very much: ""I don't need everybody to think I am an asshole. You think it's so much fun answering your questions? If I didn't think there was a good bottle of white wine at the end of it – I probably wouldn't do"

Monday, May 3, 2010

Facebook Searches Double – Words per Search to 3.5

The number of search conducted on Facebook doubled in the last year to 650 million searches. The average number of words per search has reached 3.5

Sunday, May 2, 2010

Google acquired a 3d desktop company


I wrote about my will to invest in a 3d desktop company. Google acquired one company, but they are not true 3d they simulate 3d into a 2d space.

Saturday, May 1, 2010

Oneriot is indexing public Facebook data

Now, of course, we’re only showing (indeed, only have access to) data that has been shared publicly by Facebook users. A user can restrict the visibility of these Likes on their Facebook profile. However, we’d be sidestepping the issue if we didn’t recognize that some users might be concerned that stuff they have shared on Facebook can now pop up on services like ours. Given that, we are rolling out this feature as a very limited bucket test today to assess users’ reactions and gather feedback. We love the new feature. And if users do too then we’ll roll it out to everyone at an appropriate speed.

Silently Facebook added open search API

https://graph.facebook.com/search?q=cnn.com&limit=1000 , change q=

Friday, April 30, 2010

Mugs

Can you pour exactly half of a mug of coffee from a mug filed to the brim?

Wednesday, April 28, 2010

Added a VectorSpace generator ...

Added a generator to the compressed vector space project. It's funny because I work on this coding just for the sake of coding. These are free coding sessions that I make at my favorite coffe shop in London from 8.15am to 9am.

People are telling me "so you work all the time". My point is that I do not consider this particular coding activity "a work". I make this just because is fun and just because I like it.

Studying, Coding is just fun. Fun like going to the gym (7.am-8am) or going to see a musical (9pm-..) don't you agree?

Tuesday, April 27, 2010

I like it a lot

The new feature allows any developer to drop a fairly simple piece of code into a site to create a two-way direct link with Facebook's network. If you have signed into Facebook, this third-party website will recognize who you are and feed anything you do there back into your Facebook profile.

Given Facebook's size and growth curve, it will be next to impossible for any major website to resist implementing the Open Graph. They simply cannot turn their back on the ability to leverage that massive an audience. All those users will be feeding their actions back to their Facebook friends, given the website's powerful viral promotion

Of course, it also means Facebook will control a treasure trove of information about you....


Monday, April 26, 2010

Finding the maximum sum in two sorted arrays

Given two sorted postive integer arrays A(n) and B(n) (let's say they are decreasingly sorted), we define a set S = {(a,b) | a \in A and b \in B}. Obviously there are n^2 elements in S. The value of such a pair is defined as Val(a,b) = a + b. Now we want to get the n pairs from S with largest values. in O(n).

Sunday, April 25, 2010

Number 6 and 7

If I give you 3 number 6, can you make a number 7?

Saturday, April 24, 2010

Sorted linked list into a binary search tree

Given a sorted lnked list construct a balanced binary search tree from it

Friday, April 23, 2010

Find the index of three numbers whose sum is closest to zero

given an array(unsorted) may contain negative numbers too, find the index of three numbers whose sum is closest to zero

Thursday, April 22, 2010

One in Four Countries Block Some Google Services

"Google's services are blocked or censored to some degree in one-fourth of the countries where it operates, the company said Monday."

Wednesday, April 21, 2010

Art1

Added art1 test to the compressed vector space. Here you have the code

Tuesday, April 20, 2010

Monday, April 19, 2010

62-63 = I

Can you move just one digit so that the above equation is correct?

Sunday, April 18, 2010

Ants and a segment

You have a segment with n ants over it. Each ant start to walk in a random chosen direction (right or left). When two ants collide they change the direction. What happens at the end?
Suppose that the ants move in a synchronous way. When it the end?

Saturday, April 17, 2010

Pages in a newspaper

You buy a newspaper and notice that page 8 and 21 are on the same sheet. Can you infer the total number of pages in the newspaper?

Friday, April 16, 2010

Set of intervals

Given a set of intervals and on interval i, return the set of all the intervals overlapping with i in optimal time

Wednesday, April 14, 2010

Number 2

How many numbers can you write by using 3 numbers 2 ?

Tuesday, April 13, 2010

Server allocation for different Online providers


Data is incomplete, but useful. Where is Microsoft, where is amazon, where is yahoo, etc?

Monday, April 12, 2010

Find the largest element in an interval

Given an array of n integers, find the k-th largest element in the interval [i, j]. Note that i, j, k are input parameters. What is the complexity.

Saturday, April 10, 2010

Yahoo+Microsoft +0.3, Google -0.4

Latest comscore for U.S. are out.

Microsoft's Bing scored the biggest increase, growing from 11.5 percent to 11.7 percent in March. Yahoo moved up slightly from 16.8 percent to 16.9 percent during the same period.

The Yahoo move is significant, if for no other reason than it stopped the six straight month losses in search share they experienced.

Google had the largest move, albeit downward, dropping from 65.5 percent search share to 65.1 percent.

Friday, April 9, 2010

Yahoo! to loose his CTO

Another yahoo executive left the company. This time the CTO. deja-vu.

Thursday, April 8, 2010

Random search in a random array, with duplicates

I already put this problem, but now assume that there are k elements with value x. What is the expected running time?

Suppose you have an array of random integers A[i] i = 0, ... , n-1. Suppose you adopt the following random search strategy for value x. Pick a random index i into A. If A[i] = x, then we terminate; otherwise, continue the search by picking a new random index into A. Note that we may examine a given element more than once.

Wednesday, April 7, 2010

Personal consideration about algorithms in Europe

Why I never went to U.S.? I love to _walk_ to the bar around the corner, having people that calls me by _name_. I love having my _coffe_ ready without ordering it, just because they know me. I love starting my day reading an algorithm book just sitting there with people around me while the City is waking up.

Tuesday, April 6, 2010

Ed Roberts, the father or modern PC died on April 1st

Henry Edward "Ed" Roberts (September 13, 1941 – April 1, 2010) was an American engineer, entrepreneur and medical doctor who designed the first commercially successful personal computer in 1975.[1] He is most often known as the "the father of the personal computer".[2] He founded Micro Instrumentation and Telemetry Systems (MITS) in 1970 to sell electronics kits to model rocketry hobbyists, but the first successful product was an electronic calculator kit that was featured on the cover of the November 1971 issue of Popular Electronics.[3] The calculators were very successful and sales topped one million dollars in 1973.[4]

A brutal calculator price war left the company deeply in debt by 1974. Roberts then developed the Altair 8800 personal computer that used the new Intel 8080 microprocessor. This was featured on the cover of the January 1975 issue of Popular Electronics, and hobbyists flooded MITS with orders for this $397 computer kit.

Bill Gates and Paul Allen joined MITS to develop software and Altair BASIC was Microsoft's first product. Roberts sold MITS in 1977 and retired to Georgia where he farmed, studied medicine and eventually became a small-town doctor.

Monday, April 5, 2010

AI Application Programming (Programming Series)

This is a good book, if you like to know a bit more about artificial intelligence with real programming examples in C.

Sunday, April 4, 2010

Saturday, April 3, 2010

Facebook and data privacy

From PeteSearch: "I'm sorry to say that I won't be releasing the Facebook data I'd hoped to share with the research community. In fact I've destroyed my own copies of the information, under threat of a lawsuit from Facebook.... ? From my conversations with technical folks at Facebook, there seems to be a real commitment to figuring out safeguards around the widespread availability of this data. They have a lot of interest in helping researchers find ways of doing worthwhile work without exposing private information."

Friday, April 2, 2010

February Search: Bing Gains at Yahoo's Expense



The major search engines continue their recent market share trend; Google capturing the lion’s share and steady, Bing continuing to gain ground while Yahoo! continues on its downward trend.

Thursday, April 1, 2010

Happy Birthday, Apple


Apple started 34 years ago. This was the IFirst, the first product ever releases.

Tuesday, March 30, 2010

Random in place

Can you prove that the below code produces a random permutation, where RANDOM(i, n) produces a random integer in (i, n]

RANDOMIZE-IN-PLACE(A)
n = length[A]
for i =0 ... n-1
do swap (A[i], A[RANDOM(i, n)])

Monday, March 29, 2010

Leaving Yahoo!

I always like creativity. Looking for new opportunities?

Sunday, March 28, 2010

Do you run or walk when it is raining?

Suppose you need to traverse a Leicester square in London. It's raining. Do you run or walk if you want to minimize the amount of rain you get?

Saturday, March 27, 2010

Number of inversions

Given an array A[0,.... n] of integer an inversion is defined as i < j and A[j] < A[i]. Suppose to randomly permute A. Give an algorithm that computes the number of inversion in A.

Friday, March 26, 2010

Approximate intersection of two lists

Search engines mantains a word index made up by a dictionary of words and, for each work a list of documents containing the. For instance

impossible -> 343, 5, 63459, 4, ....., 32
mission -> 3449, 558, ...., 49

Suppose the two lists are very long. For instance, the word 'impossible' can be contained in 100*10^6 documents, while the word mission can be contained in 50*10^6 documents.

1) return the documents containing the words 'impossible mission' (documents must contain both the words)
2) what is the complexity?
3) can you accellerate the computation?
4) how to compute the size of the lists intersection?
5) can you estimate this size in a fast way?

Thursday, March 25, 2010

Buying a new car

My ex-Personal Assistant she was always suggesting to buy a new car.

So I am evaluating this strategy. Every week I go to car dealer, I test a couple of cars and, If i find one that I like, a sell my current car c_i for amount of money m_i and a buy a new one c_i+1 for a new amount of money m_i+1. Note that going to the car dealer has a fixed cost say cd.

My strategy is to find the best car ever, but I want to estimate what is the cost for achieving this goal.

Wednesday, March 24, 2010

Generate a random permutation of an array of intergers

You are given an array of n integers containing numbers from 1 to n (with repetition), generate a random permutation of the array. The distribution should be uniform.

Tuesday, March 23, 2010

Tossing coins (ufff again?)

Suppose you flip a fair coin n times. What is the longest streak of consecutive heads that you
expect to see?

Monday, March 22, 2010

Points in a plane

given 2N points in a plane. Pair up to obtain N distinct pairs such that total sum of paired distances is minimum. N can be atmost 50.

Sunday, March 21, 2010

Least Square Methods: simple form of regression

Sometime simple solutions are the most effective. If you have a series of events e1, ... en, where each ei appears occ(ei) times with probability p(ei), you can represent the events in a Cartesian plan with axis containing the occurrences and the probability, respectively. Then you can imagine a straight line y = m x + b such that the distances from the line to the points in the space is minimized. Surprisingly enough, this method is straightforward has a closed solution and is very effective to predict the behavior of unseen points in the space.

Saturday, March 20, 2010

Language detection

Suppose you need to write a module for detecting the language in the text. What approach would you adopt?

Friday, March 19, 2010

Spam detection

Suppose you need to classify a set of web pages basing just on the textual content. What approach would you adopt?

Thursday, March 18, 2010

Traffic lights and probabilities

A classical probability problem. A traffic light has a mean waiting time of 14 seconds and a variance of 4 second. What is the probability of waiting more than 21 seconds?

P(X>21) = 1-P(X<=21) ; 14 / 4 = 1.5 this is the standardization of the distribution , then..

Wednesday, March 17, 2010

A ticketing system

There are b available seats in a cinema and n customers. The room is dark. At the beginning all the seats are empty. A customer enters the cinema and randomly selects a seat. If it is available, then it will be assigned to that customer. Otherwise, he will randomly select another seat. How many selections are necessary in average to get all the seat assigned?

PS: if you find this very similar to the hash collision problem, well that is not by chance.

Tuesday, March 16, 2010

Document processing with score and cost function

Suppose you have a stream of document that you are evaluating. Each document has a score function s(i) >= 0, and a cost function c(i) >= 0. if you analyze a document i you have to pay the cost c(i) and you get access to the associated score (i). The goal is to maximize the score, but minimize the cost. What strategy would you adopt?

Sunday, March 14, 2010

Random search in random array

Suppose you have an array of random integers A[i] i = 0, ... , n-1. Suppose you adopt the following random search strategy for value x. Pick a random index i into A. If A[i] = x, then we terminate; otherwise, continue the search by picking a new random index into A. Note that we may examine a given element more than once.

What is the expected number of indexes analyzed?

Saturday, March 13, 2010

A compressed vector space

Sometime is useful to represent a vector in a compressed form. This is particularly useful when you want to represent a vector of features in machine learning. The simplest data structure is an un-ordered vector of pairs (id, value), ... (id, value). The vector can be sorted on-the-fly for particular operations such as the intersection of two vectors. Here you have the code.

Friday, March 12, 2010

Sort different runs of integers

Let S be a sequence of n elements divided into n/k subsequences each of length where all of the elements in any subsequence are larger than all of the elements of a preceding subsequence and smaller than all of the elements of a succeeding subsequence. Can you give an algorithm for sorting S? What is the optimal complexity?

Thursday, March 11, 2010

Water jugs

Suppose that you are given n red and n blue water jugs, all of different shapes and sizes. All red jugs hold different amounts of water, as do the blue ones. Moreover, for every red jug, there is a blue jug that holds the same amount of water, and vice versa.
It is your task to find a grouping of the jugs into pairs of red and blue jugs that hold the same amount of water. To do so, you may perform the following operation: pick a pair of jugs in which one is red and one is blue, fill the red jug with water, and then pour the water into the blue jug. This operation will tell you whether the red or the blue jug can hold more water, or if they are of the same volume. Assume that such a comparison takes one time unit. Your goal is to find an algorithm that makes a minimum number of comparisons to determine the grouping. Remember that you may not directly compare two red jugs or two blue jugsWater

Wednesday, March 10, 2010

List cache-aware

Build a list that maximize the use of cache hierarchies. In modern computer a cache miss is a very negative situation, just like page faults some year ago.