title: Find the haystack in the needles

text:
# Question
Title: Find the haystack in the needles
In a twist on finding a needle in a haystack, you need to find the largest contiguous haystack containing **exactly** **one** **needle**. Note that you cannot connect cells on diagonals, only left/right/up/down.

## Input

An array (or a number of user input lines, your pick) of `'N'` (needles) and `'#'` (hay) characters. Input only contains those two characters, and must contain at least one of each. For example:

```
N#N#N
#NN##
###N#
N##N#

```

## Output

The size of the largest possible valid haystack. For our example, we would output 11 (there are 11 pieces of hay, and one needle).

```
   #
#  ##
###N#
 ## #

```

This is , so shortest code wins. Standard loophole restrictions apply.

## Test Cases

*Input on left, possible maximal haystack on right*

**Case 1: 4**

```
N##    ##
NN#     #
#NN     N
#N#     #

```

**Case 2: 7**

```
###   ###
N#N    #
NNN    N
###   ###

```

**Case 3: 10**

```
N###N    ###
#N#N#   #N#
#N#N#   # #
N###N    ###

```

**Case 4: 10**

```
N#N#N
#N#N#   # # #
##N##   ##N##
#N#N#   # # #
N#N#N

```

**Case 5: 1**

```
NN#NN
NNNNN
#NNN#   #N
NN#NN

```

# Answer
> 4 votes
# JavaScript (ES6), 152 bytes

```
s=>[...s].map((n,i)=>n>'M'&&(a=[...s],a[i]=r=1,a.map(_=>a.map((c,j)=>c=='#'&&a[j+1]|a[j-1]|a[j+l]|a[j-l]?a[j]=++r:0)),o=r>o?r:o),o=0,l=~s.search`
`)|o-1

```

## Explanation

For each needle in the input, sets the needle to a part of the haystack (represented by setting it to a non-zero number) and continuously checks hay cells. If hay contains an adjacent part of the hay stack, also sets it part of the haystack and increments the size of the hay stack. Outputs the highest result.

```
var solution =

s=>
  [...s].map((n,i)=>n>'M'&&(          // for each needle in s at index i
      a=[...s],                       // a = array of each character in s
      a[i]=1,                         // set the starting needle to 1 (haystack)
      r=0,                            // r = haystack size starting from this needle
      a.map(_=>                       // loop to ensure the complete haystack is found
        a.map((c,j)=>                 // for each cell c at index j
          c=='#'&&                    // if the current cell is hay
          a[j+1]|a[j-1]|a[j+l]|a[j-l] // and any adjacent cells are part of the haystack
          ?a[j]=++r:0                 // add the current cell to the haystack, increment r
        )
      ),
      o=r>o?r:o                       // o = max of o and r
    ),
    o=0,                              // o = final output, initialise to 0
    l=~s.search`
`                                     // l = line length of s
  )
  |o                                  // return o
```

```
<textarea id="input" rows="6" cols="40">N#N#N
#N#N#
##N##
#N#N#
N#N#N</textarea><br />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 4 votes
## Ruby, 207

```
->a{d=->b{0...b.size}
f=c=s=->y,x{(d[a]===y&&d[a[0]]===x&&!f[y][x]&&a[y][x]==c)?(c,f[y][x]=?#,1
1+s[y,x-1]+s[y,x+1]+s[y-1,x]+s[y+1,x]):0}
d[a].map{|y|d[y].map{|x|f,c=a.map{|b|b.map{p}},?N
s[y,x]}.max}.max-1}

```

This is an anonymous function that takes in the input as an array of arrays. Usage:

```
f=->a{......}

