title: Swap capitalization of two strings

text:
# Question
Title: Swap capitalization of two strings
`your shift key is broken. wheNever you type two lines, the cApitaL`
`LetteRs in them get swappeD. you must write a program to fiX THIS!`

## Description

The input is two strings, `s1` and `s2`, equal in length. They will each contain only printable ASCII and be at least one character in length. You may input these as two strings, an array of two strings, or a single string with `s1` and `s2` separated by either a tab or newline.

The output is the following:

* For each character `c` in `s1`:

+ If the character is not a letter, output it unchanged.
    + Otherwise, if `c` is a letter:

    - Find the matching character (the one at the same index) in `s2`.

        * If it is a capital letter, output `c` capitalized.
            * If it is a lowercase letter, output `c` in lowercase.
            * Otherwise, output `c` unchanged.
* Then do the same thing, except with `s1` and `s2` switched.

Essentially, all letters in `s1` for which the matching character in `s2` is capital should be capitalized, and all letters in `s1` with a lowercase letter at the same index in `s2` should become lowercase (and vice versa).

## Test cases

Input:

```
ABCDEfghijKlMnOpqrstuvwxyz
aaaaaaaaaaaaaaaa----------

```

Output:

```
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------

```

---

Input:

```
PRogrammiNG puzZLes & CODe golf
SdlkhkfaladlKsdlalksdg7ldklDgsl

```

Output:

```
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl

```

---

Input:

```
AAAbbb111
Cc2Dd3Ee4

```

Output:

```
AaABbb111
CC2dd3Ee4

```

# Answer
> 7 votes
# Pyth, ~~19~~ 18 bytes

```
LCmrW&@dG@drG1d2Cb

```

This defines a function **y** that accepts and return a list of strings.

Verify all test cases at once in the Pyth Compiler/Executor.

*Thanks to @Jakube for golfing off 1 byte.*

### How it works

```
                   " (implicit) Initialize G to 'abcdefghijklmnopqrstuvwxyz'.

L                  " Define y(b):
                Cb "   Zip to turn the two strings into an array of char pairs.
  m                "   Map (implicit variable d):
      @dG          "     Intersect d with G.
         @drG1     "     Intersect d with G.upper().
    W&             "     If both are non-empty:
   r          d2   "       Apply swapcase() to d.
 C                 "   Zip to turn the character pairs back into two strings.

```

# Answer
> 12 votes
# CJam, 25 bytes

```
{z{_el_eu&\__:^32&f^?}%z}

```

This is an anonymous function that pops an array of strings from the stack and leaves one in return.

In supported browsers, you can verify all test cases at once in the CJam interpreter.

### Test cases

**Code**

```
qN/2/                     e# Read input and split into arrays of two strings.

{z{_el_eu&\__:^32&f^?}%z}

%                         e# Map the block over all string arrays.
:+N*                      e# Separate the strings by linefeeds.

```

**Input**

```
ABCDEfghijKlMnOpqrstuvwxyz
aaaaaaaaaaaaaaaa----------
PRogrammiNG puzZLes & CODe golf
SdlkhkfaladlKsdlalksdg7ldklDgsl
AAAbbb111
Cc2Dd3Ee4

```

**Output**

```
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl
AaABbb111
CC2dd3Ee4

```

### How it works

```
z                       e# Zip to transform the array of strings into an array
                        e# of character pairs.
 {                  }%  e# For each character pair:
  _el                   e#   Push a copy and convert to lowercase.
     _eu                e#   Push a copy and convert to uppercase.
        &               e#   Intersect. The result will be an empty string if
                        e#   and only if both characters are letters.
         \              e#   Swap the character pair on top of the stack.
          __            e#   Push two copies.
            :^          e#   XOR both characters.
              32&       e#   Logical AND with 32. This pushes 32 for letters of
                        e#   different cases and 0 for letters of the same case.
                 f^     e#   XOR each character with the result.
                   ?    e#   Select the original copy for non-empty intersection
                        e#   and the modified one otherwise.
                      z e# Zip to turn the characters pairs back into two strings.

```

# Answer
> 8 votes
# C, 126 bytes

This is my first attempt at a code golf, ever. Let me know if I did anything wrong.

I'm using bitwise operations to perform the switching

Golfed:

```
main(u,a,s,t)char**a,*s,*t;{for(s=a[1],t=a[2];*t;s++,t++)isalpha(*s)*isalpha(*t)?u=(*t^*s)&32,*t^=u,*s^=u:0;*s=10;puts(a[1]);}

```

Ungolfed:

```
main(u,a,s,t) char**a,*s,*t; {       // K&R style arguments
    for(s=a[1],t=a[2];*t;s++,t++)    // initialize loop.
        isalpha(*s) * isalpha(*t) ? // ensure both characters are letters (if)
            u = (*t^*s) & 0x20,      // check if characters have swapped case
            *t^=u,                   // if so, xor the bit which represents case
            *s^=u                    // for both characters in the string.
        :0;                          // end ternary statement (endif)
    *s=10;                           // replace null terminator in first string
    puts(a[1]);                      // with newline. This allows both output to
}                                    // be printed out all at once

```

edit: replaced && with *

# Answer
> 6 votes
# SQL (PostGreSQL), 427 Bytes

Despite it's huge size, this ended up being quite a bit smaller than I expected. I wasn't quite sure I was going to be able to do it to be honest. I suspect there is a lot that still can be done:)

```
CREATE FUNCTION F(TEXT,TEXT)RETURNS TABLE(S TEXT) AS'SELECT unnest(array[string_agg(CASE WHEN T~''[A-Z]''THEN upper(S)WHEN T~''[a-z]''THEN lower(S)ELSE S END,''''),string_agg(CASE WHEN S~''[A-Z]''THEN upper(T)WHEN S~''[a-z]''THEN lower(T)ELSE T END,'''')])FROM(SELECT ROW_NUMBER()OVER()N,S FROM regexp_split_to_table($1,'''')X(S))A JOIN(SELECT ROW_NUMBER()OVER()M,T FROM regexp_split_to_table($2,'''')Y(T))B ON N=M'LANGUAGE SQL

```

Formatted and commented

```
-- Declare the function spec
CREATE FUNCTION F(TEXT,TEXT)RETURNS TABLE(S TEXT) AS
'SELECT unnest(   -- turns array into a table
    array[        -- build array of the column results
    string_agg( -- Aggregate the result into a string
        CASE
        WHEN T~''[A-Z]''THEN upper(S) -- uppercase it if corresponding char is uppercase
        WHEN T~''[a-z]''THEN lower(S) -- lowercase it if corresponding char is lowercase
        ELSE S END
        ,''''),
    string_agg( -- Same as the previous but swap strings
        CASE
        WHEN S~''[A-Z]''THEN upper(T)
        WHEN S~''[a-z]''THEN lower(T)
        ELSE T END
        ,'''')
    ])
FROM
    -- split the first string
   (SELECT ROW_NUMBER()OVER()N,S FROM regexp_split_to_table($1,'''')X(S))A
    JOIN
    -- split the second string
   (SELECT ROW_NUMBER()OVER()M,T FROM regexp_split_to_table($2,'''')Y(T))B
   ON N=M
'
LANGUAGE SQL

```

Test run

```
SELECT F(A,B) AS Result
FROM (VALUES
    ('AAAbbb111', 'Cc2Dd3Ee4'),
    ('ABCDEfghijKlMnOpqrstuvwxyz', 'aaaaaaaaaaaaaaaa----------'),
    ('PRogrammiNG puzZLes & CODe golf', 'SdlkhkfaladlKsdlalksdg7ldklDgsl')
    )A(A,B)

Result
-----------------------------
AaABbb111
CC2dd3Ee4
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl

```

# Answer
> 4 votes
# Julia, 140 bytes

```
f(s,t)=(C(x,y)=(i=0;z="";for c=x i+=1;z*=string(isalpha(c)?isupper(y[i])?uppercase(c):islower(t[i])?lowercase(c):c:c)end;z);(C(s,t),C(t,s)))

```

This creates a function that accepts two strings and returns a tuple of strings. Nothing particularly clever is going on here; we simply define an inner function that directly implements the algorithm in the spec and call it twice.

Ungolfed:

```
function f(s, t)
    C(x, y) = begin
        i = 0
        z = ""
        for c in x
            i += 1
            if isalpha(c)
                if isupper(y[i])
                    z *= string(uppercase(c))
                elseif islower(y[i])
                    z *= string(lowercase(c))
                else
                    z *= string(c)
                end
            else
                z *= string(c)
            end
        end
        return z
    end

    return (C(s, t), C(t, s))
end

```

# Answer
> 4 votes
# JavaScript ES6, ~~128~~ 108 bytes

```
s=(a,b,t)=>[...a].map((l,i)=>/[^a-z]/.exec(b[i])?l.toUpperCase():l.toLowerCase()).join``+(t?'':`
`+s(b,a,1))

```

JavaScript's `toUpperCase()` and `toLowerCase()` take up a lot of bytes but `String.fromCharCode()` is even longer

# Answer
> 4 votes
## Mathematica, ~~173~~ ~~169~~ 155 bytes

```
f=0>1;t=!f;c=Characters;u=ToUpperCase;StringJoin/@MapThread[#@#2&,{Reverse[{LetterQ@#,#==(u@#)}&/@c@#/.{{f,_}->(#&),{t,t}->u,{t,f}->ToLowerCase}&/@#],c/@#},2]&

```

