title: Unlucky Numbers!

text:
# Question
Title: Unlucky Numbers!
## Things to know:

First, lucky numbers.

Lucky numbers are generated like so:

Take all the natural numbers:

```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20...

```

Then, remove each second number.

```
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39...

```

Now, `3` is safe.

Remove every 3rd number:

```
1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 59...

```

Now, `7` is safe.

Remove every 7th number.

Continue, and remove every `n`th number, where `n` is the first safe number after an elimination.

The final list of safe numbers is the lucky numbers.

---

The unlucky numbers is composed of separate lists of numbers, which are `[U1, U2, U3... Un]`.

`U1` is the first set of numbers removed from the lucky "candidates", so they are:

```
2, 4, 6, 8, 10, 12, 14, 16, 18, 20...

```

`U2` is the second set of numbers removed:

```
5, 11, 17, 23, 29, 35, 41, 47, 53, 59...

```

And so on and so forth (`U3` is the third list, `U4` is the fourth, etc.)

---

## Challenge:

Your task is, when given two inputs `m` and `n`, generate the `m`th number in the list `Un`.

## Example inputs and outputs:

```
(5, 2) -> 29
(10, 1) -> 20

```

## Specs:

* Your program must work for `m` up to `1e6`, and `n` up to `100`.
    + You are guaranteed that both `m` and `n` are positive integers.
    + If you're curious, `U(1e6, 100)` = `5,333,213,163`. (Thank you @pacholik!)
* Your program must compute that within 1 day on a reasonable modern computer.

This is , so shortest code in bytes wins!

*PS: It would be nice if someone came up with a general formula for generating these. If you do have a formula, please put it in your answer!*

# Answer
# CJam, 74 bytes

```
ri0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A0@{@:B:(_0#):D{D(_A=tD<BD>+}&@)@DU=-}h]1=

```

Try it online! *Will time out for larger cases, more on time constraints below.*

---

### Explanation:

Our program shamelessly borrows for aditsu's code to generate a list of *N* lucky numbers, replacing 1 with a 2 gives the increment in each phase of the sieve. The remaining code decrements on every element until a zero is found (by slicing and appending an un-decremented tail) and effectively counts the steps in each of *N* phases of the sieve at once.

```
ri                               e# read M
0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A  e# list steps (also becomes B)
0@                               e# arrange stack [B I M]
{                                e# while M
   @:B                           e#   get current B
   :(                            e#   decrement every element in B
   _0#):D                        e#   find first 0
   {                             e#   if there is a 0
      D(_A=t                     e#     reset that element in B
      D<BD>+                     e#     replace tail after 0
   }&                            e#   end if
   @)                            e#   increment I
   @DU=-                         e#   decrement M if N-th phase of sieve
}h                               e# end loop
]1=                              e# return I

```

---

### Timing:

If you absolutely must run the program in browser for larger numbers you can use this interpreter and allow the script to continue if prompted, but this maybe too slow to qualify. Using (*M*,*N*)=(100,100) takes ~247s. The programs iteration is relatively linear in terms of *M*, so computing (1e6,100) could take ~29 days.

Using the shell interpreter on a PC the program computes (100,100) in ~6s and computes (1e4,100) in ~463s. The program should be able to compute (1e6,100) in ~13-17hrs. In this case I'll assume the program qualifies.

*Note all times were rounded up in both measurements and calculations.*
> 1 votes

# Answer
# Python 3, 170

```
from itertools import*
def L(n,k=1):
 if n<2:yield from count(2+k,2)
 t=L(n-1);l=next(t)
 for i in t:
  n+=1
  if(n%l>0)==k:yield i
U=lambda m,n:sum(islice(L(n,0),m-1,m))

```

