P19 (**) Rotate a list N places to the left.
2016-01-18 21:21
197 查看
问题描述
sash> (rotate '(a b c d e f g h) 3) -> ((a b c) (d e f g h i k)) sash> (rotate '(a b c d e f g h) -2) -> (g h a b c d e f)
Hint: Use the predefined functions
lengthand
append, as well as the result of problem P17.
解法
普通实现
按照题目的提示,很直观得到:(define rotate (lambda (ls N) (cond [(zero? N) ls] [else (let* ([n (if (positive? N) N (+ (length ls) N))] [s (split ls n)]) (append (cadr s) (car s)))])))
使用到了
length、
append,以及P17定义的
split。
CPS实现
(define split-2 (lambda (ls n k) (let f ([i 1] [s ls] [k k]) (cond [(null? s) (k '() '())] [(<= i n) (f (+ i 1) (cdr s) (lambda (ls1 ls2) (k (cons (car s) ls1) ls2)))] [else (f (+ i 1) (cdr s) (lambda (ls1 ls2) (k ls1 (cons (car s) ls2))))])))) (define return (lambda (ls1 ls2) (append ls2 ls1))) (define rotate (lambda (ls N) (cond [(zero? N) ls] [else (let ([n (if (positive? N) N (+ (length ls) N))]) (split-2 ls n return))])))
split-2的功能仍然是分割的两个列表,这个定义没有改变。这里改变了
return的定义,用来组装
split-2得到的两个列表,P17要求返回这两个列表作为元素的列表,而该题目则要求按规则
append成一个列表。
rotate则包含了顶层逻辑,处理
N的各种情况对应的结果逻辑。
其他方式
看到另外一种解法:(define (rotate xs n) (if (< n 0) (reverse (rotate (reverse xs) (- n))) (let ((parts (split xs n))) (append (cadr parts) (car parts)))))
看似简洁,但有逻辑冗余:当
n为负时,会用
-n作为
rot 4000 ate的参数,这时仍然要判断
if语句,实际上我们已经知道了
-n为正。
不建议将对
n的处理放入递归逻辑中。
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析