내 친구들에게 그들이 어떤 "쉼표 클럽"인지 알려주세요


16

같은 실리콘 밸리의 "세 쉼표 클럽"장면에서 영감 이 하나 , 당신은 십명에게 어떤에 그들은 각각 속해있는 "쉼표 클럽"을 이야기 할 것이다이 도전에.

"쉼표 클럽"이라는 용어에 익숙하지 않다면 설명해 드리겠습니다. 보유하고있는 금액이 $ 1,000.00에서 $ 999,999.99 사이의 범위에있는 경우 귀하는 1- 쉼표 클럽에 있습니다. $ 1,000,000.00 ~ $ 999,999,999.99 범위에있는 경우 쉼표 클럽에 소속되어 있습니다. 이 "클럽"은 3 개 쉼표 클럽을 통해 반복됩니다. AFAIK는 1 조 달러 이상의 달러를 소유하고 있지 않기 때문입니다 (일본 엔은 매우 빠르게 다른 이야기가 될 것입니다). 따라서 미국과 영국에서 가장 일반적인 표기법 기준에 따라 은행 계좌에있는 쉼표 수는 귀하가 속한 쉼표 클럽을 나타냅니다. 음수에 동일한 "쉼표"규칙이 적용됩니다 (음수 쉼표 클럽에 포함하고 싶지는 않지만) : 포함 범위 [-0.01, -999의 음수 금액.

테스트 사례

Friend    Amount
John      100000
Jamie     0.05
Kylie     1549001.10
Laura     999999999.99
Russ      986000000
Karla     1
Reid      99.99
Mark      999.99
Manson    1000.01
Lonnie    999999999999.00
Nelly     -123.45

정답 :

John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.

friends배열과 amounts배열 을 얻는 데 필요한 배열 설정 은 점수에 포함되지 않습니다. 따라서 Python의 경우 다음 코드는 계산되지 않습니다.

f = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie']
a = ['100000', '0.05', '1549001.10', '999999999.99', '986000000', '1', '99.99', '999.99', '1000.01', '999999999999.00']

수정 : 수정 된 테스트 사례를 참조하십시오

쉼표를 세는 것과는 대조적으로 테스트 문자열에서 실제 문자열 쉼표를 제거하여 조금 더 어렵게 만들었습니다.


2
나는 당신이 출력 형식을 매우 명확하게 생각하지 않았다고 생각합니다. 같은 것입니다 "Name number,Name number,..."허용?
FryAmTheEggman

2
f의 참가작은 긍정적이거나 -$1,234.561- 쉼표 클럽에 속합니까?
Jonathan Allan

2
@not_a_robot Fry의 의견을 말씀해 주시겠습니까? 어떤 형식 으로든 이름과 숫자 쌍을 출력하는 것으로 충분합니까?
Martin Ender

1
@FryAmTheEggman 아니요, 출력 형식 "<name> is in the <number of commas>-club."
이어야

1
테스트 사례는 사양이 아닙니다. 그리고 그들이 그렇더라도 Jonathan Allan이 제기 한 큰 부정적인 문제에 대한 테스트 사례는 없습니다.
피터 테일러

답변:


10

자바 스크립트 (ES6), 80 바이트

a=>a.map(([s,n])=>s+` is in the ${n.toFixed(n<0?3:4).length/3-2|0}-comma club.`)

[friend, amount] 배열을 취해 "friend is the n-comma club"배열을 리턴합니다. 문자열. 길이가 0- 쉼표 클럽의 경우 6-8, 1- 쉼표 클럽의 경우 9-11, 2- 쉼표 클럽의 경우 12-15가되도록 추가 0을 추가하여 작동합니다.

https://jsfiddle.net/cau40vmk/1/


나는 이것이 음수에 대해서는 효과가 없다고 생각합니다. 예를 들어 Nelly (-123.45)를 1- 쉼표 클럽에 넣습니다. 나는 더 짧은 제안합니다 Math.log10(n*n)/6|0.
Arnauld

@ Arnauld Ah 네, |00으로 잊어 버렸습니다 . 그래서 Jamie에게 올바른 대답을합니다.
Neil

8

PostgreSQL, 61 바이트

SELECT f||' is in the '||div(log(@a),3)||'-comma club.'FROM p

@x의 절대 값은 x, log(x)베이스 (10) 및 대수 div(y, x)Y / X의 정수 몫을 산출한다.


설정:

CREATE TEMP TABLE p AS
SELECT * FROM (VALUES
    ('John', 100000),
    ('Jamie', 0.05),
    ('Kylie', 1549001.10),
    ('Laura', 999999999.99),
    ('Russ', 986000000),
    ('Karla', 1),
    ('Reid', 99.99),
    ('Mark', 999.99),
    ('Manson', 1000.01),
    ('Lonnie', 999999999999.00),
    ('Nelly', -123.45)
) AS p (f, a)

산출:

            ?column?            
--------------------------------
 John is in the 1-comma club.
 Jamie is in the 0-comma club.
 Kylie is in the 2-comma club.
 Laura is in the 2-comma club.
 Russ is in the 2-comma club.
 Karla is in the 0-comma club.
 Reid is in the 0-comma club.
 Mark is in the 0-comma club.
 Manson is in the 1-comma club.
 Lonnie is in the 3-comma club.
 Nelly is in the 0-comma club.
(11 rows)

경쟁력있는 SQL 응답을 보는 것이 좋습니다.
Toby Speight

6

젤리 , 34  32 바이트

AḞbȷL’⁶;“£ṙƬs⁾`¬ụṂ“¢<ỴȦ8£l»jµ€⁹żY

은행 잔고 목록을 숫자 (10 진수 / 정수)로, 이름 목록을 문자열로 사용하고 문자열 목록을 반환하는 2 진 링크 (함수).

온라인으로 사용해보십시오! -바닥 글은çY단순히 함수를 호출하고 결과 목록을 줄 바꿈과 결합하여 전체 프로그램으로 실행될 때 좋은 결과를 얻습니다.

어떻게?

AḞbȷL’⁶;“£ṙƬs⁾`¬ụṂ“¢<ỴȦ8£l»jµ€⁹żY - Main link: bankBalances, names
                             €    - for each bankBalance:
A                                 - absolute value (treat negatives and positives the same)
 Ḟ                                - floor (get rid of any pennies)
  bȷ                              - convert to base 1000
    L                             - length (number of digits in base 1000)
     ’                            - decrement by one
      ⁶;                          - concatenate a space with that   ...because -------.
        “         “       »       - compressed list of strings:                       ↓
         £ṙƬs⁾`¬ụṂ                -     " is in the"  ← cannot compress a trailing space :(
                   ¢<ỴȦ8£l        -     "-comma club."
                           j      - join that list of strings with the "number plus space"
                            µ     - monadic chain separation (call that result L)
                              ⁹   - right argument (names)
                               ż  - zip with L

4

PHP, 76 74 바이트

// data as associative array
$d=[Poorman=>-1234,John=>100000,Jamie=>0.05,Kylie=>1549001.10,Laura=>999999999.99,Russ=>1000000000,Karla=>1,Reid=>99.99,Mark=>999.99,Manson=>1000.01,Lonnie=>999999999999.00];
// code
foreach($d as$n=>$a)printf("$n is in the %d-comma club.
",log($a*$a,1e6));

다행히도 나는 int로 캐스팅 할 필요가 없습니다 (C에서 해야하는 것처럼). PHP는이를 위해 암시 적으로 수행합니다 %d.


사람! 내가 문자를 세는 대신 계산하는 첫 번째입니까?
Titus

4

매스 매 티카 (86 바이트)

설정 (이름은 문자열, 돈은 숫자) :

n = {"John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"};
m = {100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45}

시도 :

MapThread[#~~" is in the "~~ToString@Max[Floor@Log[10^3,#2],0]~~"-comma club."&,{n,m}]

Mathematica의 모든 문자열 함수에는 이름에 "String"이 포함되므로 로그가 더 짧습니다. 는 Max[...,0]사이 -1과 1 달러를 소유 한 사람들을위한 성가신 마이너스 번호 또는 음의 무한대를 처리하는 것입니다. 음수의 로그에는 가상의 물건이 포함되지만 Mathematica는 Floor!


4

apt , 36 바이트

이것은 첫 번째 입력으로 금액을 취하고 두 번째로 이름을 취합니다.

V+`   e {w0 x4 l /3-2|0}-¬mµ club

설명

V+`   e {w0 x4 l /3-2|0}-¬mµ club
V+                                   // Second input +
  `                                  // compressed string:
      e                              // " is in the " 
        {              }             // Insert here:
         w0                          //   The larger of 0 and the first input
            x4                       //   Rounded to the 4th decimal
               l                     //   Length
                        -¬mµ club    // "-comma club"
                                     // A closing backtick is auto-inserted at the end of the program

Japt는 문자열 압축을 위해 shoco 라이브러리 를 사용합니다 .

@Neil의 솔루션에서 영감을 얻었습니다 .

@ETHproductions 덕분에 7 바이트 절약

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


1
Vw0 x4 l /3-2|0중간 바이트에서 6 바이트를 절약 할 수 있다고 생각합니다. :-)
ETHproductions

