Tuesday, July 12, 2016

#codingexercise
Given two sorted linked lists, find their intersection as a new list
For example 1,2,3,4,5,6 with 2,4,6,8 should result in 2,4,6
Node sortedIntersect(node a, node b)
{
Node dummy;
dummy.next = null;
Node tail = dummy;
While (a != null && b != null)
{
If(a.data ==b.data){
Copy(tail.next, a.data);
A=a.next;
B=b.next;
Tail = tail.next;
}else if (a.data < b.data){
a.=a.next;
}else{ b = b.next;}
}
Return dummy.next;
}

Cloudian Storage and s3 api example 

Most online documentation skip over the example of a programmatic access to Cloudian storage saying that what works for AWS works for Cloudian. It’s true that both support S3 api but there are some caveats. First, the key/secret pairs are not universal. Cloudian servers cut their own keys and do not make them available to others.  Second the direct REST API calls to the server do not appear to be straightforward as the AWS s3 3 documentation statesWhile it might be possible to capture the packets from tools such as s3cmd in order to dump the API calls made, the s3 sdks seem to work seamlessly. So here are some examples to show how to use them. 

First an example with a tool: 
Download the s3cmd tool  and modify the configuration file  with these values 
[default] 
access_key = your_access_key_goes_here 
host_base =  cloudianserver.com 
host_bucket = %(bucket)s.cloudianserver.com 
secret_key = your_secret_key_here 
website_endpoint = http://%(bucket)s.cloudianserver.com/ 

Then issue “s3cmd ls” to see the following kind of output: 
2016-06-24 17:55  s3://bucket1 
2016-06-24 17:55  s3://bucket2 
2016-04-22 17:32  s3://bucket3 