This is a function taking an array of two strings, e.g. `{"Foo","bAR"}` and outputting an array of two strings. Un-spatially-compressing it, rewriting the scheme `f@x` as `f[x]` wherever it appears, expanding the notation abbreviations (`f=0>1` a.k.a. `False`,`t=!f` a.k.a. `True`, `c=Characters`, and `u=ToUpperCaseQ`), and un-replacing UpperCaseQ\[#\] with `#==u@#` (this character equals its uppercased version), it is:

```
StringJoin /@ MapThread[#[#2] &, {
    Reverse[
        { LetterQ[#], UpperCaseQ[#] } & /@ Characters[#] /.
        { {False, _} -> (# &), {True, True} -> ToUpperCase,
          {True, False} -> ToLowerCase } & /@ #
    ],
    Characters /@ #
}, 2] &

```

Interfacing: the trailing `&` makes this a function. Its argument is inserted as the "#" at both instances of `/@ #`. For instance `f=0>1; ... & [{"AAAbbb111", "Cc2Dd3Ee4"}]` produces the output `{AaABbb111,CC2dd3Ee4}`.

Processing: Told in usual outside in order:

* The output of the `MapThread[...]` is a list of two lists of characters. StringJoin is applied to each of these two lists of characters to produce a list of two strings, the output.
* `MapThread[#[#2]&, ... , 2]` acts on an array of two 2-by-n element lists. The first list is a 2-by-n array of functions. The second list is a 2-by-n array of characters, `Characters /@ #`, the lists of characters in the two input strings. It works at depth 2, i.e., on the functions and individual characters.
* `Reverse[...]` swaps the two sublists of functions so that MapThread will apply the second string's functions to the first string and vice versa.
* `{ ... } &` is an anonymous function that is applied to each of the two input strings.
* `{LetterQ[#], UpperCaseQ[#]} & /@ Characters[#]` splits a string into a list of characters, then replaces each character with two element lists. In these two element lists, the first element is `True` if the character is a letter and `False` otherwise, similarly, the second element indicates whether the character is upper case. `UpperCaseQ[]` cannot return true if it does not receive a letter.
* `/. {{False, _} -> (# &), {True, True} -> ToUpperCase, {True, False} -> ToLowerCase}` replaces these two element lists with functions. (Expansion of the abbreviations `t` and `f` occurs before any matching is attempted.) If a two element list has `False` as its first element, it is replaced with the function `(# &)`, the identity function. (The parentheses are necessary, otherwise the arrow binds more tightly than the ampersand.) Otherwise the two element list starts with `True`, the character was a letter, and we output the functions `ToUpperCase` and `ToLowerCase` corresponding to its case. (Checking for this last `False` is unnecessary, in fact `{_,_}->ToLowerCase` would work, catching anything that hadn't been replaced yet, but this would be no shorter and more obscure.)

The only challenge was figuring out a succinct way to zip a two dimensional array of functions to an array of arguments.

Edit: Thanks to @Martin Büttner for catching "helpful" cut/paste linebreak backslashes, the `1>0` and `1<0` abbreviations, and also for the guidance to count length in bytes not characters (whatever those are :-) )

Edit2: Further thanks to @Martin Büttner for pointing out that polluting the global namespace is acceptable golf, reminding me of one character function application, and suggesting replacing the two uppercase functions with an abbreviation for one and using the one to emulate the other (saving four characters). (I think he's done this before. :-) )

# Answer
> 3 votes
# Python 3, 131 bytes

```
def j(s,g):p=lambda s,g:''.join(i.upper()if j.istitle()else i.lower()if j.islower()else i for i,j in zip(s,g));return p(s,g),p(g,s)

```

Function returns strings in a tuple

# Answer
> 2 votes
# Erlang, 157 bytes

```
f(A,B)->S=string,G=fun(A,B)->[if Q>64andalso Q<91->S:to_upper(P);Q>96andalso Q<123->S:to_lower(P);true->P end||{P,Q}<-lists:zip(A,B)]end,G(A,B)++"\n"++G(B,A).

```

Zips the two strings (actually, lists) into a two-character-tuple list and maps each character to the appropriate case using a list comprehension.

# Answer
> 2 votes
# Python 2, 101 bytes

```
lambda*I:["".join([a.upper(),a.lower(),a][~-b.isalpha()or"Z"<b]for a,b in zip(*X))for X in I,I[::-1]]

```

An anonymous function which takes two strings and returns the output strings in a list. I've marked this as Python 2 because Python 3 doesn't allow `I,I[::-1]` to sit alone at the end like that.

# Answer
> 1 votes
# Python, 126 bytes

```
t="".join;s="low","upp";y=lambda a,b:eval("a"+".%ser()"%s[b.isupper()]*b.isalpha());f=lambda a,b:(t(map(y,a,b)),t(map(y,b,a)))

```

Function `f` returns strings in a tuple

# Answer
> 1 votes
# C, 181 bytes

```
char*x,*y;main(int a,char**_){a?x=_[2],y=_[1],main(0,0),putchar(10),x=_[1],y=_[2],main(0,0):(*x?putchar(!isupper(*x)?!islower(*x)?*y:tolower(*y):toupper(*y)),x++,y++,main(0,0):0);}

```

Had trouble shortening standard library names in a worthwhile way, (#define'ing them takes 11 characters of overhead). Uses main recursion and global variables x and y as arguments.

main(\<non-zero\>,argv) = call main(0,{argv\[1\],argv\[2\]}) then print newline then call main(0,{argv\[2\],argv\[1\]})

main(0,{x,y}) = if x is end of string return 0, else print correct case of first character of x and call main(0,{x+1,y+1}).

Run with the two strings as arguments.

# Answer
> 1 votes
# C - ~~164~~ 153 Bytes - GCC

```
#define r z[_][w]
main(_,z,w)char**z;{while(--_)for(w=0;r;r+=r<25?97:r<91&&r>64?z[!(_-1)+1][w]-=32,_-1?z[_-1][w]-=97:0,32:0,w++);puts(z[1]),puts(z[2]);}

```

gcc prog.c

./a.out AfdgF a2dfsd

Will update if I can get wc -c down. Works very well actually

# Answer
> 1 votes
## Ruby, 102

```
$><<gets.chars.zip(gets.chars).map{|i|/[a-z][A-Z]|[A-Z][a-z]/=~i*''?(i.map &:swapcase):i}.transpose*''

```

Takes the original strings, pairs off letters in arrays. If they are either lower/cap or cap/lower, then swapcase on both. Then transpose the arrays back into our ordered array.

This requires a trailing newline in input.

# Answer
> 0 votes
# F#, 211 chars

```
let n x y=List.fold2(fun a i j->a@match j with|c when c>='A'&&c<='Z'->[Char.ToUpper i]|c when c>='a'&&c<='z'->[Char.ToLower i]|_->[i])[](x|>Seq.toList)(y|>Seq.toList)|>String.Concat
let m a b =n a b+"\n"+n b a

```

could be better ...

# Answer
> 0 votes
## Matlab, 140

```
function [s,t]=f(s,t)
c=s>96&s<123;C=s>64&s<91;d=t>96&t<123;D=t>64&t<91;s(c&D)=s(c&D)-32;s(C&d)=s(C&d)+32;t(d&C)=t(d&C)-32;t(D&c)=t(D&c)+32;

```

Ungolfed:

```
function [s,t] = f(s,t)
c = s>96 & s<123;         % letters that are lowercase in 1st string
C = s>64 & s<91;          % letters that are uppercase in 1st string
d = t>96 & t<123;         % letters that are lowercase in 2nd string
D = t>64 & t<91;          % letters that are uppercase in 2nd string
s(c&D) = s(c&D) - 32;     % make uppercase in 1st string
s(C&d) = s(C&d) + 32;     % make lowercase in 1st string
t(d&C) = t(d&C) - 32;     % make uppercase in 2nd string
t(D&c) = t(D&c) + 32;     % make lowercase in 2nd string

```

Example:

```
>> [s,t]=f('PRogrammiNG puzZLes & CODe golf','SdlkhkfaladlKsdlalksdg7ldklDgsl')
s =
Programming Puzzles & Code Golf
t =
SDlkhkfalADlksdLAlksdg7LDkldgsl

```

# Answer
> 0 votes
# C, 164 bytes

Pretty much implementing the algorithm as described in the problem. Takes 2 strings as input parameters.

```
char*a,*b;main(c,v)char**v;{for(a=v[1],b=v[2];*a&&*b;++a,++b)isupper(*a)&&islower(*b)?*a+=32,*b-=32:isupper(*b)&&islower(*a)?*b+=32,*a-=32:0;puts(v[1]);puts(v[2]);}

```

Ungolfed:

```
char *a, *b; /* Helpers */

main(c, v)
char **v;
{
    /* While strings not terminated... */
    for (a = v[1], b = v[2]; *a && *b; ++a, ++b)
        isupper(*a) && islower(*b)
            ? *a += 32, *b -= 32 /* Make first string lowercase, second uppercase */
            : isupper(*b) && islower(*a)
                ? *b += 32, *a -= 32; /* Make second string lowercase, first uppercase */

    puts(v[1]); /* print out first string */
    puts(v[2]); /* print out second string */
}

```

# Answer
> 0 votes
# Perl 5.10+, 101 99 bytes

```
perl -p00e '/\n/;s/([a-z])(?=.{$-[0]}([a-z]))/$x=($1^$2)&" ";$s{$-[2]}=$2^$x;$1^$x/egis;s|.|$s{$-[0]}//$&|eg'

```

96 bytes + 3 bytes for the command line flags `p00`. Takes a single newline-delimited string as input:

```
$ echo -e "AAAbbb111\nCc2Dd3Ee4" | perl -p00e '...'

```

Or you can enter input on STDIN:

```
$ perl -p00e '...'
AAAbbb111 <Enter>
Cc2Dd3Ee4 <Ctrl+D>

```

## Broken down:

```
perl -p00e'  # Slurp everything into $_, print $_ automatically at the end
    /\n/;    # Match first newline, setting $-[0] to length(s1)

    s/
        ([a-z])  # Match a single letter in s1
        (?=
            .{$-[0]}  # Match n chars where n is length(s1) (until corresponding char in s2)
            ([a-z])   # Corresponding letter in s2
        )
    /
        $x=($1^$2)&" ";   # Check whether bit 6 is the same for both chars.
                          # (Only difference between a lowercase and uppercase ASCII letter
                          # is bit 6; ASCII space is 100000 in binary)

        $s{$-[2]}=$2^$x;  # Swap case of corresponding char in s2 and store in %s,
                          # with position as the key

        $1^$x             # Swap case of current char
    /egis;

    s|.|$s{$-[0]}//$&|eg  # Do a second pass through $_. If there's a value stored in %s
                          # corresponding to this position, use it
'

```

# Answer
> 0 votes
# First attempt in scala, 138 chars

```
def f(s:String,t:String)={val g=(a:Char,o:Char)=>if(o.isUpper)a.toUpper else a.toLower;s.zip(t).map(c=>(g.tupled(c),g(c._2, c._1))).unzip}

```

f is a function that take the two input strings and do the job, with a local function, used two times, for changing case of strings.

The same code, with indentation and just a litte more readable names :

```
def f_ungolfed(first : String, second : String) = {
  val aux = (c1: Char, c2: Char) => if (c2.isUpper) c1.toUpper else c1.toLower
    first.zip(second).map(
         c => (aux.tupled(c), aux.tupled(c.swap))
    ).unzip
}

```

# Answer
> 0 votes
# Jelly, 13 bytes

```
=Œu=/ị"Ɱż"Œs$

```

A monadic Link accepting and returning lists of two "strings" (lists of characters in Jelly).

**Try it online!**

# Answer
> 0 votes
# Python 2, 97 bytes

```
lambda a,b:''.join([x,chr(ord(x)&95|ord(y)&32)][(x+y).isalpha()]for x,y in zip(a+'\n'+b,b+' '+a))

```

Try it online!

# Answer
> 0 votes
# Tcl, 194 bytes

```
proc C a\ b {proc L x\ y {expr [[set S string] is u $y]?"[$S tou $x]":"[$S is lo $y]"?"[$S tol $x]":"$x"}
lmap x [split $a ""] y [split $b ""] {append s [L $x $y]
append t [L $y $x]}
list $s $t}

```

Try it online!

# Answer
> 0 votes
# Haskell, ~~109~~ 91 bytes

```
import Data.Char
(!)=zipWith f
f c|isUpper c=toUpper|isAlpha c=toLower|1<3=id
a#b=[b!a,a!b]

```

Thanks to @Laikoni for 16 bytes!

Try it online!

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


# Question
Title: Minimum operations to get from one number to another
Let's define a simple language that operates on a single 8-bit value. It defines three bitwise operations (code explanation assumes 8-bit `value` variable):

* `!` Negate the least significant bit (`value ^= 1`)
* `<` Wrapping left-shift (`value = value << 1 | value >> 7`)
* `>` wrapping right-shift (`value = value >> 1 | value << 7`)

## Input:

Two 8-bit numbers, *a* and *b*. As they are 8-bit, you can alternatively take them as characters.

## Output:

The shortest way to get from a to b, with the three operations defined above. You can return a string or an array of characters, or define a constant, distinct values for each operation and return an array of those (yes, you could also say `<` means `>` and `>` means `<`), but please explain your output format in your answer.

If there are multiple, equally long ways, you can output any or all of them.

## Rules:

* You can submit a program or function
* Standard loopholes apply
* The submission with fewest bytes **in each language** wins (no answer will be accepted)

Solutions without brute-forcing (or at least not only brute-forcing) might get my upvote.

## Test cases:

```
12, 13 => '!'
1, 2 => '<'
254, 253 => '<'
5, 5 => ''
98, 226 -> '<!>'
64, 154 -> '!>!>>>!>'
177, 164 -> '!>>!>>>!'
109, 11 -> '>>!>!>>'
126, 92 -> '!>!>!>!<' or '!>!>>!<!'
26, 85 -> '<!<<!<!<' or '<!<<!<!>' or '<!<<<!>!'
123, 241 -> '!>!<<!' or '>!<!<!'
236, 50 -> '<<!<!>' or '<<<!>!'
59, 246 -> '<<!>'
132, 95 -> '!<<!<!<!'
74, 53 -> '!>>>!>!'
171, 127 -> '<<!<<!<'
109, 141 -> '!>>>'
185, 92 -> '!>'
166, 201 -> '!<!>>>' or '<!>!>>'
77, 155 -> '<!'
124, 181 -> '!<<<<!>>' or '!>>>>!>>'
108, 85 -> '!<<<!<!<!<' or '!<<<!<!<!>' or '!<<<!<<!>!' or '!>>>!>!>!<' or '!>>>!>!>!>' or '!>>>!>>!<!'
185, 144 -> '<!<<!<!'
70, 179 -> '<<<!<!>' or '<<<<!>!' or '>>>>!>!'

```

Here is a program to generate a few more.

# Answer
## JavaScript (ES6), ~~100~~ ~~96~~ 86 bytes

```
f=(a,b,[c,d,...e]=[a,''])=>c-b?f(a,b,[...e,c^1,d+1,c/2|c%2<<7,d+2,c%128*2|c>>7,d+0]):d
```

```
<div oninput=o.textContent=f(a.value,b.value).replace(/./g,c=>`<!>`[c])>a: <input type=number min=0 max=255 value=0 id=a> b: <input type=number min=0 max=255 value=0 id=b><pre id=o>
```

Somewhat slow breadth-first search without double-checking. Slightly more efficient 114-byte version:

```
f=(a,b,c=[],[d,e,...g]=[a,''])=>c[d]?f(a,b,c,g):d-b?f(a,b,c,[...g,d^1,c[d]=e+1,d/2|d%2<<7,e+2,d%128*2|d>>7,e+0]):e
```

```
<div oninput=o.textContent=f(a.value,b.value).replace(/./g,c=>`<!>`[c])>a: <input type=number min=0 max=255 value=0 id=a> b: <input type=number min=0 max=255 value=0 id=b><pre id=o>
```

Both versions encode `<!>` as `012` but the snippets decode this for you. Edit: Saved 10 utterly useless bytes thanks to @RickHitchcock.
> 4 votes

# Answer
# Jelly, 32 bytes

```
ṃ“ṙ1“ṙ-“¬8¦”
+⁹BḊ€0ÇẎv¥⁼ƭƒ@¥1#ḢÇ

```

Try it online!

**\<**: `['ṙ', '1']`
**\>**: `['ṙ', '-']`
**!**: `['¬', '8', '¦']`

Note: This is a function, that's why the footer is there.

Brute force. :(
> 2 votes

# Answer
# JavaScript (ES6), 105 bytes

Takes the 2 bytes in currying syntax `(a)(b)`.

Returns a string with:

* `0` = `!`
* `1` = `>`
* `2` = `<`

or an empty array if **a** is equal to **b**.

```
a=>g=(b,m=1)=>(h=(n,s=[])=>n^b?s[m]?0:h(n^1,s+0)+h(n/2|n%2<<7,s+1)+h(n%128*2|n>>7,s+2):r=s)(a)?r:g(b,m+1)

```

Try it online! (with codes translated back to `!<>`)
> 1 votes

# Answer
# Python 2, 111 bytes

```
l=[input()+('',)]
for(a,b,i)in l:a==b>exit(i);l+=[(x,b,i+y)for x,y in zip((a*2%256|a>>7,a/2|a%2<<7,a^1),'<>!')]

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~201~~ ~~199~~ ~~198~~ ~~196~~ 193 bytes

* Saved two bytes thanks to ceilingcat; golfing `a/2+a*128` to `(a+2*a*128)/2` to `a*257/2`.
* Saved a byte; golfing `a*2+a/128` to `(a*2*128+a)/128` to `(257*a)/128` to `257*a>>7`.
* Saved ~~two~~ five bytes thanks to ceilingcat, golfing the return type.

# C (gcc), 193 bytes

```
*P,D,Q,j;f(a,b,d){if(a&=255,Q&&a==b)for(Q=j=0;++j<D;printf("%d",j[P]));Q&&++d<D&&f(a^1,b,d,P[d]=1)&f(257*a>>7,b,d,P[d]=2)&f(a*257/2,b,d,P[d]=3);}F(a,b){for(D=Q=1;Q;D++){int p[D];f(a,b,0,P=p);}}

```

Try it online!
> 1 votes

---
Tags: code-golf, binary, graph-theory
---


title: Divide two strings

text:
# Question
Title: Divide two strings
One day, I saw the challenge to multiply two strings and I thought I might be able to do one better.

That challenge was fake. It was elementwise maximum. It was not real multiplication. So I set out to make something real. Real division between two strings.

I quickly realized that this would make an amazing challenge, as the algorithm was surprisingly complex and interesting to implement.

I then realized that it was actually easily reduced into a mere few operations. I'm still doing the challenge, though.

Enough with the backstory. Let's go.

## Method

To divide two strings, do the following, where `x` is the first string and `y` the second:

* If `x` does not contain `y`, return a space and a period concatenated to `x`.
    + For example, `testx` and `blah` would become `.testx`, with a space at the beginning.
* Otherwise, return every occurrence of `y` in `x`, a period, then `y` divided by `x` with every occurrence of `y` removed, with all the periods removed.
    + For example, `eestestst` and `est` would become `estest.est`.

## Challenge

Write a program or function that, given two strings via standard input, returns the first string divided by the second.

You may assume that both input strings will only contain letters between ASCII codepoints 33 and 45, and between codepoints 47 and 126 (yes, space and period are intended to be excluded), and that the operation does not require more than 10 layers of recursion.

You are not required to divide the empty string by itself.

## Test cases

```
test, es => es. es
test, blah =>  .test
okayye, y => yy. y
testes, es => eses. es
battat, at => atat. at
see, es =>  .see
see, e => ee. e
same, same => same.
aabb, ab => ab.ab
eestestst, est => estest.est
aheahahe, aheah => aheah.aheah ah
-={}[];:"'!@#$%^&*()~`\|/.<>_+?, ^&*()~` => ^&*()~`. ^&*()~`
best,  => .

```

## Scoring

As this is , the submission with the least amount of bytes wins.

# Answer
> 3 votes
# Python 2, ~~88~~ ~~85~~ ~~84~~ 77 bytes

```
f=lambda x,y,d='.':y in x and y*x.count(y)+d+f(y,x.replace(y,''),'')or' '+d+x

```

Try it online!

---

Saved

* -1 byte, thanks to LyricLy
* -7 bytes, thanks to Dead Possum

# Answer
> 2 votes
# Java (JDK 11), 146 bytes

```
String f(String x,String y){int c=x.replace(y," ").split(" ",-1).length-1;return c<1?" ."+x:y.repeat(c)+"."+f(y,x.replace(y,"")).replace(".","");}

```

Try it online using Java 10! This TIO emulates `String::repeat` of Java 11 by writing Kevin Cruijssen's implementation as a helper method with the same amount of bytes.

## Explanations

```
String f(String x,String y){                     //
  int c=x.replace(y," ").split(" ",-1).length-1; // Count the number of occurrences of y in x.
                                                 // replace(y," ") fixes the issue on special characters for the split hereafter
                                                 // .split(" ",-1) makes sure that there are trailing elements
  return c<1
    ?                                            // If there are no occurrence, return
      " ."+x                                     // " ."+x
    :                                            // Else return
        y.repeat(c)                              // y, c times
      + "."                                      // append a dot
      + f(y,x.replace(y,"")).replace(".","");    // y divided by x without y, and remove all dots
}

```

`String.repeat(int)` only exists since Java 11, hence the JDK 11 header. Alas and to my knowledge, there are currently no Java 11 online compiler / tester...

# Answer
> 1 votes
## Python 2, 72 bytes

```
lambda f,s:(s*f.count(s)+'.'*(s in f))+s*(s in f)+(' .'+f)*(f.find(s)<0)

```

# Answer
> 0 votes
# Proton, 75 bytes

```
f=(x,y)=>(u=x.count(y))?y*u+'.'+f(y,x.replace(y,'')).replace('.',''):' .'+x

```

Try it online!

# Answer
> 0 votes
# Physica,  ~~81 75~~  67 bytes

```
f=>x;y;d='.':y∈x&&y*x.count[y]+d+f[y;Replace[x;y;''];'']||' '+d+x

```

Try it online!

Utilizes Dead Possum's golfs on TFeld's answer.

# Answer
> 0 votes
# Retina, 105 bytes

```
¶.*$
$&¶.
/^(.*)¶.*\1/{*>|""L`(?<=(.*)¶.*)\1|\.$
(?<=(.*)¶.*)\1|\.$

)`(.*)¶(.*)
$2¶$1
.*¶(.*)¶(.*)
 $2$1

```

Try it online! Link includes test suite, but code normally takes `y` then `x` on separate lines. Explanation:

```
¶.*$
$&¶.

```

Append a newline and a `.` This expression is cumbersome in order to deal with an empty second input, where `$` would otherwise match twice.

```
/^(.*)¶.*\1/{

```

Repeat while `x` contains `y`.

```
*>|""L`(?<=(.*)¶.*)\1|\.$

```

Output all of the matches of `y` in `x`, plus the `.` on the first pass.

```
(?<=(.*)¶.*)\1|\.$

```

And then delete them all.

```
)`(.*)¶(.*)
$2¶$1

```

Swap over `x` and `y` and repeat.

```
.*¶(.*)¶(.*)
 $2$1

```

Output the `.` if `x` never contained `y`, and `y`.

# Answer
> 0 votes
# JavaScript (Babel Node), 90 bytes

*Based on Olivier Grégoire Answer*

```
(_,x)=>(l=_.match(RegExp(x,`g`)))?l.join``+`.`+f(x,_.replace(x,'')).split`.`.join``:` .`+_

```

Try it online!

# Answer
> 0 votes
# Stax, 28 bytes

```
Çûù=a┐µ¬▄↑ivÜ°{⌐╨[£èvÇu┴▓<v~

```

Run and debug it

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


# Question
Title: Insulate the Window Glass and Foil of your house
## Introduction:

The best options for the glass of your house will:
1. Let through as little heat as possible in both directions (insulation-value `Ug`).
(2. Let through as much sunbeams as possible from the outside to the inside.)
(3. Let through as much light as possible from the outside to the inside.)

We only care about the first one for this challenge.

In addition, there are different types of glass changing the `Ug`: regular single glass; regular double glass; HR double glass; HR+ double glass; HR++ double glass; HR+++ double glass.
HR = High Rendement glass; regular double glass with have air between both layers, but HR will have a noble gas between both layers.

Sources (not very useful for most though, because they are in Dutch, but added them anyway): Insulate and save money and What is HR++ glass?

## Challenge:

**Input:** A string indicating glass and window foil (below the possible input-strings are explained)
**Output:** (Calculate and) output the heat-transition `Ug`

**Here a table with all glass options and the expected output `Ug`-values:**

```
Glass (optional foil)    Ug-value    Description

|                        5.8         Single-layered regular glass
||                       2.7         Double-layered regular glass
| |                      1.85        HR glass
|+|                      1.45        HR+ glass
|++|                     1.2         HR++ glass
|+++|                    0.7         HR+++ glass
|r                       3.4         Single-layered regular glass with reflective foil
||r                      2.1         Double-layered regular glass with reflective foil
|f                       2.8         Single-layered regular glass with regular window-foil
||f                      2.0         Double-layered regular glass with regular window-foil

|g                       4.35        | with insulating curtain
||g                      2.025       || with insulating curtain
| |g                     1.3875      | | with insulating curtain
|+|g                     1.0875      |+| with insulating curtain
|++|g                    0.9         |++| with insulating curtain
|+++|g                   0.525       |+++| with insulating curtain
|rg                      2.55        |r with insulating curtain
||rg                     1.575       ||r with insulating curtain
|fg                      2.1         |f with insulating curtain
||fg                     1.5         ||f with insulating curtain

/                        8.7         Diagonal |
//                       4.05        Diagonal ||
/ /                      2.775       Diagonal | |
/+/                      2.175       Diagonal |+|
/++/                     1.8         Diagonal |++|
/+++/                    1.05        Diagonal |+++|
/r                       5.1         Diagonal |r
//r                      3.15        Diagonal ||r
/f                       4.2         Diagonal |f
//f                      3.0         Diagonal ||f

/g                       6.525       Diagonal | with insulating curtain
//g                      3.0375      Diagonal || with insulating curtain
/ /g                     2.08125     Diagonal | | with insulating curtain
/+/g                     1.63125     Diagonal |+| with insulating curtain
/++/g                    1.35        Diagonal |++| with insulating curtain
/+++/g                   0.7875      Diagonal |+++| with insulating curtain
/rg                      3.825       Diagonal |r with insulating  curtain
//rg                     2.3625      Diagonal ||r with insulating curtain
/fg                      3.15        Diagonal |f with insulating curtain
//fg                     2.25        Diagonal ||f with insulating curtain

```

Some things to note about the values: the first ten are all the different default values (taken from the two linked sources). Adding a `g` (insulating curtain) lowers that value by 25%. Having a `/` (diagonal window) increases that value by 50%.

## Challenge rules:

* You can ignore any floating point precision errors
* You can use the default decimal output-format of your languages, so if `3.0` is output as `3` instead; or if `0.9` is output as `0.900` or `.9` instead, it doesn't matter.
* You'll only have to worry about the input-options given above. Inputting anything else may result in undefined behavior (weird outputs, errors, etc.)

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation of your answer.

# Answer
# Python 2, ~~172~~ ~~147~~ ~~128~~ ~~117~~ ~~112~~ 99 bytes

```
lambda w:ord('8%06(*D0t0'[sum(map(ord,w.strip('g')))%77%24%13])*(2+('/'in w))*(4-('g'in w))/160.

```

Try it online!

---

**Explanation:**

Encodes the window as a sum of the ordinals of each char (without trailing `g`):

```
sum(map(ord,w[:(w+'g').find('g')]))

|      ->   124                /      ->   47
||     ->   248                //     ->   94
| |    ->   280                / /    ->   126
|+|    ->   291                /+/    ->   137
|++|   ->   334                /++/   ->   180
|+++|  ->   377                /+++/  ->   223
|r     ->   238                /r     ->   161
||r    ->   362                //r    ->   208
|f     ->   226                /f     ->   149
||f    ->   350                //f    ->   196

```

These are modded (`%77%24%13`), which gives values from 0 to 12):

```
sum(map(ord,w[:(w+'g').find('g')]))%77%24%13

|      ->   124   ->   10      /      ->   47    ->   10
||     ->   248   ->   4       //     ->   94    ->   4
| |    ->   280   ->   1       / /    ->   126   ->   1
|+|    ->   291   ->   12      /+/    ->   137   ->   12
|++|   ->   334   ->   2       /++/   ->   180   ->   2
|+++|  ->   377   ->   8       /+++/  ->   223   ->   8
|r     ->   238   ->   7       /r     ->   161   ->   7
||r    ->   362   ->   6       //r    ->   208   ->   6
|f     ->   226   ->   0       /f     ->   149   ->   0
||f    ->   350   ->   5       //f    ->   196   ->   5

```

The `Ug` values are multiplied by `20` and mapped to chars:

```
[0.7,    1.2,    1.45,   1.85,  2.0,  2.1,  2.7,  2.8,  3.4, 5.8]
[14,     24,     29,     37,    40,   42,   54,   56,   68,  116]
['\x0e', '\x18', '\x1d', '%',   '(',  '*',  '6',  '8',  'D', 't']

```

These chars are then ordered accordingly to the window-types, and padded with `'0's`. This new strign is used to look up the value based on the index.

```
'8%\x1806(*D\x0e0t0\x1d'#[sum(map(ord,w[:(w+'g').find('g')]))%77%24%13])

```

Lastly the given character is converted back into a number, and multiplied be the diagonal window and isolating curtain factors

```
*(2+('/'in w))*(4-('g'in w))/160.
equivalent to:
*2/2 or 3/2   * 4/4 or 3/4  /20

```

---

Saved

* -5 bytes, thanks to ovs
* -13 bytes, thanks to Lynn
> 7 votes

# Answer
# Java (JDK 10), 110 bytes

```
s->"8%06(*D0t0".charAt(s.split("g")[0].chars().sum()%77%24%13)*(s.charAt(0)%2+2)*(s.endsWith("g")?3:4)/160d

```

Try it online!

## Credits
> 2 votes

# Answer
# JavaScript (ES6), ~~111~~ 109 bytes

```
s=>'_FQLKIe%f:}'.charCodeAt((g=c=>~-s.split(c).length)(/\W/)+3*g` `+6*g`r`+8*g`f`)*5%117/(g`g`?8:g`|`?6:4)*.3

```

Try it online!

### How?

We define the helper function **g()** as:

```
g = c => ~-s.split(c).length

```

`split()` takes either a string or a regular expression as input. Hence, so does **g()**.

We define:

```
- N = g(/\W/) = number of non-alphanumeric characters
- S = g(' ')  = number of spaces
- R = g('r')  = number of "r"
- F = g('f')  = number of "f"
- G = g('g')  = number of "g"
- P = g('|')  = number of "|"

```

The formula **n = N + 3S + 6R + 8F** gives a unique identifier in **\[1..10\]** for all default values:

```
 input   | N | S | R | F | n
---------+---+---+---+---+----
 "|"     | 1 | 0 | 0 | 0 | 1
 "||"    | 2 | 0 | 0 | 0 | 2       NB: because 'g' characters are ignored in this formula
 "| |"   | 3 | 1 | 0 | 0 | 6           and because a '/' is counted the same way as a '|',
 "|+|"   | 3 | 0 | 0 | 0 | 3           the 2 other sets of inputs give the same results.
 "|++|"  | 4 | 0 | 0 | 0 | 4
 "|+++|" | 5 | 0 | 0 | 0 | 5
 "|r"    | 1 | 0 | 1 | 0 | 7
 "||r"   | 2 | 0 | 1 | 0 | 8
 "|f"    | 1 | 0 | 0 | 1 | 9
 "||f"   | 2 | 0 | 0 | 1 | 10

```

We use this identifier to pick the corresponding entry from the following 1-indexed array, which contains the default values multiplied by **20**:

```
[116, 54, 29, 24, 14, 37, 68, 42, 56, 40]

```

This array is encoded as the string `"FQLKIe%f:}"`. For each character, we multiply the ASCII code by **5** and apply a **modulo 117**:

```
 char | code | * 5 | mod 117
------+------+-----+---------
 'F'  |   70 | 350 |   116
 'Q'  |   81 | 405 |    54
 'L'  |   76 | 380 |    29
 'K'  |   75 | 375 |    24
 'I'  |   73 | 365 |    14
 'e'  |  101 | 505 |    37
 '%'  |   37 | 185 |    68
 'f'  |  102 | 510 |    42
 ':'  |   58 | 290 |    56
 '}'  |  125 | 625 |    40

```

Finally, we divide this value by:

* **80 / 3** if **G** is non-zero
* **60 / 3** if **P** is non-zero
* **40 / 3** otherwise
> 2 votes

# Answer
# Excel & CSV, 194 bytes

```
,"=HLOOKUP(SUBSTITUTE(SUBSTITUTE(A1,""g"",),""/"",""|""),2:3,2,)*IF(CODE(A1)=47,1.5,1)*IF(RIGHT(A1,1)=""g"",0.75,1)"
|,||,| |,|+|,|++|,|+++|,|r,||r,|f,||f
5.8,2.7,1.85,1.45,1.2,0.7,3.4,2.1,2.8,2

```

Input entered before the first `,`n and saved as `CSV`. When opened in Excel, Cell `B1` displays result.

Sample usage:

```
/+++/g,"=HLOOKUP(SUBSTITUTE(SUBSTITUTE(A1,""g"",),""/"",""|""),2:3,2,)*IF(CODE(A1)=47,1.5,1)*IF(RIGHT(A1,1)=""g"",0.75,1)"
|,||,| |,|+|,|++|,|+++|,|r,||r,|f,||f
5.8,2.7,1.85,1.45,1.2,0.7,3.4,2.1,2.8,2

```

Opens as:

```
/+++/g  0.7875
|       ||      | |     |+|     |++|    |+++|   |r      ||r     |f      ||f
5.8     2.7     1.85    1.45    1.2     0.7     3.4     2.1     2.8     2

```
> 1 votes

---
Tags: code-golf, string, number, arithmetic
---


# Question
Title: There are two new sheriffs in town – Identifying DJMcMego pairs!
We have some new ~~sheriffs~~ moderators in town, Mego and DJMcMayhem. We need a challenge to properly honour them for their new positions, so there we go.

Here's something that has caught my attention when hovering over their profiles – their user IDs are \\$31716\\$ and \\$45941\\$. If you perform digit-wise subtraction, you'll notice something pretty exciting (of course, taking the absolute differences):

```
3|1|7|1|6
4|5|9|4|1
-+-+-+-+- (-)
1|4|2|3|5

```

The number generated by the above algorithm is \\$14235\\$. There is something special about this integer: It consists of *consecutive* digits only, sorted in ascending order, but *exactly one* of the digits is not placed correctly — \\$4\\$.

We will call a pair of positive integers \\$(a, b)\\$ a *DJMcMego pair* if the digit-wise absolute differences are consecutive integers, sorted in ascending order, but exactly one of them is not where it belongs. That is, it is possible to move *exactly one* digit of the result of digit-wise subtraction to another position, such that the integer obtained only has consecutive digits, sorted in ascending order.

In our example above, the pair \\$(31716, 45941)\\$ is a *DJMcMego* pair, because if \\$4\\$ is moved between \\$3\\$ and \\$5\\$, the result is \\$12345\\$, which fulfils the criteria. Note that the digits of the resulting number **do not** need to start at \\$1\\$, they just ought to be consecutive. When one is unsure about what decision they should make, they can always rely on the other's help to sort things out.

Your task is to output a truthy/falsy value depending on whether a pair of positive integers given as input is a DJMcMego pair.

* You are guaranteed that \\$a\\$ and \\$b\\$ will have the same number of digits, always at least 4.
* You can take the integers in any reasonable format (i.e. native integers, strings, lists of digits, etc.)
* You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is , so the shortest submission (in bytes) for *every language* wins.

## Test cases

```
a, b -> Output

31716, 45941 -> Truthy
12354, 11111 -> Truthy
56798, 22222 -> Truthy
23564, 11111 -> Truthy
1759,  2435  -> Truthy
12345, 11111 -> Falsy
3333,  2101  -> Falsy
22354, 22222 -> Falsy
31717, 45941 -> Falsy
14325, 11111 -> Falsy
89789, 78865 -> Falsy
14954, 61713 -> Falsy
25631, 11114 -> Falsy

```

Or, in another format.

# Answer
> 7 votes
# C (gcc), ~~259~~ ~~258~~ ~~254~~ ~~253~~ ~~250~~ ~~248~~ ~~233~~ 222 bytes

* Thanks to Stan Strum for inspring a one byte golf.
* Saved four bytes by juggling some variable initializations.
* Saved a byte by golfing `for(...;l++)b*=B[l]==-~B[l-1];` to `for(...;b*=B[l]==-~B[~-l++]);` (most likely relying on undefined behaviour, as it requires first evaluating `B[l]` followed by `-~B[~-l++]`).
* Saved ~~three~~ five bytes.
* Saved ~~fifteen~~ twenty-six bytes thanks to ceilingcat.

```
j,k,l,L,r,b;f(char*A,char*B){for(j=r=0;k=A[L=j];)A[j++]=-~abs(A[j]-B[j]);for(;k-L;k++)for(j=~0;L-++j;r|=!b)if(k-j)for(bcopy(B-~l,strcpy(B,A)+l,strlen(A+l)),bcopy(B+j,B-~j,L+~j),B[j]=A[k],l=b=0;B[++l];b|=B[l]+~B[~-l]);A=r;}

```

Try it online!

# Explanation (248 byte version)

```
j,k,l,L,r,b;                            // global variables
f(char*A,char*B){                       // function takes two strings
 for(j=r=0;A[j];L=j)                    // loop through A, compute array length L
  A[j++]=-~abs(A[j]-B[j]);              // set every entry in A to the absolute
                                        // difference of A and B at that position
                                        /* Test out all possible movements of        *
                                         * characters and see if any one             *
                                         * results in a sorted list => DJMcMego pair */
 for(j=0;j-L;j++)                       // loop through array
  for(k=~0;L-++k;r|=!b)                 // loop through array
   if(j-k){                             // j is not equal to k
    for(l=0;A[l];B[l++]=A[l]);          // copy A to B
    for(l=j;A[l];B[~-l]=B[++l]);        // shift part of B
    for(l=L;l-k;B[-~l]=B[--l]);         // shift part of B
    B[k]=A[j];                          // insert character at correct position
    for(l=b=0;B[++l];b|=B[l]+~B[~-l]);} // test if B is sorted
 A=r;}                                  // return if there was a DJMcMego pair found

```

Try it online!

# Answer
> 7 votes
# 05AB1E, 18 bytes

```
αDæIg<ùʒD{Q}gĀ*{¥P

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 130 bytes

Takes input as two arrays of digits in currying syntax `(a)(b)`. Returns a boolean.

```
a=>b=>a.some((_,i)=>a.some((_,j)=>i-j&&!(A=a.map((v,i)=>Math.abs(v-b[i]))).some(v=>v-A[~k--]-1,A.splice(i,0,A.splice(j,1)[k=0]))))

```

Try it online!

# Answer
> 4 votes
# , 27 bytes

−8 bytes thanks to FrownyFrog

```
1"0(-:(2-/\|\:|),1#.2>/\|)-

```

Try it online!

## Initial solution:

# , 35 bytes

```
[:((1=[:*/2-/\\:~)*1=1#.0<2-/\])|@-

```

Try it online!

## Explanation

Takes lists of digits as input

`|@-` finds the absolute difference between the digits of the lists

`1=1#.0<2-/\]` Checks if only one digits is out of its place. First I find the differences between all pairs of adjacent digits and check to see if only one of them is positive.

`*` Multiply the result from the above test (1 or 0) with the following test:

`1=[:*/2-/\\:~` Are all digits consecutive? I sort the list down, take the differences for all pairs of adjacent digits, multiply them and check if it equals 1

# Answer
> 4 votes
# SWI-Prolog, 157 bytes

Not very short but the problem seemed particularly well-suited for declarative predicates, variable binding and recursion, i.e., Prolog :)

```
n(T,Y):-s(T,Q,I,J),s(Y,W,I,J),m(Q,W).
s(T,Q,I,J):-nth0(I,T,X,R),nth0(J,Q,X,R),I\=J.
m([A,B|T],[C,D|Y]):-1 is abs(B-D)-abs(A-C),m([B|T],[D|Y]).
m([_],[_]).

```

Call with, e.g., `n([3,1,7,1,6],[4,5,9,4,1]).`

Explanation: move an element in both lists to a new position (using the SWI-Prolog `nth0` built-in) and check if the difference of the new lists is consecutive.

```
s(T,Q,I,J)    % switch (yet unbounded) index I and J in list T, store in Q
s(Y,W,I,J)    % switch (now bounded) I and J in list Y
m(Q,W)        % check new lists
s(T,Q,I,J) :- nth0(I,T,X,R) % X (unbounded) is the I-th (unbounded) element
                            % of list T with rest R (=prefix+postfix)
nth0(J,Q,X,R) % the same X is the J-th element in list Q with the same rest R
I\=J          % I and J are unequal
m([A,B|T],[C,D|Y]) :-  % consider first two elements of both lists
1 is abs(B-D)-abs(A-C) % check if differences are consecutive
m([B|T],[D|Y])         % recursion starting with the second element
m([_],[_]).            % stop recursion at last element in the list

```

# Answer
> 4 votes
# Jelly, 14 bytes

```
ạµṢ_JEċ@Œ¿-Ƥ%L

```

Try it online!

### How it works

```
ạµṢ_JEċ@Œ¿-Ƥ%L  Main link. Arguments: A, B (digit arrays)

ạ               Take the elementwise absolute difference. Call the result R.
 µ              New chain. Argument: R
  Ṣ             Sort R.
    J           Indices; yield [1, ..., len(R)].
   _            Take the elementwise difference.
     E          Test if all differences are equal.
                The result is 1 if R consists of consecutive digits, 0 otherwise.
          -Ƥ    For all outfixes of R, generated by dropping one of its elements:
        Œ¿        Get its permutation index (1 if sorted, higher if not).
      ċ@        Count the number of times the Boolean from the left appears in the
                array to the right. If the Boolean is 1, the count represents the
                number of ways a single digit can be deleted to yield a sorted
                array. The count has to be positive for a DJMcMego pair, but less
                than the length of R, since R may not be sorted.
            %L  Take the result modulo len(R), mapping len(R) to 0.

```

# Answer
> 3 votes
# Japt, 18 bytes

> Been debating whether I should post this or not for a couple of hours. Came up with it quickly late last night but didn't have time to test it properly (*and* I thought it might be too long!). Oliver has since posted a similar solution (which was, when this one was originally posted, invalid) so if he, or the community, feels this is *too* similar, I'll happily delete it.

Takes input as 2 digit arrays, outputs `0` for `true` or any other number for `false`.

```
íaV
ä> x*Un än × É

```

Try it or check all test cases

---

## Explanation

```
                   :Implicit input of digit arrays U and V               :[3,1,7,1,6],[4,5,9,4,1]
í V                :Interleave V with U                                  :[[3,4],[1,5],[7,9],[1,4],[6,1]]
 a                 :Get the absolute difference of each pair             :[1,4,2,3,5]
\n                 :Assign that new array to variable U
ä>                 :Is each element greater than the next?               :[false,true,false,false]
     Un            :Sort U                                               :[1,2,3,4,5]
        än         :Get the deltas                                       :[1,1,1,1]
           ×       :Reduce by multiplication                             :1
    *              :Multiply each element in the boolean array by that   :[0,1,0,0]
   x               :Reduce by addition                                   :1
             É     :Subtract 1                                           :0

```

And, to walk through that process on a few more test cases:

```
---------------------------------------------------------------
| U   | [2,3,5,6,4] | [1,2,3,4,5] | [3,1,7,1,7] | [1,4,9,5,4] |
| V   | [1,1,1,1,1] | [1,1,1,1,1] | [4,5,9,4,1] | [6,1,7,1,3] |
|-----|-------------|-------------|-------------|-------------|
| íaV | [1,2,4,5,3] | [0,1,2,3,4] | [1,4,2,3,6] | [5,3,2,4,1] |
|-----|-------------|-------------|-------------|-------------|
| ä>  | [F,F,F,T]   | [F,F,F,F]   | [F,T,F,F]   | [T,T,F,T]   |
|-----|-------------|-------------|-------------|-------------|
| Un  | [1,2,3,4,5] | [0,1,2,3,4] | [1,2,3,4,6] | [1,2,3,4,5] |
| än  | [1,1,1,1]   | [1,1,1,1]   | [1,1,1,2]   | [1,1,1,1]   |
| ×   | 1           | 1           | 2           | 1           |
|-----|-------------|-------------|-------------|-------------|
| *   | [0,0,0,1]   | [0,0,0,0]   | [0,2,0,0]   | [1,1,0,1]   |
| x   | 1           | 0           | 2           | 3           |
| É   | 0           | -1          | 1           | 2           |
---------------------------------------------------------------

```

# Answer
> 2 votes
# Perl, ~~121~~ 118 bytes

```
($a,$b)=map[split//],@ARGV;
$s+=$l>$_,$l=$_ for@c=map abs($$a[$i]-$$b[$i++]),@$a;
@c=sort@c;
say$s==1&&$c[-1]-$c[0]==$#$a

```

Test in bash:

```
function golf {
   perl -E'($a,$b)=map[split//],@ARGV;$s+=$l>$_,$l=$_ for@c=map abs($$a[$i]-$$b[$i++]),@$a;@c=sort@c;say$s==1&&$c[-1]-$c[0]==$#$a' $1 $2
}
golf 31716 45941       #says 1, true
golf 12354 11111       #says 1, true
golf 56798 22222       #says 1, true
golf 46798 22222       #says nothing, false
golf 22354 22222       #says nothing, false
golf 1759 2435         #says 1, true
golf 12345 11111       #says nothing, false
golf 89789 78865       #says nothing, false
golf 14954 61713       #says nothing, false

```

# Answer
> 2 votes
# Java 8, ~~245~~ ~~227~~ ~~223~~ ~~194~~ 188 Bytes

### Thanks to Kevin for saving ~29 bytes

### Thanks to Kevin again for another 6 bytes

```
 z->{int l=z.length/2,c[]=new int[l],i=0,j=0;for(;i<l;)c[i]=Math.abs(z[i]-z[i+++l]);java.util.Arrays.sort(z=c.clone());for(i=0;i<l-1;j+=z[i]-z[i-1]!=1?1:0)j+=c[i]-c[++i]>0?1:0;return j==1;}

```

Followed the same pattern Galen came up with for his J answer.

Try it online!

# Answer
> 2 votes
# Retina, 102 bytes

```
+`(.)(.*¶)(.)(.*)
$2$4;$1,$3
\d
*
(_*),\1
_
L$w`(;_+\b)(.*)(;_+\b)
$%`$2$3$1$%"$3$1$2$'
m`(^;_+|\1_)+$

```

Try it online! Link includes test cases. Returns the number of ways digits can be moved to achieve an ascending sequence, which is 2 for a straight swap since either digit can be moved past the other in that case. Explanation:

```
+`(.)(.*¶)(.)(.*)
$2$4;$1,$3

```

Pair up the digits.

```
\d
*

```

Convert to unary.

```
(_*),\1
_

```

Take the difference, but then add 1 because working with zero in Retina is hard™.

```
L$w`(;_+\b)(.*)(;_+\b)
$%`$2$3$1$%"$3$1$2$'

```

List all the sequences of digits obtained by moving exactly one digit.

```
m`(^;_+|\1_)+$

```

Check for consecutive digits.

# Answer
> 2 votes
# Ruby, ~~124 113 99~~ 95 bytes

```
->l,b,d=-1{m=l.map!{|i|(i-b[d+=1]).abs}.sort;l.any?{|*i|m-i==l-i}&&m!=l&&/#{m*''}/=~[*0..9]*''}

```

Try it online!

# Answer
> 2 votes
# Perl 5, -F ~~87~~ ~~84~~ 83 bytes

Old style counting: 86 bytes (`+3` for `-F`)

Give he numbers as 2 lines on STDIN, the last line without a trailing newline.

Prints the difference string up to 2 times for true, nothing for false

The long `A0123456789` string is really annoying.

```
#!/usr/bin/perl -F
$_=<>;s%.%abs$&-$F[pos]%eg;s%%"'$`$''=~s:|:A0123456789=~/\$`$&\$'/>//&&say:reg"%eeg

```

Try it online!

I'm usure if this `79` counts as valid:

```
$_=<>;s%.%abs$&-$F[pos]%eg;s,,$a=$&;"$`$'"=~s:|:A0123456789=~/$`$a$'/%//:reg,eg

```

It crashes for a valid pair, so you get a non zero exit code. It does nothing if not a pair and exits with exit code 0. I know returning the result via exit code is allowed, but are they properly truthy and falsy or in fact reversed (for the shell `0` is true) ?

# Answer
> 1 votes
# Pyt, ~~20~~ 18 bytes

```
ą←ą-ÅĐʁ>Ʃ1=⇹ş₋Π1=∧

```

Try it online!

Explanation:

```
       Implicitly get the first number
ą      Convert to list of digits
←      Get the second number
ą      Convert to list of digits
-Å     Take the absolute value of the differences of the lists element-wise
Đ      Duplicate the list of differences
ʁ>     Reduce by greater than
Ʃ1=    Is the sum of that array equal to 1
⇹      Swap the top two items on the stack
ş      Sort the top of the stack ascending
₋      Reduce by subtraction (from the right)
Π1=    Is the product of the array equal to 1
∧      bitwise-AND (in this case, also logical AND) the top two items on the stack
       Implicit print

```

# Answer
> 1 votes
# Add++, 105 bytes

```
D,w,@~,Ñ_€|BSVcGbU1b]2b]+º=
D,k,@,BPB*
L,BcB_€|B]dBkbUBSVcGbU£>sVcGB]VBKB#BKBcB_0º>b]GBK{w}b]++b*1=BK{k}*

```

Try it online!

Defines a lambda function that takes two lists of digits as input. Outputs a positive integer divisible by **24**1 for DJMcMego pairs, **0** otherwise.

1: If this is too restrictive, it also outputs a positive integer for DJMcMego pairs, and **0** otherwise

## How it works

Here we perform 4 checks to determine if the input is valid. The parts of the code that do those checks are

```
BcB_€|B]dBkbUBSVcGbU£>sVcGB]V

```

Here, we take the list of absolute digit differences, then count the number of overlapping pairs which are sorted in descending order. Every DJMcMego pair produces a result of **1**, but they are not unique in this aspect. We also store the inputs' absolute digit differences, to save bytes later. This array will be referred to as **A** throughout.

```
BKB#BKBcB_0º>b]

```

Next, we take the elementwise differences between **A** and **A** sorted, before asserting that at least one of those differences is negative.

```
D,w,@~,Ñ_€|BSVcGbU1b]2b]+º=
GBK{w}b]

