# Question
Title: Create a seven-color rainbow with animation
# Goal

Use any graphics library or environment that can use colours and animation to create a rainbow.

# Rules

* The rings should emerge one by one in some kind of animation or succession
* The rainbow must have at least 7 colours.

# Winning Criteria

Fewest bytes wins.

# Answer
> 15 votes
# HTML + CSS + JavaScript (~~447~~ ~~440~~ ~~439~~ ~~432~~ ~~428~~ ~~434~~ ~~390~~ ~~388~~ 383 bytes)

(Byte size went up at one point in order to fulfill “appear one by one” requirement)

(Some credit to Fez Vrasta’s answer for reminding me of the existence of `document.write`)

```
<script>for(d=document,i=0;k=i>>1,k<7;setTimeout(function(w){d.getElementById(w).id="x"+w},555*k,i++))d.write("<b id="+i+"><style>b{width:0;height:0;transition:width 2s,height 2s;border-radius:50ex 50ex 0 0;position:fixed;bottom:-4ex}#x"+i+"{left:"+(9+4*k)+"ex;width:"+(80-6*k)+"ex;height:"+(40-3*k)+"ex;box-shadow:"+(i%2&&"inset 0")+" 0 6ex hsl("+50*k+",99%,50%)}</style>")</script>

```

## Screenshot (see JSFiddle for the full animation)

## Explanation

The rainbow is created by having 7 pairs of `<b>` elements, which are all positioned using `position:absolute` and a `width`, `height`, `left` and `bottom`. Within each pair, they have the same position and size, but one has an “outer” (standard) `box-shadow`, the other an `inset` one, thus creating the nice fuzzy bands. The colors are calculated using `hsl()`, allowing us to vary only the hue but having the same saturation (99%) and lightness (50%) for all. The `<b>` tags are nested inside each other, but this doesn’t matter because all of their positioning is relative to the page.

In the beginning, they all have IDs `0`, `1`, etc., and a styling rule that applies to *all* `b` elements sets their width and height to `0`, making them invisible. The code also outputs styling rules for elements with ID `x0`, `x1`, etc., which initially do not apply.

A `setTimeout` is then used to successively change their IDs from `0` to `x0`, from `1` to `x1` and so on. This triggers a CSS transition which causes them to appear one by one.

```
<script>
    for (d = document, i = 0;      // i loops from 0 to 14
         k = i >> 1, k < 7;        // k loops from 0 to 7
         setTimeout(
             function(w) {
                 // Code to change the element IDs, triggering the CSS transition
                 d.getElementById(w).id = "x" + w
             },
             555 * k,     // 555 milliseconds delay between the appearance of each band
             i++          // This argument is passed into the timeout function
         )
    )
        // For-loop body; creates a <b> element and a <style> element
        d.write(
            // The <b> element (with its initial ID)
            "<b id=" + i + ">" +
            "<style>" +
                // CSS rules that apply to all elements (esp. transition!)
                "b{width:0;height:0;transition:width 2s,height 2s;" +
                "border-radius:50ex 50ex 0 0;position:fixed;bottom:-4ex}" +
                // CSS rules for this specific element
                "#x" + i + "{" +
                    "left:" + (9+4*k) + "ex;" +
                    "width:" + (80-6*k) + "ex;" +
                    "height:" + (40-3*k) + "ex;" +
                    // “i%2” is either 0 or 1; therefore,
                    // “i%2 && "inset 0"” is either 0 or "inset 0"
                    "box-shadow:" + (i%2 && "inset 0") + " 0 6ex " +
                        // 99% is shorter than 100% ;-)
                        "hsl(" + 50*k + ",99%,50%)" +
                "}" +
            "</style>"
        )
</script>

```

# Answer
> 10 votes
# Bash + ImageMagick, 226 bytes

```
r=400
s=""
for c in 008 40c 03f 07f 0c0 ee0 f80 c00
do
s="-stroke '#$c' -draw 'circle 250,280 $r,$r' $s"
eval "convert -size 500x220 xc:'#008' -fill none -strokewidth 10 $s r$r.png"
r=$[r+7]
done
convert -delay 50 r*.png r.gif

```

Produces the following GIF animation:

# Answer
> 7 votes
# BBC BASIC, ~~101~~ 106 Bytes

```
FORC=1TO7GCOLC:A=GET:R=700-C*50FORX=-R TO R:LINE640+X,SQR(R^2-X^2)-200,640+X,SQR((R+50)^2-X^2)-200NEXTNEXT

```

EDIT: added A=GET: so that user must press a key to make each ring appear, to comply with animation requirement. Deleted one unnecessary white space after LINE. The original code can still be seen on the screenshot.

Runs at the command line in Mode 6. Emulator at www.bbcbasic.co.uk

I posted this to show how concise BBC basic was. No complicated libraries to include, all you had to do was type MODE6 and away you went.

Also to demonstrate the drawing of a circle using pythagoras theorem. Ungolfed version:

```
FOR C=1 TO 7
  A=GET                             :REM wait for user to press a key
  GCOL C                            :REM change graphics colour to C
  R=700-C*50                        :REM select the inner radius
  FOR X = -R TO R                   :REM scan through X values
    LINE 640+X,SQR(R^2-X^2)-200,   640+X,SQR((R+50)^2-X^2)-200
  NEXT
NEXT

```

The centre of the circle is at 640,-200. For the inner circle, the Y coordinate (before subtracting 200) is the square root of R^2-X^2, so we are using Pythagoras theorem.

It was specified that the rings be drawn "one by one" so for each X value the program draws a line directly upwards from the inner radius of the current colour to the outer radius. The Y coordinate for finishing the line is the square root of (R+50)^2-X^2 so the radius is 50 more.

Unfortunately the algorithm cannot reach the last bit of the left and right sides of the outer circle, because if we try to go there, the calculation for the inner circle gives a negative square root and the program crashes. The easiest workaround was simply to put the centre of the circle off the bottom of the screen. You can still see a little bit of the uncoloured area at the sides, though.

# Answer
> 6 votes
# Python 2 with Pygame

## First version - 210 198 bytes

```
import pygame as p
s=p.display.set_mode((720,360))
c=p.Color(0,0,0)
for i in range(360,0,-1):
    c.hsla=(i,100,50,100)
    p.draw.circle(s,c,(360,360),i)
    __import__('time').sleep(0.1)
    p.display.flip()

```

This creates a window showing the drawing of a rainbow from the circumference to the center. It takes 36 seconds to complete the rainbow.

## Alternative version - 235

```
import pygame as p
s=p.display.set_mode((720,360))
c=p.Color(0,0,0)
for j in range(360,-45,-45):
    for i in range(j,0,-1):
        c.hsla=(j-i,100,50,100)
        p.draw.circle(s,c,(360,360),j-i)
        __import__('time').sleep(0.01)
        p.display.flip()

```

This alternative version draws some rings with a cooler animation.

# Answer
> 5 votes
# Mathematica, 177

I doubt this is the shortest *Mathematica* way to do it.

```
ListAnimate@Table[Graphics[{Thickness[0.1], Table[{ColorData["Rainbow"]@i, Circle[{0, 0}, 7 i]}, {i, 0, m, 1/7}]}, PlotRange -> {{-8, 8}, {0, 8}}], {m, 0, 1, 1/7}]

```

# Answer
> 4 votes
# GLSL - 234 ~~200~~

(heroku flavor)

At the cost of 34 characters, added animation

```
precision lowp float;uniform vec2 resolution;uniform float time;void main(){float f=distance(gl_FragCoord.xy/resolution,vec2(.5,0))*9.;gl_FragColor=f>2.4&&f<8.?vec4(sin(f+time)+.5,sin(f+2.+time)+.5,sin(f+4.+time)+.5,1):vec4(0,0,0,0);}

```

http://glsl.heroku.com/e#14103.1

## non-animated answer:

```
precision lowp float;uniform vec2 resolution;void main(){float f=distance(gl_FragCoord.xy/resolution,vec2(.5,0))*9.;gl_FragColor=f>2.4&&f<8.?vec4(sin(f)+.5,sin(f+2.)+.5,sin(f+4.)+.5,1):vec4(0,0,0,0);}

```

http://glsl.heroku.com/e#14103.0

# Answer
> 2 votes
## JavaScript: ~~304~~ 239

```
i=-1,s=85,t=20;(function r(){if(++i<7){document.write('<b style=position:absolute;width:80px;text-align:center;font-size:'+s+'px;top:'+t+'px;color:'+['f00','f90','cf0','3f0','0ff','06f','c0f'][i]+'>∩</b>');setTimeout(r,999);s-=5;t+=5}})()

```

## JavaScript 232

**(thanks @Florent for the split idea)**

```
i=7,s=85,t=20;(function r(){if(--i){document.write('<b style=position:absolute;width:80px;text-align:center;font-size:'+s+'px;top:'+t+'px;color:'+'f007f907cf073f070ff706f7c0f'.split(7)[i-1]+'>∩</b>');setTimeout(r,999);s-=5;t+=5}})()

```

yea I know my rainbow sucks **\>\_\<"**

to test it just run this code in the JS console (F12)

# Answer
> 1 votes
# Powershell: 270b (arbitrary width/height) / 307b (screen dimensions)

For a rainbow spanning most of the screen, the following leaks like a sieve, but seems to work (for 307 bytes):

```
$d=@{};Add-Type -A System.Drawing -Pas|foreach{$d[$_.Name]=$_};$g=$d.Graphics::FromHwnd(0);$v=$g.VisibleClipBounds;$y=$h=$v.Height;$h/=9;$c=0;@(65281,11861886,16776961,16744448,256,23296,65536)|foreach{$g.DrawArc((New-Object $d["Pen"]($d.Color::FromArgb(-$_),$h)),-$h,$y-$h*$c++-$h,$v.Width+2*$h,$h,0,-180)}

```

## Ungolfed

```
$d=@{};
Add-Type -A System.Drawing -Pas | foreach { $d[$_.Name]=$_ };        # import .NET naespace "System.Drawing" and copy its members into the $d array
$g = $d.Graphics::FromHwnd(0);                                       # build a Graphics object for the screen
$v = $g.VisibleClipBounds;                                           # determine the screen size
$y = $h = $v.Height;                                                 # init start point for arcs and band height
$h /= 9;                                                             # allow space for 7 bands + clear above and below
$c=0                                                                 # counter

@(65281,11861886,16776961,16744448,256,23296,65536) | foreach {      # ARGB color values for bands (no clever calculation here, just Color.Red.ToARGB(), Color.Orange.ToARGB(), etc...)
    $g.DrawArc(
        (New-Object $d["Pen"](
            $d.Color::FromArgb(-$_),                                 # build a pen from the current color, using width = band-height
            $h
        )),
        -$h,                                                         # x-pos for start of arc (pushed slightly offscreen to avoid weird wide-pen effect)
        $y-$h*$c++-$h,                                               # y-pos for start of arc (moves up each time because of counter increment)
        $v.Width+2*$h,                                               # width of arc (pushed offscreen to avoid weird wide-pen effect)
        $h,                                                          # height of arc always the same
        0,-180                                                       # arc sweep clockwise between 0 and 180 degrees from x-axis)
    )
}

```

Of course, if you don't factor the screen size or the wide-pen effect, and just go with any arbitary width/height, you can lose the `VisibleClipBounds` stuff for approx 270 bytes, but your "animation" speed will be affected by the number of pixels it has to draw:

```
$d=@{};Add-Type -A System.Drawing -Pas|foreach{$d[$_.Name]=$_};$g=$d.Graphics::FromHwnd(0);$y=$h=300;$h/=9;$c=0;@(65281,11861886,16776961,16744448,256,23296,65536)|foreach{$g.DrawArc((New-Object $d["Pen"]($d.Color::FromArgb(-$_),$h)),0,$y-$h*$c++-$h,400+2*$h,$h,0,-180)}

```

## Results

Window-redraw makes it particularly difficult to get a screencap of the full-screen one in action, but the arbitrary-sized one (with the wide-pen awkwardness) looks like:

Edit: OK, I've managed to get a fullscreen cap, but not before some of my screen redrew:

