text:
Generate a Universal-binary-function Lookup Table
This is tangentially related to my quest to invent an esoteric programming language.
A table of the binary numbers 0 .. 15 can be used to implement a Universal Binary Function using indexing operations. Given two 1-bit inputs X and Y, all 16 possible functions can be encoded in a 4-bit opcode.
X Y  F|0 1 2 3 4 5 6 7 8 9 A B C D E F
- -    - - - - - - - - - - - - - - - -
0 0    0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1    0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 0    0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
1 1    0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
       -     -   - -   -   -   -   - -
       0    ~X  ~Y ^   &   Y   X   | 1
      ZERO    NOT-Y   AND         OR
          NOT-X   XOR              ONE

So this set of 16 functions can be applied to binary inputs as the function

U(f,x,y): (f >> ((x<<1) | y)) & 1,

or

U(f,x,y): (f / 2^(x×2 + y)) % 2,

or with indexing or matrix partitioning.
It will be useful to know the most compact way to represent or generate such a table of values for any possible languages to be built upon this type of binary operation.
The goal:
Generate this exact text output:
0101010101010101
0011001100110011
0000111100001111
0000000011111111

That's it! Shortest-code wins.

I had an intuition that the APL-family would do well here. :)

Also related: A simple logic gate calculator

Are leading or trailing newlines accepted?

Yes, extra newlines are fine.

J, 10 (13?) characters
|.|:#:i.16

Number list:
   i.16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`

to binary:
   #:i.16
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1

Transpose:
   |:#:i.16
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

Reverse:
   |.|:#:i.16
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

Do we need to remove the spaces? Looking at the other J answer it seems we do so we'll need to add 3 characters and borrow the 1": from Jan's answer.

Very nice style of explanation. +1 (damn short, too!)

As soon as I saw Peter's Golfscript answer I knew I could have done much better. Well, you had already done it.

Nice to see something shorter than Golfscript...

Reimplemented your solution in postscript

@luserdroog Wow. That's a lot of code. Much more readable than the J source code though. :-) Very cool.

It can probably be factored and improved considerably. It looks like I wrote the reverse function twice, as |. and @!

Python 2, 40
for n in 1,2,4,8:print 8/n*('0'*n+'1'*n)

APL (14)
Assuming ⎕IO=0 (that's a setting):
⎕D[⊖(4⍴2)⊤⍳16]

Explanation:

⍳16: numbers [0,16)
(4⍴2)⊤: encode each number in base 2 using 4 digits
⊖: horizontal reverse (so the MSB ends up on top)
⎕D[...]: select these values from ⎕D which is the string 0123456789. (A numeric matrix is displayed with spaces between the values, a character matrix is not. So this converts each numerical bit to one of the chars '0' '1').

Is the first character in the source supposed to look like a square, or am I still missing some fonts?

@TimSeguine Yes, it's a square, called quad in the APL literature. Variable names beginning with quad are system variables which change the environment. IO = "index origin".

Save a byte: (4⍴2)⊤ → 2⊥⍣¯1

Jelly, 42 7 bytes
⁴ḶBUz0Y

Try it online!
Thanks to Dennis for his help. Here is the first message, here is the last (other discussions also occured). With his help, I apparently (almost) square-rooted the score.

Since the language is newer than question,  I can't accept it as answer. Definitely in the running for the bounty, tho!

@luserdroog That's fine. But, I thought the challenge was newer.

I know what you mean, it doesn't feel like that long ago that I posted it. But even my own inca2, at 2 years old, is too young a language.

+1 for the 42 to 7 codegolf. That's something you don't see every day (unless done on purpose).

@KevinCruijssen Why should it be ever done on purpose? I'm just a Jelly newbie (I know Python 2 and 3 well), so I did it on a string way, while I "need to treat Jelly as an array-manipulating language".

///, 51 bytes
Try it online
/a/0101/aaaa
/b/0011/bbbb
/z/0000//o/1111/zozo
zzoo

Welcome to PPCG! You beat me to it.

@EriktheGolfer Feel free to improve, but I think that's the shortest possible version. :)

I'm porting this to Sprects.

GolfScript (18 17 15 chars)
(With thanks to Howard)
16,zip{','-~n}%

I don't understand why the 10-char
16,zip{n}/

doesn't work; I suspect that a bug in the standard interpreter is resulting in unsupported types on the stack.
An alternative at 18 characters which I understand fully is:
4,{2\?.2,*$8@/*n}%

A more mathematical approach is a bit longer, at 28 chars:
4,{2.@??)2.4??.@/+2base(;n}/

A lot of that is for the base conversion and zero-padding. Without those, it drops to 19 chars,
4,{2.@??)2.4??\/n}/

with output
21845
13107
3855
255

It was asked for exact text output - why should 16,zip{n}/ work then?

On the other hand you can do 16,zip{','-~n}%

@Howard, I think that zip should return an array of arrays, but it actually seems to return an array of Ruby arrays (is my best guess). Whatever the elements are, applying ` to them doesn't affect the way they print, which is unlike any of the 4 GolfScript data types. You're right that ','- seems to turn them into normal arrays: nice trick.

Seems to output 4 extra lines of zeros here

@aditsu, works on the online demo. I wonder why the difference. Ruby version, maybe?

I think the online demo is known to be buggy/old, but generally golfscript is quite quirky and it looks like you found a super-quirky feature/bug. How does that even make sense? Zipping an array of numbers converts to base 2?!

Postscript 108 177 126 77 74 70
[43690 52428 61680 65280]
{16{dup 2 mod =only 2 idiv}repeat<>=}forall

Reversed the values for a simpler mod- off method.
151 131 119
Applying a more APL-ish approach. edit: replaced string chopping and array zipping with indexing and for-loops.
[[0 1 15{}for]{16 add 2 5 string cvrs}forall]4
-1 1{0 1 15{2 index exch get 1 index 1
getinterval =only}for pop<>=}for