```

Third, we check if the pair **\[1, 2\]** is contained in the forward increments of **A**. This checks that, in at least one position of **A**, it is sorted, which is a criterion for DJMcMego pairs.

```
D,k,@,BPB*
BK{k}

```

As our last check, we assert that the second element of **A** is never **0**. In order for a pair, **X** and **Y**, to be a DJMcMego pair, we can assume that their **A** is always unique, as an array with duplicates in it can never be made consecutive by swapping a single value with another.

Finally, we check that the first three of these tests returned **1**, and that the fourth returned a value **x** such that **x ≠ 0**

A step for step walk through of the code is as follows

```
D,w,		; Define a function **w**;
		;   This takes an array of integers
		;   Returns whether the pair [1, 2] appears in the absolute forward differences
		;
	@	; Take one argument
	~,	; Splat that argument to the stack
		;   Example argument:		[1 4 2 3 5]
		;
	Ñ_	; Increments;		STACK = [3 -2 1 2]
	€|	; Magnitudes;		STACK = [3 2 1 2]
	BSVcGbU	; Overlapping pairs;	STACK = [[3 2] [2 1] [1 2]]
	1b]2b]+	; Push [1 2];		STACK = [[3 2] [2 1] [1 2] [1 2]]
	º=	; Any equal [1 2];	STACK = [1]

