text:
Tips for golfing in Scala
What general tips do you have for golfing in Scala? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala (e.g. "remove comments" is not an answer). Please post one tip per answer.
(This is a shameless copy of ... in Python)

disclaimer: parts of this answers are generalizations of other answers found here.
Use lambdas without specifying their argument types
It's allowed to submit something like this: a=>a.size instead of (a:String)=>a.size.
Use ascii-symbols as identifiers.
These include !%&/?+*~'-^<>|. Because they arent't letters, they get parsed separately when they're next to letters.
Examples:
a=>b       //ok
%=>%        //error, parsed as one token
% => %      //ok
val% =3     //ok
&contains+  //ok
if(x)&else* //ok

Use Set instead of contains
if (Seq(1,2,3,'A')contains x)... //wrong
if (Set(1,2,3,'A')(x))...         //right

This is possible because Set[A] extends (A => Boolean).
Use a curried function when you need two arguments.
(a,b)=>... //wrong
a=>b=>...  //right

Use the _-syntax when possible
The rules for this are somewhat obscure, you have to play a little bit around sometimes to find the shortest way.
a=>a.map(b=>b.size)) //wrong
a=>a.map(_.size)     //better
_.map(_.size)        //right

Use partial application
a=>a+1 //wrong
_+1    //better, see above
1+     //right; this treats the method + of 1 as a function

Use ""+ instead of toString
a=>a.toString //wrong
a=>a+""       //right

Use strings as sequences
"" is sometimes the shortest way to create an empty sequence if you don't care about the actual type
Use BigInt to convert numbers to and from strings
The shortest way to convert a number to a string in a base other than base 10 is through BigInt's toString(base: Int)method
Integer.toString(n,b) //wrong
BigInt(n)toString b   //right

If you want to convert a string to a number, use BigInt.apply(s: String, base: Int)
Integer.parseInt(n,b) //wrong
BigInt(n,b)           //right

Be aware that this returns a BigInt, which is useable like a number most of the times, but can't be used as an index for a sequence, for example.
Use Seq to create sequences
a::b::Nil   //wrong
List(...)   //also wrong
Vector(...) //even more wrong
Seq(...)    //right
Array(...)  //also wrong, except if you need a mutable sequence

Use Strings for Seqences of chars:
Seq('a','z') //wrong
"az"         //right

Make use of Stream for infinite sequences
Some challenges ask for the n-th element of an infinite sequence. Stream is the perfect candidate for this. Remember that Stream[A] extends (Int => A), that is, a stream is a function from an index to the element at that index.
Stream.iterate(start)(x=>calculateNextElement(x))

Use symbolic operators instead of their wordy counterparts
:\ and :/ instead of foldRight and foldLeft
a.foldLeft(z)(f) //wrong
(z/:a)(f)        //right
a.foldRight(z)(f) //wrong
(a:\z)(f)         //right

hashCode -> ##
throw new Error() -> ???
Use -> for creating and unpacking tuples
(a,b)  //wrong
a->b   //right

Use & and | instead of && and ||
They work the same for booleans, but will always evaluate both operands
Alias long method as functions
def r(x:Double)=math.sqrt(x) //wrong
var r=math.sqrt _            //right; r is of type (Double=>Double)

Know the functions in the standard library
This especially applies to the methods of collections.
Very useful methods are:
map
flatMap
filter
:/ and :\ (folds)
scanLeft and scanRight
sliding
grouped (only for iterators)
inits
headOption
drop and take
collect
find
zip
zipWithIndex3
distinct and/or toSet
startsWith

The shortest way of repeating something is with Seq.fill.
1 to 10 map(_=>println("hi!")) // Wrong!
for(i<-1 to 10)println("hi!") // Wrong!
Seq.fill(10)(println("hi!")) // Right!

for(i<-1to 10)println("hi!") has the same length

suspicious identifier: ?
You can use ? as identifier:
val l=List(1,2,3)
val? =List(1,2,3)

Here it doesn't save you anything, because you can't stick it to the equal sign:
val ?=List(1,2,3) // illegal

But later on, it often saves one character, since you don't need a delimiter:
print(?size)  // l.size needs a dot
def a(? :Int*)=(?,?tail).zipped.map(_-_)

However, it is often tricky to use:
       print(?size)
3
       print(?size-5)
<console>:12: error: Int does not take parameters
       print(?size-5)
              ^

There are also other identifiers, such as |, >, and pretty much any symbol that's not a word character (other than parentheses, commas, dots, semicolons, equal signs, square brackets, curly brackets...)

Collections
The first choice for a random collection is often List. In many cases you can replace it with Seq, which saves one character instantan. :)
Instead of
val l=List(1,2,3)
val s=Seq(1,2,3)

and, while s.head and s.tail is more elegant in usual code, s(0) is again one character shorter than s.head.
Even shorter in some cases - depending on needed functionality is a tuple:
val s=Seq(1,2,3)
val t=(1,2,3)

saving 3 characters immediately, and for accessing:
s(0)
t._1

it is the same for direct index access. But for elaborated concepts, tuples fail:
scala> s.map(_*2)
res55: Seq[Int] = List(2, 4, 6)

scala> t.map(_*2)
<console>:9: error: value map is not a member of (Int, Int, Int)
       t.map(_*2)
         ^

update
def foo(s:Seq[Int])
def foo(s:Int*)

In parameter declaration, Int* saves 4 characters over Seq[Int]. It is not equivalent, but sometimes, Int* will do.

Use infix syntax to remove the need for . characters. You don't need spaces unless adjacent items are both in alphanumeric or both in operator characters (see here), and not separated by reserved characters (brackets, commas etc).
E.g.
List(1,2,3,4).filter(_ % 2 == 0) // change to:
List(1,2,3,4)filter(_%2==0)

You can usually use map instead of foreach:
List("a","b","c") foreach println

can be replaced with
List("a","b","c") map println

The only difference is the return type (Unit vs List[Unit]), which you aren't interested in anyway when using foreach.

Call two times the same function for initialization:
val n,k=readInt

(Seen somewhere else, but can't find it now).

The true and false literals are shorter to write as 2>1 for true and 1>2 for false

define shorter Types:
If you have multiple declarations of a type, like
def f(a:String,b:String,c:String)

it is shorter to define a type alias, and use it instead:
type S=String;def f(a:S,b:S,c:S)

Original length is 3*6=18
Replacement-code is 8(type S=;)+6+3*1(=new length)=17
if (n*length < 8+length+n), then it is an advantage.
For classes which are instantiated via a factory, we can set a shorter variable name to point to that object. Instead of:
val a=Array(Array(1,2),Array(3,4))

we can write
val A=Array;val a=A(A(1,2),A(3,4))

This applies to C++ as well with #define for example, but I admit it's nice that def and val are shorter.

Hm. def is the keyword to define a method, and a simple translation to c++ for val is 'const', and it is a declaration, but the type is often inferred. The shortening is in the first case the type= which is closer to typedef - isn't it? The second example isn't from me and it is new to me. I have to watch out, where to use it.

typedef long long ll; is the same as #define ll long long, so the latter's shorter by 1.  But yeah, typedef does work.  Looking at the val example again I definitely misread it.  It seems even less Scala-specific.  x = thingWithAReallyLongComplicatedNameForNoReason is a pretty general strategy :P

@userunknown When you instantiate a List or Array etc with syntax val x = List(1,2,3) you're just calling the apply method on the List object. (This technique for object creation is known as a "factory method", in contrast to using a constructor with new.) So above, we're just making a new variable that points to the same singleton object as the variable name Array. Since it's the same thing, all the methods, including apply, are available.

Rename Methods, if their name is long, and if they're used multiple times - real world example:
 x.replaceAll(y,z)

 type S=String; def r(x:S,y:S,z:S)=x.replaceAll(y,z)

Depending on the possibility to save 'S=String' at different places too, this will  only be economical, if you replace at least replaceAll 3 times.

Initialize several variables at once using a tuple:
var(a,b,c)=("One","Two","Three") //32 characters

vs.
var a="One";var b="Two";var c="Three" //37 characters

Use lazyZip or zipped (and _) instead of zip when combining lists
Using a.zip(b) is shorter than a.lazyZip(b) or (a,b).zipped, but if you're using map on it later, the latter will be shorter, since with zip, map requires function taking a single Tuple2, but with lazyZip/zipped, you can use a function of two parameters with underscores.
Here's an example adding together two lists:
val list1 = List(1, 2, 3, 4)
val list2 = List(5, 6, 7, 8)

list1.zip(list2).map(t=>t._1+t._2)   //Not good
list1.lazyZip(list2).map((a,b)=>a+b) //Okay, this is worse
list1.lazyZip(list2).map(_+_)        //But underscores make it all better
(list1,list2).zipped.map((a,b)=>a+b) //Same as with lazyZip
(list1,list2).zipped.map(_+_)        //Same as with lazyZip

Since zipped is deprecated, I'd recommend lazyZip, as you can also use infix syntax with it. However, in some situations, such as when you're zipping more than 2 lists, zipped may still be better (and it's not available on TIO, which uses an older version of Scala - you'll need Scastie).

Treat a String as a Sequence
Use filter instead of replace or replaceAll
If you need to erase characters from a String use instead of replace / replaceAll
x replaceAll(y,"") // 18 bytes
x replace(y,"")    // 15 bytes

the filter method:
x filter(y!=)      // 13 bytes

Do not use charAt
If you need a character from a specific index from a String, do not use charAt:
x charAt 7  // 10 bytes

Treat the String as a sequence:
x(7)        // 4 bytes

Use drop / slice instead of substring
x substring y    // 13 bytes
x drop y         //  8 bytes

x substring(a,b) // 16 bytes
x slice(a,b)     // 12 bytes

Thanks to user for extending the answer!

If you want to expand your answer(s) with more String-related tips, here's another: s.drop(x) is shorter than s.substring(x), and s.slice(a,b) is shorter than s.substring(a,b) (really, almost any time you treat a String like a Seq, it's shorter).

