Sayıları pi'deki ilk oluşumlarına göre sıralayın


17

Negatif olmayan bir sayı verildiğinde n, rakamları pi'dekin ilk oluşumlarına göre sıralayın .

Girdi, işlev cli argümanı veya STDIN aracılığıyla ve bir dize, char [] veya tamsayı olarak alınabilir. Dönüş değeri, çıkış durumu veya STDOUT ile çıkış yapabilirsiniz.



Girdi ve çıktıları dize veya rakam dizisi olarak alabilir miyiz?
ETHproductions

@ETHproductions Netleştirildi.
Roman Gräf

19
Birkaç test durumu iyi olurdu.
Dennis

1
Şimdi, hepsi aynı şeyi yapan 12 cevap mevcut olduğuna göre, ne sorulduğundan hala emin değilseniz, o zaman sorunun sorunu değildir.
Leaky Nun

Yanıtlar:


14

Pyth, 8 6 bayt

ox+.n0

Burada deneyin.

Leaky Nun sayesinde -1 : Girdi 0hiç gerekliyse sağlayacaktır . Jakube
sayesinde önemsiz -1 : Backtick gerekli değil (ah, bunu nasıl özledim, NASIL?!?).


Woohoo, bu bile 05AB1E'yi geçiyor! Düzenleme: 05AB1E yendi ve çalmak istemiyorum :(
Outgolfer Erik

3
Buldum. 0Sonunda buna ihtiyacınız yok . Girişi varsa 0, 0girdi tarafından sağlanacak; girişte a yoksa 0, önemli olmayacaktır.
Leaky Nun

3
@LeakyNun ve hatta backtick kaydedebilirsiniz:ox+.n0
Jakube

Tamam, ilk yorumu dikkate almayın, LeakyNun ve Jakube sayesinde tekrar 05AB1E'yi yendim, umarım bu sefer iyi olur.
Outgolfer Erik

1
Bu çok güzel bir örtük girdi.
isaacg


18

05AB1E , 10 9 7 bayt

Yinelenenleri filtrelemenin gereksiz olduğunu belirten Leaky Nun sayesinde 1 bayt kaydedildi . Adnan
sayesinde 2 bayt tasarruf etti .

žqRvy†J

Çevrimiçi deneyin!

açıklama

žq       # push pi to 15 decimals (contains all digits but 0)
  R      # reverse
   vy    # for each char in pi
     †J  # move it's occurrences in the input to the front

13žsRvy†J9 bayt için
Leaky Nun

@LeakyNun: Oh evet, kopyalar önemli değil. Teşekkürler :)
Emigna

3
žqBunun yerine kullanabilir misin 13žs?
Adnan

@Adnan Çalışmıyor gibi görünüyor.
Erik the Outgolfer

2
@Adnan: Evet, elbette. Başka bir pi sabiti olduğunu fark etmedim :)
Emigna

8

Jöle , 10 bayt

“ṀSṪw’ṾiµÞ

Çevrimiçi deneyin!

Girişi bir basamak dizesi olarak alır.

@ETHproductions sayesinde -3 bayt

açıklama

“ṀSṪw’ṾiµÞ
        µ  - Separate chain into function “ṀSṪw’Ṿi and sort atom Þ.
         Þ - Sort the input by
       i   - Each digit's index in: 
“ṀSṪw’     - the literal 3145926870 ...
      Ṿ    - transformed into the list 3,1,4,5,9,2,6,8,7,0

Ben 31459268704 basamaklı bir taban 250 dize olarak temsil edilebilir düşünüyorum (10 yerine 6 bayt alır anlamına gelir), ama nasıl böyle sıkıştırmak için emin değilim.
ETHproductions

Jelly'in pi için bir yerleşimi yok mu?
matematik bağımlısı

@mathjunkie ama Jelly dizi manipülasyonunda çok verimli değil
Leaky Nun

@mathjunkie Evet, ancak listedeki manipülasyonlar çok fazla bayt alıyor
fireflame241

“ṀSṪw’verecek 3145926870.
Leaky Nun

8

Japt , 10 9 bayt

8 bayt kod, -Pbayrak için +1 .

–!bMP+U

Çevrimiçi deneyin! Girişi dize olarak alır.

açıklama

–!bMP+'0  // Implicit input

¬          // Split the input into chars.
 ñ         // Sort each char in the resulting list by
  !b       //   its index in
    MP+U   //     Math.PI + the input.
-P         // Join the result back into a single string.
           // Implicit: output result of last expression

7

