Biplex: ważny bezużyteczny operator


33

Wkład

  • Lista od 1 do 255 dodatnich liczb całkowitych (włącznie), każda w zakresie od 1 do 2 32 - 1 (włącznie).
  • Twój format wejściowy nie musi być identyczny z przypadkami testowymi.
  • Podanie danych bez zer wiodących musi zostać zaakceptowane.
  • Podanie z wiodącymi zerami nie jest akceptowane.
  • Między liczbami całkowitymi możesz użyć dowolnego ogranicznika.
  • Liczba całkowita może być reprezentowana przez ciąg, ale poszczególne cyfry określonej liczby całkowitej muszą być ciągłe.
  • Możesz wybrać dowolną bazę danych wejściowych (w tym binarną i jednoargumentową), pod warunkiem, że dane wyjściowe również znajdują się w tej bazie.

Wydajność

  • Jedna liczba całkowita.
  • Dane wyjściowe nie mogą mieć zer wiodących.
  • Dane wyjściowe muszą być w tej samej bazie co dane wejściowe.
  • Wynik można obliczyć w dowolny sposób, ale musi on pasować do wyniku następującego obliczenia:

Obliczanie biplex

  • Bity reprezentacji binarnej są ponumerowane od prawej strony, zaczynając od zera, więc bit i znajduje się w kolumnie reprezentującej 2 i .
  • I th bitsum jest sumą í th bitów binarnych reprezentacji każdego z numerów wejściowych.
  • Bitsum maksymalna jest najwyższą wartością podjęte przez bitsums.
  • Minimum bitsum jest najniższy niezerową wartość podjęte przez bitsums.
  • I th cyfra binarna reprezentacja wyjścia jest:
    • 1, jeżeli i- ty bitum jest równy maksimum bitowemu lub minimum bitowemu.
    • 0 w przeciwnym razie.

Przykład działał

W tym przykładzie zastosowano dane binarne dla danych wejściowych i wyjściowych.

Input:    100110
         1101110
         1100101
         _______
Bitsums: 2301321

Output:   101101

Maksymalna wartość bitowa wynosi 3, a minimalna wartość bitowa wynosi 1, więc wyjście ma 1s wszędzie, że bitsum to 3 lub 1, a 0 wszędzie indziej.


Przypadki testowe

Przypadki testowe mają postać:

Input => Output

Przypadki testowe w formacie binarnym:

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

Te same przypadki testowe w systemie dziesiętnym:

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

Tabela liderów

Dzięki fragmentowi tablicy wyników Martina


Operator został nazwany biplex, skrót od binarnego ekstremum samolotu, po dyskusji na czacie .


Czy możemy wymagać, aby dane wejściowe były binarne, jak w przykładzie?
feersum

1
@feersum You may choose to use any base for input and output (including binary and unary), provided they are both in the same base. Więc tak, idź na to :)
trichoplax

Czy możemy używać notacji takich jak [[1,0,1], [1,1,0,0], [1,0,0,1]]?
Akangka

Prawdopodobnie nie. Załóż najbardziej restrykcyjny.
Akangka

@ChristianIrwan Dane wejściowe powinny mieć postać liczb całkowitych (każda składa się z ciągłych cyfr). Liczba całkowita może być reprezentowana jako ciąg, ale między cyframi nie powinno być żadnych separatorów.
trichoplax

Odpowiedzi:


1

Galaretka, niekonkurująca

14 bajtów Ta odpowiedź nie konkuruje, ponieważ wyzwanie poprzedza powstanie galaretki.

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

Wypróbuj online!

Jak to działa

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.                

Chociaż nie ma zgody co do tego, jak dokładnie to ocenić, to meta-pytanie sugeruje, że społeczność zdecydowanie opowiada się za tym, aby nie oznaczać odpowiedzi jako niekonkurujących, gdy wyzwanie poprzedza stworzenie języka. Dlatego akceptuję tę odpowiedź.
trichoplax

11

Pyth, 26 25 bajtów

JsM.T_MjR2Qi_}RhM_BS-J0J2

Wypróbuj online: pakiet demonstracyjny lub testowy

Wyjaśnienie

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

1
_BStosowanie jest genialny
isaacg

9

J, 31 30 24 23 21 bajtów

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

Jest to milczący, monadyczny czasownik, który pobiera listę liczb całkowitych dziesiętnych i zwraca ich dziesiętny bipleks.