Indented:
[[0 1 15{}for]{16 add 2 5 string cvrs}forall]
4 -1 1{ % [] i
    0 1 15{ % [] i j
        2 index exch get % [] i [](j)
        1 index 1  % [] i [](j) i
        getinterval  % [] i [](j)<i>
        =only  % [] i
    }for
    pop<>= % []
}for

Reimplementing the functions used in the winning J answer leads to this (with a lot of support code).
-1 16 i + #: |: |.{{==only}forall()=}forall

i here is 1-based vector described in Iverson's Elementary Functions, hence the -1 ... + to produce 0 .. 15.

CJam - 16
4,{G,f{\m>2%}N}/

Equivalent java code (as explanation):
public class Lookup {
    public static void main(final String... args) {
        for (int i = 0; i < 4; ++i) {
            for (int j = 0; j < 16; ++j) {
                System.out.print((j >> i) % 2);
            }
            System.out.println();
        }
    }
}

Javascript (ECMA6), 67
s=(k,n)=>n-.5?s((k<<n/2)^k,n/2)+"0".repeat(n)+k.toString(2)+"\n":""

To use this, call
s(255,8)

Bitshift!
And also XOR and a bit of recursion.
The first thing to notice is that if we take any line and you shift it (# of continuous 0's) / 2 left, we get a nice XOR to get the next line up.
For example,
0000000011111111 //line 4
0000111111110000 //shifted 4 to the left

XOR these bitwise give us
0000111100001111 //XOR'ed. This is line 3!

which is the next line up (line 3).
Applying the same process for line 3, shift 2 left and we get...
0000111100001111
0011110000111100

XOR'ed gives
0011001100110011

which is line 2.
Notice that the amount we shift halves each time.
Now we simply call this function recursively, with 2 arguments. The integer value of this line, and N, which is how much we need to shift. When we do recursing just pass in the shifted XOR'ed value and n/2.
"0".repeat(n)

is to pad 0's to the beginning of each line because toString takes out leading 0's.

+1 Very cool. I had not noticed that pattern before.

A couple byes can be cut off this by bit shifting n instead of dividing it, and replacing the new line with a template string: s=(k,n)=>n?s((k<<n/2)^k,n>>1)+"0".repeat(n)+k.toString(2)+\
`:""`

J, 21 characters
1":<.2|(2^i.4)%~/i.16

i.16 is a list of 0..15
2^i.4 is a list (1,2,4,8)
%~/ produces the table of divisions where the left argument forms rows but is the right argument to division
2| calculates the remainder after dividing [each cell] by two
<. floors that value to 0 or 1
1": formats the table with one character per cell

I feel like the floor should not be necessary. The domain of 2| is already 0 or 1, right?

@luserdroog | operates on floats. 2|3.25 is 1.25. We don't want that.

GolfScript, 19 chars
Another GolfScript approach
4,{2\?{&!!}+16,%n}%

Ruby (44)
Boring and long: Just printing the 0-padded binary representations of the numbers.
[21845,13107,3855,255].map{|i|puts"%016b"%i}

Perl (36+1)
+1 for say, as usual.  the double 0 is not a typo :)
map say((00x$_,1x$_)x(8/$_)),1,2,4,8

No need to add 1 for say. perl -e'...' is standard and this requires perl -E'...', no increase in byte count. Anyway, I think it was decided on [meta] that -M5.01 is free.

Bash + coreutils, 65 bytes
Not the shortest, but not the longest either:
for i in {1,2,4,8};{ eval echo \$\[\({0..15}\&$i\)/$i];}|tr -d \

(The last character is a space)
Try it online.

JavaScript (ECMA6), 108
Trying a different approach here. Even though it was encouraged to use binary operators, I allowed myself to submit this solution since the challange is also kolmogorov-complexity and I was thinking - how can I reduce the amount of code representing those values...? Bases.
['gut','a43','2z3','73'].forEach(n=>{a=parseInt(n,36).toString(2);
alert(('00000000'+a).substr(a.length-8))})

(Line break for convenience).
It's a shame I had to mess with padding with leading zeros, but the point of this code is simply representing the target binary result in Base 36, which are exactly those gut, a43, 2z3, 73 values.
Note: I realize it won't be anywhere near the winning answer, but just for the sake of the idea...

I was about to do basically the same thing when I saw yours. I got it down to 92 bytes using the technique from my answer to a similar question: alert(['gut','a43','2z3',73].map(n=>(1e8+parseInt(n,36).toString(2)).slice(-16)).join('\n')). This approach uses newlines instead of four alert()s.

Sprects, 44 bytes
 aaaa
bbbb
zozo
zzoo o1111 z0000 b0011 a0101

Cedric's answer ported to Sprects.

MATL, 8 bytes
16:qYB!P

Try it online!
Explanation
16:    % Generate range [1 2 ... 16]
q      % Subtract 1, element-wise
YB     % Convert to binary. Gives a 16×4 char array. Each original number is a row
!      % Transpose
P      % Reverse vertically. Implicitly display

CJam, 10 9 bytes
Thanks to @Dennis for 1 byte off!
Y4m*zW%N*

Try it online!
Explanation
Y     e# Push 2
4     e# Push 4
m*    e# Cartesian power of 2 (interpreted as [0 1]) with exponent 4
z     e# Zip
W%    e# Reverse the order of rows
N*    e# Join with newlines. Implicitly display

JavaScript (ES6), 58 52 bytes
Builds the string recursively.
f=(n=64)=>n--?f(n)+(!n|n&15?'':`
`)+(n>>(n>>4)&1):''

How it works
This recursion is based on the fact that the pattern is made of the vertical binary representation of nibbles 0x0 to 0xF:
  0101010101010101 bit #0 <- Y = 0
  0011001100110011 bit #1
  0000111100001111 bit #2
  0000000011111111 bit #3 <- Y = 3
  ----------------
  0123456789ABCDEF
  ^              ^
X = 0          X = 15

Therefore, each position (X,Y) in this pattern can be expressed as the Y-th bit of X: X & (1 << Y). We can also isolate this bit with: (X >> Y) & 1. Rather than keeping track of X and Y, we iterate on a single variable n ranging from 0 to 63. So, the formula becomes: (n >> (n >> 4)) & 1. It's actually easier to iterate from 63 to 0, so the string is built in reverse order. In other words, character n-1 is appended to the left of character n.
As a side note, recursion doesn't bring anything here except shorter code.
Without the linebreaks, the code is 35 bytes long:
f=(n=64)=>n--?f(n)+(n>>(n>>4)&1):''

We need 17 more bytes to insert the linebreaks. This could be shortened to 14 bytes if a leading linebreak is acceptable.
Demo

f=(n=64)=>n--?f(n)+(!n|n&15?'':`
`)+(n>>(n>>4)&1):''

console.log(f());

In ideone with both languages JavaScript not compile in the exapme above there is one let more.... It is good the idea of one recursive function...

What would it take to split after the 35 bytes?

@Titus - Well. At first glance, I don't have any good solution for that. Here is a (very bad) attempt: (f=(n=64)=>n--?f(n)+(n>>(n>>4)&1):'')().match(/.{16}/g).join\\n` ` (63 bytes)

hmm ... and .replace(/.{16}/g,"$0\n") has the same length. Too bad.

f=(n=64)=>n--?f(n)+(n>>(n>>4)&1)+(~n%16?'':"\n"):''; with a trailing newline, which seems more reasonable

C 83 77 76 74 71
x;f(n){for(;x<4;x++,puts(""))for(n=0;n<16;)putchar(49-!(n++&(1<<x)));}

Pretty straightforward.
x;
f(n){
    for(;x<4;x++,puts(""))
        for(n=0;n<16;)
            putchar(49-!(n++&(1<<x)));
}

There's an easy saving of 2 by not using ?:, and another saving of 1 by moving a ++.

Saved 3 by changing main to f. lol

NARS2000 APL, 22
"01"[⊖1+(4⍴2)⊤(⍳16)-1]

Derived from marinus's APL answer, which doesn't seem to work on NARS2000.
Generate vector
      ⍳16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Change to zero-based
      (⍳16)-1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Generate shape for encode
      (4⍴2)
2 2 2 2

Encode
      (4⍴2)⊤(⍳16)-1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

Adjust for 1-based indexing
      1+(4⍴2)⊤(⍳16)-1
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2
1 1 1 1 2 2 2 2 1 1 1 1 2 2 2 2
1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2

Reverse primary axis
      ⊖1+(4⍴2)⊤(⍳16)-1
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2
1 1 1 1 2 2 2 2 1 1 1 1 2 2 2 2
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2

Index
      "01"[⊖1+(4⍴2)⊤(⍳16)-1]
0101010101010101
0011001100110011
0000111100001111
0000000011111111

You can set ⎕IO to 0, so that you don't have to adjust for 1-based indexing. That brings it down to 16 characters.

Yes, but then I fear it's too similar to the other APL answer and wouldn't deserve to be here at all.

C, 73 chars
i;main(){for(;i<64;)i&15||puts(""),putchar(48|1&~0xFF0F0F33335555>>i++);}

This is just a general solution for outputting 64 bits in four 16-bit blocks; you just need to change the number 0xFF0F0F33335555 to output an other bit sequence.
simplified & ungolfed:
int main() {
    int i;
    for(i = 0; i < 64; i++) {
        if(i % 16 == 0) {
            puts("");
        }
        int bit = ~0xFF0F0F33335555 >> i;
        bit &= 1;
        putchar('0' + bit);
    }
}

Haskell, 73
Yikes, 73 chars! I can't for the love of god get this any smaller though.
r=replicate
f n=r(div 8n)("01">>=r n)>>=id
main=mapM(putStrLn.f)[1,2,4,8]

The real sad part about this is that if you were to echo the output using bash, you'd only need 74 characters.

inca2, 33 27 24
4 16#(,`2|(~16)%.2^~4){D

