title: Can you make my terminal less boring?

text:
# Question
Title: Can you make my terminal less boring?
Terminals are so *boring* these days. They used to look like this:

Now they're just bland and dull and black-and-white. I want you to write me a program that will make my terminal all colorful again!

## Description

Take this example Ruby code:

Most Linux terminals support these **escape sequences** (`\e` stands for the escape character), and Windows can support them with ANSICON. Here is the syntax of the specific escape sequence that can change the text or background color of a string:

```
\e[{{COLOR}}m

```

where `\e` stands for the escape character (`0x1B` in ASCII) and `{{COLOR}}` is replaced by the number of the color that you want to use (more details on that later). Text that comes after this escape sequence will be formatted as directed, and a value of `0` will reset all formatting.

Your challenge is to take a string specifying some text that may contain color, and output a colorful version of it.

## Input / Output

Normal text works just like normal, and is printed literally. For example, the input `waffles` yields the same output, with no special color.

The syntax for specifying a color is similar to Wikipedia's syntax. For example, to color the words "the color red" in red in the sentence `This is the color red!`, the input would be:

```
This is {{red|the color red}}!

```

Background colors work too. If you wanted black letters on a white background, you would use this:

```
{{black|white|This text is black on white}}

```

To get only a background color, omit the foreground:

```
{{|red|This text has a red background}}

```

## Specification

Two open curly brackets always specify the beginning of a **color directive**. Two closing curly brackets specify the end. Brackets will always match; there will never be a `{{` without a corresponding `}}`, and a `}}` will never come before its corresponding `{{`. These *color directives* will not be nested, and a `{{` will never appear within a color directive.

Within a color directive, there will always be either one or two `|` symbols. If there is one, the text before it is the foreground color and the text after is the string to show in that color. If there are two, the text before the first one is the foreground color, the text after the first but before the second is the background color, and the text after the second is the string to display. These vertical bars may exist outside of a color directive, and should be printed literally.

The foreground color or background color (but not both) may be empty, in which case you should leave them as the default. The final string (the one to output) will never be empty.

Here are the directions to output text of a certain color:

* A **color sequence** is defined in the "Description" section. For example, a color sequence of 42 would be `"\e[42m"`.
* To set a color, print the color sequence of the number determined below:

```
 Color name   | Color sequence number (foreground / background)
--------------+----------
 black        | 30 / 40
 red          | 31 / 41
 green        | 32 / 42
 yellow       | 33 / 43
 blue         | 34 / 44
 magenta      | 35 / 45
 cyan         | 36 / 46
 lightgray    | 37 / 47
 darkgray     | 90 / 100
 lightred     | 91 / 101
 lightgreen   | 92 / 102
 lightyellow  | 93 / 103
 lightblue    | 94 / 104
 lightmagenta | 95 / 105
 lightcyan    | 96 / 106
 white        | 97 / 107

```
* Color names are case sensitive, and an invalid color name will never be provided. You don't have to handle stuff like `RED` or `lightgrey` (spelled with an `e`).
* After you print a color sequence, it will apply for all text following it. To end a color sequence (reset to the default color), output a color sequence of `0` (`"\e[0m"`).

## Test case

```
 {{|yellow|     }}
{{|yellow| }}     {{|yellow| }}
{{|yellow| }} {{red|'}} {{red|'}} {{|yellow| }}
{{|yellow| }} \_/ {{|yellow| }}
{{|yellow| }}     {{|yellow| }}
 {{|yellow|     }}

```

This should output a smiley face... with evil red eyes.

## Rules

* You may not use any libraries or functions of your programming language to automatically parse a color. This means that *you* must be the one to determine what `"red"` means; you can't have a library automatically do that for you.
* This is , so the shortest code in bytes will win!

# Answer
> 7 votes
## Ruby, ~~205~~ ~~189~~ ~~188~~ ~~186~~ ~~185~~ ~~182~~ ~~174~~ ~~170~~ ~~165~~ ~~161~~ ~~159~~ 154 bytes

Putting long strings of color names in your code doesn't look nerdy enough.

Down to 170 partly thanks to `rubik`. Now the scrolling bars are gone!

One obvious and one not so obvious improvement, thanks to the flex answer, without the improvement to it, I wouldn't have revisited this!

Not anymore, I saved 4 bytes with #sum. ~~I didn't intend it, but I just noticed this solution is case-insensitive as well. It happily processes `{{RED|Red text}}`.~~

Hex dump:

```
0000000: 7a3d 2d3e 6a7b 693d 2240 3054 2d44 1547  z=->j{i="@0T-D.G
0000010: 5155 0034 3256 2f46 1749 0b22 2e69 6e64  QU.42V/F.I.".ind
0000020: 6578 2028 415b 6a5d 2e74 6f5f 732e 7375  ex (A[j].to_s.su
0000030: 6d25 3839 292e 6368 723b 692b 3d69 3e39  m%89).chr;i+=i>9
0000040: 3f38 303a 3330 7d0a 243e 3c3c 243c 2e72  ?80:30}.$><<$<.r
0000050: 6561 642e 6773 7562 282f 7b7b 282e 2a3f  ead.gsub(/{{(.*?
0000060: 297d 7d2f 297b 413d 2431 2e73 706c 6974  )}}/){A=$1.split
0000070: 277c 273b 221b 5b25 693b 2569 6d23 7b41  '|';".[%i;%im#{A
0000080: 2e70 6f70 7d1b 5b30 6d22 255b 7a5b 305d  .pop}.[0m"%[z[0]
0000090: 2c31 302b 7a5b 315d 5d7d                 ,10+z[1]]}

```

You can convert it with `xxd -r hex.dump`.

The program with all non-printable characters escaped for reference purposes:

```
z=->j{i="@0T-D\x15GQU\x0042V/F\x17I\v".index (A[j].to_s.sum%89).chr;i+=i>9?80:30}
$><<$<.read.gsub(/{{(.*?)}}/){A=$1.split'|';"\x1b[%i;%im#{A.pop}\x1b[0m"%[z[0],10+z[1]]}

```

That is one line. Use it like this

```
ruby colors.rb -W0 < input.txt

```

The `-W0` flag suppresses warnings that would be sent to `stderr` otherwise. However, the program works fine without any flags.

Output:

# Answer
> 4 votes
# Ruby, 329 bytes.

```
h={};(y=0..15).each{|i|h[%w(black red green yellow blue magenta cyan lightgray darkgray lightred lightgreen lightyellow lightblue lightmagenta lightcyan white)[i]]=y.map{|j|[30,40].map{|k|k+i%8+i/8*60}}[i]}
loop{puts gets.gsub(/{{.+?}}/){|x|"\e[#{h[(g=x.scan(/[^{}|]+/))[0]][0]}m#{(g[2]? "\e[#{h[g[1]][1]}m":'')}#{g.last}\e[0m"}}

```

# Answer
> 4 votes
## Flex (lexer) - ~~226~~ ~~197~~ ~~192~~ ~~182~~ 168 (or 166)

To get it down to 166, change the `\33` to an actual escape character.

```
 int z;p(i){printf("\33[%dm",i);}
%%
"{{" z=2;
[a-z]*\| if(!z)REJECT;~-yyleng&&p("062q00t03058ns7uo0p90r4"[*(int*)&yytext[yyleng>7?4:0]%131%27]-10*z);z--;
"}}" p(z=0);

```

Compile and run:

```
$ flex -o colour.c colour.l
$ gcc -o colour colour.c -lfl
$ ./colour < input

```

# Answer
> 3 votes
## Python - 351

```
import re,sys
R=range
E=lambda n,d=0:'\033[%dm'%(T[n]+d)if n else''
def P(m):f,b,t=m.groups();return'%s%s%s\033[0m'%(E(f),E(b,10),t)
x='!red!green!yellow!blue!magenta!cyan'.replace
T=dict(zip(('black'+x('!',' ')+' lightgray darkgray'+x('!',' light')+' white').split(),R(30,38)+R(90,98)))
print re.sub(r'{{(\w+)?\|?(\w+)?\|?(.+?)}}',P,sys.stdin.read())

```

# Answer
> 1 votes
## Python, 561

Reads the text to format from stdin.

```
import re,sys
def p(f,b,t):
    p=''
    m='\033[%dm'
    if f!=0:p+=m%f
    if b!=0:p+=m%b
    return p+t+m%0
def c(n,b=0):
    s='black:30#red:31#green:32#yellow:33#blue:34#magenta:35#cyan:36#lightgray:37#darkgray:90#lightred:91#lightgreen:92#lightyellow:93#lightblue:94#lightmagenta:95#lightcyan:96#white:97'
    r=0
    for i in s.split('#'):
        (t,c)=i.split(':')
        if t==n:
            r=int(c)
            if b==1:r+=10
    return r
def r(m):
    i=m.groups()
    f=b=0
    if i[0]!='':f=c(i[0])
    if i[1]!=None:b=c(i[1],1)
    return p(f,b,i[2])
print re.sub('{{(\w*)\|(?:(\w*)\|)?([^}]+)}}',r,sys.stdin.read())

```

# Answer
> 1 votes
# Cobra - 496

It could *almost* be a single print statement.

```
use System.Text.RegularExpressions
class P
    def main
        print Regex.replace(Console.readLine,r'\{\{('+(l=List<of String>(((m=' black red green yellow blue magenta cyan'.split).join(' ')+' lightgray darkgray'+m.join(' light')+' white').split))[1:].join('|')+r')?\|?('+l[1:].join('|')+r')?\|(.*?)\}\}',do(a as Match))
            return if(x=l.indexOf('[a.groups[1]]'),r'\e['+'[if(x>8,x+81,x+29)]m','')+if(y=l.indexOf('[a.groups[2]]'),r'\e['+'[if(y>8,y+91,y+39)]m','')+'[a.groups[3]]'+if(x+y,r'\e[0m','')

```

---
Tags: code-golf
---


title: Extraction of Bits

text:
# Question
Title: Extraction of Bits
Your task is to devise a programme that extracts the bits, in order, represented by the first argument based on the set bits represented by the second argument (the mask).

**Formal Definition:**

* Let the first argument `x` represent the binary string `S=(x<sub>n</sub>)(x<sub>n-1</sub>)...(x<sub>1</sub>)` with `n>=0` and `x<sub>1</sub>` being the least significant digit and `x<sub>n</sub> = 1`.
* Let the second argument `y` represent the binary string `T=(y<sub>m</sub>)(y<sub>m-1</sub>)...(y<sub>1</sub>)` with `m>=0` and `y<sub>1</sub>` being the least significant digit and `y<sub>m</sub> = 1`.
* Let the result represent `0` if `x` represents 0 or `y` represents 0.
* Let the number of `1` digits in `T` be `p`. Let `{d<sub>i</sub>}, i in [1, p]` be the set of binary strings of the form `(d<sub>i</sub>m)(d<sub>i</sub>(m-1))...(d<sub>1</sub>)` defined by (for all i, (for all k, `|{d<sub>i</sub>k such that d<sub>i</sub>k = 1}| = 1`)) and (`if 1 <= i < j <= p then 0 < d<sub>i</sub> < d<sub>j</sub>`) and (`d<sub>p</sub> | d<sub>p-1</sub> | ... | d<sub>1</sub> = T`). In other words, `{d<sub>i</sub>}` is the ordered set of strings with a single `1` digit that makes up the string `T` when `|` is applied.
* Let the **result** of the programme represent the following binary string:

`((d<sub>p</sub> & S) << (p - 1))| ... | ((d<sub>2</sub> & S) << 1) | (d<sub>1</sub> & S)`

**Examples:**

* 1111, 110 -\> 11
* 1010, 110 -\> 01
* 1010, 10110 -\> 01
* 1101010111, 11111000 -\> 01010

**Input and Output:**

* The two arguments may be taken in any way
* The two arguments need not be binary strings. They can also be integers which represent binary strings.
* Answers which do not take input representing binary strings of arbitrary length **are** permitted.

**Winning:** Shortest code wins.

**Clarifications:**

* If your output gives a bit string, order of bits is not important. Simply state the order in your answer. As stated before, the output of your programme need only represent the bits required.

# Answer
> 5 votes
# CJam, 9 bytes

```
eaz{)~*}%

```

This reads the bit strings (LSB first) as command line arguments and prints the result (also LSB first).

To try this code in the CJam interpreter, change `ea` to `qS%` and separate the strings with a space.

### Example run

```
$ cjam <(echo 'eaz{)~*}%') 1110101111 00011111; echo
01011

```

### How it works

```
ea         " Read both command line arguments and collects them in an array. ";
  z        " Interleave the characters of both strings.                      ";
   {   }%  " For each pair of characters:                                    ";
    )~     " Pop the last character and interpret it as an integer.          ";
      *    " Repeat the remaining strings that many times.                   ";

```
* If the mask character is 0, the string consisting of the corresponding character is repeated zero times.
* If the mask character or the corresponding character do not exist, popping a character will result in an empty string to be repeated.

In either case, the result will be an empty string.

# Answer
> 11 votes
# *Edit:* APL, 1 character

`/`, the compression operator (Documentation).

Example of use:

```
0 0 1 1 1 1 1 0 0 0/1 1 0 1 0 1 0 1 1 1
0 1 0 1 0

```

Try it yourself at http://ngn.github.io/apl/web/index.html

The mask is left, and the input bitstring is right. **Disclaimer:** *I'm not an expert in APL and have never used it; I only submitted this to substitute the disqualification of my machine-code solution below. I admit that a limitation of the code above is that the left and right bitstrings must be of equal length in APL, and lack the APL skills to fix this.*

# *Rejected as loophole*:

# x86-64 Machine Code (BMI2, Haswell+), 5 bytes

`c4 e2 f2 f5 d0` is the hex representation of the raw bytes of the program as they would appear in an executable x86-64 binary program.

This represents the *single instruction* `pext %rax, %rcx, %rdx`, which accepts `S` in `rax`, `T` in `rcx` and stores the result in `rdx`. Max 64 bits. Runs in 3 clock cycles on Haswell, has throughput of 1 per clock cycle.

```
xxx@xxx:~/Documents/SO> cat > bmi2.s
.text
pext %rax, %rcx, %rdx
xxx@xxx:~/Documents/SO> gcc bmi2.s -c -o bmi2.o
xxx@xxx:~/Documents/SO> objdump -d bmi2.o

bmi2.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <.text>:

0:   c4 e2 f2 f5 d0          pext   %rax,%rcx,%rdx

```

Of course, requires a pretty modern assembler.

The documentation for PEXT is much clearer than OP's description, so here it is:

# Answer
> 3 votes
# Haskell, 68 characters

```
f[c:d,'0':b]=f[d,b];f[c:d,_:b]=c:f[d,b];f _="";main=interact$f.words

```

