Reputation: 29
Implement the function SumCells(cells)
.
Input: an arbitrary collection cells of Cell variables.
Return: a single Cell variable corresponding to summing corresponding elements in every cell in cells.
type Cell [2]float64
func SumCells(cells ...Cell) Cell {
sum := 0.0
var c Cell
c = append(c, cells)
for rowIndex, row := range cells { // loop through rows
for cellIndex := range row {
sum += [rowIndex][cellIndex]
}
}
return c
}
Could someone explain how to write this function?
Upvotes: 1
Views: 99
Reputation: 1620
// Cell is a 2D point
type Cell [2]float64
// SumCells adds a bunch of cells together
func SumCells(cells ...Cell) Cell {
var sum Cell
for _, cell := range cells {
sum = sum.Add(cell)
}
return sum
}
// Cell.Add adds two cells together
// This is a method on the Cell type
func (c Cell) Add(other Cell) Cell {
return Cell{
c[0] + other[0],
c[1] + other[1],
}
}
Upvotes: 0
Reputation: 74345
Something like this should do you:
func SumCells(cells ...Cell) (sum Cell) {
for _, c := range cells {
sum[0] += c[0]
sum[1] += c[1]
}
return sum
}
type Cell [2]float64
Or, if you wanted to future-proof yourself in case the number of elements in a Cell
changes:
func SumCells(cells ...Cell) (sum Cell) {
for _, c := range cells {
for i, v := range c {
sum[i] += v
}
}
return sum
}
type Cell [2]float64
Upvotes: 0
Reputation: 2398
Cell is a single dimensional array or simple array and in SumCells
...Cell or []Cell want's an array of Cells []Cell{{1,3}, {3, 4}}
so you can simply do this Go Playground
func SumCells(cells []Cell) float64 {
var sum float64
for _, cell := range cells {
sum += cell[0] + cell[1]
}
return sum
}
Upvotes: 1