원이 겹치나요?


21

중심의 좌표와 2 개의 원의 반지름이 주어지면 겹치거나 겹치지 않는 정확한 값을 출력합니다.

입력

  • STDIN 또는 이와 동등한 함수 인수를 통해 입력을받을 수 있지만 변수는 아닙니다. 원하는 순서대로 단일 변수 (목록, 문자열 등) 또는 여러 입력 / 인수로 사용할 수 있습니다.

  • 입력은 6 개의 실수입니다. 이 수레는 소수점 이하 3 자리입니다. 좌표는 양수 또는 음수 일 수 있습니다. 반지름은 양수입니다.

산출

  • STDOUT 또는 함수 리턴을 통해 출력 할 수 있습니다.

  • 프로그램에는 정확히 두 개의 고유 한 출력이 있어야합니다. 하나는 True 값 (원은 겹침)과 다른 하나는 False 출력 (겹치지 않음)입니다.

테스트 사례

(입력은 [(x1, y1, r1), (x2, y2, r2)]테스트 케이스 의 튜플 목록으로 제공되며 모든 형식으로 입력 할 수 있습니다)

참된

[(5.86, 3.92, 1.670), (11.8, 2.98, 4.571)]
[(8.26, -2.72, 2.488), (4.59, -2.97, 1.345)]
[(9.32, -7.77, 2.8), (6.21, -8.51, 0.4)]

그릇된

[(4.59, -2.97, 1.345), (11.8, 2.98, 4.571)]
[(9.32, -7.77, 2.8), (4.59, -2.97, 1.345)]
[(5.86, 3.92, 1.670), (6.21, -8.51, 0.4)]

이것은 코드 골프이며, 가장 짧은 대답은 바이트입니다.


4
두 개의 원이 외부에 닿으면 무엇을 반환해야합니까?
JungHwan Min

6
"터치지만 겹치지 않는"에 대한 기술 용어는 "접선"이며 다른 곳에서는 형상에 있습니다.
dmckee

2
수레를 취하는 것은 꽤 엄격한 요구 사항처럼 보입니다. 좀 더 일반적인 표현으로 긴장을 풀 수 있습니까? Brain-Flak 에서이 문제를 해결하고 싶지만 IEEE floats를 구현하는 데 시간이 걸리지 않을 것입니다. 그렇게하면 어쨌든 바이트 수의 90 %가되어 float 구현을 골프로 칠 것입니다.
밀 마법사

4
또한 많은 경우에 부동 소수점이 "소수점 3 자리"까지 정확하지 않다는 점을 지적하고 싶습니다. 나는 당신이 대답을 어떻게 처리하고 싶은지 잘 모르겠지만, 지금 약간 혼란 스럽습니다.
밀 마법사

2
수레가 어떻게 작동하는지 근본적으로 오해하고 있다고 생각합니다. 고정 크기이기 때문에 값이 클수록 정밀도가 떨어집니다. 부동 소수점이 소수점 이하 3 자리 내의 모든 값을 정확하게 표현할 수없는 지점이 있습니다. 또한 불필요한 제한을 제거하기위한 시도를 편집하지 않는 것이 좋습니다.
Mego

답변:


18

젤리 , 5 바이트

IA<S}

두 개의 복소수 (중심)를 첫 번째 인수로 사용하고 두 개의 실수 (반경)를 두 번째 인수로 사용합니다.

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

작동 원리

IA<S}  Main link.
       Left argument:  [x1 + iy1, x2 + iy2]
       Right argument: [r1, r2]

I      Increments; yield (x2 - x1) + i(y2 - y1).
 A     Absolute value; yield √((x2 - x1)² + (y2 - y1)²).
   S}  Take the sum of the right argument, yielding r1 + r2.
  <    Compare the results.

젠장, 좌표에 복잡한 숫자를 사용하는 것을 잊었습니다. 좋은 것! : D
HyperNeutrino

A여기서 관심이없는 결과 는 행 벡터 "중심"의 표준으로 간주됩니까? ( ÆḊ자체는 복잡한 내용으로 오류가 발생합니다.)
Jonathan Allan

1
@JonathanAllan 예, A중심 거리를 차이 벡터의 표준으로 계산합니다.
데니스

11

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

입력을 6 개의 고유 변수 x1 , y1 , r1 , x2 , y2 , r2 로 취합니다 .

(x,y,r,X,Y,R)=>Math.hypot(x-X,y-Y)<r+R

테스트 사례


이전에 Math.hypot을 보지 못한 사람에게 적합 합니다.
Pureferret


@ V.Courtois 매개 변수를 전달하는 방법이 메서드 선언과 일치하지 않습니다. 이어야합니다 a:Double,x:Double,b:Double,y:Double,r:Double,q:Double.
Arnauld