Function *L* generates the row of possible lucky numbers (if *k* is True) or *Un* (if False). Evaluated lazily (so I don't have to generate *n-1* infinite lists if I want *Un*).

Run function *U*.

## Speed

*U(1,000,000; 100)* takes about 1h 45min to run on my machine with PyPy. I suspect some four hours with CPython. (Yes, 4h 20min to be precise.)

If I used a list instead of generators, I might gain some speed, but I would need a list of greater size than Python allows me. And if it did, it would need dozens of gigabytes of RAM.

---

Yes, and *U(1,000,000; 100) = 5,333,213,163*.
> 7 votes

# Answer
# Perl, ~~87~~ ~~85~~ ~~82~~ 81 bytes

Includes +4 for `-pX`

Give input on STDIN as one line with n first (notice this is the reverse of the order suggested in the challenge). So to calculate `U(1000000, 100)`:

```
unlucky.pl <<< "100 1000000"

```

Algorithm based on aditsu's lucky numbers answer The time complexity is `O(n^2)` so it's rather fast for the required range. The `100, 1000000` case gives `5333213163` in 0.7 seconds. Due to the problems perl has with `do$0` based recursion it uses a lot of memory. Rewriting it as a function would make the memory use `O(n)` but is a number of bytes longer

`unlucky.pl`:

```
#!/usr/bin/perl -pX
$_=$a{$_}||=/\d+$/>--$_?2*$&+$^S:($_=$_.A.(do$0,$^S?0|$&+$&/~-$_:$&*$_-1),do$0)

```

This works as shown, but use literal `^S` to get the claimed score.

I am not aware of any earlier use of `$^S` in perlgolf.
> 7 votes

# Answer
## Haskell

## Not able to compute for n=1: ~~175~~ 160 bytes

When compiled, it took my computer 2h 35m to compute for an input of `(1000000,100)` using this:

```
n#s=y:(n#p)where y:p=drop(n-1)s
n%s=f n s$[]where f n s=(take(n-1)s++).f n(drop n s)
l 2=[1,3..]
l m=((l$m-1)!!(m-2))%(l$m-1)
m?n=(((l n)!!(n-1))#(l$n))!!(m-1)

```

I tried ridding the `where` modules, but they seem to affect the speed and I'm not sure why... But I think there is more pruning to be done here.

The method to use is `m?n` for querying the answer given an `m` and `n`.

## Ungolfed

```
everynth n xs = y:(everynth n ys) -- Takes every nth element from a list 'xs'
  where y:ys = drop (n-1) xs

skipeverynth n xs = f' n xs $ []  -- Removes every nth element from a list 'xs'
  where f' n xs = (take (n-1) xs ++) . f' n (drop n xs)

l 2 = [1,3..] -- The base case of the list of lucky numbers for 'n=2'
l m = skipeverynth ((l$m-1)!!(m-2)) (l$m-1) -- Recursively defining next case as being the last one with every 'ath' element skipped. Here, 'a' is the (m-1)th elemnent of the (l (m-1)) list.
ul m = everynth ((l m)!!(m-1)) (l$m) -- This is not used other than to compute the final, required unlucky number list. It picks out every 'ath' element.

ans m n = (ul n)!!(m-1) -- The function giving the answer.

```

I reckon it may be possible to combine the 'skipeverynth' and 'everynth' functions into a single function which returns a pair.

I used this kind person's code for skipping every nth element. I did it myself a few times, but it was always much more inefficient and I couldn't figure out why.

## Able to compute for all n: 170 bytes

This is basically the same, but a couple of `max` functions had to be thrown in to handle the special case of `n=1`.

```
n#s=y:(n#p)where y:p=drop(n-1)s
n%s=f n s$[]where f n s=(take(n-1)s++).f n(drop n s)
l 1=[1..]
l m=((l$m-1)!!(max 1$m-2))%(l$m-1)
m?n=(((l n)!!(max 1$n-1))#(l$n))!!(m-1)

```
> 3 votes

# Answer
## R 82 bytes

```
f<-function(m,n){a=1:2e8
i=1
while(i<n){a=c(0,a)[c(F,rep(T,i))]
i=i+1}
a[(n+1)*m]}

```

Usage

```
f(5,2)
Returns 29

```

This needs to have a large enough vector to start with so there are enough numbers left to return the value. The vector created is already about 800Mb and the function can handle upto m=1e4 and n=100 so still well short of the goal.

To create a large enough vector to calculate f(1e6,100) would take a starting vector of 1:2e10. Due to Rs data allocation procedures this creates a vector \>70Gb which can't be run on any computer I know although the code would run.

```
Error: cannot allocate vector of size 74.5 Gb

```

For reference f(1e4,100) runs in about in about 30 seconds. Based on this and a couple smaller tests f(1e6,100) would take about an hour.
> 2 votes

# Answer
## Racket 332 bytes

```
(λ(N m n)(let loop((l(filter odd?(range 1 N)))(i 1))(define x (list-ref l i))(if(= i (sub1 n))
(begin(set! l(for/list((j(length l))#:when(= 0(modulo(add1 j)x)))(list-ref l j)))(list-ref l(sub1 m)))
(begin(set! l(for/list((j(length l))#:unless(= 0(modulo(add1 j) x)))(list-ref l j)))(if(>= i(sub1 (length l)))l
(loop l(add1 i)))))))

```

Ungolfed version:

```
(define f
  (λ(N m n)
    (let loop ((l (filter odd? (range 1 N))) (i 1))
      (define x (list-ref l i))
      (if (= i (sub1 n))
          (begin (set! l (for/list ((j (length l))
                                   #:when (= 0 (modulo (add1 j) x)))
                           (list-ref l j)))
                 (list-ref l (sub1 m)))
          (begin (set! l (for/list ((j (length l))
                                   #:unless (= 0 (modulo (add1 j) x)))
                           (list-ref l j)))
                 (if (>= i (sub1 (length l)))
                     l
                     (loop l (add1 i))))))))

```

Testing:

```
(f 100 5 2)

```

Output:

```
29

```
> 1 votes

# Answer
## Clojure, 221 bytes

Mighty long but handles the case `(f 1)`. Without that special case it was 183 bytes. This was too much effort not to have it posted.

```
(defn f([n](if(< n 2)(take-nth 2(drop 2(range)))(f n 1(take-nth 2(rest(range))))))([n i c](if (< n 2)c(let[N(first(drop i c))F #((if(= 2 n)= >)(mod(inc %)N)0)](f(dec n)(inc i)(filter some?(map-indexed #(if(F %)%2)c)))))))

```

Sample outputs:

```
(pprint (map #(take 10 (f %)) (range 1 10)))
((2 4 6 8 10 12 14 16 18 20)
 (5 11 17 23 29 35 41 47 53 59)
 (19 39 61 81 103 123 145 165 187 207)
 (27 57 91 121 153 183 217 247 279 309)
 (45 97 147 199 253 301 351 403 453 507)
 (55 117 181 243 315 379 441 505 571 633)
 (85 177 277 369 471 567 663 757 853 949)
 (109 225 345 465 589 705 829 945 1063 1185)
 (139 295 447 603 765 913 1075 1227 1377 1537))

```

1000000 100 case was calculated in about 4.7 hours, at least it didn't crash.

```
java -jar target\stackoverflow-0.0.1-SNAPSHOT-standalone.jar 1000000 100
5333213163
"Elapsed time: 1.7227805535565E7 msecs"

```
> 1 votes

---
Tags: code-golf, math, sequence
---


title: Count the characters - bit by bit!

text:
# Question
Title: Count the characters - bit by bit!
**The simple part:** Given an input string containing only printable ASCII-characters (space - tilde), count the number of occurrences of each character and return the result on any convenient format. The result for a string `a%hda7a` should be something like: `a:3, %:1, h:1, 7:1, d:1`. Sorting is unnecessary, the delimiters and formats are optional but it must be easily understood which number corresponds to which character. You shall not include characters that are not in the input string (`a:3, b:0, c:0, d:1, ...` is not OK).

**The real challenge:**

Convert every character in your code to an 8-bit binary number (or 16-bit if you're using UTF-16 or similar), and enumerate every character starting at `0`.

For every character (`i` is the enumerator), the `i%7`-bit1 **must** be `1`. The bits are numbered from the right. All other bits can be whatever you want.

Let's use the following code as an example:

```
[f]-xif)#f

```

Converting this to binary we get the array below. The first number (representing `[` has a `1` in the 0'th position, so that one is OK. The second number (representing `f` has a `1` in the 1'st position, so that one is OK too. Continue like this, and you'll see that the code above is valid.

```
C  76543210  Bit number
-  --------  ----------
[  0101101***1***  0   - OK
f  011001***1***0  1   - OK
]  01011***1***01  2   - OK
-  0010***1***101  3   - OK
x  011***1***1000  4   - OK
i  01***1***01001  5   - OK
f  0***1***100110  6   - OK
)  0010100***1***  0   - OK
#  001000***1***1  1   - OK
f  01100***1***10  2   - OK

```

If we change the code into: `]f[-xif)#f` we'll get the following start of the sequence:

```
C  76543210  Bit number
-  --------  ----------
]  01011101  0   <- OK
f  01100110  1   <- OK
[  01011011  2   <- Not OK
-  00101101  3   <- OK

```

As we see, the third character `[` doesn't have a `1` in the 2nd position (zero-indexed), and this code is therefore not valid.

**Test cases:**

```
Input:
This is a string containing some symbols: ".#!".#&/#

Output:
   !  "  #  &  /  :  T  a  b  c  e  g  h  i  l  m  n  o  r  s  t  y  .
7  1  2  3  1  1  1  1  2  1  1  1  2  1  5  1  2  4  3  1  6  2  1  2

```

Any reasonable output format is OK (whatever is most convenient to you). You could for instance have: `:7, !:1, ":2, #:3, &:1, /:1, T:1, a:2 ...` or `[ ,7][!,1][",2][#,3][&,1]...`. The output is on any standard way (return from function, printed to STDOUT etc.)

1`i` modulus `7`.

---

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

# Answer
> 6 votes
## Pyke, ~~1~~ 6 bytes

```
1cn;1c

```

Try it here!

```
1c     - chunk(size=1, input)
  n;1  - noop.
     c - count(^)

```

Half of this code is just no-ops...

```
00110001 - 1
01100011 - c
01101110 - n
00111011 - ;
00110001 - 1
01100011 - c

```

# Answer
> 6 votes
## Pyth, ~~12~~ ~~8~~ 7 bytes

-1 byte thanks to @Loovjo

```
m+d/Qd{
      { # remove all duplicated elements from the (implicit) input
m       # map each element (d) of the parameter (the set from previous operation)
   /Qd  # count the occurrences of d in Q
 +d     # concatenate with d

```

binary representation

```
0110110**1** m
001010**1**1 +
01100**1**00 d
0010**1**111 /
010**1**0001 Q
01**1**00100 d
0**1**111011 {

```

Try here

# Answer
> 4 votes
# Befunge-93, 150 bytes

```
={<{p+}3/}*77\%*7{7:\+{}{1g}+3/*77\%*7{7:}=:_{}{}={}{}{v#{}{}`x1:~
}-}=*}{2*}97}:<$}={$_v#}!:-*84g+3/*77\%*7{7:}=:}:}+}1{}<_{@#
}{}{}={}{}{}={^.},\={<

```

Try it online!

I started by writing this as a regular Befunge program, which I golfed as much as possible. I then added padding to make sure the various characters in the program only appeared in permitted positions. This padding relied on the fact that unsupported commands are ignored in Befunge-93, so I just needed a sequence of unused characters whose bits aligned with the positions required (the sequence I used was `={}{}{}`).

The complicated bit was that the various branches between lines needed to line up correctly (e.g. the `v` arrow in one line, would need to line up with the `<` arrow below it). This was further complicated by the fact that the bridge command (`#`) could not be separated from its adjacent branching arrow. Initially I tried generating the padding programatically, but in the end it was mostly a manual process.

Because of the size of the program I'm not going to list the full character analysis, but this is a sample from the beginning and the end:

```
= 00111101 0
{ 01111011 1
< 00111100 2
{ 01111011 3
p 01110000 4
+ 00101011 5
} 01111101 6
3 00110011 0
/ 00101111 1
...
{ 01111011 1
^ 01011110 2
. 00101110 3
} 01111101 4
, 00101100 5
\ 01011100 6
= 00111101 0
{ 01111011 1
< 00111100 2

```

The line breaks are treated as a newline characters, so will either be in position 1 or 3.

# Answer
> 3 votes
## MATL, 17 bytes

```
u"G91x@=zD91x@uRD

```

Displays the count, then the corresponding character, all newline-separated. Biggest difficulty is the `@` which is `0b01000000`; I hope I can find a way to make do without it.

Try it online!

Explanation:

```
u"  % Implicit input. Take (u)nique characters and loop (") over them.
G   % Take the input a(G)ain
91x % Filler: push 91, delete immediately.
@   % Push current character of loop
=   % Check for equality with earlier G
z   % Count number of equal characters
D   % Display
91x % More filler!
@   % Get loop character again
uR  % Filler: two NOPs for the single-character @
D   % Display. Implicitly end loop.

```

### MATL, 15 bytes (questionable output)

If just leaving two row vectors on the stack is allowed (function-like behaviour as per this Meta post), we can get down to

```
u"G91x@=zv]v!Gu

```

But here, the output is not quite as neatly ordered.

# Answer
> 1 votes
# CJam, 14 bytes

```
q__|_ @sfe=]zp

```

Try it here.

The space before the `@` and the `s` after it are filler characters inserted to make the ASCII codes fit the required pattern: the space does nothing, and the `s` just converts a string into a string. Other than that, this is a pretty simple and straightforward implementation of the challenge task:

```
q_               "read the input and make a copy of it";
  _|             "collapse repeated characters in the copy";
    _            "save a copy of the collapsed string";
      @          "pull the original input string to the top of the stack";
       s         "(does nothing here)";
        fe=      "for each character in the collapsed string, count the ...";
                 "... number of times it occurs in the original string";
           ]z    "pair up the counts with the saved copy of the collapsed string";
             p   "print the string representation of the result";

```

For the input `foobar123`, this code outputs `[['f 1] ['o 2] ['b 1] ['a 1] ['r 1] ['1 2] ['2 2] ['3 1]]`. If simply printing the counts on one line and the corresponding characters on another, as in:

```
[1 2 1 1 1 2 2 1]
fobar123

```

is considered an acceptable output format, then the `]z` may be omitted to save two bytes, for a total of **12 bytes**. Yes, the shortened code will still pass the bit pattern requirement.

Ps. I also wrote a simple source code checker for this challenge. Given a line of code as input, it will first echo that line and then print the same line with each character replaced by its (*n* % 7)-th ASCII bit. If the second line is all ones, the input is valid.

# Answer
> 1 votes
# Jelly, 6 bytes in Jelly's codepage

```
ṢZṢṀŒr

```

Try it online!

This is a function that returns a list of (character, count) pairs. (Jelly represents such lists as text, e.g. if they're sent to standard output, by concatenating the elements, which is why you have to treat this as a function rather than a complete program. (Here's the same program with some code appended to call the function and then print the internal structure to standard output, proving that the output's in an unambiguous format.)

Binary representation and explanation:

```
  76543210

Ṣ 1011011**1**   Sort the characters of the input
Z 010110**1**0   Transpose the list (it's 1D, so this effectively wraps it in a list)
Ṣ 10110**1**11   Sort the list (a no-op, as it has only one element)
Ṁ 1100**1**000   Take the largest (i.e. only) element
Œ 000**1**0011   First byte of a two-byte command
r 01**1**10010   Run-length encode

```

It can be seen that the second, third, and fourth characters cancel each other out and are only there to maintain the bit pattern we need. `Œr` is just too convenient, though, and padding the program so that we can use it probably gives us a shorter program than trying to solve the problem without the builtin would.

---
Tags: code-golf, restricted-source, parsing, base-conversion
---


title: A Square of Squares

text:
# Question
Title: A Square of Squares
Given two input integers, `a >= 4` and `b >= 2`, output an ASCII square of size `a x a`. The twist is the square must be constructed of `b` `3 x 3` squares formed like the following:

```
###
# #
###

```

You can use any ASCII printable character (except whitespace) to construct the smaller squares. I'm using `#` for visibility and consistency.

The first `b` square is always placed in the upper-left, and the remaining `b` squares must be as evenly spaced as possible, going clockwise, around the larger square. The overall `a x a` square size is calculated in characters based on the center of the `b` squares.

Here's an example for `a=7` and `b=3`. Note the numbers around the outside are not part of the output, just used to illustrate the construction.

```
   1234567
  ###
1 # #       1
2 ###   ### 2
3       # # 3
4       ### 4
5           5
6   ###     6
7   # #     7
    ###
   1234567

```

The first `b` square is placed in the upper-left corner. In the remaining possible areas on the perimeter of `a x a`, we need to place two more `b` squares. Note how the smaller squares are staggered -- how they're spaced as evenly as possible around the larger square. If a potential `b` square could be in one of two spaces, your code can pick either and does not need to be deterministic.

Here's another diagram explaining the spacing. I've drawn the `a` square with `-+|` and marked the center of the smaller `b` squares with `*`. If we count clockwise around the outside of the `a` square, we have 7 characters between the first and second centers `-----+|`, 7 between the second and third `|||+---`, and again 7 between the third and first `-+|||||`. This lines up mathematically as well, since we have `24` total characters making up the `a` square, minus `3` for the center of the `b` squares, must mean we have `7` characters between the centers. And, since the upper-left `b` square is fixed, this is the most evenly spaced arrangement possible.

```
   1234567
  ###
1 #*-----+  1
2 #|#   #|# 2
3  |    #*# 3
4  |    #|# 4
5  |     |  5
6  |###  |  6
7  +-*---+  7
    ###
   1234567

```

### Input

* A two integers in any convenient format, `a >= 4` and `b >= 2`.
* You can take the input in either order -- your choice.
* The input is guaranteed to be such that no `b` squares will overlap.

### Output

The resulting ASCII art representation of the squares.

### Rules

* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

(note these are just examples, and depending upon how your code rounds the placement you may have slightly different output)

```
a=4, b=4
######
# ## #
######
######
# ## #
######

a=4, b=2
###
# #
###
   ###
   # #
   ###

a=7, b=4
###   ###
# #   # #
###   ###

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

a=5, b=3
###
# #
### ###
    # #
 ######
 # #
 ###

a=7, b=3
###
# #
###   ###
      # #
      ###

  ###
  # #
  ###

a=7, b=5
###  ###
# #  # #
###  ###

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

```

# Answer
> 3 votes
# Befunge, ~~240~~ 232 bytes

```
< vp62:&p01*4p00:-1&
-1<v3!-2\*g04!:::p04p03-\g00:%g00\/g00:/g62*g01\1:
p:|>0g*+\1-!00g*+2+\::1-!40g*\3-!30g*+\2-!00g*+9+
# >00g3+:00pv
g00p05-\g00:<v+g06%3:\!!-4::-1p07\<90p06-\g00:<
$55+,1-:!#@_^>\3/50g+7+g2%*70g+\:#^_$!3g,>1-:#^_

```

Try it online!

**Explanation**

There are two parts to this. The first part is mostly handled by the loop on lines 2 and 3, which calculates the positions of each block by dividing the route around the main square (of length `(a-1)*n4`) into *b* segments. For each division, *d*, in that length, we determine the *x* and *y* coordinates with:

```
side = d/(a-1)    // which side of the square (0 = top, 1 = right, 2 = bottom, 3 = left)
off  = d%(a-1)    // the offset along that side, in a clockwise direction
roff = a-1-off    // the reverse of that offset

x = (side==0)*off + (side==2)*roff + (side==1)*(a-1)
y = (side==1)*off + (side==3)*roff + (side==2)*(a-1)

```

i.e. depending on which side of the square we're on, the coordinate value will either be the offset along that side, the reverse offset, the width of the square, or zero. We use those coordinates to write a 1 into the lower half of the Befunge playfield to mark the spot for later output.

The second part, writing out the final pattern of squares, is handled by the triple loop on lines 5 and 6. We're looping over the y and x coordinates, and then for each point, we need to check if we've marked a spot in any of the surrounding 8 locations. This is achieved with a simple loop over a range of 9, basically summing the values it encounters in the playfield. In Python it would look something like this:

```
total = sum(playfield[y+i/3][x+i%3] * (i != 4) for i in range(9))

```

The multiplication by `i != 4` is so that we exclude the centre point in the range. If this total is greater than 0 we need to output a `#`, otherwise we output a space. To avoid any branching, we simply use `!total` as an index into a character "table" (the  at the start of line 3) to determine the character to output.

# Answer
> 2 votes
## C, ~~350~~ ~~302~~ 253

```
i,j,x,y,a,b,c;main(){scanf("%d%d",&a,&b);a+=3;char*s,o[a*a];for(;c<a;)sprintf(o+c++*a,"%*s\n",a-1,"");for(;i<b;){x=y=0;for(j=(a-4)*i++*4/b;j--;)y>0&!x?y--:y>a-5?x--:x>a-5?y++:x++;s=o+y*a+x;s[2]=s[1]=*s|=3;s+=a;s[2]=*s|=3;s+=a;s[2]=s[1]=*s|=3;}puts(o);}

```

Ungolfed:

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i,j,x,y,a,b,c;
main(int n, char** v) {
    a = atoi(v[1])+3;
    b = atoi(v[2]);
    char o[a*a-a], *s;
    for (; c < a-1; c++) {
        sprintf(o+c*a, "%*s\n",a-1," ");
    }
    for (; i < b; i++) {
        x=y=1;
        for(j=(a-4)*i*4/b;j--;){ // Set the number of steps from 1,1
            if(y>1&x<2) y--; // We are on the left wall
            else if(y>a-4) x--; // We are on the bottom
            else if(x>a-4) y++; // We are on the right wall
            else x++; // We are on the top
        }
        s = o+(y-1)*a+x-1; // Find the output position
        bcopy("#x#",s,3);
        s+=a;
        bcopy("# #",s,3);
        s+=a;
        bcopy("#y#",s,3);
    }
    printf("%s\n", o);
}

```

This compiles with gcc under linux. Windows might substitute `<windows.h>` for the `<stdlib.h>` and `<stdio.h>` includes.

**Explanation**

We initialize the output string to an array of newline-terminated rows. `sprintf` takes care of null-terminating the string. We descend into a nested group of ternary operators to determine the wall. We then write out the square. We start each square counting from (1,1). This is less efficient but saves a few bytes over the step method. It also avoids rounding errors in integer division.

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


title: Activate the auto destruct sequence

text:
# Question
Title: Activate the auto destruct sequence
`This is a code golf. The smallest amount of bytes wins! :)`

# What you need to do

You're on Deep Space Nine, a Cardassian outpost taken over by the Federation, in the year 2374. The Borg, a superior race, have collapsed your shields and assimilated half of your crew. However, you have important classified information on your hands that you can't let anyone see at all. **Activate the auto-destruct sequence.**

### What you're actually doing

Take as input an integer value, which will set the exact auto destruct time in seconds. Once the user has passed the value, have a countdown ensue. Countdown backwards by one second each and print each number. At the point it reaches zero, make the program crash.

### Rules

* You may use STDIN, a parameter, or any other standard input format.
* You must put each number on a new line.
* You may or may not have an extra delay of one second at the beginning and end.

I was looking at Shortest auto-destructive loop, so if you want to use something from that, feel free, but this isn't really a duplicate of that. You can also wait one sec at the start, but once again, I'd prefer if you don't do this:

**Note: Everything in parentheses is ignored.**

```
(input is 10)
(wait 1 sec)
10
(1 sec)
9
(1 sec)
8
(1 sec)
(..etc..)
0
(crash)

```

*And you do this*:

```
(input is 10)
10
(1 sec)
9
(1 sec)
8
(1 sec)
(..etc..)
0
(crash)

```

# Examples

If you don't have stdin but you can have a parameter inputted:

```
(grab the number from the parameter)
(once the number is loaded in, 10 in this case, print it like so:)
10
(wait one second)
9
(wait one second)
8
(wait one second)
7
(wait one second)
6
(wait one second)
5
(wait one second)
4
(wait one second)
3
(wait one second)
2
(wait one second)
1
(wait one second)
0
(either wait one second then crash, or crash instantly)

```

If you have a form of `stdin`:

```
(allow the user to enter a number, there should be no greeting message)
(once the number is entered, 10 in this case, print it like so:)
10
(wait one second)
9
(wait one second)
8
(wait one second)
7
(wait one second)
6
(wait one second)
5
(wait one second)
4
(wait one second)
3
(wait one second)
2
(wait one second)
1
(wait one second)
0
(either wait one second then crash, or crash instantly)

```

***Have fun!***

# Answer
## R, 46 bytes

```
for(i in scan():0){cat(i,"\n");Sys.sleep(i/i)}

```

Crashes after printing `0` because the sleep function is called using `0/0` which returns `NaN` in R:

```
Error in Sys.sleep(time) : invalid 'time' value

```
> 5 votes

# Answer
# Python 2, 51 bytes

```
import time
def f(i):print i;time.sleep(i/i);f(i-1)

```

Recursive function that takes in integer then counts down until the integer is 0 at which point it explodes with a DivideByZero exception.
> 1 votes

# Answer
# C, 87 bytes

```
#import<windows.h>
main(i){for(scanf("%d",&i);i--;){printf("%d\n",i);Sleep(1000*i/i);}}

```

Death by division by zero.
> 1 votes

# Answer
## Batch, 67 bytes

```
@echo off
for /l %%i in (%1,-1,0)do echo %%i&timeout/t>nul 1
if

```

Note: the trailing newline is significant; this causes the command processor to choke on the `if` statement. The odd placement of the `>nul` is to save a byte as `1>nul` would eat the `1` parameter to `timeout/t`.
> 0 votes

---
Tags: code-golf, animation
---


title: Substring Sum Set

text:
# Question
Title: Substring Sum Set
### Introduction

Let's observe this array: `[3, 2, 4, 1, 1, 5, 1, 2]`.

Each element displays the length of the substring which must be summed up. Let's take a look at the first element of the above array:

```
[3, 2, 4, 1, 1, 5, 1, 2]
 ^

```

The element at the first index is **3**, so we now take a substring of length three with the same index as the starting position:

```
[3, 2, 4]

```

When summed up, this results into **9**, so the first element of the **substring sum set** is `9`.

We do this for all the elements in the array:

```
3 -> [3, 2, 4]
2 -> [2, 4]
4 -> [4, 1, 1, 5]
1 -> [1]
1 -> [1]
5 -> [5, 1, 2]
1 -> [1]
2 -> [2]

```

You can see that the number **5** is a bit of a weird case. That number exceeds the length of the array:

```
[3, 2, 4, 1, 1, 5, 1, 2]
                ^  ^  ^  ^  ^

```

We'll ignore everything that exceeds the array, so we just use `[5, 1, 2]`.

The last step is to sum everything up:

```
[3, 2, 4]     -> 9
[2, 4]        -> 6
[4, 1, 1, 5]  -> 11
[1]           -> 1
[1]           -> 1
[5, 1, 2]     -> 8
[1]           -> 1
[2]           -> 2

```

And that is the array that needs to be outputted:

```
[9, 6, 11, 1, 1, 8, 1, 2]

```

### The Task

Given an non-empty array with positive (non-zero) integers, output the **substring sum set**. This is , so the submission with the smallest number of bytes wins!

### Test cases

```
[1, 2, 3, 4, 5] -> [1, 5, 12, 9, 5]
[3, 3, 3, 3, 3, 3, 3, 3] -> [9, 9, 9, 9, 9, 9, 6, 3]
[5, 1, 2, 4, 1] -> [13, 1, 6, 5, 1]
[1] -> [1]

```

# Answer
> 15 votes
# Jelly, 6 bytes

```
ṫJḣ"ḅ1

```

Try it online! or verify all test cases.

### How it works

```
ṫJḣ"ḅ1  Main link. Argument: A (array)

 J      Index; yield the 1-based indices of A.
ṫ       Tail; map k to the postfix of A that begins with the k-th element.
  ḣ"    Vectorized head; for each k in A, truncate the corr. postfix to length k.
    ḅ1  Convert the resulting slices from base 1 to integer.

```

# Answer
> 11 votes
# Python, 40 bytes

```
f=lambda x:x and[sum(x[:x[0]])]+f(x[1:])

```

Test it on Ideone.

# Answer
> 11 votes
# Excel, 21 bytes

`=SUM(OFFSET(A1,,,A1))`

Open a new spreadsheet, put the test values in column A. Enter the formula in B1 and double click the cell handle to ride the range.

# Answer
> 7 votes
## Python 3, 47 bytes

```
lambda X:[sum(X[i:i+k])for i,k in enumerate(X)]

```

Pretty straightforward implementation. Python's default behavior for slices that go past the end of the list was *very* convenient here.

# Answer
> 5 votes
# Haskell, ~~34~~, 33 bytes

```
f l@(x:y)=sum(take x l):f y
f x=x

```

One byte saved by nimi.

# Answer
> 4 votes
# JavaScript ES6, 50 bytes

```
a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))