; ============= ;

D,k,		; Define a function **k**;
		;   This function takes an array of integers
		;   Returns whether the second element is **0**;
		;
	@,	; Take one argument and push to the stack
		;   Example argument:		[[1 4 2 3 5]]
		;
	BP	; Behead;		STACK = [[4 2 3 5]]
	B*	; Product;		STACK = [120]
		;
		; In DJMcMego pairs, **A** may begin with a **0**
		; For example, 12354 and 11111, so we need to remove the first element
		; Taking the product yields **0** if any element is **0**
		; However, in order to be a DJMcMego pair, two digits at the same index
		;   cannot be the same, otherwise their digit-wise difference will be **0**

; ============= ;

L,		; Define a lambda function
		;
		; This lambda function takes two arrays of digits as input
		; Returns an integer to determine if those digits represent a DJMcMego pair
		;
		; A lambda function is shorter to define than a normal function
		; However, when called inside functions with the **]** command,
		;   they consume the entire stack as arguments, meaning that using functions
		;   allows us to preserve important values
		;
		; Example arguments:		[[3 1 7 1 6] [4 5 9 4 1]]
		;
		; First check:
		;
	BcB_	; Digit differences;	STACK = [-1 -4 -2 -3 5]
	€|	; Magnitudes;		STACK = [1 4 2 3 5]
	B]dBkbU	; Save a copy, **A**	STACK = [1 4 2 3 5]			**A**: [1 4 2 3 5]
	BSVcGbU	; Overlapping pairs;	STACK = [[1 4] [4 2] [2 3] [3 5]]
	£>	; Sorted descendingly?	STACK = [0 1 0 0]
	sVcG	; How many?		STACK = [1]
	B]V	; Save a copy;		STACK = []				Register: [1]
		;
		; Second check:
		;
	BK	; Retrieve **A**;		STACK = [[1 4 2 3 5]]
	B#	; Sort;			STACK = [[1 2 3 4 5]]
	BK	; Retrieve **A**;		STACK = [[1 2 3 4 5] [1 4 2 3 5]]
	BcB_	; Element differences;	STACK = [0 -2 1 1 0]
	0º>b]	; Any negatives;	STACk = [[1]]
		;
		; Third and fourth checks:
		;
	G	; Retrieve register;	STACK = [[1] [1]]
	BK	; Retreive **A**;		STACK = [[1] [1] [1 4 2 3 5]]
	{w}b]	; Run **w**;		STACK = [[1] [1] [1]]
	++	; Concatenate;		STACK = [[1 1 1]]
	b*1=	; Product = 1;		STACK = [1]
	BK{k}	; Run **k**;		STACK = [1 120]
	*	; Multiply;		STACK = [120]

		; To force output as **1** and **0** values,
		;   append a ? to the end, to output the sign (forces boolean conversion)

