title: Ascii art hangman

text:
# Question
Title: Ascii art hangman
Although there was a hangman competition before, I don't feel it was beautiful enough. The challenge is to implement a clone of http://inventwithpython.com/chapter9.html but as in the previous competition you can input the list of words in any way you want. The main difference is therefore just that you have to draw the gallows in ascii as the game goes on.

# Answer
> 1 votes
# Python 3

You will need to put the lists in a folder named wordlists, which is placed in the same folder as the source. You can download the full .zip here: https://github.com/OddLlama/ascii-gallows-club.

This program allows 7 guesses until completion, and allows guessing the full word in one blow, if you think you know it. It has a debug mode, where you enter 'debug' instead of the number of players, and does not allow you to enter a guess more than once. It also allows 2-player mode, where one player enters the word, and a second player guesses it. In this mode, the entered word does not display while being typed. Other features are score-keeping and displaying special characters (although the lists haven't been updated to represent that):

```
#!/usr/bin/env python3

import random # for choosing a word
import os # for finding files in wordlists directory
import textwrap # for ASCII art dedentation
import time # for sleeping at the end
import getpass # for 2 player

# grab all the filenames
categories = [f.split('.')[0] for f in os.listdir('wordlists')]

debug_mode = False
def debug(s):
  if debug_mode: print('[DEBUG] ' + s)

def print_ASCII(ascii_str):
  "Print ASCII art."
  print(textwrap.dedent(ascii_str))

def header():
  "Print the header."
  print_ASCII("""
    /=======================\\
    | Welcome to Hangman!!! |
    \\=======================/
  """)

def choose_category():
  "Request the user to input a category."
  for i, cat in enumerate(categories):  # print the categories & numbers
    print('%i. %s' % (i, cat))
  choice = input('Please enter a category name or number: ').lower()
  if choice.isdigit() and 0 <= int(choice) < len(categories):
    choice = categories[int(choice)]
  for i, cat in enumerate(categories):
    if choice == str(i): choice = cat
  while choice not in categories:  # loop until user enters a valid category
    choice = input('Invalid category. Try again: ')
    if choice.isdigit() and 0 <= int(choice) < len(categories):
      choice = categories[int(choice)]
  return choice

def get_word(category):
  "Retrieve a random word from a category."
  with open('wordlists/%s.txt' % category) as f: # use `with` for automatic file closure
  words = f.readlines()
  return random.choice(words).rstrip('\n').strip().lower()

def get_guess(guessed):
  "Get the user to guess a letter."
  guess = input('Guess: ').lower()
  while guess in guessed:
    guess = input('You already guessed that. Try again: ').lower()
  return guess

# draw gallows
def draw_board(bad_guesses, word):

  length = len(bad_guesses)

  # this is also always drawn
  print_ASCII("""
    ______________
    | /          |
    |/           |
    |{0}          {2}{1}{3}
    |            {4}
    |            {5}
    |           {6} {7}
    |
    |
    | {8}
    |________________|""".format('  ' if length == 1 else '', 'O' if length > 0 else '', '__' if len(bad_guesses) > 1 else '',
                                 '__' if len(bad_guesses) > 2 else '', '|' if length > 3 else '', '|' if length > 4 else '',
                                 '/' if length > 5 else '', '\\' if length > 6 else '',
                                 ' '.join(map(lambda s: '[%s]' % s, bad_guesses))).strip('\n'))

def hangman(word):  # main function
  """
  Plays hangman!
  Returns True if the user won, False otherwise.
  """

  debug('The word is %s' % word)

  # the lines showing the word so far
  guess = ['_' if char.isalnum() else char for char in word]

  # already guessed and wrong guesses
  guessed = []
  bad_guesses = []
  while len(bad_guesses) < 7: # main loop
    # print letters so far
    print(' '.join(guess))

    # request input
    letter = get_guess(guessed)
    guessed.append(letter)

    # check if letter is correct or not
    if letter in word or letter == word:
      # update chars guessed so far
      guess = [letter if char == letter else guess_char for char, guess_char in zip(word, guess)]
      if letter == word: guess = list(word)

      # did they win?
      if ''.join(guess) == word:
          print('Congratulations, you guessed the word: %s!' % word)
          return True
    else:
      bad_guesses.append(letter)
      print('%s is not in the word.' % letter)

    # add a little separation
    print()
    draw_board(bad_guesses, word)

  # if program reaches here, user failed
  print('You couldn\'t guess the word. It was %s.' % word)
  return False

if __name__ == '__main__':
  header()
  players = input('How many players? 1 for playing against computer, 2 for playing against another human: ')
  while players not in ['1', '2', 'debug']:
    players = input('Invalid input. Please try again: ')

  # debug mode stuff
  if players == 'debug':
    debug_mode = True
    debug('Debug mode has been turned on.')
  while players not in ['1', '2']:
    players = input('Number of players: ')

  print() # spacing

  if players == '1':
    wins, losses = 0, 0
    if hangman(get_word(choose_category())): wins += 1
    else: losses += 1
    while True:
      print('You have won %i time%s and lost %i time%s.' % (wins, '' if wins == 1 else 's', losses, '' if losses == 1 else 's'))
      again = input('Play again? (y/n): ').lower() == 'y'
      print() # separation
      if again:
          if hangman(get_word(choose_category())): wins += 1
          else: losses += 1
      else:
          break
  else:
    while True:
      word = getpass.getpass('Word maker: enter your word (the input will not be shown): ')
      hangman(word)
      again = input('Play again? (y/n): ').lower() == 'y'
      print() # separation
      if not again: break

print('Goodbye!')
time.sleep(2)

```

---
Tags: code-golf
---


title: 1+2+3+4+...+n = -1/12?

text:
# Question
Title: 1+2+3+4+...+n = -1/12?
Today, Numberphile posted this video where it's stated that `1+2+3+4+...+n = -1/12`.

While this isn't really new (several ways to prove that have been found, you can look here for further informations), this leads us to our question!

Your goal is to write a function that returns **-0.083333** (feel free to stop at **-0.083** if you wish), which is -1/12.

Be original, since this is a !

Most upvoted answer in 2 weeks wins this.

# Answer
> 3 votes
The Riemann Zeta function is defined as ζ(s) = Sum(n<sup>-s</sup>) where you sum from n=1 to n=infinity. Hence ζ(-1) = Sum(n) = 1 + 2 + 3 + 4 + ... to infinity.

Now scipy defines zetac to be `sum(k**(-x), k=2..inf)` (that is the zeta function with the first term removed).

Hence in python

```
>>> import scipy.special
>>> print 1+scipy.special.zetac(-1)
-0.0833333333333

```

essentially calculates the infinite sum 1+2+3+4+... to give -1/12.

# Answer
> 2 votes
## J

This is quite short, but I hope you think it's sweet:

```
(%&13@<:^:_)0

```

I'm relying on the fact that a negative twelfth is -0.1111111... in base thirteen. This function takes its argument, decrements it, and divides by 13 (a right-shift in base 13). It does this until the value converges to -1/12. To see how the base 13 stuff fits in, you might want to imagine the 13 being changed to a 10. The function would then converge at decimal -0.111111... = -1/9.

# Answer
> 2 votes
# PowerShell (and probably a polyglot)

I know this isn't code-golf, but since no other parameters are really defined for the challenge except:

> Your goal is to write a function that returns -0.083333 (feel free to stop at -0.083 if you wish), which is -1/12.

I have a really hard time justifying doing anything other than:

```
-1/12

```

This outputs:

```
-0.0833333333333333

```

---
Tags: popularity-contest
---


# Question
Title: Regex for Finding Non-Radioactive Elements
Find the shortest regex that matches all non-radioactive elements and nothing else in the Periodic Table of Elements. This is the inverse of Regex for Finding Radioactive Elements

Radioactive Elements

```
'Technetium','Promethium','Polonium','Astatine','Radon','Francium','Radium','Actinium','Thorium','Protactinium','Uranium','Neptunium','Plutonium','Americium','Curium','Berkelium','Californium','Einsteinium','Fermium','Mendelevium','Nobelium','Lawrencium','Rutherfordium','Dubnium','Seaborgium','Bohrium','Hassium','Meitnerium','Darmstadtium','Roentgenium','Copernicium','Ununtrium','Flerovium','Ununpentium','Livermorium','Ununseptium','Ununoctium'

```

Non-radioactive Elements

```
'Hydrogen','Helium','Lithium','Beryllium','Boron','Carbon','Nitrogen','Oxygen','Fluorine','Neon','Sodium','Magnesium','Aluminium','Silicon','Phosphorus','Sulphur','Chlorine','Argon','Potassium','Calcium','Scandium','Titanium','Vanadium','Chromium','Manganese','Iron','Cobalt','Nickel','Copper','Zinc','Gallium','Germanium','Arsenic','Selenium','Bromine','Krypton','Rubidium','Strontium','Yttrium','Zirconium','Niobium','Molybdenum','Ruthenium','Rhodium','Palladium','Silver','Cadmium','Indium','Tin','Antimony','Tellurium','Iodine','Xenon','Caesium','Barium','Lanthanum','Cerium','Praseodymium','Neodymium','Samarium','Europium','Gadolinium','Terbium','Dysprosium','Holmium','Erbium','Thulium','Ytterbium','Lutetium','Hafnium','Tantalum','Tungsten','Rhenium','Osmium','Iridium','Platinum','Gold','Mercury','Thallium','Lead','Bismuth'

```
* Scored by character count in the regex.
* Use standard Perl regex (just no specialized functions).
* Assume all lower case.
* You only need to count the characters of the regex itself.

Note if you used a program to get you started and maybe post how well it did. I'll post my best attempt as an answer to get started/show an example.

Edit: Apparently Bismuth is radioactive, but since I'm assuming the universe would die from heat death before it was ever much of a problem I'm not going to worry about it now.

# Answer
Small improvement on qw3n's solution (**93 characters**):

```
y|^v|h.[lfdn]|[^te]i[rodnts]|[lp].t[^o]|ru?[bs]|ll|^..ro|^[^r][^u].{1,4}$|ca..i|ma|s.l|tan|gs

```

Basically got rid of `^t[^eh]` (7 characters) clause and replaced with `tan|gs` (6 characters). Also I count qw3n's solution as 94 characters, not 95.
> 2 votes

# Answer
**Character count 94**

```
y|^v|h.[lfdn]|^t[^eh]|[^te]i[rodnts]|[lp].t[^o]|ru?[bs]|ll|^..ro|^[^r][^u].{1,4}$|ca..i|ma|s.l

```
> 3 votes

# Answer
I was tempted (and am still debating internally) to vote to close this as a duplicate of your other regex golf question on the basis that the optimal solutions are within a constant of each other, as witness:

## 70 chars

```
^(?!no|c?u|ra|.*(e.[kht]|[^l][gecv]i|[^c]oh?[rn]iu|f.r|ac|sta|bn|has))

```
> 3 votes

---
Tags: code-golf, regular-expression
---


title: Count the Zeros

text:
# Question
Title: Count the Zeros
For a given n, count the total number of zeros in the decimal representation of the positive integers less than or equal to n. For instance, there are 11 zeros in the decimal representations of the numbers less than or equal to 100, in the numbers 10, 20, 30, 40, 50, 60, 70, 80, 90, and twice in the number 100. Expect n to be as large as 10^10000.

Your task is to write a program to count zeros. Most efficient algorithm wins (Big O complexity)

**EDIT:** post your code and your answer for n = 9223372036854775807.

# Answer
> 8 votes
Some thoughts up front:

```
f[i]: number of zeros in [10^i, 2*10^i)
g[i]: number of zeros in [10*10^i, 11*10^i)
h[i]: number of zeros in [0, 10^i)

i   f       g     h
1  1*     10*     *
2  1**    10**    **
3  1***   10***   ***
4  1****  10****  ****

f[i] = 9*f[i - 1] + g[i - 1]
g[i] = f[i] + 10^i
h[i] = h[i - 1] + 9*f[i - 1]

```

Now the code:

```
def zeros(n):
    s = str(n)
    f = [0]
    g = [1]
    h = [0]
    for i in range(1, len(s) + 1):
        f.append(9*f[-1] + g[-1])
        g.append(f[-1] + 10**i)
        h.append(h[-1] + 9*f[-2])
    k = len(s) - 1
    a = h[k]                  # all numbers with fewer digits
    a += (int(s[0]) - 1)*f[k] # same number of digits but first digit less
    s = s[1:]
    while s:
        if s[0] == '0':
            a += int(s) + 1
        else:
            a += int(s[0])*f[len(s) - 1] + 10**(len(s) - 1)
        s = s[1:]
    return a

```

For n = 9223372036854775807 the result is 16577013372932555466. This is different from the currently accepted answer by @user14325, but I have more trust in it since starting at n=1000, @user14325 disagrees from the naive implementation suggested by @user2509848 in which I have a lot of trust due to its simplicity.

Complexity of my code is O(log n), at least if you assume uniform cost for arithmetic operations. Taking bit cost into account, it will probably be O(log(n)3log log(n)) or something like that, depending on how Python does its big integers and the exponentiation on them. If you care about the constants, then there is a lot of room for optimizations. Converting between numbers and strings all the time is hardly efficient. But as long as you only care for asymptotic behavior, I'll leave it at that.

# Answer
> 9 votes
Python O(1):

Since the challenge has been specified to be using Big O. I concluded that the best way to do it(since the upper bound is limited by a constant) is to just to create a giant look-up array.

However, this program would be too big to post here, so I made a program that generates it:

```
def zeroesUpToN(n):
    zeros = 0
    for i in range(n):
        s = str(i+1)
        zeros += s.count('0')
    return zeros

s = "print(["
for i in range(10^10000):
    s += str(zeroesUpToN(i+1)) + ",";
s = s[:-1] + "][int(input())])"

print(s)

```

So, this will ALWAYS take a long time to run(I mean the resulting program, not the generating program. The generating program would take even longer). But, how long it takes to run will not depend on n. Therefore, by definition it is an O(1) solution.

Here is an actual program that works for smaller outputs(up to 200):

```
print([0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,11,12,13,14,15,16,17,18,19,20,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,31][int(input())])

```

The real one is obviously much bigger.

P.S This is the problem with Big O problems.

EDIT: Oops, I forgot to give credit to @user2509848 whom I actually stole the code for generating each N.

# Answer
> 4 votes
Java:

```
public class ZeroCount {
    static final int max = 65498;

    public static void main(String[] args) {
        int res = 0;
        for (int i = 10; i <= max; i*=10) {
            res += max/i + max/(10*i) * (i-1);
            res -= (max % (10*i) < i) ? (i-1) - (max % i) / (i/10) : 0;
        }
        System.out.println(res);
    }
}

```

Should be *O(log(n))*

**Edit:**

For n=9223372036854775807 I decided to use Python instead of Java since 9223372036854775807 is Long.MAX\_VALUE in Java and I didn't want to use BigInt

```
def zeros(n):
    res = 0
    i = 10
    while i <= n:
        res += (n // i) + n // (10 * i) * (i - 1)
        res -= (i - 1) - (n % i) if n % (10 * i) < i else 0
        i *= 10
    return res

print(zeros(9223372036854775807))

> 16577013372932555466

```

# Answer
> 2 votes
# Python 3

```
n = int(input())
zeros = 0
for i in range(n):
  s = str(i+1)
  zeros += s.count('0')

print(zeros)

```

Fast up to 10,000,000. It gets slower when I bring it to 100,000,000.

# Answer
> 2 votes
# Haskell - O(n) for 10^n input

```
import Data.Char
import Data.List

p n = (10^n-10)`div`9 -- number of padded zeroes below 10^n
t n = n*10^(n-1) -- number of zeroes below 10^n with padded
digsToInt = foldl1 (\x y -> x*10+y)

-- number of zeroes below n
f :: Integer -> Integer
f n = h ds (len - 1) - p len
  where
  ds = map (fromIntegral . digitToInt) $ show n
  len = genericLength ds
h [x] _ = 0
h (x:ys) n | x == 0 = 1 + digsToInt ys + h ys (n-1)
           | otherwise = t (n+1) - (10-x) * t n + h ys (n-1)

```

Answer for 9223372036854775807 is 16577013372932555466.

# Answer
> 1 votes
# C# O(log n):

```
using System;

namespace Zeroes
{
    class program
    {
        static void Main(string[] a)
        {
            int n = int.Parse(a[0]);
            int result = 0;
            for (int i = 1; i < Math.Log(n); i++)
                result += n/(int)Math.Pow(10, i);
            Console.Write(result);
        }
    }
}

```

Only works for integers, of course, but the logic's sound. I have a feeling there's a better algorithm to be found, though. Nope, there's a bug in this.

# Answer
> 1 votes
## Python *O(log10 n)*

```
def zerosA(n):
  '''finds the number of zeros from [1, 10**n]'''
  if n < 1: return 0
  return 10*zerosA(n-1) + 10**(n-1) - 9*(n-1)

def zerosB(n):
  '''finds the number of zeros from (10**n, 2*10**n]'''
  if n < 1: return 0
  return 10**n + n*10**(n-1) - 1

def zerosC(n):
  '''finds the number of zeros from (2*10**n, 3*10**n]'''
  if n < 1: return 0
  return n*10**(n-1)

def count_zeros(n):
  p = z = 0
  while n >= 10:
    n, r = divmod(n, 10)
    if r > 0:
      z += zerosB(p) + zerosC(p)*(r-1) + `n`.count('0')*r*10**p
    p += 1
  z += zerosA(p) + zerosC(p)*(n-1)
  return z

if __name__ == "__main__":
  print count_zeros(9223372036854775807)

```

Output:

```
 16577013372932555466

```

For the number *12345*, for example, this works in the following manner:

\[*12341*, *12345*\] ⇒ *0*
\[*12301*, *12340*\] ⇒ *13*
\[*12001*, *12300*\] ⇒ *159*
\[*10001*, *12000*\] ⇒ *1599*
\[*1*, *10000*\] ⇒ *2893*

For a total sum of *4664*. No more than *log10 n* iterations are needed to reach the final answer.

---
Tags: code-challenge, fastest-algorithm
---


title: I know you, but you don't know me

text:
# Question
Title: I know you, but you don't know me
You're tasked with writing two programs. Program **A** must print out nothing on all inputs *except* when program **B** is input, in which case it should print `1`. Program **B** must print out `1` on all inputs *except* when program **A** is input, in which case it should print nothing.

**Scoring:**

* +1 For each character from **both** programs.
* Lowest score wins.

# Answer
## GTB, 25

*Executed from a TI-84 calculator*

Program `A`

```
`_@_eq;"$w;&

```

Program `B`

```
`_@_eq;"$#w;&

```

**Explanation**

``_` Input a string

`@_eq;"` Check if it equals the source code (`#` is automatically stripped along with lowercase letters)

`$w;&` If so, display 1 (otherwise nothing) \[for `B` it's `$#w;&` \- if not, display 1 (otherwise nothing)\]
> 5 votes

# Answer
## Bash - 32 characters

**Script A - 16 characters**

```
cmp -s b&&echo 1

```

**Script B - 16 characters**

```
cmp -s a||echo 1

```

**Usage**

```
$> echo "foo" | ./a
$> cat b | ./a
1
$> echo "foo" ./b
foo ./b
$> cat a | ./b

```
> 12 votes

# Answer
## Ruby, 54

A

```
$><<1if$<.read==IO.read(?B)

```

B

```
$><<1if$<.read!=IO.read(?A)

```

examples:

```
bash-3.2$ ruby A < A
bash-3.2$ ruby A < B
1bash-3.2$ ruby B < A
bash-3.2$ ruby B < B
1bash-3.2$

```
> 5 votes

# Answer
## J (62)

Since you didn't forbid this...

Store the programs as `A` and `B` respectively.

Program A (30):

```
exit echo#~(1!:1<'B')-:1!:1[3

```

Program B (32):

```
exit echo#~-.(1!:1<'A')-:1!:1[3

```

How it works (Program B, A is similar):

* `1!:1[3`: read stdin
* `1!:1<'A'`: read file `A`
* `-:`: see if they are equal
* `-.`: negate the result
* `#~`: replicate the result by itself (so, `1` results in one `1` and `0` results in zero `0`s, i.e. nothing)
* `echo`: output
* `exit`: exit (the J interpreter does not exit by default when it reaches the end of the file)

```
$ jconsole A <B
1
$ jconsole A <foo
$ jconsole B <A
$ jconsole B <foo
1
$

```
> 4 votes

# Answer
## Haskell - WITHOUT loading source - 478 644 characters

This assumes getContents ALWAYS ends with a newline and so drops the final character without checking because I don't feel like escaping it

A

```
main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d="main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d="

```

B

```
main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d="main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d="

```

It works like a standard quine, but swapping - for * to get the other program (avoiding those characters elsewhere).

The following test prints as expected (replacing main=interact$ with a= and b=)

```
main=do
  putStrLn "START"
  putStrLn$a "FOO"
  putStrLn$a "main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d=\"main=interact$($'1').replicate.(1*).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='*'='-'|n=='-'='*'|True=n;d=\"\n"
  putStrLn$b "FOO"
  putStrLn$b "main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d=\"main=interact$($'1').replicate.(1-).fromEnum.(/=map r(d++shows d[toEnum 10]))where r n|n=='-'='*'|n=='*'='-'|True=n;d=\"\n"
  putStrLn "END"

```

-

```
START

1
1

END

```
> 3 votes

# Answer
## Python 2.7 - 82

File A (literally named just `a`):

```
if raw_input()==open('b').read():print 1

```

File B (literally named just `b`):

```
if raw_input()!=open('a').read():print 1

```
> 2 votes

# Answer
## Ruby, 166 chars, no reading source

A:

```
(gets(p)==<<2.tr('&|','|&')*2+'2')&&p(1)
(gets(p)==<<2.tr('&|','|&')*2+'2')&&p(1)
2

```

B:

```
(gets(p)==<<2.tr('|&','&|')*2+'2')||p(1)
(gets(p)==<<2.tr('|&','&|')*2+'2')||p(1)
2

```

Make sure your text editor doesn't save with a trailing newline.

Usage (example):

```
 $ ruby know_a.rb know_b.rb
1
 $ ruby know_a.rb know_a.rb
 $ ruby know_b.rb know_a.rb
 $ ruby know_b.rb know_b.rb
1

```

Each program constructs the source of the other program using a HEREdoc and string transforms, then compares the result to the input.
> 2 votes

# Answer
# Python 3 - 102 characters

Prints 1 if the input is the same as program 2, otherwise nothing:

```
if input()==open('a.py').read():print('1')

```

Prints 1 if input is not the same as program 1, otherwise nothing:

```
if input()==open('a.py').read():print('1')

```
> 1 votes

# Answer
## Haskell - 138

Not really a good answer, but wanted to make both programs use the same source. Could save some chars by renaming the file, but it's not going to make this a winning solution so I don't think it's worth it.

```
import System.Environment
import Control.Monad
main=do{i<-getContents;p<-getProgName;f<-readFile "ab.hs";when((f==i)/=(p=="B"))(print 1)}

```

Compile this source as both `A` and `B`.

Test:

```
% ghc -o A ab.hs
[1 of 1] Compiling Main             ( ab.hs, ab.o )
Linking A ...
% cp A B
% ./A < ab.hs
1
% ./B < ab.hs
% ./A < ab.hi
% ./B < ab.hi
1

```
> 1 votes

# Answer
## Node.js - 142 characters

**Script `|` (otherwise known as Script A) - 80 characters**

```
f=require('fs').readFileSync;f('/dev/stdin','hex')==f('&','hex')&&console.log(1)

```

**Script `&` (otherwise known as Script B) - 62 characters**

```
eval(require('fs').readFileSync('|','utf8').replace(/&/g,'|'))

```

**Usage**

```
# \| is Script A
# \& is Script B

$> echo "foo" | node \|
$> cat \& | node \|
1
$> echo "foo" | node \&
1
$> cat \| | node \&

```

**Description**

Script B reads the contents of Script A and evals it after swapping the file names and the `and` operator to an `or`.

I named the files `&` and `|` so I can perform a single replace in Script B.
> 1 votes

# Answer
# bash/grep — 59 chars

51 chars if we only count the actual program string.

```
$ a='grep -cx "$b" | grep -x 1'
$ b='grep -vcx "$a" | grep -x 1'
$ echo 'foo' | eval $a
$ echo $b | eval $a
1
$ echo 'foo' | eval $b
1
$ echo $a | eval $b

```
> 0 votes

# Answer
## R (62 chars)

```
i=identical
A=function(x)if(i(x,B))1
B=function(x)if(!i(x,A))1

```

produces:

```
> A(123)
> A(A)
> A(B)
[1] 1
> B(123)
[1] 1
> B(A)
> B(B)
[1] 1

```

---

Meta comment: R fairs relatively bad on code golf as there is no shortcut to `function`...
> 0 votes

---
Tags: code-golf, quine
---


title: Turtle Graphics Program

text:
# Question
Title: Turtle Graphics Program
Most of you have probably heard of the famous Turtle Graphics program, initially made popular by Logo. This challenge is to implement a Turtle Graphics program in your language of choice.

Rules:

1. Rule one is that when the pen is in the down state, it must draw in both the square the turtle leaves and the square the turtle enters. This is what would happen in real life, so that is what your program should do.
2. Rule two is the turtle must include these 10 commands, which can be represented in the input as you like:

> RESET - resets board to blank - turtle position is default.
>
> UP and DOWN - these two commands set the pen/eraser state.
>
> RIGHT and LEFT - these two commands turn the turtle in the specified direction.
>
> FORWARD - advances turtle to next square.
>
> DRAW and ERASE - these commands set the turtle to drawing and erasing, respectively.
>
> DISPLAY - displays board.
>
> POSITION - prints turtle's x/y coordinate on the board.
>
> STOP, which stops drawing, displays the board, and terminates the program after the user enters any input.

1. The floor must be 20x20. You can use `vector`s, `array`s, or anything you like to represent it.
2. You must stop the turtle and display an error message if the turtle hits the wall.
3. Default turtle position is 0,0 facing right.

Scoring:

This program will use standard scoring rules with a few modifications to try to allow industry programming languages, such as Java and C++, to compete.

1. `Import`s, `include`s, `using`s and other similar statements do not score anything.
2. Loop header statements each only score one point. All other statements add the full number of characters in the statement to the score.

Example:

These statements do not score:

```
#include <iostream>
import java.util.Scanner;

def inputCommand():
string inputCommand(){}

```

These statements score only one point:

```
for(int i = 0; i < 9; i++){}
for i in range(0,10):
while(true){}
while x in y:

```

These statements score the full number of their characters:

```
string n;
i = 9;

switch(d) {
  case i:
    break;
  default:
    break;
}

return x;

cout<<'example';
cin>>s;
System.out.println()
print('example')

```

If you have any questions or comments, please let me know in the comments.

# Answer
> 5 votes
## JavaScript, one point

```
for (s='                    ',
    reset=function(){a=s.split(/./).map(function(){return s.split(/(?=.)/)}); x=0; y=0; dx=1; dy=0; pen='#'; down=1;},
    display=function(){console.log(a.map(function(x){return x.join('')}).join('\n'))},
    position=function(){console.log(x, y)},
    draw=function(){a[y][x]=down?pen:a[y][x]},
    forward=function(){draw(); x+=dx; y+=dy; (y<0||y>19||x<0||x>19) && (console.log('Hit wall')||(dx?(x-=dx):(y-=dy))); draw();},
    turn=function(d){nx=-1*(!dx)*d*dy; dy=(!dy)*d*dx; dx=nx;},
    reset();
    ((p=prompt()) != 'STOP') || display();
    (p == "RESET") && reset(),
    (p == "DISPLAY") && display(),
    (p == "POSITION") && position(),
    (p == "DRAW") && (pen='#'),
    (p == "ERASE") && (pen=' '),
    (p == "UP") && (down=0),
    (p == "DOWN") && (down=1),
    (p == "RIGHT") && turn(1),
    (p == "LEFT") && turn(-1),
    (p == "FORWARD") && forward()
);

```

Sorry, I couldn't resist.

# Answer
> 2 votes
# Mathematica (1 point and ~~211~~ ~~208~~ 205 characters)

```
A:=Abort[]
q@1:=Check[a〚##〛=c,A]&@@p
DI:=Print@ArrayPlot@a
ST:=DI+A
PO:=Print@p
FO:=p+=v
LE:=v=Cross@v
RI:=v=-LE
DR:=c=1
ER:=c=0
UP:=d=0
DO:=d=1
v={UP,DR};
a=0Array[p=0v+1,20p];
Symbol@StringTake[#,2]q@d&/@StringSplit@s

```

It prints

for

```
s = "DOWN RIGHT FORWARD FORWARD FORWARD FORWARD LEFT UP FORWARD LEFT \
   FORWARD FORWARD DOWN RIGHT FORWARD UP FORWARD LEFT FORWARD DOWN \
   FORWARD LEFT FORWARD FORWARD UP LEFT LEFT FORWARD FORWARD DOWN ERASE STOP";

```

I assume that the initial state is up&drawing.

You can put the whole code inside the header of `Do` loop

```
`Do[,{code; 1}]`

```

It is only `1` point!

# Answer
> 1 votes
# Python 2.7 (443? Points, 531 chars)

---

Not really that well golfed and the display looks kind of horrid. Takes input from a file 'i' and runs printing out the output. I defined two new 'commands': 'CW' and 'CCW' which rotate the turtle 90 degrees clockwise and counter-clockwise respectivly.

```
b=[];u=1;s=r=0;p=[];d=[(1,0),(0,1),(-1,0),(0,-1)];l='0';
def q():
 for i in b:print ''.join(i)
def z():
 r=0;p=[0]*2
 for i in [0]*20:
  b.append([l]*20)
def k():
 b[p[1]][p[0]]=(('1',l)[s],b[p[1]][p[0]])[u]
z()
for c in open('i','r').read().split():
 if c=="RESET":z()
 elif c=="UP":u=1
 elif c=="DOWN":u=0
 elif c=="FORWARD":
  k();p[0]+=d[r][0];p[1]+=d[r][1];k()
 elif c=="DRAW":s=0
 elif c=="ERASE":s=1
 elif c=="DISPLAY":q()
 elif c=="POSITION":print p
 elif c=="STOP":q();break
 elif c=="CW":r=(r+1)%4
 elif c=="CCW":r=(r-1)%4

```

---

Test Input:

```
DOWN FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW UP FORWARD FORWARD FORWARD FORWARD DOWN FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW FORWARD FORWARD CW ERASE FORWARD FORWARD STOP

```

Output:

```
11100000000000000000
10101010000000000000
11101110000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000
00000000000000000000

```

# Answer
> 1 votes
# Java

Here is my program - un-golfed (too complicated), unscored (I am unsure what the enums and Scanner object creation score as), and over-done:

```
package javaapplication74;

import java.util.Scanner;
import static java.lang.Integer.parseInt;

public class JavaApplication74 {

// create Scanner for input
static Scanner in = new Scanner(System.in);

// enumerator of commands
private enum Commands {RESET, UP, DOWN, RIGHT, LEFT, FORWARD, DISPLAY, ERASE, REVERSE, POSITION, STOP, ERROR};

// enumerator of directions turtle can face
private enum Direction {UP, DOWN, RIGHT, LEFT};

// array of valid commands
static final char[] commands = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'r' };

// width and height of room;
static final int ROOM = 20;

// turtle's position
static int[] position = {0, 0};

// number of squares to move
static int move = 0;

// Write a "turtle graphics" program
public static void main(String[] args)
{
    // array of drawn lines
    boolean[][] floor = new boolean[ROOM][ROOM];

    // store command
    Commands command;

    // store current direction - default right
    Direction direction = Direction.RIGHT;

    // pen in drawing condition
    boolean draw = false;
    boolean erase = false;

    // provide directions
    directions();

    // get and execute commands until stop
    do {
        // get command
        command = inputCommand();

        // analyse and execute command
        switch(command) {
            case RESET:
                reset(floor);
            case UP:
                draw = false;
                erase = false;
                break;
            case DOWN:
                draw = true;
                erase = false;
                break;
            case RIGHT:
            case LEFT:
                direction = turn(command, direction);
                break;
            case FORWARD:
                floor = move(floor, direction, draw, erase);
                break;
            case DISPLAY:
                display(draw, floor);
                break;
            case ERASE:
                draw = false;
                erase = true;
                break;
            case REVERSE:
                reverse(floor);
                break;
            case POSITION:
                showPosition(direction);
                break;
            case STOP:
            case ERROR:
                break;

        }   // end switch

    } while(command != Commands.STOP);
    // end do-while
}   // end method main

// Provide directions
public static void directions()
{
    System.out.println("This is a turtle graphics program.");
    System.out.println("You have 11 commands available, use the number to the right to use that command:");
    System.out.printf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n", "0: Clear floor.", "1: Pen up, eraser up (default position).", "2: Pen down.", "3: Turn right.", "4: Turn left.",
            "5: Go forward x spaces (enter 5,x)", "6: Display current layout", "7: Erase", "8: Show turtle's position", "9: Quit program", "r: Draw or erase current square.");
    System.out.println("Note: the turtle will draw one more symbol than the number of spaces entered\n\tbecause it will draw in the square it is initially in.");

}   // end method main

// Input command
public static Commands inputCommand()
{
    // store command as string
    String command;

    // input command
    do {
        System.out.print("Enter your command: ");
        command = in.next();

    } while(!valid(command.charAt(0)));
    // end do-while

    // return command as enum value
    switch(command.charAt(0)) {
        case '0':
            return Commands.RESET;
        case '1':
            return Commands.UP;
        case '2':
            return Commands.DOWN;
        case '3':
            return Commands.RIGHT;
        case '4':
            return Commands.LEFT;
        case '5':

            // recover from bad input
            if(command.substring(1).isEmpty() || command.charAt(1) != ',' || command.substring(2).isEmpty())
                return Commands.ERROR;

            move = parseInt(command.substring(2));
            return Commands.FORWARD;
        case '6':
            return Commands.DISPLAY;
        case '7':
            return Commands.ERASE;
        case '8':
            return Commands.POSITION;
        case '9':
            return Commands.STOP;
        case 'r':
            return Commands.REVERSE;
        default:
            return Commands.ERROR;
    }   // end switch
}   // end method inputCommand

// Validate command
public static boolean valid(char c)
{
    for(int ch : commands) {
        if(c == ch)
            return true;

    }   // end for

    // if reach this point, not valid
    return false;

}   // end method valid

// Turn turtle
public static Direction turn(Commands c, Direction d)
{
    // turn turtle
    switch(d) {
        case UP:
            if(c == Commands.RIGHT)
                d = Direction.RIGHT;
            else
                d = Direction.LEFT;

            break;

        case RIGHT:
            if(c == Commands.RIGHT)
                d = Direction.DOWN;
            else
                d = Direction.UP;

            break;

        case DOWN:
            if(c == Commands.RIGHT)
                d = Direction.LEFT;
            else
                d = Direction.RIGHT;

            break;

        case LEFT:
            if(c == Commands.RIGHT)
                d = Direction.UP;
            else
                d = Direction.DOWN;

            break;

    }   // end switch

    return d;

}   // end method turn

// move turtle
public static boolean[][] move(boolean[][] floor, Direction d, boolean draw, boolean erase)
{
    // get direction to move turtle
    switch(d) {
        // move turtle up
        case UP:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[0]--;

                // return to caller if turtle hits wall
                if(position[0] <= 0) {

                    // reset value
                    position[0] = 0;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

        // move turtle down
        case DOWN:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[0]++;

                // make sure turtle does not walk through wall
                if(position[0] >= ROOM) {

                    // reset value
                    position[0] = ROOM-1;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

        // move turtle right
        case RIGHT:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[1]++;

                // make sure turtle does not walk through wall
                if(position[1] >= ROOM) {

                    // reset value
                    position[1] = ROOM-1;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

        // move turtle left
        case LEFT:
            for(; move > 0; move--) {

                // draw, erase, or leave square
                draw(draw, erase, floor);

                // change position
                position[1]--;

                // make sure turtle does not walk through wall
                if(position[1] <= 0) {

                    // reset value
                    position[1] = 0;

                    // print warning
                    System.out.println("Your turtle hit the wall and had to stop.");

                    // stop moving turtle
                    break;

                }   // end if
            }   // end for

            break;

    }   // end switch

    // draw, erase, or leave square
    draw(draw, erase, floor);

    return floor;

}   // end method move

// Draw, erase, or leave square
public static boolean[][] draw(boolean draw, boolean erase, boolean[][] floor)
{
    // if draw, turtle cannot leave square without drawing
    if(draw)
        floor[position[0]][position[1]] = true;

    // if erase, turtle cannot leave square without erasing
    if(erase)
        floor[position[0]][position[1]] = false;

    return floor;

}   // end method draw

// Display array
public static void display(boolean draw, boolean[][] array)
{
    // loop through array
    for(boolean b[] : array) {
        for(boolean bb : b) {

            // draw picture
            if(bb)
                System.out.print("*");
            else
                System.out.print(" ");

        }   // end inner for

        // return at end of row
        System.out.println();

    }   // end outer for
}   // end method display

// Reverse value (draw or erase square) of current position
public static void reverse(boolean floor[][])
{
    floor[position[0]][position[1]] = !floor[position[0]][position[1]];

}   // end method reverse

// Show turtle's position
public static void showPosition(Direction d)
{
    // x-y coordinate
    System.out.printf("(%d, %d)\n", position[1], position[0]);

    // direction
    System.out.print("You are facing ");
    switch(d) {
        case UP:
            System.out.println("up.");
            break;
        case DOWN:
            System.out.println("down.");
            break;
        case RIGHT:
            System.out.println("right.");
            break;
        case LEFT:
            System.out.println("left.");
            break;

    }   // end switch

}   // end method showPosition
// Reset floor to blank
public static boolean[][] reset(boolean[][] floor)
{
    for(boolean b[] : floor)
        for(int i = 0; i < b.length; i++)
            b[i] = false;

    return floor;

}   // end method reset
}   // end class JavaApplication74

```

I wrote this for my programming class about a month ago, so it isn't optimized for golf. I thought you might like to see my solution though.

# Answer
> 1 votes
## Java, 10 Points

```
import java.util.Scanner;
import static java.lang.System.*;

class Turtle{
    public static void main(String...args){
        Scanner s=new Scanner(in).useDelimiter("\\W+");
        for(
            String board = "Lol I'm coding stuff".replaceAll(".","00000000000000000000\n"),
                input,
                x = "0",
                y = "0",
                rotation = "0",
                up = "true",
                mode = "1",
                nop
        ;
            null==(s.hasNext()?null:out.printf(board))
        ;
            nop =
            ((input=s.next()).equals("RESET")
                ?(x = y = rotation = "0") + (up = "true") + (mode = "1")
            :input.equals("STOP")
                ?(s=new Scanner("")).toString()
            :input.equals("DISPLAY")
                ?out.printf(board).toString()
            :input.equals("POSITION")
                ?out.printf("(%s,%s)",x,y).toString()
                :"")+
            (up = input.equals("UP")
                ?"true"
            :input.equals("DOWN")
                ?"false"
                :up)+
            (rotation = input.equals("LEFT")
                ?""+((1+Integer.parseInt(rotation))%4)
            :input.equals("RIGHT")
                ?""+((3+Integer.parseInt(rotation))%4)
                :rotation)+
            (mode = input.equals("DRAW")
                ?"1"
            :input.equals("ERASE")
                ?"0"
                :mode)+
            (input.equals("FORWARD")
                ?
                    ((x = Integer.parseInt(rotation)%2!=0
                        ?x
                    :rotation.equals("0")
                        ?Integer.parseInt(x)+1+""
                        :Integer.parseInt(x)-1+"")+
                    (y = Integer.parseInt(rotation)%2==0
                        ?y
                    :rotation.equals("3")
                        ?Integer.parseInt(y)+1+""
                        :Integer.parseInt(y)-1+""))
                :"")+
            (out.printf("\nx:%s y:%s rot:%s up:%s mode:%s input:%s\n",x,y,rotation,up,mode,input))+
            (board = up.equals("false")
                ?board.replaceFirst("(?<=(?:[01]{20}\n){"+y+"}.{"+x+"}).",mode)
                :board)+
            (Integer.parseInt(x)<0||Integer.parseInt(x)>20||Integer.parseInt(y)<0||Integer.parseInt(y)>20
                ?(board = String.format("Error at position (%s,%s)",x,y)) + (s=new Scanner("")).toString()
                :"")
        );
    }
}

```

`Scanner s=new Scanner(in).useDelimiter("\\W+");` counts as 9 points, and the rest of the main method is just a for-loop's header and so it counts as 1 point.

> Loop header statements each only score one point

---
Tags: atomic-code-golf
---


# Question
Title: Determine which value represents which direction in a path
**Important edit: Earlier, there was an incorrect value in Example 1. It has been fixed.**

You are given a two-dimensional array in which each cell contains one of four values.

Examples:

```
1 2 2 2 2 1        @ . .        X X V
1 3 1 4 1 4        e . @        I C V
2 3 1 3 4 2        H H @        X I V
1 4 4 2 1 3                     V C C
2 2 2 3 2 3                     X X X

```

The four values represent directional arrows (up, down, left, and right), although you don't know which value represents which direction.

The directional arrows form an unbroken path that includes every cell in the array, although you don't know where the start or end points are.

Write some code that determines which direction each of the four values represents and where the start and end points are.

An acceptable return value for an array that contains the values A, B, C, and D would be something like:

```
{ up: A, down: C, left: D, right: B, start: [2, 0], end: [4, 2] }

```

~~Because you can traverse the path both ways (from start to end and from end to start), there will always be more than one correct solution, and there might be more than two.~~ Assume that the inputs you receive (as in the above examples) always have at least one correct solution. In cases where there is more than one correct solution, returning just one of the correct solutions is sufficient.

Shortest code wins. I'll pick the winner after 7 days or 24 hours without a new submission, whichever comes first.

I'm including solutions to the examples above, but I'd encourage you to only check them once you've written your code:

One:

> { up: 3, down: 1, left: 4, right: 2, start: \[0,0\], end: \[2,5\] }

Two:

> { up: '@', down: 'e', left: '.', right: 'H', start: \[1,1\], end: \[0,0\] }

Three:

> { up: 'I', down: 'V', left: 'C', right: 'X', start: \[0,2\], end: \[4,2\] }

# Answer
> 6 votes
## C#

EDIT: Fixed a division and formatting. And added the helper class.

This is the golfed code, 807 chars

```
class M{public int c,x,y,u;}
void G(string[] z){
M K;int[]x={0,0,-1,1},y={-1,1,0,0},I={0,0,0,0};
string[]T={"Up","Down","Left","Right"};
int X,Y,R,n=0,H=z.Length,W=z[0].Length;W-=W/2;var D= string.Join(" ", z).Where(c=>c!=' ').Select(c=>new M(){c=c,x=n%W,y=n++/W}).ToList();n=0;var S=D.GroupBy(k=>k.c).ToDictionary(k=>k.Key,k =>n++);
for(;I[0]<4;I[0]++)for(I[1]=0;I[1]<4;I[1]++)for(I[2]=0;I[2]<4;I[2]++)for(I[3]=0;I[3]<4;I[3]++){
if ((1<<I[0]|1<<I[1]|1<<I[2]|1<<I[3])!=15)continue;
foreach (var Q in D){D.ForEach(p=>p.u=-1);R=1;K=Q;j:if((X=K.x+x[n=I[S[K.c]]])>=0&&X<W&&(Y=K.y+y[n])>=0&&Y<H&&(K=D[X+Y*W]).u<0){
K.u=1;if(++R==D.Count){Console.WriteLine("{4} Start({0}:{1}) End({2}:{3})",Q.x,Q.y,K.x,K.y,string.Join(", ",S.Select(k=>string.Format("{1}: '{0}'",(char)k.Key,T[I[k.Value]])).ToArray()));return;}goto j;}}}
}

```

Results for the three test cases:

> Down: '1', Right: '2', Up: '3', Left: '4' Start(0:0) End(5:2)
> Up: '@', Left: '.', Down: 'e', Right: 'H' Start(1:1) End(0:0)
> Right: 'X', Down: 'V', Up: 'I', Left: 'C' Start(0:2) End(2:4)

This is the raw code without "golf", almost 4,000 characters:

```
class Program
{
    static string[] input1 =  { "1 2 2 2 2 1",
               "1 3 4 4 1 4",
               "2 3 1 3 4 2",
               "1 4 4 2 1 3",
               "2 2 2 3 2 3"};

    static string[] input2 =  { "@ . .",
                                "e . @",
                                "H H @",
               };

    static string[] input3 =  { "0 0 1",
                                "0 0 1",
                                "3 2 2",
               };

    static void Main(string[] args)
    {
        Resolve(input1);
        Resolve(input2);
        Resolve(input3);
        Console.ReadLine();
    }

    class N { public int c; public int x, y, i, u; }

    static void Resolve(string[] input)
    {
        int[] ox = { -1, 1, 0, 0 }, oy = { 0, 0, -1, 1 }, I = { 0, 0, 0, 0 };
        string[] TXT = { "Left", "Right", "Up", "Down" };
        int X, Y, R, n = 0, H = input.Length, W = input[0].Length;
        W -= W / 2;
        N K = null;
        var data = string.Join(" ", input).Where(c => c != ' ').Select(c => new N() { c = c, x = (n % W), y = (n / W), i = n++, u = -1 }).ToList();
        n = 0;
       var S = data.GroupBy(k => k.c).ToDictionary(k => k.Key, k => n++);

        for (; I[0] < 4; I[0]++)
            for (I[1] = 0; I[1] < 4; I[1]++)
                for (I[2] = 0; I[2] < 4; I[2]++)
                    for (I[3] = 0; I[3] < 4; I[3]++)
                    {
                        if (((1 << I[0]) | (1 << I[1]) | (1 << I[2]) | (1 << I[3])) != 15) continue;
                        foreach(var Q in data)
                        {
                            data.ForEach(p => p.u = -1);
                            R = 0;
                            K = Q;
                            while (K != null)
                            {
                                n = I[S[K.c]];
                                X = K.x + ox[n];
                                Y = K.y + oy[n];
                                if (X >= 0 && X < W && Y >= 0 && Y < H)
                                {
                                    n = X + Y * W;
                                    if (data[n].u < 0)
                                    {
                                         data[n].u = K.i;
                                         K = data[n];
                                        R++;
                                        if (R == data.Count - 1)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("Start({0}:{1}) End({2}:{3})", Q.x, Q.y, K.x, K.y);
                                            Console.WriteLine(string.Join(", ", S.Select(k => string.Format("'{0}': {1}", (char)k.Key, TXT[I[k.Value]])).ToArray()));
                                            Action<N> Write = null;
                                            Write = (k) =>
                                             {
                                                 if (k.u != -1)
                                                 {
                                                     Write(data[k.u]);
                                                 }
                                                 Console.Write(string.Format("({0}:{1}){2}", k.x, k.y, k == K ? "\n" : " => "));
                                             };

                                            Write(K);
                                            return;
                                        }
                                        continue;
                                    }
                                }
                                K = null;
                            }
                        }
                    }
        Console.WriteLine("Solution not found");
    }
 }
}

```

These are the results for the three examples:

> Solution not found
>
> Start(1:1) End(0:0) '@': Up, '.': Left, 'e': Down, 'H': Right
>
> (1:1) =\> (0:1) =\> (0:2) =\> (1:2) =\> (2:2) =\> (2:1) =\> (2:0) =\> (1:0) =\> (0:0)
>
> Start(0:0) End(1:1) '0': Right, '1': Down, '3': Up, '2': Left
>
> (0:0) =\> (1:0) =\> (2:0) =\> (2:1) =\> (2:2) =\> (1:2) =\> (0:2) =\> (0:1) =\> (1:1)

# Answer
> 5 votes
## Mathematica 278

Spaces added for "clarity"

```
k@l_ := (s = #~Join~-# &@{{1, 0}, {0, 1}};
         f@r_ := Flatten[MapIndexed[#2 -> #2 + (#1 /. r) &, l, {2}], 1];
         g     = Subgraph[#, t = Tuples@Range@Dimensions@l] & /@
                       Graph /@ f /@ (r = Thread[# -> s] & /@ Permutations[Union @@ l]);
        {t[[#]] & /@ Ordering[Tr /@ IncidenceMatrix@g[[#]]][[{1, -1}]], r[[#]]} & @@@
                                                                 Position[PathGraphQ /@ g, True])

```

Session & Output:

```
 l = l1 = {{1, 2, 2, 2, 2, 1}, {1, 3, 1, 4, 1, 4}, {2, 3, 1, 3, 4, 2},
            {1, 4, 4, 2, 1, 3}, {2, 2, 2, 3, 2, 3}}; ;
 k@l1
 {{{{1, 1}, {3, 6}},
    {1 -> {1, 0}, 2 -> {0, 1}, 3 -> {-1, 0},  4 -> {0, -1}}}}

```

Which is the start Vertex, End Vertex and the transition rules associated with each symbol.

Here is the complementary code to show the oriented graph:

```
sol = sg[[Position[PathGraphQ /@ sg, True][[1, 1]]]];
Framed@Graph[
  VertexList@sol,
  EdgeList@sol,
  VertexCoordinates -> VertexList@sol /. {x_, y_} :> {y, -x},
  VertexLabels -> MapThread[Rule, {VertexList@sol, Flatten@l}],
  EdgeShapeFunction -> GraphElementData["FilledArcArrow", "ArrowSize" -> 0.03],
  ImagePadding -> 20]

```

# Answer
> 2 votes
# Mathematica (151)

```
L = {{1, 2, 2, 2, 2, 1}, {1, 3, 1, 4, 1, 4}, {2, 3, 1, 3, 4, 2},
   {1, 4, 4, 2, 1, 3}, {2, 2, 2, 3, 2, 3}};

PathGraphQ@#~If~Print@{TopologicalSort[#]〚{1,-2}〛,r}&@
Graph@Flatten@MapIndexed[#2->#2+(#/.r)&,L,{2}]~Do~{r,
Thread[Union@@L->#]&/@{-1,0,1}~Tuples~{4,2}}

```

It returns start point, end point, and transition rules. The first index is row, the second is column

```
{{{1,1},{3,6}},{1->{1,0},2->{0,1},3->{-1,0},4->{0,-1}}}

```

Note that my code works even with `{-1,0,1}~Tuples~{4,2}`. For speeding up you can use `Permutations@{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}` instead.

# Answer
> 0 votes
# APL (207)

I couldn't make it shorter than Mathematica, because I couldn't reason in terms of TopologicalSort and such. Smarter people are welcome to squeeze it further.

**Golfed:**

```
{u←∪,t←⍵⋄q r←↑(0≠+/¨r)/⊂[2]p,⍪r←{m←,⍵[u⍳t]⋄v r←⊂[1]⊃{{(↑⍴∪⍵),⊂(↑⍵)(↑⌽⍵)}n↑{3::⍬⋄i←↑⌽⍵⋄⍵,i+i⌷m}⍣n,⍵}¨⍳n←↑⍴,t⋄↑(v=n)/r}¨p←⊂[2]{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵}d←¯1 1,¯1 1×c←¯1↑⍴t⋄⊃('←→↑↓',¨u[q⍳d]),{1+(⌊⍵÷c)(c|⍵)}¨r-1}

```

**Ungolfed:**

```
D←{⎕ML ⎕IO←3 1
    pmat←{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵}   ⍝ utility: permutations of the given vector
    u←∪,t←⍵                    ⍝ the 4 unique symbols in t←⍵
    n←↑⍴,t                     ⍝ number of elements in t
    d←¯1 1,¯1 1×c←¯1↑⍴t        ⍝ the four ∆i (+1, -1, +cols, -cols)
    p←⊂[2]pmat d               ⍝ list of permutations of the four ∆i
    r←{                        ⍝ for each permutation ⍵∊p (=interpretation of the 4 symbols)
        m←,⍵[u⍳t]              ⍝ (ravelled) t-shaped matrix of ∆i, using interpretation ⍵
        v r←⊂[1]⊃{             ⍝ for each starting index ⍵∊⍳n
            v←n↑{              ⍝ trail of visited cells after n steps
                3::⍬           ⍝ if index out of bounds return empty list
                i←↑⌽⍵          ⍝ take last visited index
                ⍵,i+i⌷m        ⍝ follow the directions and add it to the list
            }⍣n,⍵
            (↑⍴∪v),⊂(↑v),↑⌽v   ⍝ number of unique cells, plus start/end indices
        }¨⍳n
        ↑(v=n)/r               ⍝ 1st couple of start/end indices to visit all cells (if any)
    }¨p
    q r←↑(0≠+/¨r)/⊂[2]p,⍪r     ⍝ select first perm. and start/end indices to visit all cells
    ⊃('←→↑↓',¨u[q⍳d]),{1+(⌊⍵÷c)(c|⍵)}¨r-1   ⍝ return char mapping and start/end indices
}

```

**Examples:**

(Indices start at 1)

```
     D⊃'122221' '131414' '231342' '144213' '222323'
 ←  4
 →  2
 ↑  3
 ↓  1
 1  1
 3  6
     D⊃'@..' 'e.@' 'HH@'
 ←  .
 →  H
 ↑  @
 ↓  e
 2  2
 1  1
     D⊃'XXV' 'ICV' 'XIV' 'VCC' 'XXX'
 ←  C
 →  X
 ↑  I
 ↓  V
 3  1
 5  3

```

---
Tags: code-golf
---


# Question
Title: Determine if land is fully enclosed by fences
Imagine a two-dimensional array of boolean values, where the 0s represent squares of grass on a rectangular plot of land and the 1s represent fences.

Write a function that accepts the 2D array as an input and determines whether you can travel from any one area of grass to any other area of grass, using only north/east/west/south movements, without running into a fence.

If any area of grass in the array is fully enclosed by fences (meaning you can't travel N/E/W/S to reach every other area of grass in the array) the function should return false; otherwise, it should return true.

Below are two sample arrays you can use as inputs, although your function should be able to handle not just these but any 2D array of boolean values:

```
0 0 0 0 0
0 1 0 0 0
0 1 1 1 1
0 0 0 0 0
0 0 0 1 1

(should return true)

0 1 0 1 0
0 1 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 1 1 0

(should return false, since the middle 0 in the top row is fully enclosed)

```

Shortest working code wins. I'll pick the winner after either a week has passed or there have been no new submissions within 24 hours.

# Answer
# Matlab 45

```
input('');c=bwconncomp(~ans,4);c.NumObjects<2

```
> 1 votes

# Answer
## APL (39)

```
{∧/,⊃{⍺∨⊖⍵}/{⍵∨(∧\~⍵)∨⌽∧\⌽~⍵}¨s,⊖¨s←⊂⍵}

```

Usage:

```
      board1 board2
 0 0 0 0 0  0 1 0 1 0
 0 1 0 0 0  0 1 1 0 0
 0 1 1 1 1  0 0 0 0 0
 0 0 0 0 0  0 0 0 1 0
 0 0 0 1 1  1 1 1 1 0
      {∧/,⊃{⍺∨⊖⍵}/{⍵∨(∧\~⍵)∨⌽∧\⌽~⍵}¨s,⊖¨s←⊂⍵} ¨ board1 board2
1 0

```
> 8 votes

# Answer
# Mathematica, ~~60~~ 58 chars

```
f=Max@MorphologicalComponents[1-#,CornerNeighbors->1>2]<2&

```

---

Usage:

```
f[{{0, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 1}}]

```

> True

```
f[{{0, 1, 0, 1, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 1, 1, 0}}]

```

> False
> 4 votes

# Answer
## Excel VBA, ~~305~~ 215 Bytes

Yes, *haha VBA*, but the matrix nature of the problem suggets a practical solution in Excel might be interesting (Plus someone has already submitted an answer in my other languages!). Obviously VBA is not going to be the most succinct, but I think it's reasonable.

This flood fills from an arbitrary starting point then checks if any "grass" left

R is a worksheet range with 1's and 0's representing the fences and grass as defined in the problem. Bonus, the playing field doesn't have to be rectangular or even contiguous.

```
0 1 1 1 1
0   0 0 0 0
0 1 1 1 1

```

For example, would return False. The zeros on the right can't be reached from the zeros on the left. The irregular field doesn't break it.

```
Function F(R)
L R, R.Find(0)
F = Not IsNumeric(R.Find(0))
End Function

Sub L(R, S As Range)
If S Or IsEmpty(S) Then Exit Sub
S = 1
L R, S.Offset(1, 0)
L R, S.Offset(-1, 0)
L R, S.Offset(0, 1)
L R, S.Offset(0, -1)
End Sub

```

**Some notes on the golfing.**

I think some chars could be trimmed if the requirement was inverted in regards to 1 and 0, but not enough to make it worth inverting.

VBA insists on a bunch a whitespace (a = b vs a=b), which doesn't help the char count.

S needs to be explicitly declared as a range. If it's left a variant, it turns into a range value rather than a range.

Maybe a better way to branch the flood? I couldn't come up with a loop that saved any chars to send it N/E/S/W

Edit: rethougt the base case on the flood fill, managed to trim quite a bit off by checking if it's at a base case after recursion rather than preventing the recursion.
> 4 votes

# Answer
# Ruby, ~~202~~ ~~198~~ 193

```
a=$<.read.split('
').map(&:split)
f=->x,y{a[x][y]=1
[[-1,0],[1,0],[0,-1],[0,1]].map{|o|d,e=x+o[0],y+o[1]
f[d,e]if a[d]&&a[d][e]==?0}}
f[i=a.index{|x|x.index ?0},a[i].index(?0)]
p !(a.join=~/0/)

```

Does a flood-fill, then checks to see if there are any 0s left.
> 3 votes

# Answer
## PHP 147 202 177 165 149 bytes

**EDIT** I beat my gzip hack with a real php solution.

A little long.... input as a text string, no spaces, rows delimited by newlines. It flood fills with `c`s and then checks to see if there are any zeros left. In the loop I use `exp` as a crude upper bound on the number of iterations required. I take advantage of the symmetry to handle the duplicate cases in less code

```
function f($s){$r=strpos;$n=$r($s,'
');$s[$r($s,'0')]=c;for(;$i++<1<<$n;)$s=strrev(ereg_replace('0(.{'.$n.'})?c','c\1c',$s));return!1==$r($s,'0');}

```

Here is an ungolfed test case:

```
<?php
$s1="00000
01000
01111
00000
00011";

$s2="01010
01100
00000
00010
11110";

function f($s){
    $n=strpos($s,"\n");
    $s[strpos($s,'0')]=c;
    for(;$i<strlen($s);++$i)
        $s=strrev(ereg_replace(
            '0(.{'.$n.'})?c',
            'c\1c'
            ,$s));
    return!1===strpos($s,'0');
}

var_dump(f($s1));
var_dump(f($s2));

```
> 3 votes

# Answer
# Python (219 bytes)

Definitely not the shortest, but it's my first try here, so I'm proud of it:

```
def f(n):
 m=[int(c) for c in n if c!='\n']
 for i in range(len(m)):
  if m[i]<1:m[i]=2;break
 g(m,n.find('\n'),i);return not 0in m
def g(n,w,i):
 for x in i-w,i-1,i+1,i+w:
  if 0<=x<len(n):
   if n[x]<1:n[x]=2;g(n,w,x)

```

It's input should be a String of 0s & 1s where rows are delimited by a newline (\n) character.

Example usage:

```
>>> f("00000\n01000\n01111\n00000\n00011")
True
>>> f("01010\n01100\n00000\n00010\n11110")
False

```
> 2 votes

# Answer
## Python (196)

Standard flood filling.

```
g=raw_input()
m=g.find(' ')
g=g.replace(' ','')
V={}
def D(V,x):
 if V.get(x,0)or g[x]=='1':return
 V[x]=1;[D(V,x+i)for i in 1,-1,m,-m if 0<=x+i<len(g)]
D(V,g.find('0'))
print len(V)==g.count('0')

```

Takes the matrix through STDIN with each row separated by a single space. For example "01010 01100 00000 00010 11110".
> 2 votes

# Answer
# Mathematica 53

```
f=Max@(Symbol@@Names@"I*`i*B*l")[Image[1-#],0,1>2]<2&

```

It calls the internal function `Image`MorphologicalOperationsDump`imageBinaryLabel`, which is similar to `MorphologicalComponents`.

```
f[{{0, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 1}}]
f[{{0, 1, 0, 1, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 1, 1, 0}}]

```

> True
>
> False
> 2 votes

# Answer
# PHP (286 chars)

Way too long, I probably went the long long way.

```
function D($a){$x=count($a);$y=count($a[0]);for($i=0;$i<$x;$i++)$a[$i][-1]=$a[$i][$y]=1;for($j=0;$j<$y;$j++)$a[-1][$j]=$a[$x][$j]=1;for($i=0;$i<$x;$i++){for($j=0;$j<$y;$j++){if($a[$i][$j]!=1){if($a[$i][$j-1]==1&&$a[$i][$j+1]==1&&$a[$i-1][$j]==1&&$a[$i+1][$j]==1)return 0;}}}return 1;}

```

Non-golfed:

```
function D($a)
{
$x=count($a);
$y=count($a[0]);
for ($i=0;$i<$x;$i++)
    $a[$i][-1]=$a[$i][$y]=1;
for ($j=0;$j<$y;$j++)
    $a[-1][$j]=$a[$x][$j]=1;
for ($i=0;$i<$x;$i++)
{
    for ($j=0;$j<$y;$j++)
    {
        if ($a[$i][$j] != 1)
        {
            if ($a[$i][$j-1] == 1 && $a[$i][$j+1] == 1 && $a[$i-1][$j] == 1 && $a[$i+1][$j] == 1)
                return 0;
        }
    }
}
return 1;
}

```
> 1 votes

# Answer
# C#, 235 Bytes

```
int[][]D;int w,h,n;bool Q(int x,int y){var r=x>=0&&x<w&&y>=0&&y<h&&(D[x][y]++==0);if(r){Q(x-1,y);Q(x+1,y);Q(x,y+1);Q(x,y-1);}return r;}
bool P(int[][]B){D=B;w=D[0].Length;h=D.Length; for(int i=0;i<w*h;i++)if(Q(i%w,i/w))n++;return n==1;}

```

It tries to flood fill every cell in the board, it it makes only one flood fill returns true.

```
bool R( int x, int y)
{
    var r = (x >= 0 && x < w && y >= 0 && y < h && D[x, y]++ == 0);
    if (r)
    {
        R(x-1, y);
        R(x+1, y);
        R(x, y+1);
        R(x, y-1);
    }
    return r;
}

public bool Do()
{
    D = Board1;
    w = D.GetLength(0);
    h = D.GetLength(1);
    for (int x = 0; x < w; x++) for (int y = 0; y< h; y++) if (R(x, y)) n++;
    return n == 1;
}

```
> 1 votes

# Answer
# Python 2.X + 3.X: 335 chararcters

Golfed:

```
def f(n):
 x,y=0,0
 z=lambda x,y:y<len(n)and x<len(n[0])and n[x][y]!=1
 while not z(x,y):
  y+=1
  if y==len(n):
   y=0
   x+=1
  if x==len(n[0]):
   return False
 t=set([(x,y)])
 v=set()
 while t:
  (x,y)=t.pop()
  v|=set([(x,y)])
  if z(x+1,y):
   t|=set([(x+1, y)])
  if z(x,y+1):
   t|=set([(x, y+1)])
 return len(v)+sum(map(sum,n))==len(n)*len(n[0])

```

Ungolfed:

```
def f(n):
    """In the following filed, starting from a 0: is it possible to
       get to every other 0?

        >>> f([[0,0,0,0,0],\
               [0,1,0,0,0],\
               [0,1,1,1,1],\
               [0,0,0,0,0],\
               [0,0,0,1,1]])
        True
        >>> f([[0,1,0,1,0],\
               [0,1,1,0,0],\
               [0,0,0,0,0],\
               [0,0,0,1,0],\
               [1,1,1,1,0]])
        False
        >>> f([[1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,1,1,1,1]])
        False
        >>> f([[1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,0,1,1,1],\
               [1,1,1,1,1]])
        True
        >>> f([[1,1,1,1,1],\
               [1,1,1,1,1],\
               [0,1,1,1,1],\
               [1,0,1,1,1],\
               [1,1,0,1,1]])
        False
        >>> f([[1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,1,1,1,1],\
               [1,1,1,1,0]])
        True
    """
    x, y = 0,0
    isValid = lambda x,y: y<len(n) and x<len(n[0]) and n[x][y] != 1
    for i in range(len(n)*len(n[0])):
        x = i%len(n)
        y = i/len(n)
        if isValid(x,y):
            break

    while not isValid(x,y):
        y += 1
        if y == len(n):
            y = 0
            x += 1
        if x == len(n[0]):
            return False # Problem is not clearly defined here
    toGo=set([(x,y)])
    visited=set()
    while toGo:
        (x,y) = toGo.pop()
        visited |= set([(x,y)])
        if isValid(x+1,y):
            toGo |= set([(x+1, y)])
        if isValid(x,y+1):
            toGo |= set([(x, y+1)])
    return len(visited)+sum(map(sum,n)) == len(n)*len(n[0])

if __name__ == "__main__":
    import doctest
    doctest.testmod()

```
> 0 votes

---
Tags: code-golf
---


title: Write a program that deletes itself

text:
# Question
Title: Write a program that deletes itself
For this code golf challenge, you must produce a .exe runnable on windows. After running this .exe from any path with any name it must be deleted after execution.

My reason for limiting this to windows is something like this may be significantly easier if you have some niche OS.

Language(and code) used to produce the .exe is irrelevant, the file size of the executable is what will be measured for this. But still post the code used to produce it, along with the resulting file size.

This is code golf, but again the goal is the smallest executable file.

# Answer
## Assembly, 4608 bytes

The source code for the assembly program, using `nasm` syntax, is as follows:

```
BITS 32

GLOBAL _main
EXTERN _system

SECTION .data
cmd:    db      'echo>).bat start cmd /c del ).bat '
cmdarg: times 128 db 0

SECTION .text

_main:
        mov     eax, [esp + 8]
        mov     esi, [eax]
        mov     edi, cmdarg
copy:   lodsb
        or      al, al
        stosb
        jnz     copy
        push    cmd
        call    _system
        add     dword [esp], 5
        call    _system
        pop     edx
        ret

```

I built the executable using the following commands:

```
nasm -f win32 selfdel.asm
gcc -Wall -s -o selfdel.exe selfdel.obj

```

(I'm curious if the size of the executable would be different if MS's linker were to be used in place of gcc's, but I don't have access to MS development tools.)

Hopefully the code is straightforward enough to not need much explanation. Basically the program creates a batch file that deletes the program (as well as itself) after the program has exited.
> 5 votes

# Answer
# Perl (11 bytes)

```
MZ+unlink$0

```

Save this as `a.exe`, or something, and run it with Perl. And yes, this is Win16 executable, except I don't know what it will do.
> 4 votes

# Answer
## Tcl, 48

```
exec cmd /c "ping ::1&&del [file na [info n]]" &

```

Use a tclsh basekit to create the executable.

**Note**: a process can not delete its own executable, because it is locked when the process is running. So your only option is to get some other process to delete your executable when it stops running.
> 2 votes

# Answer
# C - 857 byte source, 18,432 byte compilation

```
#include <stdlib.h>

size_t stringlen(const char *);
char * stringcat(char *, const char *);

main(int argc, char *argv[])
{
    if(argc > 0)
    {
        char *str = calloc(stringlen(argv[0])+11, sizeof(char));
        stringcat(str, "start del ");
        stringcat(str, argv[0]);
        system(str);
    }
}

/* Simple implementation of strcat to avoid including string.h */
char * stringcat(char *dest, const char *source)
{
    size_t i=0,j=0;
    while(dest[i] != '\0')
    {
        ++i;
    }

    while(source[j] != '\0')
    {
        dest[i+j] = source[j];
        ++j;
    }
    dest[i+j] = '\0';
    return dest;
}

/*Simple implementation of strlen to avoid including string.h */
size_t stringlen(const char *str)
{
    size_t i=0;
    while(str[i] != '\0')
    {
        ++i;
    }
    return i;
}

```

Compiled with:

```
gcc self-delete.c -pedantic -s -o self-delete.exe

```

It is now tested and works perfectly.
> 1 votes

# Answer
# Python (59 bytes)

```
import os,sys;os.remove(sys._getframe().f_code.co_filename)

```
> 0 votes

# Answer
## Assembly - 1548 bytes

Executes a delayed system command to find and delete itself

```
EXTERN system
IMPORT system msvcr100.dll

SECTION .text USE32
GLOBAL main
main:
    push string
    call [system]
    ret

string:
    db "start cmd /C ", 34, "timeout /t 3&for /f %a in ('dir /b *.exe') do (find ", 34, "someuniquestring134123asdfasd41324", 34,  " %a &if not errorlevel 1 del %a)", 34, 0

```

Compiled with:

```
nasm.exe -f obj filename.asm
alink.exe -oPE -entry main filename.obj

```

The executed script:

```
timeout /t 3
for /f %a in ('dir /b *.exe') do (
    find "someuniquestring134123asdfasd41324", %a
    if not errorlevel 1 del %a
)

```
> 0 votes

# Answer
## HTML + JS (33)

```
<body onload=document.write('')>

```
> -1 votes

---
Tags: code-golf
---


title: Thinking outside the box

text:
# Question
Title: Thinking outside the box
You are trying to fit a sphere into a 5-sided box, but sometimes it does not fit completely. Write a function to calculate how much of the sphere is outside (above the rim of) the box.

There are 3 possible situations:

* The sphere fits completely in the box. The answer will be 0.
* The sphere sits on the rim of the box. The answer will be more than half of the total volume.
* The sphere sits on the bottom of the box.

You can see each situation here:

You must write a program or function to compute this value to at least 4 significant digits.

Input: 4 non-negative real numbers in whatever format is convenient\* - width, length, depth of the box (interior measurements), and diameter of the sphere.

Output: 1 non-negative real number in a usable format\* - the total volume (not the percentage) of the sphere outside the box.

<sub>* must be convertible to/from a decimal string</sub>

You are encouraged to limit your use of trigonometry as much as possible.

This is a popularity contest, so **think outside the box!**

# Answer
## Forth

Please find, below, a sphere outside the box.

The "sphere" is the volume-computing function `f`. The reference test cases compose the "box".

```
                     ( x y z d -- v )
                 : f { F: z F: d } d f2/
              { F: r } fmin { F: m } m f2/ {
             F: b } d m f<= d z f<= and if 0e
             else r r r f* b b f* f- fsqrt f-
              { F: t } d m f<= t z f> or if d
               z f- else d t f- then r 3e f*
                  fover f- pi f* fover f*
                      f* 3e f/ then ;

                     1e                 1e
                     1e                 1e
                     f                  f.
            cr       1e        1e       0e
            1e       f         f.       cr
            1e       1e 0.5e 1e f f. cr 1e
            0.999e 1e          1e     f
            f.  cr            0.1e 1e
            1.000e 0.500e f f. cr

```

Output:

```
0.
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212

```
> 20 votes

# Answer
## Java - integer based

This program does not use pi and does not call any external function - not even sqrt. It only uses simple arithmetic - `+`, `-`, `*` and `/`. Furthermore, other than a scaling step, it works exclusively with integers. It basically divides the sphere into little cubes and counts the ones that are outside the box.

```
public class Box {
    private static final int MIN = 10000;
    private static final int MAX = MIN * 2;

    private static final int[] SQ = new int[MAX * MAX + 1];

    static {
        int t = 1;
        for (int i = 1; i <= MAX; ++i) {
            while (t < i * i) SQ[t++] = i - 1;
        }
        SQ[MAX * MAX] = MAX;
    }

    public static long outsideInt(int r, int w, int z) {
        int r2 = r * r;
        int o = z - r + 1;
        if (w < r * 2) {
            int t = 1 - SQ[r2 - w * w / 4];
            if (t < o) o = t;
        }
        long v = 0;
        for (int i = o; i <= r; ++i) {
            int d = r2 - i * i;
            int j0 = SQ[d];
            v += 1 + 3 * j0;
            for (int j = 1; j <= j0; ++j)
                v += 4 * SQ[d - j * j];
        }
        return v;
    }

    public static double outside(double x, double y, double z, double d) {
        double f = 1;
        double w = x < y ? x : y;
        double r = d / 2;
        while (r < MIN) {
            f *= 8;
            r *= 2;
            w *= 2;
            z *= 2;
        }
        while (r > MAX) {
            f /= 8;
            r /= 2;
            w /= 2;
            z /= 2;
        }
        return outsideInt((int) r, (int) w, (int) z) / f;
    }

    public static void main(final String... args) {
        System.out.println(outside(1, 1, 1, 1));
        System.out.println(outside(1, 1, 0, 1));
        System.out.println(outside(1, 1, 0.5, 1));
        System.out.println(outside(1, 0.999, 1, 1));
        System.out.println(outside(0.1, 1, 1, 0.5));
    }
}

```

Output:

```
0.0
0.5235867850933005
0.26178140856157484
0.27938608275528054
0.06542839088004015

```

In this form, the program requires more than 2GB memory (works with `-Xmx2300m` here) and is prettty slow. It uses the memory to precalculate a bunch of square roots (arithmetically); it's not really necessary, but without that it would be a LOT slower. To improve both memory needs and speed, reduce the value of the `MIN` constant (that will decrease the accuracy though).
> 5 votes

# Answer
# Python 2 (Array-based approach)

It creates an array of arrays with truth-values if a specific square in that grid is inside the circle or outside the circle. It should get more precise the bigger the circle is you draw. It then selects either an area below or above a certain row and counts the amount of squares that belongs to the circle and divides that by the amount of squares that are in the entire circle.

```
import math as magic
magic.more = magic.pow
magic.less = magic.sqrt

def a( width, length, depth, diameter ):
  precision = 350 #Crank this up to higher values, such as 20000

  circle = []
  for x in xrange(-precision,precision):
    row = []
    for y in xrange(-precision,precision):
      if magic.less(magic.more(x, 2.0)+magic.more(y, 2.0)) <= precision:
        row.append(True)
      else:
        row.append(False)
    circle.append(row)

  if min(width,length,depth) >= diameter:
    return 0
  elif min(width,length) >= diameter:
    row = precision*2-int(precision*2*float(depth)/float(diameter))
    total = len([x for y in circle for x in y if x])
    ammo = len([x for y in circle[:row] for x in y if x])
    return float(ammo)/float(total)
  else:
    #Why try to fit a sphere in a box if you can try to fit a box on a sphere
    maxwidth = int(float(precision*2)*float(min(width,length))/float(diameter))
    for row in xrange(0,precision*2):
      rowwidth = len([x for x in circle[row] if x])
      if rowwidth > maxwidth:
        total = len([x for y in circle for x in y if x])
        ammo = len([x for y in circle[row:] for x in y if x])
        return float(ammo)/float(total)

```
> 2 votes

# Answer
## Python 2.7, Spherical Cap Formula

This version will throw a runtime warning in some cases, but still outputs the correct answer.

```
import numpy as n
x,y,z,d=(float(i) for i in raw_input().split(' '))
r=d/2
V=4*n.pi*r**3/3
a=n.sqrt((d-z)*z)
b=min(x,y)/2
h=r-n.sqrt(r**2-b**2)
c=lambda A,H: (3*A**2+H**2)*n.pi*H/6
print(0 if d<=z and r<=b else c(a,d-z) if r<=b and z>r else V-c(a,z) if r<=b or z<h else V-c(b,h))

```

For 11 characters more, I can get rid of the warning.

```
import math as m
x,y,z,d=(float(i) for i in raw_input().split(' '))
r=d/2
V=4*m.pi*r**3/3
if d>z:
    a=m.sqrt((d-z)*z)
b=min(x,y)/2
h=r-m.sqrt(r**2-b**2)
c=lambda A,H: (3*A**2+H**2)*m.pi*H/6
print(0 if d<=z and r<=b else c(a,d-z) if r<=b and z>r else V-c(a,z) if r<=b or z<h else V-c(b,h))

```

Here are the test cases run on version 1:

```
$ python spherevolume.py
1 1 1 1
0
$ python spherevolume.py
1 1 0 1
0.523598775598
$ python spherevolume.py
1 1 .5 1
0.261799387799
$ python spherevolume.py
1 .999 1 1
0.279345334324
$ python spherevolume.py
.1 1 1 0.5
spherevolume.py:65: RuntimeWarning: invalid value encountered in sqrt
  a=n.sqrt((d-z)*z) or b
0.065429944144

```
> 2 votes

# Answer
# Mathematica

Using numerical integration with proper limits.

```
f[width_, length_, height_, diam_] :=
 With[{r = diam/2, size = Min[width, length]/2},
  Re@NIntegrate[
    Boole[x^2 + y^2 + z^2 < r^2], {x, -r, r}, {y, -r, r},
      {z, -r, Max[-r, If[size >= r, r - height, Sqrt[r^2 - size^2]]]}]
  ]

```
> 1 votes

# Answer
## Reference Implementation - C#

```
using System;

namespace thinkoutsidethebox
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(OutsideTheBox(1, 1, 1, 1));
            Console.WriteLine(OutsideTheBox(1, 1, 0, 1));
            Console.WriteLine(OutsideTheBox(1, 1, 0.5, 1));
            Console.WriteLine(OutsideTheBox(1, 0.999, 1, 1));
            Console.WriteLine(OutsideTheBox(0.1, 1, 1, 0.5));
        }

        static double OutsideTheBox(double x, double y, double z, double d)
        {
            x = Math.Min(x, y);
            double r = d / 2; // radius
            double xr = x / 2; // box 'radius'
            double inside = 0; // distance the sphere sits inside the box
            if (d <= x && d <= z) // it fits
            {
                return 0;
            }
            else if (d <= x || r - Math.Sqrt(r * r - xr * xr) > z) // it sits on the bottom
            {
                inside = z;
            }
            else // it sits on the rim
            {
                inside = r - Math.Sqrt(r * r - xr * xr);
            }
            // now use the formula from Wikipedia
            double h = d - inside;
            return (Math.PI * h * h / 3) * (3 * r - h);
        }
    }
}

