title: Is it a brainfuck instruction?

text:
# Question
Title: Is it a brainfuck instruction?
A very simple challenge today. Output a truthy value whether the ASCII character (or it's code) supplied is a brainfuck instruction (one of `+-,.<>[]`), and a falsy value if it's a comment (everything else).

## Input

```
+
#
<
>
.
P
,

```

## Output

```
true
false
true
true
true
false
true

```

# Answer
# brainfuck, ~~105~~ ~~103~~ 95 bytes

Outputs `\x00` for false and `\x01` for true.

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

```

Try it online!

The general principle is comparing against all values (decreasing partial distances of the char-codes), using loops to logically `OR` the results, and if none matched - change the output cell from `1` to `0`.

See my `4` answer for a more detailed explanation (`4` instructions read more easily).
> 21 votes

# Answer
# unsure, 1302 bytes

```
um um yeah err hm yeah uhhhhhhhh then ummmm uhhh errrr uhh errr ummmmm yeah err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops oops oops um then heh then uhhhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops oops um then heh then uhhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops um then heh then uhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops um then heh then uhhhhhh no oops oops then ummmmmmm uh errr uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops um then heh then uhhhhh no oops oops then umm err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops um then heh then uhhhh no oops oops then ummmmmm uhhh ummmmm errrrrr uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops um then heh then uhhh no oops oops then umm err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops um then heh then uhh no oops oops oops okay

```

This was not easy. Unsure is a new stack based language I've created, that uses words people tend to say when they're not sure about something.

It's kind of hard to explain how such a large program works, but I'll try to give a high-level explanation. First, here's an expanded version of this program:

```
um um yeah err hm yeah uhhhhhhhh then ummmm uhhh errrr uhh errr ummmmm yeah err uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops oops oops oops oops oops oops um then heh then uhhhhhhhhh no oops oops then um err uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops oops oops oops oops oops um then heh then uhhhhhhhh no oops oops then um err uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops oops oops oops oops um then heh then uhhhhhhh no oops oops then um err uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops oops oops oops um then heh then uhhhhhh no oops oops then ummmmmmm uh errr uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops oops oops um then heh then uhhhhh no oops oops then umm err uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops oops um then heh then uhhhh no oops oops then ummmmmm uhhh ummmmm errrrrr uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops um then heh then uhhh no oops oops then umm err uh

then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops um then heh then uhh no oops oops

oops okay

```

The first part sets up the stacks. There are two stacks, one of which is selected as the active stack. The first stack contains a `0` at the bottom (the return value), as well as 8 copies of the input character's ASCII character code, negated.

After this, there are 8 sections to check for equality (first one shown as an example):

```
then heh then err um heh
but um um yeah err heh no oops then
but oops heh oops oops oops oops oops oops oops oops um then heh then uhhhhhhhhh no oops oops then um err uh

```

The first line will pop the first stack and add it to the first, which in this case is `43` (the character code for `+`). It also pushes `1` to the first stack. The next line is essentially an if statement, which is used to create a NOT operator by pushing `0` to the first stack if the result of adding the character code is not `0` (meaning they are not the same).

The third line is the most complicated. It starts with a sort of else statement, as it only runs when the second line's if statement doesn't push `0` (and therefore the character code was 43). It will then replace the bottom of the first stack with `1`, the new output.

Finally, after the "else statement", the character code is incremented to 44, for `,`, and the process is repeated 7 times.

The last line, `oops okay`, just outputs the bottom item in the first stack, as the previous operations have cleared it out except for one copy of the input (`oops` discards the top of the stack, and `okay` outputs).

There's definitely a few bytes I could golf here and there, might work on it later.
> 12 votes

# Answer
# Retina 0.8.2, 9 bytes

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

```

Try it online! Link includes test cases. Explanation: This is actually a character class; the outer `[]`s delimit the class, as (by being placed immediately after the opening `[`) the first `]` is actually part of the class. The `,` isn't needed as the `-` creates a range from `+` to `.` which helpfully includes the `-` itself as well as the `,`.
> 11 votes

# Answer
# Python, 16 bytes

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

```

Try it online!

An anonymous method is shorter here than a `lambda`. See my tip Object method as answer.
> 10 votes

# Answer
## vJASS (Warcraft 3), ~~299~~ ~~278~~ 265 bytes

Using `//! import zinc "<code_path>"` command to exclude `//! zinc` and `//! endzinc`.

---

Prints T (True) and F (False).

```
library Q{trigger W=CreateTrigger();integer E;function onInit(){TriggerRegisterPlayerChatEvent(W,Player(0),"",false);TriggerAddAction(W,function(){for(0<=E<8){if(GetEventPlayerChatString()==SubString("+-<>.,[]",E,E+1)){BJDebugMsg("T");return;}}BJDebugMsg("F");});}}

```

---

**Readable Version:**

```
library CodeGolf{
    trigger chatEvent = CreateTrigger();
    integer Index;

    function onInit(){
        TriggerRegisterPlayerChatEvent(chatEvent, Player(0), "", false);
        TriggerAddAction(chatEvent, function(){
            for (0 <= Index < 8){
                if(GetEventPlayerChatString() == SubString("+-<>.,[]", Index, Index + 1)) {
                    BJDebugMsg("T");
                    return;
                }
            }
            BJDebugMsg("F");
        });
    }
}

```

---

**Output:**
> 7 votes

# Answer
# 05AB1E, 11 bytes

+1 due to a bug fix noted by @Kevin Cruijssen

-1 thanks to @Kevin Cruijssen

```
"+-,.<["ºIå

```

Try it online!

an interesting approach, but sadly it's longer and it doesn't work:

```
•q”;ιÚ•2ôIÇ;îå

```

Try it online!
> 5 votes

# Answer
# Haskell, 18 bytes

```
(`elem`"+-.,<>[]")

```

Try it online!

Low-effort unnamed function.
> 4 votes

# Answer
# Python 3, ~~26~~, 23 bytes

```
lambda s:s in'+-,.<>[]'

```

Try it online!
> 3 votes

# Answer
# , 131 bytes

Outputs `\x00` for false, `\x01` for true.

```
3.799600006010160202614146292964343199994389919999018991999901899199990189919999148991999902899199992989919999028995004999999995014

```

Try it online!

## Explanation

**4 doesn't have a simple comparison or condition instructions**, so I used while-not-zero loops to fake them and match by distances:

```
3.

6 00 00            # set constants
6 01 01
6 02 02
6 14 14
6 29 29
6 43 43

7 99               # input as integer

1 99 99 43 - 8 99  # for each brainfuck character
1 99 99 01 - 8 99  # compare to the input,
1 99 99 01 - 8 99  #  (subtracting differences to the input)
1 99 99 01 - 8 99  #  and jump to the end if true,
1 99 99 14 - 8 99  #  otherwise start a loop (to fake branching)
1 99 99 02 - 8 99
1 99 99 29 - 8 99
1 99 99 02 - 8 99
5 00 4             # if all comparisons failed, print 'false' and exit
9 9 9 9 9 9 9 9    # close loops

5 01 4             # print 'true' and exit

```
> 3 votes

# Answer
# C (gcc), 28 bytes

```
f(c){c=index("+-,.<>[]",c);}

```

No math here, no math there, no math anywhere.

Try it online!
> 3 votes

# Answer
# Pyke, 3 bytes

Built-ins FTW!

```
~B{

```

Try it online!

# Explanation

```
~B  "><+-.,[]"
  { Does it contain input?

```
> 3 votes

# Answer
# Fig, \\$10\log\_{256}(96)\approx\\$ 8.231 bytes

```
Ix"[]-=.,"

```

Try it online!

~~An answer so the bot can get 30 rep to chat.~~ Never mind, realized I had enough on SF&F, but deleting this would be useless, so here ya go.
> 3 votes

# Answer
# 6502 assembly, 17 bytes

```
0000: 69 05 29 FD A2 04 D5 0C
0008: F0 03 CA D0 F9 60 30 31
0010: 41

```

This subroutine should be called with A set to the input, and the carry flag cleared. It will return with the Z flag indicating whether the input was a Brainfuck instruction.

Here the subroutine is at `$0000` but it can go anywhere on the zero page. The asterisk in `cmp *r-1,x` forces a 2-byte zero-page-based comparison (in this web assembler, at least).

```
.org $0000
f:
  adc #5
  and #$fd
  ldx #4
loop:
  cmp *r-1,x
  beq r
  dex
  bne loop
r:
  rts  ; which is #$60
.byte $30, $31, $41

```

## How it works

The valid Brainfuck instructions are {2b, 2c, 2d, 2e, 3c, 3e, 5b, 5d} in hexadecimal. Adding 5 to the ASCII values groups them into pairs like "n or n+2" where the second-lowest bit doesn't matter:

| Instruction | ord+5 | Bit pattern |
| --- | --- | --- |
| `+` or `-` | `$30` or `$32` | 0011 00x0 |
| `,` or `.` | `$31` or `$33` | 0011 00x1 |
| `<` or `>` | `$41` or `$43` | 0100 00x1 |
| `[` or `]` | `$60` or `$62` | 0110 00x0 |

This means we can check if `(n+5)&~2` ∈ {`$30`, `$31`, `$41`, `$60`}.

Actually a lot of choices other than `5` work. But this one puts `$60` in the set of values to look for, which is the opcode for the `RTS` instruction. Thus we can interleave the table with the final instruction and save one byte.
> 3 votes

# Answer
# Keg, `-rt`, 10 bytes

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

```

This:

* Pushes the string `[]+-,.<>` onto the stack
* Subtracts that string from the input.

If it is a BF instruction, an empty string will be printed, otherwise, the input character will be printed.
> 2 votes

# Answer
# Python 3, 26 bytes

```
print(input()in"+-,.<>[]")

```
> 2 votes

# Answer
# Desmos, 43 bytes

```
1\left\{42<i<47,i=60,i=62,i=91,i=93\right\}

```

Try it online

Desmos doesn't support strings, so this turns from relatively trivial string comparison to relatively trivial integer comparison. I tried to compress the higher numbers, but I couldn't find a nice way to exclude 61 and 92, and the sequence doesn't show up in OEIS.
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
kŻ$Ƈ

```

**11 bytes:**

```
"[]<>-+.,"$Ƈ

```

**14 bytes:**

```
»ÐṘWĠœṪɲ»ɦBCsƇ

```

**16 bytes:**

```
C¿€ỵæ-j2oẹ&⁵ẏ¿sƇ

```

Due to a bug with the `Ƈ` command (which will be fixed in 2.2.0), the `s` is needed in the last two answers. They will both be one byte less in 2.2.0.

### Explanations

```
kŻ$Ƈ  # Implicit input
  $   # The input...
   Ƈ  # ...is in...
kŻ    # ...the string "[]<>-+.,"
      # Implicit output

```

```
"[]<>-+.,"$Ƈ  # Implicit input
          $   # The input...
           Ƈ  # ...is in...
"[]<>-+.,"    # ...the string "[]<>-+.,"
              # Implicit output

```

```
»ÐṘWĠœṪɲ»ɦBCsƇ  # Implicit input
»ÐṘWĠœṪɲ»       # Compressed integer 4344454660629193...
         ɦB     # ...converted to base 100 as a list...
           C    # ...and converted to ordinals...
            sƇ  # ...contains the input
                # Implicit output

```

```
C¿€ỵæ-j2oẹ&⁵ẏ¿sƇ  # Implicit input
C                 # The ordinal of the input...
              sƇ  # ...is in...
 ¿€ỵæ-j2oẹ&⁵ẏ¿    # ...the compressed list [43, 44, 45, 46, 60, 62, 91, 93]
                  # Implicit output

```

#### Screenshots
> 2 votes

# Answer
# Japt , 63 bits / 7.875 bytes

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

```

Try it

(Because, apparently, we're scoring in bits now? ♂)
> 2 votes

# Answer
# 6502 Machine-Language, 32 bytes

```
0000: AD 1E 00 A2 00 DD 15 00
0008: D0 04 EE 1F 00 00 E8 EC
0010: 1D 00 D0 F1 00 3C 3E 2B
0018: 2D 2E 2C 5B 5D 08 50 00

```

The above "ROM" includes the variables and the program. Here's a basic breakdown:

```
0000: AD 1D 00 A2 00 DD 14 00    Program
0008: D0 04 EE 1E 00 00 E8 EC
0010: 1C 00 D0 F1 00
                     3C 3E 2B    Brainfuck instructions
0018: 2D 2E 2C 5B 5D 08          ("<>+-.,[]" and an 8 for the length)
                        50 00    Input char and output byte

```

You can try it out using This online emulator by copying the above ROM into the "RAM" field and setting the input byte (`0x001D`) to the desired character in hexadecimal. Then you can load it into memory by pressing "Load Memory", then press "Show Memory" to confirm it loaded and check the box "live update" so it will show the result once it's done. Finally, you can press "Continuous Run" and it will write the result to the last byte of the ROM (`0x001E`). `0x01` for true and `0x00` for false.

Assembly Code:

```
.ORG $0000

; PROGRAM

  LDA INPUT
  LDX #0
loop:
  CMP CHARS,X
  BNE end
  INC OUTPUT
  BRK
end:
  INX
  CPX CHARSLEN
  BNE loop
  BRK

; DATA

CHARS:
  .ASCII "<>+-.,[]"
CHARSLEN:
  .BYTE 8
INPUT:
  .ASCII "P"
OUTPUT:
  .BYTE 0

```

To summarise, it basically reads the input character into the accumulator and then loops over the list of Brainfuck instructions using the X register and if Acc matches any of the chars it increments the output byte and exits.

It's probably not very good and could also probably be smaller, but I'm not very experienced with 6502 assembly and just wanted to give it a go. Feedback welcome :)

(I also haven't tested it very thoroughly so it might also not work in some cases)
> 2 votes

# Answer
# JavaScript (Node.js), ~~25~~ 23 bytes

*-2 thanks to @Arnauld*

```
c=>/[+-.<>[\]]/.test(c)

```

Try it online!
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 45 bytes

```
 "<>[]+-,." INPUT :F(F)
 X =1
F OUTPUT =X
END

```

Try it online!

1 for truthy, empty line for falsey.
> 1 votes

# Answer
# Pyth, 10 bytes

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

```

Try it online!
> 1 votes

# Answer
# Kotlin, 18 bytes

```
{it in "+-<>[].,"}

```

Try it online!
> 1 votes

# Answer
# Scala 2.12, 15 bytes

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

```

This takes the string of all brainf\*** instructions and turns it into a set. Since Scala's sets are also predicates, we can treat it like a function that returns `true` when it's a valid instruction.

Scala 2.12 is required for postfix operator `toSet`.

Try it online
> 1 votes

# Answer
# Arn, 9 bytes

```
[‚‚◄┴´£Q7

```

Try it!

# Explained

Unpacked: `"+-.,<>[]"&`

```
  "+-.,<>[]" Literal string
& Contains element
  _ Variable initialized to STDIN; implied

```
> 1 votes

# Answer
# Jelly, 10 bytes

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

```

Try it online!

## How it works

```
ẇ“+-<>[],. - Main link. Takes a character C on the left
 “+-<>[],. - Yield "+-<>[],."
ẇ          - Is C in that string?

```
> 1 votes

# Answer
# Red, 27 bytes

```
""= exclude input"+-,.<>[]"

```
> 1 votes

# Answer
# Vyxal `r`, 11 bytes

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

```

Try it Online!

More interestingly,

# Vyxal `r`, 13 bytes

```
C₁»½¤Ǎ⋏⟨꘍ċ»τc

```

Try it Online!

```
C             # Get charcode
 ₁»½¤Ǎ⋏⟨꘍ċ»τ  # Base-100 list of valid charcodes
            c # Is included?

```
> 1 votes

# Answer
# Julia 1.0, 14 bytes

```
in("+-,.<>[]")

```

Try it online!

some Julia functions will return an anonymous function when fed with not enough arguments, basically `in(x) = y -> in(y,x)`. It would be a bit more interesting with  but it costs 1 more byte.
> 1 votes

# Answer
# Pxem (pxem.mktemp.emb.posixism, `BREAK_LOOP_WHEN_INSUFFICIENT=1`), filename only: 33 bytes.

The `\0001` is an unprintable whose codepoint is 0x01.

```
[<>+-,.].i.t@.w.m.-\0001.yT.o.d.a.c.a

```

Try it online!

Accepts one character from stdin as an input. Outputs a T for truthy, nothing for falsey.

---

# Pxem (pxem.mktemp.emb.posixism, `BREAK_LOOP_WHEN_INSUFFICIENT=0`), filename only: 42 bytes.

The `\0001` is an unprintable whose codepoint is 0x01.

```
[<>+-,.].i.t@.w.c.c.z.d.a.m.-\0001.yT.o.d.a@.a

```

Try it online!

Accepts one character from stdin as an input. Outputs a T for truthy, nothing for falsey.
> 1 votes

# Answer
# Factor, 17 bytes

```
[ "+-,.<>[]"in? ]

```

Try it online!
> 1 votes

# Answer
# Ly, 14 bytes

```
"+-,.()[]"i~u>

```

Try it online!

```
"+-,.()[]"      - Push legit characters onto the stack
          i     - Read codepoint from STDIN
           ~    - Pop stack, search stack for that codepoint, push 1|0 result
            u   - Print top of stack as a number (will be 1 or 0)
             >  - Switch stacks to avoid printing the current contents

```
> 1 votes

# Answer
# jq, 18 bytes

```
inside("+-,.<>[]")

```

Try it online!

* Fix+4 thanks to @JoKing
> 1 votes

# Answer
# Scratch, 22 bytes

```
if <symbol v] contains (input) then
set [output v] to [true]
else
set [output v] to [false]

```

Try it online!
> 1 votes

# Answer
# Lua, 31 bytes

```
print((...):match'[[%]+-.,><]')

```

Try it online!

Prints either the inputted character (strings are always truthy) or nil (which is falsy).
> 1 votes

# Answer
# C (gcc) XPG4.2/Single UNIX Specification, Version 3, POSIX:2001, 30 bytes

```
f(c){c=!!index("+-,.<>[]",c);}

```

Try it online!
> 0 votes

# Answer
# APL+WIN 12 bytes

3 bytes saved thanks to @Avi F. S.

Prompts for character and returns 1 if `true` 0 if `false`:

```
⎕∊'+-,.<>[]'

```

Try it online! Courtesy of Dyalog Classic
> 0 votes

# Answer
# C (gcc), 31 bytes

```
f(c){c=!!strchr("+-,.<>[]",c);}

```

Try it online!
> 0 votes

# Answer
# Ruby `-nl`, 16 bytes

Input is STDIN. Prints `0` (Ruby truthy) or `nil` (falsy).

Annoyingly, it seems like Ruby demands that both `[` and `]` be escaped in the character class regex.

```
p~/[+-,.<>\[\]]/

```

Try it online!
> 0 votes

# Answer
# JS, 26 bytes

```
c=>'+-,.<>[]'.indexOf(c)+1

```

# x86\_16 machine code, 40 bytes

Outputs '0' (false) or '1' (true) on the screen.

```
bb1f 7cb1 5080 3f00 7409 380f 7409 83c3
01eb f2b0 30eb 02b0 31b4 0ecd 10eb fe2b
2d2c 2e3c 3e5b 5d00

```

**To boot, pad it to 510 bytes with zeros and add 55aa at the end!<br>This means "uncomment the last two assembly lines and rebuild".**

Ungolfed (compilable, compile using nasm -fbin -o is-bf is-bf.asm):

```
[org 0x7c00]

mov bx, string
mov cl, 'P' ; the character
loop_:
    cmp byte [bx], 0
    je false
    cmp byte [bx], cl
    je true
    add bx, 1
    jmp loop_
false:
    mov al, '0'
    jmp print
true:
    mov al, '1'
print:
    mov ah, 0eh
    int 10h
jmp $ ; hang forever

string: db "+-,.<>[]", 0
; times 510 - ($-$$) db 0
; dw 0xaa55

```
> 0 votes

# Answer
# LaTeX, 52 bytes

```
\usepackage{xstring}\def\f#1{\IfSubStr{[]+-.,}#1x{}}

```

Defined a macro `\f` that takes one argument and expands to `x` if the input is a brainfuck instruction and to nothing if not. Assumes there is only one character in the argument.

## Explanation

```
\usepackage{xstring}  % load the xstring package for the IfSubStr macro
\def\f#1{             % define a macro \f that takes 1 argument
  \IfSubStr{[]+-.,}#1 % test if the second argument is a substring of the first
    x                 % if it is a substring expand to x
    {}                % else expand to nothing
}

