Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tour of Go exercise #18: Slices

Tags:

slice

go

I am trying to complete the Exercise: Slices from the Go Tour.
However I don't really understand what I'm being asked to do.

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.

I have the following code

package main

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

func Pic(dx, dy int) [][]uint8 {
    a := make([][]uint8, dy)
    return a
}

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

I have created the slice of length dy so far. However I don't understand the next step. Do I need to create a for loop in which I assign every element of my slice to a value in the range of dx? I don't ask for code but rather for an explanation/clarification

like image 270
Bula Avatar asked Aug 23 '14 07:08

Bula


People also ask

What is a tour of go?

A Tour of Go is an introduction to the Go programming language. Visit https://tour.golang.org to start the tour.

How do you run the tour program of go?

When you install go, tour is not installed by default. You need to do a go get golang.org/x/tour/gotour . This downloads gotour in your workspace. If your GOPATH is unset, but default you may want to do ${GOPATH:-$HOME/go}/bin/gotour as it will work in either case.


1 Answers

Please find here a suggestion with two approaches.

package main

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

func Pic(dx, dy int) [][]uint8 {
    p := make([][]uint8, dy)
    for y := range p {
        p[y] = make([]uint8, dx)
        for x := range p[y] {
        p[y][x] = uint8(x^y)
        // p[y][x] = uint8(x*y)
        // p[y][x] = uint8((x+y)/2)
        }
    }
    return p
}

func _Pic(dx, dy int) [][]uint8 {
    p := make([][]uint8, dy)
    for i := 0; i < dy; i++ {
        p[i] = make([]uint8, dx)
    }
    for y := range p {
        for x := range p[y] {
            p[y][x] = uint8(x^y)
            // p[y][x] = uint8(x*y)
            // p[y][x] = uint8((x+y)/2)
        }
    }
    return p
}

func main() {
    pic.Show(Pic)
}
like image 141
George I. Tsopouridis Avatar answered Oct 21 '22 14:10

George I. Tsopouridis