JavaScript (ES6), 54 bytes

f=
s=>[...s].sort((a,b)=>k[a]-k[b],k=`9150236874`).join``
<input oninput=o.textContent=f(this.value)><pre id=o>

Uses strings for I/O.


7

Jelly,  8  7 bytes

-1 byte thanks to Dennis (use any existing 0 in the input, clever.)

ØP;ṾiµÞ

Try it online!

How?

ØP;ṾiµÞ - Main link: string s (char list)
     µÞ - sort the characters, c, of s by:
    i   -   first index of c in:
ØP      -     pi yield: 3.141592653589793
  ;     -     concatenate with left: [3.141592653589793, c]
   Ṿ    -     un-evaluate: "3.141592653589793,c" (a char list with the digit character c)
                                if any c is 0 ^ it will then be to the right of all others

...and there I was searching for squares - 3820009 (sqrt of 14592468760081) is still 3 digits in base 250.
Jonathan Allan

The in your explanation is misplaced.
Erik the Outgolfer

@EriktheOutgolfer - thanks, adjusted.
Jonathan Allan

6

CJam, 15 12 10 8 bytes

r{P`#c}$

Try it online!

-3: Use a string based on the P pi variable instead of a literal.
-2: Decided I don't need to uniquify at all, since finding an index takes the first occurrence anyways. -2: Thanks to jimmy23013 for an interesting approach using x mod 65536.

Explanation:

r{P`#c}$ e# Takes an input token
r        e# Take the integer as a string
 {P`#c}  e# Sorting key:
  P      e#  Push P (defaults to 3.141592653589793)
   `     e#  Convert to string representation
    #    e#  Find char's index in the string we made
         e#  A '.' will never be found in an integer, but it doesn't matter, since the shifting preserves ideal sorting.
         e#  A '0' will be indexed as -1.
     c   e#  Convert index to char
         e#  This first calculates index % 65536, and then converts to char. We need this because otherwise 0 would be indexed as -1, i.e. smallest index.
         e#  We don't need to convert back to integer, since we can use lexicographical sorting.
       $ e# Sort with key


1
Yay, beats MATL :)
Erik the Outgolfer


@jimmy23013 Wow that's clever. It's almost like there's a builtin for int(x)%65536, and ci would even convert back to integer.
Erik the Outgolfer

5

PHP, 71 Bytes

The regex solution is shorter

for(;~$c=_3145926870[$i++];)echo str_repeat($c,substr_count($argn,$c));

or

for(;~$c=_3145926870[$i++];)echo str_pad("",substr_count($argn,$c),$c);

Online Versions

PHP, 78 Bytes

for(;~$c=$argn[$i++];)$j[strpos("3145926870",$c)].=$c;ksort($j);echo join($j);

PHP, 112 Bytes

$a=str_split($argn);usort($a,function($x,$y){return strpos($d="3145926870",$x)<=>strpos($d,$y);});echo join($a);

Online Version


I've added a 69 byte solution. Maybe we can get it down to 66 byte together ;)
Christoph

5

C, 103 97 bytes

char*p="3145926870";s(*a,*b){return strchr(p,*a)-strchr(p,*b);}f(char*t){qsort(t,strlen(t),1,s);}

Try it online


Thanks, @ceilingcat, MSVC does not like this at all, I suppose I should rather prototype with gcc :-)
Johan du Toit

MSVC probably won't like the fact that gcc lets you ditch char in char*p and char*t
ceilingcat


3

MATL, 14 bytes

YP99Y$uj!y=sY"

Try it online!

Explanation with an example

The symbol ; is used as row separator in matrices. So [1 2 3] is a row vector, [1; 2; 3] is a column vector, and [1 2; 3 4] is a square matrix. The latter can also be represented, for clarity, as

[1 2;
 3 4]

Consider input 2325 as an example.

YP     % Push approximation of pi as a double (predefined literal)
       % 3.14159265358979
99Y$   % Variable-precision arithmetic with 99 digits. Gives a string.
       % The input 3.14159265358979 is recognized as representing pi
       % STACK: '3.141592653589793238462 ··· 707'
u      % Unique entries, keeping order of their first appearance
       % STACK: '3.145926870'
j      % Input line as a string
       % STACK: '3.145926870', '2352'
!      % Transpose
       % STACK: '3.145926870', ['2'; '3';'5'; '2']
y      % Duplicate the second-top element in the stack
       % STACK: '3.145926870', ['2'; '3';'5'; '2'], '3.145926870'
