A Za, A Za, Fighting...

坚信:勤能补拙

插入排序: O(n^2),稳定排序

插入排序是在一个已经有序的小序列的基础上,一次插入一个元素。当然,刚开始这个有序的小序列只有1个元素,就是第一个元素。比较是从有序序列的末尾开始,也就是想要插入的元素和已经有序的最大者开始比起,如果比它大则直接插入在其后面,否则一直往前找直到找到它该插入的位置。如果碰见一个和插入元素相等的,那么插入元素把想插入的元素放在相等元素的后面。所以,相等元素的前后顺序没有改变,从原无序序列出去的顺序就是排好序后的顺序,所以插入排序是稳定的。

void
insert_sort(
int *array, int len)
{
    
int i, j, backup;
    
for(i=1; i<=len-1++i) {
        backup 
= array[i];
        
for(j=i-1; j>=0 && array[j]>backup; --j)
            array[j
+1= array[j];
        array[j
+1= backup;
    }
}

void
insert_sort_recursive(
int *array, int len)
{
    
if(len == 1)
        
return;

    insert_sort_recursive(array, len
-1);
    
int j, backup = array[len-1];
    
for(j=len-2; j>=0 && array[j]>backup; --j)
        array[j
+1= array[j];
    array[j
+1= backup;
}
posted @ 2011-07-27 17:17 simplyzhao 阅读(138) | 评论 (0)编辑 收藏
选择排序: O(n^2),非稳定排序

选择排序是给每个位置选择当前元素最小的,比如给第一个位置选择最小的,在剩余元素里面给第二个元素选择第二小的,依次类推,直到第n-1个元素,第n个元素不用选择了,因为只剩下它一个最大的元素了。那么,在一趟选择,如果当前元素比一个元素小,而该小的元素又出现在一个和当前元素相等的元素后面,那么交换后稳定性就被破坏了。比较拗口,举个例子,序列5 8 5 2 9, 我们知道第一遍选择第1个元素5会和2交换,那么原序列中2个5的相对前后顺序就被破坏了,所以选择排序不是一个稳定的排序算法。

void
select_sort(
int *array, int len)
{
    
int i, j, min;
    
for(i=0; i<len-1++i) {
        min 
= i;
        
for(j=i+1; j<=len-1++j)
            min 
= array[min] < array[j] ? min : j;
        
if(min != i)
            swap(array
+min, array+i);
    }
}
posted @ 2011-07-27 15:52 simplyzhao 阅读(111) | 评论 (0)编辑 收藏
冒泡排序: O(n^2)时间复杂度,稳定排序

冒泡排序就是把小的元素往前调或者把大的元素往后调。比较是相邻的两个元素比较,交换也发生在这两个元素之间。所以,如果两个元素相等,我想你是不会再无聊地把他们俩交换一下的;如果两个相等的元素没有相邻,那么即使通过前面的两两交换把两个相邻起来,这时候也不会交换,所以相同元素的前后顺序并没有改变,所以冒泡排序是一种稳定排序算法。

void
swap(
int *a, int *b) /* precondition: pointer a and b can't be the same */
{
    
*= *+ *b;
    
*= *- *b;
    
*= *- *b;
}

void
bubble_sort(
int *array, int len)
{
    
int i, j;
    
for(i=0; i<len-1++i) {
        
for(j=len-1; j>i; --j) {
            
if(array[j-1> array[j])
                swap(array
+j-1, array+j);
        }
    }
}
posted @ 2011-07-27 12:51 simplyzhao 阅读(120) | 评论 (0)编辑 收藏
下半年就要正式找工了,淘宝的实习因为爷爷去世提前告一段落。

书籍

编程语言: 《C和指针》,《C专家编程》,《C++ Primer》,《Effective C++》

数据结构与算法: 《算法导论》,《编程珠玑》,《编程之美》

操作系统: 《操作系统》,《深入理解计算机系统》,《Linux内核设计与实现》

计算机网络: 《TCP/IP详解 卷一》


编程实践

常用数据结构,排序,搜索,图算法,动态规划,字符串等

参考: PKU已做题目,何海涛的面试100题,IT面试题
posted @ 2011-07-27 10:52 simplyzhao 阅读(521) | 评论 (2)编辑 收藏
题目:

题目:在数组中,数字减去它右边的数字得到一个数对之差。求所有数对之差的最大值。例如在数组{2, 4, 1, 16, 7, 5, 11, 9}中,数对之差的最大值是11,是16减去5的结果。

对于分治算法,实现的不好,参考原作者的思路,对于左半部分最大值、右半部分最小值都是可以在递归里求出的,参考:

#include<stdio.h>
#include
<stdlib.h>
#include
<assert.h>
#include
<limits.h>
#define MAX(a, b) ((a)>(b) ? (a) : (b))
#define MIN(a, b) ((a)<(b) ? (a) : (b))
/*
 * 题目:
 * 在数组中,数字减去它右边的数字得到一个数对之差。求所有数对之差的最大值
 * 例如:
 * 在数组{2, 4, 1, 16, 7, 5, 11, 9}中,数对之差的最大值是11,是16减去5的结果
 
*/

int
naive_solution(
int *array, int len) //O(n^2)
{
    
int i, j, ret = INT_MIN;
    
for(i=0; i<len; ++i)
        
for(j=i+1; j<len; ++j)
            ret 
= MAX(ret, array[i]-array[j]);

    
return ret;
}

int
divide_and_conquer_solution(
int *array, int begin, int end) //O(nlogn)
{
    
if(begin >= end)
        
return INT_MIN;
    
int i, ret, left_ret, right_ret, left_max, right_min, mid;
    mid 
= begin + ((end-begin)>>1);
    left_ret 
= divide_and_conquer_solution(array, begin, mid);
    right_ret 
= divide_and_conquer_solution(array, mid+1, end);
    left_max 
= array[begin];
    
for(i=begin+1; i<=mid; ++i)
        left_max 
= MAX(left_max, array[i]);
    right_min 
= array[end];
    
for(i=end-1; i>mid; --i)
        right_min 
= MIN(right_min, array[i]);

    ret 
= MAX(left_ret, right_ret);
    ret 
= MAX(ret, left_max-right_min);
    
return ret;
}

int
dynamic_programming_solution(
int *array, int len) //O(n)
{
    
int i, cur_ret, cur_min;
    cur_ret 
= array[len-2- array[len-1];
    cur_min 
= MIN(array[len-2], array[len-1]);

    
for(i=len-3; i>=0--i) {
        cur_ret 
= MAX(cur_ret, array[i]-cur_min);
        cur_min 
= MIN(cur_min, array[i]);
    }

    
return cur_ret;
}

int
main(
int argc, char **argv)
{
    
int i, num, *data = NULL;
    scanf(
"%d"&num);
    assert(num
>=2);
    data 
= (int *)malloc(sizeof(int* num);
    assert(data 
!= NULL);
    
for(i=0; i<num; i++)
        scanf(
"%d", data+i);

    printf(
"naive_solution result: %d\n", naive_solution(data, num));
    printf(
"divide_and_conquer_solution result: %d\n", divide_and_conquer_solution(data, 0, num-1));
    printf(
"dynamic_programming_solution result: %d\n", dynamic_programming_solution(data, num));

    free(data);
    
return 0;
}

posted @ 2011-07-26 13:25 simplyzhao 阅读(562) | 评论 (0)编辑 收藏
导读:由于Joel Spolsky的双重身份(昔日耶鲁大学计算机系学长,今日Fog Creek软件公司的CEO),所以听听他的建议,对于当今无数困扰于就业压力的中国高校计算机专业学子来说,是大有裨益的。你们会发现,大多数建议,都在强调“软实力”的价值。

  如果你喜欢编程,那么你真是受到了上天的眷顾。你是非常幸运的少数人之一,能够以自己喜欢的事谋生。大多数人没有这么幸运。你认为理所当然的观念“热爱你的工作”,其实是一个很现代的概念。通常的看法是,工作是一种让人很不开心的事,你为了拿工资才不得不去上班。你工作的目的是为了攒下钱去干那些自己真正喜欢干的事,但是前提是你得等到65岁退休之后才行,而且还有不少条件。条件一,你的积蓄必须足够多;条件二,你没有老到走不动,你还有体力去干那些事情;条件三,你喜欢的事情不需要用到脆弱的膝盖、昏花的视力,也不要求你走上一里地不喘气,等等。

  我刚才说到哪里了?对了,我要提建议。

  毕业前练好写作

  如果不是Linus Torvalds不断地散布福音,请问Linux操作系统会成功吗?虽然他是一个非常聪明的计算机天才,但是Linux吸引来全世界一大批志愿者的真正原因却是Linus Torvalds的表达能力。他通过电子邮件和邮件列表用书面形式传播自己的想法,最终引起了所有人的注意。

  你听说过现在风靡一时的“极限编程”(Extreme Programming)吗?我在这个地方不谈我对极限编程的看法,我只说如果你听过这个词,那么原因就是它的倡导者都是一些非常有才华的作家和演说家。

  即使我们缩小范围,将目光局限在任何一个软件开发团体中,你也会发现该团体中最有权势和影响力的程序员正是那些表达能力强的程序员,他们无论是做书面表达还是做口头表达,都能够清晰、自如、具有说服力地传达观点。此外,长得高也有助于提升影响力,不过这个不取决于你。

  一个普通程序员与一个优秀程序员的区别,不在于他们懂得的编程语言谁多谁少,也不在于他们喜欢用Python语言还是喜欢用Java语言,而在于他们能否与他人交流思想。如果你能说服其他人,你的力量就可以得到放大。如果你能写出清晰的注释和技术规格说明书,其他程序员就能够理解你的代码,因此他们就能在自己的代码中使用,而不必重写。如果你做不到这一点,你的代码对其他人就没有价值。如果你能为最终用户写出清晰的使用手册,其他人就能明白你的代码是用来干什么的,这是唯一让别人明白你的代码有何价值的方法。SourceForge[ ]上有许多优美的、有用的代码,但是它们都像被埋葬了一样,根本没人来用,原因就是它们的作者没有写好使用说明(或者压根就没写)。这样一来就没有人知道他们的成果,他们杰出的代码就衰亡了。

  如果一个程序员不会用英语写作、没有良好的写作能力,我就不会雇他。如果你能写,不管你去哪家公司工作,你很快就会发现写作技术文档的任务会落到你头上,这意味着你已经开始在放大自己的影响力了,管理层正在注意到你。

  大学里有些课程被公认为“写作密集型”(writing intensive)课程,这就是说为了拿到学分,你必须写作多得可怕的文字。一定要去上这样的课程!不要管学科,只要这门课每周甚至每天都要你写东西,你就去上。

  你还可以动手写日记或者网志。你写得越多,写作就会变得越容易。写起来越容易,你就会写得越多。这是一个良性循环。

  毕业前学好C语言

  第二点我要讲的是C语言。请注意,我说的是C语言,而不是C++。虽然在实际使用中C语言已经越来越罕见,但是它仍然是当前程序员的共同语言。C语言让程序员互相沟通,更重要的是,它比你在大学中学到的“现代语言”(比如ML语言、Java语言、Python语言或者其它正在教授的流行垃圾语言)都更接近机器。你至少需要花一个学期来了解机器原理,否则你永远不可能在高级语言的层次写出高效的代码。你也永远无法开发编译器和操作系统,而它们恰恰属于目前程序员能够得到的最佳工作之列。别人也永远不会放心将大型项目的架构设计交给你。我不管你懂多少延续(continuation)、闭包(closure)、异常处理(exception handling),只要你不能解释为什么while (*s++ = *t++);这句代码的作用是复制字符串,或者不觉得这是世界上对你来说再自然不过的事情,那么你就是在盲目无知的情况下编程。在我看来,这就好像一个医生不懂得最基本的解剖学就在开处方,他看病的根据完全是因为那些娃娃脸的医药厂商销售代表说这种药有用。

  毕业前学好微观经济学

  如果你没有上过任何经济学课程,那么我首先来做一个超短的评论:经济学是这样的学科之一,刚开始学的时候轰轰烈烈,有许多有用的、言之有理的理论和可以在真实世界中得到证明的事实,等等;但是,再学下去就每况愈下,有用的东西就不多了。经济学一开始那个有用的部分正是微观经济学,它是商业领域所有重要理论的基础。跟在微观经济学后面的东西就不行了。你接下来学的是宏观经济学,如果你愿意,尽管跳过去,也不会有什么损失。宏观经济学开头的部分是利息理论,内容比方说是利率与失业之间的关系,但是怎么说呢,看上去这部分里面还没有被证实的东西多于已经被证实的东西。学完这部分,后面的内容越来越糟糕,许多经济学专业的学生实际上都变成在搞物理学,因为这样才能在华尔街上找到更好的工作。但是不管怎样,你一定要去学微观经济学,因为你必须搞懂供给和需求,你必须明白竞争优势,你必须理解什么是净现值(NPV),什么是贴现,什么是边际效用。只有这样,你才会懂得为什么生意是现在这种做法。

  为什么计算机系的学生也应该学经济学?因为,从经营一家公司的角度来看,比起那些不懂的程序员,一个理解基本商业规则的程序员将会更有价值。就是这么简单。我无法告诉你有多少次我是那样地充满挫折感,因为我看到了太多的提出一些疯狂的想法的程序员,这些想法在代码上也许可行,但在资本主义世界中毫无意义。如果你懂得商业规则,你就是一个更有价值的程序员,你会因此得到回报的,但是前提是你要去学习微观经济学。

  不要因为枯燥就不选修非计算机专业的课程

  想提高GPA绩点的一个好方法就是多选修非计算机系的课程。请千万不要低估你的GPA的重大意义。千千万万的人事经理和招聘人员在拿到一份简历的时候,第一眼就会去看GPA,包括我也是这样。我们不会为这种做法道歉。为什么?因为GPA不反映单个的成绩,而是代表了许多个教授在一段很长的时间中,在不同的情况下,对你的表现的一个总的评估。SAT成绩难道不够吗?哈,那只不过是一场几个小时的测试罢了。GPA中包括了四年大学期间你的小论文、期中考试和课堂表现,总数有几百次之多。当然,GPA也有自己的问题,不是百分之百准确。比如,这些年来,老师对学生的打分越来越宽松,学习成绩有通货膨胀的趋势。再比如,GPA无法反映课程的难度,没人能够看出你的GPA是来自无名社区大学家政系的轻松课程还是来自加州理工学院针对研究生的量子力学课程。渐渐地,我形成了一套自己的做法,首先我会过滤掉所有来自社区大学、GPA低于2.5的简历,然后我会要求剩下的人给我寄成绩单和推荐信。我再从中发现那些成绩一贯优秀的人,而不是那些仅仅在计算机系课程中得到高分的人。

  为什么我要关心某人的“欧洲历史”课程成绩呢,毕竟作为雇主我要找的应该是程序员啊?何况,历史是那么枯燥,不得高分很正常。哦,这么说来,你的意思是我应该雇用你,而不用考虑一旦工作变得枯燥你会不会努力工作?别忘了,在编程工作中也有很枯燥的东西。每一项工作都有枯燥难耐的时刻。我不想雇用那些只想干有趣事情的人。

  选修有大量编程实践的课程

  我依然清楚记得我发誓绝不读研究生的那一刻。那是在一门叫做“动态逻辑”的课程上,教师是活力十足的耶鲁大学教授Lenore Zuck,她是计算机系那些聪明的老师中最聪明的人之一。

  如今, 由于记忆力糟糕, 我已经差不多把这门课的内容忘光了,但是不管怎么说,在这里我还是想要对付着说一下。大致上,形式逻辑的意思是说,如果条件成立,你就能证明结论也成立。比如,根据形式逻辑,已知“只要成绩好,就能被雇用”,然后假定“Johnny的成绩好”,你就可以得到一个崭新的结论“Johnny会被雇用”。这完全是经典方法。但是,一个解构主义者(deconstructionist)只需要10秒钟就能破坏形式逻辑中所有有用的东西。这样一来,留给你的只是一些趣味性,而不是实用性。

  现在再来说动态逻辑。它与形式逻辑其实是一回事,但是必须再多考虑时间因素。比如,“你打开灯之后,就能看见自己的鞋子”,已知“灯以前是亮的”,那么这就意味着“你看见了自己的鞋子”。

  对于像Zuck教授那样聪明的理论家,动态逻辑充满了吸引力,因为它看上去很有希望让你在形式上证明一些计算机程序的相关理论问题。这样做说不定很有用。比如,你可以用它在形式上证明,火星漫游车的闪存卡不会发生溢出(overflow)问题,不会因而整天一遍又一遍地重启,耽误了它在那颗赤红色的星球上漫游寻找火星人马文(Marvin the Martian)。

  在第一堂课上,Zuck博士写满了整整两面黑板,甚至黑板旁边的墙上都写上了很多证明步骤。需要证明的问题是,有一个控制灯泡的开关,现在灯泡没有亮,这时你打开了开关,请证明灯泡将会点亮。

  整个证明过程复杂得不可思议,处处都是陷阱,必须十分小心。保证这个证明不出错太困难了,还不如直接相信打开开关灯就会亮。真的,虽然证明过程写满了许多块黑板,但是还是有许多中间步骤被省略了,因为如果要从形式逻辑上完整证明所有步骤,那就琐碎得无法形容了。许多步骤是用各种经典的逻辑证明方法推导得到的,包括归纳法、反证法等,甚至有些部分还是由旁听的研究生证明的。

  留给我们的课后作业是证明逆命题:如果灯原来是关着的,现在却亮了,那么请证明开关的状态一定同原来相反。

  我动手开始证明,我真的去证明了。

  我在图书馆里待了很长时间。

  我对照着Zuck博士的原始证明想依样画葫芦。研究了几个小时之后,我在其中发现了一个错误。可能我抄写的时候抄错了,但是这使得我想通了一件事。如果花费3个小时,写满了一块又一块的黑板,每一秒钟都可能出错,最后能够证明的却只是一个很琐碎的结论,那么这种方式有多大的实用性呢?在活生生、充满趣味的现实世界中,你永远都不会有机会使用它。

  但是,动态逻辑的理论家们对这一点不感兴趣。他们看上它不是因为它有用,而是因为它可以为他们带来终身教职。

  我放弃了这门课,并且发誓绝不会去读计算机科学的研究生。

  这个故事告诉我们,计算机科学与软件开发不是一回事。如果你真的非常幸运,你的学校可能会开设很像样的软件开发课程。但是另一种可能是,你的学校根本不教你在现实中如何编程,因为精英学校都觉得,教授工作技能最好留给职业技术学校、犯人重返社会的培训项目去做。你到处都能学怎么写代码。别忘了,我们是耶鲁大学,我们的使命是培养未来的世界领袖。你交了16万美元的学费,却在学循环语句的写法,这怎么可以?你以为这是什么地方,难道是机场沿途的酒店里临时拼凑起来不靠谱的Java语言培训班?哼哼。

  麻烦在于我们没有一种真正教授软件开发的专门学校。你如果想成为一个程序员,你可能只能选择计算机科学专业。这是一个不错的专业,但是它同软件开发不是一回事。在那些400等级的课程代号中,去寻找名称中带有“Practicum”这个词的课程吧(编者注:指供人实习的课程)。不要被这个拉丁语单词吓倒,这些都是有用的课程,之所以起这种名字,只是为了让那些文绉绉、装腔作势、满嘴胡说八道的公司经理们觉得高深莫测。

  别担心所有工作都被印度人抢走

  我首先要说的是,如果你本身就已经在印度了,或者你就是印度人,那么你真的毫无必要去想这件事,根本不用琢磨所有的工作机会是不是都跑到了印度。那些都是非常好的工作,好好地享受吧,祝你身体健康。

  但是,我不断听说计算机系的入学人数下降得很厉害,已经到了危险的程度。根据我听到的说法,其中的一个原因是“学生们不愿去学一个工作机会都流向印度的专业”。这种担心大错特错,有很多理由可以反驳。首先,根据一时性的商业潮流决定个人的职业选择,这是愚蠢的。其次,即使编程工作无一幸存地都流向了印度和中国,但是学习编程本身依然是一种第一流的素质训练,可以为各种超级有趣的工作打下基础,比如业务流程工程(business process engineering)。再次,不管是在美国还是在印度,真正优秀的程序员依然是非常非常短缺的,这一点请相信我。不错,确实有相当一批失业的IT从业者在那里鼓噪,抱怨他们长时间找不到工作,但是你知道吗?即使冒着触怒这些人的风险,我还是要说,真正优秀的程序员根本不会失业。最后,你还能找到更好的专业吗?你觉得什么专业好?主修历史学?如果那样,你毕业的时候就会发现,根本没有其他选择,只能去法学院。不过我倒是知道一件事:99%的律师都痛恨他们的工作,痛恨他们当律师的每一分钟。可是,律师每周的工作时间偏偏长达90小时。就像我前面说过的:如果你喜欢编程,那么你真是受到了上天的眷顾。你是非常幸运的少数人之一,能够以自己喜欢的事谋生。

  不过说实话,我不觉得学生们真的有上面的想法。近年来,计算机系入学人数的下降只是回到了历史上的正常水平,因为前些年的互联网狂热使得入学人数出现了大泡沫,抬高了基数。由于这种泡沫,许多并不真的喜欢编程的人也来读计算机系。他们心里想的是,只要进了计算机系,将来就能找到诱人的高薪工作,就能获得24岁当上CEO、进行IPO的机会。谢天谢地,这些人现在都离计算机系远远的了。

  找一份好的暑期实习工作

  精明的招聘负责人都知道,喜欢编程的人高中时就将牙医的信息输入了数据库,进入大学前就去过三次电脑夏令营,为校报做过内容管理系统,有过软件公司的夏季实习经历。招聘负责人就是要在你的简历上找这些东西。

  如果你喜欢编程, 就不要随便什么工作都答应,否则你会犯下最大的错误。不管是暑期工作,还是兼职或者其他性质的工作,只要与编程无关,就不要轻易接受。我知道,其他19岁的孩子都想去购物中心里打工,在那里折叠衬衫。但是你与他们不同,你19岁时就已经掌握了一门非常有价值的技能。将时间浪费在折叠衬衫上是很愚蠢的,等到毕业的时候,你的简历上本应该写满了一大堆与编程相关的经历。就让那些财经类的毕业生去租车公司“帮助人们满足他们租车的需要”吧,你要干的是别的事(在电视中扮演超人的Tom Welling注1除外)。

  为了让你的生活变得更容易一些,也为了强调这整篇文章完全是为了满足我的个人目的,我要告诉你,我的公司——Fog Creek软件公司——提供软件开发方面的暑期实习机会。我们非常看重简历。“比起其他公司的实习工作,你在Fog Creek最有可能学到更多的编写代码、软件开发、商业运作方面的知识。”这是去年夏天我们的一个实习生Ben说的。他会这样说,并不完全是因为我派了人到他的宿舍让他这样说。我们接受实习申请的截止日期是2月1日。一起来吧。

  如果你听从了我的建议,你还是有可能落得一个悲惨的下场,比如很早就卖掉了微软公司的股票,再比如拒绝了谷歌公司的工作机会,原因是你想要一间自己的可以关上门的独立办公室,或者做出了其他生命中愚蠢的决定。但是,这些可不是我的错。我一开始就告诉过你,不要听我的话。


  本文转载自《软件随想录》(作者:Joel Spolsky ,译者: 阮一峰,2009年12月出版)
posted @ 2011-07-24 10:02 simplyzhao 阅读(215) | 评论 (0)编辑 收藏
     摘要: 来源: http://coolshell.cn/articles/4990.html月光博客6月12日发表了《写给新手程序员的一封信》,翻译自《An open letter to those who want to start programming》,我的朋友(他在本站的id是Mailper)告诉我,他希望在酷壳上看到一篇更具操作性的文章。因为他也是喜欢编程和技术的家伙,于是,我让他把...  阅读全文
posted @ 2011-07-24 09:57 simplyzhao 阅读(184) | 评论 (0)编辑 收藏
问题:

Given a random number generator which can generate the number in range (1,5) uniformly. How can you use it to build a random number generator which can generate the number in range (1,7) uniformly?


(给定一个随机数生成器,这个生成器能均匀生成1到5(1,5)的随机数,如何使用这个生成器生成均匀分布的1到7(1,7)的数?)

解法一:
拒绝采样定理
简单的说, 把 1-5 的随机数发生器用两次, 拼成一个5进制的数, 就是1-25. 将这 1-25 平均分配的25种情况映射到7种情况上, 问题就解决了. 因为21是7的倍数, 我们可以每三个映射到一个, 即1-3 映射到1, …, 19-21 映射到7. 可见, 这些情况之间的概率是一样的. 那么, 要是拼成的数字正好是 22-25 这四个呢? 有两种方法, 第一种是丢弃这个数字, 从头再来, 直到拼成的数字在1-21之间. 因为这个是个概率算法, 不能保证每次都能落在1-21, 所以采样的密度不高. 还有一种方法, 是说, 假如落到了 22-25, 那这次的采样结果就用上次的. 可以证明, 这看上去两个互相矛盾的算法, 结果都能均等的得到等概率的分布. (前者叫做 Reject Sampling, 后者叫做 Metropolis Algorithm, 都是数学物理模拟里面常用的方法)

解法二:
二进制
1-2映射到0,3跳过,4-5映射到1
生成三位的二进制即可
posted @ 2011-07-19 19:57 simplyzhao 阅读(3361) | 评论 (0)编辑 收藏
问题来源: 编程珠玑

解法一:
遍历这n个items,巧妙地利用概率来筛选
void
generate_random_m_from_n(
int n, int m)
{
    
int i, remaining, select = m;
    srand(time(NULL));
    
for(i=0; i<n; i++) {
        remaining 
= n - i;
        
if(rand()%remaining < select) {
            printf(
"%d\t", i);
            
--select;
        }
    }
    printf(
"\n");
}

解法二:
shuffle,即随机洗牌程序,然后选择前m个items即可
代码参考: http://blog.fuqcool.com/2011/04/17/algorithm-shuffle.html

洗牌算法的一种实现

作者:fuqcool 发布时间:2011-04-17 23:16:02 分类: algorithms

最近自己在做一个小的程序,需要把一个集合里面的元素全部随机地打散。自己想了一个方法,复杂度是n,觉得不太快。后来参照了一下python关于shuffle的算法,发现我的方法跟它的是一样的,连python的代码都这么写,可能已经没有办法再快了吧!

下面就来介绍洗牌算法,用C语言描述。

算法的前提是有一个产生随机数的函数

// Generates a random integer between beg and end.
int GetRandomNumber(int beg, int end);

还有一个交换函数。

// Swap a and b.
void Swap(int a, int b);

上面两个函数我就不写出实现了,因为这篇文章的重点在于算法的讨论。

假设我们有一堆扑克牌,怎么才能把这副牌完全打乱呢?计算机当然不能像人手那样洗牌。但是它可以产生随机数,随机地从一副牌中抽出一张牌是可以的。既然这样那就好办了,我们不停地从牌堆中随机抽取一张扑克牌,然后把这些牌堆起来,直到原来的牌堆只剩下一张牌的时候为止。这样不就完成了洗牌的动作了吗。

下面是C代码:

int Shuffle(int[] a, int len)
{
    for (int i = len - 1; i > 0; i--)
    {
        // Select an element from index 0 to i randomly;
        int index = GetRandomNumber(0, i);
        // exchange a[i] with a[index]
        Swap(a[index], a[i]);
    }
}

顺便也贴出python的random单元关于shuffle的实现:

def shuffle(self, x, random=None, int=int):
    """x, random=random.random -> shuffle list x in place; return None.

    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.
    """

    if random is None:
        random = self.random
    for i in reversed(xrange(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random() * (i+1))
        x[i], x[j] = x[j], x[i]

posted @ 2011-07-18 09:32 simplyzhao 阅读(434) | 评论 (0)编辑 收藏
来源:
http://coolshell.cn/articles/3345.html

Software Engineer
  • Why are manhole covers round? (陈皓:为什么下水井盖是圆的?这是有N种答案的,上Wiki看看吧)
  • What is the difference between a mutex and a semaphore? Which one would you use to protect access to an increment operation?
  • A man pushed his car to a hotel and lost his fortune. What happened? (陈皓:脑筋急转弯?他在玩大富翁游戏?!!)
  • Explain the significance of “dead beef”.(陈皓:要是你看到的是16进制 DEAD BEEF,你会觉得这是什么?IPv6的地址?)
  • Write a C program which measures the the speed of a context switch on a UNIX/Linux system.
  • Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.(陈皓:上StackOverflow看看吧,经典的问题)
  • Describe the algorithm for a depth-first graph traversal.
  • Design a class library for writing card games. (陈皓:用一系列的类来设计一个扑克游戏,设计题)
  • You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write a the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?(陈皓:协议+数字加密,我试想了一个,纸条上可以这样写,“Bob,请把我的手机号以MD5算法加密后的字符串,比对下面的字符串——XXXXXX,它们是一样的吗?”)
  • How are cookies passed in the HTTP protocol?
  • Design the SQL database tables for a car rental database.
  • Write a regular expression which matches a email address. (陈皓:上StackOverflow查相当的问题吧。)
  • Write a function f(a, b) which takes two character string arguments and returns a string containing only the characters found in both strings in the order of a. Write a version which is order N-squared and one which is order N.(陈皓:算法题,不难,不说了。一个O(n^2)和一个O(n)的算法复杂度)
  • You are given a the source to a application which is crashing when run. After running it 10 times in a debugger, you find it never crashes in the same place. The application is single threaded, and uses only the C standard library. What programming errors could be causing this crash? How would you test each one? (陈皓:和随机数有关系?或是时间?)
  • Explain how congestion control works in the TCP protocol.
  • In Java, what is the difference between final, finally, and finalize?
  • What is multithreaded programming? What is a deadlock?
  • Write a function (with helper functions if needed) called to Excel that takes an excel column value (A,B,C,D…AA,AB,AC,… AAA..) and returns a corresponding integer value (A=1,B=2,… AA=26..).
  • You have a stream of infinite queries (ie: real time Google search queries that people are entering). Describe how you would go about finding a good estimate of 1000 samples from this never ending set of data and then write code for it.
  • Tree search algorithms. Write BFS and DFS code, explain run time and space requirements. Modify the code to handle trees with weighted edges and loops with BFS and DFS, make the code print out path to goal state.
  • You are given a list of numbers. When you reach the end of the list you will come back to the beginning of the list (a circular list). Write the most efficient algorithm to find the minimum # in this list. Find any given # in the list. The numbers in the list are always increasing but you don’t know where the circular list begins, ie: 38, 40, 55, 89, 6, 13, 20, 23, 36. (陈皓:循环排序数组的二分查找问题)
  • Describe the data structure that is used to manage memory. (stack)
  • What’s the difference between local and global variables?
  • If you have 1 million integers, how would you sort them efficiently? (modify a specific sorting algorithm to solve this)
  • In Java, what is the difference between static, final, and const. (if you don’t know Java they will ask something similar for C or C++).
  • Talk about your class projects or work projects (pick something easy)… then describe how you could make them more efficient (in terms of algorithms).
  • Suppose you have an NxN matrix of positive and negative integers. Write some code that finds the sub-matrix with the maximum sum of its elements.(陈皓:以前见过一维数组的这个问题,现在是二维的。感觉应该是把二维的第一行的最大和的区间算出来,然后再在这个基础之上进行二维的分析。思路应该是这个,不过具体的算法还需要想一想)
  • Write some code to reverse a string.
  • Implement division (without using the divide operator, obviously).(陈皓:想一想手算除法的过程。)
  • Write some code to find all permutations of the letters in a particular string.
  • What method would you use to look up a word in a dictionary? (陈皓:使用排序,哈希,树等算法和数据结构)
  • Imagine you have a closet full of shirts. It’s very hard to find a shirt. So what can you do to organize your shirts for easy retrieval?
  • You have eight balls all of the same size. 7 of them weigh the same, and one of them weighs slightly more. How can you fine the ball that is heavier by using a balance and only two weighings?
  • What is the C-language command for opening a connection with a foreign host over the internet?
  • Design and describe a system/application that will most efficiently produce a report of the top 1 million Google search requests. These are the particulars: 1) You are given 12 servers to work with. They are all dual-processor machines with 4Gb of RAM, 4x400GB hard drives and networked together.(Basically, nothing more than high-end PC’s) 2) The log data has already been cleaned for you. It consists of 100 Billion log lines, broken down into 12 320 GB files of 40-byte search terms per line. 3) You can use only custom written applications or available free open-source software.
  • There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1]. Solve it without division operator and in O(n).(陈皓:注意其不能使用除法。算法思路是这样的,把output[i]=a[i]左边的乘积 x a[i]右边的乘积,所以,我们可以分两个循环,第一次先把A[i]左边的乘积放在Output[i]中,第二次把A[i]右边的乘积算出来。我们先看第一次的循环,使用迭代累积的方式,代码如下:for(r=1; i=0; i<n-1; i++){ Output[i]=r; r*=a[i]; },看明白了吧。第二次的循环我就不说了,方法一样的。)
  • There is a linked list of numbers of length N. N is very large and you don’t know N. You have to write a function that will return k random numbers from the list. Numbers should be completely random. Hint: 1. Use random function rand() (returns a number between 0 and 1) and irand() (return either 0 or 1) 2. It should be done in O(n).(陈皓:本题其实不难。在遍历链表的同时一边生成随机数,一边记录最大的K个随机数和其链接地址。)
  • Find or determine non existence of a number in a sorted list of N numbers where the numbers range over M, M>> N and N large enough to span multiple disks. Algorithm to beat O(log n) bonus points for constant time algorithm.(陈皓:使用bitmap,如果一个长整形有64位,那么我们可以使用M/64个bitmap)
  • You are given a game of Tic Tac Toe. You have to write a function in which you pass the whole game and name of a player. The function will return whether the player has won the game or not. First you to decide which data structure you will use for the game. You need to tell the algorithm first and then need to write the code. Note: Some position may be blank in the game। So your data structure should consider this condition also.
  • You are given an array [a1 To an] and we have to construct another array [b1 To bn] where bi = a1*a2*…*an/ai. you are allowed to use only constant space and the time complexity is O(n). No divisions are allowed.(陈皓:前面说过了)
  • How do you put a Binary Search Tree in an array in a efficient manner. Hint :: If the node is stored at the ith position and its children are at 2i and 2i+1(I mean level order wise)Its not the most efficient way.(陈皓:按顺序遍历树)
  • How do you find out the fifth maximum element in an Binary Search Tree in efficient manner. Note: You should not use use any extra space. i.e sorting Binary Search Tree and storing the results in an array and listing out the fifth element.
  • Given a Data Structure having first n integers and next n chars. A = i1 i2 i3 … iN c1 c2 c3 … cN.Write an in-place algorithm to rearrange the elements of the array ass A = i1 c1 i2 c2 … in cn(陈皓:这个算法其实就是从中间开始交换元素,代码:for(i=n-1; i>1; i++) {  for(j=i; j<2*n-i; j+=2) { swap(a[j], a[j+1]); } },不好意思写在同一行上了。)
  • Given two sequences of items, find the items whose absolute number increases or decreases the most when comparing one sequence with the other by reading the sequence only once.
  • Given That One of the strings is very very long , and the other one could be of various sizes. Windowing will result in O(N+M) solution but could it be better? May be NlogM or even better?
  • How many lines can be drawn in a 2D plane such that they are equidistant from 3 non-collinear points?
  • Let’s say you have to construct Google maps from scratch and guide a person standing on Gateway of India (Mumbai) to India Gate(Delhi). How do you do the same?
  • Given that you have one string of length N and M small strings of length L. How do you efficiently find the occurrence of each small string in the larger one?
  • Given a binary tree, programmatically you need to prove it is a binary search tree.
  • You are given a small sorted list of numbers, and a very very long sorted list of numbers – so long that it had to be put on a disk in different blocks. How would you find those short list numbers in the bigger one?
  • Suppose you have given N companies, and we want to eventually merge them into one big company. How many ways are theres to merge?
  • Given a file of 4 billion 32-bit integers, how to find one that appears at least twice? (陈皓:我能想到的是拆分成若干个小数组,排序,然后一点点归并起来)
  • Write a program for displaying the ten most frequent words in a file such that your program should be efficient in all complexity measures.(陈皓:你可能需要看看这篇文章Finding Frequent Items in Data Streams
  • Design a stack. We want to push, pop, and also, retrieve the minimum element in constant time.
  • Given a set of coin denominators, find the minimum number of coins to give a certain amount of change.(陈皓:你应该查看一下这篇文章:Coin Change Problem
  • Given an array, i) find the longest continuous increasing subsequence. ii) find the longest increasing subsequence.(陈皓:这个题不难,O(n)算法是边遍历边记录当前最大的连续的长度。)
  • Suppose we have N companies, and we want to eventually merge them into one big company. How many ways are there to merge?
  • Write a function to find the middle node of a single link list. (陈皓:我能想到的算法是——设置两个指针p1和p2,每一次,p1走两步,p2走一步,这样,当p1走到最后时,p2就在中间)
  • Given two binary trees, write a compare function to check if they are equal or not. Being equal means that they have the same value and same structure.(陈皓:这个很简单,使用递归算法。)
  • Implement put/get methods of a fixed size cache with LRU replacement algorithm.
  • You are given with three sorted arrays ( in ascending order), you are required to find a triplet ( one element from each array) such that distance is minimum. Distance is defined like this : If a[i], b[j] and c[k] are three elements then distance=max(abs(a[i]-b[j]),abs(a[i]-c[k]),abs(b[j]-c[k]))” Please give a solution in O(n) time complexity(陈皓:三个指针,a, b, c分别指向三个数组头,假设:a[0]<b[0]<c[0],推进a直到a[i]>b[0],计算 abs(a[i-1] – c[0]),把结果保存在min中。现在情况变成找 a[i], b[0],c[0],重复上述过程,如果有一个新的值比min要小,那就取代现有的min。)
  • How does C++ deal with constructors and deconstructors of a class and its child class?
  • Write a function that flips the bits inside a byte (either in C++ or Java). Write an algorithm that take a list of n words, and an integer m, and retrieves the mth most frequent word in that list.
  • What’s 2 to the power of 64?
  • Given that you have one string of length N and M small strings of length L. How do you efficiently find the occurrence of each small string in the larger one? (陈皓:我能想到的是——把那M个小字串排个序,然后遍历大字串,并在那M个字串中以二分取中的方式查找。)
  • How do you find out the fifth maximum element in an Binary Search Tree in efficient manner.
  • Suppose we have N companies, and we want to eventually merge them into one big company. How many ways are there to merge?
  • There is linked list of millions of node and you do not know the length of it. Write a function which will return a random number from the list.
  • You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write a the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?
  • How long it would take to sort 1 trillion numbers? Come up with a good estimate.
  • Order the functions in order of their asymptotic performance: 1) 2^n 2) n^100 3) n! 4) n^n
  • There are some data represented by(x,y,z). Now we want to find the Kth least data. We say (x1, y1, z1) > (x2, y2, z2) when value(x1, y1, z1) > value(x2, y2, z2) where value(x,y,z) = (2^x)*(3^y)*(5^z). Now we can not get it by calculating value(x,y,z) or through other indirect calculations as lg(value(x,y,z)). How to solve it?
  • How many degrees are there in the angle between the hour and minute hands of a clock when the time is a quarter past three?
  • Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. Do this in sub-linear time. I.e. do not just go through each element searching for that element.
  • Given two linked lists, return the intersection of the two lists: i.e. return a list containing only the elements that occur in both of the input lists. (陈皓:把第一个链表存入hash表,然后遍历第二个链表。不知道还没有更好的方法。)
  • What’s the difference between a hashtable and a hashmap?
  • If a person dials a sequence of numbers on the telephone, what possible words/strings can be formed from the letters associated with those numbers?(陈皓:这个问题和美国的电话有关系,大家可以试着想一下我们发短信的手机,按数字键出字母,一个组合的数学问题。)
  • How would you reverse the image on an n by n matrix where each pixel is represented by a bit?
  • Create a fast cached storage mechanism that, given a limitation on the amount of cache memory, will ensure that only the least recently used items are discarded when the cache memory is reached when inserting a new item. It supports 2 functions: String get(T t) and void put(String k, T t).
  • Create a cost model that allows Google to make purchasing decisions on to compare the cost of purchasing more RAM memory for their servers vs. buying more disk space.
  • Design an algorithm to play a game of Frogger and then code the solution. The object of the game is to direct a frog to avoid cars while crossing a busy road. You may represent a road lane via an array. Generalize the solution for an N-lane road.
  • What sort would you use if you had a large data set on disk and a small amount of ram to work with?
  • What sort would you use if you required tight max time bounds and wanted highly regular performance.
  • How would you store 1 million phone numbers?(陈皓:试想电话是有区段的,可以把区段统一保存,Flyweight设计模式)
  • Design a 2D dungeon crawling game. It must allow for various items in the maze – walls, objects, and computer-controlled characters. (The focus was on the class structures, and how to optimize the experience for the user as s/he travels through the dungeon.)
  • What is the size of the C structure below on a 32-bit system? On a 64-bit? (陈皓:注意编译器的对齐)

struct foo {

char a;
char* b;
};
posted @ 2011-07-14 10:13 simplyzhao 阅读(529) | 评论 (0)编辑 收藏
仅列出标题
共21页: 1 2 3 4 5 6 7 8 9 Last 

导航

<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