title: Remove specified non-numeric rows

text:
# Question
Title: Remove specified non-numeric rows
In case there's any doubt: `Nan = Non-numeric datatype` for the purposes of this challenge.

---

Write a program or function that takes a matrix / array as input, as well as a list of column indices.

The challenge is to remove the rows where all elements in the specified columns are `Nan`. It doesn't matter if other elements in the row are numeric or not. The following examples will hopefully make this more clear (it's one-indexed):

```
Input array:
    16   NaN     3    13
     5    11   NaN     8
   NaN     7   NaN    12
     4    14   -15     1

Input column index: [1 3]

Output array:
16   NaN     3    13
 5    11   NaN     8
 4    14   -15     1

----

Input array:
    16   NaN     3    13
     5    11   NaN     8
   NaN     7   NaN    12
     4    14   -15     1

Input column index: 3

Output array =
    16   NaN     3    13
     4    14   -15     1

----

Input array:
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

Input column index: 1 2 4

Output array:
 []

```

**Rules and clarifications:**

* The matrix will always be non-empty
* The numeric values will be finite, but not necessarily integers or positive values
* The column index vector can be empty (in which case no rows will be removed)
* The column index will never have values exceeding the matrix dimensions
* You can assume there won't be duplicates in the column index list
* You can choose if you want to use zero- or one-indexed values (please specify)
* You can take the input on any convenient format
    + Array as list of lists is OK. The column indices can be separate arguments
* `ans =` and similar is accepted in output
* You are free to choose what type of non-numeric datatype you want to use
    + It should be impossible to perform arithmetic operations with this datatype, or convert it to a finite number using functions such as `float(x)`.

This is code golf, so shortest code in bytes win.

# Answer
> 6 votes
# Pyth, ~~16~~ ~~19~~ ~~10~~ ~~9~~ ~~7~~ 10 Bytes

Column indices start at zero. Input is a list of lists. Uses an empty string as non-numeric value. Takes list of column indices on the first line and the Matrix with the values on the second line.

```
?Qf-QxkTEE

```

Try it online!

## Explanation

```
?Qf-QxkTEE       # Implicit: Q=column indices, E=Matrix

?Q       E       # If column list is empty no rows get removed
  f     E        # filter the given matrix by each row T
     xkT         # Get the indices of all occurences of an emtpy string (k)
   -Q            # If the indices match with the given column indices, remove the row

```

**Update:** My first solution handled an empty list of column indices wrong. Fixed it (pretty ugly) at the cost of 3 Bytes. Gonna try to do it better after work...

**Update 2:** Golfed it down to ~~10~~ ~~9~~ 7 bytes, with some help from @FryAmTheEggman an by improving the algorithm significantly.

**Update3:** Fixed a bug @ThomasKwa discovered. His proposed 7-byte solution did not handle empty column indices right, so I just catch that case with a ternary here. I don't see how I can shorten this atm.

# Answer
> 6 votes
# JavaScript (ES6), ~~48~~ 46 bytes

```
(a,l)=>a.filter(r=>l.some(c=>r[a=0,c]<1/0)||a)

```

## Explanation

Expects an array of rows as arrays, and an array of 0-indexed numbers for the columns to check. Returns an array of arrays.

Straight-forward `filter` and `some`. Checks for `NaN` by using `n < Infinity` (`true` for finite numbers, `false` for `NaN`s).

```
var solution =

(a,l)=>
  a.filter(r=>     // for each row r
    l.some(c=>     // for each column to check c
      r[a=0,       // set a to false so we know the some was executed
        c]<1/0     // if any are not NaN, do not remove the row
    )
    ||a            // default to a because if l is of length 0, some returns false but
  )                //     we must return true
```

```
<textarea id="matrix" rows="5" cols="40">16 NaN 3 13
5 11 NaN 8
NaN 7 NaN 12
4 14 -15 1</textarea><br />
<input type="text" id="columns" value="0 2" />
<button onclick="result.textContent=solution(matrix.value.split('\n').map(l=>l.split(' ').map(n=>+n)),(columns.value.match(/\d+/g)||[]).map(n=>+n)).join('\n')">Go</button>
<pre id="result"></pre>
```

# Answer
> 3 votes
## CJam, 18 bytes

```
{{1$\f=_!\se|},\;}

```

An unnamed block (function) expecting the matrix and the zero-based column indices on the stack (the matrix on top), which leaves the filtered matrix on the stack. I'm using the empty array `""` as the non-numeric value.

Test it here.

### Explanation

```
{     e# Filter the matrix rows based on the result of this block...
  1$  e#   Copy the column indices.
  \f= e#   Map them to the corresponding cell in the current row.
  _!  e#   Duplicate, logical NOT. Gives 1 for empty column list, 0 otherwise.
  \s  e#   Convert other copy to string. If the array contained only empty arrays, this
      e#   will be an empty string which is falsy. Otherwise it will contain the numbers
      e#   that were left after filtering, so it's non-empty and truthy.
  e|  e#   Logical OR.
},
\;    e# Discard the column indices.

```

# Answer
> 3 votes
# APL, 19 bytes

```
{⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]}

```

The left argument should be a list of indices (and it must be a list, not a scalar), the right argument is the matrix. APL has two datatypes, numbers and characters, so this filters out the character types.

Tests:

```
      m1 m2
   16  NaN    3  13   NaN  NaN  NaN  NaN
    5   11  NaN   8   NaN  NaN  NaN  NaN
  NaN    7  NaN  12   NaN  NaN  NaN  NaN
    4   14  ¯15   1   NaN  NaN  NaN  NaN
      1 3 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m1
16  NaN    3  13
 5   11  NaN   8
 4   14  ¯15   1
      (,3) {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m1
16  NaN    3 13
 4   14  ¯15  1
      1 2 4 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m2 ⍝ this shows nothing
      ⍴1 2 4 {⍵⌿⍨∨/⍬∘≡¨0↑¨⍵[;⍺]} m2 ⍝ the nothing is in fact a 0-by-4 matrix
0 4

```

Explanation:

* `⍵[;⍺]`: select the given columns from the matrix
* `0↑¨`: take the first `0` elements from the start of each item
* `⍬∘≡¨`: compare to the numerical empty list
* `∨/`: see in which of the rows at least one item matches
* `⍵⌿⍨`: select those rows from the matrix

# Answer
> 2 votes
# MATLAB, ~~32~~ 28 bytes

I'll answer my own question for once. The best I can do in MATLAB is 28 bytes. ~~I was hoping to avoid using both `all` and `isnan` somehow, but haven't found a way yet.~~

```
@(A,c)A(any(A(:,c)<inf,2),:)

```

Test:

```
A =
    35     1   NaN   NaN   NaN    24
     3    32   NaN    21    23    25
    31   NaN   NaN   NaN    27    20
   NaN    28   NaN    17   NaN    15
    30     5   NaN    12    14   NaN
     4    36   NaN    13    18    11

f(A,[3,5])
ans =
     3    32   NaN    21    23    25
    31   NaN   NaN   NaN    27    20
    30     5   NaN    12    14   NaN
     4    36   NaN    13    18    11

```

This is an unnamed anonymous function that takes the input matrix as the first input variable, and a list of column indices as the second.

In MATLAB, `NaN < Inf` evaluates to false. It can be assumed that all values are finite, thus checking if values are less than `inf` is equivalent to checking if they are non-numeric. `any(...,2)` checks if there are any true values along the second dimension (rows). If that's the case, then those rows will be returned.

**Old version:**

```
@(A,c)A(~all(isnan(A(:,c)),2),:)

```

`isnan(A(:,c))` returns an array with booleans for the specified columns. `~all(isnan(A(:,c)),2)` checks if all values along the second dimension (rows) are non-numeric, and negates it. This results in a boolean vector with ones in the positions we want to keep. `A(~all(isnan(A(:,c)),2),:)` uses logical indexing to extract the entire rows for `A`.

---

The following 24 byte solution would work if the values were guaranteed to be non-zero:

```
@(A,c)A(any(A(:,c),2),:)

```

# Answer
> 2 votes
## Ruby, 48 bytes

```
->a,c{a.select{|r|c.map{|i|Fixnum===r[i]}.any?}}

```

Input is 0-based indices1.

Fairly self-explanatory, actually. `select` elements from the array where `any?` of the indices `map`ped over the row are `Fixnum`s.

Sample run:

```
irb(main):010:0> (->a,c{a.select{|r|c.map{|i|Fixnum===r[i]}.any?}})[[[16,'',3,13],[5,11,'',8],['',7,'',12],[4,14,-15,1]],[0,2]]
=> [[16, "", 3, 13], [5, 11, "", 8], [4, 14, -15, 1]]

```

---

1: I *finally* spelled this word correctly on the first try! \o/

# Answer
> 2 votes
# MATL, 15 ~~16~~ bytes

```
tiZ)tn?ZN!XA~Y)

```

`NaN` is represented in the input as `N`. Indexing is 1-based. For example, in the first test case the input is

```
[16 N 3 13; 5 11 N 8; N 7 N 12; 4 14 -15 1]
[1 3]

```

**Try it online!**

### Explanation

```
t       % implicitly input matrix, M. Duplicate
i       % input vector specifying columns
Z)      % matrix N containing those columns of M
tn?     % duplicate matrix N. If non-empty ...
  ZN    %   true for NaN values in matrix N
  !     %   transpose
  XA    %   "all" within each column: gives true for rows of N that contained all NaN's
  ~     %   logical negate
  Y)    %   apply this logical index as a row index into the copy of M that was left
        %   at the bottom of the stack
        % ... implicitly end if
        % implictly display stack contents. If the input vector was empty, the stack
        % contains the original matrix M and an empty matrix. The latter produces no
        % displayed output. If the input vector was non-empty, the stack contains the
        % resulting matrix N

```

# Answer
> 2 votes
# K5, 15 bytes

This uses 0-indexed columns and K's natural list-of-lists matrix representation:

```
{x@&~&/'^x[;y]}

```

Index into the matrix (`x@`) the rows where (`&`) not all of each (`~&/'`) is null (`^`).

In action:

```
  m: (16 0N 3 13;5 11 0N 8;0N 7 0N 12;4 14 -15 1);
  f: {x@&~&/'^x[;y]};

  f[m;0 2]
(16 0N 3 13
 5 11 0N 8
 4 14 -15 1)

  f[m;2]
(16 0N 3 13
 4 14 -15 1)

```

# Answer
> 2 votes
# R, 49 bytes

```
function(m,j)m[!!rowSums(!is.nan(m[,j,drop=F])),]

```

Input is 1-based. The function takes a matrix (`m`) and a vector of column indices (`j`) which may be missing.

Two test cases:

```
> f <- function(m,j)m[!!rowSums(!is.nan(m[,j,drop=F])),]
> f(m)
      V1  V2  V3 V4
[1,]  16 NaN   3 13
[2,]   5  11 NaN  8
[3,] NaN   7 NaN 12
[4,]   4  14 -15  1

> f(m, c(1,3))
     V1  V2  V3 V4
[1,] 16 NaN   3 13
[2,]  5  11 NaN  8
[3,]  4  14 -15  1

```

# Answer
> 0 votes
# Lua, 148 Bytes

A function that takes a matrix and an array as input, and output a matrix with the corresponding rows at `nil`. As arrays are quite the same as C's arrays, nihilating is like `free()`ing it as the garbage collector isn't far away.

Arrays are 1-indexed in Lua, and I use the string `"NaN"` as a non-nomber element.

```
function f(m,l)c=1 while(c<#m)do x=0 for j=1,#l do x=x+((type(m[c][l[j]])=="number")and 0 or 1)end m[c]=(x<#l and m[c] or nil)c=c+1 end return m end

```

You can try Lua online, and copy/paste the following code sample to try this submission:

```
-- The function that does the stuff
function f(m,l)
  c=1
  while(c<#m)
  do
    x=0
    for j=1,#l
    do
      x=x+((type(m[c][l[j]])=="number")and 0 or 1)
    end
    m[c]=(x<#l and m[c] or nil)
    c=c+1
   end
   return m
end
-- A function to format matrixes into "readable" strings
function printMatrix(matrix,len)
  s="{"
  for v=1,len
  do
    if matrix[v]~=nil
    then
      s=s.."{"..table.concat(matrix[v],",").."}"..(v<len and",\n "or"")
    end
  end
  s=s.."}"
  print(s)
end

nan="NaN"
-- Datas in, indexed as matrices[testCase][row][column]
matrices={{{7,nan,5,3},{5,4,nan,4},{nan,4,nan,9},{5,7,9,8}},
{{16,nan,3,13},{5,11,nan,8},{nan,7,nan,12},{4,14,-15,1}},
{{nan,nan,nan,nan},{nan,nan,nan,nan},{nan,nan,nan,nan},{nan,nan,nan,nan}}}
indexes={{1,3},{3},{1,2,4}}

-- looping so we can test lots of things at once :)
for i=1,#matrices
do
  print("\ninput: "..table.concat(indexes[i]," "))
  printMatrix(matrices[i],4)
  print("output:")
  printMatrix(f(matrices[i],indexes[i]),4)
end

```

# Answer
> 0 votes
# Mathematica, ~~52~~ ~~51~~ ~~49~~ 46 bytes

```
Delete[#,Extract[#,{;;,#2}]~Position~{NaN..}]&

```

Input is \[matrix as list of lists,vector of columns\]

# Answer
> 0 votes
## Haskell, 39 bytes

```
m#[]=m
m#r=[l|l<-m,any(<1/0)$map(l!!)r]

```

This uses 0-based indices. Usage example (I'm using `sqrt(-1)` to create `NaN`s):

```
*Main> [[16,sqrt(-1),3,13], [5,11,sqrt(-1),8], [sqrt(-1),7,sqrt(-1),12], [4,14,-15,1]] # [0,2]
[[16.0,NaN,3.0,13.0],[5.0,11.0,NaN,8.0],[4.0,14.0,-15.0,1.0]]

```

It's just a simple filter as seen in other answers via list comprehension. The special case of an empty index list is caught separately.

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


title: It's snowing in my consoles window!

text:
# Question
Title: It's snowing in my consoles window!
You **love** watching the snow falling outside, but you know it won't be snowing much longer. You could take a video, but decide to make a snow animation because ... um ... you need to practice your animation skills!

## Snow

Snow is simply the `*` symbol here. Half of the snow moves at `1` char per frame, while the other half moves at `0.5` chars per frame. The program ends when all the snow reaches the bottom of the screen. The viewing area you will be using is `80x25`. You will have 100 snow flakes to output, half fast, and half slow.

Every frame you will dispense 4 flakes, 2 fast and 2 slow ones, at random locations at the top of the viewing area, until you have used all 100. The slow flakes can move either move the first frame, stay still the next, or stay still the first frame, and move the next, it doesn't matter. Overlapping flakes don't have anything special, just the `*` like the rest.

## Other notes

* You must make a full program, no functions here.
* Your program must run close to 10fps (+-1 frame per sec).
* You can assume the console is the same size as the viewing area.
* Each frame you must remove the previous output, either by pushing all previous output off the top of the console, or by clearing the output completely.

# Example

To make this shorter this just outputs 2 flakes per frame (1 fast, 1 slow), only 20 flakes will be outputted, and the viewing area is `20x5`.

```
Frame 1:
    *              *

Frame 2:
    * *            *
    *

Frame 3:
    *  *          *
      *            *
    *

Frame 4:
   *   *      *
    *             **
      *
    *

Frame 5:
   *            *  *
    *  *      *
                  **
      *

Frame 6:
        *      **
   *   *           *
    *         *    *
                  *

Frame 7:
     *  **
   *           **
    *  *           *
              *    *

Frame 8:
    *    **
     *  *       *
   *   *       *
    *              *

Frame 9:
 *  *         *
        ***
   * *          *
    *  *       *

Frame 10:
 *              **
    *    *    *
        * *     *
   * * *

Frame 11:
                *
 *  *            *
        **    *
   *      *     *

Frame 12:

 *              *
    *    *       *
        *     * *

Frame 13:

                *
 *  *
        **       *

Frame 14:

 *              *
    *    *

Frame 15:

                *
 *  *

Frame 16:

 *              *

Frame 17:

                *

```

If you want some snow/rain confusion and clean code, go here

# Answer
> 1 votes
# Octave, 179 bytes

```
A=' *';C=D=E=zeros(25,80);B=[i=1,1,(1:78)*0];do if i++>25 B=B&0;end
C=[B(randperm(80));C(1:24,:)];D=[B(randperm(80));D(1:24,:)];F=D;D=E;E=F;pause(.1);disp(A((F|=C|D)+1))
until(~F)

```

## Ungolfed

```
A=' *';                               % Index with 1,2 to translate to ' ','*'
                                      % A([2 1 2 2 1]) => '* ** '
C=D=E=zeros(25,80);                   % Locations of fast snowflakes,
                                      % slow ones moving on frame 1,3,5...
                                      % and slow ones moving on 2,4,6...
B=[1,1,zeros(1,78)];                  % Line with two snowflakes in it.
                                      % Will be added on top each frame.
i=1;
do
  if i++>25                           % We push 4 snowflakes per iteration.
    B=B&0;                            % Stop new input after 25 iterations.
  end
  C=[B(randperm(80));C(1:24,:)];      % Shift fast snowflakes down
                                      % and add randomly permuted input line.
  D=[B(randperm(80));D(1:24,:)];      % Shift one set of slow snowflakes down
                                      % and add randomly permuted input line.
  F=D;D=E;E=F;                        % Swap the two sets of slow snowflakes.
  pause(.1);
  disp(A((C|D|E)+1))                  % Print '*' where either of the matrices
                                      % is set, ' ' otherwise.
until(~(C|D|E))                       % Loop until the matrices are all zero

```

# Answer
> 1 votes
# JavaScript (ES6), 370 bytes

```
(S=(n,o,r="")=>{for(i=0;i<w;i++)o[i][0].pop(),o[i][0].unshift(0),Math.abs(n/4%2)&&(o[i][1].pop(),o[i][1].unshift(0));if(n>0)for(i=0;i<4;i++)o[Math.random()*w|0][i%2][0]++;for(j=0;j<h;j++){for(i=0;i<w;i++)r+=o[i][0][j]+o[i][1][j]>0?"*":" ";r+=`
`}console.log(r),n>2*-t&&setTimeout(g=>S(n-4,o),t)})(t=100,[...new Array(w=80)].map(i=>[0,0].map(i=>new Array(h=25).fill(0))))

```

Simulates with a multidimensional array, then plays it out. Could probably be golfed more.

Here's a slightly less compressed version:

```
(S=(c,v,o='')=>{
  for(i=0;i<w;i++){
    v[i][0].pop();v[i][0].unshift(0);
    if(Math.abs(c/4%2)){
      v[i][1].pop();v[i][1].unshift(0)
    }
  }
  if(c>0){for(i=0;i<4;i++){v[Math.random()*w|0][i%2][0]++}}
  for(j=0;j<h;j++){
    for(i=0;i<w;i++){
      o+=v[i][0][j]+v[i][1][j]>0?'*':' ';
    }
    o+=`
`}
  console.log(o);
  if(c>-t*2){setTimeout(g=>S(c-4,v),t)}
})(t=100,[...new Array(w=80)].map(a=>[0,0].map(b=>new Array(h=25).fill(0))))

```

# Answer
> 1 votes
# C, ~~295~~ 282 bytes

```
#include <stdlib.h>
main(){int z=25,q=100,h=50,w=30,m[q][w],s=0,a[q],b[q],x,y;for(;s<q;s++){memset(m,32,sizeof m);system("cls");a[s]=rand()%w;b[s]=rand()%w;for(x=0,y=s;y&&x<h;)m[y/2][b[x]]=m[--y][a[x++]]=42;for(x=0;x<z;x++){for(y=0;y<w;y++)putchar(m[x][y]);printf("\n");}sleep(1);}}

```

I've used Dev-C++/Windows to run.

Ungolfed version:

```
#include <stdlib.h>
main(){
    int z=25,                  // number of rows
        q=100,                 // number of flakes
        h=50,                  // number of flakes/2
        w=30,                  // number of columns
        m[q][w],               // matrix to print
        s=0,                   // counter
        a[q],                  // fast flakes
        b[q],                  // slow flakes
        x,y;                   // aux
    for(;s<q;s++){             // until the last slow flake takes the floor
        memset(m,32,sizeof m);   // clear the matrix (' '==32(ascii))
        system("cls");           // clear windows console
        a[s]=rand()%w;           // random (s*2-1)º fast flake position
        b[s]=rand()%w;           // random (s*2)º slow flake position
        for(x=0,y=s;y&&x<h;){    // set each flake position in matrix:
            m[y/2][b[x]]=94;       // slow flakes ('^'==94(ascii))
            m[--y][a[x++]]=42;     // fast flakes ('*'==42(ascii))
        }                        //
        printf("Frame %i:\n",s); // print frame number (step order)
        for(x=0;x<z;x++){        // for each row in matrix
            printf("%02i:",x);     // print the row index
            for(y=0;y<w;y++)       // for each column in row
                putchar(m[x][y]);    // print slow/fast flake or space
            printf("\n");          // for each row follows a new line
        }                        // then
        sleep(1);                // wait one second till next step
    }
}

```

Notes:

1. Maybe you'll need to maximize the console.
2. In the **ungolfed** code I did some extra prints for better visualization. Also used `^` for slow flakes.

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


title: Zigzagify a String

text:
# Question
Title: Zigzagify a String
Write a program (or function) that takes in a non-empty string of any printable ASCII characters.

Print (or return) a zigzagging chain of the characters in the string with every neighboring pair of characters linked by:

* `/` if the first character occurs before the second character in normal ASCII order. e.g.

```
  B
 /
A

```
* `\` if the first character occurs after the second character in normal ASCII order. e.g.

```
B
 \
  A

```
* `-` if the first and second characters are the same. e.g.

```
A-A

```

So the output for `Programming Puzzles & Code Golf` would be

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

```

If there is only one character in the input string the output would just be that character.

Your program should treat , `/`, `\`, and `-` just the same as all other characters.

e.g.  `-\//-- \ //-`  should produce:

```
      \
     / \
    -   /-/
   /       \
 -          ---   \   /-/
               \ / \ /   \
                          -
                           \

```

There should be no extraneous newlines in the output except for a single optional trailing newline. (Note that the empty line in the example just above holds the last space in the the string and is therefore not extraneous.) There may be trailing spaces on any lines in any arrangement.

**The shortest code in bytes wins.**

One more example - Input:

```
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

```

Output:

```
                          9   9       8   6   6
                         / \ / \     / \ / \ / \
            9   6       8   7   3   3   4   2   4     8       9       8-8
           / \ / \     /         \ /             \   / \     / \     /   \
      4   5   2   5   5           2               3-3   3   7   5   2     4   9       9   9-9   7
     / \ /         \ /                                   \ /     \ /       \ / \     / \ /   \ / \
3   1   1           3                                     2       0         1   7   6   3     3   5       8                             8   6
 \ /                                                                             \ /               \     / \                           / \ / \
  .                                                                               1                 1   5   2   9             9   3   7   1   4   6   8                                                   9
                                                                                \ /     \ / \           / \ / \ /         \ / \ / \                                                 /
                                                                                0       0   7   9     5   2   0           0   2   6       9-9               8   5   4             7
                                                                                \ / \   /                             \     /   \             / \ / \ / \           /
                                                                                4   4-4                               2   8     8           4   2   3   2     7   6
                                                                                \ /       \         /             \   / \ /
                                                                                0         6   8   3               1-1   0
                                                                                \ / \ /
                                                                                2   0

```

# Answer
> 8 votes
# Pyth, 69 bytes

```
aY,JhzZVtzaY,@"-\/"K-<NJ>N~JN=+ZKaY,N=+ZK;jbCmX*\ h-e=GSeMYhG-edhGhdY

```

Demonstration. Longer inputs still work, but they don't look very good in the fixed-width output box.

I start by constructing a list, in `Y`, of \[character, height\] tuples. It is `[['P', 0], ['/', -1], ['r', -2], ['\\', -1], ['o', 0], ['\\', 1], ['g', 2]]` early on in the `Programming Puzzles & Code Golf` example.

I then make strings of spaces of the appropriate length, insert the character at the appropriate location, transpose, join on newlines and print.

# Answer
> 7 votes
# Julia, 297 bytes

```
s->(l=length;d=sign(diff([i for i=s]));J=join([[string(s[i],d[i]>0?:'/':d[i]<0?:'\\':'-')for i=1:l(d)],s[end]]);D=reshape([d d]',2l(d));L=l(J);E=extrema(cumsum(d));b=2sumabs(E)+1;A=fill(" ",L,b);c=b-2E[2];for (i,v)=enumerate(J) A[i,c]="$v";i<l(D)&&(c-=D[i])end;for k=1:b println(join(A'[k,:]))end)

```

Ungolfed:

```
function f(s::String)
    # Get the direction for each slash or dash
    # +1 : /, -1 : \, 0 : -
    d = sign(diff([i for i in s]))

    # Interleave the string with the slashes as an array
    t = [string(s[i], d[i] > 0 ? '/' : d[i] < 0 ? '\\' : '-') for i = 1:length(d)]

    # Join the aforementioned array into a string
    J = join([t, s[end]])

    # Interleave D with itself to duplicate each element
    D = reshape(transpose([d d]), 2*length(d))

    # Get the length of the joined string
    L = length(J)

    # Get the maximum and minimum cumulative sum of the differences
    # This determines the upper and lower bounds for the curve
    E = extrema(cumsum(d))

    # Get the total required vertical size for the output curve
    b = 2*sumabs(E) + 1

    # Get the beginning vertical position for the curve
    c = b - 2*E[2]

    # Construct an array of spaces with dimensions corresponding
    # to the curve rotated 90 degrees clockwise
    A = fill(" ", L, b)

    # Fill the array with the curve from top to bottom
    for (i,v) = enumerate(J)
        A[i,c] = "$v"
        i < length(D) && (c -= D[i])
    end

    # Print out the transposed matrix
    for k = 1:b
        println(join(transpose(A)[k,:]))
    end
end

```

# Answer
> 5 votes
# Javascript (ES6), ~~360~~ ~~331~~ ~~316~~ 302 bytes

Here's my fourth attempt:

```
s=>{r=[],c=s[m=w=n=0];for(i in s)(i?(d=s[++i])>c?++n:c>d?--n:n:n)<m&&m--,n>w&&w++,c=d;for(i=0,n=w*2;i<(w-m)*2+1;r[i++]=[...' '.repeat(l=s.length*2-1)]);for(i=0;i<l;i++)i%2?(A=s[C=(i-1)/2])<(B=s[C+1])?r[--n,n--][i]='/':A>B?r[++n,n++][i]='\\':r[n][i]='-':r[n][i]=s[i/2];return r.map(x=>x.join``).join`
`}

```

Not as short as some of the others, but I'm satisfied with it for now.

Oh, so you want to test it? Alright, here you go:

```
z=s=>{r=[],c=s[m=w=n=0];for(i in s)(i?(d=s[++i])>c?++n:c>d?--n:n:n)<m&&m--,n>w&&w++,c=d;for(i=0,n=w*2;i<(w-m)*2+1;r[i++]=[...' '.repeat(l=s.length*2-1)]);for(i=0;i<l;i++)i%2?(A=s[C=(i-1)/2])<(B=s[C+1])?r[--n,n--][i]='/':A>B?r[++n,n++][i]='\\':r[n][i]='-':r[n][i]=s[i/2];return r.map(x=>x.join``).join('<br>')};

input=document.getElementById("input");
p=document.getElementById("a");
input.addEventListener("keydown", function(){
  setTimeout(function(){p.innerHTML = "<pre>"+z(input.value)+"</pre>";},10);
})
```

```
<form>Type or paste your text here: <input type="text" id="input"/></form>

<h3>Output:</h3>
<p id="a"></p>
```

Have fun!

### Updates:

**Update 1:** Golfed off 29 bytes with a variety of typical techniques.

**Update 2:** Golfed off 15 more bytes by building the string horizontally from the start, as opposed to building an array of the vertical strings and switching them around, which is what it did before.

**Update 3:** Saved 14 more bytes.

More golfiness coming soon!

# Answer
> 3 votes
# Python, 393 bytes

```
def z(n,h=[]):
 for j in range(len(n)):h.append(sum(cmp(ord(n[i]),ord(n[i+1]))for i in range(j)))
 h=[j-min(h)for j in h]
 for y in range(max(h)*2+2):
  s=""
  for x in range(len(n)):
   if h[x]*2==y:s+=n[x]
   else:s+=" "
   if x==len(n)-1:continue
   c=" "
   if h[x]<h[x+1]and h[x]*2==y-1:c="\\"
   if h[x]>h[x+1]and h[x]*2==y+1:c="/"
   if h[x]==h[x+1]and h[x]*2==y:c="-"
   s+=c
  print s

```

Run as: `z("Zigzag")`

# Answer
> 3 votes
# JavaScript (ES6), 202

Using template strings. Indentation spaces and newlines not counted, except the last newline inside backticks that is significant and counted.

Usual note: test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go)