# Answer
> 1 votes
**Disclaimer:** The following solutions work only in Chrome Dev Tools!
**Note:** The following solutions will draw a rainbow with an infinite radius, thus arcs are not curved!

---

# JavaScript (ES6), 121

```
i=0;'f43f82fd03c407d72eb2c'.replace(/.../g,p=>setTimeout("console.log('%c'+' '.repeat(99),'background:#"+p+"')",1e3*i++))

```

Thanks to **@manatwork** for this one!

# JavaScript, 126

```
for(c='f43f82fd03c407d72eb2c',i=7;i--;)setTimeout("console.log('%c'+' '.repeat(99),'background:#'+c.substr("+i+"*3,3))",1e3*i)

```

Details:

```
for(
  // Colors:
  //   - #f43 (red)
  //   - #f82 (orange)
  //   - #fd0 (yellow)
  //   - #3c4 (green)
  //   - #07d (blue)
  //   - #72e (indigo)
  //   - #b2c (purple)
  c='f43f82fd03c407db1c',
  // Iterate through each color
  i=6; i--;
)
  // Delay the arc emergence
  setTimeout(
    // Display a colored line into the console
    "console.log('%c'+' '.repeat(99),'background:#'+c.substr("+i+"*3,3))",
    // 1 second
    1e3*i
  )

```

Rainbow:

---
Tags: code-golf, graphical-output
---


title: Eco-ize data for printing

text:
# Question
Title: Eco-ize data for printing
Inspired by ecofont.

Given a string containing `#` and , output it more eco-friendly by cutting out circles, while keeping it "recognizable" (defined later, in the Circles section). `#` represents black, and represents white. This program is supposed to do something like this:

Input:

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

```

Sample output (rather bad score):

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

```

### Circles

These are the only valid circles (`#`s indicating characters that would be cut out):

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

   #
 #####
 #####
#######
 #####
 #####
   #

```

Every circle cut out must be of the same radius. By "recognizable", I mean that there must be a gap of at least one pixel / point between each circle, and each circle and the edge of the shape (outside of the `#` region):

Again, `#` indicates characters that would be cut out, not characters that would be left behind

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

```

Is invalid, but:

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

```

Is valid. Note that corners are considered touching. That is, in

```
#
 #

```

the two "pixels" are considered touching, thus circles cannot touch in that way.

Also, just to restate it, if we have a shape like:

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

```

Cutting circles like this is invalid (they both touch the edge of the figure):

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

```

### Scoring

Your score is the total number of `#`s left from the specified inputs. Lowest score wins.

Input #1:

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

```

Input #2:

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

```

Input #3:

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

```

Note: Tailoring specifically to the samples is not allowed.

# Answer
> 3 votes
# Python 2.7

Expects the input file to be passed via the command line, e.g.

```
python thisscript.py input1.txt

```

I implemented ~~5~~ 2 options to run:

* Using the small shape
* Using the large shape
* ~~Alternating between the small and large shape~~
* ~~Alternating between the small and large shape randomly~~
* ~~Completely random~~

I just scan the input starting from the top left and a shape is cut away as soon as possible.

The shapes themselves can be modified quite easily.

```
import sys,random,copy

def char2val(c):
    if (c=='#'):
        return 1 # this is the shape itself
    elif (c=='o'):
        return 2 # this is the boundary, for collision detection
    else:
        return 0
def val2char(v):
    if (v==0):
        return ' '
    else:
        return '#'
# convert string to array for processing
def str2arr(s):
    arr = []
    for line in s.split('\n'):
        arr.append( [ char2val(c) for c in line ] )
    return arr
# convert array to string for output purposes
def arr2str(arr):
    s=""
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            s+=val2char(arr[i][j])
        s+="\n"
    return s
# check if a cut we want to make is a valid one
def validate_cut(arr,shape,r,c):
    valid = True
    for i in range(len(shape)):
        for j in range(len(shape[i])):
            if shape[i][j] == 1: #hard cut here
                valid = ( 0 < i+r < len(arr)-1 ) and ( 0 < j+c < len(arr[i+r])-1) # bounds check
                valid = valid and ( arr[i+r][j+c]==1) # site must be cut-able
            elif shape[i][j]==2: #edge of shape
                valid = ( 0 <= i+r <= len(arr)-1 ) and ( 0 <= j+c <= len(arr[i+r])-1) # bounds check, edge allowed to lie on border
                valid = valid and arr[i+r][j+c]!=0 # edge cannot go into cut/empty space
            if not valid:
                return False
    return valid

def cut(arr,shape,r,c): # cut shape from arr, @ position r,c
    for i in range(len(shape)):
        for j in range(len(shape[i])):
            if (shape[i][j] > 0):
                arr[i+r][j+c] -= shape[i][j]
def run(inarr,opt=0):
    arr = copy.deepcopy(inarr)
    for r in range(len(arr)):
        for c in range(len(arr[r])):
            if (opt==0):
                shape = c1arr
            elif (opt==1):
                shape = c2arr
            else:
                raise Exception("run option not supported!")
            if validate_cut(arr,shape,r,c):
                cut(arr,shape,r,c)
    return arr
# global variables for the shapes,...
# \# are the shapes themselves
# o is the boundary used for collision detection
c1 = \
"\
  ooo  \n\
 oo#oo \n\
oo###oo\n\
o#####o\n\
oo###oo\n\
 oo#oo \n\
  ooo  \
"
c2 = \
"\
   ooo   \n\
 ooo#ooo \n\
 o#####o \n\
oo#####oo\n\
o#######o\n\
oo#####oo\n\
 o#####o \n\
 ooo#ooo \n\
   ooo   \
"
c1arr = str2arr(c1)
c2arr = str2arr(c2)
def main():
    #input processing
    random.seed('117')
    f = file(sys.argv[1],"r")
    inp = f.read().rstrip('\n') #input string
    inarr = str2arr(inp)        #convert string to array
    #run the algorithm
    arr0 = run(inarr,opt=0)
    arr1 = run(inarr,opt=1)
    minarr = arr0 if arr2str(arr0).count('#') < arr2str(arr1).count('#') else arr1
    #output
    print arr2str(minarr)
    print " %d # of %d remaining " % (arr2str(minarr).count('#'),inp.count('#'))
main()

```

The results are

## Input1

```
1102 # of 2030 remaining

```

## Input2

```
1766 # of 2955 remaining

```

## Input3

```
514 # of 748 remaining

```

Full output for input3:

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

```

## Total score: 3382

# Answer
> 6 votes
# PHP

\**WARNING : spaghetti english and spaghetti code ahead \**

Okay, not sure I understood everything but here's my try. So what is done ?

* Convert text input to an image. " " = white pixel, "#" = red pixel. Example :
* Draw holes inside image, cheking to not collide on a previous one. Example :
* Convert back image to text

(not sure about this red dot in the bottom right corner but, he, yolo)

```
<?php

    /* Check collision between white pixels in 2 images. */
    function checkCollision ($img1, $img2, $width, $height, $circle_x, $circle_y, $circle_size)
    {
        $start_x = $circle_x - round($circle_size / 2);
        if ($start_x < 0) return false;

        $stop_x = $circle_x + round($circle_size / 2);
        if ($stop_x > ($width - 1)) return false;

        $start_y = $circle_y - round($circle_size / 2);
        if ($start_y < 0) return false;

        $stop_y = $circle_y + round($circle_size / 2);
        if ($stop_y > ($height - 1)) return false;

        $color_white = array("red" => 255,
                "green" => 255,
                "blue" => 255,
                "alpha" => 0
                );

        for ($y = $start_y; $y < $stop_y - 1; $y++)
            for ($x = $start_x; $x < $stop_x - 1; $x++)
            {
                $pixel_img1 = imagecolorsforindex($img1, imagecolorat($img1, $x, $y));
                $pixel_img2 = imagecolorsforindex($img2, imagecolorat($img2, $x, $y));

                if ($pixel_img1 == $pixel_img2
                    && $pixel_img1 == $color_white)
                        return false;
            }

        return true;
    }

    $input      = file_get_contents("input.txt");
    $lines      = explode("\n", $input);
    $image_width    = strlen($lines[0]);
    $image_height   = count($lines);
    $circle_size    = 5;

    /* Creating an image matching dimensions and some colors. */
    $img            = imagecreatetruecolor($image_width, $image_height);
    $color_red      = imagecolorallocate($img, 255, 0, 0);
    $color_white        = imagecolorallocate($img, 255, 255, 255);

    /* Filling the freshly created image. '#' is replaced by a red pixel, ' ' by a white one. */
    for ($y = 0; $y < $image_height; $y++)
    {
        $line = $lines[$y];
        for ($x = 0; $x < strlen($line); $x++)
            if ($line[$x] == '#')
                imagesetpixel($img, $x, $y, $color_red);
            else
                imagesetpixel($img, $x, $y, $color_white);
    }

    /*Try to draw a circle on any red pixel then check if
    it not collides with any other white space before commiting */

    for ($y = 0; $y < $image_height; $y++)
        for ($x = 0; $x < $image_width; $x++)
        {
            $img_tmp = imagecreatetruecolor($image_width, $image_height);
            imagecopy($img_tmp, $img, 0, 0, 0, 0, $image_width, $image_height);

            imagefilledellipse($img_tmp, $x, $y, ($circle_size + 2), ($circle_size + 2), $color_white);

            if (checkCollision ($img, $img_tmp, $image_width, $image_height, $x, $y, ($circle_size + 2)))
                imagefilledellipse($img, $x, $y, $circle_size, $circle_size, $color_white);
        }

    /* Convert image to text */
    $output = "";
    $color_white = array("red" => 255,
            "green" => 255,
            "blue" => 255,
            "alpha" => 0
            );

    for ($y = 0; $y < $image_height; $y++)
    {
        for ($x = 0; $x < $image_width; $x++)
        {
            $pixel_img = imagecolorsforindex($img, imagecolorat($img, $x, $y));
            if ($pixel_img == $color_white)
                $output = $output . " ";
            else
                $output = $output . "#";
        }
        $output = $output . "\n";
    }

    file_put_contents("output.txt", $output)

?>

```

Spent a lot of time because I didn't know I could not just copy a GD ressource doing $a = $b.. (it creates a ref)

# Example :

## Input :

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

```

## Output :

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

```

I hope this hit the target. It's obvious that we can do it better and more properly but maybe it would help the others to understand what this code challenge is about.

# Score

## Input 1 :

> Before : 2030 "#"
> After : 1575 "#"
> 455 removed

## Input 2 :

> Before : 2955 "#"
> After : 2370 "#"
> 585 removed

## Input 3 :

> Before : 748 "#"
> After : 618 "#"
> 130 removed

## Total :

> "#" input : 5733
> "#" left : 4563 (~80%)
> "#" removed : 1170 (~20%)

# FINAL SCORE : 4563

;\_;

---
Tags: code-challenge, packing
---


# Question
Title: Graphical, networked, two-(human)-player Tic-Tac-Toe
Create a Tic-Tac-Toe game that allows two human players to play against each other using two networked devices.

Requirements:

1. Network play.
2. Program must let both players know whose turn it is.
3. Program must show who won and how (like drawing a line through the three in a row).
4. Graphical game board displayed for both players.
5. Player moves inputted "graphically" (point and click, etc...).
6. Enforce all Tic-Tac-Toe rules.

Preferred:

1. Any libraries are allowed but smaller libraries are better.
2. Support as many different platforms/devices as possible.
3. Make it "pretty".

I would love to invent scoring that would take into account the "Preferred" points, but that appears impossible. So vote for the code that does the best on the "Preferred" points.

Scoring:

* `byte count / vote count`
* lowest score wins

# Answer
> 3 votes
# PHP, work in progress (474 chars / 2 upvotes = 237 score)

It's fully functional except it doesn't have win detection yet.

>

What I *really* like about this solution is that I only learned PHP about 3 days ago, so the code is probably terrible. :D

### t.php, 474 chars (newlines can be removed and are there only for readability):

```
<style>#d>*{display:block;border:1px solid #000;width:50px;height:50px;float:left;text-align:center}#d{width:160px}</style><div id=d><?php
$f=file("a");$p=$_GET["p"];if($p!="x"&&$p!="o")die();
if(isset($_GET["m"])){$s=$f[0];$s[intval($_GET["m"])]=$p;fwrite(fopen('a','w'),$s.($f[1]=='x'?'o':'x'));echo"<a href='t.php?p=$p'>back</a>";}
else{$i=0;while($i<9){$s=($p==$f[1]&&$f[0][$i]=='.')?'a':'div';echo"<$s href='t.php?p=$p&m=$i'>".$f[0][$i++]."</$s>";}echo $f[1]."'s turn";}
?>

```

### reset.php, 57 chars

```
<?php fwrite(fopen('a','w'),"..........\nx");?>Reset done

```

---

It's live on my website. Player X should go to this URL:

```
http://keyboardfire.com/misc/tictactoegolf/t.php?p=x

```

And Player O should go here:

```
http://keyboardfire.com/misc/tictactoegolf/t.php?p=o

```

(don't worry, I added a check that only lets player "o" or "x" in so that you can't do any fancy XSS stuff :P)

To reset, go here:

```
http://keyboardfire.com/misc/tictactoegolf/reset.php

```

Obviously, it's really easy to cheat (moving for the other player, randomly resetting the board, etc.), but it's code golf so it doesn't matter :P

---
Tags: code-challenge, popularity-contest, game, graphical-output, tic-tac-toe
---


title: ASCII-art videogame edition

text:
# Question
Title: ASCII-art videogame edition
I thought it might be fun to throw this on here.
Generate an ASCII-art for one of your favorite videogames.

What you want to generate is up to you but it should meet 2 requirements.

1. It should be able to identify the game. So either a logo or something familiar like the triforce in Zelda. a pokeball for pokémon or an actual pokémon.
2. Make it solid.

I'm guessing the second requirement is a bit vague, I just dont know how to explain it so let me show you with the triforce.

```
Wrong
       /\
      /__\
     /\  /\
    /__\/__\

Right
           #
          ###
         #####
        #######
       #       #
      ###     ###
     #####   #####
    ####### #######

```

This is a popularity-contest, so be creative and dont worry about the length of your code.

### Rules

* No external resources
* You can use any language you like

**Edit**
You are meant to write some kind of algorithm that will create your ascii art rather than simply arranging the characters.
*Sorry for changing the question*

Happy Coding!

# Answer
> 14 votes
## Bash

An actual pokémon? Ok. I present the Voltorb, seen from behind.

```
#!/bin/bash
echo -e '\e[31m'    # escape character for red font
s=6
for i in `seq 8 2 16`; do
    if [ $i -ne 10 ]; then
        for j in `seq $s`; do
            echo -n ' '
        done
        for j in `seq $i`; do
            echo -n '#'
        done
        echo
    fi
    s=`expr $s - 1`
done
echo -e -n '\e[97m'    # escape character for white font
s=2
for i in `seq 16 -2 8`; do
    if [ $i -ne 10 ]; then
        for j in `seq $s`; do
            echo -n ' '
        done
        for j in `seq $i`; do
            echo -n '#'
        done
        echo
    fi
    s=`expr $s + 1`
done
echo -e '\e[0m'    # escape character for default font color

```

Output:

# Answer
> 10 votes
## Javascript

**Invaders !**

```
for(j=8,o='';j--;o+='\n')for(i=11;i--;)o+=1&"ĎĘƾŭĽļĽŭƾĘĎ".charCodeAt(i)>>j?'##':'  '

```

Output :

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

```

**Triforce**

```
for(j=8,o='';j--;o+='\n')for(i=15;i--;)o+=1&"āăćďėĳűǰűĳėďćăā".charCodeAt(i)>>j?'##':'  '

```

Output :

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

```

Any 8-lines (can be extended to 16 easily) logo can be displayed with that code, you have to change only the encoding string.
Each character of the string corresponds to a column.
You can also declare a generic function :

```
function f(s){for(j=8,o='';j--;o+='\n')for(i=s.length;i--;)o+=1&s.charCodeAt(i)>>j?'##':'  ';return o}
f('ĎĘƾŭĽļĽŭƾĘĎ'); //invaders
f('āăćďėĳűǰűĳėďćăā'); //triforce

```

To encode the column (8bits), use `parseInt`, specify the bits with a `1` at the start to enforce unicode.

Example for the first part of the triforce :

```
String.fromCharCode(parseInt('100000001',2),parseInt('100000011',2),parseInt('100000111',2),parseInt('100001111',2),parseInt('100010111',2),parseInt('100110011',2),parseInt('101110001',2),parseInt('111110000',2))

```

Output: `"āăćďėĳűǰ"`

# Answer
> 7 votes
## Python 2.7

```
#!/bin/python2

a,b=[[78,20],[2,20,47,28],[5,20,40,27],[0,23,37,23],[2,21,14,28],[0,24,29,32],[2,22,21,40],[4,19,20,42],[8,14,13,49],[7,75],[6,66],[5,65],[3,58],[2,48],[2,33],[2,30],[2,28],[1,28],[1,28],[1,28],[1,28],[1,27],[1,27]],[]
for l in a:
    c=' '
    b.append([])
    for i in l:
    b[-1].append(c*i)
        c=[' ','#'][c==' ']
b[4]=b[4][:2]+['        OBJECTION!!']+b[4][2:]
for l in b: print ''.join(l)

```

**Output**

```
                                                                              ####################
  ####################                                               ############################
     ####################                                        ###########################
#######################                                     #######################
  #####################        OBJECTION!!              ############################
########################                             ################################
  ######################                     ########################################
    ###################                    ##########################################
        ##############             #################################################
       ###########################################################################
      ##################################################################
     #################################################################
   ##########################################################
  ################################################
  #################################
  ##############################
  ############################
 ############################
 ############################
 ############################
 ############################
 ###########################
 ###########################

```

Of course, based on:

It's not a particularly novel method of generating the output, nor is it fantastic ASCII art (it looks more like a gun than a pointer finger, and the spiky hair doesn't come across great), but there isn't enough Ace Attorney in here! :)

# Answer
> 6 votes
## Game Maker Language

```
a="    "
b=a+a+a
c=b+b
d="------"
show_message(a+"  _=====_"+c+a+"   _=====_# "+a+"/ _____ \"+c+a+" / _____ \#   +.-'_____'-."+d+d+d+d+"---.-'_____'-.+#  /   |     |  '."+a+a+"S O N Y+a+a+"'  |  _  |   \# / ___| /|\ |___ \"+b+a+a+" / ___| /_\ |___ \#/ |      |      | ;  __"+a+a+"   _   ; | _         _ | ;#| | <---   ---> | | |__|"+a+a+" |_:> | ||_|   "+a+"(_)| |#| |___   |   ___| ;SELECT"+a+"   START ; |___   "+a+"___| ;#|\    | \|/ |    /  _"+a+" ___  "+a+"_   \    | (X) |    /|#| \   |_____|  .','' '', |___|  ,'' '', '.  |_____|  .' |#|  '-.______.-' /       \ANALOG/   "+a+"\  '-._____.-'   |#|"+b+"   |   "+a+"|"+d+"|"+a+"   |"+b+a+"#|"+b+"  /\   "+a+"/ "+a" \   "+a+"/\   "+b+"|#|"+b+" /  '.___.'"+a+a+"'.___.'  \"+b+"  |#|"+b+"/"+c+a+"\"+b+" |# \  "+a+a+"/  "+c+a+"\"+a+a+"   /#  \________/"+c+a+a+"\_________/")

```

**Result** (SE has too much whitespace, try copying to Notepad)

```
      _=====_                               _=====_
     / _____ \                             / _____ \
   +.-'_____'-.---------------------------.-'_____'-.+
  /   |     |  '.        S O N Y        .'  |  _  |   \
 / ___| /|\ |___ \                     / ___| /_\ |___ \
/ |      |      | ;  __           _   ; | _         _ | ;
| | <---   ---> | | |__|         |_:> | ||_|       (_)| |
| |___   |   ___| ;SELECT       START ; |___       ___| ;
|\    | \|/ |    /  _     ___      _   \    | (X) |    /|
| \   |_____|  .','' '', |___|  ,'' '', '.  |_____|  .' |
|  '-.______.-' /       \ANALOG/       \  '-._____.-'   |
|               |       |------|       |                |
|              /\       /      \       /\               |
|             /  '.___.'        '.___.'  \              |
|            /                            \             |
 \          /                              \           /
  \________/                                \_________/

```

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


title: Insert typos into text

text:
# Question
Title: Insert typos into text
I wrote some text, but it looks too professional. I want to make it look like I was really tired when I wrote it. I need you to insert some typos.

Your challenge is to take an arbitrary single line of text, and add typos. This means that for each character, there will be a 10% chance for it to be typofied.

The definition of "typofied" is that you must choose (randomly) one of the following:

* Duplicate the character.
* Delete the character.
* Shift the character one keyboard space. The "keyboard" is defined as:

```
qwertyuiop
asdfghjkl
 zxcvbnm

```

For the character shift, you must go one space up, down, left, or right. This must be chosen randomly. The shift option only applies to alphabetic characters. Case must be preserved. Be careful with edge-cases, like `m`!

