33
\$\begingroup\$

Input

  • A list of between 1 and 255 positive integers (inclusive), each in the range 1 to 232 - 1 (inclusive).
  • Your input format does not need to be identical to the test cases.
  • Input without leading zeroes is required to be accepted.
  • Input with leading zeroes is not required to be accepted.
  • You may use whatever delimiter you wish between the integers.
  • An integer may be represented by a string but the individual digits of a specific integer must be contiguous.
  • You may choose to use any base for the input (including binary and unary), provided the output is also in that base.

Output

  • A single integer.
  • The output must have no leading zeroes.
  • The output must be in the same base as the input.
  • The output can be calculated in whatever way you wish but must match the result of the following calculation:

Calculating biplex

  • The bits of a binary representation are numbered from the right starting from zero, so bit i is in the column representing 2i.
  • The i th bitsum is the sum of the i th bits of the binary representations of each of the input numbers.
  • The bitsum maximum is the highest value taken by the bitsums.
  • The bitsum minimum is the lowest non-zero value taken by the bitsums.
  • The i th digit of the binary representation of the output is:
    • 1 if the i th bitsum is equal to the bitsum maximum or the bitsum minimum.
    • 0 otherwise.

Worked example

This example uses binary for input and output.

Input:    100110
         1101110
         1100101
         _______
Bitsums: 2301321

Output:   101101

The bitsum maximum is 3 and the bitsum minimum is 1, so the output has 1s everywhere that the bitsum is 3 or 1, and 0s everywhere else.


Test cases

Test cases are in the form:

Input => Output

The test cases in binary:

[1] => 1
[10] => 10
[1, 10, 101] => 111
[11111111111111111111111111111111] => 11111111111111111111111111111111
[10010010010010010010010010010010, 10101010101010101010101010101010, 11011011011011011011011011011011] => 11100011100011100011100011100011
[10001011100010100110100101001001, 10110000111110010000111110111010, 1101110001101101011010010100101, 1010101010001011101001001010101] => 11 

The same test cases in decimal:

[1] => 1
[2] => 2
[1, 2, 5] => 7
[4294967295] => 4294967295
[2454267026, 2863311530, 3681400539] => 3817748707
[2341103945, 2969112506, 1849078949, 1430639189] => 3

Leaderboard

Thanks to Martin's Leaderboard Snippet

var QUESTION_ID=62713,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>


The operator was named biplex, short for binary plane extrema, following discussion in chat.

\$\endgroup\$
  • \$\begingroup\$ Can we require the input to be in binary, as in the example? \$\endgroup\$ – feersum Nov 3 '15 at 13:52
  • 1
    \$\begingroup\$ @feersum You may choose to use any base for input and output (including binary and unary), provided they are both in the same base. So yes, go for it :) \$\endgroup\$ – trichoplax Nov 3 '15 at 14:02
  • \$\begingroup\$ Can we use notation like [[1,0,1],[1,1,0,0],[1,0,0,1]]? \$\endgroup\$ – Akangka Nov 4 '15 at 10:28
  • \$\begingroup\$ Probably not. Assume the most restrictive one. \$\endgroup\$ – Akangka Nov 4 '15 at 10:35
  • \$\begingroup\$ @ChristianIrwan The input should be in the form of integers (each made up of contiguous digits). An integer can be represented as a string but there should be no separators between the digits. \$\endgroup\$ – trichoplax Nov 4 '15 at 10:43

23 Answers 23

1
\$\begingroup\$

Jelly, non-competing

14 bytes This answer is non-competing since the challenge predates the creation of Jelly.

BUSµḟ0Ṣ.ịe€@UḄ

Try it online!

How it works

BUSµḟ0Ṣ.ịe€@UḄ    Main link. Input: A (list)

B                 Convert each item in A to binary.
 U                Reverse each array of binary digits.
  S               Add them across columns.

   µ              Monadic chain. Argument: S (list of column sums)
    ḟ0            Remove all occurrences of 0.
      Ṣ           Sort the remaining sums.
       .ị         Take the elements with indices around 0.5.
                  Indices are 1-bases, so this selects the last and the first one.
             U    Yield S, reversed.
            @     Reverse the arguments.
         e€       Test each item in the left list for membership in the right one.
              Ḅ   Convert from binary to integer.                
\$\endgroup\$
  • \$\begingroup\$ Although there's disagreement on exactly how to judge it, this meta question suggests the community is strongly in favour of no longer marking answers as non-competing when the challenge predates the creation of the language. I'm therefore accepting this answer. \$\endgroup\$ – trichoplax Aug 2 '17 at 14:25
11
\$\begingroup\$

Pyth, 26 25 bytes

JsM.T_MjR2Qi_}RhM_BS-J0J2

Try it online: Demonstration or Test Suite

Explanation

JsM.T_MjR2Q
       jR2Q      convert each input number to binary (lists of 1s and 0s)
     _M          reverse each list
   .T            transpose (with top justify)
 sM              sum up each list (numbers of 1s at each position)
J                store this list in J

i_}RhM_BS-J0J2
         -J0     J without 0s
        S        sorted
      _B         create the list [sorted, reverse(sorted)]
    hM           take the first elments of each (bitsum-min and bitsum-max)
  }R        J    check for each value in J, if it is part of ^
 _               reverse this list of booleans
