title: Shape Identifying Program

text:
# Question
Title: Shape Identifying Program
Your task is to build a program that identifies the shape of the input. The shapes to be identified can be any of the following:

### Square

To be identified as a square, the source must have lines of all equal length, and the same number of lines as characters per line (newline characters excluded). An optional trailing newline is acceptable.

```
$_='
$_="
$_"'
;say

```

### Rectangle

To be identified as a rectangle, the source must have lines of all equal length, but the number of lines does not match the number of characters per line (newline characters excluded). An optional trailing newline is acceptable. This can be either horizontal or vertical.

```
$_=
"no
t a
squ
are
";#

$_="but it
is still a
consistent
shape!";##

```

### Triangle

To be identified as a triangle, the source must either start with one character, and each subsequent line must have one additional character (including the last), or after the first line, each subsequent line should have one character fewer until the last, which has only one.

```
$
_=
"So
this
"."".
shape;

$_="or
even,
this
way
!!
"

```

### Mess

Anything that doesn't follow a consistent format as per the above, must be identified as a mess.

## Rules

* You may return any four consistent printable values to identify each shape.
* **Your source code must also adhere to one of the above shapes (no, not a mess).**
* A single trailing newline in your source is acceptable.
* You can assume input does not contain any blank lines (including trailing newlines), is not empty, and does not consist only of newlines.
* All shapes must have a height and width of \>= 2, otherwise this is defined as a mess.
* Standard loopholes are forbidden.
* The shortest solution in bytes, in each language, wins.

# Answer
> 9 votes
# Jelly, 35 bytes

```
L€ṀR,Ṛ$ċƲȧ3
L€,;¥LE€S+Ç
ỴµZL«L>1ȧÇ

```

Try it online!

`0` = Mess
`1` = Rectangle
`2` = Square
`3` = Triangle

# Answer
> 8 votes
# Java 10, ~~231~~ ~~221~~ ~~219~~ ~~217~~ ~~213~~ ~~211~~ ~~207~~ 203 bytes

```
s->{var a=s.split("\n");int r=a.length,l=a[0].length(),R=0,i=1,L,D;if(r>1){for(L=a[1].length(),D=L-l;
++i<r;R=L-a[i-1].length()!=D?1:R)L=a[i].length();R=R<1?D==0?r==l?1:2:D*D>1|l>1&L>1?0:3:0;}return R;};

```

Function is a rectangle itself.
`1` = Squares; `2` = Rectangles; `3` = Triangles; `0` = Mess.

-14 bytes thanks to *@OlivierGrégoire*
-4 bytes thanks to *@ceilingcat*

**Explanation:**

Try it online.

```
s->{                        // Method with String parameter and integer return-type
  var a=s.split("\n");      //  Input split by new-lines
  int r=a.length,           //  Amount of lines
      l=a[0].length(),      //  Length of the first line
      R=0,                  //  Result-integer, initially 0
      i=1,                  //  Index integer, starting at 1
      L,D;                  //  Temp integers
  if(r>1){                  //  If there are at least two lines:
    for(L=a[1].length(),    //   Set `L` to the length of the second line
        D=L-l;              //   And set `D` to the difference between the first two lines
        ++i<r;              //   Loop over the array
        ;                   //     After every iteration:
         R=L-a[i-1].length()//     If the difference between this and the previous line
          !=D?              //     is not equal to the difference of the first two lines:
           1                //      Set `R` to 1
          :                 //     Else:
           R)               //      Leave `R` the same
      L=a[i].length();      //    Set `L` to the length of the current line
  R=R<1?                    //   If `R` is still 0:
     D==0?                  //    And if `D` is also 0:
      r==l?                 //     And the amount of lines and length of each line is equal:
       1                    //      It's a square, so set `R` to 1
      :                     //     Else:
       2                    //      It's a rectangle, so set `R` to 2
     :D*D>1&                //    Else-if `D` is NOT 1 nor -1,
      l>1&L>1?              //    and neither `l` nor `L` is 1:
       0                    //     Set `R` to 0, since it's a mess
      :                     //    Else (`D` is 1 or -1, and `l` or `L` is 1):
       3                    //     It's a triangle, so set `R` to 3
    :0;}                    //   In all other cases it's a mess, so set `R` to 0
  return R;}                //  Return the result `R`
;                           // No-op to make the method a rectangle

```

# Answer
> 8 votes
# Brachylog, 45 bytes

```
lᵐ{≥₁|≤₁}o{l>1&t>1&}↰₃
lg,?=∧1w|=∧2w|t⟦₁≡?∧3w

```

Try it online!

Code is a rectangle (despite the way it renders on my screen). Outputs: 1 for square, 2 for rectangle, 3 for triangle, and nothing for mess

---

### Explanation:

```
lᵐ{≥₁|≤₁}o{l>1&t>1&}↰₃
lg,?=∧1w|=∧2w|t⟦₁≡?∧3w

lᵐ                        Get the length of each string
  {     }                 Verify
   ≥₁                     The list is non-increasing
     |                    or...
      ≤₁                  The list is non-decreasing
         o                Sort it to be non-decreasing
          {        }      Verify
           l>1            The number of lines is greater than 1
              &           and...
               t>1&       The longest line is longer than 1 character
                    ↰₃    Call the following

lg,?                      Join the number of lines with the line lengths
    =∧1w                  If they are all equal, print 1 (Square)
         |=∧2w            Or if just the line lengths are equal, print 2 (Rectangle)
              |t⟦₁         Or if the range [1, 2, ... <longest line length>]
                  ≡?       Is the list of lengths
                    ∧3w    Print 3 (triangle)
                           Otherwise print nothing (mess)

```

# Answer
> 7 votes
# Jelly, ~~32~~ 27 bytes

```
,U⁼€JẸ,E;SÆ²$
ZL«L’aL€Ç$æAƝ

```

Try it online!

Now taking input at a list of lines and switched `>1×` with `’a` and using `SÆ²` after `L€` instead of `FLÆ²Ɗ`. These allowed me to condense into two lines and I saved 5 bytes in total. The following values are the same as before.

`[0.0, 0.0]`=Mess
`[0.0, 1.5707963267948966]`=Rectangle
`[0.0, 0.7853981633974483]`=Square
`[1.5707963267948966, 0.0]`=Triangle

---

`ZL«L` gets the minimum of height and width and  subtracts 1 from it. `Ç` calls the second link and at the end if the input is a single line the result of `Ç` gets logical ANDed with the previous number if there is only a single line the output will be `[0.0, 0.0]`.

In the second link: `,U` yields a list of line lengths paired with it's reverse. `J` is `range(number of lines)` and `⁼€` checks whether each of them are equal to the result of `J`.  (Any) yields 1 if the input is a triangle.

`E` checks if all line lengths are equal (rectangle/square).

`SÆ²` with a `$` to group them into a single monad checks whether the total number of characters is a square number.

So at the end of the second link we have `[[a,b],c]` where each number is `0` or `1` indicating whether the input is a triangle, rectangular, and has square number of characters respectively.

However a square number of elements doesn't imply the input is a square since an messy input like

```
a3.
4

```

has a square number of elements but isn't a square.

This is where `æA` (arctan2) comes in. `0æA0` == `0æA1` == `0`. In other words, if the input has square number of elements but is not a rectangle, then it is not a square. There are certainly more clear ways to do this but what does that matter when we have bytes to think about and we are allowed consistent arbitrary output.

Note I was previously using `æA/` instead of `æAƝ` (and a `,` instead of a `;` in the second link) but the former method distinguishes between triangles that have square number of elements and those that don't but they should obviously be counted as the same thing.

# Answer
> 6 votes
# Python 2, ~~129~~ ~~114~~ ~~109~~ ~~107~~ 113 bytes

```
l=map(len,input().split('\n'));m=len(
l);r=range(1,m+1);print[[1],0,r,r[::-
1],[m]*m,0,[max(l)]*m,l].index(l)%7/2

```

Try it online!

---

Prints

* `0` = `Mess`
* `1` = `Triangle`
* `2` = `Square`
* `3` = `Rectangle`

# Answer
> 4 votes
# Java 10, ~~274~~ ~~323~~ ~~298~~ 229 bytes

First triangle submission.

```
s
->
{
var
a=s.
split
("\n");
int i,l=
a.length,
c,f=a[0].
length(),r=
l<2||f<2&a[1
].length()<2?
0:f==l?7:5;var
b=f==1;for(i=1;
i<l;){c=a[i++].
length();r&=c!=f?
4:7;r&=(b&c!=f+1)|
(!b&c!=f-1)?3:7;f=c
;}return r;}

```

`0` Mess

`1` Rectangle

`3` Square

`4` Triangle

Try it online here.

Edited multiple times to golf it a bit more.

Of course I could save a lot of bytes by turning this into a rectangle as well (~~281~~ ~~267~~ ~~259~~ 200 bytes, see here).

The result of the identification is manipulated using bitwise AND, yielding a bitmask as follows:

```
1        1      1
triangle square rectangle

```

Ungolfed version:

```
s -> {
    var lines = s.split("\n"); // split input into individual lines
    int i, // counter for the for loop
    numLines = lines.length, // number of lines
    current, // length of the current line
    previous = lines[0].length(), // length of the previous line
    result = numLines < 2 // result of the identification process; if there are less than two lines
    || previous < 2 & lines[1].length() < 2 // or the first two lines are both shorter than 2
    ? 0 : previous == numLines ? 7 : 5; // it's a mess, otherwise it might be a square if the length of the first line matches the number of lines
    var ascending = previous == 1; // determines whether a triangle is in ascending or descending order
    for(i = 1; i < numLines; ) { // iterate over all lines
         current = lines[i++].length(); // store the current line's length
        result &= current != previous ? 4 : 7; // check if it's not a rectangle or a square
        result &= (ascending & current != previous+1)|(!ascending & current != previous-1) ? 3 : 7; // if the current line is not one longer (ascending) or shorter (descending) than the previous line, it's not a triangle
        previous = current; // move to the next line
    }
    return result; // return the result
}

```

# Answer
> 4 votes
# Jelly, 15 bytes

```
Jm0w,ET
ỴẈµLe|Ç

```

Try it online!

Returns `[1]` for triangles, `[2]` for rectangles, `[3]` for squares and `[]` for messes

## How it works

```
ỴẈµLe|Ç - Main link. Takes a string S on the left
Ỵ       - Split S into a list of lines
 Ẉ      - Take the length of each line
  µ     - Use this list of lengths W as the left and right argument:
   L    - Length of W
    e   - This length is in W?

          This returns 1 for triangles and squares and for messes with
          one (or more) lines of a length of the number of lines in the mess

      Ç - Call the helper link on W
     |  - Logical OR

Jm0w,ET - Helper link. Takes a list of lengths W on the left
J       - Replace W with it's indices ([1, 2, ..., len(W)])
 m0     - Reflect; [1, 2, ..., len(W), len(W), ..., 2, 1]
   w    - Index of W as a sublist in this array, or 0
          This returns a non-zero number for triangles
     E  - Are all elements of W equal?
          This returns 1 for squares and rectangles
    ,   - Pair
      T - Return the indices of non-zero elements

          This yields:
            - [1] for triangles
            - [2] for rectangles/squares
            - []  for messes

```

Taking the logical or between these results yields:

* `1 | [1] = [1 | 1] = [1]` for triangles
* `0 | [2] = [0 | 2] = [2]` for rectangles
* `1 | [2] = [1 | 2] = [3]` for squares
* `1 | [] = []` or `0 | [] = []` for messes

# Answer
> 3 votes
# PHP, ~~195~~ 205 bytes

```
<?$a=$argv[1];$r=substr($a,-2,1)=="\n"?strrev($a):$a;foreach(explode("\n",$r)as$l){$s=strlen($l);$x[$s
]=++$i;$m=$i==$s?T:M;}$z=count($x);echo$i*$z>2?$z==1&&key($x)==$i?S:($z==1&&$i>2?R:($i==$z?$m:M)):M;?>

```

The upside down triangle adds an expensive 56 bytes to this!

Outputs are S,R,T,M

Saved a few bytes thanks to Dom Hastings.

Try it online!

Fixed a few issues now... Test runs produce this.

```
$_="
$_="
$_""
;say

RESULT:S
=============
$_=
"no
t a
squ
are
";#

RESULT:R
=============
$
_=
"So
this
"."".
shape;

RESULT:T
=============
$_="or
even,
this
way
!!
"

RESULT:T
=============
as
smiley
asd
A

RESULT:M
=============
X

RESULT:M
=============
XX

RESULT:M
=============
cccc
a
aa
cccc

RESULT:M
=============

```

# Answer
> 3 votes
# Perl 5 `-p`, 83 bytes

* Mess: nothing
* Square: 0
* Triangle: 1
* Rectangle: 2

```
($z)=grep++$$_{"@+"-$_*~-$.}==$.,0,/$/,-1
}{$.<2or$_=$$z{$z>0||$.}?$z%2:@F>1&&2x!$z

```

Try it online!

# Answer
> 3 votes
## Javascript 125 bytes

```
_=>(g=(l=_.split('\n').map(a=>a.length)).
length)<3?0:(r=l.reduce((a,b)=>a==b?a:0))
?r==g?2:1:l.reduce((a,b)=>++a==b?a:0)?3:0

0 = Mess
1 = Rectangle
2 = Square
3 = Triangle

```

