title: Implement INTERCAL's Binary Operators

text:
# Question
Title: Implement INTERCAL's Binary Operators
The Compiler Language With No Pronounceable Acronym, abbreviated INTERCAL, is a very unique programming language. Among its unreproducible qualities are its binary operators.

INTERCAL's two binary operators are **interleave** (also known as **mingle**), and **select**. Interleave is represented with a change (¢), and select is represented with a sqiggle (~).

Interleave works by taking two numbers in the range 0-65535 and alternating their bits. For instance:

```
234 ¢ 4321
234   = 0000011101010
4321  = 1000011100001
Result: 01000000001111110010001001
Output: 16841865

```

Select works by taking two numbers in the range 0-65535, taking the bits in the first operand which are in the same position as 1s in the second operand, and right packing those bits.

```
2345 ~ 7245
2345  = 0100100101001
7245  = 1110001001101
Taken : 010   0  10 1
Result: 0100101
Output: 37

```

In this challenge, you will be given a binary expression using either the interleave or select operation. You must calculate the result, using the fewest possible bytes.

The expression will be given as a space separated string, consisting of an integer in 0-65535, a space, either `¢` or `~`, a space, and an integer in 0-65535.

Input and output may be through any standard system (STDIN, function, command line, etc.). Standard loopholes banned.

Examples:

```
5 ¢ 6
54

5 ~ 6
2

51234 ¢ 60003
4106492941

51234 ~ 60003
422

```

This is code golf - fewest bytes wins. Good luck.

EDIT: Since some languages do not support INTERCAL's change (¢) symbol, you may use the big money ($) symbol instead, at a 5 byte penalty.

# Answer
# Pyth, ~~32~~ ~~31~~ 29 bytes

```
isummFdG}\~zCm.[Z16jvd2%2cz)2

```

Try it online: Regular Input / Test Suite

Thanks to @isaacg for golfing off one byte.

### Explanation:

```
                         cz)   split input at spaces
                       %2      only take every second item (the numbers)
             m                 map each number d to:
                    vd           convert d to int
                   j  2          convert to base 2
              .[Z16              pad zeros at the left
            C                  zip
  u     }\~z                   apply the following function ("~" in input) times:
   m   G                         map each pair d to:
    mFd                          convert [x,0] to [] and [x,1] to [x]
 s                             take sum (unfold all lists)
i                           2  convert back from base 2 and print

```
> 9 votes

# Answer
# Python 2, ~~115~~ 112 bytes

```
x,y,z=input().split()
d=y<""
f=lambda a,b:a+b and(b%2+5&4-d)*f(a/2,b/2)+(a%2*2+b%2)/3**d
print f(int(x),int(z))

```

The string on the second line contains a single unprintable character `\x7d`, the next char after `~`.

All hopes of a nice, single lambda get crushed by the input format. There's probably a better way to read in input. Input like `"51234 ¢ 60003"` via STDIN.

The function `f` combines the following two recursive functions:

```
g=lambda a,b:a+b and 4*g(a/2,b/2)+a%2*2+b%2    # ¢
h=lambda a,b:a+b and(b%2+1)*h(a/2,b/2)+a*b%2   # ~

```

*(-3 bytes with the help of @xnor)*
> 13 votes

# Answer
# CJam, 31 bytes

```
rrc\r]{i2bF0e[}%(7=\zf{_)*?~}2b

```

Try it online in the CJam interpreter.

### How it works

```
rr                              e# Read two tokens from STDIN.
  c\                            e# Cast the second to char and swap with the first.
    r                           e# Read a third token from STDIN.
     ]                          e# Wrap everything in an array.
      {       }%                e# For all three elements:
       i2b                      e#   Cast to int and convert to base 2.
          F0e[                  e#   Left-pad with zeroes to complete 15 digits.
                (               e# Shift out the first base 2 array.
                 7=             e# Select its eighth MSB (1 for '¢', 0 for '~').
                   \            e# Swap with the array of base 2 arrays.
                    z           e# Zip to transpose rows with columns.
                     f{     }   e# For each pair of base 2 digits:
                                e#   Push the bit, then the pair.
                       _        e#   Copy the pair.
                        )       e#   Pop the second digit.
                         *      e#   Repeat the first digit that many times.
                          ?     e#   Ternary if. Select the pair if the bit is
                                e#    truthy, the repeated first bit if it's falsy.
                           ~    e#   Dump the selected array on the stack.
                             2b e# Convert from base 2 to integer.

```
> 11 votes

# Answer
# JavaScript (ES6), 103 ~~117 119 124~~

**Edit** now working with numbers instead of strings

(not counting leading spaces, newlines and comments)

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

```
I=s=>
  (i=>{
    for(m=r=0,[a,o,b]=s.split` `;i>0;i<<=1) // loop until bit 31 of i is set
      o>'~'?r+=(b&i)*i+(a&i)*2*i:b&i?r+=(a&i)>>m:++m
  })(1)||r

// TEST
out=x=>O.innerHTML+=x+'\n\n';

[ ['234 ¢ 4321', 16841865], ['2345 ~ 7245', 37]
, ['5 ¢ 6', 54], ['5 ~ 6', 2]
, ['51234 ¢ 60003',4106492941], ['51234 ~ 60003', 422]]
.forEach(([i,o,r=I(i)])=>{
  out('Test '+ (o==r?'OK':'Fail')+'\nInput:    '+ i+'\nResult:   '+r+'\nExpected: '+o)})
```

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

# Answer
# Python 3, 174 166 148 126

Pretty straightforward, string operations, then conversion back to integer.

Limited to numbers which in binary have 99 digits (max 2^99-1 = 633825300114114700748351602687).

Thanks, Sp3000 and Vioz!

```
a,o,b=input().split()
print(int(''.join([(i+j,i[:j>'0'])[o>'~']for i,j in zip(*[bin(int(j))[2:].zfill(99)for j in(a,b)])]),2))

```

Or 165 chars, without limit:

```
a,o,b=input().split()
a,b=[bin(int(j))[2:]for j in(a,b)]
print(int(''.join([(i if j=='1'else'')if o=='~'else i+j for i,j in zip(a.zfill(len(b)),b.zfill(len(a)))]),2))

```

Ungolfed:

```
a, op, b = input().split()
a, b = [bin(int(j))[2:] for j in(a,b)] #convert to int (base 10), then to binary, remove leading '0b'
m = max(len(a), len(b))
a = a.zfill(m) #fill with leading zeroes
b = b.zfill(m)
if op == '~':
    ret = [i if j=='1' else'' for i, j in zip(a, b)]
else:
    ret = [i + j for i, j in zip(a, b)]
ret = ''.join(ret) #convert to string
ret = int(ret, 2) #convert to integer from base 2
print(ret)

```
> 5 votes

# Answer
## Matlab, ~~119~~ 113 bytes

```
function f(s)
t=dec2bin(str2double(strsplit(s,{'¢' '~'}))');u=any(s>'~');[~u u]*bin2dec({t(1,t(2,:)==49) t(:)'})

```

Ungolfed:

```
function f(s)                                     % input s is a string
t = dec2bin(str2double(strsplit(s,{'¢' '~'}))');  % get the two numbers and convert to
                                                  % two-row char array of zeros of ones
u = any(s>'~');                                   % 1 indicates '¢'; 0 indicates '~'
[~u u]*bin2dec({t(1,t(2,:)==49) t(:)'})           % compute both results and display
                                                  % that indicated by u

```

Examples:

```
>> f('234 ¢ 4321')
ans =
    16841865

>> f('2345 ~ 7245')
ans =
    37

```
> 5 votes

# Answer
# R, 145 bytes

```
s=scan(,"");a=as.double(c(s[1],s[3]));i=intToBits;cat(packBits(if(s[2]=="~")c(i(a[1])[i(a[2])>0],i(0))[1:32] else c(rbind(i(a[2]),i(a[1]))),"i"))

```

Ungolfed + explanation:

```
# Read a string from STDIN and split it on spaces
s <- scan(, "")

# Convert the operands to numeric
a <- as.double(c(s[1], s[3]))

o <- if (s[2] == "~") {
    # Get the bits of the first operand corresponding to ones in
    # the second, right pad with zeros, and truncate to 32 bits
    c(intToBits(a[1])[intToBits(a[2]) == 1], intToBits(0))[1:32]
} else {
    # Interleave the arrays of bits of the operands
    c(rbind(intToBits(a[2]), intToBits(a[1])))
}

# Make an integer from the raw bits and print  it to STDOUT
cat(packBits(o, "integer"))

```
> 5 votes

# Answer
## Pyth, 43 bytes

Part of me feels nervous posting such a long Pyth answer on isaacg's question... :oP

```
J.(Kczd1Am.BvdKiu?qJ\~u+G?qeH\1hHk+VGHk.iGH2

```

Explaination:

```
                                               Implicit: z=input(), k='', d=' '
   Kczd                                        Split z on spaces, store in K
J.(    1                                       Remove centre element from K, store in J
         m    K                                For each d in K
          .Bvd                                 Evaluate as int, convert to binary string
        A                                      Store pair in G and H
                                               ~ processing:
                                 +VGH          Create vectorised pairs ([101, 110] -> [11, 01, 10])
                     u               k         Reduce this series, starting with empty string
                        ?qeH\1                 If 2nd digit == 1...
                              hHk              ... take the 1st digit, otherwise take ''
                      +G                       Concatenate
                                      .iGH     ¢ processing: interleave G with H
                ?qJ\~                          If J == ~, take ~ processing, otherwise take ¢
               i                          2    Convert from binary to decimal

```
> 4 votes

# Answer
# CJam, ~~61~~ ~~50~~ ~~46~~ ~~41~~ 34 bytes

Thanks @Dennis for pointing out a 4 bytes golf.

```
rrc'~=:X;r]{i2bF0e[}/.{X{{;}|}&}2b

```

Try it online.
> 3 votes

# Answer
# C, ~~127~~ 123 bytes + 5 penalty = 128

`scanf` counts the unicode symbol as more than one character which complicates things a lot, so I'm applying the 5-byte penalty for using `$`.

```
a,b,q,x,i;main(){scanf("%d %c %d",&a,&q,&b);for(i=65536;i/=2;)q%7?x=x*4|a/i*2&2|b/i&1:b/i&1&&(x=x*2|a/i&1);printf("%u",x);}

```

The changes from the original version are:

-The test for $ or ~ has been revised from `q&2` to `q%7`. This reverses the true/false values, allowing the code for $ operator to go before the `:` which means a set of parentheses can be eliminated.

-The `i` loop now counts down in powers of 2 which is longer, but permits `>>` to be substituted by `/` and saves some parentheses.

**Original version 127 bytes**

```
a,b,q,x,i;
main(){
  scanf("%d %c %d",&a,&q,&b);
  for(i=16;i--;)
    q&2?
      b>>i&1&&(x=x*2|a>>i&1):    // ~ operator. && used as conditional: code after it is executed only if code before returns truthy.
      (x=x*4|(a>>i&1)*2|b>>i&1); // $ operator
  printf("%u",x);
}

```

I went with a single loop with the conditionals inside to avoid the overhead of two loops. In both cases I rightshift the bits of the operands down to the 1's bit, and build up the result from the most significant to least significant bit, leftshifting the result (multiplying by 2 or 4) as I go.
> 3 votes

# Answer
# K5, ~~53~~ 52 bytes

```
{b/({,/x,'y};{x@&y})[*"~"=y][b\.x;(b:20#2)\.z]}." "\

```

53-byte version:

```
{b/({,/x,'y};{x@&y})[*"¢~"?y][b\.x;(b:20#2)\.z]}." "\

```

Still needs a bit more golfing.
> 3 votes

# Answer
# Haskell, 77

```
g=(`mod`2)
h=(`div`2)
0¢0=0
a¢b=g a+2*b¢h a
a?0=0
a?b=g a*g b+(1+g b)*h a?h b

```

