私のオッズから私のオッズを引きます


19

負でない整数を指定すると、偶数桁の合計と奇数桁の合計の絶対差を返します。

デフォルトのルール

  • 標準の抜け穴が適用されます。

  • 任意の標準入出力方法で入力を取得し、出力を提供できます。

  • 入力は、文字列、整数、または数字のリストとして取得できます。

  • これはなので、すべての言語でバイト単位の最短コードが勝ちます!

テストケース

入力〜>出力

0〜> 0(| 0-0 | = 0)
1〜> 1(| 1-0 | = 1)
12〜> 1(| 2-1 | = 1)
333〜> 9(| 0-(3 + 3 + 3)| = 9)
459〜> 10(| 4-(5 + 9)| = 10)
2469〜> 3(|(2 + 4 + 6)-9 | = 3)
1234〜> 2(|(2 + 4)-(1 + 3)| = 2)

1
intのリストとして入力を取得できますか?
アダム

4
@ Mr.Xcoderそれはささいなことではないでしょう。チャレンジを不必要に複雑にし、バイトを追加する任意の要件です。
Okx

4
@ Mr.Xcoder カメレオンに挑戦しないでください。あなたがここで見たいと思うかもしれません最も重要な文がされて一つに二つ以上の無関係なコアの課題を組み合わせる-個別の課題に分割挑戦したり落下不要な部分を検討
Okx

1
* chamelの電子挑戦に
CalculatorFeline

1
@Okxのルールを変更しました。数字のリストとして取ることは現在許されています。私はまだそれがふわふわするようになるとは思わない。
ミスターXcoder

回答:


8

ゼリー、6バイト

-*æ.¹A

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

使い方

-*æ.¹A  Main link. Argument: A (digit array)

-*      Raise -1 to A's digits, yielding 1 for even digits and -1 for odd ones.
    ¹   Identity; yield A.
  æ.    Take the dot product of the units and the digits.
     A  Apply absolute value.

入力をリストとして取得することにより、1バイトを保存できます。
電卓

私は午前リストとして入力を取ります。
デニス

私はリビジョン2について話している
電卓

Raise -1 to A's digits, yielding 1 for even digits and 0 for odd ones.うーん、私はあなたが何か少しか何か...混乱だと思う
エリックOutgolfer

2
@EriktheOutgolfer Darn off-by-oneエラー。
デニス

8

SHENZHEN I / O MCxxxxスクリプト、197(126 + 71)バイト

チップ1(MC6000):

  • x0:リストとして入力
  • x2:チップ2 x1
  • x3:MC4010
mov 0 dat
j:
mov x0 acc
mov 70 x3
mov -1 x3
mov acc x3
mul x3
mov acc x2
mov dat acc
add 1
tlt acc 3
mov acc dat
+jmp j
slx x0

チップ2(MC4000):

  • p0:出力
  • x0:MC4010
  • x1:チップ1 x2
mov x1 acc
add x1
add x1
mov 30 x0
mov 0 x0
mov acc x0
mov x0 p0
slx x1

1
<!-- -->コメントを入力して、リストの直後にコードを入力することができます。フィラーテキストの代わりに。または、さらに4つのスペースでコードをインデントします。)
Mat


5

TI-Basic、18 9バイト

