Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
go
fmt.Printf("Hello, world\n")
fmt.Println("Hello, World!")

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
go
package main

import (
"fmt"
"strings"
)

func main() {
str := "The quick brown fox jumps over the lazy dog. "
chs := strings.Split(str, "")
j := 1
for i := 0; i < 10; i++ {
for n, l := 0, len(chs); n < l; n++ {
if j == 1 {
fmt.Print("> ")
}
fmt.Print(chs[n])
if j == 77 {
fmt.Println()
j = 1;
}else {
j++;
}
}
}
}
package main

func main() {
chs := []rune("The quick brown fox jumps over the lazy dog. ")
j := 1
for i := 0; i < 10; i++ {
for _, v := range chs {
if j == 1 {
print("> ")
}
print(string(v))
if j == 77 {
println()
j = 1;
}else {
j++;
}
}
}
}

Define a string containing special characters

Define the literal string "\#{'}${"}/"
go
s := "\\#{'}${\"}/"
s := `"\#{'}${"}/"`

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
go
text := "This\nIs\nA\nMultiline\nString\n"
text := "This\n" + "Is\n" + "A\n" + "Multiline\n" + "String\n"
var s = `This
Is
A
Multiline
String`

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
go
a, b := 3, 4
fmt.Printf("%d+%d=%d\n", a, b, a + b)
a, b := 3, 4
fmt.Println(a, "+", b, "=", a+b)

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
go
package main;
import "utf8";
import "fmt";

func reverse(s string) string {
o := make([]int, utf8.RuneCountInString(s))
i := len(o)
for _, c := range s {
i--
o[i] = c
}
return string(o)
}

func main() {
fmt.Print(reverse("reverse me"));
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
go
words := strings.Split("This is the end, my only friend!", " ")
nr := len(words)
reversed := make([]string, nr)
for i, word := range words {
reversed[nr - i - 1] = word
}
s := strings.Join(reversed, " ")
fmt.Println(s)
func reverse(list []string) ([]string) {
if len(list) == 1 {
return list
}

return append(reverse(list[1:]), list[0])
}

func main() {
words := strings.Split("This is the end, my only friend!", " ")
s := strings.Join(reverse(words), " ")
fmt.Println(s)
}

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
go
import "fmt"
import "strings"

const WIDTH = 72

func main() {
s := "The quick brown fox jumps over the lazy dog."

words := strings.Split(s, " ")
tmp := words

for i, pos := 0, 0; i < 10; i++ {
for len(words) > 0 {
if pos == 0 {
fmt.Printf("> ")
}

if pos + len(words[0]) > WIDTH {
fmt.Printf("\n")
pos = 0
} else {
fmt.Printf("%s ", words[0])
pos += len(words[0]) + 1
words = words[1:]
}
}
words = tmp
}

fmt.Printf("\n")
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
go
s := strings.TrimSpace(" hello ")

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
go
strings.ToUpper("Space Monkey")

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
go
strings.ToLower("Caps ARE overRated")

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
go
strings.Title(strings.ToLower("man OF stEEL"))

Find the distance between two points

go
import "fmt"
import "math"

type Point struct {
x, y float64
}

func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}

func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }

fmt.Println(point.distance(origin))
}

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
go
fmt.Printf("%08d", 42)

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
go
fmt.Printf("%-6d", 1024)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
go
fmt.Printf("%.2f", 7.0 / 8.0)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
go
fmt.Printf("%10d", 73)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
go
rand.Intn(100) + 100

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
go
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()

rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
go
result, _ := regexp.MatchString("[A-Z][a-z]+", "Hello")
if result {
fmt.Println("ok")
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
go
re, _ := regexp.Compile("one (.*) three")
groups := re.FindStringSubmatch("one two three")
if len(groups) > 0 {
fmt.Println(groups[1])
}

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
go
i := 0
f := func (in string) (out string) {
i++
if i == 1 {
return "*"
}
return in
}

re, _ := regexp.Compile("e")
s := re.ReplaceAllStringFunc("Red Green Blue", f)
fmt.Println(s)

Define an empty list

Assign the variable "list" to a list with no elements
go
var l []string;

Define a static list

Define the list [One, Two, Three, Four, Five]
go
var l = []string{"One", "Two", "Three", "Four", "Five"}

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
go
s := strings.Join([]string {"Apple", "Banana", "Carrot"}, ", ")

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
go
fmt.Println(list[2])

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
go
offset := 0
list = append(list[:offset], list[offset+1:]...)

Define an empty map

go
m := make(map[int]string)

Define an initial map

Define the map {circle:1, triangle:3, square:4}
go
m := map[string]int{ "circle": 1, "square": 4, "triangle": 2 }

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
go
m := map[string]string{ "joe": "cat", "mary": "turtle", "bill": "canary" }
if _, ok := m["mary"]; ok {
fmt.Println("ok")
}

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
go
fmt.Println(pets["joe"])

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
go
pets["rob"] = "dog"

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
go
fmt.Println(pets["bill"])
delete(pets, "bill")
fmt.Println(pets["bill"])
pets["bill"] = "", false

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
go
var maplist = make(map[string]int)
var list = [6]string{"a","b","a","c","b","b"}
for _, v := range list {
maplist[v] += 1
}
fmt.Println(maplist)

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
go
if name == "Bob" {
fmt.Println("Hello", name)
}

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
go
t, err := time.Parse("2006-01-02 15:04", "2008-05-06 13:29")
if err == nil {
fmt.Println(t)
}

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
go
t := time.Now().Add(8 * 24 * time.Hour)
fmt.Println(t.Day())
// no day of year
fmt.Println(t.Month())
fmt.Println(t.Weekday())

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
go
fmt.Println(time.Now())
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
go
type Greeter struct {
whom string
}

func (g Greeter) greet() {
fmt.Printf("Hello %s\n", g.whom)
}

func main() {
Greeter{"world"}.greet()
}

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
go
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error", err)
}

defer resp.Body.Close()

bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Read Error", err)
}
matched, _ := regexp.Match(lang,bodyBytes)
if matched {
fmt.Println("Go is in the page")
} else {
fmt.Println("Go isn't in the page")
}