text:
Mean bits: an average challenge
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1
Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.
The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.
The output should be accurate to at least 7 significant figures.

Example
N = 6
0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2
Test cases
Input => output
1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571

Leaderboard Snippet
(from here)

var QUESTION_ID=80586,OVERRIDE_USER=20283;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

Nice name, very punny.

For anyone who doesn't know, I'm more likely to upvote solutions with an explanation

Not enough puns, you need a bit more for this to be perfect.

I'm assuming that by "each number" you mean "each integer"?

@Cyoce yes, thank you for pointing that out - I've edited to clarify.

Pyth, 6 bytes
.Oml.B

Try it online here.
.Oml.BdUQ              Filling in implict vars

.O                     Average of list
 m   UQ                Map over [0..input)
  l                    Length of
   .B                  Binary string representation of int
    d                  Lambda var

Joint first place but you weren't showing up on the leaderboard - I've made a minor edit to the header to fix it.

Jelly, 6 bytes
R’BFL÷

Try it online!
R’BFL÷  Main monadic chain. Argument: n

R       yield [1, 2, ..., n]
 ’      decrement; yield [0, 1, ..., n-1]
  B     convert to binary; yield [[0], [1], [1,0], [1,1], ...]
   F    flatten list; yield [0, 1, 1, 0, 1, 1, ...]
    L   length of list
     ÷  divide [by n]

Octave, 29 bytes
@(n)1+sum(fix(log2(1:n-1)))/n

Explanation
              log2(1:n-1)       % log2 of numbers in range [1..n-1]
                                % why no 0? because log2(0) = -Inf  :/
          fix(           )      % floor (more or less, for positive numbers)
      sum(                )     % sum... wait, didn't we miss a +1 somewhere?
                                % and what about that missing 0?
                           /n   % divide by n for the mean
    1+                          % and add (1/n) for each of the n bit lengths
                                % (including 0!)

Sample run on ideone.

Python 3, 43 bytes
def f(n):x=len(bin(n))-2;return(2-2**x)/n+x

Makes use of the formula on the OEIS page. Surprisingly, a named function is somehow cheaper here because of the assignment to x.
Alternative approach for 46 bytes:
lambda n:-~sum(map(int.bit_length,range(n)))/n

Unfortunately, the -~ is necessary since (0).bit_length() is 0, but even then it'd be a byte too long.

Julia, 27 bytes
n->endof(prod(bin,0:n-1))/n

Try it online!
How it works
Since * is string concatenation in Julia, prod can be used to concatenate an array of strings. It optionally takes a function as first argument that it maps over the second one before taking the actual "product", so prod(bin,0:n-1) is the string of the binary representation of all integers in the desired range. Taking the length with endof and dividing by n yields the mean.

Jelly, 8 bytes
Not shorter, but interesting algorithm, and my first Jelly submission:
Rl2Ċ»1S÷

R         1 to n
 l2       log2
   Ċ      ceiling
    »1    max of 1 and...
      S   sum
       ÷  divided by n

Julia, 28 bytes
n->mean(ceil(log2([2;2:n])))

Since bin doesn't automatically map over arrays, we're using ceil(log2(n)) to get the number of bits in n-1. This works out nicely because Julia's a:b notation is inclusive on both ends, so 2:n is a range from 2 to n, but we're really calculating the number of bits for numbers in the range 1:n-1. Unfortunately though, we need to tack on an extra 2 to account for 0.
Try it online!

MATL, 9 bytes
q:ZlksG/Q

Try it Online!
Modified version with all test cases
Explanation
    % Implicitly grab input (N)
q:  % Create array from 1:N-1
Zl  % Compute log2 for each element of the array
k   % Round down to the nearest integer
s   % Sum all values in the array
G   % Explicitly grab input again
/   % Divide by the input
Q   % Add 1 to account for 0 in [0, ... N - 1]
    % Implicitly display the result

Snap!!  (filler)

@David Actually, yours was correct. Duplicating the input at the beginning doesn't work for other values... you need the G/Q at the end.

MATL, 9 bytes
:qBYszQG/

Try it online!
Explanation
:qBYszQG/
:               % take vector [1..n]
 q              % decrement by 1 to get [0..n-1]
  B             % convert from decimal to binary
   Ys           % cumulative sum (fills in 0's after first 1)
     z          % number of nonzero elements
      Q         % increment by 1 to account for zero
       G        % paste original input (n)
        /       % divide for the mean

Java, 135 95 90 bytes
float a(int n){int i=0,t=0;for(;i<n;)t+=Integer.toString(i++,2).length();return t/(n+0f);}

I think you can get rid of the interface and simply create a function or lambda. Also you can return the value instead of printing it to stdout

Okay, I'll re implement with those rules.

I think it should be allowed. As the OP didn't specify anything I think standard I/O rules apply.

Yes a function is fine - you don't need a complete program. Note that the leaderboard picks up the score on the first line, so your score currently shows as 135 instead of 95.

@trichoplax Still last place. I blame Java personally...

We can try to fix this. But the declaration and initialization of i behind the one of t. Also you can remove the { and } from the for loop

Oops, that was on my original answer but I had netbeans auto format it and it placed the braces automatically.

Check the other side of the leaderboard - yours is currently the top Java solution... :P

@trichoplax The only Java solution... aha

I know it's almost two years, but you can golf int to Integer and Integer.toString to i.toString to save 2 bytes, as well as return t/(n+0f); to return(t+0f)/n; to save an additional byte. Alternatively you could make it a Java 8 lambda with Integer parameter: n->{int i=0,t=0;for(;i<n;)t+=n.toString(i++,2).length();return(t+0f)/n;} (72 bytes) Try it online.

Jelly, 10 bytes
BL©2*2_÷+®

From Sp3000's suggestion.
Try it here.
Jelly, 11 bytes
æḟ2’Ḥ÷_BL$N

Not very short but I need some tips.
Try it here.
Using the same formula as in Sp3000's answer. (It's not very hard to get it yourself, by differentiating geometric progression.)

Look at my Jelly answer for your reference.

@LeakyNun It's using a different approach, which I don't think it would ever be shorter than yours. But the _BL$N seemed quite long...

So basically, your code is "floor to nearest power of 2, minus 1, double, divide by input, minus binary length of input, negative"?

@LeakyNun Yes..

I can't golf that further...

Only marginally better: BL©2*2_÷+®