```
> 0 votes

# Answer
# CJam, ~~14~~ 12 bytes

*-2 bytes by treating as a self-contained program instead of a block.*

```
"+-<>[].,"q#

```

Try it online!

Returns -1 if not a brainfuck character, anything else if so.
> 0 votes

# Answer
# Perl 5 `-p`, 15 bytes

```
$_=y/+,.<>[]-//

```

Try it online!
> 0 votes

# Answer
# Java (JDK), 20 bytes

```
"<[+.,-]>"::contains

```

Try it online!
> 0 votes

# Answer
# ARBLE, 21 bytes

```
find(c,"[[%]+-.,><]")

```

Returns `1` for truthy, or nothing for falsey.

Try it online!
> 0 votes

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


title: Continued Fraction of a Rational Number

text:
# Question
Title: Continued Fraction of a Rational Number
The **continued fraction** of a number `n` is a fraction of the following form:
which converges to `n`.

The sequence `a` in a continued fraction is typically written as: \[a0; a1, a2, a3, ..., an\].

Your goal is to return the continued fraction of the given rational number (positive or negative), whether it is an:

* integer `x`
* fraction `x/y`
* decimal `x.yz`

**Input**

May be a string representation, or numbers. For fractions, it may be a string, or some native data type for handling fractions, but you may not take it as a decimal.

**Output**

May be a delimited list or string of the *convergents* (the resulting numbers). The output **does not have to have a semi-colon** between a0 and a1, and may use a comma instead.

Note that although `[3; 4, 12, 4]` and `[3; 4, 12, 3, 1]` are both correct, only the first will be accepted, because it is simpler.

### Examples:

```
860438      [860438]
3.245       [3; 4, 12, 4]
-4.2        [-5; 1, 4]
-114.7802   [-115; 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]
0/11        [0]
1/42        [0; 42]
2/7         [0; 3, 2]
-18/17056   [-1; 1, 946, 1, 1, 4]
-17056/18   [-948; 2, 4]

```

### Rules

* Shortest code wins.
* Built-ins are allowed, but I'd also like you to post in the same answer what it would be without built-ins, so that you have to know how to do it.

# Answer
> 2 votes
# Jelly, ~~16~~ ~~13~~ 12 bytes

```
:;ç%@¥@⁶Ṗ¤%?

