第n个替换(合并排序
我已经基于Ellis Dee的vb6版本在Autolisp中完成了MergeSort算法的实现:http://www.vbforums.com/showpost.php?p=2909257&postcount=12问题是我需要替换lisp数组中的第n个原子,目前唯一可以实现这一点的方法是迭代整个列表。这需要一个壮观的排序算法,并通过对列表进行第n次(log)迭代来破坏其效率。我会尽量不让水太浑浊,但这是我的第n个替换函数,基于Michels第n个移除函数。。。
(defun nth-replace (n_atom f_list f_n / ) ;replaced the nth element of a list
;n_atom is new atom
;f_list is list to be operated on
;f_n is the index that will be replaced
(if (and (numberp f_n) (listp f_list))
(if (and (>= f_n 0) (< f_n (length f_list)) n_atom)
(progn
(repeat f_n
(setq f_list (append (cdr f_list) (list (car f_list))))
)
(setq f_list (append (cdr f_list) (list n_atom)))
(repeat (- (length f_list) f_n 1)
(setq f_list (append (cdr f_list) (list (car f_list))))
)
)
)
)
f_list
);defun
我对autolisp并不完全陌生,但我希望有一个我忽略的基本函数,可以在某个级别替换原子,或者可以将列表返回到某个原子(第n个实例),然后我可以附加我的更改,然后是列表的后半部分。 考虑这个例子:
林奇
**编辑-来自VLIDE控制台的示例:
REPLACE3
_$ (replace3 '(1 2 3 3 2 1) 3 4)
(1 2 3 4 2 1)
_$
第一个想法。。
(defun nth-rep (x l n / i)
(setq i -1)
(mapcar '(lambda (a) (cond ((= (setq i (1+ i)) n) x) (a))) l)
)
编辑:哎呀。。。太晚了 快一点,但应该有用。。。
(defun _nthReplace (item index lst)
(if (and lst (> index 0))
(cons (car lst) (_nthReplace item (1- index) (cddr lst)))
(cons item (cdr lst))
)
) 伦德曼/斯特凡BMR
壮观的先生们。非常壮观。
如果我能表达我的喜悦,我将不得不键入大约5000次。
这很有道理,我很尴尬。优化时没有重新创建变量。
因此,在测试了IF和COND方法之后,IF在处理1000个随机数时以3秒的优势获胜。请记住,其中任何一个距离我拥有的都有光年,我在几个小时后停止了处理。
如果结果:
Time:
15.19 seconds
; 10 forms loaded from #<editor ".../mergesort2.LSP">
_1_$
COND结果:
Time:
18.02 seconds
; 10 forms loaded from #<editor ".../mergesort2.LSP">
_1_$
在单独的线程中发布合并排序。
李值得赞扬的是我在上面发布的代码,因为他将该产品作为我自己的增强版(在同一帖子的前面,链接在上面)。英雄联盟
... 不过,我很高兴这对你有帮助。 读了这篇文章后,我有一个问题。在AutoLisp中,为什么subst不工作?
(subst ITEM (nth INDEX LST) LST) 尝试
(subst 1 0 '(0 1 0 2 0)) 斯特凡是正确的-李也向我提出了这一点,在上面的链接线程。 我认为重点是替换第n项,而不是每个匹配项。
页:
[1]
2