남북으로 남북으로


30

N, S, E 및 W의 문자열이 주어지면 소수 자릿수 5 자리까지 올바른 방위 (북에서 시계 방향 각도)를 출력합니다.

에서 기존의 나침반 표기법 , 문자열은 2 (북북서 또는 ESE 같은) 이러한 문자로 구성되어 있습니다. 여기에는 WNNNSE와 같이 4를 모두 포함하는 문자열도 허용해야합니다 . 인간은 2 개의 기호 만 사용하여 의미를 직관적으로 이해할 수 있습니다. 4 개의 기호를 허용하면 읽기가 끔찍하지만 주어진 정확도로 베어링을 설명하는 짧은 방법을 사용할 수 있습니다.

(AS는 지적 주석 에 의해 user2357112 , 내가 잘못된 가정에이 문제를 기반으로 한 있도록, 특정 방위를 들어, 4 기호 문자열이 두 기호 문자열과 정확히 같은 길이 될 것이라고 증명할 수 밝혀졌습니다. 이 실용적인 목적의 부족이 도전에 대한 즐거움을 방해하지 않기를 바랍니다 ...)

정확한 방법은 아래에 설명되어 있으며 기존 표기법과 동일합니다 (변경하지 않고 확장 함).

입력

  • 입력은 문자 만 포함하는 단일 문자열입니다 NESW 입니다.
  • 전처리를 포함하지 않는 경우 원하는 경우 입력이 일련의 문자 일 수 있습니다. 예를 들어 중첩 목록을 가져옵니다.[N, [E, [S, [W]]]] 처리 순서를 돕기 을 것은 허용되지 않습니다.
  • 다른 캐릭터를 사용할 수 없습니다. 1234대신에 문자열을 사용할 수 없습니다NESW .

산출

  • 출력은 10 진수 또는 1의 문자열 표현이어야합니다 (이성 / 분수 아님).
  • 후행 0을 표시 할 필요는 없습니다. 베어링이 9.00000인 경우 출력9 도 소수점 5 자리까지 정확한 것으로 계산됩니다.
  • 출력 범위는 [0, 360)입니다. 즉, 0은 포함하고 360은 제외합니다.
  • 출력은 소수점 다섯 자리로 반올림하여 확인합니다. 베어링이 0.000005 인 경우 0.00001로 반올림합니다. 출력 0.00001과 0.000005는 모두 정확합니다.
  • 일부 입력에 대해서는 과학적 표기법으로 출력 할 수 있습니다. 예를 들어, 1e-5대신 0.00001.

변환

  • 단일 문자 나침반 점 N, E, S, 및 W대응하여 0, 90, 180, 270도 각각.
  • 이 중 하나를 문자열에 추가하면 단일 문자의 베어링과 원래 문자열의 베어링을 이등분하는 베어링이 생성됩니다.
  • NE가 225 도가 아닌 45도를 나타내도록 두 개의 가능한 이등분 베어링 중 가장 가까운 것이 선택됩니다.
  • 이등분 될 각도가 180 도인 경우를 제외하고는 분명합니다. 따라서 NS, SN, WE, 및EW 정의되지 않은 베어링에 해당하고, 입력은 이들의에 끝이 없을 것입니다. 그러나 입력 문자열의 다른 곳에 나타날 수 있습니다. 모호성이 없습니다.
  • 마지막 두 문자가 동일하면 이분법이 동일한 방위를 반환하므로 마지막 문자는 중복됩니다. 이것은 표기법에 아무것도 추가하지 않기 때문에 코드는 이것을 처리 할 필요가 없습니다. 따라서 NN, EE, SS, 그리고 WW정의되지 않은 베어링에 해당하고, 입력은 이들의에 끝이 없을 것입니다. 그러나 입력 문자열의 다른 곳에 나타날 수 있습니다.

N: 0
E: 90
S: 180
SE: halfway between S and E: 135
NSE: halfway between N and SE: 67.5
NNSE: halfway between N and NSE: 33.75
NNNSE: halfway between N and NNSE: 16.875
NNNNSE: halfway between N and NNNSE: 8.4375

테스트 사례

제출은 모든 테스트 사례에 대해 올바른 결과를 제공하는 경우에만 유효합니다. 테스트 케이스는 배정 밀도로 처리 할 수있는 것의 한계까지 밀려납니다. 기본적으로 단 정밀도를 사용하는 언어의 경우 올바른 출력을 얻으려면 바이트를 사용하여 배정 밀도를 지정해야합니다.

