# Question
Title: Shortest program whose concatenated program+output is a permutation of the 95 printable ASCII characters
Write a program that's as short as possible (as measured by byte-count), takes no input, contains no comments, and outputs a character string/sequence, such that concatenated program+output is exactly 95 characters long and **contains every printable ASCII character exactly once**, i.e. program+output is a permutation of the 95 characters with ASCII codes 32-126:

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

```

In the event of a tie, the winner is the entry whose (95-character) concatenated program+output is closest to the above string, as measured by the Levenshtein edit-distance (i.e. the number of single-character deletions, insertions, or substitutions required to put it into ASCII order).

# Answer
### GolfScript, 14 characters

```
{`),32>46-^}.~

```

Output:

```
 !"#$%&'(*+/015789:;<=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_abcdefghijklmnopqrstuvwxyz|

```
> 12 votes

# Answer
## Perl, 89 characters

This is the best I've been able to do so far:

```
q< !"#%&'()+/8:?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghjklmosuvwxz|>;
print~-$=.73*2,y[]{}

```

For those not conversant in Perl minutae, the two arguments to the `print` statement could be rendered as `~(-($=)) . (73 * 2)` and `tr///`.

The program outputs 6 characters:

```
591460

```

Unfortunately every single iteration construct that I can think of in Perl (`for`, `while`, `until`, `map`, `grep`) shares at least one character with `print`. If newlines were allowed to appear in the output, then I could use Perl 5.010 to eke out an 87-character solution:

```
q{ !"#%&'*,-./0:;>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^`bcdfgjkmnoprtuvxz|~}while($_+=say)<9

```
> 6 votes

# Answer
## PHP 67 bytes

```
<?=U4eB1gkFdA6J9snZD2IE8y5PhwQV^xHGmqYMfNjKpbR3vcLalCWi0_TtrOSXouz;

```

Output:

```
-|"/@>& *+}:[!],'~(){.\`7#%$

```

It seems like there should be a 65 byte solution, outputting 30 chars instead of only 28, but I couldn't get it to line up. The 6 unused characters `OSXouz` have been tacked onto one of the string literals instead.

**Edit:** Upon further reflection, it is not possible to generate more than 28 characters in this manner. `UPPER ^ lower` will always result in a character between 32 and 63, so all 10 digits are required for `@[\]_`{|}~`. Four of the remaining 22 are used in the script itself, leaving only 18 which can be obtained with letters alone. The tiebreaker could be improved significantly, though.
> 6 votes

# Answer
## Ruby, 91 chars

```
%{ !"#$&\',-/450:<=>ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcefghijklmnqvwxyz|~};puts(?@.ord*98+1)

```

Outputs `6273`.

`%{...}` trick stolen from Jan Dvorak
> 3 votes

# Answer
# Perl, 61 characters

```
print$:x8^CJIBQTOWAEULHVGFNMKRPZY,q<#"/;*g~?|={.>&+u15m97ws26

```

Output:

```
c@db[yo]le_ah\jfD`kX}zS-! %)('v304

```

`$:` defaults to `" \n-"`. `x8` repeats it eight times; the 24-character result is then bitwise-xored with a 23-character barestring (the last `-` is left as-is). Second part is a 12-character q-string bitwise-and a 10-character barestring (the last 2 characters are discarded).
> 3 votes

# Answer
# Ruby, 95 characters, 6 edits

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

```

Yep. That's it. Just a free-floating string literal that is never printed. Ruby supports string literals (borrowed from Perl, I think) in the percent-type-delimiter form - the delimiter is any non-alphanumeric character, and if the opening delimiter is an opening bracket (any of `[({<`), the closing delimiter is the corresponding closing bracket (nested brackets are allowed).

I realise this is more of a baseline submission, but unless someone manages to actually print something or unless there's a language with a two-char freeform string literal with a *different* opening and closing delimiter, this is the best there is.
> 1 votes

# Answer
### Tcl 96, edit distance 12

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

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: change two bits by using only bitwise operations
try to write shortest possible variant of logic which converts binary input by this table:

```
00 -> 00
01 -> 10
10 -> 01
11 -> 11

```

You can use only bitwise and bitshift operations. I calculate only operations and don't care brackets, spaces, constants and etc. But you can't use any control (if, while, ternary) and arithmetic operations.

If you are using bitwise and bitshift operations, your operations number will be multipled by two:

```
op_num = (your_op_num << types_of_operation_num) >> 1

```

**edit: sorry, this is not real code-golf, because I calculate operations in logic, not characters.**

# Answer
> 4 votes
# 6 operations

```
216>>i>>i&3

```

Same idea:

```
216>>(i<<1)&3

```

# Answer
> 4 votes
## 8 operations (4 * 2)

Ok, here a real answer:

```
(i&1)<<1|i>>1

```

# Answer
> 3 votes
**Javascript, 0 operators**

```
alert(prompt().split('').reverse().join(''))

```

# Answer
> 1 votes
## Tcl, 0 operators

```
string rev $i

```

# Answer
> 1 votes
# Mathematica 0 operators?

If a string, `s`, is input, any of the following should work:

```
StringReverse[s]

StringRotateLeft[s]

StringRotateRight[s]

```

If the input is a list of digits (the standard way to represent binary digits in Mathematica), this will work:

```
(# /. {{0,1} -> {1,0}, {1,0} -> {0,1}}) &

```

---
Tags: binary
---


title: Today (September 24) is HONDA birthday

text:
# Question
Title: Today (September 24) is HONDA birthday
today (24 of September) is birthday of company HONDA. Originally their company name is

`本田技研工業株式会社`

I want to ask to make a gift for HONDA. The task is to make program print company name. You can do it any way you want, but there is only one rule, Unicode is not allowed. It should be ASCII art.

I want to ask to post code and output. As always to determine winner I'll look at the length of code, however portrait in this case is also important.

**EDIT:** output have to look similar into this: `本田技研工業株式会社`

# Answer
# Mathematica

Here the characters are individually rasterized. The zero's of the binary image data of a reduced image are then replaced with asterisks and the array itself is then printed.

```
GraphicsGrid[ImageData@ImageResize[Binarize@Rasterize@Style[#, 136], 30]
/. {1 -> "", 0 -> "*"}] & /@ Characters["本田技研工業株式会社"]

```

Below all characters were rasterized as a single image. The asterisks are a bit more difficult to recognize as asterisks in this case.

```
GraphicsGrid[ImageData@ImageResize[Binarize@Rasterize@Style[#, 136], 300]
/. {1 -> "",  0 -> "*"}, ImageSize -> 1500] &["本田技研工業株式会社"]

```
> 20 votes

# Answer
## Tcl

Well, a probably crazy approach.

```
package r Tk
package r Img
pack [label .l -text 本田技研工業株式会社 -fg #000000 -bg #ffffff]
update
puts [join [lmap line [[image create photo -data .l] data] {join [lmap pixel $line {expr {$pixel ne {#ffffff}?"@":" "}}] {}}] \n]
exit

```

Here a screenshot:
> 11 votes

# Answer
---

# JavaScript + HTML, interactive version (275 + 90 = 365 chars)

Many ideas inspired by Austin's answer, but this one is interactive; you can change the font size! (also the character count is actually correct)

---

### Screenshot

Pressing the `-` and `+` buttons change the font size. Image is cut off, but you get the idea.

---

### Fiddle (try it yourself!)

Here is a JSFiddle where you can run the code yourself.

---

### JS, 275

```
h=30,(r=function(){for(x=document.createElement('canvas').getContext('2d'),x.font=h+'px sans-serif',x.fillText('本田技研工業株式会社',0,h),d=x.getImageData(0,0,w=h*10,h).data,s='',a=0;a<h;a++){for(b=0;b<w;b++)s+=d[3+w*4*a+4*b]?0:' ';s+='\n'}document.getElementById('p').innerHTML=s})()

```

---

### HTML, 90

```
<button onclick='h--;r()'>-</button><button onclick='h++;r()'>+</button><pre id='p'></pre>

```

---

## Hi-resolution version

http://jsfiddle.net/UjTbK/1/

---
> 5 votes

# Answer
# Javascript, 261 characters, 226 minified

special thanks to jsacii for inspiring this solution.

```
c = document.createElement('canvas').getContext('2d');
c.font="30px sans-serif";c.fillText("本田技研工業株式会社", 0,30);d=c.getImageData(0,0,305,40).data;
s="";
for(var y = 0; y<40;y+=2){
    for(var x=0;x<305;x++)
        s += d[3+4*x+1220*y]? "*" : " ";
    s+="\n";
}

```

minified

```
c=document.createElement("canvas").getContext("2d");c.font="30px sans-serif";c.fillText("本田技研工業株式会社",0,30);d=c.getImageData(0,0,305,40).data;s="";for(var y=0;y<40;y+=2){for(var x=0;x<305;x++)s+=d[3+4*x+1220*y]?"*":" ";s+="\n"}

```

and the output

```
             ****                                                ****        ****                                                                                ***  ***                ****        ****                           **                       ****                  ****         ****
             ****               **************************       ****        ****          *****************************                                  ****   ***  ***   ****         ****    ********                          ********                 ******                 ****         ****
             ****               **************************       ****        ****      *    ** ******* ****** ****** **    *************************       ****  ***  ***  ****          ****   **** ****                          **** *****             **********                ***         ****
 ****************************   ****       ****       ****   ****************************     ****       ****   ****       ************************    ****************************  ***************************   ****************************        ******    ******        *************    ****
  ***************************   ****       ****       ****   ***********     ****             ****       ****   ****                 ****                     ****      ****         ***************************   ****************************     *******        *******             ****     ****
          *********             ****       ****       ****       ****        ****            ****        ****   ****                 ****               **************************      **********   ****                          ****          *****************************       *********************
         ************           **************************       **** *****************     ****************************             ****               **************************      *************************    ******************          ****  ****************  *****      ****   **** **********
       ***** **** ****          **************************       ******* ****      ****    ******  ********************              ****                 **********************       **************************    ******************                                           *******       ****
      *****  ****  *****        ****       ****       ****   ********    *****   *****    *******  ***   ****   ****                 ****                 **********************      *******      ********               ****      ****         ****************************  *************    ****
   ******    ****    ******     ****       ****       ****   ********      **** ****       * ****  ***   ****   ****                 ****              **************************** *********     ***********             ****      ****           *      ****     *      **   **** *** ****    ****
 *****************************  ****       ****       ****       ****       *******          ****  ***  ****    ****                 ****              ****************************  **  ****   ********* *****           ****     * ****   ***          ****    *****              ***         ****
 ****   *    ****        ****   ****       ****       ****       ****      *********         ********* *****    ****     ****************************        ****************            **********  ****  ******         *********** ****  ****        ****       *****            ***         ****
             ****               **************************       ****  *******  *******      **************     ****     ****************************  **********  ****  ***********     ********    ****    ****  **************      ********    ***********************          ***  *******************
             ****               ****                  ****   **************        *******   ****    *****      ****                                   ******      ****       *****      ****        ****           ***                 ******    ****************     *****       ****  *******************
             ***                                                 *                     *              **         **                                                ****                  ****         ***                                                               **          ***

```
> 4 votes

# Answer
# Java, ~~267~~ 260 characters

Alright, I guess my solution is not all that different from Johannes Kuhn's answer, but as it seems this is a problem that can be handled nicely in Java; my solution is not much longer; and the output is slightly different, I'll post it nevertheless:

```
class A{public static void main(String[]a){java.awt.image.BufferedImage b=new java.awt.image.BufferedImage(130,16,2);b.createGraphics().drawString("本田技研工業株式会社",0,13);for(int y=0;y<2080;System.out.print((b.getRGB(y%130,y/130)<0?"#":" ")+(++y%130<1?"\n":"")));}}

```

Formatted as:

```
class A {
    public static void main(String[]a) {
        java.awt.image.BufferedImage b = new java.awt.image.BufferedImage(130, 16, 2);
        b.createGraphics().drawString("本田技研工業株式会社", 0, 13);
        for (int y = 0; y < 2080; System.out
                .print((b.getRGB(y % 130, y / 130) < 0 ? "#" : " ")
                        + (++y % 130 < 1 ? "\n" : "")))
            ;
    }
}

```

Output:

```
      #                     #     #                                   # #        #  # #                       #         #    #
      #       ###########   #     #     #### #######                # # # #      #  # #            # ##      # #        #    #
 ###########  #    #    #   #  ########   #   #  #    ##########  # # # # # #    #  ######         #       ##   ##    #####  #
      #       #    #    # ####    #      #    #  #        #       ###########  ### #  #     ############  #       #       #  #
     ###      #    #    #   #     #      #    #  #        #          #   #       #    #            #     # ######  ##    #  #####
    # # #     ###########   #  #######   ### #######      #       ###########   ### #######  ##### #                    #    #
   #  #  #    #    #    #   ##  #   #   ## #  #  #        #        #########   # #    #        #   #                   ###   #
  #   #   #   #    #    # ###    #  #    # #  #  #        #            #       # #   ###       #    #    ###########  # # #  #
 #  #####  #  #    #    #   #    # #     # #  #  #        #       ###########  # #  # # #      #    #        #          #    #
 #    #     # #    #    #   #    ###     ### #   #        #          # # #       # #  #  #     # ## #  #    #   #       #    #
      #       ###########   #  ##   ##   # # #   #   ###########   ##  #  ###    # #  #   # #####    # #    #    #      # #######
      #       #         # ##  #       #      #   #                #    #     #   #    #               #  ######## ##    #

```
> 1 votes

---
Tags: code-golf, popularity-contest, ascii-art
---


title: Make a JavaScript/jQuery slideshow

text:
# Question
Title: Make a JavaScript/jQuery slideshow
I am working on making a minimalistic personal testing website to conduct various experiments for my role at work. I'd like to add a couple of bells and whistles to it, particularly a slideshow that cycles between several images. I could just as easily grab a plug-in, but I'd like to promote this Stack Exchange beta site and offer a simple challenge with concrete rules.

Rules:

* JavaScript and jQuery are allowed. The jQuery library is assumed to be included.
* The function of the code is to take three images and fade-cycle through each of them at regular intervals of five seconds indefinitely. Fade time is one second.
* Must be compatible with Internet Explorer 9 (and later), Chrome, and Firefox.
* The code golf submission is the total number of characters between the inline script. Characters in externally referenced files are also included.

HTML is the following, pretty-printed as it's not part of the challenge:

```
<html>
  <head>
    <title>JS Slideshow code golf</title>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script type="text/javascript">
      /* CODE GOLF SUBMISSION HERE */
    </script>
  </head>
  <body>
    <div class="s">
      <img id="a" src="img1.png" />
      <img id="b" src="img2.png" />
      <img id="c" src="img3.png" />
    </div>
  </body>
</html>

```

Full attribution will be given to the author on any code I end up using.

# Answer
# ~~70~~ 68(JS) + 22(CSS) characters

```
setInterval('$(".s").append($(".s :first").hide().fadeIn(1e3))',5e3)

```

CSS:

```
img{position:absolute}

```

jsfiddle: http://jsfiddle.net/QACAY/

pure jQuery. The only browser-stuff is `setInterval`, which dates as far back as IE4. jQuery support doesn't reach that far. Javascript syntax here is ancient as well.

Of course, in practice, **do not pass strings to** `setInterval`! It is ten characters shorter (fewer with es6 arrow functions), but it's unreadable (madness? This is code golf!), it forces you into the global scope (which we don't mind here), it's slower (but we are far from being concerned with performance of calling jQuery code) and it won't pass any decent code review.

