title: Pirate Treasure

text:
# Question
Title: Pirate Treasure
Finding a treasure hidden by pirates is really easy. Everything you need for this is a map. It is widely known that pirates draw maps by hand and describe the algorithm to find a place in the following way: "Stand near a lone palm tree, do 30 steps towards the forest, 15 towards the lake, ..."

A journey through such route is usually a great opportunity to see the scenery... However, nowadays nobody has time for that. That's why treasure seekers have asked you to write a program that would determine the exact location of a treasure using a given map.

---

# Input

The input consists of multiple instructions `<Direction> <Distance>`, separated with commas (that are followed by one whitespace each).

**Direction** is one of the following:
**`N`** \- North, **`S`** \- South, **`E`** \- East, **`W`** \- West,
**`NE`** \- Northeast, **`NW`** \- Northwest, **`SE`** \- Southeast, **`SW`** \- Southwest.

**Distance** is an integer (1 to 1000).

# Output

The result is the coordinates where you end up after finishing the instructions, with three decimal places, separated with a comma and a whitespace. Start location has zero coordinates (0, 0).

The first coordinate is **X** (East means coordinates larger than zero, West means less than zero).
The second coordinate is **Y** (North means *more* than zero, South means *less* than zero).

---

# Examples

**1.** `N 3, E 1, N 1, E 3, S 2, W 1`

`3.000, 2.000`

**2.** `NW 10`

`-7.071, 7.071`

**3.** `NE 42, NW 42, SE 42, SW 42`

`0.000, 0.000`

---

Source (in Ukrainian). Input format is different there.

# Answer
> 8 votes
## Ruby 1.9, 175 171 162 153 130 120 117

```
l=0
gets.scan(/(\w+) (\d+)/){|d,n|l+=n.to_i*?i.to_c**%w[E NE N NW W SW S SE].index(d).quo(2)}
puts'%.3f, %.3f'%l.rect

```

# Answer
> 4 votes
## Python, 158 154 150 chars

```
p=0j
for s in raw_input().split(','):c,d=s.split();v=sum(dict(N=1j,E=1,S=-1j,W=-1)[x]for x in c);p+=v*int(d)/abs(v)
print'%.3f, %.3f'%(p.real,p.imag)

```

# Answer
> 4 votes
## Haskell (291)

```
import Text.Printf
d=sqrt(0.5)
f"N"n(x,y)=(x,y+n)
f"S"n(x,y)=(x,y-n)
f"E"n(x,y)=(x+n,y)
f"W"n(x,y)=(x-n,y)
f[a,b]n(x,y)=(s,t)where(s,_)=f[b](d*n)(x,y);(_,t)=f[a](d*n)(x,y)
p[]=(0,0)
p(a:b:c)=f a(read b::Float)$p c
s(a,b)=printf"%.3f, %.3f"a b
main=getLine>>=putStrLn.s.p.words.filter(/=',')

```

# Answer
> 4 votes
## C99 (319 chars)

```
#define B ;break;
#include<math.h>
#include<stdio.h>
float x,y,w,z,j;int
main(void){int
k;char
c[3];while(scanf("%s%d,",c,&k)==2){j=k;w=1;switch(c[1]){case'E':w=3;default:w-=2;j=sqrt(k*k/2)B
case
0:w=z=0;}switch(*c){case'N':z=1
B
case'S':z=-1
B
case'E':w=1
B
default:w=-1;}x+=w*j;y+=z*j;}printf("%5.3f, %5.3f\n",x,y);}

```

input in `stdin`, test run at ideone :)

# Answer
> 4 votes
## JavaScript, ~~179~~ ~~164~~ ~~170~~ ~~168~~ ~~158~~ ~~156~~ 153 chars

```
prompt(X=Y=0).replace(/(N|S)?(.)? (\d+)/g,
        function(m,y,x,n){
            n/=x&&y?Math.SQRT2:1
            Y+=y?y<'S'?n:-n:0
            X+=x?x<'W'?n:-n:0
        })
alert(X.toFixed(3)+', '+Y.toFixed(3))

```
* 170: fixed accuracy issue
* 168: replaced `(E|W)` in regex with `(.)`
* 158: replaced repetitive logic in function with variable `d`
* 156: reused `n` instead of a new variable `d`
* 153: Personally, I think this edit makes it ten times uglier, but it's three characters shorter. It's based on the non-standard behavior that you can call RegExp objects as functions: `/./g('string')` is the same as `/./g.exec('string')`:

`for(p=prompt(X=Y=0),R=/(N|S)?(.)? (\d+)/g;[,y,x,n]=R(p)||0;X+=x?x<'W'?n:-n:0)n/=x&&y?Math.SQRT2:1,Y+=y?y<'S'?n:-n:0;alert(X.toFixed(3)+', '+Y.toFixed(3))`

# Answer
> 3 votes
# Haskell, 199 characters

```
import Text.Printf
import Complex
i=0:+(1::Float)
e 'S'= -i
e d=i^mod(fromEnum d-1)4
g p(d:s:t)=g(p+(signum.sum.map e)d*(fst(reads s!!0):+0))t
g(x:+y)[]=printf"%.3f, %.3f"x y
main=interact$g 0.words

```

# Answer
> 2 votes
**Scala (367, 332)**

```
var (x,y,s)=(.0,.0,.7071);args.mkString(" ").split(",").foreach{m=>val a=m.trim.split(" ");var (n,u,v)=(a(1).toInt,.0,.0);a(0) match{case "N"=>v=1;case "S"=>v= -1;case "E"=>u=1;case "W"=>u= -1;case "NW"=>{u= -s;v=s};case "NE"=>{u=s;v=s};case "SW"=>{u= -s;v= -s};case "SE"=>{u=s;v= -s}};x += n*u;y += n*v};printf("%1.3f %1.3f\n",x,y)

```

# Answer
> 2 votes
## Java ~~(459) (445) (402) (382) (363)~~ (352)

```
import java.util.*;class
M{public
static void main(String[]a){double
x=0,y=0;Scanner
s=new
Scanner(System.in);s.useDelimiter("\\W+");while(s.hasNext()){String
d=s.next();double
z=Math.sqrt(d.length());int
w=s.nextInt();y+=(d.contains("N")?w:d.contains("S")?-w:0)/z;x+=(d.contains("E")?w:d.contains("W")?-w:0)/z;}System.out.format("%1.3f %1.3f",x,y);}}

```

stdin input

# Answer
> 2 votes
## PowerShell, 178

```
$input-split','|%{,@{N=0,1
NE=($s=.707106781186548),$s
E=1,0
SE=$s,-$s
S=0,-1
SW=-$s,-$s
W=-1,0
NW=-$s,$s}[($a=-split$_)[0]]*$a[1]}|%{$x+=$_[0]
$y+=$_[1]}
'{0:N3}, {1:N3}'-f$x,$y

```

This can probably lose up to 10 characters by reducing the accuracy of √2/2.

# Answer
> 2 votes
# C (gcc), ~~155~~ 152 bytes

-3 bytes thanks to ceilingcat

```
float x,y,l;D;main(d){for(;scanf("%s%f,",&d,&l)>0;y+=d^78?d^83?0:-l:l)D=d,l/=D>99?D/=256,d&=255,sqrt(2):1,x+=D^87?D^69?0:l:-l;printf("%.3f, %.3f",x,y);}

```

Try it online!

# Answer
> 0 votes
## Groovy (215)

```
x=0.0;y=0.0;args.join(' ').split(', ').each{d=it.split(' ');c=d[0]==~/../?Math.sqrt(2):1;s=d[1] as int;a=['N':1,'S':-1,'E':1,'W':-1];m=d[0]=~/N|S/;y+=m?a[m[0]]*(s/c):0;m=d[0]=~/E|W/;x+=m?s/c*a[m[0]]:0};print "$x,$y"

```

reads input as program arguments. Example:

```
groovy golf.groovy NW 10, SW 10, W 10

```

# Answer
> 0 votes
# Perl 5 `-n`, 122 bytes

```
s,(N|S)?(E|W)? (\d+),$d=$3/($1&$2?2**.5:1);$x+=$2&&$d*(-1)**($2gt F);$y+=$1&&$d*(-1)**($1gt O),ge;printf"%.3f, %.3f",$x,$y

```

Try it online!

# Answer
> 0 votes
# , 93 bytes

```
[:0j3&":@+.@(1#.".@>@{:*(0j1^2%~i.8){~<;._1@' E NE N NW W SW S SE'i.{.)@|:[:(<;._1);._1', ',]

```

Try it online!

---
Tags: code-golf
---


# Question
Title: Generate basis elements of the Steenrod algebra
The Steenrod algebra is an important algebra that comes up in algebraic topology. The Steenrod algebra is generated by operators called "Steenrod squares," one exists for each positive integer i. There is a basis for the Steenrod algebra consisting of "admissible monomials" in the squaring operations. It is our goal to generate this basis.

A sequence of positive integers is called *admissible* if each integer is at least twice the next one. So for instance `[7,2,1]` is admissible because \\$7 \geq 2\*2\\$ and \\$2 \geq 2\*1\\$. On the other hand, `[3,2]` is not admissible because \\$3 \< 2\*2\\$. (In topology we would write \\$\mathrm{Sq}^7 \mathrm{Sq}^2\mathrm{Sq}^1\\$ for the sequence `[7,2,1]`).

The *degree* of a sequence is the total of it's entries. So for instance, the degree of `[7,2,1]` is \\$7 + 2 + 1 = 10\\$. The *excess* of an admissible sequence is the first element minus the total of the remaining elements, so `[7,2,1]` has excess \\$7 - 2 - 1 = 4\\$.

## Task

Write a program that takes a pair of positive integers `(d,e)` and outputs the set of all admissible sequences of degree `d` and excess less than or equal to `e`. The output is a set so the order of the admissible sequences doesn't matter.

## Examples:

```
 Input: 3,1
 Output: [[2,1]]

```

Here we are looking for admissible sequences with total 3. There are two options, `[3]` and `[2,1]`. (`[1,1,1]` and `[1,2]` have sum 3 but are not admissible). The excess of `[3]` is 3 and the excess of `[2,1]` is \\$2-1 = 1\\$. Thus, the only sequence with excess \\$\leq1\\$ is `[2,1]`.

```
Input: 6, 6
Output: [[6], [5, 1], [4, 2]] (or any reordering, e.g., [[5,1],[4,2],[6]])

```

Since excess is always less than or equal to degree, we have no excess condition. Thus, we're just trying to find all admissible sequences of degree 6. The options are `[6]`, `[5, 1]`, and `[4, 2]`. (These have excess \\$6\\$, \\$5-1 = 4\\$, and \\$4-2=2\\$.)

```
Input: 10, 5
Output: [[7,3], [7,2,1], [6,3,1]]

```

The admissible sequences of degree 10 are:

```
[[10], [9,1], [8,2], [7,3], [7,2,1], [6,3,1]]

```

These have excess \\$10\\$, \\$9-1 = 8\\$, \\$8-2 = 6\\$, \\$7-3 = 4\\$, \\$7-2-1 = 4\\$, and \\$6-3-1=2\\$ respectively, so the last three all work.

## Scoring

This is code golf: Shortest solution in bytes wins.

## Test cases:

Any reordering of the output is equally good, so for input `(3, 3)`, outputs `[[3],[2,1]]` or `[[2,1],[3]]` are equally acceptable (however `[[1,2],[3]]` isn't).

```
Input: 1, 1
Output: [[1]]

Input: 3, 3
Output: [[2,1], [3]]

Input: 3, 1
Output: [[2,1]]

Input: 6, 6
Output: [[6], [5, 1], [4, 2]]

Input: 6, 4
Output: [[5,1], [4,2]]

Input: 6, 1
Output: []

Input: 7, 7
Output: [[7], [6,1], [4,2,1], [5,2]]

Input: 7,1
Output: [[4,2,1]]

Input: 10, 10
Output: [[10], [9,1], [7,2,1], [6,3,1], [8,2], [7,3]]

Input: 10, 5
Output: [[7,3], [7,2,1], [6,3,1]]

Input: 26, 4
Output: [15, 7, 3, 1]

Input: 26, 6
Output: [[16, 7, 2, 1], [16, 6, 3, 1], [15, 7, 3, 1], [16, 8, 2], [16, 7, 3]]

```

# Answer
> 6 votes
# 05AB1E, ~~16~~ 12 bytes

Saved 4 bytes thanks to *Grimy*

```
Åœíʒx¦@P}ʒÆ@

```

Try it online!

**Explanation**

```
Åœ              # integer partitions
  í             # reverse each
   ʒ    }       # filter, keep only elements true under:
    x           # each element doubled
     ¦          # remove the first element in the doubled list
      @         # compare with greater than or equal with the non-doubled
       P        # product
         ʒ      # filter, keep only elements true under:
          Æ     # reduce by subtraction
           @    # compare with greater than or equal to second input

```

# Answer
> 5 votes
# Wolfram Language (Mathematica), ~~67~~ 62 bytes

```
Cases[IntegerPartitions@#,a_/;2a[[1]]-#<=#2>Max@Ratios@a<=.5]&

```

Try it online!

*-4 bytes by @attinat*

* `IntegerPartitions@d` : Get all lists of integers summing to `d`
* `Cases[,...]`: Filter by the following condition:
    + `2#& @@# - d <= e &&`: Twice the first element minus the sum is less than `e`, and...
    + `Max@Ratios@#<=.5`: Ratios of successive elements of the list are all less than 1/2.

Because `e` is less than .5, we can turn this into a chained inequality.

For a few extra bytes, this is significantly faster: Try it online!

# Answer
> 5 votes
# Jelly,  ~~16~~  15 bytes

-1 thanks to Erik the Outgolfer (a smart adjustment to the checking allowing a single filter)

```
:Ɲ;_/>¥’Ạ
ŒṗUçƇ

```

A dyadic link accepting a positive integer, `d`, on the left and a positive integer, `e`, on the right which yields a list of lists of positive integers.

**Try it online!** (the footer formats the results to avoid list the implicit list formatting Jelly does as a full program)

### How?

```
:Ɲ;_/>¥’Ạ - Link 1: admissible and within excess limit? descending list, L; excess limit, e
 Ɲ        - neighbour-wise:
:         -   integer division  -- admissible if all these are >1
      ¥   - last two links as a dyad - i.e. f(L,e):
    /     -   reduce (L) by:
   _      -     subtraction
     >    -   greater than (e)? (vectorises)  -- within excess if all these are ==0
  ;       - concatenate
       ’  - decrement (vectorises)
        Ạ - all (non-zero)?

ŒṗUçƇ - Main link: integer, d; integer, e
Œṗ    - partitions (of d)
  U   - reverse each
    Ƈ - filter keep those (v in that) for which:
   ç  -   call last Link (1) as a dyad - i.e. f(v, e)

```

# Answer
> 4 votes
# Haskell, ~~59~~ ~~58~~ 54 bytes

*1 byte saved thanks to nimi*

*4 bytes saved thanks to xnor*

```
0#_=[[]]
d#m=do i<-[1..div(m+d)2];(i:)<$>(d-i)#(2*i-d)

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~213 bytes~~

~~Giant list comprehension. Most likely not the best way to do this, but I can't figure out how to skip the if statements <br>```
import itertools as z
f=lambda d,e:[c for c in [[b for b in list(z.permutations(range(1,d+1),i)) if sum(b)==d and b[0]-sum(b[1:i])<=e and all([b[i]>=b[i+1]*2 for i in range(len(b)-1)])] for i in range(1,5)] if c]

```~~

# Python 3, 172 bytes

```
from itertools import*
r=range
f=lambda d,e:filter(len,[[b for b in permutations(r(1,d+1),i)if d==sum(b)and~e<d-2*b[0]and all(i>=j*2for i,j in zip(b,b[1:]))]for i in r(5)])

```

Try it online!

As according to edits by @Jonas Ausevicius

# Answer
> 3 votes
# JavaScript (V8),  ~~88 87~~  81 bytes

Takes input as `(e)(d)`. Prints the sequences to STDOUT.

```
e=>g=(d,s=x=d,a=[])=>s>0?d&&g(d-1,s,a,g(d>>1,s-d,[...a,d])):a[s]*2-x<=e&&print(a)

```

Try it online!

### Commented

```
e =>                  // e = maximum excess
  g = (               // g is a recursive function taking:
    d,                //   d   = expected degree; actually used as the next candidate
                      //         term of the sequence in the code below
    s =               //   s   = current sum, initialized to d; we want it to be equal
                      //         to 0 when a sequence is complete
    x = d,            //   x   = copy of the expected degree
    a = []            //   a[] = current sequence
  ) =>                //
    s > 0 ?           // if s is positive:
      d &&            //   if d is not equal to 0:
        g(            //     outer recursive call:
          d - 1,      //       decrement d
          s,          //       leave s unchanged
          a,          //       leave a[] unchanged
          g(          //       inner recursive call:
            d >> 1,   //         update d to floor(d / 2)
            s - d,    //         subtract d from s
            [...a, d] //         append d to a[]
          )           //       end of inner recursive call
        )             //     end of outer recursive call
    :                 //   else:
      a[s] * 2 - x    //     s if either 0 (success) or negative (failure)
                      //     if s is negative, a[s] is undefined and this expression
                      //     evaluates to NaN, forcing the test to fail
      <= e            //     otherwise, we test whether the excess is valid
      && print(a)     //     and we print a[] if it is

```

# Answer
> 3 votes
# Pyth, 23 bytes

```
f!>-FTvzf!<#2/MCtBT_M./

```

Try it online!

```
f!>-FTvzf!<#2/MCtBT_M./Q   Implicit: Q=input 1, vz=input 2
                           Trailing Q inferred
                     ./Q   Generate partitions of Q (ordered lists of integers which sum to Q)
                   _M      Reverse each
        f                  Filter keep elements of the above, as T, where:
               CtBT          Pair the set with itself without the first element and transpose
                             This yields all adjacent pairs of values
             /M              Integer divide each pair
           #                 Filter keep elements...
          < 2                ... less than 2
                             For admissible sequences this will be empty
         !                   Logical NOT - maps [] to true, populated lists to false
                           Result of filter are all admissible sequences
f                          Filter keep the above, as T, where:
   -FT                       Reduce T by subtraction to get degree
 !>   vz                     Is the above not greater than vz?
                           Implicit print

```

# Answer
> 2 votes
# Charcoal, 42 bytes

```
Ｆθ⊞υ⟦⊕ι⟧ＦυＦ…·⊗§ι⁰θ⊞υ⁺⟦κ⟧ιＩΦυ›⁼Σιθ‹η⁻⊗§ι⁰Σι

```

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

```
Ｆθ⊞υ⟦⊕ι⟧

```

First create a list of lists from `[1]..[d]`.

```
ＦυＦ…·⊗§ι⁰θ⊞υ⁺⟦κ⟧ι

```

For each list create new lists by prefixing all the numbers from the doubled first number up to `d` and append those lists to the list of lists to be processed. This ensures that all admissible sequences containing numbers not greater than `d` are created.

```
ＩΦυ›⁼Σιθ‹η⁻⊗§ι⁰Σι

```

Output only those lists whose degree is `d` and excess is not greater than `e`. (The sum of the degree and excess is equal to twice the first number of the list.)

# Answer
> 2 votes
# Python 3, 156 bytes

```
lambda d,e:[x for y in range(5)for x in permutations(range(1,d+1),y)if all(i>=j*2for i,j in zip(x,x[1:]))and d==sum(x)and~e<d-2*x[0]]
from itertools import*

```

takes `d,e` as input; outputs list of tuples

*Similar to @OrangeCherries answer and help from comments; but more bytes saved*

Try it online!

# Answer
> 1 votes
# Jelly, 18 bytes

```
ŒṗU:Ɲ’ẠƊƇUṪ_SƊ’<ʋƇ

```

Try it online!

# Answer
> 1 votes
# Ruby, 78 bytes

```
g=->(d,e,m=1){d<m ?[]:g[d-m,e+m,m*2].map{|q|q+[m]}+g[d,e,m+1]|(d>e ?[]:[[d]])}

```

Try it online!

---
Tags: code-golf, math, combinatorics, topology
---


title: Find 77 7-letter Magic Words

text:
# Question
Title: Find 77 7-letter Magic Words
A magic word is a word whose Braille spelling contains precisely 26 dots (because the Morse code alphabet can be circularly encoded within). For example:

```
 ⠎ ⠝ ⠥ ⠛ ⠛ ⠇ ⠽ snuggly
 ⠏ ⠕ ⠇ ⠽ ⠛ ⠕ ⠝ polygon
 ⠝ ⠥ ⠛ ⠛ ⠑ ⠞ ⠽ nuggety
 ⠽ ⠕ ⠛ ⠓ ⠥ ⠗ ⠞ yoghurt

```

are all magic words.

**Objective:** Craft a program to identify 77 such magic words and output the word along with its Braille spelling.

# Answer
# Jelly, ~~77~~ 74 bytes

```
×6‘ḃØ⁵ịØJ⁾“»jVŒu
“¢~ỌƈY⁴⁸ġƁUP©¥!ḃ^⁶ẹøD’ḃ61
ÑOị¢BSS×LƲ⁼182µ77#Ñ€Ożị¢+⁽$ṁƊ$Ọ

```

Try it online! (Times out)

Demo using 4 words and starting the search later in the dictionary

All 77 words produced if enough time allocated

A full program that generates 77 seven-letter words from Jelly’s dictionary that require exactly 26 dots in Braille. Now outputs a list of lists with the word in ASCII and then Braille.
> 3 votes

---
Tags: code-golf, kolmogorov-complexity, natural-language
---


title: Press any key to continue

text:
# Question
Title: Press any key to continue
Your task is to create a program that will display the following text, wait for the user to press a key (it is okay to ignore keys like `ctrl`, `alt`, `caps lock`, etc., as long as keys like `letters`, `numbers`, `symbols`, and `enter` are not ignored), and then terminate the program:

```
Press any key to continue...

```

Trailing newlines are allowed. The program must exit immediately after a key is pressed. Also, the program must be fairly portable (i.e no OS-specific headers or modules, runs outside of an IDE, etc.).

---

The prompt must be exactly as shown above, unless a trailing newline cannot be avoided.

---

This is , so the shortest answer in bytes wins. This is also my first code-golf question, so I apologize if I do not know the rules on PPCG.

# Answer
> 5 votes
## SmallBasic, ~~18~~ 17 bytes

* Version 2.0

17 bytes

```
TextWindow.Show()
```
* Version 1.0

18 bytes

```
TextWindow.Pause()
```

# Answer
> 20 votes
## Batch, 46 bytes

```
@echo Press any key to continue...
@pause>nul

```

Because `pause`'s output contains a space before each `.`.

# Answer
> 15 votes
# HTML + JavaScript (ES6), 36 + 25 = 61 bytes

You can't really exit a JavaScript program, so clearing the webpage is the best I can think of.

```
onkeyup=_=>a.innerHTML=''
```

```
<a id=a>Press any key to continue...
```

---

# HTML + JavaScript (ES6), 33 + 28 = 61 bytes

Alternate solution suggested by @LarsW that redirects to `about:blank`.

```
onkeyup=_=>location='about:blank'
```

```
Press any key to continue...
```

---

# HTML/JavaScript, 60 bytes

Another awesome solution by @Ismael Miguel that doesn't use standalone JS. 1 byte saved!

```
<html onkeyup=this.innerHTML=''>Press any key to continue...
```

---

# HTML + JavaScript (ES6), 26 + 28 = 54 bytes

Yet another solution by @George Reith making use of document writes.

```
onkeyup=_=>document.open()
```

```
Press any key to continue...
```

# HTML + JavaScript (ES7), 23 + 28 = 51 bytes

Same program using the proposed ES7 bind operator:

```
onkeyup=::document.open
```

```
Press any key to continue...
```

---

As most of these solutions are not my own, do a courtesy and vote them up in the comments!

# Answer
> 14 votes
# MATL, 35 bytes

```
'Press any key to continue...'D0$Y.

```

**Explanation**

```
'Press any key to continue...'      % String literal
D                                   % Display the string (has trailing newline)
0$Y.                                % Pause until the user presses any key

```

# Answer
> 11 votes
# TI-Basic, 55 bytes

Basically, it loops until a key is pressed. Too bad lowercase letters are two bytes each in TI-Basic...

```
Disp "Press any","key to continuesin(
Repeat getKey
End

```

P.S. See the comment by @GoldenRatio for the explanation as to how this works. It's genius!

# Answer
> 8 votes
# Bash, ~~46~~ ~~43~~ 42 bytes

*Saved 1 byte thanks to @DigitalTrauma*

```
read -rn1 -p"Press any key to continue..."

```

Uses the `read` built-in. `-r` makes sure it doesn't allow the user to input escapes. `-n 1` allows just one character. `-p` is the prompt

# Answer
> 8 votes
# Haskell, ~~51~~ 50 bytes (Thanks @villou24)

```
main=putStr"Press any key to continue...">>getChar

```

Try it online!

# Answer
> 5 votes
# Octave / MATLAB, 42 bytes

```
disp('Press any key to continue...');pause

```

# Answer
> 4 votes
# Processing, ~~89~~ 81 bytes

```
void setup(){print("Press any key to continue...");}void draw(){if(key>0)exit();}

```

### Explanation

```
void setup(){print("Press any key to continue...");}

```

This is required since I am using more than one function in my program. Anything inside `setup()` gets called, in this case the string `"Press any key to continue..."`.

```
if(key>0)exit();

```

Checks if `key` (`key` will always contain the int value of the last key pressed) is more than `0` (ie not a null byte). If the condition is satisfied, then the program exits.

```
void draw(){}

```

`draw()` ensures that that the program will always keep looking for a key instead of stopping once the program starts.

(That feel when a builtin in a Java-like language is still verbose...)

# Answer
> 4 votes
## Bash ~~48~~ ~~44~~ 42 bytes

```
read -rn1 -p"Press any key to continue..."

```

@mame98 Thanks for saving 4 bytes.

@RaisingAgent Thanks for saving 2 bytes.

# Answer
> 4 votes
# QBasic (QB64), 37 (42?) bytes

Unfortunately, QBasic's built-in end-of-program prompt doesn't have the ellipsis, so we'll have to print it ourselves:

```
?"Press any key to continue..."
SLEEP

```

(`SLEEP` without an argument waits until a keypress.)

This code does what the question literally asks for, but it doesn't seem like it fits the spirit of the question because, of course, QBasic then displays "Press any key to continue" and waits for a keypress before returning to the IDE. Here's one that goes straight to the IDE, for +5 bytes:

```
?"Press any key to continue..."
SLEEP
STOP

```

`STOP` is a debugging statement. In regular QBasic, it sets a breakpoint: execution halts and we return to the IDE, but execution can be resumed again with F5. It's unclear whether that would count as the program "exiting." However, I'm using the QB64 emulator, which can't do breakpoints. Upon encountering `STOP`, it simply halts--returning straight to the IDE without the redundant "Press any key" message.

# Answer
> 4 votes
# Pascal, ~~75~~ 65 bytes

This was tested with the Free Pascal Compiler, version 3.0.0.
It may work with TurboPascal 7 or newer.

```
uses Crt;begin write('Press any key to continue...');readkey;end.

```

Sadly, I can't replace `readkey` with `readln` since the challenge requires that **any** key be accepted.

---

I've tested this code on http://rextester.com/l/pascal\_online\_compiler, with and without supplying an input.
As expected, the program is terminated after 10s, since it sits waiting for a keypress that never happens.

---

Thanks to @manatwork for saving me 10 bytes by proving me wrong, and showing that I don't need the `program _;`.

# Answer
> 4 votes
# Python 2, 110 bytes

```
import curses as c
s=c.initscr()
c.cbreak()
s.addstr(0,0,'Press any key to continue...')
while not s.getch():1

```

# Answer
> 4 votes
# Scratch, 81 bytes

```
when gf clicked
say [Press any key to continue...
wait until <key [any v] pressed

```

(Scratchblocks link)

If you wanted it to stop the *entire* program when you pressed a key (including other threads) you'd have to add a `stop all`. If you want to get rid of the say dialog you need an empty `say` block (`stop all` works as well).

Convenient that Scratch has a builtin for this!

# Answer
> 3 votes
# Ruby (2.3) (+ Batch), ~~52~~ ~~55~~ ~~54~~ ~~53~~ 46 bytes

Now 46 bytes thanks to Alexis Andersen.

Note: Tested on Windows, might not work if there is no `pause` command.

```
puts"Press any key to continue...";`pause>nul`

```

# Explanation

`Puts` the required text:

```
puts"Press any key to continue..."

```

End the line:

```
;

```

Run the Batch `pause` command and pipe output to `nul`:

```
`pause>nul`

```

# Answer
> 3 votes
## R, 56 bytes

```
cat('Press any key to continue...');keypress::keypress()

```

This works in Linux and OSX terminals.

# Answer
> 3 votes
# Java, 127 bytes

```
class P{public static void main(String[]a)throws Exception{System.out.print("Press any key to continue...");System.in.read();}}

```

Note: the console must be set to raw mode in order for this to work.

# Answer
> 3 votes
# SmileBASIC, 52 bytes

```
?"Press any key to continue...
WHILE""==INKEY$()WEND

```

# Answer
> 2 votes
# Mathematica, 62 bytes

```
EventHandler["Press any key to continue...","KeyDown":>Exit[]]

```

**Explanation**

```
EventHandler["Press any key to continue...","KeyDown":>Exit[]]
EventHandler[                                                ]  (* Create a new EventHandler *)
             "Press any key to continue..."                     (* Print the dialog text *)
                                            "KeyDown":>Exit[]   (* When a key is pressed down, exit *)

```

# Answer
> 2 votes
# SmileBASIC, 55 bytes

```
?"Press any key to continue..."@L IF INKEY$()!=""GOTO@L

```

Explained:

```
?"Press any key to continue..."  '? means PRINT
@L                               'start of loop
IF INKEY$()!="" GOTO @L          'if no key pressed goto @L

```

# Answer
> 2 votes
# **Python 3, 65 bytes**

Requires the Windows version of Python.

```
from msvcrt import*
print("Press any key to continue...")
getch()

```

msvcrt.getch() doesn't wait for the enter key to be pressed like input(), it returns the first key pressed.

Python Docs for msvcrt.getch(): https://docs.python.org/3/library/msvcrt.html#msvcrt.getch

Thanks to @Fliptack for saving some bytes

# Answer
> 2 votes
# Python 2/3 POSIX, 85 bytes

```
import sys,tty
print('Press any key to continue...')
tty.setraw(1)
sys.stdin.read(1)

```

# Answer
> 2 votes
# Node.js, ~~102~~ ~~101~~ 99 bytes

```
with(process)stdout.write('Press any key to continue...'),s=stdin,s.setRawMode(1),s.on('data',exit)

```

# Answer
> 2 votes
# Sinclair ZX81/Timex TS1000 BASIC: Method 1 approximately 41 bytes

```
1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 GOTO (INKEY$<>"")+VAL "2"

```

## Method 2 approximately 38 BYTES

```
1 PRINT "PRESS ANY KEY TO CONTINUE..."
2 PAUSE VAL "4E4"

```

I prefer method 1 as on the ZX81, there is a screen flicker when `PAUSE` is called, and if you want long enough (providing the ZX81 doesn't overheat or crash) the pause will eventually come to an end, whereas method 1 is stuck in an infinite loop until a key is pressed, and no screen flicker.

I'll work out the correct number of bytes used later when I have the right bit of BASIC that will tell me. By the way, using VAL "x" instead of the number saves valuable RAM on a ZX81 (I think that this is the same for the ZX Spectrum as well).

# Answer
> 1 votes
## Perl 5, 79 bytes

```
system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)

```

used as:

```
perl -e 'system "stty cbreak";$|=1;print "Press any key to continue...";read(STDIN,$a,1)'

```

No prizes of course. I'm sure some perl person will have a better way.

(89 bytes if the interpreter invocation as well needs to be included in the count)

# Answer
> 1 votes
# 8th, 47 bytes

```
"Press any key to continue..." . cr con:key bye

```

This program ignores keys like ctrl, alt, caps lock. Quits with keys like letters, numbers, symbols, and enter.

**Explanation**

```
"Press any key to continue..." . cr \ Print message
con:key                             \ Wait for key input from console
bye                                 \ Quit program

```

# Answer
> 1 votes
### PHP, 73 bytes

```
echo"Press any key to continue...";$h=fopen("php://stdin","r");fgets($h);

```

Run it in the PHP interactive shell (`php -a`)

# Answer
> 1 votes
# C#, 101 bytes

```
using C=System.Console;class P{static void Main(){C.Write("Press any key to continue...");C.Read();}}

```

Tested on Linux, should run on any system having the .NET libraries and the Common Language Runtime.

Ungolfed program:

```
using C = System.Console; // creating a shorter alias for the System.Console class

class P
{
    static void Main()
    {
        C.Write("Press any key to continue...");    // prints the message
        C.Read();   // waits for key press
    }
}

```

CTRL, ALT, SHIFT are ignored. The pressed key will be echoed on screen if printable.

Echo can be disabled by replacing *C.Read()* with *C.ReadKey(0\<1)* at the cost of 6 more bytes.

# Answer
> 1 votes
## C#, 29 bytes

```
class P{static void Main(){}}

```

Not sure if this is considered valid because it prints:

> Press any key to continue . . .

But there is a Batch answer that prints this as well.

# Answer
> 1 votes
# SmallBasic 17 bytes

```
TextWindow.Show()

```

I had this answer before the accepted answer added it to their answer by the way. (To avoid unjust flags)

# Answer
> 1 votes
# Forth (gforth), 39 bytes

```
." Press any key to continue..."key bye

```

(Yes, there is already an 8th solution but this is shorter)

# Answer
> 0 votes
# HTML + Javascript, 58 bytes

```
<html onkeyup=document.open('')>Press any key to continue.
```

# Answer
> 0 votes
# MATLAB, 41 bytes

or it could be **Octave, 40 bytes.**

This is quite similar to the obvious approach posted by Suever, but is **one glorious byte shorter**.

```
disp 'Press any key to continue...'
pause

```

or in Octave:

```
disp"Press any key to continue..."
pause

```

A little known and little used feature of both MATLAB and Octave is that most builtin functions can be called without parentheses, in which case they will treat whatever follows it as a string (as long as it doesn't contain spaces).

For instance:

```
nnz PPCG
ans = 4

size PPCG
ans = 1  4

str2num 12
ans = 12

```

Now, if the input is a word with multiple words, then we need the quotation marks, so `disp('Press any key to continue...')` is reduced to `disp 'Press any key to continue...'`, saving one byte. Instead of the semicolon separating the `disp` call and the `pause`, we now separate them using a linefeed.

# Answer
> 0 votes
# C64Mini/C64 BASIC (also VIC-20 BASIC) 52 tokenized BASIC bytes

```
 0?"PRESS ANY KEY TO CONTINUE...":POKE198,0:WAIT198,1

```

The `?` is short-hand for `PRINT`; thereafter, `POKE 198,0` will clear the keyboard buffer, whilst `WAIT 198,1` will wait until the keyboard buffer has something in it again.

Because the keyboard buffer isn't cleared whatever key is struck when the program executes is displayed. You may tidy this up with another 4 BASIC tokens by adding `:GETA$` to the end of line zero.

The screen shot shows the VIC-20 in action, which by default only has a 22 column display source

---
Tags: code-golf
---


title: Alphabet without the alphabet

text:
# Question
Title: Alphabet without the alphabet
You are tasked with displaying the string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and only that, except for trailing newlines if they're unavoidable.

You must not output any homoglyphic characters like Cyrillic A. You can use non-Unicode encodings, but just to be sure, only output the Latin letters.

Regardless of the encoding you pick, you must not use the characters from U+0041 to U+005A or from U+0061 to U+007A in your source.

No other cheats or loopholes are allowed.

This is a code golf challenge, so the shortest answer wins. However, I won't pick a winner answer since the shortest answer might change over time.

# Answer
> 4 votes
# brainfuck, 35 bytes

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

```

Try it online!

This is the first language I thought of because it is really good for no-letter no-number challenges lol.

# Answer
> 0 votes
# C64Mini/C64 BASIC (and other Commodore/CBM BASIC variants) 24 BASIC tokenized bytes used

In order to meet the criteria of "Regardless of the encoding you pick, you must not use the characters from U+0041 to U+005A or from U+0061 to U+007A in your source" (even though `Unicode` isn't a thing on the Commodore 64), you must enter this in "reverse mode" \[`REVS ON`\] by pressing `CTRL` or `Control` (or the equivalent on your emulator) and `9`.

In the screen shot, the screen codes for each character in my program is displayed after running it as I have read the memory from the start of screen RAM (top-left) (at 0x0400 or 1024) + 31 characters

```
 0FORI=65TO90:?CHR$(I);:NEXT

```

Simply starts from the 8-bit `PETSCII` `A` through to `Z` printing the character code with the `CHR$` command source

---
Tags: code-golf, restricted-source
---


# Question
Title: Find longest consecutive characters in 2D array
**Challenge**

Given a 2D array, find the length and direction of all the longest consecutive characters.

* If there are ties, output *every* possible winning combination in any order, (winners can overlap with other winners)
* Zero "0" is a special padding character which cannot be a winner.
* Code golf rules apply, shortest code wins.

**Output:** n,m,d

(Where *n* is the identified character of length *m* in *d* direction)

Valid characters for *d*: `/|\-.` *See below examples to interpret meaning.*

**Input:** The 2D array input should be in either of the following format, (your preference):

Option 1:

```
123
456
789

```

Option 2\*:

```
[["123"],["456"],["789"]]

```

\*or any combination of "{\[()\]}" characters can be used, with whitespace characters ignored outside of quotes. Quotes can be single or double. The array must read left-to-right, top-to-bottom.

**Assumptions**

* The shape of the array will always be rectangular or square
* There will always be at least one non-zero character
* Array characters will only be alphanumeric

**Examples**

1.

```
0000000
0111100
0000000

```

> 1,4,-

2.

```
00000000
aaaa0000
00bbbbb0

```

> b,5,-

3.

```
0y00x000
aayxaaaz
00xy000z
0x00y00z
x0000y0z

```

> x,5,/
>
> y,5,\

\*(in any order)

4.

```
1111
1111
1111

```

> 1,4,-
>
> 1,4,-
>
> 1,4,-

5.

```
ccc
cwc
ccc

```

> c,3,-
>
> c,3,-
>
> c,3,|
>
> c,3,|

\*(in any order)

6.

```
9

```

> 9,1,.

7.

```
ab
cd

```

> a,1,.
>
> b,1,.
>
> c,1,.
>
> d,1,.

\*(in any order)

# Answer
> 2 votes
# Jelly, ~~52~~ 54 bytes

```
,UŒD€;,Z$ṣ€€”0ŒrẎ€⁺;€"“\/-|”Ẏ2ị$ÐṀ¹F}ḟ”0;€1,”.ʋØ½œị’Ɗ?

```

Try it online!

A monadic link that takes a list of strings and returns. list of maximal outputs each in the order `n, m, d`. A third of the code is to deal with the requirement for dots (last example). Now handles Kevin Cruijssen’s edge case correctly.

# Answer
> 2 votes
# Charcoal, 110 bytes

```
≔⪫Ａ⸿θＰθＦθ«≔⟦⟧ηＦ∧¬№0⸿ι⟦→↘↓↙⟧«≔ＫＤＬθ✳κζＷ›Ｌζ№ζι≔⊟ζε⊞η⟦κιＬζ⟧»¿⁼¹⌈Ｅη§κ²⊞υ⊟ηＦη⊞υκι»⎚≔⌈Ｅυ§ι²εＦΦυ⁼⊟ιε«⊟ι,Ｉε,Ｐ✳⊟ι⎇⊖ε¹.¦⸿

```

Try it online! Link is to verbose version of code. Takes an array of strings as input. Explanation:

```
≔⪫Ａ⸿θＰθ

```

Join the strings with carriage returns (not newlines) and output them without moving the cursor.

```
Ｆθ«

```

Loop over each character in the string.

```
≔⟦⟧η

```

Collect all of the consecutive characters starting at this position in an array.

```
Ｆ∧¬№0⸿ι⟦→↘↓↙⟧«

```

If the current character is not a `0` or a carriage return, then check all four directions.

```
≔ＫＤＬθ✳κζ

```

Peek as much as possible in that direction.

```
Ｗ›Ｌζ№ζι≔⊟ζε

```

Shorten the string until all of the characters are the same.

```
⊞η⟦κιＬζ⟧»

```

Save the results in the array.

```
¿⁼¹⌈Ｅη§κ²⊞υ⊟ηＦη⊞υκ

```

If the maximum consecutive character was 1, then only push one of the results to the final array, otherwise push all of them.

```
ι»

```

Reprint the current character, this time allowing the cursor to move.

Clear the input from the canvas.

```
≔⌈Ｅυ§ι²ε

```

Find the longest consecutive length.

```
ＦΦυ⁼⊟ιε«

```

Loop over the entries with that length.

```
⊟ι,Ｉε,

```

Output the character and length.

```
Ｐ✳⊟ι⎇⊖ε¹.¦⸿

```

If the length is 1 then output a `.` otherwise output a direction character. Then move to the start of the next line for the next result.

# Answer
> 0 votes
# 05AB1E, 82 bytes

```
í‚εεygÅ0«NFÁ]€ø`IIø)εεγJ0K}˜D€gøNUε"/\-|"XèªćÙš]€`D€ÅsZQÏεDÅsi¤'.:]{γεÐнÅsig4÷∍]€`