테스트 케이스 출력은 소수점 5 자리로 반올림되며 임의의 정밀도로 표시됩니다. 둘 다 유효한 출력입니다.

WNE 337.5 337.5
WEN 337.5 337.5
WEWEWEWEWEWEWEWEWEWEWEN 330.00001 330.000007152557373046875
NESWNESWNESWNESWNESWNESWNESW 90 89.99999932944774627685546875
NNNNNNNNNNNNNNNNNNNNNNNE 0.00001 0.0000107288360595703125
NNNNNNNNNNNNNNNNNNNNNNNW 359.99999 359.9999892711639404296875
SNNNNNNNNNNNNNNNNNNNNNNNE 90.00001 90.00000536441802978515625
SNNNNNNNNNNNNNNNNNNNNNNNW 269.99999 269.99999463558197021484375

채점

이것은 입니다. 점수는 소스 코드의 길이 (바이트)이며 가장 짧은 승입니다.


페단 트리

"North by North West"가 올바른 나침반 방향이라고 생각하는 실수를했습니다. 그것은 도전 생각을했다,하지만 난 다음에서 발견 된 이후 행복한 실수, 위키 백과 페이지 :

"알프레드 히치콕 1959 영화의 제목, 북북서로 진로를 돌려라는 실제로 32 바람 나침반 방향 지점이 아니라, 영화에는 노스 웨스트 항공에 대한 언급이 포함되어 있습니다. "

또한이 과제에 사용 된 방법은 16 포인트 나침반을 포함하여 기존 나침반 포인트와 만 일치한다는 것이 밝혀졌습니다. 해당 페이지에 설명 된 32- 바인 컴퍼스는 미묘하게 다르며이 과제에 대한 존재를 편리하게 간과했습니다. .

마지막으로 "South East"대신 "Southeast"를 사용해야한다고 생각하는 사람은


WNNNSE<= 게시물 시작시이 예제 항목의 결과는 무엇입니까? 그것은 나에게는 유효하지 않은 것처럼 들리지만 말하기 어렵다.
Tensibai

@Tensibai 입력의 WNNNSE경우 출력은 다음과 같습니다 323.4375. 이 경우와 같은 방식으로 적용되는 연습은 예제 섹션을 참조하십시오.
trichoplax

입력이 f(N,N,N,S,E)괜찮습니까?
Karl Napf

@KarlNapf 명확히하기 위해 입력 섹션을 확장했습니다. 올바르게 이해하면 여러 인수가있는 예제 입력이 일련의 문자와 동등한 것으로 보이므로 받아 들일 수 있습니다.
trichoplax

2
"4 개의 기호를 허용하면 읽기가 끔찍하지만 주어진 정확도로 베어링을 설명하는 짧은 방법을 사용할 수 있습니다." -확실해? 동일한 방위를 나타내는 모든 입력은 길이가 같은 것 같습니다. 각 방위에 0에서 1까지의 이항식을 할당하면 N> 1 인 길이 -N 문자열은 항상 분모가 2 인 이항식에 해당합니다. +1) 가장 낮은 용어입니다. 또한 베어링에 두 개 이상의 고유 한 글자를 허용하면 표현력이 추가되지 않습니다. 3 자 또는 4 자 문자로 표현 된 베어링은 2로 표현할 수 있습니다.
user2357112는

답변:


13

JavaScript (ES6), 84 80 78 74 72 bytes

Saved a byte thanks to @Titus, 1 thanks to @Neil

f=([c,...s],b="NESW".search(c))=>b*90-(s[0]?(b-=f(s)/90)-4*(b*b>4):0)*45

It took a while, but I think I've finally perfected the formula...

Test snippet

Explanation

Let's start with the simplest case: a single-char string. The result is simply its (0-indexed) position in the string NESW, multiplied by 90.

For a two-char string, the result lies halfway between the result of the first char and the result of the second. However, there's a catch: if the absolute difference between the two is greater than 180 (e.g. NW or WN), we must 180 to the angle so that it's not pointing the opposite direction.

For any longer string, the result lies halfway between the result of the first char and the result of the rest of the string. This can be generalized in the following way:

  • If the input is a single char, return its index in the string NESW times 90.
  • Otherwise, return the index of the first char in the string NESW times 45, plus half the result of the rest of the string; add an extra 180 if the absolute difference between the two is greater than 90.

Excellent way to cutting the first character off the string! You can save one byte if you calculate with values divided by 45.
Titus

@Titus I can save 2 bytes with that technique, thanks!
ETHproductions

1
search instead of indexOf to save you a byte.
Neil

@Neil Thanks again! I managed to golf off three more by completely rearranging the equation.
ETHproductions

10

C#6, 226 217 207 185 bytes

using System.Linq;double N(string s){double b=f(s.Last());foreach(var c in s.Reverse()){b=(b+f(c)+(b-f(c)>2?4:f(c)-b>2?-4:0))/2;b=(b+4)%4;}return b*90;}int f(char x)=>"NESW".IndexOf(x);

Edit: -10 bytes by "borrowing" idea from ETHproductions's submission
-22 bytes thanks to @Titus

Ungolfed

// Call this method
double N(string s){
    // Initialize bearing with last direction
    double b=f(s.Last());
    // Do backward. Doing last direction once more doesn't impact result
    foreach(var c in s.Reverse()){
        // Average current bearing with new bearing, adjusted with wrapping
        b=(b+f(c)+(b-f(c)>2?4:f(c)-b>2?-4:0))/2;
        // Make bearing back to range [0,4)
        b=(b+4)%4;
    }
    // Change from "full circle = 4" unit to degree
    return b*90;
}
// helper method to convert direction to bearing. This returns bearing with full circle = 4.
int f(char x)=>"NESW".IndexOf(x);

I think you can make your range adjustment back to [0,360) shorter by using %
trichoplax

@trichoplax Won´t that cut the decimals?
Titus


1
Save 10 bytes with b=(b+360)%360; instead of b+=b>360?-360:b<0?360:0;. Save another 12 bytes with dividing everything by 90 and return b*90;.
Titus

1
Here are 10 more bytes: merge the two assignments and remove braces: b=(b+f(c)+(b-f(c)>2?4:f(c)-b>2?-4:0)+8)/2%4; then distribute +8 to the ternary results b=(b+f(c)+(b-f(c)>2?12:f(c)-b>2?4:8))/2%4;
Titus

8

PHP, 95 88 86 100 127 104 101 bytes

  • -7 bytes with the null coalescing operator
  • -2 bytes by not replacing N (and more, because that allows to put the translation to the loop head: N is truthy, but evaluates to 0 in the calculation.)
  • +41 bytes for fixing the bisection (cough)
  • -7 bytes directly and -16 indirectly inspired by @ETHproductions´ code
  • -3 bytes by replacing strtr with one of my bit jugglings

for($i=strlen($s=$argv[1]);$i--;$p=($q+$p=$p??$q)/2+2*(abs($q-$p)>2))$q=ord($s[$i])/.8+3&3;echo$p*90;

This is officially the first time ever that I use the null coalescing operator. Run with -r.

PHP 7.1

Negative string offsets in the upcoming PHP version will save 12 bytes:
Replace strlen($s=$argv[1]) with 0 and $s with $argv[1].


Free bytes for (almost) everyone:

  • Calculating with 0,1,2,3 instead of 0,90,180,270 and multiplying the final result with 90 will save two bytes and probably allow further golfing.
  • There are some patterns in the ASCII codes of the characters. Try one of these in your language:
    • (a/2%6+2)%5
    • a<87?a/2&3^3:3 or a/2&3^3*(a<87)
    • a&1?a&2|a/4&1:0
    • a/.8-1&3

5

Python 3, 133 113 bytes

Just improving on @L3viathan's answer because I just made this account and therefore can't make comments yet.

d={"N":0,"E":.5,"S":1,"W":1.5}
def B(s):
 b=d[s[-1]]
 for c in s[::-1]:b=(b+d[c])/2+(abs(b-d[c])>1)
 return b*180

Welcome to Programming Puzzles & Code Golf, and nice improvement...
trichoplax

I didn't see your answer, but Titus had a similar idea, plus I had another, I'm down to 98 now :)
L3viathan

5

05AB1E, 48 42 37 32 bytes

Saved 6 bytes thanks to Emigna. Saved 5 bytes thanks to Titus' idea to work on range [0,4[ and multiply by 90 at the end. Saved 5 bytes thanks to Adnan's mastery of ancient xor/modulo metamorphosis.

So every angle is reduced from range [0,360[ to range [0,4[ throughout the execution. Result is then multiplied by 90 and displayed.

Ç30^5%R¬U¦vXy+;DX-Ä0›2*+4%U}X90*

It can be divided into two sequentially called subprograms.
First program: convert input string into an array of the corresponding angles in range [0,4[
Ç      Take the ascii value of all input characters
 30^5% Dark ascii manipulation that yields [0,1,2,3] for [N,E,S,W]

Now we have an array of integers in range [0,4[.

Second program: actually compute the final angle
R                          Reverse the array
 ¬                         Take the first value (the last of the non-reversed array)
  U                        Pop it from the stack and set X to the same value
   ¦                       Strip the first element
    v                      For each remaining element
     Xy+;                  Compute the average value between the leftmost value and X
         DX-Ä0›            Push 1 if angular distance cast to integer is > 0 (i.e. if it is >= 1), 0 otherwise. It's equivalent to checking >= 90 degrees
               2*+         Multiply by 2 (=2 if angular distance is >= 1 and 0 otherwise) and add it to the formerly computed average value. It's equivalent to multiplying by 180
                  4%       Perform mod 4. It's equivalent to performing mod 360
                    U      Store the result back to X
                     }     End for, mandatory if input has only one character
                      X90* Push X*90 and implicitly display it

Try it online!

Potential axes of golfing:

  • Not sure if that mod 4 is required (it would save 2 bytes). All test cases work without it, but maybe there exists a tricky case. A mathematical proof to either validate it or nullify it would be top-notch.
  • There is no implicit stuff besides displaying the result (closing quote marks, closing brackets).

1
Doesn't seem to give the requested result on the NNNNNNNNNNNNNNNNNNNNNNNE and SNNNNNNNNNNNNNNNNNNNNNNNE test cases.
Emigna

2
Weird. Now I do as well. I must have pasted wrong or something, sorry. You can shorten the code down to v"NESW"yk90*})R¬U¦vXy+;DX-Ä89›180*+360%U}X.
Emigna

1
Great explanation! It might be worth including a note that 89› actually means the integer part is greater than 89, which is equivalent to saying the complete number is greater than or equal to 90 (which still works fine because exactly 90 should never occur). Currently the comment in the explained code makes it sound like it's checking for greater than 89, whereas your code passes the test cases so is clearly correctly checking for greater than 90.
trichoplax

1
I edited the explanation so, however I wrote "cast to integer" since I'm not sure how the operator should behave towards negative floating point values. There is no problem here since it works on the absolute value, but I prefer not making too strong assumptions on the operator.
Osable

1
You can replace v"NESW"yk}) with Ç30^5% :)
Adnan

5

Python 3, 146 145 117 107 97 94 93 92 bytes

f(s):u='NESW'.find(s[0])*90;return(u+f(s[1:]))/2+180*(abs(u-‌​f(s[1:]))>180)if s[1:]else u

Call f with the string.


You can't have the two ...0else they throw SyntaxErrors.
Jonathan Allan

@JonathanAllan What version of Python are you using? I'm on 3.5.2 and it works.
L3viathan

I ran it on 3.3.3 - can you remove the space between else and - too? (can in 3.3.3)
Jonathan Allan

@JonathanAllan Yes I can! Thanks, that saves me another byte.
L3viathan

2
@Titus d.find can, I had the exact idea a minute ago; see updated answer.
L3viathan

5

C, 184 bytes

double h(char c){return ((c=='E')+(c=='S')*2+(c=='W')*3);}double d(char*s){double f=h(*s);if(s[1]){double t=f;f=(f+d(s+1)/90)/2;if(((t-f)>1)||((f-t)>1))f+=2;if(f>=4)f-=4;}return f*90;}

Ungolfed

// a helper function
double direction_(char ch)
{
    if (ch=='N')
        return 0.;
    else if (ch=='E')
        return 90.;
    else if (ch=='S')
        return 180.;
    else
        return 270.;
}

// this is the main function to call
double direction(char* str)
{
    double fAngle = direction_(str[0]);
    if (str[1])
    {
        double tmp = fAngle + direction(str+1);
        if (tmp>=360.)
            tmp-=360.;
        tmp/=2;

        if (((tmp-fAngle)>90.) || ((tmp-fAngle)<-90.))
        { //  check if we need to take the "other side"; if the resulting angle is more than 90 degrees away, we took the wrong on
            if (tmp>=180.)
                tmp-=180.;
            else
                tmp+=180.;
        }
        fAngle = tmp;
    }
    return fAngle;
}

