2013年3月16日 星期六

Fibonacci Factor Problem


Story
Given a number K, find the smallest Fibonacci number that shares a common factor( other than 1 ) with it. A number is said to be a common factor of two numbers if it exactly divides both of them. 
Output two separate numbers, F and D, where F is the smallest fibonacci number and D is the smallest number other than 1 which divides K and F.
Input Format  
First line of the input contains an integer T, the number of testcases.
Then follows T lines, each containing an integer K.
Output Format
Output T lines, each containing the required answer for each corresponding testcase.

Sample Input 
3
3
5
161
Sample Output
3 3
5 5
21 7

Explanation 
There are three testcases. The first test case is 3, the smallest required fibonacci number  3. The second testcase is 5 and the third is 161. For 161 the smallest fibonacci numer sharing a common divisor with it is 21 and the smallest number other than 1 dividing 161 and 7 is 7.

Constraints :
1 <= T <= 5
2 <= K <= 1000,000
The required fibonacci number is guranteed to be less than 10^18.


My Answer: (I am no sure if it is correct.)
#include "stdafx.h"
#include <iostream>

using namespace std;

int fb(int i);

int _tmain(int argc, _TCHAR* argv[])
{
 int count = 0;
 cin >> count;
 int *input = new int[count];
 for (int i = 0; i<count; i++)
 {
  cin >> input[i];
 }

 for (int i = 0; i<count; i++)
 {
  int k = 1;
  int fbNumber = 1;
  while (fbNumber <= input[i]) 
  {
   for (int x=2; x<=fbNumber; x++)
   {
    if (fbNumber % x == 0 && input[i] % x == 0 )
    {
     cout << input[i] << " " << fbNumber << endl;
    }
   }

   k++;
   fbNumber = fb(k);
  };
 }

 return 0;
}

int fb(int i)
{
 if (i<=1)
  return 1;

 if (i==2)
  return fb(1);

 return fb(i-1) + fb(i-2);
}


Reference:
https://amazon.interviewstreet.com/challenges/dashboard/#problem/4fd653336df28

2013年3月15日 星期五

Candies giving problem

Story

Alice is a teacher of kindergarten. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her usual performance. Alice wants to give at least 1 candy for each children. Because children are somehow jealousy. Alice must give her candies according to their ratings subjects to for any adjacent 2 children if one's rating is higher than the other he/she must get more candies than the other. Alice wants to save money so she wants to give as few as candies in total.

Input

The first line of the input is an integer N, the number of children in Alice's class. Each of the followingN lines contains an integer indicates the rating of each child.

Output

On the only line of the output print an integer describing the minimum number of candies Alice must give.

Sample Input

3
1
2
2

Sample Output

4




My Answer (I am no sure if it is correct.)
#include "stdafx.h"
#include <iostream;

using namespace std;

class child {
public:
    child() : m_candy(1) {}
    child(int rating) : m_rating(rating), m_candy(1) {}

    int Rating() { return m_rating; }
    void setRating(int rate) { m_rating = rate; }
    int Candy() { return m_candy; }
    void setCandy(int candies) { m_candy = candies; }

private:
    int m_rating;
    int m_candy;
};

void showCandies(int[], int);

int _tmain(int argc, _TCHAR* argv[])
{
    const int count = 10;
    int childs_rating[] = {9,2,3,3,3,2,1,1,3,4};

    showCandies(childs_rating, count);

    cin.get();
 return 0;
}

void showCandies(int* rating, int count)
{
    child* childs = new child[count];
    for(int i=0;i<count;i++)
    {
        childs[i].setRating(rating[i]);
    }

    bool run = false;
    do
    {
        run = false;

        for(int i=0;i<count-1;i++)
        {
            if( childs[i].Rating() ; childs[i+1].Rating() && childs[i].Candy() <= childs[i+1].Candy())
            {
                run = true;
                childs[i].setCandy(childs[i+1].Candy() + 1);
            }

            if( childs[i+1].Rating() ; childs[i].Rating() && childs[i+1].Candy() <= childs[i].Candy())
            {
                run = true;
                childs[i+1].setCandy(childs[i].Candy() + 1);
            }
        }

        for(int i=0;i<count;i++)
        {
            cout << childs[i].Candy() << '\t';
        }
        cout << endl;
    } while(run);

    delete[] childs;
}



Reference:
http://stackoverflow.com/questions/11292913/candies-interviewstreet

How to sum the Integers from 1 to N.

Question:
How to sum the Integers from 1 to N.

Answer:
#include "stdafx.h"
#include 

using namespace std;

int allPlus(int n);

int _tmain(int argc, _TCHAR* argv[])
{
    const int n = 100;
    int sum = allPlus(n);

    cout << sum << endl;

    std::cin.get();
 return 0;
}