```

# Answer
> 1 votes
# , ~~110 106~~ 84 bytes

```
function(x,y,z=abs(x-y),w=z-min(z)+1)adist(p(1:max(w)),p(w),c("s"=9))==2
p=intToUtf8

```

Try it online!

@JayCe with a ridiculous 22 byte save!

The workhorse here is `adist`, which gives a "generalized Levenshtein edit distance" between two strings. By default the distance is the count of the minimal number of insertions, deletions, and substitutions required to transform one string into another. But `adist` allows you to weight things how you like - so I've weighted each substitution to add 9 to the distance rather than 1. This effectively forces the algorithm to look for insertions and deletions only.

This code accepts vectors of integers, computes the absolute elementwise differences, and translates the result to begin at 1, calling it `w`.

Then the custom weighted Levenshtein distance is computed between `w` pasted together to make a string and the string `"1234..."` (actually utf-8 `"\001\002\003\004...`" but `adist` doesn't care.) with the same number of characters as `w`.

The only way the string can have exactly one digit out of place is if you make one deletion and one insertion, giving a distance of 2.

# Answer
> 0 votes
# Python 2, ~~116~~ ~~119~~ 106 bytes

Thanks Mr. Xcoder for the `116->84` cut, but I found I have missed the "consecutive number" criteria, so 26 bytes are added for that purpose :(

After that, -1 more Thanks Mr. Xcoder, and -13 Thanks ovs

```
def m(a,b):l=[abs(x-y)for x,y in zip(a,b)];print sum(e>f for e,f in zip(l,l[1:]))==1==len(l)-max(l)+min(l)

```

Try it online!

**That one below fixes `25634 - 11111` problem but with double length (~~211~~ ~~206~~ ~~145~~ 142B)... Golfing...**

```
def m(a,b):l=[abs(x-y)for x,y in zip(a,b)];r=[l[i]-i-min(l)for i in range(len(l))];print(sum(r)==0)&(len([x for x in r if abs(x)>1])<2)&any(r)

```

Try it online!

And congratulations to new moderators :)