Dzięki @Zgarb za sugestie, które pozwoliły zaoszczędzić 4 bajty bezpośrednio i utorowały drogę dla 2 kolejnych!

Dzięki @randomra za grę w golfa jeszcze 2 bajty!

Przypadki testowe

   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

Jak to działa

                 &.    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.

9

Minkolang 0.10 , 109 79 bajtów

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

Dane wejściowe i wyjściowe są dziesiętne. Wypróbuj tutaj.

Wyjaśnienie

(                            $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

Stara wersja:

$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.

Wypróbuj tutaj!

Wyjaśnienie

Chodzi o to, że funkcja tablicowa jest intensywnie używana ( a A) do przechowywania bitów, z których można znaleźć minimum i maksimum, a następnie 1s i 0s są odpowiednio wyprowadzane, z zrzutem wiodących 0s w dwóch miejscach.

$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

Czy interpreter online pobiera dane dziesiętne i daje dane binarne?
trichoplax

Tak. Czy muszę to zmienić?
El'endia Starman

1
Ahhh, szukałem tego w punktorach i przegapiłem to w pierwszym zdaniu. Naprawię to dzisiaj.
El'endia Starman

1
Naprawiony! I tylko z dwoma dodatkowymi bajtami! : D
El'endia Starman

1
Zarobiłeś moje +1; Cieszę się, że mogę dowiedzieć się o Minkolangu.
lirtosiast

8

Brainfuck , 619 bajtów

Pierwsza odpowiedź tutaj za długo, więc pomyślałem, że zrobię dobrą!

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

Czy ... Czy wygrałem?

Ten program oczekuje znaku nowej linii (ASCII 10) po każdej liczbie binarnej i wymaga spacji (ASCII 32) na końcu.

Przebiegi testowe:

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

(Nowe linie dodawane po każdym przypadku z ++++++++++.dodawane na końcu programu)

Wyjaśnienie

Wciąż trwają prace, ale powolne. Z braku czasu właśnie skopiowałem notatki, które zrobiłem podczas pisania tego programu, które na razie wystarczą na wyjaśnienie:

[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       ]
<<<<->>~<<<<<<~+[->[-]<[->+<]<[->>[-]+<<]<<+]>-[+>>>-]++[->++++++[-<++++++++>]<.>>>+]

Nowa linia oddzielona i spacja zakończona jest całkowicie poprawna. +1
trichopaks

7

CJam, 27 bajtów

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

Pobiera dane wejściowe jako listę bazową w stylu CJam-10. Sprawdź to tutaj. Alternatywnie uruchom wszystkie przypadki testowe (skrypt odrzuca oczekiwane dane wyjściowe i konwertuje format wejściowy w razie potrzeby).

Wyjaśnienie

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.

Czy wyjście nie powinno być maksymalnym i minimalnym bitem?
DavidC,

1
@DavidCarraher Nie, zobacz przykłady. Wyjście powinno być liczbą, której reprezentacja binarna ma 1s w tych bitach, które odpowiadają płaszczyznom bitów, w których wystąpiły minima i maksima.
Martin Ender

6

JavaScript (ES6), 215 185 176 bajtów

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)}

Stosowanie

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

Wyjaśnienie

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
}

3
Witamy w PPCG! Widzę kilka sposobów, które można by skrócić. 1) Podczas definiowania funkcji strzałki za pomocą jednego parametru nie potrzebujesz nawiasów wokół niego. f=(a)=>{}= f=a=>{}2) Możesz zamienić swoje for...inpętle w for...ofpętle, oszczędzając kilka bajtów: 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) Bitowe LUB |automatycznie zmienia wartość true na 1 i false na 0, więc o+=r==q|r==d?1:0;to samo co o+=r==q|r==d;.
ETHprodukcje

1
Na koniec możesz wykonać: return parseInt(o,2)do:return+('0b'+o)
Downgoat

1
Aby zapisać 2 bajty, można zastąpić s[l-d-1]=(s[l-d-1]|0)z s[T=l-d-1]=(s[T]|0). Golić więcej 2, wymienić b=i.toString(2),l=b.length,d=lz d=l=(b=i.toString(2)).length.
Ismael Miguel,

4

Julia, 141 bajtów

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

Nie golfowany:

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

3

Simplex v.0.7 , 38 bajtów

Uproszczone komentarze. Wejście w formacie binarnym, w tej chwili nie działa interpreter. Mam nadzieję, że komentarze są wystarczające.

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 

3

Oktawa, 50 bajtów

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

Przykład:

octave:1> g = @(a)["" ((b=sum(a-48))==max(b)|b==min(b(b>0)))+48] ;
octave:2> g(["10010010010010010010010010010010"; "10101010101010101010101010101010"; "11011011011011011011011011011011"])
ans = 11100011100011100011100011100011

Chciałbym zobaczyć wyjaśnienie tego ...
trichoplax

2
@trichoplax Nie jestem zbyt błyskotliwy w matlab / oktawie, ale mam nadzieję, że to pomaga: @(a)definiuje anonimową funkcję, która przyjmuje wektor wejściowy a. ["" zmusza dane wyjściowe do ciągu (tak mi się wydaje). (b=sum(a-48))definiuje bsię jako wektor zawierający bitów. b==max(b)będzie wektorem mającym 1w danym miejscu, jeśli bit jest tam maksimum, a 0inaczej. b(b>0)jest wektorem każdego elementu bwiększego niż 0, więc b==min(b(b>0))jest wektorem zawierającym, 1gdy bitsum jest minimum, i w 0przeciwnym razie. Potem jest OR razem i +48dla ASCII.
BrainSteel,

@BrainSteel wszystko ma teraz sens - dziękuję
trichoplax

Czasami zapominam, jak różne są Octave i MATLAB. Myślę, że naprawdę powinienem zacząć używać Octave do gry w golfa, moja najkrótsza próba MATLAB to 60 bajtów, ponieważ nie możesz użyć przypisania liniowego i skończyć na function o=b(i)(newline)r=sum(i>48);o=['' (r==max(r)|r==min(r))+48];
Sanchises

3

JavaScript (ES6), 158

Funkcja z parametrem tablicy numerycznej zwracająca liczbę. Przy tej samej liczbie bajtów może uzyskać parametr tablicy ciągów (zawierający prezentacje bazy 2) i zwrócić ciąg bazy 2 - wystarczy przesunąć .toString(2)koniec na końcu po 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>


3

Haskell, 198 182 178 161 znaków

Nadal jestem początkującym golfistą. Tylko 80 reputacji pochodzi z odpowiedzi.

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)

Jak to działa.

Zamiast wypełniania odwracam tablicę, a następnie dodaję, używając zdefiniowanego przez użytkownika (&). Nie używam foldl1 (zipWith (+)), który jest krótszy, ponieważ zipWith usunie zbędny element. Następnie znajduję maksimum i niezerowe minimum, które również wymaga funkcji zdefiniowanej przez użytkownika. Następnie dopasowuję element do maksimum i niezerowego minimum, 1 jeśli pasuje, 0 jeśli nie pasuje. Następnie odwracamy i zamieniamy go na liczbę binarną.

DO ZROBIENIA:

  1. Za pomocą Data.List

2
W definicji k, cjest używany tylko raz, więc nie trzeba go umieszczać w whereklauzuli. Użyj go bezpośrednio: ...||(x==a#b).... Dlaczego nawiasy klamrowe? W l: concat.map showjest concatMap showalbo jeszcze lepiej >>=: l=(>>=show).v.... (Uwaga: jest też to, =<<co robi to samo, ale z odwróconymi argumentami:) (show=<<).v.... >>=i =<<pracuj tutaj w kontekście listy i rób różne rzeczy w funkcji lub w innych kontekstach.
nimi

2
Można wymienić []w ciągu ostatnich przypadkach &oraz #z _: b&_=ba _#l=l.
nimi

2
(x==b)||(x==c)(lub (x==b)||(x==a#b)po usunięciu c) można zastąpić przez elem x[b,c](odpowiednio:) elem x[b,a#b].
nimi

2
u=maximumi k a=m(\x->fromEnum$elem x[u a,a#u a])apowinien działać.
nimi

1
Nie rób _&a=a, musi pozostać []&a=a, w przeciwnym razie pierwsza lista zostanie utracona, jeśli druga będzie pusta. Używaj _tylko w ostatnim przypadku - może to jest twój błąd.
nimi

3

Python 3, 181 126 122 bajtów

( Wyjąłem większość ukośników z liczby bajtów, ponieważ robiło się to trochę śmieszne). 21 bajtów off dzięki 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)

Nieco mniej golfa:

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))

Dane wejściowe są oczekiwane w postaci binarnej, przy czym tylko spacje oddzielają liczby. Dane wyjściowe są również binarne.


3

JavaScript, 154 150 bajtów

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)

Dzięki za metodę edc65 do obliczeń min./maks. Skróciłem mój kod o 4 bajty.

Wyjaśnienie

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
)