1
@Arnauld 우 ~ 감사합니다! 별도로 게시해야합니까?
V. Courtois

@ V.Courtois는 물론이다. 해봐!
Arnauld


7

MATL , 5 바이트

ZPis<

입력 형식은 다음과 같습니다

[x1, y1]
[x2, y2]
[r1, r2]

온라인으로 사용해보십시오! 또는 모든 테스트 사례를 확인하십시오. .

작동 원리

ZP   % Take two vectors as input. Push their Euclidean distance
i    % Input the vector of radii
s    % Sum of vector
<    % Less than?

그것이 나인지 확실하지 않지만 평가판 링크를 사용하고 실행을 누르면 '오류 서버의 응답을 디코딩 할 수 없습니다'라는 메시지가 나타납니다. 도움이 확실하지는 않지만 (ab) 복잡한 숫자를 사용하여 젤리 답변?
데니스 Jaheruddin

@DennisJaheruddin Hey, 다시 만나서 반가워요! (1) 비난 캐싱. 하드 새로 고침을 시도 했습니까? (2) 내가했다, 그러나 나는 또한 생각 5(바이트 -|대신 ZP)
루이스 Mendo

방화벽이라고 생각합니다. 이제 -r2대신에 비슷한 형식의 입력 형식 r2이 도움이 될지 궁금합니다. 왜냐하면 2 개의 차이점과 추가 대신 3 개의 차이점이 필요하기 때문입니다. 너무 깊이 들어가기 전에 더 잘 실행해야합니다!
데니스 Jaheruddin

하나의 입력을 부정하는 것이 입력 형식으로 수용 가능하다고 생각하지 않습니다. Try It Online 서비스에 문제가 있으면 여기에 보고 하시겠습니까?
Luis Mendo

6

R , 39 바이트

function(k,r)dist(matrix(k,2,2))<sum(r)

입력을 k=c(x1,x2,y1,y2)받고 r=c(r1,r2); FALSE탄젠트 서클의 경우를 반환 합니다.

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

27 바이트 :

function(m,r)dist(m)<sum(r)

행 중심과 반지름 벡터로 주어진 원 중심을 가진 행렬로 입력을받습니다.

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


-2 바이트function(k,r)dist(matrix(k,2))<sum(r)
djhurio

무엇에 대해 dist(matrix(scan(),2))<sum(scan())?
djhurio

6

파이썬 , 40 바이트

lambda x,y,r,X,Y,R:abs(x-X+(y-Y)*1j)<r+R

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

파이썬의 복잡한 산술을 사용하여 두 중심 사이의 거리를 계산합니다. 입력 포인트를 복잡한 숫자로 직접 가져올 수 없다고 가정하므로 코드는 다음과 같이 표현합니다 x+y*1j.





4

APL (Dyalog), 10 bytes

Prompts for circle centers as list of two complex numbers, then for radii as list of two numbers

(+/⎕)>|-/

Try it online!

(+/⎕) [is] the sum of the radii

> greater than

| the magnitude of

-/⎕ the difference in centers


3

Mathematica, 16 bytes

