text:
Is string X a subsequence of string Y?
Given strings X and Y, determine whether X is a subsequence of Y. The empty string is regarded as a subsequence of every string. (E.g., '' and 'anna' are subsequences of 'banana'.)
Input

X, a possibly-empty case-sensitive alphanumeric string
Y, a possibly-empty case-sensitive alphanumeric string

Output

True or False (or equivalents), correctly indicating whether X is a subsequence of Y.

I/O examples
X      Y        output

''     'z00'    True
'z00'  'z00'    True
'z00'  '00z0'   False
'aa'   'anna'   True
'anna' 'banana' True
'Anna' 'banana' False

Criteria

The shortest program wins, as determined by the number of bytes of source code.

Example programs

Several programs that could be adapted are in this related posting.

Why is 'anna' substr of 'banana'?

@kaoD - anna is a subsequence (but not a substring) of banana. String X is a subsequence of string Y just if X can be obtained from Y by deleting zero or more of the elements of Y; e.g., deleting the b and the second a from banana gives anna.

This has about a single solution in every scripting language offering regex that's both trivial to see and impossible to golf further.

Perl 5, 17 bytes (+1?), full program
s//.*/g;$_=<>=~$_

Try it online!
Invoke with the p flag to the perl interpreter, as in perl -pe 's//.*/g;$_=<>=~$_'.  Per the established scoring rules when this challenge was originally posted, this flag costs one extra byte.  Under more recent rules, AFAICT, it may be free.
Either way, the input strings should be supplied on separate newline-terminated lines on stdin.  Output (to stdout) will be 1 if the first input string is a substring of the second, or nothing at all if it's not.
Note that both input lines must have a newline at the end, or the program won't work correctly.  Alternatively, you can add the l command line flag to the invocation to make perl strip the newlines; depending on the scoring rules in effect, this may or may not cost one extra byte. Note that using this flag will also append a newline to the output.
Original version (snippet, 18 bytes / chars)
$x=~s//.*/g,$y=~$x

Input is given in the variables $x and $y, result is the value of the expression (in scalar context).  Note that $x is modified in the process.
(Yes, I know using $_ instead of $x would let me save four chars, but doing that in a snippet that feels a bit too cheesy for me.)
How does it work?
The first part, $x=~s//.*/g, inserts the string .* between each character in $x.  The second part, $y=~$x, treats $x as a regexp and matches $y against it.  In Perl regexps, .* matches zero or more arbitrary characters, while all alphanumeric characters conveniently match themselves.

According to out (new?) consensus, submissions must be program or function, not snippet. If your submission doesn't satisfy that, consider editing it.

@user202729: This challenge is a lot older than that consensus, so unless it's assumed to apply retroactively, the answers in this thread should probably be "grandfathered" in. That said, I did just add a version that complies with current rules, and may even be one byte / char shorter (note that byte-based counting is also newer than this challenge, AFAIK) depending on how you count command-line switches.

Ruby, 32 characters
s=->x,y{y=~/#{[*x.chars]*".*"}/}

This solution returns nil if x isn't a subsequence of y and a number otherwise (i.e. ruby equivalents to false and true). Examples:
p s['','z00']        # => 0   (i.e. true)
p s['z00','z00']     # => 0   (i.e. true)
p s['z00','00z0']    # => nil (i.e. false)
p s['anna','banana'] # => 1   (i.e. true)
p s['Anna','banana'] # => nil (i.e. false)

i did basically the same thing, but it's too similar so i won't post it. i think it is acceptable to leave off the lambda, which would leave you with y=~/#{[*x.chars]*".*"}/ (23 chars). cheers!

or even y=~/#{x.split("")*".*"}/ (21 chars) :)

@padde The split one is actually 24 chars.

sorry, i guess i accidentally left off the y=~ while fiddling with this in irb...

My version is 2 char shorter.

Haskell, 51 37
h@(f:l)%(g:m)=f==g&&l%m||h%m;x%y=x<=y

Thanks to Hammar for the substantial improvement. It's now an infix function, but there seems to be no reason why it shouldn't.
Demonstration:
GHCi> :{
GHCi| zipWith (%) [""   , "z00", "z00" , "anna"  , "Anna"]
GHCi|             ["z00", "z00", "00z0", "banana", "banana"]
GHCi| :}
[True,True,False,True,False]

Since the empty list is smaller than any other list, you can simplify the base cases to s x y=x<=y. Also, you can save a few more by making it an operator and using an @-pattern instead of (f:l). This cuts it down to 37 characters: h@(f:l)%(g:m)=f==g&&l%m||h%m;x%y=x<=y

Python, 45 bytes
lambda a,b:{1,l:=iter(b)}>{c in l for c in a}
Attempt This Online!
Builds on @qwatry's method used in @xnor's answer: iter consumes elements as they are searched for, so c in l "uses up" the character if it is found.
Some trickery lets us combine the all and the iterator assignment:

{c in l for c in a} is a set comprehension which effectively deduplicates its contents, so it's always one of {}, {False}, {True}, or {False, True}
1 and 0 are equivalent to True and False
The > operator tests if {True, iter(b)} is a strict superset of the result, which is true only if that result is {} or {True}, i.e. all the c in l expressions were true
By including l:=iter(b) in the set, we can sequence the evaluation order correctly with minimal parentheses by reusing the set's {} grouping
It also lets us use > instead of >= because the iterator will never be present in the boolean set
Otherwise, >= would be necessary because {True} is not a strict superset of {True}

Python (48 chars)
import re;s=lambda x,y:re.search('.*'.join(x),y)

Same approach as Howard's Ruby answer. Too bad about Python's need to import the regex package and its "verbose" lambda. :-)

I agree, lambda is verbose.

Python 3.8 (pre-release), 42 bytes
lambda a,b:''in[a:=a[a[:1]==c:]for c in b]

Try it online!
Python 3.8 (pre-release), 48 bytes
lambda a,b,j=0:all((j:=1+b.find(c,j))for c in a)

Try it online!
In Python 3.10+, we don't need parens around the walrus expression for 46 bytes.
Python 2, 48 bytes
lambda a,b:re.search('.*'.join(a),b)>0
import re

Try it online!
Copied from this answer of Lynn. The >0 can be omitted if just truthy/falsey output is OK.
Python 2, 49 bytes
def f(a,b):l=iter(b);print all(c in l for c in a)

Try it online!
A dazzling new method introduced to me by qwatry. The idea is that turning b into the iterator l will consume values whenever they are read. So, checking c in l will consume values left to right until it finds one that equals c or it reaches the end.
Python 2, 50 bytes
f=lambda a,b:b and f(a[a[:1]==b[0]:],b[1:])or''==a

Try it online!
Python 2, 50 bytes
lambda a,b:reduce(lambda s,c:s[c==s[:1]:],b,a)==''

Try it online!

Great use of the walrus.

Python, 59 characters
def s(x,y):
 for c in y:
  if x:x=x[c==x[0]:]
 return x==""

I figured my answer would be better expressed in Python.
Edit: Added r.e.s.'s suggestions.

Surely given x="a" and y="ab" you would exit the loop with y=="b" and return false?

@PeterTaylor Yeah, I noticed when I was running the examples as tests after posting that I've mixed x and y up. In my functions y needs to be a subsequence of x. I think I'd better change them to avoid any confusion.

You can get this down to 59 chars: def s(x,y):  for c in y:   if x:x=x[c==x[0]:]  return x=="". It doesn't display correctly in a comment, but I think you can see what I mean. (Also, one added space is enough to increase the indent level.)

@r.e.s. Thanks, Python's not a language I use much as you can probably tell. Nice golfing. (63 characters according to the Codegolf userscript - it must be counting the newlines).

The if statement can all go on one line, with no space after the colon, bringing the count down to 59.

@r.e.s. Like I said - my Python-fu is weak. :-)

you could probably save one more character on the third line if you follow this suggestion: http://codegolf.stackexchange.com/a/58/3527

You can use extending slicing to protect against x being '' and save several chars by writing x=x[c==x[0:1]:]

Brachylog, 2 bytes
⊆ᵈ

Try it online!
As with this answer, ⊆ is a built-in predicate that declares a relationship between the input and output variables, and ᵈ is a meta-predicate that modifies it to declare that same relationship between the first and second elements of the input variable instead (and unify the output variable with the second element but as this is a decision problem that doesn't end up mattering here). X⊆Y is an assertion that X is a subsequence of Y, therefore so is [X,Y]⊆ᵈ.
This predicate (which of course outputs through success or failure which prints true. or false. when it's run as a program) takes input as a list of two strings. If input is a bit more flexible...
Brachylog, 1 byte
⊆

Try it online!
Takes string X as the input variable and string Y as the output variable. Outputs through success or failure, as before. If run as a full program, X is supplied as the input and Y is supplied as the first command line argument.

GolfScript (22 chars)
X[0]+Y{1$(@={\}*;}/0=!

Assumes that input is taken as two predefined variables X and Y, although that is rather unusual in GolfScript. Leaves 1 for true or 0 for false on the stack.

C (52 chars)
s(char*x,char*y){return!*x||*y&&s(*x-*y?x:x+1,y+1);}

Test cases

s(char*x,char*y){x=!*x||*y&&s(x+(*x==*y),y+1);}

Burlesque (6 chars)
6 chars in Burlesque:
    R@\/~[
(assuming x and y are on the stack. See here in action.)

C, 23:
while(*y)*x-*y++?0:x++;

result in *x
http://ideone.com/BpITZ

PHP, 90 characters
<?function s($x,$y){while($a<strlen($y))if($y[$a++]==$x[0])$x=substr($x,1);return $x=="";}

You can remove the if statement and simplify to $x=substr($x,$y[$a++]==$x[0]): http://ideone.com/Ch9vK

Also here is a slightly shorter 82-character solution using recursion: http://ideone.com/IeBns

C #, 70 113 107 90 characters
static bool S(string x,string y){return y.Any(c=>x==""||(x=x.Remove(0,c==x[0]?1:0))=="");}

Doesn't this search for a substring rather than a subsequence?

yes, I misread. Should be fixed now.

As fun as Linq is, I think you can save 10% by using recursion instead.

Here's my best attempt. Still longer.  static bool S(string x,string y){if(x!=""&&y=="")return false;return x==""||S(y[0]==x[0]?x.Remove(0,1):x,y.Remove(0,1));}

You can reduce the recursive one to x==""||y!=""&&S(...), but it's still longer than the updated Linq version. Nice use of Any!

Scala 106:
def m(a:String,b:String):Boolean=(a.size==0)||((b.size!=0)&&((a(0)==b(0)&&m(a.tail,b.tail))||m(a,b.tail)))

CoffeeScript 112 100 95 89
My first attempt at code golf... hope I don't shame my family!
z=(x,y)->a=x.length;return 1if!a;b=y.indexOf x[0];return 0if!++b;z x[1..a],y[b..y.length]

Edit: turns out Coffeescript is more forgiving than I thought with whitespace.
Thanks to r.e.s. and Peter Taylor for some tips for making it a bit sleeker

A few more chars can be eliminated as follows (this won't display right in a comment, but I think you can see what I mean): z=(x,y)->  a=x.length  return 1if a==0  b=y.indexOf x[0]  return 0if b<0  z x[1..a],y[b+1..y.length]. (In some browsers, e.g. Chrome, you can see comment code properly displayed by right-clicking, then Inspect Element.)

a.length is never going to be negative, so you can save one character more by replacing if a==0 with if a<1. I don't know how CoffeeScript's tokenisation works, but if it lexes if0 as two tokens you could save two more by reversing both conditions (i.e. if1>a).

Good points. if1>a isn't valid, but if!a is and is a character shorter! I also realised that I could shave an extra character converting b+1 to b and incrementing it on the previous line, also making the same if trick possible since it was dealing with a 0/non-0 situation.

Mathematica 19 17 27
LongestCommonSequence returns the longest non-contiguous subsequence of two strings.  (Not to be confused with LongestCommonSubsequence, which returns the longest contiguous subsequence.
The following checks whether the longest contiguous subsequence is the first of the two strings. (So you must enter the shorter string followed by the larger string.)
LongestCommonSequence@##==#&

Examples
LongestCommonSequence@## == # &["", "z00"]
LongestCommonSequence@## == # &["z00", "z00"]
LongestCommonSequence@## == # &["anna", "banana"]
LongestCommonSequence@## == # &["Anna", "banana"]

True True True False
The critical test is the third one, because "anna" is contained non contiguously in  "banana".

PHP, 41 Bytes
prints 1 for true and nothing for false

<?=!levenshtein($argv[1],$argv[2],0,1,1);

If only insertions from word 1  to word 2 done the count is zero for true cases
levenshtein
Try it online!
PHP, 57 Bytes
prints 1 for true and 0 for false
Creates a Regex

<?=preg_match(_.chunk_split($argv[1],1,".*")._,$argv[2]);

Try it online!

-2 bytes: leading .* is unnecessary. -2 bytes: don´t assign $argv to $a. +24 bytes: needs array_map(preg_quote()) for special characters (use parentheses as delimiters to avoid second preg_quote parameter.)

@Titus the leading .* is necessary for the input of an empty string and for the input I must only handle  a possibly-empty case-sensitive alphanumeric string. You are right with the quote if there are special characters. Thank you for counting the assign. Copy and paste by an earlier solution and not think about it

preg_match will not complain about an empty regex as long as the delimiters are there. It will just match anything. But preg_quote is only +22 bytes, not +24: array_map(preg_quote,str_split(...)).

But then, input is guaranteed to be alphanumeric :) But you still don´t need the leading .*.

Haskell, 36 bytes
(a:b)%(c:d)=([a|a/=c]++b)%d
s%t=s<=t

Try it online!

37 bytes
(.map concat.mapM(\c->["",[c]])).elem

Try it online!
I think mapM postdates this challenge. If we can assume the characters are printable, we can do
36 bytes
(.map(filter(>' ')).mapM(:" ")).elem

Try it online!

37 bytes
(null.).foldr(?)
c?(h:t)|c==h=t
c?s=s

Try it online!

JavaScript (no regex), 45 bytes
y=>x=>(i=0,[...y].map(c=>c==x[i]&&i++),!x[i])

Should be called like
f(haystack)(needle)

Try it online!

C - 74 71 64
This doesn't beat Peter Taylor's solution, but I think it's pretty fun (plus, this is a complete working program, not just a function)

main(int c,char**v){for(;*v[1]!=0;++v[1])v[2]+=*v[1]==*v[2];return*v[2];}

main(int c,char**v){for(;*v[1];++v[1])v[2]+=*v[1]==*v[2];return*v[2];}

main(c,v)char**v;{while(*v[1])v[2]+=*v[1]++==*v[2];return*v[2];}

And ungolfed:
main(int argc, char** argv){
   char * input = argv[1];
   char * test  = argv[2];

   // advance through the input string. Each time the current input
   // character is equal to the current test character, increment
   // the position in the test string.

   for(; *input!='\0'; ++input) test += *input == *test;

   // return the character that we got to in the test string.
   // if it is '\0' then we got to the end of the test string which
   // means that it is a subsequence, and the 0 (EXIT_SUCCESS) value is returned
   // otherwise something non-zero is returned, indicating failure.
   return *test;
}

To test it you can do something like:
./is_subsequence banana anna && echo "yes" || echo "nope"
# yes
./is_subsequence banana foobar && echo "yes" || echo "nope"
# nope

!=0 in a condition is a bit verbose... Program vs function is something which the question needs to specify clearly, and here it doesn't, so the answers take different options.

Damn, that !='\0' is a bad (good?) habit from writing non-golf code, I've let that slip into my last two rounds of golf, I'll have to be more careful in the future. As to program vs. function, yes, you're absolutely right.

@GordonBailey sorry for the bump, but I made a few changes into a shorter version.

Ruby 32 30 28
f=->a,b{b.match a.tr'','.*'}

This will return MatchData instance if a is subsequence of b or nil otherwise.
Old version that find substring instead of subsequence
Ruby 15
f=->a,b{!!b[a]}

Using String#[](str) method that returns str if str is a substring of self and !! to return Boolean if returned value can be usable as boolean (and don't need to be true or false) then it can be only 13 chars:
f=->a,b{b[a]}

It will return nil if a is not a substring of b.

Nice, but the question asks for a subsequence rather than a substring.

Python, 66 62 59 58 chars
Kind of a fun solution, definitely a neat problem.
def f(n,h,r=0):
 for c in h:r+=n[r:r+1]==c
 return r==len(n)

SWI-Prolog, SICStus
The built-in predicate sublist/2 of SICStus checks whether all the items in the first list also appear in the second list. This predicate is also available in SWI-Prolog via compatibility library, which can be loaded by the query [library(dialect/sicstus/lists)]..
Sample run:
25 ?- sublist("","z00").
true.

26 ?- sublist("z00","z00").
true .

27 ?- sublist("z00","00z0").
false.

28 ?- sublist("aa","anna").
true .

29 ?- sublist("anna","banana").
true .

30 ?- sublist("Anna","banana").
false.

The byte count can technically be 0, since all we are doing here is querying, much like how we run a program and supply input to it.

x86-16 machine code, 12 10 bytes
Binary:
00000000: 41ac f2ae e303 4a75 f8c3                 A.....Ju..

Unassembled listing:
41          INC  CX                 ; Loop counter is 1 greater than string length
        SCAN_LOOP:
AC          LODSB                   ; load next char of acronym into AL
F2 AE       REPNZ SCASB             ; search until char AL is found
E3 03       JCXZ DONE               ; stop if end of first string reached
4A          DEC  DX                 ; decrement second string counter
75 F8       JNZ  SCAN_LOOP          ; stop if end of second string reached
        DONE:
C3          RET                     ; return to caller

Callable function. Input: Y string pointer in SI, length in CX. X string pointer in DI, length in DX.  Output is ZF if Truthy.
Example test program:
This test program uses additional PC DOS API I/O routines to take multi-line input from STDIN.

x86-16 assembly is amazing! I thought this is going to take at least 20 bytes.

@2x-1 Yes it is! It's my goal to someday submit a valid answer to a question using only single-byte x86 instructions!

Red, 82 bytes
func[x y][parse/case y collect[foreach c x[keep reduce['to c 'skip]]keep[to end]]]

Try it online!

Charcoal, 18 17 bytes
ＦηＦ⁼ι∧θ§θ⁰≔Φθμθ¬θ

Try it online! Link is to verbose version of code. Uses Charcoal's default Boolean output of - for true, nothing for false. Explanation:
Ｆη

Loop over the characters of Y.
Ｆ⁼ι∧θ§θ⁰

See if this character is the next character of X.
≔Φθμθ

If so then remove that character from X.
¬θ

Were all the characters of X consumed?

05AB1E, 3 bytes
æQà

Try it online or verify all test cases.
Or alternatively:
æså

Try it online or verify all test cases.
With both programs the first input is \$Y\$ and the second input is \$X\$.
Explanation:
æ    # Get the powerset of the (implicit) input-string `Y`
 Q   # Check for each if it's equal to the (implicit) input-String `X`
  à  # And check if any are truthy by taking the maximum
     # (after which this result is output implicitly)

æ    # Get the powerset of the (implicit) input-String `Y`
 s   # Swap to take the (implicit) input-String `X`
     # (could also be `I` or `²` to simply take input)
  å  # Check if this string is in the powerset-list of strings
     # (after which this result is output implicitly)

Regex (PCRE2 v10.35+), 25 bytes
^((.)(?*.*
(\3?+.*\2)))*

Attempt This Online!
Takes input as X followed by Y, delimited by a newline.
This abuses molecular lookahead (?*...) to save a byte. Instead of using a lazy quantifier .*? to advance only as far as necessary to find the next matching character, it greedily lets the regex engine do all the work by backtracking until it is able to match all of X in Y (or fail to, after trying all possibilities).
This beats mbomb007's Retina answer by 1 byte, though not when ported to .NET (in that it is 29 bytes – see below).
Regex (Perl / PCRE / Java), 26 bytes
^((.)(?=.*
(\3?+.*?\2)))*

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Java
^                 # Anchor to start of string X
(
    (.)           # \2 = next character from X (starting at its start)
    (?=           # Atomic lookahead
        .*¶       # Skip to the beginning of string Y
        (         # \3 = concatenation of the following:
            \3?+  # previous value of \3, if set
            .*?   # Advance by as little as possible (minimum zero) to make the
                  # following match:
            \2    # Match the character we captured in \2
        )
    )
)*                # Iterate the above as many times as possible
¶                 # Assert that after doing the above, we've reached a newline,
                  # meaning the loop processed all of string X.

Taking the arguments in the opposite order takes 28 bytes:
((.)(?=.*
(\3?+\2)).*)*
\3?$

Try it online! - PCRE2
Regex (Perl / PCRE / Java / .NET), 29 bytes
^((.)(?=.*
((?>\3?).*?\2)))*

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Java
Try it online! - .NET
The uses an atomic group (?>\3?) instead of a possessive quantifier \3?+ to add .NET compatibility.
Regex (.NET), 31 bytes
(?<=(.)*)
(.*(?<-1>\1))*(?(1)^)

Try it online!
As a matter of curiosity (even though it doesn't beat the group-building method), here is a version using .NET's Balancing Groups feature.
(?<=(.)*)      # In a lookbehind, push each character of string X onto the \1
               # stack, going from right to left. There is no need to use a "^"
               # anchor, because the lookbehind is atomic and will lock in its
               # first greedy full match.
¶              # Assert that the next character is a newline, meaning that the
               # above processed the entirity of string X.
(
    .*         # Skip however many characters as needed to match the following:
    (?<-1>\1)  # Pop a capture off the \1 stack and match it. This is iterated
               # from left to right.
)*             # Iterate the above as many times as possible.
(?(1)^)        # Assert that the \1 stack is now empty (by asserting that if it
               # isn't, then we're at the start of the string – which is
               # impossible because we have at the very least matched a newline).

Regex (Perl / PCRE / Java / Pythonregex / Ruby / .NET), 33 bytes
^((.)(?=.*
(?=(\4?))(\3.*?\2)))*

Try it online! - Perl
Try it online! - PCRE1
Try it online! - PCRE2
Try it online! - Java
Try it online! - Python import regex
Try it online! - Ruby
Try it online! - .NET
Copies the capture back and forth between \3 and \4 to avoid use of nested backreferences, adding Python and Ruby support (and as the lookahead is atomic, it's also another way of adding .NET support).
\$\large\textit{Anonymous functions}\$
Julia, 52 51 50 bytes
-1 byte thanks to MarcMush
-1 byte thanks to MarcMush
x->y->count(r"^((.)(?*.*
(\3?+.*\2)))*
",x*'
'y)>0

Attempt This Online!
Yep, Julia string literals can contain an unescaped raw newline!
Beats Simeon Schaub's answer by 2 bytes when both are converted to the same type of declaration, e.g. currying, as used here.
Of course, both could also be 2 bytes shorter with operator overloading.

@MarcMush Thanks. BTW, I can't help but feel that you disapprove of my presenting the curried function as the answer, rather than the operator-overloading one. My logic is this: there's only one operator available for this type of overload (and even if there were more than one, it'd still be very limited number). A function is supposed to be usable by any program, even a large one. If the presented golfed function can be the only one used by any given program, its being a function is a sham – it's really just a full program masquerading as a function.

It's commonly accepted (I'm too lazy to find on meta but I'm pretty sure it is) and you can use $ than is unused by default

And it returns a function, without changing the original function Try it online!

Haskell + hgl, 2 bytes
iS
Attempt This Online!
So this is a builtin. There are actually a couple of builtins.  There's also fiS which is the same function but the arguments flipped, there iSW eq which how iS is defined internally.  There's fe<ss which gets all subsequences of y and checks if x is among them. There's ap eq<lSW which tests if the longest common subsequence is equal to the second element.
But these are no fun.  Let's have a true no builtins solution
Regex based, 17 bytes
pP<rXx<ic".*"<m p

Also
pP<rXx<ic".*"<!<p

This works like all the other regex answers here.  It adds .* between items and then matches a regex.
Parser based, 15 bytes
pP<mF(aK h'<χ)

This works similarly to the regex answer.  It replace every character in the string with a parser that matches anything ending in that character.  It then sequences all the parsers and checks if there is any partial matches.
It's cheaper than the regex which is a little surprising.
Reflections
The regex answer is the one with the most room for improvement.

There should be functions that build and apply regexes all in one.  It's silly to have to build and then apply the regex separately.  This would save 3 bytes on the regex solution
Hard to imagine a situation in which <!< is going to be useful.  Here we can see it's not saving anything.  Maybe this should be shortened, the docs should have some info about when it is useful.
There should be more versions of ic and is.  Some that add copies to the outside, and a versions that are mapped with pure like the regex answer.

With the above changes the regex answer could look like
pPX<icp".*"

The only other suggestion I have is that maybe aK h' should get a synonym.  It's basically "ends with", which seems like a concept that might come up again.

Factor + math.combinatorics, 19 bytes
[ all-subsets in? ]

Try it online!

CoffeeScript 73
Here's an alternative CoffeeScript answer, using regexes instead of recursion:
z=(x,y)->a='.*';a+=c+'.*'for c in x;b=eval('/'+a+'/');(y.replace b,'')<y

If the haystack matches a very greedy regex constructed from the needle, it will be replaced with an empty string. If the haystack is shorter than it started, the needle was a subsequence.
Returns false when x and y are both empty strings. Think we need a philosopher to tell us if an empty string is a subsequence of itself!
(Posted as a separate answer from my previous because it feels different enough to justify it).

PowerShell, 38
$args[1]-clike($args[0]-replace'','*')

Of course, any such regex- or pattern-matching-based solution has severe performance problems with longer strings. But since shortness is the criterion ...

APL (31)
String handling is a bit lacking in APL.
{(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N}

usage:

      {(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N} 'anna' 'banana'
1
      {(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N} 'Anna' 'banana'
0
      {(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N} '' 'banana'
1

Python 132
Similar to Daniero's. Not the easiest solution, but it was fun to try. I'm new to Python, so I'm sure I could make it shorter if I knew a little bit more.
def f(i):
    s=x;j=0
    while j<len(s):t=~i%2;s=[s[:j]+s[j+1:],s][t];j+=t;i>>=1
    return s==y
print True in map(f,range(1,2**len(x)))

A sort of anti-solution generating all subsequences of Y:
Python 93
l=len(y)
print x in[''.join(c for i,c in zip(bin(n)[2:].rjust(l,'0'),y)if i=='1')for n in range(2**l)]

Python - 72
def f(a,b):
 c=len(a)
 for i in b:a=a.replace(i,"",1)
 print len(a+b)==c

Retina, 26 bytes (not competing)
The language is newer than the challenge. Byte count assumes ISO 8859-1 encoding. Input is taken on two lines with Y first.
+`^(.)(.*¶)(?(\1).|)
$2
¶$

Try it online

Python (75 52)
s=lambda a,b:a==''or b>''and s(a[a[0]==b[0]:],b[1:])

Simple recursive solution. First time golfing, so any tips on whittling this down are much appreciated :)
Tested with the following:
assert s('anna', 'banana') == True
assert s('oo0', 'oFopp0') == True
assert s 'this', 'this is a string') == True
assert s('that', 'this hat is large') == True
assert s('cba', 'abcdefg') == False

Thanks to @lirtosiast for some clever boolean tricks.

You can get this down to 52 characters: s=lambda a,b:a==''or b>''and s(a[a[0]==b[0]:],b[1:])

Thanks, that's clever, using the boolean as the 0/1 index into the splice :)

PHP, 75 65 64 bytes
for(;$p=@strpos(_.$argv[2],$c=$argv[1][$i++],$p+1););echo""==$c;

takes input from command line arguments; prints 1 for true, empty string for false. Run with -r.
explanation:

strpos returns false if needle $c is not in the haystack $argv[2] (after position $p),
causing the loop to break.
strpos also returns false for an empty needle, breaking the loop at the end of $argv[1].
If $argv[1] is a subsequence of $argv[2], $c will be empty when the loop breaks.
strpos needs @ to suppress Empty needle warning.

+$p instead of $p+1 after that ther is no need for the underscore

@JörgHülsermann +1 is needed to advance in the haystack string; and the underscore avoids $p=-1 initialization. But ... I can avoid false!==.

Java 8, 163 162 38 35 bytes
a->b->b.matches(a.replace("",".*"))

-124 bytes by converting to Java 8, and pasting my answer from the duplicated challenge.
NOTE: Doesn't work if the input contains special regex-characters, but this would invalidate a lot of existing answers as well.
Try it online.
Explanation:
a->b->         // Method with two String parameters and boolean return-type
  b.matches(   //  Check if the second input matches the regex:
   a           //   The first input,
    .replace("",".*"))
               //   where every character is surrounded with ".*"

For example:
a="anna"
b="banana"

Will do the check:
"banana".matches("^.*a.*n.*n.*a.*$")

You're mishandling special regexp characters like "." though

@StefanReich You're right, but the same applies to almost any other existing answer, though. But I've added a note to mention this in the answer (and golfed it by 3 bytes at the same time).

Come on... you're saying there is a bug in THIS? >> à øV << (the Japt program, whatever that is)

@StefanReich The golfing languages like Jelly, Japt, 05AB1E, etc. are probably fine, since most of them just use the powerset and check if the second input is in it. I was referring to the answers using regex like mine, like the accepted Perl answer; the Python answer of Eric; the Ruby answer; etc. All answers that use regex are similar as mine (add a ".*" after each characters, and check if it matches the second input) are most likely invalid if the inputs contain special regex characters.

I was just messing around :)

Swift, 27
print(Y.range(of:X) != nil)

APL (Dyalog Unicode), 18 bytesSBCS
Full program. Prompts for Y then for X.
×≢(∊'.*'∘,¨⍞)⎕S⍬⊢⍞

Try it online!
⍞ prompt (for Y)
⊢ yield that (separates ⍬ from it)
(…)⎕S⍬ search for occurrences of the following, yielding one empty list for each match:
 ⍞ prompt (for X)
 '.*'∘,¨ prepend .* to each character
 ∊ ϵnlist (flatten)
≢ tally the number of matches
× sign of that

APL(NARS), chars 46, bytes 92
{(⊂,⍺)∊(⊂''),↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}

test:
  h←{(⊂,⍺)∊(⊂''),↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}
  '' h 'z00'
1
  'z00' h 'z00'
1
  'z00' h '00z0'
0
  'aa' h 'anna'
1
  'anna' h 'banana'
1
  'Anna' h 'banana'
0

comment:
{(⊂,⍺)∊(⊂''),↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}
 ⍳¯1+2*k←≢w←⍵    this assign to w the argument and k argument lenght, it return 1..(2^k)-1 range
 {⍵⊤⍨k⍴2}¨      for each element of 1..(2^k)-1 convert in base 2 with lenght k (as the arg lenght)
 {⍵⊂w}¨         use the binary array above calculation for all partition argument
 ,/¨            concatenate each element of partition
 ↑¨             get the firs element of each element because they are all enclosed
 (⊂''),         add to the array the element (⊂'')
 (⊂,⍺)∊         see if (⊂,⍺) is one element of the array, and return 1 true o 0 false

How all you can see the comments are +- superfluous all is easy...
I have to say not understand why the last instruction is not "(,⍺)∊" in the place of "(⊂,⍺)∊"
because for example in code
  q←{↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}
  o q '123'
┌7──────────────────────────────────────┐
│┌1─┐ ┌1─┐ ┌2──┐ ┌1─┐ ┌2──┐ ┌2──┐ ┌3───┐│
││ 3│ │ 2│ │ 23│ │ 1│ │ 13│ │ 12│ │ 123││
│└──┘ └──┘ └───┘ └──┘ └───┘ └───┘ └────┘2
└∊──────────────────────────────────────┘
  o (,'3')
┌1─┐
│ 3│
└──┘

all you see array of 1 element (,'3') is the element  of the set of instruction q '123', but
  o (,'3')∊q '123'
┌1─┐
│ 0│
└~─┘

return one array of unclosed 0 instead of number 1... for workaround that one has to write:
  o (⊂,'3')∊q '123'
1
~

that is the right result even if the element seems different because :
  o (⊂,'3')
┌────┐
│┌1─┐│
││ 3││
│└──┘2
└∊───┘

It is sure i make some error because i am not so smart... where is my error?

JavaScript, 32 bytes
Repost of a port of Kevin's Java solution to a duplicate challenge, modified in case my choices for I/O weren't standards at the time this challenge was posted.
x=>y=>!!y.match([...x].join`.*`)

Try it online! (will update with this challenge's test cases when I get back to a computer)

Perl 6, 34 28 bytes
-6 bytes thanks to nwellnhof
{$!=S:g/<(/.*/;&{?/<{$!}>/}}

Try it online!
Anonymous code block that takes input curried, like f(X)(Y). This does the familiar join by .* and evaluate as a regex as other answers, but takes a couple of shortcuts.
Explanation:
{                          }  # Anonymous code block
 $!=            # Assign to $!
    S:g/<(/.*/  # Inserting .* between every character
              ;&{         }   # And return an anonymous code block
                 ?/      /    # That returns if the input matches
                   <{$!}>     # The $! regex

Julia 1.0, 53 bytes
f(x,y)=(x==""||[x=x[2:end] for c=y if c==x[1]];x=="")

Try it online!

Ties with a pure regex solution.

Jelly, 3 bytes
ŒPi

Try it online!
Outputs 0 for false and a non-negative integer for true
How it works
ŒPi - Main link. Takes X on the left and Y on the right
ŒP  - Powerset of X
  i - Index of y, or 0

Husk, 2 bytes
€Ṗ

Try it online!
Having a single byte builtin for powerset is useful.

MMIX, 40 bytes (10 instrs)
C strings.
00000000: 8302 0000 8303 0100 dc04 0203 30FF 0203  ............0...
00000010: 73FF FF01 2200 00FF 2301 0101 5b04 fff9  s..."...#...[...
00000020: 7300 0201 f801 0000                      s.......

Disassembly
subseq  LDBU $2,$0,0        // loop: av = *a
        LDBU $3,$1,0        // bv = *v
        MOR  $4,$2,$3       // t0 = av && bv (MOR is faster than MUL)
        CMP  $255,$2,$3     // t1 = av <=> bv
        ZSZ  $255,$255,1    // t1 = !t1
        ADDU $0,$0,$255     // a += t1
        ADDU $1,$1,1        // b += 1
        PBNZ $4,subseq      // iflikely(t0) goto loop
        ZSZ  $0,$2,1        // a = !t0
        POP  1,0            // return a

Obvious algorithm, with only one branch!
For wchar_t, replace LDBU with LDWU (and similarly for codepoint_t);
additionally, replace ADDU $0,$0,$255 with 2ADDU $0,$255,$0 (4ADDU for codepoints), and ADDU $1,$1,1 with ADDU $1,$1,2 or ADDU $1,$1,4.

Vyxal, 2 bytes
ṗc

Try it Online!

K (ngn/k), 32 18 bytes
~#*{(=/*'x;1)_'x}/

Try it online!

Thunno 2 G, 2 bytes
ʠ=

Attempt This Online!
Port of Kevin Cruijssen's 05AB1E answer.
Explanation
ʠ=  # Implicit input
ʠ   # Powerset of the first input string
 =  # Vectorised equality check with the second input string
    # Check if any are true, and implicitly output

Nekomata + -e, 2 bytes
S=

Attempt This Online!
S       Check if any subset of the first string
 =      is equal to the second string

C, 120
main(i,c){char x[99],y[99];c=0;gets(y),gets(x);for(i=0;y[i]!='\0';)c+=y[i++]==x[c]?1:0;puts(x[c]=='\0'?"True":"False");}

You can save at least 15 chars by moving c=0 to the loop initialiser and eliminating every instance of == in favour of "non-zero is truthy" conditions.

Javascript, 104 chars
function _(x,y){f=true;for(c in x){if(y.indexOf(x[c])>-1)y=y.replace(x[c],"");else{f=!f;break}}return f}

Ungolfed
function _(x,y){
f=true;
    for(c in x)
    {
        if(y.indexOf(x[c])>-1)
           y=y.replace(x[c],"");
        else {
            f=!f;
            break;
        }
    }
    return f;
}

This appears to test whether x is a substring of y, but it's supposed to test whether x is a subsequence of y. E.g., 'anna' is a subsequence of 'banana', but 'banana'.indexOf('anna')>-1 evaluates to false.

@r.e.s. : My bad dint read the question properly. Thanks

@r.e.s. posted a altogether new answer

What does the new answer do for _("ab", "ba")?

returns true. demo http://jsfiddle.net/yvAdT/

J (20 chars)
(<x)e.(#:i.2^#y)<@#y

The input is given in the variables x and y. It makes a list of all subsequences of y, so don't use it for very big strings.

Python (72)
import itertools as I;any(tuple(X)==Z for Z in I.permutations(Y,len(X)))

No, that use of permutations ignores the required order of the elements; e.g., X='z00' and Y='00z0' should output False (whereas your program outputs True).

REXX, 76 bytes
o=1
do while x>''
  parse var x a+1 x
  parse var y(a)b+1 y
  o=o&a=b
  end
return o

Note that x and y are consumed by this routine. Readability is impaired by skipping a lot of whitespace and parentheses.

JavaScript (ES6), 42 bytes
Takes input n (needle) and h (haystack) in currying syntax (n)(h).
n=>h=>!!RegExp(n.split``.join`.*`).exec(h)

Test

let f =

n=>h=>!!RegExp(n.split``.join`.*`).exec(h)

console.log(f(''    )('z00'   )); // true
console.log(f('z00' )('z00'   )); // true
console.log(f('z00' )('00z0'  )); // false
console.log(f('aa'  )('anna'  )); // true
console.log(f('anna')('banana')); // true
console.log(f('Anna')('banana')); // false

What if n contains regex special characters?

@Titus Well, I assumed n is in [A-Za-z0-9] since the challenge mentions that both input strings are alphanumeric.

woops missed that. :)

Pyth, 5 bytes
}hQye

Explanation
}hQye
 hQ       The first input...
}         ... is an element of...
   y      ... the power set...
    eQ    ... of the second input.

Python 2, 47 bytes
x,y=map(list,input())
while x:y.remove(x.pop())

Try it online!
Takes two quote-delimited strings via STDIN as input.
Output is by presence or absence of an error, which is allowed per meta consensus.
Explanation:
             # get arguments from STDIN
             input()
    # convert each argument to a list
    map(list,.......)
# split arguments into two variables
x,y=..................

# while x still has elements
while x:
                 # remove the final element of x and return its value
                 x.pop()
        # remove the first matching item in y
        # this will error if there is no matching element
        y.remove(.......)

# if the loop is exited without error, all elements in x were in y

This doesn't look like it checks that the removed letters are in the right order.

Japt, 4 bytes
Repost from a duplicate challenge.
Takes input in reverse order (Y, then X).
à øV

Try it

Pyth, 5 bytes
}hQye

Try it online!

Pyth   | Explanation
-------+------------------------------------------
}hQye  | Full code
}hQyeQ | "       " with implicit variables
-------+------------------------------------------
}      | return whether arg0 is an element of arg1
 hQ    |  first element of input
   y   |  powerset of
    eQ |   last element of input

Lua, 85 68 66 bytes
_,b=...for c in (...):gmatch"."do b=b:gsub(c,"",1)end print(b=="")

Try it online!
Explanation
... is the variable argument operator, it returns all remaining arguments to the current function (the top-level block in this case). We can force it to return just one variable by encasing it in parentheses.
gmatch() is a pattern-matching function which returns an iterator function, we use it to loop over every character in the input string.
gsub() is a substitution function, we use it to clear matched characters from the subset contender. The extra parameter is the number of substitutions to make, 1 in this case.

This is only checking if the second string contains a subset of the characters in the first string, not if it's a subsequence.

Zsh -o glob_subst, 14 bytes
>:$1>${2///*}*

Try it online!
Explanation:

>:$1: copy stdin to a file named : and the first argument. The colon ensures that we don't try to create a file with an empty name in the case of an empty string as input. Since we don't take any input from stdin, this just creates an empty file.
>${2///*}*: try to copy stdin (again) to a file that matches the pattern resulting from the expansion of ${2///*}* If no such file exists, an error will occur. The -o glob_subst ensures that the expanded value is treated as a pattern. Otherwise, it will be treated as a literal string. Alternatively, this option can be removed and ${~2///*}* used instead for +1 byte.

${2}: take the second argument
///*: replace every empty string with an asterisk; this results in abc -> *a*b*c
append another asterisk. Asterisks simply mean "match any sequence

Vyxal, 6 bytes
ṗƛṅ;$c

Try it Online!

brev, 78 bytes
(define(s(x . xs)y)(aif(memq x y)(s xs(cdr it))#f))(define(s'()y)#t)

68 to define s, but you've got to call it as (as-list s) to handle string input.
(define (s (x . xs) y)
  (aif (memq x y) (s xs (cdr it)) #f))

(define (s '() y) #t)

(map (fn (apply (as-list s) x))
     '((""     "z00")
       ("z00"  "z00")
       ("z00"  "00z0")
       ("aa"   "anna")
       ("anna" "banana")
       ("Anna" "banana")))

Bonus! Regex version 50 bytes:
(fn(with(strse x"."(conc(m 0)".*"))(strse? y it)))

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


text:
Code Golf: Make a Web Crawler
A Web Crawler is a program that starts with a small list of websites and gets the source code for all of them. It then finds all the links in those source codes, gets the website it links to then puts them in a list. It then starts again but with the new list of websites.The main reason for a Web Crawler is to find all (or most) of the websites in the internet. Google use this to power their search engine.Wikipedia Page about Web Crawlers
Your task is to create a Web Crawler in any language you wish.
Rules

Your first list can contain any amount of websites <= 5 and any websites you wish.
Your web crawler can ignore any websites with the HTTP GET request or any other pages other than the home page, e.g. www.somewebsite.com/?anything=1 and www.somewebsite.com/secondpage can be ignored, we are only trying to find the website/domain, e.g. www.somewebsite.com
You can use any method you wish to store the list of websites currently being "crawled".
Although this is code golf, the highest voted answer/solution will win, and don't forget to have fun!

Participants are cautioned that you can make site owners and/or your ISP very mad by doing this badly.

"Although this is code golf, the highest voted answer/solution will win, and don't forget to have fun!" No. [code-golf] defines the winning critera. If you want a different objective winning critera you can set that, but you should be aware that many user don't like "most votes" as a criteria.

To clarify dmckee's comment, any considerate web crawler should find and honor the robots.txt document for any domain it crawls. One of my college courses used this as an assignment and consistantly got the campus network blacklsted from several major sites a few times a year. See http://www.robotstxt.org/

Oh, I never actually thought about that. So do you think this question should be deleted?

@CeilingSpy: What's about updating it? Or flag it for closing by a mod, and discuss it in chat or at the meta sandbox, which is meant for that, until clarification. It can be reopened later.

I wonder if this is a way to get some sample code for the Udacity web crawler competition which will be held after the end of Udacity's CS101 - Building a search engine - course.

Javascript, 491
Golfed
var C=function(c){w=c.length;for(i=0;i<w;i++){var b=new XMLHttpRequest;b.setRequestHeader("Access-Control-Allow-Origin","*");b.setRequestHeader("X-Requested-With","XMLHttpRequest");b.open("GET",c[i],!0);b.send();if(200===b.status){a=b.responseText.match(/\<[(a|img)]+\s[^\>]+[(http|https)]+:\/\/([\w\.])+([.])+.+?[^.]+?./gi);u=c[i].substr(7);re=RegExp(u,"i");for(j=0;j<a.length;j++)if(a[j].match(re)&&(b=a[j].match(/[(http|https)]+:\/\/([\w\.])+([.])/gi))&&!c.indexOf(b))c.push(a[j]),w++}}};

Un-Golfed
var C = function(s){
  w = s.length;
  for(i = 0; i < w; i++){
    var r = new XMLHttpRequest();
    r.setRequestHeader("Access-Control-Allow-Origin", "*")
    r.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    r.open('GET', s[i], true); r.send();
    if(r.status === 200) {
      a = r.responseText.match(/\<[(a|img)]+\s[^\>]+[(http|https)]+:\/\/([\w\.])+([.])+.+?[^.]+?./gi);
      u = s[i].substr(7),
      re = new RegExp(u,'i');
      for(j = 0; j < a.length; j++){
        if(!a[j].match(re)) continue;
        var uri = a[j].match(/[(http|https)]+:\/\/([\w\.])+([.])/gi);
        if(uri && !s.indexOf(uri)) {
          s.push(a[j]); w++;
        }
      }
    }
  }
}

Method
var c = new C(['http://www.cnn.com', 'http://www.usatoday.com', 'http://www.huffingtonpost.com', 'http://www.drudgereport.com/', 'http://news.cnet.com']);

How did you run the above script? I've tried Firefox and Node.js, both fail for different reasons.

source: Stack Exchange

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

sort: votes


text:
Underhanded Password Hashing
In the spirit of the Underhanded C Contest, I'm starting an Underhanded Code Contest.  The objective of this contest is to straightforwardly implement some code, while subtly hiding a nefarious bug inside it.
The contest
You are a secret Russian mole working in the IT department of an American spy agency.  Your American boss has just asked you to implement a password hashing algorithm to use for encrypting secret messages.
Your boss wants you to implement the following function:
f: String -> byte[16]

which converts a password to a 16-byte quantity suitable for use as an AES key.  Your boss wants a secure function, which in this context means that different password strings should generate different results with overwhelming probability.  For instance, returning the md5 hash of the input would be a simple implementation of f.
Of course, your real boss in the Russian spy agency would want you to subvert this process.  Your task is to implement f such that the Russians can decrypt all the secret messages encrypted using keys returned by f.
To do so, you must implement f so that it returns only a small subset of the 2^128 possible outputs.  In particular, your f must return at most 2^16 different results so that the Russians can do an easy brute-force search for the correct key for each encrypted message they wish to decrypt.
Keep in mind, however, that espionage carries the death penalty.  In order not to get caught, your function f must generate at least 2^8 different results, so that a cursory inspection of a few outputs of f is unlikely to reveal a duplicate.  And most importantly, the code you introduce to limit the range of f must look unintentional, not deliberate.  If you ever get hauled into a courtroom, there must be some reasonable doubt as to whether you introduced the bug deliberately or by accident.
Judging
I and two others I recruit will judge the entries (email me if you'd like to judge).  I'm offering a 200 reputation bounty for the winning entry.  Submissions must be uploaded by May 1.
Judging will take into account the following criteria:

Does f adhere to the spec, i.e. does it generate between 2^8 and 2^16 possible outputs.  Don't feel that these are hard limits, but we'll deduct points if you're too far out of range.
Is the bug plausibly the result of an unintentional mistake?
Do the outputs of f look random?
The shorter your implementation of f, the better.
The clearer your implementation of f, the better.

Notes
You may use any language to implement your code.  You're trying to hide a bug in plain sight, so obfuscated code is not suggested.
You might want to take a look at some of the previous Underhanded C contest winners to get a feel for what makes a good submission.
Input strings will be printable ascii (32 through 126, inclusive).  You may assume a reasonable max length if you want.

is there any limitations on input string? like it's only consist of alphabet?

@Gajet: you must handle all of the printable ascii characters (32 through 126, inclusive).

Is the output range all 16-byte strings, or just printable ones?

@boothby: all possible 16-byte values (2^128 possibilities)

What's the closing date?

There is no limit to the length of the input strings?

@Peter, let's say May 1.

@leftaroundabout: Not as part of the spec.  Feel free to assume a reasonable limit if you want to.

Continuing @leftaroundabout's question - isn't there an advantage for short, simple programs? The underhanded C competition encourages simple programs, where you clearly see there's no bug (although there is) over complicated ones, where the bug is hidden in the complexity.

I wish I was good enough to even try this. :-)

Should my description (or comments) include the flaw, or is it better to leave it to each one to figure out?

@ugoren: you don't need to include a description of the flaw.  Maybe just a hint.

Looks like I started the bounty too soon and had to award it or lose it.  I picked the entry I liked best so far, but I'll put up another 200 at the end (May 1) for the final judging.

Shouldn't there also have been a jury to judge the entries?

@mbomb007: yes, but no one volunteered.

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

C
2^16 possible outputs (or 2^8 times the number of used characters).
Uses Linux's MD5 implementation, which is, AFAIK, fine. But this gives the same hash, for example, for "40" and "42".
EDIT: Renamed bcopy to memcpy (swapped parameters of course).
EDIT: Converted from program to function, to meet requirements better.
#include <string.h>
#include <openssl/md5.h>

void f(const unsigned char *input, unsigned char output[16]) {

    /* Put the input in a 32-byte buffer, padded with zeros. */
    unsigned char workbuf[32] = {0};
    strncpy(workbuf, input, sizeof(workbuf));

    unsigned char res[MD5_DIGEST_LENGTH];
    MD5(workbuf, sizeof(workbuf), res);

    /* NOTE: MD5 has known weaknesses, so using it isn't 100% secure.
     * To compensate, prefix the input buffer with its own MD5, and hash again. */
    memcpy(workbuf+1, workbuf, sizeof(workbuf)-1);
    workbuf[0] = res[0];
    MD5(workbuf, sizeof(workbuf), res);

    /* Copy the result to the output buffer */
    memcpy(output, res, 16);
}

/* Some operating systems don't have memcpy(), so include a simple implementation */
void *
memcpy(void *_dest, const void *_src, size_t n)
{
    const unsigned char *src = _src;
    unsigned char *dest = _dest;
    while (n--) *dest++ = *src++;
    return _dest;
}

is this a flaw with MD5?

@Gajet, No, I used Linux's MD5, which is perfectly OK (AFAIK).

they why it doesn't generate more possible output?

@Gajet: Consider what happens in the bcopy step... it is a nice bit of misdirection, since the actual BSD bcopy function would work properly here.

@han, Actually, I now see that my bcopy is buggy. I'll change it to memcpy, and then the same implementation will become valid.

C
This may not be the flashiest contest entry, but I think the following is the kind of hash function that could have been made by any coder too clever for their own good, with a vague idea of the kind of operations you see in hash functions:
#include <stdio.h>
#include <string.h>
#include <stdint.h>

void hash(const char* s, uint8_t* r, size_t n)
{
     uint32_t h = 123456789UL;
     for (size_t i = 0; i < n; i++) {
          for (const char* p = s; *p; p++) {
               h = h * 33 + *p;
          }
          *r++ = (h >> 3) & 0xff;
          h = h ^ 987654321UL;
     }
}

int main()
{
     size_t n = 1024;
     char s[n];
     size_t m = 16;
     uint8_t b[m];
     while (fgets(s, n, stdin)) {
          hash(s, b, m);
          for (size_t i = 0; i < m; ++i)
               printf("%02x", b[i]);
          printf("\n");
     }
}

In fact the hash function can return no more than L*2048 different results, where L is the number of different input string lengths that can occur.  In practice, I tested the code on 1.85 million unique input lines from manual pages and html documents on my laptop, and got only 85428 different unique hashes.

Scala:
// smaller values for more easy tests:
val len = 16
// make a 16 bytes fingerprint
def to16Bytes (l: BigInt, pos: Int=len) : List[Byte] =
  if (pos == 1) List (l.toByte) else (l % 256L).toByte :: to16Bytes (l / 256L, pos-1)
/** if number isn't prime, take next */
def nextProbPrime (l: BigInt) : BigInt =
  if (l.isProbablePrime (9)) l else nextProbPrime (l + 1)
/** Take every input, shift and add, but take primes */
def codify (s: String): BigInt =
  (BigInt (17) /: s) ((a, b) => nextProbPrime (a * BigInt (257) + b))
/** very, very short Strings - less than 14 bytes - have to be filled, to obscure them a bit: */
def f (s: String) : Array [Byte] = {
  val filled = (if (s.size < 14) s + "secret" + s else s)
  to16Bytes (codify (filled + filled.reverse)).toArray.map (l => nextProbPrime (l).toByte)
}

Test, if the result doesn't look similar for similar input:
val samples = List ("a", "aa", "b", "", "longer example", "This is a foolish, fishy test")

samples.map (f)

 List[Array[Byte]] = List(
Array (-41, -113, -79, 127, 29, 127, 31, 67, -19, 83, -73, -31, -101, -113, 97, -113),
Array (-19, 7, -43, 89, -97, -113, 47, -53, -113, -127, -31, -113, -67, -23, 127, 127),
Array (-41, -113, -79, 127, 29, 127, 31, 67, -19, 83, -73, -31, -101, -113, 97, -113),
Array (37, -19, -7, 67, -83, 89, 59, -11, -23, -47, 97, 83, 19, 2, 2, 2),
Array (79, 101, -47, -103, 47, -13, 29, -37, -83, -3, -37, 59, 127, 97, -43, -43),
Array (37, 53, -43, -73, -67, 5, 11, -89, -37, -103, 107, 97, 37, -71, 59, 67))

The error is using just primes for the encoding. Instead of
scala> math.pow (256, 16)
res5: Double = 3.4028236692093846E38

values, we end with
scala> math.pow (54, 16)
res6: Double = 5.227573613485917E27

since there are 54 primes below 256.

5.22e27 >> 2^16.  There's no way to brute force that many possibilities.

you forgot the name of the language

@ajax333221: Scala. I added it to the top.

@KeithRandall: I could 'accidentally' only use positive Bytes, which would reduce the possibilities to math.pow (27, 16), but that is still about 8e22.

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


text:
Implement a model of computation using a type system
Implement any model of computation as powerful as a Turing machine using any existing language's type system.
Your solution should handle the computation using the language's type system, not the language's regular Turing complete features, nor a macro system.  It is however acceptable to use the language's regular features for IO, typical boilerplate, etc. so long as your program's Turing completeness hangs on the type system.
You are certainly welcome to use optional type system features that require compiler options to activate.
Please specify how to program and run your machine, ala "edit these numbers/constructs in the source, compile it and run it."
As an example, there is an implementation of brainfuck in C++ template meta-programming.  In fact, brainfuck is more complex than necessary because it offers user IO separate from its tape.  A few simpler models of computation include Brainfuck's ancestor P", λ-calculus, the (2,3) Turing Machine, and Conway's Game of Life.
We'll declare the winner to be whoever minimizes : their code's length plus 10 times the number of commenters who assert they already knew the language had a turing complete type system.

I like the task, but the criteria don't seem very objective. Could you explain a bit more detailed how you intend to do the rating?

How about minimum of length plus 10 times the number of commenters who assert they already knew the language had a turing complete type system?  Is that objective enough?

Allright (for me), though it highly depends on many people participating.

could you just give an example of a valid submission?

I've added a link to an implementation of brainfuck in C++ template meta-programming, that's way more complex than necessary.  http://graphov.blogspot.co.uk/2010/03/template-brainfuck-compiler.html

There is a one variable λ-calculus implemented in Haskell's type system here : http://www.haskell.org/haskellwiki/Type_arithmetic  I'd expect various other extensions give different solutions in Haskell

more background : http://stackoverflow.com/questions/3787960/what-makes-haskells-type-system-more-powerful-than-other-languages-type-syst

@JeffBurdges, the link you provide does not satisfy the challenge: arithmetic and logic are provided by the language and not the type system.

Isn't the distinction between the language's type system and a macro system in the context of C++ meta-programming rather ambiguous?

The current OWC is more of a bad joke than an actual scoring criterion. Please just go with a normal one...

My limited Haskell-fu has come up with this implementation of SK-calculus in Haskell's type system:
data S = S
data K = K
data A l r = A l r

class C i o | i -> o
instance C (A (A K a) b) a
instance C (A (A (A S a) b) c) (A (A a c) (A b c))

With these type declarations in place, we can define an identity function for pairs of combinator reductions:
x :: C a b => (a, b) -> (a, b)
x = id

If we add "deriving Show" to the end of those "data" lines, then this works (ie. "((K S) K) reduces to S"):
main = print $ x ((A (A K S) K), S)

Whilst this fails to compile, due to a type mismatch ("((K S) K) reduces to K", which is false):
main = print $ x ((A (A K S) K), K)


text:
Did I win the lotto?
I just submitted an answer to this question, and then looked about at some news stories about the MegaMillions lottery craze going on right now in the US. This news article stated that an individual purchased $20,000 worth of tickets at one time (that's 20,000 sets of numbers to confirm!) to try and test their luck.
That led me to thinking about how one might quickly determine whether or not they'd won any prize, not just a jackpot, on a large lot of tickets that they had purchased.
The challenge then is this:
Overview:
Write a function or program that will accept a string of numbers as an argument (STDIN, or read in from a file, your choice), and return the numbers of the tickets with at least the minimum payout awarded.
Code Details:

The input will consist of a series of lines, one for each ticket purchased. The winning numbers will be prefixed with a 0, while the drawn numbers will be prefixed with an incremented number starting at 1. (see example)
The input should be a completely random set of numbers each time, including draws and winning numbers.
The input should accept any number of tickets n where 1 <= n <= 20,000. (Assume no 0 ticket runs.)
Each line of input will have 7 numbers per line. One for the prefix noted above, 5 for the standard balls, and one additional for the 'match' ball. (see Lotto Details below)
The input can be delimited any way you wish (whitespace, semicolon, etc.)
The output should be a listing of all winning draws and the winning amount. (So you know which to turn in.)
The output listing should be ordered by win amount. (Who cares if you won $2 on one ticket if you also won $10,000 on another???)
When more than one ticket wins the same amount, the order of those tickets is irrelevant.
The output should also give a listing of the total amount won.

Lotto Details:

Standard rules for the MegaMillions game will apply, since that's what's so hot right now.
Draws consist of six numbers from two separate pools of numbers - five different numbers from 1 to 56 and one number (the match ball) from 1 to 46.
The jackpot is won by matching all six winning numbers in a drawing.
Awards for non-jackpot wins are awarded as follows (see image below).
(Main) + (Match) = (Payout)
5 + 1 = Jackpot
5 + 0 = $250,000
4 + 1 = $10,000
4 + 0 = $150
3 + 1 = $150
3 + 0 = $7
2 + 1 = $10
1 + 1 = $3
0 + 1 = $2
Assume current jackpot is $1,000,000 (one million).
Assume only one jackpot winner, unless your random draw pulls the same jackpot pick more than once (are you cheating?).
Assume no multiplier/California rules are in-play.

Challenge Details:

This is code golf, so shortest code wins.
In the event of a tie, I'll take the highest upvoted answer. I know this is somewhat subjective, but the main point is still the score.

Example:
Input:
0   2   4   23  38  46  23
1   17  18  22  23  30  40
2   2   5   24  37  45  23
3   4   23  38  40  50  9
4   2   4   23  38  46  17
5   5   16  32  33  56  46

Output:
4 - $250,000
3 - $7
2 - $3
Total Winnings: $250,010

Can you repeat the lottery rules here? I think questions should be self-contained. And also I can't access gambling sites from work.

Sure... adding above in a minute!

Isn't the Jackpot split between all winning tickets?

@leftaroundabout Fixed.

No... I win....

I'm hoping someone else will submit an answer. Perhaps I should extend the deadline?

Getting to the end. Looks like hallvabo's going to win this one...

Python, 239 chars
import sys
a=map(eval,sys.stdin)
w=lambda x:(0,2,0,3,0,10,7,150,150,1e4,25e4,1e6)[2*len(set(x[1:-1])&set(a[0][1:-1]))+(x[6]==a[0][6])]
s=0
for e in sorted(a[1:],cmp,w,1):
    t=w(e);s+=t
    if t:print e[0],"- $%u"%t
print"Total Winnings: $%u"%s

Assuming the input numbers are comma separated.

Thanks for the math idea: 1e4, etc. (I should have known it from the start!)

Do newlines count in python? what about indentation?

Yes, both counts.
Newlines count as 1 char each.
Indentation can be minimized by interleaving spaces and tabs: 1st level=, 2nd level=, 3rd level= etc.

Javascript, 353 Bytes
(function(t){u={"51":1e6,"50":25e4,"41":1e4,"40":150,"31":150,"30":7,"21":10,"11":3,"01":2},a=t.split('\n'),l=a.length-1,m=a[0].split(' '),w=m.slice(1,6),h=0;for(;l--;){s=a[l+1].split(' '),i=s.slice(1,6).filter(function(n){return!!~w.indexOf(n)}),n=i.length+''+(s[6]==m[6]?1:0),v=u[n];if(v){h+=v;console.log(l+'-$'+v)}}console.log('Total Winnings: $'+h)})("0 2 4 23 38 46 23\n" + "1 17 18 22 23 30 40\n" + "2 2 5 24 37 45 23\n" + "3 4 23 38 40 50 9\n" + "4 2 4 23 38 46 17\n" + "5 5 16 32 33 56 46")

ungolfed:
(function (t) {
    u = {
        "51": 1e6,
        "50": 25,
        "41": 1e4,
        "40": 150,
        "31": 150,
        "30": 7,
        "21": 10,
        "11": 3,
        "01": 2
    },
    a = t.split('\n'),
    l = a.length - 1,
    m = a[0].split(' '),
    w = m.slice(1, 6),
    h = 0;
    for (; l--; ) {
        s = a[l + 1].split(' '),
        i = s.slice(1, 6).filter(function (n) { return !! ~w.indexOf(n) }),
        n = i.length + '' + (s[6] == m[6] ? 1 : 0),
        v = u[n];
        if (v) {
            h += v;
            console.log(l + ' - $' + v)
        }
    }
    console.log('Total Winnings: $' + h)
})("0 2 4 23 38 46 23\n" +
"1 17 18 22 23 30 40\n" +
"2 2 5 24 37 45 23\n" +
"3 4 23 38 40 50 9\n" +
"4 2 4 23 38 46 17\n" +
"5 5 16 32 33 56 46")

Could probably knock a few chars off that :D

I see that as 499 characters (with the args at the end of your single line version)... Am I missing something?

@Gaffi Yes, that's interesting... I wrapped it in a function and "toString().length"ed it, and got 517, but a straight char count comes in at 499... Thanks for pointing that out!

VBA (660 535 Chars)
Assuming delimiter is a space (" ")...
Sub a(b)
c=Split(b,vbCr)
Set l=New Collection
Set n=New Collection
d=Split(c(0)," ")
For e=1 To UBound(c)
f=Split(c(e)," ")
p=f(0)
i=1
For g=1 To 5:For h=1 To 5
i=i-(d(g)=f(h))
Next:Next
k=IIf(d(6)=f(6),Choose(i,2,3,10,150,10^4,10^6),Choose(i,0,0,0,7,150,500^2))
If k>0 Then
o=1
For m=1 To l.Count
If k>=l(m) Then l.Add k,p,m:n.Add p,p,m:o=0:m=99999
Next
If o Then l.Add k,p:n.Add p,p
End If
Next
For m=1 To l.Count
r=r & n(m) & ":" & Format(l(m),"$#,##0") & vbCr
q=q+l(m)
Next
MsgBox r & "Total Winnings:" & Format(q,"$#,##0")
End Sub

I was able to significantly reduce the size by converting the Select Case into Choose()

Great trick! it's been so many years since I heard of Choose()... This is a nice thing to post on http://codegolf.stackexchange.com/questions/5175/tips-for-golfing-in-vba

@w0lf Not a bad idea!

you can loose quite a few chars by replacing the second to last line with Debug.?r& "Total Winnings:" &Format(q,"$#,##0") and removing whitespace in concatenations

Oh and whenever you have a For i=1 To 5 or like loop that can be condensed to For I=1To 5


text:
create an ascii progress bar
well, it's something similar to this question but with a little differences. you have to write a program to ask for width of progress bar and how much work is done. and then draw a progress bar with following features:

width indicates how many characters you have to use to draw progress bar
progress is given via a floating point value between 0..1.
first and last character in progress bar should be something different from all other character, for example "[" and "]"
your program should use two different characters to how much progress passed since the start
you have to write how much work is done right in the middle of progress bar, using a decimal number + "%" sign.

bonus point for handling extreme inputs, such as 150% or -5% work done.
scoring number of characters * (1 without bonus or 0.75 width bonus)
some examples of valid outputs
79 0.15
[||||||||||||                         15%                                     ]

25 0.76
[##########76%#####.....]

39 -0.12
[                 -12%                 ]

25 7.6
[##########760%#########]

How is input taken? Command line? Stdin? Any of the above?

@lochok I guess stdin would be a better choice.

PHP 84 x 0.75 = 63
Edit: A less 'pretty' version, but it should be valid according to the rules:
[<?=str_pad(!fscanf(STDIN,~Ú›Ú™,$a,$b),$a*min(1,$b),~ß)|str_pad(100*$b.~Ú,$a,_,2)?>]

Output:
$ echo 79 0.15 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂___________________________15%______________________________________]
$ echo 25 0.76 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂76%⌂⌂⌂⌂⌂______]
$ echo 39 -0.12 | php progress-bar.php
[_________________-12%__________________]
$ echo 25 7.6 | php progress-bar.php
[⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂760%⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂⌂]

Original (98 x 0.75 = 73.5)
[<?=strtr(str_pad(!fscanf(STDIN,~Ú›Ú™,$a,$b),$a*min(1,$b),~ß)|str_pad(100*$b.~Ú,$a,~ü,2),~ü,~ß)?>]

Output:
$ echo 79 0.15 | php progress-bar.php
[###########                           15%                                      ]
$ echo 25 0.76 | php progress-bar.php
[###########76%#####      ]
$ echo 39 -0.12 | php progress-bar.php
[                 -12%                  ]
$ echo 25 7.6 | php progress-bar.php
[##########760%###########]

I'm wondering how can I run your code.

Save it as a php file. Send it the two paramaters as a space separated string as STDIN. For example:
[windows/linux command prompt] echo 79 0.15 | php progress-bar.php
You will need to have the php-cli (command line interface) installed. Most php installers for windows should have it included (or optional), linux with apt-get install php5-cli

I've selected this answer since as far as I tested this one always worked as expected, while one that ephemient provided sometimes doesn't print the number exactly in the middle.

J, 78×0.75 = 58.5
'w p'=:_".1!:1]3
1!:2&4('%',~":100*p)(i.@[-<.@-:@-)&#}'[]'0 _1}' |'{~(w*p)>i.w

$ echo -n 79 0.15 | jconsole test.ijs
[|||||||||||                          15%                                     ]
$ echo -n 25 0.76 | jconsole test.ijs
[||||||||||76%|||||     ]
$ echo -n 39 -0.12
[                 _12%                ]
$ echo -n 25 7.6 | jconsole test.ijs
[|||||||||760%||||||||||]

(Negative numbers in J are prefixed by _, not -.  Luckily, dyadic ". can parse both formats.)

Does this exclude the space taken by the percentage when it calculates the number of bars to display? Cause it seems to get different results from mine.

@grc With 100 columns, each percent is a single bar (even if hidden by other elements such as the brackets or number/percent).

Okay I get it now. Good job :)

@ephemient now I've noticed in -0.12 case, you are printing 18 spaces at left part and 16 at right part. it means _12% is not exactly in the middle.

Perl, 96×¾ = 72
#!/usr/bin/perl -ap
formline'[@'.'|'x($F[0]-3).']',100*$F[1].'%';
$_=$^A;s# |(.)#$1//($-[0]<$F[0]*$F[1]?'|':$&)#eg

That's by traditional Perl golf rules (#! line not counted, except for the - and switches if any).

$ echo 79 0.15 | perl test.pl
[|||||||||||                          15%                                     ]
$ echo 25 0.76 | perl test.pl
[||||||||||76%|||||     ]
$ echo 39 -0.12 | perl test.pl
[                -12%                 ]
$ echo 25 7.6 | perl test.pl
[|||||||||760%||||||||||]

Python - 158 155 148 143 138 characters (score of 103.5)
x,y=raw_input().split()
x=int(x)-2
y=float(y)
p=`int(y*100)`+"%"
b="|"*int(x*y+.5)+" "*x
print"["+b[:(x-len(p))/2]+p+b[(x+len(p))/2:x]+"]"

It could be 30 characters shorter if the input was separated by a comma.

why didn't you use r=p.length()?

what do you mean?

nothing my bad, I just misunderstood you code.

but your code doesn't seem to handle -12% case.

What is it meant to do? At the moment it just prints an empty bar with the percentage.

nope, note that with y being way negative, r will also be something below zero, and that will break his code.

Multiplying strings by negative numbers just returns and empty string.

you changed his code, it was wrong before you change it!

I've been shortening it, but it has worked for me each time. Check the revision history of the post if you want.

Ruby - score 93 (124 characters)
w=gets.to_i-2
f=$_[/ .+/].to_f
e=f<0?0:f>1?w:(f*w).to_i
b='#'*e+' '*(w-e)
b[(w-l=(s='%d%'%(100*f)).size)/2,l]=s
puts"[#{b}]"

Yet another ruby implementation. Reads input from STDIN in the form described above. You may exchange characters '#', ' ' and '[', ']' directly in the code.
45 0.88
[####################88%##############      ]

60 1.22
[###########################122%###########################]

this is alway two chars too wide

@padde Why do you think it's two chars too wide? There is a -2 in the first line.

node.js: 135chars, *0.75 for bonus points, so 101.25chars.
a=process.argv,i=a[2],p=a[3],o=i/2|0,f=i-i*p,x=['['];for(;i--;){x.push((i<f?' ':'|')+(i-o?'':p*100+'%'));}console.log(x.join('')+']');

ungolfed:
a = process.argv, // console inputs
i = a[2], // input 1 -> width
p = a[3], // input 2 -> percent complete
o = i / 2 | 0, // half of i, without any decimal places
f = i - i * p, // how far along the bar to draw spaces
x = ['[']; // start an array
while(i--){ // while i > 0
    x.push( // add to the array
    (i < f ? ' ' : '|') // a space, or | depending on how far along the bar we are
    + (i - o ? '' : p * 100 + '%')); // and if we're halfway, add the percentage complete
}
console.log(x.join('') + ']'); // then write out the array as a string, with a trailing ]

output:
D:\mercurial\golf\ascii>node progressBar.js 25 7.6
[|||||||||||||760%||||||||||||]

D:\mercurial\golf\ascii>node progressBar.js 39 -0.12
[                    -12%                   ]

D:\mercurial\golf\ascii>node progressBar.js 79 0.15
[|||||||||||                             15%                                       ]

Scala 149:
val w=readInt
val p=readFloat
println(("["+"|"*(p*w).toInt+" "*((w-p*w).toInt)+"]").replaceAll("(^.{"+(w/2-3)+"}).{5}","$1 "+(p*100).toInt+("% ")))

ungolfed:
def progressbar (width: Int, pos: Double) {
  println ((
    "["+
    "|"*(pos*width).toInt+
    " "*((width-pos*width).toInt)+
    "]").
    replaceAll ("(^.{" + (width/2-3) + "}).{5}", "$1 " + (p * 100).toInt + ("% ")))}
}

I decided, for readability, you really need a space around the progress number:
(44 to 54).map (x => b (100, x/100.0))
[||||||||||||||||||||||||||||||||||||||||||||   44%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||  45%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 46%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 47%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 48%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 49%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 50%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 51%                                                  ]
[|||||||||||||||||||||||||||||||||||||||||||||| 52% |                                                ]
[|||||||||||||||||||||||||||||||||||||||||||||| 53% ||                                               ]
[|||||||||||||||||||||||||||||||||||||||||||||| 54% |||                                              ]

Q,90 chars, no bonus
{-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}

usage
q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[50;0.15]
[|||||||                 15%                     ]

q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[30;0.35]
[||||||||||    35%           ]

q){-1 @[x#" ";(1+(!)(_)x*y;0;((_)x%2)+(!)(#)($)a;x-1);:;("|";"[";a:,[;"%"]($)(100*y);"]")];}[40;0.85]
[|||||||||||||||||||85%||||||||||||    ]

C, 145 characters, score = 108.75
float p;s;m;char x[99];main(){scanf("%d%f",&s,&p);sprintf(x+s/2-1,"%.0f%%",p*100);for(;m<s;)x[++m]||(x[m]=m<p*s?35:32);x[s-1]=93;*x=91;puts(x);}

though I really liked your idea of sprintf, but it generates a minor problem, check your program with 20 1 inputs it will generate output of [#######100%######] in this case there are 7 sharps left of number and 5 sharps at right, so the number printed is not exactly in the middle.

JavaScript 127 125, no bonus
l=9,p="0.99",f=l*p|0,m=l/2|0,x=["]"];for(;l--;)x.unshift(l>=f?"-":"+");x[m++]=p[2],x[m++]=p[3],x[m]="%";alert("["+x.join(""))
//[+++99%++-]

Usage: Change l=9 with other length and/or change p="0.99" with other percent
Note: end with zero 0.X0 instead of 0.X

PHP-128x0.75=>96

<?fscanf(STDIN,'%d%d',$w,$p);$v='[';for($i=1;$i<$w-1;)$v.=($i++==$w/2-1)?$p*($i+=2)/$i.'%':(($i<$w*$p/100)?'|':' ');echo"$v]";?>

<?fscanf(STDIN,'%d%f',$w,$p);$v='[';for($i=1;$i<$w-1;)$v.=($i++==$w/2-1)?$p*100*($i+=2)/$i.'%':(($i<$w*$p)?'|':' ');echo"$v]";?>

C, 149*0.75=111.75
main(w,i){float p;for(i=printf("[",scanf("%d%f",&w,&p));i<w-1;)(i++==w/2-1)?printf("%.0f%%",p*100*(i+=2)/i):printf("%c",i<=(p*w)?'|':' ');puts("]");}

Output:
80
0.75
[||||||||||||||||||||||||||||||||||||||75%||||||||||||||||||                   ]

80
7.60
[||||||||||||||||||||||||||||||||||||||760%|||||||||||||||||||||||||||||||||||||]

80
-0.12
[                                      -12%                                     ]

p should be a floating point value, between 0..1

@Gajet thanks for bringing to notice. Has been rectified :)

MATL, score 35.25 (47 * 0.75)
qqtl&O61bti*Xl:(HG100*V37hyn2/kyny+q&:(91w93v!c

Try it online!
Explanation:
         % implicit input, say w = 79
qq       % decrement input by 2 (to allow brackets on either side)
tl&O     % duplicate and create array with that many zeros
61       % Push '=' character
b        % bubble up w-2 from below
ti*      % duplicate and multiply by second input, say p = 0.15
         %  stack: [[0;0;0;...;0], 61, 77, 11.55]
Xl       % take minimum of (w-2) and (w-2)*p
         %  (used when p > 1, makes eligible for bonus)
:        % create range 1 to that value
         %  stack: [[0;0;0;...;0], 61, [1 2 3 4 5 ... 11]]
(        % assign into the first array the value 61 ('=') at the
         %  indices denoted by the third array
HG       % push second input again
100*V    % multiply by 100 and convert to string
37h      % append the '%' symbol to it
yn2/k    % compute half of the length of the output array
yny+q    % copy of that + length of the 'N%' string - 1
         % stack: [[61;61;61;...;0;0;0], '15%', 38, 40]
&:       % make a range from the first to the second (38 to 40)
(        % assign the 'N%' string at those places into the output array
91w93    % surround by '[' (ASCII 91) and ']' (93) characters
v!       % combine into a single array, make it horizontal for display,
c        % change it to character type (implicitly displayed)

Excel VBA, 108*.75 = 81 bytes
A function that takes input from [A1] and [B1] and outputs to the console
s=""&[MID(IFERROR(REPT("",A1*B1),"")&REPT("",A1),2,A1-2)]&"":n=100*[B1]:Mid(s,([A1]-len(n))/2)=n &"%":?s

Output
with input [A1]=25 and [B1]=.76
76%

With input [A1:B1].Resize(1,2)=Split("32 -.5")
-50%

With input [A1:B1].Resize(1,2)=Split("40 10.01")
1001%

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


text:
Lorem Ipsum Random Code Generation
An IDE developer has hired you to write a program that generates (by printing to stdout) n lines of randomly generated code. They will use your program to create sample code for use in marketing their newest compiler.
Rules:
Your randomly generated output code:

must not be the same each execution (for the same n parameter)
must be written in the same language as your program
must be able to be successfully compiled without errors or warnings (including "variable not used" messages, if your language includes them)
should use a variety of the language's built-in features
should (where appropriate) follow the language's most popular style guide. For example, PEP-8 for Python
should, if n is larger than 20, have functions. Functions should be limited to a length that follows the language's style guide
does not have to have comments (but the developer will be impressed if it does!)
may include a single blank line between code blocks for clarity

You can use an external dictionary to allow generation of function/variable names, and lists of standard functions/libraries for your language. If your program uses these, please include a link (to a pastebin if your dictionary is custom written for this task)
Please include a few sample outputs to demonstrate your program's capabilities.
Winning:
The winning program should implement all the above features, and generate realistic code without sacrificing execution time or program length (to a huge degree - this isn't golf).
The winner will be chosen by community vote from entries received before 1st May 2012. Voting should be based upon realism, variety, creativity and adherence to the criteria above.
Good luck!

possible duplicate of Generate a random program in your favorite language

If you were to assign a point value to each of the requirements you'd have something rather more like the "objective winning criteria" required. Without that the issue of duplication is moot. Question for the crowd does [code-golf]/not [code-golf] constitute a sufficient distinction to avoid closing?

Good point, and thanks for the link. I'll improve the question to include a scoring system tomorrow morning (it's 2am now).

This seems different than the linked question to me because of the same language restriction. Should cut down on the x->BF entries, although I will be working on BF->BF

@dmckee I've modified the challenge, and anxiously await everyone's entries! I plan to add a bounty and my own entry to increase the appeal.

As far as I am concerned "most votes" is not, has never been and will never be an "objective criteria". It is quantitatively different from "fewest bytes" which can be determined from the entries themselves.

What's the point of "must not be the same each execution (for the same n parameter) "? Wouldn't a strictly deterministic generation be more Lorem-Ipsum-like?

I’m voting to close this question because "must be able to be successfully compiled", "blocks", "functions", "style guide", and "variety of the language's features" are subjective and not featured in all languages.

Did it in Brainfuck! I had a bit of trouble generating random numbers. I hoped something simple like a LFSR could give me a fairly decent looking sequence, but I found it looped too quickly and gave boring output. I resorted to using a RNG found here, which actually takes quite a long time to run. Since BF has no capacity to get any source of entropy from the operating system, I first have the user input any text (I pound on they keyboard) to seed the RNG. After that it takes the number of lines and outputs random BF, using 16 hard-coded subsequences.
get random seed input till newline (10)
>>>+[,[<+>>+>>>>>>+++<<<<<<<-]>[<+>-]<----------]
get number of lines
<<<,[->>

Map: n nesting seed lineCount _ _ _ _ _ _ randh randl

mod by 32 to get char count for this line
[>+>+<<-]>>[<<+>>-]>++++[<++++++++>-]<<
[->-[>+>>]>[+[-<+>]>+>>]<<<<<] >[-]>>[-]<[<<+>>-]
loop that many times
<<[-<

generate next 'random' number
>>[-]>[-]>[-]>[-]>[-]>[-]>[<<<<<<+>>>>>>-]>[<<<<<<+>>>>>>-]<<<<+++++++
[<+++++++++++>-]<[<<[>>>>>>+<<<+<<<-]>>>[<<<+>>>-]<<[>>>>>+<<<+>+<<<-]
>>>[<<<+>>>-]<[>>>>+[<<<+>+>>-]<<[>>+<<-]+<[>-<[-]]>[>+<-]<<-]<-]+++++
+[>++++++++<-]>-[<<[>>>>>+<<<<+<-]>[<+>-]>-]<<<[-]>[-]+++++[<+++++>-]<
[>>>>>>>+[<<<<<<+>+>>>>>-]<<<<<[>>>>>+<<<<<-]+<[>-<[-]]>[>>>>+<<<<-]<<
-]++++++[>>>>>>+++++++++<<<<<<-]>>>>>>[<<<<<<<<+>>+>>>>>>-]<<<<<<[>>>>
>>+<<<<<<-]<<
seed is now next number in sequence

copy and mod 16
[>>+>+<<<-]>>>[<<<+>>>-]>++++[<++++>-]<<
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<
now we have bottom 4 bits of data; pick an output sequence:
#00: +
[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]<
>++++++[<+++++++>-]<+.[-]]>

#01: +
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]<
>++++++[<+++++++>-]<+.[-]]>

#02: -
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-
[-]>[-]<
>+++++[<+++++++++>-]<.[-]]>

#03: [->-[>+>>]>[+[-<+>]>+>>]<<<<<]
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]<
>+++++++[<+++++++++++++>-]<.
>+++++[<--------->-]<-.
+++++++++++++++++.
-----------------.
>+++++[<+++++++++>-]<+.
>++++[<------->-]<-.
>+++[<------>-]<-.
>+++[<++++++>-]<+..
>+++++[<++++++>-]<+.
>+++++[<------>-]<-.
>++++[<+++++++>-]<+.
>++++++[<-------->-]<.
>++++++[<++++++++>-]<.
>+++++[<--------->-]<-.
+++++++++++++++.
-----------------.
>+++[<++++++>-]<+.
>+++++[<++++++>-]<+.
>+++++[<------>-]<-.
>+++[<------>-]<-.
>+++[<++++++>-]<+..
>+++++[<++++++>-]<+.
>++++[<-------->-]<-.....>++++[<++++++++>-]<+.[-]]>

#04: <
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-
[-]>[-]<
>++++++[<++++++++++>-]<.[-]]>

#05: <
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-
[-]>[-]<
>++++++[<++++++++++>-]<.[-]]>

#06: >
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[- ----[>+<----]>---.[-]<]>

#07: x y z
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]<
>++++[<++++++++>-]<.
>++++++++[<+++++++++++>-]<.
>++++++++[<----------->-]<.
>++++++++[<+++++++++++>-]<+.
>++++++++[<----------->-]<-.
>+++++++++[<++++++++++>-]<.[-]]>

#08: [
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-
[-]>[-]<
>+++++++[<+++++++++++++>-]<.[-]<<<<+>>>>
]>

#09: [
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-
[-]>[-]<
>+++++++[<+++++++++++++>-]<.[-]<<<<+>>>>
]>

#10: ++[>+<------]>
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-
 [-]>[-]<
>++++++[<+++++++>-]<+..
>++++++[<++++++++>-]<.
>++++[<------->-]<-.
>+++[<------>-]<-.+++++++++++++++++.
---------------......>++++++[<++++++++>-]<.
>+++++[<------>-]<-.[-]]>

#11: +<->++
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[- [-]>[-]<
>++++++[<+++++++>-]<+.
+++++++++++++++++.
---------------.
+++++++++++++++++.
>+++[<------>-]<-..[-]]>

#12: .
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]<
>+++++[<+++++++++>-]<+.[-]]>

#13: ,
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]<
>++++[<+++++++++++>-]<.
[-]]>

#14: [<+<+>>-]
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-
[-]>[-]<
>+++++++[<+++++++++++++>-]<.
>+++++[<------>-]<-.
-----------------.
+++++++++++++++++.
-----------------.
>+++[<++++++>-]<+..-----------------.
>++++++[<++++++++>-]<.[-]]>

#15: [-]
-[<+<+>>-]<[>+<-]+<[>-<[-]]>[-[-]>[-]<
>+++++++[<+++++++++++++>-]<.
>+++++[<--------->-]<-.
>++++++[<++++++++>-]<.[-]]>

[-]<<<
]
>+++++++[<+++++++++++++>-]<++<<[>>.<<-]>>[-]<<++++++++++.[-]<
]

Output for input
qqq
10

is
[<+<+>>-]<[-] x y z.< x y z<.++[>+<------]>[[-]+<. x y z++[>+<------]>.+<->++[->-[>+>>]>[+[-<+>]>+>>]<<<<<][+[<+<+>>-] x y z[<+<+>>-][<+<+>>-][<+<+>>-]++[>+<------]>+<->++]]
-[->-[>+>>]>[+[-<+>]>+>>]<<<<<][<+<+>>-][-][ x y z++[>+<------]>,[-][->-[>+>>]>[+[-<+>]>+>>]<<<<<]-]
<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]
+,++[>+<------]>-[[-]+<->++[[->-[>+>>]>[+[-<+>]>+>>]<<<<<],++[>+<------]>[->-[>+>>]>[+[-<+>]>+>>]<<<<<]++[>+<------]>.[+ x y z+<]]]
++[>+<------]>++-[-]-[-]+,[->-[>+>>]>[+[-<+>]>+>>]<<<<<][->-[>+>>]>[+[-<+>]>+>>]<<<<<][->-[>+>>]>[+[-<+>]>+>>]<<<<<]+,+[<++[>+<------]>,-+<->++]
-[<+<+>>-]-., x y z[ x y z<[<+<+>>-]< x y z<[+<->+++<->++-++[>+<------]>+<->+++[[<-[-][+<->++]]]]]
[<+<+>>-]++[<+<+>>-]-<<[-]+<->++<[]
,[->-[>+>>]>[+[-<+>]>+>>]<<<<<]++[>+<------]>++<->+++<->++[<+<+>>-]<
++[>+<------]>[<+<+>>-][+<->+++<->++[[->-[>+>>]>[+[-<+>]>+>>]<<<<<]<[<+<+>>-]++[>+<------]> x y z x y z<..[[-][<+<+>>-],[<+<+>>-]+,]]]
-, x y z<<[<[->-[>+>>]>[+[-<+>]>+>>]<<<<<].[,<-]]

and it runs in about 2 minutes on my box. Output contains entirety of BF syntax, including comments, and it well formed.

You're gonna be rich kid, when any of the major Brainfuck IDE developers see this...


text:
Water-Bucket problem
This challenge is to calculate how to measure 4 liters of water with just two unevenly sized buckets, one of 3 liters and another of 5 liters, in minimum number of steps. To extend and generalize this, write a program to evaluate the minimum number of steps to measure “X” liters of water, with “Y” buckets each having a separate denomination.
Assumptions:

Each bucket used for measuring water should be unique in denomination and the number of buckets will be <= 3
The target amount to be reached has to finally reside in a single bucket (at the end of the measuring activity).
The bucket capacities and target amount will be <= 99
If there are multiple ways to measure the same amount, only one single way, having the minimum number of steps is required.
Ties will be broken by the smallest program.

Examples:

2,3,5,4
  Implies that there are 2 buckets of capacity 3 and 5 each and the target amount desired is 4.
3,4,6,9,7
  Implies that there are 3 buckets of capacity 4, 6 and 9 each and the target amount desired is 7.

Answers:

2,3,5,4
  Fill 5
  Move 5 to 3
  Empty 3
  Move 5 to 3
  Fill 5
  Move 5 to 3
3,4,6,9,7
  Fill 4
  Move 4 to 6
  Fill 9
  Move 9 to 6

Welcome to CodeGolf.SE! Could you stop posting willy-nilly and spend a little time fixing the challenges you have already posted, please. As PhiNotPi said in a comment to your first post these are not up to spec. They do not specify a winning condition, and are difficult to read. Take some time to look at previous, well received challenges, and consider using the meta sandbox (a place to get suggestions before posting) in the future.

This has such promise...it would be a shame if it was abandoned in this state.

I agree with @dmckee. This could actually be a pretty fun challenge if it were better specified.

Python, 363 chars
Golfed it, not sure if it is golf or not.  The map P maps a reachable state to the instructions used to get to that state.  Keeps enumerating reachable states until it finds one with the target amount of water in it.
I=input()
B=I[1:-1]
R=range(I[0])
P={(0,)*I[0]:""}
while P:
 Q={}
 for s in P:
  if I[-1]in s:print P[s];P=Q={};break
  for i in R:
   Q[s[:i]+(0,)+s[i+1:]]=P[s]+"Empty %d "%B[i];Q[s[:i]+(B[i],)+s[i+1:]]=P[s]+"Fill %d "%B[i]
   for d in R:m=min(s[i],B[d]-s[d]);Q[tuple(s[j]-[0,m][j==i]+[0,m][j==d]for j in R)]=P[s]+"Move %d to\
 %d "%(B[i],B[d])
 Q.update(P);P=Q

Ruby
The following code gives a ruby implementation of the task described above. The specification is as follows:
Input: A list of integers on STDIN, where the first one is the number n of buckets available, followed by n distinct bucket denominations, followed by the target amount of water.
Output: A list of operations needed to reach the target amount in any bucket or a corresponding message if that is not possible.
Task: Start with n empty buckets each of different integer denomination. In each step you can do one of the following:

Fill X: fills the bucket with denomination X with water such that it contains exactly X water
Empty Y: empty the bucket with denomination Y, i.e. no water inside after this operation
Move A to B: take any water in bucket with denomination A and put it into bucket with denomination B up to the point where bucket B is full. (Example: Bucket 5 has 4 liters in it and bucket 3 has 2. Then Move 5 to 3 will transfer 1 liter leaving bucket 5 with 3 liters while bucket 3 is full afterwards.)

The algorithm used is quite straightforward. On a list of bucket configurations (i.e. a list of buckets with their corresponding fill levels) perform all possible operations. Each one will lead to a new configuration. Keep those which you didn't had already in previous steps (i.e. those that are really novel). This way we get a list of configurations reachable be 1 step, 2 steps, ... . Whenever we reach a configuration where one bucket is filled with exactly the target amount we are done.
Since we have a constructive algorithm, i.e. we know in each step which operation we perform, we can simultaneously build the list of operations in textual representation for any bucket configuration.
Example: 3 buckets with denominations 7, 9 and 11. Target amount of water is 1.
Input:
3, 7, 9, 11, 1

Output:
Solution found with 7 steps:
 Fill 7 Move 7 to 11 Fill 7 Move 7 to 11 Move 7 to 9 Fill 7 Move 7 to 9

Code:
# get input as list of integers
input = gets.split(/,/).map{|s| s.to_i}

count = input.shift
start = (1..count).map{[input.shift, 0]}
target = input.shift

# a bucket configuration is a list of buckets, each represented as
# array [denomination, fill level], i.e. initial configurations
# is e.g. [[3, 0], [5, 0]] for empty buckets of size 3 and 5

configurations = {start => ""}
step = 0
solution = nil

current = configurations.keys

while current.size > 0 do

  # debug output (each configuration rechable within step)
  puts "- #{step} ------------------------------------------"
  current.each{|k| puts "#{k.to_s} #{configurations[k]}"}
  puts

  # test current configurations if target amount is included
  solution = current.select{|k| k.any?{|b| b[1] == target}}[0]
  break if solution

  step += 1
  new_configurations = {}

  # for all configurations for all buckets
  current.each{|k|
    k.size.times{|i|

      # do a fill operation on this bucket
      kn = Marshal.load(Marshal.dump(k))   # make deep copy
      # increase fill level to bucket denomination
      kn[i][1] = kn[i][0]
      new_configurations[kn] = "#{configurations[k]} Fill #{kn[i][0]}"

      # do an empty operation on this bucket
      kn = Marshal.load(Marshal.dump(k))   # make deep copy
      # set fill level to zero
      kn[i][1] = 0
      new_configurations[kn] = "#{configurations[k]} Empty #{kn[i][0]}"

      # do a move operation on any other bucket
      k.size.times{|j|
        kn = Marshal.load(Marshal.dump(k))   # make deep copy
        # amount movable is current amount or space left in other bucket
        h = [kn[i][1], kn[j][0]-kn[j][1]].min
        kn[i][1] -= h
        kn[j][1] += h
        new_configurations[kn] = "#{configurations[k]} Move #{kn[i][0]} to #{kn[j][0]}"
      }
    }
  }

  # remove any configuration already reachable with less steps
  new_configurations.keep_if{|conf| !configurations[conf]}

  # merge new configurations
  configurations.merge!(new_configurations)

  current = new_configurations.keys

end

if solution
  puts "Solution found with #{step} steps:"
  puts configurations[solution]
else
  puts "Impossible to reach target"
end

I'm pretty sure, the OP hasn't made the input specification mandatory. if you use space separated values, you can use gets.split