input is given by applying the input to the functions/operators `?` and `¢` defined in the code (Haskell can't define an operator `~` for technical reasons).

basically works the old recursive approach.
> 3 votes

# Answer
# Python 3, 157 bytes

```
a,x,y=input().split()
i=int
b=bin
print(i(''.join(([c for c,d in zip(b(i(a)),b(i(y)))if d=='1'],[c+d for c,d in zip(b(i(a))[2:],b(i(y))[2:])])['¢'==x]),2))

```

Full and explanatory version can be found on my pastebin.
> 2 votes

# Answer
# J, 173

```
f=:|."1@(>@(|.&.>)@(#:@{:;#:@{.))
m=:2&#.@:,@:|:@:|.@:f
s=:2&#.@#/@:f
a=:{&a.@-.
(1!:2)&2(s@".@:a&126)^:(126 e.i)((m@".@:a&194 162)^:(1 e.194 162 E.i)i=._1}.(a.i.((1!:1)3)))

```

expects one line of input

input expected to terminate after new line with EOF
> 2 votes

# Answer
# Javascript ES6 (3 arguments) ~~141~~ ~~138~~ ~~136~~ ~~121~~ 119 bytes

```
b=x=>(65536|x).toString`2`
f=(x,o,y)=>+eval(`'0b'+(b(y)+b(x)).replace(/^1|${o=='~'?1:'(.)'}(?=.{16}(.)())|./g,'$2$1')`)

```

Test:

```
;[f(234,'¢',4321),f(2345,'~',7245)]=="16841865,37"

```

# Javascript ES6 (1 argument) ~~135~~ 133 bytes

```
b=x=>(65536|x).toString`2`
f=s=>([x,o,y]=s.split` `)|eval(`'0b'+(b(y)+b(x)).replace(/^1|${o=='~'?1:'(.)'}(?=.{16}(.)())|./g,'$2$1')`)

```

Test:

```
;[f('234 ¢ 4321'),f('2345 ~ 7245')]=="16841865,37"

```

PS: New line is counted as 1 byte as it can be replaced by `;`.
> 2 votes

# Answer
# Vyxal, 201 bitsv2, 25.125 bytes

```
⌈sṫ£⌊vΠ:ḣ∆Z$tJvf⌊÷¥\¢=[Y|Tİ]B

```

Try it Online!

Bitstring:

```
110010100100100000011011100010011001001100101100100000110010011100111001000101011101011101101110001000110011011101000000100101011000110100110001000010010001101001011101001011100110111111100100110010111

```

Possibly golfable?
> 2 votes

# Answer
# Mathematica, 155 bytes

```
f=IntegerDigits[#,2,16]&;
g=#~FromDigits~2&;
¢=g[f@#~Riffle~f@#2]&;
s=g@Cases[Thread@{f@#,f@#2},{x_,1}->x]&;
ToExpression@StringReplace[#,{" "->"~","~"->"s"}]&

```

Evaluates to an anonymous function taking the string as input. Line breaks added for clarity.

`f` and `g` convert to/from base 2. `Riffle` does exactly what *interleave* is supposed to. I wanted to use `Select` for *select* but `Cases` is better unfortunately. The last line is a bit of trickery; spaces are changed to `~` which is Mathematica's infix operator, then the string is eval'd.
> 0 votes

# Answer
# Go, 186 bytes

```
func c(a,b uint)(o uint){for i:=0;i<16;i++{o|=(a&1<<(2*i+1))|(b&1<<(2*i))
a>>=1
b>>=1}
return}
func s(a,b uint)(o uint){for i,j:=0,0;i<16;i++{if b&1>0{o|=a&1<<j;j++}
a>>=1
b>>=1}
return}

```

Attempt This Online!

`c` is `interleave`, and `s` is `select`.

## Explanations

### Interleave

```
func c(a,b uint)(o uint){       // init return value in `o` with zero value
for i:=0;i<16;i++{              // for each bit (in the uint16)...
o|=                             // OR to `o`...
   (a&1                         // the last bit of `a`
       <<                       // shifted left by
         (2*i+1))               // the current bit * 2 + 1
                 |              // OR-ed with
                  (b&1          // the last bit of `b`
                      <<        // shifted left by
                        (2*i))  // the current bit * 2
a>>=1;b>>=1}                    // discard the last bit of `a` and `b`
return}

```

### Select

```
func s(a,b uint)(o uint){ // init return value in `o` with zero value
for i,j:=0,0;i<16;i++{    // for each bit (in the uint16)...
if b&1==1{                // if the current bit in `b` is 1...
          o|=             // OR to `o`...
             a&1          // the last bit of `a`
                <<j       // shifted over by the number of 1s so far
                   ;j++}  // increment the number of 1s
a>>=1;b>>=1}              // discard last bit of `a` and `b`
return}

```
> 0 votes

---
Tags: code-golf
---


title: Perform Gray Addition

text:
# Question
Title: Perform Gray Addition
# Objective

Given two non-negative integers encoded in unbounded-length Gray code, add them and output the result, where the result is also encoded in Gray code.

# Gray code

There are many equivalent formulations of Gray code, but here's an intuitive one.

The Gray code encodes each non-negative integer as an infinite bit-string. Starting from encoding zero, as the enumeration goes, the least significant bit keeps cycling through `"0110"`. Each place of bit keeps cycling through what the previously significant bit cycles through, but doubled entry-wise. To summarize:

```
0th LSB: Cycles through "0110"
1st LSB: Cycles through "00111100"
2nd LSB: Cycles through "0000111111110000"
3rd LSB: Cycles through "00000000111111111111111100000000"
(And so on)

```

That gives the encodings of few non-negative integers as:

```
Integer = Gray code
("..." stands for infinitely many leading zeroes)
0 = "...00000"
1 = "...00001"
2 = "...00011"
3 = "...00010"
4 = "...00110"
5 = "...00111"
6 = "...00101"
7 = "...00100"
8 = "...01100"
9 = "...01101"

```

Note that, for each pair of integers differing by one, their Gray codes differ by only one bit.

# I/O format

Flexible. Standard loopholes apply.

# Examples

Here, inputs and outputs are Gray codes with their leading zeroes stripped off.

```
"" + "" = ""
"1" + "1" = "11"
"1" + "10" = "110"
"10" + "1" = "110"
"10" + "11" = "111"
"111" + "111" = "1111"

```

# Answer
> 5 votes
# Jelly, 9 bytes

```
^\€ḄSH^$B

```

Try it online!

A monadic link taking a pair of lists of binary digits as its argument and returning a list of binary digits. Expects the Gray coding with all leading zeros removed other than for zero itself; returns a Gray coded number in the same format.

## Explanation

```
^\€       | Reduce each by xor, collecting up intermediate results
   Ḅ      | Convert from binary
    S     | Sum
     H^$  | Xor with half
        B | Convert to binary digits

```

# Answer
> 3 votes
# JavaScript (Node.js), 41 bytes

```
a=>b=>(t=e(a)+e(b))^t/2
e=t=>t&&t^e(t>>1)

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 11 bytes

```
€ηOÉJCOD;^b

```

Port of *@NickKennedy*'s Jelly answer, so make sure to upvote that answer as well!

Input as a pair of lists of binary digits without leading 0s (where `0` could be either `[0]` or `[]`).

Try it online or verify all test cases.

**Explanation:**

```
€            # Map over each inner list of the (implicit) input-pair:
 η           #  Get its prefixes
  O          # Sum each inner prefix-list
   É         # Check for each sum whether it's odd
    J        # Join each inner list of binary digits together to a string
     C       # Convert each from a binary-string to a base-10 integer
      O      # Sum the pair together
       D;    # Push a copy of this sum, and halve it
         ^   # Bitwise-XOR the sum and halved sum together
             # (where both are treated as floored integers, ignoring any `.5` decimals)
          b  # Convert this from a base-10 integer to a binary-string
             # (which is output implicitly as result)

```

# Answer
> 3 votes
# Charcoal, 31 bytes

```
≔⍘ΣＥＥ²Ｓ↨²Ｅι﹪Σ…ι⊕μ²¦²θ⭆θ¬⁼ι§⁺0θκ

```

Try it online! Link is to verbose version of code. Uses bit strings for I/O. Explanation: Somewhat limited by the lack of a bitwise XOR function.

```
≔⍘ΣＥＥ²Ｓ↨²Ｅι﹪Σ…ι⊕μ²¦²θ

```

For each input, get all of its prefixes, take the digit sum modulo `2`, and interpret the results as base `2`. Then convert the sum back to base `2`.

```
⭆θ¬⁼ι§⁺0θκ

```

Compare each bit with the previous and output `0` if they the same and `1` if they differ.

---
Tags: code-golf
---


title: Is this relationship creepy?

text:
# Question
Title: Is this relationship creepy?
According to this XKCD comic, there is a formula to determine whether or not the age gap in a relationship is "creepy". This formula is defined as:

```
(Age/2) + 7

```

being the minimum age of people you can date.

Therefore a relationship is creepy if either of the people in said relationship are younger than the minimum age of the other.

Given the age of two people, can you output whether or not that relationship is creepy?

### Rules

1. Your program should take two integers as input, the age of both people in the relationship. These can be taken in any reasonable format.
2. Your program must then output a truthy or falsy value describiing whether or not the relationship is "creepy" (Truthy = Creepy).
3. Standard loopholes are not allowed.
4. This puzzle is Code Golf, so the answer with the shortest source code in bytes wins

### Test Cases

```
40, 40    - Not Creepy
18, 21    - Not Creepy
80, 32    - Creepy
15, 50    - Creepy
47, 10000 - Creepy
37, 38    - Not Creepy
22, 18    - Not Creepy

```

# Answer
# Jelly, 6 bytes

```
H+7>ṚṀ

```

Try it online!

Seemingly different algorithm than Comrade's.
> 6 votes

# Answer
# NAND gates, 551

Created with Logisim

Same principle as my other answer, but takes 2-byte signed inputs, so it can handle `47, 10000`. Works for ALL test cases!

This is not optimal for the given test cases, as 10000 can be expressed with only 15 of the 16 bits, but it works for any ages in the range \[-32768, 32768). Note that any negative age will return `1`.

Inputs on left (no particular order, 1-bit on top). Output in lower right.
> 23 votes

# Answer
# Python 3, 26 bytes

```
lambda x:max(x)/2+7>min(x)

```

Try it online!
The input is a list with both ages
> 17 votes

# Answer
# NAND gates, 274 262

Original:

Better:  Created with Logisim

This takes two inputs on the left as 1-byte signed integers, with the 1-bit at the top. Output is in the lower left; the truthy and falsey here should be obvious.

Works for all test cases except `47, 10000`, so I guess this is technically not a valid answer. However, the oldest person on (reliable) record was 122, so 8 bits (max 127) will work for any scenario ever possible to this point. I'll post a new answer (or should I edit this one?) when I finish the 16-bit version.

16-bit version is done!

You'll notice some vertical sections of the circuit. The first one (from the left) determines which input is greater. The next two are multiplexers, sorting the inputs. I then add `11111001` (-7) to the lesser in the fourth section, and I conclude by comparing twice this to the greater input. If it is less, the relationship is creepy. Since I shift the bits to double, I must take into account the unused bit of `lesser-7`. If this is a `1`, then `lesser-7` is negative, and the younger of the two is no older than six. Creepy. I finish with an OR gate, so if either creepiness test returns `1`, the entire circuit does.

If you look closely, you'll see that I used seven one constants (hardcoding the `11111011` and the trailing `0`). I did this because Logisim requires at least one value going in for a logic gate to produce an output. However, each time a constant is used, two NAND gates ensure a `1` value regardless of the constant.

-12 gates thanks to me!
> 16 votes

# Answer
# 05AB1E, ~~8~~ 6 bytes

```
;7+R‹Z

```

Try it online! or Try all test

```
         # Implicit Input: an array of the ages
;        # Divide both ages by 2
 7+      # Add 7 to both ages
   R     # Reverse the order of the ages
         #    this makes the "minimum age" line up with the partner's actual age
    ‹    # Check for less than the input (vectorized)
     Z   # Push largest value in the list

```
> 15 votes

# Answer
# C#, 22 bytes

```
n=>m=>n<m/2+7|m<n/2+7;

```
> 9 votes

# Answer
# C, 29 bytes

```
#define f(a,b)a/2+7>b|b/2+7>a

```

How it works:

* `#define f(a,b)` defines a macro function `f` that takes two untyped arguments.
* `a/2+7>b` checks if the first age divided by two plus seven is larger than the second age.
* `b/2+7>a` checks if the second age divided by two plus seven is larger than the first age.
* If either of the above values are true, return 1 (creepy). Otherwise, return 0 (not creepy).

Try it online!
> 8 votes

# Answer
# JavaScript (ES6), 21 bytes

```
a=>b=>a<b/2+7|b<a/2+7

```

Returns 0 for not creepy, 1 for creepy.

```
f=a=>b=>a<b/2+7|b<a/2+7

console.log(f(40)(40));
console.log(f(18)(21));
console.log(f(80)(32));
console.log(f(15)(50));
console.log(f(47)(10000));
console.log(f(37)(38));
console.log(f(22)(18));
```
> 7 votes

# Answer
# , ~~26~~ 25 bytes

*-1 byte thanks to @djhurio*

```
any(rev(a<-scan())<a/2+7)

```

Try it online!
> 7 votes

# Answer
# TI-Basic, ~~20~~ ~~10~~ 9 bytes

```
max(2Ans<14+max(Ans

```

-10 bytes by using a list and part of Timtech's suggestion

-1 byte using lirtosiast's suggestion

Takes in a list of two ages, "{40,42}:prgmNAME"

Returns 1 for 'creepy' and 0 for 'not creepy'.
> 5 votes

# Answer
# Python 3, ~~74~~ 45 bytes

First Code Golf, probably terrible.

29 byte reduction by @Phoenix

```
lambda a,b:0 if(a/2)+7>b or(b/2)+7>a else 1

```
> 5 votes

# Answer
## Retina, 20 bytes

```
O`.+
^1{7}(1+)¶1\1\1

```

Try it online!

Input is in unary with a linefeed between the two numbers. Output is `0` (not creepy) or `1` (creepy).

### Explanation

```
O`.+

```

Sort the two numbers, so we know that the larger one is second.

```
^1{7}(1+)¶1\1\1

```

Call the smaller age `a` and the larger age `b`. We first capture `a-7` in group `1`. Then we try to match `2*(a-7)+1` in `b`, which means `b >= 2*(a-7)+1` or `b >= 2*(a-7)` or `b/2+7 > a` which is the criterion for a creepy relationship.
> 5 votes

# Answer
# GNU APL 1.2, 23 bytes

Defines a function that takes two arguments and prints 1 if creepy, 0 if not.

```
∇A f B
(A⌊B)<7+.5×A⌈B
∇

```

### Explanation

begins and ends the function
`A f B` is the function header; function is named `f` and takes two arguments, `A` and `B` (functions in APL can be monadic - taking one argument - or dyadic - taking two arguments)
`A⌊B` is `min(A,B)` and `A⌈B` is `max(A,B)`
APL is evaluated right-to-left, so parentheses are needed to ensure proper precedence

The other operators are self explanatory.

Code might be golf-able, I'm still new to code-golf.
> 4 votes

# Answer
# JavaScript (ES6), 27 bytes

```
f=a=>b=>b>a?f(b)(a):b>a/2+7

```

No currying (call like `f(a,b)` instead of `f(a)(b)`)

```
f=(a,b)=>b>a?f(b,a):b>a/2+7

```

If `b > a`, swap parameters and retry. Otherwise, check. Currying doesn't save any bytes because of the recursive call.

```
f=a=>b=>b>a?f(b)(a):b>a/2+7

console.log(f(18)(22))
console.log(f(22)(18))
console.log(f(18)(21))
```
> 3 votes

# Answer
# Excel, ~~26~~ 24 Bytes

Cell formula that takes input as numbers from cell range `A1:B1` and output a boolean value representing creepiness to the formula cell

```
=OR(A1/2+7>B1,B1/2+7>A1)

```

**Old Version, 26 Bytes**

```
=MAX(A1:B1)/2+7>MIN(A1:B1)

```
> 3 votes

# Answer
# Java, 21 bytes

```
a->b->a/2+7>b|b/2+7>a

```

Absolutely not original.

## Testing

Try it online!

```
import java.util.function.*;

public class Pcg122520 {
  static IntFunction<IntPredicate> f = a->b->a/2+7>b|b/2+7>a;
  public static void main(String[] args) {
    int[][] tests = {
      {40, 40},
      {18, 21},
      {80, 32},
      {15, 50},
      {47, 10000},
      {37, 38},
      {22, 18}
    };
    for (int[] test: tests) {
      System.out.printf("%d, %d - %s%n", test[0], test[1], f.apply(test[0]).test(test[1]) ? "Creepy" : "Not creepy");
    }
  }
}

```
> 3 votes

# Answer
# Python 3, 31 bytes

`lambda a,b:abs(a-b)>min(a,b)-14`

Not much shorter than the other python submissions, but I found a slightly different way to check for creepiness. I noticed that the acceptable difference between ages is equal to min - 14. This follows from algebraically rearranging the formula.

```
min = (max/2) + 7
min - 7 = max/2
2*min - 14 = max

dif = max - min
max = dif + min

2*min - 14 = dif + min
min - 14 = dif

```

This let me solve without needing two constants, and also without needing to use both max and min, instead using abs(a-b). From a golfing perspective I only got one byte less than @nocturama's solution, but I used a slightly different formula to do it.
> 3 votes

# Answer
# Jq 1.5, 11 bytes

```
max/2+7>min

```

Try it online!
> 3 votes

# Answer
# Mathics, 16 bytes

```
Max@#/2+7<Min@#&

```

Try it online!

-2 bytes thanks to @GregMartin

True for not creepy, false for creepy.

```
            (* Argument: A list of integers     *)
Max@#       (* The maximum of the input         *)
 /2+7       (* Divided by 2, plus 7             *)
  <         (* Is less than?                    *)
   Min@#    (* The minimum of the input         *)
    &       (* Anonymous function               *)

```
> 2 votes

# Answer
# TI-Basic, ~~10~~ ~~9~~ 10 bytes

```
2min(Ans)-14≤max(Ans

```

List input from `Ans`, outputs `1` if "creepy" or `0` otherwise.
> 2 votes

# Answer
## SAS, 77 bytes

```
%macro t(a,b);%put%eval(%sysfunc(max(&a,&b))/2+7>%sysfunc(min(&a,&b)));%mend;

```
> 2 votes

# Answer
## Batch, 50 bytes

```
@if %1 gtr %2 %0 %2 %1
@cmd/cset/a"%1*2-14-%2>>31

```

Outputs `-1` for creepy, `0` for not creepy.

Since Batch only has integer arithmetic I have to work in units of half years.
> 2 votes

# Answer
# Crystal, 44  27 bytes

-17 from looking at daniero's answer in Ruby.

```
def a(a)7+a.max/2>a.min end

```

Try it online!
> 2 votes

# Answer
# Perl 6, 15 bytes

```
{.max/2+7>.min}

```

Try it

## Expanded

```
{ # bare block lambda with implicit parameter ｢$_｣
  # (input is a List)

  .max / 2 + 7
  >
  .min
}

```
> 2 votes

# Answer
# Python 3 - ~~32~~ 27 bytes

Unable to comment, but I got a slightly shorter answer than the other Python 3 solution:

```
lambda *a:min(a)<max(a)/2+7

```

-5 thanks to @Cyoce!
> 2 votes

# Answer
# **FORTH 96 Bytes**

```
: C 2DUP > -1 = IF SWAP THEN 2 /  7 +  SWAP > -1 = IF ."  CREEPY " ELSE ." NOT CREEPY " THEN ;

```

**Output:**

```
40 40 c NOT CREEPY  ok
18 21 c
18 21 c NOT CREEPY  ok
80 32 c
80 32 c  CREEPY  ok
15 50 c
15 50 c  CREEPY  ok
47 10000 c
47 10000 c  CREEPY  ok
37 38 c
37 38 c NOT CREEPY  ok
22 18 c
22 18 c NOT CREEPY  ok

```
> 2 votes

# Answer
# Thunno 2 `G`, 5 bytes

```
½7+r<

```

Attempt This Online!

Port of Riley's 05AB1E answer.

#### Explanation

```
½7+r<  # Implicit input
½      # Halve each value
 7+    # Add seven to each
   r   # Reverse the list
    <  # Vectorised less than
       # Get the maximum
       # Implicit output

```
> 2 votes

# Answer
# K (oK), 16 bytes

```
{(x&y)<7+-2!x|y}

```

Try it online!
> 2 votes

# Answer
# Nekomata \+ `-e`, 5 bytes

```
Ṁä7+≥

```

Attempt This Online!

Returns `True` for not creepy, `False` for creepy.

```
Ṁ        Get the maximum of the input
 ä       Divide it by 2
  7+     Add 7
    ≥    Is every element of the input greater than or equal to that?

```
> 2 votes

# Answer
# Uiua, 8 bytes

```
<+7÷2⊃↥↧

```

Try it online!

```
<+7÷2⊃↥↧    input: two ages as two separate stack items
     ⊃↥↧    push max and min of the two ages
 +7÷2       max / 2 + 7
<           is greater than min?

```
> 2 votes

# Answer
# Fourier, 37 bytes

```
oI~AI~B>A{1}{A~SA~BS~B}A/2+7>B{1}{@o}

```

**Try it on FourIDE!**

Takes two numbers as input. Will golf later.
> 1 votes

# Answer
# Japt, 11 bytes

Returns `true` for "creepy" and `false` for not.

```
wV /2+7>UmV

```

Try it online

---

## Explanation

```
      :Implicit input of first integer U
wV    :Get the maximum of U and the second integer V
/2+7  :Divide by 2 & add 7
>     :Check if the result is greater than...
UmV   :the minimum of the two integers.

```
> 1 votes

# Answer
# PHP, 29 Bytes

prints 1 for creepy, nothing for Not creepy

```
<?=max($_GET)/2+7>min($_GET);

```

Try it online!
> 1 votes

# Answer
# J, 10 bytes

```
<.<7+2%~>.

```

Outputs `1` for not creepy, `0` for creepy

### Explanation

```
<.          NB. the minimum
  >         NB. is greater than
    7+2%~>. NB. half the maximum + 7

```
> 1 votes

# Answer
# J-uby, 25 bytes

```
:>%[:min,:max|~:/&2|:+&7]

```

Call like `f^[80,32]`. Gives `true` for not creepy, `false` for creepy.

### Explanation

```
    :min                  # the minimum
:>%[    ,               ] # is greater than
         :max|            # the maximum...
              ~:/&2|        # over two...
                    :+&7    # plus 7

```
> 1 votes

# Answer
# AWK, 26 bytes

```
{$0=$1/2+7>$2||$2/2+7>$1}1

```

Try it online!

Outputs 1 for "Creepy" and 0 for "Not Creepy". Could save 3 bytes if no-output could be consider a falsy value, via:

```
$0=$1/2+7>$2||$2/2+7>$1

```
> 1 votes

# Answer
# Swift - 33 bytes

```
var f={max($0,$1)/2+7>min($0,$1)}

```

A `lambda`-function's equivalent in Swift, but unfortunately cannot take an array :((. Outputs `true` for truthy and `false` for falsy. If one must not count the declaration of the function (Python doesn't) the byte count would be 27. **Usage:** `print(f(age1,age2))`