seems that using float, doesn't give you the precision needed.
Eyal Lev

4
Welcome to PPCG! :D
mbomb007

Won't the names of the functions conflict with each other (since the names are both d)?
clismique

@qwerp, different signature (one takes char*, other takes only char)
Eyal Lev

2
Function names are not name mangled in C, as they are in C++, so you need to rename one of them if you want it to be C.
Klas Lindbäck

3

R, 172 146 bytes

z=rev((0:3*90)[match(scan(,""),c("N","E","S","W"))]);p=z[1];l=length(z);for(i in 2:l)p=(p+z[i])/2+(abs(p-z[i])>180)*180;if(l<2)p=z;sprintf("%f",p)

Ungolfed

z=rev((0:3*90)[match(scan,""),c("N","E","S","W"))]); #1
p=z[1];                                              #2
l=length(z)                                          #3
for(i in 2:l)p=(p+z[i])/2+(abs(p-z[i])>180)*180;     #4
if(l<2)p=z                                           #5
sprintf("%f",p)                                      #6

Explained

  1. Read input from stdin
    • Match input by index to c("N","E","S","W")
    • From matched indices: match to the vector of degrees 0:3*90 (instead of c(0,90,180,270))
    • Reverse and store as z
  2. Initialize p to the degree equivalent to last char in input
  3. Store length of input as l
  4. Iteratively, calculate the closest of the two possible bisecting bearings.
  5. If only one input is given, set p to z
  6. Format and print

Try the test cases on R-fiddle (note that this is a function due to scan not working on R-fiddle)


Provided that the output is correct to 5 decimal places, you don't need to perform the rounding. From the challenge: Outputs 0.00001 and 0.000005 are both correct. So you should be able to save some bytes by not rounding
trichoplax

@trichoplax I understand. Can the input also be a vector of string characters like. c("N","N","E") instead of "NNE"? This equivalent to a non-nested python list ["N","N","E"].
Billywob

Yes. I intended "sequence" to be a general term to include things like arrays, vectors, lists, tuples.
trichoplax

1
I think you can save 4 bytes if you divide everything by 90 and printf(p*90).
Titus

3

Haskell, 109 105 103 bytes

