<repo_name>wtrb/go<file_sep>/codility/10-prime-composite-numbers/min-perimeter-rectangle/min_perimeter_rectangle.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/trainingZHTSZ9-M3D/
// Detected time complexity: O(sqrt(N))
func min(N int) int {
	a := 1
	b := N / a
	minPeri := 2 * (a + b)

	for a*a <= N {
		if N%a == 0 {
			b = N / a
			cur := 2 * (a + b)
			if cur < minPeri {
				minPeri = cur
			}
		}
		a++
	}

	return minPeri
}

func main() {
	fmt.Println(min(30)) // 22
}
<file_sep>/tour/others/ellipsis.go
package main

import (
	"fmt"
)

func main() {
	// 1. variadic parameter
	fmt.Println(Sum(2, 3, 6))

	// 2.
	primes := []int{2, 3, 5, 7}
	fmt.Println(Sum(primes...)) // unpacking

	// 3. Array literals
	// the ... notation specifies a length equal to the number of elements in the literal
	stooges := [...]string{"Moe", "Larry", "Curly"}
	fmt.Println(len(stooges))
}

// Variadic function parameters
func Sum(nums ...int) int {
	res := 0
	for _, n := range nums {
		res += n
	}
	return res
}

// Three dots<file_sep>/codility/06-sorting/disc-intersections/disc_test.go
package disc

import (
	"testing"
)

func TestSolution(t *testing.T) {
	for _, c := range testCases {
		output := Solution(c.input)
		if output != c.expected {
			t.Fatalf("\nFAIL: %v\nInput: %v\nexpected: %v\ngot: %v", c.description, c.input, c.expected, output)
		}

		t.Logf("PASS: %v", c.description)
	}
}

func BenchmarkSolution(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, c := range testCases {
			Solution(c.input)
		}
	}
}

var testCases = []struct {
	description string
	input       []int
	expected    int
}{
	{
		description: "No.1",
		input:       []int{1, 5, 2, 1, 4, 0},
		expected:    11,
	},
}
<file_sep>/exercism/two-fer/two_fer.go
// Package twofer implements "One for you and one for me." logic.
package twofer

import "fmt"

// ShareWith returns the string "One for {name}, one for me.". If name is empty, "you" is used.
func ShareWith(name string) string {
	if name == "" {
		name = "you"
	}

	return fmt.Sprintf("One for %s, one for me.", name)
}
<file_sep>/tour/basic/08-pointer.go
package main

import (
	"fmt"
)

func main() {
	i := 7
	fmt.Println("Memory address: ", &i)

	inc1(i)
	fmt.Println("i not modified: ", i)

	inc2(&i)
	fmt.Println("i incremented successfully: ", i)
	fmt.Println("i memory address after incremented: ", &i, " , still the same")
}

func inc1(x int) {
	x++
}

func inc2(x *int) {
	*x++
}<file_sep>/tour/methods-interfaces/12-readers.go
package main

import (
	"fmt"
	"io"
	"strings"
)

func main() {
	r := strings.NewReader("Hello, Reader!")

	b := make([]byte, 8)
	for {
		n, err := r.Read(b)
		fmt.Printf("n = %v || err = %v || b = %v\n", n, err, b)
		fmt.Printf("b[:n] = %q\n", b[:n])
		fmt.Printf("---\n")
		if err == io.EOF {
			break
		}
	}
}

/*
n = 8 || err = <nil> || b = [72 101 108 108 111 44 32 82]
b[:n] = "Hello, R"
---
n = 6 || err = <nil> || b = [101 97 100 101 114 33 32 82]
b[:n] = "eader!"
---
n = 0 || err = EOF || b = [101 97 100 101 114 33 32 82]
b[:n] = ""
---
*/

/*
The io package specifies the io.Reader interface, which represents the read end of a stream of data.

The Go standard library contains many implementations of these interfaces, including files, network connections, compressors, ciphers, and others.

The io.Reader interface has a Read method:

func (T) Read(b []byte) (n int, err error)
*/<file_sep>/codility/09-max-slice-problem/max_slice_problem.go
package main

import (
	"fmt"
)

// prefix sums
// O(n**2)
func max1(A []int) int {
	prefixSums := make([]int, len(A)+1)
	for i := 1; i < len(A)+1; i++ {
		prefixSums[i] = prefixSums[i-1] + A[i-1]
	}

	maxSum := 0
	for p := 0; p < len(A); p++ {
		for q := p; q < len(A); q++ {
			sum := prefixSums[q+1] - prefixSums[p]
			if sum > maxSum {
				maxSum = sum
			}
		}
	}
	return maxSum
}

// without prefix sums
// O(n**2)
func max2(A []int) int {
	maxSum := 0
	for p := 0; p < len(A); p++ {
		sum := 0
		for q := p; q < len(A); q++ {
			sum += A[q]
			if sum > maxSum {
				maxSum = sum
			}
		}
	}
	return maxSum
}

// O(n)
func max(A []int) int {
	maxSum := 0
	sum := 0

	for _, a := range A {
		if sum+a > 0 {
			sum += a

		} else {
			sum = 0
		}

		if sum > maxSum {
			maxSum = sum
		}
	}

	return maxSum
}

func main() {
	fmt.Println(max([]int{1, 2, 3, 4, 5}))          // 15
	fmt.Println(max([]int{5, -7, 3, 5, -2, 4, -1})) // 10
	fmt.Println(max([]int{5, -1}))                  // 5
}
<file_sep>/codility/others/prefix-multiply/prefix_multiply.go
package main

import (
	"fmt"
)

func mul(A []int) []int {
	result := make([]int, len(A))

	for i := 1; i < len(A); i++ {
		result[i-1] = 
	}

	return result
}

func main() {
	fmt.Println(mul([]int {1, 2, 3, 4}))
	// [24, 12, 8, 6]
}<file_sep>/codility/05-prefix-sums/count-div/count_div.go
package div

// 0 <= A ≤ B <= 2,000,000,000
// 1 <= K <= 2,000,000,000
func Solution(A int, B int, K int) int {
	if A == 0 {
		return B/K + 1 // +1 because 0 mod any number = 0
	}
	return B/K - (A-1)/K
}

// https://app.codility.com/demo/results/trainingAZHYCH-BKG/
// Detected time complexity:
// O(1)
<file_sep>/exercism/house/house.go
package house

import (
	"bytes"
	"strings"
)

var (
	subjects = [...]string{"This", "that", "that", "that", "that", "that", "that", "that", "that", "that", "that", "that"}
	verbs    = [...]string{
		"is",
		"belonged to",
		"kept",
		"woke",
		"married",
		"kissed",
		"milked",
		"tossed",
		"worried",
		"killed",
		"ate",
		"lay in",
	}
	objects = [...]string{
		"the house that Jack built",
		"the malt",
		"the rat",
		"the cat",
		"the dog",
		"the cow with the crumpled horn",
		"the maiden all forlorn",
		"the man all tattered and torn",
		"the priest all shaven and shorn",
		"the rooster that crowed in the morn",
		"the farmer sowing his corn",
		"the horse and the hound and the horn",
	}
)

// Verse returns a part of the song.
func Verse(depth int) string {
	var buf bytes.Buffer

	// First line
	s := subjects[0]
	v := verbs[0]
	o := objects[depth-1]

	line := strings.Join([]string{s, v, o}, " ")
	buf.WriteString(line)

	// Second line and more
	for i := 1; i < depth; i++ {
		buf.WriteString("\n")

		s = subjects[i]
		v = verbs[len(verbs)-depth+i]
		o = objects[depth-1-i]

		line = strings.Join([]string{s, v, o}, " ")
		buf.WriteString(line)
	}

	buf.WriteString(".")

	return buf.String()
}

// Song returns the entire song.
func Song() string {
	var buf bytes.Buffer
	for i := 1; i <= len(verbs); i++ {
		buf.WriteString(Verse(i))
		buf.WriteString("\n\n")
	}
	return strings.TrimSuffix(buf.String(), "\n\n")
}
<file_sep>/learn-go-with-tests/fundamentals/03-iteration/iteration.go
package iteration

// Repeat returns character repeated by input times.
func Repeat(c string, count int) string {
	if count <= 0 {
		return c
	}

	var repeated string
	for i := 0; i < count; i++ {
		repeated += c
	}
	return repeated
}
<file_sep>/exercism/bank-account/bank_account.go
package account

import (
	"sync"
)

// Account represents a bank account.
type Account struct {
	sync.RWMutex
	balance int64
	closed  bool
}

// Open opens an account with the initial deposit. A negative deposit returns nil.
func Open(initialDeposit int64) *Account {
	if initialDeposit < 0 {
		return nil
	}
	return &Account{balance: initialDeposit, closed: false}
}

// Close will close the account and return the current balance.
func (acc *Account) Close() (payout int64, ok bool) {
	acc.Lock()
	defer acc.Unlock()

	if !acc.closed {
		acc.closed = true
		payout = acc.balance
		ok = true
	}
	return
}

// Balance will return account's current balance, or (0, false) if the account is closed.
func (acc *Account) Balance() (balance int64, ok bool) {
	acc.RLock()
	defer acc.RUnlock()

	if acc.closed {
		return
	}
	return acc.balance, true
}

// Deposit will deposit or withdraw (if negative) the specified amount.
// Withdrawals will not succeed if they result in a negative balance.
func (acc *Account) Deposit(amount int64) (newBalance int64, ok bool) {
	acc.Lock()
	defer acc.Unlock()

	if acc.closed {
		return
	}

	newBalance = acc.balance + amount
	if newBalance < 0 {
		return
	}
	acc.balance = newBalance
	ok = true
	return
}
<file_sep>/tour/basic/07-function.go
package main

import (
	"errors"
	"fmt"
	"math"
)

func main() {
	// func
	result := sum(233, 23)
	fmt.Println("result = ", result)

	//
	result2, err := sqrt(-14)
	if err != nil {
		fmt.Println("err: ", err)
	} else {
		fmt.Println("square = ", result2)
	}
}

// When two or more consecutive named function parameters share a type,
// you can omit the type from all but the last.
func sum(x, y int) int {
	return x + y
}

// A function can return any number of results.
func sqrt(x float64) (float64, error) {
	if x < 0 {
		return 0, errors.New("Undefied for nagative numbers")
	}

	return math.Sqrt(x), nil
}
<file_sep>/exercism/robot-simulator/defs.go
package robot

// definitions used in step 1

// Step1Robot is robot.
var Step1Robot struct {
	X, Y int
	Dir
}

// Dir represents directions.
type Dir int

// Directions: North, East, South, West.
const (
	N Dir = iota
	E
	S
	W
)

// String returns formatted direction.
func (d Dir) String() (s string) {
	switch d {
	case N:
		s = "North"
	case E:
		s = "East"
	case S:
		s = "South"
	case W:
		s = "West"
	}
	return
}

// Right turns right.
func Right() {
	Step1Robot.Dir++
	if Step1Robot.Dir > W {
		Step1Robot.Dir = N
	}
}

// Left turns left.
func Left() {
	Step1Robot.Dir--
	if Step1Robot.Dir < N {
		Step1Robot.Dir = W
	}
}

// Advance moves ahead.
func Advance() {
	switch Step1Robot.Dir {
	case N:
		Step1Robot.Y++
	case E:
		Step1Robot.X++
	case S:
		Step1Robot.Y--
	case W:
		Step1Robot.X--
	}
}

// additional definitions used in step 2

// Command commands the robot to move. Valid values are 'R', 'L', 'A'.
type Command byte
type RU int
type Pos struct{ Easting, Northing RU }
type Rect struct{ Min, Max Pos }
type Step2Robot struct {
	Dir
	Pos
}

// StartRobot starts robot.
func StartRobot(chan Command, chan Action) {

}

// Room prepares the room.
func Room(extent Rect, robot Step2Robot, act chan Action, rep chan Step2Robot) {

}

// additional definition used in step 3

// type Step3Robot struct {
// 	Name string
// 	Step2Robot
// }
<file_sep>/gophercises/README.md
# gophercises
gophercises.com
<file_sep>/exercism/bob/bob.go
// Package bob provides a function that simulates Bob's responses to people's questions.
package bob

import (
	"strings"
)

// Remark is a convenience type for identifying what kind of remark it is.
type Remark string

func (r Remark) isQuestion() bool {
	return strings.HasSuffix(string(r), "?")
}

func (r Remark) isYelling() bool {
	allNonLetter := true
	for _, c := range r {
		if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') {
			allNonLetter = false
		}
		if c >= 'a' && c <= 'z' {
			return false
		}
	}
	return !allNonLetter
}

func (r Remark) isExasperated() bool {
	return r.isYelling() && r.isQuestion()
}

func (r Remark) isSilence() bool {
	return r == ""
}

// Hey simulates Bob's reponse to inputted remark.
func Hey(remark string) string {
	r := Remark(strings.TrimSpace(remark))
	switch {
	case r.isExasperated():
		return "Calm down, I know what I'm doing!"
	case r.isQuestion():
		return "Sure."
	case r.isYelling():
		return "Whoa, chill out!"
	case r.isSilence():
		return "Fine. Be that way!"
	default:
		return "Whatever."
	}
}
<file_sep>/codility/06-sorting/max-product/max_product.go
package product

import "sort"

// https://app.codility.com/demo/results/training3STRZ3-6SX/
// Detected time complexity:
// O(N * log(N))
func Solution(A []int) int {
	sort.Ints(A)
	i := len(A) - 1
	rMax := A[i] * A[i-1] * A[i-2]
	lMax := A[0] * A[1] * A[i]

	if rMax > lMax {
		return rMax
	}
	return lMax
}

