Google Code jam Solutions: Problem A. Store Credit

Problem

You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide will consist of the two integers indicating the positions of the items in your list (smaller number first).

Input

The first line of input gives the number of cases, N. N test cases follow. For each test case there will be:

  • One line containing the value C, the amount of credit you have at the store.
  • One line containing the value I, the number of items in the store.
  • One line containing a space separated list of I integers. Each integer P indicates the price of an item in the store.
  • Each test case will have exactly one solution.

Output

For each test case, output one line containing “Case #x: ” followed by the indices of the two items whose price adds up to the store credit. The lower index should be output first.

Limits

5 ≤ C ≤ 1000
1 ≤ P ≤ 1000

Small dataset

N = 10
3 ≤ I ≤ 100

Large dataset

N = 50
3 ≤ I ≤ 2000

Sample

Input Output
3
100
3
5 75 25
200
7
150 24 79 50 88 345 3
8
8
2 1 9 4 4 56 90 3
Case #1: 2 3
Case #2: 1 4
Case #3: 4 5

C++ Solution:

/*
Author      :   Sreejith Sreekantan
Description :   https://code.google.com/codejam/contest/351101/dashboard#s=p0

*/

#include 
#include 
#include 
#include 

using namespace std;

int main(int argc, char const *argv[])
{

    int numOfTestInstances;
    cin >> numOfTestInstances;
    std::vector itemWeight;
    for (int testInstanceNum = 0; testInstanceNum < numOfTestInstances; ++testInstanceNum)
    {
        int limit;
        cin >> limit;

        int numOfItems;
        cin >> numOfItems;

        itemWeight.clear();
        itemWeight.reserve(numOfItems);

        for (int itemNum = 0; itemNum < numOfItems; ++itemNum)
        {
            cin >> itemWeight[itemNum];
        }

        cout << "Case #" << testInstanceNum + 1 << ": ";

        for (int i = 0; i < numOfItems; ++i)
        {
            for (int j = i + 1; j < numOfItems; ++j)
            {
                if (itemWeight[i] > limit)
                {
                    break;
                }
                if (itemWeight[j] > limit)
                {
                    continue;
                }
                if (itemWeight[i] + itemWeight[j] == limit)
                {
                    if (i < j)
                    {
                        cout << i + 1 << " " << j + 1 << endl;
                    }
                    else
                    {
                        cout << j + 1 << " " << i + 1 << endl;
                    }
                }
            }
        }

    }
    return 0;
}

Python Solution:

#! /usr/bin/python

numOfInstances = int(raw_input())

for x in xrange(1,numOfInstances+1):
    limit = int(raw_input())
    numOfItems = int(raw_input())
    d = dict()
    items = [int(x) for x in raw_input().split()]
    for y in xrange(1,numOfItems+1):
        if items[y-1] not in d:
            d[items[y-1]] = set() 
        d[items[y-1]].add(y)

     print d

    for x in d.keys():
        if x <= limit:
            index = d[x].pop()
            if (limit-x) in d and len(d[limit-x])>0:
                index2=d[limit-x].pop()
                d[limit-x].add(index2)
                print min(index, index2), max(index, index2)
            d[x].add(index)


Google Code jam Solutions: Problem B. Reverse Words

Problem

Given a list of space separated words, reverse the order of the words. Each line of text contains L letters and W words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.

Input

The first line of input gives the number of cases, N.
N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.

Output

For each test case, output one line containing “Case #x: ” followed by the list of words in reverse order.

Limits

Small dataset

N = 5
1 ≤ L ≤ 25

Large dataset

N = 100
1 ≤ L ≤ 1000

Sample

Input Output
3
this is a test
foobar
all your base
Case #1: test a is this
Case #2: foobar
Case #3: base your all

C++ Solution:

/*
    Author      :   Sreejith Sreekantan
    Description :   Problem B. Reverse Words https://code.google.com/codejam/contest/351101/dashboard#s=p1
                    
*/

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;