```
f=z=>
  [...z].map(c=>
    (d=0,x=w+c,p&&(
      c<p?o[d=1,g='\\ ',r+=2]||o.push(v,v)
      :c>p?(d=-1,g='/ ',r?r-=2:o=[v,v,...o]):x='-'+c,
      o=o.map((o,i)=>o+(i-r?i-r+d?b:g:x),v+=b)
    ),p=c)
  ,v=w=' ',o=[z[p=r=0]],b=w+w)&&o.join`
`

Ungolfed=z=>
(
  v=' ',o=[z[0]],r=0,p='',
  [...z].map(c=>{
    if (p) {
      if (c < p) {
        if (! o[r+=2])
          o.push(v,v)
        o = o.map((o,i)=>o+(i==r ? ' '+c : i==r-1 ? '\\ ' : '  '))
      } else if (c > p) {
        if (r == 0)
          o = [v,v,...o]
        else
          r -= 2
        o = o.map((o,i)=>o+(i==r ? ' '+c : i==r+1 ? '/ ' : '  '))
      } else {
        o = o.map((o,i)=>o+(i==r ? '-'+c : '  '))
      }
      v += '  '
    }
    p = c
  }),
  o.join`\n`
)

out=x=>O.innerHTML+=x+'\n'

test = [
"Programming Puzzles & Code Golf",
"-\\//-- \\ //- ",
"3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"]

test.forEach(t=>out(t+"\n"+f(t)))
```

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

# Answer
> 2 votes
# CJam, 79 bytes

```
l__0=\+2ew::-:g_0\{+_}%);_$0=fm2f*_$W=)S*:E;]z{~\_)"/-\\"=2$@-E\@t@@E\@t}%(;zN*

```

Try it online

This builds the output column by column, and transposes the result at the end to get the output row by row. This was quite painful overall.

Explanation:

```
l__   Get input and create a couple of copies.
0=\+  Prepend copy of first letter, since the following code works only with
      at least two letters.
2ew   Make list with pairs of letters.
::-   Calculate differences between pairs...
:g    ... and the sign of the differences.
_0\   Prepare for calculating partial sums of signs by copying list and
      pushing start value 0.
{     Loop for calculating partial sums.
  +_    Add value to sum, and copy for next iteration.
}%    End of loop for partial sums. We got a list of all positions now.
);    Pop off extra copy of last value.
_$0=  Get smallest value.
fm    Subtract smallest value to get 0-based positions for letters.
2f*   Multiply them by 2, since the offsets between letters are 2.
_$W=  Get largest position.
)     Increment by 1 to get height of result.
S*    Build an empty column.
:E;   Store it in variable E.
]     We got the input string, list of relative offsets, and list of
      absolute positions now. Wrap these 3 lists...
z     ... and transpose to get triplets of [letter offset position].
{     Loop over triplets.
  ~     Unwrap triplet.
  \     Swap offset to front.
  _)    Copy and increment so that offset is in range 0-2.
  "/-\\"  List of connection characters ordered by offset.
  =     Pick out connection character for offset.
  2$@   Get position and copy of offset to top.
  -     Subtract to get position of connection character.
  E     Empty column.
  \@    Shuffle position and character back to top. Yes, this is awkward.
  t     Place connection character in empty line. Done with first column.
  @@    Shuffle letter and position to top.
  E     Empty column.
  \@    Stack shuffling again to get things in the right order.
  t     Place letter in empty line. Done with second column.
}%    End of main loop for triplets.
(;    Pop off first column, which is an extra connector.
z     Transpose the whole thing for output by row.
N*    Join with newlines.

```

# Answer
> 1 votes
## Perl 5, ~~230~~ 214

```
@A=split(//,pop);$y=$m=256;map{$c=ord$_;$d=$c<=>$p;$t=$d>0?'/':$d<0?'\\':'-';$B[$x++][$y-=$d]=$t;$B[$x++][$y-=$d]=$_;$m=$y,if$m>$y;$M=$y,if$M<$y;$p=$c}@A;for$j($m..$M){for$i(1..$x){$s.=$B[$i][$j]||$"}$s.=$/}print$s

```

### Test

```
$ perl zigzag.pl "zigge zagge hoi hoi hoi"
z
 \
  i
   \
    g-g
       \
        e   z   g-g       o       o       o
         \ / \ /   \     / \     / \     / \
              a     e   h   i   h   i   h   i
                     \ /     \ /     \ /

$

```

# Answer
> 1 votes
## Ruby, 158

Saved 6 bytes thanks to histocrat. Thanks!

```
->s,*i{i[x=n=k=(4*m=s=~/$/).times{i<<'  '*m}/2][j=0]=l=s[/./]
$'.chars{|c|i[k-=d=c<=>l][j+1]=%w{- / \\}[d]
i[k-=d][j+=2]=l=c
n,x=[x,n,k].minmax}
puts i[n..x]}

```

# Answer
> 1 votes
# K, 86

```
{-1@+((d#\:" "),'1_,/("\\-/"1+e),'x)@\:!|/d:(|/b)+-:b:1_+\,/2#'e:{(x>0)-x<0}@-':6h$x;}

```

.

```
k){-1@+((d#\:" "),'1_,/("\\-/"1+e),'x)@\:!|/d:(|/b)+-:b:1_+\,/2#'e:{(x>0)-x<0}@-':6h$x;} "Programming Puzzles & Code Golf"
                                                        o
                                                       / \
  r                         z-z               o   e   G   l
 / \                       /   \             / \ / \ /     \
P   o   r   m-m   n       u     l   s   &   C   d           f
     \ / \ /   \ / \     /       \ / \ / \ /
      g   a     i   g   P         e
                     \ /

```

Ungolfed:

```
f:{
    dir:{(x>0)-x<0}-':[*a;a:"i"$x];          //directional moves (-1, 0, 1)
    chars:1_,/("\\-/"1+dir),'x;              //array of input string combined with directional indicators
    depths:(|/b)+-:b:1_+\,/2#'dir;           //depth for each char, normalised to start at 0
    -1@+((depths#\:" "),'chars)@\:!|/depths; //Pad each character by the calculated depths, extend each string to a uniform length and transpose
    }

```

# Answer
> 0 votes
## Python with Numpy: 218 bytes

It is worth it to waste 19 bytes for importing numpy.

Golfed:

```
from numpy import*
z=zip
r=raw_input()
s=sign(diff(map(ord,r[0]+r)))
c=cumsum(s)
p=2*(max(c)-c)+1
for L in z(*[c.rjust(i).ljust(max(p))for _ in z(z(p+s,array(list('-/\\'))[s]),z(p,r))for i,c in _][1:]):print''.join(L)

```

Ungolfed:

```
from numpy import *

letters = raw_input()
#letters = 'Programming Puzzles & Code Golf'
s = sign(diff(map(ord, letters[0] + letters)))
c = cumsum(s)
lines = array(list('-/\\'))[s]

letter_heights = 2 * (max(c) - c) + 1
line_heights = letter_heights + s

columns = [symbol.rjust(height).ljust(max(letter_heights))
    for pair in zip(                    # interleave two lists of (height, symbol) pairs...
        zip(line_heights,   lines),
        zip(letter_heights, letters)
    )
    for height, symbol in pair          # ... and flatten.
][1:]                                   # leave dummy '-' out
for row in zip(*columns):
    print ''.join(row)

```

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


title: Which Ubuntu versions are supported?

text:
# Question
Title: Which Ubuntu versions are supported?
Given an input date, your entry will output the full list of supported versions of the Ubuntu Linux distro on that date.

The full list of all releases is as follows:

```
Version    Code name         Release date  Supported until

4.10       Warty Warthog     2004-10-20    2006-04-30
5.04       Hoary Hedgehog    2005-04-08    2006-10-31
5.10       Breezy Badger     2005-10-13    2007-04-13
6.06 LTS   Dapper Drake      2006-06-01    2009-07-14  2011-06-01 (Server)
6.10       Edgy Eft          2006-10-26    2008-04-25
7.04       Feisty Fawn       2007-04-19    2008-10-19
7.10       Gutsy Gibbon      2007-10-18    2009-04-18
8.04 LTS   Hardy Heron       2008-04-24    2011-05-12  2013-05-09 (Server)
8.10       Intrepid Ibex     2008-10-30    2010-04-30
9.04       Jaunty Jackalope  2009-04-23    2010-10-23
9.10       Karmic Koala      2009-10-29    2011-04-30
10.04 LTS  Lucid Lynx        2010-04-29    2013-05-09  2015-04-30 (Server)
10.10      Maverick Meerkat  2010-10-10    2012-04-10
11.04      Natty Narwhal     2011-04-28    2012-10-28
11.10      Oneiric Ocelot    2011-10-13    2013-05-09
12.04 LTS  Precise Pangolin  2012-04-26    2017-04-26
12.10      Quantal Quetzal   2012-10-18    2014-05-16
13.04      Raring Ringtail   2013-04-25    2014-01-27
13.10      Saucy Salamander  2013-10-17    2014-07-17
14.04 LTS  Trusty Tahr       2014-04-17    2019-04
14.10      Utopic Unicorn    2014-10-23    2015-07-23
15.04      Vivid Vervet      2015-04-23    2016-01
15.10      Wily Werewolf     2015-10-22    2016-07
16.04 LTS  Xenial Xerus      2016-04-21    2021-04

```

### Rules

* For each supported version, the exact version string will be output, e.g. `4.10`
* For LTS (long-term support) versions, `LTS` will be appended to the version
* The three oldest LTS versions come in two flavours - desktop and server. If both of these LTS versions are supported on the given date, the output will simply be the version string as above. However if only the server version is supported, then you must append `-server` to the end of the version string
* At the time of writing, 4 of the recent versions only have YYYY-MM in their supported-until dates. You must treat these dates as if they are the last day of the given month. e.g. 2019-04 must be treated as 2019-04-30
* There will be no output for dates outside of the full date range captured in the table
* Input date formats are flexible, but must contain some enumeration of Year, Month and Day. Number of days or seconds (or other units) from an epoch are not valid input formats.
* Output lists may be given in whatever format is convenient for your language
* You may use datetime functions from your language
* You may assume all inputs are valid

### Examples:

```
Input:        Output:

2000-01-01
2004-10-20    4.10
2005-05-05    4.10, 5.04
2006-06-06    5.04, 5.10, 6.06LTS
2010-10-10    6.06LTS-server, 8.04LTS, 9.04, 9.10, 10.04LTS, 10.10
2021-04-30    16.04LTS
2021-05-01

```

# Answer
# JavaScript (ES6), 552 bytes

```
d=>(d=d.replace(/^20|-/g,'')*1,[for(r of'41020,60430;50408,61031;51013,70413;-60601,90714,110601;61026,80425;70419,81019;71018,90418;-80424,110512,130509;81030,100430;90423,101023;-91029,110430;-100429,130509,150430;101010,120410;110428,121028;111013,130509;-120426,170426;121018,140516;130425,140127;131017,140717;-140417,190430;141023,150723;150423,160131;151022,160731;-160421,210430'.split`;`.map(a=>a.split`,`))if(d>=(a=Math.abs(f=r[0]))&&((m=d<=r[1])||r[2]&&d<=r[2]))((a+'').slice(-6,-2)/100).toFixed(2)+'LTS'.slice(f)+(m?'':'-server')].join`, `)

```

Building the data array takes up ~68% of the total size. The rest is input formatting, array lookup, and output string construction.

The data string is split into an array of arrays of either 2 (normal) or 3 (server) length. The dates are reduced to numeric format, with the intial "20" stripped (along with any leading zeroes after that). LTS is denoted by a negative start date. Version numbers can be conveniently derived from all but the last two digits of the positive start date, divided by 100.
> 5 votes

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


title: Primitive Roots of Unity

text:
# Question
Title: Primitive Roots of Unity
Let `z` be a complex number. `z` is an nth **primitive root of unity** if for a certain positive integer `n`  and for any positive integer `k < n` .

## Challenge

Write a full program or function that, given a positive integer `n` as input, outputs all of the nth primitive roots of unity. You may output them in polar form (`e^θi` or `e^iθ`, argument should be a decimal with at least 2 decimal places) or rectangular form (`a + bi` or a similar form, real and imaginary parts should also be decimals), and they may be outputted in your language's list/array format or as a string with the numbers separated by spaces or newlines. Built-ins that calculate the nth roots of unity or the nth primitive roots of unity are not allowed.

This is , so shortest code in bytes wins.

## Sample Inputs and Outputs

```
6 -> e^1.05i, e^-1.05i # polar form
3 -> e^2.094395i, e^-2.094395i # any number of decimal places is OK as long as there are more than 2
8 -> 0.707 + 0.707i, 0.707 - 0.707i, -0.707 + 0.707i, -0.707 - 0.707i # rectangular form
1 -> 1 + 0i # this is OK
1 -> 1 # this is also OK
4 -> 0 + i, 0 - i # this is OK
4 -> i, -i # this is also OK

```

# Answer
> 9 votes
## Jelly, ~~11~~ 9 bytes

*Thanks to @Dennis for -2 bytes!*

```
Rg=1O÷H-*

```

I wanted to generate the numbers coprime to N by folding set difference over all of the roots of unity from 1 to N, but I couldn't figure out how so I used @Dennis's method.

```
Rg=1O÷H-*         Monadic chain:          6
R                 Range                   [1,2,3,4,5,6]
 g                Hook gcds with range    [1,2,3,2,1,6]
  =1              [gcds equal to one]     [1,0,0,0,1,0]
    O             Replicate indices       [1,5]
     ÷H           Divide by half of N     [1/3,5/3]
       -          Numeric literal: - by itself is -1.
        *         Take -1 to those powers [cis π/3,cis 5π/3]

```

~~Try it here~~. Valid in this version of Jelly, but may not be in versions after February 1, 2016.

# Answer
> 4 votes
# Jelly, 14 bytes

```
Rg=1O°÷×ı360Æe

```

Try it online!

### How it works

**z = e2tπi** is an **n**th root of **1** if and only if **t = k / n** for some integer **k**.

**z** is *primitive* if and only if **k** and **n** are coprime.

```
Rg=1O°÷×ı360Æe  Main link. Input: n

R               Yield [1, ..., n].
 g              Compute the GCDs of reach integer and n.
  =1            Compare the GCDs with 1.
    O           Get all indices of 1's.
                This computes all the list of all k in [1, ..., n]
                such that k and n are coprime.
     °          Convert the integers to radians.
      ÷         Divide the results by n.
       ×ı360    Multiply the quotient by the imaginary number 360i.
            Æe  Map exp over the results.

```

# Answer
> 3 votes
# Julia, 48 bytes

```
n->cis(360deg2rad(filter(k->gcd(k,n)<2,1:n))/n)

```

This is a lambda function that accepts an integer and returns an array of complex floats. To call it, assign it to a variable. It uses the same approach as Dennis' Jelly answer.

Ungolfed:

```
function f(n::Int)
    # Get the set of all k < n : gcd(k,n) = 1
    K = filter(k -> gcd(k,n) < 2, 1:n)

    # Convert these to radian measures
    θ = deg2rad(K)

    # Multiply by 360, divide by n
    θ = 360 * θ / n

    # Compute e^iz for all elements z of θ
    return cis(θ)
end

```

# Answer
> 2 votes
# MATL, 27 bytes

```
:1-tGYf1X-!\Xpg)2j*YP*G/Ze!

```

Uses release (9.3.1), which is earlier than this challenge.

**Try it online!**

(The online compiler uses a newer release, but the code runs in release 9.3.1 and gives the same result)

### Explanation

There are three main steps:

1. Generate integers `0`,`1`,...,`N-1`, corresponding to all roots.
2. Keep only integers corresponding to primitive roots. These are identified using the prime factor decomposition of `N`.
3. Generate the actual roots with an imaginary exponential.

Code:

```
:1-           % 1. Implicit input "N". Produce vector [0,1,...,N-1]
t             %    duplicate
GYf           % 2. Prime factors of N
1X-           %    remove factor "1" if present (only if N==1)
!\            %    all combinations of [0,1,...,N-1] modulo prime factors of N
Xpg           %    logical "and" along the prime-factor dimension
)             %    index into original vector [0,1,...,N-1] to keep only primitive roots
2j*YP*G/Ze    % 3. Imaginary exponential to produce those roots
!             %    transpose for better output format

```

# Answer
> 2 votes
# Ruby, 46 bytes

This is a non-"golfing language" implementation of Thomas Kwa's Jelly answer.

```
->n{(1..n).map{|j|1i**(4.0*j/n)if j.gcd(n)<2}}

```

Ungolfed:

```
def r(n)
  (1..n).each do |j|
    if j.gcd(n) == 1    # if j is coprime with n, then this will be a primitive root of unity
      p 1i**(4.0*j/n)   # print the fourth power of i**(j/n), i.e. the root of unity
    end
  end
end

```

# Answer
> 1 votes
# Matlab 49 bytes

```
n=input('');q=0:n-1;exp(i*2*pi/n.*q(gcd(n,q)==1))

```

Didn't get the task at the first time, but now here it is. Outputs as follows:

```
6
ans =
    0.5000 + 0.8660i   0.5000 - 0.8660i

```

# Answer
> 1 votes
## ES6, 96 bytes

```
n=>[...Array(n).keys()].filter(i=>g(i,n)<2,g=(a,b)=>a?g(b%a,a):b).map(i=>'e^'+Math.PI*2*i/n+'i')

```

Polar form was the shortest output.

# Answer
> 1 votes
# PARI/GP, 41 bytes

Pretty straightforward: find the numbers from 1 to n which are coprime to n, then

```
n->[exp(2*Pi*I*m/n)|m<-[1..n],gcd(n,m)<2]

```

There has to be some shorter way, but this was the best I could find.

---
Tags: code-golf, number-theory, complex-numbers
---


title: Check work periods

text:
# Question
Title: Check work periods
# Introduction

Here in Germany the ruling on work times is very strict. If you work 6 or more hours a day, you have to take at least a 30 minute break. If you work 9 or more hours, you need to take a 45 minute break. If you work less than 6 hours, you don't have to take any breaks.

