将船只放置在战舰中(删除重复代码)
现在我的 1D 版本已经完成,我正在(慢慢地)制作《战舰》的 2D 版本。我编写了以下函数,在给定船的长度、船的位置以及船所面向的方向的情况下将船放置在板上。然而,这个功能很丑陋。非常难看。我的意思是,代码重复的情况很多。谁能指出一些可以减少代码重复的方法?
(defun place-boat (len pos dir)
(let ((offset 0))
(dotimes (i len)
(if (= dir 0)
(if (< pos 50)
(setf (aref *ans-board*
(+ (/ pos 10) offset)
(mod pos 10))
'#)
(setf (aref *ans-board*
(- (/ pos 10) offset)
(mod pos 10))
'#))
(if (< pos 50)
(setf (aref *ans-board*
(/ pos 10)
(+ (mod pos 10) offset))
'#)
(setf (aref *ans-board*
(/ pos 10)
(- (mod pos 10) offset))
'#)))
(incf offset))))
编辑:为了澄清起见,pos
是 1 到 100 之间的数字,表示 10x10 2D 数组中的一个单元格。
I'm (slowly) working out a 2D version of Battleship now that my 1D version is done. I wrote the following function to place a boat on the board given the length of the boat, the position of the boat, and the direction the boat is facing. However, the function is ugly. Very ugly. By which I mean, there is much in the way of code duplication. Could anyone point out some ways in which I could reduce the duplication in this code?
(defun place-boat (len pos dir)
(let ((offset 0))
(dotimes (i len)
(if (= dir 0)
(if (< pos 50)
(setf (aref *ans-board*
(+ (/ pos 10) offset)
(mod pos 10))
'#)
(setf (aref *ans-board*
(- (/ pos 10) offset)
(mod pos 10))
'#))
(if (< pos 50)
(setf (aref *ans-board*
(/ pos 10)
(+ (mod pos 10) offset))
'#)
(setf (aref *ans-board*
(/ pos 10)
(- (mod pos 10) offset))
'#)))
(incf offset))))
EDIT: For clarification, pos
is a number between 1 and 100, signifying a cell in a 10x10 2D array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,对于初学者来说,我认为你不需要同时使用 i 和 offset 。它们都从 0 到 len 彼此同步。
然后你可以做这样的事情来折叠 +/- 情况 <或 >= 50 到一个语句中:
(+ (/ pos 10) (* (if (< pos 50) 1 -1) offset))
这给你(未经测试):
仍然有一些冗余。但这就是我到目前为止所得到的。
注意,我对 Common Lisp 知之甚少,所以我确信其他人可以做得更好:)
Well, for starters, I don't think you need both i and offset. They both go from 0 up to len in step with each other.
Then you could do something like this to collapse the +/- cases for < or >= 50 into one statement:
(+ (/ pos 10) (* (if (< pos 50) 1 -1) offset))
That give you (untested):
which still has some redundancy. But that's what I've got so far.
Note, I know very little about Common Lisp, so I'm sure someone else could do much better :)
假设我正确理解你的需求:
如果你要处理方向 -1,-1,10,-10 你可以很容易地做这样的事情:
Supposed I understand your needs correctly:
if you would deal with the directions -1,-1,10,-10 you could easily do something like this: