title: Find words containing every vowel

text:
# Question
Title: Find words containing every vowel
Your program must find all the words in this wordlist that contain all the vowels (`a e i o u y`). There are easy ways to do this, but I am looking for the shortest answer. I will take any language, but I'd like to see Bash.

Here is an example (could be much improved):

```
cat wordlist.txt | grep "a" | grep "e" | grep "i" | grep "o" | grep "u" | grep "y"

```

Your score is the length of the code.

-5 points for counting all occurrences of the word.

Lowest score wins.

# Answer
# GolfScript, 20 chars − 5 = 15 points

```
n%{'aeiouy'\-!},.,+`

```

Based on Howard's solution, but using a shorter test (`\-!` saves one char over `&,6=`), shorter length-appending (`.,+` = 3 chars) and shorter output formatting (nobody said the output had to be newline-separated, so ``` saves one char over `n*`).

Here's the output, given the lowercase word list as input (linebreaks inserted for readability):

```
["abstemiously" "authoritatively" "behaviourally" "consequentially" "counterrevolutionary"
"disadvantageously" "educationally" "encouragingly" "eukaryotic" "evolutionarily"
"evolutionary" "exclusionary" "facetiously" "gregariously" "heterosexuality" "homosexuality"
"importunately" "inconsequentially" "instantaneously" "insurrectionary" "intravenously"
"manoeuvrability" "neurologically" "neurotically" "ostentatiously" "pertinaciously"
"precariously" "precautionary" "questionably" "revolutionary" "simultaneously"
"supersonically" "tenaciously" "uncomplimentary" "uncontroversially" "unconventionally"
"undemocratically" "unemotionally" "unequivocally" "uninformatively" "unintentionally"
"unquestionably" "unrecognisably" 43]

```

(Ps. Technically, given that the challenge only says the code has to work for this specific input, `n%{'aeiouy'\-!},`43` would be one character shorter yet. I consider that cheating, though.)

---

### Explanation:

* `n%` splits the input on newlines into an array.
* `{ },` is a "grep" operator, executing the code between the braces for each element of the array and selecting those for which it returns a true value.
    + Inside the loop, `'aeiouy'\-` takes the literal string `aeiouy` and removes from it every character found in the candidate word. The `!` then logically negates the resulting string, yielding `1` (true) if the string is empty and `0` (false) if it's not.
* `.,+` makes a copy of the filtered array, counts the number of words in it, and appends the result to the original array.
* Finally, ``` un-evals the array, converting it into a string representation of its contents. (Without it, the words in the array would simply be concatenated in the output, yielding an unreadable mess.)
> 7 votes

# Answer
### GolfScript, 19 characters

```
n%{'aeiouy'&,6=},n*

```

Usage:

```
golfscript vowels.gs < wordlist.txt

```

Output:

```
abstemiously
authoritatively
behaviourally
[...]
uninformatively
unintentionally
unquestionably
unrecognisably

```

If you also want to output the count at the end you can use

```
n%{'aeiouy'&,6=},.n*n@,

```

which is four characters longer.
> 15 votes

# Answer
## Python - 46 characters

```
filter(lambda x:set(x)>=set("AEIOUY"),open(f))

```

Readable version: It's already pretty readable :-)
> 11 votes

# Answer
## Ruby 38

Edit 34: Best so far (from @O-I):

```
a.split.select{|w|'aeiouy'.count(w)>5}

```

Edit 1: I just noticed the question asked for 'y' to be included among the vowels, so I've edited my question accordingly. As @Nik pointed out in a comment to his answer, `"aeiouy".chars` is one character less than `%w[a e i o u y]`, but I'll leave the latter, for diversity, even though I'm risking nightmares over the opportunity foregone.

Edit 2: Thanks to @O-I for suggesting the improvement:

```
s.split.select{|w|'aeiouy'.delete(w)==''}

```

which saves 11 characters from what I had before.

Edit 3 and 3a: @O-I has knock off a few more:

```
s.split.select{|w|'aeiouy'.tr(w,'')==''}

```

then

```
s.split.reject{|w|'aeiouy'.tr(w,'')[1]}

```

and again (3b):

```
a.split.select{|w|'aeiouy'.count(w)>5}

```

I am a mere scribe!

Here are two more uncompettive solutions:

```
s.split.group_by{|w|'aeiouy'.delete(w)}['']       (43)
s.gsub(/(.+)\n/){|w|'aeiouy'.delete(w)==''?w:''} (48)

```

Initially I had:

```
s.split.select{|w|(w.chars&%w[a e i o u y]).size==6}

```

`s` is a string containing the words, separated by newlines. An array of words from `s` that contains all five vowels is returned. For readers unfamiliar with Ruby, `%w[a e i o u y] #=> ["a", "e", "i", "o", "u", "y"]` and `&` is array intersection.

Suppose

```
s = "abbreviations\nabduction\n"
s.split #=> ["abbreviations", "abduction"]

```

In the block `{...}`, initially

```
w             #=> "abbreviations"
w.chars       #=> ["a", "b", "b", "r", "e", "v", "i", "a", "t", "i", "o", "n", "s"]
w.chars & %w[a e i o u y] #=> ["a", "e", "i", "o"]
(w.chars & %w[a e i o u y]).size == 6 #=> (4 == 6) => false,

```

so "abbreviations" is not selected.

If the string `s` may contain duplicates, `s.split.select...` can be replaced by `s.split.uniq.select...` to remove duplicates.

Just noticed I could save 1 char by replacing `size==6` with `size>5`.
> 8 votes

# Answer
# APL, 21 - 5 = 16

```
(,≢)w/⍨∧⌿'aeiouy'∘.∊w

```

Expects to find the list of words as `w`. Returns a list of the words that contain all the vowels, plus their count. Tested with ngn apl. Here's an example.

**Explanation**

```
         'aeiouy'∘.∊w   # generate a truth table for every vowel ∊ every word
       ∧⌿               # reduce with ∧ along the rows (vowels)
    w/⍨                 # select the words that contain all the vowels
(,≢)                    # hook: append to the list its own tally

```
> 8 votes

# Answer
# Ruby - 28 characters (or 27 if `y` is excluded from vowels)

```
("ieaouy".chars-s.chars)==[]

```

The complete command to run is (48 chars):

```
ruby -nle 'p $_ if ("ieaouy".chars-$_.chars)==[]'

```

EDIT: replaced `puts` with `p` as suggested by @CarySwoveland
> 6 votes

# Answer
# Haskell - 67

```
main=interact$unlines.filter(and.flip map "aeiouy".flip elem).lines

```
> 6 votes

# Answer
# AWK - 29

```
/a/&&/e/&&/i/&&/o/&&/u/&&/y/
```

To run: Save the lowercase word list to `wordlist.txt`. Then, do:

```
mawk "/a/&&/e/&&/i/&&/o/&&/u/&&/y/" wordlist.txt
```

If your system does not have `mawk`, `awk` can be used as well.

You can also run it from a file by saving the program to `program.awk` and doing `mawk` or `awk` `-f program.awk`.
> 4 votes

# Answer
## Python, 45 characters

```
[w for w in open(f) if set('aeiouy')<=set(w)]

```
> 4 votes

# Answer
# Javascript/JScript 147(152-5), 158(163-5) or 184(189-5) bytes:

Here is my Javascript and JScript horribly "ungolfyfied" version (~~164~~ ~~152~~ 152-5=147 bytes):

~~`function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r.length]=s[k]);}return r;}`~~

`function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=6;for(z in c)i-=!!s[k].search(c[z]);i&&(r[r.length]=s[k]);}return r;}`

Thank you @GaurangTandon for the `search()` function, which saved me a byte!

RegExp based with **HORRIBLE** performance, but support both upper and lowercase (163-5=158 bytes):

`function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=RegExp(c[z],'i').test(s[k]);i==6&&(r[r.length]=s[k]);}return r;}`

RegExp based with **BETTER** performance, **BUT** takes a lot more bytes (189-5=184 bytes):

`function(s,k,z,x,i,c,r,l){l=[];r=[];for(z in c='aeiouy'.split(''))l[z]=RegExp(c[z],'i');for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=l[z].test(s[k]);i==6&&(r[r.length]=s[k]);}return r;}`

---

This one if just for the fun (175-5 bytes) and won't count as an answer:

`function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r[r.length]=s[k]]=1+(r[s[k]]||0));}return r;}`

It's based on the 1st answer, but has a 'twist': You can know how many times a word has been found.

You simply do like this:

`var b=(function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r[r.length]=s[k]]=1+(r[s[k]]||0));}return r;})('youaie youaie youaie youaie a word');`

`b.youaie //should be 4`

Since that `length` doesn't have all vowels, it wont be deleted and still would be an answer for the bonus.

---

How do you call it?

"Simple": You wrap the function inside `()` and then add `('string goes here');` to the end.

Like this: `(function(s,k,z,x,i,c,r){c='aeiouy'.split('');r=[];for(k in s=(s+'').split(/\b/)){i=0;for(z in c)i+=s[k].indexOf(c[z])>=0;i==6&&(r[r.length]=s[k]);}return r;})('a sentence youyoy iyiuyoui yoiuae oiue oiuea');`

This example will return an array only with 1 string: yoiuae

I know that this is the worst solution, but works!

---

Why am i counting -5?

Well, Javascript/JScript arrays have a property (`length`) in arrays which tells the number of elements that it have.

After being confirmed in the question, the bonus of -5 is for telling the number of words.

Since the number of words is in that property, automatically I have the score of -5.
> 3 votes

# Answer
# k \[22-5=17 chars\]

I have renamed the file "corncob\_lowercase.txt" to "w"

## Count the words \[22 chars\]

```
+/min'"aeiouy"in/:0:`w

```

### Output

```
43

```

## Find all words \[25 chars\]

```
x@&min'"aeiouy"in/:x:0:`w

```

Overall 43 words containing all the vowels `(a e i o u y)`

### Output

```
"abstemiously"
"authoritatively"
"behaviourally"
..
..
"unintentionally"
"unquestionably"
"unrecognisably"

```
> 3 votes

# Answer
## Mathematica (65 or 314)

Two very different approaches, the better one was proposed by Belisarius in the comments to my initial response. First, my brutish effort, which algorithmically generates every possible regular expression that matches a combination of six vowels (including "y"), and then checks every word in the target wordlist against every one of these 720 regular expressions. It works, but it's not very concise and it's slow.

```
b = Permutations[{"a", "e", "i", "o", "u","y"}]; Table[
 Select[StringSplit[
  URLFetch["http://www.mieliestronk.com/corncob_lowercase.txt"]],
  StringMatchQ[#, (___ ~~ b[[i]][[1]] ~~ ___ ~~
      b[[i]][[2]] ~~ ___ ~~ b[[i]][[3]] ~~ ___ ~~
      b[[i]][[4]] ~~ ___ ~~ b[[i]][[5]]~~ ___ ~~ b[[i]][[6]] ~~ ___)] &], {i, 1,
  Length[b]}]