Works best if all images have the same shape. But, it will work just as fine with semitransparent images as long as visible stacking counts as fine and no more background is visible when any single image is removed.

Since this does not wait for DOM ready, there's a tiny chance that only some of the image elements inside a gallery are loaded when an interval fires. In this case, the stack of images will get reordered. I don't think it's a problem. In fact, I kinda like it.

After slight tweaking, it looks like code that could easily pass through a code review and get into production (also, be sure to modify the CSS to not be too aggressive):

```
$(function(){
  $(".s").each(function(_, s){
    setInterval(function(){
      $(":first", s).hide().appendTo(s).fadeIn(1000);
    }, 5000);
  });
});

```
> 8 votes

---
Tags: code-golf
---


title: Do not use the same code again

text:
# Question
Title: Do not use the same code again
I want to give a task. The main rule is not to use the same code again, it means no loops, no jumps, no goto, no recursion, if you declare procedure it can be called only once and etc. Also if you call some standart function it should meet the requirements inside.

The main point of this task is to write the shorter code which prints the longest output.

**NOTE:** printing functions, for example `printf` probably do not meat requirements but it is allowed to use this kind of functions.

**EDIT:** after reading some comments I have to tell that output needs to be longer then input. Also you cannot use the same function twice because it means you are using the same code, sorry for not very clear requirements.

# Answer
# Python: 11 characters → 857 characters

```
import this

```

Sample run:

```
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

```
> 2 votes

# Answer
# Golfscript, 1 -\> 2

```
`

```

if the requirement is to produce the shortest code with an output longer than input, this is the winner (unless we count error messages of languages where an empty source is invalid program). Backtick means "inspect/uneval". Since the empty string (input) happens to be already present on the stack, this produces a string containing only two double quotes, which is then printed out.

# C++, 22 -\> 2^31-1 (= 2147483647)

```
printf("%*i",~0u>>1,0)

```

It's hard to argue that string concatenation or infinite precision arithmetic doesn't loop internally. In such case, we are restricted to built-in finite precision data types. However, the best place for a large value is the output precision, not the value to be printed. In C++, the variable precision type is int, so we can print with no more than 2^31-1 digits of precision. Sure, the printing routine will loop a bit, but printing routines are allowed to. But, if built in operators (but not library functions) are allowed to loop as well,

# J, (extreme growth)

```
!9
!!9
!!!9
!!!!9

```

the factorial of an n-digit number has in the order of e^n digits for some small e. This means the sequence factorial of (factorial of(factorial of ... (factorial of 9) ...))) grows *very* quickly.

It's unclear what "same code twice" exactly means, but I'll assume that two invocations of the same system function are allowed as long as the function itself is allowed. "*if you declare procedure* it can be called only once"

Of course, if function exponentiation doesn't count as iteration, we can grow much more quickly than that:

```
!^:(!^:]9)9

```

this will apply factorial to nine nine times, then use *that* as the number of applications of factorial to (another) nine. Of course, these can be nested ad lib. Say, we could take the factorial of `!^:9]9` `!^:9]9` times. We'll also shorten `!^:9]9` to just `!^:]9`.

```
!^:]!^:]9

```

Ninth composition of `!^:]` can be shortened to `!^:]^:9`. The argument'th composition is `!^:]^:]`. Unfortunately, function power cannot be applied to conjunctions like function power, so let's stop here for now (arg compositions of (arg compositions of (arg compositions of ... factorial))):

```
!^:]^:]^:]^:]

```

We could apply "eval" here, but we're way so far off the realm of definitely not iterating I better stop here and not get to stuff like string multiplication and evaluation in order to crank up this immense number even higher.

# Golfscrcript, n -\> theta(2^n)

````````````...

Languages without built-in infinite precision arithmetic can still achieve exponential growth via string concatenation (twofold increase in two characters). Or, we could inspect the inspection of the inspection of ... yielding twofold increase in just a single char.
> 2 votes

# Answer
My code is: `help` and it is Windows batch script. Output is:

```
For more information on a specific command, type HELP command-name
ASSOC          Displays or modifies file extension associations.
ATTRIB         Displays or changes file attributes.
BREAK          Sets or clears extended CTRL+C checking.
BCDEDIT        Sets properties in boot database to control boot loading.
CACLS          Displays or modifies access control lists (ACLs) of files.
CALL           Calls one batch program from another.
CD             Displays the name of or changes the current directory.
CHCP           Displays or sets the active code page number.
CHDIR          Displays the name of or changes the current directory.
CHKDSK         Checks a disk and displays a status report.
CHKNTFS        Displays or modifies the checking of disk at boot time.
CLS            Clears the screen.
CMD            Starts a new instance of the Windows command interpreter.
COLOR          Sets the default console foreground and background colors.
COMP           Compares the contents of two files or sets of files.
COMPACT        Displays or alters the compression of files on NTFS partitions.
CONVERT        Converts FAT volumes to NTFS.  You cannot convert the
               current drive.
COPY           Copies one or more files to another location.
DATE           Displays or sets the date.
DEL            Deletes one or more files.
DIR            Displays a list of files and subdirectories in a directory.
DISKCOMP       Compares the contents of two floppy disks.
DISKCOPY       Copies the contents of one floppy disk to another.
DISKPART       Displays or configures Disk Partition properties.
DOSKEY         Edits command lines, recalls Windows commands, and
               creates macros.
DRIVERQUERY    Displays current device driver status and properties.
ECHO           Displays messages, or turns command echoing on or off.
ENDLOCAL       Ends localization of environment changes in a batch file.
ERASE          Deletes one or more files.
EXIT           Quits the CMD.EXE program (command interpreter).
FC             Compares two files or sets of files, and displays the
               differences between them.
FIND           Searches for a text string in a file or files.
FINDSTR        Searches for strings in files.
FOR            Runs a specified command for each file in a set of files.
FORMAT         Formats a disk for use with Windows.
FSUTIL         Displays or configures the file system properties.
FTYPE          Displays or modifies file types used in file extension
               associations.
GOTO           Directs the Windows command interpreter to a labeled line in
               a batch program.
GPRESULT       Displays Group Policy information for machine or user.
GRAFTABL       Enables Windows to display an extended character set in
               graphics mode.
HELP           Provides Help information for Windows commands.
ICACLS         Display, modify, backup, or restore ACLs for files and
               directories.
IF             Performs conditional processing in batch programs.
LABEL          Creates, changes, or deletes the volume label of a disk.
MD             Creates a directory.
MKDIR          Creates a directory.
MKLINK         Creates Symbolic Links and Hard Links
MODE           Configures a system device.
MORE           Displays output one screen at a time.
MOVE           Moves one or more files from one directory to another
               directory.
OPENFILES      Displays files opened by remote users for a file share.
PATH           Displays or sets a search path for executable files.
PAUSE          Suspends processing of a batch file and displays a message.
POPD           Restores the previous value of the current directory saved by
               PUSHD.
