10進数へのすべてのバイナリの組み合わせ


12

免責事項

この質問は、この質問の複製ではありません。特定の桁をカウントしていません。初期パラメーターで既に設定されているためです。この質問は、提供された数字に基づいてバイナリ文字列から構築できる10進数に焦点を当てています。

チャレンジ

それぞれゼロ()と1()の数を表す2つの整数Xとが与えられた場合、提供されたゼロと1のみを使用してバイナリ文字列を作成することで決定できるすべての可能な10進数を計算し、出力として表示します。Y01

例1:

入力: 0 1

出力: 1

説明:説明1する対象は1つだけであり、一方向にのみ変換できます。

例2:

入力: 1 1

出力: 1,2

説明:011に10変換し、2 に変換します。

例3:

入力: 3 2

出力: 3,5,6,9,10,12,17,18,20,24

説明:3 0秒と2 1秒で00011(3)、00101(5)、00110(6)、01001(9)、01010(10)、01100(12)、10001(17)、10010(18)、10100(20)、11000(24)

制限と規則

  • コードが機能するの0 < X + Y <= 16は、出力の最大数が16からのみ発生する場合1(つまり、パラメーター0と)のみ16です。
  • 上記の制限の結果、出力で予想される数値の範囲はfrom 0および65535です。
  • コンマ区切りリスト、配列、STDOUTに出力されるリストなど、結果の出力が提供される限り、関数またはコードを受け入れます。出力について強調しなければならない唯一の基準は、ソートする必要があることです。
  • これはコードゴルフであり、最小バイトは最大の栄光を受け取ります。
  • 愚かな抜け穴を容認しません

1
出力をソートする必要がありますか?
デニス

こんにちは、@ Dennis、はい、言及するのを忘れていました...出力をソートする必要があります。それに応じてルールを更新しました。
WallyWest

2
ケースを処理する必要があり0 0ますか?
-ETHproductions

@ETHproductions上で述べたように0 <= X + Y <= 16、そうです。なぜなら、0 0そのルールを満たす有効な入力と見なされるからです。
WallyWest

2
その場合、期待される出力は0 0何ですか?数値0は、ゼロ、1つまたは複数のゼロで表すことができます。
デニス

回答:


5

ゼリー、8 バイト

0,1xŒ!ḄQ

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

使い方

0,1xŒ!ḄQ Main link. Argument: [x, y]

0,1x     Repeat 0 x times and 1 y times.
    Œ!   Compute all permutations of the result.
      Ḅ   Unbinary; convert each permutation from base 2 to integer.
       Q  Unique; deduplicate the results.

これは非常に印象的です...一般的なプログラミング市場でJが必要ですか?私はゼリーがそれに基づいていることに気付きましたか?
WallyWest

1
いくつかの特定のアプリケーション(主に数学/統計)にユーザーベースがありますが、正直なところわかりません。コードゴルフ以外でJを使用したことはありません。
デニス

@WallyWest関数型プログラミングの恩恵を受ける環境に最適であるため、頻繁に呼び出されることはありません。通常、非常に専門的なプログラミング専用です。
コナーオブライエン

7

Python、60バイト

lambda x,y:[n for n in range(1<<x+y)if bin(n).count('1')==y]

Ideoneでテストします。

使い方

x個のゼロと2進数で表現できるすべての正の数 yが 1のは、明らかに2 x + yよりも小さくなります。ます。 x + y + 1桁です。