```

Input as a matrix of characters. Outputs as a list of triples.

Try it online or verify all test cases.

**Explanation:**

Generate all diagonals and anti-diagonals of the input-matrix:

```
í                 # Reverse each row of the (implicit) input-matrix
 ‚                # Pair it with the (implicit) input-matrix
  ε               # Map both matrices to:
   ε              #  Map each row to:
    yg            #   Get the length of the current row
      Å0«         #   Append that many 0s at the end of the row
         NFÁ      #   Rotate the row the 0-based index amount of times towards the right
  ]               # Close the rotate-loop and nested maps
   €ø             # Transpose/zip (swapping rows/columns) for both matrices
     `            # And push both matrices to the stack

```

Put them in a list with the input-matrix itself, as well as all columns of the input-matrix:

```
I                 # Push the input-matrix
 Iø               # Push the input-matrix, and transpose/zip (swapping rows/columns)
   )              # Wrap everything on the stack into a list

```

Now that we have a list of all diagonals, all anti-diagonals, all rows, and all columns, we're going to extract chunks of the same characters, and transform them into the output triplets:

```
ε                 # Map each matrix to:
 ε                #  Map each row to:
  γ               #   Split into chunks of the same elements
   J              #   Join them together to a string
    0K            #   Remove all 0s
 }˜               #  After the map of the rows: deep-flatten all chunks
    €g            #  Get the length of each chunk
   D  ø           #  And pair it with the chunk itself
       NU         #  Store the current index in variable `X`
       ε          #  Map over the chunk and length pairs:
        "/\-|"Xè  #   Get the `X`'th character from the string "/\|-"
                ª #   And append it to the pair
        ć         #   Extract head; push the length plus character pair and chunk
                  #   separately to the stack
         Ù        #   Uniquify the chunk so a single character remains
          š       #   And prepend it back in front of the length & character pair
]                 # Close both maps
 €`               # And then flatten once