The definition of "random" is that the result must not be predictable (by looking at previous results). For example, you can't typofy every tenth character. Furthermore, the randomness must have an even distribution. For example, you can't do 30% duplicate, 30% delete, and 40% shift; it has to be a 1/3 chance for each (1/2 for each if it's a nonalphabetic character).

Example input:

```
This is some correct text. It is too correct. Please un-correctify it.

```

Example output:

```
This iissome xorreect tex..  It is too coteect. Please jn-corretify it.

```

This is , so the shortest code in bytes will win.

# Answer
> 15 votes
### GolfScript, 120 characters

```
{10{rand}:R~!{[{.}{;}{Z\?[.(.10-@).10+]{Z=}%' '-.,R=}]'QWERTYUIOP ASDFGHJKL  ZXCVBNM'' '22*11/*.{32|}%+:Z 2$?0>2+R=~}*}%

```

The code can be tested here.

```
{                      # loop over all characters
  10{rand}:R~!         # take random number [0..9] and negate (i.e. 10% chance of true)
  {                    # {...}* is the if-block
    [                  # Three possible operations (code blocks) in the arry
      {.}              # a) duplicate
      {;}              # b) delete
      {                # c) shift
        Z              #      Z is the keyboard layout (see below)
        \?             #      Find the index of the current letter
        [.(.10-@).10+] #      Calculate index of letter left, right, above, below
        {Z=}%          #      Extract the corresponding letters for indices
        ' '-           #      Remove any spaces
        .,R=           #      Take random item
      }
    ]
                       # Z is the keyboard layout (upper and lower case)
                       # with enough spaces around
    'QWERTYUIOP ASDFGHJKL  ZXCVBNM'' '22*11/*.{32|}%+:Z
    2$?0>              # Is the current letter contained in Z and not a space?
    2+                 # Add 2 (i.e. 3 for letters, 2 for any other char)
    R=                 # Take a random code block from above
    ~                  # Execute the block
  }*
}%

```

# Answer
> 19 votes
# C, 358 bytes

(There are only three lines of code, but I've broken up line 3 for legibility)

```
#define x putchar
#define y random()
c,n;main(){char*s[26]={"QS","HNV","FVX","EFSX","DRW","CDGR","FHTV","BGJY","KOU","HKNU",
"IJLM","KO","KN","BJM","ILP","OO","AW","EFT","ADWZ","GRY","IJY","BCG","ESQ","CDZ","HTU",
"SX"};while((c=getchar())>0){if(y%10>0&&x(c))continue;if(isalpha(c)&&y%3<1){n=(c&31)-1;
x(s[n][y%strlen(s[n])]|(c&32));continue;}if (y&1)x(x(c));}}

```

The array of strings at the beginning lists the possible adjacent keys for each letter of the alphabet. I had to double up the "O" (adjacent to "P") to avoid calculating `random()%1` when selecting a shifted character.

Test run:

```
$ echo "This is some correct text. It is too correct. Please un-correctify it." |./a.out
This is some  cofrect teext. It is too correct.. Plleaase un-correctify it..

```

---

**Update:**

Here's an expanded and commented version of the same source code:

```
#include <stdio.h>
#include <string.h>
/* ^^ These should be included, but the code compiles without them */

int c,n;

void main() {

  /* Adjacent keys for each letter of the alphabet (A, B, C, ..., Z): */
  char *s[26] = { "QS","HNV","FVX","EFSX","DRW","CDGR","FHTV","BGJY","KOU","HKNU",
                  "IJLM","KO","KN","BJM","ILP","OO","AW","EFT","ADWZ","GRY","IJY",
                  "BCG","ESQ","CDZ","HTU","SX" };

  /* Fetch input until null character or EOF reached */
  while ((c=getchar())>0) {

    /* For 90% of the time, just echo the character unchanged */
    if (random()%10>0 && putchar(c)) continue;

    /* If it's a letter of the alphabet, shift with 33% probability */
    if (isalpha(c) && random()%3<1) {
      /* Calculate offset to adjacent keys data */
      n=(c&31)-1;
      /* Choose a random adjacent key, and change to lower case if needed */
      putchar(s[n][random()%strlen(s[n])]|(c&32));
      continue;
    }

    /* If we reach this point, either we didn't fetch an alphabet character, or   */
    /* we did but chose not to shift it. Either way, we now need to either repeat */
    /* the character or delete it, with 50% probability for each. */

    /* This repeats the character by printing the return value from putchar() */
    if (random()&1) putchar(putchar(c));

    /* To delete the character, we don't have to do anything. */
  }
}

```

# Answer
> 19 votes
## Ruby, 168

Slightly shorter take using an array indexing strategy:

```
z='qwertyuiop.asdfghjkl...zxcvbnm'+?.*11
gets.chars{|c|$_=z[c]?z:z.upcase
h=[1,-1,11,-11].map{|d|$_[d+~/#{c}/]}-[?.]rescue[]
$><<(rand<0.9?c:[c*2,'',*h.sample].sample)}

```

Original regular expression version (184):

```
s='.qwertyuiop.asdfghjkl...zxcvbnm.'
gets.chars{|c|c=~/\w/&&(s[c]?s: s.upcase)=~/((\w).{9})?((\w)|.)#{c}((\w)|.)(.{9}(\w))?/
$><<(rand<0.9?c:[c*2,'',*[*$2,*$4,*$6,*$8].sample].sample)}

```

# Answer
> 9 votes
# Python, 251

```
from random import*
w=choice
o=ord
print"".join(w([z]*9+[w(["",z*2]+[chr(o(w("DGRC FHTV GJYB UOK HKUN JLIM KO NK BMJ IPL O WA ETF ADWZ RYG YIJ CBG QES ZCD TUH XS SQ VNH XVF SFEX WRD".split()[(o(z)&31)-6]))|o(z)&32)]*z.isalpha())])for z in raw_input())

```

Very simple look-up technique, for a moment I thought it might be cheaper to encode the keyboard as a undirected graph but the overhead for creating such a type in Python proved prohibitive. Since Python's random functions have too-descriptive names I use `choice()` exclusively, renaming it to `w`. The 10% chance of error is handled by `w([z]*9+[...])` where the nine copies of an un-typoed character are in a list with one typo.

<sub>-16 characters--thanks grc, +2 characters (and correctness, worth many more than 2 chars)--thanks Dhara</sub>

# Answer
> 8 votes
## C#, 320 bytes (360 bytes with program wrapping)

Includes support for "shifted" upper-case letters.

As a function (320 bytes):

```
string T(string s){
    string t="",z="      ",k=z+z+"qwertyuiop asdfghjkl   zxcvbnm";
    k+=k.ToUpper()+z+z;
    int[]m={-11,-1,1,11};
    var r=new System.Random();
    foreach(var c in s){
        if(r.Next(10)>0)
            t+=c;
        else{
            int i=r.Next(k.IndexOf(c)>0?3:2);
            if(i>1){
                while(' '==k[i=k.IndexOf(c)+m[r.Next(4)]]);
                t+=k[i];
            }
            else if(i>0)
                t=(t+c)+c;
        }
    }
    return t;
}

```

As a program that reads a line of text (360 bytes):

```
using System;
class P{
    static void Main(){
        string t="",z="      ",k=z+z+"qwertyuiop asdfghjkl   zxcvbnm";
        k+=k.ToUpper()+z+z;
        int[]m={-11,-1,1,11};
        var r=new Random();
        foreach(var c in Console.ReadLine()){
            if(r.Next(10)>0)
                t+=c;
            else{
                int i=r.Next(k.IndexOf(c)>0?3:2);
                if(i>1){
                    while(' '==k[i=k.IndexOf(c)+m[r.Next(4)]]);
                    t+=k[i];
                }
                else if(i>0)
                    t=(t+c)+c;
            }
        }
        Console.Write(t);
    }
}

```

Input output sample:

```
This is some correct text. It is too correct. Please un-correctify it.
This  is some corrrect texy. Ut is too correct. Pease un-coorrectify it.

TYPO RAGE CAPS TEXT!
TYPPORAGE CAOS TEX!

```

# Answer
> 8 votes
## JS, 303, 288, 275, 273, 274 (bug fix)

```
function z(s){return s.split('').map(function(d){if((r=Math.random)(b='qwertyuiop0asdfghjkl000zxcvbnm')>.1)return d
if((c=r(x=(d>'`'?b:(b=b.toUpperCase())).indexOf(d))*(/[a-z]/i.test(d)+2))<2)return c>1?d+d:''
for(a=0;!a;)a=b[x+[11,-11,1,-1][~~(r()*4)]]
return a}).join('')}

```

Algorithm for the keyslip:

* find char in string (or uppercase)
* add 11, -11, 1 or -1 to the index.
* if it's invalid (0 or null), re-roll

Non-Golfed version per request:

```
function z (s) {
  return s.split('') // split input string into characters.
          .map( // and then for each character...
    function (d) {
      r = Math.random; // set up a shortened form of Math.random
      // declare keyboard here because we have parens and we can save a delimeter.
      b = 'qwertyuiop0asdfghjkl000zxcvbnm';
      if (r() > .1) {  // normal case
        return d;
      }
      numOptions = /[a-z]/i.test(d) + 2; // if it's a character, 1+2, else 0+2 options

      // test here because we have parens. x might be -1
      if (d > '`') {
        x = b.search(d);  // x marks the spot
      } else {
        b = b.toUpperCase();
        x = b.search(d);
      }

      c = r() * numOptions; // chars can be 0-3, non-chars: 0-2
      if (c < 2) {                // this case is simple, so it comes first
        return c>1 ? d + d : ''; // double or omit.
      }

      // we must be in keyslip mode.

      // in the golfed code, this while loop become for loops,
      // but it's really a while.
      a = 0;
      while (!a) { // that is, a != null && a != 0
        v = ~~(r() * 4); // 0, 1, 2, or 3
        newX = x + [11, -11, 1, -1][v]; // choose one
        a = b[newX];  // slip the key
      }
      return a;
    }
  ) // end the map function
  .join('') // and then reassemble the string
}

```

# Answer
> 6 votes
## Perl, ~~278~~ ~~239~~ ~~197~~ ~~169~~ ~~162~~ ~~156~~ ~~151~~ 149

```
s#((\pL)|.)#rand>.1?$&:($&x2,'',do{1until/^.{@{[(2,-10,12)[rand 4]-1+index$_=QWERTYUIOP0ASDFGHJKL000ZXCVBNM,uc($,=$&)]}}(\D)/;$,&' '|$1})[rand@-]#ge

```

Run with `-p`, then 148+1=149 bytes. E.g.:

```
perl -p typos.pl
Your challenge is to take an arbitrary single line of text, and add typos.
You challenge is to tale an  arbitrary singe lind of text, and add yposs.
This is some correct text. It is too correct. Please un-correctify it.
This iis some correct text. It s too coorrect.Pleqse un-correctify it.

```

Un-golfed, more or less:

```
s#((\pL)|.)#rand>.1
    ? $&
    : ($&x2,'',
        do{
            1until/^.{@{[(2,-10,12)[rand 4]-1
                +index$_=QWERTYUIOP0ASDFGHJKL000ZXCVBNM,uc($,=$&)]}}(\D)/;
            $,&' '|$1
        }
    )[rand@-]
#ge

```

At first I thought that choosing element randomly in an array (of 26 of them of different lengths) is more statistically 'clean' (i.e. random), but maybe it was wrong. (See previous version.) This last attempt is, following the leaders:-), stepping along a string by either -1,1,-11,11 (randomly) and repeating until valid step.

Edit: Thanks to **tobyink** help and other optimizations, we managed to considerably reduce code size.

The last approach uses some tricks with regexp search to find valid step along substitution string, eliminating manual checks.

Another edit: 5 bytes off because we don't need integers for array indexes + small trick with illegal array index. I tried same trick with `[-4+rand@-]` (i.e. negative indexes) and get rid of one list element, `'',` but it didn't save anything.

Edit: Back to simplicity - replacing condition `~~rand 10` with `rand>.1` saves 2 bytes...

# Answer
> 4 votes
# **PHP, function with 368 bytes**

Here is my attempt.

It's some "frankencode", but it **kinda** works.

```
function _($m){$q=array(array('qwertyuiop','asdfghjkl',' zxcvbnm'),'!.-,;?+/');$r='mt_rand';foreach(str_split($m)as$k=>$c)if(!$r(0,9)&&$c!=' ')foreach($q[0]as$x=>$y)if(($z=strpos($y,$c))!==!1){switch($t=$r(-3,2-($z>>3)-($x>>1))){case 2:++$z;break;case 1:++$x;break;case -1:--$x;break;case -2:--$z;break;case -3:$z=8;break;}$m[$k]=$t?$q[0][$x][$z]:$q[1][$z];}return$m;}

```

A more "readable" code:

```
function _($m)
{
    $q=array(array('qwertyuiop','asdfghjkl',' zxcvbnm'),'!.-,;?+/');
    $r='mt_rand';
    foreach(str_split($m)as$k=>$c)
        if(!$r(0,9)&&$c!=' ')
            foreach($q[0]as$x=>$y)
                if(($z=strpos($y,$c))!==!1)
                {
                    switch($t=$r(-3,2-($z>>3)-($x>>1)))
                    {
                        case 2:
                            ++$z;break;
                        case 1:
                            ++$x;break;
                        case -1:
                            --$x;break;
                        case -2:
                            --$z;break;
                        case -3:
                            $z=8;break;
                    }
                    $m[$k]=$t?$q[0][$x][$z]:$q[1][$z];
                }
    return$m;
}

```

The only difference between the 2 codes is that one has tons of tabs and newlines.

It doesn't produce the same exact type of "incorrectness", but it either deletes or replaces a char using the said conditions.

You can try it at http://writecodeonline.com/php/.

Copy and paste this code:

```
function _($m){$q=array(array('qwertyuiop','asdfghjkl',' zxcvbnm'),'!.-,;?+/');$r='mt_rand';foreach(str_split($m)as$k=>$c)if(!$r(0,9)&&$c!=' ')foreach($q[0]as$x=>$y)if(($z=strpos($y,$c))!==!1){switch($t=$r(-3,2-($z>>3)-($x>>1))){case 2:++$z;break;case 1:++$x;break;case -1:--$x;break;case -2:--$z;break;case -3:$z=8;break;}$m[$k]=$t?$q[0][$x][$z]:$q[1][$z];}return$m;}
echo _('This is some correct text. It is too correct. Please un-correctify it.');

