勾配で地域を分類する


16

定義

K 番目の大きさの正方行列の環N1つの≤K≤天井(N / 2)の要素によって形成されたリストであるk個(N-K + 1)番目の行と列が、無し最初と最後のk-1要素。

例:

マトリックス:

1 2 3 4 5
6 7 8 9 1
8 7 6 5 4
3 2 1 9 8
7 6 5 4 3

リングで区切られた:

+ ------------------- +
| 1 2 3 4 5 |
| + ----------- + |
| 6 | 7 8 9 | 1 |
| | + --- + | |
| 8 | 7 | 6 | 5 | 4 |
| | + --- + | |
| 3 | 2 1 9 | 8 |
| + ----------- + |
| 7 6 5 4 3 |
+ ------------------- +

上記の最初のリングは1,2,3,4,5,1,4,8,3,4,5,6,7,3,8,6、2番目は7,8,9,5,9,1,2,73番目です6

アンNによってNの正の整数の行列が(この課題の目的のために)です。

  • k 番目のリングのすべての整数が(k + 1)番目のリングの整数よりも厳密に大きい場合、で、k1からNまでの任意の整数です (最初のリングの整数は2 番目のリングの整数より大きく、同様に、3番目のものよりも大きい)。例:

    4 5 6 4 7-> 4,5,6,4,7,4,8,5,5,4,6,5,9,5,5,4はすべてよりも高いため
    4 3 2 2 4 3,2,2,3,2,3,3,2のいずれか、これらはすべて1よりも高い
    5 2 1 3 8
    5 3 3 2 5
    9 5 6 4 5
    
  • 行列内のすべての整数が等しい場合、フラット。別の例(おそらく冗長):

    2 2 2 2
    2 2 2 2
    2 2 2 2
    2 2 2 2
    
  • 凸面上のすべての整数場合のk 番目の環は厳密によりも低い(K + 1)番目の環、kは、の間の任意の整数であり、1N (最初のリング上のものは第二にそれより低い、さ順番に3番目のものよりも低くなります)。例:

    1 2 1-> 1と2は両方とも6より小さいため
    2 6 2
    1 2 1
    
  • マトリックスが上記の基準のいずれも満たさない場合に混合されます。例:

    3 3 3 3 3
    3 2 2 2 3
    3 2 3 2 3
    3 2 2 2 3
    3 3 3 3 3
    

チャレンジ

サイズが少なくとも3の正の整数の正方行列が与えられ場合上記の定義に従って分類します。つまり、マトリックスが凹、平坦、凸、混合のいずれであるかに基づいて、4つの異なる一貫した値の1つを出力します。

これらの抜け穴はデフォルトでは禁止されていることに注意しながら、任意のプログラミング言語で競争し、標準的な方法および合理的な形式で入力を受け取り、出力を提供できます。これはであるため、すべての言語の最短の送信(バイト単位)が優先されます。

テストケース

以下に、選択可能なサンプルの例を示します。各カテゴリから6つを選択しました。

凹面

[[3, 3, 3], [3, 1, 3], [3, 3, 3]]
[[2, 3, 4], [5, 1, 6], [7, 8, 9]]
[[19, 34, 45], [34, 12, 14], [13, 13, 13]]
[[3, 4, 3, 4], [4, 2, 1, 3], [3, 1, 2, 4], [4, 3, 4, 3]]
[[4, 5, 6, 4, 7], [4, 3, 2, 2, 4], [5, 2, 1, 3, 8], [5, 3, 3, 2, 5], [9, 5, 6, 4, 5]]
[[7, 7, 7, 7, 7], [7, 6, 6, 6, 7], [7, 6, 5, 6, 7], [7, 6, 6, 6, 7], [7, 7, 7, 7, 7]]

平らな

