title: Interleaving reversing

text:
# Question
Title: Interleaving reversing
Given a string, reverse it interleavingly. Here's how to do it for `abcdefghi` and `abcdefghij`, 0-indexed:

1. Separate the chars at even indices from the chars at odd indices:
```
a c e g i
 b d f h

a c e g i
 b d f h j
```
2. Reverse the chars at odd indices:
```
a c e g i
 h f d b

a c e g i
 j h f d b
```
3. Interleave into one string again:
```
ahcfedgbi

ajchefgdib
```

# Rules

* You must support both even-length and odd-length strings.
* 0-index-wise, you must reverse the chars at odd indices, not even.
* 1-index-wise, of course, you must reverse the chars at even indices, not odd.
* Input will consist of printable ASCII (code points 32-126), no newlines.
* You can take input either as a string or as a list of chars (NOT 1-char strings). E.g. `String`/`char[]` or `char*` are allowed, but `String[]`/`char[][]` or `char**` aren't.

# Test cases

```
Input
Output

```

```
Hello, World!
HdlroW ,olle!

Hello World!
H!llooW rlde

ABCDEFGHIJKLMNOPQRSTUVWXYZ
AZCXEVGTIRKPMNOLQJSHUFWDYB

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 }"{$y&w(u*s,q.o0m2k4i6g8e:c<a>_@]B[DYFWHUJSLQNOPMRKTIVGXEZC\A^?`=b;d9f7h5j3l1n/p-r+t)v'x%z#|!~

P
P

AB
AB

xyz
xyz

```

For the empty string, return the empty string itself.

# Answer
# Jelly, 7 bytes

```
s2ZU2¦Z

```

This is a full program.

Try it online!

### How it works

```
s2ZU2¦Z  Main link. Argument: s (string)

s2       Split s into pairs.
  Z      Zip/tranpose, grouping characters by the parity of their indices.
     ¦   Sparse application:
   U         Upend; reverse both strings in the pair.
    2        Replace the second string with the reversed string.
      Z  Zip/transpose, interleaving the two strings.

```
> 7 votes

# Answer
# MATL, 8 bytes

```
t2L)P5M(

```

Try it online! Or verify all test cases.

### Explanation

```
t     % Implicit input. Duplicate
      % STACK: 'abcdefghi', 'abcdefghi'
2L    % Push [2, 2, 1j]. This represents 2:2:end when used as an index
      % STACK: 'abcdefghi', 'abcdefghi', [2, 2, 1j]
)     % Get entries at those indices
      % STACK: 'abcdefghi', 'bdfh'
P     % Flip
      % STACK: 'abcdefghi', 'hfdb'
5M    % Push [2, 2, 1j] again
      % STACK: 'abcdefghi', 'hfdb', [2, 2, 1j]
(     % Write entries at those indices. Implicit display
      % STACK: 'ahcfedgbi'

```
> 12 votes

# Answer
# Alice, 10 bytes

```
/ZY
\IOR@/

```

Try it online!

Half of the bytes of this program are spent on correctly formatting the source, the actual commands are just `IYRZO`, because Alice has just the right builtins for this task.

### Explanation

As I said, the mirrors (`/\`), the newline and `@` are there just to make the ip move in the right direction and terminate the program at the end. The actual code, linearised, is the following:

```
IYRZO
I      Input a line
 Y     Unzip it into its even positions and its odd ones
  R    Reverse the odd positions
   Z   Zip it back again
    O  Output

```

Quite straightforward, I'd say.
> 7 votes

# Answer
# Java (OpenJDK 8), ~~108~~ ~~96~~ ~~94~~ 93 bytes

*Saved 1 byte by using @Neil's neat trick of using `s[s.length+~i|1]`*

```
String f(char[]s){int a=s.length,b=0;String c="";for(;b<a;b++)c+=s[b%2<1?b:a+~b|1];return c;}

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~52~~ 50 bytes

-2 bytes (and a bug fix) thanks to pxeger

```
s=bytearray(input())
s[1::2]=s[1::2][::-1]
print s

```

Try it online! or Try all test cases
> 5 votes

# Answer
# Octave, 32 bytes

```
@(a,b=a(x)=a(flip(x=2:2:end)))a;

```

Try it online!
> 3 votes

# Answer
## JavaScript (ES6), 48 bytes

```
f=
s=>s.replace(/./g,(c,i)=>i%2?s[s.length+~i|1]:c)
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
> 3 votes

# Answer
# Jelly, 9 bytes

```
Ḋm2U
m2żÇ

```

Try it online!

```
Ḋm2U Helper Link -> Dequeue (return last len-1 elements), take every second element, reverse
m2żÇ Main Link -> Take every second element, then interleave with the result of the helper link

```

*-1 byte thanks to Dennis*
> 3 votes

# Answer
# Retina, ~~17~~ 13 bytes

```
O^$`(?<=\G.).

```

Try it online!

Fixed an error thanks to Neil.

Saved 4 bytes thanks to Kobi.

Selects each letter preceded by an odd number of characters and reverses them. Does this by using `\G` which matches the end of the last match.
> 3 votes

# Answer
# PHP\>=7.1, 58 Bytes

```
for(;$i<$l=strlen($a=$argn);$i++)echo$a[$i&1?-$i-$l%2:$i];

```

Online Version
> 2 votes

# Answer
# Japt, 14 13 bytes

12 bytes of code, +1 for the `-P` flag.

*Saved 1 byte thanks to @Shaggy*

```
¬ë íU¬Åë w)c

```

## Explanation:

```
¬ë íU¬Åë w)c
¬                   Split the input into an array of chars
 ë                  Get every other char, starting at index 0
   í                Pair with:
    U¬                Input, split into a char array
      Å               .slice(1)
       ë              Get every other char
         w            Reverse
           c       Flatten
-P                 Join into a string

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), 9 bytes

Requires `⎕IO←0` (default on many systems) for proper definition of odd and even.

```
⌽@{2|⍳≢⍵}

```

Try it online!

reverse

`@` at the elements filtered by the mask result from applying the

`{` anonyomous function

`2|` the mod-2 of

the indices of

the tally (length) of

the argument

`}` on the argument
> 2 votes

# Answer
# Vyxal, `s`, 3 bytes

```
yṘY

```

Try it Online!

Turns out by making my answer valid I saved a byte. Oh the irony

## Explained

```
yṘY
y      # un-interleave
 Ṙ     # reverse
  Y    # re-interleave

```
> 2 votes

# Answer
# 05AB1E, 7 bytes

`ι` and  have been added since this challenge was posted, both of them save bytes here.

```
Sι`R.ιJ

```

Try it online!

If we were allowed to take a list of string of length 1, `ι`R.ι` would work for 5 bytes.

```
S         # split the string into a list of characters
 ι        # uninterleave: push [even indices, odd indices]
  `       # push both values seperately to the stack
   R      # reverse the odd indices
    .ι    # interleave the two lists
      J   # join into a string

```
> 2 votes

# Answer
# Röda, 34 bytes

```
f a{a/=""a[::2]<>reverse(a[1::2])}

```

Try it online!

### Explanation

```
a/=""                    Convert the argument a into an array of length-1 strings
      <>                 Interleave
a[::2]                   Every even element of a with
        reverse(a[1::2]) Every odd element of a reversed

```

---

Here is an alternative solution at the same bytecount

### ~~36~~ 34 bytes

```
{[_/""]|_[::2]<>reverse(_1[1::2])}

```

This is an anonymous function that takes input as a string from the input stream.
> 1 votes

# Answer
# Python 2, 67 bytes

```
lambda s,j=''.join:j(map(j,zip(s[::2]+' ',s[1::2][::-1]+' ')))[:-1]

```

Try it online!
> 1 votes

# Answer
## Mathematica, 82 bytes

```
""<>(f=Flatten)[{#&@@#,Reverse@Last@#}&@f[Characters@#~Partition~UpTo@2,{2}],{2}]&

```
> 1 votes

# Answer
# OCaml, 70 bytes

```
let f s=String.(mapi(fun i c->s.[(length s land-2-i-i)*(i mod 2)+i])s)

```

Try it online!
> 1 votes

# Answer
# Haskell, 63 bytes

```
(_:r)!(a:s)=a:s!r
_!_=[]
f s=([' '|even$length s]++reverse s)!s

```

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

For odd strings like `abcdefghi`, the function `f` passes the string and its reversal to the function `!`, which alternates taking chars from both strings. For even strings this does not work, and we need to append a dummy character first to get the offset right.
> 1 votes

# Answer
# C, 69 bytes

```
c,l;f(char*s){l=strlen(s);for(c=0;c<l;++c)putchar(s[c&1?l-l%2-c:c]);}

```

Pretty simple. Walks the string, printing either the current character or the opposite one.

### Ungolfed and explained:

```
f(char *str) {
    int len = strlen(str);      // Get the total length
    for(int c = 0; c<len; ++c)  // Loop over the string
        putchar(s[              // Print the char that is,
            c & 1               // if c is odd,
                ? l - l % 2 - c // c chars from the end (adjusting odd lengths),
                : c             // and at index c otherwise
        ]);
}

```
> 1 votes

# Answer
# 05AB1E, 21 bytes

```
DgÉi¶«}2ô.BøRćR‚˜øJ¶K

```

Try it online!

I'm guessing the reason this wasn't done in 05AB1E yet is because it's gross...

Yet another time the `zip` function's auto-drop-last-element hurts instead of helps.

*P.S. If you have improvement suggestions on my answer, post your own; it's likely enough of an improvement to warrant you getting the points. I am pretty ashamed of this answer.*
> 1 votes

# Answer
# Japt, ~~8~~ 6 bytes

```
ó oÔrí

```

Try it

```
ó oÔrí     :Implicit input of string
ó          :Uninterleave
  o        :Modify last element
   Ô       :  Reverse
    r      :Reduce by
     í     :  Interleaving

```
> 1 votes

# Answer
# K (oK), 18 bytes

**Solution:**

```
{x[w:&2!!#x]:x@|w}

```

Try it online!

**Examples:**

```
> {x[w:&2!!#x]:x@|w}"Hello, World!"
"HdlroW ,olle!"
> {x[w:&2!!#x]:x@|w}"Hello World!"
"H!llooW rlde"

```

**Explanation:**

Interpretted mostly right-to-left, find the odd-indices characters, reverse them and put them back into the string

```
{x[w:&2!!#x]:x@|w} / solution
{                } / lambda function with implicit parameter x
         #x        / count x,    #"Hello, World!" -> 13
        !          / til,        !13 -> 0 1 2 3 4 5 6 7 8 9 10 11 12
      2!           / 2 modulo,   2!0 1 2 3 4 5 6 7 8 9 10 11 12 -> 0 1 0 1 0 1 0 1 0 1 0 1 0
     &             / where true, @0 1 0 1 0 1 0 1 0 1 0 1 0 -> 1 3 5 7 9 11
   w:              / store in variable w
               |w  / reverse w,  |1 3 5 7 9 11 -> 11 9 7 5 3 1
             x@    / index into x at these indices
 x[        ]:      / assign right to x at these indices

```
> 1 votes

# Answer
# J, 26 bytes

```
[:,@,./(0 1$~#)]`(|.@])/.]