```

Now that we have all our triplets, we only leave the largest ones:

```
 €Ås              # Get the middle element (the chunk-length) of each
    Z             # Get the maximum chunk-length (without popping the list itself)
     Q            # Check for each chunk-length if it's equal to this maximum
D     Ï           # And only leave the triplets at the truthy indices

```

And finally we have to fix all `.` edge cases, for chunk-lengths of size 1:

```
ε                 # Map each triplet:
 DÅsi             #  If the middle element (the chunk-length) is exactly 1:
     ¤'.:        '#   Replace the trailing character of the triplet with a "."
]                 # Close the if-statement and map
 {                # Sort the triplets
  γ               # And group them by the exact same triplets
   ε              # Map each chunk of the same triplets to:
    Ð             #  Triplicate the chunk of triplets
     нÅsi         #  If the middle element of each triplet is 1:
         g        #   Get the amount of the same triplets in this chunk
          4÷      #   Integer-divide it by 4
            ∍     #   And shorten the chunk of triplets to that size
   ]              # Close the if-statement and map
    €`            # Flatten once
                  # (after which the result is output implicitly)

```

---
Tags: code-golf, array
---


title: Counting rods; count your rods

text:
# Question
Title: Counting rods; count your rods
## Some background

Counting rods are small bars (3-14 cm long) that were used by mathematicians from many asian cultures for more than 2000 years to represent any whole number or fraction. (In this chqllenge we'l focus on unsigned integers though) There was also a written version, called rod numerals.

## Here's how it works:

(If at any point you get confused, go check out the ascii representation of each digit and some examples I have included at the bottom)

Rod numerals are a true positional numeral system with digits for 1-9 and blank for 0. The digits consist of horizontal and vertical lines; the more lines, the higher the digit. Once you get past five, you put a horizontal line on top to add 5 to the numer of lines below. One vertical line is 1, two vertical lines 2, five vertical lines is 5, one vertical line with a horizontal line on top is 6, four vertical lines with a horizontal line on top is 9 (the highest digit).

A vertical 3 digit:

```
 |||
 |||
 |||
 |||
 |||

```

To make reading rod numerals easier though, they used different notation for each alternating digit. The second notation swaps the role of the horizontal and vertical lines. so that 3 is represented by three horizontal lines and 8 by three horizontal lines with a vertical line on top.

A horizontal 8 digit:

```
  |
  |
__|__
_____
_____

```

Knowing which notation to use is easy, as previously said, tehy are used alternatingly and Sun Tzu wrote that "one is vertical, ten is horizontal". So the rightmost digit is vertical and we alternate from there on.

## The challenge

These rods were used to represent negative numbers and fractions (as explained in the wikipedia article on them. For the purpose of this challenge we'll only focus on positive integers though. The objective is simple:

Write a function or full program that takes an integer value as input in any way and prints the rod numeral representation of this integer to STDOUT (you may also write to a file if that works out better). Shortest code in bytes wins.

Every digit will be represented by 5x5 ascii characters and seperated by two collumns of 5 spaces. The exact representation you'll use for each digit is as follows:

```
space between two digits (two colums):

0 digit, both vertical and horizontal (five columns):

1 digit, vertical:
  |
  |
  |
  |
  |

2 digit, vertical:
 | |
 | |
 | |
 | |
 | |

3 digit, vertical:
 |||
 |||
 |||
 |||
 |||

4 digit, vertical:
|| ||
|| ||
|| ||
|| ||
|| ||

5 digit, vertical:
|||||
|||||
|||||
|||||
|||||

6 digit, vertical:
_____
  |
  |
  |
  |

7 digit, vertical:
_____
 | |
 | |
 | |
 | |

8 digit, vertical:
_____
 |||
 |||
 |||
 |||

9 digit, vertical:
_____
|| ||
|| ||
|| ||
|| ||

1 digit, horizontal:

_____

2 digit, horizontal:

_____
_____

3 digit, horizontal:

_____
_____
_____

4 digit, horizontal:

_____
_____
_____
_____

5 digit, horizontal:
_____
_____
_____
_____
_____

6 digit, horizontal:
  |
  |
  |
  |
__|__

7 digit, horizontal:
  |
  |
  |
__|__
_____

8 digit, horizontal:
  |
  |
__|__
_____
_____

9 digit, horizontal:
  |
__|__
_____
_____
_____

```

The digits are to be printed next to each other. Trailing spaces beyond the bounding box of the last digit are not allowed. Trailing spaces to complete the bounding box of the last digit(s) are required. You should end the output with a single trailing newline. Leading spaces that do not belong to the bounding box of the first digit are also forbidden.

Standard loopholes apply.

## Example output

Lines starting with `>` are to be interpreted as input.

```
>12
        | |
        | |
        | |
        | |
_____   | |

>8037
  |                  _____
  |                   | |
__|__         _____   | |
_____         _____   | |
_____         _____   | |

>950
_____  _____
|| ||  _____
|| ||  _____
|| ||  _____
|| ||  _____

```

# Answer
> 4 votes
# Python 2 - 216

My first shot, might be some stuff to take out, but my brain hurts, so it's good enough for now

```
x=raw_input()
for l in range(5):print'  '.join((' '*7+'|   | |  ||| || '+'|'*7+'__|'+'_'*7)[[7*(4-l<n%6+n/6)+(n>5)*(l<10-n)-(l==10-n),n%6+n/6+(l<1)*(n>5)*(12-n)][(len(x)-i)%2]*5:][:5]for i,n in enumerate(map(int,x)))

```

# Answer
> 2 votes
# JavaScript (ES6) 223

Function with numeric parameter, output to console. NB If the input parameter could be a string, the code would be 5 char shorter and without the limit of 17 significative digits of JS numbers.

```
F=n=>{
  for(r=s='',n+=s;r<5;r++,s+=q)
    for(f=q='\n',p=n.length;f=!f,p--;q=(p?'  ':'')+'     1  |  1 | | 1 ||| 1|| ||1|||||1_____1__|__'.split(1)[d]+q)
      if(d=~~n[p])e=d+r,d=d>5?f?e<10?1:e>10?6:7:r?d-5:6:f?e>4?6:0:d;
  console.log(s)
}

```

**Test**

Test in Firefox console.

`F(12)`

Output

```
        | |
        | |
        | |
        | |
_____   | |

```

`F(8037)`

Output

```
  |                  _____
  |                   | |
__|__         _____   | |
_____         _____   | |
_____         _____   | |

```

`F(950)`

Output

```
_____  _____
|| ||  _____
|| ||  _____
|| ||  _____
|| ||  _____

```

**Ungolfed**

```
F=n=>{
  z='     1  |  1 | | 1 ||| 1|| ||1|||||1_____1__|__'.split(1);
  s='';
  n+=s;

  for (r = 0; r < 5; r++)
  {
    for(q='\n',f=1,p=n.length;f=!f,p--;)
    {
      d = ~~n[p];
      if (d)
      {
        e=d+r;
        if (d > 5)
        {
          if (f)
          {
            d = e < 10 ? 1 : e >10 ? 6 : 7;
          }
          else
          {
            d = r ? d-5 : 6;
          }
        }
        else
        {
          if (f)
            d = e > 4 ? 6 : 0;
        }
      }
      q = (p ? '  ' : '') + z[d] + q;
    }
    s+=q
  }

  console.log(s)
}

```

# Answer
> 1 votes
# PowerShell, 229 bytes

```
$n="$args"
0..4|%{$l=$_;$h=$n.Length%2
($n|% t*y|%{(' '*7+'|   | |  ||| || '+'|'*7+'_'*7+'|__')|% S*g(5*(('0123456666'+'0123451234'*4+'00000611110000661117000666117600666617660666667666')[50*($h=!$h)+10*$l+"$_"]-48))5})-join'  '}

```

Try it online!

Where this string present digits:

```
# 0       1       2       3       4       5       6       7
# '     '.'  |  ',' | | ',' ||| ','|| ||','|||||','_____','__|__'

```

vertical rods:

```
"       |   | |  ||| || |||||||____________________"+   # 0123456666
"       |   | |  ||| || |||||||  |   | |  ||| || ||"+   # 0123451234
"       |   | |  ||| || |||||||  |   | |  ||| || ||"+   # 0123451234
"       |   | |  ||| || |||||||  |   | |  ||| || ||"+   # 0123451234
"       |   | |  ||| || |||||||  |   | |  ||| || ||"    # 0123451234

```

horizontal rods:

```
"                         _____  |    |    |    |  "+   # 0000061111
"                    __________  |    |    |  __|__"+   # 0000661117
"               _______________  |    |  __|_______"+   # 0006661176
"          ____________________  |  __|____________"+   # 0066661766
"     ___________________________|_________________"    # 0666667666

```

Unrolled script:

```
$digits=' '*7+'|   | |  ||| || '+'|'*7+'_'*7+'|__'
$positions = '0123456666'+'0123451234'*4+'00000611110000661117000666117600666617660666667666'

$n="$args"
0..4|%{
    $line=$_
    $horizontal=$n.Length%2
    $chunks=$n|% toCharArray|%{
        $horizontal=!$horizontal
        $startFrom = 5*($positions[50*$horizontal+10*$line+"$_"]-48)
        $digits|% Substring $startFrom 5
    }
    $chunks-join'  '
}

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Parse a C++14 integer literal

text:
# Question
Title: Parse a C++14 integer literal
According to http://en.cppreference.com/w/cpp/language/integer\_literal, integer literals consist of a decimal/hex/octal/binary literal and a optional integer suffix, that is obviously completely unnecessary, wastes precious bytes and is not used in this challenge.

A decimal literal is `a non-zero decimal digit (1, 2, 3, 4, 5, 6, 7, 8, 9), followed by zero or more decimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)`.

A octal literal is `the digit zero (0) followed by zero or more octal digits (0, 1, 2, 3, 4, 5, 6, 7)`.

A hexadecimal literal is `the character sequence 0x or the character sequence 0X followed by one or more hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F)` (note the case-insensitivity of `abcdefx`).

A binary literal is `the character sequence 0b or the character sequence 0B followed by one or more binary digits (0, 1)`.

Additionally, there may optionally be some `'`s as a digit separator. They have no meaning and can be ignored.