This is based on Jan Dvorak's answer. inca2 is able to execute this as of yesterday's bugfixes. Technically invalid since the language was invented after the question, but invention of a language was part of my goal in posing the question. So here's some payback in gratitude to the other answers. :)
Explanation:
4 16#(,`2|(~16)%.2^~4){D
          (~16)               integers 0 .. 15
                 2^~4         first 4 powers of 2: 1 2 4 8
          (~16)%.2^~4         division table
        2|                    mod 2 (and floor)
       `                      transpose
      ,                       ravel
     (               ){D      map to chars '0'..'9'
4 16#                         reshape to 4x16

Some of the parentheses should be unnecessary, but apparently there are some remaining issues with my interpretation of the grammar. And "ravel => map => reshape" is really clumsy: map needs to be smarter. Edit: bugfixes allow elimination of parens.

Factoring the base conversion into a separate function N:x|y%.x^~1+[]/x.y yields this 19 16 char version.
4 16#(,`2N~16){D

And while I'm cheating anyway here, I've gone ahead and made this a built-in function. But, even though it's a niladic function (not requiring an argument), there is no support for niladic functions, and it must be supplied with a dummy argument.
inca2, 2
U0

JavaScript (ES5) 69
for(x="";4>x;x++){z="";for(n=0;16>n;)z+=1-!(n++&1<<x);console.log(z)}

Pyth 24 / 26
The shortest method was grc's answer translated to Pyth which I felt was cheap so I did my own method:
Mine: 26 characters
 mpbjk*/8dS*d[0 1)[1 2 4 8

grc's: 24 characters
Fd[1 2 4 8)*/8d+*\0d*\1d

C++ 130
Converts hex to binary
#define B std::bitset<16>
#define C(x) cout<<x<<endl;
void main(){
B a(0xFF),b(0xF0F),c(0x3333),d(0x5555);
C(d)C(c)C(b)C(a)
}

Haskell (Lambdabot), 47 bytes
unlines$reverse$transpose$replicateM 4['1','0']

Kinda cheaty because it uses transpose from Data.List and replicateM from Control.Monad, however both are loaded by default from Lambdabot.
Also, I'm sure there is room for improvement, just wanted to share the idea

R, 53 41 bytes
A translation of @grc's python answer. Shaved off 12 bytes from the original translation through use of rep()'s each and length arguments (and partial argument matching), and by remembering that 0:1 is equivalent to c(0,1).
for(n in 2^(0:3))print(rep(0:1,e=n,l=16))

for(n in 2^(0:3))print(rep(c(rep(0,n),rep(1,n)),8/n))

You can also attempt a translation of @Gareth's J answer, something like this (34 bytes):
t(e1071::bincombinations(4))[4:1,]

However, it uses a function that's not part of base R, and outputs a matrix which is hard to format into exact printed text like in the specification.

Julia (39 Bytes)
Second script I've ever written in Julia, gotta admit I'm liking Julia, she's a pretty beast.
hcat(map(x->collect(bin(x,4)),0:15)...)

Returns
[0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]

Explanation:

bin(x,4) - Convert int to binary integer with padding to 4 characters.
collect(_) - Split string into char array.
map(x->_,0:15) - Do this for the first 16 digits in the range.
hcat(_...) - Splat and horizontally concatenate into a matrix.

PHP , 56 Bytes
for(;$i<64;$i++)echo($i%16?"":"\n").($i&2**($i>>4)?1:0);

86 Bytes
for($i=1;$i<9;$i*=2)echo str_repeat(str_pad(decbin(2**$i-1),2*$i,0,0),16/(2*$i))."\n";

C 70 bytes
c,k=1,i;x(){putchar(48+i);i^=!(++c%k);c%16||(k*=2)+puts("");k>8||x();}

use recursive function... in https://ideone.com/ it compile and result:
0101010101010101
0011001100110011
0000111100001111
0000000011111111

even if in the compiler i use it does not compile...

all functions that use global variables, if they use their value 0, can be ok only one time or only if global variable are at start 0

PHP, 76 70 68 67 61 57 45 bytes
Now it´s worth it: code shorter than its output. :)
for(;$x<64;$x++)echo$x%16?"":"
",$x>>$x/16&1;

run with -r.
runs through rows and columns in one loop:
$x/16 rounded is the row number,
$x%16 the column and decimal value of the binary value we want to display:
In columns 0,16,32,48 ($x%%16 falsy) print a linebreak.
If bit $x/16 is set ($x>>$x/16&1), print 1, else 0.

add 2 bytes for trailing instead of leading linebreak:
for(;$x<64;$x++)echo$x>>$x/16&1,$x+1&15?"":"
";

Thunno N, \$ 12 \log_{256}(96) \approx \$ 9.88 bytes

-1 character thanks to Jacob

16Rb4zKZtr.J

Attempt This Online!
Port of Gareth's J answer.
Explanation
16Rb4zKZtr.J
16R            # Push [0, 1, ... 15]
   b           # Convert each to binary
     zK        # Pad each string with "0"s
    4          # to 4 characters
       Zt      # Transpose the resulting list
         r     # Reverse this list
          .J   # Join each inner list by ""
               # N flag joins the list by newlines
               # Implicit output

Can you explain why Thunno programs are counted in their character count multiplied by log256(96)? I thought it used ASCII which is one character per byte, am I missing something?

I don't really understand how but 16Rbe04zLEZtr.J for 15 chars works. My guess is that Thunno interprets 04 as two distinct integers rather than just 4, and zL can stringify an integer for its argument?

@Jacob Thunno uses the 96 printable ASCII characters as its codepage. There was a discussion about this when Fig (which also does the same thing) was released, and the conclusion was that the character count can be multiplied by log_256(96).

Also, thanks for the suggestion! I forgot about that. Basically, the interpreter will push any leading 0s separately, and you're right in saying that zL stringifies it's arguments.

Japt -R, 9 bytes
GÇ¤ùT4ÃÕÔ

Test it
GÇ¤ùT4ÃÕÔ
G             :16
 Ç            :Map the range [0,G)
  ¤           :  To binary string
   ù          :  Left pad
    T         :    With 0
     4        :    To length 4
      Ã       :End map
       Õ      :Transpose
        Ô     :Reverse
              :Implicit output joined with new lines


text:
Total number of cells in R numeric dataframe
Problem statement
The task is to write the shortest R statement to count the cells (rows * cols) in an instance of the R type numeric data.frame. For example, the data.frame which would be displayed as
  a    b  c
1 1 2000 NA
2 2 2000 NA
3 3 2000 1
4 4 2000 Inf

has 12 cells.
Input
The data.frame is supplied in variable x. You may assume that it contains only numbers, boolean, NA, Inf (no strings and factors).
Test cases
Example code to construct your own data.frame:
x <- merge(data.frame(a = 1:100),
    merge(data.frame(b = 2000:2012),
    data.frame(c = c(NA, 10, Inf, 30))))

The expected output is 15600.
Appendix
Curious if someone can beat my solution :-) I don't want to take the fun from you so I will not reveal it now, I will only show you md5sum of my solution so that you later trust me in case you invent the same :-)
d4f70d015c52fdd942e46bd7ef2824b5

One example of input does not suffice to be a spec. What are the delimiters? Are the row and column headers guaranteed to be present? Can a cell be empty, and if so how is that represented? Also, you talk about people beating your solution, but you haven't specified a criterion for comparison.

@Peter, this is R challenge. You get x as a variable of type data.frame. It is not text input. I specified that in the question already. Ad the criterion - please read the question: "construct as short command as possible". Please if you don't understand, this is not reason for downvote.

@Peter, I've added an example of input data. Please retract the downvote.

Actually, "the question is unclear" is explicitly given as a reason for downvoting. I will try to clarify it.

@PeterTaylor this question seems pretty clear to me, perhaps because I am quite familiar with R.

@SimonO101, you're looking at the seventh revision.