int main(int argc, char const *argv[])
{
    
    int numOfTestInstances;
    cin >> numOfTestInstances;
    
    for (int testInstanceNum = 0; testInstanceNum < numOfTestInstances; ++testInstanceNum)
    {
        istringstream in;
        string s;
        cin >> ws;
        getline(cin ,s);
        replace(s.begin(), s.end(), ' ', '\n');
        in.str(s);
        
        stack stack_s_rev;

        while (in >> s)
        {
            stack_s_rev.push(s);
        }
        cout << "case #" << testInstanceNum+1 << ": ";
        while(!stack_s_rev.empty())
        {
            cout << stack_s_rev.top() << " ";
            stack_s_rev.pop();
        }
        cout << endl;

    }
    return 0;
}


Google Code jam Solutions: Problem A. Alien Language

Problem

After years of study, scientists at Google Labs have discovered an alien language transmitted from a faraway planet. The alien language is very unique in that every word consists of exactly L lowercase letters. Also, there are exactly D words in this language.

Once the dictionary of all the words in the alien language was built, the next breakthrough was to discover that the aliens have been transmitting messages to Earth for the past decade. Unfortunately, these signals are weakened due to the distance between our two planets and some of the words may be misinterpreted. In order to help them decipher these messages, the scientists have asked you to devise an algorithm that will determine the number of possible interpretations for a given pattern.

A pattern consists of exactly L tokens. Each token is either a single lowercase letter (the scientists are very sure that this is the letter) or a group of unique lowercase letters surrounded by parenthesis ( and ). For example: (ab)d(dc) means the first letter is either a or b, the second letter is definitely d and the last letter is either d or c. Therefore, the pattern (ab)d(dc) can stand for either one of these 4 possibilities: add, adc, bdd, bdc.

Input

The first line of input contains 3 integers, L, D and N separated by a space. D lines follow, each containing one word of length L. These are the words that are known to exist in the alien language. N test cases then follow, each on its own line and each consisting of a pattern as described above. You may assume that all known words provided are unique.

Output

For each test case, output

Case #X: K

where X is the test case number, starting from 1, and K indicates how many words in the alien language match the pattern.

Limits

 

Small dataset

1 ≤ L ≤ 10
1 ≤ D ≤ 25
1 ≤ N ≤ 10

Large dataset

1 ≤ L ≤ 15
1 ≤ D ≤ 5000
1 ≤ N ≤ 500

Sample

Input Output
3 5 4
abc
bca
dac
dbc
cba
(ab)(bc)(ca)
abc
(abc)(abc)(abc)
(zyx)bc
Case #1: 2
Case #2: 1
Case #3: 3
Case #4: 0

C++ Solution:

/*
    Author      :   Sreejith Sreekantan
    Description :   Problem A. Alien Language (https://code.google.com/codejam/contest/90101/dashboard#s=p0)

*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;


#define rep(v,N) for(int v=0; v<n; v++)="" #define="" <span="" class="hiddenSpellError" pre="define " data-mce-bogus="1">rep2(v,M,N) for(int v=M; v<n; v++)="" #define="" for(v,c)="" for(__typeof(c.begin())="" v="C.begin();" v!="C.end();" ++v)="" vi="" std::vector<int="">
#define vll std::vector
#define pb push_back
#define Sort(C) std::sort(C.begin(), C.end())
#define RSort(C) std::sort(C.rbegin(), C.rend())
#define Copy(ans,out) copy(ans.begin(),ans.end(), ostream_iterator<__typeof(ans[0])>(out, " "))

// #define SMALL
#define LARGE

int main(int argc, char const *argv[])
{
    freopen("a.in", "rt", stdin);
    // freopen("a.out", "wt", stdout);
#ifdef SMALL
    freopen("as.in", "rt", stdin);
    freopen("as.out", "wt", stdout);
#endif

#ifdef LARGE
    freopen("al.in", "rt", stdin);
    freopen("al.out", "wt", stdout);
#endif

    unsigned int L, D, N;
    cin >> L >> D >> N;

    std::vector dict(D);
    std::vector inp(D);
    rep(i, D)
    {
        cin >> dict[i];
    }
    rep(i, N)
    {
        cin >> inp[i];
        replace(inp[i].begin(), inp[i].end(), '(', '[');
        replace(inp[i].begin(), inp[i].end(), ')', ']');
        // cout << inp[i]<< endl;
        int c = 0;
        rep(j, D)
        {
            if (regex_match(dict[j], regex(inp[i])) ) c++;
        }
        cout << "Case #" << i+1 << ": " << c << endl;
        
    }
    return 0;
}

Google Code jam Solutions: Problem A. Minimum Scalar Product

Problem

You are given two vectors v1=(x1,x2,…,xn) and v2=(y1,y2,…,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+…+xnyn.

Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.

Input

The first line of the input file contains integer number T – the number of test cases. For each test case, the first line contains integer number n. The next two lines contain n integers each, giving the coordinates of v1 and v2 respectively.

Output

For each test case, output a line

Case #X: Y

where X is the test case number, starting from 1, and Y is the minimum scalar product of all permutations of the two given vectors.

Limits

 

Small dataset

T = 1000
1 ≤ n ≤ 8
-1000 ≤ xi, yi ≤ 1000

Large dataset

T = 10
100 ≤ n ≤ 800
-100000 ≤ xi, yi ≤ 100000

Sample

Input Output
2
3
1 3 -5
-2 4 1
5
1 2 3 4 5
1 0 1 0 1
Case #1: -25
Case #2: 6

C++ Solution:

/*
    Author      :   Sreejith Sreekantan
    Description :   Problem A. Minimum Scalar Product
                    (https://code.google.com/codejam/contest/32016/dashboard#s=p0)

*/