// Time complexity: O(n)
// Space complexity: O(1)
func useSingleScan(nums []int) int {
	min1, min2 := 1<<63-1, 1<<63-1
	max1, max2, max3 := -1<<63, -1<<63, -1<<63

	for _, n := range nums {
		if n <= min1 {
			min1, min2 = n, min1
		} else if n <= min2 {
			min2 = n
		}

		if n >= max1 {
			max1, max2, max3 = n, max1, max2
		} else if n >= max2 {
			max2, max3 = n, max2
		} else if n >= max3 {
			max3 = n
		}
	}

	p1 := min1 * min2 * max1
	p2 := max3 * max2 * max1

	if p1 > p2 {
		return p1
	}
	return p2
}
<file_sep>/codility/05-prefix-sums/genomic-range-query/genomic.go
package genomic

import (
	"strings"
)

// O(N + M)
// https://app.codility.com/demo/results/trainingJ65WK3-RK2/
// Detected time complexity: O(N + M)
func Solution1(S string, P []int, Q []int) []int {
	var genoms [3][]int
	genoms[0] = make([]int, len(S)+1) // A
	genoms[1] = make([]int, len(S)+1) // C
	genoms[2] = make([]int, len(S)+1) // G

	for i, v := range S {
		a, c, g := 0, 0, 0
		switch v {
		case 'A':
			a = 1
		case 'C':
			c = 1
		case 'G':
			g = 1
		}
		genoms[0][i+1] = genoms[0][i] + a
		genoms[1][i+1] = genoms[1][i] + c
		genoms[2][i+1] = genoms[2][i] + g
	}

	result := make([]int, len(P))
	for i := 0; i < len(P); i++ {
		fromIndex := P[i]
		toIndex := Q[i] + 1

		if genoms[0][toIndex]-genoms[0][fromIndex] > 0 {
			result[i] = 1
		} else if genoms[1][toIndex]-genoms[1][fromIndex] > 0 {
			result[i] = 2
		} else if genoms[2][toIndex]-genoms[2][fromIndex] > 0 {
			result[i] = 3
		} else {
			result[i] = 4
		}
	}

	return result
}

// Failed: extreme_large (all max ranges)
// https://app.codility.com/demo/results/training73WDJH-RUG/
// Detected time complexity: O(N + M)
func Solution(S string, P []int, Q []int) []int {
	result := make([]int, len(P))
	for i := 0; i < len(P); i++ {
		strip := S[P[i] : Q[i]+1]
		if strings.Contains(strip, "A") {
			result[i] = 1
		} else if strings.Contains(strip, "C") {
			result[i] = 2
		} else if strings.Contains(strip, "G") {
			result[i] = 3
		} else {
			result[i] = 4
		}
	}

	return result
}
<file_sep>/crypto/ecdh/ecdh.go
package ecdh

import (
	"crypto"
	"encoding/hex"
	"errors"
	"io"
)

var (
	ErrInvalidKey = errors.New("pointer to [32]byte key is required")
	ErrInvalidData = errors.New("[32]byte data is required")
)

type ECDH interface {
	GenerateKeyPair(rand io.Reader) (crypto.PrivateKey, crypto.PublicKey, error)
	ComputeSharedSecret(private crypto.PrivateKey, peerPublic crypto.PublicKey) []byte
}

var Curve25519 ECDH

func init() {
	Curve25519 = ecdhCurve25519{}
}

func PublicKeyToHexString(public crypto.PublicKey) (string, error) {
	switch buf := public.(type) {
	case *[32]byte:
		return hex.EncodeToString(buf[:]), nil
	default:
		return "", ErrInvalidKey
	}
}

func PublicKeyFromHexString(data string) (crypto.PublicKey, error) {
	var public [32]byte

	buf, err := hex.DecodeString(data)
	if err != nil {
		return nil, err
	}

	if len(buf) != 32 {
		return nil, ErrInvalidData
	}

	copy(public[:], buf)

	return &public, nil
}
<file_sep>/exercism/luhn/luhn.go
package luhn

import (
	"regexp"
	"strconv"
	"strings"
)

// Valid determines whether or not a number is valid per the Luhn formula.
func Valid(id string) bool {
	id = strings.Replace(id, " ", "", -1)
	re := regexp.MustCompile(`^\d{2,}$`)
	if !re.MatchString(id) {
		return false
	}

	arr := strings.Split(id, "")
	sum := 0
	alternate := false

	for i := len(arr) - 1; i >= 0; i-- {
		n, _ := strconv.Atoi(arr[i])
		// if err != nil {
		// 	return false
		// }
		if alternate {
			n <<= 1
			if n > 9 {
				n -= 9
			}
		}
		alternate = !alternate
		sum += n
	}

	return (sum%10 == 0)
}
<file_sep>/patterns/concurrency/sieve.go
// A concurrent prime sieve

package main

import "fmt"

// Send the sequence 2, 3, 4, ... to channel 'ch'.
func Generate(ch chan<- int) {
	for i := 2; ; i++ {
		fmt.Print("i=", i)
		ch <- i // Send 'i' to channel 'ch'.
	}
}

// Copy the values from channel 'in' to channel 'out',
// removing those divisible by 'prime'.
func Filter(in <-chan int, out chan<- int, prime int) {
	for {
		i := <-in // Receive value from 'in'.
		if i%prime != 0 {
			out <- i // Send 'i' to 'out'.
		}
	}
}

// The prime sieve: Daisy-chain Filter processes.
func main() {
	ch := make(chan int) // Create a new channel.
	go Generate(ch)      // Launch Generate goroutine.
	for i := 0; i < 10; i++ {
		prime := <-ch
		fmt.Println("prime=", prime)
		ch1 := make(chan int)
		go Filter(ch, ch1, prime)
		ch = ch1
	}
}

/*
i=2 i=3
prime= 2
prime= 3
i=4 i=5 i=6 i=7 i=8 i=9 i=10
prime= 5
prime= 7
i=11 i=12 i=13 i=14 i=15 i=16 i=17 i=18 i=19 i=20 i=21 i=22
prime= 11
prime= 13
prime= 17
i=23 i=24 i=25 i=26 i=27 i=28 i=29 i=30 i=31 i=32 i=33 i=34 i=35 i=36 i=37 i=38 i=39 i=40 i=41 i=42 i=43 i=44 i=45 i=46
prime= 19
prime= 23
prime= 29
i=47
*/<file_sep>/codility/05-prefix-sums/passing-cars/passing_cars_test.go
package passingcars

import (
	"testing"
)

func TestPassingCars(t *testing.T) {
	for _, c := range testCases {
		output := PassingCars(c.input)
		if output != c.expected {
			t.Fatalf("FAIL: %v\nInput: %v\nexpected: %v\ngot: %v", c.description, c.input, c.expected, output)
		}

		t.Logf("PASS: %v", c.input)
	}
}

func BenchmarkPassingCars(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, c := range testCases {
			PassingCars(c.input)
		}
	}
}

var testCases = []struct {
	description string
	input       []int
	expected    int
}{
	{
		description: "five pairs of passing cars",
		input:       []int{0, 1, 0, 1, 1},
		expected:    5,
	},
	{
		description: "five pairs of passing cars",
		input:       []int{0, 1, 0, 1, 1, 0},
		expected:    5,
	},
	{
		description: "seven pairs of passing cars",
		input:       []int{0, 1, 0, 1, 1, 1},
		expected:    7,
	},
	{
		description: "eight pairs of passing cars",
		input:       []int{0, 1, 0, 1, 1, 0, 1},
		expected:    8,
	},
	{
		description: "zero pairs of passing cars",
		input:       []int{1, 1, 1},
		expected:    0,
	},
	{
		description: "zero pairs of passing cars",
		input:       []int{0, 0, 0},
		expected:    0,
	},
}
<file_sep>/avatarme/main.go
package main

import (
	"log"
	"os"
	"image/png"

	"./identicon"
)

func main() {
	text := "<EMAIL>"
	icon, err := identicon.Identicon(text)
	if err != nil {
		log.Fatal(err)
	}

	file, err := os.Create("identicon.png")
	if err != nil {
		log.Fatalf("Fail to create identicon.png: %v", err)
	}

	if err := png.Encode(file, icon); err != nil {
		file.Close()
		log.Fatal(err)
	}

	if err := file.Close(); err != nil {
		log.Fatal(err)
	}

	log.Println("Identicon successfully created.")
}
<file_sep>/codility/04-counting-elements/frog-river-one/frog_river_one.go
package main

import (
	"fmt"
)

func Solution(X int, A []int) int {
	expectedTotal := X * (X + 1) / 2
	total := 0
	seen := make(map[int]struct{})

	for i, v := range A {
		if _, ok := seen[v]; !ok {
			seen[v] = struct{}{}
			total += v
		}
		if total == expectedTotal {
			return i
		}
	}

	return -1
}

func main() {
	fmt.Println(Solution(5, []int{1, 3, 1, 4, 2, 3, 5, 4})) // expected 6
	fmt.Println(Solution(3, []int{1, 3, 1, 3, 2, 1, 3}))    // expected 4
}

// https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/
// https://app.codility.com/demo/results/trainingC7Q4JH-QU6/
// Detected time complexity:
// O(N)<file_sep>/exercism/gigasecond/gigasecond.go
// Package gigasecond provides functions that calculates the moment when someone has lived for 10^9 seconds.
package gigasecond

import (
	"time"
)

// AddGigasecond calculates the moment when someone has lived for 10^9 seconds.
func AddGigasecond(t time.Time) time.Time {
	return t.Add(1e9 * time.Second)
}
<file_sep>/codility/others/phone-number-format/phone_format.go
package main

import (
	"fmt"
	"strings"
)

const (
	space = " "
	dash  = "-"
)

func format(phone string) string {
	phone = removeNonDigits(phone)

	if len(phone) <= 3 {
		return phone
	}

	var result strings.Builder
	i := 0
	for i < len(phone)-4 {
		result.WriteString(phone[i : i+3])
		result.WriteString(dash)

		i += 3
	}

	remainingDigits := len(phone) - i
	switch remainingDigits {
	case 2, 3:
		result.WriteString(phone[i:])
		break
	case 4:
		result.WriteString(phone[i : i+2])
		result.WriteString(dash)
		result.WriteString(phone[i+2:])
		break
	}

	return result.String()
}

func removeNonDigits(s string) string {
	s = strings.ReplaceAll(s, space, "")
	s = strings.ReplaceAll(s, dash, "")
	return s
}

func main() {
	fmt.Println(format(""))                    //
	fmt.Println(format("-"))                   //
	fmt.Println(format("0-"))                  // 0
	fmt.Println(format("00"))                  // 00
	fmt.Println(format("0-0"))                 // 00
	fmt.Println(format("00-"))                 // 00
	fmt.Println(format("014-"))                // 014
	fmt.Println(format("01-4-"))               // 014
	fmt.Println(format("01-4-1"))              // 01-41
	fmt.Println(format("00-44  48 5555 8361")) // 004-448-555-583-61
	fmt.Println(format("0 - 22 1985-324"))     // 022-198-53-24
	fmt.Println(format("555372654"))           // 555-372-654
}
<file_sep>/avatarme/identicon/identicon.go
package identicon

import (
	"errors"

	"crypto/sha1"

	"image"
	"image/color"
	"image/draw"
)

const (
	IconWidth = 250
	CellWidth = IconWidth / 5
)

func Identicon(data string) (image.Image, error) {
	if len(data) < 15 {
		return nil, errors.New("A text of at least 15 characters is required.")
	}

	// hashing the input data
	input := []byte(data)
	hash := sha1.Sum(input)

	// background is grey by default
	background := color.RGBA{240, 240, 240, 255}

	// the last three of the hash is used to generate the foreground color
	r := hash[17]
	g := hash[18]
	b := hash[19]
	foreground := color.RGBA{r, g, b, 255}

	icon := image.NewRGBA(image.Rect(0, 0, IconWidth, IconWidth))

	var p0, p1 image.Point

	// the first 15th of the hash are used to turn pixels on or off depending on even or odd values.
	for i := 0; i < 15; i++ {
		c := &image.Uniform{background}
		if hash[i]%2 == 0 {
			c = &image.Uniform{foreground}
		}

		// 5 columns
		if i < 5 { // 3th column is drawn first
			p0 = image.Pt(2*CellWidth, i*CellWidth)
			p1 = image.Pt(3*CellWidth, (i+1)*CellWidth)
			drawBlock(icon, p0, p1, c)
		} else if i < 10 { // then 2nd and 4th
			p0 = image.Pt(1*CellWidth, (i-5)*CellWidth)
			p1 = image.Pt(2*CellWidth, (i-4)*CellWidth)
			drawBlock(icon, p0, p1, c)

			p0 = image.Pt(3*CellWidth, (i-5)*CellWidth)
			p1 = image.Pt(4*CellWidth, (i-4)*CellWidth)
			drawBlock(icon, p0, p1, c)
		} else if i < 15 { // lastly, first and fifth
			p0 = image.Pt(0*CellWidth, (i-10)*CellWidth)
			p1 = image.Pt(1*CellWidth, (i-9)*CellWidth)
			drawBlock(icon, p0, p1, c)

			p0 = image.Pt(4*CellWidth, (i-10)*CellWidth)
			p1 = image.Pt(5*CellWidth, (i-9)*CellWidth)
			drawBlock(icon, p0, p1, c)
		}
	}

	return icon, nil
}

func drawBlock(dst draw.Image, p0 image.Point, p1 image.Point, src image.Image) {
	draw.Draw(dst, image.Rectangle{p0, p1}, src, image.ZP, draw.Src)
}
<file_sep>/exercism/sieve/sieve.go
package sieve

