How to convert a matrix of numbers to a string in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"strings"
)

func matrixToString(matrix [][]int) string {
	var builder strings.Builder
	
	for _, row := range matrix {
		builder.WriteString(fmt.Sprintf("%v\n", row))
	}
	
	return builder.String()
}

func main() {
	matrix := [][]int{
        {4, 7, 9, 18, 29, 0},
        {1, 9, 18, 99, 4, 3},
        {9, 17, 89, 2, 7, 5},
        {19, 49, 6, 1, 9, 8},
        {29, 4, 7, 9, 18, 6},
	}

	result := matrixToString(matrix)
	
	fmt.Println("Matrix as String:")
	fmt.Println(result)
}



/*
run:

Matrix as String:
[4 7 9 18 29 0]
[1 9 18 99 4 3]
[9 17 89 2 7 5]
[19 49 6 1 9 8]
[29 4 7 9 18 6]

*/

 



answered May 24 by avibootz
...