R, 1 byte
!
Example:
> !c(TRUE, FALSE)
[1] FALSE TRUE
It also works with numerical input:
> !c(1, 0)
[1] FALSE TRUE
We're not restricted to one-dimensional arrays, either. Let's make a matrix, and randomly populate it with 0s and 1s:
> mat = matrix(rbinom(16, 1, .5), ncol=4)
> mat
[,1] [,2] [,3] [,4]
[1,] 0 1 1 1
[2,] 0 1 0 0
[3,] 0 0 0 0
[4,] 1 1 1 0
We can invert this just as easily:
> !mat
[,1] [,2] [,3] [,4]
[1,] TRUE FALSE FALSE FALSE
[2,] TRUE FALSE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE
[4,] FALSE FALSE FALSE TRUE
We can continue to do this for arbitrary numbers of dimensions. Here's an example on a four-dimensional array:
> bigarray = array(rbinom(32, 1, 0.5), dim=c(2,2,2,2))
> bigarray
, , 1, 1
[,1] [,2]
[1,] 0 0
[2,] 0 0
, , 2, 1
[,1] [,2]
[1,] 1 0
[2,] 0 0
, , 1, 2
[,1] [,2]
[1,] 0 1
[2,] 0 1
, , 2, 2
[,1] [,2]
[1,] 1 0
[2,] 1 1
> !bigarray
, , 1, 1
[,1] [,2]
[1,] TRUE TRUE
[2,] TRUE TRUE
, , 2, 1
[,1] [,2]
[1,] FALSE TRUE
[2,] TRUE TRUE
, , 1, 2
[,1] [,2]
[1,] TRUE FALSE
[2,] TRUE FALSE
, , 2, 2
[,1] [,2]
[1,] FALSE TRUE
[2,] FALSE FALSE
Doesn't work for characters, I'm afraid.
> !"Hello world"
Error in !"Hello world" : Invalid argument type.
How about arrays of
0
(false, all 0 bits) and-1
(true, all 1 bits)? – Lynn – 2016-09-15T11:52:03.9135
@Lynn While it's the OPs decision, I'd say it should be up to whether your language considers though truthy/falsy.
– Martin Ender – 2016-09-15T11:53:15.473Related. (Given the simplicity of the core task, I'd say the differences in format are significant enough that these aren't duplicates.) – Martin Ender – 2016-09-15T12:28:05.810
6More than code golf this looks to me like: what is the not operator in your favourite language? Additional points if it works on lists. – licorna – 2016-09-15T23:32:25.110