[Question]
      [
# Binary to decimal converter
As far as I can see, we don't have a simple binary to decimal conversion challenge.
---
Write a program or function that takes a positive binary integer and outputs its decimal value.
You are not allowed to use any builtin base conversion functions. Integer-to-decimal functions (e.g., a function that turns `101010` into `[1, 0, 1, 0, 1, 0]` or `"101010"`) are exempt from this rule and thus allowed.
Rules:
* The code must support binary numbers up to the highest numeric value your language supports (by default)
* You may choose to have leading zeros in the binary representation
* The decimal output may not have leading zeros.
* Input and output formats are optional, but there can't be any separators between digits. `(1,0,1,0,1,0,1,0)` is not a valid input format, but both `10101010` and `(["10101010"])` are.
	+ You must take the input in the "normal" direction. `1110` is `14` not `7`.
Test cases:
```
1
1
10
2
101010
42
1101111111010101100101110111001110001000110100110011100000111
2016120520371234567
```
This challenge is related to a few other challenges, for instance [this](https://codegolf.stackexchange.com/questions/68247/convert-a-number-to-hexadecimal), [this](https://codegolf.stackexchange.com/questions/63564/simplify-binary) and [this](https://codegolf.stackexchange.com/questions/69155/base-conversion-with-strings).

[Answer]
# Clojure, ~~114~~ ~~105~~ ~~63~~ 41 bytes
## V4: 41 bytes
-22 bytes thanks to @cliffroot. Since `digit` is a character, it can be converted to it's code via `int`, then have 48 subtracted from it to get the actual number. The map was also factored out. I don't know why it seemed necessary.
```
#(reduce(fn[a d](+(* a 2)(-(int d)48)))%)
```
## V3: 63 bytes
```
(fn[s](reduce #(+(* %1 2)%2)(map #(Integer/parseInt(str %))s)))
```
-42 bytes (!) by peeking at other answers. My "zipping" was evidently very naïve. Instead of raising 2 to the current place's power, then multiplying it by the current digit and adding the result to the accumulator, it just multiplies the accumulator by 2, adds on the current digit, then adds it to the accumulator. Also converted the reducing function to a macro to shave off a bit.
Thanks to @nimi, and @Adnan!
Ungolfed:
```
(defn to-dec [binary-str]
  (reduce (fn [acc digit]
            (+ (* acc 2) digit))
          (map #(Integer/parseInt (str %)) binary-str)))
```
## V2: 105 bytes
```
#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range)(reverse %)))
```
-9 bytes by reversing the string so I don't need to create an awkward descending range.
## V1: 114 bytes
Well, I'm certainly not winning! In my defense, this is the first program I've ever written that converts between bases, so I had to learn how to do it. It also doesn't help that `Math/pow` returns a double that requires converting from, and `Integer/parseInt` doesn't accept a character, so the digit needs to be wrapped prior to passing.
```
#(reduce(fn[a[p d]](+ a(*(Integer/parseInt(str d))(long(Math/pow 2 p)))))0(map vector(range(dec(count %))-1 -1)%))
```
Zips the string with a descending index representing the place number. Reduces over the resulting list.
Ungolfed:
```
(defn to-dec [binary-str]
  (reduce (fn [acc [place digit]]
            (let [parsed-digit (Integer/parseInt (str digit))
                  place-value (long (Math/pow 2 place))]
              (+ acc (* parsed-digit place-value))))
          0
          (map vector (range (dec (count binary-str)) -1 -1) binary-str)))
```
[Answer]
# Perl, ~~21~~ ~~19~~ 16 + 4 = 20 bytes
-4 bytes thanks to @Dada
Run with `-F -p` (including the extra space after the `F`). Pipe values to the function using `echo -n`
```
$\+=$_+$\for@F}{
```
Run as `echo -n "101010" | perl -F -pE '$\+=$_+$\for@F}{'`
I feel this is sufficiently different from @Dada's answer that it merits its own entry.
Explanation:
```
-F                              #Splits the input character by character into the @F array
-p                              #Wraps the entire program in while(<>){ ... print} turning it into
while(<>){$\+=$_+$\for@F}{print}
                   for@F        #Loops through the @F array in order ($_ as alias), and...
          $\+=$_+$\             #...doubles $\, and then adds $_ to it (0 or 1)...
while(<>){              }       #...as long as there is input.
                         {print}#Prints the contents of $_ (empty outside of its scope), followed by the output record separator $\
```
This uses my personal algorithm of choice for binary-to-decimal conversion. Given a binary number, start your accumulator at 0, and go through its bits one by one. Double the accumulator each bit, then add the bit itself to your accumulator, and you end up with the decimal value. It works because each bit ends up being doubled the appropriate number of times for its position based on how many more bits are left in the original binary number.
[Answer]
# Haskell, 31 bytes
```
f=foldl(\a b->2*a+(read$b:[]))0
```
Takes input in string format (e.g. `"1111"`). Produces output in integer format (e.g. `15`).
`:[]` Converts from an element to an array -- in this chase from `Char` to `[Char]` (`String`).
`read` Converts from string to whatever context it's in (in this case the context is addition, so converts to `Num`)
so `(read$b:[])` converts `b` from `Char` to `Num`.
`a` is the accumulator, so multiply that by two and add the `Num` version of `b`.
If input in the format `[1,1,1,1]` was allowed, the 18 byte
```
f=foldl((+).(2*))0
```
would work, but since it's not, it doesn't.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 12 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
(++⊢)/⌽⍎¨⍞
```
`⍞` get string input
`⍎¨` convert each character to number
`⌽` reverse
`(`...`)/` insert the following function between the numbers
 `++⊢` the sum of the arguments plus the right argument
---
ngn shaved 2 bytes.
[Answer]
# [7](https://esolangs.org/wiki/7), 25 bytes (65 characters)
```
07717134200446170134271600446170001755630036117700136161177546635
```
[Try it online!](https://tio.run/##NcjBDcBADALBlpbYhv4rc@4iRXyGzS6JouoHuq1wHfm/oMy4oCzlBB18nLZrdsXdCw)
## Explanation
```
0**77**                             Initialize counter to 0 (an empty section)
   17134200..77546635           Push the main loop onto the frame
```
Once the original code has finished executing, the frame is
```
||**6**||**7**13420044**7**013427160044**7**000175563003**77**7001361**77**7546**35**
```
The last section of this is the main loop, which will run repeatedly until it gets deleted. All of it except the last two commands is data and section separators, which push commands onto the frame to leave it as:
```
||**6**|| (main loop) |**73426644**|**67342**1**6644**|**6667**55**3663**||0013**7**||54
```
**`3`** outputs the last section (`54`) and discards the last two bars. On the first iteration, `5` is interpreted as a switch to output format 5 ("US-TTY"), which converts each pair of commands to a character. The `4` following it does not form a group, so it is ignored. On future iterations, we are already in output format 5, so `54` is interpreted as a group meaning "input character". To do this, the character from STDIN is converted into its character code (or, on EOF, `-1`), and 1 is added. Then, the last section (which is now the `00137`) is repeated that many times. In summary:
* If the character is `0`, `00137` is repeated 49 times.
* If the character is `1`, `00137` is repeated 50 times.
* If there are no more characters, `00137` is repeated 0 times (i.e. deleted).
* If this was the first iteration, `00137` is left alone (i.e. repeated 1 time).
**`5`** removes the last section (`00137` repeated some number of times) from the frame and executes it, resulting in this many sections containing **`6673`**.
The main loop has now finished executing, so the last section (which is **`6673`** unless we reached EOF) runs. **`66`** concatenates the last three sections into one (and has some other effects that don't affect the number of sections), which **`73`** deletes. Thus, the last three sections are deleted, and this repeats until the last section is no longer **`6673`**.
* If we reached EOF, nothing happens.
* If this is the first iteration or the character was `0`, after removing the last three sections 0 or 16 times, there is just one copy left on the frame. This copy deletes itself and the two sections before it, leaving everything up to the main loop and the section after it.
* If the character was `1`, after removing the last three sections 17 times, all 50 copies and the third section after the main loop (the EOF handler) have been deleted.
Now, the last section left on the frame runs. This could, depending on the inputted character, be any of the three sections after the main loop.
If this is the first iteration or the character was `0`, the section just after the main loop, **`73426644`**, runs.
**`73`** deletes this section, and **`4`** swaps the main loop with the counter behind it. This counter keeps track of the number we want to output, stored as the number of `7`s and `1`s minus the number of `6`s and `0`s. This metric has the property that it is not changed by pacification (which changes some `6`s into `0`s, some `7`s into `1`s, and sometimes inserts `7...6` around code). **`2`** duplicates the counter and **`6`** concatenates the two copies (after pacifying the second, which, as we saw, does not change the value it represents), so the value is doubled. If this was the first iteration, the counter was previously empty, and doubling it still results in an empty section. Then, **`6`** gets rid of the empty section inserted by **`4`** (and pacifies the counter again, leaving the value unchanged), and **`44`** swaps the counter back to its original position. This leaves two empty sections on the end of the frame, which are removed automatically, and the main loop runs again.
If the character was `1`, the second section after the main loop (`**67342**1**6644**`) runs. This is just like the section before it (explained in the last paragraph), except for two extra commands: a **`6`** at the start, which joins the section with the previous one before **`73`** deletes it, and a `1` in the middle, which adds a `7` to the counter (increasing its value by 1) after it gets doubled.
If we reached EOF, the third section after the main loop (`**6667**55**3663**`) runs. **`666`** joins the last four sections (everything after the counter) into one section, to be deleted by **`3`**. `**7**55**3**` exits output format 5 by outputting `55` and deletes the section before it, leaving only `||**6**| (counter)` on the frame. **`66`** pacifies the two sections and combines them, turning the **`6`** back into a `0` (and not changing the value of the counter). Finally, the last **`3`** outputs everything.
The `0` at the start enters output format 0 ("Numerical output"), and the rest of the section (i.e. the counter) is converted to a number by taking the number of `7`s and `1`s minus the number of `6`s and `0`s. This value, which is the input converted from binary, is output in decimal and the program terminates.
[Answer]
# Excel, ~~74 70~~ 55
Trailing parens already discounted. Tested in Excel Online.
## Formulae:
* `A1`: Input
* `B1`: `=LEN(A1)` (7)
### Main Code (48):
A pretty simple "add all the powers of 2" formula:
```
=SUM(MID(A1,1+B1-SEQUENCE(B1),1)/2*2^SEQUENCE(B1))
```
Verify with:
```
=DECIMAL(A1,2)
```
[Answer]
# [R](https://www.r-project.org/), ~~48~~ 37 bytes
*-11 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126)*
```
sum(utf8ToInt(scan(,""))%%2*2^(31:0))
```
Takes input as a string, left-padded with 0s to 32 bits. [Try it online!](https://tio.run/##K/r/v7g0V6O0JM0iJN8zr0SjODkxT0NHSUlTU1XVSMsoTsPY0MpAU/O/kgFOYAiGSv8B "R – Try It Online")
I copied some good ideas from [djhurio](https://codegolf.stackexchange.com/users/13849)'s [much earlier R answer](https://codegolf.stackexchange.com/a/102320/16766), so go give that an upvote too. As with the first solution there, this solution won't work for the last test case because it's too large to fit into R's default size of integer.
### Explanation
To get a vector of the bits as integers 0 and 1, we use `uft8ToInt` to convert to a vector of character codes. This gives us a list of 48s and 49s, which we take mod 2 to get 0s and 1s.
Then, to get the appropriate powers of 2 in descending order, we construct a range from 31 down to 0. Then we convert each of those numbers to the corresponding power of two (`2^`).
Finally, we multiply the two vectors together and return their `sum`.
[Answer]
# x86-16 machine code, 10 bytes
**Binary:**
```
00000000: 31d2 acd0 e811 d2e2 f9c3                 1.........
```
**Listing:**
```
31 D2       XOR  DX, DX         ; clear output value
        CHRLOOP:
AC          LODSB               ; load next char into AL
D0 E8       SHR  AL, 1          ; CF = LSb of ASCII char
11 D2       ADC  DX, DX         ; shift CF left into result
E2 F9       LOOP CHRLOOP        ; loop until end of string
C3          RET                 ; return to caller
```
Callable function, input string in `[SI]` length in `CX`. Result in `DX`.
**Example test program I/O:**
[![enter image description here](https://i.stack.imgur.com/4rM2x.png)](https://i.stack.imgur.com/4rM2x.png)
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~11~~ 10 bytes
```
(+/2 1*,)/
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs9LQ1jdSMNTS0dTn4tLnMuQyNABBLkMgCQFgPpACkxAMIQzAGCRrgBAD01wxXFyeVnrq6sbxGjUxlka2WlbqmvEGVgmJRellCoZcaeqeXABdSRgX)
[Answer]
## C, 48 bytes
```
i;f(char *s){for(i=0;*++s;i+=i+*s-48);return i;}
```
Heavily inspired by @edc45 's answer but I made some significant changes. I made 'i' a global variable to save having to typecast. I also used a for loop to save a few bytes. It does now require a single leading 0 in the binary representation.
**More readable version**
```
f(char *s){
  int i = 0; // Total decimal counter
  for(;;*++s;i+=i+*s-48); // Shift left and add 0 or 1 depending on charecter
  return i;
}
```
[Answer]
# k, 8 bytes
Same method as the Haskell answer above.
```
{y+2*x}/
```
Example:
```
{y+2*x}/1101111111010101100101110111001110001000110100110011100000111b
2016120520371234567
```
[Answer]
# JavaScript (ES7), ~~56~~ 47 bytes
Reverses a binary string, then adds each digit's value to the sum.
```
n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)
```
**Demo**
```
f=n=>[...n].reverse().reduce((s,d,i)=>s+d*2**i,0)
document.write( f('101010') ) // 42
```
[Answer]
# Java 7, 87 bytes
```
long c(String b){int a=b.length()-1;return a<0?0:b.charAt(a)-48+2*c(b.substring(0,a));}
```
For some reason I always go straight to recursion. Looks like an [iterative solution](https://codegolf.stackexchange.com/a/102233/51785) works a bit nicer in this case...
[Answer]
# JavaScript (ES6), 38
Simple is better
```
s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")
```
**Test**
```
f=s=>eval("for(i=v=0;c=s[i++];)v+=+c+v")
console.log("Test 0 to 99999")
for(e=n=0;n<100000;n++)
{
  b=n.toString(2)
  r=f(b)
  if(r!=n)console.log(++e,n,b,r)
}
console.log(e+" errors")

```
[Answer]
# Turing Machine Code, 272 bytes
(Using, as usual, the morphett.info rule table syntax)
```
0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 1 l 1
1 1 0 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 2 r 4
3 2 3 r 4
3 3 4 r 4
3 4 5 r 4
3 5 6 r 4
3 6 7 r 4
3 7 8 r 4
3 8 9 r 4
3 9 0 l 3
4 * * r 4
4 _ _ r A
```
AKA "Yet another trivial modification of my earlier base converter programs."
[Try it online](http://morphett.info/turing/turing.html?a283209e440e64106cd35d1bc3f181e1), or you can also use test it using [this java implementation.](https://github.com/SuperJedi224/Turing-Machine)
[Answer]
## JavaScript, ~~18~~ 83 bytes
~~`f=n=>parseInt(n,2)`~~
`f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)`
**Demo**
```
f=n=>n.split('').reverse().reduce(function(x,y,i){return(+y)?x+Math.pow(2,i):x;},0)
document.write(f('1011')) // 11
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~8~~, 7 bytes
```
"@oovsE
```
[Try it online!](http://matl.tryitonline.net/#code=IkBvb3ZzRQ&input=JzEwMTAxJw)
One byte saved thanks to @LuisMendo!
[Alternate approach: (9 bytes)](http://matl.tryitonline.net/#code=b290bjpQVypz&input=JzEwMTAxJw)
```
ootn:PW*s
```
[Answer]
# Befunge, ~~20~~ 18 bytes
Input must be terminated with EOF rather than EOL (this lets us save a couple of bytes)
```
>+~:0`v
^*2\%2_$.@
```
[Try it online!](http://befunge.tryitonline.net/#code=Pit-OjBgdgpeKjJcJTJfJC5A&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ)
**Explanation**
```
>             The stack is initially empty, the equivalent of all zeros.
 +            So the first pass add just leaves zero as the current total.
  ~           Read a character from stdin to the top of the stack.
   :0`        Test if greater than 0 (i.e. not EOF)
      _       If true (i.e > 0) go left.
    %2        Modulo 2 is a shortcut for converting the character to a numeric value.
   \          Swap to bring the current total to the top of the stack.
 *2           Multiply the total by 2.
^             Return to the beginning of the loop,
 +            This time around add the new digit to the total.
                ...on EOF we go right...
       $      Drop the EOF character from the stack.
        .     Output the calculated total.
         @    Exit.
```
[Answer]
# Ruby, 37 bytes
```
ruby -e 'o=0;gets.each_byte{|i|o+=o+i%2};p o/2'
         1234567890123456789012345678901234567
```
This depends on the terminating `\n` (ASCII decimal 10) being zero modulo 2 (and on ASCII 0 and 1 being 0 and 1 mod two, respectively, which thankfully they are).
[Answer]
# [아희(Aheui)](http://esolangs.org/wiki/Aheui), 40 bytes
```
아빟뱐썩러숙
뎌반뗘희멍파퍄
```
Accepts a string composed of 1s and 0s.
**To try online**
Since the online Aheui interpreter does not allow arbitrary-length strings as inputs, this alternative code must be used (identical code with slight modifications):
Add the character `벟` at the end of the first line (after `우`) length(n)-times.
```
어우
우어
뱐썩러숙
번댜펴퍼망희땨
```
If the input is `10110`, the first line would be `어우벟벟벟벟벟`.
When prompted for an input, do NOT type quotation marks. (i.e. type `10110`, not `"10110"`)
[Try it here! (copy and paste the code)](http://jinoh.3owl.com/aheui/jsaheui_en.html)
[Answer]
# ClojureScript, 36 bytes
```
(fn[x](reduce #(+(* 2 %)(int %2))x))
```
or
```
#(reduce(fn[a n](+(* 2 a)(int n)))%)
```
The straightforward reduction. Takes a string as input.
[Answer]
# Minkolang v0.15, ~~23~~ 19 bytes
```
n6ZrI[2%2i;*1R]$+N.
```
[Try it online!](http://play.starmaninnovations.com/minkolang/?code=n6ZrI%5B2%252i%3B*1R%5D%24%2BN%2E&input=1101)
### Explanation
```
n                             gets input in the form of a number
 6Z                           converts to string (so that it is split into an array)
   r                          reverses it
    I                         gets the stack length
     [        ]               for loop with the stack's length as the number of iterations
      2%                       gets the modulo of the ascii value
                               1 =(string conversion)> 49 =(after modulo)> 1
                               0 =(string conversion)> 48 =(after modulo)> 0
        2i;                    raises 2 to the power of the loop counter
           *                   multiplies it by the modulo
            1R                 rotates stack 1 time
              $+              sums everything
                N.            outputs as number and exit
```
[Answer]
# Common Lisp, ~~99~~ ~~88~~ 72 bytes
Takes a string as input
```
(defun f(s)(reduce(lambda(a d)(+ d(* a 2)))(map'list #'digit-char-p s)))
```
Ungolfed:
```
(defun bin-to-dec (bin-str)
  (reduce (lambda (acc digit) (+ digit (* acc 2)))
          (map 'list #'digit-char-p bin-str)))
```
[Answer]
# ><> (Fish) ~~36~~ 28 bytes
```
/i:1+?!v$2*$2%+!| !
/0| ;n~<
```
Edit 1: Forgot to put the output in the original. Added output and used MOD 2 instead of minus 48 to convert ascii to decimal to save the extra bytes lost. (no change in bytes)
Edit 2: Changed the algorithm completely. Each loop now does this; times current value by 2, then add the mod of the input. (saving of 8 bytes)
[Online version](https://fishlanguage.com/playground/BPT5uHb6PgvsRyvrP)
[Try it Online!](http://fish.tryitonline.net/#code=L2k6MSs_IXYkMiokMiUrIXwgIQovMHwgO25-PA&input=MTEwMTExMTExMTAxMDEwMTEwMDEwMTExMDExMTAwMTExMDAwMTAwMDExMDEwMDExMDAxMTEwMDAwMDExMQ) - This works with bigger numbers than the above link.
[Answer]
# **C, 44 bytes**
```
d(s,v)char*s;{return*s?d(s,v+=v+*s++-48):v;}
```
Use as follows :
```
int main(){
  printf("%i\n", d("101010",0));
}
```
Remove two bytes and an unused parameter thanks to Steadybox
[Answer]
# **MATLAB, 49 bytes**
```
@(a)dot(int2str(a)-'0',2.^(floor(log10(a)):-1:0))
```
Anonymous function that splits the input into an array with `int2str(a)-'0'`, then does a dot product with powers of 2. Has rounding error for the last test case, will update the solution when I figure out a fix.
[Answer]
# Forth (gforth 0.7.3), 47 bytes
```
: x 2 base ! bl parse s>number drop decimal . ;
```
`: x` - define new word with name 'x'
`2 base !` - set base to binary
`bl parse` - read line until a space (bl) or EOL
`s>number` - try to convert the string to number
`drop` - we only want the converted number and not the success flag
`decimal` - set base to decimal
`.` - print value on top of stack
`;` - end of definition
Test cases:
```
x 1 1  ok
x 10 2  ok
x 101010 42  ok
x 1101111111010101100101110111001110001000110100110011100000111 2016120520371234567  ok
```
[Answer]
# C, ~~41~~ 37 bytes
```
i;b(char*s){i+=i+*s++%2;i=*s?b(s):i;}
```
[Wandbox](http://melpon.org/wandbox/permlink/HSeSFhE9lswSnFlj)
[Answer]
# SmileBASIC, ~~47~~ 44 bytes
```
INPUT B$WHILE""<B$N=N*2+VAL(SHIFT(B$))WEND?N
```
Another program of the same size:
```
INPUT B$WHILE""<B$N=N*2OR"0"<SHIFT(B$)WEND?N
```
[Answer]
# APL(NARS), 26 chars, 52 bytes
```
{+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵}
```
test:
```
  f←{+/a×⌽1,2x*⍳¯1+≢a←1-⍨⎕D⍳⍵}
  ⎕fmt f"0"
0
~
  f"1"
1
  ⎕fmt f"101010"
42
~~
  f"10"
2
  (≢,f)"11011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
152 4995366924470859583704000893073232977339613183
```
152 bits... It should be limited from memory for store string and numbers.
]


[Question]
      [
A brace string is defined as a string consisting of the characters `*()[]` in which braces match correctly:
```
[brace-string] ::= [unit] || [unit] [brace-string]
[unit]         ::= "" || "*" || "(" [brace-string] ")" || "[" [brace-string] "]"
```
This is a valid brace-string:
```
((())***[]**)****[(())*]*
```
But these are not:
```
)(
**(**[*](**)
**([*)]**
```
Your task is to write a program (or function) that, given a positive integer `n`, takes a number as input and outputs (or returns) all valid brace strings of length `n`.
## Specifications
* You may output the strings in any order.
* You may output as a list or a string separated by a different character.
* Your program must handle 0 correctly. There is 1 possible brace-string of length 0, which is the empty string `""`.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
## Test Cases
```
0.
1. *
2. ** () []
3. *** ()* []* (*) [*] *() *[]
4. **** ()** []** (*)* [*]* (**) **() **[] *(*) *[*] (()) ()() ()[] ([]) [**] [()] [[]] []() [][] *()* *[]*
```

[Answer]
# Prolog, 69 bytes
```
s-->[];e,s.
e-->"*";"(",s,")";"[",s,"]".
b(N,A):-length(A,N),s(A,[]).
```
One of the most interesting properties of Prolog is that in many cases it's capable of running a program backwards; for example, instead of testing to see if something's true, you can generate all solutions for which it's true, and instead of checking the length of a string, you can generate all strings with a given length. (Another nice property of Prolog is that it requires whitespace after the end of each predicate definition, and a newline can be inserted as cheaply as a space; thus even golfed programs are often fairly readable.)
The above defines a predicate (the equivalent of a function) `b` which tests to see if a string has a given length and is a "brace string" as defined in the question. Specifically, it does this via Prolog's grammar/regex/pattern-match support that gives some nice, short sugar for defining this sort of expression (apparently this is standard/portable, but I was unaware of this while originally writing the answer, and thus assumed the answer would work on only one Prolog implementation; it seems it works on every implementation that complies with the standards, though). The program can be translated into English fairly directly; the first two lines say "an *s* is an empty string, or an *e* followed by an *s*; an *e* is an asterisk, or an *s* in parentheses, or an *s* in square brackets". The third line can be interpreted as "The *b* of *N* can be *A* if *A* is a list with length *N* and *A* is an *s* followed by a null string."
I took some care to write `s` (and thus `b`) so that they match each "brace string" in exactly one way (which is the reason that both `s` and `e` have to exist, rather than grouping them into one predicate). This makes them both entirely reversible; thus `b` can be used to generate all "brace strings" of a given length, in addition to testing if a string is a brace string of a given length (it can also be used a third way round, to figure out the length of a brace string, but that is almost certainly its least useful mode of operation). The implementation is recursive, e.g. to generate an *s*, the code will generate all possible *e*s that are no longer than the required length of the output, and append all possible *s*s that fit in the remaining space to them; because I specified the length of the argument in advance (within *b*), the Prolog engine knows that it can't generate output that's longer than the given length, which allows the recursion to terminate.
Here's an example of the program in operation:
```
| ?- b(4,A),format("~s ",[A]),fail.
**** **() **[] *()* *(*) *[]* *[*] ()** ()() ()[] (*)* (**) (()) ([]) []** []() [][] [*]* [**] [()] [[]]
```
[Answer]
## Haskell, ~~101~~ 94 bytes
7 bytes saved by Zgarb!
```
b 0=[""]
b n=[x++y|k<-[1..n],x<-u k,y<-b$n-k]
u 1=["*"]
u n=[a:s++b|s<-b$n-2,a:b<-["()","[]"]]
```
Almost straightforward, following the definition, but with the `""` case moved.
Use:
```
*Main> map b [0..3]
[[""],["*"],["**","()","[]"],["***","*()","*[]","()*","[]*","(*)","[*]"]]
*Main> length $ b 10
21595
```
(The second computation takes less than a second on a slow machine.)
I'd also like to share the result of another approach I came up with while thinking about generating functions. It defines a *list* `b` of lists of strings such that `b!!n` contains all brace-strings of length `n`. Similarly, `u!!n` contains all atoms of size `n-1`. One nice thing is that the code is not using any numbers. It is not completely golfed: `u` and `i` could be inlined, and it certainly misses a few other golfing opportunities. Unfortunately, it doesn't look like it can be made shorter than the first version, but it computes `length $ b !! 10` even faster.
```
b=[""]:b%u
u=["*"]:map i b
i=concatMap(\s->['(':s++")",'[':s++"]"])
(b:c)%f=zipWith(++)[[x++y|x<-b,y<-e]|e<-f]([]:c%f)
```
[Answer]
# Mathematica, 116 bytes
```
#<>""&/@Select[Characters@"*([)]"~Tuples~#,(#/."*"->Nothing//.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b})=={}&]&
```
# Explanation
```
Characters@"*([)]"
```
Find the characters of the string `"*([)]"`, giving the `List` `{"*", "(", "[", ")", "]"}`.
```
... ~Tuples~#
```
Find the tuples of the above list with length `n`.
```
(#/."*"->Nothing//.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b})=={}&
```
Unnamed Boolean function to find whether the tuple is balanced:
```
#/."*"->Nothing
```
Delete all `"*"` in the input.
```
... //.{a___,"(",")",b___}|{a___,"[","]",b___}:>{a,b}
```
Repeatedly delete all consecutive occurrences of `"("` and `")"` or `"["` and `"]"` until the input does not change.
```
... =={}
```
Check whether the result is an empty `List`.
```
Select[ ... , ... ]
```
Find the tuples that give `True` when the Boolean function is applied.
```
#<>""&/@
```
Convert each `List` of characters into `String`s.
[Answer]
# Python 2, 128 bytes
```
n=input()
for i in range(5**n):
 try:s=','.join('  "00([*])00"  '[i/5**j%5::5]for j in range(n));eval(s);print s[1::4]
 except:1
```
Screw recursive regexes – we’re using Python’s parser! In order to verify that, for example, `*(**[])*` is a brace-string, we do the following:
1. Make a string like `"*", (0,"*","*", [0,0] ,0) ,"*"`, where every second character of four is a character from the brace-strings, and the remaining characters are *glue* to make this a potential Python expression.
2. `eval` it.
3. If that doesn’t throw an error, print `s[1::4]` (the brace-string characters).
The *glue* characters are picked so that the string I make is a valid Python expression if and only if taking every second character out of four yields a valid brace-string.
[Answer]
# Jelly, 29 bytes
-3 bytes thanks to @JonathanAllan
*Please*, alert me if there are any problems/bugs/errors or bytes I can knock off!
```
“[(*)]”ṗµḟ”*œṣ⁾()Fœṣ⁾[]FµÐLÐḟ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5xoDS3N2EcNcx/unH5o68Md84FMraOTH@5c/Khxn4amG4wZHet2aOvhCT6HJwDVcB1ud////78xAA)
The previous solution(s) I had:
```
“[(*)]”ṗµḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€Tị
“[(*)]”ṗµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€Tị
“[(*)]”ṗµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị
“[(*)]”x⁸ṗ⁸Qµ¹ḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị
“[(*)]”x⁸ṗ⁸Qµ¹µḟ”*œṣ⁾()Fœṣ⁾[]FµÐL€Ṇ€×Jḟ0ị
“[(*)]”x⁸ṗ⁸Qµ¹µḟ”*œṣ⁾()Fœṣ⁾[]FµÐLµ€Ṇ€×Jḟ0ị
```
Explanation (My best attempt at a description):
```
Input n
“[(*)]”ṗ-All strings composed of "[(*)]" of length n
µḟ”*    -Filter out all occurences of "*"
œṣ⁾()   -Split at all occurences of "()"
F       -Flatten
œṣ⁾[]   -Split at all occurences of "[]"
F       -Flatten
µÐL     -Repeat that operation until it gives a duplicate result
Ðḟ      -Filter
```
[Answer]
# PHP, 149 bytes
```
for(;$argv[1]--;$l=$c,$c=[])foreach($l?:['']as$s)for($n=5;$n--;)$c[]=$s.'*()[]'[$n];echo join(' ',preg_grep('/^((\*|\[(?1)]|\((?1)\))(?1)?|)$/',$l));
```
Uses the good old generate all possible and then filter method. Use like:
```
php -r "for(;$argv[1]--;$l=$c,$c=[])foreach($l?:['']as$s)for($n=5;$n--;)$c[]=$s.'*()[]'[$n];echo join(' ',preg_grep('/^((\*|\[(?1)]|\((?1)\))(?1)?|)$/',$l));" 4
```
[Answer]
# Python, 134 bytes
```
from itertools import*
lambda n:[x for x in map(''.join,product('*()[]',repeat=n))if''==eval("x"+".replace('%s','')"*3%('*',(),[])*n)]
```
**[repl.it](https://repl.it/Eb1x)**
Unnamed function that returns a list of valid strings of length `n`.
Forms all length `n` tuples of the characters `*()[]`, joins them into strings using `map(''.join,...)` and filters for those that have balanced brackets by removing the "pairs" `"*"`, `"()"`, and `"[]"` in turn `n` times and checking that the result is an empty string (`n` times is overkill, especially for `"*"` but is golfier).
[Answer]
## [Retina](http://github.com/mbuettner/retina), 78 bytes
Byte count assumes ISO 8859-1 encoding.
```
.+
$*
+%1`1
*$'¶$`($'¶$`)$'¶$`[$'¶$`]
%(`^
$';
)+`(\[]|\(\)|\*)(?=.*;)|^;
A`;
```
[Try it online!](http://retina.tryitonline.net/#code=LisKJCoKKyUxYDEKKiQnwrYkYCgkJ8K2JGApJCfCtiRgWyQnwrYkYF0KJShgXgokJzsKKStgKFxbXXxcKFwpfFwqKSg_PS4qOyl8XjsKCkFgOw&input=NQ)
### Explanation
I'm generating all possible strings of length 5 and then I filter out the invalid ones.
```
.+
$*
```
This converts the input to unary, using `1` as the digit.
```
+%1`1
*$'¶$`($'¶$`)$'¶$`[$'¶$`]
```
This repeatedly (`+`) replaces the first (`1`) one in each line (`%`) in such a way that it makes five copies of the line, one for each possible character. This is done by using the prefix and suffix substitutions, `$`` and `$'` to construct the remainder of each line.
This loop stops when there are no more 1s to replace. At this point we've got all possible strings of length `N`, one on each line.
```
%(`^
$';
)+`(\[]|\(\)|\*)(?=.*;)|^;
```
These two stages are executed for each line separately (`%`). The first stage simply duplicates the line, with a `;` to separate the two copies.
The second stage is another loop (`+`), which repeatedly removes `[]`, `()` or `*` from the first copy of the string, *or* removes a semicolon at the beginning of the line (which is only possible after the string has vanished completely).
```
A`;
```
Valid strings are those that no longer have a semicolon in front of them, so we simply discard all lines (`A`) which contain a semicolon.
[Answer]
# Python 3.5, 146 bytes
```
import re;from itertools import*;lambda f:{i for i in map(''.join,permutations("[()]*"*f,f))if re.fullmatch("(\**\[\**\]\**|\**\(\**\)\**)*|\**",i)}
```
Very long compared to other answers, but the shortest one I could currently find. It is in the form of an anonymous lambda function and therefore must be called in the format
`print(<Function Name>(<Integer>))`
Outputs a Python *set* of *unordered* strings representing all possible brace-strings of the input length.
For example, assuming the above function is named `G`, invoking `G(3)` would result in the following output:
```
{'[*]', '*()', '*[]', '(*)', '***', '[]*', '()*'}
```
[Try It Online! (Ideone)](http://ideone.com/6QBiBM)
---
However, if, like me, you aren't really a fan of simplifying things using built-ins, then here is my own *original* answer *not* using *any* external libraries to find permutations, and currently standing at a whopping **~~288~~ 237 bytes**:
```
import re;D=lambda f:f and"for %s in range(%d)"%(chr(64+f),5)+D(f-1)or'';lambda g:[i for i in eval('["".join(('+''.join('"[()]*"['+chr(o)+'],'for o in range(65,65+g))+'))'+D(g)+']')if re.fullmatch("(\**\[\**\]\**|\**\(\**\)\**)*|\**",i)]
```
Again, like the competing answer, this one is in the form of a lambda function and therefore must also be called in the format
`print(<Function Name>(<Integer>))`
And outputs a Python *list* of *unsorted* strings representing all brace-strings of the input length. For example, if the lambda were to be invoked as `G(3)`, this time the output would be the following:
```
['*()', '(*)', '*[]', '[*]', '()*', '[]*', '***']
```
Also, this one is also a lot faster than my other answer, being able to find all brace-strings of length `11` in about **115 seconds**, those of length `10` in about **19 seconds**, those of length `9` in about **4 seconds**, and those of length `8` in about **0.73 seconds** on my machine, whereas my competing answer takes *much* longer than 115 seconds for an input of `6`.
[Try It Online! (Ideone)](http://ideone.com/BgBlfl)
[Answer]
# 05AB1E, 23 bytes
```
…[(*.∞sãʒ'*м„()„[]‚õ:õQ
```
Some of these features might have been implemented after the question was posted. Any suggestions are welcome!
[Try it online!](https://tio.run/##MzBNTDJM/f//UcOyaA0tvUcd84oPLz41SV3rwp5HDfM0NIFEdOyjhlmHt1od3hr4/78JAA)
# How?
```
…[(* - the string '[(*'
.∞ - intersected mirror, '[(*'=>'[(*)]'
s - swap the top two items, which moves the input to the top
ã - cartesian power
ʒ ...  - filter by this code:
  '*м      - remove all occurrences of '*'
  „()„[]‚  - the array ["()","[]"]
  õ        - the empty string ""
  :        - infinite replacement (this repeatedly removes "()", "[]", and "*" from the string
  õQ       - test equality with the empty string
```
]


[Question]
      [
Many old [**Game Boy**](https://en.wikipedia.org/wiki/Game_Boy_line) games often required string input from the user. However, there was no keyboard. This was handled by presenting the user with a "keyboard screen" like so:
[![Pokemon Ruby Keyboard](https://i.stack.imgur.com/glQuY.png)](https://i.stack.imgur.com/glQuY.png)
The 'character pointer' would begin on letter A. The user would navigate to each desired character with the [D-Pad](https://en.wikipedia.org/wiki/D-pad)'s four buttons (`UP`, `DOWN`, `LEFT` and `RIGHT`), then press `BUTTON A` to append it to the final string.
*Please note:*
* ***The grid wraps around***, so pressing `UP` whilst on letter A would take you to T.
* The 'character pointer' stays put after appending a letter
# The Challenge
The above keyboard has options to change case and is an irregular shape. So, for simplicity, in this challenge we will use the following keyboard (the bottom right is ASCII char 32, a space):
```
A B C D E F G
H I J K L M N
O P Q R S T U
V W X Y Z .
```
Typing on keyboards like this is extremely slow - so, to make this easier, your task is to write a program which tells the user the ***fastest possible way*** to type a given string. If there are multiple fastest ways, you only need to show one.
The output key should be:
* `>` for `RIGHT`
* `<` for `LEFT`
* `^` for `UP`
* `v` for `DOWN`
* `.` for `BUTTON A` (append current letter to string)
For example, when given the string `DENNIS`, the solution would look like this:
```
>>>.>.>>v..>>.>>>v.
```
# Rules / Details
* Please remember, the grid wraps around!
* You may submit a full program or a function, as long as it takes the initial string and produces a solution string. Whitespace / trailing newlines are irrelevant as long as the output is correct.
* You can assume input will only consist of characters typable on the specified keyboard, but it may be empty.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins. Standard code-golf loopholes apply.
# Test Cases
*There are usually multiple solutions of the same length. For each test case, I've included the optimum length, and an example. You don't need to print the length in your answer, just the solution.*
```
FLP.TKC  ->  25 steps:  <<.<v.<<<v.<<<v.^.<<^.<^.
MOYLEX   ->  23 steps:  <<v.>>v.>>>v.>^^.^.<<^.
FEERSUM  ->  18 steps:  <<.<..<vv.>.>>.<^.
MEGO     ->  14 steps:  <<v.<^.>>.>vv.
A CAT    ->  17 steps:  .<^.>>>v.<<.<<vv.
BOB      ->  10 steps:  >.<vv.>^^.
(space)  ->  3 steps:   <^.
(empty)  ->  0 steps:   (empty)
```
You can view my testcase generator [on repl.it](https://repl.it/E304) - please notify me if there are any bugs.
Thank you everyone for the submissions! User ngn is currently the winner with 61 bytes, but if anyone can find a shorter solution, the little green tick can be moved ;)

[Answer]
## JavaScript (ES6), 147 bytes
```
s=>s.replace(/./g,c=>(q=p,p="AHOVBIPWCJQXDKRYELSZFMY.GNU ".indexOf(c),"<<<>>>".substring(3,((p>>2)+10-(q>>2))%7)+["","v","vv","^"][p-q&3]+"."),p=0)
```
An interesting behaviour of `substring` is that it exchanges the arguments if the second is less than the first. This means that if I calculate the optimal number of left/right presses as a number between -3 and 3, I can add 3, and take the substring of `<<<>>>` starting at 3 and I will get the correct number of arrows. Meanwhile the down/up presses are simply handled by looking up an array using a bitwise and of the difference in rows with 3; this way is slightly shorter as there are fewer array elements.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 61 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
[`4 7∘{∊'.',⍨⍉↑b⍴¨¨'^v' '<>'⌷¨⍨⊂¨a>b←a⌊⍺-a←⍺|↓2-/0,⍺⊤⍵⍳⍨⎕a,'.'}`](http://tryapl.org/?a=%u2395io%u21900%20%u22C4%204%207%u2218%7B%u220A%27.%27%2C%u2368%u2349%u2191b%u2374%A8%A8%27%5Ev%27%20%27%3C%3E%27%u2337%A8%u2368%u2282%A8a%3Eb%u2190a%u230A%u237A-a%u2190%u237A%7C%u21932-/0%2C%u237A%u22A4%u2375%u2373%u2368%u2395a%2C%27.%27%7D%20%A8%20%27FLP.TKC%27%20%27MOYLEX%27%20%27FEERSUM%27%20%27MEGO%27%20%27A%20CAT%27%20%27BOB%27%20%27%27&run)
assumes `⎕IO←0`
`⎕a,'.'` the alphabet followed by a full stop
`⍵⍳⍨` find the argument's chars there as indices 0..26 (`' '` and all others will be 27)
`⍺⊤` encode in base 7 (note the left arg `⍺` is bound to `4 7`), get a 2×n matrix
`0,` prepend zeros to the left
`2-/` differences between adjacent columns
`↓` split the matrix into a pair of vectors
`a←⍺|` take them modulo 4 and 7 respectively, assign to `a`
`b←a⌊⍺-a` make `b` the smaller of `a` and its modular inverse
`'^v' '<>'⌷¨⍨⊂¨a>b` choose `^` or `v` for the first vector and `<` or `>` for the second, based on where `a` differs from `b`
`b⍴¨¨` repeat each of those `b` times
`⍉↑` mix the two vectors into a single matrix and transpose it, get an n×2 matrix
`'.',⍨` append `.`-s on the right
`∊` flatten
[Answer]
# Ruby, 107 bytes
```
->s{c=0
s.tr(". ","[\\").bytes{|b|b-=65
print ["","^","^^","v"][c/7-b/7],(d=(c-c=b)%7)>3??>*(7-d):?<*d,?.}}
```
**Ungolfed in test program**
```
f=->s{                                 #Input in s.
  c=0                                  #Set current position of pointer to 0.
  s.tr(". ","[\\").                    #Change . and space to the characters after Z [\
  bytes{|b|                            #For each byte b,
    b-=65                              #subtract 65 so A->0 B->1 etc.
    print ["","^","^^","v"][c/7-b/7],  #Print the necessary string to move vertically.
    (d=(c-c=b)%7)>3?                   #Calculate the horizontal difference c-b (mod 7) and set c to b ready for next byte.
       ?>*(7-d):?<*d,                  #If d>3 print an appropriate number of >, else an appropriate number of <.
    ?.                                 #Print . to finish the processing of this byte.
  }
}
#call like this and print a newline after each testcase
f["FLP.TKC"];puts
f["MOYLEX"];puts
f["FEERSUM"];puts
f["MEGO"];puts
f["A CAT"];puts
f["BOB"];puts
```
[Answer]
**Mathematica, 193 bytes**
**Golf**
```
StringJoin@@(StringTake[">>><<<",Mod[#〚2〛,7,-3]]<>StringTake["vv^",Mod[#〚1〛,4,-1]]<>"."&/@Differences[FirstPosition[Partition[ToUpperCase@Alphabet[]~Join~{"."," "},7],#]&/@Characters["A"<>#]])&
```
**Readable**
```
In[1]:= characters = ToUpperCase@Alphabet[]~Join~{".", " "}
Out[1]= {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ".", " "}
In[2]:= keyboard = Partition[characters, 7]
Out[2]= {{"A", "B", "C", "D", "E", "F", "G"}, {"H", "I", "J", "K", "L", "M", "N"}, {"O", "P", "Q", "R", "S", "T", "U"}, {"V", "W", "X", "Y", "Z", ".", " "}}
In[3]:= characterPosition[char_] := FirstPosition[keyboard, char]
In[4]:= xToString[x_] := StringTake[">>><<<", Mod[x, 7, -3]]
In[5]:= yToString[y_] := StringTake["vv^", Mod[y, 4, -1]]
In[6]:= xyToString[{y_, x_}] := xToString[x] <> yToString[y] <> "."
In[7]:= instructionsList[input_] := xyToString /@ Differences[characterPosition /@ Characters["A" <> input]]
In[8]:= instructions[input_] := StringJoin @@ instructionsList[input]
In[9]:= instructions["DENNIS"]
Out[9]= ">>>.>.>>v..>>.>>>v."
```
[Answer]
## Python 2, 298 bytes
This is longer than it should be, but...
```
def l(c):i="ABCDEFGHIJKLMNOPQRSTUVWXYZ. ".index(c);return[i%7,i/7]
def d(f,t,a=abs):
 v,h=l(t)[1]-l(f)[1],l(t)[0]-l(f)[0]
 if a(h)>3:h=h-7*h/a(h)
 if a(v)>2:v=v-4*v/a(v)
 return'^v'[v>0]*a(v)+'<>'[h>0]*a(h)
s="A"+input()
print''.join([d(p[0],p[1])+'.'for p in[s[n:n+2]for n in range(len(s))][:-1]])
```
Any help would be greatly appreciated!
Takes input in quotation marks.
`l` returns the location of a character in the keyboard.
The two `if` statements in the middle of `d` are for checking if it would be optimal to 'wrap' around the keyboard.
The input, `s` has `"A"` prepended to it because the initial position of the cursor is `A`.
We loop through the string in pairs, discarding the last one (which is not a pair: `[:-1]`), finding the minimum distance between the two halves of the pair.
Thanks to Flp.Tkc for telling me that I can do `a=abs` instead of saying `abs` every time!
[Answer]
# Java 8, 1045 bytes
## Golf
```
staticchar[][]a={{'A','B','C','D','E','F','G'},{'H','I','J','K','L','M','N'},{'O','P','Q','R','S','T','U'},{'V','W','X','Y','Z','.',''}};staticintm=Integer.MAX_VALUE;staticStringn="";staticboolean[][]c(boolean[][]a){boolean[][]r=newboolean[4][];for(inti=0;i<4;i)r[i]=a[i].clone();returnr;}staticvoidg(inti,intj,boolean[][]v,chard,Stringp){v[i][j]=true;if(a[i][j]==d&&p.length()<m){m=p.length();n=p;}if(i-1<0){if(!v[3][j])g(3,j,c(v),d,p"^");}elseif(!v[i-1][j])g(i-1,j,c(v),d,p"^");if(i1>3){if(!v[0][j])g(0,j,c(v),d,p"v");}elseif(!v[i1][j])g(i1,j,c(v),d,p"v");if(j-1<0){if(!v[i][6])g(i,6,c(v),d,p"<");}elseif(!v[i][j-1])g(i,j-1,c(v),d,p"<");if(j1>6){if(!v[i][0])g(i,0,c(v),d,p">");}elseif(!v[i][j1])g(i,j1,c(v),d,p">");}publicstaticvoidmain(String[]args){boolean[][]v=newboolean[4][7];Scannerx=newScanner(System.in);Strings=x.next();Stringpath="";intp=0;intq=0;for(inti=0;i<s.length();i){chart=s.charAt(i);g(p,q,c(v),t,"");path=n".";n="";m=Integer.MAX_VALUE;for(intj=0;j<4;j){for(intk=0;k<7;k){if(a[j][k]==t){p=j;q=k;}}}}System.out.println(path);}
```
## Readable
```
static char[][] a = {
        {'A','B','C','D','E','F','G'},
        {'H','I','J','K','L','M','N'},
        {'O','P','Q','R','S','T','U'},
        {'V','W','X','Y','Z','.',' '}
};
static int m = Integer.MAX_VALUE;
static String n="";
static boolean[][] c(boolean[][] a){
    boolean [][] r = new boolean[4][];
    for(int i = 0; i < 4; i++)
        r[i] = a[i].clone();
    return r;
}
static void g(int i, int j,boolean[][] v,char d,String p) {
    v[i][j] = true;
    if (a[i][j]==d && p.length()<m){
        m=p.length();
        n=p;
    }
    if (i-1<0) {
        if(!v[3][j])
            g(3, j, c(v), d, p + "^");
    }
    else if (!v[i-1][j])
        g(i-1, j, c(v), d, p + "^");
    if (i+1>3) {
        if(!v[0][j])
            g(0, j, c(v), d, p + "v");
    }
    else if(!v[i+1][j])
        g(i+1, j, c(v), d, p + "v");
    if (j-1<0) {
        if(!v[i][6])
            g(i, 6, c(v), d, p + "<");
    }
    else if (!v[i][j-1])
        g(i, j-1, c(v), d, p + "<");
    if (j+1>6) {
        if (!v[i][0])
            g(i, 0, c(v), d, p + ">");
    }
    else if (!v[i][j+1])
        g(i, j+1, c(v), d, p + ">");
}
public static void main(String[] args) {
    boolean[][] v = new boolean[4][7];
    Scanner x = new Scanner(System.in);
    String s = x.next();
    String path="";
    int p=0;
    int q=0;
    for(int i=0;i<s.length();i++){
        char t=s.charAt(i);
        g(p,q,c(v),t,"");
        path+=n+".";
        n="";
        m=Integer.MAX_VALUE;
        for(int j=0;j<4;j++){
            for(int k=0;k<7;k++){
                if(a[j][k]==t) {
                    p=j;
                    q=k;
                }
            }
        }
    }
    System.out.println(path);
}
```
## Explanation
The solution is a direct approach: poorly optimized brute force. The method `g(...)` is a basic depth first search going through each permutation (up, down, left, right). With some slight modifications in ordering for the test cases I get the output:
```
<<.v<.v<<<.v<<<.^.^<<.^<.
v<<.v>>.v>>>.^^>.^.^<<.
<<.<..^^<.>.>>.^<.
v<<.^<.>>.^^>.
.^<.v>>>.<<.^^<<.
>.^^<.^^>.
^<.
// new line for the last
```
]


[Question]
      [
## Problem
The goal is as the title says to find the \$n\$th prime such that \$\text{the prime}-1\$ is divisible by \$n\$.
## Explanation
Here is an example so you understand the question, *this is not necessarily the way it ought to be solved. It merely as a way to explain the question*
given \$3\$ as an input we would first look at all the primes
```
 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 ...
```
Then we select the primes such that \$\text{the prime}-1\$ is divisible by \$n\$ (3 in this case)
```
 7 13 19 31 37 43 61 67 73 79 97 103 107 109 127 ...
```
We then select the \$n\$th term in this sequence
We would output \$19\$ for an input of \$3\$
## Note
We can also think of this as the \$n\$th prime in the sequence \$\{1, n + 1, 2n + 1, 3n + 1 ...kn + 1\}\$ where \$k\$ is any natural number
## Test Cases
```
  1 --> 2
  2 --> 5
  3 --> 19
  4 --> 29
100 --> 39301
123 --> 102337
```

[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
05AB1E uses [CP-1252](http://www.cp1252.com) encoding.
Saved a byte thanks to *Osable*
```
µN¹*>Dp½
```
[Try it online!](http://05ab1e.tryitonline.net/#code=wrVOwrkqPkRwwr0&input=MTIz)
**Explanation**
```
µ          # for N in [1 ...] loop until counter == input
 N¹*>      # N*input+1 (generate multiples of input and increment)
     D     # duplicate
      p½   # if prime, increase counter
           # implicitly output last prime
```
[Answer]
# Python 2, 58 bytes
```
n=N=input();m=k=1
while N:m*=k*k;k+=1;N-=m%k>~-k%n
print k
```
[Answer]
# Mathematica, 48 bytes
```
Select[Array[Prime,(n=#)^3],Mod[#-1,n]==0&][[n]]&
```
Unnamed function taking a single argument, which it names `n`. Generates a list of the first `n^3` primes, selects the ones that are congruent to 1 modulo `n`, then takes the `n`th element of the result. It runs in several seconds on the input 123.
It's not currently known if there's always even a single prime, among the first `n^3` primes, that is congruent to 1 modulo `n`, much less `n` of them. However, the algorithm can be proved correct (at least for large `n`) under the assumption of the [generalized Riemann hypothesis](https://en.wikipedia.org/wiki/Generalized_Riemann_hypothesis)!
[Answer]
## Haskell, ~~59~~ 47 bytes
```
f n=[p|p<-[1,n+1..],all((<2).gcd p)[2..p-1]]!!n
```
Usage example: `f 4` -> `29`.
How it works:
```
[p|p<-[1,n+1..]                     ]    -- make a list of all multiples of n+1
                                         -- (including 1, as indexing is 0-based)
           ,all((<2).gcd p)[2..p-1]      -- and keep the primes
                              !!n       -- take the nth element
```
Edit: Thanks @Damien for 12 bytes by removing the divisibility test and only looking at multiples in the first place.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘ÆP>%ð#Ṫ‘
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCYw4ZQPiXDsCPhuarigJg&input=&args=MTIz)
### How it works
```
‘ÆP>%ð#Ṫ‘  Main link. Argument: n
     ð#    Call the dyadic chain to the left with right argument n and left
           argument k = n, n+1, n+2, ... until n of them return 1.
‘          Increment; yield k+1.
 ÆP        Test k+1 for primality, yielding 1 or 0.
    %      Compute k%n.
   >       Compare the results to both sides, yielding 1 if and only if k+1 is
           prime and k is divisible by n.
       Ṫ   Tail; extract the last k.
        ‘  Increment; yield k+1.
```
[Answer]
# Java 7, 106 bytes
```
int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}}
```
**Ungolfed:**
```
int c(int n){
  for(int z = 1, i = 2, j, x; ; i++){
    x = i;
    for(j = 2; j < x; x = x % j++ < 1
                           ? 0
                           : x);
    if(x > 1 & (i-1) % n < 1 && z++ == n){
      return i;
    }
  }
}
```
**Test code:**
[Try it here](https://ideone.com/m4ilQc) (last test case results in a *Time limit exceeded* on ideone)
```
class M{
  static int c(int n){for(int z=1,i=2,j,x;;i++){x=i;for(j=2;j<x;x=x%j++<1?0:x);if(x>1&(i-1)%n<1&&z++==n)return i;}}

  public static void main(String[] a){
    System.out.println(c(1));
    System.out.println(c(2));
    System.out.println(c(3));
    System.out.println(c(4));
    System.out.println(c(100));
    System.out.println(c(123));
  }
}
```
**Output:**
```
2
5
19
29
39301
102337
```
[Answer]
**Nasm 679 bytes (Instruction Intel 386 cpu 120 bytes)**
```
isPrime1:
push ebp
mov ebp,dword[esp+ 8]
mov ecx,2
mov eax,ebp
cmp ebp,1
ja .1
.n: xor eax,eax
jmp short .z
.1: xor edx,edx
cmp ecx,eax
jae .3
div ecx
or edx,edx
jz .n
mov ecx,3
mov eax,ebp
.2: xor edx,edx
cmp ecx,eax
jae .3
mov eax,ebp
div ecx
or edx,edx
jz .n
inc ecx
inc ecx
jmp short .2
.3: xor eax,eax
inc eax
.z: pop   ebp
ret 4
Np:
push esi
push edi
mov esi,dword[esp+ 12]
xor edi,edi
or esi,esi
ja .0
.e: xor eax,eax
jmp short .z
.0: inc esi
jz .e
push esi
call isPrime1
add edi,eax
dec esi
cmp edi,dword[esp+ 12]
jae .1
add esi,dword[esp+ 12]
jc .e
jmp short .0
.1: mov eax,esi
inc eax
.z: pop edi
pop esi
ret 4
```
this is ungolfed one and the results
```
;0k,4ra,8Pp
isPrime1:
          push    ebp
          mov     ebp,  dword[esp+  8]
          mov     ecx,  2
          mov     eax,  ebp
          cmp     ebp,  1
          ja      .1
.n:       xor     eax,  eax
          jmp     short  .z
.1:       xor     edx,  edx
          cmp     ecx,  eax
          jae     .3
          div     ecx
          or      edx,  edx
          jz      .n
          mov     ecx,  3
          mov     eax,  ebp
.2:       xor     edx,  edx
          cmp     ecx,  eax
          jae     .3
          mov     eax,  ebp
          div     ecx
          or      edx,  edx
          jz      .n
          inc     ecx
          inc     ecx
          jmp     short  .2
.3:       xor     eax,  eax
          inc     eax
.z:
          pop     ebp
          ret     4
; {1, n+1, 2n+1, 3n+1 }
; argomento w, return il w-esimo primo nella successione di sopra
;0j,4i,8ra,12P
Np:
          push    esi
          push    edi
          mov     esi,  dword[esp+  12]
          xor     edi,  edi
          or      esi,  esi
          ja      .0
.e:       xor     eax,  eax
          jmp     short  .z
.0:       inc     esi
          jz      .e
          push    esi
          call    isPrime1
          add     edi,  eax
          dec     esi
          cmp     edi,  dword[esp+  12]
          jae     .1
          add     esi,  dword[esp+  12]
          jc      .e
          jmp     short  .0
.1:       mov     eax,  esi
          inc     eax
.z:
          pop     edi
          pop     esi
          ret     4
00000975  55                push ebp
00000976  8B6C2408          mov ebp,[esp+0x8]
0000097A  B902000000        mov ecx,0x2
0000097F  89E8              mov eax,ebp
00000981  81FD01000000      cmp ebp,0x1
00000987  7704              ja 0x98d
00000989  31C0              xor eax,eax
0000098B  EB28              jmp short 0x9b5
0000098D  31D2              xor edx,edx
0000098F  39C1              cmp ecx,eax
00000991  731F              jnc 0x9b2
00000993  F7F1              div ecx
00000995  09D2              or edx,edx
00000997  74F0              jz 0x989
00000999  B903000000        mov ecx,0x3
0000099E  89E8              mov eax,ebp
000009A0  31D2              xor edx,edx
000009A2  39C1              cmp ecx,eax
000009A4  730C              jnc 0x9b2
000009A6  89E8              mov eax,ebp
000009A8  F7F1              div ecx
000009AA  09D2              or edx,edx
000009AC  74DB              jz 0x989
000009AE  41                inc ecx
000009AF  41                inc ecx
000009B0  EBEE              jmp short 0x9a0
000009B2  31C0              xor eax,eax
000009B4  40                inc eax
000009B5  5D                pop ebp
000009B6  C20400            ret 0x4
68
000009B9  56                push esi
000009BA  57                push edi
000009BB  8B74240C          mov esi,[esp+0xc]
000009BF  31FF              xor edi,edi
000009C1  09F6              or esi,esi
000009C3  7704              ja 0x9c9
000009C5  31C0              xor eax,eax
000009C7  EB1D              jmp short 0x9e6
000009C9  46                inc esi
000009CA  74F9              jz 0x9c5
000009CC  56                push esi
000009CD  E8A3FFFFFF        call 0x975
000009D2  01C7              add edi,eax
000009D4  4E                dec esi
000009D5  3B7C240C          cmp edi,[esp+0xc]
000009D9  7308              jnc 0x9e3
000009DB  0374240C          add esi,[esp+0xc]
000009DF  72E4              jc 0x9c5
000009E1  EBE6              jmp short 0x9c9
000009E3  89F0              mov eax,esi
000009E5  40                inc eax
000009E6  5F                pop edi
000009E7  5E                pop esi
000009E8  C20400            ret 0x4
000009EB  90                nop
120
[0, 0] [1, 2] [2, 5] [3, 19] [4, 29] [5, 71] [6, 43] [7, 211] [8, 193] [9, 271] [1
0, 191] [11, 661] [12, 277] [13, 937] [14, 463] [15, 691] [16, 769] [17, 1531] [18
, 613] [19, 2357] [20, 1021] [21, 1723] [22, 1409] [23, 3313] [24, 1609] [25, 3701
] [26, 2029] [27, 3187] [28, 2437] [29, 6961] [30, 1741] [31, 7193] [32, 3617] [33
, 4951] [34, 3877] [35, 7001] [36, 3169] [37, 10657] [38, 6271] [39, 7879] [40, 55
21] [41, 13613] [42, 3823] [43, 15137] [44, 7349] [45, 9091] [46, 7499] [47, 18049
] [48, 6529] [49, 18229] [50, 7151] [51, 13159] [52, 10141] [53, 26501] [54, 7669]
 [55, 19801] [56, 11593] [57, 18127] [58, 13109] [59, 32569] [60, 8221] [61, 34649
] [62, 17981] [63, 21799] [64, 16001] [65, 28081] [66, 10429] [67, 39799] [68, 193
81] [69, 29947] [70, 14771] [71, 47713] [72, 16417] [73, 51539] [74, 25013] [75, 2
9101] [76, 26449] [77, 50051] [78, 16927] [79, 54037] [80, 23761] [81, 41149] [82,
 31489] [83, 68891] [84, 19237] [85, 51341] [86, 33713] [87, 45589] [88, 34057] [8
9, 84551] [90, 19531] [91, 64793] [92, 42689] [93, 54499] [94, 41737] [95, 76001]
[96, 27457] [97, 97583] [98, 40867] [99, 66529] [100, 39301] [101, 110899] [102, 2
9989] [103, 116803] [104, 49297] [105, 51871] [106, 56711] [107, 126047] [108, 385
57] [109, 133853] [110, 42901] [111, 76369] [112, 53089] [113, 142607] [114, 40129
] [115, 109481] [116, 63337] [117, 83071] [118, 67733] [119, 112337] [120, 41281]
[121, 152219] [122, 70639] [123, 102337]
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 13 bytes
Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=O-KVl2BQROKVnEAlWWDilZNOUA&input=MTIz)
```
;╗`PD╜@%Y`╓NP
```
**Ungolfing**
```
         Implicit input n.
;╗       Save a copy of n to register 0.
`...`╓   Push first n values where f(x) is truthy, starting with f(0).
  PD       Get the x-th prime - 1.
  ╜@%      Push (x_p - 1) % n.
  Y        If x_p-1 is divisible by n, return 1. Else, return 0.
NP       Get the n-th prime where n_p-1 is divisible by n.
         Implicit return.
```
[Answer]
# Common Lisp, 162 bytes
```
(defun s(n)(do((b 2(loop for a from(1+ b)when(loop for f from 2 to(1- a)never(=(mod a f)0))return a))(a 0)(d))((= a n)d)(when(=(mod(1- b)n)0)(incf a)(setf d b))))
```
Usage:
```
* (s 100)
39301
```
Ungolfed:
```
(defun prime-search (n)
  (do ((prime 2 (loop for next from (1+ prime) when
                 (loop for factor from 2 to (1- next) never
                      (= (mod next factor) 0)) return next))
       (count 0) (works))
      ((= count n) works)
    (when (= (mod (1- prime) n) 0)
      (incf count)
      (setf works prime))))
```
Some of those `loop` constructs can probably be shortened into `do` loops, but this is what I've got for now.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 12 bytes
```
1i:"`_YqtqG\
```
[Try it online!](http://matl.tryitonline.net/#code=MWk6ImBfWXF0cUdc&input=NA)
(For input `123` it times out in the online compiler, but it works offline.)
### Explanation
```
1          % Push 1
i:         % Input n and push [1 2 ... n]
"          % For each (that is, do the following n times)
  `        %   Do...while
    _Yq    %     Next prime
    tq     %     Duplicate, subtract 1
    G      %     Push n again
    \      %     Modulo
           %   End (implicit). Exit loop if top of stack is 0; else next iteration
           % End (implicit)
           % Display (implicit)
```
[Answer]
# Perl, ~~77~~ 76 + 1 = 77 bytes
```
for($p=2;@a<$_;$p++){push@a,$p if(1 x$p)!~/^(11+?)\1+$/&&($p%$_<2)}say$a[-1]
```
Uses the prime-testing regex to determine if `$p` is prime, and makes sure that it's congruent to 1 mod the input (the only nonnegative integers below 2 are 0 and 1, but it can't be 0 if it's prime, so it has to be 1. saves 1 byte over `==1`).
[Answer]
**Mathematica 44 Bytes**
```
   Pick[x=Table[i #+1,{i,# #}],PrimeQ/@x][[#]]&
```
Very fast. Uses the idea from the "Note"
```
% /@ {1, 2, 3, 4, 100, 123} // Timing
```
Output
```
{0.0156001, {2, 5, 19, 29, 39301, 102337}}
```
[Answer]
# [Perl 6](https://perl6.org), ~~46 39~~ 37 bytes
```
->\n{(2..*).grep({.is-prime&&($_-1)%%n})[n-1]}
```
```
->\n{(1,n+1...*).grep(*.is-prime)[n-1]}
```
```
{(1,$_+1...*).grep(*.is-prime)[$_-1]}
```
[Answer]
# Java 8, 84 bytes
### Golfed
```
(n)->{for(int s=n,i=1;;i+=n)for(int j=2;i%j>0&j<i;)if(++j==i&&--s<1)return n>1?i:2;}
```
### Ungolfed
```
(n) -> {
for (int s = n,      // Counting down to find our nth prime.
    i = 1;           // Counting up for each multiple of n, plus 1.
    ;                // No end condition specified for outer for loop.
    i += n)          // Add n to i every iteration.
for (int j = 2;      // Inner for loop for naive primality check.
     i % j > 0)      // Keep looping while i is not divisible by j
                     // (and implicitly while j is less than i).
     if(++j==i       // Increment j. If j has reached i, we've found a prime
     &&              // Short-circutting logical AND, so that we only decrement s if a prime is found
     --s < 1)        // If we've found our nth prime...
     return n>1?i:2; // Return it. Or 2 if n=1, because otherwise it returns 3.
}
```
## Explanation
Solution inspired by several other answers. Function is a lambda that expects a single int.
The `n>1?i:2` is a cheap hack because I couldn't figure out a better way to consider the case of n=1.
Also, this solution times out on Ideone, but has been tested for all test cases. It times out because in order to shave a couple bytes off, I took out the explicit `j<i` check in the inner loop. It's mostly implied by `i%j>0`... except in the case of `i=1` and `j=2` (the very first iteration), in which case the loop runs until j overflows (I'm assuming). Then it works fine for all iterations afterwards.
For a version that doesn't time out that's a couple bytes longer, [see here!](http://ideone.com/whXnHl)
[Answer]
## Racket 109 bytes
```
(let p((j 2)(k 0))(cond[(= 0(modulo(- j 1)n))(if(= k(- n 1))j(p(next-prime j)(+ 1 k)))][(p(next-prime j)k)]))
```
Ungolfed:
```
(define (f n)
  (let loop ((j 2)
             (k 0))
    (cond
      [(= 0 (modulo (sub1 j) n))
       (if (= k (sub1 n))
           j
           (loop (next-prime j) (add1 k)))]
      [else (loop (next-prime j) k)]  )))
```
Testing:
```
(f 1)
(f 2)
(f 3)
(f 4)
(f 100)
(f 123)
```
Output:
```
2
5
19
29
39301
102337
```
[Answer]
## Ruby 64 bytes
```
require'prime';f=->(n){t=n;Prime.find{|x|(x-1)%n==0&&(t-=1)==0}}
```
Called like this:
```
f.call(100)
# 39301
```
Also, this command-line app works:
```
n=t=ARGV[0].to_i;p Prime.find{|x|(x-1)%n==0&&(t-=1)==0}
```
called like this
```
ruby -rprime find_golf_prime.rb 100
```
but I am not so sure how to count the characters. I think I can ignore the language name, but have to include the `-rprime` and space before the script name, so that is slightly shorter, at 63 . . .
[Answer]
## R, 72 bytes
```
n=scan();q=j=0;while(q<n){j=j+1;q=q+1*(numbers::isPrime(j)&!(j-1)%%n)};j
```
Terribly inefficient and slow but it works. It reads input from stdin and then uses the `isPrime` function from the `numbers` package to find the primes. The rest is just checking whether `prime - 1` is divisible by `n`.
[Answer]
## JavaScript (ES6), 65 bytes
```
f=(n,i=n,j=1)=>i?f(n,i-!/^(..+?)\1+$/.test('.'.repeat(j+=n)),j):j
```
Uses the regexp primality tester, since it's a) 8 bytes shorter and b) less recursive than my pure recursive approach.
[Answer]
**Axiom 64 bytes**
```
f(n)==(n<0 or n>150=>0;[i*n+1 for i in 0..2000|prime?(i*n+1)].n)
```
does someone know how to write above using Axiom streams?... some example
```
-> f(i)  for i in 1..150
   Compiling function f with type PositiveInteger -> NonNegativeInteger
   [2, 5, 19, 29, 71, 43, 211, 193, 271, 191, 661, 277, 937, 463, 691, 769,
    1531, 613, 2357, 1021, 1723, 1409, 3313, 1609, 3701, 2029, 3187, 2437,
    6961, 1741, 7193, 3617, 4951, 3877, 7001, 3169, 10657, 6271, 7879, 5521,
    13613, 3823, 15137, 7349, 9091, 7499, 18049, 6529, 18229, 7151, 13159,
    10141, 26501, 7669, 19801, 11593, 18127, 13109, 32569, 8221, 34649, 17981,
    21799, 16001, 28081, 10429, 39799, 19381, 29947, 14771, 47713, 16417,
    51539, 25013, 29101, 26449, 50051, 16927, 54037, 23761, 41149, 31489,
    68891, 19237, 51341, 33713, 45589, 34057, 84551, 19531, 64793, 42689,
    54499, 41737, 76001, 27457, 97583, 40867, 66529, 39301, 110899, 29989,
    116803, 49297, 51871, 56711, 126047, 38557, 133853, 42901, 76369, 53089,
    142607, 40129, 109481, 63337, 83071, 67733, 112337, 41281, 152219, 70639,
    102337, 75641, 126001, 42589, 176531, 85121, 107071, 62791, 187069, 55837,
    152419, 94873, 104761, 92753, 203857, 62929, 226571, 72661, 144103, 99401,
    193051, 69697, 168781, 112859, 133183, 111149, 250619, 60601]
```
##  Type: Tuple NonNegativeInteger
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes
```
!⁰fṗ¡+⁰1
```
[Try it online!](https://tio.run/##yygtzv7/X/FR44a0hzunH1qoDWQZ/v//39DAAAA "Husk – Try It Online")
```
!⁰         # get the input-th element of
  fṗ       # the elements that are primes among
    ¡      # the list formed by repeatedly
     +⁰    # adding the input to the last result
       1   # starting with 1.
```
]


[Question]
      [
Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.
## Examples
```
"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"
```
## Rules
* The strings will only contain ASCII chars (32-126).
* The strings will always be the same length, and will never be empty.
* You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. `a1\nb2\nc3` for `"abc", "123"` is invalid).
* The output may be **in either order** (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes for each language wins.**

[Answer]
# Java, 68 bytes
```
(a,b)->{for(int i=a.length;--i>0;){char t=a[--i];a[i]=b[i];b[i]=t;}}
```
## Ungolfed and testing
```
import java.util.Arrays;
import java.util.Collection;
import java.util.function.BiConsumer;
public class Main {
  static BiConsumer<char[], char[]> func = (left, right) -> {
      for (int i = left.length; --i > 0;) {
        char temp = left[--i];
        left[i] = right[i];
        right[i] = temp;
      }
    };
  public static void main(String[] args) {
    test("Hello,","world!", "Hollo!", "werld,");
    test("code", "golf", "codf", "gole");
    test("happy", "angry", "hnpry", "aagpy");
  }
  private static void test(String left, String right, String x, String y) {
    char[] leftChars = left.toCharArray();
    char[] rightChars = right.toCharArray();
    func.accept(leftChars, rightChars);
    Collection mixed = Arrays.asList(new String(leftChars), new String(rightChars));
    if (mixed.containsAll(Arrays.asList(x, y))) {
      System.out.println("OK");
    } else {
      System.out.printf("NOK: %s, %s -> %s%n", left, right, mixed);
    }
  }
}
```
[Answer]
## APL, 12
```
{↓(⍳⍴⊃⍵)⊖↑⍵}
```
Explanation: {...} defines a function, ⍵ is the right argument.
The take (↑) creates a matrix out of the two strings, then rotates each column (⊖) n times, where n is the part in parenthesis (⍳⍴⊃⍵). That's defined as the iota of the length of the first argument. (Ex: length=5 ==> 1 2 3 4 5).
So first column is rotated once, second twice (getting back to original positions), third column three times, etc...
Try it at [tryapl.org](http://tryapl.org/?a=%7B%u2193%28%u2373%u2374%u2283%u2375%29%u2296%u2191%u2375%7D%20%27happy%27%20%27angry%27&run)
[Answer]
# Scala, 85 bytes
```
(_:String)zip(_:String)zip(Stream from 0)map{case(t,z)=>if(z%2==0)t else t.swap}unzip
```
take an anonymous string parameter, zip it with another string parameter, zip it with an stream of natural numbers, swap every second tuple of chars and unzip to get a tuple of sequences of chars
[Answer]
# Swift 3, ~~129~~ 107 bytes
```
func c(n:inout[String],b:inout[String]){
for(j,c)in n.enumerated(){
if j&1<1{n[j]=b[j];b[j]=c}}
print(n,b)}
```
**Original**
The function receives two arrays of strings as parameters assuming both have same length, as follows:
```
c(n:["c", "o", "d", "e"],b:["g", "o", "l", "f"])
```
Produces following output
```
codf gole
```
**Edit 1:**
Get rid of the internal tuple and change the parameters of the function to be `inout`. Instead of string concatenation manipulate the parameters directly.
Example input:
```
var a:Array<String> = ["c", "o", "d", "e"]
var b:Array<String> = ["g", "o", "l", "f"]
c(n:&a,b:&b)
```
Ouput changed to be array of strings as in:
`["g", "o", "l", "e"] ["c", "o", "d", "f"]`
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
Tz*İ_ze
```
[Try it online!](https://tio.run/##yygtzv7/P6RK68iG@KrU////e6Tm5OTr/A/PL8pJUQQA "Husk – Try It Online")
Outputs are reversed.
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 11 bytes
```
ir>ir[<o>o]
```
[Try it online!](https://tio.run/##y6n8/z@zyC6zKNom3y4/9v//5PyUVK70/Jw0AA "Ly – Try It Online")
This takes the two strings on separate input lines, and outputs the interlaced strings concatenated together. At a high level... It reads the two strings onto separate stacks, then just loops printing the top the each stack.
```
ir          - read first string onto the stack, reverse it
  >ir       - switch to new stack, read second string and reverse it
     [    ] - loop until the stack is empty
      <o    - switch to first stack and print a char
        >o  - switch to the second stack and print a char
```
]


[Question]
      [
### Background
When I was in elementary school, we used to play a game in math class that goes as follows.
All kids sit in a big circle and take turns counting, starting from **1**.
However, the following numbers must be skipped while counting:
* Numbers that are multiples of **3**.
* Numbers that have a **3** in its decimal representation.
The first 15 numbers the kids should say are
```
1 2 4 5 7 8 10 11 14 16 17 19 20 22 25
```
Whenever somebody gets a number wrong – says a number that isn't in the sequence or skips a number that is – he's removed from the circle. This goes on until there's only one kid left.
### Task
You're bad at this game, so you decide to cheat. Write a program or a function that, given a number of the sequence, calculates the next number of the sequence.
You don't have to handle numbers that cannot be represented using your language's native numeric type, provided that your program works correctly up to input **251** and that your algorithm works for arbitrarily large inputs.
Input and output can use any convenient base.
Since you have to conceal your code, it must be as short as possible. In fact, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
### Test cases
```
  1 ->   2
  2 ->   4
 11 ->  14
 22 ->  25
 29 ->  40
251 -> 254
```

[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 10 bytes
```
<.='e3:I'*
```
[Try it online!](http://brachylog.tryitonline.net/#code=PC49J2UzOkknKg&input=Mjk&args=Wg)
### Explanation
```
(?)<.                Output > Input
    .=               Assign a value to the Output
    . 'e3            3 cannot be an element of the Output (i.e. one of its digits)
        3:I'*(.)     There is no I such that 3*I = Output
```
[Answer]
# JavaScript (ES6), 30 bytes
```
f=n=>++n%3*!/3/.test(n)?n:f(n)
```
[Answer]
# J, 24 bytes
```
3(]0&({$:)~e.&":+.0=|)>:
```
Straight-forward approach that just iterates forward from input *n* until it finds the next number that is valid by the rules.
Forms five smileys, `$:`, `:)`, `0=`, `=|`, and `>:`.
## Usage
```
   f =: 3(]0&({$:)~e.&":+.0=|)>:
   (,.f"0) 1 2 11 22 29 251
  1   2
  2   4
 11  14
 22  25
 29  40
251 254
```
## Explanation
```
3(]0&({$:)~e.&":+.0=|)>:  Input: integer n
                      >:  Increment n
3                         The constant 3
 (                   )    Operate dyadically with 3 (LHS) and n+1 (RHS)
                    |       Take (n+1) mod 3
                  0=        Test if equal to 0
             &":            Format both 3 and n+1 as a string
           e.               Test if it contains '3' in str(n+1)
                +.          Logical OR the results from those two tests
  ]                         Right identity, gets n+1
   0&(   )~                 If the result from logical OR is true
       $:                     Call recursively on n+1
      {                       Return that as the result
                            Else act as identity function and return n+1
```
[Answer]
## Python 2, 73 66 43 bytes
Thanks to xnor for telling me I was being silly by using 2 variables, and thanks to Mitch Schwartz too.
```
x=~input()
while'3'[:x%3]in`x`:x-=1
print-x
```
[Answer]
## Perl, 19 bytes
**18 bytes code + 1 for `-p`.**
```
++$_%3&&!/3/||redo
```
### Usage
```
perl -pe '++$_%3&&!/3/||redo' <<< 8
10
perl -pe '++$_%3&&!/3/||redo' <<< 11
14
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes
```
[>Ð3ås3Ö~_#
```
[Try it online!](http://05ab1e.tryitonline.net/#code=Wz7DkDPDpXMzw5Z-XyM&input=Mjk)
**Explanation**
```
               # implicit input
[              # start loop
 >             # increase current number
  Ð            # triplicate
          #    # break loop IF
         _     # logical negation of
   3å          # number has one or more 3's in it
        ~      # OR
     s3Ö       # number % 3 == 0
```
[Answer]
# Java 8, ~~57~~ ~~56~~ ~~55~~ 50 bytes
*Thanks to @Numberknot for 1 byte*
*Thanks to @Kevin Cruijssen for 5 bytes*
```
i->{for(;++i%3<1|(i+"").contains("3"););return i;}
```
This is a `Function<Integer, Integer>`
**Explanation**
Naive implementation that simply increments until it reaches an acceptable number.
**Test Class**
```
public class CodeGolf {
    public static void main(String[] args) {
        Function<Integer, Integer> countingGame = i->{for(;++i%3<1|(i+"").contains("3"););return i;};
        int val = 1;
        for (int i = 0; i < 10; i++) {
            System.out.print(val + " ");
            val = countingGame.apply(val);
        }
    }
}
```
Output of Test Class:
```
1 2 4 5 7 8 10 11 14 16
```
[Answer]
# Python 2, ~~49~~ ~~44~~ 42 bytes
```
f=lambda x:'3'[:~x%3]in`~x`and f(x+1)or-~x
```
The other Python entry beats this (edit: not any more :-D), but I posted it because I rather like its recursive approach.
Thanks to Mitch Schwarz and Erik the Golfer for helping me make this shorter.
[Answer]
# Japt, 18 bytes
```
°U%3*!Us f'3 ?U:ßU
```
[**Test it online**](http://ethproductions.github.io/japt/?v=master&code=sFUlMyohVXMgZiczID9VOt9V&input=MTE=)
I finally have a chance to use `ß` :-)
### How it works
```
                    // Implicit: U = input integer
°U%3                // Increment U, and take its modulo by 3.
     !Us f'3        // Take all matches of /3/ in the number, then take logical NOT.
                    // This returns true if the number does not contain a 3.
    *               // Multiply. Returns 0 if U%3 === 0  or the number contains a 3.
             ?U     // If this is truthy (non-zero), return U.
               :ßU  // Otherwise, return the result of running the program again on U.
                    // Implicit: output last expression
```
[Answer]
## PowerShell v2+, 46 bytes
```
for($a=$args[0]+1;$a-match3-or!($a%3)){$a++}$a
```
Takes input `$args[0]`, adds `1`, saves into `$a`, starts a `for` loop. The conditional keeps the loop going while either `$a-match3` (regex match) `-or` `$a%3` is zero (the `!` of which is `1`). The loop simply increments `$a++`. At the end of the loop, we simply place `$a` on the pipeline, and output via implicit `Write-Output` happens at program completion.
### Examples
```
PS C:\Tools\Scripts\golfing> 1,2,11,22,29,33,102,251,254|%{"$_ --> "+(.\count-without-three.ps1 $_)}
1 --> 2
2 --> 4
11 --> 14
22 --> 25
29 --> 40
33 --> 40
102 --> 104
251 --> 254
254 --> 256
```
[Answer]
# R, 46 bytes
```
n=scan()+1;while(!n%%3|grepl(3,n))n=n+1;cat(n)
```
[Answer]
# Haskell, ~~50~~ 48 bytes
```
f n=[x|x<-[n..],mod x 3>0,notElem '3'$show x]!!1
```
[Try it on Ideone.](http://ideone.com/0NRlOh) Saved 2 bytes thanks to [@Charlie Harding](https://codegolf.stackexchange.com/users/15516/charlie-harding).
Alternative: (50 bytes)
```
g=f.(+1)
f n|mod n 3<1||(elem '3'.show)n=g n|1<3=n
```
[Answer]
# [Labyrinth](http://github.com/mbuettner/labyrinth), 117 102 bytes
```
?       """""""""""_
):_3    (         0/{!@
;  %;:}_';:_3-_10 1
"  1            %;_
""""_""""""""{;;'
```
[Try it online!](http://labyrinth.tryitonline.net/#code=PyAgICAgICAiIiIiIiIiIiIiIl8KKTpfMyAgICAoICAgICAgICAgMC97IUAKOyAgJTs6fV8nOzpfMy1fMTAgMQoiICAxICAgICAgICAgICAgJTtfCiIiIiJfIiIiIiIiIiJ7Ozsn&input=Mjk5)
Labyrinth is a two-dimensional, stack-based programming language and at junctions, direction is determined by the top of the stack (positive goes right, negative goes left, zero goes straight). There are two main loops in this programs. The first mods the integer input by 3 and increments if 0. The second repeatedly checks if the last digit is 3 (by subtracting 3 and modding by 10) and then dividing by 10 to get a new last digit.
[Answer]
# Lua, 58 Bytes
```
i=...+1while(i%3==0or(i..""):find"3")do i=i+1 end print(i)
```
[Answer]
## Pyke, 13 bytes
```
Whii3%!3`i`{|
```
[Try it here!](http://pyke.catbus.co.uk/?code=Whii3%25%213%60i%60%7B%7C&input=299&warnings=0)
```
              - i = input
W             - do:
 hi           -  i += 1
   i3%!       -    not (i % 3)
            | -   ^ or V
       3`i`{  -    "3" in str(i)
              - while ^
```
[Answer]
# C#, ~~56~~, 51 bytes.
This is surprisingly short for a C# answer!
```
x=>{while(++x%3<1|(x+"").Contains("3"));return x;};
```
[Answer]
# Pyth, 11 bytes
```
f&-I`T3%T3h
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=f%26-I%60T3%25T3h&input=29&test_suite_input=1%0A2%0A11%0A22%0A29%0A251&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=f%26-I%60T3%25T3h&input=29&test_suite=1&test_suite_input=1%0A2%0A11%0A22%0A29%0A251&debug=0)
### Explanation:
```
f&-I`T3%T3hQ   implicit Q at the end
f         hQ   find the smallest integer T >= input + 1 which fulfills:
  -I`T3           T is invariant under removing the digit 3
 &                and
       %T3        T mod 3 leaves a positive remainder
```
[Answer]
# Excel, ~~79~~ 66 bytes
It [Taylor Rained](https://codegolf.stackexchange.com/questions/98366/count-without-3/246608?noredirect=1#comment552856_246608) 13 bytes
```
=MIN(LET(r,ROW(A:A),FILTER(r,ISERR(FIND(3,r))*MOD(r,3)*(r>A1)>0)))
```
Input is in the cell `A1`. Output is wherever the formula is.
The `LET()` function allows you to define variables for later reference so ti works in pairs of `variable,value`. The last argument is unpaired as it is the output.
* `r,ROW(A:A)` creates an array of 1 to whatever the last row is. In the latest version of Excel, that's 1,048,576.
* `g,FILTER(r,~*~*~>0)` takes that array and filters just for the values that aren't multiples of 3 and don't have a 3 in them. This done is by multiplying:
	+ `ISERR(FIND(3,r))` which returns TRUE if if a 3 is *not* in the number and FALSE if it *is*
	+ `MOD(r,3)` which returns 0 if it's a multiple of 3 and some positive integer if it isn't
	+ `(r>A1)` creates an array of TRUE / FALSE where the first TRUE value will be the first term that's larger than the input.
	+ When you do math on booleans, Excel uses TRUE=1 and FALSE=0 so the formula `~*~*~>0` only returns TRUE when the three pieces are TRUE (no 3 in number), some positive integer (not a multiple of 3), and TRUE (larger than the input).
* `MIN(LET(~))` finds the smallest value in the filtered array which only includes the "without 3" numbers larger than the input so the first value in the array is the next value in the sequence.
[![Screenshot](https://i.stack.imgur.com/Quvq3.png)](https://i.stack.imgur.com/Quvq3.png)
[Answer]
# [Python 3](https://docs.python.org/3/), 49 48 bytes
-3 bytes thx to The Thonnu, I missed some spaces and swapping else x+1 and else-~x allowed another space to be taken out, not
+2 bytes bc I didn't know I need to count f= on a recursive function, thx xnor :)
seems clunky but i cant see more golfs, please lmk if you see something!
```
f=lambda x:f(x+1)if x%3>1or'3'in str(x+1)else-~x
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRocIqTaNC21AzM02hQtXYzjC/SN1YPTNPobikCCyemlOcqltX8b@gKDOvRCNNw1BTkwvGNkJiG6JIIMsYWSJzTIHq/gMA "Python 3 – Try It Online")
[Answer]
## [GolfSharp](https://github.com/timopomer/GolfSharp), 43 bytes
```
m=>r(m,m).w(n=>n%3>0&!n.t().I("3")).a()[1];
```
[Answer]
# Ruby, 47 bytes
```
i=gets.to_i;i while(i+=1)%3==0||"#{i}"=~/3/;p i
```
I really feel like this can be golfed further.
[Answer]
# [MATL](http://github.com/lmendo/MATL), 14 bytes
```
`Qtt3\wV51-hA~
```
[Try it online!](http://matl.tryitonline.net/#code=YFF0dDNcd1Y1MS1oQX4&input=Mjk)
### Explanation
```
`       % Do...while
  Q     %   Add 1. Takes input implicitly in the first iteration
  tt    %   Duplicate twice
  3\    %   Modulo 3
  wV    %   Swap, string representation
  51-   %   Subtract 51, which is ASCII for '3'
  h     %   Concatenate
  A~    %   True if any result was 0. That indicates that the number
        %   was a multiple of 3 or had some '3' digit; and thus a
        %   new iteration is needed
```
[Answer]
# PHP, ~~60~~ ~~55~~ ~~54~~ 46 bytes
Thanks to @user59178 for shaving off a few bytes, @AlexHowansky for a byte, @Titus for another few bytes
```
for(;strstr($i=++$argv[1],51)|$i%3<1;);echo$i;
```
Called from command line with `-r`. Naive method that loops while the number is a multiple of 3, or has 3 in its digits.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
D;Æf3ḟµ‘#2ị
```
[Try it online!](https://tio.run/nexus/jelly#@@9ifbgtzfjhjvmHtj5qmKFs9HB39////40sAQ "Jelly – TIO Nexus")
### How it works
```
D;Æf3ḟµ‘#2ị  Main link. Argument: n
      µ      Combine the links to the left into a chain.
       ‘#    Execute the chain for k = n, n + 1, n + 2, ... until n + 1 matches
             were found. Yield the array of all n + 1 matches.
D            Decimal; yield the array of k's decimal digits.
  Æf         Yield the array of k's prime factors.
 ;           Concatenate both.
    3ḟ       Filter false; remove digits and factors from [3].
             This yields [3] (truthy) if neither digits nor factors contain 3,
             [] (falsy) if they do.
         2ị  Extract the second match. (The first match is n.)
```
[Answer]
# PHP, ~~47~~ 41 bytes
inspired by [Xanderhall](https://codegolf.stackexchange.com/a/98462#98462), but the latest idea finally justifies an own answer.
```
while(strstr($n+=$n=&$argn%3,51));echo$n;
```
or
```
while(strpbrk($n+=$n=&$argn%3,3));echo$n;
```
This takes advantage from the fact that the input is also from the sequence: For `$n%3==1`, the new modulo is `2`. For `$n%3==2`, the new modulo is `4-3=1`. `$n%3==0` never happens.
Run as pipe with `-R` or [try them online](http://sandbox.onlinephpfunctions.com/code/c94a70661b4b1a7f28d583f01ce72ecc287cafe4).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~33~~ ~~28~~ ~~27~~ 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
1∘+⍣{('3'∊⍕⍺)<×3|⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/BRxwztR72LqzXUjdUfdXQ96p36qHeXps3h6cY1QEbt/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D9NwZArTcEIiA3BDBDLyBJEmBoCAA "APL (Dyalog Unicode) – Try It Online")
-6 thanks to Adám. -8 thanks to ngn.
Old Explanation:
```
1-⍨g⍣((×3|⊢)>'3'∊⍕)∘(g←+∘1)
                       +∘1  ⍝ curry + with 1, gives the increment function
                            ⍝ increments the left argument so we do not return the number itself
                    (g←   ) ⍝ assign to "g"
                   ∘        ⍝ compose g with the repeat
                 ⍕          ⍝ does parsing the argument to a string...
             '3'∊           ⍝ ...contain '3'?
        3|⊢                 ⍝ residue of a division by 3
      (×   )                ⍝ direction (0 if 0, 1 if greater, ¯1 is lower)
     (      >     )         ⍝ and not (we want the left side to be 1, the right side 0)
   g⍣                       ⍝ repeat "g" (increment) until this function is true ^
1-⍨                         ⍝ afterwards, decrement: inversed -
```
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~23~~ 17 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
1∘+⍣(3(×⍤|>∊⍥⍕)⊣)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3/BRxwztR72LNYw1Dk9/1Lukxu5RR9ej3qWPeqdqPuparPk/7VHbhEe9fY/6pnr6P@pqPrTe@FHbRCAvOMgZSIZ4eAb/T1Mw5EpTMAJiQzADxDKyBBGmhgA "APL (Dyalog Extended) – Try It Online")
Thanks to Adám. -6 thanks to ngn.
Old Explanation:
```
0+⍣(3(×⍤|>∊⍥⍕)⊢)⍢(1+⊢)⊢
0                       ⍝ the left argument (⍺)
 +⍣(3(×⍤|>∊⍥⍕)⊢)        ⍝ the left function (⍺⍺)
                 (1+⊢)  ⍝ the right function (⍵⍵)
                        ⍝     (increments its argument)
                      ⊢ ⍝ the right argument (⍵)
                        ⍝     (just returns the input)
                ⍢       ⍝ under:
                        ⍝     calls (⍵⍵ ⍵) first, which increments the input
                        ⍝     also (⍵⍵ ⍺) which gives 1
                        ⍝     then calls (⍺incremented ⍺⍺ ⍵incremented)
                        ⍝     afterwards, does the opposite of ⍵⍵, and decrements the result
  ⍣                     ⍝ ⍣ fixpoint: repeats the left operation until the right side is truthy
 +                      ⍝ calls + with ⍺incremented and the input (so, 1+input)
   (3(×⍤|>∊⍥⍕)⊢)        ⍝ right operation
    3                   ⍝ on its left, "3"
              ⊢         ⍝ on its right, the current iteration
      ×⍤|               ⍝ divisibility check: × atop |
        |               ⍝     starts with 3|⊢ (residue of ⊢/3)
      ×                 ⍝     then returns the direction (0 if 0, 1 if greater, ¯1 is lower)
          ∊⍥⍕           ⍝ contains 3:
            ⍕           ⍝    stringifies both its arguments (3 and ⊢)
          ∊⍥            ⍝    checks for membership
         >              ⍝ divisibility "and not" contains 3
```
[Answer]
# Turing Machine Code, 390 bytes
```
0 * * r 0
0 _ _ l 1
1 1 2 l 2
1 2 3 r 0
1 3 4 l 2
1 4 5 l 2
1 5 6 l 2
1 6 7 l 2
1 7 8 l 2
1 8 9 l 2
1 9 0 l 1
1 * 1 l 2
2 * * l 2
2 _ _ r 3
3 1 1 r 4
3 4 4 r 4
3 7 7 r 4
3 2 2 r 5
3 5 5 r 5
3 8 8 r 5
3 _ _ l 1
4 1 1 r 5
4 4 4 r 5
4 7 7 r 5
4 2 2 r 3
4 5 5 r 3
4 8 8 r 3
5 1 1 r 3
5 4 4 r 3
5 7 7 r 3
5 2 2 r 4
5 5 5 r 4
5 8 8 r 4
* 0 0 r *
* 6 6 r *
* 9 9 r *
* 3 3 r 0
* _ _ * halt
```
[Try it online.](http://morphett.info/turing/turing.html?9e662757c6f814b3ceb0464e715ec3ab)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~27 25~~ 24 bytes
```
{max $_+1...{!/3/&$_%3}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplqZg@786N7FCQSVe21BPT69aUd9YX00lXtW4tvZ/Wn6RgkZOZl5qsaZCNRdncWKlQpqGdq5@TIq2viZX7X8FBUMFXTsFBQUjLiCGME24FAwhooZAphFE1MgUyLQEM00MuIxMwQqMTE0A "Perl 6 – Try It Online")
Finds the first number larger than the input that doesn't have a three and has a remainder when moduloed by 3. I was hoping to do something fancy with the condition, like `!/3/&*%3` but it doesn't work with the `!`. `:(`
### Explanation:
```
{                      }   # Anonymous code block
     $_+1                  # From the input+1
         ...               # Get the series
            {         }    # That ends when
             !/3/            # The number does not contain a 3
                 &           # and
                  $_%3       # The number is not divisible by 3
 max                       # And get the last element of the series
```
[Answer]
# APOL, 51 bytes
`v(0 +(⧣ 1));w(|(!(%(⁰ 3)) c(t(⁰) '3')) ∆(0));-(⁰ 1)`
[Answer]
# Swift, 84 bytes
```
func f(_ n:Int)->Int{var n=n+1;while String(n).contains("3")||n%3==0{n+=1};return n}
```
]