text:
Domination problem in chess
Given an mxm chess board, find a minimum number of pieces of the given kind and place them on a chess board in such a way that all squares are either occupied or attacked by at least one piece.
Input
The input consists of two parameters: m, the number of squares on each side; and a letter which indicates which piece to use, according to the following key: King, Queen, Rook, Bishop, kNight. For example, an input of 8 B means that you have to find a solution for an 8x8 board with bishops.
The input will always consist of a positive integer and a valid letter. You may choose to implement a program which takes input either as command-line arguments or separated by a space on stdin; or to implement a named function/verb which takes two parameters.
Output
The output should be a chess board in the following format:
........
.....Q..
..Q.....
....Q...
......Q.
...Q....
........
........

This is a solution for the input 8 Q. Each line is separated by a newline.
Note that every valid input has a solution.
Other points
Standard loopholes are not acceptable. In particular, since your program must handle any input, it is not sufficient to hard-code the answer for small inputs.
The particular case of this problem where Queens are used has been the subject of some investigation, and the number of Queens required for square boards is in the Online Encyclopaedia of Integer Sequences as A075324. However, that probably doesn't help you for inputs larger than 18 Q, and doesn't give you the layout for smaller cases.
As a performance constraint to prevent pure brute-force approaches, the code should output a result for 18 Q in a reasonable time (approximately 6 hours).

This is a fun problem, and I'm sad that it has no solution, so I made my own!
Requires arguments in the form M P where M is the size of the board and P is the code for the piece
Java - S.java - 1359 Characters
public class S{int s;String p;String e=".";String b;String t;int c;public static void main(String[]args){new S(args);}S(String[] a){s=Integer.parseInt(a[0]);p=a[1];b="";int i;if(p.equals("P")){String r="P";for(i=1;i<s;i++)r+=e;r+="\n";for(i=0;i<s;i+=3){a(r);f(p);a(r);}m(0);}if(p.equals("B")){for(i=0;i<s-1;i++){if(s/2==i)f(p);f(e);}}if(p.equals("N")){for(i=0;i<s;i+=5){f(e);f(e);f("N");f(e);f(e);}m(0);if(s%5==2|s%5==1){m(1);f(p);}}if(p.equals("R")){f(p);for(i=1;i<s;i++)f(e);}if(p.equals("K")){String k="";for(i=0;i<s;i+=3)k+=".K.";k=k.substring(0,s-1);k+=(s%3==0)?e:"K";k+="\n";for(i=0;i<s;i+=3){f(e);a(k);f(e);}m(1);if(s%3==0)f(e);else a(k);}if(p.equals("Q"))for(i=0;i<s*s;i++){try{q(i,0,new String[s][s]);}catch(Exception e){}b=t;}System.out.println(b);}void q(int d,int g,String[][] o) throws Exception{int u=0;int i;if(g==s*s|u>c){if(u<=c){c=u;t="";for(i=0;i<s;i++){for(int j=0;j<s;j++)t+=o[i][j];t+="\n";}}throw new Exception();}int r=(d/s)%s;int c=d%s;if(o[c][r]==null){for(i=0;i<s;i++){try{o[c-r+i][i]=(o[c-r+i][i]==null)?e:o[c-r+i][i];}catch(Exception e){}try{o[i][r+c-i]=(o[i][r+c-i]==null)?e:o[i][r+c-i];}catch(Exception e){}o[i][r]=(o[i][r]==null)?e:o[i][r];o[c][i]=(o[c][i]==null)?e:o[c][i];}o[c][r]="Q";u++;}q(d+1,g+1,o);}void m(int d){b=b.substring(0,(s+1)*(s-d));}void a(String d){b+=d;}void f(String f){for(int i=0;i<s;i++){b+=f;}b+="\n";}}

(Pawns are attacking from left to right)
I couldn't find any proof of the minimum of any domination problem, but my Queen's solver at 8 solves with 5 queens and the others don't seem to be doing too badly (18 queens at 25x25). Someone will have to beat my other solutions to disprove them as minimums. That probably won't be hard!
Here is my de-golfed solution, for anyone interested. It's a bit of a mess... My first thought for doing the Queen's solver was to use backtracking, but I got lazy.
Java - SimpleChessSolver.java - 3496 Characters
(There was once a version which had a whole bunch of different classes, to represent the board, squares, pieces... But it quickly got out of control and was renamed ComplicatedChessSolver.java)
public class SimpleChessSolver {
int size;
String piece;
String period = ".";
String board;
String bestBoard;
int bestCount;

    public static void main(String[] args) {
        new SimpleChessSolver(args);
    }

    SimpleChessSolver(String[] args){
        size = Integer.parseInt(args[0]);
        piece = args[1];
        board = "";
        int index;
        if (piece.equals("P")){
            String periods = "P";
            for (index = 1; index < size; index++){
                periods += period;
            }
            periods += "\n";
            for (index = 0; index < size; index += 3){
                addString(periods);
                fillRow(piece);
                addString(periods);
            }
            trimToSize(0);
        }
        if (piece.equals("B")){
            for (index = 0; index < size - 1; index++){
                if (size/2 == index){
                    fillRow(piece);
                }
                fillRow(period);
            }
        }
        if (piece.equals("N")){
            for (index = 0; index < size; index += 5){
                fillRow(period);
                fillRow(period);
                fillRow("N");
                fillRow(period);
                fillRow(period);
            }
            trimToSize(0);
            if (size%5 == 2 || size%5 == 1){
                trimToSize(1);
                fillRow(piece);
            }
        }
        if (piece.equals("R")){
            fillRow(piece);
            for (index = 1; index < size; index++){
                fillRow(period);
            }
        }
        if (piece.equals("K")){
            String kings = "";
            for (index = 0; index < size; index += 3){
                kings += ".K.";
            }
            kings = kings.substring(0, size - 1);
            kings += (size%3 == 0) ? period : "K";
            kings += "\n";
            for (index = 0; index < size; index += 3){
                fillRow(period);
                addString(kings);
                fillRow(period);
            }
            trimToSize(1);
            if (size%3 == 0) {
                fillRow(period);
            }
            else {
                addString(kings);
            }
        }
        if (piece.equals("Q")){
            for (index = 0; index < size*size; index++){
                System.out.println(bestBoard);
                System.out.println("BlankLine\n");
                try {
                    queenSolve(index, 0, new String[size][size]);
                }
                catch (Exception e) {}
            }
            System.out.println("Final Answer");
            board = bestBoard;
        }

        System.out.println(board);
    }