1
나는 당신이 반대 순서로 입력을 받아 바이트를 절약 할 수 있다고 생각합니다.V+`...{w0...
ETHproductions

3

MATL, 50 48 43 바이트

`j' is in the 'i|kVn3/XkqV'-comma club'&hDT

MATL Online 에서 사용해보십시오

설명

`                   % Do...While loop
  j                 % Explicitly grab the next input as a string
  ' is in the the ' % Push this string literal to the stack
  i                 % Grab the next input as a number
  |                 % Compute the absolute value
  k                 % Round towards zero
  V                 % Convert to a string
  n3/Xk             % Divide the length of the string by 3 and round up
  q                 % Subtract one
  V                 % Convert to a string
  '-comma club'     % Push this string literal to the stack
  &h                % Horizontally concatenate the entire stack
  D                 % Display the resulting string
  T                 % Push TRUE to the stack, causing an infinite loop which automatically
                    % terminates when we run out of inputs
                    % Implicit end of do...while loop

3

R, 68 바이트

설정:

f <- c('John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie', 'Nelly')
a <- c(100000, 0.05, 1549001.10, 999999999.99, 986000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45)

해결책:

cat(paste0(f, " is in the ",floor(log10(abs(a))/3)),"-comma club.\n"))

계정의 절대 값의 밑이 10 인 로그를 가져와 내림 한 다음 이름으로 인쇄하십시오.

a문자형 벡터라면 더 작을 수 있는지 확실하지 않습니다 ...


1
-123.45 달러를 가진 Nelly의 경우는 어떻습니까? 그 log10전화는 NaN음수에 대해 s를 생성 합니다. log10(abs(a))작동하는 것 같습니다 .
blacksite

위의 샘플에는 Nelly가 포함되어 있지 않습니다. 그리고 나는 사양을 잘못 읽었습니다 ... 음수 값은 0 쉼표 클럽이어야한다는 것을 이해했습니다.
Joe

대신 - abs(x)사용 pmax(a,1)-1보다 작은 것을 취하고 1로 설정하여 음수에 좋은 결과를 제공합니다. 그리고 대신에을 floor(log10(...)/3)사용할 수 있습니다 log10(...)%/%3. 나는 그것을 66 바이트로 낮추고 (음수에 맞도록) 생각합니다.
Gregor Thomas

1
또한 가치의 전체 7 바이트가 있음을 지적 cat()\n콘솔에 거기에 문자열 벡터를 인쇄이 ... 수있는 충분한 (파이썬 답변처럼 * 에헴 *)로 간주 될 수있다.
Gregor Thomas

이것은 3 다음에 추가 괄호가 있습니다. 또한 Jamie의 -1 클럽을 출력합니다. pmax (a, 1)을 사용하면 문제가 해결됩니다.
BLT

3

자바 스크립트, 59 바이트

@ETHproductions 덕분에 3 바이트 절약

@Cyoce 덕분에 2 바이트 절약

n=>m=>n+` is in the ${m>1?Math.log10(m)/3|0:0}-comma club.`

데모


1
바이트를 저장하면 대신에 `${}`함수를 카레 할 수 있습니다.n=>m=>...(n,m)=>...
Cyoce

2

Vim, 72 바이트

:%s;\v +\-=(\d+).*;\=' is in the '.(len(submatch(1))-1)/3.' comma club'

어떻게 든 후회 수익이 있음을 보여 주어야하지만 어떻게 해야할지 확실하지 않습니다. 이것은 기본적인 정규식 답변이며 모든 정규식 언어로 이길 수 있다고 확신합니다. V를 사용했지만 V의 대체 명령은 /기본적으로 구분 기호로 사용 되며 나누기에 대해 불평하지 않는 방법을 알 수 없었습니다.

입력을 OP의 테이블로 가져 와서 값을 테이블로 리턴하지만 재무 정보가 "is in the X comma club"로 바뀝니다.

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


나는 \-=아무것도 추가 하지 않는다고 생각합니다 . 또한 입력에서 여분의 공백을 제거하고 정규식을 변경 \v (\d*).*;하면 4 바이트를 절약 할 수 있습니다
James

2

05AB1E , 32 바이트

Äï€g3/î<“-comma†Ú“«“€ˆ€†€€ “ì‚ø»

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

설명

Ä                                 # absolute value of input
 ï                                # convert to int
  €g                              # length of each
    3/                            # divided by 3
      î                           # round up
       <                          # decrement
        “-comma†Ú“«               # append string "-comma club" to each number
                   “€ˆ€†€€ “ì     # prepend string "is in the " to each number
                             ‚    # pair with second input
                              ø   # zip
                               »  # join by spaces and newlines

2

파이썬 2, 69 바이트

배열을 설정하십시오 :

n = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie']
a = [100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00]

그리고 우리의 기능은 다음과 같습니다.

f=lambda n,a:'%s is in %s comma club'%(n,min(3,(len(str(int(a)))/3)))

우리에게주는 :

>>> [f(x,y) for x,y in zip(n,a)]
['John is in 2 comma club', 'Jamie is in 0 comma club', 'Kylie is in 2 comma club', 'Laura is in 3 comma club', 'Russ is in 3 comma club', 'Karla is in 0 comma club', 'Reid is in 0 comma club', 'Mark is in 1 comma club', 'Manson is in 1 comma club', 'Lonnie is in 3 comma club']

배열이 질문에 제공된 배열과 동일 해야하는 경우 솔루션 비용은 76 바이트입니다.

f=lambda n,a:'%s is in %s comma club'%(n,min(3,(len(str(int(float(a))))/3)))

2

파워 쉘, 82 바이트

$args[0]|%{$_[0]+" is in the "+(('{0:N}'-f$_[1]-split',').Count-1)+"-comma club."}

의 2D 배열 입력 가정

cc.ps1 @(@("John",100000),@("Jamie",0.05),@("Kylie",1549001.10),@("Laura",999999999.99),@("Russ",986000000),@("Karla",1),@("Reid",99.99),@("Mark",999.99),@("Manson",1000.01),@("Lonnie",999999999999.00),@("Nelly",-123.45))

출력은 John is in the 1-comma club. Jamie is in the 0-comma club. Kylie is in the 2-comma club. Laura is in the 2-comma club. Russ is in the 2-comma club. Karla is in the 0-comma club. Reid is in the 0-comma club. Mark is in the 0-comma club. Manson is in the 1-comma club. Lonnie is in the 3-comma club. Nelly is in the 0-comma club.


2

하스켈, 71 바이트

n#a=n++" is in the "++(show.truncate.logBase 1e3.abs$a)++"-comma club."

정답을 제공하는 연산자 '#'을 정의합니다. 예 :

*Main> "John"#100000
"John is in the 1-comma club."

불행히도, Haskell은 log10다른 많은 언어들과 같이 간결한 기능을 가지고 있지 않지만 유용한 logBase기능을 가지고 있기 때문에 답을 3으로 나눌 필요가 없습니다. 불행히도 logBase 1000 0.05음수이므로 음수를 사용해야합니다. 반올림 truncate하기보다 길다 floor.

테스트 케이스를 포함한 전체 프로그램 :

(#) :: (RealFrac n, Floating n) => [Char] -> n -> [Char]
n#a=n++" is in the "++(show.truncate.logBase 1e3.abs$a)++"-comma club."

testCases = [
 ("John",      100000),
 ("Jamie",     0.05),
 ("Kylie",     1549001.10),
 ("Laura",     999999999.99),
 ("Russ",      986000000),
 ("Karla",     1),
 ("Reid",      99.99),
 ("Mark",      999.99),
 ("Manson",    1000.01),
 ("Lonnie",    999999999999.00),
 ("Nelly",     -123.45)]

main = putStrLn $ unlines $ map (uncurry (#)) testCases

다음과 같은 결과를 제공합니다.

John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.

1

K, 66 바이트

    /n is names and a is amounts
    n
    ("John";"Jamie";"Kylie";"Laura";"Russ";"Karla";"Reid";"Mark";"Manson";"Lonnie")
    a
    ("100000";"0.05";"1549001.10";"999999999.99";"1000000000";,"1";"99.99";"999.99";"1000.01";"999999999999.00")
    /the function
    {x," is in the ",($(#.q.cut[3;*"."\:y])-1)," comma club"}./:+(n;a)
    /output
    ("John is in the 1 comma club";"Jamie is in the 0 comma club";"Kylie is in the 2 comma club";"Laura is in the 2 comma club";"Russ is in the 3 comma club";"Karla is in the 0 comma club";"Reid is in the 0 comma club";"Mark is in the 0 comma club";"Manson is in the 1 comma club";"Lonnie is in the 3 comma club")


1

C #, 125 바이트

(p,n)=>{for(int x=0;x<p.Length;x++)Console.Write(p[x]+" is in the "+(n[x]<1e3?0:n[x]<1e6?1:n[x]<1e9?2:3)+"-comma club.\n");};

결과를 OP 형식으로 인쇄하는 익명 함수.

테스트 케이스가 포함 된 전체 프로그램 :

using System;

class CommaClub
{
    static void Main()
    {
        Action<string[], double[]> f =
        (p,n)=>{for(int x=0;x<p.Length;x++)Console.Write(p[x]+" is in the "+(n[x]<1e3?0:n[x]<1e6?1:n[x]<1e9?2:3)+"-comma club.\n");};

        // test cases:
        string[] personArr = new[] {"John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"};
        double[] amountArr = new[] {100000, 0.05, 1549001.10, 999999999.99, 1000000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45};
        f(personArr, amountArr);
    }
}

1

파이썬 3 ( 207 (159) 110 95 86 바이트 @iwaseatenbyagrue 덕분)

약간의 설정 :

f = ['John', 'Jamie', 'Kylie', 'Laura', 'Russ', 'Karla', 'Reid', 'Mark', 'Manson', 'Lonnie', 'Nelly']
a = [100000, 0.05, 1549001.10, 999999999.99, 986000000, 1, 99.99, 999.99, 1000.01, 999999999999.00, -123.45]

내 시도 :

['%s is in the %d-comma club.'%(p,-(-len(str(int(abs(v))))//3)-1) for p,v in zip(f,a)]

결과 :

['John is in the 1-comma club.', 'Jamie is in the 0-comma club.', 'Kylie is in the 2-comma club.', 'Laura is in the 2-comma club.', 'Russ is in the 2-comma club.', 'Karla is in the 0-comma club.', 'Reid is in the 0-comma club.', 'Mark is in the 0-comma club.', 'Manson is in the 1-comma club.', 'Lonnie is in the 3-comma club.', 'Nelly is in the 0-comma club.']

편집 : 모든 것을 절대 값으로 변환하면 15 바이트가 절약되었습니다.


1
가장 중요한 것은 코드 스 니펫이며 일반적으로 함수 또는 전체 프로그램 만 허용합니다. 골프는 많은 공간을 제거 할 수 있습니다. 시도 : ["%s is in the %d-comma club."%(p,v.count(','))for p,v in zip(f,a)]또한 바이트 수를 포함해야합니다.
Conor O'Brien

print'\n'.join([your array])실제로 출력 할 수 있습니다 .
Elronnd

2
사이트에 오신 것을 환영합니다! 제외 어 (예 :) -123.45는 1 개씩입니다 (를 계산 한 이후 -). 그러나 숫자 목록을 가져 와서 저장하지 않는 이유는 무엇입니까? import 문을 추가해야하며, 이것이 의미하는 바에 따르면 이것은 프로그램이나 함수가 아닌 스 니펫입니다 (기본값은 그럴만 한 이유가 없으면 권장하지 않습니다).
Jonathan Allan

1
감사합니다, @JonathanAllan. 나는 현재 이것을 개선하려고 노력하고 있으므로 수입을 세지 않아도됩니다. 파이썬의 math.ceil함수가 내 점수에 약간의 오버 헤드를 추가 할 수 있음을 알고 있습니다.
blacksite

2
당신은 대체하여 9 바이트를 저장할 수 있습니다 (-len(str(abs(v)).split('.')[0])len(str(int(float(v)))). 테스트 세트에는 음수가 없습니다 (예제에는 음수가 없음). completist가되고 싶다면 5 바이트를 사용 len(str(abs(int(float(v)))))하면 4 바이트 만 절약됩니다.
iwaseatenbyagrue

1

Perl 6, 107 95 바이트

for @f {printf "%s is in the %d-comma club.\n",@f[$++],(abs(@a[$++].split(".")[0]).chars-1)/3;}

내 자랑스러운 일이 아니라 골프 기술을 잊어 버린 경우 머리를 숙여주십시오. 편집 : @Ven 덕분에 -12 바이트


왜 주위에 parens ^@f.elems? BTW 당신은 필요하지 않습니다 .elems, for ^@f작품. 의 이름을 지정할 필요가 없습니다 . 대신 $x사용 하십시오 $_. printf를 사용하지 마십시오 "{"interpolation"}".
Ven

나는 왜 당신이 그것을 필요로하는지 이해하지 못합니다. 왜 가지 for @f않습니까? $++색인으로 사용 하여 색인을 만들 수 있습니다 (및 색인으로 @a).
Ven

PC에서 메신저로 즉시 편집 :)
Håvard Nygård

1
@ $ ++에 대해 감사합니다. "실제"프로그램에서 많은 문제를 해결합니다. 방금 Perl 6를 선택했습니다.
Håvard Nygård 17

보간이 바이트를 저장하지 않습니까?
Ven

1

파이썬 2, 87 바이트

for n,a in input():print n+' is in the %dd-comma club.'%'{:20,.2f}'.format(a).count(',')

약간 오래된 (90 바이트) :

for n,a in input():print n+' is in the '+`'{:20,.2f}'.format(a).count(',')`+'-comma club.'

튜플 목록 (이름, 양)으로 입력을받습니다.

학교에서 휴대 전화로이 작업을 수행하고 있으므로 나중에 테스트하겠습니다.


1

dc, 56 54 바이트

[P[ is in the ]Pd*vdZrX-1-3/n[-comma club.]pstz0<g]sglgx

스택에서 입력을 받으면 스택 상단에 이름, 첫 번째 숫자, 두 번째 이름, 두 번째 숫자 등이 사전로드되어야합니다.

다음은 스택을로드하고 매크로 g를 실행하는 예입니다.

#!/usr/bin/dc
_123.45         [Nelly]
999999999999.00 [Lonnie]
1000.01         [Manson]
999.99          [Mark]
99.99           [Reid]
1               [Karla]
986000000       [Russ]
999999999.99    [Laura]
1549001.10      [Kylie]
0.05            [Jamie]
100000          [John]
[P[ is in the ]Pd*v1/Z1-3/n[-comma club.]pstz0<g]sglgx

일반적인 출력을 생성합니다.

John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.

코드는 다음과 같습니다.

[P[ is in the ]Pd*v1/Z-1-3/n[-comma club.]pstz0<g]sglgx

[                    # begin macro string
P                    # print and pop person name
[ is in the ]P       # print and pop ' is in the '
# Get absolute value of number by squaring and square root
d*v                  # d=dup, *=multiply, v=root
1/                   # 1/ truncates to integer since scale is 0
Z                    # Z=number length
1-3/n                # n=print and pop (#digits - 1)//3
[-comma club.]p      # print '-comma club.' and newline
st                   # pop '-comma club.' off stack into register t
z0<g                 # Do macro g if 0 is less than z=stack height
]                    # end macro string
sg                   # Save macro g
lgx                  # Load g and do its initial execution

편집 1에서 dZrX-(d = dup, Z = number length, r = swap, X = fraction,-= 빼기)를 1/Z(숫자를 1로 나누기, 기본 스케일이 0 인 정수로 잘림 , Z = 숫자 로 바 replaced ) 길이), 2 바이트 절약.


1

스위프트 , 166 (158) 145 바이트

var c="comma club",i=0
f.map{k,v in var a=abs(v);print(k,(1000..<1000000~=a ?1:1000000..<1000000000~=a ?2:1000000000..<1000000000000~=a ?3:0),c)}

그리고 여기 사전이 있습니다 :

var f = [
    "John": 100000, "Jamie": 0.05, "Kylie" : 1549001.10,
    "Laura": 999999999.99,"Russ":1000000000,"Karla": 1,
    "Reid": 99.99,"Mark": 999.99, "Manson": 1000.01,
    "Lonnie": 999999999999.00, "Nelly": -123.45
]

여기 사용해보십시오!


0

클로저, 108 바이트

(def f ["John", "Jamie", "Kylie", "Laura", "Russ", "Karla", "Reid", "Mark", "Manson", "Lonnie", "Nelly"])
(def a ["100000", "0.05", "1549001.10", "999999999.99", "986000000", "1", "99.99", "999.99", "1000.01", "999999999999.00", "-123.45"])

(map #(str %" is in the "(quot(-(count(nth(partition-by #{\.}(drop-while #{\-}%2))0))1)3)"-comma club.")f a)

플로트에서 작동하는 것이 문자 시퀀스보다 짧을 지 확실하지 않습니다. 함수가 아닌 답변이 올바른지 확실하지 않아 일련의 답변을 반환합니다.


0

리볼, 118 바이트

d: charset"0123456789"forskip s 2[c: 0 parse s/2[opt"-"any[3 d and d(++ c)]]print[s/1"is in the"join c"-comma club."]]

배열 선언을 사용하여 ungolfed :

s: [
    {John} {100000}
    {Jamie} {0.05}
    {Kylie} {1549001.10}
    {Laura} {999999999.99}
    {Russ} {986000000}
    {Karla} {1}
    {Reid} {99.99}
    {Mark} {999.99}
    {Manson} {1000.01}
    {Lonnie} {999999999999.00}
    {Nelly} {-123.45}
    {Baz} {1.12345678}     ;; added extra Baz test case
]

d: charset "0123456789"
forskip s 2 [
    c: 0
    parse s/2 [
        opt "-"
        any [3 d and d (++ c)]
    ]
    print [s/1 "is in the" join c "-comma club."]
]

산출:

John is in the 1-comma club.
Jamie is in the 0-comma club.
Kylie is in the 2-comma club.
Laura is in the 2-comma club.
Russ is in the 2-comma club.
Karla is in the 0-comma club.
Reid is in the 0-comma club.
Mark is in the 0-comma club.
Manson is in the 1-comma club.
Lonnie is in the 3-comma club.
Nelly is in the 0-comma club.
Baz is in the 0-comma club.

0

자바 8 154 141 바이트

m.keySet().stream().map(k->k+" is in the "+(((""+Math.abs(m.get(k).longValue()))).length()-1)/3+"-comma club.").forEach(System.out::println);

언 골프

public static void main(String[] args) {
    Map<String, Number> m = new LinkedHashMap<String, Number>(){{
        put("John", 100000);
        put("Jamie", 0.05);
        put("Kylie", 1549001.10);
        put("Laura", 999999999.99);
        put("Russ", 1000000000);
        put("Karla", 1);
        put("Reid", 99.99);
        put("Mark", 999.99);
        put("Manson", 1000.01);
        put("Lonnie", 999999999999.00);
        put("Nelly", -123.45);
    }};
    m.keySet().stream().map(k->k+" is in the "+(((""+Math.abs(m.get(k).longValue()))).length()-1)/3+"-comma club.").forEach(System.out::println);
}

1
를 제거하고 대신 String.valueOf사용할 수 있습니다 (((""+Math.abs(m.get(k).longValue())).length()-1)/3).
케빈 크루이 센

1
또한 괄호를 제거 할 수도 있습니다 k->.
Kevin Cruijssen
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.