Find the most common element in a string array GO - go

i'm fairly new to golang and im having trouble finding the most common string in an array (Windrichting). it should be N but my output gives me W (it always gives me the last string so Windrichting[6]. Can someone help?
this is my code:
package main
import "fmt"
func main() {
Windrichting := [7]string{"N", "N", "N", "N", "O", "Z", "W"}
windEL, winner := Mostcommon(Windrichting)
fmt.Printf("Mostcommon windrichting: %s\n", windEL)
fmt.Printf("Komt %d x voor\n", winner)
}
func Mostcommon(Windrichting [7]string) (windEL string, winner int) {
var N int
var O int
var Z int
var W int
Windrichtingbase := [4]string{"N", "O", "Z", "W"}
for _, v := range Windrichting {
switch v {
case Windrichtingbase[0]:
N++
if N > winner {
N = winner
windEL = "Noord"
}
case Windrichtingbase[1]:
O++
if O > winner {
O = winner
windEL = "Oost"
}
case Windrichtingbase[2]:
Z++
if Z > winner {
Z = winner
windEL = "Zuid"
}
case Windrichtingbase[3]:
W++
if W > winner {
W = winner
windEL = "West"
}
}
}
return windEL, winner
}
output

winner is always 0 and you never update it. then after incrementing your direction variables (N, O, Z and W), you immediately overwrite them with the zero value stored in winner. You need to reverse the order of the assignment.
Like in this change: https://go.dev/play/p/VaJgZcijFdh
Note also, that capitalized variables in Go mean they're exported

Here's an alternate implementation. It uses a histogram to collect the number of times a word appears. It then steps through the histogram to find the most common word. Nothing is hard-coded.
https://go.dev/play/p/wTFvNaPRP6B

Related

Slices of crescent subsequences

I have a slice of float64 containing some values and a float value epsilon, what I would like to do is:
assuming that the slice got already sorted I want to go through the slice of float64 and check that every value of the sequence is bigger than the next one of at least value epsilon.
If it’s not bigger than the value epsilon than we will append on a slice of slices a new slice containing all the numbers read and the next numbers will be put in a new slice until the same condition happens or we finish going through the slice.
INPUT:
Epsilon : 0,001
Slice of floats64: [0,4351 0,455 0,4356 0,4359 0,4362]
DESIRED OUTPUT:
Returned slices: [ 0,4351 0,4355 ] [ 0,4356 0,4359 0,4362 ]
This is how I've tried to implement this:
for i := 0; i < len(sliceFloat); i++ {
for j := i + 1; j < len(sliceFloat); j++ {
if sliceFloat[i] - sliceFloat[j] <= epsilon {
sliceOfSlices = append(sliceOfSlices, sliceFloat[i:j])
} else {
continue
}
}
}
return sliceOfSlices
This is the output that I get:
[[0.4351] [0.4351 0.4355] [0.4351 0.4355 0.4356] [0.4351 0.4355 0.4356 0.4359] [0.4355] [0.4355 0.4356] [0.4355 0.4356 0.4359] [0.4356] [0.4356 0.4359] [0.4359]]
What am I doing wrong and how can I fix this?
The test input you posted is clearly wrong: GIGO: Garbage in, garbage out.
Epsilon : 0,001
Slice of floats64: [0,4351 0,455 0,4356 0,4359 0,4362]
Your code does not attempt to fully implement the specification.
else {
continue
}
After fixing all the bugs:
package main
import "fmt"
func crescents(s []float64, epsilon float64) [][]float64 {
var ss [][]float64
for i, f := range s {
if i == 0 || f <= s[i-1]+epsilon {
ss = append(ss, []float64(nil))
}
ss[len(ss)-1] = append(ss[len(ss)-1], f)
}
return ss
}
func main() {
s := []float64{0.4351, 0.4355, 0.4356, 0.4359, 0.4362}
epsilon := 0.0001
ss := crescents(s, epsilon)
fmt.Println(s, epsilon)
fmt.Println(ss)
}
https://go.dev/play/p/h-SxeIWPuu-
[0.4351 0.4355 0.4356 0.4359 0.4362] 0.0001
[[0.4351 0.4355] [0.4356 0.4359 0.4362]]

