n列すべてに1〜L(n)の行列


18

チャレンジ:

入力として正の整数を含むリストLを取得します。

3 5 2 1 6

そして、n番目の列がベクトル1:L(n)を含む行列を作成します。ここで、短い行にはゼロが埋め込まれます。

テストケース:

3   5   2   1   6
-----------------
1   1   1   1   1
2   2   2   0   2
3   3   0   0   3
0   4   0   0   4
0   5   0   0   5
0   0   0   0   6

1
-
1

1   2   3   4   3   2   1
-------------------------
1   1   1   1   1   1   1
0   2   2   2   2   2   0
0   0   3   3   3   0   0
0   0   0   4   0   0   0

ルール:

  • オプションの入力および出力形式
    • リストのリストは許容可能な出力形式です
  • 行列はできるだけ小さくする必要があります(必要以上にゼロを追加しないでください)
  • 各言語で最短のコードが優先されます
  • 説明を強くお勧めします

代わりに、範囲を水平方向に分散できますか?
ミスターXcoder

いいえ、垂直に配置する必要があります。水平/垂直という言葉に意味がない言語を使用する場合、それはオプションです。(リストのリストのいずれかの水平/垂直方向に関連付けられていない言語に関連することができる)
Stewieグリフィン

1
@StewieGriffinディメンションをネストされたリストに関連付けていない健全な言語は何ですか?
エリックアウトゴルファー

4
@EriktheOutgolfer、このサイトで使用されている非常識な言語の数は?
スティーヴィーグリフィン

2
@EriktheOutgolfer Rの場合、行列はネストされたリストとしてではなく、行ごとに折り返される1つの長いリストです。
JAD

回答:


18

R40 38バイト

function(l)outer(m<-1:max(l),l,"<=")*m

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

説明:

outer行列を生成する、その最初の二つの引数の要素の全ての組み合わせに対して、その三番目の引数(関数)を印加TRUEし、FALSE各列が有する場合TRUEどこ1:max(l)未満または対応する要素と同じであるl、例えばここでは、l=c(3,5,2,1,6)

      [,1]  [,2]  [,3]  [,4] [,5]
[1,]  TRUE  TRUE  TRUE  TRUE TRUE
[2,]  TRUE  TRUE  TRUE FALSE TRUE
[3,]  TRUE  TRUE FALSE FALSE TRUE
[4,] FALSE  TRUE FALSE FALSE TRUE
[5,] FALSE  TRUE FALSE FALSE TRUE
[6,] FALSE FALSE FALSE FALSE TRUE

次に、結果のマトリックスがAであると仮定すると、A*m-> A[i,j]=A[i,j]*iTRUE1およびFALSE0に強制され、目的の結果が生成されます。


私は思う-あなたが交換することにより、2つのバイトを保存することができfunction(l)l=scan();
AndriusZ

@AndriusZしかし、私はすべてをラップしprintなければならないので、それらのバイトを失います。
ジュゼッペ

-私はあなたがすべてをラップする必要はありません、と思うTOI
AndriusZ

2
@AndriusZ、これについては以前に間違いなく話しました。このメタの質問に対する唯一の答えsource(...,echo=TRUE)は、代替プログラムの提案があれば、標準プログラムをフルプログラムとして使用し、読み取ることに対して+4のペナルティを与えますが、必ずそこに重さを量りますが、完全なプログラムに関するRコンセンサスに、それは当分の間立っています。
ジュゼッペ

ゲームに遅れて:[このヒント](codegolf.stackexchange.com/a/111578/80010)を使用して2バイト保存
JayCe



5

Mathematica、20バイト

PadRight@Range@#&

U + F3C7を含む(Mathematicaの組み込みTranspose関数)

Wolfram Sandboxで試してみてください

使用法

PadRight@Range@#&[{3, 5, 2, 1, 6}]
{
 {1, 1, 1, 1, 1},
 {2, 2, 2, 0, 2},
 {3, 3, 0, 0, 3},
 {0, 4, 0, 0, 4},
 {0, 5, 0, 0, 5},
 {0, 0, 0, 0, 6}
}

説明

PadRight@Range@#&

         Range@#    (* Generate {1..n} for all elements of input *)
PadRight@           (* Right-pad 0s so that all lists are equal length *)
                   (* Transpose the result *)

@downvotersなぜダウン投票するのですか?すべて説明できますか?
ジョンファンミン

ダウン投票しませんでしたが、関数の署名や引数の入力が不足しているため、コードスニペットがブラックボックスにならないためだと思われます。
-sergiol

5

オクターブ、26バイト

