# Question
Title: I uppercase the source code, you reverse the input!
*It's one of these again :D*

Your task, if you wish to accept it, is to write a program/function (**without any uppercase letters**) that outputs/returns its string input/argument. The tricky part is that if I convert your source code to uppercase, the output must be reversed.

For simplicity, you can assume that the input is always a single line string containing only ASCII letters (`a-z`), digits (`0-9`), and spaces.

You do not need to handle empty input.

## Example

Let's say your source code is `abc` and its input is `hello`. If I write `ABC` instead and run it, the output must be `olleh`.

# Answer
> 47 votes
# 05AB1E, 1 byte

```
r

```

Try it online lowercase or uppercase!

Finally a question which I (a dumb brain) can answer! Thanks for this easy, yet fun challenge! (I do feel great, even though it requires little effort to make an answer in 05AB1E.)

### Wait, how?

```
r # reverses the stack. (Which literally does not do anything since only the
  # implicit input is in the stack)
R # actually reverses the top string of the stack (Which is the implicit input).
  # at the end, the input is automatically printed.

```

# Answer
> 42 votes
# Python 3,  ~~61 50 49~~  48 bytes

-1 thanks to benrg!

```
r=-1;ʳ=1;ᵖʳᵢⁿᵗ(ᵢⁿᵖᵘᵗ()[::r])

```

**lower-cased / upper-cased**

This works because

1. PEP-3131 was implemented in Python 3.0; and
2. These are the minimal length Unicode characters with no upper-case version which also normalise under the Normalization Form Compatibility Composition (NFKC) transformation to the basic latin characters one would normally use - TIO.

Note that identifiers, like `r` and the function names `print` and `input`, may be written like this but not keywords, like `def` or `lambda`.

(See the upper-casing of the code.)

# Answer
> 15 votes
# Python 3, 48 bytes

```
ᵖʳᵢⁿᵗ(ᵢⁿᵖᵘᵗ()[::b'b'[0]%3-1])

```

Lower: Try it online!

```
ᵖʳᵢⁿᵗ(ᵢⁿᵖᵘᵗ()[::B'B'[0]%3-1])

```

Upper: Try it online!

You can also verify that the upper program is truly uppercase.

---

It's unlikely we can write a program for Python 3 just using ASCII - we have no `def`, no `lambda`, and no builtin function calls. Also, all the properties of existing builtin objects are lowercase so we can't access those either. So instead our strategy is to look for Unicode characters that:

* Are not uppercase
* NFKC normalise to the character we want
* NFKC normalise to the character we want even after uppercasing

The following code does exactly that.

```
from unicodedata import normalize
for c in 'printinput':
  for i in range(0x10ffff):
    if not chr(i).isupper() and normalize('NFKC', chr(i)) == normalize('NFKC', chr(i).upper()) == c:
      print(chr(i))
      break
  else:
    raise Exception('no')

```

# Answer
> 12 votes
# Jelly, 1 byte

**lower-cased / upper-cased**

### How?

```
ṛ - Main Link: list of characters, S
ṛ - right argument (implicitly S)
  - implicitly print

Ṛ - Main Link: list of characters, S
Ṛ - reverse
  - implicitly print

```

# Answer
> 8 votes
# APL (Dyalog Unicode), 10 bytes (SBCS)

Anonymous tacit prefix function.

```
⌽⍣('a'∊⎕a)

```

Try it online!

`⌽⍣(``)` apply reverse the following number of times:

`'a'∊⎕a` is "a" a member of the uppercase **a**lphabet? (0)

### Uppercased

```
⌽⍣('A'∊⎕A)

```

Try it online!

`⌽⍣(``)` apply reverse the following number of times:

`'A'∊⎕A` is "a" a member of the uppercase **A**lphabet? (1)

---

In Dyalog APL, `⎕A` is case-insensitive and always refers to the uppercase alphabet.

# Answer
> 8 votes
# Perl 5 `-p`, ~~33~~, ~~25~~, 22 bytes

Thank's to @DomHastings who also had the same idea

```
m;$_=/.(?{$\=$&.$\})^/

```

uppercase

```
M;$_=/.(?{$\=$&.$\})^/

```

Try it online!

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

Takes and returns an array of characters.

### In lowercase

```
s=>s.map?s:s["\162\145\166\145\162\163\145"]()

```

Try it online!

### In uppercase

```
S=>S.MAP?S:S["\162\145\166\145\162\163\145"]()

```

Try it online!

---

# JavaScript (ES6),  ~~74~~  73 bytes

*Saved 1 byte thanks to @Shaggy*

Takes and returns a string.

### In lowercase

```
s=>s.big?s:[...s]["\162\145\166\145\162\163\145"]()["\152\157\151\156"]``

```

Try it online!

### In uppercase

```
S=>S.BIG?S:[...S]["\162\145\166\145\162\163\145"]()["\152\157\151\156"]``

```

Try it online!

# Answer
> 7 votes
# , 122 bytes

```
`\103`=`\162\145\166`
`\151\156\164\124\157\125\164\1468`(c(`\165\164\1468\124\157\111\156\164`(`\163\143\141\156`(,""))))

```

try it online!

TRY IT ONLINE!

Includes only one letter, the lone `c` in the middle. The rest uses octal codes to get the equivalent of

```
C=rev
intToUtf8(c(utf8ToInt(scan(,""))))

```

With the lowercase `c`, the `c` makes no difference: we convert the input to integers, concatenate it with nothing, and convert back to characters. With an uppercase `C`, the integer vector in the middle gets reversed before being converted back.

# Answer
> 6 votes
# Ruby `-p`, ~~51~~ ~~49~~ ~~47~~ 46 bytes

*Saved a byte by using a shorter lexicographical comparison taken from @WheatWizard's Haskell answer.*

### Lowercase

```
?a<?_&&(f=->_{/.$/?($_=$`;f[_+=$&]):$_=_})['']

```

Try it online!

`?a<?_` tests whether the character `a` is lexicographically less than the character `_`. The test returns `false`, short-circuiting the `&&` operator so that none of the remaining code is actually executed. The input is printed automatically thanks to the `-p` flag.

### Uppercase

```
?A<?_&&(F=->_{/.$/?($_=$`;F[_+=$&]):$_=_})['']

```

Try it online!

Now we test whether `A` is lexicographically less than `_`. Here the comparison returns `true` so we proceed past `&&`. The code after `&&` defines and calls a recursive lambda that reverses the input, which (because of `-p`) has been stored in the predefined global variable `$_`:

```
(F=->_{      # define a lambda F with parameter _
  /.$/?(     # if $_ contains at least one character, match the last one, then
    $_=$`;     # remove that character from $_
    F[_+=$&]   # recursively call F, appending that character to _
  ):$_=_     # else set $_ to _, which now contains the full reversed input
})['']       # call F, initialising _ to the empty string

```

Finally, `$_` (now containing the reversed input) is printed automatically thanks to the `-p` flag.

# Answer
> 6 votes
# Haskell, 38 bytes

```
_0(_1:_2)|'a'<'_'=_0 _2++[_1]
_0 _1=_1

```

Try it online! (lowercase)

```
_0(_1:_2)|'A'<'_'=_0 _2++[_1]
_0 _1=_1

```

Try it online! (uppercase)

Haskell requires that any variable name beginning with a capital letter is constructor of a declared type. This basically means we can't have any identifiers that start with a letter. (I think the options we actually have are `LT`, `GT`, and `EQ` but I wasn't able to find a use for any of these.) Luckily it is possible to write haskell programs without letters. We can start variable names with `_` and we add numbers to the end to make it a valid name (certain symbols would work too).

To detect that which mode we are in we use the fact that strings change and do a comparison between a changing and static string, `'a'<'_'` evaluates to `False` while `'A'<'_'` is true.

# Answer
> 5 votes
## Windows NT Batch + coreutils, 28 bytes

```
@if %os:~9%==t (tac)else cat