// Sieve finds all the primes from 2 up to a given number using Sieve of Eratosthenes.
func Sieve(limit int) (primes []int) {
	if limit <= 1 {
		return
	}

	marker := make([]bool, limit+1)

	for p := 2; p*p <= limit; p++ {
		if !marker[p] {
			for i := p * p; i <= limit; i += p {
				marker[i] = true
			}
		}
	}

	for i := 2; i <= limit; i++ {
		if !marker[i] {
			primes = append(primes, i)
		}
	}

	return
}
<file_sep>/codility/09-max-slice-problem/max-double-slice-sum/max_double_slice_sum.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/trainingRJR4TK-YDV/
// Detected time complexity: O(N)
func max(A []int) int {
	forwardSum := make([]int, len(A))
	backwardSum := make([]int, len(A))

	for i := 1; i < len(A)-1; i++ {
		if forwardSum[i-1]+A[i] > 0 {
			forwardSum[i] = forwardSum[i-1] + A[i]
		} else {
			forwardSum[i] = 0
		}
	}
	for i := len(A) - 2; i >= 1; i-- {
		if backwardSum[i+1]+A[i] > 0 {
			backwardSum[i] = backwardSum[i+1] + A[i]
		} else {
			backwardSum[i] = 0
		}
	}

	max := 0
	for i := 0; i < len(A)-2; i++ {
		if forwardSum[i]+backwardSum[i+2] > max {
			max = forwardSum[i] + backwardSum[i+2]
		}
	}
	return max
}

func main() {
	fmt.Println(max([]int{3, 2, 6, -1, 4, 5, -1, 2}))
	// forwardSum: [0, 2, 8, 7, 11, 16, 15, 0]
	// backwardSum: [0, 16, 14, 8, 9, 5, 0, 0]
	// result: 17
}
<file_sep>/tour/concurrency/20-Pi-no-routine.go
package main

import (
	"fmt"
	"math"
)

func main() {
	pi := 0.0

	for i := 0; i <= 5000; i++ {
		pi += 4 * math.Pow(-1, float64(i)) / (2*float64(i) + 1)
	}

	fmt.Println(pi)
}
<file_sep>/codility/10-prime-composite-numbers/count-factors/count_factors.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/training8E34M3-HNE/
// Detected time complexity: O(sqrt(N))
func count(N int) int {
	c := 0
	i := 1
	for i*i < N {
		if N%i == 0 {
			c += 2
		}
		i++
	}
	if i*i == N {
		c++
	}

	return c
}

func main() {
	fmt.Println(count(24)) // 8
}
<file_sep>/tour/basic/05-if.go
package main

import (
	"fmt"
	"math"
)

func sqrt(x float64) string {
	if x < 0 {
		return sqrt(-x) + "i"
	}
	return fmt.Sprint(math.Sqrt(x))
}

func main() {
	fmt.Println(sqrt(4))
	fmt.Println(sqrt(-4))

	fmt.Println(
		pow(3, 2, 10),
		pow(3, 3, 20),
	)
}

func pow(x, n, lim float64) float64 {
	// If with a short statement
	// Variables declared by the statement are
	// - only in scope until the end of the if.
	// - also available inside any of the else blocks
	if v := math.Pow(x, n); v < lim {
		return v
	} else {
		fmt.Printf("%g >= %g\n", v, lim)
	}
	// can't use v here, though
	return lim
}
<file_sep>/codility/04-counting-elements/missing-integer/missing_integer.go
package missing

import (
	"sort"
)

// O(n*log(n))
// https://app.codility.com/demo/results/trainingPYGD47-NCS/
// Detected time complexity: O(N) or O(N * log(N))
func Solution1(A []int) int {
	sort.Ints(A)
	min := 1
	for _, v := range A {
		if v == min {
			min++
		}
	}

	return min
}

// O(n)
// https://app.codility.com/demo/results/trainingT3JKNV-YMX/
// Detected time complexity: O(N) or O(N * log(N))
func Solution(A []int) int {
	positiveElems := make(map[int]struct{})
	for _, v := range A {
		if v > 0 {
			positiveElems[v] = struct{}{}
		}
	}

	min := 1
	for {
		if _, prs := positiveElems[min]; !prs {
			return min
		}
		min++
	}
}
<file_sep>/codility/05-prefix-sums/count-div/count_div_test.go
package div

import (
	"testing"
)

func TestSolution(t *testing.T) {
	for _, c := range testCases {
		output := Solution(c.input[0], c.input[1], c.input[2])
		if output != c.expected {
			t.Fatalf("\nFAIL: %v\nInput: [%v..%v] and %v\nexpected: %v\ngot: %v", c.description, c.input[0], c.input[1], c.input[2], c.expected, output)
		}

		t.Logf("PASS: %v", c.description)
	}
}

func BenchmarkSolution(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, c := range testCases {
			Solution(c.input[0], c.input[1], c.input[2])
		}
	}
}

var testCases = []struct {
	description string
	input       []int
	expected    int
}{
	{
		description: "No.1",
		input:       []int{6, 11, 2},
		expected:    3,
	},
	{
		description: "No.2",
		input:       []int{11, 14, 2},
		expected:    2,
	},
	{
		description: "No.3",
		input:       []int{11, 345, 17},
		expected:    20,
	},
	{
		description: "No.4",
		input:       []int{0, 1, 11},
		expected:    1,
	},
	{
		description: "No.5",
		input:       []int{10, 10, 5},
		expected:    1,
	},
	{
		description: "No.6",
		input:       []int{10, 10, 7},
		expected:    0,
	},
	{
		description: "No.7",
		input:       []int{10, 10, 20},
		expected:    0,
	},
}
<file_sep>/codility/02-arrays/odd-occurrences/odd.go
package main

import (
	"fmt"
)

func Solution(A []int) int {
	m := make(map[int]int)
	for _, v := range A {
		m[v]++
	}
	for k := range m {
		if m[k]%2 != 0 {
			return k
		}
	}
	return -1
}

func main() {
	fmt.Println(Solution([]int{9, 3, 9, 3, 9, 7, 9}))
}

// https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/<file_sep>/exercism/isbn-verifier/isbn_verifier.go
package isbn

import (
	"strconv"
	"strings"
)

// IsValidISBN validates the input ISBN number.
func IsValidISBN(isbn string) bool {
	isbn = strings.Replace(isbn, "-", "", -1)
	if len(isbn) != 10 {
		return false
	}

	arr := strings.Split(isbn, "")
	sum := 0
	
	if arr[len(arr)-1] == "X" {
		sum += 10
		arr = arr[0 : len(arr)-1]
	}

	for i := 0; i < len(arr); i++ {
		v, err := strconv.Atoi(arr[i])
		if err != nil {
			return false
		}
		sum += v * (10 - i)
	}

	if sum%11 == 0 {
		return true
	}

	return false
}
<file_sep>/tour/image-api/two-colorful-rectangles.go
package main

import (
	"image"
	"image/color"
	"image/draw"
	"image/png"
	"os"
)

func main() {

	new_png_file := "two_rectangles.png"

	myimage := image.NewRGBA(image.Rect(0, 0, 220, 220)) // x1,y1,  x2,y2
	mygreen := color.RGBA{0, 100, 0, 255}                //  R, G, B, Alpha

	// backfill entire surface with green
	draw.Draw(myimage, myimage.Bounds(), &image.Uniform{mygreen}, image.ZP, draw.Src)

	red_rect := image.Rect(60, 80, 120, 160) //  geometry of 2nd rectangle
	myred := color.RGBA{200, 0, 0, 255}

	// create a red rectangle atop the green surface
	draw.Draw(myimage, red_rect, &image.Uniform{myred}, image.ZP, draw.Src)

	myfile, _ := os.Create(new_png_file) // ... now lets save imag
	png.Encode(myfile, myimage)
}
<file_sep>/codility/07-stacks-queues/nesting/nesting.go
package main

import (
	"fmt"
)

// Performance issue:
// https://app.codility.com/demo/results/trainingD69EKZ-5BP/
// Detected time complexity: O(N)

// https://app.codility.com/demo/results/trainingZEWMVA-SUN/
// Detected time complexity: O(N)
func Solution(S string) int {
	if 0 == len(S) {
		return 1
	}
	if 0 != len(S)%2 {
		return 0
	}

	stack := []rune{}
	for _, r := range S {
		switch r {
		case '(':
			stack = append(stack, r)
		case ')':
			len := len(stack)
			if 0 == len {
				return 0
			}
			if stack[len-1] != '(' {
				return 0
			}
			stack = stack[:len-1]
		default:
			return 0
		}
	}

	if 0 == len(stack) {
		return 1
	}
	return 0
}

func main() {
	fmt.Println(Solution(""))           // 1
	fmt.Println(Solution("("))          // 0
	fmt.Println(Solution("(()(())())")) // 1
	fmt.Println(Solution("())"))        // 0
}
<file_sep>/codility/11-sieve-of-eratoshenes/sieve.go
package main

import (
	"fmt"
)

func primes(n int) []int {
	marker := make([]bool, n+1)
	for p := 2; p*p <= n; p++ {
		if !marker[p] {
			for i := p * p; i <= n; i += p {
				marker[i] = true
			}
		}
	}

	prime := []int{}
	for i := 2; i <= n; i++ {
		if !marker[i] {
			prime = append(prime, i)
		}
	}
	return prime
}

func factors(n int64) []int64 {
	r := make([]int64, 0)
	for i := int64(2); i <= n; i++ {
		for n%i == 0 {
			r = append(r, i)
			n /= i
		}
	}

	return r
}

func main() {
	fmt.Println(primes(10)) // 2, 3, 5, 7
	fmt.Println(primes(17)) /// 2, 3, 5, 7, 11, 13, 17
	fmt.Println(primes(30)) // 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
}
<file_sep>/exercism/grains/grains.go
// Package grains provides function that calculates the number of grains of wheat on a chessboard given that the number on each square doubles.
package grains

import "errors"

// Square returns the number of grains on a square.
func Square(square int) (uint64, error) {
	if square < 1 || square > 64 {
		return 0, errors.New("square must be from 1 to 64")
	}

	return 1 << uint64(square-1), nil
}

// Total returns the total number of grains there could be on a chessboard.
func Total() uint64 {
	return 1<<64 - 1
}
<file_sep>/codility/05-prefix-sums/passing-cars/passing_cars.go
package passingcars

const max = 1000000000

// https://app.codility.com/demo/results/trainingVWFGAN-ZNG/
// Detected time complexity:
// O(N)
func PassingCars1(A []int) int {
	total := 0
	count := 0

	for i := 0; i < len(A); i++ {
		if A[i] == 0 {
			count++
		} else {
			total += count
		}

		if total > max {
			return -1
		}
	}

	return total
}

// O(n)
// https://app.codility.com/demo/results/training8HTB7M-TV9/
// Detected time complexity: O(N)
func PassingCars(A []int) int {
	total := 0
	for _, v := range A {
		total += v
	}

	passingCars := 0
	leftTotal := 0
	for _, v := range A {
		if v == 0 {
			passingCars += total - leftTotal
			if passingCars > max {
				return -1
			}
		}
		leftTotal += v
	}

	return passingCars
}
<file_sep>/exercism/parallel-letter-frequency/frequency.go
package letter

import (
	"sync"
)

// FreqMap records the frequency of each rune in a given text.
type FreqMap map[rune]int

// Frequency counts the frequency of each rune in a given text and returns this
// data as a FreqMap.
func Frequency(s string) FreqMap {
	m := FreqMap{}
	for _, r := range s {
		m[r]++
	}
	return m
}

// ConcurrentFrequency is the concurrent version of Frequency.
func ConcurrentFrequency(strs []string) FreqMap {
	var counter = struct {
		sync.Mutex
		freq FreqMap
	}{freq: map[rune]int{}}

	var wg sync.WaitGroup
	wg.Add(len(strs))

	for _, s := range strs {
		go func(s string) {
			for _, r := range s {
				counter.Lock()
				counter.freq[r]++
				counter.Unlock()
			}
			wg.Done()
		}(s)
	}

	wg.Wait()

	return counter.freq
}
<file_sep>/codility/04-counting-elements/max-counters/max_counters.go
package main

import (
	"fmt"
)

func Solution(N int, A []int) []int {
	counter := make([]int, N)
	max := 0
	lastMax := 0
	for _, v := range A {
		if v >= 1 && v <= N {
			cv := counter[v-1]
			if cv < lastMax {
				cv = lastMax
			}
			cv++
			if cv > max {
				max = cv
			}
			counter[v-1] = cv
		} else if v == N+1 {
			lastMax = max
		}
	}

	for i, v := range counter {
		if v < lastMax {
			counter[i] = lastMax
		}
	}
	return counter
}

func main() {
	fmt.Println(Solution(5, []int{3, 4, 4, 6, 1, 4, 4})) // expected: [3, 2, 2, 4, 2]
}

// https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/
// https://app.codility.com/demo/results/trainingAWNA36-FCR/
// Detected time complexity:
// O(N + M)
<file_sep>/exercism/space-age/space_age.go
// Package space provides function to calculate Earth-years old.
package space

// Solar system planets
const (
	Earth   = "Earth"
	Mercury = "Mercury"
	Venus   = "Venus"
	Mars    = "Mars"
	Jupiter = "Jupiter"
	Saturn  = "Saturn"
	Uranus  = "Uranus"
	Neptune = "Neptune"
)

// Planet orbital periods
const (
	EarthObPeriod   float64 = 31557600
	MercuryObPeriod float64 = EarthObPeriod * 0.2408467
	VenusObPeriod   float64 = EarthObPeriod * 0.61519726
	MarsObPeriod    float64 = EarthObPeriod * 1.8808158
	JupiterObPeriod float64 = EarthObPeriod * 11.862615
	SaturnObPeriod  float64 = EarthObPeriod * 29.447498
	UranusObPeriod  float64 = EarthObPeriod * 84.016846
	NeptuneObPeriod float64 = EarthObPeriod * 164.79132
)