#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int main(int argc, char const *argv[])
{
    // freopen("as.in", "rt", stdin);
    // freopen("as.out", "wt", stdout);
    int n;
    cin >> n;
    int c;
    int tmp;
    vector v1, v2;
    int a, b;
    for(int a=0; a<n; a++)=""    ="" {=""        ="" v1.clear();="" v2.clear();="" cin="">> c;
        for(int b=0; b<c; b++)=""        ="" {=""            ="" cin="">> tmp;
            v1.push_back(tmp);
        }
        for(int b=0; b<c; b++)=""        ="" {=""            ="" cin="">> tmp;
            v2.push_back(tmp);
        }
        sort(v1.begin(),v1.end());
        sort(v2.rbegin, v2.rend());

        long long sumofprod = inner_product(v1.begin(), v1.end(), v2.begin(), (long long)0);
        cout << "Case #" << a + 1 << ": " << sumofprod << endl;
    }
    return 0;
}


Project Euler Problem 9: Solution in C++

Special Pythagorean triplet

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

/*
    Author      :   Sreejith Sreekantan
    Description :   
                    Special Pythagorean triplet
                    Problem 9

                    A Pythagorean triplet is a set of three natural numbers, 
                    a < b < c, for which, a2 + b2 = c2

                    For example, 32 + 42 = 9 + 16 = 25 = 52.

                    There exists exactly one Pythagorean triplet for which 
                    a + b + c = 1000.
                    Find the product abc.

    Eg: for Pythagorean triplets:
    (3, 4, 5 )  (5, 12, 13)     (8, 15, 17)     (7, 24, 25)
    (20, 21, 29)    (12, 35, 37)    ( 9, 40, 41)    (28, 45, 53)
    (11, 60, 61)    (16, 63, 65)    (33, 56, 65)    (48, 55, 73)
    (13, 84, 85)    (36, 77, 85)    (39, 80, 89)    (65, 72, 97)
    (20, 99, 101)   (60, 91, 109)   (15, 112, 113)  (44, 117, 125)
    (88, 105, 137)  (17, 144, 145)  (24, 143, 145)  (51, 140, 149)
    (85, 132, 157)  (119, 120, 169)     (52, 165, 173)  (19, 180, 181)
    (57, 176, 185)  (104, 153, 185)     (95, 168, 193)  (28, 195, 197)
    (84, 187, 205)  (133, 156, 205)     (21, 220, 221)  (140, 171, 221)
    (60, 221, 229)  (105, 208, 233)     (120, 209, 241) (32, 255, 257)
    (23, 264, 265)  (96, 247, 265)  (69, 260, 269)  (115, 252, 277)
    (160, 231, 281)     (161, 240, 289)     (68, 285, 293)

*/
#include 
#include 


