title: Reverse the consonants

text:
# Question
Title: Reverse the consonants
The program should take a string as input and reverse the consonants in it, while keeping the order of vowels. All the letters will be lowercase, so you don't have to worry about casing. Examples follow.

1. Input: `a test case`.
The consonants here are `t,s,t,c,s`. They should come in reversed order, i.e. `s,c,t,s,t` and inserted back into the string to the same positions where the pre-reversed characters were located: `a sect sate`.
2. Input: `well-done`. Output: `nedl-lowe`.
3. Input: `reverse the consonants`. Output: `setenne sne cohtosarvr`.

This is the code golf, the shortest solution wins.

`Y` should be considered vowel regardless of what it is and not reversed.

Anything, as well as numbers, punctuation, quotes, and other symbols (`@#$%^&*(){}[]\|/<>~-_+=``), could potentially appear in the input.

# Answer
# Retina, ~~22~~ ~~21~~ ~~20~~ 17

```
O#^`[b-z-[eiouy]]

```

Try it online!

1 byte thanks to Leaky Nun!

4 bytes thanks to Martin!

`O` means sort, and `#` means to sort by numeric value. Since none of the matched characters will ever have a numeric value, all letters have the same weight: 0. `^` means to reverse the order of the sorted values, which thanks to stable sorting means the values are reversed.

The `-[...]` means to do the setwise difference between the outer character class and this inner class. This is part of .NET and you can read more at the MSDN.
> 16 votes

# Answer
## Python 2, 86 bytes

```
s='';c=()
for x in input():b='{'>x not in'aeiouy'<x;s+=b*'%s'or x;c=(x,)*b+c
print s%c

```

Takes input as a string in quotes. Iterates through the input, replacing each consonant with `%s` in `s`. The tuple `c` stores the consonants encountered in reversed order. Then, string formatting replaces the `%s`'s in `s` with the consonants in `c`.

Thanks to Sp3000 for the consonant check, which saved 4 bytes over listing the consonants.
> 15 votes

# Answer
# Jelly, ~~22~~ 20 bytes

```
Øaḟ“<1Ṛż»
e€¢œpżf¢Ṛ$

```

Try it online!

### How it works

```
Øaḟ“<1Ṛż»   Helper link. No arguments.

Øa          Yield the lowercase alphabet/
   “<1Ṛż»   Decompress that string, yielding "oui aye".
  ḟ         Filter; remove the characters from the right string from the left one.

e€¢œpżf¢Ṛ$  Main link. Argument: s (string)

  ¢         Call the helper link, yielding the string of all consonants.
e€          Test each character of s for membership.
   œp       Partition s at members/consonants.
         $  Combine the three links to the left into a monadic chain.
      f¢    Filter by presence in the consonant string.
        Ṛ   Reverse the result.
     ż      Zipwith; interleave chunks of non-consonants and reversed consonants.

```
> 9 votes

# Answer
# JavaScript ES6, ~~82~~ ~~81~~ ~~80~~ 78 bytes

Saved a byte thanks to each of Martin and Leaky Nun, and 2 bytes to Neil!

```
a=>a.replace(r=/(?[_aeiouy])\w/g,e=>[...a].reverse().join``.match(r)[i++],i=0)

```

## Testing

```
f=
a=>a.replace(r=/(?![aeiouy])[a-z]/g,e=>[...a].reverse().join``.match(r)[i++],i=0)
;
q.onchange=q.onkeydown=q.onkeyup=function(){
  o.innerHTML = "";
  o.appendChild(document.createTextNode(f(q.value)));
}
```

```
*{font-family:Consolas,monospace;}
```

```
<input autocomplete="off" id=q>
<div id=o></div>
```
> 6 votes

# Answer
# GNU sed, 73

Score includes +1 for the `-r` flag passed to sed.

```
:
s/([b-df-hj-np-tv-xz])(.*)([b-df-hj-np-tv-xz])/\u\3\2\u\1/
t
s/./\l&/g

```

Ideone.

Repeatedly switches the first and the last lowercase consonant and converts them to upper case, until there are no more matches. Then convert the whole string back to lowercase.
> 5 votes

# Answer
# Python 2, 106 bytes

```
s=input()
b=[x for x in s if x in'bcdfghjklmnpqrstvwxz']*2
print''.join(x in b and b.pop()or x for x in s)

```

Expects input in `"quotes"`, which I think is allowed.
> 5 votes

# Answer
## Pyke, 18 bytes

```
FD~c{IK_#~c{)oR@(s

```

Try it here!

or 16 bytes with the new version:

(Change so if for returns all string output and had string input, return string instead of a list)

```
FD~c{IK_#~c{)oR@

```

Try it here!

`~c` contains the consonants: `bcdfghjklmnpqrstvwxz`

```
F                - For i in input:
  ~c{I           -  if i in "bcdfghjklmnpqrstvwxz":
       _#~c{)    -    filter(reversed(input), <-- in "bcdfghjklmnpqrstvwxz")
             oR@ -   ^[o++]

```
> 4 votes

# Answer
# MATL, ~~18~~ ~~22~~ 21 bytes

```
tt2Y211Y2'y'hX-m)P5M(

```

*1 byte saved thanks to @Luis*

Unfortunately the longest part of this is getting the list of consonants (`2Y211Y2'y'hX-`).

**Try it Online!**

**Explanation**

```
            % Implicitly grab the input
tt          % Duplicate twice
2Y2         % Grab the pre-defined list of all lower-case letters
llY2        % Grab the pre-defined list of lower-case vowels (excluding 'y')
'y'h        % Add 'y' to the list of vowels
X-          % Find the set difference between these two lists (the consonants)
m           % Create a boolean array the size of the input that is true for all consonants
)           % Use this as an index to grab all consonants
P           % Reverse the order of the consonants
5M          % Get the boolean array again
(           % Re-assign the flipped consonants with the original consonant locations
            % Implicitly dislpay the result

```
> 4 votes

# Answer
## JavaScript (ES6), 72 bytes

```
s=>s.split(/([^\W\d_aeiouy])/).map((c,i,a)=>i&1?a[a.length+~i]:c).join``

```

Splitting on `/([^\W\d_aeiouy])/` results in the consonants falling in the odd-numbered entries in the array. It then suffices to switch those entries with the equivalent entry counting back from the end of the array and join the result together.
> 4 votes

# Answer
# Ruby, ~~53~~ ~~50~~ 47 bytes

*-3 bytes from @manatwork. -3 bytes from @Jordan.*

```
->s{a=s.scan r=/[^\Waeiouy_]/
s.gsub(r){a.pop}}

```

Attempt This Online!
> 4 votes

# Answer
# J, 53 bytes

```
C.~[:~.<@~.@/:~"1@(,.|.)@I.@e.&'bcdfghjklmnpqrstvwxz'

```

Maybe the not the best way but I wanted to use `C.` since this can be solved using permutations.

## Usage

```
   f =: C.~[:~.<@~.@/:~"1@(,.|.)@I.@e.&'bcdfghjklmnpqrstvwxz'
   f 'a test case'
a sect sate
   f 'well-done'
nedl-lowe
   f 'reverse the consonants'
setenne sne cohtosarvr

```

## Explanation

```
C.~[:~.<@~.@/:~"1@(,.|.)@I.@e.&'...'  Input: s
                               '...'  The list of consonants
                            e.&'...'  Generate a boolean mask where an index is true
                                      if the char at that index in s is a consonant
                         I.@          Get a list of the true indices
                  (  |.)@             Reverse that list
                  (,.  )@             Join the original and reversed list as columns
            /:~"1@                    Sort each row of that 2d list
         ~.@                          Take the distinct values in each row
       <@                             Box them
   [:~.                               Take the distinct boxes - Now represents the
                                      permutation needed to solve this in cycle notation
C.~                                   Permute s according the cycles and return

```
> 4 votes

# Answer
# Perl 5 (58 + 4 = 62 bytes)

```
$_=<>;$r=qr/(?![eiouy])[b-z]/;@a=/$r/g;s/$r/pop@a/ge;print

```

+4 penalty for running with `-0777` flag, which sets Perl to slurp mode to handle newlines correctly.

Accepts input through STDIN and prints to STDOUT.

## Explanation

```
                   $_=<>;   Read the input
 $r=qr/(?![eiouy])[b-z]/;   Save the regex; we'll be using it twice
                @a=/$r/g;   Store all the consonants in an array
           s/$r/pop@a/ge;   Replace each consonant with the final value in the array and pop
                   print    Output the result

```
> 4 votes

# Answer
# Perl 5, ~~92~~ ~~68~~ 55 bytes

Saved **37** bytes thanks to @manatwork's help. ;-)

```
$_=<>;@b=@a=/[^\Waeiou]/g;print$_~~@b?pop@a:$_ for/./g

```

A translation of @Lynn Python solution to Perl.
> 4 votes

# Answer
# JavaScript (ES6), 57 ~~70~~

**Edit** Amazing 20% saving thx @Neil

Late to the party, but it seems all javascript people missed something

```
a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r))

```

*Test*

```
f=a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r))

function test() {
  var i=I.value
  O.textContent=f(i)
}

test()
```

```
#I { width:90% }
```

```
<input id=I oninput="test()" value="reverse the consonants."><pre id=O></pre>
```
> 4 votes

# Answer
# Pyth, ~~26~~ ~~25~~ ~~24~~ 23 bytes

```
~~s.i:Q++\[J-G"aeiouy"\]3_@J~~
J-G"aeiouy"sm?@dJ@_@JQ~hZ     <-- just keeping this because of the @_@
~~J-G"aeiouy"sm?@dJ@@JQ=tZ~~
sm?@dJ-G"aeiouy"@@JQ=tZ
sm|-dJ-G"aeiouy"@@JQ=tZ

```

Test suite.
> 3 votes

# Answer
# Java, 319 305 261 188 bytes

Credit to @Leaky Nun for helping with this :-)

```
char[]r(char[]s){int i=0,j=0,n=s.length;char[]o=new char[n];for(;i<n;i++){if((s[i]+"").matches("(?![eiouy])[b-z]")){o[j++]=s[i];s[i]=65;}}for(i=0;i<n;i++)if(s[i]==65)s[i]=o[--j];return s;}

```

Old:

```
s(String p){int i=0,j=0;char[]s=p.toCharArray(),o=p.toCharArray();for(;i<s.length;i++){if(((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]")))continue;o[j++]=(s[i]);s[i]='A';}for(i=0;i<s.length;i++)if(s[i]=='A')s[i]=o[--j];return new String(s);}

```

Inspiration taken from **here**

### Ungolfed

```
String s(String p){
    int i = 0, j = 0;
    char[]s=p.toCharArray(),o=p.toCharArray();
    for (;i<s.length;i++) {
        if (((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]"))) continue;
        o[j++] = (s[i]); // Store the consonant into o
        s[i] = 'A'; // Put a special character in its place
    }
    for (i=0;i<s.length;i++)
        if (s[i] == 'A') // If special character
            s[i] = o[--j]; // Put back the consonant in reverse order
    return new String(s);
}

```
> 3 votes

# Answer
# Julia, 53 bytes

```
!s=s[flipud(i)]=s[i=find(c->'}'>c∉"aeiouy"<"$c",s)]

```

This takes a character array as input and reverses its consonants in-place. Try it online!

*Credit goes to @Sp3000 for the lowercase consonant check.*

### How it works

`i=find(...,s)` yields all indices of **s** for which the predicate *...* returns **true** and saves them it the variable **i**.