```

Output:

```
0
0.523598775598299
0.261799387799149
0.279345334323962
0.0654299441440212

```
> 0 votes

# Answer
# Ruby

Let's see...
If the box is fully inside, then width\>diameter; length\>diameter and height\>diameter.
That should be the 1st check to run.

If it's sitting at the bottom, then w\>d ; l\>d and h `V=(pi*h^2 /3)*(3r-h)` So in that case, We just get the height and run it through that.

If it's stuck, we use a similar formula (`V=(pi*h/6)*(3a^2 + h^2)`). In fact our earlier formula is based on this one! Essentially, we use that, and a is simply the smaller one of w and l. (hint, we can get height by doing `h=r-a`)

Now the code!

```
def TOTB(wi,le,hi,di)
  if wi>=di and le>=di and hi>=di
    res = 0
  elsif wi>=di and le>=di
    r = di/2
    res = 3*r
    res -= hi
    res *= Math::PI
    res *= hi*hi
    res /= 3
  else
    r = di/2
    if wi>le
      a=le
    else
      a=wi
    end #had issues with the Ternary operator on ruby 2.2dev
    h = r-a
    res = 3*a*a
    res += h*h
    res *= Math::PI
    res *= h
    res /= 6
  end
  res
end

```

Note\** I didn't test it too much, so an error may have crept in, if anyone notices one, do tell!
The math is solid though.
Shorter version:

```
v1 = ->r,h{(3*r -h)*Math::PI*h*h/3}
v2 = ->r,a{h=r-a;((3*a*a)+(h*h))*h*Math::PI/6}
TOTB = ->wi,le,hi,di{(di<wi&&di<le&&di<hi)?0:((di<wi&&di<le)?v1[di/2,hi]:v2[di/2,((wi>le)?le:wi)])}