int allPlus(int n)
{
    if (n == 0)
        return 0;

    return n + allPlus(n-1);
}


Advanced Answer:
Change function allPlus below for O(1) time complexity
int allPlus(int n)
{
    return (1 + n) * n / 2;
}


* All answer just my answer, I am no sure if it is correct.

2013年3月14日 星期四

Find duplicated numbers in an array.

Question:
Given an array with N+M items, each item is number between 1 to N, please give a O(M+N) solution to print all duplicated numbers.

Answer:
#include "stdafx.h"
#include 

using namespace std;

void printDuplicate(int arr[], int nm, int n);

int _tmain(int argc, _TCHAR* argv[])
{
    const int n = 10, m = 5;
    const int nm = n+m;
    int arr[nm] = {1,2,3,4,5,6,7,8,9,10,1,2,3,4,2};

    printDuplicate(arr, nm, n);

    std::cin.get();
    return 0;
}

void printDuplicate(int arr[], int nm, int n)
{
    int* pArray = new int[n];
    for (int i=0; i<n; i++)
    {
        pArray[i] = 0;
    }

    for (int i=0; i<nm; i++)
    {
        int value = arr[i];
        pArray[value]++;

        if (pArray[value] == 2)
            cout << value << endl;
    }
}


Advanced Question:
Give an answer without using extra space.

Answer:
Change function printDumplicate as below.
void printDuplicate(int arr[], int nm, int n)
{
    int pArray = 0;

    for (int i=0; i 0)
            cout << value << endl;

        pArray |= (1 << (value-1));
    }
}


Thinking:
If you use bits of an integer variable to keep all status, remember that there are 32 bits only.


* All answer just my answer, not the best one.

How to swap two variables without using a temporary variable.

Question:
How to swap two variables without using a temporary variable.


Anser:
There are 3 methods to tackle this issue.

1. XOR
a = a ^ b;
b = a ^ b;
a = a ^ b;

2. Addition and Minus
a = a + b;
b = a - b;
a = a - b;


3. Multiplying and Division
a = a * b;
b = a / b;
a = a / b;


Thinking:
It is possible overflow if you use method 2 and 3.

Why method 1 work? Because N ^ N = 0 and N ^ 0 = N, so you can think
a' = a ^ b;
b' = a' ^ b 
   = a ^ b ^ b 
   = a ^ 0 
   = a;
a'' = a' ^ b' 
    = a ^ b ^ a 
    = 0 ^ b 
    = b;



Reference:
http://emn178.pixnet.net/blog/post/92113175
http://emn178.pixnet.net/blog/post/92389195-%E9%9D%A2%E8%A9%A6%E5%B8%B8%E8%A6%8B%E7%A8%8B%E5%BC%8F%E8%80%83%E9%A1%8C-%E7%A8%8B%E5%BC%8F%E5%AF%A6%E5%81%9A


2013年3月10日 星期日

internal and external iterator

What different between internal and external iterator?


external iterator:
It is a separate class that can step through its container/collection.
So you can control the logic to get the item what you want.


ex.
std::vector<int> v;
for(vint::iterator it=v.begin(), it!=v.end(); ++i)
    std::cout << *it << "\n";




internal iterator:
It is implemented with member functions to step through.
You only can get the items in turn, but it is more easy to use than external iterator.


ex.
MACRO_FOREACH(v)
{
    std::cout << v << "\n";
}


2013年1月16日 星期三

Output Debug String

As we know, we can use API OutputDebugString to show string on output window, like,

OutputDebugString(" This is debug message. ");
OutputDebugStringW(L" This is debug message. ");

You also can attach some variable to the output string.

wchar_t* world = L"world";
wchar_t* szBuffer = new wchar_t[512];
wsprintf(szBuffer, _T(" Hello %s \n"),  world);
OutputDebugString(szBuffer);
delete[] szBuffer;

or

wchar_t* message = L"world !";

wchar_t* str = L" Hello ";
wchar_t* buffer = new wchar_t[sizeof(str)+sizeof(message)+1];
wcscpy(buffer, str);
wcscat(buffer, message);
OutputDebugStringW(buffer);


or

float value = 100;
wchar_t* szBuffer = new wchar_t[512];
wsprintf(szBuffer, L" My math grade is %d \n",   (int)value);
OutputDebugString(szBuffer);
delete[] szBuffer;

or

float value = 100;
char* szBuffer = new char[512];
sprintf(szBuffer, L" My math grade is %f \n",  value);
OutputDebugStringA(szBuffer);
delete[] szBuffer;




2013年1月15日 星期二

[Platform Builder] Output Logging Message to File

