text:
Homework time! Find me the lowest even digit in a string
Another brilliant question from Stack Overflow turned into a code-golf challenge!
Write a program that:

Accepts a string as user input (not piped in or a command line argument). The data type of the input must be a string, if the language does auto evals on input, it must be cast to a string.
Finds the index (0 or 1 based) of the first lowest even digit.
Prints 2 integers, the index and the lowest even digit.
If there is no even digit, return -1 as the index, the second number can be anything.
For the purposes of this zero is not even.

Test examples, given the string on the left output the values on the right:
25376  -->  0,2
523726 -->  1,2
583746 -->  4,4
53771  --> -1,0
_4___2 -->  5,2

The winner: is the program with the lowest character count. No bonuses, no penalties.
edit: (about stdin) I screwed up on the user input part, basically no piping data in, and no command line arguments. You must provide a user prompt of some kind within the program itself.

What if the lowest even integer has two digits? Ok, twas a joke.

@belisarius Grrr. very funny...

Given the sample input they gave, I had assumed they meant digit. Too late, challenge has been thrown down!

What's wrong with stdin?

How liberal can we be with the output? Must it be "1,2"? or would "(1,'2')" be acceptable?

@MtnViewMark I assume (1,2) is acceptable because Lego Stormtroopr's answer does exactly that (usually [(1,2)])

@JanDvorak Because arbitrary rules, thats why.

@MtnViewMark Any data structure that spits out 2 numbers is ok.

Do you really need to link to a question that was removed?

Unclear on this: "as user input ... not stdin"  How are you defining the difference between "user input" and "stdin"? User input is most often, in a console app, read from stdin. Taking a look below, your Python reference example reads from stdin. It's late. Maybe I'm not seeing the obvious difference.

+1 for the link to the awesome question on StackOverflow.

"If there is no even digit ... the second number can be anything" - can the second number be nothing?

Also, do you care about non-terminating error output? I've got a script written, but it needs 41 characters to shut up the error output.

Why the limitation of zero not being even? That seems rather odd.

@lszi Because it means you have to work around the limitation of 0%2 == 0. And no as long as it prints the numbers thats ok.

@DarrenStone That was me trying to be specific about input, and I think I got it wrong. Basically, you need to use an "input" call of some type, data can't be piped into the program or read as a command line argument.

Your input requirements really make no sense: For most systems, input comes from stdin, whether prompted by the program or no. Whether or not the input is piped in or not is not under control of the program. -- If your aim was to have users create an interactive program, then you should have been precise about the input and output (including formatting), and the interaction required.

@MtnViewMark For some interpreted languages, the method of input is not only controllable - it must be specified. In PowerShell, you can only take input as one of: argument ($args), pipeline ($input), or interactively (read-host). You can make a script that will take any or all of the above, but it requires a significant amount of extra work to do so.

@Iszi: "Why the limitation of zero not being even? That seems rather odd." Pun intended or not?

@Iszi +1 for nice pun (That seems rather odd.)

Golfscript, 26 (28) characters
'#{gets}'.'246'&8+$1<.@\?

Example:
;'583746'
.'246'&8+$1<.@\?
#44

;'53771'
.'246'&8+$1<.@\?
#8-1

live test: http://golfscript.apphb.com/?c=Oyc1Mzc3MScKLicyNDYnJjgrJDE8LjA9QD8%3D
Explanation:

'#{gets}' is an escape to ruby to satisfy the I/O requirements; STDIN is assumed to be empty
. clones the input
'246'&8+ finds which even digits are present in the input, except 8 is always retained
$1< sorts the list, then takes the first digit, but keeps it as a string
.@\? orders the stack {digit, input, digit}, then finds the digit in the input; thanks @peterTaylor for noticing me of the [array, array] signature of ?.

I've been very bold with the spec interpretation this time; namely:

The spec does not mandate in which order the integers are output; Use the other @peter's suggestion :x?x to fix (I don't like temporary variables.
The spec does not require any delimiter between the two integers; since the digit found is always a single digit, this does not matter much. If it does, append n@ (which also performs the swap), n\ (which doesn't), or ]` (which formats the output as ["8" -1]).

They aren't crazy requirements, they are arbitrary requirements :P

Also, the spec requires the index to be first, but I can't read GolfScript well enough to tell if you didn't

@LegoStormtroopr the only point of the spec that mentions the order is #4: "If there is no even digit, return -1 as the index, the second number can be anything". #3 does not specify the order; what about the "no delimiter" boldness?

Oh snap, you are correct sir! I mentioned the two numbers to output, but not the order. I stand corrected!

You can replace .0=@? with .@\? or :x?x to save one character and avoid the doubt over the order. Nice use of 8 as a fallback.

I'm pretty sure your input code doesn't (and can't be made to) work, because 1) the string needs to be double-quoted for Ruby escapes to work, and 2) even if you fix that, plain gets reads from the same default handle that has already been slurped dry by the interpreter. Also, even if you fix both of those, the Ruby code is normally executed at compile time, so you can't e.g. print a prompt before it. However, using '"#{STDIN.gets}"'~ and running the program as ruby golfscript.rb lowest_digit.gs /dev/null does work, in the sense that you can print a prompt before, it if you want.

(Even that alone doesn't work in a loop to read multiple numbers, since GolfScript caches the values of strings. If you really want to do true interactive input in GolfScript, you need something crazy like 10,{'"#{STDIN.gets'\n*+'}"'+~}% to read 10 lines of input.)

APL (37)
(1-based by default, but obeys ⎕IO)
{×⍴m←⍵/⍨⍵∊'2468':z,⍨⍵⍳⍕z←⌊/⍎¨m⋄¯1,0}⍞

Explanation:

⍞: read user input
m←⍵/⍨⍵∊'2468': remove all the characters that aren't 2468, store in m.
×⍴m: see if there are any
:: If so:

z←⌊/⍎¨m: evaluate each character in m, find the lowest number and store in z.
z,⍨⍵⍳⍕z: return the index of z in ⍵, followed by z.

⋄: If not:

¯1,0: return (-1, 0)

Wow, I've beat APL (not with the J solution, but still...)

Explanation? APL is so self-explaining... ;)

Python 3 ,69
combining ideas from here.
s=input();print(([(s.find(x),x)for x in'2468'if x in s]+[(-1,0)])[0])

I like the use of a string rather than a list, and the resulting omission of the (now removed) ` quotes.

@boothby I guess you didn't notice i'm using python 3. In python 3 input() Accepts a string as user input.

@SimonT  ` (backticks) are not just quotes. It is a deprecated alias for repr() in python 2. But its no longer available in Python 3. So, If I wanna use `` on something in python 3, i have to write repr(something) which cost 4 more chars. Thats why i get rid of it ;)

@Wasi yes indeed, my mistake.

@Wasi, yes thank you.  I was aware of that and by "now removed" I actually meant removed as a part of the language altogether.  Cheers.

Ruby, 60 characters
x=gets.chars.sort.find{|c|c=~/[2468]/};p x ?$_.index(x):-1,x

$_ contains the last input read by gets.
p calls inspect on the arguments and prints the results.

perl - -94- 53 chars (or 48)
Instead of index()'s  zero-based approach we use pos and start at one; no CPAN. Run this with perl -nE and it will wait for input (which it can also receive from STDIN).
The first match (//) operation works on the default value ($_) from input, matching against the given even numbers, sorting the matches into an array, and then storing them in a "scalar list" ($m). In scalar context the list value of the sorted array is one item long and thus consists of the lowest matched even digit in the number.
Having isolated the lowest even matched digit, we then use $m for a second match operation which will find the first occurrence of the value of $m in the original string. We are still using the default value here $_ and we are saving the match against the contents of $m in $1 (the reason for the () around $m in the second statement). After that, pos and say do the rest (and in fewer characters than index and print).
perl -nE'($m)=sort/[2468]/g;/($m)/g;$1?say pos.",$1":say"-1,0"'
33467
3,4

If output order or commas don't matter then it's possible to make this 5 chars shorter:
($m)=sort/[2468]/g;/($m)/g;$1?say$1.pos:say"-10"

In my earlier attempt I rushed and made an error - I just wanted to beat python and ruby (but failed) ... sigh.
Congrats to the winner and the other participants on their cool solutions - especially to perl6 :-) A possible Perl6 adaptation of this approach could use ".comb (suggested on freenode by Masak et.al.).
$_=get;my $n=.comb(/<[2468]>/).min;/$n/;say $/.from//-1,",$/"

Was so focused on beating python/ruby that I posted a one liner that did not work when no even numbers were present: eagerly using an earlier version of the above from my $SHELL history for the "win". This working version is ridiculously long and embarrassing.  Serves me right: will shorten later to avoid shame :-(

older hack: if(/[2468]/){for$i(2,4,6,8){if(index($_,$i)>-1){say$i,",",index($_,$i)+1;last}}}else{say"0,-1"}

Good, but room is left for further golfing: ($m)=sort/[2468]/g;/$m/g;say$&?pos.",$&":"-1,0" (47+1 bytes, AFAIK -n costs an additional byte).

NB. pos returns the offset.  So in effect it's returning 1-based index in your example.

@draegtun oopsie :-) thanks.  @Heiko true that: switches should count otherwise perl's -M would win every time ;-)

Perl 6, 37 55 60 characters
$_=get;say m/<{~.comb(/<[2468]>/).min}>/.from//-1,',',$/.Int

EDIT: I misunderstood the question the first time. This update should be correct. It finds the lowest number of 2,4,6, or 8 that the input contains, and then does a regex match against the input with that lowest number. $/.from gets the position of the match and ',', $/.Int is a comma plus the match itself, or 0 if the text didn't match.
While you're here, go upvote G. Cito, who helped me fix my entry in the comments and on irc :)

Unfortunately this prints first even number (2468) found and not the lowest :(  NB. Also there is an issue with $/.from when nothing is found (this maybe a bug in my old version of Rakudo).  Here's a variation of your solution which works (for me!) my$x=get;for 2,4,6,8 ->$n{if $x~~/$n/ {say $/.from,",$/";exit}};say "-1 0";  Comes in at 75 chars but I'm sure a shorter perl6 solution can be made.

@draegtun ... I made a similar error with my perl5 attempt yesterday (see below). My fix added 70 chars!  Just updated it with a ~50 char version - which seems to work. I think if you sort all the even digits in the number you can then do a match using the (now) first digit in the sort and be sure you have the lowest and the first.  Am I right?

@G.Cito Looks good to me and have already +1 your answer.  I can see way to shave off a few chars but I see Heiko as done even better than what I was going to suggest!

@draegtun Oh, geez, I completely misunderstood the question then :( Thank you so much! I'll update this ASAP

@mouq Here's an approach one that uses the same approach as the perl5 example I posted below: my $n; $_="333992";$n=.comb(/<[2468]>/).min;/$n/;say $/.from//-1,",$/".  I learned about .comb about 20 minutes ago and I already like it :-)

@G.Cito Thanks for your help! Updated

I knew there must be a much better way than my suggestion! +1    However you need to show a second number (can be any number) when there isn't a match.  Here's one slight change that works but I'm sure it can be improved on: $_=get;say m/<{~.comb(/<[2468]>/).min}>/.from//-1,",",$/.Int;

Aww, okay -- thank you @draegtun! I'll update accordingly :)

Python 2.7 - 76
A reference answer I fully expect to be beaten. But to start people off:
s=raw_input()
print[(s.index(`e`),e)for e in[2,4,6,8]if`e`in s][:1]or(-1,0)

you can shave off a character by changing index to find; you can also change [2,4,6,8] to 2,4,6,8 (with space in front).

Shorter: print[(s.find(\e`),e)for e in 2,4,6,8if`e`in s+'8'][0]`

I think you broke your own rule... Since when is raw_input not stdin?

print[(s.index(c),c)for c in'2468'if c in s][0]or(-1,0)

J, 44 characters
echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1

outputs the last character of the input if no even digit is found
Example:
   echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1
523726
+-+-+
|1|2|
+-+-+
   echo(;{&i){._1,~(#~(#i)&>)'2468'i.~i=.1!:1]1
53771
+--+-+
|_1|1|
+--+-+

Explanation:

echo ... i=.1!:1]1 is input/output. Way longer than I want it to. Input is stashed away into i as well.
'2468'i.~ finds the first occurence of each even digit in the input, returning the input length if the digit cannot be found
(#~(#i)&>) reads "select by the length of input being greater than this"; in other words, select those indices that point into the input. Way longer than I want it to.
_1,~ appends -1 to the back. Underscore is the J's way of representing negative values.
{. selects the first element
(;{&i) concatenates it with the input character at that position in two boxes; since we're concatenating a number with a character, non-boxing concatenation (,) won't do. If unboxed display is desired, the index needs to be formatted (":) first at a cost of two chars.

R, 104
y=as.integer(strsplit(scan(,""),"")[[1]]);z=which(!y%%2&y);a=z[which.min(y[z])];cat(a,"-1 0"[!sum(a)],y[a])

Examples (in R, the index starts at 1):
_4_502
6  2

_3_501
-1 0

583746
5  4

Powershell, 76 73 71
$s=read-host;2,4,6,8|%{if($i=$s.indexof("$_")+1){"$i,$_";break}};"-1,0"

$s=read-host        stores user input into $s
2,4,6,8|%{...}    runs what's inside {} for digits 2,4,6,and 8
$i=$s.indexof("$_")+1  sets $i to 1-based index of a digit in $s or 0 if the digit is not found
if( $i=... ){...}     the condition will be true when $i is not 0
"$i,$_";break         outputs the index and the digit, and stops execution
"-1,0"                otherwise outputs -1,0

This does not output the proper index. In PowerShell, as in the test cases given for the question, indexes start at zero.

Rule #2 says the index can be 0 or 1 based.

Oh. Didn't spot that. Either way, here's a zero-based variant that's only 5 characters longer. $s=read-host;(2,4,6,8)|%{if(($i=$s.indexof("$_"))-gt-1){"$i,$_";break}};'-1,0'

Also, I'm pretty sure the parenthesis around 2,4,6,8 are unnecessary.

Zero-based variant can be made 2 characters longer, if you change the if condition to: if(1+($i=$s.indexof("$_")))

I'm lost. Why does break avoid "-1,0"? It's not part of the loop.

foreach-object (not to be confused with foreach) is not a loop in Powershell.

When is a loop not a loop? When it's a cmdlet!

C++11, 173 (including two new-line chars)
Here's the compressed version:
#include<iostream>
#include<string>
int main(){std::string s;std::cin>>s;for(char c:"2468")for(char&k:s)if(k==c){std::cout<<(&k-&s[0])<<','<<c;return 0;}std::cout<<"-1,8";}

Here's the readable version:
#include<iostream>
#include<string>
int main() {
    std::string s; // auto s = ""s; (since C++14: -3 characters)
    std::cin >> s;
    for (char c : "2468")
        for (char& k : s)
            if (k == c) {
                std::cout << (&k - &s[0]) << ',' << c;
                return 0;
            }
    std::cout << "-1,8";
}

Here's an older version:
C++11, 175 (including two new-line chars)
Here's the compressed version:
#include<iostream>
#include<string>
int main(){std::string s;std::cin>>s;for(char c:"2468"){int i=s.find(c);if(i<s.size()){std::cout<<i<<','<<c;return 0;}}std::cout<<"-1,8";}

Here's the readable version:
#include<iostream>
#include<string>
int main() {
    std::string s;
    std::cin >> s;
    for (char c : "2468") {
        int i = s.find(c);
        if (i < s.size()) {
            std::cout << i << ',' << c;
            return 0;
        }
    }
    std::cout << "-1,8";
}

Try #define o std::cout<<.  I think it trims your code by 1 character.

@user2509848, nope, it's actually 2 characters longer. But thanks anyway :)

k==c?std::cout<<(...),throw 0:0; - the conditional operator can replace if, when all you need are expressions. throw is an expression and also one character shorter than return.

C, 80 character
main(){char a[81],b=strcspn((gets(a),a),"2468");printf("%d,%c",a[b]?b:-1,a[b]);}

C# - 124
I'm a bit late to the party
void Main(string[]a){var x=a[0].Where(w=>char.IsDigit(w));var y=x.Min();Console.Write(y%2==0?a[0].IndexOf(y)+","+y:"-1,0");}

vb.net (108c)
Sub Main()
t=ReadLine()                          '12c
For Each c In "2468"                  '20c
i=t.IndexOf(c)                        '14c
If i>=0 Then Exit For                 '21c
Next                                  ' 4c
WriteLine("{0},{1}",i,If(i<0,0,t(i))) '37c
End Sub

Smells slightly cos it's exploiting VB's dynamic setting. Option Explicit Off and Imports System.Console.

VB.net (193c) using LINQ
This one is primarily utilising a LINQ query.
Dim r = From d In "2468" Group Join q In ReadLine.Select(Function(c, p) New With {.c = c, .i = p})
                              On d Equals q.c Into g = Group
                                        Skip While g.Count = 0 ' 138c
WriteLine(If(r.Any,r(0).g(0).i&","&r(0).g(0).c,"-1,0"))        '  55c

Golf-Basic 84, 91 characters
:L1/L1_L2i`L1:fpart(L1,2)2_L1:SortA(L1)@cumSum(L1)=length(L1):Thend`-1#d`cumSum(L1):Endd`L1

Make sure there's no 0 in the input (it's not even, who said it had to be odd?)
Get input into L1 (List 1)
Loop finding modulus of 2 for each value
Sort L1 from smallest to highest
Display the index (either -1 or the cumulative sum) and the smallest number

Bourne shell (sh), 88 chars
(echo 88;sed 's/./\n&/g')|nl -v-1|awk '{print $2,$1}'|sed '/^[^2468]/d'|sort -n|head -n1

I thought I'd do a string-processing thing for fun.  Technically it reads from stdin, but if you run it interactively it'll prompt the user for input since the keyboard is the default stdin stream.  Uses basic shell commands to split up the input on lines, number them (using the ill-known nl utility), filter out lines fitting the criteria, sort them and output the lowest-digit one.  Prints 88 -1 if no even digit was found.

C++ - 223 221 Characters:
#include<iostream>
#include<string>using namespace std;
int main(){int s=9;int p=-1;string x;cout<<"Enter characters: ";cin>>x;for(int i=0;i<x.length();i++){int n=x[i]-48;if(n%2==0&n<s){s=n;p=i;}}cout<<p<<", "<<s;return 0;}

Readable version:
#include<iostream>
#include<string>
using namespace std;

int main() {
    int s = 9;
    int p= - 1;
    string x;

    cout << "Enter characters: ";
    cin >> x;

    for (int i = 0; i < x.length(); i++) {
        int n = x[i] - 48;

        if (n % 2 == 0 & n < s) {
            s = n;
            p = i;
        }
    }

    cout << p << ", " << s;

    return 0;
}

It is long, but not as bad as Java.

It's actually 221 + 2 (new line characters) otherwise it won't compile.

Oh.  Word only detected 221, I will change it.

Haskell, 79 characters
s&d=filter((==d).snd)$zip[-1..]$'0':s
main=interact$show.head.("24680">>=).(&)

This runs a little fast and loose with the output formatting:
& echo 523726 | runhaskell 16083-LowEven.hs
(1,'2')
& echo 583746 | runhaskell 16083-LowEven.hs
(4,'4')
& echo 53771 | runhaskell 16083-LowEven.hs
(-1,'0')
& echo _4___2 | runhaskell 16083-LowEven.hs
(5,'2')
& echo 25376 | runhaskell 16083-LowEven.hs
(0,'2')

PowerShell: 145 103

Changes from original
  Removed error quelch per comment from asker.

Code:
"$([array]::IndexOf(($s=(read-host)-split''|?{$_}),($x=$s|?{$_%2-eq0}|?{$_-gt0}|sort|select -f 1))),$x"

Walkthrough:
"..." Everything within the quotes will be included in the output.
$(...) Everything between the parenthesis will be treated as a commands, and the output of that code will be included instead of the commands themselves.
[array]::IndexOf(...) This is used to get the index of an element with the array. Its first parameter is the array object to be searched. The second parameter is the object to be found. This only outputs the index of the first matching element. I tried simply using an IndexOf method directly against $s (e.g.: $s.IndexOf($x), but this fails for some reason I've yet to figure out - it claims the method doesn't exist on that object.
(...) Expression within the parenthesis will be the first parameter for IndexOf.
$s= $s will be a variable to store the user input.
(read-host)-split'' Gets user input, and splits it into an array of characters.`
|?{$_} Filters out extra empty array elements that are generated by -split''.
,(...) Expression within the parenthesis will be the second parameter for IndexOf.
$x= $s will be a variable to store the lowest even digit from the user input.
$s|?{$_%2-eq0} Pulls out the even numbers from $s.
|?{$_-gt0} Invalidates zero.
|sort Sorts the remaining objects, default order is ascending.
|select -f 1 Picks the first object, which will by now be the lowest even digit.
,$x The above code will output the index of our lowest even digit. This adds a comma, and then outputs the digit itself.
Notes:
This is perhaps stretching rule #4 a little bit. If there is no even digit, the output will not include a second number.
Also, this will throw some non-terminating errors if the input includes non-numeric elements. The script will still run and give proper output, but you might want to set $ErrorActionPreference to 'SilentlyContinue' before running it.

@DankoDurbić Now that you've soundly defeated me, would you mind helping me figure out why I couldn't use $s.IndexOf here? It was giving me an error saying the method didn't exist for that object, even though $s|gm said it did. It works on the system I'm on now, but not the one I was trying to do it on earlier today. Is it a version compatibility issue? Earlier system was PSv2, current is PSv4.

Your $s is string[], and $s.indexof doesn't work because ...[System.String[]] doesn't contain a method named 'indexOf', which seems reasonable (I'm running PS 2.0). $s|gm returns members of System.String, not System.String[]. I'm not sure why it does that.

Javascript 93 characters
b=prompt();((r=b.match(/[2468]/g)||[-1]).sort(function(a,b){return a-b})[0])+","+b.indexOf(r)

Get all event numbers, sort the array and prints the first digit.

Mathematica, 157 characters
f = Row@{If[(x = Min@#) == Infinity, -1, Position[#, x][[1, 1]]],
      ",", x} &[IntegerDigits@ToExpression@StringReplace[#,
       {"0" -> "1", x_?DigitQ :> x, _ -> "1"}] /. _?OddQ -> Infinity] &

inputs = {"25376", "523726", "583746", "53771", "_4___2"}

f /@ inputs // Column

1,2
2,2
5,4
-1,∞
6,2

C, 110 Characters
i,f,r,c,m=9;main(){while(r=getchar()>31){c=r-48;i++;if(c>=0&&~c&1&&c<m)m=c,f=i;}printf("%i,%i",m>8?-1:f-1,m);}

ungolfed:
i,f,r,c,m=9;
main(){
  while(r=getchar()>31){
    c=r-48;
    i++;
    if(c>=0&&~c&1&&c<m) m=c,f=i;
  }
  printf("%i,%i",m>8?-1:f-1,m);
}

Javascript, 69
a=prompt(),b=[-1,9];for(i in a)if(+a[i]%2==0&&+a[i]<b[1])b=[+i,+a[i]]

Reads the value, iterates through each character, if the number representation mod 2 equals 0 and the number is less that what is already stored in b, replace the values in b

Rebol, 69
s: input for n 2 8 2[if f: find s n[print[index? f f/1]q]]print[-1 0]

Ruby 55
p gets.chars.sort*''=~/[2468]/?[$_.index($&),$&]:[-1,0]

Julia, 84
julia> f(a)=(for i=2:2:8;(k=search(a,'0'+i))==0||return(k,i);end;(-1,0))
julia> f(readline(STDIN))
583746
(5,4)
julia> f(readline(STDIN))
_4___2
(6,2)

Julia really needs a shorter way to get input for golfing. I counted the definition of f and one call to f. One based indexing is why the answers are different from the examples.

JavaScript - 53 Characters
for(y=prompt(x=0);x<8&&(i=y.indexOf(x+=2))<0;);x+''+i

Reads input from prompt and outputs (to the console) the lowest even character then (without a delimiter) the first index of that character; if there are no non-zero even characters then it outputs 8-1.

JavaScript/jQuery 149
Golfed
$(function(){
var i=prompt(),k=-1,n=0,c,e="2468";
while(n<i.length){c=i.charAt(n);k=e.indexOf(c);if(k>=0){break;}n++;}$('#d').append(k+","+n);
});

Full source
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="d"></div>
<script type="text/javascript">
$(function(){
var i=prompt();
var k=-1;
var n=0;
var c;
var e="2468";
while(n<i.length){
c=i.charAt(n);
k=e.indexOf(c);
if(k>=0){
break;
}
n++;
}
$('#d').append(k+","+n);
});
</script>
</body>
</html>

authors: Евгений Новиков


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

I'm unsure if this should be changed to Befunge in general, but Befunge 93 is much less ideal for golfing than 98.

We've had a recent Befunge 93 topic, but I think it'd be better to generalise this topic instead. Would that be okay? (and maybe mark which tips are good for which version/s, in the same way that Python tips say whether or not they're Python 2/Python 3 specific)

When using a multi-line loop, try to use as much of it as possible:
>1234....v
^        <

vs
>1234v
^....<

Need to drop a value after a conditional (e.g. because the other path depends on the value, but this one doesn't)?  Instead of using >$ or $<, take advatage of the fact that you know the truth value of the variable and use _ instead to both change direction and pop stack.
Example
'* : v           >$ .. @          Prints number in binary followed by the original
                                  decimal number.
     > :2%\2/ :!#^_ \.

gets turned into
'* : v           _  .. @          Since we know that the topmost value on the stack
                                  will be 0, we combine `>$` into `_`.
     > :2%\2/ :!#^_ \.

Don't forget that 0 is always on the stack. For example, this means that, with an empty stack, g is equivalent to 00g and p is equivalent to 000p.

If you need to push a number larger than 15, use ' to fetch the ASCII value of the next character:
'*

to push 42 rather than:
4a*2+

Or, 67* works too

@Doorknob Maybe I should have chosen a prime number to get my point across clearer, but 42 is such a great number.

Note that this tip only applies to Befunge-96 and later. Befunge-93 did not support the ' instruction.

Instead of using |, requiring another line (often with many extra spaces), try using j. For example:
01-`j@more code here

would stop if the number on top of the stack was negative and continue onward otherwise. If you need multiple characters, use n*j where n is the number of characters you need when the value passed to j is 0. Example:
01-`4*j01-*more code

which would negate a negative number.

Note that this tip only applies to Befunge-96 and later. Befunge-93 did not support the j instruction.

Is the 0 at the beginning necessary? 0 is always on the stack.

In Befunge-93, if the first thing you're pushing onto the stack is a string, you can often get away with dropping the opening quote. For example this:
"!iH",,,@

could be simplified to this:
!iH",,,@

Try it online!
What's happening is the interpreter first tries to execute the characters in the unquoted string. The ! performs a harmless not, and the i and H are not valid instructions, so they're ignored (although on some implementations you may get a warning).
When the " is encountered, that is considered the start of the string, but because there is no closing quote, it wraps all the way around the playfield until the " is encountered a second time. What ends up pushed onto the stack is then this:
,,,@  ···72 spaces···  !iH

Since we only care about the last few characters, though, none of that other stuff matters. So after the quote, we then finally get to execute the three , commands, writing out the message, and the @ command, which exits.
Note that this won't typically work in Befunge-98, since an unrecognised instruction will cause the interpreter to reflect instead of ignoring it.

In Befunge-98 you can instead put the required string at the end of the line, like so; ",,,@!iH. Note that Pyfunge adds an extra space, while FBBI doesn’t.

@JoKing I didn't want to suggest that, because, as you pointed out, the behaviour differs from one interpreter to the next. And even when it seems to work, it's inconsistent (note the extra space in FBBI in this case), so it's quite possibly a bug that may end up being fixed at some point.

Hmm... I think the space might actually be part of the specification. I remember reading somewhere that multiple spaces will be skipped and counted as a single space. Example in both PyFunge and FBBI. FBBI seems to pad each line to the length of the longest line while PyFunge adds the extra spaces implicitly.

You're right - the spec does say that multiple spaces in a string should be treated as a single space. In fact that rule was specifically proposed to deal with the problem of wrapping strings in an infinite playfield (so PyFunge is clearly correct AFAIC). But the spec's description of the wrapping algorithm is somewhat open to interpretation, so I can understand why some implementations might do things differently. But the bottom line is this is a fairly complicated issue, and I think it would be better covered as a separate tip specific to Befunge-97/98.

In Befunge-93, the character input command (~) can often be used as a shortcut for -1, since that is the value it returns on EOF.
As an example, the code below will output -1:
~.@

Try it online!
This is not recommended in production code, since when run in an interactive environment, the program would pause and wait for user input. And obviously if the user were to input something, the result would no longer be -1.
That said, the rule on PPCG is that a program may assume an empty input stream, and that's how it would typically be run on TIO.
Also note that you aren't necessarily precluded from using this trick just because your program needs to read something from the input stream. You just have to make sure you process your inputs up front, after which all future uses of ~ should return -1.

In Befunge-93, it can often be advantageous to flatten a loop into a single line, with the loop section of code being executed in both directions.
For example, consider the code below, which outputs the letter a eight times:
"a"9>1-:#v_@
    ^\,:\<

This can flatten be flattened into a single line by interspersing the loop sequence with bridge instructions (#):
"a"9>1#\-#,:#:>#\_@

Try it online!
If you're just looking at the non-whitespace characters, you may get the impression that this is longer than the the original. But once you take into account the linefeed and the additional padding required in the two line version, you actually end up saving four bytes.
In this particular case, the code be compressed even further by noting that that sequence :#: can simply be replaced with :.
"a"9>1#\-#,:>#\_@

Try it online!
In fact, any time you have the same instruction repeated on either side of a # command, you can simplify that to just the one instruction, so this is something you should always be looking out for when flattening a loop.
To understand how this works, it can help to write out the loop sequence twice, once with all the characters following the # removed (i.e. what happens when executing left to right), and once with the characters preceding the # removed (i.e. executing right to left).
"a"9>1#\-#,:>#\_@
    >1  -  :>  _      ; executing left to right
    >  \  ,:  \_      ; executing right to left

You can clearly see now how this matches the original two line version of the code.

Use the direction of the IP when dealing with _ or |, rather than using an extra character for !.
Real example (from this post):
#v~
,>:!#@_

Can be changed to
#v~
:<,_@#

Don't forget that 0k does not execute the next instruction. This means that instead of doing:
;some boolean test;!jv;code if false;
       ;code if true;<

You can save a character by doing
;some boolean test;kv;code if false;
      ;code if true;<

Note that this tip only applies to Befunge-98 and later. Earlier versions of Befunge did not support the k instruction.

Output by exit code, where this is an allowed output form. If the challenge asks you to print one number, you can save a byte by ending the program with q instead of .@

Note that this tip only applies to Befunge-98 and later. In earlier versions of Befunge the q instruction had a different function (queue mode) or was not supported.

Don't forget about the k operator. Instead of "!dlroW olleH",,,,,,,,,,,,@, do "!dlroW olleH"bk,@. Note that k does the operation on the cell that it is at so 9k, would print not 9 times but 10; 9 times with the k, and once with ,.

Note that this tip only applies to Befunge-98 and later. Earlier versions of Befunge did not support the k instruction.

When pushing small numbers onto the stack, you can probably figure out easily enough that 45* will get you 20, and 67* will get you 42. When it comes to larger numbers, though, you really need a program that can calculate the most efficient representation for you.
The easiest option for this is Mike Schwörer's online interface for BefunRep. You simply type in a number and it'll spit out an equivalent Befunge representation. It's not always the most optimal, but it's close enough, and it's almost certain to be better than anything you could come up with by hand.
The online system is limited to numbers in the range 0 to 16777215, so if you need anything larger than that, you'll want to download the standalone BefunRep utility and run the calculations yourself.
If you're programming in Befunge-98, another option to consider is Fungify. In general it isn't nearly as optimal as BefunRep, but for some of the lower numbers, where hex digits and single quote characters are most effective, it can sometimes produce better results.

When pushing small numbers in Befunge 98, you'd use '. E.g. for 42: '*

@Justin I mentioned that in the last paragraph, but the whole point of this tip is you don't need to know a whole lot of these tricks for generating numbers if you just use a tool to do it for you.

Merge branches as soon as possible
If two or more code branches are merging together and they all end with the same sequence of instructions, you can merge them immediately before the instructions they have in common. This is a fairly common circumstance to be on the lookout for.
As an example, I have this subprogram for reading input onto the playing field from my self-interpreter:

Notice that three different branches are coming together at the marked cell, each of which wants to write to the playing field. The one on the top right is 520p to put 5 at (2,0). The top left is 00p to put the computed value at (0,0). And on the right (and below) is 20p to put the computed value at (2,0). Since all of these instructions end with 0p, I save at least 4 bytes by merging the branches first and then doing 0p afterwards.

Use String Mode to Allow the IP to Pass Through Other Code
If you need the IP to get from here to there and there's a bunch of existing and unmovable code in the way in every direction, just push a 0, go into string mode, pass through the code, come out of string mode, and pop all the garbage before continuing. This trick employed in Wim Rijnder's Wumpus here:

(Yes, it would have been more efficient to put the quotes closer to the actual code there, but this is golf--we don't care about speed!)
This trick requires you to be able to spare at most 2 cells on this side and at least 3 on the other side, but it might end up saving space in the long run if writing yourself into a corner that requires this trick ends up greatly compressing the rest of the program. (In particular it could save you from having to write in a low-code-density "lane" for the IP to travel down.)

source: Stack Exchange

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

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

sort: votes


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

Need to provide a type annotation for a variable so that you can call a method on it? Just compare it against a literal of the type you want it to be then throw away the result:
let f (x:string)=x.Length
let f x=x="";x.Length

Use function instead of match when possible; it'll save 6 characters for 1-character variable names:
let f=function // ... (14 chars)

vs
let f x=match x with // ... (20 chars)

It can also replace any pattern match to consistently save 1 character:
match a with|          // ... (13 chars)
a|>function|           // ... (12 chars)
(function| (* ... *))a // (12 chars)

Use the prefix notation for infix operators when you can - it'll save you from having to define a function to use them.
For example, you can turn this:
List.map(fun i->i+2)[1;1;2;3;5;8]

into this:
List.map((+)2)[1;1;2;3;5;8]

I use it here thank you!

Tuple deconstruction
In case you can't get around to using variables, use tuple deconstruction instead of multiple let expressions
let a,b ="",[]

instead of
let a=""
let b=[]

Reading from stdin
F# core library defines an alias for System.Console.In called stdin. These allow you to read input.
// Signature:
stdin<'T> :  TextReader

TextReader on msdn
The big advantage aside the fact that it's shorter than Console is, you don't have to open System either
Iterating over string
string is basically a char seq, this allows you to use Seq.map directly with strings. It's also possible to use them in comprehensions [for c in "" do]
Mutables/Reference cells
Using reference cells is not always shorter as every read operation comes with an additional character to deref the cell.
General tips

It is possible to write the complete match .. with inline
function|'a'->()|'b'->()|_->()

There is no need for white-space before and after non alphanumeric characters.
String.replicate 42" "
if Seq.exists((<>)'@')s then
if(Seq.exists((<>)'@')s)then

In case you need to left or right pad a string with spaces, you can use [s]printf[n] flags for that.
> sprintf "%20s" "Hello, World!";;
val it : string = "       Hello, World!"

Core.Printf Module

Use id instead of x->x
id is an operator standing for the identity function.
let u x=x|>Seq.countBy (fun x->x)

can be written
let u x=x|>Seq.countBy id

source
I use it here

Eta-conversion for functions
Many thanks to Laikoni for this tip in one of my solutions.
Consider a function to, say, sum a string with 3 for upper-case letters and 1 for all other characters. So:
let counter input = Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1) input

By eta-conversion this can be re-written as:
let counter = Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)

and called in the same way as before:
counter "Hello world!" |> printfn "%i"

The function forward-composition operator >>
Now suppose our original challenge would be to sum a string with 3 for upper-case letters and 1 for lower-case letters, and all other characters are excluded.
We might write this as:
let counter input = Seq.filter Char.IsLetter input |> Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)

We can use the forward-composition operator (>>) to chain the two functions (Seq.filter and Seq.sumBy) together. With eta-conversion the function definition would become:
let counter = Seq.filter Char.IsLetter >> Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)

Chris Smith did a great write-up on the >> operator on his MSDN blog.

Prefer new line string over "\n"
This will start to pay off at even a single new line character in your code. One use case might be:
(18 bytes)
string.Concat"\n"

(17 bytes)
string.Concat"
"

Inspired from Chiru's answer for es6.
Used here

Use .NET
.NET offers a lot of nice builtins. F# can use them, so dont forget them!
Example:
open System.Linq

It can be helpful!

Avoid parenthesis when using one parameter and on tuple
let f = [(0,1);(1,4)]|>Seq.map(fst)
printfn "%A" f

can be written
let f = [0,1;1,4]|>Seq.map fst
printfn "%A" f

You also don't need () around tuples:
let f=[0,1;1,4]|>Seq.map fst

When possible Seq is shorter than List:
[[1];[2;3];[4];[5]|>List.collect

[[1];[2;3];[4];[5]|>Seq.collect

is one char shorter...

Use for...to instead of for...in to walk a range
for i in[0..2]
for i=0 to 2

for in
for to

The module keyword can be used to shorten module names when used repeatedly. For example:
Array.fold ...
Seq.iter ...
List.map ...

can become
module A=Array
A.fold ...
module S=Seq
S.iter ...
module L=List
L.map ...

This is more useful for longer programs where module methods are used repeatedly (and must be fully named each time because they have the RequireQualifiedAccess modifier), and allows shaving a few chars off especially when it's more useful to use a regular CLR array (e.g., mutability) than an F# seq or list.

Use lambdas to save a byte. For example, this:
let f x=x*x

Can be expressed as this:
fun x->x*x

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


text:
Desperately Seeking Santa
Find Santa and his reindeer in a crowded scene.
Input
Input will be on STDIN and will be a variable number of lines of characters of equal, but variable, length.
If Santa (represented by the character S) is in the scene, his sack of presents (represented by the character P) will be in one of the positions adjacent to him (horizontally, vertically or diagonally). His reindeer (each represented by the character R) will all be within the 5x5 square surrounding him. If an S appears in the scene that does not have a sack of presents, or is not accompanied by at least 4 reindeer, then it is not Santa.
Output
The scene cleared of all obfuscation (all non-Santa, non-presents, non-reindeer characters replaced with a space), showing Santa, his sack of presents, and his reindeer - all other characters should be replaced with spaces. If Santa and his reindeer are not in the scene, output it unchanged. It is guaranteed that there will only be one solution, so there will never be more than one valid Santa and he will never be carrying more than one sack of presents.
Examples
In these examples I'm just using the * character to make it easy to see the S, P, and R characters, but your program should be able to handle any ascii character from ! to ` (33 to 96). I've left out lower case characters and above to avoid confusion.
Input:
***********
***********
***********
*****R*****
******P****
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

Output: (ignore dots, they're to force the page to show the blank lines)
.
.
.
     R
      P
     S
     R
    R  R
.
.
.
.

Input: (not enough reindeer)
***********
***********
***********
***********
******P****
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

Output:
***********
***********
***********
***********
******P****
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

Input: (no sack of presents)
***********
***********
***********
*****R*****
***********
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

Output:
***********
***********
***********
*****R*****
***********
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

Input: (presents not close enough)
***********
***********
***********
*****R*****
***********
*****S*P***
*****R*****
****R**R***
***********
***********
***********
***********

Output:
***********
***********
***********
*****R*****
***********
*****S*P***
*****R*****
****R**R***
***********
***********
***********
***********

Input: (one of the reindeer not within the 5x5 square around Santa)
***********
***********
***********
*****R*****
******P****
*****S*****
*****R*****
****R******
*******R***
***********
***********
***********

Output:
***********
***********
***********
*****R*****
******P****
*****S*****
*****R*****
****R******
*******R***
***********
***********
***********

Test Scripts
As in some of my past questions, I've once again butchered some test scripts originally created by Joey and Ventero to provide some test cases for this question:

bash
Powershell

Usage: ./test [your program and its arguments]
Plain text version of the tests for reference: Plain text
Rewards
Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of 31/12/2013 will be accepted as the winner.

I realise this is similar to my previous question Facial recognition, but it's been a couple of years since then. Also, I apologise for skipping the Question Sandbox but with it being christmas related it needed to be posted quickly or it wouldn't be relevant.

The first example output does not display properly (appears to be smaller size).

@DennisJaheruddin It looks like the Markdown is removing all the blank lines. I've added dots at the start of those lines to show that they're there. Sorry about the confusion.

MATLAB: 110 ,95 characters
f=@(x,y) filter2(ones(x),y);a=M==83;b=M==82;c=M==80;d=f(5,a&f(5,b)>3&f(3,c))&(a|b|c);if ~d,M,else,M(~d)=32,end

Not sure about the way input is supposed to be processed, but the rest is pretty straightforward.
Normally formatted version:
f=@(x,y) filter2(ones(x),y);
a=M==83;
b=M==82;
c=M==80;
d=f(5,a&f(5,b)>3&f(3,c))&(a|b|c);
if ~d
  M
else
  M(~d)=32
end

Example input:
M=['***********'
'***********'
'***********'
'*****R*****'
'******P****'
'*****SQL_2*'
'*****R*****'
'****R**R***'
'***********'
'***********'
'***********'
'***********'];

Hmmm, running the test scripts on this is going to be awkward. A quick look over the code suggests that you're only using the examples given above which use * characters as the crowd to make it easier to see the S, P and R characters - whereas the tests in the test script use all ascii characters from 33 (!) up to (and including) 96 (```). I'll make this clear in the question. I've done a plain text version of the tests you need to pass which I'll also add to the question.

@Gareth Updated, seems to pass the tests now. Too bad that santa doesn't wear a Quilt, would have saved me at least 2 characters.

Okay. I don't have Matlab so I'm just downloading Octave (which the internets tell me is the best free way to run Matlab code) and will run through the tests in the morning to check.

Okay I've checked this and it does appear to meet the spec. The one place it has an unfair advantage is on the input requirements. I've upvoted, but I won't be able to accept it as winner unless it reads input (from a file since it seems Matlab doesn't read from STDIN).

You slipped SQL_2 into the sample input... nice :)

Have not tried to optimize this, but if you want to read a (single) crowded scene from a file called x, you can use this code preceding the solution: M=textread('x','%s');M=vertcat(M{:});

Python 2 (353 381)
import re,sys
a=sys.stdin.readlines()
h=len(a)
w=len(a[0])
a=''.join(a)+' '*99
print a
b=[''.join(q) for x in range(0,w) for y in range(0,h) for q in [[a[(y+z)*w+x:(y+z)*w+x+5] for z in range(0,5)]]]
for c in b:
 if c[12]=='S' and 'P' in ''.join([c[1+5*z:4+5*z] for z in range(1,4)]) and c.count('R')>3:
  a=re.sub('[^RPS]','.',c)
  w=h=5
for y in range(0,h):
 print a[y*w:(y+1)*w]

First attempt at writing code as compact as possible. Python is not really the language for that, as indentation and newlines are simply required by design. I mainly choose to use this language, because of the way you can play with lists, and strings as lists. A language with easy matrix manipulation would be ideal for this task, but sadly I don't know any of them.
To test thing, something needs to be assigned to a, e.g.
a=['1**********','*2*********','**3********','***4*******','****5*P****','*****S*****','*****,*****','****R**R***','***********','***********','****R******','**RPSRRR***']

Main interesting thing in this code is probably:
b=[''.join(q) for x in range(0,w) for y in range(0,h) for q in [[a[(y+z)*w+x:(y+z)*w+x+5] for z in range(0,5)]]]

which is a fancy way of writing: "b becomes a list of a representation (string of 25 characters) of every 5x5 square in the original representation".

While Matlab may have difficulty reading from STDIN, Python doesn't I'm afraid. Reading the input from STDIN is one of the requirements (to make running the test script possible as much as to stop people from coming up with their own input format).

oops, totally missed that.

Altered the code, but can't test if it actually works here. It should read it in the same format it used to be in.

Okay, I've had a chance to run the tests over this now and there's a couple of issues. 1) In cases where Santa is found, the input is output as is  before your solution. 2) Your solution is a different size than the input. I've tried to make the question clearer on this point - all non-(santa, presents, reindeer) characters should be replaced with spaces. It was like this in the first example, but it was not stated explicitly in the question. 3) When Santa is not found the output has double line-spacing.

There should be only one Santa in file (if more than 2 "S", I need update the code).
Using awk
cat santa.awk

BEGIN{FS=""}
{ for (i=1;i<=NF;i++)
         { a[NR FS i]=$i
           if ($i=="S") {l=NR;c=i}
         }
     }
END{ if (l=="") {print "No Santa";exit}
     for (i=l-1;i<=l+1;i++)
        for (j=c-1;j<=c+1;j++)
          if (a[i FS j]=="P") p++
     if (p<1) {print "Santa has no presents";exit}
     for (i=l-2;i<=l+2;i++)
        for (j=c-2;j<=c+2;j++)
          if (a[i FS j]=="R") r++
     if (r<4) {print "Santa has no enough reindeers";exit}
     else {  print "found Santa "
             for (i=1;i<=NR;i++)
               { for (j=1;j<=NF;j++)
                   if (a[i FS j]~/[R|S|P]/) {printf a[i FS j]} else {printf " "}
                 printf RS
                }
           }
    }

Run awk command as below
awk -f santa.awk file

Result
found Santa

     R
    R R
    PS
    RR
    R  R

Apologies for not reviewing this sooner (I'm on holiday and don't have easy access to wifi). Unfortunately, 2 S are allowed as long as only one is a 'valid' Santa. The tests (provided in the question) have a couple of cases that would fail for this reason.


text:
Write an interactive Deadfish interpreter
Deadfish is a joke "programming language" with four commands. Because the Esolang page is a bit contradictory and the interpreters on that page don't all work exactly the same, you should implement the following variation:

Specification

There is an accumulator which is at least 16 bits in size, more is allowed but less is not. Negative numbers do not need to be supported. The accumulator is 0 when the program starts.
There are the following two sets of four commands, and your program must support both at the same time.

  Standard Deadfish    │   XKCD Variant   │    Meaning
  ─────────────────────┼──────────────────┼────────────────────────────────────
        i              │        x         │    Increment accumulator
        d              │        d         │    Decrement accumulator
        s              │        k         │    Square ( acc = acc * acc )
        o              │        c         │    Output accumulator, as a number

If, after executing a command, the accumulator is either -1 or 256, the accumulator must be reset to zero. Note that this is not normal wrap-around. If, say, the accumulator is 20, and the s command is run, the accumulator should be 400 afterward. Similarly, if the accumulator is 257 and the d command is run, the accumulator should become 0.
Any input that isn't one of these commands should be ignored.

Test programs

xiskso should output 0
xiskisc should output 289

I/O
Your program should display a prompt: >>. The prompt must be at the beginning of a new line. It should then read a line of user input, and run the given commands left-to-right. When outputing numbers, the numbers must be separated. I.e., 12 34 is OK, 12,34 is OK,
12
34

is OK, but 1234 is not.
Your program should keep doing this in a loop, at least until EOF is reached.
Example session:
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

Because of the prompting for input, I can't use GolfScript :-(

@ProgramFOX: You can use ruby input right?

According to the GolfScript tutorial, you can't prompt for input in GolfScript, all input comes from STDIN.

@ProgramFOX: I would have thought something like #{STDIN.gets} would work but indeed it doesn't.

Are we allowed to take input with uppercase letters instead?

I believe d is double, not decrement

Can we assume all statements will end with o or c?

K, 77 bytes
  {1">>";0{x*2=-1 256?x:y@x}/("xkcdiso"!7#(1+;{x*x};{-1@$x;x};-1+))@0:0;.z.s`}`
>>xiskso
0
>>xiskisc
289

Note this is K4. A K6 solution is slightly longer because the IO verbs are longer, even if everything else is better:
{""0:">>";0{x*^-1 256?x:y@x}/("xkcdiso"!7#(1+;{x*x};{""0:,$x;x};-1+))@0:"";o`}`

""0: prints and returns its argument. Note in K4 we simply apply to 1.
0 f/ args demonstrates reduce with an initial value, i.e. f[f[0;first arg];second arg]…
{x*2=-1 256?x… classifies x into the 0 (for -1), 1 (for 256) and 2 for all other values. 2= means we get 1 for unclassified values and 0 otherwise, multiplying by x is shorter than a conditional. In K6 we can do a little better because {x*^-1 256?x:y@x} relies on the fact that -1 256?x returns 0N (null) and ^ detects nulls.
The "parser" is the map "xkcdiso" instead of the suggested order because 7# will wrap around the four arguments i.e. 7#"abcd" returns "abcdabc" which keeps our table smaller
The map translates "x" and "i" to the projection 1+ which is equivalent to the function {1+x} but shorter.
The map translates "d" to the projection -1+ which is equivalent to the function {-1+x} but shorter.
The map translates "k" and "s" to the function {x*x}
The map translates "c" and "o" to the output function {-1@$x;x} which again in K6 is slightly longer: {""0:,$x;x} but both print its output followed by a newline, and then returns the argument.
.z.s is self-recursion. In K6 we can simply say o` which is shorter.

Perl 5, 90 bytes
do{print+(map{$?+=/i|x/-/d/;$?**=1+/s|k/;$?=~s/-1|^256$/0/;"$?
"x/o|c/}/./g),'>> '}while<>

Try it online!
Thanks to @xfix for his help on this previously! Saved 4 bytes thanks to @Xcali!

Your program prints 1 when accumulator overflows. Also, you can shorten your program by five characters, by changing $a to $? (which is initialized to 0, and won't change until you run some external program from Perl).

Ahhhh, I was hunting for a variable I could use, perfect, thank you! As for overflowing, I didn't notice it as it only happens if you run issso as one command, not if you do each separately... I'll have a look at this later on and will certainly use $?. Thank you!

So I think I left an older version in the code section at the top with '' instead of "" so when used with perl -e '...' the map would end with the result of the s///. Thanks again!

OK, you're the shortest.

No longer the shortest answer.

Using a -F flag and combining the first two conditions can get this down to 77 bytes of code: Try it online!

@Xcali As this needs to be interactive (and print out the >>  before first input) I don't think I can use -n/-F. :( but I can definitely combine the first two checks, that great, thanks!

Rebol 3, 178 169 161 159
f: does [if a = -1 or (a = 256)[a: 0]]d: [any[["i"|"x"](++ a f)|["d"](-- a f)|["s"|"k"](a: a * a f)|["o"|"c"](print a)| skip]]a: 0 forever [parse (ask ">>") d]

Prettier version:
f: does [if a = -1 or (a = 256) [a: 0]]
d: [
    any [
        ["i"|"x"] (++ a f) |
        ["d"] (-- a f) |
        ["s"|"k"] (a: a * a f) |
        ["o"|"c"] (print a) |
        skip
    ]
]
a: 0
forever [parse (ask ">>") d]

Powershell, 131 126 121 114 113
for($x=0){[char[]](read-host ">>")|%{switch -r($_){"i|x"{$x++}"d"{$x-=!!$x}"s|k"{$x*=$x}"o|c"{$x}}
$x*=$x-ne256}}

for($x=0){...}     - set the accumulator to 0 and loop forever
read-host '>>' - get the user input with prompt >>
[char[]](...)    - convert the user input to an array of characters
|%{...}          - perform what's inside {} for each character
switch -r($_)    - regex switch for each character
"i|x"{$x++}      - match i or x - increase the accumulator
"d"{$x-=!!$x}    - match d - decrease $x by !!$x, which will be 0 if $x is 0, and 1 otherwise. This makes sure the accumulator never reaches -1.
"s|k"{$x*=$x}    - match s or k - square
"o|c"{$x}        - match o or c - output the accumulator
$x*=$x-ne256 - multiply the accumulator by 0 if it is 256 or by 1 otherwise

Example output
>>: xiskso
0
>>: xiskisc
289
>>: ddddo ddddo
285
281
>>: ddddo ddddo
277
273
>>: dddddddo
266
>>: dddddddddo
257
>>: do
0
>>: do
0
>>: io
1
>>:

I guess the implementation of read-host is host specific, so this Powershell host (ConsoleHost) appends : to the specified prompt.

Nice! Love the decrement by !!$x, shame I can't utilise that...

Hey Danko, could you post some test output please? I don't think I can test power shell on non-windows... (please correct me if I'm wrong!)

I've added some test output to the answer.

Haskell, 202
r=pure;-1%c=0%c;256%c=0%c;s%'o'=s<$print s;s%'c'=s%'o';s%'i'=r$s+1;s%'x'=s%'i'
s%'d'=r$s-1;s%'s'=r$s^2;s%'k'=s%'s';s%_=r s;n s(c:[])=s%c;n s(c:f)=s%c>>=(`n`f)
main=p 0;p s=putStr">> ">>getLine>>=n s>>=p

You could probably save a few characters by changing e and v into operators. I also tried rewriting v and g so that the parameter x stays in IO, and print etc. get lifted. I didn't manage to get it working, but I think that might be a good place to go for someone who knows their haskell.

@shiona: Yeah, the thing about keeping things in IO is that they either print too often (that’s why I used r n instead of x) or not enough because the value is never asked for…. So how would I change e and v into operators?

I had the same problems with printing. What comes to operators you can do (using e as example) 'i'%x=x+1;'d'%x=x-1... And just call it in v do n<-x;r$w$o%n. The reason operators save space is that they don't require spaces around them.

@shiona: Oh! Good call, thank you!

No problem. I first thought about making an answer of my own but since I couldn't get my big ideas working I thought it would be just rude post exactly the same code with just different notation for the same functions.

You can save some bytes by using (>>), using pure and getting rid of the import: Try it online! (see my solution for why this works).

Python 3, 141
I know I am to late, but I wanted to take the opportunity to post a shorter Python-version (and my first CodeGolf-attempt). :)
v=0
m=lambda y:(0,y)[-1!=y!=256]
i=x='+1'
d='-1'
s=k='*v'
c=o=');print(v'
while 1:
 for n in input('>>'):exec('v=m(v'+locals().get(n,'')+')')

The print-statement was kinda tricky for this.
If the prompt has to end with a whitespace, add one char to the count. :)
Explanation
v is the accumulator.
m checks whether the given value is -1 or 256. If so, 0 will be returned, the value otherwise.
In the following lines the operations are assigned to the corresponding variables (as some have the same meaning (like i and x) this is shorter than instantiating a new dictionary). Those are then used in the exec below.
while 1: is the main-loop
Now the fun begins. Like @jazzpi's solution, it iterates over each char of the input. locals() is the dictionary of all current (visible) variables. With .get(n,'') the corresponding key will be put into the exec-string (an empty string, if the key (= other input) was not found). This then will be, when executed, concatenated with v and passed towards m. The return value will be stored in v again.

Short example:
Be n = 'i' (n = input-char), we get '+1' out of the locals-block as i is the variable with value '+1'.
  The string for the exec than looks like this: 'v=m(v+1)'.
  Maybe now it is easier to see, that, when executing, it will call m with the value of v+1 and store it's output in v again.

Repeat this until you are bored. :)

I realize I'm VERY late to the party, but the lambda for m can be y*(-1!=y!=256) for -3 bytes

just 5 years :) thanks for the input though. I am too lazy to fix the answer not but I'll keep it in mind

K, 121
i:0;while[1;1">> ";{i{(r;0)(-1~r)|256~r:y x}/d{x@&x in y}[x;!d:"ixdskoc"!,/(2#(1+);-1+;2#{x*x};2#{-1@$i::x;})]}'" "\:0:0]

.
C:\q>q deadfish.k -q
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

My version is shorter. I compressed the map, relied on ? to classify for "wrapping" values, used recursion instead of while, and a functional interpreter instead of amend.

Ruby, 140 138
a=0
loop{$><<'>> '
eval gets.gsub(/./){|c|({i:i='a+=1',x:i,d:'a-=1',s:s='a**=2',k:s,o:o='p a',c:o}[:"#{c}"]||'')+';a=a==-1||a==256?0:a;'}}

Sample session (same as yours):
c:\a\ruby>deadfish
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

Ada
Here's an Ada implementation for the few who're interested by this language. It took me quite some time in order to use some of Ada's best practices (like the use of Indefinite_Holders instead of access) and also to fully comprehend how's Deadfish must work.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Holders;
with Ada.Integer_Text_IO;

procedure Deadfish is
   package String_Holder is new Ada.Containers.Indefinite_Holders(String);
   use String_Holder;

   value_output : Natural := 0;
   str_input : String_Holder.Holder := To_Holder("");
begin
   Prompt :
   loop
      Put(">> ");
      String_Holder.Replace_Element(str_input, Get_Line);
      for rg in str_input.Element'Range loop
         case str_input.Element(rg) is
            when 'i' | 'x' =>
               case value_output is
                  when 255 => value_output := 0;
                  when others => value_output := Natural'Succ(value_output);
               end case;

            when 'd'       =>
               case value_output is
                  when 257 => value_output := 0;
                  when 0 => null;
                  when others => value_output := Natural'Pred(value_output);
               end case;
            when 's' | 'k' =>
               case value_output is
                  when 16 => value_output := 0;
                  when others =>value_output := value_output * value_output;
               end case;
            when 'o' | 'c' => Ada.Integer_Text_IO.Put(value_output, Width => 0); Put_Line("");
            when others => null;
         end case;
      end loop;
   end loop Prompt;
end Deadfish;

And the output :
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

If some people experimented in Ada could give me some optimisation hints, I would be thankful.

Welcome to PPCG! The goal of code-golf is to create the shortest possible code, and you should include the size of you program in the header (1396 bytes here)

C, 159 chars
A; main(c) {
  printf(">> ");
  while (c = getchar(), ~c)
    A = c - 'i' & c - 'x'?
        c - 'd'?
        c - 's' & c - 'k'?
        c - 'o' & c - 'c'?
        c - '\n'?
        A :
        printf(">> "), A :
        printf("%d\n", A), A :
        A * A :
        A - 1 :
        A + 1,
    A *= ~A && A - 256;
}

I tried another approach based on setting up a look-up table for instruction decoding, but unfortunately that ended up longer (169).  I included it since someone might come up with a clever tweak to cut down the size. (Must be run without any arguments)
#define X !--c?A

A,M[256];
main(c) {
  for(; !M['x']; c++) M["@osid\nckx"[c]]-=c%5+1;
  for (printf(">> "); c = ~M[getchar()]; A *= ~A && A - 256)
  A= X,printf("%d\n", A),A:X*A:X+1:X-1:A;
  main();
}

155 bytes

Python 3, 181 175 171 162
a=0
s=lambda x:"a=%d"%(x!=-1and x!=256and x)
while 1:
 for i in input(">>"):u,b,o=s(a+1),s(a*a),"print(a)";exec(dict(i=u,x=u,d=s(a-1),s=b,k=b,o=o,c=o).get(i,""))

This outputs a newline after the >>, but the OP didn't say that wasn't allowed. Not anymore!
Thanks to GlitchMr, minitech and golfer9338!

You can use lambda instead of def for a function that immediately returns.

x in(-1,256) saves two characters. Alternatively,
s=lambda x:"a=%d"%(x!=-1and x!=256and x) could save some.

You could remove print(">>") and use for i in input(">>") instead; input() allows specifying a prompt. Then, there will be no newline after >>, and you save characters.

Your score should be, I think, one char shorter right now.  Please doublecheck, but I get a count of 161 instead of the posted 162: lines of 3+40+8+107, plus 3 newlines. Truth be told, I'm jealous, because either way, you're a few chars shorter than my C answer.  Cheers!

C, 163
#define i(u,v);if(c==u+89|c==v+89)
a;main(c){printf(">>");while(c=getchar()-10){i(6,21)a++i(1,1)a--i(8,16)a*=a;i(0,12)printf("%d\n",a);a=a==-1|a==256?0:a;}main();}

R, 161, 148, 138
a=0;repeat{x=readline(">> ");for(i in utf8ToInt(x)-99){a=a^((i==8|i==16)+1)+(i==6|i==21)-(i==1&a);a=a*(a!=256);if(i==0|i==12)cat(a,"\n")}}

Ungolfed version:
a = 0
repeat{
  x = readline(">> ")
  for(i in utf8ToInt(x) - 99) {
    a = a ^ ((i == 8 | i == 16) + 1) + (i == 6 | i == 21) - (i == 1 & a)
    a = a * (a != 256)
    if(i == 0 | i == 12) cat (a, "\n")
  }
}

Example session (in interactive mode):
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

Python 2, 139
a=0
while 1:
 for c in raw_input(">> "):
  if c in'ix':a+=1
  if c=='d':a-=1
  if c in'sk':a*=a
  if c in'oc':print a
  if a in(-1,256):a=0

This is neat, but also pretty straightforward.
Here's a longer, cooler version:
def i(a):
 while 1:
  c=yield
  if c in'ix':a+=1
  if c=='d':a-=1
  if c in'sk':a*=a
  if c in'oc':print a
  if a in(-1,256):a=0
 j=i(0);next(j)
while 1:
 for c in raw_input(">> "):j.send(c)

Weighing in at 190 characters, it's perhaps not the most competitively-lengthed answer here.  On the other hand, coroutines are pretty rad and I'm always looking for an excuse to use (and share) them

TI-BASIC, 104 107 102 100 98
For TI-83+/84+ series calculators.
Name this prgmD; it eventually overflows the stack by calling itself. Replace the recursion with a While 1, at the cost of two bytes, to fix this.
Input ">>",Str1
For(I,1,length(Str1
int(.5inString("?ixskd?oc",sub(Str1,I,1
If Ans=4
Disp Y
imag(i^Ans)+Y^int(e^(Ans=2     //decrements when Ans=3; increments when Ans=1
min(0,Ans(Ans≠256→Y
End
prgmD

Y is 0 by default, so either run this with a freshly memory-cleared calculator or store 0 to Y manually before running this.
Too bad that the lowercase letters (in the string literals) are two bytes each; otherwise this would be shorter than Dom Hastings' answer.
EDIT: Fixed a divide-by-zero (0^0) error at the cost of three bytes.
107 -> 102: Used imaginary exponentiation trick to save four bytes (including 1 from parentheses and -1 from lengthening the lookup string) and used Y instead of X, which takes one less byte to initialize.

C (224 212 characters)
This is probably a bad language choice, but oh well. It's not that language like C can do better than some dynamic programming language. On Clang, you will need to specify a value for return (this is not necessary for gcc).
#define s(x,y)case x:y;break;
main(){int c=10,a=0;for(;;){switch(c){s(-1,return)s('i':case'x',++a)s('d',--a)s('s':case'k',a*=a)s('c':case'o',printf("%d\n",a))s(10,printf(">> "))}a!=-1&a!=256||(a=0);c=getchar();}}

Wouldn't it be shorter to just remove the define q and just use printf?

@DoorknobofSnow Actually no. q is used 3 times, so define q saves ~2 chars.

156 bytes

Postscript 272
/cmd<</i{1 add}/x 1 index/d{1 sub}/s{dup mul}/k 1 index/o{dup =}/c 1 index>>def
0{(>> )print flush{/f(%lineedit)(r)file def}stopped{exit}if{f
1 string readstring not{exit}if cmd exch 2 copy known{get exec}{pop pop}ifelse
dup -1 eq 1 index 256 eq or{pop 0}if}loop pop}loop

Ungolfed:
/cmd <<  % define commands
/i { 1 add }
/x 1 index
/d { 1 sub }
/s { dup mul }
/k 1 index
/o { dup = }
/c 1 index
>> def
0        % accumulator on stack
{
    (>> )print flush   % print prompt
    { /f (%lineedit) (r) file def } stopped {exit} if  % read input line or quit
    {
        f 1 string readstring not {exit} if   % read 1-char string from line
        cmd exch 2 copy known { get exec }{ pop pop } ifelse   % execute command or don't
        dup -1 eq 1 index 256 eq or { pop 0 } if   % adjust accumulator if needed
    } loop
    pop
}loop

Haskell, 186 178 bytes
This needs to be run with runhaskell (or inside ghci) since they both set the BufferMode to NoBuffering by default which safes quite a lot of bytes:
infix 4#
-1#x=0#x
256#x=0#x
r#x:y=case x of 'i'->r+1#y;'x'->r+1#y;'d'->r-1#y;'s'->r^2#y;'k'->r^2#y;'o'->print r>>r#y;'c'->r#'o':y;_->r#y
r#_=putStr">> ">>getLine>>=(r#)
main=0#""

Try it online!
Explanation
This defines a new operator state # source (the fixity declaration allows us to drop parentheses when using it in conjunction with other operators (+),(-),(^),(:) and (>>)):

the first two lines "fix" the states -1 and 256
it then matches the first character and acts upon it
once it runs out of characters (r#_), it reads new ones and starts over again keeping the old state

To start the process we initialize the state with 0 and read a new source line, ie. begin with an empty source:
main=0#""

Python 3, 130 119 bytes
a=0
while 1:
 for c in input(">> "):
  a+=(c in'ix')-(c=='d')+(a*a-a)*(c in'sk')
  if c in'oc':print(a)
  a*=-1!=a!=256

Try it online!
This is just a conversion of stackspace's response to Python 3, with an improvement to the wrap-around code. We gain 1 byte from losing the print statement, but save 4 bytes from switching to input(), and remove another 6 from the new wrap-around code.
Edit: Saved another 11 bytes by moving all the math operations onto one line. Moving the square operation doesn't actually save any bytes, but it does look cooler.

You can save a few bytes by doing a-=c=='d' and a+=c in'ix' instead of the first 2 if statements

Welcome to the site!  Piggy backing off of the suggestion from @Dudecoinheringaahing you can then combine the two lines into one as a+=(c in'ix')-(c=='d')

That is evil. Thank you both.

Lua, 230 228
a=0repeat io.write(">> ")x=io.read()for i=1,#x do c=x:sub(i,i)if c=="i"or c=="x"then a=a+1 elseif c=="d"then a=a-1 elseif c=="s"or c=="k"then a=a*a elseif c=="o"or c=="c"then print(a)end if a==256or a==-1then a=0 end end until _

Not the worst, not the best.
NOTE: as reported by @mniip 256or may not work in your interpreter. More info in comments.
(more or less) Readable version:
a=0
repeat
  io.write(">> ")
  x=io.read()
  for i=1,#x do
    c=x:sub(i,i)
    if c=="i"or c=="x"then
      a=a+1
    elseif c=="d"then
      a=a-1
    elseif c=="s"or c=="k"then
      a=a*a
    elseif c=="o"or c=="c"then
      print(a)
    end
    if a==256or a==-1then
      a=0
    end
  end
until _

Output:
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

Edit: thanks to @mniip for 2 char optimization: until nil -> until _

repeat until x (x is nil as not been defined) is 2 chars shorter, and while 1 do end is exact same length, other than that what lua version is that? 256or is invalid syntax in my interpreter

@mniip Thanks for hint about repeat until x. I'm using latest windows binary from here. As you can see a=a+1 elseif have space. That's because e is hexadecimal digit, while o in 256or is not, so my interpreter takes or as another statement/block/howYouCallIt.

yeah pretty much besides 256or, also 0repeat and 1then; I am using official lua from lua.org, your code doesn't compile in either 5.1, 5.2, or 5.3

Windows Batch, 204 256
@echo off
set a=0
:a
set /p i=^>^>
if %i%==i set /a a=%a%+1
if %i%==x set /a a=%a%+1
if %i%==d set /a a=%a%-1
if %i%==s set /a a=%a%*%a%
if %i%==k set /a a=%a%*%a%
if %i%==o echo %a%
if %i%==c echo %a%
if %a%==256 set a=0
if %a%==-1 set a=0
set i=n
goto a

Successfully ignores other commands. Really got bloated without having or to work with...
Edit:

Fixed:

No more Echoing all commands
Made it actually DO math with /a
Reset on -1
Reset input after every cycle

This cost 52 characters.
Didn't fixed:

Squaring 0 writes "0*0" in a.
Inputting space (or inputing nothing, when you just opened it) crashes script.
You NEED to input one char at a time.

This one just plain does not work at all (Windows 7). I don't mean to be an asshole but did you test this?

@marinus It's been fixed.

Windows Command Script - 154
Abusin unknown features to the max.
@echo off
set i=1
set x=1
set d=-1
set/as=[*[-[
set/ak=[*[-[
set.=0
set/p.=^>^>
set/a[=[+%.%
e%.:o=c%h%.:c=o% %[% 2>nul
set[=%[:-1=%
if;%[%==256 set[=
%0

><>, 258 bytes
I've done another ><> answer since I couldn't test phase's and it used pre-stacked commands rather than emulating a shell anyway.
0v
"<vooo">>
!~>i:0)?v~ >
 ^?=a:  /  ^!?="c"v?="o":v?="s":v?="k":v?="d":v?="x":v?="i":
   voan:<        ~<  v*:~<      <  v-1~<  v+1~<      <
   <                 <             <      <vv?=-10:v?=*:+1f:
  v                                        <>      >~0

It can certainly be golfed down, but I'm not sure I'll have the needed insanitybravery !
I tested it with the official interpreter running under python 3.5 under cygwin under windows 7 and could reproduce the test run :
$ python fish.py deadfish.fish
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>> (pressed ctrl-Z)Stopped

In case you can't run it on your machine (input seems to be tricky) or you just want to try it without any other software, you can use the following version on the online interpreter.
0v
 <vooo">> "<
  >i:0)?v~
      o:/  ^!?="c"v?="o":v?="s":v?="k":v?="d":v?="x":v?="i":
 ^oanoa:<        ~<  v*:~<      <  v-1~<  v+1~<      <
   <                 <             <      <vv?=-10:v?=*:+1f:
  v                                        <>      >~0

It obviously disregards \n and EOF since you can't input them in the online interpreter, but will behave as if enter had been pressed after each output command.

C (gcc), 139 bytes
Compile with -Dk="_nZZiaeY" (included in byte count). -2 bytes if prompt >>\n is allowed.
x;f(c){for(printf(">>");c=getchar()-10;x+=c--?c--?c--?c||printf("%i\n",x),0:x*x-x:-1:1,x*=~x&&x^256)c=strchr(k,c)-k>>1;f();}

Try it online!
Degolf
/** Preprocessor **/
-Dk="_nZZiaeY" // This is a lookup string; it corresponds to "ixddskoc",
               // with 10 deducted from each character. Upon compilation,
               // all occurences of the string literal are replaced with a
               // pointer to its location in memory.

/** Source **/
x;f(c){ // x: 32-bit accumulator, c: local variable for read character
    for(printf(">>"); // Start for-loop and print prompt.
            c=getchar()-10; // Read a character from STDIN.
                            // Loop breaks if it is '\n'.

            // The below happens at the end of each iteration.
            x+=c--?c--?c--?
               // Find the correct operation by testing c and post-
               // decrementing with multiple ternary-ifs. If c is 0,
               // operation was found, add the else-value to the
               // accumulator x.
               //     If the character is invalid, the value of c is
               // very large, and will not reach 0 with 3 decrements.

               c||printf("%i\n",x),0
               // If c-3 is 0, print accumulator, else do nothing.
               // Returns 0 regardless of what happens. (No change to x)
               :x*x-x
               // Square. Results in x=x+x*x-x, and is shorter than (x*=x)
               :-1:1,
               // Decrement, Increment.
               x*=~x&&x^256
               // Because -1==0xffffffff, ~x==0 when x==-1. Likewise,
               // x^256==0 only when x==256. The logical-AND coerces the result
               // to boolean 1 (no match) or 0 (match). Multiplication resets
               // the accumulator as appropriate.
           )
        // This is the actual body of the for-loop
        c=strchr(k,c)-k>>1;
           // Finds the index of the read character in the lookup string,
           // then "divides" it by two.
           // Because strchr() returns NULL (0) when character is not found,
           // deducting k from it results in a very negative number.
           // The right-shift results in division by 2 for positive numbers,
           // while the negative numbers become very large positive numbers
           // (c >= 0x70000000) because of the 2's complement representation.
    // Finally, recurse until forceful termination.
    f();
}

Keg, 68B
0{'::"ÿ1+=$0<+['_0"] \>\>\
,,,,?:o=[':."]:i=['1+"]:d=['1-"]:s=[':*"

Haskell, 230
import System.IO
i""n=[]
i(a:b)n
 |a=='o'||a=='c'=[n]++i b n
 |True=i b$v a n
v a n=w(case a of 'i'->n+1;'x'->n+1;'d'->n-1;'s'->n^2;'k'->n^2)
w(-1)=0
w 256=0
w n=n
main=do;putStr ">> ";hFlush stdout;s <- getLine;print$i s 0;main

If only I could get rid of that pesky hFlush stdout call!  Without it, the prompt is not displayed until an o operation is performed.  Any advice?

You can get rid of the hFlush by using runhaskell instead of compiling (see my answer), but as for this solution it's not valid and errors out.

Golf-Basic 84, 88 characters
:0_A:0_O:1_I:2_D:3_S:O_C:I_X:S_Kl`1i`N@A=256:0_A@N=0d`A@N=1:A+1_A@N=2:A-1_A@N=3:A^2_Ag`1

Prompts one command at a time, as in at least 3 other solutions. Here is a test run for xiskisc:
?X
?I
?S
?K
?I
?S
?C
             289

Also, xiskso outputs 0, as it should.

Which other solutions prompt one command at a time?

The Perl and Haskell ones.

I wrote the Haskell one, and no, it doesn’t. Nor does the Perl one, so I’m really not sure what you’re talking about.

@minitech: For fun I did add a Perl one that doesn't print a prompt and accepts one char only per line at 77 chars.

This doesn't follow the I/O rules.

Still doesn't follow the rules, and uses uppercase letters rather than lowercase.

If you know about TI-BASIC, it only supports uppercase input.

PHP+HTML 345
<form><?php $i=0;$o='';if(isset($_GET[i])){$i=$_GET[a];foreach(@str_split($_GET[i]) as $j=>$v){$v==i||$v==x?$i++:($v==d?$i--:($v==k||$v==s?$i*=$i:($v==o||$v==c?$o.=$i."\n":'')));($i==256||$i==-1)&&$i=0;}$_GET[p].='>> '.$_GET[i]."\n".$o;echo"<textarea locked name=p>$_GET[p]</textarea><input type=hidden name=a value=$i><br>";}?>>> <input name=i>

output is a little sketchy (history/session is shown on a textarea, and with error reporting enabled a lot warnings are printed) but everything works

><>, 239
v
\r0&
v                  <
\&::&01-=$f1+:*=+?v
v             &0~&<
\:"i"=?v
       >~&1+&      ^
\:"d"=?v
       >~&1-&      ^
\:"s"=?v
       >~&:*&      ^
\:"o"=?v
       >~&:o&      ^
\:"h"=?v
       >~;        (^)
>~                 ^

The initial stack is the input.
You can try it online here.

JavaScript (Node.js), 204 Bytes
process.openStdin(f=a=>process.stdout.write((i=0,""+a).split` `.map(x=>([...x.slice(0,-1)].map(d=>({i:x=e=>i++,d:e=>i--,s:k=e=>i*=i,o:c=e=>e,x,k,c})[d](i=-1||i==256?i=0:0)),i))+"\n>> "),f``).on("data",f)

This can probably be golfed. Node.js again proves it's strange disguised verbosity once again.
Code explained:
process.openStdin( // This function has to be called to take input, but doesn't have arguments
  f=a=> // Define a function f. This is the deadfish interpreter. It takes an argument `a` which is a Buffer
  process.stdout.write( // Same as console.log, but doesn't output trailing newline
    (i = 0, "" + a) // Take advantage of comma operator to (A) define the accumulator i, and casts a (which is a Buffer) to a String
      .split` ` // Split the string a at spaces, making it an array
      .map(     // Map through each element of the array
        x=>     // Map function, takes argument x, the value in the array (string)
          ([...x.slice(0,-1)] // Remove the last character (newline) and than use the spread operator to divide the string into an array of it's chars
            .map(d=> // Map function, you know how this works
              ({ // Here I define the various deadfish commands
                i: x = e => i++,
                d: e => i--,
                s: k = e => i*=i,
                o: c = e => e,
                // Take advantage of ES6 object notation. Equivilent to {"x": x, "k": k, "c", c}
                x,
                k,
                c
              })
              [d] // Get the command to execute. If this is passed something which isn't valid, a giant error will appear
              (
                i==-1 || i==256 ? i = 0 : 0 // Take advantage of the fact that none of the command functions take arguments to handle the strange "overflow"
              )
            ),
          i)
      ) +
  "\n>> "), // Display the prompt again, as well as a newline
  f`` // Initalize the prompt by passing an empty script
)
.on("data",f) // Bind the f function to newline on STDIN

C#, 311 bytes
using System;class p{static void Main(){int a=0;int s(int b)=>b==-1||b==256?0:b;while(true){Console.Write(">>");var c=Console.ReadLine();for(int i=0;i<c.Length;i++){switch(c[i]){case'i':case'x':a=s(a+1);break;case'd':a=s(a-1);break;case's':case'k':a=s(a*a);break;case'o':case'c':Console.WriteLine(a);break;}}}}}

would be 283 byte if usings and class declaration etc could be ommitted by just providing a function definition

05AB1E, 50 bytes
0[„>>,I"idsoxdkc"©Ãε®skн}"><n="sè"Džz1(‚såi0}"ý.V

Try it online!
Explanation:
The basic idea is to translate it into 05AB1E code and eval it.
0[„>>,I"idsoxdkc"©Ãε®skн}"><n="sè"Džz1(‚såi0}"ý.V
0                                                    Set the accumulator to 0.
 [                                                   Do this forever.
  „>>,                                               Print ">>"
      I                                              Read input
       "idsoxdkc" Ã                                  Keep only "idsoxdkc" characters.
                 ©                                   Also put "idsoxdkc" in the register.
                   ε    }                            For each character in the filtered input:
                    ®skн                             Find it's index in "idsoxdkc"
                         "><n="sè                    Index into "><n="
                                 "Džz1(‚såi }"ý      After each command, check if accumulator = -1 or 256
                                           0         If it does, change it to 0
                                               .V    Evaluate as 05AB1E code.

Tidy, 136 bytes
a:=0{h:a:=a+1 if h='i∨h='xa:=a-1 if h='da:=a*a if h='s∨h='kout(a)if h='o∨h='ca:=0 if a=-1∨a=256}→stoa(h)while h:=prompt(">> ")

Try it online! prompt is interactive, so it looks a bit weird online. See the "Example run" section below.
Ungolfed and commented
? initialize the accumulator
acc := 0

map(

    ? map this function...
    { char :
        acc := acc + 1      if char = 'i  or  char = 'x
        acc := acc - 1      if char = 'd
        acc := acc * acc    if char = 's  or  char = 'k
        out(acc)            if char = 'o  or  char = 'c
        acc := 0            if acc  = -1  or  acc  = 256
    },

    ? over each character...
    stoa(line)

? over each line
) while line := prompt(">> ")

Example run
C:\Users\conorpc\Programming\Tidy (master -> origin)
λ tidy test.tidy
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

Emojicode, 308 bytes
0➡a>>❗c❗↪dxdikscoc❗➡i↪i◀4a⬅➕i2✖2➖1↪i◀6a⬅✖aa 10❗❗↪a-1a2560➡a

Try it online here.
Ungolfed:
    Main code block
    0 ➡   a   Accumulator, initialised to 0
         Repeat forever:
         >> ❗   Output prompt
         c    ❗    For each character c in the next line of input:
            ↪  dxdiksco c ❗ ➡ i    If the character is a valid command, get its index i in the string "dxdiksco"
                ↪ i ◀ 4    If that index is less than 4, it is either the increment or the decrement command ...
                    a ⬅ ➕ i  2 ✖ 2 ➖ 1   ... adjust accumulator accordingly

                 ↪ i ◀ 6    Else, if it is smaller than 6, it is the square command ...
                    a ⬅ ✖ a   ... multiply the accumulator by itself
                     Else, it must be the print command ...
                      a 10 ❗❗   .. output the accumulator in base 10, followed by a line feed

                ↪ a  - 1  a  256    If the accumulator is now either -1 or 256 ...
                    0 ➡  a   ... reset it to 0

Pip, 70 bytes
W(O">> ")&#YqR'i'xFcy@`[xkcdso]`;V("U SQ:  P i&D SQ:"^sAc)."i*:i!=256"

(-1 byte if no space is needed after the >>, which is what the accepted answer does but is contrary to the example given in the question. +1 byte if an empty line isn't an acceptable way of marking end-of-input.)
Try it here!
Explanation
The core of the interpreter is based on my answer to the other Deadfish question, with some reshuffling to accommodate the xkcd input, so I won't repeat that part of the explanation. The interaction loop is as follows:
W                                 While...
  O">> "                           Output the prompt with no newline
 (      )&                         Logical AND that (nonempty string, truthy) with...
            q                      Read a line of input
             R'i'x                 Replace all i's with x's
           Y                       Store it in y
          #                        Take the length
                                  So, loop while (prompt and read input) is nonempty:
                                    [translate and eval all valid commands in y]

AWK, [133] 122 bytes
gsub(z,FS){for(a=0;b=$++a;c==-1||c==256?c=0:0)if(b~"o"||b~"c")print c;else b~"i"||b~"x"?c++:b~"d"?c--:b~"s"||b~"k"?c*=c:0}

Try it online!
Thanks to user41805 for hints that dropped 11(!) chars
This is pretty straight forward in the end.  I think the only reason it's somewhat short is that AWK is essentially a state machine, which fits the problem pretty well.
gsub(z,FS)

Splits the input line such that each letter is one positional field.
{for(a=0;b=$++a; ... ) ... }

Loops through all the positional variables (one letter for each one).
c==-1||c==256?c=0:0

The end of loop statement just handles the wrap around code, resetting the accumulator c when it hits -1 or 256.
if(b~"o"||b~"c")print c;else ...

The print command can't be handled by the nested ternary that deals with all the other commands, since in AWK print doesn't return a value.  So that's pulled out into an if/then/else statement.
b~"i"||b~"x"?c++:b~"d"?c--:b~"s"||b~"k"?c*=c:0

Handles all the other commands, adjusting the accumlator c as necessary.

$0 is implicit in gsub and can be removed. " " can be replaced with FS. Also the b=="..."'s can be replaced with b~"...".


text:
Is it a Diff or not?
Your program will be run an undetermined amount of times. On all but the last, there will be a file called data in the same directory of your program that has the same value each time. On the last run, the file will be there but will have different data in it. On all the times except the last, you can do whatever you want, as long as the following rules are met:

Don't output anything
Don't change data file

On the last run, you must print out the diff of the first data file and the current data file.
Rules:

You may save whatever you want in any files you want, just don't edit the data file

Scoring:

Lowest char score wins

Cheating encouraged. You have no indication of which run you're in except that the data file is changed.

what's the definition of "diff"?

also, what is the possible contents of data? Can we assume it contains all alphanumeric characters?

@DoorknobofSnow https://en.wikipedia.org/wiki/Diff

what I meant is, can we do something like -olddata +newdata? what is the format of the diff?

On all the times except the last, we don't output anything. How is the "last run" defined?

If you're saving a file, doesn't that contradict Don't output anything?

@KaranGoel The last run is defined as the one where the data is changed.

@DoorknobofSnow Assume you will be calling the diff utility.

Bash (31)
[ -e x ]&&diff data x;cp data x

Kinda obvious.

Here it is with good ol' Windows batch:
@echo off
  if exist lastdata goto compare_data
  type data > lastdata
  goto end
:compare_data
  fc data lastdata > nul
  if errorlevel 1 goto last
  if errorlevel 0 goto end
:last
  fc data lastdata
  del lastdata
:end


text:
Make a regex that matches certain binary numbers
Your task is to create a regular expression that matches most binary numbers with an even number of 0s and an odd number of 1s (e.g. "101100011").
The full criteria for the regex are:

matches 90% or more of all binary numbers between 0 and 11111111 with even number of 0s and an odd number of
1s,
doesn't match 90% or more of all binary numbers between 0 and 11111111 with odd number of 0s or an even number of
1s,
works in most common programming languages.

Ideally, it should be short and creative.
The input string always has a length that is greater than 1, less than infinity, and only contains 1s and 0s.
I will upvote any answer that seriously attempts to match the above criteria. Once the activity around this question dies down, I'll accept the highest-voted answer that is at least only 1.333... times the length of the shortest answer.

http://stackoverflow.com/q/20485486/1223693

@DoorknobofSnow shhhhh

Maybe I don't understand the problem, but there are none which can match. All binaries you assume as input are exactly 8 bits long (your examples indicate that leading zeros are provided) and thus odd+even cannot be true at all.

Moreover: short and creative doesn't sound very objective. If it is popularity-contest please tag it accordingly. (note: I don't think that this is a good example of a popularity-contest).

As @Howard points out, the 8-bit range specific criteria are impossible, but that would still appear to leave the initial statement of "most binary numbers with an even number of 0s and an odd number of 1s", later qualified with length "greater than 1, less than infinity."  I take most to mean >50%.

@Howard Thanks for noticing that. I feel stupid now.

I think there is a missing specification of "without leading zeroes" here, which would allow for 8-bit binary numbers <1111101 to match the target pattern.

Remaining thoughts...  Opening sentence suggests 9-bit numbers are in scope, while the "full criteria" section limits itself to 8-bits, but then later I read that input strings can be binary strings of infinite length. These are not strictly conflicting, but it's a bit of a head-scratcher. I would also suggest removing the word "most" in the opening sentence (since it suggests a portion of more than 50%) of even 0-count and odd 1-count (of any length, apparently at least 9 bits in the example string) but that is not emphasized again.

The following regex
(?=^1*(01*0)*1*$)^.(..)*$

works in many languages. It performs a perfect match for any binary of arbitrary length.
Basically, it consists of two parts which are joined via and by using a lookahead pattern:

^1*(01*0)*1*$ matches if an even number of zeros is provided.
^.(..)*$ tests for an odd number of digits in total.

The test run can be seen here.

80 characters long
^(?:(?(1)|(1))|0101|1010|(?:1{2})+|(?:0{2})+|0(?:1{2})+0|1(?:0{2})+1|)+(?(1)|a)$

Doesn't match some numbers that have an odd number over four 1s in a row, e.g 01111101

so does this match exactly 90% of numbers between 0 and 0b11111111? (I tried to test, but apparently this regex doesn't work in Ruby.)

@DoorknobofSnow Whoops, edited question.

Ah, okay, well in that case, why the {2}s? Repeating the previous digit would be shorter.

And what's with the a at the end?

@DoorknobofSnow I don't quite know why I put those {2}s there... The a makes the regex fail if the the first capturing group doesn't capture anything, which should only happen if there is an even number of 1s.

I've been able to get down to 52 characters with only the most basic regex features: (1|0(00|11)*(10|01))((10|01)(00|11)*(10|01)|00|11)*