[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
[[8, 8, 8], [8, 8, 8], [8, 8, 8]]
[[120, 120, 120], [120, 120, 120], [120, 120, 120]]
[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]
[[5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5]]

[[1, 2, 1], [2, 6, 2], [1, 2, 1]]
[[1, 1, 1], [1, 2, 1], [1, 1, 1]]
[[19, 34, 45], [34, 76, 14], [13, 6, 13]]
[[3, 3, 3, 3], [3, 4, 4, 3], [3, 4, 4, 3], [3, 3, 3, 3]]
[[192, 19, 8, 6], [48, 324, 434, 29], [56, 292, 334, 8], [3, 4, 23, 23]]
[[291, 48, 7, 5], [47, 324, 454, 30], [58, 292, 374, 4], [9, 2, 53, 291]]

混合

[[1, 2, 3], [4, 5, 9], [6, 7, 8]]
[[10, 14, 21], [100, 8, 3], [29, 2, 19]]
[[5, 5, 5, 5], [5, 4, 4, 5], [5, 4, 6, 5], [5, 5, 5, 5]]
[[3, 3, 3, 3], [3, 1, 2, 3], [3, 3, 2, 3], [3, 3, 3, 3]]
[[12, 14, 15, 16], [12, 18, 18, 16], [12, 11, 11, 16], [12, 14, 15, 16]]
[[5, 5, 5, 5, 5], [5, 4, 4, 4, 5], [5, 4, 6, 4, 5], [5, 4, 4, 4, 5], [5, 5, 5, 5, 5]]

このチャレンジは、以前Sandboxに投稿されました。貴重なフィードバックをいただいた方々に感謝します。
ミスターXcoder

2
いろいろな言語でこれらのすべてのテストケースを処理するのに便利な行列関数への/からの配列の文字列変換があると便利ではありません:)
ngm

回答:


5

Java(JDK 10)247 232 220バイト

x->{int i=0,j=x.length,k,m,M,p=0,P=0,r=0;for(;i<j;){for(M=m=x[k=i][--j];k<=j;)for(int q:new int[]{x[i][k],x[j][k],x[k][i],x[k++][j]}){m=m<q?m:q;M=M<q?q:M;}r=i++>0?(k=P<m?3:p>M?1:P==m?2:4)*r!=r*r?4:k:0;p=m;P=M;}return r;}

オンラインでお試しください!

出力:

  • 1 「凹面」
  • 2 「フラット」用
  • 3 「凸」
  • 4 「混合」用

ゴルフをしていない:

x -> { // lambda that takes in the input int[][]
  int i = 0, // index of right bound of ring
      j = x.length, // index of left bound of ring
      k, // index of row-column-pair in ring
      m, // minimum of ring
      M, // maximum of ring
      p = 0, // minimum of previous ring
      P = 0, // maximum of previous ring
      r = 0; // result
  for (; i < j; ) { // iterate the rings from outside inwards
    // set both min and max to be to top right corner of the ring (and sneakily set some loop variables to save space)
    for (M = m = x[k = i][--j]; k <= j; ) // iterate the row-column pairs of the ring from top-right to bottom-left
      for (int q : new int[] {x[i][k], x[j][k], x[k][i], x[k++][j]}) { // iterate all of the cells at this row-column pair (and sneakily increment the loop variable k)
        // find new minimum and maximum
        m = m < q ? m : q;
        M = M < q ? q : M;
      }
    r = // set the result to be...
      i++ > 0 ? // if this is not the first ring... (and sneakily increment the loop variable i)
              // if the new result does not match the old result...
              (k = P < m ? // recycling k here as a temp variable to store the new result, computing the result by comparing the old and new mins/maxes
                         3
                         : p > M ?
                                 1
                                 : P == m ? 
                                          2
                                          : 4) * r != r * r ? // multiplying by r here when comparing because we want to avoid treating the case where r = 0 (unset) as if r is different from k
                                                            4 // set the result to "mixed"
                                                            : k // otherwise set the result to the new result
              : 0; // if this is the first ring just set the result to 0
    // set the old ring mins/maxes to be the current ones
    p = m; 
    P = M;
  }
  return r; // return the result
}

5

ゼリー 18 17  16 バイト