// Age calculates and returns Earth-years old.
func Age(seconds float64, planet string) float64 {
	switch planet {
	case Earth:
		return seconds / EarthObPeriod
	case Mercury:
		return seconds / MercuryObPeriod
	case Venus:
		return seconds / VenusObPeriod
	case Mars:
		return seconds / MarsObPeriod
	case Jupiter:
		return seconds / JupiterObPeriod
	case Saturn:
		return seconds / SaturnObPeriod
	case Uranus:
		return seconds / UranusObPeriod
	case Neptune:
		return seconds / NeptuneObPeriod
	}
	return 0.00
}
<file_sep>/exercism/paasio/paasio.go
package paasio

import (
	"io"
	"sync"
)

type counter struct {
	mux    *sync.Mutex
	nbytes int64
	nops   int
}

func newCounter() counter {
	return counter{mux: new(sync.Mutex)}
}
func (c *counter) count(nbytes int) {
	c.mux.Lock()
	defer c.mux.Unlock()
	c.nops++
	c.nbytes += int64(nbytes)
}
func (c *counter) stats() (nbytes int64, nops int) {
	c.mux.Lock()
	defer c.mux.Unlock()
	return c.nbytes, c.nops
}

type readCounter struct {
	r io.Reader
	counter
}

func (rc *readCounter) Read(p []byte) (n int, err error) {
	n, err = rc.r.Read(p)
	rc.count(n)
	return
}
func (rc *readCounter) ReadCount() (nbytes int64, nops int) {
	return rc.stats()
}

type writeCounter struct {
	w io.Writer
	counter
}

func (wc *writeCounter) Write(p []byte) (n int, err error) {
	n, err = wc.w.Write(p)
	wc.count(n)
	return
}
func (wc *writeCounter) WriteCount() (nbytes int64, nops int) {
	return wc.stats()
}

type readWriteCounter struct {
	ReadCounter
	WriteCounter
}

// NewReadCounter returns an implementation of ReadCounter.  Calls to
// r.Read() are not guaranteed to be synchronized.
func NewReadCounter(r io.Reader) ReadCounter {
	return &readCounter{r: r, counter: newCounter()}
}

// NewWriteCounter returns an implementation of WriteCounter.  Calls to
// w.Write() are not guaranteed to be synchronized.
func NewWriteCounter(w io.Writer) WriteCounter {
	return &writeCounter{w: w, counter: newCounter()}
}

// NewReadWriteCounter returns an implementation of ReadWriteCounter.
// Calls to rw.Write() and rw.Read() are not guaranteed to be synchronized.
func NewReadWriteCounter(rw io.ReadWriter) ReadWriteCounter {
	return &readWriteCounter{NewReadCounter(rw), NewWriteCounter(rw)}
}
<file_sep>/tour/basic/12-function-closure-easier-to-understand.go
package main

import (
	"fmt"
)

func main() {
	f := inc()
	fmt.Println(f())
	fmt.Println(f())
	fmt.Println(f())
	fmt.Println(f())
	fmt.Println(f())

	fmt.Println("New...")

	g := inc()
	fmt.Println(g())
	fmt.Println(g())
	fmt.Println(g())
	fmt.Println(g())
	fmt.Println(g())
}

func inc() func() int {
	x := 0
	return func() int {
		x++
		return x
	}
}

/*
1
2
3
4
5
New...
1
2
3
4
5
*/
<file_sep>/exercism/rna-transcription/rna_transcription.go
// Package strand provides function to transcibe dna to rna
package strand

import (
	"bytes"
)

// ToRNA transcibes dna to rna
func ToRNA(dna string) string {
	if dna == "" {
		return ""
	}

	var buf bytes.Buffer
	for _, nucleotide := range dna {
		switch nucleotide {
		case 'G':
			buf.WriteRune('C')
		case 'C':
			buf.WriteRune('G')
		case 'T':
			buf.WriteRune('A')
		case 'A':
			buf.WriteRune('U')
		}
	}
	return buf.String()
}
<file_sep>/codility/others/string-obtained-string/obtained.go
package main

import (
	"fmt"
	"strings"
)

const (
	nothing    = `NOTHING`
	add        = `ADD %s`
	change     = `CHANGE %s %s`
	move       = `MOVE %s`
	impossible = `IMPOSSIBLE`
)

func equal(S, T string) string {
	if S == T {
		return nothing
	}
	return ""
}

func addable(S, T string) string {
	if len(S) == len(T)-1 && S == T[:len(T)-1] {
		return fmt.Sprintf(add, T[len(T)-1:])
	}

	return ""
}

func changable(S, T string) string {
	n := len(S)
	m := len(T)

	if n == m {
		diffIndexes := []int{}
		i := 0
		for i < n {
			if S[i] != T[i] {
				diffIndexes = append(diffIndexes, i)
				if len(diffIndexes) > 1 {
					return ""
				}
			}
			i++
		}
		return fmt.Sprintf(change, string(S[diffIndexes[0]]), string(T[diffIndexes[0]]))
	}

	return ""
}

func moveable(S, T string) string {
	n := len(S)
	m := len(T)

	if n == m {
		for i := 0; i < n; i++ {
			if S[i] != T[i] {
				s := S[i+1:]
				t := strings.Replace(T[i:], string(S[i]), "", 1)
				if s == t {
					return fmt.Sprintf(move, string(S[i]))
				}
				return ""
			}
		}
	}

	return ""
}

func obtain(S, T string) string {
	S = strings.ToLower(S)
	T = strings.ToLower(T)

	result := equal(S, T)
	if result != "" {
		return result
	}

	result = addable(S, T)
	if result != "" {
		return result
	}

	result = changable(S, T)
	if result != "" {
		return result
	}

	result = moveable(S, T)
	if result != "" {
		return result
	}

	return impossible
}

func main() {
	fmt.Println(obtain("", ""))             // NOTHING
	fmt.Println(obtain("a", "a"))           // NOTHING
	fmt.Println(obtain("a", "A"))           // NOTHING
	fmt.Println(obtain("abcd", "AbCD"))     // NOTHING
	fmt.Println(obtain("0", "odd"))         // IMPOSSIBLE
	fmt.Println(obtain("nice", "nicer"))    // ADD r
	fmt.Println(obtain("xx", "xXx"))        // ADD x
	fmt.Println(obtain("test", "tent"))     // CHANGE s n
	fmt.Println(obtain("text", "tent"))     // CHANGE x n
	fmt.Println(obtain("text", "texx"))     // CHANGE t x
	fmt.Println(obtain("test", "tenk"))     // IMPOSSIBLE
	fmt.Println(obtain("beans", "banes"))   // MOVE e
	fmt.Println(obtain("beanse", "banese")) // MOVE e
}
<file_sep>/codility/08-leader/equi-leader/equi_leader.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/training78FUEM-78H/
// O(N)
func Solution(A []int) int {
	if 0 == len(A) {
		return 0
	}

	value := A[0]
	size := 0
	for _, a := range A {
		if 0 == size {
			size++
			value = a
		} else {
			if a != value {
				size--
			} else {
				size++
			}
		}
	}

	candidate := -1
	if 0 != size {
		candidate = value
	}

	count := 0
	for _, a := range A {
		if a == candidate {
			count++
		}
	}

	leader := -1
	if count > len(A)/2 {
		leader = candidate
	} else {
		return 0
	}

	equi := 0
	left := 0
	right := 0
	for i, a := range A {
		if a == leader {
			left++
			right = count - left
		}
		if (left > (i+1)/2) && (right > (len(A)-(i+1))/2) {
			equi++
		}
	}

	return equi
}

func main() {
	fmt.Println(Solution([]int{4, 3, 4, 4, 4, 2})) // 2
}
<file_sep>/codility/05-prefix-sums/min-avg/min_avg_test.go
package minavg

import (
	"testing"
)

func TestSolution(t *testing.T) {
	for _, c := range testCases {
		output := Solution(c.input)
		if output != c.expected {
			t.Fatalf("\nFAIL: %v\nInput: %v\nexpected: %v\ngot: %v", c.description, c.input, c.expected, output)
		}

		t.Logf("PASS: %v", c.description)
	}
}

func BenchmarkSolution(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, c := range testCases {
			Solution(c.input)
		}
	}
}

var testCases = []struct {
	description string
	input       []int
	expected    int
}{
	{
		description: "Positive integers",
		input:       []int{4, 2, 2, 5, 1, 5, 8},
		expected:    1,
	},
	{
		description: "Nagative integers",
		input:       []int{-3, -5, -8, -4, -10},
		expected:    2,
	},
}
<file_sep>/codility/09-max-slice-problem/max-profit/max_profit.go
package main

import (
	"fmt"
)

// O(n)
// https://app.codility.com/demo/results/trainingUZ5J8F-4S6/
func max(A []int) int {
	minDailyPrice := 200000
	maxProfit := 0
	for _, a := range A {
		if a < minDailyPrice {
			minDailyPrice = a
		}
		if a-minDailyPrice > maxProfit {
			maxProfit = a - minDailyPrice
		}
	}
	return maxProfit
}

func main() {
	fmt.Println(max([]int{23171, 21011, 21123, 21366, 21013, 21367})) // 356
}
<file_sep>/codility/04-counting-elements/perm-check/perm_check.go
package main

import (
	"fmt"
)

func Solution(A []int) int {
	counter := make(map[int]struct{})
	for _, v := range A {
		if v > len(A) {
			return 0
		}
		counter[v] = struct{}{}
	}
	if len(counter) == len(A) {
		return 1
	}
	return 0
}

func main() {
	fmt.Println(Solution([]int{4, 1, 3, 2})) // 1
	fmt.Println(Solution([]int{4, 1, 3})) // 0
}

// https://app.codility.com/demo/results/training9WRW9M-F43/
// Detected time complexity:
// O(N) or O(N * log(N))<file_sep>/codility/04-counting-elements/missing-integer/missing_integer_test.go
package missing

import (
	"testing"
)

var testCases = []struct {
	description string
	input       []int
	expected    int
}{
	{
		description: "positve with duplication",
		input:       []int{1, 3, 6, 4, 1, 2},
		expected:    5,
	},
	{
		description: "positve incresing integers starting from 1",
		input:       []int{1, 2, 3},
		expected:    4,
	},
	{
		description: "negative only",
		input:       []int{-1, -3},
		expected:    1,
	},
	{
		description: "positve and negative",
		input:       []int{-1, -3, 0, 4, 2},
		expected:    1,
	},
	{
		description: "minimal and maximal values",
		input:       []int{-1000000, 1000000},
		expected:    1,
	},
	{
		description: "a single element",
		input:       []int{1},
		expected:    2,
	},
	{
		description: "a single element",
		input:       []int{3},
		expected:    1,
	},
	{
		description: "a single element",
		input:       []int{-2},
		expected:    1,
	},
}

func TestSolution(t *testing.T) {
	for _, c := range testCases {
		output := Solution(c.input)
		if output != c.expected {
			t.Fatalf("FAIL: %v\nInput: %v\nexpected: %v\ngot: %v", c.description, c.input, c.expected, output)
		}

		t.Logf("PASS: %v", c.input)
	}
}

func BenchmarkSolution(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, c := range testCases {
			Solution(c.input)
		}
	}
}
<file_sep>/codility/03-time-complexity/frog-jmp/frog_jmp.go
package main

import (
	"fmt"
)

func Solution(X int, Y int, D int) int {
	dis := Y - X
	steps := dis / D
	if dis%D == 0 {
		return steps
	}
	return steps + 1
}

func main() {
	fmt.Println(Solution(10, 85, 30))
}

// https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/
// https://app.codility.com/demo/results/trainingMJ2TT6-F38/
// Detected time complexity:
// O(1)<file_sep>/exercism/alphametics/alphamatics.go
// Package alphametics sfs.
package alphametics

// Solve attempts to solve the alphametics puzzle and return a map of all the letter substitutions for both the puzzle and the addition solution.
func Solve(puzzle string) (map[string]int, error) {

}
<file_sep>/tour/methods-interfaces/04-pointer-receivers.go
package main

import (
	"fmt"
	"math"
)

type Vertex struct {
	X, Y float64
}

func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func (v *Vertex) Scale(f float64) {
	v.X = v.X * f
	v.Y = v.Y * f
}

func main() {
	v := Vertex{3, 4}
	v.Scale(10)
	// even though v is a value and not a pointer, the method with the pointer receiver is called automatically.
	// That is, as a convenience, Go interprets the statement v.Scale(10) as (&v).Scale(10) since the Scale method has a pointer receiver.

	fmt.Println(v.Abs())
}

// You can declare methods with pointer receivers.
// Methods with pointer receivers can modify the value to which the receiver points
// Since methods often need to modify their receiver, pointer receivers are more common than value receivers.
<file_sep>/codility/07-stacks-queues/stone-wall/stone_wall.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/trainingR3MP65-A8J/
// Detected time complexity: O(N)
func Solution(H []int) int {
	stones := 0
	stack := []int{}

	for _, h := range H {
		for 0 != len(stack) && stack[len(stack)-1] > h {
			stack = stack[:len(stack)-1]
		}
		if 0 != len(stack) && stack[len(stack)-1] == h {
			continue
		} else {
			stack = append(stack, h)
			stones++
		}
	}

	return stones
}

func main() {
	fmt.Println(Solution([]int{8, 8, 5, 7, 9, 8, 7, 4, 8})) // 7
	fmt.Println(Solution([]int{3, 2, 1}))                   // 3
}
<file_sep>/exercism/robot-name/robot_name.go
package robotname

import (
	"errors"
	"fmt"
	"math/rand"
	"time"
)

const max = 26 * 26 * 10 * 10 * 10

var counter = 0
var nameDB = map[string]bool{}

