阿里巴巴校园招聘在线面试之附加题

来源:互联网 发布:ubuntu vnc远程桌面 编辑:程序博客网 时间:2024/04/28 20:48

写在前面:

昨晚做了阿里巴巴的在线面试,感觉阿里的单选好难啊,40分钟才做了一般多,自动被提交。附加题倒是还行,两道编程题一道设计题,由于比较喜欢写代码,就抱着试试看的态度把其中的两道编程题目给做了,虽然粗糙,但毕竟这也是一种经历,为方便今后的查找,还是决定把它们贴出来。

题目一:

第一题比较简单,就是用伪随机数的方式不重复地打印出1-1000中的500个数,可以使用java.util.Random类

思路:

感觉毕竟比较简单,也没有多想,开辟一个1001个整数大小的整型数组,并将其赋值为arr[i]=i;打印一个数字并将该数字归0,直至打印出所有的数字。

代码:

public static void printRandomNum(){Random random=new Random();int len=1001;int arr[]=new int[len];for(int i=1;i<len;i++)arr[i]=i;int randomNum=0;for(int i=0;i<900;i++){randomNum=random.nextInt(1000)+1;while(arr[randomNum]==0)randomNum=random.nextInt(1000)+1;System.out.print(randomNum+"\t");arr[randomNum]=0;if(i%10==9)System.out.println();}}

结果:


题目二:

用程序模拟甲往一个箱子里放苹果,乙从箱子向外去苹果的过程。

思路:

说白了就是一个生产者消费者的问题,试着实现了一下

代码:

//put apple threadclass PutThread extends Thread {PutGetDemo putGetDemo;public PutThread(PutGetDemo putGetDemo) {this.putGetDemo = putGetDemo;}public void run() {while (true) {putGetDemo.putApple();// put an apple}}}// get apple threadclass GetThread extends Thread {PutGetDemo putGetDemo;public GetThread(PutGetDemo putGetDemo) {this.putGetDemo = putGetDemo;}public void run() {while (true) {putGetDemo.getApple();// get an apple}}}public class PutGetDemo {private final int MAX_SIZE = 5;// the max num of apples in the boxprivate int produceNum = 0;private List<Integer> list = new ArrayList<Integer>();// to store the apples// put apple into the boxpublic synchronized void putApple() {int appleNum = 0;while (list.size() + 1 > MAX_SIZE) {System.out.println("the box is full");try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}appleNum = produceNum % 5 + 1;// the apple numberlist.add(appleNum);System.out.println("Push apple:" + appleNum);produceNum++;System.out.println("I have put an apple into box!");notify();}// //get the apple from the boxpublic synchronized void getApple() {while (list.size() == 0) {System.out.println("The box is empty");try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println("Get apple: " + list.get(0));list.remove(0);System.out.println("I have get an apple!");notify();}public static void main(String[] args) {// TODO Auto-generated method stubPutGetDemo putGetDemo = new PutGetDemo();PutThread putThread = new PutThread(putGetDemo);// the put apple threadGetThread getThread = new GetThread(putGetDemo);// the get apple threadputThread.start();getThread.start();//CreateRandomNum.printRandomNum();}}

结果:



1 0
原创粉丝点击