PRINT          Prints a text file.
PROMPT         Changes the Windows command prompt.
PUSHD          Saves the current directory then changes it.
RD             Removes a directory.
RECOVER        Recovers readable information from a bad or defective disk.
REM            Records comments (remarks) in batch files or CONFIG.SYS.
REN            Renames a file or files.
RENAME         Renames a file or files.
REPLACE        Replaces files.
RMDIR          Removes a directory.
ROBOCOPY       Advanced utility to copy files and directory trees
SET            Displays, sets, or removes Windows environment variables.
SETLOCAL       Begins localization of environment changes in a batch file.
SC             Displays or configures services (background processes).
SCHTASKS       Schedules commands and programs to run on a computer.
SHIFT          Shifts the position of replaceable parameters in batch files.
SHUTDOWN       Allows proper local or remote shutdown of machine.
SORT           Sorts input.
START          Starts a separate window to run a specified program or command.
SUBST          Associates a path with a drive letter.
SYSTEMINFO     Displays machine specific properties and configuration.
TASKLIST       Displays all currently running tasks including services.
TASKKILL       Kill or stop a running process or application.
TIME           Displays or sets the system time.
TITLE          Sets the window title for a CMD.EXE session.
TREE           Graphically displays the directory structure of a drive or
               path.
TYPE           Displays the contents of a text file.
VER            Displays the Windows version.
VERIFY         Tells Windows whether to verify that your files are written
               correctly to a disk.
VOL            Displays a disk volume label and serial number.
XCOPY          Copies files and directory trees.
WMIC           Displays WMI information inside interactive command shell.

For more information on tools see the command-line reference in the online help.

```

I didn't count size of output because it is my own question and I'm not willing to win.
> 1 votes

# Answer
# Mathematica

```
RandomInteger[{10^980, 10^990}]

```
> 1 votes

# Answer
## Ruby, 13 chars, 599994 char output, ~46153:1 ratio

```
999999**99999

```

Simply raises a very large number to the power of another very large number. Takes about ten seconds to run. I could increase the numbers, but that would make the running time even longer.
> 1 votes

---
Tags: code-golf
---


# Question
Title: Solve the CodeSprint4 Leibniz code golf challenge in Python in 66 characters
Check out this challenge:

https://www.hackerrank.com/codesprint4/challenges/leibniz

(The competition has already ended, so I'm just curious about the Python solution, which the organizers refused to reveal, so this is not cheating in any way.)

Modified from that page:

> In Calculus, the Leibniz formula for \\$\pi\\$ is given by:
>
> $$\sum\_{n=0}^\infty \dfrac{\left(-1\right)^n}{2n+1}$$
>
> You will be given an integer \\$n\\$. Your task is to print the summation of the Leibniz formula up to the \\$n\\$th term of the series correct to 15 decimal places.
>
> That is given \\$n\\$ calculate:
>
> $$\sum\_{k=0}^n \dfrac{\left(-1\right)^k}{2k+1}$$
>
> with the first 15 decimal places correct.
>
> # Input Format
>
> The first line contains the number of test cases (\\$T\\$) which is less than 100. Each additional line is a test case for a positive integer value less than 10^7.
>
> # Output Format
>
> Output \\$T\\$ lines each containing the calculated result for the corresponding line of the input.
>
> # Scoring
>
> This is .

I only managed to solve the challenge in 77 characters. (Talking only about Python here.) However, one adr2370 managed to solve the challenge in 66 characters!

Please help me find the 66-character solution! I'm very very curious because I had to work really hard to bring mine down to 77, and I'm amazed as to how someone came up with a 66-character solution.

For reference, my solution:

```
for j in'x'*input():print'%.15f'%sum((-1)**i/(2.*i+1)for i in range(input()))

```

# Answer
## Python 71 bytes

```
exec"print'%.15g'%sum((-1.)**i/(i-~i)for i in range(input()));"*input()

```

Not quite 66 bytes, but with a score of 22.90, it would have ranked second overall.

**Edit**: regarding Ari's comment about the 66 byte Python solution being a 'hack', I don't think that's exactly what happened. I've noticed several times that the submitted language is displayed incorrectly. For example here: Baconian Cipher. This challenge may only be submitted in Brainf\_ck, yet the second ranked solution was submitted in Python 2 (interestingly enough, spot 23 is also Python 2. If I were to speculate, I would say that if the language information is missing from a submission for whatever reason, it seems to default to Python).

I suspect that a similar error may have occurred here, and that the shortest Python solution submitted during the challenge was actually 72 bytes.

**Update**: After speaking with a moderator, it seems that Ari was right:
> 5 votes

# Answer
## Python, 65 characters

```
exec'print`sum((-1.)**x/(x-~x)for x in range(input()))`;'*input()

```
> 6 votes

# Answer
# Python 2 (50 chars, with input loop grows)

```
a=n=1.;s=0;exec's+=a/n;a=-a;n+=2;'*input();print s

```

also prints only 12 digits of result, with loop and formatting

```
exec input()*"a=n=1.;s=0;exec's+=a/n;a=-a;n+=2;'*input();print '%.15f'%s;"

```

74 chars

# Python 3 (57 chars, with input loop grows to 79 chars)

without loop

```
a=n=1;s=0;exec('s+=a/n;a=-a;n+=2;'*int(input()));print(s)

```

with loop

```
exec(int(input())*"a=n=1;s=0;exec('s+=a/n;a=-a;n+=2;'*int(input()));print(s);")

```

Python 3 prints 16 digits by default

```
exec(int(input())*"print(sum((-1)**i/(i-~i)for i in range(int(input()))));")

```

76 chars
> 1 votes

---
Tags: code-golf, tips, python, pi
---


title: math with bitwise operators

text:
# Question
Title: math with bitwise operators
## objective

write a program that can perform addition, subtraction, multiplication, and division, using only bit-wise operators, by bit-wise operators i mean the equivalent of JavaScript `&`, `|`, `^`, `~`, `<<` ,`>>` ,`>>>`. (`AND`, `OR`, `XOR`, `NOT`, and `SHIFT`s)

## rules

* you **can use other operators**, just not for the actual operation/output. (i.e. loop-indentation is ok).
* it need not actually take input, just be technically functional. (i.e. functions that take arguments).
* any output is OK, you can even return a object with the sum, difference, etc.
* you need not return floats for division `int`s are ok as well, you can round anyway you like.
* as short as you can.

# Answer
> 6 votes
# JavaScript, ~~124~~ 119

```
a=(x,y)=>y?a(x^y,(x&y)<<1):x
s=(x,y)=>a(x,a(1,~y))
m=(x,y)=>x?a(y,m(s(x,1),y)):0
d=(x,y)=>(x=s(x,y))>>31?0:a(1,d(x,y))

```

Addition and Subtraction work for any signed numbers, multiplication and division only for unsigned (this hasn't been specified).

The input is assumed to be 32 bit.

I've been very strict and not even used comparison operators, except testing for equality with zero. It could probably be written a bit shorter otherwise.

# Answer
> 5 votes
## C, 313 characters

```
s(a,b){return a&b?s(a^b,(a&b)<<1):a^b;}
d(a,b){return s(s(a,~b),1);}
P(a,b,c){return b?P(a<<1,b>>1,b&1?s(c,a):c):c;}
p(a,b){return b<0?d(0,P(a,d(0,b),0)):P(a,b,0);}
q(a,b,c,z){long v=b=(z=b<0)?d(0,b):b,w=1;for(a=a<0?z^=1,d(0,a):a;a>=v;v<<=1)w<<=1;
for(c=0;b<=a;v<=a?a=d(a,v),c=s(c,w):0)v>>=1,w>>=1;return z?s(~c,1):c;}

```

The four functions are `s` = sum, `d` = difference, `p` = product, and `q` = quotient. `P` is an internal helper function used by `p`, and is not part of the API. (Note that despite `q`'s definition, it should be invoked with only two parameters.)

Please note that `p` and `q` do not work by iterative addition/subtraction, but actually do the bitwise computation. (Otherwise `q` could be significantly shorter.) Thus their running time is a respectable O(log N).

All four functions accept the full range of positive and negative integers as inputs. Dividing by zero will produce an infinite loop, since there's no portable way to raise the appropriate exception.

Special note for C standards lawyers: The code assumes that sizeof(long) is strictly greater than sizeof(int), which is true more often these days than it used to be. *If* longs and ints are the same size, however, *and* the implementation sign-extends on right-shift (as most do), then `q`'s valid input range is decreased such that the absolute value of the second argument cannot have its highest (non-sign) bit set. (Since dividing by such values can only be equal to zero or one, this isn't too much of a restriction in practice.)

---
Tags: code-golf, arithmetic, binary
---


title: Implement superoptimizer for addition

text:
# Question
Title: Implement superoptimizer for addition
The task is to write code that can find small logical formulae for sums of bits.

The overall challenge is for your code to find the smallest possible propositional logical formula to check if the sum of y binary 0/1 variables equals some value x. Let us call the variables x1, x2, x3, x4 etc. Your expression should be equivalent to the sum. That is, the logical formula should be true if and only if the sum equals x.

Here is a naive way to do it to start with. Say y=15 and x = 5. Pick all 3003 different ways of choosing 5 variables and for each make a new clause with the AND of those variables AND the AND of the negation of the remaining variables. You end up with 3003 clauses each of length exactly 15 for a total cost of 45054.

Your answer should take be a logical expression of that sort that can just be pasted into python, say, so I can test it. If two people get the same size expression, the code that runs the fastest wins.

You ARE allowed to introduce new variables into your solution. So in this case your logical formula consists of the y binary variables, x and some new variables. The whole formula would be satisfiable if and only if the sum of the y variables equals x.

As a starting exercise some people may want to start with y=5 variables adding to x=2. The naive method will then give a cost of 50.

The code should take two values y and x as inputs and output the formula and its size as the output. The cost of a solution is just the raw count of variables in its output. So `(a or b) and (!a or c)` counts as 4. The only allowed operators are `and`, `or` and `not`.

**Update** It turns out there is a clever method for solving this problem when x =1, at least in theory .

# Answer
## Python, 644

A simple recursive equation generator. `S` generates an equation that is satisfied iff the list of `vars` adds up to `total`.

There are some obvious improvements to be done. For instance, there are a lot of common subexpressions that appear in the 15/5 output.

```
def S(vars, total):
    # base case
    if total == 0:
        return "(" + " and ".join("not " + x for x in vars) + ")"
    if total == len(vars):
        return "(" + " and ".join(vars) + ")"

    # recursive case
    n = len(vars)/2
    clauses = []
    for s in xrange(total+1):
        if s > n or total-s > len(vars)-n: continue
        a = S(vars[:n], s)
        b = S(vars[n:], total-s)
        clauses += ["(" + a + " and " + b + ")"]
    return "(" + " or ".join(clauses) + ")"

def T(n, total):
    e = S(["x[%d]"%i for i in xrange(n)], total)
    print "equation", e
    print "score", e.count("[")

    # test it
    for i in xrange(2**n):
        x = [i/2**k%2 for k in xrange(n)]
        if eval(e) != (sum(x) == total):
            print "wrong", x

T(2, 1)
T(5, 2)
T(15, 5)