## Input

A string that represents a C++14 integer literal or an array of its charcodes.

## Output

The number represented by the input string in base 10, with an optional trailing newline. The correct output never will exceed 2\*10^9

## Winning criteria

The GCC contributors need over 500 lines of code to do this, therefore our code must be as short as possible!

## Test cases:

```
0                       ->    0
1                       ->    1
12345                   ->    12345
12345'67890             ->    1234567890
0xFF                    ->    255
0XfF                    ->    255
0xAbCdEf                ->    11259375
0xa'bCd'eF              ->    11259375
0b1111'0000             ->    240
0b0                     ->    0
0B1'0                   ->    2
0b1                     ->    1
00                      ->    0
01                      ->    1
012345                  ->    5349
0'123'4'5               ->    5349

```

# Answer
# Japt, 6 bytes

```
OxUr"'

```

---

```
OxUr"'  Full Program. Implicit Input U
  Ur"'  Remove ' from U
Ox      Eval as javascript

```

Try it online!
> 6 votes

# Answer
# x86 (32-bit) machine code, ~~59~~ 57 bytes

This function takes `esi` as a pointer to a null-terminated string and returns the value in `edx`. (Listing below is GAS input in AT&T syntax.)

```
        .globl parse_cxx14_int
        .text
parse_cxx14_int:
        push $10
        pop %ecx                # store 10 as base
        xor %eax,%eax           # initialize high bits of digit reader
        cdq                     # also initialize result accumulator edx to 0
        lodsb                   # fetch first character
        cmp $'0', %al
        jne .Lparseloop2
        lodsb
        and $~32, %al           # uppercase letters (and as side effect,
                                # digits are translated to N+16)
        jz .Lend                # "0" string
        cmp $'B', %al           # after '0' have either digit, apostrophe,
                                # 'b'/'B' or 'x'/'X'
        je .Lbin
        jg .Lhex
        dec %ecx
        dec %ecx                # update base to 8
        jmp .Lprocessdigit      # process octal digit that we just read (or
                                # skip ' if that is what we just read)
.Lbin:
        sub $14, %ecx           # with below will update base to 2
.Lhex:
        add $6, %ecx            # update base to 16
.Lparseloop:
        lodsb                   # fetch next character
.Lparseloop2:
        and $~32, %al           # uppercase letters (and as side effect,
                                # digits are translated to N+16)
        jz .Lend
.Lprocessdigit:
        cmp $7, %al             # skip ' (ASCII 39 which would have been
                                # translated to 7 above)
        je .Lparseloop
        test $64, %al           # distinguish letters and numbers
        jz .Lnum
        sub $39, %al            # with below will subtract 55 so e.g. 'A'==65
                                # will become 10
.Lnum:
        sub $16, %al            # translate digits to numerical value
        imul %ecx, %edx
#        movzbl %al, %eax
        add %eax, %edx          # accum = accum * base + newdigit
        jmp .Lparseloop
.Lend:
        ret

```

And a disassembly with byte counts - in Intel format this time, in case you prefer that one.

```
Disassembly of section .text:

00000000 <parse_cxx14_int>:
   0:   6a 0a                   push   0xa
   2:   59                      pop    ecx
   3:   31 c0                   xor    eax,eax
   5:   99                      cdq
   6:   ac                      lods   al,BYTE PTR ds:[esi]
   7:   3c 30                   cmp    al,0x30
   9:   75 16                   jne    21 <parse_cxx14_int+0x21>
   b:   ac                      lods   al,BYTE PTR ds:[esi]
   c:   24 df                   and    al,0xdf
   e:   74 28                   je     38 <parse_cxx14_int+0x38>
  10:   3c 42                   cmp    al,0x42
  12:   74 06                   je     1a <parse_cxx14_int+0x1a>
  14:   7f 07                   jg     1d <parse_cxx14_int+0x1d>
  16:   49                      dec    ecx
  17:   49                      dec    ecx
  18:   eb 0b                   jmp    25 <parse_cxx14_int+0x25>
  1a:   83 e9 0e                sub    ecx,0xe
  1d:   83 c1 06                add    ecx,0x6
  20:   ac                      lods   al,BYTE PTR ds:[esi]
  21:   24 df                   and    al,0xdf
  23:   74 13                   je     38 <parse_cxx14_int+0x38>
  25:   3c 07                   cmp    al,0x7
  27:   74 f7                   je     20 <parse_cxx14_int+0x20>
  29:   a8 40                   test   al,0x40
  2b:   74 02                   je     2f <parse_cxx14_int+0x2f>
  2d:   2c 27                   sub    al,0x27
  2f:   2c 10                   sub    al,0x10
  31:   0f af d1                imul   edx,ecx
  34:   01 c2                   add    edx,eax
  36:   eb e8                   jmp    20 <parse_cxx14_int+0x20>
  38:   c3                      ret

```

And in case you want to try it, here is the C++ test driver code that I linked with it (including the calling convention specification in GCC asm syntax):

```
#include <cstdio>
#include <string>
#include <iostream>

inline int parse_cxx14_int_wrap(const char *s) {
    int result;
    const char* end;
    __asm__("call parse_cxx14_int" :
            "=d"(result), "=S"(end) :
            "1"(s) :
            "eax", "ecx", "cc");
    return result;
}

int main(int argc, char* argv[]) {
    std::string s;
    while (std::getline(std::cin, s))
        std::printf("%-16s -> %d\n", s.c_str(), parse_cxx14_int_wrap(s.c_str()));
    return 0;
}

```

---

-1 byte due to comment by Peter Cordes

-1 byte from updating to use two decrements to change 10 to 8
> 24 votes

# Answer
# JavaScript (Babel Node), 26 bytes

lol x2

```
_=>eval(_.split`'`.join``)

```

Try it online!
> 12 votes

# Answer
# C++ (gcc), ~~141~~ ~~138~~ ~~134~~ 120 bytes

This is a function that takes an array of characters (specified as a pair of pointers to the start and end - using the pair of iterators idiom) and returns the number. Note that the function mutates the input array.

(This does rely on the behavior of gcc/libstdc++ that `#include<cstdlib>` also places the functions in global scope. For strictly standard compliant code, replace with `#include<stdlib.h>` for a cost of one more character.)

Brief description: The code first uses `std::remove` to filter out `'` characters (ASCII 39). Then, `strtol` with a base of 0 will already handle the decimal, octal, and hexadecimal cases, so the only other case to check for is a leading `0b` or `0B` and if so, set the base for `strtol` to 2 and start parsing after the leading 2 characters.

```
#import<algorithm>
#import<cstdlib>
int f(char*s,char*e){e=s[*std::remove(s,e,39)=1]&31^2?s:s+2;return strtol(e,0,e-s);}

```

Try it online.

---

Saved 3 bytes due to suggestion by ceilingcat and some more golfing that followed.

Saved 4 bytes due to suggestions by grastropner.

-2 bytes by Lucas

-12 bytes by l4m2
> 8 votes

# Answer
# Python 2, 32 bytes

```
lambda a:eval(a.replace("'",""))

```

Try it online!

lol

(needs Python 2 because Python 3 changed octal literals to `0o(...)`).
> 5 votes

# Answer
# , ~~79~~ ~~71~~ 69 bytes

```
`+`=strtoi;s=gsub("'","",scan(,""));na.omit(c(+s,sub("..",0,s)+2))[1]

```

Try it online!

`strtoi` does everything except for the base 2 conversions and ignoring the `'`, so there's quite a lot of bytes just to fix those things.

*Thanks to Aaron Hayman for -6 bytes, and inspiring -4 more bytes (and counting!)*

Verify all test cases (old version)
> 4 votes

# Answer
# Perl 5 (-p), 14 bytes

```
y/'/_/;$_=eval

```

TIO
> 4 votes

# Answer
# 05AB1E, ~~16~~ 14 bytes

Saved 2 bytes thanks to *Grimy*

```
''KlÐïK>i8ö}.E

```

Try it online! or as a Test Suite

**Explanation**

```
''K                # remove "'" from input
   l               # and convert to lower-case
    Ð              # triplicate
     ï             # convert one copy to integer
      K            # and remove it from the second copy
       >i  }       # if the result is 0
         8ö        # convert from base-8 to base-10
            .E     # eval

```
> 4 votes

# Answer
# Excel, 115 bytes

```
=DECIMAL(SUBSTITUTE(REPLACE(A1,2,1,IFERROR(VALUE(MID(A1,2,1)),)),"'",),VLOOKUP(A1,{"0",8;"0B",2;"0X",16;"1",10},2))

```

Input from A1, output to wherever you put this formula. Array formula, so use `Ctrl`+`Shift`+`Enter` to enter it.

I added a couple test cases you can see in the image - some early attempts handled all given test cases correctly but got rows 16 and/or 17 wrong.
> 4 votes

# Answer
# x86-64 machine code, 44 bytes

(The same machine code works in 32-bit mode as well.)

@Daniel Schepler's answer was a starting point for this, but this has at least one new algorithmic idea (not just better golfing of the same idea): **The ASCII codes for `'B'` (`1000010`) and `'X'` (`1011000`) give 16 and 2 after masking with `0b0010010`**.

So after excluding decimal (non-zero leading digit) and octal (char after `'0'` is less than `'B'`), we can just set base = `c & 0b0010010` and jump into the digit loop.

Callable with x86-64 System V as `unsigned __int128 parse_cxx14_int(int dummy, const char*rsi);` Extract the EDX return value from the high half of the `unsigned __int128` result with `tmp>>64`.

