text:
Shortest way to reverse a number
Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.
For example given 76543 return 34567

Go back to the time the number was a string, then reverse the string

The idea of a "shortest algorithm" is somewhat specious, especially if you'll allow "any language." Think up an algorithm, and I'll give you a DSL with an appropriate "~" operator ...

Just a notice: any number ending with 0 becomes a shorter number of digits when reversed...

I know an algorithm that takes no time at all, but only works on palindromic numbers ;)

Found time to do the re-write myself. I hope this remain the puzzle that eltond meant to pose.

The algorithm for palindromic numbers needs at least one time step to output the number ;)

HTML 21 7 chars (1 char if I'm cheeky...)
n

replace n with your number

This is just plain genius. I'd go for one char. Or 2, as it encodes to two bytes in UTF-16 :P

Hahaha I did a Google search on that tag and was rewarded with Your search - - did not match any documents.

U could try this link in browser: data:text/html,&%238238;egnahcxEkcatS olleH

Funny in google transate too. @JoeFish: I can't reproduce, please post a link!

@JoeFish When I look at the comment, your username is flipped and there is some text after it. txet emos si ereH

Python
int(str(76543)[::-1])
EDIT:
Shorter solution as suggested by  @gnibbler:
int(`76543`[::-1])

or, if above is unclear:
x=76543
int(`x`[::-1])

s[::-1] is a lot faster than ''.join(reversed(s))

You can use backticks (for repr) instead of using str

@gnibbler Thanks for suggestion. I've updated my answer.

TBH, that ain't a function/proceduce/whatever you want to call it, and the specs require it.

Also, it doesn't even accept a value...

Work's only in Python 2

It doesn't work with negative values.

This doesn't work with numbers that are longs. Example: print int(`2**32`[::-1])

Universal (language agnostic/independent)
If you want to use only numbers (avoid converting the number to string) and don't want to use some specific library (to be universal for any language):
x = 76543 # or whatever is your number
y = 0
while x > 0:
    y *= 10
    y += ( x %10 )
    x /= 10 # int division

This is python, but it could be done in any language, because it's just a math method.

If you replace mod with %, it's valid Python ;)

You're right, actually :) 10x

But see below it is not the shortest way.

Not the shortest, but the most common and universal.

y=y*10+x%10....

I prefer this to all the string methods, because it's more efficient and elegant, and some APIs may decide that the reverse of e.g. 110 ('011') is 11 octal.

Why not use the built-in divmod() function? You don't even have to import it.

Because I wanted to make universal solution, that can be written in any language and I didn't want to use any built-in functions.

Not every language has a modulus operator... so it's not universal. Just an FYI.

@mbomb007 that's interesting, for example?

BrainFuck doesn't, though it can be calculated. Any language that doesn't have it can use a - (n * int(a/n)) instead of a mod n. Also, if you look here, the modulus operation is implemented differently in every language. (See the table on the right.)

Perl 6
+$n.flip

or:
$n.flip

for dynamically typed code.
Numbers got string methods due to language design.

J - 6 characters + variable
".|.":y

Where y is your value.

As a function: |.&.": "reverse under do" which is pretty much a literal translation of the task.

APL (3)
⍎⌽⍕

Usage:
⍎⌽⍕12345 => 54321

PHP, 9 chars
(int)strrev(123);

To do it short where N is a constant:
strrev(N)

Vim 17 chars
:se ri<CR>C<C-R>"

I would say that's 10 chars (keystrokes) if you type the command directly in vim. Btw, I learned something new in vim today, thanks :)

Befunge (3 characters)
Complete runnable program:
N.@

Where N is your number. Rules say "accept a single integer valued argument"; In Befunge you can only enter integers from 0 to 9.

Those are the only literals, but other numbers could certainly be represented. Otherwise, the winning answer would be Brainfuck with the empty program. ;-)

Language-independent/mathematics
Inspired by Kiril Kirov's answer above.  I got curious about the mathematical properties of reversing a number, so I decided to investigate a bit.
Turns out if you plot the difference n - rev(n) for natural numbers n in some base r, you get patterns like this ((n - rev(n)) / (r - 1), for r=10, wrapped at r columns, red denotes negative number):

This sequence could be generated as such (pseudocode):
for i=1 to r:
  output 0

for m=0, 1, …
  for k=1 to (r-1):
    for d=1 to r^m:
      for i=0 to (r-1):
        output (r-1) * (r+1)^m * (k - i)

If you store these values in a list/array, then n - arr[n] would get you the reversed form of n.  Now, to "mathematically golf" this, we'd ideally want a closed-form expression that gives us the n:th value in the sequence, so that we could have a closed-form expression for solving the entire task.  Unfortunately, I haven't been able to find such an expression... but it looks like it should be possible. :(
So yeah, not so much a code-golf as a mathematical curiosity, but if there is a closed-form expression of the above sequence it might actually be useful in proper PL golf submissions.

Haskell, 28 24 characters
f=read.reverse.show.(+0)

How about f=read.reverse.show.(+0)?

(+0): Legit man! Though technically you don't need the .(+0) at all, as f would be more polymorphic than what the problem requires (it is allowed to return a 'similarly typed' output). I would shave off those 5 characters.

Ruby (14)
x = 13456
x.to_s.reverse

"no" is undefined. I think you meant to put "x" there.

123456.to_s.reverse is even shorter.

@mmdemirbas - thanks for fixing the typo

Needs to be .to_s.reverse.to_i to comply with spec.

A number that starts with 0 doesnt seem to work.
0112.to_s.reverse.to_i
=> 47

@Joel A "number starting with 0", in ruby, is octal. I.e. 0112 == 74. So unless you make a fundamental change to the ruby language, I think that's outside of scope.

Also, you can shave an extra digit off, with: x.digits.join.to_i

Scala - 33 Chars
def r(a:Int)=(a+"").reverse.toInt

+1 for scala, nice to see something else than python/ruby/perl

This will fail on negative Int. -123 should return -321

Python 3+
Function form: 28 characters
r=lambda i:int(str(i)[::-1])

(Sub)program form: 25 characters
print(input()[::-1])

I consider some of the other Python examples to be cheating, or at least cheap, due to using hardcoded input and/or not fully satisfying the requirements.

It is possible to convert a number a string, then reverse the string and then convert that string back to number. This kind of feature is probably available in all language. If you are looking for a more mathematical method then this might help:
int n = 76543;
int r = 0;

while (n > 0) {
    r *= 10;
    r += n % 10;
    n /= 10;
}

Mine is absolutely the same (:

Ya, only difference is your code looks like Python.

This method overflow's on languages with limited precision. try 1111111119

Golfscript, 5 chars
`-1%~

This takes an argument on the stack and leaves the result on the stack. I'm exploiting the "subprogram" option in the spec: if you insist on a function, that's four chars more leaving it on the stack:
{`-1%~}:r

I think you must've meant \-1%~rather than`-1$~` (and I've taken the liberty of editing your answer to say so).

In shell scripting :
  echo "your number"|rev

Hope this was useful :)

good one! didn't know bash was capable to that also!

I guess technically it does return a similarly-typed "number"... could be shortened further with rev<<<yournumber, e.g. rev<<<132 (for bash/zsh, not per POSIX though)

Just rev is enough, the question doesn't say it has to be a function. You could compare rev to a built-in function, even though it's not one.

this is invalid: 'rev' is not a builtin, but an external program call.

67 Bytes pure POSIX shell: X=$1;while [ $X != 0 ];do Y=$((Y*10+X%10));X=$((X/10));done;echo $Y

Kinda late but
APL, 3
⍎⌽⍞

If you insists on a function
⍎∘⌽∘⍕

Well looks like I couldn't spot a duplicate above...(due to it being on the 2nd page)

I'm sad, that nobody gave brainfu*k or whitespace solution :( (one more vote and you're on the first page )

@KirilKirov I've a brainfu*k solution : http://codegolf.stackexchange.com/a/32826/24829

Mathematica, 14 bytes
IntegerReverse

This is not competing, because this function was only added in last week's 10.3 release, but for completeness I thought I'd add the only ever (I think?) built-in for this task.

Depends on what you mean by short (javascript):
alert(String(123).split('').reverse().join('')),

this is short for sure :)

alert((''+123).split('').reverse().join(''));

Why not alert(prompt().split('').reverse().join('')); ?

You could do the following in Java. Note that this converts to String and back and is not a mathematical solution.
public class test {
    public static int reverseInt(int i) {
        return Integer.valueOf((new StringBuffer(String.valueOf(i))).reverse().toString());
    }

    public static void main(String[] args) {
        int i = 1234;
        System.out.println("reverse("+i+") -> " + reverseInt(i));
    }
}

It is a mathematical solution. Mathematics is not numbers is not arithmetics. Mathematics also deals with strings of symbols. And in this special case, the conversion to and from string is just conversion to and from base-10.

