Why is my solution incorrect for tour of go slices exercise?

Viewed 190

I am learning golang and trying to finish the tour of go. I am stuck on the exercise for slices. Copy pasting the question and my solution here. Can someone critique it and tell me what I am doing incorrectly here?

Question:

Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit 
unsigned integers. When you run the program, it will display your picture,
interpreting the integers as grayscale (well, bluescale) values.

The choice of image is up to you. Interesting functions include (x+y)/2, x*y, and x^y.

(You need to use a loop to allocate each []uint8 inside the [][]uint8.)

(Use uint8(intValue) to convert between types.)

My Solution:

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
    ans := make([][]uint8, dy)
    for i:=0; i< dy; i++ {
        slice := make([]uint8, dx)
        for j := 0; j<dx;j++{
            slice = append(slice, uint8((i+j)/2))
        }
        ans = append(ans,slice)
    }
    return ans
}

func main() {
    pic.Show(Pic)
}

Upon running I get the error:

panic: runtime error: index out of range [0] with length 0

I am not sure what I am doing wrong here. Also, why is there a function being passed in the exercise? Is this intended?

1 Answers

Ok I got it. As I said in my comment, you should replace your append calls by slice[j] = uint((i+j)/2) and ans[i] = slice.

The exercise calls your function with 256x256. You create a slice that is 256 long and then append other slices 256 times, resulting in a 512 long slice ans. The first 256 entries are empty, since append appends slice at the end. Therefore when the pic library iterates your data, it tries to access an empty slice.

Update: Another way to fix the algorithm is to initialize the slices with length of 0. So editing

ans := make([][]uint8, 0) and slice := make([]uint8, 0)

should also give the correct results.

Related