goglide-golang

Say The Numbers - Sololearn Go Challenge


I'm currently learning Go using the SoloLearn App.
The Challenge was :
Taking 3 numbers in the range of 0-10 as input and output the corresponding texts in English.
Test Case #1, Test Case #3, Test Case #4 and #Test Case #5 were successful.
But I have problems concluding Test Case #2 and Test Case #6.
Thank you in advance for any help.

package main
import "fmt"

func main() {
   
   for i:=0;i<3;i++ {
   var x int
   fmt.Scanln(&x)

   if (x>=0 && x<10) {
  
       switch x {
          case 0:
            fmt.Print("Zero")
          case 1:
            fmt.Print("One")
          case 2:
            fmt.Print("Two")
          case 3:
            fmt.Print("Three")
          case 4:
            fmt.Print("Four")
          case 5:
            fmt.Print("Five")
          case 6:
            fmt.Print("Six")
          case 7:
            fmt.Print("Seven")
          case 8:
            fmt.Print("Eight")
          case 9:
            fmt.Print("Nine")
          case 10:
            fmt.Print("Ten")
          default:
            fmt.Println("This is not a number or a number between 0 and 10")
         }
        }
        if i<2 {
           fmt.Println("")
        }
       }
   
  }

Solution

  • Maybe by sharing the test cases would be easier for us to understand whats happening.

    But at a first sight I would replace the x<10 with x<=10 and all the fmt.Print with fmt.Println and remove this parts.

        if i<2 {
           fmt.Println("")
        }
    

    If you keep the condition that validates that the input number is between 0 and 10 the message of the default case would never be printed.

    And also let me share you another approach of the solution, is the same but with a couple of good practices:

    package main
    
    import "fmt"
    
    var validWrittenNumbers = map[int]string{
        1: "One",
        2: "Two",
        3: "Three",
        4: "Four",
        5: "Five",
        6: "Six",
        7: "Seven",
        8: "Eight",
        9: "Nine",
        10: "Ten",
    }
    
    func printValidWrittenNumber(candidateNumber int) {
        if stringNumber, ok := validWrittenNumbers[candidateNumber]; ok {
            fmt.Println(stringNumber)
        }
    }
    
    func main() {
        inputTimes := 3
    
        for index := 0; index < inputTimes; index++ {
            var candidateNumber int
            _, _ = fmt.Scanln(&candidateNumber)
    
            printValidWrittenNumber(candidateNumber)
        }
    }
    

    I hope this works and sorry for not being more helpful!