@PeterTaylor point taken. It is all the better for the revisions.

Naive:
> nrow(x)*ncol(x)
[1] 15600

First idea:
> prod(dim(x))
[1] 15600

Best I can do so far:
> length(!x)
[1] 15600

SimonO10 on the R chat had an idea (sum(!(F&x))), which I modded to get:
> sum(T|x)
[1] 15600

Note this doesn't work on factors, but you excepted those.

Very good! But it still can be few characters shorter ... :)

+1 joint honours I reckon unless Tomas has something sneaky up his sleeve!

sum(x|T) is my solution!!! You can check the md5 sum now!!! :-)

@Tomas How do you get that md5sum? I get 093130007d6f8d5d43e6bbab25f68733 for a file containing only sum(x|T).

@ChristopherBottoms you have to remove the newline - it is without newline.

@Tomas Thanks. I didn't think it had a newline, but xxd -p showed that it did.

My best two attempts so far only got me down to 11 characters. I'd love to see fewer than @Spacedman's 10!
>sum( `[<-`(x,,,1) )
[1] 15600

>sum(!(F&x))
[1] 15600

Got it!
sum(x^0)
[1] 15600

NA^0 is 1? Whooda thunk it?

@Spacedman I know! It makes sense though right. NA is missing data, but anything ^ to 0 is 1.

yes, but NA isn't anything :) It's absence of thing. Although I guess the argument is that even if you have a missing measurement for something you know that whatever it was to the zeroth power is going to be 1. NaN^0 == 1 is a bit more worrying (philosophically) though.

Agreed. I thought NA was a placeholder for missing data. Sicne this is numeric data it has to be a missing number therefore it has to resolve to 1. FWIW if you try x^0 on character column with NAs you correctly get an error.

@Spacedman what is even more worrying is that is.numeric(NaN) == TRUE :-) As well as in javascript, "Not a Number" IS number :D

you both guys now have the same length solution as me. Let's see if someone can make something even shorter :-)

@Tomas is yours the same as one of ours or do you have a third one that is the same length?

@SimonO101 see the comment on Spacedmans answer

sum(1^x) worked as well

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Change the innermost element type of a jagged array — any .NET language: C#, F#, VB.NET, MSIL, C++/CLI, etc
Write a class containing a method with the signature
System.Array ChangeElementType(System.Array jaggedArray)

(you may rename identifiers ChangeElementType, jaggedArray and shorten the type System.Array with using directives). The class may contain any additional members if needed.
You may assume the following preconditions (and do not need to validate them):

The argument jaggedArray is not null.
The argument jaggedArray is an array instance whose type can be represented in C# notation as int[...]..., i.e. the type int followed by 1 or more rank specifiers [...] where each rank specifier is a pair or square brackets with 0 or more commas between them. For example, it could be an array of type int[], int[,][][,,,], etc.
No element at any level of the jaggedArray is null.
All elements at any level of the jaggedArray are distinct w.r.t. reference equality (i.e. the same array instance does not appear at several different positions).
The lower bound of any array dimension is 0.
The length of any dimension and the total number of elements of any array fits into the type int.

The method must create and return an array of type long[...]... which is obtained from the type of jaggedArray by replacing int with long and keeping all rank specifiers the same. The result must have the same shape as jaggedArray, i.e. all array dimensions at any level must be the same. All elements at the innermost level must have the same numeric values (cast from int to long). The method must not mutate the argument jaggedArray or any its elements at any level.
The solution may be implemented in any language for the .NET platform: C#, F#, VB.NET, MSIL, C++/CLI, etc. All necessary using, open or imports directives or fully qualified names must be explicitly specified (do not rely on IDE defaults). The only referenced assembly must be mscorlib, no P/Invoke or COM Interop allowed. The solution cannot access any Internet services to get the result, intermediate data or to download parts of an algorithm.
It is a golf — try to minimize the number of bytes in the source.

can you clarify what The lower bound of any array dimension is 0. means? does this just mean to use 0-based array indexing, or maybe some notion of 0-length arrays? in general, i'm having trouble understanding the objective here

Does is have to accept both value types and reference types? I can create a version for each but I'm struggling to make one that does both.

@Pharap The innermost element type of the input array is guaranteed to be int and it should be converted to long. You do not need to handle arrays whose innermost element type is not int (e.g. any reference type).

@ardnew See http://msdn.microsoft.com/en-us/library/system.array.getlowerbound

C# - 396 440 595
I'm not entirely sure why I did this, and I can't help but feel I'm missing something. Rewrote the old c (for copy) method as a for-loop in the ChangeElementType method (f). Unless I find something substantial, I think I'll not be making this any shorter.
Golfed code:
using A=System.Array;using T=System.Type;class P{T g(T o){return o.IsArray?g(o.GetElementType()).MakeArrayType(o.GetArrayRank()):typeof(long);}A f(A a){var R=a;int i,r;for(var x=new int[i=r=a.Rank];;){if(i<1){if(a!=R)return R;R=A.CreateInstance(g(a.GetType().GetElementType()),x);i=1;}if(--i<r)if(x[i]-->0)i+=2;else x[i]=a.GetLength(i);else{var o=a.GetValue(x);R.SetValue(o is A?f((A)o):o,x);}}}}

Readable code with an excuse for a test:
using A=System.Array;
using T=System.Type;

class P
{
    // turns a type like "int[,][]" into "long[,][]"
    T g(T o)
    {
        return o.IsArray?g(o.GetElementType()).MakeArrayType(o.GetArrayRank()):typeof(long);
    }

