DEV Community

loading...

Discussion on: Daily Challenge #5 - Ten Minute Walk

Collapse
margo1993 profile image
margo1993
type PersonPosition struct {
    xAxis int
    yAxis int
}

func GenerateWalk(minutes int) ([]string, error) {
    personPosition := PersonPosition{0, 0}
    var walkingRoute []string

    if minutes % 2 != 0 {
        return walkingRoute, errors.New("Minutes must be even number, otherwise you can't end on starting point")
    }

    rand.Seed(time.Now().UnixNano())
    directions := []string{"n", "s", "e", "w"}

    for i := 0; i < minutes; i++ {

        personYAxis := personPosition.yAxis
        personXAxis := personPosition.xAxis
        distanceFromHome := abs(personYAxis) + abs(personXAxis)
        timeToGoHome := minutes - i
        if personYAxis >= 0 && timeToGoHome  == distanceFromHome{
            directions = removeItemFromArray(directions, "n")
        }

        if personYAxis <= 0 && timeToGoHome == distanceFromHome {
            directions = removeItemFromArray(directions, "s")
        }

        if personXAxis >= 0 && timeToGoHome == distanceFromHome {
            directions = removeItemFromArray(directions, "e")
        }

        if personXAxis <= 0 && timeToGoHome == distanceFromHome {
            directions = removeItemFromArray(directions, "w")
        }

        direction := rand.Intn(len(directions))
        route := directions[direction]
        walkingRoute = append(walkingRoute, route)

        switch route {
        case "n":
            personPosition.yAxis += 1
        case "s":
            personPosition.yAxis -= 1
        case "e":
            personPosition.xAxis += 1
        case "w":
            personPosition.xAxis -= 1
        }
    }

    return walkingRoute, nil
}

func removeItemFromArray(array []string, item string) []string {
    for i,  v:= range array {
        if v == item {
            return append(array[:i], array[i+1:]...)
        }
    }
    return array
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}