Clojure, 71 64 63 bytes
It looks like ratios are ok according to Which number formats are acceptable in output?
(fn[n](/(inc(apply +(map #(.bitLength(bigint %))(range n))))n))

n=1 => 1
n=7 => 15/7

ungolfed (and slightly rewritten for ease of explanation)
(fn [n]
 (->
  (->>
   (range n)                      ;;Get numbers from 0 to N
   (map #(.bitLength (bigint %))) ;;Cast numbers to BigInt so bitLength can be used
   (apply +)                      ;;Sum the results of the mapping
   (inc))                         ;;Increment by 1 since bitLength of 0 is 0
  (/ n)))                         ;;Divide the sum by N

old answer that used (float):
(fn[n](float(/(inc(apply +(map #(..(bigint %)bitLength)(range n))))n)))
output is like:

n=1 => 1.0
n=7 => 2.142857

The question of whether fractions or ratios are acceptable hadn't been raised before. For this challenge I'll accept whatever consensus is reached on what the default should be.

05AB1E, 9 7 bytes
Code:
L<bJg¹/

Explanation:
L<         # range from 0..input-1
  b        # convert numbers to binary
   J       # join list of binary numbers into a string
    g      # get length of string (number of bits)
     ¹/    # divide by input

Try it online
Edit: saved 2 bytes thanks to @Adnan

Python 3, 46 Bytes
lambda x:sum(len(bin(i))-2for i in range(x))/x

Call it like
f = lambda x: sum(len(bin(i))-2for i in range(x))/x
print(f(6))
# 2.0

I had to revert the map revision because it failed for input of 5

J, 21 17 15 bytes
From 17 bytes to 15 bytes thanks to @Dennis.
+/@:%~#@#:"0@i.

Can anyone help me golf this?...
Ungolfed version
range        =: i.
length       =: #
binary       =: #:
sum          =: +/
divide       =: %
itself       =: ~
of           =: @
ofall        =: @:
binarylength =: length of binary "0
average      =: sum ofall divide itself
f            =: average binarylength of range

I tried an alternate approach, by stringifying the list of binary numerals, and came out with 25 bytes: %~>:@#@([:":10#.[:#:i.)-]. Your solution is looking rather optimal.

C#, 87 bytes
double f(int n){return Enumerable.Range(0,n).Average(i=>Convert.ToString(i,2).Length);}

I wrote a C# answer because I didn't see one. This is my first post to one of these, so please let me know if I'm doing anything wrong.

Welcome to Programming Puzzles and Code Golf. This is a great first answer, +1. Could you change double to float to save one byte, or do you need the precision?

@wizzwizz4 Thanks! I had the same thought, but Average() returns a double. If I change my return type to float then I have to explicitly cast the double and gain 7 bytes on that.

Vyxal r, 5 bytes
ʁbfL/

Try it Online!
ʁ     # 0...a
 b    # Turn each into base 2
  f   # Flatten
   L  # Get the length
    / # Divide by the input

Try it Online! for 4 bytes nowadays

JavaScript (ES7), 38 32 bytes
n=>(l=-~Math.log2(n))-(2**l-2)/n

Using @sp3000's formula (previous version was a recursive solution). ES6 version for 34 bytes:
n=>(l=-~Math.log2(n))-((1<<l)-2)/n

Explanation of formula: Consider the case of N=55. If we write the binary numbers (vertically to save space), we get:
                                11111111111111111111111
                111111111111111100000000000000001111111
        11111111000000001111111100000000111111110000000
    111100001111000011110000111100001111000011110000111
  11001100110011001100110011001100110011001100110011001
0101010101010101010101010101010101010101010101010101010

The size of this rectangle is nl so the average is just l but we need to exclude the blanks. Each row of blanks is twice as long as the previous so the total is 2 + 4 + 8 + 16 + 32 = 64 - 2 = 2l - 2.

Perl 6,  34  32 bytes

{$_ R/[+] map *.base(2).chars,^$_}

{$_ R/[+] map {(.msb||0)+1},^$_}

Explanation:
{
  $_  # the input
  R/  # divides ( ｢$a R/ $b｣ is the same as ｢$b / $a｣ )
  [+] # the sum of:
  map
    {
      (
       .msb # the most significant digit (0 based)
       || 0 # which returns Nil for ｢0.msb｣ so use 0 instead
            # should be ｢(.msb//0)｣ but the highlighting gets it wrong
            # it still works because it has the same end result
      )
      + 1   # make it 1 based
    },
    ^$_ # ｢0 ..^ $_｣ all the numbers up to the input, excluding the input
}

Test:
use v6.c;

# give it a name
my &mean-bits = {$_ R/[+] map {(.msb||0)+1},^$_}

for 1..7 {
  say .&mean-bits
}

say '';

say mean-bits(7).perl;
say mean-bits(7).base-repeating(10);

1
1
1.333333
1.5
1.8
2
2.142857

<15/7>
(2. 142857)

Dyalog APL, 14 bytes
(+/1⌈(⌈2⍟⍳))÷⊢

range ← ⍳
log   ← ⍟
log2  ← 2 log range
ceil  ← ⌈
bits  ← ceil log2
max   ← ⌈
fix0  ← 1 max bits
sum   ← +/
total ← sum fix0
self  ← ⊢
div   ← ÷
mean  ← sum div self

J, 15 bytes
%~[:+/#@#:"0@i.

This is a monadic verb, used as follows:
   f =: %~[:+/#@#:"0@i.
   f 7
2.14286

Try it here!
Explanation
I implemented the challenge spec pretty literally.
There are other approaches, but all turned out to be longer.
%~[:+/#@#:"0@i.  Input is y
             i.  Range from 0 to y-1.
          "0@    For each number in this range:
      #@           Compute the length of
        #:         its base-2 representation.
  [:+/           Take the sum of the lengths, and
%~               divide by y.

Actually, 7 bytes:
;r♂├Σl/

Try it online!
Explanation:
;r♂├Σl/
;        duplicate input
 r       push range(0, n) ([0, n-1])
  ♂├     map binary representation
    Σ    sum (concatenate strings)
     l/  divide length of string (total # of bits) by n

If it weren't for a bug that I just discovered, this solution would work for 6 bytes:
r♂├♂læ

æ is the builtin mean command.

Isn't this 10 bytes? I checked at bytesizematters.com.

@m654 Actually doesn't use UTF-8, it uses CP437 (or something like that).

@AlexA. Oh, didn't know that.

@m654 Bytesizematters uses a completely made up encoding that does not (and cannot) exist in practice. For UTF-8, use https://mothereff.in/byte-counter.

@Dennis Thanks for the info, I'll keep that in mind.

CJam, 13 12 11 bytes
One byte saved thanks to @Sp3000, and another thanks to @jimmy23013
rd_,2fbs,\/

Try it online!
Explanation
Straightforward. Applies the definition.
rd      e# read input and convert to double
_       e# duplicate
,       e# range from 0 to input minus 1
2fb     e# convert each element of the array to binary
s       e# convert to string. This flattens the array
,       e# length of array
\       e# swap
/       e# divide

Vitsy, 26 bytes
This is a first attempt, I'll golf this down more and add an explanation later.
0vVV1HV1-\[2L_1+v+v]v1+V/N
Try it online!

Perl 5.10, 54 bytes
for(1..<>){$u+=length sprintf"%b",$_;$n++}$u/=$n;say$u

Pretty much straightforward. sprintf"%b" is a neat way to output a number in binary in Perl without using additional libraries.
Try it online!

PowerShell v2+, 64 bytes
param($n)0..($n-1)|%{$o+=[convert]::ToString($_,2).Length};$o/$n

Very straightforward implementation of the spec. Loops from 0 to $n-1 with |%{...}. Each iteration, we [convert] our input number $_ to a string base2 and take its length. We accumulate that in $o. After the loops, we simply divide $o/$n, leaving that on the pipeline, and output is implicit.
As long as this is, it's actually shorter than the formula that Sp & others are using, since [math]::Ceiling() and [math]::Log() are ridiculously wordy. Base conversion in PowerShell is yucky.

Jolf, 10 bytes
/uΜr0xdlBH

Try it here!
Explanation
/uΜr0xdlBH
  Μr0x      map range 0..x
      dlBH  over lengths of binary elements
/u          divide sum of this
            by implicit input (x)

Swift, 72 bytes
func f(n:Double)->Double{return n<1 ?1:f(n-1)+1+floor(log2(n))}
f(N-1)/N

You don't need to call the function, leaving it as a defined function is okay. Nice first post.

Minkolang 0.15, 23 bytes
n$z1z[i1+2l$M$Y+]kz$:N.

Try it here!
Explanation
n$z                       Take number from input and store it in register (n)
   1                      Push 1 onto the stack
    z[                    For loop that repeats n times
      i1+                 Loop counter + 1
         2l$M             log_2
             $Y           Ceiling
               +          Add top two elements of stack
                ]         Close for loop
                 z$:      Float divide by n
                    N.    Output as number and stop.

Pretty straightfoward implementation.

JavaScript ES5, 55 bytes
n=>eval(`for(o=0,p=n;n--;o+=n.toString(2).length/p);o`)

Explanation
n =>   // anonymous function w/ arg `n`
  for( // loop
      o=0,  // initalize bit counter to zero
      p=n   // copy the input
    ;n-- // will decrease input every iteration, will decrease until it's zero
    ;o+=    // add to the bitcounter
        n.toString(2)  // the binary representation of the current itearations's
                     .length // length
        /p   // divided by input copy (to avergage)
   );o       // return o variable

Hoon, 71 bytes
|=
r/@
(^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq

...I'm pretty sure this is actually the first time I've used Hoon's floating point cores. It's actually an implementation written in Hoon that jets out to SoftFloat, since the only data types in Hoon are atoms and cells.
Create a function that takes an atom, r. Create a list from [0..(r - 1)], map over the list taking the binary logarithm of the number, then fold over that list with ++add. Convert both the output of the fold and r to @rq (quad-precision floating point numbers) with ++sun:rq, and then divide one by the other.
The oddest thing in this snippet is the :.^rq at the end. a:b in Hoon means "evaluate a in the context of b". ++rq is the core that contains the entire quad-precision implementation, like a library. So running (sun 5):rq is the same thing as doing (sun:rq 5).
Luckily, cores in Hoon are like nesting dolls; when you evaluate the arm ++rq to get the core, it adds the entire stdlib to it as well, so you get to keep roll and turn and gulf and all that fun stuff instead of being stuck with only the arms defined in ++rq. Unluckily, rq redefines ++add to be floating-point add instead, along with not having r in its context. . (the entire current context) does, however.
When evaluating an expression in a context, the compiler looks for the limb depth-first. In our case of a:[. rq] it would look in the entire current context for a before moving on to looking in rq. So add will look up the function that works on atoms instead of floating-point numbers...but so will div. Hoon also has a feature where using ^name will ignore the first found reference, and look for the second.
From there, it's simply using the syntatic sugar of a^b being equal to [a b] to evaluate our snippet with both our current context and the quad-precision float library, ignoring the atomic div in favor of ++div:rq.
> %.  7
  |=
  r/@
  (^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
.~~~2.1428571428571428571428571428571428

AWK, 59 bytes
{for(s=1;++n<$0;s+=int(log(n*2)/log(2)));printf"%.8g",s/$0}

Since AWK only does base-10 logs, I had to convert to base-2 and I chose to multiply the argument by 2 rather than add 1 to the result.  It's the same byte-count, but I like it. :)
Try it online!

Japt, 6 bytes
o¤xÊ/U

Try it

Explanation
           :Implicit input of integer U
o          :Range [0,U)
 ¤         :Convert each to a base-2 string
   Ê       :Get length of each
  x        :Reduce by addition
    /U     :Divide by U
           :Implicit output of result

K4, 16 bytes
Solution:
(1+#,/2\:'!x)%x:

Example:
(1+#,/2\:'!x)%x:5
1.8
(1+#,/2\:'!x)%x:6
2f
(1+#,/2\:'!x)%x:7
2.142857

Explanation:
Convert each number to binary, sum up the bits, add 1 for 0, divide by input.
(1+#,/2\:'!x)%x: / the solution
              x: / store input as x
(           )%   / divide left by right
          !x     / range 0..x-1
      2\:'       / convert each (') to bits (2\:)
    ,/           / flatten result
   #             / count length of list
 1+              / add one (as 0 contains 0 bits!)

Extra:
Precision is determined by the P system setting. Default is 7, max is 17
\P 7
(1+#,/2\:'!x)%x:7
2.142857

\P 12
(1+#,/2\:'!x)%x:7
2.14285714286

\P 17
(1+#,/2\:'!x)%x:7
2.1428571428571428

R, 51 bytes
Takes input from stdin. Uses the OEIS formula and then divides by n.
(2+ceiling(log2(n<-scan()))*n-2^ceiling(log2(n)))/n

Try it online!

Pyt, 8 bytes
⁻řļ⌊⁺Á1µ

Explanation:
                Implicit input (N)
⁻               Decrement by 1 (N-1)
 ř              Push [1,2,...,N-1]
  ļ             element-wise log base 2 of [1,2,...,N-1]
   ⌊⁺           element-wise floor and increment
     Á          Push contents of array onto stack
      1         Push 1
       µ        Get mean of stack
                Implicit output

Try it online!

Mathematica, 28 bytes
(Tr@⌈Log2@Range@#⌉+1)/#&

or
Tr@⌈Log2@Range@#⌉/#+1/#&

In either case, it's an unnamed function which takes N as an input and returns an exact (rational) result for the mean.

Pyke, 8 bytes
Qmb2slQ/

Try it here!

Haskell, 50 bytes
r x|x<1=0|1<2=1+r(x/2)
f n=(sum(r<$>[0..n-1])+1)/n

J, 22 bytes
[:(+/%#)[:([:##:)"0 i.
Usage:
    bin =: [:(+/%#)[:([:##:)"0 i.
    bin 7
2.14286

Ruby, 44 34 bytes
Now starring the formula used by @Sp3000
->x{(2.0-2**b=x.to_s(2).size)/x+b}

Old version:
->x{r=0.0;x.times{|i|r+=i.to_s(2).size};r/x}

PHP, 48 bytes
a direct port of Sp3000´s answer
<?=(2-2**$x=strlen(decbin($n=$argv[1]))-2)/$n+$x

Perl 5, 44 43 + 2 (-pa) = 45 bytes
-1 thanks to @DomHastings
$\+=(length sprintf'%b',$_)/"@F"while$_--}{

Try it online!

Good idea to add cumulatively... You can save 1 byte using "@F" instead of $F[0]!

Thunno 2, 4 bytes
Lḃḷm

Try it online!
Explanation
Lḃḷm  # Implicit input
L     # Push [0..input)
 ḃ    # Convert each to binary
  ḷ   # And get the length of each one
   m  # Take the average of the result
      # Implicit output


text:
Female and Male Sequences
This question is probably harder than all of those "generate a sequence of numbers" tasks, because this requires TWO sequences working in unison.
Really looking forward to the answers!
In his book "Gödel, Escher, Bach: An Eternal Golden Braid", Douglas Hofstadter has a quite few sequences of numbers inside, all of them rely on the previous term in some way. For information on all of the sequences, see this Wikipedia page.
One pair of sequences that's really interesting is the Female and Male sequences, which are defined like so:

for n > 0.
Here's the Female sequence and the Male sequence.
Your task is, when given an integer n as input, return a list of the Female sequence and the Male sequence, with the amount of terms equal to n, in two lines of output, with the Female sequence on the first line and the Male sequence on the second.
Sample inputs and outputs:
Input: 5
Output: [1, 1, 2, 2, 3] [0, 0, 1, 2, 2]
Input: 10
Output: [1, 1, 2, 2, 3, 3, 4, 5, 5, 6] [0, 0, 1, 2, 2, 3, 4, 4, 5, 6]
NOTE: The separation between lists signifies a line break.
This is code-golf, so shortest code in bytes wins. Also, put an explanation in as well for your code.
Leaderboard

var QUESTION_ID=80608,OVERRIDE_USER=49561;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Can we return a pair of lists from a function, instead of printing the lists?

Other challenges involving Hofstadter's sequences: Q sequence, figure-figure sequence

@Zgarb You can, as long as the two lists are in different lines.

@DerpfacePython There are no lines in a pair of lists; if a function returns a pair of lists, you can print them however you want. That being said, I'm not a huge fan of the lines requirement, even when printing the output. Cumbersome I/O formats are one of the things to avoid when writing challenges.

@Dennis But it's just a newline in the output - how hard can it really be? At most, it's around 5 bytes of code.

It's no big deal for some approaches/languages, but it can make a big difference for others. In C, a lot of bytes could be saved by printing the sequences in columns rather than rows. In Python, the shortest approach I can think of is a recursive lambda similar to my recursive Julia answer that returns a pair of lists, but having to convert that into a string with a linefeed makes it a lot longer, even longer than the full program posted by Sp3000. Other approaches, such as a recursive solution that counts down instead of up, are completely ruled out since it is impossible to add the newline.

Jelly, 22 20 bytes
ṙṪḢạL}ṭ
çƓḤ¤Ð¡1ṫ-Ṗ€G

Try it online!
How it works
çƓḤ¤Ð¡1ṫ-Ṗ€G  Main link. No user arguments. Left argument defaults to 0.
   ¤          Combine the two links to the left into a niladic chain.
 Ɠ              Read an integer from STDIN.
  Ḥ             Unhalve/double it.
ç   Ð¡1       Call the helper link that many times. Return all results.
              In the first call, the left and right argument are 0 and 1 resp.
              After each iteration, the left argument is set to the return value
              and the right argument to the prior value of the left one.
       ṫ-     Tail -1; keep the last two items of the list of results.
         Ṗ€   Discard the last item of each list.
           G  Grid; format the pair of lists.

ṙṪḢạL}ṭ       Helper link. Arguments: x, y (lists)

ṙ             Rotate x k units to the left, for each k in y.
 Ṫ            Tail; extract the last rotation.
  Ḣ           Head; extract the last element.
              This essentially computes x[y[-1]] (Python notation), avoiding
              Jelly's 1-based indexing.
    L}        Yield the length of y.
   ạ          Take the absolute difference of the results to both sides.
      ṭ       Tack; append the difference to y and return the result.

And this is the part where I feel proud of myself for making a challenge that makes Jelly use more than 10 bytes.

Julia, 52 48 bytes
x->[n÷φ|(5n^2|4∈(2:3n).^2)for| =(+,-),n=1:x]

Try it online!
Background
In On Hofstadter's married functions, the author shows that

where φ denotes the golden ratio,

and Fn denotes the nth Fibonacci number.
Furthermore, in Advanced Problems and Solutions, H-187: Fibonacci is a square, the proposer shows that

where Ln denotes the nth Lucas number, and that – conversely – if

then n is a Fibonacci number and m is a Lucas number.
From this, we deduce that

whenever n > 0.
How it works
Given input x, we construct a 2 by x matrix, where | is addition in the first column and subtraction in the second, and n iterates over the integers between 1 and x in the rows.
The first term of both F(n - 1) and M(n - 1) is simply n÷φ.
We compute δ(n) and ε(n) by calculating 5n² | 4 and testing if the result belongs to the array of squares of the integers between 2 and 3n. This tests both for squareness and, since 1 is not in the range, for n > 1 if | is subtraction.
Finally we add or subtract the Boolean resulting from 5n^2|4∈(2:3n).^2 to or from the previously computed integer.

can this be expressed in a non-recursive/iterative way ?, what is the closed form for it ?

I've added an explanation.

Python 2, 79 70 bytes
a=0,;b=1,
exec"a,b=b,a+(len(a)-b[a[-1]],);"*~-input()*2
print b,'\n',a

Iterative rather than recursive, because why not. The first line has a trailing space - if that's not okay it can be fixed for an extra byte. -9 bytes thanks to @Dennis.
Here are some combined lambdas which didn't really help:
f=lambda n,k:n and n-f(f(n-1,k),k^1)or k
f=lambda n,k:[k][n:]or f(n-1,k)+[n-f(f(n-1,k)[-1],k^1)[-1]]

Both take n and a parameter k either 0 or 1, specifying male/female. The first lambda returns the nth element, and the second lambda returns the first n elements (with exponential runtime).

MATL, 23 bytes
1Oiq:"@XJth"yy0)Q)_J+hw

Try it online!
Explanation
This works iteratively. Each sequence is kept in an array. For each index n the new term of each sequence is computed and attached to the corresponding array. A for loop with N−1 terms is used, where N is the input number.
The update for sequence M needs to be done first. This is because sequence F is always greater than or equal to sequence M for the same index, so if we tried to update F first we would need a term of M not computed yet.
The two update equations are the same interchanging F and M. Thus the code for the updating is reused by applying a for loop with two iterations and swapping the sequences in the stack.
1        % Push 1: seed for F sequence
O        % Push 0: seed for M sequence
iq:      % Input N. Generate range [1 2 ... N-1]
"        % For each (i.e. iterate N-1 times)
  @      %   Push current index, n (starting at 1 and ending at N-1)
  XJ     %   Copy to clipboard J
  th     %   Duplicate and concatenate. This generates a length-2 array
  "      %   For each (i.e. iterate twice)
    yy   %   Duplicate top two elements, i.e. F and M sequences
    0)   %     In the *first* iteration: get last entry of M, i.e M(n-1)
    Q)   %     Add 1 and index into F. This is F(M(n-1))
    _J+  %     Negate and add n. This is n-F(M(n-1)), that is, M(n)
    h    %     Concatenate to update M
    w    %     Swap top two elements, to bring F to top.
         %     In the *second* iteration the procedure is repeated to update F,
         %     and then the top two elements are swapped to bring M to top again,
         %     ready for the next iteration of the outer loop
         %   End for implicitly
         % End for implicitly
         % Display implicitly from bottom to top: first line is F, second is M

J, 47 bytes
f=:1:`(-m@f@<:)@.*
m=:0:`(-f@m@<:)@.*
(f,:m)@i.

Uses the recursive definition. The first two lines define the verbs f and m which represent the female and male functions, respectively. The last line is a verb that takes a single argument n and outputs the first n terms of the female and male sequences.
Usage
   (f,:m)@i. 5
1 1 2 2 3
0 0 1 2 2
   (f,:m)@i. 10
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6

JavaScript (ES6), 75 bytes
g=n=>--n?([f,m]=g(n),m=[...m,n-f[m[n-1]]],[[...f,n-m[f[n-1]]],m]):[[1],[[0]]

I could save 2 bytes if I was allowed to return the Male sequence first:
g=n=>--n?([f,m]=g(n),[m=[...m,n-f[m[n-1]]],[...f,n-m[f[n-1]]]]):[[1],[[0]]

Haskell, 57 bytes
l#s=scanl(\a b->b-l!!a)s[1..]
v=w#1
w=v#0
(<$>[v,w]).take

Usage example: (<$>[v,w]).take $ 5 -> [[1,1,2,2,3],[0,0,1,2,2]]
The helper function # builds an infinite list with starting value s and a list l for looking up all further elements (at index of the previous value). v = w#1 is the female and w = v#0 the male sequence. In the main function we take the first n elements of both v and w.

Python 2, 107 bytes
F=lambda n:n and n-M(F(n-1))or 1
M=lambda n:n and n-F(M(n-1))
n=range(input())
print map(F,n),'\n',map(M,n)

Try it online
Larger input values cause a RuntimeError (too much recursion). If this is a problem, I can write a version where the error doesn't happen.

Clojure, 132 131 bytes
(fn [n](loop[N 1 M[0]F[1]](if(< N n)(let[M(conj M(- N(F(peek M))))F(conj F(- N(M(peek F))))](recur(inc N)M F))(do(prn F)(prn M)))))

Simply builds the sequences iteratively up from zero to n.
Ungolfed version
(fn [n]
  (loop [N 1 M [0] F [1]]
    (if (< N n)
      (let [M (conj M (- N (F (peek M))))
            F (conj F (- N (M (peek F))))]
        (recur (inc N) M F))
      (do
        (prn F)
        (prn M)))))

Nice answer, welcome to the site! Is a trailing space or newline necessary? I'm counting 131 + a trailing whitespace.

No, there's no need for a trailing whitespace. Sneaky vim added a newline at the end for wc to count.

Julia, 54 bytes
f(n,x=1,y=0)=n>1?f(n-.5,[y;-x[y[k=end]+1]+k],x):[x y]'

Try it online!

Pyth, 23 bytes
jCuaG-LHtPs@LGeGr1Q],1Z

Try it online: Demonstration
Explanation:
jCuaG-LHtPs@LGeGr1Q],1Z

  u                ],1Z    start with G = [[1, 0]]
                           (this will be the list of F-M pairs)
  u             r1Q        for each H in [1, 2, ..., Q-1]:
              eG              take the last pair of G [F(H-1), M(H-1)]
           @LG                lookup the pairs of these values:
                              [[F(F(H-1)), M(F(H-1))], [F(M(H-1)), M(M(H-1))]]
          s                   join them:
                              [F(F(H-1)), M(F(H-1)), F(M(H-1)), M(M(H-1))]
        tP                    get rid of the first and last element:
                              [M(F(H-1)), F(M(H-1))]
     -LH                      subtract these values from H
                              [H - M(F(H-1)), H - F(M(H-1))]
   aG                         and append this new pair to G
jC                         at the end: zip G and print each list on a line

Alternative solution that uses a function instead of reduce (also 23 bytes):
L?>b1-LbtPsyMytb,1ZjCyM

Nice. Very nice indeed.

Pyth, 24 bytes
It is probably impossible to use reduce to reduce the byte-count.
Straightforward implementation.
L&b-b'ytbL?b-by'tb1'MQyM

Try it online!
How it works
L&b-b'ytb  defines a function y, which is actually the male sequence.

L          def male(b):
 &b            if not b: return b
   -b          else: return b-
     'ytb            female(male(b-1))

L?b-by'tb1 defines a function ', which is actually the female sequence.

L          def female(b):
 ?b            if b:
   -by'tb          return b-male(female(b-1))
         1     else: return 1

'MQ        print(female(i) for i from 0 to input)
yMQ        print(male(i) for i from 0 to input)

Do I include the anagrammatized name or your original name in the leaderboard? Also, this code is awfully long for a Pyth program.

How long have you been here... how come you know that I changed my name? Put my new name there.

I've been here long enough to know that you changed your name.

@DerpfacePython Seeing that other answers are almost 4 times as long... I'd say my solution is not very long.

That's very true, but it's still long compared to other Pyth programs for other questions.

That's because this is a complicated recursion...

Let us continue this discussion in chat.

Challenge accepted: http://codegolf.stackexchange.com/a/80722/29577

Brachylog, 65 bytes
:{:1-:0re.}fL:2aw,@Nw,L:3aw
0,1.|:1-:2&:3&:?--.
0.|:1-:3&:2&:?--.

My attempt at combining both predicates for male and female into one actually made the code longer.
You could use the following one liner which has the same number of bytes:
:{:1-:0re.}fL:{0,1.|:1-:2&:3&:?--.}aw,@Nw,L:{0.|:1-:3&:2&:?--.}aw

Note: This works with the Prolog transpiler, not the old Java one.
Explanation
Main predicate:
:{:1-:0re.}fL                Build a list L of integers from 0 to Input - 1
             :2aw            Apply predicate 2 to each element of L, write the resulting list
                 ,@Nw        Write a line break
                     ,L:3aw  Apply predicate 3 to each element of L, write the resulting list

Predicate 2 (female):
0,1.                         If Input = 0, unify Output with 1
    |                        Else
     :1-                     Subtract 1 from Input
        :2&                  Call predicate 2 with Input - 1 as argument
           :3&               Call predicate 3 with the Output of the previous predicate 2
              :?-            Subtract Input from the Output of the previous predicate 3
                 -.          Unify the Output with the opposite of the subtraction

Predicate 3 (male):
0.                           If Input = 0, unify Output with 0
  |                          Else
   :1-                       Subtract 1 from Input
      :3&                    Call predicate 3 with Input - 1 as argument
         :2&                 Call predicate 2 with the Output of the previous predicate 3
            :?-              Subtract Input from the Output of the previous predicate 3
               -.            Unify the Output with the opposite of the subtraction

Wait... which one's predicate 3?

@DerpfacePython whoops, fixed. Also note that predicate one is {:1-:0re.}, used to create the range list.

Ruby, 104 92 97 82 bytes
f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}

Edit: f and m are now one function thanks to HopefullyHelpful. I changed the second function to print f then m. The whitespace after p is significant, as otherwise the function prints (0...n) instead of the result of map.
The third function prints first an array of the first n terms of f, followed by an array of the first n terms of m
These functions are called like this:
> f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
> s=->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}
> s[10]
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6]
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6]

you can drop the p and parens.  Output is not required to be printed.  Also, you can dorp parens around the range.

you can replace the 2 function with 1 that has 2 arguments n and i n>0?n-f(f(n-1,i),-i):i>0?1:0

@HopefullyHelpful Thanks a bunch :D

@NotthatCharles Is the output not required to be printed? In Ruby, if I want that line break between f and m, I need to print it. Otherwise, I just get an array like [[1, 1, 2, 2, 3, 3, 4, 5, 5, 6], [0, 0, 1, 2, 2, 3, 4, 4, 5, 6]]

oh, it does say "line break".  Too bad.

APL (Dyalog Unicode), 45 25 bytes
Anonymous tacit function. Requires ⎕IO←0, which is standard on many APL systems.
1 0∘.{×⍵:⍵-(~⍺)∇⍺∇⍵-1⋄⍺}⍳

Try it online!
This works by combining F and M into a single dyadic function with a Boolean left argument which selects the function to apply. We use 1 for F and 0 for M so that we can use this selector as return value for F (0) and M (0). We then observe that both functions need to call themselves first (on the argument minus one) and then the other function on the result of that, so first we recurse with the given selector and then with the logically negated selector.
⍳ ɩndices; zero through argument minus one
1 0∘.{…} outer (Cartesian) "product" (but with the below function instead of multiplication) using [1,0] as left arguments (⍺) and the indices as right arguments (⍵):
 ×⍵ if the right argument is strictly positive (lit. the sign of the right argument):
  ⍵-1 subtract one from the right argument
  ⍺∇ call self with that as right argument and the left argument as left argument
  (~⍺)∇ call self with that as right arg and the logical negation of the left arg as left arg
  ⍵- subtract that from the right argument and return the result
 ⋄ else:
  ⍺ return the left argument

That works well, but assuming input is stored in a variable is disallowed by default.

@Dennis It doesn't really. It is a tfn body. When I was new here, ngn told me I didn't have to count the tfn header (which would be two bytes, a single-char name + a newline, just like the source filename isn't counted, and anonymous fns are allowed. So too here, where the header is a 1-char name + space + a 1-char argument name (n) + plus a newline.

What exactly is a tfn?

@Dennis Tfns are the traditional APL representation of functions. Consist of lines of code with almost none of the dfns's restrictions. E.g you can have proper control structures, and expressions with no result. Line "0" is a header which indicates the fn's syntax.

Perl 5.10, 85 80 bytes
Meh, dunno if I have more ideas to golf this down...
@a=1;@b=0;for(1..<>-1){push@a,$_-$b[$a[$_-1]];push@b,$_-$a[$b[$_-1]]}say"@a\n@b"

Try it online !
I had to add use 5.10.0 on Ideone in order for it to accept the say function, but it doesn't count towards the byte count.
It's a naive implementation of the algorithm, @a being the "female" list and @b the "male" list.
Crossed-out 85 is still 85 ?

Explanation, please?

Pretty much the same as my JS answer

@DerpfacePython It's a naive implementation actually. :)

I haven't tested, but I don't think you should need the parentheses around each pushed term, nor the final semicolon before the close-brace.

@msh210 Indeed, forgot about this. Saves 5 bytes in total, thanks!

ES6, 89 85 83 bytes
2 bytes saved thanks to @Bálint
x=>{F=[n=1],M=[0];while(n<x){M.push(n-F[M[n-1]]);F.push(n-M[F[n++-1]])}return[F,M]}

Naïve implementation.
Explanation:
x => {
    F = [n = 1], //female and term number
    M = [0]; //male
    while (n < x) {
        M.push(n - F[M[n - 1]]); //naïve
        F.push(n - M[F[n++ - 1]]); //post-decrement means n++ acts as n in the calculation
    }
    return [F, M];
}

I think you can make it an anonymus function, and replace the &&-s with &

You can't, && short-circuits, which is wanted, but I removed it anyway because brace syntax is equally short anyway

Then you could do`F=[n=1]

Mathematica, 69 62 bytes
Thanks to Sp3000 for suggesting a functional form which saved 14 bytes.
k_~f~0=1-k
k_~f~n_:=n-f[1-k,f[k,n-1]]
Print/@Array[f,{2,#},0]&

This defines a named helper function f and then evaluates to an unnamed function which solves the actual task of printing both sequences.

Java, 169 bytes total
int f(int n,int i){return n>0?n-f(f(n-1,i),-i):i>0?1:0;}void p(int n,int i){if(n>0)p(n-1,i);System.out.print(i==0?"\n":f(n,i)+" ");}void p(int n){p(n,1);p(0,0);p(n,-1);}

F(), M() 56 bytes
int f(int n,int i){
    return n>0?n-f(f(n-1,i),-i):i>0?1:0;
}

recursive-for-loop and printing 77 Bytes
void p(int n,int i) {
    if(n>0) {
        p(n-1,i);
    }
    System.out.print(i==0?"\n":f(n,i)+" ");
}

outputting the lists in two different lines 37 Bytes
void p(int n) {
    p(n,1);
    p(0,0);
    p(n,-1);
}

input : p(10)
output :
1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9

C, 166 Bytes
#define P printf
#define L for(i=0;i<a;i++)
f(x);m(x);i;c(a){L P("%d ",f(i));P("\n");L P("%d ",m(i));}f(x){return x==0?1:x-m(f(x-1));}m(x){return x==0?0:x-f(m(x-1));}

Usage:
main()
{
    c(10);
}

Output:
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6

Ungolfed (331 Bytes)
#include <stdio.h>

int female(int x);
int male(int x);
int i;
int count(a){
    for(i=0;i<a;i++){
        printf("%d ",female(i));
    }
    printf("\n");
    for(i=0;i 5 FM
1 1 2 2 3
0 0 1 2 2

ok> 10 FM
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6

Explanation
This code uses recursion and deferred word
defer: M - The word M is declared to be defined later. This is a deferred word
: F dup not if 1 nip else dup n:1- recurse M n:- then ; - Define F recursively to generate female numbers according definition. Please note that M has not yet been defined
( dup not if 0 nip else dup n:1- recurse F n:- then ) is M - Define M recursively to generate male numbers according definition
: FM n:1- dup ( F . space ) 0 rot loop cr ( M . space ) 0 rot loop cr ; - Word used to print sequences of female and male numbers

source: Stack Exchange

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

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

sort: votes


text:
Separate alphabets and numbers
A paragraph of text has numbers and alphabetic letters mixed. Your task is to separate the numbers to the left side and the alphabetic letters to the right side in the same order of each line.
Rules:

Numbers are plain integers; so no decimal point, and no negative/positive signs.
Numbers may or may not be contiguous, but whatever the case may be, they have to be pushed to left side in the same order.
Numbers may occur in between words.
The text contains only ASCII alphabetic letters and numbers, along with spaces, underscores, commas and dots.
The one who does this with minimum keystrokes (like vim macros) or least amount of bytes in case of scripting is the winner.

Example Text:
A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

Expected output:
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

"all the numbers has to be moved left side but numerical values has to be pasted o right side" ?!?!?!

numbers to leftside and alphabets to right side in each line? Please post a couple of test cases complete with output and including several lines. Also, by numbers do you mean digits or sets of contiguous digits considered as a unit? In the latter case, can the number contain minus sign, decimal point, exponential notation? Voting to close as unclear. I'll remove my vote when clarified

I will update it. I am new here :)

@SibiCoder Welcome aboard then! You might want to use the sandbox next time. It's used for posting challenges before doing it here. That way you can get feedback from other users and improve the challenge

In the first output line there is a space missing before the last comma. Also, you should include commas in spec, item 4)

Using alphabet to mean letter is, I believe, a distinctive of Indian English.

Sorry if this is obvious but I am new here. Does this need to be a function or a program?

@AstroDan Both are allowed by default.

@AstroDan Welcome to the site! I hope you have a lot of fun here. :)

Seems pretty clear now.  @close-voters - do you think you can retract your votes now?

@DigitalTrauma, I think the test cases contradict the spec, which requires the alphabetic letters to be moved to the end of the line. The four (out of five) test cases which have punctuation don't respect that requirement.

@PeterTaylor I would say Rule #2 (and the absence of other rules in the same template) clarifies this over what the introductory paragraph says.  But perhaps I'm over-relying on the absence of other rules bit.

What happened to the space after like in the first line of the example?

@PeterTaylor Couldn't we just edit the test cases? It's pretty obvious where they're unclear.

Fixed the first test case, since it was most likely nothing more than a typo. I am voting to reopen this post.

Retina, 14 bytes
O%$`\d|(.)
$#1

Try it online!
Explanation
O introduces a sorting stage. % tells Retina to apply the transformation to each line separately. $ tells it to sort the matches by the result of the specified substitution.
The regex itself is \d|(.) which either matches a digit, or anything else which is captured into group 1. This is substituted with $#1 which is the number of captures of group 1. That is, the sorting key for digits is 0 and the sorting key for everything else is 1. Since sorting in Retina is stable, this simply moves digits to the left and everything else to the right.

05AB1E, 14 10 bytes
Code:
|vyþyyþ-¶J

Explanation:
|                 # push all lines in input as array of strings
 v                # for each line in array
  yþ              # push only digits from line
    yyþ-          # push line without digits
        ¶         # push newline char
         J        # join as string
                  # end loop and print explicitly

Example Input:

A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless words co43mbined togeth81er.

Example Output:

433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
4381meaningless words combined together.

Try it online

Python 3, 64 bytes
Three equivalent solutions! I can’t pick.
while 1:print(*sorted(input(),key=lambda x:-x.isdigit()),sep='')
while 1:print(*sorted(input(),key=lambda x:x<'0'or'9'<x),sep='')
while 1:print(*sorted(input(),key=str.isdigit,reverse=1),sep='')

Another variant of the same length: while 1:print(*sorted(input(),key=lambda x:-('/'<x<':')),sep='')

Perl, 17 bytes
16 bytes code + 1 switch
s/\d/!print$&/ge

Requires -p.
Usage
perl -pe 's/\d/!print$&/ge' <<< 'a1b2c3d4e5f6'
123456abcdef

Alternatively:
print/\d/g,/\D/g

Requires -n.
Usage
perl -ne 'print/\d/g,/\D/g' <<< 'a1b2c3d4e5f6'
123456abcdef

It's cool to see a non-golfing language be competitive, even against golfing languages.

@DrGreenEggsandHamDJ I'm glad you liked it! I don't add many answers but I quite liked the solution of this one! Also I'm sure some people would classify Perl as a golfing language, since its described as write only!

Hoon, 92 83 bytes
|*
*
(turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))

++lore splits a multi-line cord into a (list cord), (trip +<) turns it into a tape. ++skid seperates a list in two: one side where the function returns yes, one side where it returns no. Our function tries to parse the character with ++nud (numeric) and checks if it parses fully, and then we weld the two lists back together into a tape.
> %.
  '''
  A word can have any number of text like 433884,
  but all the numb89ers has to be moved left side
  but alph6abetical va9lues has to be pas46ted on right side.
  The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
  meaningless1 words co43mbined togeth81er.
  '''
  |*
  *
  (turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))
<<
  "433884A word can have any number of text like ,"
  "89but all the numbers has to be moved left side "
  "6946but alphabetical values has to be pasted on right side."
  "4292The text might contain characters shuffled like hlep or dfeintino or even"
  "14381meaningless words combined together."
>>

God, I will never not upvote Hoon. ♥

MATL, 13 12 bytes
`jt4Y2m&)hDT

Exits with an error (allowed by default), producing the correct output.
Try it online!
Explanation
`          T    % infinite loop
 j              % input one line as a string
  t             % duplicate
   4Y2          % predefined literal: '0123456789'
      m         % true for elements of string that are digits, false for the rest
       &)       % two-output indexing: push digits, then non-digits
         h      % concatenate the two strings
          D     % display

V, 12 bytes
òí¨Ä©¨ä©/²±

V, is an unfinished, 2D string based golfing language. Although it is unfinished, this program works as of commit 45, which was published last night, making this a competing answer. (Most of my previous V answers were non-competing.)
Note, the trailing newline is necessary, although this is due to a bug.
Try it online!
Explanation:
ò            #Recursively, do:
 í           #Substitute on every line
  ¨Ä©¨ä©/²±  #The following regex.

¨Ä©¨ä©/²± expands into the vim regex:
:%s/\(\D\)\(\d\)/\2\1

which is a non-digit (\D) followed by a digit (\d), and swap them.
Since this is filled with gross unicode characters, here is a reversible hexdump:
00000000: f2ed a8c4 a9a8 e4a9 2fb2 b10a            ......../...

I'm really proud of this answer. With some more work on the language, this could easily be 4-5 bytes shorter, but it's cool to see the features I've been working on actually be useful. This would not have worked a day ago. =D

CJam, 9 13 16 bytes
qN/{{A,s-,}$}%N*

There isn't f$...
This 13 bytes version nearly works:
{l{A,s-,}$N}h

Pyth, 16 15 bytes
1 byte thanks to @FryAmTheEggman.
jms+@J`MTd-dJ.z

Try it online!
Sample input:
A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

Sample output:
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

How it works
jms+@J`MTd-dJ.z

 m           .z    for each line (d):
         d           yield d (the line)
     J                 assign J to
        T              [0,1,2,3,...,9]
      `M               with each number converted to string
    @                intersect with J
   +                 append:
          -dJ          filter d for characters not in J
  s                  convert to one string
j                  join by newline

You don't need the U because maps automatically cast integers to ranges.

Oh, thanks for reminding!

Javascript ES6, 40 bytes
a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')
Tried several other solutions, but couldn't get it smaller than this.
My first try was a=>[...a.match(/\d/g),...a.match(/\D/g)].join`` but that's 5 bytes longer
Try it here

f=
a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

a.innerHTML='
'+
  ['A word can have any number of text like 433884,',
 'but all the numb89ers has to be moved left side',
 'but alph6abetical va9lues has to be pas46ted on right side.',
 'The text might con4tain chara29cters s2huffled like hlep or dfeintino or even',
 'meaningless words co43mbined togeth81er.'].map(b=>f(b)).join('
')+'
'

PowerShell v2+, 55 bytes
$args[0]-split"`n"|%{($_-replace'\D')+($_-replace'\d')}

Due to the need to support multi-line input, we have to encapsulate our -replace statements with a loop and -split on newlines. Otherwise basically equivalent to the JavaScript solution.

Pyth - 11 bytes
Don't like my grouping test. Takes input as list of lines, tell me if that's not ok.
jms_.g}k`MT

Try it online here.

Factor 61
[ "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ]

It's a naive approach.
"\n"split splits the string on top of the stack into lines. Then, for each line:

[ digit? ] partition splits each line into digits-only and non-digits-only
[ write ] bi@ outputs both, and nl prints a newline.

PS:
As a word 90 bytes (71 if you replace the-factorish-long-name with 1 letter):
: numbers-to-the-front ( s -- ) "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ;

Pyth, 14 bytes
FG.zo_:N"\d"0G

Try it online!
Explanation:
FG             : For every G in ...
  .z           : the-list-where-lines-of-input-are-stored ...
               : (implicitly print)
    o        G : sorted G ...
     _N        : where, a negative key is given ...
       :"\d"0  : to the individual character if it is a digit

The logic of the solution is the same as in Lynn's answer.

Retina, 16 bytes
Stable bubble sort.
%+`(\D)(\d)
$2$1

Sample input:
A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

Sample output:
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

Try it online!

Please update your code. Numbers may come in between words. If yours is updated, then its fine.

Java 8, 130 126 86 bytes
a->{for(String s:a)System.out.println(s.replaceAll("\\D","")+s.replaceAll("\\d",""));}

-4 bytes converting Java 7 to 8 and removing an unused character
-40 bytes converting program to function and changing [^\\d] to \\D
Explanation:
Try it here.
a->{                             // Method with String-array parameter and no return-type
  for(String s:a)                //  Loop over the array
    System.out.println(          //   Print with a trailing new-line:
      s.replaceAll("\\D","")     //    All digits,
      +s.replaceAll("\\d",""));  //    plus all non-digits

C#, 59 bytes
I=>Regex.Replace(I,"[^0-9]","")+Regex.Replace(I,@"\d+","");

A simple C# lambda function using regex.
Sample output
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

GNU Sed, 28
Score includes +1 for -r option to sed.
:
s/([^0-9])([0-9])/\2\1/
t

Repeatedly switches one non-number character followed by one number character until no more substitutions are made.
Sadly sed regexes don't have \d or \D, so these have to be written out longhand.
Ideone.

C# (LINQ), 110 bytes
s=>string.join("",s.Where(c=>"0123456789".Contains(c).Concat(s.SelectMany(c=>new[]{c}.Except("0123456789"))));

Not the shortest solution, by far, but I thought this would be a good use of LINQ.

Similar but slightly shorter : string.Join("", s.Where(c => char.IsDigit(c)).Concat(s.Where(c => !char.IsDigit(c))));

@Marc wow, I've been using this language for 5 years and I didn't know char.IsDigit existed...

Oracle SQL 11.2, 131 bytes
The lines in the input string are separated by '¤'.
That way it is not necessary to create a table to use as the input.
A word can have any number of text like 433884,¤but all the numb89ers has to be moved left side ¤but alph6abetical va9lues has to be pas46ted on right side.¤The text might con4tain chara29cters s2huffled like hlep or dfeintino or even¤meaningless1 words co43mbined togeth81er.

Query :
SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')||REGEXP_REPLACE(COLUMN_VALUE,'[0-9]')FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'));

Un-golfed
SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')||  -- Every number
       REGEXP_REPLACE(COLUMN_VALUE,'[0-9]')     -- Every character not a number
FROM   XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))  -- Split on ¤

Octave, 37 32 bytes
@(s)disp([s(x=s>47&s<58),s(~x)])

ans('The text might con4tain chara29cters s2huffled like hlep or dfeintino or even')
4292The text might contain characters shuffled like hlep or dfeintino or even

Input can be multiline; see (updated) challenge

Clojure, 113 bytes
(fn[s](map(fn[x](println(apply str(sort-by #(when-not(Character/isDigit %)1)x))))(clojure.string/split-lines s)))

Sorts digits to the beginning of the line.

APL, 28 chars
{⍵[⍋(~⍵∊⎕D)++\¯1⌽⍵=⎕UCS 13]}

Haskell, 60 bytes
import Data.List;g(n,l)=n++l;f=g.partition(`elem`['0'..'9'])

Usage
f "A word can have any number of text like 433884,"

Sed, 35 bytes
h
s/[0-9]//g
x
s/[^0-9]//g
G
s/\n//

This makes a copy of the line, removes digits from one copy and letters from the other, before recombining them.

Bash, 42 bytes
read a&&echo "${a//[^0-9]}${a//[0-9]}"&&$0

Be warned that this recursive implementation forks a new process for each line of input!

Japt v2, 14 12 bytes
-2 bytes thanks to ETHproductions
®o\d +Zr\d}R

Run it

Julia 0.6, 77 bytes
x->(l=r="";for c=x
c=='\n'?(println(l*r);l=r=""):'/'<c<':'?(l*=c):(r*=c)
end)

Anonymous function taking a string and printing output. Loops over characters, adding them to the left l or right r buffers until it finds a newline, then it prints and empties buffers. Lots of potential useful constructs like sort, filter and logical indexing (indexing with an array of boolean values) don't work on Strings.
Try it online!

Vim, 30 keystrokes
qr:%s/\v(\D+)(\d+)/\2\1/<Enter>@rq@r

Record a search and replace action that moves digits to the left of non-digits. Call the macro recursively until an exception is thrown by the pattern not being found (when there are no more digits to the right of any non-digits).

C (gcc), 106 bytes
g(s,x)char*s;{for(;*s;s++)isdigit(*s)^x&&putchar(*s);}f(s,n)char**s;{for(;n--;puts(""))g(*s,0),g(*s++,1);}

Try it online!

Jelly, 10 bytes
Ỵðf;ḟµ€ØDY

Try it online!

K4, 21 bytes
Solution:
{x(&a),&~a:x in .Q.n}

Example:
q)k){x(&a),&~a:x in .Q.n}"The text might con4tain chara29cters s2huffled like hlep or dfeintino or even"
"4292The text might contain characters shuffled like hlep or dfeintino or even"

Explanation:
{x(&a),&~a:x in .Q.n} / the solution
{                   } / lambda function, implicit arg x
                .Q.n  / list "0123456789"
           x in       / true/false for each character of x
         a:           / save as variable a
        ~             / negate (so non numerics)
       &              / indices where true
      ,               / joined with
  (&a)                / indices where true
 x                    / index into x at these indices

Bonus:
23 byte implementation in K (oK):
{x(&a),&~a:x in 48+!10}

Try it online!

ReRegex, 25 bytes
([^\n\d])(\d)/$2$1/#input

Try it online!

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


text:
Convert ASCII box drawing into Unicode
I am shamelessly posting a request for something I would actually find useful.  The task is to take an arbitrary ascii box drawing like this
     |
+----+----+
| state A +---+
+---------+   |
              |
         +----v----+
         | state B |
         +---------+

... and turn it into something more beautiful using unicode box drawing characters, e.g.
     │
╭────┴────╮
│ state A ├───╮
╰─────────╯   │
              │
         ╭────v────╮
         │ state B │
         ╰─────────╯

In more detail:

convert only + - | characters - other characters should be unchanged
use

BOX DRAWINGS LIGHT VERTICAL (U+2502) │
BOX DRAWINGS LIGHT HORIZONTAL (U+2500) ─
BOX DRAWINGS LIGHT ARC DOWN AND RIGHT (U+256D) ╭
BOX DRAWINGS LIGHT ARC DOWN AND LEFT (U+256E) ╮
BOX DRAWINGS LIGHT ARC UP AND LEFT (U+256F) ╯
BOX DRAWINGS LIGHT ARC UP AND RIGHT (U+2570) ╰
BOX DRAWINGS LIGHT VERTICAL AND LEFT (U+2524) ┤
BOX DRAWINGS LIGHT VERTICAL AND RIGHT (U+251C) ├
BOX DRAWINGS LIGHT DOWN AND HORIZONTAL (U+252C) ┬
BOX DRAWINGS LIGHT UP AND HORIZONTAL (U+2534) ┴
BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL (U+253C) ┼
- always replaced with U+2500
| always replaced with U+2502
+ is replaced with a unicode character that depends on the 4 characters north, south, east and west of it (if they exist)
< and > are treated as vertical wall segments if north or south of a + (so that you can have arrows terminating in vertical walls of a box)
v and ^ are treated as horizontal wall segments if east or west of a + (so that you can have arrows terminating in horizontal walls of a box)
+ is treated as a wall segment if either north, south, east or west of a + (so that lines can connect next to a box corner)

Testcases
+-+     +---+   +---+   |
| +--   |ABC|  -+   |  +++
+-+     ++--+   +---+  +-+
         |
         +--->
  |           +--+
+-v+   +---+  |  |  +-----+
|Hi|  ->   |  +^-+  |world<-----+
+--+   +---+   |    +-----+     |
               |                +--
   |
---+---
   |

Becomes
╭─╮     ╭───╮   ╭───╮   │
│ ├──   │ABC│  ─┤   │  ╭┴╮
╰─╯     ╰┬──╯   ╰───╯  ╰─╯
         │
         ╰───>
  │           ╭──╮
╭─v╮   ╭───╮  │  │  ╭─────╮
│Hi│  ─>   │  ╰^─╯  │world<─────╮
╰──╯   ╰───╯   │    ╰─────╯     │
               │                ╰──
   │
───┼───
   │

Shortest code wins!

Where is the "intersection", i.e. if the + has lines around it everywhere?

You probably mean Unicode rather than UTF-8

Could we have some test cases? Particularly for edge cases like where two boxes touch at an edge or corner (or clarification that this will never happen).

@LeakyNun I don't think the intersection should ever be needed.  Box walls always terminate lines (which will end in one of +,<,>,^,v if they hit a box wall, otherwise they end in |,-).  Lines don't enter boxes.  Lines don't cross.

Would be nice to post the required outputs for those test cases.

Will boxes ever touch at an edge, e.g. could there ever be pluses in a 'T' shape all touching? Also, there are no test cases that have boxes with a height > 3 or with any other arrow directions.

Can the output have additional spaces at the end of each line?

Ugh, I was just composing an answer :-(

Thanks for all the comments everyone.  This is my first golfing expedition so I'm just getting used to the rules!  PS:  I do now have a code of my own for this which I can post as a reference design if that is a proper thing to do.

@Loovjo No, sorry.

JavaScript (ES6), 236 bytes
s=>`
${s}
`.split`
`.map((l,i,a)=>l.replace(/[+-|]/g,(c,j)=>c>`-`?`│`:c>`+`?`─`:`┼┬├╭┤╮??┴?╰?╯`[g(a[i-1][j])+g(l[j-1],1)*2+g(l[j+1],1)*4+g(a[i+1][j])*8]),g=(c,f)=>(f?`+-^v`:`+<>|`).indexOf(c)<0).slice(1,-1).join`
`


text:
Parse a 1D language
Given a string containing only 0's 1's, 2's and brackets, output the grammar tree of the string.
A 2 requires 2 arguments - one to the left and one to the right
A 1 requires a single argument - to either the left or right
A 0 doesn't require any arguments and is the base case
A pair of brackets counts as one argument and the contents of the brackets are evaluated separately from the rest of the string. Nested brackets are possible
A input string will always be a complete tree with no characters falling off. The string will also only have a single correct solution. Note that the functions are commutative and any arrangement of arguments for 2 will be acceptable. You will not have to handle input that doesn't conform to these requirements.
The output grammar format will be in the form function(arguments) recursively
Test cases
0 --> 0
01 --> 1(0)
020 --> 2(0,0)
101 --> 1(1(0))
0120 --> 2(1(0),0)
0120210 --> 2(1(0),2(0,1(0)))
01210 --> 2(1(0),1(0))
(020)210 --> 2(2(0,0),1(0))
((020)20)1 --> 1(2(0,2(0,0)))

Is 10201 valid input?

No, it could be 1(2(0,1(0))) or 2(1(0),1(0))

Actually I was thinking it was 1(2(1(0),0)) ;-)

I still don't see why 0120210 can't also be parsed as 2[4](2[2](1[1](0[0]), 0[3]), 1[5](0[6])) where the bracketed numbers indicate position in the string.

101 is also ambiguous.

Python 3.6 (pre-release), 199
Saved 6 bytes thanks to Morgan Thrapp
import re
def f(s):s=s.strip('()');i,j=[m.start()if m else-1for m in(re.search(c+'(?![^(]*\))',s)for c in'21')];return i>0and f'2({f(s[:i])},{f(s[i+1:])})'or j>=0and f'1({f(s[:j])or f(s[j+1:])})'or s

Explanation & ungolfed version:
import re

def f(s):
    s=s.strip('()')
    # Search for '2' and '1' outside of brackets
    i, j = [m.start() if m else -1
            for m in (re.search(c + '(?![^(]*\))', s) for c in '21')]

    if i > 0:
        # Call `f(s[:i])` and `f(s[i+1:])`, concatenate the results
        return f'2({f(s[:i])},{f(s[i+1:])})'
    elif j>=0:
        # Call `f(s[:j])` and `f(s[j+1:])`, choose the non-empty result
        return f'1({f(s[:j]) or f(s[j+1:])})'
    else:
        return s


text:
Surjective, Injective, Bijective, or Nothing?
Given a mapping from the integers from 1 to N to the integers from 1 to N, determine if the mapping is surjective, injective, bijective, or nothing.
You may choose any character/digit for the four outputs.
Specs
Input format: n, arrays of pairs (n is the highest number in the domain and range)
For example, if the first number is 3, then both the domain and the co-domain are {1,2,3}.
For example, {i+1 | i from 1 to 9} (n=10) is represented by 10, [[1,2],[2,3],...,[9,10]].
The input may contain duplicate.
Testcases
2, [[1,2],[2,1]] => bijective
2, [[1,1],[1,2]] => surjective
3, [[1,1]] => injective
3, [[1,2],[2,3]] => injective
4, [[1,2],[2,2],[3,2],[4,2]] => nothing
2, [[1,2],[1,2]] => injective
3, [[1,1],[1,2],[1,3]] => surjective
2, [[1,1],[1,1],[2,2]] => bijective

Some languages don't have arrays of pairs. Can the input be more flexible? Like two arrays for functions' domain and codomain?

What's the desired result for 2, [[1,1],[1,2],[2,2]]?

^^yes, ^nothing

Do the mappings need to be functions to qualify as bi/in/surjections?

Why is 4 surjective when the result is only ever 2? Is the mapping really from {1,...,N} to {1,...,N}?

@David Sorry, thanks for reminding.

Could you also help me check the other testcases?

Since the domain and codomain are equal, being injective implies surjective, and vice versa, so you can only have a bijection or nothing. If the sets don't have to be {1,...,N} then it's OK. (e.g. to be surjective but not injective, the domain has to have more elements than the codomain)

@LeakyNun My case 2 and case -2 returned False, I have looked into it and it seems we have different definitions for "injection". I took the definition from Wikipedia: https://en.wikipedia.org/wiki/Injective_function which states no "Y" is mapped from more than one "X", and it doesn't state whether "X" can map to more than one "Y". This Math.SE answer also agrees: http://math.stackexchange.com/a/1051229/332147 However none of the definitions really stand if your map can have more than one value for each arg right? "Injective" is rly just "one-to" and func is "to-one"  so that "inj func"="1to1"

Injective means that the preimage of an element in the codomain is a unique element in the domain, or that one input has at most one output. Surjective means that every possible output has at least one input, or that the preimage of the codomain is a subset of the domain. Bijective means both properties are satisfied. Function doesn't necessarily have any special meaning (it sometimes does), and in this case the question asks about mappings anyway.

From wiki, "In other words, every element of the function's codomain is the image of at most one element of its domain," which means each output has at most one input instead of what you said above that each input has at most one output.

function means surjective No it doesn't. There are functions that are not surjective. I'm not sure it makes sense to define "surjective" for mappings that are not functions. Perhaps you should restrict the challenge to functions. This also confuses me: n is the highest number in the domain and range. For the third example, 3, [[1,1]], does that mean the domain is 1 2 3 (then the mapping is not a function)? Or that the codomain is 1 2 3? Or both? I think the rules should be made clearer

@LuisMendo Sorry, could you help me check the testcases?

What confuses me is that fact that you can have the first input exceeding the number of pairs, or a first-element repeated in two differnet pairs. Any of those implies the mapping is not a function, and I think "injective" or "surjective" only make sense for functions. So perhaps you should restrict the input to be a function. That means each element in the domain has one and only one image element in the codomain

@LuisMendo Please edit my question as you see fit.

@LeakyNun But that would imply a big change: removing cases; restricting the input to be functions only; which would make the first number redudant (and so an optional input). It would affect the two current answers. Perhaps contact with the two answerers first

Pyth - 10 9 13 bytes
im&{IdqSQSdE2

Takes domain and codomain separately as allowed by comments in OP.
Test Suite.

It does not work...

@LeakyNun, but, but it gives the right answers?

You did not account for duplicates

@LeakyNun what about now?

Looks like I've confused the definition of surjectivity... consider changing your answer?

Also, I've clarified the treatment of duplicates in the testcases.

Pyth, 15 bytes
+!-SQJeC{E*2{IJ

The output is identified by:
nothing   : 0
surjective: 1
injective : 2
bijective : 3

In pseudocode,
                  Q=input()                 # pre-initialized var, 'n'
+                 sum(                      # sur=1,in=2,thus bi=sur+in=3,no=0
 !                  not(                    # if 'filtrate'=[], true/surjective
  -SQ                 filter(range(1,Q),    # filter codomain by range
     JeC{E              J=transpose(deduplicate(input()))[-1]
                    ))  # find the "redundant" range, may corrspnd to diffrnt args
 *2{IJ              2*invariant(J,deduplicate)
                  ) # if J(redundnt range) invariant undr dduplicatn, true/injectiv

Test suite
Currently, the test suite returns two False's, namely for case 2 and case -2 (second-to-last). This has to do with the definition of "injective", and will be discussed with the OP.

Python, 85 82 bytes
The methodology here is basically:

Remove duplicate points
Check if the cardinality of the image of the domain + cardinality of domain is equal to twice the number of points

If true -> injective -> return 1

Check if the cardinality of the image of the domain is equal to the cardinality of the codomain

If true -> surjective -> return 2

If both true -> bijective -> return 3
If neither -> nothing -> return 0

def f(n,t):l=len;d,c=zip(*set(t));x=l(set(c));return(x+l(set(d))==l(c)*2)+(x==n)*2

Test Cases
print(f(2, [(1,2),(2,1)])==3)# => bijective
print(f(2, [(1,1),(1,2)])==2)# => surjective
print(f(3, [(1,1)])==1)# => injective
print(f(3, [(1,2),(2,3)])==1)# => injective
print(f(4, [(1,2),(2,2),(3,2),(4,2)])==0)# => nothing
print(f(2, [(1,2),(1,2)])==1)# => injective
print(f(3, [(1,1),(1,2),(1,3)])==2)# => surjective
print(f(2, [(1,1),(1,1),(2,2)])==3)# => bijective

Update

-3 [16-05-26] Multiplied by 2 instead of adding