```

Generates:

```
equation (((not x[0]) and (x[1])) or ((x[0]) and (not x[1])))
score 4
equation (((not x[0] and not x[1]) and (((not x[2]) and (x[3] and x[4])) or ((x[2]) and (((not x[3]) and (x[4])) or ((x[3]) and (not x[4])))))) or ((((not x[0]) and (x[1])) or ((x[0]) and (not x[1]))) and (((not x[2]) and (((not x[3]) and (x[4])) or ((x[3]) and (not x[4])))) or ((x[2]) and (not x[3] and not x[4])))) or ((x[0] and x[1]) and (not x[2] and not x[3] and not x[4])))
score 27
equation (((not x[0] and not x[1] and not x[2] and not x[3] and not x[4] and not x[5] and not x[6]) and (((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (x[11] and x[12] and x[13] and x[14])) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((x[7] and x[8] and x[9] and x[10]) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))))) or ((((not x[0] and not x[1] and not x[2]) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (x[11] and x[12] and x[13] and x[14])) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((x[7] and x[8] and x[9] and x[10]) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((x[0] and x[1] and x[2]) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (x[3] and x[4] and x[5] and x[6])) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((x[0] and x[1] and x[2]) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6]))))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (x[3] and x[4] and x[5] and x[6])) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((x[0] and x[1] and x[2]) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6]))))) and (not x[7] and not x[8] and not x[9] and not x[10] and not x[11] and not x[12] and not x[13] and not x[14])))
score 644

```
> 8 votes

# Answer
I would have made this a comment, but I don't have a reputation. I wanted to comment that the results of Kwon & Klieber (known as the "Commander" encoding) for k=1 have been generalised for k\>=2 by Frisch et al. "SAT Encodings of the At-Most-k Constraint." What you're asking about is a special case of the AM-k constraint, with an additional clause to guarantee At-Least-k, which is trivial, just a disjunction of the all variables to the AM-k constraint. Frisch is a leading researcher in constraint modelling, so I would feel comfortable suggesting that \[(2k+2 C k+1) + (2k+2 C k-1)\] * n/2 is the best bound known on the number of clauses required, and k\*n/2 for the number of new variables to be introduced. The details are in the quoted paper, along with the instructions of how this encoding to built. It's fairly simple to write a program to generate this formula, and I think such a solution would be competitive with any other solutions you'll likely find for now. HTH.
> 3 votes

---
Tags: code-challenge, math, optimization, logic-gates
---


title: Make a colorful table

text:
# Question
Title: Make a colorful table
For this challenge, you must accept input as a comma-separated list (columns) of a run (rows) of the first letters of any of the colors `red`, `orange`, `yellow`, `green`, `blue`, or `purple`, and output (to stdout) the HTML for a table of those colors.

This is fairly hard to understand, so I'll just give a simple example.

Input:

```
rgb,gbr,grb

```

Output (with example screenshot):

```
<html>
  <head>
  </head>
  <body>
    <table>
      <tbody>
        <tr>
          <td style="background-color: red" width="50" height="50"></td>
          <td style="background-color: green" width="50" height="50"></td>
          <td style="background-color: blue" width="50" height="50"></td>
        </tr>
        <tr>
          <td style="background-color: green" width="50" height="50"></td>
          <td style="background-color: blue" width="50" height="50"></td>
          <td style="background-color: red" width="50" height="50"></td>
        </tr>
        <tr>
          <td style="background-color: green" width="50" height="50"></td>
          <td style="background-color: red" width="50" height="50"></td>
          <td style="background-color: blue" width="50" height="50"></td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

```

Note that the HTML you output need not be valid; it just has to work. By "work", I mean that your output will be pasted into a `.html` file and viewed in the latest (currently, 9/28/13) Chrome (v 29.0.1547.76). The squares must be 50 pixels width and height. You may have whatever padding between them as you want (Chrome automatically uses 1 pixel of padding, even when you specify `padding: 0px`, so I can't control that).

Input will always be valid (letters will be one of `roygbp`), but the rows are not guaranteed to have equal amounts of squares in them. For example, `roygbp,ooo` is valid and should output

This is , shortest code wins.

# Answer
# Perl: ~~153~~ ~~126~~ ~~124~~ ~~116~~ 114 characters

```
s!\w!'<td bgcolor=#'.substr(ff00f90707,yrbxoxgp=~$&&&@-[0],3).' width=50 height=50>'!ge;s!,!<tr>!g;$_="<table>$_"

```

Sample run:

```
bash-4.1$ perl -p table.pl <<< 'rgb,oyp'
<table><td bgcolor=#f00 width=50 height=50><td bgcolor=#070 width=50 height=50><td bgcolor=#00f width=50 height=50><tr><td bgcolor=#f90 width=50 height=50><td bgcolor=#ff0 width=50 height=50><td bgcolor=#707 width=50 height=50>

```

Sample output:

```
bash-4.1$ perl -p table.pl <<< 'yrryyryyryyyrrr,ryyyryryryyyryy,ryryryryryyyrry,yrryyryyrrryryy'

```
> 7 votes

# Answer
## Razor Leaf, 136

```
table for r in prompt().split(",")
    tr for x in r
        td bgcolor:"##{"rf00of90yff0g070b00fp707".match(x+"(...)")[1]}"width:"50"height:"50"

```

Razor Leaf. The indentation is tabs, by the way.

You might have some trouble running this in a browser, so try Node.js and define `global.prompt` to return a fixed output. :)

```
var fs = require("fs");
var razorleaf = require("razorleaf");

global.prompt = function() {
    return "rgb,byp";
};

console.log(razorleaf.compile(fs.readFileSync("test.leaf", "utf-8"))());

```

Using other people’s tricks is 126, but that’s no good.

```
table cellpadding:"26"for r in prompt().split(",")
    tr for x in r
        td bgcolor:"##{"rf00rof90oyff0yg070gb00fbp707".split(x)[1]}"

```
> 4 votes

# Answer
# Mathematica ~~148~~ 139

```
d_~f~n_:=Export[n,Grid@ToExpression@Characters@d/.{r->Red,o->Orange,y->Yellow,g->Green,
b->Blue,p->Purple}/.{x_RGBColor:>Graphics@{x,Rectangle[]}}]

```

---

`f`, defined above, is a simple function that takes the color strings as input and outputs an HTML file.

**Usage**

```
f[{"rgb","gbr","grb"}, "ColorfulTable.html"]

```

The HTML code that is output to file "ColorfulTable.html":

```
< ?xml version="1.0" encoding="UTF-8"?>
< ! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
"HTMLFiles/xhtml-math11-f.dtd" >
< ! --Created by Wolfram Mathematica 9.0 : www.wolfram.com-- >
< html xmlns = "http://www.w3.org/1999/xhtml" >
< head >
< title > Untitled
< /title >
< link href = "HTMLFiles/ColorfulTable.css" rel = "stylesheet" type = "text/css"/ >
 < /head >
 < body >
 < p class = "Output" >
  < img src = "HTMLFiles/ColorfulTable.gif" alt = "ColorfulTable.gif" width = "360" height = "360"
   style = "vertical-align:middle"/ >
       < /p >
       < div style = "font-family:Helvetica; font-size:11px; width:100%; border:1px none #999999; border-top-style:solid; padding-top:2px; margin-top:20px;" >
        < a href = "http://www.wolfram.com/products/mathematica/" style = "color:#000; text-decoration:none;" >
          < img src = "HTMLFiles/spikeyIcon.png" alt = "Spikey" width = "20" height = "21" style = "padding-right:2px; border:0px solid white; vertical-align:middle;"/ >
               < span style = "color:#555555" > Created with < /span > Wolfram < span style = "font-style: italic;" > Mathematica < /span > 9.0
< /a >
< /div >
< /body >
< /html >

```

**HTML rendering in Chrome**
> 3 votes

# Answer
# JavaScript, ~~203~~ 146

```
for(h='<table cellpadding=26>',p=prompt(),i=0;c=p[i++];)
h+=","==c?"<tr>":'<td bgcolor=#'+'rF00roFA0oyFF0yg080gb00Fbp808'.split(c)[1]+'>';
alert(h)

```

Credit to @C5H8NNaO4 for the single loop & cellpadding ideas. I'm using a split string to find the right color. (the line breaks were added for readability)

Input:

```
rgb,bgroyp

```

Output:

```
<table cellpadding=26><td bgcolor=#F00><td bgcolor=#080><td bgcolor=#00F><tr><td bgcolor=#00F><td bgcolor=#080><td bgcolor=#F00><td bgcolor=#FA0><td bgcolor=#FF0><td bgcolor=#808>

```

Here's the JSFiddle

Does anyone know how to use unicode characters in JSFiddle? I could shave a few more characters off, but some characters wouldn't paste in correctly.
> 3 votes

# Answer
## GolfScript, ~~154~~ ~~144~~ 119

```
'<table><tr>'\{:^44='<tr>'{"<td bgcolor="['red''orange''yellow''green''blue''purple']{0=^=}?" width=50 height=50>"}if}%

```

Online test

With credit to @bendytree for introducing the no-close-tags trend which allowed me to cut 25 chars.
> 2 votes

# Answer
# Python 3 (158)

```
print('<table>',*['<tr>'+''.join('<td width=50 height=50 bgcolor=#%03x>'%dict(r=3840,o=3984,y=4080,g=96,b=15,p=1799)[c]for c in r)for r in input().split(',')])

```

Cool things:

* This uses the `*` operator to pass multiple arguments to `print`, saving 6 characters compared to `''.join`.
* The colors are stored in decimal, then rendered as hex in the HTML. I found this to be much shorter than using string literals directly.
> 1 votes

# Answer
# Javascript, ~~199~~ ~~183~~ ~~173~~ ~~171~~ ~~167~~ ~~164~~ ~~159~~ ~~158~~ 154

```
h="<table cellpadding=26>";p=prompt();for(i=0;c=p[i++];)h+=","==c?"<tr>":'<td bgcolor=#'+{r:"F00",o:"FA0",y:"FF0",g:"080",b:"00F",p:"808"}[c]+'>';alert(h)

```

<sub> *just realized i don't need an opening `<tr>` tag*
*stupid me, i of course do **not** need to split the input string to access single chars*
*... as well as i of course do not need to initialise `c`*
*inlined the lookup object*
*you can actually leave out the px for width and height*
*changed width and height to cellpadding 26px*
*replaced `</tr>` with `<tr>`* *removed the `'` around 26 at the cellpadding and from the bgcolor* </sub>

*Changin the `for` to a `for .. in` loop would save only one character, so i keep the for*

Example Output for `roygbp,ooo`

```
<table cellpadding=26><td bgcolor=#F00><td bgcolor=#FA0><td bgcolor=#FF0><td bgcolor=#080><td bgcolor=#00F><td bgcolor=#808><tr><td bgcolor=#FA0><td bgcolor=#FA0><td bgcolor=#FA0>

```
> 1 votes

# Answer
# ECMAScript 6: 148 characters

```
alert('<table>'+prompt().replace(/./g,x=>x==','?'<tr>':'<td bgcolor='+'red green orange yellow blue purple'.match(x+'\\w+')+' width=50 height=50>'))

```

(Just to exercise the fat arrow syntax.)
> 1 votes

# Answer
## PHP, ~~182~~ ~~164~~ 163 characters

Example input:

```
<?php $x = 'roygbp,ooo'; ?>

```