    // ChangeElementType
    A f(A a)
    {
        var R=a; // R is the result, a gives us the type and a nice default value
        int i,r; // i is a counter, r is the rank

        // this loop first counts backwards filling the x array with the dimension lengths
        // then it does a tree traversal and copies things about
        for(var x=new int[i=r=a.Rank];;) // create the x array, and sets i and r
        {
            if(i<1)
            { // gone off start
                if(a!=R) // been here before
                    return R; // return the result
                R=A.CreateInstance(g(a.GetType().GetElementType()),x); // create the array to fill
                i=1; // move to start of x
            }

            if(--i<r) // move back
                if(x[i]-->0) // decrement index
                    i+=2; // move forward instead
                else
                    x[i]=a.GetLength(i); // reset index
            else
            {
                var o=a.GetValue(x); // get the int/array
                R.SetValue(o is A?f((A)o):o,x); // if it's an array, Change it, if not, pass it directly (the int)
            }
        }
    }

    // test method (prints True if the code works, might print False if it doesn't)
    static void Main()
    {
        string old = "";

        var a = new int[10][,];

        for (int i = 0; i < 10; i++)
        {
            a[i] = new int[3,5];

            for (int j = 0; j < 3; j++)
            {
                for (int k = 0; k < 5; k++)
                {
                    int v = i * j * k;
                    a[i][j,k] = v;
                    old += v.ToString();
                }
            }
        }

        long[][,] l = (long[][,])(new P().f(a));

        string nwe = "";

        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                for (int k = 0; k < 5; k++)
                {
                    nwe += l[i][j,k].ToString();
                }
            }
        }

        System.Console.WriteLine(old == nwe);

        System.Console.ReadKey(true);
    }
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
(Python) Implementing incrementation
Challenge: Implement incrementation without addition, multiplication, exponentiation, and any higher binary operators (and their opposites) in Python.
Winner is the person who can do it in the least amount of code. You score 5 characters less if you can do it for negative numbers and without unary operators.

3
-~i

Just good ol' unary - and bitwise-NOT.
Demo
>>> i = 3
>>> -~i
4
>>> i = 0
>>> -~i
1
>>> i = -3
>>> -~i
-2

14
I'm not a python guy, so here we go:
len(' '*i+' ')

According to the docs, I don't use addition, only string concatenation and repetition.

yeah nevermind, i figured it out. im not 100% perfect with python, so i wouldnt think of using string concatenation. pretty good!

Writing a good code golf challenge is hard. It is part of the [tag:code-golf] game to stretch the rules to the limit if it makes your scoring better.

17 characters
Not shortest, but another way. This time no maths or binary operators involved at all.
But it only works on numbers greater than -1.
len(range(-1,x))

Proof:
>>> inc = lambda x: len(range(-1,x))
>>> inc(7)
8
>>> inc(100)
101

28 = 33-5 characters
Definitely out of contention but this does it for all positive and negative integers, again no math, no unary tricks.
len(range(-1,x)) or range(x,1)[1]

Proof:
>>> inc = lambda x:len(range(-1,x)) or range(x,1)[1]
>>> for i in range(-2,2): print i, inc(i)
...
-2 -1
-1 0
0 1
1 2

-1 on 33-5: len(range(-1,x))or range(x,1)[1]. The score is 27=32-5 then.

10 - 5 = 5
sum((i,1))

Demo
>>> i = -3
>>> sum((i,1))
-2
>>> i = 0
>>> sum((i,1))
1
>>> i = 3
>>> sum((i,1))
4

isnt this pretty much addition?

@DavidHewett At it's core, it is addition. But this does not explicitly use +. The challenge description as-is seems to permit this; correct me if I'm wrong.

the description states addition, and a sum of two numbers is the same thing as addition.

@DavidHewett So we can't use any function that, somewhere in its C implementation, uses addition? Also note that sum returns the sum of an iterable, in this case the tuple (i,1).

You can use a function that uses addition, but not a function that "does" addition, if that makes any sense.

There's no clear distinction between a function that uses addition and one that does addition.  E.g., sum() can also be used to concatenate tuples: sum([(2,3), (4,5)], ()) returns (2, 3, 4, 5).

@DavidHewett It's impossible to differentiate the two.

27-5=22
It's not really very short, but it doesn't use len(), range(), sum() and other stuff which definitely has a lot of increments and additions in it. Works with negative numbers, and no unary operations. Only pure, natural, raw, organic bitwise magic :)
j=i
k=1
while i<=j:i^=k;k<<=1

Demo:
>>> def inc(i):
...     j=i
...     k=1
...     while i<=i:i^=k;k<<=1
...     return i
...
>>> inc(1)
2
>>> inc(2)
3
>>> inc(20)
21
>>> inc(-24)
-23
>>>

(UPD: Sorry, I'm not sure whether newlines are counted as chars, if yes, it should be 29 not 27...)


text:
Build a solver for the cow and chicken problem
The cow and chicken problem is a traditional problem for introducing young students to the concept of systems of equations. It goes as follows:

A farmer raises cows and chickens on his farm. His animals have a total of 24 heads and 68 legs. How many cows and how many chickens does he have?

The numbers of heads h and legs l can vary, but the idea of the problem is the same. This problem can't be solved by plugging in a one-variable formula; both variables (the number of cows k, and the number of chickens x) will always be involved in each formula that you can derive directly.
That being said, for this version of the problem, there is a formula k = l/2 - h that you can readily use to obtain the solution of 10 cows and 14 chickens, so it's not too interesting.
Here's a slightly different problem, this time involving cows and chickens who can have a different number of heads and legs.
Your task is to build a program that takes the following inputs (all positive integers):

hk, the number of heads a cow has.
lk, the number of legs a cow has.
hx, the number of heads a chicken has.
lx, the number of legs a chicken has.
h, the total number of heads.
l, the total number of legs.

: and output k and x, how many cows and chickens the farmer has.
However, depending on the input given, the problem has several states of solvability:

There is a solution in the nonnegative integers. The input 1 4 1 2 24 68 (which is the problem above) has the solution 10 14.
There is no solution in the nonnegative integers, but there is one in the nonnegative fractional numbers. The input 1 4 1 2 24 67 is an example of this, with a solution of 9.5 14.5.
There is no solution in the nonnegative numbers, but one in the integers in general. The input 1 4 1 2 24 36 is an example of this, with a solution of -6 30.
There is no solution in either the nonnegative fractional numbers or the integers in general, but one in the real numbers in general. The input 1 4 1 2 24 97 is an example of this, with a solution of 24.5 -0.5.
There is no solution at all. The input 2 4 1 2 24 68 is an example of this.
There are multiple solutions in the positive integers (and therefore infinitely many solutions in the real numbers). The input 2 4 1 2 24 48 is an example of this. If there is exactly one solution in the positive integers but infinitely many solutions in the real numbers (as is the case with the input 6 9 4 6 10 15 with a solution of 1 1), your solution can treat it as a case of this state.

Your program, given the inputs, must first output which state of solvability the problem has. Only if the problem is in the first state of solvability should you output how many cows and chickens there are, as any other solution is considered an "invalid problem".
The shortest code to do all of the above in any language wins.

must first output which state of solvability the problem has first This is the hardest part; I've been trying for a while and I still can't even think of a way to start doing it :P

@primo No, it's not. Note that 2 4 1 2 means that there are always twice as much legs as heads, no matter how many cows or chicken are involved. Thus there is no way to have 24 heads but 68 legs.

Sorry, I had my lk and lx switched.

See also this problem over the rationals.

GolfScript, 105 101 characters
{](=}+1360222640 6base%4/{~*@@*-}%.2=0<{{~)}%}*).{1${1$%0>}%~|2${0<}%~|.++.)p!{{/}+%p}*;;}{;~|!5+p}if