    void queenSolve(int start, int depth, String[][] board2D) throws Exception {
        int currentCount = 0;
        int index;
        if (depth == size*size || currentCount > bestCount){
            if (currentCount <= bestCount){
                bestCount = currentCount;
                bestBoard = "";
                for (index = 0; index < size; index++){
                    for (int jdex = 0; jdex < size; jdex++){
                        bestBoard += board2D[index][jdex];
                    }
                    bestBoard += "\n";
                }
            }
            throw new Exception();
        }
        int row = (start / size) % size;
        int col = start % size;
        if (board2D[col][row] == null){
            for (index = 0; index < size; index++){
                try{
                    board2D[col - row + index][index] = (board2D[col - row + index][index] == null) ? period : board2D[col - row + index][index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                try{
                    board2D[index][row + col - index] = (board2D[index][row + col - index] == null) ? period : board2D[index][row + col - index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                board2D[index][row] = (board2D[index][row] == null) ? period : board2D[index][row];
                board2D[col][index] = (board2D[col][index] == null) ? period : board2D[col][index];
            }
            board2D[col][row] = "Q";
            currentCount++;
        }
        queenSolve(start + 1, depth + 1, board2D);
    }

    void trimToSize(int additionalTrim){
        board = board.substring(0, (size + 1) * (size - additionalTrim));
    }

    void addString(String toAdd){
        board += toAdd;
    }

    void fillRow(String filler){
        for (int index = 0; index < size; index++){
            board += filler;
        }
        board += "\n";
    }

}

How it works
Other than the queens, the other solutions are very simple. The Knights, Rooks, and Bishops can all be solved by putting a straight line in the correct place. Rooks cover their whole rank, so it works to just put a line anywhere on the board. A row of knights will cover four parallel rows, two in each direction. If there is a row of bishops on approximately (+/- 0.5) the middle row, they can cover every square. A row of pawns covers the parallel rows to their immediate left and right except for the bottom square, so I put a pawn on that square to occupy it. Kings can only cover the 3x3 squares around them, so I just stick Kings such that their squares don't overlap, with overlapping kings added if I need to fill out a size%3 != 0 board.
Queens is a little trickier. My algorithm, which may not be the best, iterates over the board, so that it starts on every square, then puts a queen there. It fills in periods for every square that queen covers, then walks along the board until it finds a square not already occupied by a Q or a period. As I said, this produces the current minimum for a 8x8 board (5 Queens) and I couldn't find a reference for any other board size.


text:
Convert a program to a palindromic program
A palindrome is a string that is the same forwards and backwards, such as "racecar".
Write a program in some language L, that takes any program P1 in language L as input, and outputs a palindromic program P2 in language L that does the same thing as P1.
You do not need to worry about handling input programs with syntax errors.
This is code golf, so the solution with the fewest number of bytes wins.

Can we define the language L?

@GregHewgill Yes. L is the language you choose to write your program in.

In some languages, this is surprisingly tough.

With a turing complete subset of Python, this is a valid entry: x=input();print(x+'#'+x[::-1]). The subset is the set of all programs that don't include newlines.

Perl, 55 54 bytes
undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a;

Reads program source from stdin and writes to stdout.
Result of running on itself:
undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a;

__END__

__DNE__

;a$esrever ralacs,a$tnirp;"n\__DNE__n\".><=a$;/$fednu

+1 for not using comments

I like that it marks the apparent gibberish at the bottom with "DNE" - a common shorthand for "Do Not Erase" used to mark things on chalkboards/whiteboards so that people don't mistake them for unimportant scribblings and wipe them off.

how does it work, I don't know perl, more specifically how does it quine(get the line that it's reversing)?

@Cruncher: __END__ indicates the end of the parseable portion of the script. See http://perldoc.perl.org/functions/END.html For input, <> reads the input from stdin.

@GregHewgill the program source is read through stdin? That's odd. I assume that nothing after END goes through this stream then?

@Cruncher: The program doesn't read its own source. The program takes whatever input you give to it. You can give it itself as input, which is what I did for the example.

@GregHewgill I misunderstood the question a bit. I got it now. I thought it was supposed to palindromize itself

1+ Works in most cases except when program ends with __DATA__ that is read.. eg. print while(<DATA>);\n__DATA__ will change behaviour.

@Sylwester: True. This works for the subset of Perl scripts that don't use __DATA__. :)

Java, 225 bytes
class c{public static void main(String[]a){String s="";java.util.Scanner r=new java.util.Scanner(System.in);while(r.hasNext())s+=r.nextLine()+"\n";s=s.replace("\n","//\n");System.out.print(s+new StringBuilder(s).reverse());}}

Output on itself (when prettified beforehand):
class c {//
    public static void main(String[] a) {//
        String s = "";//
        java.util.Scanner r = new java.util.Scanner(System.in);//
        while (r.hasNext()) s += r.nextLine() + "\n";//
        s = s.replace("\n", "//\n");//
        System.out.print(s + new StringBuilder(s).reverse());//
    }//
}//

//}
//}
//;))(esrever.)s(redliuBgnirtS wen + s(tnirp.tuo.metsyS
//;)"n\//" ,"n\"(ecalper.s = s
//;"n\" + )(eniLtxen.r =+ s ))(txeNsah.r( elihw
//;)ni.metsyS(rennacS.litu.avaj wen = r rennacS.litu.avaj
//;"" = s gnirtS
//{ )a ][gnirtS(niam diov citats cilbup
//{ c ssalc

Problem if comment ending in *. See comment

Python 2, 68 bytes
import sys
x=''.join(l[:-1]+'#\n'for l in sys.stdin)
print x+x[::-1]

Doesn't work if run from IDLE, because you need to generate an EOF character to stop the program from waiting on input.
Output when run on itself:
import sys#
x=''.join(l[:-1]+'#\n'for l in sys.stdin)#
print(x+x[::-1])#

#)]1-::[x+x(tnirp
#)nidts.sys ni l rof'n\#'+]1-:[l(nioj.''=x
#sys tropmi

Thanks to Greg Hewgill for helping to hammer out problems and to golf.

Nice job, beats my kinda lame Python attempt.

@GregHewgill I prefer a nice upvote to a nice comment ;-)

Ok okay... I don't usually vote against myself. :)

@GregHewgill I vote "against" myself a lot. I upvote answers based on their merits, not based on whether or not I answered.

GolfScript, 10 9 bytes
"
}"+.-1%

Quite similar to minitech's solution, but it works well with newlines. It relies on GolfScript's funny (and undocumented) behavior to ignore an unmatched (and uncommented) }, as well as everything that follows it.
It will fail if the input contains an unmatched {, but that would technically constitute a syntax error.
How it works
"
}"   # Push the string "\n}".
+    # Concatenate it with the input string.
.    # Duplicate the modified string.
-1%  # Reverse the copy.

