text:
"Useful" self-modifying script for financial firm
True Story:  Several years ago while interviewing at an investment advisory firm that managed over a billion dollars in client funds, I was asked a collection of reasonable and bizarre questions by a partner in the firm.  An example of a reasonable question would be "What can go wrong with a linear fit?".
But then, things devolved....
Interviewer: "Have you ever written code that modifies itself?"
Job Candidate:  "No, can't say that I have"
Interviewer: "We have one guy who writes programs that modify themselves, I think he uses awk"
Job Candidate: "Wow. That's pretty incredible. AWK? "
Now it is your turn to be that one guy that financial houses would kill to hire...
Challenge:  Write a self-modifying script of some kind that performs a "useful financial function".
Rules:

Use a scripting language, not a language requiring compilation such as C or Java.  Perl, Python and the like that will work from a #! are OK.  Of course, heroes use awk, but awk is not a requirement.
Self-modifying means that the script modifies its own source code. The script must be reusable after it has modified itself. The script might also generate useful user output to STDOUT or some other interface.
The definition of "useful financial function" is left to the voters and can be as intriguing or dysfunctional as you prefer. If you need examples for inspiration, here are a few ideas: stock picking, stock trading, prediction and/or fitting, future value of account, Ponzi scheme generator, risk analysis of Nigerian email deals, salary bonus calculator for partners vs employees, etc.
Most upvotes wins.

EDIT:  I agree with one participant who notes that it is not obvious how to read the current gawk script from within gawk. Here is a solution for Linux-based systems and other O/S that have a /proc filesystem.
#!/usr/bin/gawk -f
BEGIN {
pid = PROCINFO["pid"]
commfile = "/proc/"pid"/comm"
print "I will look here for the script file name: " commfile
print "Here is what is in that file:"
getline scriptfilename < commfile
print scriptfilename
print "Here is my script:"
while (getline line < scriptfilename){
      print line
      }
}

Removed code-challenge tag because it would require an objective winning criterion.

Wait, rule 2 disallows the self-modify Befunge. :-(

@Quincunx How would you modify the rule?

@Paul I'd just say that the program must be self-modifying: edits its own source code.

@Quincunx Sounds like a fine idea.

Wow, I tried to do this in AWK. I gave up after I found out that AWK doesn't support reading the current program. https://gist.github.com/xfix/8201410 - I checked every single variable - nope.

@GlitchMr My personal preference is to use awk for short data transformation scripts involving STDIN and STDOUT that are trivial enough not to need perl or python. I can't imagine anyone in their right mind writing a serious application in awk for production use that needs to open/close various files or goes beyond minor data munging or calculation in a pipe.

@Paul: I agree, but it was somewhat annoying to find out that after writing everything else in the program.

@GlitchMr I found a way.

You'd need to dig out the pid with gawk's PROCINFO["pid"] and then use that (on Linux) to read the file /proc/(pid)/comm, which has the filename (but not the full path) of the script in it. One could be lazy at this point and assume the script is in the current directory, or read some more PROCINFO and ENV vars and /proc filesystem entries until that is pinned down too.

Hm, ok. That would require me to access /proc filesystem that doesn't have to exist (it doesn't exist on FreeBSD I use), but that could work.

In PERL, special variable $0 contains the full pathname to the running script.  Just goes to show you shouldn't bring gawk to a perl fight.

What! You disallow Java eh! Well, I'm going to write a self modifying Java program, complete with compilation. Challenge accepted.

Question: Are we allowed to write our own CPU architecture to run this on, because I have the ISA/Specs. for a computer that I designed where self-modification of programming code is frequent/necessary for small code.  Down with Harvard architectures, Up with Von Neumann Architectures!  Long live the Princeton Architecture!  So, I can't see a problem with it, as assembly is technically interpreted by the machine...

Pseudocode
// Set up a cron job to run this script (only) once a day

yesterdays_stock_price = '46.48'

todays_stock_price = curl_google_finance('VTSMX')

print "Difference between yesterday's stock price and today's: "

print todays_stock_price

self = open('self.file')

self.replace( /yesterdays_stock_price = '[0-9\.]+'/, todays_stock_price)

self.save()

Nice.  I like how it doesn't work if you use it too much or at the wrong interval.

Maybe it should have a wait and loop in it too so it can self run, I love it.

Funny how you call it pseudocode where it's actually nearly Python.

gawk (1224 characters, as this is not code golf)
One of reasons why awk shouldn't be used for self-modifying scripts.
#!/usr/bin/gawk -f
function download(name,     url, service, host, old_rs, old_ors) {
    old_rs = RS
    old_ors = ORS
    RS = ORS = "\r\n"

    host = "download.finance.yahoo.com"
    url = "http://"host"/d/quotes.csv?s="name"&f=l1"
    service = "/inet/tcp/0/"host"/80"
    print "GET", url |& service
    service |& getline
    close(service)

    RS = old_rs
    ORS = old_ors

    return $0
}

function update(value,       file, self, result) {
    # Do complex stuff in order to find the program itself.
    file = "/proc/"PROCINFO["pid"]"/comm"
    if (getline < file <= 0) {
        print "/proc filesystem not supported." > "/dev/stderr"
        exit
    }
    close(file)
    if ($0 ~ /^g?awk$/) {
        print "You need to run program directly." > "/dev/stderr"
        exit
    }
    self = $0
    result = ""
    while (getline < self > 0) {
        # Avoid finding this line.
        if (/[y]esterday/) gsub(/[0-9]+(\.[0-9]+)?/, value)
        result = result $0"\n"
    }
    printf "%s", result > self
    close(self)
}

BEGIN {
    yesterday = 1120.71
    today = download("GOOG")
    update(today)
    print "Yesterday:", yesterday
    print "Today:", today
    print "Difference:", today - yesterday
}

Wow, an HTTP client in GAWK.

Using @jawns317 psueudocode:
BASH
#!/bin/bash
set -e;
google_price_last=1118.79;
current_google_price=`wget -qO- "http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=l1"|tr -d "\r\n"`;
echo "Current Price: $current_google_price";
echo "Last Price: $google_price_last";
echo "Price change: "`echo $current_google_price - $google_price_last | bc -l`;
sed -ri 's/last=[0-9\.]+\;/last='"$current_google_price"';/g' $0;

Back at uni I discovered (ah-hem) a system which I though would prove fool-proof at the local casino. Bet on red on the roulette wheel, and if you lost double the bet, and so on ...See Martingale System
VBS
Dim objFSO
Dim objTF
Dim strFile
Dim lngBet

lngBet = 5
strFile = "boss.txt"
'spin roulette wheel
Randomize

'18 blacks, 18 reds, 1 green
intnumber = Int(36 * Rnd + 1)

'mofify code to double-down losing bets
Do While intnumber < 18
intnumber = Int(36 * Rnd + 1)
bfound = True
Set objFSO = CreateObject("scripting.filesystemobject")
Set objTF = objFSO.createtextfile(strFile, 2)
objTF.writeline "lngbet=lngbet*2"
objTF.Close
Set objTF = objFSO.opentextfile(strFile, 1)
Execute objTF.ReadAll()
objTF.Close
Loop

If bfound Then objFSO.deletefile (strFile)
wscript.echo "final bet was " & lngBet

I have some pseudo code for someone to develop. All it really needs are some functions built to do the text replacement. I feel the function names give a sufficient description that the actual code is probably trivial.
Write "You should really give him back his stapler."
Write "No one has noticed an account with $0 ."
Write "Your TPS reports are complete."
Write "You should throw that Piece of * out the window."

$event = Random 1..3
$fireStarter = Random 1..100
$fractions = Random 1..100

switch $event
    {
    1 - $stapler = $false
    2 - $TPSreports = $false
    3 - $printerJam = $true
    }

if ($stapler = false)
    { Write "I think you have my stapler"

           if ( ($times + $fireStarter ) -GreaterThan 100 ) { Function Burn }
    $times + 1
    $stapler = $true
    Function SelfModifyLine1
    Function SelfModifyTimes
    }

if ( $Fractions -LessThan 50 )
    { $account = $account + $fractions
    Function SelfModifyLine2 }

if ( $TPSreports = $false ) {  Function SelfModifyLine3  }

Function YellAtPrinter
Out-file $scriptPath


text:
Write a function that tells you which TWO of its lines has been removed
In my previous code challenge, I asked you to write a function that tells you which of its lines has been removed.
The instructions were:

Write a function that contains five lines.
If you run the function as-is, it should return 0.
If you remove any one of the five lines and run the function, it
  should tell you which of the lines has been removed (e.g., if you
  remove the final line it should return 5).

Now, let's try something a teensy bit more difficult.
Follow the same rules as above, but this time, the function should return an array telling you which TWO lines have been removed.
So, for instance, if I remove lines 1 and 5, the return value should be [1,5], and if I remove lines 3 and 4, the return value should be [3,4].
Again, if no lines are removed, the function should return 0.  Bonus points if you can also handle the one-line-removed case, but it's not strictly necessary that you do so.
Can you make use of helper functions?  Yes, but only if you have to.  A single self-contained function that pulls this off is the ideal.
As with the last challenge, the highest upvoted solution wins.  I'll pick the winner in a week, or sooner if no new submissions have been received in 24 hours.

Is returning an empty list OK if no lines are removed, or does it have to be the number 0?

is the return line in the function one of the lines that can be removed?

May we expect that tomorrow the version "three-lines" will be posted?

Must the function literally return the array or can it edit a variable in the global scope .etc? I do not think this is possible in 5 lines whilst actually returning due to not being able to look ahead as all lines must return incase the return is removed. Unless there are some language quirks like automatic returning functions I don't know about.

I think you should also provide the link to your previous question, as for someone who is interested and has not seen it.

Could you please ask that as an actual standalone question, instead of a question referencing something else? It's making it hard to read for no good reason and it's turning away people who might not have been there in time for said previous question.

Perl
sub foo {
    @a = (2..5);
    @a = grep $_ != 2, (@a ? @a : (1..5));
    @a = grep $_ != 3, (@a ? @a : (1..5));
    @a = grep $_ != 4, (@a ? @a : (1..5));
    @a = grep $_ != 5, (@a ? @a : (1..5));
}

This actually works for any number of lines removed (as long as it's not all the lines, that is), and can be trivially extended to more than 5 lines.  No helper functions are used, and it even uses only one statement per line.  It relies on the fact that, in the absence of an explicit return statement, the return value of a Perl function is the value of the last statement in it.
Note that (in list context) this code returns an empty list rather than the number 0 if no lines have been deleted.  This could be fixed (e.g. by appending "@a ? @a : 0;" to the last line), but would make the code uglier.  In any case, in scalar context it does return the number of deleted lines, which will be 0 if no lines have been removed. ;-)

Ruby
Similar to the Perl version, but in Ruby. I return 0 if no lines are deleted as requested, but I agree it makes the code uglier and doesn't quite make sense as a return value.
def which_lines_removed(arr = [*1..5])
  arr -= [1]
  arr -= [2]
  arr -= [3]
  arr -= [4]
 (arr -= [5]).empty? ? 0 : arr
end

If an empty array is acceptable as the return value when no lines are deleted, the code looks like this:
def which_lines_removed(arr = [*1..5])
  arr -= [1]
  arr -= [2]
  arr -= [3]
  arr -= [4]
  arr -= [5]
end

Both methods work for any number of lines deleted between 0 and 5.

JavaScript, 152 characters golfed
function t() {
    var fa = (f + '').match(/\d/g)
    var ra = []
    for (var i = 0; i < 5; i++) {
        if (fa.indexOf(i + '') < 0) ra.push(i + 1)
    }
    return ra
}