i            2   convert from binary to base 10 and print
\$\endgroup\$
  • 1
    \$\begingroup\$ The _B use is brilliant \$\endgroup\$ – isaacg Nov 4 '15 at 3:27
9
\$\begingroup\$

J, 31 30 24 23 21 bytes

+/(e.>./,<./@#~@)&.#:

This is a tacit, monadic verb that takes a list of decimal integers and returns their decimal biplex.

Thanks to @Zgarb for his suggestions, which saved 4 bytes directly and paved the way for 2 more!

Thanks to @randomra for golfing off 2 more bytes!

Test cases

   biplex =: +/(e.>./,<./@#~@)&.#:

   biplex ,1
1
   biplex ,2
2
   biplex 1 2 5
7
   biplex ,4294967295
4294967295
   biplex 2454267026 2863311530 3681400539
3817748707
   biplex 2341103945 2969112506 1849078949 1430639189
3

How it works

                 &.    Dual. Apply the verb to the right, the verb to the left,
                       and finally the inverse of the verb to the right.
                   #:  Convert the input list from integer to base 2.
  (            @)      Define an adverb, i.e., an operator that takes a verb as
                       its left argument.
+/                     Call it with "reduce by sum". This calculates the sum of
                       the corresponding binary digits of all integers before
                       executing the remainder of the adverb's body, i.e, this:
             #~          Replicate the sum N a total of N times, i.e., turn
                         0 1 2 3 into 1 2 2 3 3 3. This eliminates zeroes.
         <./@            Calculate the minimum of the result.
     >./                 Calculate the maximum of the sums.
        ,                Append; wrap both extrema into a list.
   e.                    Check if each of the sums is in the list of extrema.
                         This yields 1 if yes and 0 if no.
                       (from &.) Convert from base 2 to integer.
\$\endgroup\$
9
\$\begingroup\$

Minkolang 0.10, 109 79 bytes

(n1$(d2%$r2:d)99*I-DmI2:[+1R]$I)rI$d$(s0(x0gd,)Ik3R2g1-X0I3-[2*2gd0c=$r1c=++]N.

Input and output are in decimal. Try it here.

Explanation

(                            $I)    Loop until input is empty
 n                                  Read in number from input
  1$(       d)                      Start a while loop with only the top of stack
     d2%                            Next least-significant bit (modulo by 2)
        $r                          Swap top two values
          2:                        Divide by 2
              99*I-D                Pad with 0s
                                    (when the while loop exits, top of stack is 0)
                    m               Merge (interleave) stack
                     I2:[   ]       For each pair...
                         +1R        Add and rotate stack to the right
                                    <<This does the work of computing bitsums>>

r       Reverse stack
 I      Push length of stack
  $d    Duplicate whole stack
        <<This lets me sort the bitsums without affecting the original order>>

$(                      Start while loop with <top of stack> elements
  s                     Sort
   0(     )             Push a 0 and start another while loop
     x                  Dump top of stack
      0g                Get front of stack and put it on top
        d,              Duplicate and <not> for end-while condition check
           Ik           Push length of stack and break out of while loop
             3R         Rotate [min, max, length] to front
               2g1-     Get length and put it on top, then subtract 1
                   X    Dump that many elements off the top of stack
                        <<Now I have min and max>>

0                        Initialize decimal with 0    
 I3-[               ]    For as many bits as there are...
     2*                  Multiply by 2
       2gd               Get the next most significant bit and put it on top
          0c=            Copy min and check for equality
             $r          Swap top two elements of stack
               1c=       Copy max and check for equality
                  ++     Add 1 if bitsum item is equal to min or max, 0 otherwise
N.                       Output as integer and stop

Old version:

$nI[(d2%i1+0a+i1+0A00ai`4&i00A2:d)x]00a1+[i1+0a]s0(x0gd,)rI2-[x]00a1+[i1+0ad0c=$r1c=+]0gx0gx0(xd,)0I1-[2*+]N.

Try it here!

Explanation

The crux of it is that the array feature is heavily used (a A) to store the bitsums, of which the minimum and maximum are found, then 1s and 0s are outputted appropriately, with dumping of leading 0s in two places.

$n                                      Read in whole input as integers
  I[(                             x]    Convert each number to binary
     d2%                                Get next least significant bit (modulo by 2)
        i1+0a                           Get current value in array for that position
             +                          Add
              i1+0A                     Put current value in array for that position
                   00ai`                Get first value of array (bitsum length)
                      i`                Greater than loop counter?
                        4&i00A          If not, put loop counter there
                              2:        Divide by 2
                                d)      If 0, exit loop

00a                Get first value of array (maximum length
   1+              Add one
     [i1+0a]       Get bitsum values from array and push on stack
            s      Sort
0(                 Push a 0 (for dump) and start a while loop -- dumps leading 0s
  x                Dump top of stack
   0g              Get bottom of stack
     d,            Duplicate and <not> it
       )           Exit loop when top of stack is non-zero (i.e., the minimum)
        r          Reverse stack (so now it's [min, max, <stuff>])
         I2-[x]    Dump everything else

00a1+[               ]    Get bitsum length and loop that many times
      i1+0a               Get bitsum value at current position
           d              Duplicate
            0c=           Copy front of stack and check for equality
               $r         Swap
                 1c=      Copy next-to-front of stack and check for equality
                    +     Add (so it's 1 if it's equal to min or max, 0 otherwise)

0gx0gx       Dump front two elements of stack (the min and max)
0(xd,)       Dump leading 0s
0            Push 0 for conversion to decimal
 I1-[   ]    For each bit...
     2*+     Multiply by 2 and add
N.           Output as integer and stop
\$\endgroup\$
  • \$\begingroup\$ From the online interpreter, does this take decimal input and give binary output? \$\endgroup\$ – trichoplax Nov 4 '15 at 13:11
  • \$\begingroup\$ Yes. Do I need to change that? \$\endgroup\$ – El'endia Starman Nov 4 '15 at 20:48
  • 1
    \$\begingroup\$ Ahhh, I was looking for it in the bullet points and missed it in the very first sentence. I'll fix it sometime today. \$\endgroup\$ – El'endia Starman Nov 5 '15 at 21:10
  • 1
    \$\begingroup\$ Fixed! And with only two extra bytes! :D \$\endgroup\$ – El'endia Starman Nov 5 '15 at 23:03
  • 1
    \$\begingroup\$ You've earned my +1; I'm glad to learn about Minkolang. \$\endgroup\$ – lirtosiast Nov 7 '15 at 1:16
8
\$\begingroup\$

Brainfuck, 619 bytes

First answer in far too long here, so I thought I'd do a good one!

>->->->>>,----------[--<++++++[>------<-]>>>>,----------]-<<<+[-<<<+]->>,<++++[>--------<-]>[<++++[>+++++<-]>++[--<++++++[>------<-]>>>+>]<-[+>-<<+[-<<<+]-<<+[->+[->[-[->>>+<<<]<<<+]+[-->>>++]-<+]<<<+[-[->+<]<<<+]->>+>]<-[+>->>>>+[->>>+]->+[-<[-[->>>+<<<]<<<+]+[-->>>++]->+]-<+<<<+[-[->+<]<<<+]->>]]>,<++++[>--------<-]>]>+[->>>+]>->->>-[+<<<<<<+[-<-<<+]->>[+>>>[>>>]>+[<<->>[->>>+]->>>[-]+<<<<<+[-<<<+]+>->]<]>->>+>-]<[<<<<<+[-<+<<+]->>[-]>+[->>>+]->>-]>-[+<<<<<<+[-<+<<+]->>[->>>[>>>]>+[<<<->>>[->>>+]->>>[-]+<<<<<<+[-<<<+]+>>+>]<]>->>>-]<<<<-<<<<+[->[-]<[->+<]<[->>[-]+<<]<<+]>-[+>>>-]++[->++++++[-<++++++++>]<.>>>+]

Did... Did I win?

This program expects newlines (ASCII 10) after every binary number, and requires a space (ASCII 32) at the end.

Test runs:

Me$ bf bpx.bf
1
10
101

111

Me$ bf bpx.bf
11111111111111111111111111111111

11111111111111111111111111111111

Me$ bf bpx.bf
10010010010010010010010010010010
10101010101010101010101010101010
11011011011011011011011011011011

11100011100011100011100011100011

Me$ bf bpx.bf
10001011100010100110100101001001
10110000111110010000111110111010
1101110001101101011010010100101
1010101010001011101001001010101

11

(Newlines added after each case with ++++++++++. added at the end of the program)

Explanation

Still a work in progress, but a slow one. For lack of time, I've just copied the notes I made whilst writing this program, which will suffice for an explanation for now:

[Biplex Calculator]

[

Bitsum writing philosophy: 

Start with [0 255 255 255 ...].
The 255s will be markers that we can 'search' for to get back to the start.
After that, the next byte should be a 0, fairly permanently. (The first reference 0)
It is useful to have 0-bytes handy for general calculations. 
The next byte is where we will read the first digit of any binary number. (The first read)
The next byte holds the first bitsum.
Afterward, the next byte is 0, the following byte is the place
to read the second binary digit, the following byte is the second bitsum,
and so on.
I'll use the terminology nth reference 0, nth read, and nth bitsum to refer to
each part of the triplet of bytes.

The location three places after the final bitsum will be 255,
and the location three places after the final read will be 255.
We can move entire numbers by lining up these 255s after every binary number.

]


>->->->>>~                  [0 255 255 255 0 0 0 0 0                ]

[From the first bitsum, read input to create an initial set of bitsums                  ]
,----------
[
    --<++++++[>------<-]            [Convert the input '1' or '0' into a bit        ]
    >>>>,---------- 
]~                      
-<<<+[-<<<+]->>                 [Mark 255 after the last bit, then go back to first read]

,<++++[>--------<-]             [Check for space, using the first reference 0       ]
>
[
    <++++[>+++++<-]             [Check for \n                       ]
    >++
    [
        --<++++++[>------<-]        [It wasn't \n, so convert the input into a bit      ]
        >>>+>               [Write 1 to the next reference 0, and go to next read   ]
    ]
    <-
    [
        +>              [It was \n                      ]
        -<              [Mark 255 on this (nth) read and go to (n-1)th bitsum   ]
        <+[-<<<+]           [Search for a 255 off to the left           ]

        [We've either struck our marker, or the last bitsum. We need to check.          ]
        -<<+
        [
            -           [We hit the last bitsum. Move the bitsums right.    ]
            >+
            [
                ->[-[->>>+<<<]<<<+] [Move until we reach the start          ]
                +[-->>>++]      [From the start, move to our last bitsum    ]
                [Repeat this move until the read here is a 255              ]
                -<+
            ]
            [We now need to go to the first reference zero, and put a 1 there       ]
            <<<+[-[->+<]<<<+]->>+>      [Add bits to bitsums and end on first read  ]
        ]
        <-
        [
            +>->>>>+[->>>+]     [Go to the 255 after our reads              ]
            ->+
            [
                -<[-[->>>+<<<]<<<+] [Move until we reach the start          ]
                +[-->>>++]      [From the start, move to the 255 after our reads]
                [Repeat this move until we see the 255 bitsum               ]
                ->+
            ]
            [We now need to go to the first read                        ]
            -<+<<<+[-[->+<]<<<+]->>     [Add bits to bitsums and end on first read  ]
        ]
        >>>>>>>>>>>>>>>>>>>>>>>>>~<<<<<<<<<<<<<<<<<<<<<<<<<
    ]

    [We're at the reference 0 to the left of our next read                      ]
    >,<++++[>--------<-]            [Check for space, using the first reference 0       ]
    >
]

[

Let BN be the nth bitsum. Then our situation at the moment is:

[0 255 255 255 0 0 B1 0 0 B2 ... 0 0 BN 0 0 255] 
                 ^
I'm just happy nothing's exploded yet.

]

[Next goal: Mark the minimums                                       ]

>+[->>>+]>->->>~            [Zero the 255 and put 2 255s after it, then move after it   ]

-[
    +<<<<<<
    +[-<-<<+]               [Subtract one from each bitsum              ]
    ->>
    [
        +>>>[>>>]           [Find the first 0 bitsum                ]
        >+
        [
            <<->>[->>>+]->>>[-]     [Mark the zero as a minimum, and set a flag     ]
            +<<<<<+[-<<<+]+>->
        ]
        <
    ]
    >->>+>-
]~

[Hey, that worked. Weird. Alright, moving on...                             ]
[Reset the bitsums to what they were before we messed them all up                   ]

<[<<<<<+[-<+<<+]->>[-]>+[->>>+]->>-]>~

[After the stuff up there, that's not too bad.                              ]
[Now it's time to mark the maximums, in virtually the opposite way we did the minimums.         ]

-[
    +<<<<<<
    +[-<+<<+]               [Add one to each bitsum                 ]
    ->>
    [
        ->>>[>>>]           [Find the first 0 bitsum                ]
        >+
        [
            <<<->>>[->>>+]->>>[-]   [Mark the zero as a maximum, and set a flag     ]
            +<<<<<<+[-<<<+]+>>+>
        ]
        <
    ]
    >->>>-
]~

[Alright, now OR the maxs and mins, take care of leading zeros, output, and cross fingers       ]
<<<<->>~<<<<<<~+[->[-]<[->+<]<[->>[-]+<<]<<+]>-[+>>>-]++[->++++++[-<++++++++>]<.>>>+]
\$\endgroup\$
  • \$\begingroup\$ Newline separated and space terminated is perfectly valid. +1 \$\endgroup\$ – trichoplax Nov 9 '15 at 19:15
7
\$\begingroup\$

CJam, 27 bytes

q~2fbWf%:.+_0-$(\W>|fe=W%2b

Takes input as a base-10 CJam-style list. Test it here. Alternatively, run all test cases (the script discards the expected output and converts the input format as necessary).

Explanation

q~    e# Read and evaluate input.
2fb   e# Convert each number to base 2.
Wf%   e# Reverse each digit list, to align digits in case there are numbers with different 
      e# widths.
:.+   e# Add up the bit planes.
_0-   e# Make a copy and remove zeroes.
$     e# Sort the bit plane sums.
(\W>| e# Get the first and last element. We use set union instead of addition so that the
      e# resulting array will contain only one value if min = max.
fe=   e# For each element in the bit plane sums, count how often it appears in the min/max
      e# array, which is either 1 or 0.
W%    e# Reverse the digits again (to undo the initial reversing).
2b    e# Interpret as base-2 digits.
\$\endgroup\$
  • \$\begingroup\$ Shouldn't the output be the bitsum maximum and minimum? \$\endgroup\$ – DavidC Nov 3 '15 at 13:31
  • 1
    \$\begingroup\$ @DavidCarraher No, see the examples. The output should be a number whose binary representation has 1s in those bits which correspond to the bit planes where the minima and maxima occurred. \$\endgroup\$ – Martin Ender Nov 3 '15 at 13:32
6
\$\begingroup\$

JavaScript (ES6), 215 185 176 bytes

f=a=>{s=[];for(i of a)for(b=i.toString(2),d=l=b.length;d--;)s[x=l-d-1]=(s[x]|0)+(b[d]|0);q=255;for(r of s)d=r>d?r:d,q=r<q?r||q:q;o="";s.map(r=>o=(r==q|r==d)+o);return+("0b"+o)}

Usage

f([2454267026, 2863311530, 3681400539])
=> 3817748707

Explanation

f=a=>{

  // Create an array of bitsums
  s=[];                   // s = bitsums
  for(i of a)             // iterate through the passed array of numbers
    for(
      b=i.toString(2),    // b = number as binary string
      d=l=b.length;       // l = number of digits in b
      d--;                // iterate through each digit of the binary string
    )
      s[x=l-d-1]=         // add to the digit of the bitsum array
        (s[x]|0)+         // get the current value of the bitsum array (or 0 if null)
        (b[d]|0);         // add the result to the bitsum array

  // Get the maximum and minimum bitsums
  q=255;                  // q = min bitsum
  //d=0;                  // d = max bitsum
  for(r of s)             // iterate through the bitsums
    d=r>d?r:d,            // set d to maximum
    q=r<q?r||q:q;         // set q to minimum

  // Calculate the result
  // (unfortunately JavaScript only supports bitwise operations on signed 32-bit
  // integers so the temporary binary string is necessary)
  o="";                   // o = output
  s.map(r=>               // iterate through the bitsum digits
    o=(r==q|r==d)+o       // add a 1 to the string if the digit is equal to min or max
  );
  return+("0b"+o)         // convert the binary string to a number
}
\$\endgroup\$
  • 3
    \$\begingroup\$ Welcome to PPCG! I see a couple of ways that this could be made shorter. 1) When defining an arrow function with one parameter, you don't need the parentheses around it. f=(a)=>{} = f=a=>{} 2) You could turn your for...in loops into for...of loops, saving a few bytes: for(i in a)for(b=a[i]... = for(i of a)for(b=i..., for(i in s)r=s[i],d=... = for(r of s)d=... 3) Bitwise OR | automatically changes true to 1 and false to 0, so o+=r==q|r==d?1:0; is the same as o+=r==q|r==d;. \$\endgroup\$ – ETHproductions Nov 4 '15 at 2:45
  • 1
    \$\begingroup\$ At the end you can make: return parseInt(o,2) to: return+('0b'+o) \$\endgroup\$ – Downgoat Nov 5 '15 at 3:28
  • 1
    \$\begingroup\$ To save 2 bytes, you can replace s[l-d-1]=(s[l-d-1]|0) with s[T=l-d-1]=(s[T]|0). To shave more 2, replace b=i.toString(2),l=b.length,d=l with d=l=(b=i.toString(2)).length. \$\endgroup\$ – Ismael Miguel Nov 5 '15 at 9:37
4
\$\begingroup\$

Julia, 141 bytes

A->(s=reduce(.+,map(i->digits(i,2,maximum(map(i->ndigits(i,2),A))),A));parse(Int,reverse(join([1(i∈extrema(filter(j->j>0,s)))for i=s])),2))

Ungolfed:

function biplex(A::AbstractArray)
    # Get the maximum number of binary digits in each element
    # of the input array
    L = maximum(map(i -> ndigits(i, 2), A))

    # Create an array of arrays of binary digits corresponding
    # to the inputs
    B = map(i -> digits(i, 2, L), A)

    # Get the bitsums
    S = reduce(.+, B)

    # Replace the minimum and maximum bitsums with ones and
    # the rest with zeros
    s = [1 * (i in extrema(filter(j -> j > 0, S))) for i in S]

    # Join this into a string and parse it as a base 2 integer
    # Reverse is required because digits() returns the digits
    # in reverse order
    p = parse(Int, reverse(join(s)), 2)

    return p
end
\$\endgroup\$
3
\$\begingroup\$

Simplex v.0.7, 38 bytes

Simplified comments. Input in Binary, no interpreter working at the moment. Hopefully the comments are sufficient.

hj&=j&Lun?&RvRpp]{Ri}^XKRJ@jqLhR@LhuTo
h               ]                        ~~ define macro 0
 j&                                      ~~ insert a new byte and write register to it
   =                                     ~~ equal to the previous byte?
    j&                                   ~~ insert a new byte and write register to it
      L                                  ~~ return to equality
       u    v                            ~~ go up/down a strip
        n?&                              ~~ write the register iff byte = 0
           R                             ~~ go right
             Rpp                         ~~ remove two bytes
                 {Ri}                    ~~ take input until input = 0
                     ^X                  ~~ take the sum of the strip
                       K                 ~~ split that sum into digits
                        RJ@              ~~ take the max; write to register
                           jq            ~~ take the min
                             Lh          ~~ call macro 0
                               R@        ~~ set min to register
                                 Lh      ~~ apply macro 0
                                   uTo   ~~ output result 
\$\endgroup\$
3
\$\begingroup\$

Octave, 50 bytes

@(a)["" ((b=sum(a-48))==max(b)|b==min(b(b>0)))+48]

Example:

octave:1> g = @(a)["" ((b=sum(a-48))==max(b)|b==min(b(b>0)))+48] ;
octave:2> g(["10010010010010010010010010010010"; "10101010101010101010101010101010"; "11011011011011011011011011011011"])
ans = 11100011100011100011100011100011
\$\endgroup\$
  • \$\begingroup\$ I'd love to see an explanation for this one... \$\endgroup\$ – trichoplax Nov 4 '15 at 9:18
  • 2
    \$\begingroup\$ @trichoplax I'm not too brilliant with matlab/octave, but hopefully this helps: @(a) defines an anonymous function that takes an input vector a. ["" forces the output into a string (I believe). (b=sum(a-48)) defines b to be the vector containing the bitsums. b==max(b) will be a vector having a 1 in a given place if the bitsum there is a maximum, and a 0 otherwise. b(b>0) is a vector of every element of b greater than 0, so b==min(b(b>0)) is a vector containing a 1 when the bitsum is the minimum, and 0 otherwise. Then it's OR'd together, and +48 for ASCII. \$\endgroup\$ – BrainSteel Nov 4 '15 at 16:29
  • \$\begingroup\$ @BrainSteel all makes sense now - thank you \$\endgroup\$ – trichoplax Nov 4 '15 at 17:30
  • \$\begingroup\$ Sometimes I forget how different Octave and MATLAB are. I guess I should really start using Octave for golfing in the future, my shortest MATLAB attempt is 60 bytes because you cannot use inline assignment and end up with function o=b(i) (newline) r=sum(i>48);o=['' (r==max(r)|r==min(r))+48]; \$\endgroup\$ – Sanchises Nov 10 '15 at 13:44
3
\$\begingroup\$

JavaScript (ES6), 158

A function with a numeric array parameter, returning a number. With the same byte count it could get a string array parameter (containing base 2 rapresentations) and return a base 2 string - just move the .toString(2) at the end after r.

f=l=>(l.map(v=>[...v.toString(2)].reverse().map((x,i)=>t[i]=~~t[i]-x),t=[]),t.map(v=>(r+=v==Math.min(...t)|v==Math.max(...t.filter(x=>x))&&b,b+=b),r=0,b=1),r)

// More readable

u=l=>(
  t=[],
  l.map(v =>
    [...v.toString(2)]
    .reverse()
    .map((x,i) => t[i] = ~~t[i] - x)
  ),
  r=0,b=1,
  t.map(v => (
    r += v==Math.min(...t) | v==Math.max(...t.filter(x=>x)) && b, b+=b
  )),
  r
)

// Test
console.log=s=>O.innerHTML+=s+'\n'

;[
 [[1], 1]
,[[2], 2]
,[[1, 2, 5], 7]
,[[4294967295], 4294967295]
,[[2454267026, 2863311530, 3681400539], 3817748707]
,[[2341103945, 2969112506, 1849078949, 1430639189], 3]
].forEach(t =>{ 
  r=f(t[0])
  x=t[1]
  console.log('Test '+(r==x?'OK':'Fail (Expected: ' + x +')')
  +'\nInput: '+t[0]+'\nResult: ' +r+'\n')                       
})  
<pre id=O></pre>

\$\endgroup\$
3
\$\begingroup\$

Haskell, 198 182 178 161 character

I'm still beginner at golfing. Only 80 reputation comes from answer.

m=map
v=reverse
(b:x)&(c:y)=(b+c):x&y
[]&a=a
b&_=b
l=(show=<<).v.(\a->m(fromEnum.(`elem`[maximum a,minimum$(replicate=<<id)=<<a]))a).foldl1(&).m(m(read.(:[])).v)

How does it work.

Instead of padding, I reverse the array then I add using user defined (&). I don't use foldl1(zipWith(+)) that is shorter because zipWith will delete the superflous item. Then I find the maximum and nonzero minimum, that also required user defined function. Then I match the item with the maximum and nonzero minimum, 1 if match, 0 if it doesn't match. Then we reverse and turn it into binary number.

TODO:

  1. Using Data.List
\$\endgroup\$
  • 2
    \$\begingroup\$ In the definition of k, c is only used once, so no need to put it in the where clause. Use it directly: ...||(x==a#b).... Why the curly braces? In l: concat.map show is concatMap show or even better >>=: l=(>>=show).v.... (Note: there's also =<< which does the same, but with arguments flipped: (show=<<).v...). >>= and =<< work in list context here and do different things in function or other contexts. \$\endgroup\$ – nimi Nov 4 '15 at 13:39
  • 2
    \$\begingroup\$ You can replace [] in the last cases of & and # with _: b&_=b and _#l=l. \$\endgroup\$ – nimi Nov 4 '15 at 13:43
  • 2
    \$\begingroup\$ (x==b)||(x==c) (or (x==b)||(x==a#b) when you remove c) can be replaced by elem x[b,c] (resp: elem x[b,a#b]). \$\endgroup\$ – nimi Nov 4 '15 at 13:50
  • 2
    \$\begingroup\$ u=maximum and k a=m(\x->fromEnum$elem x[u a,a#u a])a should work. \$\endgroup\$ – nimi Nov 4 '15 at 13:58
  • 1
    \$\begingroup\$ Don't do _&a=a, it must stay []&a=a, else the first list is lost if the second is empty. Use _ only in the last case - maybe that is your error. \$\endgroup\$ – nimi Nov 4 '15 at 14:03
3
\$\begingroup\$

Python 3, 181 126 122 bytes

(I took out most of the byte count slashes because it was getting a bit ridiculous.) 21 bytes off thanks to Sp3000!

*z,=map(sum,zip(*[map(int,t.zfill(99))for t in input().split()]))
k=0
for x in z:k=k*10+(x in[min(z)or 1,max(z)])
print(k)

Slightly less golfed:

s=input().split()
k=list(map(lambda t:list(map(int,t))[::-1],s))
z=list(map(sum,zip(*k)))
y=z[:]
while min(y)==0:y.remove(0)
a,b=min(y),max(y)
f=''.join(map(lambda x:str(1*(x in[a,b])),z[::-1]))
print(int(f))

Input is expected in binary with only spaces separating the numbers. Output is in binary as well.

\$\endgroup\$
3
\$\begingroup\$

Javascript, 154 150 bytes

t=i=>(m=0,r=[],i.map(n=>{for(j=31;j+1;r[k=31-j]=(r[k]|0)+((n>>>j)%2),--j);}),r.map(n=>m=(n==Math.min(...r.filter(x=>x))|n==Math.max(...r)?1:0)+m*2),m)

Thanks for edc65 method for min/max calculation, it shortened my code by 4 bytes.

Explanation

t=i=>(
    m=0,//m=>output
    r=[],//Bitsum then final number in binary
    i.map(
        n=>
        {
            //Decimal to binary + bitsum
            for(j=31;j+1;r[k=31-j]=(r[k]|0)+((n>>>j)%2),--j);
        }),
    //Output formatting
    r.map(
        n=>
            m=(n==Math.min(...r.filter(x=>x))|n==Math.max(...r)?1:0)+m*2
        ),
    m
)
\$\endgroup\$
  • \$\begingroup\$ +1 nice. Bit arithmetic beats string conversion by far. And I see 2 ways to shorten it more. \$\endgroup\$ – edc65 Nov 7 '15 at 14:23
  • \$\begingroup\$ 132: f=i=>(m=0,r=[],i.map(n=>{for(k=32;k--;n=n/2|0)r[k]=~~r[k]+n%2}),r.map(n=>m+=m+(n==Math.min(...r.filter(x=>x))|n==Math.max(...r))),m) \$\endgroup\$ – edc65 Nov 7 '15 at 14:38
  • \$\begingroup\$ Even better! I need to learn more about golfing for loops, still not use to hijeck for instructions. \$\endgroup\$ – Naouak Nov 7 '15 at 14:44
3
\$\begingroup\$

ShapeScript, 186 bytes

'"1
"$0?_1-"+"*":2"@~@"0
"~"0
"$"
"~+'1?_*!"2"$"0"~"
"$""~":"1?'@1?"+"$_1>"+"*+@1?"0"+$""~'1?_*!#"0"+@":+"'1?1?"0"+$_2<"+"*+'1?_*!"0"+$"1"~@$"1"~":"$""~"+"$""~'"
"@+"
0"$""~'1?_*!"
"$""~

An important, useless language for an important, useless operator.

I/O is in binary. The program expects each number on a separate line, each ending with a linefeed.

Try it online!

Test cases

$ echo -e '1' | shapescript biplex.shape; echo
1
$ echo -e '10' | shapescript biplex.shape; echo
10
$ echo -e '1\n10\n101' | shapescript biplex.shape; echo
111
$ echo -e '11111111111111111111111111111111' | shapescript biplex.shape; echo11111111111111111111111111111111
$ echo -e '10010010010010010010010010010010\n10101010101010101010101010101010\n11011011011011011011011011011011' | shapescript biplex.shape; echo
11100011100011100011100011100011
$ echo -e '10001011100010100110100101001001\n10110000111110010000111110111010\n1101110001101101011010010100101\n1010101010001011101001001010101' | shapescript biplex.shape; echo
11
\$\endgroup\$
  • \$\begingroup\$ I don't know what this garbage is you call a language, but I love it! \$\endgroup\$ – phase Nov 10 '15 at 5:37
2
\$\begingroup\$

APL, 27 bytes

{2⊥S∊(⌈/,⌊/)0~⍨S←+/⍵⊤⍨32⍴2}

This is a monadic function that takes a list of decimal integers and returns their decimal biplex.

Try it online in the ngn/apl demo.

How it works

                     32⍴2  Create a list of 32 2's.
                  ⍵⊤⍨      Base-encode the right argument.
                +/         Add the corresponding binary digits.
              S←           Save the sums in S.
           0~⍨             Remove 0's.
    (⌈/,⌊/)                Apply minimum (⌊/), maximum (⌈/) and concatenate.
  S∊                       Check which binary digits are in the extrema list.
2⊥                         Convert from base 2 to integer.
\$\endgroup\$
2
\$\begingroup\$

Wolfram Language, 113 bytes

This version takes input from a popup window, with the numbers being input in the form "{x,y,z,...}", (no quotes).

FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@Input[]]

Input:

popup window dynamic

Output:

output

Takes input in a dynamic Manipulate as a string of the form "{x,y,z}" with x, y, and z being base 10 integers (with or without leading zeroes). The output is also in base 10.

Manipulate[FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@ToExpression@i],{i,"{1}"}]

example

There are other ways to input this in a way that would save on character counts, but I think this solution is an elegant use of a dynamic GUI that performs the computation

If you want to run this in the cloud, we can use CloudDeploy:

o=CloudDeploy[FormPage[{"i"->"String"},(FromDigits[#/.{Max[#]->1,Min[#/.{0->Nothing}]->1,_Integer->0},2]&@Total[PadLeft[IntegerDigits[#,2],33]&/@ToExpression@#i])&]];SetOptions[o,Permissions->{All->{"Read","Execute"},"Owner"->{"Read","Write","Execute"}}];o

The Cloud deploy brings the character count up to 256 however...

The input to the FormPage is also a string of the form "{x,y,z}" with x, y, and z being base 10 integers.

I cloud-deployed this myself and you can try it out at https://www.wolframcloud.com/objects/97b512df-64f8-4cae-979b-dba6d9622781

cloud example

\$\endgroup\$
  • \$\begingroup\$ I've tested the cloud link without the leading zeroes and it still correctly outputs 3. \$\endgroup\$ – trichoplax Nov 12 '15 at 12:24
  • \$\begingroup\$ If you have shorter code without the GUI, you can edit it into this answer to improve your score, and still leave the GUI version in your answer as an alternative example to show what's possible. Best of both worlds... \$\endgroup\$ – trichoplax Nov 12 '15 at 12:28
  • \$\begingroup\$ @trichoplax Noted, I added what I think is the shortest version with Input[]. Could also hypothetically expect the numbers to be stored in a variable, which could also decrease the character count, but then it's ambiguous as to how you enter the input into it I think \$\endgroup\$ – Ian Johnson Nov 12 '15 at 15:39
  • \$\begingroup\$ Storing the numbers in a variable isn't one of the default input methods... So that additional step isn't available, but what you have so far is great :) \$\endgroup\$ – trichoplax Nov 12 '15 at 21:33
1
\$\begingroup\$

Python 3, 197

import itertools
o='0'
d=[sum(map(int,n))for n in itertools.zip_longest(*map(reversed,input().split(' ')),fillvalue=o)]
m=max(d),min(d)or 1
print(''.join((o,'1')[g in m]for g in d[::-1]).lstrip(o))

It takes in space delimited binary numbers.

Ungolfed version:

import itertools
nums = map(reversed, input().split(' '))
digits = []
for num in itertools.zip_longest(*nums, fillvalue='0'):
    current_digit = sum(map(int,num))
    digits.append(current_digit)
bit_max = max(digits)
bit_min = min(digits) or min(digits) + 1
print(''.join(('0','1')[digit in(bit_max,bit_min)]for digit in digits[::-1]).lstrip('0'))
\$\endgroup\$
1
\$\begingroup\$

C#, 255

A complete program, input as command line arguments - space separated - in decimal.

using System.Linq;class P{static void Main(string[]l){var n=new uint[32];uint i,r=0,b;foreach(var v in l)for(i=0,b=uint.Parse(v);b!=0;b/=2)n[i++]+=b&1;b=1;foreach(var v in n){r+=(v==n.Max()|v== n.Min(x=>x>0?x:n.Max()))?b:0;b+=b;}System.Console.Write(r);}}

More readable:

using System.Linq;

class P
{
    static void Main(string[] l)
    {
        var n = new uint[32];
        uint i, r = 0, b;

        foreach (var v in l)
            for (i = 0, b = uint.Parse(v); b != 0; b /= 2) n[i++] += b & 1;
        b = 1;
        foreach (var v in n)
        {
            r += (v == n.Max() | v == n.Min(x => x > 0 ? x : n.Max())) ? b : 0;
            b += b;
        }
        System.Console.Write(r);
    }
}
\$\endgroup\$
1
\$\begingroup\$

Ruby, 127 bytes

def f l;a=[];32.times{|i|a[i]=0;l.each{|n|;a[i]+=n[i]}};a.map{|b|a.reject{|c|c==0}.minmax.index(b)?1:0}.reverse.join.to_i 2;end

Takes an array as input.

\$\endgroup\$
1
\$\begingroup\$

CoffeeScript, 194 bytes

Takes input as coma separated binary numbers, outputs in binary.

a=(s.split('').reverse()for s in prompt().split(','))
for i in b=[0..31]
 b[i]=0
 b[i]+=+c[31-i]||0for c in a
m=1/M=0
for d in b
 M=d if d>M;m=d if m>d&&d
alert +(+(d in[m,M])for d in b).join ''

Try it.

\$\endgroup\$
1
+150
\$\begingroup\$

GolfScript, 46 bytes

~{2base-1%}%zip{{+}*}%-1%.$0-)\1<|`{&,}+%2base

Try it online on Web GolfScript.

Test cases

$ golfscript biplex.gs <<< '[1]'
1
$ golfscript biplex.gs <<< '[2]'
2
$ golfscript biplex.gs <<< '[1 2 5]'
7
$ golfscript biplex.gs <<< '[4294967295]'
4294967295
$ golfscript biplex.gs <<< '[2454267026 2863311530 3681400539]'
3817748707
$ golfscript biplex.gs <<< '[2341103945 2969112506 1849078949 1430639189]'
3
\$\endgroup\$
1
\$\begingroup\$

C++, 192 bytes

Accepts input a 32 bit unsigned integer array, and a count of items in that array.

typedef unsigned long U;U b(U*a,int c){U x[32],t,i,j,M=0,m=c,r=0;for(i=0;i<32;x[i++]=t,m=t&&m>t?t:m,M=M<t?t:M)for(t=j=0;j<c;)t+=a[j++]>>i&1;for(i=0;i<32;++i)r|=(x[i]==m||x[i]==M)<<i;return r;}

Ungolfed :

unsigned long b(unsigned long*a, int c){
    unsigned long x[32],t,i,j,M=0,m=c,r=0;
    for(i=0;i<32;x[i++]=t){
        m = (t && m > t)?t:m;
        M = M < t ? t:M;
        for(t=j=0;j<c;){
            t+=a[j++]>>i&1;
        }
    }
    for(i=0;i<32;++i)
        r|=(x[i]==m||x[i]==M)<<i;
    return r;
}
\$\endgroup\$
  • 1
    \$\begingroup\$ @trichoplax I changed it. \$\endgroup\$ – MegaTom Nov 13 '15 at 3:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.