title: Validate a codice fiscale

text:
# Question
Title: Validate a codice fiscale
# Validate a codice fiscale

Every Italian resident/citizen is given a 16-character alphanumeric *codice fiscale*

## Challenge

The final letter is a check code, which is calculated as follows :

* Characters of the code are split up into even and odd character according to their positions (check letter excluded)
* Both sets are replaced according to the following tables :

| ODD CHARACTERS (1st, 3rd...) |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Character | Value | Character | Value | Character | Value | Character | Value |
| 0 | 1 | 9 | 21 | I | 19 | R | 8 |
| 1 | 0 | A | 1 | J | 21 | S | 12 |
| 2 | 5 | B | 0 | K | 2 | T | 14 |
| 3 | 7 | C | 5 | L | 4 | U | 16 |
| 4 | 9 | D | 7 | M | 18 | V | 10 |
| 5 | 13 | E | 9 | N | 20 | W | 22 |
| 6 | 15 | F | 13 | O | 11 | X | 25 |
| 7 | 17 | G | 15 | P | 3 | Y | 24 |
| 8 | 19 | H | 17 | Q | 6 | Z | 23 |

| EVEN CHARACTERS (2nd, 4th...) |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Character | Value | Character | Value | Character | Value | Character | Value |
| 0 | 0 | 9 | 9 | I | 8 | R | 17 |
| 1 | 1 | A | 0 | J | 9 | S | 18 |
| 2 | 2 | B | 1 | K | 10 | T | 19 |
| 3 | 3 | C | 2 | L | 11 | U | 20 |
| 4 | 4 | D | 3 | M | 12 | V | 21 |
| 5 | 5 | E | 4 | N | 13 | W | 22 |
| 6 | 6 | F | 5 | O | 14 | X | 23 |
| 7 | 7 | G | 6 | P | 15 | Y | 24 |
| 8 | 8 | H | 7 | Q | 16 | Z | 25 |

* Sum both sets together
* Get the remainder of sum/26 and replace according to the table

| Remainder | Letter | Remainder | Letter | Remainder | Letter | Remainder | Letter |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | A | 7 | H | 14 | O | 21 | V |
| 1 | B | 8 | I | 15 | P | 22 | W |
| 2 | C | 9 | J | 16 | Q | 23 | X |
| 3 | D | 10 | K | 17 | R | 24 | Y |
| 4 | E | 11 | L | 18 | S | 25 | Z |
| 5 | F | 12 | M | 19 | T |  |  |
| 6 | G | 13 | N | 20 | U |  |  |

## Input

A 16-character *codice fiscale* in the `XXXXXX00X00X000X` form.

Assume the check letter will always be a letter

## Output

Is the *Codice Fiscale* valid (the language truthy value) or not (language falsy value)?

For the purpose of the challenge, we consider a *codice fiscale* to be valid if the calculated check letter corresponds with the input's check letter.

## Examples

```
TMDVSZ30T13L528J -> true
NWWFBE83P20A181A -> false
YNFLJC39E06C956L -> true
YNFLJC39E06C956E -> false

```

## Scoring

This is , the shortest number of bytes wins

# Answer
> 3 votes
# Jelly, ~~33~~ 31 bytes

```
ØWiⱮịÐo“ÐVẈ÷{⁷.ƝİRḟ’Œ?¤’N0¦S26ḍ

```

Try it online!

A monadic link taking a string and returning 1 for valid and 0 for invalid.

## Explanation

```
ØWiⱮ                            | Index of each character in word characters (A-Aa-z0-9)
    ịÐo“ÐVẈ÷{⁷.ƝİRḟ’Œ?¤         | Index odd positions in the list into the 15593538177379092215583486‘th permutation of 1..26; leave even ones alone
                       ’        | Decrease by 1
                        N0¦     | Negate the final value
                           S    | Sum
                            26ḍ | Is divisible by 26

```

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

```
f=([a,...x],s=i=0)=>x+x?f(x,s+g(++i%2?'BAFHJNPRTVCESULDGIMOQKWZYX'[g(a)]:a)):g(a)==s%26
g=x=>1/x?+x:parseInt(x,36)-10

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~165~~ 159 bytes

```
lambda s:chr((sum(ord(x)-48-17*(x>':')for x in s[1:-1:2])+sum(b"! %')-/135! %')-/135\"$24+#&(,.0*6987"[ord(x)-48-7*(x>':')]-32for x in s[:-1:2]))%26+65)==s[-1]

```

Try it online!

*-3 bytes* thanks to @CommanderMaster's amazing observation about removing the constant `v`!

*-3 bytes* by using multiplication instead of indexing on the condition.

---

A function that accepts a parameter `s`, which is the code to be validated.

It returns

```
chr((S_E+S_O)%26+65)==s[-1]

```

That is, evaluates the remainder between the sum of both sets (`S_O` odd characters, `S_E` even characters) and 26, adds 65 to it (i.e. transforms a number `0-25` to `A-Z` using ASCII conversion) and checks if it's equal to the last character of the input.

`S_E` is

```
sum(ord(x)-48-17*(x>':')for x in s[1:-1:2])

```

`x>':'` is a condition that evaluates to true (or 1) if the character `x` is a letter (since its ASCII code is higher than `:`'s). Therefore, it'll subtract 48 from the ASCII code of `x` if its numeric, otherwise it'll subtract 65. It basically maps `'0' -> 0`, ... `'9' -> 9`, `'A' -> 0`, ..., `'Z' -> 25` and sum the resulting values.

`S_O` is

```
sum(b"! %')-/135! %')-/135\"$24+#&(,.0*6987"[ord(x)-48-7*(x>':')]-32for x in s[:-1:2])

```

If you take every ASCII code of the bytestring characters and subtract 32, you will see that it'll match the odd-characters table. So that's a transformation similar to `S_E`'s, but it now maps `'0' -> 0`, ... `'9' -> 9`, `'A' -> 10`, ..., `'Z' -> 35`, get the byte at that bytestring index and subtract 32.

# Answer
> 1 votes
# APL+WIN, 161 bytes

Prompts for string.

```
c←8 2⍴⎕⋄c[7;1]=a[26|+/((('BAKPLCQDREVOSFTGUHMINJWZYX'⍳c[;0])~26),(¯65+⎕av⍳'BAFHJNPRTV')[(n⍳c[;0])~10]),(((n←(⍕⍳10)~' ')⍳c[;1])~10),((a←⎕av[65+⍳26])⍳¯1↓c[;1])~26]