*Update 1; if you silence (or just ignore) E\_NOTICE you can remove the quotes around strings that start with letters, shaving off another 18 characters*

*Update 2; trimmed 1 character!*

```
<?php echo'<table cellpadding=50><tr>';$a=[r=>f00,g=>'080',b=>blue,o=>fa0,p=>'808',y=>ff0];foreach(str_split($x)as$b){echo$b==','?'<tr>':"<td bgcolor=#$a[$b]>";}?>

```
> 1 votes

# Answer
# Ruby, ~~221~~ 187

I am presenting my own solution first, as always:

```
$><<'<table>'+gets.chop.split(?,).map{|r|'<tr>'+r.chars.map{|t|"<td bgcolor=#{'red green orange yellow blue purple'.match(t+'\w+')[0]} width=50 height=50></td>"}*''+'</tr>'}*''+'</table>'

```
> 0 votes

# Answer
## PHP, 277 characters

```
<style>div div{display:inline-block;width:50px;height:50px}<?foreach(array(red,orange,yellow,green,blue,purple)as$c){echo".$c[0]{background-color:$c}";}?></style><?foreach(split(",",fgets(STDIN))as$r){?><div><?foreach(str_split($r)as$c)echo"<div class='$c'></div>"?></div><?}?>

```

Input:

```
rgb,bgr,gbr

```

Output:

```
<style>div div{display:inline-block;width:50px;height:50px}.r{background-color:red}.o{background-color:orange}.y{background-color:yellow}.g{background-color:green}.b{background-color:blue}.p{background-color:purple}</style><div><div class='r'></div><div class='g'></div><div class='b'></div></div><div><div class='b'></div><div class='g'></div><div class='r'></div></div><div><div class='g'></div><div class='b'></div><div class='r'></div></div>

```

Hmmm... the stylesheet is killing me here. I don't have time now, but I'll come back to have a look at this later.

And yes, I'm deliberately not using tables for layout. ;-)
> 0 votes

# Answer
# Python 2.7 (176)

```
I=raw_input().split(",")
h="<table>"
c=dict(r=3840,o=3984,y=4080,g=96,b=15,p=1799)
for r in I:
 h+="<tr>"
 for x in r:h+="<td width=50 height=50 bgcolor='#%03x'>"%c[x]
print h

```

I pinched the use of dict and the insertion of Hex values from @Lambda Fairy

And for good measure, here is a jsfiddle with an example output
> 0 votes

---
Tags: code-golf, generation
---


title: English numeral calculator

text:
# Question
Title: English numeral calculator
# Challenge

Write a calculator that takes input in a verbal form (as one might speak an equation) and also outputs in a verbal form (as one might speak a number).

# Rules

The calculator should be able to:

* add, subtract, multiply and divide
* handle operands between negative one million and one million
* handle outputs between negative one billion and one billion
* handle decimal points in its input and place them correctly in its output
* handle decimal output to the hundredths place, rounding where needed

All operations yielding fractional results should round to the nearest hundredths place (identically to the output formatting).

Report with output "E" (for error) when input would cause the program to fail due to being incorrectly formatted or dividing by 0; basically, the program shouldn't crash on bad input, because that would be a lousy calculator.

The calculator is *allowed*, but *not required* to report errors when operands or output escape their bounds. This is meant to simplify the problem, but if you disagree with me, feel free to make a calculator capable of correctly handling greater operands and outputs without reporting errors.

Output "E" in the event that an operand for an operation exceeds the bounds defined for operands.

Output "E" in the event that the output exceeds the bounds described for outputs

How the program handles case-sensitivity and whitespace are left up to the golfer, as is the choice of British or American English.1

Programs that bypass the implementation of the calculator by using a language or library that has already implemented the functionality described above will be ineligible for victory.

# Winner

The program with the lowest number of characters wins.

# Examples

**Input:** two plus two
**Output:** four

**Input:** twenty-one point five minus one point five
**Output:** twenty

**Input:** one minus two
**Output:** negative one

**Input:** five times five
**Output:** twenty-five

**Input:** twenty-five divided by five
**Output:** five

**Input:** two plus two minus five times five divided by negative zero point five
**Output:** ten

**Input** one million times one thousand
**Output:** one billion

**Input:** one million times one thousand plus one
**Output:** E

**Input:** two million plus one million
**Output:** E

**Input:** one million plus one million plus one million
**Output:** E

# Answer
> 6 votes
First of all, this is totally cheaty, and not complete to the specs.

*requires the `--disable-web-security` flag on chrome, +22*

# Javascript 509 + 22 = 531

```
x=new XMLHttpRequest;y=Object.keys(x);b=alert;q="querySelectorAll";s="send";x[y[3]]="document";x.open("GET","http://www.wolframalpha.com/input/?i="+escape(prompt()));x[y[10]]=function(c){4===x.readyState&&(w=[].filter.call(x.response[q](".pod h2"),function(a){return"ame:"==a.innerText.slice(-4)})[0].parentElement,(k=w[q]("a")[0])&&"Words only"==k.innerText?(x.open("GET",k.href),x.send()):alert(JSON.parse([].pop.call(x[y[2]][q]("script")).innerHTML.match(/d_0.00\.push\((.+?)\)/)[1]).stringified))};x[s]()

```

The first off the spec is as well the example output
The input `two plus two minus five times five divided by negative zero point five` outputs

Any other case should get handled fine (now), this is yet pretty ungolfed as is, I just wanted it to get fixed.

```
input: two plus two
output: four

input: twenty-one point five minus one point five
output: twenty

input: one minus two
output: negative one

input: five times five
output: twenty-five

input: twenty-five divided by five
output: five

input: two plus two minus five times five divided by negative zero point five
output: fifty-four

input: one million times one thousand
output: one billion

input: one million times one thousand plus one
output: one billion, one

input: two million plus one million:
output: three million

input: one million plus one million plus one million
output: three million

```

Oh, and if you actually going to test it, it may take a few seconds, as it loads the complete Wolfram Alpha page up to two times.

Well, there might be a lot to enhance though.

# Answer
> 4 votes
## Python, 982

```
from re import*
S=split
U=sub
a=S(' ',U('_','teen ','zero one two three four five six seven eight nine ten eleven twelve thir_four_fif_six_seven_eigh_nine_')+U('_','ty ','twen_thir_for_fif_six_seven_eigh_nine_'))
b=range(20)+range(20,99,10)
d=dict(zip(a,b))
D=dict(zip(b,a))
p='point'
v='negative'
def f(s):
 s=S('[ -]',s);n=0.;m=10**(p in s and(s.index(p)-len(s)))
 for x in s[::-1]:m*=10*(m<1)+100*('hu'in x)+1e3*('ho'in x)+1e6*('m'in x)or 1;n+=(x in d)and m*d[x]
 return n-2*n*(v in s)
def F(n):
 l=[v]*(n<0);x=abs(n)
 for i in(9,6,3,0):z=int(x/10**i);h=z%100;g=(z>99)*[D[z/100],'hundred']+(h>0)*[h in D and D[h]or D[h-z%10]+'-'+D[z%10]];l+=g and g+[[],['thousand'],['million'],['billion']][i/3];x%=10**i
 l+=[c=='.'and p or D[int(c)]for c in'%.2g'%x][n**2>=1:];return' '.join(l)
c=lambda n,l:c(eval(`n`+l[0]+`f(l[1])`),l[2:])if l else n
i=S(' (?=. )|(?<= .) ',U('di.*?y','/',U('times','*',U('minus','-',U('plus','+',raw_input())))))
try:print F(c(f(i[0]),i[1:]))
except:print'E'

```

I think it works as it should according to the specs, but there are probably a few more bugs. It might act weirdly for input \>= one billion or any unexpected words that it interprets incorrectly.

Here's a slightly more readable version with a few changes:

```
import re
words = re.split(' ', re.sub('_', 'teen ', 'zero one two three four five six seven eight nine ten eleven twelve thir_four_fif_six_seven_eigh_nine_') + re.sub('_', 'ty ', 'twen_thir_for_fif_six_seven_eigh_nine_'))
values = range(20) + range(20, 99, 10)
d = dict(zip(words, values))
D = dict(zip(values, words))

def str_to_num(s):
    s = re.split('[ -]', s)
    n = 0.0
    multiplier = 10 ** ('point' in s and (s.index('point') - len(s)))

    for word in s[::-1]:
        multiplier *= 10 * (multiplier < 1) + 100 * ('hundred' == word) + 1e3 * ('thousand' == word) + 1e6 * ('million' == word) or 1
        n += (word in d) and multiplier * d[word]

    return n - 2 * n * ('negative' in s)

three_digit_num_to_str = lambda n: (n > 99) * [D[n / 100], 'hundred'] + (n % 100 > 0) * [n % 100 in D and D[n % 100] or D[n % 100 - n % 10] + '-' + D[n % 10]]

def num_to_str(n):
    word_list = ['negative'] * (n < 0)
    x = abs(n)

    for i in (9, 6, 3, 0):
        three_digit_str = three_digit_num_to_str(int(x / 10 ** i))
        if three_digit_str:
            word_list += three_digit_str + [[], ['thousand'], ['million'], ['billion']][i / 3]

        x %= 10 ** i

    word_list += [char == '.' and 'point' or D[int(char)] for char in '%.2g' % x][n ** 2 >= 1:]
    return ' '.join(word_list)

calculate = lambda n, l: calculate(eval(str(n) + l[0] + str(str_to_num(l[1]))), l[2:]) if l else n

i = re.split(' (?=. )|(?<= .) ', re.sub('di.*?y', '/', re.sub('times', '*', re.sub('minus', '-', re.sub('plus', '+', raw_input())))))

try:
    print num_to_str(calculate(str_to_num(i[0]), i[1:]))
except:
    print 'E'

```

# Answer
> 1 votes
There we go. Golfing the version before broke it, but now we're back online. I'm positive it can be further golfed. I'll work on it more tomorrow. It was hard enough to get it working properly WITHOUT golfing it, though, and my eyes are tired of staring at it. Haha

# Java - 3220