```

Pretty self-explanatory. It `map`s over each element in the array, getting the `slice` from that `i`ndex through the index plus that `e`lement's value, and `reduce`ing by adding.

```
f=
  a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))

;[
  [3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]
].forEach(function(test){
  document.getElementById('p').textContent += test + ' => ' + f(test) + '\n';
});
```

```
<pre id="p"></pre>
```

# Answer
> 4 votes
# J, 11 bytes

```
+/@{."_1]\.

```

### Usage

```
   f =: +/@{."_1]\.
   f 3 2 4 1 1 5 1 2
9 6 11 1 1 8 1 2
   f 1 2 3 4 5
1 5 12 9 5

```

### Explanation

```
+/@{."_1]\.  Input: A
        ]\.  Get each suffix of A from longest to shortest
   {."_1     For each value in A, take that many values from its corresponding suffix
+/@          Sum that group of values taken from that suffix
             Return the sums

```

# Answer
> 4 votes
# JavaScript (ES6), 45

`reduce` beaten again!

```
a=>a.map((v,i)=>eval(a.slice(i,v+i).join`+`))

```

```
F=
a=>a.map((v,i)=>eval(a.slice(i,v+i).join`+`))

;[[3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]].forEach(t=>console.log(t+' -> '+F(t)))
```

# Answer
> 3 votes
# Mathematica ~~60~~ 55 bytes

```
Tr@Take[#,UpTo@#&@@#]&/@Drop[#,t-1]~Table~{t,Length@#}&

```

eg

```
f = %; f /@ {{1, 2, 3, 4, 5}, {3, 3, 3, 3, 3, 3, 3, 3}, {5, 1, 2, 4, 1}, {1}}

(*    {{1, 5, 12, 9, 5}, {9, 9, 9, 9, 9, 9, 6, 3}, {13, 1, 6, 5, 1}, {1}}    *)

```

Thanks @MartinEnder for shaving off 5 bytes :)

# Answer
> 3 votes
## Retina, 38 bytes

Byte count assumes ISO 8859-1 encoding.

```
\d+
$*
M!&`\b1(1)*(?<-1>,1+)*
M%`1
¶
,

```

Input and output are comma-separated lists.

Try it online! (The first line enables a linefeed-separated test suite.)

# Answer
> 3 votes
## 05AB1E, ~~11~~ 8 bytes

```
[D¬£Oˆ¦Ž

```

**Explanation**

```
[         # infinite loop
 D        # duplicate current list
  ¬       # get head of list
   £      # get that many elements from list
    O     # sum
     ˆ    # add to global array
      ¦   # remove first element of list
       Ž  # break if stack is empty
          # implicitly push and print global array

```

Try it online

# Answer
> 2 votes
# Pyth, 8 bytes

```
.es:Qk+b

```

Test suite.

Translation of El's answer in Python.

# Answer
> 2 votes
# Erlang, 69 bytes

```
f(A)->put(1,1),L=lists,[L:sum(L:sublist(A,put(1,get(1)+1),X))||X<-A].

```

Erlang's higher-order functions for lists do not receive the index of the current element. This uses the process dictionary to set the index of the current element.

# Answer
> 2 votes
## Pyke, ~~12~~ 7 bytes

```
FKo>i<s

```

Try it here!

```
        - o = 0
F       - for i in input:
  o     -    o+=1
   >    -    input[o:]
    i<  -   ^[:i]
      s -  sum(^)

```

# Answer
> 2 votes
# VBA, 160 bytes

```
Function e(g())
Dim h()
k=LBound(g)
l=UBound(g)
ReDim h(k To l)
On Error Resume Next
For i=k To l
For j=i To i+g(i)-1
h(i)=h(i)+g(j)
Next
Next
e=h
End Function

```

# Answer
> 2 votes
# Matricks, 25 bytes

Yay, finally a challenge I don't need new features for!

```
md{z:l-g:c;+c;q:c;};:1:l;

```

Run with: `python matricks.py substring.txt [[<input>]] 0`

Explanation:

```
m                  :1:l;   #loop over entire input
                           #set each value to...
 d{               }        #the sum of...
   z:l-g:c:+c;q:c;         #the input cropped to
                           #the length of the value in the cell

```

# Answer
> 2 votes
# Pyth, 6 bytes

```
ms<~tQ

```

Test suite

This is a different solution from any others so far. It loops over the input, slicing an summing the initial values, then removing the first element of the stored input, and repeat.

Explanation:

```
ms<~tQ
ms<~tQdQ    Implicit variable introduction
            Implicit: Q = eval(input())
m      Q    Map d over the input, Q
  <  Qd     Take the first d elements of Q
 s          Sum them
   ~tQ      Afterwards, set Q to the tail of Q, removing the first element.

```

# Answer
> 1 votes
# MATL, ~~17~~ ~~14~~ 13 bytes

```
fGy+!-R0<G*!s

```

### Explanation

Try it online! Or verify all test cases (code modified to handle several inputs).

```
f     % Take input implicitly. Indices of nonzero elements: this gives [1 2 ... n]
      % where n is input size
G     % Push input again
y     % Push a copy of [1 2 ... n]
+     % Add. Gives [a+1 b+2...] where [a b...] is the input
!     % Transpose into a column vector
-     % Subtraction with broadcast. Gives 2D array
R     % Keep upper triangular part, making the rest of entries 0
0<    % True for negative entries. Each row corresponds to a substring sum.
      % For each row, this gives true for the entries of the input that make up
      % that substring sum. Each row is thus a mask to select entries of the input
G     % Push input again
*     % Multiply with broadcast. This multiplies the input times each row
!s    % Sum of each row. Implicitly display

```

# Answer
> 1 votes
## Javascript (using External Library) (66 bytes)

```
n=>_.From(n).Select((v,i)=>_.From(n).Slice(i,i+v).Sum()).ToArray()

```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: \_.From is loading the input array into the library, which is basically LINQ for js. Then each item in the array is mapped according to the following predicate: Take the input, and slice it from current item index and take that index plus the current item's value. Then Sum up that subsequence. Convert the result to a native JS array and return it

# Answer
> 1 votes
## F#, ~~84~~ 82 bytes

```
let f(A:int[])=[for i in 0..A.Length-1->Seq.skip i A|>Seq.truncate A.[i]|>Seq.sum]

```

# Answer
> 1 votes
# Julia, 39 bytes

```
!x=x!=[]?[take(x,x[])|>sum;!x[2:end]]:x

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6) - 79 Bytes

A recursive solution that does not use any of the Array methods:

```
f=([a,...t],n)=>a&&n?a+f(t,n-1):0;g=([a,...t],r=[])=>a?g(t,[...r,a+f(t,a-1)]):r

```

Testing:

```
f=([a,...t],n)=>a&&n?a+f(t,n-1):0;
g=([a,...t],r=[])=>a?g(t,[...r,a+f(t,a-1)]):r;

[
  [3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]
].forEach(a=>console.log(''+g(a)));
```

# Answer
> 1 votes
## C#, 89 bytes

```
int[]s(List<int>a)=>a.Select((n,i)=>a.GetRange(i,Math.Min(n,a.Count-i)).Sum()).ToArray();

```

**pretty straight forward**

improvement ideas appreciated

# Answer
> 1 votes
# Brachylog, 27 bytes

```
.v|h~l(A:Tc?;A?)b:0&~b.h~+A

```

Try it online! or verify all test cases.

### Explanation

```
  .v           Input = Output = []
|            Or
  h~l          A is a list, its length is the value of the first element of the Input
  (
    A:Tc?        The concatenation of A with another list T results in the Input
  ;            Or
    A?           A = Input
  )
  b:0&         Call recursively on Input minus the first element
  ~b.          Output is the output of that call with an extra element at the beginning
  h~+A         That extra element is the sum of the elements of A

```

# Answer
> 1 votes
## Dyalog APL, 15 bytes

```
{+/¨⍵↑∘⌽¨⌽,\⌽⍵}

```

or

```
{⌽+/¨(-↑¨,\)⌽⍵}

```

# Answer
> 1 votes
# PHP program, 72 Bytes

```
<?foreach($a=$_GET[a]as$i=>$v)echo array_sum(array_slice($a,$i,$v)),"
";

```

call with `php-cgi -f <filename> 'a[]=3&a[]=2&a[]=4...`

+11 as a function:

```
function f($a){foreach($a as$i=>$v)$r[]=array_sum(array_slice($a,$i,$v));return$r;}

```

+9 without builtins:

```
function p($a){foreach($c=$r=$a as$i=>$v)for($k=$i;$k--;)if(--$a[$k]>0)$r[$k]+=$v;return$r;}

```

($c keeps the original values, $a counts down for each index, $r gets the sums)

-3 as program:

```
<?foreach($a=$r=$c=$_GET[a]as$i=>$v)for($k=$i;$k--;)if(--$c[$k]>0)$r[$k]+=$v;print_r($r);

```

# Answer
> 1 votes
# q (37 bytes)

```
{sum each(til[count x],'x)sublist\:x}

```

Example:

```
q){sum each(til[count x],'x)sublist\:x}3 2 4 1 1 5 1 2
9 6 11 1 1 8 1 2

```

# Answer
> 1 votes
## Clojure, 63 bytes

```
(defn f[[b & r]](concat[(apply + b(take(dec b)r))](if r(f r))))

```

Uses pattern matching to decompose input argument in to the first and the rest of the arguments.

# Answer
> 0 votes
**C#, 94 bytes**

```
Console.Write(String.Join(",",a.Select((v,i)=>a.Skip(i).Take(v).Sum().ToString()).ToArray()));

```

Where a is an int\[\] that represents the input to be solved.

---
Tags: code-golf, math, number, arithmetic, array
---


title: Same length sub arrays

text:
# Question
Title: Same length sub arrays
# Background:

Here's a little simple challenge. You want to be able to find out whether the arrays inside an array have the same length.

# Input:

Your input should consist of exactly one array *(this is the value passed to the function, not a user input)*. Your function takes exactly 1 parameter. It could contain arrays or be empty. No error checking needed, assume only list is ever passed in. Assume a 1-D array such as `[1]` or `[1,2,3,4,5]` is never passed in.

# Output:

Return `true` if all the list elements have the same length, `false` if they don't, and the parameter itself if the list is empty (or null if your language doesn't support multiple return types).

### Some test cases:

```
List: [] - [] (or null/your language equivalent)
List: [[1], [1], [2]] - True
List: [[1]] - True
List: [[1, 2, 3, 4]] - True
List: [[1, 2, 3, 4, 5], [2], [12, 314123]] - False
List: [[1, 2, 3, 4], [1]] - False

```

No std(in/out) input/output needed (however, it is allowed, just not required!), the function only needs to return boolean values `true` or `false`; or the parameter itself if the function is passed an empty list (or null/your language equivalent). Only one return value is returned.

# Rules:

Shortest byte count wins, only function is necessary (full programs are allowed if you desire).

# Answer
# Pyth - ~~7~~ 5 bytes

*Saved 2 bytes thanks to @FryAmTheEggman.*

And I was the one who told @issacg to remove the `q` default...

```
?QqCC

```

Test Suite.
> 6 votes

# Answer
# Python 2, 31

```
lambda l:l and l==zip(*zip(*l))

```

This requires the lists to be lists of tuples. `zip` Drops extra elements if the input was ragged, so double zipping is only a noop if the lists all have the same length.

Try it here
> 9 votes

# Answer
# Javascript ES6, ~~44~~ ~~43~~ 42 bytes

Saved 1 byte thanks to @Neil

```
a=>a[0]?!a.some(b=>b.length-a[0].length):a

```

Alternative solutions

```
a=>a[0]?a.every(b=>b.length==a[0].length):a // 43
a=>a[0]?new Set(a.map(b=>b.length)).size==1:a // 45
a=>a[0]?Math.max(...a.map(b=>b.length))==a[0].length:a // 54
a=>a[0]?[a[0].length,...a].reduce((b,d)=>b==d.length):a // 55, doesn't work as intended

```

Somehow the stacksnippet doesn't print `[]`, try it in your console for the actual result.

```
f=
a=>a[0]?a.every(b=>b.length==a[0].length):a

z.innerHTML = [
  [],
  [[1], [1], [2]],
  [[1]],
  [[1, 2, 3, 4]],
  [[1, 2, 3, 4, 5], [2], [12, 314123]],
  [[1, 2, 3, 4], [1]]
].map(m=>JSON.stringify(f(m))).join`<br>`
```

```
<pre id=z>
```

(yay for crossed out 44)
> 4 votes

# Answer
# Jelly, 5 bytes

```
L€E⁸ȧ

```

Try it online!

### How it works

```
L€E⁸ȧ  Monadic link. Argument: A (list)

L€     Map length over the list.
  E    Test if all elements are equal.
   ⁸ȧ  Take the logical AND of A and the resulting Boolean.

```
> 4 votes

# Answer
# Perl 6, 17 bytes

```
{$_??[==] $_!!$_}

```

`[==] $_` does a reduce of the input (`$_`) with `&infix:<==>`. `&infix:<==>` is a Numeric operator so it coerces its inputs to Numeric. The rest is just the ternary operator `??` `!!`.

This is roughly equivalent to

```
sub ( $_ ) {
  if $_ {
    # the ｢map｣ is for clarity, it is not needed
    $_.map(*.elems).reduce(&infix:<==>)
    # ｢[OP] List｣ is actually smarter than ｢List.reduce(&infix:«OP»)｣
    # as it takes into account operator chaining, and associativity
  } else {
    $_
  }
}

```

### Test:

```
#! /usr/bin/env perl6

use v6.c;
use Test;

# put it into the lexical namespace for clarity
my &same-elems = {$_??[==] $_!!$_}

my @tests = (
  [] => [],
  [[1], [1], [2]] => True,
  [[1],] => True,
  [[1, 2, 3, 4],] => True,
  [[1, 2, 3, 4, 5], [2], [12, 314123]] => False,
  [[1, 2, 3, 4], [1]] => False,
);

plan +@tests;

for @tests -> ( :key(@input), :value($expected) ) {
  is same-elems(@input), $expected, @input.perl
}

```

```
1..6
ok 1 - []
ok 2 - [[1], [1], [2]]
ok 3 - [[1],]
ok 4 - [[1, 2, 3, 4],]
ok 5 - [[1, 2, 3, 4, 5], [2], [12, 314123]]
ok 6 - [[1, 2, 3, 4], [1]]

```
> 4 votes

# Answer
# Swift 3 \- 47 Bytes

```
{$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}

```

To invoke, first assign it to a variable:

```
 let f: ([[Any]]) -> Bool? = {$0.isEmpty ?nil:Set($0.map{$0.count}).count<2}
 f([[1], [1,2], [1,2,3]])

```
> 3 votes

# Answer
## Mathematica, 22 bytes

```
a@{}={};a@b_:=ArrayQ@b

```

The requirement of `a[{}] == {}` ruins everything and prevents a 6 byte solution of the built-in `ArrayQ`, since in Mathematica a zero length array is also an array.
> 2 votes

# Answer
# Julia, 33 bytes

```
!x=[]==x?x:diff(map(endof,x))⊆0

```

Try it online!

### How it works

We redefine the unary operator **!** for this task.

If **x** is the empty array, we simply return **x**.

Else, we map `endof` (equivalent to `length`) over the arrays in **x** and compute the differences of consecutive lengths with `diff`. If all length are equal, this will generate an array of **0**'s. Otherwise, there will be non-zero numbers in the result.

Finally, `⊆0` tests if all differences are **0** and return the corresponding Boolean.
> 2 votes

# Answer
## Haskell, ~~48~~ 46 bytes

```
f[]=Nothing
f x|h:t<-length<$>x=Just$all(==h)t

```

Wraps the result in the `Maybe` type and returns `Nothing` if the input is the empty list and `Just True`/`Just False` otherwise.

Usage example:

```
*Main> map f [[],[[1],[2],[3]],[[1]],[[1,2,3,4]],[[1,2,3,4,5],[2],[12,314123]],[[1,2,3,4],[1]]]
[Nothing,Just True,Just True,Just True,Just False,Just False]

```

How it works:

```
f[]=Nothing                   -- empty input
f x                           -- otherwise
   |(h:t)<-length<$>x         -- map length function over the input and bind h
                              -- to the first element and t to rest of the list
          =     all(==h)t     -- return whether all values in t equal h
           Just$              -- wrapped in the Maybe type

```

Edit: @Lynn saved two bytes. Thanks!
> 2 votes

# Answer
# Brachylog, 9 bytes

```
.v|:ladl1

```

Returns `true` or `false` or the empty list.

### Explanation

```
.v      Unify the output with the input if it's the empty list
|       Or
:la     Apply length to each element of the input
   d    Remove all duplicates
    l1  The length of the resulting list is 1

```
> 2 votes

# Answer
# Ruby, 27 bytes

`->i{!i.map(&:size).uniq[1]}`

### Test:

```
s = ->i{!i.map(&:size).uniq[1]}
s[[[1, 2, 3, 4], [1]]]
=> false
s[[[1, 2, 3, 4]]]
=> true

```
> 2 votes

# Answer
# Java 10, ~~145~~ ~~129~~ ~~107~~ ~~106~~ ~~103~~ ~~93~~ 77 bytes

Loads of bytes saved thanks to *@Frozn*, and by using `Object` as return-type, we can comply with OP's rules of returning the input-array when the array is empty, despite Java's one-return-type-only nature regarding methods.

```
m->{int f=1;for(var a:m)f=m[0].length!=a.length?0:f;return m.length<1?m:f>0;}

```

Try it online.

**Explanation:**

```
m->{                  // Method with integer-matrix parameter and Object return-type
  int f=1;            //  Flag-integer, starting at 1
  for(var a:m)        //  Loop over the rows of the matrix
    f=m[0].length!=a.length?
                      //   If the length of the first and current row aren't the same:
       0              //    Change `f` to 0
      :               //   Else:
       f;             //    Leave `f` the same
  return m.length<1?  //  If there is only one row:
          m           //   Return the input-matrix as result
         :            //  Else:
          f>0;}       //   Return whether the flag `f` is still 1 as boolean

```
> 2 votes

# Answer
## PowerShell v2+, 53 bytes

```
param($a)if($a){($a|%{$_.count}|select -u).count-eq1}

```

This presumes that standard I/O methods and both programs and functions are allowed. Additionally, in PowerShell, the concept of "returning" an empty array is meaningless -- it's converted to `$null` as soon as it leaves scope -- and so it is the equivalent of returning nothing, which is what is done here.

We take input `$a`, and `if` it's non-empty we collect all the `.count`s of each sub-array. We pipe that to `Select-Object` with the `-u`nique flag, take *that* `.count` and verify that it's `-eq`ual to `1`. Returns Boolean `$true` or `$false`. If the input is the empty array, returns nothing (i.e., `$null`).

### Examples

```
PS C:\Tools\Scripts\golfing> .\same-length-sub-arrays.ps1 ((1),(2),(3))
True

PS C:\Tools\Scripts\golfing> .\same-length-sub-arrays.ps1 ((1),(2),(3,4))
False

PS C:\Tools\Scripts\golfing> .\same-length-sub-arrays.ps1 @()

PS C:\Tools\Scripts\golfing> (.\same-length-sub-arrays.ps1 @()).GetType()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ (.\same-length-sub-arrays.ps1 @()).GetType()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PS C:\Tools\Scripts\golfing> (.\same-length-sub-arrays.ps1 @())-eq$null
True

```
> 2 votes

# Answer
# Python, 45 bytes

```
lambda x:x and min(x,key=len)==max(x,key=len)

```
> 1 votes

# Answer
# Octave, 51 bytes

```
@(x)repmat(2>n(unique(cellfun(n=@numel,x))),n(x)>0)

```

**Online Demo**

**Explanation**

Loops through the input (a cell array) and determines the number of elements in each entry `numel`, then from this array of the number of elements, we ensure that there is only one unique value: `2 > numel(unique(numberOfElements))`. This will give us the boolean we want. Unfortunately, it is difficult to yield an empty array efficiently so in order to deal with the case of an empty input, we use `repmat` to repeat this boolean value `N` times where `N` is the number of subarrays in the input. If the input is empty this repeats the boolean value `0` times leading to `[]`.
> 1 votes

# Answer
## Actually, 18 bytes

```
`♂l╔l;Y"[].⌂"£n=1`

```

Try it online! (calls the function with `ƒ`)

Explanation:

```
`♂l╔l;Y"[].⌂"£n=1`  push a function:
 ♂l                   map length over input
   ╔l                 uniquify
     ;Y               1 if list is empty else 0
       "[].⌂"£n       call this function that many times:
        [].             print an empty list
           ⌂            exit
               =1     1 if length of unique list equals 1 else 0

```

If the function-only requirement is lifted, the equivalent program works for 15 bytes:

```
♂l╔l;Y`[].⌂`n=1

```

Try it online!
> 1 votes

# Answer
## 05Ab1E, 12 bytes

```
Dg0Qië€gÙg1Q

```

**Explained**

```
Dg0Qi          # if empty list, return input
     ë         # else
      €g       # map length over list
        Ùg1Q   # check if length of uniquified list is 1

```

Try it online
> 1 votes

# Answer
## F#, 78 bytes

```
function
|[]->None
|x->Seq.forall(fun y->Seq.length y=Seq.length x.[0])x|>Some

```

Output is the F# Option type. If the input is empty output is None, else it's Some bool, where the bool value indicates whether all the sub-arrays are of equal length.

```
// F# Interactive
let f =
    function
    |[]->None
    |x->Seq.forall(fun y->Seq.length y=Seq.length x.[0])x|>Some;;

val f : _arg1:#seq<'b> list -> bool option

> f [[0;1];[2];[3]];;
val it : bool option = Some false
> f [[0;1];[2;3];];;
val it : bool option = Some true
> f [];;
val it : bool option = None

```
> 1 votes

# Answer
# J, 26 bytes

```
]`(1=[:#@~.#@>@>)@.(*@#@>)

```

Since J doesn't support ragged arrays, I will use boxed arrays instead. It returns `1` for true, `0` for false, and the input if empty.

## Usage

```
   f =: ]`(1=[:#@~.#@>@>)@.(*@#@>)

   NB. Boxed array representing [[1, 2, 3, 4, 5], [2], [12, 314123]]
   < 1 2 3 4 ; 2 ; 12 314123
┌─────────────────────┐
│┌───────┬─┬─────────┐│
││1 2 3 4│2│12 314123││
│└───────┴─┴─────────┘│
└─────────────────────┘
   f < 1 2 3 4 ; 2 ; 12 314123
0
   NB. The empty list
   a:
┌┐
││
└┘
   f a:
┌┐
││
└┘
   f < 1 ; 1 ; 2
1
   f < < 1
1
   f < < 1 2 3 4
1
   f < 1 2 3 4 ; 1
0

```
> 1 votes

# Answer
# Retina, 35 bytes

If only `[]` could return true or false. Returning a 3rd value makes it so much longer.

```
\[]
xx
\d|],

M`^\[(\[,*)\1*]]|x
2

```

**Try it online**

This is the core program. It removes digits and occurrences of `],`, then matches if the number of commas is the same after each `[`. It would return `0` for `[]`. The code above varies because I added a check for an empty list to make it match twice, then I replace `2` with nothing for a null return.

```
\d|],

^\[(\[,*)\1*]]

```
> 1 votes

# Answer
## APL, 13 bytes

```
1=(×∘⍴⍴≢)∪≢¨⎕

```

In English:

* compute the unique of the tallies of each of the subarrays;
* reshape the result with the signum of its shape: if its an empty vector, it remains an empty vector;
* is it equal to 1?
> 1 votes

# Answer
## C#, 80 bytes

Im checking length 4 times in this golf. i wish there was a better way to be honest.

```
bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).Count()==a.Count;}

```

alternative version also 80 bytes..

```
bool f(List<int[]>a){return a.Where(m=>m.Length==a[0].Length).SequenceEqual(a);}

```
> 0 votes

# Answer
## Prolog, 40

```
m([],L).
m([H|T],L):-length(H,L),m(T,L).

```

Provide a true/false answer when calling `m(X,L)` for some input `X`.
> 0 votes

# Answer
# APL, 13 bytes

```
{(×⍴⍵)↑⍵≡↓↑⍵}

```

Explanation:

* `↓↑⍵`: turn the list of arrays into a matrix, and then turn the matrix back into a list of arrays. Because a matrix has to be rectangular, short arrays will be padded with zeroes to match the longest.
* `⍵≡`: see if the result is equal to the input. This is only the case if no zeroes have been added, which means all the sublists were the same length.
* `×⍴⍵`: take the sign of the length of , which is `0` if  is empty and `1` if not.
* : take the first 0 or 1 items from the result depending on whether the array was empty or not.
> 0 votes

# Answer
## Clojure, 40 bytes

```
#(if(not-empty %)(apply =(map count %)))

```

Yay for suitable language features :)
> 0 votes

---
Tags: code-golf, array
---


title: Print Polyglot Pieces

text:
# Question
Title: Print Polyglot Pieces
Typically, polyglots are constructed in such a manner that each language can ignore parts of the code that are present for other languages, by wrapping them in string literals, using comment syntax, or other similar tricks.

Your goal is to write a polyglot where the output for each language is the code from the polyglot that produces that output. Specifically, the output must be constructed from the polyglot code with only deletions, and it must be a quine in the given language.

## Rules

* Only proper quines are allowed (no reading the source code, no taking input, output must be to STDOUT or closest alternative if STDOUT is not an option, and the programs must consist of more than just literals that are implicitly printed).
* Since different languages can use different encodings, the raw bytes are what matters here. For example, if language A uses UTF-8 and language B uses CP437, the (hex) code `C3 88 46 47` would be `ÈFG` for language A and `├êFG` for language B.
* All outputs must be distinct (again, comparing raw bytes). This avoids complications with trying to restrict minor language versions - if two languages use the same part of the code to do the same thing, you can't claim them both.
    + If you have two languages A and B such that `XY` is a valid output in both, but `YZ` is also valid in B, you may choose `XY` as the output for A and `YZ` as the output for B, so you can claim both of them in your score (but you can't claim `XY` for both languages because of the above rule).
* All outputs must be as short as possible. For example, if your code was `print('foo')#something`, for Python 3 (ignoring the fact that the output is not correct), the code you would need to output would be `print('foo')`, and `print('foo')#` would not be allowed. If there are multiple strings of equal (minimal) length that produce correct output, you may choose any one of them.
* Submissions must be polyglots in at least 2 languages.
* Your score will be given by `(number of programming languages with distinct outputs)**3/(total byte size of polyglot)`. The highest score wins. In the event that two submissions achieve the same score, the submission that reached that score first will win.

# Answer
## GolfScript \+ CJam \+ Fission 2 \+ Jelly, 4 languages, 24 bytes, score 2.667

Let's start with the hex dump:

```
00000000:  3322 3024 700a 2721 2b4f 5222 0a3c 3024 700a 6523 7fff cccc

```

For GolfScript, CJam and Fission 2, we interpret this in some ASCII-compatible single-byte encoding like ISO 8859-1 (the exact encoding doesn't really matter, because the languages only define operators for ASCII characters anyway):

```
3"0$p
'!+OR"
<0$p
e#<DEL>ÿÌÌ

```

Where `<DEL>` is the control character `0x7f`.

In Jelly, this is assumed to be in Jelly's own code page, where it looks like this instead:

```
3"0$p½'!+OR"½<0$p½e#¶”ṘṘ

```

### GolfScript

The `e` on the last line is an unknown variable and `#` comments out the remainder of the line, so this prints

```
"0$p"
0$p

```

*with* a trailing linefeed. This is the GolfScript/CJam polyglot version of the standard quine:

```
".p"
.p

```

Try the polyglot. | Try the quine.

### CJam

Here, `e#` comments out the last line, so almost identically, this prints

```
"0$p"
0$p

```

*without* a trailing linefeed.

Try the polyglot | Try the quine.

### Fission

Fission only sees the second line which *is* the standard Fission quine, so it prints

```
'!+OR"

```

I can't provide an online link for the polyglot here, because TIO sends the file to Fission as UTF-8, but Fission reads the source byte by byte, which makes the last line too long. However, I've tested this locally with an ISO 8859-1 encoded file (in which the last line has the same length as the second), to confirm that this works.

Try the quine.

### Jelly

The pilcrow is an alias for linefeeds in Jelly, so the source is equivalent to:

```
3"0$p½'!+OR"½<0$p½e#
”ṘṘ

```

All but the last line of a Jelly program are "helper links" (i.e. functions) which can be ignored unless they are called, provided they are syntactically valid. This is actually the reason the `3` comes first in the CJam and GolfScript programs, because otherwise the `"` can't be parsed in Jelly.

Otherwise, since the function isn't called, the program is equivalent to only its second line, which is the standard Jelly quine.

Try the polyglot. | Try the quine.
> 10 votes

# Answer
# \>\<\> + Python, 2 languages, ~~51~~ 46 bytes, score~=~~0.16~~ 0.17

Since there are no answers yet, I'll start with a simple one

```
#.09;!?lo}*2+2f"
_='_=%r;print _%%_';print _%_

```

Try it for \>\<\> and Python

For \>\<\> the first line is a quine (# reflects, " puts the whole line on the stack, then we push 34 (charcode for ") and print everything) , execution never moves from it, so it effectively ignores the rest of the code.

For Python the first line is a comment, while the second one is a quine (standard approach in python, using string substitution with the same string as both arguments).
> 8 votes

# Answer
# JavaScript + Python 2 + Japt, 3 languages, 132 bytes, score ~= 0.205

```
A="`i96d)p2`i96d)p2";1//2;A=1
S="S=%s;console.log(S,uneval(S))";A//2;S="S=%r;print S%%S";"""
console.log(S,uneval(S))//""";print S%S

```

This prints

```
S="S=%s;console.log(S,uneval(S))";console.log(S,uneval(S))

```

in JavaScript (only in Firefox),

```
S='S=%r;print S%%S';print S%S

```

in Python 2, and

```
`i96d)p2`i96d)p2

```

in Japt. (Test it online!)

### JavaScript

This is what JavaScript sees:

```
A="`i96d)p2`i96d)p2";1
S="S=%s;console.log(S,uneval(S))";A
console.log(S,uneval(S))

```

The first line is a no-op because `A` is not used in any way. The second line sets `S` to the string `S=%s;console.log(S,uneval(S))`, and the third prints it after replacing the `%s` with the `uneval`ed representation of `S` (just `S` wrapped in quotes). The result is a quine in JavaScript.

### Python

This is basically what Python sees:

```
A="`i96d)p2`i96d)p2";1//2;A=1
S="S=%s;console.log(S,uneval(S))";A//2;S="S=%r;print S%%S"
print S%S

```