using namespace std;

void pythagoreanTriplet(unsigned long sum)
{
    unsigned long m, n, s=sum;
    s /= 2;
    unsigned long sqrt_s = sqrt(s);

    for (int m = 1; m <= sqrt_s ; ++m)
    {
        if (s%m==0)
        {
            n = (s/m)-m;
            if (m>n)
            {
                cout << sum << " : " << pow(m,2)-pow(n,2) << " "  
                << 2*m*n << " "  << pow(m,2)+pow(n,2) << endl;
            }
        }
    }

}


int main(int argc, char const *argv[])
{
    unsigned long sums[] = {12, 30, 40, 56, 70, 84, 90, 126, 132, 
                            144, 176, 182, 1000};
    for (int i = 0; i < sizeof(sums)/sizeof(unsigned long); ++i)
    {
            pythagoreanTriplet(sums[i]);
    }

    cout << " the end..." << endl;
    return 0;
}


C++ Brain Teaser : Virtual Destructor

Hi All,

This time I plan to explain to you a C++ brain teaser I came across. With no further adieu, let me get directly to the question:

C++ Brain Teaser : Virtual Destructor Question

What is the problem with this code, if any?

(Assurance from me: this code will compile and execute fine. ie. no compilation error)

.

.

.

.

.

.

Hope you have put enough thought on it. Some might have already cracked it. For the rest of the folks, let me reveal it.

Yes, this code has some serious problem at run-time. If not compilation-error, what is it?

You are right; the worst nightmare, memory leak! But where is it leaking?

Let pause that question for a few minutes to discuss something in C++ language.

In a scenario where a Child class inherits a Parent class, when a Child object is created, first the Parent-Constructor is invoked and then the Child-Constructor and when the Child object is destroyed, first the Child-Destructor is invoked and then the Parent-Destructor is executed.

In our above program, we use a variable of type “Parent” to point to a “Child” object. Lets use below program to check if the order of invocation of constructor and destructor is followed in this case.

virtual Destructor program with cout

Output of the above program is:

Screen Shot 2014-02-04 at 2.33.23 PM

As you can see, here the child destructor is not invoked, which means, whatever we coded in the Destructor method of Child class is not executed. In our main program, we allocate an array of memory in the Constructor of Child and delete the same in its Destructor. So our main program successfully allocates an array of memory but don’t delete it, which will result in Memory Leak.

So we have answered our question. Now lets see how we can avoid it.

Here is where Virtual-Destructor comes for help. Make the destructor of “Parent” class virtual and this issue is solved.

New implementation of “Parent”:

Virtual Destructor New Parent impNew output:

Virtual Destructor new output

To put it straight, virtual destructor forces the parent class to check for child class destructors and executes it.

Use a virtual destructor if you ever expect a derived class to be destroyed through a pointer to the base class to ensure that the destructor of the most derived classes gets called.

It’s a good practice to make the destructors of all interface classes, ie. any class with at-least one virtual method, as virtual.

C++ build tool: boost bjam intro

Reference Material : HERE

Source code (hello_sree.cc):

Screen Shot 2014-02-26 at 2.56.26 PM

build file (jamroot.jam or Jamroot): Screen Shot 2014-02-26 at 7.00.22 PM

Now in terminal, change the present working directory to the folder where the code and build-file resides. Run any of the below commands:

Screen Shot 2014-02-26 at 7.01.05 PMORScreen Shot 2014-02-26 at 7.00.45 PMORScreen Shot 2014-02-26 at 7.01.52 PMORScreen Shot 2014-02-26 at 7.03.09 PM

Ensure you have a space between “hello_sree.cc” and “;” in the build file. Otherwise you will get the below error:Screen Shot 2014-02-26 at 7.03.23 PM

Screen Shot 2014-02-26 at 7.03.33 PM

You will get this message at the successful run:Screen Shot 2014-02-26 at 7.04.01 PMYou will see a bin folder with a hierarchy of folders and executable file created as part of successful build of our program