숫자 색인


15

숫자로 된 문자열이나 정수를 입력으로 받으면 인덱싱해야합니다.

입력을 수정하는 방법입니다. 우리는 30043376111예제로 사용할 것입니다 :

먼저, 각 숫자의 각 발생에 대한 인덱스의 합계를 찾으십시오.

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

그런 다음, 위의 숫자가 색인의 합계 순서로가는 새 정수 또는 문자열을 구성하십시오. 여러 자릿수가 동일한 합계를 생성하는 경우 작은 자릿수가 큰 숫자 앞에옵니다.

047631

마지막으로 선행 0을 제거하고 결과를 반환하거나 인쇄하십시오.

47631

인덱싱 된 입력을 반환하거나 인쇄하는 프로그램이나 함수를 작성해야합니다.

이것은 이므로 바이트 단위의 가장 짧은 코드가 이깁니다!

요청하면 더 많은 테스트 사례를 추가 할 수 있습니다.


함수의 경우 문자열을 반환해도 괜찮습니까? 문자열을 인수로 취하는 것은 어떻습니까?
코너 오브라이언

@ ConorO'Brien 숫자의 문자열 또는 정수가
주어짐

@AdmBorkBork 글쎄, 그것은 입력 질문에 대답합니다> _>
Conor O'Brien

@ ConorO'Brien 또한, 새로운 정수 나 string 을 구성하면 문자열 반환도 괜찮습니다.
AdmBorkBork

답변:


1

k, 7 바이트

.<+/'=$

온라인 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

함수의 병렬 배치는 구성이므로 명시적인 매개 변수 또는 입력이 필요하지 않습니다.


3

하스켈, 69 바이트

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

문자열을 받아서 숫자를 반환합니다. 사용 예 : f "30043376111"-> 47631. 온라인으로 사용해보십시오!

매우 간단합니다. 입력 문자열의 숫자를 먼저 색인의 합계와 숫자 자체 (-> 쌍 (-..., d))로 정렬하고 중복을 제거하고 숫자로 변환하여 Leading을 제거하십시오 0. 은 0+종류를 잘 얻을 필요합니다.


3

스택 , 59 바이트

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

온라인으로 사용해보십시오!

이것은 문자열을 취합니다 $'1231231'스택 맨 위에서 입력으로 )을 스택에 문자열을 남깁니다.

설명

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

이제 우리는 (chr, index of sumes) 쌍으로 남아 있습니다.

[-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

3

05AB1E , 29 28 바이트

라일리 덕분에 -1

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

온라인으로 사용해보십시오!

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
당신은 대체 할 수 있습니다 TFN에 대한9Ývy
라일리

2
@ Riley 05AB1E는 이상한 언어입니다 ... 더 오래 사용할수록 모든 것을 지나치게 복잡하게 만들려고합니다 ... 감사합니다, 그렇습니다.
Magic Octopus Urn

3

JavaScript (ES6), 98 바이트

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

string을 가져 n와서 Set으로 변환 한 다음 고유 숫자의 배열로 변환합니다. 이 자릿수를 숫자 순으로 정렬 한 다음 인덱스 합계에 따라 다시 정렬합니다. 정렬 된 배열을 문자열로 연결하고 마지막으로 0을 제거하기 위해 숫자로 변환합니다.

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'))


반복 정렬이 필요합니까?
코너 오브라이언

예, "여러 자릿수가 같은 합계를 산출하는 경우 작은 자릿수가 큰 숫자 앞에옵니다." 제없이 .sort()1,332 수율 132 대신 123의 입력
darrylyeo

아, 알 겠어요
Conor O'Brien

2

PowerShell , 88 바이트

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

온라인으로 사용해보십시오!

빈 해시 테이블을 설정 한 $a다음 입력 $argschar배열 로 캐스트하고 각 요소를 반복합니다 |%{...}. 입력의 인덱스를 카운트하기 위해 "현재 요소"의 값을 $a씩 증가하도록 설정합니다 $i++. 예를 들어 input 300433766111의 경우 첫 번째 루프 $a[3]+=0; 다음 루프$a[0]+=1; 기타

다음으로, Sort해시 테이블이 필요 합니다. 안타깝게도 내부 언어 문제로 인해 $a.GetEnumerator()실제 정렬을 수행하려면 먼저 해야 합니다. 더 작은 자릿수의 요구 사항을 충족시키기 위해을 기준으로 정렬 한 value다음을 name기준으로 정렬합니다. 우리는 .Name그것들을 (정렬 된 순서대로) 뽑아내어 -join문자열로 묶고 그 문자열을 정수로 캐스팅 +하여 선행 0을 제거합니다. 그것은 파이프 라인에 남아 있으며 출력은 암시 적입니다.


2

젤리 , 10 바이트

Ġ’S$ÞịDFQḌ

온라인으로 사용해보십시오!

정수를 가져와 반환합니다.

어떻게?

Ġ’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

1

PHP, 103 바이트

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

1

파이썬 2, 102 92 바이트

10 바이트를 절약 한 Ben Frankel에게 감사합니다!

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

온라인으로 사용해보십시오!

입력을 문자열로 받아서 정수를 출력합니다. 사전을 사용하여 인덱스의 합계를 저장 한 다음 값을 기준으로 정렬합니다. int보다 작기 때문에 선행 0을 제거하기 위해 정수로 변환합니다 .lsplit('0').


a[j]=a.get(j,0)+i10 바이트를 절약합니다.
벤 프랭클

1

파이썬 3.5, 86 85 바이트

바이트를 저장해 준 @Ben Frankel에게 감사드립니다.

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

오래된 코드 :

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

자릿수 문자열을 가져와 정수를 반환하는 익명 함수


sum(i*(c==d)for1 바이트를 저장합니다.
벤 프랭클

1

, 18 바이트

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

숫자를 명령 행 인수로 사용합니다. 온라인으로 사용해보십시오!

설명

                    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)

0

C #, 245 바이트

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');};

그것이 얼마나 오래 지속되었는지에 대해 만족하지 못하고 아마도 더 짧을 수도 있지만 이것이 내가 끝내는 것입니다.


0

펄 6 ,  65 61  52 바이트

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

시도 해봐

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

시도 해봐

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

시도 해봐

넓히는

{      # 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
}

0

스칼라, 123104 바이트

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

예 (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

튜플을 2 차 정렬을위한 정렬 술어로 사용하는 것은 매우 간단합니다.


0

Pyth, 9 바이트

sosxNcQ1{

온라인으로 사용해보십시오

문자열을 입력으로받습니다.

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.
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.