=      % Test for equality, with broadcast. This gives a matrix with
       % all pairwise comparisons)
       % STACK: '3.145926870', [0 0 0 0 0 0 1 0 0 0 0;
       %                        1 0 0 0 0 0 0 0 0 0 0;
       %                        0 0 0 0 1 0 0 0 0 0 0;
       %                        0 0 0 0 0 0 1 0 0 0 0]
s      % Sum of each column
       % STACK: '3.145926870', [1 0 0 0 1 0 2 0 0 0 0]
Y"     % Run-length decoding. Implicitly display
       % STACK: '3522'


2

C# Interactive, 37 36 Bytes

i.OrderBy(c=>"145926870".IndexOf(c))

Actually you have to execute this in the C# interactive for proper results, but I guess this is what you meant with exit status. The variable i actually is the input variable (it can be for example a string), so it's basically the method parameter.

I think the code itself is pretty straight forward.


Where's the 3?
Paul

1
@Paul it's not neccessary, as it returns -1 if the element isn't found.
MetaColon

This is just a snippet of code though, I'm pretty sure even in interactive you have to specify why i is somewhere so it can be taken as input. Also if you're saying C# you have to include using System.Linq; into the byte count. However, if this is Interactive you should specify the language as C# Interactive not solely C#.
TheLethalCoder

@TheLethalCoder I updated it to C# Interactive. The using isn't neccesaary in the interactive, as it's included automatically.
MetaColon

2

05AB1E, 5 6 bytes (noncompeting)

Had to realise that 0 is not present in the standard length pi constant.

Σтžsyk

Try it online!

Σтžsyk
Σ      Sort by the result of code
 тžs   Push 100 digits of pi
   yk  Index of digit in pi

You should mark this non-competing as Σ is newer than the challenge.
Emigna

@Emigna marked it, thanks. But after the required fix it's not anymore shorter than the winning answer anyway ):
kalsowerus

Too bad you needed that zero for this method. It should be optimal for this language at least. Can't ask for more than that :)
Emigna

2

PHP, 66 65 bytes

Saved 1 byte thanks to Titus.

while(~$d=_3145926870[++$i])echo preg_filter("/[^$d]/",'',$argn);

1

Java 7, 110 bytes

String c(String s){String r="";for(char i:"3145926870".toCharArray())r+=s.replaceAll("[^"+i+"]","");return r;}

Explanation:

String c(String s){                       // Method with String parameter and String return-type
  String r="";                            //  Result String
  for(char i:"3145926870".toCharArray())  //  Loop over the characters of "3145926870"
    r+=s.replaceAll("[^"+i+"]","");       //   Append the result-String with all the occurrences of the current character
                                          //  End of loop (implicit / single-line body)
  return r;                               //  Return the result-String
}                                         // End of method

Test code:

Try it here.

class M{
  static String c(String s){String r="";for(char i:"3145926870".toCharArray())r+=s.replaceAll("[^"+i+"]","");return r;}

  public static void main(String[] a){
    System.out.println(c("12345678908395817288391"));
  }
}

Output:

33311145599922688888770

1

Clojure, 38 bytes

#(sort-by(zipmap"3145926870"(range))%)

Input in string, returns a sequence of characters. zipmap creates a "dictionary" object, which can be used in a function context as well.

(f "1234")
(\3 \1 \4 \2)

If input digits were guaranteed to be unique then you could simply do #(filter(set %)"3145926870").


1

PHP, 69 68

for(;(~$d=$argn[$j++])||~$c=_3145926870[$i+++$j=0];)$c==$d&&print$d;

Still beaten by preg_filter but I thought it was quite nice itself. Maybe someone can golf off some bytes.


$c!=$d?:print$d as alternative for $c==$d&&print$d I only see in the moment
Jörg Hülsermann

1
_3145926870 instead of `"3145926870" save 1 Byte
Jörg Hülsermann

for(;(~$d=$argn[$j++])?:~$c=_3145926870[++$i+$j=0];$c!=$d?:print$d); is also a working alternative
Jörg Hülsermann

0

Perl 6, 34 bytes

*.comb.sort:{3145926870.index: $_}

Try it

*\       # WhateverCode lambda (this is the parameter)
.comb    # split into digits
.sort: { # sort by

  3145926870.index: $_ # its index in this number
}

0

k, 19 bytes

{x@<"3145926870"?x}

Explanation:

{                 } /function(x)
    "3145926870"?x  /for each x: "3145926870".index(x)
   <                /get indices with which to sort
 x@                 /sort x by those indices
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.