Use syntactic sugar and built-in functions to save bytes.

syntactic sugar, e.g.    use /: operator (fold left)
val sum = numbers.foldLeft(0) { (accumulator, element) => accumulator + element }

val sum = (0 /: numbers) { (accumulator, element) => accumulator + element }

Type conversion.  231+.0 instead of 231.toDouble.  231+"" instead of 231.toString

Use Seq instead of Array or List

Rewrite type name and method name.

Rewrite the type name if the type appears very many times.
Use generic parameter instead of external type definition to save more bytes.
/*42 bytes*/
def f(a:String,b:String,c:String,d:String)

/*36 bytes*/
type S=String
def f(a:S,b:S,c:S,d:S)

/*33 bytes*/
def f[S<:String](a:S,b:S,c:S,d:S)

If the method appears very many times, please rewrite the method name.
implicit class V[A](val x:A)extends AnyVal{def Q=x.toSet}

Avoid def return type if possible.   Use def instead of lambda function val f=.   e.g.
use def f(a:Int)=a+1 instead of val f:(Int=>Int)={a:Int=>a+1} to save bytes.

Avoid unnecessary braces {} ()

Simultaneously initialize multiple variables val r,c=new StringBuilder;

use  0 to x-1 instead of 0 until x

Use generic parameter instead of external type definition: def f[S<:String](a:S,b:S,c:S,d:S) This is shorter than just inlining the type if you have more than 2 arguments of that type.

@noodle man,  so many thanks.

If you need to reuse a function, make a def instead of a val
If you absolutely need to define a function in your answer to reuse multiple times, it's usually better to define it like a method rather than using a lambda.
Consider these two pairs of functions:
//Recursive
def f(i:Int):Int=if(i>0)i*f(i-1)else 1
val f:Int=>Int=i=>if(i>0)i*f(i-1)else 1

//Not recursive is also shorter with def
def f(i:Int)=i+1
val g=(i:Int)=>i+1

Except when using pattern matching
However, if you're pattern matching, you can use Scala's special syntax and omit match when assigning an anonymous function to a val. As you can see, it's a lot shorter:
//Highly efficient way to sum a list
val g:List[Int]=>Int={case h::t=>h+f(t)case _=>0}
def f(l:List[Int]):Int=l match{case h::t=>h+f(t)case _=>0}

You can also use ⇒ instead of using => for function definitions.

Hello and welcome to PPCG. Since most of the time, answers are counted in bytes rather than characters, your tip only has a limited scope. I would address this and also add a tip title like Shortening function definitions in character count based code golf challenges.


text:
Simulate a Minsky Register Machine (II)
This is an extension of Simulate a Minsky Register Machine (I). I'm not going to repeat all of the description there, so please read that problem description first.
The grammar in part (I) was as simple as possible, but results in rather long programs. Since this is a code golf site, we'd rather have a golfed grammar, wouldn't we?
At a high level, the changes from the original grammar are as follows:

The label on the first line is optional
Whitespace is optional except where required to separate two adjacent identifiers
States can be inlined. To ensure non-ambiguous parsing, if the first state of a decrement operation is an inlined state, it must be enclosed in parentheses. This means that any program can be golfed into a one-liner.

For example, in the original test cases we had:
b+=a, t=0
init : t - init d0
d0 : a - d1 a0
d1 : b + d2
d2 : t + d0
a0 : t - a1 "Ok"
a1 : a + a0
a=3 b=4

In the golfed grammar this could be shortened to:
init:t-init d
d:a-(b+t+d)a
a:t-(a+a)"Ok"
a=3 b=4

or even:
init:t-init d:a-(b+t+d)a:t-(a+a)"Ok"
a=3 b=4

The new BNF for the "program" lines (as opposed to the final line, which is data) is:
program    ::= first_line (newline line)*
first_line ::= cmd
line       ::= named_cmd
state      ::= state_name
             | cmd
             | '"' message '"'
delim_state::= '(' cmd ')'
             | '"' message '"'
cmd        ::= raw_cmd
             | named_cmd
named_cmd  ::= state_name ' '* ':' ' '* raw_cmd
raw_cmd    ::= inc_cmd
             | dec_cmd
inc_cmd    ::= reg_name ' '* '+' ' '* state
dec_cmd    ::= reg_name ' '* '-' ' '* delim_state ' '* state
             | reg_name ' '* '-' ' '* state_name ' '* delim_state
             | reg_name ' '* '-' ' '* state_name ' '+ state
state_name ::= identifier
reg_name   ::= identifier

Identifiers and messages are flexible as in the previous challenge.

All of the test cases from the previous challenge are still applicable. In addition, the following golfed Josephus solution should exercise most of the grammar:
in:k-(r+t+in)in2:t-(k+in2)r-(i+n-0"ERROR n is 0")"ERROR k is 0"
0:n-(i+2:k-(r+t+2)5:t-(k+5)7:i-(r-(t+7)c:t-(i+r+c)i+0)a:t-(i+a)7)"Ok"
n=40 k=3

Expected output:
Ok
i=40 k=3 n=0 r=27 t=0

And I think this covers the remaining case:
k+k-"nop""assert false"
k=3

Expected output:
nop
k=3

You may assume that all programs will have sensible semantics. In particular, they will have at least one state and will not redefine a state. However, as before, a state may be used before it is defined.
The scoring is a variant on code-golf. You can write a self-contained program and it will score as the length of the program in bytes after UTF-8-encoding. Alternatively, because code reuse is a Good Thing, if you have implemented part (I) in n1 bytes, you can write a program which turns a part (II) program into a part (I) program, ready for piping to the original. Your score will then be the length of your transformation program plus ceil(n1 / 2).
NB If you opt for the transformation, you will need to generate names for the anonymous states in such a way that you guarantee that they don't clash with named states.

Haskell, 552 499 493 characters
import Control.Monad.RWS
import Data.Map
main=interact$z.lines
z x=let(s:_,w)=evalRWS(mapM(q.t)x)w[]in s.f.i.t$last x
p=get>>=q
q(l:":":x)=x%do a<-p;tell$f[(l,a)];r a
q(v:"+":x)=x%fmap(.a v 1)p
q(v:"-":x)=x%liftM2(d v)p p
q(('"':s):x)=x%r(\w->unlines[init s,do(v,x)<-assocs w;v++'=':show x++" "])
q(n:x)|n<"*"=x%p|1<3=x%asks(!n)
d v p n w|member v w&&w!v>0=p$a v(-1)w|1<3=n w
t[]=[];t x=lex x>>= \(y,x)->y:t x
i(v:_:x:t)=(v,read x):i t;i[]=[]
x%m=put x>>m;r=return;a=insertWith(+);f=fromList

Did more or less a full rewrite. Replaced CPS with a RWS monad which reads its own output to look up states it hasn't parsed yet (yay for laziness!), plus some other tweaks.

source: Stack Exchange

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

sort: votes


text:
Fastest C/C++ comparison function for an opaque field containing doubles
Description:
Write the fastest comparison function for an opaque field containing a double. Here is my example:
// Three-way comparison function:
//   if a < b: negative result
//   if a > b: positive result
//   else: zero result
inline int Compare(const unsigned char* a, const unsigned char* b) const
{
    if (*(double*)a < *(double*)b) return -1;
    if (*(double*)a > *(double*)b) return +1;
    return 0;
}

Size: 188 characters (excluding the comments)
Speed: N/A
Background:
Google's LevelDB stores keys as opaque fields (i.e. bytes) and it requires the use of a comparator when the keys cannot be compared as bytes, such as the case with doubles. You can read this article to see why Floating-Point binary comparison is tricky, so when LevelDB stores key-value pairs on disk it has to properly compare the opaque keys in order to achieve good data locality.
Correct Submission:

The submission must be written in C/C++.
The submission must correctly compare the opaque fields as doubles.
Given that 1 and 2 are satisfied, the winner should be selected based on the minimum CPU operations ticks (i.e. the fastest comparison).

If there is a tie, then the shortest correct submission will be awarded.
P.S. This is my first time posting, so please let me know if I should correct/improve something in the competition.

"Minimum CPU operations" isn't well defined unless you specify at minimum an architecture and a compiler, and even then sometimes using fewer operations isn't better. Moreover, with the exception of signed zeros and NaNs comparing doubles as bytes is really easy.

@PeterTaylor, I should probably change it to CPU ticks... additionally, we could run the code in codepad.org or ideone.com; however, I suspect that the performance may differ depending on the server load at the time. And I'm not exactly sure what's the best way to performance test (i.e. found out the number of CPU cycles).

@Lirik What you could do is giving a large array of test data and a sorting algorithm. Then you write a test-script where the sorting algorithm's object file is linked with the object files of each candidate code and you run a sort operation on the array. If the array is sorted correctly, the code is right. The time needed for sort is the time that counts.

@FUZxxl, I'll try to come up with a good test data set for performance testing and I appreciate your submission! :) thanks!