**Check it out!**
> 1 votes

# Answer
# Röda, 16 bytes

```
{sort|[_<_/2+7]}

```

Try it online!

This is an anonymous function that takes input as two literals (not an array) from the input stream.

### Explanation

```
{sort|[_<_/2+7]}                 Anonymous function
 sort                            Sorts the numbers in the input stream
     |[       ]                  And push
       _<                        whether the smaller value  is less than
         _/2+7                   the greater value / 2 + 7

```
> 1 votes

# Answer
# Ruby, 21 bytes

```
->*x{x.max/2+7>x.min}

```

Yup.

```
f = ->*x{x.max/2+7>x.min}
f[18,21]  #=> false
f[80,32]  #=> true

```
> 1 votes

# Answer
# Python 3, 115 bytes

Edit : Bugfix according to @Alexx Roche

```
a=int(input())
b=int(input())
c=a
d=b
if b < a:
 c=b
 d=a
if not c < d/2.0+7:
 print("Not ",end='')
print("Creepy")

```

Try it online!
> 1 votes

# Answer
# z-shell (zsh), 38 bytes

```
n=(${(no)@});echo $((n[2]/2+7-n[1]>0))

```

`${(no)@}` is a numeric sort of the argument array
> 1 votes

# Answer
# Perl 5, 34 + 2 (-ap) = 36 bytes

```
$_=$F[0]/2+7>$F[1]|$F[1]/2+7>$F[0]

```

Try it online!
> 1 votes

# Answer
## BASH, 135 bytes

I dabbled in this area a few years ago. I think that Greg Martin's point should factor in, and wonder how he picked 13 and not, (for example) 12 as 13 is the upper bound of x \< x/2+7. Leo what is the test cases for \[14,21\], \[15,15\] and \[16,21\]?

```
#!/bin/bash
[ $1 -lt $2 ]&&./$0 $2 $1&&exit
[ $(($1+$2)) -ge $(((($1-$2)/2)**2)) ]&&[ $((((($2*10)+5)/19)+7)) -lt $2 ]&&echo -n 'Not ';echo Creepy

```

(could save bytes by using ✗ for "Creepy" and ✓ for "Not Creepy" or exit codes)
> 1 votes

# Answer
# ARBLE, 25 bytes

