Search code examples
stringgounicodeasciifor-range

standard unicode in GO programming language


I have a string containing cards from ace of hearts to 10 of hearts via unicode (the exercise requires using a string, so no arrays or slices) Given a number n I have to extract n cards from this string. How do I do this if with the for-range I get fewer bits than I need?

package main

import (
    "fmt"
    "math/rand"
    "strconv"
    "strings"
    "time"
)

func main() {
    var n int
    var deck string

    rand.Seed(int64(time.Now().Nanosecond()))

    n = readNumber()
    deck = deckGenerator()
    drawCards(deck, n)

}

func readNumber() (n int) {
    for n <= 0 || n >= 10 {
        fmt.Print("Enter number between 1 and 9: ")
        fmt.Scan(&n)
    }
    return n
}

func deckGenerator() (deck string) {
    for i := 0; i < 10; i++ {
        deck += strconv.Itoa('\U0001F0B1' + i)
    }
    return deck
}

func drawCards(deck string, n int) {
    for i := 0; i < n; i++ {
        cardPulledOut, deck2 := drawCard(deck)
        fmt.Println("Pulled out the card", cardPulledOut, "- Cards left in the deck:", deck2)
    }
}

func drawCard(deck string) (cardPulledOut rune, deck2 string) {
    for true {
        card := rune(('\U0001F0B1') + rand.Intn(10)) //random number between 0 and 9 inclusive

        for _, v := range deck {
            fmt.Println(v, card)
            /*
                output: (infinity loop)
                ...
                49 127156
                53 127156
                56 127156
                ...
            */
            if v == card {
                deck = strings.Replace(deck, string(card), "", 1)
                return cardPulledOut, deck2
            }
        }
    }
    return
}

Solution

  • Your population function has a bug:

    func deckGenerator() (deck string) {
        for i := 0; i < 10; i++ {
            // deck += strconv.Itoa('\U0001F0B1' + i) // converts integers to their string equivalent e.g. "127156"
    
            deck += string(rune('\U0001F0B1' + i))    // fix
        }
        return deck
    }
    

    https://go.dev/play/p/E3sVRZK4exh