h=180
a#b|abs(a-b)<h=n|n>h=n-h|1>0=n+h where n=(a+b)/2 -- calculates the new "mean" on the cirlce
f 'N'=0                                          -- translates characters to angles
f 'E'=90
f 'S'=h
f _=270
foldr1(#).map f                                  -- traverses the whole string

Thanks for -2 byte @xnor!


The exhaustive list for f looks long, but I'm having trouble finding anything shorter. Closest I got was f c=90*until(\i->"NESW"!!i==c)(+1)0 (35). I think you can replace 'W' with _.
xnor

Yeah I also expected there to be something shorter, but didn't find anything. Thanks for the _!
flawr

3

Dyalog APL, 55 45 38 bytes

Solution

Requires ⎕IO←0, which is default on many systems. Asks for direction.

360|÷○÷180×12○(+÷(|+))/¯12○○2÷⍨'NES'⍳⍞

Explanation

Goes around the problem by converting each letter to a complex number 1∠θa + b · i, then doing a sum reduction from right-to-left (APL's forte) while normalizing at each step. The final θ is then converted to degrees and normalized to be within [0, 360):

'NES'⍳⍞ the indices of each input letter in "NES"; N→0, E→1, S→2, anything else→3

○2÷⍨ convert to angles in radians; θ = π · x2

¯12○ convert to complex numbers on the unit circle; ei · θ

(...)/ reduce the list with... (i.e. insert the function between the elements of...)

+÷(|+) ... the normalized sum; xn - 1 + xn|xn - 1 + xn|

12○ convert to angle; θ

÷○÷180× convert to degrees; 1π · 1180 · x

360| division remainder when divided by 360

TryAPL online!

Anecdote

If input and output was as orthogonal complex units, the entire solution would be just:

(+÷(|+))/

The rest of the code is parsing input and formatting output.


I notice the test outputs do not match those in the challenge to 5 decimal places, making this invalid. Does Dyalog APL have the option of using double precision?
trichoplax

@trichoplax Yes, ⎕FR←1287 makes use of 128 bit floats, but TryAPL doesn't allow it.
Adám

I think anything greater than or equal to 64 bit floats should work (I've only tested in Python though). Does this mean you can make the code valid but it will then only work for people who have installed the language? Maybe you could show the full valid code for the score, and include the online version that doesn't quite have the required accuracy so people can see that the algorithm is correct.
trichoplax

@trichoplax Actually, TryAPL uses double precision, but your test cases accumulate errors beyond 53 bits.
Adám

If it can be shown that the difference is due to differences in interpretation of the IEEE 754 standard, that are still standard compliant, then I'll adjust the test cases to make sure both interpretations give the same result to 5 decimal places. I chose the test cases such that they gave the same result to 5 decimal places in Python for both float (double precision) and arbitrary precision decimals. I'll have a look into it.
trichoplax

2

Common Lisp, 347 327 bytes

Thanks to @Titus for taking off a few

This can probably be golfed more, but at least it works (I think):

(defun d(c)(if(eql c #\N)0(if(eql c #\E)1(if(eql c #\S)2(if(eql c #\W)3)))))(defun m(a b)(if(> a b)(rotatef a b))(if(<(+(- 4 b)a)(- b a))(+(/(+(- 4 b)a)2)b)(+(/(- b a)2)a)))(defun f(s)(let((c))(setf c(d(char s(1-(length s)))))(do((a)(p(-(length s)2)(1- p)))((< p 0))(setf a(char s p))(setf c(m(d a)c)))(format t"~5$"(* c 90))))

Usage:

* (f "WNE")
337.50000
NIL

Function d takes a character N, E, W, or S and returns the appropriate degree. Function m gets the approprate combined degree of two given directions. Function f iterates through the provided string, computes the appropriate degree, and prints it as a floating point.


My LISP is rusty, but can dividing everything by 90 save 6 bytes?
Titus

@Titus I think it would. I've realized some other improvements so I'll add this when I'm at my computer
artificialnull

2

Befunge, 183 181 175 bytes

>~#+:#25#%6*#/`#2_$>5%4*:00p"Z}"4*:***20g#v_+2/00g10g-:8`\0\-8`+!v
v5:+*:*:"d"/+55+5$_^#!:\p01/**:*4"}Z":p020<%**:*"(2Z"+**5*:*"0}"!<
>5>+#<%#56#58#:*#/+\#5:#5_$$$,,,".">:#,_@

Try it online!

Explanation

This follows a similar algorithm to many of the other answers, only it's using fixed point calculations emulated with integers since Befunge doesn't support floating point.

Thanks to @Titus for the ASCII-to-int routine.

 ~ : 5 6* ` _$        while ((c = getchar()) > 30)  // ends with any ctrl char or EOF
> + 2 %6 / 2            push(c / 2 % 6 + 2)         // partial conversion to int

                      do {
  5%                    dir = pop() % 5             // completes the conversion to int   
  4*:00p                dir *= 4; lowres_dir = dir  // used by the 180-flip calculation
  "Z}"4*:***            dir *= 22500000             // this is 90000000 / 4 
  20g_                  if (!first_pass) {
    +2/                   dir = (dir+last_dir)/2    // last_dir is second item on stack
    00g10g-               diff = lowres_dir - last_lowres_dir
    :8`\0\-8`+!!          flip = diff>8 || -diff>8
    "}0"*:*5**+           dir += flip * 180000000   // add 180 degrees if we need to flip
    "Z2("*:**%            dir %= 360000000          // keep within the 360 degree range
                        }
  020p                  first_pass = false
  :"Z}"4*:**/10p        last_lowres_dir = dir / 22500000
  \                     last_dir = dir              // saved as second item on stack
  :!_                 } while (!stack.empty())

$                     pop()                         // this leaves the final dir on top
5+55+/                dir = (dir + 5)/10            // round down to 5 decimal places
"d":*:*+              dir += 100000000              // add a terminating digit
                      while (true) {                // convert into chars on stack
:55 + % 6 8 * +\ : _    push(dir%10+'0'); if (!dir) break
   > < 5 5 : /+ 5 5     dir /= 10
                      }

$$$                   pop() x 3                     // drop the chars we don't need
,,,                   putchar(pop()) x 3            // output first three chars
"."                   push('.')                     // add a decimal point
>:#,_@                while(c=pop()) putchar(c)     // output the remaining chars

Does that just mean you need to emulate a larger fixed point type (more decimal places)? The test cases are designed to require double precision, which is no more than 17 significant figures (a maximum of 16 decimal places), and 14 decimal places might possibly be enough.
trichoplax

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