Friday, July 1, 2011

给定一个array和一个固定值sum,

给 定一个array和一个固定值sum,
找出array中加和等于sum的最少元素个数
array中肯定有{1}这个元素,除了{1}这个元素只能用一次意外,其他元素可以重复使用

例如 arr={90,30,18,15,10,5,3,2,1} sum=32
则返回2, 即最小的组合是两个数{30,2}


Java version:

public int solve(int[] a, int sum) {
        HashSet<Integer> set = new HashSet<Integer>();
        for (int i : a) set.add(i);
        set.remove(1);
        
        int[] m = new int[sum+1];
        m[1] = 1;
        for (int i=2; i<=sum; i++) {
            m[i] = sum+1;
            for (int j : set) {
                if (j<=i) m[i] = Math.min(m[i], 1+m[i-j]);
            }
        }
        
        return m[sum];
    }



带输出的,不用分配那么多空间,只要记住parent index就行。

public int solve2(int[] a, int sum) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for (int i : a) if (i!=1) numbers.add(i);
        
        int[][] m = new int[sum+1][2];
        m[0] = new int[]{0, -1};
        m[1] = new int[]{1, 0};
        for (int i=2; i<=sum; i++) {
            m[i] = new int[]{sum+1, -1};
            for (int j : numbers) {
                if (j<=i && m[i][0] > 1+m[i-j][0]) {
                    m[i][0] = 1+m[i-j][0];
                    m[i][1] = i - j;
                }
            }
        }
        
        print(m, sum);
        return m[sum][0];
    }
    
    private void print(int[][] m, int sum) {
        for (int i=sum; i>0; ) {
            System.out.print(i - m[i][1] + " ");
            i = m[i][1];
        }
        System.out.println();
    }
  

Thursday, June 30, 2011

G的一道题 分析

http://www.mitbbs.com/article_t/JobHunting/31903469.html

grass的解法完全正确。

[2, 0, 1, 0] 如何得到 (1, 2, 3, 4)的某个排列?
推出第一个元素一定是(1, 2, 3, 4)中排名第三的数,也就是3
然后就有点递归的意味了。
[0, 1, 0] 如何得到(1, 2, 4)的某个排列?
推出第一个元素一定是(1, 2, 4)中排名第一的数,也就是1
[1, 0]如何得到(2,4)的某个排列?
推出第一个元素一定是(2, 4)中排名第二的数,也就是4
[0]如何得到(2)的某个排列?
这个是trival case了。实际上,Count array的最后一个元素永远是0,属于无效信息。

最后推出原数组是[3, 1, 4, 2]

Let Count be the count array, let Array be the original array.
用伪代码实现如下

Create ordered set S, and add 1, 2, ..., n to S

for (i = 0; i < n; i++)
{
    int index = Count[i] + 1;
    Array[i] = S.FindKth(index);
    
    S.RemoveKth(index); 
}

/*
如果RemoveKth同时返回值,如同stack的pop操作那样,还可以简化为
for (i = 0; i < n; i++)
{
    int index = Count[i] + 1;
    Array[i] = S.RemoveKth(index);
}
*/

问题的难点在于如何实现S,使得RemoveKth操作最多是lg(n)的
如果用数组,移动操作是O(n)的
如果用链表,定位操作是O(n)的
都不符合要求

怎么办呢?实际上lg(n)本身就是一个很大的提示,你可以联想到binary search, 
quick sort, binary tree, BST, heap, 分治,递归... 一定是套用其中某个或几个的
思想。

如果考虑BST,从第i个元素这个要求,你可以想到一道经典题:
如何在log(N)时间找到BST的第i个元素?

中序遍历的方法是O(N)的,怎么办?空间换时间!(类似思路有O(1)时间取得stack的最
小值)

方法就是每个节点附加左子树的元素个数,用递归或迭代。假定BST是平衡的,这样FindKth就是log(N)的。

但是这只是FindKth是log(N), RemoveKth呢?

grass巧妙的解决了这个问题,RemoveKth和FindKth的代码几乎一样,只是多了个删除
操作。但是,无须真正删除节点!树还是那棵一开始就创建好的平衡BST, 包含了自然
数1到n。只需要标记节点被删除就可以了,同时需要更新受影响的节点的左子树元素个
数。