```

(Now I know for sure that getting h for v2 is done differently, but I'll fix it later.
> 0 votes

# Answer
**c++**

```
#define _USE_MATH_DEFINES   //so I can use M_PI
#include <math.h>           //so I can use sqrt()
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    double w;
    double l;
    double d;
    double sd;
    double min_wl;
    double pdbd;
    double sl;
    cin >> w >> l >> d >> sd;

    min_wl = min(w, l);
    if(sd <= min_wl)
    {
        pdbd = 0.0;
    } else
    {
        pdbd = (sqrt((((sd/2)*(sd/2))-((min_wl/2)*(min_wl/2)))) + (sd/2));
    }
    sl = sd - d;

    if(sd <= min(min_wl, d))
    {
        cout << 0;
        return 0;
    } else if((sl < pdbd) && (pdbd > 0.0))    //sits on lip of box
    {
        cout << (M_PI * (((sd/2) * pdbd * pdbd) - ((pdbd * pdbd * pdbd)/(3))));
        return 0;
    } else                  //sits on bottom of box
    {
        cout << (M_PI * (((sd/2) * sl * sl)-((sl * sl * sl)/(3))));
        return 0;
    }
    return 0;
}

```

My code finds the volume of the solid of rotation of the graph of some portion of a half-circle. `pdbd` holds the linear distance of the projection of a point on the surface of the sphere that touches the lip of the box to the diameter of the sphere that, if extended, would be normal to the bottom of the box. The two expressions that contain `M_PI` are basically the anti-derivative of the integral of `pi * -(x^2)+2rx` with respect to x (where x is a measure of the length along the above mentioned diameter through the sphere and where r is the radius of the sphere) evaluated at either `pdbd` or the difference of the sphere diameter and the box depth depending on the particular case that occurs with the different dimensions.
> 0 votes

---
Tags: math, popularity-contest, geometry
---


title: Find the next "interesting" time

text:
# Question
Title: Find the next "interesting" time
I happened to glance at my watch today at exactly 11:11:11 (and today is 1/11; too bad it's not 2011), and that got me thinking: *I know! I should make a code golf question out of this! I'm a dork.*

Anyway, your challenge is to take an hour, minute, and second as input, and output the next "interesting" time. Here, I will define interesting as these steps:

1. Concatenate the hour, minute, and second. (For example, at 4:14:14, this would be 41414.)
2. Check for consecutive groups of one, two, or three that span the length of the entire string. For example, I could find `[41][41][4]` in the example time (if the group cannot reach through the string, just cut it off like I did in this example). Another example: in the time in my first example at the beginning of the question, it would be `[1][1][1][1][1][1]`, `[11][11][11]`, or `[111][111]`.
3. Is there a consecutive group that goes all the way through the string? If so, the time is "interesting!" Otherwise, it's not.

The input can be in any *reasonable* format, but it must not be hardcoded. The output can also be in any *reasonable* format, and it need not be in the same format as the input.

If you use network access for some reason, **all** bytes downloaded from the network count to your score.

This is ; shortest code in bytes wins.

# Answer
> 2 votes
## J, ~~113~~ ~~99~~ 90

Probably still quite golfable.

```
f=:t#:[:(>:^:([:(3&g+:2&g=.[:*/]=(]$)${.)@(":@{.,3}.7":100#.1,])t#:])^:_)1+(t=.24,2$60)#.]