func makeName() string {
	src := rand.NewSource(time.Now().UnixNano())
	rnd := rand.New(src)

	c1 := rune('A' + rnd.Int()%26)
	c2 := rune('A' + rnd.Int()%26)
	n := rnd.Int() % 1000

	return fmt.Sprintf("%c%c%03d", c1, c2, n)
}

// Robot has a name.
type Robot struct {
	name string
}

// Name returns robot name.
func (r *Robot) Name() (string, error) {
	if r.name == "" {
		if err := r.Reset(); err != nil {
			return "", err
		}
	}
	return r.name, nil
}

// Reset resets robot name.
func (r *Robot) Reset() error {
	if counter > max {
		return errors.New("namespace is exhausted")
	}

	name := makeName()
	for nameDB[name] {
		name = makeName()
	}

	nameDB[name] = true
	r.name = name
	counter++

	return nil
}
<file_sep>/tour/others/const-iota.go
package main

import (
	"fmt"
)

const (
	Sunday = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Partyday
	sfdsds
	numbdderOfDays  // this constant is not exported
)

func main() {
	fmt.Println("Hello, playground")
	fmt.Println(Sunday)
	fmt.Println(Wednesday)
	fmt.Println(Partyday)
	fmt.Println(numbdderOfDays)
}
<file_sep>/codility/01-iterations/binary_gap.go
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func Solution(N int) int {
	str := strconv.FormatInt(int64(N), 2)
	str = strings.TrimRight(str, "0")
	arr := strings.Split(str, "1")

	longest := 0
	for _, v := range arr {
		if len(v) > longest {
			longest = len(v)
		}
	}

	return longest
}

func main() {
	fmt.Println(Solution(2147483646))
}

// https://app.codility.com/programmers/lessons/1-iterations/binary_gap/<file_sep>/exercism/armstrong-numbers/armstrong.go
package armstrong

import (
	"math"
	"strconv"
)

// IsNumber checks whether a number is an Armstrong number,
// that is the sum of its own digits each raised to the power of the number of digits.
func IsNumber(n int) bool {
	return isNumberVb(n)
}

func isNumberVa(n int) bool {
	sum := 0
	s := strconv.Itoa(n)
	y := float64(len(s))

	for _, v := range s {
		x, _ := strconv.Atoi(string(v))
		sum += int(math.Pow(float64(x), y))
	}
	
	if sum == n {
		return true
	}
	return false
}

func isNumberVb(n int) bool {
	y := float64(int(math.Log10(float64(n))) + 1)

	sum := 0
	i := n
	for {
		x := float64(i % 10)
		sum += int(math.Pow(x, y))
		i /= 10
		if i == 0 {
			break
		}
	}

	if sum == n {
		return true
	}
	return false
}<file_sep>/codility/06-sorting/triangle/trianlge.go
package triangle

import (
	"sort"
)

// https://app.codility.com/demo/results/training8VR3Q4-TKG/
// Detected time complexity:
// O(N*log(N))
func Solution(A []int) int {
	sort.Ints(A)
	for i := 0; i < len(A)-2; i++ {
		if A[i]+A[i+1] > A[i+2] {
			return 1
		}
	}
	return 0
}
<file_sep>/codility/others/trim/trim.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(Solution("The quick brown fox jumps over the lazy dog", 39))
}

func Solution(message string, K int) string {
	if len(message) < K {
		return message
	}

	arr := strings.Split(message, " ")
	for i := len(arr); i > 1; i-- {
		result := strings.Join(arr[:i], " ")
		if len(result) <= K {
			return result
		}
	}

	return ""
}
<file_sep>/codility/others/nth-highest-sums/main.go
package main

func main() {
}

func findHighestSums(lists [][]int, n int) {

}
<file_sep>/codility/06-sorting/disc-intersections/disc.go
package disc

const limit = 10000000

// O(N) complexity and O(N) memory
// https://app.codility.com/demo/results/training39GYB5-J3P/
// Detected time complexity:
// O(N*log(N)) or O(N)
func Solution(A []int) int {
	totalDiscs := len(A)
	startPts := make([]int, totalDiscs)
	endPts := make([]int, totalDiscs)
	for i, a := range A {
		start := i - a
		if start < 0 {
			start = 0
		}

		end := i + a
		if end > (totalDiscs - 1) {
			end = totalDiscs - 1
		}

		startPts[start]++
		endPts[end]++
	}

	result := 0
	activeDiscs := 0
	for i := 0; i < totalDiscs; i++ {
		if startPts[i] > 0 {
			result += activeDiscs * startPts[i]
			result += startPts[i] * (startPts[i] - 1) / 2

			if result > limit {
				return -1
			}

			activeDiscs += startPts[i]
		}
		activeDiscs -= endPts[i]
	}

	return result
}
<file_sep>/tour/basic/05-loop.go
package main

import "fmt"

func main() {
	// loops
	fmt.Println("I'm looping...")
	for i := 0; i < 10; i++ {
		fmt.Println(i)
	}

	sum := 0
	for i := 0; i <= 100; i++ {
		sum += i
	}
	fmt.Println("sum: ", sum)

	// while loop
	i := 0
	for i < 5 {
		fmt.Println(i)
		i++
	}

	// forever
	// for {
	// }

	// loop + array
	arrl := []string{"a", "b", "c"}
	for index, value := range arrl {
		fmt.Println("index: ", index, " - value: ", value)
	}

	// loop + map
	mapl := make(map[string]string)
	mapl["a"] = "alpha"
	mapl["b"] = "beta"
	
	for key, value := range mapl {
		fmt.Println("key: ", key, " - value: ", value)
	}
}
<file_sep>/exercism/beer-song/beer.go
package beer

import (
	"errors"
	"fmt"
	"strings"
)

const (
	upperBound int = 99
	lowerBound int = 0
)

const (
	v0 = `No more bottles of beer on the wall, no more bottles of beer.\n
	Go to the store and buy some more, 99 bottles of beer on the wall.\n`

	v1 = `1 bottle of beer on the wall, 1 bottle of beer.\n
	Take it down and pass it around, no more bottles of beer on the wall.\n`

	v2 = `%v bottles of beer on the wall, %v bottles of beer.\n
	\Take one down and pass it around, 1 bottle of beer on the wall.\n`

	vN = `%v bottles of beer on the wall, %v bottles of beer.\n
	Take one down and pass it around, %v bottles of beer on the wall.\n`
)

// Verse returns the verse based on the input bottle.
func Verse(bottle int) (string, error) {
	if bottle < lowerBound || bottle > upperBound {
		return "", errors.New("invalid number of bottles")
	}

	if bottle == 0 {
		return v0, nil
	}
	if bottle == 1 {
		return v1, nil
	}
	if bottle == 2 {
		return fmt.Sprintf(v2, bottle, bottle), nil
	}
	return fmt.Sprintf(vN, bottle, bottle, bottle-1), nil
}

// Verses returns a range from [upper] to [lower] of verses.
func Verses(upper, lower int) (string, error) {
	if lower < lowerBound || upper > upperBound || lower > upper {
		return "", errors.New("invalid bound(s)")
	}

	verses := make([]string, upper-lower+1)
	for i := upper; i >= lower; i-- {
		v, err := Verse(i)
		if err != nil {
			return "", err
		}
		verses = append(verses, v, "\n")
	}

	return strings.Join(verses, ""), nil
}

// Song returns the entire song.
func Song() string {
	s, _ := Verses(99, 0)
	return s
}
<file_sep>/tour/methods-interfaces/11-errors-Sqrt.go
package main

import (
	"fmt"
	"math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
	return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

const e = 1e-8

func Sqrt(x float64) (float64, error) {
	if x < 0 {
		return 0, ErrNegativeSqrt(x)
	}

	if x == 0 {
		return 0, nil
	}

	z := float64(1)

	for {
		oldZ := z

		z -= (z*z - x) / (2 * z)

		if math.Abs(z-oldZ) < e {
			return z, nil
		}
	}

	return z, nil
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(math.Sqrt(2))
	fmt.Println(Sqrt(-2))
}
<file_sep>/gophercises/03-choose-your-own-adventure/main.go
package main

import (
	"errors"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"strings"

	"github.com/nguyenthanh1290/gophercises/03-choose-your-own-adventure/story"
)

var templates = template.Must(template.ParseFiles("index.html", "story.html"))
var stories map[string]story.Story
var storyNames []string

func main() {
	var err error
	stories, err = loadStories("./story/")
	if err != nil {
		log.Fatal(err)
	}

	storyNames, err = listStories(stories)
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/story", storyHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func loadStories(dirname string) (map[string]story.Story, error) {
	stories := make(map[string]story.Story)

	files, err := ioutil.ReadDir(dirname)
	if err != nil {
		return nil, err
	}

	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".json") {
			st, _ := loadStory(dirname + f.Name())
			stories[f.Name()] = st
		}
	}

	return stories, nil
}

func loadStory(name string) (story.Story, error) {
	data, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, err
	}

	st, err := story.New(data)
	if err != nil {
		return nil, err
	}

	return st, nil
}

func listStories(stories map[string]story.Story) ([]string, error) {
	if len(stories) < 1 {
		return nil, errors.New("Empty stories")
	}

	names := make([]string, len(stories))
	i := 0
	for k := range stories {
		names[i] = strings.TrimRight(k, ".json")
		i++
	}

	return names, nil
}

// rootHandler handles all requests to website root /
// where the user can choose a story to begin with
func rootHandler(w http.ResponseWriter, r *http.Request) {
	templates.ExecuteTemplate(w, "index.html", storyNames)
}

// storyHandler handles requests matching /story?name=[story name]&arc=[next arc]
// Ex: /story?name=gopher&arc=new-york
func storyHandler(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()

	name := query.Get("name")
	if name == "" {
		http.Redirect(w, r, "/", http.StatusNotFound)
	}
	name += ".json"

	arc := query.Get("arc")
	if arc == "" {
		arc = story.BeginArc
	}

	templates.ExecuteTemplate(w, "story.html", stories[name][arc])
}
<file_sep>/tour/first-class-functions/first-class-functions.go
package main

import "fmt"

func main() {
	fmt.Println("First class functions")
	s1 := Student{
		Firstname: "Steven",
		Lastname:  "Swachb",
		Age:       33,
		Grade:     "12",
	}
	s2 := Student{
		Firstname: "Steven",
		Lastname:  "Tran",
		Age:       30,
		Grade:     "10",
	}
	s3 := Student{
		Firstname: "Jonh",
		Lastname:  "Awd",
		Age:       30,
		Grade:     "10",
	}

	s := []Student{s1, s2, s3}
	f := filter(s, func(s Student) bool {
		if s.Age == 30 {
			return true
		}
		return false
	})

	fmt.Println("Filter")
	fmt.Println(f)

	a := []int{5, 6, 7, 8, 9}
	r := iMap(a, func(n int) int {
		return n * 5
	})

	fmt.Println("Mapping")
	fmt.Println(r)
}

// Student stores a student data
type Student struct {
	Firstname string
	Lastname  string
	Age       int
	Grade     string
}

func filter(s []Student, f func(s Student) bool) []Student {
	var r []Student

	for _, v := range s {
		if f(v) {
			r = append(r, v)
		}
	}

	return r
}

func iMap(s []int, f func(int) int) []int {
	var r []int
	for _, v := range s {
		r = append(r, f(v))
	}
	return r
}
<file_sep>/exercism/clock/clock.go
// Package clock implements a clock that handles times without dates.
package clock

import "fmt"

// Clock defines the clock type with hour and minute.
type Clock struct {
	hour, minute int
}

const minOfDay = 24 * 60

// New returns a new clock.
func New(h, m int) Clock {
	totalMin := (minOfDay + (h*60+m)%minOfDay) % minOfDay
	h = totalMin / 60
	m = totalMin % 60

	return Clock{h, m}
}

// Add returns a new clock after adding minutes to it.
func (c Clock) Add(m int) Clock {
	return New(c.hour, c.minute+m)
}

// Subtract returns a new clock after subtracting minutes to it.
func (c Clock) Subtract(m int) Clock {
	return New(c.hour, c.minute-m)
}

// String returns a string that represents the clock in format of [hh]:[mm].
func (c Clock) String() string {
	return fmt.Sprintf("%02d:%02d", c.hour, c.minute)
}
<file_sep>/tour/methods-interfaces/06-methods-and-pointer-indirection.go
package main

import "fmt"

type Vertex struct {
	X, Y float64
}

func (v *Vertex) Scale(f float64) {
	v.X = v.X * f
	v.Y = v.Y * f
}

func ScaleFunc(v *Vertex, f float64) {
	v.X = v.X * f
	v.Y = v.Y * f
}

func main() {
	v := Vertex{3, 4}
	v.Scale(2)
	// even though v is a value and not a pointer, the method with the pointer receiver is called automatically.
	// That is, as a convenience, Go interprets the statement v.Scale(2) as (&v).Scale(2) since the Scale method has a pointer receiver.

	// ScaleFunc(v, 10)  // Compile error!
	ScaleFunc(&v, 10)
	// functions with a pointer argument must take a pointer

	p := &Vertex{4, 3}
	p.Scale(3)
	ScaleFunc(p, 8)

	fmt.Println(v, p)
}
<file_sep>/codility/03-time-complexity/perm-missing-elem/perm_missing_elem.go
package main

import (
	"fmt"
)

func Solution(A []int) int {
	if len(A) == 0 {
		return 1
	}

	sumA := 0
	for _, v := range A {
		sumA += v
	}

	n := len(A) + 1
	sumM := n * (n + 1) / 2

	return sumM - sumA
}

func main() {
	fmt.Println(Solution([]int{2, 3, 1, 5}))
}

