Readme

created the project under $GOPATH

Modulus 1

Week 3

Sort a list with the given arbitrary inputs

Not working, but in progres 2 5 3 4

import "fmt"
type P struct {
    x string
	y int
}
func main() {
	b := P{"x", -1}
	a := [...]P{P{"a", 10},
        P{"b", 2},
        P{"c", 3}}
	for _, z := range a {
		if z.y > b.y {
			b = z
		}
	}
	fmt.Println(b.x)
}

import "fmt"
func main() {
	s := make([]int, 0, 3)
	s = append(s, 100)
	fmt.Println(len(s), cap(s))
}
Equivalent in JSON

{“name” : “joe”, “addr”:”a st.”, “phone”:”123”}

JSON (Mod4.1.2)

Properties

  • All Unicode
  • Human-readable
  • Fairly compact representation
  • Types can be combined recursively
    • Array of structs, struct in struct, etc.

JSON Marshalling (encoding to JSON)

Example

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	name  string
	addr  string
	phone string
}

func main() {
	p1 := Person{name: "joe", addr: "a st.", phone: "123"}

	barr, err := json.Marshal(p1)
	fmt.Println(err)
	fmt.Println("byte array (barr):", barr, "\t person 1 (p1) in Go:", p1)

	var p2 Person
	err2 := json.Unmarshal(barr, &p2)
	fmt.Println("person 2 (p2) in Go:", p2, "error:", err2)
}

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name  string `json:"name"`
    Addr  string `json:"addr"`
    Phone string `json:"phone"`
}

func main() {
    p1 := Person{Name: "joe", Addr: "a st.", Phone: "123"}

    barr, err := json.Marshal(p1)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(barr))

	var p2 Person
	err2 := json.Unmarshal(barr, &p2)
	fmt.Println("person 2 (p2) in Go:", p2, "error:", err2)
}

os package

Open, Read, etc.

package main

import ("fmt"
	"os")

func main() {
	f, err := os.Open("dt.txt")
	fmt.Println(f, err)
	barr := make([]byte, 10000)
	nb, err := f.Read(barr)
	fmt.Println(string(nb[:10]), err)
	f.Close()
}

package main

import (
    "fmt"
    "os"
    "bufio"
)


func main() {
    file, err := os.Open("dt.txt")
    if err != nil {
		fmt.Println(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
		fmt.Println(err)
    }
}

Assignment

Assignment 1

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name  string `json:"name"`
	Address  string `json:"address"`
}

func main() {
	var x string
	fmt.Println("Enter 'Name':")
	_, _ = fmt.Scan(&x)

	var y string
	fmt.Println("Enter 'Address':")
	_, _ = fmt.Scan(&y)

	p1 := Person{Name: x, Address: y}

	barr, err := json.Marshal(p1)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(barr))
}

Assignment 2

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

type T struct {
	fname string
	lname string
}

func main() {
	// Ask for file name (fn)
	fmt.Println("Enter file name, e.g.: 'names.txt'")
	var fn string
	_, _ = fmt.Scan(&fn)

	// Open file
	file, err := os.Open(fn)
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()

	// Create a slice, in which the T constructs will be populated.
	var slice []T

	// Counter for each line
	i := 0

	// Read each line and iterate on it
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
		strline := scanner.Text()
		// words := strings.Split(strline, " ")
		// var words [20]string
		words := strings.Fields(strline)
		// fmt.Println(words, len(words))
		fmt.Println("First name:", words[0], "Last name:", words[1])
		slice = append(slice, T{fname: words[0], lname: words[1]})
		fmt.Println("Slice so far:", slice)
		i = i + 1
	}

	if err := scanner.Err(); err != nil {
		fmt.Println(err)
	}

	// return slice with T-type elements
	fmt.Println(slice)

	// Iterate and return first and last names
	fmt.Println("List of first and last names in the file:")

	for _, value := range slice {
		fmt.Println("First name:", value.fname, "Last name:", value.lname)
	}

Modulus 2

Week 1

Assignment 3 – Bubble Sort

First try (working)

package main

import (
	"flag"
	"fmt"
	"strconv"
)