```

Takes a vector `(h m s)` as input, and returns a vector in the same format as output.

Examples:

```
   f 0 0 0
0 1 0
   f 4 14 14
4 14 41
   f 23 59 59
0 0 0
   f 3 14 15
3 14 31

```

# Answer
> 1 votes
# Haskell - ~~227~~223

That's one way of doing it.

```
    import Data.List
e _ []=False
e f s=let (h,t)=f s in t`isPrefixOf`h||h`isPrefixOf`t&&e f t
i [a,b,s]=head[t|s<-[s+1..],f<-map splitAt[1..3],let m=b+s`div`60;h=a+m`div`60;t=[h`mod`24,m`mod`60,s`mod`60],e f$concatMap show t]

```

Examples

```
λ: i [11,11,11]
[11,21,1]
λ: i [4,14,14]
[4,14,41]

```

# Answer
> 1 votes
# Mathematica 125

```
F=Do[#~MatchQ~{#〚-1〛..,_}&&Break@#&@Partition[(i=IntegerDigits)@f[n~i~60,100],m,m,1,a_],
{n,#~(f=FromDigits)~60+1,7^6},{m,3}]&

```

It returns a pattern of the next interesting time:

```
F@{11, 11, 11}
F@{4, 14, 14}

```

> {{1, 1, 2}, {1, 1, 2}}
>
> {{4, 1, 4}, {4, 1, a\_}}

`a_` marks the end of the time.

# Answer
> 1 votes
# Lua

I've got four different solutions, as I wasn't sure about some of the requirements.

**Version 1: removal of 0s, command line input as well as os.time() backup (315)**

Minimised:

```
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end h,g,e,u=os.date,os.time(y),":",tonumber while 1 do g=g+1 b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) a=b..c..d for x=1,#a/2 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end end end end

```

Full version with comments:

```
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end --get command line arguments
h,g,e,u=os.date,os.time(y),":",tonumber --set up references, if command line arguments accepted use y else use current time
while 1 do
    g=g+1
    b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) --get HH:MM:SS seperately (which allows removal of the zeroes with tonumber())
    a=b..c..d  --concat
    for x=1,#a/2 do  --check up to half of the string
        p=1
        for _ in a:gmatch(a:sub(1,x))do --for each match
            p=p+1  --count number of matches
            if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end --if matches span entire string, cheer (and print in a pretty format)
        end
    end