Bridge and Torch Problem for 'n' people with Go [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Problem: Given an array of positive distinct integer denoting the crossing time of ‘n’ people. These ‘n’ people are standing at one side of bridge. Bridge can hold at max two people at a time. When two people cross the bridge, they must move at the slower person’s pace. Find the minimum total time in which all persons can cross the bridge.
I am not able to find the pattern as of how to scale this for 'n' people. But somehow I managed to find the case with 4 people. Can someone help me with this. I am new to Golang and I am stuck with this problem.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"gopkg.in/yaml.v2"
)
type conf struct {
Person []map[string]float32 `yaml:"person"`
}
func (c *conf) getConf() *conf {
filename := os.Args[1] // Taking file input
yamlFile, err := ioutil.ReadFile(filename) // Yaml parse
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
return c
}
func main() {
var c conf // Object of struct conf
c.getConf() // calling getConf function
// Sorting the current conf map
n := map[float32][]string{} // Map to store current conf map
var a []float32 // Store values from conf map
for k, v := range c.Person {
v := float32(v)
fmt.Println(k, v)
n[v] = append(n[v], k)
}
for k := range n {
a = append(a, k)
}
// Converting float32 as float64 in order to sort the values in conf map
float32AsFloat64Values := make([]float64, len(a))
for i, val := range a {
float32AsFloat64Values[i] = float64(val)
}
sort.Float64s(float32AsFloat64Values)
for i, val := range float32AsFloat64Values {
a[i] = float32(val)
}
var time float32
fmt.Printf("\n%v\n", a)
for _, k := range a {
min1 := a[0]
min2 := a[1]
min3 := a[2]
for _, s := range n[k] {
//Debug:
fmt.Printf("%s, %g\n", s, k)
if len(a) > 3 {
time = (3 * min2) + min1 + a[3] //Formula for minimum time in case of 4 people
} else if len(a) == 3 {
time = min1 + min2 + min3
} else {
fmt.Println("Enter valid arguments in config.yaml")
}
}
}
fmt.Printf("Minimum time taken to cross the bridge is:\t%g\n", time)
}
Playground: https://play.golang.org/p/ObTVA8gk0mg
Config.yaml is:
person:
person_1: 2
person_2: 1
person_3: 5
person_4: 8
person_5: 9
One could run this as: 'go run main.go config.yaml'.
My scenario is that there could be 4,5 or 'n' number of people given in this yaml. Then what would be the minimum time for them to cross the bridge given the constraints.
I think the original problem is a bit more interesting than the one stated (yes, there has to be a Torch in the "Bridge and Torch" problem!).
Based on the Wikipedia description, for example,
Four people come to a river in the night. There is a narrow bridge, but it can only hold two people at a time. They have one torch and, because it's night, the torch has to be used when crossing the bridge. Person A can cross the bridge in 1 minute, B in 2 minutes, C in 5 minutes, and D in 8 minutes. When two people cross the bridge together, they must move at the slower person's pace. The question is, can they all get across the bridge if the torch lasts only 15 minutes?
In our case, of course, there are N people instead of just four, and it takes them variable amount of time to cross the bridge, but the rest of the story is the same.
Here's the implementation:
import (
"fmt"
"sort"
)
func minCrossingTime(x []int) int {
if len(x) == 1 {
return x[0]
}
sort.Ints(x)
t := 0
a, b := x[0], x[1]
x = x[2:]
for len(x) >= 2 {
n := len(x)
c, d := x[n-2], x[n-1]
x = x[:n-2]
t1 := 2*b + a + d
t2 := d + c + 2*a
if t1 < t2 {
t += t1
} else {
t += t2
}
}
if len(x) == 1 {
c := x[0]
t += a + b + c
} else {
t += b
}
return t
}
func main() {
x1 := []int{1, 2, 5, 8}
fmt.Printf("x = %x, time = %d\n", x1, minCrossingTime(x1))
x2 := []int{3, 8, 1, 6, 2, 9}
fmt.Printf("x = %x, time = %d\n", x2, minCrossingTime(x2))
}
Output:
x = [1 2 5 8], time = 15
x = [1 2 3 6 8 9], time = 27
Note: the first example [1 2 5 8] is straight from the Wikipedia, so the answer is yes, they can cross in 15 minutes
Key idea:
Definitions:
Let X = [X1,X2,...,XN] be the sorted array of crossing times with X1 being the fastest and XN the slowest
Let's denote as {XI,XJ} crossing by the pair of people XI and XJ, and {XK} crossing by one person XK, with +{...} indicating the crossing in the desired direction and -{...} in the opposite direction
Logic:
If N < 4 the problem is trivial:
N = 1 => t = X1 (+{X1})
N = 2 => t = X2 (+{X1,X2})
N = 3 => t = X1 + X2 + X3 (+{X1,X2} -{X1} + {X1,X3})
If N >= 4 consider the following problem: how to make two slowest people (and only them) cross the bridge and have the torch brought back in minimal time. There are two "good" ways to do it, with times
t1 = X1 + 2*X2 + XN (+{X1,X2} -{X1} +{X[N-1],XN} -{X2}) and
t2 = 2*X1 + X[N-1] + XN (+{X1,X[N-1]} -{X1} +{X1,XN} -{X1}), so we choose the best (minimum) out of these two
Now the two slowest have crossed the bridge, and the torch is on the same side where it started, so we are left with the original problem for X' = [X1, X2, ..., X[N-2]], which can be solved iteratively by applying the same logic and summing up the crossing times
Extras:
For mathematical proof and more context see e.g. https://page.mi.fu-berlin.de/rote/Papers/pdf/Crossing+the+bridge+at+night.pdf
Code golf solutions in different programming languages: https://codegolf.stackexchange.com/questions/75615/the-bridge-and-torch-problem
Problem: Given an array of positive distinct integer denoting the
crossing time of ‘n’ people. These ‘n’ people are standing at one side
of bridge. Bridge can hold at max two people at a time. When two
people cross the bridge, they must move at the slower person’s pace.
Find the minimum total time in which all persons can cross the bridge.
person:
person_1: 2
person_2: 1
person_3: 5
person_4: 8
person_5: 9
Your algorithm looks complicated.
For example,
package main
import (
"fmt"
"sort"
)
func minCrossingTime(people []int) int {
sort.Slice(people, func(i, j int) bool {
return people[i] > people[j]
})
min := 0
for i := 0; i < len(people); i += 2 {
min += people[i]
}
return min
}
func main() {
people := []int{2, 1, 5, 8, 9}
fmt.Println(len(people), people)
crossingTime := minCrossingTime(people)
fmt.Println(len(people), people)
fmt.Println(crossingTime)
}
Playground: https://play.golang.org/p/pXdGcinwxr-
Output:
5 [2 1 5 8 9]
5 [9 8 5 2 1]
15

