Given a string of digits or an integer as input, you will have to indexize it.

This is how you modify the input. We will use 30043376111 as an example:

First, find the sum of the indices of each occurrence of the respective digits:

0: 1 + 2 = 3
1: 8 + 9 + 10 = 27
3: 0 + 4 + 5 = 9
4: 3
6: 7
7: 6

Then, construct a new integer or string where the digits above go in the order of the sums of their indices. In the case that multiple digits yield the same sum, the smaller digit comes before the larger one:


Finally, remove any leading zeroes, and return or print the result:


You must write a program or function which returns or prints the input indexized.

This is , so shortest code in bytes wins!

More test cases can be added if requested.

  • \$\begingroup\$ For functions, is returning a string okay? How about taking a string as an argument? \$\endgroup\$ – Conor O'Brien Mar 28 '17 at 19:38
  • \$\begingroup\$ @ConorO'Brien Given a string of digits or an integer \$\endgroup\$ – AdmBorkBork Mar 28 '17 at 19:39
  • \$\begingroup\$ @AdmBorkBork Well, that answers the input question >_> \$\endgroup\$ – Conor O'Brien Mar 28 '17 at 19:40
  • \$\begingroup\$ @ConorO'Brien Also, construct a new integer or string, which sounds like returning a string is OK, too. \$\endgroup\$ – AdmBorkBork Mar 28 '17 at 19:41

15 Answers 15


k, 7 bytes


online repl

  $30043376111 / convert to string($)
  =$30043376111 / group(=) - return a mapping (dict) from unique chars to indices
"304761"!(0 4 5
 1 2
 8 9 10)
  +/'=$30043376111 / sum(+/) each(') value in the dict
"304761"!9 3 3 6 7 27
  <+/'=$30043376111 / grade(<) ascending values - return keys from the dict
  .<+/'=$30043376111 / execute(.) the string - convert it to a number

Juxtaposition of functions is composition, so no explicit parameter or input is required.


Haskell, 69 bytes

import Data.List
f x=0+read(nub$sortOn(\d->(sum$elemIndices d x,d))x)

Takes a string, returns a number. Usage example: f "30043376111" -> 47631. Try it online!

Pretty straight forward: sort the digits of the input string first on the sum of their indices and the by the digit itself (-> pairs of (sum ...,d)), remove duplicates and convert to a number to remove leading 0. The 0+ is needed to get the types right.


Stacked, 59 bytes