// https://app.codility.com/programmers/lessons/3-time_complexity/perm_missing_elem/
// https://app.codility.com/demo/results/trainingJSDCQ6-8XK/
// Detected time complexity:
// O(N)<file_sep>/patterns/concurrency/06/time_out.go
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func boring(msg string) <-chan string {
	c := make(chan string)
	go func() {
		for i := 0; ; i++ {
			c <- fmt.Sprintf("%s %d", msg, i)
			time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
		}
	}()
	return c
}

func main() {
	c := boring("Long")
	for {
		select {
		case s := <-c:
			fmt.Println(s)
		case <-time.After(500 * time.Millisecond):// timeout for each message, that's why it takes too long to time out.
			fmt.Println("You're too slow.")
			return
		}
	}
}

// https://talks.golang.org/2012/concurrency.slide#35
<file_sep>/codility/others/bulbs/bulbs.go
package main

import (
	"fmt"
	"sort"
)

func main() {
	a1 := []int{2, 1, 3, 5, 4}
	a2 := []int{2, 3, 4, 1, 5}
	a3 := []int{1, 3, 4, 2, 5}
	a4 := []int{1, 2, 6, 3, 4, 5}
	fmt.Println(Solution(a1))
	fmt.Println(Solution(a2))
	fmt.Println(Solution(a3))
	fmt.Println(Solution(a4))
}

func Solution(A []int) int {
	count := 0

	for i := 0; i < len(A); i++ {
		arr := A[:i+1]
		if areAllBulbsTurnedOn(arr) {
			count++
		}
	}

	return count
}

// given the input condition: the elements of A are all distinct,
// we can verify if all the bulbs are turned of by sorting and
// then check if the first element is 1 and
// the last element equals to the total number of the array.
func areAllBulbsTurnedOn(arr []int) bool {
	sort.Ints(arr)
	if arr[0] == 1 && arr[len(arr)-1] == len(arr) {
		return true
	}
	return false
}
<file_sep>/codility/09-max-slice-problem/max-slice-sum/max_slice_sum.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/trainingPESXMD-AA7/
// Detected time complexity: O(N)
func max(A []int) int {
	maxSlice := A[0]
	maxEnding := A[0]

	for i := 1; i < len(A); i++ {
		if A[i] > maxEnding+A[i] {
			maxEnding = A[i]
		} else {
			maxEnding += A[i]
		}
		if maxEnding > maxSlice {
			maxSlice = maxEnding
		}
	}

	return maxSlice
}

func main() {
	fmt.Println(max([]int{3, 2, -6, 4, 0})) // 5
	fmt.Println(max([]int{-10}))            // -10
	fmt.Println(max([]int{-10, -3}))        // -3
	fmt.Println(max([]int{5, 1}))           // 6
	fmt.Println(max([]int{-2, 1}))          // 1
	fmt.Println(max([]int{1, 3}))           // 4
}
<file_sep>/tour/concurrency/temp.go
package main

import (
	"sync"
	"fmt"
)

type FreqMap map[rune]int

func ConcurrentFrequency(strs []string) FreqMap {
	var counter = struct {
		sync.Mutex
		freq FreqMap
	}{freq: map[rune]int{}}

	var wg sync.WaitGroup
	wg.Add(len(strs))

	for _, s := range strs {
		go func(s string) {
			for _, r := range s {
				counter.Lock()
				counter.freq[r]++
				counter.Unlock()
			}
			wg.Done()
		}(s)
	}

	wg.Wait()

	return counter.freq
}

func main() {
	var f =	ConcurrentFrequency([]string{euro, dutch, us})

	fmt.Println(f)
}

var (
	euro = `Fre<NAME>
Tochter aus Elysium,
Wir betreten feuertrunken,
Himmlische, dein Heiligtum!
Deine Zauber binden wieder
Was die Mode streng geteilt;
Alle Menschen werden Brüder,
Wo dein sanfter Flügel weilt.`

	dutch = `<NAME>
ben ik, van Duitsen bloed,
den vaderland getrouwe
blijf ik tot in den dood.
Een Prinse van Oranje
ben ik, vrij, onverveerd,
den Koning van Hispanje
heb ik altijd geëerd.`

	us = `O say can you see by the dawn's early light,
What so proudly we hailed at the twilight's last gleaming,
Whose broad stripes and bright stars through the perilous fight,
O'er the ramparts we watched, were so gallantly streaming?
And the rockets' red glare, the bombs bursting in air,
Gave proof through the night that our flag was still there;
O say does that star-spangled banner yet wave,
O'er the land of the free and the home of the brave?`
)<file_sep>/codility/07-stacks-queues/fish/fish.go
package fish

// https://app.codility.com/demo/results/trainingCESQ49-XGY/
// Detected time complexity:
// O(N)
func Solution(A []int, B []int) int {
	survivals := 0
	down := []int{}

	for i, v := range A {
		if B[i] == 0 {
			if len(down) == 0 {
				survivals++
			} else {
				j := len(down) - 1
				for j >= 0 {
					if down[j] > v {
						break
					}
					j--
				}
				if j < 0 {
					down = []int{}
					survivals++
				} else {
					down = down[:j+1]
				}
			}
		} else {
			down = append(down, v)
		}
	}

	survivals += len(down)

	return survivals
}<file_sep>/tour/concurrency/20-Pi.go
// http://www.mathscareers.org.uk/article/calculating-pi/
// Calculating Pi (π) using infinite series
// Gregory-Leibniz Series
package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(pi(5000))
}

func pi(n int) float64 {
	c := make(chan float64)
	for i := 0; i <= n; i++ {
		go term(c, float64(i))
	}

	pi := 0.0
	for i := 0; i <= n; i++ {
		pi += <-c
	}

	return pi
}

func term(c chan float64, k float64) {
	c <- 4 * math.Pow(-1, k) / (2*k + 1)
}
<file_sep>/codility/02-arrays/cyclic-rotation/cyclic_rotation.go
package main

import (
	"fmt"
)

func Solution(A []int, K int) []int {
	if K == 0 || len(A) == 0 || len(A) == 1 {
		return A
	}

	if K > len(A) {
		K = K % len(A)
	}

	arr := A[len(A)-K:]
	arr = append(arr, A[:len(A)-K]...)
	return arr
}

func main() {
	fmt.Println(Solution([]int{4, 6, 0, 0, -2, 10}, 15))
}

// https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/<file_sep>/exercism/acronym/acronym.go
// Package acronym provides a function that converts a pharse to its ancronym.
package acronym

import (
	"regexp"
	"strings"
)

// Abbreviate converts a pharse to its ancronym.
func Abbreviate(s string) string {
	reg := regexp.MustCompile(`\b[a-zA-Z]`)
	abbr := reg.FindAllString(s, -1)

	return strings.ToUpper(strings.Join(abbr, ""))
}
<file_sep>/tour/basic/02-variables.go
package main

import "fmt"

// A var statement can be at package or function level.
var c, python, java bool

func main() {
	fmt.Println(c, python, java)

	// A var declaration can include initializers, one per variable.
	// If an initializer is present, the type can be omitted; the variable will take the type of the initializer.

	fmt.Println("integer:")
	var a int = 1
	var b, c int
	b = 2
	c = 3
	fmt.Println(a)
	fmt.Println(b + c)

	fmt.Println("floating point number:")
	var d float64 = 9.99
	fmt.Println(d)

	var str string = "This is a string"
	fmt.Println(str)

	// Shorthand Declaration
	// Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
	// foo := "bar" is equivalent to var foo string = "bar"
	e := 9
	f := "golang"
	g := 923.2

	fmt.Println(e)
	fmt.Println(f)
	fmt.Println(g)

	// Outside a function, every statement begins with a keyword (var, func, and so on)
	// and so the := construct is not available.
}
<file_sep>/exercism/allergies/allergies.go
// Package allergies provides functions that help determining allergy.
package allergies

var allergenDb = map[string]uint{
	"eggs":         1,
	"peanuts":      2,
	"shellfish":    4,
	"strawberries": 8,
	"tomatoes":     16,
	"chocolate":    32,
	"pollen":       64,
	"cats":         128,
}

// Allergies returns a full list of allergies based on input score with the tesed database.
func Allergies(score uint) (allergens []string) {
	for k, v := range allergenDb {
		if score&v != 0 {
			allergens = append(allergens, k)
		}
	}
	return
}

// AllergicTo determines whether the person is allergic to the given allergen with the given score.
func AllergicTo(score uint, allergen string) bool {
	if v, prs := allergenDb[allergen]; prs {
		if score&v != 0 {
			return true
		}
	}
	return false
}
<file_sep>/codility/05-prefix-sums/min-avg/min_avg.go
package minavg

// Detected time complexity:
// O(N ** 2)
func Solution1(A []int) int {
	result := 0
	minAvg := 100000.0

	for i := 0; i < len(A)-1; i++ {
		sum := float64(A[i])
		divisor := 2.0
		for j := i + 1; j < len(A); j++ {
			sum += float64(A[j])
			avg := sum / divisor

			if avg < minAvg {
				minAvg = avg
				result = i
			}

			divisor++
		}
	}

	return result
}

// https://app.codility.com/demo/results/training75V4F8-ETS/
// Detected time complexity:
// O(N)
// The slice contains at least two elements =>
// we only need to check for slices of length 2 and 3,
// because slices of length 4 are actually 2 slices of length 2.
func Solution(A []int) int {
	minAvg := float64(A[0]+A[1]) / 2.0
	result := 0

	for i := 0; i < len(A)-1; i++ {
		avg := float64(A[i]+A[i+1]) / 2.0
		if avg < minAvg {
			minAvg = avg
			result = i
		}
	}

	for i := 0; i < len(A)-2; i++ {
		avg := float64(A[i]+A[i+1]+A[i+2]) / 3.0
		if avg < minAvg {
			minAvg = avg
			result = i
		}
	}

	return result
}
<file_sep>/codility/07-stacks-queues/brackets/brackets.go
package brackets

// https://app.codility.com/c/run/trainingNCAFFJ-FF3/
// https://app.codility.com/demo/results/trainingNCAFFJ-FF3/
// Detected time complexity:
// O(N)
func Solution(S string) int {
	if len(S) == 0 {
		return 1
	}

	stack := []rune{}
	for _, v := range S {
		switch v {
		case '(', '{', '[':
			stack = append(stack, v)
		case ')', '}', ']':
			if len(stack) == 0 {
				return 0
			}
			pair := string(stack[len(stack)-1]) + string(v)
			if pair != "()" && pair != "{}" && pair != "[]" {
				return 0
			}
			stack = stack[:len(stack)-1]
		default:
			return 0
		}
	}

	if len(stack) > 0 {
		return 0
	}
	return 1
}
<file_sep>/codility/05-prefix-sums/genomic-range-query/genomic_test.go
package genomic

import (
	"testing"
)

func TestSolution(t *testing.T) {
	for _, c := range testCases {
		output := Solution(c.dna, c.p, c.q)
		if len(output) != len(c.expected) {
			t.Fatalf("FAIL:\nDNA: %v\nQuery: %v %v\nexpected: %v\ngot: %v", c.dna, c.p, c.q, c.expected, output)
		}
		for i, v := range output {
			if v != c.expected[i] {
				t.Fatalf("FAIL:\nDNA: %v\nQuery: %v %v\nexpected: %v\ngot: %v", c.dna, c.p, c.q, c.expected, output)
			}
		}

		t.Logf("PASS: %v", c.dna)
	}
}

func BenchmarkSolution(b *testing.B) {
	for i := 0; i < b.N; i++ {
		for _, c := range testCases {
			Solution(c.dna, c.p, c.q)
		}
	}
}

var testCases = []struct {
	dna      string
	p        []int
	q        []int
	expected []int
}{
	{
		dna:      "CAGCCTA",
		p:        []int{2, 5, 0},
		q:        []int{4, 5, 6},
		expected: []int{2, 4, 1},
	},
	{
		dna:      "C",
		p:        []int{0},
		q:        []int{0},
		expected: []int{2},
	},
	{
		dna:      "CA",
		p:        []int{0},
		q:        []int{1},
		expected: []int{1},
	},
	{
		dna:      "CC",
		p:        []int{0, 0, 1},
		q:        []int{1, 0, 1},
		expected: []int{2, 2, 2},
	},
	{
		dna:      "AAAC",
		p:        []int{0, 0, 1, 3, 2},
		q:        []int{1, 2, 3, 3, 3},
		expected: []int{1, 1, 1, 2, 1},
	},
}
<file_sep>/exercism/README.md
https://exercism.io<file_sep>/patterns/options/options.go
package options

import (
	"context"
	"fmt"
	"net/http"
	"time"
)

const (
	defaultTimeout = 1 * time.Second
)

func main() {
	fmt.Println("Options pattern")

	tr := &http.Transport{
		MaxIdleConns:       10,
		IdleConnTimeout:    30 * time.Second,
		DisableCompression: true,
	}
	client := &http.Client{Transport: tr}
	u := NewContext(
		WithUsername("thanhn"),
		WithPassword("<PASSWORD>"),
		WithClient(client),
		WithTimeout(defaultTimeout),
	)

	fmt.Printf("%#v", u)
}

type Context struct {
	ctx      context.Context
	client   *http.Client
	username string
	password string
	timeout  time.Duration
}

// NewContext creates a new Context with the provided options
func NewContext(opts ...ContextOption) *Context {
	// Here we can do any initialization for all options, then the provided parameters can overwrite them.
	uCtx := Context{}
	for _, o := range opts {
		o(&uCtx)
	}
	return &uCtx
}

type ContextOption func(*Context)

// WithTimeout sets the context timeout
func WithTimeout(ttl time.Duration) ContextOption {
	return func(c *Context) {
		c.timeout = ttl
		var cancel func()
		c.ctx, cancel = context.WithTimeout(context.Background(), ttl)
		tick := time.NewTimer(ttl)
		go func() {
			select {
			case <-c.ctx.Done():
				cancel()
			case <-tick.C:
				cancel()
			}
		}()
	}
}