私はこの努力がゴルフをしのぐ可能性があると信じています

L‘HạŒỤṀ€IṠQṢ«FE$

整数のリストを返す数のリストのリストを受け入れるモナドリンク:

Concave ->  [0, 0]
Flat    ->  [-1, 0, 1]
Convex  ->  [-1, 0]
Mixed   ->  [-1, 0, 0]

オンラインでお試しください!または、テストスイートを参照してください。

L‘Hより効率的ではないが原子的に短いものに置き換えることができましたJÆm

どうやって?

L‘HạŒỤṀ€IṠQṢ«FE$ - Link: list of (equal length) lists of numbers
L                - length
 ‘               - increment
  H              - halve
                 -   = middle 1-based index (in both dimensions as the input is square)
    ŒỤ           - sort multi-dimensional indices by their corresponding values
                 -   = a list of pairs of 1-based indexes
   ạ             - absolute difference (vectorises)
                 -   = list of [verticalDistanceToMiddle, horizontalDistanceToMiddle] pairs
      Ṁ€         - maximum of €ach
                 -   each = N/2-k (i.e. 0 as middle ring and N/2 as outermost)
        I        - incremental deltas (e.g. [3,2,2,3,1]->[3-2,2-2,3-2,1-3]=[-1,0,1,-2])
         Ṡ       - sign (mapping -n:-1; 0:0; and +n:1)
          Q      - de-duplicate
           Ṣ     - sort
                 -   = concave:[0, 1]; convex:[-1, 0]; flatOrMixed:[-1, 0, 1]
               $ - last two links as a monad
             F   -   flatten
              E  -   all equal? (1 if flat otherwise 0)
            «    - minimum (vectorises)
                 -   = concave:[0, 0]; convex:[-1, 0]; mixed:[-1, 0, 0]; flat:[-1, 0, 1]

5

パイソン2219の 216 189 176バイト

def g(M):A=[sorted((M[1:]and M.pop(0))+M.pop()+[i.pop(j)for j in[0,-1]for i in M])for k in M[::2]];S={cmp(x[j],y[~j])for x,y in zip(A,A[1:])for j in[0,-1]};return len(S)<2and S

オンラインでお試しください!

出力set([1]), set([0]), set([-1]),又はFalseそれぞれ凹状、平坦、凸状、または混合しました。

Thx for:ovsによるいくつかの最適化から、なんと27バイト。その後、さらに 13バイト。

リストの内包表記A(ovsによる)は、ソートされた各リングの要素のリストを作成します。

次に、Aの各ソート済みリストのthおよびth要素を見て、隣接するリング間maxmin値と値を比較します。たとえば、凹の場合、各外側のリングは次の最も内側のリングより大きい; そして、各外側のリングも次に内側のリングよりも大きくなります。0-1Mminmaxmaxmin

場合M凹状、平坦、又は凸状である、これらのセットmin/maxの比較からのみ1要素を有することになります{-1, 0, 1}。混合されている場合、2つ以上の要素があります。


@ovs:それはかなり列です。リスト内包表記に変換することで別のバイトを保存しました(そして、これは他の同様の課題にとって非常に有用なテクニックかもしれないと考えています)。
チャスブラウン

リストの理解を短くする方法があるかもしれませんが、whileループはまだ短いようです:while M:k=M[0]+M[-1];M=M[1:-1];A+=sorted(k+[i.pop(j)for j in[0,-1]for i in M]),(174バイト)
ovs

@ovs:,A=()バイトカウントを省略しています...
Chas Brown

私が手174のバイトをしてA=()
OVS

あ!謝罪、私は誤解しました。これは、以前のバージョンの形式とは異なりますwhile M: A+= (some expression)
チャスブラウン


4

JavaScript(ES6)、168バイト

戻り値:

  • -1 フラット用
  • 0 混合用
  • 1 凸用
  • 2 凹面用
