我是 nim 新手,正在嘗試一些代碼挑戰
根據https://www.codewars.com/kata/58f8a3a27a5c28d92e000144/nim
我可以通過以下方式解決這個 kata:
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)
但我正在尋找一種解決這個問題的實用方法
謝謝。
uj5u.com熱心網友回復:
這是我的第一個 stackoverflow 答案,所以我有點不確定該說什么。但這對于功能解決方案應該沒問題!
另請注意,任何函式呼叫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://www.uj5u.com/shujuku/531462.html
