DevQuiz 2011 - Go

解答晒し。誰が書いても似た様になるだろうけど。


1つだけ疑問。オリジナルのCountColorの引数がpngになっていたけど、image/pngをimportした時に、名前が衝突してpng.Decode()が呼び出せない。io.Readerの変数名がpngというのも気持ち悪いのでsrcに変更したけど、本当はどうすべきだったのか*1

package main

import (
	"fmt"
	"io"
	"strings"
	"image"
	"image/png"
	/* add more */
)

func rgbaToInt(s image.Color) uint32 {
	r, g, b, a := s.RGBA()
	i32 := r + g<<8 + b<<16 + a<<24 
	return i32
}

func CountColor(src io.Reader) int {
	hash := make(map[uint32] int)

	dec, e := png.Decode(src)
	if e != nil {
		fmt.Println(e)
		return -1
	}

	for y := dec.Bounds().Min.Y; y < dec.Bounds().Max.Y; y++ {
		for x := dec.Bounds().Min.X; x < dec.Bounds().Max.X; x++ {
			color := dec.At(x, y)
			if hash[rgbaToInt(color)] != 1 {
			   hash[rgbaToInt(color)] = 1
			}
		}
	}
	return len(hash)
}

/* これらの関数は提出時に自動挿入されます。 */
func main() {
	png := GetPngBinary()
	cnt := CountColor(png)
	fmt.Println(cnt)
}

*1:@adakoda 情報: importでPNG "image/png"とするとエイリアスがつけられる。