Prints nothing if the input isn't exactly two words.
The first argument can contain any characters. So can the filter; only `0` is treated as "not select".
If arguments are of different length, they are taken left-aligned (LSB first; explicitly allowed since revision #4).

# Haskell function, 48 characters

```
f(c:d)('0':b)=f d b;f(c:d)(_:b)=c:f d b;f _ _=""

```

Subtract two more characters if "function of two integer arrays" is an acceptable signature

# Answer
> 2 votes
# Golfscript, ~~54~~ 51 characters

```
'0':x;{.,64\-x*\+}:b~:m;'X':x;b{m(\:m;48={;}*}%'X'-

```

Only works for binary strings of length 64 or less.

Explanation:

```
'0':x;       store '0' in the x variable (which will be used in the following)
{.,64\-x*\+} block that pads strings to a length of 64 with the character stored in x
:b~          store the block in b and execute, second argument (y) is now padded with '0's
:m;          store second argument as mask (m)
'X':x;b      pad the first argument with 'X's (will be removed later)
{...}%       for each character in the first argument (x), ...
  m(\:m;     grab and delete the first character of m (mask)
  48={...}*  if this character is equal to 48 (0 in ASCII)...
    ;        remove the digit. Hence, this if statement keeps a digit only if the mask is 1.
'X'-         finally, remove the 'X's added in step 5

```

# Answer
> 2 votes
# J, 16 Characters:

```
(#=@i.@#)@],@:#[

```

**Usage:**

```
1 0 1 0 1 1 ((#=@i.@#)@],@:#[) 0 1 1 1 0 0 -> 0 1 0

```

**Explanation:**

First argument is left, second argument is right (mask).

```
(#=@i.@#)@],@:#[ -> (# =@i.@#)@] ,@:# [

```
* Take right argument, produce identity matrix of size length of right argument.
* Use set bits of right argument to choose rows of produced identity matrix.
* Use chosen rows of identity matrix to choose digits of left argument.
* Concatenate the digits chosen from left argument.

# J, 13 Characters

According to the rules, the form of output is not important. Therefore, if we omit the concatenation of the output digits, we can have the following shorter answer.

```
`(#=@i.@#)@]#[`

```

# Answer
> 2 votes
# J, 1 character

`#`, the tally operator (Documentation).

Example of use:

```
0 0 1 1 1 1 1 0 0 0#1 1 0 1 0 1 0 1 1 1
0 1 0 1 0

```

This solution does not cater for the case when the length of the mask is less than that of the string. Given that the above might be seen as a loophole, we have the following solution.

# J, 11 characters

```
[#~],0$~-&#

```

This solution is like the original `#`, but also caters for the case when the length of the mask is less than that of the string. Note here that the mask is the right argument, and not the left argument as in the first solution.

```
x ([ #~ ] , 0 $~ -&#) y
   x #~ (y , (0 $~ (x -&# y)))
   x #~ (y , (0 $~ ((# x) - (# y))))
   x #~ (y , (((# x) - (# y)) $ 0))
   x #~ (y , 0 0 ... 0 0)
   x #~ y 0 0 ... 0 0
   y 0 0 ... 0 # x

```
* `[` and `]` choose `x` and `y` respectively.
* `x (u&v) y` -\> `(v x) u (v y)`.
* `(x -&# y)` -\> `(# x) - (# y)`.
* `# x` -\> length of `x`.
* `x v~ y` -\> `y v x`.
* `n $ 0` -\> list of n `0`s.
* `(0 $~ (x -&# y))` -\> `m` `0`s, where `m` is the difference between the length of the string and the length of the mask.
* `(y , 0 0 ... 0 0)` -\> the list `y 0 0 ... 0 0` such that its length is equal to that of the string.
* `a # b` -\> the elements of `b` chosen by the binary mask `a`.

Even though this solution is shorter than my other solution of 16 characters, I think it still makes unfair use of `#`. In any case, I think it's still interesting.

# Answer
> 2 votes
# Haskell, 33 characters

```
((map snd.filter((>0).fst)).).zip

```

# Usage

```
(((map snd.filter((>0).fst)).).zip) [1, 0, 1, 0] [1, 0, 0, 1]
[1, 0]

(((map snd.filter((>0).fst)).).zip) [1, 1] [1, 1, 0, 1]
[1, 1]

```

# Answer
> 1 votes
# J, 10 characters, no use of tally `#`

This solution does not cater for input where mask is shorter than string.

```
;@:(<@$"0)

```

**Usage**

```
1 0 0 1 (;@:(<@$"0)) 1 0 1 0
1 0

```

**Explanation**

* This makes no use of `#`, which on its own can be used to solve this golfing problem.
* This solution works by interleaving both sides, one element by one. This is expressed by `"0`, which makes `<@$` applied to each pair of elements.
* `x $ y` means `x` `y`s as a list. `3 $ 4` -\> `4 4 4`.
* `< x` puts `x` in a "box". A box can contain an object of any dimension (list, matrix, nothing). Boxes can be concatenated into lists.
* `1 $ x` -\> one-dimensional list consisting of `x`.
* `0 $ x` -\> nothing
* `1 (<@$"0) x` -\> one-dimensional list consisting of `x` inside a box.
* `0 (<@$"0) x` -\> nothing in a box.
* `;` takes a list of boxes and concatenates its contents, throwing away empty boxes.
* `u@:v` composes `u` and `v` in such a way that `u` is applied only after `v` has been applied to the whole of the arguments. In this case `;` is applied only after the right side of the `@:` has been applied to each interleaved pair `x` and `y` made from the arguments.

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


title: Voice recognition: "Yes" or "No"?

text:
# Question
Title: Voice recognition: "Yes" or "No"?
## Task

Implement a program in minimum bytes of source or binary code that does voice recognition of a voice sample (me saying "yes", "yeah" or "no" in voice or in whisper, plainly or quirkily) based on training samples with maximum accuracy.

The program should read `train/yes0.wav`, `train/no0.wav`, `train/yes1.wav` and so on (there are 400 yeses and 400 noes in training dataset), then start reading `inputs/0.wav`, `inputs/1.wav` until it fails to find the file, analysing it and outputting "yes" or "no" (or other word for intermediate answer).

If you want, you may pre-train the program instead of reading `train/`, but the resulting data table counts towards the score (and beware of overfitting to training samples - they don't overlap with examination ones). Better to include the program used to produce the data table as an addendum in this case.

All sample files are little endian 16-bit stereo WAV files, just from laptop mic, without filtering/noise reduction.

## Limits

Forbidden features:

* Using network;
* Trying to reach the answers file `inputs/key`;
* Subverting the `runner` program that calculates accuracy;
* Using existing recognition libraries. Linking to FFT implementation not allowed: only external math functions taking constant amount of information (like `sin` or `atan2`) are allowed; If you want FFT, just add it's implementation to your program source code (it can be multilingual if needed).

Resource limits:

* The program should not take more than 30 minutes of CPU time on my i5 laptop. If it takes more, only output produced in the first 30 minutes are counted and eveything else is assumed a half-match;
* Memory limit: 1GB (including any temporary files);

## Tools

The `tools/runner` program automatically runs your solution and calculates the accuracy.

```
$ tools/runner solutions/example train train/key
Accuracy: 548 ‰

```

It can examine the program using training data or using actual exam data. I'm going to try submitted answers on examination dataset and publish results (accuracy percentage) until I make the dataset public.

## Scoring

There are 5 classes of solution depending on accuracy:

* All samples guessed correctly: Class 0;
* Accuracy 950-999: Class 1;
* Accuracy 835-950: Class 2;
* Accuracy 720-834: Class 3;
* Accuracy 615-719: Class 4;

Inside each class, the score is number of bytes the solution takes.

Accepted answer: smallest solution in the best nonempty class.

## Links

All samples should be considered CC-0 (Public Domain), scripts and programs should be considered MIT.

## Example solution

It provides very poor quality of recognition, just shows how to read files and output answers

```
#define _BSD_SOURCE
#include <stdio.h>
#include <assert.h>
#include <endian.h>

#define Nvols 30

#define BASS_WINDOW 60
#define MID_WINDOW 4

struct training_info {
    double bass_volumes[Nvols];
    double mid_volumes[Nvols];
    double treble_volumes[Nvols];
    int n;
};

struct training_info yes;
struct training_info no;

static int __attribute__((const)) mod(int n, int d) {
    int m = n % d;
    if (m < 0) m+=d;
    return m;
}

// harccoded to 2 channel s16le
int get_file_info(const char* name, struct training_info *inf) {
    FILE* in = fopen(name, "rb");

    if (!in) return -1;

    setvbuf(in, NULL, _IOFBF, 65536);

    inf->n = 1;

    fseek(in, 0, SEEK_END);
    long filesize = ftell(in);
    fseek(in, 128, SEEK_SET);
    filesize -= 128; // exclude header and some initial samples

    int nsamples = filesize / 4;

    double bass_a=0, mid_a=0;
    const int HISTSIZE  = 101;
    double xhistory[HISTSIZE];
    int histpointer=0;
    int histsize = 0;

    //FILE* out = fopen("debug.raw", "wb");

    int i;
    for (i=0; i<Nvols; ++i) {
        int j;

        double total_vol = 0;
        double bass_vol = 0;
        double mid_vol = 0;
        double treble_vol = 0;

        for (j=0; j<nsamples / Nvols; ++j) {
            signed short int l, r; // a sample
            if(fread(&l, 2, 1, in)!=1) break;
            if(fread(&r, 2, 1, in)!=1) break;
            double x = 1/65536.0 * ( le16toh(l) + le16toh(r) );

            bass_a += x;
            mid_a  += x;

            if (histsize == HISTSIZE-1) bass_a   -= xhistory[mod(histpointer-BASS_WINDOW,HISTSIZE)];
            if (histsize == HISTSIZE-1) mid_a    -= xhistory[mod(histpointer-MID_WINDOW ,HISTSIZE)];

            double bass = bass_a / BASS_WINDOW;
            double mid = mid_a / MID_WINDOW - bass;
            double treble = x - mid_a/MID_WINDOW;

            xhistory[histpointer++] = x;
            if(histpointer>=HISTSIZE) histpointer=0;
            if(histsize < HISTSIZE-1) ++histsize;

            total_vol  += bass*bass + mid*mid + treble*treble;
            bass_vol   += bass*bass;
            mid_vol    += mid*mid;
            treble_vol += treble*treble;

            /*
            signed short int y;
            y = 65536 * bass;

            y = htole16(y);
            fwrite(&y, 2, 1, out);
            fwrite(&y, 2, 1, out);
            */
        }

        inf->bass_volumes[i] = bass_vol / total_vol;
        inf->mid_volumes[i] = mid_vol / total_vol;
        inf->treble_volumes[i] = treble_vol / total_vol;

        //fprintf(stderr, "%lf %lf %lf    %s\n", inf->bass_volumes[i], inf->mid_volumes[i], inf->treble_volumes[i], name);
    }
    fclose(in);

    return 0;
}

static void zerotrdata(struct training_info *inf) {
    int i;
    inf->n = 0;
    for (i=0; i<Nvols; ++i) {
        inf->bass_volumes[i] = 0;
        inf->mid_volumes[i] = 0;
        inf->treble_volumes[i] = 0;
    }
}

static void train1(const char* prefix, struct training_info *inf)
{
    char buf[50];

    int i;

    for(i=0;; ++i) {
        sprintf(buf, "%s%d.wav", prefix, i);
        struct training_info ti;
        if(get_file_info(buf, &ti)) break;

        ++inf->n;

        int j;
        for (j=0; j<Nvols; ++j) {
            inf->bass_volumes[j]   += ti.bass_volumes[j];
            inf->mid_volumes[j]    += ti.mid_volumes[j];
            inf->treble_volumes[j] += ti.treble_volumes[j];
        }
    }

    int j;
    for (j=0; j<Nvols; ++j) {
        inf->bass_volumes[j]   /= inf->n;
        inf->mid_volumes[j]    /= inf->n;
        inf->treble_volumes[j] /= inf->n;
    }
}

static void print_part(struct training_info *inf, FILE* f) {
    fprintf(f, "%d\n", inf->n);
    int j;
    for (j=0; j<Nvols; ++j) {
        fprintf(f, "%lf %lf %lf\n", inf->bass_volumes[j], inf->mid_volumes[j], inf->treble_volumes[j]);
    }
}

static void train() {
    zerotrdata(&yes);
    zerotrdata(&no);

    fprintf(stderr, "Training...\n");

    train1("train/yes", &yes);
    train1("train/no", &no);

    fprintf(stderr, "Training completed.\n");

    //print_part(&yes, stderr);
    //print_part(&no, stderr);

    int j;
    for (j=0; j<Nvols; ++j) {
        if (yes.bass_volumes[j]   > no.bass_volumes[j]) {   yes.bass_volumes[j] = 1;   no.bass_volumes[j] = 0; }
        if (yes.mid_volumes[j]    > no.mid_volumes[j]) {    yes.mid_volumes[j] = 1;    no.mid_volumes[j] = 0; }
        if (yes.treble_volumes[j] > no.treble_volumes[j]) { yes.treble_volumes[j] = 1; no.treble_volumes[j] = 0; }
    }
}

double delta(struct training_info *t1, struct training_info *t2) {
    int j;
    double d = 0;
    for (j=0; j<Nvols; ++j) {
        double rb = t1->bass_volumes[j] - t2->bass_volumes[j];
        double rm = t1->mid_volumes[j] - t2->mid_volumes[j];
        double rt = t1->treble_volumes[j] - t2->treble_volumes[j];
        d += rb*rb + rm*rm + rt*rt;
    }
    return d;
}

int main(int argc, char* argv[])
{
    (void)argc; (void)argv;

    train();

    int i;

    int yes_count = 0;
    int no_count = 0;

    for (i=0;; ++i) {
        char buf[60];
        sprintf(buf, "inputs/%d.wav", i);

        struct training_info ti;

        if(get_file_info(buf, &ti)) break;

        double dyes = delta(&yes, &ti);
        double dno = delta(&no, &ti);

        //printf("%lf %lf %s ", dyes, dno, buf);

        if (dyes > dno) {
            printf("no\n");
            ++no_count;
        } else  {
            printf("yes\n");
            ++yes_count;
        }
    }

    fprintf(stderr, "yeses: %d noes: %d\n", yes_count, no_count);

}

```

# Answer
> 27 votes
# C++11 (gcc; ~~1639~~ ~~1625~~ 1635 bytes, Class 1, score=983, 960)

Let's get it started. It's probably the longest code I've ever shortened...

```
#include <bits/stdc++.h>
#define $ complex<double>
#define C vector<$>
#define I int
#define D double
#define P pair<D,I>
#define Q pair<D,D>
#define E vector<D>
#define V vector<P>
#define W vector<Q>
#define S char*
#define Z(x)if(fread(&x,2,1,y)!=1)break;
#define B push_back
#define F(i,f,t)for(I i=f;i<t;i++)
#define _ return
#define J first
#define L second
const I K=75,O=16384;using namespace std;C R(C&i,I s,I o=0,I d=1){if(!s)_ C(1,i[o]);C l=R(i,s/2,o,d*2),h=R(i,s/2,o+d,d*2);C r(s*2);$ b=exp($(0,-M_PI/s)),f=1;F(k,0,s){r[k]=l[k]+f*h[k];r[k+s]=l[k]-f*h[k];f*=b;}_ r;}C T(C&i){_ R(i,i.size()/2);}char b[O];E U(S m){FILE*y;if(!(y=fopen(m,"r")))_ E();setvbuf(y,b,0,O);fseek(y,0,2);I z=ftell(y)/4-32;fseek(y,128,0);C p;F(i,0,z){short l,r;Z(l);Z(r);if(i&1)p.B($(0.5/O*le16toh(l),0));}p.resize(O);E h(O),n(O);p=T(p);F(j,0,O)h[j]=norm(p[j])/O;F(i,1,O-1)n[i]=(h[i-1]+h[i+1]+h[i]*8)/10;fclose(y);_ n;}W G(E&d){V p;F(i,3,O/2-3)if(d[i]==*max_element(d.begin()+i-3,d.begin()+i+4))p.B({d[i],i});sort(p.begin(),p.end(),greater<P>());W r;F(i,3,K+3)r.B({D(p[i].L)/O*22050,log(p[i].J)+10});D s=0;F(i,0,K)s+=r[i].L;F(i,0,K)r[i].L/=s;_ r;}char m[O];I X(S p,W&r){E t(O),h(t);I f=0;while(1){sprintf(m,"%s%d.wav",p,f++);h=U(m);if(!h.size())break;F(j,0,O)t[j]+=h[j];}F(j,0,O)t[j]/=f;r=G(t);}D Y(W&a,W&b){D r=0;F(i,0,K){D d=b[i].L;F(j,0,K)if(abs((b[i].J-a[j].J)/b[i].J)<0.015)d=min(d,abs(b[i].L-a[j].L));r+=d;}_ r;}I H(S p,W&y,W&n){I f=0;while(1){sprintf(m,"%s%d.wav",p,f++);E h=U(m);if(!h.size())break;W p=G(h);D q=Y(p,y),r=Y(p,n);printf(abs(q-r)<=0.01?"?\n":q<r?"yes\n":"no\n");}}I main(){W y,n;X("train/yes",y);X("train/no",n);H("inputs/",y,n);}

```

"Ungolfed" (although it's hard to call an over 1.5K source code golfed):

```
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <vector>
#include <math.h>
#include <complex>
#include <endian.h>
#include <functional>

using namespace std;

typedef complex<double> CD;

vector<CD> run_fft(vector<CD>& input, int offset, int size, int dist){
    if(size == 1){
        return vector<CD>(1, input[offset]);
    }
    vector<CD> partLow = run_fft(input, offset, size/2, dist*2),
               partHi  = run_fft(input, offset+dist, size/2, dist*2);

    vector<CD> result(size);
    CD factorBase = exp(CD(0, (inv?2:-2)*M_PI/size)), factor = 1;

    for(int k = 0; k < size/2; k++){
        result[k] = partLow[k] + factor*partHi[k];
        result[k+size/2] = partLow[k] - factor*partHi[k];
        factor *= factorBase;
    }
    return result;
}

vector<CD> fft(vector<CD>& input){
    int N = input.size();
    return run_fft(input, 0, N, 1);
}

const int MAX_BUF = 65536;
const int PWR_TWO = 16384;
const int NUM_CHECK = 75;
int sampling;

char buf[MAX_BUF];
vector<double> read_data(char* filenam){
    FILE* fp = fopen(filenam, "r");
    if(!fp)
        return vector<double>();
    setvbuf(fp, buf, _IOFBF, MAX_BUF);

    fseek(fp, 0, SEEK_END);
    int filesiz = ftell(fp);
    fseek(fp, 128, SEEK_SET);
    filesiz -= 128;

    int insamp = filesiz / 4;
    int freqsamp = 2,
        act_mod = 0;
    sampling = 44100 / freqsamp;
    int inputSize;

    vector<CD> input;

    for(int i = 0; i < insamp; i++){
        signed short int l, r;
        if(fread(&l, 2, 1, fp) != 1) break;
        if(fread(&r, 2, 1, fp) != 1) break;

        double act = 1/32768.0 * (le16toh(l));

        if((++act_mod) == freqsamp){
            inputSize++;
            input.push_back(CD(act,0));
            act_mod = 0;
        }
    }
    inputSize = input.size();

    //printf("%s\n", filenam);
    int numParts = (inputSize+PWR_TWO-1)/PWR_TWO;
    double partDelta = (double)inputSize / numParts, actDelta = 0;
    vector<CD> ndata(PWR_TWO);
    for(int i = 0; i < numParts; i++){
        vector<CD> partInput(PWR_TWO);
        int from = floor(actDelta),
            to = floor(actDelta)+PWR_TWO;

        for(int j = from; j < to; j++)
            partInput[j-from] = input[j];

        vector<CD> partData = fft(partInput);
        for(int j = 0; j < PWR_TWO; j++)
            ndata[j] += partData[j]*(1.0/numParts);
    }

    vector<double> height(PWR_TWO);
    for(int i = 0; i < PWR_TWO; i++)
        height[i] = norm(ndata[i])/PWR_TWO;

    vector<double> nheight(height);
    nheight[0] = (height[0]*0.8 + height[1]*0.1)/0.9;
    nheight[PWR_TWO-1] = (height[PWR_TWO]*0.8 + height[PWR_TWO-1]*0.1)/0.9;
    for(int i = 1; i < PWR_TWO-1; i++)
        nheight[i] = height[i-1]*0.1 + height[i]*0.8 + height[i+1]*0.1;

    fclose(fp);

    return nheight;
}

vector< pair<double,double> > get_highest_peaks(vector<double>& freqData){
    vector< pair<double,int> > peaks;

    for(int i = 3; i < PWR_TWO/2-3; i++){
        if(freqData[i] == *max_element(freqData.begin()+i-3, freqData.begin()+i+4)){
            peaks.push_back(make_pair(freqData[i], i));
        }
    }

    sort(peaks.begin(), peaks.end(), greater< pair<double,int> >());

    vector< pair<double,double> > res;
    for(int i = 3; i < NUM_CHECK+3; i++){
        res.push_back(make_pair((double)(peaks[i].second)/PWR_TWO*sampling, log(peaks[i].first)+10));
    }

    double sum_res = 0;
    for(int i = 0; i < NUM_CHECK; i++)
        sum_res += res[i].second;
    for(int i = 0; i < NUM_CHECK; i++)
        res[i].second /= sum_res;

    /*for(int i = 0; i < NUM_CHECK; i++)
        printf("%12lf %12lf\n", res[i].first, res[i].second);
    printf("\n");*/

    return res;
}

void train(char* dir, const char* type, vector< pair<double,double> >& res){
    vector<double> result(PWR_TWO), height(PWR_TWO);

    int numFile = 0;
    while(true){
        char filenam[256];
        snprintf(filenam, 255, "%s/%s%d.wav", dir, type, numFile);
        height = read_data(filenam);

        if(height.size() == 0)
            break;

        for(int j = 0; j < PWR_TWO; j++)
            result[j] += height[j];

        numFile++;
    }
    fprintf(stderr, "trained %s on %d files\n", type, numFile);

    for(int j = 0; j < PWR_TWO; j++)
        result[j] /= numFile;

    res = get_highest_peaks(result);
}

double dist_ab(vector< pair<double,double> >& A, vector< pair<double,double> >& B){
    double result = 0;
    for(int i = 0; i < NUM_CHECK; i++){
        double add = B[i].second;

        for(int j = 0; j < NUM_CHECK; j++){
            double dist = (B[i].first-A[j].first)/B[i].first;
            if(abs(dist) < 0.015)
                add = min(add, abs(B[i].second - A[j].second));
        }
        result += add;
    }
    return result;
}

void trial(char* dir, const char* pref, vector< pair<double,double> >& yes,
                                        vector< pair<double,double> >& no){
    int numFile = 0;
    int numYes = 0, numDunno = 0, numNo = 0;
    while(true){
        char filenam[256];
        snprintf(filenam, 255, "%s/%s%d.wav", dir, pref, numFile);

        vector<double> height = read_data(filenam);
        if(height.size() == 0)
            break;

        vector< pair<double,double> > peaks = get_highest_peaks(height);

        double distYes = dist_ab(peaks, yes),
               distNo = dist_ab(peaks, no);

        if(abs(distYes-distNo) <= 0.01){
            printf("dunno\n");
            numDunno++;
        } else if(distYes < distNo){
            printf("yes\n");
            numYes++;
        } else {
            printf("no\n");
            numNo++;
        }
        //printf(" (%lf %lf)\n", distYes, distNo);

        numFile++;
    }
}

int main(int argc, char** argv){
    vector< pair<double,double> > yes, no;

    train("train", "yes", yes);
    train("train", "no", no);

    trial("inputs", "", yes, no);
}

```

I have no freaking idea if it will work correctly on real data set (I bet it won't, but I must have a try).

How it works:

1. Take N=214 samples from left channel, each in equal time span. Normalize them so that min value=0 and max value=1.
2. Process them using FFT. Now we switched from time domain to frequency domain. We might say that 0th cell of resulting array is 0Hz equivalent and 213-1st cell is 22050Hz equivalent (that is because I took every other sample from L channel, so my sampling is 22050Hz instead of WAV's frequency, 44100Hz).
3. Find the mean of all such signals - call it "mean frequency distribution". Find K highest peaks in such distribution (here K=75), omitting first few (probably noise) and find their strength. I used `log(mean distribution)+10` and then normalized so that the sum of the biggest peaks was 1.
4. We have two "peak distributions" - one for Yes, second for No. If we have a WAV to test, we transform it in the same way as before (steps 1, 2, 3) and get distribution D. Then we have to check which distribution (Y/N) D is more similar to. I used the following approach: for each peak in Y/N, try to find it in D. If we find it (approximately), the score for this peak is absolute difference between Y/N's and D's strength; in opposite case, it's Y/N's strength (we assume it's always positive). Better (smaller) score wins. If the results are very close (I used 0.01 absolute difference), output `dunno`.

As I said, probably on final tests it will be classified as "even worse than random". Of course, I hope it won't :D

**Edit:** fixed bug (forgot to close the files).

---
Tags: code-golf, classification, audio, test-battery
---


title: Implement an 8 bit adder

text:
# Question
Title: Implement an 8 bit adder
## The Challenge

Implement a function which accepts two integers whose values range from 0 - 255 and returns the sum of those integers mod 256. You may only use bitwise negation (~), bitwise or (|), bit shifting operators (\>\>,\<\<), and assignment (=).

Things you cannot use include (but are not limited to)

* Addition, subtraction, multiplication, and division
* Loops
* Conditional statements
* Function calls

*Fewest uses of binary or, binary negation, and bit shift operations wins*. In the event of a tie, the most popular solution wins. As always, standard loopholes apply.

Here is an example of a simple 2-bit adder. It uses 77 binary negations, 28 binary ors, and 2 bit-shifts for a total score of 107 (this can be seen by running the C preprocessor with `gcc -E`). It could be made much more efficient by removing the `#define`s and simplifying the resulting expressions, but I've left them in for clarity.

```
#include <stdio.h>

#define and(a, b) (~((~a)|(~b)))
#define xor(a, b) (and(~a,b) | and(a,~b))

int adder(int a, int b)
{
    int x, carry;
    x = xor(and(a, 1), and(b, 1));
    carry = and(and(a, 1), and(b, 1));
    carry = xor(xor(and(a, 2), and(b, 2)), (carry << 1));
    x = x | carry;
    return x;
}

int main(int argc, char **argv)
{
    int i, j;
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            if (adder(i, j) != (i + j) % 4) {
                printf("Failed on %d + %d = %d\n", i, j, adder(i, j));
            }
        }
    }
}

```

Update: Added example and changed scoring critera

# Answer
## Python, 36 operations

A methods that's logarithmic in the parameter "8"!

```
def add(a,b):
    H = a&b   #4 for AND
    L = a|b   #1
    NX = H | (~L) #2
    K = NX

    H = H | ~(K | ~(H<<1)) #5
    K = K | (K<<1) #2

    H = H | ~(K | ~(H<<2)) #5
    K = K | (K<<2) #2

    H = H | ~(K | ~(H<<4)) #5

    carry = H<<1 #1

    neg_res = NX ^ carry  #7 for XOR
    res_mod_256 = ~(neg_res|-256) #2
    return res_mod_256

```

The idea is to figure out which indices overflow and cause carries. Initially, this is just the places where both `a` andd `b` have a `1`. But since carried bits can cause further overlows, this needs to be determined iteratively.

Rather than overflowing each index into the next one, we speed up the process by moving 1 index, then 2 indices, then 4 indices, being sure to remember places where an overflow happened (H) and where an overflow cannot happen any more (K).

---

A simpler iterative solution with **47** operations:

```
def add(a,b):
    H = a&b   #4 for AND
    L = a|b   #1
    NX = H | (~L) #2

    c=H<<1  #1

    for _ in range(6): #6*5
        d = (~c)|NX
        e = ~d
        c = c|(e<<1)

    res = c ^ NX  #7 for XOR

    res_mod_256 = ~(res|-256) #2
    return res_mod_256

```

---

Test rig, for anyone who wants to copy it.

```
errors=[]
for a in range(256):
    for b in range(256):
        res = add(a,b)
        if res!=(a+b)%256: errors+=[(a,b,res)]

print(len(errors),errors[:10])

```
> 9 votes

# Answer
# C - 0

It does use operators outside of ~, |, \>\>, \<\<, and =, but I see solutions using casting and comma operators, so I guess the rule isn't too strict provided it isn't using the forbidden operators.

```
unsigned char sum(unsigned char x, unsigned char y)
{
    static unsigned char z[] = {
        0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
        16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
        32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
        48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
        64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
        80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
        96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
        112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
        128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
        144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
        160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
        176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
        192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
        208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
        224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
        240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
        0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
        16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
        32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
        48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
        64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
        80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
        96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
        112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
        128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
        144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
        160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
        176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
        192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
        208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
        224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
        240,241,242,243,244,245,246,247,248,249,250,251,252,253,254
    };

    return (&z[x])[y];
}

```
> 9 votes

# Answer
## python, score = 83 80

```
def g(x,y):
    for i in xrange(7):
        nx = ~x
        ny = ~y
        x,y = ~(x|ny)|~(nx|y), (~(nx|ny))<<1
    x = ~(x|~y)|~(~x|y)
    return ~(~x|256)

```

Unroll the loop. It's 10 ops per loop times 7 loops, 7 for the last xor, and 3 to squash the 9th bit at the end.

Implements the equation `x+y = x^y + 2*(x&y)` by repeating it 8 times. Each time there is one more zero bit at the bottom of `y`.
> 7 votes

# Answer
# C, Score: 77 60

Golfed just for the hell of it, 206 169 131 bytes:

```
#define F c=((~(~c|~m))|n)<<1;
a(x,y){int m=(~(x|~y))|~(~x|y),n=~(~x|~y),c;F F F F F F F return (unsigned char)(~(m|~c))|~(~m|c);}

```

Expanded:

```
int add(x,y)
{
    int m=(~(x|~y))|~(~x|y);
    int n=~(~x|~y);
    int c = 0;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    c=((~(~c|~m))|n)<<1;
    return (int)((unsigned char)(~(m|~c))|~(~m|c));
}

```

Essentially the same solution (mathematically) that @KeithRandall @JuanICarrano came up with, but takes advantage of C's ability to play fast and loose with variable types and pointers to wipe everything after the first 8 bits without using any more operators.

Depends on the endian-ness of the machine and the sizeof() an int and a char, but should be able to be ported to most machine specific applications with the proper pointer math.

**EDIT:** This is a challenge that C (or other low level languages) will have a distinct upper hand at -- unless somebody comes up with an algorithm that doesn't have to carry.
> 7 votes

# Answer
# Python - Score ~~66~~ 64

```
def xand(a,b):
    return ~(~a|~b) #4

def xxor(a,b):
    return (~(a|~b))|~(~a|b) #7

def s(a,b):
    axb = xxor(a,b)   #7
    ayb = xand(a,b)   #4

    C = 0
    for i in range(1,8):
        C = ((xand(C,axb))|ayb)<<1    #(1+1+4)x7=6x7=42

    return xxor(axb,xand(C,255))    #7 + 4 = 11
    #total: 7+4+42+11 = 64

```

It is the equation for a ripple adder. C is the carry. It is computed one bit at a time: in each iteration the carry is propagated left. As pointed out by @Orby, the original version did not make a modular addition. I fixed it and also saved a cycle in the iteration, as the first carry-in is always zero.
> 4 votes

# Answer
# C++ - score: 113

```
#define ands(x, y) ~(~x | ~y) << 1
#define xorm(x, y) ~(y | ~(x | y)) | ~(x | ~(x | y))

int add(int x, int y)
{
int x1 = xorm(x, y);
int y1 = ands(x, y);

int x2 = xorm(x1, y1);
int y2 = ands(x1, y1);

int x3 = xorm(x2, y2);
int y3 = ands(x2, y2);

int x4 = xorm(x3, y3);
int y4 = ands(x3, y3);

int x5 = xorm(x4, y4);
int y5 = ands(x4, y4);

int x6 = xorm(x5, y5);
int y6 = ands(x5, y5);

int x7 = xorm(x6, y6);
int y7 = ands(x6, y6);

int x8 = xorm(x7, y7);
int y8 = ands(x7, y7);

return (x8 | y8) % 256;
}

```
> 2 votes

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


title: Write a Program in Disguise

text:
# Question
Title: Write a Program in Disguise
The challenge is to create a program that solves *any one* of the HQ9+ problems while looking like another language.

**Note**: This is not a golf challenge.

## Rules:

* The program must perform one of the following tasks when run.
    + Print "Hello, World!"
    + Print its entire source.
    + Print the lyrics to "99 Bottles of Beer on the Wall" (as seen here).
* At first glance the program should look like another language.

## Grading

* Working program that satisfies the rules. **+3**
* Bonus points if the "other language" can be run (syntax valid). **+1**
* Even more points if the "other language" can do something useful. **+3**
* Lots of bonus points for the program being valid (and useful) in even more languages. **+5** for each language over 2.

# Answer
## T-SQL

```
Print 'Hello, World!' -- she said.

```

Looks like **English**.
> 20 votes

# Answer
# Ruby + C + Whitespace.

This program is C but looks like (and runs as) Ruby. I also managed to throw some whitespace in there.

C prints its own source (not quite a quine unfortunately). Ruby prints 99 bottles of beer and whitespace says hello.

```
#include <stdio.h>
#define def int
#define beer main(int i){char b[1024];
#define print(v) print(int v){
#define end ;}
#define if(x) fputs(b,stdout); fgets(b,1024,f); if(x){
#define else ;} else{
#define puts
#define print
#define open(fn) FILE *f = fopen(fn,"r");
#define while(x) fgets(b,1024,f); while(!feof(f)){

def beer
    # define beer

    open("test.c")

   i=100;

    while ( i >= 0 )
        if ( i > 0 )
            print "#{i} bottle#{i==1&&''||'s'} of beer on the wall, "
            puts  "#{i} bottle#{i==1&&''||'s'} of beer."
            print "Take one down and pass it around, "
            puts  "#{i-1} bottle#{i==2&&''||'s'} of beer on the wall."
            puts
        else
            puts "No more bottles of beer on the wall, no more bottles of beer."
            puts "Go to the store and buy some more, 99 bottles of beer on the wall."
        end
        i -= 1
    end

    return 0
end

beer

```

And since SO isn't very nice to ws here is a link.
> 18 votes

# Answer
# Golfscript / HQ9+

```
9

```

A Golfscript quine that doubles as an HQ9+ program that prints the lyrics to 99 bottles of beer.

I know this isn't a golf challenge, but I couldn't resist the desire to answer this with one character.
> 15 votes

# Answer
## Perl, 7 points

```
99 <?php
for($i='no more',$_="`\2l\";7hF'`-{9\17p\t\2ZY\14fE\25T\133J`\35l\"76~\x3";
99>${2}="$i bottle".(${$i+=1}<'))'?+s?:s:!'((').' of beer';
${3}="
Take one down and pass it around, ${1}.

".ucfirst("${1}, ${2}.${3}"))${1}=$i||${2}?"${2} on the wall":'?;\'';
print substr("${1}, ${2}.${3}".
($_^"jE\3\2OXH2O\5\15\10M$_").", ${2} on the wall.",3,13*$i*$i);

```

This is a Perl program that prints `Hello, World!`.

**Score breakdown:**

* Follows all rules: **+3**
* Is valid syntax in another language: **+1**
* Does something interesting in the other langauge: **+3**

**Sidenote:**

Once you know what it does it might seem 'obvious' where it's hanging out, but this is a dupe.

The following:

```
$_="`\2l\";7hF'`-{9\17p\t\2ZY\14fE\25T\133J`\35l\"76~\x3";
print$_^"jE\3\2OXH2O\5\15\10M$_"

```

will output:

```
Go to the store and buy some moreET[J`l"76~

```
> 7 votes

# Answer
# JavaScript, 7 points

```
<!--
h='Hello, World!'
-->

/******<br>

<b>Hello, World!</b><br>

*******<br>

This is my <i>awesome</i> Hello World page<br>

*******<br>

Look I can make images I'm so good at HTML:<br>
<img src='http://pieisgood.org/images/slice.jpg' alt='awwww you cannot see my amazing image' /><br>
<hr>

These are the things this page has:<br>
<ul>
<li>Bold</li>
<li>Italics</li>
<li>Images</li>
<li>Lists</li>
</ul><br>

I like random characters! That's what this page will finish with:<br>
;37!&$89]"]0(!)89^!&8*/81+-0;h

```

When run in JavaScript, produces "Hello, World!"

When viewed as HTML, looks like this:

# Scoring

* Working program that satisfies the rules **+3**
* Other language syntax is valid **+1**
* Other language does something useful (you can put any HTML you want in there) **+3**
> 7 votes

# Answer
**C++/Python**

```
#include <iostream>

#define print(a) int main() {std::cout << a << std::endl;}

print("Hello, World!")

```

Will run in Python (both 2.x and 3.x) and compile in C++ to print (with carriage return):

> Hello, World!
> 7 votes

# Answer
The following prints "Hello,World" (and a random table) in HTML and "Hello, World!" in Whitespace.

```
<html>
<head>
<title>
Hello,World!
</title>
<body>
<p>
Hello,World!
</p>
<table>
<caption>
Summary
</caption>
<tbody>
<tr>
<th>Year</th>
<th>Revenue</th>
</tr>
<tr>
<td>2012</td>
<td>$100,000</td>
</tr>
</tbody>
</table>
<footer>
HTML5!
</footer>
<!--Comment-->
</html>

```
> 6 votes

# Answer
# PHP, HQ9+, Brainfuck and Bash (23 points, I think)

Looks like PHP, but...

Abuse of STDERR redirection and quotes.

```
what the >&_@ is a "<?php
//Boring, really ( ;[ ). This just prints Hello World!"
echo "Hello, World!"; //]&> are random characters that I like putting in"
?>" program?

```

This runs and does things in all the languages listed, but looks like (slightly weird) PHP code.

In Bash, it merely prints "Hello, World!" (creating junk files along the way).

In HQ9+, it prints Hello World a few times (once for every occurence of `H` or `h`).

In Brainfuck, it is a "cat program" - it reads from standard input and outputs its input to standard output (`><,[.,]>>`).

In PHP, it prints some text:

> what the \>&\_@ is a "Hello, World!" program?

## Bash Explanation

`>&_@` is disguised as harmless text substituting a curse, but it is in fact a redirection of STDERR to the file `_@`, so that Bash doesn't complain that `what` is not a valid program. It also eats the `is a <?php` bit and the first comment.

The first comment has a quote at the end (the quotes are there to prevent `<?php` from being run). `echo "Hello, World!";` runs normally in both languages. The next comment serves to hide another quote, and there is an output redirection from STDERR to the file `are`, to eat the message " //: Is a directory".

Since the closing `?>` is in quotes, it doesn't get run, and gets eaten along with the second comment and the bit after it.
> 5 votes

# Answer
## JavaScript, 3p

```
<!--
$res = Array();
$ks  = Array("", "", "");

function convert($x) { return $x["toString"](36); }
for ($i=0; $i < 1000000; $i++) {
  this[convert($i)] = $i;

  if ($i == 626 || $i == 777 || $i == 865 || $i == 1176 || $i == 35761)
    $res[$res.length] = convert($i);

  if ($i == 381  || $i == 19145) $ks[0] += convert($i);
  if ($i == 19   || $i == 31775) $ks[1] += convert($i);
  if ($i == 1033 || $i == 27893) $ks[2] += convert($i);
}
this[$ks[0]]($res[$ks[1]]("")[$ks[2]](1)[$ks[1]](" "));
-->

yay

<h1>hi</h1>   /// heading
<p>lol</p>    /// content

```

Masquerades the output of a misconfigured web server, as (something that at first glance looks like) **PHP+HTML** mess.

This started out small but grew bigger as I tried to make it less obvious what it does (when evaluated as JS)... it might've become more obfuscated than the task intended, sorry about that. Anyway, the main thing I wanted to include was my trick for embedding (a subset of) HTML such that it's also valid JavaScript code, which is what you see at the end of the code.

Edit: oh, I should mention, *when run in a website context the code alerts "hello world"*.
> 4 votes

# Answer
# Python/PHP/Lua/Perl/Perl 6/Ruby/JavaScript/HQ9+ (37 points)

```
print("Hello, World!")

```

This looks like "Hello, World" in Python, but it's actually a quine written in PHP. It also works in JavaScript (SpiderMonkey), Lua, HQ9+, Perl, Perl 6 and Ruby, for bonus points.
> 2 votes

# Answer
# JavaScript/Python 3/PHP/Lua/Brainfuck/bash

This looks like... Umm... Obfuscated PHP?

```
#!,[.,]
echo = --[[0] ] [0][0] //1#>/dev/null;echo Hello, World!;exit # ]]0
--[[0] ] [0][0] //1#<?php for ($i = 99; $i > 1;) { printf("%d bottles of beer on the wall, %d bottles of beer.\nTake one down and pass it around. %d bottle%s of beer on the wall.\n\n", $i, $i, --$i, ($i != 1 ? "s" : "")); } print("1 bottle of beer on the wall, 1 bottle of beer.\nTake on e down and pass it around. No more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more. 99 bottles of beer on the wall.\n"); die(); ?>
2//2; print("Hello world!"); exit();"""
console.log("Hello, World!");/*]]
f = io.open(arg[0])
print(f:read("*a"))
--[[*///]]--"""

```
* If you run it in bash, JavaScript or Python it'll print "Hello, World!"
* If you run it in Lua, it'll print the script's source code (if provided as the first argument to `lua`).
* If you run it in PHP it'll print the lyrics of 99 bottles of beer
* If you run it as Brainfuck, it'll work like `cat`.

## Score: 27

* Follows the rules: 3
* Other language can run: 1
* Does something useful: 3 (cat program)
* Also works in JS/Python 3/Lua/bash: 20

I hope I'm not bending the rules too much :)
> 2 votes

# Answer
**Java written in C++**

```
#include <stdio.h>

typedef char* String;

class P{
public:
    static void println(String s){
        puts(s);
    }
};

class S{
public:
    P out;
};

int main()
{
    S System;
    System.out.println("Hello world!");
    return 0;
}

```

Score 3 points.
> 0 votes

# Answer
```
print `open(__file__).read()`, 1000 // len('''
/* Calculate code conciseness score for some random JavaScript */

function print() {
    console.log('Hello, world!');
}

<!--''') # ASCII submarine

```

This looks like Python 2, and runs as Python 2, printing its own source in Python string literal form, as well as a code conciseness score of some kind! When run as ES6, however, it prints “Hello, world!”.
> 0 votes

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


title: Draw centered polygonal numbers

text:
# Question
Title: Draw centered polygonal numbers
A centered polygonal number is able to be put into an arrangement of multiple concentric polygons, each with a side length of one more than the inner one. For example (image from linked page),

the above image has 31 dots, so 31 is a *centered pentagonal number*.

Write a program which receives a number as input (any typical input method is fine), and displays a picture similar to the above.

In particular:

* There must be a centered dot.
* Each concentric polygon contains an increasing number of dots, all connected through a line.
* The angles must be correct for the appropriate regular polygon.
* The distance between connected dots must be the same throughout the picture.
* Each polygon must be centered inside the surrounding polygon.

The input will be between 2 and 1000, and is guaranteed to be a centered polygonal number of some kind.

If there are multiple possible solutions, display them all. For example, an input of 181 should display both a centered square (of 9 "rings") and a centered pentagon (of 8 "rings").

No hardcoding answers.

# Answer
# HTML + JS, ~~913~~ ~~857~~ 675 bytes

(Line breaks are added for readability)

```
<body><script>
function O(X,x,y,R){X.beginPath();X.arc(x,y,R,0,M.PI*2,true);X.closePath();X.fill()}
Z=300,P=3,H=Z/2,$=+prompt(),M=Math;for(S=3;S<$;S++){for(C=1;C<30;C++){if(S*C*C+S*C+2==$*2){
V=document.createElement("canvas");V.width=V.height=Z;document.querySelector("body").appendChild(V);X=V.getContext("2d");
O(X,H,H,P);for(R=1;R<=C;R++){
D=[],A=R*(H-P)/C,G=0;X.beginPath();X.moveTo(H+A,H);D.push([H+A,H]);for(s=1;s<S;s++){x=M.cos(G+=M.PI*2/S)*A,y=M.sin(G)*A;X.lineTo(H+x,H+y);D.push([H+x,H+y])}X.closePath();X.stroke();
for(j=0;j<D.length;j++){x=D[j][0],y=D[j][1],q=D[(j+1)%S][0]-x,w=D[(j+1)%S][1]-y;O(X,x,y,P);for(k=0;k<R-1;k++)O(X,x+=q/R,y+=w/R,P)}
}break}}}
</script></body>

```

This is working jsfiddle example, and ungolfed source. It gets input from `prompt()`. You can adjust output size by adjusting `sz = 300`, and dot size by `pt = 3` (in pixels).

## Example (31 dots)
> 6 votes

# Answer
# Python - ~~189, 258, 251, 249, 239, 222~~ 219

```
from pylab import*
m=input()-1;R=arange
for j in R(1,m):
 i=2.*m/(j*j+j);f=2*pi/i
 if i%1==0:
  figure();axis('equal')
  for r in R(j+1):o=f*R(i);s=R(r+1)[:,None];t=r-s;plot(t*cos(o)+s*cos(o+f),t*sin(o)+s*sin(o+f),'.-')

```

**Example output for n = 31:**

(Not sure if the first one is valid...)
> 3 votes

# Answer
## HTML5 + JS (378 364 chars)

```
<script>P='<svg><path stroke=red fill=none d='
C=''
N=prompt()-1
M=Math
for(i=t=1;N>t*2;t+=i)for(r=148/i,j=++i;N%t<1&&j--;)for(A=2*M.PI*t/N,y=150,x=j*r+310*i,P+='M'+x+','+y,a=s=0;s<N;s+=t)for(a+=A,k=-!j;k++<j;P+='L'+x+','+y,C+='<circle fill=red r=2 cx='+x+' cy='+y+' />')if(j)x+=(M.cos(a)-M.cos(a-A))*r,y+=(M.sin(a)-M.sin(a-A))*r
document.write(P+' />'+C)</script>

```

Online demo. Sorry about the long line, but it cannot be split without increasing the character count. Every semicolon which could be replaced by a newline courtesy of JavaScript's semicolon insertion has been replaced. Every space character is inside a string literal.

As with my previous "drawing in HTML" answer, SVG is slightly shorter than canvas.

Since the question doesn't say anything about positioning, I've saved a couple of characters by not guaranteeing that the diagrams will be evenly spaced.
> 2 votes

# Answer
# BBC BASIC, 281 ASCII characters, tokenised filesize 236

Emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

Newlines are required and included in the score.

```
  c=400INPUTa:n=1t=0REPEATt+=n:s=(a-1)/t:r%=c/n/2CLS:MOVEc,c:s%=s:IFs%=s u=r%*2:v=0FORp=1TOs%q%=r%*COS(p/s%*2*PI)x=q%*2q%=r%*SIN(p/s%*2*PI)y=q%*2q=FNt(n)u=x:v=y:NEXT:q=GET
  n+=1UNTILs<=3END
  DEFFNt(d)PLOT153,8,0MOVEBY-8,0IFd MOVEBY u,v:q=FNt(d-1)DRAWBY x-u,y-v:q=FNt(d-1)MOVEBY-x,-y
  =0

```

A centered `s`-gonal number is of the form `(triangular number t[n])*s+1`. I take an input `a`, then iterate through the triangular numbers until a-1 is not greater than `3*t[n]`. If `s` is an integer, we clear the screen and plot the drawing. After plotting, we wait for the user to press a key (the screen will be cleared again for the next drawing if there is one.) To check if `s` s an integer, we store it in an integer variable `s%` (integer variables are identified by the `%` suffix) and compare the two. In this program I use casting to integer variables several times as a means of converting reals to integers.

The polygon is plotted wedge by wedge. The radial vectors for the first two points `(u,v)` and `(x,y)` are calculated. All the code for this must be on the same line as the IF statement. Unfortunately the resolution of the plotting of this BBC basic emulator is only to the nearest multiple of 2, so in order to avoid problems we ensure that the vector parameters are multiples of 2 (by storing the values of the trig calculations in an integer variable `q%` then multiplying by 2. (the vectors themselves are real variables, to save characters.) There is also a variable `q` which serves only to accept return values of functions (required for syntax reasons.)

In order to avoid trying to do too much in the first `IF` statement, it is natural to put the plotting operation in a function, and having done that it may as well be recursive. The function plots the wedge as a binary tree with overlapping branches. This is short, but highly inefficent (exponential time in number of rings.) With the largest sizes some points are plotted literally millions of times. The worst case is 976, where there are 25 triangular rings, which is expected to take several hours to run :-) This only happens for a very small number of inputs and is fixable for a few extra characters (currently 15) but I don't see speed as essential to the rules.

**Ungolfed Code**

```
  c=400                        :REM Approx half the height of the screen area
  INPUTa
  n=1                          :REM Number of rings
  t=0                          :REM t=triangular number n
  REPEAT
    t+=n                       :REM Update t to the next triangular number
    s=(a-1)/t                  :REM Number of sides of polygon
    r%=c/n/2                   :REM Choose a good length for (half)the radius of the first ring.
    CLS:MOVEc,c                :REM Clear screen and move graphics cursor to middle
    s%=s                       :REM Store the number of sides in an integer variable
    IFs%=s                     :REM If real variable and integer variable are equal (all the following indent MUST be on the same line as the IF)
      u=r%*2:v=0:              :REM initialise (u,v) to 360 deg.
      FORp=1TOs%:              :REM Loop through the sides.
        q%=r%*COS(p/s%*2*PI):  :REM Calculate x/2, assign to integer variable
        x=q%*2:                :REM assign to x, ensuring x is a multiple of 2.
        q%=r%*SIN(p/s%*2*PI):  :REM ditto y.
        y=q%*2:                :REM ditto y.
        q=FNt(n):              :REM Plot the wedge from n down to 0 (the first row is the centre dot, which will be overdrawn s times)
        u=x:v=y:               :REM Reinitialise u and v with the last values of x and y
      NEXT:                    :REM in order to plot the next wedge.
      q=GET                    :REM Allow user to view output, wait for keypress.
    n+=1                       :REM increment n ready to try the next triangular number
  UNTILs<=3                    :REM If number of sides already <=3
  END                          :REM exit program.

  DEFFNt(d)                    :REM BBC basic puts the nut & bolt functions at the end!
    PLOT153,8,0:MOVEBY-8,0     :REM Draw a filled circle radius 8 centred at the current graphics cursor position. After drawing, return cursor to centre of circle.
    IFd                        :REM if this is not the final iteration (all the following indent MUST be on the same line as the IF)
      MOVEBY u,v:              :REM move to the point where the first circle of the next ring is to be drawn
      q=FNt(d-1):              :REM draw the circle and the rest of the branch
      DRAWBY x-u,y-v:          :REM draw the concentric line to the second circle of the next ring
      q=FNt(d-1):              :REM draw the circle and the rest of the branch
      MOVEBY-x,-y              :REM return cursor to where it was before calling the function
  =0                           :REM supply a return value to exit the function.

```

**Output, 31 dots**

I know the dots are small, but that comes in handy for the larger numbers.
> 1 votes

# Answer
# Python 2.7.6, 272 bytes

I'm still learning python, so I'm sure there is more room to golf this. This is more of a challenge to myself than a competitive entry:

```
from turtle import*
from math import*
def f(n):pu();fd(20*n);pd()
P=input()
for n in range(2,P):
 a=2*P-2;b=n*n-n;m=a/b
 if a%b==0:
    f(n);dot(5)
    for r in range(1,n):
     f(1);rt(90-180/m)
     for s in [1]*m:
        rt(360/m)
        for t in [1]*r:dot(5);fd(40*sin(pi/m))
     lt(90-180/m)

```

Add `exitonclick()` to the end if you want the display to stay open after rendering.

Output for input of 31:
> 1 votes

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


# Question
Title: Decompose words into other words (e.g., “afterglow” = “aft” + “erg” + “low”)
Here's one for all you wordsmiths out there! Write a program or function which takes a list of words and produces a list of all possible concatenative decompositions for each word. For example:

***(Note: This is only a small sampling for illustrative purposes. Actual output is far more voluminous.)***

```
afterglow = after + glow
afterglow = aft + erg + low
alienation = a + lie + nation
alienation = a + lien + at + i + on
alienation = a + lien + at + ion
alienation = alien + at + i + on
alienation = alien + at + ion
archer = arc + her
assassinate = ass + as + sin + ate
assassinate = ass + ass + in + ate
assassinate = assassin + ate
backpedalled = back + pedal + led
backpedalled = back + pedalled
backpedalled = backpedal + led
goatskin = go + at + skin
goatskin = goat + skin
goatskin = goats + kin
hospitable = ho + spit + able
temporally = tempo + rally
windowed = win + do + wed
windowed = wind + owed
weatherproof = we + at + her + pro + of
yeasty = ye + a + sty

```

Ok, you get the idea. :-)

## Rules

* Use any programming language of your choosing. Shortest code by character count *for each language* wins. This means there is one winner for each language used. The overall winner will be simply the shortest code of all submitted.
* The input list can be a text file, standard input, or any list structure your language provides (list, array, dictionary, set, etc.). The words can be English or any other natural language. (If the list is English words, you'll want to ignore or pre-filter-out single-letter items except for "a" and "i". Similarly, for other languages, you'll want to ignore nonsensical items if they appear in the file.)
* The output list can be a text file, standard output, or any list structure your language uses.
* You can use any input dictionary you like, but you'll probably want to use one that provides sensible words rather than one that provides too many obscure, arcane, or obnubilated words. This the file I used: *The Corncob list of more than 58000 English words*

## Questions

This challenge is primarily about writing the *code* to accomplish the task, but it's also fun to comb through the results...

1. What subwords occur most commonly?
2. What word can be decomposed into the greatest number of subwords?
3. What word can be decomposed the most different ways?
4. What words are composed of the largest subwords?
5. What decompositions did you find that were the most amusing?

# Answer
# Python 186

```
a=open(raw_input()).read().split()
def W(r):
 if r:
    for i in range(1,len(r)+1):
     if r[:i]in a:
        for w in W(r[i:]):yield[r[:i]]+w
 else:yield[]
while 1:
 for f in W(raw_input()):print f

```

Not particularly efficient but actually not terrible slow. It just naively (I suppose it's possible, though I think unlikely that python does some clever optimizations) checks that sub-words are in the corncob dictionary and recursively finds as many words as it can. Of course this dictionary is pretty extensive and you could try one which doesn't include various abbreviations and acronyms (leading to things like `bedridden: be dr id den`). Also the linked dictionary did not seem to have 'A' or 'I' listed as words so I manually added them in.

Edit:

Now the first input is the filename of the dictionary to use, and every additional one is a word.
> 3 votes

# Answer
# Cobra - 160

```
sig Z(x,y)
def f(b)
    c as Z=do(x,y)
        if x.length<1,print y
        for z in File.readLines('t'),if z==x[:e=z.length].toLower,c(x[e:],y+' '+z)
    for t in b,c(t,'[t]:')

```

This is a function (sort-of two functions) that takes a `List<of String>`* and prints the strings containing the possible sub-word arrangements for each string in the argument list.

* the type is actually `List<of dynamic?>`, but providing anything other than `List<of String>` will probably break it.
> 2 votes

# Answer
# Scala, 132 129

Edit: slightly shorter as a loop reading from stdin than a function

```
while(true)print(readLine.:\(Seq(List(""))){(c,l)=>l.flatMap{m=>Seq(c+""::m,c+m.head::m.tail)}}filter(_.forall(args contains _)))

```

run as

```
scala decompose.scala aft after erg glow low

```

(or use a longer word list :) )

Original:

```
def f(s:Seq[String])=s.map{_.:\(Seq(List(""))){(c,l)=>l.flatMap{m=>Seq(c+""::m,c+m.head::m.tail)}}filter(_.forall(args contains _))}

```

Function from Seq\[String\] to Seq\[Seq\[List\[String\]\]\]. Takes dictionary as the command line arguments.

Ungolfed:

```
def decompose(wordList: Seq[String]) =
  wordList.map{ word =>                              // for each word
    word.foldRight(Seq(List(""))){ (char, accum) =>  // for each character
      accum.flatMap{list =>
        Seq(char+""::list,char+list.head::list.tail) // add it as both a new list and
      }                                              // the to start of the first list
    }.filter(_.forall(args contains _))              // filter out lists w/ invalid words
  }

```

Approach is to generate all the possible lists of substrings and filter out those that contain a string not in the dictionary. Note that some of the substrings generated contain an extra empty string, I assume the empty string will not be in the dictionary (there's no way to pass it in on the command line anyways).
> 2 votes

---
Tags: code-golf, string, natural-language
---


title: Implement map()...with bugs

text:
# Question
Title: Implement map()...with bugs
**EDIT:** The behavior may be inconsistent. Also, associative arrays are permitted.

Make a function that iterates through an indexed array, mapping a function of a single argument to each member of the array. The catch: introduce a hidden bug where the function is not correctly applied to at least one index of the input array.

Example:

```
map(lambda a: a+1, [1, 2, 3, 4])
# Should be [2, 3, 4, 5]
# Could be: [2, 3, 5, 4] or [2, 4, 6, 5] or anything else

```

Rules:

1. Use either a static method with two arguments, function and array, or a non-static method with one, an array or function (`this` being of the other type). Examples:

* `std::vector<F> map(F (*fn)(E), std::vector<E> array);` (C++)
    * `def map(fn, array): ...` (Python)
    * `Array.prototype.map = function (fn) {...};` (JavaScript)
2. If your language features a method already to do this, re-implement it.
3. The ignored entry may be of any type desired.
4. Assume the arguments to actually be correct (if the language has dynamic type checking).
5. It may or may not be in place.
6. Hide your malice.
7. Highest vote count wins.

Here's an example of a correct, bug-free implementation in JavaScript (excluding type checking):

```
Array.prototype.map = function (fn) {
  var i   = this.length,
  ret = new Array(i);
  while (i--) { // decrements to 0 after evaluation
    ret[i] = fn(this[i]);
  }
  return ret;
};

```

# Answer
## Perl

```
sub mymap (&@) {
  my $fn = shift;
  my @ret;
  while (my $val = shift) {
    local $_ = $_[0]; # map calling convention is element in $_
    push @ret, $fn->();
  }
  return @ret;
}

```

Looks plausible for at least a moment, until you have the sense to go "why isn't he using `$val`?"
> 8 votes

# Answer
## Javascript

Let's use Object.defineProperty to define a lazy map function that only evaluates its result the first time it is requested.

```
function map(arr, f) {
    var result = {};
    for (var i = 0; i < arr.length; i++) {
        var value = arr[i], evaluated;
        Object.defineProperty(result, i, {
            get: function () {
                if (!evaluated) {
                    evaluated = f(value);
                }
                return evaluated;
            }
        });
    }
    result.length = arr.length;
    return result;
}

// Used like this
var x = map([1, 2, 3], function (x) { return x + 1; });

```

> The code has a pretty common error that often occurs when defining functions inside loops - since JS does not introduce a new context in a for loop, the variables `i`, `value`, and `evaluated` are the same for all the 'get' functions. This means that all elements in the result will be the same, namely `f(arr[arr.length - 1])`. Not very sneaky, but an interesting quirk of JS.

Addition:

> Sneaky bug #2: if `f(arr[arr.length - 1])` returns falsey, accessing an element in the array will apply `f` again! So sneaky I didn't realize it myself when writing up the sample.
> 4 votes

# Answer
I thought I'd try to take a stab at my own challenge here...please pardon my long spoilers.

# JavaScript

It's a bit simplified compared to the spec (it requires type checking and `this` isn't necessarily an Array instance)

```
Array.prototype.map = function (fn) {
  var ret = [];
  for (var i in this) {
    ret.push(fn(i));
  }
  return ret;
};

```

Sounds great! Where's the problem?

> It is widely known in the JavaScript world that the for-in loop returns the indices of arrays, not the entries. The confusion still brings headaches, even to some more seasoned developers. Also, in past versions of IE, for-in loops also iterated over additional properties, such as Array.prototype.toString. The proper way to fix this bug would be to use `this[i]` instead of `i` and append \`if (this.hasOwnProperty(i)), so that it looks like this:
>
> ```
>
>  Array.prototype.map = function(fn) {
>    var ret = [];
>    for (var i in this) {
>      if (this.hasOwnProperty(i)) {
>        ret.push(fn(this[i]));
>      }
>    }
>    return ret;
>  };
>
> ```
>
> This looks correct now?

> Try again. If there is any enumerable property ever assigned to the array, this loop will also see it and apply the function to it. That is relatively easy to do, considering the two standard means of setting properties default to being enumerable (which you can't change this way, either):
>
> ```
>
>  object.prop = val;
>  object['prop'] = val;
>
> ```
>
> Keep in mind that you can assign a property to anything in JavaScript. If you were to try that "correct" implementation on a standards-comforming browser you would get this:
>
> ```
>
>  var old = [1, 2, 3, 4, 5];
>  old.foo = 'Hi!';
>  var new = old.map(function (a) {return a + 1;});
>  console.log('Old length: ' + old.length);
>  console.log('New length: ' + new.length);
>  console.log('Old contents: ' + old); // implicit toString
>  console.log('New contents: ' + new);
>
> ```
>
> ```
>  Output:
>  Old length: 5
>  New length: 6
>  Old contents: 1,2,3,4,5
>  New contents: 2,3,4,5,6,Hi!1
>
> ```
>
> Also, there is no guarantee that the for-in loop iterates in order. The `push()` method implies the need to be in order. This could mean that the last line could very well print out the contents as `2,6,4,3,Hi!1,5`.
>
> The only way to define a non-enumerable property is through `Object.defineProperty()`, `Object.defineProperties()`, `Object.create()`, and the like.
>
> Moral of the story, never use for-in loops to iterate through arrays. It's a code smell, and a terrible one at that. It leads to misunderstanding and bugs. It was clearly designed for associative arrays, not indexed ones. This should prove it. Always use the more standard for loop. Not only is it quicker, it is harder to screw up with. The for loop should have been:
>
> ```
>
>  for (var i = this.length - 1; i > 0; i--) {
>    ret[i] = this[i];
>  }
>
> ```
>
> Ironically, this *could* be done out of order.
> 4 votes

# Answer
Here's a nice broken recursive lisp function:

```
(defun xmap (l f) (when (cdr l) (cons (funcall f (car l)) (xmap (cdr l) f))))

```

> `(cdr l)` will be `NIL` when `l` has one element, so the base case is a single-element list (in which the return value is nothing). Therefore, the output list is mapped from every element of the input list, except the last one.

This solution has the delightful property of being one letter different from a working function. Happy debugging with 3AM tired eyeballs!
> 3 votes

# Answer
# C-sharp

So since this function will ship with a large library (really!), we'll have to keep it as generic as possible - it even works for non-zero based arrays (first entry)!

```
public U[] Map<T, U>(T[] inArray, Func<T, U> fn)
{
    U[] outArray = new U[inArray.Length];

    for (int i = inArray.GetLowerBound(0); i < inArray.GetUpperBound(0); i++)
        outArray[i] = fn(inArray[i]);

    return outArray;
}

```

> So obviously the '\<' in the for-loop should be '\<='. An array with 2 elements has an upperbound of 1. The idea behind this trick is that everyone is used to writing 'i = 0; i \< a.len', and will hopefully miss this detail at the first glance. The last entry in the outArray will remain zero.
> 3 votes

# Answer
# C++

Let's have fun with some meta programming.

```
template <class ...Args>
struct Helper;

// base case for Helper
template <class F, class T>
struct Helper<F, T, std::tuple<>> {
    using type = std::tuple<T>;
};

template <class F, class T, class ...Args>
struct Helper<F, T, std::tuple<Args...>> {
    using t1 = typename F::template apply<T>;
    using type = std::tuple<t1, Args...>;
};

template <class F, class ...Args>
struct Map;

// base case for Map
template <class F>
struct Map<F, std::tuple<>> {
    using type = std::tuple<>;
};

template <class F, class T, class ...Args>
struct Map<F, std::tuple<T, Args...>> {
    using type = typename Helper<F, T, typename Map<F, typename std::tuple<Args...>>::type>::type;
};

```

Usage:

```
struct Func {
    template <class T>
    using apply = typename std::add_rvalue_reference<T>::type;
};

Map<Func, std::tuple<int, double , int const>>::type t;
// t suppose to have type std::tuple<int&&, double&&, int const&&>
// but it is std::tuple<int&&, double&&, int const>

```

The `Map` struct is a meta function that can apply another meta function to the types of a `tuple`, except the last member...

in Coliru

> While the base case for `Map` is required to handle empty tuple, the base case for `Helper` isn't really helpful. Delete it will make everything working again.
> 1 votes

# Answer
# PowerShell

I spent two hours trying to think of ways to be tricky with PowerShell, so I hope this isn't too easy to see through. Shouldn't be too hard to figure out what I did here.

```
function Map-Array($inArray, $functionName){
$outArray = $inArray.Clone()
$inArray.GetLowerBound(0)..($inArray.GetUpperBound($inArray.Rank-1)-1)|%{$outArray[$_-1] = & $functionName $([char]$inArray[$_-1])}
$outArray
}
function Black-Box($in){[char](([int]$in)-32)}
$x=@('a','b','c','d','e','f')

$y = Map-Array -inArray $x -functionName 'Black-Box'

```

Black-Box capitalizes all letters in the char array $x, anything else it just rolls back 32 spots on the ASCII table.

However...

```
-join $y
ABCDeF

```

> Went a little overboard with my array index checking heh. Mainly because I like the fact that an index of -1 automatically points to the last element in the array in Powershell.
> 1 votes

# Answer
**JS**

<sub>(after a little editing, because first was second and second was first but now first is more... interesting)</sub>

Let me borrow the OP's code, however due to our company's naming policy we need to change the name:

```
Array.prototype.array_map = function (fn) {
  var i   = this.length,
  ret = new Array(i);
  while (i--) { // decrements to 0 after evaluation
    ret[i] = fn(this[i]);
  }
  return ret;
};

var a = [1,2,3].array_map(function(x){ return x+1 });
console.log(a);

```

`[2, 3, 4, array_map: function]`

What's this rubbish?

> The problem lies with definition of properties on objects. Array is an object in JS (or should I say Object). While `map` property is defined (or undefined if your browser is very old), JS has no problems with overwriting it and while the value of it will change (from one function to the other) the properties of this property won't (`map` isn't enumerable). Creating another method on `Array.prototype` by default defines this property as enumerable and as such is "accessible" (or - displays) like any other value of the array. Adding call to defineProperty solves this problem:
>
> ```
> var a = [1,2,3].array_map(function(x){ return x+1 }); console.log(a);
> [2, 3, 4, array_map: function]
> ```
>
> ```
> Object.defineProperty(Array.prototype, "array_map", {enumerable : false});
> var b = [1,2,3].array_map(function(x){ return x+1 }); console.log(b);
> [2, 3, 4]
> ```

---

I always felt that there should be `map` on objects (associative arrays for you non-JS folks). As there's no such method in JS this code golf gave me the opportunity to write one.

First, let's define method length, as there's no such method in JS on objects as well (sheesh, JS, c'mon):

`Object.prototype.length = function() {
 var size = 0;
 for (var key in this)
 size++;
 return size;
}`

Now, let's do this!

```
Object.prototype.map = function (f) {
    var r=this;
    for (var i=0; i<this.length(); i++)
        if (this[i])
            r[i] = f(this[i]);
    return r;
}

```

Seriously, I don't know why JS didn't have it before. Now, let's test it!

```
var a = {O: 1, 1: 2, 2: 3};
console.log(a, 1);
console.log(a.map(function(x){ return x+1 }), 2);

Object {1: 2, 2: 3, O: 1, length: function, map: function} 1
Object {1: 3, 2: 4, O: 1, length: function, map: function} 2

```

Perfect!

> I hope this didn't give too much headache to any of you JS developers out there. This code is riddled with problems - creating methods on Object (big no no), implementation of length (object doesn't actually have length, as methods on given object are part of the object - you can see that in the output itself; you can count the property indexes but this is not the way to do it), but the offending problem is actually a malice on my part - actually the O in the a objects isn't 0. While we're creating r as a copy of object, by iterating through it via for loop we're assigning values to all numeric elements, but r\[0\] isn't there.
> 1 votes

# Answer
## Clojure

A simple, lazily evaluating map (basically a simplified version of Clojure's map).

```
(defn map' [f coll] (if (next coll) (lazy-seq (cons (f (first coll)) (map' f (rest coll))))))

(map' #(* % %) [0 1 2 3 4 5])
=> (0 1 4 9 16)

```

> You would probably want to check if the collection is empty, without dropping one element from it. `(next coll)` returns `nil` if the collection has one element in it. Correct behaviour could be gained by using `(seq coll)`.
> 0 votes

# Answer
# PHP

```
function map($arr, $func){
    foreach($arr as &$x)
        $x = $func($x);

    $result = array();
    foreach($arr as $x)
        $result[] = $x;
    return $result;
}

```

> This one is obvious to those who know PHP. `$x` is still a reference to the last item after the first loop.
> 0 votes

# Answer
## Python

Um, since the question says "at least one":

```
ma = lambda m:[1]*len(m)

```

---

Slightly foolproofed:

```
def ma(p, f):
    return [0] + ma(p[1:],f) if m[0]==1 else [1] * len(m)

```

---

I know, I know, bring on the downvotes. Here's another:

```
ma = lambda m,f:[f(x) for x in range(len(p))]

```
> 0 votes

---
Tags: popularity-contest, underhanded
---


title: Plug it back in tonight or this weekend

text:
# Question
Title: Plug it back in tonight or this weekend
*This is my first code golf so please let me know if it's too broad or if I'm missing any information for a good puzzle!*

# Challenge

In Ontario and possibly other areas of the world, electricity is billed using Time-Of-Use (TOU) pricing, which varies the cost per kilowatt-hour according to when you use power.

Given a date and time, I want to know whether I'm in an on-peak (red), mid-peak (yellow), or off-peak (green) time period.

# Input

Assume that input is provided in an acceptable timezone-less ISO 8601 date-time format with the minimum precision of hours: `YYYY-MM-DDThh[:mm[:ss]]` (the T is literal).

### Examples

* 2014-09-01T14
* 2014-09-01T17:30
* 2014-09-01T17:30:02

# Output

The output should be a string `On`, `Mid`, or `Off`.

# Rules

* Shortest code wins
* For the purposes of this challenge, ignore statutory holidays
* Assume the information found in this post. The actual rules of time-of-use pricing might change in the future by the Ontario Ministry of Energy.

# Information

## Summer weekdays (May 1st to October 31st)

* Off-peak: 19h00 - 07h00
* Mid-peak: 07h00 - 11h00 and 17h00 - 19h00
* On-peak: 11h00 - 17h00

## Winter weekdays (November 1st to April 30th)

* Off-peak: 19h00 - 07h00
* Mid-peak: 11h00 - 17h00
* On-peak: 07h00 - 11h00 and 17h00 - 19h00

## Weekends

* Off-peak: All day

# Answer
## Ruby - ~~147 144 143 141 137~~ 135

```
x=->s{y,m,d,h=s.scan(/\d+/).map &:to_i
g=Time.new(y,m,d).wday%6<1?0:[0..11,4..9].count{|r|r===h-7}
%W{Off Mid On}[m<5||m>10?(3-g)%3:g]}

```

This represents a function which takes a string as a parameter and returns a string.

Here's an online demo with some test cases: **http://ideone.com/wyIydw**
> 3 votes

# Answer
# Python 2 - 164

```
from datetime import*
d,t=input().split('T')
y,m,d=map(int,d.split('-'))
t=int(t[:2])
print'OMOfinfd'[(1+((10<t<17)==(4<m<11)))*(date(y,m,d).weekday()<5<6<t<19)::3]

```

---

If needed, below is a explanation of the logic in the final line:

The final line prints a slice of `'OMOfinfd'` depending on the evaluation of its conditionals.

* First, evaluate the operation `1+((10<t<17)==(4<m<11))`.

If the XNOR between the conditions `10<t<17` and `4<m<11` is `False`, this will evaluate to `1+False => 1+0 => 1`. Otherwise, the operation will evaluate to `1+True => 1+1 => 2`.
* Finally, multiply that result of the above operation by whether the day is a weekday and whether the time is between 6am-7pm.

If this is `False`, either the day is a weekend or the time is between 7pm-6am, and the result will be `(1|2)*0 => 0`. Otherwise the result will be `(1|2)*1 => 1|2`.

A result of `0` will print `Off`, `1` will print `Mid`, and `2` will print `On`.
> 8 votes

# Answer
## Ruby - 135

Abuses the Time module. Input by command line argument.

```
d=Time.new(*$*[0].scan(/\d+/)[0..3])
o,m,f=%w{On Mid Off}
o,m=m,o if (d.mon-5)%10<6
p d.wday%6<1||(12>h=(d.hour+5)%24)?f:15<h&&h<22?m:o

```

**Edit:** Thanks w0lf for Time which helped shorten and solve a bug.
> 5 votes

# Answer
## C# - ~~240~~ 220 chars

```
string x(string s){var d=DateTime.Parse((s+":00:00").Substring(0,19));int h=d.Hour,i=(int)d.DayOfWeek,x=d.Month;string o="off",m="mid",f="on";return i==6|i==0?o:x>=5&x<11?h>18|h<7?o:h>10&h<17?f:m:h>18|h<7?o:h>10&h<17?m:f;}

```

Nothing special. Straight forward coding.

Thanks to w0lf :)
> 5 votes

# Answer
## Groovy - 621 534 524 491 chars

Some further golfing to do, but pretty simple when leveraging Joda-Time

```
@Grab(group='joda-time',module='joda-time',version='2.3')
f={p,a->org.joda.time.format.DateTimeFormat.forPattern(p).parseDateTime a}
g={p,a->def x=null;try{x=f p,a}catch(Exception e){}}
a=args[0]
d=["",":mm",":mm:ss"].collect{g "yyyy-MM-dd'T'HH$it",a}.find{it}
r="Off"
m="Mid"
j={d,a,b->d.hourOfDay>a&&d.hourOfDay<b}
k={j(it,6,11)||(j(it,16,19))}
if(d.dayOfWeek<6){x=d.monthOfYear;if(x>4&&x<12){if(j(d,10,17))r="On";if(k(d))r=m}else if(x<5||x>10){if(j(d,10,17))r=m;if(k(d))r="On"}}
println r

```

sample runs:

```
bash-3.2$ ./run.peak.sh
groovy Peak.groovy 2014-08-26T19
Off
groovy Peak.groovy 2014-08-26T07:00
Mid
groovy Peak.groovy 2014-08-26T18:00:00
Mid
groovy Peak.groovy 2014-08-26T12:30:30
On
groovy Peak.groovy 2014-11-01T00
Off
groovy Peak.groovy 2014-02-05T11:11:11
Mid
groovy Peak.groovy 2014-01-05T08:08
Off
groovy Peak.groovy 2014-12-18T18:59:59
On
groovy Peak.groovy 2014-08-31T14
Off

```

Ungolfed:

```
@Grab(group='joda-time',module='joda-time',version='2.3')

f = { p,a -> org.joda.time.format.DateTimeFormat.forPattern(p).parseDateTime a}
g = { p,a -> def x=null; try{x=f p,a} catch(Exception e) {} }
a=args[0]

d = ["",":mm",":mm:ss"].collect{g "yyyy-MM-dd'T'HH$it",a}.find{it}
r = "Off"
m = "Mid"

j = {d,a,b -> d.hourOfDay > a && d.hourOfDay < b}
k = { j(it,6,11) || (j(it,16,19)) }

if (d.dayOfWeek<6) {
    x = d.monthOfYear;
    if ( x>4 && x<12 ) {
        if (j(d,10,17)) r="On";
        if (k(d)) r=m
    } else if (x<5||x>10) {
        if (j(d,10,17)) r=m;
        if (k(d)) r="On"
    }
}
println r

```
> 3 votes

# Answer
## R, ~~243~~ 204 characters

```
b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,2,3),f(w,3,2)))])