func Swap(first, next, count int) (int, int, int) {
	if first > next {
		first, next = next, first
		count = count + 1
	}
	return first, next, count
}

func BubbleSort(sli []int) []int {
	count_sort := 0
	for i := 0; i < len(sli)-1; i++ { // sort two-by-two, all 2-tuples
		sli[i], sli[i+1], count_sort = Swap(sli[i], sli[i+1], count_sort)
	}
	if count_sort != 0 {
		BubbleSort(sli)
	}
	return sli
}

func useFlags() []int {
	flag.Parse()
	args := flag.Args()
	fmt.Println("args:", args)

	nums := make([]int, len(args))
	// for each argument, insert in position nums[i] the string-converted value num64
	for i, arg := range args {
		num64, err := strconv.ParseInt(arg, 0, 0)
		if err != nil {
			fmt.Println("You probably didn't enter only integers.")
		}
		nums[i] = int(num64)
	}
	return nums
}

func main() {
	unsorted := useFlags()
	sorted := BubbleSort(unsorted)
	fmt.Println(sorted)
}

Second try (working)

package main

import (
	"flag"
	"fmt"
	"strconv"
)

func Swap(sli []int, i int) bool {
	if sli[i] > sli[i+1] {
		sli[i], sli[i+1] = sli[i+1], sli[i]
		return true
	} else {
		return false
	}
}

func BubbleSort(sli []int) []int {
	count_sort := 1
	for count_sort > 0 {
		count_sort = 0
		for i := 0; i < len(sli)-1; i++ { // sort two-by-two, all 2-tuples
			if Swap(sli, i) {
				count_sort++
			}
		}
		if count_sort != 0 {
			BubbleSort(sli)
		}
	}
	return sli
}

func useFlags() []int {
	flag.Parse()
	args := flag.Args()
	fmt.Println("args:", args)

	nums := make([]int, len(args))
	// for each argument, insert in position nums[i] the string-converted value num64
	for i, arg := range args {
		num64, err := strconv.ParseInt(arg, 0, 0)
		if err != nil {
			fmt.Println("You probably didn't enter only integers.")
		}
		nums[i] = int(num64)
	}
	return nums
}

func main() {
	unsorted := useFlags()
	sorted := BubbleSort(unsorted)
	fmt.Println(sorted)
}

Week 2

Functions as first-class

Variables as Functions

Declaring a func as var

import "fmt"

var funVar func(int) int
func incFn(x int) int {
	return x+1
}

func main (){
	funVar = incFn
	fmt.Println(funVar(1))
	fmt.Println(incFn)
}

As arg

import "fmt"

var funVar func(int) int
func incFn(x int) int {
	return x+1
}

func applyIt(f func (int) int, x int) int {
	return f(x)
}

func main (){
	funVar = incFn
	fmt.Println(funVar(1))
	fmt.Println(incFn)
	fmt.Println(applyIt(incFn,1))
	fmt.Println(applyIt(incFn,(applyIt(incFn,1))))
}

Assignment 4

import "fmt"

func useFlags() [3]float64 {
	flag.Parse()
	args := flag.Args()
	fmt.Println("args:", args)

	nums := make([]int, len(args))
	// for each argument, insert in position nums[i] the string-converted value num64
	for i, arg := range args {
		num64, err := strconv.ParseFloat(arg, 0, 0)
		if err != nil {
			fmt.Println("You probably didn't enter only integers.")
		}
		nums[i] = int(num64)
	}
	return nums
}

func GenDisplaceFn(a, v0, s0 float64) func(float64){
	space := func (t float64){
		return (1/2)*a*t*t + v0*t + s0
	}
	return space
}

func main (){
	// fmt.Println("Enter a acceleration (a), initial velocity (v0) and (s0):")
	var params [3]float64
	params = useFlags()
	fn := GenDisplaceFn(params[0], params[1], params[2])

	var t float64
	fmt.Println("Enter a time (t) to calculate the displacement, with the \n the acceleration (a), initial velocity (v0) and (s0) you executed the program:")
	_, _ = fmt.Scan(&t)
	fmt.Println("The displacement for t=",t,"s(t):", fn(t))
}

GitHub

View Github