Last list item: Difference between revisions

→‎{{header|Go}}: Added second version as per Wren.
(→‎{{header|Wren}}: Added second version which doesn't use sorting.)
(→‎{{header|Go}}: Added second version as per Wren.)
Line 174:
=={{header|Go}}==
{{trans|Wren}}
===With sorting===
<lang go>package main
 
Line 188 ⟶ 189:
sum := a[0] + a[1]
fmt.Printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum)
a = append(a, a[0]+a[1]sum)
a = a[2:]
}
Line 211 ⟶ 212:
Two smallest: 150 + 228 = 378
Sorted list: [243 378]
Two smallest: 243 + 378 = 621
Last item is 621.
</pre>
 
===Without sorting===
<lang go>package main
 
import "fmt"
 
func findMin(a []int) (int, int) {
ix := 0
min := a[0]
for i := 1; i < len(a); i++ {
if a[i] < min {
ix = i
min = a[i]
}
}
return min, ix
}
 
func main() {
a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11}
for len(a) > 1 {
fmt.Println("List:", a)
var s [2]int
for i := 0; i < 2; i++ {
min, ix := findMin(a)
s[i] = min
a = append(a[:ix], a[ix+1:]...)
}
sum := s[0] + s[1]
fmt.Printf("Two smallest: %d + %d = %d\n", s[0], s[1], sum)
a = append(a, sum)
}
fmt.Println("Last item is", a[0], "\b.")
}</lang>
 
{{out}}
<pre>
List: [6 81 243 14 25 49 123 69 11]
Two smallest: 6 + 11 = 17
List: [81 243 14 25 49 123 69 17]
Two smallest: 14 + 17 = 31
List: [81 243 25 49 123 69 31]
Two smallest: 25 + 31 = 56
List: [81 243 49 123 69 56]
Two smallest: 49 + 56 = 105
List: [81 243 123 69 105]
Two smallest: 69 + 81 = 150
List: [243 123 105 150]
Two smallest: 105 + 123 = 228
List: [243 150 228]
Two smallest: 150 + 228 = 378
List: [243 378]
Two smallest: 243 + 378 = 621
Last item is 621.
9,482

edits