```
lt(min(a,b),max(a,b)/2+7)

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 14 Bytes

```
:{:{(?r2,7+)n;

```

Pretty simple, but I don't see any obvious ways to cut down on characters.

### Explanation:

```
               | Assume input is on the stack
:{:{           | Duplicate items on the stack (we pop them for inequality testing)
    (?r        | Sort them, so that the larger is on top of the stack
       2,7+    | Divide top item by 2 and add 7
           )n; | Print the truthy value of younger > (older/2) + 7

```

Prints 1 for non-creepy relationships, 0 for creepy ones
> 1 votes

# Answer
# Add++, 8 bytes

```
L,#2/7+>

```

Try it online!

2 bytes off Jelly just feels weird

## How it works

```
L,   - Lambda function
     - Example arguments: [15 50]
  #  - Sort;      STACK = [15 50]
  2/ - Halve;     STACK = [15 25]
  7+ - Add 7;     STACK = [15 32]
  >  - Greater;   STACK = [1]

```
> 1 votes

# Answer
# Befunge, 28 bytes

```
&:&:00p`00g\> #0 #\_\7-2*`.@

```

Try It Online

Since Befunge uses integer math, I flipped it and added 7 to the minimum then multiplied by 2. 1 = Creepy, 0 = Not creepy
> 1 votes

# Answer
# Pyt, 7 bytes

```
Đ↔₂7+≥Π

```

Try it online!

Takes input as an array of integers

Explanation:

```
       Implicit input [x,y]
Đ      Duplicate the array  [x,y],[x,y]
↔      Flip the top array   [x,y],[y,x]
₂      Divide the top of the stack by 2    [x,y],[y/2,x/2]
7+     Add 7 to each element of the top of the stack    [x,y],[y/2+7,x/2+7]
≥      Is the second on the stack greater than or equal to the top elementwise [x>=y/2+7,y>=x/2+7]
Π      Take the product (auto-casts to integers)
       Implicit print

```
> 1 votes

# Answer
# Stax, 6 bytes

```
Æ╠àá;╚

```

Run and debug online

Here's the ungolfed ascii representation of the same program.

```
oE  sort inputs and push each to stack, now the larger age is on top of the stack
^h  increment larger age and integer divide by 2
7+  add 7
<   is the first number less than the second?

```

Run this one
> 1 votes

# Answer
# Japt, 10 bytes

```
n v <U/2+7

```

Try it online!

Takes a 2-element array as input.

### How it works

```
Un v <U/2+7

Un  Sort the input
v   Pop the first element (smaller one)
<   less than...
U/2+7  Implicitly cast the remaining 1-length array to number (larger one)
       then calculate /2+7

```
> 1 votes

# Answer
# Vyxal, 8 bytes

```
sh½7+⁰t≥

```

Try it Online!

Inputs are a 2 element list.
> 1 votes

# Answer
# Husk, 8 bytes

```
F·>o+7½O

```

Takes input as a 2-element list

```
F·>o+7½O
       O  sort
F         fold / apply following binary function to the elements
 · o+7½   apply this to the second argument
      ½   halve
   o+7    then add 7
  >       compare

```

Try it online!
> 1 votes

# Answer
# Arturo, 20 bytes

```
$=>[>7+0.5*do sort&]

```

Try it!

```
$=>[       ; a function where input is assigned to &
    sort&  ; sort input
    do     ; dump both ages from input list onto the stack
    0.5*   ; multiply TOS (the higher age) by 0.5
    +7     ; add 7 to TOS
    >      ; is NOS greater than TOS?
]          ; end function

```
> 1 votes

# Answer
# PowerShell, 60 bytes

```
$c={param($a,$b)[math]::max($a,$b)/2+7-gt[math]::min($a,$b)}

```

Try it online!

No doubt could be improved upon!
> 1 votes

# Answer
# PowerShell, 42 bytes

```
    $c={param($a,$b)$a/2+7-gt$b-or$b/2+7-gt$a}

```

Rather than using `[math]::min` and `::max`, I'm trying both `$a` vs `$b` and `$b` vs `$a` then -or the result.
> 1 votes

# Answer
# Excel VBA, 28 Bytes

Anonymous immediate window function that tTakes age inputs from cells `[A1]` and `[B1]` as expected type `Integer` and outputs a `Boolean` value representing creepyness to the VBE immediate window

```
?[B1]/2+7>[A1]|[A1]/2+7>[B1]

```
> 0 votes

# Answer
# shortC, 21 bytes

```
D(a,b)a/2+7<b|b/2+7<a

```
> 0 votes

# Answer
## QBIC, 30 bytes

```
~:>:|c=a┘d=b\c=b┘d=a]?d>=c/2+7

```

Explanation

```
           First, we mustsort the input parameters
~:>:       IF a (from cmd line) > b (from cmd line)
|c=a┘d=b   THEN set c and d
\c=b┘d=a   ELSE set c and d in the other way
]          END IF
?d>=c/2+7  PRINT -1 if d is higher than c's lower bound, 0 for creepy

```
> 0 votes

# Answer
# Pyth, ~~17~~ ~~16~~ ~~13~~ 12 bytes

```
>+7/.)JSQ2hJ

```

Takes a list. Outputs True for creepy, False for not creepy.

Try it!

### explanation

```
>+7/.)JSQ2hJ
      JSQ        # Sort the input list (Q) and store the result in J
    .)           # pop the last/largest element from J (lets call it x)
          hJ     # the first/only element of J (lets call it y)
>+7/     2       # 7 + x/2 > y

```

## old approach, 13 bytes

```
s.b<Y+7/N2_QQ

```

Takes a list. Outputs 1 for creepy, 0 for not-creepy.

Try it!

### explanation

```
s.b<Y+7/N2_QQ
 .b       _QQ        # map over the list and it's reversal (variables: Y,N)
   <Y+7/N2           # Y < N/2 + 7
s                    # sum: False + False = 0; True + False = 1 (; True + True = 2 can never occur, because one of the ages is always larger or equal)

```
> 0 votes

# Answer
# CJam, 10 bytes

```
q~$~2d/7+<

```

Takes input as a list.

Try it online!

### Explanation

```
q~          e# Read and eval input.
  $         e# Sort the list.
   ~        e# Dump the list on the stack.
    2d/7+   e# Apply age/2+7 to the greater age.
         <  e# Check if the other age is less than that.

```
> 0 votes

# Answer
# Actually, 12 bytes

```
;RZ⌠i½7+≤⌡Mπ

```

Try it online, or run all test cases!

Outputs `1` if it's not creepy, and `0` if it is.

Explanation:

```
;RZ⌠i½7+≤⌡Mπ  implicit input: [a, b]
;RZ           zip input with its reverse ([[a,b], [b,a]])
   ⌠i½7+≤⌡M   for each pair:
    i           flatten
     ½7+        half of one plus 7
        ≤       is less than or equal to the other?
           π  product (acts as a boolean AND)

```
> 0 votes

# Answer
# q/kdb+, ~~17~~ 16 bytes

**Solution:**

```
{(x&y)<7+.5*x|y}

```

Try it online! (**oK** rather than **q/kdb+**)

**Examples:**

```
q){(x&y)<7+.5*x|y}[22;18]
0b
q){(x&y)<7+.5*x|y}[22;17]
1b

```

**Explanation:**

Outputs creepy as boolean 1b (true, creepy) or 0b (false, not creepy)

```
{(x&y)<7+.5*x|y} / solution
{              } / lambda function with implicit parameters x and y
            x|y  / max of x and y
         .5*     / multiply by 0.5 (aka divide by 2)
       7+        / add 7
      <          / less than?
 (x&y)           / min of x and y

```

**Notes:**

Polyglot in:

* q/kdb+
* K
* oK (see TIO link)
> 0 votes

# Answer
# Alice, ~~21~~ 18 bytes

```
/o
\i@/sh2:-6-.H+n

```

Try it online!

-3 bytes thanks to Martin Ender.

Input is in any format that includes exactly two integers. Output is `1` if creepy and `0` if not creepy.

### Explanation

```
ish2:-6-.H+no

i                Input numbers
 s               Sort the two ages
  h2:            Divide larger age by 2 rounded up
     -           Subtract from smaller age
      6-         Subtract 6
        .H+      Determine whether result is negative
           n     Push 1 if was negative, 0 otherwise
            o    Output

```
> 0 votes

# Answer
# tcl, 59

```
scan $argv %d\ %d x y
puts [expr max($x,$y)/2+7>min($x,$y)]

```

demo

To try, type

`tclsh main.tcl Age1 Age2`

on the green area.
> 0 votes

# Answer
# Tcl, 44

I was losing to answers implementing it as a function, so I had to make mine into a function also:

```
proc c x\ y {expr max($x,$y)/2+7>min($x,$y)}

```

demo — You just have to press on the "Execute" button and see the 0 and 1 digits on the green area matching the question's creepiness values.
> 0 votes

# Answer
# Wolfram Language, 16 bytes

```
Min@#<Max@#/2+7&

```

Takes input as a list.
> 0 votes

# Answer
# S.I.L.O.S, 64 bytes

```
readIO
j=i
readIO
x=i/2+7-j
y=j/2+7-i
if x c
if y c
print k
lblc

```

Try it online!

It prints out the letter "k" if the relationship is ok, otherwise it prints out nothing. I couldn't figure out any mathemagical way with standard mathematical operators to do an if x\>0 pr y\>0 to save bytes.

---

Alternatively, we can create an "or gate" by exploiting the fact that x^.5 will error out if the number is negative.This removes the need for a conditional, but lengthens our code. This version outputs 0 for creepy and some positive number for not creepy.

# S.I.L.O.S, 67 bytes

```
readIO
j=i
readIO
x=0-i/2-7+j
y=0-j/2-7+i
a=x^.5+y^.5+1
printInt a

```

Try it online!
> 0 votes

# Answer
# MATL, 10 bytes

```
tEP-X>-14>

```

My first ever solution. :) Try it online!

Explainer:

```
t    % push the input array [a b] (possibly redundant)
EP   % push the flipped(P)+doubled(E) array [2b 2a]
-    % subtract to get [a-2b b-2a]
X>   % take the maximum
-14> % if either exceeds -14, then it is creepy af bro!

```
> 0 votes

# Answer
# Ly, 8 bytes

```
a2/7+Lfp

```

Try it online!

Explanation:

```
a2/7+Lfp

a        # sort (implicit input)
 2/7+    # halve and add 7
     L   # less than?
      fp # pop value, leaving just the result
         # implicit output

```
> 0 votes

# Answer
## C, C++, Java, C#, D, 56 bytes

-1 byte thanks to Zacharý

```
int c(int a,int b){return((a>b?a:b)/2+7)>(a>b?b:a)?1:0;}

```

**C, C++, D optimization : 52 bytes**

```
int c(int a,int b){return((a>b?a:b)/2+7)>(a>b?b:a);}

```
* C++ convert bool object to int implicitly ( false = 0, true = 1 )
* In C, booleans are represented by integers values, where 0 is false, and 1 is true.
* ~~I barely know how to print something in D, so i won't comment about boolean to int conversions in this language~~ Zacharý just informed me that D bool to int conversion works exactly like in C/C++
* Unfortunately, Java and C# can't convert an integer to a boolean, so we need to use ternary operator.
> 0 votes

# Answer
# Dyalog APL, 11 bytes

```
⌊<(⌊7+.5×⌈)

```

Try it online!
> 0 votes

# Answer
## Sakura, 7 bytes

```
>Ƣ+ħ⓪7ƣ

```

Takes input as an array and outputs -1 if creepy and 0 otherwise.

Explanation:

```
>                     >
 Ƣ      max(         )
  +                +
   ħ             /2
    ⓪       input
     7              7
      ƣ                min(     )
                           input

```
> 0 votes

# Answer
# x86-64 machine code, 16 bytes

Takes the ages in `edi, esi`, returns 0 or 1 in `eax`, following x86-64 SysV ABI for `bool creepy(int, int);`.

```
39 f7 7d 02 87 fe 8d 44  36 f2 29 f8 c1 e8 1f c3

```

Assembly source follows. We test `2*young - 14 - old < 0`.

```
creepy:
        cmp     edi, esi
        jge     ready
        xchg    edi, esi
ready:
        ;;  higher age now in edi
        lea     eax, [rsi*2-14]
        ;; eax = highest age the younger person can date
        sub     eax, edi
        ;; if result is negative, then creepy
        shr     eax, 31
        ret

```
> 0 votes

# Answer
# ARM64 machine code, 24 bytes

Takes the ages in `w0, w1`, returns 0 or 1 in `w0`, following normal ARM64 calling conventions for `bool creepy(int, int);`. (You could handle 64-bit ages by replacing all `w` with `x` registers, with no increase in size.)

```
4b010402
4b000423
3100385f
3a4ed860
1a9fd7e0
d65f03c0

```

Assembly source follows. We test `x-2*y > -14 || y-2*x > -14`.

```
creepy:
    sub     w2, w0, w1, lsl #1
    sub     w3, w1, w0, lsl #1
    cmn     w2, #14
    ccmn    w3, #14, #0, le     // #0 = none of NZCV, makes gt true
    cset    w0, gt
    ret

```
> 0 votes

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


title: Sort useless characters

text:
# Question
Title: Sort useless characters
This challenge is inspired by this very nice answer by TidB.

---

In TidB's answer, every eight character is in the correct order: `gnilwoB edoC` (`Code Bowling` backwards). The other strings however ~~are~~ were in a strange, random order.

Your challenge is to fix this.

Take a (non-empty) string and a positive integer `n` as input. The string will contain ASCII characters in the range: 32-126 (space to tilde).

You must sort the string in **ascending** order (seen from the left, based on the ASCII-code value), but skip every `n`th character, starting from the end of the string. As an example, let's take the string `abcdABC123` as input, and `n=4`, then we'll get:

```
abcdABC123   <- Input string. (n=4)
_b___B___3   <- These will not be sorted (every 4th starting from the end)
1_2AC_acd_   <- The remaining characters, sorted
1b2ACBacd3   <- The final string (the output)

```

Another example:

```
9876543210   <- Input string (n=2)
_8_6_4_2_0   <- These will not be sorted
1_3_5_7_9_   <- The remaining characters, sorted
1836547290   <- The final string (the output)

```

The input string can be taken on an optional format (string, list of characters, list of single character strings ...). The input integer can also be taken on an optional format.

**Test cases:**

The format will be `n=__`, followed by the input string on the next line. The output is on the line below.

```
n=1   (All elements will stay in place)
nafgaksa1252#"%#
nafgaksa1252#"%#

