Sort numbers lexicographically
Sort numbers lexicographically 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.
Given an integer n, return 1 - n in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
Go
<lang go>package main
import (
"fmt" "sort" "strconv"
)
func lexOrder(n int) []int {
if n <= 1 { return []int{1} } strs := make([]string, n) for i := 1; i <= n; i++ { strs[i-1] = strconv.Itoa(i) } sort.Strings(strs) ints := make([]int, n) for i := 0; i < n; i++ { ints[i], _ = strconv.Atoi(strs[i]) } return ints
}
func main() {
fmt.Println("In lexicographical order:\n") for _, n := range []int{5, 13, 21} { fmt.Printf("%2d: %v\n", n, lexOrder(n)) }
}</lang>
- Output:
In lexicographical order: 5: [1 2 3 4 5] 13: [1 10 11 12 13 2 3 4 5 6 7 8 9] 21: [1 10 11 12 13 14 15 16 17 18 19 2 20 21 3 4 5 6 7 8 9]
Ring
<lang ring>
- Project : Lexicographical numbers
- Date : 2018/07/25
- Author : Gal Zsolt (~ CalmoSoft ~)
- Email : <calmosoft@gmail.com>
lex = 1:13 strlex = list(len(lex)) for n = 1 to len(lex)
strlex[n] = string(lex[n])
next strlex = sort(strlex) see "Lexicographical numbers = " showarray(strlex)
func showarray(vect)
see "[" svect = "" for n = 1 to len(vect) svect = svect + vect[n] + "," next svect = left(svect, len(svect) - 1) see svect + "]" + nl
</lang> Output:
Lexicographical numbers = [1,10,11,12,13,2,3,4,5,6,7,8,9]