登录
首页 >  Golang >  Go问答

无法让 for 循环迭代足够的次数以使我的程序正常工作

来源:stackoverflow

时间:2024-04-08 19:18:36 341浏览 收藏

本篇文章向大家介绍《无法让 for 循环迭代足够的次数以使我的程序正常工作》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我正在尝试做一些教授给我们的练习来准备考试,但我遇到了一个非常烦人的问题。

该练习需要两个输入 n 和 d,并且程序必须找到从数字 n 中除去 d 位小数后的最小数字。问题出在第 40 或 41 行附近,因为我不知道如何获得足够的循环来尝试每种可能。就目前而言,该程序受到限制,无法在大多数输入下正常运行。

输入示例: 32751960 3

预期输出:21960(这是我们从第一个数字中去掉 3 位小数后得到的最小数字)

我得到的: 31960

预先感谢任何愿意帮助我的人。

代码:

package main

import (
    "fmt"
    "os"
    "bufio"
    "strconv"
    "strings"
    "math"
)

var (
    input string
    n, d, max int
    num, dec string
    in []int
)

func main (){
    getInput()
    max = n
    fmt.Println("Variables: ", n, d)

    //Check
    if d>len(num){
        fmt.Println(math.NaN())
        os.Exit(0)
    }

    //The problematic cicle
    for i:=d; i<=len(num); i++{ //On line 40 or 41 lies the problem: I don't get enough loops to check every possible combination,
                                //and at the same time i have to limit the i var to not exceed the slice boundaries
        temp := num[:i-d] + num[i:] 
        if temp == ""{ //To avoid blank strings
            continue
        }
        itemp, _ := strconv.Atoi(temp)
        fmt.Println(itemp)
        if itemp < max {
            max = itemp
        }

    }
    fmt.Println("Best number:",max)
}

func getInput(){
    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan(){
        input = scanner.Text()
    }
    for _, s := range strings.Fields(input){
        i, err := strconv.Atoi(s)
        if err != nil {
            fmt.Println(err)
        }
        in = append(in, i) //
    }
    n = in[0] //main number
    d = in[1] //decimals to remove
    num = strconv.Itoa(n)
    dec = strconv.Itoa(d) 
}

解决方案


你需要先考虑算法。
并且要删除的数字似乎不连续:
这里 temp := num[:i-d] + num[i:] 您正在尝试删除 3 个相邻的数字(对于 d=3),并且您应该尝试删除不相邻的数字。
提示:
一次删除一位数字 (k): n = n[:k] + n[k+1:]

  1. 首先出于学习目的,我建议您尝试暴力方法:生成所有可能的状态并找到其中最小的数字。
  1. 对于最小的数字,左边的数字小于右边的数字。
    删除 d 不连续的数字,然后找到最小的数字。我建议对 d 数字进行一个循环:
    for i := 0;我 < d; i++ {
    另一个循环用于查找要删除的 k 位置:
    for j := 0; j < k; j++ {

例如 thisthis

package main

import "fmt"

func main() {
    n := "32751960"
    d := 3
    // fmt.scan(&n, &d)
    for i := 0; i < d; i++ {
        k := len(n) - 1
        for j := 0; j < k; j++ {
            if n[j] > n[j+1] {
                k = j
                break
            }
        }
        n = n[:k] + n[k+1:]
    }
    fmt.println(n) // 21960
}
  1. 使用 1 个循环,例如 this
package main

import "fmt"

func main() {
    n := "322311"
    d := 3
    // fmt.Scan(&n, &d)
    for j := 0; j < len(n)-1; j++ {
        if n[j] > n[j+1] {
            n = n[:j] + n[j+1:]
            j = -1
            d--
            if d <= 0 {
                break
            }
        }
    }
    n = n[:len(n)-d]
    fmt.Println(n) // 211
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>