end

```

The other versions are very similar, so I will only post the minimised versions:

**Version 2: no command line input (239)**

```
h,g,e,u=os.date,os.time(),":",tonumber while 1 do g=g+1 b,c,d=u(h("%H",g)),u(h("%M",g)),u(h("%S",g)) a=b..c..d for x=1,#a/2 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>math.ceil(#a/x) then print(b..e..c..e..d)return 1 end end end end

```

**Version 3: no 0 removal, with command line input (240)**

```
z=arg if z[1] then y={hour=z[1],min=z[2],sec=z[3],day=1,month=1,year=1}end h,g=os.date,os.time(y) while 1 do g=g+1 a=h("%H%M%S",g) for x=1,3 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>6/x then print(h("%T",g))return 1 end end end end

```

**Version 4: none of the fancy stuff (no 0 removal or command line input) (164)**

```
h,g=os.date,os.time() while 1 do g=g+1 a=h("%H%M%S",g) for x=1,3 do p=1 for _ in a:gmatch(a:sub(1,x))do p=p+1 if p>6/x then print(h("%T",g))return 1 end end end end

```

**Usage instructions**

In a terminal, run (versions 1 and 3)

```
lua interesting.lua HOURS MINUTES SECONDS

```

or just

```
lua interesting.lua

```

If you want it to go off the system clock.

Is there a prize for feature completeness? :P

---
Tags: code-golf, date
---


title: Produce a palindrome from this text

text:
# Question
Title: Produce a palindrome from this text
* Copy and paste or `curl` this text: http://lorem-ipsum.me/api/text
* Using any language make the text palindromic.
* You may remove letters.
* You may rearrange letters.
* The goal is to make the text palindromic by the **sequence of the letters and spaces**. The end result might not contain words. It will be merely a sequence of letters and spaces.
* Capital letters are considered the same as lowercase letters.
* You may use each letter only once, or you may remove the letter.
* You may also use each space only once. Or you may remove the space.
* The result should be the longest palindrome you can programmatically create from the text.
* While you could technically print just the letters `AaA` or something similar to it, that is not what I am looking for.
* Your palindrome creator should work with any text.
* A palindrome, by definition, is a word, phrase, number, or other sequence of symbols that reads the same backward as forward. A sequence of symbols that reads the same backward as forward is the acceptable palindromic definition I am looking for in this `CodeGolf` example.
* Scoring will be `Length of palindrome` / `Length of code`. The winner is the one with the highest score.

**Text**:

```
Lorem ipsum dolor sit amet, consectetur adipisicing elit, possimus voluptatem do ut vel deserunt laborum. cupidatat libero minim at a aute minus cupiditate excepturi reiciendis blanditiis, atque vero. dolorem dolores dolore corrupti aute recusandae repellat recusandae modi deleniti libero nostrud aute delectus quidem alias odio nostrum pariatur. placeat minus similique a aliquip facere ullamco officiis eligendi ad at magnam commodi maxime.