```

After testing, please, tell me if it is a valid answer.

# Answer
> 3 votes
# C#, 581 bytes

```
using System;class B{static void Main(){var z=Console.ReadLine();var r=new Random();foreach(char C in z){String o;if(r.Next(10)==0){int w=r.Next(3);o=w==0?C+""+C:w==1?"":f(C,r);}else{o=C+"";}Console.Write(o);}Console.ReadLine();}static string f(char C,Random r){string[]k={"00000000000","0qwertyuiop0","0asdfghjkl0","00zxcvbnm0","000000000"};char L=char.ToLower(C);char h='0';for(int i=1;i<4;i++){var d=k[i].IndexOf(L);if(d!=-1){while(h=='0'){int n=r.Next(4);h=n==0?k[i][d-1]:n==1?k[i][d+1]:n==2?k[i-1][d]:k[i+1][d];}h=char.IsUpper(C)?char.ToUpper(h):h;return h+"";}}return C+"";}}

```

and in a more readable format:

```
using System;

class A
{
    static void Main()
    {
        var z = Console.ReadLine();
        var r = new Random();

        foreach (char C in z)
        {
            String o;

            if (r.Next(10) == 0)
            {
                int w = r.Next(3);
                o = w == 0 ? C + "" + C :
                    w == 1 ? "" :
                             f(C, r);
            }
            else
            {
                o = C + "";
            }

            Console.Write(o);
        }
    }

    static string f(char C, Random r)
    {
        string[] k = {
                            "00000000000",
                            "0qwertyuiop0",
                            "0asdfghjkl0",
                            "00zxcvbnm0",
                            "000000000"};
        char L = char.ToLower(C);
        char h = '0';

        for (int i = 1; i < 4; i++)
        {
            var d = k[i].IndexOf(L);

            if (d != -1)
            {
                while (h == '0')
                {
                    int n = r.Next(4);

                    h = n == 0 ? k[i][d - 1] :
                        n == 1 ? k[i][d + 1] :
                        n == 2 ? k[i - 1][d] :
                                 k[i + 1][d];
                }
                h = char.IsUpper(C) ? char.ToUpper(h) : h;
                return h + "";
            }
        }
        return C + "";
    }
}

```

# Answer
> 3 votes
## PHP, ~~326~~ ~~320~~ ~~318~~ 315 chars

```
$h=array(qs,vhn,vxf,sefx,wrd,drgc,fthv,gyjb,uko,hukn,jilm,ok,nk,bjm,ilp,o,aw,etf,awdz,rgy,yji,cgb,qse,zdc,thu,sx);$a=x.$argv[1];for(;$d=$a[++$b];)echo!rand(0,9)&&($c=ord($d)-65)?(!($g=rand(0,($e=($c>-1&&$c<26)or$c>31&&$c<58)+1))?$d.$d:($g<2?"":(($j=$i[rand(0,strlen($i=$h[$c-!$e*32]))])&&$e?strtoupper($j):$j))):$d;

```

And a more readable and commented version:

```
// $a   input
// $b   char iterator
// $c   current char ascii value
// $d   current char
// $e   is uppercase
// $g   rand() output
// $h   char displacement
// $i   current character in $h
// $j   temporary var for uppercasing

// the neighbouring characters of a-z, in alphabetical (and ASCII) order
$h=array(qs,vhn,vxf,sefx,wrd,
    drgc,fthv,gyjb,uko,hukn,
    jilm,ok,nk,bjm,ilp,
    o,aw,etf,awdz,rgy,
    yji,cgb,qse,zdc,thu,
    sx);
// input from argument
$a=x.$argv[1];

for(;$d=$a[++$b];)
    echo!rand(0,9)&&($c=ord($d)-65)? /* 10% chance, read char ASCII value - 65 into $c */
        (!($g=rand(0,($e=($c>-1&&$c<26)or$c>31&&$c<58)+1))?
          /* random number from 0 to 2 (if alphabetic) or 0 to 1 stored in $g */
            $d.$d: /* double char if $g = 0 */
            ($g<2?
                "": /* omit char if $g = 1*/
                (($j=$i[rand(0,strlen($i=$h[$c-!$e*32]))])&&$e?
                  /* $j = random neighbour of the current char */
                    strtoupper($j): /* uppercase $j */
                    $j)))
        :$d; /* keep char */

```

Still could be improved, I suppose.

-2, -3 thanks to Ismael Miguel

# Answer
> 2 votes
# Java (475 bytes)

This is my try in the verbose language that is Java. Getting random numbers is quite long in Java, and the mapping isn't really efficient. It can probably be improved.

```
import static java.lang.Math.*;public class T{public static void main(String[]a){String z="",v;for(char c:a[0].toCharArray()){double g=random()*60;if(g>=6)z+=c;else{boolean u='A'<=c&c<='Z',l='a'<=c&c<='z';if(g<(l|u?2:3))z+=""+c+c;else if((l|u)&g<4){v="qs,hnv,fvx,efsx,drw,cdgr,fhtv,kou,bgjy,hknu,ijlm,ko,kn,bjm,ilp,o,aw,eft,adwz,gry,ijy,bcg,eqs,cdz,htu,sx".split(",")[u?c-'A':c-'a'];c=v.charAt((int)(random()*v.length()));z+=u?(char)(c-'a'+'A'):c;}}}System.out.println(z);}}

```

Usage:

```
java T "This is some correct text. It is too correct. Please un-correctify it."

```

Uncompressed, accolades added:

```
import static java.lang.Math.*; // Need random()

public class T {
    public static void main(String[] a) {
        String z = "", v;
        for (char c : a[0].toCharArray()) {
            double g = random() * 60; // Compute random only once for two cases.
            if (g >= 6) {
                // 90% must be correct (accolades are stripped)
                // so we just copy the character.
                z += c;
            } else {
                // These tests come often.
                boolean u = 'A' <= c & c <= 'Z', l = 'a' <= c & c <= 'z';

                // reuse the random. g is [0,6[.
                if (g < (l | u ? 2 : 3)) {
                    // If c is an ascii letter (l|u) then g must be [0,2[ ; if not, then g must be [0,3[.
                    // If those conditions are met, we duplicate the character
                    z += "" + c + c;
                } else if ((l | u) & g < 4) {
                    // if c is letter and g [2,4[ then we perform the wrong key event.
                    // I could not compress it using the keyboard mapping shorter in Java than expanding it like it is now.
                    v = "qs,hnv,fvx,efsx,drw,cdgr,fhtv,kou,bgjy,hknu,ijlm,ko,kn,bjm,ilp,o,aw,eft,adwz,gry,ijy,bcg,eqs,cdz,htu,sx".split(",")[u ? c - 'A' : c - 'a'];
                    // get a random character from the string.
                    c = v.charAt((int) (random() * v.length()));

                    // Keep the case of the character.
                    z += u ? (char) (c - 'a' + 'A') : c;
                } else { // if c is not an ascii letter or if g is [4,6[
                    // Do nothing. This else is stripped.
                }
            }
        }
        System.out.println(z);
    }
}

```

# Answer
> 2 votes
# AutoHotkey 441 bytes

The input must be given as a command line parameter, the output is given as an error message.

Golfed version

```
loop, parse, 1
{
k:={1:"q",2:"w",3:"e",4:"r",5:"t",6:"y",7:"u",8:"i",9:"o",10:"p",21:"a",22:"s",23:"d",24:"f",25:"g",26:"h",27:"j",28:"k",29:"l",42:"z",43:"x",44:"c",45:"v",46:"b",47:"n",48:"m"},a:=A_LoopField,q:=r(z?3:2),z=
if r(10)!=10{
h.=a
continue
}
for x,y in k
z:=y=a?x:z
if q=1
h.=a a
if q=3
{
Loop{
t:=r(4),w:=z+(t=1?20:t=2?-20:t=3?1:-1)
} until k.HasKey(w)
h.=k[w]
}
}
throw % h
r(n){
Random,w,1,n
return w
}
```

Un-golfed and annotated version (difference is that this version has more white space and the variable assignments are on separate lines for readability.)

```
k:={1:"q",2:"w",3:"e",4:"r",5:"t",6:"y",7:"u",8:"i",9:"o",10:"p",21:"a",22:"s",23:"d",24:"f",25:"g",26:"h",27:"j",28:"k",29:"l",42:"z",43:"x",44:"c",45:"v",46:"b",47:"n",48:"m"}
loop, parse, 1
{
    a:=A_LoopField
    ;get a random number from 1-10 and check if it is 10
    ;  if it isn't skip the rest of this iteration
    if r(10)!=10
    {
        h.=a
        continue
    }

    ;check if the current character is in the k
    z=
    for x,y in k
        z:=y=a?x:z

    ;choose a random number to decide what typo to do
    q:=r(z?3:2)
    if q=1
        h.=a a ;duplicate the key
    if q=3
    {
        ;the keyboard array is set up so that by adding or subtracting
        ;  20 from the index you are moving up or down a row
        ;  and by adding or subtracting 1 you move right or left
        ;  then you just need to check if the adjusted index
        ;  is valid
        Loop
        {
            t:=r(4)
            w:=z+(t=1?20:t=2?-20:t=3?1:-1)
        } until if k.HasKey(w)
        h.=k[w]
    }
}
;display the string as an error message
throw % h
r(n)
{
    Random,w,1,n
    return w
}
```

---
Tags: code-golf
---


# Question
Title: String of alphanumeric characters to a sorted list of comma-separated ranges
Given a string of unsorted alphanumeric characters, *e.g.*

```
ABC321STPpJqZZr0

```

output a ", "-separated list of character ranges, sorted by ASCII value, ignoring case and removing duplicates (*i.e.* outputting only uppercase and numeric characters), *e.g.*

```
0-3, A-C, J, P-T, Z

```

### Rules

* The length of your program is your base score, as usual.
* You must initialize (hardcode) the above example within your program, but you may discount the length of that example from your program length, *e.g.* for `char* s="ABC321STPpJqZZr0";` you may discount 16 chars, the other 11 chars counting toward your program length.

### Bonus (+50 bounty)

* As this was a real problem encountered by my coworker today, needing to be written in Tcl 8.0.5 (an ancient version, lacking many of the latest Tcl built-ins), I'll award 50 points to whomever writes the shortest Tcl 8.0.5 solution, if there are at least 2 valid submissions in Tcl 8.0.5.

# Answer
> 5 votes
## Ruby, 87-16=71

**EDIT:** Had to add some characters so that two-character ranges are displayed correctly. Also using `?[` instead of `?Z` to fix a bug with ranges ending in Z.

```
$><<[*?0..?[].join.gsub(/[^ABC321STPpJqZZr0]/i,$/).gsub(/\B.+\B/,?-).scan(/.-.|./)*', '

```

You can see the Ideone run here.

# Answer
> 2 votes
# Julia, 131

```
julia> l=sort(unique(uppercase("ABC321STPpJqZZr0")))
julia> prod([!(c+1 in l)?"$c"*(c==l[end]?"":", "):!(c-1 in l)?"$c":(c+1 in l)&&!(c+2 in l)?"-":"" for c in l])

"0-3, A-C, J, P-T, Z"

```

Not supported by Ideone.com, and will probably be crushed anyway.

# Answer
> 2 votes
## GolfScript ~~57~~ ~~54~~ 52

```
 'ABC321STPpJqZZr0'
 {.95>32*-}%.|:x..{(}%&-x..{)}%&-+$2/{.|'-'*}%', '*

```

Try it here.

The code first capitalizes everything:

```
{.95>32*-}%

```

Then gets unique characters and saves it in a variable:

```
.|:x

```

Then, we get the characters whose direct predecessors are not in the string (so that they are the beginning part of a range):

```
..{)}%&-x

```

We similarly get the ends of ranges with `x..{)}%&-`.

Now actually form the ranges by concatenating the lists, sorting, and splitting into groups of 2:

```
+$2/

```

The rest is just formatting, using `*` as string join.

# Answer
> 2 votes
## C#, 221 bytes

```
class P{
    static void Main(){
        var s="ABC321STPpJqZZr0";
        var l=new int[257];
        foreach(int c in s.ToUpper())
            l[c]=1;
        var r="";
        for(int i=0;i<255;){
            if(l[i++]-l[i]<0)
                r+=", "+(char)i;
            else if(l[i+1]-l[i]<0)
                r+="-"+(char)i;
        }
        System.Console.Write(r.Substring(2));
    }
}

