Mittenchops
Mittenchops

Reputation: 19664

Print matrix as string in golang

I have a matrix of integers, represented by a multivariate array. I'm trying to concatenate the numbers into a string representation, rows-by-columns. My naive approach is to walk over all entries in the matrix and append them to a nullstring.

However, I'm getting an error that my append function is saying:

./main.go:xx:yy: first argument to append must be slice; have string

My code is:

type MatString string 
type IntMat [3][3]Int // external constraints require fixed size, symmetric.

func Matrix2String(t IntMat) MatString {
    // s var string
    s := ""
    for i := range t {
        for j := range t[i] {
            s = append(s[:], fmt.Sprintf("%s", j))
            // fmt.Sprintf(s)
        }
    }
    return MatString(s)
}

What am I misunderstanding about arrays, slices, and joins, and how can I iteratively build up this string correctly?

Upvotes: 3

Views: 1709

Answers (2)

samix73
samix73

Reputation: 3063

You can simply concatenate converted integers to strings, to the response

func Matrix2String(t IntMat) MatString {
    s := ""

   for i := range t {
      for _, n := range t[i] {
          s += fmt.Sprintf("%d", n)
      }
   }

    return MatString(s)
}

Playground

Upvotes: 1

Thundercat
Thundercat

Reputation: 120951

Collect the elements in a slice of strings. Join the slice to produce the result.

func Matrix2String(t IntMat) MatString {
    var s []string
    for i := range t {
        for _, n := range t[i] {
            s = append(s, fmt.Sprintf("%d", n))
        }
    }
    return MatString(strings.Join(s, ""))
}

Another approach is to build the string in a []byte and convert at the end:

func Matrix2String(t IntMat) MatString {
    var s []byte
    for i := range t {
        for _, n := range t[i] {
            s = strconv.AppendInt(s, int64(n), 10)
        }
    }
    return MatString(s)
}

I didn't include any delimiters because the question didn't include them.

Upvotes: 4

Related Questions