Adipisicing modi enim similique maxime ex nisi sed eu suscipit earum corrupti assumenda perferendis cumque maiores qui praesentium nobis. Sed voluptas consequatur voluptates rerum facilis qui dolor commodi minim provident, magnam facere, tenetur. Aliqua voluptatibus delectus illum dolorem excepturi aliquip duis odio. Excepturi similique hic iusto eu consectetur laboriosam quidem esse eiusmod, anim. Eu consequatur magnam tempor vel.

Nobis incididunt eius cum distinctio magnam velit facilis libero ullam, tenetur distinctio eius eveniet. Anim possimus expedita fugiat facilis vel consequatur in temporibus laboriosam at molestiae velit cupidatat. Vel consequatur voluptate cum sint dolores ullamco quas omnis quibusdam id officiis tenetur voluptas, tempore tenetur aliquam debitis. Nostrud, do in numquam magnam quia voluptate incidunt accusamus distinctio officia molestiae fuga. Nam corporis ex quos recusandae sed.

Ullamco incidunt cupidatat eos voluptate delectus nostrud nisi irure quod quis alias. Fuga quam autem mollit ex dolores quod non tempor mollitia quas labore sapiente a anim deserunt expedita minus. Ex pariatur accusamus alias deleniti quo, quia similique voluptas. In voluptatibus esse perferendis commodo aute repellendus accusamus laboriosam deserunt aute possimus laboriosam.