Of course you can split those breaks, but each part has to be at least 15 minutes long to be counted.

# The Challenge

In this challenge you will get a list of work periods and you have to check if enough breaks were taken, using the following rules:

Let `w` be the work time in hours:

```
w < 6         -> No breaks needed
6 <= w < 9    -> 30 minute break needed
w >= 9        -> 45 minute break needed

```

Additionally, each break has to be at least 15 minutes long. Also you can always take more breaks than needed. Those are all "at least" values.

# Input

Your input will be a list of work periods. The exact format is up to you, but it has to contain only time values as hours and minutes.

**Example:**

Format here is a list of tuples while each tuple represents a working period. The first element in a tuple will be the start time, the second one will be the end time.

```
[("07:00","12:00"),("12:30","15:30"),("15:45","17:15")]

```

This results in a total work time of 9.5 hours and a total break time of 45 minutes.

Note that those working periods don't have to be separated by breaks. There can also be working periods which just follow each other (example see test cases).

Also note that breaks don't count into the working time. Those are two separate values.

You may assume that the working periods are ordered.

# Output

Given this input, output a *truthy* value if enough breaks were taken and a *falsy* value if not.

# Rules

* Specify the input format you are using in your submission.
* You don't have to handle empty input. There will always be at least one working period.
* The working periods will only span one day, so you don't have to handle work over midnight.
* Date-/Time-/Whatever- Builtins allowed, as long as it comes with your language.
* Function or full program allowed.
* Default rules for input/output.
* Standard loopholes apply.
* This is , so lowest byte-count wins. Tie-breaker is earlier submission.

# Test cases

Same input format as in the example above.

```
[("07:00","12:00"),("12:30","15:30"),("15:45","17:15")] -> TRUE  // 9:30h work, 45 minutes break -> OK
[("07:20","07:45"),("07:59","11:30"),("11:55","15:00")] -> FALSE // 7:01h work, 39 minutes break, but first break does not count because < 15 minutes
[("06:00","09:00"),("09:00","11:50")] -> TRUE   // Only 5:50h work, so no break needed
[("07:30","12:00"),("12:30","16:00")] -> TRUE   // 8h work, 30 minutes break -> OK
[("08:00","12:30"),("13:05","17:45")] -> FALSE // 9:10h work, only 35 minutes break instead of the needed 45
[("08:00","14:00")] -> FALSE  // 6h work, no breaks, but 30 minutes needed

```

**Happy Coding!**

# Answer
# Pyth, ~~56~~ 52 bytes

```
La.*bgsm*ydgyd15cPt_Jmid60Q2@[0030 45)hS,/syRcJ2C\´3

```

Takes input in the form `[[hh,mm], [hh,mm], ...]` with no leading `0`s

Explanation:

```
La.*bgsm*ydgyd15cPt_Jmid60Q2@[0030 45)hS,/syRcJ2C\´3

La.*b                                                - def y(b): return absdiff(*b)

                    Jmid60Q                          - Unpack the input to mins and assign to J
                    J                                - autoassign J = V
                     m    Q                          - [V for d in Q]
                      id60                           - conv_base(V, 60)

      sm*ydgyd15cPt_J      2                         - Get the total break
                   _J                                - reverse(J)
                 Pt                                  - ^[1:-1]
                c          2                         - chop(2, ^)
                                                     -
       m                                             - [V for d in ^]
            yd                                       - y(d)
           g  15                                     - >= 15
         yd                                          - y(d)
        *                                            - y(d) * (y(d)>=15)
                                                     -
      s                                              - sum(^)

                            @[0030 45)hS,/syRcJ2C\´3 - Get the break required
                                             cJ2     - chop(J, 2)
                                           yR        - map(y, ^)
                                          s          - sum(^)
                                                     - Now have the total time worked in mins
                                         /      C\´  - ^/ord("`")
                                                     - (^/180)
                                                     - Now have the time worked in 3 hour intervals
                                      hS,          3 - sorted([^, 3])[0]
                                                     - (min(^, 3))
                                                     - Now have hours worked in 3 hour intervals capped at 9 hours
                            @[0030 45)               - [0,0,30,45][^]
                                                     - Get the break required for that time

     g                                               - break >= break required

```

Try it here

Or try all the test cases here
> 1 votes

# Answer
# Javascript, ~~108~~ 106 bytes

```
m=>(k=t=0,m.map(l=>(a=l[0]*60+l[1],k+=t?a-b<15?0:a-b:0,b=l[2]*60+l[3],t+=b-a)),t/=60,t<6||k>44||t<9&&k>29)

```

Takes an array of arrays. Each inner array has the start hour and minute and end hour and minute respectively for each period.

```
f=m=>(                           // assign function to f
    k=t=0,                       // k break // t work
    m.map(l=>(                   // for each period
        a=l[0]*60+l[1],          // started time in minutes
        k+=t?a-b<15?0:a-b:0,     // if there was a break add it
        b=l[2]*60+l[3],          // ended time in minutes
        t+=b-a                   // sum worked time (the difference)
    )),                          //
    t/=60,                       // turn t from minutes to hours
    t<6||k>44||t<9&&k>29         // the main logic
)                                //

document.body.innerHTML = '<pre>' +
  f([[07,00,12,00],[12,30,15,30],[15,45,17,15]]) + '\n' +
  f([[07,20,07,45],[07,59,11,30],[11,55,15,00]]) + '\n' +
  f([[06,00,09,00],[09,00,11,50]]) + '\n' +
  f([[07,30,12,00],[12,30,16,00]]) + '\n' +
  f([[08,00,12,30],[13,05,17,45]]) + '\n' +
  f([[08,00,14,00]]) + '\n' +
'</pre>'
```
> 5 votes

# Answer
# Python 3, 135

Saved 3 bytes thanks to DSM.

This is one of my mathier solutions in a while.

```
def f(l):
 h=r=e=0
 for(a,b)in l:a+=a%1*2/3;b+=b%1*2/3;h+=b-a;r-=(e-a)*(e and(a-e)>.24);e=b
 return(h<6)|(6<=h<9and.5<=r)|(h>9and.74<r)

```

Here're my test cases, it also shows how I expect the function to be called.

```
assert f([(07.00, 12.00), (12.30, 15.30), (15.45, 17.15)])
assert not f([(07.20, 07.45), (07.59, 11.30), (11.55, 15.00)])
assert f([(06.00, 09.00), (09.00, 11.50)])
assert f([(07.30, 12.00), (12.30, 16.00)])
assert not f([(08.00, 12.30), (13.05, 17.45)])
assert not f([(08.00, 14.00)])

```
> 3 votes

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


title: Interpret the Pig series

text:
# Question
Title: Interpret the Pig series
Given an input of a Pig, SickPig, DeadPig, QuinePig, or DeafPig program, choose one of those "languages" randomly and interpret the input as that "language."

First, randomly choose between one of the five members of the "Pig series":

* ## Pig

If the choice was Pig, mimic the reference interpreter by doing the following:

+ Find the first occurrence of the word `PIG` in the input (case-sensitive).
    + If the word `PIG` does not appear in the input, output the message `File must contain the string 'PIG'.` and exit.
    + Otherwise, split the input string on the first occurrence of `PIG`. Output the text after the first occurrence of `PIG` to a file with a filename of the text before `PIG`.

    `PIG` may be contained in the text to be output (so, an input of `fooPIGbarPIGbaz` should output `barPIGbaz` to a file called `foo`).

Note that the reference interpreter takes input via a command line argument that specifies a filename to read from. However, your submission may take input in any of the standard methods accepted on PPCG.
* ## SickPig

If the choice was SickPig, follow the same instructions as Pig. However, instead of writing the text after `PIG` to the file, choose randomly from the following list

```
GRUNT
MOAN
OINK
BURP
GROAN
WHINE

```

and output that to the file instead. This random choice must be independent of the previous choice (so, an output of `GRUNT` should have a 1/5 * 1/6 = 1/30 chance overall).
* ## DeadPig

DeadPig is like SickPig, but it always outputs the following string instead of randomly choosing a string:

```
Your pig has unfortunately died. Please try again.

```
* ## QuinePig

QuinePig is like Pig, but instead of writing the text after `PIG` to the file, it instead writes the entire input to the file (so, an input of `fooPIGbarPIGbaz` should output `fooPIGbarPIGbaz` to a file called `foo`).
* ## DeafPig

If the choice was DeafPig, do nothing. (The pig is deaf... what do you expect?)

Miscellaneous rules:

* "Random" means each choice should be roughly equally likely (so, choosing Pig 90% of the time and the other variants only 2.5% of the time is invalid).
* You may assume that the requested filenames will always be valid for your file system (but they may contain spaces, etc.).
* For all the variants of Pig, your code may optionally output a single trailing newline to the file as well.
* Since this is , the shortest code in bytes will win.

# Answer
# Pyth - 157 bytes

Will be doing string compression.

```
?}J"PIG"z?=GO[jJtKczJOc"GRUNT MOAN OINK BURP GROAN WHINE"d"Your pig has unfortunately died. Please try again."z0).wGhK.q"File must contain the string 'PIG'."

```

Doesn't work online cuz of file I/O, but try it outputting `[content, filename]` to stdio here.
> 1 votes

# Answer
# Bash, ~~251~~ 246 bytes

```
r=$RANDOM
((r%5<4))||exit
[[ $1 =~ PIG ]]||(echo "File must contain the string 'PIG'.";exit)
s=(GRUNT MOAN OINK BURP GROAN WHINE)
m=("${1#*PIG}" ${s[r%6]}
"Your pig has unfortunately died. Please try again." "$1")
echo -n "${m[r%5]}">"${1%%PIG*}"

```

This would be a lot shorter if deaf pigs could at least read...
> 6 votes

# Answer
# Python 2, ~~296~~ ~~286~~ 278 bytes

```
def g(p):
 import random;f=random.randint;r=f(0,4);i=p.find("PIG")
 if r:
    if i+1:open(p[:i],"w").write([0,p[i+3:],["GRUNT","MOAN","OINK","BURP","GROAN","WHINE"][f(0,5)],"Your pig has unfortunately died. Please try again.",p][r])
    else:print"File must contain the string 'PIG'."

```

*The last two lines start with a tab, instead of the rendered 4 spaces.*

Takes input program as function argument.
> 4 votes

# Answer
## Batch, ~~409~~ ~~406~~ 405 bytes

```
@echo off
set/ar=%random%%%5
if 0==%r% exit/b
set p=x%1
set q=%p:*PIG=%
if %q%==%p% echo File must contain the string 'PIG'.&exit/b
set p=%1
call set p=%%p:PIG%q%=%%
goto %r%
:1
echo %q%>%p%
exit/b
:2
for %%a in (GRUNT.0 MOAN.1 OINK.2 BURP.3 GROAN.4 WHINE.5)do if %%~xa==.%time:~6,1% echo %%~na
exit/b
:3
echo Your pig has unfortunately died. Please try again.>%p%
exit/b
:4
echo %1>%p%

