Task
Given an array of positive integers, replace each element with the parity of the sum of the other elements. The array is guaranteed to have at least 2 elements.
Definition
- Parity: whether a number is odd or even.
Example
For the array [1,2,3,1]:
- Replace
1with the parity of2+3+1, i.e.even. - Replace
2with the parity of1+3+1, i.e.odd. - Replace
3with the parity of1+2+1, i.e.even. - Replace
1with the parity of1+2+3, i.e.even.
Output: [even, odd, even, even]
Input
An array of positive integer.
You may take it as a proper array, or as a linefeed-separated string of positive integers.
You may assume that the array and the values inside are within the handling capability of your language.
Output
An array of two consistent values, one representing odd, one representing even.
You may output it as a linefeed-separated string of the two values.
Testcases
Inputs:
[1, 2, 3, 1]
[1, 2, 3, 2, 1]
[2, 2]
[100, 1001]
Outputs:
[even, odd, even, even]
[even, odd, even, odd, even]
[even, even]
[odd, even]
Note: you may choose other consistent values other than odd and even.
Scoring
This is code-golf. Shortest answer in bytes wins.
Standard loophole applies.
-
\$\begingroup\$ Just a question - can you always recover the parity of the other elements? \$\endgroup\$user100887– user1008872021年05月24日 19:58:56 +00:00Commented May 24, 2021 at 19:58
41 Answers 41
Jelly, 3 bytes
+SḂ
How it works
+SḂ Main link. Argument: A (array)
S Compute the sum of A.
+ Add the sum to each element of A.
Using _ (subtraction) or ^ (bitwise XOR) would also work.
Ḃ Bit; compute the parity of each resulting integer.
-
\$\begingroup\$ That's a clever approach. \$\endgroup\$Leaky Nun– Leaky Nun2017年05月02日 18:42:51 +00:00Commented May 2, 2017 at 18:42
-
2\$\begingroup\$ @LeakyNun It's the same approach everyone else is using, only shorter :P \$\endgroup\$ETHproductions– ETHproductions2017年05月02日 18:46:27 +00:00Commented May 2, 2017 at 18:46
-
\$\begingroup\$ @ETHproductions Pretty much, yes. Thete are only so many ways to compute the parity... \$\endgroup\$Dennis– Dennis2017年05月02日 18:48:07 +00:00Commented May 2, 2017 at 18:48
-
\$\begingroup\$ @ETHproductions this uses addition instead of subtraction... \$\endgroup\$Leaky Nun– Leaky Nun2017年05月02日 18:48:18 +00:00Commented May 2, 2017 at 18:48
-
\$\begingroup\$ @LeakyNun True, my Japt answer does as well. In Jelly it'd just be
_SḂ\$\endgroup\$ETHproductions– ETHproductions2017年05月02日 18:49:59 +00:00Commented May 2, 2017 at 18:49
JavaScript (ES6), (削除) 38 36 (削除ここまで) 32 bytes
a=>a.map(b=>eval(a.join`+`)-b&1)
Uses 0 for even and 1 for odd.
Test
f=
a=>a.map(b=>eval(a.join`+`)-b&1)
console.log(f([1, 2, 3, 1]))
console.log(f([1, 2, 3, 2, 1]))
console.log(f([100, 1001]))
-
\$\begingroup\$ 2 bytes off:
c-b&1instead of(c-b)%2\$\endgroup\$Leaky Nun– Leaky Nun2017年05月02日 18:34:39 +00:00Commented May 2, 2017 at 18:34 -
\$\begingroup\$ Bah! You beat me to it! \$\endgroup\$Shaggy– Shaggy2017年05月02日 18:44:05 +00:00Commented May 2, 2017 at 18:44
-
3\$\begingroup\$ I'll have to remember to use
eval(a.join`+`)overa.reduce((x,y)=>x+y). That's clever \$\endgroup\$Cyoce– Cyoce2017年05月04日 02:03:17 +00:00Commented May 4, 2017 at 2:03
Haskell, 20 bytes
f x=odd.(sum x-)<$>x
Uses True for odd values and Falsefor even values.
Subtract each element from the sum of the list and test if it's odd.
f turned to pointfree has also 20 bytes: map=<<(odd.).(-).sum.
MATL, (削除) 5 (削除ここまで), 4 bytes
ts-o
One byte saved thanks to Dennis!
This gives '1' for odd and '0' for even. Explanation:
t % Duplicate the input
s % Get the sum of the input
- % Subtract it from the original input
o % Get the parity of each element
Alice, (削除) 31 (削除ここまで) 28 bytes
/O.HQ\d$K@
\i#\ /d2-&+!w?+2%
The input format doesn't matter as long as the integers are separated. The output format is linefeed-separated.
The layout is probably still not optimal but I haven't found a way to shorten this further yet.
Explanation
/ Reflect to SE. Switch to Ordinal.
i Read all input as a string.
Reflect off bottom boundary. Move to NE.
. Duplicate the input string.
Reflect off top boundary. Move to SE.
\ Reflect to N. Switch to Cardinal.
H Implicitly convert the top copy of the input to the integers it
contains and take the absolute value of the top-most one. (Taking
the absolute value doesn't do anything, but we need the implicit
conversion to integers.)
The IP wraps back to the second line.
\ Reflect to SE. Switch to Ordinal.
Immediately reflect off bottom boundary. Move to NE.
Q Reverse the stack (this converts the integers back to strings but
that's irrelevant). After this, we end up with all the individual
integers on the bottom of the stack in reverse order and the other
copy of the input string with all integers on top.
Reflect off top boundary. Move to SE.
/ Reflect to E. Switch to Cardinal.
d Push the stack depth, which is one more than the number of list
elements (due to the other input string on the stack).
2- Subtract 2.
&+ Run + that many times, which implicitly converts the second string
to the integers it contains and then adds up all the list elements.
! Store the sum on the tape.
w Push the current IP position to the return address stack. This
lets us return here repeatedly to implement a loop.
?+ Retrieve the input sum from the tape and add it to the current
element.
2% Compute its parity. Other ways to do this are 1A and 0x. 2F would
also work but it gives 0/2 instead of 0/1.
The IP wraps the first column of the grid.
\ Reflect to NE. Switch to Ordinal. The IP bounces diaginally up
and down until it hits the next \.
O Implicitly convert the current parity to a string and print it
with a trailing linefeed.
# Skip the next command (the H).
\ Reflect to E. Switch to Cardinal.
d Push the stack depth. This is zero when we're done.
$ Skip the next command if the stack depth is indeed zero, which
exits the loop.
K Jump to the return address on top of the return address stack without
popping it (so that the next K will jump there again).
@ Terminate the program.
Pyth, (削除) 7 (削除ここまで) 6 bytes
mi2-sQ
-1 Byte thanks to @KZhang
Outputs 1 for odd, 2 for even.
Explanation
m%-sQd2
m Q # For each element in the (implicit) input list
sQ # Take the sum of all the elements
- d # subtract that element, so that we now have the sum of the other elements
% 2 # modulo 2; 1=off, 0=even
05AB1E (legacy), (削除) 4 (削除ここまで) 3 bytes
O^È
O # Sum
^ # XOR with (implicit) input
È # Print 1 for even / 0 for odd
-
\$\begingroup\$ 1 byte off \$\endgroup\$Leaky Nun– Leaky Nun2017年05月02日 18:39:27 +00:00Commented May 2, 2017 at 18:39
-
\$\begingroup\$ I know it's been a while, but you can remove the initial
D, since input is implicitly. \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2019年05月31日 13:18:17 +00:00Commented May 31, 2019 at 13:18
R, 21 bytes
(sum(n<-scan())-n)%%2
reads the list from stdin and returns 0 for even, 1 for odd. binds the input to the variable n inside the call to sum instead of calling it outside, i.e., n=scan();(sum(n)-n)%%2
Mathematica, 13 bytes
#+Tr@#&/*OddQ
or
OddQ[#+Tr@#]&
Clojure, 30 bytes
#(for[i %](odd?(apply - i %)))
Substracts all values from each value in turn, for example with input [a b c d] the 2nd calculated value is b - a - b - c - d = -(a + c + d). Output is false for even and true for odd.
But you might as well use + and calculate each subsequent term twice so it doesn't affect the parity.
CJam, 10 bytes
{_:+f+1f&}
This is an anonymous block (function) that takes the input from the stack and replaces it by the output.
Explanation
Consider input [1 2 3 1].
{ e# Begin block
e# STACK: [1 2 3 1]
_ e# Duplicate
e# STACK: [1 2 3 1], [1 2 3 1]
:+ e# Fold addition over the array: compute its sum
e# STACK: [1 2 3 1], 7
f+ e# Map addition over the array with extra parameter
e# STACK: [8 10 11 8]
1 e# Push 1
e# STACK: [8 10 11 8], 1
f& e# Map bit-wise "and" over the array with extra parameter
e# STACK: [0 0 1 0]
} e# End block
Retina, (削除) 40 (削除ここまで) 38 bytes
\d+
¶$` $'
^¶
\d+
$*
+` |11
%M`1
¶
Try it online! Outputs 1 for odd and 0 for even. Explanation: The first two lines duplicate the input once for each number in the input, but without the element itself. This creates an extra blank line which is then deleted. The input is then converted from decimal to unary, the spaces are deleted and the parity computed. Even parity is then converted to zero and the results joined back in to one line. Edit: Saved 2 bytes thanks to @FryAmTheEggman. I tried some other versions which are conceptually more pleasing but which take far too many bytes to express:
\d\B
T`2468O`00001
T`d`10`^([^1]*1[^1]*1)*[^1]*1[^1]*$
Changes all inputs to their parity, then flips all their parities if the total has odd parity.
\d+
$*
^.*
$&¶$&
(?=.*$)
11
\B
0
T`d`10`.*¶1
¶0
Sums a duplicate of the input, then takes the parity of everything, then inverts the parities if the sum is odd, then deletes the sum again.
-
\$\begingroup\$ I tried what came to mind for me, and got a slightly shorter solution, though I still think it's hardly optimal. Particularly I don't like how I handle the extra zero I get at the end. \$\endgroup\$FryAmTheEggman– FryAmTheEggman2017年05月02日 23:59:52 +00:00Commented May 2, 2017 at 23:59
-
\$\begingroup\$ @FryAmTheEggman Your saving comes from having a less visible way of converting your
;s back to spaces. If you put the;at the beginning then you can save a byte by deleting it immediately instead of after it converts to a 0. \$\endgroup\$Neil– Neil2017年05月03日 00:19:30 +00:00Commented May 3, 2017 at 0:19 -
\$\begingroup\$ Actually, looking again, why isn't your last stage just replacing newlines with spaces? Wouldn't that save 2 bytes? \$\endgroup\$FryAmTheEggman– FryAmTheEggman2017年05月03日 02:02:45 +00:00Commented May 3, 2017 at 2:02
-
\$\begingroup\$ @FryAmTheEggman Yes; I think I originally had more than one replacement to make in a previous iteration. \$\endgroup\$Neil– Neil2017年05月03日 08:02:01 +00:00Commented May 3, 2017 at 8:02
Japt, 7 bytes
£x +X&1
Explanation
£ x +X&1
mX{ x +X&1} // Ungolfed
UmX{Ux +X&1} // Variable introduction
UmX{ } // Replace each item in the input array with
&1 // the parity of
Ux // the sum of the input array
+X // plus X.
// Implicit: output result of last expression
Perl 5, 31 bytes
sub{map$x+=$_,@_;map$x-$_&1,@_}
Outputs 1 for odd and 0 for even.
-
\$\begingroup\$ +1, nice. I think this is 28 bytes, though:
perldoc perlsubsays, "The signature is part of a subroutine's body. Normally the body of a subroutine is simply a braced block of code.". \$\endgroup\$msh210– msh2102017年05月02日 22:42:25 +00:00Commented May 2, 2017 at 22:42 -
\$\begingroup\$ @msh210 Thanks! I don't think that's how it works, though- sure the body of the subroutine is only 28 bytes, but you can't leave out
subwithout breaking it. \$\endgroup\$Chris– Chris2017年05月03日 23:35:19 +00:00Commented May 3, 2017 at 23:35 -
\$\begingroup\$ But sometimes a subroutine works without
sub, e.g. aftersortorgrepor as an argument to another subroutine. This may be worth asking about on Code Golf Meta. \$\endgroup\$msh210– msh2102017年05月04日 04:22:56 +00:00Commented May 4, 2017 at 4:22 -
\$\begingroup\$ @msh210 A subroutine works without
subonly if it is used in a prototyped function (sortandgrepare more or less prototyped). But otherwise, thesubis required. Regardless, golfing 3 bytes by omittingsubisn't really interesting. \$\endgroup\$Dada– Dada2017年05月04日 12:16:20 +00:00Commented May 4, 2017 at 12:16
Clojure(Script), 36 bytes
Output is true for odd and false for even. Both output and input are sequences.
(fn[l](map #(odd?(-(apply + l)%))l))
PHP, 50 Bytes
1 for odd , 0 for even
Output as string separated with _
<?foreach($_GET as$v)echo array_sum($_GET)-$v&1,_;
PHP, 72 Bytes
Output as array use array_map
<?print_r(array_map(function($v){return array_sum($_GET)-$v&1;},$_GET));
-
1\$\begingroup\$ You can drop the
?:0it doesn't do anything.foreach($_GET as$v)echo array_sum($_GET)-$v&1,_;\$\endgroup\$Christoph– Christoph2017年05月03日 06:27:43 +00:00Commented May 3, 2017 at 6:27
C, (削除) 68 (削除ここまで) 62 bytes
i;s;f(c,l)int*l;{while(i<c)s+=l[i++];while(i)l[--i]=s-l[i]&1;}
1 for odd, 0 for even
Detailed Try Online
f(int c, int * l)
{
int i = 0, s = 0;
while(i < c)
{
s = s + l[i];
i = i + 1;
}
// assert(i == c)
while(i > 0)
{
i = i - 1;
l[i] = s - l[i]&1;
}
}
Ohm, 4 bytes
DΣ-é
Basically a direct port of the MATL and 05AB1E answers. Uses true for even and false for odd.
Fig, \4ドル\log_{256}(96)\approx\$ 3.292 bytes
%2-S
1 for odd, 0 for even.
%2-S
S # sum
- # minus each item of input array
%2 # mod each by 2
-
\$\begingroup\$
%2can be replaced withO\$\endgroup\$Seggan– Seggan2023年02月28日 20:30:59 +00:00Commented Feb 28, 2023 at 20:30 -
\$\begingroup\$ @Seggan
-Syields a list,Owould join that list by nothing, unless it has been updated. \$\endgroup\$south– south2023年02月28日 20:34:30 +00:00Commented Feb 28, 2023 at 20:34 -
1\$\begingroup\$ oops, true. never mind \$\endgroup\$Seggan– Seggan2023年02月28日 20:35:30 +00:00Commented Feb 28, 2023 at 20:35
k, 9 bytes
{2!x-+/x}
The output is a 1 for odd, and a 0 for even. Try it online.
Converted to pseudocode, it would be:
for number in x:
yield (number - sum(x)) % 2
Brain-Flak, (削除) 94 (削除ここまで) (削除) 68 (削除ここまで) 66 bytes
({({}<>)<>})<>{<>(({})<({}<>{}<>(())){({}[()]<([{}])>)}{}>)<>}<>{}
This seems a little long for the task. There might be a more convenient way to do this.
Explanation
First we calculate the sum of the stack with:
({({}<>)<>})
The we go through the entire stack adding that result to each element and determine the pairity
<>{<>(({})<({}<>{}<>(())){({}[()]<([{}])>)}{}>)<>}<>{}
This uses a pretty cool mod 2 algorithm I came up with for this challenge.
({}(())){({}[()]<([{}]())>)}{}
This pushes 1 under the input decrements until the input reaches zero each time performing 1-n to the 1 we placed earlier, it then removes the input.
-
\$\begingroup\$ You can mod 2 at the last. You don't need to mod 2 the sum. \$\endgroup\$Leaky Nun– Leaky Nun2017年05月03日 03:57:36 +00:00Commented May 3, 2017 at 3:57
-
\$\begingroup\$ @LeakyNun Thanks! I just realized that and made the fix. \$\endgroup\$2017年05月03日 03:59:43 +00:00Commented May 3, 2017 at 3:59
Wise, (削除) 54 (削除ここまで) 52 bytes
::^:??[:!^:?^:!^:?^?]|!::^??[!:?^:><^!:?^:!^:?^?]!&|
Explanation
This code would be a lot shorter if it didn't take so many bytes to swap the top two elements. The current record is
:?^:!^:?^!
This unfortunately constitutes the majority of the code.
First we take the XOR sum of the stack
::^:??[:!^:?^:!^:?^?]|!
We then XOR this with every element and the element with it last bit zeroed
::^??[!:?^:><^!:?^:!^:?^?]!&|
Java, (削除) 81 (削除ここまで) 78 bytes
3 bytes thanks to Kevin Cruissen
void f(int[]a){int s=0,i=a.length;for(int x:a)s+=x;for(;i-->0;a[i]=s-a[i]&1);}
Modifies the array in-place.
-
\$\begingroup\$ You can golf it by 3 bytes like this:
void f(int[]a){int s=0,i=a.length;for(int x:a)s+=x;for(;i-->0;a[i]=s-a[i]&1);}\$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2017年05月03日 08:38:50 +00:00Commented May 3, 2017 at 8:38 -
\$\begingroup\$ 67 bytes if you use a lambda: Try it online! \$\endgroup\$Brian McCutchon– Brian McCutchon2017年05月03日 15:58:53 +00:00Commented May 3, 2017 at 15:58
-
\$\begingroup\$ Thanks, but I don't like to use a lambda. \$\endgroup\$Leaky Nun– Leaky Nun2017年05月03日 15:59:55 +00:00Commented May 3, 2017 at 15:59
AWK, 64 bytes
{for(i=0;++i<=NF;print s[i]%2)for(j=0;++j<=NF;)if(i!=j)s[i]+=$j}
Outputs a 0 for even sums and 1 for odd sums separated by newlines. The only even slightly out-of-the-box thinking was placing the print command inside the for "increment" step. I tried a few "clever" ways to print, but they didn't save bytes.
Just for giggles, if you don't want newlines:
{for(i=0;++i<=NF;m=m,s[i]%2)for(j=0;++j<=NF;)if(i!=j)s[i]+=$j}1
which has the same byte-count as above, but is a bit more obtuse.
Swift - 55 bytes
Finally beats C! Also, 0 for even, 1 for odd
func g(a:[Int]){for i in a{print((a.reduce(0,+)-i)%2)}}
A function, with usage: g(a: [1,2,3,2,1] // => 0 1 0 1 0
-
\$\begingroup\$ Not familiar with Swift, but in many languages you can replace
(x-y)%2withx-y&1\$\endgroup\$Cyoce– Cyoce2017年05月04日 01:57:04 +00:00Commented May 4, 2017 at 1:57 -
\$\begingroup\$ @Cyoce For me, after testing, it doesn't work. Bitwise operations aren't Swift's forte \$\endgroup\$Mr. Xcoder– Mr. Xcoder2017年05月04日 04:43:21 +00:00Commented May 4, 2017 at 4:43