Norm[#-#2]<+##3&

Input: [{x1, y1}, {x2, y2}, r1, r2]


Mathematica has a RegionIntersection builtin, but that alone is 18 bytes long...

Built-in version:

RegionIntersection@##==EmptyRegion@2&

Takes 2 Disk objects. [Disk[{x1, y1}, r1], Disk[{x2, y2}, r2]].





3

Java 8, 41 38 bytes

(x,y,r,X,Y,R)->Math.hypot(x-X,y-Y)<r+R

Try it here.

Apparently, Java also has Math.hypot, which is 3 bytes shorter.

EDIT: Just realized this answer is now exactly the same as @OlivierGrégoire's Java 8 answer, so please upvote him instead of me if you like the 38-byte answer.

Old answer (41 bytes):

(x,y,r,X,Y,R)->(x-=X)*x+(y-=Y)*y<(r+=R)*r

Try it here.


1
Oh! So that's why I got 3 upvotes today, but 0 when the challenge was posted? ^^ I was wondering what triggered this weird behavior ;) Since I like my answer, and you posted the same, you get a +1 as well! :p
Olivier Grégoire


2

Perl 6, 13 bytes

*+*>(*-*).abs

Try it online!

The first two arguments are the radii, in either order. The third and fourth arguments are the coordinates of the centers, as complex numbers, in either order.


2

Taxi, 1582 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to Tom's Trims.Pickup a passenger going to Tom's Trims.Go to Tom's Trims:n.[a]Go to Post Office:s.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 5 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 r.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Addition Alley.Go to Tom's Trims:s 1 r 3 r.Pickup a passenger going to The Babelfishery.Switch to plan "b" if no one is waiting.Switch to plan "a".[b]Go to Addition Alley:n 1 r 1 l 3 l 1 l.Pickup a passenger going to Magic Eight.Go to Post Office:n 1 r 1 r 3 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 5 l 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 r.Switch to plan "c" if no one is waiting.'1' is waiting at Writer's Depot.[c]'0' is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.

Try it online!

Outputs 1 for overlapping circles.
Outputs 0 for non-overlapping circles (including tangential circles).

Ungolfed / formatted:

Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to Tom's Trims.
Pickup a passenger going to Tom's Trims.
Go to Tom's Trims: north.
[a]
Go to Post Office: south.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: north 5th left.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st right.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to Addition Alley.
Go to Tom's Trims: south 1st right 3rd right.
Pickup a passenger going to The Babelfishery.
Switch to plan "b" if no one is waiting.
Switch to plan "a".
[b]
Go to Addition Alley: north 1st right 1st left 3rd left 1st left.
Pickup a passenger going to Magic Eight.
Go to Post Office: north 1st right 1st right 3rd right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: north 5th left 1st left.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left.
Pickup a passenger going to Multiplication Station.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to Magic Eight.
Go to Magic Eight: south 1st right.
Switch to plan "c" if no one is waiting.
'1' is waiting at Writer's Depot.
[c]
'0' is waiting at Writer's Depot.
Go to Writer's Depot: west 1st left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.

2

C#, 50 41 bytes

(x,y,r,X,Y,R)=>(x-=X)*x+(y-=Y)*y<(r+=R)*r

Saved 9 bytes thanks to @KevinCruijssen.


Can't you save a few bytes there by writing (r+R)*2 instead of (r+R)+(r+R)?
Ian H.

@IanH. Yeah don't know how I missed that.
TheLethalCoder

Am I missing something or does this not work?
Ian H.

@IanH. I'd made a typo, the + on the RHS should have been a *.
TheLethalCoder

And my feedback even made that worse. Good job on the solution though!
Ian H.


1

PostgreSQL, 41 characters

prepare f(circle,circle)as select $1&&$2;

Prepared statement, takes input as 2 parameters in any circle notation.

Sample run:

Tuples only is on.
Output format is unaligned.
psql (9.6.3, server 9.4.8)
Type "help" for help.

psql=# prepare f(circle,circle)as select $1&&$2;
PREPARE

psql=# execute f('5.86, 3.92, 1.670', '11.8, 2.98, 4.571');
t

psql=# execute f('8.26, -2.72, 2.488', '4.59, -2.97, 1.345');
t

psql=# execute f('9.32, -7.77, 2.8', '6.21, -8.51, 0.4');
t

psql=# execute f('4.59, -2.97, 1.345', '11.8, 2.98, 4.571');
f

psql=# execute f('9.32, -7.77, 2.8', '4.59, -2.97, 1.345');
f

psql=# execute f('5.86, 3.92, 1.670', '6.21, -8.51, 0.4');
f

1

Java, 50 38 bytes

(x,y,r,X,Y,R)->Math.hypot(x-X,y-Y)<r+R

Using ideas in other answers, this can be shortened to 38 like so: (x,y,r,X,Y,R)->Math.hypot(x-X,y-Y)<r+R. In fact, just realised this is the exact same as Arnauld's JavaScript answer.
laszlok

Thanks... This answer was nevee intended to be golfed... i thought it was such a simple challenge there wouldn't be anything that can be golfed...
Roman Gräf

I'm afraid your answer is now exactly the same as the already posted answer by @OlivierGrégoire..
Kevin Cruijssen

1

x86 Machine Code (with SSE2), 36 bytes

; bool CirclesOverlap(double x1, double y1, double r1,
;                     double x2, double y2, double r2);
F2 0F 5C C3        subsd   xmm0, xmm3      ; x1 - x2
F2 0F 5C CC        subsd   xmm1, xmm4      ; y1 - y2
F2 0F 58 D5        addsd   xmm2, xmm5      ; r1 + r2
F2 0F 59 C0        mulsd   xmm0, xmm0      ; (x1 - x2)^2
F2 0F 59 C9        mulsd   xmm1, xmm1      ; (y1 - y2)^2
F2 0F 59 D2        mulsd   xmm2, xmm2      ; (r1 + r2)^2
F2 0F 58 C1        addsd   xmm0, xmm1      ; (x1 - x2)^2 + (y1 - y2)^2
66 0F 2F D0        comisd  xmm2, xmm0
0F 97 C0           seta    al              ; ((r1 + r2)^2) > ((x1 - x2)^2 + (y1 - y2)^2)
C3                 ret

The above function accepts descriptions of two circles (x- and y-coordinates of center point and a radius), and returns a Boolean value indicating whether or not they intersect.

It uses a vector calling convention, where the parameters are passed in SIMD registers. On x86-32 and 64-bit Windows, this is the __vectorcall calling convention. On 64-bit Unix/Linux/Gnu, this is the standard System V AMD64 calling convention.

The return value is left in the low byte of EAX, as is standard with all x86 calling conventions.

This code works equally well on 32-bit and 64-bit x86 processors, as long as they support the SSE2 instruction set (which would be Intel Pentium 4 and later, or AMD Athlon 64 and later).

AVX version, still 36 bytes

If you were targeting AVX, you would probably want to add a VEX prefix to the instructions. This does not change the byte count; just the actual bytes used to encode the instructions:

; bool CirclesOverlap(double x1, double y1, double r1,
;                     double x2, double y2, double r2);
C5 FB 5C C3      vsubsd   xmm0, xmm0, xmm3   ; x1 - x2
C5 F3 5C CC      vsubsd   xmm1, xmm1, xmm4   ; y1 - y2
C5 EB 58 D5      vaddsd   xmm2, xmm2, xmm5   ; r1 + r2
C5 FB 59 C0      vmulsd   xmm0, xmm0, xmm0   ; (x1 - x2)^2
C5 F3 59 C9      vmulsd   xmm1, xmm1, xmm1   ; (y1 - y2)^2
C5 EB 59 D2      vmulsd   xmm2, xmm2, xmm2   ; (r1 + r2)^2
C5 FB 58 C1      vaddsd   xmm0, xmm0, xmm1   ; (x1 - x2)^2 + (y1 - y2)^2
C5 F9 2F D0      vcomisd  xmm2, xmm0
0F 97 C0         seta     al                 ; ((r1 + r2)^2) > ((x1 - x2)^2 + (y1 - y2)^2)
C3               ret

AVX instructions have the advantage of taking three operands, allowing you to do non-destructive operations, but that doesn't really help us to compact the code any here. However, mixing instructions with and without VEX prefixes can result in sub-optimal code, so you generally want to stick with all AVX instructions if you're targeting AVX, and in this case, it doesn't even hurt your byte count.



1

PHP, 66 bytes

<?php $i=$argv;echo hypot($i[1]-$i[4],$i[2]-$i[5])<$i[3]+$i[6]?:0;

Try it online!

Runs from the command line, taking input as 6 command-line parameter arguments, and prints 1 if the circles overlap, else 0.


0

Julia 0.6.0 (46 bytes)

a->((a[1]-a[2])^2+(a[3]-a[4])^2<(a[5]+a[6])^2)

0

Clojure, 68 bytes

#(<(+(*(- %4 %)(- %4 %))(*(- %5 %2)(- %5 %2)))(*(+ %6 %3)(+ %6 %3)))

Takes six arguments: x1, y1, r1, x2, y2, r2. Returns true or false.

Sadly, Clojure does not have a pow function of some sorts. Costs a lot of bytes.


0

Actually, 8 bytes

-)-(h@+>

Try it online!

Explanation:

-)-(h@+>  (implicit input: [y1, y2, x1, x2, r1, r2])
-         y2-y1 ([y2-y1, x1, x2, r1, r2])
 )-       move to bottom, x1-x2 ([x1-x2, r1, r2, y2-y1])
   (h     move from bottom, Euclidean norm ([sqrt((y2-y1)**2+(x2-x1)**2), r1, r2])
     @+   r1+r2 ([r1+r2, norm])
       >  is r1+r2 greater than norm?

0

R (+pryr), 31 bytes

pryr::f(sum((x-y)^2)^.5<sum(r))

Which evaluates to the function

function (x, y, z) 
sum((x - y)^2)^0.5 < sum(z)

Where x are the coordinates of circle 1, y are the coordinates of circle 2 and z the radii.

Calculates the distance between the two centers using Pythagoras and tests if that distance is smaller than the sum of the radii.

Makes use of R's vectorisation to simultaneously calculate (x1-x2)^2 and (y1-y2)^2. These are then summed and squarely rooted.


0

Go, 93 bytes

package q
import c "math/cmplx"
func o(a,b complex128,r,R float64)bool{return c.Abs(b-a)<r+R}

Fairly simple algorithm, same as several other answers, except it uses the built-in complex type and calls math/cmplx.Abs().

Taking the radii as complex numbers doesn't help, because the cast to float64 adds more bytes than the variable declaration saves (can't do float64 < complex128).

Try it online! Includes the test cases, and uses package main instead of a library.

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