숫자를 0으로 나누기


16

우리는 인생의 어느 시점에서 0으로 나누는 것이 불가능하다는 말을 들었습니다. 그리고 대부분의 경우, 그 진술은 사실입니다. 그러나 금지 된 작업을 수행 할 수있는 방법 있다면 어떨까요? 내 최신 작품에 오신 것을 환영합니다 : b-numbers.

b-숫자는 상상의 숫자와 조금 비슷합니다 : 관련된 주 계수는 수학적으로 불가능하지 않은 표현을 i나타냅니다 ( √를 나타냄)1 ). 이 경우b는 식 1 을 나타냅니다.10 . 여기에서x가무엇인지 쉽게 판단 할 수 있습니다.x0 은 다음과 같습니다.

x0=x110=xb

작업

0으로 나누는식이 주어지면 b 단순화 된 값을 출력합니다 . 입력은 n/0n이 임의의 유리수이거나 b10 진수 형식의-숫자 형식입니다. 선행 0과 후행 0은 포함되지 않습니다.

입력 예

4/0
1/0
0/0
80/0
-8/0
1.5/0
2.03/0
-1/0
-3.14/0
b/0
3b/0
-b/0
121/0

출력 예

4b
b
0
80b
-8b
1.5b
2.03b
-b
-3.14b
b
3b
-b
121b

점수

이것은 코드 골프이므로 가장 적은 바이트가 이깁니다. 표준 허점은 금지되어 있습니다.

리더 보드

다음은 일반 리더 보드와 언어 별 수상자 개요를 생성하는 스택 스 니펫입니다.

답변이 표시되도록하려면 다음 마크 다운 템플릿을 사용하여 헤드 라인으로 답변을 시작하십시오.

# Language Name, N bytes

N제출물의 크기는 어디에 있습니까 ? 당신이 당신의 점수를 향상시킬 경우에, 당신은 할 수 있습니다 를 통해 눈에 띄는에 의해, 헤드 라인에 오래된 점수를 유지한다. 예를 들어 :

# Ruby, <s>104</s> <s>101</s> 96 bytes

헤더에 여러 숫자를 포함하려는 경우 (예 : 점수가 두 파일의 합계이거나 인터프리터 플래그 페널티를 별도로 나열하려는 경우) 실제 점수가 헤더 의 마지막 숫자 인지 확인하십시오 .

# Perl, 43 + 2 (-p flag) = 45 bytes

언어 이름을 링크로 만들어 리더 보드 스 니펫에 표시 될 수도 있습니다.

# [><>](http://esolangs.org/wiki/Fish), 121 bytes


7
나는 내가 잘못하고 있다고 의심하지만, b/0 = b그렇다면 두 부분을 b그때로 나눕니다 1/0 = 1. c이처럼 나누려면 숫자가 필요 합니까?
내 대명사는 monicareinstate 오전

4
@Erik은 b/b = 0일반적으로 1 일 것으로 예상 될 때 (그리고 모든 다양한 공리에서 쉽게 입증 될 것이라고 확신합니다) 그렇지 않으면 b의 곱셈 역수가 곱셈의 역수가 아닌 것처럼 보입니다. 나는 당신이 추가 b=1/0하거나 비슷한 것을 0으로 나누는 것에 대해 허점을 만들 수 없다고 확신합니다 .
내 대명사는 monicareinstate입니다.

30
0으로 나누기가 정의되지 않은 이유가 있습니다 ... . 당신은 모든 예 (0 세 번째 제외) 단순화 할 수 있어야한다 그래서Bb=1b=11b=3=10=0=10=
대부분 무해

8
세 번째 예제가 0b아닌 출력이 아니어야합니까 0? 두 표현이 동일하다면 질문은 전제가 없을 것이다
trichoplax

4
권장 테스트 사례 :3.1b/0
jimmy23013

답변:


19

Malbolge Unshackled (20 트릿 회전 변형), 3,62e6 바이트