// WithClient set an *http.Client to be used by the context
func WithClient(client *http.Client) ContextOption {
	return func(c *Context) {
		c.client = client
	}
}

// WithUsername is an option that sets the username for remote server collector connections
func WithUsername(username string) ContextOption {
	return func(c *Context) {
		c.username = username
	}
}

// WithPassword is an option that sets the password for remote server collector connections
func WithPassword(password string) ContextOption {
	return func(c *Context) {
		c.password = password
	}
}

// FromContext sets a derived context
func FromContext(ctx context.Context) ContextOption {
	return func(c *Context) {
		c.ctx = context.WithValue(c.ctx, "context", ctx)
	}
}
<file_sep>/gophercises/03-choose-your-own-adventure/README.md
Exercise details can be found here: https://gophercises.com/exercises/cyoa

Recommand to check this well guided [doc](https://golang.org/doc/articles/wiki/) before doing the exercise to have a good base knowledge of the net/http package.

## Skills developed

- net/http
- html/template
- encoding/json
  - Decoding/Unmarshal
- strings

### Issue
<file_sep>/learn-go-with-tests/fundamentals/go.mod
module tdd

go 1.15
<file_sep>/gophercises/03-choose-your-own-adventure/story/story.go
package story

import (
	"encoding/json"
)

type Story map[string]Chapter

type Chapter struct {
	Title      string   `json:"title"`
	Paragraphs []string `json:"story"`
	Options    []Option `json:"options"`
}

type Option struct {
	Text string `json:"text"`
	Arc  string `json:"arc"`
}

const BeginArc = "intro"

func New(data []byte) (Story, error) {
	var story Story
	err := json.Unmarshal(data, &story)
	if err != nil {
		return nil, err
	}
	return story, nil
}
<file_sep>/codility/03-time-complexity/tape-quilibrium/tape_quilibrium.go
package main

import (
	"fmt"
	"math"
)

func Solution(A []int) int {
	min := math.MaxInt32
	total := sum(A...)
	lSum := 0
	for i := 0; i < len(A)-1; i++ {
		lSum += A[i]
		rSum := total - lSum

		diff := abs(lSum - rSum)
		if diff < min {
			min = diff
		}
	}

	return min
}

func abs(n int) int {
	return int(math.Abs(float64(n)))
}

func sum(n ...int) int {
	sum := 0
	for _, v := range n {
		sum += v
	}
	return sum
}

func main() {
	fmt.Println(Solution([]int{3, 1, 2, 4, 3}))
}

// https://app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/
// https://app.codility.com/demo/results/training5MXBJQ-SRA/
// Detected time complexity:
// O(N)<file_sep>/exercism/reverse-string/reverse_string.go
package reverse

import (
	"strings"
)

// String reverses the input.
func String(s string) string {
	var builder strings.Builder
	runes := []rune(s)
	for i := len(runes) - 1; i >= 0; i-- {
		builder.WriteRune(runes[i])
	}
	return builder.String()
}
<file_sep>/patterns/concurrency/04/restoring_sequencing.go
package main

import (
	"fmt"
	"math/rand"
	"time"
)

// Message defines a message type that contains a channel for the reply.
type Message struct {
	str  string
	wait chan bool
}

// https://talks.golang.org/2012/concurrency.slide#29
// Send a channel on a channel, making goroutine wait its turn.
// Receive all messages, then enable them again by sending on a private channel.<file_sep>/codility/others/max-repeated-square-root/square_root.go
package main

import (
	"fmt"
	"math"
	"sort"
)

func maxRepeated(A, B int) int {
	lower := int(math.Ceil(math.Sqrt(float64(A))))
	upper := int(math.Floor(math.Sqrt(float64(B))))

	sqrts := []int{}
	for i := lower; i <= upper; i++ {
		sqrts = append(sqrts, primitiveSqrt(i))
	}

	sort.Ints(sqrts)

	return sqrts[len(sqrts)-1]
}

func primitiveSqrt(n int) int {
	steps := 0
	p := int(math.Sqrt(float64(n)))
	if p*p == n {
		steps++
		return steps + primitiveSqrt(p)
	}
	return steps
}

func main() {
	fmt.Println(maxRepeated(10, 20))
	fmt.Println(maxRepeated(6000, 7000))
}
<file_sep>/exercism/collatz-conjecture/collatz_conjecture.go
package collatzconjecture

import "errors"

// CollatzConjecture takes any [n] positive number and returns the number of steps required to reach 1 by repeating divide [n] by 2, if [n] is even, else multiply [n] by 3 and add 1.
func CollatzConjecture(n int) (int, error) {
	if n <= 0 {
		return 0, errors.New("positive integer is required")
	}

	steps := 0
	for n != 1 {
		if n%2 == 0 {
			n = n / 2
		} else {
			n = n*3 + 1
		}
		steps++
	}
	return steps, nil
}
<file_sep>/exercism/etl/etl.go
package etl

import (
	"strings"
)

// Transform returns an ETL of input.
func Transform(in map[int][]string) (out map[string]int) {
	out = map[string]int{}

	for k, v := range in {
		for _, e := range v {
			out[strings.ToLower(e)] = k
		}
	}

	return
}
<file_sep>/gophercises/02-url-shortener/README.md
Exercise details can be found here: https://gophercises.com/exercises/urlshort

However, I recommend to check this Go doc first, https://golang.org/doc/articles/wiki/. By following the doc to build a Web App, you will have enough knowledge about http package to complete this exercise.

## Skills developed

* net/http package
* yaml

### Issue
"panic: yaml: line 2: found character that cannot start any token"

Fix:
- make sure there is no tab character in your yaml text
- that includes, do not indent the lines when declaring the variable storing the yaml text
<file_sep>/exercism/grade-school/grade_school.go
package school

import (
	"sort"
)

// Grade is a struct with a level and a slice of students.
type Grade struct {
	level    int
	students []string
}

// School is a map with grade as key and slice of students as value.
type School map[int][]string

// New returns an empty school.
func New() *School {
	return &School{}
}

// Add adds a student to appropriate grade.
func (s *School) Add(name string, level int) {
	if stus, prs := (*s)[level]; prs {
		stus = append(stus, name)
		(*s)[level] = stus
	} else {
		(*s)[level] = []string{name}
	}
}

// Grade returns all students enrolled.
func (s *School) Grade(level int) []string {
	if _, prs := (*s)[level]; prs {
		return (*s)[level]
	}
	return []string{}
}

// Enrollment returns a sorted list of all students in all grades.
func (s *School) Enrollment() []Grade {
	ret := []Grade{}

	levels := []int{}
	for k := range *s {
		levels = append(levels, k)
	}
	sort.Ints(levels)

	for _, l := range levels {
		stus := (*s)[l]
		sort.Strings(stus)
		ret = append(ret, Grade{l, stus})
	}

	return ret
}
<file_sep>/crypto/crypto.go
package crypto

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"errors"
	"io"
)

// Encryption/decryption errors.
var (
	ErrPlaintextEmpty                   = errors.New("plaintext is empty")
	ErrCiphertextTooShort               = errors.New("ciphertext is too short")
	ErrCiphertextNotMultipleOfBlockSize = errors.New("ciphertext is not a multiple of the block size")
	ErrPlaintextNotMultipleOfBlockSize  = errors.New("plaintext is not a multiple of the block size")

	// ErrInvalidBlockSize indicates hash blocksize <= 0.
	ErrInvalidBlockSize = errors.New("invalid blocksize")

	// ErrInvalidPKCS7Data indicates bad input to PKCS7 pad or unpad.
	ErrInvalidPKCS7Data = errors.New("invalid PKCS7 data (empty or not padded)")

	// ErrInvalidPKCS7Padding indicates PKCS7 unpad fails to bad input.
	ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
)

// Encrypt encrypts the given byte slice using AES-CBC algorithm.
func Encrypt(plaintext []byte, key []byte) ([]byte, error) {
	if len(plaintext) == 0 {
		return nil, ErrPlaintextEmpty
	}

	plaintext, err := pkcs7Pad(plaintext, aes.BlockSize)
	if err != nil {
		return nil, err
	}

	if len(plaintext)%aes.BlockSize != 0 {
		return nil, ErrPlaintextNotMultipleOfBlockSize
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)

	return ciphertext, nil
}

// Decrypt decrypts the AES-CBC algorithm encrypted cipher text.
func Decrypt(ciphertext []byte, key []byte) ([]byte, error) {
	if len(ciphertext) < aes.BlockSize {
		return nil, ErrCiphertextTooShort
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	// Remove the embedded IV.
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	// CBC mode always works in whole blocks.
	if len(ciphertext)%aes.BlockSize != 0 {
		return nil, ErrCiphertextNotMultipleOfBlockSize
	}

	mode := cipher.NewCBCDecrypter(block, iv)

	plaintext := make([]byte, len(ciphertext))
	mode.CryptBlocks(plaintext, ciphertext)

	plaintext, err = pkcs7Unpad(plaintext, aes.BlockSize)
	if err != nil {
		return nil, err
	}

	return plaintext, nil
}

// pkcs7Pad right-pads the given byte slice with 1 to n bytes, where
// n is the block size. The size of the result is x times n, where x
// is at least 1.
func pkcs7Pad(b []byte, blocksize int) ([]byte, error) {
	if blocksize <= 0 {
		return nil, ErrInvalidBlockSize
	}
	if len(b) == 0 {
		return nil, ErrInvalidPKCS7Data
	}

	n := blocksize - (len(b) % blocksize)
	pb := make([]byte, len(b)+n)
	copy(pb, b)
	copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))

	return pb, nil
}

// pkcs7Unpad validates and unpads data from the given bytes slice.
// The returned value will be 1 to n bytes smaller depending on the
// amount of padding, where n is the block size.
func pkcs7Unpad(b []byte, blocksize int) ([]byte, error) {
	if blocksize <= 0 {
		return nil, ErrInvalidBlockSize
	}
	if len(b) == 0 {
		return nil, ErrInvalidPKCS7Data
	}
	if len(b)%blocksize != 0 {
		return nil, ErrInvalidPKCS7Padding
	}

	c := b[len(b)-1]
	n := int(c)
	if n == 0 || n > len(b) {
		return nil, ErrInvalidPKCS7Padding
	}
	for i := 0; i < n; i++ {
		if b[len(b)-n+i] != c {
			return nil, ErrInvalidPKCS7Padding
		}
	}

	return b[:len(b)-n], nil
}
<file_sep>/tour/doc-play/README.md
https://golang.org/doc/play/<file_sep>/exercism/triangle/triangle.go
// Package triangle provides a function that determines triangle type.
package triangle

import "math"

// Kind defines the triangle type.
type Kind int

// Different kinds of triangle
// - NaT: not a triangle
// - Equ: equilateral
// - Iso: isosceles
// - Sca: scalene
const (
	NaT Kind = 1 << iota
	Equ
	Iso
	Sca
)

// KindFromSides takes the given sides and returns the type of a triangle they can form.
func KindFromSides(a, b, c float64) Kind {
	// for _, v := range []float64{a, b, c} {
	// 	if v <= 0 || math.IsNaN(v) || math.IsInf(v, 1) {
	// 		return NaT
	// 	}
	// }
	if a <= 0 || b <= 0 || c <= 0 || math.IsNaN(a+b+c) || math.IsInf(a+b+c, 1) {
		return NaT
	}

	if (a+b < c) || (a+c < b) || (b+c < a) {
		return NaT
	}

	if a == b && b == c {
		return Equ
	}

	if a == b || a == c || b == c {
		return Iso
	}

	return Sca
}
<file_sep>/exercism/accumulate/accumulate.go
package accumulate

// Accumulate returns a new collection containing the result of applying that operation to each element of the input collection.
func Accumulate(in []string, fn func(string) string) []string {
	out := make([]string, len(in))
	for i, e := range in {
		out[i] = fn(e)
	}
	return out
}
<file_sep>/gophercises/03-choose-your-own-adventure/story/story_test.go
package story

import (
	"testing"
)

func TestNew(t *testing.T) {
	t.Error("Failed")
}<file_sep>/tour/basic/05-switch.go
package main

import (
	"fmt"
	"runtime"
	"time"
)

func main() {
	fmt.Print("Go runs on ")

	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.", os)
	}
	fmt.Println("\n")

	// switch evaluation order
	today := time.Now().Weekday()
	fmt.Println("Today is: ", today)

	fmt.Println("When's Saturday?")

	switch time.Saturday {
	case today + 0:
		fmt.Println("Today.")
	case today + 1:
		fmt.Println("Tomorrow.")
	case today + 2:
		fmt.Println("In two days.")
	default:
		fmt.Println("Too far away.")
	}
	fmt.Println("\n")

	// Switch with no condition
	t := time.Now()
	fmt.Println("Now is: ", t)
	switch {
	case t.Hour() < 12:
		fmt.Println("Good morning!")
	case t.Hour() < 17:
		fmt.Println("Good afternoon.")
	default:
		fmt.Println("Good evening.")
	}
}

// Go only runs the selected case, not all the cases that follow.
// In effect, the break statement that is needed at the end of each case in those languages is provided automatically in Go.

// Another important difference is that Go's switch cases need not be constants,
// and the values involved need not be integers.
<file_sep>/crypto/ecdh/ecdh-curve25519.go
package ecdh

import (
	"crypto"
	"io"

	"golang.org/x/crypto/curve25519"
)

type ecdhCurve25519 struct {
}

