packagemainimport("bufio""fmt""math/rand""os""time")constDebugbool=truevarstdin*bufio.Readerfuncmain(){varguessintvartrialuintanswer:=GenRandNumber()// Ask guess initially
guess=UserInput()fortrial=1;guess!=answer;trial++{ifguess>answer{fmt.Println("Your number is greater than the answer.")}else{fmt.Println("Your number is lesser than the answer.")}ifguess<0||guess>=100{fmt.Println("Hint: answer is a number in range from 0 to 99")}// Ask your guess again
guess=UserInput()}fmt.Println("Correct, congratulation!")fmt.Printf("Tried %d times",trial)}funcinit(){// Configure random seed
rand.Seed(time.Now().UnixNano())stdin=bufio.NewReader(os.Stdin)}funcGenRandNumber()int{// Generate random number from 0 to 99
answer:=rand.Intn(100)// For debugging condition, print answer first
ifDebug{fmt.Println("Answer is :",answer)}returnanswer}funcUserInput()int{varnintfor{fmt.Print("Write your guess: ")_,err:=fmt.Scanln(&n)iferr!=nil{stdin.ReadString('\n')fmt.Println("Please write only numbers!")}else{returnn}}}
$ ./match_number
Answer is : 78
Write your guess: a
Please write only numbers!
Write your guess: 99
Your number is greater than the answer.
Write your guess: 77
Your number is lesser than the answer.
Write your guess: 100
Your number is greater than the answer.
Hint: answer is a number in range from 0 to 99
Write your guess: -1
Your number is lesser than the answer.
Hint: answer is a number in range from 0 to 99
Write your guess: 78
Correct, congratulation!
Tried 5 times