```

Sadly `%p:*PIG=%` fails if p is blank, thus the `x%1` hack. `call set` is a nice way to avoid enabledelayedexpansion that I found on Stack Overflow; while the `%%~xa==.` was a flash of inspiration on my part.

Edit: Saved 3 bytes thanks to @CᴏɴᴏʀO'Bʀɪᴇɴ. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.
> 2 votes

---
Tags: code-golf, string, random, file-system
---


title: All the numbers that fit in a string

text:
# Question
Title: All the numbers that fit in a string
Write a program or function that takes in a positive integer N. Output a list of all the distinct decimal numbers that can be written *in exactly N characters* using digits (`0123456789`), decimal points (`.`), and negative signs (`-`).

For example, some numbers that would be in the N = 4 output list are `1337`, `3.14`, `.999`, `-789`, `-2.7`, and `-.09`.

The numbers are to be written in the normal way, **but in as short a form as possible**. This means:

* The decimal point should only be included if the number is not an integer.

+ e.g. `45.0` and `45.` should be written as plain `45`
    + `-45.00` should be written as `-45`
* There should be no leading zeroes to the left of the decimal point.

+ `03` and `003` should be written as `3`, but `30` and `300` are fine as they are
    + `0.3` and `00.3` should be written as just `.3`
    + `-03` should be written as `-3`
    + `-0.3` should be written as `-.3`
* There should be no trailing zeroes to the right of the decimal point

+ `.50` and `.500` should be written as `.5`
    + `900.090` should be written as `900.09`
* The exception to the two last rules is zero itself, which should **always be written as plain `0`**.
* Positive signs (`+`) should not be used since they unnecessarily lengthen the number.

Also note that the negative sign (`-`) should not be used as a subtraction sign. It should only appear as the first character of numbers less than zero.

# Formatting

**The order of the output list of numbers does not matter.** It could be ascending, descending, or completely mixed up. It only matters that ***all*** of the distinct numbers that can be written in N characters are present.

The list can be formatted in a reasonable way, using spaces, newlines, commas, or perhaps something else between the numbers, as long as things are consistent. Leading and trailing brackets (or similar) are alright but things like quotes around numbers are not. (i.e. don't visibly mix up strings and ints/floats in the output.)

For example, when N = 1, some valid outputs would be:

```
0 1 2 3 4 5 6 7 8 9
```

```
[1, 2, 3, 4, 5, 6, 7, 9, 0]
```

```
ans = { 5 8 9 1 3 2 0 3 4 7 6 }
```

But this would be invalid:

```
[0, 1, 2, 3, 4, "5", "6", "7", "8", "9"]
```

# Examples

```
N = 1 -> 0 1 2 3 4 5 6 7 8 9

N = 2 -> -9 -8 -7 -6 -5 -4 -3 -2 -1 .1 .2 .3 .4 .5 .6 .7 .8 .9 10 11 12 ... 97 98 99

N = 3 -> -99 -98 ... -11 -10 -.9 -.8 ... -.2 -.1 .01 .02 ... .98 .99 1.1 1.2 ... 1.9 2.1 2.2 ... 2.9 3.1 ...... 9.9 100 101 ... 998 999