f=(a,k=w=~-a.length/2,p,P,i,m,M,y=w)=>k<0?i%4%3-!i:a.map(r=>r.map(v=>Y|(X=k*k-x*x--)<0&&X|Y<0||(m=v>m?m:v,M=v<M?M:v),x=w,Y=k*k-y*y--))|f(a,k-1,m,M,i|M-m<<2|2*(M<p)|m>P)

オンラインでお試しください!

どうやって?

各リングの最小値と最大値

各リングで最小mと最大Mを計算します。

各軸のマトリックスの中心からの距離の2乗を計算することにより、セルが特定のリング上にあるかどうかをテストします。絶対値をとることも同様に機能しますが、二乗はより短くなります。

次の式が偽である場合、(x、y)のセルはn番目のリング(最も外側のインデックスから始まる0から始まるインデックスに配置されます

((Y != 0) or (X < 0)) and ((X != 0) or (Y < 0))

どこ:

  • X =k²-(x-w)²
  • Y =k²-(y-w)²
  • w =(a.length-1)/ 2
  • k = w-n

例: 6x6マトリックスの2番目のリング上のセル(1、2)は?

  | 0 1 2 3 4 5   w = (6 - 1) / 2 = 2.5
--+------------   (x, y) --> ( x-w,  y-w) --> ((x-w)²,(y-w)²)
0 | 0 0 0 0 0 0   (1, 2) --> (-1.5, -0.5) --> (  2.25,   0.5)
1 | 0 1 1 1 1 0   
2 | 0[1]0 0 1 0   k = w - 1 = 1.5
3 | 0 1 0 0 1 0   k² = 2.25
4 | 0 1 1 1 1 0   X = 2.25 - 2.25 = 0 / Y = 2.25 - 0.5 = 1.75
5 | 0 0 0 0 0 0   ((X != 0) or (Y < 0)) is false, so (1,2) is on the ring

各反復の終わりに、mおよびMを前のリングの最小pおよび最大Pと比較し、それに応じてフラグ変数iを更新します。

  • i |= 1m> Pの場合
  • i |= 2M <pの場合
  • M!= mの場合、iの上位ビットを設定します

プロセスの最後に、iの最終値を次のように変換します。

i % 4  // isolate the 2 least significant bits (for convex and concave)
% 3    // convert 3 to 0 (for mixed)
- !i   // subtract 1 if i = 0 (for flat)

4

K(ngn / k)100 71 69バイト

{$[1=#?,/a:(,/x)@.=i&|i:&/!2##x;;(&/m>1_M,0)-&/(m:&/'a)>-1_0,M:|/'a]}

オンラインでお試しください!

1= concave、::= flat、-1= convex、0= mixedを返します

::kの欠損値のプレースホルダーとして使用されます)


oKを使用した別の戦略:&/1_`{&/+(y>|/x;y<&/x;,/x=/:y)}':(,/*:'(|+:)\)'-1_(-1_1_+-1_1_)\
zgrep

@zgrepいいね!:)自由に別の回答として投稿し、必要に応じて私のアイデアを取り入れてください-たとえば、リングへの分割は短いようですが、私はまだ
OK


ああ、それは非常にきちんとしたリング分割です!私はそれが好きです。
zgrep


1

C ++ 17(gcc)、411バイト

#import<map>
#define R return
#define T(f,s)X p,c;for(auto&e:r){c=e.second;if(p.a&&!p.f(c)){s;}p=c;}R
using I=int;struct X{I a=0;I z=0;I f(I n){R!a||n<a?a=n:0,n>z?z=n:0;}I
l(X x){R z<x.a;}I g(X x){R a>x.z;}I e(X x){R a==z&a==x.a&z==x.z;}};I
N(I i,I j,I s){i*=s-i;j*=s-j;R i<j?i:j;}auto C=[](auto&&m){I
s=size(m),i=-1,j;std::map<I,X>r;for(;++i<s;)for(j=-1;++j<s;)r[N(i,j,s-1)].f(m[i][j]);T(g,T(l,T(e,R 0)3)2)1;};

新しいハイスコア!(少なくとも投稿の時点では)まあ、それは少し気の利いたものですが、それでもC ++です。

オンラインでお試しください!

ラムダ Cはa std::vector<std::vector<int>>を取り、凹の場合は1、凸の場合は2、フラットの場合は3、混合の場合は0を返します。

コードのより読みやすいバージョンで、説明的な識別子、コメント、R-> returnおよびI->のint記述などがあります。

#include <map>

// Abbreviation for golfing. Spelled out below.
#define R return

// Macro to test whether all pairs of consecutive Ranges in `rings`
// satisfy a condition.
// func: a member function of Range taking a second Range.
// stmts: a sequence of statements to execute if the condition is
//        not satisfied. The statements should always return.
//        May be missing the final semicolon.
// Expands to a statement, then the return keyword.
// The value after the macro will be returned if all pairs of Ranges
// satisfy the test.
#define TEST(func, stmts)                                     \
    Range prev, curr;                                         \
    for (auto& elem : rings) {                                \
        curr = elem.second;                                   \
        // The first time through, prev.a==0; skip the test.  \
        if (prev.a && !prev.func(curr))                       \
        { stmts; }                                            \
        prev = curr;                                          \
    }                                                         \
    return

// Abbreviation for golfing. Spelled out below.
using I = int;

// A range of positive integers.
// A default-constructed Range is "invalid" and has a==0 && z==0.
struct Range
{
    int a = 0;
    int z = 0;
    // Add a number to the range, initializing or expanding.
    // The return value is meaningless (but I is shorter than void for golfing).
    int add(int n) {
        return !a||n<a ? a=n : 0, n>z ? z=n : 0;
        /* That is:
        // If invalid or n less than previous min, set a.
        if (a==0 || n<a)
            a = n;
        // If invalid (z==0) or n greater than previous max, set z.
        if (n>z)
            z = n;
        return dummy_value;
        */
    }

    // Test if all numbers in this Range are strictly less than
    // all numbers in Range x.
    int less(Range x)
    { return z < x.a; }

    // Test if all numbers in this Range are strictly greater than
    // all numbers in Range x.
    int greater(Range x)
    { return a > x.z; }

    // Test if both this Range and x represent the same single number.
    int equal(Range x)
    { return a==z && a==x.a && z==x.z; }
};

// Given indices into a square matrix, returns a value which is
// constant on each ring and increases from the first ring toward the
// center.
// i, j: matrix indices
// max: maximum matrix index, so that 0<=i && i<=max && 0<=j && j<=max
int RingIndex(int i, int j, int max)
{
    // i*(max-i) is zero at the edges and increases toward max/2.0.
    i *= max - i;
    j *= max - j;
    // The minimum of these values determines the ring.
    return i < j ? i : j;
}

// Takes a container of containers of elements convertible to int.
// Must represent a square matrix with positive integer values.
// Argument-dependent lookup on the outer container must include
// namespace std, and both container types must have operator[] to
// get an element.  (So std::vector or std::array would work.)
// Returns:
//   1 for a concave matrix
//   2 for a convex matrix
//   3 for a flat matrix
//   0 for a mixed matrix
auto C /*Classify*/ = [](auto&& mat)
{
    int mat_size=size(mat), i=-1, j;
    std::map<int, Range> rings;

    // Populate rings with the range of values in each ring.
    for (; ++i<mat_size;)
        for (j=-1; ++j<mat_size;)
            rings[RingIndex(i, j, mat_size-1)].add(mat[i][j]);

    // Nested macros expand to
    // Range prev, curr; for ... if (...) {
    //   Range prev, curr; for ... if (...) {
    //     Range prev, curr; for ... if (...) {
    //       return 0;
    //     } return 3;
    //   } return 2;
    // } return 1
    // Note each scope declares its own prev and curr which hide
    // outer declarations.
    TEST(greater, TEST(less, TEST(equal, return 0) 3) 2) 1;
};

1
私はあなたがそれが意味だと思う何の気の利いた」という意味はないと思う
ASCIIのみ
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.