@(x)((y=1:max(x))'<=x).*y'

行ベクトルを入力し、行列を出力する無名関数。

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

説明

入力を検討してくださいx = [3 5 2 1 6]。これは、サイズ1×5の行ベクトルです。

1:max(x)[1 2 3 4 5 6]変数に割り当てられる行ベクトルを与えるy

その転置、つまり列ベクトル[1; 2; 3; 4; 5; 6]<=、入力と-(ブロードキャストと要素単位で)比較されます[3 5 2 1 6]。結果は6×5行列です

[1 1 1 1 1;
 1 1 1 0 1;
 1 1 0 0 1;
 0 1 0 0 1;
 0 1 0 0 1;
 0 0 0 0 1]

最後に、転置[1; 2; 3; 4; 5; 6]として取得された列ベクトルを(ブロードキャストで要素単位で)乗算yすると、望ましい結果が得られます。

[1 1 1 1 1;
 2 2 2 0 2;
 3 3 0 0 3;
 0 4 0 0 4;
 0 5 0 0 5;
 0 0 0 0 6]

1
MATLAB / Octaveの提出を期待していた。何も考えずにこれを実装したので、おそらく40バイト以上でした。非常に良い解決策:)
Stewie Griffin



3

Pyth、6バイト

.tSMQZ

ここで試してみてください!または、すべてのテストケースを検証します(きれいに印刷します)!


説明

.tSMQZ-完全なプログラム。

  SMQ-それぞれの包括的な単項範囲を取得します。
.t-転置、コピーのパディング...
     Z-...ゼロ。
         -暗黙の印刷。

非組み込みの転置バージョンは次のようになります

mm*hd<dkQeS

これは次のように機能します。

mm*hd<dkQeS   - Full program.

m        eS   - Map over [0, max(input)) with a variable d.
 m      Q     - Map over the input with a variable k.
   hd         - d + 1.
  *           - Multiplied by 1 if...
     <dk      - ... d is smaller than k, else 0.
              - Output implicitly.


3

実際には、17バイト