ラムダは、単に[0、2 x + yの整数を反復処理し、すべての整数nを保持します有し、その範囲内にYもの。以来、N <2 のx + yはで表すことができるされているX(以下)ゼロ。


5

Mathematica、59 57バイト

Mathematicaの通常の結果:高レベル関数=良い、長い関数名=悪い。

#+##&~Fold~#&/@Permutations@Join[0&~Array~#,1&~Array~#2]&

Join[0&~Array~#,1&~Array~#2]正しい数の0sと1s でリストを作成します。Permutationsそのリストのすべての順列を繰り返しなしで(私が学んだように)ソートされた順序で生成します。#+##&~Fold~#(のゴルフクラブ版#~FromDigits~2)は、2進数のリストをそれらが表す整数に変換します。

前のバージョン、Martin Enderのコメントの前:

#~FromDigits~2&/@Permutations@Join[0&~Array~#,1&~Array~#2]&

1
それでも、よく観察され、文書化されています... Mathematicaは数値
計算に最適

1
FromDigits通常は短縮できます。#+##&~Fold~#&/@Permutations...
Martin Ender

@MartinEnder:わかった!他のベースにも一般化する方法を参照してください。この賢いイディオムを教えてくれてありがとう。
グレッグマーティン


1
それはに切り替えることが判明したデニスのアプローチは短いものの:Select[Range[2^+##]-1,x=#;DigitCount[#,2,1]==x&]&
マーティン・エンダー

5

CJam(15 14バイト)

{As.*s:~e!2fb}

これは、入力を配列として受け取り、[number-of-ones number-of-zeros]出力を配列として返す匿名ブロック(関数)です。

オンラインデモ


かなり先のことですが、もっと面白いです。これは、置換ビルトインやベース変換なしです。

{2\f#~1$*:X;[({___~)&_2$+@1$^4/@/|_X<}g;]}

GolfScriptの展開としてうまく機能します。


私は交換するためにしようとしていたee{)*}/使用して何かを.*して、この14バイトの解決策を考え出した。けれども、今少し非効率的になります。{As.*s:~e!2fb}s:~
マーティンエンダー

1
@MartinEnder、私は実際に始めて.*、それeeが例えばより良いと決めました2,:a.*e_。しかしe!、引数の順序に関係なく同じ出力が得られることに気付きませんでした。
ピーターテイラー


4

Japt、16バイト

'0pU +'1pV)á mn2

オンラインでテストしてください!

使い方

                  // Implicit: U = first integer, V = second integer
'0pU              // Repeat the string "0" U times.
     +'1pV)       // Concatenate with the string "1" repeated V times.
           á      // Take all unique permutations.
             mn2  // Interpret each item in the resulting array as a binary number.
                  // Implicit: output last expression

代替バージョン、17バイト

2pU+V o f_¤è'1 ¥V
                   // Implicit: U = first integer, V = second integer
2pU+V              // Take 2 to the power of U + V.
      o            // Create the range [0, 2^(U+V)).
        f_         // Filter to only items where
           è'1     //  the number of "1"s in
          ¤        //  its binary representation
               ¥V  //  is equal to V. 
                   // Implicit: output last expression

私は両方のバージョンをさらにゴルフしようとしていますが、たるみが見つかりません...


これはすごいですね... しかし、インタープリターは右側にトランスコードされたコードを表示していませんか?私はそれがどのようにレンダリングされるか見てみたいですか?
WallyWest

@WallyWestそれは大まかに転送し("0".p(U)+"1".p(V)).á().m("n",2)ます; 各.x()関数はソースファイルで定義されています
ETHproductions

3

ルビー、63バイト

シンプルな実装。ゴルフの提案を歓迎します。

->a,b{(?0*a+?1*b).chars.permutation.map{|b|(b*'').to_i 2}.uniq}

アンゴルフ

def f(a,b)
  str = "0"*a+"1"*b                   # make the string of 0s and 1s
  all_perms = str.chars.permutation   # generate all permutations of the 0s and 1s
  result = []
  all_perms.do each |bin|             # map over all of the permutations
    bin = bin * ''                    # join bin together
    result << bin.to_i(2)             # convert to decimal and append
  end
  return result.uniq                  # uniquify the result and return
end

3

Pyth-11バイト

{iR2.psmVU2

テストスイート

{                Uniquify
 iR2             Map i2, which converts from binary to decimal
  .p             All permutations
   s             Concatenate list
    mV           Vectorized map, which in this case is repeat
     U2          0, 1
     (Q)         Implicit input

2

Python 2-105 99バイト

出力をソートする必要があるため、+ 8バイト

lambda x,y:sorted(set(int("".join(z),2)for z in __import__('itertools').permutations("0"*x+"1"*y)))

印象的な編集!
WallyWest

1
おかげで、ラムダ関数でモジュールをインポートできるとは思いもしませんでした。
ジェレミー

私はいつも、あなたがコードゴルフの目的のために別の輸入声明を出すことが許されていると思っていました。(明らかに、その長さを含める必要があります。)これにより、1〜2バイト節約できますか?
ニール

2

Mathematica、47バイト

Cases[Range[2^+##]-1,x_/;DigitCount[x,2,1]==#]&

2つの引数を取る、名前のない関数:1sの数、0sの数。

本質的には、デニスのPythonソリューションの移植版です。0toの範囲を作成し、-bitsの量が最初の入力に等しい数値のみを保持します。最も興味深いのは、おそらく、2つの引数の追加を囲む括弧を避けるために、いくつかのシーケンスマジックを使用することです。2x+y-112^+##


2

MATLAB 57 + 6

@(a,b)unique(perms([ones(1,a) zeros(1,b)])*2.^(0:a+b-1)')

run using

ans(2,3)

ungolfed

function decimalPerms( nZeros, nOnes )
  a = [ones(1,nOnes) zeros(1,nZeros)];  % make 1 by n array of ones and zeros
  a = perms(a);                         % get permutations of the above 
  powOfTwo = 2.^(0:nOnes+nZeros-1)';    % powers of two as vector
  a = a * powOfTwo;                     % matrix multiply to get the possible values
  a = unique(a)                         % select the unique values and print

1
What's the plus 6 bytes for?
mbomb007

私は同じことをしようとしていた
-WallyWest

2

MATL、9バイト

y+:<Y@XBu

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

説明

このアプローチは、デニスのゼリーの回答と似ています

y     % Implicitly take two inputs (say 3, 2). Duplicate the first.
      %   STACK: 3, 2, 3
+     % Add
      %   STACK: 3, 5
:     % Range
      %   STACK: 3, [1 2 3 4 5]
<     % Less  than
      %   STACK: [0 0 0 1 1]
Y@    % All permutations
      %   STACK: [0 0 0 1 1; 0 0 0 1 1; ...; 0 0 1 0 1; ...; 1 1 0 0 0]
XB    % Binary to decimal
      %   STACK: [3 3 ... 5 ... 24]
u     % Unique
      %   STACK: [3 5 ... 24]
      % Implicitly display

1

実際には、21バイト

Rubyの回答の移植版。ゴルフの提案を歓迎します。オンラインでお試しください!

│+)'1*@'0*+╨`εj2@¿`M╔

使い方

          Implicit input of a and b.
│+)       Duplicate a and b, add, and rotate to bottom of stack. Stack: [b a a+b]
'1*@      "1" times b and swap with a.
'0*+      "0" times a and add to get "0"*a+"1"*b.
╨`...`M   Take all the (a+b)-length permutations of "0"*a+"1"*b
          and map the following function over them.
  εj        Join the permutation into one string
  2@¿       Convert from binary to decimal
╔         Uniquify the resulting list and implicit return.

1

Groovy 74バイト、93バイトまたは123バイト

どちらがあなたがより完全に質問に答えると考えるかわかりませんが...

74バイトソリューション

​{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().unique()}(1,2)

入力が1,2の場合、次のようになります。

[[1,0,1], [0,1,1], [1,1,0]]

93バイトソリューション

{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().collect{it.join()}.unique()}(1,2)​

入力が1,2の場合、次のようになります。

[101, 011, 110]

123バイトソリューション

{a,b->((1..a).collect{0}+(1..b).collect{1}).permutations().collect{it.join()}.unique().collect{Integer.parseInt(it,2)}}(1,2)

入力が1,2の場合、次のようになります。

[5, 3, 6]

ここで試してください:

https://groovyconsole.appspot.com/edit/5143619413475328


I'd be counting the 123 byte solution as this matches the output type mentioned in the brief. Well done.
WallyWest

1

JavaScript (Firefox 48), 85 76 74 71 70 bytes

Saved 3 bytes thanks to @Neil.

(m,n,g=x=>x?g(x>>1)-x%2:n)=>[for(i of Array(1<<m+n).keys())if(!g(i))i]

Array comprehensions are awesome. Too bad they haven't made it into official ECMAScript spec yet.

JavaScript (ES6), 109 87 79 78 71 70 bytes

(m,n,g=x=>x?g(x>>1)-x%2:n)=>[...Array(1<<m+n).keys()].filter(x=>!g(x))

Should work in all ES6-compliant browsers now. Saved 7 bytes on this one, also thanks to @Neil.


Uh, @ETHProductions, for some reason I'm getting it returning undefined now with every test run I'm doing...?
WallyWest

@WallyWest Make sure you're first assigning it to a variable, e.g. f=(m,n)=>..., then call it like f(3,2). If that's what you're doing, what browser are you using?
ETHproductions

Chrome 52... I don't have firefox on this machine, so I could only test the ES6 non-Firefox version...
WallyWest

Trying to run it inthe browser console.
WallyWest

Oh, hmm. I see that problem too in Chrome. Try this eval-less version (does exactly the same thing, but 3 bytes longer): (m,n)=>{a="";for(i=0;i<1<<m+n;i++)if(i.toString(2).split(1).length==n+1)a+=i+" ";return a}
ETHproductions

1

Groovy 80 Bytes

based on the answer by @carusocomputing

his 123 Byte solution can be compressed into 80 Bytes:

80 Byte Solution

{a,b->([0]*a+[1]*b).permutations()*.join().collect{Integer.parseInt(it,2)}}(1,2)

For an input of 1,2 you get:

[5, 3, 6]

1

C (gcc), 72 68 bytes

f(a,b){for(a=1<<a+b;a--;)__builtin_popcount(a)^b||printf("%d\n",a);}

Try it online!

Unfortunately there is no popcount() in the standard library, but it is provided as a "builtin function" by GCC. The output is sorted, but in reverse order.

Thanks to @ceilingcat for shaving off 4 bytes!


Still acceptable. Nice work!
WallyWest

0

PHP, 80 or 63 bytes

depending on wether I must use $argv or can use $x and $y instead.

for($i=1<<array_sum($argv);$i--;)echo$argv[2]-substr_count(decbin($i),1)?_:$i._;

prints all matching numbers in descending order delimited by underscores.
filename must not begin with a digit.

no builtins, 88 or 71 bytes

for($i=1<<array_sum($argv);$i--;print$c?_:$i._)for($n=$i,$c=$argv[2];$n;$n>>=1)$c-=$n&1;

add one byte each for only one underscore after every number.

@WallyWest: You were right. Saves 3 bytes for me from for($i=-1;++$i<...;)


0

Perl 6,  64 62  49 bytes

{(0 x$^a~1 x$^b).comb.permutations.map({:2(.join)}).sort.squish}
{[~](0,1 Zx@_).comb.permutations.map({:2(.join)}).sort.squish}
{(^2**($^x+$^y)).grep:{.base(2).comb('1')==$y}}

Explanation:

# bare block lambda with two placeholder parameters 「$^x」 and 「$^y」
{
  # Range of possible values
  # from 0 up to and excluding 2 to the power of $x+$y
  ( ^ 2 ** ( $^x + $^y ) )

  # find only those which
  .grep:

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

    # convert to base 2
    # ( implicit method call on 「$_」 )
    .base(2)

    # get a list of 1s
    .comb('1')

    # is the number of elements the same
    ==

    # as the second argument to the outer block
    $y
  }
}
say {(0..2**($^x+$^y)).grep:{.base(2).comb('1')==$y}}(3,2)
# (3 5 6 9 10 12 17 18 20 24)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.