text:
Calculating distances mod N
You have been collecting data from a Advanced Collecting Device Controller™ for a long time. You check the logs, and to your horror you discover that something has gone terribly wrong: the data only contains the last bits of the numbers!
Luckily, you know the starting value and that the value never changes fast. That means you can recover the rest by just finding the distance from the start.
Challenge
You will write a program or a function to calculate the amount a value has changed, given a modulus N and a list of the intermediate values modulo N.
The change between every pair of numbers is always less than N/2, so there will only be one valid answer for each test case.
You will be given as input an integer N > 2 and a list of values, in a format of your choice. Input may be given via STDIN or command line or function arguments.
You will output a single integer, the amount the original value has changed. Output may be printed to STDOUT or returned.
Rules

Your program must work for any distance and modulus less than 2^20.
You may assume that:

N is at least 3.
The list has at least 2 values.
All the values in the list are at least 0 and less than N.
All changes in the numbers are less than N/2.

Anything else is an invalid input, and your program may do whatever it wants.
Standard loopholes, any non-standard libraries and built-in functions for this exact purpose are forbidden.
This is code-golf, so the shortest program in bytes wins.

Example test cases
Input:
3
0 1 2 2 0 1 0 2 1 2 0 1 2 1 1

Output:
4

Explanation (with example value):
Value mod 3: 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
Value:       0 1 2 2 3 4 3 2 1 2 3 4 5 4 4

Input:
10
5 2 8 9 5

Output:
-10

Explanation (with example value):
Value mod 10:  5  2  8  9  5
Value:        15 12  8  9  5

Invalid inputs:
2
0 0 0 0 0

(too small modulus)
6
2 5 4 2

(too large change between 2 and 5)