```
fa=_=>(g=(l=_.split('\n').map(a=>a.length)).length)<3?0:(r=l.reduce((a,b)=>a==b?a:0))?r==g?2:1:l.reduce((a,b)=>++a==b?a:0)?3:0

var square = `asd
asd
asd`

var rectangle = `asd
asd
asd
asd
asd
asd`

var triangle = `asd
asdf
asdfg
asdfgh`

var mess = `asd
dasdasd
sd
dasasd`

console.log(fa(square), fa(rectangle), fa(triangle), fa(mess))
```

# Answer
> 3 votes
# 05AB1E, ~~35~~ ~~29~~ 27 bytes

Saved 8 bytes thanks to *Magic Octopus Urn*

```
DgV€g©ZU¥ÄP®Y
QP®ËJCXY‚1›P*

```

Try it online!

`0` = Mess
`4` = Triangle
`1` = Rectangle
`3` = Square

# Answer
> 3 votes
# Stax, 39 bytes

```
L{%m~;:-c:u{hJchC;
|mb1=-C;%a\sI^^P}M0

```

Run and debug online!

Shortest ASCII-only answer so far.

> 0 - Mess
> 1 - Rectangle
> 2 - Square
> 3 - Triangle

## Explanation

The solution makes use of the following fact: If something is explicitly printed in the execution of the program, no implicit output is generated. Otherwise, the top of stack at the end of the execution is implicitly output.

```
L{%m~;:-c:u{hJchC;|mb1=-C;%a\sI^^P}M0
L                                        Collect all lines in an array
 {%m                                     Convert each line to its length
    ~;                                   Make a copy of the length array, put it on the input stack for later use
      :-                                 Difference between consecutive elements.
                                         If the original array has only one line, this will be an empty array
        c:u                              Are all elements in the array the same?
                                         Empty array returns false
           {                      }M0    If last test result is true, execute block
                                         If the block is not executed, or is cancelled in the middle, implicitly output 0
            hJ                           The first element of the difference array squared (*)
              chC                        Cancel if it is not 0 or 1
                 ;|m1=                   Shortest line length (**) is 1
                      -                  Test whether this is the same as (*)
                                         Includes two cases:
                                             a. (*) is 1, and (**) is 1, in which case it is a triangle
                                             b. (*) is 0, and (**) is not 1, in which case it is a square or a rectangle
                        C                Cancel if last test fails
                         ;%              Number of lines
                           a\            [Nr. of lines, (*)]
                             I           Get the 0-based index of (**) in the array
                                         0-> Square, 1->Triangle -1(not found) -> Rectangle
                              ^^P        Add 2 and print

```

# Answer
> 3 votes
# Perl 6, 81 bytes

```
{.lines>>.chars.&{($_==.[0],3)[2*(2>.max
)+($_ Z- .skip).&{.[0].abs+.Set*2+^2}]}}

```

Try it online!

Returns `True` for square, `False` for rectangle, `3` for triangle, `Nil` for mess.

# Answer
> 3 votes
# Haskell, ~~113~~ ~~107~~ ~~103~~ 101 bytes

```
((#)=<<k).map k.lines;k=length;1#x=0;l#x|x==[1..l]
  ||x==[l,l-1..1]=3;l#x=k[1|z<-[l,x!!0],all(==z)x]

```

Try it online!

Returns 0, 1, 2 and 3 for mess, rectangle, square and triangle, respectively.

*Edit: -2 bytes thanks to Lynn!*

# Answer
> 2 votes
# , 101 bytes

```
"if"(var(z<-nchar(y<-scan(,"",,,"
","")))==0,"if"(length(y)==z,1,2
),"if"(all(abs(diff(z))==1),3,4))

```

> 1=Square
> 2=Rectangle
> 3=Triangle
> 4=Random

Code cannot deal with 'NEGATIVE ACKNOWLEDGE' (U+0015) or the square in the code above. This byte can be switched to something different if the input requires contains this byte.

Try it online!

# Answer
> 2 votes
# Snails, 29 bytes

```
ada7A
.2,lr
?!(t.
rw~)z
.+~o~

```

Output key:

* **0** \- Mess
* **3** \- Triangle
* **6** \- Rectangle
* **7** \- Square

It would be 23 bytes without source layout:

```
zA
.2,dun!(t.rf~)z.+~o~

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 119 bytes

```
(x=StringLength/@#~StringSplit~"\n")/.{{1}->3,s~(t=Table)~{
s=Tr[1^x]}:>0,x[[1]]~t~s:>1,(r=Range@s)|Reverse@r:>2,_->3}&

```

Using `Replace` `/.` and pattern matching on the character count by line. `Replace` will kick out the first RHS of a rule that is matched, so the ordering is to test for the 1 character input, then squares, rectangles, triangles, and a fall-through for messes.

square=0,rectangle=1,triangle=2,mess=3

Try it online!

# Answer
> 1 votes
# Ruby, ~~115~~ 111 bytes

```
->s{m=s.split(?\n).map &:size;r=*1..s=m.size;s<2?4:(m|[
]).size<2?m[0]<2?4:s==m[0]?1:2:r==m.reverse||r==m ?3:4}

```

Try it online!

Anonymous lambda. Outputs:

1. Square
2. Rectangle
3. Triangle
4. Mess

# Answer
> 1 votes
# Red, 209 bytes

```
func[s][c: copy[]foreach a split s"^/"[append c length? a]d: unique c
r: 0 if 1 < l: length? c[if 1 = length? d[r: 2 if(do d)= l[r: 1]]n: 0
v: copy[]loop l[append v n: n + 1]if(v = c)or(v = reverse c)[r: 3]]r]

```

Try it online!

`0` Mess

`1` Square

`2` Rectangle

`3` Triangle

# Answer
> 1 votes
# AWK, 119 bytes

```
{p=l;l=L[NR]=length($0)
D=d}{d=p-l;x=x?x:NR>2?\
d!=D:0}END{print x==1?\
3:d*d==1?(L[NR]+L[1]==\
NR+1)?2:3:p!=NR}#######

```

Try it online!

Output:

`0` = Square
`1` = Rectangle
`2` = Triangle
`3` = Mess

# Answer
> 1 votes
# C (gcc), ~~125~~ 123 bytes

Thanks to ceilingcat for -2 bytes.

```
f(L,n)int**L;{int i,l,c,F=strlen(*L),s=-F;for(l=i=0;i<n;l=c)c
=strlen(L[i++]),s+=c-l;s=n>1?s||F<2?~abs(s)+n?0:3:n^F?2:1:0;}

```

Try it online!

---
Tags: code-golf, string, source-layout
---


title: Find the nth base-b digit of (b^k-1)^-2

text:
# Question
Title: Find the nth base-b digit of (b^k-1)^-2
## Task

Your task is simple. Write a program or function which takes three positive integer arguments \\$n\\$, \\$k\\$, and \\$b\\$ in any order, such that \\$2 ≤ b ≤ 36\\$, and returns or outputs the nth (1-indexed) base-\\$b\\$ digit after the decimal point of the rational number (\\$b^k-1)^{-2}\\$.

The output must be correct for \\$n\\$ and \\$b^k\\$ up to the largest integer value your language of choice can natively represent. This will most likely mean that you cannot depend on built-in floating point representations to exactly represent the base-\\$b\\$ expansion of the number.

Fortunately, this class of numbers has a rather nice property \[Spoiler Alert!\]: https://www.youtube.com/watch?v=daro6K6mym8

## Rules

* Base conversion built-ins are permitted.
* Built-in spigot functions capable of indexing digits of exactly represented real numbers are forbidden.
* The digits for base \\$b\\$ are the first \\$b\\$ symbols in the string `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ` or alternately `0123456789abcdefghijklmnopqrstuvwxyz`. Your choice.

## Winning

This is code golf. Shortest solution in bytes wins.

## Test Cases

(You need not be able to correctly handle all of these if \\$n\\$ or \\$b^k\\$ overflows your integer datatype.)

```
Input (n,k,b)               Output
9846658,3,31                5
789234652,4,10              4
4294967295,17,2             1
4294967254,72,15            B
137894695266,3,30           H
184467440737095595,6,26     L
184467440737095514,999,36   T

```

# Answer
# APL (Dyalog Extended), 31 bytes

```
(⎕D,⎕A)⊃⍨⊃⎕⌽¯1⌽,⍉⎕(⊣⊤⍳⍤*~*-2⍨)⎕

```

Try it online!

A full program that takes numbers from stdin in the order of `k`, `b`, `n`. `n` being 1-based cost me 3 bytes `¯1⌽`.

### How it works

The main mathematical trick is well explained in Neil's answer. The gist is that the repeating part of the base-`b` representation consists of length-`k` base-`b` digits of `0..b^k-1`, except `b^k-2`.

This answer implements it very literally: list all repeating base-`b` digits, cyclically fetch `n`th digit from it, and convert it to `0-9A-Z`. Cyclic indexing uses ngn's trick.

```
⎕(...)⎕     ⍝ Take k (the right) and b (the left) from stdin
  ⍳⍤*~*-2⍨  ⍝ Create a list of 0..b^k-1, and remove the number b^k-2
  ⊣⊤        ⍝ Convert these numbers into base-b digits into columns
,⍉          ⍝ Transpose and flatten to get the repeating base-b digits
⊃⎕⌽¯1⌽      ⍝ Take n from stdin and get the nth digit cyclically
(⎕D,⎕A)⊃⍨   ⍝ Convert the number to the corresponding char in 0-9A-Z

```
> 7 votes

# Answer
## ES7, 59 bytes

```
(n,k,b)=>(1+!(n/k%(d=b**k-1))+d+--n/k%d).toString(b)[n%k+1]

```

ES6-compatible version for people who don't have Firefox Nightly:

```
(n,k,b)=>(1+!(n/k%(d=Math.pow(b,k)-1))+d+--n/k%d).toString(b)[n%k+1]

```

Explanation (possibly the same as in the video; I haven't watched it):

I start with the simple case of (b-1)-1 in b-ary notation. Obviously b-1 does not divide 1, so we add an extra zero after the b-ary point. 1.0 divided by b-1 is 0.1 remainder 0.1. This continues in the obvious manner to give (b-1)-1 as being 0.111... in b-ary notation.

(bk-1)-1 is not much harder; the only difference is that we have to add k extra zeros before we can divide. We then have 1.00...00 \[k zeros\] divided by bk-1 is 0.00...01 remainder 0.00...01 \[k-1 zeros\]. This obviously continues to give (bk-1)-1 as being 0.00...0100...0100... \[k-1 zeros each time\] in b-ary notation.

To form (bk-1)-2 it merely suffices to divide (bk-1)-1 itself by bk-1. Again we consider k digits each time. The first k digits are just 00..01 which obviously don't divide by bk-1, so the first k digits of the result are 00..00. The next k digits are of course also 00..01 so we divide bk+1 by bk-1 giving 1 remainder 2. Considering the next k digits we divide 2bk+1 by bk-1 giving 2 remainder 3. At each step we have mbk+1 = m(bk-1)+m+1. This continues until we reach (bk-3)bk+1 which divides by bk-1 giving bk-3 remainder bk-2. At this point (bk-2)bk+1 is equal to (bk-1-1)(bk-1+1)+1 which can be written as (bk-1)2-12+1 or simply (bk-1)2, which therefore divides exactly by bk-1.

We therefore have managed to divide the first k(bk-1) digits of (bk-1)-1 by bk-1 exactly, and the sequence therefore repeats at this point. In effect, (bk-1)-2 is formed by concatenating all the (zero-padded) k-digit numbers from 0 to bk-3, plus bk-1 itself, and then repeating.

My solution divides n-1 by k and then reduces modulo bk-1 to find the appropriate k-digit number. If n is an exact multiple of k(bk-1) it adds 1 to the number because the last k-digit number is bk-1 itself. Having found the number it then adds bk, which has the effect of forcing the base conversion to generate any required leading zeros. The appropriate digit of the converted number is then returned.
> 4 votes

# Answer
## Python 2, 110 bytes

```
n,k,b=input()
n=~-n%(k*b**k-k)
print"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[(n/k+(n/k+2==b**k))/b**(k-1-n%k)%b]

```

Maybe answering it myself (poorly) will bring this EASY question some more attention. Usually easy questions get more answers...
> 0 votes

---
Tags: code-golf, math, number, base-conversion
---


title: Draw the Heart Shape

text:
# Question
Title: Draw the Heart Shape
# Challenge

Draw a Heart shape

...as ASCII art!

Your art doesn't have to look exactly like mine, but it has to look like a Heart Shape.

The inside of of the heart has to contain the words "Love" at least 20 times

# Rules

* The program must write the art to the console.
* Shortest code (in bytes, any language) wins.

The winner will be chosen on February 14th on Valentines Day

# Answer
> 52 votes
## JavaScript \[160 bytes\]

The following code seems to be **160 bytes** unformatted.

```
   ('l2v2l6v2'+  'e1l1v3l2'+
 'v3e1v7e1v7e1v7e1l2v6e1l4v5'+
'e1l6v4e1l8v3e1l7l3v2e1l9l3v1')
 .replace(/[lve]\d/g,function
   (c){return Array(-~c[1]).
      join({l:' ',v:'Love'
         ,e:'\n'}[c[0
             ]])})