**Explanation:**

```
l=[abs(x-y)for x,y in zip(a,b)]

```

Generates the list of absolute differences of the digits.

```
r=[l[i]-i-min(l)for i in range(len(l))]

```

Calculates the offset from the proper position.

```
sum(r)==0

```

If the sequence is not continuous, then offset sum will "usually" not be 0. But even if it equals 0, the next ones will block them out.

```
len([x for x in r if abs(x)>1])<2

```

Only 0 or 1 item will have absolute offset larger than 1 (the one with wrong position, and 0 is in the case like `1,2,3,5,4`)

```
any(r)

```

Blocks the case when the numbers are all in correct positions

# Answer
> 0 votes
# JavaScript, ~~137~~ ~~136~~ ~~135~~ ~~134~~ ~~132~~ 123 bytes

Takes input as two arrays of digits in currying syntax, outputs `0` for `true` and any other number for `false`.

```
a=>b=>(c=a.map((x,y)=>(x-=b[y])<0?-x:x)).map(x=>t+=x>c[++j]&(d=[...c].sort()).slice(i=0,-1).every(x=>d[++i]-x&1),t=j=0)|t^1

```

---

## Test Cases

```
f=
a=>b=>(c=a.map((x,y)=>(x-=b[y])<0?-x:x)).map(x=>t+=x>c[++j]&(d=[...c].sort()).slice(i=0,-1).every(x=>d[++i]-x&1),t=j=0)|t^1
o.innerText=`${l=`-`.repeat(21)}\n|   #1  |   #2  | f |${m=`\n|${`|`.padStart(8,`-`).repeat(2)}---|\n`}${[[31716,45941],[12354,11111],[56798,22222],[23564,11111],[1759,2435],[12345,11111],[3333,2101],[22354,22222],[31717,45941],[89789,78865],[14954,61713]].map(([x,y])=>`| ${JSON.stringify(x).padEnd(6)}| ${JSON.stringify(y).padEnd(6)}| ${f([...``+x])([...``+y])} |`).join(m)}\n`+l
```

```
<pre id=o></pre>
```

# Answer
> 0 votes
# Haskell, ~~182~~ ~~163~~ ~~162~~ 132 bytes

```
(#)=zipWith(-)
a&b|s<-abs<$>a#b=or[all(==1)$tail a#a|(x,h:y)<-p s,(q,r)<-p$x++y,a<-[q++h:r],a/=s]
p l=[splitAt k l|k<-[0..length l]]

```

Takes input as a list of digits. Helper function `p` that gives all possible ways to split a list into two parts is used to take an element out and again to insert it elsewhere.

Try it online!

---
Tags: code-golf, array, decision-problem, sorting
---


title: I forgot towel day

text:
# Question
Title: I forgot towel day
# I forgot towel day

Sandbox link

PHP script for both examples (error, formatting the string)

Corrected php script, the input is self explanatory

PHP script with more input comment/uncomment `$argv` to see different results

As you may know, May 25 is well known as **Towel Day**, because of the many uses a towel can have.

A simple extract of the book **"The Hitchhiker's Guide to the Galaxy"** (personally I took this book as an **"everyday guide"**) states:

> *"A towel is about the most massively useful thing an interstellar hitchhiker can have. Partly it has great practical value."*

If you need more information about towels check **this SE.scifi answer**

---

## The Challenge

Hopefully you will do this with a towel used as a blanket for your legs.

Write a full program or function in any valid programming language that takes two inputs

```
size        Integer  : #The size
message     string   : #A sentence

```

### How to draw a towel with these values?

**First using `size`**:

Draw a towel depending on the size input, for our towel

```
  width = 12*size

  #the line that has the "bar" its always present with different sizes

  Width is defined as:
  from the first | to the second | has to be equal to size*12 including both ||

      <-   width->
  [===|          |====]
      | 12 chars ||   1  height starts here, just after the "bar"
      | SIZE = 1 ||   2
      |          ||   3   height = 5*size
      |          ||   4
      |          ||   5  height ends here just before the first line |=======|
      |==========||   # the lines with the #
      |==========||   # are always fixed
      """"""""""""|   # it means, every towel
       |          |   # always has this 5 rows
       """"""""""""   # no matter the size

```

**Second, give it the `message`**

You have to give it a message, *what is a towel without a beautiful message sewed in golden thread?*

**Example 1**

```
  input: size=1, message="a simple message can stay with size"

  width = 12*size

  #the line that has the "bar" it's always present with different sizes
  #no words allowed at the bar level

  [===|          |====]
      | a simple ||   1  height starts here, just after the "bar"
      | message  ||   2
      | can stay ||   3   height = 5*size
      | with size||   4
      |          ||   5  height ends here just before the first line |=======|
      |==========||   # the lines with the #
      |==========||   # are always fixed
      """"""""""""|   # it means, every towel
       |          |   # always has this 5 rows
       """"""""""""   # no matter the size

```

**Example 2**

```
input size=2
message="Don't Panic and bring a towel to SE Programming Puzzles and CodeGolf"

The size is 2
That means 24 width and 10 heigth

    <-    24 chars width  ->
[===|                      |====]
    | Don't Panic and bring||   1
    | a towel to SE        ||   2
    | Programming Puzzles  ||   3
    | and CodeGolf         ||   4
    |                      ||   5
    |                      ||   6
    |                      ||   7
    |                      ||   8
    |                      ||   9
    |                      ||   10
    |======================||   #  The lines with the "#"
    |======================||   #  always present and
    """"""""""""""""""""""""|   #  adapted to
     |                      |   #  the towel width
     """"""""""""""""""""""""   #

```

**Accepted answer criteria**

* This is **codegolf** so normal rules apply.

**Rules**

* You are guaranteed that all the input strings will fit the size, so no input like `size=1; message="This string is just tooooooooooooooooooooo long to fit the width and height of your towel"`.
* The string format is up to you, if you want to center the substrings for example.
* **Word-breaks** are disallowed.

### Edits

I am truly sorry about any confussion, because the ansii towels i draw did not matched the parameters, added a **PHP script for both examples** for you to check the expected outputs.

Also thank you to all the people who voted up and considered my first challenge :D.

# Answer
# Python 2, ~~223~~ ~~210~~ ~~209~~ 204 bytes

```
def f(s,m):w=12*s-2;l='    |';print'[===|'+' '*w+'|====]';exec"j=(m+' ').rfind(' ',0,-~w);print l+'%*s||'%(w,m[:j]);m=m[j+1:];"*s*5;print(l+w*'='+'||\n')*2+' '*4+'"'*12*s+'|\n '+l+' '*w+'|\n    ','"'*12*s

```

Try it online!
> 4 votes

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

This is the worst submission you will get, but at least I tried xD half of bytes are spaces though

```
(s,_,w=12*s-2,h=5*s)=>`
[===|${j=' '.repeat(w)}|====]
${[...Array(h)].map((g,i)=>_.split` `.reduce((a,b)=>((l=a.split`,`)[l.length-1]+b).length>w-1?a+','+b:a+' '+b,'').split`,`[i]).map(a=>`    |${a?(r=a.length)<w?a+' '.repeat(w-r):a:j}||    `).join`\n`+
`
    |${'='.repeat(w)}||    `.repeat(2)}
    ${y='"'.repeat(w+2)}|
     |${j}|
     ${y}
`

```

Try it online!
> 2 votes

# Answer
# JavaScript (Node.js), ~~347 345 343 337 334 328~~ 326 bytes

```
b=>d=>`
[===|${M=" "[X="repeat"](c=12*b-2)}|====]
${[...Array(5*b)].map((a,b)=>d[Y="split"]` `.reduce((a,b)=>((l=a[Y]`,`)[l[Z="length"]-1]+b)[Z]>c-1?a+","+b:a+" "+b)[Y]`,`[b]).map(a=>`    |${a?(r=a[Z])<c?a+" "[X](c-r):a:" "[X](c)}||    `).join`
`+`
    |${"="[X](c)}||    `[X](2)}
    ${y='"'[X](c+2)}|
     |${M}|
     ${y}
`

```

Try it online!

---

# Explanation :

```
b =>                                   // lambda function taking arg 1 : size
    d =>                               // arg 2 : message
        `                              // begin string template for drawing
[===|${                                // draw first part and now open literal
        M = ' '[X='repeat'(c=12*b-2)]  // set 3 variables, M, X , c to be used again
    }|====]                            // close and draw the next part ====]
${[...Array(5*b)]                      // open and create an array of length 5 * b =width
.map(a,b=>                             // begin map function two args : a,b
        d[Y='split']` `                // use d(message), split at whitespace, set to Y
.reduce((a,b) =>                       // reduce to single value, arg 1 : a, arg 2 : b
        ((l = a[Y]`,`)                 // declare l and then find in l
        [l[Z='length']-1]              // set Z as length
        + b)                           // add value of b
        [Z]                            // find the length
        > c-1 ?                        // check if it's less than c - 1
        a+','+b                        // then add `${a},${b}`
        : a + ' ' + b                  // otherwise `${a} ${b}`
        )[Y]`,`                        // close and split at comma
        [b]                            // use b again
        )                              // close
        .map(a =>                      // map over that arg 1 : a
                `    |${               // four space + | and open
        a ?                            // if a is true or a truthy value
            (r=a[Z])                   // set value of r as a's length
            < c ?                      // check if it's less than c
                a+' '[X](c-r)          // then draw a + space repeated c-r times
                : a + ' '[X](c)        // else draw a + space repeated c times
            }                          // close
            ||    `                    // add || and 4 spaces and close
        )                              // end
        .join`
`                                      // and turn to string with new line as separator
    +                                  // add to that
    `
    |{                                 // new line , 4 spaces and |
        '='[X](c)}                     // repeat = c times
        ||    `[X](2)}                 // and repeat that 2 times
    ${                                 // new line + 4 space
    y = '"'[X](c+2)                    // repeat " c + 2 times and set to y
    }|                                 // close and add |
    |{                                 // add | and open
        M}|                            // put M and close and add |
    {y}                                // new line , 4 spaces and variable y
`                                      // end with new line.

```
> 2 votes

# Answer
# Charcoal, 79 bytes

```
Ｎθ≔×⁵θε≔×¹²θδ←Ｐ←====[↓⁺³ε×"δ↖Ｐ↑⁺³ε←Ｇ↑²←⁻δ²↓²=↓↓↓¹×"δ↖↑⁺⁴ε====]Ｆ⪪Ｓ «×⸿›⁺ⅈＬι⁻δ² ι

```

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

```
Ｎθ≔×⁵θε≔×¹²θδ

```

Calculate the size of the towel.

```
←Ｐ←====[↓⁺³ε×"δ↖Ｐ↑⁺³ε←Ｇ↑²←⁻δ²↓²=↓↓↓¹×"δ↖↑⁺⁴ε====]

```

Draw the towel.

```
Ｆ⪪Ｓ «

```

Loop over each word of the message.

```
×⸿›⁺ⅈＬι⁻δ² ι

```

Print each word without overflowing the width.
> 2 votes

# Answer
# , ~~142~~, ~~128~~, ~~121~~, 119 bytes

```
:let @h=5*@a
:let @w=12*@a-2
O[===|@wá 4á=á]
:set tw=w
Vgq@hï{+@hjI    |kf|@hjjyt=pjp+@hjkl@wr=Ùjlr|Ù@w««r"YkP0xÁ|

```

Try it online!
> 1 votes

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


title: Finding number of digits in an integer

text:
# Question
Title: Finding number of digits in an integer
Given an integer n as input write a program to output the numbers of digit in it.

**Input**

```
12346

456

```

**Output**

```
5

3

```

**Constraint**

```
n<=10^9

```

# Answer
> 8 votes
# GolfScript, 1 character

```
,

```

`,` means length...

Edit: You seem to have changed your question... please don't do that, but I still have a solution:

# GolfScript, ~~12~~ 7 characters (for multiline)

```
n%{,n}/

```

Thanks @Howard for reminding me about `n` to push newline and using separate strings instead of one, to save 5 chars ;)

Solutions that work with negative numbers:

# GolfScript, 5 (for negative)

```
'-'-,

```

# GolfScript, 11 (for multiline and negative)

```
n%{'-'-,n}/

```

# Answer
> 4 votes
I'm trying to stay away from the simple string length functions, but the BF solution basically does a count.

# Pure math/Mathematica - 22 chars (for mathematica)

```
floor(log10(abs(n)))+1

```

Thanks to @plg for the correction when n is a power of 10. This invokes undefined behavior when n=0, but that case can be returned by a simple check.

# PHP implementation of the above math solution - 34 chars

```
($n==0)?1:floor(log(abs($n),10))+1;

```

# BrainF\*ck - 54 characters

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

```

# Answer
> 4 votes
# Perl

```
s/\D//;$_=length

```

run as:

```
perl -ple 's/\D//;$_=length'

```

# Answer
> 3 votes
## python 2, 25

```
print len(`abs(input())`)

```

works for both positive and negative integers

# Answer
> 3 votes
# Dc: 3 characters

```
?Zp

```

Sample run:

```
bash-4.2$ dc -e '?Zp' <<< '12346'
5

bash-4.2$ dc -e '?Zp' <<< '345'
3

```

# Answer
> 2 votes
# PHP (30 chars)

echo `$n<0?(strlen($n)-1):strlen($n)`

(without php opening tags `<?php` & `?>`)

## Explanation

Pretty simple, ints can be interpreted as strings, therefore `$n<0` has a minus-char that should be removed in the true-statement of the ternary operator. If its positive then we just count the length ;)

# Answer
> 2 votes
# Java 8, ~~29~~ 28 bytes

```
i->(""+(i<0?-i:i)).length();

```

# Ungolfed test program

```
public static void main(String[] args) {
    IntFunction<Integer> func = i -> ("" + (i < 0 ? -i : i)).length();

    System.out.println(func.apply(12345)); //5
}

```

# Answer
> 2 votes
## R, 25 bytes

```
cat(nchar(scan("stdin")))

```

# Answer
> 1 votes
# Perl (with `-lp`) (11 bytes, counting `lp`)

```
$_=length

```

# Answer
> 1 votes
## Befunge-98, 8 or 12 chars

**Single number** (actually counts input bytes ≥15 and prints count at EOF)
```
#.~f`+#@

```
**Multiline support** (same as above, but print count at byte \<15 and reset counter)
```
#@~f`:2*j\.+

```

# Answer
> 1 votes
# C - 59 characters

```
main(k){scanf("%i",&k);printf("%i\n",(int)log10(abs(k))+1);}

```

# Answer
> 1 votes
A DELPHI PROGRAM FOR CONSOLE

```
program P;
{$APPTYPE CONSOLE}
uses
  System.SysUtils;
var a: Integer;
begin
   readln(a);
   writeln(length(IntToStr(a)));
end.

```

# Answer
> 1 votes
**Ruby**

```
$*.first.size

```

or

```
ARGV.first.size

```

# Answer
> 1 votes
# Python 2, 22 bytes

```
lambda a:len(`abs(a)`)

```

I actually built this myself, before seeing Wasi's answer! This is how I thought of it:

* I need: a `lambda`.
* `len`? `False`! What about `n<0`? Should the `-` be counted? `False`!
* How to eliminate the `-` in just a few bytes? `abs`!

*\[Thinking ends\]*

# Answer
> 1 votes
## Go, 67 bytes

```
package main;import."fmt";func main(){s:="";Scan(&s);Print(len(s))}

```

# Answer
> 0 votes
# JavaScript, 20

```
alert((""+n).length)

```

# Answer
> 0 votes
# k \[7 chars\]

```
f:{#$x}

```

Example:

```
f 12346
5

f 456
3

```

Though only 2 characters (#$) are required to find the length of the input number.

```
#$123444
6

```

# Explanation

convert the input to string.

```
$123456
"123456"

```

count the number of characters:

```
#$123456
6

```

Q equivalent of this code:

```
f:{count string x}
f 123456
6

```

# Answer
> 0 votes
### R

The solution at 18 characters (identical in concept to the python solution of Wasi):

```
nchar(abs(scan()))

```

And the funnier one at 33 characters:

```
which(!abs(scan())%/%10^(1:9))[1]

```

# Answer
> 0 votes
## GTB, 3

Assuming value is already stored:

```
l?_

```

To make user input:

```
`_l?_

```

Newline support with interactive input:

```
[`_~l?_]

```

# Answer
> 0 votes
### Perl

### 15 chars - no input or constraint checks

```
$_=()=$_=~/\d/g

```

### 48 chars - checks input & constraint

```
$_=/^-?(\d+)$/?($1<=10**9?length($1)."\n":$_):$_

```

NB. If the input (`$_`) is an integer (positive or negative) and comes under the constraint then it amends `$_` to the number of digits. Otherwise it just leaves the input as is.

Usage example:

```
perl -ple '... insert above code...'

```

# Answer
> 0 votes
## PowerShell (25)

```
($n-replace"-",'').length

```

where $n is a number

# Answer
> 0 votes
## C, 63 59 57 characters

It's slightly longer than the other C solution, but it works on arbitrarily large numbers (numbers with `2^32 - 1` digits rather than numbers up to `2^32 - 1`).

EDIT: It's now shorter than the other C solution!

```
c;main(n){n-10?main(getchar(),c+=n>47):printf("%d\n",c);}

```

Note: if you call the program with exactly 9 arguments, it will fail. But why would you do that??

# Answer
> 0 votes
# bash - 19 characters

Assuming input via standard input:

```
grep -o [0-9]|wc -l

```

Multi-line version - 48 characters:

```
while read L;do echo $L|grep -o [0-9]|wc -l;done

```

# Answer
> 0 votes
### APL - 4 characters

```
ρ'n'

```

The first symbol, rho, checks the number of cells in an array, where one character of a string is equal to one cell.

# Answer
> 0 votes
# Tcl, 26 bytes

```
puts [string length $argv]

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 2 bytes

```
þg

```

Try it online or verify all test cases.

**Explanation:**

```
þ     # Take the digits of the input
 g    # And output the length

```

# Answer
> 0 votes
# Japt, 2 bytes

```
ìl

```

Try it

`ì` converts to a digit array and `l` gets the length.

# Answer
> 0 votes
# RProgN 2, 2 bytes

```
âL

```

Gets the length of the Absolute Value of the input. Trivial.

Try it online!

# Answer
> 0 votes
# Braingolf, 5 bytes

```
!s*dl

```

Try it online!

As with all the others, `abs` then `len`

# Answer
> 0 votes
# Thing, 12 bytes

```
idh\-=[tLe]L

```

Try it online!

## How?

Gets input from command line arguments. If the first character of input is "-", push the length of the all but first items of the string and immediately end the program. Else, push the length of the string. Then implicitly print.

Does not work with multiline.

```
i push input
d duplicate
h first character of
\- push the character "-"
= if top two values are equal, push 1, if not, 0
    [ if top value is truthy (not [] or 0), go into the block. if not,  go past the end of the block.
    t push the all but first items of the stack's top value (literally s[1:] in python)
    L length
    e end the program
    ] end loop
L length

```

---
Tags: code-golf
---


title: Decode My String (Brackets)

text:
# Question
Title: Decode My String (Brackets)
*Taken from StackOverflow Question*

**Challenge**

Given an encoded string in format `n[s]` where `n` is the amount of times `s` will be repeated, your task is to output the corresponding decoded string.

* `n` will always be a positive number
* `s` can not contain empty spaces
* `strings` only contains letters from the alphabet
* `s` length can be `>= 1`
* encoded format is `number [ string ]`
* string can have nested encoded string `number [ number [ string ] ]`
* return the same string if not encoded

**Examples**

```
2[a]                 => aa
3[2[a]]              => aaaaaa
2[b3[a]]             => baaabaaa
3[a]5[r3[c]2[b]]a    => aaarcccbbrcccbbrcccbbrcccbbrcccbba
a                    => a  // Not Encoded
3                    => 3  // Not Encoded
3a3[b]               => 3abbb
10[b20[a]]           => baaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaa
3[hello]             => hellohellohello

```

**Other test cases**

```
a[a] => a[a]
a1[a] => aa
3[] =>    // Nothing because are 3 empty string
2[2][a] => 2[2][a]

```

---

**This is my own submission.**

```
f=i=>(r=/(\d+)\[([a-z]*)\]/g).test(l=i.replace(r,(m,n,s)=>s.repeat(n)))?f(l):l

console.log(f("2[a]"))
console.log(f("3[2[a]]"))
console.log(f("2[b3[a]]"))
console.log(f("3[a]5[r3[c]2[b]]a"))
console.log(f("a"))
console.log(f("3"))
console.log(f("3a3[b]"))
console.log(f("10[b20[a]]"))
console.log(f("3[hello]"))
```

---

If more test cases needed please tell me.

# Answer
> 2 votes
# QuadR, 17 +  flag = 28 bytes

```
\d+\[\pL*]
∊(⍎⍵M∩⎕D)⍴⊂⍵M∩⎕A

```

Try it online!

Find:

`\d+\[\pL*]` find **d**igit(s) followed by bracketed **L**etters

Replace with:

`⎕A` uppercase **A**lphabet

`⍵M∩` intersection of **M**atch and that

enclose (to treat as a whole)

`(``)⍴`**r**eshape to length:

`⎕D`**D**igits

`⍵M∩` intersection of **M**atch and that

execute (converts text to number)

**ϵ**nlist (flatten)

---

This is equivalent to the Dyalog APL function:

```
'\d+\[\pL*]'⎕R{∊(⍎⍵.Match∩⎕D)⍴⊂⍵.Match∩⎕A}⍣≡

```

# Answer
> 1 votes
# Perl 6,  ~~44~~  36 bytes

```
{({S{(\d+)\[(<:L>*)\]}=$1 x$0}...*eq*).tail}

```

Test it

```
Nil while s{(\d+)\[(<:L>*)\]}=$1 x$0

```

Test it (with `-p`)

## Expanded:

```
Nil                   # silence warning by using Nil rather than 0

while                 # do the above while the following is truish

  s {                 # string replace (implicitly on $_)

    ( \d+ )           # capture a series of digits into $0
    \[
      ( <:L>* )       # capture letters
    \]

  } = $1 x $0         # replace it with the string repeated by the number

```

# Answer
> 1 votes
# Retina, 24 bytes

```
+`(\d+)\[(\p{L}*)]
$1*$2

```

Try it online!

Updated to support additional test cases. -1 thanks to @Adám!

# Answer
> 0 votes
## Perl 5, 36 bytes

```
0while s/(\d+)\[([a-z]*)]/$2x$1/e

```

# Answer
> 0 votes
# Japt v2.0a0, 19 bytes

```
e/(\d+).(\l+)]/@ZpY