// GenerateKeyPair generates a pair of private and public key using entropy from rand.
func (e ecdhCurve25519) GenerateKeyPair(rand io.Reader) (crypto.PrivateKey, crypto.PublicKey, error) {
	var private, public [32]byte

	// Compute secret key.
	_, err := rand.Read(private[:])
	if err != nil {
		return nil, nil, err
	}

	private[0] &= 248
	private[31] &= 127
	private[31] |= 64

	// Compute public key.
	curve25519.ScalarBaseMult(&public, &private)

	return &private, &public, nil

}

// ComputeSharedSecret computes shared secret key.
func (e ecdhCurve25519) ComputeSharedSecret(private crypto.PrivateKey, peerPublic crypto.PublicKey) []byte {
	var sharedSecret [32]byte

	curve25519.ScalarMult(&sharedSecret, private.(*[32]byte), peerPublic.(*[32]byte))

	return sharedSecret[:]
}
<file_sep>/tour/image-api/chessboard.go
package main

import (
	"fmt"

	"image"
	"image/color"
	"image/draw"
	"image/png"

	"os"
)

func main() {

	new_png_file := "chessboard.png"
	board_num_pixels := 240

	myimage := image.NewRGBA(image.Rect(0, 0, board_num_pixels, board_num_pixels))
	colors := make(map[int]color.RGBA, 2)

	colors[0] = color.RGBA{0, 100, 0, 255}   // green
	colors[1] = color.RGBA{50, 205, 50, 255} // limegreen

	index_color := 0
	size_board := 8
	size_block := int(board_num_pixels / size_board)
	loc_x := 0

	for curr_x := 0; curr_x < size_board; curr_x++ {

		loc_y := 0
		for curr_y := 0; curr_y < size_board; curr_y++ {

			draw.Draw(myimage, image.Rect(loc_x, loc_y, loc_x+size_block, loc_y+size_block),
				&image.Uniform{colors[index_color]}, image.ZP, draw.Src)

			loc_y += size_block
			index_color = 1 - index_color // toggle from 0 to 1 to 0 to 1 to ...
		}
		loc_x += size_block
		index_color = 1 - index_color // toggle from 0 to 1 to 0 to 1 to ...
	}

	myfile, err := os.Create(new_png_file)
	if err != nil {
		panic(err.Error())
	}
	defer myfile.Close()

	png.Encode(myfile, myimage)           // ... save image
	fmt.Println("firefox ", new_png_file) // view image issue : firefox  /tmp/chessboard.png
}
<file_sep>/codility/12-euclidean-algorithm/chocolates/chocolates.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/trainingE4989R-ZHY/
// Detected time complexity: O(log(N + M))
// Least common multiple
func eat(N, M int) int {
	if 1 == M {
		return N
	}
	if N == M {
		return 1
	}

	a := N
	b := M
	for b != 0 {
		a, b = b, a%b
	}

	return N / a
}

func main() {
	fmt.Println(eat(10, 4))   // 5
	fmt.Println(eat(10, 8))   // 5
	fmt.Println(eat(100, 4))  // 25
	fmt.Println(eat(100, 8))  // 25
	fmt.Println(eat(1000, 4)) // 125
	fmt.Println(eat(1000, 8)) // 125

	fmt.Println(eat(10, 3))     // 10
	fmt.Println(eat(10, 9))     // 10
	fmt.Println(eat(7, 9))      // 7
	fmt.Println(eat(2, 3))      // 2
	fmt.Println(eat(2, 19))     // 2
	fmt.Println(eat(2, 111119)) // 2

	fmt.Println(eat(2, 1))          // 2
	fmt.Println(eat(3, 1))          // 3
	fmt.Println(eat(3, 2))          // 3
	fmt.Println(eat(1000000000, 1)) // 1000000000
}
<file_sep>/exercism/raindrops/raindrops.go
// Package raindrops provides a function that convert raindrops to its appropriate sound.
package raindrops

import "fmt"

// Convert returns a sound based on the number of raindrops.
func Convert(drops int) string {
	s := ""
	if drops%3 == 0 {
		s += "Pling"
	}
	if drops%5 == 0 {
		s += "Plang"
	}
	if drops%7 == 0 {
		s += "Plong"
	}

	if s == "" {
		s = fmt.Sprintf("%v", drops)
	}

	return s
}
<file_sep>/codility/08-leader/dominator/dominator.go
package main

import (
	"fmt"
)

// https://app.codility.com/demo/results/trainingK4BM6J-KRW/
// O(N)
func Solution(A []int) int {
	if 0 == len(A) {
		return -1
	}
	value := A[0]
	size := 0
	for _, a := range A {
		if 0 == size {
			size++
			value = a
		} else {
			if a != value {
				size--
			} else {
				size++
			}
		}
	}

	candidate := -1
	if 0 != size {
		candidate = value
	}

	index := -1
	count := 0
	for i, a := range A {
		if a == candidate {
			count++
			if count > len(A)/2 {
				return i
			}
		}
	}

	return index
}

func main() {
	fmt.Println(Solution([]int{6, 8, 4, 6, 8, 6, 6}))     // 6
	fmt.Println(Solution([]int{1, 2, 19, 1, 4, 2, 1}))    // -1
	fmt.Println(Solution([]int{3, 4, 3, 2, 3, -1, 3, 3})) // 7
}
<file_sep>/exercism/isogram/isogram.go
// Package isogram provides functions that determines if a word or phrase is an isogram.
package isogram

import "unicode"

// IsIsogram returns true if input is an isogram, else returns false.
func IsIsogram(input string) bool {
	dict := map[rune]int{}

	for _, c := range input {
		if c == ' ' || c == '-' {
			continue
		}
		if _, prs := dict[unicode.ToUpper(c)]; prs {
			return false
		}
		dict[unicode.ToUpper(c)]++
	}
	return true
}
<file_sep>/exercism/secret-handshake/secret_handshake.go
// Package secret provides functions that decodes the code to the appropriate sequence of events for a secret handshake.
package secret

const (
	wink = 1 << iota
	doubleBlink
	closeEyes
	jump
	reverse
)

func reverseArray(input []string) {
	for i, j := 0, len(input)-1; i < j; i, j = i+1, j-1 {
		input[i], input[j] = input[j], input[i]
	}
}

// Handshake returns a decoded handshake.
func Handshake(code uint) (output []string) {
	if code&wink != 0 {
		output = append(output, "wink")
	}
	if code&doubleBlink != 0 {
		output = append(output, "double blink")
	}
	if code&closeEyes != 0 {
		output = append(output, "close your eyes")
	}
	if code&jump != 0 {
		output = append(output, "jump")
	}
	if code&reverse != 0 {
		reverseArray(output)
	}
	return
}
<file_sep>/tour/basic/05-my-sqrt.go
package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := float64(1)

	for {
		oldZ := z

		z -= (z*z - x) / (2 * z)

		fmt.Println("z = ", z)

		if oldZ == z {
			return z
		}
	}

	return z
}

func main() {
	x := float64(2222)

	fmt.Println("My sqrt:", Sqrt(x))
	fmt.Println("Go sqrt:", math.Sqrt(x))
}
<file_sep>/exercism/perfect-numbers/perfect_numbers.go
package perfect

import (
	"errors"
)

// Classification represents the classification values for natural numbers.
type Classification int

// Classification values
const (
	ClassificationDeficient Classification = iota
	ClassificationPerfect
	ClassificationAbundant
)

// ErrOnlyPositive is a customer error type.
var ErrOnlyPositive = errors.New("positive integer is required")

// Classify determines if a number is perfect, abundant, or deficient based on
// Nicomachus' (60 - 120 CE) classification scheme for natural numbers.
func Classify(n int64) (Classification, error) {
	if n <= 0 {
		return -1, ErrOnlyPositive
	}

	aSum := aliquotSum(n)
	if aSum == n {
		return ClassificationPerfect, nil
	}
	if aSum > n {
		return ClassificationAbundant, nil
	}
	return ClassificationDeficient, nil
}

// The aliquot sum is the sum of the factors of a number not including the number itself.
func aliquotSum(n int64) (aSum int64) {
	for i := int64(1); i < n; i++ {
		if n%i == 0 {
			aSum += i
		}
	}
	return
}
<file_sep>/exercism/proverb/proverb.go
// Package proverb provides function to generate the "For Want of a Nail" proverb.
package proverb

import "fmt"

const (
	line = "For want of a %s the %s was lost."
	last = "And all for the want of a %s."
)

// Proverb generates the "For Want of a Nail" proverb base on input rhyme.
func Proverb(rhyme []string) []string {
	if len(rhyme) == 0 {
		return []string{}
	}

	proverb := make([]string, len(rhyme))
	for i := 0; i < (len(rhyme) - 1); i++ {
		proverb[i] = fmt.Sprintf(line, rhyme[i], rhyme[i+1])
	}
	proverb[len(rhyme)-1] = fmt.Sprintf(last, rhyme[0])

	return proverb
}
<file_sep>/tour/temp.go
package main

import (
	"fmt"
	"math"
	"strconv"
)

func main() {
	fmt.Println(isPalindrome(-101))
	fmt.Println(smallest(2))
	fmt.Println(largest(2))
}

func smallest(n int) (minProduct int, factor1 int, factor2 int) {
	lowerBound := int(math.Pow10(n - 1))
	upperBound := int(math.Pow10(n) - 1)

	minProduct = math.MaxInt32

	for f1 := lowerBound; f1 <= upperBound; f1++ {
		for f2 := lowerBound; f2 <= f1; f2++ {
			p := f1 * f2
			if p > minProduct {
				break
			}
			if p < minProduct && isPalindrome(p) {
				minProduct = p
				factor1 = f1
				factor2 = f2
			}
		}
	}

	return
}

func largest(n int) (maxProduct int, factor1 int, factor2 int) {
	lowerBound := int(math.Pow10(n - 1))
	upperBound := int(math.Pow10(n) - 1)

	for f1 := upperBound; f1 >= lowerBound; f1-- {
		for f2 := upperBound; f2 >= f1; f2-- {
			p := f1 * f2
			if p < maxProduct {
				break
			}
			if p > maxProduct && isPalindrome(p) {
				maxProduct = p
				factor1 = f1
				factor2 = f2
			}
		}
	}

	return
}

func isPalindrome(n int) bool {
	return isPalindromeVc(n)
}
func isPalindromeVc(n int) bool {
	reverse := 0
	copyOfN := n
	for copyOfN != 0 {
		reverse = reverse*10 + copyOfN%10
		copyOfN /= 10

	}
	return reverse == n
}
func isPalindromeVa(n int) bool {
	if n < 0 {
		n = -n
	}
	divisor := 1
	for n/divisor >= 10 {
		divisor *= 10
	}

	for n != 0 {
		leading := n / divisor
		trailing := n % 10

		if leading != trailing {
			return false
		}

		// Removing the leading and trailing digit from number.
		n = (n % divisor) / 10

		// Reducing divisor by a factor of 2 as 2 digits are dropped.
		divisor /= 100
	}

	return true
}
func isPalindromeVb(n int) bool {
	if n < 0 {
		n = -n
	}

	s := strconv.Itoa(n)
	l := len(s)
	for i := 0; i < l/2; i++ {
		if s[i] != s[l-1-i] {
			return false
		}
	}
	return true
}
<file_sep>/tour/basic/06-defer.go
package main

import "fmt"

func main() {
	i := 0

	i++
	defer fmt.Println("defer i = ", i)

	i++
	fmt.Println("i = ", i)
}

// i= 2
// defer i =  1

// A defer statement defers the execution of a function until the surrounding function returns.

// The deferred call's arguments are evaluated immediately,
// but the function call is not executed until the surrounding function returns.

// 1. A deferred function's arguments are evaluated when the defer statement is evaluated.<file_sep>/codility/06-sorting/distinct/distinct.go
package distinct

import "sort"

// https://app.codility.com/demo/results/trainingJ2JGAF-HCV/
// Detected time complexity:
// O(N*log(N)) or O(N)
func Solution(A []int) int {
	if len(A) == 0 {
		return 0
	}

	sort.Ints(A)
	result := 1
	for i := 1; i < len(A); i++ {
		if A[i] != A[i-1] {
			result++
		}
	}
	return result
}

// https://app.codility.com/demo/results/trainingTEP555-WWU/
// Detected time complexity:
// O(N)
func Solution1(A []int) int {
	m := make(map[int]struct{})
	for _, v := range A {
		m[v] = struct{}{}
	}

	return len(m)
}

// by counting elements
// Notice that we have to know the range of the sorted values.
// If all the elements are in the set {0, 1, . . . , k},
// then the array used for counting should be of size k + 1

// The time complexity here is O(n + k).
// We need additional memory O(k) to count all the elements
func SolutionXXX(A []int, K int) int {
	counter := make([]int, K + 1) //init all elements of the slice to 0 value
	for _, v := range A {
		counter[v]++
	}
	result := 0
	for _, v := range counter {
		if v > 0 {
			result++
		}
	}
	return result
}<file_sep>/patterns/concurrency/README.md
# go-concurrency-patterns
<file_sep>/exercism/prime-factors/prime_factors.go
package prime

// Factors returns the prime factors of the given natural number.
func Factors(n int64) []int64 {
	r := make([]int64, 0)
	for i := int64(2); i <= n; i++ {
		for n%i == 0 {
			r = append(r, i)
			n /= i
		}
	}

	return r
}
<file_sep>/tour/basic/10-array.go
package main

import "fmt"

func main() {
	// int array
	var arr [3]int
	arr[0] = 1
	arr[0] = 2
	arr[0] = 3

	// alternative syntax
	arr2 := [4]int{3, 2, 5, 1}
	fmt.Println(arr2)

	//string array
	var strArray [3]string
	strArray[0] = "hello"
	strArray[1] = "hi"
	strArray[2] = "hey"
	fmt.Println(strArray[2])

	arrp := []int{1, 3, 6, 2, 6}
	arrp = append(arrp, 23)
	fmt.Println(arrp)
}