abs(sum((-1)^AnsAns

説明

リストの各桁に-1を乗じ、奇数桁ごとに否定してから合計します。



4

R、30 29バイト

abs(sum((d=scan())-2*d*d%%2))

d = scan() 入力番号を次々に入力します。

@Giuseppeのおかげで-1バイト!


これは非常に優れています!ただし、1バイトの節約を行う必要がありますabs(sum((d=scan())-2*d*d%%2))
ジュゼッペ

@ジュゼッペありがとう、良いヒント、編集!
-Nutle

4

C#、57バイト

namespace System.Linq{i=>Math.Abs(i.Sum(n=>n%2<1?n:-n))}

入力をasとして取りi、オッズを負に変えて整数を合計します。


ここで最初の答え。このすべてを実際のC#プログラムにラップし、それらのバイトもカウントする必要があるかどうかはわかりません。
-TyCobb

定型文を含めてnamespace System.Linq{、実際の機能を作成する必要があります。参照のために他のC#の答えを参照してください
氏Xcoder

@ Mr.Xcoder情報をありがとう。私が得たと思う。バイト数をほぼ倍にした=(lol
TyCobb

うん、C#は本当に最高のゴルフ言語ではありません
氏Xcoder

@ Mr.Xcoderいいえ、最初のページに名前空間のないスリムなバージョンがあり、が表示されなかったため、ルールが緩和されたと思いましたMain。私がそれに答えると思った唯一の理由。まあ
TyCobb

4

Mathematica、20バイト

Abs@Tr[(-1)^(g=#)g]&

入力として数字のリストを受け取ります

「新しいルール」について教えてくれた@LLlAMnYPへの特別な感謝


それに私を打つ!:)おそらく必要ありません*
グレッグマーティン

OPがコードの要件を大幅に短縮できるようになりました。+1
LLlAMnYP

3

Japt、8バイト

x_*JpZÃa

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

説明

 x_  *JpZÃ a
UxZ{Z*JpZ} a
                Implicit: U = list of digits
UxZ{     }      Take the sum of each item Z in U mapped through the following function:
      JpZ         Return (-1) ** Z
    Z*            times Z. This gives Z if even, -Z if odd.
           a    Take the absolute value of the result.
                Implicit: output result of last expression

3

ニーム、7バイト

ΓDᛃΞ𝐍}𝐬

説明:

Γ        Apply the following to each element in the input array
 D         Duplicate
  ᛃ        Modulo 2, then perform logical NOT
   Ξ       If truthy, then:
    𝐍        Multiply by -1
      }  Close all currently running loops/conditionals etc
       𝐬 Sum the resulting array

2でmodを行い、結果として論理的にNOTとするビルトインを持っているのは誰ですか
22

@cairdcoinheringaahing基本的には「偶数かどうかを確認する」ことです
-Okx

3

APL、8バイト

|⊢+.ׯ1*⊢

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

どうやって?

¯1*⊢- -1 Nのためn

[ 4 5 91 ¯1 ¯1]

⊢+.×-での有理乗算o、次に合計

[ +/ 4 5 9 × 1 ¯1 ¯1+/ 4 ¯5 ¯9¯10]

| - 絶対値


テスト環境を提供していただけますか?
ミスターXcoder

@ Mr.Xcoderが追加されました
Uriel

|⊢+.ׯ1*⊢新しい入力仕様で。
アダム

@Adámありがとう。製品を見逃したなんて信じられない。
ウリエル

説明で詳細を提供できますか?このメソッドをJに移植できますか?私は現在キーを使用しています(私の回答を参照)が、この方法は数バイトを削る可能性があります
ジョナ

3

JavaScript(ES6)、43 38バイト

入力を文字列として数字の配列として受け取ります。

a=>a.map(d=>s+=d&1?d:-d,s=0)&&s>0?s:-s

テストケース


3

編集:よりゴルフ中心のアプローチ:

EXCEL、42 36 29バイト

Magic Octopus Urnのおかげで6バイトを節約できました

=ABS(SUMPRODUCT(A:A,-1^A:A))

入力用にA列の整数のリストを取得します。おそらくさらにゴルフをするか、文字列バージョンを使用して、A1の文字列を入力に使用できます。

EXCEL、256バイト

=ABS(LEN(SUBSTITUTE(A1,1,""))-2*LEN(SUBSTITUTE(A1,2,""))+3*LEN(SUBSTITUTE(A1,3,""))-4*LEN(SUBSTITUTE(A1,4,""))+5*LEN(SUBSTITUTE(A1,5,""))-6*LEN(SUBSTITUTE(A1,6,""))+7*LEN(SUBSTITUTE(A1,7,""))-8*LEN(SUBSTITUTE(A1,8,""))+9*LEN(SUBSTITUTE(A1,9,""))-5*LEN(A1))

enter image description here


1
免責事項、長さが100未満の数字でのみ機能します
魔法のタコUr

1
A:Aに切り替えると、6バイトが節約され、その問題が解消されます。
マーク

うわー、私の建設的な批判がバイトを節約することはめったにありません。
魔法のタコUr

また、You may take input as a String, as an Integer or as a list of digits.あなたの42バイトの答えのためにあなたが使用する答えでなければなりません。
魔法のタコUr

最初はユーモラスな試みでしたが、私はそれらを切り替えます。
マーク


2

、7バイト

≠0ṁṠ!¡_

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

入力として数字のリストを受け取ります。

まだ「abs」ビルトインがありませんが、良い結果はすべて同じです:)

説明

Ṡ!¡_は、数値nを取得しn-1、その関数_(否定)にを適用する回数nです。これにより、n奇数nまたは偶数-nになりますnます。

リストの各要素に関数を適用し、結果を合計します。

≠0 数値と0の絶対差を返します。


2

05AB1E、6バイト

-1のパワートリックをくれたデニスに感謝します。入力を数字のリストとして受け取ります

®sm*OÄ

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

説明

®sm*OÄ                                               Example [4, 5, 9]
®      # Push -1                                   % STACK: -1
 sm    # Take -1 to the power of every number      % STACK: [1, -1, -1]
         in the input list 
   *   # Multiply with original input              % Multiply [1, -1, -1] with [4, 5, 9] results in STACK: [4, -5, -9]
    O  # Sum them all together                     % STACK: -10
     Ä # Absolute value                            % STACK: 10
       # Implicit print

I can´t follow the explanation. Would you add an example please.
Titus

@Titus there you go. Hope it helps :)
Datboi

And here I was with È2*<*O like a filthy casual.
Magic Octopus Urn

2

PHP, 51 bytes

while(~$n=$argn[$i++])$s+=$n&1?$n:-$n;echo abs($s);

adds digit to $s if odd, subtracts if even. Run as pipe with -nR.

or

while(~$n=$argn[$i++])$s+=(-1)**$n*$n;echo abs($s);

using Dennis´ -1 power trick.


2

Mathematica, 67 bytes

(s=#;Abs[Subtract@@(Tr@Select[IntegerDigits@s,#]&/@{EvenQ,OddQ})])&

2

PHP, 54 bytes

for(;~$n=$argn[$i++];)${eo[$n&1]}+=$n;echo abs($e-$o);

Try it online!

PHP, 57 bytes

store the even and odd sums in an array

for(;~$n=$argn[$i++];)$r[$n&1]+=$n;echo abs($r[0]-$r[1]);

Try it online!

PHP, 57 bytes

store the even and odd sums in two variables

for(;~$n=$argn[$i++];)$n&1?$o+=$n:$e+=$n;echo abs($e-$o);

Try it online!


54 bytes: odd sum in ${1} and even sum in ${0}: while(~$n=$argn[$i++])${$n&1}+=$n;echo abs(${1}-${0});
Titus

@Titus nice I think ` for(;~$n=$argn[$i++];)${eo[$n&1]}+=$n;echo abs($e-$o);` is also a nice variant. Or we can do it more nathematical for(;~$n=$argn[$i++];$s+=$n)$u+=($n&1)*$n;echo abs($s-2*$u); and for(;~$n=$argn[$i++];)$u+=(($n&1)-.5)*2*$n;echo abs($u); is an interesting way
Jörg Hülsermann

2

Haskell, 47 42 39 38 26 25 bytes

-1 thanks to nimi

-12 thanks to Bruce

-1 thanks to xnor

abs.sum.map(\x->x*(-1)^x)

Try it online!


1
You can inline s: ((*)=<<((-1)^)).
nimi

1
It's one byte shorter to just write (\x->x*(-1)^x).
xnor

1

Perl 6, 28 bytes

{abs sum $_ Z*.map(*%2*2-1)}

Try it online!

Takes a list of digits as input.

  • $_ is the input argument.
  • .map(* % 2 * 2 - 1) maps each digit to either 1 or -1 depending on whether the digit is odd or even, respectively.
  • Z* zips the original list of digits with the even/odd list using multiplication.

1

Braingolf, 18 bytes

{.2%?M|}&+v&+c-!s*

Try it online!

Takes input as a list of digits

Explanation

{.2%?M|}&+v&+c-!s*  Implicit input from commandline args
{......}            Foreach loop, runs on each item in the stack..
 .2%                ..Parity check, push 1 if odd, 0 if even
    ?               ..If last item != 0 (pops last item)..
     M              ....Move last item to next stack
      |             ..Endif
        &+          Sum entire stack
          v&+       Switch to next stack and sum entire stack
             c-     Collapse into stack1 and subtract
               !s   Sign check, push 1 if last item is positive, -1 if last item is
                    negative, 0 if last item is 0
                 *  Multiply last item by sign, gets absolute value
                    Implicit output

1

R, 72 43 bytes

b=(d=scan())%%2<1;abs(sum(d[b])-sum(d[!b]))

First, d = scan() takes the number as input, one digit after the other (thanks to @Giuseppe comment !)
Then, b = d %% 2 <1 associates to b a TRUE or FALSE value at each index depending on the digits' parity. Therefore, b values are TRUE for even numbers, and !b are TRUE for odd values.

Finaly, abs(sum(d[b]) - sum(d[!b])) does the job.


<1 is one byte shorter than ==0, but note that you may take input as a list of digits as well.
Giuseppe

@Giuseppe Well spotted ! Thanks !
Frédéric

1

Bash 141 139 99 Bytes

while read -n1 a; do
[ $[a%2] = 0 ]&&e=$[e+a]||o=$[o+a]
done
(($[e-o]>0))&&echo $[e-o]||echo $[o-e]

Try it online!




1

05AB1E, 7 bytes

È2*<*OÄ

Try it online!

        # Input              | 1234567
È       # Is Even?           | [0,1,0,1,0,1,0]
 2*<    # (a * 2) - 1        | [-1,1,-1,1,-1,1,-1]
    *   # Multiply w/ input. | [-1,2,-3,4,-5,6,-7]
     O  # Sum.               | -10
      Ä # Absolute value of. | 10

1

x86-64 Machine Code, 30 bytes

31 C0 99 8B 4C B7 FC F6 C1 01 74 04 01 CA EB 02 01 C8 FF CE 75 ED 29 D0 99 31 D0 29 D0 C3

The above code defines a function that accepts a list/array of integer digits and returns the absolute difference between the sum of its even digits and the sum of its odd digits.

As in C, assembly language doesn't implement lists or arrays as first-class types, but rather represents them as a combination of a pointer and a length. Therefore, I have arranged for this function to accept two parameters: the first is a pointer to the beginning of the list of digits, and the second is an integer specifying the total length of the list (total number of digits, one-indexed).

The function conforms to the System V AMD64 calling convention, which is standard on Gnu/UNIX systems. In particular, the first parameter (pointer to the beginning of the list) is passed in RDI (as this is 64-bit code, it is a 64-bit pointer), and the second parameter (length of the list) is passed in ESI (this is only a 32-bit value, because that's more than enough digits to play with, and naturally it is assumed to be non-zero). The result is returned in the EAX register.

If it's any clearer, this would be the C prototype (and you can use this to call the function from C):

int OddsAndEvens(int *ptrDigits, int length);

Ungolfed assembly mnemonics:

; parameter 1 (RDI) == pointer to list of integer digits
; parameter 2 (ESI) == number of integer digits in list (assumes non-zero, of course)
OddsAndEvens:
   xor  eax, eax              ; EAX = 0 (accumulator for evens)
   cdq                        ; EDX = 0 (accumulator for odds)
.IterateDigits:
   mov  ecx, [rdi+rsi*4-4]    ; load next digit from list
   test cl, 1                 ; test last bit to see if even or odd
   jz   .IsEven               ; jump if last bit == 0 (even)
.IsOdd:                       ; fall through if last bit != 0 (odd)
   add  edx, ecx              ; add value to odds accumulator
   jmp  .Continue             ; keep looping
.IsEven:
   add  eax, ecx              ; add value to evens accumulator
.Continue:                    ; fall through
   dec  esi                   ; decrement count of digits in list
   jnz  .IterateDigits        ; keep looping as long as there are digits left

   sub  eax, edx              ; subtract odds accumulator from evens accumulator

   ; abs
   cdq                        ; sign-extend EAX into EDX
   xor  eax, edx              ; XOR sign bit in with the number
   sub  eax, edx              ; subtract sign bit

   ret                        ; return with final result in EAX

Here's a brief walk-through of the code:

  • First, we zero out the EAX and EDX registers, which will be used to hold the sum totals of even and odd digits. The EAX register is cleared by XORing it with itself (2 bytes), and then the EDX register is cleared by sign-extending the EAX into it (CDQ, 1 byte).
  • Then, we go into the loop that iterates through all of the digits passed in the array. It retrieves a digit, tests to see if it is even or odd (by testing the least-significant bit, which will be 0 if the value is even or 1 if it is odd), and then jumps or falls through accordingly, adding that value to the appropriate accumulator. At the bottom of the loop, we decrement the digit counter (ESI) and continue looping as long as it is non-zero (i.e., as long as there are more digits left in the list to be retrieved).

    The only thing tricky here is the initial MOV instruction, which uses the most complex addressing mode possible on x86.* It takes RDI as the base register (the pointer to the beginning of the list), scales RSI (the length counter, which serves as the index) by 4 (the size of an integer, in bytes) and adds that to the base, and then subtracts 4 from the total (because the length counter is one-based and we need the offset to be zero-based). This gives the address of the digit in the array, which is then loaded into the ECX register.

  • After the loop has finished, we do the subtraction of the odds from the evens (EAX -= EDX).

  • Finally, we compute the absolute value using a common trick—the same one used by most C compilers for the abs function. I won't go into details about how this trick works here; see code comments for hints, or do a web search.

__
* The code can be re-written to use simpler addressing modes, but it doesn't make it any shorter. I was able to come up with an alternative implementation that dereferenced RDI and incremented it by 8 each time through the loop, but because you still have to decrement the counter in ESI, this turned out to be the same 30 bytes. What had initially given me hope is that add eax, DWORD PTR [rdi] is only 2 bytes, the same as adding two enregistered values. Here is that implementation, if only to save anyone attempting to outgolf me some effort :-)

                    OddsAndEvens_Alt:
31 C0                   xor    eax, eax
99                      cdq
                    .IterateDigits:
F6 07 01                test   BYTE PTR [rdi], 1
74 04                   je     .IsEven
                    .IsOdd:
03 17                   add    edx, DWORD PTR [rdi]
EB 02                   jmp    .Continue
                    .IsEven:
03 07                   add    eax, DWORD PTR [rdi]
                    .Continue:
48 83 C7 08             add    rdi, 8
FF CE                   dec    esi
75 ED                   jne    .IterateDigits
29 D0                   sub    eax, edx
99                      cdq
31 D0                   xor    eax, edx
29 D0                   sub    eax, edx
C3                      ret


1

TI-BASIC, 11 6 bytes

abs(sum(Anscos(πAns

Takes input as a list. i²^Ans saves two bytes over (-1)^Ans because we don't need the parentheses.

abs(sum(Anscos(πAns
           cos(πAns                  1 for evens, -1 for odds
        Ans                          Multiply by original list
abs(sum(                             Sum the list and take absolute value, which also
                                     fixes rounding errors from cos(.

1

J, 14 bytes

|-/(2&|+//.[),

Try it online!

explanation

|                absolute value of
 -/              the difference between
                 the items on the list returned by this fork
   (2&|          is an item odd? (1 for yes, 0 for no)
       +//.      the "key" verb /. which partitions on above (even / odd) then sums
           [)    identity, ie, the list of digits passed
             ,   turn it into a list (to handle 1 element case)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.