As we all know, there are lots of useful message shown in output window.
The window doesn't has huge buffer to keep all of messages.













We can try to output it to file and check it later.
Click Target->Debug Message Options->Check Send to file and specify file path









2012年12月8日 星期六

[AOSP] Build Android Framework

Just brief note the steps to build AOSP

PC: i5-3210, 8G RAM, 750G HD
OS: Ubuntu 10.04 64 bits on VM WorkStation 8.0
Code Name: Jelly Bean
Tag: android-4.1.2_r1

Set up environment  ===========
1. Install Ubuntu 10.04 64 bits.
       http://releases.ubuntu.com/lucid/

2. Install Python.
$ sudo apt-get install python.
 
3. Install make
$ sudo apt-get update
$ sudo apt-get install gcc g++ build-essential
 
4. Install JDK6
$ sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk

 * If you got message below in step 4:
   Package sun-java6-jdk is not available, but is referred to by another package.
   This may mean that the package is missing, has been obsoleted, or
   is only available from another source
   E: Package 'sun-java6-jdk' has no installation candidate

 * Use following command instead
$ sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy multiverse"
$ sudo apt-get update
$ sudo apt-get install sun-java6-jdk

5. Install git
$ sudo apt-get install git-core

6. Install Required Package
$ sudo apt-get install git-core gnupg flex bison gperf build-essential zip curl zlib1g-dev libc6-dev lib32ncurses5-dev ia32-libs x11proto-core-dev libx11-dev lib32readline5-dev lib32z-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc

7. Configuring USB Access
$ sudo gedit /etc/udev/rules.d/51-android.rules

 * Paste following text into the editing file and replace <username> to actual username

# adb protocol on passion (Nexus One)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e12", MODE="0600", OWNER="<username>"
# fastboot protocol on passion (Nexus One)
SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", ATTR{idProduct}=="0fff", MODE="0600", OWNER="<username>"
# adb protocol on crespo/crespo4g (Nexus S)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e22", MODE="0600", OWNER="<username>"
# fastboot protocol on crespo/crespo4g (Nexus S)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e20", MODE="0600", OWNER="<username>"
# adb protocol on stingray/wingray (Xoom)
SUBSYSTEM=="usb", ATTR{idVendor}=="22b8", ATTR{idProduct}=="70a9", MODE="0600", OWNER="<username>"
# fastboot protocol on stingray/wingray (Xoom)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="708c", MODE="0600", OWNER="<username>"
# adb protocol on maguro/toro (Galaxy Nexus)
SUBSYSTEM=="usb", ATTR{idVendor}=="04e8", ATTR{idProduct}=="6860", MODE="0600", OWNER="<username>"
# fastboot protocol on maguro/toro (Galaxy Nexus)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e30", MODE="0600", OWNER="<username>"
# adb protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d101", MODE="0600", OWNER="<username>"
# fastboot protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d022", MODE="0600", OWNER="<username>"
# usbboot protocol on panda (PandaBoard)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d00f", MODE="0600", OWNER="<username>"
# usbboot protocol on panda (PandaBoard ES)
SUBSYSTEM=="usb", ATTR{idVendor}=="0451", ATTR{idProduct}=="d010", MODE="0600", OWNER="<username>"
# adb protocol on grouper (Nexus 7)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e42", MODE="0600", OWNER="<username>"
# fastboot protocol on grouper (Nexus 7)
SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="4e40", MODE="0600", OWNER="<username>"


  * After you save the file, execute following command.
    $ sudo chmod a+r /etc/udev/rules.d/51-android.rules

8. Setting up ccache
$ export USE_CCACHE=1


Download source  ============
1. Create a bin/ directory in home directory and make it included in path.
$ mkdir ~/bin
$ PATH=~/bin:$PATH

2. Download the Repo script
$ curl https://dl-ssl.google.com/dl/googlesource/git-repo/repo > ~/bin/repo
$ chmod a+x ~/bin/repo

3. Create a working directory, the name is up to you.
$ mkdir WORKING_DIRECTORY
$ cd WORKING_DIRECTORY

4. Run repo init
$ repo init -u https://android.googlesource.com/platform/manifest

5. Check out branch
$ repo init -u https://android.googlesource.com/platform/manifest -b android-4.1.2_r1

6. Start to download
$ repo sync

7. Verifying Git Tags, I don't know what the step for.
$ gpg --import

  * Paste following text, then enter Ctrl-D