+1 fajnie. Zdecydowanie bitowa arytmetyczna konwersja ciągu znaków. Widzę 2 sposoby, aby bardziej to skrócić.
edc65,

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)
edc65,

Nawet lepiej! Muszę dowiedzieć się więcej o grze w golfa w pętlach, wciąż nie używam instrukcji hijeck.
Naouak

3

ShapeScript , 186 bajtów

'"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?_*!"
"$""~

Ważny, bezużyteczny język dla ważnego, bezużytecznego operatora.

I / O jest w formacie binarnym. Program oczekuje każdej liczby w osobnej linii, z których każda kończy się na linii.

Wypróbuj online!

Przypadki testowe

$ 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

Nie wiem, jak te śmieci nazywacie językiem , ale uwielbiam to!
faza

2

APL, 27 bajtów

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

Jest to funkcja monadyczna, która pobiera listę liczb całkowitych dziesiętnych i zwraca ich bipleks dziesiętny.

Wypróbuj online w wersji demonstracyjnej ngn / apl .

Jak to działa

                     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.

2

Wolfram Language, 113 bajtów

Ta wersja pobiera dane z wyskakującego okna, przy czym liczby są wprowadzane w postaci „{x, y, z, ...}”, (bez cudzysłowów).

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

Wkład:

wyskakujące okno dynamiczne

Wydajność:

wydajność

Pobiera dane wejściowe w dynamicznym manipulatorze jako ciąg w postaci „{x, y, z}”, gdzie x, y i z są podstawowymi liczbami całkowitymi 10 (z zerami wiodącymi lub bez). Dane wyjściowe znajdują się również w bazie 10.

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

przykład

Istnieją inne sposoby wprowadzania tego w sposób, który pozwoliłby zaoszczędzić na liczbie znaków, ale myślę, że to rozwiązanie jest eleganckim zastosowaniem dynamicznego GUI, który wykonuje obliczenia

Jeśli chcesz uruchomić to w chmurze, możemy użyć 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

Wdrożenie w chmurze zwiększa liczbę znaków do 256, jednak ...

Dane wejściowe do strony FormPage są także ciągiem znaków w postaci „{x, y, z}”, gdzie x, yiz stanowią 10 liczb całkowitych podstawowych.

Sam to wdrożyłem w chmurze i możesz to wypróbować na https://www.wolframcloud.com/objects/97b512df-64f8-4cae-979b-dba6d9622781

przykład chmury


Przetestowałem link do chmury bez wiodących zer i nadal poprawnie wyprowadza 3.
trichoplax

Jeśli masz krótszy kod bez GUI, możesz edytować go w tej odpowiedzi, aby poprawić swój wynik, i nadal pozostaw wersję GUI w odpowiedzi jako alternatywny przykład, aby pokazać, co jest możliwe. Najlepsze z obu światów ...
trichoplax

@trichoplax Zauważyłem, że dodałem coś, co moim zdaniem jest najkrótszą wersją z Input []. Można również hipotetycznie oczekiwać, że liczby będą przechowywane w zmiennej, co może również zmniejszyć liczbę znaków, ale myślę, że sposób wprowadzania danych wejściowych jest niejasny
Ian Johnson

Przechowywanie liczb w zmiennej nie jest jedną z domyślnych metod wprowadzania danych ... Więc ten dodatkowy krok nie jest dostępny, ale to, co do tej pory masz, jest świetne :)
trichoplax

1

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))

Zajmuje liczby binarne rozdzielane spacjami.

Wersja bez golfa:

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'))

1

C #, 255

Kompletny program, wprowadzany jako argumenty wiersza poleceń - oddzielone spacją - dziesiętnie.

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);}}

Bardziej czytelny:

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);
    }
}

1

Rubin, 127 bajtów

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

Pobiera tablicę jako dane wejściowe.


1

CoffeeScript, 194 bajty

Pobiera dane wejściowe jako liczby binarne oddzielone przecinkami, dane wyjściowe w postaci binarnej.

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 ''

Spróbuj.


1

GolfScript, 46 bajtów

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

Wypróbuj online na Web GolfScript .

Przypadki testowe

$ 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

1

C ++, 192 bajty

Akceptuje wprowadzanie 32-bitowej tablicy liczb całkowitych bez znaku oraz liczbę elementów w tej tablicy.

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;}

Nie golfowany:

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;
}

1
@trichoplax to zmieniłem.
MegaTom,
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.