The first line is pretty much a no-op; the only important part is the `A=1` at the end. This turns `A` into a number so that the integer division `A//2` on the second line doesn't throw an error.

The second line is mostly the same way, except it sets `S` to the string `S=%r;print S%%S`. The third line prints `S` after replacing the `%r` with the raw representation of `S` (just `S` wrapped in single-quotes). The result is a quine in Python 2.

### Japt

This is the JavaScript code the Japt interpreter sees:

```
A="`i96d)p2`i96d)p2";1//2;A=1
S="S=%s;console.log(S,uneval(S))";A//2;S="S=%r;print S%%S";"","\nconsole.log(S,uneval(S))//","";.p("r".i("n".t(),S%S))

```

As you can see, it's mostly the same as the JavaScript answer, with one main exception: the last two lines are combined. As a result, this is what the interpreter actually sees:

```
A="`i96d)p2`i96d)p2";1
S="S=%s;console.log(S,uneval(S))";A

```

The first line sets `A` to the Japt quine, and the second sets `S` to part of the JS quine. In Japt however, only the last expression is sent to output; this is `A`, so the output is ``i96d)p2`i96d)p2`.
> 6 votes

# Answer
# Jolf + \>\<\>, score = 2\**3/15 = 0.533....

```
"r0:g>o<
"Q«Q«

```