```
import java.util.*;class a{int D=0,i,l,j;static boolean T=true,F=false;enum O{A("plus"),S("minus"),M("times"),D(""),P("point");String t;O(String u){t=u;}double p(double f,double s){if(this==A)f+=s;if(this==S)f-=s;if(this==M)f*=s;if(this==D)f/=s;return f;}static O f(String s){O r=null;for(O o:values())if(s.equals(o.t))r=o;return r;}}enum N{A("zero",0,F),B("one",1,F),C("two",2,F),D("three",3,F),E("four",4,F),AG("five",5,F),G("six",6,F),H("seven",7,F),I("eight",8,F),J("nine",9,F),K("ten",10,F),L("eleven",11,F),M("twelve",12,F),N("thirteen",13,F),O("fourteen",14,F),P("fifteen",15,F),Q("sixteen",16,F),R("seventeen",17,F),S("eighteen",18,F),AH("nineteen",19,F),U("twenty",20,F),V("thirty",30,F),W("forty",40,F),X("fifty",50,F),Y("sixty",60,F),Z("seventy",70,F),AA("eighty",80,F),AB("ninety",90,F),AC("hundred",100,T),AD("thousand",1000,T),AE("million",1000000,T),AF("billion",1000000000,T);String t;double v;boolean q;N(String u,int w,boolean r){t=u;v=w;q=r;}static N f(String s){N r=null;for(N n:values())if(s.equals(n.t))r=n;return r;}static N f(char s){return d(q(""+s));}static N d(double v){N r=null;for(N n:values())if(v==n.v)r=n;return r;}static String c(double n){return d(n).t;}}public static void main(String[]a){new a();}a(){while(T){try{List p=p(new Scanner(System.in).nextLine()),t=new ArrayList();double d=0;for(j=0;j<p.size();j++){Object o=p.get(j);if(o(o)){if((O)o==O.P){t.add((d(t.get(t.size()-1))+((d=d(p.get(j+1)))<10?d*=100:d<100?d*=10:d)/1000));t.remove(t.size()-2);j++;}else t.add(o);}else {N n=N.d(d(o));if(n!=null&&n.q){t.add((d(o))*d(t.get(t.size()-1)));t.remove(t.size()-2);}else t.add(o);}}double r=d(t.get(0));for(j=1;j<t.size();j++){Object c=t.get(j),l=t.get(j-1);if(o(c))continue;if(c instanceof Double&&l instanceof Double)r+=d(c);else r=((O)t.get(j-1)).p(r,d(t.get(j)));}System.out.println(p(r));}catch(Exception e){System.out.println("E");}}}List p(String s) {List r=new ArrayList();Scanner i=new Scanner(s);while(i.hasNext()){String c=i.next();if(c.equals("divided")){r.add(O.D);i.next();}else if(c.indexOf("-")!=-1){String[] num=c.split("-");r.add(N.f(num[0]).v+N.f(num[1]).v);}else{Object o=N.f(c);r.add(o!=null?((N)o).v:O.f(c));}}return r;}String p(double n){String a=String.valueOf(n),w,d=null,b="";l=a.indexOf(".");if(l!=-1){w=a.substring(0,l);d=a.substring(l+1);}else w=a;if(d.equals("0"))d=null;D=0;while(w.length()%3!=0)w=" "+w;for(i=w.length();i>0;i-=3,D++)b=w(w.substring(i-3,i))+b;return b+d(d);}String w(String w) {if(w==null)return "";w=w.trim();String b="";l=w.length();if(l>1&&w.charAt(l-2)!='0'){if(w.charAt(l-2)=='1')b=N.d(q(w.substring(l-2))).t;else b+=N.d(q(w.charAt(l-2)+"0")).t+"-"+N.f(w.charAt(l-1)).t;}for(j=(b.equals("")?l-1:l-3);j>-1;j--){N n=N.f(w.charAt(j));if(n==N.A)continue;if(j==l-1)b=n.t;else if(j==l-2)b=N.f(n.t+"0")+"-"+b;else if(j==l-3)b=n.t+" hundred "+b;}if(!b.trim().equals("")){if(D==1)b+=" thousand ";if(D==2)b+=" million ";if(D==3)b+=" billion ";}return b;}String d(String d) {if(d==null)return"";if(d.length()>3)d=d.substring(0,3);String b = " point ";for(char n:d.toCharArray())b+=N.f(n).t+" ";return b;}boolean o(Object o){return o instanceof O;}Double d(Object o){return (Double)o;}static double q(String s){return Double.parseDouble(s);}}

```

**With line breaks and tabs**

```
import java.util.*;

class a{

    int D=0,i,l,j;
    static boolean T=true,F=false;

    enum O{
        A("plus"),
        S("minus"),
        M("times"),
        D(""),
        P("point");

        String t;
        O(String u){
            t=u;
        }

        double p(double f,double s){
            if(this==A)f+=s;
            if(this==S)f-=s;
            if(this==M)f*=s;
            if(this==D)f/=s;
            return f;
        }

        static O f(String s){
            O r=null;
            for(O o:values())if(s.equals(o.t))r=o;
            return r;
        }
    }

    enum N{
        A("zero",0,F),
        B("one",1,F),
        C("two",2,F),
        D("three",3,F),
        E("four",4,F),
        AG("five",5,F),
        G("six",6,F),
        H("seven",7,F),
        I("eight",8,F),
        J("nine",9,F),
        K("ten",10,F),
        L("eleven",11,F),
        M("twelve",12,F),
        N("thirteen",13,F),
        O("fourteen",14,F),
        P("fifteen",15,F),
        Q("sixteen",16,F),
        R("seventeen",17,F),
        S("eighteen",18,F),
        AH("nineteen",19,F),
        U("twenty",20,F),
        V("thirty",30,F),
        W("forty",40,F),
        X("fifty",50,F),
        Y("sixty",60,F),
        Z("seventy",70,F),
        AA("eighty",80,F),
        AB("ninety",90,F),
        AC("hundred",100,T),
        AD("thousand",1000,T),
        AE("million",1000000,T),
        AF("billion",1000000000,T);

        String t;
        double v;
        boolean q;

        N(String u,int w,boolean r){
            t=u;
            v=w;
            q=r;
        }

        static N f(String s){
            N r=null;
            for(N n:values())if(s.equals(n.t))r=n;
            return r;
        }

        static N f(char s){
            return d(q(""+s));
        }

        static N d(double v){
            N r=null;
            for(N n:values())if(v==n.v)r=n;
            return r;
        }

        static String c(double n){
            return d(n).t;
        }

    }

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

    a(){
        while(T){
            try{
                List p=p(new Scanner(System.in).nextLine()),t=new ArrayList();
                double d=0;
                for(j=0;j<p.size();j++){
                    Object o=p.get(j);
                    if(o(o)){
                        if((O)o==O.P){
                            t.add((d(t.get(t.size()-1))+((d=d(p.get(j+1)))<10?d*=100:d<100?d*=10:d)/1000));
                            t.remove(t.size()-2);
                            j++;
                        }
                        else t.add(o);
                    }
                    else {
                        N n=N.d(d(o));
                        if(n!=null&&n.q){
                            t.add((d(o))*d(t.get(t.size()-1)));
                            t.remove(t.size()-2);
                        }
                        else t.add(o);
                    }
                }

                double r=d(t.get(0));
                for(j=1;j<t.size();j++){
                    Object c=t.get(j),l=t.get(j-1);
                    if(o(c))continue;
                    if(c instanceof Double&&l instanceof Double)r+=d(c);
                    else r=((O)t.get(j-1)).p(r,d(t.get(j)));
                }

                System.out.println(p(r));
            }
            catch(Exception e){
                System.out.println("E");
            }
        }
    }

    List p(String s) {
        List r=new ArrayList();
        Scanner i=new Scanner(s);
        while(i.hasNext()){
            String c=i.next();
            if(c.equals("divided")){
                r.add(O.D);
                i.next();
            }
            else if(c.indexOf("-")!=-1){
                String[] num=c.split("-");
                r.add(N.f(num[0]).v+N.f(num[1]).v);
            }
            else{
                Object o=N.f(c);
                r.add(o!=null?((N)o).v:O.f(c));
            }
        }
        return r;
    }

    String p(double n){

        String a=String.valueOf(n),w,d=null,b="";

        l=a.indexOf(".");
        if(l!=-1){
            w=a.substring(0,l);
            d=a.substring(l+1);
        }
        else w=a;

        if(d.equals("0"))d=null;

        D=0;
        while(w.length()%3!=0)w=" "+w;

        for(i=w.length();i>0;i-=3,D++)b=w(w.substring(i-3,i))+b;

        return b+d(d);
    }

    String w(String w) {
        if(w==null)return "";
        w=w.trim();

        String b="";
        l=w.length();

        if(l>1&&w.charAt(l-2)!='0'){
            if(w.charAt(l-2)=='1')b=N.d(q(w.substring(l-2))).t;
            else b+=N.d(q(w.charAt(l-2)+"0")).t+"-"+N.f(w.charAt(l-1)).t;
        }

        for(j=(b.equals("")?l-1:l-3);j>-1;j--){
            N n=N.f(w.charAt(j));
            if(n==N.A)continue;
            if(j==l-1)b=n.t;
            else if(j==l-2)b=N.f(n.t+"0")+"-"+b;
            else if(j==l-3)b=n.t+" hundred "+b;
        }

        if(!b.trim().equals("")){
            if(D==1)b+=" thousand ";
            if(D==2)b+=" million ";
            if(D==3)b+=" billion ";
        }

        return b;
    }

    String d(String d) {
        if(d==null)return"";
        if(d.length()>3)d=d.substring(0,3);

        String b = " point ";
        for(char n:d.toCharArray())b+=N.f(n).t+" ";

        return b;
    }

    boolean o(Object o){
        return o instanceof O;
    }

    Double d(Object o){
        return (Double)o;
    }

    static double q(String s){
        return Double.parseDouble(s);
    }

}

```

---
Tags: code-golf
---


title: Fastest modular exponentiation

text:
# Question
Title: Fastest modular exponentiation
The challenge is to write code in any open source, available on linux, language of your choice to perform modular exponentiation. The input will be two randomly chosen 2048 bit positive integers numbers x and y and a 2048 bit prime z. Here is a sample snippet of python to compare to.

```
def pow_mod(x, y, z):
    n = 1
    while y:
        if y & 1:
            n = n * x % z
        y >>= 1
        x = x * x % z
    return n

```

The code should accept a file with each of the three numbers on separate lines and output the result to standard out. You may not use any libraries for modular exponentiation of course.

The code that runs the fastest on average over 100 runs on my computer wins.

For those who want really accurate timing, the best way may be for the timing code to actually be in the code you provide and for your code to simply repeat 100 times (without cheating :) ). This avoids any problems with start up overheads.

# Answer
## C++/asm

Runs in about 7ms on my laptop. Less than a factor of 2 away from GMP, which is heavily optimized for this task.

Uses Montgomery reduction to compute the modular reductions quickly. Uses a python script to generate x86 assembly to do the 2048 bit ops (multiply, add, etc.) in great swathes of straightline code.

The code is about 270 lines, a bit big to paste in an answer box. Download it here.
> 1 votes

# Answer
## Haskell

Though it's simple, it should be pretty fast if built with GHC:

```
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}

module Main where

import Data.Bits

seqI :: Integer -> Integer
seqI x = seq x x

seqB :: Bool -> Bool
seqB x = seq x x

getInteger :: IO Integer
getInteger = fmap (seqI . read) getLine

modExp' :: Integer -> Integer -> Integer -> Integer -> Integer
modExp' r b p m = let nextR = seqI $ mod (seqI $ r*b) m
                      nextB = seqI $ mod (seqI $ b*b) m
                      nextP = seqI $ shiftR  p 1
                      incl  = seqB $ testBit p 0
                      cont  = seqB $ nextP  /= 0
                  in  if incl
                         then if cont
                                 then modExp' nextR nextB nextP m
                                 else nextR
                         else if cont
                                 then modExp' r     nextB nextP m
                                 else r

modExp :: Integer -> Integer -> Integer -> Integer
{-# INLINE modExp #-}
modExp !b !p !m = modExp' 1 b p m

main = do
          b <- getInteger
          p <- getInteger
          m <- getInteger
          print $ modExp b p m

```

### Prime modulus optimization

If the modulus is guaranteed to be a prime, but the exponent might be greater than or equal to the modulus, the last line should be changed to:

```
          print $ modExp b (mod p (m - 1)) m

```

### Handling multiple inputs