```

Try it

# Answer
> 0 votes
# Stax, 21 bytes

```
è/g1┘+α╣m?╣t╥ó⌂ß─"H║à

```

Run and debug it

# Answer
> 0 votes
# ReRegex, 83 bytes

```
#import base
(\d+)\[([a-z]+)]/Au<$1>,$2,B/_,([a-z]+),/,$1,$1/A,.*?,(.*?)B/$1/#input

```

ReRegex is a language designed around regex. Sadly, it doesn't really understand numbers. So repeating the string is the hardest part of this.

Try it online!

# Answer
> 0 votes
# Red, 158 bytes

```
func[s][b: charset[not"[]"]d: charset"0123456789"until[r: on
parse s[to remove[copy n any d"["copy t any b"]"](insert/dup
c: copy""t do n r: off)insert c]r]s]

```

Try it online!

## More readable:

```
f: func [ s ] [
    b: charset [ not "[]" ]
    d: charset "0123456789"
    until [
        r: on
        parse s [
            to remove [ copy n some d "[" copy t any b "]" ]
                ( insert/dup c: copy "" t do n
                r: off )
            insert c ]
        r
    ]
    s
]

```

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


title: Tips for golfing in Visual Basic

text:
# Question
Title: Tips for golfing in Visual Basic
## This page is not for Visual Basic .NET Tips or VBA tips

Visual Basic (VB or VB6) is an object-oriented and event-driven dialect of that was developed and released by Microsoft in 1991. The last release of Visual Basic came as Visual Basic 6.0 in 1998, and the language was declared a legacy language in 2008. Visual Basic .NET replaced Visual Basic in 2002.

All answers on this site that are written in Visual Basic are assumed to be written for Visual Basic 6.0 unless otherwise stated.

> Some helpful links

You may compile and execute Visual Basic code using Visual Studio Community.

There is no online resource for compiling VB code.

# Answer
# Use `DefXXX` statements when declaring multiple variables

The statement

```
DefDbl A-D

```

Defines all variables that start with `A` through `D` as being of the type `Double`, which means this can shorten cases such as

```
Dim A As Double
Dim B As Double
Dim C As Double
Dim D As Double

```

Similar commands exist for the following types

```
DefBool     ''  Boolean
DefByte     ''  byte
DefCur      ''  Currency
DefDate     ''  Date
DefDbl      ''  Double
DefDec      ''  Decimal
DefInt      ''  Integer
DefLng      ''  Long
DefObj      ''  Object
DefSng      ''  Single
DefStr      ''  String
DefVar      ''  Variant

```
> 1 votes

# Answer
# Use `Console.Write` over `Console.WriteLine`

There is quite a large amount of overhead code necessary to get a snippet of code to execute in VB, and by default this overhead is configured to take up quite a large amount of bytes - for instance

```
Module M
Sub Main
Console.WriteLine("Hello, World!")
End Sub
End Module