I don't get it.  As Peter says, IEEE-754 is designed such that an integer comparison of the underlying bytes is the same as comparing the represented floating point numbers (modulo the various NaN values coming "after" infinity), nothing tricky about it.

@ephemient, unless I'm misunderstanding how doubles work, double floating-point numbers have a leading bit for the sign. So negative double value, when stored as an opaque (binary) field, will start with 1 and if it's used in something like LevelDB, then I'm not sure how LevelDB will know that the leading 1 is a sign or if it's a really large 64-bit integer?

@Lirik: you would need to sort the 64-bit integers while treating them as signed.

@KeithRandall got it... so casting the double to a signed 64-bit integer would work for sorting purposes.

But I don't like C/C++! (I love C++, and I like C, though.)

[tag:code-golf], [tag:code-challenge], and [tag:fastest-code] all together don't make sense.

What architecture are you targeting? Do you only care about x86, or is this challenge supposed to be something that will compile well across multiple architectures?  Which compiler and options (i.e. x86 with just SSE2, with SSE4, with AVX?  Does it have to be efficient for 32-bit code, is doing the comparison using 64-bit integers good (after type punning the double bit pattern to an int64_t, not just casting).   Is branching vs. branchless important?

What is Compare going to inline into?  Will it branch on the result, or will it store it somewhere?  There's just nowhere near enough detail here for a micro-optimization question.

This is so old... I can't even remember what I needed it for.

This function is written in MMIX assembly. It should perform the calculation in 2υ
+ 5μ. If you inline it, the call is no longer needed so you can save the POP instruction. This function should be compatible with gcc for MMIX. (Read TAOCP vol 1. fasc 1 for more information):
compareDoubles IS @  ; Declare symbol, @ is the current position
   LDOU $0,$0,0      ; Load first double  (LDOU: load octa unsigned), 1v
   LDOU $1,$1,0      ; Load second double, 1
   FCMP $0,$0,$1     ; Compare floating point values, 4µ
   POP  1,0          ; return, 1µ

If you assemble it, the code is 16 bytes long and may looks this:
8f 00 00 00  8f 01 01 00  01 00 00 01  f8 01 00 00

-1, fails spec: not written in C or C++.  Still pretty neat, though.

@Ilmari It's unusual to downvote a submission just because the language is wrong.

Yeah, I realized that the downvote was unreasonable after I made it, but it was too late to revoke it.  I'd mistakenly thought this was a new challenge, and wondered why people were rushing to upvote an obviously non-compliant answer.  FWIW, I did go and find another one of your answers that I liked and upvoted it to make up for the hasty downvote.

Can't you load that into a memory location, then cast it as a function pointer and throw stuff at it?  Kind of like how you'd run shell code in C?

@GigaWatt Good idea. I just have to be careful about GCC's own interpretation of the calling convention.

Technically the “v”s in this post should each be “υ” (U+03C5 GREEK SMALL LETTER UPSILON) (see footnote on page 22 of Fasc 1)… though in the font being used here as I type, it doesn't look as much like “v” as in the font used in the book.

@ShreevatsaR Satisfied?

#define compare(X, Y) ((X)<(Y)?-1:((X)>(Y)?1:0))
// 48 characters

or want to pass a pointer you can define
#define compare(X, Y) (*((double*)X)<*((double*)Y)?-1:(*((double*)X)>*((double*)Y)?1:0))
// 88 characters

Doesn't follow specs.

@trinithis why? defines just force the compiler to use inline calling, and removes type checking (and both happen in question example)

#define does not remove type checking. It's just a macro. In any case, your code will compare char*s as chars, not as doubles.

@trinithis fixed that, but anyway it's the fastest possible.

all_licenses: 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/


text:
Write a function that returns past tense of given verb
Challenge

Write a function which takes an argument which is a verb, and returns the past tense of the verb. (Assume that the verb is regular)

Past tense
Note: consider y as neither consonant nor vowel.
Normally, just adding ed after the end of verb makes the past tense of the verb.
Ex: jump → jumped, ask → asked
However, there are other rules.

If the last character of the given verb is e, just add d.
Ex: love → loved, move → moved
If the verb is ended with a consonant + y, then change y to i, and add ed.
Ex: study → studied, cry → cried
However, if the verb is ended with a vowel + y, then just add ed.
Ex: play → played, stay → stayed
If a verb is ended with a vowel and a consonant, then write the consonant one more time, and add ed.
Ex: stop → stopped, plan → planned
However, if a verb is ended with multiple vowels + a consonant or single vowel + multiple consonants, then just add ed.
Ex: look → looked, jump → jumped

There are more rules but let's care above rules only. For example, according to above rule, visit → visitted.
Winner
Since this is code golf, the shortest code that correctly returns past tenses wins.
Example (JS, 127)
function f(x){return x.replace(/([^aeiouy])y$/,'$1i').replace(/([^aeiouy][aeiou])([^aeiouy])$/,'$1$2$2').replace(/e$/,'')+'ed'}

Now that's a nice challenge.

inverse stemming! interesting! I'll try to give a try when I get back home :)

Any solution that's shorter than 1800 characters is incorrect (irregular verbs).

@Quandary That's why I said '(Assume that the verb is regular)'

@Quandary: Not quite true... see Belisarius' answer.

something directly related to it, can there be a function which returns the third form?

sed, 76 characters
Does a sed script count as a function for this problem?
s/\([^aeiou]\)y$/\1i/
s/\([^aeiou][aeiou]\)\([^aeiouy]\)$/\1\2\2/
s/e\?$/ed/

Mathematica 43 chars
f=WordData[#,"InflectedForms","List"][[1]]&

Usage:
f /@ {"call", "try", "use", "wash", "play", "stop", "look"}

{"called", "tried", "used", "washed", "played", "stopped", "looked"}

Also:
f /@ {"buy", "run", "swim"}

{"bought", "ran", "swam"}

You don't think that a dictionary look-up is kinda cheating? :-)

@Simon Definitively no. WordData is part of the language :)

Groovy - 111 characters
v={it==~'[aeiou]'};p={s->r=s[0..-2];a=s[-1];b=v s[-2];(a=='e'?r:a=='y'?!b?r+'i':s:v(s[-3])|!b|v(a)?s:s+a)+'ed'}

assert ['jump', 'ask', 'love', 'move', 'study', 'cry', 'play', 'stay', 'stop', 'plan', 'look'].collect { p(it) } == ['jumped', 'asked', 'loved', 'moved', 'studied', 'cried', 'played', 'stayed', 'stopped', 'planned', 'looked']

Perl 5 (82 characters):
sub f{$_=pop;$C='[^aeiouy]';s/($C)y$/$1i/;s/($C[aeiou])($C)$/$1$2$2/;s/e?$/ed/;$_}

I am sure it can be improved.

C - 120 119 characters
In typical C style, the function f updates a string buffer in place, assuming that the caller has reserved enough space for up to three extra characters.  The second argument should be given as 0.  The declaration of the global state variable l is included in the total character count.
#include <stdio.h>
#include <string.h>

l;void f(b,i)char*b;{*b?f(b+1,i/2+4*!strchr("aeiouy",l=*b)):(i-5?*--b=l=='y'&i/2?'i':l:(*b=l),strcpy(b+=l!='e',"ed"));}

int main()
{
  char b[10000];
  while (gets(b)) {
    f(b,0);
    puts(b);
  }
  return 0;
}

Explanation: The function iterates over the characters recursively. The second argument i encodes which of the previous three characters were consonants in its bottom three bits.  At the end of the string, if i==5 then the last three characters were a consonant, a vowel and a consonant, and thus the last character must be duplicated.  Similarly, if bit 1 of i indicates that the second-to-last character was a consonant and the last character is 'y', then the 'y' is replaced by 'i'.

Scala 199 273 chars
def v(c:Char)="aeiouy" contains c
def p(o:String)={val s=o.reverse
if(s(0)=='e')o+"d"else
if(!v(s(1))&& s(0)=='y')o.replaceAll("y$","ied")else
if(!v(s(0))&& v(s(1))&& !v(s(2)))o+s(0)+"ed"else
o+"ed"}

Invocation:
val li = List ("move", "cry", "plan", "play", "look")
li map p

My first approach was much longer, by moving the if-else-cascade to a list=> to a function:
type S=String
def f(l:List[(Boolean,S)]):S=if(l(0)._1)l(0)._2 else f(l.tail)
def v(c:Char)="aeiouy" contains c
def c(o:S)={val s=o.reverse
f(List((s(0)=='e',o+"d"),(!v(s(1))&& s(0)=='y',o.replaceAll("y$","ied")),(!v(s(0))&& v(s(1))&& !v(s(2)),o+s(0)+"ed"),(true,o+"ed")))}

Maybe the approach is interesting. Degolfed and explained:
// just for shortening
type S=String
/* take a list of Booleans and Strings, and return early
   if a Boolean is true. This approach would work,
   if there where much more conditions, I guess.
*/
def doFirst (list: List[(Boolean, S)]): S =
  if (list(0)._1) list(0)._2 else doFirst (list.tail)
// vocal - is it a vocal
def v(c:Char)="aeiouy" contains c
// here is the key function
def toPast(o:S)={
  // reversing the String allows easy access to the last elements,
  // without considering how long the string is.
  val s=o.reverse
  doFirst (List (
    (s(0)=='e', o+"d"),
    (!v(s(1)) && s(0)=='y', o.replaceAll("y$","ied")),
    (!v(s(0)) && v(s(1)) && !v(s(2)), o+s(0)+"ed"),
    (true, o+"ed")
  ))}

Ruby, 101 characters
Probably can be smaller.
def f x;x.sub(/([^aeiouy])y$/,'\1i').sub(/([^aeiouy][aeiou])([^aeiouy])$/,'\1\2\2').sub(/e$/,'')+'ed';end

Usage:
f("try")  #=> "tried"
f"call"   #=> "called"

Use Ruby 1.9 lambda syntax f=->(x){...} to get shorter code. Also aeiouy IMHO should be a constant.

Poop - 72 characters
f[s]s^6pow>4<<last&8*(/"ed""id""eid"/|out|flush)+rep'y'1-2-3"aeiou"ord#s

Python - 147

def f(v):T,x,m='aeiou',"ed",v[-1];return[[[v+x,v+m+x][v[-2]in T and m and v[-3]not in T],[v+x,v[:-1]+"ied"][v[-2]not in T]][m=='y'],v+"d"][m=='e']


text:
Build railroad tracks and cheat the government
You are a railroad entrepreneur in the 19th-century United States when trains become popular because they are the most efficient means of transporting large volumes of materials by land. There is a national need for railroad tracks from the east coast through some recently colonized lands in the west.
To accommodate this need, the U.S. government is going to levy a tax to subsidize railroads. They have promised to pay money to your railroad company for each mile of track laid. Since laying tracks in hilly and mountainous regions is more expensive than laying tracks in flat land, they adjust the amount they give accordingly. That is, the government will pay

$5,000 per mile of track laid in flat land
$12,500 per mile of track laid in hilly land
$20,000 per mile of track laid in mountains.

Of course, this plan does not accurately reflect how much it actually costs to lay tracks.
You have hired some cartographers to draw relief maps of the regions where you will be laying track to analyze the elevation. Here is one such map:
S12321
121234
348E96

Each digit represents one square mile of land. S is the starting point, E is the ending point. Each number represents the intensity of the elevation changes in that region.

Land numbered 1-3 constitutes flat land.
Land numbered 4-6 constitutes hilly land.
Land numbered 7-9 constitutes a mountain range.

You have, through years of experience building railroad tracks, assessed that the cost of track building (in dollars) satisfies this formula:
Cost_Per_Mile = 5000 + (1500 * (Elevation_Rating - 1))

That means building on certain elevation gradients will cost you more money than the government gives, sometimes it will be profitable, and sometimes you will just break even.
For example, a mile of track on an elevation gradient of 3 costs $8,000 to build, but you only get paid $5,000 for it, so you lose $3000. In contrast, building a mile of track on an elevation gradient of 7 costs $14,000, but you get paid $20,000 for it: a $6,000 profit!
Here is an example map, as well as two different possible paths.
S29    S#9    S##
134    1#4    1##
28E    2#E    2#E

The first track costs $30,000 dollars to construct, but the government pays you $30,000 for it. You make no profit from this track.
On the other hand, the second costs $56,500 to build, but you get paid $62,500 for it. You profit $6,000 from this track.
Your goal: given a relief map, find the most profitable (or perhaps merely the least expensive) path from the start to the end. If multiple paths tie, any one of them is an acceptable solution.
Program Details
You are given text input separated with a rectangular map of numbers and one start and end point. Each number will be an integer inclusively between 1 and 9. Other than that, the input may be provided however you like, within reason.
The output should be in the same format as the input, with the numbers where track has been built replaced by a hash (#). Because of arbitrary regulations imposed by some capricious politicians, tracks can only go in horizontal or vertical paths. In other words, you can't backtrack or go diagonally.
The program should be able to solve in a reasonable amount of time (i.e. <10 minutes) for maps up to 6 rows and 6 columns.
This is a code golf challenge, so the shortest program wins.
I have an example (non-golfed) implementation.
Sample I/O
S12321
121234
348E96

S12321
######
3##E##

S73891
121234
348453
231654
97856E

S#3###
1###3#
3#####
######
#####E

What is, if the output is ambiguous?

The output can be ambiguous, but ambiguous in a way where the profit is the same regardless of how you trace it.

I think there's small mistake. Should 4 in 134 in the example map be 6?

@JiminP Yes, that was a mistake from changing numbers in one place but not another. It should be fixed now.

Three years later, the government looks around and starts wondering why are all* the hills and mountains covered in railroad tracks. But hey, the local transit users got a nice roller coaster / tour ride ---for free--- funded by the goverment, making the people happier, so why care? (* except for some grade-6 hills)

Python, 307 chars
import os
I=os.read(0,99)
n=I.find('\n')+1
I='\0'*n+I+'\0'*n
def P(p):
 S=[]
 for d in(-n,-1,1,n):
  y=p[-1]+d
  if'E'==I[y]:S+=[(sum((int(I[v])-1)/3*75-15*int(I[v])+15for v in p[1:]),p)]
  if'0'<I[y]<':'and y not in p:S+=P(p+[y])
 return S
for i in max(P([I.find('S')]))[1][1:]:I=I[:i]+'#'+I[i+1:]
print I,

P takes a partial path p and returns all ways of extending it to reach E.  Each returned path is paired with its score so max can find the best one.
Takes about 80 seconds on a 6x6 map.

You can replace the second level of indents with tabs to save 3 chars

Python: 529 482 460 bytes
My solution will not win any prizes.  However, since there are only two solutions posted and I found the problem interesting, I decided to post my answer anyway.
Edit: Thanks to Howard for his recommendations.  I've managed to shave a lot of my score!
import sys
N=len
def S(m,c,p=0):
 if m[c]=='E':return m,p
 if m[c]<'S':
    b=list(m);b[c]='#';m=''.join(b)
 b=[],-float('inf')
 for z in(1,-1,w,-w):
    n=c+z
    if 0<=n<N(m)and m[n]not in('S','#')and(-2<z<2)^(n/w!=c/w):
     r=S(m,n,p+(0if m[n]=='E'else(int(m[n])-1)/3*5-int(m[n])+1))
     if b[1]<r[1]:b=r
 return b
m=''
while 1:
 l=sys.stdin.readline().strip()
 if l=='':break
 w=N(l);m+=l
b,_=S(m,m.index('S'))
for i in range(0,N(b),w):print b[i:i+w]

That's how it starts. :)

Some minor improvements: P and M are only used once each so it is a good idea to inline then (for a single invocation it works in almost all cases for two sometimes). m[c]!='S' can be shortened to m[c]<'S', also abs(z)==1 to abs(z)<2 or even -2<z<2.

Your "minor improvements" save me 47 bytes.  I'm editing my answer.

Ruby, 233 characters
R=->s{o=s=~/S/m
s=~/E/m?(q=[-1,1,-N,N].map{|t|s[f=o+t]>'0'?(n=s*1
n[o]='#'
n[f]='S'
a=R[n]
a&&[a[0]-(e=s[f].to_i-1)/3*5+e,a[1]]):nil}-[nil]
q.sort!&&q[0]):[0,(n=s*1;n[o]='E'
n[$_=~/S/m]='S'
n)]}
N=1+(gets(nil)=~/$/)
$><<R[$_+$/*N][1]

A Ruby brute-force approach which runs well inside the time constraints on a 6x6 board. The input must be given on STDIN.
Examples:
S12321
121234
348E96

S#2321
1#####
3##E##
--
S73891
121234
348453
231654
97856E

S#####
1212##
#####3
#3####
#####E

@PeterOlson I tried to give at least a little bit of attention to your challenge ;-)


text:
Selective character count (only non-alphanumeric)?
Challenge (Easy)

Write a function which takes an argument and returns the number of non-alphanumeric characters found.

Challenge (Hard)

Write a function which takes an argument and returns the number of bytes used to store the number of non-alphanumeric characters found.  (ie: include calculation for multi-byte characters.)

Rules / Notes

Alphanumeric in this case is defined as:
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
A null character should count as 0 characters, but as 1 byte when stored.
NUL
Showing multi-byte support (if too complicated) only has to demonstrate one character set or language reference / codepage (if this actually matters.  I don't know, so just putting it out there.)

Winner
Since this is code golf, the shortest code that correctly matches the challege wins.

Require to support multibyte char? Require UTF8?

For C non-unicode they are just same challenge?

@l4m2 "Showing multi-byte support (if too complicated) only has to demonstrate one character set or language reference / codepage"

Perl, 14 characters
y/A-Za-z0-9//c

Jelly, 7 6 4 bytes
ḟØBL

Try it online!
ḟØBL
ḟ         reverse ḟilter: remove all of the input characters that are also in...
 ØB       alphanumeric characters...
   L      and get the Length of the resulting string!

6-byte solution:
ḟØWṖ¤L

Try it online!
ḟØWṖ¤L
ḟ         reverse ḟilter: remove all of the input characters that are also in...
 ØWṖ¤     the "word" character class with the underscore popped from it, taken as a nilad...
     L    ...and take the length of the resulting string

You can use (nilad) (links) ¤ as a new nilad, like so: ḟØWṖ¤L

Alternatively, ØWṖ⁸ḟL works too, of course. (That ⁸ḟ is the fourth monad chain pattern.)

@Lynn Thank you! I wasn't able to understand ¤ from the docs before but now I understand it!

You can use ØB (push '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') instead of ØWṖ¤ to save 2 bytes.

@KevinCruijssen, thanks! Don't know why I didn't catch that nilad when I was making this.

Stax, 3 bytes (Easy)
├Dr

Run and debug it
Explanation
VL-%        # Full program, unpacked
VL          # Push "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  -         # Remove all elements in b from a.
    %       # Length and implicitly print result

Dang, ninja'd me by a minute! My solution was identical. I'd describe VL as "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" rather than as many separate elements.

@Scrooble Yeah that is what I had it as originally, but I thought it looked too long, so I formatted it like that to be more concise. I see how they could be viewed at differently. I'll change it to be like you recommended though.

Groovy
Easy: 26 25 30 characters
c={(it=~/[[^\00\w]_]/).size()}

assert c("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789")== 2
assert c("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")==0
assert c("a-b-7*NNuah ~#77%")==7
assert c('_|') == 2
assert c('\0') == 0

Hard: 47 characters
s={it.replaceAll(/[\w&&[^_]]/,'').bytes.size()}

assert s("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789")== 2
assert s("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")==0
assert s("a-b-7*NNuah ~#77%")==7
assert s('_') == 1

Is that | supposed to be in the first regex?

I thought it was... but looks unnecessary :) thanks

Looked to me like a bug, because I think it would have messed up the counts in strings with a |.

Waiting for some other entries, but nice go at it.  Have you tried running some Chinese or Japanese characters into the hard function to see if it counts them properly?

I don't see you handling '\0' in easy (they should also be excluded)

@ratchet Good point re: NUL; @cbroughton will check with some japanese...

@cbroughton hard answer will use default charset of whatever system it's run on, and should accurately count storage size, although may struggle if e.g. Japanese characters are not supported in that character set

D
easy (29 chars)
count!"!isAlphaNum(b)&&b"(s);

hard (35 chars)
s needs to be a char[]
s.length-count!"!isAlphaNum(b)"(s);

R, 68 42 bytes
-26 bytes thanks to Giuseppe.

function(x)nchar(gsub('[[:alnum:]]',"",x))

Try it online!

05AB1E, 4 bytes (easy)
žKмg

Try it online.
Explanation:
žK      # Push "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  м     # Remove all occurrences of this second string from the input string
   g    # Push and implicitly output the length of the result

05AB1E, 19 bytes (hard)
žKмÇεDžy‹i1ë.²<5÷>н]O

Thanks to @Mr.Xcoder for helping me put two sub-solutions together with D, and explaining how ] closes both the if-statement and foreach-loop. (I accidentally placed the D before the ε and used one } instead of two..)
Try it online.
Explanation:
žK                     # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  м                    # Remove all occurrences of this second string from the input string
   Ç                   # Convert each character to its unicode value
    εD                 # Foreach over this list
         i             #  If the current item
        ‹              #  is maller than
      žy               #  128
          1            #   Use 1
           ë           #  Else
            .²         #   Use log_2
              <        #   minus 1
               5÷      #   integer-divided by 5
                 >     #   plus 1
                  н    #  Take the head of the sublists
                   ]   # Close both the if-else and for-each (shorter version of `}}`)
                    O  # Sum everything together

05AB1E doesn't have any builtins for knowing the amount of bytes a character costs, so I'm converting them to unicode values with Ç and use the following pseudo-code to determine their bytes:
if(unicodeValue < 128)
  return 1
else
  return log_2(unicodeValue-1)//5+1    # (where // is integer-division)

Pseudo-code inspired by @TheBikingViking's Python 3 answer for the Bytes/Characters challenge.

Husk, 4 bytes (easy)
#(¬□

Try it online!
Explanation
Pretty simple usage of isanum (□):
#(¬□)  -- example: "Input!"
#(  )  -- count number of
 ( □)  -- | is alphanumeric: [73,110,112,117,116,0]
 (¬ )  -- | not: [0,0,0,0,0,1]
       -- : 1

MS-SQL, 85 bytes (easy)
SELECT SUM(1)FROM spt_values,t
WHERE type='P'AND SUBSTRING(v,number,1)LIKE'[^a-z0-9]'

Handles strings up to 2047 characters. Per our IO standards, input is taken via a pre-existing table t with varchar field v.
This must be run in the master database (which exists on every SQL server). This database has a system table dbo.spt_values, which, if we filter by type='P', contains counting numbers from 0 to 2047. Join that to our input table to split each character into its own row, then count up those that match the LIKE filter (which supports character ranges).
MS-SQL, 85 bytes (hard)
SELECT SUM(2)FROM spt_values,t
WHERE type='P'AND SUBSTRING(v,number,1)LIKE'[^a-z0-9]'

You also need to change the input table to an nvarchar field v instead of varchar.
So yeah, this is kind of cheaty, because the nvarchar data type uses 2 bytes for every character, even for normal ASCII characters. That means I don't have to distinguish between characters that could be stuffed into a single byte and those that can't. But it does strictly satisfy the challenge, since it reflects the number of bytes that SQL is actually using to store nvarchar strings.

Javascript 1.8
easy (48 chars)
function f(s)(s.match(/[^a-z0-9]/gi)||[]).length

PowerShell, easy, 44
filter e{($args-replace"[a-z0-9]").Length}

If we stretch the definition of »arguments«, we can shorten it a bit more (41):
filter e{($_-replace"[`0a-z0-9]").Length}

but it then requires input to be sent via the pipeline.
PowerShell, hard, 71
function x{[text.encoding]::utf8.GetByteCount($args-replace'[a-z0-9]')}

Again, if we allow the pipeline we get it to 68:
function x{[text.encoding]::utf8.GetByteCount($_-replace'[a-z0-9]')}

Scala
Easy (43 chars)
def c(s:String)=s.count(!_.isLetterOrDigit)

Hard (58 chars)
def c(s:String)=s.filter(!_.isLetterOrDigit).getBytes.size

Python
easy (39 chars)
f=lambda s:sum(1-i.isalpha()for i in s)

You can remove the f= to save 2 bytes

Brainfuck
Easy (1397 chars)
>+[,[>+>+<<-]>>[<<+>>-]>-[<->+++++]<--->>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[
<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]<[-]<<[>>+>+<<
<-]>>[<<+>>-]>>-[<<->>---------]>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[
-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]>----[<+>----]<++>>>+
<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->
]<+<<-]>>>[-]<[-]<[-]<[-]<[-]<<[>>>+<<<-]>>>[[-]<<[>>+<+<-]>[<+>-]>[<<<+>>>[-]]][-
]<[-]<[-]<<[>>>+<<<-]>>>[<<<->>>[-]]<<[>>+<+<-]>[<+>-]>[<<<[-]->>>[-]][-]<[-]<[-]
<<[>>+>+<<<-]>>[<<+>>-]>>--[<<->>---]<<++++>>>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>
[>-]>[<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]>--[<->
+++++]<----->>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[-]>>->]<+<<[>-[>-]
>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]<[-]<<[>>>+<<<-]>>>[[-]<<[>>+<+<-]>[<+>
-]>[<<<+>>>[-]]][-]<[-]<[-]<<[>>>+<<<-]>>>[<<<->>>[-]]<<[>>+<+<-]>[<+>-]>[<<<[-]-
>>>[-]][-]<[-]<[-]<<[>>+>+<<<-]>>[<<+>>-]>>----[<<+++>>--]>>+<<<[>+>+<<-]>[<+>-]<<
[>>+<<-]+>>>[>-]>[<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]
<[-]<[-]<<[>>>+<<<-]>>>[<<<->>>[-]]<<[>>+<+<-]>[<+>-]>[<<<[-]->>>[-]][-]<[-]<[-]<[
<<+>>[-]]<----------]>--[<->+++++]<--<-[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>>>-[<->+++
++]<---[<+>-]<.[-]++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>>>-[<->+++++]<---[<+
<+>>-]<.<.

All hand coded. It takes input until it gets a 0xA character signifying end of input (not counted). Only handles up to 255 nonalphanumeric input characters.

Perl (easy) 27 characters
sub _{$_=shift;(s/\W|_//g)}

usage:
say _('@abc_123ABC -("~ abc')
---> 8

Ruby, easy, 32
f=->s{s.scan(/[^a-z0-9]/i).size}

Gol><>, Easy, 26 bytes
iEh$"0:A[a{"{16F@2k)S^|}~+

Try it online!
How it works
iEh$"0:A[a{"{16F@2k)S^|}~+

iEh                         Take input as char; if EOF, print the top as int and halt
   $                        Move the input under the char counter
    "0:A[a{"                Push six boundary chars
            {1              Pull the input to the top, and push 1 (XOR counter)
                            (Stack: [char counter, ...boundary, input, XOR counter])
              6F      |     Repeat 6 times...
                @             Pull a boundary char to the top
                 2k)          Copy the input char and compare (boundary > input)
                    S^        XOR with the XOR counter
                            (Stack: [char counter, input, XOR counter])
                       }~+  Move XOR counter to bottom, discard input, and
                              add to the char counter
                            Repeat indefinitely

Pyth
Easy, 17 bytes
l:z"[a-zA-Z0-9]"k

Try it online!
Hard, 30 bytes
/lsm.[\08.BCd:z"[a-zA-Z0-9]"k8

Try it online!

Java 10, 42 bytes (easy)
s->s.replaceAll("[A-Za-z0-9]","").length()

Try it online.
Explanation:
s->                               // Method with String parameter and integer return-type
  s.replaceAll("[A-Za-z0-9]","")  //  Remove all digits and letters
   .length()                      //  And return the length

Java 10, 102 bytes (hard)
s->{int r=0;for(var c:s.replaceAll("[A-Za-z0-9]","").split(""))r+=c.getBytes("utf8").length;return r;}

Try it online.
Explanation:
s->{                              // Method with String parameter and integer return-type
  int r=0;                        //  Result-integer, starting at 0
  for(var c:s.replaceAll("[A-Za-z0-9]","")
                                  //  Remove all digits and letters
             .split(""))          //  And loop over the remaining characters
    r+=                           //   Add to the result-sum:
      c.getBytes("utf8").length;  //    The UTF-8 bytes of the current character
  return r;}                      //  Return the result-sum

Haskell, 58 52 bytes (easy)
-6 bytes, thanks to Laikoni (inverting the test, using elem instead)!
f s=sum[1|c<-s,elem c":;<=>?@[\\]^_`"||c>'z'||c<'0']

Try it online!

51 bytes: f s=sum[1|c<-s,elem c":;<=>?[\\]^_`"||c>'z'||c<'0'].

@Laikoni: Thanks! (you missed one though: @)


text:
Fastest python implementation of multiplication table
I'd be interested to see who can come up with the fastest function to produce multiplication tables, in the following format:
   1   2   3   4   5   6   7   8   9  10  11  12
   2   4   6   8  10  12  14  16  18  20  22  24
   3   6   9  12  15  18  21  24  27  30  33  36
   4   8  12  16  20  24  28  32  36  40  44  48
   5  10  15  20  25  30  35  40  45  50  55  60
   6  12  18  24  30  36  42  48  54  60  66  72
   7  14  21  28  35  42  49  56  63  70  77  84
   8  16  24  32  40  48  56  64  72  80  88  96
   9  18  27  36  45  54  63  72  81  90  99 108
  10  20  30  40  50  60  70  80  90 100 110 120
  11  22  33  44  55  66  77  88  99 110 121 132
  12  24  36  48  60  72  84  96 108 120 132 144

Use the following template to benchmark your code using a 12-width table, and post your  code and the resulting time here.
#!/usr/bin/python
import timeit
cycles = 100000

referencecode = r'''

def multable(width):
  '\n'.join(''.join('{0:4}'.format(x*y) for x in range(1,width+1)) for y in range(1,width+1))

'''

yourcode = r'''

def multable(width):
  pass # Your function here

'''

referencetime = timeit.Timer('multable(12)', setup=referencecode).timeit(number=cycles)
yourtime = timeit.Timer('multable(12)', setup=yourcode).timeit(number=cycles)

print 'Your code completed', referencetime / yourtime, 'times faster than the reference implementation'

In the template, your multable() is missing a return. Also it might be a good idea to have the template check if the two multable()s return the same output.

About 352 times faster, according to the benchmark code
(on my machine)  Python 2.7
Exactly how much faster it is will vary widely between machines. I tested it on my web server also and there it was only 288 times as fast.
import itertools as i, operator as o

def multable(width, m={}):
   if not width in m.keys():
      m[width] = '\n'.join(['%4d'*width]*width)%tuple(i.starmap(o.mul,i.product(range(1,width+1),repeat=2)))
   return m[width]

The actual algorithm is only about 1.25 times as fast as the reference one, but if you have a function which is called often, caching the result saves a lot of time.

def multable(width):
  R=range(1,width+1)
  M=[i*j for i in R for j in R]
  return(('%4d'*width+'\n')*width)%tuple(M)

about 3.3x faster than the reference implementation.

Should that be 1.3x?

@bluepnume: well, it is 3.3x with python 3.2 and 1.3x with python 2.7.

Oh wow, that's impressive -- didn't realise 3.2 had sped things up so much!

tweaking your code, I could go up to 3.58x on Python 3.2

transform R into a list and do the comprehension inside the tuple

My approach (python2.7):
1.63x Faster
from itertools import imap, izip, starmap, product
from operator import mul

def multable(width):
  return '\n'.join(imap(''.join, izip(*((imap('{:4}'.format, starmap(mul, product(xrange(1,13), repeat=2))),) * 12))))

2.32x Faster
from itertools import starmap, product
from operator import mul

def multable(width):
  return (('{:4}' * width + '\n') * width).format(*starmap(mul, product(xrange(1,13), repeat=2)))


text:
Unfolding an integer
Given the functions
L: (x, y) => (2x - y, y)
R: (x, y) => (x, 2y - x)

and a number N generate a minimal sequence of function applications which take the initial pair (0, 1) to a pair which contains N (i.e. either (x, N) or (N, y)).
Example: N = 21. The minimal sequence is of length 5, and one such sequence is
          (  0,  1)
1. L ---> ( -1,  1)
2. L ---> ( -3,  1)
3. R ---> ( -3,  5)
4. L ---> (-11,  5)
5. R ---> (-11, 21)

Write the shortest function or program you can which generates a minimal sequence in O(lg N) time and O(1) space. You may output / return a string in either application order (LLRLR) or composition order (RLRLL), but document which.

Ruby, 55 or 39 characters
f=->n{(n>0?n-1:-n).to_s(2).tr'01',n>1?'LR':n<0?'RL':''}

The function returns the function sequence in composition order.
Usage:
puts f[21]     # RLRLL
puts f[-6]     # LLR

Edit: If we allow recursion (which violates the O(1) memory constraint but such does any function since the return value itself is O(lg n)) we can shrink the code to 39 characters.
f=->n{n<n*n ?f[(n-1)/2+1]+'RL'[n%2]:''}

Perl, 82 81 Characters (complete program)
$n=<>;@_=(R,L);if($n<0){$n=1-$n;$a--}while($n>1){print$_[$n%2+$a];$n+=$n%2;$n/=2}

It takes one number as input, and it outputs the sequence in application order.
Edit: Instead of redefining the array in the if statement, set a number to negative one and add it to the index when the array is referenced. It achieves the same effect.

Jelly, 15 bytes
“”HĊß;ị⁾LR$ƲḂƑ?

Try it online!
This uses the same allowance in Howard's answer, in that we can use recursion, despite it violating the \$O(1)\$ memory requirement. If this isn't allowed, then the following 20 byte solution works instead:
ḶȯAṀ©Bị⁾LRUAƑ}¡$®aḟ0

Try it online!
Both output the composition order
How they work
“”HĊß;ị⁾LR$ƲḂƑ? - Main link f(N). Takes N on the left
              ? - If statement:
             Ƒ  -   If: Invariant under:
            Ḃ   -     Bit; Yields 1 for 0/1, else 0
“”              -   Then: Return the empty string
           Ʋ    -   Else:
  H             -     N÷2
   Ċ            -     Ceiling
    ß           -     f(⌈N÷2⌉)
          $     -     Group the previous 2 links together as a monad g(N):
       ⁾LR      -       "LR"
      ị         -       Modular index N into "LR"
     ;          -     Append to f(⌈N÷2⌉)

The 20 byte version (+6 bytes to handle \$N = 0, 1\$):
ḶȯAṀ©Bị⁾LRUAƑ}¡$®aḟ0 - Main link. Takes N on the left
Ḷ                    - [0, 1, ..., N-1] for N > 0 else []
  A                  - abs(N)
 ȯ                   - Replace [] with abs(N)
   Ṁ                 - Max; N-1 if N > 0 else abs(N)
    ©                - Save this to the register R
     B               - Convert R to binary
               $     - Group the previous 2 links into a monad f(N):
       ⁾LR           -   "LR"
             }       -   To N:
            Ƒ        -     Invariant under:
           A         -       Absolute value; 1 if N ≥ 0 else 0
              ¡      -   Do the following that many times:
          U          -     Reverse "LR"
                         This yields "RL" if N ≥ 0 else "LR"
      ị              - For each bit in R, index into "RL" or "LR",
                       yielding a list of Rs and Ls, S
                ®    - Yield R
                 a   - Replace all but R = 0 with S
                  ḟ0 - Change R = 0 to []


text:
Try to understand this java code
The students in my high school computer science class were asked to write the game of nim for a simple project. Most of them found it very easy and finished quickly. However, one student came up with this solution. I'll probably make them redo it anyway, but I'm wondering if anyone can understand what's going on.
enum $ {

$$;
static int _, $_$, $_, _0_;

{
    {
        {
            {
                _$ $_ = _$.__;
            }
        }
    }
}

enum _$ {

    __(new byte[][]{
        "\nNumber of stones: \0\nPlayer one move: \0Computer takes \0\nComputer wins!\n\0\nPlayer wins!\n".getBytes(),
        new byte[]{(byte) (_ = (int) (Math.random() * (_ = ((_ = -~_) * (_ << -~-~_) + -~-~-~_ + -~ ~ ~-~_)) + _))}},
        null);

    java.io.Console ___ = System.console();
    _$(byte[] _$_[], String $[]) {
        for ($ = new String(_$_[$_$]).split(Character.toString((char) $_$)); _ > 0;) {
            ___.printf($[$_$] + _);
            do _0_ = ___.readLine($[-~$_$]).getBytes()[$_$] - 060;
            while (_0_ > -~-~-~$_$ || _0_ > _);
            _ -= $_$ + _0_ >> $_$;
            if (((!(!(((!((!((_) < -~($_ = $_$))))))))))) break;
            _ -= $_ = Math.min((int) (Math.random() * -~-~-~$_$ + -~$_$), _);
            ___.printf($[-~-~$_$] + $_);
        }
        ___.printf(($_$ = -~-~-~$_$) > _ ? $[$_ > 0 ? -~$_$ : $_$] : $[2]);}}};

`

See http://stackoverflow.com/questions/7906483/what-causes-noclassdeffounderror-on-a-main-class/7906484#7906484 The rest is just obfuscating variable names. And it has a bug, because it allows the player to take 0.

PS This isn't actually on topic for this site. It's essentially a duplicate of the linked post, so I would suggest that you flag it for closing; otherwise, I'm not sure where it would fit.

just cause I have way too much time on my hands:
import java.io.*;
import java.util.*;

enum MyEnum {

    $$;

    {
        EnumCalc $_ = EnumCalc.CONSTR;
    }

    enum EnumCalc {

        static int total, $_$, comp, player;
            CONSTR( );

        PrintStream out = System.out;
        Scanner scan = new Scanner(System.in);

        EnumCalc() {

            total = (int) (Math.random() * 20 + 20);
            strings = new String[] { "\nNumber of stones: ",
                    "\nPlayer one move: ", "Computer takes ",
                    "\nComputer wins!\n","\nPlayer wins!\n" };
            while(total > 0) {
                out.printf("\nNumber of stones: " + total);

                do {
                    out.printf("\nPlayer one move: ");
                    player = scan.nextLine().charAt(0) - '0';
                } while (player > 3 || player > total);//input loop

                total -= player;
                comp = 0;
                if (total < 1)
                    break;
                comp = Math.min((int) (Math.random() * 4), total);
                total -= comp;
                out.printf("Computer takes " + comp);
            }
            String string;
            if (3 > total)
                string = comp > 0 ?"\nPlayer wins!\n":"\nComputer wins!\n";
            else
                string = "Computer takes ";
            out.printf(string);
        }

    }
};

note that -~i is the same as 1+i
and I replaced the console calls with System.out and Scanner cause eclipse doesn't give me a Console


text:
Generate excel column name from index
This one comes from a real life problem. We solved it, of course, but it keeps feeling like it could have be done better, that it's too lengthy and roundabout solution. However none of my colleagues can think of a more succinct way of writing it. Hence I present it as code-golf.
The goal is to convert a nonnegative integer into a string the same way Excel presents its column headers. Thus:
0 -> A
1 -> B
...
25 -> Z
26 -> AA
27 -> AB
...
51 -> AZ
52 -> BA
...
16,383 -> XFD

It has to work at least up to 16,383, but beyond is acceptable too (no bonus points though). I'm looking forward most to the C# solution, but, as per traditions of code-golf, any real programming language is welcome.

Are you sure that 16383 should be XFD? What do you get for 676 and 702?

Well, that's what Excel shows, and I found it on the web that it has 16384 columns. I'll test it tomorrow with our (known to work) code (is late night right now where I live).

Also, testing with Excel itself reveals that 676=ZA and 702=AAA.

The reason I ask is that I wrote some straightforward base-26 code, got results which fit yours precisely, but broke on 676 and 702.

Yup. It's not Base-26. That's the problem. ;)

If your numbering started from 1 it would be base-27 (A-Z and the empty string representing the 0), I think. As it is, the rightmost column has 26 possible values and the rest have 27. Which is awkward.

@Gareth, it's more complicated than that, because e.g. the 2nd least significant column only has 27 possible values if the 3rd least significant column is ''. Otherwise it's restricted to 'A'..'Z'.

@PeterTaylor True. I know it took a good half hour or so of fiddling to get my version to give the correct result.

r1c1 notation is allowed?

That would be too easy :)

This is a super old challenge, but I'm a bit flummoxed why you've specified a 0-based index, since Excel itself uses a 1-based index.=ADDRESS(1,1) returns $A$1. See Dr. belisarius' Excel answer.

@BradC - You know, I don't really remember anymore. :) It could be that I'm just used to 0-based indexing. Or maybe we did use that result as an index in a 0-based array (we used C#). Or maybe that's how it appears internally in the XLSX files. Anyways, converting from 0-based to 1-based is just a +1, so it doesn't matter much. :)

Perl 6, 16 14 bytes
{("A"..*)[$_]}

Works even beyond XFD. Thanks to infinite lists in Perl 6, this doesn't take forever (and a half) to execute.
Try it online!

Excel Formula:), 36 chars
=SUBSTITUTE(ADDRESS(1,A1,4),"1","")

Usage:

Sorry, couldn't resist ...

Arghh! I had actually thought of prohibiting this, but forgot to mention it in the post! :D Still, Excel formulas are not a programming language (and yes, Excel VBA is off limits too). :P

@Vilx- Thanks God someone came up with a shorter solution. I don't want to enter history being the only person who won a golf contest using Excel formulas :)

I still might accept your answer. >:D

@Vilx- That would be slightly sadistic on your part :)

<laughter type="evil">Muhahahahaha!</laughter>

You can drop 2 bytes by replacing "1" with 1

=@TEXTSPLIT(ADDRESS(1,A1,2),"$") would be 32 bytes using ms365 insiders function TEXTSPLIT().

Perl, 17 characters
say[A..XFD]->[<>]

The .. operator does the same thing as the magical auto-increment, but without the need for the temporary variable and loop. Unless strict subs is in scope, the barewords A and XFD are interpreted as strings.
(This answer was suggested by an anonymous user as an edit to an existing answer.  I felt it deserves to be a separate answer, and have made it one.  Since it wouldn't be fair for me to gain rep from it, I've made it Community Wiki.)

Since it's the shortest answer so far, I guess it deserves to be marked as "accepted" until a shorter solution is found (probably only available in JonSkeetScript) :P Ironic.

Since the question is vague on how input and output are done, that actually allows shortening this considerably.  For example, if input is in $_ and the output is the value of the expression, then (A..XFD)[$_] solves the challenge with only 12 chars.

Sorry how should this be run?  With perl 5.18 it prints nothing when given as the argument to -E.

@EdAvis: It's waiting for you to type in a number. Or you could put the number in a file and do perl -E 'say[A..XFD]->[<>]' < number.txt. Or, in shells that support it, just give the input on the command line with perl -E 'say[A..XFD]->[<>]' <<< 123.

I think this can be optimized to say+(A..XFD)[<>]

Haskell, 48
f=(!!)(sequence=<<(tail$iterate(['A'..'Z']:)[]))

Less golfed:
f n = (concatMap sequence $ tail $ iterate (['A'..'Z'] :) []) !! n

Explanation
Haskell's sequence combinator takes a list of actions and performs them, returning the result of each action in a list.  For example:
sequence [getChar, getChar, getChar]

is equivalent to:
do
    a <- getChar
    b <- getChar
    c <- getChar
    return [a,b,c]

In Haskell, actions are treated like values, and are glued together using the >>= (bind) and return primitives.  Any type can be an "action" if it implements these operators by having a Monad instance.
Incidentally, the list type has a monad instance.  For example:
do
    a <- [1,2,3]
    b <- [4,5,6]
    return (a,b)

This equals [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)] .  Notice how the list comprehension is strikingly similar:
[(a,b) | a <- [1,2,3], b <- [4,5,6]]

Because lists are a type of "action", we can use sequence with lists.  The above can be expressed as:
sequence [[1,2,3],[4,5,6]]

Thus, sequence gives us combinations for free!
Thus, to build the list:
["A","B"..."Z","AA","AB"]

I just need to build lists to pass to sequence
[['A'..'Z'],['A'..'Z','A'..'Z'],...]

Then use concatMap to both apply sequence to the lists, and concatenate the resulting lists.  Coincidentally, concatMap is the =<< function for lists, so the list monad lets me shave a few characters here, too.

C, 53 characters
It's like playing golf with a hammer...
char b[4],*p=b+3;f(i){i<0||(*--p=i%26+65,f(i/26-1));}

Normal version:
char b[4];
char *p = b+3;
void f(int i) {
    if (i >= 0) {
        --p;
        *p = i%26 + 65;
        f(i/26-1);
    }
}

And the usage is like that:
int main(int argc, char *argv[])
{
    f(atoi(argv[1]));
    printf("%s\n", p);
    return 0;
}

Perl, 26 characters
$x='A';map$x++,1..<>;say$x

Ruby, 35 characters
e=->n{a=?A;n.times{a.next!};a}

Usage:
puts e[16383]   # XFD

Note: There is also a shorter version (30 characters) using recursion.
    e=->n{n<1??A:e[n-1].next}

But using this function you might have to increase the stack size for large numbers depending on your ruby interpreter.

Groovy, 47
m={it<0?'':m(((int)it/26)-1)+('A'..'Z')[it%26]}

[0:'A',1:'B',25:'Z',
        26:'AA',
        27:'AB',
        51:'AZ',
        52:'BA',
        16383:'XFD'].collect {k,v-> assert v == m(k);m(k) }

Python 45 51
f=lambda i:i>=0and f(i/26-1)+chr(65+i%26)or''

you can remove 2 parentheses by pulling +chr(65+i%26) inside and testing for i>=0, saving you 1 character :)

You could also shave 4 characters off by using f=lambda i: rather than def f(i):return

actually that doesn't work well for numbers 37 and above. I had to update this code a bit: f = lambda i: i >= 0 and f(math.floor(i / 26 - 1)) + chr(int(round(65 + i % 26))) or ''

PHP, 30 bytes
for($c=A;$argn--;)$c++;echo$c;

Run as pipe with `-nr' or try it online.

Excel (MS365), 32 bytes.
=TEXTBEFORE(ADDRESS(1,A1,4),"1")

Welcome to Code Golf!

@RadvylfPrograms Sir, gracias .

Scala, 62 characters
def f(i:Int):String=if(i<0)""else f((i/26)-1)+(i%26+65).toChar

Usage:
println(f(16383))

returns:
XFD

You can try this on Simply scala. Copy and paste the function and use f(some integer) to see the result.

You don't need the ""+ on the else case.

Excel VBA, 31 Bytes
Anonymous VBE immediate window function that takes input from cell [A1] and outputs to the VBE immediate window
?Replace([Address(1,A1,4)],1,"")

Java, 57 bytes (recursive)
String f(int n){return n<0?"":f(n/26-1)+(char)(n%26+65);}

Try it online.
Explanation:
String f(int n){        // Recursive method with integer parameter and String return-type
  return n<0?           //  If `n` is negative:
    ""                  //   Return an empty String
   :                    //  Else:
    f(n/26-1)           //   Recursive call with `n` integer-divided by 26, minus 1
    +(char)(n%26+65);}  //   And append `n%26+65` as character

Java 10, 62 bytes (iterative)
n->{var r="";for(;n>=0;n=n/26-1)r=(char)(n%26+65)+r;return r;}

Try it online.
Explanation:
n->{                      // Method with integer parameter and String return-type
  var r="";               //  Result-String, starting empty
  for(;n>=0;              //  Loop as long as `n` is not negative
      n=n/26-1)           //    After every iteration: divide `n` by 26, and subtract 1
    r=(char)(n%26+65)+r;  //   Prepend `n%26+65` as character to the result-String
  return r;}              //  Return the result-String

Hi. Sorry but I stole your code : Here. :)

@MuhammadSalman Hehe, no problem. I actually got mine from the Scala answer. ;)

JavaScript (Node.js), 50 bytes
f=_=>_<0?'':f(_/26-1)+String.fromCharCode(_%26+65)

Try it online!
Seeing that a lot of people started answering this I answered too.
Note :
This is basically a rip off of @kevinCruijssen's answer in Java shortened thanks to this being JS.

VBA/VB6/VBScript (non-Excel), 73 bytes
Function s(i):While i:i=i-1:s=Chr(i Mod 26+65)&s:i=i\26:Wend:End Function

Calling s(16383) will return XFC.

Welcome to PPCG! Can you add an explanation for users unfamiliar with VB?

@AdmBorkBork Not much to add to previous answers, just language bind!

This appears to fail on all cases where i>675  - s(676)=A@@(expected YZ), s(677)=A@A (expected ZA)

@TaylorScott You're right. Working on it...

@TaylorScott Corrected, +6 bytes... Thanks.

Jq 1.5, 71 bytes
[range(1;4)as$l|[65+range(26)]|implode/""|combinations($l)]|map(add)[N]

Expects input in N. e.g.
def N:16383;

Expanded:
[                       # create array with
   range(1;4) as $l     #  for each length 1,2,3
 | [65+range(26)]       #   list of ordinal values A-Z
 | implode/""           #   converted to list of strings ["A", "B", ...]
 | combinations($l)     #   generate combinations of length $l
]
| map(add)[N]           # return specified element as a string

Try it online!

Javascript, 147 bytes
I had a similar problem. This is the golf of the solution. Excel columns are bijective base-26.
n=>{f=Math.floor;m=Math.max;x=m(0,f((n-24)/676));y=m(0,f(n/26-x*26));return String.fromCharCode(...[x,y,n+1-x*676-y*26].filter(d=>d).map(d=>d+64))}

Expanded, except using 1-indices:
function getColName(colNum){ // example: 16384 => "XFD"
    let mostSig = Math.max(0, Math.floor((colNum - 26 - 1)/26**2));
    let midSig = Math.max(0, Math.floor((colNum - mostSig*26**2 - 1)/26));
    let leastSig = colNum - mostSig*26**2 - midSig*26;

    return String.fromCharCode(...[mostSig,midSig,leastSig].filter(d=>d).map(d=>d+64));
}

You could add a TIO link. Other than that a great first answer. Also welcome to PPCG.

Also answering a question asked 7 years ago is not really a great idea.

Ok , nvm this is wrong on so many levels how did I ever not see this

I wanted to ask this question but it was a duplicate. I'm not sure what you're getting at @MuhammadSalman

I will get back to you in a minute, Anyways welcome to PPCG. nice answer. Plz note that when writing an answer you must provide a full program or a function

Here is an updated and one that is acceptable according to rules : Try it online!

Forth (gforth), 59 bytes
: f dup 0< if drop else 26 /mod 1- recurse 65 + emit then ;

Try it online!
Explanation
dup 0<            \ duplicate the top of the stack and check if negative
if drop           \ if negative, drop the top of the stack
else              \ otherwise
   26 /mod        \ divide by 26 and get the quotient and remainder
   1- recurse     \ subtract one from quotient and recurse on result
   65 + emit      \ add 65 to remainder and output ascii char
then              \ exit if statement

R, 65 bytes
Recursive answer as are many previous answers.

function(n,u=LETTERS[n%%26+1])"if"(n<=25,u,paste0(g(n%/%26-1),u))

Try it online!

Powershell, 68 bytes
param($n)for(;$n-ge0;$n=($n-$r)/26-1){$s=[char](($r=$n%26)+65)+$s}$s

Alternative recursive version, 68 bytes:
filter g{if($_-ge0){(($_-($r=$_%26))/26-1|f)+[char]($r+65)}else{''}}

Test script:
$f = {

param($n)for(;$n-ge0;$n=($n-$r)/26-1){$s=[char](($r=$n%26)+65)+$s}$s

}

filter g{if($_-ge0){(($_-($r=$_%26))/26-1|f)+[char]($r+65)}else{''}}

@(
    ,(0 , "A")
    ,(1 , "B")
    ,(25 , "Z")
    ,(26 , "AA")
    ,(27 , "AB")
    ,(51 , "AZ")
    ,(52 , "BA")
    ,(676 , "ZA")
    ,(702 , "AAA")
    ,(16383 , "XFD")
) | % {
    $n, $expected = $_
    $result = &$f $n
    # $result = $n|g      # Alternative
    "$($result-eq$expected): $result"
}

Output:
True: A
True: B
True: Z
True: AA
True: AB
True: AZ
True: BA
True: ZA
True: AAA
True: XFD

Note: Powershell does not provide a div operator.

Ruby, 26 bytes
->n{(?A..).take(n+1).last}

Attempt This Online!

Excel, 30 bytes
=@TEXTSPLIT(ADDRESS(1,A1,4),1)

Haskell, 48
I really thought that I would be able beat the other Haskell entry, but alas...
f(-1)=""
f n=f(div n 26-1)++[toEnum$mod n 26+65]

I am certain it is possible to shave a couple of characters off this, but I haven't coded in Haskell for nearly a year, so I am quite rusty.
It's not exactly what you would call elegant.

Not bad! :) But Ha - after more than 3 years, still no C# solution. :D

Haha, indeed. But a C# solution is trivial to write using this same method. string f(int n){return n<0?"":f(n/26-1)+(char)(n%26+65);} 57 characters, so I would almost feel bad by posting it as an answer.

><>, 29 bytes
!v:2d*%:"A"+@-2d*,1-:0(?!
$<o

Try it online!

Icon, 58 bytes
procedure f(n);return(n<0&"")|f(n/26-1)||char(65+n%26);end

Try it online!

Factor + successor, 27 bytes
[ "A"[ successor ] repeat ]

Attempt This Online!
Yup, Factor has a vocab for this.

Still not as crazy as mathematica

C (GCC), 39 bytes
f(i){i>25&&f(i/26-1);putchar(65+i%26);}

Try It Online!
Explanation:
f(i)
{
    // If i cannot be represented as a single letter
    i>25 &&
        // Print the next letter
        f(i/26-1);

    // Print the current letter
    putchar(65+i%26);
}

I thought using 0-based indexing was a little strange, so here's 1-based indexing in the same number of bytes:
f(i){i-->26&&f(i/26);putchar(65+i%26);}

Try It Online!


text:
PCM Wave time stretch
Write the smallest program performs a time stretch operation on a PCM Wave (.wav) file.
Rules:

Parameter input will by via whatever standard argument mechanism your language comes with, e.g. argv in C/C++, $_GET in PHP. Hard coded paths are not allowed.
First parameter will be a decimal value that represents the stretch coefficient. 1 means don't stretch, 2 means twice the length, 0.5 means half the length, 0.333 means one third the length. An example might be stretch.exe 1.5 c:\sound.wav
The time stretch operation does not need to perform pitch correction.
You must not drop samples to fit a compression (i.e. stretch < 1). You should use interpolation, weighted mean, or a similar method.
Assume a WAVE PCM file with a RIFF header.
Assume 16-bits per sample (bonus if your code works for 8-bit and 24-bit audio)
You must handle any number of audio channels.
You must at least handle 11025, 22050 and 44100Hz sample rates, though the ability to handle arbitrary rates would be a bonus! :)
Your output file must keep the same sample rate, sample size and channel count as the input file.
The output file must be named "stretch.wav"
You may not use any 3rd party libraries or built-in functions for audio processing. The parsing of the WAV file and the time stretch operation must be your own code.

On Windows, the C:\Windows\Media directory contains plenty of WAV files to test with.

Ruby, 220 characters
s,n=$*
w=IO.binread(n).unpack r='s<*'
x=[];t=[g=0]*c=w[11]
w[u=22..-1].each_slice(c){|f|g+=v=1.0/s.to_f
c.times{|h|t[h]+=f[h]*v}
(c.times{|h|x<<=m=t[h]/g;t[h]-=m};g-=1)until 1>g}
w[u]=x;IO.binwrite'stretch.wav',w.pack(r)

This version works with ruby 1.9.3 with basic 16 bit files (e.g. no additional chunks) for any sample rate or number of channels.