text:
draw ASCII function plots
Consider a function plot like this:
                                                       ###########
                                                    #################
                                                  ####################
                                                 #######################
                                               ###########################
                                              #############################
                                            ################################
                                           ###################################
                                          #####################################
                                        ########################################
--------------------------------------------------------------------------------
  #####################################
   ###################################
    #################################
      #############################
       ###########################
         #######################
          #####################
            #################
               ###########

This function plot has been created with the J code below, which is not a solution to this challenge.
([: |: ([: |."1 [: #&'#'"0 [: >. [: - (* 0&>)) ,. '-' ,. [: #&'#'"0 [: <. (* 0&<)) 10 * sin 12.7 %~ i. 80

Your task is to write a function or program that takes as input from an implementation defined source that is not the source code of your entry:

Two positive integers

w, the width of the plot
h, the height of the plot

Two real numbers

b, the beginning of the region to plot
e, the end of the region to plot

A function f mapping real numbers to real numbers. You may assume that this function does not crash, throw an exception, return a NaN or ±∞ for arguments in the range b to e inclusive. The way in which this function is described is implementation defined, but it should be possible to use any combination of the following:

floating point constants except NaN and ±∞
addition
subtraction
multiplication
division
the ex function
natural logarithm
sine and cosine

Your function or program shall return or print out an ASCII art plot with dimensions w × h that looks like plot above and plots f in the range b to e inclusive. The plot shall be scaled so that both the topmost and bottommost line contain a # sign or a -. Your output format may diverge from the output format shown above in a meaningful way if that doesn't simplify your solution. In particular, you may exchange # and - for other characters that give the impression of black space and horizontal line.
The score of your submission is the number of tokens your program source consists of. String literals count as the length of the string they describe but at least as one point, numeric literals count as ⌈log256(|n|)⌉ where n is the number described by the numeric literal.
An identifier which is either predefined by the language or a library your submission uses or whose name can be exchanged with any other unused name counts as one character. All other identifiers count as their length in characters.
If the programming language your submission is written does not have the concept of a token, it's score is the total number of characters that can't be removed from the source without changing the meaning of the program.
The scoring rules ensure that you can indent your code and use descriptive names for your variables, etc. and lowers the edge of domain-specific languages for golfing.
The winner is the submission with the least score.

@FryAmTheEggman I didn't know that tag existed. Thank you for the information.

Your definitions of how to count tokens are probably going to be abused as they are. E.g. by base64-encoding the code, naming a variable like this (which is a single token) and then getting a string representation of the variable name and base64-decoding it again.

@MartinBüttner Hm… That counts as a standard loophole in my opinion.

It does not and should be clarified by the OP if he does not intend to let people abuse them, like you did with string and number

If your main concern is readability of the code, ask people to include an ungolfed version. If your main concern is golfing languages, then I guess you'll have to go along with scoring by tokens, but in my experience it doesn't really help a lot, because in most languages a function call is 3 tokens (function name plus parentheses) + 1 token for the first argument + 2 tokens for every further argument (because of a delimiter like a comma), whereas in CJam, say, it's just number of arguments + 1.

@Optimizer Fixed that loophole.

More importantly, how should we the horizontal line be placed if it doesn't fit exactly on a particular row like in your example? (e.g. if the function is a sine, but h is even)

Also, it cannot be both code-golf and atomic-code-golf

@MartinBüttner The horizontal line does not have to be exactly in the center.

@FUZxxl Of course, but that doesn't tell me where I should put it if y = 0 falls between two lines of the ASCII output. An example output would be helpful.

@MartinBüttner The horizontal line denotes the place where y = 0 on the cartesian coordinate system you are plotting on. The output format is intentionally a little bit fuzzy so you have more freedom for finding a solution.

I like this question, but I think it could have benefited from a pass in the sandbox.

@MartinBüttner No. It's correct like it is. Where un(der)specified, your solution is free to choose reasonable behaviour. This is an explicit design decision in crafting this challenge.

The spec needs to explicitly state the criteria for shading a cell, because there are a number of plausible options and we can't tell which is intended. In particular, is the cheap and crappy "shade a pixel iff its midpoint is between 0 and the value at that x-coordinate" intended, or should the program attempt to compute the extrema of the image of the column and either shade the pixel iff its (centre-bottom / midpoint / centre-top) is between 0 and one of the extrema, or shade the pixel iff at least 50% of its area is?

Or, indeed, am I guessing wrongly that the shaded pixels in the column should always extend to the x-axis? For all I know, the example image shows sin(x)sin(1000x) and the line does actually pass through all of those shaded pixels.

The first behaviour (the "crappy" one) is correct. I'm on a trsin right now, let me amend the specificarion in a minute.

@Ypnypn As described in the question, a string counts as one point per character it contains. For instance, the C string "a\n" counts as two characters, the C string u"aä", too.

@MartinBüttner Good catch...

I think numerics should count like strings, or somebody could take some data consisting of bits bbb... and encode that as a number 0.999bbb..., which counts as pretty much 0 (Log_256(0.999...)). Or perhaps, count numbers without the decimal point or other separators: 1.75 would count as 175, the rational number literal 9992345/10000000r in ruby would count as 999234510000000 (and not as 0.9992345) etc.

@blutorange The scoring scheme is flawed anyway.

Ruby (>=2.1), ~28.19812
As @FUZxxl considered that the scoring scheme is flawed anyway, I shall make full use of it.
eval ([encoded data, 5654 characters]).numerator.to_s.chars.each_slice(3).map{|x|x.join.to_i.chr}.join

Try it online here at repl.it. Click run, then enter a valid argument line, such as 35 15 0 2*pi sin x.
Note that ruby has got numeric literals in rational notation, ie. 4/5r is the number 0.8. For your convenience, that number is in decimal notation:
0.[encoded data, 5651 characters]

This is a complete program, use it like this from the command line:
~ $ ruby cplot.rb 35 15 0 2*pi 'sin x'

      ######
     ########
    ##########
   ############
  ##############
 ###############
#################
-----------------------------------
                  #################
                   ###############
                   ##############
                    ############
                     ##########
                      ########
                       ######

or
~ $ ruby cplot.rb 35 15 1/pi pi '1/x'
#
#
##
##
###
###
####
######
#######
#########
#############
##################
#############################
###################################
-----------------------------------

I count the code as follows:
eval
(
<numeric> [log_256(1)=0]
)
.
numerator
.
to_s
.
chars
.
each_slice
(
<numeric> [log_256(3)=0.19812]
)
.
map
{
|
x
|
.
join
.
to_i
.
chr
}
.
join

Jupp. This scoring system turned out to be a bad idea.

I cant figure it out

@Ewan That long number is of the form a/br, with b=a+1. In ruby, that's a numeric literal and taking the logarithmic gives pretty much zero. The numerator a contains 3*n digits, each group of 3 representing a byte (100=0x64="d"). These bytes are the actual program. Try replacing eval with puts and you can see the program.

i get the scoring trickery, i don't understand how the program functions

ahh ok i see now, v clever!

This is the actual program. Rather straight-forward, but since size was not an issue anyway, I included easy input via cli arguments. It's also using the coordinates of the center of each pixel/block.

c# - 70ish?
using System;
using System.Collections.Generic;
using System.Linq;
class P
{
    static void Main()
    {
        Func<double,double> f = x => Math.Sin(x) -0.5;
        string r = Draw(60, 20, -10, 10, f);
        Console.Write(r);
        Console.ReadLine();
    }

    static string Draw(int w, int h, int b, int e, Func<double, double> f)
    {
        IEnumerable<double> values = Enumerable.Range(0, w).Select(i => f(i * (double)(e - b) / w));
        double scale = h / (values.Max() - values.Min());

        return String.Join(Environment.NewLine,
            Enumerable.Range(0, h)
            .Select(y => ((h - y) / scale) - Math.Abs(values.Min()))
            .Select(ypos => Math.Abs(ypos) < 1 / (scale * 2)
                ? new String('-', w)
                : new String(values.Select(v => v > ypos ^ ypos < 0
                    ? '#'
                    : ' ').ToArray())
                )
        );
    }
}


text:
Find the inverse of a matrix
Write a full program to calculate the inverse of a 4-by-4 matrix.
Rules
The sixteen values of the initial matrix must be hard-coded to variables, as follows:
_       _
|a b c d|
|e f g h|
|i j k l|
|m n o p|
-       -

Then print the values of the inverse matrix, row by row, with each number separated by some delimiter. You may assume that the given matrix has an inverse.
The results must be completely accurate, limited only by the programming language. For example, you may assume that (1 / 3) * 3 = 1, there's no such thing as integer overflow, and so on.
You may use only the following operations:

Addition - 10 points
Subtraction - 15 points
Multiplication - 25 points
Division - 50 points
Assignment to a variable - 2 points
Printing a variable (not an expression) and a delimiter - 0 points
Recalling a variable or numeric constant - 0 points

For example: x = (a + b) / (a - 2) would score 77 points.
To clarify, you may not use any other operations or structures, such as arrays, functions (outside the main method, if needed), if-statements, etc.
The initial hard-coding of the variables does not give any points.
Fewest points wins.
Testcases
Note that all testcases can be used in reverse.
a=1; b=1; c=2; d=-1; e=-2; f=0; g=-2; h=1; i=-1; j=2; k=1; l=0; m=2; n=-1; o=0; p=2

Print, in order: 9 7 -4 1 10 8 -4 1 -11 -9 5 -1 -4 -3 2 0
a=1; b=2; c=3; d=0; e=2; f=2; g=1; h=0; i=4; j=4; k=4; l=4; m=2; n=1; o=-2; p=0

Print, in order: -5 7 0 -4 6 -8 0 5 -2 3 0 -2 1 -2 .25 1
a=-.25; b=.5; c=0; d=.5; e=1; f=.25; g=-.5; h=0; i=-1; j=-.5; k=.5; l=.25; m=.25; n=1; o=0; p=0

Print, in order: -2 4 4 2 .5 -1 -1 .5 -3.75 5.5 7.5 4.25 .5 3 3 .5

Just checking, but creating arrays is not allowed, correct?

Can we also assume the variables to be stored in an array? I assume we may also use other structures like loops/conditionals etc, do we?

Is the score for an operation counted each time the operation is written in the code, or each time it is performed during execution?

Can our code fail on a measure zero subset of matrices that cause a divide by zero even though they are invertible? Gaussian elimination is likely to run into this.  If not, can we use an if statement?

@JamesPringle No.

@feersum Performed, though it shouldn't make a difference.

@xnor No.. No..

It makes a huge difference.

Java: 3974
Now this is a totally new version of the prgoram, that satisfies the updated conditions. Note that I did use an array for printing in this version here, but I counted as if every assignment was an own new variable. The for loops save some space for those who want to see the code here...
I am using the only possible approach (i think) under the restrictions via minor determinats that form the adjoint matrix.
For those who want to check the correctness of the formula.
Stats:
= :  2* 42
+ : 10* 44
- : 15* 60
* : 25*100
/ : 50*  1

public static void main(String[] args){
    double a=4,b=1,c=1,d=2,
           e=4,f=4,g=1,h=5,
           i=2,j=1,k=5,l=1,
           m=4,n=2,o=4,p=3;
    double af=a*f;
    double kp=k*p;
    double lo=l*o;
    double ag=a*g;
    double jp=j*p;
    double ln=l*n;
    double ah=a*h;
    double jo=j*o;
    double kn=k*n;
    double be=b*e;
    double bg=b*g;
    double lm=l*m;
    double bh=b*h;
    double io=i*o;
    double km=k*m;
    double ce=c*e;
    double cf=c*f;
    double ip=i*p;
    double ch=c*h;
    double in=i*n;
    double jm=j*m;
    double de=d*e;
    double df=d*f;
    double dg=d*g;

    double z = 1/(af*(kp-lo)+ag*(ln-jp)+ah*(jo-kn)+be*(lo-kp)
               +bg*(ip-lm)+bh*(km-io)+ce*(jp-ln)+cf*(lm-ip)
               +ch*(in-jm)+de*(kn-jo)+df*(io-km)+dg*(jm-in));

    double[] inv = {h*(jo-kn)+g*(ln-jp)+f*(kp-lo) , d*(kn-jo)+b*(lo-kp)+c*(jp-ln) , (ch-dg)*n+(df-bh)*o+(bg-cf)*p , (dg-ch)*j+(bh-df)*k+(cf-bg)*l,
            h*(km-io)+g*(ip-lm)+e*(lo-kp) , d*(io-km)+c*(lm-ip)+a*(kp-lo) , (dg-ch)*m+(ah-de)*o+(ce-ag)*p , (ch-dg)*i+(de-ah)*k+(ag-ce)*l,
            h*(in-jm)+f*(lm-ip)+e*(jp-ln) , d*(jm-in)+a*(ln-jp)+b*(ip-lm) , (bh-df)*m+(de-ah)*n+(af-be)*p , (df-bh)*i+(ah-de)*j+(be-af)*l,
            g*(jm-in)+e*(kn-jo)+f*(io-km) , c*(in-jm)+b*(km-io)+a*(jo-kn) , (cf-bg)*m+(ag-ce)*n+(be-af)*o , (bg-cf)*i+(ce-ag)*j+(af-be)*k};

    for(int u=0;u<16;u++){
        inv[u] = inv[u]*z;  //counting as 16 assignments and 16 multiplicatiosn

    }
    //printing all the values
    for(int u=0;u<16;u++){
        if(u%4 == 0){
            System.out.println("");
        }
    System.out.print(inv[u]+" ");

    }

}

source: Stack Exchange

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

sort: votes


text:
Transferring the DNA of bacteria from generations
Introduction
Scientists have recently found a new type of bacteria that replicates in odd ways. To reproduce, two bacteria each split into 3 (for a total of 6) and pairs combine (resulting in 3 bacteria, two parents, one child). However, the bacteria can only split if it has a partner. For example, 2 bacteria split and combine into 3, 3 into 4, 4 into 6, etc. Additionally, when a bacteria splits, only one of the daughter cells combines with the other parent cell's daughter cells, and vice versa. In other words, if bacteria A and B split, the daughter cells will combine to be AA, AB, and BB.
The Challenge
Your challenge is to make a program that accepts or generates 4 bacteria's DNA, each with a strand in a 10-bit Quaternary format. An example DNA strand could be 0123302012. When two daughter bacteria combine, the DNA is merged in a punnet-square style (the DNA can be merged in every pair or only the AB pair, your choice). Meaning that 0 is the recessive trait, 1 is the mixed trait, and 2 is the dominant trait. However, when there is a 3, it is a mutated trait (more on this later). Starting with the 4 bacteria, have your program run 20 trials (4 splitting into 6 would be the first trial). Once it is done, have the program output through STDOUT (or equivalent) each cell's DNA on a seperate line, but only from the cells generated from the 20th trial.
Key Features

Each trial must calculate the new number of cells and each new cell's DNA (see below).
The program must output each 20th-trial cell's DNA (The 4046 new bacteria) each on a seperate line in STDOUT (or equivalent).
The bacteria must each replicate in the method stated above. (A and B split into AA, AB, and BB).

How the DNA is Passed on
The DNA is passed from the parents to child in a punnet-square style where:

0 is a recessive trait (rr).
1 is a mixed trait (Rr).
2 is a dominant trait (RR).

If one of the traits is a 3 (a mutation), the ending trait is decided randomly, but if both are 3,the ending trait is a 3. Parents can be decided randomly or in order (A & B, C & D, etc).
Example:
    |   DNA A    |   DNA B    | DNA C (Child) |
    | 0123311200 | 1203123213 |  0113012203   |

Scoring
This is code golf, so shortest character count wins! For legibility, please include a version that separates the code onto multiple lines, if possible. If the challenge is not explained well or you have suggestions, post a comment!
Here is an example program (in java) that successfully completes the challenge: Ideone Link.

Are you sure you want to discount newlines? That gives an advantage to certain languages. You can always just ask for an ungolfed version for clarity.

@Geobits good point, i'll change that.

There are a few things which aren't clear to me. 1. What's the point of the introduction? The rest of the question looks like basis meiosis, but the introduction confuses me and makes me unsure whether that's the intention or not. 2. What exactly is a trial? Is the intention that we start with generation 0 of 4 bacteria, and at each trial we pair up the current generation (possibly with an unpaired specimen) and add the offspring to the current generation to get the new generation? And then we have to output the 12138 members of gen 20? Or the 4046 members of gen 20 who aren't in gen 19?

When you say that "the ending trait is decided randomly", from what distribution? Is it a 50/50 between the two traits being combined, a 25/25/25/25 between all 4 possibilities, or something else?

The introduction is just for people to get familiar with the question and to explain what is happening. 2. A trial is a new generation where trial 1 is where the population is 6. 3. Say the parent's genes are a 0 and a 3. The child's gene could be 0, 1, 2, or 3.

CJam: 71
Golfed:
qS/{mr2/{_,({3*$2/{z{:~_3#){~=Z4mr?}{{[0Ymr1]=}%:+}?`}%}/}{~}?}%}K*{N}/

Indented and commented:
qS/             "Read the input and split around spaces";
{               "Loop";
  mr2/            "Shuffle the DNA strings and group into pairs";
  {               "For each pair";
    _,(             "Check if it's really a pair";
    {               "If it's really a pair AB";
      3*$2/           "Create the breeding combinations AA AB BB";
      {               "For each breeding combination";
        z               "Pair the corresponding alleles together";
        {               "For each pair of alleles";
          :~              "Map each allele (currently a string) to an int";
          _3#)            "Check if one of the alleles is a 3";
          {               "If one allele is a 3";
            ~=              "Check if both alleles are 3";
            Z               "If so, generate a 3 as the new allele";
            4mr?            "Otherwise, generate a random number from 0 to 3 as the new allele";
          }{              "If neither allele is a 3";
            {[0Ymr1]=}%     "For each allele, map 0 to 0, 1 to 0 or 1 (random), and 2 to 1";
            :+              "Add the mapped values to generate the new allele";
          }?`             "Convert the allele back to a string";
        }%              "Result: two DNA strings bred into one";
      }/              "Result: two DNA strings combined and bred into three";
    }{~}?           "If it's not a pair, just unwrap it from its group";
  }%              "Result: all pairs of DNA strings combined and bred into three";
}K*             "Result: bred for 20 generations";
{N}/            "Put a newline after each DNA string";

You added the stipulation that DNA is only merged punnet-square-style for "AB" bacteria after I wrote my code, but mine generates all bacteria by merging that way. Based on your description of how breeding occurs, my interpretation (which also seems to be Siddhanathan's interpretation) seemed more accurate. Talking about bacteria splitting into 3 doesn't make any sense otherwise. But I'll change things if necessary.
I also assumed that breeding pairs should be decided randomly, but that seems like a safer assumption.

No need to change anything. Your suggestions were also nice and I incorporated them to the best of my ability!

Haskell -- 349
import Control.Monad
import System.Random
import Data.List
a=[0,1,2,3,3,1,1,2,0,0]
b=[a,a,a,a]
f 3 _=randomRIO(0,3)
f _ 3=randomRIO(0,3)
f x y=return$div(x+y)2
z::[Integer]->[Integer]->IO[Integer]
z x y=zipWithM f x y
c=filter(\x->length x==2).subsequences
r=sequence.map(\x->z(x!!0)(x!!1)).c
y=foldr(<=<)return.replicate 20
main=y r b>>=mapM_ print

Try it online with nicer looking source code: http://ideone.com/9FUMLd
The online example does only till 2 instead of 20 because of ideone's time limit.

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


text:
Join N copies of a snippet to produce N^2 characters
Challenge
Write the shortest snippet of code possible such that, when N copies of it are concatenated together, the number of characters output is N2. N will be a positive integer.
For example if the snippet was soln();, then running soln(); would print exactly 1 character, and running soln();soln(); would print exactly 4 characters, and running soln();soln();soln(); would print exactly 9 characters, etc.
Any characters may be in the output as long as the total number of characters is correct. To avoid cross-OS confusion, \r\n newlines are counted as one character.
Programs may not read their own source or read their file size or use other such loopholes. Treat this like a strict quine challenge.
The output may go to stdout or a file or a similar alternative. There is no input.
Comments in the code are fine, as is exiting mid-execution.
Any characters may be in the program. The shortest submission in bytes wins.

Does the program have to terminate?

@MartinBüttner Yes

TECO, 4 bytes
V1\V

V prints the contents of the current line in the text buffer. 1\ inserts the string representation of the number 1 at the current position.
So on the Nth iteration of the program, the first V will output N - 1 copies of the character 1, then add another 1 to the text, then output N 1s.

Can you add a link to TECO?

Brainfuck, 17 16 bytes
[>+>-..+<<-]-.>+

You can test it here. Just use the fact that n2+2n+1=(n+1)2.

I can't believe I'm seeing BF at a competitive level of bytes!

Brainfuck, 11
I saw the first Brainfuck answer and thought it's way too long :)
[.<]>[.>]+.

The output may be easier to see if you replace the plus with a lot more pluses.
On the Nth iteration, each loop outputs N - 1 copies of the character with ASCII value 1, and then one more with +..

You need to print N^2 characters, not N characters.  I can't read BF code, so I don't know if your code is incorrect or if your description is incorrect.

@BrianJ It prints N^2 characters. You can test it here: http://copy.sh/brainfuck/ Replace the plus with a minus if you can't see the output.

@alephalpha Oops, I now see that I misread the comment.  The code does not do (N - 1) + 1 like I originally thought.

Python 2, 22
a='';print a;a+='xx';a

Prints the empty string, then two x's, then x' four and so on. With the newline after each string, this comes out to n*n characters.
One copy: "\n" (1 char)
Two copies: "\nxx\n" (4 chars)
Three copies:  "\nxx\nxxxx\n" (9 chars)
In order to stop the initial variable a from being reinitialized each run, I end the code with a ;a, which is benign on its own, but combined with the next loop to create the scapegoat aa to be assigned instead. This trick isn't mine; I saw it in a previous answer. I'd appreciate if someone could point me so I could give credit.

Actually, is the final newline printed?

no I don't think the final newline is printed. But simply removing the , after print a should work. print a prints a newline after each print.

@Quincunx Oh, of course, thanks!

Are you talking about this post?

CJam, 6 bytes
LLS+:L

Uses the fact that n2 + n + (n+1) = (n+1)2.
L      "Push L. Initially this is an empty string, but its length increases by 1 with each copy
        of the snippet.";
 L     "Push another L.";
  S+   "Add a space to the second copy.";
    :L "Store the lengthened string in L for the next copy of the snippet.";

:L..1+ is the same idea in GolfScript.

@PeterTaylor I was thinking ..n+ in GolfScript, but that pesky trailing newline... :(

Hah, you're right. No need for :L because it's not used.

///, 21 bytes
I'm sure there is a really short and twisted way to solve this in /// but I couldn't find anything, beyond the "straightforward" way yet:
1/1\//112\///2\//1\//

This is based on the approach of printing consecutive odd numbers. The snippet consists of a 1 at the start which is printed, and two replacements which add two more 1s to that first part of each consecutive copy of the snippet. Let's go through this for N = 3. The following should be read in groups of 3 or more lines: 1. the current code, 2. the processed token(s), 3. (and following) a comment what the above token does.
1/1\//112\///2\//1\//1/1\//112\///2\//1\//1/1\//112\///2\//1\//
1
is printed
/1\//112\///2\//1\//1/1\//112\///2\//1\//1/1\//112\///2\//1\//
/1\//112\//
replaces all occurrences of 1/ with 112/. This affects the starts of all further snippets
but not the substitution commands, because the slashes in those are always escaped.
It is necessary to put a 2 in there, because otherwise the interpreter goes into an infinite
loop replacing the resulting 1/ again and again.
/2\//1\//112/1\//112\///2\//1\//112/1\//112\///2\//1\//
/2\//1\//
Replace all occurrences of 2/ with 1/, so the the next snippets substitution works again.
111/1\//112\///2\//1\//111/1\//112\///2\//1\//
111
is printed
/1\//112\///2\//1\//111/1\//112\///2\//1\//
/1\//112\//
add two 1s again
/2\//1\//11112/1\//112\///2\//1\//
/2\//1\//
turn the 2 into a 1 again
11111/1\//112\///2\//1\//
11111
print 11111
/1\//112\///2\//1\//
the last two substitutions have nothing to substitute so they do nothing

Interestingly, it works just as well if we move the 1 to the end:
/1\//112\///2\//1\//1

><>, 14 bytes
1:na*a*';'10p!

Uses the "sum of consecutive odd integers starting from 1" idea. It starts off with 1 and multiplies it by 100 each time, increasing the length of the output progressively by increments of 2.
For example, appending 5 copies gives
1100100001000000100000000

I tested by piping the output to a file, and didn't see a trailing newline.
Breakdown
1                   Push 1, skipped by ! every time except the first
 :n                 Copy top of stack and output as num
   a*a*             Multiply by 10 twice
       ';'10p       Modify the source code so that the first : becomes a ; for termination
             !      Skip the next 1

CJam, 10 9 bytes
],)_S*a*~

This prints N2 spaces where N is the number of copies of the code.
Code eexpansion:
],            "Wrap everything on stack and take length";
  )_          "Increment and take copy";
    S*        "Get that length space string";
      a*      "Wrap that space string in an array and create that many copies";
        ~     "Unwrap so that next code can use to get length";

Try it online here

Python 2, 20 bytes
g=0
print'g'*g;g+=2#

Java - 91 bytes
{String s=System.getProperty("a","");System.out.println(s);System.setProperty("a","xx"+s);}

This solution is equivalent to this other one in Python. It surely won't win, but it was fun :)

Don't you need a class to run anything?

No, since OP asked for snippets of code. We can assume this is running inside a main, for example.

Then I have a 59 or even 44 byte solution.

Cool :) I prefer one-liners, but yours is indeed shorter!

Perl, 14 bytes
print;s//__/;

This needs to be run with Perl's -l command switch, which causes print to append new lines.
It prints the default variable $_, then prepends two underscores via substitution.
Example:
$ perl -le 'print;s//__/;print;s//__/;print;s//__/;print;s//__/;'

__
____
______

flags are counted as 1 more byte per flag

What about say?

@chilemagic I tried that, but I couldn't get it working on my versions of Perl.

@grc it's version 5.10 and higher and you need -E instead.

@chilemagic hmm, that didn't seem to work for me on 5.16.

@grc that's really odd. I just tested it on 5.14 in cygwin perl -E 'say;s//__/;say;s//__/;say;s//__/;say;s//__/;' prints the same output as the example in your answer.

Brainfuck, 10 chars
Both previous Brainfuck solutions were waaay too long (16 and 11 chars) so here is a shorter one:
+[.->+<]>+

In the n-th block it prints out 2*n-1 characters (with codepoints from 2*n-1 to 1)

This wouldn't work in standard brainfuck, only if the cells are unlimited-size. Actually, it wouldn't totally make sense then either. How do you output character code 1 trillion?

C, 87 bytes
#if!__COUNTER__
#include __FILE__
main(a){a=__COUNTER__-1;printf("%*d",a*a,0);}
#endif

This uses two magic macros. __COUNTER__ is a macro that expands to 0 the first time it is used, 1 the second, etc. It is a compiler extension, but is available in both gcc, clang, and Visual Studio at least. __FILE__ is the name of the source file. Including a file in C/C++ is literally the same as pasting it directly into your source code, so it was a little tricky to make use of.
It would still be possible to use this technique without __COUNTER__. In that case, the standard guard against using code twice could be used for the #if statement, and __LINE__ could be used to count the number of characters needed.

This solution is not written in C, but rather a C dialect. Please correct the language name.

@FUZxxl Most code-golf answers are only designed to work in gcc, so I'm not sure why this would be an issue.

It isn't, but you should really declare that.

I'm confused. Why declare a non-issue? O_o

@corsiKa It's only a non-issue if you declare it. The C gcc speaks is not standard C.

@FUZxxl I would say the compiler listens to C, not speaks it :) It understands standard C perfectly well, but also knows some other words.

@feersum I don't care how you say it. A standard conforming compiler may reject your program for it violates the standard.

Prelude, 18 12 bytes
^1+(9!1-)#2+

This prints N2 tabs. It assumes a standard-compliant interpreter which prints characters instead of numbers, so if you use the Python interpreter you'll need to set NUMERIC_OUTPUT to False.
The idea is simply to use the top of the stack (which is initially 0) as 2(N-1), and print 2N-1 tabs, then increment the top of the stack by 2. Hence each repetition prints the next odd number of tabs.

Java - 59 / 44 (depending on requirements)
static String n="1";
static{System.out.print(n);n+="11";}//

Apparently we're allowed to assume code runs in a class.
If it can go inside a main method:
String n="1";
System.out.print(n);n+="11";//

Dyalog APL, 20 19 bytes
A matrix based solution.
{⍺≢⍵:⍵⍪⍵,⍺⋄∊⍺}⍨⍪'a'

Try it here. Returns a string of N2 repetitions of a. Explanation by explosion for N = 2:
{⍺≢⍵:⍵⍪⍵,⍺⋄∊⍺}⍨⍪'a'{⍺≢⍵:⍵⍪⍵,⍺⋄∊⍺}⍨⍪'a'
                                  ⍪'a'  Wrap 'a' into a 1x1 matrix.
                'a'{            }⍨      Binary function: bind 'a' to ⍵ and the matrix to ⍺.
                    ⍺≢⍵:                The arguments are not identical,
                        ⍵⍪⍵,⍺           so add to the matrix 1 column and 1 row of 'a's.
               ⍪                        Identity function for a matrix.
{            }⍨                         Unary function: bind the matrix to both ⍵ and ⍺.
 ⍺≢⍵:                                   The arguments are identical,
           ∊⍺                           so flatten the matrix into the string 'aaaa'.

T-SQL 117
IF OBJECT_ID('tempdb..#')IS NULL CREATE TABLE #(A INT)INSERT INTO # VALUES(1)SELECT REPLICATE('a',COUNT(*)*2-1)FROM #

Note the trailing space to ensure that the if condition is properly checked every time.
Uses the odd numbers approach. Not sure if there's a newline on select statements.
Not sure if there's a shorter way to create a table if it doesn't exist.

Kudos to you for an unusual language choice.

STATA 20
di _n($a)
gl a=$a+2

There is a trailing new line to make sure that the display (di) statement works.
First display the current number in $a newlines (and one additional from the default of display). Then add 2 to $a.
Uses the even numbers approach (i.e. odd numbers approach minus 1) with an extra newline every time.

PostScript, 35 chars
count dup 2 mul 1 add string print

Each pass "leaks" one thing on the stack, so count goes up by 1 each time.  Then it justs uses the sum of odd numbers trick.
The bytes output are all \000 because that's the initial value of strings.

Haskell, 72
putStr$let a="1";aputStr=(\n->take(n^2)$show n++cycle" ").(+1).read in a

Explanation
The apply operator $ acts as if you place surrounding parentheses around the rest of the line (there are exceptions to this, but it works in this case). aputStr is a function that takes a string with the format "abc    ...", where "abc" is the square root of the length of the string, including abc. It will parse the string as an integer, and return a string starting with abc+1 and having that length squared. Because of the $ operator, this will get called recursively on "1" N times.

Vyxal, 4 bytes
:I,⇧

Try it Online!
-2 thanks to lyxal.
Note: output is  in spaces + newlines.

I'm a little (a lot) late, but 5 bytes

Pyth, 8 bytes
*d*2Z~Z1

This relies on the fact that N2 is equal to the sum of N odd numbers. Now Pyth auto prints an new line, so I have to just print Z * 2 characters in each code where Z goes from 0 to N - 1.
Code Expansion:
*d               "Print d whose value is a space character"
  *2Z            "2 * Z times where Z's initial value is 0"
     ~Z1         "Increment the value of Z";

Try it online here

Golflua, 23 bytes
X=2+(X|-2)w(S.t("&",X))

outputs a combination of & and \n characters.
Equivalent Lua code
X = 2 + (X or -2)          -- initialize X to 0 the first time, add 2 ever other time

print(string.rep("&", X))

Each time the code snippet runs it produces 2 more characters of output than the last time, starting with 1 character. The print function appends a newline, so I initialize X to 0 instead of 1.

ActionScript - 27 / 26 bytes
var n=""
trace(n);n+="11"//

or
var n=1
trace(n);n+="11"//

How it works:
var n=""
trace(n);n+="11"//var n=""
trace(n);n+="11"//

It simply comments out the first line. Note: trace adds a newline. Or maybe all the IDE's I use do that automatically.

GML, 27
a=''show_message(a)a+='xx'a

Nim, 24 bytes
var s=""
echo s
s&="ss"#

Attempt This Online!
Attempt This Online!Attempt This Online!Attempt This Online!Attempt This Online!Attempt This Online!

Zsh, 12 bytes
<<<$n
n+=..

Try it online!
Same \$ n^2 = \sum_{k=1}^n 2k + 1 \$ as has been used elsewhere. The TIO test has to do some extra work because naively capturing the output in $(f) removes trailing newlines, and would output 0, 3, 8, 15, etc. Instead, we insert a printf : to add a character after the last newline, then ${output:0:-1} to remove it.

Pyt, 10 bytes
0ǰąŁ⁻√⁺²⑴ǰ

Try it online!
0              pushes 0
 ǰ             ǰoins stack with no delimiter
  ą            convert to ąrray of characters
   Ł           get the Łength
    ⁻          decrement
     √         square root
      ⁺        increment
       ²       square
        ⑴     array of (top of stack) 1s
          ǰ    ǰoin array with no delimiters (implicitly prints at end of code)

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


text:
How many contiguous "strings" can you find in a set of strings?
Consider the set of 16-character strings containing only the 95 printable ASCII characters. There are 9516 ≈ 4.4×1031 such strings.
Imagine these strings are put into a list and sorted lexicographically (which is the way most languages will sort a list of strings). What is the largest contiguous slice of this list you can find such that every string is a valid program in your programming language of choice whose output is the sole word string?
All output should go to the same place for all programs; use stdout or a similar alternative.
An optional trailing newline may be a part of the output, but otherwise nothing besides string should be printed for any of your 16-character programs. There is no input and all programs should run without erroring. The program does not have to terminate.
The list of length 16 strings does not "loop-around" from ~~~~~~~~~~~~~~~~ to                  (16 spaces).
Give your starting string and ending string and explain why every program-string that's in between them lexicographically outputs string.
The submission with the largest slice wins.

Is it my imagination or is this challenge just "find the language that prints a string literal and can throw away the most additional characters"?

///, 6634204313747905 > 958
From
string/.~~~~~/0

to
string/0     /.~

This relies on the program not being required to terminate. I started from a core-range of 958 much like the other solutions, from
string//

to
string//~~~~~~~~

However, in this case, // is not a comment. In /// everything that's not a slash is just printed (hence this always prints string before doing anything else). A slash then starts a substitution pattern of the form /pattern/replacement/. If only one or two / are found, then the program simply terminates. However, the above range obviously also includes strings with three or more slashes. The trick here is that the pattern to be searched for is empty, and substitutions are performed iteratively until the pattern cannot be found any more. Since the empty string can always be found, this substitution never terminates, and hence the program never gets around to print anything after the initial string.
But since this doesn't rely on // being a comment, we can actually go a bit further! E.g. the previous and next string around this range, respectively, are:
string/.~~~~~~~~
string/0

These still don't contain a full substitution instruction so they also only print string and then terminate. Let's see how far we can go! I'll focus on the upper end of the range (the lower end works analogously). What if we get another /? The first time this happens is
string/0       /

But that's still not a valid replacement pattern, so all is well. It looks like we need three slashes to break the magic. The first time we get three slashes is at
string/0      //

What now? Well, the pattern to be searched for is 0 (and a bunch of spaces), to be replaced with an empty string. That pattern is never found, so the substitution completes immediately. But luckily, there is nothing to print afterwards in the source code, so the result is still only string. Neat. :)
So we need a valid substitution instruction and more source code afterwards to not print string:
string/0     //

And this is indeed the first code that doesn't work to spec, as it prints string followed by a space. So the last code that works is
string/0     /.~

We can apply the same argument to the beginning of the range, the last failing code being
string/.~~~~~//~

such that the first code that works is
string/.~~~~~/0

pyexpander: 95^8 = 6634204312890625
string$#

to
string$#~~~~~~~~

Wow, it took forever to find the language I was looking for: one that outputs most source literals untouched and has a rest-of-line comment delimiter. This is still not theoretically optimal, as it's possible that another language like this exists, but with a one-character comment delimiter. However, I couldn't find one.

This is almost 100 times better than the other answers. xD

GolfScript: 95^7 = 69833729609375
"string"#

to
"string"#~~~~~~~

Everything from the # is a comment; the literal string is echoed at the end of execution.

I think your score is actually a bit higher. The code before your first one is "string""~~~~~~~ and as far as I know and unmatched " acts like a "supercomment" just as an unmatched } does. So I think your earliest valid code is "string""~~~~~~#.

@MartinBüttner, no, the parser complains "Unterminated string meets end of file".

PHP, 95^7 = 69833729609375
string<?#

followed by arbitrary characters.

+1 for using my pet language. Golfing in PHP is a real challenge :)

Microscript, 95^6=735091890625
"gnirts"ah (padded to 16 chars with trailing spaces) through "gnirts"ah~~~~~~

Windows Powershell: 95^7 = 69833729609375
"string"#

to
"string"#~~~~~~~

All characters from the # and following are part of a comment.
Same as @PeterTaylor's GolfScript answer


text:
Black or white keys of jazz chords?
When playing the piano, I realized that to play a chord right, I usually need to remember just which tones of the chord are played on white and which on black keys. The rest is usually handled by the "autopilot".
Let's write a program that given a 7th chord, it outputs which of its tones are to be played on black (character ^) and which on white keys (character -). Each chord name has a root, which is a capital letter A to G, optionally followed by b or #, and then by its type, which is one of the following. All 7th chords contain 4 notes, and the formulas are given in integer notation below.

7 Dominant (0,4,7,10)
M7 Major (0,4,7,11)
m7 Minor (0,3,7,10)
dim7 Diminished (0,3,6,9)
m7b5 Half-Diminished (0,3,6,10)
-M7 Minor/Major (0,3,7,11)

Integer notation means that you must play the four notes that are (w,x,y,z) semitones from the root. (w is the root and is therefore always zero.)
So for example for input Bb-M7 the output would be ^^-- (corresponding to Bb-Db-F-A).
The program should either read the chord form stdin and output the result to stdout, or it should be a function that accepts a string and returns a string.

Interesting challenge. Is it just coincidence or why do we actually talk the same topic in music class?

I like the challenge, but I felt for people like me, who can barely read music, the explanation in the link was rather difficult to follow. I've gone ahead and added integer notation to the question, which is much easier to follow for non-musicians.  Roll it back if you don't like it. Also '-M7' should be minor/major. C major minor 7th would just be C dominant.

Isn't this essentially a duplicate of this earlier question?

@PeterTaylor I would say not, because the bonus for the 7th chords on the question you linked was quite low, so nobody did it. Also the fact that this question only requires an output of black/white will lead to very different strategies, such as the one I introduced in this question http://codegolf.stackexchange.com/q/36497/15599

Is "Bb-M7" a Major or Major/Minor chord?

Is the example a typo meant to be "BbM7"?

@steveverrill like a keytar?

@steveverrill I remember a Super simplified version of this with an electric keyboard from moog in the early ninties. there was a "meta pedal" when pressed it changed the key layout to one you could define. did not change any keys that were pressed when the pedal was pushed. there may be an implementation out there somewhere thats does what you want.

@dennisdeems No, it really is Bb-M7 - it's the Minor/Major chord, denoted by -M7.

@PetrPudlák In that case ^--- is wrong.

Petr, I think @dennisdeems 's point is, that if it is a Minor/Major chord, it should have a Db in it Bb-Db-F-A. If that is what you mean, please correct. Also note that the question still says "Major-minor" where I believe you mean minor-major"

Yes, that's what I meant.  Either the chord is named incorrectly or spelled incorrectly.

@dennisdeems You're right, I corrected the answer.

@steveverrill have a virtual medal for picking up after Petr :)

@aditsu haha thanks. I'll have another one for my 155-byte C answer which I'm going to post soon, if I may.

CJam - 75
q('@m2*_6/-\_0="b #"#_){(@+\1>}{;}?1b81*A+H/6%8+2b1>{1$3++}/]2774Ybf="^-"f=

Try it at http://cjam.aditsu.net/
Brief explanation:

('@m2*_6/- Convert the first character to a number of semitones (starting from G for convenience)
\_0="b #"#_){(@+\1>}{;}? Adjust for b or #
1b81*A+H/6%8+2b1>{1$3++}/] Convert the rest of the chord to a unique number (I used the sum of ASCII codes here) and then do some clever calculations with it to obtain the 4 notes of the chord
2774Ybf="^-"f= Convert the notes to black/white as 0/1 (binary digits of 2774), then convert 0/1 to ^/-.

Python3, 293 242 bytes
This is my first CodeGolf. I am curious to see how others do this.
def f(s):
 for j in 4,3,2,1:
  try:return ''.join(['-^--^-^--^-^'[('A BC D EF G'.index(s[0])-('b'==s[1])+('#'in s)+i)%12]for i in(0,)+{'7':(4,7,10),'M7':(4,7,11),'m7':(3,7,10),'dim7':(3,6,9),'m7b5':(3,6,10),'-M7':(3,7,11)}[s[-j:]]])
  except:pass

Edit on 01.06.15
Thanks to the commenters, we found some tricks to shorten the code. I also discovered that changing to a function is slightly shorter. Old code: http://ideone.com/j5gmV2. P.S. I am just copying the code into triple quotes in Python and calling len to get the number of bytes.
Note:
I am assuming that Bb-M7 is Bb Major/Minor, i.e. that there is no delimiter between the note and the chord type, as described in the OP's second paragraph. Thus Bb-M7 gives ^^--. If Bb-M7 means Major, then what is Bb Major/Minor? Should it be Bb--M7?

Dicts where the key or value is a single char tend to be shorter with a bit of zipping, e.g. dict(zip('ABCDEFG',[0,2,3,5,7,8,10]))

@Sp3000 even better: 'A BC D EF G'.find(s[0])

Golfed it down a lot: http://ideone.com/1N1BJx. It's at 247 chars now

And 238 bytes with a while loop I think.

Welcome, not bad for a first golf :) Feel free to edit your answer using the suggestions from the comments.

C, 154 151 bytes
Rev 1 eliminated variable f by doubling with p, and placed formula search inside for bracket.
char c[9],s[]="d7m+mM-";n;main(p){gets(c);n=*c*2%7+(c[p]&4?0:5+c[p++]%2*2);for(p=strchr(s,c[p])-s<<!!c[p+3]|8;p;p/=2)putchar(45+n%12/7*49),n+=9-p%2*5;}

Rev 0
char c[9],s[]="d7m+mM-";n;f;main(p){gets(c);n=*c*2%7+(c[p]&4?0:5+c[p++]%2*2);f=strchr(s,c[p])-s<<!!c[p+3]|8;for(;f;f/=2)putchar(45+n%12/7*49),n+=9-f%2*5;}

EXPLANTATION
I've used a bit of music theory to help reduce my score.
Terminology
A seventh chord is composed of the 1st, 3rd, 5th and 7th notes of a diatonic scale. These names are also used to describe intervals.
A "3rd" is an interval of 3 or 4 semitones, known as "minor" and "major" 3rds respectivelty.
A "5th" is made by stacking two "3rds", and a "7th" is made by stacking a "5th" and a "3rd."
The standard 5th is the "perfect 5th" (of 3+4 or 4+3 = 7 semitones.) "Diminished" (3+3=6) and "augmented" (4+4=8) 5ths are also possible.
There are two standard 7ths: "minor" (7+3=10) and "major" (7+4=11) and one nonstandard 7th: "diminished" (6+3=9.)
Note that there is no "augmented" 7th interval, because 8+4=12 sums to a whole octave.
Stacked Thirds
All of the seventh chords required in this question are based on stacked thirds. That is, the inteval between one note and the next is always three or four semitones. Therefore we can encode the formula for the chord type as a 3-bit binary number as below. (The increments are coded into binary from right to left and the 4th bit is set to 1 to signal the end of the information.)
Symbol   Name             Formula   Increments  Binary
dim7     Diminished       0,3,6,9       3,3,3   1 000
7        Dominant         0,4,7,10      4,3,3   1 001
m7       Minor            0,3,7,10      3,4,3   1 010
+M7      Augmented/Major* 0,4,8,11      4,4,3   1 011
m7b5     Half-Diminished  0,3,6,10      3,3,4   1 100
M7       Major            0,4,7,11      4,3,4   1 101
-M7      Minor/Major      0,3,7,11      3,4,4   1 110

*The augmented major seventh chord is not required by the question, nor is it implemented correctly, because it clashes with the #/b correction.

The binary is obtained from the first character of the chord type by finding its position in the string "d7m+mM-". There is a problem with the m7b5 chord, because there are two m's in the string and strchr will always find the first one. To fix this, the binary is leftshifted one place whenever the chord type has more than 3 characters.
Circle of fifths
Instead of organising the notes as A A#/Bb B C etc, I use an imporant alternate representation called the Circle of fifths. In this we start at F and count 7 semitones each time, giving the following sequence:
F C G D A E B F#/Gb C#Db G#/Ab D#/Eb A#/Bb

As can be seen, all the white notes come first, followed by all the black notes. This is no coincidence: the fifth (7 semitones, frequency ratio 3/2) is the most important musical interval after the octave (12 semitones, ratio 2/1). The familiar scale of 7 out of the 12 available notes is constructed by stacking these "fifths."
The input note letter can be converted to its position in the circle of 5ths by ASCII code*2%7, then 5 is added for a flat or 7 for a sharp.
In the domain of fifths, a minor third is nine fifths (minus five octaves): 9*7=63, 63%12=3 and a major third is four fifths (minus two octaves): 4*7=28, 28%12=4.
For output, any number below 7 is a white note, any number 7 and above is a black note.
REV 0 UNGOLFED CODE
char c[9],s[]="d7m+mM-";n;f;                     //array c is filled with zeroes
main(p){                                         //if no arguments are given, p initialised to 1
  gets(c);
  n=*c*2%7                                       //convert character zero to its position in cycle of fifths, then correct for #/b in the next line
  +(c[p]&4?0:5+c[p++]%2*2);                      //# and b are the only characters in position 1 whose ASCII codes have the 4's bit clear.
  f=strchr(s,c[p])-s<<!!c[p+3]|8;                //find binary representation of stacked 3rds, correct for m7b5, and OR with 8
  for(;f;f/=2)                                   //at end of iteration, rightshift f. loop will end when f=0 (when 8's bit shifted out)
    putchar(45+n%12/7*49),                       //if n%2<7, put ASCII 45='-', else put ASCII 45+49='^'
    n+=9-f%2*5;                                  //increment n by a minor third (9 fifths) or major third (4 fifths)
}

Java 513 492 characters
This is my first time entering as well.  Hope I'm doing this right.
public class W{String n="C D EF G A B",a="b_#",w="-^-^--^-^-^-";
public String z(String h){int r=0,i=0;char k=h.charAt(i);int p=n.indexOf(k);char l=h.charAt(++i);
if(a.contains(String.valueOf(l))){i++;r=a.indexOf(l)-1;}
p=(p+r)%12;String q=h.substring(i);q="q"+q.replace("-","_");
C c=C.valueOf(q);int[] s=c.s;String y="";
for(int j:s){int t=(j+p)%12;y+=w.charAt(t);}return y;}
enum C{q7(0,4,7,10),qM7(0,4,7,11),qm7(0,3,7,10),qdim7(0,3,6,9),qm7b5(0,3,6,10),q_M7(0,3,7,11);
int[] s;C(int...a){s=a;}}}

Ungolfed
public class BlackWhiteKeys
{
String noteNames = "C D EF G A B";
String accidentals = "b_#";
final String blackWhite = "-^-^--^-^-^-";

public String analyze( String chordName )
{
    int index = 0;
    char tonic = chordName.charAt( index );
    int pitch = noteNames.indexOf( tonic );
    char alteration = chordName.charAt( ++index );
    int transpose = 0;
    if ( accidentals.contains( String.valueOf( alteration ) ) )
    {
        index++;
        transpose = accidentals.indexOf( alteration ) - 1;
    }
    pitch = ( pitch + transpose ) % 12;

    String quality = "q" + chordName.substring( index ).replace( "-" , "_" );
    Chord c = Chord.valueOf( quality );
    int[] semitones = c.semitones;
    String pattern = "";
    for ( int i : semitones )
    {
        int tone = ( i + pitch ) % 12;
        pattern += blackWhite.charAt( tone );
    }
    return pattern;
}

enum Chord
{
    q7(0, 4, 7, 10),
    qM7(0, 4, 7, 11),
    qm7(0, 3, 7, 10),
    qdim7(0, 3, 6, 9),
    qm7b5(0, 3, 6, 10),
    q_M7(0, 3, 7, 11);
    int[] semitones;

    Chord( int... semitones )
    {
        this.semitones = semitones;
    }
}
}

I could use a map instead of the enum, but it would be less object-oriented that way.

Welcome :) Remember, the goal here is to make it as short as possible. That usually goes against good programming practices and coding conventions.

I just noticed that the question doesn't say so explicitly, however it is tagged as code-golf.

Welcome to PPCG! As this is [tag:code-golf], please show some effort shortening your code, by at least removing unnecessary whitespace and using single-letter variable/function/class names. You can always include an "ungolfed" (readable) version in addition to that.

Thanks for the guidance.  I've modified to be more compact.  I've seen other Java entries use character count, so I've done likewise.

C# 468
string f(string p){var x=new Dictionary<char,int>{{'C',1},{'D',3},{'E',5},{'F',6},{'G',8},{'A',10},{'B',12}};var y=new Dictionary<string,string>{{"7","0,4,7,10"},{"M7","0,4,7,11"},{"m7","0,3,7,10"},{"dim7","0,3,6,9"},{"m7b5","0,3,6,10"},{"-M7","0,3,7,11"}};var m="--^-^--^-^-^-";var r="";int j=1,i=0,k=0;if(p[1]=='b')i--;if(p[1]=='#')i++;if(i!=0)j=2;i=i+x[p[0]];var a=y[p.Substring(j)].Split(new char[]{','});for(;k<a.Length;k++)r+=m[(int.Parse(a[k])+i)%12];return r;}

For me it looks ok. I tested it but who knows ;)
I also think that for
Bb-M7

you should get
^^--

Mathematica 296
f[s_]:=StringJoin[Mod[#3+#1+Switch[#2,"",0,"b",-1,"#",1],12]&@@StringSplit[s,Join[Thread@Rule[Characters["C D EF G A B"],Range[0,11]],{"7"->{0,4,7,10},"M7"->{0,4,7,11},"m7"->"0,3,7,10","dim7"->{0,3,6,9},"m7b5"->{0,3,6,10},"-M7"->{0,3,7,11}}]]/.Thread@Rule[Range[0,11],Characters["-^-^--^-^-^-"]]]

For Cdim7 (<-my favourite one)
In:= f["Cdim7"]
Out= -^^-

Java - 247
String j(String s){int i=2,t=0,x=s.charAt(0)*2-128,c=s.charAt(1);x-=x/6+(c==98?1:c==35?-1:(i=1)-1);while(i<s.length())t+=s.charAt(i++);int[]a={0,t%11>0?3:4,t%9>0?7:6,(t%9-t%5)/3+10};s="";for(i=0;i<4;)s+=(1717&1<<(x+a[i++])%12)>0?"-":"^";return s;}

Basically a translation of my CJam solution :)
Executable program with better formatting:
public class J {
    String j(String s) {
        int i = 2, t = 0, x = s.charAt(0) * 2 - 128, c = s.charAt(1);
        x -= x / 6 + (c == 98 ? 1 : c == 35 ? -1 : (i = 1) - 1);
        while (i < s.length())
            t += s.charAt(i++);
        int[] a = { 0, t % 11 > 0 ? 3 : 4, t % 9 > 0 ? 7 : 6, (t % 9 - t % 5) / 3 + 10 };
        s = "";
        for (i = 0; i < 4;)
            s += (1717 & 1 << (x + a[i++]) % 12) > 0 ? "-" : "^";
        return s;
    }

    public static void main(final String... args) {
        System.out.println(new J().j("D#m7"));
    }
}

Output:
^^^^


text:
Typing with scrambled keys
Your friend isn't too good with computers so as a practical joke someone scrambled the letters (a-z) on his keyboard. When he sit down and tried to type his name looking at the keyboard he realized that the letters are scrambled and asked your help.
You are smart so you know that if he types his name and then repeatedly retypes what comes up on the screen instead of his name he will succeed inputting in his name eventually. You are also kind and rearrange the keys but want to know how many turns would it take to succeed.
Your task is to write a program or function that given the shuffling of the letters and the friend's name computes the number of turns.
Input details:

Two string are given as input in a structure convenient for your language.
The first string is the list of the new lowercase letters in alphabetical order of the old ones. (The first character is the one that is at the position of a, last one is  at the position of z.) Some change will always occur in the string.
The second string is the name. It could contain any printable ascii character but only the upper and lowercase alphabetical characters will be shuffled if any. The name itself might not get shuffled at al.

Output details:

Output is a single integer the number of turns minimally required. Newline is optional.

Examples:
Input:
'abcfdeghijklmnopqrstuvwxyz' 'Mr. John Doe' (d, e, f positions changed)
Output:
3 (The shown names are: Mr. John Fod => Mr. John Eof => Mr. John Doe )
Input:
'nopqrstuvwxyzabcdefghijklm' 'Mr. John Doe' (the ROT13 cipher)
Output:
2 (Any input name that contains letters will take 2 rounds to produce the original name.)
Input:
'aebcdjfghiqklmnopzrstuvwxy' 'John Doe'
Output:
140
This is code-golf so the shortest entry wins.

You should probably include this test case: aebcdjfghiqklmnopzrstuvwxy (output 1260 for Mr John Doe). This is the maximum possible - it consists of cycles of order 4, 5, 7, 9 (and an unchanged a), and every name that contains at least one letter from each cycle will yield 1260. And I guess taking the alphabet itself as input or using an unaffected name are also important edge cases.

@MartinBüttner Added with modification.

I'm a bit confused about how you come up with the number of turns.

@FUZxxl In general, you can decompose the permutation into cycles, then you check which cycles include characters from the name. The result is the LCM of the lengths of those cycles (cycles through characters not in the name are irrelevant, of course). However, for this challenge, that's not really necessary... just perform the substitutions until you hit the original name and count how often you had to substitute.

Clarification: If no keys were moved, is the output 1? 0? either?

@isaacg 1 as the name would show up in the first try.

As a side note, John File Marker aka EOF is totally amazing!

Pyth, 16 bytes
JGfqzuXGJrQ0UTz1

Try it here.
Input should be given on two lines, name and then permutation. Permutation should be quoted. Name may be quoted or unquoted. For example:
"John Doe"
"aebcdjfghiqklmnopzrstuvwxy"

Gives 140.
Explanation:
                            Implicit:
                            z = input()              z is the name.
                            Q = eval(input())        Q is the permutation.
                            G = 'abcdefghijklmnopqrstuvwxyz'

JG                          J = G
  f             1           Starting at 1 and counting upwards, find
                            the first case where the following is true:
   qz                       z ==
     u       UTz            reduce, where the accumulator, G, is initialized to z on
      XG                    translate G
        J                   from the normal alphabet, J
         rQ0                to Q.lower().

Input method should be identical for the strings.

CJam, 31 27 25 24 bytes
l:A;lel:N{_A_$er_N#}g;],

Takes input in the form of:
aebcdjfghiqklmnopzrstuvwxy
Mr. John Doe

i.e. first line - alphabets, second line - name.
How it works:
l:A;lel:N{_A_$er_N#}g;],
l:A;                         "Read the alphabets from the 1st line in A and pop from stack";
    lel:N                    "Read the name in small caps from 2nd line and store in N";
         {         }g        "Run a while loop until we have the original name back again";
          _                  "Put a dummy string on stack just to keep count of times";
           A                 "Put the alphabets on stack";
            _$               "Copy them and sort the copy to get the correct order";
              er             "Transliterate the right keys with the wrong ones";
                _N#          "Copy the result and see if its equal to the original name";
                     ;]      "Pop the last name and wrap everything in an array";
                       ,     "Get the length now. Since we were putting a dummy string";
                             "on stack in each iteration of the while loop, this length";
                             "represents the number of times we tried typing the name";

Try it online here

Ruby, 58
->a,n{t=""+n
(1..2e3).find{t.tr!("a-zA-Z",a+a.upcase)==n}}

Explanation

Input is taken as arguments to a lambda.
Use Enumerable#find (thanks @Ventero!) and  String#tr! to replace characters until the replaced String matches the real name.

""+n is a bit shorter than n.dup, and you can save another byte by making creative use of Enumerable#find instead of using an explicit counter: (1..1e4).find{t.tr!(...)==n}

Also, you can save a lot of bytes by making the input n lowercase

@Optimizer That doesn't seem to save me anything, Ruby's method to convert to lowercase is quite lengthy (I'd have to use n.downcase!).

yeah, but then you dont have to do A-Z and +a.upcase

A-Z+a.upcase and n.downcase!\n have the same length :)

CJam, 32 31 bytes
llel_2e3,{;'{,97>3$er_2$=}#)p];

Test it here. It takes the permutation on the first line, and the name on the second line of the input.
Explanation
llel_2e3,{;'{,97>3$er_2$=}#)p];
ll                              "Read both lines into strings.";
  el_                           "Convert the name to lower-case and duplicate.";
     2e3,                       "Get a range from 0 to 1999 to cover all possible results.";
         {               }#     "Find the first index where the block yields a true result.";
          ;                     "Discard the number, it's just a dummy.";
           '{,97>               "Create a string of the lower-case alphabet.";
                 3$             "Copy the permutation.";
                   er           "Substitute letters in the second copy of the name.";
                     _2$=       "Duplicate and check for equality with original name.";
                           )p   "Increment by 1 and print.";
                             ]; "Clear the stack to prevent extraneous output.";

Pyth 26
KGJ@GrQZfqJusm@zxKdGUTJ!!J

Try it online here.
There are quite a few unfortunate consequences that cost this program bytes, like having to store G in K to use it in the reduce, as well as needing to use not(not(J)) to start the filter. Because of this, I expect this can still be golfed.
This is a program that takes input like:
aebcdjfghiqklmnopzrstuvwxy
'John Doe'

(Note the lack of quotes in the first argument)
Explanation to come after crippling exhaustion ;)

Should I repeat my previous comment ')

@Optimizer :P I  lost that last one ;)

You were saying ? ;)

Haskell 131 bytes
import Data.Char
h n=(!!((ord n)-97))
g s n m|n==m=1|0<1=1+g s(h n s)m
f s=foldr1 lcm.map((\x->g s(h x s)x).toLower).filter isAlpha

Call f with the permutation string and name to get the result
Explanation
-- h finds the mapping of a character given the permutation
h :: Char   -> -- Character to map
     String -> -- Character permutation
     Char      -- Mapped character

-- g finds the number of character mappings required to reach a given character
-- by calling h on the given character every time it calls itself.
g :: String -> -- The character permutation
     Char   -> -- The current character
     Char   -> -- The character to find
     Int       -- The number of mapped to find the character

-- f finds the number of mappings required to return the given string back to itself
-- by finding the lowest common multiple of the period of all the characters in the
-- given string
g :: String -> -- The permutation string
     String -> -- The string to get back
     Int       -- The final answer

GolfScript (33 bytes)
~{32|}%\:A&{.{A$?A=}%.-1$=!}do],(

Takes input as two (single- or double-) quoted strings separated by any amount of whitespace; e.g.
'abcfdeghijklmnopqrstuvwxyz' 'Mr. John Doe'

Online demo
Dissection
~           # Eval. Stack: perm name
{32|}%      # Lower-case name (also affects non-alphabetic characters but...)
\:A&        # Store perm in A and filter name to alphabetic characters, giving str_0
{           # do-while loop. Stack: str_0 str_1 ... str_i
  .         #   Duplicate str_i
  {A$?A=}%  #   tr 'a-z' perm   giving str_{i+1}
  .-1$=!    #   Loop while str_{i+1} != str_0
}do         # end do-while loop
],(         # Gather the sequence of permuted strings in an array and take its length - 1
            # to account for containing str_0 twice

The transliteration relies on the fact that all the characters are affected (it's {'ABC'?'abc'=}% with the sorted string A$ replacing 'ABC' and the permutation A replacing 'abc'); the more general alternatives don't save enough because the filter to alphabetic characters is so cheap.
This also relies on -1$ to access the bottom of the stack, which is a relatively rare GS trick.


text:
Keep your distance on a circle
This is based on this challenge and Geobits's/CarpetPython's idea to improve it:
Keep your distance!
For this challenge, the distance between two numbers is measured on a loop, so, for example, the distance between 0 and 999 is 1. This should prevent strategies like always picking the lowest or highest number from winning almost every time. The only other change is that the lowest number that can be chosen is now 0 instead of 1.
I'll summarize it here:

Write a function in Java, Python, or Ruby that takes three arguments:

the number of rounds played so far
the number of players
the numbers picked in the previous rounds, as an array of space-separated strings

It should return an integer from 0 to 999, inclusive
The score for a program each round is the sum of the square roots of the distances to the numbers each other program picked
The program with the highest score after 100 rounds wins.
One answer per person

The control program is here:
https://github.com/KSFTmh/src/
Leaderboard
NumberOne, by TheBestOne, is winning.

NumberOne - 9700
NumberOnePlusFourNineNine - 9623
AncientHistorian - 9425
FindCampers - 9259
WowThisGameIsSoDeep - 9069
Sampler - 9014
SabotageCampers - 8545

Apparently, my camper sabotage...er(?) doesn't work very well.
Here are the full results: https://github.com/KSFTmh/src/blob/master/results-3
I think this is different enough to not be a duplicate.
By the way, this is my first time asking a question on Stack Exchange, so let me know if I'm doing something wrong.

Do we really want a question this similar ?

@Optimizer A few people in the comments seemed to think this was a good idea. Answers from the original will work very differently here, so I don't think it's a duplicate.

I want to do this like the original, but I don't know how it worked, exactly. Did the person who posted the challenge run the control program to find the scores?

As the original question had a major loophole I wouldn't close this one. It might worth a meta topic to discuss if "fixing" a question is allowed if it considerably improves it's value. Unrelated but what if the answer would be also different thanks to the modification?

Thanks KSFT for organising this improved challenge. I have been AFK. As I understand it, the control program calls each answer program each round with the history of the previous calls (but I have not read the code). This may mean that you need to install a variety of obscure compilers and interpreters on your machine. You should also make sure the code does not do anything hostile before you run it. The output of the control program should provide the information for a leader board.

The credit for suggesting the challenge should go to @Geobits. I just agreed with him.

@CarpetPython Should I run the control program with all of the submissions each time a new answer is submitted?

@KSFT I am new to this leaderboard business. I would guess once per day or more often if more entries are added or changed (if your time allows). It should be up to you.

You have probably already thought of this, but the controller's distance calculation needs to change to something like sum(sqrt(min(1000-abs(x-y), abs(x-y))) for y in others) to implement the wrap-around feature.

@CarpetPython What I did was really long, but basically the same as that. I don't know Java very well, but I'm pretty sure it'll work right.

We need "Keep your distance on a sphere" for the next question :).

@KennyTM That's a good idea. I might post that if I ever get the controller for this one working.

Mmm. It seems that a constant number wins again. I am curious as to why that is. Could we see the 600 output numbers in the question, or on github or pastebin? I suspect some of our predictors have bugs. Possibly mine :-(

Until when will the challenge run? I.e., a certain date

@KennyTM How about on a toroid? The distance function would be much simpler.

@TheBestOne Ooh, I like that idea. What other shapes would work? Would these be closed as duplicates?

I suspect all puzzles using this idea will suffer from the same problem. The fixed point solutions will win. Predictors will stay away from the fixed points and crash into each other, ensuring the fixed points win. We would need a rule change to reward movement.

@KFST A toroid is equivalent to a rectangle with wrap around its edges. I expect they would.

@CarpetPython A simple change would be to compute the distance between the points from last around in addition to the points from this round.

@CarpetPython I had an idea about how to do that, actually. What if scores hare calculated based on distsance to numbers chosen in previous rounds, too?

@TheBestOne Wow

@CarpetPython/TheBestOne Should we use just one previous round or all of them? If we use just one round, what about the first round? If we use all previous rounds, should scores be multiplied in earlier rounds to compensate for the higher scores in later rounds because there are more points?

Why the downvote?

Am I allowed to add my own answer?

I am no expert on the rules here, but it is fine with me. I have added (non competitive) answers to many of my challenges, and nobody has complained.

The latest run seems to prove that camping is the best solution. Unlike most KOTH challenges, this one rewards being predictable. Rewarding predictability will mean the results will be, errr, predictable. Including previous numbers will just motivate campers to slowly (and predictably) move slightly each turn.

I find it amusing that my answer has only 1 upvote. I think I wouldn't it upvote either. :)

By 'Python', do you mean Python 2, Python 3, or both?

@ASCIIThenANSI Python 2 will definitely work, but I'm not sure about Python 3.

Python 2, Sampler
This entry is based on the same code for Keep your distance, Sampler entry. I hope it will do better here where the 1 and 999 advantages do not exist.
Out of a list of places, choose the one that is farthest away from recently used
numbers, ignoring the previous turn (because other entries may predict based on just the previous turn).
def choose(turn, players, history):
    sample = map(int, (' '.join( history[-5:-1] )).split())
    def distance(x):
        return sum(min(1000-abs(x-y), abs(x-y))**0.5 for y in sample)
    score, place = max((distance(x), x) for x in range(1000))
    return place

It looks like this one's winning, but that might be because I'm not compiling the controller right and the others are all crashing.

Number OnePlusFourNineNine, Java
public static int choose(int round, int players, String[] args) {
    return 500;
}

The logic is really simple. Unless someone finds a real algorithm which takes previous scores into consideration, this answer is fairly optimized.
Now that we count the distance in a circle, the maximum distance of any two points can be 500. Now if all entries were generating random numbers (or pseudo random based on some algorithm), this answer would not have been in any advantage at all. But there is at least 1 entry which produces a constant answer which an almost maximum distance. The makes the score come in favor of 500 as there is a fixed source of maximum distance possible in each round :)

You optimized my answer. ;)

@TheBestOne haha

AncientHistorian - Python
It is the same algorithm from the previous one, except when calculating the potential scores it uses the circular distance. Since I'm losing horribly and can't get the controller to compile, I'm just trying a new strategy, where I use the worst from the previous rounds.
def choose(round, players, scores):
    calc = lambda n, scores: sum([min(abs(int(i)-n), 1000-max(int(i),n)+min(int(i),n))**.5 for i in scores.split(' ')])
    return min(range(1000), key=lambda n: sum([calc(n, j) for j in scores[1:]])) if round>1 else 250

This doesn't work. i is an element of scores.split(' '), meaning it's a string, not an int.

@KSFT oh shoot, I really should have tested, updating.

FindCampers - Python 2
Find all the campers from the last 10 rounds and stay away from them. I'm hoping that predictors will run from me. I will now ignore my old choices.
def choose(rounds, players, previous):
    from collections import Counter

    def distance(x, y):
        return min(1000 - abs(x-y), abs(x-y))

    pastRounds = list(map(lambda x: Counter(map(int, x.split())), previous))
    me = 751
    for (index, round) in enumerate(pastRounds):
        round.subtract((me,))
        pastRounds[index] = set(round.elements())
        campers = reduce(lambda x,y: x.intersection(y), pastRounds[max(1, index-9):index], pastRounds[max(0,index-10)])
        if campers:
            dist, me = max(min((distance(x, y), x) for y in campers) for x in range(1000))
        else:
            me = 751
    return me

Aww...I was hoping this would go towards the campers when I saw the name...

Lol. I could add an entry that will sabotage campers.

Unfortunately, I only allowed one entry per person.

I just posted an entry to sabotage campers myself.

Mine doesn't work because I didn't realize that previous results were sorted. How does yours detect campers?

It turns the lists of numbers from the last 5 rounds into sets. It then intersects each set with the others. This will return a set containing only the numbers chosen in every round. I assume that these are the campers.

Does it avoid itself?

No. Every 10 turns, it will jump to the next best place, as it will think itself is a camper.

SabotageCampers - Python
def choose(rounds, players, previous):
    if rounds<3:
        return 1
    prevchoices=[int(i) for i in " ".join(previous[-5:]).split(" ")]
    remove=[]
    for i in prevchoices:
        if prevchoices.count(i)<3:
            remove.append(i)
    campers=[i for i in prevchoices if i not in remove]
    return random.choice(campers)

The campers are still winning. Let me know if you have any suggestions for this.

Number One, Java
The first answer. Copied from my previous answer.
public static int choose(int round, int players, String[] args) {
    return 1;
}

Someone seems to have downvoted all of the answers.

WowThisGameIsSoDeep, Java
I have analyzed the game for 10 years on a 1 million-core cluster and found the optimal
solution.
public static int choose(int round, int players,String[]spam) { return(int)(Math.random()*1e3); }

This ain't no [tag:code-golf]

That solution is not optimal. If you want a uniform distribution, you should use Random.nextInt(int).

This seems to always return 1.

@KSFT I tested it and got many different numbers. Maybe it's sabotage after all?

@KSFT I see the controller's process method returns 1 if it hits any kind of exception, so it's probably an error in your code.

It doesn't seem to be throwing any exceptions.

@KSFT How do you know it's not throwing exceptions if you catch them?

I have it print exception messages when it catches them.

@KSFT In the code I'm looking at, a message is printed only in the event of a ClassNotFoundException. Any other Exception is silently discarded.

I modified it so it always prints the message.

@KSFT If you aren't going to fix the controller, then please run "It's Sabotage" instead.

Aha! I fixed it! I accidentally typed "WowThisGameIsSoDeep.py", and it was trying to run it as a Python file.

Circilinear Extrapolator, Ruby
def choose(round, players, previous_choices)
  previous_rounds = previous_choices.map{ |round| round.split.map(&:to_i) }
  optimal_past_choices = previous_rounds.map do |choices|
    (0..999).max_by { |i| choices.map{ |c| root_distance(i,c) }.inject(:+) }
  end
  if (last_round = optimal_past_choices.last)
    (last_round + average_delta(optimal_past_choices).round) % 1000
  else
    750
  end
end

def root_distance(i,j)
  dist = (i-j).abs
  dist = [dist, 1000 - dist].min
  dist ** 0.5
end

def directed_distance(i,j)
  dist = j - i
  if dist > 500
    dist - 1000
  elsif dist < -500
    dist + 1000
  else
    dist
  end
end

def average_delta(ary)
  ary.each_cons(2).map{ |x,y| directed_distance(x,y) }.inject(0,:+)/ary.count
end

This is giving this error: NoMethodError: undefined method \split' for #Array:0x720f56e2
choose at CircilinearExtrapolator.rb:2`

Oh, is previous_choices an array of values like ["1 6 500","2 8 503"] ?

It is. Did you think it was something else? If not, I probably just messed something up running it.

I thought it was just a flat string, sorry. I'll edit.

Edited. Now everybody knows I posted something without testing it...

I'm now getting this: NoMethodError: undefined method \/' for nil:NilClass
average_delta at CircilinearExtrapolator.rb:31
choose at CircilinearExtrapolator.rb:7`

I don't know Ruby very well, but I can't figure out why that's happening.

Ah, I got it! It's only happening the first round. It's because there's only one element in ary.

Sorry again, fixed again.


text:
C golfing tips - returning 0 without return statement
I'm looking for some solution in returning values in main function, I need to shorten my program more, return 0 takes too much characters of my code, I need to return 0, or my code fails. I know that in C there can be no return statement, and then program will use result of last operation - but on which operations I can 'really' shorten my code?
At the moment I found brk(0) as shortest return.
main(n){while(~scanf("%i",&n))printf("%i ",n*~n/-2);brk(0);}

Which code-golfing contest requires that main return 0?

It would help to know some things: Can n be 0? Does extra whitespace invalidate the answer?

@feersum  it's from spoj challenges, code has to pass test - it has to return 0 or it does not pass it because of error, n can be <1,1001>, it can print answers with spaces, or new lines, it does not matter, judge checks numbers, i can even write 100x ' ' between each result

@encoree1337 "in C there can be no return statement, and then program will use result of last operation" - I think you are pushing it a bit there. Can you point to that being specified anywhere? As opposed to the result of last operation just coincidentally being left in the accumulator, which is where the return value would be on x86 (but not necessarily on other architectures)?  http://en.wikipedia.org/wiki/X86_calling_conventions

You don't need to do anything.
This assumption:

then program will use result of last operation

is erroneous. If there is no return statement, main returns 0. It is not dependent on whatever might be left over in registers or anything like that.
From the standard:

5.1.2.2.3 Program termination
If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.  If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

(emphasis mine)
Your program's main already returns zero, or something is wrong somewhere else.

Perhaps it should be noted that the standard you are referring to is C99, not C89 (which is the default on most compilers), in which omitting the return 0; resulted in undefined behaviour.
So yes, C99 and C++ allow you to omit the return 0; thing.

(and consequently, C11 too)

I believe the server in question indeed uses gcc in C89 mode, so this auto-return rule does not apply.

To be precise, the return value is generally dependent not on any previous "operation", but on the return value of the last function call. You are hoping that the function dumps a 0 into the EAX register, and that it stays there when main returns.
You may be able to get better mileage out of atoi/atol and gets here. When gets hits EOF without reading a line, it returns a null pointer. Then, atol will return 0 upon receiving a null pointer as input. Since 0 is not an allowed value for n, this can be used as the loop condition, as well as the way to drop 0 into the appropriate register.
main(n){while(n=atol(gets(??????)))printf("%i ",n*~n/-2);}

The only problem is to find some memory for gets to write on. I'm not familiar with the Unix-specific library functions such as brk, but surely you can find something 6 characters or less (needed for an overall shortening) which returns char* or void* among all the cruft.


text:
Pair-golfing Twin primes and the Collatz sequence
This is a new kind of challenge inspired by the Recover the mutated source code problem.
You should write two programs or functions both in the same language. The first one should solve Task #1 and the second one should solve Task #2.
Your score will be the sum of the longer program and the Levenshtein distance between the two programs source code. Lower score is better so you should try to make the two solutions similar while keeping the lengths of the programs short.
Task #1
You are given a positive integer N and you should output the Collatz sequence of N separated by spaces or newline.  Trailing separator is allowed.
The first element of the Collatz sequence is N. The rest of the elements are generated based on their successor \$a_{i-1}\$:
$$ a_i =
\begin{cases}
\frac{a_{i-1}}{2} & \text{ if } a_{i-1} \text{ is even} \\
3a_{i-1} + 1 & \text{ if } a_{i-1} \text{ is odd}
\end{cases}
$$
As soon as the sequence reaches 1 no new elements are generated.
Input => Output examples:
6 => 6 3 10 5 16 8 4 2 1
8 => 8 4 2 1
1 => 1

Task #2
A pair of twin primes is a pair of positive integer whose difference is 2 and they are both primes.
You are given a positive integer N and you should output the smallest pair of twin primes where both primes are bigger than N The first number should be the smaller one and the two primes should be separated by spaces or newline.  Trailing separator is allowed.
Input => Output examples:
6 => 11 13
42 => 59 61
1 => 3 5

Snippet for calculating the score
(Modification of the one in the Recover the mutated source code problem.)

var f=document.getElementById("f"),g=document.getElementById("s");function h(){var a=f.value,e=g.value,m=Math.max(a.length,e.length);if(10000<a.length)a="First program is too long!";else if(10000<e.length)a="Second program is too long!";else{if(0===a.length)a=e.length;else if(0===e.length)a=a.length;else{var d=[],b;for(b=0;b<=e.length;b++)d[b]=[b];var c;for(c=0;c<=a.length;c++)d[0][c]=c;for(b=1;b<=e.length;b++)for(c=1;c<=a.length;c++)d[b][c]=e.charAt(b-1)===a.charAt(c-1)?d[b-1][c-1]:Math.min(d[b-1][c-1]+1,Math.min(d[b][c-1]+1,d[b-1][c]+ 1));a=d[e.length][a.length]}a="Distance = "+a+"   Longer length = "+m+"   Score = "+(a+m)+""}document.getElementById("d").innerHTML=a}f.onkeyup=h;g.onkeyup=h;
First program<textarea id=f rows=2 cols=80 style="width:100%"></textarea>Second program<textarea id=s rows=2 cols=80 style="width:100%"></textarea>

Edit
In the answers' header let's use the format
[Language], [longer length] + [distance] = [final score].
E.g.
Python 2, 60 + 32 = 92

Pyth, 18 + 13 = 31
Collatz Sequence:
QWtQ=Q@,/Q2h*Q3QQ

Twin Primes:
=Qf!ttP*T+T2hQQ+Q2

Try it here.
Some ideas thanks to FryAmTheEggman.

CJam, 24 + 17 = 41 42
Collatz program:
ri2*{:N2%N3*)N2/?__p(}g;

Twin primes program:
ri_2+]{:)_{mp}/&_+((}gS*

Both take input from STDIN and print space/newline separated numbers to STDOUT
Try them online here

CJam, 25 + 16 = 41
Collatz program:
l~2*{_2%{3*)}{2/}?_p_(}g;

Twin primes program:
l~_2+]{:)_{mp}/&!_&}gS*

Test it here.
I just golfed both of them for now. I'll see if I can reduce the score somehow.

Pyth, 20 + 14 = 40 34
Collatz:
QWtQ=Q@,/Q2h*3QQQ

Prime Pairs:
~Q1WttP*Q+Q2~Q1;Q+Q2

Both are programs that take input from STDIN and output the numbers on newlines. Just golfed both answers while using the same looping primitive for now. This could probably be improved quite a bit.
Edit: Added better condition checking stolen from @isaacg. Seems like using filter is still shorter than using a while loop for the prime pairs.
Try it online here.

This outputs 3 5 for the input 3 on prime pairs. It should output 5 7.

@isaacg Fixed it, costed 3 :(

05AB1E, 14 + 13 10 9 = 27 24 23
-4 score thanks to ASCII-only
Collatz sequence (14 bytes):
[DÉi3*>ë2÷}Ð,#

Try it online!
Twin primes (14 bytes):
[DÅND>>Dp#}s,,

Try it online!

Golfed Twin primes (11 bytes):
[ÅNDÌp#]DÌ»

Try it online!

Collatz link is incorrect

primes, -3 score. probably worth keeping golfed version in the answer as a side note in case there's a different, better golf (what exactly does pair do, btw? like why do i have to do ,,, and why does only Ð, work there)

-1 more (edit: never mind, first number should be smaller. score 24 for now

22?

Thanks! Guess I was more focused on trying to golf each individual challenge rather than minimize the score. I am not quite familiar with the Levenshtein distance :)
Pair ‚ pops a, b and pushes [a,b]. Note that the pair instruction is not a comma :). The comma is actually the print instruction ,. Compare these programs: two prints and [pair](https://tio.run/##yy9OTMpM/f8/2uVwq5@LnV2BcqzL4Z5HDbP@/zc1NQIA "05AB1E – Try It Online). Note that the two different characters look identical in the tio.run font. :)

24 is the shortest correct one i think

score 23 if it is allowed to have output being a list of a list

Let us continue this discussion in chat.

Java 8, 118 + 84  = 202
Collatz:
n->{for(System.out.println(n);n>1;System.out.println(n=n%2<1?n/2:3*n+1));}

Twin primes:
n->{t:for(int p,z;;n++){for(z=n;z<n+3;z=z+2)for(p=2;p<z;p++)if(z%p<1)continue t;System.out.print(n+" "+(n+2));break;}}

mention Java 8 ..

><>, 116 + 86 = 202
Collatz program (46):
0i:0(?v$a*$'0'-+!
?v6,>:>~:nao:1=?;3*:2%
 >1+^

Twin primes program (116):
0i:0(?v$a*$'0'-+!
v&2+1~<:-2
<v!?%&+1:&:v?=&:&:
 >&~0$2&2+v>&~143.
:&:1+&%?!v>:&:&=?v
0v?*r$0~&< .561~&<.1
:<;noan-2

Ouch. Both programs start with the same atoi function, but after that twin primes goes downhill. The same piece of code is repeated twice for primality check — it might be slightly shorter to somehow reuse the piece, but the setup for it wouldn't save many bytes.
Could do a lot better by throwing the back half of twin primes into the unused spots of the Collatz program, but I'm not sure if that's allowed.

"Golf it, Golf it NAO!" - Noanold Golfzenegger. That said, the question doesn't seem to say that adding in garbage to reduce the Levenshtein distance is taboo, so I would go nuts ;)

Mathematica, 53 + 29 = 82
Collatz Sequence:
Print/@(NestWhileList[If[OddQ@#,3#+1,#/2]&,#,#>1&]);&

Twin primes program:
Print/@(NestWhile[NextPrime,#,!PrimeQ[#+2]&]+{0,2});&

C++ Distance = 114 Longer length = 155 Score = 269
Task 1
void c(int N){while(N>1){cout<<N<<' ';N=(N%2==0)?N/2:N*3+1;}cout<<N;}

Task 2
int p(int x){int z=0;for(int i=2;i<x;i++){if(x%i==0){z=1;break;}}return z;}
void c(int N){N=(N%2==0)?N+1:N+2;int M=N+2;while(p(N)+p(M)>0){N=M;M+=2;}cout<<N<<' '<<M;}

Task 2 improved
int p(int N){int z=0;for(int i=2;i<N;i++){if(N%i==0){z=1;break;}}return z;}
void c(int N){N=(N%2==0)?N+1:N+2;while(p(N)+p(N+2)>0){N+=2;}cout<<N<<' '<<N+2;}

I think you did not even try to reduce the score. For instance, you have different function names, different argument name different return type and what not which are increasing your distance.

@Optimizer I don't know of another way to test for primes? Other languages have this built in.

I was not even talking about changing the algo. For instance, this code has only 102 distance: int p(int x){int z=0;for(int i=2;1<x;i++){cout<<x<<' ';x=(x%2==0)?x/2:x*3+1;}cout<<x;return z;}

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