我是尼姆的新手,我尝试了一些代码挑战
根据https://www.codewars.com/kata/58f8a3a27a5c28d92e000144/nim
我可以用以下方法解决这个问题:
import options
proc first_non_consecutive*(arr: seq[int]): Option[int] =
for i, item in arr:
if i > 0 and item - arr[i-1] > 1:
return some(item)但我在寻找一种实用的方法来解决这个问题
谢谢。
发布于 2022-11-08 22:02:59
这是我的第一个堆叠溢出的答案,所以我有点不知道该说什么。但是对于功能性解决方案来说,这应该是很好的!
还请注意,任何函数调用(如len(arr) )都可以更改为arr.len,我认为func只是一个注释过程的模板,说明它没有副作用。
import options
func isPrev1Below(arr: seq[int], idx: int): Option[int] =
if idx > len(arr) - 1:# incase we reach the end of the array
return none(int)
if arr[idx] - arr[idx-1] != 1:# if the difference between this and the previous are not 1, it's not consecutive
return some(arr[idx])
return isPrev1Below(arr, idx + 1)# otherwise returns the result of the next item.
func firstNonConsecutive*(arr: seq[int]): Option[int] =
isPrev1Below(arr, 1)# start on second item because it will never be first
echo firstNonConsecutive @[1,2,3,4,5,6,7,8]# equivelant to echo(firstNonConsecutive(@[1,2...]))https://stackoverflow.com/questions/74332529
复制相似问题