:@q uniq[:q\eq q size:>*sum,]map[-1#]sortby[0#]map''#`'^0'-

Try it online!

This takes a character string (like $'1231231') as input from the top of the stack, and leaves a string on the stack.


:@q uniq[:q\eq q size:>*sum,]map        stack: (str)
:                                       stack: (str str)
 @q                                     stack: (str)        ; store as `q`
    uniq                                stack: (str')       ; de-duplicate
        [                   ]map        map the inner over each element
         :                              stack: (chr chr)
          q\eq                          stack: (chr q')     ; `q'` is where equality occurs
               q size:>                 stack: (chr, q', k) ; `k` is range from 0, size(q')
                       *sum             stack: (chr, k')    ; `k'` is sum of indices
                           ,            stack: ((chr, k'))

Now we are left with pairs of (chr, sum of indices).

[   ]sortby                    sort by the inner function
 -                             vectorized subtraction of two pairs
  1#                           use the second element as the comparison
           [0#]map             get the first element of each row
                  ''#`         join by the empty string
                      '^0'-    remove all leading zeroes

05AB1E, 29 28 bytes

-1 thanks to Riley


Try it online!

TFN            }             # Loop from 0 to 9.
   ¹SQ                       # Push 1 if index is same as `y`.
      Dg<ÝsÏ                 # Push index of the number instead of 1.
            ON‚              # Sum, combine with current `y`.
                ){           # Collect, sort 'em.
                  vyD0å_i1è, # Only print the ones with a count above 0.
  • 1
    \$\begingroup\$ Can you substitute TFN for 9Ývy \$\endgroup\$ – Riley Mar 28 '17 at 20:05
  • 2
    \$\begingroup\$ @Riley 05AB1E is a weird language... It seems the longer you use it the more you attempt to over-complicate EVERYTHING... Thanks, yes, that does seem to work fine. \$\endgroup\$ – Magic Octopus Urn Mar 28 '17 at 20:13

JavaScript (ES6), 98 bytes

n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join``

Takes a string n, then converts it to a Set and then to an Array of distinct digits. Sorts these digits in numerical order, then sorts again according to sums of indices. Concatenates the sorted Array to a String, and finally converts to a Number to remove leading zeros.

n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join``


  • \$\begingroup\$ is the repeated sort necessary? \$\endgroup\$ – Conor O'Brien Mar 28 '17 at 20:38
  • \$\begingroup\$ Yes, "In the case that multiple digits yield the same sum, the smaller digit comes before the larger one". Without the first .sort(), an input of 1332 yields 132 instead of 123. \$\endgroup\$ – darrylyeo Mar 29 '17 at 0:24
  • \$\begingroup\$ Ah, okay, I see \$\endgroup\$ – Conor O'Brien Mar 29 '17 at 1:11

PowerShell, 88 bytes

$a=@{};[char[]]"$args"|%{$a[$_]+=$i++};+-join(($a.GetEnumerator()|Sort value,name).Name)

Try it online!

Sets an empty hashtable $a, then casts the input $args as a char array, and loops through each element |%{...}. We set the value at "the current element" of $a to be incremented by $i++, to count up our input's indices. For example, for input 300433766111, the first loop $a[3] gets +=0; the next loop, $a[0] gets +=1; etc.

Next, we need to Sort our hashtable. Unfortunately, due to an internal language quirk, this means we need to $a.GetEnumerator() before we can do the actual sorting. We sort by value, then by name, to satisfy the requirement of smaller digits get sorted first. We pull out the .Names thereof (in sorted order), -join them together into a string, and cast that string as an int + to remove leading zeros. That's left on the pipeline and output is implicit.


Jelly, 10 bytes


Try it online!

Takes and returns an integer.


Ġ’S$ÞịDFQḌ - Main link: n            e.g. 30043376111
Ġ          - group indices of n by value  [[2,3],[9,10,11],[1,5,6],[4],[8],[7]] (implicitly treats the number as a decimal list)
    Þ      - sort that by:
   $       -     last two links as a monad:
 ’         -         decrement (since Jelly is 1-indexed)
  S        -         sum                  [[2,3],[4],[7],[8],[1,5,6],[9,10,11]] (this leaves those indices of lower value to the left as required)
      D    - decimal list of n            [3,0,0,4,3,3,7,6,1,1,1]
     ị     - index into                   [[0,0],[4],[7],[6],[3,3,3],[1,1,1]]
       F   - flatten                      [0,0,4,7,6,3,3,3,1,1,1]
        Q  - unique                       [0,4,7,6,3,1]
         Ḍ - cast to a decimal number     47631

PHP, 103 Bytes

for(;$i<strlen($a="$argv[1]");)$r[$a[$i]]+=$i++;ksort($r);asort($r);echo ltrim(join(array_keys($r)),0);

Python 2, 102 92 bytes

Thanks to Ben Frankel for saving 10 bytes!

for i,j in enumerate(input()):a[j]=a.get(j,0)+i
print int(''.join(sorted(a,key=a.get)))

Try it Online!

Takes input as a string and outputs an integer. Uses a dictionary to store the sum of indexes, then sorts it by value. Converts to an integer to strip off leading zeroes because int is shorter than .lsplit('0').

  • \$\begingroup\$ a[j]=a.get(j,0)+i saves 10 bytes. \$\endgroup\$ – Ben Frankel Mar 29 '17 at 0:54

Python 3.5, 86 85 bytes

Thanks @Ben Frankel for saving a byte:

f=lambda s:int(''.join(sorted({*s},key=lambda d:sum(i*(c==d)for i,c in enumerate(s)))))

Old code:

lambda s:int(''.join(sorted({*s},key=lambda d:sum(i for i,c in enumerate(s)if c==d))))

Anonymous function taking a string of digits and returning an integer

  • \$\begingroup\$ sum(i*(c==d)for saves 1 byte. \$\endgroup\$ – Ben Frankel Mar 30 '17 at 1:56

Pip, 18 bytes


Takes the number as a command-line argument. Try it online!


                    a is 1st cmdline arg (implicit)
               UQa  Get unique digits in a
             SN     Sort (numerically)
           SK       Then sort with this key function:
      a@*_           Find all indices of argument in a
   $+(    )          and sum them
 J:                 Join the resulting list back into a string (: is used to lower the
                    precedence of J)
+                   Convert to number (eliminates leading 0)
                    Print (implicit)

C#, 245 bytes

using System.Linq;s=>{var a=new int[10];for(int i=0,l=0;i<10;i++){a[i]=-1;while((l=s.IndexOf(i+"",l+1))!=-1)a[i]+=l;}return string.Concat(a.Select((c,i)=>new{c,i}).OrderBy(o=>o.c).ThenBy(o=>o.i).Where(o=>o.c>-1).Select(o=>o.i)).TrimStart('0');};

Not happy with how long it ended up being and it can probably be shorter but this is what I ended up with.


Perl 6,  65 61  52 bytes

{+[~] {}.push(.comb.map:{$_=>$++}).sort({.value.sum,.key})».key}

Try it

{+[~] {}.push(.comb.antipairs).sort({.value.sum,.key})».key}

Try it

{+[~] .comb.antipairs.Bag.sort({.value,.key})».key}

Try it


{      # bare block lambda with implicit parameter 「$_」

  +    # turn the following into a Numeric
  [~]  # reduce the following using &infix:<~> (join)

    .comb              # list of digits from 「$_」 (implicit method call)
    .antipairs         # get a list of 「value => index」 pairs from above list
    .Bag               # combine them together (does the sum)
      { .value, .key } # sort it by the sum of indexes, then by the digit
    )».key             # get the list of digits from that

Scala, 123 104 bytes


Example (using Scala REPL):

scala> (_:String).zipWithIndex.groupBy(_._1).toSeq.sortBy(c=>c._2.map(_._2).sum->c._1).map(_._1).mkString.toInt
res0: String => Int = <function1>

scala> res0("30043376111")
res1: Int = 47631

Pretty straightforward, using tuple as sorting predicate for secondary sort.


Pyth, 9 bytes


Try it online

Takes a string of digits as input.

sosxNcQ1{Q    Implicit variable introduction
        {Q    Unique digits
 o            Order by
     cQ1      Chop input into list of individual characters.
   xN         Find all indexes of the digit in question in the list.
  s           Sum
s             Convert string to integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.