A format of your choice is a slippery slope. Can my GolfScript solution rely on an input list looking like :^;[5 2 8 9 5](\  ?

@Mauris Generally, no... "a format of your choice" is usually assumed to mean "a conventional representation in your language of choice".

You can, however, rely on the input list looking like "10 5 2 8 9 5" or "10,5 2 8 9 5" or "10 5,2,8,9,5".

TI-BASIC, 15 bytes
Input N
sum(N/πtan⁻¹(tan(ΔList(πAns/N

Takes the list from Ans and the modulus from Input.
                       πAns/N    ; Normalize the list to [0,π)
                 ΔList(          ; Take differences, which are in the range (-π,π)
       tan⁻¹(tan(                ; Modulo, but shorter. Now elements are in (-π/2,π/2)
    N/π                          ; Multiply by N/π. These are displacements at each step.
sum(                             ; Add up all the displacements

Python 2, 53 bytes
lambda n,l:sum((b-a+n/2)%n-n/2for a,b in zip(l,l[1:]))

Super straight forward answer. I wonder if there is a shorter way.

I missed that bit. Thanks.

@Jakube I already did it - I wasn't aware of .:_2 to generate pairs until I saw your answer - I was using zip.

@Jakube I got it down to 19 :)

Mathematica, 30 bytes
Tr@Mod[Differences@#2,#,-#/2]&

This is an anonymous function which takes two arguments.  Example usage:
Tr@Mod[Differences@#2,#,-#/2]&[3, {0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 2, 1, 1}]
(* 4 *)
Tr@Mod[Differences@#2,#,-#/2]&[10, {5, 2, 8, 9, 5}]
(* -10 *)

This works by taking the Differences between successive elements, wrapping them to the range -n/2 to +n/2 with Mod and its offset parameter, then taking the total with Tr (matrix trace, sum of diagonal elements).

Note that even ungolfed it's only 43 bytes!
f[n_, l_] := Total[Mod[Differences[l], n, -n/2]]

@ is unnecessary when you're already calling the function with square brackets. Having both is a syntax error.

@DavidZhang Whoops, don't know what I was thinking.  Serves me right for trying to answer without opening Mathematica!

J, 24 bytes
[+/@(]-(>-:)~*[)[|2-~/\]

Usage:
   f=:[+/@(]-(>-:)~*[)[|2-~/\]

   3 f 0 1 2 2 0 1 0 2 1 2 0 1 2 1 1
4

   10 f 5 2 8 9 5
_10

Will try to golf more and add some explanation after that.
Try it online here.

Sure its J and not CJam ? :P

Pyth, 20 19 bytes
sm-J/Q2%+-FdJQ.:vw2

Stole .:_2 from Jakube, idea from Mauris.

R, 38 bytes
function(n,v)sum((diff(v)+n/2)%%n-n/2)

This creates an unnamed function that accepts an integer and a vector as input and returns a single integer. To call it, give it a name, e.g. f=function(n,v)....
Ungolfed + explanation:
f <- function(n, v) {
    # Compute the differences between sequential elements of v
    d <- diff(v)

    # Add n/2 to the differences and get the result modulo n
    m <- (d + n/2) %% n

    # Subtract n/2 then sum the vector
    sum(m - n/2)
}

Examples:
> f(3, c(0, 1, 2, 2, 0, 1, 0, 2, 1, 2, 0, 1, 2, 1, 1))
[1] 4

> f(10, c(5, 2, 8, 9, 5))
[1] -10

MatLab, 33 bytes
@(x,y)sum(mod(diff(y)+x/2,x)-x/2)

My apologies, this is my first answer on this website. Typing this in MatLab then using the input ans(modulus_value, [intermediate_values]) will return the requested value, where 'modulus_value' is the modulus value, and 'intermediate_values' is a list of the intermediate values separated by either spaces or commas.
Example:
ans(3, [0 1 2 2 0 1 0 2 1 2 0 1 2 1 1])

The anonymous function takes advantage of MatLab's mod, diff, and sum functions to compute the answer. First, the difference between each of the intermediate values is calculated. The result is then offset by the modulus divided by two, resulting in a set of difference values that is bound by [-modulus/2 modulus/2]. The result is then offset and summed again.
I think this can be golfed more, I'll be back soon with an update. Special thanks to @2012rcampion for the idea.
Edit: Matlab's unwrap function almost works here, but it's tough to golf. The following code returns an array where the last value is the amount the first value has changed:
@(x,y)unwrap(y/x*2*pi)/2/pi*x-y(1)
The intermediate values are scaled to the range of [-pi pi], then "unwrapped" such that no consecutive value is more than pi apart. These values are then re-scaled and shifted, resulting in an array of distances from the starting value.
Interesting, but not very practical for this challenge :D

Pyth, 29 bytes
+sm**._K-Fdvz>y.aKvz.:Q2-eQhQ

Try it online: Pyth Compiler/Executor

Input is space-separated, not comma-separated; your program doesn't seem to handle this.

@Mauris "a list of values, in a format of your choice"

Oh, my bad! I totally missed that part of the spec.

CJam, 27 bytes
0q~:_2ewf{~\m1$2/:I+\,=I-+}

Test it here.

Pip, 39 bytes
Qn$+({a>n/2?a-na<-n/2?a+na}Mg@>1-g@<-1)

Requires the list of data as command-line arguments and the modulus on STDIN. If that's too much of a stretch, I have a version that takes two command-line args for 5 bytes more.
Explanation:
                                         g is list of cmdline args (implicit)
Qn                                       Read n from stdin
                            g@>1         All but the first of the cmdline args
                                -g@<-1   ...minus all but the last of the cmdline args
                                         (i.e. a list of the differences of adjacent items)
     {                    }M             ...to which, map the following function:
      a>n/2?a-n                            If diff is too big, subtract n;
               a<-n/2?a+n                  else if too small, add n;
                         a                 else return unchanged
  $+(                                 )  Sum; print (implicit)

And just to prove that this not-so-competitive score is more reflective on my golfing skills than my language, here's a port of Mauris's Python solution in 30 bytes:
Qn$+({(n/2-$-a)%n-n/2}MgZg@>1)

Jelly
6 bytes
Iæ%H}S

Try it online!
How it works
Iæ%H}S    Main link. Left input: A (list). Right input: N (integer).

I         Compute the increments (deltas of consecutive elements) of A.
   H}     Halve the right input (N).
 æ%       Mod the increments into (-N/2, N/2].
     S    Take the sum of all results.


text:
Fake Marquee Text
In this challenge fake marquee text is text that is shown part by part, in a scrolling-like fashion.
Some examples:
testing 4

   t
  te
 tes
test
esti
stin
ting
ing
ng
g

hello 2

 h
he
el
ll
lo
o

foobarz 3

  f
 fo
foo
oob
oba
bar
arz
rz
z

Something a bit longer 10

         S
        So
       Som
      Some
     Somet
    Someth
   Somethi
  Somethin
 Something
Something
omething a
mething a
ething a b
thing a bi
hing a bit
ing a bit
ng a bit l
g a bit lo
 a bit lon
a bit long
 bit longe
bit longer
it longer
t longer
 longer
longer
onger
nger
ger
er
r

small 15

              s
             sm
            sma
           smal
          small
         small
        small
       small
      small
     small
    small
   small
  small
 small
small
mall
all
ll
l

aaa 3

  a
 aa
aaa
aa
a

brace yourself 6

     b
    br
   bra
  brac
 brace
brace
race y
ace yo
ce you
e your
 yours
yourse
oursel
urself
rself
self
elf
lf
f

You have to write a program or a function that takes in two input and prints the output as described above. You may or may not output trailing spaces in your output. This is code-golf so shortest code in bytes wins.
If your program is standalone (i.e. when run actually prints the lines) (Input can be hard-coded but easy to change) and sleeps a bit between each line of output you get a -10 bonus.

What do you mean by "includes Output" ?

Also, I suggest you specify the input structure and format. For example, what if I want my text to have spaces ?

Also, do we have to print the first and the last lines which are simply spaces ?

What about trailing spaces on the last few lines ?

@Optimizer Spaces can be treated exactly like the other symbols, may be inside or after the message.

My question was regarding trailing spaces on the lines where the complete string is printed. For example aaa 3, do we print a space after the aa on the 3rd line or not ?

@Optimizer only the visible output is important in this challenge, as spaces are invisible you may or may not print them on your choosing.

Inspired by this?

@CoolGuy yes, I forgot to mention that

A single empty line at the beginning seems to be allowed. How about another empty line at the end?

@nimi only the visible output is important in this challenge

Since you're talking about "only visible output", can we assume that the input will only be printable ASCII? (character codes 0x20 to 0x7E)

@MartinBüttner input can be assumed to be in the character codes  0x20 to 0x7E

Why don't we just start calling marquees scrolly texts again? It would make the world a better place.

Old question, but this should probably specify maximums for the inputs: how large can n be? How long can the string be? My answer works for all given samples, but fails for extremely large inputs.

@BradC I guess max n should be 79 the standard max line length

CJam, 12 11 bytes
1 byte saved by Dennis.
,Sf*\f+$zN*

I'm making use of "Input can be hard-coded but easy to change": this expects the input to be already on the stack, so you can prepend "testing" 4 to the above, for instance.
Test it here.
Explanation
Notice that the transpose of the desired output is much simpler:
   testing
  testing
 testing
testing

So we just need to create n lines, prepending i spaces for i from n-1 down to 0. That's what the code does:
,            e# Turn n into a range [0 1 .. n-1]
 Sf*         e# Turn each i into a string of i spaces.
    \f+      e# Swap this array with the input string and append it to each of the
             e# strings of spaces.
       $     e# Sort the array to have the string with n-1 spaces first.
        z    e# Transpose the grid.
         N*  e# Join the lines with newline characters.

19 - 10 = 9?
I find the "sleeps a bit between each line" bonus a bit vague and dodgy, but here is a 19 byte version that simply stalls after each line by computing all permutations of the array [0 1 .. 7]. In the online interpreter this simply leads to the final result being shown a bit later, but if you use the Java interpreter this will actually print each line after "sleeping a bit":
,Sf*\f+$z{oNo8e!;}/

Nice use of z. Assuming the input is printable ASCII, you can replace W% with $.

@Dennis Oh, I like that. I've requested clarification on this from the OP. (That said, I use z all the time for ascii grid-based challenges.)

C, 69 bytes
printf magic!
f(s,n,i)char*s;{for(i=n;*s;i?i--:s++)printf("%*s%.*s\n",i,"",n-i,s);}

Expanded version with some explanation:
f(s,n,i)char*s;{       /* s is the string, n is the width of the grid. */
  for(i=n;             /* i is the number of preceding spaces. */
      *s;              /* Stop once we reach the end of the string. */
      i?i--:s++)       /* Decrease the number of spaces, and when there's
                          none left start truncating the string itself. */
  printf("%*s          /* The first argument is the minimum width to print the
                          string (left padded with spaces) and the second
                          argument is the string to print. We use the empty
                          string just to print the i spaces. */
    %.*s              /* The third argument is the maximum number of
                         characters from the string (which is the fourth
                         argument) to print. */
    \n",i,"",n-i,s);
}

And here's an example:

$ ./marquee stackoverflow 12

           s
          st
         sta
        stac
       stack
      stacko
     stackov
    stackove
   stackover
  stackoverf
 stackoverfl
stackoverflo
tackoverflow
ackoverflow
ckoverflow
koverflow
overflow
verflow
erflow
rflow
flow
low
ow
w

Pyth, 13 bytes
jb.:++K*dQzKQ

Try it online: Pyth Compiler/Executor
Explanation
                 implicit: z = input string, Q = input number
      K*dQ       K = " " * Q
    ++K   zK     K + z + K
  .:        Q    all substrings of length Q
jb               join by newlines and print

Python 65 63
s=lambda t,s:'\n'.join((' '*s+t)[i:s+i]for i in range(len(t)+s))

This was actually used to write the examples. Baseline solution.
>>> print(s("foobarz", 3))

  f
 fo
foo
oob
oba
bar
arz
rz
z

i haven't tested it but you should be able to remove the square brackets inside join

@undergroundmonorail right

Javascript (ES7 Draft), 61 bytes

f=(s,l)=>[x.substr(i,l)for(i in x=' '.repeat(l)+s)].join(`
`)
<input id="str" value="Some String" />
<input id="num" value="5" />
<button onclick="out.innerHTML=f(str.value, +num.value)">Run</button>

Javascript (ES6) Hardcoded Inputs, 47 bytes
Assuming hard-coded inputs in variables s (string) and l (length), it can be reduced to 47 bytes printing with an alert for each line:
for(i in x=' '.repeat(l)+s)alert(x.substr(i,l))

K, 19 bytes
{x#'![1]\(x#" "),y}

Tack x spaces (x#" ") onto the beginning of the string y. Then use the "fixed-point scan" form of the operator \ to create the set of rotated strings. A fixed-point in K stops iterating if the result of applying the function returns a repeated result or if the initial input is revisited. Since ![1] will rotate a string one step at a time, ![1]\ is a nice idiom for cyclic permutations. Then we just trim the results with x#'.
A sample run:
  {x#'![1]\(x#" "),y}[4;"some text"]
("    "
 "   s"
 "  so"
 " som"
 "some"
 "ome "
 "me t"
 "e te"
 " tex"
 "text"
 "ext "
 "xt  "
 "t   ")

Julia, 75 bytes
(s,n)->(n-=1;print(join([(" "^n*s*" "^n)[i:n+i]for i=1:length(s)+n],"\n")))

This creates an unnamed function that accepts a string and integer as input and prints the output. To call it, give it a name, e.g. f=(s,n)->(...).
Ungolfed + explanation:
function f(s, n)
    # Decrement n by 1
    n -= 1

    # Construct the lines as an array using comprehension by repeatedly
    # extracting subsets of the input string padded with spaces
    lines = [(" "^n * s * " "^n)[i:n+i] for i = 1:length(s)+n]

    # Print the array elements separated by a newline
    print(join(lines, "\n"))
end

Examples:
julia> f("banana", 3)
  b
 ba
ban
ana
nan
ana
na
a

julia> f("Julia", 6)
     J
    Ju
   Jul
  Juli
 Julia
Julia
ulia
lia
ia
a

Note that this solution is 66 bytes if s and n are assumed to already exist in the program.

J (22)
This ended up longer than I anticipated, but I guess it is not too bad.
[{."0 1[:]\.(' '#~[),]

Fun fact: non of the [ and ] are actually matched, or have anything to do with each other.

After 3 small changes: [{."1]]\.@,~' '#~[ (18 bytes).

QBasic, 56 - 10 = 46
This is golfed QBasic--the autoformatter will expand ? into PRINT and add some spaces. Tested with QB64, though there shouldn't be anything in here that won't work with DOS QBasic.
s=SPACE$(n)+s
FOR i=1TO LEN(s)
?MID$(s,i,n)
SLEEP 1
NEXT

QBasic generally isn't good with string operations, but there very conveniently is a function that returns a given number of spaces!
Taking some liberties with "input may be hard-coded," this code expects the variable s to be DIM'd AS STRING, in order to avoid the $ type suffix, as well as the string being assigned to s and the number to n.
Example preamble:
DIM s AS STRING
s="string"
n=4

Output:

   s
  st
 str
stri
trin
ring
ing
ng
g

The top blank row may be eliminated by starting the FOR loop at 2 instead of 1.
Bonus: Adding CLS right before NEXT for a paltry four bytes turns this into... a real marquee!

I PRINT CHR$(3) QBasic. :^D

I should try QBasic again... It's what I first learned on

Ruby, 68, 55  bytes
a=" "*$*[1].to_i+$*[0]+" ";a.size.times{|b|puts a[b...b+$*[1].to_i]}

After an update from @blutorange:
a=" "*(z=$*[1].to_i)+$*[0];a.size.times{|b|puts a[b,z]}

Output:
         S
        So
       Som
      Some
     Somet
    Someth
   Somethi
  Somethin
 Something
Something
omething a
mething a
ething a b
thing a bi
hing a bit
ing a bit
ng a bit l
g a bit lo
 a bit lon
a bit long
 bit longe
bit longer
it longer
t longer
 longer
longer
onger
nger
ger
er
r

ruby marquee.rb "Something a bit longer" 10
First submission so asking for criticism.

Looks well done to me, using some ruby shortcuts. The final space doesn't seem to be neccessary though ("only the visible output matters"), and you can save some bytes by using a temporary variable: a=" "*(z=$*[1].to_i)+$*[0];a.size.times{|b|puts a[b,z]}

@blutorange Thanks for the feedback!

You're welcome. Feel free to edit the answer if you'd like ;)

Haskell, 61 59 54 bytes
m n=unlines.scanr((take n.).(:))[].(replicate n ' '++)

Usage example:
*Main> putStr $ m 6 "stackoverflow"

     s
    st
   sta
  stac
 stack
stacko
tackov
ackove
ckover
koverf
overfl
verflo
erflow
rflow
flow
low
ow
w

*Main>

Edit: an empty line at the beginning / end is allowed

Bash, 109 - 10 = 99 bytes
I see that in the time it took me to write my solution, I have been soundly beaten. Nevertheless, I spent too long writing it to not post it...
Besides which, it has some unique features, like the time between lines printing being user-adjustable based on how much is in the current directory! (Also somewhat inconsistent, depending on how your disk feels)
l=${#1};s=$1;for j in `seq 1 $2`;do s=" $s";done;for i in `seq 0 $((l+$2))`;do echo "${s:i:$2}";find 1>2;done

Example:
cd <some directory in which you own everything recursively>
Marquee.sh "Test Case" 4

   T
  Te
 Tes
Test
est
st C
t Ca
 Cas
Case
ase
se
e

Ungolfed and commented:
l=${#1} #Length of the incoming string
s=$1 #Can't reassign to the parameter variables, so give it another name
for j in `seq 1 $2`; do
    s=" $s" # Put on the padding spaces
done

for i in `seq 0 $((l+$2))`; do
    #Cut the string and print it. I wish I could lose "padding" that easily!
    echo "${s:i:$2}" #Format is ${string:index:length}, so always the same
    # length, with the index moving into the string as the loop advances
    find 1>2  #Wait "a bit". From ~/, about 6 minutes per line on my junky
    # computer with a huge home directory. Probably in the <1 sec range for
    # most people.
    #This actually has the same character count as sleep(X), but is much
    # more fun!
done

I've never really tried this before. Suggestions and comments welcome!

Pure Bash, 61 bytes
printf -vs %$2s"$1"
for((;++i<${#1}+$2;)){
echo "${s:i:$2}"
}

Output:
$ ./marquee.sh testing 4
   t
  te
 tes
test
esti
stin
ting
ing
ng
g
$

I guess I don't understand the distinction "pure" Bash, so maybe this suggestion isn't any good, but sleep(1) is 8 characters and gives you -10 (and is a GNU Core Util)

Pyth, 12 bytes
jb.:X*dyQQzQ

Demonstration.

Pyth, 17 - 10 = 7 bytes
FN.:X*dyQQzQ&.p9N

This version employs a delay between line prints. This can be seen on the command line compiler, which you can get here.
Run the following:
pyth -c 'FN.:X*dyQQzQ&.p9N' <<< 'testing
4'

This has a delay of about 0.3 seconds before each print. If you prefer a longer delay, you can use:
FN.:X*dyQQzQ&.pTN

This has about a 4 second delay.

Perl, 50
$c=$" x$^I;$_="$c$_$c";sleep say$1while(/(?<=(.{$^I}))/g)

57 characters +3 for -i, -n and -l. -10 characters for the sleep.
-i is used for the numeric input, which is stored in $^I. Basically, we add i spaces to the front and end of the input, and then search for every i characters and loop through them with while. say conveniently returns 1 which we can input to sleep.
echo "testing" | perl -i4 -nlE'$c=$" x$^I;$_="$c$_$c";sleep say$1while(/(?<=(.{$^I}))/g)'

I know this is old, but it's just jumped back onto the front page and I've had a go at shrinking this down somewhat: s/^|$/$"x$^I/eg;sleep say$1 while s/.(.{$^I})/$1/. You can also lose the -l flag, but I think you need to count 5 for -i -n (since -i isn't a default flag) if you run via: echo -n "testing" | perl -i4 -nE'...'. Should still be down to 44 though!

@DomHastings thanks Dom! Nice work, I'll edit my answer later :)

Java, 133 119 115
int i;void f(String s,int n){for(;++i<n;)s=" "+s+" ";for(;i<=s.length();)System.out.println(s.substring(i-n,i++));}

Long version:
int i;
void f(String s, int n) {
    for(; ++i < n;)
        s = " " + s + " ";
    for(; i<=s.length();)
        System.out.println(s.substring(i-n, i++));
}

Padding is applied to the string, and then substrings of the padded string are printed to the console.
-4 bytes thanks to @KevinCruijssen.

I know it's been more than a year, but you can golf the second for-loop a bit: for(;i<= s.length();System.out.println(s.substring(i-n,i++))); (-3 bytes)

Doesn't mean it can't be improved. :) Thanks.

Python 2, (52 bytes - 10 = 42)  64 62 60 46 44
(I assumed the line for hard-coded input doesn't add to byte count.)
I didn't see a program yet that actually sleeps between printing lines, so I made one that does, since it looks more like a marquee that way. This program is 2 more bytes in Python 3.
EDIT: The program now does a computation instead of sleeping. I used i in the calculation so that the program doesn't store it as a constant, but must compute it each time.
Try It Online!
i=0
while s[i-n:]:print(' '*n+s)[i:n+i];i+=1;i**7**7

Maybe instead of time.sleep there's some long computation you can use? Also, it's a bit shorter to use a while loop: i=0\nwhile s[i-n:]:print(' '*n+s)[i:n+i];i+=1

@xnor Exponentiation a couple times works pretty well for a computation.

@mbomb007 I don't think you need to store the value of the computation to get python to actually do it (so you can save 'q='). Also, x^7^7 is mathematically equivalent to x^49, although python seems to resolve the latter slightly faster for me. You can save a few characters that way.

@Sompom Try it in the repl. If I consolidate the expression into a single exponentiation, it completely removes the time delay. But I will remove q=. Thanks.

@Sompom Exponentiation is right-associative, so this is actually i**(7**7)

@Sp3000 and mbomb007 -- Oops. I guess that I saw a time delay was mostly based on me running it on my old and slow work computer :) . I'll ponder, but I don't know any clever trick off the top of my head.

Something with 9e99 or the like might work better

@Sp3000 I tried that already. Anything larger than i**9e1 causes an overflow error, and there is not a useful delay on the ones that run.

POSIX shell, 94
[ $3 ]||set "`printf "%${2}s"`$1" $2 t
[ "$1" ]&&printf "%-.${2}s" "$1" "
"&&$0 "${1#?}" $2 t

I know it looks closer to perl, but this really is shell!
The first line adds the necessary leading spaces, only on the first time through the loop.  It sets $3 to indicate that it has done so.
The second line (N.B. embedded newline) recurses until input is exhausted, printing the first n characters of the string, then invoking itself with the first character removed from $1.
Tested with Debian /bin/dash - sample outputs follow:
./marquee "testing" 4
   t
  te
 tes
test
esti
stin
ting
ing
ng
g

./marquee "Something a bit longer" 10
         S
        So
       Som
      Some
     Somet
    Someth
   Somethi
  Somethin
 Something
Something
omething a
mething a
ething a b
thing a bi
hing a bit
ing a bit
ng a bit l
g a bit lo
 a bit lon
a bit long
 bit longe
bit longer
it longer
t longer
 longer
longer
onger
nger
ger
er
r

./marquee "small" 15
              s
             sm
            sma
           smal
          small
         small
        small
       small
      small
     small
    small
   small
  small
 small
small
mall
all
ll
l

I can add 9 chars to get the -10 bonus!
[ "$1" ]&&printf "%-.${2}s" "$1" "
"&&sleep 1&&$0 "${1#?}" $2 t

Python 2, 51 bytes / 37 bytes
Without hardcoded input (51 bytes):
def f(s,n):
 s=" "*n+s
 while s:print s[:n];s=s[1:]

Call like f("testing", 4).
With hardcoded input (37 bytes):
s="testing";n=4

s=" "*n+s
while s:print s[:n];s=s[1:]

Both versions output an initial line of spaces.

Canvas, 3 bytes
＊／⤢

Try it here!
Input is string and integer (in either order) separated by a newline.

Explanation:
＊     | Repeat a b times vertically (a=string input, b=int input)
  ／   | Make antidiagonal (add one extra space to each line bottom up)
    ⤢　| Transpose (reflect along top-left to bottom-right diagonal)

Matlab, 95
As always, it is a manipulation of matrices. The core here is the command spdiags which lets you create diagonal matrices very easily.
t=input('');
n=numel(t);
k=input('');
flipud(char(full(spdiags(repmat(t,n+k-1,1),1-n:0,n+k-1,k))))

With hardcoding 71 bytes (expected string stored in t and the number in k)
n=numel(t);flipud(char(full(spdiags(repmat(t,n+k-1,1),1-n:0,n+k-1,k))))

APL, 50 - 10 = 40 chars
I'm sure it could be shorter. 50 is the length of the program without the two constants.
{⍵≡⍬:⍬⋄⎕←↑⍵⋄⎕DL 99⋄∇1↓⍵}⊂[0]⊖s⍴⍨n,¯1+⍴s←'brace yourself',' '⍴⍨n←6

Explanation:
                               ' '⍴⍨n←6   call the number 'n' and make n spaces
            s←'brace yourself',           append them to the string and call it 's'
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
                             s⍴⍨n,¯1+⍴s   make a len(s)-1 by n matrix by repeating s
                        ⊂[0]⊖             reflect the matrix and extract the columns
{                      }                  pass the list of columns to this function
 ⍵≡⍬:⍬⋄                                   return if the list is empty
       ⎕←↑⍵⋄                              print the first column (as a row)
            ⎕DL 99⋄                       wait for 99ms
                   ∇1↓⍵                   recurse with the rest of the columns

Developed for ngn APL on the terminal.

Powershell - 85 83 bytes
It's late, it's not going to win :-) But I thought I'd throw in a Powershell one for completeness:
function m($s,$n){1..$($n+$s.length)|%{-join(" "*$n+$s+" "*$n)[$_-1..$($n+$_-1)]}}

J, 15 14 bytes
,.~/@(' '&,~<)

Try it online!

This is gorgeous.

Add++, 38 bytes
L#,b]*ApR1€Ω_32C€*dbR@$BcB]€¦+bU@BcBJn

Try it online!

Thunno 2 N, 8 bytes
L€ṣs+rðƬ

Try it online!
Explanation
L€ṣs+rðƬ  # Implicit input
L€ṣ       # Push [" " * 0, " " * 1, ..., " " * (n-1)]
   s+     # Prepend each to the input
     rðƬ  # Reverse and transpose with filler space
          # Implicit output, joined on newlines

PHP4.1, 85-10=75 bytes
Yes, this is a very old version, but it has a functionality I need.
You can still run it in any more recent versions of PHP, but you need to set the variables yourself before running the code below.
That helps me to reduce the size of my code a lot!
It is really basic:
<?for($s=str_repeat(' ',$n).$s;$i++<strlen($s)+$n;sleep(1))echo substr($s,$i,$n),'
';

I ran for the bonus due to this, quoting O.P.:

If your program is standalone (i.e. when run actually prints the lines) (Input can be hard-coded but easy to change) and sleeps a bit between each line of output you get a -10 bonus.

As you can obviously see, it has a sleep.
This assumes that you have register_globals enabled by default, which were the default settings for this version.

You can easily test in your browser, with minimal some changes:

//detects if it is running in js or php
//true for js, false for php
if('\0'=="\0")
{
 function strlen($s){
  return $s.length;
 }

 function str_repeat($s,$n){
  return Array($n+1).join($s);
 }

 function substr($s,$n,$m){
  return $s.substr($n,$m);
 }

 function printf($s){
  document.write($s);
 }

 function concat($a,$b){
  return $a+$b;
 }
}
else
{
 function concat($a,$b){
  return $a.$b;
 }
}

//sets the variables, not required for PHP if you pass the values by GET or POST
$i=0;
$s='example';
$n=6;

for($s=concat(str_repeat('-',$n),$s);$i++<strlen($s)+$n;)printf(concat(substr($s,$i,$n),'
'));
*{font-family:monospace}

The above code is a polyglot and you can run in your browser or in a PHP interpreter. Shouldn't I get a prize for this? A cookie, perhaps?
List of changes:

Removed the sleep(1) in this test
Created 2 versions of the function concat
The goal is to overcome PHP and JS differences in concatenating strings.
Instead of a space, a - is used to fill the space
Instead of echo, printf is uses instead (PHP limitation)
Instead or a 'real' newline,
 is uses instead

Cobra - 60
def f(n,s)
    s=' '.repeat(n)+s
    while''<s,print (s=s[1:])[:n]

Groovy - 82
n=args[1]as int;t=" "*n+args[0]+" "*n;(0..t.size()-n).each{println t[it..it+n-1]}

Lua, 79 bytes
r=io.read;t=r()w=r()s=" "t=s:rep(w)..t;for i=1,t:len()do print(t:sub(i,i+w))end

C#, 112 bytes
s=>n=>{var r=new string(' ',n-1);s=r+s+r;r="";for(int i=0;i<s.Length-n+1;)r+=s.Substring(i++,n)+"\n";return r;};

Full program with ungolfed method and test cases:
using System;

namespace FakeMarqueeText
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,Func<int,string>>f= s=>n=>
            {
                var r=new string(' ',n-1);
                s=r+s+r;
                r="";
                for(int i=0;i<s.Length-n+1;)
                    r+=s.Substring(i++,n)+"\n";

                return r;
            };

            // test cases:
            Console.WriteLine(f("testing")(4));
            Console.WriteLine(f("hello")(2));
            Console.WriteLine(f("foobarz")(3));
            Console.WriteLine(f("Something a bit longer")(10));
            Console.WriteLine(f("small")(15));
            Console.WriteLine(f("aaa")(3));
            Console.WriteLine(f("brace yourself")(6));

        }
    }
}

Charcoal, 7 bytes
ＦＮ«Ｐ↓η↗

Try it online!

Jelly, 15 bytes - 10 = 5 (non-competing?)
ḶṚ⁶ẋ;€⁹ZṄœS$€ṛ“

Try it online!
Sleeps for a second between each line. Prints a trailing newline, if that's acceptable.
yay Jelly beats Charcoal

APL (Dyalog), 17 bytes
⌽⍉↑(⎕,⍨' '/⍨⊢)¨⍳⎕

Try it online!
(the program assumes ⎕IO←0 which is default on many machines)
Explanation
⍳⎕               Create a range 0 .. input-1
¨                For each element in this range do:
 ' '/⍨⊢           A space duplicated right argument (which is the element in  the range) times
 ⎕,⍨              Concatenated with the input string to its right
⌽⍉               Transpose and reflect horizontally

Python 3, 62 bytes
Definitely think it can be golfed further, particularly with the for loop notation.
Unfortunately I'm not that fluent with Python yet, maybe someone here can help.
def f(s,n):
 s=n*" "+s
 for i in range(len(s)):print(s[i:i+n])

Try it online!
I hope leading spaces are allowed.

Welcome to site!

PowerShell, 60 bytes
param($s,$n)($t=' '*--$n+$s)|% t*y|%{-join$t[$i..($i+++$n)]}

Try it online!

Japt -R, 7 bytes
VÆiYîÃz

Run it online

Nibbles, 6.5 bytes (13 nibbles)
`'.\`,$:^$" "_

Transpose approach copied from The Thonnu's Thunno 2 answer.
    `,          # list of 0..
                #   arg1-1
   \            # reversed
  .             # map over this
       :        # append
             _  # arg2 onto
        ^$      # that many
          " "   # spaces
`'              # and then transpose it all

Google Sheets, 79 bytes
=ARRAYFORMULA(JOIN("
",MID(REPT(" ",A2)&A1,ROW(OFFSET(A2,0,0,LEN(A1)+A2)),A2)))

Text is input in cell A1 and the marquee width is in cell A2.
ARRARYFORMULA + ROW(OFFSET()) lets us return multiple values into the MID function.
After that, all we do is return A2 characters from the middle of the text prepended with spaces as needed.
JOIN combines them all with a line break in between each.
Sample outputs:

I expected this challenge to require clearing the screen so it looks like a marquee in place but, as it (currently) doesn't, I think this answer is valid.

T-SQL, 110 bytes
DECLARE @n INT,@ CHAR(99)SELECT @n=n,@=space(@n)+s FROM t
L:SET @=RIGHT(@,98)PRINT LEFT(@,@n)IF LEN(@)>0GOTO L

Input is via pre-existing table t with columns n (INT) and s (CHAR), per our IO standards.
Formatted:
DECLARE @n INT, @ CHAR(99)
SELECT @n=n, @=space(@n)+s FROM t
L:
    SET @=RIGHT(@,98)
    PRINT LEFT(@,@n)
IF LEN(@)>0 GOTO L

The question didn't specify the range of values my code had to handle; it works for all given samples, but will cut off the text if n + len(s) exceeds 99. To handle huge values of n and much longer strings without cutting off, add two bytes by changing 99 to 999 and 98 to 998.

Perl 5, 43
53 bytes - 10 bonus
push@F,($")x($t=<>);sleep say@F[$_-$t..$_-1]for 1..@F

Try it online!

Zsh, 42 bytes
s=${(l:$2:)}$1;eval '<<<${s:'{1..$#s}:$2\}

Try it online!

GolfScript, 20 bytes
~.' '*@+{.2$<p(;.}do

Try it online!
It prints the length at the end, due to it still being on the stack and implicit printing. I like to think of it as a feature, sort of like its a spelling bee ;)
Really taking the "input can be hardcoded but easy to change" to heart, I managed to get it down to only 17 bytes:
' '*\+{.b<p(;.}do

Try it online!
Input is appended to the stack, in addition to the size being stored in a variable. The main issue was organizing the stack because the length is needed once to create a string of spaces, then it is also needed every loop cycle in order to truncate the string to the correct length. This adds 1 char for duplicating it, one to rotate the stack, and another to duplicate the length every loop cycle.

Vyxal L, 5 bytes
*/¹ɾ꘍

Try it Online!
Wow it's been way too long since I last used vertical join. Takes n then the string.
Explained
*/¹ɾ꘍
*      # Repeat the string n times
 /     # And split into n chunks
  ¹ɾ꘍  # append [1, n] spaces to each chunk (pairwise vectorised)
# The L flag transposes then joins on newlines.

Created with the help of Luminespire.
Now you're probably wondering why there's such a specific flag. Well that's because it's a shortcut for having § at the end of the program. § is a built-in that transposes then joins on newlines.
Now you're probably wondering why there's such a specific built-in. Well that's because back in 2020 when I first added it, apparently I thought it was a useful enough thing that it was worth adding.

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:
Undirect a Graph
Introduction
In this challenge, you are given a directed graph with self-loops, and your task is to convert it to an undirected graph without self-loops.
Input
Your input is a directed graph with vertex set {0, 1, ..., n-1} for some natural number n ≥ 0 (or {1, 2, ..., n} if you use 1-based indexing).
The graph is given as a length-n list L where L[i] is a list of the out-neighbors of vertex i.
For example, the list [[0,1],[0],[1,0,3],[]] represents the graph
.-.
| v
'-0<--2-->3
  ^   |
  |   |
  v   |
  1<--'

Note that the neighbor lists are not necessarily ordered, but they are guaranteed to be duplicate-free.
Output
Your output is another graph in the same format as the input, obtained from it as follows.

Delete all self-loops.
For each remaining edge u -> v, add the reversed edge v -> u if it's not already present.

As with the input, the neighbor lists of the output graph may be unordered, but they cannot contain duplicates.
For the above graph, a correct output would be [[1,2],[0,2],[0,1,3],[2]], which represents the graph
0<->2<->3
^   ^
|   |
v   |
1<--'

Rules
You can use 0-based or 1-based indexing in the graphs.
Both functions and full programs are acceptable.
The lowest byte count wins, and standard loopholes are disallowed.
Test Cases
These test cases use 0-based indexing; increment each number in the 1-based case.
These neighbor lists are sorted in ascending order, but it is not required.
[] -> []
[[0]] -> [[]]
[[],[0,1]] -> [[1],[0]]
[[0,1],[]] -> [[1],[0]]
[[0,1],[0],[1,0,3],[]] -> [[1,2],[0,2],[0,1,3],[2]]
[[3],[],[5],[3],[1,3],[4]] -> [[3],[4],[5],[0,4],[1,3,5],[2,4]]
[[0,1],[6],[],[3],[3],[1],[4,2]] -> [[1],[0,5,6],[6],[4],[3,6],[1],[1,2,4]]
[[6],[0,5,1],[5,4],[3,5],[4],[5,6],[0,3]] -> [[1,6],[0,5],[4,5],[5,6],[2],[1,2,3,6],[0,3,5]]
[[1,0],[5,1],[5],[1],[5,7],[7,1],[],[1]] -> [[1],[0,3,5,7],[5],[1],[5,7],[1,2,4,7],[],[1,4,5]]
[[2,8,0,9],[5,2,3,4],[0,2],[3,7,4],[8,1,2],[5,1,9,2],[6,9],[6,5,2,9,0],[9,1,2,0],[3,9]] -> [[2,7,8,9],[2,3,4,5,8],[0,1,4,5,7,8],[1,4,7,9],[1,2,3,8],[1,2,7,9],[7,9],[0,2,3,5,6,9],[0,1,2,4,9],[0,3,5,6,7,8]]

Pyth, 17 16 bytes
.e-.|f}k@QTUQbkQ

Try it online: Demonstration or Test Suite
Explanation
                   implicit: Q = input
.e             Q   enumerated mapping of Q (k index, b out-neighbors):
     f     UQ         filter [0, 1, ..., len(Q)-1] for elements T, which satisfy:
      }k@QT              k in Q[T]
                      # this are the in-neighbors
   .|        b        setwise union with b
  -           k       remove k

By the way, .e was just switched from k,Y to k,b, so to run this, use .e-.|f}k@QTUQbkQ

@isaacg Will do so, once the online compiler updates.

It has been updated.

CJam, 43 40 35 34 33 bytes
2 bytes saved by Sp3000.
This started out as a really elegant solution and then grew increasingly hideous as I tried patching up some holes I overlooked. I'm not sure yet if the original idea is still salvageable, but I'll try my best...
q~_,,\ff{&W+0=)}_z..-{_,{;(},+}%`

Test it here. Alternatively, run the entire test harness.
I'll add an explanation once I'm sure the patient is dead.

Python 2, 107 bytes
Still trying to figure out if I can golf this more, but for now, this is the best I can do.
def u(g):e=enumerate;o=[set(_)-{i}for i,_ in e(g)];[o[j].add(i)for i,_ in e(o)for j in _];print map(list,o)

I use sets to prevent duplicates; also, unlike list.remove(i), {S}-{i} doesn't throw an error if i is not in S.

Ruby, 78 bytes
Finally some use for ruby's set operators ([1,2]&[2]==[2] and [3,4,5]-[4]==[3,5]).
->k{n=k.size;n.times{|i|n.times{|j|(k[j]&[i])[0]&&k[i]=(k[i]<<j).uniq-[i]}};k}

ideone, including all test cases, which it passes.

CJam, 26 bytes
l~_,,:T.-_T\ff&Tf.e&.|:e_p

Not very short...
Explanation
l~                           e# Read the input.
  _,,:T                      e# Get the graph size and store in T.
       .-                    e# Remove self-loops from the original input.
         _T\ff&              e# Check if each vertex is in each list, and
                             e# return truthy if yes, or empty list if no.
               Tf.e&         e# Convert truthy to vertex numbers.
                    .|       e# Merge with the original graph.
                      :e_    e# Remove empty lists.
                         p   e# Format and print.

JavaScript(ES6), 96 110
Creating adjacency sets from adjacency list, that helps avoiding duplicates.
Ad last it rebuilds the lists starting from the sets.

//Golfed
U=l=>
  l.map((m,n)=>m.map(a=>a-n?s[n][a]=s[a][n]=1:0),s=l.map(m=>[]))
  &&s.map(a=>[~~k for(k in a)])

// Ungolfed

undirect=(adList)=>(
  adSets=adList.map(_ => []),
  adList.forEach((curAdList,curNode)=>{
    curAdList.forEach(adNode=>{
      if (adNode!=curNode) {
        adSets[curNode][adNode]=1,
        adSets[adNode][curNode]=1
      }
    })
  }),
  adSets.map(adSet=>[~~k for(k in adSet)])
)

// Test
out=s=>OUT.innerHTML+=s+'\n'

test=[
 [ [], [] ]
,[ [[0]], [[]] ]
,[ [[],[0,1]] , [[1],[0]] ]
,[ [[0,1],[]] , [[1],[0]] ]

,[ [[0,1],[0],[1,0,3],[]] , [[1,2],[0,2],[0,1,3],[2]] ]
,[ [[3],[],[5],[3],[1,3],[4]] , [[3],[4],[5],[0,4],[1,3,5],[2,4]] ]
,[ [[0,1],[6],[],[3],[3],[1],[4,2]] , [[1],[0,5,6],[6],[4],[3,6],[1],[1,2,4]] ]
,[
   [[6],[0,5,1],[5,4],[3,5],[4],[5,6],[0,3]] ,
   [[1,6],[0,5],[4,5],[5,6],[2],[1,2,3,6],[0,3,5]]
 ]
,[
  [[1,0],[5,1],[5],[1],[5,7],[7,1],[],[1]] ,
  [[1],[0,3,5,7],[5],[1],[5,7],[1,2,4,7],[],[1,4,5]]
 ]

,[
  [[2,8,0,9],[5,2,3,4],[0,2],[3,7,4],[8,1,2],[5,1,9,2],[6,9],[6,5,2,9,0],[9,1,2,0],[3,9]] ,
  [[2,7,8,9],[2,3,4,5,8],[0,1,4,5,7,8],[1,4,7,9],[1,2,3,8],[1,2,7,9],[7,9],[0,2,3,5,6,9],  [0,1,2,4,9],[0,3,5,6,7,8]]
 ]
]

show=l=>'['+l.map(a=>'['+a+']').join(',')+']'

test.forEach(t => (
  r = U(t[0]),
  ck = show(r) == show(t[1]),
  out('Test ' + (ck ? 'OK: ':'FAIL: ') + show(t[0])+' -> ' +
      '\nResult: ' + show(r) +
      '\nCheck : ' + show(t[1]) + '\n\n')
) )

Groovy - 87
u={g->g.eachWithIndex{n,i->g[i]=n-i;g[i].each{g[it]<g.eachWithIndex{n,i->g[i]=n-i;g[i].each{g[it]<<i}};g.each{it=it.sort().unique()}}
assert u([]) == []
assert u([[0]]) == [[]]
assert u([[],[0,1]]) == [[1],[0]]
assert u([[0,1],[]]) == [[1],[0]]
assert u([[0,1],[0],[1,0,3],[]]) == [[1,2],[0,2],[0,1,3],[2]]
assert u([[3],[],[5],[3],[1,3],[4]]) == [[3],[4],[5],[0,4],[1,3,5],[2,4]]
assert u([[0,1],[6],[],[3],[3],[1],[4,2]]) == [[1],[0,5,6],[6],[4],[3,6],[1],[1,2,4]]
assert u([[6],[0,5,1],[5,4],[3,5],[4],[5,6],[0,3]]) == [[1,6],[0,5],[4,5],[5,6],[2],[1,2,3,6],[0,3,5]]
assert u([[1,0],[5,1],[5],[1],[5,7],[7,1],[],[1]]) == [[1],[0,3,5,7],[5],[1],[5,7],[1,2,4,7],[],[1,4,5]]
assert u([[2,8,0,9],[5,2,3,4],[0,2],[3,7,4],[8,1,2],[5,1,9,2],[6,9],[6,5,2,9,0],[9,1,2,0],[3,9]]) == [[2,7,8,9],[2,3,4,5,8],[0,1,4,5,7,8],[1,4,7,9],[1,2,3,8],[1,2,7,9],[7,9],[0,2,3,5,6,9],[0,1,2,4,9],[0,3,5,6,7,8]]

Python 3, 127 bytes
l=list;g=l(map(set,eval(input())))
for i in range(len(g)):
    for j in g[i]:g[j]=g[j]^g[j]&{j}|{i}
print(l(map(l,g)))

Try online
Not my best attempt...

Java, 150
a->{int i=0,j,k=a.size();for(;i<k;a.get(i).remove((Object)i++))for(j=k;j-->0;)if(a.get(j).contains(i)&!a.get(i).contains(j))a.get(i).add(j);return a;}

Expanded, runnable code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function
public class C {
    static Function<List<List<Integer>>, List<List<Integer>>> f = a -> {
        int i = 0, j, k = a.size();
        for (; i < k; a.get(i).remove((Object) i++)) {
            for (j = k; j-- > 0;) {
                if (a.get(j).contains(i) & !a.get(i).contains(j)) {
                    a.get(i).add(j);
                }
            }
        }
        return a;
    };
    public static void main(String[] args) {
        System.out.println(f.apply(new ArrayList(Arrays.asList(
                new ArrayList(Arrays.asList(0, 1)),
                new ArrayList(Arrays.asList(1)),
                new ArrayList(Arrays.asList(1, 0, 3)),
                new ArrayList(Arrays.asList()))
        )));
    }
}

Mathematica, 84 66 64 bytes
Using 1-based indexing.
MapIndexed[Union[#,First/@l~Position~Tr@#2]~Complement~#2&,l=#]&

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


text:
Connecting Gaps with Tetris Pieces
You should write a program or function which given a list of tetris blocks as input outputs or returns the biggest gap between two points in the same height level which the pieces can connect.
The 7 types of tetris pieces are the following:

We will refer to these pieces by the letters I, J, L, O, S, T and Z respectively, referring to their shapes. You can rotate the pieces but cannot mirror them just like in a Tetris game.
Our task is to create an orthogonally connected area (sides connected to sides) from the given pieces. This area should connect (also orthogonally) two unit squares which are at the same height. We should find the biggest possible gap between the two squares which we can bridge.
Detailed examples
With the piece L we can connect a gap of 3
   L
XLLLX

With the piece S we can connect a gap of 2
  SS
XSSX

With the pieces S,S,O we can connect a gap of 7 (Note that we can't connect a gap of 8)
 S
XSSOO SSX
  SOOSS

Input

A string representing the available pieces containing only the uppercase letters I, J, L, O, S, T and Z. Every letter represents a complete tetris piece.
The letters will be in alphabetical order in the string.
The string will be at least one character long.

Output

A single positive integer, the biggest gap connectable with the given pieces.

Examples
Input => Output
OSS  =>  7

LS  =>  5

LZ  =>  6

ZZZZ  =>  10

LLSSS  =>  14

IIJSSSTTZ  =>  28

IISSSSSS  =>  24

OOOSSSSSSSSSSSSTT  =>  45

IJLOSTZ  =>  21

IJLOSTZZZZZZZ  =>  37

IIJLLLOSTT  =>  31

IJJJOOSSSTTZ  =>  35

This is code-golf so the shortest entry wins.

Ahh, I see. I was looking at them as are.

CJam, 53
'[,73>qf{1$e=s':+\+~}:+3*I+O-SZ-JO+m0e>ZS-LO+-e>2+3/-

Try it online
The idea is: assign each of the I, J, ..., Z variables to be the number of occurences of that letter, and calculate string length * 3 + I - O. Then count the number of non-compensated S's or Z's: an S can be compensated by Z, J or O, and a Z can be compensated by S, L or O, and subtract ceil(that number/3), as we lose 1 unit for every 3 S's or Z's.


text:
Count balanced binary strings matching any of a set of masks
A binary string is a string which contains only characters drawn from 01. A balanced binary string is a binary string which contains exactly as many 0s as 1s.
You are given a positive integer n and an arbitrary number of masks, each of which is 2n characters long, and contains only characters drawn from 012. A binary string and a mask match if it is the same length and agrees on the character in every position where the mask doesn't have a 2. E.g. the mask 011022 matches the binary strings 011000, 011001, 011010, 011011.
Given n and the masks as input (separated by newlines), you must output the number of distinct balanced binary strings which match one or more of the masks.
Examples
Input
3
111222
000112
122020
122210
102120

Reasoning

The only balanced binary string matching 111222 is 111000.
The only balanced binary string matching 000112 is 000111.
The balanced binary strings matching 122020 are 111000 (already counted), 110010 and 101010.
The balanced binary strings matching 122210 are 110010 (already counted), 101010 (already counted) and 100110.
The balanced binary strings matching 102120 are 101100 and 100110 (already counted).

So the output should be
6

Input
10
22222222222222222222

Reasoning

There are 20 choose 10 balanced binary strings of length 20.

Output
184756

Winner
The winner will be the one that computes the competition input the fastest, of course treating it the same way as it would any other input. (I use a determined code in order to have a clear winner and avoid cases where different inputs would give different winners. If you think of a better way to find the fastest code, tell me so).
Competition input
http://pastebin.com/2Dg7gbfV

Also, I personally highly prefer https://gist.github.com/ over pastebin, both for aesthetics and future faults.

@AlbertMasclans I think you should reserve the right to change the input. Otherwise, someone can hardcode the output.

It would be useful if you could post a small example in the question, with the expected result, and an explanation. I might just be slow, but I don't quite get the definition. So for the example, since n=30, we're looking for sequences of 30 0s or 30 1s (with 2 being a wildcard) in any row? Can those sequences overlap? For example, if I find a sequence of 32 1s, does that count as 3 sequences, or as a single sequence? What if I find a sequence of 60 1s (entire row)? Is that 1 sequence, 2 sequences, or 31 sequences?

Hope it's clearer now.
In case you'd need the output of some specific sample, ask for it and'll I post it.

So you're asking for the number of unique arrays in this matrix that have equal numbers of 1s and 0s, right?

@ASCIIThenANSI actually yes, that's another way to put it I did not think about.

Can we have some more test data please?

And just as important, the expected output, especially for the larger test cases?

It looks like the number of intersections on the  large test case is tiny (I count 6 total).  This allows a naive program that only checks for pairwise intersections to get the correct output.  In order to make this more challenging, you will want to test on an intersection-heavy case (especially where there are common intersections between three or more sets, not just two).

If you like, I can generate some really evil test cases for you.

@Albert Question: why did blutorange get the accepted answer?  On the competition input, his took around 0.4s, while mine took around 0.002s.  This was fastest-code, no?  (Also, I don't think his program gives correct results for all inputs, in particular ones with many intersections.)

Totally true, I forgot to change it.
Btw, about the evil cases, I found them too. I did myself a code that also does in milliseconds, but takes years with some other arrays (smaller than the example one)

C
If you're not on Linux, or otherwise having trouble compiling, you should probably remove the timing code (clock_gettime).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

long int binomial(int n, int m) {
  if(m > n/2) {
    m = n - m;
  }
  int i;
  long int result = 1;
  for(i = 0; i < m; i++) {
    result *= n - i;
    result /= i + 1;
  }
  return result;
}

typedef struct isct {
  char *mask;
  int p_len;
  int *p;
} isct;

long int mask_intersect(char *mask1, char *mask2, char *mask_dest, int n) {

  int zero_count = 0;
  int any_count = 0;
  int i;
  for(i = 0; i < n; i++) {
    if(mask1[i] == '2') {
      mask_dest[i] = mask2[i];
    } else if (mask2[i] == '2') {
      mask_dest[i] = mask1[i];
    } else if (mask1[i] == mask2[i]) {
      mask_dest[i] = mask1[i];
    } else {
      return 0;
    }
    if(mask_dest[i] == '2') {
      any_count++;
    } else if (mask_dest[i] == '0') {
      zero_count++;
    }
  }
  if(zero_count > n/2 || any_count + zero_count < n/2) {
    return 0;
  }
  return binomial(any_count, n/2 - zero_count);
}

int main() {

  struct timespec start, end;
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);

  int n;
  scanf("%d", &n);
  int nn = 2 * n;

  int m = 0;
  int m_max = 1024;

  char **masks = malloc(m_max * sizeof(char *));

  while(1) {
    masks[m] = malloc(nn + 1);
    if (scanf("%s", masks[m]) == EOF) {
      break;
    }
    m++;
    if (m == m_max) {
      m_max *= 2;
      masks = realloc(masks, m_max * sizeof(char *));
    }
  }

  int i = 1;
  int i_max = 1024 * 128;

  isct *iscts = malloc(i_max * sizeof(isct));

  iscts[0].mask = malloc(nn);
  iscts[0].p = malloc(m * sizeof(int));

  int j;
  for(j = 0; j < nn; j++) {
    iscts[0].mask[j] = '2';
  }
  for(j = 0; j < m; j++) {
    iscts[0].p[j] = j;
  }
  iscts[0].p_len = m;

  int i_start = 0;
  int i_end = 1;
  int sign = 1;

  long int total = 0;

  int mask_bin_len = 1024 * 1024;
  char* mask_bin = malloc(mask_bin_len);
  int mask_bin_count = 0;

  int p_bin_len = 1024 * 128;
  int* p_bin = malloc(p_bin_len * sizeof(int));
  int p_bin_count = 0;

  while (i_end > i_start) {
    for (j = i_start; j < i_end; j++) {
      if (i + iscts[j].p_len > i_max) {
        i_max *= 2;
        iscts = realloc(iscts, i_max * sizeof(isct));
      }
      isct *isct_orig = iscts + j;
      int x;
      int x_len = 0;
      int i0 = i;
      for (x = 0; x < isct_orig->p_len; x++) {
        if(mask_bin_count + nn > mask_bin_len) {
          mask_bin_len *= 2;
          mask_bin = malloc(mask_bin_len);
          mask_bin_count = 0;
        }
        iscts[i].mask = mask_bin + mask_bin_count;
        mask_bin_count += nn;
        long int count =
            mask_intersect(isct_orig->mask, masks[isct_orig->p[x]], iscts[i].mask, nn);
        if (count > 0) {
          isct_orig->p[x_len] = isct_orig->p[x];
          i++;
          x_len++;
          total += sign * count;
        }
      }
      for (x = 0; x < x_len; x++) {
        int p_len = x_len - x - 1;
        iscts[i0 + x].p_len = p_len;
        if(p_bin_count + p_len > p_bin_len) {
          p_bin_len *= 2;
          p_bin = malloc(p_bin_len * sizeof(int));
          p_bin_count = 0;
        }
        iscts[i0 + x].p = p_bin + p_bin_count;
        p_bin_count += p_len;
        int y;
        for (y = 0; y < p_len; y++) {
          iscts[i0 + x].p[y] = isct_orig->p[x + y + 1];
        }
      }
    }

    sign *= -1;
    i_start = i_end;
    i_end = i;

  }

  printf("%lld\n", total);

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);

  int seconds = end.tv_sec - start.tv_sec;
  long nanoseconds = end.tv_nsec - start.tv_nsec;
  if(nanoseconds < 0) {
    nanoseconds += 1000000000;
    seconds--;
  }

  printf("%d.%09lds\n", seconds, nanoseconds);
  return 0;
}

Example cases:
robert@unity:~/c/se-mask$ gcc -O3 se-mask.c -lrt -o se-mask
robert@unity:~/c/se-mask$ head testcase-long
30
210211202222222211222112102111220022202222210122222212220210
010222222120210221012002220212102220002222221122222220022212
111022212212022222222220111120022120122121022212211202022010
022121221020201212200211120100202222212222122222102220020212
112200102110212002122122011102201021222222120200211222002220
121102222220221210220212202012110201021201200010222200221002
022220200201222002020110122212211202112011102220212120221111
012220222200211200020022121202212222022012201201210222200212
210211221022122020011220202222010222011101220121102101200122
robert@unity:~/c/se-mask$ ./se-mask < testcase-long
298208861472
0.001615834s
robert@unity:~/c/se-mask$ head testcase-hard
8
0222222222222222
1222222222222222
2022222222222222
2122222222222222
2202222222222222
2212222222222222
2220222222222222
2221222222222222
2222022222222222
robert@unity:~/c/se-mask$ ./se-mask < testcase-hard
12870
3.041261458s
robert@unity:~/c/se-mask$

(Times are for an i7-4770K CPU at 4.1 GHz.)  Be careful, testcase-hard uses around 3-4 GB of memory.
This is pretty much an implementation of inclusion-exclusion method blutorange came up with, but done so that it will handle intersections of any depth.  The code as written is spending a lot of time on memory allocation, and will get even faster once I optimize the memory management.
I shaved off around 25% on testcase-hard, but the performance on the original (testcase-long) is pretty much unchanged, since not much memory allocation is going on there.  I'm going to tune a bit more before I call it: I think I might be able to get a 25%-50% improvement on testcase-long too.
Mathematica
Once I noticed this was a #SAT problem, I realized I could use Mathematica's built-in SatisfiabilityCount:
AbsoluteTiming[
 (* download test case *)
 input = Map[FromDigits,
   Characters[
    Rest[StringSplit[
      Import["http://pastebin.com/raw.php?i=2Dg7gbfV",
       "Text"]]]], {2}]; n = Length[First[input]];
 (* create boolean function *)
 bool = BooleanCountingFunction[{n/2}, n] @@ Array[x, n] &&
   Or @@ Table[
     And @@ MapIndexed[# == 2 || Xor[# == 1, x[First[#2]]] &, i], {i,
      input}];
 (* count instances *)
 SatisfiabilityCount[bool, Array[x, n]]
]

Output:
{1.296944, 298208861472}

That's 298,208,861,472 masks in 1.3 seconds (i7-3517U @ 1.9 GHz), including the time spent downloading the test case from pastebin.

So I've rewritten this in C... unfortunately it's too fast for me to use gperftools on it!  I'll find some harder test cases before I post tomorrow.

testcase-hard can be completed very quickly if your code looks for masks that can be combined.  If your code does this, then delete every other line (so just the /^2*02*$/ cases remain).  I don't think that case can be optimized.

ruby, pretty fast, but it depends upon the input
Now speed-up by a factor of 2~2.5 by switching from strings to integers.
Usage:
cat <input> | ruby this.script.rb

Eg.
mad_gaksha@madlab ~/tmp $ ruby c50138.rb < c50138.inp2
number of matches: 298208861472
took 0.05726237 s

The number of matches for a single mask a readily calculated by the binomial coefficient. So for example 122020 needs 3 2s filled, 1 0 and 2 1. Thus there are nCr(3,2)=nCr(3,1)=3!/(2!*1!)=3 different binary strings matching this mask.
An intersection between n masks m_1, m_2, ... m_n is a mask q, such that a binary string s matches q only iff it matches all masks m_i.
If we take two masks m_1 and m_2, its intersection is easily computed. Just set m_1[i]=m_2[i] if m_1[i]==2. The intersection between 122020 and 111222 is 111020:
122020 (matched by 3 strings, 111000 110010 101010)
111222 (matched by 1 string, 111000)
111020 (matched by 1 string, 111000)

The two individual masks are matched by 3+1=4 strings, the interesection mask is matched by one string, thus there are 3+1-1=3 unique strings matching one or both masks.
I'll call N(m_1,m_2,...) the number of strings matched all m_i. Applying the same logic as above, we can compute the number of unique strings matched by at least one mask, given by the inclusion exclusion principle and see below as well, like this:
N(m_1) + N(m_2) + ... + N(m_n) - N(m_1,m_2) - ... - N(m_n-1,m_n) + N(m_1,m_2,m_3) + N(m_1,m_2,m_4) + ... N(m_n-2,m_n-1,m_n) - N(m_1,m_2,m_3,m_4) -+ ...

There are many, many, many combinations of taking, say 30 masks out of 200.
So this solution makes the assumption that not many high-order intersections of the input masks exist, ie. most n-tuples of n>2 masks will not have any common matches.
Use the code here, the code at ideone may be out-dated.

Test case 1: number of matches: 6
Test case 2: number of matches: 184756
Test case 3: number of matches: 298208861472
Test case 4: number of matches: 5

I added a function remove_duplicates that can be used to pre-process the input and delete masks m_i such that all strings that match it also match another mask m_j.,For the current input, this actually takes longer as there are no such masks (or not many), so the function isn't applied to the data yet in the code below.
Code:
# factorial table
FAC = [1]
def gen_fac(n)
  n.times do |i|
    FAC << FAC[i]*(i+1)
  end
end

# generates a mask such that it is matched by each string that matches m and n
def diff_mask(m,n)
  (0..m.size-1).map do |i|
    c1 = m[i]
    c2 = n[i]
    c1^c2==1 ? break : c1&c2
  end
end

# counts the number of possible balanced strings matching the mask
def count_mask(m)
  n = m.size/2
  c0 = n-m.count(0)
  c1 = n-m.count(1)
  if c0<0 || c1<0
    0
  else
    FAC[c0+c1]/(FAC[c0]*FAC[c1])
  end
end

# removes masks contained in another
def remove_duplicates(m)
  m.each do |x|
    s = x.join
    m.delete_if do |y|
      r = /\A#{s.gsub(?3,?.)}\Z/
      (!x.equal?(y) && y =~ r) ? true : false
    end
  end
end

#intersection masks of cn masks from m.size masks
def mask_diff_combinations(m,n=1,s=m.size,diff1=[3]*m[0].size,j=-1,&b)
  (j+1..s-1).each do |i|
    diff2 = diff_mask(diff1,m[i])
    if diff2
      mask_diff_combinations(m,n+1,s,diff2,i,&b) if n<s
      yield diff2,n
    end
  end
end

# counts the number of balanced strings matched by at least one mask
def count_n_masks(m)
  sum = 0
  mask_diff_combinations(m) do |mask,i|
    sum += i%2==1 ? count_mask(mask) : -count_mask(mask)
  end
  sum
end

time = Time.now

# parse input
d = STDIN.each_line.map do |line|
  line.chomp.strip.gsub('2','3')
end
d.delete_if(&:empty?)
d.shift
d.map!{|x|x.chars.map(&:to_i)}

# generate factorial table
gen_fac([d.size,d[0].size].max+1)

# count masks
puts "number of matches: #{count_n_masks(d)}"
puts "took #{Time.now-time} s"

This is called the inclusion exclusion principle, but before somebody had pointed me to it I had my own proof, so here it goes. Doing something yourself feels great though.
Let us consider the case of 2 masks, call then 0 and 1, first. We take every balanced binary string and classify it according to which mask(s) it matches. c0 is the number of those that match only mask 0, c1 the nunber of those that match only 1, c01 those that match mask 0 and 1.
Let s0 be the number sum of the number of matches for each mask (they may overlap). Let s1 be the sum of the number of matches for each pair (2-combination) of masks. Let s_i be the sum of the number of matches for each (i+1) combination of masks. The number of matches of n-masks is the number of binary strings matching all masks.
If there are n masks, the desired output is the sum of all c's, ie. c = c0+...+cn+c01+c02+...+c(n-2)(n-1)+c012+...+c(n-3)(n-2)(n-1)+...+c0123...(n-2)(n-1). What the program computes is the alternating sum of all s's, ie. s = s_0-s_1+s_2-+...+-s_(n-1). We wish to proof that s==c.
n=1 is obvious. Consider n=2. Counting all matches of mask 0 gives c0+c01 (the number of strings matching only 0 + those matching both 0 and 1), counting all matches of 1 gives c1+c02. We can illustrate this as follows:
0: c0 c01
1: c1 c10

By definition, s0 = c0 + c1 + c12. s1 is the sum number of matches of each 2-combination of [0,1], ie. all uniqye c_ijs. Keep in mind that c01=c10.
s0 = c0 + c1 + 2 c01
s1 = c01
s = s0 - s1 = c0 + c1 + c01 = c

Thus s=c for n=2.
Now consider n=3.
0  : c0 + c01 + c02 + c012
1  : c1 + c01 + c12 + c012
2  : c2 + c12 + c02 + c012
01 : c01 + c012
02 : c02 + c012
12 : c12 + c012
012: c012

s0 = c0 + c1 + c2 + 2 (c01+c02+c03) + 3 c012
s1 = c01 + c02 + c12 + 3 c012
s2 = c012

s0 = c__0 + 2 c__1 + 3 c__2
s1 =          c__1 + 3 c__2
s2 =                   c__2

s = s0 - s1 + s2 = ... = c0 + c1 + c2 + c01 + c02 + c03 + c012 = c__0 + c__1 + c__2 = c

Thus s=c for n=3. c__i represents the of all cs with (i+1) indices, eg c__1 = c01 for n=2 and c__1 = c01 + c02 + c12 for n==3.
For n=4, a pattern starts to emerge:
0:   c0 + c01 + c02 + c03 + c012 + c013 + c023 + c0123
1:   c1 + c01 + c12 + c13 + c102 + c103 + c123 + c0123
2:   c2 + c02 + c12 + c23 + c201 + c203 + c213 + c0123
3:   c3 + c03 + c13 + c23 + c301 + c302 + c312 + c0123

01:  c01 + c012 + c013 + c0123
02:  c02 + c012 + c023 + c0123
03:  c03 + c013 + c023 + c0123
12:  c11 + c012 + c123 + c0123
13:  c13 + c013 + c123 + c0123
23:  c23 + c023 + c123 + c0123

012:  c012 + c0123
013:  c013 + c0123
023:  c023 + c0123
123:  c123 + c0123

0123: c0123

s0 = c__0 + 2 c__1 + 3 c__2 + 4 c__3
s1 =          c__1 + 3 c__2 + 6 c__3
s2 =                   c__2 + 4 c__3
s3 =                            c__3

s = s0 - s1 + s2 - s3 = c__0 + c__1 + c__2 + c__3 = c

Thus s==c for n=4.
In general, we get binomial coefficients like this (↓ is i, → is j):
   0  1  2  3  4  5  6  .  .  .

0  1  2  3  4  5  6  7  .  .  .
1     1  3  6  10 15 21 .  .  .
2        1  4  10 20 35 .  .  .
3           1  5  15 35 .  .  .
4              1  6  21 .  .  .
5                 1  7  .  .  .
6                    1  .  .  .
.                       .
.                          .
.                             .

To see this, consider that for some i and j, there are:

x = ncr(n,i+1): combinations C for the intersection of (i+1) mask out of n
y = ncr(n-i-1,j-i): for each combination C above, there are y different combinations for the intersection of (j+2) masks out of those containing C
z = ncr(n,j+1): different combinations for the intersection of (j+1) masks out of n

As that may sound confusing, here's the defintion applied to an example. For i=1, j=2, n=4, it looks like this (cf. above):
01:  c01 + c012 + c013 + c0123
02:  c02 + c012 + c023 + c0123
03:  c03 + c013 + c023 + c0123
12:  c11 + c012 + c123 + c0123
13:  c13 + c013 + c123 + c0123
23:  c23 + c023 + c123 + c0123

So here x=6 (01, 02, 03, 12, 13, 23), y=2 (two c's with three indices for each combination), z=4 (c012, c013, c023, c123).
In total, there are x*y coefficients c with (j+1) indices, and there are z different ones, so each occurs x*y/z times, which we call the coefficient k_ij. By simple algebra, we get k_ij = ncr(n,i+1) ncr(n-i-1,j-i) / ncr(n,j+1) = ncr(j+1,i+1).
So the index is given by k_ij = nCr(j+1,i+1) If you recall all the defintions, all we need to show is that the alternating sum of each column gives 1.
The alternating sum s0 - s1 + s2 - s3 +- ... +- s(n-1) can thus be expressed as:
s_j = c__j * ∑［(-1)^(i+j) k_ij］ for i=0..n-1
     = c__j * ∑［(-1)^(i+j) nCr(j+1,i+1)］ for i=0..n-1
     = c__j * ∑［(-1)^(i+j) nCr(j+1,i)］｛i=0..n｝ - (-1)^0 nCr(j+1,0)
     = (-1)^j c__j

s   = ∑［(-1)^j  s_j］ for j = 0..n-1
    = ∑［(-1)^j (-1)^j c__j)］ for j=0..n-1
    = ∑［c__j］ for j=0..n-1
    = c

Thus s=c for all n=1,2,3,...

I am not sure if you are aware, but the method you are applying is http://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle, so you don't have to prove it, if this was what you are trying to do. Also while not needed for the test cases you could eliminate from the groups masks that are completely included in another mask in the group. For example in TC5: 0011 < 2211, 0022 < 0222. I think that this makes the groups no larger than 2*n, though it is still too big in the worst case.

@nutki I hadn't been aware of this, so thanks for the link. Occasionally, proving and thinking about something for oneself is still a nice exercise, though:). As for your suggestion, yes, it had occured to me to do that, but I don't think I'm going to implement it unless a test case is added that requires it to get the result in a reasonable amount of time.

@blutorange did u think to use decision tree ?

I think you mean intersection (matches both masks), not union (matches one or the other mask).

@2012rcampion As in unifying two masks the term union makes sense to me and I xan define that way, but you're right, in the interest of mutual understanding I've chabged. @Agawa001 Can you be more specific? Also, if you've got some good idea to make this faster, feel free to use any ideas from this answer for your program/answer. For now, it's fast enough for the large test case, and if made multi-threaded it should take <0.1s, which is below any meaningful measurement/comparison, so for harder test cases are needed.

@blutorange lol wish i have time for it , its an enticing challenge but , try to use abstract data structures struct , to implement trees that would reduce the overall entry sweeping from n(n+1)/2 until 2*n somtimes

Investigating a little, your intuition about the number of intersections seems correct: there are only 6 intersections in the test case!  (lines 2/191, 23/101, 36/75, 40/124, 144/190, and 178/199)

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_combination.h>

int main (int argc, char *argv[]) {

    printf ("reading\n");
    char buffer[100];
    gets(buffer);
    char n = atoi(buffer);

    char *masks[1000];
    masks[0] = malloc(2 * n * sizeof(char));
    char c,nrows,j,biggestzerorun,biggestonerun,currentzerorun,currentonerun = 0;

    while ((c = getchar()) && c != EOF) {
        if (c == '\n') {
            nrows++;
            if (currentonerun > biggestonerun) {
                biggestonerun = currentonerun;
            }
            if (currentzerorun > biggestzerorun) {
                biggestzerorun = currentzerorun;
            }
            j=currentonerun=currentzerorun=0;
            masks[nrows] = malloc(2 * n * sizeof(char));
        } else if (c == '0') {
            masks[nrows][j++] = 1;
            currentzerorun++;
            if (currentonerun > biggestonerun) {
                biggestonerun = currentonerun;
            }
            currentonerun=0;
        } else if (c == '1') {
            masks[nrows][j++] = 2;
            currentonerun++;
            if (currentzerorun > biggestzerorun) {
                biggestzerorun = currentzerorun;
            }
            currentonerun=0;
        } else if (c == '2') {
            masks[nrows][j++] = 3;
            currentonerun++;
            currentzerorun++;
        }
    }
    if (currentonerun > biggestonerun) {
        biggestonerun = currentonerun;
    }
    if (currentzerorun > biggestzerorun) {
        biggestzerorun = currentzerorun;
    }

    printf("preparing combinations\n");

    int nmatches=0;

    gsl_combination *combination = gsl_combination_calloc(2*n, n);

    printf("entering loop:\n");

    do {
        char vector[2*n];
        char currentindex, previousindex;
        currentonerun = 0;
        memset(vector, 1, 2*n);

        // gsl_combination_fprintf (stdout, combination, "%u ");
        // printf(": ");

        for (char k=0; k<n; k++) {
            previousindex = currentindex;
            currentindex = gsl_combination_get(combination, k);
            if (k>0) {
                if (currentindex - previousindex == 1) {
                    currentonerun++;
                    if (currentonerun > biggestonerun) {
                        goto NEXT;
                    }
                } else {
                    currentonerun=0;
                    if (currentindex - previousindex > biggestzerorun) {
                        goto NEXT;
                    }
                }
            }
            vector[currentindex] = 2;
        }

        for (char k=0; k<=nrows; k++) {
            char ismatch = 1;
            for (char l=0; l<2*n; l++) {
                if (!(vector[l] & masks[k][l])) {
                    ismatch = 0;
                    break;
                }
            }
            if (ismatch) {
                nmatches++;
                break;
            }
        }

        NEXT: 1;

    } while (
        gsl_combination_next(combination) == GSL_SUCCESS
    );

    printf ("RESULT: %i\n", nmatches);

    gsl_combination_free(combination);
    for (; nrows>=0; nrows--) {
        free(masks[nrows]);
    }
}

Good luck getting the big input to run on this - it'll probably take all night to get through approx. 60^30 permutations! Maybe an intermediate sized dataset might be a good idea?


text:
Magic Sequences of length n
A magic sequence is a sequence of non-negative integers x[0..n-1] such that there are exactly x[i] instances of i
For instance, 6,2,1,0,0,0,1,0,0,0 is a magic sequence since there are 6 0's, 2 1’s, and so on.
Write a function which when given n, outputs all magic sequences of length n

The program that can produce the correct output for the highest value of n within 10 seconds win. (All programs are welcome, though)
For example, Alice's program can deal with upto n=15 within 10 seconds while Bob's can deal with upto n=20 within the same time. Bob wins.
Platform: Linux 2.7GHz @ 4 CPUs

Welcome to PPCG! This is a great challenge, but you need a winning criterion. For example, you could say that the winner is the shortest program.

Relevant: Self-descriptive number

@Ypnypn thanks I've added the winning criteria

Sorry, I changed the winning criteria.

Please don't change the winning criterion after answers have been posted. Also, this was much better as a code golf than as fastest code, at least in my opinion.

For fastest code, is there a reasonable approach other than enumerating all sequences and checking for magicness?

@xnor you can start by generating the integer partitions of n and checking if they can be self-descriptive.

@MartinBüttner Good point, I'm seeing some interesting ways to short-circuit the searches now.

What's the smallest  n>5 with a solution not of the form [n-4, 2, 1, ..., 0, 0, 1, 0, 0, 0]?  I've looked up to n=20 and not found one, and wondering if I'm making an error.

Given that xnor has now established that this has a trivial solution, and is therefore not appropriate for fastest code, can we switch it back to code-golf?

This is not appropriate as [tag:fastest-code] - you're only limited by I/O speed.

Python, n≈108
def magic_sequences(n):
    if n==4:
        return (1, 2, 1, 0),(2, 0, 2, 0)
    elif n==5:
        return (2, 1, 2, 0, 0),
    elif n>=7:
        return (n-4,2,1)+(0,)*(n-7)+(1,0,0,0),
    else:
        return ()

This uses the fact, which I'll prove, that the only Magic sequences of length n are:

[1, 2, 1, 0] and  [2, 0, 2, 0] for n=4
[2, 1, 2, 0, 0] for n=5
[n-4, 2, 1, 0, 0, ..., 0, 0, 1, 0, 0, 0] for n>=7

So, for n>=7, one only needs to return a huge tuple. I can do this for up to roughly n=10^8 on my laptop, which is likely limited by memory; any more and it freezes up. (Thanks to trichoplax for the idea of using tuples rather than lists.) Or, if one can instead print a dictionary of nonzero entries, {0:n-4, 1:2, 2:1, (n-4):1}, one can do this for ginormous n.
I prove the uniqueness for n>=7; the other ones can be checked by brute force or casework.
The sum of the entries of l is the total count of all numbers of the list, which is its length n. The list has l[0] zeroes, and so n-l[0] nonzero entries. But by definition l[0] must be nonzero or we get a contradiction, and each of the other nonzero entries is at least 1. This already accounts for a sum of l[0] + (n-l[0]-1)*1 = n-1 out of the overall sum of n. So not counting l[0], there can be at most one 2 and no entry bigger than 2.
But that means the only nonzero entries are l[0], l[1], l[2], and l[l[0]], whose values are at most l[0] and a permutation of 1,1,2, which gives a maximum sum of l[0]+4. Since this sum is n, which is at least 7, we have l[0]>=3, and so l[l[0]]=1. Now, there's at least one 1, which means l[1]>=1, but if l[1]==1 that's another 1, so l[1]>=2, which implies l[1] is the lone 2. This gives l[2]=1, and all the remaining entries are 0, so l[0]=n-4, which completes the solution.

And the language is ...?

@edc65 It looks like python. But I'm not sure.

Python 3, n≈40
def plausible_suffix(l,N):
    if sum(l)>N:
        return False

    pairs = [(N-1-i,l[i]) for i in range(len(l))]

    if sum(i*x for i,x in pairs)>N:
        return False

    num_remaining = N - len(l)

    for index, desired_count in pairs:
        count = l.count(index)
        more_needed = desired_count - count
        if more_needed<0:
            return False
        num_remaining -= more_needed
        if num_remaining<0:
            return False
    return True

plausible_func = plausible_suffix

def generate_magic(N):
    l=[0]
    while l:
        extend = False
        if plausible_func(l,N):
            if len(l)==N:
                yield l[::-1]
            else:
                extend = True
        if extend:
            l.append(0)
        else:
            while l[-1]>=N-2:
                l.pop(-1)
                if not l:raise StopIteration
            l[-1]+=1

n=40 #test parameter

if n>0:
    for x in generate_magic(n):
        print(n,x)

Does a breadth-first search of possible lists, filling in entries from right to left, stopping the search at a suffix if it isn't plausible, which can happen if:

The sum of the entries in the suffix exceeds n (the sum for the whole list must be n)
The weighted sum of i*l[i] in the suffix exceeds n (the sum for the whole list must be n)
Any number appears in the suffix more times that the suffix says it should
The number of remaining unfilled spots is too small to account for all numbers that need to appear more times.

I had original tested prefixes left to right, but that went more slowly.
The outputs up to n=30 are:
4 [1, 2, 1, 0]
4 [2, 0, 2, 0]
5 [2, 1, 2, 0, 0]
7 [3, 2, 1, 1, 0, 0, 0]
8 [4, 2, 1, 0, 1, 0, 0, 0]
9 [5, 2, 1, 0, 0, 1, 0, 0, 0]
10 [6, 2, 1, 0, 0, 0, 1, 0, 0, 0]
11 [7, 2, 1, 0, 0, 0, 0, 1, 0, 0, 0]
12 [8, 2, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0]
13 [9, 2, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
14 [10, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
15 [11, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
16 [12, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
17 [13, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
18 [14, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
19 [15, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
20 [16, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
21 [17, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
22 [18, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
23 [19, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
24 [20, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
25 [21, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
26 [22, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
27 [23, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
28 [24, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
29 [25, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
30 [26, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]

Except for the first three lists [1, 2, 1, 0], [2, 0, 2, 0], [2, 1, 2, 0, 0], there is exactly one list of each length n>6, and it has the form [n-4, 2, 1, ..., 0, 0, 1, 0, 0, 0]. This pattern persists up to at least n=50. I suspect it holds forever, in which case it's trivial to output a huge number of these. Even if not, a mathematical understanding on the possible solutions would greatly speed up a search.

@Ypnypn I've special-cased n=0. I'd missed that we're returning the result for a single n, not counting up n's. This gets me up to n=40.

Pyth - 15 bytes
Uses brute force by all possible sequences of len n and then filters.
f.A.eq/TkYT^UQQ

Full explanation coming soon.
Try it here online.

FYI, the OP changed the winning criterion to fastest code.

Regardless of the winning criterion, here's a 3 byte golf:  fqm/TdQT^UQQ

K, 26 bytes
{f@&{x~(+/x=)'!#x}'f:!x#x}

Like Maltysen's approach, brute force. The heart of the program is a predicate which tests whether a given vector is "magic":
{x~(+/x=)'!#x}

Build an iota vector as long as the input vector (!#x), count the occurrences of each digit ((+/x=)') and compare the result with the input vector (x~). If there's a match, you have a magic sequence.
Unfortunately, this first stab seems to be pretty slow. Testing using Kona on my laptop it takes about 12 seconds to handle n=7. I need to give this a bit more thought.