;M╗♂R⌠╜;0@α(+H⌡M┬

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

説明:

;M╗♂R⌠╜;0@α(+H⌡M┬
;M╗                store the maximal element (M) of the input in register 0
   ♂R              range(1, n+1) for each n in input
     ⌠╜;0@α(+H⌡M   for each range:
      ╜;0@α          push a list containing M 0s
           (+        append to range
             H       take first M elements
                ┬  transpose

ええ、実際にはパディングサポート付きのzipが実際に必要です...
エリックアウトゴルファー

2

パイク、3バイト

これはPykeの新機能である16進エンコーディングを使用しています...最良の部分はJellyを結び付けることです!生バイト:

4D 53 AC

ここで試してみてください!

ASCII-Pykeに相当するものは4バイトです。

MS.,

どうやって?

4D 53 AC-フルプログラム。

4D-マップ。
   53-包括的範囲。
      AC-ゼロで転置します。
           -暗黙的に出力します。

-------------------------------------

MS。、-完全なプログラム。

M-マップ。
 S-包括的範囲。
  。、-ゼロで転置します。
       -暗黙的に出力します。

ここでは ASCIIとプリティプリントバージョンがあり、そしてここ進エンコーディングを有するものです。


2

Perl 6、39バイト

{zip (1 X..$_).map:{|@_,|(0 xx.max-1)}}

それを試してみてください

拡張:

{                # bare block lambda with implicit parameter 「$_」

  zip

    (1 X.. $_)   # turn each input into a Range that starts with 1

    .map:        # map each of those Ranges using the following code

    {            # bare block lambda with implicit parameter 「@_」 
                 # (「@_」 takes precedence over 「$_」 when it is seen)

      |@_,       # slip the input into a new list

      |(         # slip this into the list

        0        # a 「0」
        xx       # list repeated by

          .max   # the max of 「$_」 (implicit method call)
          - 1    # minus 1 (so that zip doesn't add an extra row)
      )
    }
}

zip最短の入力リストがなくなると終了することに注意してください。


2

C#、136バイト


データ

  • 入力 Int32[] i intの配列
  • 出力 Int32[,]双方向配列。

ゴルフ

i=>{int m=System.Linq.Enumerable.Max(i),l=i.Length,x,y;var o=new int[m,l];for(y=0;y<m;y++)for(x=0;x<l;)o[y,x]=i[x++]>y?y+1:0;return o;};

非ゴルフ

i => {
    int
        m = System.Linq.Enumerable.Max( i ),
        l = i.Length,
        x, y;

    var o = new int[ m, l ];

    for( y = 0; y < m; y++ )
        for( x = 0; x < l; )
            o[ y, x ] = i[ x++ ] > y ? y + 1 : 0;

    return o;
};

読みやすい

// Take an array of Int32
i => {

    // Store the max value of the array, the length and declare some vars to save some bytes
    int
        m = System.Linq.Enumerable.Max( i ),
        l = i.Length,
        x, y;

    // Create the bidimensional array to output
    var o = new int[ m, l ];

    // Cycle line by line...
    for( y = 0; y < m; y++ )

        // ... and column by column...
        for( x = 0; x < l; )

            // And set the value of the line in the array if it's lower than the the value at the index of the input array
            o[ y, x ] = i[ x++ ] > y ? y + 1 : 0;

    // Return the bidimentional array.
    return o;
};

完全なコード

using System;
using System.Collections.Generic;

namespace TestBench {
    public class Program {
        // Methods
        static void Main( string[] args ) {
            Func<Int32[], Int32[,]> f = i => {
                int
                    m = System.Linq.Enumerable.Max( i ),
                    l = i.Length,
                    x, y;
                var o = new int[ m, l ];
                for( y = 0; y < m; y++ )
                    for( x = 0; x < l; )
                        o[ y, x ] = i[ x++ ] > y ? y + 1 : 0;
                return o;
            };

            List<Int32[]>
                testCases = new List<Int32[]>() {
                    new[] { 1, 2, 5, 6, 4 },
                    new[] { 3, 5, 2, 1, 6 },
                    new[] { 1, 2, 3, 4, 3, 2, 1 },
                };

            foreach( Int32[] testCase in testCases ) {
                Console.WriteLine( " INPUT: " );
                PrintArray( testCase );

                Console.WriteLine( "OUTPUT: " );
                PrintMatrix( f( testCase ) );
            }

            Console.ReadLine();
        }

        public static void PrintArray<TSource>( TSource[] array ) {
            PrintArray( array, o => o.ToString() );
        }
        public static void PrintArray<TSource>( TSource[] array, Func<TSource, String> valueFetcher ) {
            List<String>
                output = new List<String>();

            for( Int32 index = 0; index < array.Length; index++ ) {
                output.Add( valueFetcher( array[ index ] ) );
            }

            Console.WriteLine( $"[ {String.Join( ", ", output )} ]" );
        }

        public static void PrintMatrix<TSource>( TSource[,] array ) {
            PrintMatrix( array, o => o.ToString() );
        }
        public static void PrintMatrix<TSource>( TSource[,] array, Func<TSource, String> valueFetcher ) {
            List<String>
                output = new List<String>();

            for( Int32 xIndex = 0; xIndex < array.GetLength( 0 ); xIndex++ ) {
                List<String>
                    inner = new List<String>();

                for( Int32 yIndex = 0; yIndex < array.GetLength( 1 ); yIndex++ ) {
                    inner.Add( valueFetcher( array[ xIndex, yIndex ] ) );
                }

                output.Add( $"[ {String.Join( ", ", inner )} ]" );
            }

            Console.WriteLine( $"[\n   {String.Join( ",\n   ", output )}\n]" );
        }
    }
}

リリース

  • v1.0の - 136 bytes-初期ソリューション。

ノート

  • なし


1

Java 10、115バイト

a->{int l=a.length,m=0;for(int j:a)m=j>m?j:m;var r=new int[m][l];for(;l-->0;)for(m=0;m<a[l];r[m][l]=++m);return r;}

説明:

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

a->{                  // Method with integer-array parameter and integer-matrix return-type
  int l=a.length,     //  Length of the array
      m=0;            //  Largest integer in the array, 0 for now
  for(int j:a)        //  Loop over the array
    m=j>m?            //   If the current item is larger than `m`:
       j              //    Set `m` to this item as new max
      :               //   Else:
       m;             //    Leave `m` the same
  var r=new int[m][l];//  Result-matrix of size `m` by `l`, filled with zeroes by default
  for(;l-->0;)        //  Loop over the columns
    for(m=0;m<a[l];   //   Inner loop over the rows
      r[m][l]=++m);   //    Set the cell at position `m,l` to `m+1`
  return r;}          //  Return the result-matrix


0

プロトン、38バイト

a=>[[i<j?-~i:0for j:a]for i:0..max(a)]

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


バグはそれ以降のスペースですか?
ケアニアン共犯

@cairdcoinheringaahingはい。疑問符は、別の疑問符ではないことを確認するためにその文字を消費しますが、余分な文字を補うのを忘れてスキップされました。
ハイパーニュートリノ

引っ張られたようです。通知を削除できるようになりました:)
エリックアウトゴルファー


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