```

### ungolfed

```
[: ,@,./ (0 1 $~ #) ]`(|.@])/. ]

```

### explanation

* `(0 1$~#)]`(|.@])/.]` Use Key `/.` to split the input into the even/odd groups: `(0 1$~#)` creates the group definition, by repeating 0 and 1 cyclically to the length of the input. We use the gerundial form of Key for its main verb `]`(|.@])`, which applies the identity to the first group and reverses the second group: `(|.@])`.
* Now that we have the two groups, the odd one reversed, we just zip them together and flatten: `,@,./`

Try it online!
> 1 votes

# Answer
# Thunno 2, 3 bytes

```
^rI

```

Try it online!

#### Explanation

```
     # Implicit input

^    # Uninterleave into two parts and push them separately to the stack
     #   "Hello, World!"  ->  "Hlo ol!", "el,Wrd"
     #   "ABCDEF"         ->  "ACE", "BDF"
     #   "P"              ->  "P", ""

 r   # Reverse the top of stack (second part from before)
     #   "Hello, World!"  ->  "Hlo ol!", "drW,le"
     #   "ABCDEF"         ->  "ACE", "FDB"
     #   "P"              ->  "P", ""

  I  # Interleave the two strings together
     #   "Hello, World!"  ->  "HdlroW ,olle!"
     #   "ABCDEF"         ->  "AFCDBE"
     #   "P"              ->  "P"

     # Implicit output

```
> 1 votes

# Answer
# Python 3, ~~93~~ 87 bytes

```
lambda s:"".join("".join(t)for t in zip(s[::2],reversed(s[1::2])))+("",s[-1])[len(s)%2]

```
> 0 votes

# Answer
# Perl 6,  ~~63 58~~  55 bytes

```
{[~] .comb[{flat roundrobin (0,2...^*>=$_),[R,] 1,3...^*>=$_}]}

```

Test it

```
{[~] flat roundrobin .comb[{0,2...*},{$_-1-$_%2,*-2...*}]}

```

Test it

```
{[~] flat roundrobin .comb[{0,2...*},{[R,] 1,3...^$_}]}

```

Test it

```
{  # bare block lambda with implicit parameter ｢$_｣

  [~]                 # reduce using string concatenation operator

    flat              # make the following a flat list

    roundrobin        # grab one from each of the following 2 lists,
                      # repeat until both are empty

    .comb\            # split the input into graphemes (implicit method call)

    [                 # index into that sequence

      { 0, 2 ... * }, # code block producing every non-negative even number

      {               # code block producing reversed odd numbers
                      # (｢$_｣ here contains the number of available elements)

        [R,]          # reduce with reversed comma operator
                      # (shorter than ｢reverse｣)

        1, 3 ...^ $_  # odd numbers stopping before it gets
                      # to the number of input elements
      }

    ]
}

```

I had to use `roundrobin` rather than `zip`, because `zip` stops as soon as one of the input lists is exhausted.
> 0 votes

# Answer
# Mathematica, 62 bytes

takes as input a string

```
(s=Characters@#;Row@Riffle[s[[;; ;;2]],Reverse@s[[2;; ;;2]]])&

```

Try it online!
> 0 votes

# Answer
# APL (Dyalog), 24 bytes

*Bytes golfed thanks to @Adám*

```
A⊣A[i]←⌽A[i←2×⍳⌊2÷⍨⍴A←⎕]

```

Try it online!
> 0 votes

# Answer
# GNU APL 1.2, 24 bytes

```
R[X]←⌽R[X←2×⍳⌊.5×⍴R←⍞]◊R

```

APL works from right to left. `⍴R←⍞` assigns user input to `R` and then evaluates its length. Halve this by multiplying by `.5` and apply  floor function.  returns all numbers from 1 to the argument.

APL operates on arrays, so  the array we just got from  doubles each element, giving us just the even indices (1-indexed, so relies on `⎕IO` being 1).

When accessing multiple indices of a vector, APL gives the elements at those indices in a vector. `R[X←2×⍳⌊.5×⍴R←⍞]` gives just the even-indexed elements.  reverses the elements. Then, assign the reversed values back to the even indices (assigning these indices to `X` saves 6 bytes).

is the statement separator. After the reversing is done, evaluate `R` to print the result.
> 0 votes

# Answer
# q/kdb+, ~~70~~ ~~56~~ ~~47~~ ~~38~~ ~~35~~ ~~29~~ 27 bytes

**Solution:**

```
{x[w]:x(|)w:(&)#:[x]#0 1;x}

```

**Example:**

```
q){x[w]:x(|)w:(&)#:[x]#0 1;x}"Hello, World!"
"HdlroW ,olle!"
q){x[w]:x(|)w:(&)#:[x]#0 1;x}"Hello World!"
"H!llooW rlde"

```

**Explanation:**

Find the odd indices of the string, reverse this list, pull out elements at these points and then reassign them in-place to the original string.

```
{x[w]:x reverse w:where count[x]#0 1;x} / ungolfed
{                                   ; } / lambda function with two lines
                                 0 1    / the list (0;1)
                                #       / take
                        count[x]        / length of input
                  where                 / indices where this is > 0
                w:                      / save in variable w
        reverse                         / reverse this list
      x                                 / index into x at these points
     :                                  / assignment
 x[w]                                   / assign x at indices with new values
                                     x  / return x

```

**Edits:**

* -9 bytes; switching out `count` for `(#:)`, `til` for `(!)`, `where` for `(&:)` and `reverse` for `(|:)`.
* -3 bytes; switching out `(#:)` for `(#)`, `(&:)` for `(&)` and `(|:)` for `(|)`
* -6 bytes; complete re-write
* -2 bytes; using assignment rather than apply
> 0 votes

# Answer
# Perl 5, 46 + 3 for -F flag = 49 bytes

```
while(++$x<@F){print$F[$x%2?$x-1:@F-$x-$#F%2]}

```

Uses the `-F` flag to auto split the input into an array of characters, `@F`. Loops through the array and outputs that element for an even index or that index (plus one for an odd length string) from the end for an odd input.

Takes input with a trailing newline. Without the trailing newline, can just change the pre-increment on `$x` to a post-increment.

A little more readable:

```
while(++$x<@F) { #While the index is less than the number of elements in the array. $x is 1-indexing the array despite the fact that perl is 0-indexed because it keeps us from having to use a proper for loop or a do-while loop
    if($x%2) { #If $x is odd
        print $F[$x-1] #Print the element
    } else {
        print $F[@F-$x-$#F%2] #Print from the end. $#F%2 fixes it for odd length strings
    }
}

```
> 0 votes

# Answer
# 05AB1E, 12 bytes

```
RDgÈúøvyNÉè?

```

Try it online!

```
RDgÈúøvyNÉè?   Implicit input: "abcdefghij"
R              Reverse the string: "jihgfedcba"
 DgÈú          Put (length is even?1:0) spaces in front of it " jihgfedcba"
     ø         Zip (reinjects the input implicitly): ["a ", "bj", "ci", ...]
      vy       For each element of the list
        NÉè    Extract&push element[iteration is odd?1:0]
           ?   Print without newline

```
> 0 votes

# Answer
# Jq 1.5, 84 bytes

```
[_nwise(2)|[_nwise(1)]]|transpose|map(map(values))|.[1]|=reverse|[transpose[][]]|add

```

Expanded

```
   [_nwise(2)|[_nwise(1)]] # make list of two character lists
 | transpose               # convert to list of two lists of characters
 | map(map(values))        # discard null
 | .[1] |= reverse         # reverse second list
 | [transpose[][]]         # transpose back to two lists and flatten
 | add                     # convert back to string

```

Try it online!
> 0 votes

# Answer
# Perl, 27 bytes

Includes +5 for `-F lp`

```
perl -F -lpe 's/.\K./$F[@F%-2-pos]/g' <<< "abcdefghi"

```

If you give STDIN without newline you can drop the `l` option
> 0 votes

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


title: Make String Waves

text:
# Question
Title: Make String Waves
Given a string as input, output the string with the following algorithm applied:

```
1. Split the String by " " (find the words): "Hello World" -> ["Hello","World"]
2. Find the vowel count of each component: [2,1]   ( ["H[e]ll[o]","W[o]rld"] )
3. For each of the components, output the first n letter where n is the number
   of vowels it contains: ["He","W"]
4. Join the list to a single string and reverse it: "HeW" -> "WeH"

```

## Specs

* You may take input and provide output by any standard form, and the only data type allowed for both Input and Output is your language's native String type. Taking input directly as a list of individual words is not permitted.
* You are guaranteed that there will be no consecutive spaces.
* The vowels are `"a","e","i","o","u","A","E","I","O","U"`, but `"y","Y"` *are not considered vowels*.
* You are guaranteed that only letters and spaces will appear in the input, but without any newlines.
* Output *must* be case-sensitive.
* You are not guaranteed that each word contains a vowel. If no vowels appear in that word, you do not have to output anything for it.

## Test Cases

```
Input -> Output
---------------

""                                  -> ""
"Hello World"                       -> "WeH"
"Waves"                             -> "aW"
"Programming Puzzles and Code Golf" -> "GoCauPorP"
"Yay Got it"                        -> "iGY"
"Thx for the feedback"              -> "eeftf"
"Go Cat Print Pad"                  -> "PPCG"
"ICE CREAM"                         -> "RCCI"

```

## Scoring

The shortest valid submission for each language wins, this is . Good luck and have fun!

---

Sandbox for those who can see deleted posts.

# Answer
## Haskell, 59 bytes

```
map fst.reverse.(>>=zip<*>filter(`elem`"aeiouAEIOU")).words

```

Try it online!

```
       words     -- split into a list of words
  (>>=      )    -- apply a function to every word and collect the results in a
                 -- single list
     zip<*>filter(`elem`"aeiouAEIOU")
                 -- f <*> g x = f x (g x), i.e. zip x (filter(...)x)
                 -- we now have a list of pairs of (all letters of x, vowel of x)
                 -- with the length of number of vowels
 reverse         -- reverse the list
map fst          -- drop vowels from the pairs

```
> 7 votes

# Answer
# , 31 bytes

```
Í /ò
òÄøã[aeiou]
|DJ@"|D-òÍî
æ

```

Try it online!

```
00000000: cd20 2ff2 0af2 c4f8 e35b 6165 696f 755d  . /......[aeiou]
00000010: 0a01 7c44 4a40 227c 442d f2cd ee0a e6    ..|DJ@"|D-.....

```

And explanation:

```
Í               " Substitute Every space
  /             " With
   ò            " Newlines
                " This puts us on the last line of the buffer
ò               " Recursively:
 Ä              "   Duplicate the current line
  ø             "   Count:
   ã            "   Case insensitive
    [aeiou]     "   The number of vowels
<C-a>           "   Increment this number
     |          "   Go to the beginning of this line
DJ              "   Delete the number of vowels, and remove a newline that was accidentally made.
                "   Also, my name! :D
  @"            "   Run the unnamed register, which is the number of vowels that we deleted
    |           "   And move to the n'th column in this line
     D          "   Delete everything on this line after the cursor, keeping the first *n* characters
      -         "   Move up a line
       ò        " End the loop
        Íî      " Remove all newlines
æ               " And reverse:
                "   (implicit) The current line

```
> 6 votes

# Answer
# Brachylog, 17 bytes

```
ṇ₁{{∋ḷ∈Ṿ}ᶜ}ᶻs₎ᵐc↔

```

Try it online!

### Explanation

That's a direct translation of the problem:

```
Example input: "Hello World"

ṇ₁                  Split on spaces:         ["Hello", "World"]
  {       }ᶻ        Zip each word with:      [["Hello",2],["World",1]]
   {    }ᶜ            The count of:
    ∋ḷ∈Ṿ                Chars of the words that when lowercased are in "aeiou"

            s₎ᵐ     Take the first substring of length <the count> of each word: ["He","W"]
               c    Concatenate:             "HeW"
                ↔   Reverse:                 "WeH"

```
> 6 votes

# Answer
# Perl 5 \+ `-p040F`, 35 bytes

```
$\=$_.$\for@F[0..lc=~y/aeiou//-1]}{

```

Try it online!
> 5 votes

# Answer
# Japt v2.0a0, ~~12~~ 10 bytes

```
¸®¯Zè\vÃ¬w

```

Try it

---

## Explanation

Pretty much does exactly what the spec describes!

```
        :Implicit input of string U.
¸       :Split to array on spaces.
®       :Map over the array, replacing each element with itself ...
¯       :  sliced from the 0th character to ...
Zè\v    :  the count (è) of vowels (\v) in the element (Z).
Ã       :End mapping.
¬       :Join to a string.
w       :Reverse.
        :Implicit output of result.

```
> 4 votes

# Answer
# Perl 6, 57 bytes

```
{flip [~] .words.map:{.substr(0,.comb(rx:i/<[aeiou]>/))}}

```
> 4 votes

# Answer
## Alice, 32 bytes

```
/.'*%-.m"Re.oK"
\iu &wN.;aoi$u@/

```

Try it online!

### Explanation

```
/....
\...@/

```

This is just a framework for linear code in Ordinal (string-processing mode). Unfolding the program, we get:

```
i' %w.."aeiou".u*&-Nm;Ro.$K@

```

Here's what it does:

```
i           Read all input.
' %         Split the input around spaces.
w           Push the current IP address to the return address stack to mark
            the beginning of the main loop. Each iteration will process one
            word, from the top of the stack to the bottom (i.e. in reverse
            order).

  ..          Make two copies of the current word.
  "aeiou"     Push this string.
  .u*         Append an upper case copy to get "aeiouAEIOU".
  &-          Fold substring removal over this string. What that means is that
              we push each character "a", "e", ... in turn and execute -
              on it. That will remove all "a"s, all "e"s, etc. until all
              vowels are removed from the input word.
  N           Compute the multiset complement of this consonant-only version
              in the original word. That gives us only the vowels in the word.
              We now still have a copy of the input word and only its vowels
              on top of the stack.
  m           Truncate. This reduces both strings to the same length. In particular,
              it shortens the input word to how many vowels it contains.
  ;           Discard the vowels since we only needed their length.
  R           Reverse the prefix.
  o           Print it.
  .           Duplicate the next word. If we've processed all words, this
              will give an empty string.

$K          Jump back to the beginning of the loop if there is another word
            left on the stack.
@           Otherwise, terminate the program.

```
> 4 votes

# Answer
## JavaScript (ES6), 76 bytes

```
s=>s.split` `.map(w=>w.split(/[aeiou]/i).map((_,i)=>o=i?w[i-1]+o:o),o='')&&o

```

### Test cases

```
let f =

s=>s.split` `.map(w=>w.split(/[aeiou]/i).map((_,i)=>o=i?w[i-1]+o:o),o='')&&o

console.log(f(""                                 )) // -> ""
console.log(f("Hello World"                      )) // -> "WeH"
console.log(f("Waves"                            )) // -> "aW"
console.log(f("Programming Puzzles and Code Golf")) // -> "GoCauPorP"
console.log(f("Yay Got it"                       )) // -> "iGY"
console.log(f("Thx for the feedback"             )) // -> "eeftf"
console.log(f("Go Cat Print Pad"                 )) // -> "PPCG"
```
> 4 votes

# Answer
# Ruby, ~~54~~ 59+1 = ~~55~~ 60 bytes

Uses the `-p` flag for +1 byte.

```
$_=$_.split.map{|w|w[0,w.count("aeiouAEIOU")]}.join.reverse

```

Try it online!
> 4 votes

# Answer
# Python 3, 83 81 79 77 bytes

```
lambda z:''.join(i[:sum(y in'aeiouAEIOU'for y in i)]for i in z.split())[::-1]

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 96 bytes

```
s=>[...s.split` `.map(w=>w.slice(0,(m=w.match(/[aeiou]/gi))&&m.length)).join``].reverse().join``

```

```
f=
s=>[...s.split` `.map(w=>w.slice(0,(m=w.match(/[aeiou]/gi))&&m.length)).join``].reverse().join``

console.log(
    f(''),
    f('Hello World'),
    f('Waves'),
    f('Programming Puzzles and Code Golf'),
    f('Yay Got it'),
    f('Thx for the feedback'),
    f('Go Cat Print Pad')
)
```
> 3 votes

# Answer
# 05AB1E, 14 bytes

```
#RʒDžMDu«Ãg£R?

```

Try it online!

*Darn 05AB1E doesn't have builtin for AEIOUaeiou ಠ\_ಠ*
> 3 votes

# Answer
# Java 8, ~~171~~ 151 bytes

-20 bytes thanks to @Lukas Rotter

I feel like it still needs some golfing... let me know in the comments if you have any suggestions.

```
s->{String z="";for(String w:s.split(" "))z+=w.substring(0,w.replaceAll("(?i)[^aeiou]","").length());return new StringBuilder(z).reverse().toString();}

```

Try it online!
> 3 votes

# Answer
# Pyth, 31

This took me a long time to write, and I feel like there is probably a better approach, but here is what I have:

```
_jkm<Fd.T,cQ)ml:d"[aeiou]"1crQ0

```

Online test.

```
                             Q     # input
                            r 0    # to lowercase
                           c       # split by whitespace
               :d"[aeiou]"1        # lambda: regex to find vowels in string
              l                    # lambda: count the vowels in string
             m                     # map lambda over list of words
          cQ)                      # split input by whitespace
         ,                         # list of (input words, vowel counts)
       .T                          # transpose
    <Fd                            # lambda to get first n chars of string
   m                               # map lambda over list of (input words, vowel counts)
 jk                               # join on on empty strings
_                                 # reverse

```
> 3 votes

# Answer
# Pyth - 19 bytes

```
_jkm<dl@"aeiou"rd0c

```

Try it here

Explanation:

```
_jkm<dl@"aeiou"rd0c
                  c  # Split implicit input on whitespace
   m                 # For each word d...
               rd0   # ...take the lower-case conversion...
       @"aeiou"      # filter it to only vowels...
      l              # and find the length of this string (i.e., the number of vowels in the word)
    <d               # Take the first # characters of the word (where # is the length from above)
 jk                  # Join on empty string (can't use s, because that will screw up when the input is the empty string)
_                    # Reverse the result (and implicitly print)

```

I could have 18 bytes if not for the empty string:

```
_sm<dl@"aeiou"rd0c

```
> 3 votes

# Answer
# Ohm, 13 bytes

```
z:αv_K_σh;0JR

```

## Explanation

* First the (implicit) input is split on spaces by `z`.
* Then a foreach loop is started (`:`) with it's associated codeblock being `αv_K_σh`.
    + `av` pushes `aeiou`
    + `_` pushes the current iterated element
    + `K` counts the occurrences of `aeiou` in `_`
    + `_` the element again
    + `σh` Splits the element into slices of length `occurences` and takes the first element.
        - Effectively this takes the first `occurences` chars
* `0J` Pushes the stack joined on `''`
    + The `0` is necessary because it requires an argument that will be joined. If that argument isn't an array it joins the stack
* `R` reverses the result
* implicit print of the TOS
> 3 votes

# Answer
# Vyxal, 10 bytes

```
⌈ƛk∨↔LẎ;∑Ṙ

```

Try it Online!

```
⌈          # Split on spaces
 ƛ     ;   # Map...
    ↔      # Remove characters not in...
  k∨       # 'aeiouAEIOU'
     L     # Get the length of that
      Ẏ    # Get that many characters of the original string
        ∑  # Concatenate all of them
         Ṙ # Reverse the whole thing

```
> 3 votes

# Answer
# Jelly, 12 bytes

```
ḲµfØcLḣ@µ€FU

```

Try it online!
> 2 votes

# Answer
# k, ~~33~~ ~~28~~ 27 bytes

```
|,/{x@!+/~^"aeiou"?_x}'" "\

```

Try it online!

---

-5 bytes thanks to coltim, -1 byte thanks to doug.
> 2 votes

# Answer
# Mathematica, 145 bytes

```
(s=StringCount[#,{"a","e","i","o","u","A","E","I","O","U"}]&/@(x=StringSplit@#);StringReverse[""<>Table[StringTake[x[[i]],s[[i]]],{i,Tr[1^s]}]])&

```
> 2 votes

# Answer
# Retina, ~~49~~ 46 bytes

```
i`(?=(([aeiou])|\w)+)((?<-2>.)+)\w* ?
$3
O^$`.

```

Try it online! Link includes test suite. Explanation: This is an application of .NET's balancing groups. The lookahead searches the word for vowels, which are captured in group 2. The group is then popped as each letter is matched, thus capturing the number of letters equal to the number of vowels in the word. The rest of the word and any trailing space is then ignored so that the process can begin again with the next word. Finally the remaining letters are reversed.
> 2 votes

# Answer
# C# (.NET Core), 144 bytes

```
using System.Linq;s=>new string(string.Join("",s.Split(' ').Select(e=>e.Substring(0,e.Count(c=>"aeiouAEIOU".Contains(c))))).Reverse().ToArray())

```

Try it online!

The worst part is that reversing a `string` in C# returns a `IEnumerable<char>` which you have to convert back to a `string`.
> 2 votes

# Answer
# PHP, 96 bytes

```
foreach(explode(" ",$argn)as$w)$r.=substr($w,0,preg_match_all("#[aeiou]#i",$w));echo strrev($r);

```

Try it online!
> 2 votes

# Answer
# Common Lisp, 218 bytes

```
(defun p(s &aux(j 0)c(v 0)r)(dotimes(i(1+(length s))(apply'concatenate'string r))(cond((or(= i(length s))(eql(setf c(elt s i))#\ ))(setf r(cons(reverse(subseq s j(+ j v)))r)v 0 j(1+ i)))((find c"AEIOUaeiou")(incf v)))))

```

**Explanation**

```
(defun p(s &aux (j 0) c (v 0) r)               ; j start of word, c current char, v num of wovels, r result
  (dotimes (i                                  ; iteration var
            (1+ (length s))                    ; iteration limit
            (apply 'concatenate 'string r))    ; iteration final result
    (cond ((or (= i (length s))                ; if string is terminated
               (eql (setf c (elt s i)) #\ ))   ;  or, set current char, and this is a space, then
           (setf r (cons (reverse (subseq s j (+ j v))) r) ; push on result from current word chars as number of vowels
                 v 0                           ; reset number of vowels to 0
                 j (1+ i)))                    ; reset start of current word to next char
          ((find c "AEIOUaeiou")               ; if current char is a wovel
           (incf v)))))                        ;   then increment num of vowels

```
> 2 votes

# Answer
# Swift 3, 240 bytes

This is a function that can be used with `f(s:"Input")`. Surprisingly, I don't think it can be golfed further:

```
import Foundation
func f(s:String){var c=s.components(separatedBy:" "),r="";for i in c{let b=i.startIndex;r+=i[b...i.index(b,offsetBy: i.characters.filter{"aeiouAEIOU".contains(String($0))}.count-1)]};print(String(r.characters.reversed()))}

```

Try it at IBM Sandbox!
> 2 votes

# Answer
# sed, 133 (132+1) bytes

sed is called with the `-E` flag, which apparently means I add one byte.
Note: I have not really attempted to golf this yet.

```
s/$/\n/
:l
s/(.)(\n.*)/\2\1/
tl
s/\n/ /
h
s/[aoeui]//g
G
:r
s/^(\S*) \S(.*\n\S* )\S/\1 \2/
tr
s/^ //
s/(\n\S*) /\1/
/^\n/!br
s/\s//g

```

Try it online!
> 2 votes

# Answer
## Clojure, ~~96~~ 94 bytes

```
#(apply str(mapcat(fn[i](take(count(filter(set"aeiouAEIOU")i))i))(reverse(re-seq #"[^ ]+"%))))

```

Well this length is quite ridiculous. `mapcat` saved two bytes.
> 2 votes

# Answer
# CJam, 26 bytes

```
qS/{_el"aeiou"fe=:+<}%:+W%

```

Try it online!

I was proud of coming up with the `el"aeiou"fe=:+` snippet to count vowels.
> 2 votes

# Answer
# GolfScript, 33 bytes

```
" "/-1%{.{"aeiouAIUEO"?)},,<-1%}/

```

Try it online!

```
" "/                                # Split the words                          ["Hello" "World"]
    -1%                             # Reverse the list                         ["World" "Hello"]
       {                       }/   # For each word                            "World"         | "Hello"
        .                           # Copy it                                  "World" "World" | "Hello" "Hello"
         {              },          # List all letters that pass this test
          "aeiouAIUEO"?)            # Is it a vowel?                           "World" ["o"]   | "Hello" ["e" "o"]
                          ,         # Get the number of letters in the list    "World" 1       | "Hello" 2
                           <        # Get that many letters from the beginning "W"             | "He"
                            -1%     # Reverse it                               "W"             | "eH"
                                                                               "WeH"

```
> 2 votes

# Answer
# Husk, 17 bytes

```
ṁS↑ṁ#¨aeıuAEIOU¨w

```

Try it online!

Even without a builtin, does pretty well.
> 1 votes

# Answer
# Vyxal, 8 bytes

```
⌈ƛA∑Ẏ;∑Ṙ

```

Try it Online!

```
⌈        # Split on spaces
 ƛ   ;   # Map...
  A      # Vowel mask (1 for vowel, 0 for not for each character)
   ∑     # Sum (vowel count)
    Ẏ    # First ^ letters
      ∑Ṙ # Sum + reverse

```
> 1 votes

# Answer
# Arturo, 72 bytes

```
$=>[reverse join map split.words&'x->take x match.count x{/(?i)[aeiou]}]

```

Try it
> 1 votes

# Answer
# , 37 bytes

```
[:|.@;({.~1#.'AEIOUaeiou'e.~])&.>@cut

```

Attempt This Online!

```
[:|.@;({.~1#.'AEIOUaeiou'e.~])&.>@cut
[:                                     NB. enforce f(g(y))
                                >@cut  NB. split on spaces and unbox
                              &.       NB. then for each word
      (                      )         NB. monadic hook
             'AEIOUaeiou'e.~]          NB. checks if each character of input is a vowel
          1#.                          NB. sum the result, count of vowels
       {.~                             NB. take that many from the word
                              &.       NB. u&.v will do v⁻¹(u(v(y))) so box the result
  |.@;                                 NB. unbox and concat then reverse

```
> 1 votes

# Answer
# Lua, 93 bytes

```
print((...):gsub('%g+ ?',load's=..._,n=s:gsub("[aeiouAEIOU]",s)return s:sub(1,n)'):reverse())

```

Try it online!
> 1 votes

# Answer
# Thunno 2 `c`, 8 bytes

```
OıṃSɱ;Jr

```

Try it online!

#### Explanation

```
OıṃSɱ;Jr  # Implicit input
O         # Split on spaces
 ı   ;    # Map over this list:
  ṃ       #  Check if each character is a vowel
   S      #  And sum to get the vowel count
    ɱ     #  Take that many characters from the front
      J   # Join into a string
       r  # And reverse the string
          # Implicit output

```
> 1 votes

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


title: Return all letter counts as an integer

text:
# Question
Title: Return all letter counts as an integer
# Definition

Given some string return an integer whose digits are the number ocurrences of a-z (case insensitive, in alphabetical order) in that string. Any character with 0 instances is skipped. Characters with 10 or more instances will define 2 or more digits of the returned integer. For example, aaaaaaaaaaaaaaaaaaaaaaaaaaad (27 a's followed by d) will return 271.

# Input

A single string with one or more letters

# Output

An integer or a string representing an integer

# Test Cases

| Input | Output |
| --- | --- |
| acfzzA | 2112 |
| Hello World! | 1113211 |
| ---!&\*#$ | invalid input, any result is acceptable |
| ---!&\*#$a | 1 |
| aaaaaaaaaaaaaaaaaaaaaaaaaaad | 271 |
| aaaaaaaaaad | 101 |
| cccbba | 123 |
| abbccc | 123 |

This is code-golf, so the shortest answer in bytes wins! Standard loopholes and rules apply. Tie goes to first poster.

# Answer
# Vyxal, 44 bitsv2, 5.5 bytes

```
Ǎ⇩sĠ@ṅ

```

Try it Online!

## Explained

```
Ǎ⇩sĊvtṅ
Ǎ       # keep only letters of the alphabet
 ⇩      # and convert to lowercase
  sĊ    # sort that and get the counts of each letter - this returns [[letter, count of letter] for each letter
    vtṅ # join the counts of letters on ""

```
> 4 votes

# Answer
# Python 3.8, 76 bytes:

```
lambda x:''.join(str(i)for a in range(97,123)if(i:=x.lower().count(chr(a))))

```

Try it online!
> 7 votes

# Answer
# Python 2, 64 bytes

```
f=lambda s,c=65:91/c*s and'%.d'%s.upper().count(chr(c))+f(s,c+1)

```

Try it online!
> 7 votes

# Answer
# C, ~~137~~, ~~124~~, 90, ~~88~~ bytes

Thank you @AnttiP and @tsh for suggestions!

```
s[99];main(c){while(c-10)s[(c=getchar())&~32]++;for(c=64;c-90;)s[++c]&&printf("%d",s[c]);}

```

less golfed version:

```
s[99];

int main(c){

    while(c-10)
        s[(c=getchar())&~32]++;

    for(c=64;c-90;)
        s[++c]&&printf("%d",s[c]);
}

```

Try it online!
> 7 votes

# Answer
# Charcoal, 10 bytes

```
⭆α⪫↨№↥θιχω

```

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

```
 α          Predefined variable uppercase alphabet
⭆           Map over letters and join
    №       Count of
       ι    Current letter in
     ↥      Uppercased
      θ     Input string
   ↨    χ   Convert to base 10
  ⪫      ω  Join digits together

```

Charcoal's arbitrary base conversion returns an empty list for an input of zero, which is the easiest way to map zero to an empty string.
> 6 votes

# Answer
# , ~~78~~ 69 bytes

Or **\>=4.1, 62 bytes** by replacing the word `function` with `\`.

*Edit: -9 bytes inspired by @Giuseppe's answer.*

```
function(s)cat(table(utf8ToInt(gsub("[^a-z]","",tolower(s)))),sep="")

```

Try it online!

Prints the resulting number like in @Giuseppe's answer.
> 4 votes

# Answer
# Wolfram Language (Mathematica), ~~54~~ 52 bytes

```
""&@@@Array[ToString/@Counts@LetterNumber@#,26]<>""&

```

Try it online!

```
                             LetterNumber@#             a->1,...,z->26, others->0
                      Counts@                           letter counts
      Array[                               ,26]           for a,...,z
""&@@@                                                    (don't include missing letters)
            ToString/@                         <>""     concatenate

```
> 4 votes

# Answer
# PHP, 66 bytes

```
<?=join(count_chars(preg_replace('~\W~','',strtolower($argn)),1));

```

Try it online!

A rarely useful builtin function, but it turns out satisfying when it does
> 4 votes

# Answer
# Perl 5 \+ `-p`, 23 bytes

```
s/\pl/$\.=s!$&!!gi/ge}{

```

Try it online!

---

# Perl 5 \+ `-n`, 23 bytes

```
s/\pl/print s!$&!!gi/ge

```

Try it online!
> 4 votes

# Answer
# bash, ~~64~~ 44 bytes

#### Original Solution (64 Bytes)

Fairly simple `tr`-based solution - `bash` probably isn't a good way to make a competitive answer, but I had fun doing it!

```
tr [A-Z] [a-z]|tr -dc [a-z]|grep -o .|sort|uniq -c|tr -dc [0-9]

```

Depending on how you want to count characters, it could be more than 64 when including the input to this. A very simple case would be:

```
echo my-input-string|tr [A-Z] [a-z]|tr -dc [a-z]|grep -o .|sort|uniq -c|tr -dc [0-9]

```

which really only adds six characters at best and eight if you have to single-quote the input string.

Explanation:

```
tr [A-Z]  [a-z]   # Convert all capitals to lowercase in the input stream
tr -dc [a-z]      # Delete everything that isn't a lowercase letter
grep -o .         # Output every character on its own line
sort | uniq -c    # Get a two-column output of all unique characters and their frequencies
tr -dc [0-9]      # Delete everything that isn't a digit

```

#### 44 Byte Solution (by @Digital Trauma)

```
grep -io [a-z]|sort -i|uniq -ci|tr -dc [0-9]

```

Among other improvements, this bash solution utilizes some case-insensitive options for utilities such as `sort` and `uniq`.

Here's @Digital Trauma's Try It Online
> 4 votes

# Answer
# 05AB1E, 7 bytes

```
lDáêS¢J

```

Try it online!

-2 bytes and fix thanks to @KevinCruijssen and @ovs
> 3 votes

# Answer
# Factor \+ `spelling`, 56 bytes

```
[ >lower ALPHABET counts values [ present ] map-concat ]

```

The `counts` word postdates Factor build 1525, the one TIO uses, so here's a screenshot of running the above code in build 2101's listener:

## Explanation

```
                        ! "acfzzA"
>lower                  ! "acfzza"
ALPHABET                ! "acfzza" "abcdefghijklmnopqrstuvwxyz"
counts                  ! { { 97 2 } { 99 1 } { 102 1 } { 122 2 } }
values                  ! { 2 1 1 2 }
[ present ] map-concat  ! "2112"

```
> 3 votes

# Answer
# JavaScript (ES6), 63 bytes

Expects an array of characters.

```
a=>a.map(c=>o[i=parseInt(c,36)]=-~o[i],o=[])|o.slice(10).join``

```

Try it online!

### Commented

```
a =>                // a[] = input array
a.map(c =>          // for each character c in a[]:
  o[                //   update o[]:
    i =             //     let i be the result of
    parseInt(c, 36) //     c parsed in base-36
                    //     which gives 0 to 9 for [0-9],
                    //     10 to 35 for [a-z] and [A-Z]
                    //     and NaN for anything else
                    //     (o[NaN] is not an entry of the array but
                    //     an object property which will be ignored
  ] =               //     by join())
    -~o[i],         //     increment it / set it to 1 if it's undefined
  o = []            //   initialize o[] to an empty array
) |                 // end of map()
o.slice(10)         // ignore the first 10 entries
.join``             // join the remaining ones; undefined values are
                    // coerced to empty strings

```
> 3 votes

# Answer
# BQN, ~~30~~ 28 bytesSBCS

```
{∾•Fmt¨×⊸/+˝(⥊-⌜"aA")=⌜↕26}

```

Run online!

`↕26` Range from 0 to 25.
`⥊-⌜"aA"` Differences between each of the characters in the input and a or A.
`=⌜` Equality table between those two vectors.
Sum the columns.
`×⊸/` Keep the values with sign 1 (or: remove the zeros)
`∾•Fmt¨` Convert each value to a string and join.

A slightly different approach using *Bins Down* at 29 bytes:

```
{∾•Fmt¨×⊸/»1↓/⁼27↕⊸⍋⥊-⌜"aA"}

```

Run online!
> 3 votes

# Answer
# Husk, ~~11~~ ~~9~~ 8 bytes

*Edit: -2 bytes but +1 (bug fix) for a net -1 byte, all thanks to Razetime*

```
ṁosLk_f√

```

Try it online!

Digits are in alphabetical order of each letter.

```
       f√    # filter for only letters,
     k_      # and group letters by lowercase value;
 ṁo          # now map to each group & combine the results:
    L        #  get the length
   s         #  and convert to a string

```
> 3 votes

# Answer
# , ~~75~~ 72 bytes

```
function(s,x=tabulate((y=utf8ToInt(s))%%32*(y>64),26))cat(x[!!x],sep="")

```

Try it online!

Prints the result. For invalid input, prints nothing.

-3 bytes thanks to Dominic van Essen.

Test harness taken from pajonk's answer.
> 3 votes

# Answer
# PowerShell, ~~56~~ 50 bytes

```
%{-join($_|% T*y|% *g|sort|group|? N* -m \w|% C*)}

```

Input comes from the pipeline.

Try it online!

Try it in a PS console:

```
$strings = 'acfzzA', 'Hello World!', '---!&*#$', '---!&*#$a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaad', 'aaaaaaaaaad', 'cccbba', 'abbccc'
$result = $strings |
%{-join($_|% T*y|% *g|sort|group|? N* -m \w|% C*)}
1..($strings.Length-1)|%{"'$($strings[$_])' --> '$($result[$_])'"}

```

*-5 by rearranging the first version `%{-join($_|% T*y|% *g|?{$_-match'\w'}|sort|group|% C*t)}`; moving the "match" filter after the "group" allows the use of the "\<Property\> \<Operator\> \<Value\>" syntax of Where-Object instead of using a FilterScript.*
*-1 by removing the unnecessary "t" from "% C\*t"*

## Explanation

**%{...}** "%" is an alias for the cmdlet "ForEach-Object", which accepts input from the pipeline and processes each incoming object inside the ScriptBlock {...}
**-join(...)** Unary operator which will join the all the character counts returned inside the expression
**% T\*y** takes the input string and calls its method "ToCharArray()", turning the string into an array of single characters.
**% \*g** takes the array of characters and turns them back to single-character strings by invoking ToString() (the only method matching "\*g"), because Group-Object is case sensitive for characters, but not for strings.
**sort** is an alias for Sort-Object, which will sort the characters.
**group** is an alias for Group-Object, which will group the characters, and return objects with a Count property for each character; returns GroupInfo objects.
**? N\* -m \w** "?" is an alias for "Where-Object", the rest expands to "-Property 'Name' -match '\w'" - this lets only objects pass where the Name property (which contains the grouped character) consists only of word (\w) characters. PS allows for partial named parameters, so -m will be identified as -match.
**% C\*** gets the property "Count" (the only one starting with C) of the GroupInfo objects.
All the counts will now be collected and joined to a single string; output is implicit.

## Ungolfed

```
ForEach-Object -Process {
    -join (                                             # Will join the counts of all characters produced inside the brackets into a single string
        $_ |                                            # Input string
            ForEach-Object -MemberName ToCharArray |    # input string to single chars
            ForEach-Object -MemberName ToString |       # input chars to single-char strings
            Sort-Object |
            Group-Object |                              # group same characters
            Where-Object -Property 'Name' -match '\w' | # let only word characters pass ("Name" contains the string/character used to group)
            ForEach-Object -MemberName Count            # get only the count of the grouped objects
    )
}

```
> 3 votes

# Answer
# Python3, ~~72~~ ~~70~~ ~~67~~ 87 bytes

```
lambda x:''.join(map(str,map((x:=x.lower()).count,sorted(filter(str.isalpha,set(x))))))

```

Try it online
> 3 votes

# Answer
# Jelly, 8 bytes

```
ŒufØAṢŒɠ

```

Try it online!

# Jelly, 8 bytes

```
ŒuċⱮØA¹Ƈ

```

Try it online!

Both as full programs, taking advantage of Jelly's automatic smash-printing behavior.
> 2 votes

# Answer
# Haskell, ~~120~~ ~~84~~ 73 bytes

```
f x=do(v,u)<-zip['a'..'z']['A'..];1:r<-[[1|k<-x,v==k||u==k]];show$sum$1:r

```

Try it Online!

-36 bytes thanks to Unrelated String

-11 bytes thanks to Wheat Wizard
> 2 votes

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

```
s=>s.sort().join(o='').replace(/([a-z])\1*/gi,c=>o+=c.length)&&o

```

Try it online!

Based off Arnauld's answer. Takes input as a character array.

Sort, join, match runs of one character and append that to `o`, and yield that at the end.
> 2 votes

# Answer
# APL+WIN, ~~48~~ 44 bytes

Prompts for string

```
10⊥((+/(48+m)∘.=n)++/(m←17+⍳26)∘.=n←⎕av⍳⎕)~0

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# PowerShell 6+, ~~47~~ 46 bytes

*-1 byte thanks @Julian*

```
-join($args|?{$_-in'a'..'z'}|group{"$_"}|% c*)

```

Try it online!
> 2 votes

# Answer
# Scala, 64 bytes

```
s=>('A'to'Z').map(c=>s.count(_.toUpper==c)).filter(_>0).mkString

```

Try it online!
> 2 votes

# Answer
# Ruby, 48 bytes

```
->s{((?A..?Z).map{|c|s.upcase.count(c)}-[0])*''}

```

Try it online!
> 1 votes

# Answer
# T-SQL, 168 bytes

```
SELECT STRING_AGG(c,'')WITHIN GROUP(ORDER BY
x)FROM(SELECT x,sum(1)c
FROM(SELECT substring(@,number,1)x FROM spt_values WHERE'P'=type)x
GROUP BY x)x WHERE x like'[a-z]'

```

**Try it online**

This will work for input fewer than 2048 characters. The output is ordered according to the position of the letter in the alphabet
> 1 votes

# Answer
# Retina 0.8.2, 24 bytes

```
T`Llp`LL_
O`.
(.)\1*
$.&

```

Try it online! Link includes test cases. Explanation:

```
T`Llp`LL_

```

Uppercase all letters and delete all other printable ASCII.

```
O`.

```

Sort the letters together.

```
(.)\1*
$.&

```

Get the lengths of all the runs.
> 1 votes

# Answer
# Lua, 94 91 84 bytes

```
for i=65,90 do _,c=(...):upper():gsub(string.char(i),"")io.write(c~=0 and c or"")end

```

Try it online!
> 1 votes

# Answer
# Julia 1.7, 47 bytes

```
!x=join((c=count.('a':'z',lowercase(x)))[c.>0])
```

Attempt This Online!

# Julia 1.0, 49 bytes

```
r='a':'z'
!x=join((c=@.sum(in((r-32)r),x))[c.>0])

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), 23 bytes

```
{,/$#'=x@<x:("a{"')__x}

```

Try it online!

* `_x` lowercase the input
* `("a{"')_` drop all non-letter characters
* `x@<x:` sort the characters
* `#'=` build a dictionary mapping the distinct characters to the number of times they appear
* `,/$` convert the counts to strings, then join them (and implicitly return)
> 1 votes

# Answer
# Thunno 2 `J`, 6 bytes

```
LỊDḳ€c

```

Try it online!

#### Explanation

```
LỊDḳ€c  # Implicit input
L       # Lowercase the input
 Ị      # Only keep alphabetic characters
  D     # Duplicate this string
   ḳ    # Sort and uniquify it
    €c  # Count of each character
        # Implicit output

```
> 1 votes

# Answer
# Java 8, ~~121~~ 118 bytes

```
s->{var C=new int[91];s.chars().filter(c->(c&95)%91>64).forEach(c->C[c&95]++);for(int c:C)if(c>0)System.out.print(c);}

```

Input as a Stream of character codepoints. Assumes the input only contains printable ASCII.

Try it online.

**Explanation:**

```
s->{                        // Method with IntStream parameter and no return-type
  var C=new int[91];        //  Counters-array, starting all at 0
  s.filter(c->(c&95)%91>64) //  Filter the input to only keep letters
   .forEach(c->             //  Loop over each letter-codepoint:
     C[c&95                 //   Convert the codepoint of the char to uppercase
           ]++);            //   And increase the counter of that letter by 1
  for(int c:C)              //  Loop over the counts:
    if(c>0)                 //   If the count is not 0:
      System.out.print(c);} //    Print that count

```
> 0 votes

# Answer
# Python 3.8, 72 bytes:

```
lambda x:'%.*s'*26%(*(x.lower().count(chr(a//2+97))for a in range(52)),)

```

Try it online!

---

Started with another Python 3 solution and ported the string truncation from this Python 2 solution.

---

Used `'%.*s'` to convert a number to a string, and truncate it. By passing in the character count twice, it will either produce an empty string or the count as a string.

`'%.*s % (0,0)'` -\> `''`

`'%.*s % (1,1)'` -\> `'1'`

`'%.*s % (27,27)'` -\> `'27'`

This string formatting needs a tuple, so to produce a doubled up tuple (`(10, 20, 30) -> (10, 10, 20, 20, 30, 30)`) I doubled the range of numbers and then mapped them back down to the original values.

```
(97, 97, 98, 98, ..., 122, 123) == (a//2 for a in range(97*2, 123*2))
(a//2 for a in range(97*2, 123*2)) == (a//2 for a in range(194, 246))

```

Then make the range start from 0 to save some characters

```
(a//2 for a in range(194,246)) == (a//2+97 for a in range(0,52))
(a//2+97 for a in range(52))   == (a//2+97 for a in range(0,52))

```
> 0 votes

# Answer
# Pip, 8 bytes

```
FI^zNLCa

```

Replit! Or, here's the closest equivalent (10 bytes) in Pip Classic: Try it online!

### Explanation

```
FI^zNLCa
   z      Lowercase alphabet
  ^       Split into a list of characters
    N     For each character, count number of occurrences in
     LCa  First command-line arg, lowercased
FI        Filter (removing zeros)
          The resulting list of numbers is concatenated together and autoprinted

```
> 0 votes

# Answer
## PHP5.1 (68 chars)

Given *$argv\[1\]* as a command line argument, it's using 2 error control operator to silence warning :

```
foreach(range(@A,@Z)as$a)str_ireplace($a,1,$argv[1],$n)+$n&&print$n;

```

Try it Online \- 63 chars
> 0 votes

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


# Question
Title: All non-ordered pairs between the elements of an array
**Task:**

Return an array with **all possible pairs** between the elements of an array.

**Example**

From `a=["a", "b", "c", "d"];` return `b=[["a","b"],["a","c"],["a","d"],["b","c"],["b","d"],["c","d"]]`.

Pairs can be in any order as long as all possible combinations are included and obviously `["b","d"]` is the same to `["d","b"]`.

**Input**

Array of unique string elements composed of chars from the class `[a-z]`.

**Output**

2d array containing all the possible pairs of input array's elements.

**Test Cases**

```
input=["a","b","c"];
//output=[["a","b"],["a","c"],["b","c"]]

input=["a","b","c","d","e"];
//output=[["a","b"],["a","c"],["a","d"],["a","e"],["b","c"],["b","d"],["b","e"],["c","d"],["c","e"],["d","e"]]

```

**Note:** I could not find a ***duplicate*** to this challenge. If there is one, alert me with a comment to drop question.

# Answer
> 5 votes
# Jelly, 2 bytes

```
Œc

```

Try it online!

# Answer
> 9 votes
# Haskell, 29 bytes

```
f(a:b)=map((,)a)b++f b
f _=[]

```

Try it online! Example usage: `f ["a","b","c"]` yields `[("a","b"),("a","c"),("b","c")]`.

---

With the flag `-XTupleSections` this can be shortened to 27 bytes, however the flag would need to be counted:

```
f(a:b)=map(a,)b++f b
f _=[]

```

Try it online!

# Answer
> 6 votes
# Mathematica, 14 bytes

```
#~Subsets~{2}&

```

**input**

> \[{"a", "b", "c"}\]

# Answer
> 6 votes
## Haskell, 25 bytes

```
f l=[(x,y)|x<-l,y<-l,x<y]

```

Try it online!

Outer (`x`) and inner (`y`) loop through the input list and keep the pair `(x,y)` only if `x < y`.

# Answer
> 6 votes
## vim, ~~50~~ 48

```
AX<esc>qqYplX@qq@qqrYpllDkxh@rq:g/./norm@r<cr>:g/X/d<cr>dG

```

Takes input in the form

```
abcd

```

and outputs as

```
ad
ac
ab
bd
bc
cd

```

### Explanation

First, `AX<esc>` appends an `X` to the input in order to handle 2-length input, which is necessary for reasons that will become clear shortly.

Then comes the first recursive macro, of the form `qq...@qq@q`. (Record macro `q`, run itself again at the end, end the recording, then run itself once.) In the body of the macro, `Yp` duplicates the current line, `l` breaks out of the macro if the line is now one character long, and `X` deletes the first character in the line. This has the end result of producing

```
abcdX
abcX
abX
aX
X
X

```

Ignoring the `X`s for now, all we have to do is turn `abcdX`, for example, into `ab / ac / ad / aX`. This is achieved with the second recursive macro, `qr...@rq`.

In this macro, we first duplicate the line (`Yp`), then delete everything but the first two characters by moving right two (`ll`) and deleting to the end of the line (`D`). Since the cursor is now on the second charcater of the line, `kx` will delete the second character from the previous line, which happens to be the one that was just paired with the first character on the line. This process is then repeated starting again from the beginning of the line (`h`) as many times as necessary due to the recursive nature of the macro.

It's now just a matter of running the macro on every line, which can be achieved with `:g/./norm@r` (I'm not sure why this behaves differently than `:%norm@r`, but suffice to say, the latter does not work as intended.) Lines with `X` are deleted with `:g/X/d`, and the blank lines at the end left as a result of the construction of the `r` macro are cleaned up with `dG`.

# Answer
> 6 votes
# Brachylog, 5 bytes

```
{⊇Ċ}ᶠ

```

Try it online!

## How it works

```
{⊇Ċ}ᶠ
    ᶠ   find all the possible outputs of the following predicate
 ⊇          the output is an ordered subset of the input
  Ċ         the output is a list with two elements

```

# Answer
> 5 votes
# 05AB1E, 3 bytes

### Code:

```
æ2ù

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
æ      # Powerset of the input
 2ù    # Keep the items of length two

```

# Answer
> 4 votes
# Octave, 23 bytes

```
@(s)[nchoosek(+s,2) '']

```

Try it online!

# Answer
> 4 votes
# Python 3, 44 bytes

```
f=lambda k,*s:[*s]and[[k,x]for x in s]+f(*s)

```

Try it online!

Takes input as individual function parameters.

# Answer
> 4 votes
# Octave, ~~49~~ 48 bytes

```
@(x)[imag(y=(y=triu(x+j*x',1))(~~y)) real(y) '']

```

Anonymous function that avoids the built-in (`nchoosek`).

**Try it online!**

### Explanation

`x+j*x'` uses broadcasting to build a matrix of complex numbers where the real and imaginary parts are all pairs of code points from the input `x`.

`y=triu(...,1)` keeps the upper triangular part excluding the diagonal, making the rest of elements zero. The result is assigned to variable `y`.

`y=(...)(~~y)` retains the nonzero elements in the form of a column vector, which is assigned to variable `y`.

`imag(...)` and `real(...)` extract the real and imaginary parts.

`[... ... '']` converts back to char to build the output.

# Answer
> 3 votes
# Python, 53 bytes

*2 bytes saved thanks to @CalculatorFeline*

```
lambda a:[(x,y)for i,x in enumerate(a)for y in a[:i]]

```

Try it online!

# Answer
> 3 votes
# , 18 bytes

```
combn(scan(,''),2)

```

reads the list from stdin, returns a matrix where the columns are pairs.

Try it online!

# Answer
> 3 votes
# Perl 6, 17 bytes

```
*.combinations(2)

```

Whew, that's a long method name.

# Answer
> 3 votes
# Pari/GP, 34 bytes

```
a->concat([[[x,y]|y<-a,x<y]|x<-a])

```

Try it online!

# Answer
> 3 votes
# Octave, 38 bytes

```
@(s)s([[x y]=find(s|s'),y](y<x,[2 1]))

```

Another answer to avoid `nchoosek` built-in.

Try it online!

# Answer
> 3 votes
# Arturo, 18 bytes

```
$=>[combine.by:2&]

```

Try it

# Answer
> 2 votes
# Python ≥ 2.7, 55 bytes

```
lambda l:list(combinations(l,2))
from itertools import*

```

repl.it!

# Answer
> 2 votes
# Javascript (ES 5), from 108 to 78 bytes

I post my answer today but I obviously promise to not accept my own answer:

```
x=input;
a=[];

for(n=0;n<(x.length-1);n++){for(i=n+1;i<(x.length);i++){a.push([x[n],x[i]]);}}

```

# Answer
> 2 votes
# Pyth, 7 4 bytes

<sup> -3 bytes thanks to Leaky Nun!</sup>

```
.cQ2

```

Try it online!

# Answer
> 2 votes
# Scala, 17 bytes

```
_.combinations(2)

```

# Answer
> 2 votes
# Python, 74 bytes

```
f=lambda a:[(c,d) for i,c in enumerate(a) for j,d in enumerate(a) if i<j]

```

# Answer
> 2 votes
# Japt, 2 bytes

```
à2

```

Test it (`-Q` flag for visualisation purposes only)

# Answer
> 2 votes
# Python, 64 bytes

```
f=lambda a:sum((list(zip(a, a[i:]))for i in range(1,len(a))),[])

```

# Answer
> 2 votes
# Ruby, ~~38 34~~ 24 bytes

```
->x{[*x.combination(2)]}

```

Thanks Seims for the idea that saved 10 bytes.

Try it online!

# Answer
> 2 votes
## Clojure, 42 bytes

```
#(set(for[i % j(remove #{i}%)](set[i j])))

```

Returns a set of sets :)

# Answer
> 2 votes
# , 17 bytes

```
({~$#:I.@,)#\</#\

```

Try it online!

## Explanation

```
({~$#:I.@,)#\</#\  Input: string S
               #\  Get the length of each prefix of S
           #\      Get the length of each prefix of S again
             </    Test using greater than (<) between each
         ,         Flatten
      I.@          Find the indices where the value is 1
   $               Shape of that table
    #:             Convert the indices to the base represented by the shape
 {~                Index into S at those values

```

# Answer
> 2 votes
# Pip, `-p` 4 bytes

```
aCB2

```

`CB` is the operator for combinations, not much explanation needed

Try It Online!

# Answer
> 2 votes
# Go, 132 bytes

```
func f[T any](S[]T)(O[][]T){if len(S)<3{O=append(O,S)}else{for a,i:=range(S){for _,j:=range(S[a+1:]){O=append(O,[]T{i,j})}}}
return}

```

Attempt This Online!

A generic function that takes in a slice of type `T` and outputs a slice of slices of type `T`.

A solution that does only `[]string -> [][]string` is 8 bytes longer.

### Explanation

```
func f[T any](S[]T)(O[][]T){  // boilerplate
if len(S)<3{                  // if the input length < 3,
  O=append(O,S)               // just return the input
}else{                        // otherwise,
  for a,i:=range(S){          // for each 1st element,
    for _,j:=range(S[a+1:]){  // and each 2nd element,
      O=append(O,[]T{i,j})}}} // add the pair
return}                       // return the result

```

# Answer
> 1 votes
# JavaScript ES6, 52 bytes

```
a=>a.map((x,i)=>a.slice(0,i).map(y=>[x,y])).slice(1)

```

If there was like a `flatMap` that would save a lot of bytes.

# Answer
> 1 votes
# Python, 55 bytes

```
f=lambda s:[(s[0],j)for j in s[1:]]+f(s[1:])if s else[]

```

Try it online!

Longer than other Python answers, but it uses a different technique so I think it's worth posting.

# Answer
> 1 votes
# Nibbles, 1.5 bytes

```
`_~

```

Attempt This Online!

# Answer
> 1 votes
# Thunno, \\$ 3 \log\_{256}(96) \approx \\$ 2.47 bytes

```
2zQ

```

Attempt This Online!

Almost a built-in. `zQ` is "combinations of b with length a".

# Answer
> 1 votes
# Vyxal, 2 bytes

```
2ḋ

```

Try it Online!

Almost a built-in.  is the built-in for "combinations of a with length b"

# Answer
> 1 votes
# Curry (PAKCS), 20 bytes

```
f(_++x:_++y:_)=[x,y]

```

Attempt This Online!

# Answer
> 1 votes
# Thunno 2, 2 bytes

Try it online!

`ċ` = "all combinations of b with length a"

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


# Question
Title: My device malfunctions... Abuse its undefined string behaviour!
Help! My device malfunctions and whenever I try to repeat a String, I get a messy results. Instead of repeating the same string **N** times, it fills an **NxN** square with each of its characters, and stacks the squares up.

For example, given the String `"Test"` and the number `2`, instead of `"TestTest"`, I get:

```
TT
TT
ee
ee
ss
ss
tt
tt

```

---

After I have seen this for a while, I started to like it. Your task today is to reproduce this strange behaviour. Given a *non-empty* string that consists of printable ASCII only, and a *positive* integer, output the String my malfunctioning device returns.

* All standard rules apply.
* The input and output may be handled through any reasonable mean.
* This is , so the shortest code in bytes in each language wins.

---

# Test Cases

```
Input
Output

----------

"Test", 2

TT
TT
ee
ee
ss
ss
tt
tt

----------

"UuU", 3

UUU
UUU
UUU
uuu
uuu
uuu
UUU
UUU
UUU

----------

"A", 5

AAAAA
AAAAA
AAAAA
AAAAA
AAAAA

----------

```

You can find a larger test case here. Good luck and have fun golfing!

# Answer
# Jelly, 5 bytes

This is exactly what we are asked to do... Abuse undefined behaviour!\*

```
×+⁷×⁴

```

Try it online!

* By *undefined behaviour* I am talking about using `×` for repeating strings. Sometimes it's shorter than usual behaviour, so why not?
> 9 votes

# Answer
# Jelly, 4 bytes

Inspired by Mr. Xcoder's Jelly abuse

```
x⁹×Y

```

A full program taking the string and the number as command line arguments and printing the result (since as a dyadic link it returns a list of strings and newline characters, which may not really be acceptable).

**Try it online!**

### How?

The naive (non-abusive) five byter is:

```
x⁹x€Y - Main link: list of characters, s; number, n  e.g. "xyz", 2
 ⁹    - chain's right argument, n                         2
x     - times (repeat each element)                       ['x','x','y','y','z','z']
  x€  - times for €ach                                   [['x','x'],['x','x'],['y','y'],['y','y'],['z','z'],['z','z']]
    Y - join with newlines                                ['x','x','\n','x','x','\n','y','y','\n','y','y','\n','z','z','\n','z','z']
      - as a full program: implicit print
      -   note: this could be submitted as a dyadic link (AKA unnamed function)

```

The abuse used by Mr. Xcoder (Python's `operator.mul` may act on a `str` and an `int` to repeat the `str` \- here single characters - and the atom which uses it, `×`, vectorises w.r.t. its left argument) can be used here too to replace `x€` with `×` \- yielding the full program:

```
x⁹×Y - Main link: list of characters, s; number, n  e.g. "xyz", 2
 ⁹   - chain's right argument, n                         2
x    - times (repeat each element)                       ['x','x','y','y','z','z']
  ×  - multiply (vectorises)                             ["xx","xx","yy","yy","zz","zz"]
     -     (note, these "..." are actually strings, something not usually seen in Jelly)
    Y - join with newlines                                ["xx",'\n',"xx",'\n',"yy",'\n',"yy",'\n',"zz",'\n',"zz"]
      - implicit print

```
> 9 votes

# Answer
# Haskell, 26 bytes

The function `(!)` returns a list of lines.

```
n!s=map(<$[1..n])s<*[1..n]

```

Try it online!
> 5 votes

# Answer
# Bash + GNU Sed, 58

Using a very similar technique to this answer to illustrate how close to being a dup to this that this question is:

```
printf -vr %$1s
sed "s/./${r// /&}\n/g;s/\S*./${r// /&}/g"

```

Try it online.
> 5 votes

# Answer
# Husk, ~~5~~ 4 bytes

-1 byte thanks to @Zgarb

```
SṀRṘ

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

-2 bytes thanks to scottinet

```
ε×²F=

```

Try it online!

```
ε     # For each character:
 ×    #   Repeat this character N times
  ²F  #   For 0 .. N:
    = #     Print without popping

```
> 3 votes

# Answer
# PowerShell, 31 bytes

```
param($a,$b)$a|%{,("$_"*$b)*$b}

```

Try it online!

Explanation:

```
param($a,$b)                    # Takes input $a (char-array) and $b (integer)
            $a|%{             } # Loop through every character in $a
                   "$_"*$b      # Construct a string of $b length of that character
                 ,(       )*$b  # Repeat that $b times
                                # Implicit Write-Output inserts a newline between elements

```
> 3 votes

# Answer
# Python 3, 42 bytes

```
lambda x,y:"".join(y*(r*y+"\n")for r in x)

```

Try it online!
> 2 votes

# Answer
# Japt, 7 bytes

Outputs an array of strings.

```
VÆmpVÃy

```

Try it (`-R` flag for visualisation purposes only)

---

## Explanation

Implicit input of string `U` and integer `V`.

```
VÆ    Ã

```

Generate an array of integers from `0` to `V-1` and pass each through a function.

```
mpV

```

Map (`m`) over `U` and repeat (`r`) each character `V` times.

```
y

```

Transpose and implicitly output resulting array.
> 2 votes

# Answer
## C++, ~~125~~ 123 bytes

-2 bytes thanks to aschepler

```
#include<string>
using s=std::string;s u(s a,int b){s r;for(auto&c:a)for(int i=0;i<b*b;){if(!(i++%b))r+=10;r+=c;}return r;}

```

Make sure that the overload of the `+=` operator called takes a `char` data type in this instruction `if(!(i++%b))r+=10`
> 2 votes

# Answer
# MATL, 5 bytes

```
t&Y"!

```

**Try it online!**

### Explanation

```
t     % Implicitly input a number, n. Duplicate
&Y"   % Implicitly input a string. Three-input repelem function. Repeats
      % each entry in the first input (s) the specified numbers of times
      % vertically (n) and horizontally (n). Gives a char matrix
!     % Transpose. Implicit display

```
> 2 votes

# Answer
# Charcoal, ~~9~~ 8 bytes

-1 thanks to Kevin Cruijssen

```
ＦＳ«ＧTηι↓

```

Try it online!

## Explanation

```
ＦＳ        For each character (i) in the next input as a string
   «
    Ｇ   ι  Polygon using i as fill
      T     Right, down, then left
       η    The second input (h) (automatically casted to a number)
          ↓ Move down

```
> 2 votes

# Answer
# Brainfuck, 103 Bytes

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

```

Try it online (Make sure to turn on dynamic memory or it won't run)

Note: The input is slightly different. This code takes in a string where the last character is a digit for number of repeats. So input might look like `Test5`.

This code requires an unbounded tape, and relies on byte wrapping behavior.

Ungolfed:

```
,[>,]< Take Input
>-[>+<-----]>--- ASCII 0, to use in next step
[-<<->>]<< Convert ASCII number to raw number by subtracting ASCII 0
[->+<]> Move the number over one to separate it from the phrase
[
  [->+>+<<]>>[-<<+>>]< Copy the number
  [
    <<<[<]> Back to Letter
    . Print Letter
    [>]>>- Back to Counter
  ]
  ++++++++++.[-]< Print the newline
  <<[<]>[-]> Clear Letter
  [>]> Back to Counter
]

```
> 2 votes

# Answer
# J, ~~15~~ 14 bytes

```
[:,/]$"1 0~[,[

```

Sub-optimal for sure. Returns a 2D array of chars. Takes `n` as the left argument and the string as the right.

On mobile, so the usual amenities are missing.

# Explanation

(For old answer)

```
[:,/(2#[)$"1 0]

```

`$"1 0` reshape each character to

`(2#[)` an `n` * `n` matrix.

`,/` join matrices together to yield the output.
> 1 votes

# Answer
# SOGLOnline commit 2940dbe, 4 bytes

```
∙ι*I

```

This was made for a specific commit, namely the one before I changed  from, when used on an array of strings, repeating each letter x times to repeat each item x times. Here is the online interpreter without that version, which, as can be seen, doesn't work.

To try the commit, download this, open the `index.html` file, in the program paste `∙ι*I` and in the input write something like

```
Test
2

```

Explanation:

```
∙ι*I
∙     get an array with 2nd input amount of items of the 1st input
 ι    pop one implicit input to cycle back to the number
  *   multiply horizontally each separate character
   I  rotate clockwise

```
> 1 votes

# Answer
# , 59 bytes

```
function(S,n)write(rep(strsplit(S,"")[[1]],e=n*n),"",n,,"")

```

Writes to stdout.

Splits the string into characters, repeats each `n^2` times, and then prints with width `n` and with no separator.

Try it online!
> 1 votes

# Answer
# Pyth, 9 bytes

```
VEp*+*NQb

```

Try it here!

# Pyth, ~~11~~ 10 bytes

```
sm*Q+*QdbE

```

Try it here!

**Or, 10 bytes:**

```
jsm*Q]*QdE

```

**Or, 11 bytes:**

```
js*RQm]*dQE
jsm*vzm*dvz
sm*vz+*dvzb

```
> 1 votes

# Answer
# Perl 5, 26 + 1 (-p) = 27 bytes

```
$"=<>;s|.|($&x$".$/)x$"|ge

```

Try it online!
> 1 votes

# Answer
# Java 8, ~~152~~ ~~128~~ ~~118~~ 100 bytes

```
s->n->{for(char c:s)for(int j=0;j++<n;System.out.println("".valueOf(new char[n]).replace('\0',c)));}

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog), 8 bytes

Takes repetition as left argument and text as right argument.

```
{⍺⌿⍺/⍪⍵}

```

Try it online!

`{``}` an unnamed lambda where  represents the left argument and  the right argument

`⍪⍵` make the text into a one-column table

`⍺/` replicate  times horizontally

`⍺⌿` replicate  times vertically
> 1 votes

# Answer
# Japt, 7 bytes

```
mpV² òV

```

Returns an array of strings.

Try it online! with the `-R` flag to join the array with newlines.

## Explanation

```
mpV² òV     Implicit input of U=string, V=number
m           Map each char in the input string to...
 pV²        Itself repeated V² times
     òV     Cut the resulting string into partitions of length V

```
> 1 votes

# Answer
# D, 86 bytes

```
S u(S,I)(S a,I b){S r;foreach(c;a)for(I i;i<b*b;){if(!(i++%b))r~='\n';r~=c;}return r;}

```

Try it online!

Takes the string as the left argument, and the integer as the right argument. This is a port of HatsuPointerKun's C++ answer into D.
> 1 votes

# Answer
# Thunno 2 `N`, 3 bytes

```
Ḅd×

```

Try it online!

Takes the number then the string

#### Explanation

```
Ḅd×  # Implicit input                                  ->  2, "Test"
Ḅ    # Multiply each of the characters by the number   ->  "TTeesstt"
 d   # Split this string into a list of characters     ->  ["T",  "T",  "e",  "e",  "s",  "s",  "t",  "t" ]
  ×  # Repeat each character input number of times     ->  ["TT", "TT", "ee", "ee", "ss", "ss", "tt", "tt"]
     # Implicit output, joined on newlines

```
> 1 votes

# Answer
# C (gcc), ~~83~~ 79 bytes

```
i,j;f(p,n)char*p,n;{for(;*p;p++)for(i=n;i--;puts(""))for(j=n;j--;putchar(*p));}

```

Try it online!
> 0 votes

# Answer
# CJam, 11 Bytes

```
{__*@e*/N*}

```

Function that takes string followed by int.

Try it Online
> 0 votes

# Answer
# Kotlin 1.1 - 99 bytes

```
fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.joinToString("\n"){p->List(c,{p}).joinToString("")}

```

Returns the whole output as a string.

**Can't use TryItOnline as 1.1 is not supported**

## Test

```
fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.joinToString("\n"){p->List(c,{p}).joinToString("")}

fun main(args: Array<String>) {
    println(s("Hello World", 5))
}

```

It would be 84 if a list of strings was acceptable as output:

```
fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.map{p->List(c,{p}).joinToString("")}

```
> 0 votes

# Answer
# Mathematica, 49 bytes

```
(z=#2;Grid[Column/@Table[#,z,z]&/@Characters@#])&

```

**input**

> \["Test",4\]
> 0 votes

# Answer
# PHP, 97 bytes

```
for($i=0;$i<strlen($s=$argv[1]);$i++)for($j=0;$j<$r=$argv[2];$j++)echo str_repeat($s[$i],$r)."
";

```
> 0 votes

# Answer
# Pyth, 12 bytes

Small minded, but I haven't gotten there just yet.

```
VQp*+*Nszbsz

```

Explanation:

```
VQ          For every letter in the first input...
  p         Print without newline...
   *+*Nszsz (The index * int(second input) + newline) * int(the second input)

```

Test Suite
> 0 votes

# Answer
# Clojure, 82 75 bytes

```
#(dotimes[x(count %1)](dotimes[y %2](prn(apply str(repeat %2(get %1 x))))))

```

Try it online!

Uncompressed:

```
#(dotimes [x (count %1)]
  (dotimes [y %2]
    (prn
      (apply str
        (repeat %2 (get %1 x))))))

```

Edit: Shaved a few chars off the end by replacing a for loop with the stdlib repeat function.
> 0 votes

# Answer
# C# (.NET Core), 68 + 18 bytes

```
a=>n=>new int[a.Length*n].Select((x,i)=>Enumerable.Repeat(a[i/n],n))

```

Also included in byte count:

```
using System.Linq;

```

Try it online!

Output is a collection of collections of characters (one collection for each line).

Explanation:

```
a => n =>                                // Take a string and a number
    new int[a.Length * n]                // Create new collection, 'n' times larger than 'a'
    .Select((x, i) =>                    // Replace every member with
        Enumerable.Repeat(a[i / n], n)   //     a collection of repeated character from 'a', based on index
    )

```
> 0 votes

# Answer
# Clojure v1.8, ~~63~~ ~~62~~ 58 bytes

```
#(map(fn[l](dotimes[i %2](prn(apply str(repeat %2 l)))))%)

```

Try it online!

# Explanation

```
(map ... s)           For every letter of the string 's'
(dotimes[i %2] ...)   Do 'n' times
(prn(apply str(repeat %2 l))) Repeat the letter 'n' times, combine to string and print

```
> 0 votes

# Answer
## GNU APL, 11 bytes

```
⍪/⎕{⍺⍺⍴⍵}¨⍞

```

Left argument:  number of repetitions.  the string.

This uses  to repeat each letter ( in the inner `{}` block) in `⍺x⍺` matrix.

Then we use `⍪/` to "laminate" them.
> 0 votes

# Answer
# Bash, 49 bytes

```
sed s/./$(printf \&%.s `seq $[$1*$1]`)/g|fold -$1

```

Try it online!
> 0 votes

# Answer
# Python 2, 46 bytes

```
x,y=input()
for p in x:print'\n'.join([p*y]*y)

```

Try it online!
> 0 votes

# Answer
# MathGolf, 8 bytes

```
*mÅn+m*~

```

String input as a list of characters.

Try it online.

**Explanation:**

```
*        # Repeat each character in the second (implicit) input-list the first
         # (implicit) input-integer amount of times
 mÅn+    # Append a newline to each inner string:
 m       #  Map over each string,
  Å      #  using the following two characters as inner code-block:
   n     #   Push a newline character
    +    #   And append it to the string
     m*  # Repeat each inner string the first (implicit) input-integer amount of times
       ~ # Dump this list of lines with trailing newlines to the stack
         # (after which the entire stack is joined and output implicitly as result)

```
> 0 votes

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


title: Complementary colors

text:
# Question
Title: Complementary colors
Given an input of a color in `#rrggbb` hex format, output its RGB complement in the same format.

The RGB complement R2G2B2 of any color R1G1B1 is defined as the color with R2 value *255 - R1*, B2 value *255 - B1*, and G2 value *255 - G1*.

Hex digits may be either in uppercase (#FFAA20) or lowercase (#ffaa20). The case of the input and output need not be consistent (so you may take input in lowercase but output in uppercase, and vice versa).

Since this is , the shortest code in bytes wins.

Test cases (note that since giving your program/function its own output should result in the original input (it is involutory), the test cases should work in both directions):

```
In/Out   Out/In
----------------
#ffffff  #000000
#abcdef  #543210
#badcab  #452354
#133742  #ecc8bd
#a1b2c3  #5e4d3c
#7f7f80  #80807f

```

# Answer
> 19 votes
## Pyth, ~~9~~ 8 bytes

*Thanks to @isaacg for -1 byte!*

```
sXz.HM16

```

Subtracting a certain color's value from 255 is equivalent to subtracting each of its hexadecimal digits from 15. Say a number is ***16a+b***. Then the value of the number created by subtracting its digits from 15 is ***16(15-a) + (15-b) = 255 - (16a+b)***.

```
sXz.HM16     implicit: z=input()
      16
   .HM        map hex representation over range
   .HM16     '0123456789abcdef'
  z           the input string
 X            Translate characters in x1 present in x2 to reversed x2
              that is, '0' becomes f, '1' becomes 'e', and so on.
              The initial '#' is unchanged.
s             That produced a list, so join into a string by reducing +

```

Try it here. Test suite.

# Answer
> 7 votes
# Retina, ~~13~~ 10 bytes

```
T`w`G-A9-0

```

There are three parts to the code, separated by backticks (```): `T` specifies transliterate mode, which replaces each character in the second part with its corresponding character in the third part.

`w` is the same as traditional regex's `\w`, or `_0-9A-Za-z`, which is expanded to `_0123456789ABCDEFGH...`.

The second part is expanded to `GFEDCBA9876543210`, thanks to Retina's nifty ability to expand in reverse order. Put these on top of each other, and we get:

```
_0123456789ABCDEFGH...
GFEDCBA987654321000...
 ^^^^^^^^^^^^^^^^

```

Note that the last character, `0`, is repeated to fit the length of the longer string, but we only care about the hexadecimal characters, shown by carets.

Thanks to Martin Büttner for suggesting this approach.

Try the test suite online.

# Answer
> 5 votes
# Julia 0.6, ~~74~~ 49 bytes

```
h->"#"join([hex(15-parse(Int,i,16))for i=h[2:7]])

```

Try it online!

Pretty long at the moment but it's a start. This is a lambda function that accepts a string and returns a string. The output will be in lowercase but the input can be in either.

As Thomas noted, subtracting each 2-digit color component from 255 is equivalent to subtracting each individual digit in the hexadecimal input from 15. Looping over the input string, excluding the leading `#`, we convert 15 - the parsed digit to hexadecimal. We join all of these then tack on a `#` and call it good.

# Answer
> 4 votes
# JavaScript ES6, 61 bytes ~~66 68 48 53 64~~

*Saves quite a few bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ, @NinjaBearMonkey, and @nderscore*

```
s=>"#"+(1e5+(8**8+~('0x'+s.slice(1))).toString(16)).slice(-6)

```

Takes advantage of auto-type-casting. Fixing the zeros killed the byte count

# Answer
> 4 votes
# Marbelous, 41 bytes

```
00@0
\\]]\/
-W/\@0
-W
~~
<A+700
+O//]]
+O

```

Online Interpreter here. Input should be in uppercase.

### Explanation

The `00` and `]]` at the bottom will fetch the first character (the `#`) and it will fall to the bottom and be outputted before anything else.

The first 3 lines are a loop to fetch all the remaining characters.

First we need to convert the hex digit characters to 0-15, by doing `x -= 48, x -= x > 9 ? 7 : 0` (since `'A' - '9'` is 8).

To find the complement, we simply need to convert every digit `x` to `15-x`. This is equivalent to (for 8-bit values) `(~x)+16 = ~(x-16)`.

Finally, we have to convert these numbers back into hex digits, by doing `x += x > 9 ? 7 : 0, x += 48`.

So now we have `x -= 48, x -= x > 9 ? 7 : 0, x = ~(x - 16), x += x > 9 ? 7 : 0, x += 48`.

Note that if we remove the expression with the first ternary operator, then input digits `A`-`F` will result in a negative x after negation.

Thus we can change the previous expression to: `x -= 48, x -= 16, x = ~x, x += (x > 9 || x < 0) ? 7 : 0, x += 48`, which is equal to `x -= 64, x = ~x, x += (x > 9 || x < 0) ? 7 : 0, x += 48`.

The above code is just an implementation of the last expression. `-W` is `x -= 32` and `+O` is `x += 24`. Since Marbelous uses unsigned 8-bit arithmetic, the condition `<A` covers both the case of `x > 9` and `x < 0`.

# Answer
> 4 votes
## JavaScript ES6, ~~63~~ ~~58~~ ~~52~~ 49 bytes

```
c=>c.replace(/\w/g,x=>(15-`0x${x}`).toString(16))

```

*Thanks to nderscore for saving 11 bytes!*

# Answer
> 4 votes
# Vyxal, 4 bytes

```
k6ḂĿ

```

Try it Online!

```
k6ḂĿ
k6   # Hex chars - "012356789abcdef"
  Ḃ  # Bifurcate - push its reverse without popping
   Ŀ # Transliterate the input from the hex chars to the reverse hex chars

```

# Answer
> 3 votes
# Jolf, 17 bytes

```
pq#-w^88C Li1~560
pq                pad
         _Li1     the input, w/out the first char
        C    ~5   parsed as a base-16 integer (~5 = 16)
    w^88          8 ^ 8 - 1 (the magic number)
   -              subtract the parsed input from said number
  #               convert result to hexadecimal
               60 pad the result with 6 0's

```

Try it here!, Test suite (Use full run, which now works.)

# Answer
> 3 votes
# Japt, ~~35~~ ~~32~~ ~~22~~ ~~20~~ ~~16~~ 15 bytes

```
¡Y?(F-XnG)sG :X

```

Explanation:

```
¡                 //Take input and map (shortcut to "Um@"). Input should in the form of "#123456"
 Y?               //if Y is not 0, then return (F-XnG)sG, otherwise last step...
    F-XnG           //Subtract X, converted from hexadecimal (G is 16) to decimal, from 15
          sG        //convert decimal to hexadecimal
             :X   //...otherwise return X unchanged (happens only with #, the first char)

```

# Answer
> 2 votes
# MATL, 21 bytes

```
35,5Y216,j6L)!16ZA-)h

```

This uses release 6.0.0 of the language/compiler, which is earlier than the challenge.

Input digits should be uppercase.

### Example

This has been executed on Octave:

```
>> matl
 > 35,5Y216,j6L)!16ZA-)h
 >
> #FFAA20
#0055DF

```

### *Edit (June 12, 2016)*

The code can now be **tried online**. Commas need to be replaced by spaces, and `6L` by `4L`, to conform to changes in the language.

### Explanation

```
35,             % number literal: ASCII code of '#'
5Y2             % '0123456789ABCDEF'
16,             % number literal
j               % input string
6L)             % remove first element
!               % transpose
16ZA            % convert from hex to dec
-               % subtract from 16
)               % index into '0123456789ABCDEF' to convert back to hex
h               % prepend 35, which gets automatically converted into '#'

```

# Answer
> 2 votes
# Perl, 30 bytes

*includes +1 for `-p`*

```
s/\w/sprintf"%x",15&~hex$&/eg

```

usage: `echo #000000 | perl -p file.pl`
or `echo #000000 | perl -pe 's/\w/sprintf"%x",15&~hex$&/eg'`.

# Answer
> 2 votes
# x86-16 machine code, IBM PC DOS, ~~60~~ ~~41~~ 32 bytes

**Binary:**

```
00000000: be82 00ac cd29 b106 ac3c 397e 022c 272c  .....)...<9~.,',
00000010: 30f6 d03c f976 0204 2704 40cd 29e2 e9c3  0..<.v..'.@.)...

```

**Unassembled listing:**

```
BE 0082     MOV  SI, 82H            ; command line input set to string
AC          LODSB                   ; load first '#' char
CD 29       INT  29H                ; write it to console
B1 06       MOV  CL, 6              ; loop 6 chars
        INLOOP:
AC          LODSB                   ; load next ASCII hex char into AL
3C 39       CMP  AL, '9'            ; is char an alpha (a-f)?
7E 02       JLE  NOHEX_IN           ; if not, is numeric
2C 27       SUB  AL, 'f'-'9'-6      ; otherwise ASCII adjust a-f
        NOHEX_IN:
2C 30       SUB  AL, '0'            ; ASCII to decimal convert
F6 D0       NOT  AL                 ; complement the color (magic happens here)
3C F9       CMP  AL, 0F9H           ; is char <= 9?
76 02       JBE  NOHEX_OUT          ; if not, is numeric
04 27       ADD  AL, 'f'-'9'-6      ; otherwise ASCII adjust a-f
        NOHEX_OUT:
04 40       ADD  AL, '0'+10H        ; decimal convert to ASCII
CD 29       INT  29H                ; write char to console
E2 E9       LOOP INLOOP             ; keep looping
C3          RET                     ; return to DOS

```

So nearly all of this code is brute-force conversion from an ASCII hex string into a numeric value and then back again. No CPU instructions on x86-16 to help with that I'm afraid!

**I/O:**

Standalone PC DOS executable. Input via command line, output to `STDOUT`.

# Answer
> 2 votes
# Japt v2.0a0, 9 bytes

```
r\wÈnG'nF

```

Try it

```
r\wÈnG'nF     :Implicit input of string
r             :Replace
 \w           :  RegEx /[0-9a-z]/gi
   È          :  Pass each match through the following function
    n         :    Toggle base
     G        :      16
      'n      :    Subtracting intermediate result from
        F     :      15

```

# Answer
> 1 votes
# Pyth, ~~20~~ 19 bytes

*1 byte thanks to xnor.*

```
%"#%06x"-t^8 8itz16

```

Try it online. Test suite.

### Explanation

* `z` is the input
* `tz` removes the `#`
* `itz16` parses as a hexadecimal number
* `t^8 8` calculates 8<sup>8</sup> \- 1
* `-t^8 8itz16` calculates 8<sup>8</sup> \- 1 - input
* `%"#%06x"-t^2 24itz16` formats it into a zero-padded 6-character hex string and adds the `#`

# Answer
> 1 votes
# Mathematica, ~~69~~ 60 bytes

```
"#"<>IntegerString[8^8-#~StringDrop~1~FromDigits~16-1,16,6]&

```

Once again, it's the string processing that kills me here.

# Answer
> 1 votes
# Java, ~~95~~ 90 bytes

```
String f(String v){return v.format("#%06x",0xFFFFFF^Integer.parseInt(v.substring(1),16));}

```

Bitwise XOR.

# Answer
> 1 votes
## sed, 48 bytes

```
y/0123456789ABCDEFabcdef/fedcba9876543210543210/

```

Or 36 bytes if you only need to support one case.

# Answer
> 1 votes
# Haskell, 85 bytes

My first submission, it will probably be the longest (85 bytes) but hey, you got to start somewhere. In Haskell:

```
import Numeric;f=('#':).concatMap((flip showHex)"".(15-).fst.head.readHex.(:[])).tail

```

It's using the same subtract from 15 trick I saw other people use.

I also tried using printf along with the other trick (subtract 8^8 - 1) and it works in ghci but for some reason it doesn't compile:

```
g=printf "#%06x" .(8^8-1-).fst.head.readHex.tail

```

If someone could make this work that would be great!

# Answer
> 1 votes
# C, 94 bytes

```
t(char*b){for(int i;i=*b;++b)*b=i>96&i<103?150-i:i>64&i<71|i>47&i<54?118-i:i>53&i<58?111-i:i;}

```

Function takes in a char array, returns inverse value. Produces uppercase letters for response. The code flips each ASCII hex character to its inverse if it's valid, ignores it otherwise.

# Answer
> 1 votes
# 2, 18 chars / 34 bytes

```
ïē/\w⌿,↪(ḏ-`ᶍ⦃$}”ⓧ

```

`Try it here (Firefox only).`

Using a version created after the challenge.

# Explanation

```
ïē/\w⌿,↪(ḏ-`ᶍ⦃$}”ⓧ // implicit: ï=input, ḏ=15
ïē/\w⌿,             // replace all alphanumeric chars in ï with:
       ↪(ḏ-`ᶍ⦃$}”ⓧ // (15 - char's decimal form) converted to hex
                    // implicit output

```

# Non-competitive solution, 15 chars / 29 bytes

```
ïē/\w⌿,↪(ḏ-`ᶍ⦃$}”ⓧ

```

Uses transliteration.

# Answer
> 1 votes
## Python, 96

```
x=input()
print("#")
for i in range(3):
    print(hex(255-int(x[(1+2*i)]+x[(2+2*i)],16))[2:4])

```

First code golf, please give opinions :)

# Answer
> 1 votes
# C (clang), ~~53~~ 49 bytes

```
p(*s){printf("#%06x",0xffffff-wcstol(s+1,0,16));}

```

Try it online!

-4 thanks to @jdt

# Answer
> 1 votes
# Befunge-98, 37 bytes

```
~,v>v
~f<^ s
>,^ >-:9w>'0+
^+W'    ]^

```

This takes input in lowercase, outputs the answer in lowercase, then enters an infinite loop.

Try it online!

40 byte version that terminates

## Explanation

```
~,v

```

This gets the first character of the input (which is always `#`), outputs it unchanged, and enters the loop.

```

~f<  s

```

At the start of the loop, `f` pushes `15` onto the stack, `~` gets the next character of the input, and `s` puts that character one space to its left in the source code (without executing it).

```
   >v
   ^I

```

(I'm using `I` to represent the character from the input that is now in the source code.) This section loops back around to execute that character. Every character in the range `0-9` or `a-f` pushes the corresponding hex value on the stack.

```

    >-:9w

```

The hex value is subtracted from `15` (the previous top of the stack) to get its complement. `:9w` creates a copy of the complement, and compares the copy with `9`, with the IP going down, up or right depending on whether it is greater, less than, or equal.

```

         >
        ]^

```

If the complement is greater than 9, the IP goes down and hits the `]` ("turn right") from above, turning to move left. If the copy was less than 9, the IP goes up and hits the `]` from below, turning to move right. In that case, it gets redirected back to the third line. If the copy was exactly 9, the IP goes right and hits the `>` immediately.

```

          '0+

```

If the complement is less than or equal to 9 (i.e. a digit), it is added to ASCII 48 (`0`) to produce the correct digit.

```

^+W'

```

If the complement is greater than 9, it is added to ASCII 87 (`W`) to produce the correct character (in the range `a-f`).

```

  <
>,^

```

In all cases, the character corresponding to the complement is printed and the IP moves back to the start of the loop.

The loop repeats, outputting the complement of every hex digit in the input.

After we print the answer, the input has been completely used up. Once EOF is reached, `~` reflects the IP. This means that `~f<` is now an infinite loop that pushes `15` on the stack forever. This doesn't produce any effects (except for possibly crashing), so we don't care about it.

# Answer
> 1 votes
# Julia 1.0, 46 bytes

```
h->'#'repr(~parse(UInt,h[2:7];base=16))[13:18]

```

Try it online!

# Julia 0.6, 40 bytes

```
h->"#"hex(~parse(UInt,h[2:7],16))[11:16]

```

Try it online!

Simply a bitwise not (`~`) on the full number, in hex, the rest around is to parse and print the numbers in hexadecimal and keeping the last 6 numbers

# Answer
> 1 votes
# Nibbles, 8 bytes (16 nibbles)

```
`($+.$hex- 15hex

```

```
`($+.$hex- 15hex
`($                 # output the first element of input (the '#')
                    # and save the rest;
    .$              # now, map over the rest
             hex    #   convert from hex,
         - 15       #   subtract from 15,
      hex           #   and convert back to hex
   +                # and convert the resulting list of characters to a string
                    # (which is implicitly output after the '#')

```

# Answer
> 1 votes
# Go, 111 bytes

```
import(."strconv";."fmt")
func f(s string)string{n,_:=ParseInt(s[1:],16,64)
return Sprintf("#%06x",0xffffff-n)}

```

Attempt This Online!

# Answer
> 0 votes
# TeaScript, 24 bytes

```
"#"+S(8**8-1-xS1)t16))x6

```

Bugs in the interpreter aren't letting me get this shorter :(

Try it online

# Answer
> 0 votes
# CJam, 16 bytes

```
qA,'G,65>+s_W%er

```

This is fairly long because CJam handles base changes differently, so it was shorter to just do transliteration. See my Retina answer for more on transliteration.

Try it online.

### Explanation

```
q      e# Get the input
A,     e# Push [0 1 ... 8 9]
'G,65> e# Push "ABCDEF"
+s     e# Combine and convert to string
_W%    e# Make a copy and reverse it
er     e# Replace each character in the first string with
       e# the corresponding character in the second

```

# Answer
> 0 votes
# Python 3, 44 bytes

Originally I used `256^3`, then `16^6`. Then I saw Pietu1998's `8^8` and now this solution uses that instead.

```
"#{:06x}".format(8**8-1-int(input()[1:],16))

```

# Answer
> 0 votes
## Bash + tr, 35 bytes

```
tr 0-9A-Fa-f fedcba9876543210543210

```

Output is always lowercase.

Unfortunately "tr" does not take ranges in reverse order so I had to spell them out.

# Answer
> 0 votes
## C, 147 bytes

```
void p(char s[]){char c[3];int i=1;printf("#");while(i<6){strncpy(c,s+i++,2);i++;int x=255-strtol(c,NULL,16);x<10?printf("0%x",x):printf("%x",x);}}

```

Used strtol to convert from hex string to int then subtracted the number from 255 to get the compliment like the original post said. I am, however, wondering if there is a way to pass a range of characters from s to strtol so I don't have to waste a bunch of bytes copying to a new string?

# Answer
> 0 votes
## R, 62 bytes

```
f=function(a)sprintf('#%06x',(8^8-1)-strtoi(substr(a,2,7),16))

```

# Answer
> 0 votes
## PowerShell, 48 bytes

```
param($a)"#{0:x6}"-f(16MB-1-("0x"+$a.Trim('#')))

```

Necessarily takes input via `param($a)` as a string, delimited with `'` or `"`, since `C:\Tools\Scripts\Golfing> .\complementary-colors #a1b2c3` on the PowerShell command line will treat `#a1b2c3` as a comment and summarily ignore it.

Left-to-right, the `"#{0:x6}"-f(...)` formats our output calculations back into hexadecimal with a guaranteed 6 characters (to account for input `#ffffff`). Inside the parens, we subtract our input number from `0xffffff`. We do this by leveraging the fact that PowerShell parses hexadecimal numbers in format `0xNNN`, so we construct a proper-format hex number from our input number `$a`. (Note that concatenation plus `.Trim()` is shorter than `.Replace()` here by one byte.) We also leverage the `MB` unary operator via `16MB-1` to construct `16777215` instead of `0xffffff`.

# Answer
> 0 votes
# PHP, 37 bytes

```
printf('#%06x',8**8-1-hexdec($argn));

```

Try it online!

Or if you prefer to be more bit-wise (and byte-foolish) about it:

### PHP, 38 bytes

```
printf('#%06x',~hexdec($argn)&8**8-1);

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
kfḲṆ

```

Try it online!

## Thunno 2 `j`, 11 bytes

```
ḣ²Hɠ⁻_Ḥ2ṛ'#

```

Try it online!

#### Explanation

```
kfḲṆ  # Implicit input
kf    # Hexadecimal characters: "0123456789ABCDEF"
  Ḳ   # Bifurcate: duplicate and reverse
   Ṇ  # Transliterate: [0-9A-F] -> [F-A9-0]
      # Implicit output

```

```
ḣ²Hɠ⁻_Ḥ2ṛ'#  '# Implicit input
ḣ             # Remove the leading "#"
 ²            # Split into pairs
  H           # Convert each from hexadecimal
   ɠ⁻_        # Subtract each from 255
      Ḥ       # Convert each to hexadecimal
       2ṛ     # Pad with 0s to length 2
         '#  '# Push "#" to the stack
              # Implicit output of joined stack

```

# Answer
> 0 votes
# Ruby, 31 bytes

```
->s{"#%6x"%(8**8-1-s[1..].hex)}

```

Attempt This Online!

# Answer
> 0 votes
# 05AB1E, 6 bytes

```
15ÝhÂ‡

```

Try it online or verify all test cases.

**Or with the more straight-forward approach (15 bytes):**

```
ćs2ôH₅αh2jð0:J«

```

Try it online or verify all test cases.

**Explanation:**

```
15Ý         # Push a list in the range [0,15]
   h        # Convert each integer to a hexadecimal character
    Â       # Bifurcate this list; short for Duplicate & Reverse copy
     ‡      # Transliterate the (implicit) input-string using these two lists
            # (after which the result is output implicitly)

```

```
ć           # Extract head of the (implicit) input-string; push remainder-string and
            # first item separately to the stack
s           # Swap so the remainder-string is at the top
 2ô         # Split it into pairs
        H   # Convert each string in the triplet from hexadecimal to an integer
         ₅α # Take the absolute difference with 255
        h   # Convert it back to hexadecimal
   2jð0:    # Pad leading 0s to single hexadecimal characters if necessary:
   2j       #  Pad potential leading spaces to make all strings of length 2
     ð0:    #  Then replace all spaces with 0s
 J          # Join the triplet of pairs back to a string
«           # Append it back to the "#" that's on the stack
            # (after which the result is output implicitly)

```

---
Tags: code-golf
---