Example
$ echo -n '1{"race{car"}
> {"foo\"bar"}
> if#' | golfscript make-palindrome.gs
1{"race{car"}
{"foo\"bar"}
if#
}}
#fi
}"rab"\oof"{
}"rac{ecar"{1
$ echo '1{"race{car"}
> {"foo\"bar"}
> if#
> }}
> #fi
> }"rab"\oof"{
> }"rac{ecar"{1' | golfscript
race{car

Try 1\n2# (\n would be an actual newline character) as your input.

@Quincunx: Pesky comments... A newline before the curly bracket should fix that.

Before and after. Need to remain a palindrome.

@Quincunx: Of course. It should work now.

x86 machine code on DOS (.com file) - 70 bytes
Dealing with .COM files, creating a palyndrome is easy - since the COM "loader" just puts the content of the file at address 100h and jumps there, the program must already hardcode its end somehow and ignore everything after it, so we can just append the reverse of the first N-1 bytes (only caveat: if the program somehow tries to do tricks with the length of file everything breaks).
Here is the hex dump of my .COM-palyndromizing .COM:
00000000  31 db 8a 1e 80 00 c6 87  81 00 00 ba 82 00 b8 00  |1...............|
00000010  3d cd 21 72 30 89 c6 bf  ff ff b9 01 00 ba fe 00  |=.!r0...........|
00000020  89 f3 b4 3f cd 21 3c 01  75 18 b4 40 bb 01 00 cd  |...?.!<.u..@....|
00000030  21 85 ff 75 e5 89 f3 f7  d9 88 ee b8 01 42 cd 21  |!..u.........B.!|
00000040  eb d8 47 74 f0 c3                                 |..Gt..|

It takes the input file on the command line, and writes the output on stdout; the expected usage is something like compalyn source.com > out.com.
Commented assembly:
    org 100h

section .text

start:
    ; NUL-terminate the command line
    xor bx,bx
    mov bl, byte[80h]
    mov byte[81h+bx],0
    ; open the input file
    mov dx,82h
    mov ax,3d00h
    int 21h
    ; in case of error (missing file, etc.) quit
    jc end
    ; si: source file handle
    mov si,ax
    ; di: iteration flag
    ; -1 => straight pass, 0 reverse pass
    mov di,-1
loop:
    ; we read one byte at time at a bizarre memory
    ; location (so that dl is already at -2 later - we shave one byte)
    mov cx,1
    mov dx,0feh
    mov bx,si
    mov ah,3fh
    int 21h
    ; if we didn't read 1 byte it means we either got to EOF
    ; or sought before the start of file
    cmp al,1
    jne out
    ; write the byte on stdout
    mov ah,40h
    mov bx,1
    int 21h
    ; if we are at the first pass we go on normally
    test di,di
    jnz loop
back:
    ; otherwise, we have to seek back
    mov bx,si
    ; one byte shorter than mov cx,-1
    neg cx
    ; dl is already at -2, fix dh so cx:dx = -2
    mov dh,ch
    mov ax,4201h
    int 21h
    jmp loop
out:
    ; next iteration
    inc di
    ; if it's not zero we already did the reverse pass
    jz back
end:
    ret

Tested on itself and the solutions to a previous question seems to work fine in DosBox, some more extensive testing on "canonical" DOS executables will follow.

GolfScript, 8
.-1%'#'\

Doesn’t handle newlines, but nobody uses those in GolfScript.

Using newline in string literals can be used quite often ;-)

Bash+coreutils, 39 bytes
f="`cat`
exit"
echo "$f"
tac<<<"$f"|rev

Reads from STDIN and outputs to STDOUT:
$ cat hello.sh
#!/bin/bash

echo 'Hello, World!'

$ ./palin.sh < hello.sh
#!/bin/bash

echo 'Hello, World!'
exit
tixe
'!dlroW ,olleH' ohce

hsab/nib/!#
$

@user23013  Seems to work fine.  At least a simple test like ( echo 'Hello, World!' ).  bash pretty much ignores everything after the exit.

Javascript (ES6) Multi-line - 71
Kinda sorta stole Quincunx's comment method here:
alert((x=prompt().replace(/\n/g,'//\n')+'/')+[...x].reverse().join(''))

Single line - 49
alert((x=prompt()+'/')+[...x].reverse().join(''))

C++, 214 209 bytes
#include<cstdio>
#include<stack>
int main(){std::stack<char>s;int c;while((c=getc(stdin))>EOF){if(c=='\n')for(int i=2;i;i--)s.push(putchar('/'));s.push(putchar(c));}while(s.size()){putchar(s.top());s.pop();}}

Result of running on itself:
#include<cstdio>//
#include<stack>//
int main(){std::stack<char>s;int c;while((c=getc(stdin))>EOF){if(c=='\n')for(int i=2;i;i--)s.push(putchar('/'));s.push(putchar(c));}while(s.size()){putchar(s.top());s.pop();}}//

//}};)(pop.s;))(pot.s(rahctup{))(ezis.s(elihw};))c(rahctup(hsup.s;))'/'(rahctup(hsup.s)--i;i;2=i tni(rof)'n\'==c(fi{)FOE>))nidts(cteg=c((elihw;c tni;s>rahc<kcats::dts{)(niam tni
//>kcats<edulcni#
//>oidtsc<edulcni#

Fail when continuation char '' is used. Try [http://ideone.com/TCZHr9]

@edc65: Yeah, I thought about that later. The only obvious way I can think of to handle that would be to unfold the folded lines first.

can be done at small cost - se my C answer

C 168 175
Correctly handles escaped newline inside source code
Edit 1 fixed bug when last newline missing
Edit 2 fixed bug when line inside comment ends with *: add a tab char before the // comment
(and golfed more)
b[999999];main(c,z){char*p,for(p=b;(*p=c=getchar())>=0;z=c,p++)c-10||(z-92?*p++=9,*p++=47,*p++=47,*p=c:(p-=2));*p=47;for(p=b;*p;)putchar(*p++);for(;p>b;)putchar(*--p);}

C99 Standard, valid code, many warnings
Ungolfed
b[999999]; // working buffer ~ 4M on 32 bit machine, max source size
// c is current char, z is previous char,
main(c,z) // z  start as argv pointer, will be out of char range
{
  char *p;
  for(p = b;
      (*p=c=getchar()) >= 0; // while testing EOF copy char to buffer set c variable
      z=c, p++) // at end loop increment p and set previous = current
  {
      c-'\n' || // if newline
       (z - '\\' // check if escaped
          ? *p++='\t',*p++='/',*p++='/', *p=c // if not escaped, add tab,/,/ and newline
          : (p-=2) // if escaped, drop both escape and newline
       );
  }
  *p='/'; // if last newline missing, will add a comment anyway
  for(p=b;*p;) putchar(*p++); // ouput buffer
  for(;--p>=b;) putchar(*p); // outbut buffer reversed
}

there is a little bug in it. try /* *<NL> */int main(){}

Brainfuck, 749 without whitespace (not golfed)
This produces brainfuck programs which mirrored palindromes, i.e. they are are mirror images of themselves.
++++++++++
[->++++>+++++++++<<]>+++.>+..<.>++.
>>>>+[>,]<-[+<-]
>[
  [-<+<<+>>>]
  +<-------------------------------------------[-<+>>[-]<]>[-<<<.>>>]
  +<<-[->+>[-]<<]>>[-<<<.>>>]
  +<-[-<+>>[-]<]>[-<<<.>>>]
  +<<-[->+>[-]<<]>>[-<<<.>>>]
  +<--------------[-<+>>[-]<]>[-<<<.>>>]
  +<<--[->+>[-]<<]>>[-<<<.>>>]
  +<-----------------------------[-<+>>[-]<]>[-<<<.>>>]
  +<<--[->+>[-]<<]>>[-<<<.>>>]
  <[-]>>
]
<<<<[<]
<--.<.>++..--..<.>++.
>>[>]
<[
  [->+>>+<<<]
  +>-------------------------------------------[->+<<[-]>]<[->>>.<<<]
  +>>-[-<+<[-]>>]<<[->>>.<<<]
  +>-[->+<<[-]>]<[->>>.<<<]
  +>>-[-<+<[-]>>]<<[->>>.<<<]
  +>--------------[->+<<[-]>]<[->>>++.--<<<]
  +>>--[-<+<[-]>>]<<[->>>--.++<<<]
  +>-----------------------------[->+<<[-]>]<[->>>++.--<<<]
  +>>--[-<+<[-]>>]<<[->>>--.++<<<]
  >[-]<<
]
<--.<.>++..<.

Given a program it outputs
+[[+]PROGRAM[+]][[+]MIRROR[+]]+

with PROGRAM and MIRROR replaced by the program (without non-brainfuck characters) and its mirror image.

C# - 174
using System;using System.Linq;class c{public static void Main(){var a="";var b="";while((a=Console.ReadLine())!="")b+=a+"//\n";Console.Write(b+string.Concat(b.Reverse()));}}

Test Input:
using System;
using System.Linq;
class c
{
    public static void Main()
    {
        var a = "";
        var b = "";
        while ((a = Console.ReadLine()) != "")
            b += a + "//\n";
        Console.Write(b+string.Concat(b.Reverse()));
    }
}

Test Output:
using System;
using System.Linq;
class c
{
    public static void Main()
    {
        var a = "";
        var b = "";
        while ((a = Console.ReadLine()) != "")
            b += a + "//\n";
        Console.Write(b+string.Concat(b.Reverse()));
    }
}

// }
// }
// ;)))(esreveR.b(tacnoC.gnirts+b(etirW.elosnoC
// ;"n\//" + a =+ b
// )"" =! ))(eniLdaeR.elosnoC = a(( elihw
// ;"" = b rav
// ;"" = a rav
// {
// )(niaM diov citats cilbup
// {
// c ssalc
// ;qniL.metsyS gnisu
// ;metsyS gnisu

I think you may have misunderstood one of the instructions. Your program should be able to take any program as input, and write out a palindromic program that does the same thing as the original program.

It can.. If I input the C++ code from your answer, it returns exactly what you have.

All your program does is reverse its input. The output of your program is not a complete palindromic program.

Oh yeah, i get ya. Updated - better now?

Well, almost. Now it works for your program (with the // at the end of each line), but would not work for any other program. It's a very simple change to make it work from this point, though.

Ahh yes. added it. //\n

Yup, that's it. Your test output should have the // at the end of each line now though.

PHP, 96 bytes
function a($b){
    echo $c = "a('$b')" . strrev("a)'" . $b . "'(");
    $d = substr($c, 0, strlen($b) + 5);
    eval("$d;");
}

Sample Usage:
a('apple'); // echoes a('apple')('elppa')a until your bytes get exhausted

This is nothing clever. It's just a simple piece of code that does the job... I was in a mood for playing.
I do know that this code is rife with bad programming practices!
Finally, I will gladly accept any criticism and edits to this code!

Welcome to Code Golf. This is a function, not a program. See the other answers, they provide good examples.

Cobra - 134
class P
    def main
        i=List<of String?>(Console.readLine.split('\n'))
        print '/#\n[i.reversed.join("\n")]\n#/#\n[i.join("\n")]\n#/'

Racket 133
(require srfi/13)(let((r read-line)(w display))(let l((i(r)))(when
(not(eq? eof i))(w i)(w";\n")(l(r))(w"\n;")(w(string-reverse i)))))

Ungolfed (but still very imperative):
(require srfi/13)
(let recurse ((instr (read-line)))
  (when (not (eof-object? instr))
    (display instr)
    (display ";\n")
    (recurse (read-line))
    (display "\n;")
    (display (string-reverse instr))))

Output when given the ungolfed version as input:
(require srfi/13);
(let recurse ((instr (read-line)));
  (when (not(eof-object? instr));
    (display instr);
    (display ";\n");
    (recurse (read-line));
    (display "\n;");
    (display (string-reverse instr))));

;))))rtsni esrever-gnirts( yalpsid(
;)";n\" yalpsid(
;))enil-daer( esrucer(
;)"n\;" yalpsid(
;)rtsni yalpsid(
;))rtsni ?tcejbo-foe(ton( nehw(
;)))enil-daer( rtsni(( esrucer tel(
;)31/ifrs eriuqer(

source: Stack Exchange

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

sort: votes


text:
Print 123454321 without if statements and using only 2 variables
The challenge: Write a function, that delivers following output: "1 2 3 4 5 4 3 2 1".
Kids stuff? Of course. But here's the point:

You only can use: 1 for loop, 2 int variables.
You must not use: IF terms, another function, ...
Do not hardcode the output

There are also some more restrictions to make this harder:

No functions like abs or sth. else are allowed! (Yep, it's possible)
No static output like echo "1 2 3 4 5 4 3 2 1"

This is a popularity-contest, so the answer with the most votes wins!

I think the function you're looking for is abs. Python: for i in range(1, 10): print 5-abs(5-i),

Just to give folks some background this was a "do my homework" question on SO 10 min ago...

@monocell Most of the languages he gets answers in will be too obscure to be useful.. let alone readable.

So easy: print "1 2 3 4 5 4 3 2 1"

@Mhmd: That answer fails the stipulation "do not hard code the output"

@monocell it was / is a facebook challenge.. Not my homework ;)

I think 6-%:*:_5+i.11 (J) is technically valid, but I won't post it, for the silly amount of rules it breaks/bends.

This question appears to be off-topic because it looks too much like a homework assignment or "brain twister".

Fun fact! If you take the binary representation of the unicode string "1 2 3 4 5 4 3 2 1" and convert it into a base 10 number, it becomes 3922771099780750640552066885681. I wanted to generate this in some epic way and cout it with No Comment's @ operator, but turns out, it's prime. What.

@Trimsty what if you append a newline?

@JanDvorak 62764337596492010248833070170906, which is not prime: 2 * 3 * 9587 * 911979101447 * 1196448709617859. :c

for(x=11111;x<=11111;x*=x);printf("%d\n", x);

I don't understand why OP's accepted answer is as is, as it doesn't comply with the rules.

Even if it's a 'solve my homework' type of question, the question is interesting and some creative answers can be given. Why do we need to judge intentions/purpose while the problem set is valid?

Cobra
Really, this is quite trivial.
class Program
    def main
        for i in 10, Console.write(5 - Math.abs(5 - i))

Or
class Program
    def main
        v as int = 123454321
        for i in v.toString, Console.write(i)

Or even simpler
class Program
    def main
        print 1, 2, 3, 4, 5, 4, 3, 2, 1

But if you insist on following the question exactly:
class Program
    def main
        num as int = 123454321
        for i in '[num]'
            Console.write(i)
            Console.write(' ')

This uses only one integer variable, only one loop, and the only function explicitly called is used for output.

I'm not sure whether Math.abs constitutes "another function" which is forbidden. haha

I was about to submit your latest example to lol

@justhalf latest version only explicitly calls the print function.

The last 3 versions appear to fail the stipulation "do not hardcode the output"

Doesn't seem particularly right, since these solutions either use hard-coded data or use another function (Math.abs).

Python
One for loop, one int variable (i), no if, no other functions (unless you consider print or +-*/ as functions, haha):
for i in range(9):
    print i+1 - 2*(i//5)*(i-4),

This one gets my vote as it complies with ALL the rules, i.e. does not use any functions or extra variables. I think we can call print a procedure as we are not interested in its return value (I don't know if it returns a value in Python.) // is integer division in python? hmmm

Steveverrill,  '//' one of the slashes is likely a directive for the print function to ignore the other slash.  I think the idea here is that print functions will think the slash is a file system slash instead of a math operator.  The double slash clears this up.

@Marc // is integer divison in python. You're thinking of \\\, where one backslash escapes the other.

@steve Integer division is the default in python 2, in python 3 you specify it manually with //.

I'm working with Python 2 and Python 3 sometimes, so to be sure that I'm doing integer division, I always use //, because it works in both Python 2 and Python 3.
Thanks for all the votes!

C
No function, no hidden IF (abs, min, etc.)
#include <stdio.h>

int main()
{
int sum=0;
for (int i=3; i<12; i++)
    {
    sum += 1-2*(i/8);
    printf("%d\n", sum );
    }
}

Explanation :
The 4th bit of i is the heart of the trick : it's 0 for [3,7] and 1 for [8,11].
i/8 gives the value of the bit (just like i>>3) for i in [3,11] it gives : 0, 0, 0, 0, 0, 1, 1, 1, 1
1-2*(i/8) is simple math to obtain 1, 1, 1, 1, 1, -1, -1, -1, -1
+= is used to sum the values

This is another answer that fully complies with all the rules. I was thinking on something like this, but at the end I used another approach since why two int variables when you can only use one? :D

Why hopping when you can use your both legs? :o) But I have to admit that your answer is better.

I like your analogy. +1

Javascript, 32 characters
+new Date(1970,0,2,11,17,34,321)

edit:
not timezone-dependant, 42 chars
+new Date(Date.UTC(1970,0,2,10,17,34,321))

I get 107254321 http://jsfiddle.net/KnLJL/

what browser are you using? it works for me in firefox and chrome.

Firefox 24.3.0.

sorry, dunno. works with firefox 29.

Chrome 35, I get 145054321.

This answer is probably timezone-dependent.

and hard-coded.

of course... to make it timezone-independent, it'd have to be +new Date(Date.UTC(1970,0,2,10,17,34,321))

Please add that to your answer

Delphi XE3
I dont think this requires much explaining right?
function p:string;
var
  i:integer;
begin
  for I:=1 to 4 do
    Result:=Format('%s%d ',[Result,I]);
  Result:=Format('%s%d%s',[Result,5,ReverseString(Result)]);
end;

In case it does.
Function loops from 1 to 4, and keeps adding the number + [space].
Then it adds I again which became 5 which made it quit the loop and adds the reversed string as it is now.
Variation
function p:string;

const
      s='123454321'
    var
      i:integer;
    begin
      s:='123454321';
      for I:=1to Length(s) do
        Result:=Format('%s %s',[Result,s[i]]);
      Exit(Trim(Result));
    end;
This might seem hardcoded but the constant doesnt have the spaces that are required.
Although it might seem impossible but there is a solution that is even lamer than this.
function p:string;
const
  s='123454321'
begin
  result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9]])
  {or}
  result:=Format('%s %s %s %s %s %s %s %s %s',[s[1],s[2],s[3],s[4],s[5],s[4],s[3],s[2],s[1]])
 {OR!}
  result:=Format('%d %d %d %d %d %d %d %d %d',[1,2,3,4,5,4,3,2,1])
end;

I would argue that to reverse a string you require another loop. But let OP decide on this.

hmm.. Fair point sir. But yes let the OP decide and hope he agrees with it :P ill see if I can come up with something else.

Golfscript, 16 characters
6,(;)1$-1%++' '*

I assume this is meant to be a code golf?
No variables. All data (two arrays and a number) is on the stack. The only loops are implicit ones.
Online demonstration: http://golfscript.apphb.com/?c=NiwoOykxJC0xJSsrJyAnKg%3D%3D

C++: Works finely in VC 11.0
#include <iostream>
#include <cstring>
#include <vector>
#include <conio.h>
#include <algorithm>

using namespace std;

bool called = false;
int main();
int f() {
    called = true;
    typedef vector<int>::iterator _v_interate;
    int l;
    static bool d;
    vector<int> iVector;
    for(l = 1; (true); (!d) ? l++ : l--) {
        _v_interate i = find(iVector.begin(), iVector.end(), 4);
        _v_interate i2 = find(iVector.begin(), iVector.end(), 3);
        _v_interate i3 = find(iVector.begin(), iVector.end(), 2);
        _v_interate i4 = find(iVector.begin(), iVector.end(), 1);
        _v_interate i5 = find(iVector.begin(), iVector.end(), 5);
        d =  (i != iVector.end()) &&  (i2 != iVector.end()) &&  (i3 != iVector.end()) &&  (i4 != iVector.end()) ? 1 : 0;
        iVector.push_back(l);
        cout << l << " ";
        (d && (l==1) ? main() : 0);
    }
    return 0;
}

int main() {
    !called ? f() : 0;
    _getch();
    exit(0); // Removing the exit(0) causes an infinite loop; I don't know why.
    return 0;
}

A simple solution:
#include <iostream>

void main() {
  cout << "1 2 3 4 5 4 3 2 1";
}

Perhaps I'm mistaken on the count, but I count 10 variables in your first solution which is about 5x more than the maximum. And your second solution fails the "do not hardcode the output" stipulation.

Perl
Version 1:
for(1..9){
    $x = ($_%18 - 5);
    print 5 - ($x, -$x)[$x < -$x] . " ";
}

Version 2:
for(1..9){
    $x = ($_%18 - 5);
    $x =~ s/-//;
    print 5 - $x . " ";
}

For both versions: 1 For loop, and 2 variables, $_ and $x, and I'm not using if or any other function.

Ruby - 47 chars
(1..4).to_a.push((1..5).to_a.reverse).join ' '

Edit - 33 chars
[*(1..4),[*(1..5)].reverse]*' '

to_a can be simplified using splats since Ruby 1.9.x or so. Also, look up Array#*

@JanDvorak Made it 33 chars

Java
Used one loop and the loop variable. Added a constant for the upper bound.
public class Test {
   private static final int BOUND = 5;
   public static void main(String[] args) {
      for (int i = 1; i < BOUND * 2; i++) {
         System.out.print(i - (2 * ((i % BOUND) * (i / BOUND))) + " ");
      }
   }
}

Brainfuck, 83
+++++++[>+++++++>+++++++>+++++++>+++++++>+++++++<<<<<-]>.>+.>++.>+++.>++++.<.<.<.<.

Only 1 loop, no ifs (if you don't count the loop as an if). No int variables.

JavaScript
function f(){
  for ( var i=1,j=5; j>0; ++i>j&&(--i,--i,--j) )
    console.log(i);
}

for(a=b=0;b++<9;)console.log(a+=(b<6)-(b>5))

How does this work? ++i>j&&(--i,--i,--j)

C
Not sure if it follows exactly the rules but my answer is below
int main()
{
    int x;
    for(x = 123454321; x > 10; x /= 10)
    {
        printf("%d ", x % 10);
    }
    printf("%d", x);
    return 0;
}

Run the code

Well, I guess the fastest and most naive solution (in Python) would be:
' '.join (str(x) for x in range(1,6)) + ' ' + ' '.join (str(x) for x in range(4,0,-1))

Two range will constitute as two loops, which is against the rule, I guess.

@justhalf I was rather relying on range not counting as a loop :p

And by the way the fastest solution in Python should be print '1 2 3 4 5 4 3 2 1' :D

Javascript
This might not be the best and fastest way to do it, but I like what I came up with.
z = '';
for (x = 1; x <= 5; x++) { // Don't need a loop, but hey, I like loops!
    z += x + ' '; // Creates "1 2 3 4 5 "
}
document.getElementById('result').innerHTML = z + z.split("").reverse().join("").substring(2, 10);
// "1 2 3 4 5 " + " 4 3 2 1"

Result:
1 2 3 4 5 4 3 2 1

You can see it in action Here!

Uses the function String.prototype.reverse

As 2.0
var num:Int = 11111;
alert(num*num);

C
#include <stdio.h>

int main(void) {
    int i;
    for (i = 21911761; i > 0 && printf("%d", i&7); i = i>>3)
        i > 1 && printf(" ");

    return 0;
}

Java, 79 chars (standalone: 131 chars)
int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));}

Uses two ints, and no other variables. No if statements, just a for loop for evaluation. This will run on its own when put in the main(String[] args) method in a class, or in any other function. The full code, including class declaration and method, is 131 chars.
public class M{public static void main(String[]a){int b=-1,i=1;for(;i>0&(i<5||(b=1)==1);i-=b){System.out.print(i+(b==i?"":" "));}}}

While I'm at it:
PHP, 70 chars (standalone: 78 chars)
$b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");}

Uses same method as Java. Standalone script is 62 chars:
<?php $b=-1;for($i=1;$i>0&($i<5||($b=1)==1);$i-=$b){echo$i.($b==$i?"":" ");}?>

I think that the ternary operator would count as an if statement

Ah, you're right. I didn't notice that.

Fortran 90: 60
integer::j(9)=5;do i=1,4;j(i)=i;j(10-i)=i;enddo;print*,j;end

If you wanted it formatted slightly better, I can add a few characters to make the print statement print'(9i2)',j. Ungolfed & written properly, this is
program main
   implicit none
   integer :: i, j(9)
   j = 5
   do i=1,4
      j(i) = i
      j(10-i) = i
   enddo
   print *,j
end program main

Powershell
((1..9)|%{
    $_ = ($_%18-5)
5 - @($_,-$_)[$_ -lt -$_]
})-join ' '

1 variable, no if, no functions (unless you were to count -join which is just for displaying the data...
Explanation: Loops from 1 to 9, then for each value calculates the reminder of the current value by 18, then subtracts 5 and assigns it to the currently used $_ variable. After that it evaluates $_ < -$_ (this is to handle negative values), and uses the result (False/True) to get the value from the array @($_,-$_), therefore making sure we always get a positive number in this case, after that it subtracts this number to 5 and finally joins the results with space.

Since I can't add an answer, another option would be "$(1..5+4..1)"

Scala, 53
(4 to 12).foldLeft(1)((a,b)=>{print(a);a+1-2*(b/8)})

I stole the neat bit shifting idea from @cpri
http://scalafiddle.net/console/3b3fff6463464959dcd1b68d0320f781

This fits the rules better:
(1 to 9).map(x => 5-Math.abs(5-x)).mkString(" ")

If you found a shorter code, you can [edit] your answer to update the code.

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


text:
What a wonderful world
The challenge is programming a program that prints following lyrics of Louis Armstrong's What A Wonderful World with as few characters as possible. The key is obviously kind of a 'compression'. I encourage to use and enhance ideas of previous answers, but please declare if you do so!
Rules:
No information can be stored externally, everything must be contained in the code itself.
Only ASCII characters allwed in the code.
The text must be reproduced exactly.
Output to console or text file.
I see trees of green, red roses, too,
I see them bloom, for me and you
And I think to myself
What a wonderful world.

I see skies of blue, and clouds of white,
The bright blessed day, the dark sacred night
And I think to myself
What a wonderful world.

The colors of the rainbow, so pretty in the sky,
Are also on the faces of people going by.
I see friends shaking hands, sayin', "How do you do?"
They're really sayin', "I love you."

I hear babies cryin'. I watch them grow.
They'll learn much more than I'll ever know
And I think to myself
What a wonderful world

Yes, I think to myself
What a wonderful world

PS: Why I think this is different to other encoded songs: Longer text; ASCII-only; a lot of repeating text/similar text.
EDIT: FEWEST of course. Ending will be 22th of June!

This is shorter than the rickroll, which was also ASCII-only with lots of repetition. The same techniques will be applicable.

Flawr, I think you mean as few characters as possible. not as many  @PeterTaylor duplicate or not, this is a much better song than http://codegolf.stackexchange.com/q/6043/15599 On the other hand, if you like Rick Astley's music, check out Stacey Solomon's x-factor version of Wonderful World on youtube. (Nobody thought a girl with that personality would sing like that.)

@steveverrill yes of course, thank you.
Peter_Taylor As far as I understand you could use any UTF-8 characters in the rickroll.

@PeterTaylor As far as I understand you could use any UTF-8 characters in the rickroll?

Cobra - 585
Still many improvements to be made
class P
    def main
        i='I see '
        f='s of '
        w=' I think to myself\nWhat a wonderful world'
        a='\nAnd[w]'
        t=' the '
        s=' sayin\', "'
        print "[i]trees of green, red roses, too,\n[i]them bloom, for me and you[a].\n\n[i]skie[f]blue, and cloud[f]white,\nThe bright blessed day,[t]dark sacred night[a].\n\nThe colors of[t]rainbow, so pretty in[t]sky,\n are also on[t]face[f]people going by.\n[i]friends shaking hands,[s]How do you do?\"\nThey're really[s]I love you.\"\n\nI hear babies cryin'. I watch them grow.\nThey'll learn much more than I'll ever know\nAnd[w]\n\nYes,[w]"


text:
Check for occurences of string in other string
Challenge
I'm sure you read the title, and came in to farm your rep, thinking its kids' stuff, but think again! You have to challenge each other in the shortest code to count the occurences of a string in another. For example, given the following input:

aaaabbbbsssffhd

as a string, and the string

s

should output

3

Rules
Just before you smile and say, "Hey, I'll use ----," read this:

No use of external libraries, or your language's API. You have to implement it manually. Which means you can't use your language's built-in function or method for counting occurences
No file I/O
No connecting with a server, website, et cetera
In a case of `ababa`, where it starts with `aba` and if you read the last 3 letters it's also `aba`, you only count one*

Thank you @ProgramFOX for that (the last rule)!

*Hint: When you count occurences, you can remove the ones you counted to avoid disobeying this rule
I think the last 2 rules are just for rule benders!
Winning Criterion
As previously stated the winner is the code with the less bytes used. The winner will be announced five days later (15 June 2014)
My Small Answer
Here's my C++ answer, where it assumes that the li variable holds the string to check occurences in, and l is the string to look for in f:
Ungolfed
int c = 0;
while (li.find(lf) != string::npos)
{
    int p = li.find(lf);
    int l = p + lf.length() - 1;
    for (p = p; p <= l; p++)
    {
        li[p] = static_cast<char>(8);
    }
    ++c;
}

Of course, to use std::string, you have to include the string header file!
Golfed
int c=0;while(li.find(lf)!=string::npos){int p=li.find(lf);int l=p+lf.length()-1;for(p=p;p<=l;p++){li[p]=static_cast<char>(8);}++c;}

Result
The variable c is going to be the value of how many times the string was found

                                                                          Enjoy!
Winner
After a long wait @Dennis answer wins with only 3 bytes, written in GolfScript

Should we count the same character twice? For example, if the input is ababa and aba, should we output 1 or 2? The third a is both the end of the first aba and the begin of the second aba.

Does language's API mean libraries that can be imported (that come with the language) or methods of builtin datatypes or commands themselves?

Does it need to deal with strings longer than s for matching? If not: I have a 5 char J solution: +/a=b

Does input come through variables or STDIN?

@ProgramFOX Sorry, forgot to out that in... You should output 1. Thanks for the pointers!

@Synthetica To your utter dismay, it should be able to handle almost any string length ;)

