I'm trying to do some exercise our professor gave us to prepare for the exam, but I'm stuck on a pretty annoying problem.
The exercise require two inputs, n and d, and the program has to find the smallest number removing d decimals from the number n. The problem lies around line 40 or 41, because I don't know how to get enough loops to try out every possibily. As for now, the program is limited and won't work properly with most of the inputs.
Example input: 32751960 3
Expected output: 21960 (which is the smallest number we can get by removing 3 decimals from the first number)
What I get: 31960
Thanks in advance to anyone willing to help me.
Code:
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)
}
You need think about algorithm first.
And the digits to remove do not appear to be contiguous:
Here temp := num[:i-d] + num[i:]
you are trying to remove 3 adjacent digits (for d=3
) and you should try to remove also not adjacent digits.
Tip:
Remove one digit at a time (k
): n = n[:k] + n[k+1:]
d
not contiguous digits then find smallest number. I recommend one loop for d
digits:for i := 0; i < d; i++ {
k
position to remove:for j := 0; j < k; j++ {
.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
}
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
}