Documentation
¶
Overview ¶
Package array2d contains an implementation of a 2D array.
Index ¶
- type Array2D
- func (a Array2D[T]) Copy() Array2D[T]
- func (a Array2D[T]) Fill(x1, y1, x2, y2 int, value T)
- func (a Array2D[T]) Get(x, y int) T
- func (a Array2D[T]) Height() int
- func (a Array2D[T]) Row(y int) []T
- func (a Array2D[T]) RowSpan(x1, x2, y int) []T
- func (a Array2D[T]) Set(x, y int, value T)
- func (a Array2D[T]) String() string
- func (a Array2D[T]) Width() int
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Array2D ¶
type Array2D[T any] struct { // contains filtered or unexported fields }
Array2D is a 2-dimensional array.
Example ¶
//go:build go1.18
// +build go1.18
package main
import (
"fmt"
"strings"
"github.com/fufuok/utils/generic/array2d"
)
type Sudoku struct {
arr array2d.Array2D[byte]
}
func (s Sudoku) PrintBoard() {
var sb strings.Builder
for y := 0; y < s.arr.Height(); y++ {
if y%3 == 0 {
sb.WriteString("+-------+-------+-------+\n")
}
for x := 0; x < s.arr.Width(); x++ {
if x%3 == 0 {
sb.WriteString("| ")
}
val := s.arr.Get(x, y)
if val == 0 {
sb.WriteByte(' ')
} else {
fmt.Fprint(&sb, val)
}
sb.WriteByte(' ')
}
sb.WriteString("|\n")
}
sb.WriteString("+-------+-------+-------+\n")
fmt.Print(sb.String())
}
func main() {
s := Sudoku{
arr: array2d.OfJagged(9, 9, [][]byte{
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9},
}),
}
s.arr.Set(2, 5, 3)
s.PrintBoard()
}
Output: +-------+-------+-------+ | 5 3 | 7 | | | 6 | 1 9 5 | | | 9 8 | | 6 | +-------+-------+-------+ | 8 | 6 | 3 | | 4 | 8 3 | 1 | | 7 3 | 2 | 6 | +-------+-------+-------+ | 6 | | 2 8 | | | 4 1 9 | 5 | | | 8 | 7 9 | +-------+-------+-------+
func OfJagged ¶
OfJagged initializes a 2-dimensional array based on a jagged slice of rows of values. Values from the jagged slice that are out of bounds are ignored.
func (Array2D[T]) Fill ¶
Fill will assign all values inside the region to the specified value. The coordinates are inclusive, meaning all values from [x1,y1] including [x1,y1] to [x2,y2] including [x2,y2] are set.
The method sorts the arguments, so x2 may be lower than x1 and y2 may be lower than y1.
func (Array2D[T]) Get ¶
Get returns a value from the array.
The function will panic on out-of-bounds access.
func (Array2D[T]) Height ¶
Height returns the height of this array. The maximum y value is Height()-1.
func (Array2D[T]) Row ¶
Row returns a mutable slice for an entire row. Changing values in this slice will affect the array.
func (Array2D[T]) RowSpan ¶
RowSpan returns a mutable slice for part of a row. Changing values in this slice will affect the array.
func (Array2D[T]) Set ¶
Set sets a value in the array.
The function will panic on out-of-bounds access.