text:
Narayana-Zidek-Capell numbers
Generate the nth Narayana-Zidek-Capell number given an input n. Fewest bytes win.
f(1)=1, f(n) is the sum of the previous floor(n/2) Narayana-Zidek-Capell terms.
Test Cases:
f(1)=1

f(9)=42

f(14)=1308

f(15)=2605

f(23)=664299

Welcome to Programming Puzzles & Code Golf! This is a nice first challenge. Though it's ultimately up to you, typically we recommend waiting at least a week to accept an answer. Having an accepted answer early on can send a signal to other users that the challenge is more or less over, which discourages them from participating.

Jelly, 11 10 bytes
HĊrµṖß€Sȯ1

Try it online!
Takes n as argument and prints the result.
Explanation
H              divide input by 2
 Ċ             round up to get first n to recurse
  r            inclusive range from that to n
   µ           (chain separator)
    Ṗ          remove n itself from the range
     ß€        call self recursively on each value in the range
       S       sum results
        ȯ1     if sum was zero, return one

Stumbled across this old answer. I found a couple of saves. Firstly the trailing 1 is redundant since the argument will be one in the case it is used. Secondly, we can take the second "half" of the range from zero to n to get the same list of numbers as HĊrµṖ gets us which is ḶŒHṪ - TIO

Ruby, 34 32 bytes
This uses a formula from the OEIS page for the Narayana-Zidek-Cappell numbers.
Edit: Got rid of parentheses using operator precedence with thanks to feersum and Neil.
f=->x{x<4?1:2*f[x-1]-x%2*f[x/2]}

Surely you don't need parentheses for x%2?

Well, not if you put x%2* at least.

@feersum and Neil Thank you both

Previous question edits suggested that the formula was x<2?... this makes it much clearer thanks!

Python 2, 48 42 38 36 bytes
Algorithm taken from the OEIS page. n<3 may be changed to n<4 with no effect. Returns the nth number, where n is a positive integer.
a=lambda n:n<3or 2*a(n-1)-n%2*a(n/2)

Try it online

C, 38
A translation of the OEIS algorithm. There's just not enough C code around here!
f(n){return n<3?:2*f(n-1)-n%2*f(n/2);}

How does n<3?:(...) work?

It's a GCC extension (seems to work in clang too) that evaluates to the conditional itself if the middle expression is missing. See the relevant GCC page and this SO question for more details.

05AB1E, 16 bytes
An iterative solution as 05AB1E doesn't have functions.
X¸sGDN>;ï£Os‚˜}¬

X¸               # initialize a list with 1
  sG          }  # input-1 number of times do
    D            # duplicate current list
     N>;ï£       # take n/2 elements from the list
          O      # sum those elements
           s‚˜   # add at the start of the list
               ¬ # get the first element and implicitly print

Try it online

Python 3, 67 bytes
def f(n):
 x=1,
 for i in range(n):x+=sum(x[-i//2:]),
 print(x[-1])

A function that takes input via argument and prints to STDOUT. This is a direct implementation of the definition.
How it works
def f(n):               Function with input target term index n
 x=1,                   Initialise term list x as tuple (1)
 for i in range(n):...  For all term indices in [0,n-1]...
 x[-i//2:]              ..yield the previous floor(i/2) terms...
 x+=sum(...)            ...and append their sum to x
 print(x[-1])           Print the last term in x, which is the nth term

Try it on Ideone

Pyth, 12 bytes
L|syM>/b2Ub1

Try it online. Test suite.
Defines a function y(n) that returns the nth Narayana-Zidek-Capell-number.

Mathematica, 38 bytes
If[#<4,1,2#0[#-1]-#~Mod~2#0[(#-1)/2]]&

Anonymous function. Takes  as input and returns () as output. Based off of the Ruby solution.

There's no built in?

@Insane No, there's no built-in.

Simply amazing!

Haskell, 34 bytes
f 1=1
f n=sum$f<$>[n-div n 2..n-1]

Usage example: f 14 -> 1308.
A direct implementation of the definition.

Java, 63 Bytes
int z(int n){return n<3?1:n%2>0?(2*z(n-1)-z(n/2)):(2*z(n-1));}

Go, 63 bytes
func f(i int) int{if(i<4){return 1};return 2*f(i-1)-i%2*f(i/2)}

Pretty much a direct port from the C answer

R, 55 bytes
x[1]=1;for(i in 2:10){x[i]=sum(x[i-1:floor(i/2)])};x[9]

Change 10 in the for loop and x[9] to get whichever index the user wants.

Here's a recursive version that is 54 bytes long:
f=function(n)ifelse(n<4,1,2*f(n-1)-n%%2*f(floor(n/2)))

JavaScript, 54 52
f=n=>Math.round(n<3?1:2*f(n-1)-n%2*f(parseInt(n/2)))

Based on the C answer.

Saved 2 bytes by using parseInt instead of Math.floor

PHP, 81 bytes
This is a full program without recursion. A recursive function can be defined in 52 bytes (it might be possible to beat that) but that's just a pretty boring port of sherlock9's answer (and it errors if you ask for f(100) or more) so I'm putting up this longer and more interesting version
<?php for($i=$argv[1];$j=$i;$i--)for(;--$j*2>=$i;)$a[$j]+=$a[$i]?:1;echo$a[1]?:1;

Causes many (O[n]) notices but that's fine.

O(n) notices? Huh?

notices are a non critical error type that don't stop execution and are commonly silenced in production environments. whenever you try to get the value of an undeclared variable or an undefined offset in an array you get a notice. This program tries to get the value of O[n] undefined offsets (and a couple of undeclared variables too) so you get O[n] notices.

Maple, 46 44 bytes
`if`(n<4,1,2*f(n-1)-(n mod 2)*f(floor(n/2)))

Usage:
> f:=n->`if`(n<4,1,2*f(n-1)-(n mod 2)*f(floor(n/2)));
> seq( f(i), i = 1..10 );
  1, 1, 1, 2, 3, 6, 11, 22, 42, 84

R, 63 bytes
f=function(n,a=0)if(n<2)1 else{for(i in n-1:(n%/%2))a=a+f(i);a}

a=0 is added as a default because it saves me two curly brackets. Function recursively calls itself as needed.

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


text:
Walk the labyrinth
Or maybe it's not really a labyrinth, but still.
Rules:

Input is a two-line string, consisting of *, 1, x and X. That string is a labyrinth to walk through. The lines have the equal length.
You could take the input as a string with , (comma) or any convenient separator between these two lines. Or you could take both lines as separate arguments to your function.
Output is the number of steps you have to take to exit the string (last step is the step which moves you out of the string).
You start in the top left corner (the higher line), before the first symbol.
For each step, you move forward by one symbol (from nth to (n+1)th position). Then, depending on the character you step on, the outcome is different. Here's what each char does:

* - nothing. You just step on it normally.
x - once you stepped on it, switch the line, but remain on the same horizontal distance from the beginning. For example, you stepped on the third position of the higher line, and met a lowercase x here. Then you immediately move to the lower line, but again at the third position.
X - switch the line and go to the next position. The example is the same there, but you also move from the third to the forth position (thus you're on the second line at the forth position).
1 - just move forward by yet another position.

Once each character does its job, it's replaced with a space and no longer "works".
Examples follow.

Input:
x
*

As said before, you start before the first symbol of the first line. The first step moves you on letter x and this letter switches you to the second line. The letter x no longer functions as x, but replaced with *. This will be more relevant in the latter examples. You're now on an asterisk on the lower line, and it did nothing to you.
The second step is moving you forward and you exit the string, so the labyrinth is completed, and it took 2 steps.
Output 2.
Input:
xX*
x1*

1st step: you move on x, which moves you on the x of the lower line. Here comes the rule which says that the used character is replaced with asterisk. Then you move back on the first line, but it's no longer x there, since it has been used and became an asterisk. So you move safely on this asterisk and the step is completed (you are now on the first position of the first line).
2nd step: you move on X, it pushes you to the lower line and then pushes you forward. You now reside on the third position of the second line (asterisk), having never visited the second position (which contains 1).
3rd step: you move forward, exiting the string.
Output: 3.

Test cases:

Input:
*1*
xxx

Output: 3. (because 1 makes you jump on the third position). There you never visit the second line, but it's required part of the input.
Input:
*X*1*x
x*1xx*

Output: 4.
Input:
1x1x
***X

Output: 3.
Input:
1*x1xxx1*x
x*x1*11X1x

Output: 6.
Input:
xXXXxxx111*
**xxx11*xxx

Output: 6.

An empty string should not be a valid input, as it's not a two line string

@edc Haha, I'm contradicting myself. Yes, indeed.

"\n\n" is a two line string...

@feersum then I think output should be 1, as you start before the 1st line, then you move forward one step, and then you finish the labyrinth...

Snails, 34 bytes
A^
\1r|\xud|\Xaa7},(\*|\xud=\x)r},

Expanded:
{
    {
        \1 r |
        \x ud |
        \X aa7
    },
    (\* | \x ud =\x)
    r
},

For a path that takes N steps, the program finds one successful match for each traversal of 0 steps, 1 steps, ..., N - 1 steps.

Haskell, 68 66 65 bytes
(a:b)#l@(c:d)|a<'+'=1+b#d|a>'w'=l#('*':b)|a>'W'=d#b|1<2=b#d
_#_=1

Function # takes both lines as separate parameters. Usage example: "1x1x" # "***X" -> 3.
We just have to count the stars * we step on plus 1 for leaving.
(a:b)#l@(c:d)             -- bind: a -> first char of first line
                                   b -> rest of first line
                                   l -> whole second line
                                   c -> first char of second line (never used)
                                   d -> rest of second line
   |a < '+' = 1+b#d       -- stepped on a *, so add 1 and go on
   |a > 'w' = l#('*':b)   -- x switches lines and replaces the x with *
   |a > 'W' = d#b         -- X switch lines and go on
   |1<2     = b#d         -- the rest (-> 1) simply walks forward
_#_=1                     -- base case: the empty string counts 1 for leaving

Edit: @feersum saved a byte. Thanks!

Could you probably provide a working demo (on http://ideone.com it would be convenient), I'm not a Haskell programmer but would like to play with it.

@nicael:  see here

Could you use e.g. a>'a' instead of a=='x' ?

I haven't realized that, but actually empty string is invalid input (since I've stated myself that the input is a two-line string), so you could remove the validation for this edge case :)

@feersum: yes, that works. Thanks!

@nicael: checking the empty string is the base case (and therefore end) of my recursive function, so I cannot omit it.

Thanks for making me aware of the @ =)

JavaScript (ES6), 119
l=>{z=-~l.search`
`,l=[...l+' '];for(n=p=0;(c=l[p%=2*z])>' ';p+=c>'X'?z:c>'1'?z+1:c>'0'?1:(++n,1))l[p]='*';return-~n}

Less golfed
l=>{
  z=1+l.search`\n`;
  l=[...l+' '];
  for( n = p = 0;
       (c=l[p%=2*z])>' ';
       p += c>'X' ? z : c>'1' ? z+1 : c>'0'? 1 : (++n,1) )
    l[p] = '*';
  return 1+n
}

Test

f=l=>{z=-~l.search`
`,l=[...l+' '];for(n=p=0;(c=l[p%=2*z])>' ';p+=c>'X'?z:c>'1'?z+1:c>'0'?1:(++n,1))l[p]='*';return-~n}

[['x\n*',2]
,['xX*\nx1*',3]
,['*1*\nxxx',3]
,['*X*1*x\nx*1xx*',4]
,['1x1x\n***X',3]
,['1*x1xxx1*x\nx*x1*11X1x',6]
,['xXXXxxx111*\n**xxx11*xxx',6]
].forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
  console.log('Test result '+r+(r==k?' OK ':' KO (expected '+k+')')+'\n'+i)
})