n=214  (The last character will stay in place. All other are sorted.
&/lpfAVD
&/AVflpD

n=8
g7L9T E^n I{><#ki XSj!uhl y= N+|wA}Y~Gm&o?'cZPD2Ba,RFJs% V5U.W;1e  0_zM/d$bH`@vKoQ 43Oq*C
g       n !#$%&'i*+,./01l234579;w<=>?@ADoEFGHIJKBLMNOPQR STUVWXYeZ^_`abcdhjkmqsuovyz{|}~C

```

# Answer
> 8 votes
# MATL, ~~15~~ 14 bytes

```
ttfiX\qgP)S5M(

```

Inputs are a string enclosed in single quotes and a number. Single-quote symbols in the string should be escaped by duplicating (as in MATLAB and Octave).

Try it online! Or verify all test cases.

### Explanation

Consider inputs `'abcdABC123'` and `4`.

```
tt     % Implicitly input string. Duplicate twice
       % STACK: 'abcdABC123', 'abcdABC123', 'abcdABC123'
f      % Find: indices of nonzero elements: gives [1 2 ... n] where n is input length
       % STACK: 'abcdABC123', 'abcdABC123', [1 2 3 4 5 6 7 8 9 10]
i      % Input n
       % STACK: 'abcdABC123', 'abcdABC123', [1 2 3 4 5 6 7 8 9 10], 4
X\     % 1-based modulo
       % STACK: 'abcdABC123', 'abcdABC123', [1 2 3 4 1 2 3 4 1 2 3 4]
qg     % Subtract 1, convert to logical: gives true (1) for 1, false (0) otherwise
       % STACK: 'abcdABC123', 'abcdABC123', [0 1 1 1 0 1 1 1 0 1]
P      % Flip
       % STACK: 'abcdABC123', 'abcdABC123', [1 0 1 1 1 0 1 1 1 0]
)      % Use as logical index into the string
       % STACK: 'abcdABC123', 'acdAC12'
S      % Sort
       % STACK: 'abcdABC123', '12ACacd'
5M     % Push logical index again
       % STACK: 'abcdABC123', '12ACacd', [1 0 1 1 1 0 1 1 1 0]
(      % Write into original string as specified by the index. Implicitly display
       % STACK: 1b2ACBacd3

```

1-based modulo means that `mod([1 2 3 4 5], 3)` gives `[1 2 3 1 2]` instead of the usual (0-based) `[1 2 0 1 2]`. This is needed here to handle the case `n=1` adequately.

# Answer
> 6 votes
# Octave, ~~65~~ 54 bytes

```
function s=f(s,n)
l=~~s;l(end:-n:1)=0;s(l)=sort(s(l));

```

Try it online!

Uses logical indexing to make an array of 'fixed' and 'sorted' characters. Explanation:

```
function s=f(s,n) % Create a function, taking a string `s` and the number `n`; the output is also named `s`.
l=~~s;             % Create logical array with the same size of the input string
                  %    [equivalent to much more verbose true(size(s))].
l(end:-n:1)=0;    % Set the 'fixed' character positions. MATLAB/Octave automatically produces
                  %    the correct result even if n is larger than the string length.
s(l)=sort(s(l)) % Select the elements from `s` where `l` is true. Sort, and store in the corresponding positions in `s`.

```

The way I created `l` requires that `s` is nonzero, which I think is a reasonable requirement, as many languages use `\0` as an end-of-string delimiter.

# Answer
> 6 votes
# PHP, 101 bytes

negative string indexes (PHP 7.1) save 21 bytes - and possibly the day:

```
for([,$s,$n]=$argv;a&$c=$s[$i-=1];)$i%$n+1?$a[]=$c:0;for(sort($a);++$i;)echo$i%$n+1?$a[+$k++]:$s[$i];

```

Run with `php -nr '<code>' '<string>' <N>`.

**breakdown**

```
for([,$s,$n]=$argv;     # import command line arguments to $s and $n
    a&$c=$s[$i-=1];)    # loop backward through string
    $i%$n+1?$a[]=$c:0;      # if index is not n-th, copy character to array
for(sort($a);           # sort array
    ++$i;)              # loop forward through string:
    echo$i%$n+1             # if index is not n-th
        ?$a[+$k++]              # print character from array
        :$s[$i]                 # else print character from string
    ;

```

# Answer
> 6 votes
# Python 2, 191 bytes

Yeah, I'm sure this is a terrible solution.

```
n,s=input()
s=s[::-1]
R=range(len(s)/n+1)
J=''.join
k=s[::n]
t=J(sorted(J(s[i*n+1:i*n+n]for i in R)))
n-=1
print J(j[::-1]for i in zip(k,[t[::-1][i*n:i*n+n][::-1]for i in R])for j in i)[::-1]

```

**Try it online**

I'm not going to bother explaining it. It was alright until I realized that it needs to be indexed from the end. Now it's a monster. At this point, I'm just glad it works.

# Answer
> 5 votes
## JavaScript (ES6), ~~100~~ 93 bytes

Takes input in currying syntax `(s)(n)`.

```
s=>n=>s.replace(/./g,(c,i)=>(F=_=>(s.length-++i)%n)()?[...s].filter(F,i=0).sort()[j++]:c,j=0)

```

### Formatted and commented

```
s => n => s.replace(        // given a string s and an integer n
  /./g,                     // for each character c of s
  (c, i) => (               // at position i:
    F = _ =>                //   F = function that tests whether the
      (s.length - ++i) % n  //       character at position i is non-static
  )()                       //   call F() on the current position
  ?                         //   if the current character is non-static:
    [...s].filter(F, i = 0) //     get the list of non-static characters
      F, i = 0              //     by filtering all characters in s with F()
    )                       //
    .sort()[j++]            //     sort them and pick the next occurrence
  :                         //   else:
    c,                      //     let c unchanged
  j = 0                     //   initialize j = non-static character pointer
)                           //

```

### Test cases

```
let f =

s=>n=>s.replace(/./g,(c,i)=>(F=_=>(s.length-++i)%n)()?[...s].filter(F,i=0).sort()[j++]:c,j=0)

console.log(f("abcdABC123")(4))
console.log(f('nafgaksa1252#"%#')(1))
console.log(f('&/lpfAVD')(214))
console.log(f("g7L9T E^n I{><#ki XSj!uhl y= N+|wA}Y~Gm&o?'cZPD2Ba,RFJs% V5U.W;1e  0_zM/d$bH`@vKoQ 43Oq*C")(8))
```

# Answer
> 3 votes
# Perl 5 `-lF`, 78+3 = 81 bytes

```
$i=<>;map{(@F-++$c)%$i&&((push@b,$_),$_='')}@F;say map/./?$_:(sort@b)[$g++],@F

```

Try it online!

# Answer
> 2 votes
# Jelly, ~~14~~  13 bytes

```
FṢṁ
ṚsṚµḢ€ż@Ç

```

Full program that prints the string to STD out\*.

**Try it online!**

### How?

```
ṚsṚµḢ€ż@Ç - Main link: string s, non-negative number n
Ṛ         - reverse s
 s        - split into chunks of size n
  Ṛ       - reverse the resulting list
   µ      - monadic chain separation (call that list x)
    Ḣ€    - head €ach - yield a list of the first entries of each of x and modify x
        Ç - call the last link (1) as a monad - get the sorted and re-split list
      ż@  - zip together (with reversed @rguments)

FṢṁ - link 1, sort and reshape like self: list of lists
F   - flatten into a single list
 Ṣ  - sort
  ṁ - mould the result like the input

```

*~~I can't help but think~~ there is a way to use the fact that  modifies its input*

* for a function one would want to flatten the output into a single list with `F`.
For example an input of `"abcdABC123"`, `4` yields:
`[[['1'],['b']],[['2','A','C'],['B']],[['a','c',',d'],['3']]]`
rather than:
`['1','b','2','A','C','B','a','c',',d','3']`

# Answer
> 2 votes
# JavaScript (Node.js), 100 bytes

```
n=>g=x=>x.some((c,i)=>(i-(L=x.length-1))%n&&x.some((d,j)=>(j-L)%n&&i<j&c>d&&[x[i]=d,x[j]=c]))?g(x):x

```

Attempt This Online!

Use no `sort`

# Answer
> 1 votes
# Perl 5, 94 bytes

88 bytes of code + `-F -pl` flags.

```
$_=join"",(map{(--$i%$n?"":$F[$#F-$i--]),$_}sort grep$i++%$n,reverse@F),chop if($n=<>)>1

```

Try it online!

It's quite too long in my opinion, but already not that ugly... I'm still trying to golf it further anyway.

# Answer
> 1 votes
# Python \+ NumPy, ~~115~~ 114 bytes

```
from numpy import *
def f(x,n):l=len(x);x=array(x);m=[1<2]*l;m[-1::-n]=[1>2]*len(m[0::n]);x[m]=sort(x[m]);return x

```

Takes a regular Python list as input (wasn't sure whether taking an array would be considered kosher); returns a NumPy array containing the result.

Works by masking out the relevant indices and sorting the rest.

# Answer
> 1 votes
## Python 2, ~~119~~ 113 bytes

```
n,l=input()
i=range(len(l))
print"".join(sorted(l[~a]for a in i if a%n)[-a+a/n]if a%n else l[~a]for a in i)[::-1]

```

Builds a list of all characters to be sorted, sorts them and merges them for printing, while avoiding some of the reversing via negative indexing.

# Answer
> 1 votes
# Burlesque, 36 bytes

```
pe<-jJ-.hdcoJ)-]j)[-++<>#acoz[\[\[<-

```

Try it online!

Takes input as `N "String"`

```
pe       # Parse and push
<-       # Reverse the string
j        # Put N at the top of the stack
J-.hd    # Store N-1 for later
co       # Split string into chunks of N
J)-]     # Duplicate and take the heads
j)[-     # Take the tails of the other duplicate
++       # Reduce all the "useless" chars to string
<>       # Reverse sort
#aco     # Split into chunks of N-1
z[       # Zip the two lists
\[\[     # Flatten to string
<-       # Reverse the string

```

# Answer
> 1 votes
# Perl 6, 53 bytes

```
{(my@a=$^a.comb)[grep (@a-*-1)%$^n,^@a].=sort;[~] @a}

```

Try it online!

It feels like there should be a shorter way of doing this

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
DāR<IÖ≠©Ï{®ƶ<ǝ

```

I/O of the string as a list of characters.

Try it online or verify all test cases (feel free to remove the `S` and `J` in the test suite to see the actual I/O with character lists).

And I agree with *@mbomb007*'s comment, although it's still pretty short this way. :)

**Explanation:**

```
                #  Example inputs: s=["a","b","c","d","A","B","C","1","2","3"] and n=4
D               # Duplicate the (implicit) character-list input
                #  STACK: [["a","b","c","d","A","B","C","1","2","3"],
                #          ["a","b","c","d","A","B","C","1","2","3"]]
 ā              # Push a list in the range [1,list-length] (without popping the list)
                #  STACK: [s, s, [1,2,3,4,5,6,7,8,9,10]]
  R             # Reverse it to range [length,1]
                #  STACK: [s, s, [10,9,8,7,6,5,4,3,2,1]]
   <            # Decrease each by 1 to range (length,0]
                #  STACK: [s, s, [9,8,7,6,5,4,3,2,1,0]]
    IÖ          # Check for each if it's divisible by the integer-input
                #  STACK: [s, s, [0,1,0,0,0,1,0,0,0,1]]
      ≠         # And invert those truthy/falsey values
                #  STACK: [s, s, [1,0,1,1,1,0,1,1,1,0]]
       ©        # Store this list of truthy/falsey values in variable `®`
        Ï       # Only keep the characters in the list at the truthy indices
                #  STACK: [s, ["a","c","d","A","C","1","2"]]
         {      # Sort those
                #  STACK: [s, ["1","2","A","C","a","c","d"]]
          ®     # Push the truthy/falsey list again from variable `®`
                #  STACK: [s, ["1","2","A","C","a","c","d"], [1,0,1,1,1,0,1,1,1,0]]
           ƶ    # Multiply each by their 1-based index
                #  STACK: [s, ["1","2","A","C","a","c","d"], [1,0,3,4,5,0,7,8,9,0]]
            <   # Decrease everything by 1 to make it 0-based indexing
                #  STACK: [s, ["1","2","A","C","a","c","d"], [0,-1,2,3,4,-1,6,7,8,-1]]
             ǝ  # Insert the sorted characters at those indices in the list
                # (NOTE: Unlike almost all other 05AB1E builtins that use indices, this
                # insert builtin ignores negative and too large indices instead of using
                # modular indexing, so the -1 are conveniently ignored here.)
                #  STACK: [["1","b","A","C","a","B","d","1","2","3"]]
                # (after which this list is output implicitly as result)

```

# Answer
> 1 votes
# Uiua, 16 bytes

```
⍜▽(⊏⍏.)¬⇌=0◿:⇡⧻,

```

Try it!

```
⍜▽(⊏⍏.)¬⇌=0◿:⇡⧻,
             ⇡⧻,  # range of length
           ◿:     # modulo input
         =0       # where is it zero?
        ⇌         # reverse
       ¬          # not
⍜▽(⊏⍏.)           # under-keep-sort (sort input where mask is 1)

```

# Answer
> 1 votes
# , 28 bytes

```
]/:~@#~`(I.@])`[}0<(|i.@-@#)

```

Try it online!

# Answer
> 1 votes
# Vyxal, 11 bytes

```
ẏṘ~ḞFṘ⁽s?∇¢

```

Try it Online!

Outputs as a list of characters

## Explained

```
ẏṘ~ḞFṘ⁽s?∇¢
  ~Ḟ         # Every nth item of
ẏṘ           # The range [len(string), 0]
  ~          # without popping anything
    F        # Remove each item in that "every nth item" list from the range
     Ṙ       # Reverse that so that the indices are in ascending order
          ¢  # Apply
      ⁽s     # A function that sorts its argument
         ∇   # to the items at indices in
        ?    # the string
          ¢  # and insert the items in the result back at those indices

```

Created with the help of Luminespire.

# Answer
> 0 votes
# Ruby, 64 bytes

Uses regex to grab all irrelevant characters, both for replacement and for sorting.

```
->i,s,j=-1{s.gsub(r=/.(?!(?=.{#{i}})*$)/){s.scan(r).sort[j+=1]}}

```

Try it online

# Answer
> 0 votes
# Python 3.8 (pre-release), ~~111~~ 109 bytes

```
lambda n,s:(l:=len(s),r:=sorted(s[~i]for i in range(l)if i%n),[r.insert(i,s[i])for i in range(~-l%n,l,n)])[1]

```

Try it online!

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


# Question
Title: Shortest C code to display argv in-order
I recently tried to produce the shortest C code possible to display all its command line arguments (which are stored in argv).

I ended with a relatively small piece of code, and I was wondering if there was some trick I'm not aware of.
Here's my try (I compile with C17, but any standard before C23 is very likely to compile/link/run as intended, probably with some warnings though):

```
main(c,v)int**v;{for(;*v;)puts(*v++);}

```

First, `main(c,v)int**v`. In C, every variable and function must have a type, but if it isn't specified at the declaration, then `int` is assumed. For now, it means `main` function returns an `int`, and both `c` and `v` (argc and argv) are also of `int` type. But, the `int**v` right after the closing parenthesis is actually changing the type of `v` to `int**`. This syntax is the old-style function definition, back from the K&R book. However, C23 standard plans to remove this feature from the language (see on cppreference). So we end up with `c` being an int (as a normal `argc` is), and `v` being an `int**` (contrary to a normal `argv` which is `char**` or `char*[]` (but `char*[]` is treated as a `char**` in a function)).

Then, the for loop `for(;*v;)` (note: a `while(*v)` does the same thing). As a remainder, `v` is filled with a list of char pointers to the command line arguments, but they're treated as integer pointers and not character pointers here. Thus, the loop runs until the first pointer in `v` is NULL (is equal to 0).

`puts(*v++);` does two things ; writing down the first string (it takes the first pointer in `v`, a `int*`, but `puts` expects a `char*`, so it can correctly deal with it) in the console and increases `v` (instead of having an iterator variable i, then doing `v[i]`, here I use `*v` and `v++` to save some characters). I also haven't used curly brackets around the for loop because when omitting them, the loop body is the first statement below it. I used `int` instead of `char` to declare `v`, in order to save a char. But is there a platform where those pointer types aren't the same size ? I once saw that function pointers may have a different size than ordinary pointers, but I don't know if this may be true for two pointers of different types.

It is guaranteed that `argv[argc]` is NULL, thus the code is guaranteed not to have an infinite loop (see here).

Then no need to add a `return 0;` because it is guaranteed `main` will return 0 if I don't put a `return` statement.

Some may wonder why I was able to call `puts` without including stdio.h, it's because in C, the whole library is linked to the binary (this question is a duplicate, but I put it here because the answer better explains this point than the original question). It also not seems to have a standard behavior (hence the warning), thus be aware of that (never rely on an undefined behavior). Same thing seems to apply for implicit `int` type.
Can someone confirm or not ?

Thus, my final question, is there any way to shorten this code ? I'm asking either for standard or platform-specific ways.

Sorry for the long post, but I wanted to explain for any interested beginner.

# Answer
> 11 votes
# C (gcc), 37 bytes

```
main(c,v)int*v;{for(;*v;)puts(*v++);}

```

Try it online!

When using 32-bit, you can use `int` to store a pointer if not explicitly deferred

# C (gcc), 35 bytes, exit by segment fault

```
main(c,v)int*v;{for(;puts(*v++););}

```

Try it online!

# Answer
> 4 votes
# C (GCC), 34 bytes

```
main(c,v)int*v;{execvp("echo",v);}

```

Attempt This Online!

# C (GCC) with `-m32` flag, 28 bytes

*thanks to @jdt*

```
main(c,v){execvp("echo",v);}

```

Try it online!

---

Replaces the current process image with the process image of `/bin/echo` (which is assumed to be in the `PATH`). It may not work correctly if the first argument(s) are recognized as flags by your version of echo.

May not be useful in every situation.

Note that more than the first argument could be messed up. For example, with GNU coreutils' echo:

* `-n`, `-e`, `-E` are recognized as short arguments, so `/bin/echo -n -e x` outputs just `x`, while `/bin/echo -n x -e` outputs `x -e`;
* `/bin/echo --help` and `/bin/echo --version` print a lot of stuff that wasn't present in the arguments.

# Answer
> 2 votes
# (gcc): 37 bytes

```
main(c,v)int**v;{main(puts(*v),++v);}

```

Don't forget about recursion. :)

Try it online

# Answer
> -1 votes
# C (gcc), 37 bytes

```
main(c,v)int*v;{for(;*v;)puts(*v++);}

```

---
Tags: code-golf, tips, c
---


title: Collatz, Sort, Repeat

text:
# Question
Title: Collatz, Sort, Repeat
## Background

The Collatz (or 3x+1) map (A006370) is defined as the following:

$$ a(n) = \begin{cases} n/2, & \text{if $n$ is even} \\ 3n+1, & \text{if $n$ is odd} \end{cases} $$

Now, let's define the sequence \\$s\_0\\$ as the infinite sequence of positive integers \\$1, 2, 3, 4, \cdots\\$, and define \\$s\_k\\$ as the result of applying the process \\$k\\$ times to \\$s\_0\\$:

1. Apply Collatz map to each term of the input sequence.
2. Sort all the terms to get a non-decreasing sequence.

Here are first few terms of \\$s\_0, \cdots, s\_3\\$:

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

```

## Challenge

Given \\$k\\$ as input, output the sequence \\$s\_k\\$.

Default I/O methods are allowed. For this challenge, this means you can use one of the following:

* Take \\$k\\$ as input, and output the terms of \\$s\_k\\$ forever.
* Take \\$k, n\\$ as input, and output the value of \\$s\_k(n)\\$ (0- or 1-indexed).
* Take \\$k, n\\$ as input, and output the first \\$n\\$ values of \\$s\_k\\$.

You can also use 0- or 1-indexing for \\$k\\$.

Standard rules apply. The shortest code in bytes wins.

# Answer
> 8 votes
# Python 2, 81 bytes

```
f=lambda k,n:k and sorted([x/2,x*3+1][x%2]for x in f(k-1,n*2))[:n]or range(1,n+1)

```

Try it online!

-19 bytes thanks to Leo and Bubbler
-11 bytes thanks to dingledooper (-6 + -5 from Python 2)
-8 bytes by swapping over to the brute force solution
-2 bytes thanks to Noodle9

To get \\$s\_k\\$ up to \\$n\\$ elements, we only need to get \\$s\_{k-1}\\$ up to \\$2n\\$ elements.

# Answer
> 7 votes
# Husk, ~~27~~ ~~25~~ ~~23~~ 20 bytes

```
!¡ȯΞzme½o→*3Mfe¦2%2N

```

Try it online!

The idea for this comes from a message by rak1507 in the Husk chat. Returns the full sequence corresponding to the given 1-based k.

### Explanation

We start from the list of natural numbers and then at each step produce one list with each even number halved and another list with each odd number multiplied by 3 and incremented, then we merge the two lists keeping them sorted.

```
!¡(Ξzme½(→*3)Mfe¦2%2)N
                     N    Start from the infinite list of natural numbers
 ¡                        Then iterate the following function
             Mfe           Build two lists by applying the following two filters
                ¦2          Numbers divisible by 2
                  %2        Numbers not divisible by 2
    zme                    Apply the following two functions respectively
                           to the first and second list
       ½                    Halve
         →*3                Multiply by 3, then increase
   Ξ                       Merge the two resulting lists
!                         Finally, return the result of the kth iteration

```

---

# Previous answer, 25 bytes

```
`ṘN!¡§z+oĊ2tȯ↓2ṁ:R5 0Ċ2∞1

```

Try it online!

A bit clunky, but here's what I have for now. Returns the full sequence corresponding to the given 1-based `k`.

-2 bytes thanks to Razetime.

### Explanation

Rather than building the sequence directly, we build a list containing at each position `n` the number of occurrences of `n` in the sequence, then we convert it to the final sequence.

```
`ṘN!¡§z+oĊ2tȯ↓2ṁ:R5 0Ċ2∞1
                       ∞1    Start from an infinite list of ones
                                (in s0 each number appears once)
    ¡                        Iterate the following function
     §z+                       Sum together
        oĊ2t                   The even-positioned values
            ȯ        Ċ2        with the odd-positioned values
               ṁ:R5 0            with 5 zeros added before each one
             ↓2                  and the initial 2 zeros dropped
   !                         Get the kth iteration
`ṘN                          Repeat each natural number as many times as indicated

```

The trick here is that at each step we build two infinite lists and sum them together: the first one is the even-position values, which will each move to position `n/2` simply because we remove the odd positions from the list; the second one starts from the odd positions (`n->(n+1)/2`), inserts 5 zeros before each value (`(n+1)/2->3n+3`), and removes the first two zeros (`3n+3->3n+1`).

# Answer
> 7 votes
# Haskell, 73 bytes

```
([1..]>>=).(#)
k#n|k<1=[n]|s<-k-1=n<$s#(2*n)++[n|_<-s#div n 3,mod n 6==4]

```

Try it online!

`k#n` returns a list of the appropriate number of copies of `n`. The anonymous function `([1..]>>=).(#)` concatenates all of those together.

# Answer
> 6 votes
# Jelly, 16 or 17 bytes

```
×3‘
H
æ«ḂĿ€⁴¡Ṣḣ³

```

Try it online!

Takes *n* and *k* as arguments in that order, and outputs the first *n* elements of *s**k*. The 16-byte version above does not work for *k* = 0; if this invalidates the solution, you can add an `R` after `æ«` for a 17-byte solution.

## Algorithm

As is so often the case, producing terse code here was a matter of translating the problem directly using a brute-force algorithm rather than looking for a nice mathematical way to solve the problem. We simply start with a sufficiently long list, then Collatz and sort it the required number of times, and output the first *m* elements. (As an optimization, which saves runtime but more importantly a byte, we can in fact Collatz it the required number of times but sort it only once, because sorting+mapping+sorting a list is equivalent to just mapping+sorting it.)

The number of terms we start with is *n*×2*k*; this guarantees that all terms which are numerically at least *n* will be correct in the output (any term that started higher than this couldn't be reduced to *n* in only *k* iterations), and therefore the first *n* elements will necessarily be correct in the output (because no *s**k* can grow faster than the integers do, thus *s**k*(*n*) ≤ *n*).

## Explanation

```
Function 1Ŀ:
×3‘
×3             Multiply by 3
  ‘            Increment

Function 2Ŀ:
H
H              Halve

Main program:
æ«ḂĿ€⁴¡Ṣḣ³
æ«             Calculate {n} times 2 to the power of {k}
      ¡        Loop   times:
     ⁴              k
    €            On each {of the previous iteration's results, if any
                          or the numbers from 1 to the input, if not}
   Ŀ             Call the function whose index is
  Ḃ                determined by whether {that number} is odd or even
       Ṣ       Sort {the resulting list}
        ḣ      Take the first   elements
         ³                    n

```

I'm actually not sure why `ḂĿ` (which should call `1Ŀ` on odd numbers but a nonexistent "`0Ŀ`" on even numbers) decides to call `2Ŀ` on even numbers, but it's convenient here. (I assume it's some special case in Jelly that recognises that it doesn't make sense to do a recursive call here, but I'm not sure what triggers it; the special case isn't mentioned in the documentation for `Ŀ`, but the quicks aren't fully documented anyway.)

One interesting thing about this code is that it's a self-polyglot; the  does something different on the first loop iteration than it does on the other loop iterations (and the code wouldn't typecheck in a typical statically typed language as a consequence). I frequently do this sort of thing in horrifyingly low-level esolangs that are a nightmare to program in, but this is the first time I remember doing it in Jelly. As a consequence, the code doesn't work for *k* = 0 (it tries to sort the *digits* of *n*, due to a special case in Jelly that's more harmful than useful here). If this is a problem, it can be fixed at the cost of 1 additional byte by adding an `R` after the `æ«`.

# Answer
> 4 votes
# , 39 bytes

```
]{.[:/:~[_&(]2&|`(-:,:1+3&*)})1+[:i.2&*

```

Try it online!

Called like `k f n`, returns the first `n` elements.

I am using the same algorithm as ais523, though I stumbled upon it independently.

* `1+[:i.2&*` Generate `n*2^k` elements starting at 1.
* `_&(]2&|`(-:,:1+3&*)})` Apply collatz k times using Item Amend.
* `[:/:~` Sort.
* `]{.` Return first n.

# Answer
> 2 votes
# JavaScript (Node.js), 78 bytes

```
i=0;f=k=>f(k,c=(n,k)=>k--?c(2*n,k)|n%6==4&&c(~-n/3,k):console.log(i),c(++i,k))

```

Try it online!

Quite port but still some changes

# JavaScript (Node.js), 98 bytes

```
i=>g=(n,a=[...Array(i<<n+1)])=>n?g(n-1,a.map((c,j)=>(c=c||j,c%2?c*3+1:c/2))):a.sort((a,b)=>a-b)[i]

```

Try it online!

Pure definition

`i<<n+1` for `n=1` case

# Answer
> 2 votes
# 05AB1E, 19 bytes

```
o*L¹FεDÉi3*>ë2÷]{I£

```

Try it online!

A port of the jelly answer

# Answer
> 2 votes
# Ruby, ~~67~~ 65 bytes

```
f=->k,n{k<1?[*1..n]:f[k-1,n*2].map{|x|x%2<1?x/2:x*3+1}.sort[0,n]}

```

Try it online!

### Quickly explained:

If we know that the output is in the range (1..n), then we can start reducing the array (1..n\*2^k). The rest is standard Collatz for k steps.

(Thanks Kirill L. for -1 byte)

# Answer
> 2 votes
# Brachylog, 34 bytes

Generates each sequence. Still a bit too verbose …

```
∧ℕ₁≜gT;?⟨×₂ᵐc{-₁/₃.%₂1∧}ˢ⟩ⁱ⁾l;Tj₍∋

```

Try it online!

```
∧ℕ₁≜gT;?⟨×₂ᵐc{-₁/₃.%₂1∧}ˢ⟩ⁱ⁾l;Tj₍∋
∧ℕ₁≜gT                              trying T = [1], then T = [2], then T = [3], …
      ;?⟨                ⟩ⁱ⁾        apply the predicade input times:
         ×₂ᵐ                         multiply each element by 2
             {-₁/₃.%₂1∧}ˢ            select outputs where
                                      (element - 1)/3 must be odd
            c                        join both lists together
                            l;Tj₍∋  get the length of the final result,
                                     and output T so many times

```

# Answer
> 1 votes
# Retina, 84 bytes

```
~`(.+),(.+)
.+¶$1*$(2$*)$2$*$¶¶¶$$.`$*¶%$1+`(_+)\1$$|(_+)¶3$*$$2$$1$$#2$*¶O`¶,G$2`¶_

```

Try it online! Explanation: Uses the same `n2ᵏ` approach as other answers. Works by building up a Retina program with `k` and `n` hardcoded in and then evaluating it. For example, the link demonstrates `k=3` and `n=20`, and this results in the following Retina program:

```
.+
2*2*2*20*¶

```

Replace the input with `n2ᵏ` newlines.

```

$.`*

```

Generate all of the integers from `0` to `n2ᵏ` in unary.

```
%`

```

Separately for each line...

```
3+`

```

... repeat `k` times...

```
(_+)\1$|(_+)
3*$2$1$#2*

```

... if the current value is even, then halve it, otherwise treble it and add `1`. (The `3*` needs to be at the beginning to avoid conflicting with the `$1` while the `$#2*` needs to be at the end to allow for an implicit `_`.)

```
O`

```

Sort all of the lines into order. (This is not a numeric sort because the lines are still in unary at this point.)

```
,G20`

```

Select the `n`th line.

```
_

```

Convert it to decimal.

At a cost of 4 bytes, the first `n` terms can be output instead:

```
~`(.+),(.+)
.+¶$1*$(2$*)$2$*$¶¶¶$$.`$*¶%$1+`(_+)\1$$|(_+)¶3$*$$2$$1$$#2$*¶O`¶,G1,$2`¶%`_

```

Try it online! Explanation: Only the last two lines change.

```
,G1,20`

```

Select the first to the `n`th line. (There is actually a zeroth line that we need to skip.)

```
%`_

```

Convert each line to decimal.

# Answer
> 1 votes
# C (gcc), ~~183~~ \\$\cdots\\$ ~~148~~ 126 bytes

```
g;t;l;i;f(k,n){int a[g=l=n<<k];for(;g||k--;g=qsort(a,l,4,L"\x62b078bǃ"))for(i=l;i--;a[i]=g?i+1:t%2?3*t+1:t/2)t=a[i];i=a[n-1];}

```

Try it online!

*Saved a whopping 22 bytes thanks to ceilingcat!!!*

Inputs \\$k\\$ and \\$1\\$-based \\$n\\$ and returns the \\$n^{\text{th}}\\$ element of \\$s\_k\\$.

### Explanation

```
g;t;l;i;                                 // declare all int vars needed
f(k,n){                                  // main function
    int a[         ];                    // array a to hold sequences
          g=                             // init g to non-zero
             l=n<<k                      // length is n * 2**k
    for(;                                // main loop
         g||                             // g non-zero is an init loop for a
            k--;                         // after that loop k times
                g=qsort(a,l,4,           // end of each loop sort
                          L"\x62b078bǃ") // using a -zexecstack
                                         // comparator and set g
                                         // to zero (return value
                                         // of qsort for success)
        for(i=l;i--;                     // loop over all elements in a
                    a[i]=                // each loop set a[i] to...
                         g?              // if it's the init loop
                          i+1            // set a[i] to i + 1
                          :              // otherwise post-init loops
                         t%2?            // apply Collatz map to a[i]
                           3*t+1
                           :
                           t/2)
            t=a[i];                      // temp for a[i] to save bytes
    i=a[n-1];                            // return the 1-based nth value
}

```

# Answer
> 1 votes
# MathGolf, 9 bytes

```
²╒kÉm■sk<

```

Port of *hyper-neutrino♦*'s Python 2 answer, so will also output the first \\$n\\$ values (and will use the trick of only checking the range \\$\[1,n^2\]\\$).

Try it online or verify some more test cases.

**Explanation:**

```
²         # Square the (implicit) first input `n`
 ╒        # Pop and push a list in the range [1,n²]
  k       # Push the second input `k`
   É      # Pop and loop `k` amount of times using 3 characters as inner code-block:
    m     #  Map each value in the list to:
     ■    #   Pop and calculate its Collatz value
      s   #  Then sort the list from lowest to highest
       k  # After the loop, push the first input `n` again
        < # And only leave that many leading items from the list
          # (after which the entire stack is output implicitly as result)

```

# Answer
> 0 votes
# Charcoal, 46 bytes

```
ＮθＮη≔…·¹×ηＸ²θζＦθＵＭζ⎇﹪κ²⊕×³κ⊘κＷ⁻ζυＦ№ζ⌊ι⊞υ⌊ιＩ…υη

```

Try it online! Link is to verbose version of code. Outputs the first `n` elements. Explanation:

```
ＮθＮη

```

Input `k` and `n`.

```
≔…·¹×ηＸ²θζ

```

Create a range from `1` to `n2ᵏ`.

```
ＦθＵＭζ⎇﹪κ²⊕×³κ⊘κ

```

Apply the Collatz formula `k` times to the range.

```
Ｗ⁻ζυＦ№ζ⌊ι⊞υ⌊ι

```

Sort the range.

```
Ｉ…υη

```

Output the first `n` elements.

A port of @hyper-neutrino's algorithm takes 48 bytes:

```
ＮθＮη≔⁰ζＷ‹Ｌυη«≦⊕ζ≔⟦ζ⟧εＦθ≔⁺⊗ε÷Φε⁼⁴﹪λ⁶¦³εＦε⊞υζ»Ｉ…υη

```

Try it online! Link is to verbose version of code. Explanation:

```
ＮθＮη

```

Input `k` and `n`.

```
≔⁰ζ

```

Start counting at `0`.

```
Ｗ‹Ｌυη«

```

Repeat until we have at least `n` elements.

```
≦⊕ζ

```

Get the next value we want to calculate the count for.

```
≔⟦ζ⟧ε

```

Start with a list of just that value.

```
Ｆθ

```

Repeat `k` times...

```
≔⁺⊗ε÷Φε⁼⁴﹪λ⁶¦³ε

```

Double the list and integer divide an appropriately filtered copy of the list by 3. This results in a list of all the values that result in the target value after `k` steps.

```
Ｆε⊞υζ

```

Add that many copies of the target value to the list of results.

```
»Ｉ…υη

```

Output the first `n` elements.

# Answer
> 0 votes
# , 76 bytes

```
f=function(k,n,a=1:(n*2^k),b=a%%2)`if`(k,f(k-1,n,sort(a*b*3+b+a/2*!b)),a[n])

```

Try it online!

# Answer
> 0 votes
# Haskell, 96 bytes

```
(x:w)#h|x<=h!!0=x:w#h
x#y=y#x
g x=[div i 2|i<-x,even i]#[3*i+1|i<-x,odd i]
f 0=[1..]
f n=g$f$n-1

```

Try it online!

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


title: Percentage of work days in a month

text:
# Question
Title: Percentage of work days in a month
Given a year and a month, find out the percentage of work days in said month. Work days are Monday through Friday with no regard to holidays or other special things. The Gregorian calendar is used.

**Input**

A year and month in ISO 8601 format (YYYY-MM). The year always has four digits, the month always has two digits. The given year will not be before 1582.

**Output**

Output is the percentage of work days (according to above definition) in the given month, rounded to a whole number. No percent sign or fractional digits follow.

**Sample 1**

```
Input                Output

2010-05              68

```

**Sample 2**

```
Input                Output

2010-06              73

```

**Sample 3**

```
Input                Output

1920-10              68

```

**Sample 4**

```
Input                Output

2817-12              68

```

A week has passed, an answer has been accepted. For the curious, the sizes of the submissions we got in our contest:

> 129 – Z shell
> 174 – VB.NET
> 222 – C
> 233 – C
> 300 – C

As well as our own (unranked) solutions:

> 75 – PowerShell
> 93 – Ruby
> 112 – Bourne shell

# Answer
> 4 votes
## 64-bit Perl, 67 ~~68~~

Perl 5.10 or later, run with `perl -E 'code here'` or `perl -M5.010 filename`

```
map{$d++,/^S/||$w++if$_=`date -d@ARGV-$_`}1..31;say int.5+100*$w/$d

```

Concessions to code size:

* locale-sensitive: it counts as work days the days whose `date` output don't start with a capital S. Run under `LC_ALL=C` if in doubt.
* output is pure and well-formatted, but there's "garbage" on stderr on months shorter than 31. `2> /dev/null` if upset.
* ~~for some reason, my version of `date` considers 2817-12 an invalid month. Who knew, GNU new apocalypse is due!~~ Requires a 64 bit build of `date` for dates after 2038. (Thanks Joey)

# Answer
> 3 votes
## PHP - 135

I made it in PHP because I had a similar problem to treat a few days ago.

```
<?php $a=array(2,3,3,3,2,1,1);$t=strtotime($argv[1]);$m=date(t,$t);echo round((20+min($m-28,$a[date(w,strtotime('28day',$t))]))/$m*100)

```

(Somewhat) More legibly, and without notices about constants being used as strings:

```
<?php
date_default_timezone_set('America/New_York');
$additionalDays = array(2, 3, 3, 3, 2, 1, 1);
$timestamp = strtotime($argv[1]);
$daysInMonth = date('t', $timestamp);
$limit = $daysInMonth - 28;
$twentyNinthDayIndex = date('w', strtotime("+28 days", $timestamp));
$add = $additionalDays[$twentyNinthDayIndex];
$numberOfWorkDays = 20 + min($limit, $add);
echo round($numberOfWorkDays / $daysInMonth * 100);
?>

```

This is made possible by a very simple algorithm to compute the number of work days in a month: check for the weekdayness of the 29th, 30th and 31st (if those dates exist), and add 20.

# Answer
> 3 votes
# Swift, 346 bytes

Short version:

```
func f(_ s:String)->Int{let c=Calendar.current,m=Int(s.suffix(2))!,y=Int(s.prefix(4))!,mR=c.range(of:.day,in:.month,for:DateComponents(calendar:c,year:y,month:m).date!)!,n=mR.reduce(0){p,d in let d=c.date(from: DateComponents(year:y,month:m,day:d))!,w=c.component(.weekday,from:d);return(2...6).contains(w) ?p+1:p};return (n*1000/mR.count+5)/10}

```

Slightly longer version:

```
func f2(_ s: String) -> Int {
    let c=Calendar.current
    let m=Int(s.suffix(2))!
    let y=Int(s.prefix(4))!
    let mR=c.range(of:.day,in:.month,for:DateComponents(calendar:c,year:y,month:m).date!)!
    let n=mR.reduce(0){p,d in
        let d=c.date(from: DateComponents(year:y,month:m,day:d))!
        let w=c.component(.weekday,from:d)
        return(2...6).contains(w) ?p+1:p
    }
    return (n*1000/mR.count+5)/10
}

```

# Answer
> 2 votes
**Python 152 Characters**

```
from calendar import*
y,m=map(int,raw_input().split('-'))
c=r=monthrange(y,m)[1]
for d in range(1,r+1):
 if weekday(y,m,d)>4:c-=1
print '%.f'%(c*100./r)

```

# Answer
> 2 votes
## Windows PowerShell, 80

```
$x=$args;1..31|%{"$x-$_"|date -u %u -ea 0}|%{$a++
$b+=!!($_%6)}
[int]($b*100/$a)

```

# Answer
> 1 votes
# D: 186 Characters

```
auto f(S)(S s){auto d=Date.fromISOExtendedString(s~"-28"),e=d.endOfMonth;int n=20;while(1){d+=dur!"days"(1);if(d>e)break;int w=d.dayOfWeek;if(w>0&&w<6)++n;}return rndtol(n*100.0/e.day);}

```

More Legibly:

```
auto f(S)(S s)
{
    auto d = Date.fromISOExtendedString(s ~ "-28"), e = d.endOfMonth;
    int n = 20;

    while(1)
    {
        d += dur!"days"(1);

        if(d > e)
            break;

        int w = d.dayOfWeek;

        if(w > 0 && w < 6)
            ++n;
    }

    return rndtol(n * 100.0 / e.day);
}

```

# Answer
> 1 votes
## Python - 142

```
from calendar import*
y,m=map(int,raw_input().split('-'))
f,r=monthrange(y,m)
print'%.f'%((r-sum(weekday(y,m,d+1)>4for d in range(r)))*100./r)

```

Thanks to fR0DDY for the calendar bit.

# Answer
> 1 votes
## Ruby, 124 119 111

```
require 'date'
e=Date.civil *$*[0].split(?-).map(&:to_i),-1
p ((e+1<<1..e).count{|d|d.cwday<6}*1e2/e.day).round

```

Requires Ruby 1.9 due to splatting the year and month before the -1 "day" argument and `?-` for `"-"`. For Ruby 1.8, we must add 2 characters:

```
require 'date'
e=Date.civil *$*[0].split('-').map(&:to_i)<<-1
p ((e+1<<1..e).count{|d|d.cwday<6}*1e2/e.day).round

```

**Edit**: Shave five characters based on @Dogbert's help.
**Edit**: Shave eight more characters based on @steenslag's help.

# Answer
> 1 votes
# Bash + coreutils, 82 bytes

```
f()(cal -NMd$1|sed -n "s/^$2.//p"|wc -w)
dc -e`f $1 "[^S ]"`d`f $1 S`+r200*r/1+2/p

```

# Answer
> 1 votes
# PHP 5.2, 88 bytes

Although I already golfed zneak´s solution down to 85 bytes (I just found one more), here´s my own:
I doubt that I can squeeze another three bytes out here.

```
$a=_4444444255555236666304777411;echo$a[date(t,$t=strtotime($argn))%28*7+date(N,$t)]+67;

```

takes input from STDIN: Run with `echo <yyyy>-<mm> | php -nR '<code>'`.

The string `$a` maps days per month (`date(t)`) and week day of the first day of the month (`date(N)`: Monday=1, Sunday=7) to the percentage of work days-67; `strtotime` converts the input to a UNIX timestamp; the rest of the code does the hashing.

+1 byte for older PHP 5: Replace `N` with `w` and `$a=_...;` with `$a="..."`.
another +3 bytes for PHP 4: insert `.-1` after `$argn`.

-5 bytes for PHP 5.5 or later (postdates the challenge):
Remove everything before `echo` and replace `$a` with `"4444444255555236666304777411"`.

# Answer
> 1 votes
# C#, 158 bytes

```
s=>{var d=DateTime.Parse(s);int i=0,t=DateTime.DaysInMonth(d.Year,d.Month),w=0;while(i<t)w-=-(int)d.AddDays(i++).DayOfWeek%6>>31;return Math.Round(1e2*w/t);};

```

Anonymous method which returns the required percentage.

Full program with ungolfed, commented method and test cases:

```
using System;

class WorkingDayPercentage
{
    static void Main()
    {
        Func <string, double> f =
        s =>
        {
            var d = DateTime.Parse(s);                      // extracts a DateTime object from the supplied string
            int i = 0,                                      // index variable
                t = DateTime.DaysInMonth(d.Year, d.Month),  // number of total number of days in the specified month
                w = 0;                                      // number of working days in the month

            while (i < t)                                   // iterates through the days of the month
                w -= -(int)d.AddDays(i++).DayOfWeek%6 >> 31;// d.AddDays(i) is the current day
                                                            // i++ increments the index variable to go to the next day
                                                            // .DayOfWeek is an enum which hold the weekdays
                                                            // (int)..DayOfWeek gets the days's index in the enum
                                                            // note that 6 is Saturday, 0 is Sunday, 1 is Monday etc.
                                                            // (int)DayOfWeek % 6 converts weekend days to 0
                                                            // while working days stay strictly positive
                                                            // - changes the sign of the positive numbers
                                                            // >> 31 extracts the signum
                                                            // which is -1 for negative numbers (working days)
                                                            // weekend days remain 0
                                                            // w -= substracts the negative numbers
                                                            // equivalent to adding their modulus

            return Math.Round(1e2 * w / t);                 // the Math.round function requires a double or a decimal
                                                            // working days and total number of days are integers
                                                            // also, a percentage must be returned
                                                            // multiplying with 100.0 converts the expression to a double
                                                            // however, 1e2 is used to shorten the code
        };

        // test cases:
        Console.WriteLine(f("2010-05")); // 68
        Console.WriteLine(f("2010-06")); // 73
        Console.WriteLine(f("1920-10")); // 68
        Console.WriteLine(f("2817-12")); // 68
    }
}

```

Alternative function, which adds negative values to the number of working days, changing the sign in the return with no extra byte cost:

```
s=>{var d=DateTime.Parse(s);int i=0,t=DateTime.DaysInMonth(d.Year,d.Month),w=0;while(i<t)w+=-(int)d.AddDays(i++).DayOfWeek%6>>31;return-Math.Round(1e2*w/t);};

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 55 bytesSBCS

Anonymous tacit prefix function.

```
⌊.5+100×2÷/(2 5)2{≢⍎⍕↓⍺↓¯2⌽' ',cal⍎' '@5⊢⍵⊣⎕CY'dfns'}¨⊂

```

enclose date to treat it as a whole

`(2 5)2{` apply the following function on that, but with the left arguments `[2,5]` and `2`:

`⎕CY'dfns'` copy the "dfns" library

`⍵⊣` discard the report in favour of the date

`' '@5⊢` replace the 5th character (`-`) with a space

execute that to get two-element list

`cal` call the calendar function on that

`' ',` prepend a column of spaces to that

`¯2⌽` rotate the last two columns (Saturday) to the front

`⍺↓` drop left-argument number of rows (2, headers) and columns (if specified; 5=Sat+Sun)

split matrix into list of lines

format (flattens with insertion of double-spacing)

execute (turns remaining day numbers into a flat numeric list)

tally those

`2÷/` divide each pair (there's only one)

`100×` multiply by a hundred

`.5+` add a half

floor

Try it online!

# Answer
> 1 votes
# Go, 243 bytes

```
import(."time";."math")
func f(s string)int{t,_:=Parse("2006-01",s)
D,o:=Hour*24,0.0
y,m,_:=t.Date()
d:=Date(y,m+1,0,0,0,0,0,UTC).Add(D).Sub(t).Hours()/24
for;t.Month()==m;t=t.Add(D){if w:=t.Weekday();0<w&&w<6{o++}}
return int(Round(100*o/d))}

```

Attempt This Online!

Loops through the days of the month and checks each for being a weekday (between `0=Sunday` and `6=Saturday`).

# Answer
> 0 votes
# Rebol - 118 113

```
w: b: 0 o: d: do join input"-01"while[d/2 = o/2][if d/7 < 6[++ w]++ b d: o + b]print to-integer round w / b * 100

```

Ungolfed:

```
w: b: 0
o: d: do join input "-01"
while [d/2 = o/2] [
    if d/7 < 6 [++ w]
    ++ b
    d: o + b
]
print to-integer round w / b * 100

```

# Answer
> 0 votes
# Oracle SQL, 110 bytes

```
select round(100*sum(1-trunc(to_char(x+level-1,'d')/6))/sum(1))from dual,t connect by level<=add_months(x,1)-x

```

It works with an assumption that input data is stored in a table in using `date` data type, e.g.

```
with t as (select to_date('2010-06','yyyy-mm') x from dual)

```

# Answer
> 0 votes
# Perl 6, 78 bytes

```
{round 100*@_.grep(6>*.day-of-week)/@_}o{Date.new("$_-01")...^*.month-*.month}

```

Try it online!

# Answer
> 0 votes
# Japt, ~~36~~ 34 bytes

```
HÆÐU+XnÃf@¤¤ÅÉ¶XÎÃme
èÈ©n6Ã*L/UÊ r

```

Try it

Not pretty at all! Needs more work.

## ~~34~~ 32 bytes

2 bytes can be saved by always rounding down as the challenge doesn't specify that we must round to the nearest integer:

```
HÆÐU+XnÃf@¤¤ÅÉ¶XÎÃme
èÈ©n6ÃzUÊ/L

```

Try it

# Answer
> 0 votes
# Bash + ncal, ~~75~~ 70 bytes

```
m=`ncal ${1#*-} ${1%-*}`
set $m
wc -w<<<${m%%Sa*}|dc -e ?7-A0*$#\ 9-/p

```

We start by using `ncal` to print a calendar:

```
    May 2010
Mo     3 10 17 24 31
Tu     4 11 18 25
We     5 12 19 26
Th     6 13 20 27
Fr     7 14 21 28
Sa  1  8 15 22 29
Su  2  9 16 23 30

```

The total number of days in the month is the word-count of this output, minus 9 (the seven weekday names and the month and year of the header). This word-count is obtained using `set` and `$#`.

The number of work days is a similar calculation, but we first eliminate everything from `Sa` onwards (we can't just match `S` because the month may be `Sep`), and subtract only 7 surplus words. We count this using `wc`.

We then use `dc` to compute a percentage (using `A0` as short form of `100`).

Note that this program rounds fractional percentages downwards - the question's examples appear to use a different choice for the rounding, but it didn't impose a specific direction. Rounding to nearest would cost an additional 7 bytes by executing `$#\ 2/+` before we divide by the total: `?7-A0*$#\ 2/+$#\ 9-/p`.

# Answer
> 0 votes
# GNU date+bc, 56 bytes

## Abstract

This Answer demonstrates that the following 56-byte shell pipeline calculates the percentage of work days in a given month, rounded to the nearest whole percent:

```
date -d$1-1month-4week +'70+%d-3*(%w+1<%d)-3*(%u<%d)'|bc

```

## Analysis

There are 28 possible monthly calendars, that can be identified according to the last day/date of the month:

|  | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
| --- | --- | --- | --- | --- | --- | --- | --- |
| **28th** | 20/28 | 20/28 | 20/28 | 20/28 | 20/28 | 20/28 | 20/28 |
| **29th** | 21/29 | 21/29 | 21/29 | 21/29 | 21/29 | 20/29 | 20/29 |
| **30th** | 21/30 | 22/30 | 22/30 | 22/30 | 22/30 | 21/30 | 20/30 |
| **31st** | 21/31 | 22/31 | 23/31 | 23/31 | 23/31 | 22/31 | 21/31 |

There are nine distinct fractions here, that can be converted to percentages:

|  | 20 | 21 | 22 | 23 |
| --- | --- | --- | --- | --- |
| **28** | 71 |  |  |  |
| **29** | 69 | 72 |  |  |
| **30** | 67 | 70 | 73 |  |
| **31** |  | 68 | 71 | 74 |

Substituting these gives our conversion table:

|  | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 28th | 71 | 71 | 71 | 71 | 71 | 71 | 71 |
| 29th | 72 | 72 | 72 | 72 | 72 | 69 | 69 |
| 30th | 70 | 73 | 73 | 73 | 73 | 70 | 67 |
| 31st | 68 | 71 | 74 | 74 | 74 | 71 | 68 |

The pattern becomes more clearly evident when we split this into a basic value for a month containing four weekends, less an amount for a fifth Saturday and for a fifth Sunday:

|  | Basic | Thu | Fri | Sat | Sun | Mon | Tue | Wed |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 28th | 71 | . . | . . | . . | . . | . . | . . | . . |
| 29th | 72 | . . | . . | . -3 | -3 . | . . | . . | . . |
| 30th | 73 | . . | . . | . -3 | -3 -3 | -3 . | . . | . . |
| 31st | 74 | . . | . . | . -3 | -3 -3 | -3 -3 | -3 . | . . |

The basic value is clearly 71 plus one for each day more than 28 days.

And we must then subtract 3 if the last day is in a range beginning Saturday and having length equal to those excess days, less three for a similar range beginning Sunday.

## Implementation

Firstly, we append a day number to turn year and month into a full date: `$1-01`.

Rather than finding the *last* day of the month, we select a date nearer the start of the month, by subtracting 28 days from the start of the following month. This gives us a day-of-week that's one later than used in the analysis section:

```
date -d'$1-01 +1month-4week'

```

Using this date, we then format a calculation for `bc` to execute and print. The basic percentage is simple; it's just 70 more than the day number we landed on: `70+%d`.

The adjustments for extra weekend days are then computed using a pair of inequalities, taking advantage of the fact that there are two representations for day-of-week, with Sunday represented as 0 or as 7. We subtract 3 points from the basic percentage for each of those inequalities.

## Demo

We can reproduce the results from the examples in the question:

| Command | Result |
| --- | --- |
| `./1158 2010-05` | 68 |
| `./1158 2010-06` | 73 |
| `./1158 1920-10` | 68 |
| `./1158 2817-12` | 68 |

And we can show that we get the correct results for all 28 shapes of month shown in the first table:

```
for i in $(printf '%s\n' 20{{00..03}-{03..12},{00..24}-02}-01+month-1day |
           date -f- +'%Y-%m%t%d %u %a' | sort -k2,3 -u | cut -f1)
do ./1158 $i
done | rs 0 7

```

```
71  71  71  71  71  71  71
72  72  72  72  72  69  69
70  73  73  73  73  70  67
68  71  74  74  74  71  68

```

# Answer
> 0 votes
# Scala, 152 bytes

A port of @adrianmp's C# answer in Scala.

---

Golfed version. Try it online!

```
s=>{val d=java.time.YearMonth.parse(s);val t=d.lengthOfMonth;var w=0;for(i<-0 to t-1)if(d.atDay(i+1).getDayOfWeek.getValue<6)w+=1;Math.round(100.0*w/t)}

```

Ungolfed version. Try it online!

```
import java.time._
import java.time.temporal._

object Main {
  def main(args: Array[String]): Unit = {
    val f: String => Double = s => {
      val d = YearMonth.parse(s)
      val totalDays = d.lengthOfMonth
      var workingDays = 0

      for (i <- 0 until totalDays) {
        val dayOfWeek = d.atDay(i + 1).getDayOfWeek
        if (dayOfWeek.getValue >= DayOfWeek.MONDAY.getValue && dayOfWeek.getValue <= DayOfWeek.FRIDAY.getValue) {
          workingDays += 1
        }
      }

      Math.round(100.0 * workingDays / totalDays)
    }

    // test cases:
    println(f("2010-05")) // 68
    println(f("2010-06")) // 73
    println(f("1920-10")) // 68
    println(f("2817-12")) // 68
  }
}

```

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