A first (and rather clumsy) approach using GolfScript.
The test cases (see online):
> 1 4 1 2 24 68
1
[10 14]

> 1 4 1 2 24 67
2

> 1 4 1 2 24 36
3

> 1 4 1 2 24 97
4

> 2 4 1 2 24 68
5

> 2 4 1 2 24 48
6

Out of curiosity, what does the "1360222640" do?

@Joe Magic.

@JoeZ. and Doorknob - what else do you expect from a magic number.

@JoeZ. 1360222640 6base 4/ decodes to [[3 4 2 5] [5 0 1 4] [3 0 1 2]] which is used to calculate take product of parameters 3 and 4 and subtract that from product of parameters 2 and 5, ...

I was just thinking, it sort of looked like a Unix time stamp, so...

(The unix time 1360222640 corresponds to 7:37:20 AM, Thursday, February 7, 2013 in UTC.)

Mathematica 359 314
About 200 characters went into determining which condition applies.
f@{a_, b_, c_, d_, i_, l_} :=
 Module[{s, t, z = "invalid problem", y = IntegerQ},
  t@n_ := y@n \[And] (n > 0);
  p@n_ := n \[Element] Rationals \[And] n > 0;
  q@n_ := n \[Element] Reals;
  w = Flatten@Quiet@Solve[{d*x + b*k == l, c*x + a*k == i}, {k, x}];
  s = {k, x} /. w;
  Which[w == {}, {5, z},
   Length[w] != 2, {6, z},
   True, If[And @@ (t /@ s), {1, s},
    Which[
     And @@ (p /@ s), {2, z},
     And @@ (y /@ s), {3, z},
     And @@ (q /@ s), {4, z},
     3 == 3, {7, z}]]]]

f[{1, 4, 1, 2, 24, 68}]
f[{7, 14, 9, 6, 25, 18}]
f[{1, 4, 1, 2, 24, 67}]
f[{1, 4, 1, 2, 24, 36}]
f[{1, 4, 1, 2, 24, 97}]
f[{2, 4, 1, 2, 24, 68}]
f[{2, 4, 1, 2, 24, 48}]
f[{1, 4, 1, 2, -23, (3 + I)^2/(5 - I)}]
f[{6, 9, 4, 6, 10, 15}]

{1, {10, 14}}
{2, "invalid problem"}
{2, "invalid problem"}
{3, "invalid problem"}
{4, "invalid problem"}
{5, "invalid problem"}
{6, "invalid problem"}
{7, "invalid problem"}
{6, "invalid problem"}

How it works
The  equations d*x+b*k==land c*x+a*k==i express the constraints in the general cow and chickens problem,where

a is "the number of heads per cow"
b is "the number of legs per cow"
c is "the number of heads per chicken"
d is "the number of legs per chicken"
i is "the number of  heads"
l is "the number of legs"
k is "the number of cows"
x is "the number of chickens".

Solve returns the real - valued solutions, if any exist, for the cows and chickens, as a list of 2 substitution rules, e.g.
{k->10, x-> 14}
If no solutions exist, an empty list is returned.
If the data cannot be processed, Solve will return a different number of elements.
The tests are performed in the following order.

If there are 0 solutions, condition 5 is satisfied

If the list of "solution"s has anything other than 2 elements, then condition 6 is satisfied .

If there are 2 solutions, then

if function t yields True, the solution is a pair of non-negative integers, and condition 1 is satisfied.
if function p yields True, the solution is a pair of  non negative rationals and condition 2 is satisfied.
if function q yields True, the solution is a pair of  non negative rationals and condition 3 is satisfied.
if function y yields True, the solution is a pair of  integers and condition 4 is satisfied.
Otherwise, condition 7 is satisfied.

Minor Variant of f
g@{a_, b_, c_, d_, i_, l_} :=
 Module[{s, t, z = "invalid problem", y = IntegerQ},
  t@n_ := y@n \[And] (n > 0);
  p@n_ := n \[Element] Rationals \[And] n > 0;
  q@n_ := n \[Element] Reals;
  w = Flatten@Quiet@Solve[{d*x + b*k == l, c*x + a*k == i}, {k, x}];
  s = {k, x} /. w;
  Which[w == {}, {5, z, w}, Length[w] != 2, {6, z, w}, True,
   If[And @@ (t /@ s), {1, s, w},
    Which[And @@ (p /@ s), {2, z, w}, And @@ (y /@ s), {3, z, w},
     And @@ (q /@ s), {4, z, w}, 3 == 3, {7, z, w}]]]]

