[英]How to check if element exists in an array without for loop?
我正在做一個我不能使用for
循環的挑戰,所以我使用goto
語句來實現它。
基本上,我得到了一個正數數組,因此需要消除諸如-1
之類的負數。 但是通過這樣做,我的數組的長度會縮短,因此,在我檢查循環是否結束的下一輪,我會收到index out of range
。
我正在尋找一種方法來確定下一個元素是否存在,如果不存在,則停止程序。
我的代碼:
func main() {
fmt.Println("Please enter number of test cases: ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
testCasesNumberInput := scanner.Text()
testCaseNumber, _ := strconv.Atoi(testCasesNumberInput)
if testCaseNumber <= 0 {
fmt.Print("Number of test cases must be higher or equal to 1")
return
}
fmt.Println("Please enter test cases: ")
scanner.Scan()
scannerText := scanner.Text()
input := strings.Fields(scannerText)
testCases := make([]int, len(input))
if len(testCases) != testCaseNumber {
fmt.Print("Wrong number of test cases!")
return
}
inputIndex := 0
outputIndex := 0
var intInput int
start:
if inputIndex < len(testCases) {
intInput, _ = strconv.Atoi(input[inputIndex])
testCases[inputIndex] = intInput
inputIndex++
goto start
}
goto prepareResult
prepareResult:
if outputIndex > len(testCases) {
fmt.Print("result: \n", testCases)
return
}
if testCases[outputIndex] <= 0 {
copy(testCases[outputIndex:], testCases[outputIndex+1:])
testCases[len(testCases)-1] = 0
testCases = testCases[:len(testCases)-1]
if outputIndex == 0 {
if len(testCases) < outputIndex+2 {
fmt.Print("")
return
}
} else {
if len(testCases) < outputIndex {
fmt.Print("")
return
}
}
}
outputIndex++
goto prepareResult
}
提前感謝任何幫助。
您需要做的就是:
刪除正在檢查testCases[outputIndex] <= 0
的 if 和 else 語句,並將其替換為指向prepareResult
的goto
,這使您的outputIndex
保持在當前值,並且由於您已經從數組中刪除了一個元素,因此它可以正常工作美好的。
將if outputIndex > len(testCases)
更改為if outputIndex >= len(testCases)
以獲得良好的測量結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.