```

Try it online!

# Answer
> 4 votes
## Ruby, ~~45~~ ~~43~~ 46 bytes

```
f=->n{x,y=n.to_r.divmod 1;[x,*y==0?[]:f[1/y]]}

```

Accepts input as a string.

All test cases pass:

```
llama@llama:~$ for n in 860438 3.245 -4.2 -114.7802 0/11 1/42 2/7 -18/17056 -17056/18; do ruby -e 'f=->n{x,y=n.to_r.divmod 1;[x,*y==0?[]:f[1/y]]}; p f["'$n'"]'; done
[860438]
[3, 4, 12, 4]
[-5, 1, 4]
[-115, 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]
[0]
[0, 42]
[0, 3, 2]
[-1, 1, 946, 1, 1, 4]
[-948, 2, 4]

```

Thanks to Kevin Lau for 2 bytes!

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

I noticed @Doorknob♦ beat me to a Ruby answer right before posting, and theirs is also shorter! As such this is just here for posterity now. Takes in a string or an integer (floats have rounding issues, so decimal values need to be put in as strings)

```
f=->s{s=s.to_r;[s.floor]+(s%1!=0?f[1/(s%1)]:[])}

```

# Answer
> 3 votes
# Nekomata, 7 bytes

```
ᶦ{1%ŗ}k

```

Attempt This Online!

A port of @Parcly Taxel's Mathematica answer.

```
ᶦ{1%ŗ}k
ᶦ{   }        Iterate the following function until it fails
  1%            Modulo 1
    ŗ           Reciprocal
      k       Floor

```

# Answer
> 2 votes
## JavaScript (ES6), 52 bytes

```
f=(n,d)=>n%d?[r=Math.floor(n/d),...f(d,n-r*d)]:[n/d]

```

Accepts numerator and denominator and returns an array, e.g. `f(-1147802, 1e4)` returns `[-115, 4, 1, 1, 4, 1, 1, 5, 1, 1, 4]`.

# Answer
> 2 votes
# MATL, 29 bytes

```
`t1e7*Yo5M/kwy-t1e-5>?-1^T}xF

```

**Try it online!**

This works by repeatedly rounding and inverting (which I think is what Doorknob's answer does too). There may be numerical issues due to using floating point, but it works for all the test cases.

```
`         % Do...while
  t       %   Duplicate. Takes input implicitly the first time
  1e7*    %   Multiply by 1e7
  Yo      %   Round
  5M/     %   Divide by 1e7. This rounds to the 7th decimal, to try to avoid
          %   numerical precision errors
  k       %   Round
  w       %   Swap top two elements of stack
  y       %   Copy the secomnd-from-bottom element
  -       %   Subtract
  t       %   Duplicate
  1e-5>   %   Is it greater than 1e-5? (1e-5 rather than 0; this is again to
          %   try to avoid numerical precision errors)
  ?       %   If so
    -1^   %     Compute inverse
    T     %     Push true as loop condition (to start a new iteration)
  }       %   Else
    xF    %     Delete and push false (to exit loop)
          %   End if implicitly
          % End do...while implicitly
          % Display implicitly

```

# Answer
> 2 votes
# Java, ~~85~~ 83 bytes

```
String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));}

```

### Takes integer or fraction or decimal as String, 311 bytes

```
String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));String[]a=i.split("/");int n=Integer.decode(a[0]),d=Integer.decode(a[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}}

```

### Sample input/output:

```
860438
860438

3.245
3,4,12,4

-4.2
-5,1,4

-114.7802
-115,4,1,1,4,1,1,5,1,1,4

0/11
0

1/42
0,42

2/7
0,3,2

-18/17056
-1,1,946,1,1,4

-17056/18
-948,2,4

```

### Actual input/output from full program:

```
860438
860438
860438
860438
860438
3.245
3,4,12,4
3,4,12,4
3,4,12,4
3,4,12,4
-4.2
-5,1,4
-5,1,4
-5,1,4
-5,1,4
-114.7802
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
-115,4,1,1,4,1,1,5,1,1,4
0/11
0
0
0
0
1/42
0,42
0,42
0,42
0,42
2/7
0,3,2
0,3,2
0,3,2
0,3,2
-18/17056
-1,1,946,1,1,4
-1,1,946,1,1,4
-1,1,946,1,1,4
-1,1,946,1,1,4
-17056/18
-948,2,4
-948,2,4
-948,2,4
-948,2,4

```

### Full program (including ungolfed functions):

```
import java.util.Scanner;

public class Q79483 {
    String cf_ungolfed(String input){
        try{
            int result = Integer.parseInt(input);
            return Integer.toString(result);
        }catch(Exception e){
            if(input.indexOf('.')>=0){
                int numerator = Integer.parseInt(input.replaceAll("\\.",""));
                int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1);
                return cf_ungolfed(numerator+"/"+denominator);
            }
            int numerator = Integer.parseInt(input.substring(0,input.indexOf('/')));
            int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1));
            if(numerator%denominator == 0){
                return Integer.toString(numerator/denominator);
            }
            if(numerator < 0){
                return "-"+cf_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator)))+"/"+denominator);
            }
            return (numerator/denominator) + "," + cf_ungolfed(denominator+"/"+(numerator%denominator));
        }
    }
    String c(String i){try{return""+Integer.decode(i);}catch(Exception e){int o=i.indexOf(46);if(o>=0)return c((i+"/"+Math.pow(10,i.length()-o-2)).replaceAll("\\.",""));int n=Integer.decode(i.split("/")[0]),d=Integer.decode(i.split("/")[1]);return n<0?"-"+c(2*(d+n%d)-n+"/"+d):n%d<1?""+n/d:n/d+","+c(d+"/"+(n%d));}}
    String f_ungolfed(int numerator,int denominator){
        if(numerator%denominator == 0){
            return Integer.toString(numerator/denominator);
        }
        if(numerator < 0){
            return "-"+f_ungolfed((denominator-numerator+(denominator+2*(numerator%denominator))),denominator);
        }
        return (numerator/denominator) + "," + f_ungolfed(denominator,(numerator%denominator));
    }
    String f(int n,int d){return n<0?"-"+f(2*(d+n%d)-n,d):n/d+(n%d<1?"":","+f(d,n%d));}
    public static int[] format(String input){
        if(input.indexOf('.') != -1){
            int numerator = Integer.parseInt(input.replaceAll("\\.",""));
            int denominator = (int) Math.pow(10, input.length()-input.indexOf('.')-1);
            return new int[]{numerator,denominator};
        }
        if(input.indexOf('/') != -1){
            int numerator = Integer.parseInt(input.substring(0,input.indexOf('/')));
            int denominator = Integer.parseInt(input.substring(input.indexOf('/')+1));
            return new int[]{numerator,denominator};
        }
        return new int[]{Integer.parseInt(input),1};
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String input = sc.next();
            System.out.println(new Q79483().cf_ungolfed(input));
            System.out.println(new Q79483().c(input));
            int[] formatted = format(input);
            System.out.println(new Q79483().f_ungolfed(formatted[0], formatted[1]));
            System.out.println(new Q79483().f(formatted[0], formatted[1]));
        }
        sc.close();
    }
}

```

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

*-4 from alephalpha*

```
Floor@NestWhileList[1/t&,#,(t=#~Mod~1)>0&]&

```

Try it online!

# Answer
> 1 votes
# Pyth, 15 bytes

```
M+]/GH?J%GHgHJY

```

Try it online! (The `g.*` at the end is to fetch the input.)

# Answer
> 1 votes
# APL(NARS), 107 chars, 214 bytes

```
dd←{⍵=0:0⋄0>k←1∧÷⍵:-k⋄k}⋄nn←{1∧⍵}⋄f←{⍵=0:0x⋄m←⎕ct⋄⎕ct←0⋄z←{0=(d←dd⍵)∣n←nn⍵:n÷d⋄r←⌊n÷d⋄r,∇d÷n-r×d}⍵⋄⎕ct←m⋄z}

```

The function of the exercise f, should have as input one rational number (where 23r33 means as "23/33" in math) ...The algo is the same of the one Neil posted as JavaScript solution... test

```
  f 860438r1
860438
  f 3245r1000
3 4 12 4
  f ¯42r10
¯5 1 4
  f ¯1147802r10000
¯115 4 1 1 4 1 1 5 1 1 4
  f 0r11
0
  f 1r42
0 42
  f 2r7
0 3 2
  f ¯18r17056
¯1 1 946 1 1 4
  f ¯17056r18
¯948 2 4
  f 17056r¯18
¯948 2 4
  f 18r¯17056
¯1 1 946 1 1 4
  f 123r73333333333333333333333333373
0 596205962059620596205962059 1 16 1 1 3
  +∘÷/f 123r73333333333333333333333333373
123r73333333333333333333333333373