What I meant by "not a mathematical solution" is that we're not doing any math ourselves. The methods are doing all of the parsing and mathematics for us. As opposed to e.g. Kiril Kirov's answer.

Will Overflow...

Lua
Numbers and strings are interchangeable, so this is trivial
string.reverse(12345)

This one ACTUALLY takes an input, unlike some of the rest:
print`input()`[::-1]

Python btw.

Actionscript
43 characters. num as the parameter to the function:
num.toString().split('').reverse().join('')

Groovy
r={"$it".reverse() as BigDecimal}

assert r(1234) == 4321
assert r(345678987654567898765) == 567898765456789876543
assert r(345346457.24654654) == 45645642.754643543

Perl, 11 chars
The p flag is needed for this to work, included in the count.
Usage:
$ echo 76543 | perl -pE '$_=reverse'

I count 10 chars

The p flag is included in the count

Clojure (42 chars)
#(->> % str reverse(apply str)read-string)

Example usage:
(#(->> % str reverse(apply str)read-string) 98321)

returns 12389

Common Lisp - 60 chars
(first(list(parse-integer(reverse(write-to-string '4279)))))

will get you 9724.

Why (first(list? parse-integer already returns the number.

K, 3 bytes:
.|$

Evaluate (.) the reverse (|) of casting to a string ($).
Usage example:
  .|$76543
34567

rs, 20 bytes
#
+#(.*)(.)/\2#\1
#/

Technically, this doesn't count (rs was created earlier this year), but I didn't see any other regex-based answers, and I thought this was neat.
Live demo.
Explanation:
#

Insert a pound character at the beginning of the string. This is used as a marker.
+#(.*)(.)/\2#\1

Continuously prepend the last character of the main string to the area before the marker until there are no characters left.
#/

Remove the marker.

mIRC 4.45 (35 Bytes)
$regsubex(12,/(.)/g,$mid(\A,-\n,1))

this is AS3 code, so you may need to make slight changes
function reverseData ( inData:String ):* {
    var ar1 = inData.split(''); //Takes string value, split each digit into an array

    var ar2 = ar1.reverse(); //Inverses the array direction
    /* //OR (if not supported) [not AS3]
    var ar2 = new Array();
    for( var i:int = (ar1.length - 1); i > 0; i++ ) {
        ar2.push( ar1[i] );
    }
    */

    var result = ar2.join();
    return result;
}

It should work for a string equavalent (that should be easy to typecast)
For a javascript example...
function flip( inData ) {
    return ( parseInt( (inData + '').split('').reverse().join('') ) );
}

alert( flip(123) );

C#
int reversed = Convert.ToInt32(String.Join<char>(null, 76543.ToString().Reverse()));

int.Parse should be shorter.

An anonymous user proposed editing this to int reversed = int.Parse(string.Join("", ("" + 76543).Reverse()));

Perl (19 chars)
Simple:
$x=reverse (98765);

k4 - 6 characters
"I"$|$

Examples:
  "I"$|$76543
34567
  "I"$|$98765
56789

Explanation from right to left:
("I"$ = cast to integer)(| = reverse)($ = convert to string)

It's possible to use . (eval) instead of "I"$, i.e. .|$.

Java
""+new StringBuilder(""+i).reverse();

ruby (26)
The existing ruby answer wasn't a function/lambda, so here goes:
f=->i{i.to_s.reverse.to_i}

in Q (20 characters)
f:{"I"$reverse -3!x}

Sample Usage:
q)f 89478237
73287498

Use the k version of reverse (wrapped in parentheses) to make it shorter
{"I"$(|:) -3!x}

also just define it as a lambda to take 2 chars off for a total of 15

Bash (15)
read a;rev<<<$a

As a number of other entries do, '01234' becomes '43210' and '2340' becomes '0432'; i.e. in Python terms it does print reverse(raw_input()). If behaviour like print int(reverse(str(int(raw_input())))) is expected, it is a bit longer:
Takes care of trailing zeroes (36)
read a;sed s.^0*..\;s.0*$..<<<$a|rev

I think right count is 3: rev alone will suffice

“Write a function” – So I think the shortest solution is still 15 characters, but this way: r(){ rev<<<$1;}. (And even that is kind of cheating as the complete solutions is r(){ return \rev<<<$1`;}`.)

@manatwork Shorter versions: r()(rev<<<$1) or r()(exit `rev<<<$1`).

Cool trick, @user23013.

str(int(raw_input())) really? [Python 2] [str(int(input()))] [from your example print int(reverse(str(int(raw_input()))))]

BaCon
PRINT REVERSE$(STR$(76543))

Replace 76543 with any number.

Brainfuck, 11
>,[>,]<[.<]

This accepts any string, not just numbers (ASCII 48-57).

Pyth (3 chars)
Try it here
v_z

TI-BASIC, 35 32 31 (or 28) bytes
Takes input from the calculator's answer variable, which is whatever was last evaluated (like _ in the interactive python shell).
fPart(.1int(Ans10^(seq(A,A,~int(log(Ans+.5)),not(Ans
sum(Ans10^(cumSum(1 or Ans

10^( is 2NDLOG and ~ is ( - ), next to ENTER. Everything else can be found in the 2ND0 catalog.

If the program doesn't have to handle the possibility of 0 as input, it can be reduced to 28 bytes by changing ~int(log(Ans+.5)),not(Ans to ~int(log(Ans)),0.
Credit goes partially to Thomas Kwa for helping to golf this.

Doesn't work with 0; you could easily fix this by replacing log(Ans) with log(Ans+.5) and int( with iPart(. The shortest I found in a few minutes with a forwards list of digits was fPart(.1int(Ans10^(seq(A,A,~int(log(Ans)),0:sum(Ans10^(cumSum(1 or Ans; this can probably be improved. Overall, good work!

@ThomasKwa yep, using 0 for the end argument throws ERR:INCREMENT. You're right about not(Ans, though.

ES6 Javascript, 31 bytes
x=>[...x+''].reverse().join('')

You could save 2 bytes by using .join``  instead of .join('').
Also, what do you mean with that comment: "This doesn't assume b is an integer."

C++:
int reverse(int number, int number1, int number2){std::vector<int> v; v.push_back(number); v.push_back(number1); v.push_back(number2); std::cout << v[2] << v[1] << v[0]; return 0;}

Welcome to Programming Puzzles and Code Golf letsch! It is customary to include the byte count along with your submission, as this question is a [tag:code-golf]. You might want to format your header as such: # C++, <number of bytes> bytes

Adding to what Conor said, you should also attempt to make your code as short as possible since this is a code golf competition. You could start by removing unnecessary whitespace and using single letter names.

Scheme, 75 characters
(string->number(list->string(reverse(string->list(number->string 76543)))))

You can probably remove all the spaces but the last one.

Count in bytes, please.

k3, 4 chars
0$|$

0$|$76543 \-> gives 34567

See also the K4 solution here. The only difference (saving two chars) is that 0$ converts to int.

PHP, 37
<?function f($n){return strrev($n);}

C, 44
x;m(n){for(;n;x=x*10+n%10,n/=10);return x;}

Neither of these are functions, as specified.

@KevinReid Rectified!

R (35 characters)
> cat(rev(strsplit("12345","")[[1]]))
5 4 3 2 1

With help from my friends in R chat.

12345->54321, not 12345->5 4 3 2 1.

Game Maker Language, 44
Replace 12345 with whatever number or variable you want:
n=12345while(n>0){r=r*10+(n mod 10)n div 10}

If you want to prompt for user input, use this 56 character long code instead:
n=get_string('','')while(n>0){r=r*10+(n mod 10)n div 10}

In both pieces of code, the reverse number is stored in r

The question specifically asks for "a function (or equivalent subprogram)" which takes "a single integer valued argument". Neither of your code snippets meet that spec.

@PeterTaylor They're assumed to be scripts (function equivalents).

Haskell, 61,23
Using the string reversing technique. digitToInt is available from the Data.Char library, and of course this code would be shorter if we'd be able to assume if Data.Char already was available.
-- original version 61 chars
foldl1((+).(*)10).map(Data.Char.digitToInt)$reverse$show 1234

--bonus foldonly version, 67 chars
foldl1((+).(*)10).foldl(flip((:).Data.Char.digitToInt))[]$show 1234

--FireFly's suggestion: 23 chars. Note that read's return type is `a`
-- so you might want to tack on a +1 on ghci etc so `Int` can be derived.
read.reverse.show$1234

Hm, why not read it back after reversing? I.e. read.reverse.show$1234.

hmm for some silly reason I thought read had to do with IO monads. You're right, read would work.

Added it. fold was more fun though :)

Groovy 32
def r(n){print ((n+"").reverse())}

Rebol, 29
f: func[n][do reverse mold n]

Usage example in Rebol console:
>> f 76543
== 34567

If you only wanted this to work on integer input then....
f: func [n [integer!]] [do reverse mold n]

TI-BASIC, 58 54
Input N:0:While N>0:Ans+E3fpart(N,10:N/10→N:End:Ans

Usage
prgmREVERSE
?598028
          820895
            Done

POWERSHELL, 25
-join(Read-Host)[-1..-9]

a longer version to take arbitrary input , 36
-join($a=Read-Host)[-1..-$a.length]

usage
PS C:\> -join(Read-Host)[-1..-9]
123456789
987654321
PS C:\>

Julia, 23
r(x)=int(reverse("$x"))

$ interpolates an argument (or the result of a function) into a string, denoted by the double quotes. int() automatically deletes leading zeroes.
Example:
julia> x=1234567890;r(x)
987654321

or
julia> r(1234567890)
987654321

C# - 58
I think we need more C#
int.Parse(string.Concat(Enumerable.Reverse(x.ToString())))

The spec requires a function or equivalent subprogram (a lambda would probably be acceptable, but a statement isn't); and it requires the return value to be similarly typed to the input (i.e. you're missing an int.Parse or a Convert.ToInt32).

@CoolerRanch still a statement I think

Burlesque, 2 bytes
Certain built-ins treat numbers as list of digits. The reverse built-in for example treats integers as a list of digits and thus reverses integers.
blsq ) 76543<-
34567

(For characters <-  switches case).

MATL, 3 bytes (non-competing)
VPU

This uses release 10.1.0 of the language/compiler, which is the current version at the time of writing.
Try it online!
Explanation
V   % implicitly input a number and convert to string
P   % flip
U   % convert to number and implicitly display

Python 2, 26 bytes
print int(`input()`[::-1])

Python 3, 33 bytes
I decided to make a function instead of hardcoding it.
def r(n):print(int(str(n)[::-1]))

The code is pretty self-explanatory.
Usage: r(12345)

Oracle SQL 11.2, 35 34 bytes
SELECT 0+REVERSE(:1||'')FROM DUAL;

JavaScript (ES6) 35
a=b=>b.split("").reverse().join("")

This doesn't assume b is an integer.


text:
Tips for golfing in Clojure
What are your tips for code golfing using Clojure?
The aim of this question is to collect a list of techniques that are specific to Clojure and can be used in general code-golfing problems.

Hmm.. shouldn't these types of posts be in meta (granted I'm not sure meta existed 5+ years ago)

Use reader syntax for lambdas.
So use
#(+ % %2 %3)

instead of
(fn [x y z] (+ x y z))

You can also eliminate whitespace some of the time:
#(if (< % 0) (- %) %)
#(if(< % 0)(- %)%)

by the way #(+ % %2 %3) is equivalent to +.

Where you can remove whitespace:

Between a string and anything else:
(println(+"Hello, World!"1))

Between brackets and anything else:
(for[x(range 5)](* x x))

Between a number and everything other than builtins or variable names:
Allowed:
(+ 1"Example")
(map{1"-1"2"-2"}[1 2 3])

Not allowed:
(+1 2)

Between @ (dereference for atoms) and brackets.

Also before the deref reader macro @

Also at times you might be able to re-arrange stuff at a let and get rid of some spaces.

Also before parameters in anonymous functions: #(+ 1(first%)) = #(+ 1 (first %))

Strings can be treated as a sequence of chars
e.g. to sort the characters in a string alphabetically:
(sort "hello")
=> (\e \h \l \l \o)

Strings are by definition a sequence of chars in almost every language, but you can't apply this trick in all of them :-)

Or rather, "sequence" has a special meaning in Clojure than means you can apply extra tricks ::-)

Use nth ... 0 instead of first
To get the first element of a collection, using (nth ... 0) over first saves a byte:
(first[2 3 4]): 14 bytes
(nth[2 3 4]0): 13 bytes (saves a byte!)

same goes for second (2 bytes)

Also you can use vectors as functions, so ([2 3 4]1) returns the element at index 1. This should be benefitical if for example the input format is flexible.

Use maps instead of ifs when testing for equality
;; if n=3 then A else B
(if (= 3 n) A B) ; (if(=3n)AB)
({3 A} n B)      ; ({3A}nB) -> -3 chars

;; if n=2 or n=3 then A else B
(if (#{2 3} n) A B) ; (if(#{23}n)AB)
({2 A 3 A} n B)     ; ({2A3A}nB) -> -4 chars

Use apply instead of reduce
For example #(apply + %) is one byte shorter than #(reduce + %).

Bind long function names at let to a single-byte symbol
For example if you need to use partition or frequencies multiple times, it could be beneficial to bind them to a single-byte symbol in a let macro. Then again it might not be worth it if you don't need the let otherwise, and the function name is relatively short.

Avoid let if you already have a for
For example: #(for[a[(sort %)]...) instead of #(let[a(sort %)](for ...)).
For does also have a :let construct but it is too verbose for code golf.

Use + and - instead of inc and dec
This saves 1 byte if you're using inc/dec on an expression with parens:
(inc(first[1 3 5]))
(+(first[1 3 5])1)

Use for instead of map
For instance #(for[i %](Math/abs i)) is a lot shorter than the map equvalent.

source: Stack Exchange

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

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

sort: votes


text:
Daily horoscope for zodiac signs
Code a daily horoscope for the 12 zodiac signs, it needs to be self-sustained (no external ressources), quite randomized but fixed by zodiac sign for each day.
It needs to extract three "variables" from 1 to 3 :

love
work
money

Each one ranked from 1 to 3.
Ex. of variables that can be used (vars fixed for a day or more, can be extended) :

Year
Month
Day
Day of week
Math.PI
Zodiac signs order (from 1 to 12)

Exact duplicate: http://stackoverflow.com/questions/6355525/coding-a-daily-horoscope-algorithm

Requirements are fairly unclear

@Paul: Thanks for the pointer, but I think that in this epoch code golf is off-topic on Stack Overflow, so this version takes precedence.

Welcome to CodeGolf.SE! As it stands your task is highly underspecified and in danger of being closed. You might want to examine the tag wiki for code golf or some of our more popular tasks. In the future you can get help in the sandbox or on the puzzle lab chat before your task goes live.

Please make an effort to bring this more in-line with our usual level of specification. There is nothing intrinsically wrong with this task, you just have said what the task is yet.

Python, 106 chars
import time,zlib
for i in range(12):n=zlib.crc32(time.strftime('%%Y%%j%d'%i));print 1+n%3,1+n/3%3,1+n/9%3

Calculates the CRC of a string made up of the current year, day of year, and zodiac sign.  Grabs some bits of the result for the horoscope.

From SO : "Add year+month*11+day*13+sign, feed this in as a seed to your local PRNG. After that you can either generate one "next random number" mod 27, extracting your 3 3s from there, or run it three times mod 3."

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


text:
Shortest, lexicographically smallest generating string
A string x generates a string y if y is a substring of an infinite repeat of x.  For example abc generates bcabcab.
Write a program to find the shortest, lexicographically smallest string that will generate the input.  You are given on standard input a single line of text.  You should print the generating string to standard output.  For example:
input
bcabcabca

output
abc

Shortest code wins.  You may assume the input contains only the characters a-z (and a trailing newline if you want).

Output should be in any order? Say output can be bac in your example rather than abc?

@GroovyUser: no, the input is not a substring of a repeated pattern of bacs.

But the input could consist of a substring of (bca)^n, which means bca is just as valid for the given example as abc.

@JAB: bca is not the smallest lexicographically.

Ah, I somehow missed that part.

Ruby 1.9, 40 characters
gets;a=?a;a.next!until(a*~/$/)[$_];$><<a

Assumes the input is not terminated by a newline. Also it's probably ridiculously slow for larger results.
$ echo -n "bcabcabca" | ruby genlex.rb
abc
$ echo -n "barfoobarfoobarfoo" | ruby1.9 genlex.rb
arfoob

Python 88 185 chars
import re
s=raw_input()
m=s.index(min(s))
s=s[m:]+s[:m]
i=0
while s.replace(s[:i],''):i+=1
m=min(s[:i])
s=re.findall('%s[\w]*?(?=%s|$)'%(m,m),s[:i])
m=s.index(min(s))
print ''.join(s[m:]+s[:m])

Output:
bcabcabca
abc

aaa
a

abc
abc

cccbbcccbbcccbb
bbccc

barfoofoobarfoofoo
arfoofoob

bacabac
abacbac

Doesn't give you the lexicographically smallest string for some inputs, e.g. "bacabac"

@Howard You are right. I've updated my code, it is much longer now, but handles strings like bacabac correctly.

"abac" would be correct, see @yogsototh's answer: abacabacabac.

Haskell, 299 128 characters
import Data.List
main=interact(\z->minimum$filter(\w->isInfixOf z$concat$replicate(length z)w) $filter((/=)"")$inits=<<tails z)

Thanks to jloy! Now the version is both far shorter and I believe correct.

So, the good news is that it's possible to golf this solution down to about 91 chars if you accept input on stdin as in Ventero's Ruby solution.  Unfortunately, the input cabcabcabc produces abcabc, so this solution isn't quite there.  I think you'll need to modify q++q++q in order to get the desired result.  My quick attempt at fixing bumped things back up to 145 chars though. (Spoilers are here: https://gist.github.com/1035161)

Thanks! I didn't knew about interact nor never though about inits <<= tails to get all substrings. I slightly modified your version to gain a bit of characters. I removed sort and changed filter(not.null) by filter((/=)""). Thanks again!

Why do you need (/=)"" condition? It doesn't seem to do anything. Also, getting rid of lambdas helps: you can get rid of w altogether using . operator and change main function to main=interact s to save a couple of characters.

I think the answer for "bca" is wrong. It should be "abc", but is "bca" now.

One possible solution is to use permutations instead of tails.

@Rostor is correct about the null filter.  That was left over from an brief experiment with cycle and shouldn't be necessary.

Python, 161 159 166 140 141 134 132 chars
y=raw_input();i=n=l=len(y)
while i:
 if (y[:i]*l)[:l]==y:n=i
 i-=1
x=y[:n];y=x*2
while i<n:
 x=min(x,y[i:i+n])
 i+=1
print x

EDIT : Golfed the code after reading  Jules Olléon's comment. Removed a 'bug' that bcdabcdab results in abbc.
EDIT2 : Fixed the bug (abaa results in aaa) spotted by Jules Olléon.
I don't know about Python well, so this code is probably 'not golfed'.
I love this rule:
You may assume the input contains only the characters a-z...
Inputs & Outputs
bcdabcd
abcd

bcabcabca
abc

abcdabcd
abcd

bcdabcdab
abcd

barfoofoobarfoofoobar
arfoofoob

cccbbcccbbcccbb
bbccc

aaaaaaaaaaaaaaaa
a

thequickbrownfox
brownfoxthequick

ababa
ab

abaa
aab

Brown fox, the quick! Dog, the lazy!

Nice solution, pretty short and probably the best complexity here! You could golf it a bit - for instance, you dont need "int" to compare strings; and replace "while i>0" by "while i" and "y=y+y" by "y*=2".

Actually there's a problem : for abaa it prints aaa...

@Jules Thanks for the comment! I didn't think about that one...

You can do i-=1 instead of i=i-1. Likewise for the increment.

Python, 121 137 129 chars
s=raw_input()
n=len(s)
l=[(s+s)[i/n:i/n+i%n+1]for i in range(n*n)]
print min(filter(lambda x:(x*len(s)).find(s)+1,sorted(l)),key=len)

EDIT: fixed the bug spotted by JiminP

Wow, it's great! Unfortunately, it prints aabab for string ababa... :(

Ok, fixed... it's getting longer :(

Ruby 1.9, 36
$><<(?a..gets).find{|s|(s*~/$/)[$_]}

Uses the same approach as Ventero's solution.

Mathematica 124 bytes
x = StringLength@(y = "");
For[i = 1, ! (s = y~StringTake~i)~StringRepeat~x~StringContainsQ~y,i++];
First@Sort@StringPartition[s <> s, i, 1]

Whitespace and newlines (in the presence of semicolons at the ends of lines) have no meaning in Mathematica and are included here for readability.
Input goes in between the quotation marks in the first line. If recast as a function, that takes string input like so:
f=(x=StringLength@(y=#);For[i=1,!(s=y~StringTake~i)~StringRepeat~x~StringContainsQ~y,i++];First@Sort@StringPartition[s<>s,i,1])&

f@"bca"

(* "abc" *)

f@"abaa"

(* "aab" *)

then it's 128 bytes.
The For loop takes the first i characters of the input and repeats them at least up to the length of the input, then checks if the input is a substring of the result. Having found the length of the period of the string, the StringPartition command concatenates two copies of that period and takes all substrings of that length from it (basically gets all cyclic permutations), then First@Sort finds the first one of them when lexicographically ordered.

PowerShell, 23 bytes
-join($args|group|% N*)

Try it online!

This doesn't seem to work. Given input abacaba it gives abc, which could never generate the input...

javascript 96 Chars.
var temp = {},len = str.length;
for(i in str)
temp[str[i]] = true;
Object.keys(temp).join("");

Working Plunkr

Welcome to the community ! I couldn't test your code though, could you provide either code reading from GET/POST and writing with alert or console.log or a function taking the input as a parameter and returning the output?

@AaronGOUZIT added pluckr

Thanks, that helps. Still, the code you posted can't be used alone, so that cheats the byte count. More importantly, I'm afraid your code doesn't respect the specs : I believe you return a set of unique letters used rather than a "generating string", which we should be able to repeat (as a whole) with optional truncation to obtain the input. I'm looking forward to seeing your updated code !


text:
What's the day today (or other dates)?
Task
Write a program or a function that calculates a week-day name of a date which a user inputs.
Input & Output
Input is a string, YYYYMMDD.
Example of input values:

20110617 : June 17, 2011
19040229 : February 29, 1904
06661225 : December 25, 666
00000101 : January 1, 0
99991231 : December 31, 9999

You may assume that all inputs are valid. Note that year zero is valid.
Output is an integer between 0 and 6. Each integer represents a week-day name. You can decide freely which integer represents a week-day name, like this one

0 : Monday
1 : Tuesday
2 : Wednesday
...
6 : Sunday

(in order) or this one

0 : Monday
1 : Wednesday
2 : Sunday
...
6 : Saturday

(not in order).
Test Cases

Input     Week-day   Output ([0..6 -> Monday..Sunday] is used in this example.)

20110617  Friday     4
19500101  Sunday     6
22220202  Saturday   5
19000228  Wednesday  2
19000301  Thursday   3
19450815  Wednesday  2
19040229  Monday     0
19040301  Tuesday    1
17760704  Thursday   3
20000228  Monday     0
20000229  Tuesday    1
20000301  Wednesday  2
20121223  Sunday     6
00000401  Saturday   5
66660606  Wednesday  2
59161021  Saturday   5

Restriction
You must not use any kind of function/class/... which are related to timestamp or date, like Date class in Java/JavaScript/ActionScript, or getdate function in PHP.
You should use Gregorian calender, which is used by many people now.
Of course, shortest code wins. If two code have same length, then the code with highest votes wins.
(Due: When there's more than 5 codes which has more than (or equal) +1 votes.)

To-day?  Why, Christmas Day!

Optimistic solution written in Bash (6 chars):echo 4.

@trutheality No, I didn't mean that.. What I wanted is a code that prints/returns the day of week of a date someone typed, not just print the day of week of today.

Oh I know. That's what this one does.

It's right at least 14% of the time!

Ruby, 95 92 characters
Plain straightforward ruby implementation with 0:Monday, ...
p ((y=(d=gets.to_i)/(k=100)/k-((m=d/k%k)<3?1:0))+y/4-y/k+y/400+"squsptrotqro"[-m].ord+d%k)%7

PHP - 101 97 103 125 characters

Sakamoto Algorithm
0 = Sunday

Code
<?php fscanf(STDIN,"%4d%2d%2d",$y,$m,$d);@$a=a032503514624;$y-=$m<3;$z=$y+1;echo($y+$y/4%$z-$y/100%$z+$y/400%$z+$a[$m]+$d)%7;

Note
Unfortunately, due to PHP's dynamic, weak typing, the Sakamoto algorithm doesn't function properly without explicitly flooring each division operation.

Can you please test again? For some years it gives me different results (e.g. testcase 17760704 yields tuesday instead of wednesday).

@Howard that's very odd; for 17760704, I get Wednesday. I do get other inconsistencies, though, which I cannot account for, e.g. 19040229 returns Tuesday. Not sure what could be causing this. I get the same results when I expand the algorithm back out to y+y/4-y/100+y/400.

I can see it happening with 497*y/400: y=4 in that case returns 4, instead of the correct 5 from y+y/4+y/100+y/400 (where only the first two terms come into play). That is what plagues my JavaScript answer. Is it possible that doubles are being created instead of ints? (My PHP is too weak to know.)

@DocMax: Leaving the expression expanded has the same result (497y/400 should be equivalent: y/100 is subtracted and y/400 added again regardless). I'm guessing that PHP is just chopping off everything after the decimal instead of rounding it. I tested this by rounding before the modulo. This fixes two of the anomalies, but 19040229 still returns the same result. Any other ideas?

@rintaun i don't think it is the rounding. They are fundamentally different. Take the example from above (y=4): 497*4/400=1988/400=4 but on the other hand 4+4/4-4/100+4/400=4+1-0+0=5. The terms /100 and /400 get too much weight in your calculation such that the 2000 can not be reached.

@Howard The two equations are mathematically identical. With y=4, 497*4/400=1988/400=4.97 (which is rounded down to 4), while with the original equation, 4+4/4+4/100+4/400=4+1-0.04+0.01=4.97 (which is rounded down to 4). The problem is that because PHP is weakly typed, the integer is converted immediately to a double when necessary, and only converted back to an integer when performing the modulo.

@rintaun that's what I meant. The original equation only deals with integer divisions and in that case they are not equivalent (see my example). You have to split the term into separate ones and make sure that they are integer divisons.

@Howard Ah, I see now. That really cramps my style. :p

Javascript, 126 123 characters
Using Sakamoto's algorithm with 0 = Sunday:
prompt().replace(/(....)(..)(..)/,function(_,y,m,d){y-=m<3;alert((+d+y-~(y/4)+~(y/100)-~(y/400)+ +".621462403513"[+m])%7)})

I suspect the divisions can be collapsed, but right now I'm not seeing it.
Edit: Improved the divisions (no need to ~~ when you can just ~).

C - 129
main(y,m,d,s)
{
    scanf("%04d%02d%02d",&y,&m,&d);
    y-=s=86400;
    d+=y+"-addgbegcfadf"[m];
    m>2?y++:0;
    putchar(48+(d+y/4-y/100+y/400+s+s)%7);
}

This abuses how division rounds toward zero, at least on my system (Linux x86).
The magic constant, 86400, serves two purposes:

Subtract from the year to make it negative, without affecting the day of the week.  This makes it so the divisions will round up instead of down.
Shift the day number so Monday will be 0.

It also happens to be the number of seconds in a day.

Use y+=m>2; instead of m>2?y++:0; and shave a few bytes off.

Python 2, 83 116 113 109 bytes
Implements Sakamoto's algorithm. Golfing suggestions welcome. Try it online!
Edit: I should have fixed this ages ago. -6 bytes from Jonathan Allan's suggestions +2 bytes to actually fixing the code.
def w(s):m=int(s[4:6]);y,d=int(s[:4])-(m<3),int(s[6:]);return(y+y/4-y/100+y/400+int('032503514624'[m-1])+d)%7

Input should be a single string.

int('032503514624'[m-1]) saves 6

C (126 bytes)
main(y,m,d){scanf("%4d%2d%2d",&y,&m,&d);y%=400;putchar(((5*y+3)/4-y/100+"-KGGJLHJFIKGI"[m]+(!(y%4)&&m>2&&y%100||!y)+d)%7+48);}

Try it online!

Perl -- 110 bytes
Here is a solution to be run with perl -p source.pl OR perl -pe 'here-is-code'.
s/((..)(..))(..)(..)/(1+3*$1+$2-2*($1%4+$2%4)-(2<$4?$4+(1&$4&&4-(8&$4)):(2^$4)+(!($3%4)-!-$3+!($2%4)))+$5)%7/e

Simply copy-paste the test cases to stdin.
This seems to be the only code without variables, string constants and divisions.


text:
Tips For Golfing In Groovy
As I have seen many questions asking tips for golfing in their interested language, I decided to ask for my favorite language: Groovy. People can give some tips and tricks that will be used in golfing with Groovy.

Well this isn't very popular, is it :-(

@Alison : I feel Bad, as there is no Golf tip for Groovy in this site :(

Do you have any tips to start us off?

I'm new to this whole golfing thing, this is what I got so far:
Use Closures not functions:

def a(b){print b}

is longer than

a={print it}

You can use a negative index in arrays and lists as an alias for size()-

c = "abc"
d = ["a", "b", "c"]

assert c[c.size()-1] == c[-1]
assert c[c.size()-2] == c[-2]
assert d[d.size()-1] == d[-1]
assert d.last() == d[-1]

The spread operator is a shortcut for collect:
assert d*.size() == d.collect{it.size()}
For sorting use the spaceship operator:
e = [54,5,12]
assert e.sort{a,b->a<=>b}==e.sort{a,b->a<b?-1:+1}
assert e.sort{a,b->a<=>b}==e.sort{a,b->if (a>b) {return(-1)} else {return(+1)}}

Edit Conversions:
assert "123" as int == "123".toInteger()

if on something listish the *.X spread operator can often be written as .X

As Groovy is a somewhat verbose language, you could use Groovys MOP to shorten method calls.
The following snippet for example would pay off after the fourth usage:
''.metaClass.r<<{i->(int)Math.random()*i}
''.r(12)

Tip golfing edit:
0.metaClass.r<<{i->(int)Math.random()*i}
0.r(12)

Or, you know:
r={(int)Math.random()*it}
r(12)

grep is short and works on several problems
get the chars of a string as a list with spaces and without leading elements: 'ABC XYZ'.grep() returns [A, B, C,  , X, Y, Z]
grep with regexp is shorther than converting to upper case, if required: it.grep(~/(?i)$c/) instead of it.toUpperCase().grep(c)

'ABC XYZ'as Set is one character shorter and works in most of the same places

Getting An Array from a List of Objects
If you have a list of objects like:
def users = [[user:'A',id:1],[user:'B',id:2],[user:'C',id:3]]

You can generate an ArrayList with a certain property using:
def userIds = users*.id // [1, 2, 3] no explicit loops!

BONUS: Groovy... on Rails!
Well, in Grails Framework we must get many values from a select with multiple attribute. You can use loops, flatten and other programming more typical structures, but you can save some lines. If you have a select like:
<select id="users" multiple="true" name="users">
    <option value="193">User A</option>
    <option value="378">User B</option>
    <option value="377">User C</option>
</select><%-- No Grails tags for now --%>

Then, in your controller you can simple write:
def aListOfUsers = User.getAll(params.list('userIds'))

Would this question accept Grails golfing tips? I confess I'm afraid of downvote snipers...

Don't be afraid, PCG is full of extremely nice people :)


text:
Shortest code for Seven-Eleven
The Seven-Eleven problem is find 4 positive numbers (with two decimal digits, A.BC) such that their sum is equal to their product and is equal to 7.11.
a + b + c + d = a * b * c * d = 7.11
0 < a <= b <= c <= d

Write the shortest program to compute all non-decreasing quadruples. Precomputing the values is not allowed.

Since both addition and multiplication are commutative, the last constraint of "0 < a <= b <= c <= d" is somewhat redundant; one simply has to solve for any a, b, c, and d that satisfies the other constraints and then sort the values in ascending order.

At first sight, two negative numbers would lead to an positive product as well, and could lead to a sum which is a solution. So (a,b,c,d) >= 0 would be fine. (!= 0 follows for some other reason from the question).

@user unknown: I need to follow up on how to consider accepted solution since I don't want to accept only CodeGolf scripts.

Ruby, 105 characters
Unfortunately I didn't get it below the 100 mark. It just brute forces all possible tuples and checks afterwards. Nevertheless it still finishes in finite time.
(1..m=711).map{|a|(a..m).map{|b|(b..m).map{|c|d=m-a-b-c;p [a/u=1e2,b/u,c/u,d/u]if d>=c&&a*b*c*d==m*1e6}}}

The formatted version looks like this:
(1..m=711).map{ |a|
  (a..m).map{ |b|
    (b..m).map{ |c|
      d=m-a-b-c
      p [a/u=1e2,b/u,c/u,d/u] if d>=c && a*b*c*d==m*1e6
    }
  }
}

Haskell - 121
(extra newline added for readability)
h=711
main=mapM(print.map((/100).realToFrac))
     [[a,b,c,d]|a<-[1..h],b<-[a..h],c<-[b..h],let d=h-a-b-c,c<=d,a*b*c*d==h*10^6]

This meets the requirements by only working with numbers with two decimal digits.  It computes the solution (there's only one of them) using integer arithmetic, scaled up by 100.  Floating-point arithmetic is too untrustworthy for this.

Python (146 152 characters)
Here's a "real" answer, if my Wolfram Alpha one doesn't please:
n=711
r=lambda v:range(v,n)
print [[a*0.01,b*0.01,c*0.01,d*0.01]for a in r(1)for b in r(a)for c in r(b)for d in r(c)if a+b+c+d==n and a*b*c*d==n]

It's very, very inefficient, but it works.

It looks like I've used basically the same method as Joey, just in a more verbose language :-)

My solution (Haskell) was too slow until I computed d rather than brute-forcing it.

Also, I think you can replace def r(v):... with r=lambda v:range(v,n).

C (229 characters)
Sacrificial offering:
#include<stdio.h>
int main(void){int a,b,c,d;for(a=1;a<=711/4;++a)for(b=a;b<=711/4;++b)for(c=b;c<=711/4;++c){d=711-(a+b+c);if(d<c)break;if(a*b*c*d==711000000)printf("a=%.2f,b=%.2f,c=%.2f,d=%.2f\n",a/100.,b/100.,c/100.,d/100.);}}

Re-formatted for readability:
#include <stdio.h>

int main()
{
    int a, b, c, d;

    for (a = 1; a <= 711 / 4; ++a)
        for (b = a; b <= 711 / 4; ++b)
            for (c = b; c <= 711 / 4; ++c)
            {
                d = 711 - (a + b + c);
                if (d < c) break;
                if (a * b * c * d == 711000000)
                    printf("a = %.2f, b = %.2f, c = %.2f, d = %.2f\n", a / 100., b / 100., c / 100., d / 100.);
            }
}

You can make it shorter by abusing implicitly-declared arguments, rather than explicitly declaring variables: main(a,b,c,d){ instead of int main(void){int a,b,c,d;

@Joey: thanks, I could do that but I think I'd feel dirty afterwards. ;-)

If you feel dirty doing that sort of thing, then you will have some critical limitations in code golf.

@Peter: good point - I may have to work on this

b can run to 711/3, c to 711/2. (a,b,c) can then be precomputed (see my scala-solution). By optimising for speed, one would let b run to (711-a)/3, c to (711-a-b)/2 but not for golfing.

GNU Prolog REPL, 57 bytes
(The REPL input ends with two newlines, which are included in the byte count.)

A+B+C+D#=711,A*B*C*D#=711000000,fd_labeling([A,B,C,D]).

The first line prints the first solution (very quickly, in fact; fd_labeling often needs tuning to run quickly, but it didn't in this case). GNU Prolog's generates the solution which has the arguments in sorted order first. In this case, only one solution is in sorted order, so we can enter a newline at the "more solutions?" prompt to not generate the remaining solutions; arguably this is hardcoding the number of solutions, but as required by the question, it doesn't hardcode the values in the solution. Uses fixed-point arithmetic (so the numbers are printed without a decimal point), because GNU Prolog's built-in equation solver handles only integers.
This is just a case of finding a language with a language feature that solves the problem almost directly. Mathematica might be the obvious choice, but GNU Prolog has a constraint solver too. If only the REPL ran fd_labeling automatically! (Come to think of it, maybe I should write a language that uses GNU Prolog's constraint solver behind the scenes and has a terser syntax; it'd be useful in this sort of challenge when it comes up in the future, and possibly even for general use. Oh, and that's designed to solve problems using normal arithmetic operations rather than INTERCAL's.)

This is a fairly old challenge, so I was potentially concerned about language-newer-than-the-challenge, but it works using a version of GNU Prolog from 2007.

K, 67 chars
Brute force, requires about ten seconds.
For information about K (unique mix of APL, functional, and Database programming language). see kdb.com
{if[(_711e6)=*/r:x,711-+/x;R::r]}'?{|':1+a\:x}'!*/a:3#_711%4;R%100

generates the answer
1.2 1.25 1.5 3.16

Explanation:

Algorithm:

Generates range 1..711/4 for each of three values
calculates the fourth as 711-sum of the other three
Filter to guarantee ascending order of the values
Calculates product of values and compare with 711000000

About syntax

Many predefined functions are one-letter operators. There are diad (x OP y) and monad (OP x) variants. Evaluation left to right, no precendence, ';' as sentence separator, 'var : value' to assign. {..} defines an anonimous function
diads: % is divide, x:y computes list fo digits of y in x-base, x#y takes, | is max
monads: _ is floor, f/ reduces list with funcion f (ej. */ calculates product, +/ calculates sumation), !x generate values 0..x-1, ?x return unique values of list x, f': applies f to each pair of the argument list (|':x to guarantee non.decreasing values)
func'args applies the function over each of the args

Scala  168  139
def h(i:Int)=i/100.0
val x=711
for(a<-1 to x;
b<-a to x;
c<-b to x;
d=x-a-b-c
if(d>c&&h(a)*h(b)*h(c)*h(d)==7.11))yield(h(a),h(b),h(c),h(d))

Mathematica
Solve[
    a + b + c + d == a * b * c * d / 10^6 == 711
        && 0 < a <= b <= c <= d,
    {a, b, c, d},
    Integers
]

Basically, solve it as an integer Diophantine equation. The advantage is that this avoids possible floating-point error.
On my computer, Mathematica runs out of memory, but it might work in principle...
It might be possible to run this on Wolfram Alpha, but I'm not familiar enough with its syntax.
In Mathematica, this is 58 characters + 1 fraction line + 1 exponentiation box.


text:
Jumping and Running
Matthew likes solving puzzles. Whenever he manages to solve one he skips
around happily. Recently he really needs to do this as a meteor shower
has opened craters and holes in the ground in which he wouldn't like to
fall.
You are given a part of landscape that Matthew wants to cross, hopefully
arriving healthy at the end. The ground is given in meters, with each
meter being either normal ground or a hole. When he is running he manages
to cross one meter per step; the alternative is jumping which crosses four
meters per step. Matthew starts at the far left on the first ground meter
and wants to get to the last one (not beyond it, though – just imagine an
endless hole beyond the last meter given in the landscape).
Input
Input is given as a single line on standard input, terminated by a line break. The line consists of
either dashes (-) or underscores (_), representing a ground or hole
meter, respectively. A sample input could be:
----__--___---

The given landscape is at least one and at most 30 meters long and always
starts with ground.
Output
Output is given on standard output and represents a series of movement
commands to Matthew, either run (R) or jump (J). As noted above, a
run command causes Matthew to run one meter while jumping carries him
forward exactly four meters. For the example given above the following
movement is possible:
RRJRJRR

which looks approximately as follows:

If there is no safe path through the landscape, then a single exclamation
mark (!) should be printed.
Sample inputs
--------
----__--___---
-_______
-_-_-_-_-_-
-

Sample outputs
JRRR
RRJRJRR
!
!

(the last output is blank as no movement is necessary, but I guess,
Markdown cannot parse this)
Note
Only a single possible path is necessary, so the program output does not
have to conform exactly to the sample outputs. As long as a solution is
given if it exists and every movement command moves to ground and the last
meter is reached eventually, the output is valid.
Additional output on standard error is ignored.
Winning condition
Shortest code wins, as is customary in golf. In case of a tie, the earlier
solution wins.
Test cases
There are two tests scripts, containing identical test cases:

bash (Thanks to Ventero)
PowerShell

Invocation is in both cases: <test script> <my program> [arguments], e.g. ./test ruby jumprun.rb or ./test.ps1 ./jumprun.exe.
Another note
This task was part of a golf contest held at my university during
2011-W24. The scores and languages of our contestants were as follows:

104 – Haskell
131 – Haskell
154 – C
170 – C
275 – VB.NET
286 – Common Lisp

Our own solutions were

  92 – Ruby
124 – PowerShell

@Joey I get an error trying to run test.sh with ./test.sh perl jump.pl -- ./test.sh: line 42: syntax error near unexpected token 'done', under bash 3.2.48

@Joey I cleared my cache, redownloaded and it works great now. Thanks.

Looking at the solutions, it was apparently really too trivial. Apologies.

I presume backwards running/jumping isn't allowed?  If it were, it would make landscapes like ---- solvable.

Keith: a bit too late now to change the task, I guess.

Perl, 53 characters
s/-...(?=(-|-...)*-$)/J/g;y/-/R/;/_/?$_="!":s/.$//

Run this with perl -p jumpnrun.pl. I've counted 3 characters for the -p option, which is the length difference between perl jumpnrun.pl and perl -p jumpnrun.pl.
I'm not that fluent in Perl, so I'm pretty sure this can be shortened further. This uses a regexp similar to Howard's solution.

Ruby, 93 90 79 70 characters
I thought a regex solution would be quite fine and compact (let the matcher do the work). Unfortunately all the edge-cases and special treatments made this one such long - at least I didn't touch the 100 ;-).
puts gets.gsub(/-...(?=(-|-...)*-$)/,?J).tr(?-,?R)=~/^([JR]*)R$/?$1:?!

It passes all testcases of the provided script.
Saved several characters in comparison to the previous script (now a single call to gsub is sufficient).
Edit 1: Changed puts z!=?-??!:'' to z!=?-&&$><<?! after the test script allowed no output for test case 1.
Edit 2: The previous version was
z=gets.chop
z.chars{z.sub!(/^(-|-...)((-|-...)*-)$/){$><<($1==?-??R:?J);$2}}
z!=?-&&$><<?!

My original idea was to replace the characters by using a look-behind and look-ahead strategy like this: The pattern was ^(?<=[RJ]*)(-|-...)(?=(-|-...)*-$) and I then would replace '-' with 'R' and otherwise with 'J'. Unfortunately Ruby does not allow variable-length look-behind and another capturing group for the first part made the code even longer.
So then I did the iterative approach: if I can start with a step or jump ^(-|-...) followed by series of other steps or jumps until the last platform (-|-...)*-$ then I print the corresponding letter, remove the first one/four characters and start over again. On can even tune the RJ vs. JR priority by switching the choices inside the expression (currently it prefers RJ).
Edit 3:
Splitting the single subtitution
puts (z=gets.chop.gsub(/(-...|-)(?=(-|-...)*-$)/){$1==?-??R:?J})=~/_/??!:z.chop

into two
puts (z=gets.chop.gsub(/-...(?=(-|-...)*-$)/,?J).tr(?-,?R))=~/_/??!:z.chop

gave another few chars. Finally I managed to get rid of this end-of-line issue but at a cost: the fail-detection costs some more characters.

You can save 3 characters by changing the last line to z!=?-&&$><<?!. Other than that, great solution, +1!

@Ventero I had that one put the first test failed because of no output at all for "-" ;-)

Hm, it appears that my PowerShell script has a tiny bug. It apparently accepts no input for Test 2 and won't accept it for Test 1. That's ... weird, to say the least. I'll try to fix.

Ok, the test script should be fixed and no longer reject an actually empty result for test 1. Ok, now it should be fixed.

@Joey Danke. Nun sind es 90 ;-)

Perl - 71 60
$_=<>;y/-/R/;s/R...(?=(R(...)?)*R$)/J/g;print/_/?"!":s/.$//r

Now passes all of the testcases. :) Turns out I was removing the last character too soon... and half of my original regex was entirely redundant.

    $_=$ARGV[0];y/-/R/;s/(R...(?=R))(R*(?=R))/J$2/g;chop;print//?"!":$,$/
Yet another regex solution, passes the 5 testcases in the post.
Could be shortened by running as a one-liner with -E and say instead of print, but then perl tries to interpret the input as a switch... (Unrecognized switch: -_-_-_-_-_-)

The question states that input is given on stdin. When changing your solution to read from stdin instead of using $ARGV, it still fails 108 testcases from the test scripts.

@Ventero Oh oops... I think I know why it does that, I'll put up a fix soon... that's what I get for not going through all of the testcases... >_>

Well, the intention of the scripts was to allow people to easily check for validity and adherance to the specification :-)

@Joey The problem was that I somehow managed to confuse 'test script' with 'reference implementation' until Ventero posted his comment :) ... script is now almost fixed now though, currently only fails 20, all false negatives

Haskell, 90 characters:
My first solution -- long, but works in linear time, using dynamic programming. :) 150 characters:
x!y="!"
q '-'=max
q c=(!)
s i=r where r=zipWith3 q i(0&'R')$3&'J';n&c="":replicate n"!"++map(c#)r
c#"!"="!"
c#s=c:s
main=interact$reverse.last.s.init

The second solution -- much slower (exponential time), but much shorter: 90 characters
s"-\n"=""
s('-':t)=max('R'#s t)$'J'#s(drop 3 t)
s _="!"
c#"!"="!"
c#s=c:s
main=interact s

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


text:
Compute the difference between two days.
Another date-manipulating problem :P
Task

Write a program or a function that calculates the difference between two dates given by a user.

Input & Output
Similar to the previous one, inputs are two YYYYMMDDs, separated by a space , a comma ,, or a minus sign -.
Example of input values:
20100101-20010911
20110620-20121223
19000101 20101010
33330101,19960229
00010101 99991231

Output is an integer, which is difference between two dates, in days.
For example, input 20110101-20100101 yields 365, and 33320229 17000101 yields 596124.
You may test results at here at here. (See rintaun's comments below.) If two dates are same, the program should returns 0, if the date is valid (see Score).
Restriction
Of course, you must not use any kinds of function/class/... which are related to timestamp or date, and you should use Gregorian calender.
Score
If your code doesn't keep the restriction, then score = -∞.
Default bonus is 1.

If your code works regardless of order of inputs (for example, 20100101,20110101 returns 365 or -365), bonus+=1.
If your code can handle year 0, bonus+=0.5.
If your code recognizes invalid month(between 1~12)/date(between 1~31), like 20109901 or 34720132, and prints E (& terminates the program or returns something like 0), bonus+=1.
Regardless of above rule, if your code recognizes invalid dates, like 20100230, 20100229, or 20111131, and prints E (& terminates the program or returns something like 0), bonus+=1.
Regardless of above two rules, if your code recognizes invalid input string, like 20100101|20100202 or 2010010120100202, and prints E (& terminates the program or returns something like 0), bonus+=1.

score = floor(-4.2*code.length/bonus). Code with highest score wins. If two top codes have same score, then codes with highest bonus wins. If two top codes have both same score and bonus, then codes with highest votes wins.
(Due: When there's more than 5 codes which has more than (or equal) +1 votes.)

Is 20030229 considered an invalid date by the third bonus?

@rintaun Yes. It's invalid, unlike 20040229. :P

Does WolframAlpha actually return the correct result? I'm getting conflicting answers from it and timeanddate.com. My program, which I believe is working correctly (at least in that instance :P), agrees with the latter.

@rintaun I think Wolfram|Alpha was wrong, since 365*4 + 2 + 2 = 1464. Thanks for the information!

It should be noted that even with timeanddate.com, there are some problems: it only accepts years 1-3999, and it auto-adjusts for the 11-day discrepancy between the Julian and Gregorian calendars for dates prior to Sept. 3, 1752 (so 17520903 through 17520914 are not valid dates). Keep this in mind when testing results.

Mathematica 8 can call wolfram alpha from a notebook... Is this acceptable?

Can you clarify what you mean by "handle year 0" under the Gregorian calendar? Are we supposed to treat it as 1 BC?

Also, are we supposed to account for the jump between Julian and Gregorian? (i.e. subtract 11 days) Or can we ignore it? This isn't clear in the question.

@migimaru Handle year 0 as leap year (like year 2000). And you should ignore the jump before Julian and Gregorian, since only the Gregorian calender is used (...and you should use Gregorian calender.)

@JiminP Okay, though it's confusing because you use the example 33320229 17000101 = 596124. That's only true if the jump is accounted for, otherwise it should be 596135 when only using the Gregorian calendar.

@migimaru ...I think I need a good date calculator...

It sounds like you intend people to calculate using the proleptic gregorian calendar.

You can use perl6 -e 'say [-] @*ARGS.map: {Date.new(|+«%(m/$<year>=(\d**4)$<month>=(\d**2)$<day>=(\d**2)/))}' 33320229 17000101 (596134) to test ( Perl 6 uses the proleptic gregorian calendar. )

Perl 5.14, score = -162
-163 -181 -196 -214 -167 -213 -234

code.length = 211: 208 source characters + 3 for running perl with the -p option
bonus = 5.5: default, order, year 0, never-valid month/day, invalid date, wholly-invalid input

Code
$_=eval(join'-',map{($y,$m,$d)=/(....)(..)(..)/;die"E\n"if!($m*$d)||$m>12||$d>30+($m&1^$m>7)-($m==2)*(2-!($y=~s/00$//r%4));$y-=($m<3)-400;$d+int(($m+9)%12*30.6+.4)+int(365.2425*$y)}/^(\d{8})[ ,-](\d{8})$/)//E

Calculates a modified Julian day number for each date (ignoring the epoch-related adjustments to save code length) and subtracts the two. (ref. "Julian Day" at Wikipedia).

requires perl 5.14+ for the /r option on the substitutions
month-length calculation to get the invalid date bonus: the 30+($m&1^$m>7) part gives the length of any month but February; the rest adjusts for February in an ordinary or leap year

Assumptions

"use Gregorian calendar" means the proleptic Gregorian calendar for dates before whichever Julian to Gregorian transition we're using.  That is, don't subtract 11 days for intervals that cross, for example, the 3 Sep 1752 - 14 Sep 1752 British transition.
"handle year 0" means, for example, 00000101-00010101 should give 366, as 0 is an integral multiple of 400, and so year 0 is a leap year.

With the changes you made, it seems like your program now accepts invalid months and days, like 20111300-20119999 returns 2717.

@migimaru: I have indeed optimized out the correctness. Darn. I'll edit and maybe come back to it.

PHP, Score: -539.1

706 characters
All bonus items; bonus = 5.5

Code
<?php $a='(\d{4})(0[0-9]|1[0-2])([0-2][0-9]|3[01])';@$p=preg_match;if(!$p('/^(\d{8})[- ,](\d{8})$/',fgets(STDIN),$z))@die(E);unset($z[0]);sort($z);foreach($z AS$x){if(!$p('/(\d{4})(0[0-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])/',$x,$w))die(E);$n[]=$w;}$m=array(31,28,31,30,31,30,31,31,30,31,30,31);$r=0;$b=$n[0][1];$c=$n[0][2];$d=$n[0][3];$e=$n[1][1];$f=$n[1][2];$g=$n[1][3];@$t=str_pad;if((($b.$e==229)&&(!(!($b%4)+!($b%100)-!($b%400))))||($c>12))die(E);for($z=$b.$c.$d;;$s=$d,$r++){if($z==$e.$f.$g)break;if($z>$e.$f.$g)@die(E);if(@$s==$d)$d++;if((($c!=2)&&($d>$m[$c-1]))||(($c==2)&&($d>($m[$c-1]+!($b%4)-!($b%100)+!($b%400))))){$c++;$d=1;}if($c>12){$b++;$c=1;}$z=$b.$t($c,2,0,0).$t($d,2,0,0);}echo($r>0)?--$r:0;

Ungolfed
<?php
$a='(\d{4})(0[0-9]|1[0-2])([0-2][0-9]|3[01])';
@$p=preg_match;
if(!$p('/^(\d{8})[- ,](\d{8})$/',fgets(STDIN),$z)) @die(E);
unset($z[0]);
sort($z);
foreach($z AS $x)
{
        if (!$p('/(\d{4})(0[0-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])/',$x,$w)) die(E);
        $n[]=$w;
}
$m=array(31,28,31,30,31,30,31,31,30,31,30,31);
$r=0;
$b=$n[0][1];
$c=$n[0][2];
$d=$n[0][3];
$e=$n[1][1];
$f=$n[1][2];
$g=$n[1][3];
@$t=str_pad;
if ((($b.$e==229)&&(!(!($b%4)+!($b%100)-!($b%400))))||($c>12)) die(E);
for ($z=$b.$c.$d;;$s=$d,$r++)
{
        if ($z==$e.$f.$g)break;
        if ($z>$e.$f.$g)@die(E);
        if (@$s==$d)$d++;
        if ((($c!=2)&&($d>$m[$c-1]))||(($c==2)&&($d>($m[$c-1]+!($b%4)-!($b%100)+!($b%400)))))
        {
                $c++;
                $d=1;
        }
        if ($c>12)
        {
                $b++;
                $c=1;
        }
        $z=$b.$t($c,2,0,0).$t($d,2,0,0);
}
echo($r>0)?--$r:0;

Note
Calculates the number of days by iterating through each valid date between the two provided. It's pretty slow on larger ranges. I'm sure this isn't the best way to solve this, but I got impatient, and this is what I ended up with. :)
Also, I know the "ungolfed" code still isn't very readable, but rewriting it completely would require too much effort.

Python, Score: -478

characters: 455
bonus: reverse dates, invalid day/month, invalid date

solution:
import re
a=re.split('[-, ]',raw_input())
def c(x):return x[0]
def f(x,y=3):return(1if x%400==0 or x%100!=0and x%4==0 else 0)if y>2 else 0
t=[31,28,31,30,31,30,31,31,30,31,30,31]
[q,w,e],[i,o,p]=sorted([map(int,[a[x][:4],a[x][4:6],a[x][6:]])for x in[0,1]],key=c)
print sum(map(f,range(q,i)))+(i-q)*365+p+sum(t[:o-1])-e-sum(t[:w-1])+f(i,o)-f(q,w)if 0<w<13and 0<e<32and 0<o<13and 0<p<32and(e<=t[w-1]or(f(q)and e==29))and(p<=t[o-1]or(f(i)and p==29))else 'E'

I don't have "ungolfed" version as this is how I wrote it. I didn't test it properly so if you find a bug - please comment.
edit: hopefully fixed a bug pointed out in a comments and added unpacking in form of [a,b],[c,d]=[[1,2],[3,4]

Sorry, but when I tested with Python 2.7 Shell, invalid inputs like '20000001,20010101' doesn't print E. (FYI, 0>-1>12, 0>6>12, 0>13>12 returns False.)

Thanks. I'm quite new to python. Writing this script I learned that python does this x<y<z comparison or there is a x if y else z. Tried to fix it.

@rpInt: for golfing, there is also the [x,z][y] which is shorter than x if y else z, though it doesn't always work since unlike the if-expression it's not lazy.

Ruby 1.9, Score: -175 -186 -191 -199

Code length: 229 243 250 260 characters
Bonus: 5.5 (default, order, year 0, invalid month/day, invalid date, invalid input)

The code accepts input through stdin.
h=->n{n/4-n/100+n/400+1}
u,v=gets.split(/[ ,-]/).map{|s|s=~/^\d{8}$/?(d,e,f=[s[0,4],s[4,2],s[6,2]].map &:to_i;x=[0,y=31,28+h[d]-z=h[d-1]]+[y,30,y,30,y]*2
(!x[e]||e*f<1||f>x[e])?0:d*365+z+eval(x[0,e]*?+)+f):0}
puts (v*u>0)?u-v :?E

Notes:

h returns the number of leap years up until that year (including year 0 for the bonus).
The regex handles the invalid input bonus.
The (!x[e]||e*f<1||f>x[e]) condition handles the invalid month/day/date bonuses.
The result is displayed as the first date minus the second date, so if the second date is later it will output as a negative number.
Does not adjust for the change between Julian and Gregorian calendars, so 33320229 17000101 results in 596134.

Thanks for error-checking my solution and for pushing me to keep improving. I particularly like your February-length calculation here.

@DCharness Thanks for pushing me as well. I realized there was plenty of room for improvement in my original submission.

PHP, score: -516
chars : 685 676
bonus : 5.5
<? $z='/((\d{1,4})(\d\d)(\d\d))[- ,]((\d{1,4})(\d\d)(\d\d))/';if(!preg_match($z,$argv[1],$m))die('E');$s=1;if($m[1]>$m[5]){if(!preg_match($z,"$m[5] $m[1]",$m))die('E');$s=-1;}$b=array(31,28,31,30,31,30,31,31,30,31,30,31);list($x,$v,$c,$d,$e,$w,$f,$g,$h)=$m;if($d>12||1>$d||$g>12||1>$g||1>$e||1>$h||($e>$b[$d-1]&&!($d==2&&$e<30&&$c%4==0))||($h>$b[$g-1]&&!($g==2&&$h<30&&$f%4==0)))die('E');$z='array_slice';$y='array_sum';$x=$d!=$g||$e>$h;$r=$x?$b[$d-1]+$h-$e:$h-$e;$d+=$x;if($d>12){$c++;$d=1;}$r+=$d>$g?$y($z($b,$d-1,13-$d))+$y($z($b,0,$g-1)):($d!=$g?$y($z($b,$d-1,$g-$d)):0);$r+=($f-$c-($d>$g))*365;for($i=$c;$i<=$f;$i++)if($i%4==0&&$i.'0229'>$v&&$i.'0229'<$w)$r++;echo $s*$r;

PHP code needs the <? at the beginning to run, otherwise it just prints out the code.

PowerShell, 294 bytes, ~-353 score, +3.5 bonus
function J($s){if($s.length-ne8){"E";exit};iex ('$Y_0,4));$M_4,2));$D_6,2))'-replace'_','=[int]($s.substring(');$B=($M-14)/12;if($m-notin1..12){'E';exit};$A=$Y+4800;($J=1461*($A+$B)/4+367*($M-2-12*$B)/12-(3*(($A+$B+100)/100))/4+$D-32075)};[math]::truncate((J("$($args[0])"))-(J("$($args[1])")))

Try it online!
It uses Julian Date to calculate difference between to YYYYMMDD dates.
Explanation

At first, to avoid redundant code, it's better to use a function. So we declare a function named J which calculates the julian date of a given date in YYYYMMDD format, and takes the parameter as $s.

Next, we need to check for invalid string. If the given string length is not 8 (YYYYMMDD length is 8), then output E and exit.

Parse the string. We used substrings for that. First 4 characters are the year ($Y), next 2 are the month ($M), and next 2 are the day ($D). To get a substring, we use .NET .substring() method for that, and cast it to type [int]. But its a huge part of code, and to golf it we replace =[int]($s.substring( with _ and build a string $Y_0,4));$M_4,2));$D_6,2)) and while in the code replace _ with =[int]($s.substring( again and evaluate the expression using iex (Which is an alias of Invoke-Expression).

Another check for month validity. 1..12 is the array of numbers between 1 to 12, if $M (month number) is not in the 1..12 array, we output E and exit.

Then the main logic goes. We calculate the Julian date. I found the algorithm here

End the function.

We compute date difference after that. $args is an automatic array in Powershell which contains the parameters provided to the script (Not the function). We cast 0 and 1 index to string ($() operator is sub-expression operator, which evaluates a string as code inside a double-quoted string, and then surround double quotes to cast to string), pass each to J function and subtract the returned integer Julian dates.

At last, truncate the result using .NET [math]::truncate() method.

Bonus

Initial bonus, so bonus +1

The code will work if the first date is smaller than second one (i.e. 20100101 20110101), so bonus +1

Cannot handle year 0, so bonus +0

Can handle invalid month, but not invalid Day, so bonus +0.5

Cannot determine invalid dates, so bonus +0

Can handle invalid strings in parameters, so bonus +1

Total: 1+1+0+0.5+0+1=3.5
Total score

Code length: 294 bytes
Total bonus: +3.5

$$
floor(-4.2*294/3.5) = -353
$$