编辑:对于这个问题的新手,我已经发布了一个答案,澄清了发生了什么.接受的答案是我认为最能回答我最初发布的问题的答案,但有关详细信息,请参阅我的答案.
注意:此问题最初是伪代码和使用列表.我已将它改编为Java和数组.因此,虽然我很想看到任何使用Java特定技巧的解决方案(或任何语言的技巧!),但请记住原始问题与语言无关.
比方说,有两个未排序整型数组a和b,以允许元素的重复.它们是相同的(关于包含的元素),除了一个数组有一个额外的元素.举个例子:
int[] a = {6, 5, 6, 3, 4, 2};
int[] b = {5, 7, 6, 6, 2, 3, 4};
Run Code Online (Sandbox Code Playgroud)
设计一种算法,将这两个数组作为输入并输出单个唯一整数(在上例中为7).
我想出了这个:
public static int getUniqueElement(int[] a, int[] b) {
int ret = 0;
for (int i = 0; i < a.length; i++) {
ret ^= a[i];
}
for (int i = 0; i < b.length; i++) {
ret ^= b[i];
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
课堂上提出的"官方"解决方案:
public static …Run Code Online (Sandbox Code Playgroud) 假设我有一个结构(其参数多于此处所示):
(defstruct location
name)
Run Code Online (Sandbox Code Playgroud)
以及使用反引号定义一系列位置的关联列表:
(defparameter *locations* `(
(ASIA ,(make-location :name "Asia"))
(AFRICA ,(make-location :name "Africa"))
)
Run Code Online (Sandbox Code Playgroud)
这工作正常,并正确创建位置结构.问题是,我正计划拥有很多地点,而不仅仅是亲手打包:
(defparameter *locations* `(
(ASIA ,(make-location :name "Asia"))
(AFRICA ,(make-location :name "Africa"))
(LOC1 ,(make-location :name "Location 1"))
; Lots more...
(LOC1024 ,(make-location :name "Location 1027"))
)
Run Code Online (Sandbox Code Playgroud)
很多这些额外的位置都有类似的参数,这样我就可以定义一个"生成器函数"来创建它们的列表:
(defun generate-locations (symbol name count)
(loop for i from 1 to count collect (list
(read-from-string (format nil "~A~D" symbol i))
(make-location :name name))))
;;; Creates list ((LOC1 #S(LOCATION :NAME "Location 1")) (LOC2 ...
(generate-locations "LOC" "Location …Run Code Online (Sandbox Code Playgroud)