```
        .globl parse_cxx14_int
## Input: pointer to 0-terminated string in RSI
## output: integer in EDX
## clobbers: RAX, RCX (base), RSI (points to terminator on return)
parse_cxx14_int:
        xor %eax,%eax           # initialize high bits of digit reader
        cdq                     # also initialize result accumulator edx to 0
        lea 10(%rax), %ecx      # base 10 default
        lodsb                   # fetch first character
        cmp $'0', %al
        jne .Lentry2
    # leading zero.  Legal 2nd characters are b/B (base 2), x/X (base 16)
    # Or NUL terminator = 0 in base 10
    # or any digit or ' separator (octal).  These have ASCII codes below the alphabetic ranges
    lodsb

    mov    $8, %cl              # after '0' have either digit, apostrophe, or terminator,
    cmp    $'B', %al            # or 'b'/'B' or 'x'/'X'  (set a new base)
    jb   .Lentry2               # enter the parse loop with base=8 and an already-loaded character
         # else hex or binary. The bit patterns for those letters are very convenient
    and    $0b0010010, %al      # b/B -> 2,   x/X -> 16
    xchg   %eax, %ecx
    jmp  .Lentry

.Lprocessdigit:
    sub  $'0' & (~32), %al
    jb   .Lentry                 # chars below '0' are treated as a separator, including '
    cmp  $10, %al
    jb  .Lnum
    add  $('0'&~32) - 'A' + 10, %al   # digit value = c-'A' + 10.  we have al = c - '0'&~32.
                                        # c = al + '0'&~32.  val = m+'0'&~32 - 'A' + 10
.Lnum:
        imul %ecx, %edx
        add %eax, %edx          # accum = accum * base + newdigit
.Lentry:
        lodsb                   # fetch next character
.Lentry2:
        and $~32, %al           # uppercase letters (and as side effect,
                                # digits are translated to N+16)
        jnz .Lprocessdigit      # space also counts as a terminator
.Lend:
        ret

```

The changed blocks vs. Daniel's version are (mostly) indented less than other instruction. Also the main loop has its conditional branch at the bottom. This turned out to be a neutral change because neither path could fall into the top of it, and the `dec ecx / loop .Lentry` idea for entering the loop turned out not to be a win after handling octal differently. But it has fewer instructions inside the loop with the loop in idiomatic form do{}while structure, so I kept it.

Daniel's C++ test harness works unchanged in 64-bit mode with this code, which uses the same calling convention as his 32-bit answer.

```
g++ -Og parse-cxx14.cpp parse-cxx14.s &&
./a.out < tests | diff -u -w - tests.good

```

Disassembly, including the machine code bytes that are the actual answer

```
0000000000000000 <parse_cxx14_int>:
   0:   31 c0                   xor    %eax,%eax
   2:   99                      cltd
   3:   8d 48 0a                lea    0xa(%rax),%ecx
   6:   ac                      lods   %ds:(%rsi),%al
   7:   3c 30                   cmp    $0x30,%al
   9:   75 1c                   jne    27 <parse_cxx14_int+0x27>
   b:   ac                      lods   %ds:(%rsi),%al
   c:   b1 08                   mov    $0x8,%cl
   e:   3c 42                   cmp    $0x42,%al
  10:   72 15                   jb     27 <parse_cxx14_int+0x27>
  12:   24 12                   and    $0x12,%al
  14:   91                      xchg   %eax,%ecx
  15:   eb 0f                   jmp    26 <parse_cxx14_int+0x26>
  17:   2c 10                   sub    $0x10,%al
  19:   72 0b                   jb     26 <parse_cxx14_int+0x26>
  1b:   3c 0a                   cmp    $0xa,%al
  1d:   72 02                   jb     21 <parse_cxx14_int+0x21>
  1f:   04 d9                   add    $0xd9,%al
  21:   0f af d1                imul   %ecx,%edx
  24:   01 c2                   add    %eax,%edx
  26:   ac                      lods   %ds:(%rsi),%al
  27:   24 df                   and    $0xdf,%al
  29:   75 ec                   jne    17 <parse_cxx14_int+0x17>
  2b:   c3                      retq

```

Other changes from Daniel's version include saving the `sub $16, %al` from inside the digit-loop, by using more `sub` instead of `test` as part of detecting separators, and digits vs. alphabetic characters.

Unlike Daniel's *every* character below `'0'` is treated as a separator, not just `'\''`. (Except `' '`: `and $~32, %al` / `jnz` in both our loops treats space as a terminator, which is possibly convenient for testing with an integer at the start of a line.)

Every operation that modifies `%al` inside the loop has a branch consuming flags set by the result, and each branch goes (or falls through) to a different location.
> 4 votes

# Answer
# Octave, ~~29~~ ~~21~~ 20 bytes

```
@(x)str2num(x(x>39))