```

# Answer
> 2 votes
# C, 193

```
char*s="ABC321STPpJqZZr0";
int c[99];memset(c,0,396);while(*s){++c[toupper(*s++)];}for(int i=0,f=1,r=0;
i<=99;++i){if(!r&&c[i])r=i;if(r&&!c[i]){if(!f)printf(", ");putchar(r);
if(i-r>1)printf("-%c",i-1);r=f=0;}}

```

# Answer
> 2 votes
# Q, 94

```
{","sv(,/){{"-"sv(?) -1 1#\:x}'[cut[;a]0,1_(&)1<(-':)"i"$'a:asc upper[x]inter y]}[x]'[.Q`n`A]}

```

# Answer
> 1 votes
## Python 2.x, 304 - 16 = 288

This can surely be golfed further, all comments welcome!

```
e=[""]*11;f=[""]*27
for c in"ABC321STPpJqZZr0".lower():e["0123456789".find(c)]=f["abcdefghijklmnopqrstuvwxyz".find(c)]=c
e[-1]=f[-1]=""
def h(j):
 g=[];k=l=i=0
 for e in j:
  if e:
   if not l:k=i;l=1
  elif l:l=g.append((k,i-1))
  i+=1
 print", ".join([j[m],j[m]+"-"+j[n]][n-m>1]for m,n in g)
h(e);h(f)

```

# Answer
> 1 votes
# Rebol (218 - 16 = 202)

```
m: s: sort uppercase unique"ABC321STPpJqZZr0"i: :to-integer f: does[either 1 = length? x: copy/part m s[x][rejoin[x/1"-"last x]]]while[not tail? s: next s][if(1 + i pick back s 1)!=(i s/1)[prin join f", "m: s]]print f

```

Non-minified version:

```
m: s: sort uppercase unique "ABC321STPpJqZZr0"
i: :to-integer

f: does [
    either 1 = length? x: copy/part m s [x] [rejoin [x/1 "-" last x]]
]

while [not tail? s: next s][
    if (1 + i pick back s 1) != (i s/1) [
        prin join f ", "
        m: s
    ]
]

print f

```

# Answer
> 1 votes
# q \[116 chars\]

```
{.a:();{m:6h$x;.a:.a,$[m[1]=1+m[0];45;m[0],44,m 1];1_x}/[x:asc distinct upper x];p where differ 6h$p:-3_10h$x[0],.a}

```

## Usage

```
{.a:();{m:6h$x;.a:.a,$[m[1]=1+m[0];45;m[0],44,m 1];1_x}/[x:asc distinct upper x];p where differ 6h$p:-3_10h$x[0],.a}"ABC321STPpJqZZr0"

```
Output
```
"0-3,A-C,J,P-T,Z"

```

There is a scope of saving chars, i'll try some other method and post it.

# Answer
> 0 votes
## Tcl 8.0.5, 344 (360 bytes)

```
set a ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
set s string
set x [join [lsort [split [$s toupper ABC321STPpJqZZr0] ""]] ""]
regsub -all (.)\\1+ $x \\1 x
set i 36
while {[incr i -1]} {set j -1
while {$i+[incr j]<36} {set y [$s range $a $j [expr $i+$j]]
regsub $y $x [$s index $y 0]-[$s index $y end],\  x}}
while {[regsub -all {(\w)(\w)} $x {\1, \2} x]} {}
puts $x

```

## Tcl 8.0.5, 340 (356 bytes)

Tinkering with the `rename` command yielded some fun tricks! I've documented them in another thread.

```
rename rename &
& set =
& regsub R
& string S
& while W
= a ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
= x [lsort [split [S toupper ABC321STPpJqZZr0] ""]]
R -all {(.) \1+| } $x \\1 x
= i 36
W {[incr i -1]} {= j -1
W {$i+[incr j]<36} {= y [S range $a $j [expr $i+$j]]
R $y $x [S index $y 0]-[S index $y end],\  x}}
W {[R -all {(\w)(\w)} $x {\1, \2} x]} {}
puts $x

```

## Tcl 8.0.5, 332 (348 bytes) \[Unstable—depends on $PATH\]

```
info script ""
set tcl_interactive 1
set a ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
set x [lso [sp [st toupper ABC321STPpJqZZr0] ""]]
regs -all {(.) \1+| } $x \\1 x
set i 36
wh {[inc i -1]} {set j -1
wh {$i+[inc j]<36} {set y [st range $a $j [exp $i+$j]]
regs $y $x [st index $y 0]-[st index $y end],\  x}}
wh {[regs {(\w)(\w)} $x {\1, \2} x]} {}
pu $x

```

Credit to @JohannesKuhn for the interactive trick.

---
Tags: code-golf, string
---


title: Draw a Suanpan abacus

text:
# Question
Title: Draw a Suanpan abacus
Write the shortest program that takes a single integer as input and prints out a Suanpan abacus

Testcases

Input:

```
314159

```

Output:

```
|\======================================/|
||  (__)  (__)  (__)  (__)  (__)  (__)  ||
||  (__)  (__)  (__)  (__)   ||    ||   ||
||   ||    ||    ||    ||    ||    ||   ||
||   ||    ||    ||    ||   (__)  (__)  ||
|<======================================>|
||  (__)  (__)  (__)  (__)   ||   (__)  ||
||  (__)   ||   (__)   ||    ||   (__)  ||
||  (__)   ||   (__)   ||    ||   (__)  ||
||   ||    ||   (__)   ||    ||   (__)  ||
||   ||    ||    ||    ||    ||    ||   ||
||   ||    ||    ||    ||   (__)   ||   ||
||   ||   (__)   ||   (__)  (__)   ||   ||
||   ||   (__)   ||   (__)  (__)   ||   ||
||  (__)  (__)   ||   (__)  (__)   ||   ||
||  (__)  (__)  (__)  (__)  (__)  (__)  ||
|/======================================\|

```

Input:

```
6302715408

```

Output:

```
|\==============================================================/|
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  ||
||   ||   (__)  (__)  (__)   ||   (__)   ||   (__)  (__)   ||   ||
||   ||    ||    ||    ||    ||    ||    ||    ||    ||    ||   ||
||  (__)   ||    ||    ||   (__)   ||   (__)   ||    ||   (__)  ||
|<==============================================================>|
||  (__)  (__)   ||   (__)  (__)  (__)   ||   (__)   ||   (__)  ||
||   ||   (__)   ||   (__)  (__)   ||    ||   (__)   ||   (__)  ||
||   ||   (__)   ||    ||    ||    ||    ||   (__)   ||   (__)  ||
||   ||    ||    ||    ||    ||    ||    ||   (__)   ||    ||   ||
||   ||    ||    ||    ||    ||    ||    ||    ||    ||    ||   ||
||   ||    ||   (__)   ||    ||    ||   (__)   ||   (__)   ||   ||
||  (__)   ||   (__)   ||    ||   (__)  (__)   ||   (__)   ||   ||
||  (__)   ||   (__)  (__)  (__)  (__)  (__)   ||   (__)   ||   ||
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)   ||   (__)  (__)  ||
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  ||
|/==============================================================\|

```

# Answer
> 14 votes
## J, 126 124 121 119 116 115 113 105 116 115 112 characters

```
'|'s":(' 's[:,.(_6[\'  ||   (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1[(s=:[,.~,.)9!:7'\=/<=>/=\|='

```

Takes input from the keyboard. Example:

```
   '|'s":(' 's[:,.(_6[\'  ||   (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1[(s=:[,.~,.)9!:7'\=/<=>/=\|='
6302715408
|\==============================================================/|
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  ||
||   ||   (__)  (__)  (__)   ||   (__)   ||   (__)  (__)   ||   ||
||   ||    ||    ||    ||    ||    ||    ||    ||    ||    ||   ||
||  (__)   ||    ||    ||   (__)   ||   (__)   ||    ||   (__)  ||
|<==============================================================>|
||  (__)  (__)   ||   (__)  (__)  (__)   ||   (__)   ||   (__)  ||
||   ||   (__)   ||   (__)  (__)   ||    ||   (__)   ||   (__)  ||
||   ||   (__)   ||    ||    ||    ||    ||   (__)   ||   (__)  ||
||   ||    ||    ||    ||    ||    ||    ||   (__)   ||    ||   ||
||   ||    ||    ||    ||    ||    ||    ||    ||    ||    ||   ||
||   ||    ||   (__)   ||    ||    ||   (__)   ||   (__)   ||   ||
||  (__)   ||   (__)   ||    ||   (__)  (__)   ||   (__)   ||   ||
||  (__)   ||   (__)  (__)  (__)  (__)  (__)   ||   (__)   ||   ||
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)   ||   (__)  (__)  ||
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  ||
|/==============================================================\|

```

The main trick here is the abuse of J's boxing by redefining the characters it uses. It uses a global parameter \- `9!:7` \- to do this. There may be room for further golfing, but to be honest I was just glad to get something working that should compensate for my last attempt at this question.

Fits in a tweet with enough characters left to say 'Gaz made this' :-).

**Edit:** 3 characters of savings are due to borrowing the `2 6$' || (__)'` from Jesse Millikan's answer.

**Further edit:** Lost 11 characters adding extra spaces at either side that I hadn't noticed were not present.

**Explanation:**

The code is in three main sections:

**1) Setup**

```
[(s=:[,.~,.)9!:7'\=/<=>/=\|='

```

This is itself in two parts.
`9!:7'\=/<=>/=\|='` redefines the characters that J will use to display boxes. J's boxing normally looks like this:

```
   2 2$<"0[1 2 3 4
┌─┬─┐
│1│2│
├─┼─┤
│3│4│
└─┴─┘

```

but after redefining it looks like this:

```
   2 2$<"0[1 2 3 4
\===/
|1|2|
<===>
|3|4|
/===\

```

`(s=:[,.~,.)` defines a verb I'm going to be using a couple of times later. This turns out to be the best place to declare it. It takes a character on the left and an array of characters on the right and sandwiches the array between the character. For example:

```
   3 5$'abcdefghijklmno'
abcde
fghij
klmno

   '-' s 3 5$'abcdefghijklmno'
-abcde-
-fghij-
-klmno-

```

The final `[` just serves to separate the setup from the next part.

**2) Input and Representation**

```
,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1

```

`".,.1!:1[1` takes the input from the keyboard and separates it into individual digits:

```
   ".,.1!:1[1
314159
3 1 4 1 5 9

```

`((i.5)</5|])` creates a zeros and ones representation of the bottom part of the abacus:

```
   ((i.5)</5|]) 3 1 4 1 5 9
1 1 1 1 0 1
1 0 1 0 0 1
1 0 1 0 0 1
0 0 1 0 0 1
0 0 0 0 0 0

```

`|:@(1,.<&5)` creates a zeroes and ones representation of the top part of the abacus:

```
   |:@(1,.<&5) 3 1 4 1 5 9
1 1 1 1 1 1
1 1 1 1 0 0

```

These two parts are boxed together using `;`:

```
   (|:@(1,.<&5);((i.5)</5|])) 3 1 4 1 5 9
\=======================/
|1 1 1 1 1 1|1 1 1 1 0 1|
|1 1 1 1 0 0|1 0 1 0 0 1|
|           |1 0 1 0 0 1|
|           |0 0 1 0 0 1|
|           |0 0 0 0 0 0|
/=======================\

```

Then the boxes are placed one on top of the other to form the basis of the abacus, giving:

```
   ,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\===========/
|1 1 1 1 1 1|
|1 1 1 1 0 0|
<===========>
|1 1 1 1 0 1|
|1 0 1 0 0 1|
|1 0 1 0 0 1|
|0 0 1 0 0 1|
|0 0 0 0 0 0|
/===========\

```

**3) Output**

```
'|'s":(' 's[:,.(_6[\'  ||   (__)'){~(,-.))&.>

```

`&.>` means that what follows will operate on both boxes in turn.
`(,-.)` this is a hook which will negate the input and then add it to the end of the original:

```
   2 5$1 0 1 0 1
1 0 1 0 1
1 0 1 0 1

   (,-.) 2 5$1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
0 1 0 1 0
0 1 0 1 0

```

This is really part of the representation, but for golfing purposes it's better to have it in this section. Applied to the previous input:

```
   (,-.)&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\===========/
|1 1 1 1 1 1|
|1 1 1 1 0 0|
|0 0 0 0 0 0|
|0 0 0 0 1 1|
<===========>
|1 1 1 1 0 1|
|1 0 1 0 0 1|
|1 0 1 0 0 1|
|0 0 1 0 0 1|
|0 0 0 0 0 0|
|0 0 0 0 1 0|
|0 1 0 1 1 0|
|0 1 0 1 1 0|
|1 1 0 1 1 0|
|1 1 1 1 1 1|
/===========\

```

`[:,.(_6[\' || (__)'){~` The zeroes and ones are now used to select a string to represent a bead or the absence of one:

```
   ([:,.(_6[\'  ||   (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\====================================/
| (__)  (__)  (__)  (__)  (__)  (__) |
| (__)  (__)  (__)  (__)   ||    ||  |
|  ||    ||    ||    ||    ||    ||  |
|  ||    ||    ||    ||   (__)  (__) |
<====================================>
| (__)  (__)  (__)  (__)   ||   (__) |
| (__)   ||   (__)   ||    ||   (__) |
| (__)   ||   (__)   ||    ||   (__) |
|  ||    ||   (__)   ||    ||   (__) |
|  ||    ||    ||    ||    ||    ||  |
|  ||    ||    ||    ||   (__)   ||  |
|  ||   (__)   ||   (__)  (__)   ||  |
|  ||   (__)   ||   (__)  (__)   ||  |
| (__)  (__)   ||   (__)  (__)   ||  |
| (__)  (__)  (__)  (__)  (__)  (__) |
/====================================\

```

But now, as Howard pointed out to me, there is one space short on either side of the beads. So we use the predefined `s` verb to sandwich the contents of each box between two columns of spaces:

```
   (' 's[:,.(_6[\'  ||   (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
\======================================/
|  (__)  (__)  (__)  (__)  (__)  (__)  |
|  (__)  (__)  (__)  (__)   ||    ||   |
|   ||    ||    ||    ||    ||    ||   |
|   ||    ||    ||    ||   (__)  (__)  |
<======================================>
|  (__)  (__)  (__)  (__)   ||   (__)  |
|  (__)   ||   (__)   ||    ||   (__)  |
|  (__)   ||   (__)   ||    ||   (__)  |
|   ||    ||   (__)   ||    ||   (__)  |
|   ||    ||    ||    ||    ||    ||   |
|   ||    ||    ||    ||   (__)   ||   |
|   ||   (__)   ||   (__)  (__)   ||   |
|   ||   (__)   ||   (__)  (__)   ||   |
|  (__)  (__)   ||   (__)  (__)   ||   |
|  (__)  (__)  (__)  (__)  (__)  (__)  |
/======================================\

```

Having done that, all that's left is to convert this into a string using `":` so that we can sandwich it between two columns of `|`:

```
   '|'s":(' 's[:,.(_6[\'  ||   (__)'){~(,-.))&.>,.(|:@(1,.<&5);((i.5)</5|]))".,.1!:1[1
314159
|\======================================/|
||  (__)  (__)  (__)  (__)  (__)  (__)  ||
||  (__)  (__)  (__)  (__)   ||    ||   ||
||   ||    ||    ||    ||    ||    ||   ||
||   ||    ||    ||    ||   (__)  (__)  ||
|<======================================>|
||  (__)  (__)  (__)  (__)   ||   (__)  ||
||  (__)   ||   (__)   ||    ||   (__)  ||
||  (__)   ||   (__)   ||    ||   (__)  ||
||   ||    ||   (__)   ||    ||   (__)  ||
||   ||    ||    ||    ||    ||    ||   ||
||   ||    ||    ||    ||   (__)   ||   ||
||   ||   (__)   ||   (__)  (__)   ||   ||
||   ||   (__)   ||   (__)  (__)   ||   ||
||  (__)  (__)   ||   (__)  (__)   ||   ||
||  (__)  (__)  (__)  (__)  (__)  (__)  ||
|/======================================\|

```

# Answer
> 14 votes
## Ruby 1.9, 154 characters

```
puts'|\%s/|'%$r=?=*(2+6*gets.size),(0..14).map{|a|a==4?"|<#$r>|":"|| #{$_.gsub(/./){(5*a+n=$&.hex)/10!=1&&(a-n%5)/5!=1?' (__) ':'  ||  '}} ||"},"|/#$r\\|"

```

Assumes the input is *not* terminated by a newline.

Fun fact: Due to the way I'm turning the input digits into numbers (`$&.hex` is one byte shorter than `$&.to_i`), this abacus actually works with hex digits up to `e`:

```
$ echo -n "0123456789abcdef" | ruby suanpan.rb
|\==================================================================================================/|
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)   ||    ||    ||    ||    ||    ||   ||
||  (__)  (__)  (__)  (__)  (__)   ||    ||    ||    ||    ||    ||    ||    ||    ||    ||   (__)  ||
||   ||    ||    ||    ||    ||    ||    ||    ||    ||    ||   (__)  (__)  (__)  (__)  (__)  (__)  ||
||   ||    ||    ||    ||    ||   (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  ||
|<==================================================================================================>|
||   ||   (__)  (__)  (__)  (__)   ||   (__)  (__)  (__)  (__)   ||   (__)  (__)  (__)  (__)   ||   ||
||   ||    ||   (__)  (__)  (__)   ||    ||   (__)  (__)  (__)   ||    ||   (__)  (__)  (__)   ||   ||
||   ||    ||    ||   (__)  (__)   ||    ||    ||   (__)  (__)   ||    ||    ||   (__)  (__)   ||   ||
||   ||    ||    ||    ||   (__)   ||    ||    ||    ||   (__)   ||    ||    ||    ||   (__)   ||   ||
||   ||    ||    ||    ||    ||    ||    ||    ||    ||    ||    ||    ||    ||    ||    ||    ||   ||
||  (__)   ||    ||    ||    ||   (__)   ||    ||    ||    ||   (__)   ||    ||    ||    ||   (__)  ||
||  (__)  (__)   ||    ||    ||   (__)  (__)   ||    ||    ||   (__)  (__)   ||    ||    ||   (__)  ||
||  (__)  (__)  (__)   ||    ||   (__)  (__)  (__)   ||    ||   (__)  (__)  (__)   ||    ||   (__)  ||
||  (__)  (__)  (__)  (__)   ||   (__)  (__)  (__)  (__)   ||   (__)  (__)  (__)  (__)   ||   (__)  ||
||  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  (__)  ||
|/==================================================================================================\|

```

For `0xf`, a third bead magically appears in the upper half.

When allowing additional flags during script invocation, this can be shortened to 152 bytes (149 bytes code + 3 bytes additional invocation flags):

```
puts'|\%s/|'%$r=?=*(2+6*~/$/),(0..14).map{|a|a==4?"|<#$r>|":"|| #{$_.gsub(/./){(5*a+n=$&.hex)/10!=1&&(a-n%5)/5!=1?' (__) ':'  ||  '}} ||"},"|/#$r\\|"

```

Run with `ruby -n suanpan.rb`.

# Answer
> 12 votes
## Perl (151 chars)

(~~168~~ ~~163~~ ~~158~~ ~~157~~ ~~156~~ ~~154~~)

```
$i=<>;$c.=$_-4?"
||  $i||":"
|<$m>|",$m='==',$c=~s!\d!$m.='='x6;($_-$&%5)/5%2|(5*$_+$&)/10%7==1?' ||   ':'(__)  '!eg for 0..14;print"|\\$m/|$c
|/$m\\|"

```

### Explanation

```
# Read the number from STDIN.
$i = <>;

# for statement starts here...

    # Append to $c a line containing either the horizontal dividing bar (in row #4)
    # or the current abacus row with the digits in place of the pegs.
    # This relies on the fact that $m will have been computed after at least one iteration.
    $c .= $_-4 ? "\n||  $i||" : "\n|<$m>|",

    # Notice that $m is redundantly recomputed from scratch in each iteration.
    $m = '==',

    # Substitute the correct pegs for the digit characters.
    $c =~ s!\d!
        $m .= '=' x 6;

        # Weird expression for the abacus function.
        # I have to use “% 7” because otherwise the division is floating-point...
        # Notice that $_ is the row and $& is the digit.
        ($_ - $& % 5)/5 % 2 | (5*$_ + $&)/10 % 7 == 1
        ? ' ||   '
        : '(__)  '
    !eg
for 0..14;

# Could shorten further by using “say” if you don’t mind excluding the “-E” from the count...
print "|\\$m/|$c\n|/$m\\|"

```

### Edits

* **(154 → 151)** Changed three `\n`s to actual newline characters. Can’t believe I didn’t think of that earlier!

# Answer
> 8 votes
## Windows PowerShell, 191

```
$y='='*(2+6*($i=[char[]]"$input").Count)
filter f($v){"|| $((' (__)','  || ')[($i|%{iex $_%$v})])  ||"}"|\$y/|"
f 1
f 10-ge5
f 1+1
f 10-lt5
"|<$y>|"
1..5|%{f 5-lt$_}
1..5|%{f 5-ge$_}
"|/$y\|"

```

History:

* 2011-03-11 23:54 **(340)** Initial attempt.
* 2011-03-12 00:21 **(323)** Using string interpolation throughout the code.
* 2011-03-12 00:21 **(321)** Inlined `$l`.
* 2011-03-12 01:07 **(299)** Used a function for the more repetitive parts as well as a format string.
* 2011-03-12 01:19 **(284)** Changed the arguments to the function slightly. Hooray for command parsing mode.
* 2011-03-12 01:22 **(266)** More variables for recurring expressions.
* 2011-03-12 01:28 **(246)** Now every row is generated by the function.
* 2011-03-12 01:34 **(236)** Since I use the chars only in string interpolation I can safely ignore the `%` that makes numbers from the digits.
* 2011-03-12 01:34 **(234)** Slightly optimized the array index generation in the function.
* 2011-03-12 01:42 **(215)** I no longer need `$r` and `$b`. And `$a` is also obsolete. As is `$l`.
* 2011-03-12 01:46 **(207)** No need to set `$OFS` if I need it only once.
* 2011-03-12 01:49 **(202)** Inlined `$f`.
* 2011-03-12 01:57 **(200)** No need for the format string anymore. String interpolation works just fine.
* 2011-03-12 02:00 **(198)** Slightly optimized generating the individual rows (re-ordering the pipeline and array index).
* 2011-03-12 02:09 **(192)** No need for `-join` since we can actually use the additional space to good effect.

# Answer
> 5 votes
## Haskell, 243 characters

```
z x|x=" (__) ";z _="  ||  "
h[a,b]d f w='|':a:replicate(2+6*length d)'='++b:"|\n"++q z++q(z.not)
 where q b=w>>=(\v->"|| "++(d>>=b.(>v).f)++" ||\n")
s d=h"\\/"d(5-)[-9,0]++h"><"d(`mod`5)[0..4]++h"/\\"d id[]
main=interact$s.map(read.(:[])).init

```

Not particularly clever. I'm sure it can be shortened somehow...

---

* Edit: (246 -\> 243) took @FUZxxl's suggestion to use interact

# Answer
> 4 votes
## Delphi, 348

This version builds up a string to write just once; The digits are handled by a separate function that works via a `digit modulo m >= value` construct (negated if value \<0).

```
var d,s,o,p:string;c:Char;i:Int8;function g(m,v:Int8):string;begin p:='|| ';for c in d do p:=p+Copy('  ||   (__) ',1+6*Ord(((Ord(c)+2)mod m>=Abs(v))=(v>0)),6);g:=p+' ||'^J;end;begin ReadLn(d);s:=StringOfChar('=',2+6*Length(d));for i:=1to 5do o:=g(5,6-i)+o+g(5,-i);Write('|\'+s+'/|'^J+g(1,-1)+g(10,-5)+g(1,1)+g(10,5)+'|<'+s+'>|'^J+o+'|/'+s+'\|')end.

```

Delphi, 565

First attempt :

```
var _:array[0..6]of string=('  ||  ',' (  ) ','======','|\==/|','||  ||','|/==\|','|<==>|');m:array[0..186]of Byte;o:array[0..16]of string;i,j,c,f,l:Word;begin for i:=0to 9do begin f:=i*17;m[f+1]:=1;m[f+2]:=Ord(i<5);m[f+3]:=0;m[f+4]:=Ord(i>4);for j:=6to 10do m[f+j]:=Ord(i mod 5>j-6);for j:=11to 15do m[f+j]:=Ord(i mod 5<=j-11);m[f]:=2;m[5+f]:=2;m[16+f]:=2;end;f:=170;m[f]:=3;for i:=1to 15do m[f+i]:=4;m[f+5]:=6;m[f+16]:=5;repeat for i:=0to 16do Insert(_[m[f+i]],o[i],l);Read(PChar(@c)^);c:=c-48;f:=c*17;l:=Length(o[0])-2;until c>9;for i:=0to 16do WriteLn(o[i])end.

```

This uses 3 arrays; one for the 7 strings that could be discerned, one for the output lines and one to map the 7 strings to 11 columns (10 digits and 1 initial column).

# Answer
> 3 votes
### GolfScript, 139 characters

```
0+17'|':Q*:R'\<||'4Q**'/'+@{48-.5<)[1]*2,2*$+4<\5%[1]*2,5*$+10<+`{{1$=}%+2>'=='1/*5/('='+\+}+'     (|_|_ )'2//}/;;;;'/>||'4Q**'\\'+R]zip n*

```

Not much golfed yet, but it fits into a tweet (with only ASCII). Try it here.

# Answer
> 2 votes
# J, 225

Passes two tests given, should work up to at least several hundred digits.

```
c=:2 6$'   ||   (__)'
f=:(2{.[),('='#~2+6*#@]),2}.[
d=:'||',"1'  ||',~"1,"2&(c{~|:)
g=:('|\/|'&f,d&(1,.-.,.0,.])&(4&<),'|<>|'&f,d&(5($!.0"1)0,~"(1)1#~"0|~&5),|.&d&(5($!.0"1)1#~"0(5-5|])),'|/\|'&f)
4(1!:2)~LF,"1 g"."0}:(1!:1)3

```

First off: Yes, yes, gravedigging. Second: That's just embarassingly long. Oh well. I haven't decided yet whether to golf it further or curl up in fetal position and cry. (Or both!)

Here's a bit of explanation in lieu of a shorter program:

* c is 2x6 table of empty cell, bead cell for rendering.
* f renders an '=' row with the four outside characters as left argument.
* d renders an abacus row by translating 0/1 matrices into bead cells padded with ||
* g takes digits and vertically compiles character rows using f for 'formatting' rows and d for abacus rows.
* The last row gets input, splits into characters and converts those to numbers, feeds to g and then prints.

# Answer
> 2 votes
## C, ~~277~~ 274 characters

You know, it seems to me that we just don't have enough solutions here that really take advantage of the C preprocessor. Partly that's because those `#define`s actually take up a fair bit of space. But still, there's so much potential. I feel the need to address this deficiency.

```
#define L(x,z)for(printf("|"x),p=b;*p||puts(#z)<0;++p)printf(
#define F(x,y,z)L(#x,==z|)"======",y);
#define T(y)L("|  ",||)*p-47 y?"(__)  ":" ||   ");
i;char*p,b[99];main(j){gets(b);F(\\,0,/)T()T(<6)T(<1)T(>5)F(<,*p>52?*p-=5:0,>)
for(;++i<6;)T(>i)for(;++j<7;)T(<j)F(/,0,\\)}

```

That's better.

# Answer
> 2 votes
# Mathematica 281

```
w@n_:= Module[{t=Table,f,g},
 f@d_:=ReplacePart["O"~t~{7},{2-Quotient[d,5]-> "|",3+Mod[d,5]-> "|"}];
 g@k_:=IntegerDigits@n~PadLeft~10;
 Grid[Insert[Insert[(f/@g@n)T,"=="~t~{10},{{1},{3},{8}}]T,""~t~{10},{{1},{11}}]T]]

```

**Example**

```
w[6302715408]

```

# Answer
> 1 votes
## C, 548

```
#define p(a) printf(a);
#define F(x,m) for(x=0;x<m;x++)
#define I(x) {p("||")F(j,l)if(b[l*(i+x)+j]){p("  (__)")}else{p("   || ")}p("  ||\n")}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int a,char* c[]){int i,j,l,m,*b;l=strlen(c[1]);b=(int*)malloc(l*56);m=6*l;F(i,14*l)b[i]=0;
F(j,l){b[j]=1;if(c[1][j]<53){b[l+j]=1;}else{b[3*l+j]=1;c[1][j]-=5;}F(i,5){if(i<c[1][j]-'0'){
b[(i+5)*l+j]=1;}else{b[(i+9)*l+j]=1;}}}p("|\\=")F(i,m)p("=")p("=/|\n")F(i,4)I(0)p("|<=")F(i,m)
p("=")p("=>|\n")F(i,9)I(5)p("|/=")F(i,m)p("=")p("=\\|\n")}

```

First version, just a bit of golfing so far.

# Answer
> 1 votes
## Scala (489 characters)

```
def a(i:String){val b=" (__) ";val n="  ||  ";1 to 17 map{l=>;{print(l match{case 1=>"|\\=";case 6=>"|<=";case 17=>"|/=";case _=>"|| "});print(l match{case 1|6|17=>"======"*i.size;case 2|16=>b*i.size;case 4|11=>n*i.size;case 3=>i flatMap{d=>{if(d.asDigit<5)b else n}};case 5=>i flatMap{d=>{if(d.asDigit>4)b else n}};case _=>i flatMap{d=>{if(l<11)if(d.asDigit%5<l-6)n else b else if(d.asDigit%5>l-12)n else b}}});;print(l match{case 1=>"=/|";case 6=>"=>|";case 17=>"=\\|";case _=>" ||"})}}}

```

Pretty crappy attempt really.

# Answer
> 1 votes
# Sclipting, 77 chars

The bounty refers to *tweets*, and Twitter counts *characters* (not bytes). :)

```
꿓뤽꿓뤽①長復標독렽꿐②껷렊밃겠上❶가侔是丟돃렽꿐②꿧렊不돇렠글⓶①各❷❷걐剩減갰減갰分❸⓷걀大加增增감右與꺅뭟꺒갠⓵긇롼긂갠嗎⓶終丟돇렊終終돂묽꿐②뇇렊

```

I actually wrote this years ago (when this challenge was posted), but I never posted it because I invented Sclipting after this challenge was first posted. If you feel that this makes it ineligible, I understand.

## Explanation

```
꿓뤽꿓뤽①長復 | let x = "======" times the length of the input string
標 | mark
독렽꿐②껷렊 | "|\\==" + x + "/|\n"
밃겠上 | for row in [-4 .. 10]
    ❶가侔是 | if row == 0
        丟돃렽꿐②꿧렊 | "|<==" + x + ">|\n"
    不 | else
        돇렠글 | "||  "
        ⓶①各 | foreach char c in input
            | ((r-(c%5)-3)/3 & ((r + (c>4?3:2)) >> 1)) ? "(__) " : " ||   "
            ❷❷걐剩減갰減갰分❸⓷걀大加增增감右與꺅뭟꺒갠⓵긇롼긂갠嗎⓶
        終丟
        돇렊 | "||\n"
    終
終
돂묽꿐②뇇렊 | "|/==" + x + "\\|\n"

```

# Answer
> 1 votes
# Python, ~~309~~ ~~301~~ 288 chars

Compact version:

```
q=p,b="  ||  "," (__) "
t="|| %s ||\n"
a=lambda h:t%"".join(q[i]for i in h)
n=[int(d)for d in str(input())]
c=len(n)
e="="*(c*6+2)
h="|\\"+e+"/|"
print h+"\n"+t%(b*c)+a(d<5 for d in n)+t%(p*c)+a(d>4 for d in n)+"|<"+e+">|\n"+"".join(a((d%5>i%5)^(i>4)for d in n)for i in range(10))+h[::-1]

```

Clear version:

```
bead = " (__) "
pole = "  ||  "
template = "|| %s ||\n"
output = ""
def addline(hasbeads):
    global output
    output += template % "".join([bead if item else pole for item in hasbeads])

digits = [int(d) for d in str(input())]
count = len(digits)
equalsigns = "=" * (count * 6 + 2)
output = ""
header = "|\\" + equalsigns + "/|"
output += header + "\n"
output += template % (bead * count)
addline([d < 5 for d in digits])
output += template % (pole * count)
addline([d > 4 for d in digits])
output += "|<" + equalsigns + ">|\n"
for i in range(5):
    addline([d % 5 > i for d in digits])
for i in range(5):
    addline([d % 5 <= i for d in digits])
output += header[::-1]
print output

```

Note that for compactification, variables were renamed to a single letter, and list comprehensions were changed to generators that don't require extra brackets.

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


# Question
Title: Compute the greater common divisor & the smallest common multiple of N numbers
Your mission is to write 2 functions that accept a list of N integers (positive or negative).

N can be higher than 2.

The first one returns the greater common divisor of the N numbers

**Example**: \[10, 15, 20\] -\> 5

the second one returns the smallest common multiple of the N numbers

**Example**: \[10, 15, 20\] =\> 60

Smallest code (in number of characters) wins!

# Answer
> 1 votes
### Ruby 38 characters

```
g=->a{a.inject:gcd}
l=->a{a.inject:lcm}

```

demo:

```
ar = [10,15,20]
p g[ar] #=> 5
p l[ar] #=> 60

```

# Answer
> 0 votes
## J, 12 characters

```
g=.+./
l=.*./

```

A bit pointless giving them aliases like this really.

# Answer
> 0 votes
# Smalltalk (Smalltalk/X) (73 chars)

```
a:=#(10 15 20).
g:=a fold:[:i :e|i gcd:e].
l:=a fold:[:i :e|i lcm:e].

```

without fold: (Ansi Smalltalk), use (102 chars):

```
a := #(10 15 20).
g := a inject:a first into:[:i :e | i gcd:e].
l := a inject:a first into:[:i :e | i lcm:e].

```

---
Tags: code-golf
---


title: Plot gif of 3 dimensional heart in R

text:
# Question
Title: Plot gif of 3 dimensional heart in R
inspired by this blog: http://alstatr.blogspot.co.uk/2014/02/r-animating-2d-and-3d-plots.html I made a 2D gif of a heart with:

```
library(animation)
saveGIF({
for(i in 1:150){
dat<- data.frame(t=seq(0, 2*pi, by=0.1) )
xhrt <- function(t) 16*sin(t)^3
 yhrt <- function(t) 13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
dat$y=yhrt(dat$t)
dat$x=xhrt(dat$t)
with(plot(x,y, type="l", xlim = c(-100  , i ^ 2 / 10 )) )
}
}, interval = 0.1, ani.width = 550, ani.height = 550)

```

I wonder if anyone out there could show me how to do this in 3D!

# Answer
# Mathematica

This is done in Mathematica, but it may give you some ideas as to how to implement it in R.

```
hearts = Table[
  With[{v = RotationTransform[\[Theta], {0, 0, 1}][{3, 0, -.2}]},
   ContourPlot3D[(2 (4/3 x)^2 + 2 y^2 + z^2 - 1)^3 - (4/3 x)^2 z^3/
       10 - y^2 z^3, {x, -2, 2}, {y, -2, 2}, {z, -2, 2},
    MaxRecursion -> 6, Mesh -> None,
    BoxRatios -> {.3, 1, 1},
    SphericalRegion -> True,
    Contours -> {0}, Boxed -> False, PlotRange -> All, Axes -> False,
    ViewPoint :> v, ContourStyle -> Red,
    ImageSize -> 300]], {\[Theta], 0, 2 Pi, Pi/24}]

```
> 6 votes

---
Tags: graphical-output, r, animation
---