이 답변의 크기가 게시 가능한 최대 프로그램 크기 (eh)를 초과하므로 코드가 내 GitHub 리포지토리에 있습니다 (참고 : CTRL + A 및 CTRL + C를 사용하여 코드를 복사하지 마십시오. 마우스 오른쪽 버튼을 클릭하고 "대상 요소를 다른 이름으로 저장"을 클릭하십시오. .. ").

이것을 실행하는 방법?

순진한 Haskell 통역사가 이것을 실행하기 위해 나이가 들기 때문에 이것은 까다로운 부분 일 수 있습니다. TIO는 괜찮은 Malbogle Unshackled 통역사가 있지만 슬프게도 사용할 수 없습니다 (제한 사항).

내가 찾을 수있는 가장 좋은 방법은 고정밀 20 회전 회전 폭 변형입니다.이 변형은 매우 잘 수행되며 즉시 계산합니다 .

인터프리터를 좀 더 빠르게 만들기 위해 Matthias Lutter의 Malbolge Unshackled 인터프리터에서 모든 검사를 제거했습니다.

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

작동합니다!

작동합니다!


6
나는 당신이 모든 것을 입력하지 않았기를 바랍니다.
connectyourcharger

5
내가 프로그램을 열었을 때, 크롬 폴란드에서 번역을 시도
Tharwen

@Tharwen 한눈에보기가 어렵습니다. 폴란드인지 아니면 폴란드어인지는 어렵습니다. 슬프게도 내 언어는 배울 수있는 지옥입니다.
Krzysztof Szewczyk

7

PHP , 65 64 61 58 바이트

(빈 문자열) b대신 -1 바이트를 사용하십시오 ''. "b"는 트리밍되므로이 특정 경우 빈 문자열과 같습니다.

substr대신 explode입력을 사용하여 -3 바이트 를 입력합니다.

더 나은 방법을 사용하여 -3 바이트를 감지 1하고 및 -1.

<?=($n=substr($argn,0,-2))?trim($n+1?$n-1?$n:b:'-',b).b:0;

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

테스트 : 온라인으로 사용해보십시오!

"/"앞의 입력의 첫 부분 (이를 호출 함 $n)이 0이면 0을 인쇄합니다.

Else $n는 끝에서 "b"를 자르고 -1과 1의 특수한 경우를 처리하므로 "1"숫자는 인쇄되지 않습니다. 그리고 마지막에 하나의 "b"를 추가합니다. 트리밍 부분은 "3bb"와 같이 끝에 "b"가 두 배가되지 않도록하는 것입니다.


아주 잘 했어요!
Lyxal

교체 $n==-1$n>0(-2 바이트) 작동하는 것 같다. 당신은 그것을 시도 할 수 있습니다.
Ismael Miguel

@IsmaelMiguel, 그것은 작동 $n<0하지 않습니다 -8/0.
Night2

@IsmaelMiguel,하지만 당신은 내게 대체 아이디어, 준 $n==-1?'-':$n으로 $n+1?$n:'-'2 바이트를 저장하기를!
Night2

1
: / 테스트했을 때 작동하는 것 같습니다. 하지만 다른 방법으로 찾은 것이 좋습니다.
Ismael Miguel


4

젤리 , 18 바이트

나는 이것에 대한 Erik 's ṾṖ$İƑ¡ 를 훔치는 것을 끝내었다 (그렇지 않으면 나는 또한 19를 가질 것이다) ...

ṖṖv0ḢṾṖ$İƑ¡,Ạ¡”boḢ

결과를 인쇄하는 전체 프로그램.

온라인으로 사용해보십시오! 또는 테스트 스위트를 참조하십시오.

어떻게?

ṖṖv0ḢṾṖ$İƑ¡,Ạ¡”boḢ - Main Link: list of characters S
Ṗ                  - discard right-most (of S)
 Ṗ                 - discard right-most
   0               - literal zero
  v                - evaluate as Jelly code with right argument (0)
                   - ... b is covert-to-base, so "nb0" gives [n]
    Ḣ              - head ([n]->n or n->n)
          ¡        - repeat...
         Ƒ         - ...# of times: is invariant under:
        İ          -   reciprocation (n->1/n)
       $           - ...action: last two links as a monad:
     Ṿ             -   un-evaluate (-1->"-1" or 1->"1")
      Ṗ            -   discard right-most ("-1"->"-" or "1"->"")
             ¡     - repeat...
            Ạ      - ...# of times: all?
           ,  ”b   - ...action: pair with a 'b' character
                o  - logical OR with:
                 Ḣ -   head (S)  (i.e. if we end with 0 use the 1st character of the input)
                   - implicit print

1
아아, 나는 내가 남용 할 수있는 방법을 생각하고 있었다 v. : D
Outgolfer Erik

4

펄 6 , 32 바이트

{~m/^0/||S/[(\-|^)1|b]?\/0/$0b/}

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

입력이 경우 정규 표현식에, 몇 사람이 확인하는 0/0, 다른 하나는 후행를 교체 /0단지와 b(과 제거 된 b, 1및 / 또는 -1)

설명 (이전)

{                          }  # Anonymous codeblock
 ~m/^0/     # Return 0 if the input starts with 0
       ||   # Otherwise
         S/             / /  # Substitute
                     \/0       # The /0
          (        )?          # Optionally starting with
           <wb>1               # 1 or -1
                |b             # Or b
                         b   # With just b

3

망막 , 28 24 바이트

b?/0
b
^0b
0
(^|-)1b
$1b

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

먼저 Retina를 사용해보십시오. 골프를위한 충분한 공간이있을 것입니다.



무엇을하는지 사냥 한 후에 \b(나는 정규식 경험하지 못했습니다) 인쇄 할 수없는 백 스페이스 문자로 단축 될 수 없다는 것을 알게되어 약간 실망했습니다. 어쨌든, 감사합니다
관련없는 문자열

1
@UnrelatedString은 물론 백 스페이스로 단축 될 수 없습니다. 결국 \b일반 문자열에서 백 스페이스 문자의 ASCII 표현 일뿐입니다. : P
ASCII-only

2

파이썬 3 , 68 바이트

import re
print(re.sub('^0b$','0',re.sub(r'(^1)?b?/0','b',input())))

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


좋은 해결책! 그러나 import re
바이트

1
@ movatica 좋은 점, 여기에 새로운 내용이므로 수입 명세서가 포함되어 있음을 알지 못했습니다 (물론 물론입니다). 편집했습니다.
Kazim

어서 오십시오! :) 그래도 더 짧은 람다 버전을 유지할 수 있습니다! 전체 프로그램 일 필요는 없습니다. 그리고 import 문은 람다 정의 뒤에 위치 할 수 있으므로 64 바이트 가 가능합니다 !
movatica