function f() {
    0; return t()
    1; return t()
    2; return t()
    3; return t()
    4; return t()
}

Golfed:
function t(){for(a=[],i=0;++i<5;)if((f+'').indexOf(i)<0)a.push(i+1);return a}function f(){
return t(0)
return t(1)
return t(2)
return t(3)
return t(4)
}

Self contained (but ugly):
function f() {
    0; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    1; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    2; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    3; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
    4; var ra = []; for (var i = +![]; i < 5; i++) if ((f + '').match(/\d/g).indexOf(i + '') < +![]) ra.push(i); return ra
}

Basically exploits function toString by numbering each line. Note that you actually have to remove the line because of this (commenting it out will not work).
This actually works for any number of lines removed! It will return an array of the lines removed, or an empty array if none have been removed. (I could easily change that to return zero (by replacing return ra with return ra || 0), but I like the empty array solution since it would be more useful in the real world.)
For example, removing the first line returns [1], and removing everything but the first line returns [2,3,4,5]. (Of course, it doesn't work if you remove all lines ;-))

Python
f=lambda:{1,2,3,4,5}-{
1,
2,
3,
4,
5,
} or 0

Returns 0 if no line is removed, otherwise returns the removed lines. You can remove 1 to 5 lines, except the 0th and 6th line ;-).

Ruby
def f
    a = [ 2, 3, 4, 5 ]
    defined?(a) ? a = a.select { |num|    num != 2 } : a = [ 1, 3, 4, 5 ]
    defined?(a) ? a = a.select { |num|    num != 3 } : a = [ 1, 2, 4, 5 ]
    a = a.select { |num|    num != 4 }
    (a = a.select { |num|    num != 5 }) == [] ? a = 0 : a
end

How this works: my idea was: create an array, and on each line, remove a specific value. So, on the first line, I actually have the array [ 1, 2, 3, 4, 5], with the element 1 removed. At the second line, if a is already defined, remove the element 2. Otherwise, create a new array with the element 2 removed. Do the same for line 3. At line 4, you can be sure that there is already an array created, so just remove element 4. At line 5, first remove element 5, and if a is then an empty array, return 0. Otherwise, return a.

Javascript
(function (i){

i += .1;     // line 1
i += .02;    // line 2
i += .003;   // line 3
i += .0004;  // line 4
i += .00005; // line 5

return (Math.round((.12345-i)*100000)/100000+'').match(/([1-5])/g) || 0 })(0)

Call it what you like, but I think it's pretty.
Lets you know which lines were removed (1 or more), or 0 if no lines are removed. All 5 lines can be removed.
EDIT:
Because it was brought to my attention that my code might actually consists of 6 lines, and is in violation of the rules, I adjusted it to the following:
(Math.round((.12345 - (new (function(){

    this.i = isFinite(this.i) ? this.i + .1 : .1 ;
    this.i = isFinite(this.i) ? this.i + .02 : .02;
    this.i = isFinite(this.i) ? this.i + .003 : .003;
    this.i = isFinite(this.i) ? this.i + .0004 : .0004;
    this.i = isFinite(this.i) ? this.i + .00005 : .00005;

})().i || 0) )*100000)/100000+'').match(/([1-5])/g) || 0

The same applies -- it will return an array of removed lines ranging from 1-All or 0 if none.

Not sure if its going to help but I noticed some others doing it, so.. Mine is 149 characters with spacing & 128 without.

Since it's not a code-golf, you don't need to remove the whitespace.

The "return" line is within the function, so the function actually has six lines of code, which violates the rules of the challenge.

@jawns317, I am unsure how a "line" is defined.  Could someone please provide a clear definition?

@logic8 Remove function(){ and } (and any helper functions). Count the number of lines.

Thanks @DoorknobofSnow.  So just for clarity, a line is defined by a carriage return, and not the number of statements/expressions per line?

Yes, that is correct.

JavaScript, self-contained, works for 0, 1, 2 removed lines (607  315 186 chars)
→ live demo ←
Abusing JS variable hoisting and global leaking, like in the other challenge :)
function(r){
r.shift();
r.splice(r.indexOf(2),1)
r.splice(r.indexOf(3),1);a=b=1;if(this.a&&this.b)return r
var a;r.splice(r.indexOf(4),1);b=1;if(this.b)return r
var b;r.pop();return r[0]?r:0
}