`c->'}'>c∉"aeiouy"<"$c"` performs three tests and returns **true** if and only if all are positive.

* `'}'>c` checks if the character **c** comes before **{**.
* `"aeiou"` checks if the *string* **c** comes after **a**.
* `c∉"aeiouy"` verifies that **c** is not a vowel.

Finally, `s[i]` yields all consonants and `s[flipud(i)]=s[i]` assigns them to positions in **s** that correspond to the reversed indices in in **i**.
> 3 votes

# Answer
# R, 120 bytes

New answer:

```
az=function(x){
y=strsplit(x, NULL)[[1]]
a=regexpr("[bc-df-hj-np-tv-z]", y)
y[a==1]=rev(y[a==1])
paste(y, collapse="")
}

```

takes a character string as x

```
az("reverse the consonants")
[1] "setenne sne cohtosarvr"

```

Old response below (110 bytes) was poor form on my part, which just reversed the consonants:

```
xrev=function(x){y=rev(strsplit(x, NULL)[[1]])
paste(y[is.na(match(y, c("a", "e","i","o","u","y")))], collapse="")}

```
> 3 votes

# Answer
## Python 2, ~~103~~ ~~98~~ 100 bytes

```
import re
def r(s):a=re.split("([^\W\d_aeiouy])",s);print''.join(sum(zip(a[::2],a[-2::-2]+['']),()))

```

Port of my JavaScript answer. Edit: Saved 5 bytes thanks to @Dennis♦, of which I promptly had to spend two fixing digits.
> 2 votes

# Answer
# APLX, 31 bytes

```
(c/t)←⌽t/⍨c←(t←⍞)∊⎕a~'aeoiuy'
t

```

`⎕a~'aeoiuy'` lowercase alphabet without vowels
`t←⍞` store character input as *t*
`c←(``)∊` store Boolean "consonant?" as *c*
`t/⍨` extract (consonants) from *t*
reverse
`(c/t)←` replace consonants with (the reversed ones)
`t` return the modified string
> 2 votes

# Answer
# s-lang, ~~17~~ 16 bytes (non-competing)

*Saved one byte because s-lang no longer requires last argument bracket*

### Try it online!

```
r[(?![aeiouy])\w

```

I started working on a string manipulation golfing language (I have been wanting to do this for a time now), and I thought this would be a fun question to work on it with.

## Explanation:

* `r` reverses the string with a given regex character matcher (if no regex argument is given, it will default to `.`)
* `[` begins the optional regex argument for `r`
* `(?![aeiouy])\w` the regex to match any consonant character excluding y (unfortunately JavaScript doesn't allow character class subtraction)
* `]` usually ends optional regex argument for `r`, but we don't need it since it is the last function and last argument
> 2 votes

# Answer
# 05AB1E, 11 bytes

```
.āžPIåÏø`Rǝ

```

I/O as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
.ā          # Enumerate the (implicit) input, pairing each character with its index
  žP        # Push the consonants constant (excluding 'y'): "bcdfghjklmnpqrstvwxz"
    I       # Push the input
     å      # Check for each character if it's in the consonants string
      Ï     # Keep the enumerated pairs at the truthy indices
       ø    # Zip/transpose; swapping rows/columns
        `   # Dump the list of consonants and list of indices separated to the stack
         R  # Reverse the list of indices
          ǝ # Insert the consonants at the (reversed) indices in the (implicit) input
            # (after which the result is output implicitly)

```
> 2 votes

# Answer
## Matlab, 67 chars

For an input `'this is a string of- stuff.'`

```
s=input('','s');si=regexp(s,'[b-df-hj-np-tv-xz]');s(si)=s(flip(si))

```

produces `s = ffit is a fgnirt os- ssuht.`

`si` is the indices of the consonants in the input string. The final statement replaces those characters with the same characters but in reverse order by indexing.
> 1 votes

# Answer
## Python 2.7, 144 bytes

```
def f(a):c='bcdfghjklmnpqrstvwxz';b=[x for x in list(a[::-1])if x in c];[b.insert(x,a[x])for x in range(len(a))if a[x]not in c];return''.join(b)

```

This first builds a reversed list of the consonants, then inserts each of the other characters back in at their original index.

Un-golfed:

```
s = 'well-done'
reverse = list(s[::-1])
consonants = [i for i in reverse if i in 'bcdfghjklmnpqrstvwxz']

for x in range(len(s)):
    if s[x] not in 'bcdfghjklmnpqrstvwxz':
        consonants.insert(x,s[x])

print(''.join(consonants))

```

https://repl.it/C30O
> 1 votes

# Answer
# Mathematica 216 bytes

```
Module[{h,v,i},v=Characters["aeiouy "];h[s_]:=SortBy[Flatten[Thread/@Transpose@{v,#[[All,1]]&/@(StringPosition[s,#]&/@v)},1],Last];i[s_,{a_,n_}]:=StringInsert[s,a,n];Fold[i,StringReverse@StringReplace[#,v->""],h@#]]&

```
> 1 votes

# Answer
# Haskell, ~~157~~ 131 bytes

```
k="bcdfghjklmnpqrstvwxz";f c((r:q),s)=if c`elem`k then(q,r:s)else(r:q,c:s);f c("",s)=("",c:s);g s=snd$foldr f(filter(`elem`k)s,"")s

```

**Update**

@atlasologist's solution made me realize I only need a list of the consonants instead of pairs (no need to reverse them though since I'm using right fold.)

**Ungolfed**

```
consonants = "bcdfghjklmnpqrstvwxz"

-- Combining function (right fold, improved)
f :: Char -> (String, String) -> (String, String)
f c ((r:rest), s) = if c `elem` consonants then (rest, r:s) else (r:rest, c:s)
f c ("", s) = ("", c:s)

transform :: String -> String
transform s = snd $ foldr f (filter (`elem` consonants) s, "") s

main = do
    line <- getLine
    putStrLn . transform $ line

```

---

**Old**

```
c="bcdfghjklmnpqrstvwxz";n c(a@((f,t):q),s)=if c==f then(q,t:s)else(a,c:s);n c([],s)=([],c:s);g s=let z=filter(`elem`c)s in snd$foldr n(zip (reverse z)z,"")s

```

Creates a list of pairs of consonants, then walks through the string replacing each consonant using said list.

A bit primitive, but I wanted to figure this out without looking at the answers first. :)
> 1 votes

# Answer
# PowerShell, 81 bytes

```
-join(($a=$args|% t*y)|%{if($_-in($c=$a-match'[^\W\d_aeiouy]')){$_=$c[--$i]};$_})

```

Try it online!

Less golfed:

```
$a          = $args|% toCharArray
$consonants = $a-match'[^\W\d_aeiouy]'
$result     = $a|%{if($_-in$consonants){$_=$consonants[--$i]};$_}
-join($result)

```

---

# PowerShell, 88 bytes, -f

```
$i=0;-join($args|% t*y|%{if($_-match'[^\W\d_aeiouy]'){$c=,$_+$c;$_="{$i}";$i++};$_})-f$c

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Extended), 22 bytes

```
⌽@(('aeiou'~⍨∘⌊⎕A)∊⍨⊢)

```

Try it online!
> 1 votes

# Answer
# Raku, ~~48~~ 46 bytes

```
{my$r=/<:L-[aeiouy]>/;S:g[$r]=pop @||=m:g/$r/}

```

Try it online!

* `$r` is set to a consonant-matching regex.
* `@ ||= m:g/$r/` stores the consonants in the input string in the anonymous state array `@`, if it's empty.
* `S:g[$r] = pop ...` replaces each consonant with the consonant popped off the end of the array into which all of the consonants were stored initially.
> 1 votes

# Answer
# q/kdb+, 45 bytes

**Solution:**

```
{x[w]:x(|)w:(&)max x=/:.Q.a except"aeiouy";x}

```

**Explanation:**

Find indices of the consonants, and replace them with the reversed consonants:

```
{x[w]:x reverse w:where max x=/:.Q.a except "aeiouy";x} / ungolfed
{                                                   ; } / two-statement lambda
                                .Q.a except "aeiouy"    / alphabet (a..z) except vowels
                            x=/:                        / equals each-right (returns boolean lists where input is each a consonant)
                        max                             / 'or' the results together
                  where                                 / indices where results are true
                w:                                      / save in variable w
        reverse                                         / reverse this list
      x                                                 / index into input at these indices
 x[w]:                                                  / assign values to x at indices w
                                                     x  / return x

```

**Notes:**

I had 3 ways to build the consonant list, the one in the solution is slightly better than the alternatives:

* `"bcdfghjklmnpqrstvwxz"` for 22 chars (most boring)
* `.Q.a _/0 3 6 11 16 19` for 21 chars (kinda cool, drop each index)
* `.Q.a except"aeiouy"` for 19 chars (second most boring)
> 0 votes

# Answer
# Jq 1.5, ~~289~~ 263 bytes

```
def C:"bcdfghjklmnpqrstvwxz";. as$s|[("^","")as$p|[match("([\($p)\(C)]+)";"g").captures[].string]]|.[1]|=(reduce map(length)[]as$l({s:add|explode|reverse|implode,r:[]};.r+=[.s[0:$l]]|.s=.s[$l:])|.r)|if$s[0:1]|inside(C)then[.[1,0]]else . end|transpose|map(add)|add

```

Explanation

```
def consonants:"bcdfghjklmnpqrstvwxz";

  . as $s
| [  ("^","") as $p                                              # parse string onto non-consonant
   | [match("([\($p)\(consonants)]+)";"g").captures[].string]]   # and consonant groups
| .[1] |= (
     reduce map(length)[] as $l (                                # build new for consonant groups
       {s:add|explode|reverse|implode,r:[]}                      # by adding groups from reversed string
     ; .r+=[.s[0:$l]] | .s=.s[$l:]
     )
     |.r
  )
| if $s[0:1]|inside(consonants) then  [.[1,0]] else . end        # put groups into proper order for merge
| transpose | map(add) | add                                     # merge groups into final string

```

Sample run

```
$ jq -MRr 'def C:"bcdfghjklmnpqrstvwxz";. as$s|[("^","")as$p|[match("([\($p)\(C)]+)";"g").captures[].string]]|.[1]|=(reduce map(length)[]as$l({s:add|explode|reverse|implode,r:[]};.r+=[.s[0:$l]]|.s=.s[$l:])|.r)|if$s[0:1]|inside(C)then[.[1,0]]else . end|transpose|map(add)|add' input
a sect sate
nedl-lowe
setenne sne cohtosarvr

```

Try it online
> 0 votes

# Answer
# Java 8, 157 bytes

```
s->s.format(s.replaceAll("[^\\W\\d_aeiouy]","%s"),s.chars().mapToObj(c->""+(char)c).filter(c->c.matches("[^\\W\\d_aeiouy]")).reduce("",(x,y)->y+x).split(""))

```

Try it online!
Note: prints compiler warnings to stderr.
**Explanation:**

```
s->                                                    // Lambda function
    s.format(                                          // Format a string using the given arguments
        s.replaceAll("[^\\W\\d_aeiouy]","%s"),         // Generate the format string by replacing all consonants with "%s"
        s.chars()                                      // Stream the characters of the input string s
            .mapToObj(c->""+(char)c)                   // Map characters back to strings
            .filter(c->c.matches("[^\\W\\d_aeiouy]"))  // Filter out vowels and symbols
            .reduce("",(x,y)->y+x)                     // Build the string of consonants in reverse
            .split("")                                 // Turn into an array of single-char strings (varargs abuse)
    )                                                  // Implicit return of the formatted string

```

Not gonna lie, my only goal was to beat this answer
> 0 votes

# Answer
# Rust, 209 bytes

```
|o:&[char]|{let p:Vec<_>=(0..o.len()).filter(|&i|"tkmpbxvwzfgsnqrcdljh".contains(o[i])).collect();(0..o.len()).map(|i|&o[if let Some(j)=p.iter().position(|&k|k==i){p[p.len()-j-1]}else{i}]).collect::<String>()}

```

Attempt This Online!
> 0 votes

# Answer
# Vyxal, 9 bytes

```
‡k¹↔ḟ~İṘȦ

```

Try it Online!
> 0 votes

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


title: Square from Digits with Largest Sum

text:
# Question
Title: Square from Digits with Largest Sum
You should write a program or function which receives a list of digits as input and outputs or returns the largest sum achievable by putting these digits in a square.

Input will always contain a square number of digits. An example square arrangement for the input `9 1 2 3 4 5 6 7 7` could be

```
677
943
125

```

The sum is calculated as the sum of all rows and columns. For the above arrangement the sum would be `677 + 943 + 125 + 691 + 742 + 735 = 3913`. Note that this is not the maximal sum so this isn't the expected output.

## Input

* A list with length `n^2` (`n>=1`) containing non-zero digits (`1-9`).

## Output

* An integer, the largest sum achievable with the input digits put in a square.

## Examples

Example format is `input => output`.

```
5 => 10

1 2 3 4 => 137

5 8 6 8 => 324

9 1 2 3 4 5 6 7 7 => 4588

2 4 9 7 3 4 2 1 3 => 3823

8 2 9 4 8 1 9 3 4 6 3 8 1 5 7 1 => 68423

5 4 3 6 9 2 6 8 8 1 6 8 5 2 8 4 2 4 5 7 3 7 6 6 7 => 836445

```

This is code golf so the shortest entry wins.

# Answer
# Pyth, 15 bytes

```
s*VSsM^^LTUQ2SQ

```

Demonstration. Test harness.

Note: Input in any python sequence format, such as `a,b,c,` or `[a, b, c]`. Fails on `a`.

This will be an explanation for the example input `5,8,6,8`.

`^LTUQ`: This is a list of powers of 10, out to the length of `Q`. `[1, 10, 100, 1000]`.

`^ ... 2`: Then, we take pairs of powers of 10. `[[1, 1], [1, 10], ...`.

`sM`: Then, we sum those pairs. `[2, 11, 101, ...` Each number repesents the value of a grid location. The value of the bottom right corner is 2, because the digit placed there is in the ones place of the two numbers it is in. Note that 16 values were generated, even though we only need 4. This will be handled shortly.

`S`: Sort the value in increasing order. `[2, 11, 11, 20, 101, ...`. Note that the only values which are relevant for this input are the first 4, because this square will not have hundreds or thousands places.

`SQ`: Sort the input in ascending order. `[5, 6, 8, 8]`

`*V`: Vectorized multiplication over the two lists. Pyth's vectorized multiplication truncates the longer input, so this performs `[5*2, 6*11, 8*11, 8*20]`, equivalent to filling in the grid, smallest to largest, bottom right to top left.

`s`: Sum the results, `324`. Printing is implicit.
> 7 votes

# Answer
# CJam, 23 bytes

```
q~$_,mQ,A\f#2m*::+$.*:+

```

Try it online. Generates the weights for each cell and assigns the highest digits to the highest weights.

An alternative 23:

```
q~$_,mQ_,A\f#*_$.+$.*:+

```
> 4 votes

# Answer
# CJam, 25 bytes

```
q~_e!\,mqf/{_z+Afb:+}%$W=

```

Pretty straight forward approach. Generate all combinations, get the sum, print largest.

Try it online here
> 2 votes

# Answer
# Vyxal `G`, 8 bytes

```
Ṗƛ²:∩J⌊∑

```

Try it Online!

Brute force, so pretty slow.

```
Ṗƛ²:∩J⌊∑
Ṗ          # get all permutations
 ƛ         # map over them:
  ²        #  format as a square (returns a list of strings)
   :∩J     #  append the transpose to itself
      ⌊     #  convert each string to an integer
       ∑   #  sum
           # G flag gets the maximum

```
> 1 votes

# Answer
# Husk, 16 bytes

```
▲moS(ṁd+)TSCo√LP

```

Try it online!

# Husk, 16 bytes

```
Σz*O¹OmΣπ2↑:1İ⁰L

```

Try it online!

same idea as isaacg's answer.

Somehow both of these are still 1 byte more than Pyth.
> 0 votes

# Answer
# Japt `-x`, 13 bytes

Tried a few different approaches with permutations and partitions but, in the end, an adaptation of isaacg's solution ended up being the shortest.

```
ñ í*¡ApYÃï+ ñ

```

Try it or run all test cases

```
ñ í*¡ApYÃï+ ñ     :Implicit input of array U
ñ                 :Sort
  í               :Interleave with
   *              :And reduce each pair my multiplication
    ¡             :  Map each 0-based index Y in U
     A            :    10
      pY          :    Raised to the power of Y
        Ã         :  End map
         ï        :  Cartesian product with itself
          +       :  Reduce each pair by addition
            ñ     :  Sort
                  :Implicit output of sum of resulting array

```
> 0 votes

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


title: 50 digits of π in HQ0-9+-INCOMPUTABLE?

text:
# Question
Title: 50 digits of π in HQ0-9+-INCOMPUTABLE?
## Background

**HQ0-9+-INCOMPUTABLE?!** is a half-joke programming language introduced in Internet Problem Solving Contest 2011, Problem H.

> HQ9+ is an esoteric programming language specialized for certain tasks. For example, printing “Hello, world!” or writing a quine (a program that prints itself) couldn’t be any simpler. Unfortunately, HQ9+ doesn’t do very well in most other situations. This is why we have created our own variant of the language, HQ0-9+-INCOMPUTABLE?!.
>
> A HQ0-9+-INCOMPUTABLE?! program is a sequence of commands, written on one line without any whitespace (except for the trailing newline). The program can store data in two memory areas: the buffer, a string of characters, and the accumulator, an integer variable. Initially, the buffer is empty and the accumulator is set to 0. The value of the buffer after executing all the commands becomes the program’s output.
>
> HQ0-9+-INCOMPUTABLE?! supports the following commands:

| command | description |
| --- | --- |
| `h`, `H` | appends `helloworld` to the buffer |
| `q`, `Q` | appends the program source code to the buffer (not including the trailing newline) |
| `0-9` | replaces the buffer with `n` copies of its old value – for example, `2` doubles the buffer (`aab` would become `aabaab`, etc.) |
| `+` | increments the accumulator |
| `-` | decrements the accumulator |
| `i`, `I` | increments the ASCII value of every character in the buffer |
| `n`, `N` | applies ROT13 to the letters and numbers in the buffer (for letters ROT13 preserves case; for digits we define `ROT13(d) = (d + 13) mod 10`) |
| `c`, `C` | swaps the case of every letter in the buffer; doesn’t change other characters |
| `o`, `O` | removes all characters from the buffer whose index, counted from the end, is a prime or a power of two (or both); the last character has index 1 (which is a power of 2) |
| `m`, `M` | sets the accumulator to the current buffer length |
| `p`, `P` | removes all characters from the buffer whose index is a prime or a power of two (or both); the first character has index 1 (which is a power of 2) |
| `u`, `U` | converts the buffer to uppercase |
| `t`, `T` | sorts the characters in the buffer by their ASCII values |
| `a`, `A` | replaces every character in the buffer with its ASCII value in decimal (1–3 digits) |
| `b`, `B` | replaces every character in the buffer with its ASCII value in binary (exactly eight `0`/`1` characters) |
| `l`, `L` | converts the buffer to lowercase |
| `e`, `E` | translates every character in the buffer to l33t using the following table:
`ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789`
`48(03=6#|JXLM~09Q257UVW%Y2 a6<d3f9hijk1m^0p9r57uvw*y2 O!ZEA$G/B9` |
| `?` | removes 47 characters from the end of the buffer (or everything if it is too short) |
| `!` | removes 47 characters from the beginning of the buffer (or everything if it is too short) |

> To prevent code injection vulnerabilities, **during the execution of your program the buffer must never contain non-alphanumeric characters**, i.e. characters other than A-Z, a-z, and 0-9. Should this happen, the program fails with a runtime error, and your submission will be rejected.

The original problem statement contains limits about the code length and buffer length, but I removed them in this challenge. This is also reflected in the interpreter link below. (If you need even larger buffer, you can change the `MAX_BUFFER` constant near the top. I doubt using a longer buffer will give reasonably short code though.)

## Task

Output the string (which is 50 digits of Pi without leading `3.`)

```
14159265358979323846264338327950288419716939937510

```

in HQ0-9+-INCOMPUTABLE?!.

An answer is scored as follows:

* Each occurrence of `Q`/`q` adds **1,000,000 points**.
* Each occurrence of `E`/`e` adds **10,000 points**.
* Each occurrence of any other valid command adds **1 point**.

Lowest score wins.

Bonus: ~~+500 bounty to the first answer that achieves the score of 9,999 points or lower. I have confirmed that this is possible.~~ *claimed by dingledooper*

C++ interpreter

If you're wondering about the role of the accumulator, you're right: it still does nothing useful.

# Answer
# HQ0-9+-INCOMPUTABLE?!, ~~7884~~ ~~5134~~ ~~4122~~ 806 points

*Thanks to @JonathanAllan for suggesting using `n` in the pool code*

*Thanks to @Neil for suggesting being looser with the pool and using strings instead of char code arrays*

```
hahaha!!4?????3?????????h?2!!????2!!!h?2!!!2!!!!!hh2????2???2hhhhh?hhh2!!!!!!!!h?2!!?????!6!!!!!!!!!!!!hhh?hhhhh?hhhh?2!!?????!!2hhhhh?3!!!!!!hhhh?2??2!hh2????2???h?2!???!2hhhh?2!!!h3??????hh?2!??!2!h?3!!!2?2!hhhh?hhh2!!!h?2!!h2??h2??h?2?!6!!!!!!!h?2!!2!?4!!!!h?2?h?2??2?!2!3!!!!!3!!!!h?5????2?h?2?2hhhhh?2!!!h2!!2??2?2!hhh?hhh2!!!hh?hhhh2????2??!2h2!!!hhhh?hhhh?2??!2!3!!!2!!3???2??2?6????????2!???!2!hhh2!!!h?3!!!!!3????h3??????2?!2h?2!!!2!!!!hh2!!!hh?2!??2hh3!!!!!!!!hh?h2??2???h?2??!2hhhh?2!??2!hh2!!!!h?hhhh?2??!2!2!!hhhh?2?4???h2???2???2!??2hh?2!!!!2!!!!!hhhh2?????2!???!2!4!!!!!2!!!3???h?2?2!!hh?2!!2??2?!2h?hhh2!!!!3??????h?2!??2hhhh?2!!!hh2!!!!2???h2???2??!2!h2!hh2!!!!2??2???2?4!!!!h2!!!h2???2????2??!2!hhhh?hhhh?2??!6!!!!!2!!h2??2?2!hh2!!!!h?2??3????2?2!2!!!!!2????2????h?2!???!3!!hhh2!!!h3?????

```

Verify it online!

This uses a much different approach from dingledooper's answer – notably, it only uses `h1-9a?!`. The initial `hahaha` fills the buffer with a pool containing all digits, and then it uses careful duplications and slices to construct the string in a contiguous stretch in the buffer, at which point it chops off the surrounding character pool.

## Generating Program

```
import { BinaryHeap } from "https://deno.land/std@0.164.0/collections/binary_heap.ts";

class State {
  constructor(public answer = "", public buffer = "") {}

  clone() {
    return new State(this.answer, this.buffer.slice());
  }

  set(state: State) {
    this.answer = state.answer;
    this.buffer = state.buffer;
  }

  i() {
    this.answer += "i";
    this.buffer = fromCharCodes(toCharCodes(this.buffer).map((x) => x + 1));
  }

  a() {
    this.answer += "a";
    this.buffer = toCharCodes(this.buffer).join("");
  }

  h() {
    this.answer += "h";
    this.buffer += "helloworld";
  }

  n() {
    this.answer += "n";
    this.buffer = fromCharCodes(
      toCharCodes(this.buffer).map((x) =>
        x >= "0".charCodeAt(0) && x <= "9".charCodeAt(0)
          ? ((x - "0".charCodeAt(0) + 13) % 10) + "0".charCodeAt(0)
          : x >= "a".charCodeAt(0) && x <= "z".charCodeAt(0)
          ? ((x - "a".charCodeAt(0) + 13) % 26) + "a".charCodeAt(0)
          : x >= "A".charCodeAt(0) && x <= "Z".charCodeAt(0)
          ? ((x - "A".charCodeAt(0) + 13) % 26) + "A".charCodeAt(0)
          : -1
      ),
    );
  }

  cutStart47(n = 47): number {
    while (n >= 47) {
      n -= 47;
      this.answer += "!";
      this.buffer = this.buffer.slice(47);
    }
    return n;
  }

  cutEnd47(n = 47): number {
    while (n >= 47) {
      n -= 47;
      this.answer += "?";
      this.buffer = this.buffer.slice(0, -47);
    }
    return n;
  }

  copy(n: 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) {
    this.answer += n;
    this.buffer = this.buffer.repeat(n);
  }

  cut(start: number, end: number) {
    start = this.cutStart47(start);
    end = this.cutEnd47(end);
    [start, end] = this.search(
      [start, end],
      (_, [start]) => start === 0,
      function* (state, [start, end]) {
        if (state.buffer.length % 47) {
          for (const n of [2, 3, 4, 5, 6, 7, 8, 9] as const) {
            const state2: State = state.clone();
            let start2 = start + state2.buffer.length * (n - 1);
            state2.copy(n);
            start2 = state2.cutStart47(start2);
            yield [state2, [start2, end]];
          }
        }
        state.h();
        end += 10;
        end = state.cutEnd47(end);
        yield [state, [start, end]];
      },
    )!;
    // start = this.cutStart47(start);
    // end = this.cutEnd47(end);
    this.search(
      end,
      (_, end) => end === 0,
      function* (state, end) {
        if (state.buffer.length % 47) {
          for (const n of [2, 3, 4, 5, 6, 7, 8, 9] as const) {
            const state2 = state.clone();
            let end2 = end + state2.buffer.length * (n - 1);
            state2.copy(n);
            end2 = state2.cutEnd47(end2);
            yield [state2, end2];
          }
        }
        state.h();
        end += 10;
        end = state.cutEnd47(end);
        yield [state, end];
      },
    );
  }

  search<T>(
    init: T,
    isDone: (state: State, data: T) => boolean,
    opts: (state: State, data: T) => Iterable<[State, T]>,
  ) {
    const pq = new BinaryHeap<[State, T]>(([a], [b]) =>
      a.answer.length - b.answer.length
    );
    pq.push([this.clone(), init]);
    let cur;
    while ((cur = pq.pop())) {
      if (isDone(...cur)) {
        this.set(cur[0]);
        return cur[1];
      }
      pq.push(...opts(...cur));
    }
  }
}

function toCharCodes(x: string) {
  return [...x].map((x) => x.charCodeAt(0));
}

function fromCharCodes(x: number[]) {
  return x.map((x) => String.fromCharCode(x)).join("");
}

let state = new State();

state.h();
state.a();
state.h();
state.a();
state.h();
state.a();

const goal = "14159265358979323846264338327950288419716939937510";

let nextEnd = 0;
for (let i = 0; i < goal.length;) {
  if (state.buffer.length > i + nextEnd + 47) {
    const state2 = state.clone();
    state2.cutStart47();
    if (
      [..."1234567890"].every((x) =>
        state2.buffer.slice(0, -nextEnd).includes(x)
      )
    ) {
      state = state2;
      continue;
    }
  }
  console.log(state.buffer, i);
  let bestCnt = 0;
  for (let j = 0; j < state.buffer.length; j++) {
    let cnt = 0;
    while (goal[i + cnt] === state.buffer[j + cnt]) cnt++;
    bestCnt = Math.max(cnt, bestCnt);
  }
  if (bestCnt === 0) throw 0;
  let bestLen = Infinity;
  let best: [State, [number, number]] | undefined;
  for (let j = 0; j < state.buffer.length; j++) {
    let cnt = 0;
    while (goal[i + cnt] === state.buffer[j + cnt]) cnt++;
    if (cnt !== bestCnt) continue;
    const inner: State = state.clone();
    const len = inner.buffer.length - nextEnd;
    if (i === 0) {
      const end = inner.cutEnd47(len + nextEnd - j - cnt);
      best = [inner, [i + cnt, end]];
      continue;
    }
    inner.copy(2);
    inner.cut(j, nextEnd);
    inner.copy(2);
    inner.cutStart47(len + nextEnd - j);
    const end = inner.cutEnd47(len * 2 + nextEnd - j - cnt);
    if (i + cnt === goal.length) {
      inner.cut(inner.buffer.length - end - goal.length, end);
    }
    if (inner.answer.length < bestLen) {
      bestLen = inner.answer.length;
      best = [inner, [i + cnt, end]];
    }
  }
  [state, [i, nextEnd]] = best!;
}

state.answer = state.answer.replace(/22/g, "4").replace(/23|32/g, "6");

console.log(state.answer);
console.log(state.answer.length);
console.log(state.buffer);
console.log(goal);

```
> 34 votes

# Answer
# Score 1253 791 717 684 495 379

```
hicnhannnhh?4!4!!h?3!hh?3!!!!4?h?3!h?3!hh?5?!h?4??2?h?3!3?!!h?5?!!5?!!!!h2???4!!!h2?h?4?!h?5!!!!2??4!!!2???3!!2??4!!!!2h?5?????2???3?!h2!!hhh?2!!7?!!!!!!3!h?2!!!hhhh?5????h?3!!!!3?3????!!!!3??!hhh?3!!!!!4??!!hh2!!h?4!!h?hhhh?2?hhh?hhh2!!h?2!!!5???h?5???!!!!h?2!hhh?2!!4??!3???2??4??!h3!!!!!!!!2???3??!h?2!!!2!!hhhh?3??2!!h2!!!!h?7???!!!2???2???2?2???h?3???!!!2!!!2!!2?2??h?3!!!!!

```

Try it online!

##### How?

Just a heavily tweaked (but still surely not optimal) version of @tjjfvi's strategy.

Thanks to @Mukundan314 for -9.
> 29 votes

# Answer
# HQ0-9+-INCOMPUTABLE?!, ~~8265~~ 8261 points

*-5 points thanks to @Bubbler*
*-4 points thanks to @Mukundan314*

This was a very interesting puzzle to solve; note that this is definitely not the cleanest solution.

```
h5?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hh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hhhhh?hhhhh?hhhhh?iiihhhhh?iiiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?iiichhhhh?iiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?ihhhhh?iiiiiiiiiiiinhhhhh?chhhhh?iiiiiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiiihhhhh?iiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiichhhhh?iiiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iichhhhh?iiiiiiiiiiinciiiichhhhh?iiiiiiiiinchhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiiniiiihhhhh?iiiiiiiiiniiiichhhhh?iiiiiiiiinchhhhh?iiiihhhhh?iiiiiiiiinhhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?hhhhh?iiiihhhhh?iiiiiiiiinhhhhh?apppppppppppppppppppppppppphhhhhhhhhhhhhh???

```

Verify it online!

### Explanation

The main idea is to generate a long string of letters, and then perform a single `a` operation to convert it to the desired output. By itself, there is no such sequence of letters which lead exactly to the first 50 digits of pi. To increase our chances, we can instead find a sequence that works *after* performing some number of `p` operations. To illustrate this, if `p=1`, we would need to find a sequence of letters that decodes to the below (the `?`s are wildcards):

```
?????1??41?5?92??6?535?89793?2??3846?264?3?383?27950?28841?9?71?69?399?3?7510

```

And for `p=2`:

```
??????????????1?????41??5?92?????6?5?35??8?979?3?2???3846??2?64??3??38?3??2795?0?2?8841??9?71?69??39?9??3??7?510

```

As you can see, the position of the digits become more sparse, therefore there is more room for a valid letter sequence to exist.

The next part is figuring out how to build this letter sequence. First, notice that a command with 33 `h`s followed by 7 `?`s appends exactly one `h` to the buffer. Second, take note of the `a` and `r` operations, which increments and *rot13s* each character, respectively. Using these two facts, we can effectively append every letter from `a` to `h`.

For example, to append `c` to `abg`, we can take these steps:

* Perform `aaaaa`, so `abg` becomes `fgl`
* Perform 33 `h`s + 7 `?`s, so `fgl` becomes `fglh`
* Perform `aaaaaaaa`, so `fglh` becomes `notp`
* Perform `n`, so `notp` becomes `abgc`

Alright, so we know how to build an arbitrary string consisting of `a-h` (as well as `A-H`, by making use of the `c` operator). It turns out that there exists a string consisting of only `a-hA-H`, such that it turns into the desired output after applying an `a` followed by 14 `p`s (don't quote me on this number). We can calculate this string in many ways, such as with dynamic programming.

In essence, this is how the algorithm works. The actual code actually applies another optimization that decreased my score from 30K to \<10K. That is, instead of using 33 `h`s and 7 `?`s every time we want to append, we can instead use 5 `h`s and 1 `?`, which creates the string `hel`. Note that this requires more `p`s so that the digits are sparse enough for a solution to exist.
> 28 votes

# Answer
# HQ0-9+-INCOMPUTABLE?!, ~~1577~~...~~536~~ 510 points

```
hcoh3ioohhh8hh???????ichhhhh?iichh6????iiihh7?????iiiiiiinch9h?????chh3??3h?ch5???ich4hhh???ihhhhh?2hh?h8??????ch2?3hhh??h4???3hh??2hh3h??????iiiiiiiiiiinchh2h??2?ihhhhhhh2????iih6hh???????iiiiiiiiiinh5hhh??????iichhhh2h???chh2??iihh3hh????iiiiiiiiiniiichh3h????ihhhhh?ih2h??iiiiiiiiniiih2h??hhhhh?ihhhhh?iiiiiiiiinihhhhh?ih2??iih3????2hhhhhh???iihh3h?????iiiiiiiniihhhhh?ihhh3hh??????iiiiiiiiiinchhhhh2????hhhhh2????iihh2h???iichhhhh?2??chhh3??????2??2hhhh???2hhh???iiiiiiiiinhhhhh?2hh???2h???2???iannnnppop?o

```

Try it online!

This mostly extends @dingledooper approach; differences:

* uses both `o` and `p` operation
* allows constructing rot13 of the solution the transforming it back
* uses `2-9` (multiplication) in the middle of the solution

Things that are tuned by hand:

* currently there are occurrences of `i...ini...i` in the result which can be shortened by hand
* the end of the sequence can usually be optimized manually since we are no longer restricted to characters in `a-fA-F`

Code used for generation (bit outdated):

```
import functools
import itertools
import json
import pathlib
import time

import re2 as re  # stdlib's regex can't handle this

TARGET = "14159265358979323846264338327950288419716939937510"
CACHE_PATH = pathlib.Path(__file__).parent / "incomputable-cache.json"

MAX_BUFFER = 10**5

ROT_13 = (
    "------------------------------------------------"
    "3456789012"
    "-------"
    "NOPQRSTUVWXYZABCDEFGHIJKLM"
    "------"
    "nopqrstuvwxyzabcdefghijklm"
    "-----"
)

def prime_sieve(n):
    """returns a sieve of primes >= 5 and < n"""
    flag = n % 6 == 2
    sieve = bytearray((n // 3 + flag >> 3) + 1)
    for i in range(1, int(n**0.5) // 3 + 1):
        if not (sieve[i >> 3] >> (i & 7)) & 1:
            k = (3 * i + 1) | 1
            for j in range(k * k // 3, n // 3 + flag, 2 * k):
                sieve[j >> 3] |= 1 << (j & 7)
            for j in range(k * (k - 2 * (i & 1) + 4) // 3, n // 3 + flag, 2 * k):
                sieve[j >> 3] |= 1 << (j & 7)
    return sieve

def prime_list(n):
    """returns a list of primes <= n"""
    res = []
    if n > 1:
        res.append(2)
    if n > 2:
        res.append(3)
    if n > 4:
        sieve = prime_sieve(n + 1)
        res.extend(3 * i + 1 | 1 for i in range(1, (n + 1) // 3 + (n % 6 == 1)) if not (sieve[i >> 3] >> (i & 7)) & 1)
    return res

REMOVE_SET = set(prime_list(MAX_BUFFER) + [2**i for i in range(24)])

def run(prog, buffer=()):
    """HQ0-9+-INCOMPUTABLE?! interpreter"""
    buffer = list(buffer)

    for char in prog:
        if char == "h":
            buffer.extend("helloworld")
        elif char.isdigit():
            buffer *= ord(char) - 48
        elif char == "i":
            if any(i in "9Zz" for i in buffer):
                return
            buffer = [chr(ord(c) + 1) for c in buffer]
        elif char == "n":
            buffer = [ROT_13[ord(c)] for c in buffer]
        elif char == "c":
            buffer = [c.swapcase() for c in buffer]
        elif char == "o":
            buffer = [c for i, c in enumerate(buffer) if (len(buffer) - i) not in REMOVE_SET]
        elif char == "p":
            buffer = [c for i, c in enumerate(buffer) if (i + 1) not in REMOVE_SET]
        elif char == "u":
            buffer = [c.upper() for c in buffer]
        elif char == "t":
            buffer.sort()
        elif char == "a":
            buffer = [i for c in buffer for i in str(ord(c))]
        elif char == "b":
            buffer = [i for c in buffer for i in f"{ord(c):08b}"]
        elif char == "l":
            buffer = [c.lower() for c in buffer]
        elif char == "?":
            buffer = buffer[:-47]
        elif char == "!":
            buffer = buffer[47:]

        if len(buffer) > MAX_BUFFER:
            return

    return buffer

def unrun(prog, buffer):
    """un-runs part of a program; computes possible buffers before prog was executed"""
    ret = list(buffer)
    for char in reversed(prog):
        if char == "o":
            ret = ["#" if i + 1 in REMOVE_SET else ret.pop() for i in range(10 * len(ret)) if ret]
            ret.reverse()
        elif char == "p":
            ret.reverse()
            ret = ["#" if i + 1 in REMOVE_SET else ret.pop() for i in range(10 * len(ret)) if ret]
        elif char == "?":
            ret.extend("#" * 47)
        elif char == "!":
            ret = ["#"] * 47 + ret
    return ret

def brute_start(max_length=5):
    """
    brute-force for programs that satisfy conditions:
      - shortest to generate its output
      - does not contain 0-9, m-z, M-Z in output
    """

    if CACHE_PATH.exists():
        saved = json.loads(CACHE_PATH.read_text())
        return list(zip(saved.values(), saved.keys()))

    mid_chars = "h23456789incopt?!"
    last_chars = "hincopt?!"

    saved = {"": ""}
    for length in range(1, max_length + 1):
        for prog in itertools.product("h", *[mid_chars] * (length - 2), last_chars):
            if (output := run(prog)) is None or any(c.lower() > "l" for c in output):
                continue
            output = "".join(output)
            if output not in saved:
                saved[output] = "".join(prog)

    CACHE_PATH.write_text(json.dumps(saved))

    return list(zip(saved.values(), saved.keys()))

@functools.cache
def optimal_trim(size, trim):
    """more optimal ways exists, but good enough for now"""
    best = None
    for i in range(1, 10):
        tens = (-(trim + size * (i - 1)) * pow(10, -1, 47)) % 47
        rem = (size * (i - 1) + tens * 10 + trim) // 47
        pre, post = tens // i, tens % i
        curr = f"{'h' * pre}{i if i != 1 else ''}{'h' * post}{'?' * rem}"
        if best is None or len(curr) < len(best):
            best = curr
    return best

@functools.cache
def optimal_prefix(size, extra):
    """optimal way to achieve buffer + buffer[:extra]"""
    best = None
    for i in range(2, 10):
        if size * (i - 1) < extra:
            continue
        if size * (i - 1) == extra:
            return str(i)
        trim = optimal_trim(size * i, size * (i - 1) - extra)
        if best is None or len(trim) + 1 < len(best):
            best = f"{i}{trim}"
    return best

def solve(target, start, transform_map, max_prog=10 ** 9):
    dp = [(None, None)] * (len(target) + 1)

    def add(matched, prog, output):
        if len(prog) > max_prog:
            return
        if dp[matched][0] is None or len(prog) < len(dp[matched][0]):
            dp[matched] = (prog, output)

    for prog, output in start:
        transformed = [j for i in output for j in transform_map[i]]
        if all(i in ["#", j] for i, j in zip(target, transformed)):
            add(len(transformed), prog, output)

    for matched, (prog, output) in enumerate(dp):
        if prog is None:
            continue

        for prefix in ["h", "he", "hel", "hell"]:
            trim = optimal_trim(len(output) + 10, 10 - len(prefix))
            for shift in range(ord(min(prefix)) - ord('a') + 1):
                shifted = "".join(chr(ord(i) - shift) for i in prefix)
                for is_upper, cased in enumerate([shifted, shifted.upper()]):
                    transformed = [j for i in cased for j in transform_map[i]]
                    if matched + len(transformed) > len(target):
                        continue
                    if all(target[i] in ["#", c] for i, c in enumerate(transformed, matched)):
                        add(
                            matched + len(transformed),
                            (
                                f"{prog}"
                                f"{'c' * is_upper}"
                                f"{'i' * shift}"
                                f"h{trim}"
                                f"{'i' * (-shift % 13)}{'n' * bool(shift)}"
                                f"{'c' * is_upper}"
                            ).replace("cc", ""),
                            output + cased,
                        )

        new_matched, new_output = matched, output
        for i, c in enumerate(itertools.cycle(output)):
            if new_matched + len(transform_map[c]) > len(target) or i >= len(output) * 8:
                break
            if not all(target[j] in ["#", k] for j, k in enumerate(transform_map[c], new_matched)):
                break
            new_output += c
            new_matched += len(transform_map[c])
            add(new_matched, prog + optimal_prefix(len(output), i + 1), new_output)

    return dp[-1]

def main():
    start = brute_start()

    # constraint: transform(a) + transform(b) == transform(a + b)
    transforms = [f"{'n'*j}a{'n'*i}" for i in range(10) for j in range(2)]

    best = None

    prev = time.perf_counter()
    for transform in transforms:
        transform_map = {i: run(transform, i) for i in "ABCDEFGHIJKLabcdefghijkl"}
        regex_filter = re.compile(f"^({'|'.join(''.join(f'[{j}#]' for j in i) for i in transform_map.values())})+$")

        print(
            "\033[0;33m",
            f"[{time.perf_counter() - prev:.2f}]",
            f"transform: {transform}",
            f"(filter size: {regex_filter.programsize})",
            "\033[0m",
        )

        prev = time.perf_counter()

        for end in itertools.product("po", repeat=11):
            sparse_target = unrun(end, TARGET)
            if regex_filter.match("".join(sparse_target)) is None:
                continue

            prog, _ = solve(sparse_target, start, transform_map, len(best) if best else 2000)
            if prog is not None:
                prog = f"{prog}{transform}{''.join(end)}"
                # assert "".join(run(prog)) == TARGET
                if best is None or len(prog) < len(best):
                    print(len(prog), prog)
                    best = prog

if __name__ == "__main__":
    main()

```
> 13 votes

# Answer
1000076 points

```
1415c9c265c35c89c7c93238c46264c338c3c279c5028cc8c41971c693c9cc93c7c51cc0cccqo

```

c is a placeholder. It can be replaced with any digit, or with any other letter command that has no effect when the buffer is empty.

The only commands that do anything are q and o. So it loads the source code into the buffer then removes characters using o, but it only removes the letters. I tried to do it by ending with qp instead but it didn't line up.

These two attempts don't work because if you use q then ? can not be in the source code.

```

14159265358979323846264338327950288419716939937510q111111111111111111111111111111111111111111111?

14159265358979323846264338327950288419716939937510q5?????

```
> 1 votes

---
Tags: code-challenge
---


title: Shorten the Java Package

text:
# Question
Title: Shorten the Java Package
## Briefing

Given a Fully Qualified Java Class/ Package name, you must shorten it as such:

Each part of the dot separated package will be shortened to its first letter, apart from the last section and the class (if it exists).

package names will be all lower case, and the class (if it exists) will start with a capital letter and be UpperCamelCase. packages come in the form of:

```
foo.bar.foo

```

and

```
foo.bar.foo.Class

```

## Examples

```
(No Class)
Input com.stackoverflow.main
Output c.s.main

(Class)
Input com.google.parser.Gson
Output c.g.parser.Gson

(Class)
Input com.google.longer.package.TestClass
Output c.g.l.package.TestClass

```

## Rules

* Shortest code in bytes wins
* Standard loopholes apply

# Answer
> 10 votes
## Retina, 17 bytes

```
\B\w+(\.[a-z])
$1

```

Try it online!

### Explanation

```
\B         # Start from a position that isn't a word boundary. This ensures that
           # the first letter of the package name is skipped.
\w+        # Match one or more word characters. This is the remainder of the
           # package name which we want to remove.
(          # Capture the next part in group 1, because we want to keep it...
  \.[a-z]  #   Match a period and a lower-case letter. This ensures that we
           #   don't match the package that precedes the class, or the package or
           #   class at the end of the input.
)

```

This is replaced with `$1`, which is the period and lower case letter which shouldn't be removed.

# Answer
> 4 votes
# JavaScript (ES6), ~~68~~ 53 bytes

```
s=>s.split`.`.map((x,y,z)=>z[y+1]>"["?x[0]:x).join`.`

```
* 15 bytes saved thanks to Arnauld.

See my other solution here.

---

## Try it

```
f=
s=>s.split`.`.map((x,y,z)=>z[y+1]>"["?x[0]:x).join`.`
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("com.stackoverflow.main"))
console.log(f("c.g.parser.Gson"))
console.log(f("com.google.longer.package.TestClass"))
```

```
<input id=i><pre id=o>
```

# Answer
> 3 votes
# Java 8, ~~66~~ 41 bytes

```
s->s.replaceAll("\\B\\w+(\\.[a-z])","$1")

```

Port from *@MartinEnder*'s amazing Retina answer.

Try it online.

# Answer
> 3 votes
# Python 2, ~~88~~ 81 bytes

```
f=lambda s,d=".":s.count(d)>(s.split(d)[-1]<"[")and s[0]+d+f(s[s.find(d)+1:])or s

```

Try it online!

# Answer
> 2 votes
# Mathematica, 75 bytes

```
#[[;;-3]]~StringTake~1~Join~#[[-2;;]]~StringRiffle~"."&[#~StringSplit~"."]&

```

Anonymous function. Takes a string as input and returns a string as output.

# Answer
> 2 votes
# Japt, ~~30 27~~ 25 bytes

```
¡Y>Zl -('[>ZgJ)-2?X:Xg}'.

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~76~~ 73 bytes

```
q=input().split('.')
i=~(q[-1]<'_')
q[:i]=zip(*q[:i])[0]
print'.'.join(q)

```

Try it online! or Try all test cases

# Answer
> 2 votes
# , 9 bytes

```
Íì“ƒ…®õÀ!

```

Try it online!

Hexdump:

```
00000000: cdec 9383 85ae f5c0 21                   ........!

```

This is a wonderful example of V's signature *regex compression*.

Explanation:

```
Í          " Remove every match on every line:
 ì         " A lower case letter
  “ …      "   *ONLY MATCH THIS PART:*
   ƒ       "   As few characters as possible
      ®    " Followed by a dot
       õÀ! " Not followed by an uppercase letter

```

# Answer
> 2 votes
# Haskell, 58 bytes

```
f s|[(a:t,p:x:r)]<-lex s=a:concat[t|x<'a']++p:f(x:r)|1<3=s

```

Try it online! Usage: `f "some.string"`.

`lex` parses a string as Haskell tokens, so `lex "some.string"` returns `[("some",".string")]`. `f` recurses over the tokens in the string and always appends the first char `a` of the current token, but the rest `t` of the token only if the remaining string after the colon `p` starts with an uppercase char, that is `x<'a'`. If the pattern match failed, we have reached the last token and simply return `s`.

# Answer
> 1 votes
# Python 2, ~~108~~ ~~97~~ 89 bytes

```
i=input().split(".")
for x in range(len(i)+~(i[-1][0]<"[")):i[x]=i[x][0]
print".".join(i)

```

Try it online!

-8 with many thanks to @ovs for the tip

# Answer
> 1 votes
# JavaScript (ES6), 36 bytes

Another port of Martin's Retina answer. See my other solution here.

```
s=>s.replace(/\B\w+(\.[a-z])/g,"$1")

```

```
f=
s=>s.replace(/\B\w+(\.[a-z])/g,"$1")
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("com.stackoverflow.main"))
console.log(f("c.g.parser.Gson"))
console.log(f("com.google.longer.package.TestClass"))
```

```
<input id=i><pre id=o>
```

# Answer
> 1 votes
# sed, 57 22 bytes

I expected sed solution to be a little shorter than this...

**Edit:**

The shorter solution uses regex from Martin Ender's answer.

21 bytes sourcecode + 1 byte for `-r` flag (or `-E` flag for BSD sed).

```
s|\B\w+(\.[a-z])|\1|g

```

# Answer
> 1 votes
# 05AB1E, ~~20~~ 15 bytes

```
ΔA3ãvy'.«ÀDõ1ǝ:

```

Try it online or verify all test cases. (Extremely slow, so the `A` has been replaced with `Dálê` (duplicate; keep letters; convert to lowercase; sorted-uniquify) in the TIO-links.)

**Original 20 bytes approach:**

```
'.©¡Rć¬.uisć}s€н`r®ý

```

Try it online or verify all test cases.

**Explanation:**

I basically keep replacing every `ab.c` to `a.c`, where `abc` are any combination of lowercase letter including duplicates:

```
Δ                 # Loop until the result no longer changes,
                  # using the (implicit) input-string in the first iteration
 A                #  Push the lowercase alphabet
  3ã              #  Create all possible triplets of lowercase letters with the
                  #  cartesian power of 3
    v             #  Loop over each triplet `y`:
     y'.«        '#   Append a "." to the triplet
         À        #   Rotate it once towards the right: "abc." to "ab.c"
          D       #   Duplicate it
           õ1ǝ    #   Replace the character at index 1 with "": "ab.c" to "a.c"
              :   #   Replace all "ab.c" in the string to "a.c"
                  # (after which the resulting string is output implicitly)

```

```
'.               '# Push "."
  ©               # Store it in variable `®` (without popping)
   ¡              # Pop and split the (implicit) input by this "."
    R             # Reverse this list
     ć            # Extract head; pop and push remainder-list and first item separated
                  # to the stack
      ¬           # Get the first character (without popping the string)
       .ui        # Pop, and if it's uppercase:
          s       #  Swap so the remainder-list is at the top of the stack
           ć      #  Extract its head again
         }        # Close the if-statement
          s       # Swap so the remainder-list is at the top of the stack
           €      # Map over each string in this list:
            н     #  Pop and only leave its first character
             `    # Pop and dump these characters to the stack
              r   # Reverse the stack
               ®ý # Join the stack by the "."-delimiter from variable `®`
                  # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Go, 101 bytes

```
import."regexp"
func f(B string)string{return MustCompile(`\B\w+(\.[a-z])`).ReplaceAllString(B,`$1`)}

```

Attempt This Online!

Port of Martin's Retina answer.

# Answer
> 1 votes
# Pip, ~~22~~ 19 bytes

```
aR`\B\w+(\.[a-z])`B

```

-3 thanks to DLosc!

Yet another port of Martin's Regex.

Try It Online!

---

## First Attempt(Non-Competing)

# Pip, 45 bytes

```
d:"."c:dNae:XU Na?c-1ca:a^dFi,e{a@i:a@i@0}aJd

```

Try It Online!

---
Tags: code-golf
---


title: Make the cheapest cut

text:
# Question
Title: Make the cheapest cut
“Cut” a matrix of integers on the line where the sum of the absolute differences of “severed” neighbors is the least.

## Example

Consider this matrix:

```
 1  2 -4
 5 -1  3
 2 -2  0

```

It can be cut in 4 places, here shown by lines lettered `A``D`:

```
     A    B
     ╷    ╷
   1 ╎  2 ╎ -4
C ---╎----╎----
   5 ╎ -1 ╎  3
D ---╎----╎----
   2 ╎ -2 ╎  0
     ╵    ╵

```

The cost to cut on a line is the sum of the absolute differences of the numbers opposing each other on that line. For example, cutting on `B` would cost \\$\lvert 2--4\rvert+\lvert-1-3\rvert+\lvert-2-0\rvert=12\\$.

Your task, however, is to find the cheapest cut, which in this case is `D`: \\$\lvert 5-2\rvert+\lvert-1- -2\rvert+\lvert 3-0\rvert=7\\$.

## Input

The input will be a 2-D matrix of integers in any reasonable format. It will always have at least two rows and at least two columns and might not be square.

## Output

The output may be one of the following:

1. Two separate matrices representing the “pieces” of the original matrix after the cut, in any reasonable format. The two matrices may be in either order but must be the same shape as they were in the original matrix.
2. An expression representing where the cut is, e.g. `D` as above or the equivalent index 3 (0-based) or 4 (1-based), in any reasonable format. You may invent your own indexing scheme but it must be described in your answer and be consistent.

## Rules

## Test cases

```
Input

 8  1  2 -3
 6 -2 -7 -4
-1 -6 -9  3

Output
      x
 8  1 ╎  2 -1
 6 -2 ╎ -7 -4
-1 -6 ╎ -9  3
      ╵

```

```
Input

 2 -2  1
 8  7 -7
-9  5 -3
 0 -8  6

Output

  2 -2  1
x---------
  8  7 -7
 -9  5 -3
  0 -8  6

and/or

  2 -2  1
  8  7 -7
x---------
 -9  5 -3
  0 -8  6

```

# Answer
> 6 votes
# Excel, 321 bytes

**Golfed code:**

```
Sub z()
With ActiveSheet.UsedRange
m=-1
x=.Rows.Count
y=.Columns.Count
For c=2To y
t=0
For r=1To x
t=t+Abs(Cells(r,c)-Cells(r,c-1))
Next
If m=-1Then m=t
If t <= mThen m=t:Set a=.Columns(c)
Next
For r=2To x
t=0
For c=1To y
t=t+Abs(Cells(r,c)-Cells(r-1,c))
Next
If t<mThen m=t:Set a=.Rows(r)
Next
a.Insert
End With
End Sub

```

**Formatted and commented code:**

```
Sub z()

    ' Using With for the entire procedure saves plenty of bytes.
    With ActiveSheet.UsedRange

        ' Set the initial minimum to -1 so we can tell when it hasn't been changed yet.
        ' We could possibly set this (2^1023*1.99) or something but then there'd be some weird edge case where this would fail to cut at the right place.
        m = -1

        ' Save the number of rows and columns now to save bytes later.
        x = .Rows.Count
        y = .Columns.Count

        ' Loop through each column, starting with the second column and looking to the left.
        For c = 2 To y

            ' Calculate the cut cost for this column.
            t = 0
            For r = 1 To x
                t = t + Abs(Cells(r, c) - Cells(r, c - 1))
            Next

            ' Check if the min is still the initial value and change it.
            If m = -1 Then m = t

            ' If the total is <= the current minimun, then save it as the new minimum.
            ' We have to use <= here because "a" is not set in the line above.
            If t <= m Then m = t: Set a = .Columns(c)
        Next

        ' Repeat everything we just did but go row by row instead and don't worry about the initial min value.
        For r = 2 To x
            t = 0
            For c = 1 To y
                t = t + Abs(Cells(r, c) - Cells(r - 1, c))
            Next
            If t < m Then m = t: Set a = .Rows(r)
        Next

        ' Insert a row or column as needed. This will default to shifting rows and and columns to the right.
        a.Insert

    End With

End Sub

```

**Input format:**

Input the matrix with one number per cell starting in cell `A1` of the active sheet.

**Output format:**

The code will insert a row or column in the correct location, cutting the data. This is equivalent to output option #1 the way the question is written now.

# Answer
> 5 votes
# MATLAB / Octave, ~~63~~ 46 bytes

*-17 bytes thanks to @Luis Mendo*

```
g=@(B)sum(abs(diff(B))')
@(A)min([g(A') g(A)])

```

Returns an anonymous function, used like

```
f = ans
[v,i] = f([1 2 3; 4 5 6; 7 8 9])

```

Where `i` becomes the "index" of the cut, mapping to the letter assigned to the cut in the problem description (`1` -\> `A`, `2` -\> `B`, etc.)

# Answer
> 3 votes
# , 23 bytes

```
(=<./)@,&(1#.2|@-/\])|:

```

Try it online!

## output

Output is a boolean list of "all possible horizontal cuts" followed by "all possible vertical cuts". For example, if the input is a 3 x 4 matrix, the output will be length 5 and should be interpreted as follows:

```
      the first vertical cut is minimal
      v
0 0 | 1 0 0
^^^
 neither horizontal cut is minimal

```

If there are multiple ones in the output, all of them are minimal.

## how

* `...|:` For both the input and its transpose...
* `&(1#.2|@-/\])` Take every pair of rows, take the absolute value of the elementwise differences, and sum
* `,` Cat those results together, putting the horizontal results first
* `(=<./)` Mark every place that equals the minimum with a 1

# Answer
> 3 votes
# Jelly, 9 bytes

```
,ZạƝ€§NŒM

```

A monadic Link that accepts a list of lists and yields a list of all possible minimal cuts, each of which is a pair of numbers, the (1-indexed) index to cut before (an integer, two or greater) and a direction indicator which is \\$1\\$ if the index is counting rows or \\$2\\$ if counting columns - e.g. `[5,2]` means to cut after the fifth column.

**Try it online!**

### How?

```
,ZạƝ€§NŒM - Link: list of lists, M
 Z        - transpose (M)
,         - (M) paired with (that)
    €     - for each:
   Ɲ      -   for neighbours:
  ạ       -     (left) absolute difference (right) (vectorises)
     §    - sums (vectorises at depth 1)
      N   - negate
       ŒM - maximal multi-dimensional indices

```

# Answer
> 3 votes
# MATL, 13 bytes

```
!G,wd|!s]h&X<

```

The output indicates the cut as the letters in the challenge text, with `1`, `2` corresponding to `A`, `B`, ...

Try it online! Or verify all test cases.

### How it works

```
!      % Implicit input. Transpose
G      % Push input again
,      % Do twice
  w    %   Swap
  d    %   Consecutive differences, vertically
  |    %   Absolute value, element-wise
  !    %   Tranpose
  s    %   Sum, vertically. Gives a row vector
]      % End
h      % Concatenate the two row vectors
&X<    % (1-based) index of (first) minimum. Implicit display

```

# Answer
> 3 votes
# APL (Dyalog APL), 18 bytes

```
⊃∘⍋,⍥(+⌿∘|2-/⊢)∘⍉⍨

```

Attempt This Online!

## I/O

* Input is a numerical matrix
* Output is the index of the cut with the same (1-based) indexing scheme as the OP -- leftmost vertical cut is 1, enumerate vertical cuts left-to-right, then horizontal cuts top-to-bottom

## Explanation

```
⊃∘⍋,⍥(+⌿∘|2-/⊢)∘⍉⍨

       (+⌿∘|2-/⊢)     ⍝ Cost function, calculates costs of vertical cuts
            2-/⊢      ⍝   Pairwise difference of horizontally adjacent entries
           |          ⍝   Absolute value
        +⌿           ⍝   Sum vertically

    ,⍥( ...... )     ⍝ Concatenate the result of calling the cost function on ...
                 ∘⍉⍨ ⍝   ...the input and its transpose
⊃∘⍋                  ⍝ Argsort ascending and return the first entry
                      ⍝  (index of smallest value)

```

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
ø‚€üαOWQ

```

Outputs a pair of \\$\[horizontalCuts,verticalCuts\]\\$, where the truthy cut (`1`) is the minimum result (e.g. `[[0,1],[0,0]]` for the example of the challenge description, where the cuts are \\$\[\[C,D\],\[A,B\]\]\\$). (If more than one minimal cut is possible like the final test case, both cuts will be `1`.)

Try it online or verify all test cases.

**Explanation:**

```
ø         # Zip/transpose the (implicit) input-matrix; swapping rows/columns
 ‚        # Pair the (implicit) input-matrix with its transposed matrix
  €       # Map over this pair of matrices:
   ü      #  Loop over each overlapping pair of rows:
    α     #   Take the (vectorized) absolute difference between values at the same
          #   positions in the two rows
     O    # Take the sum of each inner-most list
      W   # Push the flattened minimum (without popping the pair of lists)
       Q  # Check which inner-most value(s) are equal to this minimum
          # (after which the result is output implicitly)

```

# Answer
> 2 votes
# PARI/GP 114 bytes

```
C(v,w)=vecsum(abs(v-w));c(M)=vecmin(concat(vector(#M-1,i,C(M[,i+1],M[,i])),vector(#M~-1,i,C(M[i+1,],M[i,]))),&L);L

```

Input: Matrix M, output: position of cut, encoded as integer, i.e., {1,2,3,4,...} corresponds to {A,B,C,D,...} in the task description.

## Examples

```
c([1,2,-4;5,-1,3;2,-2,0])
4
c([2,-2,1;8,7,-7;-9,5,-3;0,-8,6])
3
c([8,1,2,-3;6,-2,-7,-4;-1,-6,-9,3])
2

```

# Answer
> 1 votes
# Charcoal, 36 bytes

```
Ｆ⟦θＥ⌊θＥθ§λκ⟧Ｆ⊖Ｌ⌊ι⊞υΣＥι↔⁻§λκ§λ⊕κＩ⌕υ⌊υ

```

Try it online! Link is to verbose version of code. Outputs a 0-indexed integer corresponding to the letters from the challenge. Explanation:

```
Ｆ⟦θＥ⌊θＥθ§λκ⟧

```

Loop over the matrix and its transpose.

```
Ｆ⊖Ｌ⌊ι

```

Loop over the indices of pairs of adjacent columns (which for the transposed matrix map to rows of the original matrix).

```
⊞υΣＥι↔⁻§λκ§λ⊕κ

```

Calculate the cost of this cut.

```
Ｉ⌕υ⌊υ

```

Output the (first) index of the minimum cost.

# Answer
> 1 votes
# sclin, 50 bytes

```
"tpose"Q ,"."mapf"\& fold~"Q =
2%`",_ - abs +/"map

```

Try it here!

For testing purposes:

```
[[8 1 2 3_ ][6 2_ 7_ 4_ ][1_ 6_ 9_ 3]] ; \>N map >A f>o
"tpose"Q ,"."mapf"\& fold~"Q =
2%`",_ - abs +/"map

```

## Explanation

Prettified code:

```
\tpose Q , \; mapf ( \& fold~ ) Q =
2%` ( ,_ - abs +/ ) map

```
* `\tpose Q ,` pair matrix with its transposed copy
* `\; mapf` flatmap...
    + `2%` (...) map` pairwise map over each row/column...
        - `,_ - abs +/` absolute difference, sum
* `( \& fold~ ) Q` get minimum sum
* `=` get all minimum sums

---
Tags: code-golf, matrix
---


title: Tips for golfing in QBasic

text:
# Question
Title: Tips for golfing in QBasic
What general tips do you have for golfing in QBasic? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to QBasic (e.g. "remove comments" is not an answer).

Tips pertaining to the QB64 emulator are also welcome. It has some extra features that aren't in Microsoft QBasic.

# Answer
> 12 votes
# Know your looping constructs

QBasic has several looping constructs: `FOR ... NEXT`, `WHILE ... WEND`, and `DO ... LOOP`. You can also use `GOTO` or (in some situations) `RUN` to loop.

* `FOR ... NEXT` is pretty good at what it does. Unlike in Python, it's almost always shorter than the equivalent `WHILE` or `GOTO` loop, even when it gets a little fancier:

```
FOR i=1TO 19STEP 2:?i:NEXT
i=1:WHILE i<20:?i:i=i+2:WEND
i=1:9?i:i=i+2:IF i<20GOTO 9

```

Note that you don't need to repeat the variable name after `NEXT`, and you can eliminate space between numbers and most following keywords.
* `WHILE ... WEND` is good for when you have a loop that might need to execute 0 times. But if you know the loop will execute at least once, `GOTO` might be one byte shorter:

```
WHILE n>1:n=n\2:WEND
1n=n\2:IF n>1GOTO 1

```
* I only use `DO ... LOOP` for infinite loops (except where `RUN` can be used instead). While it costs the same number of characters as an unconditional `GOTO`, it's a little more intuitive to read. (Note that "infinite loop" can include loops that you break out of using a `GOTO`.) The `DO WHILE`/`DO UNTIL`/`LOOP WHILE`/`LOOP UNTIL` syntax is too verbose; you're better off using `WHILE` or `GOTO` as appropriate.
* `GOTO` is, as mentioned above, the shortest general way to write a do/while loop. Use single-digit line numbers instead of labels. Note that when a `GOTO` is the only thing in the `THEN` part of an `IF` statement, there are two equally terse shortcut syntaxes available:

```
IF x>y GOTO 1
IF x>y THEN 1

```

`GOTO` can also be used to create more complicated control flows. The naysayers refer to this as "spaghetti code," but this is code golf: unreadability is almost a virtue! `GOTO` pride!
* `RUN` is useful when you need to jump to a fixed place in the program and you don't need to keep any of the variables' values. `RUN` by itself will restart the program from the top; with a label or line number, it will restart at that line. I've mainly used it to create stateless infinite loops.

# Answer
> 8 votes
# Divisibility testing

In programs that require you to test whether one integer is divisible by another, the obvious way is to use `MOD`:

```
x MOD 3=0

```

But a shorter way is to use integer division:

```
x\3=x/3

```

That is, `x` int-div `3` equals `x` float-div `3`.

Note that both of these approaches will return `0` for falsey and `-1` for truthy, so you may need to negate the result, or subtract it instead of adding.

---

If you need the opposite condition (i.e. `x` is *not* divisible by `3`), the obvious approach is to use the not-equals operator:

```
x\3<>x/3

```

But if `x` is guaranteed to be nonnegative, we can save a byte. Integer division truncates the result, so it will always be less than or equal to float division. Therefore, we can write the condition as:

```
x\3<x/3

```

Similarly, if `x` is guaranteed to be negative, truncation *increases* the result, and we can write `x\3>x/3`. If you don't know the sign of `x`, you'll have to stick to `<>`.

# Answer
> 7 votes
# Scanner abuse

As in a lot of languages, knowing which characters can and can't be removed is important.

* Any space next to a symbol can be removed: `IF""=a$THEN?0`
* Space can usually be removed between a digit and a letter occurring *in that order*: `FOR i=1TO 10STEP 2`. There are some differences between QBasic 1.1 (available at archive.org) and QB64:
    + QBasic 1.1 allows removal of space between any digit and a following letter. Furthermore, in print statements, it will infer a semicolon between consecutive values: `?123x` becomes `PRINT 123; x`. The exceptions to the above are sequences like `1e2` and `1d+3`, which are treated as scientific notation and expanded to `100!` and `1000#` (single- and double-precision, respectively).
    + QB64 is generally the same, but digits can't be followed by `d`, `e`, or `f` at all unless they are part of a well-formed scientific notation literal. (For example, you can't omit the space after the line number in `1 FOR` or `9 END`, like you can in QBasic proper.) It only infers semicolons in print statements if one of the expressions is a string literal: `?123"abc"` works, but not `?TAB(5)123` or `?123x`.
* Speaking of semicolons, QBasic 1.1 adds a trailing semicolon to a `PRINT` statement that ends with a call to `TAB` or `SPC`. (QB64 does not.)
* `0` can be omitted before or after the decimal point (`.1` or `1.`), but not both (`.`).
* `ENDIF` is equivalent to `END IF`.
* The closing double quote of a string can be omitted at the end of a line.

# Answer
> 6 votes
# Use shortcuts for `PRINT` and `REM`

You can use `?` instead of `PRINT`, and `'` instead of `REM` (comment).

`'` might also come useful when polygloting with languages that support `'` as a part of char or string syntax.

# Answer
> 5 votes
# Know your input methods

QBasic has several ways to get user keyboard input: `INPUT`, `LINE INPUT`, `INPUT$`, and `INKEY$`.

* `INPUT` is your standard multipurpose input statement. The program stops what it's doing, displays a cursor, and lets the user type some input, terminated by `Enter`. `INPUT` can read numbers or strings, and it can read multiple values comma-separated. You can specify a string as a prompt, you can go with the default question-mark prompt, and you can even (I just learned this tonight) suppress the prompt altogether. Some sample invocations:
    + `INPUT x$,y`
    Uses the default `?`  prompt and reads a string and a number, comma-separated.
    + `INPUT"Name";n$`
    Prompts with `Name?`  and reads a string.
    + `INPUT"x=",x`
    Prompts with `x=` (no question mark! note the comma in the syntax) and reads a number.
    + `INPUT;"",s$`
    Suppresses the prompt (using the above comma syntax with an empty prompt string), reads a string, and does not move to the next line when the user hits enter (that's what the semicolon after `INPUT` does). For example, if you `PRINT s$` immediately after this, your screen will look like `User_inputUser_input`.
* One drawback of `INPUT` is that you can't read a string with a comma in it, since `INPUT` uses comma as a field separator. To read a single line of arbitrary (printable ASCII) characters, use `LINE INPUT`. It's got the same syntax options as `INPUT`, except it takes exactly one variable which must be a string variable. The other difference is that `LINE INPUT` does not display a prompt by default; if you want one, you'll have to specify it explicitly.
* `INPUT$(n)` displays no prompt or cursor but simply waits until the user enters `n` characters, and then returns a string containing those characters. Unlike `INPUT` or `LINE INPUT`, the user doesn't need to press `Enter` afterwards, and in fact `Enter` can be one of the characters (it'll give ASCII character 13, known to C-like languages as `\r`).

Most often, this is useful as `INPUT$(1)`, typically in a loop. `INPUT$` is good in interactive programs where single keypresses do things. Unfortunately, it only works with keys that have ASCII codes; this includes things like `Esc` and `Backspace`, but not the arrow keys, `Insert` and `Delete`, and others.
* Which is where `INKEY$` comes in. It is similar to `INPUT$(1)` in that it returns the results of a single keypress1, but different in that:

+ `INKEY$` takes no argument.
    + While `INPUT$(n)` halts execution until the user enters `n` characters, `INKEY$` does not halt execution. If the user is currently pressing a key, `INKEY$` returns a string representing that key; if not, it returns `""`. This means that if you want to use `INKEY$` to get the next keypress, you have to wrap it in a busy-waiting loop:2

    ```
    k$=""
    WHILE""=k$
    k$=INKEY$
    WEND

    ```
    + Both `INPUT$` and `INKEY$` return ASCII characters for keys that correspond to ASCII characters (including control characters like escape, tab, and backspace). However, `INKEY$` can also handle some keys that do not have ASCII codes. For these (saith the help file), "INKEY$ returns a 2-byte string made up of the null character (ASCII 0) and the keyboard scan code."

    Clear as mud? Here's some examples. If you use the `INKEY$` loop above to capture a keypress of the left arrow key, `k$` will contain the string `"␀K"` (with the `K` representing scan code 75). For the right arrow, it's `"␀M"` (77). Page down is `"␀Q"` (81). F5 is `"␀?"` (63).

    Still clear as mud? Yeah. It's not the most intuitive thing in the world. The help file has a table of scan codes, but I always just write a little program to print the results of `INKEY$` and press a bunch of keys to find out what the right values are. Once you know which characters correspond to which keys, you can use `RIGHT$(k$,1)` and `LEN(k$)` to distinguish between all the different cases you may encounter.

Bottom line? `INKEY$` is weird, but it's the only way to go if your program requires non-blocking input or needs to use the arrow keys.

---

1 Not including `Shift`, `Ctrl`, `Alt`, `PrntScr`, `Caps Lock`, and similar. Those don't count. :^P

2 The `WHILE ... WEND` idiom here is what I learned in my QBasic books. For golfing purposes, however, a `GOTO` loop is shorter.

# Answer
> 4 votes
# `PRINT` (`?`) has some quirks

Numbers are printed with a leading and trailing space.

Printing adds a linebreak. This behaviour can be altered by adding a comma at the end of the statement to insert a tab instead, or a semi-colon to avoid any insertions.

It is not necessary to use `+` or `;` between distinct expressions when printing, eg. `?1"x"s$` prints the number `1`, with spaces on each side, the letter `x` and the contents of `s$`.

```
?"foo"
?"bar"
?10
?"foo",
?"bar"
?"foo";
?"bar"
?1CHR$(65)
?1" "CHR$(65)
?"A","B

```

Outputs

```
foo
bar
 10
foo           bar
foobar
 1 A
 1  A
A             B

```

Printing a linebreak can be done with just `?`.

# Answer
> 4 votes
# Combine `Next` Statements

```
Next:Next:Next

```

May be condensed down to

```
Next k,j,i

```

where the iterators for the `For` loops are `i`,`j`, and `k` \- in that order.

For example the below (69 Bytes)

```
Input n,m,o
For i=0To n
For j=0To m
For k=0To o
?i;j;k
Next
Next
Next

```

May be condensed down to 65 Bytes

```
Input n,m,o
For i=0To n
For j=0To m
For k=0To o
?i;j;k
Next k,j,i

```

And as far as how this impacts formatting and indentation, I think the best approach to handling this is left aligning the next statement with the outer most for statement. Eg.

```
Input n,m,o
For i=0To n
    For j=0To m
        For k=0To o
            ?i;j;k
Next k,j,i

```

# Answer
> 3 votes
In QBasic, it is customary to use the `DIM` statement to create variables, giving them a name and a type. However, this isn't mandatory, QBasic can also derive a type by the suffix of the variable's name. Since you can't declare and initialise a variable at the same time, it's often wise to skip the `DIM` in codegolf. Two snippets that are functionally identical\*:

```
DIM a AS STRING: a = "example"
a$ = "example"

```

* Note that this does create two different variable names.

We can specify the type of the variable by adding `$` to the end of a variable name for strings, `!` for single precision numbers and `%` for doubles. Singles are assumed when no type is specified.

```
a$ = "Definitely a string"
b! = "Error!"

```

Note that this also holds for arrays. Usually, an array is defined as:

```
DIM a(20) AS STRING

```

But arrays also don't need to be `DIM`med:

```
a$(2) = "QBasic 4 FUN!"

```

`a$` is now an array for strings with **11** slots: from index 0 to and including index 10. This is done because QBasic has an option that allows both 0-based and 1-based indexing for arrays. A default array kind of supports both this way.

Remember the twenty-slot array we `DIM`med above? That actually has 21 slots, because the same principle applies to both dimmed and non-dimmed arrays.

# Answer
> 3 votes
# LOCATE can be really powerful

The `LOCATE` statement allows you to place the cursor anywhere on the screen (within the usual 80x40 character space limits) and print something at that location. This answer to a challenge really shows this off (and is also combined with a lot of other tips from this topic).

The challenge asks us to output every character a user has pressed in a 16x6 grid. With `LOCATE` this is simply a matter of div and mod over the ASCII code (`a` in this code):

```
LOCATE a\16-1,1+2*(a MOD 16)

```

And then printing the character:

```
?CHR$(a)

```

# Answer
> 3 votes
# Shortening `IF` statements

`IF` statements are rather expensive, and golfing them down can save a lot of bytes.

Consider the following (adapted from an answer by Erik the Outgolfer):

```
IF RND<.5THEN
x=x-1
a(i)=1
ELSE
y=y-1
a(i)=0
ENDIF

```

The first thing we can do is save the `ENDIF` by using a single-line `IF` statement:

```
IF RND<.5THEN x=x-1:a(i)=1ELSE y=y-1:a(i)=0

```

This works as long as you don't try to put it on the same line as anything else. In particular, if you have nested `IF` statements, only the innermost one can be one-lined.

But in this case, we can eliminate the `IF` entirely using math. Consider what we actually want:

* If `RND<.5` is true (`-1`), we want:
    + `x` to decrease by 1
    + `y` to stay the same
    + `a(i)` to become 1
* Otherwise, if `RND<.5` is false (`0`), we want:
    + `x` to stay the same
    + `y` to decrease by 1
    + `a(i)` to become 0

Now if we save the result of the conditional in a variable (`r=RND<.5`), we can calculate the new values of `x`, `y`, and `a(i)`:

* When `r` is `-1`, `x=x-1`; when `r` is `0`, `x=x+0`.
* When `r` is `-1`, `y=y+0`; when `r` is `0`, `y=y-1`.
* When `r` is `-1`, `a(i)=1`; when `r` is `0`, `a(i)=0`.

So our final code looks like:

```
r=RND<.5
x=x+r
y=y-1-r
a(i)=-r

```

saving a whopping 20 bytes (40%) over the original version.

---

The math approach can be applied surprisingly often, but when there's a difference in logic between the two cases (e.g. when you need to input something in one case but not in the other), you will still need to use `IF`.

# Answer
> 3 votes
# Sometimes, you should avoid arrays

Arrays in QBasic, when instantiated without `DIM` have only 11 slots. If a challenge requires more than 11 slots (or N slots, where N can be bigger than 11), you should `DIM` the array. Also, let's assume we want to populate this array with data:

```
DIM a$(12)
a$(0) = "Value 1"
a$(1) = "Value 2"
...

```

Even golfed, this can take up a lot of space. On such occasions, it might be cheaper in bytes to do this:

```
a$ = "value 1value 2"

```

Here, we place everything in 1 concatenated string. Later, we access it like so:

```
?MID$(a$,i*7,7)

```

For this approach, it is important that all values are of equal length. Take the longest value and pad out all the others:

```
a$="one  two  threefour "

```

You don't need to pad the last value, and you can even skip the closing quotes! If the challenge specifies that white-space is not allowed in the answer, use `RTRIM$()` to fix that.

You can see this technique in action here.

# Answer
> 2 votes
# `WRITE` may be useful in place of `PRINT`

`PRINT` is usually the way you'll want to do output, since it's pretty flexible and has the `?` shortcut. However, the `WRITE` command can save you bytes in specific situations:

* When outputting a string, `WRITE` wraps it in double quotes (`"`). If you need output with double quotes, `WRITE s$` is much shorter than `?CHR$(34);s$;CHR$(34)`. See, for example, the shortest known QBasic quine.
* When outputting a number, `WRITE` does not add spaces before and after it like `PRINT` does. `WRITE n` is much shorter than `?MID$(STR$(n),2)`. See, for example, FizzBuzz in QB64.
* When outputting multiple values, `WRITE` separates them with commas: `WRITE 123,"abc"` outputs `123,"abc"`. I can't think of a scenario where this would be useful, but that doesn't mean there isn't one.

Limitations of `WRITE`:

* There is no way to output multiple values without a separator like with `PRINT a;b`.
* There is no way to suppress the newline at the end of output. (You may be able to work around this with `LOCATE`, but that costs a lot of bytes.)

# Answer
> 2 votes
# Sometimes, QBasic mangles inputs to functions. Abuse that!

There's a couple of functions that work on characters instead of strings, but there isn't a `char` datatype in QBasic, there is only the `string ($)` type. Take for instance the `ASC()` function, which returns the ASCII keycode for a character. If we would enter

```
PRINT ASC("lala")

```

only the first `l` would be considered by QBasic. This way, we don't have to bother with cutting a string down to length 1.

Another example comes from this question where the `STRING$()` function is used in one of the answers.

> The STRING$ function takes two arguments, a number n and a string s$, and constructs a string consisting of n copies of the first character of s$
>
> @DLosc, here

Note that QBasic, when offered a multi-char string and needing only one char, automatically takes the first char and ignores the rest.

# Answer
> 1 votes
# `Integer` vs `Ulong`

Sometimes you can simply reduce 2 bytes by using this trick:

```
DIM r AS Integer

vs

DIM r AS Ulong

```

This works on most occassions.

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