Last list item
Last list item is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
- Task
List = [6, 81, 243, 14, 25, 49, 123, 69, 11]
Find two smallest items, summarize them, add to the end of list and delete them.
Repeat it until list contains one element.
Show the steps and last item on this page.
Go
<lang go>package main
import (
"fmt" "sort"
)
func main() {
a := []int{6, 81, 243, 14, 25, 49, 123, 69, 11} for len(a) > 1 { sort.Ints(a) a = append(a, a[0]+a[1]) a = a[2:] } fmt.Println("Last item is", a[0], "\b.")
}</lang>
- Output:
Last item is 621.
Ring
<lang ring> see "working..." + nl
List = [6,81,243,14,25,49,123,69,11] Temp = []
while true
Temp = sort(List) first = Temp[1] second = Temp[2] ind1 = find(List,first) ind2 = find(List,second) del(List,ind2) del(List,ind1) sum = first + second add(List,sum) if len(List) = 1 exit ok showList(first,second,List)
end
see "Last item is: " +List[1] + nl see "done..." + nl
func showList(first,second,List)
see "two smallest number is = " + first + " " + second + nl see "List = " showArray(List)
func showArray(array)
txt = "" see "[" for n = 1 to len(array) txt = txt + array[n] + "," next txt = left(txt,len(txt)-1) txt = txt + "]" see txt + nl
</lang>
- Output:
working... two smallest number is = 6 11 List = [81,243,14,25,49,123,69,17] two smallest number is = 14 17 List = [81,243,25,49,123,69,31] two smallest number is = 25 31 List = [81,243,49,123,69,56] two smallest number is = 49 56 List = [81,243,123,69,105] two smallest number is = 69 81 List = [243,123,69,150] two smallest number is = 69 123 List = [243,69,192] two smallest number is = 69 192 List = [243,261] Last item is: 504 done...
Wren
<lang ecmascript>var a = [6, 81, 243, 14, 25, 49, 123, 69, 11]
while (a.count > 1) {
a.sort() a.add(a[0] + a[1]) a = a[2..-1]
}
System.print("Last item is %(a[0]).")</lang>
- Output:
Last item is 621.