피타고라스 정리 a² + b² = c²를 누가 좋아하지 않습니까? 값 a와 b를 취하고 "이 직각 삼각형의 빗변은"+ c를 출력하는 모든 언어로 가능한 가장 짧은 방법을 작성하십시오. c는 소수점 이하 세 자리 만 유지하십시오.
code-golf태그는 "Code-golf는 가장 적은 바이트 의 소스 코드 에서 특정 문제를 해결하기위한 경쟁" 이라고 명시 적으로 말합니다 . 스코어링 코드 골프 (바이트 대 문자)를 참조하십시오 .
피타고라스 정리 a² + b² = c²를 누가 좋아하지 않습니까? 값 a와 b를 취하고 "이 직각 삼각형의 빗변은"+ c를 출력하는 모든 언어로 가능한 가장 짧은 방법을 작성하십시오. c는 소수점 이하 세 자리 만 유지하십시오.
code-golf태그는 "Code-golf는 가장 적은 바이트 의 소스 코드 에서 특정 문제를 해결하기위한 경쟁" 이라고 명시 적으로 말합니다 . 스코어링 코드 골프 (바이트 대 문자)를 참조하십시오 .
답변:
'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2
테스트:
'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2
⎕:
9 10
The hypotenuse of this right triangle is 13.454
설명:
⎕*2: 입력의 값을 두 번째 거듭 제곱으로 올립니다.+/: 합계를.5*⍨: 결과를 0.5 승으로 올립니다3⍕: 소수점 이하 3 자리로 반올림Input :Disp "THE HYPOTENUSE OF THIS RIGHT TRIANGLE IS
Fix 3:R▶Pr(X,Y
아니요, 닫는 괄호는 필요하지 않습니다. 또한 APL 답변보다 적은 바이트 :)
R▶Pr(A,B.
Fix 3:R►Pr(X,Y
Input을 요청 X하고하는 것은 Y재미의 종류이다. 허용 하면 빗자루 길이가 1 바이트로 표시되도록 PolarGCbefore 설정도 허용해야 합니까? 물론 커서를 움직일 때 및 값 이 더 이상 표시 되지 않지만 적절한 변수에 저장 됩니다. (우리가 다음 사용하지 않을 것이다, 그러나 그것은 카운트는 생각입니다.)InputRPolarGCXY
글坼各갠方終加감半方갾밈乘增貶껠矽녆둥긆둹댆뭴뉖멵댶넠닶눠덆둩댲걲늖덨덂건댦땡닦덬뉒걩댲밀⓶
공백으로 구분 된 두 개의 숫자 (분수 일 수 있음)로 입력을 예상합니다.
불편한 트릭을 몇 개 사용해야하지만 APL보다 짧습니다.
글坼 | split at space
各 | for each...
갠方 | to the power of two
終
加 | add
감半方 | to the power of one half
갾밈乘 | multiply by 1000
增貶 | increment, then decrement (kludge for rounding)
껠矽 | insert '.' at 4th-last character position
녆둥긆둹댆뭴뉖멵댶넠닶눠덆둩댲걲늖덨덂건댦땡닦덬뉒걩댲밀⓶ | "The hypotenuse..."
APL 답변의 점수를 접합니다!
2^r2^+3kv[The hypotenuse of this right triangle is ]Pp
테스트:
$ dc
3 4
2^r2^+3kv[The hypotenuse of this right triangle is ]Pp
The hypotenuse of this right triangle is 5.000
dc -e '2^r2^+3kv[The hypotenuse of this right triangle is ]Pp'입력을 기다리지 않고 "dc: stack empty"3 회 인쇄 한 다음 "이 직각 삼각형의 빗변은 2.000입니다."
dc -e '3 4 2^r2^+3kv[...3과 4가 매개 변수입니다.
입력이 함수 인수 일 수있는 경우 77 자 :
f(a,b){printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}
stdin에서 입력을 읽어야하는 경우 99
a,b;f(){scanf("%d %d",&a,&b);printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}
@Yimin Rong에게 큰 감사합니다!
파워 쉘
내가 할 수 있는지 확인하기 위해 ...
echo "The hypotenuse of this right triangle is " ([math]::round([math]::sqrt(([math]::pow(([double](Read-Host -p "A")),2) + [math]::pow(([double](Read-Host -p "B")),2))),3))
Read-Host.
p "The hypotenuse of this right triangle is %.3f"%(Math.sqrt(gets.to_i**2+gets.to_i**2))
업데이트 (의견 감사) :
p "The hypotenuse of this right triangle is %.3f"%(gets.to_i**2+gets.to_i**2)**0.5
a**0.5대신을 사용하면 몇 개의 문자를 저장할 수 있습니다 Math.sqrt(a). 그리고 이후의 공간 p도 제거 할 수 있습니다.
%(Math...).
print'The hypotenuse of this right triangle is %.3f'%(input()**2+input()**2)**.5
void h(int a,int b){printf("The hypotenuse of this right triangle is %.3f\n",hypot(a,b));}
pow(a,2)언제 할 수 a*a있습니까? 또한 바닥과 +.5의 목적을 이해하고 1000을 곱하고 1000으로 나눕니다
{printf "The hypotenuse of this right triangle is %.3f
",sqrt [+] @_ X**2}
{}람다 함수를 선언합니다. [+]합계 연산자, X**교차 전력 연산자 (예 : 1, 2 X+ 10, 20gives 11, 21, 12, 22)입니다. 이 경우 교차 전력 연산자는 하나의 인수를 취하므로 결과의 길이는와 같습니다 @_. @_모든 함수 인수를 포함합니다.
가 (안전하지 않은) 인수의 잘못된 번호를 취할 수있다 기능을하도록 허용 있다면, 그것을 대체하는 것이 가능 [+] @_ X**2하여 $^a**2+$^b**2, 어디 $^a와 $^b자리 표시 자 인수입니다.
A ridiculously inefficient algorithm.
x;f(a,b){for(;x-a*a-b*b;x=rand());printf("The hypotenuse of this right triangle is %.3f",sqrt(x));}
program p;
{$APPTYPE CONSOLE}
var a,b:integer;
begin
readln(a,b);
writeln('the hypotenuse of this right triangle is',sqrt(b*b+a*a):2:3);
end.
integer to int16 You dont have to include the first 2 lines for your answer, and you can remove whitespace. doing all that gives you 106 characters.
Golfscript (69 67 66 65)
This would be much easier if floating point was actually supported without resorting to workarounds... :)
~'The hypotenuse of this right triangle is '@.*@.*+2-1??+.'.'?4+<
2.!~ when 2-1 is shorter?
the difference between 2- 1` and 2-1 wrong, so was probably temporarily confused :) Fixed, thanks.
def p(a,b):print'The hypotenuse of this right triangle is %.3d'%((a*a+b*b)**.5)
math for some savings. (a*a+b*b)**.5
def saving a newline and an indent.
awk '{printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5}'
Thanks to Wasi for suggesting ^ operator and removing ()!
e.g.
$ echo 3 4 | awk '{printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5}'
The hypotenuse of this right triangle is 5.000
{printf"The hypotenuse of this right triangle is %.3f\n",($1^2+$2^2)^.5}
Golfed Code
1..2|%{sv $_ (read-host)};"The hypotenuse of this right triangle is $("{0:N3}"-f[math]::sqrt($1/1*$1+$2/1*$2))"
Walkthrough
1..2|%{sv $_ (read-host)}; Gets two inputs interactively from the user, and stores them in $1 and $2. Might be able to cut some length by using arguments or pipeline inputs instead.
"The hypotenuse of this right triangle is Required text in the output, per the challenge specifications.
$(...)" Encapsulated code block will be processed as script before being included in the output.
"{0:N3}"-f Formats output from the next bit of code as a number with exactly three digits after the decimal point.
[math]::sqrt(...) Gets the square root of the encapsulated value.
$1/1*$1+$2/1*$2 Serves as our "a^2+b^2". Multiplying a number by itself is the shortest way to square it in PowerShell, but the variables need to be divided by 1 first to force them to integers. Otherwise, they are treated as text and 3*3+4*4 would be 3334444 instead of 25.
i=prompt,'The hypotenuse of this right triangle is '+Math.hypot(i(),i()).toFixed(3)
Currently the shortest JS implementation using stdin :D
Works only on Firefox 27.0+ (EcmaScript 6)
If we can use just two variables (as lot of scripts do here):
a=2,b=3,'The hypotenuse of this right triangle is '+Math.hypot(a,b).toFixed(3)
(Also prints out a No Such Method error, though I'm not sure if this is against the rules)
class A{static{int a=1,b=1;System.out.printf("The hypotenuse of this right triangle is %.3f",Math.hypot(a,b));}}
(No error)
class A{static{int a=1,b=1;System.out.printf("The hypotenuse of this right triangle is %.3f",Math.hypot(a,b));}public static void main(String[] a){}}
C#
Method Only (114)
void H(double a, double b)
{
Console.Write("The hypotenuse of this right triangle is {0:N3}", Math.Sqrt(a * a + b * b));
}
Complete Program (171)
using System;
class P
{
static void H(double a, double b)
{
Console.Write("The hypotenuse of this right triangle is {0:N3}", Math.Sqrt(a * a + b * b));
}
static void Main()
{
H(3, 4);
}
}
Complete Program (without using method - 141)
using System;class P{static void Main(){double a=3,b=4;Console.Write("The hypotenuse of this right triangle is {0:N3}",Math.Sqrt(a*a+b*b));}}
Unlike @micha's solution, mine takes in two variables via function and sends the alert of the result.
function(a,b){m=Math;c=d=>d*d,e=1e3;alert("The hypotenuse of this right triangle is "+m.round(m.sqrt(c(a)+c(b))*e)/e)}
function(a,b){e=1e3;alert("The hypotenuse of this right triangle is "+Math.round(Math.sqrt(a*a+b*b)*e)/e)}
Fat arrow functions to the rescue!
h=(a,b,e=1e3)=>"The hypotenuse of this right triangle is "+Math.round(Math.sqrt(a*a+b*b)*e)/e
c(). Aliasing Math doesn't save bytes in your case.
0inputa,b:?"The hypotenuse of this right triangle is";sQ(a*a+b*b)
Screenshot:
cat("The hypotenuse of this right triangle is",round(sqrt(sum(scan()^2)),3))
cat displays its content to STDOUT.
The scan() function takes user's input from keyboard. This input exists as a vector, on which the ^2 is applied (^function is vectorized), and the sum() sums the elements of the vector. sqrt outputs the square-root, which is rounded to 3 decimal places by round(,3)
Thanks to @caird coinheringaahing for noticing that the previous answer didn't round.
"The hypotenuse of this right triangle is "shnhn+A6`*N3eD
This simply outputs the string
"The hypotenuse of this right triangle is "s
hnhn+A6`*N3eD
hn take input and square it
hn take another input and square it
+ add them
A6` push 10^6
* multiply the sum with that number
N take integer square root
3eD output with three places of precision
implicit output
,²S½ær3µ,“¡ÆC⁷⁺ɱSoṿȤç½?⁶Ẏtḍỵŀ»ṚK
There is probably a better string compression that allows me to get around needing to join with spaces but I was having trouble finding it.
Explanation:
,²S½ær3µ,“...»ṚK Example inputs: 3, 4
, Pair the inputs. Result: [3, 4]
² Square them. Result: [9, 16]
S Sum them. Result: 25
½ Get the square root of the sum. Result: 5
ær3 Round to 3 decimal places. Result: 5
µ Take the result of that... Result: 5
“...» ...and the compressed string Result: "The hypotenuse of this right triangle is"
, And put them into a pair. Result: [5, "The hypotenuse of this right triangle is"]
Ṛ Reverse that. Result: ["The hypotenuse of this right triangle is", 5]
k Join it with spaces. Result: "The hypotenuse of this right triangle is 5.0"
Implicit output.
only three decimal places means less than or equal to three decimal places, the output looks fine.