ポリゴンの重心を見つける


16

ウィキペディアから:

n個の頂点(x 0、y 0)、(x 1、y 1)、...、(x n --1、y n-1)で定義される非自己交差閉多角形の重心は、ポイント(C x、C y)、ここで

重心の式

また、Aはポリゴンの署名された領域です。

多角形の面積の式

これらの式では、頂点には、ポリゴンの周囲に沿った出現順に番号が付けられていると想定されています。さらに、頂点(x n、y n)は(x 0、y 0)と同じであると想定されます。これは、最後のケースでi + 1i = 0にループする必要があることを意味します。ポイントに時計回りに番号が付けられている場合、上記のように計算された領域Aは負の符号を持つことに注意してください。ただし、この場合でも重心座標は正確です。


  • 頂点のリストを順番に(時計回りまたは反時計回りに)指定して、頂点によって表される自己交差しない閉じたポリゴンの重心を見つけます。
    • 役立つ場合は、入力をCWのみ、またはCCWのみと想定することができます。これが必要な場合は、答えでそう言ってください。
  • 座標は整数である必要はなく、負の数値を含む場合があります。
  • 入力は常に有効で、少なくとも3つの頂点が含まれます。
  • ご使用の言語のネイティブ浮動小数点データ型に適合する入力のみを処理する必要があります。
  • 入力番号には常に小数点が含まれると想定できます。
  • 入力整数は.またはで終わると仮定できます.0
  • 入力には複素数を使用できます。
  • 出力は、1000分の1単位で正確でなければなりません。

[(0.,0.), (1.,0.), (1.,1.), (0.,1.)]        -> (0.5, 0.5)
[(-15.21,0.8), (10.1,-0.3), (-0.07,23.55)]  -> -1.727 8.017
[(-39.00,-55.94), (-56.08,-4.73), (-72.64,12.12), (-31.04,53.58), (-30.36,28.29), (17.96,59.17), (0.00,0.00), (10.00,0.00), (20.00,0.00), (148.63,114.32), (8.06,-41.04), (-41.25,34.43)]   -> 5.80104769975, 15.0673812762

座標平面上の各ポリゴンが見えすぎる場合は、このページの[編集]メニューに角括弧なしで座標を貼り付けます

このPolygon Centroid Point Calculatorを使用して結果を確認しましたたが、これはひどいです。すべての頂点を一度に入力できるもの、または-最初に入力したときに記号を消去しようとしないものは見つかりませんでした。人々が答える機会を得た後、あなたの使用のために私のPythonソリューションを投稿します。


すべてのxとyを平均化するはるかに単純な手法は、最初の2つのセットで機能しますが、3番目のセットでは機能しません。何が違いをもたらすのだろうか?
-ETHproductions

1
@ETHproductions 3番目のポリゴンは凸面ではありません。
ジョンファンミン

1
@ETHproductions円を多角形で近似する場合、重心にほとんど影響を与えず多角形を凸状に保ちながら、その点に近い点をさらに使用することにより、円上の点の近くで平均点を任意に移動できます。
クリスチャンシーバーズ

2
@ETHproductions実際に凸性が理由ではありません。すべてxのsとysを平均化すると、体全体に分散するのではなく、頂点にすべてのウェイトが配置されます。最初の方法は規則的であるため機能するため、どちらの方法も対称中心になります。三角形の場合、両方の方法が同じポイントにつながるため、2番目の方法が機能します。
トンホスペル

1
I / Oに複素数を使用できますか?
xnor

回答:


16

ゼリー25 24 22 21 18バイト

S×3÷@×"
ṙ-żµÆḊçS€S

問題に示されている式を適用します。

@ Jonathan Allanの助けを借りて3バイトを節約しました

オンラインでお試しください!またはすべてのテストケースを検証します。

説明

S×3÷@×"  Helper link. Input: determinants on LHS, sum of pairs on RHS
S        Sum the determinants
 ×3      Multiply by 3
     ×"  Vectorized multiply between determinants and sums
   ÷@    Divide that by the determinant sum multipled by 3 and return

ṙ-żµÆḊçS€S  Main link. Input: 2d list of points
ṙ-          Rotate the list of points by 1 to the right
  ż         Interleave those with the original points
            This creates all overlapping slices of length 2
   µ        Start new monadic chain
    ÆḊ      Get the determinant of each slice
       S€   Get the sum of each slice (sum of pairs of points)
      ç     Call the helper link
         S  Sum and return

あなたは置き換えることができṁL‘$ṡ2ṙ1ż@żṙ1$
ジョナサン・アラン

@JonathanAllanおかげで、また、私はで回転させることができṙ-ż、スワップを回避し、別のバイトを保存するために
マイル

はい、もちろんです!
ジョナサンアラン

17

Mathematica、23バイト

RegionCentroid@*Polygon

テイクTHATを、ゼリーを!

編集:1つは単にゼリーを倒しません...

説明

Polygon

指定されたポイントに頂点を持つポリゴンを生成します。

RegionCentroid

多角形の重心を見つけます。


2
さて、あなたが私を打つが、私が持っているものより短い方法はおそらくあります、私はまだゼリーの完全な理解を持っていない
マイル

3
@miles aw ... :(
ジョンファンミン

4

J、29バイト

2+/@(+/\(*%3*1#.])-/ .*\)],{.

問題に示されている式を適用します。

使用法

   f =: 2+/@(+/\(*%3*1#.])-/ .*\)],{.
   f 0 0 , 1 0 , 1 1 ,: 0 1
0.5 0.5
   f _15.21 0.8 , 10.1 _0.3 ,: _0.07 23.55
_1.72667 8.01667
   f _39 _55.94 , _56.08 _4.73 , _72.64 12.12 , _31.04 53.58 , _30.36 28.29 , 17.96 59.17 , 0 0 , 10 0 , 20 0 , 148.63 114.32 , 8.06 _41.04 ,: _41.25 34.43
5.80105 15.0674

説明

2+/@(+/\(*%3*1#.])-/ .*\)],{.  Input: 2d array of points P [[x1 y1] [x2 y2] ...]
                           {.  Head of P
                         ]     Get P
                          ,    Join, makes the end cycle back to the front
2                              The constant 2
2                      \       For each pair of points
                  -/ .*        Take the determinant
2    +/\                       Sum each pair of points
         *                     Multiply the sum of each pair by its determinant
          %                    Divide each by
             1#.]              The sum of the determinants
           3*                  Multiplied by 3
 +/@                           Sum and return

4

マキシマ、124118116112106バイト

f(l):=(l:endcons(l[1],l),l:sum([3,l[i-1]+l[i]]*determinant(matrix(l[i-1],l[i])),i,2,length(l)),l[2]/l[1]);

私はMaximaに慣れていないので、どんなヒントでも大歓迎です。

使用法:

(%i6) f([[-15.21,0.8], [10.1,-0.3], [-0.07,23.55]]);
(%o6)              [- 1.726666666666668, 8.016666666666668]

3

ラケット420バイト

(let*((lr list-ref)(getx(lambda(i)(lr(lr l i)0)))(gety(lambda(i)(lr(lr l i)1)))(n(length l))(j(λ(i)(if(= i(sub1 n))0(add1 i))))
(A(/(for/sum((i n))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i))))2))
(cx(/(for/sum((i n))(*(+(getx i)(getx(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A)))
(cy(/(for/sum((i n))(*(+(gety i)(gety(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A))))
(list cx cy))

ゴルフをしていない:

(define(f l)
  (let* ((lr list-ref)
         (getx (lambda(i)(lr (lr l i)0)))
         (gety (lambda(i)(lr (lr l i)1)))
         (n (length l))
         (j (lambda(i) (if (= i (sub1 n)) 0 (add1 i))))
         (A (/(for/sum ((i n))
                (-(* (getx i) (gety (j i)))
                  (* (getx (j i)) (gety i))))
              2))
         (cx (/(for/sum ((i n))
                 (*(+(getx i)(getx (j i)))
                   (-(*(getx i)(gety (j i)))
                     (*(getx (j i))(gety i)))))
               (* 6 A)))
         (cy (/(for/sum ((i n))
                 (*(+(gety i)(gety (j i)))
                   (-(*(getx i)(gety (j i)))
                     (*(getx (j i))(gety i)))))
               (* 6 A))))
    (list cx cy)))

テスト:

(f '[(-15.21 0.8)  (10.1 -0.3)  (-0.07 23.55)] ) 
(f '[(-39.00 -55.94)  (-56.08 -4.73)  (-72.64 12.12)  (-31.04 53.58) 
     (-30.36 28.29)  (17.96 59.17)  (0.00 0.00)  (10.00 0.00)  
     (20.00 0.00) (148.63 114.32)  (8.06 -41.04)  (-41.25 34.43)])

出力:

'(-1.7266666666666677 8.01666666666667)
'(5.8010476997538465 15.067381276150996)

3

R、129 127バイト

function(l){s=sapply;x=s(l,`[`,1);y=s(l,`[`,2);X=c(x[-1],x[1]);Y=c(y[-1],y[1]);p=x*Y-X*y;c(sum((x+X)*p),sum((y+Y)*p))/sum(p)/3}

入力としてタプルのRリストを受け取る名前のない関数。指定された同等のものは、たとえば次を使用して呼び出すことができます。

f(list(c(-15.21,0.8),c(10.1,-0.3),c(-0.07,23.55)))

非ゴルフと説明

f=function(l){s=sapply;                           # Alias for sapply
              x=s(l,`[`,1);                       # Split list of tuples into vector of first elements
              y=s(l,`[`,2);                       # =||= but for second element 
              X=c(x[-1],x[1]);                    # Generate a vector for x(i+1)
              Y=c(y[-1],y[1]);                    # Generate a vector for y(i+1)
              p=x*Y-X*y;                          # Calculate the outer product used in both A, Cx and Cy
              c(sum((x+X)*p),sum((y+Y)*p))/sum(p)/3    # See post for explanation
}

最後のステップは、( c(sum((x+X)*p),sum((y+Y)*p))/sum(p)*2/6)の両方を算出するベクトル化方法であるCxCy。以下のための式中の和CxCyベクトルに格納され、その結果「の合計によって分割されますA*2/6。例えば:

(SUMinCx, SUMinCy) / SUMinA / 3

、そして暗黙的に印刷されます。

Rフィドルで試してみてください


*2/6たぶん/3
mbomb007

@ mbomb007それはとても骨の折れるほど明白で、私は他の部分のゴルフに巻き込まれたと思います。/肩をすくめる
Billywob

エレガント、sapplyこれらのリストを扱うためにあなたが使用するのが好きです!ここにはゴルフの余地があるかもしれませんが、許容される入力がどれほど柔軟かはわかりません。のように一連の座標だけを入力c(-15.21,0.8,10.1,-0.3,-0.07,23.55)できる場合、関数の最初の行をに置き換えることで17バイトを節約できますy=l[s<-seq(2,sum(1|l),2)];x=l[-s];。つまり、のyすべての偶数インデックス要素に設定しlxすべての奇数インデックス要素に設定します。
rturnbull

ただし、のように行列(または配列)を入力できる場合はmatrix(c(-15.21,0.8,10.1,-0.3,-0.07,23.55),2)さらに便利です。関数の先頭はでありx=l[1,];y=l[2,];、35バイトを節約できます。(入力行列は転置できますx=l[,1];y=l[,2];。その場合。)もちろん、すべての最も簡単な解決策は、xyが別々のベクトルとして入力される場合ですがfunction(x,y)、それは許可されないと思います...
rturnbull

@rturnbull私はコメントでOPを尋ねましたが、彼はタプルのリストを特に望んでいました(もちろんRでは非常に不便です)ので、マトリックスアプローチが許可されているとは思わない。そして、たとえそうであったとしても、入力はベクトル部分でなければなりません(つまり、c(...))ず、行列変換は関数内で実行する必要があります。
ビリーウォブ

2

Python、156 127バイト

def f(p):n=len(p);p=p+p[:1];i=s=0;exec'd=(p[i].conjugate()*p[i+1]).imag;s+=d;p[i]=(p[i]+p[i+1])*d;i+=1;'*n;print sum(p[:n])/s/3

ゴルフをしていない:

def f(points):
  n = len(points)
  points = points + [points[0]]
  determinantSum = 0
  for i in range(n):
    determinant = (points[i].conjugate() * points[i+1]).imag
    determinantSum += determinant
    points[i] = (points[i] + points[i+1]) * determinant
  print sum(points[:n]) / determinantSum / 3

イデオネ。

これは、ポイントの各ペアを[x, y]複素数としてx + y*j受け取り、結果の重心を同じ形式の複素数として出力します。

点の対について[a, b][c, d]、価値a*d - b*c点の各ペアのために必要とされる行列の行列式から計算することができます

| a b |
| c d |

複雑な演算を使用して、複素数値a + b*jc + d*jとして使用することができます

conjugate(a + b*j) * (c + d*j)
(a - b*j) * (c + d*j)
(a*c + b*d) + (a*d - b*c)*j

虚数部は行列式に等しいことに注意してください。また、複素数値を使用すると、他の操作でコンポーネントごとにポイントを簡単に合計できます。


2

R + sp(46バイト)

想定 spパッケージがインストールされているとます(https://cran.r-project.org/web/packages/sp/

(例えば、頂点のリストを取りますlist(c(0.,0.), c(1.,0.), c(1.,1.), c(0.,1.))

ポリゴンの「実験室」が重心であるという事実を利用します。

function(l)sp::Polygon(do.call(rbind,l))@labpt

2

JavaScript(ES6)、102

数式の直接実装

l=>[...l,l[0]].map(([x,y],i)=>(i?(a+=w=t*y-x*u,X+=(t+x)*w,Y+=(u+y)*w):X=Y=a=0,t=x,u=y))&&[X/3/a,Y/3/a]

テスト

f=
l=>[...l,l[0]].map(([x,y],i)=>(i?(a+=w=t*y-x*u,X+=(t+x)*w,Y+=(u+y)*w):X=Y=a=0,t=x,u=y))&&[X/3/a,Y/3/a]

function go()
{
  var c=[],cx,cy;
  // build coordinates array
  I.value.match(/-?[\d.]+/g).map((v,i)=>i&1?t[1]=+v:c.push(t=[+v]));
  console.log(c+''),
  [cx,cy]=f(c);
  O.textContent='CX:'+cx+' CY:'+cy;
  // try to display the polygon
  var mx=Math.max(...c.map(v=>v[0])),
    nx=Math.min(...c.map(v=>v[0])),
    my=Math.max(...c.map(v=>v[1])),
    ny=Math.min(...c.map(v=>v[1])),  
    dx=mx-nx, dy=my-ny,
    ctx=C.getContext("2d"),
    cw=C.width, ch=C.height,
    fx=(mx-nx)/cw, fy=(my-ny)/ch, fs=Math.max(fx,fy)
  C.width=cw
  ctx.setTransform(1,0,0,1,0,0);
  ctx.beginPath();
  c.forEach(([x,y],i)=>ctx.lineTo((x-nx)/fs,(y-ny)/fs));
  ctx.closePath();
  ctx.stroke();
  ctx.fillStyle='#ff0000';
  ctx.fillRect((cx-nx)/fs-2,(cy-ny)/fs-2,5,5);
}
go()
#I { width:90% }
#C { width:90%; height:200px;}
<input id=I value='[[-15.21,0.8], [10.1,-0.3], [-0.07,23.55]]'>
<button onclick='go()'>GO</button>
<pre id=O></pre>
<canvas id=C></canvas>


1

Python 2、153バイト

複素数は使用しません。

P=input()
A=x=y=0;n=len(P)
for i in range(n):m=-~i%n;a=P[i][0];b=P[i][1];c=P[m][0];d=P[m][1];t=a*d-b*c;A+=t;x+=t*(a+c);y+=t*(b+d)
k=1/(3*A);print x*k,y*k

オンラインで試す

ゴルフをしていない:

def centroid(P):
    A=x=y=0
    n=len(P)
    for i in range(n):
        m=-~i%n
        x0=P[i][0];y0=P[i][1]
        x1=P[m][0];y1=P[m][1]
        t = x0*y1 - y0*x1
        A += t/2.
        x += t * (x0 + x1)
        y += t * (y0 + y1)
    k = 1/(6*A)
    x *= k
    y *= k
    return x,y

1

実際、45 40 39バイト

これは、マイルのゼリーの回答に似たアルゴリズムを使用します。ドット積を使用して行列式を計算するより短い方法がありますが、現在のところ、実数のドット積にはバグがあり、フロートのリストでは機能しません。ゴルフの提案を歓迎します。オンラインでお試しください!

;\Z♂#;`i¥`M@`i│N@F*)F@N*-`M;Σ3*)♀*┬♂Σ♀/

アンゴルフ

         Implicit input pts.
;\       Duplicate pts, rotate right.
Z        Zip rot_pts and pts together.
♂#       Convert the iterables inside the zip to lists
         (currently necessary due to a bug with duplicate)
;        Duplicate the zip.
`...`M   Get the sum each pair of points in the zip.
  i        Flatten the pair to the stack.
  ¥        Pairwise add the two coordinate vectors.
@        Swap with the other zip.
`...`M   Get the determinants of the zip.
  i│       Flatten to stack and duplicate entire stack.
           Stack: [a,b], [c,d], [a,b], [c,d]
  N@F*)    Push b*c and move it to BOS.
  F@N*     Push a*d.
  -        Get a*d-b*c.
;Σ3*)    Push 3 * sum(determinants) and move it to BOS.
♀*       Vector multiply the determinants and the sums.
┬        Transpose the coordinate pairs in the vector.
♂Σ       Sum the x's, then the y's.
♀/       Divide the x and y of this last coordinate pair by 3*sum(determinants).
         Implicit return.

より短く、非競争的なバージョン

これは、複素数を使用する別の24バイトバージョンです。このチャレンジより後のバグ修正に依存しているため、非競争的です。オンラインでお試しください!

;\│¥)Z`iá*╫@X`M;Σ3*)♀*Σ/

アンゴルフ

         Implicit input a list of complex numbers, pts.
;\       Duplicate pts, rotate right.
│        Duplicate stack. Stack: rot_pts, pts, rot_pts, pts.
¥)       Pairwise sum the two lists of points together and rotate to BOS.
Z        Zip rot_pts and pts together.
`...`M   Map the following function over the zipped points to get our determinants.
  i        Flatten the list of [a+b*i, c+d*i].
  á        Push the complex conjugate of a+bi, i.e. a-b*i.
  *        Multiply a-b*i by c+d*i, getting (a*c+b*d)+(a*d-b*c)*i.
           Our determinant is the imaginary part of this result.
  ╫@X      Push Re(z), Im(z) to the stack, and immediately discard Re(z).
           This map returns a list of these determinants.
;        Duplicate list_determinants.
Σ3*)     Push 3 * sum(list_determinants) and rotate that to BOS.
♀*Σ      Pairwise multiply the sums of pairs of points and the determinants and sum.
/        Divide that sum by 3*sum(list_determinants).
         Implicit return.

1

C ++ 14、241バイト

struct P{float x;float y;};
#define S(N,T)auto N(P){return 0;}auto N(P a,P b,auto...V){return(T)*(a.x*b.y-b.x*a.y)+N(b,V...);}
S(A,1)S(X,a.x+b.x)S(Y,a.y+b.y)auto f(auto q,auto...p){auto a=A(q,p...,q)*3;return P{X(q,p...,q)/a,Y(q,p...,q)/a};}

出力はヘルパー構造体ですP

ゴルフをしていない:

 //helper struct
struct P{float x;float y;};

//Area, Cx and Cy are quite similar
#define S(N,T)\  //N is the function name, T is the term in the sum
auto N(P){return 0;} \   //end of recursion for only 1 element
auto N(P a,P b,auto...V){ \ //extract the first two elements
  return (T)*(a.x*b.y-b.x*a.y) //compute with a and b
         + N(b,V...); \        //recursion without first element
}

//instantiate the 3 formulas
S(A,1)
S(X,a.x+b.x)
S(Y,a.y+b.y)


auto f(auto q,auto...p){
  auto a=A(q,p...,q)*3; //q,p...,q appends the first element to the end
  return P{X(q,p...,q)/a,Y(q,p...,q)/a};
}

使用法:

f(P{0.,0.}, P{1.,0.}, P{1.,1.}, P{0.,1.})
f(P{-15.21,0.8}, P{10.1,-0.3}, P{-0.07,23.55})

1

Clojureは、177の 156 143バイト

更新:[a b c d 1]関数として使用しているコールバックの代わりに、引数はこのベクターへのインデックスのリストにすぎません。1は、計算時にセンチネル値として使用されますA

更新2:入力ベクトルを1つオフセットするために使用しAlet、で事前計算しません(rest(cycle %))

#(let[F(fn[I](apply +(map(fn[[a b][c d]](*(apply +(map[a b c d 1]I))(-(* a d)(* c b))))%(rest(cycle %)))))](for[i[[0 2][1 3]]](/(F i)(F[4])3)))

元のバージョン:

#(let[F(fn[L](apply +(map(fn[[a b][c d]](*(L[a b c d])(-(* a d)(* c b))))%(conj(subvec % 1)(% 0)))))A(*(F(fn[& l]1))3)](map F[(fn[v](/(+(v 0)(v 2))A))(fn[v](/(+(v 1)(v 3))A))]))

ゴルフの少ないステージでは:

(def f (fn[v](let[F (fn[l](apply +(map
                                    (fn[[a b][c d]](*(l a b c d)(-(* a d)(* c b))))
                                    v
                                    (conj(subvec v 1)(v 0)))))
                  A (* (F(fn[& l] 1)) 3)]
                [(F (fn[a b c d](/(+ a c)A)))
                 (F (fn[a b c d](/(+ b d)A)))])))

F任意のコールバックで合計を実装するヘルパー関数を作成しますl。以下のためにA常にコールバックが戻る1XとY座標のに対し、独自の機能を持っています。(conj(subvec v 1)(v 0))この方法は、それがのトラック維持することは容易である、最初の要素を削除し、最後に追加x_iしてをx_(i+1)。たぶん、特に最後に、まだいくつかの繰り返しを排除する必要があります(map F[...

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.