代码如下,index从1开始
Node remove(Node node, int index)
{
    if (node.numOfLeftChildren >= index)
    {
        // left
        node.numOfLeftChildren--;
        return remove(node.left, index);
    }
    else if (node.numOfLeftChildren + 1 == index && !node.removed)
    {
        // current
        node.removed = true;
        return node;
    }
    else
    {
        // right
        return remove(node.right, index - node.numOfLeftChildren - (node.
removed ? 0 : 1));
    }
}

也可以用迭代,因为是尾递归。
此外上述代码最好加上判断node是否null, 可以处理index越界而查找失败的情况。

自此问题得到圆满解决。

总结:
1) Try a simple example first.
2) Use pseudo code first, then focus on the details.
3) 多尝试几种不同的数据结构,比较各自的优缺点
4) 化归到经典题(数学中化归的思想, 比如一道DP题能否化归到背包问题)
5) 空间换时间的策略
6) 对树的操作一定和递归密切相关
7) 标记节点状态而不破坏原始结构的思想(比如图的遍历)
8) 其它...

Monday, April 18, 2011

c++ cast Nice Post

http://stackoverflow.com/questions/103512/in-c-why-use-static-castintx-instead-of-intx

Friday, April 15, 2011

ASCII Pronunciation Rules for Programmers

http://www.codinghorror.com/blog/2008/06/ascii-pronunciation-rules-for-programmers.html