@TheRare It is not specified, use what you want, but don't add the bytes used by input in calculating total bytes...

@TheRare What I mean is if your language has a built-in method or function for this purpose, you are not permitted to use it. The whole point is writing your own, in the shortest code...

Edit all that info in and I'll give you a +1.

Function or program?

@KyleKanos Well, this challenge is a lot more free than others: you choose!

GolfScript, 3 bytes
/,(

Assumes string and substring are on the stack.
Try it online.
How it works
/  # Split the string around occurrences of the substring.
,  # Get the length of the split array.
(  # Subtract 1.

Impressive.. But I have a small question, did you learn GolfScript just for code golf and solving code problems?

I did, but I use it occasionally for other tasks by now. Need an ASCII table? golfscript <<< '127,32,-""+' is faster than opening a web browser.

@Dennis [win key] jqt [return] a. [return] is even quicker ;)

@Synthetica: Well, it was just an example. But jqt sounds interesting. What is it?

@Dennis It's the standard J console that comes with J (it's one of those graphical consoles, like the iPython QTConsole)

@Synthetica: jc <<< a. seems to work as well. Learning J is still on my to-do list...

@Dennis Could be, I'm a gamer, so basically stuck on Windows. Also: learning GolfScript is still on mine as well.

@Synthetica I put it off for a good long while too. When I finally got around to it, it turns out there wasn't anything to learn. I do find often find myself writing out a phantom stack as I go, though

