入門Goプログラミングのアウトプット

2021-01-15 更新

書籍: 入門Goプログラミングの中にある、チャレンジのアウトプット。

Challenge1


package main

import (
	"fmt"
	"math/rand"
)

const (
	Distance = 62100000
	Day      = 24 * 60 * 60
)

func main() {
	fmt.Println("Spaceline        Days  Trip type   Price")
	fmt.Println("========================================")

	for i := 0; i < 10; i++ {
		var agent string
		var trip_type string
		var price int
		var days int

		// 旅行会社をランダムに決定
		switch n := rand.Intn(3); n {
		case 0:
			agent = "Space Adventures"
		case 1:
			agent = "SpaceX"
		case 2:
			agent = "Virgin Galactic"
		}

		// 往復か、片道かをランダムに決定
		if r := rand.Intn(2); r == 0 {
			trip_type = "Round-trip"
		} else {
			trip_type = "One-way"
		}

		// 飛行速度
		speed := rand.Intn(15) + 16

		// 料金(往復なら価格2倍)
		price = speed + 20

		if trip_type == "Round-trip" {
			price *= 2
		}

		// days
		days = Distance / speed / Day

		fmt.Printf("%-16v %-5v %-11v $ %2v\n", agent, days, trip_type, price)
	}

}

結果


Spaceline        Days  Trip type   Price
========================================
Virgin Galactic  39    One-way     $ 38
Virgin Galactic  37    One-way     $ 39
SpaceX           42    Round-trip  $ 74
Space Adventures 42    Round-trip  $ 74
Space Adventures 24    One-way     $ 49
Virgin Galactic  34    One-way     $ 41
Virgin Galactic  34    Round-trip  $ 82
Space Adventures 24    Round-trip  $ 98
Space Adventures 31    One-way     $ 43
SpaceX           44    Round-trip  $ 72

fmt.Printf()内の %-16v について

Printfは文章の任意の場所で値を置換する以外に、テキストのアラインメント(文字寄せ)を調節可能。

%5v といった正の数なら左に空白を置く。
%-10v 負の数なら右に空白が入る。


a, b := "left", "right"
  fmt.Printf("111%-5v111\n", a)
  fmt.Printf("111%10v111\n", b)

111left 111
111     right111

P.98 練習問題-1


package main

import (
	"fmt"
)

func main() {
	message := ""

	cipherText := "CSOITEUIWUIZNSROCNKFD"
	keyword := "GOLANG"
	keyIndex := 0

	for i := 0; i < len(cipherText); i++ {
		c := cipherText[i] - 'A'
		k := keyword[keyIndex] - 'A'
		
		c = (c-k+26)%26 + 'A'
		message += string(c)

		keyIndex++
		keyIndex %= len(keyword)
	}

	fmt.Println(message)
}

結果


WEDIGYOULUVTHEGOPHERS

P.170 練習問題

文章の文字列に含まれる単語の出現頻度を数え、2回以上出現した単語を表示する。


package main

import (
	"fmt"
	"strings"
)

func countWords(s string) map[string]int {
	strSlice := strings.Fields(strings.ToLower(s)) // 小文字に変換し、一単語ずつスライスに格納
	wordCounter := make(map[string]int, len(strSlice))

	for _, i := range strSlice {
		i = strings.Trim(i, ",.;?") // 句読点などを削除
		wordCounter[i]++
	}

	return wordCounter
}

func main() {
	s := "As far as eye could reach he saw nothing but the stems of the great plants about him receding in the violet shade, and far overhead the multiple transparency of huge leaves filtering the sunshine to the solemn splendour of twilight in which he walked. Whenever he felt able he ran again; the ground continued soft and springy, covered with the same resilient weed which was the first thing his hands had touched in Malacandra. Once or twice a small red creature scuttled across his path, but otherwise there seemed to be no life stirring in the wood; nothing to fear—except the fact of wandering unprovisioned and alone in a forest of unknown vegetation thousands or millions of miles beyond the reach or knowledge of man."

	wordCounter := countWords(s)

	for word, count := range wordCounter {
		if count >= 2 {
			fmt.Printf("%v -> %v\n", word, count)
		}
	}
}

結果


nothing -> 2
his -> 2
as -> 2
and -> 3
a -> 2
which -> 2
but -> 2
in -> 5
he -> 4
the -> 12
far -> 2
to -> 3
of -> 7
or -> 3
reach -> 2
Go