Sort numbers lexicographically

From Rosetta Code
Revision as of 21:19, 25 July 2018 by rosettacode>Gerard Schildberger (→‎{{header|REXX}}: added an example of negative integers.)
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.
Task

Given an integer   n,   return   1──►n   (inclusive)   in lexicographical order.

Show all output here on this page.


Example

Given   13,
return:   [1,10,11,12,13,2,3,4,5,6,7,8,9].

C

<lang c>#include <math.h>

  1. include <stdio.h>
  2. include <stdlib.h>
  3. include <string.h>

int compareStrings(const void *a, const void *b) {

   const char **aa = (const char **)a;
   const char **bb = (const char **)b;
   return strcmp(*aa, *bb);

}

void lexOrder(int n, int *ints) {

   int i, len;
   char **strs = malloc(n * sizeof(char *));
   for (i = 1; i <= n; ++i) {
       len = (int)log10(i) + 2;
       strs[i-1] = malloc(len);
       sprintf(strs[i-1], "%d", i);
   }
   qsort(strs, n, sizeof(char *), compareStrings);
   for (i = 0; i < n; ++i) {
       ints[i] = atoi(strs[i]);
       free(strs[i]);
   }
   free(strs);

}

int main() {

   int i, j, n, *ints;
   int numbers[3] = {5, 13, 21};
   printf("In lexicographical order:\n\n");
   for (i = 0; i < 3; ++i) {
       n = numbers[i];
       if (n < 1) n = 1;
       ints = malloc(n * sizeof(int));
       lexOrder(n, ints);
       printf("%2d: [", numbers[i]);
       for (j = 0; j < n; ++j) {
           printf("%d ", ints[j]);
       }
       printf("\b]\n");
       free(ints);
   }
   return 0;

}</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]

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]

Kotlin

<lang scala>// Version 1.2.51

fun lexOrder(n: Int): List<Int> {

   if (n <= 1) return listOf(1)
   return (1..n).map { it.toString() }.sorted().map { it.toInt() }

}

fun main(args: Array<String>) {

   println("In lexicographical order:\n")
   for (n in listOf(5, 13, 21)) {
       println("${"%2d".format(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]

Perl 6

Works with: Rakudo version 2018.06

<lang perl6>sub lex (Int $n) { (1…$n).sort: ~* }

  1. TESTING

printf("%4d: [%s]\n", $_, .&lex.join: ',') for 13, 21, -22</lang>

Output:
  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]
 -22: [-1,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-2,-20,-21,-22,-3,-4,-5,-6,-7,-8,-9,0,1]

REXX

This REXX version allows the starting and ending integer to be specified via the command line (CL). <lang rexx>/*REXX pgm displays a horizontal list of a range of integers sorted lexicographically.*/ parse arg LO HI . /*obtain optional arguments from the CL*/ if LO== | LO=="," then LO= 1 /*Not specified? Then use the default.*/ if HI== | HI=="," then HI= 13 /* " " " " " " */

  1. =0 /*for actual sort, start array with 1.*/
            do j=LO  to  HI;  #= # + 1;   @.#=j /*construct an array from  LO   to  HI.*/
            end   /*j*/

call lSort # /*sort integer array with a simple sort*/ $= /*initialize horizontal integer list. */

            do k=1  for  #;   $= $','@.k        /*construct      "         "      "    */
            end   /*k*/                         /* [↑]  prefix each number with a comma*/

say 'for ' LO"──►"HI' (inclusive), ' # "elements sorted lexicographically:" say '['strip($, "L", ',')"]" /*strip leading comma, bracket the list*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ lSort: procedure expose @.; parse arg n; m=n-1 /*N: is the number of @ array elements.*/

      do m=m  by -1  until ok;     ok=1         /*keep sorting the  @ array until done.*/
         do j=1  for m;   k=j+1;  if @.j>>@.k  then parse value @.j @.k 0 with @.k @.j ok
         end   /*j*/                            /* [↑]  swap 2 elements, flag as ¬done.*/
      end      /*m*/;     return</lang>
output   when using the default input:
for  1──►13  (inclusive),  13 elements sorted lexicographically:
[1,10,11,12,13,2,3,4,5,6,7,8,9]
output   when using the input of:     1   34
for  1──►34  (inclusive),  34 elements sorted lexicographically:
[1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,26,27,28,29,3,30,31,32,33,34,4,5,6,7,8,9]
output   when using the input of:     -11   22
for  -11──►22  (inclusive),  34 elements sorted lexicographically:
[-1,-10,-11,-2,-3,-4,-5,-6,-7,-8,-9,0,1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,3,4,5,6,7,8,9]

Ring

<lang ring>

  1. Project : Lexicographical numbers
  2. Date  : 2018/07/25
  3. Author : Gal Zsolt (~ CalmoSoft ~)
  4. 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]

zkl

<lang zkl>fcn lexN(n){ n.pump(List,'+(1),"toString").sort().apply("toInt") }</lang> <lang zkl>foreach n in (T(5,13,21)){ println("%2d: %s".fmt(n,lexN(n).concat(","))) }</lang>

Output:
 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