```

Indented and commented:

```
b=strptime(scan(,""),"%Y-%m-%dT%H") #Takes stdin and converts into POSIXct
i=function(x)as.integer(format(b,x)) #Format the POSIXct and convert it to integer
h=i("%H")      #Format to hours
d=i("%m%d")    #Format to Month/Day
w=d>1100|d<430 #True if winter time, false if summer
f=ifelse
cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19, #If weekend or night
                          1,                       #Case 1
                          f(h>11&h<17,            #Else if mid-day
                             f(w,3,2),             #Case 2 in winter, case 3 in summer
                             f(w,2,3)))])          #else vice versa

```

Examples:

```
> b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,3,2),f(w,2,3)))])
1: 2014-08-26T15
2:
Read 1 item
On
> b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,3,2),f(w,2,3)))])
1: 2014-12-10T15
2:
Read 1 item
Mid
> b=strptime(scan(,""),"%Y-%m-%dT%H");i=function(x)as.integer(format(b,x));h=i("%H");d=i("%m%d");w=d>1100|d<430;f=ifelse;cat(c("Off","Mid","On")[f(i("%u")%in%5:6|h<7|h>19,1,f(h>11&h<17,f(w,3,2),f(w,2,3)))])
1: 2014-08-26T23
2:
Read 1 item
Off