Second try the boto sdk: 
def listS3(): 
    import boto 
    import boto.s3 
    import sys 
    import os 
    import math 
    from boto.s3.key import Key 
    try: 
       from urllib.parse import quote_plus 
    except: 
       from urllib import quote_plus 
    try: 
       from ConfigParser import RawConfigParser 
    except: 
       from configparser import RawConfigParser 

    parser = RawConfigParser() 
    parser.read('config.ini') 

    Cloudian_ACCESS_KEY_ID = parser.get('Cloudian', 'key') 
    Cloudian_SECRET_ACCESS_KEY = parser.get('Cloudian', 'secret') 

    conn = boto.connect_s3( 
    aws_access_key_idCloudian_ACCESS_KEY_ID, 
    aws_secret_access_key = Cloudian_SECRET_ACCESS_KEY, 
    host = ‘cloudianserver.com') 
   bucket_name = 'bucket1' 
    bucket = conn.get_bucket(bucket_name, validate=False) 
    print('bucket_list='+repr(bucket.list())) 
    for item in bucket.list(): 
        print(repr(item)) 

listS3() 

This should give an output like following: 
<Key: bucket1,1424338922-Tulips.jpg> 
<Key: bucket1,1424344182-Hydrangeas.jpg> 

#data structure discussion : https://1drv.ms/w/s!Ashlm-Nw-wnWk1i1yfh79Kw_ki7O 

Monday, July 11, 2016

#codingexercise
Generate a 2D distance matrix for the nearest distance from each cell as city location to  a parking spot that appears as one or more occupied cells.
 static int[][] getParkingDistanceGrid(int cityLength, int cityWidth, int[] parkingXCoordinates, int[] parkingYCoordinates) {
        var d = new int[cityWidth][];
        for (int i = 0; i < cityWidth; i++)
            d[i] = new int[cityLength];
        for (int i = 0; i < cityWidth; i++)
        {
            for (int j = 0; j < cityLength; j++)
                {
                    var parkingdistances = new List<int>();
                    for (int count = 0; count < parkingXCoordinates.Length; count++)
                    {
                        int distance = GetDistance(i+1, j+1, parkingXCoordinates[count], parkingYCoordinates[count]);
                        parkingdistances.Add(distance);
                    }
                    int min = INT_MAX;
                    for (int k = 0; k < parkingXCoordinates.Length; k++)
                        if (parkingdistances[k] < min)
                           min  = parkingdistances[k];
                    d[i][j] = min; 
                }
        }
        return d;
    }

    static int GetDistance(int r1, int c1, int r2, int c2)
    {
        int deltax = r1 - r2;
        deltax = deltax > 0 ? deltax : 0-deltax;
        int deltay = c1 - c2;
        deltay = deltay > 0 ? deltay : 0-deltay;
        return deltax + deltay;        

    }

Generate a recommendation list of courses taken by the social circle of a user. The recommendation must include courses taken by the members of her social circle but not by her. It must be ranked by the number of attendees to the course. A social circle consists only of the persons direct friends and their direct friends.
public List<string> getRankedCourses(string user) {
    var coursePopularity = new Dictionary<string, int>();
    var circle = new List<string>();
    
    var direct = getDirectFriendsForUser(user);
    circle.AddRange(direct);
    foreach (var friend in direct){
        if (friend != user){
        var directForFriend = getDirectFriendsForUser(friend);
        directForFriend.Remove(user);
        circle.AddRange(directForFriend);
        }
    }
    
    foreach (var person in circle)
    {
        var attended = getAttendedCoursesForUser(person);
        foreach(var course in attended)
        {
            if (!coursePopularity.ContainsKey(course))
            {
                coursePopularity.Add(course,1);   
            }
            else
            {
                coursePopularity[course] += 1;   
            }
        }
    }
    
    foreach(var attending in getAttendedCoursesForUser(user))
    {
     coursePopularity.Remove(attending);   
    }
    List<KeyValuePair<string, int>> ranked = coursePopularity.ToList();
    ranked.Sort(
    delegate(KeyValuePair<string, int> pair1,
    KeyValuePair<string, int> pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
    );
    
    var recommendations = new List<string>();
    foreach (var kvp in ranked)
        recommendations.Add(kvp.Key);
    recommendations.Reverse();
    return recommendations;

}
#codingexercise
test whether an integer is BigIndian or LittleIndian
bool IsLittleIndian()
{
int c = 1;
char * ptr = reinterpret_cast<char*>&c;
return *ptr & 0x1;
}

#codingexercise
Generate a 2D distance matrix for the nearest distance from each cell as city location to  a parking spot that appears as one or more occupied cells.
 static int[][] getParkingDistanceGrid(int cityLength, int cityWidth, int[] parkingXCoordinates, int[] parkingYCoordinates) {
        var d = new int[cityWidth][];
        for (int i = 0; i < cityWidth; i++)
            d[i] = new int[cityLength];
        for (int i = 0; i < cityWidth; i++)
        {
            for (int j = 0; j < cityLength; j++)
                {
                    var parkingdistances = new List<int>();
                    for (int count = 0; count < parkingXCoordinates.Length; count++)
                    {
                        int distance = GetDistance(i+1, j+1, parkingXCoordinates[count], parkingYCoordinates[count]);
                        parkingdistances.Add(distance);
                    }
                    int min = INT_MAX;
                    for (int k = 0; k < parkingXCoordinates.Length; k++)
                        if (parkingdistances[k] < min)
                           min  = parkingdistances[k];
                    d[i][j] = min; 
                }
        }
        return d;
    }

    static int GetDistance(int r1, int c1, int r2, int c2)
    {
        int deltax = r1 - r2;
        deltax = deltax > 0 ? deltax : 0-deltax;
        int deltay = c1 - c2;
        deltay = deltay > 0 ? deltay : 0-deltay;
        return deltax + deltay;        

    }

Generate a recommendation list of courses taken by the social circle of a user. The recommendation must include courses taken by the members of her social circle but not by her. It must be ranked by the number of attendees to the course. A social circle consists only of the persons direct friends and their direct friends.
public List<string> getRankedCourses(string user) {
    var coursePopularity = new Dictionary<string, int>();
    var circle = new List<string>();
    
    var direct = getDirectFriendsForUser(user);
    circle.AddRange(direct);
    foreach (var friend in direct){
        if (friend != user){
        var directForFriend = getDirectFriendsForUser(friend);
        directForFriend.Remove(user);
        circle.AddRange(directForFriend);
        }
    }
    
    foreach (var person in circle)
    {
        var attended = getAttendedCoursesForUser(person);
        foreach(var course in attended)
        {
            if (!coursePopularity.ContainsKey(course))
            {
                coursePopularity.Add(course,1);   
            }
            else
            {
                coursePopularity[course] += 1;   
            }
        }
    }
    
    foreach(var attending in getAttendedCoursesForUser(user))
    {
     coursePopularity.Remove(attending);   
    }
    List<KeyValuePair<string, int>> ranked = coursePopularity.ToList();
    ranked.Sort(
    delegate(KeyValuePair<string, int> pair1,
    KeyValuePair<string, int> pair2)
    {
        return pair1.Value.CompareTo(pair2.Value);
    }
    );
    
    var recommendations = new List<string>();
    foreach (var kvp in ranked)
        recommendations.Add(kvp.Key);
    recommendations.Reverse();
    return recommendations;

}

Sunday, July 10, 2016

#codingexercise
Given n ropes of different length, combine them into a single rope,such that total cost is minimum. You can tie two ropes at a time,and cost of tying is sum of length of ropes.
Int getmin (list <int> Len)
{
Int cost = 0
Heap h = build_heap(len)
While (h.size () >1)
{
First = extract_min (h)
Second = extract_min (h)
Cost += first + second
H.insert (first+second );
}
Return cost;
}
Given a “2 x n” board and tiles of size “2 x 1″, count the number of ways to tile the given board using the 2 x 1 tiles. A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e., as 2 x 1 tile.
Let the number of ways be GetCount(n)
If the tile is placed vertically, the problem reduces to GetCount(n-1)
If the tile is placed horizontally, the problem reduces to GetCount(n-2)
This is Fibonacci series
int GetCount(int n)
{
if (n <=1) return n;
return GetCount(n-1) + GetCount(n-2);
}
A car factory has two assembly lines, each with n stations.
Each station is dedicated to some sort of work. Cars may proceed from one station to other on the same line or transfer across another line. There is a cost to transfer as well as cost for entry and exit on each line in terms of minutes. Compute the minimum time it will take to build a car.

int GetCarTime(int [,] A, int [,] t, int numStations,  ref int[] entry, ref int[] exit) // A, entry and exit have two rows each and correspond to the static costs
{
int T1[numStations];
int T2[numStations];
T1[0] = entry[0] + A[0,0];
T2[0] = entry[1] + A[1,0];
for (i = 1; i < numStations; ++i)
{
T1[i] = mint(T1[i-1] + A[0,i], T2[i-1] +t[1,i] + A[0,i]);
T2[i] = min(T2[i-1] + A[1,i], T1[i-1] +t[0,i] +A[1,i]);
}
return min(T1[numStations-1] + exit[0], T2[numStations-1] + exit[1]);
}
Given an array of random numbers, Push all the zero’s of a given array to the right end of the array in minimum possible swaps. Order of appearance doesn’t matter. Print the minimum swaps needed to do so.

input : {1, 9, 8, 0, 0, -2, 0, 1, 6}.output :swaps : 2 (-2 as it is and swap 1 and 6 from first two zeros. )
Int GetMinShifts(List<int>A, int N)
{
int count = 0;
Int swaps = 0;
for (int i =0; i < N; i++)
    for ( int j = N-1; j > i; j--){
    if (A[i] == 0 && A[j] != 0){
          int temp = A[j];
          A[j] = A[i];
          A[i] = temp;
          swaps++;
         break;
     } 
}
return swaps;
}

convert big indian to little indian
List<byte> ToLittleIndian(List<byte> num)
{
var ret = new List<byte>();
for (int i = num.Count-1; i >=0; i--)
      ret.Add(num[i]) // at initial position
return ret;
}