If you'd like it to handle multiple inputs per run, add `import System.IO` under the other `import` and the following two lines just under the `print` line:

```
          isDone <- isEOF
          if isDone then return () else main

```

### Running

Once it's compiled, it can be run as `modexp < file`.
> 3 votes

---
Tags: fastest-code
---


title: Magic square generator

text:
# Question
Title: Magic square generator
Create the shortest function to print a magic square of given size.

A magic square is a NxN matrix of distinct numbers and the sum of each row, column and diagonal is equal to a constant.

A magic square of size 4 is:

```
07 12 01 14
02 13 08 11
16 03 10 05
09 06 15 04

```

And the constant is 34.

The function should be able to handle inputs up to N = 30 and doesn't need to show leading zeroes.

Using Matlab's `magic` function or similar built-in function is not allowed.

More useful information: http://mathworld.wolfram.com/MagicSquare.html

The output doesn't need to be pretty printed and may contain `[](){},`  or List/Array delimiters of your language. Although, it should use one line for each row

E.g.

```
1, 2,
3, 4,

((9,8),
 (6,7))

[10 2]
[3 456]

```

PS: The corner case, when N = 2 is undefined behavior as there's no magic square of that size.

Also, the function should complete in less than **1 minute** to avoid brute force.

# Answer
> 4 votes
### Ruby, 344 characters

```
q=->n{r=0...n;n%2>0?(m=r.map{[]*n};x=n/2;y=i=0;r.map{r.map{m[y%=n][x%=n]=i+=1;x+=1;y-=1};x-=1;y+=2};m):n<5?[[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]]:(d=q[n/2];r.map{|y|r.map{|x|4*d[b=y/2][a=x/2]-[0,3,2,1,3,0,2,1,3,0,1,2][(n/2%2<1?b<n/4?0:8:a==n/4&&b==n/4?4:a==n/4&&b==n/4+1?0:b<=n/4?0:b==n/4+1?4:8)+y%2*2+x%2]}})}
Q=->n{q[n].map{|s|p s}}

```

You can use it e.g. like

```
Q[3]

```

and the output will be

```
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]

```

The solution is not yet fully golfed. Also huge squares are generated reasonably fast. It uses a recursive function `q` to generate the squares unless `n` is odd in which case the square is generated directly or `n==4` which is hard-coded.

# Answer
> 1 votes
# Q, 50

Works for odd numbers

```
{(+)a rotate'(+)(a:((!)x)-1)rotate'x cut 1+(!)x*x}

```

usage

```
q){(+)a rotate'(+)(a:((!)x)-1)rotate'x cut 1+(!)x*x} 5
24 1  8  15 17
5  7  14 16 23
6  13 20 22 4
12 19 21 3  10
18 25 2  9  11

```

# Answer
> 1 votes
**Magic Square Generator in Python, 127 106 characters**

**106 char code**

`#Works for odd numbers only`

```

n=5
print [[(i+j-1+n/2)%n*n+(i+2*j-2)%n+1for j in range(n)]for i in range(n)]

```
`**127 char code**

`#Works for odd numbers only``
```
n=3
j,A=n/2,[[0]*n for i in[0]*n]
i=c=0
while c<n*n:c=A[i][j]=c+1;i,j=[i+1,[n,i][i>0]-1][c%n>0],[j,[n,j][j>0]-1][c%n>0]
print A

```

See: http://ajs-handling-problems-in-pythonblog.blogspot.in/2013/10/shortest-magic-square-generator-code-in.html

---
Tags: code-golf, math, restricted-time
---


title: Convert CP437 to UTF-8

text:
# Question
Title: Convert CP437 to UTF-8
The goal is to read bytes from input encoded in Code Page 437 and output the same characters encoded as UTF-8. That is, bytes should be translated into Unicode codepoints per this table (a particular revision of the Wikipedia article). Bytes 0-31 and 127 are to be treated as graphics characters.

**Rules**

Input and output is via stdin/stdout, or something equivalent to it (only a function that performs the conversion doesn't qualify). Input is 0 or more bytes before the input stream is closed.

Encoding with UTF-8 is part of the task (as is decoding the input as CP437), so to that end built-in functions or language features that perform conversion between character encodings are not allowed. Submissions should implement the character encoding conversion themselves.

Scoring is pure code-golf, shortest code wins. Code length is measured in bytes assuming the source code is encoded using UTF-8.

**Example**

A byte containing `0x0D` received on input, representing '♪', should output bytes `0xE2`, `0x99`, `0xAA` (in that order), which represents codepoint U+266A encoded in UTF-8.

**Links**

# Answer
### Tcl, 675

```
eval [zlib i Ò×sgÆáB\nPÃïÿòpÁ\f0\fv®4\fBc!j¶%cluYbãdÃw¨)+½MB()zàõÍóÝ=\{vÏì®ÿ¢Ö¶\rk×áóUë\tÌÀOÖ)'*ð,ò¦Ì1\[¦y\v?e~oÀÛ\;¼3)ï*S!ïMgÀÜé¬0OVy_sÌÇï©³@ýa>ÀoïæCMl°7ÎG¸«£Æ'º6Ä\"e±³DÆX*#,Ãïd¹êª²Á&ü®Al±!¬Ì,KË³KÓØèÀ*tbU¶cCìÀöÓíc'VcæKl+¬(V\$µÇFI`ãtc#ô`ôbHbS¤°ú°~vã²ôãrìÁÀäD4!í%\$ÕÉcÃ°(E\\®În²vPÁÕ¨âSÃ5ØË°We?nÚ>Ê°1\"ãÄOyÆð»3Ë,²¯d7dº2)\{iÈ=ý|-w3¥\tÈGå(NÖ0ÙÏ1ä¸lpBý\}\t¾e¾E¾i¾<Y£)KCy~ÎÉçe\v2ÆEç¬rYV¸¢ç&¹*»¸¦\;¸.ÃÜ\]ÜnÉ\ ·ñùÄÇóÍ\ ?ãåøæîàÆøf»xEîá%¹WæÞ(¿é_àwíü7Æ:.ó¿3Ã_¸a©,ð·Ìó>Veÿ°\tëtOpxªS<ÃMð\\e/ð7Oñ7ÂÿzÍ4¯pé´lølÕjZÛV¯\]·råk]

```

Just a simple mapping between input and output. Decompressed it looks like

```
puts [string map { âº  â»  â¥  â¦  â£  â   â¢  â {  } â {
} â {} â {} â {
} âª  â«  â¼  âº  â  â  â¼  Â¶  Â§  â¬  â¨  â  â  â  â  â  â  â²  â¼  â  Ã  Ã¼  Ã©  Ã¢  Ã¤  Ã   Ã¥  Ã§  Ãª  Ã«  Ã¨  Ã¯  Ã®  Ã¬  Ã  Ã  Ã  Ã¦  Ã  Ã´  Ã¶  Ã²  Ã»  Ã¹  Ã¿  Ã  Ã  Â¢  Â£  Â¥  â§  Æ   Ã¡ ¡ Ã ¢ Ã³ £ Ãº ¤ Ã± ¥ Ã ¦ Âª § Âº ¨ Â¿ © â ª Â¬ « Â½ ¬ Â¼  Â¡ ® Â« ¯ Â» ° â ± â ² â ³ â ´ â¤ µ â¡ ¶ â¢ · â ¸ â ¹ â£ º â » â ¼ â ½ â ¾ â ¿ â À â Á â´ Â â¬ Ã â Ä â Å â¼ Æ â Ç â È â É â Ê â© Ë â¦ Ì â  Í â Î â¬ Ï â§ Ð â¨ Ñ â¤ Ò â¥ Ó â Ô â Õ â Ö â × â« Ø âª Ù â Ú â Û â Ü â Ý â Þ â ß â à Î± á Ã â Î ã Ï ä Î£ å Ï æ Âµ ç Ï è Î¦ é Î ê Î© ë Î´ ì â í Ï î Îµ ï â© ð â¡ ñ Â± ò â¥ ó â¤ ô â  õ â¡ ö Ã· ÷ â ø Â° ù â ú Â· û â ü â¿ ý Â² þ â  ÿ Â } [read stdin]]

```
> 4 votes

# Answer
## JavaScript (ES6), 668 bytes

```
console.log(prompt()[p='replace'](/[\S\s]/g,s=>String.fromCharCode(...(z=`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6]).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s)<(x=128)?[z]:z<2048?[0|192+z/64,x+z%64]:[0|224+z/4096,0|x+z%4096/64,x+z%64])))

```

`prompt()`s for input and `console.log()`s the result. Tested in Firefox, utilises ES6 features of arrow functions, template strings and the spread operator (`...`). The bulk of the data here is the string which is a comma separated list of base36 numbers that equate to the UTF-8 code points of the characters to update (1-31, 127-255) and pads the other points with empty space/`NaN`s. The code iterates around each char in the source string, replacing it if necessary. I'm sure it should be possible to shave off more bytes, but I'm done for now! Here's a function for easier testing:

```
c=t=>t[p='replace'](/[\S\s]/g,s=>String.fromCharCode(...(z=(`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6])).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s)<(x=128)?[z]:z<2048?[0|192+z/64,x+z%64]:[0|224+z/4096,0|x+z%4096/64,x+z%64]))

```

Run the above and call `c()` to extract data:

```
c('\x0d').split('').map(s=>`\\x${s.charCodeAt(0).toString(16)}`).join``
"\xe2\x99\xaa"