```

~320 characters. A few could be saved through using alternate notation, and additional characters are lost preparing the dictionary file as a list of strings (the natural format for the dictionary in Mathematica. Other languages may not need this prep, but Mathematica does). If we omit that step, presuming it to have been handled for us, the same approach can be done in under 250 characters, and if we use Mathematica's built-in dictionary, we get even bigger savings,

```
Map[DictionaryLookup[(___ ~~ #[[1]] ~~ ___ ~~ #[[2]] ~~ ___ ~~ #[[3]]
~~ ___ ~~ #[[4]] ~~ ___ ~~ #[[5]]~~ ___ ~~ #[[6]] ~~ ___) .., IgnoreCase -> True] &,
 Permutations[{"a", "e", "i", "o", "u","y"}]]

```

Under 200 characters. Counting the number of words found requires only passing the result to `Length[Flatten[]]`, which can be added around either block of code above, or can be done afterwards with, for example, `Length@Flatten@%`. The wordlist specified for this challenge gives 43 matches, and the Mathematica dictionary gives 64 (and is much quicker). Each dictionary has matching words not in the other. Mathematica finds "unprofessionally," for example, which is not in the shared list, and the shared list finds "eukaryotic," which is not in Mathematica's dictionary.

Belisarius proposed a vastly better solution. Assuming the wordlist has already been prepared and assigned to the variable `l`, he defines a single test based on Mathematica's `StringFreeQ[]` function, then applies this test to the word list using the `Pick[]` function. 65 characters, and it's about 400 times faster than my approach.

```
f@u_ := And @@ (! StringFreeQ[u, #] & /@ Characters@"aeiouy"); Pick[l,f /@ l]

```
> 2 votes

# Answer
# Javascript - Score = 124 - 5 = 119 !!!

### Edit: 17/02/14

```
function(l){z=[],l=l.split("\n"),t=0;while(r=l[t++]){o=0;for(i in k="aeiouy")o+=!~r.search(k[i]);if(o==0)z.push(r)}return z}

```

Big thanks to @Ismael Miguel for helping me cut off **~12 chars**!

I removed the fat arrow notation function form because though I have seen it begin used, it doesn't work. No idea why...

---

### To make it work:

Pass all the words separated by newline as an argument to the function as shown below.

---

### Test:

```
// string is "facetiously\nabstemiously\nhello\nauthoritatively\nbye"

var answer = (function(l){z=[],l=l.split("\n"),t=0;while(r=l[t++]){o=0;for(i in k="aeiouy")o+=!~r.search(k[i]);if(o==0)z.push(r)}return z})("facetiously\nabstemiously\nhello\nauthoritatively\nbye")

console.log(answer);
console.log(answer.length);

/* output ->
    ["facetiously", "abstemiously", "authoritatively"]
    3 // count
*/

```

---
> 2 votes

# Answer
# Ruby ~~39~~ 38

Currently the shortest Ruby entry when counting the **whole program** including input and output.

Saved a char by using `map` instead of `each`:

```
$<.map{|w|w*5=~/a.*e.*i.*o.*u/m&&p(w)}

```

Another version, 39 characters with prettier output:

```
puts$<.select{|w|w*5=~/a.*e.*i.*o.*u/m}

```

Both programs take input from stdin or as a file name passed as a command line argument:
`$ ruby wovels.rb wordlist.txt`

It costs 3 extra characters to inclyde `y` as a wovel.
> 2 votes

# Answer
# Perl 6 - 35 characters

Inspired by @CarySwoveland 's Ruby solution:

```
say grep <a e i o u y>⊆*.comb,lines

```

This selects (`grep`s) each line that returns `True` for `<a e i o u y> ⊆ *.comb`, which is just a fancy way of asking "is the Set `('a','e','i','o','u','y')` a subset () of the Set made up of the letters of the input (`*.comb`)?"

Actually, both `<a e i o u y>` and `*.comb` only create `List`s:  (or `(<=)` if you're stuck in ASCII) turns them into `Set`s for you.

To get the number of lines printed, this **42 character - 5 = 37 point** script will output that as well:

```
say +lines.grep(<a e i o u y>⊆*.comb)».say

```
> 2 votes

# Answer
## C - 96 bytes

```
 char*gets(),*i,j[42];main(p){while(p=0,i=gets(j)){while(*i)p|=1<<*i++-96;~p&35684898||puts(j);}}

```

I saved several bytes of parentheses thanks to a fortunate coincidence of operator precedence.
> 2 votes

# Answer
## Bash (grep) - 36 bytes

```
g=grep;$g y|$g u|$g o|$g i|$g a|$g e

```

Note the order of vowels tested, least frequent first. For the test case, this runs about 3 times as fast as testing in order a e i o u y. That way the first test removes a larger number of words so subsequent tests have less work to do. Obviously this has no effect on the length of the code. Many of the other solutions posted here would benefit similarly from doing the tests in this order.
> 2 votes

# Answer
# Bash + coreutils, 39

```
eval cat`printf "|grep %s" a e i o u y`

```

Takes input from stdin.
> 2 votes

# Answer
### sed 29 chars

```
/y/{/u/{/o/{/i/{/a/{/e/p}}}}}

```

Order choosed from Letter frequency on wikipedia to speed check.

On my host:

```
time sed -ne '/a/{/e/{/i/{/o/{/u/{/y/p}}}}}' </usr/share/dict/american-english >/dev/null
real    0m0.046s

```

and

```
time sed -ne '/y/{/u/{/i/{/o/{/a/{/e/p}}}}}'</usr/share/dict/american-english >/dev/null
real    0m0.030s

```
> 2 votes

# Answer
# JavaScript - 95 bytes

Here's my golf.

```
function f(s){return[var a=s.match(/^(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*/),a.length];}

```

And I would also like to point out that your golf doesn't seem to find all occurrences of vowels.

Ungolfed:

```
function countVowels(string) {
  var regex   = /^(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*/;
  var matches = string.match(regex);
  var length  = matches.length;
  return [matches, length];

```
> 1 votes

# Answer
## D - 196

```
import std.regex,std.stream;void main(string[]a){auto f=new File(a[1]);while(!f.eof)if(!(a[0]=f.readLine.idup).match("(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*").empty)std.stdio.writeln(a[0]);}

```

**Un-golfed**:

```
import std.regex, std.stream;

void main( string[] a )
{
    auto f = new File( a[1] );

    while( !f.eof )
        if( !( a[0] = f.readLine.idup ).match( "(?=.*a)(?=.*e)(?=.*i)(?=.*o)(?=.*u)(?=.*y).*" ).empty )
            std.stdio.writeln( a[0] );
}

```

**Usage**: `C:\>rdmd vowels.d wordlist.txt`

`wordlist.txt` must contain the lowercase list words.
> 1 votes

# Answer
# Rebol (104 chars)

```
remove-each w d: read/lines %wordlist.txt[6 != length? collect[foreach n"aeiouy"[if find w n[keep n]]]]

```

### Un-golfed:

```
remove-each w d: read/lines %wordlist.txt [
    6 != length? collect [foreach n "aeiouy" [if find w n [keep n]]]
]

```

`d` now contains list of found words. Here is an example from Rebol console:

```
>> ; paste in golf line.  This (REMOVE-EACH) returns the numbers of words removed from list

>> remove-each w d: read/lines %wordlist.txt[6 != length? collect[foreach n"aeiouy"[if find w n[keep n]]]]
== 58067

>> length? d
== 43

```
> 1 votes

# Answer
# Bash

Not as short as the OP's , but one line in Bash:

```
while read p; do if [ $(sed 's/[^aeiouy]//g' <<< $p | fold -w1 | sort | uniq | wc -l) -eq 6 ] ; then echo $p; fi; done < wordlist.txt

```
> 1 votes

# Answer
# sort + uniq + sed

This one does not match repeated occurrences of a word. It also does not match the letter 'y' if is occurs at the beginning of a word.

```
sort wordlist.txt | uniq | sed -n '/a/p' | sed -n '/e/p' | sed -n '/i/p' | sed -n '/o/p' | sed -n '/u/p' | sed -nr '/^[^y]+y/p'

```
> 1 votes

# Answer
# Smalltalk (36/57 chars)

```
'corncob_lowercase.txt' asFilename contents select:[:w | w includesAll:'aeiouy']

```

to get the count, send #size to the resulting collection. The result collection contains 43 words ('abstemiously' 'authoritatively' ... 'unquestionably' 'unrecognisably')

The code above has 77 chars, but I could have renamed the wordlist file to 'w', so I count the filename as 1 which gives a score of 57.

Is reading the file part of the problem or not? If not (see other examples), and the list of words is already in a collection c, then the code reduces to:

```
c select:[:w | w includesAll:'aeiouy']

```

which is 36 chars (with omittable whitespace removed).
> 1 votes

# Answer
updated: unnecessary spaces removed

Very slow but in bash (81 chars):

```
while read l;do [ `fold -w1<<<$l|sort -u|tr -dc ieaouy|wc -m` = 6 ]&&echo $l;done

```

EDIT: `echo $l|fold -w1` replaced with `fold -w1<<<$l` as suggested by @nyuszika7h
> 1 votes

# Answer
# Mathematica - ~~136~~ 102

```
Fold[Flatten@StringCases@## &,
Flatten@Import@"http://bit.ly/1iZE9kY",
___ ~~ # ~~ ___ & /@ Characters@"aeiouy"]

```

The shortened link goes to http://www.mieliestronk.com/corncob\_lowercase.txt
> 1 votes

# Answer
## C-Sharp

I've never done this before and I'm not exactly sure what the posting procedures are. But this is what i came up with:

## 185 bytes

```
Action<string>x=(s=>s.Split('\n').ToList().ForEach(w=>{if("aeiouy".All(v=>w.Contains(v)))Console.Write(w);}));using(var s=new StreamReader(@"C:\corncob_lowercase.txt"))x(s.ReadToEnd());

```

`wordList` = a `List<string>` of all the words.

if you want to display a total:

## 219 - 5 = 214 bytes

```
Action<string>x=(s=>{var t=0;s.Split('\n').ToList().ForEach(w=>{if("aeiouy".All(v=>w.Contains(v))){Console.Write(w);t++;}});Console.Write(t);});using(var s=new StreamReader(@"C:\corncob_lowercase.txt"))x(s.ReadToEnd());

```

---

**Expanded**
```
// init
var words = "";
var vowels = "aeiouy";
var total = 0;

using (var stream = new StreamReader(@"C:\corncob_lowercase.txt"))
{
    // read file
    words = stream.ReadToEnd();

    // convert word to List<string>
    var wordList = words.Split('\n').ToList();

    // loop through each word in the list
    foreach (var word in wordList)

        // check if the current word contains all the vowels
        if(vowels.All (w => word.ToCharArray().Contains(w)))
        {
            // Count total
            total += 1;
            // Output word
            Console.Write(word);
        }

    // Display total
    Console.WriteLine(total);
}

```
> 1 votes

# Answer
# C# - 170

```
using System.Linq;class P{static void Main(string[]a){System.Console.Write(string.Join(",",System.IO.File.ReadAllLines(a[0]).Where(w=>"aeiouy".All(c=>w.Contains(c)))));}}

```

Formatted:

```
using System.Linq;
class P
{
    static void Main(string[] a) {
        System.Console.Write(
            string.Join(",", System.IO.File.ReadAllLines(a[0])
                .Where(w => "aeiouy".All(c => w.Contains(c)))));
    }
}

```

~~Not in the mood right now to implement counting but should be easy.~~ The path to the (lower-case version of the) wordlist should be passed to the program as first argument:

```
program.exe D:\foo\bar\corncob_lowercase.txt

```

**Output:**

```
abstemiously,authoritatively,behaviourally,consequentially,counterrevolutionary,
disadvantageously,educationally,encouragingly,eukaryotic,evolutionarily,evolutio
nary,exclusionary,facetiously,gregariously,heterosexuality,homosexuality,importu
nately,inconsequentially,instantaneously,insurrectionary,intravenously,manoeuvra
bility,neurologically,neurotically,ostentatiously,pertinaciously,precariously,pr
ecautionary,questionably,revolutionary,simultaneously,supersonically,tenaciously
,uncomplimentary,uncontroversially,unconventionally,undemocratically,unemotional
ly,unequivocally,uninformatively,unintentionally,unquestionably,unrecognisably

```

I took the liberty of outputting and comma-separating the words; neither of which is specified in the rules (which state "must find all the words", not how (and IF) to output).

## Including count (+output): 192 - 5 = 187

```
using System.Linq;class P{static void Main(string[]a){var r=System.IO.File.ReadAllLines(a[0]).Where(w=>"aeiouy".All(c=>w.Contains(c)));System.Console.Write(string.Join(",",r)+" "+r.Count());}}

```

Output:

```
abstemiously,authoritatively,behaviourally,consequentially,counterrevolutionary,
disadvantageously,educationally,encouragingly,eukaryotic,evolutionarily,evolutio
nary,exclusionary,facetiously,gregariously,heterosexuality,homosexuality,importu
nately,inconsequentially,instantaneously,insurrectionary,intravenously,manoeuvra
bility,neurologically,neurotically,ostentatiously,pertinaciously,precariously,pr
ecautionary,questionably,revolutionary,simultaneously,supersonically,tenaciously
,uncomplimentary,uncontroversially,unconventionally,undemocratically,unemotional
ly,unequivocally,uninformatively,unintentionally,unquestionably,unrecognisably 4
3

```

(Note the count at the end: 43)

## No output ("must *find* all the words"): 137 - 5 = 132

```
using System.Linq;class P{static void Main(string[]a){var r=System.IO.File.ReadAllLines(a[0]).Where(w=>"aeiouy".All(c=>w.Contains(c)));}}

```

(Bending the rules a bitm then again: not really) This **finds** all the words and the count is available by executing `r.Count()`.
> 1 votes

# Answer
**vb.net** (Score 91 = 96c - 5)<sub>*<sub>0</sub></sub>

<sub>*<sub>0</sub> +49c min</sub>

This creates an enumeration contain all of the words which contain all of the vowels.

```
Dim r=IO.File.ReadLines(a(0)).Where(Function(w)"aeiou".Intersect(w).Count=5)
Dim c=r.Count

```
> 1 votes

# Answer
## Batch - 52 Bytes

if you're not worried about the original word list -

```
@for %%a in (a e i o u)do @find "%%a" %1>f&type f>%1

```

This outputs the new list to a file called `f`, preserving the original word list - 66 bytes -

```
@type %1>f&for %%a in (a e i o u)do @find "%%a" f>f%%a&type f%%a>f

```

If you want it to clean up the files it leaves around, just add `&del f%%a` to the end for an extra 9 bytes.

Takes list of words as input.

```
H:\uprof>vowles.bat wordlist.txt

```

**Old solution - 162 Bytes**

```
@echo off&setLocal enableDelayedExpansion&for /f %%a in (%1) do (set a=%%a&set t=&for %%b in (a e i o u) do if "!a:%%b=!"=="!a!" set t=1)&if "!t!" NEQ "1" echo %%a

```
> 0 votes

# Answer
# JavaScript - 118 bytes

```
function(a){r=[];for(k in a=a.split("\n")){c=0;for(b in s="aeiouy")c+=!!~a[k].search(s[b]);c>5&&r.push(a[k])}return r}

```

Paste this into the console to test it:

```
(function(a){r=[];for(k in a=a.split("\n")){c=0;for(b in s="aeiouy")c+=!!~a[k].search(s[b]);c>5&&r.push(a[k])}return r})(document.getElementsByTagName('pre')[0].innerText)

```
> 0 votes

# Answer
## Bash (sed) - 36 bytes

```
s=/!d\;;sed /y$s/u$s/o$s/i$s/a$s/e$s

```

As in my bash (grep) solution, I changed the order of tests to make the job run about 40 percent faster for the given input file.
> 0 votes

# Answer
### Pure bash 86 chars

```
t=aeuoiy;while read w;do v=${w,,};r=${v//*([^$t])};[ "${t//*([$r])}" ] || echo $w;done

```

Demo:

```
t=aeuoiy
while read w;do
    v=${w,,}
    r=${v//*([^$t])}
    [ "${t//*([$r])}" ] || echo $w
  done < /usr/share/dict/american-english
Aureomycin
Aureomycin's
Byelorussia
Byelorussia's
ambidextrously
authoritatively
...

```
> 0 votes

# Answer
# Javascript (ES6) - 60 - 5 (Bonus) = 55 Characters

```
x.filter(s=>s.replace(/[^AEIOUY]|(.)(?=.*\1)/g,'').length>5)

```

Assumes the variable `x` contains an array of upper-case words.

Filters the array to find all the strings when if you replace all non-vowels and duplicate characters it has a length greater than 5.

\[Counting the bonus -5 as Firefox (which is the only browser to support ES6 arrow function syntax) outputs the result of an expression in the console and will output the length property of an array alongside all the elements.\]

**An aside**

To get the word list into a JavaScript array format:

* Save the upper-case file linked in the question as `Words.txt`
* run `gawk -F: '{ print "\"" $1 "\"," }' Words.txt > Words2.txt` to add surrounding quotes and trailing commas to each line.
* Open `Words2.txt` and manually add `x=[` before the first line and replace the comma on the last line with a closing bracket `]`.
* Then you can copy/paste the entire thing into the firefox console (it might take a while to generate a 58,000 row array but it managed it for me).
> 0 votes

# Answer
# Perl command line - 45 - 5 = 40

```
perl -ne 'print if /a/&/e/&/i/&/o/&/u/&/y/;' wordlist.txt

```

It's 45 characters not including the file name, and I think it qualifies for the bonus. Fairly readable as well. :)

Nice question!
> 0 votes

# Answer
# Python 65 bytes

```
def count(word): return False not in [j in word for j in 'aeiou']

```
> 0 votes

# Answer
## C# (49c)

Getting the file lines will be the hard to golf aspect of the challenge for C#.

```
var r=l.Where(w=>"aeiou".Intersect(w).Count==5);

```

This will be an enumeration of all the words containing all the vowels.

Just wanting the count then use.

```
var r=l.Count(w=>"aeiou".Intersect(w).Count==5);

```
> 0 votes

# Answer
# Go - 186 (or 215)

Go's not much for code golf. (The designers like explicit code, and, heck, we're talking about a language where standard style is usually `gofmt`-enforced.) Nonetheless, 186 decidedly unidiomatic bytes:

```
package main
import (."bufio"
."os")
func main(){f:=NewReader(Stdin)
for{l,d:=f.ReadBytes(13)
s,n:=0,17842449
for _,c:=range l{s|=1<<(c-97)}
if s&n==n{Stdout.Write(l)}
if d!=nil{break}}}

```

Some \n's could be ;'s, but it wouldn't affect the byte count. You can see a formatted version.

I sort of like this variant, though, which is longer, but just reads bytes from stdin without even having line splitting done for it (formatted):

```
package main
import ."os"
func main(){var b,w[1024]byte
s,i,m:=0,0,17842449
for{n,e:=Stdin.Read(b[:])
for _,c:=range b[:n]{s|=1<<(c-97)
w[i]=c
i++
if c==13{if s&m==m{Stdout.Write(w[:i])}
s,i=0,0}}
if e!=nil{break}}}

```
> 0 votes

# Answer
# Python

```
file = open('wordlist.txt', 'r')
for word in file:
    if 'a|e|i|o|u' in word:
        print(word)

```
> -1 votes

---
Tags: code-challenge, natural-language
---


title: Alphanumeric Hello World

text:
# Question
Title: Alphanumeric Hello World
Your goal is to write "Hello, World!" (minus the quotes). This is a , so most up votes wins. Code length will be used to break ties.
Anything goes, as long as it is within the following rules:

* All characters must be either letters or numbers, so you may only use characters in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".
* All code you use must be in one file, with the exception of imported modules/classes/whatever they're called in your favourite language.
* Only the standard libraries/frameworks for your language of choice are allowed (for example, Python's Math module is allowed, but Numpy, Scipy, and Pygame are not). I will allow TkInter as it is the de facto standard for GUIs in Python.
* No input is permitted, be it reading from stdin, reading a file, displying an image, or reading from the web.

+10 brownie points if you figure out how to do it in Java without bending the rules.

---

On your marks, get set, code!

EDIT: braces ({}), brackets (\[\]), and parentheses (()) are allowed as this would be pretty much impossible for most languages without them. I'm also removing the character limit rule. Hopefully this will make it more interesting.

EDIT^2: white space is also allowed. My brain isn't working properly, sorry. \>.\<

# Answer
> 105 votes
# Perl

Some say perl is a language full of ascii noise and random symbols like `$`... That is not true :P

```
s zzHelloq worldmz and s zqzchr 44ze and s zmzchr 33ze and print

```

> Let's break this up into subexpressions:
>
> ```
> (s zzHelloq worldmz) and (s zqzchr 44ze) and (s zmzchr 33ze) and (print)
> ```
> It should be obvious that it executes from left to right as long as every expression returns true. But what on earth is `s zqzchr 44ze`?
>
> In perl, there is a group of "quote-like operators" which includes `q(str)`, `qw(li st)`, `/regex/`, `s/from/to/` among other things. It turns out all of these operators can use almost any character as a delimeter, with a couple pecularities: opening parethesis has to be closed by a matching closing parenthesis, and if you wish to **use a letter as a delimiter** you have to put a space after the operator letter (to disambiguate it from a bareword).
>
> In this case we see three uses of the `s///` (regex substitution) operator:
>
> ```
> s//Helloq worldm/
> s/q/chr 44/e
> s/m/chr 33/e
> ```
> All delimited by the character `z`. The `/e` flag on the last two causes the substitution to be interpreted as code to be evaluated, rather literal text.
>
> A fairly well-known fact about perl is that most operations default to operating on the `$_` builtin variable unless otherwise specified. All these three substitutions and the `print` operate on `$_` in this case, so first we put the words Hello world into the variable, then we fix the punctuation by using the numeric ascii values of the characters, then we print the contents of the variable.

# Answer
> 77 votes
# C

```
int main(void) {
  if (putchar(72))
    if (putchar(101))
      if (putchar(putchar(108)))
        if (putchar(111))
          if (putchar(44))
            if (putchar(32))
              if (putchar(87))
                if (putchar(111))
                  if (putchar(114))
                    if (putchar(108))
                      if (putchar(100))
                        if (putchar(33))
                        {
                        }
}

```

# Answer
> 50 votes
(edit - BBC basic moved to separate answer as suggested. Most of the votes on this are definitely for the LOGO answer.)

# LOGO

Interpreter at http://www.calormen.com/jslogo/#

```
TO h        pd  fd 100 rt  90  pu  fd 50  rt 90  pd  fd 100  rt 180 fd 50  lt 90  fd 50  rt 90  pu END
TO e        pu  fd 25  rt  90  pd  fd 25  rt 90  arc 270 25  lt 90  fd 25  lt 90  pu END
TO l        pd  fd 100 pu  END
TO o        rt  45 fd  35  pd  arc 360 25  lt  45  pu END
TO comma    pd  rt 90  arc 90  15  lt  90  pu END
TO w         l  rt 180 l   pd  lt  135 fd  35  rt  90  fd 35  lt 135  l  END
TO r        pd  fd 25  rt  90  pu  fd  25  rt 180  arc 180 25 rt 90 END
TO d         o  rt 135 fd  35  lt  135  l  END
TO exclaim arc 360 5   fd  10  l  END

clearscreen
setpencolor 4 pu
setxy 0 150      h
setxy 100 150    e
setxy 200 150    l
setxy 250 150    l
setxy 300 150    o
setxy 350 150    comma
setpencolor 1
setxy 0 0        w
setxy 100 0      o
setxy 200 0      r
setxy 300 0      l
setxy 350 0      d
setxy 450 0      exclaim
fd 100

```

Output (the green triangle is the turtle cursor)

# Answer
> 31 votes
# Applescript

No brackets `[]`, braces `{}` or parentheses `()` at all in this one:

```
set s to ASCII character 72
set s to s as list
set end of s to ASCII character 101
set end of s to ASCII character 108
set end of s to end of s
set end of s to ASCII character 111
set end of s to ASCII character 44
set end of s to space
set end of s to ASCII character 87
set end of s to item 5 of s
set end of s to ASCII character 114
set end of s to third item of s
set end of s to ASCII character 100
set end of s to ASCII character 33
display dialog s as text

```

Output is:

# Answer
> 26 votes
# Bash

This sort of works, if you squint your eyes:

```
echo NN i NN i i i iNN NNi i i i i i i NN i NN i i i i i i i NNi i i NN NN
echo NN i NNi i i i NN NN i i i i i i iNN i NN i i i i i i i NN i i iNN NN
echo NN i NN iNNNNi NN NN iNNNNi i i i NN i NN iNNNNi NN NN iNN iNNN NN NN
echo NNNNNNN NN iNN NN NN NN iNN i i i NN i NN NN iNN NNN iN NN NN iNNN N
echo NN i NN NNNNNN NN NN NNi NN i i i NN N NN NNi NN NN i i NN NNi iNN N
echo NN i NN NN i i NN NN NN iNN i i i NNN NNN NN iNN NN i i NN NN i NN
echo NN i NN iNNNi iNN NN iNNNNi N i i NN i NN iNNNNi NN i i NN iNNNN N NN
echo i i i i i i i i i i i i i i N

```

# Answer
> 22 votes
## base64

```
SGVsbG8sIFdvcmxkIQ

```

Satisfies the original rules.

# Answer
> 22 votes
## Python

So what, we just assume everybody reads horizontally? For those users who like to read vertically:

```
print chr(72)
print chr(101)
print chr(108)
print chr(108)
print chr(111)
print chr(44)
print chr(32)
print chr(87)
print chr(111)
print chr(114)
print chr(108)
print chr(100)
print chr(33)

```

# Answer
> 21 votes
# Polyglot: HQ9+, H9+, HQ9++, CHIQRSX9+, HQ9+B and HQ9+2D (1 byte)

```
H

```

Thank you @victor for the list of languages.

# Answer
> 21 votes
## COBOL

```
   ID DIVISION
   DATA DIVISION
   01  HELLOWORLDBINARY
       05  HE                       COMP    PIC 9999
       05  LL                       COMP    PIC 9999
       05  OCOMMA                   COMP    PIC 9999
       05  SPACEW                   COMP    PIC 9999
       05  ORTEXT                   COMP    PIC 9999
       05  LD                       COMP    PIC 9999
       05  EXCLAMATION              COMP    PIC 9999
   01  FILLER REDEFINES HELLOWORLDBINARY
       05  HELLOWORLDTEXT                   PIC XXXXXXXXXXXXX
       05  FILLER                           PIC X
   PROCEDURE DIVISION
       MOVE 51333                   TO HE
       MOVE 37779                   TO LL
       MOVE 38507                   TO OCOMMA
       MOVE 16614                   TO SPACEW
       MOVE 38553                   TO ORTEXT
       MOVE 37764                   TO LD
       MOVE 23104                   TO EXCLAMATION
       DISPLAY HELLOWORLDTEXT
       GOBACK

```

Required some changes to become truly alphanumeric source only.

PROGRAM-ID can be dropped. You get a generated program name (see messages).

WORKING-STORAGE can be dropped. Again the compiler moans.

Since both of these lines previously had missing full-stops/periods, which are no longer relevant now that the descriptions are entirely missing, the number of error messages is the same as before, and still does not affect the generated code for the program.

In changing COMP-5 to COMP, the VALUE clauses are no longer allowed, as COMP 9999 is only four decimal digits whereas COMP-5 is a two-byte binary with all bit-values available.

The values in the MOVEs are the decimal values which give the binary values which give the pairs of characters.

Even though the COMP fields have four digits, and do not allow VALUE clauses with more than four digits, you can use more digits in the MOVE of a literal value without truncation at that point... don't ask me why. Compiler option DIAGTRUNC (which I have turned off) will produce Warning diagnostics for these.

Compiler option TRUNC(BIN) could be used to treat COMP as COMP-5, but the MOVEs are another way to do it.

Since it is COBOL, the output must be in UPPER CASE (a lie, but just for fun).

```
HELLO WORLD!

```

OK, relented, now produces:

```
Hello, World!

```

Which, being an odd-number of characters, required some further changes, since we can't have odd-number-byte binary fields with this compiler. Look at that line of 13 Xs! It would normally be written as X(13), but can be as I've shown...

And ORTEXT is needed (or not OR, anyway) as a name because OR is a reserved word to the compiler (it means OR, of course).

These are EBCDIC values, not ASCII, since it is running on an EBCDIC-aware, and Big Endian, box.

Oh, COBOL requires lots of full-stops/periods. I left them out (they're banned) so got lots of compile messages. Just told the compiler to generate the code anyway (none of the messages relate to the object code).

Even without DIAGTRUNC, the messages are now up to 17...

```
  1  IGYDS1003-E   A "PROGRAM-ID" paragraph was not found.
  Program-name "CBLNAM01" was assumed.

  2  IGYDS1082-E   A period was required.  A period was assumed
  before "DATA".

  3  IGYDS1082-E   A period was required.  A period was assumed
  before "01".

                   Same message on line:     11

  3  IGYDS1040-E   A data item was found in the "DATA DIVISION"
                   before a section header was encountered.
                   "WORKING-STORAGE SECTION" was assumed.

  4  IGYDS1082-E   A period was required.  A period was assumed
  before "05".

                   Same message on line:      5      6      7      8
                   9     10     12     13

 14  IGYDS1082-E   A period was required.  A period was assumed
 before "PROCEDURE".

 15  IGYPS2145-E   A period was required.  A period was assumed
 before "MOVE".

 23  IGYSC1082-E   A period was required.  A period was assumed
 before "END OF PROGRAM".

```

# Answer
> 21 votes
# OMGROFL

I'm a big fan of esoteric languages. Luckily OMGROFL is alphanumeric:

```
lol iz 72
rofl lol
lol iz 101
rofl lol
lol iz 108
rofl lol
rofl lol
lool iz 111
rofl lool
loool iz 44
rofl loool
loool iz 32
rofl loool
loool iz 87
rofl loool
rofl lool
lool iz 114
rofl lool
rofl lol
lol iz 100
rofl lol
lol iz 33
rofl lol
stfu

```

The `iz` command sets a value to a variable, in this case `lol`, `lool` and `loool` serve as variables...

The `rofl` command echoes out the ASCII equivalent to the number stored in the variable.

The `stfu` command terminates the program ;)

# Answer
> 19 votes
# Javascript

```
with (function SGVsbG8sIFdvcmxkIQ(){}) atob(name)

```

Use browser's console to test.

# Answer
> 15 votes
# Ruby (using only alnums and whitespace)

```
putc 72
putc 101
putc 108
putc 108
putc 111
putc 44
putc 32
putc 87
putc 111
putc 114
putc 108
putc 100
putc 33

```

Output: `Hello, World!`

# Answer
> 15 votes
# JavaScript

```
with (String) with ([]) {
    push(fromCharCode(72))
    push(fromCharCode(101))
    push(fromCharCode(108))
    push(fromCharCode(108))
    push(fromCharCode(111))
    push(fromCharCode(44))
    push(fromCharCode(32))
    push(fromCharCode(87))
    push(fromCharCode(111))
    push(fromCharCode(114))
    push(fromCharCode(108))
    push(fromCharCode(100))
    push(fromCharCode(33))
    alert(join([]))
}

```

# Answer
> 13 votes
**C**

Uses only alphanumeric characters, spaces and braces {}, brackets \[\] and parenthesis ().

```
main()
{
        if(printf((long long []){0x202c6f6c6c6548}))
                if(printf((long long []){0x21646c726f57})){}
}

```

printf( ) accepts a char * as an argument, but since we can't use quotes("), I typecast the string as a long long array. The values seen here are ASCII strings, in little endian (0x48=H, 0x65=e, 0x6c=l, and so on). I typecast it to long long \[\] since that way I can pass an 8-byte argument and hence use only two printf( ) calls instead of four.

# Answer
> 12 votes
# ferNANDo

```
h E R
e I S
h E
l L O
w O
r L
d U S
i N G
o N L
y L E
t T E
r S

H e L L o W O R
L d h E L l O w
O r l D h e L L
O w o R l d H E
L l o W o r l d
H E l L o w O R
L D h E L L O W
O r L d H e l l
O w o R l d h e
L l o w O R l D
H e l L o w O R
L d h E L l O W
O R l D H E L l
O w O
r L d

```

# Answer
> 12 votes
# BBC BASIC

Emulator at bbcbasic.co.uk

Split from my LOGO answer.

**The easy way**

The numbers on the right are just ASCII codes. This is just the same as printing. If I was allowed a comma I could do it on a single line (`VDU 72,101,108,etc.`)

```
   10 VDU 72
   20 VDU 101
   30 VDU 108
   40 VDU 108
   50 VDU 111
   55 VDU 44
   60 VDU 32
   70 VDU 87
   80 VDU 111
   90 VDU 114
  100 VDU 108
  110 VDU 100
  120 VDU 33

```

**A more creative way**

```
    5 MODE 6
   10 READ B
   12 WHILE B
   15   PROC1(B)
   16   PRINT
   17   READ B
   18 ENDWHILE
   20 END

REM procedure prints first square on line,
REM then calls itself recursively with A DIV 2 to print the next
REM VDU 17 tell VDU controller we want to change colour
REM Next line changes background colour.
REM Then following line VDU 32 prints a space in that background colour.

  110 DEFPROC1(A)
  115 VDU 17
  120 IF A AND 1 THEN VDU VPOS DIV 6 EOR 133 ELSE VDU 128
  125 VDU 32
  130 IF A THEN PROC1(A DIV2)
  140 ENDPROC

REM binary bitmap data for each row, least significant at left
  150 DATA 463221
  160 DATA 332053
  170 DATA 332151
  180 DATA 332053
  190 DATA 2586485
  200 DATA 1048576
  210 DATA 4395895
  220 DATA 4527447
  230 DATA 4526935
  240 DATA 333143
  250 DATA 4420981
  260 DATA 0

```

# Answer
> 12 votes
# Rebol

Alphanumeric only solution:

```
prin quote Hello prin add space 12 prin space prin quote World print add space 1

```

Above is an update which uses Dr Rebmu excellent suggestion of `add space 1` (which produces `!`) to get to all the characters.

Below is the original version:

```
prin quote Hello prin pick mold system 264 prin space prin quote World print pick mold system 12

```

Shorter version with brackets:

```
print rejoin [quote Hello pick mold system 264 space quote World pick mold system 12]

```

And even shorter version with braces:

```
print join {Hello} join pick mold system 264 join { World} pick mold system 12

```

And shortest version with both brackets & braces:

```
print rejoin [{Hello} pick mold system 264 { World} pick mold system 12]

```

Rebol uses braces `{}` for multi-line quoting. So completely valid under rule changes but not quite in full spirit (IMHO) as my first two answers above.

NB. Printing the `!` was a pain!

Rebol allows and uses punctuation characters routinely for function names and datatypes. So options like `to-char 33` or `to char! 33` would not be allowed under the rules (even though these punctuations are not operators par se).

Fortunately I found a cheeky way by turning the Rebol system object: `make object! [...]` into a string and cherry pick that `!` from it :)

Update: And now also cherry picked comma from license text in system object.

# Answer
> 12 votes
# JavaScript!

And they said that it couldn't be done... No assignment operators, no concatenators, no quotes! Arghhhh!

Fear not... For the force is `with` you...

```
function w(x){
    with(document){
        with(String){
            write(fromCharCode(x))
        }
    }
}
w(72)
w(101)
w(108)
w(108)
w(111)
w(44)
w(32)
w(87)
w(111)
w(114)
w(108)
w(100)
w(33)

Output (on browser screen): Hello, World!

```

# Answer
> 12 votes
# DC

DC is just about the perfect tool for the job.

```
5735816763073854918203775149089P

```

DCs `P`-command pops one number from the stack and outputs its raw computer representation to STDIO. Seeing as `5735816763073854918203775149089 = 0x48656C6C6F2C20576F726C6421`, which is represented as `0x21, 0x64, 0x6C... = 'H', 'e', 'l'...` in a little-endian architecture, it outputs `Hello, World!`.

# Answer
> 11 votes
## Mathematica

```
Unprotect[Times]
ClearAll[Times]
Print[Hello FromCharacterCode[44] world FromCharacterCode[33]]

```

# Answer
> 11 votes
## Javascript

*Update:* Managed to cut a bunch of characters by introducing a World function as well.

Another Javascript solution that writes to console.log:

```
function World() { with (World) return name }
function Hello() {}
with (console)
with (String)
with (Hello)
with (name)
with (concat(fromCharCode(44)))
with (concat(fromCharCode(32)))
with (concat(World()))
log(concat(fromCharCode(33)))

```

Inspired by this entry.

First, I define functions named Hello and World. This will be used later on.

Then I start my chain of nested withs. The `with (console)` and `with (String)` are used so that I can later on invoke `console.log` and `String.fromCharCode` without using a dot.

The plan is now to build the string `Hello, World!` by abusing nested withs. Each time I invoked concat(), the resulting string will be the context in the next with-block. I take a short cut to quickly get `"Hello"` by accessing the `name` property of the `Hello` function. Then I concatenate the comma and space characters by using `String.fromCharCode`.

The next trick is to get the `"World"` part of the string. I cannot use the same method I used to get `Hello`, since I cannot invoke World.name. Instead I put that logic inside the World method, and invoke it.

Finally, I append the final exclamation mark and send the result right to the log function, which is of course console.log.

# Answer
> 10 votes
# Python:

```
import antigravity

```

causes "Hello, world!" to appear on your screen. Don't believe me? Try it out for yourself! Also, this doesn't actually use the web, it opens a browser, that might lookup a website.

# Answer
> 7 votes
# Perl

In a modern Perl (5.10 or newer):

```
print q{Hello} and print chr 44 and print q{ World} and say chr 33

```

In older Perl:

```
print q{Hello} and print chr 44 and print q{ World} and print chr 33 and print chr 10

```

Both solutions above use Perl `q` quote-like operator and allows selective delimiters for quoting a string, for eg. `q{}` `q[]` `q()` `q//`

This solution requires the rule change that allows braces, brackets or parens. So while totally valid I think `mniip` excellent Perl answer is more in the true spirit of the rules (+1).

However taking a leaf out of `mniip` answer my solution could be written like so:

```
print q xHellox and print chr 44 and print q x Worldx and say chr 33

```

and while harder on the eye it does work.

# Answer
> 7 votes
# Perl

```
print chr hex for qw z48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21z

```

# Answer
> 5 votes
# dc, (26 bytes for the golfers)

Whitespace and `[]` brackets are now allowed:

```
[Hello]n44P[ World]n33P[]p

```

Output:

```
$ dc <<< "[Hello]n44P[ World]n33P[]p"
Hello, World!
$

```

# Answer
> 5 votes
# Python:

Pfff, who needs the numeric part of alphanumeric?

```
from string import lowercase
from string import uppercase
from string import punctuation
print uppercase[len(str([[[len(str())]]]))]
print lowercase[len(str([[]]))]
print lowercase[len(str([[[[[len(str())]]]]]))]
print lowercase[len(str([[[[[len(str())]]]]]))]
print lowercase[len(str([[[[[[[]]]]]]]))]
print punctuation[len(str([[[[[len(str())]]]]]))]
print
print uppercase[len(str([[[[[[[[[[[]]]]]]]]]]]))]
print lowercase[len(str([[[[[[[]]]]]]]))]
print lowercase[len(str([[[[[[[[len(str())]]]]]]]]))]
print lowercase[len(str([[[[[len(str())]]]]]))]
print lowercase[len(str([len(str())]))]
print punctuation[len(str())]

```

This is locale-dependant, so your milage may vary. However, if you really want to replicate this result, you could use the following instead of the import statements:

```
lowercase="abcdefghijklmnopqrstuvwxyz"
uppercase="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
punctuation="!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"

```

(this is not part of my submission, it's just sharing my locals for recreatability)

# Answer
> 5 votes
## Rebmu, 46 characters

```
pnUPPqHELLO01pnADsp12pnSPpnUPPqWORLD01pnADsp01

```

Strongly parallels @dragetun's solution in Rebol *(Because Rebmu is a Rebol/Red teaching tool which is a "dialect" that aims to draw attention to the languages by rocking at Code Golf. :-P)*

However, to get the missing characters, I did something more obvious. I just added to space, instead of going and looking through system strings. You can get **add space 1** to get character literal #"!" and **add space 12** to get character literal #",".

If we run this we can see it get "unmushed":

```
>> rebmu/debug/stats "pnUPPqHELLO01pnADsp12pnSPpnUPPqWORLD01prADsp01"
Original Rebmu string was: 46 characters.
Rebmu as mushed Rebol block molds to: 46 characters.
Unmushed Rebmu molds to: 62 characters.
Executing: [pn upp q hello 1 pn ad sp 12 pn sp pn upp q world 1 pr ad sp 1]
Hello, World!

```

Which is fairly logial:

```
; print with no newline the result of doing an uppercase/part
; on the quoting of the symbolic word hello, of only the first
; N characters (where N is 1)
pn upp q hello 1

; print the character you get when you add 12 to the space
; character literal, a.k.a. comma...again no newline
pn ad sp 12

; print a space, no newline
pn sp

; do the same trick of printing the quoted word hello with the
; first letter converted to uppercase
pn upp q world 1

; print the character you get when you add 1 to the space
; character literal, a.k.a. exclamation point...with newline now
pr ad sp 1

```

# Answer
> 5 votes
# Whitespace

Okay, we can use whitespace. It uses only `Space`, `Tab`, `LineFeed` and ignores any other characters.

```

```

With comment: `S`, `T` or `L` means `Space`, `Tab` or `LineFeed` respectively.

```
S S S T S S T   S S S L
T   L
S S S S S T T   S S T   S T L
T   L
S S S S S T T   S T T   S S L
T   L
S S S S S T T   S T T   S S L
T   L
S S S S S T T   S T T   T   T   L
T   L
S S S S S T S T T   S S L
T   L
S S S S S T S S S S S L
T   L
S S S S S T T   T   S T T   T   L
T   L
S S S S S T T   S T T   T   T   L
T   L
S S S S S T T   T   S S T   S L
T   L
S S S S S T T   S T T   S S L
T   L
S S S S S T T   S S T   S S L
T   L
S S S S S T S S S S T   L
T   L
S S L
L
L

```

With highlighting: http://en.wikipedia.org/wiki/Whitespace\_(programming\_language)#Sample\_code

# Answer
> 4 votes
## T-SQL, 52

Ah, this is better! Direct binary conversion, only 52 characters.

```
SELECT CAST(0x48656C6C6F2C20576F726C6421 AS VARCHAR)

```

**Previously...**

There's a much cleverer and golfier solution to this that would work *if* we could use `=` and `+` (Looking up standard built-in data in msdb and using that to construct an EXEC-able query string)

But since we can't, you get this naive approach:

```
SELECT CHAR(72)SELECT CHAR(101)SELECT CHAR(108)SELECT CHAR(108)SELECT CHAR(111)SELECT CHAR(44)SELECT CHAR(32)SELECT CHAR(87)SELECT CHAR(111)SELECT CHAR(114)SELECT CHAR(108)SELECT CHAR(100)SELECT CHAR(33)

```

# Answer
> 4 votes
# Groovy

So updated. Much `wat`.

```
def wat(i) { print i
  this
}
def wat(int i) { wat i as char }
def getProperty(String p) { p }
wat Hello wat 44 wat 32 wat World wat 33

```

# Answer
> 4 votes
# J - 73 char

It *can* be done, after all!

```
72 101 108 108 111 44 32 87 111 114 108 100 33{do 1 8{show 0 def 0
take
)

```

Here's the thing about J. Most of the primitives are ASCII punctuation, followed by up to two dots or colons. Those primitives that aren't made of punctuation are an alphanumeric character followed up to two dots or colons. So we're allowed none of those, except for `{ } [ ]`. `[` and `]` are identity verbs and are thus useless.

Luckily, `{` indexes arrays, so if we had, say, a string with every single ASCII character (`a.`, called *Alphabet*), we could pull the letters out by their ASCII codepoints. We also have a backup way of making strings, `0 : 0` and then stuff and then a lone `)`; the colon in which has an alias in the standard library, `def`.

Then there's a verb in the standard library, `show`, that gives you the internal representation of a verb if you pass it the name as a string. There's another verb, `do`, that will eval a string. So if we can pull out an `a.` from any such representation, we can eval that and pull out `Hello, World!`.

Our saviour comes in the form of `take`, an alias for `{.` that has an `a` in its name. `show'take'` will return `take=: {.`, so we have our `a.` and thus a solution.

We can get rid of `{` by using the essentially equivalent `pick` from the standard library, but the paren at the very end can't be avoided.

# Answer
> 4 votes
# perl

How about a more straight-forward perl implentation?

```
print q zHelloz and print chr 44 and print q z worldz and print chr 33

```

# Answer
> 4 votes
# GolfScript

```
389960998265612367812323333 115base]zip

```

Try it online.

### How it works

Since both number and square brackets are allowed, pushing an array containing the character codes of all bytes in the string “Hello, World!” is straightforward:

```
[72 101 108 108 111 44 32 87 111 114 108 100 33]

```

The highest character count is 114, so we could also push this array as a base 115 number:

```
389960998265612367812323333 115base

```

The problem lays in casting this array to a string. There's already a string on the stack (the empty string, since there was no input from STDIN). Strings have higher priority than arrays in GolfScript, so any way of combining the empty string with the array from above will yield a string.

Almost all built-ins are out, since they use non-alphanumeric characters (e.g., `+` for concatenation), but we can use `zip`, which transposes array rows with columns.

First, we append a `]` to the array, so a two-dimensional array consisting of the empty string an the character array will lay on the stack.

Then, we append `zip`. The result of the transpose will be the following array:

```
[   "H"   "e"   "l"   "l"   "o"   ","   " "   "W"   "o"   "r"   "l"   "d"   "!"   ]

```

By default, GolfScript prints all item on the stack, one by one. The result is:

```
Hello, World!

```

# Answer
> 3 votes
# GO (golang)

```
package main

func main() {
    print(string(72))
    print(string(101))
    print(string(108))
    print(string(108))
    print(string(111))
    print(string(44))
    print(string(32))
    print(string(87))
    print(string(111))
    print(string(114))
    print(string(108))
    print(string(100))
    print(string(33))
}

```

No "fmt" used... Just print.

# Answer
> 3 votes
## Lua (112)

```
io[ [[write]]][[Hello]]io[ [[write]]](string[ [[char]]](44))io[ [[write]]][[ World]]print(string[ [[char]]](33))

```

Pretty straightforward. Lua's alternate string syntax is quite a boon here, in addition to "the only data structure is a table" which means that `io.write` is equilavent to `io['write']`.

# Answer
> 2 votes
# Haskell

Not exactly a program, as it is impossible to create a program without `main=`. This is simply an expression for an interactive interpreter, such as `ghci`:

```
putStrLn (map toEnum (scanl (const id) 72 (scanl (const id) 101 (scanl (const id) 108 (scanl (const id) 111 (scanl (const id) 44 (scanl (const id) 32 (scanl (const id) 119 (scanl (const id) 111 (scanl (const id) 114 (scanl (const id) 108 (scanl (const id) 100 [33]))))))))))))

```

`scanl (const id)` is used instead of `(:)`,
`toEnum :: a -> Char` is used instead of `chr`, as I'd have to import `Data.Char` then.

# Answer
> 2 votes
## Emacs Lisp

Displays "Hello, World!" in a browser when you eval it.

it's lisp as ascii values of base64 of lisp of base64 of ascii values if you start unobfuscating it.

```
(eval (read (eval (list (intern (string 98 97 115 101 54 52 45 100 101 99 111 100 101 45 115 116 114 105 110 103))
                        (string 75 71 120 108 100 67 65 111 75 71 90 112 98 71 85 103 75 71 86 50 89 87 119 103
                                75 72 74 108 89 87 81 103 75 71 74 104 99 50 85 50 78 67 49 107 90 87 78 118 90
                                71 85 116 99 51 82 121 97 87 53 110 73 67 74 76 83 69 52 119 89 50 49 115 100 86
                                112 53 10 81 84 86 78 97 85 70 52 84 85 82 82 90 48 49 85 81 88 104 74 82 69 86
                                51 84 48 78 66 101 69 49 69 90 50 100 78 86 69 86 52 83 85 82 70 101 69 57 84 81
                                88 104 78 86 69 86 110 84 86 82 70 77 69 108 69 82 88 100 80 81 48 70 52 84 85 82
                                66 10 90 48 49 85 82 88 104 74 82 69 86 52 84 110 108 66 101 69 49 85 87 87 100
                                78 86 69 86 53 83 85 82 70 101 69 53 53 81 88 104 78 86 70 108 110 84 107 82 90
                                90 48 49 85 81 84 66 74 82 69 86 52 84 109 108 66 101 69 49 69 97 50 100 78 86 69
                                69 48 10 83 49 69 57 80 83 73 112 75 83 107 112 75 83 65 111 100 50 108 48 97 67
                                49 48 90 87 49 119 76 87 90 112 98 71 85 103 90 109 108 115 90 83 65 111 97 87 53
                                122 90 88 74 48 73 67 104 108 100 109 70 115 73 67 104 121 90 87 70 107 73 67 104
                                105 89 88 78 108 10 78 106 81 116 90 71 86 106 98 50 82 108 76 88 78 48 99 109 108
                                117 90 121 65 105 83 48 104 79 77 71 78 116 98 72 86 97 101 85 69 121 84 85 78 66
                                101 69 49 69 85 87 100 79 86 69 86 110 84 109 112 74 90 48 53 54 83 87 100 78 86 69
                                70 52 83 85 82 70 10 100 48 57 68 81 88 104 78 82 71 100 110 84 86 82 70 101 69 108
                                69 85 84 66 74 82 69 49 53 83 85 82 110 77 48 108 69 82 88 104 78 85 48 70 52 84 86
                                82 82 90 48 49 85 81 84 82 74 82 69 86 51 84 85 78 66 101 107 49 53 81 84 74 78 81
                                48 69 119 10 84 110 108 66 101 69 49 69 85 87 100 79 86 69 86 110 84 109 112 74 99
                                67 73 112 75 83 107 112 75 83 65 111 89 110 74 118 100 51 78 108 76 88 86 121 98 67
                                49 118 90 105 49 109 97 87 120 108 73 71 90 112 98 71 85 112 73 67 107 103)))))

```

# Answer
> 2 votes
# CJam

One of the few answers satisfying the original requirement for the character set:

```
72c101c108c108c111c44c32c87c111c114c108c100c33c

```

This straightforwardly builds the string character by character.

Another solution:

```
389960998265612367812323333 115b{Xc}fX

```

This converts the first number to base 115 then converts each digit to a character.

And finally, a solution that uses only 3 different characters: K, ) and c (newlines are optional):

```
K))))))))))))))))))))))))))))))))))))))))))))))))))))c
K)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K))))))))))))))))))))))))c
K))))))))))))c
K)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))c
K)))))))))))))c

```

I used K because it's the variable initialized with the largest number (20).

Online interpreter: http://cjam.aditsu.net/

# Answer
> 1 votes
# FORTH

UPDATE: Here's the basically similar version that executed straight from forth file, as opposed to defining a WORD (subroutine) and it uses only alphanumeric characters.

```
72 EMIT
101 EMIT
108 EMIT
108 EMIT
111 EMIT
44 EMIT
32 EMIT
87 EMIT
111 EMIT
114 EMIT
108 EMIT
100 EMIT
33 EMIT

```

been a while with FORTH but this seems to work, thanks for the 'C' language reply I didn't bother looking up ACSII codes. I used the iMop and iBucket (http://sourceforge.net/projects/powermops/files/iMops/) and also tested with an osx variant (https://sites.google.com/site/chrishinsley/)

```
: HELLOWORLD ( -- )
72 EMIT
101 EMIT
108 EMIT
108 EMIT
111 EMIT
44 EMIT
32 EMIT
87 EMIT
111 EMIT
114 EMIT
108 EMIT
100 EMIT
33 EMIT
;

```

code: 224 data: 16

cr HELLOWORLD

Hello, World!

# Answer
> 1 votes
# Python, 148 bytes

```
from binascii import unhexlify
print unhexlify(bytearray(str(0)if c in hex(14)else c for c in hex(0x48656c6c6f2c2e776f726c6421)if c not in hex(0L)))

```

# Answer
> 1 votes
**REXX**

Using standard build-in functions only (ASCII based)

```
  SAY x2c(48656c6c6f2c20576f726c6421)

```

Yields:

> Hello, World!

# Answer
> 1 votes
## PHP - 46 bytes (with invalid underscore)

```
if(print(base64_decode(SGVsbG8sIFdvcmxkIQ))){}

```

## PHP - 88 bytes

```
if(print(Hello))if(print(chr(44)))if(print(chr(32)))if(print(World))if(print(chr(33))){}

```

Works by abusing the fact that PHP will assume any unassigned constant is a string equal to its name.

# Answer
> 1 votes
# Racket

```
(quasiquote (unquote (quote (Hello (unquote (quote World))))))

```

It barely works. The output is `'(Hello ,'world)`

To run this code, start DrRacket and paste the code above to the console.

Don't do it in Advanced Student Language, it shows up `(list 'Hello (list 'unquote (list 'quote 'world)))` instead.

# Answer
> 0 votes
JavaScript:

```
with(String) {
    with(console) {
        log(fromCharCode(72))
        log(fromCharCode(101))
        log(fromCharCode(108))
        log(fromCharCode(108))
        log(fromCharCode(111))
        log(fromCharCode(44))
        log(fromCharCode(32))
        log(fromCharCode(87))
        log(fromCharCode(111))
        log(fromCharCode(114))
        log(fromCharCode(108))
        log(fromCharCode(100))
        log(fromCharCode(33))
    }
}

```

Unfortunately the Firefox console displays this as

> H
> e
> l(2)
> o

etc....

# Answer
> 0 votes
# Java (NetBeans)

```
class Hello extends Exception
{
    Hello(String s)
    {
        super(s)
    }
}

public class HelloWorld
{
    public static void main(String[] args) throws Hello
    {
        world((char)130)
    }

    static void world(char c) throws Hello
    {
        throw new Hello(new String(new char[]{c}))
    }
}

```

Output:

```
Exception in thread "main" Hello: ,
    at HelloWorld.world(HelloWorld.java:18)
    at HelloWorld.main(HelloWorld.java:13)
Java Result: 1

```

A few notes:

1. NetBeans allows you to omit semicolons, but isn't happy about it. Eclipse and `javac` don't compile.
2. I don't get the +10 brownie points, since including unnecessary output is bending (but not violating) the rules.
3. The exclamation point is courtesy of NetBeans, objecting like crazy to the lack of semicolons.

# Answer
> 0 votes
## Lua

```
io[ [[write]]][[Hello]]
io[ [[write]]](string[ [[char]]](44))
io[ [[write]]][[ World]]
io[ [[write]]](string[ [[char]]](33))

```

**edit:** Didn't see AlliedEnvy's answer, which is identical to mine, except mine doesn't print a newline at the end.

# Answer
> 0 votes
# VBA

Since equals, quotes and dot are out of the question, and as everyone loves message boxes:

```
Sub helloworld()
    MsgBox Chr(72)
    MsgBox Chr(101)
    MsgBox Chr(108)
    MsgBox Chr(108)
    MsgBox Chr(111)
    MsgBox Chr(44)
    MsgBox Chr(87)
    MsgBox Chr(111)
    MsgBox Chr(114)
    MsgBox Chr(108)
    MsgBox Chr(100)
    MsgBox Chr(33)
End Sub

```

# Answer
> 0 votes
# PHP (111 chars)

```
<?=chr(72).chr(101).chr(108).chr(108).chr(111).chr(44).chr(32).chr(87).chr(111).chr(114).chr(108).chr(100).chr(33)?>

```

Assuming `.` is OK (I have used: `[chr0-9\(\)\.]`).

# Answer
> 0 votes
# dc - 25 bytes

```
33[ World]44[Hello]PaPPap

```

I'm starting to like dc.

# Answer
> 0 votes
## Logo, 52 chars

```
pr se word [Hello] char 44 word char [World] char 33

```

Using the new rule that brackets are allowed. Otherwise, one could `word` together lots more `char`s to achieve the same goal.

# Answer
> 0 votes
# Julia

Option 1, using square brackets and join, and just one print/char:

```
print(join(char([72 101 108 108 111 44 32 87 111 114 108 100 33])))

```

Option 2, one "char" at a time:

```
print(char(72))
print(char(101))
print(char(108))
print(char(108)
print(char(111))
print(char(44))
print(char(32))
print(char(87))
print(char(111))
print(char(114))
print(char(108))
print(char(100))
print(char(33))

```

Options 3 + 4, same as above, but with 0x?? char creation. That is, rather than char(72), use 0x72. Or, in the join case, replace 72 with 0x72 (and so on) and remove the "char" operation entirely.

# Answer
> -2 votes
## Common Lisp

This almost works, except that `-` isn't allowed. If only there were the functions `stringCapitalize` and `codeChar` instead…

```
(mapcar (lambda (x)
          (princ (string-capitalize x)))
        (list (quote hello)
              (code-char 44)
              (code-char 32)
              (quote world)
              (code-char 33))))

```

The nice thing here is that string-capitalize takes a *string designator*, which can be a string, symbol, or character. Sample use:

```
CL-USER> (mapcar (lambda (x)
                   (princ (string-capitalize x)))
                 (list (quote hello)
                       (code-char 44)
                       (code-char 32)
                       (quote world)
                       (code-char 33)))
Hello, World!

```

---
Tags: popularity-contest, restricted-source, hello-world
---


# Question
Title: Linear Function Solver from Two Points (x,y)
# The Task

Write a function L() that takes two Tuple arguments of coordinates in the form (x, y), and returns their respective linear function in the form (a, c), where a is the co-efficent of the x term and c is the y-intercept.

You can assume that the input will not be a line perpendicular the the x axis, and that the two inputs are separate points.

# Scoring

This is Code Golf: shortest program wins.

Please Note: No use of any mathematical functions apart from basic operators (+,-,/,\*).

# Example

Here is my un-golfed solution in Python.

```
def L(Point1, Point2):
    x = 0
    y = 1
    Gradient = (float(Point1[y]) - float(Point2[y])) / (float(Point1[x]) - float(Point2[x]))
    YIntercept = Point1[y] - Gradient * Point1[x]
    return (Gradient, YIntercept)

```

Output:

```
>>> L( (0,0) , (1,1) )
(1.0, 0.0)

>>> L( (0,0) , (2,1) )
(0.5, 0.0)

>>> L( (0,0) , (7,1) )
(0.14285714285714285, 0.0)

>>> L( (10,22.5) , (5,12.5) )
(2.0, 2.5)

```

# Answer
> 1 votes
# J - 23 char

Fairly straightforward. Defines a dyadic verb `L` to be used as `(x1,y1) L (x2,y2)`.

```
L=:%~/@:-,-/@(*|.)%-&{.

```

Explanation:

```
L=:%~/@:-,-/@(*|.)%-&{.  NB. the function L
                    &{.  NB. x coord of both points
                   -     NB. left x minus right x
             ( |.)       NB. flip right argument: (y2,x2)
              *          NB. pointwise multiplication of (x1,y1) and (y2,x2)
          -/@            NB. subtract the two results: (x1*y2)-(y1*x2)
                  %      NB. divide: (x1*y2 - y1*x2)/(x1-x2)
        -                NB. pointwise subtraction
   %~/@:                 NB. divide y difference by x diff: (y1-y2)/(x1-x2)
         ,               NB. append results together
L=:                      NB. assign function to L

```

Examples:

```
   L=:%~/@:-,-/@(*|.)%-&{.
   0 0 L 1 1
1 0
   0 0 L 2 1
0.5 0
   0 0 L 7 1
0.142857 0
   10 22.5 L 5 12.5
2 2.5
   0 0 L 0 1  NB. __ is negative infinity
__ 0

```

# Answer
> 7 votes
# GNU dc, 30 24 bytes

```
[sysxly-rlx-/dlx*lyr-]sL

```

Defines a macro `L` such that (x1, y1, x2, y2) should be pushed to the stack in that order before calling, and after calling `L`, (a, c) may be popped from the stack (in reverse order of course - it is a stack).

### Testcase (save as "linear.dc" and run `dc linear.dc`):

```
[sysxly-rlx-/dlx*lyr-]sL   # Define L macro

10                         # Push x1 to the stack
22.5                       # Push y1 to the stack
5                          # Push x2 to the stack
12.5                       # Push y2 to the stack

lLx                        # Call L macro
f                          # Dump the stack

```

Output is:

```
$ dc linear.dc
2.5
2
$

```

### Explanation of L macro:

* `sy` pop y2 to `y` register
* `sx` pop x2 to `x` register
* `ly` push `y` register (y2)
* `-` subtract y2 from y1
* `r` swap (y1 \- y2) and x1 on stack
* `lx` push `x` register (x2)
* `-` subtract x2 from x1
* `/` divide (y1 \- y2) by (x1 \- x2) to get gradient
* `d` duplicate gradient
* `lx` push `x` register (x2)
* `*` multiply (x2) by gradient
* `ly` push `y` register (y2)
* `r` swap (y2) and (x2 * gradient) on stack
* `-` subtract (x2 * gradient) from (y2)

# Answer
> 5 votes
# Haskell, 41 characters

```
f(x,y)(u,v)=(a,y-a*x)where a=(y-v)/(x-u)

```

Not a lot to golf here. It's pretty much what you'd write normally minus whitespace.

# Answer
> 4 votes
## Mathematica, ~~55~~ 38 bytes

~~This was surprisingly long (those pesky long function names...)~~ **EDIT:** Changed the approach for the axis intercept (taking some inspiration from the OP's own answer). It turns out calculating it directly wasn't the most clever idea.

```
L={g=1/Divide@@(#2-#),#[[2]]-g#[[1]]}&

```

Use like

```
L[{10,22.5},{5,12.5}]
> {2., 2.5}

```

Thanks to Mathematica you can also obtain the general result:

```
L[{r,s},{p,q}]
> {(p - r)/(q - s), (q r - p s)/(q - s)}

```

(This last example shows how I had originally implemented this.)

Just for the record

```
L[{0,0},{0,1}]
> {ComplexInfinity, Indeterminate}

```

which is technically correct.

# Answer
> 2 votes
## JavaScript, ~~62~~ 48

Thanks to @Michael for golfing it down with ES 6.

```
L=(a,b)=>[s=(b[1]-a[1])/(b[0]-a[0]),a[1]-s*a[0]]

```

Old version:

```
function L(a,b){return[s=(b[1]-a[1])/(b[0]-a[0]),a[1]-s*a[0]]}

```

Sample input:

```
L([0,0],[7,1])

```

Sample output:

```
[0.14285714285714285, 0]

```

For the record:

```
L([0,0],[0,1])
[Infinity, NaN]

```

# Answer
> 2 votes
## C# 105 bytes

This is isn't just the function and will compile completely on it's own. I had put `L` in the `System` namespace to shorting the using, but it's better to fully qualify and save on using a namespace. Saved the brackets. Also a saving from `return new z[]` into `return new[]`

```
using z=System.Single;class P{z[] L(z[]a,z[]b){z c=(a[1]-b[1])/(a[0]-b[0]);return new[]{c,a[1]-c*a[0]};}}

```

# Answer
> 2 votes
# Python3 (51)

```
def L(p,q):x,y=p;X,Y=q;m=(Y-y)/(X-x);return m,y-x*m

```

# Answer
> 1 votes
## Lua 5.1.4: ~~66~~ 64 bytes

```
function L(q,w)a=(q[2]-w[2])/(q[1]-w[1])return a,q[2]-a*q[1];end

```

Example Usage:

```
> print(L( {0,0}, {1,0} ))
-0   0
> print(L( {0,0}, {1,1} ))
1    0
> print(L( {0,0}, {7,1} ))
0.14285714285714    0
> print(L( {0,0}, {0,1} ))
-inf   -nan
> print(L( {0,0}, {0,0} ))
-nan   -nan

```

# Answer
> 1 votes
## C++ 88 (was 106)

Improved: thanks for your comments.

```
struct t{double x,y;};
t L(t u, t v){u.x=(v.y-u.y)/(v.x-u.x);u.y=v.y-u.x*v.x;return u;}

```

Golfed:

```
typedef struct T{double x,y;}t;
t line(t u, t v){t z;z.x=(v.y-u.y)/(v.x-u.x);z.y=v.y-(z.x*v.x);return z;}

```

Source

```
typedef struct T{
    double x,y;
} t;

t line(t u, t v)
{
t z;
z.x=(v.y-u.y)/(v.x-u.x);
z.y=v.y-(z.x*v.x);
return z;
}

```

# Answer
> 1 votes
# Apple Swift ~~95~~ 86

*This may be the first Swift entry on PCG.SE??*

```
func L(x:Float...)->(Float,Float){var a=(x[3]-x[1])/(x[2]-x[0]);return(a,x[1]-a*x[0])}

```

I don't see this language being a huge hit to the Code Golf community.

# Answer
> 0 votes
# Python3 - 64 57 Bytes

```
def L(q,w):a=(q[1]-w[1])/(q[0]-w[0]);return a,q[1]-a*q[0]

```

You can get it down to 43 if you don't use Tuple, which many people are doing...

```
def L(x,y,q,w):a=(x-q)/(y-w);return a,y-a*x

```

# Answer
> 0 votes
### Golfscript: 25 bytes

```
~:y\:x;-\x--1?*.x-1**y+\p

```

Since the function needs to be named 'L', I saved it as 'L.gs' locally.

The catch, as explained by @Dennis in this post, is that we need to trick Golfscript into using rational numbers instead of integers. So this works if you're willing to accept input `X1 Y1 X2 Y2` *in golfscript notation*

```
# L( (0,0) , (1,1) )
echo "0 0 1 1" | golfscript L.gs
> 1/1
> 0/1
#L( (10,22.5) , (5,12.5) )
echo "10 22 2-1?+ 5 12 2-1?+" | golfscript L.gs
> 2/1
> 5/2

```

# Answer
> 0 votes
### Ruby – 48 characters

Nearly identical to the JavaScript answer:

```
L=->u,v{a,b,c,d=*u,*v;[s=(d-b).fdiv(c-a),b-s*a]}

```

# Answer
> 0 votes
# PHP (75 chars)

```
function L($u,$v){return[$s=($v[1]-$u[1])/($v[0]-$u[0]),$v[1]-($s*$v[0])];}

```

test : `print_r(L([0,0],[7,1]));`

output :

```
Array
(
    [0] => 0.14285714285714
    [1] => 0
)

```

(thanks @ace)

---
Tags: code-golf
---


# Question
Title: Count the number of times a function runs
This is a teaser a friend of mine sent. It seems straightforward, but I can't seem to get my head around it, probably due to my lack of sleep.

1. You have 16 bits available.
2. Compose a function, and find a way to know when the function has run approximately one million times.
3. You MAY NOT use any additional memory space other than the 16 bits given.
4. Recursion may be used for efficiency, but, again, you MAY NOT use memory definition inside the recursion frames: only the 16 bits.

# Answer
One-million in binary is equal to `11110100001001000000` (20 bits). Thus, we cannot implement a simple counter for this.

Instead, the max number we can represent with 16 bits is `1111111111111111` = 65,535. Since the answer requires that we only need to approximate 1 million function runs, we could add one to the counter approximately once every 16 function runs, and know that the function has run about 1 million times when the counter reaches 1000000/16 = 62500.

Below is the pseudocode of a potential solution, assuming that `counter` is a positive integer stored in 16 bits. Also, this assumes that calls such as `random(1,16)` do not count towards memory as long as they are not stored in a variable. Last, the `random(x,y)` function should give a random integer between `x` and `y` inclusive.

```
counter = 0;

function amIAttaBoutaMillionYet(){
    if(random(1,16)==16 && counter<62501){
        counter++;
    }
    if(counter==62500){
        return true;
    }
    return false;
}

```

**UPDATE**

Fixed function so that it won't show true after about 2 million+, 3 million+, etc. function runs. (**thanks trinithis!**)
> 8 votes

# Answer
Beaten to it by `Briguy37`. :-(

Just call the function code 16 times for each tick of the counter.

```
def function()
{
    do stuff here...
}
while(loop<65535)
{
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    function()
    loop+=1
}

```
> 2 votes

# Answer
You could make it so that for every external call of function `A`, `A` is called another 999,999 times internally. Therefore, you are guaranteed that that last internal call is the millionth call.

```
var internal = false;
function A() {
    if (internal)
        return;

    internal = true;

    A();
    A();
    // ...999999 times...
    A();
    A(); // This last call is guaranteed to be the millionth call

    internal = false;
}

A();

```
> 2 votes

# Answer
The obvious approach is self-modifying code. Something along the lines of (and bearing in mind that I scarcely ever touch C, consider this to be pseudocode and don't try compiling it)

```
uint16 counter = 0;

void fun() {
    byte x = 0;
    if (x == 15) counter++;
    (*fun)=(x+1)&15;
    if (counter == 62500 && x == 0) sprint("Jackpot!");
}

```

It is, of course, cheating, but so is every possible approach, because the problem taken literally violates basic principles of information theory. And there may be a small offset needed when overwriting the initial value of x: depends on your processor and compiler. (No, I'm not going to dig out my notes on ARM assembler just for this).
> 1 votes

# Answer
Primary answer:

Does not use crazy macro expansion. Uses recursion and two 8 bit variables. The code works by recursing enough such that the first call to `foo` generates enough calls where the function is called approximately 1 million times.

```
//unsigned long count = 0;
//unsigned long numTimesTrue = 0;

#define SET_HIGH(x) (x |= (unsigned char)(1 << 7))
#define MASK_HIGH(x) (x & (unsigned char)~(1 << 7))
#define TEST_HIGH(x) (x & (unsigned char)(1 << 7))

int foo (unsigned char n = 0) {
    static unsigned char i;
    //++count;
    if (n == 0) {
        SET_HIGH(n);
    }
    if (MASK_HIGH(i) >= 20) {
        return 0;
    }
    for (i = n; MASK_HIGH(i) < 20; ++i) {
        n = i;
        foo(MASK_HIGH(i) + 1);
        i = n;
    }
    //if (TEST_HIGH(i) != 0) ++numTimesTrue;
    return TEST_HIGH(i) != 0;
}

int main () {
    int r1 = foo(); // 1, count == 1048576
    int r2 = foo(); // 0, count == 1048577
    int r3 = foo(); // 0, count == 1048578
    //assert(numTimesTrue == 1);
    return 0;
}

```

Secondary answer:

This returns true only once and only when the function has been run approximately 1 million times. I'm talking liberty in the usage of the word approximate in that the integers are unbounded. (1 is approximately 1,000,000 with respect to 100!!!!!! (you have to figure out which are factorials and which are exclamation points).)

```
int foo () {
    static int hasRun = 0;
    if (!hasRun) {
        hasRun = 1;
    }
    return !hasRun;
}

```
> 1 votes

# Answer
Well, similar to Briguy37. I divided the 16 bits to two 8 bits vars. low byte is incremented on every call and reset when it reaches 250. On reset of low byte increment hi. When hi reaches 4000 (1000000/250 = 4000), we have 1 million calls

```
    byte hi=0
    byte lo=0

    function oneMillionCallFunction()
        lo++
        if lo==250 then
            hi++
            lo=0
        if hi==4000 then
            return true
        return false

```
> 0 votes

# Answer
to implement Briguy's solution in D

```
import std.random;
bool foo(){
    static ushort count = 0;//16 bits
    if(uniform(0,16)==0)count++;//increment once in approx every 16 calls
    if(count==62500)return true;//we're close enough
    return false;
}

```
> 0 votes

# Answer
This scala-code contains the test, to see how much we are away:

```
val r = util.Random

def resetAndTest () {

var x = 0 : Short

def mioFun (n: Int) = {
  if (r.nextInt (30518) < 1000)
    x = (x + 1).toShort
  if (x < 0) {
    println ("n calls " + n )
    true }
  else false
}

(1 to 1010000).find (mioFun)

}

```

typical results:

```
scala> (1 to 10).foreach (_ => resetAndTest)
n calls 1001214
n calls 1000340
n calls  993883
n calls 1005774
n calls 1001670
n calls  997401
n calls 1009786
n calls  992853
n calls 1002313
n calls 1002992

```
> 0 votes

# Answer
I just had a strange idea - but it works. This python version works **without any counter**. The one-millionth call returns `1` any other the value `0`.

```
def fun():
    global f
    try:
      f
    except NameError:
      def fun_int():
        yield 0
        yield 0
        ...
        yield 0
        yield 1
        while 1:
          yield 0
      f = fun_int()
    return f.__next__()

print(fun())
print(fun())
...
print(fun())
print(fun())

```

Unfortunately the generator reference `f` takes some bits - so please use a python implementation which does it in 16 bits or less.
> 0 votes

# Answer
Since Peter Taylor points out that using a PRNG may violate the 16-bit limit, what about using the system time? Would that also violate the limit?

In PHP:

```
$counter = 0;
function maybeOneMillion() {
  global $counter;
  $time = gettimeofday();
  if ($time['usec'] % 100 == 0) {
    $counter++;
    if ($counter == 10000) return true;
  }
  return false;
}

```
> 0 votes

# Answer
# Python

Likely also bending the rules:

```
x = 0
def f():
    global x
    if x < 20:
        x = x + 1
        f()
        f()
        x = x - 1

```

Arguably could do with just 5 bits, and would probably be shorter in C. Stretches rule (3) perhaps a bit.
> 0 votes

# Answer
# C

it's actually 6 bit. (Does rand() == 12679 count...?)

```
void func(void)
{
    static struct {
        unsigned short int count : 6;
    } S = {42};
    if (rand() == 12679)
        S.count--;
    if (!S.count)
        puts("1 MILLION REACHED");
}

```
> 0 votes

# Answer
# C

This answer changes the name of the process, and more precisely uses the first character of the name as an additional 8-bits counter.

```
#include <stdio.h>

int main(int argc, char* argv[])
{
unsigned short cpt=0;

argv[0][0]=0;
while(argv[0][0]!=20)
    {
    cpt++;

    /* the function printf is called 1.0000.000 times */
    printf("ok\n");

    if (cpt==50000)
        {
        cpt=0;
        argv[0][0]++;
        }
    }

}

```
> 0 votes

---
Tags: programming-puzzle
---


title: Are the rooms connected?

text:
# Question
Title: Are the rooms connected?
You are locked in a massive fortress, slowly starving to death. Your guards inform you that there is food in the fortress, and even tell you where it is and provide a map of the building.

However, you are not sure that you can actually reach the food, given that the every door is locked, and every room is its own labyrinth. Are you able to reach the food? If you're in the same room, you should try. If you're not in the same room, then you might as well stay put, preserving your strength in case help from the outside world comes.

# Input

Two arrays: 3 coordinates of where you are, and 3 coordinates of where the food is. (Both are 0-based)

:Optional: an array of three numbers, indicating the size of the following fortress in each dimension.

A three dimensional array of the fortress, where each point in the array is either 1/true (if that point is a wall) or 0/false (if the point is empty). The array is a rectangular prism, and there is no guarantee that the structure follows the laws of physics. (Thus, the bottom floor might be completely empty.)

The place where you are and the place where the food is both have a 0/false.

# Output

Are the two points in the same room, unseparated by a wall? Note that you can not move through a diagonal.

# Format

You may write a program or a function.

The input may be through STDIN, command line or function arguments, or reading from a file. If you choose a text-based input (like STDIN) you may use any delimiters to help your program parse the input.

The output may be through STDOUT or the function result. You can output/return "true"/"false", 0/1, or the like.

# Examples

In these examples, I put a Y where you are, and a F where the food is. This is just to help you understand the examples; in the actual input they would be 0/false.

## Input

```
[0 0 1]      // You are at x = 0, y = 0, z = 1
[1 2 2]      // The food is at x = 1, y = 2, z = 2
[[[0 0 0]    // z = 0, y = 0
  [0 0 0]    // z = 0, y = 1
  [1 1 1]]   // z = 0, y = 2
 [[Y 0 0]
  [0 0 0]    // z = 1
  [1 1 1]]
 [[0 0 0]
  [1 1 0]    // z = 2
  [0 F 0]]]

```

## Output

True. (The places are connected. You can move from \[0 0 1\] \> \[2 0 1\] \> \[2 0 2\] \> \[2 2 2\] \> \[1 2 2\].)

## Input

```
[3 0 1]
[1 1 0]
[4 2 2]         // If you want, you can include this in the input, to indicate the fortress's size
[[[0 1 0 0]     // z = 0, y = 0
  [0 F 1 0]]    // z = 0, y = 1
 [[0 0 1 Y]
  [0 1 0 0]]]

```

## Output

False. (There are two rooms. Your room includes \[2 0 0\], \[2 1 1\], \[3 0 0\], \[3 0 1\], \[3 0 1\], and \[3 1 1\]. The food's room includes the other empty spaces. Note that a wall of 1's divides the fortress in half.

# Winning criterion

Code golf. Shortest code for your function/program wins.

# Answer
### GolfScript, 93 characters

```
~[[]]@{,`{{1$+}%\;~}+%}/:A[\{{~}/}%]zip{~!*}%:S;]1/~{{3,{)1$/.())+\+\()(+\+}%{[]*}/}%S&}A,*&,

```

The code expects the input as specified above (including the fortress' dimensions) on STDIN. The result is `1` if food is reachable and `0` otherwise.

Try the code online.
> 1 votes

# Answer
# Python 2.x - 177 168 167 bytes

Basic flood fill to kick the game going. Requires the dungeon size.

```
f,(a,b,c),(w,h,d),p=input()
def l(x,y,z):
 if w>x>-1<y<h>0<=z<d and p[z][y][x]<1:p[z][y][x]=2;[(l(x+i,y,z),l(x,y+i,z),l(x,y,z+i))for i in-1,1]
l(*f)
print p[c][b][a]>1

```

Examples:

```
Input:  [0,0,1],[1,2,2],[3,3,3],[[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[1,1,0],[0,0,0]]]
Output: True

Input:  [3,0,1],[1,1,0],[4,2,2],[[[0,1,0,0],[0,0,1,0]],[[0,0,1,0],[0,1,0,0]]]
Output: False

```

Ungolfed code:

```
(e,f,g),(a,b,c),(w,h,d),field=input()

def fill(x,y,z):
    if 0<=x<w and 0<=y<h and 0<=z<d and field[z][y][x]<1:
        field[z][y][x]=2
        fill(x+1,y,z)
        fill(x-1,y,z)
        fill(x,y-1,z)
        fill(x,y+1,z)
        fill(x,y,z-1)
        fill(x,y,z+1)

fill(e,f,g)
print field[c][b][a]==2

```
> 4 votes

# Answer
## Mathematica, 173 bytes

```
f=(v=#;(v=ReplacePart[v,Reverse[#+1]->#2])&@@@{{#3,2},{#4,3}};VertexConnectivity[VertexDelete[GridGraph[#2],Join@@(l=Flatten@v)~(s=Position)~1],(h=s[l,#][[1,1]]&)@2,h@3]>0)&

```

This defines a function `f` which can be called like

```
f[{{{0,1,0,0},...}, {4,2,2}, {3,0,1}, {1,1,0}]

```

using your second example.

Ungolfed:

```
f = (
   v = #;
   (v = ReplacePart[v, Reverse[# + 1] -> #2]) & @@@ {{#3, 2}, {#4, 3}};
   VertexConnectivity[
    VertexDelete[
     GridGraph[#2],
     Join @@ (l = Flatten@v )~(s = Position)~1
     ],
    (h = s[l, #][[1, 1]] &)@2,
    h@3] > 0
   ) &

```

I'm simply creating a grid graph for the entire building, then delete all walls (and their adjacent edges) from the graph and then check that the two vertices are connected.
> 2 votes

# Answer
# Javascript (E6) 123 ~~128 132 140 167 286 344~~

~~First try. Simple fill, not recursive, fortress size not needed. <br>*Must simplify multidimensional array handling (90 chars!!).*~~

**Edit** Recursive fill, no need to know the fortress dimensions, should work even for irregular shapes.
**Edit** Tip***s*** by TheRare to shorten the recursive call & golf more
**Edit** Contribution by MT0, cut same () and use exact equal
**Edit** Contribution by nderscore, multidimensional array handling (learned sth new again)
**Edit** With a clever trick, nderscore bring the food check back inside the loop, where it belongs. Now returning a boolean, 'some' is more fit than 'map' (and shorter)

```
A=(Y,F,M)=>(S=(x,y,z)=>(t=(M[z]||0)[y]||0)[x]-1&&[x,y,z]+''==F|[-1,t[x]=1].some(d=>S(x+d,y,z)|S(x,y+d,z)|S(x,y,z+d)))(...Y)

```

**Usage**

```
A([0,0,1],[1,2,2],
  [[[0,0,0],[0,0,0],[1,1,1]],
  [[0,0,0],[0,0,0],[1,1,1]],
  [[0,0,0],[1,1,0],[0,0,0]]])

```

Return 1

```
A([3,0,1],[1,1,0],
  [[[0,1,0,0],[0,0,1,0]],[[0,0,1,0],[0,1,0,0]]])

```

Return 0

**Ungolfed**

```
A=(Y,F,M)=>
  (S=(x,y,z)=>
     (t=(M[z]||0)[y]||0)[x]-1 // NaN==out,-1==open,0==wall or visited
     && [x,y,z]+''==F // compare with food position converting to string
     | [-1,t[x]=1] // mark as visited, then recurse popping out the return value if true
       .some(d=>S(x+d,y,z)|S(x,y+d,z)|S(x,y,z+d))
  )(...Y)

```
> 1 votes

---
Tags: code-golf
---