JavaScript 32
Nothing really interesting here...
(p=prompt)().split(p()).length-1

split main purpose is to create an array from a string using the delimiter in argument.

split() isn't part of "your language's API"?

it is but its purpose is not to count occurrences of a string... so where is the limit of authorized APIs ?

@Michael I apologize of being vague, this is acceptable.. I edited the question to rephrase to "you can't use your language's built-in function or method for counting occurences", so if it is not intended for the purpose of the question, you can use it...

@404NotFound Good to know ... this is my answer too then? :) ... (+1)

This is the only answer which doesn't assume that the vars have already been initialized, so you've got my upvote. If you assumed the vars were initialized like all the other answers, you would've gotten a.split(b).length-1 19. Maybe @svidgen should clarify initialization in the question.

J (7)
No use of external libraries Check! , or your language's API. Check...? I don't know what an language API is. You have to implement it manually Check!
No file I/O Check!
No connecting with a server, website, et cetera Check!
+/a E.b

How it works:
E. is WindowedMatch: the J Refsheet gives 're' E. 'reread' as example. This gives 1 0 1 0 0 0. Then, the only thing left to do is simply adding this with +/ (basically sum).
I don't think this counts as using your language's built-in function or method for counting occurences, but that's disputable.
EDIT:
Just to be clear:
   +/'aba'E.'ababa'
2

I thought ababa -> aba was to return 1?

@KyleKanos It was, but the author specifically said @Synthetica Absolutley go for it! when I asked him, so I suppose it's okay.

Python 2.x - 49 23 22 bytes
This is assuming variable input is okay. Both strings can be of any length.
Shortened @avall.
a='s'
b='aaaabbbbsssffhd'
print~-len(b.split(a))

49 bytes version, counts every instance of the substring ('aba' is in 'ababa' twice).

a='s'
b='aaaabbbbsssffhd'
print sum(a==b[i:i+len(a)]for i in range(len(b)))