```

Explanation: `%OS%` contains `Windows_NT` and the substring starting at position `9` is compared with the letter `t`. If the batch file is uppercased then the comparison succeeds and `tac` is invoked otherwise `cat` is invoked.

# Answer
> 5 votes
# , 21 14 bytes

```
|.^:({.\:'a_')

```

Try it online!

*-7 bytes thanks to Adam!*

Taking inspiration from Adam's APL answer.

## how

* `|.^:` Reverse the following number of times...
* `:({.\:'a_')` Grade down `\:` the string `a_` and take the first element `{.`.
    + "Grade down" returns a list of indexes for the string, sorted descending. Thus `\:'abc'` would return `2 1 0`, for example.
    + "Grade down" will thus return `0` for the string `a_`, and `1` for the string `A_`, since `_` is between `a` and `A` in the ascii alphabet.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 24 bytes

```
#[[i=1;i^2;;-i^2;;i^2]]&

```

Try it online!

`I` is the built-in symbol for the imaginary unit \\$i\\$. Its value cannot be overridden without `Unprotect`ing it first.

# Answer
> 4 votes
# APL (Dyalog Extended), 9 bytes

```
⌽⍣(<×'a')

```

Try it online (both lower and upper)!

In Extended, `×` (signum) on letters queries the letter case, giving -1 for lowercase and 1 for uppercase. Then `<` has implicit left arg of 0, so it tests if the right arg is positive (1) or not (0). Therefore, `<×'a'` evaluates to 0 and `<×'A'` evaluates to 1.

# Answer
> 4 votes
# V (vim), 2 bytes

Try it online!

And uppercased:

Try it online!

Hexdump:

```
00000000: 76e6                                     v

```

## How?

`v` enters 'visual mode' and begins selecting characters. At first, only 1 character will be selected. Then `æ` reverses every character that is selected. Reversing only 1 character does nothing.

But `V` will select every character on the current line, and then `æ` flips the whole line.

# Answer
> 4 votes
# Forth (gforth), 61 bytes

```
: f 'a 65 = if bounds 1- swap 1- -do i c@ emit 1 -loop then ;

```

try it online! TRY IT ONLINE!

A challenge where the case insensitivity of Forth has a use ... except that you don't have a string reversal built-in, so you have to loop through the string itself in reverse.

Almost all words in Forth are case-insensitive. The only case-sensitive part in the code is `'a` or `'A`, where the char's ASCII code (97 for `a`, 65 for `A`) is pushed to the stack. So we can compare it with a (trivially case-insensitive) numeric literal `65`. If they're equal, the string is printed in reverse. Otherwise, the string is returned as-is.

# Answer
> 3 votes
# Brachylog, 3 bytes

```
ṡ↔|

```

and

```
Ṡ↔|

```

Try it online!

```
ṡ↔
ṡ   if input is a square matrix,
Ṡ   if input is a string,
 ↔   it is reversed
  | otherwise return input unaltered

```

# Answer
> 3 votes
## PowerShell 7+, 56, 35 bytes

```
-join"$args"['a'[0]-97?99..0:0..99]

# save as golf.ps1 and call .\golf.ps1 "string"
# e.g. (running in anonymous function &{} for demo):

PS C:\> &{-join"$args"['a'[0]-97?99..0:0..99]} '123 Alice'
123 Alice
PS C:\> &{-JOIN"$ARGS"['A'[0]-97?99..0:0..99]} '123 Alice'
ecilA 321

```

With golfing suggestions from mazzy.

Assuming the string is \<= 100 characters. Change both the 99s to 1e5 notation for +2 bytes, much longer inputs, and much much slower code.

### old 56 byte version

```
&{$a="$args";(gv a).name[0]-97?-join$a[$a.length..0]:$a}

e.g.

PS C:\> &{$a="$args";(gv a).name[0]-97?-join$a[$a.length..0]:$a} "123 Alice"
123 Alice

PS C:\> &{$A="$ARGS";(GV A).NAME[0]-97?-join$A[$A.LENGTH..0]:$A} "123 Alice"
ecilA 321

```

The parameters to the anonymous function `{}` appear in the automatic variable `$args` and get stored in variable `$a`. String quotes `"$args"` cast to a single string. PowerShell is indifferent about the case of variable names, command names, property names, operator names, etc. so all the code runs in either case. `gv` is `get-variable` which looks for the `a` variable, finds its `.Name` (`a` or `A` depending on the case of the script - case is preserved), gets character \[0\] which is `a` or `A` again but this time as a `[char]` type, subtracts 97 (lowercase `a` value in ASCII), and `? :` ternary operators whether that hit zero or non-zero, and either prints the original or reverse-indexes the characters and joins them into a reversed string. Printing is implicit. `&{}` runs the anonymous function.

NB. TIO.Run only has PowerShell 5 or 6 at the time of writing, and ternary ?: is not in that version.

# Answer
> 3 votes
# Pip, 6 bytes

```
[r_]@1

```

This is a function solution. Since it relies on the recently added unary `R` operator, it doesn't work on TIO, but a similar 7-byte version does:

```
[rv_]@2

```

try it online! or TRY IT ONLINE!

### Explanation

Lowercase:

```
[  ]    Make a list containing
 r       A random number between 0 and 1;
  _      The identity function
    @1  Get the item at index 1 (the identity function)

```

Uppercase:

```
[  ]    Make a list containing
 R_      A function that reverses its argument
    @1  Get the item at index 1, with cyclical indexing (the function)

```

The TIO version is the same idea, but uses the `RV` operator for reverse. It therefore has three items in the lowercase list (including `v`, which is -1) and gets the function using index 2 instead of 1.

# Answer
> 3 votes
# JavaScript (V8), 46 44 then by tch: 37 bytes

```
$=([o,...a])=>o?o.sub?o+$(a):$(a)+o:a

```

Try it online!

Thanks to tsh for saving 7 bytes!.

Recursive function `$` takes a string and destructures it into the first character `o` and an array `a` of the remaining characters.

If lower case, `o` has a property `sub` it returns the forward string `o+$(a)`. Otherwise, `O` has no property `SUB` and it returns the reverse string `$(A)+O`.

The final iteration happens when `$` is called with and empty array so there is no `o`. Here it returns `a`, an empty array `[]` which acts as and empty string `""` in string addition.

# Answer
> 3 votes
# Klein 0X0, 68 bytes

*Works in both 000 and 010*

## Lower case

```
"a`"1+-+?@      \
/!?:    (0)?/!?:<@?
>$:?!\?>:?!\\(  /
\   (/ \  )/

```

Try it online!

## Upper case

```
"A`"1+-+?@      \
/!?:    (0)?/!?:<@?
>$:?!\?>:?!\\(  /
\   (/ \  )/

```

Try it online!

---

Most of this is just a program that reverses the input, which is not exactly easy in Klein.

```
>:?!\?)0(    :?!\?@
\  (//!?:<?/!?:$<
     \)  / \(   /

```

Try it online!

To do the condition we have the very simple

```
"a`"1+-+?@

```

Which is an expression that is exactly zero, but becomes something else when `a` is capitalized. This is pretty much the exact method used by every other answer. The `?@` means that when it is zero it halts immediately (a cat program). Otherwise we continue execution to the reverse program bit.

# Answer
> 3 votes
# Raku, 28 bytes

```
{.?"{'flip'~^'    '}"()||$_}

```

Try it online!

* `$_` is the input to the function. Method calls lacking an explicit invocant are called on it.
* `flip` is the method to reverse a string.
* `$obj."name"()` is the syntax to call a method where the name is a string. The double quotes can contain interpolated values as usual.
* `$obj.?method` means to call `method` on `$obj` if that method is defined for it, and otherwise return `Nil`.
* `~^` is the stringy exclusive-or operator, which exclusive-ors the corresponding characters of its operands.

Putting it all together, the uncapitalized program xors `flip` and a string containing four spaces, producing `FLIP`. That method is not defined for strings, so the `.?` method call returns `Nil`. Then `Nil || $_` evaluates to the original string. When the source code is uppercased, `flip` becomes `FLIP`, which when xor-ed with the spaces becomes `flip`, which when called on the input string, reverses it.

# Answer
> 3 votes
# SNOBOL4 (CSNOBOL4), 61 bytes

```
	&lcase 'a'	:f(r)
	output =input
r	output =reverse(input)
end

```

Try it online!

SNOBOL by default case-folds identifiers and labels (unless `&CASE` is set to `0` or the flag `-CASE 0` is used at the start of the program), so the only thing that really changes is the `'a' -> 'A'`, as SNOBOL uses case-sensitive pattern matching. Since `'A'` is not lowercase, it jumps to the label `R`, which reverses.

# Answer
> 2 votes
# Charcoal -v, 24 bytes

```
ternaryless"a""_"reverse

```

Try it online! In upper case:

```
TERNARYLESS"A""_"REVERSE

```

Try it online! Explanation: If `a` or `A` as appropriate is less than `_`, the ternary then reverses the implicit input, otherwise just takes implicit input. The result is then implicitly printed.

# Answer
> 2 votes
# Japt, 1 byte

## Lowercase

```
ô

```

Try it

Partitions the input at falsey characters, but there's no such thing as a falsey character in JavaScript.

## Uppercase

```
Ô

```

Try it

The shortcut for `w<space>`, Japt's built-in for reversing.

# Answer
> 2 votes
# Coconut, 21 bytes

```
_->_[::('a'>'_')*2-1]

```

Try it online!

Try it uppercased!

# Answer
> 2 votes
# Keg, 9 bytes

```
?r\{9-=[^

```

try it online! TRY IT ONLINE!

Somehow, by making the answer valid, I saved bytes.

# Answer
> 2 votes
# MAWP, 19 bytes

```
%|11a{%%0~}<%0/>[;]

```

try it! or TRY IT!

MAWP ignores lowercase letters, so this answer uses a conditional to check if subtraction has happened or not, and reverses based on it.

# Answer
> 2 votes
# oK, 13 bytes

```
.:9+23*7!"!g"

```

Try it online!

Explanation:

```
         "!g" /magic string
  9+23*7!     /9 + 23 * (ascii value mod 7)
.:            /eval ascii values as a string

```

When the input is `"!g"` it becomes `"||"` which is evaluated as reversing twice.
When the input is `"!G"` it becomes `"| "` which is evaluated as reversing once.

## oK repl, 10 bytes

I'm going to say that this one doesn't count, because it relies on the fact that the oK repl works in mysterious ways.

```
.:4*54!"u"

```

Try it in repl!

When the input is `"u"` it becomes `"$"` which evaluates as "string of expression". In the repl it is a noop when applied to strings.
When the input is `"U"` it becomes `"|"` which evaluates as reversing.

# Answer
> 2 votes
# Excel VBA, 58 bytes

Lowercase:

```
sub r(s)
if asc("a")=65then s=strreverse(s)
[a1]=s
end sub

```

Uppercase:

```
SUB R(S)
IF ASC("A")=65THEN S=STRREVERSE(S)
[A1]=S
END SUB

```

Output is to the cell `A1` of the currently active sheet (if this is in a module) or the parent sheet (if this is in a sheet object). I'm a little concerned this doesn't comply with the spec, though, because VBA auto-formats much of the code once it's input:

```
Sub r(s)
If Asc("a") = 65 Then s = StrReverse(s)
[a1] = s
End Sub

```

Of course, the standard has been to not consider the extra formatting in the byte count so I presume we can also ignore the capitalization. Really, I'm more worried about the answer being too straightforward to be interesting rather than that technicality.

# Answer
> 2 votes
# PowerShell, 45 bytes

```
$args|%{$s+=$_;$r=$_+$r};($s,$r)['a'[0]-ne97]

```

Try it online!. Outputs `123 Alice`.

```
$ARGS|%{$S+=$_;$R=$_+$R};($S,$R)['A'[0]-NE97]

```

Try it online!. Outputs `ecilA 321`.

# Answer
> 2 votes
# Haskell, 46 bytes

```
_f[]=[]
_f _s|'a'>'_'=_s|_x:_r<-_s=_f _r++[_x]

```

Try it online!

```
_F[]=[]
_F _S|'A'>'_'=_S|_X:_R<-_S=_F _R++[_X]

```

TRY IT ONLINE!

---

Regular identifiers in Haskell may not start with an upper-case letter, though starting with an underscore is fine. We cannot use the built-in `reverse` function, so we implement our own.

```
f [] = []
f s | 'a'>'_' = s            -- if we are lower-case, just return the string s
    | x:r <- s = f r ++ [x]  -- otherwise, split of the first char x, recursively reverse
                             -- the remainder r and concatenate it to x

```

# Answer
> 2 votes
## Javascript 75 bytes

```
_=>'a'<'['?[..._]['\162\145\166\145\162\163\145']()['\152\157\151\156']``:_

```

Seems the straightforward way to do it:

* test if 'a' has become 'A' by now having a lower ascii value than '\['
* if so, break the input into an array, then call `.reverse().join('')` on it, using octal to avoid spelling out the names of the functions
* otherwise return the string

Would be a lot shorter if the reversing happened on the lowercase version :)

# Answer
> 2 votes
# Husk, ~~9~~ 8 bytes

*Edit: -1 byte with non-ASCII case-change thanks to Razetime*

```
?↔o↔↔→ḋ2

```

Try it online!

If (`?`) last element () of binary igits of `2` is falsy (it's zero, so it is!), reverse the reverse of the input (`o↔↔`) - so, output the input unchanged.

**Uppercased:**

```
?↔O↔↔→Ḋ2

```

Try it online!

If (`?`) last element () of ivisors of `2` is truthy (it's 2, so it is!), reverse input ().

---

As an alternative that uses the approach of *not* uppercasing non-ASCII characters, there is also:

```
?↔+ø→d10

```

also for **8 bytes** (try it)...

# Answer
> 1 votes
# Google Sheets, ~~87~~ 75

Input is in A1.

Lower: A2: `=len(a1`

Output: `=arrayformula(if(code("a")-65,a1,join(,mid(a1,sequence(a2,1,a2,-1),1`

Upper: A2: `=LEN(A1`

Output: `=ARRAYFORMULA(IF(CODE("A")-65,A1,JOIN(,MID(A1,SEQUENCE(A2,1,A2,-1),1`

# Answer
> 1 votes
# x86 machine code, 18 bytes

dst=EDI, src=ESI, byte count = ECX. Copies src to dst either forward or reversed.

The only ASCII upper-case byte in the machine code is the `0x71` `'q'`, the opcode for `jno`, which is always taken (because it follows an xor-zeroing). When lowercased, it becomes `0x51 'Q'`, a `push ecx`, which is balanced by a `pop ecx` in the fall-through path before reaching the loop.

http://ref.x86asm.net/coder32.html#x71 is a useful opcode map. Conveniently, most of the `jcc` conditional branch opcodes are in the upper-case range.

```
rev:
    xor   edx, edx
%if 1
    jno   .loop                 ; 71 08  lower case: straight copy
%else
    db 0x51, 0x08               ; JNO becomes 0x51 push ecx, leaving the displacement as an opcode
%endif
    db 0xd1                ; ModRM for the uppercase case, where 08 is an OR opcode
.fallthrough:
    db 0x59                      ;pop  ecx (or RCX in 64-bit mode on TIO)

;    nop                         ; jump displacement needs to be 8, not 7 POP ES which will fault
;    add   edi, ecx
;    dec   edi                   ; so might as well use a longer single instruction
    lea   edi, [edi + ecx - 1]  ; point to *last* byte of destination
    mov   dl, 2
.loop:
    movsb                       ; *edi++ = *esi++
    sub   edi, edx              ; 0 for copy forwards, 2 for copy backwards
    loop  .loop

    ret

```

Try it online! with a `_start` that passes buffers and write()s the result.

The code in the fall-through path is 1 byte longer than it needs to be on its own: that makes the jump displacement `08` instead of `07`, because opcode `07` is `pop es`. That segfaults on many values we could push.

And `07` is not valid in 64-bit mode (illegal instruction), otherwise we could possibly arrange a jump that turns into a `push` of the just-zeroed register, allowing us to pop the null selector into ES. Setting ES to 0 in 32-bit user-space will fault, or lead to `movsb` faulting. (Even under a 64-bit kernel where 64-bit user-space does run with ds=es=0 null selectors.)

Disassembly of the uppercased version:

```
08049000 <rev>:
 8049000:       31 d2                   xor    edx,edx
 8049002:       51                      push   ecx
 8049003:       08 d1                   or     cl,dl        # c |= 0  leaves ECX unchanged

08049005 <rev.fallthrough>:
 8049005:       59                      pop    ecx
 8049006:       8d 7c 0f ff             lea    edi,[edi+ecx*1-0x1]
 804900a:       b2 02                   mov    dl,0x2

0804900c <rev.loop>:
 804900c:       a4                      movs   BYTE PTR es:[edi],BYTE PTR ds:[esi]
 804900d:       29 d7                   sub    edi,edx
 804900f:       e2 fb                   loop   804900c <rev.loop>
 8049011:       c3                      ret

```

(lower-case ASCII ranges from `'a'` 0x61 to `'z'` (`0x7a`). The 7C ModRM for the LEA is just beyond that. `59` pop ecx is already upper case. If there was a case-flip instead of just upper-case version of this challenge, we could make it 0x79. That byte isn't executed in the upper-case version: `jno` jumps over it.

The lower-case version is:

```
08049000 <rev>:
 8049000:       31 d2                   xor    edx,edx
 8049002:       71 08                   jno    804900c <rev.loop>
 8049004:       d1                      .byte 0xd1

08049005 <rev.fallthrough>:        # having this label here syncs disassembly after the stray byte above
 8049005:       59                      pop    ecx
 8049006:       8d 7c 0f ff             lea    edi,[edi+ecx*1-0x1]
 804900a:       b2 02                   mov    dl,0x2

0804900c <rev.loop>:
 804900c:       a4                      movs   BYTE PTR es:[edi],BYTE PTR ds:[esi]
 804900d:       29 d7                   sub    edi,edx
 804900f:       e2 fb                   loop   804900c <rev.loop>
 8049011:       c3                      ret

```

# Answer
> 1 votes
# Pascal (FPC), 128 bytes

The procedure just prints each character recursively, but switches the printing to after the recursive call if in uppercase mode to reverse the output.

```
procedure f;var c:char;begin if eof then exit;read(c);if byte('a')-97<0 then begin f;write(c);end else begin write(c);f;end;end;

```

Try it online!

# Answer
> 1 votes
# Self-modifying Brainfuck, 52 bytes

represents the literal null byte `\x00`

```
-[<->---]<[[-]<[<]>----------------[>]]>,[␀>,]<[.<]u

```

Try it online!

On the interpreter the input has a null byte at the end

EOF is `\x00`

---
Tags: code-golf, string, source-layout
---


title: PRINT like THIS

text:
# Question
Title: PRINT like THIS
Write a program that takes an input to STDIN and makes all of the lowercase letters (including accented letters) in the `2k-1`th word uppercase and all the uppercase letters (also including accented letters) in the `2k`th word lowercase (`k` is a positive integer). The program should not affect any other characters in any word. For example, if the string is `Ook! O0k!`, then the output should be `OOK! o0k!`.

A new word is formed when there is a nonzero amount of whitespace after a non-whitespace character. Whitespace at the beginning of an input should be ignored. If a word does not contain any changed characters, the program should still consider it as a word and continue.

*Sample inputs* (Different inputs are separated by a blank newline). **Please note the third example**, which should have leading spaces, and have the first `be` capitalised.

```
Nineteen Eighty-Four (1984)

Programming Puzzles & Code Golf   -
Hooray for Code Golf Stack Exchange!

     2be or not 2be, that is the ~~~QuEsTiOn~~~

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

```

*Sample outputs*

```
NINETEEN eighty-four (1984)

PROGRAMMING puzzles & code GOLF   -
HOORAY for CODE golf STACK exchange!

     2BE or NOT 2be, THAT is THE ~~~question~~~

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

```

---

This is code golf, fellas. Standard CG rules apply. Shortest program in bytes wins.

---

I'm pretty sure I covered all the loopholes regarding whitespace and non-letter characters, but if I've missed any, please tell me.

---

Thanks to @Optimizer for creating the following code snippet. To use, click "Show code snippet", scroll to the bottom and click "► Run code snippet".

```
/* Configuration */

var QUESTION_ID = 59464; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43444; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
> 6 votes
# Vim script, ~~22~~ 21 bytes

```
nm Q vEUWvEuWQ|norm Q

```

Explanation:

The first command maps `Q` to:

`vEU` make word uppercase
`W` go to next word
`vEu` make word lowercase
`W` go to next word
`Q` repeat recursive mapping

and `|norm Q` executes the mapping

## Usage of the program

This is how you get *Vim* to read from stdin:

```
$ vim - -c 'nm Q vEUWvEuWQ|norm Q'
Vim: Reading from stdin
This is the first line!
This is the second line!
This is the third and last line I type to check if this works!
^D

```

This will open up *Vim* displaying this:

```
THIS is THE first LINE.
this IS the SECOND line.
THIS is THE third AND last LINE i TYPE to CHECK if THIS works!
~
~
~

```

# Answer
> 6 votes
# GNU sed, 28

Score includes +2 for `-rz` passed to GNU sed.

```
s/(\S+\s*)(\S*)/\U\1\L\2/g

```

### Test output

```
$ for t in 'Nineteen Eighty-Four (1984)' \
> 'Programming Puzzles & Code Golf   -
> Hooray for Code Golf Stack Exchange!' \
> '     2be or not 2be, that is the ~~~QuEsTiOn~~~' \
> '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'; do
> echo "$t" | sed -zrf PRINTlikeTHIS.sed
> done
NINETEEN eighty-four (1984)
PROGRAMMING puzzles & code GOLF   -
HOORAY for CODE golf STACK exchange!
     2BE or NOT 2be, THAT is THE ~~~question~~~
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
$

```

# Answer
> 5 votes
# Perl, 26 bytes

25 bytes code + 1 byte command line

```
s/\S+/++$i%2?uc$&:lc$&/eg

```

Thanks to ThisSuitIsBlackNot for fixing a couple of bugs!

Usage:

```
perl -p entry.pl

```

# Answer
> 3 votes
# Pyth, 23

```
jdmjbmrk=xZ!!kcdbcjb.zd

```

Try it online or run the test suite

Alternates between pyth's `lower` and `upper` functions, which are `r...0` or `r...1`. This will probably affect unicode characters, waiting on OP clarification to change.

I feel like something must be golfable. Particularly the XOR to change the switch on which of `upper`/`lower` should be used.

# Answer
> 2 votes
# JavaScript ES6, ~~74~~ 71 bytes

`.toUpperCase()` and `.toLowerCase()` absolutely slaughter the byte count (adds 32 bytes 0.o). Most work-arounds end up with more bytes though

```
s=>s.replace(/(\S+\s*)(\S*)/g,(_,a,b)=>a.toUpperCase()+b.toLowerCase())

```

# Answer
> 2 votes
## Perl, 87 bytes

After screwing with both regular expressions and `map` for a while, I could not come up with an elegant solution, so this is the result:

```
@a=split(" ",lc(<>));while($i<=$#a/2){@a[$i*2]=uc(@a[$i*2]);$i++;}print(join(" ", @a));

```

# Answer
> 2 votes
# Ruby, 56 bytes

```
$><<gets.gsub(/\S+/){($.+=1)%2>0?$&.downcase: $&.upcase}

```

# Answer
> 2 votes
# Delphi, 290 bytes

```
program P;uses SysUtils;var s:string;i:word;w:byte;f:boolean;begin repeat readln(s);w:=0;f:=false; for I:=1 to length(s) do begin if s[i]>' ' then begin if w=0 then f:=not f;w:=1;if f then s[i]:=uppercase(s[i])[1] else s[i]:=lowercase(s[i])[1] end else w:=0 end;writeln(s)until false;end.

```

Not really a good language to golf with ...

# Answer
> 1 votes
# Groovy, ~~108~~ ~~125~~ 120

```
System.in.eachLine{def b;it.split(" ").any{if(!it.empty)b=!b;print "${b?it.toUpperCase():it.toLowerCase()} "};println()}

```

Not as clean as I was hoping it would be, which seems to be a theme with my Groovy answers.

* +17 to fix behavior with leading whitespace
* -5 for removing trailing newline and switching from .isEmpty() to .empty

```
$ cat tests.txt
Nineteen Eighty-Four (1984)

Programming Puzzles & Code Golf   -
Hooray for Code Golf Stack Exchange!

     2be or not 2be, that is the ~~~QuEsTiOn~~~

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
$ groovy PRINTlikeTHIS.groovy < tests.txt
NINETEEN eighty-four (1984)

PROGRAMMING puzzles & code GOLF   -
HOORAY for CODE golf STACK exchange!

     2BE or NOT 2be, THAT is THE ~~~question~~~

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

```

# Answer
> 1 votes
# Lua, 96 bytes

```
i=0 print(io.read'*l':gsub('%S+',function(x)i=i+1 return i%2==1 and x:upper() or x:lower()end))

```

# Answer
> 1 votes
## Pyth, ~~17~~ 22 bytes

```
FGcwd=+YrG=Z%+1Z2;jdY

```

Try it here

# Answer
> 1 votes
# Python 3, ~~103~~ 95 bytes

```
print(' '.join(b.lower()if a%2 else b.upper()for a,b in enumerate(input().strip().split(' '))))

```

# Answer
> 1 votes
## STATA, 252 bytes

```
insheet using a.b
g b=word(v,1)
gl c=0
forv x=1/`=_N'{
loc d=1
while b[`x']!=""{
if !$c replace v=subinword(v,b,upper(b),1) if `x'==_n
if $c replace v=subinword(v,b,lower(b),1) if `x'==_n
loc ++d
replace b=word(v,`d') if `x'==_n
gl c=1-$c
}
di v[`x']
}

```

Expects input as a csv file (one column) called a.b.

Explanation:

Read data in (default variable name is v1, shortenable to v). Make a new variable b equal to the first word (space separated token) of v for each line. For each line, while the next word is not empty (only occurs if no more characters on that line), replace the word in v with the upper or lower case version of that word in the current line, depending on how many (mod 2) words have already been found. Then get the next word and repeat. Print out the whole line when finished with it.

# Answer
> 1 votes
# Lua, 88 bytes

```
a=io.read():gsub("%g+",function(s)m=not m return m and s:upper()or s:lower()end)print(a)

```

# Answer
> 1 votes
# CJam, 28 bytes

```
q{C' >Sc'!<*X^:XCelCeu?:S}fC

```

I'm currently considering the first 33 ASCII/Unicode characters (and only those) whitespace. I'm awaiting clarification to know whether this is valid or not.

Try it online in the CJam interpreter.

# Answer
> 1 votes
# C#, 104 100 99 bytes

```
static void Main(){string.Join(" ","".Split(' ').Select((o,i)=>i++%2==0?o.ToUpper():o.ToLower()));}

```

It's 79 bytes with

```
string.Join(" ","".Split(' ').Select((o,i)=>i++%2==0?o.ToUpper():o.ToLower()));

```

# Answer
> 1 votes
# Perl 5 \+ `-040plF/^ +$/`, 17 bytes

```
$_=($|-=@F)?uc:lc

```

Try it online!

# Answer
> 1 votes
# Husk, 12 bytes

```
z?a_mȯ%2Lwḣ¹

```

Try it online!

Preserves whitespace in the input, in agreement with the test cases.

```
z?a_mȯ%2Lwḣ¹
z             # zip two lists together,
              # using this function on each pair of elements:
 ?            # if element from list1 is truthy
  a           # uppercase the element from list2
   _          # otherwise lowercase the element from list2
    mȯ%2Lwḣ¹  # list1:
    mȯ        # map this function on each element of
          ḣ¹  # all the prefixes of the input string:
        Lw    # number of elements after splitting on whitespace
      %2      # modulo 2
              # list2: the input string

```

---

A different program which uppercases & lowercases in words, and does "not affect any other characters in any word" (which I wrote after reading the instructions, but before realising that the third "Sample output" should also be considered as part of the specification), could be only **10 bytes**:

```
wzom?a_İ¬w

```

Try it online!

# Answer
> 0 votes
# PowerShell, 106 bytes

```
$k=@();$i=0;$args[0].trim().split(' ')|%{if($i%2){$k+=$_.tolower()}else{$k+=$_.toupper()};$i++};$k-join" "

```

Try it online!

Shameless port of python 3 solution, Just horrible attempt to golf ;-(

---
Tags: code-golf
---


# Question
Title: What are the repeating Fibonacci Digits?
As you probably know, a Fibonacci Number is one which is the sum of the previous two numbers in the series.

A Fibonacci Digit™ is one which is the sum of the two previous *digits*.

For instance, for the series beginning `1,1`, the series would be `1,1,2,3,5,8,13,4,7,11,2...` The change occurs after the `13`, where, instead of adding `8+13`, you add `1+3`. The series loops at the end, where `4+7=11`, and `1+1=2`, same as the series starts.

For another example, the series beginning `2,2`: `2,2,4,6,10,1,1,2,3,5,8,13,4,7,11,2,3...`. This one starts out uniquely, but once the digits sum to `10`, you end up with `1+0=1, 0+1=1`, and the series continues - and loops - the same way the `1,1` series did.

---

# The Challenge

Given an integer input `0≤n≤99`, calculate the loop in the Fibonacci Digit series beginning with those two digits. (You are certainly *allowed* to consider integers out of this range, but it's not required.) If given a one-digit input, your code should interpret it to denote the series beginning `0,n`.

All numbers in the loop that are two-digits *must* be outputted as two digits. So, for instance, the loop for `1,1` would contain `13`, not `1,3`.

The output begins with the first number in the loop. So, based on the above restrictions, the loop for `1,1` begins with `2`, since `1,1` and `11` are counted separately.

Each number of the output may be separated by whatever you want, as long as it's consistent. In all of my examples I use commas, but spaces, line breaks, random letters, etc. are all allowed, as long as you always use the same separation. So `2g3g5g8g13g4g7g11` is a legal output for `1`, but `2j3g5i8s13m4g7sk11` is not. You can use strings, lists, arrays, whatever, provided that you have the correct numbers in the correct order separated by a consistent separator. Bracketing the entire output is also allowed (ex. `(5,9,14)` or `[5,9,14]`, etc.).

**Test Cases:**

```
1 -> 2,3,5,8,13,4,7,11
2 -> 2,3,5,8,13,4,7,11
3 -> 11,2,3,5,8,13,4,7
4 -> 3,5,8,13,4,7,11,2
5 -> 2,3,5,8,13,4,7,11
6 -> 3,5,8,13,4,7,11,2
7 -> 14,5,9
8 -> 13,4,7,11,2,3,5,8
9 -> 11,2,3,5,8,13,4,7
0 -> 0
14 -> 5,9,14
59 -> 5,9,14

```

This is , so the lowest number of bytes wins.

# Answer
> 11 votes
# Jelly, 15 bytes

```
DFṫ-SṭḊ
d⁵ÇÐḶZḢ

```

Try it online!

### How it works

```
d⁵ÇÐḶZḢ  Main link. Argument: n (integer)

d⁵       Divmod 10; yield [n:10, n%10].
  ÇÐḶ    Call the helper link until a loop is reached. Return the loop.
     Z   Zip/transpose the resulting array of pairs.
      Ḣ  Head; extract the first row.

DFṫ-SṭḊ  Helper link. Argument: [a, b] (integer pair)

D        Decimal; replace a and b with the digits in base 10.
 F       Flatten the resulting array of digit arrays.
  ṫ-     Tail -1; take the last two digits.
    S    Compute their sum.
      Ḋ  Dequeue; yield [b].
     ṭ   Append the sum to [b].

```

# Answer
> 6 votes
# Perl 6, ~~96 78~~ 75 bytes

*-3 bytes thanks to nwellnhof*

```
{0,|.comb,((*~*)%100).comb.sum...{my$a=.tail(2);m/(\s$a.*)$a/}o{@_};$_&&$0}

```

Try it online!

0 returns 0, and other number return a Match object which stringifies to the numbers separated by a space with a leading a trailing space.

### Explanation:

```
{                                                                         }   # Anonymous code block
 0,|.comb,                    ...   # Start a sequence with 0,input
                                    # Where each element is
                          .sum      # The sum of
          (     %100).comb          # The last two digits
           (*~*)                    # Of the previous two elements joined together
                                                                         # Until
                                 {                           }o{@_}   # Pass the list into another function
                                  my$a=.tail(2); # Save the last two elements
                                                m/(\s$a.*)$a/  # The list contains these elements twice?
                                                                     # And return
                                                                   ;$_     # Input if input is 0
                                                                      &&   # Else
                                                                        $0 # The looping part, as matched

```

# Answer
> 5 votes
# Python 3, ~~187~~ ~~176~~ ~~158~~ ~~139~~ ~~138~~ ~~129~~ ~~121~~ ~~120~~ ~~112~~ ~~96~~ ~~95~~ ~~120~~ 116 bytes

```
f=lambda n,m=0,z=[]:(n,m)in zip(z,z[1:])and z[z.index(m)::-1]or f((z and n//10or m%10)+n%10,z and n or n//10,(m,*z))

```

Try it online!

Edit: As noted by @Jules, shorter solution applies to Python 3.6+. No longer distinct solutions for Python 3 / 3.6+

Edit: Indexing of `z` was too verbose. Without that now there is no gain in using `eval`.

Edit: Simplified finding if last two elements already appeared in the sequence.

Edit: Changed output format from list to tuple + replaced `lambda` with `def`

Edit: Back to `lambda` but embedded `t` into `f`.

Edit: Input `n` can be actually interpreted as head of growing collection `z` which would represent tail in recursive approach. Also beats @Arbo's solution again.

Edit: Actually you can unpack two items from head which cuts another 16 bytes.

Edit: Actually 17 bytes.

Edit: As noted by @Arbo solution was giving answers for `14` and `59` cases as they were in initial test cases which were proven later to be wrong. For now this isn't so short but at least it works correctly.

---

Quite an abuse of `f-strings` and `eval`. Original ungolfed code although I suspect it could be done somehow easier:

```
def is_subsequence(l1, l2):
    N, n = len(l1), len(l2)
    for i in range(N-n):
        if l1[i:i+n]==l2:
            return True
    return False

def generate_sequence(r):
    if is_subsequence(r,r[-2:]):
        return r
    last_two_digits = "".join(map(str,r))[-2:]
    new_item = sum(int(digit) for digit in last_two_digits)
    return generate_sequence(r + [new_item])

def f(n):
    seq = generate_sequence([n,n])[::-1]
    second_to_last = seq[1]
    first_occurence = seq.index(second_to_last)
    second_occurence = seq.index(second_to_last, first_occurence + 1)
    return seq[first_occurence + 1 : second_occurence + 1][::-1]

```

# Answer
> 5 votes
# JavaScript (ES6),  ~~111 104~~  103 bytes

```
f=(n,o=[p=n/10|0,n%10])=>n^o[i=o.lastIndexOf(n=(q=p+[p=n])/10%10+q%10|0)-1]?f(n,[...o,n]):o.slice(i,-1)

```

Try it online!

### Commented

```
f = (                       // f = recursive function taking:
  n,                        //    n = last term, initialized to the input
  o = [                     //    o = sequence, initially containing:
    p = n / 10 | 0,         //      p = previous term, initialized to floor(n / 10)
    n % 10 ]                //      n mod 10
) =>                        //
  n ^                       // we compare n against
  o[                        // the element in o[] located at
    i = o.lastIndexOf(      //   the index i defined as the last position of
      n =                   //     the next term:
        (q = p + [p = n])   //       q = concatenation of p and n; update p to n
        / 10 % 10           //       compute the sum of the last two digits
        + q % 10            //       of the resulting string
        | 0                 //       and coerce it back to an integer
      ) - 1                 //   minus 1
  ] ?                       // if o[i] is not equal to n:
    f(n, [...o, n])         //   append n to o[] and do a recursive call
  :                         // else:
    o.slice(i, -1)          //   we've found the cycle: return it

```

# Answer
> 4 votes
# C (gcc), ~~114~~ ~~112~~ 109 bytes

```
f(n,s){int i[19]={};for(s=n/10,n%=10;i[s]-n;n+=n>9?-9:s%10,s=i[s])i[s]=n;for(;printf("%d ",s),i[s=i[s]]-n;);}

```

Try it online!

-3 from ceilingcat

Includes a trailing space.

```
f(n,s){
    int i[19]={};                               //re-initialize edges for each call
    for(s=n/10,n%=10;                           //initialize from input
        i[s]-n;                                 //detect loop when an edge s->n repeats
        n+=n>9?-9:s%10,s=i[s])i[s]=n;           //step
    for(;printf("%d ",s),i[s=i[s]]-n;);         //output loop
}

```

# Answer
> 3 votes
# Perl 5, ~~90~~ 76 bytes

```
s/.\K/ /;s/(.?) *(.)\K$/$".($1+$2)/e until/^0|\b(.\B.|. .)\b.*(?= \1)/;$_=$&

```

TIO

# Answer
> 2 votes
# Java (JDK), 194 bytes

```
n->"acdfinehlcdfinehfjofj".chars().map(x->x-97).skip((n="abbicbcsfibbbgqifiibbgbbbcsfbiiqcigcibiccisbcqbgcfbffifbicdqcibcbicfsisiibicfsiffbbicfsifiibicfsifii".charAt(n)%97)).limit(n<1?1:n<9?8:3)

```

Try it online!

Hardcoded seemed the shortest given that Python already had an answer of 187...

# Answer
> 2 votes
# Python 2, ~~123~~ ~~114~~ 113 bytes

```
n=input()
p=b=l=n/10,n%10
while~-(b in p):p+=b,;l+=(b[1]/10or b[0]%10)+b[1]%10,;b=l[-2:]
print l[p.index(b)-2:-2]

```

Try it online!

The program builds up a tuple `p` of all 2-value pairs that have occurred in the sequence, which is initialised with junk to save some bytes. The sequence itself gets built in the tuple `l`, and the last two elements of this tuple are stored in `b` for easy (and short) reference. As soon as a repeat is found, we can look up the index of `b` in `p` to know where the loop began.

EDIT: Cleaned this up a bit, and shaved off one more byte... My method does seem to be nearing its byte count limit, and I really should stop working on this.

# Answer
> 2 votes
## Haskell, 100 bytes

```
d!p@(s,t)|(_,i:h)<-span(/=p)d=fst<$>i:h|q<-d++[p]=q!(t,last$mod s 10+t:[t-9|t>9])
h x=[]!divMod x 10

```

Try it online!

```
d!p@(s,t)                -- function '!' recursively calculates the sequence
                         -- input parameter:
                         -- 'p': pair (s,t) of the last two numbers of the sequence
                         -- 'd': a list of all such pairs 'p' seen before
  |       <-span(/=p)d   -- split list 'd' into two lists, just before the first
                         -- element that is equal to 'p'
   (_,i:h)               -- if the 2nd part is not empty, i.e. 'p' has been seen
                         -- before
          =fst<$>i:h     -- return all first elements of that 2nd part. This is
                         -- the result.
  |q<-d++[p]             -- else (p has not been seen) bind 'q' to 'd' followed by 'p'
   =q!                   -- and make a recursive call to '!' with 'q' and
     (t,    )            -- make the last element 't' the second to last element
                         -- the new last element is
          [t-9|t>9]      -- 't'-9 (digit sum of 't'), if 't'>9
       mod s 10+t        -- last digit of 's' plus 't', otherwise

h x=                     -- main function
     []!divMod x 10      -- call '!' with and empty list for 'd' and
                         -- (x/10,x%10) as the pair of last numbers

```

# Answer
> 1 votes
# Charcoal, 46 bytes

```
≔Ｅ◧Ｓ²ΣιθＷ¬υ≔ΦＥ⊖Ｌ⊞ＯθΣ…⮌⪫θω²✂θλＬθ¹⁼κ✂θ⊗⁻λＬθλ¹υＩυ

```

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

```
≔Ｅ◧Ｓ²Σιθ

```

Input the number, pad it to 2 characters, then take the digital sum of each character, and save the resulting list.

```
Ｗ¬υ

```

Repeat while the list of loops is empty.

```
⊞ＯθΣ…⮌⪫θω²

```

Calculate the sum of the two previous digits and add it to the Fibonacci list.

```
Ｅ⊖Ｌ...✂θλＬθ¹

```

Take all the nontrivial suffixes of the list.

```
≔Φ...⁼κ✂θ⊗⁻λＬθλ¹υ

```

Filter out those that don't repeat and save the result in the list of loops.

```
Ｉυ

```

Cast the list of loops to string and print.

# Answer
> 1 votes
# Python 2, ~~149~~ 139 bytes

```
s=input()
s=[s/10,s%10]
while zip(s,s[1:]).count((s[-2],s[-1]))<2:s+=[(s[-1]/10or s[-2]%10)+s[-1]%10]
print s[-s[::-1].index(s[-2],2)-1:-2]

```

Try it online!

Expects a non-negative integer as input. Smaller bytecount, but likely will no longer work for integers \>99.

**Explanation:**

```
# get the input from STDIN
s=input()
# convert the input into two integers via a divmod operation
s=[s/10,s%10]
# count number of times the last two numbers appear in sequence in list.
# turn list into list of adjacent value pairs Ex: [1,1,2]->[(1,1),(1,2)]
      zip(s,s[1:])
                  # count number of times the last two items in list appear in entire list
                  .count((s[-2],s[-1]))
# if >1 matches, we have found a repeat.
while .................................<2:
        # the first digit of the last number, if it is >9
        # else the last digit of the second to last number
        (s[-1]/10or s[-2]%10)
                             # the last digit of the last number
                             +s[-1]%10
    # add the new item to the list
    s+=[..............................]
         # reverse the list, then find the second occurrence of the second to last item
         s[::-1].index(s[-2],2)
# get the section of the list from the second occurrence from the end, discard the final two items of the list
print s[-......................-1:-2]

```

# Answer
> 1 votes
# Red, ~~189~~ ~~178~~ ~~164~~ 137 bytes

```
func[n][b: n % 10 c: reduce[a: n / 10]until[append c e: b
b: a *(pick[0 1]b > 9)+(a: b % 10)+(b / 10)k: find c reduce[e b]]take/last k k]

```

Try it online!

# Answer
> 1 votes
# Husk, 15 bytes

```
UṠ-U_2¡ȯΣ↑_2ṁd;

```

Try it online!

```
UṠ-U_2¡ȯΣ↑_2ṁd;
U                   # longest prefix of unique elements from sequence
 Ṡ-U_2              # (after removing longest prefix with
                    # all unique sublists of length 2)
      ¡ȯΣ↑_2ṁd;     # fibonacci digit sequence:
      ¡             # repeatedly apply function to list
              ;     # (starting with list formed from input):
       ȯ            # combination of 3 functions -
        Σ           # sum of
         ↑_2        # last 2 elements of
            ṁd      # digits of list

```

---
Tags: code-golf
---


title: Swap program halves to test divisors

text:
# Question
Title: Swap program halves to test divisors
## Four integer sequences

In this challenge, you will test four different properties of a positive integer, given by the following sequences. A positive integer **N** is

1. *perfect* (OEIS A000396), if the sum of proper divisors of **N** equals **N**. The sequence begins with 6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128...
2. *refactorable* (OEIS A033950), if the number of divisors of **N** is a divisor of **N**. The sequence begins with 1, 2, 8, 9, 12, 18, 24, 36, 40, 56, 60, 72, 80, 84, 88, 96, 104, 108, 128...
3. *practical* (OEIS A005153), if every integer **1 ≤ K ≤ N** is a sum of some distinct divisors of **N**. The sequence begins with 1, 2, 4, 6, 8, 12, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 48, 54, 56...
4. *highly composite* (OEIS A002128), if every number **1 ≤ K \< N** has strictly fewer divisors than **N**. The sequence begins with 1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040...

## Four programs

Your task is to write four programs (meaning full programs, function definitions or anonymous functions that perform I/O by any of the standard methods). Each program shall solve the membership problem of one of these sequences. In other words, each program will take a positive integer **N ≥ 1** as input, and output a truthy value if **N** is in the sequence, and a falsy value if not. You can assume that **N** is within the bounds of the standard integer type of your programming language.

The programs must be related in the following way. There are four strings `ABCD` such that

1. `AC` is the program that recognizes perfect numbers.
2. `AD` is the program that recognizes refactorable numbers.
3. `BC` is the program that recognizes practical numbers.
4. `BD` is the program that recognizes highly composite numbers.

## Scoring

Your score is the total length (in bytes) of the strings `ABCD`, or in other words, the total byte count of the four programs divided by two. The lowest score in each programming language is the winner. Standard rules apply.

For example, if the four strings are `a{`, `b{n`, `+n}` and `=n}?`, then the four programs are `a{+n}`, `a{=n}?`, `b{n+n}` and `b{n=n}?`, and the score is 2+3+3+4=12.

# Answer
## JavaScript (ES6), 46 + 55 + 6 + 36 = ~~282~~ ~~274~~ ... ~~158~~ 143 bytes

A:

```
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)

```

B:

```
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))

```

C:

```
?!g:!q

```

D:

```
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1

```

The result is 4 anonymous functions which give truthy/falsy values for their respective inputs (`AC`, `AD`, and `BC` give `true`/`false`, `BD` gives `1`/`0`).

### Test snippet

```
let AC =
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)
?!g:!q

let AD =
n=>(r=0,D=x=>x&&D(x-1,n%x||(r++?q-=x:q=n)))(n)
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1

let BC =
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))
?!g:!q

let BD =
n=>(q=(g=D=x=>x&&!(n%x||(g|=m>2*(m=x),0))+D(x-1))(m=n))
?(P=k=>--k?D(n=k)<q&P(k):1)(n):n%r<1

let update = n => O.innerText = [
  'perfect: ' + AC(n),
  'refactorable: ' + AD(n),
  'practical: ' + BC(n),
  'highly composite: ' + BD(n)
].join("\n")
```

```
<input type=number value=1 min=1 oninput=update(this.value)>
<pre id=O></pre>
```
> 7 votes

# Answer
# Jelly, 8 + 17 + ~~2~~ 1 + 2 = ~~29~~ 28 bytes

A:

```
Æṣ⁼$Ædḍ$

```

B:

```
ÆDŒPS€QṢwRµṖÆdṀ<Ʋ

```

C:

```
ƭ

```

D:

```
0?

```

For practical numbers (BC), `0` is falsy and any other result is truthy.

AC and BC are full programs, since they're not reusable as functions.
> 3 votes

# Answer
# Jelly, 5 + 17 + 3 + 3 = 28 bytes

There's already a 28-byte Jelly answer, but I have a different approach, so why not add it too?

## Parts

The pilcrow  represents a newline.

A: `S=¶ḍ¶` (5 bytes)
B: `ŒP§iⱮḶ}Ạ¶>ḶÆd$}Ạ¶` (17 bytes)
C: `ÆḌñ` (3 bytes)
D: `Ædç` (3 bytes)

## Perfect (8 bytes)

```
S=
ḍ
ÆḌñ

```

Try it online!

### Explanation

```
S=   Auxiliary dyadic link
S    Sum of items in left argument
 =   Equals right argument?

ḍ   Ignored

ÆḌñ   Main monadic link
ÆḌ    Proper divisors
  ñ   Apply next link, with the number as right argument

```

## Refactorable (8 bytes)

```
S=
ḍ
Ædç

```

Try it online!

### Explanation

```
S=   Ignored

ḍ   Auxiliary dyadic link: Divides?

Ædç   Main monadic link
Æd    Number of divisors
  ç   Apply previous link, with the number as right argument

```

## Practical (20 bytes)

```
ŒP§iⱮḶ}Ạ
>ḶÆd$}Ạ
ÆḌñ

```

Try it online!

### Explanation

```
ŒP§iⱮḶ}Ạ   Auxiliary dyadic link
ŒP         Power set
  §        Sum of each
   iⱮ      Find index of each item from
     Ḷ}      Lowered range [0..(right argument - 1)]
       Ạ   All?

>ḶÆd$}Ạ   Ignored

ÆḌñ   Main monadic link
ÆḌ    Proper divisors
  ñ   Apply next link, with the number as right argument

```

## Highly composite (20 bytes)

```
ŒP§iⱮḶ}Ạ
>ḶÆd$}Ạ
Ædç

```

Try it online!

### Explanation

```
ŒP§iⱮḶ}Ạ   Ignored

>ḶÆd$}Ạ   Auxiliary dyadic link
>         Greater than?
    $     (
 Ḷ   }      Lowered range [0..(right argument - 1)]
  Æd        Number of divisors [of each]
    $     )
      Ạ   All?

Ædç   Main monadic link
Æd    Number of divisors
  ç   Apply previous link, with the number as right argument

```
> 1 votes

# Answer
# 05AB1E, 8 + 16 + 1 + 0 = 25 bytes

A: `Ñ¨O©QI®Ö`
B: `ÑæOILåPILÑ€gRć‹P`
C: `s`
D:

The long parts each calculate both values, `s` swaps to the first one.

```
Ñ          # push list of divisors
 ©         # store this list
  ¨        # remove the last (largest) value
   O       # take the sum
    Q      # is this equal to the input (perfect)
     I     # push the input
      ®    # push the stored divisor list
       g   # take the length
        Ö  # does it divide the input? (refactorable)
        (s)# (swap to perfect)

```

Try *perfect* online! or Try *refactorable* online!

```
ÑæOILåP    # practical?
Ñ          # push list of divisors
 æ         # take the powerset
  O        # sum of each subset
   IL      # push the range [1..input]
     å     # is each value in the sums of divisor-subsets?
      P    # take the product / boolean all

ILÑ€gRć‹P  # highly composite?
IL         # push the range [1..input]
  Ñ        # take the divisors of each integer
   €g      # take the length of each divisor list
     R     # reverse it (swap the input's to the front)
      ć    # push the first value seperately
       ‹   # is this larger
        P  # than all other values?

(s)        # (swap to practical)

```

Try *practical* online! or Try *highly composite* online
> 1 votes

# Answer
# Haskell, 69 + 133 + 3 + 3 = score 208

A:

```
d n=filter((<1).mod n)[1..n]
f n=[sum(d n)-n==n,length(d n)`elem`d n]

```

B:

```
import Data.List
d n=filter((<1).mod n)[1..n]
f n=[all(\n->any(==n)$sum$subsequences$d n)[1..n],all((<length(d n)).length.d)[1..n-1]]

```

C:

```
!!0

```

D:

```
!!1

```

Try it online!

Yeah, it's pretty cheap but I'm not smart enough for a cooler solution. :P
> 0 votes

---
Tags: code-golf, decision-problem, number-theory, source-layout, multiple-holes
---


title: All-inclusive semi-primes

text:
# Question
Title: All-inclusive semi-primes
\\$723 = 3 \times 241\\$ is a semi-prime (the product of two primes) whose prime factors include all digits from \\$1\\$ to \\$n\\$, where \\$n\\$ is the total number of digits between them. Another way to look at this is that the (sorted) digits in the factorisation of \\$723\\$ are all consecutive. The first 10 such semi-primes and their factorisations are

```
[26, 62, 723, 862, 943, 1263, 2906, 3086, 7082, 7115]
[2×13, 2×31, 3×241, 2×431, 23×41, 3×421, 2×1453, 2×1543, 2×3541, 5×1423]

```

We will call the numbers that have this feature **all-inclusive semi-primes**

You may choose whether to:

* Take an integer \\$n\\$ and output the \\$n\\$th all-inclusive semi-prime (0 or 1 indexed)
* Take an integer \\$n\\$ and output the first \\$n\\$ all-inclusive semi-primes
* Output the sequence of all-inclusive semi-primes indefinitely

This is so the shortest code in bytes wins!

This is a Jelly program which takes an integer \\$n\\$ and outputs the first \\$n\\$ all-inclusive semi-primes and their factorisations. Spoilers for any Jelly based solutions.

The first 100 all-inclusive semi-primes are

```
[26, 62, 723, 862, 943, 1263, 2906, 3086, 7082, 7115, 8306, 9026, 10715, 10793, 10826, 10862, 11705, 12443, 12773, 21155, 21443, 22313, 22403, 29126, 29306, 31286, 32906, 69302, 70922, 72902, 73082, 87302, 90722, 91226, 91262, 92306, 92702, 104903, 106973, 108326, 108722, 109262, 112862, 116213, 123086, 123155, 127082, 128306, 129026, 129743, 130826, 132155, 135683, 142283, 148373, 155123, 157373, 161393, 171305, 181205, 206315, 216305, 225833, 226223, 230543, 237023, 241103, 241223, 244913, 259433, 270934, 271294, 273094, 274913, 275903, 280403, 287134, 291274, 310715, 312694, 312874, 316205, 317105, 320615, 321155, 328714, 330874, 335003, 335086, 335243, 337111, 340313, 349306, 350926, 355741, 359881, 373701, 379371, 379641, 380581]

```

# Answer
> 9 votes
# 05AB1E, ~~17~~ ~~16~~ ~~14~~ ~~12~~ 11 bytes

```
∞ʒÒDS{āQиg<

```

Outputs the infinite sequence.

-2 bytes thanks to *@CommandMaster*, which also opened up the opportunity to golf 2 more bytes
-1 byte thanks to *@ovs*.

Try it online.

**Explanation:**

```
∞         # Push an infinite list of positive integers: [1,2,3,...]
 ʒ        # Filter this list by:
  Ò       #  Get a list of its prime factors (including duplicates)
   D      #  Duplicate this list
    S     #  Convert the list of integers to a flattened list of digits
     {    #  Sort these digits
      ā   #  Push a list in the range [1,length] (without popping the list itself)
       Q  #  Check that the two lists are equal (1 if truthy; 0 if falsey)
    и     #  Repeat the list if prime factors that many times as list
          #  (so it'll become empty for falsey results; and stays the same for truthy)
     g    #  Pop and push the length of this list
      <   #  And decrease it by 1
          #  (NOTE: only 1 is truthy in 05AB1E, so if the amount of prime factors was
          #  anything other than 2, this will be falsey)
          # (after which the filtered infinite list is output implicitly as result)

```

# Answer
> 8 votes
# Brachylog, 9 bytes

*-3 thanks to Unrelated String!*

This defines a predicate that unifies with all-inclusive-semi-primes. In Prolog this is equivalent to a generator, that will return all all-inclusive-semi-primes one by one.

```
ḋĊcẹo~⟦₁&

```

Try it online!

```
ḋĊcẹo~⟦₁&
ḋ         prime factors
 Ċ        are a pair (list of length 2)
  cẹ      and the elements of the concatenation (all the digits)
    o     ordered
     ~⟦₁  are the result of a range operation, f.e.
            4 ⟦₁ [1,2,3,4]
            [1,2,3,4] ~⟦₁ 4
        & return the input

```

# Answer
> 6 votes
# 05AB1E, 13 bytes

Outputs all **all-inclusive semi-primes**, not quite in ascending order.

```
7°ÅpâʒS{āQ}PÙ

```

Try it online!

**Commented**:

The `S{āQ` is borrowed from Kevin's answer.

```
7°              # push 10^7
  Åp            # push the first 10^7 primes
                # the first 5694505 would be enough but costs more bytes
    â           # take the cartesian product of that list with itself
                # to create all pairs of primes
     ʒ    }     # filter the pairs by
      S         #   split into a list of digits
       {        #   sort the digits
        ā       #   push the range [1 .. length]
         Q      #   are those lists equal?
           P    # take the product of each pair
            Ù   # take the unique elements

```

The different order is a result of the order of the cartesian product, pairs that start with `2` are first, then pairs with `3`, `7`... The order could be fixed by replacing `Ù` with `ê` (unique sort), but this would prevent output until all calculations are finished.

`98765431`, the `5694505th` prime number, is the largest prime that can be used to create an all-inclusive semi-prime.

# Answer
> 5 votes
# Husk, ~~21~~ ~~19~~ ~~18~~ ~~16~~ 14 bytes

(or **15 bytes** for versions that just output the n-th, or first *n* all-inclusive semi-primes, and so will always terminate instead of running indefinitely)

*Edit: -2 bytes thanks to Razetime's suggestion to just use `p` twice instead of my complicated approach of spending 3 bytes just to save one character...*

*...then another -1 byte, and again -3 bytes, thanks to Razetime*

*...then -2 more bytes thanks to Leo*

```
fȯεtpfȯS¦ŀṁdpN

```

Try it online!

Returns infinite list of all-inclusive semi-primes.
TIO header selects first 20 to avoid timing-out.

```
!fo§&o=2L(§=OoḣLṁd)pN
!                       # get the input-th element of
 f                  N   # natural numbers that satisfy
  o§&              p    # both conditions of prime factors:
     o=2L               # there are 2 of them, and
                ṁd)     # their digits
            O           # sorted
         (§=            # are equal to
             oḣL        # the sequence from 1..number of digits

```

# Answer
> 5 votes
# Stax, ~~22 21 17~~ 16 bytes

```
âH«q☻╧Ñ♦├x╓║Nm"°

```

Run and debug it

-1 byte using a generating block.

-4 bytes using a filter.

-1 byte from wastl.

Outputs infinite list, separated by newlines.

## Explanation (Uncompressed)

```
VIf|fY%2=y$eEc%R|}*
VIf                          filter natural numbers, printing truthy values
                             take current iteration value
    |fY                      store prime factorization in Y(without pop)
       %                     Length
        2=                   Equals 2?
          y                  Push prime factors again
           $eE               Convert to string, then to digits
              c%             copy and take length
                R            Range [1..length]
                 |}          are they setwise equal?
                   *         multiply the two values

```

# Answer
> 4 votes
# Japt, ~~22~~ ~~21~~ 19 bytes

Returns the first `n` terms; replace `j` with `i` to return the 0-indexed `n`th term.

```
È=k)cì ÍeX¬ÊõXÊÉ}jU

```

Try the first 10 terms or the first 100 terms

```
È=k)cì ÍeX¬ÊõXÊÉ}jU     :Implicit input of integer U
È                       :Function taking an integer X as argument
 =                      :  Reassign to X
  k                     :  Prime factors
   )                    :  End reassignment
    c                   :  Flat map
     ì                  :    Digit arrays
       Í                :  Sort
        e               :  Test equality with
         X¬             :    Join X
           Ê            :    Length (a)
             XÊÉ        :    Length of X minus 1 (b)
            õ           :    Range [b,a]
                }       :End function
                 jU     :Get the first U integers that return true (or the Uth, if using i)

```

# Answer
> 3 votes
# JavaScript (ES6), 108 bytes

Returns the **n**-th term, 1-indexed.

```
f=(n,k=2)=>(g=n=>a=q>n?'':n%q?g(n,q++):q+g(n/q,i--))(k,q=i=2)*i|[...a].sort().some(v=>v^++i)||--n?f(n,k+1):k

```

Try it online!

### Commented

```
f = (                   // f is a recursive function taking:
  n,                    //   n = input
  k = 2                 //   k = next integer to test
) => (                  //
  g = n =>              // g is a recursive function taking an integer and building
                        // a concatenation of its divisors
    a =                 //   assign the final result to a:
      q > n ?           //     if q is greater than n:
        ''              //       stop and coerce the answer to a string
      :                 //     else:
        n % q ?         //       if q is not a divisor of n:
          g(n, q++)     //         do a recursive call to g with q + 1
        :               //       else:
          q +           //         append q
          g(n / q, i--) //         and do a recursive call to g with n / q and i - 1
)(k, q = i = 2)         // initial call to g with n = k, q = 2 and i = 2
* i |                   // if i is not equal to 0 (i.e. k has not exactly 2 divisors)
[...a].sort()           // or the sorted digits of a ...
.some(v => v ^ ++i)     // ... do not match the sequence 1, 2, ..., x
|| --n ?                // or the previous conditions are met but decrementing n does
                        // not result in 0:
  f(n, k + 1)           //   do a recursive call to f with k + 1
:                       // else:
  k                     //   success: return k

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 123 bytes

outputs the nth term

```
(n=w=0;While[n<#,If[Last/@(f=FactorInteger)@w=={1,1}&&(s=Sort[Join@@(IntegerDigits@#&@@@f@w)])==Range@Max@s,n++];w++];w-1)&

```

Try it online!

the following prints all `36918` terms

# Wolfram Language (Mathematica), 139 bytes

```
Union@(f=Flatten)[Times@@d/@#&/@Select[f[(q=#;TakeDrop[q,#]&/@o)&/@Permutations[o=Range@#],1],And@@PrimeQ[(d=FromDigits)/@#]&]&/@3~Range~9]

```

Try it online!

# Answer
> 2 votes
# Java (JDK), ~~228~~...~~214~~ 212 bytes

-7 bytes thanks to @Kevin Cruijssen!

```
b->{int x=9,l,C[],y,i=b;for(;i>0;i-=b){y=++x;var s="";for(b=0;y>1&&b++<2;y/=l,s+=l)for(l=1;l++<y&y%l>0;);C=new int[l=s.length()];b-=y;for(var c:s.getBytes())b&=c-49<l&c>48?C[c-49]=1:0;for(int k:C)b&=k;}return x;}

```

Try it online!

Returns the nth element of the sequence (1-indexed).

Ungolfed:

```
b -> {
int x = 9, l, C[], y, b, i = b;
for (; i > 0; i -= b) {
    y = ++x;
    var s = "";
    for (b = 0; y > 1 && b++ < 2; y /= l, s += l)
        for (l = 1; l++ < y & y % l > 0;);
    C = new int[l = s.length()];
    b -= y;
    for (var c : s.getBytes())
      b &= c - 49 < l & c > 48 ? C[c - 49] = 1 : 0;
    for (int k : C) b &= k;
}
return x;
}

```

# Answer
> 2 votes
# Factor, ~~190~~ 175 bytes

```
: f ( n -- n ) 1 [ over 0 = ] [ dup factors [ 10 >base ] map
[ pair? ] [ concat [ length [1,b] [ 48 + ] map ] keep
diff ""= ] bi and [ [ 1 - ] dip ] when 1 + ] until nip 1 - ;

```

Try it online!

# Answer
> 1 votes
# Retina, ~~112~~ 111 bytes

```

123456789
L$`.
:::$>`
+%/\d$/&Lv$`(.)(.*:)(.)
$`$1$3$2$'
\d+
*
A`:_?:|(:_+)\1|:(__+)\2+:
:(_+):(_+):
$.($.1*$2

```

Try it online! Above program outputs the entire sequence, but TIO times out if the total number of semiprime digits is not less than 5, so the link only outputs six elements. Explanation:

```

123456789

```

Start with the potential semiprime digits.

```
L$`.
:::$>`

```

Get all their prefixes and add some markers to delimit the potential prime factors.

```
+%/\d$/&Lv$`(.)(.*:)(.)
$`$1$3$2$'

```

Generate all permutations of the digits among the potential primes.

```
\d+
*

```

Convert all the numbers to unary.

```
A`:_?:|(:_+)\1|:(__+)\2+:

```

Delete all results unless both numbers are prime and the first is greater than the second. This is one of the slowest parts of the program; Try it online! can calculate 23 results if these are split into separate filters. However, despite my best efforts, larger results are simply too slow.

```
:(_+):(_+):
$.($.1*$2

```

Calculate the resulting semiprimes.

# Answer
> 1 votes
# Raku, 123 bytes

```
{grep({$!=$_/($/=first $_%%*,2..$_);$!.is-prime&&{.[0]===.first(:k,0)}(+«[\∖]
"$!$/".comb.Bag,|('1'..'9'))},9..∞)[$_]}

```

Try it online!

* `$_` is the argument to the function.
* `grep(..., 9..∞)` filters the integers from nine to infinity. `[$_]` indexes into that sequence with the function argument and returns that value. Within the filtering function `$_` is the number being tested.
* `$! = $_ / ($/ = first $_ %% *, 2..$_)` sets `$/` to the smallest (necessarily prime) divisor of `$_`, and `$!` to `$_` divided by that number.
* If `$!` is not prime, then `$_` is not a semiprime, so the filter function returns false.
* `"$!$/"` is the concatenation of the semiprime's two factors.
* `.comb` returns a list of those digits.
* `.Bag` returns a bag (that is, a set with multiplicity) of those digits.
* `[\∖]` is a triangular reduction using the set-difference operator  on the list consisting of the aforementioned Bag and each of the digits from 1 to 9. The elements of this reduction are the initial Bag, then the same bag with a single `1` removed, then that second Bag with a single `2` removed, and so on.

Now the idea is to check that this sequence of bags gets exactly one element smaller as one of each successive digit is removed until it reaches a size of zero.

* turns that list of Bags into a list of their sizes (which counts multiplicity).
* That list of sizes is fed into the bracket-delimited anonymous function, which is immediately called. Within that function, `$_` refers to the list of sizes.
* `.first(:k, 0)` returns the index of the first zero element of the list. If no element is zero, `Nil` is returned instead.
* `.[0] === .first(:k, 0)` is true if the index of the first zero is equal to the first element of the list. This will be true only for lists of the form `N, N-1, N-2, ..., 1, 0, 0, 0`. From the way the list is constructed, each successive element can only ever be one or zero less than the preceding element.

# Answer
> 0 votes
# Python 3.8, 208 bytes

```
def f(x,r={26},n=9,R=range):
 while len(r)<x:
  for d in R(2,n:=n+1):n%d<1and all(k%i for k in(d,n//d)for i in R(2,k))*(l:=[*map(int,sorted(str(d)+str(n//d)))])==[*R(1,len(l)+1)]and r.add(n)
 return sorted(r)

```

Try it online!

Inputs an integer \\$n\\$ and output the first \\$n\\$ all-inclusive semi-primes (\\$1\\$-indexed).

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


# Question
Title: Fastest square root of an arbitrary size
We do seem to have a fastest square root challenge, but it's very restrictive. In this challenge, your program (or function) will be given an arbitrarily sized nonnegative integer, which is the square of an integer.

**Input**

You may take input in any normally allowed way, including (but not limited to) an arbitrary sized integer type, string in any base, or list of numbers representing digits.

**Output**

The allowed output methods are similar to the input ones, they just need to be in a way which can also represent a number of arbitrary size.

**Requirements**

* Your program should theoretically work correctly given any number (which is the square of an integer), assuming the language is capable of this
* All submissions should be in either:
    + A language with an online interpreter that can give (or be trivially modified to give) accurate times, and doesn't time out with your solution
    + A language with an interpreter/compiler available from the `apt` package manager, and is less than 1 GiB, in which case it will be run on my Chromebook's Linux VM
* If it doesn't take under 20 minutes, I'll just give a good estimate based on the first test cases and time complexity
* Built in square root functions are allowed (but boring :p)

**Scoring**

Your program's score will be the amount of time it takes to find the square root of:

* All 4096 perfect squares up to (not including) \\$2^{24}\\$
* A random (but same for all programs) 2048 perfect squares up to \\$2^{48}\\$
* A random (but same for all programs) 1024 perfect squares up to \\$2^{144}\\$
* A random (but same for all programs) 512 perfect squares up to \\$2^{1440}\\$
* A random (but same for all programs) 256 perfect squares up to \\$2^{5760}\\$
* A random (but same for all programs) 128 perfect squares up to \\$2^{14400}\\$
* A random (but same for all programs) 64 perfect squares up to \\$2^{86400}\\$

**UPDATE:** The numbers have been made bigger. This is a total of 8128 numbers as inputs, specifically these. Remember that fitting the test cases specifically is a standard loophole. The only part that counts toward the time is the math. I/O and setup can be ignored.

# Answer
> 11 votes
# C++, 140 µs

This is a trivial answer that uses GMP, but I’m submitting it anyway to drive home the point that **the test cases are way too small**. Scores in the range of literally nanoseconds per input cannot meaningfully be compared. We need larger test cases for this to be an interesting challenge.

```
#include <chrono>
#include <gmpxx.h>
#include <iostream>
#include <vector>

int main() {
  std::vector<mpz_class> numbers;
  mpz_class number;
  while (std::cin >> number)
    numbers.push_back(number);
  auto t0 = std::chrono::high_resolution_clock::now();
  for (auto &number : numbers)
    number = sqrt(number);
  auto t1 = std::chrono::high_resolution_clock::now();
  for (const auto &number : numbers)
    std::cout << number << '\n';
  std::cout
      << std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()
      << "ns\n";
}

```

Try it online!

# Answer
> 9 votes
# JavaScript (Node), Unknown time due to TIO not liking 2.6 million characters as the input.

If you want to see the previous tests, then Try it online!. Currently, we can't use TIO with all of the inputs.

```
function iroot(base) {
  let s = base + 1n;
  let u = base;
  if (!base) { console.log(0n); return; }
  while (u < s) {
    s = u;
    u = (u + base / u) / 2n;
  }
  return s;
}

const inputs = [/* the gist goes here*/]

console.time("sqrt");

inputs.map(iroot);

console.timeEnd("sqrt");

for (let i = 0; i < iroot.length; i++) {
  console.log(inputs[i]);
}

```

This is based off of a StackOverflow answer I did, which was based off of Newton's formula. This function is better than the built in `Math.sqrt()` or `Math.pow()` or `**` since this gives precision even to the last digits instead of 1.457746e57 or something like that. Also with BigInt, all numbers are `integers`, so you can't use `**` a decimal/fraction.

This code expects a long array to be prefilled with the numbers as bigints: https://gist.github.com/Samathingamajig/23b8107f299649d6bd3399b04f65c257 , which can be compressed into one line through this gist: https://gist.github.com/Samathingamajig/88f64e58ba21bd8d392be23bbb85dd9d

A Gist with all the data as raw JSON can be found here: https://gist.github.com/Samathingamajig/c15fd1f15a7bca6181a2e792c469503d

# Answer
> 8 votes
# Rust 450 μs

```
use std::time::SystemTime;
use num_bigint::BigUint;

fn main() {
    // Parse the numbers
    let mut numbers: Vec<_> = INPUT.iter().map(|i| {
        i.parse::<BigUint>().unwrap()
    }).collect();

    let start = SystemTime::now();

    // Do the calculation
    numbers.iter_mut().for_each(|s| *s = s.sqrt());

    // Print the time.
    println!("{}us", start.elapsed().unwrap().as_micros());
}

```

I agree that the input is too small. If performance was an issue, we would not use a library, but create a custom integer algorithm for monotonic series of integers, do them on SIMD hardware and multithreaded on 64 cores.

# Answer
> 4 votes
# Ruby, ~16-28 ms on TIO

```
def newtonRoot base
    s = base + 1
    u = base
    if base == 0
        return 0
    end
    while u < s do
        s = u
        u = (u + base / u) / 2
    end
    return s
end

t = Time.now
outputs = inputs.map{ |i| newtonRoot i }
puts "> time elasped: #{ (Time.now - t) * 1000 } ms.\n\n"

puts outputs.map{ |v| v * v } == inputs

# un-comment below line to see outputs!
# outputs.map{ |i| print "#{i}, " }

```

The former code is a modification of latter code, which is specific to the square root of a "perfect square", and a bit faster!

Try it online!

---

# Ruby, ~22-36 ms on TIO

```
def newtonRoot (base, root)
    s = base + 1
    k1 = root - 1
    u = base
    if (base == 0)
        print "0, "
        return
    end
    while (u < s) do
        s = u
        u = ((u * k1) + base / (u ** k1)) / root
    end
    print "#{s}, "
end

t = Time.now

inputs.each{|i| newtonRoot(i, 2)}

puts "\n\n> time elasped: #{ (Time.now - t) * 1000 } ms."

```

A remix of Newton's formula in Ruby. I posted this as I think Ruby is very fast.

# Answer
> 4 votes
# JavaScript (Node.js), \< 60 ms on TIO

```
function iroot(input) {
  let bit = 1n << BigInt(input.toString(2).length - 1 >> 1);
  let root = 0n;
  while (bit) {
    let diff = (root + root + bit) * bit;
    if (input >= diff) {
      input -= diff;
      root += bit;
    }
    bit /= 2n;
  }
  return root;
}

console.time("sqrt");
let roots = inputs.map(iroot);
console.timeEnd("sqrt");

for (let root of roots) {
  console.log(root);
}

```

Try it online! Can't remember the name of this method sorry, but it's very handy for square rooting floating-point numbers by shifting as the bit is always `1` thus reducing the complexity even further.

# Answer
> 3 votes
# Python 3, unknown time

Finishes the first 7979 cases on my machine after 19.2 minutes. (Using `head -n 7979 input.txt | python3 sqrt.py`)

```
from time import time

numbers = []
try:
  while True:
    numbers += [int(input())]
except:
  pass

t1 = time()

for i in range(len(numbers)):
  base = numbers[i]
  u, s = base, base + 1
  if u:
    while u < s:
      u, s = (u + base // u) // 2, u
  numbers[i] = u

t2 = time()
print(t2 - t1, "seconds")

```

Uses the same method as Samathingamajig's answer.

# Answer
> 2 votes
# Rust Babylonian + New data 33 ms

This uses the new, larger data set and a novel recursive version of the Babylonian algorithm.

The algorithm refines the guess for the babylonian by calculating the square root of the top half of the number, which is much less expensive.

use num_bigint::BigUint;
use std::time::SystemTime;
use num_traits::{FromPrimitive, ToPrimitive};
use rayon::prelude::*;

fn recursive_babylonian_sqrt(a: &BigUint) -> BigUint {
    if a.bits() < 53 {
        //println!("a={} exact={}", a, BigUint::from_f64(a.to_f64().unwrap().sqrt()).unwrap());
        return BigUint::from_f64(a.to_f64().unwrap().sqrt()).unwrap();
    }

    let mut guess = recursive_babylonian_sqrt(&(a >> a.bits()/4*2)) << (a.bits()/4);
    //println!("a={} sqrt={} guess={}", a, a.sqrt(), guess);

    //let mut nits = 0;
    loop {
        let mut new = a / &guess;
        new += &guess;
        new >>= 1;
        //nits += 1;
        if new == guess {
            break;
        }
        guess = new;
    }
    //println!("{} nits", nits);
    guess
}

pub fn main() {
    let text = std::fs::read("numbers-updated.txt")
        .unwrap();

    let numbers : Vec<_> = text[0..text.len()-1]
        .split(|c| *c == b'\n')
        .map(|s| std::str::from_utf8(s).unwrap().parse::<BigUint>().unwrap() )
        .collect();

    let start = SystemTime::now();

    let result : Vec<_> = numbers
        .par_iter()
        .map(|s| recursive_babylonian_sqrt(s))
        .collect();

    // Print the time.
    println!("{}us", start.elapsed().unwrap().as_micros());

    numbers
        .iter()
        .zip(result.iter())
        .for_each(|(n, r)| assert_eq!(&n.sqrt(), r));
}
```

---
Tags: math, number, fastest-code
---


title: Substitute a string with itself!

text:
# Question
Title: Substitute a string with itself!
## Substitute a string with itself

Your goal is to substitute a string with itself by replacing each character in the original string with the one before it, starting with the first character and wrapping around. Here are some examples to show what I mean:

1st example:

```
Input: program
Output: apgopra

How:
Program -> mrogram (replace p by m in program)
-> mpogpam (replace r by p in mrogram)
-> mprgpam (replace o by r in mpogpam)
-> mpropam (replace g by o in mprgpam)
-> mpgopam (replace r by g in mpropam)
-> mpgoprm (replace a by r in mpgopam)
-> apgopra (replace m by a in mpgoprm)

```

2nd example:

```
Input: robot
Output: orbro

How:
Robot -> tobot (replace r by t in robot)
-> trbrt (replace o by r in tobot)
-> trort (replace b by o in trbrt)
-> trbrt (replace o by b in trort)
-> orbro (replace t by o in trbrt)

```

3rd example:

```
Input: x
Output: x

How:
x -> x (replace x by x in x)

```

4th example:

```
Input: xy
Output: xx

How:
xy -> yy (replace x by y in xy)
-> xx (replace y by x in yy)

```

Sidenotes:

* The string `x` will only contain lowercase alphanumeric characters and spaces
* This is so shortest code in **bytes** wins!

# Answer
> 19 votes
## CJam, 11 bytes

```
q__1m>.{er}

```

Test it here.

### Explanation

```
q__    e# Read input and make two copies.
1m>    e# Rotate the second copy one character to the right.
.{er}  e# For each pair of characters from the second and third string,
       e# replace occurrences of the first with the second.

```

# Answer
> 9 votes
# TeaScript, 17 bytes ~~19~~ ~~21~~ ~~24~~

TeaScript is JavaScript for golfing

```
xd(#lg(i,xC(1#a))

```

Nice and short

Try it online (watch for trailing whitespace in the input)

### Ungolfed & Explanation

```
x.reduce     // Reduce over input
  (#         // Anonymous function expands to ((l,i,a)=>
    l.g(        // global replace...
     i          // replace var i with...
     x.cycle(1) // Cycle x 1
     [a]        // At position a
    )
  )

```

# Answer
> 8 votes
# JavaScript ES6, 69 bytes

```
s=>[...s].reduce((p,c,i)=>p.replace(RegExp(c,'g'),s.slice(i-1)[0]),s)

```

```
F=s=>[...s].reduce((p,c,i)=>p.replace(RegExp(c,'g'),s.slice(i-1)[0]),s)

input.oninput=()=>output.innerHTML=F(input.value)
```

```
#input, #output {
  width: 100%;
}
```

```
<textarea id='input' rows="5">
</textarea>
<div id="output"></div>
```

# Answer
> 3 votes
# Mathematica, ~~89~~ ~~75~~ ~~74~~ 57 bytes

```
""<>Fold[#/.#2&,c=Characters@#,Thread[c->RotateRight@c]]&

```

# Answer
> 3 votes
# Ruby, ~~50~~ 48 bytes

```
->s{t=s.dup;t.size.times{|i|t.tr!s[i],s[i-1]};t}

```

Test:

```
f=->s{t=s.dup;t.size.times{|i|t.tr!s[i],s[i-1]};t}
f["program"]
=> "apgopra"

```

# Answer
> 3 votes
# Pyth, 13 bytes

```
u:G.*HC.>Bz1z

```

Try it online. Test suite.

# Answer
> 3 votes
# k2 - 17 char

Function taking 1 argument.

```
{_ssr/[x;x;-1!x]}

```

k2 has a builtin called `_ssr` for **S**tring **S**earch and **R**eplace. `_ssr[x;y;z]` will find `y` in `x` and replace it with `z`. So we use `/` to fold this functionality over each replacement we want to make. For those unfamiliar with folding (as in functional programming), essentially `_ssr/[x; (y1; y2; y3); (z1; z2; z3)]` becomes `_ssr[_ssr[_ssr[x; y1; z1]; y2; z2]; y3; z3]`. Strings are lists of their characters, so we may simply rotate the input back a step and get the replacements, and plug right in.

```
  {_ssr/[x;x;-1!x]} "program"
"apgopra"
  {_ssr/[x;x;-1!x]} "robot"
"orbro"
  {_ssr/[x;x;-1!x]} (,"x")   / one-letter strings are ,"x" and parens are required
,"x"
  {_ssr/[x;x;-1!x]} "xy"
"xx"

```

# Answer
> 2 votes
# Python, ~~67~~ ~~64~~ ~~62~~ 57 Bytes

Straightforward solution, will look into something to shorten this. Thanks to @RandyC for saving 5 bytes.

```
c=input()
for x in zip(c,c[-1]+c):c=c.replace(*x)
print c

```

Input should be in quotes.

# Answer
> 2 votes
# Haskell, 76 bytes

```
[]#_=[];(x:y)#g@(a,b)|x==a=b:y#g|2>1=x:y#g;h x=foldl(#)x$zip x$last x:init x

```

Too bad, Haskell doesn't even have a build-in substitution function.

# Answer
> 2 votes
## PHP, 76 bytes

```
function($s){$f=str_split;echo str_replace($f($s),$f(substr($s,-1).$s),$s);}

```

Here is the ungolfed version:

```
function selfSubstitute($originalString)
{
    $shiftedString = substr($originalString, -1) . $originalString;

    $splitOriginalString = str_split($originalString);
    $splitShiftedString = str_split($shiftedString);

    echo str_replace($splitOriginalString, $splitShiftedString, $originalString);
}

```

# Answer
> 2 votes
# Haskell, 58 bytes

```
r(x,y)c|x==c=y|0<1=c;f s=foldl(flip$map.r)s.zip s$last s:s

```

Pretty similar to Christian's solution, but using `map` and the fact that `zip` ignores superfluous elements if the lists are of unequal length. It folds through the list of replacements (on the form `(from,to)`), updating the string by mapping the hand written replacement function `r` on each letter.

The expression `flip$map.r` was derived using LambdaBot's "Pointless" plugin.

# Answer
> 2 votes
# Jelly, ~~10~~ ~~9~~ 7 bytes

```
ṙ-ż@y@ƒ

```

Try it online!

Having seen caird's `y`-based solution, I spent several hours trying to use matrix multiplication instead, but eventually I took a crack at `y` and arrived at this.

Speaking of caird's solution, I was about to pose the question to JHT of how to outdo `J_.ịƲU` for "obtaining pairs of elements from the input followed by the elements preceding them, wrapping around", but as I wrote that whole thing out I realized I never did actually try using `ż`!

The edit history contains some nice old explanations if anyone wants to read them.

```
ṙ          Rotate the input left
 -         by -1.
  ż@       Zip the input with the rotated input.
      ƒ    Starting with the input, reduce the resulting pairs by
    y@     substitution.

```

# Answer
> 1 votes
# Jelly, 15 bytes

```
żṙ-$,µ,Ḣy¥¥/ḷ/¿

```

Try it online!

Jelly sucks at strings

## How it works

```
żṙ-$,µ,Ḣy¥¥/ḷ/¿ - Main link. Takes a string S on the left
   $            - Group the previous two links together:
  -             -   -1
 ṙ              -   Rotate S 1 unit to the right
ż               - Zip S with rotated S; Call this M
    ,           - Pair with S; [M, S]
     µ          - Begin a new link with this pair as the argument
          ¥     - Group the previous two links together as a dyad f(p, s):
         ¥      -   Group the previous two links together as a dyad g(p, s):
       Ḣ        -     Remove the first pair in p and use it; [c, t]
        y       -     Replace c with t in s
      ,         -   Yield a pair with the modified p and the replaced s
              ¿ - While:
            ḷ/  -   The first element is truthy
           /    -   Run f(M, S)

```

# Answer
> 1 votes
# Japt, 5 bytes

```
dUíUé

```

Try it

```
dUíUé     :Implicit input of string U
d         :For each pair XY in the following string, recursively replace X with Y
 Uí       :  Interleave U with
   Ué     :  U rotated right

```

# Answer
> 1 votes
# , 18 bytes

```
rplc~/@,~|.,.1|.|.

```

Try it online!

# Answer
> 0 votes
# Perl 5 `-pF`, 34 bytes

```
for$a(0..$#F){s/$F[$a]/$F[$a-1]/g}

```

Try it online!

# Answer
> 0 votes
# Brachylog, 29 bytes

```
⟨tc≡⟩⟨gcs₂ᶠ⟩{gᵗz{tᵛ&th|h}ᵐ}ˡb

```

Try it online!

```
  c                   Concatenate
 t                    the last item of the input
⟨  ≡⟩                 with the input.
       c              Concatenate
      g               that result in a singleton list
     ⟨  s₂ᶠ⟩          with a list of its length-2 substrings.
             ... b    Remove the extra element from the final result.

{             }ˡ      Left fold:
 gᵗz                  zip each element of the first element with the entire second element,
    {       }ᵐ        and for each of those pairs:
     tᵛ               the last element of both is the same
       &th            and the first element of the last element of the pair
          |           is the output, or
           h          the first element of the pair is the output.

```

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