f["
N##
NN#
#NN
#N#
".strip.split.map(&:chars)] # => 4

```

The proc named `s` recursively finds the size of the haystack with needle at specific coordinates and is called on each needle in the haystack.

---
Tags: code-golf, grid, graph-theory
---


title: Reading a timeline

text:
# Question
Title: Reading a timeline
Inspired by Draw a timeline.

Given a timeline of events, output the date for each event.

A timeline will be given in the form

```
    2000
--AF-C-------E--D---B--

```

Where the first line shows a known point in time. The known year is always the character below the first digit of the known year

You may assume:

* On the timeline itself, each character represents one year.
* There will always be at least one event
* The events don't have to be in order
* You may assume every character in the range between `A` and the furthest character is present
* There will be at most 26 events
* The known point will not have any padding to the right
* There can be negative numbers in both the known point and the output
* You will not have to handle numbers bigger than 2^32
* You will not have to handle ranges bigger than 2^8
* You can take input as lowercase letters instead of uppercase

You should write a program that takes a timeline in this form and outputs the key dates in order (A, B, C, D...)

You may output in a convenient form but you must take input in the format given.

Test cases:

```
    2000
--AF-C-------E--D---B--
[1998, 2016, 2001, 2012, 2009, 1999]

     10
--C-AB--D
[9, 10, 7, 13]

     0
--ABCDEFG--
[-3, -2, -1, 0, 1, 2, 3]

          5
--ABCDEFG--
[-3, -2, -1, 0, 1, 2, 3]

```

# Answer
# Pyth, 16 bytes

Takes input as lowercase letters instead of uppercase.

```
VS@GJw+-sz/zdxJN

```
> 1 votes

# Answer
# 05AB1E, ~~19~~ 18 bytes

Code:

```
ð¢>UágF²N>.bkX-¹+,

```

Explanation:

```
ð¢                   # Count the number of spaces before the year starts
  >                  # Increment by 1
   U                 # Pop and store this into X
    á                # Keep the alphabetic characters of the second input
     g               # Take the length
      F              # For N in range(0, length), do...
       ²             #   Take the second input
        N>           #   Push N and increment by 1
          .b         #   Converts 1 to A, 2 to B, etc.
            k        #   Find the index of that letter in the second input
             X       #   Push X
              -      #   index - X
               ¹     #   Get the first input, which contains the year
                +    #   Add to the difference of the index
                 ,   #   Pop and output the sum

```

Try it online!

Uses **CP-1252** encoding.
> 2 votes

# Answer
# JavaScript (ES6), 72

```
(a,b,r=[])=>[...b].map((x,i)=>r[parseInt(x,36)-10]=+a+i-a.search`\\d`)&&r

```

**Test**

```
f=(a,b,r=[])=>[...b].map((x,i)=>r[parseInt(x,36)-10]=+a+i-a.search`\\d`)&&r

console.log=x=>O.textContent+=x+'\n'

;[['    2000','--AF-C-------E--D---B--'],
['     10','--C-AB--D'],
['     0','--ABCDEFG--'],
['          5','--ABCDEFG--']]
.forEach(t=>{
  var a=t[0],b=t[1],r=f(a,b)
  console.log(a+'\n'+b+'\n'+r+'\n')
})
```

```
<pre id=O></pre>
```
> 1 votes

# Answer
# Bash + coreutils, 68

Line 1 is input as a quoted command-line option and line 2 is input from STDIN:

```
s="${1//[0-9]}"
fold -1|nl -v$[$1-${#s}]|sort -k2|sed '/-$/d;s/.$//'

```
> 1 votes

# Answer
## Perl, 58 + 1 = 59 bytes

```
/\d/;$b=<>;for$c(A..Z){($z=index$b,$c)>-1&&say$_+$z-$-[0]}

```

Breakdown:

```
/\d/;                    # Match first digit in input string, this will set $-[0]
$b=<>;                   # Read next line (--A--CB--...) into $b
for $c (A..Z){           # Iterate over A, B, C, ... Z
  ($z=index$b,$c) >-1 && # If the character is found inside $b
  say $_+$z-$-[0]        #   then print
}

```

Requires `-n` and the free `-M5.010`:

```
# Added line breaks for each test case
$ perl -nE'/\d/;$b=<>;for$c(A..Z){($z=index$b,$c)>-1&&say$_+$z-$-[0]}' tl
1998
2016
2001
2012
2009
1999

9
10
7
13

-3
-2
-1
0
1
2
3

-3
-2
-1
0
1
2
3
$ cat tl
    2000
--AF-C-------E--D---B--
     10
--C-AB--D
     0
--ABCDEFG--
          5
--ABCDEFG--

```
> 1 votes

# Answer
## Pyth, 22 bytes

```
V+r\AJeSKwJ+xKN-izT/zd

```

No I did not write this before I posted the challenge.

Explanation:

```
                       - autoassign z = input()
 +r\AJeSKwJ            -  create range of letters
        Kw             -      autoassign K = input()
      eS               -     sorted(K)[-1] (get the biggest character)
     J                 -    autoassign J = ^
  r\A                  -   range("A", ^)
 +        J            -  ^ + J
V                      - for N in ^: V
               -izT/zd - Get the number at the start
                izT    -   int(z, 10)
               -       -  ^-V
                   /zd -   z.count(" ")
           +           - V+^
            xKN        -  K.index(N)

```

Try it here
> 0 votes

# Answer
# Python 3, 118

Man, today is the day of long Python answers.

```
def f(p,l):o=sum(x<'0'for x in p);e={x:i-o+int(p[o:])for i,x in enumerate(l)if'@'<x};return list(map(e.get,sorted(e)))

```
> 0 votes

# Answer
## Perl, ~~80~~ ~~79~~ ~~71~~ 67 bytes

```
($a=<>)=~/\d/;$b=<>;say$a+$_-$-[0]for grep{$_+1}map{index$b,$_}A..Z

```

Thanks to @dev-null for 12 bytes!

```
($a=<>)=~/\d/;  # read first line of input, find position of first digit
                # (saved in the $- variable)
$b=<>;          # read the second line
                                           A..Z  # generate range 'A','B',...
                            map{index$b,$_}      # find index for each
                  grep{$_+1}                     # select only those != -1
              for                                # foreach of remaining...
say$a+$_-$-[0]                                   # calculate proper date

```
> 0 votes

# Answer
## Seriously, 40 bytes

```
' ,c,;)l@;±)@-(x@;╗@Z`i3╤τ+@┐`MX╜ú∩S`└`M

```

Try it online!

Explanation to come later after further golfing.
> 0 votes

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


# Question
Title: Does the water ultimately reach the tank?
In the ASCII art world, there is water, hash walls and letter mechanisms.

You are in a room made up of hash walls (`#` signs):

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

```

You install an S water source (`S` sign) and an E water tank (`E` sign) which can receive water from any direction, but you only have one S source and one E tank.

```
#######
#  S  #
#     #
#     #
# ### #
#  E  #
#######

```

So you have to select wisely where to place the source. That's where you pull off your skills.

## The task

You get an input consisting of a string representing a room with the source and the tank:

```
#######
#  S  #
#     #
#     #
# ### #
#  E  #
#######

```

You have to find out if the water ultimately reaches the tank. The water flows down, if possible, else to the left and right, if possible. The water doesn't accumulate because it doesn't go up.

So, for the above input, the result is:

```
#######
#  *  #
#  *  #
#*****#
#*###*#
#**O**#
#######

```

The water happily reaches the tank, so you must output a truthy value.

But if the water doesn't reach the tank:

```
#######
#S    #
#     #
#  E  #
# ### #
#     #
#######

#######
#*    #
#*    #
#* X  #
#*### #
#*****#
#######

```

Then you must output a falsy value.

Write a program to decide whether the water ultimately reaches the tank. Your code should be as short as possible.

## Assumptions

* Assume that the input is always valid (the entire room is an enclosed rectangular region with the S and E).
* Assume there is only one room provided as input.

## Test Cases

Your program should return a truthy value for the following test cases:

```
#######
#  S  #
#     #
#     #
# ### #
#  E  #
#######

#######
#  S  #
#     #
#  E  #
#     #
#     #
#######

#######
#     #
#     #
# SE  #
# ### #
#     #
#######

###############################################
#                      S                      #
#                                             #
#                                             #
#                                             #
#               ###############               #
#                                             #
#  ##################     ##################  #
#                                             #
#                                             #
#                    #####                    #
#                      E                      #
###############################################

#######
#  S  #
#     #
#     #
# ### #
#   # #
### ###
## E ##
#     #
#######

```

But a falsy value for the following test cases:

```
#######
#S    #
#     #
#  E  #
# ### #
#     #
#######

#######
#     #
# SE  #
#     #
#     #
#     #
#######

#######
#     #
#  E  #
#     #
#  S  #
#     #
#######

####################################
#                                  #
#                                  #
#                                  #
#S             #                  E#
####################################

```

The second to last room in the True category and the last room in the False category were shamelessly ~~stolen~~ borrowed from ~~Koth: Jump and Run~~ by Manu (who deleted the sandbox post).

The last room in the True category is from Martin Buttner's answer in Retina.

# Answer
> 14 votes
# Snails, 20 bytes

```
\S{d(=\#n)?^#},!(t\E

```

Prints `0` for the falsey value and `1` for the truthy value.

Try it online!

* `\S` matches `S` at the start
* `d` sets direction to down
* `{...},` matches the stuff in braces 0 or more times
* `=\#` is an assertion which succeeds if there is a `#` char ahead of the snail, but does not move it
* `n` turns 90 degrees in either direction
* `(...)?` matches the pattern in parentheses 0 or 1 times
* `\ ` matches a space and moves the snail onto it
* `!(...` is a negative assertion
* `t` teleports to any unmatched square in the grid
* `\E` matches `E`

# Answer
> 11 votes
## Slip, 20 + 2 = 22 bytes

```
S>( ^4|^4(?|`#)^T)*E

```

So Slip's still as broken as ever, but for once this was a challenge it could actually do. It was never really designed to be that golfy though, so it'll never beat Snails at anything :P

Needs the `r` flag (no repeating cells) to terminate.

Try it online. Output is the path taken for truthy, empty for falsy.

```
S                 Match S
>                 Rotate pointer downward
(                 Either...
 <space>^4          Match a space and point downwards
 |                  or
 ^4                 Point downwards
 (?|`#)             Match # below then reset pointer
 ^T                 Either turn left or right
)*                ... 0+ times
E                 Match E

```

# Answer
> 6 votes
## Retina, 87 bytes

Byte count assumes ISO 8859-1 encoding.

```
+mT`E `S`(?<=^(?(1)!)(?<-1>.)*S.*¶(.)*)[E ]|.?S(?=(.)*¶.*#(?<-2>.)*(?(2)!)$)[E ]?
M`E
0

```

Try it online!

As much as 2D string processing is possible in Retina (or .NET regex in general), it's not exactly concise...

### Explanation

```
+mT`E `S`(?<=^(?(1)!)(?<-1>.)*S.*¶(.)*)[E ]|.?S(?=(.)*¶.*#(?<-2>.)*(?(2)!)$)[E ]?

```

This is a flood-fill which marks all the cells that are reached by water with `S`. It does so by matching the characters that can be reached and then transliterating them to `S` with `T`-mode. This flood-fill goes through both spaces and `E`. The `+` at the beginning repeats this until the output stops changing.

As for the actual regex is contains two separate cases:

```
(?<=^(?(1)!)(?<-1>.)*S.*¶(.)*)[E ]

```

This matches a space or `E` which is exactly one cell below an `S`. The vertical matching is done by counting the prefix on the current line using balancing groups so we can ensure that the horizontal position is the same. This one takes care of falling water.

```
.?S(?=(.)*¶.*#(?<-2>.)*(?(2)!)$)[E ]?

```

This is very similar: it matches an `S` and if available the character before and after it, provided that the character directly beneath the `S` is a `#`. This takes care of water spreading along the ground.

When we're done it's very easy to determine if the water reached `E`. If it did, then `E` has been removed from the string in the flood-fill, and if not the `E` is still there. So let's count the number of `E`s:

```
M`E

```

But now that's `0` (which I'd consider falsy) for truthy test cases and `1` (which I'd consider truthy) for falsy test cases. We can invert this very easily by counting the number of `0`s in this result:

```
0

```

Done.

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


title: Chain words crossword-style

text:
# Question
Title: Chain words crossword-style
# The challenge

Given a list of words `["Programming", "Puzzles", "Code", "Golf"]` output the words crossword-style:

```
      P r o g r a m m i n g
      u
      z
      z
  G   l
C o d e
  l   s
  f

```

# The Algorithm

* You have to process the list in the given order.
* The words are printed in alternating orientations, starting **horizontally**.
* The two words intersect at the first letter in the first word which is also present in the second word. If this letter occurs multiple times in the seond word, take the first one.

**Example**:
`["no", "on"]` becomes:

```
o
n o

```

and **not**

```
n o
  n

```

# Additional notes

* Adjacent words in the list will have at least one common letter. `["Hi", "there"]` is not a valid input.
* Words will never collide. There will always be enough space to print the a word at the first possible intersection. `["Hello", "there", "end", "hello"]` is not a valid input
* The matching is case-sensitive.
* Words can expand to the left and to the top.
* The letters of the horizontal words have to be separated by one space.
* The input list will contain at least two words.
* All words will match the regex: `[A-Za-z]+`
* You may print as many trailing whitespaces or newlines as you want, as long as the words are correctly chained.
* On the other hand you may not add additional leading whitespaces. The word which floats to the left the most has zero leading spaces, the other lines have so many leading spaces that it all lines up correctly.
* You program has to be able to deal with an arbitrary amount of words

# Rules

# Test cases

Input list on the first line, output starts on the second line.

```
["Stack", "Exchange"]
    E
    x
    c
    h
S t a c k
    n
    g
    e

```

```
["This", "site", "graduated", "finally"]
    f
    i       s
    n   T h i s
g r a d u a t e d
    l       e
    l
    y

```

**Happy Coding!**

# Answer
# JavaScript (ES6) 253

As an anonymous function with an array parameter

```
z=>(z.map((w,i)=>(i&&[...p].some((c,j)=>~(k=w.search(c))?i&1?[y-=k,x+=j]:[y+=j,x-=k]:0),[p=w,x<t?t=x:x,y<u?u=y:y]),t=u=x=y=0).map(([w,x,y],i)=>{x-=t,y-=u;for(c of w)(o[y]=o[y]||[])[x]=c,i&1?y++:x++},o=[]),o.map(r=>[...r].map(x=>x||' ').join` `).join`
`)

```

```
F=z=>(z.map((w,i)=>(i&&[...p].some((c,j)=>~(k=w.search(c))?i&1?[y-=k,x+=j]:[y+=j,x-=k]:0),[p=w,x<t?t=x:x,y<u?u=y:y]),t=u=x=y=0).map(([w,x,y],i)=>{x-=t,y-=u;for(c of w)(o[y]=o[y]||[])[x]=c,i&1?y++:x++},o=[]),o.map(r=>[...r].map(x=>x||' ').join` `).join`
`)

// Less golfed
F=z=>(
  z.map( // Step 1, find intersection points and relative position
    (w,i)=>(
      i && // for each word after thw first, find position respect the previous word
      [...p].some((c,j)=> // scan prec word using .some to exit at the first intersection found
         ~(k=w.search(c)) // search current char of p inside w
         ?i&1 // calc position, odd is vertical, even is horizontal
           ?[y-=k, x+=j] // returning an array so to have a truthy value
           :[y+=j, x-=k] // returning an array so to have a truthy value
         :0 // false = not found, continue the scan
      ),
      [p=w, // set preceding word
       x<t?t=x:x, // keep trace of min x
       y<u?u=y:y  // keep trace of min y
      ] // meanwhile, return word, x and y to be used in next step
    ), t=u=x=y=0 // initializations
  )
  .map(([w,x,y],i)=>{ // Step 2, put char into the output array
      x-=t,y-=u; // normalize position respect to min values
      for(c of w) // for each char in word, set in the output array at the right place
        (o[y]=o[y]||[])[x]=c,
        i&1?y++:x++ // increment x or y, again odd is vertical, even is horizontal
    }, o=[] // initialization of output array
  ),
  // Step 3, add the missing spaces and newlines
  o.map(r=>[...r].map(x=>x||' ').join` `).join`\n`
)

O.textContent=F(["This", "site", "graduated", "finally"])
```

```
<pre id=O></pre>
```
> 3 votes

# Answer
# ANSI C, 385 ~~390~~ Characters

```
int N,a=1,x,y,d=1,u,k,l;int main(int c,char**v){for(;a<c;)N+=strlen(v[a++]);int H=N*2,W=N*4,m=H,n=N,q=m,w=n;char*p,F[W][H],*o;memset(F,32,W*H);for(a=1;a<c;a++){q=(x=m)<q?m:q;w=(y=n)<w?n:w;m=-1;for(p=v[a];*p;p++){F[x][y]=*p;if(m<0&&a<c-1&&(o=strchr(v[a+1],*p))){u=o-v[a+1];m=d?x:x-u*2;n=d?y-u:y;}if(d)x+=2;else y++;}d=!d;}for(l=w;l<H;l++){for(k=q;k<W;)putchar(F[k++][l]);putchar(10);}}

```

Call it like this: `./crossword This site graduated finally`

Ungolfed version:

```
int N,a=1,x,y,d=1,u,k,l;
int main(int c, char **v) {
    for(;a<c;)
        N+=strlen(v[a++]);
    int H = N*2, W = N*4, m = H, n = N, q=m, w=n;
    char *p,F[W][H], *o;
    memset(F, 32, W*H);
    for (a=1; a < c; a++) {
        q=(x=m)<q?m:q;
        w=(y=n)<w?n:w;
        m=-1;
        for (p=v[a]; *p; p++) {
            F[x][y] = *p;
            if (m<0&&a<c-1&&(o = strchr(v[a+1], *p))) {
                u = o-v[a+1];
                m = d ? x : x-u*2;
                n = d ? y-u : y;
            }
            if (d) x+=2; else y++;
        }
        d=!d;
    }
    for (l = w; l < H; l++) {
        for (k = q; k < W;)
            putchar(F[k++][l]);
        putchar(10);
    }
}

```

Thank you tucuxi for the tips!
> 3 votes

---
Tags: code-golf, string, grid, crossword
---


title: Bit Manipulator/Reader

text:
# Question
Title: Bit Manipulator/Reader
# Introduction

There are often times that we have challenges which require communication of some sort (such as in team KOTH), where density of information may be more important than density of code. There are a number of compression techniques that can allow us to convey more information in less space, but for simple data flags, sometimes flipping bits themselves can be a great way to achieve desired data density.

# Challenge

Write a program or function in the language of your choice that can take an integer to be manipulated (must handle at least 32 bit), a start bit position (integer), a number of bits to manipulate (integer), and a manipulation mode (integer), and returns the original integer manipulated in the way specified below. In addition, write a second program or function that serves as a bit reader, taking in an integer, a start bit position (integer), and a number of bits to read (integer), and returns an integer consisting of just that group of bits shifted down, and every other bit as `0`.

Some further details and rules are as follows:

* The first argument will be an integer, signed or unsigned.
* The second argument will be the bit position to start from (counting from least significant bit, zero-indexed).
* The third argument will be the number of bits to be read/manipulated, moving up in bit significance from the start bit. If not given as an argument, the value should default to `1`.
* The fourth argument (manipulator only) will be the manipulation mode:
    + When passed a `0` or null value, the behavior will be to flip (xor) all of the specified bits (default if no value given).
    + When passed a positive value, the behavior will be to set all of the specified bits to `1`.
    + When passed a negative value, the behavior will be to set all of the specified bits to `0`.
* The return value of the manipulator function should be the initial integer with the above bit manipulations applied.
* The return value of the reader function should be the start bit shifted to the least significant bit, and every bit beyond the length of bits set to `0`.
* Assume that only valid input will be used. Don't worry about error handling.

The winner will be determined by the shortest sum of the length of both programs/functions. They will be selected in at least 7 days, or if/when there have been enough submissions. In the event of a tie, the answer that came earlier wins.

# Examples

Here's a few examples of input and output that your code should be able to handle. I've golfed both functions in JavaScript that I can release if people want to test their results, but otherwise I'll probably wait a few days before I post it up.

### Manipulator

```
F(0, 2) => 4 (0 => 100)

F(4, 2) => 0 (100 => 0)

F(0, 2, 4) => 60 (0 => 111100)

F(170, 2, 4, 0) => 150 (10101010 => 10010110)

F(170, 2, 4, 1) => 190 (10101010 => 10111110)

F(170, 2, 4, -1) => 130 (10101010 => 10000010)

F(0, 31) => (+/-)2147483648 (0 => 10000000000000000000000000000000)

```

### Reader

```
F(0, 2) => 0 (0 => 0)

F(4, 2) => 1 (100 => 1)

F(60, 2, 4) => 15 (111100 => 1111)

F(170, 2, 4) => 10 (10101010 => 1010)

F((+/-)2147483648, 0, 32) => (+/-)2147483648 (10000000000000000000000000000000 => 10000000000000000000000000000000)

```

# Answer
> 4 votes
# JavaScript (ES6), 75 bytes

*Saved 4 bytes thanks to @Mwr247*

**Manipulator: (47 bytes)**

```
(a,b,c=1,d=0,z=(1<<c)-1<<b)=>d?d<0?a&~z:a|z:a^z

```

**Reader: (28 bytes)**

```
(a,b,c=1)=>a>>b&(1<<c-1)*2-1

```

## How it works

**Manipulator**

The first thing we need to do is figure out the number that has `c` bits set, starting at the `b`th bit. Possibly the best way to do this is `z=(1<<c)-1<<b`, which works like so:

```
b  c    1<<c     -1     <<b    z
2  1      10     01    0100    4
2  2     100    011   01100   12
2  3    1000   0111  011100   28
1  4   10000  01111  011110   30

```

Now we take into account `d`. For case `0`, we flip the bits with `a^z`; for case `1`, we set the bits to 1 with `a|z`; for case `-1`, we set the bits to 0 with `a&~z`.

# Answer
> 3 votes
# Python 2, 89 bytes

Done in a method similar to ETH. Python lambdas aren't as short as in JS. Also, default parameter values can't depend on other parameters.

**Manipulator, 63 bytes**

```
def f(a,b,c=1,d=0):
    z=2**c-1<<b;return[a^z,a|z,a&~z][cmp(d,0)]

```

**Reader, 26 bytes**

```
lambda a,b,c=1:a>>b&2**c-1

```

**Try it online**

---
Tags: code-golf, math, bitwise
---


title: Leaping Lizards!

text:
# Question
Title: Leaping Lizards!
Suppose we define a simple program that takes an array L of natural numbers with some length N and does the following:

```
i=0                 #start at the first element in the source array
P=[]                #make an empty array
while L[i]!=0:      #and while the value at the current position is not 0
    P.append(L[i])  #add the value at the current position to the end of the output array
    i=(i+L[i])%N    #move that many spaces forward in the source array, wrapping if needed
return P            #return the output array

```

Every such program will either run forever or will eventually terminate, producing a list of positive integers. Your job is to, given a list P of positive integers, produce a shortest list, L, of natural numbers that terminates and produces P when plugged into the previous program.

Such a list always exists, since one can just add `P[i]-1` zeros after each `P[i]` in the list, then one final 0, and it will produce the original list. For example, given `[5,5]`, one solution is `[5,0,0,0,0,5,0,0,0,0,0]`. However, `[5,0,5]` is much shorter, so the automatic solution is not a valid one for your program.

```
[5,6]->[5,6,0,0]
[5,7]->[5,0,0,0,0,7,0,0]
[5,6,7]->[5,6,0,7]
[5,6,8]->[5,0,8,0,0,6,0,0,0]
[1,2,3,4]->[1,2,0,3,0,0,4,0]
[1,2,1,2]->[1,2,0,1,2,0,0]
[1,3,5,7]->[1,3,0,0,5,0,0,0,0,7]
[1,3,5,4]->[1,3,4,0,5,0,0]

```

Input is a list of positive integers(in some format you can specify) and output should be in the same format. List and integer size can be up to 2^16. This is code golf, so shortest program in bytes wins!

# Answer
> 6 votes
## Python 3, ~~109 102 100 95~~ 93 bytes

```
def f(L,k=1,i=0):
 P=[0]*k
 for x in L:x=P[i]=P[i]or x;i=(i+x)%k
 return P[i]and f(L,k+1)or P

```

A recursive solution. Call it like `f([1,2,3,4])`. Watch it pass all test cases.

We start with `k=1` (length of output) and `i=0` (position in output), and make a list `P` with `k` zeros. Then we iterate along the elements `x` of `L`, updating `P[i]` to `P[i]or x` (so `P[i]` keeps its value if it's nonzero) and `i` to `(i+P[i])%k`. After that, we check that the final value of `P[i]` is zero, incrementing `k` if it's not, and return `P`.

If at any point of the algorithm `P[i]` is already nonzero, it enters a loop going around some of the nonzero values of `P`, and ends up at a nonzero value; then we recurse.

---
Tags: code-golf, number
---


title: LaTeX Table Generator

text:
# Question
Title: LaTeX Table Generator
Write a function or program which, given a number of lines and columns, generates a corresponding `tabular` environment for LaTeX with no data in it.

### Table format and `tabular` Environment

Here is an example of a table with 2 rows and 4 columns:

As you can see, we do not count the first row nor do we count the first column: those are for the labels of the table.

The top left corner is also "missing", in that there is no border around it.

The corresponding LaTeX's code to generate this table is the following:

```
\begin{tabular}{|c|c|c|c|c|}
    \cline{2-5}
    \multicolumn{1}{c|}{} & & & & \\
    \hline
    & & & & \\
    \hline
    & & & & \\
    \hline
\end{tabular}

```
* There are as many `c` in the first line as there are **total** columns (that is, 1 more than the number of columns given as input). These `c` are separated by `|` (and there are `|` on both the extreme left and extreme right too).
* The first horizontal separator is generated by `\cline{2-X}` where X is the index of the last column (starting from 1).
* The first element of the first row is always `\multicolumn{1}{c|}{}` (this removes the borders of the top left corner).
* Each row has `C` `&`, `C` being the number of columns given as input. Each line ends with `\\`.
* Each row is followed by a `\hline`.

### Formatting details

* You must indent everything between the `begin{tabular}{...}` and `\end{tabular}` tags with **4 spaces**.
* The `&`'s are separated with exactly one space on each row. The first one of the row does not have an extra space before it (since it already has 4 spaces before it). Note that this is not true for the first row, where the first `&` has a space before it because of the `\multicolumn` element.
* `\\` is separated from the last `&` by a space.
* Each `\hline` and row description is on its own new line.

### Input

Input is a couple of two integers representing the number of columns and the number of rows. Note that this is the number of columns and rows excluding the very first row and very first column.

You may assume that the row and column inputs will always be at least 1, and less than 1024.

Those two numbers can be taken whichever way is most appropriate in your language (two args, a list, etc.).

### Output

The output is a string of the LaTeX code that generates a table with the appropriate number of rows and columns. This can be returned from a function or outputted to STDOUT.

A trailing new line is allowed after the `\end{tabular}`. Trailing spaces are not allowed at the end of any line.

### Test cases

```
Input: (1,1)
Output:
\begin{tabular}{|c|c|}
    \cline{2-2}
    \multicolumn{1}{c|}{} & \\
    \hline
    & \\
    \hline
\end{tabular}

Input: 2 rows, 4 columns
Output:
\begin{tabular}{|c|c|c|c|c|}
    \cline{2-5}
    \multicolumn{1}{c|}{} & & & & \\
    \hline
    & & & & \\
    \hline
    & & & & \\
    \hline
\end{tabular}

```

### Scoring

This is , so the shortest code in bytes `\emph{wins}`.

# Answer
> 2 votes
# JavaScript (ES6), ~~172~~ 170 bytes

```
a=>b=>`\\begin{tabular}{${'|c'[r='repeat'](++b)}|}
    \\cline{2-${b--}}
    \\multicolumn{1}{c|}{} ${('& '[r](b)+`\\\\
    \\hline
    `)[r](a+1).trim()}
\\end{tabular}`

```

Called as `F(a)(b)` (credit to Patrick Roberts for finding this method)

Would have been much messier if not for template strings. Originally came in at 200, when I had a separate repeat for the multicolumn `&`'s, but cut it down a good amount by combining them and using `trim` to get rid of the final unneeded indentation.

# Answer
> 2 votes
# Python 2, 197 bytes

This solution uses string formatting to reduce repetition. Each string component is assembled, then placed within the template. It is tricky to use so many backslashes in Python strings. I used the raw string `r'\\'` and multi-line `'''blah \n blah'''` string techniques here.

```
def a(d,e):
 c='c|'*e;b='& '*e+r'\\';g=' '*4+b+'\n    \\hline\n';f=g*d;h='{tabular}'
 return r'''\begin%s{|c|%s}
    \cline{2-%s}
    \multicolumn{1}{c|}{} %s
    \hline
%s\end%s'''%(h,c,e+1,b,f,h)

```

Before the minifier, it looks like this:

```
def latextable(height, width):
    columns = 'c|' * width;
    linespec = '& ' * width + r'\\';
    line = ' '*4 + linespec + '\n    \\hline\n';
    block = line * height;
    mode = '{tabular}'
    return r'''\begin%s{|c|%s}
    \cline{2-%s}
    \multicolumn{1}{c|}{} %s
    \hline
%s\end%s''' % (mode, columns, width+1, linespec, block, mode)

print latextable(1, 1)
print latextable(2, 4)

```

The output tests:

```
\begin{tabular}{|c|c|}
    \cline{2-2}
    \multicolumn{1}{c|}{} & \\
    \hline
    & \\
    \hline
\end{tabular}
\begin{tabular}{|c|c|c|c|c|}
    \cline{2-5}
    \multicolumn{1}{c|}{} & & & & \\
    \hline
    & & & & \\
    \hline
    & & & & \\
    \hline
\end{tabular}

```

As a side note, I wrote a latex macro processor like this to format my thesis. I think I spent longer on developing that macro processor than on writing the words...

# Answer
> 1 votes
**C#, 248 byte**

```
string t(int r,int c){string i="\r\n    ",d="",q="",m;for(int j=0;j++<c;){d+="c|";q+="& ";}q+=$"\\\\{i}\\hline";m=@"\begin{tabular}{|c|"+d+"}"+i+@"\cline{2-"+(c+1)+"}"+i+@"\multicolumn{1}{c|}{} "+q;for(;r-->0;)m+=i+q;return m+"\r\n\\end{tabular}";}

```

Tester:

```
using System;
class Table
{
    static int Main()
    {
        var x = new Table();
        Console.WriteLine(x.t(1,1));
        Console.WriteLine(x.t(2,4));
        Console.Read();
        return 0;
    }
    string t(int r,int c){string i="\r\n    ",d="",q="",m;for(int j=0;j++<c;){d+="c|";q+="& ";}q+=$"\\\\{i}\\hline";m=@"\begin{tabular}{|c|"+d+"}"+i+@"\cline{2-"+(c+1)+"}"+i+@"\multicolumn{1}{c|}{} "+q;for(;r-->0;)m+=i+q;return m+"\r\n\\end{tabular}";}

    string tab(int row, int col){
        string i="\r\n    ",sc="",sr="",msg;
        for(int j=0;j++<col;){sc+="c|";sr+="& ";}
        sr+=$"\\\\{i}\\hline";
        msg=@"\begin{tabular}{|c|"+sc+"}"+i+@"\cline{2-"+(col+1)+"}"+i+@"\multicolumn{1}{c|}{} "+sr;
        for(;row>0;)msg+=i+sr;
        return msg+"\r\n\\end{tabular}";
    }
}

```

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


title: Find the different letter

text:
# Question
Title: Find the different letter
You may have seen puzzles like this:

> Find the `0`:
> `OOOOOOOOOOOOOOOOOOOO0OOOOOOOOOOOOOOOOOO`

The challenge is to write a program that finds the index of the different letter given an image.

### Input

Input will be an `Image`. The image will consist of *one line* of *black* text in the *Helvetica 24 pt.* font on a *white* background. The text will consist from a selection of two characters: one character that is repeated, and one character that appears only once. For instance:

### Output

Output will be an `Integer`, the index of the different character. In the example above, the output will be `4`. (Note that indices of a string start at `0`)

### Program Specifications

As per usual for code golf, the shortest program wins.

---

## Test Cases

`=> 10`
`=> 11`
`=> 5`
`=> 16`
`=> 10`
`=> 21`
`=> 20`
`=> 13`
`=> 11`
`=> 4`
`=> 7`

# Answer
> 6 votes
# Dyalog APL, ~~31~~ 32 bytes

```
{1⍳⍨+⌿∘.≡⍨{⍵/⍨~∧⌿⍵}¨⍵⊂⍨2>/∧⌿1,⍵}

```

`⎕IO←0` to get indices starting with 0 (per OP), and which is anyway default in many APL systems.

`1,⍵` prepend a column of white pixels (to ensure margin)
`∧⌿` boolean for each column if all-white (vertical AND-reduction)
`2>/` boolean at each character's left edge (pair-wise greater-than)
`⍵⊂⍨` split into blocks beginning at each TRUE.
`{` for each block
`∧⌿⍵` boolean for each column if all-white (vertical AND-reduction)
`⍵/⍨~` columns that are not \[all-white\]
`∘.≡⍨` match each element to all elements
`+⌿` number of blocks identical to each block (vertical plus-reduction)
`1⍳⍨` index of first one (i.e. unique element)

Assumes the image is black (0) and white (1) pixels in the matrix `I`, and that there is at least one all-white pixel column between characters.

```
      f←{1⍳⍨+⌿∘.≡⍨{⍵/⍨~∧⌿⍵}¨⍵⊂⍨2>/∧⌿1,⍵}

```

"!I!!":

```
      ⊢I←6 12⍴(13/1),(22⍴0 1 1),(5/1),0,(8/1),(10⍴0 1 1),13/1
1 1 1 1 1 1 1 1 1 1 1 1
1 0 1 1 0 1 1 0 1 1 0 1
1 0 1 1 0 1 1 0 1 1 0 1
1 1 1 1 0 1 1 1 1 1 1 1
1 0 1 1 0 1 1 0 1 1 0 1
1 1 1 1 1 1 1 1 1 1 1 1
      f I
1

```

"mmnmm":

```
      ⊢I←7 31⍴(94/1),0 0,(∊0 1⌽¨2/⊂12⍴6↑1 0 1 1),0 1,(62⍴1 1 1,(⊢,⌽)(14⍴0 1)),33/1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 1 0 1 1 0 0 1 0 1 1 0 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
      f I
2

```

# Answer
> 3 votes
# Mathematica, 125 bytes

```
StringCases[#,x:Except[StringCases[#~StringTake~3,x_~~___~~x_:>x][[1]]]:>Position[Characters@#,x]][[1,1,1]]-1&@*TextRecognize

```

Ahh, Mathemeatica builtins. So amazing. (And so long...) Blows up on |/! :/; ,/. \`/' and blows up differently on m/n.

# Answer
> 3 votes
# Mathematica, 46 bytes

```
Length@First@Split@Characters@TextRecognize@#&

```

Same failures as the other mathematica solution as it relies on the same `TextRecognize` function.

---
Tags: code-golf, image-processing, optical-char-recognition
---


# Question
Title: Symbolic Differentiation of Composed Functions
# Symbolic Differentiation 2: Back on the Chain Gang

## Task

Write a program that takes in a certain sort of function from stdin and differentiates it with respect to *x*, using the chain rule.\* The input function will be a string of the following form:

```
"trig_1 trig_2 trig_3 ... x"

```

where `trig_n` is a trigonometric function `sin` or `cos`, and there are at most four functions in the term. The example string

```
"cos sin sin x"

```

represents the function cos(sin(sin(x))).

Your output must take the following form:

```
k(trig_1 trig_2 x)(trig_a trig_b trig_c x)(trig_m trig_n x) et cetera

```

where `k` is a constant and parentheses represent groups to be multiplied together.

\*The chain rule states that `D[f(g(x))] = f'(g(x)) * g'(x)`

## Examples

```
"sin sin sin sin x" ==> 1(cos x)(cos sin x)(cos sin sin x)(cos sin sin sin x)
"cos x" ==> -1(sin x)
"cos sin x" ==> -1(cos x)(sin sin x)

```

## Scoring

Your score is the length of your program in bytes, multiplied by three if you use a built-in or a library that does symbolic algebra.

## Similar Challenges

The previous installment: polynomial differentiation
Polynomial integration
General differentiation

# Answer
> 1 votes
# Java 8, ~~224~~ 214 bytes

Let the games begin!

```
interface B{static void main(String[]a){String o="";int v=2,z=a.length-1,i=z,k;for(;i>0;o+="x)"){if(a[--i].equals("cos")){o+="(sin ";v=(v+2)%4;}else o+="(cos ";for(k=i;++k<z;)o+=a[k]+" ";}System.out.print(v-1+o);}}

```

This could (theoretically) extend infinitely.

Output for `sin cos sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x`:

```
1(cos x)(sin sin x)(sin cos sin x)(sin cos cos sin x)(cos cos cos cos sin x)(sin sin cos cos cos sin x)(cos cos sin cos cos cos sin x)(cos sin cos sin cos cos cos sin x)(sin sin sin cos sin cos cos cos sin x)(cos cos sin sin cos sin cos cos cos sin x)(cos sin cos sin sin cos sin cos cos cos sin x)(cos sin sin cos sin sin cos sin cos cos cos sin x)(sin sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin sin sin cos sin sin cos sin cos cos cos sin x)(sin sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(sin sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)
```

# Answer
> 1 votes
# sed, 88 + 1 = ~~123~~ 89 bytes

`+1` for the `-r` (extended regex) flag.

```
s/^/d/
:
s/d(-?)sin (.*)/(\1cos \2)d\2/
s/d(-?)cos (.*)/(\1-sin \2)d\2/
s/--//
s/dx/1/
t

```

## Explanation

Note: A single `d` is used as short version of `d/dx` in the golfed program.

First, preceed the string with `d/dx`. Then, reapeat the following replacements until the string does not change anymore:

```
d/dx sin ...    => (cos ...)d/dx ...
d/dx cos ...    => (-sin ...)d/dx ...
d/dx -sin ...   => (-cos ...)d/dx ...
d/dx -cos ...   => (sin ...)d/dx ...
d/dx x          => 1

```

Edit: The positive and negative cases are now handled within a single regex. This requires an additional search and replace to drop a double minus and is less elegant, but way shorter.

# Answer
> 0 votes
# Mathematica, 115 bytes

```
ToExpression["d["<>StringReplace[#,{" "->"@"}]<>"]"]//.d[x_[y__]]->d[x][y]d[y]/.{d[sin]->cos,d[cos]->-sin,d[x]->1}&

```

---
Tags: code-golf, string, parsing, calculus
---


title: Play a sound, any sound

text:
# Question
Title: Play a sound, any sound
Your program has to make the computer produce a sound, any sound.

Shortest code wins, not sooner than 10 days after the first valid answer. If there is a tie, the one submitted sooner, wins.

* The program should run on a reasonable, not too uncommon personal computer.
* Opening a pop-up, message box, etc. (for example, on a web page) does not count, as they might or might not produce a sound, depending on a lot of settings.
* Just entering a wrong command or invalid character on a console and receiving a warning beep does not count, just as the compiler/interpreter/OS beeping on an error or crash does not count either. Your code must be a valid program.

# Answer
> 20 votes
# dc, 2 chars

this one prints the bell character, too:

```
7P

```

Run with `$ dc <<< 7P` or save `7P` to file and run `$ dc file`.

Also:

# Befunge, 2 chars

Similar but infinitly looping and beeping:

```
7,

```

# Answer
> 48 votes
# bash (13)

```
sudo rm -rf /

```

The faster the hard drive the better the sound. Don't work with SSDs.
**(Don't try this at home, `sudo rm -rf /` erases everything on your hard drive)**

# Answer
> 43 votes
# \*sh (5)

```
eject

```

(does not work if you have no CD/DVD or similar drive..)

# Answer
> 36 votes
## Befunge, 0

If I read the spec correctly, this is an endless loop.
Endless loop = you'll hear your CPU cooler spin up.

# Answer
> 27 votes
## sh 7

```
w|aplay

```

Plays a short noise.

Also 7:

```
aplay *

```

## Assembly

Another non-bell solution. Resulting binary is just 15 bytes.

```
mov al, 182
out 43h, al
out 42h, al
mov al, 16
out 42h, al
mov al, 3
out 61h, al
ret

```

Assemble with `nasm sound.asm -o sound.com`. Can be tried with `dosbox sound.com`.

# Answer
> 25 votes
## brainfuck: 8

```
+++++++.

```

Prints the bell character.

# Answer
> 22 votes
### bash (Mac OS X) 5

```
say a

```

although stylistically I prefer the somewhat longer:

```
say 'Hello, Code Golf !'

```

# Answer
> 18 votes
Haha, good ol' QBASIC code.

```
BEEP

```

# Answer
> 16 votes
# Python 3.3.3, one character

```
<bell character>

```

The error message will contain a bell character, causing the sound.

# Python 3.3.3, 10 characters

If errors are not allowed, this solution won't output the error message, only the sound.

```
print('<bell character>')

```

# Answer
> 13 votes
### Golfscript 3

```
'.'

```

*(where the `.` is in fact a BELL character)*

The HEX representation of the above code is:

```
27 07 27

```

# Answer
> 11 votes
# Java - 222

Enough of this bell character or predefined beep function stuff, this makes a real sound :)

```
import javax.sound.sampled.*;class S{static{try{SourceDataLine
l=AudioSystem.getSourceDataLine(new
AudioFormat(4000,8,1,0<1,0>1));l.open();l.start();for(byte
i=9;i!=0;i+=9)l.write(new byte[]{i},0,1);}catch(Exception e){}}}

```

# Answer
> 10 votes
## DOS Prompt / DOS Script

```
a:

```

Requires 3.5" floppy drive :)

# Answer
> 9 votes
## J (2)

```
a.

```

This prints all the characters from 0 to 255, that includes the bell.

If I have to do it without printing anything else, it's 4 characters:

```
7{a.

```

# Answer
> 9 votes
# Pascal: 30 characters

```
uses Crt;begin
Sound(999)
end.

```

This takes advantage of the lack of any rule regarding the sound's duration. So just turns on the speaker on 999 Hz and lets it so. (At least until another program calls `Nosound` or the computer is turned off.)

# Answer
> 8 votes
# Mathematica 6

This will evoke the system beep. On my computer, it is currently a chirp.

```
Beep[]

```

# Answer
> 8 votes
## Bash, 22

Back in the 90's, my brother taught me this one -- to be used in a computer lab where one has remote access and knows a person to be alone in said lab. Kids these days won't know what a computer lab is... but oh well.

```
cd /dev;cat sda1>audio

```

# Answer
> 7 votes
# cat/type/PHP 1

This is actually polyglot. It runs in `cat` (or Microsoft Cat called `type`) and PHP.

```
$ xxd file
0000000: 07                                       .

```

Execution:

```
$ xxd -r > file
0000000: 07                                       .
^D
$ cat file # cat could be replaced with type (on Windows) or with php

```

# Answer
> 6 votes
### brainfuck, 5 bytes

```
+[.+]

```

prints all chars including bell

# Answer
> 5 votes
## R 9

The bell character

```
cat("\a")

```

# Answer
> 5 votes
# Ruby, 7

```
$><<?\a

```

Tested on Windows with Ruby 1.9.3.

# Answer
> 5 votes
## DOS, 5

Indirect, requires user cooperation.

```
pause

```

# Answer
> 5 votes
## PowerShell, 24 17

Since nobody has posted this version yet:

```
[console]::beep()

```

**UPDATE:** Removed frequencies so it uses the default frequency and duration (MSDN says the default is 800 hertz and 200 milliseconds)

# Answer
> 4 votes
**Python** 9 chars

---

produces beep sound when executed.

```
print'\a'

```

# Answer
> 4 votes
# Applescript (4 Characters)

```
beep

```

This will play the default beep sound of OS X.

# Answer
> 4 votes
# top & aplay - 9

`top` has rhythm!

```
top|aplay

```

The periodic display sometimes does not feed the sound sink fast enough but `aplay` continues after grouching a bit... :-)

...this will run on many Linuxes...

### Bonus:

While running this, type "s 1 ENTER" to get more beats per second. :-)

Party on!!! \o/

# Answer
> 4 votes
# Mathematica 7

Using Mathematica's built in text to speech capability.

```
Speak@x

```

Will make it say "x"

# Answer
> 3 votes
# **C: 19**

```
main(){puts("\a");}

```

**edit:** header file is not needed for "puts"

# Answer
> 3 votes
## \>\<\> 3

As in all answers, prints the bell (0x07) to stdout.

```
7o;

```

# Answer
> 3 votes
## Tcl, 1 char

```
-

```

replace `-` with the bell char.
It will print the bell char as part of the error message. Twice.

And if you think this is not a valid program, add this before the bell char:

```
proc \007 {} {};

```

It is a valid program, I just did not define the command, because I like the error message.

# Answer
> 2 votes
### Ruby 8

```
 puts"\a"

```

Tested on Windows with Ruby 1.9.3.

# Answer
> 2 votes
## Bash, 26

Standard unix (not modern linux, sadly, unless you have alsa-oss installed; the BSDs are fine):

```
cat /dev/random > /dev/dsp

```

# Answer
> 2 votes
# Scala: 44

```
java.awt.Toolkit.getDefaultToolkit().beep();

```

*same as @nrubin29's answer, but shorter*

# Answer
> 2 votes
# GolfScript (3)

Since everyone else is doing this anyway:

```
'^G'

```

where `^G` is the bell character.

Hex dump:

```
0000000: 2707 27                                  '.'

```

# Answer
> 2 votes
# Linux shell (6 characters)

This requires a correctly configured analog modem (you also might need to run it as root):

```
wvdial

```

# Answer
> 1 votes
## sh 6

```
echo .

```

*(where the `.` is in fact a BELL character)*

The HEX representation of the above code is:

```
65 63 68 6f 20 07

```

# Answer
> 1 votes
**Autoit 6**

```
Beep()

```

Although declaring a function would allow for less characters, not counting the declaration:

```
z()
Func z()
Beep()
EndFunc

```

# Answer
> 1 votes
# ATARI BASIC (4 chars)

```
?"E"

```

(? is short for "print". E is in fact the "escape" symbol; see http://raster.infos.cz/atari/chars/atascii.htm, item 1B. Printing this symbol would make a characteristic noise.)

# Answer
> 1 votes
### PowerShell, 3

```
'^G'

```

Of course, the `^G` has to be entered manually, or written to a file with another script, like the following:

```
"'$([char]7)'"|Set-Content beep.ps1

```

# Answer
> 1 votes
## VBScript

```
CreateObject("SAPI.SpVoice").speak "a"

```

Nice thing about this is you can make it say anything you want.

# Answer
> 1 votes
# Windows Command Promt

```
logoff

```

Indeed, this makes an OS sound but it is not `OS beeping on an error or crash`.

# Answer
> 1 votes
Matlab **UNTESTED** (1)

I am not sure whether this works in matlab, as I don't have sound available, but  is in fact a single character. Hence calling or printing it may produce the desired effect in some languages.

Matlab verified (4)

```
beep

```

# Answer
> 1 votes
# Windows batch script, 14

```
sort %comspec%

```

%comspec% just points to C:\Windows\System32\cmd.exe, and calling sort will find the bell character at some point in cmd's binary.

# Answer
> 1 votes
# Batch, 16

```
type sethc.exe

```

I discovered this. When I do this, I'll get the 'BEEP' sound from reading the \< BELL \> character.

# Answer
> 1 votes
# JavaScript - 99 103

```
Audio
  ("data:audio;base64,UklGRgWsAABXQVZFZm10IBAAAAABAAEARKwAAESsAAABAAgAZGF0YeGrAACAbebe")
.play();

```

\*chirp\* (in firefox, it is definitely a chirp)

# Answer
> 1 votes
## Java: 103

```
public class S {
    public static void main(String[] a) {
        java.awt.Toolkit.getDefaultToolkit().beep();
    }
}

```

# Answer
> 1 votes
## JS, 117

```
new Audio('data:audio/wav;base64,UklGRl9vT19XQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YU'+Array(1e3).join(123)).play()

```

# Answer
> 1 votes
# QBASIC (8)

```
PLAY "A"

```

---

> Body must be at least 30 characters; you entered 19.

ಠ\_ಠ

# Answer
> 1 votes
# Python3 34

Any of the python versions printing the bell character to stdout was working for me, so here it is one using the standard libarary, in Windows:

```
import winsound as w;w.Beep(99,99)

```

The semicolon could be replaced with a newline, but looks cooler this way :)

# Answer
> 1 votes
# Powershell, 4

```
"`a"

```

Sends a beep signal to the computer's speaker.

# Answer
> 1 votes
# OS X Command Line

> say a

This causes the computer to say the letter 'A'

# Answer
> 1 votes
# Visual Basic 6

```
beep

```

VB 6, good times.

# Answer
> 1 votes
## C 23

Make a beep sound.

```
int main(){putchar(7);}

```

# Answer
> 1 votes
# Debianish solution, works on some other systems too - 9 chars

```
aplay /i*

```

...will play the files `/initrd.img` and `initrd.img.old` which are symlinks to some system startup ramdisks in directory `/boot`.

If you prefer the sound of kernels, try...

```
aplay /v*

```

...and look yourself why it works or fails on your system.

I got...

```
$ LANG=C ls -l / | grep ^[^d]
total 88
lrwxrwxrwx   1 root root    36 Dec 15  2012 initrd.img -> /boot/initrd.img-3.2.0-0.bpo.4-amd64
lrwxrwxrwx   1 root root    30 Dec  9  2012 initrd.img.old -> boot/initrd.img-2.6.32-5-amd64
lrwxrwxrwx   1 root root     4 Dec  9  2012 lib64 -> /lib
lrwxrwxrwx   1 root root    32 Dec 15  2012 vmlinuz -> boot/vmlinuz-3.2.0-0.bpo.4-amd64
lrwxrwxrwx   1 root root    27 Dec  9  2012 vmlinuz.old -> boot/vmlinuz-2.6.32-5-amd64

```

...here and that may or may not explain a lot to you and I demand the absence of solid facts and that I may or may not be called vroomfondel!

# Answer
> 1 votes
## PHP (CLI): 1 byte

```

```

Source code as seen in Notepad++:

In the absence of `<?php` opening tag, source code is simply dumped to output.

Yeah, I know, another BEL answer, but still, tough to beat a single byte, especially in an interpreted language like PHP ;)

# Answer
> 0 votes
# k/Q (6 chars)

Bell character to stdout.

```
1"c"$7

```

# Answer
> 0 votes
## Windows Command Script - 1 Byte

As most of the answers, this also uses the bell character.

```
0x07

```

Note: Must be run from console to work, since the sound needs some time to trigger.

# Answer
> 0 votes
## Spoon, 13

```
1111111001010

```

Similarly to the BF solution, it prints the bell character.

# Answer
> 0 votes
# C++ 45

```
#include<iostream>
int main(){std::cout<<'\a';}

```

# Answer
> 0 votes
# Fortran 95, 18 chars

```
print*,char(7);end

```

Produces a bell sound

# Answer
> 0 votes
# ZX Spectrum BASIC (3)

```
SAVE STR$ PI

```

It is only 3 bytes because BASIC keywords (with surrounding spaces) occupy single byte in ZX spectrum's memory. Here's its hex representation:

```
F8 C1 A7

```

This program saves current program to audio tape under the name "3.1415927" which is the string representation of π.

In fact it require 7 keypresses: S Caps+Symbol Y Caps+Symbol M

# Answer
> 0 votes
## C#

```
System.Media.SystemSounds.Beep.Play();

```

It's long, but anyway...

# Answer
> 0 votes
## R, 7

```
alert()

```

but sadly I think this is just a wrapper for printing the bell character.

# Answer
> 0 votes
**In AppleScript ; 4 characters**

```
beep

```

\[ This is so short that my answer firstly did not reach the minimum length to be posted ! \]

# Answer
> 0 votes
## Ruby, 8 chars

```
puts ?\a

```

## \>\<\>, 2-3 chars

```
7o;

```

or with infinite loop:

```
7o

```

# Answer
> 0 votes
## Autohotkey

I found my answer in the Documentation on the Autohotkey Docs.

```
SoundBeep

```

# Answer
> 0 votes
# C#, 72 bytes

```
class Program{public void main(string[]args){System.Console.Beep(500);}}

```

# Answer
> -1 votes
# C on linux

```
#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>

int main() {
  ioctl(open("/dev/sdb", O_RDONLY), CDROMEJECT);
}

```

Opens the CD-ROM door.

You may need to change sdb to whatever your optical drive's device is.

---
Tags: code-golf
---