A tuple assignment in Go

From spec:
A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right-hand operand is a single multi-valued expression such as a function call, a channel or map operation, or a type assertion. The number of operands on the left-hand side must match the number of values. For instance, if f is a function returning two values, x, y = f() assigns the first value to x and the second to y. In the second form, the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and the nth expression on the right is assigned to the nth operand on the left: one, two, three = '一', '二', '三'
The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in the left-to-right order.
Using this code ( i, n = i+2, n-1 inside for loop) :
package main
import (
"fmt"
"math"
)
func main() {
p := &Prime{}
p.Generate(1000000)
fmt.Println(p.Last()) // 15485863
}
func (p *Prime) Generate(n uint) {
p.Primes = make([]uint64, 1, n)
p.Primes[0] = 2
next:
for i := uint64(3); n > 1; i, n = i+2, n-1 {
q := uint64(math.Sqrt(float64(i)))
for _, v := range p.Primes[1:] {
if v > q {
break
}
if i%v == 0 {
continue next
}
}
p.Primes = append(p.Primes, i)
// n--
}
}
type Prime struct {
Primes []uint64
}
func (p *Prime) Last() uint64 {
return p.Primes[len(p.Primes)-1]
}
Output is:
1999993
This is not a correct result.
And this code:
func (p *Prime) Generate(n uint) {
p.Primes = make([]uint64, 1, n)
p.Primes[0] = 2
next:
for i := uint64(3); n > 1; i += 2 {
q := uint64(math.Sqrt(float64(i)))
for _, v := range p.Primes[1:] {
if v > q {
break
}
if i%v == 0 {
continue next
}
}
p.Primes = append(p.Primes, i)
n--
}
}
The output is correct:
15485863
go version go1.11.5 linux/amd64
Am I missing something on tuple Assignments in Go?
Thanks in advance.
Nope, it is not tuple assignment that gives wrong result.
There is a subtle difference between the two code, which causes the bug. In the playgound code, i,n = i+2,n-1 makes n = n-1 runs everytimes the loop is iterated, while the github code only runs n = n-1 when i is a prime (it skips n-- if continue next runs).

