15
\$\begingroup\$

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:

047631

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

47631

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.

\$\endgroup\$
  • \$\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

1
\$\begingroup\$

k, 7 bytes

.<+/'=$

online repl

  $30043376111 / convert to string($)
"30043376111"
  =$30043376111 / group(=) - return a mapping (dict) from unique chars to indices
"304761"!(0 4 5
 1 2
 ,3
 ,6
 ,7
 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
"047631"
  .<+/'=$30043376111 / execute(.) the string - convert it to a number
47631

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

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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.

Explanation

:@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).

[-1#]sortby[0#]map''#`'^0'-
[   ]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
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 29 28 bytes

-1 thanks to Riley

TFN¹SQDg<ÝsÏON‚}){vyD0å_i1è,

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.
\$\endgroup\$
  • 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
3
\$\begingroup\$

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.

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

console.log(f('30043376111'))

\$\endgroup\$
  • \$\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
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Jelly, 10 bytes

Ġ’S$ÞịDFQḌ

Try it online!

Takes and returns an integer.

How?

Ġ’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
\$\endgroup\$
1
\$\begingroup\$

PHP, 103 Bytes

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

Python 2, 102 92 bytes

Thanks to Ben Frankel for saving 10 bytes!

a={}
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').

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

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

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

Pip, 18 bytes

+J:$+(a@*_)SKSNUQa

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

Explanation

                    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)
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

Expanded

{      # 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)
    .sort(
      { .value, .key } # sort it by the sum of indexes, then by the digit
    )».key             # get the list of digits from that
}
\$\endgroup\$
0
\$\begingroup\$

Scala, 123 104 bytes

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

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.

\$\endgroup\$
0
\$\begingroup\$

Pyth, 9 bytes

sosxNcQ1{

Try it online

Takes a string of digits as input.

sosxNcQ1{
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.
\$\endgroup\$

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.