```

---

## JavaScript (ES6), 618 bytes

There is a method in JavaScript for easily converting to source bytes for Unicode chars (that was shared to me by Mathias Bynens on a conversion tool I'd written!) that involves URL encoding and decoding the string which saves bytes, but I feel isn't in the spirit of the original challenge:

```
console.log(unescape(encodeURIComponent(prompt()[p='replace'](/[\S\s]/g,s=>String.fromCharCode((`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6])).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s)))))

```

and as a function:

```
c=t=>unescape(encodeURIComponent(t[p='replace'](/[\S\s]/g,s=>String.fromCharCode(z=(`BjuBjvBl1Bl2BkzBkwAciBh4BgrBh5Bk2Bk0Bl6Bl7BjwBgaBgkAmtAd8D2CnBfwAncAmpAmrAmqAmoAqnAmsBg2Bgc${','.repeat(96)}DjB0AhAaAcA8AdAfAiAjAgAnAmAkDgDhDlAeDiAsAuAqAzAxB3DyA4CiCjClAg7,b6A9AlArAyApDtCqD6DbAxcCsD9D8ChCrD7Bf5Bf6Bf7Bb6Bc4GtGuGiGhGvGdGjGpGoGnBbkBboBckBccBbwBb4BcsGqGrGmGgBe1GyGsGcBe4GzBe0GwGxGlGkGeGfBe3Be2BbsBbgBewBesBf0Bf4BeoE9A7FfEoFvErD1EsFyFkE1EcAqmEuEdAqxAshCxAslAskAxsAxtAvArsCwAqhD3AqiAf3CyBfkCg`[p](/G/g,'Bd')[p](/[A-F]/g,s=>','+'745qp6'[s[o='charCodeAt']()%6])).split`,`.map(i=>parseInt(i,36))[s=s[o]()]||s))))

```
> 2 votes

# Answer
### Tcl, 183

```
chan con stdin -en cp437
chan con stdout -en utf-8
puts [string map [concat {*}[lmap c [split {☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼} {}] {list [format %c [incr i]] $c}]  ⌂] [read stdin]]

```

You probably have to setup the input/output in your shell to binary, so it does not mangle the input/output.
> 1 votes

---
Tags: code-golf, conversion, unicode
---


title: Bitwise GCD Challenge

text:
# Question
Title: Bitwise GCD Challenge
Write the shortest iterative function to find gcd of two numbers (assume 32 bit numbers).

**Rules:**

* Arithmetic, Comparison and Logical Operators are not allowed **(except equality comparison (`a==b`) operator)**.
* Function should work for both positive and negative numbers
* No inbuilt functions allowed.
* All bitwise operators allowed.

# Answer
> 5 votes
## Python - 196 bytes

```
def A(a,b):
 while b:a,b=a&~b|~a&b,(a&b)<<1
 return a
def G(a,b,i=0):
 if a>>31:a=A(~a,1)
 if b>>31:b=A(~b,1)
 while~a&b|a&~b:c,d=~a&1,~b&1;i=A(i,c&d);a,b=[b,a>>c,A(a,b),b>>d][c|d::2]
 return a<<i

```

Sample usage:

```
from random import randint
for i in range(10):
  a = randint(-2147483647,2147483647)
  b = randint(-2147483647,2147483647)
  print 'gcd(%d, %d) = %d'%(a, b, G(a,b))

```

Sample output:

```
gcd(-36916085, -1872111029) = 1
gcd(1355889652, 1816917540) = 188
gcd(-366482295, 1612196424) = 9
gcd(836632083, -1156302534) = 3
gcd(1223074731, -1299765354) = 123
gcd(-1154829176, 522085100) = 4
gcd(-1673024403, 1589241938) = 1
gcd(-1871498822, -1089342630) = 2
gcd(1653429392, 2095617430) = 2
gcd(1525670601, -1985869899) = 39

```

---

### Implementation Notes

* `A` -\> a function which adds two integers.
* `a&~b|~a&b` -\> `a^b`
* `if a>>31` -\> `if a<0`
* `a=A(~a,1)` -\> `a=-a` (taken together, `if a>>31:a=A(~a,1)` -\> `a=abs(a)`)
* `~a&1` -\> `a%2==0` a.k.a. `a` is even.

The function `G` begins by removing powers of 2 from both `a` and `b` (and shifting the result if both are even). When both `a` and `b` are odd, it continues on with `a=b, b=(a+b)/2`. This works because `gcd(a, b) = gcd(a, a+b)`, and `a+b` is necessarily even. This would terminate noticeably sooner using a comparison and a subtraction (subtracting the smaller value from the larger), but neither are available.

---
Tags: code-golf, math, restricted-source
---


# Question
Title: Golfing: How many unit-length squares in a list of 2d coordinates?
Given a list of 2d (x, y) coordinates, determine how many unit squares (edge length 1 unit) can be formed using the coordinates.

* Input will be an array of 0 or more pairs of coordinates:
e.g. in JavaScript: `numofsq([[0,0], [1,0], [1,1], [0,1]])`
* No duplicate coordinates in input
* Input order will be random (random 2d coordinates).
* Coordinate form: \[x-coordinate, y-coordinate\] (duh)
* Order of coordinates: \[0,0\], \[1,0\], \[1,1\], \[0,1\] and \[0,0\], \[0,1\], \[1,1\], \[1,0\] denote the same unit square (to be counted just once)
* Coordinates can be negative or positive integers (duh)
* Function will return just the number of unit squares possible, 0 or more.

Test cases:

```
Input Coordinates Pairs                                               Expected Output
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2]                              2
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1]                3
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]         4
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0], [9,9]  4

```

---

### Spoiler Alert: Solution stuff here-onwards \[JS\]

Non-Golfed, quick and dirty, brute-force approach (included to provide some directions).

```
//cartesian distance function
function dist(a, b) {
    if (b === undefined) {
        b = [0, 0];
    }
    return Math.sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]));
}

```

---

```
//accepts 4 coordinate pairs and checks if they form a unit square
//this could be optimized by matching x,y coordinates of the 4 coordinates
function isUnitSquare(a) {
    var r = a.slice(),
        d = [],
        c = [],
        i,
        j = 0,
        counter = 0;

    for (i = 1; i < 4; i++) {
        if (dist(a[0], a[i]) === 1) {
            d.push(a[i]);
            r[i] = undefined;
            counter++;
        }
    }
    r[0] = undefined;
    c = d.concat(r.filter(function(a) {return undefined !== a}));

    if (dist(c[0], c[1]) === 1) {j++};
    if (dist(c[1], c[2]) === 1) {j++};
    if (dist(c[2], c[0]) === 1) {j++};
    return counter === 2 && j === 2;
}

```

---

```
//a powerset function (from rosetta code)
//however, we will need only "sets of 4 coordinates"
//and not all possible length combinations (sets of 3 coords or
//sets of 5 coords not required). Also, order doesn't matter.
function powerset(ary) {
    var ps = [[]];
    for (var i=0; i < ary.length; i++) {
        for (var j = 0, len = ps.length; j < len; j++) {
            ps.push(ps[j].concat(ary[i]));
        }
    }
    return ps;
}

//so to capture only sets of 4 coordinates, we do
var res = powerset([[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]])
          .filter(function (a) {return a.length === 8;});

//and a little bit of hoopla to have a nice set of sets of 4 coordinates.
//(Dizzy yet? Wait for the generalized, 3D, cube of any edge length version ;))
var squareQuads = res.map(function(ary) {
    return ary.join().match(/\d\,\d/g)
       .map(function(e) {
           return [+e.split(',')[0], +e.split(',')[1]];
        });
});

```

---

```
//Finally, the last bit
var howManyUnitSquares = 0;
squareQuads.map(function(quad) {
    if (isUnitSquare(quad)) {
        howManyUnitSquares++;
    }
});

console.log(howManyUnitSquares);

```

---

```
//Cleaning up and putting those in-line stuff into a function
function howManySquares(r) { //r = [[x,y], [x,y], [x,y], [x,y], ......];
    var res = powerset(r)
          .filter(function (a) {return a.length === 8;});
    var squareQuads = res.map(function(ary) {
        return ary.join().match(/\d\,\d/g)
               .map(function(e) {
                   return [+e.split(',')[0], +e.split(',')[1]];
                });
    });

    var answer = 0;
    squareQuads.map(function(quad) {
        if (isUnitSquare(quad)) {
            answer++;
        }
    });

    return answer;
}

```

# Answer
> 5 votes
## APL(Dyalog), 30

```
+/{(2-/⍵)≡2-/,⍳2 2}¨,∘.,⍨⍣2⊂¨⎕

```

Well, in most cases, readability and char count is proportional.

---

**Sample Output**

```
⎕:
      (0 0)(0 1)(1 0)(1 1)(0 2)(1 2)(2 2)(2 1)(2 0)
4

```

---

**Explaination**

So, 4 points forms a unit square if and only if their relative positions are (1,1),(1,2),(2,1),(2,2)
`{(2-/⍵)≡2-/,⍳2 2}` is a function that return 1 or 0 (true/false) given a set of 4 points as input based on whether they are in relative positions and sorted in the order (1,1),(1,2),(2,1),(2,2):
`⍳2 2` Generate a 2×2 matrix of the points (1,1),(1,2),(2,1),(2,2)
`,` Unravel that matrix to an array of points
`2-/` Pair-wise subtraction reduce: (1,1) - (1,2) ; (1,2) - (2,1) ; (2,1) - (2,2), which gives the array \[(0,-1),(-1,1),(0,-1)\]
`(2-/⍵)` Pair-wise subtraction reduce on the input
Check if the two arrays equal

The main program
Takes input and evals it. Things like `(0 0)(0 1)(1 0)(1 1)` evaluates to a nested array (Equivalent of `[[0,0],[0,1],[1,0],[1,1]]` in JS)
`⊂¨` For every point (`¨`), enclose it in a scalar () (`[[[0,0]],[[0,1]],[[1,0]],[[1,1]]]`)
`∘.,⍨⍣2` For every pair of elements of the array, concatenate them to form a new array. (`[ [[0,0],[0,0]],[[0,0],[0,1]]...`) Repeat once. This gives all sets of 4 points that can be made using the given points. In some of these sets, the same point would be used multiple times, but these would not be unit squares so no need to waste keystrokes to remove them. (`,` concatenates 2 arrays, `∘.` means "do that for every pair of elements",  means "use right operand as both left and right operands", and `⍣2` means "do this twice")
`,` As the previous operation would give a 4-dimensional array (note that nested arrays and multi-dimensional arrays are different things in APL), we have to unravel it to get an array of sets (of 4 points).
`¨` For each of the sets,
`{...}` execute the aforementioned function. The result would be an array of 0s and 1s indicating whether the set is a unit square. Note that because the function also check ordering, duplicates are eliminated.
`+/` Finally, sum resulting array to get the count.

# Answer
> 3 votes
# Mathematica 65 chars

```
f@d_ := Length@Select[Subsets[d, {4}], Sort[g@#] == {1, 1, 1, 1, √2, √2} &]

```

**Tests**

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

```

> 2

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

```

> 3

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

```

> 4

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

```

> 4

**Explanation**

Generates all subsets of 4 points and checks all the inter-point distances. The sorted inter-point distances for a unit square are: \`{1, 1, 1, 1, √2, √2}.

`Length` then counts the number of unit squares.

# Answer
> 1 votes
## Ruby, ~~164~~ ~~161~~ ~~153~~ 147 characters

```
f=->a{a.combination(4).map(&:sort).uniq.count{|x|[x[1][0]==l=x[0][0],x[3][0]==m=x[2][0],x[2][1]==n=x[0][1],x[3][1]==o=x[1][1],m-l==1,o-n==1].all?}}

```

It's actually *very* readable, except for the part that tests whether it's a unit square or not.

Probably many improvements possible, attempting to find them now.

Samples (all of them work):

```
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2]]]                             #--> 2
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1]]]               #--> 3
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]]]        #--> 4
puts f[[[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0], [9,9]]] #--> 4

```

I may be able to find a trick with `transpose`, but I've been trying for a while and I can't. Here's what it does:

```
irb(main):001:0> a = [[5, 10], [5, 11], [6, 10], [6, 11]]
=> [[5, 10], [5, 11], [6, 10], [6, 11]]
irb(main):002:0> a.transpose
=> [[5, 5, 6, 6], [10, 11, 10, 11]]

```

# Answer
> 0 votes
## Python, 61 chars

```
f=lambda l:sum(1for x,y in l if{(x+1,y),(x,y+1),(x+1,y+1)}<l)

```

Sample:

```
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2)})
2
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2), (2,2), (2,1)})
3
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2), (2,2), (2,1), (2,0)})
4
>>> f({(0,0), (0,1), (1,1), (1,0), (0,2), (1,2), (2,2), (2,1), (2,0), (9,9)})
4

```

# Answer
> 0 votes
# Mathematica, 56 characters

```
f=Count[#-#[[1]]&/@Subsets[{}⋃#.{1,I},{4}],{0,I,1,1+I}]&

```

---
Tags: code-golf, math, combinatorics, geometry
---