```

Lists are in ascending order, ellipsized in some places for reading convenience.

# Scoring

The shortest code in bytes wins. In case of ties, the higher voted answer wins

# Answer
# Pyth, ~~47~~ 45 bytes

*Thanks to FryAmTheEggman for noting that the order does not matter.*

```
jf!sm:Td)c".- \..*\. ^-?0. [.-]0*$"d^{`c_T17Q

```

Try it online.

The runtime is horrible, basically O(12n), but I tested it for `n` = 6 on my computer (which took 2 minutes). Running `n` ≥ 5 *will* time out online.

Due to the way I generate the characters `0123456789.-` the output is in a really weird order.

One could technically remove the `{` near the end, but it would result in a complexity of O(19n). (It would also produce lots of duplicates, but that's allowed.)

### Explanation

```
                  _T       -10
                 c  17     -10 / 17 = -0.5882352941176471
                `          representation: "-0.5882352941176471"
               {           uniquify: "-0.582394176"
              ^       Q    input'th Cartesian power
 f                         filter on:
         c"…"d               split this string by spaces
    m:Td)                    check if the parts match the current string
  !s                         true if none of the parts matched
j                            join by newlines

```

The main part of the code is `".- \..*\. ^-?0. [.-]0*$"`, which contains the regexes any output must *not* match.

```
.-         minus must be first character
\..*\.     there may only be one decimal point
^-?0.      no extra leading zeroes
[.-]0*$    number must not end with decimal/minus and 0+ zeroes

```
> 2 votes

# Answer
## Pyth, 57 bytes

```
j-f:T"^0$|^-?([1-9]\d*)?(\.\d*[1-9])?$"0{.P*Q+jkUT".-"Q\-

```

Try it on the online interpreter.

Way too long, and with horrific runtime (takes several seconds for N=4, running with N=5 is not recommended).

```
            .P           Q    all permutations of length (input) of
                 jkUT         ... the string "0123456789"
                +    ".-"     ... plus the chars "." and "-"
              *Q              ... whole thing times the input -- pyth has
                              no repeated_permutation, so this is necessary
           {                  uniquify
  f                           filter by
   :T"..."0                   does it match the really long regex?
 -                        \-  get rid of "-"
j                             join on newline

```

Regex explanation:

```
^0$|            "0", or...
^
 -?             optional negative sign
 ([1-9]\d*)?    optional part-before-decimal
 (\.\d*[1-9])?  optional part-after-decimal
$

```
> 3 votes

# Answer
# Julia, ~~126~~ 117 bytes

```
n->filter(i->ismatch(r"^0$|^-?([1-9]\d*)?(\.\d*[1-9])?$",i)&&i!="-",∪(map(join,combinations((".-"join(0:9))^n,n))))

```

This is a lambda function that accepts an integer and returns an array of strings. To call it, assign it to a variable. The approach here is the same as Doorknob's Pyth answer.

Ungolfed:

```
function g(n::Int)
    # Get all n-character combinations of .-0123456789
    c = combinations((".-"join(0:9))^n, n)

    # Join each group of n characters into a string and take unique
    u = ∪(map(join, c))

    # Filter to only appropriately formatted strings
    filter(i -> ismatch(r"^0$|^-?([1-9]\d*)?(\.\d*[1-9])?$", i) && i != "-", u)
end

```
> 2 votes

# Answer
# MATL, 60 bytes

```
45:57iZ^!"@!'^(-?(([1-9]\d*)|([1-9]\d*)?(\.\d*[1-9]))|0)$'XX

```

Try it online!

This uses super-brute force (via Cartesian power) followed by filtering (via a regular expression). I'll add an explanation later.

The results are displayed at the end of the program. This may take a while. If you want to see results as they are generated, add `D` at the end:

```
45:57iZ^!"@!'^(-?(([1-9]\d*)|([1-9]\d*)?(\.\d*[1-9]))|0)$'XXD

```
> 1 votes

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


title: What language is this word?

text:
# Question
Title: What language is this word?
Your should write a program or function that determines the language of a given word.

The task is to recognize some of the 5000 most common words in 4 languages:

* English
* German
* Italian
* Hungarian

The word lists can be found in this GitHub repository.

You are **allowed to make mistakes in 40% of the provided test cases**. I.e. you can miscategorize 8000 of the 20000 inputs.

## Details

* The lists only contain words with lowercase letters `a-z` so e.g. `won't` and `möchte` are not included.
* A few words appear in multiple languages which means your code can't always guess the expected output correctly.
* For convenience you can download all the test cases as one list. In each line a number indicates the language of the word. (`1` for English, `2` for German, `3` for Italian and `4` for Hungarian.)
* Standard loopholes are disallowed.
* Using word lists our similar data provided by your programming language is forbidden.

## Input

* A string containing only lowercase English letters (a-z).
* Trailing newline is optional.

## Output

* You can categorize the words by providing a distinct and consistent (always the same) output for each language. (E.g. `1` for English, `2` for German, `3` for Italian and `4` for Hungarian.)

This is code golf so the shortest program or function wins.

Related code golf question: Is this even a word?

The word lists were taken from wiktionary.org and 101languages.net.

# Answer
## Retina, 51 bytes

```
.*[aeio]$
1
A`en$|ch|ei|au
^$
2
A`[jkz]|gy|m$
\D+
4

```

I came up with the regexes and @MartinBüttner did the conversion to/golfing in Retina so ... hurray for team effort?

The mapping is `1 -> Italian, 2 -> German, (empty) -> Hungarian, 4 -> English`, with the amount classified in each category being `4506 + 1852 + 2092 + 3560 = 12010`.

Try it online! | Modified multiline version

### Explanation

First off, the equivalent Python is something like this:

```
import re
def f(s):
  if re.search("[aeio]$", s):
    return 1
  if re.search("en$|ch|ei|au", s):
    return 2
  if re.search("[jkz]|gy|m$", s):
    return ""
  return 4

```

Let me just say that `o$` is an *excellent* indicator of Italian.

The Retina version is similar, with pairs of lines forming replacement stages. For example, the first two lines

```
.*[aeio]$
1

```

replaces matches of the first line with the contents of the second.

The next three lines do the same, but using Retina's anti-grep mode - anti-grep (specified with `A``) removes the line if it matches the given regex, and the following two lines is a replacement from an empty line to the desired output.

```
A`en$|ch|ei|au
^$
2

```

The following line uses anti-grep again, but doesn't replace the empty line, giving the fixed output for Hungarian.

```
A`[jkz]|gy|m$

```

Finally, the last two lines

```
\D+
4

```

replaces a non-empty non-digit line with `4`. All of the substitutions can only happen if no previous substitution activated, simulating an `if/else if` chain.
> 10 votes

# Answer
# LabVIEW, 29 LabVIEW Primitives and 148.950 Bytes

cycles through the languages and puts the iterator into an array if the word is there. This gets checked by the inner loop, picking the ith line and doing `=`. In LabVIEW it only gives a true if the Strings are exactly the same.

Now take the first element of output array so englishgoes over the rest.

The output for now is `0` for English, `1` for German, `2` for Italian and `3` for Hungarian.
> 2 votes

# Answer
# Java, 3416 bytes, 62%

this is my solution, i analyze list of given words and find 60 most commons bigrams and trigrams for each languages. Now i'm checking my n-grams against word, and choosing language with most n-grams in word.

```
public class Classificator {

    String[][] triGr = {
            {"ing","ion","ent","tio","ted","nce","ter","res","ati","con","ess","ate","pro","ain","est","ons","men","ect","red","rea","com","ere","ers","nte","ine","her","ble","ist","tin","for","per","der","ear","str","ght","pre","ver","int","nde","the","igh","ive","sta","ure","end","enc","ned","ste","dis","ous","all","and","anc","ant","oun","ten","tra","are","sed","cti"},
            {"sch","che","ver","gen","ten","cht","ich","ein","ste","ter","hen","nde","nge","ach","ere","ung","den","sse","ers","and","eit","ier","ren","sen","ges","ang","ben","rei","est","nen","nte","men","aus","der","ent","hei","her","lle","ern","ert","uch","ine","ehe","auf","lie","tte","ige","ing","hte","mme","end","wei","len","hre","rau","ite","bes","ken","cha","ebe"},
            {"ent","are","ato","nte","ett","ere","ion","chi","con","one","men","nti","gli","pre","ess","att","tto","par","per","sta","tra","zio","and","iam","end","ter","res","est","nto","tta","acc","sci","cia","ver","ndo","amo","ant","str","tro","ssi","pro","era","eri","nta","der","ate","ort","com","man","tor","rat","ell","ale","gio","ont","col","tti","ano","ore","ist"},
            {"sze","ere","meg","ett","gye","ele","ond","egy","enn","ott","tte","ete","unk","ban","tem","agy","zer","esz","tet","ara","nek","hal","dol","mon","art","ala","ato","szt","len","men","ben","kap","ent","min","ndo","eze","sza","isz","fog","kez","ind","ten","tam","nak","fel","ene","all","asz","gon","mar","zem","szo","tek","zet","elm","het","eve","ssz","hat","ell"}

                    };
    static String[][] biGr = {
        {"in","ed","re","er","es","en","on","te","ng","st","nt","ti","ar","le","an","se","de","at","ea","co","ri","ce","or","io","al","is","it","ne","ra","ro","ou","ve","me","nd","el","li","he","ly","si","pr","ur","th","di","pe","la","ta","ss","ns","nc","ll","ec","tr","as","ai","ic","il","us","ch","un","ct"},
        {"en","er","ch","te","ge","ei","st","an","re","in","he","ie","be","sc","de","es","le","au","se","ne","el","ng","nd","un","ra","ar","nt","ve","ic","et","me","ri","li","ss","it","ht","ha","la","is","al","eh","ll","we","or","ke","fe","us","rt","ig","on","ma","ti","nn","ac","rs","at","eg","ta","ck","ol"},
        {"re","er","to","ar","en","te","ta","at","an","nt","ra","ri","co","on","ti","ia","or","io","in","st","tt","ca","es","ro","ci","di","li","no","ma","al","am","ne","me","le","sc","ve","sa","si","tr","nd","se","pa","ss","et","ic","na","pe","de","pr","ol","mo","do","so","it","la","ce","ie","is","mi","cc"},
        {"el","en","sz","te","et","er","an","me","ta","on","al","ar","ha","le","gy","eg","re","ze","em","ol","at","ek","es","tt","ke","ni","la","ra","ne","ve","nd","ak","ka","in","am","ad","ye","is","ok","ba","na","ma","ed","to","mi","do","om","be","se","ag","as","ez","ot","ko","or","cs","he","ll","nn","ny"}

                    };

    public int guess(String word) {

        if (word.length() < 3) {
            return 4; // most words below 2 characters on list are hungarians
        }
        int score[] = { 0, 0, 0, 0 };
        for (int i = 0; i < 4; i++) {
            for (String s : triGr[i]) {
                if (word.contains(s)) {
                    score[i] = score[i] + 2;
                }
            }
            for (String s : biGr[i]) {
                if (word.contains(s)) {
                    score[i] = score[i] + 1;
                }
            }
        }
        int v = -1;
        int max = 0;
        for (int i = 0; i < 4; i++) {
            if (score[i] > max) {
                max = score[i];
                v = i;
            }
        }
        v++;
        return v==0?Math.round(4)+1:v;
    }
}

```

and this is my testcase

```
public class Test {

    Map<String, List<Integer>> words = new HashMap<String, List<Integer>>();

    boolean validate(String word, Integer lang) {
        List<Integer> langs = words.get(word);
        return langs.contains(lang);
    }

    public static void main(String[] args) throws FileNotFoundException {

        FileReader reader = new FileReader("list.txt");
        BufferedReader buf = new BufferedReader(reader);
        Classificator cl = new Classificator();
        Test test = new Test();
        buf.lines().forEach(x -> test.process(x));
        int guess = 0, words = 0;
        for (String word : test.words.keySet()) {
            int lang = cl.guess(word);
            if (lang==0){
                continue;
            }
            boolean result = test.validate(word, lang);
            words++;
            if (result) {
                guess++;
            }
        }
        System.out.println(guess+ " "+words+ "    "+(guess*100f/words));
    }

    private void process(String x) {
        String arr[] = x.split("\\s+");
        String word = arr[0].trim();
        List<Integer> langs = words.get(word);
        if (langs == null) {
            langs = new ArrayList<Integer>();
            words.put(word, langs);
        }
        langs.add(Integer.parseInt(arr[1].trim()));

    }

}

```
> 2 votes

---
Tags: code-golf, natural-language, word, classification
---


# Question
Title: Implement almost-equals for IEEE numbers
Isn't it annoying when you're working with floating point numbers and your code doesn't work because two numbers are not equal by the least significant bit? Now you can fix that!

Write some code that takes two floating point numbers in any IEEE 754 binary format and returns `TRUE` if:

* the two numbers are exactly equal
* for two positive numbers: adding the value of the least significant bit to the smaller number makes it exactly equal to the larger value
* for two negative numbers: subtracting the value of the least significant bit from the larger number makes it exactly equal to the smaller value

Return `FALSE` if:

* any other case

IEEE 754 allows both positive and negative zero. Treat all zeros as the sign of the other non-zero number. IEEE 754 defines `0 === -0`. You can enter the numbers as text only if the binary representation in memory is accurate to the least significant bit.

### Test Data

The test data will vary slightly, depending on exactly which format your language uses. The table below shows the bit representation, followed by how to calculate the value, since most values will be impractical to directly input. A value such as `-1.5b-3` means -1.5 x 2<sup>-3</sup>.

Your code must be able to handle every format your language supports:

* binary16 (Half precision)
* binary32 (Single precision)
* binary64 (Double precision)
* binary128 (Quadruple precision)

If you are supporting any format other than binary64, expand or contract the bit patterns from the test data to their equivalents.

If your language doesn't natively support IEEE 754 at all, you may import an external library at no cost that fully implements at least one IEEE 754 binary format, but with no extra functions, i.e. you can't put your own function in the included library.

IEEE 754 binary64 (Double precision):

Zero and Subnormals:

```
0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074)
0 00000000000 0000000000000000000000000000000000000000000000000010 (1b-1073)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
0 00000000000 0000000000000000000000000000000000000000000000000010 (1b-1073)
FALSE

0 00000000000 0000000000000000000000000000000000000000000000000111 (1.75b-1072)
0 00000000000 0000000000000000000000000000000000000000000000001000 (1b-1071)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074)
TRUE

1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074)
1 00000000000 0000000000000000000000000000000000000000000000000010 (-1b-1073)
TRUE

0 00000000000 0000000000000000000000000000000000000000000000000000 (0)
1 00000000000 0000000000000000000000000000000000000000000000000010 (-1b-1073)
FALSE

0 00000000000 0000000000000000000000000000000000000000000000000001 (1b-1074)
1 00000000000 0000000000000000000000000000000000000000000000000001 (-1b-1074)
FALSE

```

Normalised numbers:

```
0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111111 0000000000000000000000000000000000000000000000000010 (1 + 1b-51)
FALSE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111111 0000000000000000000000000000000000000000000000000001 (1 + 1b-52)
TRUE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
TRUE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111110 1111111111111111111111111111111111111111111111111111 (1 - 1b-53)
TRUE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111110 1111111111111111111111111111111111111111111111111110 (1 - 1b-52)
FALSE

0 01111111111 0000000000000000000000000000000000000000000000000000 (1)
0 01111111110 0000000000000000000000000000000000000000000000000000 (0.5)
FALSE

0 10000010101 1111111111111111111111111111111111111111111111111110 (16777216 - 1b-28)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
FALSE

0 10000010101 1111111111111111111111111111111111111111111111111111 (16777216 - 1b-29)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
TRUE

0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
TRUE

0 10000010110 0000000000000000000000000000000000000000000000000001 (16777216 + 1b-28)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
TRUE

0 10000010110 0000000000000000000000000000000000000000000000000010 (16777216 + 1b-27)
0 10000010110 0000000000000000000000000000000000000000000000000000 (16777216)
FALSE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010111 (-1 / 3 - 1b-53)
FALSE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010110 (-1 / 3 - 1b-54)
TRUE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
TRUE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010100 (-1 / 3 + 1b-54)
TRUE

1 01111111101 0101010101010101010101010101010101010101010101010101 (-1 / 3)
1 01111111101 0101010101010101010101010101010101010101010101010011 (-1 / 3 + 1b-53)
FALSE

1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
TRUE

1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
1 11111111110 1111111111111111111111111111111111111111111111111110 (-1b1024 + 1b970)
TRUE

1 11111111110 1111111111111111111111111111111111111111111111111111 (-1b1024 + 1b971)
1 11111111110 1111111111111111111111111111111111111111111111111101 (-1b1024 + 1.5b970)
FALSE

```

Infinity and Not A Number:

```
X 11111111111 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

INF
INF
TRUE

INF
Any other value
FALSE

-INF
-INF
TRUE

-INF
Any other value
FALSE

NAN
Any value, including NAN
FALSE

```

### Scoring

Number of bytes - (number of bytes needed for IEEE 754 library `include`, if an external library is used)

# Answer
> 2 votes
# C++14 using IEEE754 platform, 17 + 49 = 66 bytes

Includes, 17 bytes:

```
#include <cmath>

```

Lambda expression, 49 bytes:

```
[](auto a,auto b){return b==std::nextafter(a,b);}

```

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


title: Smallest Lua table copy

text:
# Question
Title: Smallest Lua table copy
So I really like to mess with tables and shallow and deep copies and I can do it in 239 chars! I wonder if there's a shorter way to do it...

Rules:

* It must be done in less than 239 chars.
* You must set table.copy.shallow and table.copy.deep.
* A deep copy must maintain recursion. (so if I had tx.t == tx, a deep copy must have ty.t == ty (where ty is a deep copy of tx))
* You must make a local copy of every function you use. (for speed)
* You must be able to pass in a custom recursion table with a metatable to override default copy behavior. (at least on the deep copy function, see examples here)
* If needed, use metatables. If possible, abuse them.
* It must work in Lua 5.1 and 5.2.
* You may use load/loadstring.
* You may use the C API.
* Some input/output examples (actually unit test): https://gist.github.com/SoniEx2/7942bdd0658b719ab275

# Answer
> 2 votes
## 235

Substantially based on the guts of SoniEx2's 239 answer.

```
local o,k,F=type,next,{}for n=0,2 do
F[n]=function(a,r,t,G)if n<1 or o{}~=o(a)then return a end
t={}r=r or{}r[a]=n<2 and t G=F[n%2]for x,y in k,a do
t[r[x]or G(x,r)]=r[y]or G(y,r)end
return t end end
table.copy={shallow=F[2],deep=F[1]}

```

The advantage comes from using the same function prototype for both functions. Instantiating the same function prototype with different upvalues allows it to fill both roles.

Ungolfed:

```
-- ungolfed
-- note that type and next must have local copies to meet the spec
local o, k, F = type, next, {}
for n = 0, 2 do
  -- F[0] will be the identity function
  -- F[1] will be table.copy.deep
  -- F[2] will be table.copy.shallow
  F[n] = function(a, r, t, G)
    -- a is the table input
    -- r is the optional "custom recursion table" that is required
    -- t and G are just locals
    -- the spec implies (but does not state) that the global environment shouldn't be polluted
    -- r will only be used by recursive calls

    -- if n < 1, this is F[0], so act is the identity
    -- o is type, o{} is "table"
    -- if a is not a table, just return it
    if n < 1 or o{} ~= o(a) then
      return a
    end

    -- t will be the copy
    t = {}

    -- r will be the map that remembers which tables in the original map to which tables in the copy
    -- or, if it is passed in, it is a table that controls the behavior of the copy
    r = r or {}

    -- F[0] doesn't each here
    -- F[1] must add t to the map
    -- F[2] must not add t to the map
    -- (adding false will not hurt F[2] -- only true values will be picked up below)
    -- (behavior may not be exactly as desired for shallow copy, but spec doesn't require this feature)
    r[a] = n < 2 and t

    -- this is the function we will call to copy members
    -- for F[1] table.copy.deep, this is F[1] itself
    -- for F[2] table.copy.shallow, this is F[0] the identity
    -- (for F[0], we never get this far)
    -- the byte count seems equivalent making this a local vs putting it
    -- in both places it is used, but this is probably more efficient
    G=F[n%2]

    -- loop over and copy members
    -- first try r (which will only have non-1 entries for tables in F[1])
    -- then try G
    -- note that instead of calling "pairs" as usual, we can observe that pairs(a)
    -- is defined to return next, a, nil -- we use these (with implicit nil) directly
    for x, y in k, a do
      t[r[x] or G(x,r)] = r[y] or G(y,r)
    end

    return t
  end
end

-- export the functions as required
table.copy = {
  shallow = F[2],
  deep = F[1]
}

```

Hopefully I understood the spec correctly. This passes the provided test cases and there is enough similarity in the construction that I'm reasonably sure it does the same thing.

Note -- Initially I didn't understand the part about the "custom recursion table", but I have edited my answer to support it.

Note 2 -- Improved answer. I've also decided that the provided reference solution in 239 bytes does not exactly match my understanding of how the custom recursion table ought to work, since it cannot be used to add false into the copy. However, I believe my solution works as well as the provided one.

# Answer
> 1 votes
## 238 chars!

Turns out, it wasn't impossible!

```
loadstring(("local k,o,d=next,type dDif o{}~=o(a)thenBaAt={}r=r or{}r[a]=tCt[r[x]or d(x,r)]=r[y]or d(y,r)ABtAtable.copy={shallowDt={}Ct[x]=yABtA,deep=d}"):gsub("%u",{A=" end ",B=" return ",C=" for x,y in k,a do ",D="=function(a,r,t)"}))()

```

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


title: Find the coastline

text:
# Question
Title: Find the coastline
Your task is to find the length of the coastline of a map of islands provided in an ASCII map. The input map will consist of 1 or more `#` characters that indicate land, and spaces which indicate water. The coastline is considered to be any edge between land and water, including inland lakes and islands.

Your solution should be a complete program that reads in a file, a string or an array of strings, and outputs a single integer to the screen or stdout. Each input line may have leading or trailing space, and zero or more hash characters. The borders of the map are assumed to be space (water).

Lines may be of different lengths.

## Examples:

```
Input:
##
##
Output: 8

Input:
    ###    ###
  #####     #
   ##
Output: 26

Input:
  #####
  #   #
  # # #
  #   #
  #####
Output: 36

```

This is code golf, so the smallest byte count wins.

# Answer
# Snails, 8 bytes

```
A
\#o!\#

```

The `A` option means to count all matching paths rather which starting points a match succeeds from. `\#` consumes a `#`, `o` turns in a cardinal direction, and `!\#` is a negative assertion which succeeds if there is not a `#` in front of us.
> 14 votes

# Answer
# Pyth - ~~25~~ 23 bytes

First it pads the input to a rect. Then counts the occurrences of `" #"` over the 4 permutations of transpositions and reversals of the input+space.

```
/ssm_B++;j;d;CB.t.zd" #

```

Try it online here.
> 4 votes

# Answer
## ES6, ~~123~~ ~~115~~ 114 bytes

```
a=>a.map((s,i)=>s.replace(/#/g,(h,j)=>r+=(s[j-1]!=h)+(s[j+1]!=h)+((a[i-1]||'')[j]!=h)+((a[i+1]||'')[j]!=h)),r=0)|r

```

Edit: Saved 9 bytes thanks to @edc65.
> 3 votes

# Answer
# MATL, 42 bytes

```
c2\FTFt!*Y+2*qFTFtl-4lhhbvv_2X53$Y+t0>)s2/

```

This accepts the input as a cell array of strings, of the form

```
{'#####', '#   #', '# # #', '#   #', '#####'}

```

It first converts the input to a 2D char array, padding with spaces, and then to a matrix of zeros and ones. 2D-convolution is then applied twice, with two different masks: first for expanding the matrix, second for detecting edges.

Try it online!
> 2 votes

# Answer
# Japt, ~~22~~ 19 bytes

```
4o £UzX è"#%s|#$} x

```

Assumes the input is padded with spaces to form a rectangle. Test it online!

### How it works

```
          // Implicit: U = input string, S = a space
4o £    } // Create the array [0,1,2,3], and map each item X to:
UzX       //  Rotate U by 90 degrees X times.
è"#%s|#$  //  Count the number of "#"s followed by a space, newline, or end-of-string.
x         // Sum the resulting array.

```
> 0 votes

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


# Question
Title: Print sin, cos, and tan of special angles
In trigonometry, there are certain angles known as "special angles". This is because when you take sin, cos or tan of one of these angles, you get a result that is easy to remember because it is a square root of a rational number. These special angles are always multiples of either `pi/6`, or `pi/4`. Here is a visualization of all the special angles, and their corresponding trig values.

As you can see, for each angle their is a corresponding pair of numbers. The first number is cosine of that angle, and the second is sine of that angle. To find tangent of one of these angles, just divide sin by cos. For example, `tan(pi/6)` is equal to

```
sin(pi/6) / cos(pi/6) ==
(1/2) / (√3/2) ==
1/√3 ==
√3/3

```

# The Challenge

You must write a full program that takes 3 inputs.

1. A single char representing the trig function you're supposed to calculate. This will be either 's' (sin), 'c' (cos), or 't' (tan).
2. The numerator of the input angle. This can be any positive integer. Note that an input of 5 means the numerator is 5 * pi.
3. The denominator of the input angle. This will always be one of the following: `1, 2, 3, 4, 6`

Then print out the exact value the trig function of that angle. Here is a list of sin, cos, and tan of all angles up to 2 * pi:

```
sin(0pi):    0
sin(pi/6):   1/2
sin(pi/4):   root(2)/2
sin(pi/3):   root(3)/2
sin(pi/2):   1
sin(2pi/3):  root(3)/2
sin(3pi/4):  root(2)/2
sin(5pi/6):  1/2
sin(1pi):    0
sin(7pi/6):  -1/2
sin(5pi/4):  -root(2)/2
sin(4pi/3):  -root(3)/2
sin(3pi/2):  -1
sin(5pi/3):  -root(3)/2
sin(7pi/4):  -root(2)/2
sin(11pi/6): -1/2
sin(2pi):    0

cos(0pi):    1
cos(pi/6):   root(3)/2
cos(pi/4):   root(2)/2
cos(pi/3):   1/2
cos(pi/2):   0
cos(2pi/3):  -1/2
cos(3pi/4):  -root(2)/2
cos(5pi/6):  -root(3)/2
cos(1pi):    -1
cos(7pi/6):  -root(3)/2
cos(5pi/4):  -root(2)/2
cos(4pi/3):  -1/2
cos(3pi/2):  0
cos(5pi/3):  1/2
cos(7pi/4):  root(2)/2
cos(11pi/6): root(3)/2
cos(2pi):    1

tan(0pi):    0
tan(pi/6):   root(3)/3
tan(pi/4):   1
tan(pi/3):   root(3)
tan(pi/2):   nan
tan(2pi/3):  -root(3)
tan(3pi/4):  -1
tan(5pi/6):  -root(3)/3
tan(1pi):    0
tan(7pi/6):  root(3)/3
tan(5pi/4):  1
tan(4pi/3):  root(3)
tan(3pi/2):  nan
tan(5pi/3):  -root(3)
tan(7pi/4):  -1
tan(11pi/6): -root(3)/3
tan(2pi):    0

```

If you get a number larger than 2pi, subtract 2pi from it until you get a number that is in range. For example, `sin(17pi/6)` is the same as `sin(5pi/6)` == 1/2. Your program is expected to do basic simplification, for example, if your input is `cos(2pi/4)` this is the same as `cos(pi/2)` == 0. Builtin trigonometry functions are disallowed.

Shortest answer in bytes wins!

# Answer
## Pyth, 125 122 bytes

Uses the formula `n = 4 - |floor(4.5-9k)|`, where `kπ = θ` i.e. k is the quotient of the second and third inputs, to determine which special angle is in question: the angles 0, 30, 45, 60 and 90 degrees are numbered 0 to 4 respectively, and the 90~180 degrees angles go in reverse; this formula works for `θ∈[0,π]`. The values of corresponding sines would be `sqrt(n)/2` and existent, non-zero tangents would be `3^(n/2-1)`. However, my implementation uses lists with hard-coded compressed strings for higher control of output format, and it seems the code is shorter that way too.

```
A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"dc." t@a'óè©ê¶oyÑáîwÀ(";J+cEE?qz\c.5ZK-4.as-4.5*3*3%J1?qz\t+?>%J1 .5\-k@GK+?>%J2 1\-k@HK

```

Let's turn it into pythonic pseudocode:

```
                                   z = input()
                                   k = ""
                                   d = " "
                                   Z = 0
A,c." t8¾Îzp³9ÓÍÕ¬$ ·Íb³°ü"d       G = "0 sqrt(3)/3 1 sqrt(3) nan".split(d)
  c." t@a'óè©ê¶oyÑáîwÀ(";          H = "0 1/2 sqrt(2)/2 sqrt(3)/2 1".split()
J+cEE                              J = eval(input())/eval(input()) +
  ?qz\c.5Z                             0.5 if z == "c" else Z
                                   # the second term converts sin to cos
K-4.as-4.5*3*3%J1                  K = 4 - abs(int(4.5 - 3*3*(J%1)))
                                   # 9* would lose precision so 3*3* instead
?qz\t                              if z == "t"
  +?>%J1 .5\-k                         print(("-" if J%1 > 0.5 else k) +
   @GK                                     G[K])
                                   else:
  +?>%J2 1\-k                          print(("-" if J%2 > 1 else k) +
   @HK                                     H[K])

```

Test online.
> 2 votes

---
Tags: code-golf, trigonometry
---


title: Eat the Chocolate Bar

text:
# Question
Title: Eat the Chocolate Bar
I have a chocolate bar and I need help eating it so you'll be writing a program just to do that.

## Explanation

The first line is the input. Examples are separated by an empty line.

```
7
   ____
 __|__|
|__|__|
|__|__|
|__|__|

6
_______
|__|__|
|__|__|
|__|__|

5
   ____
 __|__|
|__|__|
|__|__|

0

1
   ____
   |__|

```

## Spec

Hopefully the examples clearly specify this challenge but to avoid any possible confusion, here's a spec:

You can have a single optional trailing/leading whitespace

An input of `0` is an empty output.

If the input is even, the top rows looks like:

```
_______
|__|__|

```

If it's odd, the top row is:

```
   ____
   |__|

```

If it's odd and greater than 1, the top rows are:

```
  ____
__|__|

```

---

The following rows are:

```
|__|__|

```

until the number of instances of `|__|` is the same as the input

# Answer
> 1 votes
# Pyth, 55 bytes

```
K"|__|"IQ>7<*3%Q2r"3 7_"9?tQjb+XW%Q2J+KtKZd*/tQ2]J+*3dK

```

Try it online. Test suite.

This is really quick and dirty, written on my phone. Will get to more golfing later.

# Answer
> 4 votes
# Haskell, 101 bytes

Haskell has never been great for code golfing...

```
b="\n|__|__|"
h="   ____\n "
f 1=h++"  |__|"
f 2="_______"++b
f 3=h++"__|__|"++b
f n=f(n-2)++b
f _=""

```

# Answer
> 3 votes
# JavaScript ES6, 80 bytes

```
x=>(x%2?`   ____
 ${x<2?"  ":"__"}|__|`:x?"_______":"")+`
|__|__|`.repeat(x/2)

```

Uses the same technique as my Japt answer, and is surprisingly not much longer...

# Answer
> 1 votes
# Japt, ~~60~~ 57 bytes

```
U%2?[S³'_²²RSU¥1?S²:'_²"|__|"]¬:U?'_p7 :P +"
|__|__|"pU/2

```

Just a basic answer. Can probably be improved. Test it online!

# Answer
> 1 votes
# C, 104 102 bytes

```
f(x){x?x%2?printf("   ____\n%3s|__|\n",x<2?"":"__"):puts("_______"):0;for(x/=2;x>0;x--)puts("|__|__|");}

```

Maybe I can use some printf trickery to improve this...
Apparently I can

# Answer
> 1 votes
# PHP, 134 chars

```
<?$i=$argv[1];if($i>0){echo($i%2===0?"_______\n|__":"   ____\n".($i>1?"___":"   "))."|__|\n";echo str_repeat("|__|__|\n",($i-1)/2);}?>

```

Notes:

* PHP was not built for code golfing
* I sure had FUN making this snippet
* It throws an error if argv is undefined
* Any help to short it is appreciated.

# Answer
> 1 votes
# , 53 chars / 67 bytes

```
ï%2?`   ⟮__⟯Ⅰ
 ⦃ï<2?⍞  :⍞Ⅰ⦄|Ⅰ|`:ï?⍘_ď7:⬯⦄
|Ⅰ|Ⅰ|`ď ï/2

```

`Try it here (Firefox only).`

This is quite similar to the Javascript ES6 answer, even though I found it independently. Explanation to come when I finish golfing.

# Answer
> 1 votes
# Retina, 69 bytes

```
r`(1?)1
$1__|__|¶
^__(?=\D{5}$)

^.
$0____¶ $0
^\D

^1
___
 ?1
|

```

Takes input in unary.

Try it online here.

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