Home > OS >  How to add zeros to 2d slice string elements
How to add zeros to 2d slice string elements

Time:11-28

The task is to add zeros to string elements of 2d slice. So the stdin is [["7" "3" "1"]["2" "9"]] and I need to add zeros from the last element of each slice to the first one. For each step the counter of zeros is incremented by 1. Therefore, stdout is expected to be [["700", "30", "1"]["20", "9"]].

I have tried to do such an algorithm but can't get expected answer. Here is my code:

package main

import (
    "fmt"
    "strings"
)

func addZero(strs [][]string) [][]string {
    zero := "0"
    counter := 0
    for i := range strs {
        for j := range strs[i] {
            strs[i][j]  = strings.Repeat(zero, counter)
        }
        counter  
    }
    return strs
}

func main() {
    fmt.Println(addZero([][]string{{"7", "3", "1"}, {"2", "9"}}))// here the result is [[7 3 1] [20 90]]
 
}

How to change my code to get an expected answer ?

CodePudding user response:

Counting zeros has to reset in each line, so move that code inside the first loop.

Also range goes from index 0, and you want increasing zeroes from the end of lines, so counter has to start from len(strs[i])-1, and you have to decrement it:

func addZero(strs [][]string) [][]string {
    for i := range strs {
        zero := "0"
        counter := len(strs[i]) - 1
        for j := range strs[i] {
            strs[i][j]  = strings.Repeat(zero, counter)
            counter--
        }
    }
    return strs
}

With these changes output will be (try it on the Go Playground):

[[700 30 1] [20 9]]

Note that if you would process lines from the end, the suffix to append (the zeros) would increase. So you could ditch strings.Repeat() by keeping and "extending" the previous suffix:

func addZero(strs [][]string) [][]string {
    for _, line := range strs {
        zeros := ""
        for i := len(line) - 1; i >= 0; i-- {
            line[i]  = zeros
            zeros  = "0"
        }
    }
    return strs
}

This outputs the same. Try it on the Go Playground.

Also note that strings can be sliced, and the result shares the memory with the sliced string. So it's fast and does not create garbage! You could build a single, long zeros string holding just zeros, and you could slice this long string to have as many zeros as you need to append. This solution avoids any unnecessary string allocations and concatenations:

var zeros = strings.Repeat("0", 1000) // Use the maximum length here

func addZero(strs [][]string) [][]string {
    for _, line := range strs {
        count := len(line) - 1
        for i := range line {
            line[i]  = zeros[:count-i]
        }
    }
    return strs
}

This again outputs the same, try it on the Go Playground.

  • Related