1
@movatica 아, 좋아! 수입품과 람다와 함께 작동시키는 방법을 찾지 못했습니다. 감사합니다
Kazim

1

작은 통 , 18B

모든 크레딧은 Jono 2906입니다.

__:b=;[b]^:\1=[_]^

설명

__                 # Take implicit input and remove the "trash" (/0).
  :b=              # Is the last character equal to b?
     ;             # Negate(decrement) this value.
      [b]          # If the last character is not b, append b.
         ^         # Reverse the stack.
          :\1=     # Is the first character equal to 1?
              [_]  # If so, reduce the value.
                 ^ # Reverse the stack back and implicit output.

티오!



1

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

s=>+(n=s.split`/`[0])?[n*n-1?n:'-'[~n]]+'b':n

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

댓글

s =>                  // s = input: "numerator/0"
  +(                  //
    n = s.split`/`[0] // n = numerator, as a string
  ) ?                 // if n coerced to a Number is neither equal to 0 nor NaN:
    [ n * n - 1 ?     //   if abs(n) is not equal to 1:
        n             //     append the numerator
      :               //   else:
        '-'[~n]       //     append '-' if n = -1, or an empty string otherwise
    ] + 'b'           //   append 'b'
  :                   // else:
    n                 //   just output the numerator because it's either "0" or
                      //   an expression that already contains 'b'

1

C, 209 203 137 바이트

ceilingcat 덕분에 -66 바이트

char a[9];main(f){gets(a);f=strlen(a)-3;a[f+1]=0;printf((*a==55&a[1]==49&f==1?a[1]=98:*a==49&!f?*a=98:a[f]==98|*a==48&!f)?"%s":"%sb",a);}

TIO


-0/0을 입력하면 -0b가 표시되지만 예제 입력 또는 테스트 사례에는 없었으므로 정확합니다.
girobuz

1

naz , 64 바이트

6a8m1s2x1v2m4a2x2v1x1f1r3x1v2e3x2v3e1o1f0x1x2f2m4a1o0x1x3f1o0x1f

설명 ( 0x명령 제거)

6a8m1s2x1v             # Set variable 1 equal to 47 ("/")
2m4a2x2v               # Set variable 2 equal to 98 ("b")
1x1f                   # Function 1
    1r                 # Read a byte of input
      3x1v2e           # Jump to function 2 if it equals variable 1
            3x2v3e     # Jump to function 3 if it equals variable 2
                  1o1f # Otherwise, output it and jump back to the start of the function
1x2f2m4a1o             # Function 2
                       # Set the register equal to 98 and output once
1x3f1o                 # Function 3
                       # Output once
1f                     # Call function 1

0

Brainfuck, 25 바이트

>,[>,]<[-<+>]<+++[<]>[.>]

설명

>,[>,]        read from stdin
<[-<+>]<+++   add last two cells and add three ( ascii('/') + ascii('0') + 3 = ascii('b')
[<]>          move pointer to first char to output
[.>]          output until cell w/ value 0

1
b/0예상 b,있어 bb; 0/0예상 0,있어 0b; -1/0예상 -b얻었다 -1b.
a'_ '

네, 기본적으로 이것은 단지는 대체 /0를위한 b과에 대한 계정에 각 호의 어느 하나에 해당하는 경우를 고려하지 않습니다 0b, 1b, -1b또는 이미 포함되어 있는지 어떤 입력b
조 왕
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.