How to extract x top int values from a map in Golang?

I have a map[string]int
I want to get the x top values from it and store them in another data structure, another map or a slice.
From https://blog.golang.org/go-maps-in-action#TOC_7. I understood that:
When iterating over a map with a range loop, the iteration order is
not specified and is not guaranteed to be the same from one iteration
to the next.
so the result structure will be a slice then.
I had a look at several related topics but none fits my problem:
related topic 1
related topic 2
related topic 3
What would be the most efficient way to do this please?
Thanks,
Edit:
My solution would be to turn my map into a slice and sort it, then extract the first x values.
But is there a better way ?
package main
import (
"fmt"
"sort"
)
func main() {
// I want the x top values
x := 3
// Here is the map
m := make(map[string]int)
m["k1"] = 7
m["k2"] = 31
m["k3"] = 24
m["k4"] = 13
m["k5"] = 31
m["k6"] = 12
m["k7"] = 25
m["k8"] = -8
m["k9"] = -76
m["k10"] = 22
m["k11"] = 76
// Turning the map into this structure
type kv struct {
Key string
Value int
}
var ss []kv
for k, v := range m {
ss = append(ss, kv{k, v})
}
// Then sorting the slice by value, higher first.
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value
})
// Print the x top values
for _, kv := range ss[:x] {
fmt.Printf("%s, %d\n", kv.Key, kv.Value)
}
}
Link to golang playground example
If I want to have a map at the end with the x top values, then with my solution I would have to turn the slice into a map again. Would this still be the most efficient way to do it?
Creating a slice and sorting is a fine solution; however, you could also use a heap. The Big O performance should be equal for both implementations (n log n) so this is a viable alternative with the advantage that if you want to add new entries you can still efficiently access the top N items without repeatedly sorting the entire set.
To use a heap, you would implement the heap.Interface for the kv type with a Less function that compares Values as greater than (h[i].Value > h[j].Value), add all of the entries from the map, and then pop the number of items you want to use.
For example (Go Playground):
func main() {
m := getMap()
// Create a heap from the map and print the top N values.
h := getHeap(m)
for i := 1; i <= 3; i++ {
fmt.Printf("%d) %#v\n", i, heap.Pop(h))
}
// 1) main.kv{Key:"k11", Value:76}
// 2) main.kv{Key:"k2", Value:31}
// 3) main.kv{Key:"k5", Value:31}
}
func getHeap(m map[string]int) *KVHeap {
h := &KVHeap{}
heap.Init(h)
for k, v := range m {
heap.Push(h, kv{k, v})
}
return h
}
// See https://golang.org/pkg/container/heap/
type KVHeap []kv
// Note that "Less" is greater-than here so we can pop *larger* items.
func (h KVHeap) Less(i, j int) bool { return h[i].Value > h[j].Value }
func (h KVHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h KVHeap) Len() int { return len(h) }
func (h *KVHeap) Push(x interface{}) {
*h = append(*h, x.(kv))
}
func (h *KVHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}

Find the minimum value in golang?

In the language there is a minimum function https://golang.org/pkg/math/#Min But what if I have more than 2 numbers? I must to write a manual comparison in a for loop, or is there another way? The numbers are in the slice.
No, there isn't any better way than looping. Not only is it cleaner than any other approach, it's also the fastest.
values := []int{4, 20, 0, -11, -10}
min := values[0]
for _, v := range values {
if (v < min) {
min = v
}
}
fmt.Println(min)
EDIT
Since there has been some discussion in the comments about error handling and how to handle empty slices, here is a basic function that determines the minimum value. Remember to import errors.
func Min(values []int) (min int, e error) {
if len(values) == 0 {
return 0, errors.New("Cannot detect a minimum value in an empty slice")
}
min = values[0]
for _, v := range values {
if (v < min) {
min = v
}
}
return min, nil
}
General answer is: "Yes, you must use a loop, if you do not know exact number of items to compare".
In this package Min functions are implemented like:
// For 2 values
func Min(value_0, value_1 int) int {
if value_0 < value_1 {
return value_0
}
return value_1
}
// For 1+ values
func Mins(value int, values ...int) int {
for _, v := range values {
if v < value {
value = v
}
}
return value
}
You should write a loop. It does not make sense to create dozens of function in standard library to find min/max/count/count_if/all_of/any_of/none_of etc. like in C++ (most of them in 4 flavours according arguments).

Resources