TSQL(sqlserver 2012+), 276 bytes
Golfed:
DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'

,@t BIT=0,@c INT=1,@ INT=1WHILE @<LEN(@i)/2SELECT @t-=IIF(a like'[1*]'or'xx'=a+b,0,1),@c+=IIF(a='*'or'xx'=a+b,1,0),@+=IIF(a='x'and'x'>b,0,1)FROM(SELECT SUBSTRING(d,@t*c+@,1)a,SUBSTRING(d,(1-@t)*c+@,1)b FROM(SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x)x PRINT @c

Ungolfed:
DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'

,@t BIT=0,@c INT=1,@ INT=1
WHILE @<LEN(@i)/2
  SELECT
    @t-=IIF(a like'[1*]'or'xx'=a+b,0,1),
    @c+=IIF(a='*'or'xx'=a+b,1,0),
    @ +=IIF(a='x'and'x'>b,0,1)
  FROM
    (
      SELECT
        SUBSTRING(d,@t*c+@,1)a,
        SUBSTRING(d,(1-@t)*c+@,1)b
      FROM
        (SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x
    )x

PRINT @c

Fiddle

JavaScript, 211 bytes
I'm thinking about making a version that shows each step played after each other, displayed on a webpage.
(x,y)=>{t=0;l=0;n=1;while(t<x.length){c=(l?x:y);if(c[t]=='x'){l=!l;if(l){x=x.slice(0,t-2)+'*'+x.slice(t-1);}else{y=y.slice(0,t-2)+'*'+y.slice(t-1);}}if(c[t]=='X'){l=!l;t++;}if(c[t]=='1'){return n}

Used more bytes than I'd hoped to when replacing x with * because of JS immutable Strings. Suggestions to improve are appreciated, especially with the replacement part.

source: Stack Exchange

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

sort: votes


text:
Return the nth digit of the sequence of aliquot series
0. DEFINITIONS
A sequence is a list of numbers.
A series is the sum of a list of numbers.
The set of natural numbers contains all "non-negative integers greater than zero".
A divisor (in this context) of a natural number j is a natural number i, such that j÷i is also a natural number.
1. PREAMBLE
A couple of other questions on this site mention the concept of the aliquot, or the sequence of divisors of a natural number a which are less than a. Determining amicable numbers involves computing the sum of these divisors, called an aliquot sum or aliquot series. Every natural number has its own aliquot sum, although the value of a number's aliquot sum is not necessarily unique to that number. (Exempli gratia, every prime number has an aliquot sum of 1.)
2. CHALLENGE
Given a natural number n, return the nth digit of the sequence of aliquot sums. The first several series in the sequence, starting with the series for 1, are:
{0, 1, 1, 3, 1, 6, 1, 7, 4, 8, 1, 16, 1, 10, 9, 15, 1, 21, 1, 22, 11, 14, 1, 36, 6, 16, 13}

Concatenated, these look like:
0113161748116110915121122111413661613

Input may be zero-indexed or one-indexed, according to your preference. Solutions must be programs or functions capable of returning the 10,000th digit (input up to 9999 or 10000). The shortest working solution wins.
3. TEST CASES
Correct input-output pairs should include, but are not limited to, the following:
   0 or     1    ->    0
   4 or     5    ->    1
  12 or    13    ->    6
9999 or 10000    ->    7

The number preceding the "or" is 0-indexed; the number following is 1-indexed.
Additional test cases may be provided upon request.
4. REFERENCES
OEIS has a list of numbers and their aliquot sums.

Nice first challenge, btw. :)

if the language cant manage 10k chars strings?? (e.g. the awful Oracle SQL 4k limit)is the answer valid if it's the language limit?

@MartinEnder, thanks! And thanks for that link; it was enlightening. Is there anything out there that explains how to treat answers in languages with limitations? I couldn't find anything, but I know that doesn't mean it's not there. :)

I may be being completely thick, but how are the numbers in that series calculated?

@TomCarpenter: For the first element, take all the divisors of 1 that are less than 1, and add them together. (1 is the only divisor of 1, so the first element ends up being zero.) Second element, the divisors of 2 that are less than 2 (only 1 fits this); third, divisors of 3 (still just 1); and so on. The divisors of 4 are {1, 2}, and 1+2==3, so the fourth element is 3. It took me a while to figure it out too ;)

05AB1E, 14 11 10 bytes
Compute n = 9999 in about 15 seconds. Code:
ÌL€Ñ€¨OJ¹è

Explanation:
Ì           # Increment implicit input by 2
 L          # Generate the list [1 .. input + 2]
  €Ñ        # For each, get the divisors
    €¨      # For each, pop the last one out
      O     # Sum all the arrays in the array
       J    # Join them all together
        ¹è  # Get the nth element

Uses the CP-1252 encoding. Try it online!.

Mathematica, 51 bytes
Array[##&@@IntegerDigits[Tr@Divisors@#-#]&,#][[#]]&

An unnamed function which takes and returns an integer and uses 1-based indexing. Handles input 10000 instantly.
Explanation
This is a very straight-forward implementation of the definition, making use of the fact that the first n divisor sums are always enough to determine the nth digit. As usual, the reading order of golfed Mathematica is a bit funny though:
Array[...&,#]...&

This generates a list with all the results of applying the unnamed function on the left to all the values i from 1 to n inclusive.
...Tr@Divisors@#-#...

We start by computing the divisors of i, summing them with Tr and subtracting i itself so that it's just the sum of divisors less than i.
...IntegerDigits[...]...

This turns the result into a list of its decimal digits.
##&@@...

And this removes the "list" head, so that all the digit lists are automatically concatenated in the result of Array. For more details on how ## works, see the "Sequences of arguments" section in this post.
...[[#]]

Finally, we select the nth digit from the result.

Pyth, 26 21 20 15 bytes
@sm`sf!%dTtUdSh

Try it online. Test suite.
Uses 0-based indexing. The program is O(n²) and completes for n = 9999 in about 14 minutes on my 2008 machine.

What's up with that complicated divisor search? f!%dTr1d is much shorter (but also slower)

@Jakube whoops, modified the wrong version for the 20 byte solution.

f!%TYtUT is what I used to have.

@Jakube I changed to that. It's still running for n = 9999, been over 5 mins now :\

Brachylog, 40 bytes
:2-I,?:?:1yrc:Im.;0.
:1e:2f+.
>.>0,?:.%0

This is 1-indexed, takes about 0.15 seconds for N = 100, 15 seconds for N = 1000. I'm currently running for N = 10000, I'll report the run time once it ends (If my estimation is correct, it should take about 8 hours)
Edit: by fixing premature constraints propagation in Brachylog, it now (on a 3 bytes longer code) takes about 2.5 minutes for 10000 but returns an out of global stack error.
Explanation

Main Predicate: Input = N
:2-I,                 I = N - 2
     ?:?:1y           Find the N first valid outputs of predicate 1 with input N
           rc         Reverse and concatenate into a single number
             :Im.     Output is the Ith digit of that number
                 ;    Or (I strictly less than 0)
                  0.  Output is 0

Predicate 1: computes the sum of the divisors
:1e                   Get a number between N and 1
   :2f                Find all valid outputs of predicate 2 with that number as input
      +.              Output is the sum of those outputs

Predicate 2: unifies output with a divisor of the input
>.>0,                 Output is a number between Input and 0
     ?:.%0            Input is divisible by Output

You can allocate more global stack with the -G option. The default is only 128M. You can use for example: swipl -G2G to use 2 GO.

Jelly, 13 11 10 bytes
2 bytes thanks to @Adnan and 1 more thanks to @Dennis.
ÆDṖSDµ€Fị@

Try it online!
Uses 1-based indexing. Completes for n = 10000 in under 2 seconds online.

ÆDṖSDµ€Fị@ saves a byte.

@Dennis so does that apply the € to the entire first chain?

@Pietu1998: Yes, precisely: in general, at parse time, € is applied to chain.pop() if chain else chains.pop(). The newly started chain is empty, so the last finished chain is used instead.

PHP, 90 bytes
0 indexed
<?php for(;strlen($s)<=$a=$argv[1];$s.=$n)for($n=0,$j=++$i;--$j;)$i%$j||$n+=$j;echo$s[$a];

Absolutely not subtle or with a clever way of approaching it at all.
Also, as usual, produces three notices which are ignored.

J, 34 bytes
{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>:

This is zero-indexed and uses the formula below to calculate the divisor sums.

Explanation
{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>:  Input: n
                                >:  Increment n
                             i.@    Create the range [0, 1, ..., n]
    1                       +       Add one to each to get [1, 2, ..., n+1]
          (               )@        For each value
                        q:            Get the prime factors
                   /.~&.              For each group of equal prime factors
                #.~                     Raise the first to the first power, the second
                                        squared and so on, and sum them
             >:@                        Increment that sum
                      &.q:            Reduce the groups using multiplication
           -~                         Subtract the initial value from that sum
       ":@                            Convert each to a string
     <@                               Box each
 [:;                                Unbox each and concatenate the strings
{                                   Select the character from that string at index n
                                    and return it

MATL, 16 15 bytes
:"@@q:\~fsV]vG)

Indexing is 1-based.
The last test case times out in the online compiler, but it does give the correct result with the offline compiler, in about 15 seconds.
Try it online!
:         % Take input n. Push [1 2 ... n]
"         % For each k in [1 2 ... n]
  @       %   Push k
  @q:     %   Push [1 2 ... k-1]
  \       %   Modulo. Zero values correspond to divisors
  ~f      %   Indices of zeros. These are the divisors
  s       %   Sum
  V       %   Convert to string
]         % End for each
v         % Concatenate all stack contents vertically
G)        % Take n-th digit. Implicitly display

Haskell, 52 bytes
(([1..]>>= \n->show$sum[m|m<-[1..n-1],mod n m<1])!!)

Usage example: (([1..]>>= \n->show$sum[m|m<-[1..n-1],mod n m<1])!!) 12-> 6.
It's a direct implementation of the definition: foreach n sum it's divisors and convert it into a string. Concatenate all such strings and pick the element at the requested index. Haskell's laziness takes only as much ns from the infinite list [1..] as needed.

Python 3.5, 103 93 92 bytes:
R=range;A=lambda f:''.join([str(sum([j for j in R(1,i)if i/j%1==0]))for i in R(1,f+1)])[f-1]

Pretty straightforward implementation of method described in post.
Try It Online! (Ideone)
Does not quite finish within the allotted 5 seconds in the online compiler for input 10000, but it does finish on my machine for the same input within about 8.5 seconds.

Husk, 8 bytes
!ṁödΣhḊN

Try it online!

Octave, 71 bytes
This one is Octave only. It won't work in MATLAB. A virtual function is created which works on 1-indexed numbers. It can probably be simplified a bit further. Will have a look this evening.
@(x)c((c=num2str(arrayfun(@(n)sum(b(~rem(n,b=(1:n-1)))),1:x)))~=' ')(x)

You can try online here.
Simply run the command above, prefixed with a= or whatever (just so that you can use it multiple times), and then do a(10000) or whatever. It takes about 7 seconds to calculated that the 10000th digit is a 7.

Java 8, 220 bytes
import java.util.stream.IntStream;
char a(int n){return IntStream.range(1,n+2).map(i->IntStream.range(1,i).filter(k->i%k==0).sum()).mapToObj(Integer::toString).collect(java.util.stream.Collectors.joining("")).charAt(n);}

Well, it's fast at least. It averages 0.3 seconds to get the 9999/10000th element on my machine. It generates only as many aliquot sums as the index you specified. This means the string will be slightly longer than your index in most cases, since some aliquot sums have 2 or more digits, but for the most part, it only generates as long of a string as we need.
Usage:
public static void main(String[] args) {
    System.out.println(a(0));
    System.out.println(a(4));
    System.out.println(a(12));
    System.out.println(a(9999));
}

Ungolfed:
public static void main(String[] args) {
    System.out.println(all(0));
    System.out.println(all(4));
    System.out.println(all(12));
    System.out.println(all(9999));
}

static int aliquotSum(int n) {
    return IntStream.range(1, n).filter(k -> n % k == 0).sum();
}

static IntStream sums(int n) {
    return IntStream.range(1, n + 2).map(i -> aliquotSum(i));
}

static String arraycat(IntStream a) {
    return a.mapToObj(Integer::toString).collect(java.util.stream.Collectors.joining(""));
}

static char all(int index) {
    return arraycat(sums(index)).charAt(index);
}

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


text:
Power Grid Resource Costs
Power Grid Resource Costs
Introduction
In the board game Power Grid, an integral part of the game is the act of buying resources to fuel your power stations. There are four types of resource used in the game (five, if you include renewable energy, but obviously you can't buy resources for that). These are Coal, Oil, Garbage, and Uranium. The resource market looks like this:

1---- | 2---- | 3---- | 4---- | 5---- | 6---- | 7---- | 8---- | 10  | 12
CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   |  U  |  U
OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | 14  | 16
GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   |  U  |  U

When resources are bought, they are taken from the left of the market, where they are cheapest. When new resources are added to the market, they are added from the right. As can be seen, this produces a supply and demand balance - if more resources of a particular type are being bought than are being replenished each round, the price of that resource will rise. Similarly, if it's less, the cost will reduce.
Coal, Oil, and Garbage all scale up in cost at the same rate, while Uranium scales much faster. A single unit of a non-Uranium resource costs 8 - floor((<units available> - 1) / 3). A single unit of Uranium costs 13 - <units available> if there are 5 or more units available, and 18 - (2 * <units available>) otherwise.
For example, at the start of the game there are all 24 units of Coal available to buy. If the first player would like to buy 4 units of Coal, the first three units would cost 1 each, and the 4th would cost 2, making the total cost 5. This leaves 20 units available. If the second player would also like to buy 4 units of Coal, the cost would be (2*2 + 2*3) = 10.
The Challenge
Your challenge is to write a program or function which calculates the cost of buying a given amount of a particular resource, assuming that there is a given amount of that resource present in the market.
Your submission should accept, in any reasonable input format and in any order, the following parameters:

The resource type - guaranteed to be one of [C, O, G, U].
The amount of that resource that is present in the market - guaranteed to be a non-negative integer. If the resource type is not U, it will not be greater than 24. If the resource type is U, it will not be greater than 12.
The amount of that resource that a player would like to buy - guaranteed to be a non-negative integer which is less than or equal to the amount already present in the market.

The output should be the cost of the requested resources.
Additional Rules

The formulae given are for illustrative purposes only, feel free to use any method of calculating the costs you like.
The letter codes for the different resource types (C, O, G, U) may be replaced by their lower case equivalents. You may also replace the letters for numbers, either in the form C=0, O=1, G=2, U=3 or C=1, O=2, G=3, U=4.
This is code-golf, so the smallest submission in bytes will be the winner.
If your submission requires the input in a different order or format than specified in the previous section, you should provide details.

Test cases
Test case format:
resource type, amount in market, amount to buy
> result

Test cases:
C, 24, 4
> 5

C, 20, 4
> 10

O, 3, 3
> 24

U, 1, 1
> 16

C, 1, 1
> 8

G, 0, 0
> 0

O, 10, 7
> 44

U, 12, 4
> 10

G, 11, 4
> 22

Do we assume the inputs are legal, or de we have to handle things like f("O",1,5)?

@Katenkyo No, as detailed in the spec the inputs are guaranteed to be valid. IMO error checking in code golf is tedious so I've done away with it :o)

Perfect, might have missed that in the specs. Gonna do the post for my submission :)

I think there are some errors in the test cases. I double checked and got f(G, 11, 4) = 22 and f(O, 10, 7) = 44.

@Pietu1998 You're absolutely right, not sure how I got that wrong :\ editing now

Just FYI guys, the test case format that I'd previously put in the question was for illustration only, it wasn't intended for you to have to adhere to it. I've edited it now, so you can change up your answers if you want to golf them any more

Javascript (ES6), 71 59 bytes
f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1)

Takes type, market_amount and buy_amount as arguments. type is an integer between 0 and 3.
Demo

f=(t,m,b)=>b&&(t>2?m>4?13-m:18-m*2:9+~(~-m/3))+f(t,m-1,b-1)
function run() { var tests = document.getElementById("tests").value.split("\n"), test, C = 0, O = 1, G = 2, U = 3; console.clear(); for (var test of tests) { console.log(test); console.log("> " + eval(test)); } }
<textarea rows="10" id="tests">f(C, 24, 4)
f(C, 20, 4)
f(O, 3, 3)
f(U, 1, 1)
f(C, 1, 1)
f(G, 0, 0)
f(O, 10, 7)
f(U, 12, 4)
f(G, 11, 4)</textarea><br/><button onclick="run()">Run</button>

Python 3, 71 69 bytes
Thanks to @xnor for -2 bytes
f=lambda r,a,b:b and[8-int(~-a/3),max(18-2*a,13-a)][r>2]+f(r,a-1,b-1)

A function that takes input via argument of the zero-indexed resource type r, the amount available a and the amount to buy b, and returns the cost.
This makes use of the fact that True and False equate to 1 and 0 in Python, allowing the use of Boolean expressions to index into lists.
How it works
f=lambda r,a,b           Function with input resource type r, amount available a and amount
                         to buy b
b and...                 Base case: return 0 if b=0
[8-int(~-a/3),...][r>2]  If not uranium, yield the unit cost 8-floor((a-1)/3)...
max(18-2*a,13-a)         ..else yield the current uranium unit cost
...f(r,a-1,b-1)          Decrement a and b, then pass to function
...+...                  Add the cost of each unit to give the total cost
:...                     Return the above

Try it on Ideone

You can do max(18-2*a,13-a) in place of [18-2*a,13-a][a>4].

Befunge, 142 bytes
&2`#v_&&>:!#v_\:1-3/8\-v
v:&&<   ^-1\ -1p15+g15 <
v>#<v       <
! v5<
# 1:
>^g-
| 81
\ 4\
: *-
4 -1
` .p
# @^15+g15<
>:49+\-   ^
|
>:2*92*\- ^

Try it here! Takes input as 3 integers, where the resource type is 0,1,2,3. Output is an integer.
No idea if this can be golfed any better. There's not that much whitespace, but the newlines probably hurt.

Python 2.7, 85 bytes:
F,G,H=input();B=0;exec"B+=[[18-(2*G),13-G][G>5],8-((G-1)/3)][F!='U'];G-=1;"*H;print B

Based on R. Kap's answer, but you can shave a byte down to 85 by removing the extra / for floor division. Because these are all integers it's automatically floored down to a whole number.

Welcome to PPCG!

Lua, 107 101 Bytes
Recursive function that have to be called with f(resource,stock,buy). resource have to be a number between 0 and 3.
The output is done via the returned value.
Thanks LeakyNun for saving me 6 bytes : (25-y+(y-1)%3)/3 is shorter than 8-math.floor((y-1)/3) by 5 bytes and allow me to gain one more byte due to its placement.
function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end

Ungolfed
function f(x,y,z)                      -- define a function f with 3 parameters
  return z<1                           -- if we don't buy anything else
           and 0                       --   return 0
         or(                           -- else
           x<3                         --   if we're not buying Uranium
             and (25-y+(y-1)%3)/3      --     return 8-floor((stock-1)/3)
           or(y<5                      --   elseif there's less than 5 Uranium left
                and 18-y*2             --     return 18-stock*2
              or 13-y))                --   else return 13-stock
         +f(x,y-1,z-1)                 -- if we bought this iteration
                                       -- add f(resource,stock-1,toBuy-1)
                                       -- to the returned value
end

You can test this code online by copy-pasting the following snippet.
function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end
print(f(1,24,4))
print(f(2,20,4))
print(f(0,10,7))
print(f(3,1,1))
print(f(3,12,4))

@Pietu1998 it's Lua 5.3. I don't know about 5.2, but in 5.3 it won't complain about these when they aren't forming hexadecimal values. for instance, 6and won't work because 6a is an hex value, but 6an isn't.

8-math.floor((y-1)/3) is really (25-y+(y-1)%3)/3

Python 2.7, 86 bytes:
F,G,H=input();B=0;exec"B+=[[18-(2*G),13-G][G>5],8-((G-1)//3)][F!='U'];G-=1;"*H;print B

Takes input by an array in the format [resource type, units available, units to purchase]. Output is an integer. Will try to golf more over time.
Try It Online! (Ideone)


text:
Latin square compression
A Latin square is a square that has no repeated symbols in the rows or columns:.
13420
21304
32041
04213
40132

And as many Sudoku players know, you don't need all of the numbers to deduce the remaining numbers.
Your challenge is to compress a Latin square into as few bytes as possible.  You need to provide one or two program(s) that compresses/decompresses.
Various info:

The numbers used will always be 0..N-1, where N is the length of the square's edge, and N<=25
On decompression, the latin square must be identical to the input.
Your program(s) should be able to (de)compress any latin square (within the maximum square size), not just the ones I've provided.  Compression ratios should be similar as well.
You must actually run the compression and decompressor to obtain your score (No end-of-universe runtimes)

The test cases can be found on github.  Your score is total size of compressed test cases.
EDIT: As of 20:07 on July 7th, I updated the test cases (in order to fix a generation issue).  Please rerun your program on the new test cases.  Thanks Anders Kaseorg.

"A Latin square is a square that has no repeated symbols in the rows or columns." I suppose there's also the requirement that only symbols 0 to n-1 are used?

Well, by definition, any symbol could be used, but my test cases just happen to use 0 though n-1 :)

Similar: http://codegolf.stackexchange.com/questions/41523/sudoku-compression

@NathanMerrill well, the point was only being allowed to use n different symbols. :P

Can multibyte characters be used?

@DavidC It shouldn't matter, as the size is measured in bytes.

Does the output have to be the same every time the program is ran on the same input, or can we use randomness?

@Loovjo randomness is fine.

What's to stop you hard-coding the test cases and compressing them to 1 byte, total score 25 bytes, and fitting the "compressing/decompressing any square" by leaving others unchanged?

@TessellatingHeckler fixed.

One of the answers encodes the output in bits. Is that allowed?

@Dennis AFAIK, we allow for any encoding.  It sounds like a meta question to me.

The default for code golf is bytes, but since this isn't code golf, I'd say its up to you.

I'm ok with bit encoding.  If somebody manages to encode their answer in 1 less bit, more power to them.

19 of your 25 test cases (all those except 4, 6, 8, 10, 12, 14) were generated by permuting the rows and columns of the trivial Latin square whose (i, j) entry is i + j mod n. This makes them very easy to compress much more than a random Latin square. Although your rules say we should have similar compression ratios for all Latin squares, this might be easy to break by accident. The test cases should be more representative.

It turns out that SageMath has a built in Latin square generator  (documentation), because of course it does. Run it on SageMathCell.

@AndersKaseorg nice investigation.  You are correct in your assumption of permutation (the site I used only did it via permutation at sizes higher than 15).  I'll check out your link

What does "within the maximum square size" mean? Up to size 25, the maximum of any of the test cases? (I assume so.)

@DavidConrad correct.

FWIW, at the end of this XKCD forum post is some Python 2 code I wrote a few years ago that generates random Latin Squares. It's reasonably fast (for Python): it can do an order 60 square in under 30 seconds on my old 2GHz machine, which is considerably faster than an Exact Cover algorithm. It can display the grid in numeric form (with 1-based indices) or in alphabetic string form; it can also output the grid as a PPM image.

@PM2Ring An approach based on completing rectangles to squares almost certainly cannot yield a uniform distribution, because different rectangles can be completed to squares in different numbers of ways. See Generate Random Latin Squares. SageMath uses the Jacobson and Matthews (1996) algorithm.

@AndersKaseorg: Ah, ok. FWIW, I wasn't implying that my code gives a uniform distribution, just that the squares it makes are more random than those obtained by randomly permuting rows & columns (& symbols) of a trivial Latin Square. But thanks for that info, and thanks for looking at my code.

Python, 1281.375 1268.625 bytes
We encode the Latin square one “decision” at a time, where each decision is of one of these three forms:

which number goes in row i, column j;
in row i, which column the number k goes in;
in column j, which row the number k goes in.

At each step, we make all the logical inferences we can based on previous decisions, then pick the decision with the smallest number of possible choices, which therefore take the smallest number of bits to represent.
The choices are provided by a simple arithmetic decoder (div/mod by the number of choices).  But that leaves some redundancy in the encoding: if k decodes to a square where the product of all the numbers of choices was m, then k + m, k + 2⋅m, k + 3⋅m, … decode to the same square with some leftover state at the end.
We take advantage of this redundancy to avoid explicitly encoding the size of the square.  The decompressor starts by trying to decode a square of size 1.  Whenever the decoder finishes with leftover state, it throws out that result, subtracts m from the original number, increases the size by 1, and tries again.
import numpy as np

class Latin(object):
    def __init__(self, size):
        self.size = size
        self.possible = np.full((size, size, size), True, dtype=bool)
        self.count = np.full((3, size, size), size, dtype=int)
        self.chosen = np.full((3, size, size), -1, dtype=int)

    def decision(self):
        axis, u, v = np.unravel_index(np.where(self.chosen == -1, self.count, self.size).argmin(), self.count.shape)
        if self.chosen[axis, u, v] == -1:
            ws, = np.rollaxis(self.possible, axis)[:, u, v].nonzero()
            return axis, u, v, list(ws)
        else:
            return None, None, None, None

    def choose(self, axis, u, v, w):
        t = [u, v]
        t[axis:axis] = [w]
        i, j, k = t
        assert self.possible[i, j, k]
        assert self.chosen[0, j, k] == self.chosen[1, i, k] == self.chosen[2, i, j] == -1

        self.count[1, :, k] -= self.possible[:, j, k]
        self.count[2, :, j] -= self.possible[:, j, k]
        self.count[0, :, k] -= self.possible[i, :, k]
        self.count[2, i, :] -= self.possible[i, :, k]
        self.count[0, j, :] -= self.possible[i, j, :]
        self.count[1, i, :] -= self.possible[i, j, :]
        self.count[0, j, k] = self.count[1, i, k] = self.count[2, i, j] = 1
        self.possible[i, j, :] = self.possible[i, :, k] = self.possible[:, j, k] = False
        self.possible[i, j, k] = True
        self.chosen[0, j, k] = i
        self.chosen[1, i, k] = j
        self.chosen[2, i, j] = k

def encode_sized(size, square):
    square = np.array(square, dtype=int)
    latin = Latin(size)
    chosen = np.array([np.argmax(square[:, :, np.newaxis] == np.arange(size)[np.newaxis, np.newaxis, :], axis=axis) for axis in range(3)])
    num, denom = 0, 1
    while True:
        axis, u, v, ws = latin.decision()
        if axis is None:
            break
        w = chosen[axis, u, v]
        num += ws.index(w)*denom
        denom *= len(ws)
        latin.choose(axis, u, v, w)
    return num

def decode_sized(size, num):
    latin = Latin(size)
    denom = 1
    while True:
        axis, u, v, ws = latin.decision()
        if axis is None:
            break
        if not ws:
            return None, 0
        latin.choose(axis, u, v, ws[num % len(ws)])
        num //= len(ws)
        denom *= len(ws)
    return latin.chosen[2].tolist(), denom

def compress(square):
    size = len(square)
    assert size > 0
    num = encode_sized(size, square)
    while size > 1:
        size -= 1
        square, denom = decode_sized(size, num)
        num += denom
    return '{:b}'.format(num + 1)[1:]

def decompress(bits):
    num = int('1' + bits, 2) - 1
    size = 1
    while True:
        square, denom = decode_sized(size, num)
        num -= denom
        if num < 0:
            return square
        size += 1

total = 0
with open('latin_squares.txt') as f:
    while True:
        square = [list(map(int, l.split(','))) for l in iter(lambda: next(f), '\n')]
        if not square:
            break

        bits = compress(square)
        assert set(bits) <= {'0', '1'}
        assert square == decompress(bits)
        print('Square {}: {} bits'.format(len(square), len(bits)))
        total += len(bits)

print('Total: {} bits = {} bytes'.format(total, total/8.0))

Output:
Square 1: 0 bits
Square 2: 1 bits
Square 3: 3 bits
Square 4: 8 bits
Square 5: 12 bits
Square 6: 29 bits
Square 7: 43 bits
Square 8: 66 bits
Square 9: 94 bits
Square 10: 122 bits
Square 11: 153 bits
Square 12: 198 bits
Square 13: 250 bits
Square 14: 305 bits
Square 15: 363 bits
Square 16: 436 bits
Square 17: 506 bits
Square 18: 584 bits
Square 19: 674 bits
Square 20: 763 bits
Square 21: 877 bits
Square 22: 978 bits
Square 23: 1097 bits
Square 24: 1230 bits
Square 25: 1357 bits
Total: 10149 bits = 1268.625 bytes

I'm trying this code at ideone, but it just gives runtime errors. I modified it using stdin instead of file f. http://ideone.com/fKGSQd

@edc65 It doesn't work because Ideone's NumPy is outdated.

@edc65 Ideone has NumPy 1.8.2 which is too old for np.stack(). In this case it can be replaced with np.array([…]), and I have done so in the current version.

hmmm. are all the squares stored in one byte stream? is the information about their size also stored, or the decoder assumes that they are of size 1,2,3,… etc?

@SargeBorsch Each square is compressed to a separate bitstream. The decompressor recovers the square size unambiguously from the bit stream, using the algorithm I described. No assumption is used.

Python 3, 10772 bits (1346.5 bytes)
def compress(rows):
    columns = list(zip(*rows))
    size = len(rows)
    symbols = range(size)
    output = size - 1
    weight = 25
    for i in symbols:
        for j in symbols:
            choices = set(rows[i][j:]) & set(columns[j][i:])
            output += weight * sorted(choices).index(rows[i][j])
            weight *= len(choices)
    return bin(output + 1)[3:]

def decompress(bitstring):
    number = int('1' + bitstring, 2) - 1
    number, size = divmod(number, 25)
    size += 1
    symbols = range(size)
    rows = [[None] * size for _ in symbols]
    columns = [list(column) for column in zip(*rows)]
    for i in symbols:
        for j in symbols:
            choices = set(symbols) - set(rows[i]) - set(columns[j])
            number, index = divmod(number, len(choices))
            rows[i][j] = columns[j][i] = sorted(choices)[index]
    return rows

Takes 0.1 seconds to compress and decompress the combined test cases.
Verify the score on Ideone.

Woah, care to explain?

In a nutshell, the compressor travels through the square in reading order, keeping track of the symbols that already appeared in that row and column, and arithmetically encoding the index of the symbol in the ascending list of possible symbols. I'll add a detailed explanation after cleaning my code up a bit and testing if bijective base 256 saves any bytes.

I'm not completety sure what your code is doing, but isn't it possible to leave the last line out and solve it while decompressing?

@TuukkaX When there's only one possible symbol len(possible) is 1 and possible.index(rows[i][j]) is 0, so that symbol is encoded at no cost.

Yay, the new test cases saved 6 bits. :)

@Dennis I understand how you are coming up with the index in the possible symbols.  However, I'm not sure what your "arithmetic encoder" is doing.  My naive way would simply to store the numbers into prime powers (2^A3^B5^C...), but I'm guessing yours is smaller.

MATLAB, 3'062.5 2'888.125 bytes
This approach just ditches the last row and the last column of the square, and converts each entry into words of a certain bit depth. The bit depth is chosen minimal for the given size square. (Suggestion by @KarlNapf) These words are just appended to each other.  Decompression is just the reverse.
The sum for all the test cases is 23'105 bits or 2'888.125 bytes. (Still holds for the updated test cases, as the size of my outputs is only dependent of the size of the input.)
function bin=compress(a)
%get rid of last row and column:
s=a(1:end-1,1:end-1);
s = s(:)';
bin = [];
%choose bit depth:
bitDepth = ceil(log2(numel(a(:,1))));
for x=s;
    bin = [bin, dec2bin(x,bitDepth)];
end
end

function a=decompress(bin)
%determine bit depth
N=0;
f=@(n)ceil(log2(n)).*(n-1).^2;
while f(N)~= numel(bin)
    N=N+1;
end
bitDepth = ceil(log2(N));
%binary to decimal:
assert(mod(numel(bin),bitDepth)==0,'invalid input length')
a=[];
for k=1:numel(bin)/bitDepth;
    number = bin2dec([bin(bitDepth*(k-1) + (1:bitDepth)),' ']);
    a = [a,number];
end
n = sqrt(numel(a));
a = reshape(a,n,n);
disp(a)
%reconstruct last row/column:
n=size(a,1)+1;
a(n,n)=0;%resize
%complete rows:
v = 0:n-1;
for k=1:n
    a(k,n) = setdiff(v,a(k,1:n-1));
    a(n,k) = setdiff(v,a(1:n-1,k));
end
end

You could compress a little more by using a variable bitrate, like forn=9..16 4 bits are enough.

@KarlNapf How do you discriminate the different length words then? As far as I know you then need additional prefixes, don't you?

Not variable inside one compression, more like depending on the size of the square. If n>16 then use 5 bits fixed, if 8<n<=16 use 4 bits fixed and so on.

Oh right this makes sense, thank you!

Why are you using ' instead of , for a thousands separator?

For the same reason you're doing it the other way around, it's probobably the way you're used to. =)

J, 2444 bytes
Relies on the builtin A. to convert to and from a permutation of integers [0, n) and a permutation index.
Compress, 36 bytes
({:a.)joinstring<@(a.{~255&#.inv)@A.

The input is a 2d array representing the Latin square. Each row is converted to a permutation index, and that index is converted to a list of base 255 digits and replaced with an ASCII value. Each string is then joined using the ASCII character at 255.
Decompress, 45 bytes
[:(A.i.@#)[:(_&,(255&#.&x:);._1~1,255&=)u:inv

Splits the input string at each ASCII value of 255, and parse each group as base 255 digits. Then using the number of groups, create a list of integers [0, length) and permute it according to each index and return it as a 2d array.

Python, 6052 4521 3556 bytes
compress takes the square as a multiline string, just like the examples and returns a binary string, whereas decompress does the opposite.
import bz2
import math

def compress(L):
 if L=="0":
  C = []
 else:
  #split elements
  elems=[l.split(',') for l in L.split('\n')]
  n=len(elems)
  #remove last row and col
  cropd=[e[:-1] for e in elems][:-1]
  C = [int(c) for d in cropd for c in d]

 #turn to string
 B=map(chr,C)
 B=''.join(B)

 #compress if needed
 if len(B) > 36:
  BZ=bz2.BZ2Compressor(9)
  BZ.compress(B)
  B=BZ.flush()

 return B

def decompress(C):

 #decompress if needed
 if len(C) > 40:
  BZ=bz2.BZ2Decompressor()
  C=BZ.decompress(C)

 #return to int and determine length
 C = map(ord,C)
 n = int(math.sqrt(len(C)))
 if n==0: return "0"

 #reshape to list of lists
 elems = [C[i:i+n] for i in xrange(0, len(C), n)]

 #determine target length
 n = len(elems[0])+1
 L = []
 #restore last column
 for i in xrange(n-1):
  S = {j for j in range(n)}
  L.append([])
  for e in elems[i]:
   L[i].append(e)
   S.remove(e)
  L[i].append(S.pop())
 #restore last row
 L.append([])
 for col in xrange(n):
  S = {j for j in range(n)}
  for row in xrange(n-1):
   S.remove(L[row][col])
  L[-1].append(S.pop())
 #merge elements
 orig='\n'.join([','.join([str(e) for e in l]) for l in L])
 return orig

Remove the last row+column and zip the rest.

Edit1: well base64 does not seem necessary
Edit2: now converting the chopped table into a binary string and compress only if necessary

Python3 - 3,572 3,581 bytes
from itertools import *
from math import *

def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
    if isinstance(x,complex):
        return (int2base(x.real,b,alphabet) , int2base(x.imag,b,alphabet))
    if x<=0:
        if x==0:return alphabet[0]
        else:return  '-' + int2base(-x,b,alphabet)
    rets=''
    while x>0:
        x,idx = divmod(x,b)
        rets = alphabet[idx] + rets
    return rets

def lexicographic_index(p):
    result = 0
    for j in range(len(p)):
        k = sum(1 for i in p[j + 1:] if i < p[j])
        result += k * factorial(len(p) - j - 1)
    return result

def getPermutationByindex(sequence, index):
    S = list(sequence)
    permutation = []
    while S != []:
        f = factorial(len(S) - 1)
        i = int(floor(index / f))
        x = S[i]
        index %= f
        permutation.append(x)
        del S[i]
    return tuple(permutation)

alphabet = "abcdefghijklmnopqrstuvwxyz"

def dataCompress(lst):
    n = len(lst[0])

    output = alphabet[n-1]+"|"

    for line in lst:
        output += "%s|" % int2base(lexicographic_index(line), 36)

    return output[:len(output) - 1]

def dataDeCompress(data):
    indexes = data.split("|")
    n = alphabet.index(indexes[0]) + 1
    del indexes[0]

    lst = []

    for index in indexes:
        if index != '':
            lst.append(getPermutationByindex(range(n), int(index, 36)))

    return lst

dataCompress takes a list of integer tuples and returns a string.
dateDeCompress takes a string and returns a list of integer tuples.
In short, for each line, this program takes that lines permutation index and saves it in base 36. Decompressing takes a long time with big inputs but compression is really fast even on big inputs.
Usage:
dataCompress([(2,0,1),(1,2,0),(0,1,2)])
result: c|4|3|0
dataDeCompress("c|4|3|0")
result: [(2, 0, 1), (1, 2, 0), (0, 1, 2)]

You'd probably get a lot better runtime if you didn't wrap your permutations calls in list calls - permutations returns a generator, which lazily generates all the permutations, but if you try to make it into a list, it eagerly generates all the permutations, which takes a very long time.

Could you explain a bit better how to use your code?

@Mego Sure, maybe I'll implement the lazy evaluation also, although it's still fairly uncomputable.

Determining the lexicographical index of a permutation can be done in O(n) time, rather than the O(n!) brute-force approach of checking all the permutations.

@Mego Wow! I can finally calculate my score with the method you provided, thanks! :D

@TuukkaX have you successfully decompressed the latin square of size 25?

@NathanMerrill I haven't, no :/ But I figured that this still competes, since I have ran my program to obtain my score: "You must actually run your program to obtain your score...".

You have to run both parts, sorry.  I'll make it clearer.

Why is this non-competing?

@Dennis OP edited the question, so that I must also run the decompressor. Sadly, my decompressor is so slow, that I think I'm not able to run it in a reasonable time. I might just start the decompression algorithm, and if it finishes, this becomes competing again.

@Dennis Nevermind, memory runs out. Only way I'd get this solution to compete again would to make a workaround for the decompression, or if someone with a good computer would run the last testcase :D

I tried running your code on my machine, but something seems to have messed up the indentation. At least rets='' and the following loop are out of place.

@Dennis Fixed. I have to manually cut & paste tabulations to each line, since stack exchange formats my code wrong :/

Thought that I would save bytes by taking the permutation index of the whole board, appears that the last test case (whole board) permutation index is...1478 bytes with base 10 representation. The last test case x4 takes 7411 bytes.

There's also an efficient method for computing a permutation given its index.

@Mego Thanks again! Back in the competition :D

Python 3, 1955 bytes
Yet another one that uses permutation indices...
from math import factorial

test_data_name = 'latin_squares.txt'

def grid_reader(fname):
    ''' Read CSV number grids; grids are separated by empty lines '''
    grid = []
    with open(fname) as f:
        for line in f:
            line = line.strip()
            if line:
                grid.append([int(u) for u in line.split(',') if u])
            elif grid:
                yield grid
                grid = []
    if grid:
        yield grid

def show(grid):
    a = [','.join([str(u) for u in row]) for row in grid]
    print('\n'.join(a), end='\n\n')

def perm(seq, base, k):
    ''' Build kth ordered permutation of seq '''
    seq = seq[:]
    p = []
    for j in range(len(seq) - 1, 0, -1):
        q, k = divmod(k, base)
        p.append(seq.pop(q))
        base //= j
    p.append(seq[0])
    return p

def index(p):
    ''' Calculate index number of sequence p,
        which is a permutation of range(len(p))
    '''
    #Generate factorial base code
    fcode = [sum(u < v for u in p[i+1:]) for i, v in enumerate(p[:-1])]

    #Convert factorial base code to integer
    k, base = 0, 1
    for j, v in enumerate(reversed(fcode), 2):
        k += v * base
        base *= j
    return k

def encode_latin(grid):
    num = len(grid)
    fbase = factorial(num)

    #Encode grid rows by their permutation index,
    #in reverse order, starting from the 2nd-last row
    codenum = 0
    for row in grid[-2::-1]:
        codenum = codenum * fbase + index(row)
    return codenum

def decode_latin(num, codenum):
    seq = list(range(num))
    sbase = factorial(num - 1)
    fbase = sbase * num

    #Extract rows
    grid = []
    for i in range(num - 1):
        codenum, k = divmod(codenum, fbase)
        grid.append(perm(seq, sbase, k))

    #Build the last row from the missing element of each column
    allnums = set(seq)
    grid.append([allnums.difference(t).pop() for t in zip(*grid)])
    return grid

byteorder = 'little'

def compress(grid):
    num = len(grid)
    codenum = encode_latin(grid)
    length = -(-codenum.bit_length() // 8)
    numbytes = num.to_bytes(1, byteorder)
    codebytes = codenum.to_bytes(length, byteorder)
    return numbytes + codebytes

def decompress(codebytes):
    numbytes, codebytes= codebytes[:1], codebytes[1:]
    num = int.from_bytes(numbytes, byteorder)
    if num == 1:
        return [[0]]
    else:
        codenum = int.from_bytes(codebytes, byteorder)
        return decode_latin(num, codenum)

total = 0
for i, grid in enumerate(grid_reader(test_data_name), 1):
    #show(grid)
    codebytes = compress(grid)
    length = len(codebytes)
    total += length
    newgrid = decompress(codebytes)
    ok = newgrid == grid
    print('{:>2}: Length = {:>3}, {}'.format(i, length, ok))
    #print('Code:', codebytes)
    #show(newgrid)

print('Total bytes: {}'.format(total))

output
 1: Length =   1, True
 2: Length =   1, True
 3: Length =   2, True
 4: Length =   3, True
 5: Length =   5, True
 6: Length =   7, True
 7: Length =  11, True
 8: Length =  14, True
 9: Length =  20, True
10: Length =  26, True
11: Length =  33, True
12: Length =  41, True
13: Length =  50, True
14: Length =  61, True
15: Length =  72, True
16: Length =  84, True
17: Length =  98, True
18: Length = 113, True
19: Length = 129, True
20: Length = 147, True
21: Length = 165, True
22: Length = 185, True
23: Length = 206, True
24: Length = 229, True
25: Length = 252, True
Total bytes: 1955

Java, 2310 bytes
We convert each row of the square to a number representing which lexicographic permutation it is using factoradic numbers, also known as a factorial number system, which is useful for numbering permutations.
We write the square to a binary file where the first byte is the size of the square, and then each row has one byte for the number of bytes in the binary representation of a Java BigInteger, followed by the bytes of that BigInteger.
To reverse the process and decompress the square we read the size back and then each BigInteger, and use that number to generate each row of the square.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Latin {
    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("java Latin {-c | -d} infile outfile");
        } else if (args[0].equals("-c")) {
            compress(args[1], args[2]);
        } else if (args[0].equals("-d")) {
            decompress(args[1], args[2]);
        } else {
            throw new IllegalArgumentException(
                "Invalid mode: " + args[0] + ", not -c or -d");
        }
    }

    public static void compress(String filename, String outname) {
        try (BufferedReader br = Files.newBufferedReader(Paths.get(filename))) {
            try (OutputStream os =
                    new BufferedOutputStream(new FileOutputStream(outname))) {
                String line = br.readLine();
                if (line == null) return;
                int size = line.split(",").length;
                if (size > 127) throw new ArithmeticException(
                    "Overflow: square too large");
                Permutor perm = new Permutor(size);
                os.write((byte) size); // write size of square

                do {
                    List<Integer> nums = Arrays.stream(line.split(","))
                        .map(Integer::new)
                        .collect(Collectors.toList());
                    byte[] bits = perm.which(nums).toByteArray();
                    os.write((byte) bits.length); // write length of bigint
                    os.write(bits); // write bits of bigint
                } while ((line = br.readLine()) != null);
            }
        } catch (IOException e) {
            System.out.println("Error compressing " + filename);
            e.printStackTrace();
        }
    }

    public static void decompress(String filename, String outname) {
        try (BufferedInputStream is =
                new BufferedInputStream(new FileInputStream(filename))) {
            try (BufferedWriter bw =
                    Files.newBufferedWriter(Paths.get(outname))) {
                int size = is.read(); // size of latin square
                Permutor perm = new Permutor(size);
                for (int i = 0; i < size; ++i) {
                    int num = is.read(); // number of bytes in bigint
                    if (num == -1) {
                        throw new IOException(
                            "Unexpected end of file reading " + filename);
                    }
                    byte[] buf = new byte[num];
                    int read = is.read(buf); // read bits of bigint into buf
                    if (read != num) {
                        throw new IOException(
                            "Unexpected end of file reading " + filename);
                    }
                    String row = perm.nth(new BigInteger(buf)).stream()
                        .map(Object::toString)
                        .collect(Collectors.joining(","));
                    bw.write(row);
                    bw.newLine();
                }
            }
        } catch (IOException e) {
            System.out.println("Error reading " + filename);
            e.printStackTrace();
        }
    }
}

Permutor is adapted from a class I wrote a few years ago to work with permutations:
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.math.BigInteger;
import static java.math.BigInteger.ZERO;
import static java.math.BigInteger.ONE;

public class Permutor {
    private final List<Integer> items;

    public Permutor(int n) {
        items = new ArrayList<>();
        for (int i = 0; i < n; ++i) items.add(i);
    }

    public BigInteger size() {
        return factorial(items.size());
    }

    private BigInteger factorial(int x) {
        BigInteger f = ONE;
        for (int i = 2; i <= x; ++i) {
            f = f.multiply(BigInteger.valueOf(i));
        }
        return f;
    }

    public List<Integer> nth(long n) {
        return nth(BigInteger.valueOf(n));
    }

    public List<Integer> nth(BigInteger n) {
        if (n.compareTo(size()) > 0) {
            throw new IllegalArgumentException("too high");
        }
        n = n.subtract(ONE);
        List<Integer> perm = new ArrayList<>(items);
        int offset = 0, size = perm.size() - 1;
        while (n.compareTo(ZERO) > 0) {
            BigInteger fact = factorial(size);
            BigInteger mult = n.divide(fact);
            n = n.subtract(mult.multiply(fact));
            int pos = mult.intValue();
            Integer t = perm.get(offset + pos);
            perm.remove((int) (offset + pos));
            perm.add(offset, t);
            --size;
            ++offset;
        }
        return perm;
    }

    public BigInteger which(List<Integer> perm) {
        BigInteger n = ONE;
        List<Integer> copy = new ArrayList<>(items);
        int size = copy.size() - 1;
        for (Integer t : perm) {
            int pos = copy.indexOf(t);
            if (pos < 0) throw new IllegalArgumentException("invalid");
            n = n.add(factorial(size).multiply(BigInteger.valueOf(pos)));
            copy.remove((int) pos);
            --size;
        }
        return n;
    }
}

Usage:
With a Latin square in latin.txt, compress it:
java Latin -c latin.txt latin.compressed

And decompress it:
java Latin -d latin.compressed latin.decompressed


text:
Unzip some numbers
Your task is to create a program or function that generates a zipper with a length of 10 lines. Each line of the zipper is represented by two dashes --:
--
--
--
--
--
--
--
--
--
--

The program/function will take a percentage (divisible by 10) as input, and the output will be the zipper "unzipped" (dashes separated) from the top by the percentage, revealing the 1-indexed, lowest level repeated 2 times, with all prior levels repeated 4, 6, 8, ...etc. times, while keeping the bottom of the zipper centered.
Examples
>>10%
-11-
 --
 --
 --
 --
 --
 --
 --
 --
 --

>>50%
-1111111111-
 -22222222-
  -333333-
   -4444-
    -55-
     --
     --
     --
     --
     --

>>100%
-11111111111111111111-
 -222222222222222222-
  -3333333333333333-
   -44444444444444-
    -555555555555-
     -6666666666-
      -77777777-
       -888888-
        -9999-
         -10-

The input (percentage) can be formatted however you like (50%, .5, 50, 5 [zero implied], etc), and it will always be in the range of 0 to 100 and divisible by 10. The spacing in the examples must be preserved in your output.

May the input ever be 0%? Are we allowed to take the input divided by 10? e.g. instead of 50%, get 5?

The input (percentage) can be formatted however you like (50%, .5, 50), Can it be just 5?

@DrGreenEggsandIronMan the input can be 0%, and you can take the input in the most convenient format.

@LuisMendo, yes, I'll edit that into the question, thanks.

Is a leading line break instead of a trailing one accepted? Is absolute padding accepted?

@Titus as long as the output looks the same as my examples.

Python 2 - 184 151 146 Bytes
def r(n):
  n/=10
  for i in range(1,11):
    if n<0:print"%s--"%p
    elif i>9:print" %s-10-"%p
    else:p=" "*~-i;print"%s-%s-"%(p,`i`*2*n);n-=1

The last number kinda messed with me a little. I might be able to remove the second if statement if I look at it later.
EDIT: Thx to mbomb007 for removing 3 bytes. Thanks to charredgrass for the formatting tips to help remove lots and lots of bytes! :-D Thanks to TheBikingViking for helping with yet another two bytes!

Use i>9 instead of i==10 and remove the space in range(1, 11).

Small tip for golfing in python: you cut down on a lot of bytes from whitespace by compressing your statements onto one line. For example the last 3 lines can become p=" "*(i-1);print"%s-%s-"%(p,str(i)*2*n);n-=1.

thanks ! That helps a lot with this one and I'll definitely keep that in mind in future golfing

You can shave off 2 bytes by replacing (i-1) in the last line with ~-i. This takes advantage of operator precedence and the fact that a bit flip followed by a negation is the same as subtracting 1.

What is the point of using range(1,11) and then (i-1)?

@LeakyNun Because i is used more often.

Another quick tip: you don't need all of the whitespace before each indented line. One space and two spaces are recognised as different indentation levels in Python, knocking off 8 bytes, or you could even use one space and the tab character (which is again recognised as a different level), which would knock off 10 bytes.

Python 2, 74 bytes
n=input()
x=0
exec"print' '*x+'-'+`x+1`*(n-x<<1-x/9)+'-';x=min(x+1,n);"*10

Saved two bytes by exec-ifying a loop, thanks to Dennis.
EDIT: I took a slightly different approach and saved two more bytes.

You can save 2 bytes using string formatting by replacing '-'+\x+1`(n-x<<1-x/9)+'-'in theexecloop with'-%s-'%`x+1`(n-x<<1-x/9)`.

Nope, I’d need parens around the \x+1`*(n-x<<1-x/9)`.

PowerShell v2+, 130 120 116 110 bytes
param($n)$i=0;10..1|%{" "*$i+(("-"+("$($i+1)"*([math]::Max($n-10+$_,0))*2)),"-10")[$n-$_-eq9]+"-";$i+=$i-ne$n}

Edit 1 - Golfed 10 bytes by eliminating $x variable and slightly redoing how the string is formulated.
Edit 2 - Golfed another 4 bytes by redoing how input happens and by redoing how $i is calculated each loop.
Edit 3 - Saved 6 bytes by OP allowing input as 0..10, so no need to divide by 10.
Surprisingly difficult!
Takes input as 1,5, etc., stored in $n. Sets helper $i variable (one of the very rare times that a variable needs to be initialized to 0 in PowerShell), and then starts a loop from 10 to 1.
Each iteration, we set start our string with a number of spaces equal to $i, followed by a pseudo-ternary (... , ...)[]. Inside the pseudo-ternary, we select a string of either - with a number of digits (the higher of $n-10+$_ or 0, multiplied by 2), or the string -10 -- the selection is based on whether we're at the 10th iteration and our input was 100. We concatenate that with a final -. That resultant string is placed onto the pipeline.
Finally, we increment $i, and this was really tricky. We wound up using a binary-cast-to-int trick to only increment $i up until it reaches $n, and then keeping it at the same value thereafter. This ensures we've reached the "end" of the zipper indentation at the appropriate level.
Once the loop has finished, the resultant strings are all accumulated on the pipeline and output is implicit.
Examples
PS C:\Tools\Scripts\golfing> .\unzip-some-numbers.ps1 70
-11111111111111-
 -222222222222-
  -3333333333-
   -44444444-
    -555555-
     -6666-
      -77-
       --
       --
       --

PS C:\Tools\Scripts\golfing> .\unzip-some-numbers.ps1 100
-11111111111111111111-
 -222222222222222222-
  -3333333333333333-
   -44444444444444-
    -555555555555-
     -6666666666-
      -77777777-
       -888888-
        -9999-
         -10-

Python, 95 84 bytes
I wasn't aware lambdas were legal, thanks @Dr Green Eggs and Iron Man
lambda p:'\n'.join(' '*min(p,l)+'-'+(2-(l==9))*(p-l)*str(l+1)+'-'for l in range(10))

Hey, great first answer! You can move it out of a list comprehension to save 2 bytes, join can take a generator directly.

You can do a lambda instead of printing. With Morgan's suggestion: lambda p:'\n'.join(' '*min(p,l)+'-'+(2-(l==9))*(p-l)*str(l+1)+'-'for l in range(10)) (84 bytes)

Pyth, 37 34 bytes

=h/QTjm+*;thS,dQj<*`d20eS,0y-Qd"--"ST
=h/QTjm+*;thS,dQj*`d/y-Qdl`d"--"ST

Test suite.

MATL, 48 41 35 bytes
0:9"@GhX<Z"45h@QVG@-E@8>-OhX>Y"h45h

Try it online!

Ruby, 74 bytes
Uses the implied-zero format specified in the question, so 40% is f[4] if the anonymous function is assigned to f. If a full percentage is needed, +6 bytes for n/=10;
Try it online!
->n{10.times{|i|puts' '*[i,n].min+"-#{i>8?10:(i+1).to_s*2*(n-i)if i<n}-"}}

Python 3, 98, 90, 87, 85 bytes.
Takes the number already divided by 10. I can probably remove some of the parens, but this is pretty closed to fully golfed.
lambda n:'\n'.join(' '*min(i,n)+'-%s-'%(str(i+1)*(n>i>8or(n-i)*2))for i in range(10))

Javascript es7, 105 bytes
A=>[...Array(10)].map((a,i)=>' '.repeat((d=A<i)?A:i)+('-'+(i+1+'').repeat(d?0:i<9?2*(A-i):1)+'-')).join`
`

call with
f=A=>[...Array(10)].map((a,i)=>' '.repeat((d=A<i)?A:i)+('-'+(i+1+'').repeat(d?0:i<9?2*(A-i):1)+'-')).join`
`

f(10)
f(5)
f(0)

The program/function ... - not snippet

If you replace the \n with an actual newline, you can save a byte.

@Titus What are you talking about? This "snippet" is a function.

ah right. ES7, I forgot.

@MamaFunRoll I had that, but couldn't wrap in "" and do .length so I wasn't 100% confident I was in the clear - I'll add it in :)

Haskell, 83 bytes
f n=unlines[[[1..y]>>" ",take(2*(n-y))$cycle$show$y+1]>>=(++"-")|y<-min n<$>[0..9]]

What's ++"-"?

Python 2.7, 113 108 77 bytes

    n=input()
    for x in range(0,10):
        v=str(x+1)*(n-x)2
        if xn>89:v='10'
        print' '*min(x,n)+'-'+v+'-'

First time playing golf. Gonna keep going, try to get it <100.
Assumes input is 1-10.
Edit:
Used some tricks from @LeakyNun 's answer (thanks), then crunched it a bit further and got... basically the same answer :/  Didn't know about the `int` string conversion, and 2 - boolean let me get rid of the if statement, which let me get rid of the whole v variable.  Very cool.
My version:
n=input()
for x in range(10):print' '*min(x,n)+'-'+`x+1`*(n-x)*(2-(x>8))+'-'

Nice answer, and welcome to the site! You could take off 9 bytes by changing the indentation level to 1 space, instead of 4.

Actually, you could make this even shorter with this: n=input(); for x in range(0,10):print' '*min(x,n)+'-'+('10'if x*n>89 else str(x+1)*(n-x)*2)+'-'

Python 2, 81 bytes
n=input()/10
for i in range(10):print(' '*min(i,n)+'-'+2*(n-i)/-~(i>8)*`i+1`+'-')

Ideone it!

Python 2.7, 110 99 95 91 bytes:
G=input();i=1;exec"print' '*[~-i,G][i>G]+'-%s-'%[`i`*(2*-~G-i*2),'10'][(i>9)*G>9];i+=1;"*10

A full program that takes input by an integer in the inclusive range [1,10], where 10 means 100% and 1 means 10%. Can probably be golfed down a bit more.
Try It Online! (Ideone)

PHP 5.3, 92 91 bytes
<?for(;$i<10;$i++)echo'
'.str_pad('-'.str_repeat($i+1,$n>9&&$i>8?:($n-$i)*2).'-',22,' ',2);

for PHP 5.3 with register_globals=1 and short_open_tags=1 (and error_reporting=0)
call in cli with php-cgi -f <filename> n=<number>
number from 0 to 10

to call in web browser with


text:
Convert n strings of m length to m strings of n length
Write a program that, given any 'n' number of strings of 'm' length, returns 'm' number of 'n'-length strings, with this condition:
Every new string should contains the letters at the same index of the others strings
For example, the first output string must contain the first letter of all the input strings, the second output string must contain the second letter of all the input strings, and so on.
Examples (the numbers under the letters are the indexes of the strings):
input: "car", "dog", "man", "yay"
        012    012    012    012
output: "cdmy", "aoaa", "rgny"
         0000    1111    2222

input: "money", "taken", "trust"
        01234    01234    01234
output: "mtt", "oar", "nku", "ees", "ynt"
         000    111    222    333    444

Assume that the input is correct everytime
Shortest bytes' code wins!
Edit:
Since there are many programming languages, and there could be many possible solutions for each of them, I will post the shortest solution for each programming language and the user who provided it. Keep coding!
Re-Edit:
Thanks to user Dennis I inserted a snippet for the leaderboards.

var QUESTION_ID=85255,OVERRIDE_USER=56179;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

We have a leaderboard snippet that you can add to your question body. No need to do that by hand.

Duplicate: http://codegolf.stackexchange.com/q/17305

I'm sorry, I didn't know it was called "transposing"

I do not believe these challenges are duplicates, because of the differences involving ragged transposition and some weird whitespace handling in the other question. While in some languages the answers might be very similar, I think in most they will be different enough that this shouldn't be a duplicate.

Related, Related

Pyth, 1 byte
C

Try it here
Another transpose builtin

How is this even possible?!

Surely you're joking!

Pyth is the new Mathematica!

Python, 36 29 bytes
zip(*s) returns a list of tuples of each character, transposed.
lambda s:map(''.join,zip(*s))

Try it online

The output says "cdmy", "aoaa", "rgny", which is a list ["cdmy", "aoaa", "rgny"] or a tuple ("cdmy", "aoaa", "rgny")

map(''.join,zip(*s)) also works for the string conversion (Python 2 only), and for Python 3, [*map(''.join,zip(*s))] afaik works

@KevinLau-notKenny map(''.join,zip(*s)) is valid for Python 3 also - we allow iterators/generators in place of lists by default.

Jelly, 1 byte
Z

Try it online!

Vim, 37 36 keystrokes
All the other answers are boring, and using boring single-byte builtins. Here's a hacky answer that does the entire thing manually, in something that isn't even a programming language:
Gmaqqgg:s/./&<cr>d<C-v>`aGo<esc>pvGgJ@qq@q`adgg

Explanation:
G                                   "move to the end of this line
     ma                             "And leave mark 'a' here
       qq                           "Start recording in register 'q'
         gg                         "Move to the beginning
           :s/./&<cr>               "Assert that there is atleast one character on this line
                      d             "Delete
                       <C-v>        "Blockwise
                            `a      "Until mark 'a'

    G                               "Move to the end of the buffer
     o<esc>                         "Open a newline below us
           p                        "And paste what we deleted
            vG                      "Visually select everything until the end
              gJ                    "And join these without spaces
                @q                  "Call macro 'q'. The first time, this will do nothing,
                                    "The second time, it will cause recursion.
                  q                 "Stop recording
                   @q               "Call macro 'q' to start it all

Now, everything is good, but the buffer has some extra text left over. So we must:
`a                              "Move to mark 'a'
  dgg                           "And delete everything until the first line

MATL, 1 byte
!

Try it online!
Takes input implicitly, transposes, displays output implicitly.

PowerShell v2+, 66 54 bytes
param($n)for($x=0;$n[0][$x];$x++){-join($n|%{$_[$x]})}

Yo ... no map, no zip, no transpose, etc., so we get to roll our own. Big props to @DarthTwon for the 12-byte golf.
Takes input $n, sets up a for loop. Initialization sets $x to 0, the test is whether we still have letters in our word $n[0][$x], and we increment $x++ each iteration.
Inside the loop, we take our array of strings, pipe it to an inner loop that spits out the appropriate character from each word. That is encapsulated in a -join to form a string, and that string is left on the pipeline. At end of execution, the strings on the pipeline are implicitly printed.
PS C:\Tools\Scripts\golfing> .\convert-n-strings.ps1 "Darth","-Twon","Rocks"
D-R
aTo
rwc
tok
hns

Nice, that's the kind of the answers I wanted to see ;)
It's too simple writing , rather than thinking about the answer

Using a while loop can further pare that down: param($n)$x=0;while($n[0][$x]){-join($n|%{$_[$x]});$x++}. And no errors here :D

@DarthTwon Excellent. Or, use a for loop for another two. ;-)

Hmm... I tried that, but not after really paring down my while loop. Good work sir!

Can you use Linq in Powershell?

@aloisdg Mmm, kinda. Usually it requires a lengthy call like [System.Linq.<something>] since it's not native like in C#, so it's usability is limited in code-golf. In many cases, there's a roughly-equivalent PowerShell-native method.

CJam, 6 5 bytes
Saved 1 byte thanks to Luis Mendo.
qS%zp

Try it online!
q      e# Get all input
 S%    e# Split it on spaces
   z   e# Take the transpose
    p  e# Print it as an array

Retina, 45 43 bytes
Byte count assumes ISO 8859-1 encoding.
O$#`.(?<=(.+))|¶
$.1
!`(?<=(¶)+.*)(?<-1>.)+

The leading linefeed is significant. Input and output are linefeed-terminated lists of printable ASCII strings (note that both have a single trailing linefeed).
Try it online!
I knew for a while that transposing rectangular blocks would be a pain in Retina (whereas transposing squares isn't too bad), but never actually tried. The first solution was indeed a whopping 110 bytes long, but after several substantial changes in the approach, the resulting 45 bytes are by far not as bad as I suspected (but still...). Explanation will follow tomorrow.
Explanation
Stage 1: Sort
O$#`.(?<=(.+))|¶
$.1

This does the main work of reordering the characters in the input, but it ends up messing up the separation into lines. Interestingly, if we remove the |¶, we get the code required to transpose a square input.
Sort stages (denoted by the O) work like this: they find all matches of the given regex (the thing after the `), and then sort those matches and reinsert them into the places where the matches were found. As it happens, this regex matches every single character: non-linefeeds via the .(?<=(.*)) alternative and linefeeds via the ¶. Hence, it sorts all characters in the input. The more interesting part is what they are sorted by.
The $ option activates a "sort-by" mode, where each match is replaced with the substitution pattern on the second line, which is then used for comparing the matches. Furthermore, the # tells Retina to convert the result of the substitution to an integer, and compare those integers (instead of treating them as strings).
So finally, we need to look at the regex and the substitution. If the first alternative matches (i.e. we have matched any character within one of the lines), then the (?<=(.*)) captures everything up to that character on that line into group 1. The $.1 in the substitution pattern replaces this with the length of group 1. Hence, the first character in each string becomes 1, the second becomes 2, the third becomes 3 and so on. It should be clear now how this transposes a square input: all the first characters of the lines come first and all end up in the top-most line, then all the second characters end up in the second line and so on. But for these rectangular inputs, we're also matching the linefeeds. Since group 1 is unused in this case, the substitution is empty, but for the purposes of the # option, this is considered 0. That means, all the linefeeds are sorted to the front.
So now we do have the characters in the first order (first character of each string, second character of each string, etc.) and all the linefeeds at the start.
Stage 2: Match
!`(?<=(¶)+.*)(?<-1>.)+

We now need to split up the characters into lines of the correct length. This length corresponds to the number of lines in the original input, which is corresponds to the number of linefeeds we have at the beginning of the string.
The splitting is done here with the help of a match stage, which simply finds all matches of the given regex and uses the ! option to print those matches (the default would be to count them instead). So the goal of the regex is to match one line at a time.
We start by "counting" the number with the lookbehind (?<=(¶)*.*). It generates one capture in group 1 for every linefeed at the front.
Then, for each of those captures, we match a single character with (?<-1>.)+.

28 bytes (Credit goes to mbomb007 and Leo)

@KevinCruijssen Feel free to post as a separate answer. This one was before the Retina 1.0 features used in yours (and I don't really feel like updating the explanation).

Pyke, 1 byte
,

Try it here!
Transpose.

Oh... Didn't think it would have been so simple :/

Yeah, I can't seem to find a duplicate by looking for 60 secs though

x86 machine code, 19 bytes
In hex:
fc89d35651a401dee2fb91aa595e464a75f1c3

Input: ECX: # of strings (n), EDX: individual string length (m), ESI: array of input strings, EDI: output buffer receiving array of strings. Array is presumed to be defined as char src[n][m+1] for input and char dst[m][n+1] for output, and all strings are NULL-terminated.
0:  fc                  cld
1:  89 d3               mov ebx,edx   ;EDX is the counter for the outer loop
_outer:
3:  56                  push esi
4:  51                  push ecx
_inner:
5:  a4                  movsb         ;[EDI++]=[ESI++]
6:  01 de               add esi,ebx   ;Same char, next string
8:  e2 fb               loop _inner   ;--ECX==0 => break
a:  91                  xchg eax,ecx  ;EAX=0
b:  aa                  stosb         ;NULL-terminate just completed string
c:  59                  pop ecx
d:  5e                  pop esi       ;First string,
e:  46                  inc esi       ;...next char
f:  4a                  dec edx
10: 75 f1               jnz _outer
12: c3                  ret

Brachylog, 5 bytes
z:ca.

Expects a list of strings as input, e.g. run_from_atom('z:ca.',["money":"taken":"trust"],Output).
Explanation
z       Zip the strings in the Input list
 :ca.   output is the application of concatenation to each element of the zip

05AB1E, 3 bytes
ø€J

Explained
     # implicit input, eg: ['car', 'dog', 'man', 'yay']
ø    # zip, producing [['c', 'd', 'm', 'y'], ['a', 'o', 'a', 'a'], ['r', 'g', 'n', 'y']]
 €J  # map join, resulting in ['cdmy', 'aoaa', 'rgny']

Try it online

Can be just ø now (in the legacy version at least). In the new version it can also be just ø, but then the I/O is a list of lists of characters. With a list of strings as I/O it would be 4 bytes instead: €SøJ.

JavaScript ES6, 48 46 bytes
a=>[...a[0]].map((n,x)=>a.map(a=>a[x]).join``)

I feel left out, we have no built in zip function. Thanks nicael for pointing out my type error.
Usage
(a=>[...a[0]].map((n,x)=>a.map(a=>a[x])))(["asd","dsa"]); //or whatever is above, might change due to edits

returns
["ad","ss","da"]

Exception: TypeError: a[0].map is not a function

You need [...a[0]].map, since a[0] isn't an array.

@nicael thanks. messed up the types. this proves why I should not golf this early in the morning.

@nicael I .joined them to fix that problem.

Yep, does work now. @edc please retract your downvote, the answer has been fixed.

join``  instead of join('') to save 2 bytes. Downvote retracted

CJam, 3 bytes
{z}

This is a code block (equivalent to a function; allowed by default) that expects the input on the stack and leaves the output on the stack.
Try it online!

Sure about that?

@Drgreeneggsandironman Well, the answer with more votes says The default should be "programs or functions"

Bash + BSD utilities, 27
sed s/./\&:/g|rs -c: -g0 -T

I/O via STDIN/STDOUT newline-separated strings.
You may need to install rs with sudo apt install rs or similar.  Works out of the box on OS X.
The -T option to rs does the heavy lifting of the transposition.  The rest is just formatting:

The sed command simply inserts : after every character
-c: specifies input columns are : separated
-g0 specifies output columns have zero width separation

If my reading of the rs manpage is correct, then the following ought to work for a score of 12, but unfortunately it doesn't work - see note below:
rs -E -g0 -T

Example output:
$ printf "%s\n" car dog man yay |sed s/./\&:/g|rs -c: -g0 -T
cdmy
aoaa
rgny
$

If input is expected to be all printable ASCII, then the : may be replaced with some unprintable character, e.g. 0x7 BEL.

Note
I wanted to understand why I couldn't get the -E option to work and get rid of the sed preprocessing.  I found the rs source code here.  As you can see, giving this option sets the ONEPERCHAR flag.  However, there is nothing in the code that actually checks the state of this flag.  So I think we can say that despite the fact that is option is documented, it is not implemented.
In fact, this option is documented in the Linux rs manpage:

-E      Consider each character of input as an array entry.

but not the OS X version.

PHP, 82 bytes
function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;}

takes and returns an array of strings
break down
function f($a)
{
    foreach($a as$s)                    // loop through array $a
        foreach(str_split($s)as$i=>$c)  // split string to array, loop through characters
            $y[$i].=$c;                 // append character to $i-th result string
    return$y;
}

examples
$samples=[
    ["asd","dsa"], ["ad","ss","da"],
    ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"],
    ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"]
];
echo '
';
while ($samples)
{
    echo 'in: ';         print_r($x=array_shift($samples));
    echo 'out: ';        print_r(f($x));
    echo 'expected: ';   print_r(array_shift($samples));
    echo '
';
}

APL, 3 bytes
↓⍉↑

↑ takes the input strings and turns them into a char matrix.
⍉ transposes the matrix.
↓ splits back the rows of the resulting matrix into strings.

K, 1 byte
+

Try it here!
Transpose

MATLAB / Octave, 4 bytes
@(x)x'

This defines an anonymous function. Input format is ['car'; 'dog'; 'man'; 'yay'].
Try it here.

What format is the input for this solution? I don't think it will work with the way Matlab handles strings if you try to input them in a Matlabby way, e.g. f = @(x)x', f([{'abcd'},{'abcd'},{'abcd'}]) outputs
ans =
'abcd'
'abcd'
'abcd'

@sintax Input format should be a 2D char array, as in the example linked in the answer. You are using a cell array of strings (obtained by concatenating singleton cell arrays). It should be: f(['abcd';'abcd';'abcd']). I've edited the answer to specify the input format

Mathematica, 26 bytes
""<>#&/@(Characters@#)&

Anonymous function. Takes a string list as input and returns a string list as output. The Unicode character is U+F3C7, representing \[Transpose]. Works by converting to a character matrix, transposing, and converting back to a string list. If the input/output format was stretched, then a simple 5-byte transpose would work:
#&

+1 you beat me to the punch! (But I wasn't able to use the Transpose symbol.)  By the way, why doesn't the T show up on screen? (It is there when I copy your code to Mathematica).

@DavidC The Unicode character is in the Private Use Area, which is marked as a section for proprietary characters and is therefore neither officially assigned a glyph nor rendered at all in most fonts. Mathematica's font just happens to render this character as a supserscript T and interpret it as a \[Transpose].

@DavidC Why don't they use ᵀ?

@Adám IDK, you'd have to ask Wolfram Research about that, not me

@LegionMammal978 Nah, I'm happy as long as I have APL's obvious ⍉.

Adám,  I was puzzled myself.  From LegionMammal978's answer, I gather that he wanted code that would run unaltered in Mathematica.  I think the superscripted T that you showed will not run when copied and pasted from Code Golf to Mathematica.

Haskell, 41 bytes
f l=zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0

Or with a bit more air:
f l = zipWith ($) [map (!! n) | n <- [0..]] $
                  l <$ (l !! 0)

The second list is the list of words repeated “the length of a word” time. On each list of words, we select the n-th letter of each word, giving the result.

There's no need for a full program, because "program" means "program or function", so a function is enough. You can pass and return a list of strings and therefore omit wordsand unwords. Further, map(\_->l)(l!!0) is l<*l!!0, so it boils down to \l->zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0.

Oh, good thanks :) I'm updating.

Oops, typo: it's l<$l!!0 (first time wrong, second time right), but you got it right anyway.

Common Lisp, 62 bytes
(lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s))

The map function takes a result type (here list), a function f to apply and one or more sequences s1, ..., sn. All sequences are iterated in parallel. For each tuple of elements (e1,...,en) taken from those sequences, we call (f e1 ... en) and the result is accumulated in a sequence of the desired type.
We take a list of strings, say ("car" "dog" "man" "yay"), and use apply to call map. We have to do this so that the input list is used as more arguments to map. More precisely, this:
(apply #'map 'list fn '("car" "dog" "man" "yay"))

... is equivalent to:
(map 'list f "car" "dog" "man" "yay")

And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls f as follows:
(f #\c #\d #\m #\y)

The anonymous lambda takes the list of arguments given to it and coerces it back to a string.

Perl, 91 bytes
So lengthy one..
$l=<>;$p=index($l," ")+1;@i=split//,$l;for$a(0..$p-1){print$i[$a+$_*$p]for(0..$p);print" "}

Try it here!

Ruby, 40 bytes
->a{a.map(&:chars).transpose.map &:join}

Attempt This Online!

J-uby, 24 bytes
Port of my Ruby answer.
:*&A|:transpose|:*&:join

Attempt This Online!
Explanation
:* & A | :transpose | :* & :join

:* & A |                          # Map converting to character arrays, then
         :transpose |             # Transpose, then
                      :* & :join  # Map with join

Go, 111 bytes
type S=[]string
func f(I S)S{O:=make(S,len(I[0]))
for _,s:=range I{for j,r:=range s{O[j]+=string(r)}}
return O}

Attempt This Online!

Japt, 1 byte
Simply transposes the input.
Õ

Try it

Ruby, 46 bytes
Probably the first time that "Ruby strings aren't Enumerables" is actually biting me hard since I had to map the strings into arrays before processing. (Normally having to use String#chars isn't enough of a byte loss to matter, but since I need to map them, it stings a lot more)
->s{s.map!(&:chars).shift.zip(*s).map &:join}

Clojure, 68 bytes
#(map(fn[g](reduce(fn[a b](str a(nth b g)))""%))(range(count(% 0))))

Maps a function which is just reduce (goes on elements of the list one by one and joins nth character of the string) on the range from 0 to length of the first string.
See it online: https://ideone.com/pwhZ8e

C#, 53 bytes
t=>t[0].Select((_,i)=>t.Aggregate("",(a,b)=>a+b[i]));

C# lambda (Func) where the output is IList<string> and the output is IEnumerable<string>. I dont know how work zip in other language but I can't find a way to use the C#'s one here. Aggregate fit the need well. No transpose in C#, there is one in Excel but I wont use it.
Try it online!