-----BEGIN PGP PUBLIC K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MX
LWBGWE0znfRrnczI5p49i2YZJAjyX1P2WzmScK49CV82dzLo71MnrF6fj+Udtb5+
OgTg7Cow+8PRaTkJEW5Y2JIZpnRUq0CYxAmHYX79EMKHDSThf/8AAwUIAJPWsB/M
pK+KMs/s3r6nJrnYLTfdZhtmQXimpoDMJg1zxmL8UfNUKiQZ6esoAWtDgpqt7Y7s
KZ8laHRARonte394hidZzM5nb6hQvpPjt2OlPRsyqVxw4c/KsjADtAuKW9/d8phb
N8bTyOJo856qg4oOEzKG9eeF7oaZTYBy33BTL0408sEBxiMior6b8LrZrAhkqDjA
vUXRwm/fFKgpsOysxC6xi553CxBUCH2omNV6Ka1LNMwzSp9ILz8jEGqmUtkBszwo
G1S8fXgE0Lq3cdDM/GJ4QXP/p6LiwNF99faDMTV3+2SAOGvytOX6KjKVzKOSsfJQ
hN0DlsIw8hqJc0WISQQYEQIACQUCSedYRAIbDAAKCRDorT+BmrEOeCUOAJ9qmR0l
EXzeoxcdoafxqf6gZlJZlACgkWF7wi2YLW3Oa+jv2QSTlrx4KLM=
=Wi5D
-----END PGP PUBLIC KEY BLOCK-----


Build   ===================
1. Set up environment
        $ . build/envsetup.sh

2. Choose a Target
        $ lunch full-eng

3. Build
        $ make -j4

The building process is done if you see message below.
Install system fs image: out/target/product/generic/system.img


Run on emulator  ===========
1. Boot up emulator.
        $ emulator


Reference:
http://source.android.com/source/index.html

[AOSP] make: *** [out/host/common/obj/JAVA_LIBRARIES/smali_intermediates/smaliLexer.java]

Problem:
When I built Android Framandroid-4.1.2_r1 on Ubuntu, I got the error message below.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Vector.<init>(Vector.java:111)
at java.util.Vector.<init>(Vector.java:124)
at org.antlr.analysis.DFA.createTransitionTableEntryForState(DFA.java:551)
at org.antlr.analysis.DFA.createStateTables(DFA.java:440)
at org.antlr.codegen.CodeGenerator.genLookaheadDecision(CodeGenerator.java:645)
at org.antlr.grammar.v3.CodeGenTreeWalker.block(CodeGenTreeWalker.java:2876)
at org.antlr.grammar.v3.CodeGenTreeWalker.rule(CodeGenTreeWalker.java:2382)
at org.antlr.grammar.v3.CodeGenTreeWalker.rules(CodeGenTreeWalker.java:1537)
at org.antlr.grammar.v3.CodeGenTreeWalker.grammarSpec(CodeGenTreeWalker.java:1441)
at org.antlr.grammar.v3.CodeGenTreeWalker.grammar_(CodeGenTreeWalker.java:461)
at org.antlr.codegen.CodeGenerator.genRecognizer(CodeGenerator.java:421)
at org.antlr.Tool.generateRecognizer(Tool.java:655)
at org.antlr.Tool.process(Tool.java:468)
at org.antlr.Tool.main(Tool.java:93)
make: *** [out/host/common/obj/JAVA_LIBRARIES/smali_intermediates/smaliLexer.java] Error 1
make: *** Waiting for unfinished jobs....



Solution:
Open file in  
external/smali/smali/Android.mk
Find the line 
$(GEN): PRIVATE_CUSTOM_TOOL = java -jar $(ANTLR_JAR) -fo $(dir $@) $<
Change it to 
$(GEN): PRIVATE_CUSTOM_TOOL = java -Xmx512m -jar $(ANTLR_JAR) -fo $(dir $@) $<


Reference:
https://groups.google.com/forum/#!msg/android-building/Or1C6bpq8GQ/xAEMEEM0gKAJ


**********************************************************************
Related issues:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

at java.lang.String.toCharArray(String.java:2726)
at java.util.zip.ZipOutputStream.getUTF8Bytes(ZipOutputStream.java:483)
at java.util.zip.ZipOutputStream.writeLOC(ZipOutputStream.java:348)
at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:179)
at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:92)
at com.android.tools.layoutlib.create.AsmGenerator.createJar(AsmGenerator.java:241)
at com.android.tools.layoutlib.create.AsmGenerator.generate(AsmGenerator.java:225)
at com.android.tools.layoutlib.create.Main.main(Main.java:98)
make: *** [out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar] Error 1
make: *** Deleting file `out/host/common/obj/JAVA_LIBRARIES/temp_layoutlib_intermediates/javalib.jar'

Edit the file
frameworks/base/tools/layoutlib/Android.mk

Reference:
https://groups.google.com/forum/?fromgroups=#!topic/android-building/D3QmmvsMRME