```

# Answer
> 1 votes
# Python 3, 46 bytes

```
f=lambda n,d:[n//d]+(n%d*[0]and f(d,n-n//d*d))

```

Try it online!

Port of Neil's javascript answer

# Answer
> 0 votes
# Scala, 72 bytes

Golfed version. Try it online!

```
(n,d)=>if(n<0)"-"+f(2*(d+n%d)-n,d)else n/d+(if(n%d<1)""else","+f(d,n%d))

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 222 bytes/75 bytes

## A function that takes a string, 222 bytes

```
(a,o)=>{var@b=$"{a}/1".Split("/");var@c=$"{b[0]}.0".Split(".");int@n=int.Parse(c[0]),m=int.Parse(c[1]),d=1,r;for(;d<m;d*=10);for(n=n*d+(n>0?1:-1)*m,d*=int.Parse(b[1]);d>0;(n,d)=(d,n-r*d))o.Add(r=(int)Math.Floor(1m*n/d));};

```

Try it online!

## Just the part that takes numerator and denominator, 75 bytes

```
(n,d,o)=>{for(int@r;d>0;(n,d)=(d,n-r*d))o.Add(r=(int)Math.Floor(1m*n/d));};

```

Try it online!

## Un-golfed code:

```
(input, output) =>
{
	var fracStr = $"{input}/1".Split("/"); // append "/1" so we never get an array out of bounds
	var decStr = $"{fracStr[0]}.0".Split("."); // append ".0" so we never get an array out of bounds

	// parse the decimal number first,
	// if we weren't passed a decimal, m will be 0
	int n = int.Parse(decStr[0]);
	int m = int.Parse(decStr[1]);
	int d = 1;

	// denominator will be the next power of 10 larger than m:
	for (; d < m; d *= 10);

	// scale the numerator by the denominator, and add the decimal part:
	n = n * d + (n > 0 ? 1 : -1) * m;

	// now handle the fraction case
	// if we weren't passed a fraction then fracStr[1] will be "1"
	// if we were passed a fraction, d will be 1
	d *= int.Parse(fracStr[1]);

	// now actually calculate the continued fraction:
	for (; d > 0; )
	{
		int r = (int)Math.Floor(1m * n / d);
		output.Add(r);
		(n, d) = (d, n - r * d);
	}
};

```

---
Tags: code-golf, math, rational-numbers
---


title: Find the needle in the haystack

text:
# Question
Title: Find the needle in the haystack
Given a rectangular haystack of size at least 2x2 composed of all the same printable ASCII characters, output the location (counting from the top-left) of the needle which is a different character.

For example, if the following haystack is input:

```
#####
###N#
#####
#####

```

The output should be `3,1` when zero-indexed (what I'll be using in this challenge) or `4,2` when one-indexed.

The haystack can be composed of any printable ASCII character:

```
^^^
^^^
^N^
^^^
^^^
^^^

```

output: `1,2`

and the needle will be any *other* printable ASCII character:

```
jjjjjj
j@jjjj
jjjjjj

```

output `1,1`

It's also possible to have a needle in the corner:

```
Z8
88

```

output `0,0`

```
88
8Z

```

output `1,1`

or to have the needle at the edge:

```
>>>>>>>>>>
>>>>>>>>>:
>>>>>>>>>>

```

output `9,1`

### Rules and Clarifications

* Input and output can be given by any convenient method. This means you can take input as a list of list of characters, as a single string, etc.
* You can print the result to STDOUT or return it as a function result. Please state in your submission what order the output is in (i.e., horizontal then vertical, as used in the challenge, or vice versa).
* Either a full program or a function are acceptable.
* You do *not* get to pick which characters to use. That's the challenge.
* The haystack is guaranteed to be at least 2x2 in size, so it's unambiguous which is the needle and which is the hay.
* There is only ever one needle in the input, and it's only ever one character in size.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# , ~~49~~ ~~47~~ 44 bytes

```
function(m,`?`=which)m==names(?table(m)<2)?T

```

Try it online!

Takes input as a matrix, returns 1-indexed coordinates
> 21 votes

# Answer
# Perl 6, ~~41 38~~ 37 bytes

*3 bytes saved thanks to @nwellnhof.*

*1 byte saved thanks to Jo King.*

```
{map {[+] ^∞Z*!<<.&[Z~~]},$_,.&[Z]}

```

Try it online!

## Explanation

It takes the input as a list of lists of characters and returns list of length 2 containing zero-based X and Y coordinates of the needle.

It works by applying the block `{[+] ^∞ Z* !<<.&[Z~~]}` on the input and on its transpose. `.&[Z~~]` goes through all columns of the argument and returns `True` if all the elements are the same, `False` otherwise. We then negate all the values (so we have a list with one bool per column, where the bool answers the question "Is the needle in that column?"), multiply them element-wise with a sequence 0,1,2,... (`True = 1` and `False = 0`) and sum the list, so the result of the whole block is the 0-based number of the column where the needle was found.

# Nwellnhof's better approach, Perl 6, 34 bytes

```
{map *.first(:k,*.Set>1),.&[Z],$_}

```

Try it online!

## Explanation

Generally the same approach, just more effective. It still uses a block on the array and its transpose, but now the block converts all *rows* into`Sets` and checks for the number of elements. The `first` function then gives index (due to the `:k`) of the first row that contained more than 1 element. Because of that, the order of `$_` and `.&[Z]` needed to be swapped.
> 9 votes

# Answer
# Python 2, 57 bytes

```
lambda m:[map(len,map(set,a)).index(2)for a in zip(*m),m]

```

**Try it online!**

---

A port of this to **Python 3** can be **62 bytes**:

```
lambda m:[[len(set(v))for v in a].index(2)for a in(zip(*m),m)]

```

The list comprehension, `[len(set(v))for v in a]`, is shorter than the double map by two bytes now as it would need to be cast to a list like `list(map(len,map(set,a)))`

Try it online!
> 9 votes

# Answer
# Brachylog, 20 bytes

```
c≡ᵍ∋Ȯ&;I∋₎;J∋₎gȮ∧I;J

```

Try it online!

Outputs `[I,J]`, where `I` is the row index and `J` the column index, both 0-indexed.

Stupidely long, but getting indexes in Brachylog is usually very verbose.

### Explanation

```
c                       Concatenate the Input into a single string
 ≡ᵍ                     Group identical characters together
   ∋Ȯ                   Ȯ is a list of One element, which is the needle character
     &;I∋₎              Take the Ith row of the Input
          ;J∋₎          Take the Jth character of the Ith row
              gȮ        That character, when wrapped in a list, is Ȯ
                ∧I;J    The output is the list [I,J]

```
> 6 votes

# Answer
# PHP, ~~99~~ 85 bytes

Using string without newlines and the width (or height) `('########N###########', 5`) as input.

* -5 bytes by removing chr() call, props to @Titus
* -9 bytes by taking input as two function args, also props to @Titus

```
function($a,$l){return[($p=strpos($a,array_flip(count_chars($a,1))[1]))%$l,$p/$l|0];}

```

Try it online!

Ungolfed:

```
function need_hay( $a, $l ) {

    // identify the "needle" by counting the chars and
    // looking for the char with exactly 1 occurrence
    // note: this is 1 byte shorter than using array_search()
    $n = array_flip( count_chars( $a, 1 ) )[1];

    // find the location in the input string
    $p = strpos( $a, $n );

    // row is location divided by row length, rounded down
    $r = floor( $p / $l );

    // column is remainder of location divided by row length
    $c = $p % $l;

    return array( $c, $r );

}

```

Output:

```
#####
###N#
#####
#####
[3,1]

^^^
^^^
^N^
^^^
^^^
^^^
[1,2]

jjjjjj
j@jjjj
jjjjjj
[1,1]

```
> 6 votes

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

Saved 3 bytes switching input format.

Input is taken as a string and a row-length.
Output is a zero-based list of the form `[y, x]`

```
D.mks‰

```

Try it online! or as a Test Suite

**Explanation**

```
D           # duplicate the input string
 .m         # get the least frequent character
   k        # get its index in the string
    s       # swap the row length to the top of the stack
     ‰      # divmod the index of the least frequent char with the row length

```
> 5 votes

# Answer
# Python 3 \+ NumPy, ~~75~~ 66 bytes

-9 bytes thanks to @ASCII-only

```
lambda x:where(x.view('i')-median(x.view('i')))
from numpy import*

```

Try it online!

This assumes that the input is a NumPy array. The output is zero-indexed, and first vertical, then horizontal.

It converts the input from `char` to `int` then calculates the median of the array, which will be the haystack character. We subtract that from the array, which makes the needle the only non-zero element. Finally, return the index of that element with `numpy.where()`.
> 5 votes

# Answer
# JavaScript (ES6), 55 bytes

Takes input as \\$(s)(w)\\$, where \\$s\\$ is a string and \\$w\\$ is the width of the matrix. Returns \\$\[x,y\]\\$.

```
s=>w=>[(i=s.indexOf(/(.)\1+(.)/.exec(s+s)[2]))%w,i/w|0]

```

Try it online!

---

# JavaScript (ES6),  ~~65~~  64 bytes

*Saved 1 byte thanks to @Neil*

Takes input as a matrix of characters. Returns \\$\[x,y\]\\$.

```
m=>m.some((r,y)=>r.some((c,x)=>!m[p=[x,y],~y&1].includes(c)))&&p

```

Try it online!

### How?

We look for the first character \\$c\\$ located at \\$(x,y)\\$ which does not appear anywhere in another row \\$r\[Y\]\\$. We can perform this test on any row, as long as \\$Y\ne y\\$. Because the input matrix is guaranteed to be at least \\$2\times 2\\$, we can simply use \\$Y=0\\$ if \\$y\\$ is odd or \\$Y=1\\$ if \\$y\\$ is even.
> 4 votes

# Answer
# Java 8, ~~132~~ 111 bytes

```
m->{int c=m[0][0],i=0,j;for(c=m[1][0]!=c?m[1][1]:c;;i++)for(j=m[i].length;j-->0;)if(m[i][j]!=c)return i+","+j;}

```

-8 bytes (and -13 more implicitly) thanks to *@dana*.

Input as character-matrix.

Try it online.

**Explanation:**

```
m->{                    // Method with char-matrix parameter and String return-type
  int c=m[0][0],        //  Character to check, starting at the one at position 0,0
      i=0,j;            //  Index integers
  for(c=m[1][0]!=c?     //  If the second character does not equal the first:
         m[1][1]        //   Use the character at position 1,1 instead
        :c;             //  Else: keep the character the same
      ;i++)             //  Loop `i` from 0 indefinitely upwards:
    for(j=m[i].length;j-->0;)
                        //   Inner loop `j` in the range (amount_of_columns, 0]:
      if(m[i][j]!=c)    //    If the `i,j`'th character doesn't equal our character to check:
        return i+","+j;}//     Return `i,j` as result

```
> 4 votes

# Answer
# Jelly, 5 bytes

Outputs **\[height, width\]** (1-indexed).

```
ŒĠLÐṂ

```

Try it online!

```
ŒĠLÐṂ – Monadic link / Full program. Takes a list of strings M as input.
ŒĠ    – Group the multidimensional indices by their values (treating M as a matrix).
  LÐṂ – And retrieve the shortest group of indices (those of the unique character).

```

---

### Jelly, 5 bytes

```
ŒĠḊÐḟ

```

Try it online!
> 4 votes

# Answer
# Jelly, 4 bytes

Maybe this could've just been a comment for Mr. Xcoder it is pretty similar...

```
ŒĠEƇ

```

A monadic link accepting the matrix of characters which yields a list of one item, the 1-indexed (row, column) co-ordinate from top-left.
(...As a full program given an argument formatted such that parsing results in a list of lists of characters -- that is a list of strings in Python format -- the single coordinate is printed.)

**Try it online!**

### How?

```
ŒĠEƇ - Link: matrix, M
ŒĠ   - multi-dimensional indices grouped by Value
     -  ...due to the 2*2 minimum size and one needle this will be a list of two lists one
     -     of which will have length one (the needle coordinates as a pair) and the other
     -     containing all other coordinates as pairs
   Ƈ - filter keeping those for which this is truthy:
  E  -   all equal?
     -   ... 1 for the list of length 1, 0 for the list of at least 3 non-equal coordinates

```
> 4 votes

# Answer
# Wolfram Language ~~37~~ 58 bytes

My earlier entry did not correctly handle the case where the "odd character out" was at the upper left corner of the matrix. This does.

```
#~Position~Keys[TakeSmallest[Counts@Flatten@#,1]][[1]]&

```

---

`Counts@Flatten@#` lists how many of each character are in the array, `#`.

`TakeSmallest[...,1]` returns the least frequent count, in the form of an association rule such as `<| "Z"->1|>`

`Keys...[[1]]` returns the "key" to the only item in the association, that of the least used character. ("Z" in the present case)

`#~Position~...` returns then position of the key in the original matrix, `#`.
> 3 votes

# Answer
# MATL, ~~12~~ 8 bytes

```
tX:XM-&f

```

Try it online!

Using the `mode` function as the majority-detector. Returns 1-based indices.

```
 t           % duplicate the input
  X:         % turn the copy into a linear array
    XM       % find the arithmetic mode of that (the 'haystack' character)
      -      % Subtract that from the original input
       &f    % find the position of the non-zero value in that result

```

*-4 characters thanks to @LuisMendo*
> 3 votes

# Answer
# Perl 5 `-p00`, ~~52~~ 45 bytes

```
/^(.)(\1*
)*(\1*)|^/;$_=$&=~y/
//.$".length$3

```

45 bytes

52 bytes

How

* `-p00` : like `-n` but also print, paragraph mode
* `/^(.)(\1*
)*(\1*)|^/` : matches either
    + from start `$1`: first character, `$2`: repetition (not used), `$3`: characters before the "needle" in the line, `$&` whole match
    + or null string (position 0) no capture.
* `$_=` : to assign the default input/argument variable
* so `$&=~y/
//` the number of newlines of `$&`
* `.$".` : concatenate with `$"` (space character by default) and concatenate
* `length$3` : the length of `$3`
> 3 votes

# Answer
# 42 bytes

```
function(m)which(ave(m,m,FUN=length)==1,T)

```

Try it online!

**Input:** a haystack matrix `m`

**Output:** `(row,col)` vector - index starting at `1`
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~109~~ ~~108~~ 107 bytes

First() =\> Last() for -1 byte

currying for -1 byte thanks to Embodiment of Ignorance

```
a=>w=>{var d=a.Where(b=>b!=a[0]).Select(b=>a.IndexOf(b));return d.Count()>1?(0,0):(d.Last()%w,d.Last()/w);}

```

Try it online!
> 2 votes

# Answer
# , 22 bytes

```
$#:(i.~.{~1 i.~#/.~)@,

```

Try it online!

NB. returns answer in (row, column) format.
> 2 votes

# Answer
# Python 2, ~~53~~ 47 bytes

```
lambda s,w:divmod(s.find(min(s,key=s.count)),w)

```

Try it online!

Call as `f("########N###########", 5)` (allowed in a comment). Outputs `(y, x)`.

Erik saved 6 bytes, suggesting rearranging the output + using `divmod`. Thanks!
> 2 votes

# Answer
# PowerShell, ~~107~~ ~~98~~ ~~82~~ 77 bytes

```
$l=@{}
$args|%{if($_-10){$l.$_+=$x++,+$y}else{$x=0;++$y}}
$l|% v*|? c*t -eq 2

```

Try it online!

Takes a splatted string with LFs. Returns zero-indexed location x,y. Unrolled:

```
$locations=@{}                      # make a hashtable. key=char, value=location array
$args|%{
    if($_-10){                      # if current char is not LF
        $locations.$_+=$x++,+$y     # add $x,$y to hashtable value and move $x to next pos
    }else{
        $x=0;++$y                   # move $x,$y to next line
    }
}
$locations|% Values|? Count -eq 2   # find and output location array with 2 elements (x,y)

```
> 2 votes

# Answer
# Scala, 98 bytes

Golfed version. Try it online!

```
def f(m:Seq[String])=m.transpose.map(_.toSet.size).indexOf(2)::m.map(_.toSet.size).indexOf(2)::Nil

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val tests = Seq(
      """#####
        |###N#
        |#####
        |#####""".stripMargin,
      """^^^
        |^^^
        |^N^
        |^^^
        |^^^
        |^^^""".stripMargin,
      """jjjjjj
        |j@jjjj
        |jjjjjj""".stripMargin,
      """Z8
        |88""".stripMargin,
      """88
        |8Z""".stripMargin
    )

    val f: Seq[String] => Seq[Int] = m => m.transpose.map(_.toSet.size).indexOf(2) :: m.map(_.toSet.size).indexOf(2) :: Nil

    tests.foreach { test =>
      val v = test.split("\n")
      v.foreach(println)
      println("   -> " + f(v) + "\n")
    }
  }
}

```
> 2 votes

# Answer
# Julia, 78 bytes

```
s->(n=argmin(x->count(x,'
's),s);q=split(s);~=findlast;b=~(n.∈q);(n~q[b],b))

```

Attempt This Online!

This function takes input as a single string, which probably isn't the most efficient approach. The output is 1-indexed.

-19 bytes thanks to MarcMush: add a newline to the haystack to guarantee that the needle is always the least frequent character, even in a 2x2 haystack.

Interestingly, concatenating a character literal with a string variable doesn't require an operator in Julia. Apparently, it's parsed just like numeric literal coefficients with variables. This saves a byte here, which is the best thing to come out of Julia's choice of concatenation operator.
> 2 votes

# Answer
# Lua, 103 91 bytes

```
s,l=...s:gsub('.',load'c=...b=b or not s:find(c..c,1,1)and s:find(c,1,1)')print(b%l-1,b//l)

```

Try it online!

Ungolfed version:

```
s,l=...                                           --Take in haystack and line width as args
s:gsub('.',function (d)                           --For each character in s
    b=b or not s:find(c..c,1,1)and s:find(c,1,1)  --If there is only one instance of c, store location
end)
print(b%l-1,b//l)                                 --Print results

```
> 2 votes

# Answer
# Stax, 15 bytes

this can probably be golfed down a bit as there's a lot of register shenanigans i'm not a huge fan of. takes an array of a single string with a width

```
Ç║æ░·╝;J╕╤¢ⁿÿì<

```

Try it online! (With test cases)

This is Packed Stax, which unpacks to the following:

# Stax, 17 bytes

```
Nc|!IYxhX%yx/2l|u

```

Run and debug it

```
N                 # get the string
 c|!              # get the rarest element
    I             # get the first index in the string of this
     Y            # store that in register Y
      xh          # get the width
        X         # and store this value in register x
         %        # modulo with what was stored in register Y
          yx      # register y and register x from above
            /     # divide them
             2l   # create an array of the top two elements on the stack
               |u # and put it in a format which can be printed

```
> 2 votes

# Answer
# Python 3, 93 bytes

```
def f(s):x=s.find("\n")+1;return[(i%x,i//x)for i,c in enumerate(s)if s.count(c)<2and" "<c][0]

```

Try it online!

Input is taken as a multiline string. Output is 0-indexed
> 1 votes

# Answer
# Octave, 40 bytes

```
@(x){[r,c]=find(x-mode(+x(:))) [c,r]}{2}

```

Port of @sundar's MATL answer. Output is a two-element vector with 1-based column and row indices.

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 41 bytes

```
s`(?=(.)+\1)(.*?¶)*(.*)(?!\1|¶).+
$.3,$#2

```

Try it online! 0-indexed. Explanation:

```
s`

```

Allow `.` to match newlines. This costs 3 bytes (3rd byte is the `?` before the ) but saves 6 bytes.

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

```

Look ahead for two identical characters. `\1` then becomes the hay.

```
(.*?¶)*

```

Count the number of newlines before the needle.

```
(.*)

```

Capture the hay to the left of the needle.

```
(?!\1|¶)

```

Ensure that the needle isn't hay or a newline.

```
.+

```

Match the rest of the hay so that the result replaces it.

```
$.3,$#2

```

Output the width of the left hay and the number of newlines.
> 1 votes

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

```
x=>w=>{int y=x.IndexOf(x.GroupBy(c=>c).Last(g=>g.Count()<2).Key);return(y%w,y/w);}

```

Thanks to dana for shaving off 6 bytes!

Try it online!

# Old solution, 106 bytes

```
n=>m=>{var z=n.Distinct();int d=n.IndexOf(n.Count(c=>c==z.First())>1?z.Last():z.First());return(d%m,d/m);}

```

Both take input as a string and an integer specifying the amount of columns.

Try it online!
> 1 votes

# Answer
# C (clang), 74 bytes

```
h(char*s,z,x){for(s+=z--;*s==*--s|*s==s[-1];)z--;printf("%d,%d",z%x,z/x);}

```

Try it online!

DEGOLF

```
int h(char*s,int z,int x){// z = string size, x = row size

 for(s+=z--;
 // move pointer just over the end of the string
 // and move z counter to the end of string

*s-*--s?   ==>  *s==*--s|  @ceilingcat suggestion
 // if the previous element is different we will check if the next element is also different
 // if not the result is 1 and the iteration continue
 // in the first iteration it will be different because the pointer is just  over the end

 *s-s[-1]? ==> changed to *s==s[-1]   @ceilingcat suggestion
 // the second check returns 0 if the char changed again so it was the needle
 // if not it's because in the first iteration the first check finded a difference just because the pointer was just over the end

 /*0:1*/   :1;)z--;

 printf("%d,%d",z%x,z/x);
}

```
> 1 votes

# Answer
# Python 3, ~~93~~ ~~89~~ ~~85~~  58 bytes

Complete rewrite taking input as `concatenated string, width`:

```
lambda g,w:divmod(g.index({g.count(c):c for c in g}[1]),w)

```

Try it online!

---

Original answer:

```
def k(g):t=''.join(g);return divmod(t.index({t.count(c):c for c in t}[1]),len(g[0]))

```

EDIT: Saved 4 bytes by swapping linebreak/indent for semicolons. Saved another 4 bytes by using `divmod`(thanks @JonathanFrech).

Try it online!

I know this could be a lot shorter, but I just wanted to try an approach around this `dict` comprehension.
> 1 votes

# Answer
Java 8, 104 Bytes

```
(x,w)->{int i=0,p=x.length;for(;i<p;i++)if(x[i]!=x[(i+1)%p]&&x[i]!=x[(i+2)%p])break;return i/w+","+i%w;}

```

Input is array of char, and integer indicating row width.

Output is zero-based, vertical then horizontal (i.e., row number then column number)

Explanation:

```
(x,w)->{
    int i=0, p=x.length;
    for (;i<p;i++)          //iterate through characters in x
      if (x[i]!=x[(i+1)%p] && x[i]!=x[(i+2)%p])    //compare x[i] with the two subsequent characters in array, wrapping around if necessary
        break;
    return i/w+","+i%w;}  //return row number then column number, zero-based

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 9 bytesSBCS

Anonymous tacit prefix function. In a sense, this is actually a kind of poly-glot, as it takes as argument either a character matrix or a list of strings, with the code meaning something else in each case. Always returns `[row,column]` in which ever index origin is currently active. (APL lets you choose.)

```
⍸↑=∊~∘∊∩/

```

Try it online!

**If the argument is a matrix, the function works like this:**

`∩/` intersection reduction of each row. Since there will be at least one all-hay row, this gives us at least one hay character. And since every row has at least one hay character, the intersection will always empty out the row that has the needle character.

**ϵ**nlist (flatten) this, giving us one or more hay characters

then…

`~` remove all such characters from…

the **ϵ**nlisted (flattened) argument, leaving just the needle

`↑=` Boolean matrix indicating where the matrix equals the needle

the indices where true

**If the argument is a list of strings, the function works like this:**

`∩/` intersection reduction of the strings. Since only one string will have a needle, and all strings have hay, this will give us one or more hay characters without the needle character.

**ϵ**nlist (flatten) this, giving us the one or more hay characters

then…

`~` remove all such characters from…

the **ϵ**nlisted (flattened) argument, leaving just the needle

`↑=` Boolean matrix indicating where the matrix constructed by merging the strings equals the needle

the indices where true
> 1 votes

# Answer
# Ruby, 43 bytes

Takes the haystack as a single line and its width as arguments. Returns the 0-based row, then column as an array.

```
->s,w{(/[^#{s[/(.)(?=\1)/]}]/=~s).divmod w}

```

Attempt This Online!
> 1 votes

# Answer
# Arturo, 49 bytes

```
$[s w]->/%index s first select tally s[k v][1=v]w

```

Try it

Takes input as a single line and a width. Returns a 0-indexed `[row col]` pair.
> 1 votes

# Answer
# Vyxal, 5 bytes

```
ƒ⊍hÞḟ

```

Try it Online!

Takes a list of lines. Outputs 0-indexed `[row, column]`. Vyncode does nothing here apparently, it decided.

## Explained

```
ƒ⊍hÞḟ
ƒ⊍    # reduce by set xor
  h   # get the first of that
   Þḟ # find it's multidimensional index

```
> 1 votes

# Answer
# C# .NET, ~~133~~ ~~112~~ 111 bytes

```
m=>{var c=m[0][0];c=m[1][0]!=c?m[1][1]:c;for(int i=0,j;;i++)for(j=m[i].Count;j-->0;)if(m[i][j]!=c)return(i,j);}

```

-1 byte thanks to *@EmbodimentOfIgnorance*.

Port of my Java answer, but with a `List<List<char>>` input and `int`-tuple output, instead of `char[][]` input and `string` output.

Try it online.
> 0 votes

# Answer
# MATLAB, ~~68~~ 22 bytes

~~`[r,c]=find(v~=v(1));if size(r,1)>1 disp([1,1]);else disp([r,c]);end;`~~

~~If I could exclude any one case, such as `[1,1]` in this solution, I could have saved several bytes.~~

**Updated solution**:

```
@(v)find(v-mode(v(:)))

```

Thanks to @sundar for helping me with the special case problem and saving 42 bytes! Also, thanks to @Luis\_Mendo for the suggestions and saving me another 2 bytes!
> 0 votes

# Answer
# MATL, 11 bytes

```
tX:YmyYk-&f

```

Output is row, then column; 1-based.

Try it online!

### Explanation

```
t    % Implicit input. Duplicate
X:   % Linearize into a column
Ym   % Compute mean (characters are converted to ASCII codes)
y    % Duplicate from below: pushes input again
Yk   % Closest value: gives the input value that is closest to the mean
-    % Subtract, element-wise. Gives non-zero for the value farthest from the mean
&f   % Two-output find: gives row and column indices of nonzeros. Implicit display

```
> 0 votes

# Answer
# Pyth, ~~15~~ ~~14~~ 12 bytes

```
.Dxz-zh.-z{z

```

Takes input as the length of the row and the input without lines and outputs as \[row, column\].
Try it here

### Explanation

```
.Dxz-zh.-z{z
       .-z{z    Subtract one of each character from the input.
      h         Take the first.
    -z          Remove all instances from the input.
  xz            Find the remaining character in the input.
.D          Q   Take the result divmod the (implicit) length of the row.

```

## Old approach

```
mxJmt{kdeSJ.TB

```

Try it here

### Explanation

```
mxJmt{kdeSJ.TB
           .TBQ   Take the (implicit) input and its transpose...
m      d          ... and for each...
   mt{k           ... deduplicate each row...
 xJ     eSJ       ... and find the index of the largest.

```
> 0 votes

# Answer
# Charcoal, 40 bytes

```
≔§⎇⌕θ§θ¹ηθ⁰ζＳθＷ⁼№θζＬθ«⊞υωＳθ»Ｉ⌕Ｅθ⁼ιζ⁰,ＩＬυ

```

Try it online! Link is to verbose version of code. I must be doing something wrong because this is almost as long as the Retina answer. Explanation:

```
≔§⎇⌕θ§θ¹ηθ⁰ζ

```

Check whether the second character in the first string is also the first character, and take the first character of the first string if so otherwise the first character of the second string if not. This is then the hay.

```
ＳθＷ⁼№θζＬθ«⊞υωＳθ»

```

Keep reading strings until a string whose hay is less than its length is found.

```
Ｉ⌕Ｅθ⁼ιζ⁰,ＩＬυ

```

Output the position of the mismatching element and then the number of strings previously read.
> 0 votes

# Answer
# Röda, 81 bytes

```
f a{i=indexOf;l=i("
",a)+1;chars a|sort|count|[[_2,_1]]|min|i _[1],a|[_%l,_1//l]}

```

Try it online!

Takes input as a string containing newline-terminated lines. Returns a stream containing 0-indexed horizontal and vertical indexes.
> 0 votes

# Answer
# Perl 5 `-n0`, 77 bytes

```
$t=(@b=sort/./g)[0]eq$b[1]?pop@b:$b[0];++$y&/\Q$t/g&&say"$y,",pos for /.+$/mg

```

Try it online!

Output is `row,column` starting from the top left, 1-indexed
> 0 votes

# Answer
# Haskell, 64 bytes

```
f s=[(r,c)|c<-[0..],r<-[0..length s-1],any(notElem$s!!r!!c)s]!!0

```

Try it online! `f` takes a list of lines and returns zero-indexed `(row,column)`.

Works by iterating through the columns and rows and looking for a character which does not appear on all rows.
> 0 votes

# Answer
# APL+WIN, 39 bytes

Index origin =1. Prompts for character matrix as a string input followed by row width. Outputs row by column index position.

```
(,(⍳i÷n)∘.,⍳n←⎕)[((1=+/m∘.≡m)/⍳i←⍴m←⎕)]

```

Try it online! Courtesy of Dyalog Classic

Explanation:

```
⍳i←⍴m←⎕ Prompt for string and create a vector of indices from 1 to length string.

(1=+/m∘.≡m) Boolean vector identifying position of unique character in string.

(...)/⍳i Use Boolean to select index position of unique character.

,⍳n←⎕ Prompt for row width of character matrix and create a vector of indices.

,(⍳i÷n)∘., Create a nested vector of row by column indices of character matrix.

(...)[...] Select row by column index position of unique character.

```
> 0 votes

# Answer
# Kotlin, 142 bytes

The result is zero based \[vertical,horizontal\].

```
{d:List<String>->val h=if(d[0][0]!=d[0][1])d[1][0]
else d[0][0]
var a=""
for(r in d.indices)for(c in d[r].indices)if(h!=d[r][c])a="[$r,$c]"
a}

```

Try it online!
> 0 votes

# Answer
# Python3

Well I've never tried to do code golf before and I really can't compete with some of these really good solutions, so I've prepared a long-form answer just to demonstrate how I would solve this problem. This function takes a 2-D list of characters of any size as its input.

(edited to shorten the function up as much as I could)

```
def f(i):
    a = None
    b = 0
    c = None
    d = 0
    h = len(i)
    for y in range(h):
        for x in range(len(i[y])):
            if a == None:
                a = i[y][x]
            elif a != None:
                if i[y][x] != a:
                    c = i[y][x]
            if i[y][x] == a:
                b += 1
            elif i[y][x] == c:
                d += 1
    if b == 1:
        n = a
    elif d == 1:
        n = c
    for y in range(h):
        for x in range(len(i[y])):
            if i[y][x] == n:
                return (x, y)

```

Here is a longer version that demonstrates the example input. If you run this script it will show you the 2-D array and the needle (randomly generated every time) as well as solve it with the find\_needle() function.

```
# Code golf! Needle in a haystack challenge
# sgibber2018 (my email handle)
"""
Notes: I can't really compete with what's already been done but I'm doing
       it just to do it.
"""

import random

input_height = 10
input_width = 10
example_input = [["#" for x in range(input_width)] \
    for y in range(input_height)]
needle_spot_y = random.randrange(input_height)
needle_spot_x = random.randrange(input_width)
example_input[needle_spot_y][needle_spot_x] = "!"

for y in range(input_height):
    print(example_input[y])

# and now for the algorithm itself:
def find_needle(example_input):
    # declare two variables to count different char types
    c1 = None
    c1_count = 0
    c2 = None
    c2_count = 0
    # iterate through the whole list
    height = len(example_input)
    for y in range(height):
        for x in range(len(example_input[y])):
            # assign c1 or c2 accordingly
            if c1 == None:
                c1 = example_input[y][x]
            elif c1 != None:
                if example_input[y][x] != c1:
                    c2 = example_input[y][x]
            # count the symbols based on whether or not they match
            if example_input[y][x] == c1:
                c1_count += 1
            elif example_input[y][x] == c2:
                c2_count += 1
    # Find the value with just one increment
    if c1_count == 1:
        needle = c1
    elif c2_count == 1:
        needle = c2
    # go back through the list and find the needle and get it's pos
    for y in range(height):
        for x in range(len(example_input[y])):
            if example_input[y][x] == needle:
                return (x, y)

print(find_needle(example_input))

```

The function find\_needle() takes a 2-D list and returns the coordinates of the character that only has one count. I could probably shorten this up a little but I don't think I can compete with the existing Python3 answer which is mighty impressive. How do you calculate the size of your answers?
> 0 votes

# Answer
# C (gcc), 81 bytes

Takes input as three pointers: one to the array, and two to the dimensions. Returns by modifying the dimensions to be the coordinates of the needle.

```
i;f(char*a,int*w,int*h){for(i=0;*a==a[i];i++);i=i-1?i:*a==a[2];*h=i/ *w,*w=i%*w;}

```

Try it online!

## Degolf

```
i;f(char*a,int*w,int*h)
{
  for(i=0;*a==a[i];i++); // Count the number of elements equal to
                         // the one at (0,0)
  i=i-1?i:*a==a[2];  // Special case i==1, because it is
          // ambiguous whether the needle is at 0 or 1 there.
  *h=i/ *w,*w=i%*w; // Modify pointers to indicate coordinates.
  // the space between i/ and *w is required, as /* starts a comment
}

```
> 0 votes

# Answer
# Python 2, 63 bytes

```
lambda s,w:divmod(s.find({s.count(c):c for c in s}[1]),w)[::-1]

```

Try it online!

Expects a string with no newlines and the width of the haystack as arguments.

**Explanation:**

```
                         # get a dictionary of (number of occurrences : character)
                         {s.count(c):c for c in s}
                         # only one character will have one occurrence, so get that character
                         .........................[1]
                  # get the 0-indexed index of the needle character
                  s.find(............................)
           # flat_index / width will give us how many rows "down" the needle is (the y-value)
           # the remainder will give us how many columns "over" the needle is (the x-value)
           # so take the divmod and reverse the returned values to get (x,y)
           divmod(....................................,w)[::-1]
# anonymous function, takes haystack string with no newlines and haystack width
lambda s,w:

```
> 0 votes

# Answer
# C# (.NET Core), ~~135~~ 111 bytes

```
S=>{for(int x=0,y;;x++)try{for(y=0;;y++)if(S[x][y]!=(S[0][0]==S[0][1]?S[0][0]:S[1][0]))return y+","+x;}catch{}}

```

Try it online! (111 bytes)
Try it online! (135 bytes)

New one:

```
for (int x = 0, y; ; x++)
    try
    {
        for (y = 0; ; y++)
            if (S[x][y] != (S[0][0] == S[0][1] ? S[0][0] : S[1][0]))
                return y + "," + x;
    }
    catch { }

```

Previous one:

```
int i = 0, y;
var r = "";
for (; i < S.Length; i++)
    for (y = 0; y < S[i].Length; y++)
        r = S[i][y] != (S[0][0] == S[0][1] ? S[0][0] : S[1][0]) ? i + "," + y : r;
return r;

```
> 0 votes

# Answer
**C (VC++) Visual Studio 2017, 538bytes**

well there can be a couple of Bytes be stripped of if the haystack and needle string is Input via command line Parameters but i can not get it to work proberly then so the haystack and needle string is hard coded in the source (ugly….. ) takes 50bytes

Maybe anyone wants to improve on that

anyway the Code i came up with is

```
#include"stdafx.h"
#define r v[1][i]
#define i(x,y) if(x==y)
void main(){const char*v[]={"haystack.exe","#####\n##+##\0" };int i=0,z=0,s=0,c=r,f=c,a=-1,h=0;do{c=r;i(c,f)a++;i(a,1)h=c;if(h&&c!=h&&c!=10)break;i(c,10){z++;s=0;}}while(s++,i++,c);printf("%d,%d",s-1,z);}

```

the ungolfed variant is

```
#include "stdafx.h"

int main(/*int argc, const char * argv[]*/)
{
    const char * argv[] = {"haystack.exe","#####\n##+##\0" };
    int i = 0,row = 0, col = 0;
    char character = argv[1][i];
    char firstChar = character;
    int howMany = -1;
    char hay = '\0';
    do
    {
        char character = argv[1][i];
        if (character == firstChar)
        {
            howMany++;
        }
        if (howMany ==1)
        {
            hay = character;
        }
        if ((hay != '\0') && (character != hay)&&(character!='\n'))
        {
            break;
        }
        if (character == '\n')
        {
            row++;
            col = 0;
        }
        col++;
        i++;
    } while (character != '\0');
    printf("%d,%d", col-1, row);
    while (1);
    return 0;
}

```

i dont expect this to be explained
> 0 votes

# Answer
# Befunge-98 (PyFunge), 62 bytes

```
~:04p~-k#v>~:a-!2j6$_04g-!..@
-#v_$$1+0>  >~:a
.;>04g-#;_1+^@.

```

Try it online!

Output is: column row
> 0 votes

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


# Question
Title: Remove more than n consecutive vowels from input string
I don't like strings with more than three vowels in a row. Can you write a program that removes all the vowels I don't want from words?

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Input is a string containing only printable ASCII character (0x20 to 0x7E, inclusive).

Output is a string containing only runs of at most 3 consecutive vowels. If there is a run of more than 3 consecutive vowels in the input string, your program should produce an output string including the first three vowels encountered in that run, discarding any further consecutive vowels.

Y is not a vowel for the purposes of this challenge.

This is code golf, so the shortest code (in bytes) wins.

### Test Cases

```
"Aeiou" => "Aei"
"screeeen" => "screeen"
"We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
"Spaces break runs: aei iou." => "Spaces break runs: aei iou."

```

# Answer
# Pyth, 21 bytes

```
sfg3=Z&}rT0"aeiou"hZz

```

Try it online: Demonstration or Test Suite

### Explanation:

I iterate through all chars and keep track of how many vowels I passed using a counter. Every time I pass a char, which is not a vowel, I reset the counter to 0. I reomve chars, whenever the counter is \> 4.

```
sfg3=Z&}rT0"aeiou"hZz   implicit: z = input string
                                  Z = 0
 f                  z   test every char T in z; keep chars, that return true:
        rT0                convert T to lower
       }   "aeiou"         test if T is a vowel
      &           hZ       logical and with Z+1,
                           gives 0 if ^ is false, otherwise Z+1
    =Z                     update Z with this value
  g3                       test if 3 >= Z
s                       sum up all remaining chars and print

```
> 6 votes

# Answer
# Unreadable, 1647 bytes

> '"""""'""'""""""'"""'""""""'""'""'"""'""""""""""'"""""""""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'""""""""'"""'"""'"""'"""'"""'"""'"""'"""'"""'"""'"""'"""""""""'""'""'""'""'""""""'""'"""'""""""""'"""""""'""'"""'"'"""""""'""'""'"""'""""""'""'"""'""'"""""""'""'"""'""""'"'"""""""'""'""'"""'""""""'""'"""'""""""""'"""

# Explanation

This program is equivalent to pseudocode like this:

```
while (cp = (ch = read)) + 1 {
    (
        (cp -= 65) ?    // A
            (cp -= 4) ?     // E
                (cp -= 4) ?     // I
                    (cp -= 6) ?     // O
                        (cp -= 6) ?     // U
                            (cp -= 12) ?    // a
                                (cp -= 4) ?     // e
                                    (cp -= 4) ?     // i
                                        (cp -= 6) ?     // o
                                            (cp - 6) ?      // u
                                                0
                                            : 1
                                        : 1
                                    : 1
                                : 1
                            : 1
                        : 1
                    : 1
                : 1
            : 1
        : 1
    ) ? ((--vs)+4) ? print(ch) : (++vs) : {
        print(ch)
        vs = 0
    }
}

```

with the following variable assignments:

```
0   (unused)   (13 bytes)
1   cp         ( 4 bytes; occurs 20× in the code)
2   vs         ( 7 bytes; occurs  5× in the code)
3   ch         (10 bytes; occurs  3× in the code)

```

As you can see, I avoided variable slot 0 because `0` is such a long constant to write.

So we read each character and store the value in both `cp` and `ch`. We will modify `cp` but keep `ch` around so that we can print it if necessary. We successively subtract numbers 65, 4, 4, 6, etc. from `cp` to check if it’s each of the 10 possible vowel characters in ASCII (note the very last one doesn’t need to be an assignment).

`vs` always contains 3 less than the number of vowels still allowed to be printed. It starts out at `0`, so 3 vowels can be printed. When it reaches `-3`, we stop printing vowels.

If we encounter a *non-vowel* (including the space), we execute `print(ch)` followed by `vs = 0`. As you have probably guessed, this resets the vowels counter.

If we encounter a *vowel*, we execute `((--vs)+4) ? print(ch) : (++vs)`. Let’s break this down:

* decrement `vs`;
* if the value is now `-4`, we’ve gone too far, so don’t print anything, but increment `vs` back to `-3` so we will *continue* to refuse to print vowels;
* otherwise, print the character.
> 11 votes

# Answer
## Retina, 25 bytes

```
i`([aeiou]{3})[aeiou]+
$1

```

Try it online.

Fairly straightforward regex substitution. This also works for the same byte count:

```
Ri`(?<=[aeiou]{3})[aeiou]

```
> 10 votes

# Answer
# JavaScript (ES6), 42

As an anonymous function

```
s=>s.replace(/[aeiou]+/gi,v=>v.slice(0,3))

```
> 8 votes

# Answer
# Perl, 27 characters

(26 characters code + 1 character command line option)

```
s/[aeiou]{3}\K[aeiou]+//gi

```

Not a big deal, just a rare occasion I remember `\K` exists.

Sample run:

```
bash-4.3$ perl -pe 's/[aeiou]{3}\K[aeiou]+//gi' <<< "
> Aeiou
> screeeen
> We're queueing up for the Hawaiian movie.
> Spaces break runs: aei iou."

Aei
screeen
We're queung up for the Hawaiin movie.
Spaces break runs: aei iou.

```
> 5 votes

# Answer
## APL, 40 chars

```
{⍵/⍨1↓4≠⊃+/(1-⍳4)⌽¨⊂'aeiouAEIOU'∊⍨' ',⍵}

```

In English:

* `'aeiouAEIOU'∊⍨' ',⍵`: find the vowels (and prepend a space to break on rotation);
* `(1-⍳4)⌽¨⊂`: rotate 0, 1, 2, 3 times (with wrap-around) pushing to the right the boolean vector;
* `⊃+/ sum`: the rotations and unbox
* `1↓4≠`: find the different than 4, and remove the first one (to cather for the space we prepended)
* `⍵/⍨`: in the argument, keep only the element where the sum was different than 4.
> 3 votes

# Answer
## Mathematica, 68 bytes

```
a=Characters@"aeiouAEIOU";StringReplace[#,b:a~Repeated~{3}~~a..:>b]&

```

The regex answer would be the same length, but who uses regex?
> 2 votes

# Answer
# C, 166 bytes

not the shortest answer by far but nicely golfed I think..

```
#define V v[1][i]!=
#define P printf("%c",v[1][i]),j
j;main(i,v)char**v;{for(i=0;V 0;i++)(V 97&V 'e'&V 'i'&V 'o'&V 'u'&V 65&V 69&V 73&V 79&V 85)?P=0:j>3?j++:P++;}

```

test case:

```
$ a.exe "We're queueing up for the Hawaiian movie."

We're queung up for the Hawaiin movie.

$ wc -c vowels.c

166 vowels.c

```
> 2 votes

# Answer
# Javascript ES6, 43 chars

```
s=>s.replace(/([aeiou]{3})[aeiou]*/gi,"$1")

```

Test:

```
f=s=>s.replace(/([aeiou]{3})[aeiou]*/gi,"$1")
;`"Aeiou" => "Aei"
"screeeen" => "screeen"
"We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
"Spaces break runs: aei iou." => "Spaces break runs: aei iou."`
.replace(/"/g,"").split("\n").every(s=>f((s=s.split(" => "))[0])==s[1])

```
> 2 votes

# Answer
# Java, 115 bytes

```
class a{public static void main(String[] a){System.out.println(a[0].replaceAll("(?i)([aeiou]{3})[aeiou]*","$1"));}}

```

Expects input as program parameter.

Unit test output:

```
Aei
screeen
We're queung up for the Hawaiin movie.

```
> 2 votes

# Answer
# Arturo, 44 bytes

```
$=>[replace&{/(?i)([aeiou]{3})[aeiou]+}"$1"]

```

Try it
> 2 votes

# Answer
# Japt, 9 bytes

```
r"%v+"È¯3

```

Try it

```
r"%v+"È¯3     :Implicit input of string
r             :Replace
 "%v+"        :RegEx /[aeiou]+/gi
      È       :Pass each match through the following function
       ¯3     :  Slice to length 3

```
> 2 votes

# Answer
# Vyxal `s`, 60 bits1, 7.5 bytes

```
⁽AḊƛAa[3Ẏ

```

Try it Online!
> 2 votes

# Answer
# Tcl, ~~82~~ 56 bytes

Saved 26 bytes thanks to the comment of @naffetS

---

Golfed version. Try it online!

```
proc f s {regsub -all {(?i)([aeiou]{3})[aeiou]*} $s \\1}

```

Ungolfed version. Try it online!

```
proc remove_vowels {s} {
    regsub -all -- {([aeiouAEIOU]{1,3})[aeiouAEIOU]*} $s {\1} result
    return $result
}

puts [remove_vowels "Aeiou"]
puts [remove_vowels "screeeen"]
puts [remove_vowels "We're queueing up for the Hawaiian movie."]
puts [remove_vowels "Spaces break runs: aei iou."]

# "Aeiou" => "Aei"
# "screeeen" => "screeen"
# "We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
# "Spaces break runs: aei iou." => "Spaces break runs: aei iou."

```
> 2 votes

# Answer
# Thunno 2 , 24 bytes

```
Oı"([%]+)"kWDL+%ḄıDhṃ?3ɱ

```

Attempt This Online!

Feel like maybe I'm doing something wrong

## Explained

```
Oı"([%]+)"kWDL+%ḄıDhṃ?3ɱ
O                        # Split the input on spaces
 ı                       # to each item in that:
  "([%]+)"kWDL+%Ḅ        #   split on the regex ([AEIOUaeiou]+) - the () makes it so that the group is retained
                 ı       #   to each group:
                  Dhṃ?   #     if it starts with a vowel:
                      3ɱ #       keep only the first three items
# Ṡ flag joins on spaces before printing

```
> 2 votes

# Answer
# Perl 6,  ~~36~~  35 bytes

~~```
{S:g:i/(<[aeiou]>**3)<[aeiou]>+/$0/} # 36 bytes

```~~
```
$ perl6 -pe 's:g:i/(<[aeiou]>**3)<[aeiou]>+/$0/' # 34 + 1 = 35 bytes

```

usage:

```
$ perl6 -pe 's:g:i/(<[aeiou]>**3)<[aeiou]>+/$0/' <<< "
> Aeiou
> screeeen
> We're queueing up for the Hawaiian movie.
> Spaces break runs: aei iou."

```

```
Aei
screeen
We're queung up for the Hawaiin movie.
Spaces break runs: aei iou.

```
> 1 votes

# Answer
## C (205 bytes)

```
#include <stdio.h>
#define T(x)for(i=0;i<10;++i){if(v[i]==x){b=x;m=1;break;}}putchar(c);
main(b,c,i,m){char v[]="aeiouAEIOU";
while((c=getchar())!=EOF){if(!m){T(c);}else{if(b==c)continue;else{m=0;T(c);}}}}

```

(One line break added for clarity)
> 1 votes

# Answer
# Matlab / Octave, 54 bytes

```
@(s)regexprep(s,'(?<=[aeiouAEIOU]{3})[aeiouAEIOU]','')

```

Example:

```
>> @(s)regexprep(s,'(?<=[aeiouAEIOU]{3})[aeiouAEIOU]','')
ans =
    @(s)regexprep(s,'(?<=[aeiouAEIOU]{3})[aeiouAEIOU]','')

>> ans('We''re queueing up for the Hawaiian movie.')
ans =
We're queung up for the Hawaiin movie.

```

**Try it at ideone**.
> 1 votes

# Answer
## Scala, 107 bytes

```
readLine.foldLeft("",0)((a,n)=>if(!"aeiou".contains(n|32))a._1+n->0 else if(a._2>2)a else(a._1+n,a._2+1))_1

```
> 1 votes

# Answer
## Seriously, 34 bytes

```
,;ù0╗`Ok"aeiou"Okd-Y;╜+*;╗4>`M@░εj

```

Hex Dump:

```
2c3b9730bb604f6b226165696f75224f6b
642d593bbd2b2a3bbb343e604d40b0ee6a

```

Try it online

It uses the same algorithm as the Pyth answer, mapping over the string while keeping track of the length of the current run of vowels in a register, incrementing it whenever the current character is a vowel, and checking whether it has exceeded the allowed length, returning 0 if so, and then filtering the original string with this generated filter. It will be a lot shorter once we can use set subtraction on strings. (The `Ok` can be deleted and the `Okd` can be replaced with just `@`). I hear this feature is coming in the next update....
> 1 votes

# Answer
## x86 MS-DOS .COM file, ~~44 bytes~~ 36 bytes

.COM files are widely supported from MS-DOS 1 through the present---I'm running in dosemu, using 8086 commands only.

Reduced from 44 to 36 bytes by using REPNE SCASB to test for vowels instead of using a separate command to test each vowel.

```
Hex dump, reversible using `xxd -r -seek -256`:
0100: b3 03 43 b4 08 cd 21 88 c2 24 df b1 05 bf 1f 01   ..C...!..$......
0110: f2 ae 74 02 b3 05 4b 74 e9 b4 02 cd 21 eb e4 41   ..t...Kt....!..A
0120: 45 49 4f 55                                       EIOU

Unassembled using debug:
0100 B303    MOV BL,03     ; initialize counter to 3 (will increment by 1 to be 4)
0102 43      INC BX        ; increment counter--runs each time it hits 0 so it never goes <0
0103 B408    MOV AH,08     ;
0105 CD21    INT 21        ; with AH=8, read 1 char without echo
0107 88C2    MOV DL,AL     ; copy input for potential output
0109 24DF    AND AL,DF     ; make input uppercase for testing
010B B105    MOV CL,05     ; count of 5 vowels to test against
010D BF1F01  MOV DI,011F   ; location of first vowel to test against
0110 F2AE    REPNE SCASB   ; test input against each vowel
0112 7402    JZ 0116       ; if input was not a vowel:
0114 B305    MOV BL,05     ;    reset counter to 5 (will decrement by 1 to be 4)
0116 4B      DEC BX        ; decrement counter regardless
0117 74E9    JZ 0102       ; if hit 0 (fourth or later vowel): goto 102
0119 B402    MOV AH,02     ;
011B CD21    INT 21        ; with AH=2, print char
011D EBE4    JMP 0103      ; go to 103 for next character

bytes 011f-0123 contain the uppercase vowels AEIOU

```
> 1 votes

# Answer
# , 21 bytes (noncompeting)

```
ñ[aeiou]ñÍãqû3}úsq*

```

Try it online!

Explanation:

```
ñ[aeiou]ñ                     "Assign the string `[aeiou]` to register 'q'
         Íã                   "Search and replace on multiple lines (case insensitive):
           <C-r>q             "Register 'q'
                 û3}          "Repeated 3 times
                    ús        "Mark the following to be removed:
                      <C-r>q* "Register 'q' repeated any number of times

```

This is just barely shorter than the more straightforward solution:

```
Íã[aeiou]û3}ús[aeiou]*

```

(22 bytes)
> 1 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
ḟ€ØckŻḣ€4FḊ

```

Try it online!

Copy-paste from my answer to a similar challenge, except somehow even worse. `e€Øc‘×¥\<4x@` is nicer for one more byte (check edit history for an explanation).

```
 €             For each character of the input,
ḟ              filter out
  Øc           vowels.
     Ż         Prepend a 0 to the input, and
    k          partition that after truthy (nonempty) positions in the original.
      ḣ€4      Keep the first 4 elements of each slice,
         F     flatten the slices,
          Ḋ    and remove the 0.

```
> 1 votes

# Answer
# Ruby, 44 bytes

```
><<$<.read.gsub(/([aeiou]{3})[aeiou]+/i,'\1')

```

Example:

```
% ruby -e "$><<$<.read.gsub(/([aeiou]{3})[aeiou]+/i,'\1')" <<< "
Aeiou
screeeen
We're queueing up for the Hawaiian movie.
Spaces break runs: aei iou."

Aei
screeen
We're queung up for the Hawaiin movie.
Spaces break runs: aei iou.

```
> 0 votes

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


title: Tips for golfing in Thunno 2

text:
# Question
Title: Tips for golfing in Thunno 2
Thunno 2 is a stack-based golfing language with around 400 commands (achieved through overloads) created by me, The Thonnu.

It seems like a good idea to share some tips for golfing in Thunno 2.

Please, one tip per answer, and no tips like “remove comments and whitespace”.

---

Links:

# Answer
# Variables

Thunno 2 has many variables. Here they are.

## `x` and `y`

`x` and `y` are initialised to `1` and `2`. You can get them by using `x` and `y`, and set them by using `X` and `Y`. As well as that, you can set them without popping by using  and , and apply a command to them by using  and .

## `n` and

These are context variables, so you cannot set them. `n` takes the value of the current loop variable, and  takes the value of the iteration index (0-indexed). You can get them by using `n` and .

## `¡` and `!`

You can name variables using `¡` and `!`. All variables in Thunno 2 have a one-character long name. You can get a named variable by using `¡` and then the name. You can set a named variable by using `!` and then the name.

## `Ȥ` and `ȥ`

This is the global array. It is initialised to an empty list at the start of the program. You can get it by using `Ȥ` and add to it by using `ȥ`. Currently, there is no command to remove an item from the global array, but it may be added in the future.
> 5 votes

# Answer
# Compress your numbers, strings, and lists

Thunno 2, like many other golfing languages, has utilities to compress numbers, strings, and lists. Here they are.

## Base 255 compression

You can compress all three data types in base 255.

### Numbers

This is the simplest one. You can just convert your number to base 255 using the Thunno 2 Codepage. **This program can compress a number for you**. For example, `1234567890` can be compressed into `»Jt€Ṇ»`.

Compressed numbers are delimited by `»`. However, you can also compress smaller numbers with `«`. If your number is less than 65025, you can use `«` followed by two characters from the codepage, which saves you one byte from the ending delimiter. For example, `54321` can be compressed into `«ḍ©`.

### Strings

You can compress a string which consists only of letters and spaces in base 255. **This program can compress a string for you**. For example, `"n ne e se s sw w nw"` can be compressed into `“£ḂA⁷<ọŒ⁼Ẓ2Ẏ®“`.

Lowercase compressed strings are delimited by . Title case compressed strings are delimited by .

### Lists

You can also compress numeric lists in base 255. **This program can compress a numeric list for you**. For example, `[43,44,45,46,60,62,91,93]` can be compressed into `¿€ỵæ-j2oẹ&⁵ẏ¿`.

Compressed numeric lists are delimited by `¿`. You can compress the following characters only: `0123456789-.,`. You can leave out the brackets when compressing.

## Dictionary compression

Thunno 2 has a dictionary consisting of around 32000 words. Each of these words can be compressed in 2 characters. **This program can optimally dictionary compress a string for you**. (Note: the program will not give you the delimiters). For example, `"Hello, World!"` can be compressed into `’Ƙ¥, «ʋ!’`.

Lowercase dictionary compressed strings are delimited by . Title case dictionary compressed strings are delimited by . Any alphanumeric characters will not be compressed, so `’Ƙ¥, «ʋs!’` is `"Hello, Worlds!”`. The same goes for the characters `.,!?:\"'% ()`.
> 4 votes

# Answer
# Use the flags

Thunno 2 has some very useful flags that can often shave 2 or more bytes off of your answer. Here's the full list, but I'll show off a couple here that are particularly useful.

## `J`, `j`, `N`, `n`, ,

These flags are used to join a list to a string by a specific character, and can be very useful in many challenges. Each uppercase letter joins the top of the stack, while the lowercase equivalent joins the entire stack.

* `J` and `j` join by nothing
* `N` and `n` join by newlines
* and  join by spaces

## `B`

The B flag converts any input strings to integer arrays representing the codepoint of each character, and any integer array output back to a string. This is very useful for -based challenges, where you have to transform some string or maybe just need to output some characters with a high codepoint.

## `G`, `M`, `S`, `s`

These flags are pretty standard in golfing languages these days, but that doesn't mean they aren't useful. `G` returns the maximum of the top of the stack, `M` the minimum, and `S` the sum. There is also `s` for the sum of the entire stack.

## `v`, `e`

These flags aren't necessarily useful for golfing, but they can come in very handy. As of writing this, they are deemed "experimental." `e` automatically outputs an explanation of your code, with the definition of each command commented to the side. `v` enables verbose mode, which lets you use long token names for builtins while developing your answer, which you can then switch to regular commands when you've finished. I encourage you to try them out, though you may or may not find them useful.

There are other useful flags, but these are just a few that seem particularly handy to me.
> 4 votes

# Answer
# Use shortcut endings

*(This only works in Thunno 2.2.0+. Attempt This Online is on 2.1.9, so it will not work there.)*

So let's say we need a discard filter (i.e. remove items for which the filter code is true). Simple, right? Just use a filter and a not:

```
æ ... ¬;

```

But what if I told you we can go one byte better? You see, there is actually a shortcut for `¬;`, and that's `}`. So a discard filter will be:

```
æ ... }

```

Similarly, `:` is a shortcut for `=;`.

Note: `}` will not work at the end of a for loop, and `:` will not work in an if statement, but they work everywhere else (map/filter/sort by/group by/while/etc.)
> 3 votes

# Answer
# Remember that mapping/filtering/etc. casts numbers to ranges

If your code looks like this:

```
Rı ... ;

```

The `R` is unnecessary as numbers are implicitly cast to ranges when mapping/filtering/etc.

So, you can just use:

```
ı ... ;

```

Note: implicit range generation is always `[1..n]` (`R`). Anything else will need something before the map/filter/etc.

* If you want `[0..n)`, use `L`
* If you want `[0..n]`, use `Ė`
* If you want `[1..n)`, use `ė`
> 3 votes

# Answer
# Use one, two, and three character strings

In Thunno 2 strings start and end with `"`. But there are also other strings that don't need an ending delimiter:

* `'` is a one-character string. It pushes the next character to the stack as a string.
* ``` is a two-character string. It pushes the next two characters to the stack as a string.
* `ʋ` is a three-character string. It pushes the next three characters to the stack as a string.

**But be careful.** ``` and `ʋ` might try to decompress a dictionary-compressed string if you give them the wrong characters:

* ``` will look at the next two characters. If both of them are in the dictionary codepage (i.e. neither of them are in the uncompressable characters string below), it will decompress them as a dictionary-compressed word. Otherwise, it will default to normal behaviour.
* `ʋ` will look at the next four characters. If all four of them are in the dictionary codepage (i.e. none of them are in the uncompressable characters string below), it will decompress them as two dictionary-compressed words. Otherwise, it will default to normal behaviour.

These are the uncompressable characters in Thunno 2: `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?:\"'%() ‘’`
> 1 votes

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