0

I am a beginner programmer and was going through some GitHub repositories and found this simple classic fizzbuzz implementation using a map. However when I run it a couple of times it prints buzzfizz when the isMultiple is true for both 3 and 5. For instance, once in a while for the values 15 or 60 it may print buzzfizz instead of fizzbuzz which seems inconsistent to me and got me curious to fix it. Can someone explain why does this happen and what I am missing here? Is it merely a language behavior or the code can be improved for this consistency?

package main

import (
    "fmt"
)

func isMultiple(i,j int)bool  {
    return i%j==0
}
func main(){
    fizzbuzz:=make(map[int]string)
    fizzbuzz[3]="fizz"
    fizzbuzz[5]="buzz"
    for i:=1; i<101; i++ {
        str:=""
        for k,v:=range fizzbuzz{
            if isMultiple(i,k)==true{str+=v}
        }
        fmt.Println(i,":",str)
    }

}

Edit: Decided to put the code here seeing the common convention it is better here.

1 Answers1

2

Go maps are unordered data structures, you should not rely on ordering of keys.

To prevent developers from accidentally relying on small map ordering, Go randomizes small maps every time.

Please read up on maps in Go.

Marc
  • 19,394
  • 6
  • 47
  • 51
  • 1
    See also [the spec](https://golang.org/ref/spec#For_statements): "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next." – Adrian Dec 15 '17 at 21:02