最近面试时候碰到的算法题目,自己写一下,顺便和大家交流下groovy的语法糖
题目都比较简单——用什么语言写,都不是重点——笔试中我都是狂省略式写法的
?
?? 1.上周五面试时候要写一个生产者消费者的例子——网上一堆的,我用Groovy写一个
?
?
import java.util.concurrent.*def q = new ArrayBlockingQueue(10)// ProductorThread.start{10.times{q << new Random().nextInt(100)sleep(1000 * 3)}}// ConsumerThread.start{8.times{def obj = q.take()println obj?:'Nothing keep waiting.'sleep(1000 * 2)}}?
2. 有一个整数数组,其中除了0,其他的数字均不重复,写一个程序,随即取出5个数字,并判断该5个数字是否相邻,其中0可以变成任何整数。
?
?
def is_adj = {arr ->def r = new Random()def ll = []5.times{ll << arr[r.nextInt(arr.size())]}ll = ll.unique() - [0]return ll.max() - ll.min() < 5}def arr = (10..25) + (1..5).collect{0}println is_adj(arr)?
3. 给一个字符串(只有字母),写个方法返回字符串,使得每一个字母按照下列变化规则——
?
?? A-Z B-Y...Z-A a-z...z-a
?
def transf(String str){return str.collect{(char)((int)it >= 97 ? (97*2-(int)it+25) : (65*2-(int)it+25))}.join('')}println transf('ABCcba')?
?
4. 还有在je上发现的——http://www.iteye.com/topic/545378
?
一个画图程序 要求打印出?
- int?i=5;??
- 1??2??3??4??5??
- 16?17?18?19?6??
- 15?24?25?20?7??
- 14?23?22?21?8??
- 13?12?11?10?9??
- ??
- int?i=6??
- 1??2??3??4??5???6??
- 20?21?22?23?24??7??
- 19?32?33?34?25??8??
- 18?31?36?35?26??9??
- 17?30?29?28?27?10??
- 16?15?14?13?12?11??
?
?
?
def set = {num, matrix, len, left ->int begin = 0 // 这一圈的开始补值if(left){(1..left).each{begin += (len + it * 2 - 1) * 4}}if(num <= len) // 顶行matrix[0 + left][num + left - 1] = begin + numelse if(num < len * 2) // 右列matrix[num-len+left][len-1+left] = begin + num else if(num < len * 3 - 1) // 底行matrix[len-1+left][len * 3 - 2 - num + left] = begin + numelse // 左列matrix[len-1-(num-3*len+2)+left][0+left] = begin + num}int n = 25int[][] matrix = new int[n][n]int left = 0 // 一圈一圈的,表示第几圈for(int k = n; k > 0; k = k - 2){(1..4*(k-1)).each{set(it, matrix, k, left)} // 分别把数填进去left++}matrix.each{println it}?如果哪位童鞋最近找工作,笔试中有什么算法题,可以分享出来呵
x += (2 - d) * (d & 1);y += (1 - d) * ((d + 1) & 1);其中d为方向 上 右 下 左 分别为 0 1 2 3x += (2 - d) * (d & 1);y += (1 - d) * ((d + 1) & 1);
其中d为方向 上 右 下 左 分别为 0 1 2 3
强——我试试(平时对位操作根本就不了解)。谢谢 9 楼 congdepeng 2011-03-22 tterry 写道groovy其实还真不错, 不明白很多人为什么看不起她
没有人看不起groovy啊,只是语言而已。
我以前也学过groovy,写了一个小工具,现在业余在学Python。