to be called with the array [1,2,3,4,5] as parameter.
315 chars
function(r){
var a;
var b;
var c;a=1;b=2;d=4;e=5;for(i in(z="abde".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
var d;a=1;b=2;c=3;e=5;for(i in(z="abce".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
var e;a=1;b=2;c=3;d=4;for(i in(z="abcd".split("")))if(y=this[z[i]])r.push(y);return r.length?r:0
}

to be called with an empty array as parameter.

non-golfed version
(also works for 3 and 4 lines removed):
function(r){
var a;b=c=d=e=1;if(this.b)r.push(2);if(this.c)r.push(3);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var b;a=c=d=e=1;if(this.a)r.push(1);if(this.c)r.push(3);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var c;a=b=d=e=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.d)r.push(4);if(this.e)r.push(5);return r.length?r:0;
var d;a=b=c=e=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.c)r.push(3);if(this.e)r.push(5);return r.length?r:0;
var e;a=b=c=d=1;if(this.a)r.push(1);if(this.b)r.push(2);if(this.c)r.push(3);if(this.d)r.push(4);return r.length?r:0;
}

to be called with an empty array as parameter.

JavaScript:
var f = function(){
    1
    2
    a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;3
    a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;4
    a=[];for(i=0;i++<6;){if((f+'').indexOf(i)<0){a.push(i)}}return a.length?a:0;5
}

fiddle

Python
def function(a = [1,2,3,4,5]):
    delete(a, len(a)-5)#1
    delete(a, len(a)-4)#2
    delete(a, len(a)-3);print a if len(a)==2 else '',#3
    delete(a, len(a)-2);print a if len(a)==2 else '',#4
    delete(a, len(a)-1);print a if len(a)==2 else '',#5

def delete(a, i):
    del a[i]
    return a

It works for all lines - but only if two are deleted. If only one line is deleted then it will print the deleted line and line 5. If too many lines are deleted it won't print anything.
This uses a helper function because the del keyword can't be used in a line with a ;(as far as I know)
Basically, each line deletes itself in the array that is declared in the constructor, then if enough lines have been deleted the array is printed.
This function misses the spec in two ways:

it doesn't print 0 if it is run as-is(it assumes the last two lines have been commented and so prints 4, 5
It assumes that print and return are interchangeable

Will doing print '' not generate an extra newline character though?

Common Lisp
(defun which-lines-are-removed (&aux (x (list 1 2 3 4 5)))
  (setq x (remove-if #'(lambda (x) (eql x 1)) x))
  (setq x (remove-if #'(lambda (x) (eql x 2)) x))
  (setq x (remove-if #'(lambda (x) (eql x 3)) x))
  (setq x (remove-if #'(lambda (x) (eql x 4)) x))
  (setq x (remove-if #'(lambda (x) (eql x 5)) x))
)

It works for removal of 1-4 lines. If you remove all lines it will return the same as if you remove none.
NB: Having ending parenthesis on it's own line is considered bad style, but since other languages has end and } I assume it is allowed.

Déjà Vu
Works for removing any number of lines (as long as you leave at least one line)
local line n:
    try:
        dup
    catch stack-empty:
        dup set{ 1 2 3 4 5 }
    delete-from swap n

func which-gone:
    line 1
    line 2
    line 3
    line 4
    line 5

JavaScript (136/166 chars)
A smaller version with some values declared at the beginning:
function(){b=[1,2,3,4,5],i=0
    b.splice(0,1);i++
    b.splice(1-i,1);i++
    b.splice(2-i,1);i++
    b.splice(3-i,1);i++
    b.splice(4-i,1);i++
return b}

A self-contained version (you don't need to pass anything - the b argument is there so I can check if b is defined with ||)
function(b){
    b=[2,3,4,5],i=1
    b=b||[1,2,3,4,5],i=i||0,b.splice(1-i,1);i++
    b=b||[1,2,3,4,5],i=i||0,b.splice(2-i,1);i++
    b.splice(3-i,1);i++
    b.splice(4-i,1);i++
return b}

Yes, both have return statements, but that is only fair if I am competing with languages with implicit return.

True, it's easier in those languages, but it's not impossible in JS.  I don't consider either of these to have met the constraints of the challenge, since your 136-char version has seven lines of code within the function, and your 166-char version has six.  The fact that you have code on the same line as the opening or closing brackets doesn't mean that code isn't part of the function.

What about the answers that use helpers?

Helper functions are explicitly permitted.  But the function from which lines are removed should contain five lines of code.

C++
void function(int & i)
{
        i=i|1;
        i=i|2;
        i=(i|4);
        i=(i|8);
        i=(i|16);
}

int[] func2(int i)
{
    int arr[]={0,0};
    int k=0,l=1;
    for(int j=1;j<=16;j*=2,l++)
    {
        if((i&j)==0)
        {
             arr[k++]=l;
        }
    }
    return arr;
}

How to use: call the function with i and use func2 for understanding that what function is telling.
If you change the line int arr[]={0,0} to int arr[]={0,0,0,0,0} it will also work for all five lines, it is also handline one line remove test case automatically, what i am doing is simply using a bits of a variable as a flag for each line....

Doesn't function have six lines, not five?

return is not part of that, u can see other answers also.... it's language dependency

See this comment from the author of the challenge on one of the other entries: "True, it's easier in those languages, but it's not impossible in JS. I don't consider either of these to have met the constraints of the challenge, since your 136-char version has seven lines of code within the function, and your 166-char version has six. The fact that you have code on the same line as the opening or closing brackets doesn't mean that code isn't part of the function. – jawns317"

check it now and tell me ur responce

C doesn't work like that. It gives a compiler error. Probably you're thinking of C++.

my mistake, updated,

R
A simple version (not foolproof as you will get an error if you remove line 5):
doit <- function() setdiff(1:5, c(
       1,
       2,
       3,
       4,
       5
    ))

And a foolproof version:
doit<-function() setdiff(1:5, scan(text="
1
2
3
4
5
"))

It works with any number of lines removed (except if you remove all the lines), and can easily be extended to more than 5 lines. Running it "as is" will return integer(0) which is conceptually similar to returning just 0. Returning an actual 0 would make it uglier and longer but would not be complicated.
Finally, a version using magic:
Helper function:
dysfunction <- function(E){
    FUN <- function(){}
    e <- substitute(E)
    e[[1]] <- as.name("list")
    nb <- quote(setdiff(as.list(1:5), x))
    nb[[3]] <- e
    body(FUN) <- nb
    FUN
    }

The actual function:
df <- dysfunction({
1
2
3
4
5
})

R
I have another version in R which I think is better (but uses a helper function):
trick <- function(sym, value) {
  assign(sym, value, envir=parent.frame())
  values <- unlist(as.list(parent.frame()))
  if(length(values)==5) 0 else which(!1:5 %in% values)
}

reportRemovedLines <- function(){
  trick("a", 1)
  trick("b", 2)
  trick("c", 3)
  trick("d", 4)
  trick("e", 5)
}

Or one can avoid using the helper function by defining it as a default argument (works identically but is less readable -- however, it does not use a "separately defined" helper function):
funnyVersion <- function(trick = function(sym, value) {
  assign(sym, value, envir=parent.frame())
  values <- unlist(as.list(parent.frame()))
  if(length(values)==5) 0 else which(!1:5 %in% values)
}){
  trick("a", 1)
  trick("b", 2)
  trick("c", 3)
  trick("d", 4)
  trick("e", 5)
}

Both reportRemovedLines() and funnyVersion() work with any number of lines removed - except if you remove all lines (in that case, they will return NULL). They actually return the line numbers, not just print them - as in R, the value of the last expression evaluated within a function will automatically be returned.
How does it work? The trick is in the trick function which takes all objects from its "parent environment" (i.e., environment of the function that calls it), puts their values together in a vector, and returns, which values from 1 to 5 are not represented.

source: Stack Exchange

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

sort: votes


text:
Let's simulate a random snowflake
I saw this question on https://mathematica.stackexchange.com/ and I think it's pretty cool. Let's make the snowflake with other programming languages.
This is a quote from the original question:

'Tis the season... And it's about time I posed my first question on Mathematica Stack Exchange. So, here's an holiday quest for you Graphics (and P-Chem?) gurus.
What is your best code for generating a (random) snowflake? By random I mean with different shapes that will mimic the diversity exhibited by real snowflakes. Here's a link to have an idea: http://www.its.caltech.edu/~atomic/snowcrystals/ , more specifically here are the different types of snowflakes: http://www.its.caltech.edu/~atomic/snowcrystals/class/class.htm .
  Here we are trying to generate a single snowflake (possibly with different parameters to tune its shape), the more realistic, the better. Three dimensional renderings, for adding translucency and colors are also welcome. Unleash your fantasy, go beyond the usual fractals!

Rules:

Generate a random single snowflake.
The flake should be six-fold radial symmetry.
It doesn't need to be realistic. (But prefer)
Single character answers, like *, ⚹, ❅, ❄, ❆ are not allowed.
Most upvotes wins!

Better disallow single character outputs like '*⚹❅❄❆'[Math.floor(Math.random()*5)].

@nitro2k01: you realize that he referenced that exact mathematica.SE site in the very first sentence of the posting, right?

Oops, sorry. I honestly skipped right to the rules.

Bash and ImageMagick
#!/bin/bash

third=()
x=90
y=90
while (( x>10 )); do
  (( dx=RANDOM%10 ))
  while :; do (( dy=RANDOM%21-10 )); (( y-dy<95 )) && (( y-dy>(x-dx)/2 )) && break; done
  third+=(
    -draw "line $x,$y $(( x-dx )),$(( y-dy ))"
    -draw "line $x,$(( 200-y )) $(( x-dx )),$(( 200-y+dy ))"
    -draw "line $(( 200-x )),$y $(( 200-x+dx )),$(( y-dy ))"
    -draw "line $(( 200-x )),$(( 200-y )) $(( 200-x+dx )),$(( 200-y+dy ))"
  )
  (( x-=dx ))
  (( y-=dy ))
done

third+=(
  -draw "line 90,90 90,110"
  -draw "line $x,$y 15,100"
  -draw "line $x,$(( 200-y )) 15,100"
  -draw "line 110,90 110,110"
  -draw "line $(( 200-x )),$y 185,100"
  -draw "line $(( 200-x )),$(( 200-y )) 185,100"
  -draw 'color 20,100 filltoborder'
  -draw 'color 180,100 filltoborder'
)

convert \
  -size '200x200' \
  xc:skyblue \
  -background skyblue \
  -stroke 'white' \
  -strokewidth 1 \
  -fill 'white' \
  -bordercolor 'white' \
  -fuzz 10% \
  "${third[@]}" \
  -rotate 120 \
  -crop '200x200' \
  "${third[@]}" \
  -rotate 120 \
  -crop '200x200' \
  "${third[@]}" \
  -draw 'ellipse 100,100 15,15 0,360' \
  x:

Sample run:
bash-4.1$ for i in {1..30}; do ./showflake.sh "showflake-$i.png"; done

bash-4.1$ montage showflake-*.png x:

Javascript
Fiddle located here
More fancy Fiddle located here
It's not golfed, not by a long shot. Also required are the Perlin Noise function and seeded Random (both included in Fiddle, seeded random needed for Perlin). Fiddle also displays the current seed for keeping track of favorites ;)
function DoFlake(canvas){
    var width = canvas.width;
    var height = canvas.height;

    var ctx = canvas.getContext('2d');
    var thing = document.createElement('canvas'); thing.width = 128; thing.height = 32;
    var thingctx = thing.getContext('2d');
    var noise = new ImprovedPerlin((new Date()).getTime());

    var wDiv = 1/64;
    var y = 7/32;
    var z = 2/11;

    for(var x = 0; x < 128; x++){
        var h = 32 - (x * 32 / 128);
        h += 16 * noise.Noise(4 * x * wDiv, y, z);
        h += 8 * noise.Noise(8 * x * wDiv, y, z);
        h += 4 * noise.Noise(16 * x * wDiv, y, z);
        h += 2 * noise.Noise(32 * x * wDiv, y, z);
        h += 1 * noise.Noise(64 * x * wDiv, y, z);

        thingctx.fillRect(x, 0, 1, h);
    }

    ctx.translate(128,128);
    var angle = Math.PI / 3;
    for(var i = 0; i < 6; i++){
        ctx.rotate(angle);
        ctx.drawImage(thing, 0, 0);
        ctx.scale(1, -1)
        ctx.drawImage(thing, 0, 0);
        ctx.scale(1, -1);
    }
}

ZXSpectrum Basic, 21
Well, I Can't do the 6 fold symmetry, but I can get all sorts of randomness
using the ZX Spectrum: Emulator Here
Remember that keywords are a single character in the ZX Spectrum
OVER 1
PLOT 40,40
DRAW 40,40,RND*5000

To enter these commands on the emulator:
TAB ,1 ENTER
q 40,40 ENTER
w 40,40,TAB tCTRL+B5000ENTER
(Don't you just love the spectrum keyboard)

This does not work. It either outputs "B Integer out of range, 0:1" or renders some strange donut shape.

the bad thing about spectrum code is that plots sometimes exceed the minimal amount of screen space. alter the 3rd number in the draw to get different patterns and shapes

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


text:
Find all Perrin pseudoprimes less than 100 million
Simply put, the Perrin sequence has the following recurrence relation:

P(n) = P(n-2) + P(n-3);
P(0) = 3; P(1) = 0; P(2) = 2;

But wait!! There's more!!
The Perrin sequence has a very bizarre property:

If N is prime, then P(N) mod N = 0.

Furthermore, there are very few composite numbers which have this property.  This can serve as a simple primality test which gives very few false positives.
There are 5761462 numbers under 100 million which satisfy this congruence. Out of those, 5761455 (99.9999%) are prime numbers.
Your mission is to compute those 7 numbers which pass the test but which are not prime.  To be specific, your program must output these numbers in a reasonable format:
271441, 904631, 16532714, 24658561, 27422714, 27664033, 46672291

You can find more perrin pseudo primes (all of them up to 10^16) with factorization here. For this challenge only the first 7 are important, since they are the only one smaller than 100 million.
(Your program must compute these numbers without having them pre-made, or accessing the internet, or similar stuff.)
Also, your program should not produce integer overflows.  This may at first seem difficult because the 100 millionth Perrin number is really, really big.  Algorithms do exist, however, which would not cause overflows.
This is code golf, shorter solutions are better.

What is P(2)...?

@DoorknobofSnow Simple mistake.

Is having p(0),p(1), & p(2) stored as a single global array okay?

@KyleKanos Sounds fine.

If you say shorter solutions are better - do you assume that the program has to run in reasonable time?

@Howard The time shouldn't be astronomical, but any program will take a long time.

Do you think this would have made a better [tag:fastest-code] competition?

@PhiNotPi I'm tempted to answer yes - although I am not a big fan of fastest-code.

Do you want us to consider up to the 100 millionth Perrin number, or numbers under 100 million?

The link you include saying "all of them up to 10^16) does not include all of them.  It is a partial list.  6335800411, 7045248121, 7825642579, ... and many more are missing.

Ruby, 183
require'Prime'
f=->a{a=a.flat_map{|n|String===n ? n : n<3?%w[3 0 2][n]:[n-2,n-3]} until a.all?{|x|String===x}
a.map(&:to_i).inject :+}
n=1
p n if f[[n+=1]]%n==0&&!n.prime? while n<1e8

Technically works but runs in an unreasonable amount of time. Try setting the lower bound to 271435 and upper bound to 271450.

GolfScript, 53 50 characters
10 8?,{3 0 2{@2$+3$%}4$2-*])!*},{.,2>{1$\%!},*},n*

Do not try to run this version - it'll take very long time to complete (if ever). The code creates a list of all candidates and then consists of two filter steps, first to select all assumed primes and then filter all non-primes from the remaining list. In order to see the code work you can try the following snippet:
30,{271430+}%
.p
{3 0 2{@2$+3$%}4$2-*])!*},
.p
{.,2>{1$\%!},*},
p

Can be shortened a bit if both tests are packed into one but then it'll be even slower.

Unless I've missed something, the +,( could just be ,*.

And similarly, I think -1=! could be )!*.

@PeterTaylor Of course you're right. I was a little bit too anxious to leave anything on the stack and forgot that you can use the array as boolean also.

PARI: 148
The oeis webpage on the Perrin number contains a PARI code written by Joerg Arndt that can easily be modified (a number & spacing) to fit the criteria
N=10^8;
default(primelimit, N);
M=[0,1,0;0,0,1;1,1,0];
a(n)=lift(trace(Mod(M,n)^n));
{for(n=1,N,if(isprime(n),next());if(a(n)==0,print1(n,",");););}

It takes quite a while, but it definitely works. I will work on translating this to Fortran for speed computation, but it definitely will not be small (especially if I put the prime test in the code & not as a use <module> declaration).

With newer Pari/GP this can be reduced.  Get rid of the first two lines, change the last to forcomposite(n=1,10^8,a(n)||print1(n","))

Python (127)
a=i=3
b,c=0,2
while i<10**8:
    c,b,a=a+b,c,b
    j=2
    if c%i==0:
        while j*j<=i:
            if i%j==0:print i;break
            j+=1
    i+=1

Unnecessary usage of memory avoided but the solution tends to be slow due to big integer operations. Primality testing is done with a slow algo.

You can use 1e8 instead of 10**8, I think.

AutoHotkey 132
o:={-2:1,-1:-1,0:3}
loop % 10**8
{
p:=0
if !Mod(o[(l:=A_index)-2]+o[l-3],l)
loop % l
if !Mod(l,A_index)
p++
if p>2
s.=l ","
}
msgbox % s

Not possible as Integer limit is surpassed.

According to the AutoHotkey documentation, integers are signed 64-bit. The largest number required for a direct approach like this is about 40000000 bits. Are you sure this doesn't overflow and give nonsense results?

@PeterTaylor According to doc "AutoHotkey supports 64-bit signed integers, which range from -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF)." 10**8 is less than 9223372036854775807 and that is the reason I think it's okay.

108 is fine, but you're computing 1.3...(10**8), which is much much larger.

@PeterTaylor I didn't thought P(n) for say n=100 can get that big. Yes, you are right. Ahk won't compute that. I will edit that.

Husk, 22 bytes
↑7fo¬ṗtW¬z%Ntƒ(+d302Ẋ+

(Don't bother to) Try it online!: as many other answers this is extremely slow, so you won't see anything in the 60s TIO allows. Try this online instead! for a modified version that finds the first Perrin pseudoprime after 271440 (yes, it's 271441).
Explanation
↑7fo¬ṗtW¬z%Ntƒ(+d302Ẋ+
             ƒ(+d302Ẋ+    Recursive definition of the Perrin sequence:
                d302       Start with the digits of 302
               +           and append after them
                    Ẋ+     the pairwise sums
             ƒ             of the sequence itself
            t             Drop the first value (we like counting from 1 in Husk)
         z%N              Compute each value modulo its index
       W¬                 Find the indices of 0s
      t                   Drop the fist one (0 mod 1 is 0, but for some reason
                           1 is not one of the required outputs)
  f                       Keep only those values
   o¬                     that are not
     ṗ                    primes
↑7                        Take the first 7 results

Haskell (169)
p=3:0:2:zipWith(+)p(tail p)
s(x:y)=x:s[a|a<-y,a`rem`x/=0]
s[]=[]
w=s$2:[3,5..10^8]
k(y,x)z|x`rem`y==0&&(y`notElem`w)=y:z|1<2=z
main=print.foldr k[]$zip[2..10^8].drop 2$p

p is an infite list producing the Perrin numbers, s is a simple sieve function, w contains all primes up to 10^8. k checks whether the pair (y,x) (where y is the Perrin number's index and x is the number itself) fulfils the condition and adds them to the list z. main folds k along the zip of the list [2..10^8] and the Perrin numbers (except for N=0 and N=1).
Don't run this program. It will generate the prime numbers first, which takes very, very, very long due to the inefficient sieve. Faster versions would use a wheel sieve and a binary search instead of the current linear search. Also, starting at around 10^5, garbage collection will eat up almost all productivity.

Perl 68
use ntheory":all";forcomposites{say if is_perrin_pseudoprime($_)}1e8

Takes 66 seconds on my macbook with the latest version, 6 minutes with previous one (that had no prefilters -- basically a sped up version of Arndt's Pari code).
Of course this is cheesy by using a module that does all the work in C. 88 lines of C with prefilters for faster operation, 28 lines if removing the filters and an optimization to avoid mulmod for small inputs.

Jelly, 30 bytes
Ø.’ịṖS;@
Ø.Ḥ3;Ç⁸¡ị@‘
Ẓ=Ç%$Ɗ8#Ḋ

Try it online!
Wildly inefficient, times out on TIO before printing anything.
How it works
Ø.’ịṖS;@    - Helper link. Takes a list l on the left
            - l is the list of previous Perrin numbers and the link appends the next Perrin number
Ø.’         - Yield [-1, 0]
    Ṗ       - Remove the last element of l
   ị        - Index into the cropped version of l
            - This gives the second and third elements from the end of l
     S      - Take the sum of these two
      ;@    - Append to l

Ø.Ḥ3;Ç⁸¡ị@‘ - Helper link. Takes an integer k on the left
            - This link takes an integer k and returns the kth Perrin number
Ø.          - Yield [0, 1]
  Ḥ         - Double to [0, 2]
   3;       - Prepend 3
      ⁸¡    - Do the following k times, operating on the list [3, 0 2]:
     Ç      -   Call the above helper link
          ‘ - Yield k+1
        ị@  - Take the 1-indexed (k+1)th index of this list

Ẓ=Ç%$Ɗ8#Ḋ   - Main link. Takes no arguments
     Ɗ8#    - Do the following over n = 0, 1, 2, ... until 8 values return True:
Ẓ           -   Is n prime?
    $       -   Group the previous two links and run over n:
  Ç         -     Get the nth Perrin number
   %        -     Modulo it by n
 =          -   Are the two values equal?
            -   The two values will either be equal if:
            -     n is prime and P(n) mod n = 1 or
            -     n is composite and P(n) mod n = 0 or
            -     n = 1
            -   The first is never true, therefore this only returns True if n is composite and P(n) mod n = 0 or n = 1
            - This returns [1, 271441, 904631, 16532714, 24658561, 27422714, 27664033, 46672291]
        Ḋ   - Remove 1 from this list

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


text:
Just Another Polyglot Hacker!
Make a program which prints just another #{LANG} hacker where #{LANG} is the name of the language with which the program is being run.
For example, if I run your program with Bash, I'd expect just another Bash hacker as the output, but when running the same program through C++, I'd expect the output to be just another C++ hacker.
Your program must run in and produce correct output in at least two different languages.

This is in no way a duplicate of the other suggested question, Write a polyglot that prints the language's name; that question asks for a rather short (and in my opinion) uninteresting output, increasing the easiness of writing and number of languages in an answer, and then it assesses them (these polyglots) based on the source's length!
A correct response to this question, however, would produce longer outputs, and thus would have actually been fairly challenging and fun to write and it would be more difficult to add languages to your polyglot. I then assess the polyglots in a natural way; by the number of languages they support!
I think that this will lead to very different answers being submitted on either question, but also different uses for these answers; the programs which will be submitted here are the type of programs which would be flaunted around the internet for their ingenuity and creativity, "look! Here's a guy who can pull off a swaggy polyglot in 4 different languages! They're cool!"
When I asked this question, I thought I'd put a twist on the popular and well known Just Another Perl Hacker competition, but add some creativity and an extra "Wow!" factor; JAPH programs are often sported as signatures in forums etc., and I believe entries here will inspire similar use, unlike entries for the other question.
Also, because this isn't a form of code-golf like the other question, but I'm actually assessing answers on the number of languages they support, I believe we can expect some rather incredible entries, making use of language features and loopholes we never knew existed!

Rules:

Two different versions of the same language only count separately if:

You print out the version as well as the language name, for each version.
You detect which version is running thraough a less trivial method than running a ver() function or similar built-in of your language.
The two have different major version numbers.

For example, if you say your program runs in both Python 3.4.1 and 2.7.8, here are the necessary outputs:
Python 3.4.1
just another Python 3.4.1 hacker

Python 2.7.8
just another Python 2.7.8 hacker

If your program doesn't produce the above outputs for each version, then you cannot list the two separate versions as different languages under which your code runs.

You may not have any errors on the maximum level of warning in any of the languages.
Program must terminate.

Winner:

Whoever's (valid) answer supports the most languages. In the case of a tie, the shorter answer (by program byte count) wins.

Why the 'maximum level of warning'? That seems rather harsh.

I think this is sufficiently separate from those.

Please don't write your question starting with what's it's almost like, then what to change to make it the question (or, in your case, initial idea, then edit), it's really a pain to read. 2) It's still the same challenge as the question marked as duplicate.

Then there is this: http://codegolf.stackexchange.com/questions/4481/what-code-compiles-in-the-most-number-of-languages?s=20|0.1193

C, C++, Perl, Bash – 230
#include <stdio.h>
#define c const char*\
s="just another %s hacker\n"
//bin/test;printf "$s" Bash;exit
int main(){c;printf(s,sizeof'a'-1?"C":"C++");}
/*==;seek DATA,0,0;@a=readline DATA;eval'$'.$a[2];printf $s,"Perl";
__DATA__*/

This was fun! :-)
230 chars including a newline at end of file. To run, save as both poly.c and poly.cpp and do:
$ gcc -Wall -Wextra -pedantic poly.c && ./a.out
just another C hacker
$ g++ -Wall -Wextra -pedantic poly.cpp && ./a.out
just another C++ hacker
$ perl poly.c
just another Perl hacker
$ bash poly.c
just another Bash hacker

This generates warnings when run with perl -w, and doesn't compile at all with -Mstrict.

ANSI C/C++
#ifdef __cplusplus
#    include <iostream>
#    define LANG "C++"
#    define PRINT(text) { std::cout << text; }
#else
#    include <stdio.h>
#    define LANG "C"
#    define PRINT(text) { printf("%s", text); }
#endif

int main(void) {
    PRINT("just another ");
    PRINT(LANG);
    PRINT(" hacker\n");

    return 0;
}

Compiling and executing:
$ gcc -ansi -Wall -Wextra -pedantic -o prog-c prog.c
$ ./prog-c
just another C hacker
$ g++ -ansi -Wall -Wextra -pedantic -o prog-cpp prog.c
$ ./prog-cpp
just another C++ hacker

BASH + BrainF*ck + PHP, 269 characters
#><?="Just another PHP hacker\n";die();?><
echo Just another BASH hacker #++++++++++[>+++++++>++++++++++++>++++++++++>+++++++++++>+++>+<<<<<<-]>++++.>---.--.+.>>>++.<<---.>.+.<<.>+++++++.---.>+++.>.<<<<<++++[>--<-]>.++++.>>>>.<<+++.-------.++.>-------.<++.>+++++++.>>.

Running the program:
$ php langs.sh
#>Just another PHP hacker
$ ./2langs.sh
Just another BASH hacker
$ bf 2langs.sh
Just another BF hacker

A bit of stretching the rules with that PHP one, but it seems to work. I can fix it if it doesn't count.

One could possibly argue this is invalid because the language name is Brainfuck and not BF.

@nyuszika7h It's commonly abbreviated that way. https://www.google.com/search?q=BF+programming

True, I don't want to be the one deciding this, but it wasn't specified so...

Why not just edit the brainfuck program? Then it will be valid and it won't take very much effort to append a longer program in that comment.

JavaScript, HTML, BF
<!--
    // > to fix previous comment delim
    /*
        ++++++++++[>+++++++>++++++++++++
        >++++++++++>+++++++++++>+++>+<<<<<<-]>++++
        .>---.--.+.>>>++.<<---.>.+.<<.>+++++++.---
        .>+++.>.<<<<<++++[>--<-]>.++++.>>>>.<<+++.
        -------.++.>-------.<++.>+++++++.>>.
    */
    alert('Just another JavaScript hacker')
// --> Just another HTML hacker

Relies on the fact that most JS implementations ignore <!--.
BF code shamelessly stolen from @Tyzoid, all credit to him :-)
Make sure your BF interpreter supports pointer wrapping.

Careful! The first < will make your BrainF*ck program crash!

Yea, invalid...

@Tyzoid Oops, didn't notice :-P fixed

@DoorknobofSnow It's still not fixed. The problem is that BF starts on element zero on the tape, and does not allow a < to move you to element -1. It crashes before it hits your fix. It's the same problem I'm having with my PHP solution.

@Tyzoid I mentioned that - "Make sure your BF interpreter supports pointer wrapping."

Lua 5.3/5.2/5.1/5.0/4.0/3.2
You said as long as I don't use _VERSION it is fine
print("Just another Lua"..(string and(loadstring"return 0//0"and"5.3"or(_ENV and"5.2"or(string.gmatch and"5.1"or"5.0")))or tremove(next({[{"4.0","3.2"}]=1},nil))).." hacker")

I don't know about Lua, but they must also have different version numbers and major syntax differences.

Well the question did not state the majorness of the syntactical differences. After all, C/C++ entries are valid


text:
Rosetta Stone Challenge: Gene Mapping
The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!
The Challenge
Your challenge is to implement a program that will map some genes using cross-over frequencies, in as many programming languages as possible. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase.
What is "gene mapping?"
Gene mapping is the process of locating the relative position of genes on chromosomes. This is done by measuring the crossing-over frequency of pairs of genes, equal to the percent of offspring in which that the pair is not inherited together.  Distance is measured in map units with one map unit equal to one percent of crossing over.  For example, if genes C & D have a crossing-over frequency of 11%, then gene C is a distance of 11 map units away from gene D.
Gene mapping is performed with multiple pairs of genes to determine their relative order.  For example, the data (A,B,12) (D,B,7) (A,D,5) (D,H,2) (H,B,9) produces the following map:
A..H.D......B

You may have noticed that B......D.H..A is also a valid map.  This is true, because it is not possible to distinguish between mirror opposites.  Your program can pick which one to output.  Although the input may not include every possible pair, there will always be enough information to reconstruct the entire map (so there will never be more than 2 valid outputs).  In addition, the numbers will always work out (unlike actual biology), meaning that you won't have stuff like (A,B,3) (B,C,4) (A,C,13).
Input
Input will begin with a number n followed by a list of genes (uppercase letters).  There will then be n triplets of data.  Each set will consist of a pair of genes and their crossing over frequency (distance).
3,P,H,I
P,H,3
H,I,1
P,I,4

7,A,B,G,Q,U
B,Q,4
A,B,10
G,U,13
Q,U,10
A,G,9
G,Q,3
A,Q,6

Input is not rigidly defined, because different languages may have restrictions on what is feasible.  For example, you may change the delimiters to something other than commas and newlines.  Input formatting is largely up to you.
Output
Output will be a rendition of the gene map.  It will consist of the genes (capital letters) spaced out by periods such that the distances are accurately portrayed.  Here are the outputs for the above examples.
P..HI  *or*  IH..P

BG..Q.....A...U  *or*  U...A.....Q..GB

This also isn't a completely rigid requirement. For example you could use something other than periods, like commas or spaces.
The Objective Winning Criterion
As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language.
Rules, Restrictions, and Notes
Your program can be written in any language that existed prior to December 20th, 2013. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them.

Current Leaderboard
This section will be periodically updated to show the number of languages and who is leading in each.

AutoHotkey (632) - Avi
dj (579) - rubik

Current User Rankings

Avi (1): AutoHotkey (632)
rubik (1): dj (579)

Should we include code to read the input? Or should we just assume input is passed as first argument of the function?

@Jefffrey I suppose either one is fine.

.. the leaderboard ? :-)

What are the input bounds? Not so much n, but primarily the bounds for the crossing over frequency (distance). Can we assume it will always be, say, less than 1000?

@PhiNotPi: can you provide a couple more test cases? I've almost finished mine and I'd like to test it more.

@PhiNotPi I added my solution, the leaderboard should be edited.

Sorry for the delay, I've been extremely busy lately.  I've updated it.

AutoHotkey (632)
f(i){
o:={},f:={},n:=0
loop,parse,i,`n
{
a:=A_LoopField
if A_index!=1
{
@:=Substr(a,1,1),#:=Substr(a,3,1),n+=($:=Substr(a,5))
if !IsObject(o[@])
o[@]:={}
if !IsObject(o[#])
o[#]:={}
o[@][#]:=o[#][@]:=$
}
}
f[n+1]:=@,f[@]:=n+1,a:=""
while !a
{
a:=0
for k,v in o
{
if !f[k]
{
c1:=c2:=s:=0
for k1,v1 in v
{
if f[k1]
if s
{
if (r1==f[k1]-v1)or(r1==f[k1]+v1)
c1:=r1
else r1:=c1:=""
if (r2==f[k1]-v1)or(r2==f[k1]+v1)
c2:=r2
else r2:=c2:=""
}
else
c1:=r1:=f[k1]+v1,c2:=r2:=f[k1]-v1,s:=1
}
if c1
f[c1]:=k,f[k]:=c1,a:=1
else if c2
f[c2]:=k,f[k]:=c2,a:=1
}
}
}
loop % 2*n+1
{
v:=f[A_index]
if v
z:=1
r.=z?(!v?".":v):v
}
return Rtrim(r,".")
}

The code can be more shortened by renaming all vars to 1 character .. It should then be about 610 characters.
Test Cases
v := "
(7,A,B,G,Q,U
B,Q,4
A,B,10
G,U,13
Q,U,10
A,G,9
G,Q,3
A,Q,6
)"

msgbox % f(v)
msgbox % f("3,P,H,I`nP,H,3`nH,I,1`nP,I,4")

Python 311
import sys,random
d=sys.stdin.readlines()
u=[]
r=g=0
m={}
l=d[0].split()[1:]
for a in l:m[a]=g;g+=1
for v in d[1:]:i=v.split();u+=[i];r+=int(i[2])
j=len(l)
y=range(j)
while any(abs(y[m[t]]-y[m[w]])!=int(p) for t,w,p in u):y=random.sample(range(r),j)
o=["."]*r
for a in m:o[y[m[a]]]=a
print "".join(o).strip(".")

My first code-golf :D
(Im not sure with the counting, i just postet it online in a character count)
The idea of the algorithm is pretty bad, but it is short.
Try randomly all positions for the Symbols until they satisfy all constraints.
The Input is with whitespace for example
3 P H I
P H 3
H I 1
P I 4

Hit after that CTRL+D in the console to end the reading.
Here is the original code which still uses ',' as delimiter.
import sys, random
#data = sys.stdin.readlines()
data = [
"3,P,H,I",
"P,H,3",
"H,I,1",
"P,I,4"
]
container = []
max_range = 0
map = {}
map_counter = 0

line_split = data[0].split(',')[1:]
count = len(line_split) # Number of genes
for symbol in line_split:
    map[symbol] = map_counter
    map_counter += 1

for line in data[1:]:
    line_split = line.split(',')
    container.append(line.split(','))
    max_range += int(line_split[2])

restart = True
while restart == True:
    positions = random.sample(range(max_range), count) # Since this loop will take like forever, but some day it will produce the correct positions
    restart = False
    for symbol1, symbol2, distance in container:
        if abs(positions[map[symbol1]] - positions[map[symbol2]]) != int(distance):
            restart = True
            break

output = ["."] * max_range
for symbol in map:
    output[positions[map[symbol]]] = symbol
print "".join(output).strip(".") # Strip . to make it more pretty

dg - 717 579 bytes
A Python one is incoming.
import '/sys'
w,o=list,tuple
p=g a b m->
 b in g=>a,b=b,a
 i,l,k=g.index a,w$g,w$g
 l!!(i+m),k!!(i-m)=b,b
 g!!(i+m)=='.'=>yield$o$l
 g!!(i-m)=='.'=>yield$o$k
g=t->
 d=sorted key:(i->snd i)$map((a,b,i)->((a,b),int i))$filter fst$map(i->i.split ',')$t.split '\n'
 (a,b),i=d.pop!
 g=w$('.',)*i*4
 g!!i,g!!(i+i)=a,b
 s=set'$o g
 while d=>
  d.sort key:((k,v)->set k&(set$fst$w s))
  n,(a,b),i=set! :+d.pop!
  for r in s=>
   if(a in r and b in r=>i==abs(r.index a-r.index b)=>n.add r)(1=>n.update$p r a b i)
   s = n
 '\n'.join$map(l->(''.join l).strip '.')s
print$g sys.stdin.read!

Examples:
$ echo """P,H,3
H,I,1
P,I,4""" | dg dna.dg
P..HI
$ echo """B,Q,4
A,B,10
G,U,13
Q,U,10
A,G,9
G,Q,3
A,Q,6""" | dg dna.dg
BG..Q.....A...U

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <malloc.h>

struct Gene
{
    char a1 , a2 ;
    int d ;
};
typedef struct Gene gene ;

struct Set
{
    int appr_id ;
    char CMN_char ;
};
typedef struct Set set ;

gene *stack;
int cp_id1 , cp_id2 , N=0 , cid , *used , n ;
char ucmn_char , *cmp1 , *cmp2 , *base , ep[15] ;
set ap_set ;

void randomize(void)
{   int i;
    Set temp;
    for(i=0;i<(n-1);i++)
    {
        temp=stack[i];
        stack[i]=stack[i+1];
        stack[i+1]=temp;
    }

    return;

}
void populate_ep ( char ucmn_char )
{
    int i;
    for ( i=0 ; ep[i] != '\0' ; i ++ );
        ep[ i ] = ucmn_char ;
}

set find_appr ( void )
{
    int i , j ;
    set s ;
    for ( i = 0 ; i < n ; i++ )
    {
        if ( used[ i ] == 1 )
            continue ;
        else
        {
            for ( j = 0 ; ep[ j ] != '\0' ; j++ )
            {
                if ( ep[ j ] == stack[ i ].a1 || ep[ j ] == stack[ i ].a2 )
                {
                    s.appr_id = i ;
                    s.CMN_char = ep[ j ] ;
                    return s ;
                }
            }
        }
    }
}

void destroy ( int id )
{
    used[ id ] = 1 ;
}

int get_center_id ( char a )
{
    int i ;
    for ( i = 0 ; i < N * 2 ; i++ )
        if ( base[ i ] == a )
            return i ;
}

int get_comparer ( void )
{
    int i , j , k ;
    for ( i = 0 ; i < n ; i ++ )
    {
        if ( used[ i ] == 0 )
        for ( j = 0 ; ep[ j ] != '\0' ; j ++ )
            if ( stack[ i ].a1 == ep[ j ])
                for ( k = 0 ; k < 15 ; k ++ )
                    if ( stack[ i ].a2 == ep[ k ] )
                        return i ;
    }
    printf ( "\nWrong set of genes....\n" ) ;
    exit ( 0 ) ;
}

void compare_and_merge ( int cid, int cp_id1, int cp_id2 )
{
    int base_cp_id , i ;
    char temp = ( ucmn_char == stack[ cid ].a1 ) ? stack[ cid ].a2 : stack[ cid ].a1 ;
    for ( i = 0 ; i < N * 2 ; i ++ )
        if ( base[ i ] == temp )
            base_cp_id = i ;
    if ( stack[ cid ].d == ( sqrt ( pow ( ( cp_id1 - base_cp_id ) , 2 ) ) ) )
    {
        base[ cp_id1 ] = cmp1[ cp_id1 ] ;
        return ;
    }
    else
    {
        base[ cp_id2 ] = cmp2[ cp_id2 ] ;
        return ;
    }
}

void show_stack ( void )
{
    int i ;
    printf ( "The gene sets you entered are: \n" ) ;
    printf ( "____________\n" ) ;
    for ( i = 0 ; i < n ; i ++ )
        if ( used[ i ] == 0 )
            printf ( "%c %c %d\n" , stack[i].a1, stack[i].a2, stack[i].d ) ;
    printf ( "____________\n" ) ;
}

int main ( void )
{
    printf ( "Enter number of gene sets: " ) ;
    scanf ( "%d" , &n ) ;
    stack = ( gene* ) calloc ( n , sizeof ( gene ) ) ;
    used = ( int* ) calloc ( n , sizeof ( int ) ) ;
    int i ;
    N = 0 ;
    for ( i = 0 ; i < n ; i ++ )
    {
        char y[ 2 ] ;
        scanf ( "%s" , y ) ;
        stack[ i ].a1 = y[ 0 ] ;
        scanf ( "%s" , y ) ;
        stack[ i ].a2 = y[ 0 ] ;
        scanf ( "%d" , &stack[ i ].d ) ;
        N += stack[ i ].d ;
        used[ i ] = 0 ;
        fflush ( stdin ) ;
    }
    randomize();
    show_stack ( ) ;
    int ff ;
    strcpy ( ep , " " ) ;
    cmp1 = ( char* ) calloc ( N * 2 , sizeof ( char ) ) ;
    cmp2 = ( char* ) calloc ( N * 2 , sizeof ( char ) ) ;
    base = ( char* ) calloc ( N * 2 , sizeof ( char ) ) ;
    for ( i = 0 ; i < N * 2 ; i ++ )
        base[ i ] = cmp1[ i ] = cmp2[ i ] = '=' ;
    base[ N ] = stack[ 0 ].a1 ;
    base[ N + stack[ 0 ].d ] = stack[ 0 ].a2 ;
    destroy ( 0 ) ;
    ep[ 0 ] = stack[ 0 ].a1 ;
    ep[ 1 ] = stack[ 0 ].a2 ;
    for ( ff = 0 ; ff < n / 2  ; ff ++ )
    {
        ap_set = find_appr ( ) ;
        cmp1[ get_center_id ( ap_set.CMN_char ) ] = ap_set.CMN_char ;
        cmp2[ get_center_id ( ap_set.CMN_char ) ] = ap_set.CMN_char ;
        ucmn_char = ( stack[ ap_set.appr_id ].a1 == ap_set.CMN_char ) ? stack[ ap_set.appr_id ].a2 : stack[ ap_set.appr_id ].a1;
        cmp1[ cp_id1 = get_center_id ( ap_set.CMN_char ) + stack[ ap_set.appr_id ].d ] = ucmn_char ;
        cmp2[ cp_id2 = get_center_id ( ap_set.CMN_char ) - stack[ ap_set.appr_id ].d ] = ucmn_char ;
        populate_ep ( ucmn_char ) ;
        destroy ( ap_set.appr_id ) ;
        cid = get_comparer ( ) ;
        compare_and_merge ( cid , cp_id1 , cp_id2 ) ;
        destroy ( cid ) ;
    }
    int start , end ;
    for ( i = 0 ; i < N * 2 ; i ++ )
        if ( base[ i ] != '=' )
        {
            start = i ;
            break ;
        }
    for ( i = N * 2 - 1 ; i >= 0 ; i -- )
        if ( base[ i ] != '=' )
        {
            end = i ;
            break ;
        }
        for ( i = start ; i <= end ; i ++ )
            printf( "%c" , base[ i ] ) ;
    printf( "\n\n" ) ;
}

Welcome to PPCG! This is code golf, so please show some effort to solve the problem in the minimal amount of code. For a start you could remove all unnecessary whitespace and use single-letter variable, struct and function names. Please also include the language and the total byte-count at the top of your answer.


text:
Make a package manager
It's time to make a more advanced program (rather than something simple, like printing some shape). You need a package manager for something, I guess.
First of all, if something wasn't defined, you are allowed to do anything, including destroying the computer (but please, don't, unless this will save your characters). After all, you will be using the package manager 100% correctly, so this won't happen. Who cares about security problems? It just has to be fast, like C programs.
The package manager should use STDIN and STDOUT as storage - that is, the database should be read from STDIN, and result database should be output to STDOUT, in true Unix style. The format of database is anything you want, as long you will be able to read it back.
The package manager shall support four commands. Typing unrecognized command is undefined, and anything can happen.

init - outputs the empty database to be read by other commands. This shouldn't read the database state.
install x y z - installs the programs x y z. If the program already exists, you can do anything
remove x y z - removes the programs x y z. If the program doesn't exist, you can do anything.
list - shows every program (with new line after every program). The list should be in alphabetical order. This mustn't output the database state.

The packages are only allowed to have lowercase ASCII letters (a-z). Anything else is undefined.
There is an example of example program:
$ ./lolmanager init > db
$ ./lolmanager install cat dog < db > db2
$ ./lolmanager remove dog < db2 > db
$ ./lolmanager list < db
cat
$ ./lolmanager install something else < db > db2
$ ./lolmanager list < db2
cat
else
something
$

The shortest code wins.

"shows every program (with new line after every program). The list should be in alphabetical order. This shouldn't output the database state." So in effect, this means that separated by newlines, in alphabetical order, is a forbidden db state format?

alphabetical order in the description and any order in the example seem to be different.

@Howard: You catched me on a small mistake. I couldn't have decided whether list should be ordered or not (by accident). This should be fixed now, it's just a mistake while writing the task.

Similar: Write a program to perform set operations

GolfScript (23 chars)
n%"#{ARGV*'
'}"n/(;^$n*

My database format is the same as the list format.
I interpret the spec to allow assuming that the init command guarantees no input on stdin and no further command-line arguments, and that the list command guarantees no further command-line arguments. Then every command does exactly the same thing: xor the supplied database with the 2nd to nth command-line argument.

GolfScript, 59 characters
[{;;[]`}:it{|`}:ll{-`}:ve{;$n*}:st];~"#{ARGV*' '}"' '%(-2>~

Implemented the first idea which came into my mind. The database format is simply a GolfScript array representation. Install/remove also handle the case when a program is already installed.
Explanation
# Define four functions for later use ([...]; simply removes them from the stack):
[
  {;;[]`}:it         # init -> discard arguments, discard db, create empty db
  {|`}:ll            # install -> add arguments to db (if not already there)
  {-`}:ve            # remove -> remove all arguments from db
  {;$n*}:st          # list -> discard arguments, sort, join with newline
];

~                    # Parse db given on STDIN
"#{ARGV*' '}"' '%    # Parse command line arguments into array
(-2>                 # Take first argument (command) and the last two chars from it
~                    # Execute that command (i.e. "it" for "init", ...)

Golf-Basic 84 for TI-84 Calculators, Character count: 84
:2_R:1_I:0_L:""_Str0i`Nd`Str0l`0i`Ng`Ad`Str0g`0l`Ai`S@N=2:Str0+S_Str0@N=1:""_Str0g`0

Hide the source code. Your teacher might think you're cheating :)
Output
?Init|db
?Install|db
?"CAT, DOG"
?List|db
CAT, DOG
?Remove|db
?"CAT, DOG"
?List|db

?Install|db
?"LOL"
?List|db
LOL

84 84 84 Too much 84

@CatsAreFluffy They work on all in the early TI-8X series, notably TI-83s ;)

Ruby, 102 bytes
c,*a=$*
$/=?\0
puts c=~/it/?'':(i=STDIN.gets.split
case c
when/a/
a|i
when/v/
i-a
when/st/
i.sort
end)

Edit: Inspired by Howard, I replaced init, install, remove and list literals for some more general patterns: /it/, /a/, /v/ and /st/.

Only remove has v, so you can shorten the pattern.

You're right, thanks! Also install is the only one containing a.

Your program doesn't sort the values when you use list (I just tested it).

@GlitchMr I didn't read the rules properly I guess. Fixed (and shortened).

And while shortening, you somehow managed to remove /v/ optimization ;-).

Oops. Fixed, and shortened again.

J (127 108)
Runs as a script (obviously). I could save some characters if I could assume it always receives an end-of-file even for init.
exit echo;,&LF&.>(LF cut stdin^:(-.A e.~<'init')''),`(*/@(~:/~)#[)`((/:{])@[)`[@.('irl'i.{.>2}A)[3}.A=:ARGV


text:
Pascal's Trapezoid
Write a function which for any given input array of numbers and a row number r, returns the r-th vector or array where each subsequent vector or array is constructed from the previous following the rules used in Pascal's Triangle. For example, for an input vector of [3 1 2] and a row number of 1 (indicating the 'next' row), the correct return vector or array is [3 4 3 2].
As an example, a Clojure solution to this problem might be:
(defn pascals-trapezoid-row [r n]
  (last (take (+ n 1) ((fn p [c] (cons c (lazy-seq (p (flatten (conj [(first c)] (map #(apply +' %) (partition 2 1 c)) [(last c)] )))))) r))))

The winning and accepted solution will be the one with the fewest number of characters in the solution code. Legibility is not a requirement. You're on your honor as to whether or not your proposed solution actually works, but remember that while cheaters often win nobody likes them very much, and karma is real (except in Fortran). Solutions must be posted by 07-Jan-2014 at 12:00 noon Eastern Standard Time (-5 timezone) to be considered. Extra credit (i.e. upvotes) will be awarded by me (and perhaps others) for interesting or novel solutions, including but not limited to those done in unusual languages, one-liners, unbelievably ugly solutions, unbelievably beautiful solutions, and anything I happen to like. I will not downvote any answer, although I make no guarantees about what others may do.
GO!

To clarify... in your example, if r=0, would the appropriate result be [3 1 2]? And no negative values of r?

@DarrenStone: in the case of the code I posted, r=1 would result in '[3 4 3 2]' and an arg of 0 would result in [3 1 2]. I'm not going to be all that picky about "is r an index or an offset?", and I'll always supply a zero-or-positive row number - but make it work, argue that you're consistent with whatever, and I'm going to go with it. I'd rather have a good time than argue over "rules"...

Sheesh! Three answers, and I like 'em all enough to upvote 'em. I'm too easy...

And our winner is @Timtech, whose solution has pushed back the frontiers of computing+!  In addition to having his answer accepted, he will also be receiving an autographed set of Ginsu steak knives++, a lifetime supply of McDonalds gift certificates+++, and a lifetime subscription to Code Golf Digest++++! Congratulations!!  (+ = not really, but it was a cool answer; ++ = blatant hyperbole; +++ = this would be very unhealthy, so you're lucky this is not true; ++++ = no such publication exists, and even if it did this would also be, yes, a lie)

Golf-Basic 84 - 10 characters
Executed from a TI-84 calculator.
i`N,Rd`N11

Sample run
?(3;1;2)            <== Array of numbers
?1                  <== Row number
            3432

The phrase "executed from a calculator" in the context of code-golf makes me smile.

@DarrenStone When code golf = math, it's time to pull out the calculator.

WINNER! Congratulations!

@BobJarvis Thanks! I'm happy :) First code-golf competition I've ever won!

What does this compile to?

APL (16 / 14)
{{2+/0,⍵,0}⍣⍺⍨⍵}

Takes the vector as the right argument, and the row number as the left argument, like so:
      1{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 4 3 2
      2{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 7 7 5 2
      3{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 10 14 12 7 2

If I get to take input from the keyboard, instead of as a function, I can shave off two characters:
{2+/0,⍵,0}⍣⎕⍨⎕

Takes the vector on the first line and the row number on the second.

Ah, brings back fond memories of my days in college, back at dear Miskatonic U... Ia! Ia! Cthulhu fhtagn!!!

GolfScript, 14 characters
{[0\{.@+\}/]}*

Takes input (vector plus number of rows) on top of stack and replaces that by the result. Example (also online):
[3 1 2] 3    {[0\{.@+\}/]}*      # -> [3 10 14 12 7 2]

http://codegolf.stackexchange.com/a/3822/194

@PeterTaylor Ups, didn't realize that. Reinvented the method on my own ;-)

@PeterTaylor Voted to close as duplicate - although different it is quite similar.

R, 45
function(x,r){for(i in 1:r)x=c(x,0)+c(0,x);x}

Example usage:
fun <- function(x,r){for(i in 1:r)x=c(x,0)+c(0,x);x}

fun(c(3, 1, 2), 1)
[1] 3 4 3 2

fun(c(3, 1, 2), 2)
[1] 3 7 7 5 2

fun(c(3, 1, 2), 5)
[1]  3 16 37 50 45 28 11  2

Ruby, 51
a=eval$_;a.pop.times{a<<j=0;p a.map!{|i|(v=j)+j=i}}

Run from command line with [array,R] as input.  It shows each increment of R along the way. The last line is the solution.
For example, if the array is [3,1,2] and R=7:
$ ruby -ne 'a=eval$_;a.pop.times{a<<j=0;p a.map!{|i|(v=j)+j=i}}' <<< [3,1,2,7]
[3, 4, 3, 2]
[3, 7, 7, 5, 2]
[3, 10, 14, 12, 7, 2]
[3, 13, 24, 26, 19, 9, 2]
[3, 16, 37, 50, 45, 28, 11, 2]
[3, 19, 53, 87, 95, 73, 39, 13, 2]
[3, 22, 72, 140, 182, 168, 112, 52, 15, 2]   <-- answer

For the same char count but different calling convention:
lambda{|a,r|r.times{a<<j=0;a.map!{|i|(v=j)+j=i}};a}

iX2Web, 94
**iX2004FB 800345MTAJ Tj18fAkwDQ oxMAlSPXx8 CTANCjIyCU 89W05dKjEx fEMJMA0KMw lbT118XzAJ MA0K=*

Not likely to beat my Golf-Basic solution. Makes up for it with pretty GUI and output. Windows only.

Please add an explanation for this code since iX2Web doesn't appear to have a free interpreter.

It gets input via GUI in the form of [R] and [N] and outputs in [O] (uses instantEXE3 framework, which I stopped using some years ago).

authors: Bob Jarvis - Слава Україні


text:
An improved version of GolfScript
I am planning to write an improved GolfScript for even shorter programs that can do more things. This is not a challenge; it is a request for feedback and tips on what I should do. (see tags)
I'm not sure if this should be Community Wiki. If you think so, just flag for a moderator to convert it :)
This language will be very similar to GolfScript. It is still written in Ruby. However, it has a few differences:

Using ` as a string delimiter, because it's an uncommon character, so less escaping will be needed. (Another character can replace its function, like # (more on that later)). \` to escape a backtick, \\ to escape a backslash, and there are no other escape sequences. If you need a newline, just stick an actual literal newline in the string.
Using Ruby's Rationals for arbitrary precision floating point, one of GolfScript's major flaws.
The ability to convert types to other types. For example, you can convert a block to a string.
Regular expressions. Probably created with "...". Operators will be overloaded for them as well. For example, "\W"~{`Invalid: non-word character`}{`OK`}if. Will automatically execute when pushed from a variable, like blocks.
File and Date objects, to do more stuff that was impossible in GolfScript. These will not have literals, but will have functions for initializing them, such as `file.txt`fl (name of the file-making-function may change).
Hashes maybe, but I'm not sure on that one. Should I?
Helper functions to do even more. For example, `http://example.com`net for network access (again, net operator may be renamed). rb to execute a string as Ruby code. There will be many more of these; suggestions welcome.
No comments, so that # can be used for something else. If you want a comment, `comment here`; will work fine. (Maybe # can replace `'s function)
It will be completely rewritten in a way that it will be much easier to add functions. Basically, the code will be more readable. (Have you seen the GolfScript source? :/)
It will be on Github so it can be collaboratively worked on. I'll license it under MIT or something.
No final newline, so cheaty quines work :P

And I'm setting these apart because I think they're the most drastic and helpful changes (except maybe adding floating point):

It will have many Ruby functions built-in. For example, shuffle (which may be abbreviated to sf) (previously took 9 characters), tr (previously 14 chars), sample (sm, previously .,rand=), flatten (fl, previously ???), etc.
It will be mushed, like Rebmu. For example, now you can do ~:a0<{0a-}aIF (using a letter variable name) instead of ~:$0<{0$-}$if (overwriting the sort function). (example from here). Note that this way, it is case-insensitive, and numbers are not allowed in variable names. This is okay in my opinion since it's a golfing language :P
It will have debugging. I will add the ability to supply a flag specifying array delimiters, element delimiters, etc., number output (rational, float, or int?), stepping through instructions one at a time, tokenizing and outputting each token instead of running the program, etc.

So, my question is: what is there to improve? What do you think I should add?
Any other ideas for this, before I start coding it?

Do realize that if you add mushing you lose case sensitivity.

@marinus I realize that. I should have made that clear; editing...

Also what it really needs is a way to do explicit I/O (for interactive programs). The interpreter could check beforehand if the program uses explicit I/O, and only do implicit I/O if it doesn't.

@marinus Great, you should add that as an answer then :)

` is already a quite important operator, thus not good as string delimiter.

@Howard I was planning on replacing \`` with #` or some other character. I'll edit that also

But I still have a need for comments! Otherwise you cannot save comments with your code.

@Howard \comment here`;` will work. I just don't see the need for comments in a golfing language...

``comment here; will be interpreted while comments are not. What about strings in the comment? Or #{}?

Related: Language idea for golfing purposes

@Howard Good point. I could add a rb command instead of #{}, and I guess you'll just have to escape \``. (Use `\``` for backtick in comments :-P)

Escaping inside comments? That sounds very strange. What's wrong with " as string delimiter?

@Howard, I sometimes do multi-line comments as 'comment';, but it is slightly fragile because it's possible to use ' in the comment unintentionally.

@Howard " is used more often, and would require an extra char to escape. Yes escaping in comments is odd, but it is a golfing language :-P

No no no ;-) If you'd post the first one as answer I'd downvote it.

Ok, I have to go on a plane so I'll not comment for a while. Looking forward to ideas when I land! :-)

Any updates on this? I've thought about upgrading Golfscript myself. Will try to remember some ideas I had and post them.

@Claudiu My development on my new language is quite alive, although I've recently been fairly busy so I haven't done much with it for a little while. Some of these ideas are just not good ideas though, which I am not using :P

Questions like this are no longer considered a good fit for the site, so I'm closing this.

@MartinBüttner Good call. Think we should lock it as well?

Flexible I/O
Golfscript cannot at present be used for interactive programs. I propose some functions for explicit input be added (i.e. readline, getchar and friends). The interpreter should see if the program uses these before running it.
If the program does not call any input functions, the interpreter should act like Golfscript normally does.
I wouldn't expect the interpreter to detect input functions in eval'ed code generated at runtime, but if it somehow can do that, kudos.

This is a great idea; limited io is one of golfscript's large limitations. +1

Shorter built-ins
Single-character aliases for all of the built-in commands which don't have them. I would use base a lot more if it were just B.

But what if you use b as a variable name? Still; good idea; you just remember to not use that name if you're going to use the function, and if you aren't using the function, then it doesn't affect you at all.

@DoorknobofSnow, you can already use built-ins (and even tokens such as ^ or $) as variable names. It doesn't make that problem any worse. Besides, I suggested aliases to allow backwards compatibility, so you would just have to use the longer name if you'd assigned something else to the shorter alias.

Z for zip would also be very useful.

Maybe we can release an official standard library for GolfScript. But I am unclear about how it can be included in solutions (missing #include and "#{IO.read'lib'}"~ is too long).

@Howard Now that's an idea... I could add libraries into my language, maybe like mylang -Llibname somefile.ext.

Combined div-mod
This is a bit more niche than some of the suggestions, but when working on number-theoretic programs I frequently find myself wanting an operation which pops two integers a and b from the stack and pushes a/b and a%b. (At present this is 1$1$/@@%).

Since it's so niche, maybe something like dvm for DiV-Mod. Thanks for all the ideas :-) +1

Numbers
Change the lexer such that leading 0 is not part of a number:
# current behaviour
01     # -> 1

# new
01     # -> 0 1

Also negative numbers should be written with _ instead:
# current behaviour
1 2-3   # -> -1 3

# new
1 2_3     # -> 1 2 -3

Wow, that's interesting. Usually you don't typically push two numbers in a row, but this would help with that a lot. The negative thing is great too, instead of 0 100- for negative 100. +1

I've thought about this before. There shouldn't be any support for negative integer literals at all. It's already handled by ~. E.g. -1 is 0~. This makes a small number of numbers longer by one char, but removes the moderately frequent need for whitespace after -.

Wait a minute, how would you push, for example, 1001? I think you meant leading zero, not trailing.

@DoorknobofSnow Right.

What would you think about doing {0\-}:~; (~ negative-izes a number) and using not for bitwise (just like and or xor)?

@Doorknob, bad idea. You lose the overloads; not sounds more like an alias for !; and it doesn't even gain consistency because and or aren't bitwise.

@Peter Well, I meant while still keeping the other overloads, but yes, it is probably a bad idea. Okay, I won't do that

@Howard: That's not the current behavior. 1 2-3 # -> 1 2 -3

@Dennis Of course you're right. With hindsight I might have meant that I want it that way to save a space if - is not treated as sign but always as operator (and '_' as sign).

Access to the whole stack
GolfScript is a stack-based language, but access to all but the top three items on the stack is limited to <integer>$ to copy the nth item. It would be useful to have something like PostScript's roll command so that it's easier to work with more than three "live" variables.
Ideally there would be one-arg and two-arg versions, but if there aren't enough names around then the one-arg should get preference for a one-character one.
The one-arg one just takes the number of items to roll. E.g. 1 roll does nothing; 2 roll is equivalent to \; 3 roll is equivalent to @; 4 roll and for higher numbers doesn't have an existing equivalent; the closest that's possible is something like
]-4/()\+\+[]*-1%~

(and that doesn't even handle non-integers at certain positions on the stack, or active [, and almost certainly breaks inside loops too).
The two-arg one also takes an amount to roll; a b roll2 is equivalent to {a roll}b*.

So, like Ruby's rotate. You should edit this into the CW answer.

@Doorknob, no. I'm talking about operating on a slice of the stack, not on an array.

Umm...I'm not sure what you mean. I'm not familiar with postscript, but roll just rotates the array, right?

@DoorknobofSnow, stack. An array is an item which goes on the stack.

Oh, so it rotates the whole stack. Ah, that might be useful! +1

@DoorknobofSnow Doesn't rotate the whole stack but only part of it, namely the top a items.

@Doorknob I've got a pretty full explanation of postscript's roll operator over on SO

CJam
I have implemented "an improved GolfScript" and it is called CJam - http://sf.net/p/cjam
Now at the second release (version 0.6) it already has many if not most of the features discussed here. I'll try to list them:

still written in Ruby - nope, java
using ` as a string delimiter - no, but it uses double-quoted strings with minimal escaping (\ escapes only \ and ")
floating point - supported, but only standard "double", not arbitrary precision
convert types to other types - yes
regular expressions - not yet, but planned; will use regular strings with special operators
File and Date objects - no, but can get the current date/time
hashes - assuming those are like python dicts or java maps, then they're not supported (may consider in the future)
helper functions to do even more - yes, a lot
`http://example.com`net - "example.com"g
execute a string as Ruby code - nope
no comments - exactly, # used for something else, "comments like this";
easier to add functions - I think so, but I'm also biased :)
on Github - even better (in my opinion, please don't shoot) - on SourceForge, using hg
licensed under MIT - yes
no final newline - right
shuffle - mr
tr - er
sample - not done, _,mr=
flatten - not done, but probably easier to achieve
mushed - nope, but identifiers don't need to be separated
debugging - only stack traces, and ed operator for showing the stack
flexible I/O - yes, but only explicit input
shorter built-ins - yes, b = base, z = zip
separate leading 0 - no, but can use predefined variables
disambiguate - - yes, but not with _; 1 2-3 -> 1 2 -3; 1 2m3 -> -1 3
roll/rotate the stack - nope
array set - t
divmod - md
change the lexer (for identifiers) - yes, more below
cartesian product - not exactly the same, but yes, m*
unicode operators - no
single-character identifiers - predefined operators have 1 or 2 characters and variables are single-character uppercase letters; they can all be concatenated without confusing the lexer/parser
operators on blocks - no
stable sort - yes
turn symbols back into code blocks - no, but may add later
current date/time - et
command line args - ea
clearly separating built-ins - yes, but capitals are variables; built-ins are or start with lowercase and special characters
min and max - yes, currently only for 2 values: e<, e>
absolute value - z (GolfScript has abs, not lacking)
sum and product of an array - :+, :*
Manhattan distance - nope
chr - c (converts to a character, not a string)
spill a string onto the stack - CJam strings are made of characters, not numbers; to spill the characters it's still {}/
a version of : that consumes what is stored - nope
operators for >=, <= - nope, use <!, >!
base64 and zlib - nope
shortcuts for 1$, 2$, 3$, 4$, 5$ - nope
copy the top two stack items - planned; for now use 1$1$
local variables - nope
HQ9+ features - no, thank you

CJam has a lot more features, check out https://sourceforge.net/p/cjam/wiki/Operators/

I disagree with SourceForge and Mercurial being better than GitHub.

@nyuszika7h it's ok, we all have our preferences

I just posted my very first CJam answer, because my GolfScript answer was in desperate need of a proper sqrt function. CJam is a lot faster than GolfScript!

@Dennis Awesome :)

@aditsu Would you consider CJam a dialect of GolfScript or a new language inspired by GolfScript? (Here's the reason I'm asking: http://codegolf.stackexchange.com/questions/37464/write-a-polyquine#comment86644_37464)

@MartinBüttner I consider it a new language inspired by GolfScript. I'm curious about that quine, I know a 9-char one that has different syntax in the 2 languages.

Change the lexer
GolfScript's lexer treats a Ruby identifier (anything which matches the regex [_a-zA-Z][_a-zA-Z0-9]*) as a single token. If it instead treated [a-zA-Z]+ as a token that would free up _ to be a built-in and would allow an alpha variable to be followed by a literal integer without separating whitespace.

Well, currently I'm using simply [a-z]+|[A-Z]+, for the mushing, so underscore is free. This is an interesting and very unique idea though! +1

Unicode aliases
Multiple-character commands could have unicode aliases. This would save on the score when the score is counted in characters and not in bytes.

uh... we don't want another APL...

Golfscript isn't anything like APL, Unicode or no. We already have several other APLs, like J and K. (or even R which looks quite APL-inspired to me, to the point that you can do literal translations quite often)

The distinguishing point about APL is that it uses a very different charset than anything else, not that it uses vector arithmetic natively. I like J, I use it, and I commonly upvote J answers. I've yet to upvote one APL answer. If I wanted to paint my programs instead of writing them, I'd use Piet.

I think APL is more legible than J, certainly more legible than Golfscript.

Stable sort
The $ builtin on blocks should perform a stable sort.

Array set operator
["A" "B" "C" "D" "E" "F"] -1 4 S    # -> ["A" "B" "C" "D" -1 "F"]

Any built-in we can make available for that?

+1 I started writing a blog post about implementing array set, but never finished it. It's currently extremely hard in full generality. This would make a big difference to some challenges.

I can't believe this isn't built in to golfscript already. +1

Single-character identifiers
It's not like a code golf solution is going to have too many variables. And it would save on spaces.

Hmm.. This could also be done by changing the parser. Perhaps a flag to specify this behavior? Great idea! +1

% as builtin for product
[1 2][1 2 3]%  # -> [[[1 1][1 2][1 3]][[2 1][2 2][2 3]]]

+1; you could edit my CW answer and add this one

What about modulo?

Regex support
The lack of regex support has always struck me as odd in a language designed for golfing. It would be great to have

<string> <string> <string> y (aka tr, using Perl's one-char alias for it)
<string> <string> <string> s (substitute)
<string> <string> <block> s (substitute with callback)
<string> <string> m (match)

I already mentioned regex in my question.

Builtins for current date/time
It is currently very quirky to get date/time using Ruby evals.
D     # -> [2013 12 31]
T     # -> [23 59 59]

Does that give date/time in Lima or Zulu?

@PeterTaylor Don't know - times are changing ;-)

@howard Did you mean, "The times, they are a-changing "?

Already mentioned as the Time type in the OP.

Make |, & and ^ built-ins do something useful on blocks
E.g. <array/string> <block> | can be used as index function
[0 -10 -20 30 40 -50 60] {0<} |   # -> [1 2 5]

Any ideas for <array/string> <block> & or <array/string> <block> ^?

What does array block = do now?

@JanDvorak Compare. Useful if you want to compare a string to a block, e.g. "0<" {0<} =.

How often do you need that? I'd rather drop that, and use array block = for "select by predicate"

@JanDvorak select by predicate is already implemented using ,.

oh, never mind. Go on :-)

Nice idea. Lol, I thought golfscript overloaded everything already :-P +1

A way to turn symbols back into code blocks
Currently, we can bind code blocks to symbols with :, but there's no way to reverse the process: executing a symbol bound to a code block just executes the block.
I can see a couple of ways to implement this:

add new syntax, e.g. #foo to push the value of foo to the stack, even if it's a code block, or
add an operator to expand every symbol in a code block, so that (using _ as the new operator), e.g. {2*}:dbl; {dbl dbl}_ would produce {2* 2*}.

I can see advantages to both methods.  The latter could substitute for the former, at the cost of two extra chars ({foo}_ instead of #foo), but I can see some potential applications for the former syntax where those two chars would be prohibitive (e.g. using array #func % instead of array {func} %).
Meanwhile, the former syntax could be used to replace the latter if there was a convenient way to somehow iterate over the tokens in a code block (which could be useful on its own, anyway).

In either case, I'd propose that expanding symbols that are bound to native built-ins (i.e. implemented in Ruby code) should return some kind of stub that could be called to obtain the functionality of the built-in, while being either impossible or just unlikely to be overridden.  For example #$ (or {$}_) could return e.g. {builtin_dollar}, where builtin_dollar would contain the actual implementation of the $ built-in (and #builtin_dollar or {builtin_dollar}_ should just return {builtin_dollar} itself).
This would allow built-ins to be redefined without losing access to their functionality (see my earlier suggestion), so that if I, say, for some reason wanted to swap the meanings of $ and @, I could just do #$ #@ :$; :@; (or {$}_ {@}_ :$; :@;).

One detail I'm not sure of is what the _ operator should do if the code block contains variable assignments. The obvious thing would be to just leave any :symbol tokens untouched and expand anything else, but this would cause _ to break any code using local variables. Making it not break such code might be impractically complicated, though.

Your second version would fit together with an flatten operator on arrays: [[1] [2] [3]] _ -> [1 2 3].

So what would be the result of 2:A;{1:A;A}_?

Naïvely, {1:A;2} (or, to be technical, {1:A builtin_semicolon 2} if the built-in expansion feature was included). If some kind of "local variable exclusion" feature was included, it might plausibly evaluate to just {1:A;A}.

Or to be even more technical {builtin_1 :A builtin_semicolon 2}.

Possibly, although I'd be inclined to leave numbers and whitespace (and strings!) alone. If you redefine them, you deserve all the pain you'll get.

Still struggling with your example: it should read {2*}:dbl; {dbl dbl}_ -> {{2*} {2*}}, shouldn't it?

No, if {dbl}_ evaluates to {2*}_, then {dbl dbl} should evaluate to {2* 2*}, while {{dbl} {dbl}}_ should become {{2*} {2*}}.

That would mean that you expand symbols deep into code-blocks?

Yes; I didn't state that explicitly in my post above, but I think that'd be the right thing to do, especially given that code blocks appear so often in looping constructs like array {loop} % where there's little distinction between the code inside and outside the block, except for the number of times it is executed.

Hmm, maybe just [some character]varname to push instead of execute, implemented on regex too. Good idea! +1

+1, but only for the _ version ;-)

Variable preset with command line args
Unfortunately, there isn't any char left unassigned, but maybe we can use A for that?

_ is available. Perhaps that? Anyway, yes, golfscript needs a way of taking cmd line args +1

Native Ruby functions that I should implement
This is Community Wiki; feel free to edit and add the functions you think I should implement!
Format: "nativeFunctionName (nameInMyLanguage)"

shuffle (sf)
tr (tr)
sample (sm)

Take features from APL and HQ9+ too!

Shortcuts, like in APL. EDIT: just saw the answer "unicode aliases". That's what I meant :)
Other golf-oriented shortcuts, like in H9+, HQ9+, CHIQRSX9+

Okay, so how would you propose that? Any specific ideas?

unicode characters allowing to do complex things in just one character.

@Doorknob of Snow , I updated my answer with the shortcuts I'd like to see: those from APL, and those from CHIRQSX9+ :)

Hmm, the hq9+ thing seems too cheaty :-P

It's golf oriented :P im my opinion your language should do at least as well :)

Clearly separating built-ins
e.g. capitals : built-ins ; making B for base feasable

As mentioned above there is no need to separate. If someone likes to overwrite a builtin he should be able to do so. I even found useful applications of overwriting operators like {-}:+.

No need, also this language will be case insensitive.

Since the goal is to provide less strokes per hole, having case sensitivity and more built-ins effectively leads towards the mission statement.

Local variables / closures
One thing I really miss in GolfScript is the ability to temporarily change the value of a symbol.
In particular, there's currently no way to temporarily override the meaning of a "primitive" built-in: once you, say, redefine $, you're never going to sort anything in that program again.  (Well, not without writing your own sort implementation, at least.)  It would be really nice to be able to say, for example, that in this code block $ means something else, but still keep the normal meaning elsewhere.
Related to the above, it would be nice to bind symbols in a code block to their current value.  Sure, I can write, say, {$-1%}:rsort and be able to use rsort to sort and reverse an array, but that works only as long as the definition of $ (or -1 or %) doesn't change, since my rsort function is still calling the global symbol $.  It would be nice to be able to say "let rsort do what $-1% currently does, even if those symbols are later redefined."
In particular, the standard library could use this kind of binding.  It's kind of surprising to realize that, say, changing n changes the behavior of puts, or that redefining ! completely messes up xor.  (Then again, some caution should be exercised here, since, in particular, the ability to change the behavior of puts turns out to be turns out to be the only way to avoid printing a final newline in the current version of GS.)
Edit: Being able to turn symbols back into code blocks would go a long way towards implementing this functionality.  In particular, the {foo}_ syntax suggested in that answer would effectively perform one level of static binding by expanding all symbols in a code block.  Combine that with a fixpoint combinator for deep static binding, and Bob's your uncle...

Come on - all the fancy new languages celebrate lazy evaluation ;-) Let's keep that feature in GolfScript.

On second thought - you're right, it is more a feature of binding than evaluation. But then - static binding is more complex than it sounds - e.g. provide recursive calls inside a definition.

"let rsort do what $-1% currently does, even if those symbols are later redefined" So Emmental?

More built-in functions
Make all the single-letter variables a-z and A-Z perform some generic, useful function. Some built-ins that are lacking:

min and max: all or some of top 2 stack values, top n stack values, over an array
absolute value
sum and product of an array. why do {+}* when you can do S? You have 52 functions to work with here!
Manhattan distance (i.e. x1 y1 x2 y2 --> abs(x2-x1)+abs(y2-y1). Now it'd have to be @-A@@-A+ if A is a built-in absolute value. Granted this only came up caues of my most recent post but I always figured that'd be a good way to expand golfscript: write down what functions would be handy to have, collect them, and add them as built-ins.
Convert an integer to a one-character string (equivalent of python's chr).
Spill a string onto the stack (currently {}/)
A version of : that consumes what is stored. This would have to not get 'stuck' to identifiers to be useful.
Operators for >=, <=
As someone suggested, a way to put a variable containing a block onto the stack without executing it. So you could reduce ifs of the form 1{\}{|}if to something like 1?\?|if
Built-in base64 conversion and zlib support to make embedding data take less characters
Beyond base64, make a custom base93 encoding (using all printable characters that aren't the string delimiter).
Shortcuts for 1$, 2$, 3$, 4$, 5$
An operator to copy the top two stack items as they are, i.e. \.@.@\

It'd be nice if the value written or computed in the last line of a function was automatically returned

It's stack-based, so...

There's no such thing as a function.

Functions don't return anything... and they're called blocks

That might be nice...in some other language. (No more annoying return statements at the end of functions! Yay! (But I haven't needed return statements ever, so...))