```

Simply run this in the browser console (e.g. in Firebug or Chrome Dev Tools).

# Answer
> 27 votes
## GolfScript: ~~62~~ ~~57~~ 54 characters

```
4 1.5\.5,+{.5\-\2*\0.}/]4/{[32'LOVE']2*]zip{(*}%''+}%~

```

Output:

```
    LOVE    LOVE
  LOVELOVELOVELOVE
LOVELOVELOVELOVELOVE
  LOVELOVELOVELOVE
    LOVELOVELOVE
      LOVELOVE
        LOVE

```

Or, for some added love, and the obligatory abuse of whitespace insignificance (for 84 characters):

```
    5 1       .8\
  .)...5   ,{.5\-\3
 *\0.}/]4 /{[32[9829
  :x.'LOVE'\]''+]2
    *[@;]zip{(*}%
     ''+}%~' '15
        *x[]+
          +

```

Output:

```
     ♥LOVE♥        ♥LOVE♥
  ♥LOVE♥♥LOVE♥  ♥LOVE♥♥LOVE♥
♥LOVE♥♥LOVE♥♥LOVE♥♥LOVE♥♥LOVE♥
   ♥LOVE♥♥LOVE♥♥LOVE♥♥LOVE♥
      ♥LOVE♥♥LOVE♥♥LOVE♥
         ♥LOVE♥♥LOVE♥
            ♥LOVE♥
               ♥

```

# Answer
> 16 votes
# C - 183 bytes

Not a winner, but a whole lotta love. Can you figure out how it works?

```
#include <stdio.h>
#define C(a) ((a)*(a)*(a))
int main(){int x,y;for(y=9;y>-6;y--){for(x=-8;x<9;x++)putchar(C(x*x+y*y-25)<25*x*x*y*y*y?"LOVE"[(x+10)%4]:'-');putchar('\n');}return 0;}

```

Output:

```
-----------------
--LOVE-----OVEL--
-ELOVEL---LOVELO-
-ELOVELO-ELOVELO-
-ELOVELO-ELOVELO-
-ELOVELOVELOVELO-
--LOVELOVELOVEL--
--LOVELOVELOVEL--
---OVELOVELOVE---
----VELOVELOV----
----VELOVELOV----
------LOVEL------
-------OVE-------
--------V--------
-----------------

```

# Answer
> 15 votes
## Scala - 273 Characters

Well, I certainly don't expect to win for brevity, but I wanted to see if I could do it in Scala. A smarter golfer could probably shave several bytes off, but here's what I got:

```
type D=Double;def w(x:D,y:D,a:D)={val(i,j)=(x-a,y-8);Math.sqrt(i*i+j*j)< 8};val l:Stream[Char]="love".toStream#:::l;val c=l.toIterator;def p(b:Boolean)=print(if(b)c.next else' ');for(y<-0 to 24){for(x<-0 to 32){if(y>7)p((16-x).abs< 24-y)else p(w(x,y,8)|w(x,y,24))};println}

```

Or, if you prefer (still valid code!)

```
  type D=      Double
def w(x:D,    y:D,a:D)=
{val(i,j)=   (x-a,y -8);
Math.sqrt(i* i+j*j)< 8};
val l : Stream [Char] =
"love".toStream#:::l;val
 c= l .toIterator;def p
  (b:Boolean) =print(if
   (b)c.next else' ');
    for (y <-0 to 24)
     { for (x<- 0 to
      32){if(y >7)
        p((16-x).
          abs <
          24-y)
         else
        p(w
       (x,
       y,
      8
      )
      |
      w(
       x,
         y,
           24)
              )}
                 println}

```

Prints out two semicircles and a triangle to the screen, making a pretty decent facsimile of a heart.

Needs to be run with the scala interpreter (compiling would require adding some extra cruft for `object Main { def main(args: Array[String]) = { ... } }` and I'm just havin' none of that.

# Answer
> 14 votes
## Python, 210 characters

Of course, this won't win because it is a code golf, but I wanted to be creative and I have **not** used the word `Love` in my source code:

```
import gzip
print(gzip.decompress(b'\x1f\x8b\x08\x00\x95\x10\xe0R\x02\xffSPP\xf0\xc9/KU\x80\x03\x10\x8f\x0bB\xa1c.l\x82dJ\xe0\xb0\x01\xe6\x02\x0cATa.T\xf7\x02\x00\xd9\x91g\x05\xc5\x00\x00\x00').decode('ascii'))

```

This is the output:

```
   Love          Love
  LoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLove
  LoveLoveLoveLoveLove
    LoveLoveLoveLove
      LoveLoveLove
          Love

```

# Answer
> 12 votes
## Python 2, 117

prints exactly 20 `love`s horizontally.

```
x="love";print"   x    x\nx xx x\nx   x   x".replace("x",x)
for i in range(5):print" "*i+x+" "*(9-i*2),x
print" "*6,x

```

output:

```
   love    love
love lovelove love
love   love   love
love          love
 love        love
  love      love
   love    love
    love  love
       love

```

# Answer
> 11 votes
## Perl - 36 bytes

```
  open    0;s
/\S.?/Lo.ve
  /ge,print
    , , for
        <0>

```

Output:

```
  LoveLove    LoveLove
LoveLoveLoveLoveLoveLove
  LoveLoveLoveLoveLove
    LoveLoveLoveLove
        LoveLove

```

This is a bit of a cheat; it will print `Love` once for every two non-white space characters in the source code. With the required whitespace to make the heart shape, the code is *61* bytes in length: flattened it is only *36* bytes:

```
open 0;s/\S.?/Lo.ve/ge,print,,for<0>

```

---

## Perl - 60 bytes

```
print$"x(15&ord),Love,$/x/\D/for'3h112a05e0n1l2j4f6b9'=~/./g

```

Outputs the following:

```
   Love        Love
 Love Love  Love Love
Love     Love     Love
Love              Love
 Love            Love
  Love          Love
    Love      Love
      Love  Love
         Love

```

Exactly 20 `Love`.

---

**Brief Explaination**
by request

* **`for'3h112a05e0n1l2j4f6b9'=~/./g`**
This modifies the print statement, and iterates over each character. The regex `/./` obviously matches a single character, and in a list context `/./g` will return a list of all characters in the string. A more common, but slightly longer way to write this would be `for split//,'3h112a05e0n1l2j4f6b9'`.
* **`print$"x(15&ord),Love,$/x/\D/`**
The special variable `$"` defaults to a space. The ordinal value of each character mod 16 stores the number spaces needed between each `Love` via string repetition (`x`). Finally, if the character is not a digit (`/\D/`), the value of `$/`, which defaults to `"\n"` is tacked on to the end.

# Answer
> 6 votes
# Wolfram Language (Mathematica) - 111

```
i=0;MatrixForm@Table[If[(x^2+y^2-200)^3+10x^2y^3<0,{"L","O","V","E"}[[i++~Mod~4+1]],""],{y,-20,20},{x,-20,20}]

```

# Answer
> 5 votes
# Javascript - 147 141 137 133 characters

```
with(Math){s="";for(k=800;k--;)
x=abs(1.25-k%40/16),y=k/320-1.25,
s+=.75>x+abs(y)|.5>sqrt(x*x-x+y*y-y+.5)
?"Love"[k%4]:39==k%40?"\n":" "}s

```

Note : I posted another answer, but this one use different approach and heart has a different shape.

How it works :

First, I render a diamond (equation is `|x|+|y|`) then, I combine two circles on the top. x values are mirrored (so only one circle is needed).

# Answer
> 4 votes
# Ruby, 47, or Golfscript, 41

Boring answer.

```
puts" Love  Love
"+"LoveLoveLove
"*6+"    Love"

```

Golfscript version:

```
" Love  Love
""LoveLoveLove
"6*"    Love"

```

Output:

```
 Love  Love
LoveLoveLove
LoveLoveLove
LoveLoveLove
LoveLoveLove
LoveLoveLove
LoveLoveLove
    Love

```

# Answer
> 4 votes
## JavaScript - 136 121 115 113 characters

```
s="";for(k=800;k--;)
x=1.25-k%40/16,y=k/320-1.25,
s+=Math.pow(x*x+y*y-1,3)<x*x*y*y*y
?"Love"[k%4]:39==k%40?"\n":" ";s

```

To run : copy paste into browser console (eg : Chrome or Firefox)

# Answer
> 4 votes
# Sclipting — 28 chars / 56 bytes

```
겤뙡늆굚넰밌各긂밀❷거雙復냄뭖끐❸갰右거雙復겠⓸걠右復終

```

Output:

```
    LOVE    LOVE
  LOVELOVELOVELOVE
LOVELOVELOVELOVELOVE
  LOVELOVELOVELOVE
    LOVELOVELOVE
      LOVELOVE
        LOVE

```

# Answer
> 3 votes
## C, 116 chars

(I don't know if this is heart-shaped enough... fills the inside of three circles to produce the output.)

```
i = 192, x, y;
main(t) {
  for (; i--; putchar(i % 16? y : 10))
    y = i / 16 - 8,
    x = i % 16 - 8,
    t = x*x + y*y,
    y = " Levo"[ (t < 64 & y < 0 | t < 8*abs(x)) * (i % 4 + 1) ];
}

```

Output:

```
 veLov   veLov
oveLove oveLove
oveLove oveLove
oveLove oveLove
oveLoveLoveLove
oveLoveLoveLove
oveLoveLoveLove
 veLoveLoveLov
 veLoveLoveLov
  eLoveLoveLo
    oveLove

```

Earlier in the golfing process, before replacing constant expressions (change `M` to adjust size):

```
#define M 4

i = 3*M * 4*M, x, y;
main(t) {
  for (; i--; putchar(i % (4*M)? x : '\n')) {
    y = i / (4*M) - 2*M, x = i % (4*M) - 2*M,
    t = x*x + y*y, x = " Levo"[ (t < 4*M*M & y < 0 | t < abs(2*M*x)) * (1 + i % 4) ];
  }
}

```

I also felt compelled to do this. :P

```
#define F for
#define M main

 /*##     ####
####*/i  =192,x
,y;M(t) {F(;i--
;putchar(i %16?
y:10))y=i/16-8,
x=i%16-8,t=x*x+
y*y,y=" Levo"[(
 t<64&y<0|t<8*
  abs(x))*(i%
    4+1)];}

```

# Answer
> 3 votes
# **Ruby - 113 Characters**

```
l=->a,b=28,c=1{puts (("Love"*a).center(b))*c};l.call(2,14,2);l.call(3,14,2);[7,7,7,6,5,4,3,2,1].map{|x|l.call(x)}

```

**Output:**

```
1.9.3p448 :811 > l=->a,b=28,c=1{puts (("Love"*a).center(b))*c};l.call(2,14,2);l.call(3,14,2);[7,7,7,6,5,4,3,2,1].map{|x|l.call(x)}
   LoveLove      LoveLove
 LoveLoveLove  LoveLoveLove
LoveLoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLoveLove
LoveLoveLoveLoveLoveLoveLove
  LoveLoveLoveLoveLoveLove
    LoveLoveLoveLoveLove
      LoveLoveLoveLove
        LoveLoveLove
          LoveLove
            Love

```

To be more clear

# Answer
> 3 votes
**Perl - 159 characters**

Not massively golfed...

```
printf"%-14s%14s\n",$_,~~reverse for map{($.,$i,$c)=split',';($"x$i).($.x$c)}qw(L,5,3 o,3,8 v,1,11 e,0,13 L,1,13 o,3,11 v,5,9 e,7,7 L,8,6 o,10,4 v,12,2 e,13,1)

```

Here's the same with added whitespace for slightly better readability...

```
printf "%-14s%14s\n", $_, ~~reverse
   for map {
      ($.,$i,$c) = split',';
      ($"x$i).($.x$c)
   } qw(
      L,5,3
      o,3,8
      v,1,11
      e,0,13
      L,1,13
      o,3,11
      v,5,9
      e,7,7
      L,8,6
      o,10,4
      v,12,2
      e,13,1
   )

```

Output is...

```
     LLL            LLL
   oooooooo      oooooooo
 vvvvvvvvvvv    vvvvvvvvvvv
eeeeeeeeeeeee  eeeeeeeeeeeee
 LLLLLLLLLLLLLLLLLLLLLLLLLL
   oooooooooooooooooooooo
     vvvvvvvvvvvvvvvvvv
       eeeeeeeeeeeeee
        LLLLLLLLLLLL
          oooooooo
            vvvv
             ee

```

The complete word "Love" is contained within (vertically) 22 times, plus numerous partials.

# Answer
> 3 votes
# APL, 36 chars / bytes\*

```
7 16⍴∊'  ' 'Love'[20400948744⊤⍨36/2]

```

Must be evaluated with `⎕IO←0` (the default varies by implementation)

\*APL can be written in a single-byte charset if needed (as long as you don't use any other Unicode character) so N chars = N bytes for the purpose of counting.

**Output:**

Contains exactly 20 "Love"

```
  Love    Love
LoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLoveLove
  LoveLoveLove
    LoveLove
      Love

```

# Answer
> 2 votes
# Extended BrainFuck : 193 (counted without non essential whitespace)

```
    {h]<[<]<        [<}>>-->
-3>->-3>+9>+9>+>-7>+>->-5>+>->->
-3>+>+>>4->->6+>5+>>4+[-<4+>]<[-
<4+<5+<5+<5+4>&h++]>[-[-[<10+.[-]
    >-[[-]3<[-]]>[<4+3<[[->>
    +<<]<]]]>[[>]>[.>&h]<<++
        >]]>[<<4+[->8+<]
        >....[-]<<+>>]>]

```

Turns into:

# Brainfuck: 264 (counted without non essential whitespace)

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

```

You run it with any bf interpreter. Ubuntu has `bf` and `beef` and both works nicely.

```
bf heart.bf

```

The output (344 bytes):

```
    LOVELOVE        LOVELOVE
    LOVELOVE        LOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
LOVELOVELOVELOVELOVELOVELOVELOVE
    LOVELOVELOVELOVELOVELOVE
    LOVELOVELOVELOVELOVELOVE
        LOVELOVELOVELOVE
        LOVELOVELOVELOVE
            LOVELOVE
            LOVELOVE

```

Ungolfed EBF code:

```
>>--> ; mark

;; ##  ##@
;;########@
;;########@
;; ######@
;;  ####@
;;   ##@
;; the block below is the art above
;; where space is replaced with ->
;; # with > and @ with +>
->>>->->>>+>
>>>>>>>>+>
>>>>>>>>+>
->>>>>>>+>
->->>>>>+>
->->->>>+>+>

;; we store the string LOVE after a blank
>
~"LOVE"<[<]<
[<++] ;; add 2 to every cell until mark

;; Variables
:new
:zero
:in
:next

@zero
$in(
  -[ ; 1
     -[ ; 2
        $zero 10+.[-]
        $in-[#[-]$new<[-] @in] ; its second round lf
        $next[#$in++++$new<[[->>+<<]<]]@new     ; 2
      ]
      >[[>]>[.>]<[<]<[<]<<++>   ]@new
  ]>[@next $zero 4+(-$in 8+) $in.... (-) $new+ $in]@zero
)

```

# Answer
> 2 votes
# C# 224

```
class P{static void Main(){for(int i=0,m=1;i<30;i++)for(int l=0;l<new[]{5,6,7,6,8,10,3,10,4,13,1,13,1,87,1,27,4,23,7,20,11,16,16,11,20,7,24,3,27,1}[i];l++,m++)System.Console.Write((i%2>0?"love"[m%4]:' ')+(m%29>0?"":"\n"));}}

```

Formatted:

```
class P
{
    static void Main()
    {
        for (int i = 0, m = 1; i < 30; i++)
            for (int l = 0; l < new[] { 5, 6, 7, 6, 8, 10, 3, 10, 4, 13, 1, 13, 1, 87, 1, 27, 4, 23, 7, 20, 11, 16, 16, 11, 20, 7, 24, 3, 27, 1 }[i]; l++, m++)
                System.Console.Write((i % 2 > 0 ? "love"[m % 4] : ' ') + (m % 29 > 0 ? "" : "\n"));
    }
}

```

Output:

```
     velove       elovel
   ovelovelov   velovelove
 lovelovelovel velovelovelov
lovelovelovelovelovelovelovel
ovelovelovelovelovelovelovelo
velovelovelovelovelovelovelov
 lovelovelovelovelovelovelov
   elovelovelovelovelovelo
    ovelovelovelovelovel
      lovelovelovelove
         lovelovelov
           elovelo
             vel
              l

```

# Answer
> 1 votes
**Perl - 97 characters**

This answer is based on @Wasi's 121 character Python solution.

```
$.=love;say"   $.    $.$/$. $.$. $.$/$.   $.   $.";say$"x$_,$.,$"x(9-$_*2),$.for 0..4;say$"x 6,$.

```

You need to run perl with the `-M5.010` option to enable 5.10-specific features. This is apparently allowed.

Interesting features:

* I use the variable `$.` to store the word "love". This is because it can be immediately followed by another word if necessary. `$.for` is unambiguously tokenized as `$.` followed by `for`; `$_for` would not be tokenized as `$_` followed by `for` because `$_for` is itself a legal variable name.
* `$"`, a built-in variable representing that character that arrays will be joined with when interpolated into a string (and defaults to a single space character) is used instead of `" "` for savings of one character here and there.
* Perl's string interpolation beats the python `.replace` method significantly in code golfing.
* Perl's `for 0..4` similarly wins over `for i in range(5)`

# Answer
> 1 votes
# Python, 334 Bytes

```
x = "love"
print("\t  love\t      love")
print("\t"+str(x*2)+"    "+str(x*2))
print("      "+str(x*6))
print(str(" "*5)+str(x*6)+"lo")
print(str(" "*5)+str(x*6)+"lo")
print("      "+str(x*6))
print("\t"+str(x*5))
print("\t"+str(" "*2)+str(x*4)+"l")
print("\t"+str(" "*4)+str(x*3)+"l")
print("\t"+str(" "*7)+str(x*2))
print("\t"+str(" "*10)+"v")

```

output:

# Answer
> 1 votes
# CJam - 33 bytes

```
19285703234336595Zb["Love"SS+N]f=

```

Try it online

**Output:**

```
  Love    Love
LoveLoveLoveLove
LoveLoveLoveLove
LoveLoveLoveLove
  LoveLoveLove
    LoveLove
      Love

```

**Explanation:**

```
19285703234336595    number that contains the pattern as base-3 digits
Zb                   converts to base 3 (Z=3)
["Love"SS+N]         creates an array containing "Love", "  " and a newline
f=                   replaces the base-3 digits with the corresponding strings
                     (0 -> "Love", 1 -> "  ", 2 -> newline)

```

# Answer
> 0 votes
**Bash, 170 bytes**

totally a copy of programFOX's :)

```
echo '\x1f\x8b\x08\x00\x95\x10\xe0R\x02\xffSPP\xf0\xc9/KU\x80\x03\x10\x8f\x0bB\xa1c.l\x82dJ\xe0\xb0\x01\xe6\x02\x0cATa.T\xf7\x02\x00\xd9\x91g\x05\xc5\x00\x00\x00'|gunzip

```

# Answer
> 0 votes
print('\n'.join(\[''.join(\[(' *Your text here*'\[(x-y) % len(' *Enter same text here*')\] if ((x*0.05)\**2+(y*0.1)\**2-1)\**3-(x\*0.05)**2*(y*0.1)\**3 \<= 0 else ' ') for x in range(-30, 30)\]) for y in range(30, -30, -1)\]))

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


title: There Was an Old Lady

text:
# Question
Title: There Was an Old Lady
Your goal is to write a program that prints the following poem exactly as it appears here:

```
There was an old lady who swallowed a fly.
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a spider,
That wriggled and iggled and jiggled inside her.
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a bird,
How absurd to swallow a bird.
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a cat,
Imagine that to swallow a cat.
She swallowed the cat to catch the bird,
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a dog,
What a hog to swallow a dog.
She swallowed the dog to catch the cat,
She swallowed the cat to catch the bird,
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a horse,
She died of course.

```

The text must appear exactly as it does here, and fewest characters wins.

Edit: Your program may not access the internet.

# Answer
## Perl 5.10, ~~392~~ ~~384~~ ~~372~~ ~~235~~ 369 (ASCII) / 234 (Unicode)

The shortest ASCII version of this is 369 characters long:

```
@_=(fly,spider,bird,cat,dog);$_="There was an old lady who!ed a";for$P("",",
That wrJand Jand jJinside her",",
How absurd&",",
Imagine that&",",
What a hog&"){$p=$c;$c=$".shift@_;$t=$p?"She!ed the$c to catch the$p,
$t":"I don't know why she!ed that$c,
Perhaps she'll die.

$_";$_.="$c$P.
$t";s/&/ to! a$c/}s/!/ swallow/g;s/J/iggled /g;say"$_ horse,
She died of course."

```

It started from this base program:

```
my @animals = qw(fly spider bird cat dog);
my $buf = "There was an old lady who swallowed a ";
for my $phrase ( "",
                 ",\nThat wriggled and iggled and jiggled inside her",
                 ",\nHow absurd&",
                 ",\nImagine that&",
                 ",\nWhat a hog&" ) {
  $previous = $current;
  $current = shift @animals;
  $trail = $previous ? "She swallowed the $current to catch the $previous,\n$trail"
                     : "I don't know why she swallowed that $current,\n"
                       . "Perhaps she'll die.\n\n$buf";
  $buf .= "$current$phrase.\n$trail";
  $buf =~ s/&/ to swallow a $current/;
}
say "$buf horse,\nShe died of course.";

```

The core idea is to keep the end of the rhyme and the beginning of the next one in `$trail`, augmenting it as we go along. It's made non-trivial by the need of a special case for the first use, and the attempt to re-use the animal name variable even in the animal-specific phrase. Further optimizations include:

* one-character identifiers for everything
* using barewords instead of quoted strings for the animal list
* use of the accumulator `$_` for `$buf` to shorten most substitution operations even more (use of `@_` is by force of habit and doesn't win anything more than any other character)
* including the preceding space directly inside the animal name variable (the space character taken from the `$"` variable)
* regexp substitution to shorten the most common phrases: `' swallow'` and `'iggled '`
* no code spacing whatsoever and all `\n` in string literals replaced with actual newlines

All but the last optimization yield this:

```
@_ = (fly, spider, bird, cat, dog);
$_ = "There was an old lady who!ed a";
for $P ( "",
         ",\nThat wrJand Jand jJinside her",
         ",\nHow absurd&",
         ",\nImagine that&",
         ",\nWhat a hog&" ) {
  $p = $c;
  $c = $" . shift @_;
  $t = $p ? "She!ed the$c to catch the$p,\n$t"
          : "I don't know why she!ed that$c,\nPerhaps she'll die.\n\n$_";
  $_ .= "$c$P.\n$t";
  s/&/ to! a$c/;
}
s/!/ swallow/g;
s/J/iggled /g;
say "$_ horse,\nShe died of course.";

```

Additionally, this golf is a victim of the underspecified encoding problem. As it—as of now—counts individual characters instead of bytes in a specified encoding, there's a big gain to be achieved by decoding the program source from UCS2 before starting. The final result isn't very readable anymore, but it's short all right. (234 characters, counted as a difference from `perl -E''` as usual) (I had to include the trailing newline back to make it valid UCS2)

```
$ perl -MEncode=from_to -e'$_="䁟㴨晬礬獰楤敲Ɫ楲搬捡琬摯朩㬤弽≔桥牥⁷慳渠潬搠污摹⁷桯Ⅵ搠愢㭦潲⑐⠢∬∬੔桡琠睲䩡湤⁊慮搠橊楮獩摥敲∬∬ੈ潷扳畲搦∬∬੉浡杩湥⁴桡琦∬∬੗桡琠愠桯朦∩笤瀽④㬤挽␢⹳桩晴䁟㬤琽⑰㼢卨攡敤⁴桥④⁴漠捡瑣栠瑨攤瀬ਤ琢㨢䤠摯渧琠歮潷⁷桹⁳桥Ⅵ搠瑨慴④Ⰺ健牨慰猠獨攧汬楥⸊ਤ弢㬤弮㴢④⑐⸊⑴∻猯☯⁴漡④⽽猯ℯ⁳睡汬潷⽧㭳⽊⽩杧汥搠⽧㭳慹∤张桯牳攬੓桥楥搠潦潵牳攮∊";from_to($_,utf8,ucs2);eval'

```

A good thing there was a lot to golf from before resorting to Unicode, or it wouldn't be much fun.

*Edit:* ~~can't find a way to copy/paste the 234-character version to this browser, so I'm leaving the 235-character one. Will fix this evening, when I get my hands on a real UTF8-aware clipboard.~~ found a way. Quasi-proof on ideone.
> 17 votes

# Answer
## Perl, 120 94 chars

Count includes call to the interpreter.

You did say to reproduce it *exactly* as it does here ;)

```
perl -MLWP::Simple -E'($p=get("http://goo.gl/kg17j"))=~s#^.+?pr.*?de>|</co.*?re>.+$##sg;say$p'

```

### N.B.

This solution is what prompted the 'no-Internet' restriction. Let it be a lesson for future code-golf question specifications :)
> 9 votes

# Answer
# Vim, 373 keystrokes

```
iThere was an old lady who swallowed a fly.
I don't know why she s<C-n> that f<C-n>,
Perhaps she'll die.

T<C-x><C-l><Left><C-w>spider<Esc>oThat wriggled <Esc>6hiand <Esc>3hy$u$ppbij<End>inside her.
She s<C-n> the sp<C-n> to catch the f<C-n>,
I<C-x><C-l><C-x><C-l><Esc>qqyapGp3jYPkk$Bqcwbird<Esc>+CHow absurd to sw<C-n><Backspace><Backspace> a b<C-n>.<Esc>qwyb5wvep$Bvepq@qcwcat<Esc>+CImagine that to sw<C-p> a cat.<Esc>@w@qcwdog<Esc>+CWhat a hog to sw<C-p> a dog.<Esc>@w@qcwhorse<Esc>+cGShe d<C-p>d of course.

```

Funny how exponential that scrambling is.
> 5 votes

# Answer
## Python 3.x: 407 chars

```
import base64,zlib;print(zlib.decompress(base64.b64decode(b'eNrlkLFOxDAQRPt8xXTXoHwHdEhEot7L+myD8Z7snKz8Pd6LT7mgFFQIRGftPs/OzOBMMiiUQRESGIF4RnGCXCgEKYZBOIW5B7onsMTDhPcopTIzsjN33ORoUvShos8mOTpnJQ4hgL3pu2741rF89mySigwqWJK3NugmMu6eb+3tY648qrRafPniyDQ5TIKRptFdZ83kz+Q5+sQq8ViP0DFfEquZRrT9vnXdbI2v3fzCoPXs9dgHWR/NorpJWoH9oONCrr5vnf35TlisKryqGsGJ3TZS1/uN8EKurlu5/6k7Jymbm7f6kSEnjHKp0/4TSSOZgA==')).decode('utf8'))

```
> 4 votes

# Answer
## JavaScript (422)

Works in the SpiderMonkey interpreter versions used by both anarchy golf and ideone.

```
for(a="fly0spider0bird0cat0dog0horse0How absurd0Imagine that0What a hog".split(i=0);p=print;p("I don't know why she swallowed that fly,\nPerhaps she'll die.\n")){p("There was an old lady who swallowed a",a[i]+(i?",":"."));i>4&&quit(p("She died of course."));i&&p(i>1?a[4+i]+" to swallow a "+a[i]+".":"That wriggled and iggled and jiggled inside her.");for(j=i++;j;)p("She swallowed the "+a[j]+" to catch the "+a[--j]+",")}

```

A bit more nicely formatted:

```
for (a = "fly0spider0bird0cat0dog0horse0How absurd0Imagine that0What a hog".split(i = 0);
p = print; p("I don't know why she swallowed that fly,\nPerhaps she'll die.\n")) {
    p("There was an old lady who swallowed a", a[i] + (i ? "," : "."));
    i > 4 && quit(p("She died of course."));
    i && p(i > 1
        ? a[4 + i] + " to swallow a " + a[i] + "."
        : "That wriggled and iggled and jiggled inside her."
    );
    for (j = i++; j;) p("She swallowed the " + a[j] + " to catch the " + a[--j] + ",");
}

```
> 3 votes

# Answer
# C (gcc), ~~429~~ ~~424~~ 423 bytes

-5 bytes thanks to ceilingcat

```
c,*w[]={"384fly<1","I don't know why she5ed that fly<Perhaps she'll die.772","There was an old lady who5ed a ","She5ed the "," to catch the "," swallow"," to5 a ","\n","spider","bird","cat","iggled ",",7","3948<0"};U(char*s){for(;c=*s++;)c>47&c<65?U(w[c-48]):putchar(c);}f(){U("2fly.718<That wr;and ;and j;inside her.709<How absurd69.7=:<Imagine that6:.73:49<=dog<What a hog6dog.73dog4:<3:49<=horse<She died of course.7");}

```

Try it online!
> 3 votes

# Answer
# ink, ~~370~~ ~~369~~ 354 bytes

```
LIST B=fly,spider,bird,cat,dog,horse
VAR s=" swallow"
-(i)~B=B(i)
There was an old lady who{s}ed a {B}{.|,}
{|That wriggled and iggled and jiggled inside her|How absurd|Imagine that|What a hog|She died of course.->END}{|.| to{s} a {B}.}
-(k)~B--
{B:
She{s}ed the {B+1} to catch the {B},
->k
}I don't know why she{s}ed that fly,
Perhaps she'll die.
\
->i

```

Try it online!

### Explanation

```
LIST B=fly,spider,bird,cat,dog,horse           // Ink's "LIST"s aren't much like lists - they're more like enums. Here we create a list type stating what animals exist, and make a set containing none of them.
VAR s=" swallow "                              // Pretty self-explanatory
-(i)~B=B(i)                                    // The i label keeps track of how many times we've visited it. We set B (the set) to be equal to the i-th item in B (the list type).
There was an old lady who{s}ed a {B}{.|,}      // Print the first line. {.|,} is a sequence - it's a period the first time it's encountered, and a comma every subsequent time.
                                               // Sequences can have more than one item in them, which is how we print the second line. When we get to the horse one, we terminate the program right away.
{|That wriggled and iggled and jiggled inside her|How absurd|Imagine that|What a hog|She died of course.->END}{|.|to{s} a {B}}.}
-(k)~B--                                       // Step back through the list type.
{B:                                            // A conditional - we execure the next two lines if B is non-empty.
She{s}ed the {B+1} to catch the {B},           // Print the "she swallowed the..." line
->k                                            // And repeat
}I don't know why she{s}ed that fly,           // Only reached when the conditional fails.
Perhaps she'll die.
\                                              // A backslash and a space to force an empty line.
->i                                            // Back to the top

```
> 3 votes

# Answer
### Ruby, 436 characters

```
w=" swallowed "
f="There was an old lady who#{w}a "
c=" to swallow a %s"
b="dog","cat","bird","spider","fly"
s=nil,"That wriggled and iggled and jiggled inside her","How absurd"+c,"Imagine that"+c,"What a hog"+c
a=[]
5.times{k=g=b.pop;t,*s=s
puts f+k+(t ??,:?.),t&&[t%k+?.,a.map{|x|y,k=k,x;"She#{w}the #{y} to catch the #{k},"}],"I don't know why she#{w}that fly,","Perhaps she'll die.",""
a=[g]+a}
puts f+"horse,","She died of course."

```
> 2 votes

# Answer
## Scala (~~706~~ ~~619~~ ~~599~~ 550 chars)

```
val L=Seq("fly","spider","bird","cat","dog")
val M="\nThere was an old lady who %sed a %s,"
type S=String
def s(l:S,a:S="",b:S="")=l.format("swallow",a,b)
def p(l:S,a:S=""){println(s(l,a))}
var i=0
var r=List[S]()
L.map{a=>{p(M,a)
if(i>0){p(Seq("","That wriggled and iggled and jiggled inside her.","How absurd","Imagine that","What a hog")(i)+(if(i>1)" to %s a %s."else""),a)
r::=s("She %sed the %s to catch the %s,",L(i),L(i-1))
r.map(p(_))}
p("I don't know why she %sed that fly,\nPerhaps she'll die.")
i+=1}}
p(M,"horse")
p("She died of course.")

```

Using map instead of foreach allows to squeeze more chars... In codegolf, we don't care about performance, elegance (non-mutability) or logic...
> 2 votes

# Answer
# Stax, 195 bytes

```
ó┤♣≤jß¡εD<Çjò≡²£c¼ìv┴Åô║,·~┼¢╝EΦ5xZ&√σ"ømÿ≡ZπvÅ╦♣1♦>▄\¬◘¡jS¢í╞╟╚);4j↕i¢s♦éÇöy‼ac┴àÇ╩»-ó»ónú¢│g5εÿ╔µ┬bîæ¢k‼f╓fJ○▐═╜<^Γ▀o▀Δnq░╩αÄ&│♣ⁿâmû╣Ç≡*@☺pG_ⁿö┤mσ/V\└?iq┌îB½Ä¿L╙N┐£Ç≥δ2 0δrµLä⌡(⌡▀╬àΦ⌠tƒìg" ⌠ZHó

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
`]q~*}8x9uA3_P0O`jX         push ["fly", "spider", "bird", "cat", "dog"] and store in X register
{                           start iteration over animal list
  `p{+P91{m@Lwe\Jk?!#8`Yp   Store "There was an old lady who swallowed a " in Y register and print it
  .,.i!@+                   Concatenate "." on the first iteration and "," thereafter to the animal
  P                         Print
  i{                        On all iterations after the first, execute this block
    `r4uB2O'O(4XghNqE PhaMg^-riMgR{N>A8LfCNqh@Rn$=aHX|93@_5d?d7qp2-`
                        Push "That wriggled and iggled and jiggled inside her. How absurd, bird. Imagine that, cat. What a hog, dog. She died of course"
    ',`?~nA${F"`R       Replace "," with " to swallow a"
    .. /                Split on string ". "
    iv@                 Get the (i-1)th element where i is the iteration index
    '.+P                Concatenate "." and print
  }M                    End of conditional block
  x2B                   Get adjacent pairs from x (list of animals)
  i(                    Keep first i pairs where i is the iteration index
  r{                    Iterate over reversed list of pairs
    `_,m+"S3&#`p        Print "She swallowed the "
    Ep                  Print the second animal from the pair
    `p<qr?t`p           Print " to catch the "
    ',+P                Concatenate "," to the first animal from the pair and print
  F                     End iterating block
  `;p(9Cv,77BzpP'kB|"`P Print "I don't know why she swallowed that fly,"
  `%?/3.=iHiS6y!`P      Print "Perhaps she'll die."
  zP                    Print a newline
F                       End outer animal iteration.
yp                      Print y register. ("There was an old lady who swallowed a ")
`zvVH`P                 Print "horse,"
                        Print "She died of course." with an unterminated literal
`AJt6Q.3+$!

```

Run this one
> 2 votes

# Answer
# Zsh \+ coreutils, <sup>~~406~~</sup> 375 bytes

```
g()ls -t<>"She$d the $1 to catch the $2,"
set bird spider \ swallow iggled\
<<Z
${b=There was an old lady who${d=$3ed} a }fly.${5=
I don't know why she$d that fly,
Perhaps she'll die.

$b}$2,
That wr$4and $4and j$4inside her.
`g $2 fly`$5$1,
How absurd${6= to$3 a }$1.
`g $@`$5cat,
Imagine that$6cat.
`g cat $1`$5dog,
What a hog$6dog.
`g dog cat`$5horse,
She died of course.

```

Try it online!

Tricks:

* the `g` function creates the line as a file and then `ls` lists the files in the current directory in order of creation (`-t`), to avoid having to repeat the previous lines every time.
    + I used `<>` (which creates the file before the command is executed) instead of `>...;` because using multiple commands in a function requires `{}` around them
* `set bird ...` assigns the words to `$1`, `$2`, etc.
* `\ swallow` includes a space at the start of without needing to use quotes
* `<<Z` starts a heredoc which is effectively a long interpolated string
* `${b=There...}` is a shorthand form setting `b` to that string and substituting its value in
* Indexed variables like `$1`, `$2`, etc. can be substituted without a space afterwards (rather than being interpreted as a variable called `5dog`, for example), so we prefer them as it allows us to include the space inside the assignment to avoid repeating it
* `g $@`: since we set `$1` and `$2` to `bird` and `spider` respectively, we can pass all the numbered variables to `g` in one go with `$@` instead of `g $1 $2` (it ignores the extra ones, `$3` etc.)
> 2 votes

# Answer
# PowerShell Core, ~~503~~ 484 bytes

```
$i=" bird"
$k=" swallowed"
$g="She$k the"
$h=" to catch the"
$c="There was an old lady who$k a"
$e=" to swallow a"
$s=" spider"
"$c fly."
$c="`n$c"
($a="I don't know why she$k that fly,`nPerhaps she'll die.")
"$c$s,`nThat wriggled and iggled and jiggled inside her."
($d="$g$s$h fly,")
$a
"$c$i,`nHow absurd$e$i."
($j="$g$i$h$s,")
$d
$a
"$c cat,`nImagine that$e cat."
($b="$g cat$h$i,")
$j
$d
$a
"$c dog,`nWhat a hog$e dog.`n$g dog$h cat,"
$b
$j
$d
$a
"$c horse,`nShe died of course."

```

Try it online!

It was a fun one! :)
> 2 votes

# Answer
# 05AB1E, ~~237~~ ~~222~~ ~~218~~ 224 bytes

+6 bytes to fix a bug (In most verses the first line ends in a `,`)

```
“¤†É¾£‡—Ä‹·î€“#©€“€Ç€¥€¤„Ï£î€Ð 1ed€… ÿ,“®¦¦¨.•Ω\3¯ÓõÔ)V₄H`«Å₆éÅΘΓåò•ć¡δ"ÿ to 1 a ÿ."Å\“€Š wr0€ƒ 0€ƒ j0‹â‚®.“š“‚Îœ·€‚…£.“ª0šø0δK®ü“‚Î 1ed€€ ÿ€„¬ª€€ ÿ,“¨ηíõšε“i¥Ú'tƒ€„Ý‚Î 1ed€Š¤†,“ª“™¡‚Î'll—Ç.
“ª}õª.ι˜.ª»T.•4Ƶ›₅8zεÚS•#‡¨','..;

```

Try it online!

**Commented:**

```
“¤†É¾£‡—Ä‹·î€“              # push dictionary compressed string "fly spider bird cat dog horse"
#                           # split on spaces
©                           # store the list of animals in the register
€“€Ç€¥€¤„Ï£î€Ð 1ed€… ÿ,“    # for each animal, push the string "there was an old lady who 1ed a ÿ,"
                            #   where ÿ s replaced by the animal
®                           # push the list of animals again
¦¦¨                         # remove the fly, the spider and the horse: ["bird", "cat", "dog"]
.•Ω\3¯ÓõÔ)V₄H`«Å₆éÅΘΓåò•    # push alphabet compressed string "xhow absurdximagine thatxwhat a hog"
ć                           # extract the first character "x"
¡                           # split the remaining string on "x": ["how absurd", "imagine that", "what a hog"]
δ"ÿ to 1 a ÿ."Å\            # format the string "ÿ to 1 a ÿ." with a value from this list and one from the short animal list
                            #  => ["how absurd to 1 a bird.", "imagine that to 1 a cat.", "what a hog to 1 a dog."]
“€Š wr0€ƒ 0€ƒ j0‹â‚®.“      # push compressed dictionary string "that wr0 and 0 and j0 inside her."
š                           # prepend this to the list
“‚Îœ·€‚…£.“                 # push compressed dictionary string "she died of course."
ª                           # append this to the list
0š                          # prepeand a 0
ø                           # zip both lists together
0δK                         # remove 0's in sublists
                            #  => [["there was an old lady who 1ed a fly,"],
                            #      ["there was an old lady who 1ed a spider,", "that wr0 and 0 and j0 inside her."],
                            #      ["there was an old lady who 1ed a bird,", "how absurd to 1 a bird."],
                            #      ["there was an old lady who 1ed a cat,", "imagine that to 1 a cat."],
                            #      ["there was an old lady who 1ed a dog,", "what a hog to 1 a dog."],
                            #      ["there was an old lady who 1ed a horse,", "she died of course."]]
®                           # push the list of animals again
ü“‚Î 1ed€€ ÿ€„¬ª€€ ÿ,“      # format the string "she 1ed the ÿ to catch the ÿ," with adjacent pairs of animals
¨                           # remove the last string
                            #  => ["she 1ed the spider to catch the fly,", "she 1ed the bird to catch the spider,", "she 1ed the cat to catch the bird,", "she 1ed the dog to catch the cat,"]
η                           # take the prefixes of this list
í                           # reverse each prefix
õš                          # prepend the empty string
ε                           # map over the prefixes:
  “i¥Ú'tƒ€„Ý‚Î 1ed€Š¤†,“    #   push compressed string "i don't know why she 1ed that fly,"
  ª                         #   append to the prefix
  “™¡‚Î'll—Ç.\n“            #   push compressed string "perhaps she'll die.\n"
  ª                         #   append to the prefix
}                           # end of map
õª                          # append an empty string to the list of prefixes
.ι                          # interleave the list of prefixes with the earlier list
˜                           # flatten everything into a list of lines
.ª                          # sentence-case each line
»                           # join by newlines
T                           # push 10
.•4Ƶ›₅8zεÚS•                # push compressed string "swallow iggled"
#                           # split on the space
‡                           # in the poem replace every digit of 10 with the corresponding word in this list
                            #   1 -> swallow, 0 -> iggled
¨                           # remove a trailing newline
','..;                      # replace the first "," with a "."

```
> 2 votes

# Answer
## Python, 484

Ok, I did it but was pretty boring...

The last sentence is always with "fly" so some chars were removed...

```
f,s,b,c,d=o='fly spider bird cat dog'.split()
x='There was an old lady who swallowed a %s.\n'
t=' to swallow a %s.\n'
r=['That wriggled and iggled and jiggled inside her.\n','How absurd'+t%b,'Imagine that'+t%c,'What a hog'+t%d]
t=("She swallowed the %s to catch the %s,\n"*4%(d,c,c,b,b,s,s,f)).split('\n')
print("I don't know why she swallowed that fly,\nPerhaps she'll die.\n\n".join([x%f]+[x%o[i]+r[i-1]+'\n'.join(t[-i-1:])for i in range(1,5)]+[''])+x%'horse'+'She died of course.')

```

Less golfed version:

```
f,s,b,c,d = all = 'fly spider bird cat dog'.split()

what = 'There was an old lady who swallowed a %s.\n'

t = ' to swallow a %s.\n'
comments = ['That wriggled and iggled and jiggled inside her.\n',
            'How absurd' + t%b,
            'Imagine that' + t%c,
            'What a hog' + t%d]

swallowed = "She swallowed the %s to catch the %s,\n"
lines = (swallowed*4%(d,c,c,b,b,s,s,f)).split('\n')

end = '''I don't know why she swallowed that fly,
Perhaps she'll die.\n\n'''

def who_catch_who(i):
    return '\n'.join(lines[-i-1:])

p = end.join([what % f] +
             [what % all[i] +
              comments[i-1] +
              who_catch_who(i) for i in range(1,5)] +
             [''])

print(p + what % 'horse' + 'She died of course.')

```
> 1 votes

# Answer
## Haskell, 515 498

*Score does not count newlines and spaces added for presentation.*

```
b c a="There was an old lady who swallowed a "++a++c++".\n"
t r a=b(",\n"++r++" to swallow a "++a)a
s(a,b)="She swallowed the "++a++" to catch the "++b++",\n"
z=["fly","spider","bird","cat","dog"]
h=[b"",b",\nThat wriggled and iggled and jiggled inside her",t"How absurd",
 t"Imagine that",t"What a hog"]
v(g,p)=g++(=<<)s(zip p$tail p)++
 "I don't know why she swallowed that fly,\nPerhaps she'll die.\n\n"
main=putStr$(=<<)v(zip(zipWith($)h z)(tail$scanl(flip(:))[]z))++b
 ",\nShe died of course""horse"

```

### Ungolfed:

```
type Animal = String
type Comment = String

beginning :: Animal -> Comment -> String
beginning animal comment = "There was an old lady who swallowed a " ++ animal ++ comment ++ ".\n"

ending :: String
ending = "I don't know why she swallowed that fly,\nPerhaps she'll die.\n\n"

to_swallow :: String -> Animal -> Comment
to_swallow start animal = ",\n" ++ start ++ " to swallow a " ++ animal

swallowed_to_catch :: (Animal, Animal) -> String
swallowed_to_catch (a, b) = "She swallowed the " ++ a ++ " to catch the " ++ b ++ ",\n"

animals :: [(Animal, Animal -> Comment)]
animals = [("fly",    const "")
          ,("spider", const ",\nThat wriggled and iggled and jiggled inside her")
          ,("bird",   to_swallow "How absurd")
          ,("cat",    to_swallow "Imagine that")
          ,("dog",    to_swallow "What a hog")
          ]

-- Turn [1,2,3,4,5] into [[1], [2,1], [3,2,1], [4,3,2,1], [5,4,3,2,1]]
trail :: [a] -> [[a]]
trail = tail . scanl (flip (:)) []

verses :: [String]
verses = zipWith verse animals (trail $ map fst animals)

verse :: (Animal, Animal -> Comment) -> [Animal] -> String
verse (animal, comment) swallow_chain =
    beginning animal (comment animal) ++
    concatMap swallowed_to_catch (zip swallow_chain (tail swallow_chain)) ++
    ending

poem :: String
poem = concat verses ++ beginning "horse" ",\nShe died of course"

main :: IO ()
main = putStr poem

```
> 1 votes

# Answer
# C, for fun (561 chars)

*Score does not count newlines and spaces added for presentation.*

Thanks to J B for his improvements!

```
#include <stdio.h>

void main() {
    char *e = "\nShe swallowed the cat to catch the bird,\nShe swallowed the bird to catch the spider,\nShe swallowed the spider to catch the fly,\nI don't know why she swallowed that fly,\nPerhaps she'll die.\n\nThere was an old lady who swallowed a ";
    printf("%sfly.%sspider,\nThat wriggled and iggled and jiggled inside her.%sbird,\nHow absurd to swallow a bird.%scat,\nImagine that to swallow a cat.%sdog,\nWhat a hog to swallow a dog.\nShe swallowed the dog to catch the cat,%shorse,\nShe died of course.", e+191, e+128, e+85, e+41, e, e);
}

```
> 1 votes

# Answer
**C#, 556 chars**

```
class P{static void Main(){string a="There was an old lady who swallowed a ",b="I don't know why she swallowed that ",c="She swallowed the ",d=" to catch the ",e="Perhaps she'll die.\n\n",f="fly",g="spider",h="bird",i="cat",j="dog",k=",\n",l=".\n",m="to swallow a ",n=c+g+d+f+k,o=c+h+d+g+k,p=b+f+k,q=c+i+d+h+k,r=n+p,s=o+r,t=q+s,u=e+a;System.Console.Write(a+f+l+p+u+g+k+"That wriggled and iggled and jiggled inside her"+l+r+u+h+k+"How absurd "+m+h+l+s+u+i+k+"Imagine that "+m+i+l+t+u+j+k+"What a hog "+m+j+l+c+j+d+i+k+t+u+"horse"+k+"She died of course.");}}

```
> 1 votes

# Answer
# Perl, 489 chars

```
sub Y{$t=pop;my$s;while($b=pop){$s.="She ${W}ed the $t to catch the $b,\n";$t=$b;}$s.=$l{fly}.$/;}$W='swallow';$w='iggled';$q=" to $W a";$o="There was an old lady who ${W}ed a";$h='hat';@f=qw/fly spider bird cat dog/;@l{@f}=("I don't know why she ${W}ed t$h fly,
Perhaps she'll die.$/","T$h wr$w and $w and j$w inside her.","How absurd$q bird.","Imagine t$h$q cat.","W$h a hog$q dog.");map{$m=$f[$_];print"$o $m,
$l{$m}
",$_?Y@f[0..$_]:'';}0..$#f;print"$o horse,
She died of course.$/"

```
> 1 votes

# Answer
# tcl, 451 bytes

```
lassign {\ swallowed fly, spider " to catch the " bird cat iggled " to swallow a"} W f s c b a i w
puts "[set t "There was an old lady who$W a "]fly.
[set I "I don't know why she$W that $f
Perhaps she'll die.

"]$t$s,
That wr$i and $i and j$i inside her.
[set S "She$W the "]$s$c$f
$I$t$b,
How absurd$w $b.[set v \n$S$b$c$s,\n$S$s$c$f\n$I]$t$a,
Imagine that$w $a.
[set X $S$a$c$b,$v$t]dog,
What a hog$w dog.
${S}dog$c$a,
$X\horse,
She died of course."

```

Available to run on: http://rextester.com/live/GXF89639 (10th attempt)
> 1 votes

# Answer
# PHP, 344 bytes

```
<?=gzinflate(base64_decode("5VAxTsQwEOz9iu2uifIO6JA4iXovu2cbjPdk+2Tl96zjoLugFFQIRGfNjGdn5ug4MVTMgBEkEASkGaoTyBVDkMoECOcwj+YRSOKhwFuUqooZsuM7VXFYmnAwT5wcXnLjDyEAeR6NOX7rUL544jSoWs1q8taGhkeCu+fr+vYxqxrUeDTPX7LwagVFYMIyuQVb4v1Ej5NPNJgHPYCnfE3UYqz8yu5Fbvg28Ocev6yentRD72h95O646af0Xr2p6255+0p/eAcSO5iX5oTgxG5XUHJvBeq6W9plzP+wlpOUuafSbwRyhkmuio0f"));

```

Try it online!

# PHP, 405 bytes

```
<?=strtr("0fly.
106That wr8and 8and j8inside her.
23107,
How absurd57.
274623109,
Imagine that59.
2947,
27462310dog,
What a hog5dog.
2dog49,
2947,
27462310horse,
She died of course.",["There was an old lady who swallowed a ","I don't know why she swallowed that fly,
Perhaps she'll die.

","She swallowed the ","spider to catch the fly,
"," to catch the "," to swallow a ","spider,
",bird,"iggled ",cat]);

```

Try it online!
> 1 votes

# Answer
# Bubblegum, 255 bytes

```
0000000: e0 04 85 00   f7 5d 00 2a   1a 08 a7 55   8e 22 31 d2 │ à...÷].*..§U."1Ò
0000010: cb f7 30 fa   52 4d 88 81   61 e4 be 9d   c2 f0 0e f8 │ Ë÷0úRM..aä¾.Âð.ø
0000020: dc c9 de 24   63 c9 1f c7   f7 71 e4 ed   40 68 0e d2 │ ÜÉÞ$cÉ.Ç÷qäí@h.Ò
0000030: cd 76 d8 d9   0d 61 78 f7   40 cf 23 95   48 e9 be 27 │ ÍvØÙ.ax÷@Ï#.Hé¾'
0000040: aa 75 57 ff   51 9e 1f 1f   25 d8 93 4d   18 69 c9 01 │ ªuWÿQ...%Ø.M.iÉ.
0000050: 12 16 ec c1   ff e0 01 7e   fa ea 1e cc   84 d7 58 b8 │ ..ìÁÿà.~úê.Ì.×X¸
0000060: 47 d4 40 b4   ff c7 64 a9   2f 07 bf 7b   f4 25 74 94 │ GÔ@´ÿÇd©/.¿{ô%t.
0000070: af da 8a fc   0c 18 81 58   b8 3c 2e 97   c0 9d e8 27 │ ¯Ú.ü...X¸<..À.è'
0000080: 3e 02 8a d2   1b 7c 94 cc   cb f4 05 7c   c7 77 f3 75 │ >..Ò.|.ÌËô.|Çwóu
0000090: ea 7e 02 d6   3a 84 5c 4e   1f 88 e7 03   9a 1d 3f 13 │ ê~.Ö:.\N..ç...?.
00000a0: a6 9f 2e cf   be 77 16 be   f1 5f 01 52   cf 13 89 b3 │ ¦..Ï¾w.¾ñ_.RÏ..³
00000b0: f3 8a f7 90   18 08 50 99   27 f7 83 d2   a4 32 08 76 │ ó.÷...P.'÷.Ò¤2.v
00000c0: ef b4 99 6c   80 dd 1a 47   04 26 fe b1   02 b3 d4 e7 │ ï´.l.Ý.G.&þ±.³Ôç
00000d0: 3d 44 3a 64   64 46 39 77   35 61 6b 6c   7b 68 34 db │ =D:ddF9w5akl{h4Û
00000e0: 51 75 39 2e   bc 46 8e 96   d1 8a 4c 79   f4 7a 7b e0 │ Qu9.¼F..Ñ.Lyôz{à
00000f0: f5 44 85 eb   ef 68 d5 22   26 4a 2a ef   fc 60 00    │ õD.ëïhÕ"&J*ïü`.

```
> 1 votes

# Answer
# Python 2, ~~453 442 427~~ 387 bytes

* **@nore saved 11 bytes:**  Thanks a ton!!: pointed `£` used before was a double byte char!!
* saved 15 bytes: `swallow` shorthand
* **@nore saved 40 bytes!!!!!** THANKS A LOT!!!
* @Zachary T saved 1 byte: space between `in` and `"..."` removed
* Thanks to notepad++'s find and replace tool. ;)

```
r="%2(:0)That wr66j5 inside her(_1)How absurd+1({3)Imagine that+3(}4)What a hog+4(~4*3)}horse)She died of course."
for i in"}~3*1){!{~1*0)_!_~0*2):!:^2)$%!~She7ed the !%There was an old lady who7ed a !$Perhaps she'll die(\n!* to 3ch the !^I don't know why she7ed that !+ to7 a !(.\n!),\n!0spider!1bird!2fly!3cat!4dog!65 and !5iggled!7 swallow".split("!"):r=r.replace(i[0],i[1:])
print r

```

Try it online!
> 1 votes

# Answer
# Groovy, 475 bytes

```
b="swallowed"
a="There was an old lady who $b a"
c="I don't know why she $b that fly,\nperhaps she'll die."
d="She $b the"
e=" to catch the"
f=" to swallow a"
g="iggled"
h=" spider"
i=" fly"
j=" dog"
k=" cat"
l=" bird"
m="$d$h$e$i,"
n="$d$l$e$h,"
o="$d$k$e$l,"
print"""
$a$i.
$c

$a$h,
That wr$g and $g and j$g inside her.
$m
$c

$a$l,
How absurd$f$l.
$n
$m
$c

$a$k,
Imagine that$f$k.
$o
$n
$m
$c

$a$j,
What a hog$f$j
$d$j$e$k,
$o
$n
$m
$c

$a horse,
She died of course."""

```

Nothing too interesting, just a lot of string interpolation. Golfing tips on this one are welcome!
> 1 votes

# Answer
# PowerShell, 349 bytes = Script:9 + Archive:340

```
tar xOf t

```

Try it online!

The Powershell script to create the archive `t` (see TIO):

```
(
@'
There was an old lady who swallowed a fly.
I don't know why she swallowed that fly,
Perhaps she'll die.
......
There was an old lady who swallowed a horse,
She died of course.
'@
) | Set-Content f -Force
tar zcfo t f
Get-ChildItem f,t # output info about archive size

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 295 bytes

```
BinaryDeserialize@ByteArray@ToCharacterCode@"8C:xœåPANÃ0<ãWì—(ï€R‘8o³[ÛÅx+;••ðnÖqª6(NÄÍšÏÎÌþãáÅqb(˜#H H'† …	ŽaêÍÄÝoQŠ*&ÈŽïT£Ã±
;óÌÉá9W~çÞ˜ïÊgOœ:U«YIÞÚPñHp÷<-o³ªA{³ÿ’…+7cs¼Ÿèqð‰:ó¨ð/‰jŒ…_ØÈ_¾îñËêéI=ôŽÖGnŽ«~JoÕšî–·ô‡w ±yNNìz%·V ¦»¥Çük9I™[*ýF Gä¢Xÿ	Tÿ”\""

```

Try it online!

This solution is a 46-byte decompressor `BinaryDeserialize@ByteArray@ToCharacterCode@"..."` acting on a 248-byte array masquerading as an ASCII string. Transferring this string between different programs is a bit tricky. TIO, for instance, blows this solution up into 416 bytes using UTF-8 encoding instead of keeping the ASCII string. To get the minimal 295-byte solution, save the text in a variable `text` and run

```
BinaryWrite["ThereWasAnOldLady.wl", Join[
  ToCharacterCode["BinaryDeserialize@ByteArray@ToCharacterCode@\""],
  Normal[BinarySerialize[text, PerformanceGoal -> "Size"]] /. {34 -> Sequence[92, 34]},
  ToCharacterCode["\""]]]

```

then execute the generated file on the command-line with

```
wolframscript -print -f ThereWasAnOldLady.wl

```
> 1 votes

# Answer
# 05AB1E, ~~516~~ 408 chars

-108 chars by not restricting the allowed characters to CJK Unified Ideographs Extension B

```
""ÇŽáá-•Gαm•β₆BŽm&",.'
"‡""ÇŽáá-•Gαm•βbT„Aa‡.Ï

```

Try it online!

This exploits the fact that this is an old question that counts in chars.

# Version without using UTF-16 strings, 925 bytes

```
•*™w8?áZм<r¼Ë}ÈdEÄŸ€Kβ;’Ì÷`₆NËr;OÙнΛ¤øoE~ÝùÇ?}6Å±T÷Eā2²ïápK|¯Ð†˜CYîâÀJ¯Ð₅“λ˜'=\₃0ˆN‹BM©мe½Ì½ÜÙÈ?QXt”
v´qØú!þ3$òšpô/—èi_ð@tγµðB}¯S₄6´>ÝN¯ζlçæ‡¼¶§āj]\0þGwN₁<âX1oƵ[Òg³KÓ‹ì‚üÿ₃1E®Ìηʒ(ΔÃλËXŒlµV#₃ Î¤Ý´ö÷ε_%C+zÝ-C-†¬‘mö¹z∍³ǝq†€Tʒ„2žUÞ>Ï©ι‹ó≠ÿöì₆н—₃\мā9þ6jΩÛγ„€LÙÐ¾Ym9îîaü±µŒžÖ»Ÿæ×çîóú®ùŽÊ>Ô₄G÷5Λ‚sÙ₆=øHlãsPÏØ\¬»E†¯ÄÇŠP@¡ŠÁ*Ñ₁oƵ°eø¾Ù₂Îæ₂.Â(₅”uCDr‡₃OþR₃Æ-&ÑâÀ₄˜g¾þ;q‡8}5,z—H÷‹}Þjô&„HKFÈ≠ΘúĆ0¸aJ+bàGÈzÞÉY4w-/Ê‡α_Ù$!i±—þq9ǝ*SнǝθeBQÑK+}‰Ý‰—‡Ω¶Σx¢32DÓ†vª‰Í%иt5ž*|Îæ)³₄¡NýXн¦®ÇÃþ¸.¸ò8r¢›§e›Ì"P₆ƵāÑÖºjΣ~ï`
∞åŒwïìsÐº∊ā‰Š®#¸вP=jû∊ÕÇëäûм—sJTǝ—ƒв¼êι‘Ù†¨ΓõćIÎåš¢4û6é›a™ÌV½ƶ≠ÃÑlëðβ‰«˜p:™°½“°2ï$£äζgŸ
¯ΛÿĆ„…û≠Q³¹îèïuøÉ₁¦ÁÝl^¨{Ê}мÁñ₄<нΘï÷@ãr1ôÑÌнÕ´…+ÕûÒO}öNηÆßã‘ó÷ß0xå1_|£ÒζÜqzÚ¼W^ÕæÓt\[šIvε©lø‚Õ∊H∞OŒƵŒ›ö;»E¾ƶćĀ#8lràQ˜aç½>¬λÓ™¾²ópöη¼Ā-æĆ„Wp6m”^tøgOõΛ¦≠ÅúÑDβ=ʒRJζã₂4N,]ÄKåí•₆BŽm&",.'
"‡•vŽ²~³ÖĀw`]¬ê₂R∞v³ÿkØæ!Xh¤li£4ĆdCµ Aëp
UÎ‘±6ʒιéµÞ3Y>Ý{#r9›½, å<š*å$”Wµ->Mé₅åˆíÏV"£³§`%kIŽ²,‡èα²‚… ÙP§¢∞>r”∍(+Ā~∊³β¨ÔX3ÃðØ³ž˜ûтÇiúÉ,9ΩÍÌJöεš¢≠«¼“UPºi]¤z¥•bT„Aa‡.Ï

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~512~~ 493 bytes

-19 bytes thanks to ceilingcat

```
*s[]={"That wriggled and iggled and jiggled inside her.","How absurd to swallow a bird.","Imagine that to swallow a cat.","What a hog to swallow a dog.","fly","spider","bird","cat","dog","horse"};r(i,x){return i&&r(i-1,!printf("She swallowed the %s to catch the %s,\n",s[i+4],s[i+3],x&&puts(s[i-1])));}f(i){for(i=0;printf("There was an old lady who swallowed a %s.\n",s[i+4]),i<5&&puts("I don't know why she swallowed that fly,\nPerhaps she'll die.\n",r(i++,1)););puts("She died of course.");}

```

Try it online!
> 1 votes

# Answer
## Java 758 chars

Here is my Java effort ( 758 chars )

```
public class Poem{public static void main(String[] args){String s1="swallowed",st="There was an old lady who "+s1+" a |.",d1="Perhaps she'll die.",d2="She died ofcourse.",e="I don't know why she " + s1 + " that fly,\n";String[] a={ "fly","spider","bird","cat","dog","horse"};String[] q={ "","That wriggled and iggled and jiggled inside her.","How absurd |","Imagine that |","What a hog |",null};for(int i=0;i < a.length;i++){print(st.replace("|",a[i]));if(q[i]==null){print(d2);break;}if(!q[i].isEmpty()){               print((q[i].replace("|","to swallow a " + a[i])).trim());for(int j=i;j > 0;j--){print("She swallowed the " + a[j] + " to catch the " + a[j - 1] + ",");}}print(e + d1 + "\n");}}
static void print(String value){System.out.println(value);}}

```
> 0 votes

# Answer
# Java, 655 bytes

```
public class M{public static void main(String[]P){String S="swallowed",T="There was an old lady who "+S+" a |.",e="I don't know why she "+S+" that fly,\n";String[]a={"fly","spider","bird","cat","dog","horse"};String[]q={"","That wriggled and iggled and jiggled inside her.","How absurd |","Imagine that |","What a hog |",null};for(int i=0;i<a.length;i++){p(T.replace("|",a[i]));if(q[i]==null){p("She died of course.");break;}if(!q[i].isEmpty()){p((q[i].replace("|","to swallow a "+a[i])).trim());for(int j=i;j>0;j--){p("She swallowed the "+a[j]+" to catch the "+a[j-1]+",");}}p(e+"Perhaps she'll die.\n");}}static void p(String v){System.out.println(v);}}

```

This is a **golfed** version of this answer. There's over 100 bytes saved on minor things.
> 0 votes

# Answer
# Charcoal, 369 366 bytes

```
Ａ”↓0*)Ｂ⎚D³9;7Ｑ7∨-f¶_²χ⁶；↧l⁺I´”¦αＡ“V×q▶²▷O≕⦃0j↖▷(τ⎇⦄4ω\`j0Ｔ⁹ψＩ2b1züρÀ↑‹⁻ê£ＡＺ‹？ＤOR§1φ”¦βＡ⟦spider¦bird¦cat¦dog⟧¦λＡ,¶¦νＡ⟦”↶7⎇ＩＰＶpθθ⪪➙Ｓ²p⸿H⁸✂ν‖2↖²φ↘nτME⦄Ｂ↓ξlＦ⁵y”¦”↶7Nl@;⪫λ38Ｎ∕´≕⁺)³ nÀ‴⦃”¦”↶7←´<7ＹKＢYχnＺ-↖Ｕ⎇ι\HUθ%；⟧”¦”↶7∧§‴⟧O×φ¢\`*NQ¶G⁺$π‽ξat”⟧μＡ”↓/!Ｚm⪫⟧αÀ⁻Ｖε>⟲”¦σＡ”｜‽aＣ-⁴t;Z⌕”¦τＡ“Y∨↷ur1ＢＯ#ÿk»⁻υv‽⌊←zω↘^”¦η⁺αβＦ⁴«⁺⁺⁺α§λιν§μιＦ⮌…⁰ι«⁺⁺⁺⁺σ§λ⁺κ¹τ§λκν»⁺⁺⁺σ§λ⁰τβ»⁺αη

```

Try it online!

Link to the verbose version of the code.
> 0 votes

# Answer
# PowerShell, 512 bytes

```
[IO.StreamReader]::new(([IO.Compression.GZipStream]::new([IO.MemoryStream]::new(([Convert]::FromBase64String('H4sIAAAAAAAEAOVQQWoDMQy8L+wfdMsl5B3tLdBAz8pKsd26VrAdzP4+cm2SbNlDT6WlN6EZzYzmYDkyFEyAAcQTeKQZihVIBb2XwgQIJz/vxuEZSMImw3uQopQZkuUHWraYK3M7DnuOFs+pEjbeAznW83E4fMssnR1x3Fa6CpbojPEVCAQP41ufXUhKB1VWi5cvgbiLQRaYME/2c9cy/tA3RxdJNZ7UBI/pEqlm6YQOrwavwDL2rZdf+KXaVrMPNC5wU128qfjql1Mj3lP3uv56HyRGJV6rGoIVs2xD0dU2qBHvmVut/6c2KzFxj6aXBHKCSS663F0B')),0,249),[IO.Compression.CompressionMode]::Decompress))).ReadToEnd()

```

Try it online!

Credit to @Chirishman for their post.
> 0 votes

---
Tags: code-golf, kolmogorov-complexity
---


title: Find whether a number is happy or not?

text:
# Question
Title: Find whether a number is happy or not?
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). Given a number print whether it is happy or unhappy.

```
Sample Inputs
7
4
13

Sample Outputs
Happy
Unhappy
Happy

```

Note: Your program should not take more than 10 secs for any number below 1,000,000,000.

# Answer
> 8 votes
## Golfscript - 34 chars

```
~{0\`{48-.*+}/}9*1="UnhH"3/="appy"

```

Basically the same as this and these.

The reason for 9 iterations is described in these comments (this theoretically returns correct values up to about `10^10^10^974` (A001273)).

# Answer
> 11 votes
## Ruby, 77 characters

```
a=gets.to_i;a=eval"#{a}".gsub /./,'+\&**2'until a<5
puts a<2?:Happy: :Unhappy

```

# Answer
> 9 votes
## C - 115

```
char b[1<<30];a;main(n){for(scanf("%d",&n);b[n]^=1;n=a)for
(a=0;a+=n%10*(n%10),n/=10;);puts(n-1?"Unhappy":"Happy");}

```

This uses a 230-byte (1GB) array as a bitmap to keep track of which numbers have been encountered in the cycle. On Linux, this actually works, and efficiently so, provided memory overcommitting is enabled (which it usually is by default). With overcommitting, pages of the array are allocated and zeroed on demand.

Note that compiling this program on Linux uses a gigabyte of RAM.

# Answer
> 7 votes
## Haskell - 77

```
f 1="Happy"
f 4="Unhappy"
f n=f$sum[read[c]^2|c<-show n]
main=interact$f.read

```

# Answer
> 6 votes
### Golfscript, 49 43 41 40 39 chars

```
~{0\10base{.*+}/.4>}do(!"UnhH"3/="appy"

```

Every happy number converges to 1; every unhappy number converges to a cycle containing 4. Other than exploiting that fact, this is barely golfed at all.

(Thanks to Ventero, from whose Ruby solution I've nicked a trick and saved 6 chars).

# Answer
> 5 votes
## Python - 81 chars

```
n=input()
while n>4:n=sum((ord(c)-48)**2for c in`n`)
print("H","Unh")[n>1]+"appy"

```

Some inspiration taken from Ventero and Peter Taylor.

# Answer
> 5 votes
**eTeX, 153**

```
\let~\def~\E#1{\else{\fi\if1#1H\else Unh\fi appy}\end}~\r#1?{\ifnum#1<5
\E#1\fi~\s#1{0?}}~\s#1{+#1*#1\s}~~{\expandafter\r\the\numexpr}\message{~\noexpand

```

Called as `etex filename.tex 34*23 + 32/2 ?` (including the question mark at the end). Spaces in the expression don't matter.

EDIT: I got down to **123**, but now the output is dvi (if compiled with `etex`) or pdf (if compiled with `pdfetex`). Since TeX is a typesetting language, I guess that's fair.

```
\def~{\expandafter\r\the\numexpr}\def\r#1?{\ifnum#1<5 \if1#1H\else
Unh\fi appy\end\fi~\s#1{0?}}\def\s#1{+#1*#1\s}~\noexpand

```

# Answer
> 4 votes
## Javascript (~~94~~ ~~92~~ ~~87~~ 86)

```
do{n=0;for(i in a){n+=a[i]*a[i]|0}a=n+''}while(n>4);alert(['H','Unh'][n>1?1:0]+'appy')

```

Input is provided by setting a to the number desired.

Credits to mellamokb.

# Answer
> 4 votes
## Python (98, but too messed up not to share)

```
f=lambda n:eval({1:'"H"',4:'"Unh"'}.get(n,'f(sum(int(x)**2for x in`n`))'))
print f(input())+"appy"

```

Way, way too long to be competitive, but perhaps good for a laugh. It does "lazy" evaluation in Python. Really quite similar to the Haskell entry now that I think about it, just without any of the charm.

# Answer
> 4 votes
## dc - 47 chars

```
[Unh]?[[I~d*rd0<H+]dsHxd4<h]dshx72so1=oP[appy]p

```

Brief description:

`I~`: Get the quotient and remainder when dividing by 10.
`d*`: Square the remainder.
`0<H`: If the quotient is greater than 0, repeat recursively.
`+`: Sum the values when shrinking the recursive stack.

`4<h`: Repeat the sum-of-squares bit while the value is greater than 4.

# Answer
> 4 votes
## Befunge, 109

Returns correct values for 1\<=n\<=109-1.

```
v v              <   @,,,,,"Happy"<      >"yppahnU",,,,,,,@
>&>:25*%:*\25*/:#^_$+++++++++:1-!#^_:4-!#^_10g11p

```

# Answer
> 3 votes
# J (50)

```
'appy',~>('Unh';'H'){~=&1`$:@.(>&6)@(+/@:*:@:("."0)@":)

```

I'm sure a more competent J-er than I can make this even shorter. I'm a relative newb.

New and improved:

```
('Unhappy';'Happy'){~=&1`$:@.(>&6)@(+/@:*:@:("."0)@":)

```

Newer and even more improved, thanks to ɐɔıʇǝɥʇuʎs:

```
(Unhappy`Happy){~=&1`$:@.(>&6)@(+/@:*:@:("."0)@":)

```

# Answer
> 3 votes
# J, 56

```
'Happy'"_`('Unhappy'"_)`([:$:[:+/*:@:"."0@":)@.(1&<+4&<)

```

A verb rather than a standalone script since the question is ambiguous.

Usage:

```
   happy =: 'Happy'"_`('Unhappy'"_)`([:$:[:+/*:@:"."0@":)@.(1&<+4&<)
happy =: 'Happy'"_`('Unhappy'"_)`([:$:[:+/*:@:"."0@":)@.(1&<+4&<)
   happy"0 (7 4 13)
happy"0 (7 4 13)
Happy
Unhappy
Happy

```

# Answer
> 3 votes
## Scala, 145 chars

```
def d(n:Int):Int=if(n<10)n*n else d(n%10)+d(n/10)
def h(n:Int):Unit=n match{
case 1=>println("happy")
case 4=>println("unhappy")
case x=>h(d(x))}

```

# Answer
> 2 votes
# Python (91 characters)

```
a=lambda b:b-1and(b-4and a(sum(int(c)**2for c in`b`))or"Unh")or"H";print a(input())+"appy"

```

# Answer
> 2 votes
# Common Lisp 138

```
(format t"~Aappy~%"(do((i(read)(loop for c across(prin1-to-string i)sum(let((y(digit-char-p c)))(* y y)))))((< i 5)(if(= i 1)"H""Unh"))))

```

More readable:

```
(format t "~Aappy~%"
        (do
          ((i (read)
              (loop for c across (prin1-to-string i)
                    sum (let
                          ((y (digit-char-p c)))
                          (* y y)))))
          ((< i 5) (if (= i 1) "H" "Unh"))))

```

Would be shorter to just return "Happy" or "Unhappy" right from the `(do)`, but arguably that wouldn't count as a whole program

# Answer
> 2 votes
# K, 43

```
{{$[4=d:+/a*a:"I"$'$x;unhappy;d]}/x;`happy}

```

# Answer
> 2 votes
# Jelly, 17 bytes

```
D²SµÐLỊị“¢*X“<@Ḥ»

```

**Try it online!**

### How?

```
D²SµÐLỊị“¢*X“<@Ḥ» - Main link: n
   µÐL            - loop while the accumulated unique set of results change:
D                 -   cast to a decimal list
 ²                -   square (vectorises)
  S               -   sum
                  - (yields the ultimate result, e.g. n=89 yields 58 since it enters the
                  -  "unhappy circle" at 145, loops around to 58 which would yield 145.)
      Ị           - insignificant? (abs(v)<=1 - in this case, 1 for 1, 0 otherwise)
        “¢*X“<@Ḥ» - dictionary lookup of ["Happy", "Unhappy"] (the central “ makes a list)
       ị          - index into
                  - implicit print

```

# Answer
> 1 votes
# Perl 5 - 77 Bytes

```
{$n=$_*$_ for split//,$u{$n}=$n;exit warn$/.'un'[$n==1].'happy'if$u{$n};redo}

```

$n is the input value

# Answer
> 1 votes
# Perl 5, 62 + 1 (`-p`) = 63 bytes

```
$_=eval s/./+$&**2/gr while$_>1&&!$k{$_}++;$_=un x($_>1).happy

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 21 bytes

```
'ŽØs[SnOD5‹#}≠i„unì}™

```

Try it online or verify the first 100 test cases.

**Explanation:**

Each number will eventually result in either `1` or `4`, so we loop indefinitely, and stop as soon as the number is below 5.

```
'ŽØ                    '# Push string "happy"
   s                    # Swap to take the (implicit) input
    [       }           # Loop indefinitely
     S                  #  Convert the integer to a list of digits
      n                 #  Square each
       O                #  Take the sum
        D5‹#            #  If this sum is smaller than 5: stop the infinite loop
             ≠i    }    # If the result after the loop is NOT 1:
               „unì     #  Prepend string "un" to string "happy"
                    ™   # Convert the string to titlecase (and output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `'ŽØ` is `"happy"`.

# Answer
> 1 votes
# Python 2, 71 bytes

```
f=lambda n:n>4and f(sum(int(d)**2for d in`n`))or("H","Unh")[n>1]+"appy"

```

Try it online!

...or, for the same byte count:

```
f=lambda n:n>4and f(eval('**2+'.join(`n*10`)))or("H","Unh")[n>1]+"appy"

```

Try it online!

# Answer
> 0 votes
# C++ 135 , 2 Lines

```
#include<iostream>
int n,i,j;int main(){for(std::cin>>n;n>1;n=++j&999?n*n+i:0)for(i=0;n/10;n/=10)i+=n%10*(n%10);std::cout<<(n?"H":"Unh")<<"appy";}

```

This is a modified version of the one I did here:

https://stackoverflow.com/questions/3543811/code-golf-happy-primes/3545056#3545056

# Answer
> 0 votes
Yes, this challenge has three years; yes, it already has a winner answer; but since I was bored and done this for another challenge, thought I might put it up here. Surprise surprise, its long - and in...

# Java - ~~280~~ 264 bytes

```
import java.util.*;class H{public static void main(String[]a){int n=Integer.parseInt(new Scanner(System.in).nextLine()),t;while((t=h(n))/10!=0)n=t;System.out.print(t==1?"":"");}static int h(int n){if(n/10==0)return n*n;else return(int)Math.pow(n%10,2)+h(n/10);}}

```

Ungolfed:

```
import java.util.*;

class H {

    public static void main(String[] a) {
        int n = Integer.parseInt(new Scanner(System.in).nextLine()), t;
        while ((t = h(n)) / 10 != 0) {
            n = t;
        }
        System.out.print(t == 1 ? "" : "");
    }

    static int h(int n) {
        if (n / 10 == 0) {
            return n * n;
        } else {
            return (int) Math.pow(n % 10, 2) + h(n / 10);
        }
    }
}

```

# Answer
> 0 votes
# C# 94 bytes

```
int d(int n)=>n<10?n*n:(d(n%10)+d(n/10));string h(int n)=>n==1?"happy":n==4?"unhappy":h(d(n));

```

For any given number (as `int`), `h()` will return the correct value. You can try the code on .NetFiddle.

Kudos to user unknown for the original algorithm.

# Answer
> 0 votes
## Clojure, ~~107~~ 97 bytes

Update: Removed unnecessary `let` binding.

```
#(loop[v %](case v 1"Happy"4"Unhappy"(recur(apply +(for[i(for[c(str v)](-(int c)48))](* i i))))))

```

Original:

```
#(loop[v %](let[r(apply +(for[i(for[c(str v)](-(int c)48))](* i i)))](case r 1"Happy"4"Unhappy"(recur r))))

```

First time using a nested `for` :o

# Answer
> 0 votes
# R, ~~117~~ 91 bytes

-16 bytes thanks to Giuseppe

```
a=scan();while(!a%in%c(1,4))a=sum((a%/%10^(0:nchar(a))%%10)^2);`if`(a-1,'unhappy','happy')

```

# Answer
> 0 votes
# Julia 1.5 , 188 bytes (without indent)

```
f(s)=sum([parse(Int64,i)^2 for i in string(s)])
function g(s)
         a=[f(s)]
         while true;h=f(last(a))
             if h in a
                 println("unhappy")
                 break
             elseif h==1
                 println("Happy")
                 break
             end
             append!(a,h)
         end
      end

```

Try it online!

---
Tags: code-golf, decision-problem
---