```

May be golfed down by 4 bytes by the `Console.Write(...)` command over `Console.WriteLine(...)`.

```
Module M
Sub Main
Console.Write("Hello, World!")
End Sub
End Module

```
> 0 votes

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


title: Tips for golfing in Proton

text:
# Question
Title: Tips for golfing in Proton
Proton is a quite new language created by PPCG user Hyper Neutrino.

It is very similar to Python, and has similar syntax to the language Cheddar, hence there are some clever tricks you can use in order to reduce your byte count. Let's get those cool tricks listed here. As usual, please post one tip per answer and avoid obvious things (e.g. remove spaces). If you have any further questions about any of the tips listed, there is a dedicated chat room for Proton.

# Answer
# Use currying when you need a lambda with 2 arguments

If you want a function with 2 arguments, currying syntax always saves 1 byte. For example:

```
f=(a,b)=>a+b

```

Is one byte longer than:

```
f=a=>b=>a+b

```

The first function can be called with `f(number_1, number_2)`, whilst the latter is called using `f(number_1)(number_2)`.

Try it online!
> 3 votes

# Answer
# Take advantage of the fun features: operator functions

`(+)` for all binary operators where the `+` is evaluates to a function that performs the exact same task as the operator itself. Where you'd use `int.__add__` when golfing in Python, use `(+)` for many bytes saved.
> 3 votes

# Answer
# Use `..`-ranges

Instead of using `range(lower_bound, upper_bound)`, use `lower_bound..upper_bound`. For unary ranges, use `0..number` instead of `range(number)`. Some examples:

```
range(1,10)

```

Can be replaced by (-6 bytes):

```
1..10

```

And:

```
range(10)

```

Can be replaced by (-4 bytes):

```
0..10

```
> 1 votes

# Answer
# Use inline-assignment

Consider the following two:

```
a=>(a+5)*2/(a+5)
a=>(b=a+5)*2/b

```

You can use inline assignments (where you treat an assignment as an expression) in Proton. The value given will be the right side of the assignment. This can sometimes help you take off a few bytes; more the longer the repeated expression, and especially if it has brackets already (because you need the brackets around the expression).
> 1 votes

# Answer
# Use point-free notation

Even though lambda notation has a much shorter overhead than Python (`a=>` vs `lambda a:`), point-free notation is still often shorter, where you define a function as a composition of other functions. For example, consider the following chain of golfing:

```
a=>b=>dict(a)[b]
a=>dict(a).get
dict+((.)&get)

```

The last one currently isn't any shorter than the second last, but it does become shorter in some cases, for example, this:

```
a=>b=>[dict(a).get(f)for f:b]
a=>b=>map(dict(a).get,b)
a=>map(dict(a).get)
dict+((.)&get)+map

```

You can get some pretty short code with that. `a & b` will return a function `*q => a(*q, b)` if `a` is a function and otherwise `*q => b(a, *q)` if `b` is a function, and `a + b` will return a function `*q => b(a(*q))`.
> 1 votes

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


title: Goodness, it's covered in tabs!

text:
# Question
Title: Goodness, it's covered in tabs!
Space indentation users, *unite*! We must fight against all the lowly tab users!

Your mission (should you choose to accept it) is to write a program or function that takes in two arguments:

* A string: This is the input.
* A positive integer: This the number of spaces per tab.

You must go through every line of the string and replace every tab *used for indentation* with the given number of spaces, and every tab not used for indentation (e.g. in the middle of a line) with one space.

Note that lines such as `\t \tabc` are undefined behavior; they were inserted by the evil tab users to complicate your programs.

According to the Tabs Must Die Society, your program must be as short as possible to avoid detection by the evil tab users.

## Example

`\t` is used to represent tabs here.

Input string:

```
a
\t\tb\tc
d

```

Input number:

```
4

```

Output:

```
a
        b c
d

```

The middle line was indented by 8 spaces, 4 per tab (since the given number was 4).

Input string:

```
\ta\t\tb

```

Input number:

```
4

```

Output:

```
    a  b

```

**NOTE:** This is *not* a duplicate of the tab expansion challenge; it requires a very different input format and slightly different requirements.

# Answer
> 7 votes
# CJam, ~~30~~ ~~24~~ 23 bytes

```
q{_9=NA=Seasi*' ?@?:N}/

```

I usually refuse to post malicious code on the internet…

This is a full program that reads the string from STDIN and the number as a command-line argument.

Try it online in the CJam interpreter.

### How it works

```
q                        Read all input from STDIN.
 {                   }/  For each character C in the input:
  _9=                      Push 1 if C is a tab and 0 otherwise.
     NA=                   See below.
        Seasi*             Push a string of W spaces, where W is the integer from
                           the command-line arguments.
              '            Push a spaces character.
                ?          Select the string if NA= pushed a truthy value, the
                           single space otherwise.
                 @         Rotate C on top of the stack.
                  ?        Select the string of spaces or the single space if _9=
                           pushed 1, the character C otherwise.
                   :N      Save the result in N.

```

What `NA=` does:

* For the first character, `N` will contain its default value, i.e., the string `"\n"`.

For all subsequent characters, `N` will contain the result of the last iteration, i.e., the last character from input, a space character or a string of one or more spaces.
* If `N` is a string, `NA=` selects the element at index 10 of N (wrapping around). The result will be a space or a linefeed character. Both are truthy.

If N is a character, `NA=` pushes 1 for a linefeed and 0 otherwise.
* Because of the above, `NA=` will push a truthy value for the first character, a character preceded by a linefeed or a character preceded by a string of spaces (indentation that has already been replaced).

In all other cases (including a tabulator that has been replace by a space *character*), `NA=` will push a falsy value.

# Answer
> 19 votes
# K5, ~~53~~ 45 bytes

```
{{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y}

```

In action:

```
  {{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y}[4;(,"a";"\t\tb\tc";,"d")]
(,"a"
 "        b c"
 ,"d")

```

I just want the record to show that this question is morally reprehensible.

# Answer
> 8 votes
# Perl, 23 bytes

22 bytes code + 1 bytes command line

Hopefully not too cheeky to assume the numeric input can be given via the -i parameter! Ensure to replace \t in the below code with the actual tab character.

```
s/\G\t/$"x$^I/ge;y/\t/ /

```

Usage example:

```
printf "a\n\t\tb\tc\nd" | perl -p entry.pl -i4

```

Or for convenience:

```
printf "a\n\t\tb\tc\nd" | perl -pe 's/\G\t/$"x$^I/ge;y/\t/ /' -i4

```

### Explanation:

Using the `-p` argument will execute the program for every line in the input, then print the result at the end.

In the above example, the regex substitution replaces `\G\t` with `" "x4` (a space repeated four times). `\G` is a little-known regex construct which matches either the position of first match if the first iteration, or from the position of the previous match if not the first iteration, meaning it will only replace all tabs at the start of the string, and will do so one-by-one. The `y/\t/ /` simply replaces all remaining tabs with spaces.

# Answer
> 2 votes
# Julia, ~~69~~ 59 bytes

```
f(s,n)=(r=replace)(r(s,r"^\t*"m,i->" "^endof(i)n),"\t"," ")

```

Ungolfed:

```
function f(s::String, n::Int)
    # Replace the leading indentation tabs
    r1 = replace(s, r"^\t*"m, i -> " "^endof(i)n)

    # Replace any remaining tabs between words
    r2 = replace(r1, r"\t", " ")

    # Return
    r2
end

```

Saved 10 bytes and fixed an issue thanks to Glen O!

# Answer
> 2 votes
# Mathematica, ~~42~~ 37 bytes

Thanks to @LegionMammal978 for multiple code-saving suggestions. The first parameter, `#` is for the input text, the second parameter, `#2`, for the number of spaces per tab.

```
StringReplace[#,"\t"->" "~Table~{#2}]&

```

# Answer
> 2 votes
# Haskell, 82 bytes

```
n!('\t':x)=([1..n]>>" ")++n!x
n!x=f<$>x
f '\t'=' '
f x=x
g n=unlines.map(n!).lines

```

Then `g 3 "a\n\t\tb\tc\nd"` does the thing.

# Answer
> 1 votes
# Ruby 49 bytes

```
def r s,t;s.gsub! /^\t/,' '*t;s.gsub!"\t",' ';end

```

# Answer
> 1 votes
# JavaScript (ES6), 70

Using template strings, the newline is significant and counted

```
(s,n,r=n)=>[...s].map(c=>c<`
`?` `.repeat(r):(r=c<` `?n:1,c)).join``

```

Test running the snippet below in Firefox.

```
F=(s,n,r=n)=>[...s].map(c=>c<`
`?` `.repeat(r):(r=c<` `?n:1,c)).join``

// TEST
out=x=>O.innerHTML+=x+'\n\n'

out('Input: "A\\n\\t\\tB\\tC\\nD" 4\nOutput:\n'+F('A\n\t\tB\tC\nD',4))

out('Input: "\\tA\\t\\tB" 4\nOutput:\n'+F('\tA\t\tB', 4))
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
# CoffeeScript, 72 bytes

```
(s,n)->s.replace(/^\t+/mg,(m)->" ".repeat(m.length*n)).replace /\t/g," "

```

(Trying to golf it at least 2 more bites, so it will beat the ES6 solution... Help appreciated :D)

Usage:

```
f=(s,n)->s.replace(/^\t+/mg,(m)->" ".repeat(m.length*n)).replace /\t/g," "
str="""
My nice\tString
\tIndent <--
\t\tDouble
""" #\t is recognized as tab by CS
alert(f(str,4))

```

# Answer
> 1 votes
# Retina, 42 bytes

All occurrences of `.` are spaces, all `\t` are literal tabs (1 byte), and `<empty>` represents a blank file. It's just for readability. I'm also not entirely sure that I'm doing the loop correctly, but I think so. Each line should be placed in its own file. I've added 1 byte for each additional file.

Input is assumed to be in Unary on its own line at the end of the input.

```
(1*)$
_$1
m+`(?<!^|\t)\t
.
(`1$
<empty>
)`\t
\t.
\t|_
<empty>

```

### Explanation

I add a `_` before the Unary input to delimit it during replacement, so that I don't remove any trailing ones from the input string. Then, I replace all tabs not at the beginning of a line with a single space. Then, I loop, removing a single `1` and adding a single space after each tab, until I run out of input. Finally, I clean up by removing the tabs and underscore.

# Answer
> 1 votes
# Python, ~~72~~ 68 bytes

Tabs are literal tabs (1 byte), so `r'...'` is not needed. Unfortunately, Python requires "fixed-width" look-behinds / look-aheads, so I can't use `(?<!^|\t)`. Uses pretty much the same method as my Retina solution.

```
import re
lambda s,n:re.sub('\t',' '*n,re.sub('(?<!^)(?<!\t)\t',' ',s))

```

# Answer
> 1 votes
# Stax, 20 bytes

```
ÜR╧█╧╫≡eX,)~σOÜ¢G╩N‼

```

Run and debug it

This program reads the first line as the indent width, and the rest of the input as the program.

# Answer
> 1 votes
# Japt v2.0a0, 17 bytes

```
r/^\t+/m_çVçÃr\tS

```

Try it

# Answer
> 0 votes
# Haskell, 75 bytes

```
s#m|let('\t':r)#n=(' '<$[1..n])++r#n;(x:r)#n=x:r#(m^sum[1|x<' ']);e#_=e=s#m

```

Try it online! This assumes the input contains only printable chars as well as tabs and newlines, as allowed by OP in the comments.

**Explanation:**

The outer `#` function takes a string `s` and a number `m` and calls the inner locally defined `#` function with the same arguments. This is done to keep track of the original `m` value, as the inner `#` function changes the number:

* `('\t':r)#n=(' '<$[1..n])++r#n` If you encounter a tab, replace it by `n` spaces and leave `n` unchanged.
* `(x:r)#n=x:r#(m^sum[1|x<' '])` If some `x` which is not a tab is encountered, keep it as is but set `n` to the original number `m` if `x` is a newline and to `1` otherwise. This is done by `m^sum[1|x<' ']`: `m` is taken to the power of `sum[1|x<' ']` which evaluates to `1` when `x` is smaller than a space (i.e. a newline), so we get `m^1 = m`. Otherwise it's `0` and we have `m^0 = 1`.

# Answer
> 0 votes
# Java 11, 134 bytes

```
n->s->{var r="";for(var p:s.split("\n")){for(;p.charAt(0)==9;p=p.substring(1))r+=" ".repeat(n);r+=p+"\n";}return r.replace('\t',' ');}

```

Try it online.
NOTE: Java 11 isn't on TIO yet, so `" ".repeat(n)` has been emulated as `repeat(" ",n)` instead (with the same byte-count).

**Explanation:**

```
n->s->{                 // Method with integer & String parameters and String return-type
  var r="";             //  Result-String, starting empty
  for(var p:s.split("\n")){
                        //  Loop over the rows (split by new-lines)
    for(;p.charAt(0)==9;//   Inner loop as long as the current row starts with a tab
       p=p.substring(1))//     After every iteration: remove the first character (tab)
      r+=" ".repeat(n); //    Append `n` amount of spaces to the result-String
    r+=p+"\n";}         //   Append the rest of the row with a newline to the result
  return r.replace('\t',' ');}
                        //   Replace any remaining tabs with a space, and return the result

```

---
Tags: code-golf, string, conversion, whitespace
---