Working on adding another language to this.
> 3 votes

# Answer
## \>\<\>, Python 2 and 3, 3 languages, 107 bytes, score = 27/107 ~= 0.252

```
#o<}-1:"
a=1/1is 1;b="(_%(_,b))"[a:-a|9];_='a=1/1is 1;b="(_%%(_,b))"[a:-a|9];_=%r;print %s';print (_%(_,b))

```

Try it online: Python 2, Python 3, \>\<\>

The Python 3 output is the second line exactly, and the Python 2 output is this quine. The \>\<\> output is the first line.

## Explanation

This program is based off of the classic Python 2 quine:

```
_='_=%r;print _%%_';print _%_

```

First, to make it compatible with both Python 2 and Python 3, I changed the `print` statement to a function call, and added an extra space which will come in handy later:

```
_='_=%r;print (_%%_)';print (_%_)

```

Next, I needed a way to distinguish Python 2 from Python 3. One of the simplest ways is to take advantage of the fact that `/` is integer division in Python 2, but float division in Python 3. Thus, the following code evaluates to `True` in Python 2, but `False` in Python 3:

```
1/1is 1

```

In order to make the outputs distinct between the two languages, I needed to selectively remove the first and last parentheses in the `print` call (that's why I needed the space earlier - with no space, it wouldn't be a valid `print` statement in Python 2). Thus, I needed to modify the quine harness like so:

```
a=1/1is 1;b="(_%(_,b))"[a:-a|9];_='a=1/1is 1;b="(_%%(_,b))"[a:-a|9];_=%r;print %s';print (_%(_,b))

```

That expression `a:-a|9` evaluates to `0:9` in Python 2 and `1:-1` in Python 3. Thus, `b` is `"(_%(_,b))"` in Python 3, but in Python 2 the first and last characters are discarded, leaving `_%(_,b)`. And with that modification, the polyglot was valid for this challenge.

As suggested by Teal pelican, the \>\<\> quine `#o<}-1:"` could be added fairly easily, thanks to the fact that `#` begins a single-line comment in Python. Simply prepending it and a newline adds another language and increases the score by nearly tenfold.
> 2 votes

# Answer
# Python 2 + Retina, 2 languages, 55 bytes, score = 2^3/55 ≈ 0.145

I used `$n` instead of  to keep them both valid ASCII.

```
S='S=%r;print S%%S';print S%S#|
#$n\(*S1`$n\(*S1`
#\`#

```

**Python**, **Retina**

Python:

```
S='S=%r;print S%%S';print S%S

```

Retina:

```

\(*S1`
\(*S1`
```
> 1 votes

# Answer
## \>\<\> + Pyke + Python 2, 81 bytes, score = 3\**3/81 ~0.333

```
"""r00gol?!;60.
a=%r;print a%%a"""#);"34.Cp\D\Es"DEp00/
a=__doc__[-15:]
print a%a

```

I've tried to do something different with all the languages.

### \>\<\> sees:

```
"""r00gol?!;60.

```

This is a slight modification of the standard \>\<\> quine to use a triple quoted string at the beginning. This allows the ending triple quotes for Python to be on a different line.

Try it online!

### Pyke sees:

```
"34.Cp\D\Es"DEp00/

```

I hadn't created a quine in Pyke before and thus had to think of one. I used traditional quining techniques to create a string and then eval it with itself as an input. Note for this to work without visual impact, warnings will have to be disabled. Errors out with a division by 0 error in the generation step.

Try it here! Or just the quine part.

### Python sees:

It all. Python uses all of the code to produce its quine. I decided to embed the quine part in the docstring (though ultimately it would save bytes to remove but I think it's cool). It's a modification of the standard quining technique.

Try it online!
> 0 votes

---
Tags: code-challenge, quine, polyglot
---


title: The Baum-Sweet Sequence

text:
# Question
Title: The Baum-Sweet Sequence
# The Baum-Sweet Sequence (A086747 with a Twist)

Take in a positive integer `n` and print the integers from 1 to n for which the Baum-Sweet sequence returns true. The Baum-Sweet sequence should return **falsy** if the binary representation of the number contains an odd number of consecutive zeros anywhere in the number, and **truthy** otherwise. For more information, click the link. Here's a couple of examples:

```
1 -> 1 -> Truthy
2 -> 10 -> Falsy
3 -> 11 -> Truthy
4 -> 100 -> Truthy (Even run of zeros)

```

# Here's an example given `n=32`

Step 1: The Baum-Sweet sequence visualized for `n=32`

```
1               1 (1)
1 0             0 (2)
11              1 (3)
1 00            1 (4)
1 0 1           0 (5)
11 0            0 (6)
111             1 (7)
1 000           0 (8)
1 00 1          1 (9)
1 0 1 0         0 (10)
1 0 11          0 (11)
11 00           1 (12)
11 0 1          0 (13)
111 0           0 (14)
1111            1 (15)
1 0000          1 (16)
1 000 1         0 (17)
1 00 1 0        0 (18)
1 00 11         1 (19)
1 0 1 00        0 (20)
1 0 1 0 1       0 (21)
1 0 11 0        0 (22)
1 0 111         0 (23)
11 000          0 (24)
11 00 1         1 (25)
11 0 1 0        0 (26)
11 0 11         0 (27)
111 00          1 (28)
111 0 1         0 (29)
1111 0          0 (30)
11111           1 (31)
1 00000         0 (32)

```

So, after computing the Baum-Sweet sequence for n, take the numbers that were truthy for the sequence and collect them for the final result. For `n=32` we would have:

```
[1, 3, 4, 7, 9, 12, 15, 16, 19, 25, 28, 31]

```

As the final answer.

---

This is , shortest byte count wins.

# Answer
> 7 votes
# 05AB1E, ~~10~~ 9 bytes

Saved a byte thanks to *Adnan*

```
ƒNb00¡SP–

```

Try it online!

**Explanation**

```
ƒ          # for N in [0 ... input]
 Nb        # convert N to binary
   00¡     # split at "00"
      S    # convert to list of digits
       P   # product of list
        –  # if 1, print N

```

# Answer
> 8 votes
# JavaScript (ES6), ~~70~~ ~~68~~ 63 bytes

```
g=n=>n?g(n-1).concat(/0/.test(n.toString(2).split`00`)?[]:n):[]

console.log(g(1000).join(", "))
```

Slightly more interesting recursive solution:

```
n=>[...Array(n+1).keys()].filter(f=n=>n<2?n:n%4?n&f(n>>1):f(n/4))

```

67 bytes thanks to @Neil.

`g` is the function to call.

# Answer
> 4 votes
# Bash, ~~58~~, 46 bytes

EDITS:

* Replaced *bc* with *dc* (Thx @Digital Trauma !)
* Start with 1;

**Golfed**

```
seq $1|sed 'h;s/.*/dc -e2o&p/e;s/00//g;/0/d;x'

```

**Test**

```
>./baum 32
1
3
4
7
9
12
15
16
19
25
28
31

```

**Explained**

*shell*

```
seq $1 #generate a sequence of integers from 1 to N, one per line
|sed   #process with sed

```

*sed*

```
h                #Save input line to the hold space
s/.*/dc -e2o&p/e #Convert input to binary, with dc
s/00//g          #Remove all successive pairs of 0-es
/0/d             #If there are still some zeroes left
                 #(i.e. there was at least one odd sequence of them)
                 #drop the line, proceed to the next one
x                #Otherwise, exchange the contents of the hold
                 #and pattern spaces and (implicitly) print

```

Try It Online !

# Answer
> 4 votes
## Python 2, 62 bytes

```
g=lambda n:n*[0]and g(n-1)+[n]['0'in`bin(n)[1:].split('00')`:]

```

Checks for odd runs of 1's in the binary representation by splitting on `00` and checking if any zeroes remain in the string representation of the resulting list. Annoyingly, binary numbers start with `0b`, which has a zero that needs to be removed to avoid a false positive.

The enumeration is done by recursing down.

# Answer
> 3 votes
## Batch, 143 bytes

```
@for /l %%i in (1,1,%1)do @call:c %%i
@exit/b
:c
@set/ai=%1
:l
@if %i%==1 echo %1&exit/b
@set/ar=%i%%%4,i/=4-r%%2*2
@if %r% neq 2 goto l

```

# Answer
> 3 votes
# Perl 6, 40 bytes

```
{grep {.base(2)!~~/10[00]*[1|$]/},1..$_}

```

Try it

```
{
  grep            # find all of them
  {
    .base(2)      # where the binary representation
    !~~           # does not match
    /
      10          # ｢10｣
      [ 00 ]*     # followed by an even number of ｢0｣s
      [ 1 | $ ]   # either at end or before a ｢1｣
    /
  }, 1 .. $_      # from one to the input
}

```

( `[]` are used for non-capturing grouping, with `<[]>` used for character classes )

# Answer
> 2 votes
# PowerShell, ~~79~~ 61 bytes

```
1..$args[0]|?{0-notin([convert]::ToString($_,2)-split'1|00')}

```

Try it online!

I had inspiration this morning to change how I perform the `-split` operation, then see that it's similar to how xnor's answer is constructed, so, I guess great minds think alike?

We loop from `1` up to input `$args[0]`, and use a `Where-Object` operator to pull out the appropriate numbers `|?{...}`. The clause is a simple Boolean value -- we're ensuring that `0` is `-notin` the results of `(...)`.

Inside the parens, we `[convert]::` the current number `$_` `ToString` with the base `2` (i.e., turn it into a binary string). We then `-split` the string on the regex `1|00` -- this is a greedy match, and results in an array of strings (for example, `100010` would turn into `'','','0','','0'` and so forth).

Thus, if every run of `0`s in the binary string is even (meaning the regex has split them out into empty strings), then `0` will be `-notin` the result, so the `Where` clause is true, and the number is selected. Those numbers are left on the pipeline and output is implicit.

# Answer
> 2 votes
# Python 2, ~~67~~ 47 bytes

```
f=lambda n,k=1:n/k*[1]and[k]+f(n,k-~k)+f(n,4*k)

```

*Thanks to @xnor to golfing off 20(!) bytes!*

Returns an unordered list. It's quite efficient: input **100,000** takes roughly 40 ms on TIO.

Try it online!

# Answer
> 2 votes
## Mathematica, 59 bytes

```
Select[Range@#,!Or@@OddQ/@Tr/@Split[1-#~IntegerDigits~2]&]&

```

Mathematica answer number 4...

# Answer
> 1 votes
# MATL, ~~12~~ 11 bytes

```
:"@BY'og)?@

```

Try it online!

### Explanation

To detect if a number is valid this converts to binary, applies run-length encoding, keeps only runs of odd length, and checks if no run of zeros survives.

```
:       % Take input n implicitly. Push range [1 2 ... n]
"       % For each k in [1 2 ... n]
  @     %   Push k
  B     %   Convert to binary
  Y'    %   Run-length encoding. Pushes array of values and array of run-lengths
  o     %   Parity. Gives array that contains 0 for even lengths, 1 for odd
  g)    %   Convert to logical and use index into the array of values
  ?     %   If the result does not contain zeros
    @   %     Push k
        %   End
        % End
        % Implicitly display stack

```

# Answer
> 1 votes
## R, 75 bytes

```
for(i in 1:scan()){x=rle(miscFuncs::bin(i));if(!any(x$l%%2&!x$v))cat(i,"")}

```

Reads input from stdin and uses the `bin` function from the `miscFuncs` package to convert from decimal to binary vector. Consequently performs run-length encoding to check values `== 0` and lengths are odd.

# Answer
> 1 votes
# Stacked, 69 bytes

Try it here!

```
:>1+[bits{e.b:e b 0#=}chunkby[0 has]filter$sizemap 2%0 eq all]"filter

```

Or, noncompeting at 67 bytes:

```
:>1+[bits{e.b:e b 0#=}chunkby[0 has]filter$sizemap even all]"filter

```

And, even more noncompeting at 49 bytes:

```
:>1+[bits rle{k:k 0=}filter values even all]fkeep

```

All take input as TOS and leaves output on TOS.

## Explanation

```
:>1+[...]"filter   input: n
:>                 range from [0, n)
  1+               range from [1, n]
    [...]          a function
         "filter   apply to each cell and filter

```

The function:

```
bits{e.b:e b 0#=}chunkby[0 has]filter$sizemap 2%0 eq all  input: c
bits                                                      convert c to binary
    {e.b:e b 0#=}chunkby                                  split into chunks of contiguous 0s
                        [0 has]filter                     take only chunks with 0s
                                     $sizemap             map each chunk to its size
                                              2%          vectorized modulus 2
                                                0 eq      vectorized equality with 0
                                                     all  all of them are of even lengths

```

### Explanation of noncompeting:

It's the same as above, with a few key differences:

```
:>1+[bits rle{k:k 0=}filter values even all]fkeep   input: y
          rle                                       run length encode y
             {k:k 0=}filter                         keep keys that = 0
                            values                  get those values
                                            fkeep   like `filter`, but is implemented with
                                                    taking `f` as a boolean mask

```

# Answer
> 1 votes
# Befunge, ~~84~~ ~~51~~ 49 bytes

After a bit of experimentation, I realised I could do quite a bit better than my original solution by using a technique similar to the Batch answer that Neil came up with.

```
<v::\<&1
:_v#:/+2*2!%2:_v#-2%4
:$<@_v#!:-1\+1$<:.

```

Try it online!

As with my original solution, there are two loops - the outer loop iterating over the numbers we want to test, and an inner loop testing the bit sequence for each number. The way the test works is by examining two bits at a time (modulo 4 of the current value). If that's equal to 2 we've got an odd sequence of zeros and can abort the inner loop and proceed to the next number.

If the modulo 4 is not equal to 2, we need to continue testing the remaining bits, so we shift up the bits that have already been tested. This is done by dividing the value, lets call it *n*, by `2+2*!(n%2)`. This means if the first bit was a 1, we divide by 2 (dropping that 1 bit), but if it was a 0, we divide by 4, so we'll always be dropping pairs of zeros.

If we eventually get down to zero, that means there weren't any odd sequences of zero bits, so we write out the number.

# Answer
> 1 votes
## Java, ~~144~~ ~~130~~ 128 Bytes

This isn't as golfed as I think it can be, but I thought it'd be a cute solution to use a Regex, despite never having used one.

Golfed:

`static String a(int n){String s="";for(Integer i=0;i++<n;)if(i.toString(i,2).replaceAll("00|1","").isEmpty())s+=i+" ";return s;}`

Ungolfed:

```
static String a(int n){
    String s="";                      //Cheaper than using a list/array
    for(Integer i=0;i++<n;)           //Loop n times
        if(i.toString(i,2)            //Convert int to base 2 string
                .replaceAll("00|1","")//Find and remove ones and consecutive zeroes
                .isEmpty())           //If any chars remain, i is truthy
            s+=i+" ";                 //Append i to the storage string
    return s;                         //Return all values
}

```

**Edit:** I was able to save 14 bytes by making the regex 00|1 instead of 00, and removing ".replace("1","")" between the replaceAll and isEmpty!

**Edit 2:** I was able to save 2 bytes by making i an Integer and referencing Integer.toString with i.toString.

# Answer
> 1 votes
# Visual Basic(.net 4.5) 163 bytes

First ever answer here so I'm sure I've screwed something up. Let me know and I'll fix. Are Visual Basic lambdas even allowed?

Thanks to MamaFunRoll for the remove consecutive zeroes idea

```
Dim R=Sub(m)System.Console.WriteLine(String.Join(",",System.Linq.Enumerable.Range(1, m).Where(Function(s) Not Convert.ToString(s,2).Replace("00","").Contains(0))))

```

R(32) outputs

```
1,3,4,7,9,12,15,16,19,25,28,31

```

# Answer
> 0 votes
## Clojure, 103 bytes

I don't think this is the shortest way...

```
#(remove(fn[v]((set(map(fn[s](mod(count s)2))(re-seq #"0+"(Integer/toString v 2))))1))(range 1(inc %)))

```

Uses `re-seq` to find consecutive zeros, maps their modulo-2 lengths to a `set`, discards them if number `1` is found from the set.

# Answer
> 0 votes
# C# ~~159~~ ~~157~~ 155 bytes

Saved 2 x two bytes thanks to TuukkaX.

Note: prints out the ints in reverse order.

```
void B(int n){var b=Convert.ToString(n,2);int c=0,i=0;for(;i<b.Length;){if(b[i++]<49)c++;else if(c%2>0)break;}if(c%2<1)Console.WriteLine(n);if(n>1)B(--n);}

```

Explanation:

```
void B(int n)
{
    // convert our int to a binary string
    var b = Convert.ToString(n, 2);

    // set our '0' counter 'c' and our indexer 'i'
    int c = 0, i = 0;

    // loop over the binary string, without initialisation and afterthought
    for (; i < b.Length;)
    {
        // check for '0' (48 ASCII) and increment i. increment c if true
        if (b[i++] < 49)
            c++;

        // otherwise check if c is odd, and break if it is
        else if (c%2 > 0)
            break;
    }

    // print the int if c is even
    if (c%2 < 1)
        Console.WriteLine(n);

    // recursively call B again with the next number
    if (n > 1)
        B(--n);
}

```

# Answer
> 0 votes
# Wonder, 38 bytes

```
@(!>@=1len iO0Rstr#["00"]bn#0)rng1+1#0

```

Usage:

```
(@(!>@=1len iO0Rstr#["00"]bn#0)rng1+1#0) 32

```

# Explanation

More readable:

```
@(
  fltr@
    = 1
      len
        iO 0
          Rstr #["00"]
            bn #0
) rng 1 +1 #0

```

`rng 1 +1 #0`: Range from 1 to input.

`fltr@ ...`: Filter range with the following predicate.

`bn #0`: Convert current item to binary. (This will have a leading `0b`).

`Rstr #["00"]`: Recursively prune any occurrences of `00` in the string.

`len iO 0`: Count the amounts of `0`s in the string.

`=1`: Check if the amount is equal to 1. If the only `0` left in the string after pruning is in the leading `0b`, then this returns true; otherwise, this returns false.

# Answer
> 0 votes
# Ruby, ~~78~~ ~~69~~ 68 bytes

```
->n{(1..n).select{|m|m.to_s(s=2).split(?1).map{|i|s|=i.size};s&1<1}}

```

Older versions:

```
->n{(1..n).select{|m|m.to_s(2).split(?1).select{|i|i.size%2>0}[0].!}}
->n{(1..n).select{|m|b=z=0;(m.to_s(2)+?1).each_char{|i|z+=i>?0?b|=z:1};b&1<1}}

```

# Answer
> 0 votes
# Python 3, ~~86~~ 82 bytes

Golfing in progress...

```
lambda n:[x for x in range(1,n+1)if 1-any(i%2for i in map(len,bin(x).split('1')))]

```

Golfed off 4 bytes by changing `bin(x)[2:]` to just `bin(x)` \- this leaves `0b` at the start of the string, but I realised this does not actually affect the calculations :)

# Answer
> 0 votes
# Mathematica, 81 bytes

```
Select[Range@#,FreeQ[Union@#+Mod[Length@#,2,1]&/@Split[#~IntegerDigits~2],{1}]&]&

```

Computes, for each run of consecutive digits in a number, { the common digit in that run plus (1 if the length is odd, 2 if the length is even) }; if any of the answers is {1} then the number isn't in the sequence.

# Answer
> 0 votes
## Mathematica, 75 bytes

```
Select[Range@#,And@@EvenQ/@Length/@Cases[Split[#~IntegerDigits~2],{0..}]&]&

```

`#~IntegerDigits~2` computes the list of binary digits of the input `#`. `Split` that list into runs of identical elements, take the `Cases` that match `{0..}`, take the `Length` of each of them, take `EvenQ` of the lengths and then return `And` of the results.

# Answer
> 0 votes
# Python, 142 bytes

This is mainly just to practice golfing my Python.

```
def o(n):
 r=0
 for i in bin(n)[2:]:
  if i=='1':
   if r&1:return 0
   r=0
  else:r+=1
 return ~r&1
lambda n:[i for i in range(1,n+1)if o(i)]

```

# Answer
> 0 votes
# Jelly, ~~15~~ ~~13~~ 10 bytes

*saved two bytes after looking at other answers, another 3 bytes thanks to Dennis*

```
Bœṣ0,0Ȧµ€T

```

# Explanation

```
Bœṣ0,0Ȧµ€T -Helper link: argument K (integer): ex. 24
B          -Convert K to a list of its binary digits: 24 -> [1,1,0,0,0]
   0,0     -Create a list of two 0's: [0,0]
 œṣ        -Split the binary digits on instances of the sublist: [1,1,0,0,0]-> [[1,1],[0]]
      Ȧ    -Any and All: Check if our list has any falsy values or is empty
       µ   -Take all our previous atoms and wrap them into one monad.
        €  -Map this new monad over a list. Since our input is an integer, this implicitly maps it over the range [1..N] (Like the 'R' atom)
         T -Get the indices of all truthy values (1's)

```

# Answer
> 0 votes
# Jelly, 10 bytes

```
2ṗx"`ḂḄf@R

```

Terribly inefficient. Try it online!

# Answer
> 0 votes
# Ruby, 54 53 48 bytes

```
->n{(1..n).reject{|x|x.to_s(2)=~/10(00)*(1|$)/}}

```

I didn't think the regex for this was going to be quite so basic.

**edit 1:** switched to reject to get rid of negation for -1.

**edit 2:** switched `match` to `=~` for -5.

# Answer
> 0 votes
# Mathematica, 69 bytes

```
Select[Range@#,FreeQ[#~IntegerDigits~2//.{x___,0,0,y___}:>{x,y},0]&]&

```

The same length:

```
Select[Range@#,#~IntegerString~2~StringDelete~"00"~StringFreeQ~"0"&]&

```

# Answer
> 0 votes
## Ruby, 53 Bytes

```
->n{(1..n).each{|n|p n if n.to_s(2).count(?0).even?}}

```

---
Tags: code-golf, sequence, base-conversion, binary
---


title: Convert English to a number

text:
# Question
Title: Convert English to a number
**Short and sweet description of the challenge:**

Based off the ideas of several other questions on this site, your challenge is to write the most creative code in any program that takes as input a number written out in English and converts it to integer form.

**Really dry, long and thorough specifications:**

* Your program will receive as input an integer in **lowercase** English between `zero` and `nine hundred ninety-nine thousand nine hundred ninety-nine` inclusive.
* It must output only the integer form of the number between `0` and `999999` and nothing else (no whitespace).
* The input will **NOT** contain `,` or `and`, as in `one thousand, two hundred` or `five hundred and thirty-two`.
* When the tens and ones places are both nonzero and the tens place is greater than `1`, they will be separated by a HYPHEN-MINUS character `-` instead of a space. Ditto for the ten thousands and thousands places. For example, `six hundred fifty-four thousand three hundred twenty-one`.
* The program may have undefined behavior for any other input.

**Some examples of a well-behaved program:**

`zero` -\> `0`
`fifteen` -\> `15`
`ninety` -\> `90`
`seven hundred four` -\> `704`
`sixty-nine thousand four hundred eleven` -\> `69411`
`five hundred twenty thousand two` -\> `520002`

# Answer
# Applescript

A silly, hacky mash-up that might upset some Cupertino/Mountain View folks, but I *think* its a creative silly, hacky mash-up.

```
set myNumber to text returned of (display dialog ¬
    "Enter number as text:" buttons {"Continue…"} ¬
    default answer "" default button 1)
tell application "Google Chrome"
    activate
    open location "https://www.google.com"
end tell
delay 5
say "ok google. " & myNumber
delay 2
tell application "System Events"
    tell application process "Google Chrome"
        set fullURL to value of text field 1 of toolbar 1 of window 1
    end tell
end tell
set AppleScript's text item delimiters to "="
display alert item 2 of text items of fullURL

```

Uses OSX text to speech to speak the text number, and google audio search to listen for it and convert it to an integer.

Requirements

* OSX
* Google chrome
* speech-recognition enabled in your google account
* volume turned up to a reasonable level

The delay timings may need to be adjusted depending on your chrome load time and google lookup time.

Example input:

Example output:
> 93 votes

# Answer
# Bash, 93 64 55 characters\*

In the fantastic `bsd-games` package that's available on most Linux operating systems, there's a small command-line toy called `number`. It turns numbers into English text, that is, it does the exact opposite of this question. It really is the exact opposite: all the rules in the question are followed by `number`. It's almost too good to be a coincidence.

```
$ number 42
forty-two.

```

Of course, `number` doesn't answer the question. We want it the other way around. I thought about this for a while, tried string parsing and all that, then realised that I can just call `number` on all 999.999 numbers and see if something matches the input. If so, the first line where it matches has twice the line number I'm looking for (`number` prints a line of dots after every number). Simple as that. So, without further ado, here's the complete code for my entry:

```
seq 0 999999|number -l|awk "/$1/{print (NR-1)/2;exit}"

```

It even short-circuits, so converting "two" is quite fast, and even higher numbers are usually decoded in under a second on my box. Here's an example run:

```
wn@box /tmp> bash unnumber.sh "zero"
0
wn@box /tmp> bash unnumber.sh "fifteen"
15
wn@box /tmp> bash unnumber.sh "ninety"
90
wn@box /tmp> bash unnumber.sh "seven hundred four"
704
wn@box /tmp> bash unnumber.sh "sixty-nine thousand four hundred eleven"
69411
wn@box /tmp> bash unnumber.sh "five hundred twenty thousand two"
520002

```

Of course, you'll need to have `number` installed for this to work.

---

\*: Yes, I know, this is not a `code-golf` challenge, but shortness is pretty much the only discerning quality of my entry, so... :)
> 35 votes

# Answer
# Javascript

```
(function parse(input) {
  var pat = "ze/on/tw/th.?r/fo/fi/ix/se/ei/ni/ten/ele".split("/");
  var num = "", last = 0, token = input.replace(/-/g, " ").split(" ");
  for(var i in token) {
    var t = token[i];
    for(var p in pat) if(t.match(RegExp(pat[p])) !== null) num += "+" + p;
    if(t.indexOf("een") >= 0) num += "+10";
    if(t.indexOf("lve") >= 0) num += "+10";
    if(t.indexOf("ty") >= 0) num += "*10";
    if(t.indexOf("dr") >= 0) { last = 100; num += "*100"; }
    if(t.indexOf("us") >= 0) {
      if(last < 1000) num = "(" + num + ")"; last = 0;
      num += "*1000";
    }
  }
  alert(eval(num));
})(prompt());

```

Do you like some `eval()`?

Run this script on your browser's console.

**Edit:** Thanks for the feedback. Bugs fixed (again).
> 13 votes

# Answer
## Python

Just to get the ball rolling.

```
import re
table = {'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,
         'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19,
         'twenty':20,'thirty':30,'forty':40,'fifty':50,'sixty':60,'ninety':90}
modifier = {'hundred':100,'thousand':1000}

while True:
    text = raw_input()
    result = 0
    tmp = 0
    last_multiplier = 1
    for word in re.split('[- ]', text):
        multiplier = modifier.get(word, 1)
        if multiplier > last_multiplier:
            result = (result+tmp)*multiplier
            tmp = 0
        else:
            tmp *= multiplier
        if multiplier != 1:
            last_multiplier = multiplier
        tmp += table.get(word,0)
    print result+tmp

```
> 7 votes

# Answer
# Perl + CPAN

Why reinvent the wheel, when it has been done already?

```
use feature 'say';
use Lingua::EN::Words2Nums;

say words2nums $_ while <>;

```

This program reads English strings from standard input (or from one or more files specified as command line arguments), one per line, and prints out the corresponding numbers to standard output.

I have tested this code using both the sample inputs from the challenge, as well as an exhaustive test suite consisting of the numbers from 0 to 999999 converted to text using the bsd-games `number` utility (thanks, Wander Nauta!), and it correctly parses all of them. As a bonus, it also understands such inputs as e.g. `minus seven` (−7), `four and twenty` (24), `four score and seven` (87), `one gross` (144), `a baker's dozen` (13), `eleventy-one` (111) and `googol` (10100).

(*Note:* In addition to the Perl interpreter itself, this program also requires the CPAN module Lingua::EN::Words2Nums. Here are some instructions for installing CPAN modules. Debian / Ubuntu Linux users may also install this module via the APT package manager as *liblingua-en-words2nums-perl*.)
> 5 votes

# Answer
# Python

A general recursive solution, with validity checking. Could be simplified for the range of numbers required, but here's to showing off I guess:

```
terms = 'zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split()
tee  = 'twenty thirty forty fifty sixty seventy eighty ninety'.split()
for t in tee:
    terms.append(t)
    for s in terms[1:10]:
        terms.append(t+'-'+s)

terms = dict(zip(terms, range(100)))

modifiers = [('hundred', 100), ('thousand', 1000), ('million', 10**6), ('billion', 10**9)]

def read_num(words):
    if len(words) == 0: return 0
    elif len(words) == 1:
        if words[0] in terms:
            return terms[words[0]]
        else:
            raise ValueError(words[0]+' is not a valid english number.')
    else:
        for word, value in reversed(modifiers):
            if word in words:
                i = words.index(word)
                return read_num(words[:i])*value+read_num(words[i+1:])

    raise ValueError(' '.join(words)+' is not a valid english number.')

while True:
    try:
        print(read_num(input().split()))
    except ValueError as e:
        print(e)

```
> 4 votes

# Answer
## VBScript 474

This is a fairly routine answer... unfortunately, so routine that @Snack pretty much posted the same process but before me.

```
i=split(REPLACE(REPLACE(inputbox(""),"lve","een"),"tho","k"))
o=split("z on tw th fo fi si se ei ni ten ele")
y=split("red *100) k )*1000 ty *10) een +10)")
z=""
p=0
for t=0 to UBOUND(i)
    s=split(i(t),"-")
    u=ubound(s)
    r=s(0)
    for x=0 to UBOUND(o)
        IF INSTR(r,o(x)) THEN
            z=z+"+"+CSTR(x)
        END IF
        IF u Then
            IF INSTR(s(1),o(x)) THEN
                z=z+CSTR(x)
            END IF
        END IF
    next
    for m=0 to UBOUND(y)
        IF INSTR(r,y(m))AND u=0 THEN
            z=z+y(m+1)
            p=p+1
        END IF
    next
next
Execute("MSGBOX "+String(p,"(")+z)

```
> 2 votes

# Answer
## Haskell

Similar to other recursive solutions I guess, but I took the time to make it clean.

Here is the complete source with all explanations : http://ideone.com/fc8zcB

```
-- Define a type for a parser from a list of tokens to the value they represent.
type NParse = [Token] -> Int

-- Map of literal tokens (0-9, 11-19 and tens) to their names.
literals = [
        ("zero", 0), ("one", 1), ("two", 2), ("three", 3), ("four", 4), ("five", 5), ("six", 6), ("seven", 7), ("eight", 8), ("nine", 9),
        ("eleven", 11), ("twelve", 12), ("thirteen", 13), ("fourteen", 14), ("fifteen", 15), ("sixteen", 16), ("seventeen", 17), ("eighteen", 18), ("nineteen", 19),
        ("ten", 10), ("twenty", 20), ("thirty", 30), ("fourty", 40), ("fifty", 50), ("sixty", 60), ("seventy", 70), ("eighty", 80), ("ninety", 90)
    ]

-- Splits the input string into tokens.
-- We do one special transformation: replace dshes by a new token. Such that "fifty-three" becomes "fifty tens three".
prepare :: String -> [Token]

-- Let's do the easy stuff and just parse literals first. We just have to look them up in the literals map.
-- This is our base parser.
parseL :: NParse
parseL [tok] = case lookup tok literals of
    Just x -> x

-- We're going to exploit the fact that the input strings have a tree-like structure like so
--                    thousand
--          hundred             hundred
--      ten       ten       ten         ten
--    lit   lit lit  lit   lit  lit    lit  lit
-- And recursively parse that tree until we only have literal values.
--
-- When parsing the tree
--       thousand
--     h1       h2
-- The resulting value is 1000 * h1 + h2.
-- And this works similarly for all levels of the tree.
-- So instead of writing specific parsers for all levels, let's just write a generic one :

{- genParse ::
    NParse      : the sub parser
    -> Int      : the left part multiplier
    -> Token    : the boundary token
    -> NParse   : returns a new parser -}
genParse :: NParse -> Int -> Token -> NParse
genParse delegate mul tok = newParser where
    newParser [] = 0
    newParser str = case splitAround str tok of
        -- Split around the boundary token, sub-parse the left and right parts, and combine them
        (l,r) -> (delegate l) * mul + (delegate r)

-- And so here's the result:
parseNumber :: String -> Int
parseNumber = parseM . prepare
    where   -- Here are all intermediary parsers for each level
    parseT = genParse   parseL  1       "tens"       -- multiplier is irregular, because the fifty in fifty-three is already multiplied by 10
    parseH = genParse   parseT  100     "hundred"
    parseK = genParse   parseH  1000    "thousand"
    parseM = genParse   parseK  1000000 "million" -- For fun :D

test = (parseNumber "five hundred twenty-three thousand six hundred twelve million two thousand one") == 523612002001

```
> 1 votes

# Answer
# Common Lisp, 94

```
(write(cdr(assoc(read-line)(loop for i to 999999 collect(cons(format()"~r"i)i)):test #'equalp)))

```

Number to text conversion is built in to CL, but not the other way around. Builds a reverse mapping for the numbers and checks the input on it.
> 0 votes

---
Tags: popularity-contest
---