```

Try it online! Thanksto Dyalog Classic

# Answer
> 1 votes
# Perl 5 `-pF`, 137 bytes

```
$c=pop@F;pairmap{$s+=$b=~s|\D|-65+ord$&|er+($a=~/\d/?1+$a*2-($a==1)+2*($a>4):BAKPLCQDREVOSFTGUHMINJWZYX=~/$a/*"@-")}@F;$_=$s%26+65==ord$c

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~36~~ 32 bytes

```
25Ý•D+>∞¢-‹ ŸΔŒ•.IžKIkι`Šèì`(O₂Ö

```

-4 bytes by porting *@NickKennedy*'s Jelly answer.

Input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
25Ý              # Push a list in the range [0,25]
   •D+>∞¢-‹ ŸΔŒ• # Push compressed integer 15593538177379092215583485
     .I          # Get the (0-based) 15593538177379092215583485th permutation of the [0,25]-list:
                 #  [1,0,5,7,9,13,15,17,19,21,2,4,18,20,11,3,6,8,12,14,16,10,22,25,24,23]
žK               # Push constant "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  Ik             # Get the (0-based) index of each character of the input in this string
    ι            # Uninterleave it into two parts
     `           # Pop and push both parts to the stack
      Š          # Triple-swap the three lists on the stack
       è         # Index the 0-based even indices into the permuted list
        ì        # Prepend-merge the two lists back together
         `       # Pop and push all integers separated to the stack
          (      # Negate the last one
           O     # Sum all integers on the stack together
            ₂Ö   # Check whether this sum is divisible by 26
                 # (after which it is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•D+>∞¢-‹ ŸΔŒ•` is `15593538177379092215583485`.
The `15593538177379092215583485` is generated using Jelly's \\$n^{th}\\$ permutation builtin `œ¿`: try it online (minus 1, because 05AB1E uses 0-based indexing and Jelly 1-based indexing).

# Answer
> 0 votes
# Excel ms365, 199 bytes

Assuming input in `A1`:

```
=CHAR(MOD(SUM(MAP(ROW(1:15),LAMBDA(i,TOROW(FIND(MID(A1,i,1),IF(ISODD(i),{"10   2 3 4   5 6 7 8 9","BAKPLCQDREVOSFTGUHMINJWZYX"},{"0123456789","ABCDEFGHIJKLMNOPQRSTUVWXYZ"})),3)-1))),26)+65)=RIGHT(A1)

```

# Answer
> 0 votes
# Funge-98, 108 bytes

```
"NRTS"4(I'0>'v00p
<@.!-+A'g20w1p21-1:g21p20%'+g20+-fg3-+0'*'`9':\-+0'*'`9':

 "$!#%('&

```

Try it online!

Contains non-printable characters, so here is a hex dump:

```
00000000: 224e 5254 5322 3428 4927 303e 2776 3030  "NRTS"4(I'0>'v00
00000010: 700a 3c40 2e21 2d2b 4127 6732 3077 3170  p.<@.!-+A'g20w1p
00000020: 3231 2d31 3a67 3231 7032 3025 1a27 2b67  21-1:g21p20%.'+g
00000030: 3230 2b2d 6667 332d 2b30 272a 1127 6039  20+-fg3-+0'*.'`9
00000040: 273a 5c2d 2b30 272a 1127 6039 273a 0a00  ':\-+0'*.'`9':..
00000050: 080a 100f 1416 181c 1e20 2224 1113 2123  ......... "$..!#
00000060: 1a12 1517 1b1d 1f19 2528 2726            ........%('&

```

# Answer
> 0 votes
# Charcoal, 50 bytes

```
ＦＳ⊞υ⌕⁺α⭆χκι¬﹪⁻⊟υΣＥυ⎇﹪κ²ι⌕α§”$⌈⊟⌈σEζ⊖)"⁷hＹ✂&⊕⧴C”ι²⁶

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a valid code, nothing if not. Explanation:

```
ＦＳ⊞υ⌕⁺α⭆χκι

```

Loop through the input string, converting each character into its index in the string `A..Z0..9`.

```
¬﹪⁻⊟υΣＥυ⎇﹪κ²ι⌕α§”...”ι²⁶

```

Remove the last value, permute alternate elements (permutation string shamelessly stolen from @Arnauld's answer), take the sum, and compare the the removed last value modulo 26.

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


title: Complete a Mystery Sequence

text:
# Question
Title: Complete a Mystery Sequence
Given a sequence of three integers, determine if the sequence is arithmetic (of the form `[a, a+d, a+2*d]`) or geometric (of the form `[a, a*r, a*r^2]`) by outputting a fourth term that completes it (`a+3*d` for arithmetic, `a*r^3` for geometric).

Examples:

```
[1, 2, 3] -> 4 (This is an arithmetic sequence with a difference of 1)
[2, 4, 8] -> 16 (This is a geometric sequence with a ratio 2)
[20, 15, 10] -> 5 (arithmetic sequence, d=-5)
[6, 6, 6] -> 6 (arithmetic with d=0 OR geometric with r=1)
[3, -9, 27] -> -81 (geometric with r=-3)

```
* The input is guaranteed to be a valid arithmetic and/or geometric sequence (so you won't have to handle something like `[10, 4, 99]`)
* None of the inputted terms will be `0` (both `[2, 0, 0]` and `[1, 0, -1]` would not be given)
* For geometric sequences, the ratio between terms is guaranteed to be an integer (ie. `[4, 6, 9]` would be an invalid input, as the ratio would be 1.5)
* If a sequence could be either arithmetic or geometric, you may output either term that completes it
* You may take input as a 3-term array (or whatever equivalent) or as three separate inputs
* This is code golf, so aim for the lowest byte count possible!

# Answer
> 18 votes
# Python, 34 bytes

### -1 thanks to @Arnauld

```
lambda a,b,c:c+(c-b)**2/(b-a or 1)

```

Attempt This Online!

## How?

Uses the fact that the increments form a geometric sequence in either case. (This avoids the longish (in Python) ternary operator.)

Indeed: \\$c+\frac{(c-b)^2}{b-a} = \begin{cases} c+(c-b)=2c-b & \text{if }c-b=b-a \\ c+(c-b)\times \frac c b = \frac{c^2} b & \text{if } \frac c b = \frac b a \end{cases}\\$

# Answer
> 10 votes
# Raku (Perl 6), 13 bytes

A block taking a sequence of length 3 as a single argument. This task is a perfect match for Raku's sequence operator.

```
{($_...*)[3]}

```

Attempt This Online!

# Answer
> 9 votes
# Python 3, 24 bytes

```
lambda a,b,c:c*(a+c)/b-b

```

Try it online!

Note that this fails when \\$ a=0 \\$ or \\$ b=0 \\$, but that seems to be OK for this challenge :). We can verify its correctness:

* For an arithmetic sequence \\$ b-a = c-b \implies 2b = a+c \\$, the formula rightfully produces \\$ 2c-b \\$: $$ \frac{c\*(a+c)}{b}-b = \frac{c\*2b}{b}-b = 2c-b $$
* Likewise, for a geometric sequence \\$ b/a = c/b \implies a = b^2/c \\$, the formula rightfully produces \\$ c^2/b \\$: $$ \frac{c\*(a+c)}{b}-b = \frac{c\*(b^2/c+c)}{b}-b = \frac{b^2+c^2}{b}-b = b+\frac{c^2}{b}-b = \frac{c^2}{b} $$

# Answer
> 7 votes
# JavaScript (ES6), 28 bytes

```
(a,b,c)=>c-2*b+a?c*c/b:2*c-b

```

Try it online!

### Commented

```
(a, b, c) =>    // given the 3 integers,
c - 2 * b + a ? // if the sequence is not arithmetic:
  c * c / b     //   assume it's geometric and return the next geometric term
:               // else:
  2 * c - b     //   return the next arithmetic term

```

# Answer
> 6 votes
# , 28 bytes

```
\(a,b,c)c+(c-b)^2/(b-a+!b-a)

```

Attempt This Online!

Port of @loopy walt's Python answer.

# , 33 bytes

```
\(a,b,c)`if`(c-b-b+a,c*c/b,c+c-b)

```

Attempt This Online!

Straightforward approach.

# Answer
> 5 votes
# Google Sheets, 34 bytes

```
=IF(A3/A2=A2/A1,A3*A2/A1,A3+A2-A1)

```

The formula assumes the sequence is in `A1:A3`.

# Answer
> 4 votes
# Awk, 33 bytes

```
1,$0=$1-2*$2+$3?$2*$3/$1:$2+$3-$1

```

Try it online!

You could remove the `1,` at the start if you assume that the output will not be 0, saving 2 bytes.

# Answer
> 3 votes
# Jelly, 11 bytes

```
I+×÷Ɲ$}E?UḢ

```

Try it online!

A monadic link taking a list of three integers and returning an integer.

## Explanation

```
I           | Increments (differences between consecutive list members)
       E?   | If all equal then:
 +       U  | - Add the increments to the reversed input list
     $}  U  | Else, following as a monad applied to the reversed input list:
  ×         | - Multiply by:
   ÷Ɲ       |   - The result of dividing each pair of neighbouring list members
          Ḣ | Head

```

# Answer
> 3 votes
# Vyxal 3, 13 bytes

```
¯≈[Ṛ+|ᵃ÷Iᵃ×]t

```

Try it Online!

Port of Nick Kennedy's Jelly answer, sort of?

# Answer
> 3 votes
# Alice, 29 bytes

```
3&/O
?+\M@/!]!?-R.n$n?[?-.*~:

```

Try it online!

-4 bytes thanks to Nitrodon!

Uses loopy walt's solution, go upvote them!

```
3&/M\                        Read 3 arguments a b c on the stack
     !]!                     Pop and write c then b on the tape
        ?-R                  Push b on the stack and calculate b-a
           .n$n              if b-a is 0, replace with 1
               ?[?           Push b and c on the stack
                  -.*        Calculate (c-b)^2
                     ~:      Calculate (c-b)*(c-b)/(b-a or 1)
                       ?+    Pop c and calculate c+(c-b)*(c-b)/(b-a or 1)
                         \O@ Output the result

```

# Answer
> 2 votes
# APL+WIN, ~~43~~ 38 bytes

Prompts for integers

```
↑(=/¨a b)/(↑v×↑a←2÷/v),(↑v+↑b←2-/v←⌽⎕)

```

Try it online! Thanks to Dyalog Classic

# Answer
> 2 votes
# Funge-98, 46 bytes

```
<@.+wR-R:VI\OO-R:VIVI(4"FRTH"(4"STRN"
/\OR<@.*

```

Try it online!

# Answer
> 2 votes
# Jelly, 9 bytes

Uses the trick described by loopy walt in their excellent Python answer although the implementation is somewhat different.

```
IQ²÷¥@/+Ṫ

```

A monadic Link that accepts a triple of integers, `[a, b, c]`, that is either arithmetic or geometric and yields the next integer in the series, `d`.

**Try it online!**

### How?

```
IQ²÷¥@/+Ṫ - Link: list of integers, [a, b, c]
I         - forward differences -> [b-a, c-b]
 Q        - deduplicate
             -> if arithmetic: L=[b-a] (potentially [0])
                else:          L=[b-a, c-b] (with no zeros)
      /   - reduce L by:
     @    -   with swapped arguments:
    ¥     -     last two links as a dyad - f(x, y):
  ²       -       square -> x^2
   ÷      -       divide -> x^2/y
             -> if arithmetic: Z=b-a (only one item so reduce does not perform f)
                else:          Z=(c-b)^2/(b-a)
       +  - add {[a, b, c]} (vectorises) -> [a+Z,b+Z,c+Z]
        Ṫ - tail -> c+Z (= d)
             -> if arithmetic: d=c+(b-a)
                else:          d=c+(c-b)^2/(b-a)

```

# Answer
> 2 votes
# Vyxal, 6 bytes

```
+∇/*⁰-

```

Try it Online!

Port of dingledooper's clever formula, go look at that for an explanation of why this works.

```
       # input c, a, b
+      # c+a
 ∇     # rotate stack to b, c, c+a
  /    # c/b
   *   # (c+a) * c/b
    ⁰  # last input (b)
     - # (c+a) * c/b - b

```

This uses four necessary operations (`+/-*`) and two stack-manipulation operations (`⁰∇`). I'm fairly sure that a solution with only one stack-manipulation op is impossible but I'd love to be proven wrong.

# Answer
> 2 votes
# Desmos, 19 bytes

```
f(a,b,c)=c(a+c)/b-b

```

Try It On Desmos!

Port of dingledooper's Python 3 solution, so make sure to upvote that one too!

# Answer
> 2 votes
# C (gcc), 24 bytes

```
f(a,b,c){a=c*(a+c)/b-b;}

```

Another port of dingledooper's answer!

Try it online!

# Answer
> 1 votes
# MathGolf, 6 bytes

```
+╠*k;,

```

Port of *dingledooper*'s Python 3 answer, so make sure to upvote that answer as well!

I/O as floats, and inputs are in the order \\$c,a,b\\$.

Try it online.

**Explanation:**

```
+       # Add the first two (implicit) inputs together: c+a
 ╠      # Divide it by the third (implicit) input: (c+a)/b
  *     # Multiply it by the first (implicit) input: (c+a)/b*c
   k;   # Push the second input, and discard it
     ,  # Subtract it by the third (implicit) input: (c+a)/b*c-b
        # (after which the entire stack is output implicitly as result)

```

The `k;,` could also be `?-Þ` for the same byte-count: Try it online.

```
   ?    # Triple-swap the top three values: a,(c+a)/b,b
    -   # Subtract the top two: a,(c+a)/b-b
     Þ  # Only keep the top value of the stack: (c+a)/b-b
        # (after which the entire stack is output implicitly as result)

```

# Answer
> 1 votes
# Retina 0.8.2, 65 bytes

```
.+
$*
¶1+¶
$'$&
1(?=1*¶1+¶(1+))
$1
(?=1+¶(1+)¶)\1
1
(1+)¶\1¶1+

1

```

Try it online! Takes input on separate lines but link is to test suite that splits on non-digits for convenience. Limited to positive integers due to use of unary arithmetic. Explanation: Uses @dingledooper's formula.

```
.+
$*

```

Convert to unary.

```
¶1+¶
$'$&

```

Add `c` to `a`.

```
1(?=1*¶1+¶(1+))
$1

```

Multiply `a+c` by `c`.

```
(?=1+¶(1+)¶)\1
1

```

Divide that by `b`.

```
(1+)¶\1¶1+

```

Subtract `b` and remove `b` and `c`.

```
1

```

Convert to decimal.

# Answer
> 1 votes
# Charcoal, 16 bytes

```
ＮθＮηＮζＩ⁻÷×⁺θζζηη

```

Try it online! Link is to verbose version of code. Explanation: Trivial implementation of @dingledooper's formula.

35 bytes to validate the input:

```
ＮθＮηＮζ¿⁼⊗η⁺θζＩ⁻⁺ζηθ¿∧θ⁼×ηη×θζＩ÷×ζηθ

```

Try it online! Link is to verbose version of code. Works with edge cases such as `0 0 0`, `1 0 0`, `1 0 -1`. Doesn't output anything if the input is not an arithmetic or geometric sequence.

Notes for both solutions:

* 6 bytes (`ＮθＮηＮζ`) could be saved by requiring the input to be in JSON format.
* Floating-point arithmetic could be used by replacing `÷` with .

# Answer
> 0 votes
# Perl 5 `-ap`, 41 bytes

```
$_=2*($b=<>)-$_-($c=<>)?$c*$c/$b:$c+$b-$_

```

Try it online!

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


# Question
Title: I irradiate your source code, you irradiate your output
Your task is to write a program \\$p\\$ which outputs a string \\$s\\$ with the same length as \\$p\\$, where \\$s \neq p\\$.

If I remove the \\$n\\$th byte from your program to get program \\$q\\$, then either \\$q\\$ outputs \\$s\\$ with the \\$n\\$th byte removed, or it does something else.

Your score is the number of ways a single byte being removed from \\$p\\$ results in a program that does "something else" or that has become a quine, with a lower score being the goal. Ties will be broken by code golf.

*Note that the effective smallest byte count for an answer with score 0 is 2 bytes (not accounting for fractional byte systems).*

# Answer
> 18 votes
# brainfuck, 2 bytes, score 0

```
..

```

Try it online!

Outputs two null bytes.

Removing either `.` leaves `.`, which outputs one null byte. (Try it online!)

# Answer
> 8 votes
# Charcoal, 4 bytes, score 0

```
¹--¹

```

Try it online! Explanation: `¹` on its own outputs a `-`, so the whole program outputs 4 `-`s. (I could have used any two ASCII characters in the middle; I just chose `-` to be confusing.) Removing any character results in a program that outputs 3 `-`s. I need both `¹`s to prevent the program from becoming a (trivial) quine, and I need two `-`s to prevent the `¹`s from being interpreted as `11` when they are adjacent.

# Answer
> 7 votes
# REPL\*, ~~125~~ 90 bytes, score 0

**(or any other R environment in which errors do not halt execution of subsequent commands: entering the program into the R interactive console works fine; alternatively (and as simulated in the ATO link) we can use the command-line option `-e 'options(error=function(){})'`, which would define the language as "`R -e 'options(error=function(){})'`".*

```
x=1;if(x)cat(strrep(x,9*(2)*5-(nchar(readLines(c=stdin(),n=1))<9*(2))))
cat(strrep(1,89))#

```

Attempt This Online!

The strategy here is to write a 2-line program. If the first line runs Ok, it uses the second line as input (and, as a side-effect, prevents the second line from running), and checks that it contains the expected number of characters: if it does, print string `s` (90 `1`s); if it doesn't, print string `s` without one character (all the characters are the same, so this is equivalent to removing the `n`th character for any `n`).
The first line is written to error (and so do nothing) if any character is removed. In this case, the second line won't be used as input, and it will run: it always prints string `s` without 1 character.

The length of the entire program is expressed as `9*(2)*5` (so removing any character will error). For a similar reason, the second line is adjusted to be 18 characters long, so we can check whether its length is less than `9*(2)`.

---

# , 8 bytes, score 8

```
cat(8^8)

```

Attempt This Online!

In principle, we could try to wrap the R+REPL program above into a `tryCatch()` expression to force it to run in base R, but this would already inflate the score to at least 10, and this trivial approach is both shorter and scores better (even though it's rather boring).

# Answer
> 2 votes
# Vyxal, 2 bytes, score 0

```
₴₴

```

Try it Online!

Prints 2 0s. Removing either print without newline prints only 1 0.

# Answer
> 1 votes
# MathGolf, 2 bytes, score: 0

```
⌂⌂

```

Outputs `**`:
Try it online.

If either  is removed, it'll only output a single `*`:
Try it online.

**Explanation:**

```
⌂   # Push "*" to the stack
 ⌂  # Push "*" to the stack again
    # (after which the entire stack is joined together and output implicitly as result)

```

# Answer
> 1 votes
# Score 0

All of these work by repeating one of following commands twice:

* output the accumulator
* print top of stack, when empty default to printing some value (usually 0)
* push something to stack, and language implicitly outputs stack at end

## !@#$%^&\*()\_+, 2 bytes, score 0

```
##

```

Try it online!

## 33/Alphabetti spaghetti/Deadfish~, 2 bytes, score 0

```
oo

```

Try it online! (33)
Try it online! (Deadfish~)
Try it online! (Alphabetti spaghetti)

## Aceto, 2 bytes, score 0

```
pp

```

Try it online!

## Actually, 2 bytes, score 0

```
εε

```

Try it online!

## AlphaBeta, 2 bytes, score 0

```
MM

```

Try it online!

## anyfix, 2 bytes, score 0

```
®®

```

Try it online!

---

# Score 1

All of these work the same way as the zero score solutions, but require an extra character to terminate the program

## Ahead/Backhand, 3 bytes, score 1

```
OO@

```

Try it online! (Ahead)
Try it online! (Backhand)

## axo, 3 bytes, score 1

```
{{\

```

Try it online!

## Hexagony, 3 bytes, score 1

```
!!@

```

Try it online!

---
Tags: code-challenge, radiation-hardening
---


title: Inverse Colombian Function

text:
# Question
Title: Inverse Colombian Function
Let's define a sequence: The **n digit summing sequence** (n-DSS) is a sequence that starts with **n**. If the last number was **k**, then the next number is **k + digit-sum(k)**. Here are the first few n-DSS:

```
1-DSS: 1, 2, 4, 8, 16, 23, 28, 38, 49, 62, 70...
2-DSS: 2, 4, 8, 16, 23, 28, 38, 49, 62, 70, 77...
3-DSS: 3, 6, 12, 15, 21, 24, 30, 33, 39, 51, 57...
4-DSS: 4, 8, 16, 23, 28, 38, 49, 62, 70, 77, 91...
5-DSS: 5, 10, 11, 13, 17, 25, 32, 37, 47, 58, 71...
6-DSS: 6, 12, 15, 21, 24, 30, 33, 39, 51, 57, 69...
7-DSS: 7, 14, 19, 29, 40, 44, 52, 59, 73, 83, 94...
8-DSS: 8, 16, 23, 28, 38, 49, 62, 70, 77, 91, 101...
9-DSS: 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99...

```

For 1, this is A004207, although the first few digits are different due to a slightly different definition. For 3, it's A016052; for 9, A016096.

Today's challenge is to find the lowest n digit sum sequence that a given number appears in. This is called the "Inverse Colombian Function", and is A036233. The first twenty terms, starting with 1 are:

```
1, 1, 3, 1, 5, 3, 7, 1, 9, 5, 5, 3, 5, 7, 3, 1, 5, 9, 7, 20

```

Some other good test cases:

```
117: 9
1008: 918

```

You only have to handle integers greater than 0, and you can take input and output in any standard format. As usual, this is , so shortest answer in each language wins.

# Answer
# Haskell, ~~104~~ ~~64~~ 63 bytes

**(-26 thanks to H.PWiz, additional -14 thanks to Sriotchilism O'Zaic, additional -1 thanks to cole)**

This is a function.

```
f x=[y|y<-[1..],x==until(>=x)(foldr((+).read.pure)<*>show)y]!!0

```

Try it online!

---

Explanation:

```
(foldr((+).read.pure)<*>show)

```

Sequence of composited functions that returns y+digital sum of y. Converts to string first, then does some monad gymnastics to get the sum of the characters and the original number (thanks to Cole).

The `<*>` operator in this context has type and definition

```
(<*>) :: (a -> b -> c) -> (a -> b) -> c
f <*> g = \x -> f x (g x)

```

so we can write the above as

```
\x -> foldr ((+) . read . pure) x (show x)

```

This `read . pure` converts a `Char` into a number, so `(+) . read . pure :: Char -> Int -> Int` adds a digit to an accumulated value. This value is initialized to the given number in the fold.

```
until (>=x) {- digital sum function -} y

```

`until` repeatedly applies a function to its result (in this case, the y+digital sum y) until it meets a requirement specified by a function in the first argument. This gives the smallest y-DSS element that's greater or equal to x.

```
[y | y<-[1..]; x == {- smallest y-DSS element >= x -} ]

```

Infinite lazy list of y's such that the smallest y-DSS element \>= x is actually x. Uses Haskell's list comprehension notation (which I'd also totally forgotten about, thank y'all).

```
f x = {- aforementioned list -} !! 0

```

First element of that list, which is the smallest y that satisfies the requirement of the challenge.
> 12 votes

# Answer
# Python 2, ~~73~~ 71 bytes

-2 bytes thanks to Erik.

```
n=input();k=K=1
while n-k:K+=k>n;k=[k+sum(map(int,`k`)),K][k>n]
print K

```

Try it online!
> 5 votes

# Answer
# Perl 6, 44 bytes

```
->\a{+(1...{a∈($_,{$_+.comb.sum}...*>a)})}

```

Try it online!

Naive solution that checks every sequence until it finds one that contains the input

### Explanation:

```
->\a{                                    }  # Anonymous code block taking input as a
     +(1...{                           })   # Find the first number
            a∈(                       )     # Where the input is an element of
                                ...         # The sequence
               $_,                          # Starting with the current number
                  {            }   # Where each element is
                   $_+             # Is the previous element plus
                      .comb.sum    # The digit sum
                                   *>a      # Until the element is larger than the input

```
> 4 votes

# Answer
# Jelly, 11 bytes

```
D+ƒ$Ð¡€œi⁸Ḣ

```

Try it online!

Full program.
> 3 votes

# Answer
# Ruby, 51 bytes

```
->n{(1..n).find{|i|i+=i.digits.sum while i<n;i==n}}

```

Try it online!
> 3 votes

# Answer
# MATL, 18 bytes

```
`@G:"ttFYAs+]vG-}@

```

Try it online! Or verify the first 20 values.

### Explanation

For input `i`, this keeps increqsing `n` until the first `i` terms of `n`-th sequence include `i`. It is sufficient to test `i` terms for each sequence because the sequence is increasing.

```
`         % Do...while
  @       %   Push iteration index, n. This is the firsrt term of the n-th sequence
  G:      %   Push [1 2 ... i], where i is the input
  "       %   For each (i.e., do the following i times)
    tt    %     Duplicate twice
    FYA   %     Convert to digits
    s     %     Sum
    +     %     Add to previous term. This produces a new term of the n-th sequence
  ]       %   End
  v       %   Concatenate all terms into a column vector
  G-      %   Subtract i, element-wise. This is the do...while loop condition (*).
}         % Finally (this is executed right before exiting the loop)
  @       %   Push current n. This is the output, to be displayed
          % End (implicit). A new iteration will start if all terms of (*) are nonzero
          % Display (implicit)

```
> 3 votes

# Answer
# Pyth, 13 bytes

```
fqQ.W<HQ+ssM`

```

Try it here or check out the **test suite**.

---

### How it works

```
fqQ.W<HQ+ssM`     Full program. Takes input Q from STDIN, writes to STDOUT.
f{...}            Loop over 1,2,3,... and find the first number to yield truthy results when
                     applying the function {...} (whose variable is T = the current integer).
 qQ.W<HQ+ssM`     The function {...}, which will be analysed separately.
   .W             Functional while. While condition A is true, do B.
     <HQ          Cond. A (var: H - starts at T): Checks if H is less than Q.
        +ssM`     Func. B (var: G - G & H are the same): If A, G & H become G+digit sum(G)
                  The last value of this functional while will be the least possible number N
                  in the T-DSS that is greater than or equal to Q.
                  If N = Q, then Q ∈ T-DSS. Else (if N > Q), then Q ∉ T-DSS.
 q                That being said, check whether N == Q.

```

In most languages, it would be easier to loop on the set of the natural numbers, find the first \\$n\\$ terms of the \\$k\\$-DSS (because the digit sum is always at least \\$1\\$ so the repeated addition of this type of quantity cannot result in a value smaller than \\$n\\$) and check if \\$n\\$ belongs in those first \\$n\\$ terms of the \\$k\\$-DSS. In Pyth, however, the available control-flow structures actually make it easier to generate terms until a certain condition is met, rather than a fixed number of terms.
> 3 votes

# Answer
# Forth (gforth), 106 bytes

```
: f
>r 0 begin 1+ dup begin dup i < while dup begin 10 /mod >r + r> ?dup 0= until repeat i = until rdrop
;

```

Try it online!

### Code Explanation

```
: f                \ start a new word definition
  >r               \ store the input on the return stack for easy access
  0                \ set up a counter
  begin            \ start an indefinite loop
    1+ dup         \ add 1 to the counter and duplicate
    begin          \ start a 2nd indefinite loop
      dup i <      \ check if current value is less than the input value
    while          \ if it is, continue with the inner loop
      dup          \ duplicate the current value
      begin        \ innermost loop, used to get the digit-wise sum of a number
        10 /mod    \ get quotient and remainder of dividing by 10
        >r + r>    \ add remainder to current list value
        ?dup 0=    \ check if quotient is 0
      until        \ end the innermost loop if it is
    repeat         \ go back to the beginning of the 2nd loop
    i =            \ check if the "last" value of the current list = the input value
  until            \ if it does, we're done
  rdrop            \ remove the input value from the return stack
;                  \ end the word definition

```
> 3 votes

# Answer
# Jelly, 9 bytes

```
DS+)i$ƬṖṪ

```

A monadic Link accepting a positive integer `n` which yields a positive integer, `a(n)`, the Inverse Colombian of `n`.

**Try it online!** Or see the test-suite.

### How

Effectively we work backwards, repeatedly looking for the value we added to until we cannot find one:

```
DS+)i$ƬṖṪ - Link: integer n
      Ƭ   - Repeat until a fixed point, collecting up:
     $    -   last two links as a monad - f(n):
   )      -     left links as a monad for each - [g(x) for x in [1..n]]:
D         -       decimal digits of x
 S        -       sum
  +       -       add x
    i     -     first (1-indexed) index of n in that list, or 0 if no found
       Ṗ  - pop of the rightmost value (the zero)
        Ṫ - tail

```

Using `13` as an example...

```
D  )  = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[1,0],[1,1],[1,2],[1,3]]
 S    = [  1,  2,  3,  4,  5,  6,  7,  8,  9,    1,    2,    3,    4]
  +   = [  2,  4,  6,  8, 10, 12, 14, 16, 18,   11,   13,   15,   17]
    i 13 = .......................................... 11
    i 11 = .................................... 10
    i 10 = ............... 5
    i 5 = not found = 0
    i 0 = not found = 0
    Ƭ -> [13, 11, 10, 5, 0]
    Ṗ =  [13, 11, 10, 5]
    Ṫ =               5

```
> 3 votes

# Answer
# Python 2, 85 bytes

```
f=lambda n,a=[]:n in a and a.index(n)or f(n,[k+sum(map(int,`k`))for k in a]+[len(a)])

```

Try it online!

This certainly works for all the test cases, plus all of the 1..88 entries given at OEIS; but still I'm not quite sure it's *provably* correct. (This is one of my complaints regarding the Church Of Unit Testing :)).
> 2 votes

# Answer
# Wolfram Language (Mathematica) 14.0+, ~~61~~ 48 bytes

```
Min@Position[Range@#//.j_/;j<#:>j+DigitSum@j,#]&

```

Try it online!

As of version 14.0, `DigitSum` finally exists. Since TIO is on 12.0.1, the linked version uses `Tr@IntegerDigits` (+8 bytes) instead.
> 2 votes

# Answer
# MathGolf, 13 bytes

```
╒môk(É∙Σ+=k/)

```

Try it online!

Great challenge! It caused me to find a few bugs within the implicit pop behavior of MathGolf, which added 1-2 bytes to the solution.

## Explanation (using input \\$3\\$)

```
╒               range(1,n+1) ([1, 2, 3])
 mô             explicit map using 6 operators
   k(           push input-1 to TOS
     É          start block of length 3 (repeat input-1 times)
      ∙Σ+       triplicate TOS, take digit sum of top copy, and add that to second copy
                This transforms the array items to their respective sequences instead
                Array is now [1, 2, 4, 2, 4, 8, 3, 6, 12]
         =      get index of element in array (the index of 3 is 6)
          k/    divide by input (gives 2)
            )   increment (gives the correct answer 3)

```

To prove that this will always work, it is easy to see that `n <= input`, because `input` is the first element of the `input`th sequence. I have technically not proved that this solution is always valid, but it does pass every test case that I have tested.
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
L.ΔIGÐSO+})Iå

```

Try it online!
> 2 votes

# Answer
# Japt, ~~15~~ 14 bytes

The ternary to handle cases where `input=output` is annoying me!

```
@Ç?X±ìx:XÃøU}a

```

Try it

```
@Ç?X±ìx:XÃøU}a     :Implicit input of integer U
@                  :A function taking an integer X as its argument
 Ç                 :  Map each Z in the range [0,U)
  ?                :    If Z>0
   X±              :      Increment X by
     ì             :      Convert X to digit array
      x            :      Reduce by addition
       :X          :    Else X
         Ã         :  End map
          øU       :  Contains U
            }      :End function
             a     :Return the first integer that returns true when passed through that function

```
> 1 votes

# Answer
# Clean, 86 bytes

```
import StdEnv
$n=hd[i\\i<-[1..]|n==while((>)n)(\j=j+sum[toInt d-48\\d<-:toString j])i]

```

Try it online!

Expanded:

```
$ n                    // function `$` of `n` is
 = hd [                // the first
   i                   // integer `i`
  \\                   // for
   i <- [1..]          // each integer from 1 upwards
  |                    // where
   n ==                // `n` is equal to
   while ((>) n) (     // the highest value not more than `n` from
    \j = j + sum [     // `j` plus the sum of
      toInt d - 48     // the digital value
     \\                // for each
      d <-: toString j // digit in the string form of `j`
     ]                 // where `j` is the previous term
    )                  // of the sequence
   i                   // starting with term `i`
  ]

```

It bothers me that `digitToInt d` is longer than `toInt d-48`
> 1 votes

# Answer
# C (gcc), 102 bytes

```
f(n,i,s){for(i=1;n^s;)for(s=i++;s<n;){char*p,j=0,l=asprintf(&p,"%d",s);for(;j<l;)s+=p[j++]-48;}n=~-i;}

```

Try it online!
> 1 votes

# Answer
# JavaScript, 65 bytes

```
n=>eval('for(i=p=1;n-p;p=p>n?++i:p)for(j=p;j;j=j/10|0)p+=j%10;i')

```

Try it online!

---

It also works as C, but cost one more byte

# C (gcc), 66 bytes

```
i,p,j;f(n){for(i=p=1;n-p;p=p>n?++i:p)for(j=p;j;j/=10)p+=j%10;n=i;}

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~83~~, 82 bytes

```
n=>Enumerable.Range(1,n).First(x=>{for(;x<n;x+=(x+"").Sum(c=>c-48));return x==n;})

```

Try it online!
> 1 votes

# Answer
# cQuents, 18 bytes

```
#|1:#bN;A
=A?Z+UDZ

```

Try it online!

## Explanation

```
=A?Z+UDZ      second line - helper function
               first input = A
               second input = n
=A            first term is A
  ?           mode=query, return true if n in sequence, false if n not in sequence
              each term in the sequence equals
   Z+          previous term +
     U   )                     sum (                          )
      D )                            digits (               )
       Z                                      previous term

#|1:#bN;A     main program
               first input = A  (user input)
               second input = n
#|1           n = 1
   :          mode=sequence, return the nth term in the sequence
    #     )   conditional - next term equals next N that evaluates to true
              N increments, any terms that evaluate to true are added to the sequence
               conditional (                      )
     b   )                   second line (      )
      N;A                                  N, A

```
> 1 votes

# Answer
# Husk, ~~14~~ 10 bytes

<sup>-4 thanks to @H.PWiz</sup>

```
V£⁰m¡SF+dN

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 99 bytes

```
: f >r 0 begin 1+ dup begin dup i < while dup 20 for 10 /mod >r + r> next + repeat i = until r> . ;

```

Try it online!

Largely similar to reffu's submission (106 bytes). The golfed parts are:

* Digit sum calculation (-6)
* Final cleanup (-1) by printing some garbage to stdout. (No problem because the result is returned on the top of the stack.)

### How it works

```
: dsum ( n -- n+digitsum ) \ Sub-function. Given n, add its digit sum to n.
  dup                      \ Copy n to form ( n m ) -> extract digits from m and add to n
  20 for                   \ Repeat 20 times (a 64-bit int is at most 20 digits)
    10 /mod >r + r>        \   n += m%10, m = m/10
  next + ;                 \ End loop and discard 0

: f ( n -- ans )    \ Main function.
  >r                \ Move n to the return stack, so it can be referenced using `i`
  0 begin 1+        \ Initialize counter and loop starting from 1
    dup begin       \   Copy the counter (v) and loop
      dup i < while \     break if v >= n
      dsum          \     v += digit sum of v
    repeat          \   End loop
  i = until         \ End loop if n == v
  r> . ;            \ Cleanup the return stack so the function can return correctly
                    \ `r> .` is one byte shorter than `rdrop`

```
> 1 votes

# Answer
# Red, 103 bytes

```
func[n][m: 1 loop n[k: m until[if k = n[return m]s: k
foreach d to""k[s: s + d - 48]n < k: s]m: m + 1]]

```

Try it online!
> 0 votes

# Answer
# Charcoal, 26 bytes

```
ＮθＷ¬№υθ«ＵＭυ⁺κΣκ⊞υ⊕Ｌυ»Ｉ⊕⌕υθ

```

Try it online! Link is to verbose version of code. Uses @ChasBrown's algorithm. If that turns out to be invalid, then for 29 bytes:

```
ＮθＷ¬№υθ«≔⊕ＬυηＷ‹ηθ≧⁺Σηη⊞υη»ＩＬυ

```

Try it online! Link is to verbose version of code. Works by calculating the first member of each digit summing sequence not less than `n`. Explanation:

```
Ｎθ

```

Input `n`.

```
Ｗ¬№υθ«

```

Loop until we find a digit summing sequence containing `n`.

```
≔⊕Ｌυη

```

The next sequence begins with one more than the number of sequences so far.

```
Ｗ‹ηθ

```

Loop while the member of the sequence is less than `n`.

```
≧⁺Σηη

```

Add the digit sum to get the next member of the sequence.

```
⊞υη

```

Push the final member to the list.

```
»ＩＬυ

```

Print the number of lists computed until we found one containing `n`.
> 0 votes

# Answer
# CJam, 25 bytes

```
q~:T,{[){__Ab:++}T*]T&}#)

```

Try it online!
> 0 votes

# Answer
# Gaia, 16 bytes

```
1⟨⟨:@<⟩⟨:Σ+⟩↺=⟩#

```

Try it online!

Returns a list containing the smallest integer.

```
1⟨	      ⟩#	% find the first 1 positive integers where the following is truthy:
	     =		% DSS equal to the input?
  	    ↺		% while
  ⟨:@<⟩			% is less than the input
       ⟨:Σ+⟩		% add the digital sum to the counter

```

# Gaia, 16 bytes

```
1⟨w@⟨:):Σ++⟩ₓĖ⟩#

```

Try it online!

Uses the observation made by Mr. Xcoder. It's not shorter than the other, but it's an interesting approach nonetheless.

```
1⟨	      ⟩#	% find the first 1 integers z where:
  	     Ė		% the input (n) is an element of
  w@⟨:):Σ++⟩ₓ		% the first n terms of the z-th Digital Sum Sequence

```

# Gaia, 16 bytes

```
┅ẋ⟨@⟨:):Σ++⟩ₓĖ⟩∆

```

Try it online!

Third approach not using `N-find`, `#`, but still relying on the same observation as the middle approach. Returns an integer rather than a list.
> 0 votes

# Answer
## Clojure, 106 bytes

```
#(loop[j 1 i 1](if(= j %)i(if(< j %)(recur(apply + j(for[c(str j)](-(int c)48)))i)(recur(inc i)(inc i)))))

```

Try it online!

This is 99 bytes but results in Stack Overflow on larger inputs (maybe tweaking the JVM would help):

```
#((fn f[j i](if(= j %)i(if(< j %)(f(apply + j(for[c(str j)](-(int c)48)))i)(f(inc i)(inc i)))))1 1)

```
> 0 votes

# Answer
# ink, ~~130~~ 127 bytes

```
-(l)
+(i)[+]->l
*(w)[{i}]
~temp n=w
-(o){n<i:
~n+=s(n)
->o
}{n>i:->w}{w}
==function s(n)
{n>9:
~return n%10+s(n/10)
}
~return n

```

Try it online!

* `-3 bytes` by converting to a full program which takes unary input.

This feels too long to not be golfable.

### Ungolfed

```
// This program takes unary input. It passes through the same choice prompt as long as it recieves 1, and execution begins when it recieves 2
-(input_loop)
+(input_value)[+] -> input_loop                 // When this option (option 1) is selected, its read count is incremented. We can access this via the "input_value" variable. We then return to the prompt by going back to the "input_loop" gather
*(which_sequence)[{i}]                          // When this option (option 2) is selected, execution begins. Its read count also serves to keep track of which DSS we're checking.
~temp current_value = which_sequence            // The initial value for the n-DSS is n, of course.
-(sequence)                                     //
{current_value < input_value:                   // If we're still below the value we're looking for, we might find it.
    ~ current_value += digit_sum(current_value) // To get the next number, we add the current number's digit sum
    -> sequence                                 // Then we loop
}
{n > i: -> which_sequence}                      // If we get here, we're at or above our target number. If we're above it, we know it's the wrong sequence and move on to the next one by going back up to option 2. This increments its read count.
{which_sequence}                                // If we get here, we've found the target number, so we output the sequence's number.
// End of main stitch, program ends.

// A function to calculate the digit sum of a number
== function digit_sum(n) ==
{n > 9: // If given a number greater than 9, recurse
    ~ return (n % 10) + digit_sum(n / 10)
}
~ return n // Otherwise, return the input (it's a single digit)

```
> 0 votes

# Answer
# C (gcc), ~~80~~ ~~79~~ 78 bytes

```
i,j;r;v;f(n){for(r=v=n;i=--r;v=n-i?v:r)for(;i<n;)for(j=i;i+=j%10,j/=10;);n=v;}

```

Try it online!

-2 from ceilingcat
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 75 bytes

```
n=>{int a=0,b=0;for(;b!=n;)for(b=++a;b<n;)b+=(b+"").Sum(x=>x-48);return a;}

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-MList::Util=sum -p`, 57 bytes

```
map{$;=$_;"@F"-($_+=sum/./g)or$\||=$;while"@F">$_}1..$_}{

```

Try it online!
> 0 votes

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


title: Expand Sine and Cosine

text:
# Question
Title: Expand Sine and Cosine
Trigonometry has LOTS of identities. So many that you can expand most functions into sines and cosines of a few values. The task here is to do that in the fewest bytes possible.

# Identity list

Well, the ones we're using here.

```
sin(-x)=-sin(x)
sin(π)=0
cos(-x)=cos(x)
cos(π)=-1
sin(a+b)=sin(a)*cos(b)+sin(b)*cos(a)
cos(a+b)=cos(a)cos(b)-sin(a)sin(b)

```

For the sake of golfing, I've omitted the identities that can be derived from these. You are free to encode double-angles and such but it may cost you bytes.

# Input

* You should take in an expression as a string with an arbitrary number of terms consisting of a coefficient and some sine and cosine functions, each with an exponent and an arbitrary number of arguments.
* Coefficients will always be nonzero integers.
* Each argument will be a coefficient, followed by either a single latin letter or pi.
* You can decide whether to take in pi as `pi` or `π`. Either way remember that you're scored in bytes, not characters.

# Output

Output the same expression, but…

* All trig functions are either `sin` or `cos`.
* All arguments of trig functions are single variables, with no coefficients.
* All like terms are combined.
* Terms with a coefficient of 0 are removed.
* All factors in the same term that are the same function of the same variable are condensed into a single function with an exponent.

Note: Leading `+` signs are allowed, but not required. `a+-b` is allowed, and equivalent to `a-b`. If there are no terms with nonzero coefficients, then output either `0` or an empty string.

# Worked Example

We'll start with `sin(-3x)+sin^3(x)`. The obvious first thing to do would be to deal with the sign using the parity identity, leaving `-sin(3x)`. Next I can expand `3x` into `x+2x`, and apply the sine additive identity recursively:

```
-(sin(x)cos(2x)+cos(x)sin(2x))+sin^3(x)
-(sin(x)cos(2x)+cos(x)(sin(x)cos(x)+sin(x)cos(x)))+sin^3(x)

```

Next, some distributive property and like terms:

```
-sin(x)cos(2x)-2cos^2(x)sin(x)+sin^3(x)

```

Now, I expand the `cos(2x)` and apply the same reduction:

```
-sin(x)(cos(x)cos(x)-sin(x)sin(x))-2cos^2(x)sin(x)+sin^3(x)
-sin(x)cos^2(x)+sin^3(x)-2cos^2(x)sin(x)+sin^3(x)
2sin^3(x)-3sin(x)cos^2(x)

```

And now, it's finished!

# Test Cases

In addition to the following, all of the individual identities (above) are test cases. Correct ordering is neither defined nor required.

```
cos(2x)+3sin^2(x) => cos^2(x)+2sin^2(x)
sin(-4x) => 4sin^3(x)cos(x)-4sin(x)cos^3(x)
cos(a+2b-c+3π) => 2sin(a)sin(b)cos(b)cos(c)-sin(a)sin(c)cos^2(b)+sin(a)sin(c)sin^2(b)-cos(a)cos^2(b)cos(c)+cos(a)sin^2(b)cos(c)-2cos(a)sin(b)cos(b)sin(c)
sin(x+674868986π)+sin(x+883658433π) => 0 (empty string works too)
sin(x+674868986π)+sin(x+883658434π) => 2sin(x)

```

…and may the shortest program in bytes win.

# Answer
# Bracmat, 221 bytes

```
(P=F v a b.!arg:((sin|cos):?F.?v)&(!v:@&(!F.!v)|!F$!v)|!arg:%?a_%?b&(P$!a)_(P$!b)|!arg)&(f=i a b n u.1+(!arg:e^(?n*((i|-i):?i)*?u+?b)&(!i*(sin.!u)+(cos.!u))^!n*f$(e^!b)|!arg:%?a_%?b&(f$!a)_(f$!b)|!arg)+-1)&(Z=.f$(P$!arg))

```

Try it online!
> 3 votes

# Answer
# Python3, 841 bytes

Longer than I hoped, but the logic is straightforward.

```
E=enumerate
S,O='sin','cos'
def f(e):
 e=[[(a,b,[([1,-1][j<0]*([1,j]['pi'==C]),C)for j,C in c for _ in range(1,abs(j)+1 if'pi'!=C else 2)],d)for a,b,c,d in i]for i in e]
 P=1
 while P:
  P=0
  for i,a in E(e):
   F=0
   for I,A in E(a):
    if len(A[2])>1:q,*w=A[2];l=[[(A[0],S,[q],1),(1,O,w,1)],[(A[0],S,w,1),(1,O,[q],1)]]if S==A[1]else[[(A[0],O,[q],1),(1,O,w,1)],[(-1*A[0],S,[q],1),(1,S,w,1)]];l=[u+a[:I]+a[I+1:]for u in l];e=e[:i]+e[i+1:]+l;F=1;break
   if F:P=1;break
 r={}
 for i in e:
  R,T={},1
  for a,b,[(C,V)],d in i:
   if C==-1 and'sin'==b:a*=-1
   if'pi'==V:
    if(L:=[[1,-1][abs(C)%2],0][b==S])==0:R,T={},0;break
    else:T*=L*a
   else:R[(b,V)]=R.get((b,V),0)+d;T*=a
  r[M]=r.get(M:=str(sorted(R.items())),0)+T
 return' + '.join(str(b)+''.join(f'{j}{["^"+str(l),""][l==1]}({k})'for(j,k),l in eval(a))for a,b in r.items()if b)

```

Try it online!
> 1 votes

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


title: Doubleouble Talkalk

text:
# Question
Title: Doubleouble Talkalk
# Input

A non-empty string or list of capital letters `k` with length between 3 to 5000.

# Output

A value indicating whether `k` can be expressed as `a+b+b`, where `a` and `b` are non-empty.

# Truthy test cases

```
SSS
SNYYY
SNYY
SNNYY
SNYNY

```

# Falsy test cases

```
FALSYTESTCASES
FALSYFALSYTESTCASES
FALSYTESTCASESXFALSYTESTCASES
FALSYTESTCASESFALSYTESTCASES
SMARTIEATIE

```

# Neglegible cases:

```
XX
lowercase
123
ABC (repeated 2000 times)

```

# Answer
> 9 votes
# JavaScript (ES6), 21 bytes

Takes a string and returns a Boolean value.

```
s=>/.(.+)\1$/.test(s)

```

Try it online!

---

# JavaScript (ES6), 59 bytes

A non-regex solution.

```
s=>(g=i=>s[2*i]&&s.slice(-2*i)==(q=s.slice(-i))+q|g(-~i))``

```

Try it online!

# Answer
> 6 votes
# Haskell \+ hgl, 13 bytes

```
cP$h_*>h_>~ʃ

```

Attempt This Online!

## Explanation

This uses the parser library.

`h_` parses any non-empty string, so we ask if there is a `h_` followed by `h_` and then we feed the output of the second `h_` into `ʃ`. Since `ʃ` parses any fixed string given as input, this means it parses whatever `h_` gave again.

`cP` takes the parser we built and turns it into a function which returns true when there is at least one parse which completely consumes the string.

## Reflection

This is such a simple challenge it's hard for this to get any better, but I have some thoughts:

* `(>~ʃ)` is a pretty common function. It attempts to parse the result of the last parse again. However unless I assigned it a 2 byte name it wouldn't make any savings in this particular case.
* `(h_*>)` might also be useful to have a shortcut for.

# Answer
> 6 votes
# Nekomata \+ `-e`, 4 bytes

```
Jtđ=

```

Attempt This Online!

```
Jtđ=
J       Split the input into a list of parts
 t      Remove the first part
  đ     Check that there are exactly two remaining parts
   =    Check that the two remaining parts are equal

```

# Answer
> 5 votes
# Jelly, 7 bytes

```
ŒHÐƤḊEƇ

```

A monadic Link that accepts a list of characters and yields a non-empty list (truthy) if the input can be expressed as `a+b+b` or an empty list (falsey) otherwise.

**Try it online!**

### How?

```
ŒHÐƤḊEƇ - Link: list of characters, S
  ÐƤ    - for suffixes of S:
ŒH      -   split into half (if odd length first half is longer)
    Ḋ   - dequeue (we don't want to test for a+a, only a+b+b)
      Ƈ - keep those for which:
     E  -   all equal?

```

# Answer
> 4 votes
# Retina, 8 bytes

```
.(.+)\1$

```

Try it online!

# Answer
> 4 votes
# Curry (PAKCS), ~~20~~ 19 bytes

```
f(_:_++b++b)|b>""=1

```

Try it online! with truthy, or

Try it online! with falsy test case.

Thanks for a byte saved by Wheat Wizard.

# Answer
> 4 votes
# C (gcc), 67 bytes

```
n;f(char*s){n=strlen(++s);return~-n&&!bcmp(s-~n/2,s+n%2,n/2)|f(s);}

```

Try it online!

-1 byte from ceilingcat

# Answer
> 2 votes
# Uiua, 45 bytes

```
S←≡(□↙)+1⊃⇡↯⧻.
∊:⊙□♭⊞(□⊐/⊂⇌⊂⊂.).⊐/⊂∵(□S⊐⇌)S⇌.

```

Test pad

# Answer
> 2 votes
# Charcoal, 16 bytes

```
⊙ΦＥθ…⮌θκι⁼ι×²∕ι²

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for `a+b+b`, nothing if not. Explanation:

```
   θ                Input string
  Ｅ                 Map over characters
      θ             Input string
     ⮌              Reversed
    …               Truncated to length
       κ            Current index
 Φ                  Filtered where
        ι           Reversed suffix (is not empty)
⊙                   Any reversed suffix satisfies
              ι     Current reversed suffix
             ∕ ²    First half
           ×²       Repeated twice
         ⁼          Equals
          ι         Current reversed suffix
                    Implicitly print

```

# Answer
> 2 votes
# Vyxal 3, 6 bytes

```
Ḣᶜϩ½≈a

```

Try it Online!

Essentially, a case is truthy if some suffix of the input minus the first character (ensuring a is non empty) can be split into two equal halves.

## Explained

```
Ḣᶜϩ½≈a
Ḣ       # Remove the first character of the string because it could be `a`
 ᶜϩ     # Over all suffixes:
   ½    #   Split into halves
    ≈   #   And test whether both halves are the same
     a  # Output whether any are true.

```

Created with the help of Luminespire.

# Answer
> 2 votes
# Perl 5 `-p`, ~~15~~ 13 bytes

*-2 bytes thanks to @NahuelFouilleul*

```
$_=/.(.+)\1$/

```

Try it online!

# Answer
> 2 votes
# Brachylog, ~~7~~ 5 bytes

*-2 bytes thanks to Unrelated String*

```
ba₁ḍ=

```

Try it online!

### Explanation

```
b      Remove the first character from the input
 a₁    Get a nonempty suffix of the remaining string
   ḍ   Split it into two halves
    =  Assert that both are identical

```

The first `b` is necessary to prevent the prefix from being empty.

# Answer
> 1 votes
# BQN (CBQN), 42 bytes

```
{∨´(≡˝2‿↑⊸⥊)¨2↓»↓}

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 9 bytes

Three different alternatives:

**Explanation:**

```
.œ        # Get all partitions of the (implicit) input-string
  3ù      # Only keep the partitions containing three parts
    ε     # Map over each over each remaining partition:
     ¦    #  Remove the first part
      Ë   #  Check if the remaining two parts are equal
    }à    # After the map: check if any is truthy
          # (which is output implicitly as result)

```

```
.s        # Get all suffixes of the (implicit) input-string
  ¨       # Remove the last suffix (the input itself)
   ε      # Map over each suffix:
    2ä    #  Split it into two equal-sized parts (first part is larger for odd lengths)
      Ë   #  Check that both parts are equal
   }à     # After the map: check if any is truthy
          # (which is output implicitly as result)

```

```
¦         # Remove the first character of the (implicit) input-string
 D        # Duplicate it
  .s      # Pop the copy, and push its prefixes
    2×    # Double each string
      Å¿  # Check if the input minus first character ends with a string
        à # Check if any is truthy
          # (which is output implicitly as result)

```

# Answer
> 1 votes
# Python 3 with regex, ~~43~~ 42 bytes

```
import re
f=re.compile(r'.+(.+)\1$').match

```

Python3 port of the Javascript answer.

Takes a string for input, returns a `re.Match` object as truthy, `None` as falsy.

Try it online!

# Python 3, ~~65~~ ~~59~~ 57 bytes

```
lambda s:any(s.endswith(2*s[i:],1)for i in range(len(s)))

```

Takes a string for input, returns `True` and `False` accordingly.

Try it online!

# Answer
> 1 votes
# Scala 3, 32 bytes

```
s=>".+(.+)\\1$".r.findFirstIn(s)

```

Attempt This Online!

# Answer
> 0 votes
# APL+WIN, 39 bytes

Prompts for string.

```
×+/n=+/¨(n↑¨⊂v)=n↑¨(n←⍳⌊.5×⍴v)↓¨⊂v←⌽1↓⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 0 votes
# Python 3.8, 90 bytes

The function takes as input a string `s`. It returns `0` for True cases, `None` for False ones.

```
def f(s):
 l=len(s)
 for i in range(1,l):
  x=(i+l)//2
  if s[i:x]==s[x:]:return 0
 return

```

Try it online!

---

*Explanation*

The function takes as input a string `s`.

The `i` loop takes substrings of `s` representing `b+b`, starting from the second character in order to leave a non-empty substring `a`.

`x` represents the middle of the substring.

The two halves of the substring are compared: if they are equal, return `0`. If no equal halves are found, return `None`.

# Answer
> 0 votes
# Zsh, 57 bytes

```
repeat $#1-2 {1=${1:1};eval '>${1//${1:0:'{2..$#1}'-1}}'}

```

Attempt This Online!

Outputs via exit code.

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


title: Increment The Time

text:
# Question
Title: Increment The Time
Every digital clock contains a small creature that has to advance the time every minute \[citation needed\]. Due to the popularty of digital clocks and the popularity of catching them in the wild, they are nearly extinct in nature which is why in this challenge we try to automate this task:

Given your string of a given time in the 24h format, the task is to advance this time by one minute.

## Details

* Both the input and output must be strings.
* The time is given as a five character string.
* Both the hour and the minutes are given as a two digit number: if the number is below 10, there will be a leading zero.
* The two numbers are separated by a colon.

## Examples

```
Input    Output
00:00    00:01
00:02    00:03
05:55    05:56
09:59    10:00
12:49    12:50
20:05    20:06
23:59    00:00

```

# Answer
> 62 votes
# Microsoft Excel, 9 bytes

```
=A1+"0:1"

```

Input is in cell `A1`.
Tested on my Mac (Excel for Mac version 16.53) and online at Office.com.

# Answer
> 11 votes
# Bash \+ coreutils date, 17

```
date -d$1+min +%R

```

Try it online!

This assumes everything is in UTC (such as how TIO appears to be set up). If this is not OK, then 4 bytes must be added:

---

# Bash \+ coreutils date, 21

```
date -ud$1UTC+min +%R

```

Try it online!

# Answer
> 11 votes
# x86-16 machine code, ~~61~~ ~~55~~ 54 bytes

```
00000000: be82 008b fe8b d6ad 86c4 9346 56ad 86c4  ...........FV...
00000010: 4037 0430 3d30 367c 1293 4037 0430 3d34  @7.0=06|..@7.0=4
00000020: 327c 03b8 3030 86c4 abb0 305f 86c4 abb8  2|..00....0_....
00000030: 2409 aacd 21c3                           $...!.

```

Listing:

```
BE 0082     MOV  SI, 82H            ; SI point to DOS command line tail
8B FE       MOV  DI, SI             ; save pointer to beginning of string for later
8B D6       MOV  DX, SI             ; save pointer to beginning of string for output
AD          LODSW                   ; load hours digits into AX
86 C4       XCHG AL, AH             ; endian convert
93          XCHG AX, BX             ; save hours in BX
46          INC  SI                 ; skip colon
56          PUSH SI                 ; save string offset to minutes
AD          LODSW                   ; load minutes digits into AX
86 C4       XCHG AL, AH             ; endian convert
40          INC  AX                 ; add one minute
37          AAA                     ; BCD Adjust After Addition!
04 30       ADD  AL, '0'            ; ASCII fix low digit
3D 3630     CMP  AX, '60'           ; is minutes wrap around?
7C 13       JL   NO_CARRY_HOUR      ; if not, skip hours
93          XCHG AX, BX             ; move hours into AX
40          INC  AX                 ; increment hours
37          AAA                     ; BCD Adjust After Addition!
04 30       ADD  AL, '0'            ; ASCII fix low digit
3D 3234     CMP  AX, '24'           ; rolled over to 24 hours?
7C 03       JL   NO_CARRY_DAY       ; if not, skip to convert
B8 3030     MOV  AX, '00'           ; reset hours to '00'
        NO_CARRY_DAY:
86 C4       XCHG AL, AH             ; endian convert
AB          STOSW                   ; write hours string
B0 30       MOV  AL, '0'            ; reset minutes to '00'
        NO_CARRY_HOUR:
5F          POP  DI                 ; minutes string offset to DI
86 C4       XCHG AL, AH             ; endian convert
AB          STOSW                   ; write minutes to output string
B8 0924     MOV  AX, 0924H          ; AL = '$', AH = write string function
AA          STOSB                   ; write DOS string terminator to end of string
CD 21       INT  21H                ; write output to console
C3          RET                     ; return to DOS

```

Thought it would be a more straightforward use of BCD operations, though it gave me a use for the `AAA` instruction so there's that.

Standalone DOS executable. Input via command line, output to console.

### OR...

**21 bytes** if I could take I/O as a packed BCD hex word (`12:59` == `0x1259`), and get to use `AAA`'s bastard step-sibling `DAA`!

```
40          INC  AX             ; increment the time
27          DAA                 ; decimal adjust packed BCD
3C 60       CMP  AL, 60H        ; did minutes reach 60?
7C 0E       JL   DONE           ; if not, do nothing else
32 C0       XOR  AL, AL         ; otherwise, reset minutes to 0
86 E0       XCHG AH, AL         ; swap hours and minutes in AL
40          INC  AX             ; increment the hours
27          DAA                 ; decimal adjust packed BCD
3C 24       CMP  AL, 24H        ; did hours reach 24?
86 E0       XCHG AH, AL         ; real quick, swap hours and minutes back
7C 02       JL   DONE           ; if less than 24, do nothing else
32 E4       XOR  AH, AH         ; otherwise, reset hour to 0
        DONE:
C3          RET

```

# Answer
> 9 votes
# Python 2, 68 bytes

```
def f(s):v=int(s[:2])*60-~int(s[3:]);print'%02d:%02d'%(v/60%24,v%60)

```

Try it online!

# Python 3.8, ~~65~~ 64 bytes

*-1 byte thanks to @Matthew Willcockson*

```
lambda s:f"{(v:=int(s[:2])*60-~int(s[3:]))//60%24:02}:{v%60:02}"

```

Try it online!

# Answer
> 9 votes
# PHP, 35 bytes

```
<?=date("H:i",strtotime($argn)+60);

```

Try it online!

# Answer
> 9 votes
# brainfuck, 216 bytes

```
,++++++++>,>>,>+>,++++>,+<<<[-<<-<-<+>>>>>>->-<<<]>>>[<<-]<<[>>----------<+[<-]<[->------<<<+<+[++++++[>-]>[<<[>>-]>>[<----<-->>->>]<]<<------>]>[<----------<+>>->]]<]<<<[->+>+>>+>>+>+<<<<<<<]>--------.>.>>.>>----.>.

```

Try it online!

The character `:` is the ASCII character after `9`, so the program uses the one provided to it in the input to check if digits need to be carried, allowing it to avoid creating any large constants.

```
[
Read in the string and set up for the comparisons later. Increment minutes.
Subtract ':' from all characters and copy it elsewhere.
Layout:        Cell #  -1  0 1 2 3 4 5 6
        Cell contents  ':' A B _ _ 1 C D
The central 0 and 1 cells allow all of the conditionals to land near each other,
reducing the amount of travel needed in the worst case.
]
,++++++++>,>>,>+>,++++>,+
<<<[-<<-<-<+>>>>>>->-<<<]
# If minutes are 10: Carry
>>>[<<-]<<[
    >>----------<+
    # If tenminutes are 6: Carry
    [<-]<[
        ->------<<<+<+
        # If hours are not 10: Check for 24:00 rollover
        [
            ++++++
            [>-]>[
                <<[>>-]>>[
                    <----<--
                >>->>]
            <]
            <<------
        # If hours are 10: Carry
        >]>[
            <----------<+
        >>->]
    ]
<]
# Undo modifications from the start and print
<<<[->+>+>>+>>+>+<<<<<<<]
>--------.>.>>.>>----.>.

```

# Answer
> 8 votes
# Java (JDK), ~~83~~ 49 bytes

```
i->java.time.LocalTime.parse(i).plusMinutes(1)+""

```

Try it online!

Huge cut-off thanks to Olivier Grégoire

# Answer
> 7 votes
# MATL, 12 bytes

```
YOl13L/+15XO

```

Beaten by Excel... :-D

Try it online! Or verify all test cases.

### Explanation

```
YO     % Implicit input. Convert to date number. The integer part represents date,
       % the fractional part represents time of day
l      % Push 1
13L    % Push 1440 (predefined literal)
/      % Divide. Gives 1/1440, which is 1 minute expressed as fraction of a day
+      % Add
15XO   % Convert to date string with format 15, which is 'HH:MM'
       % Implicit display

```

# Answer
> 6 votes
# Jelly,  ~~20~~  19 bytes

```
ØDṗ2ḣ“ð<‘Œpj€”:ðṙiḢ

```

A monadic Link that accepts a list of characters and yields a list of characters.

**Try it online!**

### How?

Surprisingly tricky to get anything below 22 in Jelly, no time-based functionality while parsing, evaluating and then adding leading zeros where needed is expensive, so I went with constructing all strings as a list and getting the next string cyclically.

```
ØDṗ2ḣ“ð<‘Œpj€”:ðṙiḢ - Link: characters, S
ØD                  - digit characters -> "0123456789"
  ṗ2                - Cartesian power 2 -> ["00",...,"99"]
     “ð<‘           - list of code-page indices -> [24, 60]
    ḣ               - head to -> [["00",..."23"],["00",...,"59"]]
         Œp         - Cartesan product -> [["00","00"],...,["23","59"]]
           j€”:     - join each with colons -> ["00:00",...,"23:59"]
               ð    - start a new dyadic chain, f(Times, S)
                 i  - first 1-indexed index of S in Times
                ṙ   - rotate Times left by that
                  Ḣ - head

```

# Answer
> 6 votes
**Powershell**, **82** or **153** bytes

`get-date ((get-date ($Time=read-host "Enter the time")).addminutes(1)) -uformat %R`

Or, if you want to show the input as well as the output;

```
do {$Time=read-host "Enter the time"
    write-host -nonewline $time `t
    get-date ((get-date $Time).addminutes(1)) -uformat %R
    } while ($Time)

```

# Answer
> 5 votes
# Retina 0.8.2, 32 bytes

```
T`_d`d0`.9?(:59)?$
T`d`0`(24)?:6

```

Try it online! Link includes test cases. Explanation:

```
T`_d`d0`.9?(:59)?$

```

Increment all the digits in `09:59`, `19:59`, `X:59`, `:X9` or just the last digit if nothing else matches. Incrementing `9` automatically rolls over to `0`.

```
T`d`0`(24)?:6

```

Zero out `24:60` and the seconds of `X:60` (X will already have been incremented above so it is correct).

# Answer
> 5 votes
# JavaScript (Chrome / Edge / Node), 50 bytes

Very hackish.

```
s=>(new Date(+new Date([1,s])+6e4)+s).slice(16,21)

```

Try it online!

### Commented

```
s =>              // s = "HH:MM"
  ( new Date(     // generate a date:
      +new Date(  //   generate a timestamp corresponding to:
        [1, s]    //     "1,HH:MM" which is interpreted as
                  //     Mon Jan 01 2001 HH:MM:00
      )           //   end of Date()
      + 6e4       //   add 60000 milliseconds (1 minute)
    )             // end of Date()
    + s           // coerce to a string
  ).slice(16, 21) // extract the updated "HH:MM"

```

# Answer
> 5 votes
# C#, ~~64~~ ~~62~~ 55 bytes

-7 bytes thanks to asherber

```
(x)=>$"{System.DateTime.Parse(x).AddMinutes(1):HH:mm}";

```

dotnetfiddle!

## Old version (62 Bytes)

```
(x)=>System.DateTime.Parse(x).AddMinutes(1).ToString("HH:mm");

```

# Answer
> 4 votes
# Python 3, ~~100~~ 95 bytes

```
from datetime import*
f='%H:%M'
t=lambda s:(datetime.strptime(s,f)+timedelta(0,60)).strftime(f)

```

Try it online!

-5 thanks to @pandubear

Python is terrible at this...

# Answer
> 4 votes
# Ruby `-pl`, 40 bytes

```
$_="#{Time.gm(1,1,~/:/,$`,$')+60}"[11,5]

```

Try it online!

`~/:/` matches the colon in the input (yielding its index, `2`), setting the pre- and post-match regexes `$`` and `$'` to the hour and minute, respectively.

---

# Ruby `-plaF:`, 35 bytes

*Suggested by @dingledooper*

```
$_="#{Time.gm(1,1,1,*$F)+60}"[11,5]

```

Try it online!

The array `$F` is formed by automatically splitting the input at the colon.

---

Both versions perform the following operations:

* convert input to a `Time` object,
* add 60 seconds,
* convert to a string of the form `0001-01-dd hh:mm:00 UTC`, where for the 40 byte version `dd` is either `02` or `03` (the latter only when the input is `23:59`); for the 35 byte version it is `01`,
* extract the 11th to 15th characters.

It's somewhat noteworthy that `Time#gm` internally coerces string arguments to integers.

# Answer
> 4 votes
# C (gcc), ~~71~~ 69 bytes

Thanks to dingledooper for the -2.

The only sneaky things were to reuse the input parameter and cache the format string.

```
i,z;f(s){sscanf(s,z="%02d:%02d",&i,&s);printf(z,(i+s/60)%24,++s%60);}

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 18 bytes

```
23Ý59ÝâT‰J':ýDIk>è

```

Try it online or verify all test cases.

**Explanation:**

```
23Ý                 # Push a list in the range [0,23]
   59Ý              # Push a list in the range [0,59]
      â             # Get the cartesian product of these two lists
       T‰J          # Format each integer to a string with potentially leading 0:
       T‰           #  Take the divmod-10: [n//10,n%10]
         J          #  And join these pairs of digits together
          ':ý      '# Join each inner pair together with ":" delimiter
             D      # Duplicate this list
              Ik    # Get the index of the input in this duplicated list
                >   # Increase it by 1
                 è  # And use it to index into the list
                    # (after which the result is output implicitly)

```

# Answer
> 3 votes
# , ~~46~~ 43 bytes

*-3 bytes thanks to Jonathan Carroll*

Or **\>=4.1, 36 bytes** by replacing the word `function` with `\`.

```
function(t)format(strptime(t,h<-"%R")+60,h)

```

Try it online!

---

Without datetime functions:

### , ~~89~~ 85 bytes

```
function(t,`[`=substr,m=el(t[4,5]:0+1)%%60)sprintf("%02d:%02d",el(t[1,2]:0+!m)%%24,m)

```

Try it online!

# Answer
> 3 votes
# PHP, 40 bytes

```
fn($s)=>date('H:i',strtotime("$s+1min"))

```

Try it online!

PHP relative date formatting at its finest, trying to compress it to the max. Should take in account the DST following the locale

# Answer
> 3 votes
# MathGolf, 24 bytes

```
╟r■gæ├M<Þmò♀+░m╞':u_l=)§

```

Try it online.

**Explanation:**

```
╟r                       # Push a list in the range [0,60)
  ■                      # Take the cartesian product with itself
   g                     # Filter this list of pairs by,
    æ                    # using the following four characters as inner code-block:
     ├  Þ                #  Where the first value of the pair
      M<                 #  Is smaller than 24
         m               # Then map each remaining pair to,
          ò              # using the following eight characters as inner code-block:
           ♀+            #  Add 100 to both integers
             ░           #  Convert both to a string
              m╞         #  Remove the first character (the "1") from both strings
                ':u     '#  Join this pair with ":" delimiter
                   _     # After the map, duplicate the list of all possible times
                    l=   # Get the index of the string-input in this duplicated list
                      )  # Increase it by 1
                       § # And use it to (0-based modulair) index into the list
                         # (after which the entire stack is output implicitly as result)

```

# Answer
> 3 votes
# SQL Server, 36 bytes

```
select left(dateadd(n,1,a),5) from t

```

Try it online (using all of the input values given in the question).

# Answer
> 3 votes
# PowerShell, 33 bytes

```
%{'{0:HH:mm}'-f((Date $_)+'0:1')}

```

Input comes from the pipeline.

Try it online!

Try it in a PS console (Windows or Core):

```
 '00:00', '00:02', '05:55', '09:59', '12:49', '20:05', '23:59'|%{'{0:HH:mm}'-f((Date $_)+'0:1')}

```

## Explanation

**%** is an Alias for the Cmdlet "ForEach-Object", which accepts input from the pipeline and processes each incoming object inside the ScriptBlock {...}
**'{0:HH:mm}'** is the output string; {0:HH:mm} is a placeholder for the first argument of the following **-f** format operator. It contains formatting information to print a DateTime object in 24 hour format.
**-f** is the format operator, which will replace the placeholder with the actual time. Using -f is shorter than calling the .ToString('HH:mm') method.
**((Date $\_)+'0:1')** does the heavy lifting: It first turns the current string coming in from the pipeline ($\_) into a DateTime object by passing it to the Cmdlet **Get-Date**. The 'Get-' is implicit in PS, so leaving it out saves 4 bytes (Disclaimer: **never** use that in a regular script; it slows things down, because PS will search the path for a matching command as well - each time it's called!).
Now that there's a DateTime object on the left side, and PS sees an Add operation, it interpretes the '0:1' as timespan of 1 minute (try `[TimeSpan]'0:1'` in a PS console); this is shorter than using the DateTime's object AddMinutes() method.
The result of the addition is then inserted into the string, output is implicit.

# Answer
> 2 votes
# Scala, 52 bytes

```
java.time.LocalTime.parse(_).plusMinutes(1).toString

```

Try it online!

Straightforward approach: parse string as time information via built-in functionality, add one minute to it, output as string

# Answer
> 2 votes
# Factor, 56 bytes

```
[ ":"without hhmm>duration 1 minutes time+ duration>hm ]

```

This doesn't run on TIO because the `calendar.parser` vocabulary postdates Factor build 1525 (the one TIO uses) by just a bit. Here's a screenshot of running it in build 1889, the official 0.98 stable release:

## Explanation

It's a quotation that takes a string from the data stack as input and leaves a string on the data stack as output. Assuming `"23:59"` is on top of the data stack when this quotation is called...

| Snippet | Comment | Data stack (the bottom is the top) |
| --- | --- | --- |
| ``` ":"without ``` | Remove the colon | ``` "2359" ``` |
| ``` hhmm>duration ``` | Parse a 4-digit string into a duration with hours and minutes | ``` T{ duration f 0 0 0 23 59 0 } ``` |
| ``` 1 minutes ``` | Create a duration of one minute | ``` T{ duration f 0 0 0 23 59 0 }<br>T{ duration f 0 0 0 0 1 0 } ``` |
| ``` time+ ``` | Add two durations and/or timestamps | ``` T{ duration f 0 0 0 23 60 0 } ``` |
| ``` duration>hm ``` | Convert a duration or timestamp to a HH:MM string | ``` "00:00" ``` |

# Answer
> 2 votes
## Batch, 83 bytes

```
@set/ps=
@set/am=6%s::=*60+1%-99,h=m/60%%24+100,m=m%%60+100
@echo %h:~-2%:%m:~-2%

```

Takes input on STDIN. Explanation:

```
@set/ps=

```

Read in the time.

```
@set/am=6%s::=*60+1%-99,h=m/60%%24+100,m=m%%60+100

```

Batch parses leading `0`s as octal, so to allow hours and minutes to be `08` or `09`, `6` is prefixed to the hours and `1` to the minutes. Additionally, the `:` is changed to `*60+` and the resulting string evaluated. The `6` prefix does not change the overall result because `600` hours is exactly `25` days, while the `1` adds `100` minutes so `99` minutes are subtracted to obtain the desired total number of minutes. The total minutes are then divided back into hours and minutes, but with 100 added so that the last two digits can be extracted.

```
@echo %h:~-2%:%m:~-2%

```

Print the last two digits to get the real hours and minutes again.

# Answer
> 2 votes
# Japt, 13 bytes

```
Ð6e4°ÐNi1¹¤¯5

```

Try it

# Answer
> 2 votes
# Julia 1.0, ~~43~~ 42 bytes

```
using Dates
~t="$(Time(t)+Minute(1))"[1:5]

```

Try it online!

# Answer
> 2 votes
# QBasic, ~~132~~ 129 bytes

```
INPUT t$
i=6
1i=i-1+f
x=ASC(MID$(t$,i))-47
f=i=4
x=x<10+f*4AND x
MID$(t$,i,1)=CHR$(x+48)
IF x=0GOTO 1
IF"24"<t$THEN t$="00:00
?t$

```

Try it here!

### Explanation

```
' Read the input time into t$
INPUT t$
' i is the index of the current digit, starting one digit to the right of the string
i = 6
' Label 1 is the start of the loop
1
' Subtract 1 from i, and subtract an additional 1 if f is set (see below)
i = i - 1 + f
' x is the current digit plus 1
x = ASC(MID$(t$, i)) - 47
' f is true (-1) only when i = 4
f = (i = 4)
' If x = 10, or if f is true and x = 6, set x to 0; otherwise, leave it unchanged
x = x < (10 + f * 4) AND x
' Write that digit back into the string t$ at the current position
MID$(t$, i, 1) = CHR$(x + 48)
' Loop if this digit wrapped around to 0
IF x = 0 THEN GOTO 1
' Special case: when t$ is 24:00, wrap around to 00:00
IF "24" < t$ THEN t$ = "00:00"
' Print the final result
PRINT t$

```

# Answer
> 2 votes
# C (clang), 63 bytes

```
f(*s){strptime(s,"%R",s);*s=84;mktime(s);strftime(s,8,"%R",s);}

```

Try it online!

Thanks to @AZTECCO for the "%R" format!!

# Answer
> 2 votes
# Julia 1.0, 66 bytes

```
using Dates;f="HH:MM";g(s)=Dates.format(DateTime(s,f)+Minute(1),f)

```

Try it online!

Using libraries because why not and it's still shorter than Python.

# Answer
> 2 votes
# C (gcc), 101 bytes

I was hoping this would be shorter, but I am posting it despite the length because I think it's an interesting way to compute the answer.

This function modifies the input string so the output is the input. I'm not too familiar with the C golfing rules on this but since it's so long I'm neglecting that issue.

This function treats the input as individual characters, where each column has a 'max' value (the first 5 characters in `u`) and a 'reset' value (last 5 characters in `u`). First the last character of the input string is incremented, then from right to left each character is compared to the max. If any character is greater than its max, it is set to the 'reset' value of that column and the column to the left is incremented.

As described so far, this function will reset after 29:59. To make it reset after 23:59 I used `short *a` to check the first two characters at once to see if they equal `"24"` and if they do, set them to `"00"`.

Also note that I had to modify the test code in order to copy input strings into writable memory.

Improvements are welcome, I think I'm out of ideas on this one.

Thanks to att for -22 bytes, a bugfix, and some awesome golfing!

```
c;f(char*x){for(x[c=4]++;~c;)x[--c]+=x[c]>"29:59"[c]&&(x[c]=c-2?48:58);*x<49&&x[1]==52?*x=x[1]=48:0;}

```

Try it online!

# Answer
> 1 votes
# Red, 85 bytes

```
func[s][p: func[t][pad/left/with t 2 #"0"]s:(load s)+ 0:1 rejoin[p s/1 % 24":"p s/2]]

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 26 bytes

```
':¡`©59%(d+24%®>60%‚т‰J':ý

```

Try it online!

I am sorry.

-1 byte fix thanks to Kevin Cruijsen!!

# Answer
> 1 votes
# Vyxal, 25 bytes

```
24ʁ60ʁẊƛƛS2↳ð0V;\:j;:?ḟ›i

```

Try it Online!

What a mess. Handling 0-padding, *and* some slightly cursed vectorising, was a pain.

```
24ʁ                       # 0...23
   60ʁ                    # 0...59
      Ẋ                   # Cartesian product
       ƛ           ;      # Map...
        ƛ      ;          # Map...
         S                # Stringify
          2↳              # pad left to length 2 (with spaces, we really need zfill)
            ð0V           # Replace spaces with zeroes
                \:j       # Join by colons
                     ?ḟ   # Find input in this
                       ›  # Increment
                    :   i # Index into this

```

# Answer
> 1 votes
# Twue, 123 bytes

```
a::>*
:59$::=$:00
23$:::=00:
0$::=1
1$::=2
2$::=3
3$::=4
4$::=5
5$::=6
6$::=7
7$::=8
8$::=9
9$::=$0
^_::=!_^
!_::~_
::=
^a$
```

Try it on the website!

Works by taking input through `a`, having two replacement rules governing roll-over (`:59` -\> `:00` and add 1, `23$:` -\> `00:`). Then, we have a rule for incrementing, rolling over only when we increment a `9`. After that, we output everything.

# Answer
> 1 votes
# Haskell, 130 bytes

```
import Text.Printf
f(a:b:c:d)|[m,h]<-map read[d,a:[b]]::[Int]=[mod(m+1)60,mod(h+m`div`59)24]
g s|[m,h]<-f s=printf"%0.2d:%0.2d"h m

```

Try it online!

Haskell is missing, hope to see a better one because I feel like mine is a bit messy

* `f` reads the input string and increments the values properly
* `g` prints/converts back values using C-like formatting of Text.Printf

# Answer
> 1 votes
# Perl 5 `-F:`, ~~67~~ 64 bytes

*~~63~~ 60 bytes for code; +4 bytes for -F switch*
*-3 bytes thanks to erlik*

```
@F=++$F[0],0if++$F[1]>59;$F[0]*="@F"<24;printf"%02d:%02d",@F

```

Try it online!

Ungolfed version:

```
if (++$F[1] > 59) {
    @F = (++$F[0], 0);
}
$F[0] *= "@F" < 24;
printf("%02d:%02d", @F);

```

# Answer
> 1 votes
#### Slim Sharp 46 Bytes

```
P(T.Parse(t).AddMinutes(1).ToString("HH:mm"));

```

Try it Online!

##### How it Works

```
P(                               // Write the contents to the console.
  T.Parse(t)                     // Parse the input as a date time object.
            .ToString(           // Output the date time object as a string.
                      "HH:mm"    // Format the output in 24 hour time with hours and minutes only.
                             )); // End statement.

```

# Answer
> 1 votes
# Zsh builtins (no date utils), 66 bytes

Reinventing the wheel... Try it Online!

```
m=$[(${1:3}+1)%60]
printf %02d:%02d $[(${1:0:2}+(m==0?1:0))%24] $m

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 47 bytes

```
StringTake[ToString@DatePlus[#,1/1440],-{8,4}]&

```

Try it online!

# Answer
> 1 votes
# Python 3.8, 66 bytes

```
lambda t:f'{(int(t[:2])+((m:=(int(t[3:])+1)%60)<1))%24:02}:{m:02}'

```

Try it online!

A slightly different approach to @dingledooper's answer (and 2 bytes longer ), but the same basic idea.

# Answer
> 1 votes
# **PowerShell, 45 bytes**

`(Get-date $x).AddMinutes(1).ToString("HH:mm")`

Try it online

# Answer
> 1 votes
# Visual Basic, 49 bytes (format command)

```
Dim ins$, out$

ins = "20:21"
out = Format$(DateAdd("n", 1, TimeValue(ins)), "hh:mm")

```

Uses internal time functions.

# Answer
> 1 votes
# Python 3.8, 86 bytes

Little late on this one, but haven't done code golf in a long time and was bored :)

**EDIT: -8 bytes**

```
lambda s:'%02d:%02d'%([x:=int(s[:2]),[x+1,0][x>22]][(y:=int(s[3:])+1)>59],[y,0][y>59])

```

Try it online!

# Answer
> 1 votes
# Python 3.8 (pre-release), 88 bytes

```
def f(s):h,m=int(s[:2]),int(s[-2:]);m=(m+1)%60;m or(h:=(h+1)%24);return f'{h:02}:{m:02}'

```

Try it online!

Very straightforward solution here. Nowhere near competitive and nothing novel, but I enjoyed this! I learned a new trick along the way:

`m or(h:=(h+1)%24)` is equivalent to `if m<1:h=(h+1)%24` and the same length, but allows the whole function to be collapsed into one line with semicolons, saving four characters. Without that, this would be four lines.

```
def f(s):
 h,m=int(s[:2]),int(s[-2:]);m=(m+1)%60
 if m<1:h=(h+1)%24
 return f'{h:02}:{m:02}'

```

Other fun equivalences I learned today:

`m=(m+1)%60` is the same length as
`m+=1;m%=60`

`return f'{h:02}:{m:02}'` is the same length as
`return'%02d:%02d'%(h,m)`

# Answer
> 0 votes
In Go you can do this 153 bytes

```
package main

import (
    "fmt"
    "time"
    "os"
)

func main() {
    t,_ := time.Parse(`15:04`, os.Args[1])
    fmt.Print(t.Add(time.Minute).Format(`15:04`))
}

```

Try it online

# Answer
> 0 votes
# , 9 bytes

```
-3!1+-5!x

```

# , 14 bytes:

```
string 1+"U"$x

```

## Explanation

Q is evaluated from right to left:

```
         "U"$x          // Cast input x into the minutes types
       1+               // Add one (automatically casted into minutes)
string                  // Cast to string

```

For this specific input string, the casting part can also be written as

```
parse x

```

Resulting in a quite readable 16 bytes:

```
string 1+parse x

```

Replacing `string` and `parse` with the K internal function equivalents (`-3!` and `-5!` respectively) we get:

```
-3!1+-5!x

```

# Answer
> 0 votes
# Python 3.8, ~~118 114 113~~ 112 bytes

**New version**

```
i=input();t=[-1]*59+[59];h=[0]*24+[-23];a=int(i[:2]);b=int(i[3:]);print(f'{a+h[a+int(t[b]/30)]:02}:{b-t[b]:02}')

```

**Old version:**

```
i=input();t=(1,0)*59+(-59,1);h=[0]*24+[-23];a=int(i[:2]);b=int(i[3:]);print(f'{a+h[a+t[b*2+1]]:02}:{b+t[b*2]:02}')

```

**Older version:**

```
i=input();t=[(1,0)]*59+[(-59,1)];h=[0]*23+[-24];a=int(i[:2]);b=int(i[3:]);print(f'{a+h[a]+t[b][1]:02}:{b+t[b][0]:02}')

```

Try it here!

**Cleaner version**

```
i=input()
t=[1]*59+[-59]
h=[0]*24+[-23]
a=int(i[:2])
b=int(i[3:])
print(f'{a+h[a+int(t[b]/-30)]:02}:{b+t[b]:02}')

```

A somewhat dumb but interesting approach I tried, I am pretty sure I can probably shorten this somewhere by 15-20~ Bytes, I will have to check it again later. The method uses two lookup arrays to figure out what to do with the date. Its worse than the other answers, but I thought its interesting enough to leave in after golfing it a bit. I am not really good at this yet haha.

Some thoughts that would be interesting to discuss, I see a few places where I can see an improvement being possible, but not sure how:

1. In the part (`a=int(i[:2]);b=int(i[3:]);` this saves a number of bytes since I use a and b alot, but its still a very... ugly solution for the lack of a better word, I looked into `a,b=map(int,i.split(":"))` which looks neater but unfortunately has the exact same size. I am still looking for a better solution here though.
2. I really hate how the lists/tuples are initialized, must be a better way..

Edit: I legitimately have no idea how I came up with this madness, but some weird maths helped me remove an extra byte, somehow haha...

I am certain I can push this further later..

Dang, just as I posted this I thought of a simple change with the signs that did save me another byte.

# Answer
> 0 votes
# Knight (v2.0-alpha), 70 bytes

```
;=t+1+*+0=iP60Gi 3 2O++G=x+'0'%/t 60 24-Lx 2 2':'(G=x+'0'%t 60-Lx 2 2)

```

Try it online!

# Answer
> 0 votes
# Scala, 106 bytes

Golfed version. Try it online!

```
def f(s:String)={val g=DateTimeFormatter.ofPattern("HH:mm");LocalTime.parse(s,g).plusMinutes(1).format(g)}

```

Ungolfed vesion. Try it online!

```
import java.time._
import java.time.format.DateTimeFormatter

object Main {
  def f(s: String): String = {
    val formatter = DateTimeFormatter.ofPattern("HH:mm")
    val time = LocalTime.parse(s, formatter)
    val newTime = time.plusMinutes(1)
    newTime.format(formatter)
  }

  def main(args: Array[String]): Unit = {
    val s = Array("00:00", "00:02", "05:55", "09:59", "12:49", "20:05", "23:59")
    val r = Array("00:01", "00:03", "05:56", "10:00", "12:50", "20:06", "00:00")

    for (i <- s.indices) {
      val result = f(s(i))
      println(s"${s(i)} => $result (should be: '${r(i)}')")
    }
  }
}

```

# Answer
> 0 votes
# Vyxal 3, 21 bytes

```
24ʀ60ʀẊƛᵛ2Þ0':j]:?Ḟꜝi

```

Try it Online!

Same as Vyxal 2, might be golfable with modular arithmetic tricks but I doubt it

# Answer
> 0 votes
# Go, 95 bytes

```
import."time"
func f(s string)string{F:="15:04"
t,_:=Parse(F,s)
return t.Add(Minute).Format(F)}

```

Attempt This Online!

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