For loop ends with its body and dont go furter
I need find wIndex, check if its in the slice, if no add value Where I go wrong?
var x make(map[int]float32, 10)
var s []int
var value = 100
for i := 1; i <= 10; i++ {
wIndex := int(rand.Intn(len(x))) // random Index choice among map values
for _, v := range s { //end of loop here (if exactly it returnts to loop before)
if v != wIndex {
s = append(s, wIndex)
x[wIndex] += value
}
}
}
You start with an empty s
slice. So you will never enter your inner for loop where you add elements to the slice.
Here is an alternative and straight forward way to do it:
for i := 1; i <= 10; i++ {
wIndex := int(rand.Intn(len(x) + 1))
found := false
for _, v := range s {
if v == wIndex {
found = true
break
}
}
if !found {
s = append(s, wIndex)
x[wIndex] += float32(value)
}
}
note that you need to convert the value to a float32, so x[wIndex] += float32(value)
instead of just x[wIndex] += value
rand.Intn(n int)
generates numbers in the range [0,n), so you need to add 1 to cover the proper range, and avoid panic when the map is empty.
The inside loop will never execute because the slice does not have a value it is empty so insert a random value into the slice and then range over it.
There are other things to notice as well since rand.Intn
already returns int then there is no need to type cast it into int.
int(rand.Intn(len(x))) // no requirement to typecast it into int.
One more thing is the length of map is 0
which is why the rand.Intn
will throw an error when running your code.
wIndex := int(rand.Intn(len(x))) // This will throw an error.
Change your code as below.
package main
import (
"fmt"
"math/rand"
)
func main() {
var x = make(map[int]float32)
var s []int
var value = 100
for i := 1; i <= 10; i++ {
wIndex := rand.Intn(10) // random Index choice among map values
s = append(s, wIndex)
for _, v := range s { //end of loop here (if exactly it returnts to loop before)
if v != wIndex {
x[wIndex] += float32(value)
}
}
}
fmt.Println(s)
fmt.Println(x)
}
Working Example on Go playground