g is f` with the additional property that it returns the output of Solve.
g[{1, 4, 1, 2, 24, 68}]
g[{7, 14, 9, 6, 25, 18}]
g[{1, 4, 1, 2, 24, 67}]
g[{1, 4, 1, 2, 24, 36}]
g[{1, 4, 1, 2, 24, 97}]
g[{2, 4, 1, 2, 24, 68}]
g[{2, 4, 1, 2, 24, 48}]
g[{1, 4, 1, 2, -23, (3 + I)^2/(5 - I)}]
g[{6, 9, 4, 6, 10, 15}]

{1, {10, 14}, {k -> 10, x -> 14}}
{2, "invalid problem", {k -> 1/7, x -> 8/3}}
{2, "invalid problem", {k -> 19/2, x -> 29/2}}
{3, "invalid problem", {k -> -6, x -> 30}}
{4, "invalid problem", {k -> 49/2, x -> -(1/2)}}
{5, "invalid problem", {}}
{6, "invalid problem", {x -> 24 - 2 k}}
{7, "invalid problem", {k -> 615/26 + (19 I)/26, x -> -(1213/26) - (19 I)/26}}
{6, "invalid problem", {x -> 5/2 - (3 k)/2}}

Problems falling under condition 6 have multiple solutions, as evidence by the equations.  The problem that falls under condition 5 returns an empty set (no solutions).
Note: element and and are single characters in Mathematica.

I guess I should have included more test cases. Could you run 7 14 9 6 25 18 by and see if it returns 2?

The additional test case returns 2, as expected.

I also threw in a case with a complex number.

It's no longer a positive integer, then. The problem statement says that all inputs will be positive integers.

Exactly. The issue was not whether a complex number is valid for the problem, but rather, what condition should flag it as invalid. It fails each of the first 6 conditions. The 6 conditions, in other words, do not exhaust all of the possible conditions.  Hence the need for a seventh "everything else" condition. The condition is satisfied when the first 6 conditions are not met and 3 = 3.

Can you come up with a positive-integer problem that doesn't trigger any of the six conditions I gave?

I'm not sure what you are requesting. If the positive integer problem has a solution pair, then condition 1 is returned. If it has no solution, then condition 5 is returned. What other possibilities exist?

What I mean is, if it's never going to happen with positive-integer inputs, your seventh case is unnecessary.

You are correct. Those will all be caught by condition 1 and the function t.

I'll need you to run one more test case... does 6 9 4 6 10 15 return 1 or 6?

@JoeZ. I included that case above, along with some additional information.

The problem I posted actually only has one solution in the positive integers, but I've updated the program requirements to allow you to be able to treat it as a case of solvability state 6 anyway.

Python 2, 138
a,A,b,B,h,l=input()
d=a*B-b*A
k=B*h-b*l
c=a*l-A*h
if d:K=k/d;C=c/d;z=K>=0<=C;print[[3,[1,K,C]][z],4-2*z][k%d+c%d!=0]
else:print(0==c==k)+5

Expects comma seperated input. The inputs
1, 4, 1, 2, 24, 68
7, 14, 9, 6, 25, 18
1, 4, 1, 2, 24, 67
1, 4, 1, 2, 24, 36
1, 4, 1, 2, 24, 97
2, 4, 1, 2, 24, 68
2, 4, 1, 2, 24, 48

yield the (admittedly not very nicely formatted) answers
[1, 10, 14]
2
2
3
4
5
6

J - 124 characters
(excluding the assignment)
Reduced the "invalid problem reporting" clutter (154 -> 124).
chico =: ((>:@],(#"1~-.@*))#.@(0&>,&(>./)(~:<.)) ::({&0 4 5@#))~@(({:%.}:)@; ::(":@(11-#@~.@;@:(%/&.>))))@(((0 2,:1 3);4 5)&({&.>;~))

tests:
t =: ,. 1 4 1 2 24 68;1 4 1 2 24 67;1 4 1 2 24 36 ;1 4 1 2 24 97;2 4 1 2 24 68;2 4 1 2 24 48
chico &.> t
NB. outputs:
+-----------------+
|1 10 14          |
+-----------------+
|2                |
+-----------------+
|3                |
+-----------------+
|4                |
+-----------------+
|5                |
+-----------------+
|6                |
+-----------------+

un-golfed version + comments
NB. Print case and the solution if the state is 0.
print  =: (>:@],(#"1~-.@*))

NB. 0 1 2 3 considering binary coding based on positivity and fractionality of
NB. all (>./) elements of the solution. If error caused by a string, then choose 4
NB. or 5 based on length of the string passed.
case   =: #.@(0&> ,&(>./) (~:<.)) :: ({&0 4 5@#)

NB. Solve, if error, determine whether multiple solutions exist, then output
NB. '10' else output '9' (just for having length 1 or 2 strings)
solve  =: ({:%.}:)@; ::(":@(11-#@~.@;@:(%/&.>)))

NB. Parse input list to obtain matrix and rhs of the system to solve.
format =: (((0 2,:1 3);4 5)&({&.>;~))

NB. Piece the bricks together:
chico_ng =: (print case)~ @ solve @ format

NB. testcases and solutions:
t=: (,.1 4 1 2 24 68;1 4 1 2 24 67;1 4 1 2 24 36;1 4 1 2 24 97;2 4 1 2 24 68;2 4 1 2 24 48)
sols =: ,. 1 10 14 ; (1$2) ; (1$3) ;(1$4) ;(1$5);(1$6)
(sols -: chico_ng each t) # 'fail','pass'
+----+
|pass|
+----+

C - 181 177 characters
a,b,c,d,e,f,g,j;main(){scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f);g=b*c-a*d;a=b*e-a*f;b=c*f-d*e;j=g?2*(b*g<0||a*g<0)+(b%g&&a%g):b||a?4:5;putchar(j+49);j||printf(" %d %d",b/g,a/g);}

Just a rough sketch, I should be able to get it down to around 150 characters with some massage.