Worked with every test I put it in...

And language's API means you have to use your own function or method, not use the language's built-in way to do it (if it has one, I'm a C++ programmer;( )

Well the second one absolutely is language's own method for it. Also, the first one outputs 3 if a='aa' and b is the same. Is that okay?

Yes, absolutely

Also, it outputs 2 for the a='aba'; b='ababa' case.

@404NotFound If this is acceptable, I have a 7-byte J solution for you.

@Synthetica J is awesome, but it hurts my head. Python is clean, but takes so much space. I'm being torn apart by wanting both.

@TheRare I love both, I'm actually working on a library to unite both (J control structures and trains hurt my head, and I absolutely love Python's synthax/control structures and such).

@Synthetica PYG is nice, but I feel too dirty when using it.

@TheRare Oh, I'm not talking about PYG (rarely use it nowadays, only in chalenges that have me use itertools). I'm just working on some nice J bindings for Python, that are actually supposed to be suitable for an production environment.

@Synthetica I understood that, just came to my mind.

Let us continue this discussion in chat.

@Synthetica Absolutley go for it!

You can save one byte changing print X-1 statement to print~-X

@avall Interesting. I always forget Python has unary operators.

C# - 73
//a = "aba";
//b = "ababa";

Console.Write(b.Split(new string[]{a},StringSplitOptions.None).Length-1);

// output = "1"

It's wrong! aba appears twice in ababa: aba ba ab aba.

@Runemoro "In a case of ababa, where it starts with aba and if you read the last 3 letters it's also aba, you only count one*" << In the rules..

Oh, didn't read...

Powershell 32
($args[0]-split$args[1]).count-1

Works like this:
PS C:\MyFolder> .\ocurrences.ps1 ababa aba
1

Explanation: Uses -split to separate the first argument by the second one, returns the size of the array resulting from the split (minus 1)

Mathematica 26  23
Works like Dennis' algorithm, but wordier:
Length@StringCases[a,b]

Three chars shaved off by Szabolics.

Length@StringCases[a,b] is shorter.  This problem is not well specified because if we're not allowed to use StringCount, it's not clear whether any of the other builtin String* functions should be allowed either ... they're all based on the same underlying code.

Thanks. I forgot about StringCases. It was unclear to me what the OP meant by the language's API.

Using the new composition operator in Mathematica 10, we could even just write a function as Length@*StringCases.  This is shorter than Length@StringCases[##]& if we were to go for just writing a function but not actually apply it to a and b.

Applescript, 106 bytes
Applescript is a fun, but silly language to golf in.
on run a
set AppleScript's text item delimiters to (a's item 1)
(count of (a's item 2)'s text items)-1
end

Run with osascript:
$ osascript instr.scpt s aaaabbbbsssffhd
3
$

Cobra - 25
print a.split(b).length-1

K/Kona 6
+/y~'x

where x is the string and y the substring. ~ is the negate operator, with ', it is applied to every element in x; it will return 0 if it does not match and 1 if it does match. Since it is applied element-wise, the result of y~'x is a vector, the +/ then sums the result giving the total number of occurrences.
Unfortunately, this method requires that y is only one character, otherwise we will be comparing a multi-character string to a single character string, resulting in a length error.

C# - 66 Bytes
//s = "aba"
//t = "ababa"

Console.Write(t.Split(new[]{s},StringSplitOptions.None).Length-1);

//Output: 1

lol. That's basically my answer. Usually on this site, if you cant come up with something different than an existing answer, you can give hints to the existing answer on how to save a few extra bytes.

@malik Listen, I wasn't able to comment at that time. Otherwise I'd commented on your answer. I'm willing to take my answer down, if you want to.

Fair enough. I don't mind either way. I was just letting you know.

C 130 120
Note: will probably crash if called with incorrect arguments.
r;main(int c,char**a){char*p=*++a,*q,*t;while(*p){for(q=a[1],t=p;*q&&*q==*t;q++)t++;*q?p++:(p=t,r++);}printf("%d\n",r);}

Ungolfed (kinda):
int main(int argc, char *argv[]) {
    int result = 0;
    char *ptr = argv[1];
    while (*ptr) {
        char *tmp, *tmp2 = ptr;
        // str(n)cmp
        for (tmp = argv[2]; *tmp; tmp++, tmp2++)
            if (*tmp != *tmp2)
                break;
        if (*tmp) {
            ptr++;
        } else {
            result++;
            ptr += tmp;
        }
    }
    printf("%d\n", result);
}

Old version with strstr and strlen: 103
l;main(int c,char**a){char*p=a[1];l=strlen(a[2]);while(c++,p>l)p=strstr(p,a[2])+l;printf("%d\n",c-5);}

Delphi XE3 (113)
Takes 2 strings, removes substring from string and substracts new length from old length followed by a division of the substring length.
function c(a,b:string):integer;begin c:=(Length(a)-Length(StringReplace(a,b,'',[rfReplaceAll])))div Length(b)end;

Testing:

c('aaaabbbbsssffhd','s') = 3
c('aaaabbbbsssffhd','a') = 4
c('ababa','aba') = 1
c('ababa','c') = 0

Lua (48)
So i thought I could just submit another answer, this time in lua.
Its very possible this could be improved a lot, im very new to this.
print((a.len(a)-a.len(a.gsub(a,b,"")))/b.len(b))

Fortran 90: 101
Standard abuse of implicit typing, works for any length arrays a and b, though one should expect that len(a) < len(b).
function i();i=0;k=len(trim(b))-1;do j=1,len(trim(a))-k;if(a(j:j+k)==b(1:1+k))i=i+1;enddo;endfunction

This function must be contained within a full program to work. a and b are received from stdin and can be entered either on the same line (either comma or space separated) or on different lines. Compile via gfortran -o main main.f90 and execute as you would any other compiled program.
program main
   character(len=256)::a,b
   read*,a,b
   print*,i()
 contains
   function i()
     i=0
     k=len(trim(b))-1
     do j=1,len(trim(a))-k
        if(a(j:j+k)==b(1:1+k))i=i+1
     end do
   end function
end program main

Tests:
>ababa aba
2

I could make the above return 1 if I add 4 characters (,k+1) for the do loop
> aaaabbbbbsssffhd s
3

C++ 225
int n,k,m;
int main()
{
string s1,s2;
cin>>s1;
cin>>s2;
int x=s1.size(),y=s2.size();
if(x>=y)
{
for(int i=0;i<x;i++)
{
k=0,m=0;
for(int j=0;j<y;j++)
{
if(s2[j]==s1[i+m])
{
    k++,m++;
}
else break;
}
if(k==y)
{
n++;
i+=(y-1);
}
}
}
cout<<n<<endl;
return 0;
}

Java (38)
System.out.print(a.split(b).length-1);

(The question did not require a complete program or function.)