```
> 2 votes

# Answer
## Bash, 286

this is a simple bash answer using the date program

```
d(){ date -d $1 +%$2; };D=$(echo $1|sed 's/\(T..\)$/\1:00/');H=$(d $D H);M=$(d $D m);if [ $(d $D u) -gt 5 ]||[ $H -lt 7 ]||[ $H -gt 18 ];then echo Off;exit;fi;if [ $M -gt 4 ]&&[ $M -lt 11 ];then I=On;O=Mid;else I=Mid;O=On;fi;if [ $H -gt 10 ]&&[ $H -lt 17 ];then echo $I;else echo $O;fi

```
> 1 votes

# Answer
Here goes another one!

# JavaScript, ~~175~~ 171

```
function f(x){d=new Date(x.slice(0,10));t=x.slice(11,13),m=(x.slice(5,7)+1)%12;return(t<8||t>18||!(d.getUTCDay()%6)?'off':((t<11||t>17)?(m<5?'on':'mid'):(m<5?'mid':'on'))}

```

Unminified:

```
function f(x) {
  d = new Date(x.slice(0, 10));
  t = x.slice(11, 13), m = (x.slice(5, 7) + 1) % 12;
  return (t < 8 || t > 18 || !(d.getUTCDay() % 6) ? 'off' : ((t < 11 || t > 17) ? (m < 5 ? 'on' : 'mid') : (m < 5 ? 'mid' : 'on'))
}

```

Only works on interpreters where an ISO8601 date string can be passed into the `Date` constructor.

# CoffeeScript, ~~192~~ 189

Surprisingly, it's longer in CoffeeScript because there's no ternary operator in that language (which as you can see from my JavaScript, I heavily relied on).

```
f=(x)->d=new Date(x.slice(0,10));t=x.slice(11,13);m=(x.slice(5,7)+1)%12;return'off'if(t<8||t>18||!(d.getUTCDay()%6));if(t<11||t>17)then(if m<5then'on'else'mid')else(if m<5then'mid'else'on')

```
> 1 votes

# Answer
# Python 3 - 352 chars

```
import datetime as dt
t=input()
i=int
p=print
a='on'
b='mid'
c='off'
m=i(t[5:7])
h=i(t[11:13])
d=dt.date(i(t[0:4]),m,i(t[8:10])).weekday()
if 5==d or 6==d:p(c)
elif h>=19 and h<7:p(c)
elif m<=10 and m>=4:
 if h>=7 and h<11:p(b)
 if h>=11 and h<17:p(a)
 if h>=17 and h<19:p(b)
else:
 if h>=7 and h<11:p(a)
 if h>=11 and h<17:p(b)
 if h>=17 and h<19:p(a)

```
> 0 votes

# Answer
## Java - ~~426~~ 309 / 301? (see comments)

```
String z(String a){
    DateParser b=new DateParser(a);
    boolean c=b.parseEcmaDate();
    Integer[]d=b.getDateFields();
    GregorianCalendar e=new GregorianCalendar(d[0],d[1]-(c?0:1),d[2]);
    e.setTimeZone(new SimpleTimeZone(0,""));
    return(124>>e.get(7)&1)>0&d[3]>6&d[3]<19?
           d[3]>10&d[3]<17^(1008>>e.get(2)&1)>0?"Mid":"On":"Off";
}

```

Example output:

```
2014-03-02T00   Off
2014-03-02T06   Off
2014-03-02T07   Off
2014-03-02T10   Off
2014-03-02T11   Off
2014-03-02T16   Off
2014-03-02T17   Off
2014-03-02T18   Off
2014-03-02T19   Off
2014-03-02T23   Off
2014-04-02T00   Off
2014-04-02T06   Off
2014-04-02T07   On
2014-04-02T10   On
2014-04-02T11   Mid
2014-04-02T16   Mid
2014-04-02T17   On
2014-04-02T18   On
2014-04-02T19   Off
2014-04-02T23   Off
2014-05-02T00   Off
2014-05-02T06   Off
2014-05-02T07   Mid
2014-05-02T10   Mid
2014-05-02T11   On
2014-05-02T16   On
2014-05-02T17   Mid
2014-05-02T18   Mid
2014-05-02T19   Off
2014-05-02T23   Off

```

I used the same EXOR trick as the Python submission. ~~I also used a `+` as an OR function, for when it's `weekend OR night`.~~

My other big trick: bit masks.

For example, to see if a number is between 2 and 6 (Monday to Friday), first create a bit pattern where the interesting values are 1:

```
  6   2
0b1111100 = 124

```

Then, use bit shift to get the interesting bit to the LSB and extract it:

```
(124 >> day_of_week) & 1

```

Similarly, I made bit patterns for months and hours:

```
  9    4
0b1111110000 = 1008

      76          76
0b111110000000000001111111 = 16253055
0b000000011111100000000000 = 129024

```

Unfortunately, it turns out simply `x>y&x<z` is shorter in most cases, so I didn't use it in some places.

And finally, a bit of hackery (highly implementation dependent) with `jdk.nashorn.internal.parser.DateParser`: When `parseEcmaDate()` doesn't completely parse a date (like when it reads hour and hits end of string), it returns false.

* When it finishes properly, the date is stored in an `Integer[]` (auto-unboxing ftw), with the month fixed to be base-0 (like other Java classes).
* When it returns false, it aborted half-way and didn't do this fixing. It however still put whatever it parsed into the array, which is readily available. Hence the `-(c?0:1)`.
> 0 votes

# Answer
# ES6 - 146

This is in function form, uses a couple nasty hacks.

```
let y,m,d,h,c=s=>[y,m,d,h]=s.split(/[T:-]/g).map(i=>+i),new Date(y,m,d).getDay()in{0:1,6:1}||h<20||8>h?'Off':['Mid','On'][(10>h&&h>16)^(m>5||m<8)]

```

Explained:

```
// These variables are declared outside of the function scope to save
// characters.
let y, // year
    m, // month
    d, // day
    h, // hour
    c = s => // c for check, called as c(isoString)
      [y, m, d, h] = // Assign to fields
        s.split(/[T:-]/g) // Split at delimiters
         .map(i => +i), // Convert all to numbers
                        // Comma used to keep it as a single statement.
      new Date(y, m, d).getDay() // Create Date to get day of week
        in {0:1, 6:1} // Check if it is good (0 = Sunday, 6 = Saturday). It
                      // is shorter to use an object literal than to
                      // do individual checks.
      ||
      h < 20 || 8 > h ? // h is between 7 and 19 (7pm)
       'Off' : // Return 'Off'
       ['Mid','On'][ // Two other outputs
        (10 > h && h > 16) ^ // Check if it is 11-16 (5pm)
        (m > 5 || m < 8)] // Invert that if the month is in summer/fall. Note
                          // that this returns a number, either 1 or 0. This
                          // is an ugly hack using the bitwise xor operator.

```
> 0 votes

# Answer
Nothing stops me from entering my own, and there's other shorter ones here anyways, so…

# PHP 5.4+, 194

```
<?function f($x){$t=substr($x,11,2);$m=(substr($x,5,2)+1)%12;if($t<8||$t>18||(new DateTime(substr($x,0,10)))->format('N')>5)return'off';return($t<11||$t>17)?($m<5?'on':'mid'):($m<5?'mid':'on');}

```

Unminified and commented:

```
<?
function f($x) {
  $t = substr($x,11,2); // hour
  $m = (substr($x,5,2) + 1) % 12; // month shifted up by 1

  if ($t < 8 || $t > 18 || (new DateTime(substr($x,0,10)))->format('N') > 5)
    return 'off'; // evenings and weekends

  return ($t < 11 || $t > 17)
    ? ($m < 5 ? 'on' : 'mid') // morning and mid-afternoon
    : ($m < 5 ? 'mid' : 'on'); // afternoon
}

```

Also note that the `date.timezone` directive in php.ini must be set, otherwise an Exception will be thrown.
> -1 votes

---
Tags: code-golf, date
---