Common perl pronunciations:
- # arrow
= # fat arrow
= # spaceship operator 
~ # tilde
# # hash 
! # not , bang
@ # at, ampersand
$ # dollar
[] # square brackets
() # brackets
{} # curlies, curly brackets
` # back tick
"" # double quote
' # single quote
| # pipe
* # asterix, star
# left angle bracket, right angle bracket
In perl there are operators that have identical pronunciation, eg "==" and "eq" which differ by the context they give to. Both pronounced equals.
I rarely pronounce symbols them the same unless I'm actually dictating. Usually, when paring or discussing code, it's just a matter of describing the intent or effect. 
rj on June 12, 2008 2:44 AM


Wednesday, April 13, 2011

Good Lisp study post

Good Lisp study post

http://abhishek.geek.nz/docs/features-of-common-lisp/


[转载]Common Lisp中使用字符串动态调用函数

 original post:
http://blog.csdn.net/albert_lee/archive/2011/04/14/6322730.aspx

Common Lisp中使用字符串动态调用函数 收藏 应用场景:一个统计查询的后端程序,根据查询名称字符串分别调用相应的处理函数。 一般的处理方法,可以用一个全局的注册表,将名称字符串与函数名对应起来。但是,lisp程序员是很懒惰的,既然lisp环境本身已经提供了名称注册的机制,为什么还要自己写一套呢?事实上,Lisp环境本身的核心就在于 namespace 。 简单的说解决办法如下:



这是第一步的实现,但是没有进行异常处理,例如调用一个不存在的函数,系统会报异常。 待续。。

Sunday, April 10, 2011

meetbsd 2010

http://meetbsd.org/category/meetbsd-2010

Friday, April 8, 2011

Max Panlidrome problem.

http://blog.csdn.net/g9yuayon/archive/2008/06/21/2574781.aspx

Tuesday, April 5, 2011

C语言OPEN函数详解


http://blog.csdn.net/xuefu2008/archive/2009/10/13/4662167.aspx


 http://www.slideshare.net/dimitar9/unix-open

算法和数据结构词典

original post: http://coolshell.cn/articles/1499.html 我们知道,在编程的世界里,主要就是两个事,用一定的算法去处理一定的数据。算法可以理解为业务逻辑流程,而数据自然一定是按某种结构来存放,这就是数据结构。我们知道,数据结构的修改一定会导致算法的修改,我们也知道,数据结构直接关系到了整个程序的繁简性,高效性。而算法则是关系到数据处理的时间、空间性能,以及日后的扩展和维护。这两个东西是计算机科班出生的人或是需要学习编程的人必需要注意的两件头等大事。 下面这个网站,由 Software and Systems Division, Information Technology Laboratory 创建。 http://xlinux.nist.gov/dads/ 这是一个关于算法,算法技术,数据结构,系统架构等相关问题的一个词典。其中,算法包括了一些常见的算法,比如: Ackermann’s function ,一些算法问题包括了 traveling salesman(销售员出差问题) and Byzantine generals(拜占庭将军问题),还有一些关于这些问题,算法的 实现链表 以及更多的信息。而索引页包括 领域索引 和 类型索引.

Friday, April 1, 2011

monte carlo simulation interview question

据说是一个monte carlo simulation的模拟,老毛子跟我说的,我不懂monte carlo。 一个系统有2000个cpu,有若干个任务(>>2000)等待执行,每个任务消耗CPU时间不等, 从几分钟到几小时都有。每个任务在结束的时候,都会产生一个输出文件,大小从几K 到100G不等。注意输出的文件大小跟运行时间没有关系。任务之间也是相互独立的。这 些文件产生之后通过网络写入到一个NFS server。整个过程就是这样。 现在这个系统的瓶颈在NFS的写入速度上。如果有大并发同时写NFS的时候,比如说超过 100个concurrent writers,NFS会崩溃,所有写入失败。 问怎样能提高这个系统的性能?这里的提高性能是指在不增加额外NFS的情况下,最大 限度的提高NFS的平均写入速率。 Answer:先用一些短的CPU任务去跑~~ 星星@GZ#杂(3165281) 01:21:19 跑到NFS挂,多挂几次~~就能得到统计概率的任务长短分布和I/O分布~~ 星星@GZ#杂(3165281) 01:21:46 然后根据这个样本得到的概率,来调度实际任务集的执行情况~~

Find most appearenced words in a file. Word Cound

http://www.cplusplus.com/forum/general/14560/

Thursday, March 31, 2011

CalculateNumberOfOnes

/*
回忆去年的一道Google笔试题(搜索算法的剪枝优化)
2007-04-07 01:21
这个题目的英文原题是:
Consider a function which, for a given whole number n, returns the number of ones required when writing out all numbers between 0 and n.
For example, f(13)=6. Notice that f(1)=1. What is the next largest n such that f(n)=n?
翻译过来大体是这样:
有一个整数n,写一个函数f(n),返回0到n之间出现的"1"的个数。比如f(13)=6,现在f(1)=1,问下一个最大的f(n)=n的n是什么?

为什么f(13)=6, 因为1,2,3,4,5,6,7,8,9,10,11,12,13.数数1的个数,正好是6.


*/
import java.util.HashMap;
import java.util.Map;

/**
* @author Kevin
*/
public class CalculateNumberOfOnes {
//存储已经检查过的符合条件的f(n)
static Map treeNodeOKcache = new HashMap();
private int currentSize = 0;

//private int maxValue = Integer.MAX_VALUE;//2147483647
private int maxTestValue = 40000000;

public void getNextNum(int n){

n = n<=1?1:n ; /* * 说明当前没有计算过 */ if(0 == currentSize){ //f(1) = 1 currentSize = 1; treeNodeOKcache.put(String.valueOf(1),String.valueOf(1)); } /* * f(n+1) = f(n) + fs(n+1); * 计算本次fs(n+1)的结果 */ for(int i=2;i 0 ){
//模除10
int mod = n%10;
if ( mod == 1 )
count++;
n = n/10;
}
return count;
}

public static void main(String[] args){
CalculateNumberOfOnes instance = new CalculateNumberOfOnes();
long start = System.currentTimeMillis();
instance.getNextNum(0);
System.out.println("satisfy condition num is ="+treeNodeOKcache.size());
System.out.println(" total spent "+(System.currentTimeMillis()-start)+"ms used!");
}

}

Saturday, March 26, 2011

brain teaser. Probability.

某城市发生了一起汽车撞人逃跑事件。该城市只有两种颜色的车,蓝色15%,绿色85%。
事发时有一个人在现场看见了,他指证是蓝车。但是根据专家在现场分析,当时那种条
件能看正确的可能性是80%。
那么,肇事的车是蓝车的概率到底是多少?

Conditional probability, joint probability.

B: the car is blue P(B) = 0.15
S: claim a car is blue
P(S) = P(B) * 0.8 + P(-B) * 0.2 = 0.15 * 0.8 + 0.85 * 0.2
P(BS)= P(B)*0.8=0.15 * 0.8
P(B|S) = P(BS)/P(S) = 41.37%

Palantir interview question: phone interview.

http://www.palantir.com/

given int[] in, generate int[] out, out[i]= product of every element of in except
in[i],canot use divede mark (/), O(n) time required

/**
* c[i] = A[0]*A[1]*..*A[i]
* d[i] = A[n]*A[n-1]*..*A[i]
*
* and c[0] = a[0], d[n]=a[n];
*
* then B[i] = c[i-1] * d[i+1]
*
* @return b
*/
public static final int[] multiply(int[] a) {
if (a.length==1)
return a;

int n = a.length-1;
int[] b = new int[n+1];
int[] c = new int[n+1];
int[] d = new int[n+1];

c[0] = a[0];
d[n] = a[n];

for (int i=1;i<=n;i++) {

c[i] = c[i-1] * a[i];
d[n-i] = d[n-i+1] * a[n-i];
}

b[0] = d[1];
b[n] = c[n-1];
for (int i=1; i<=n-1; i++) {
b[i] = c[i-1] * d[i+1];
}
return b;
}

Thursday, March 24, 2011

Singleton Pattern

definition:

The singleton Pattern ensures a class has only one instance, and provides a global point of access to it


public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Synchronized Singleton getInstance() { if (uniqueInstance == null) {
synchronized
uniqueInstance = new Singleton(); return uniqueInstance;
}


But , synchronized is expensive.
the only time synchronization is relevant is the first time through this method. In other words, once we've set the uniqueInstance variable to an instance of Singleton, we have no further need to synchronize this method. After the first time through, synchronization is totally unneeded overhead!





/*
Creational Pattern: SINGLETON
Author: Rajesh V.S
Language: C++
Email: rajeshvs@msn.com
*/

#include


using namespace std;

class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor

}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}

void Singleton::method()
{
cout << "Method of the singleton class" << endl; } int main() { Singleton *sc1,*sc2; sc1 = Singleton::getInstance(); sc1->method();
sc2 = Singleton::getInstance();
sc2->method();

return 0;
}







For other c++ singleton pattern code: check here:
http://www.yolinux.com/TUTORIALS/C++Singleton.html

atoi bug free C cod. My atoi.

int atoi( char* pStr )
{
int iRetVal = 0;

if ( pStr )
{
while ( *pStr && *pStr <= '9' && *pStr >= '0' )
{
iRetVal = (iRetVal * 10) + (*pStr - '0');
pStr++;
}
}
return iRetVal;
}

Difference between static in C and static in C++??

Difference between static in C and static in C++??
http://stackoverflow.com/questions/943280/difference-between-static-in-c-and-static-in-c

C++ has one more use, static within a class. When used there, it becomes a single class variable that's common across all objects of that class. One classic example is to store the number of objects that have been instantiated for a given class.

class Plop
{
static int x; // This is a member of the class not an instance.

public:
static int getX() // mehtod is a member of the class.
{
return x;
}
};

int Plop::x = 5;






________________
The use of static at the file scope to restrict access to the current translation unit is deprecated in C++, but still acceptable in C.

Instead, use an unnamed namespace




----------------
Note that the use of static to mean "file scope" (aka namespace scope) is only deoprecated by the C++ Standard for objects, not for functions. In other words,:

To quote Annex D of the Standard:

The use of the static keyword is deprecated when declaring objects in namespace scope.

use "grep" command to find txt files containing telephone number.

use "grep" command to find txt files containing telephone number.
telephone number format could be:
"***-*******"
"**********"
"*** *******"
"***-***-****"

How to write it?

numbers are 3 digits (\d{3}), space or dash [\s-], 3 digits (\d{3}), space or dash [\s-], 4 digits (\d{4}).


grep '\d{3}[\s\-]{0,1}\d{3}[\s\-]{0,1}\d{4}' infile.txt

Tuesday, March 22, 2011

Interview question: how to OO design a spell checker

question:
How to use OO Design to build a spell checker,and how to dispatch job to developers.

Simple solution
simple factory +singleton pattern

interface Check{
checkWord();
checkGrammar();
checkTense();
checkXX..()
...
}

class checkFactory{
if(Chinese)
return new ChinesCheck();//if singleton return ChinesCheck.getInstance(
);
else
......///other languages instances
}

class ChineseCheck implement Check {
...
}

class EbglishCheck implement Check {
...
}

each program do one language work...