Why does my code not solve my golang backtracking problem

50 Views Asked by At

I was set the following problem in school and cannot for the life of me figure out a solution. Any help would be appreciated:

There are 9 cuboids in a box (27cm x 31cm x 43cm). Your job is to build a tower that is exactly 242cm high. Depending on the position of the cuboid, the tower's height therefore increases by 27,31 or 43 cm.

Find the code in Golang, using backtracking, that provides you with all the possible tuples that solve this problem.

I have this so far, but it's not doing what I want it to do and it's driving me bonkers:

package main

import "fmt"

var lv [9]int
var h [3]int= [3]int{27,31,43}
const max = 242

func setze(n int) {
    for i :=0; i <9; i++ {
        for j := 0; j<3; j++ {
            lv[i] = h[j]
        }
    }
    if passt(n) {
        if n == 9 {
            fmt.Println("Eine Lösung ist", lv)
            } else {
            setze(n+1)  
            }
    }
}
            
//Hilfsfunktion Summe
func sum(a []int) int { // gibt ein int zurück
   s := 0
   for i := 0; i < len(a); i++ {
   s = s+ a[i]
    }
    return s
}

//überprüft Bedingungen
func passt (n int) bool {
    return sum(lv[:]) == 242
}

func main() {
    setze(0)
}

1

There are 1 best solutions below

1
0xgotznit On

The primary issue is that your setze function doesn't properly iterate through the options for each position in the tower. Instead, it's assigning all possible heights to each level in the tower, which isn't the intended behavior.

package main

import (
    "fmt"
)

var lv [9]int
var h [3]int = [3]int{27, 31, 43}
const max = 242

// setze tries to build the tower by placing a cuboid at level n.
func setze(n int, sum int) {
    // Base case: if the current height is exactly max and we used all cuboids, we print the solution.
    if sum == max && n == 9 {
        fmt.Println("Eine Lösung ist", lv[:n])
        return
    }

    // If the sum exceeds max or if we have placed all cuboids, we return.
    if sum > max || n >= 9 {
        return
    }

    // Try each type of cuboid at this level.
    for i := 0; i < len(h); i++ {
        lv[n] = h[i]
        setze(n+1, sum + h[i])
    }
}

func main() {
    setze(0, 0)
}