```

Try it online!

-8 bytes thanks to @TomCarpenter
> 1 votes

# Answer
# Bash, 33 bytes

```
x=${1//\'};echo $[${x/#0[Bb]/2#}]

```

TIO

# Zsh, ~~29~~ 27 bytes

-2 bytes thanks to @GammaFunction

```
<<<$[${${1//\'}/#0[Bb]/2#}]

```

TIO
> 1 votes

# Answer
# , 48 bytes

```
cut@'0x 16b +0b 2b +0 8b0 '''do@rplc~'+',tolower

```

Try it online!

Eval after string substitution.

```
0XfF -> +16bff -> 255
0xa'bCd'eF -> +16babcdef -> 11259375
0B1'0 -> +2b10 -> 2
0 -> 8b0 -> 0
01 -> 8b01 -> 1
0'123'4'5 -> 8b012345 -> 5349

```
> 1 votes

# Answer
# Retina, 96 bytes

```
T`'L`_l
\B
:
^
a;
a;0:x:
g;
a;0:b:
2;
a;0:
8;
[a-g]
1$&
T`l`d
+`;(\d+):(\d+)
;$.($`*$1*_$2*
.+;

```

Try it online! Link includes test suite. Explanation:

```
T`'L`_l

```

Delete `'`s and convert everything to lower case.

```
\B
:

```

Separate the digits, as any hex digits need to be converted into decimal.

```
^
a;
a;0:x:
g;
a;0:b:
2;
a;0:
8;

```

Identify the base of the number.

```
[a-g]
1$&
T`l`d

```

Convert the characters `a-g` into numbers `10-16`.

```
+`;(\d+):(\d+)
;$.($`*$1*_$2*

```

Perform base conversion on the list of digits. `$.($`*$1*_*$2*` is short for `$.($`*$1*_*$2*_)` which multiplies `$`` and `$1` together and adds `$2`. (`$`` is the part of the string before the `;` i.e. the base.)

```
.+;

```

Delete the base.
> 1 votes

# Answer
# Perl 6, 29 bytes

```
{+lc S/^0)>\d/0o/}o{S:g/\'//}

```

Try it online!

Perl 6 requires an explicit `0o` prefix for octal and doesn't support uppercase prefixes like `0X`.

### Explanation

```
                   {S:g/\'//}  # remove apostrophes
{                }o  # combine with function
     S/^0)>\d/0o/    # 0o prefix for octal
  lc  # lowercase
 +    # convert to number

```
> 1 votes

# Answer
# Go, 75

```
import "strconv"
func(i string)int64{n,_:=strconv.ParseInt(i,0,0);return n}

```
> 0 votes

# Answer
# JavaScript (ES6), 112 bytes

```
n=>+(n=n.toLowerCase().replace(/'/g,""))?n[1]=="b"?parseInt(n.substr(2),2):parseInt(n,+n[0]?10:n[1]=="x"?16:8):0

```
> 0 votes

# Answer
# Jelly, 27 bytes

```
ØDiⱮḢ=1aƲȦ
ṣ”';/Ḋ⁾0o;Ɗ¹Ç?ŒV

```

Try it online!

Almost all of this is handling octal. Feels like it could be better golfed.
> 0 votes

# Answer
# Java, ~~158~~ 154 bytes

This just waiting to be outgolfed. Just tries regexes until something works and default to hex.
-4 bytes thanks to @ValueInk

```
n->{n=n.replace("'","");var s=n.split("[bBxX]");return Long.parseLong(s[s.length-1],n.matches("0[bB].+")?2:n.matches("0\\d+")?8:n.matches("\\d+")?10:16);}

```

Try it online

# Using ScriptEngine, ~~92~~ 87 bytes

Eval train coming through. Technically this is passing the torch to JS, so it's not my main submission.

```
n->new javax.script.ScriptEngineManager().getEngineByName("js").eval(n.replace("'",""))

```

TIO
> 0 votes

# Answer
# Ruby with `-n`, 17 bytes

Just jumping on the `eval` train, really.

```
p eval gsub(?'){}

```

Try it online!
> 0 votes

# Answer
# Java (JDK), 101 bytes

```
n->{n=n.replace("'","");return n.matches("0[bB].+")?Long.parseLong(n.substring(2),2):Long.decode(n);}

```

Try it online!

`Long.decode` deals with all kinds of literals except the binary ones.

Template borrowed from Benjamin's answer
> 0 votes

# Answer
# C (gcc), ~~120~~ 118 bytes

-1 byte thanks to ceilingcat

```
f(char*s){int r=0,c=s[1]&31,b=10;for(s+=2*(*s<49&&(b=c^24?c^2?8:2:16)-8);c=*s++;)r=c^39?r*b+(c>57?c%32+9:c-48):r;c=r;}

```

Try it online!
> 0 votes

# Answer
## C (gcc), ~~101~~ ~~97~~ 83 bytes

```
*d;*s;n;f(int*i){for(s=d=i;*d=*s;d+=*s++>39);i=wcstol(i+n,0,n=!i[1]||i[1]&29?0:2);}

```

Try it online
> 0 votes

# Answer
# C (gcc) / Bash / C++, 118 bytes

```
f(i){asprintf(&i,"echo \"#import<iostream>\nmain(){std::cout<<%s;}\">i.C;g++ i.C;./a.out",i);fgets(i,i,popen(i,"r"));}

```

Try it online!
> 0 votes

# Answer
**PHP - 43 Byte**

```
eval("return ".str_replace($a,"'","").";");

```

Same method as https://codegolf.stackexchange.com/a/185644/45489
> 0 votes

# Answer
# C++, G++, 189 bytes

```
#include<fstream>
#include<string>
void v(std::string s){{std::ofstream a("a.cpp");a<<"#include<iostream>\nint main(){std::cout<<"<<s<<";}";}system("g++ -std=c++14 a.cpp");system("a.exe");}

```

No need for tests

Requires installation of `g++` with C++14 support

Now, explanations :

> It writes a file called `a.cpp`, uses GCC to compile it and gives a file that output the number
> 0 votes

# Answer
# Pyth, 27 bytes

```
Jscz\'?&qhJ\0}@J1r\0\7iJ8vJ

```

Try it online!

Unlike the previous (now deleted) Pyth answer, this one passes all test cases in the question, though it is 3 bytes longer.
> 0 votes

---
Tags: code-golf, parsing
---


title: Generate Aheui Number

text:
# Question
Title: Generate Aheui Number
Make a Number Expression is related : actually, it is also about Aheui. But it just made number expression, but this made real Aheui code.

---

Aheui is esolang written in only Korean character. Because of its nature, Aheui can't use Arabic numbers.

But, of course, there is way to generate number.

## Brief introduction to Aheui

Reading the link above is best, but put it shortly : Aheui is befunge-like esolang : have cursor, every character is instructor, and using stack.

One instructor, looks like , have three part : Initial consonant, vowel, final consonant.

First part, initial consonant, determine what to do.

Here is table of initial consonant that can be useful here:

* : no operation.
* : terminate.
* : pop two number from current stack, than add them, and push to current stack.
* : same as , but multiply instead of add.
* : pop two number from current stack, push `second // first` to current stack.
* : same as , but subtract instead of divide.
* : same as , but modulo instead of divide.
* : push number to current stack. Number is given by final consonant.
* : duplicate top of current stack.
* : swap top two value of current stack.

Second part, vowel, determine momentum. Maybe you just need , go to next.

Last part, final consonant, determine number to used in  commend.

Here is list of final consonant and number.

1. Nothing
2. , ,
3. , ,
4. , , , , , , ,
5. , ,
6.
7. ,
8.
9. ,

Finally,  is printing operator. Your code have to print `망희` or `망하` or whatever after calculation, to print and terminate the program.

## Korean Character

Every Aheui instructor is Korean character.

As I mentioned above, Korean character has three part : Initial consonant(`choseong` or `초성`), Vowel(`jungseong` or `중성`), Final consonant(`jongseong` or `종성`).

Every character has initial consonant and vowel, but final consonant is option.

Korean character in Unicode is from `AC00`() to `D7A3`().

For composing Korean character, look at this webpage for help.

## Question

Input is an positive integer. Generate aheui code that prints given integer, without hardcode every possibility.

You can test your Aheui code at try it online.

## Examples

```
Input | Output | Discription
1 | 반밧나망희 | Put two 2s in stack, divide, print, and halt.
1 | 반반나망희 | Same as above.
1 | 밪반타망희 | Put 3 then 2 in stack, subtract, print, and halt.
3 | 받망희 | Put 3 in stack, print, halt.
3 | 반밧나빠빠다다망희 | Put two 2s in stack, divide, duplicate two times, add two times, print, halt. This is OK, but won't get good point.
72 | 밢밣따망희 | Put 8 and 9 in stack, multiply, print, and halt.
10 | 박밙따망희 | Put 2 and 5 in stack, multiply, print, and halt.

```

## Scoring

Average length of 101 Aheui codes that prints 100 to 200. If score is same, shorter code wins.

# Answer
# Jelly, Score 849/101 = 8.406; 126 bytes of Jelly code

```
9,`€µŒċZ€ṪḢ,0Ɗ¹E?ṭƊ€ż,ƭ€Ɱ€⁾+×ẎF€€ḢV;Ɗ€;@1ị<ɗƇ201FL$Þµ1ịⱮŒQTịµ$3¡Ṣṫ100Ṫ€F€⁵;‘,@⁾+×¤yⱮị⁽ıaD×588+“Ḥþ’Ḣ;+¥“ƲG~ọ’b21¤;ƲƲ¤;€“ẒP“ṃƓ’Ọ

```

Try it online!

A niladic link that returns a list of Jelly strings, one for each Aheui number from 100 to 200. The footer on TIO prepends the total length and the mean length.

Note this is equal in score to attinat’s Mathematica answer, but shorter in code length to generate the Aheui numbers. Full explanation to follow. Uses ㅂ (push), ㄷ (add), ㄸ (multiply) and ㅃ (duplicate) for initial consonants.

Output:

```
8.405940594059405
849
100 - 밖밙빠따따망희
101 - 밖밙따밟빠따다망희
102 - 밨밤밟다따망희
103 - 밙밤따밞밟따다망희
104 - 밤밖밟다따망희
105 - 받밙밞따따망희
106 - 밙빠따밟빠따다망희
107 - 밙밞따밤밟따다망희
108 - 박밨밟따따망희
109 - 밖밞따밟빠따다망희
110 - 바밟다박밟다따망희
111 - 밙밨따밟빠따다망희
112 - 박밞밤따따망희
113 - 밖밤따밟빠따다망희
114 - 밨밞따밤밟따다망희
115 - 받박밞밤따따다망희
116 - 밙밞따밟빠따다망희
117 - 밟밖밟다따망희
118 - 밨밟따밤빠따다망희
119 - 밞밤밟다따망희
120 - 받밙밤따따망희
121 - 박밟다빠따망희
122 - 바박밟다빠따다망희
123 - 밨밞따밟빠따다망희
124 - 박밨밞밤따다따망희
125 - 밙밙빠따따망희
126 - 박밞밟따따망희
127 - 밞밟따밤빠따다망희
128 - 박밤빠따따망희
129 - 밨밤따밟빠따다망희
130 - 바밟다밖밟다따망희
131 - 받박밤빠따따다망희
132 - 박밨따박밟다따망희
133 - 밙박밤빠따따다망희
134 - 박받밤빠따다따망희
135 - 받밙밟따따망희
136 - 밤밤밟다따망희
137 - 밞밤따밟빠따다망희
138 - 박밙밤빠따다따망희
139 - 받밤밤밟다따다망희
140 - 밖밙밞따따망희
141 - 바밖밙밞따따다망희
142 - 박밖밙밞따따다망희
143 - 박밟다밖밟다따망희
144 - 박밤밟따따망희
145 - 밤빠따밟빠따다망희
146 - 박바밤밟따다따망희
147 - 받밞빠따따망희
148 - 바받밞빠따따다망희
149 - 박받밞빠따따다망희
150 - 밙밙밨따따망희
151 - 바밙밙밨따따다망희
152 - 박밖밤밟따다따망희
153 - 밟밤밟다따망희
154 - 박밞따박밟다따망희
155 - 박밟밤밟다따다망희
156 - 박밨따밖밟다따망희
157 - 밖밟밤밟다따다망희
158 - 박밞밤밟따다따망희
159 - 받밖밞빠따다따망희
160 - 밖밙밤따따망희
161 - 바밖밙밤따따다망희
162 - 박밟빠따따망희
163 - 바박밟빠따따다망희
164 - 박바밟빠따다따망희
165 - 박밟다받밙따따망희
166 - 박박밟빠따다따망희
167 - 밙박밟빠따따다망희
168 - 받밞밤따따망희
169 - 밖밟다빠따망희
170 - 바밟다밤밟다따망희
171 - 박밖밟다빠따다망희
172 - 박밙밟빠따다따망희
173 - 밖밖밟다빠따다망희
174 - 박밨밟빠따다따망희
175 - 밙밙밞따따망희
176 - 박밤따박밟다따망희
177 - 박밙밙밞따따다망희
178 - 박밤밟빠따다따망희
179 - 밖밙밙밞따따다망희
180 - 밖밙밟따따망희
181 - 바밖밙밟따따다망희
182 - 박밞따밖밟다따망희
183 - 받밖밙밟따따다망희
184 - 밖바밙밟따다따망희
185 - 밙바밖밟따다따망희
186 - 받밨밞밤따다따망희
187 - 박밟다밤밟다따망희
188 - 밖박밙밟따다따망희
189 - 받밞밟따따망희
190 - 바받밞밟따따다망희
191 - 박받밞밟따따다망희
192 - 받밤빠따따망희
193 - 바받밤빠따따다망희
194 - 박받밤빠따따다망희
195 - 받밙따밖밟다따망희
196 - 밖밞빠따따망희
197 - 바밖밞빠따따다망희
198 - 박밟다박밟따따망희
199 - 받밖밞빠따따다망희
200 - 밙밙밤따따망희

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), score 849/101 = 8.406

```
g@n_:=f@n<>"망히"
f@n_:=f@n=Switch[n,-1,"밯",1,"반반나",9,"밞",8,"밣",7,"밝",6,"밦",5,"발",4,"밗",3,"받",2,"박",
_,mn@{m@n,a@n,s@n}]
m@n_:=m@n=f@#<>If[# #==n,"빠",f[n/#]]<>"따"&/@Select[Divisors@n,1<# #<=n&]//mn
a@n_:=a@n=f@#<>f[n-#]<>"다"&/@Range[⌈n/2⌉-1]//mn
s@n_:=s@n=m[n+#]<>f@#<>"타"&/@Range[n-1]//mn
mn=First@*MinimalBy[StringLength[""<>#]&]

```

Try it online!

Builds numbers with  (+)  (\*)  (-), and  (duplicate), in addition to literals for 2..9. Doesn't actually make use of =-1.

Paste the tio output (Unicode character codes) into Mathematica to see the result:

```
100 -> 밗발빠따따망히
101 -> 박밞박밞다따다망히
102 -> 밦밣밞다따망히
103 -> 받밗발빠따따다망히
104 -> 밣밗밞다따망히
105 -> 받발밝따따망히
106 -> 박밗밝빠따다따망히
107 -> 박받발밝따따다망히
108 -> 박밦밞따따망히
109 -> 밗받발밝따따다망히
110 -> 박발박밞다따따망히
111 -> 받박발밝따다따망히
112 -> 박밝밣따따망히
113 -> 발박밦밞따따다망히
114 -> 박받밦밞따다따망히
115 -> 발박받밝따다따망히
116 -> 박박밝밣따다따망히
117 -> 밞밗밞다따망히
118 -> 박받밝밣따다따망히
119 -> 밝밣밞다따망히
120 -> 받발밣따따망히
121 -> 박밞다빠따망히
122 -> 박발밝밣따다따망히
123 -> 받발밗밞따다따망히
124 -> 박밦밝밣따다따망히
125 -> 발발빠따따망히
126 -> 박밝밞따따망히
127 -> 박발발빠따따다망히
128 -> 박밣빠따따망히
129 -> 받받발밣따다따망히
130 -> 박발밗밞다따따망히
131 -> 받박밣빠따따다망히
132 -> 박밦박밞다따따망히
133 -> 밝박밣밞다다따망히
134 -> 박받밣빠따다따망히
135 -> 받발밞따따망히
136 -> 밣밣밞다따망히
137 -> 박받발밞따따다망히
138 -> 박발밣빠따다따망히
139 -> 받밣밣밞다따다망히
140 -> 밗발밝따따망히
141 -> 받박발밞따다따망히
142 -> 박밝밣빠따다따망히
143 -> 박밞다밗밞다따망히
144 -> 박밣밞따따망히
145 -> 발박받밞따다따망히
146 -> 박밞밣빠따다따망히
147 -> 받밝빠따따망히
148 -> 박박밣밞따다따망히
149 -> 박받밝빠따따다망히
150 -> 발발밦따따망히
151 -> 밗받밝빠따따다망히
152 -> 박밗밣밞따다따망히
153 -> 밞밣밞다따망히
154 -> 박밝박밞다따따망히
155 -> 발받밗밝따다따망히
156 -> 박밦밗밞다따따망히
157 -> 밗밞밣밞다따다망히
158 -> 박밝밣밞따다따망히
159 -> 받밗밝빠따다따망히
160 -> 밗발밣따따망히
161 -> 밝박받밝따다따망히
162 -> 박밞빠따따망히
163 -> 받밗발밣따따다망히
164 -> 밗발밗밞따다따망히
165 -> 받발박밞다따따망히
166 -> 박박밞빠따다따망히
167 -> 발박밞빠따따다망히
168 -> 받밝밣따따망히
169 -> 밗밞다빠따망히
170 -> 박발밣밞다따따망히
171 -> 받받밦밞따다따망히
172 -> 박발밞빠따다따망히
173 -> 밗밗밞다빠따다망히
174 -> 박밦밞빠따다따망히
175 -> 발발밝따따망히
176 -> 박밣박밞다따따망히
177 -> 받받밝밣따다따망히
178 -> 박밣밞빠따다따망히
179 -> 밗발발밝따따다망히
180 -> 밗발밞따따망히
181 -> 밦발발밝따따다망히
182 -> 박밝밗밞다따따망히
183 -> 받발밝밣따다따망히
184 -> 밗밗밦밝따다따망히
185 -> 발박발밝따다따망히
186 -> 받밦밝밣따다따망히
187 -> 박밞다밣밞다따망히
188 -> 밗박발밞따다따망히
189 -> 받밝밞따따망히
190 -> 발박밗밞따다따망히
191 -> 박받밝밞따따다망히
192 -> 받밣빠따따망히
193 -> 밗받밝밞따따다망히
194 -> 박받밣빠따따다망히
195 -> 받발밗밞다따따망히
196 -> 밗밝빠따따망히
197 -> 발받밣빠따따다망히
198 -> 박밞박밞다따따망히
199 -> 받밗밝빠따따다망히
200 -> 발발밣따따망히

```

The lowest number that improves with  is 211, with `받밣밞따따발타` (3\*8\*9-5) beating out `발밠밝따따반반나다` (5\*6\*7+2/2).

The next lowest, 239 (`받밞빠따따밗타`=3\*9\*9-4), didn't require `반반나` in its /-only construction (`받밣밞따밝다따박다`=3\*(8\*9+7)+2).

An earlier version of this program generated /-only constructions.

---

## With `밯=-1` (score unchanged)

```
g@n_:=f@n<>"망히"
f@n_:=f@n=Switch[n,1,"밯",9,"밞",8,"밣",7,"밝",6,"밦",5,"발",4,"밗",3,"받",2,"박",
_,mn@{m@n,a@n,s@n}]
m@n_:=m@n=f@#<>If[# #==n,"빠",f[n/#]]<>"따"&/@Select[Divisors@n,1<# #<=n&]//mn
a@n_:=a@n=f@#<>f[n-#]<>If[#==1,"타","다"]&/@Range[⌈n/2⌉-1]//mn
s@n_:=s@n=m[n+#]<>f@#<>If[#==1,"다","타"]&/@Range[n-1]//mn
mn=First@*MinimalBy[StringLength[""<>#]&]

```

Try it online!

If the program is given no input,  (read a character from input) returns -1, which allows for a one-character `1` literal.

The lowest number that benefits from this is 269, which improves to `발밦밞따따밯다` (5\*6\*9+(-1)) from `박받밣밞빠따다따다` (2+3\*(8+9\*9)).
> 3 votes

---
Tags: number, code-challenge, code-generation
---


title: New Site Design!

text:
# Question
Title: New Site Design!
Unless you have a userscript that modifies the site's design (or even if so), you should have noticed that we have our site design!

(It's November now)

So, to celebrate, let's make a program that retroactively applies this design (oversimplified, of course)!

So, the most important changes are:

* our new name is now Code Golf and Coding Challenges
* our site is no longer the default blue color and is instead a nice dark green

So, given a string, change:

* `PPCG` to `CGCC`
* `Programming Puzzles {non-whitespace} Code Golf` to `Code Golf {same-thing} Coding Challenges` (for example, `Programming Puzzles + Code Golf`, `and Code Golf`, and `& Code Golf` would all be changed to `Code Golf + Coding Challenges`, `and Coding Challenges`, and `& Coding Challenges`.
* `#abc` to `#acb` (swap blue to green and vice versa - just ignore the fact that green shouldn't logically become blue but I don't want to complicate the color shifting)
* `#abcdef` to `#abefcd` (same as above)

Note that for the color swaps, you should accept any hexadecimal digit from `0-9` to `a-f`. You can choose what case of hex digit to require, but it must be consistent and the same from input to output.

Your substitutions can be case-sensitive, and if not, please specify how the output works.

The substitutions should only happen when the string is surrounded by word boundaries (including the start of the `#`). In other words, each of the specified substitutions should only occur if the match is at the edge of the string or is bordered by non-alphanumeric characters (on both sides).

Standard loopholes apply. This is a code-golf challenge, so the shortest code wins!

# Examples

```
PPCG -> CGCC
Programming Puzzles or Code Golf -> Code Golf or Coding Challenges
PPCG stands for Programming Puzzles and Code Golf and its site color is #abf -> CGCC stands for Code Golf and Coding Challenges and its site color is #afb
The color #00f is much more intense than #5568ed -> The color #0f0 is much more intense than #55ed68
Programming Puzzles and No Substitution -> Programming Puzzles and No Substitution
No Substitution and Code Golf -> No Substitution and Code Golf
Programming Puzzles and no substitution Code Golf -> Programming Puzzles and no substitution Code Golf
Code Golf and Programming Puzzles -> Code Golf and Programming Puzzles
Programming Puzzles and Programming Puzzles and Code Golf -> Programming Puzzles and Code Golf and Coding Challenges

```

(for the last test case, it is important to note that the translated string could be translated again but the transformation must be applied *exactly* once)

# Important Update

(Thanks @tsh)

The `Programming Puzzles ... Code Golf` substitution rule can include the other rules inside of it (`Programming Puzzles PPCG Code Golf` is valid). In this case, you may choose whether or not the rules are applied, but it must be deterministic. I'm not requiring that you be consistent between `PPCG` and `#...` because answers seem to implement the rules in my list ordering which results in inconsistencies. This is just a clarification; I believe all current answers remain valid.

# Answer
# Stax, 85 bytes

```
ì▀¼FΣ¼≤C╛╓ÄydîNû►┘Δ▲Bd♫|α╒oñFτ▒t!↑▌╩┘♦pMc6Hèé▄·│╝∙↔¥^4b5╠·9█&╨^╨♂═î£ε■å±«\┴J₧å♠Å≡z╜û♀

```

Run and debug it
> 4 votes

# Answer
# Ruby `-p`, ~~165~~ ~~164~~ 159 bytes

It ended up being very similar to the sed answer, but it abuses Ruby's string interpolation to duplicate the hex group matching `([\da-f]{1,2})` within the third regex three times instead of needing to repeat the whole thing again.

* *-1 byte from @randomdude999.*
* *-5 bytes from leveraging @Xcali's Perl solution*

```
gsub /\bPPCG\b/,"CGCC"
gsub /\bProgramming Puzzles( \S+ )(Code Golf)\b/,'\2\1Coding Challenges'
[1,2].map{|i|gsub /(^|\s)#\K#{'([\da-f]{%d})'%i*3}\b/,'\2\4\3'}

```

Try it online!
> 12 votes

# Answer
# C++ (gcc), ~~270~~ ~~285~~ 283 bytes

Thanks to Neil for pointing out a bug.

-2 bytes thanks to ceilingcat.

```
#import<regex>
#import<string>
auto f=[](auto s){typeof(s)R[][2]{"bPPCG","CGCC","bProgramming Puzzles( \\S+ )(Code Golf)","$2$1Coding Challenges","B#(?=([\\da-f]{3}){1,2}\\b)(.+?)(..??)(..??)","#$2$4$3"};for(auto r:R)s=std::regex_replace(s,std::regex('\\'+*r+"\\b"),r[1]);return s;};

```

Try it online!
> 9 votes

# Answer
# Retina 0.8.2, ~~153~~ 130 bytes

```
\bPPCG\b
CGCC
\bProgramming Puzzles( \S+ )(Code Golf)\b
$2$1Coding Challenges
\B(#(?=([\da-f]{3}){1,2}\b).+?)(..??)(..??)\b
$1$4$3

```

Try it online! Link includes test cases. All substitutions are case sensitive. Assumes normal regex word characters are acceptable so that `\B#` matches only `#`s that don't follow a word character. Edit: Saved 22 bytes thanks to @tsh.
> 6 votes

# Answer
# GNU sed `-E`, 198 chars

```
s/\bPPCG\b/CGCC/g
s/\bProgramming Puzzles( \S* Cod)e Golf\b/Code Golf\1ing Challenges/g
s/((^|\W)#[0-9a-f])([0-9a-f])([0-9a-f])\b/\1\4\3/g
s/((^|\W)#[0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\b/\1\4\3/g

```

Runnable using e.g. `sed -E 'the above'`; newlines can either be included literally, or replaced with `;` if you so wish. Both work.

@HyperNeutrino come on that word boundary rule is stupid. Look what I had to do in the `#` case.

Yes, I didn't even try. :P

+9 by @Value Ink
> 5 votes

# Answer
# 05AB1E, ~~123~~ ~~109~~ ~~105~~ ~~110~~ 114 bytes

```
žKISå_Å¡JεÐć'#QsžhA6£«sSåP*i3äćsRJ«ë"PPCG"Qi"CGCC"]J”–±ÇÀ”DU¡ćsε”ƒËŠˆ”©¡DVćDÁ2ôεðå}ćs_P*YyÊP*i”Âïªï”«s®ý«®ìëyXì]J«

```

+5 bytes fixing test cases like `Programming Puzzles and no substitution Code Golf` and `Programming Puzzles and Programming Puzzles and Code Golf`.
+4 bytes fixing test cases like `color-#00f` (colors with something besides spaces/newlines surrounding it). Thanks to *@Grimy* for bringing this to my attention.

Case-sensitive. Hexadecimal values are with lowercase `abcdef`; `Programming Puzzles ... Code Golf` is in titlecase; `PPCG` is in full uppercase.

**Try it online.**

Definitely not the right language for the job.. Mimicking word-boundaries and replacing `Programming Puzzles \S+ Code Golf`, but not `Code Golf \S+ Programming Puzzles` or `Programming Puzzles \S+ \S+ Code Golf` without any regexes is pretty hard (to do short).. \>.\>

**Explanation:**

```
žK                # Push "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
                  # (NOTE: if '_' also count as word boundary, use `žj` instead)
  IS              # Push the input as a list of characters
    å_            # Check for each character if they are NOT in the string
      Å¡          # Split the (implicit) input on truthy values
        J         # Join each inner character list to a string again
ε                 # Map each word to:
 Ð                #    Triplicate the word
  ć               #    Extract head; push remainder and head separately to the stack
   '#Q           '#    Check if the head equals "#"
    žh            #    Push string "0123456789"
      A6£«        #    Append the first 6 letters of the alphabet: "0123456789abcdef"
   s      sSåP    #    Check if the characters of the remainder are all in this string
   *i             #    If both are truthy:
     3ä           #     Split the 'word' into three parts
                  #      i.e. "#ab12cd" → ["#ab","12","cd"]
       ćs         #     Extract head, and swap
         R        #     Reverse the remainder list
          J«      #     Join them together, and merge them to the head again
    ë"PPCG"Qi     #    Else-if the word is "PPCG":
     "CGCC"       #     Push "CGCC"
                  #    (Implicit else:
                  #      Use the word that's still there from the initial triplicate)
]                 # Close all if statements and the nested map
 J                # Join the mapped words together again
”–±ÇÀ”            # Push dictionary string "Programming Puzzles"
      DU          # Save a copy in variable `X`
        ¡         # Split the string by this
         ćs       # Extract head & swap; pushing head and remainder to the stack
ε                 # Map each substring `y` in the remainder to:
 ”ƒËŠˆ”           #  Push dictionary string "Code Golf"
       ©          #  Save it in variable `®` (without popping)
        ¡         #  Split the current substring we're mapping by it
         DV       #  Save a copy of this list in variable `Y`
           ćD     #  Extract the head and duplicate
                  #  (so the stack is: remainder, head, head)
 Á                #  Rotate the characters in the head-string once towards the right
  2ô              #  Split it into parts of size 2
    εðå}          #  Check in each part if it contains a space
        ćs        #  Extract head and swap again
          _       #  Check if all values are 0
           P      #  And check if this is truthy for all
          *       #  And check if this is truthy, as well as the head
                  #  (this means the current string has a leading and trailing space,
                  #   and no other spaces)
 YyÊP             #   Check that none of the susbtrings in variable `Y`
                  #   are equal to the current substring `y`
 *i               #   If both checks above are truthy:
   ”Âïªï”«        #    Prepend "Coding Challenges" to the duplicated head
          s®ý     #    Join the remainder by variable `®` ("Code Golf")
             «    #    Append it
              ®ì  #    And prepend an additional variable `®` ("Code Golf")
  ë               #   Else:
   y              #    Simply keep the substring `y` as is
    Xì            #    And prepend variable `X` ("Programming Puzzles")
                  #    since we've split by it
]                 # Close all if-else statements and the map
 J                # Join the mapped substrings together to a single string
  «               # And append it to the initially extracted head
                  # (then output the resulting string implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”–±ÇÀ”` is `"Programming Puzzles"`; `”ƒËŠˆ”` is `"Code Golf"`; and `”Âïªï”` is `"Coding Challenges"`.
> 4 votes

# Answer
# Python 2, 240 bytes

```
import re
lambda x,s=re.sub,b='(?<!\w)',e='(?!\w)',h='([\da-f]',t=r'#\1\3\2':s(b+'#%s{2})'%h+h+'{2})%s{2})'%h+e,t,s(b+'#%s)'%h+h+')%s)'%h+e,t,s(b+'Programming Puzzles( \S+ Cod)e Golf'+e,r'Code Golf\1ing Challenges',s(b+'PPCG'+e,'CGCC',x))))

```

Try it online!
> 3 votes

# Answer
# JavaScript (Node.js), 174 bytes

```
s=>s[R='replace'](/\bPPCG\b/g,'CGCC')[R](/\bProgramming Puzzles( \S+ )(Code Golf)\b/g,'$2$1Coding Challenges')[R](/\B#(?=([\da-f]{3}){1,2}\b)(.+?)(..??)(..??)\b/ig,'#$2$4$3')

```

Try it online!
> 3 votes

# Answer
# Pyth, ~~177~~ ~~173~~ ~~162~~ 142 bytes

```
J::jb.z"\\bPPCG\\b""CGCC"." z¶NZI°Pÿúd(MÜ_BöIkxnqä'u)"." s6#~ÍN³=<nñu/GÎg"VS2~:J%"(^|\W)#%s\\b"*3%"([\da-f]{%d})"N$r"\1#\2\4\3"$)J

```

Here's a version without Pyth's string compression mechanisms (aka it's safe to copy-paste):

```
J::jb.z"\\bPPCG\\b""CGCC""\\bProgramming Puzzles( \S+ )(Code Golf)\\b""\\2\\1Coding Challenges"VS2~:J%"(^|\W)#%s\\b"*3%"([\da-f]{%d})"N$r"\1#\2\4\3"$)J

```

Try it online!

This ended up being really long because I tried to be as pedantic as possible with the regexes. I tried to compress every string possible, but most of them either didn't get smaller or couldn't be pasted into TIO properly.

Explanation:

```
J::                      # definition of J to the following 2 regex replacements
   jb.z                  # input to first regex replacement: all input lines joined together
   "\\bPPCG\\b"          # first regex
   "CGCC"                # first replacement
   ."<compressed>"       # second regex: "\\bProgramming Puzzles( \S+ )(Code Golf)\\b"
   ."<compressed>"       # second replacement: "\\2\\1Coding Challenges"
VS2                      # loop twice, N = 1 or 2
  ~:J                    # some weird assignment: J = regex replace in J (would be J := (regex, replacement) if : was python's regex replace operator)
    %                    # third regex: string format
     "(^|\W)#%s\\b"      # format string
     *3                  # repeat 3 times:
       %"([\da-f]{%d})"N # string format, replace %d with N (the loop counter)
    $r"\1#\2\4\3"$       # third replacement: uses python raw literals because it's shorter than escaping the backslashes
    )                    # end for loop
J                        # print J

```
* -11 thanks to a better regex from Value Ink's Ruby answer
* -20 thanks to using a loop for both of the hex replacements, inspired by the Ruby and Perl answers
> 2 votes

# Answer
# Perl 5 `-p`, ~~152~~ 145 bytes

*@ValueInk saves 7 bytes*

```
s/\bPPCG\b/CGCC/g;s/\bProgramming Puzzles( \S+ )(Code Golf)\b/$2$1Coding Challenges/g;for$a(1,2){$p="([a-f0-9]{$a})"x3;s/(^|\s)#\K$p\b/$2$4$3/gi}

```

Try it online!
> 1 votes

# Answer
# Java 8, 192 bytes

```
s->s.replaceAll("\\bPPCG\\b","CGCC").replaceAll("\\bProgramming Puzzles( \\S+ )(Code Golf)\\b","$2$1Coding Challenges").replaceAll("\\B(#(?=([0-9a-f]{3}){1,2}\\b).+?)(..??)(..??)\\b","$1$4$3")

```

Port of *@Neil*'s Retina answer, so make sure to upvote him!

Try it online.
> 0 votes

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