Labore hic tempora, ad iusto hic aliqua ducimus. Distinctio omnis tempore incididunt ut sed mollit, quidem, aute sunt eius eveniet, vel distinctio cupiditate eius atque. Fuga asperiores tenetur enim, provident similique aliqua nostrum ad dolorum, molestiae, repudiandae ad sunt. Consequatur ullamco a nisi aliqua non omnis officia.

Labore sapiente obcaecati libero quas eos incididunt. Saepe quas voluptas mollitia consectetur dolores dolores officiis id, quo, laboriosam reprehenderit alias. Voluptates cumque dignissimos, cumque dolor. Incididunt minima consectetur harum et.

```

# Answer
> 3 votes
# Mathematica ~~146~~ 92 chars (score 2130/92 = 23.15)

## Shorter Version (92 chars)

This palindrome has the characters grouped,

```
""<>{s=({#[[1]],Length@#~Quotient~2}&/@ Gather@Characters@t)
/.{c_,n_}:>c~Table~{n},Reverse@s}

```

---

## Longer Version (146 chars)

This will return a maximum length, randomized palindrome from t. Because capital letters are equivalent to lowercase letters, I converted all capitals to lower case. (This can be changed if necessary.)

```
f@t_ := "" <> Join[s = RandomSample[ Flatten[({#[[1]], Quotient[Length[#], 2]} & /@
     Gather[Characters@ToLowerCase@t]) /. {c_, n_} :> ConstantArray[c, n]]], Reverse@s]

```

**Example**:

When `t` is the suggested, Lorem ipsum, text. (Ignore line returns; all line returns were generated via the SE editor.)

> "ti,iopexri rpiuu opaat tismimetnesa lvuot oiaiu oaaittcoar nc muapua elhpibemu utin ia f ihide sdourgeeic e oaasa.marsae dstircd ci ndn rs t egoaiq.aeatntreusng xi a lumalnoiieqqeq cc otiueasniieu nrpupdlmnai o cdsm t gt.iccmittli i t tu.rust.li maui bea gqiceeo pncu eonttecvtutqun eaaariusoquppsedlqu scrddmt esiafidurs hitlpna nlamltire ivmumbabi nbuderup td x uuualsoq.eiib li olel ru aeelau
> idbc lrop iil ssur anda o scnmsr ,m uri,teo esmiaveuomrt ldqqaid ihi snsr spueeoevcre oe msirulaleaisormm.oicolarsstteo td aatncn ieqrsuam boid te utcf eccp siacu m etnqutlacniiereltiulqemltaqx a qtdlxmliibileoheesimittlusqemooamuiippeaiilcgudsatfsiemamsc irn rsgoi, ie nmteiaiiptraned alsomsui noru ic,mditi ic ouud oadmv iudinrfuludet eeiidueel nndaemcrepnioe sials unetuamconn,i ubpo eiu ei dsn equi,ue ostmp udiatqu dalmau nueeiit ln e mioancteop ntiiao ts noeefubtefrit ldeop earnmsm oas
> d.catirotulvliodiellmesurotiomsmduia.nauenb iuiroimduriohs.lrndsaroc t inidrssq apeuionnlaa eqdroounosmotidr arxr o taouarut ussce uamae is.dcadaimuoaprad iifl i lmml i lfii darpaoumiadacd.si eamau ecssu turauoat o rxra rditomsonuoordqe aalnnoiuepa qssrdini t corasdnrl.shoirudmioriui bneuan.aiudmsmoitorusemlleidoilvlutoritac.d
> sao msmnrae poedl tirfetbufeeon st oaiitn poetcnaoim e nl tiieeun uamlad uqtaidu pmtso eu,iuqe nsd ie uie opbu i,nnocmautenu slais eoinpercmeadnn leeudiiee tedulufrnidui vmdao duuo ci itidm,ci uron iusmosla denartpiiaietmn ei ,iogsr nri csmameisftasdugcliiaeppiiumaoomeqsulttimiseehoelibiilmxldtq a xqatlmeqluitlereiincaltuqnte m ucais pcce fctu et diob mausrqei ncntaa dt oettssralocio.mmrosiaelalurism eo ercveoeeups rsns ihi diaqqdl trmouevaimse oet,iru m, rsmncs o adna russ lii porl cbdi ualeea ur lelo il biie.qoslauuu x dt puredubn ibabmumvi eritlmaln anpltih srudifaise tmddrcs uqldesppuqosuiraaae nuqtutvcettnoe ucnp oeeciqg aeb iuam il.tsur.ut t i ilttimcci.tg t msdc o ianmldpuprn ueiinsaeuito cc qeqqeiionlamul a ix gnsuertntaea.qiaoge t sr ndn ic dcritsd easram.asaao e cieegruods edihi f ai nitu umebiphle aupaum cn raocttiaao uiaio touvl asentemimsit taapo uuipr irxepoi,it"

# Answer
> 2 votes
## Python, 1/4

A single character is a palindrome, so...

```
s[0]

```

presuming the target text is stored in `s`.

# Answer
> 1 votes
## Ruby, 78 chars

Reads from standard input.

```
s=gets.downcase.chars.group_by{|c|c}.map{|k,v|k*(v.size/2)}*''
$><<s+s.reverse

```

For example, passing the text from @LegoStormtrooper's first comment on the question:

```
What if the text isn't symmetric? For example, the text of this comment in this question can't be palindromed as it has more than one letter that occurs an odd number of times, hence it can be flipped without duplicating a letter.

```

The program will return this:

```
whhhhhaaaaaattttttttttttt                    iiiiiiiffeeeeeeeeeeexssssnnnnnn'mmmmrrrrccccooooopplll,uubddddddbuu,lllppoooooccccrrrrmmmm'nnnnnnssssxeeeeeeeeeeeffiiiiiii                    tttttttttttttaaaaaahhhhhw

```

If you don't want the punctuation at all (on re-reading the question it sounds like you only want letters and spaces) this will work (87 chars):

```
s=gets.downcase.scan(/[a-z ]/).group_by{|c|c}.map{|k,v|k*(v.size/2)}*''
$><<s+s.reverse

```

Which returns:

```
whhhhhaaaaaattttttttttttt                    iiiiiiiffeeeeeeeeeeexssssnnnnnnmmmmrrrrccccoooooppllluubddddddbuulllppoooooccccrrrrmmmmnnnnnnssssxeeeeeeeeeeeffiiiiiii                    tttttttttttttaaaaaahhhhhw

```

# Answer
> 1 votes
## Python 2.7 - 82

Takes an input, converts it all to lower case, makes an array with half (rounded down) of each character, then prints that out concatenated to itself in reverse.

Worst case scenario, it outputs an empty string if every character is unique.

```
L=raw_input().lower()
o=[x*(L.count(x)/2)for x in set(L)]
print''.join(o+o[::-1])

```

# Answer
> 1 votes
## Python, 107

```
s="""Lorem ipsum dolor sit amet, consectetur adipisicing elit, hic a sunt odio eius culpa labore. vero vero possimus irure quidem est saepe ut do quis excepturi incididunt. magna eveniet nisi enim quidem distinctio.

Ullam saepe officiis consequatur, provident soluta blanditiis sunt possimus minima impedit corporis voluptatibus occaecat distinctio mollitia, commodo et. Facilis autem cum dolor dignissimos magna modi nisi labore animi incididunt numquam quam voluptatem optio tempor provident fugiat ullam. Consequat tempora numquam minim tempore eius perferendis ullamco labore corporis officiis. Saepe deserunt a asperiores rerum quis excepteur odio voluptatibus ducimus itaque.

Qui nam provident corrupti sunt velit est laboris. Delectus tempora possimus quas cillum exercitation debitis cupidatat omnis voluptatibus. A dignissimos saepe repellat nostrum quaerat rerum molestias, alias dolorum provident fuga repellat sed, esse cum illum culpa animi. Placeat atque necessitatibus nostrud saepe maxime cupiditate, impedit elit iure hic.

Excepturi id numquam odio aliquam maiores, expedita eveniet. Repellendus eos voluptates quaerat excepteur sunt velit consectetur vel eius ad voluptatem corporis cillum tempore incidunt molestiae. Atque tempora, duis vero, tempore et sint nostrud molestiae laboris eligendi maxime nam reprehenderit.

Fugiat anim commodo sed incidunt, et aut, labore corrupti velit incididunt quaerat. Aliquam saepe minima sunt minima eos, nobis, eu delectus itaque optio consequatur voluptatibus delectus ex sapiente deserunt dolor. Optio doloribus officiis ducimus dolores.

Voluptas commodo cupidatat molestiae tempora quia consequatur. Repellendus ea rerum exercitationem, odio voluptatem ullam perferendis ea animi deleniti deleniti quaerat magnam repellat voluptates. Obcaecati aut exercitation dolore nisi eos."""

import itertools
t=''.join(''.join(list(g[1])[1::2]) for g in itertools.groupby(sorted(s)))
print t+t[::-1]

```

`itertools.groupby(sorted(s))` groups identical characters. `list(g[1])[1::2]` takes each group and cuts it in half, rounding down for odd-length groups. It then joins the lists together and prints the resulting string concatenated with its reverse. Could be improved in a number of ways, as already demonstrated by others.

---
Tags: code-challenge, palindrome
---