I have a slice in golang with strings. Each letter w, d and l have a numerical value…
- User
I have a slice in golang with strings. Each letter w, d and l have a numerical value that i have to count : for example w is 3, d is 1 and l is 0. What would be the best and simplest way to count all the values of w, of l and of d? This is the slice results := []string{"w", "l", "w", "d", "w", "l", "l", "l", "d", "d", "w", "l", "w", "d"}
- Assistant
The simplest way to count the values of 'w', 'd', and 'l' based on their associated numerical values is to loop through the slice and sum up the values accordingly. The code would look something like this:
package main import ( "fmt" ) func main() { results := []string{"w", "l", "w", "d", "w", "l", "l", "l", "d", "d", "w", "l", "w", "d"} // Define scores for each letter scores := map[string]int{ "w": 3, "d": 1, "l": 0, } // Initialize counters wCount, dCount, lCount := 0, 0, 0 // Loop through the results and sum up counts for _, result := range results { switch result { case "w": wCount += scores["w"] case "d": dCount += scores["d"] case "l": lCount += scores["l"] } } // Print results fmt.Printf("Total score for 'w': %d\n", wCount) fmt.Printf("Total score for 'd': %d\n", dCount) fmt.Printf("Total score for 'l': %d\n", lCount) }When you run this code, it will output the total score for each letter type based on the given slice:
Total score for 'w': 21 Total score for 'd': 4 Total score for 'l': 0In the code above, we have initialized a map called
scoresthat holds the numerical values associated with each letter. We then set up counts initialized to zero for 'w', 'd', and 'l'. The loop checks each string in the slice and adds the appropriate score to the corresponding count according to what letter was encountered. Finally, we print out the accumulated scores.