# Question
Title: Stripping off extra spaces from a string
You are given a string. Output the string with one space per words.

# Challenge

Input will be a string (not `null` or empty), surrounded with quotes(`"`) sent via the `stdin`. Remove leading and trailing spaces from it. Also, if there are more than one space between two words (or symbols or whatever), trim it to just one space. Output the modified string with the quotes.

# Rules

* The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to `~`(tilde) (character codes 0x20 to 0x7E, inclusive) except `"`,i.e, the string will not contain quotes(`"`) and other characters outside the range specified above. See ASCII table for reference.
* You must take input from the `stdin`( or closest alternative ).
* The output must contain quotes(`"`).
* You can write a full program, or a function which takes input (from `stdin`), and outputs the final string

# Test Cases

```
"this  is  a    string   "         --> "this is a string"

"  blah blah    blah "             --> "blah blah blah"

"abcdefg"                          --> "abcdefg"

"           "                      --> ""

"12 34  ~5 6   (7, 8) - 9 -  "     --> "12 34 ~5 6 (7, 8) - 9 -"

```

# Scoring

This is code golf, so the shortest submission (in bytes) wins.

# Answer
# CJam, 7 bytes

```
q~S%S*p

```

**Code Explanation**

CJam has reserved all capital letters as inbuilt variables. So `S` has a value of a space here.

```
q~          e# Read the input (using q) and evaluate (~) to get the string
  S%        e# Split on running lengths (%) of space
    S*      e# Join (*) the splitted parts by single space
      p     e# Print the stringified form (p) of the string.

```

This removes the trailing and leading spaces as well

Try it online here
> 12 votes

# Answer
# ///: 18 characters

```
/  / //" /"// "/"/

```

Sample run:

(Using faubiguy's interpreter from his Perl answer for Interpret /// (pronounced 'slashes').)

```
bash-4.3$ ( echo -n '/  / //" /"// "/"/'; echo '"   foo  *  bar   "'; ) | slashes.pl
"foo * bar"

```
> 10 votes

# Answer
# Perl, 22

(20 bytes of code, plus 2 command line switches)

```
s/ +/ /g;s/" | "/"/g

```

Needs to be run with the `-np` switch so that `$_` is automatically filled via stdin and printed to stdout. I'm going to assume this adds 2 to the byte count.
> 5 votes

# Answer
# Bash, ~~36~~ 32 bytes

As a function, a program, or just in a pipe:

```
xargs|xargs|xargs -i echo '"{}"'

```

## Explanation

The first `xargs` strips the quotation marks.

The second `xargs` trims the left side and replaces multiple adjacent spaces in the middle of the string with one space by taking each "word" and separating each with a space.

The `xargs -i echo '"{}"'` trims the right side and rewraps the resulting string in double quotes.
> 5 votes

# Answer
# Ruby, ~~31~~ ~~29~~ ~~25~~ 23 Bytes

```
p$*[0].strip.squeeze' '

```

**Code Explanation:**

* **`p`** outputs string within double quotes to `STDOUT` (There's more to it though...)
* **`$*`** is an array of `STDIN` inputs, `$*[0]` takes the first one
* **`strip`** removes starting and ending spaces
* **`squeeze ' '`** replaces \>1 space characters with a single space

**Test Cases:**
> 5 votes

# Answer
# Pyth, ~~17~~ ~~15~~ ~~11~~ 10 bytes

(thanks to Ypnypn and FryAmTheEggman)

```
pjd-cQdkNN

```

Could probably be golfed more.

If the output can use `'` instead of `"` then I only need 8 bytes:

```
`jd-cQdk

```
> 4 votes

# Answer
# JavaScript (ES6), 49 ~~52 58~~

**Edit** 6 bytes shorter, thanks to @Optimizer

**Edit 2** -3, thanks to @nderscore

Input/output via popup. Using template string to cut 1 byte in string concatenation.

Run snippet to test in Firefox.

```
alert(`"${prompt().match(/[^ "]+/g).join(" ")}"`)
```
> 3 votes

# Answer
# Haskell, ~~31~~ 25 bytes

```
fmap(unwords.words)readLn

```

`words` splits the string into a list of strings with spaces as delimiters and `unwords` joins the list of strings with a single spaces in-between. The quotes `"` are stripped of and put back by Haskell's `read` and `show` (implicitly via the REPL) functions on strings.

Outputting by the function itself is three bytes longer, i.e. 28 bytes:

```
print.unwords.words=<<readLn

```

Edit: @Mauris pointed to the `readLn` function, which saved some bytes.
> 3 votes

# Answer
## Python2, 37

Reduced by 1 byte thanks to @ygramul.

```
print'"%s"'%' '.join(input().split())

```

Original version:

```
print'"'+' '.join(input().split())+'"'

```

Test cases:
> 2 votes

# Answer
# R, 45 bytes

```
cat('"',gsub(" +"," ",readline()),'"',sep="")

```

The `readline()` function reads from STDIN, automatically stripping any leading and trailing whitespace. Excess space between words is removed using `gsub()`. Finally, double quotes are prepended and appended and the result is printed to STDOUT.

Examples:

```
> cat('"',gsub(" +"," ",readline()),'"',sep="")
    This   is     a   string
"This is a string"

> cat('"',gsub(" +"," ",readline()),'"',sep="")
12 34  ~5 6   (7, 8) - 9 -
"12 34 ~5 6 (7, 8) - 9 -"

```
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
#õKðý'".ø

```

Try it online!

---

```
#         | Split on spaces.
 õK       | Remove empty Strings.
   ðý     | Join with spaces.
     '".ø | Surround with quotes.

```
> 2 votes

# Answer
# Java 8, 40 bytes

```
s->'"'+s.replaceAll(" +"," ").trim()+'"'

```

**Explanation:**

Try it here.

```
s->                        // Method with String as parameter and return-type
  '"'                      //  Return a leading quote
  +s.replaceAll(" +",      //  + Replace all occurrences of multiple spaces in the input
                     " ")  //    with a single space
    .trim()                //    and remove all leading and trailing spaces
  +'"'                     //  + a trailing quote

```
> 2 votes

# Answer
# Mathematica, 75 bytes

```
a=" ";b=a...;Print[InputString[]~StringReplace~{b~~"\""~~b->"\"",a..->a}]

```
> 1 votes

# Answer
# KDB(Q), 28 bytes

```
" "sv except[;enlist""]" "vs

```

# Explanation

```
                       " "vs    / cut string by space
      except[;enlist""]         / clear empty strings
" "sv                           / join back with space

```

# Test

```
q)" "sv except[;enlist""]" "vs"12 34  ~5 6   (7, 8) - 9 -  "
"12 34 ~5 6 (7, 8) - 9 -"

```
> 1 votes

# Answer
# Japt `-Q`, ~~10~~ 4 bytes

```
¸f ¸

```

Try it
> 1 votes

# Answer
# Octave, 44 bytes

```
@(x)[34 strjoin(regexp(x,'\S+','match')) 34]

```

**Try it online!**
> 1 votes

# Answer
# Tcl, 69 bytes

```
puts [string map {{ "} \" {" } \"} [regsub -all \ + [gets stdin] \ ]]

```

Try it online!

~~Tcl, 79 bytes
```
puts \"[string trim [regsub -all \ + [string range [gets stdin] 1 end-1] \ ]]\"

```
Try it online!<br>~~
> 1 votes

# Answer
# Jq 1.5, 42 bytes

```
split(" ")|map(select(length>0))|join(" ")

```

Sample Run

```
$ jq -M 'split(" ")|map(select(length>0))|join(" ")' < data
"this is a string"
"blah blah blah"
"abcdefg"
""
"12 34 ~5 6 (7, 8) - 9 -"

$ echo -n 'split(" ")|map(select(length>0))|join(" ")' | wc -c
  42

```

Try it online
> 1 votes

# Answer
# Perl 5, 17 bytes

16 bytes of code + 1 for `-p`

```
s/ *("| ) */$1/g

```

Try it online!
> 1 votes

# Answer
# Powershell, 40 bytes

```
"`"$(($args-Replace' +'," ").trim())`""

```

Pretty straight forward and not very impressive.

**Explanation**

Take input parameter via (predfined) args-variable, replace all multiple spaces with one, trim leading and trailing spaces using trim()-method, add quotes. Powershell will print strings to console as default behavior.
> 1 votes

# Answer
# Zsh, 15 bytes

```
<<<\"${(Qz)1}\"

```

Try it online!

Input string contains embedded quotes. Remove the `Q` for **14 bytes** if the input string does not contain embedded quotes, as is done in some of the other answers here.

Parameter expansion flags: `Q` dequotes, then `z` splits into words as the shell does. The words are then implicitly joined by spaces.
> 1 votes

# Answer
# GolfScript, 8 bytes

```
' '%' '*

```

Try it online!

# Explanation

The logic is quite simple:

```
' '%     # Split on spaces, remove empty results
    ' '* # Join on spaces

```
> 1 votes

# Answer
# K (ngn/k), ~~21~~ ~~18~~ ~~16~~ 15 bytes

```
" "/(~#:')_" "\

```

Try it online!

* `" "\` split (implicit) input on spaces
* `(~#:')_` drop empty strings
* `" "/` join remaining items with spaces
> 1 votes

# Answer
# Fortran, 113 bytes

Try it Online!

```
character(99)S;read(*,'(A)')S;S='"'//trim(adjustl(S))//'"'
do i=1,99;if(S(i:i+1)>'  ')call fput(S(i:i));enddo;end

```

Per wikibooks, "*It should be remembered that Fortran is designed for scientific computing and is probably not a good choice for writing a new word processor.*"

Fortran doesn't have a regex concept either. This just makes string challenges more interesting!

In this solution, we trim the string `S`, then iterate over it. Print each character unless it's a space followed by another space.

Previously: ~~127 bytes~~, ~~147 bytes~~
> 1 votes

# Answer
# Nim, 72 bytes

```
import strutils
echo'"',stdin.readAll[1..^2].splitWhitespace.join" ",'"'

```

Try it online!

Ignoring the IO restrictions as many answers do, **58 bytes**:

```
import strutils
echo stdin.readAll.splitWhitespace.join" "

```

Try it online!
> 1 votes

# Answer
# C (gcc), 82 bytes

```
char*s=&s+9;main(t){for(gets(s);*s;s++)*s>32|(s[1]>32&&s[2]&&t)&&putchar(*s,--t);}

```

Try it online!
> 1 votes

# Answer
# ARBLE, 26 bytes

```
join(explode(s,"%S+")," ")

```

`explode` groups by non-spaces, and then `join` re-concatenates them.

Try it online!
> 1 votes

# Answer
# Thunno 2, 4 bytes

```
OðjṘ

```

Try it online!

#### Explanation

```
OðjṘ  # Implicit input
      # Implicit eval to
      # remove the quotes
O     # Split on spaces
 ðj   # Join on spaces
   Ṙ  # Repr (surround
      # by quotes)
      # Implicit output

```
> 1 votes

# Answer
# golfua, 42 bytes

```
L=I.r():g('%s*\"%s*','"'):g('%s+',' ')w(L)

```

Simple pattern matching replacement: find any double quotes (`\"`) surrounded by 0 or more spaces (`%s*`) & return the single quote, then replace all 1 or more spaces (`%s+`) with a single space.

A Lua equivalent would be

```
Line = io.read()
NoSpaceQuotes = Line:gsub('%s*\"%s*', '"')
NoExtraSpaces = NoSpaceQuotes:gsub('%s+', ' ')
print(NoExtraSpaces)

```
> 0 votes

# Answer
# Cobra - 68

As an anonymous function:

```
do
    print'"[(for s in Console.readLine.split where''<s).join(' ')]"'

```
> 0 votes

# Answer
**Objective-C 215**

```
-(NSString*)q:(NSString*)s{NSArray*a=[s componentsSeparatedByString:@" "];NSMutableString*m=[NSMutableString new];for(NSString*w in a){if(w.length){[m appendFormat:@"%@ ",w];}}return[m substringToIndex:m.length-1];}

```

Uncompressed version:

```
-(NSString*)q:(NSString*)s{
    NSArray *a=[s componentsSeparatedByString:@" "];
    NSMutableString *m=[NSMutableString new];
    for (NSString *w in a) {
        if (w.length) {
            [m appendFormat:@"%@ ",w];
        }
    }
    return[m substringToIndex:m.length-1];
}

```
> 0 votes

# Answer
Bash ,14 bytes

```
read f;echo $f       # assume f="this  is  a    string   "

```
> 0 votes

# Answer
# Python2, 28 Bytes

```
lambda s:" ".join(s.split())

```

---

## Explanation

```
lambda s

```

Anonymous function which takes as input s.

```
s.split()

```

Returns a list of the words (which are separated by arbitrary strings of whitespace characters) of the string s.

```
" ".join(...)

```

Joins list back into a string, with each word separated by a space (" ").
> 0 votes

# Answer
# k4, 23 bytes

```
" "/:x@&~~#:'x:" "\:0:0

```

---

```
                    0:0  / read from stdin
             x:" "\:     / split string on spaces and assign to x
        ~~#:'            / boolean true where string len>0, bool false otherwise
     x@&                 / x at indices where true
" "/:                    / join with spaces

```
> 0 votes

# Answer
# Wren, 56 bytes

Wait. The replace only does it *once*? Now I have to use the split-join combo.

```
Fn.new{|x|x.trim().split(" ").where{|i|i!=""}.join(" ")}

```

Try it online!

## Explanation

```
Fn.new{|x|                                             } // New anonymous function with the operand x
          x.trim()                                       // Trim out whitespace from both sides of the string
                  .split(" ")                            // Split the string into space-separated chunks
                             .where{|i|i!=""}            // Keep all of those that aren't the null string (due to two consecutive spaces)
                                             .join(" ")  // Join the replaced list together

```
> 0 votes

# Answer
# Husk, 5 bytes

```
sJ' w

```

Try it online!

Fully ascii!

## Explanation

```
sJ' w
    w split into words
 J'   join with spaces
s     add quotes

```
> 0 votes

# Answer
# Python 3, 37 bytes

```
print("%r"%' '.join(input().split()))

```

Based of user12205's python2 answer. I've replaced the %s with a %r so that single quotes are printed around the string automatically.

Try it online!
> 0 votes

# Answer
# Factor, 23 bytes

```
[ [ 32 = ] " "compact ]

```

Try it online!

Factor has a combinator called `compact` that does this. From the documentation:

> Generate a new sequence where all runs of elements for which the predicate returns true are replaced by a single instance of *elt*. Runs at the beginning or end of the sequence for which the predicate returns true are removed.
> 0 votes

# Answer
# Alice, 31 bytes

```
/ot!h';$ !Q'w!/
@Mq!"~K'.% >]]\

```

Try it online!

```
Mt!h~;' %Qw]!]' !.$K'"!qo@  Flattened, without flow characters
M                           Read an argument, push it on the stack
 t!h~;                      Remove the leading and trailing quote, write one of them on the tape
      '                     Adds a space on the stack
        %                   Pop the space, pop the argument, split the argument by space and push all of them words on the stack
         Q                  Reverse the stack
          w      .$K        While the stack is not empty
           ]                Go to the end of the tape
            !]              Pop a word from the stack, write to the tape, go to the end of the tape
              ' !           Add a space on the stack
                    '"!     Write a quote on the tape, overwriting the last space
                       q    Concatenate the content of the tape, word and spaces, push the result on the stack
                        o   Pop, output the concatenated result
                         @  Bye

```
> 0 votes

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


title: Find the Squarish Root

text:
# Question
Title: Find the Squarish Root
Write code that when given a positive number \\$x\\$ as input, outputs the largest positive divisor of \\$x\\$ less than or equal to the square root of \\$x\\$.

In other words find the largest \\$n \> 0\\$ such that

\\$\exists m\geq n:m\cdot n=x\\$

<sup>(Exists \\$m\\$ greater than or equal to \\$n\\$ such that \\$m\\$ times \\$n\\$ is \\$x\\$)</sup>

---

For example if the input were \\$12\\$ the divisors are \\$1\\$, \\$2\\$, \\$3\\$, \\$4\\$, \\$6\\$, and \\$12\\$. \\$1\\$, \\$2\\$ and \\$3\\$ all multiply by larger numbers to get \\$12\\$, but \\$3\\$ is the largest so we return \\$3\\$.

---

This is so answers will be scored in bytes with fewer bytes being considered a better score.

## Test Cases

```
(1,1)
(2,1)
(3,1)
(4,2)
(5,1)
(6,2)
(7,1)
(8,2)
(9,3)
(10,2)
(11,1)
(12,3)
(13,1)
(14,2)
(15,3)
(16,4)
(17,1)
(18,3)
(19,1)
(20,4)
(21,3)
(22,2)
(23,1)
(24,4)
(25,5)
(26,2)
(27,3)
(28,4)
(29,1)
(30,5)
(31,1)
(32,4)
(33,3)
(34,2)
(35,5)
(36,6)
(37,1)
(38,2)
(39,3)
(40,5)
(41,1)
(42,6)
(43,1)
(44,4)
(45,5)
(46,2)
(47,1)
(48,6)
(49,7)
(50,5)

```

OEIS A033676

# Answer
> 11 votes
# Python3, 49 47 bytes

```
def f(x):
 l=x**.5//1
 while x%l:l-=1
 return l

```

# Explanation

* `l=x**.5//1` → Assign `l` the largest integer less than equal to the square root of `x`
* `while x%l:l-=1` → While `l` does not evenly divide `x`, decrement `l`.

### Edits

* Mention Python3, not Python2
* Use `...//1` to save two bytes. (Decimals are okay! Thanks @Rod)

# Answer
> 8 votes
# MATL, 7 bytes

```
Z\tn2/)

```

Try it online!

For this explanation, we will use '12' as a sample input. Explanation:

```
Z\      % Divisors.
        % Stack:
        %   [1 2 3 4 6 12]
  t     % Duplicate.
        % Stack:
        %   [1 2 3 4 6 12]
        %   [1 2 3 4 6 12]
   n    % Number of elements.
        % Stack:
        %   6
        %   [1 2 3 4 6 12]
    2/  % Divide by 2
        % Stack:
        %   3
        %   [1 2 3 4 6 12]
      ) % Index (grab the 3rd element)
        % 3

```

This works because of a lot of lucky coincidences.

1. MATL uses 1 indexing
2. If we index with a non-integer (this will happen for any perfect square input), then `<n>)` will index \\$\lceil n \rceil\\$

# Answer
> 7 votes
# C (gcc) `-lm`, 35 bytes

```
i;f(n){for(i=sqrt(n);n%i;i--);n=i;}

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 5 bytes

```
Ñ2äнθ

```

Try it online! or as a Test suite

**Explanation**

```
Ñ        # push the list of divisors
 2ä      # split it into 2 parts
   н     # take the first haft
    θ    # take the last element of that

```

# Answer
> 5 votes
# APL (Dyalog Unicode), ~~16~~ ~~14~~ 12 bytes

I'm glad I was able to write some answer in APL since I only just learned it. Many, many thanks to Adám for help with golfing. Golfing suggestions very much welcome. Try it online!

To learn more about APL, take a look at The APL Orchard.

**EDIT:** -2 bytes to fixing a problem with my code. Thanks to H.PWiz for pointing out that problem. -2 bytes from shortening everything again.

```
⌈/{⍳⌊⍵*÷2}∨⊢

```

**Ungolfing**

```
⌈/{⍳⌊⍵*÷2}∨⊢
          ∨   GCD of the following...
           ⊢    The right argument, our input.
  {⍳⌊⍵*÷2}
     ⍵            Our input.
      *÷2         To the power of 1/2, i.e. square root.
    ⌊             Floor.
   ⍳              Indices up to floor(sqrt(input)).
                In total, range from 1 to floor(sqrt(input)).
⌈/            The maximum of the GCDs of our input with the above range.

```

# Answer
> 4 votes
# Husk, 4 bytes

```
→←½Ḋ

```

Try it online!

### Explanation

```
→←½Ḋ
   Ḋ      Divisors of (implicit) input.
  ½       Bisect.
→←        Take the last element of the first half.

```

# Answer
> 3 votes
# , ~~45~~ 33 bytes

```
function(x,y=1:x^.5)max(y[!x%%y])

```

Try it online!

Original:

```
function(x,y=x/1:x^.5)max(which(y==floor(y)))

```

Try it online!

# Answer
> 3 votes
# x86 32-bit (IA32) machine code: ~~18~~ 16 bytes

changelog: handle the `n=1` test case correctly, save 2 bytes, and return in EAX.

**Count up until `n/i <= i` (i.e. when we reach the sqrt), and use the first exact divisor after that.**

A 64-bit version of this is callable from C with the x86-64 System V calling convention, as
`int squarish_root_countup(int edi)`.

`nasm -felf32 -l/dev/stdout squarish-root.asm`:

```
58                         DEF(squarish_root_countup)
59                             ; input: n in EDI
60                             ; output: EAX
61                             ; clobbers: eax,ecx,edx
62                         .start:
63 00000025 31C9               xor    ecx, ecx
64                         .loop:                    ; do{
65
66 00000027 41                 inc    ecx                ; ++i
67 00000028 89F8               mov    eax, edi
68 0000002A 99                 cdq
69 0000002B F7F9               idiv   ecx                ; edx=n%i    eax=n/i
70
71 0000002D 39C1               cmp    ecx, eax
72 0000002F 7CF6               jl     .loop          ; }while(i < n/i
73                                                   ;          || n%i != 0);  // checked below
74                             ; falls through for i >= sqrt(n)
75                             ; so quotient <= sqrt(n) if we get here
76
77                                                   ; test edx,edx / jnz  .loop
78 00000031 4A                 dec    edx            ; edx-1 is negative only if edx was zero to start with
79 00000032 7DF3               jge   .loop           ; }while(n%i >= 1);
80                             ; falls through for exact divisors
81
82                             ; return value = quotient in EAX
83
84 00000034 C3                 ret

           0x10 bytes = 16 bytes.

85 00000035 10             .size: db $ - .start

```

Try it online! with an asm caller that uses the first byte of argv\[1\] as an integer directly, and uses the result as process exit status.

```
$ asm-link -m32 -Gd squarish-root.asm &&
for i in {0..2}{{0..9},{a..f}};do
    printf "%d   " "0x$i"; ./squarish-root "$(printf '%b' '\x'$i)"; echo $?;
done

0   0  # bash: warning: command substitution: ignored null byte in input
1   1
2   1
3   1
4   2
5   1
6   2
7   1
8   2
9   3
10   0       # this is a testing glitch: bash ate the newline so we got an empty string.  Actual result is 2 for n=10
11   1
12   3
13   1
14   2
15   3
16   4
   ...

```

# Answer
> 2 votes
# Japt `-h`, ~~8~~ 6 bytes

```
â f§U¬

```

Try it

2 bytes saved thanks to Oliver

---

## Explanation

```
           :Implicit input of integer U
â          :Divisors of U
  f        :Filter
   §       :  Less than or equal to
    U¬     :  Square root of U
           :Implicitly get the last element in the array and output it

```

# Answer
> 2 votes
# JavaScript ES7, ~~33~~ 31 bytes

```
n=>(g=x=>n%x?g(x-1):x)(n**.5|0)

```

Try it online

# Answer
> 2 votes
# Jelly, 5 bytes

```
ọⱮ½TṪ

```

Try it online!

# Answer
> 2 votes
# Snowman, 38 bytes

```
((}1vn2nD`#nPnF|:|NdE|;:,#NMo*|,;bW*))

```

Try it online!

```
((
  }        activate variables b, e, and g
  1vn2nD`  e=1/2
  #        retrieve the input into b
  nP       set b=b^e, which is sqrt(input)
  nF       floor the square root
  |        move b into g so there's space for a while loop
  :        body of the loop
    |NdE|  decrement the value in g
  ;:       loop condition
    ,#     assign b=input, e=current value
    NMo    store the modulo in g
    *|     discard the input value and place the modulo in the condition slot
    ,      put the current value back into g
  ;bW      continue looping while the modulo is nonzero
  *        return the result
))

```

# Answer
> 2 votes
# dc, 24

```
?dsnv1+[1-dlnr%0<m]dsmxp

```

Try it online!

### Explanation:

```
?                         # read input
 d                        # duplicate
  sn                      # store copy 1 in register n
    v                     # take the square root of copy 2
     1+                   # add 1
       [          ]       # define macro to:
        1-                #   subtract 1
          d               #   duplicate
           ln             #   load from register n
             r            #   reverse top 2 stack members
              %           #   calculate modulo
               0<m        #   if not 0, recursively call macro m again
                   d      # duplicate macro
                    sm    # store copy 1 in register m
                      x   # execute copy 2
                       p  # print final value

```

# Answer
> 2 votes
# J, 24 19 bytes

*-5 bytes thanks to Sherlock's GCD idea*

```
([:>./+.)1+i.@<.@%:

```

Try it online!

# original answer

```
([:{:]#~0=]|[)1+i.@<.@%:

```

Try it online!

## parsed

```
┌───────────────────────────────┬──────────────────────┐
│┌──┬──┬───────────────────────┐│┌─┬─┬────────────────┐│
││[:│{:│┌─┬─────┬─────────────┐│││1│+│┌─────────┬─┬──┐││
││  │  ││]│┌─┬─┐│┌─┬─┬───────┐││││ │ ││┌──┬─┬──┐│@│%:│││
││  │  ││ ││#│~│││0│=│┌─┬─┬─┐│││││ │ │││i.│@│<.││ │  │││
││  │  ││ │└─┴─┘││ │ ││]│|│[││││││ │ ││└──┴─┴──┘│ │  │││
││  │  ││ │     ││ │ │└─┴─┴─┘│││││ │ │└─────────┴─┴──┘││
││  │  ││ │     │└─┴─┴───────┘│││└─┴─┴────────────────┘│
││  │  │└─┴─────┴─────────────┘││                      │
│└──┴──┴───────────────────────┘│                      │
└───────────────────────────────┴──────────────────────┘

```

## explanation

* `1 + i.@<.@%:` gives the range `1 .. floor(sqrt)`.
* the entire verb `(A) B` forms a hook, with the above range passed as the right arg `]` to A and the original number passed as its left arg `[`. Thus...
* `] | [` gives the remainer of each item in the range divided into the original arg.
* and `0 = ] | [` gives the divisors with no remainder.
* `] #~ ...` then filters the range, leaving only those.
* and `{:` gives the last item in the list, ie, the largest one.

# Answer
> 2 votes
# Python 2, 41 bytes

```
n=k=input()
while(k*k>n)+n%k:k-=1
print k

```

Try it online!

# Answer
> 2 votes
# Vyxal `G`, 5 bytes

```
K'?√≤

```

Try it online, or see a flagless MATL port.

Explanation:

```
K      # Factors
 '     # Filter by:
   √   #   Square root of
  ?    #   The input
    ≤  #   Is less than or equal to the input
       # Get the greatest item with the G flag

```

# Answer
> 1 votes
# Jelly, 5 bytes

```
½ḍƇµṪ

```

Try it online!

# Answer
> 1 votes
# Haskell, 36 bytes

```
f x=[z|y<-[1..],z<-[1..y],y*z==x]!!0

```

Try it online!

Well this is my answer to this challenge. This uses a particular list comprehension to find the answer. In our list comprehension we pick \\$y\\$ from the infinite list `[1..]` that is the positive integers, and we pick \\$z\\$ from the list `[1..y]`. This means that \\$(y,z)\\$ is all the ordered pairs such that \\$y \geq z\\$.

We then select only those pairs such that \\$y\cdot z=x\\$, meaning that we make the list of all pairs of numbers that multiply to \\$x\\$. Now since our comprehension is based first on \\$y\\$ and then \\$z\\$ this means that our pairs are in ascending order of \\$y\\$, or more usefully in descending order of \\$z\\$.

So to get the largest \\$z\\$ we take the \\$z\\$ belonging to the first element. This is our result.

# Answer
> 1 votes
## QBasic (4.5), 52 bytes

```
INPUT x
FOR i=1TO sqr(x)
if x/i=x\i then m=i
next
?m

```

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

The shortest way seems to be using the floating point stack and `fsqrt`, the shortest I could get without it was 62 bytes using `/mod` and checking if the quotient was greater than the divisor.

```
: f dup s>f fsqrt f>s 1+ begin 1- 2dup mod 0= until ;

```

Try it online!

### Explanation

1. Calculate the square root
2. Starting at the square root, decrement by 1 until we find a factor of the original number

### Code Explanation

```
: f                \ Start a word definition
dup                \ duplicate the input
s>f fsqrt          \ move the number to the float stack and get the square root
f>s                \ truncate result and move to integer stack
1+                 \ add 1 to the square root
begin              \ start indefinite loop
  1- 2dup          \ decrement divisor and duplicate input and divisor
  mod              \ calculate n % divisor
0= until           \ if result equals 0 (no remainder) end the loop
;                  \ end the word definition

```

# Answer
> 1 votes
# F#, 55 49 bytes

```
let f x=Seq.findBack(fun i->x%i=0.0){1.0..x**0.5}

```

Try it online!

`Seq.findBack`: Returns the last element for which the given function returns `True`. The function in this case checks to see if a number is a factor of the value.

# Answer
> 1 votes
# Brain-Flak, 144 bytes

```
{({}{}<<>({}<>)<>([({})()]<>({}(<>)())){(<{}({}[()]{}<({}())>)>)}{}((({}<>)<>(({})))[({}[{}])])>[({<({}[()])><>({})<>}{}<><{}>)])}{}{}<>{}({}<>)

```

Try it online!

I'm not really sure this answer is very good. I feel like there may be a nice way to solve this task however I'm just not clever enough.

## Explanation

I tried to do an exploded view of the answer but there are so many moving parts it was not very enlightening, so here is an explanation of what the code does.

The first important bit is this

```
({}<>)<>([({})()]<>({}(<>)())){(<{}({}[()]{}<({}())>)>)}{}

```

This takes the two numbers on top of the stack and if they are unequal increments the second one, if they are equal it increments the first one and replaces the second one with zero. If we repeat this code a bunch we will get all the pairs \\$(x,y)\\$ such that \\$x \geq y\\$.

The next part is multiplication, taken with modification from the wiki. This multiplication is special because it preserves the existing values without destroying them. It goes like:

```
((({}<>)<>(({})))[({}[{}])])({<({}[()])><>({})<>}{}<><{}>)

```

So we are multiplying all these ordered pairs. For each result we check if it is equal to the input. If so we terminate and return the smaller item in the pair.

# Answer
> 0 votes
# Jelly, 6 bytes

```
ÆDŒHḢṪ

```

Try it online!

# Answer
> 0 votes
# Perl 5 `-p`, 26 bytes

```
$\=0|sqrt;$\--while$_%$\}{

```

Try it online!

# Answer
> 0 votes
# Rust, 71 70 bytes

```
fn f(x:u64)->u64{let mut l=(x as f64).sqrt()as u64;while x%l>0{l-=1}l}

```

## Pre-uglified version

```
fn f(x: u64) -> u64 {                    // function takes u64, gives u64
  let mut l = (x as f64).sqrt() as u64;  // l takes integer'ed root value
  while x % l > 0 {                      // loop while l leaves remainder
    l -= 1                               // decrement
  }
  l                                      // return the found value
}

```

### Edits

* Save a byte with `> 0` over `!= 0`. (Thanks to @CatWizard)

# Answer
> 0 votes
# Japt, 8 bytes

```
â w æ§Uq

```

Try it online!

# Answer
> 0 votes
# Triangularity, 49 bytes

```
....)....
...@_)...
..IEdF)..
.2)1/)IE.
^>{m.....

```

Try it online!

# Answer
> 0 votes
# Pyret, 93 bytes

```
{(z):rec f={(i,x):if num-modulo(i, x) == 0:x else:f(i,x - 1)end}
f(z,num-floor(num-sqrt(z)))}

```

You can try this online by copying it into the online Pyret editor!

The above evaluates to an anonymous function. When it is applied to an integer, it returns a result according to the specification.

# Answer
> 0 votes
# Actually, 7 bytes

Based on my APL answer here. Golfing suggestions welcome! Try it online!

```
;√LR♀gM

```

**Ungolfing**

```
;√LR♀gM  Implicit input n
;        Duplicate n
 √       sqrt(n)
  L      floor(sqrt(n))
   R     1..floor(sqrt(n))
    ♀g   gcd(n, foreach(1..floor(sqrt(n)))
      M  The maximum of the GCDs.
         Return this maximum.

```

# Answer
> 0 votes
A port of this Mathematica answer.

# Jelly, 11 bytes

```
½ðḞ³÷Ċ³÷µÐL

```

Try it online!

This (11 bytes) also works, and don't depend on `³`:

```
½Ḟ÷@Ċ÷@ʋƬµṪ

```

Unfortunately `½Ḟ÷@Ċ÷@ʋÐL` (10 bytes) doesn't work. And apparently `Ƭ` and `ÐĿ` is not exactly the same (when the link is dyadic)

---

Method: (let \\$n\\$ be the input)

* Start with an upper bound \\$i = \sqrt n\\$ of the answer \\$a\\$.
* At each step:
    + If \\$i\\$ is not an integer, then the upper bound can be made \\$\lfloor i\rfloor\\$ (because the result must be an integer)
    + If \\$n\over i\\$ is not an integer, then \\$a \le i \Rightarrow \frac n a \ge \frac n i \Rightarrow \frac n a \ge \lceil \frac n i \rceil \Rightarrow a \le n \div \lceil \frac n i \rceil \\$.
* So we repeatedly replace \\$i\\$ with \\$n \div \lceil \frac n {\lfloor i\rfloor} \rceil\\$ until it's fixed.

# Answer
> 0 votes
# Java 8, ~~65~~ 54 bytes

```
n->{int r=(int)Math.sqrt(n);for(;n%r>0;r--);return r;}

```

Port of *@hunteke*'s Python 3 answer.

Try it online.

---

**Old 65 bytes answer:**

```
n->{int r=1,i=n;for(;i-->1;)r=n%i<1&n/i<=i&n/i>r?n/i:r;return r;}

```

Try it online.

**Explanation:**

```
n->{                // Method with integer as both parameter and return-type
  int r=1,          //  Result-integer, starting at 1
  i=n;for(;i-->1;)  //  Loop `i` in the range (n, 1]
    r=n%i<1         //   If `n` is divisible by `i`,
      &n/i<=i       //   and if `n` divided by `i` is smaller than or equal to `i` itself,
      &n/i>r?       //   and if `n` divided by `i` is larger than the current `r`
       n/i          //    Set `n` divided by `i` as the new result `r`
      :             //   Else:
       r;           //    Leave result `r` unchanged
  return r;}        //  Return the result `r`

```

# Answer
> 0 votes
# Pari/GP, 25 bytes

```
n->(d=divisors(n))[#d\/2]

```

Try it online!

# Answer
> 0 votes
# Ruby, 35 bytes

```
->n,i=n{i-=1until(i*i<=n&&n%i<1);i}

```

Try it online!

# Answer
> 0 votes
# Julia 0.6, 26 bytes

```
x->(r=1:√x)[x%r.<1][end]

```

Try it online!

`r=1:√x` generates the list of integers upto (and possibly including) √x. From those, select values for which `x%r` is 0 i.e. values which divide x. From those, select the last value.

# Answer
> 0 votes
# Rust, 52 bytes

```
|x|(1..=(x as f64).sqrt()as _).rev().find(|l|x%l==0)

```

Try it online!

# Answer
> 0 votes
# Thunno 2 `ht`, 3 bytes

```
F2Ẇ

```

Try it online!

#### Explanation

```
       # Implicit input

F      # All factors of the input
       #   12 -> [1,2,3,4,6,12]
       #   15 -> [1,3,5,15]
       #   25 -> [1,5,25]

 2Ẇ    # Split into 2 (left-bias)
       #   12 -> [[1,2,3],[4,6,12]]
       #   15 -> [[1,3],[5,15]]
       #   25 -> [[1,5],[25]]

   h   # Take the first item
       #   12 -> [1,2,3]
       #   15 -> [1,3]
       #   25 -> [1,5]

    t  # Take the last item
       #   12 -> 3
       #   15 -> 3
       #   25 -> 5

       # Implicit output

```

---
Tags: code-golf, math, number, factoring
---


title: Reverse hex cipher

text:
# Question
Title: Reverse hex cipher
Characters in strings are sometimes represented as their ASCII hexadecimal codes. Printable characters have two hex digits in their representation. Swapping those digits leads to another character, which will be our output.

The table of relevant character codes can be found on Wikipedia.

## Details

1. Take a string as input.
2. For each character:
    1. Find corresponding hex value of ASCII code.
    2. Swap (reverse) the hex digits.
    3. Convert back to character.
3. Output the new string.

## Rules

* To make thinks easier, let's consider only characters "reversible" within standard printable ASCII range - that is codepoints (in hex): `22-27,32-37,42-47,52-57,62-67,72-77` or characters: `"#$%&'234567BCDEFGRSTUVWbcdefgrstuvw`.
* Input and output should be strings or closest equivalent in your language of choice.
* You may assume the input is non-empty.
* This is , the usual rules apply.

## Example

```
input: debug
hex codes: 64 65 62 75 67
reversed: 46 56 26 57 76
output: FV&Wv

```

## Test cases

```
bcd <-> &6F
234 <-> #3C
screw <-> 76'Vw
debug <-> FV&Wv
BEEF <-> $TTd
7W66V77 <-> success
"#$%&'234567BCDEFGRSTUVWbcdefgrstuvw <-> "2BRbr#3CScs$4DTdt%5EUeu&6FVfv'7GWgw

```

# Answer
> 13 votes
# Vyxal `s`, 5 bytes

```
CHRHC

```

Try it Online!

Look ma, no unicode, and it's a palindrome!

```
C   C # To charcodes...
 H H  # To hexadecimal versions of charcodes
  R   # Reverse each
      # (s flag transforms output into string)

```

# Answer
> 10 votes
# Ruby, 26 bytes

Accepts input from STDIN.

```
$<.bytes{|c|putc c*257>>4}

```

Try it online!

Alternative 26s:

```
$<.bytes{|c|putc c*16%255}
$<.bytes{|c|putc c*16.065} # was discovered by @Arnauld

```

# Ruby, 28 bytes

```
->s{s.unpack('H*').pack'h*'}

```

Try it online!

# Answer
> 8 votes
# Python 3, ~~55~~ 54 bytes

```
lambda x:''.join(chr(c%16*16|c>>4)for c in map(ord,x))

```

Try it online!

Can be shorter if bytestrings are permitted:

# Python 3, 38 bytes

```
lambda x:bytes(c%16*16|c>>4for c in x)

```

Try it online!

# Answer
> 6 votes
# APL (dzaima/APL), ~~14~~ 13 bytes

−1 thanks to Unrelated String

Anonymous tacit prefix function.

```
⊖⍢(0 16⊤⎕UCS)

```

Try it online!

flip…

`⍢(``)` while argument is represented as…

`0 16⊤`… two-digit hexadecimal representation of…

`⎕UCS` Universal Character Set code points

# Answer
> 5 votes
# JavaScript (Node.js),  ~~33~~  32 bytes

*Saved 1 byte thanks to @dingledooper*

```
s=>Buffer(s).map(n=>n*257>>4)+''

```

Try it online!

### How?

When `map`'ing over a `Buffer`, the updated values are implicitly truncated to bytes, so we can just do `n * 257 >> 4` without worrying about the upper nibble.

# Answer
> 5 votes
# Perl 5 \+ `-p`, 22 bytes

A port of @dingledooper's second Ruby answer.

```
$_=pack'h*',unpack'H*'

```

Try it online!

# Answer
> 5 votes
# sh + coreutils, 34 bytes

```
xxd -p|tr -d \\n|rev|xxd -r -p|rev

```

Try it online!

# Answer
> 4 votes
# Husk, 11 bytes

```
m(cB16↔B16c

```

Try it online!

`m`ap `(` `c`haracters of `B`ase-16 values of =reverse of `B`ase-16 representation of `c`haracter codes of the input.

# Answer
> 4 votes
# GeoGebra, 107 bytes

```
s=""
InputBox(s)
UnicodeToText(Zip(FromBase(Sum(Reverse(Split(ToBase(a,16),{""}))),16),a,TextToUnicode(s)))

```

To enter this code into GeoGebra, copy/paste in one line at a time and press enter to go to a new line. Do not copy paste directly; it won't work.

Input goes in the Input Box. It was a bit of a challenge to get this working, as GeoGebra has a pretty limited set of tools for working with strings.

Try It On GeoGebra!

### Explanation

`Zip(...,a,TextToUnicode(s))`: For every integer element `a` in the list of char codes of each character in the input string `s`:

```
FromBase(Sum(Reverse(Split(ToBase(a,16),{""}))),16)
                           ToBase(a,16)                Convert a to a base 16 string
                     Split(            ,{""})          Split the string into a list of characters
             Reverse(                        )         Reverse the list
         Sum(                                 )        Concatenate the characters into a string
FromBase(                                      ,16)    Convert the base 16 string back to base 10

```

`UnicodeToText(...)`: Convert the list of char codes back to a string

# Answer
> 4 votes
# Retina 0.8.2, 33 bytes

```
T`#-'4-7E-GVWgvuet\dTscSCrbRB2`Ro

```

Try it online! Link includes test cases. Explanation: `o` substitutes for the transliteration string and `R` reverses it so each listed character gets mapped to the one opposite. Character ranges are used twice to reduce the byte count and once to avoid quoting the `E` but as `d` maps to `F` I can't use character ranges for both `d` and `E`.

# Answer
> 4 votes
# Rust, 49 bytes

```
fn f(s:&mut[u8]){for c in s{*c=c.rotate_left(4)}}

```

Rust doesn't have a string type for plain-ASCII strings, only UTF-8 with enforcement. An SO answer recommends `&[u8]` slices for working with ASCII bytes. I realize this is bending the rules, so I did also find sufficient incantations to get Rust to let me do this to the bytes of an actual `str` primitive type (a slice of which is like a C `char*` \+ length). IDK if there's any shorter way to write this, or a way to use compiler options instead of the `unsafe{}`.

# Rust using `str` strings, 72 bytes

```
fn h(s:&mut str){unsafe{for c in s.as_bytes_mut(){*c=c.rotate_left(4)}}}

```

These could apparently be smaller as closures, but I'm just taking baby steps towards learning some Rust. Suggestions welcome.

Expanding ASCII codes to hex-strings and then swapping pairs is equivalent to rotating the original integer by 4, to swap nibbles. Rust is fun for that because it has as language built-in most of the common things many CPU instructions can do to integers. Instead of needing voodoo that a compiler has pattern-recognize back to a rotate or popcount for portable code to run efficiently. The `u8` docs include all these operations.

These compile to x86-64 asm that rotates the bytes in an array, as you can see on Godbolt. (Note the `rol byte ptr [rcx], 4` in the cleanup loop if the SIMD code isn't easy to follow. (2x shifts and vpternlogd as a bit-blend.) Unfortunately the `-C opt-level=1` asm is rather hard to follow, and the opt-level=2 code vectorizes, so I couldn't get just a simple scalar loop to look at more easily. But I'm just using range-for stuff so I don't have to worry about loop bounds.)

Unlike many languages, Rust does *not* do implicit promotion to wider types for operators like `*`, or even implicit conversion of integer types on assignment. The `*16%255` hack does not save space over `.rotate_left(4)`. I don't know if both sets of `()` are truly necessary around the `as i32` and so on, but I'm pretty sure the `as something` and `as u8` are necessary.

```
fn g(s:&mut[u8]){for c in s{*c=((*c as i32)*16%255) as u8}}

```

# Answer
> 4 votes
# JavaScript (ES6), ~~113~~ ~~107~~ 77 bytes

```
s=>String.fromCharCode(...[...s].map(c=>c.charCodeAt()).map(c=>c%16*16|c>>4))

```

77 bytes if we use Unrelated String's method.

Try it online!

---

107: Slightly better.

```
s=>String.fromCharCode(...[...s].map(c=>parseInt([...c.charCodeAt().toString(16)].reverse().join(''), 16)))

```

Try it online!

---

Original 113 byte answer:

```
s=>[...s].map(c=>String.fromCharCode(parseInt([...c.charCodeAt().toString(16)].reverse().join(''), 16))).join('')

```

Try it online!

This is my first time ever posting here. Obviously not the best solution but I wanted to compete.

# Answer
> 3 votes
# Jelly, 7 bytes

```
⁴ɓObUḅỌ

```

Try it online!

Not a palindrome, but still sounds kind of goofy.

```
  O        Character codes.
   b       Convert to base
⁴ɓ         16,
    U      reverse each,
⁴ɓ   ḅ     convert from base 16,
      Ọ    and convert from character codes.

```

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
ÇhíHçJ

```

Try it online or verify all test cases.

**Explanation:**

```
Ç      # Convert the (implicit) input-string to a list of codepoint integers
 h     # Convert each integer to a hexadecimal string
  í    # Reverse each string in the list
   H   # Convert each string from hexadecimal to a base-10 integer
    ç  # Convert each codepoint-integer to a character
     J # Join them together to a string, since a string I/O that overwrites the
       # default I/O ruling is mandatory for this challenge
       # (after which it is output implicitly as result)

```

# Answer
> 3 votes
# Java 8, ~~116~~ ~~61~~ 57 bytes

```
s->s.chars().forEach(c->System.out.printf("%c",c*16%255))

```

-55 bytes by porting *@UnrelatedString*'s Python answer, so make sure to upvote him/her as well!
-4 bytes thanks to *@dingledooper*

Input as String (which is mandatory according to the rules and overwrites the default rules..), but outputs directly to STDOUT.

Try it online.

**Explanation:**

```
s->                    // Method with String parameter and no return-type
  s.chars().forEach(c->//  Loop over the input-characters as integers:
    System.out.printf( //   Print:
     "%c",             //    Converting a codepoint-integer to character:
     c*16              //     The integer multiplied by 16
         %255))        //     Modulo-255

```

With default I/O rules this could have been 21 bytes, by having the I/O as a stream of codepoint integers: `s->s.map(c->c*16%255)` \- Try it online.

### Original 116 bytes answer:

```
s->s.chars().forEach(c->{var t="".format("%02x",c).split("");System.out.print((char)Long.parseLong(t[1]+t[0],16));})

```

Again input as a String and output directly to STDOUT.

Try it online.

**Explanation:**

```
s->                     // Method with String parameter and no return-type
  s.chars().forEach(c->{//  Loop over the input-characters as integers:
    var t="".format("%02x",c)
                        //   Convert the integer to a hexadecimal string of two hex-digits
          .split("");   //   Convert it to a String-array
    System.out.print(   //   Print:
      (char)            //    Cast a long to character:
        Long.parseLong( //     Convert a string to a long:
          t[1]+t[0],    //      The hex-digits in reversed order
          16));})       //      Converted from base-16 to base-10

```

Some notes:

* It loops over the array as integers with `for(int c:s)` so we can use `c` in the `"".format(...,c)`, instead of as characters with `for(var c:s)` so we would need an explicit cast to integer `(int)c`.
* Although `Long.valueOf` is 2 bytes shorter, it'll return an object `Long`, which requires a cast to `long` before the cast to `char` (`(char)(long)Long.valueOf(...)`). So instead we use `Long.parseLong`, which already returns a primitive `long`.

# Answer
> 3 votes
# MathGolf, 6 bytes

```
Æ$¢x¢$

```

I guess it could be a palindrome by adding a trailing no-op `Æ`. ;)

Try it online.

**Explanation:**

```
Æ       # Loop over the characters of the (implicit) input-string,
        # using five characters as inner code-block:
 $      #  Convert the character to a codepoint-integer
  ¢     #  Convert the integer to a hexadecimal string
   x    #  Reverse it
    ¢   #  Convert it from a hexadecimal string to an integer
     $  #  Convert it from a codepoint-integer to a character
        # (after the loop, implicitly output the entire stack joined together)

```

# Answer
> 3 votes
# Factor, ~~29~~ 23 bytes

```
[ [ 4 8 bitroll ] map ]

```

Try it online!

Roll each code point 4 bits to the left, wrapping around after 8 bits.

# Answer
> 3 votes
# x86 32-bit machine code, 7 bytes

```
C0 02 04 42 E2 FA C3

```

Try it online!

Following the `fastcall` calling convention, this takes the length and address of a string in ECX and EDX, respectively, and modifies the string in place.

In assembly:

```
f:  rol BYTE PTR [edx], 4   # Rotate the character left by 4 bits, swapping its nybbles.
    inc edx     # Add 1 to EDX, advancing the pointer.
    loop f      # Subtract 1 from ECX and jump back if it is nonzero.
    ret         # Return.

```

# Answer
> 3 votes
# C (clang), <sup>~~36~~ \\$\cdots\\$ ~~34~~</sup> 29 bytes

```
f(*s){for(;*s++=*s*16%255;);}

```

Try it online!

*Saved a byte thanks to ovs!!!*
*Saved a byte thanks to Juan Ignacio Díaz!!!*
*Saved 5 bytes thanks to dingledooper!!!*

Inputs a pointer to a wide string.
Returns the reverse hex cipher through the input pointer.

# Answer
> 3 votes
# K (ngn/k), 10 bytes

```
`c$16/|16\

```

Try it online!

* `16\` treating the string input as if it is integers (corresponding to the ASCII codes), convert it to a base-16 representation
* `|` reverse the digits
* `16/` convert back from the base-16 representation
* ``c$` convert back to a character/string format and (implicitly) return

# Answer
> 3 votes
# Fig, \\$8\log\_{256}(96)\approx\\$ 6.585 bytes

```
CmHe$mHC

```

Try it online!

Input as string, output as list of chars.

```
CmHe$mHC
       C # Charcodes
     mH  # To hex
   e$    # Reverse each
 mH      # From hex
C        # To chars

```

# Answer
> 2 votes
# Charcoal, 12 bytes

```
⭆Ｓ℅↨¹⁶⮌↨℅ι¹⁶

```

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

```
 Ｓ              Input string
⭆               Map over characters and join
         ι      Current character
        ℅       ASCII code
       ↨        Convert to base
          ¹⁶    Literal integer `16`
      ⮌         Reversed
   ↨            Convert from base
    ¹⁶          Literal integer `16`
  ℅             ASCII Character
                Implicitly print

```

If both parameters to `Base` are integers then the second is always the base but if one parameter is an array then the other is the base. This allows the two `16`s to be naturally separated in the code thus avoiding an explicit separator.

# Answer
> 2 votes
# , 50 bytes

```
function(s,r=utf8ToInt(s))intToUtf8(16*r%%16+r/16)

```

Try it online!

Much more boring than my previous approach, but 7 bytes shorter.

---

Previous approach:

# , 57 bytes

```
function(s)intToUtf8(t(matrix(0:255,16))[utf8ToInt(s)+1])

```

Try it online!

# Answer
> 2 votes
# Desmos, ~~105~~ 17 bytes

```
f(a)=mod(16a,255)

```

Try it on Desmos!

Input and output are list of codepoints because Desmos doesn't support strings.

# Answer
> 2 votes
# StackCell (u32), 20

`'.[@:'ÿ'␂+*'␐x/'ÿ&;]` ~~(due to an interpreter bug, programs are required to contain valid UTF-8 - the 255 bytes need to be converted to `#FF` to run this, losing two bytes; however, by the language's specification this is a well-formed program - therefore I have not counted the two lost bytes as part of my score; let me know if I need to)~~ I have just fixed this interpreter bug

Explanation:

```
'.[@:'ÿ'␂+*'␐x/'ÿ&;]
'.                   Push a non-null byte (46) to the stack
  [                ] Loop until EOF
   @:                Input a byte (0xXY) and duplicate it
     'ÿ'␂+           Push the bytes 255 and 2 to the stack, and add them together
          *          Multiply the inputted character by 0x101 (-> 0xXYXY)
           '␐x       Push the byte 16 to the stack and swap it below the multiplied character
              /      Divide the character by 16 (-> 0xXYX)
               'ÿ&   Mask the character with 0xFF (-> 0xYX)
                  ;  Print the swapped character

```

# Answer
> 2 votes
# J-uby, 26 bytes

```
~:unpack&'H*'|~:pack&'h*'

```

Try it online!

packing and unpacking turns out to be the same length as the optimal ruby solution.

# J-uby, 37 bytes

```
:bytes|:*&(:*&257|~:>>&4)|~:pack&'c*'

```

Try it online!

# J-uby, 52 bytes

```
:bytes|:*&(~:to_s&16|:reverse|~:to_i&16)|~:pack&'c*'

```

Try it online!

# Answer
> 2 votes
# \>\<\>, ~~22~~ 21 bytes

-1 byte thanks to enigma

```
i:0(?;:a6+,$a6+:@%*+o

```

E'—–GöæÆ–æV

## Explanation

`a6+` is 16. Basically, divide by 16, mod 16, `* 16`, sum up and print.

# Answer
> 1 votes
# Burlesque, 13 bytes

```
m{**b6<-b6L[}

```

Try it online!

```
m{  # Map
 ** # Codepoint
 b6 # To hex
 <- # Reverse
 b6 # From hex
 L[ # To char
}

```

# Answer
> 1 votes
# C (gcc), ~~70~~ ~~66~~ 60 bytes

*-7 bytes thanks to @ceilingcat*

```
main(t,v)char**v;{for(++v;t=**v;++*v)putchar(t>>4|t%16<<4);}

```

Try it online!

# Answer
> 1 votes
# BQN, 17 bytes

```
16(@+⟜⌊÷˜+⊣×|)-⟜@

```

Try it at BQN online REPL

```
               -⟜@   # subtract null character (@) to get ASCII codepoints
16(           )       # now, with this as right arg and 16 as left arg:
             |        # right arg (codepoints) modulo left arg (16)
            ×         # multiplied by
           ⊣          # left arg (16)
          +           # plus
        ÷˜            # right arg (codepoints) divided by left arg (16)
      ⟜⌊              # now use the floor of this
    @+                # to add to null character (@) to get ASCII characters

```

# Answer
> 1 votes
# Red, 39 bytes

```
func[s][foreach c s[prin c * 16 % 255]]

```

Try it online!

Based on other similar answers. Thanks to @dingledooper and @UnrelatedString (I think) for discovering it.

# Answer
> 1 votes
# Knight, 47 bytes

```
;;;;=xP=y""=i~1W<=i+1iLx=y+yA%*16A Gx i 1 255Oy

```

Try it online!

Ungolfed & explained:

```
; = x PROMPT                                               # x = input()
; = y ""                                                   # y = ""
; = i ~1                                                   # i = -1
; WHILE (< (= i (+ 1 i)) (LENGTH x))                       # while (i = i + 1) < length(x):
  : = y (+ y (ASCII (% (* 16 (ASCII (GET x i 1))) 255)))   #   y = y + chr((ord(x[i]) * 16) % 255)
: OUTPUT y                                                 # print(y)

```

# Answer
> 1 votes
# Knight, 32 bytes

```
;=xP:Wx;O+A%*16Ax 255"\"=xGx 1Lx

```

Try it online!

Golfed Steffan's answer to minimize the use of auxiliary variables. `y` is not necessary if we print each char right away; `i` is not necessary since `A` implicitly grabs the 0th char from the current string and we can chop `x` directly.

Ungolfed:

```
; = x P                       x = a line of stdin
: W x                         While x is nonempty:
  ; O + A % * 16 A x 255 "\"    Output chr(ord(x[0]) * 16 % 255) + "\"
                                (to suppress the implicit newline ending)
  : = x G x 1 L x               x = x[1:]

```

If output of each char separated by newline is allowed:

# Knight, 29 bytes

```
;=xP:Wx;O A%*16Ax 255=xGx 1Lx

```

Try it online!

# Answer
> 1 votes
# Pyth, 9 bytes

```
mCi_.Hd16

```

Test suite

Outputs a list of characters.

##### Explanation:

```
mCi_.Hd16  | Full program
mCi_.Hd16Q | with implicit variables
-----------+-----------------------------------
m        Q | For each character d of the input,
    .Hd    |  Convert to hexstring
   _       |  Reverse
  i    16  |  Convert from base 16
 C         |  Convert to character

```

# Answer
> 1 votes
# , 15 bytes

```
[:u:255|16*3&u:

```

Try it online!

# Answer
> 1 votes
# Thunno 2 `B`, 3 bytes

```
ḤṃH

```

Try it online!

#### Explanation

```
ḤṃH  # Implicit input
     # Implicit cast to ordinals
Ḥ    # Convert each to hexadecimal
 ṃ   # Reverse each string
  H  # Convert each from hexadecimal
     # Implicit cast to characters
     # Implicit output

```

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


title: Mathematical Combination

text:
# Question
Title: Mathematical Combination
Write a program that takes an input such as:

```
n,k

```

which then computes:

$$\binom n k = \frac {n!} {k!(n-k)!}$$

and then prints the result.

---

A numerical example:

Input:

```
5,2

```

Internal computation:

$$\frac {5!} {3!\times2!}$$

Printed Output:

```
10

```

---

I'd like to see an answer that beats my python solution of 65 characters, but all languages are obviously welcome.

Here's my solution:

```
n,k=input();f=lambda x:+(x<2)or x*f(x-1);print f(n)/(f(k)*f(n-k))

```

**Edit:**

I admit that this question is from the codegolf website mathematical combination puzzle. I know that my answer may look like not much progress can be made on it, but the leaders of this puzzle have solved it in nearly half as many characters.

# Answer
> 12 votes
## C 96

With I/O (which takes about 34 chars). Added a couple of newlines to make it readable.

```
main(a,b,c,d){scanf("%d,%d",&a,&b);
d=a-b;for(c=1;a>b;){c*=a--;}for(;d;)
{c/=d--;}printf("%d",c);}

```

Now if you'll excuse me, I have an ASCII n choose k rocket to catch.

```
    d;main(a
   ,         b
  ,           c
 )  int        a
 ;   {scanf    (
 (   "%d %d"   )
 ,   &a,  &b   )
 ;   d    =a   -
 b   +     b   -
 b   *     1   ;
 a             -
 a  ;for    (  c
 =  1;a>   b   ;
 )  {c=   c    *
 (  (a-- )     )
 ;  }for(      b
 =  b + 1      ;
 d  ;    )     {
 c  =     c    /
 (  d--    )   ;
  }           {
  }           {
   }         (
  printf("%d",c)
 )      ;       }
/*     *  *   * *\
 * * X   * 8 * * |
|     *      *    \
*/    //       *  */

```

# Answer
> 11 votes
# APL, 3 bytes

```
⎕!⎕

```

Or for those whose browser doesn't render the above, in an ASCII rendering:

```
{Quad}!{Quad}

```

# Answer
> 9 votes
# R (11 Chars)

```
choose(n,r)

```

# Answer
> 7 votes
## GolfScript, 17 chars

This solution handles cases like k=0 or k=1 correctly.

```
~>.,,]{1\{)*}/}//

```

Factorial-like portion is based off a previous answer.

# Answer
> 6 votes
## Ruby 1.9, ~~52~~  46 (42) characters

```
eval"A,B="+gets;i=0;p eval"(A-B+i+=1)/i*"*B+?1

```

If stderr is ignored:

```
eval"A,B=I="+gets;p eval"I/(A-I-=1)*"*B+?1

```

Ruby 1.8, 43 characters, no additional output to stderr:

```
eval"a,b=i="+gets;p eval"i/(a-i-=1)*"*b+"1"

```

Edits:

* (52 -\> 48) Found a shorter way to parse the input
* (48 -\> 46) Less looping, more eval.

# Answer
> 6 votes
# GolfScript 21

```
~~)>.,,]{{)}%{*}*}%~/

```

Not particularly short, GolfScript lacks a real factorial function, however this has got to be the most wicked data manipulation that I have ever done, this calls for a stack trace:

"5,2" Data on the stack from input.
`~` Eval command, note that , is an operator that turns a number into an array.
\[0 1 2 3 4\] 2
`~` Binary not.
\[0 1 2 3 4\] -3
`)` Increment.
\[0 1 2 3 4\] -2
`>` Take end of array, -2 as parameter to get the last 2 elements.
\[3 4\]
`.` Duplicate element.
\[3 4\] \[3 4\]
`,` Array length.
\[3 4\] 2
`,` Turn number to array.
\[3 4\] \[0 1\]
`]` Create array.
\[\[3 4\] \[0 1\]\]
`{{)}%{*}*}` Block of code.
\[\[3 4\] \[0 1\]\] {{)}%{\*}\*}
`%` Execute block once for each element of the array. The following part only demonstrate the first loop.
\[3 4\]
`{)}%` Increment each array element.
\[4 5\]
`{*}` Block containing a multiply command.
\[4 5\] {\*}
`*` "Fold" the array using the block command, that is in this case make the product of all elements.
20
After the big loop has finished it returns an array with the results.
\[20 2\]
`~` Deconstruct the array.
20 2
`/` Division.
10

# Answer
> 4 votes
## Python (56)

```
f=lambda n,k:k<1and 1or f(n-1,k-1)*n/k;print f(*input())

```

Ungolfed code and some explanation of a shortcut for calculating the binomial coefficient. (Note: There is some insight that I just haven't figured out in order to get down to the 39 char version; I don't think this approach will get you there.)

```
# Since choose(n,k) =
#
#     n!/((n-k)!k!)
#
#          [n(n-1)...(n-k+1)][(n-k)...(1)]
#        = -------------------------------
#            [(n-k)...(1)][k(k-1)...(1)]
#
# We can cancel the terms:
#
#     [(n-k)...(1)]
#
# as they appear both on top and bottom, leaving:
#
#    n (n-1)     (n-k+1)
#    - ----- ... -------
#    k (k-1)       (1)
#
# which we might write as:
#
#      choose(n,k) = 1,                      if k = 0
#                  = (n/k)*choose(n-1, k-1), otherwise
#
def choose(n,k):
    if k < 1:
        return 1
    else:
        return choose(n-1, k-1) * n/k

# input() evaluates the string it reads from stdin, so "5,2" becomes
# (5,2) with no further action required on our part.
#
# In the golfed version, we make use of the `*` unpacking operator,
# to unpack the tuple returned by input() directly into the arguments
# of f(), without the need for intermediate variables n, k at all.
#
n, k = input()

# This line is left as an exercise to the reader.
print choose(n, k)

```

# Answer
> 4 votes
## RPL (4)

(using built-in function)

```
COMB

```

# Answer
> 3 votes
## Windows PowerShell, 57

```
$a,$b=iex $input
$p=1
for($a-=$b;$a-ge1){$p*=1+$b/$a--}$p

```

# Answer
> 3 votes
# J, 33 36

```
(":!~/".;._1}:toJ',',1!:1(3))1!:2(4)

```

35 characters are input, parsing and output. The other character, `!`, is n choose k.

I don't have Windows around for testing this at the moment, but I believe it should work there.

# Answer
> 3 votes
# Q, 32 chars

```
{f:{1*/1.+(!)x};f[x]%f[y]*f x-y}

```

# Answer
> 3 votes
# Python 2, 39 bytes

```
n,k=input()
B=2<<n
print(B+1)**n/B**k%B

```

Try it online!

A full program, as the challenge asks for. The method is explained in this tip.

# Answer
> 2 votes
## Perl 6 (55)

```
my ($a,$b)=lines;$_=1;for 1..$a-$b {$_+=$_*$b/$^a};.say

```

# Answer
> 2 votes
## RPL (22)

(not using built-in COMB function)

```
→ n k 'n!/(k!*(n-k)!)'

```

# Answer
> 2 votes
## Q (50 45)

```
 f:{(prd 1.+til x)%((prd 1.+til y)*prd 1.+til x-y)}

```

You can shave a few characters off the above by removing redundant brackets and using 1\*/ instead of prd.

```
f:{(1*/1.+til x)%(1*/1.+til y)*1*/1.+til x-y}

```

# Answer
> 2 votes
# Mathematica 12

Straightforward, built-in function.

```
n~Binomial~k

```

# Answer
> 2 votes
# Perl 6, ~~25~~ 16 bytes

*-9 bytes thanks to nwellnhof*

```
+*o&combinations

```

Try it online!

Anonymous function that takes two numbers and returns an int. This uses the built-in `combinations` and converts the returned list to an int.

# Answer
> 1 votes
## PHP (71 79)

```
<?$a=fgetcsv(STDIN);$x=1;while($a[1]-$i)$x=$x*($a[0]-++$i+1)/$i;echo$x;

```

```
<?php $a=fgetcsv(STDIN);$x=1;while(++$i<=$a[1])$x=$x*($a[0]-$i+1)/$i;echo $x?>

```

# Answer
> 1 votes
# Python (54)

```
f=lambda n,k:k<1or f(n-1,k-1)*n/k;print 1*f(*input())

```

Essentially the same as the Python one above, but I shave off four bytes by dropping the

```
and 1

```

from the function definition. However, this results in the function returning True instead of 1 if k=0, but this can be fixed by multiplying with 1 before printing, since 1\*True=1, thus adding two bytes.

# Answer
> 1 votes
## J, 11 characters

```
!~/".1!:1[1

```

Takes input from the keyboard.

```
    !~/".1!:1[1
5,2
10

```

# Answer
> 1 votes
# Python 3.8 (pre-release), 21 bytes

```
import math
math.comb

```

Try it online!

# Answer
> 1 votes
# Jelly, 1 byte

```
c

```

Try it online!

2 bytes to take input as `n,k`

# Answer
> 1 votes
# Rust, 53 bytes

```
fn f(n:i32,k:i32)->i32{if k<1{1}else{f(n-1,k-1)*n/k}}

```

This is essentially the same as the Python code in some of the previous answers, and computes the binomial coefficient through recursion.

Try it online!

# Answer
> 1 votes
# Go, 58 bytes

```
func b(n,k int)int{if k<1{return 1}
return b(n-1,k-1)*n/k}

```

Attempt This Online!

### Alternative using `math.Gamma()`, 82 bytes

```
import."math"
func b(n,k float64)float64{g:=Gamma
return g(n+1)/(g(k+1)*g(n-k+1))}

```

Attempt This Online!

# Answer
> 0 votes
## Haskell (80)

```
f(_,0)=1
f(n,k)=n/k*f(n-1,k-1)
main=getLine>>=putStr.show.f.read.(++")").('(':)

```

But, if input in the format `x y` is allowed instead of in the format `x,y`, it's 74 chars:

```
f[_,0]=1
f[n,k]=n/k*f[n-1,k-1]
main=interact$show.f.map read.take 2.words

```

# Answer
> 0 votes
### Scala 54

```
val n,k=readInt
((k+1)to n product)/(1 to(n-k)product)

```

# Answer
> 0 votes
# Python (52)

```
 f=lambda n,k:k<1or f(n-1,k-1)*n/k;print+f(*input())

```

Improved from the other two by using `print+` to convert the result of `f` from `boolean` to `int` in case `k==0`.

Still have no idea how to shrink it to 39, I wonder whether they are using lambda at all.

# Answer
> 0 votes
*(The OP only loosely specified the input & output method/format, so the following seems acceptable.)*

## Sage Notebook (~~39 41~~ 40)

In the current cell,

```
f=lambda n,k:k<1or f(n-1,k-1)*n/k;+f(*_)

```

where the input in the form `n,k` is entered & evaluated in the preceding cell. This simulates "command-line input" by assigning it to `_` (similar to command-line arguments).

## Sage Notebook (~~42 44~~ 43)

Alternatively, using "in-source input" (with only the `x=` and newline characters adding to the score), e.g.,

```
x=5,2
f=lambda n,k:k<1or f(n-1,k-1)*n/k;+f(*x)

```

*Both of these approaches are obviously spin-offs from earlier answers by others.*

# Answer
> 0 votes
# Tcl, 80 bytes

```
proc C n\ k {proc f n {expr $n?($n)*\[f $n-1]:1}
expr [f $n]/([f $k]*[f $n-$k])}

```

Try it online!

# Answer
> 0 votes
# Javascript, 27 bytes

First my own 35-byte solutions:

```
f=(n,k)=>n-k&&k?f(--n,k)+f(n,k-1):1

```

Or, alternatively,

```
f=(n,k,i=k)=>i?f(n-1,k-1,i-1)*n/k:1

```

The first working recursively, with the simple `(n,k) = (n-1,k) + (n-1,k-1)` rule. The second using that `(n,k) = (n-1,k-1) * n/k`.

**EDIT**

I just noticed the solution by Arnould in a duplicate of this:

```
f=(n,k)=>k?n*f(n-1,k-1)/k:1

```

Which is a whopping 8 bytes less (27 bytes)

# Answer
> 0 votes
# TI-BASIC, 16 chars (8 bytes)

```
Ans(1) nCr Ans(2

```

Input is a list of length 2 in `Ans`.
Output is the result of the formula defined here.

If the above solution doesn't suffice, then the following **35 chars (24 bytes)** solution also works:

```
Ans(2)!⁻¹(Ans(1)-Ans(2))!⁻¹Ans(1)!

```

---

**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.

# Answer
> 0 votes
# 05AB1E, 1 (or 5?) bytes

```
c

```

Builtins ftw ¯\\\_(ツ)\_/¯

Takes two loose inputs, \\$k\\$ as first and \\$n\\$ as second.

Try it online.

If the `"n,k"` format is mandatory, it would be **5 bytes** instead:

```
',¡`c

```

Try it online.

This will split the (implicit) input on the ","; pop and push both values separated to the stack; and than uses the `a choose b` builtin.

# Answer
> 0 votes
# Excel, 13 chars

```
=COMBIN(A1,B1

```

`A1` is n, `B1` is r. Surprised this wasn't restricted, honestly.

# Answer
> 0 votes
# CJam, 19 bytes

```
l~\_m!@@\_m!@@-m!*/

```

Try it online!

# Answer
> 0 votes
# Japt, 2 bytes

```
àV

```

Try it out here

# Answer
> 0 votes
# Thunno 2, 1 byte

```
c

```

Try it online!

Built-in.

## Thunno 2, 9 bytes

```
w$w÷$$-w÷

```

Try it online!

Non-built-in.

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


title: Append and erase

text:
# Question
Title: Append and erase
Given one line that consists of only letters, process as following:

* You maintain a string that's empty at the beginning.
* If the next input character is in the string, remove it from the string.
* If the next input character isn't in the string, append it to the string.

Output the final state of the string.

You can safely assume the input consists at least one character (i.e. non-empty), but there's no guarantee that the output isn't empty.

Pseudocode (Feel free to golf this):

```
str = EMPTY
for each character ch in input
  if ch exists in str
    remove all ch from str
  else
    append ch to str
print str

```

The input matches the regular expression `^[A-Za-z]+$`.

Sample test cases:

```
ABCDBCCBE -> ADCBE
ABCXYZCABXAYZ -> A
aAABBbAbbB -> aAbB
GG -> (empty)

```

The input can be given in any applicable way, but it must be treated as a string, and the same for output. The program should **not** exit with an error.

The shortest program in each language wins!

**Extra** (Optional): Please explain how your program works. Thank you.

# Answer
# Jelly, 3 bytes

```
œ^/

```

Try it online!

Full program.
> 11 votes

# Answer
# Haskell, ~~44~~ 42 bytes

```
foldl(#)""
s#x|z<-filter(/=x)s=z++[x|z==s]

```

Try it online! *Edit: -2 bytes thanks to Zgarb!*

**Explanation:**

The second line defines a function `(#)` which takes a string `s` and a character `x` and performs either the remove or append. This is achieved by `filter`ing out every occurrence of `x` in `s`, resulting in the string `z`. If `x` does not occur in `s`, then `z` is equal to `s` and `z++[x|z==s]` yields the original string with `x` appended. Otherwise `[x|z==s]` yields the empty string and only the filtered string is returned.

`foldl(#)""` is an anonymous function which takes a string and adds one character after the other the initially empty string `""` with the function `(#)`.
> 10 votes

# Answer
# , 21 19 bytes

```
#~~:&.|.(2|*)1#.=/~

```

How it works:

`=/~` \- makes a table of equality of the characters in the string:

```
   a =. 'ABCXYZCABXAYZ'
   ]b =: =/~ a
1 0 0 0 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 0 0 0 0 0 1
0 0 1 0 0 0 1 0 0 0 0 0 0
1 0 0 0 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 1 0 0 1 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 0 0 0 0 0 1

```

`1#.` \- sum of each row by base 1 conversion (how many times the letter occurs)

```
   ]c =: 1#. b
3 2 2 2 2 2 2 3 2 2 3 2 2

```

`~:&.|` \- reverse, then apply nub sieve (is the char unique) and reverse again. Thus I find the last occurrences of the characters in the string:

```
   ]d =. ~:&.|. a
0 0 0 0 0 0 1 0 1 1 1 1 1

```

`*` \- multiplies the count by 1 for the last position of the character in the sring, by 0 otherwise, computed by the above `~:&.|`

```
   ]e =. c * d
0 0 0 0 0 0 2 0 2 2 3 2 2

```

`2|` \- modulo 2 (sets to 0 the positions of the chars that have even count):

```
   ]f =. 2| e
0 0 0 0 0 0 0 0 0 0 1 0 0

```

`#~` \- copy the right argument left arg. times (~ reverses the places of the args)

`]f # a
A`

Try it online!
> 8 votes

# Answer
# Brainfuck, 95 bytes

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

```

Try It Online

### How It Works

```
, Gets first input
[ Starts loop
    <<< Go to start of string
    [ Loop over the string
        [->+>>>+<<<<] Duplicates the current char of the string
        >>>[-<+<->>] Duplicates and subtracts the inputted char from the duplicate of the string char
        <<[[-]<] If the char is different to the input, remove the difference
        > If the char is the same
        [
            [-]>>[-]>[[-<+>]>]<<[<]<< Remove the char from the string and sets the inputted char to 0
        ]
        << Moves to the next char of the string
    ]
    >>>[->+<] adds the inputted char to the string
    >>[>]>>, gets the next input
]
<<<[.<] prints the string

```
> 6 votes

# Answer
# Haskell, 47 bytes

*Another one bytes the dust thanks to Bruce Forte.*

```
import Data.List
foldl1(\x y->union(x\\y)$y\\x)

```

Try it online!

Takes a list of Strings.

Symmetric difference is annoying...
> 5 votes

# Answer
## Retina, 16 bytes

```
+1`(.)(.*?)\1
$2

```

Try it online!
> 3 votes

# Answer
# MATL, 6 bytes

```
vi"@X~

```

Doesn't work in the TIO environment, but works fine on the MATLAB implementation, and thanks to a fresh patch, you may try it on MATL Online

`X~` equals `setxor`, or symmetric difference, which does exactly what the challenge asks. The rest is just looping over the input `i"@` and starting with an empty string by concatenating the entire stack which is empty at the start (thanks Luis Mendo).
> 3 votes

# Answer
# K (ngn/k), ~~21~~ 9 bytes

```
|&2!#'=|:

```

Try it online!

If a character appears an even number of times in the string, it won't be present in the output. If it appears an odd number of times, only its last instance will remain.

* `#'=|:` count the number of times each distinct character occurs in the string (reversing the order)
* `|&2!` filter down to where the character appears an odd number of times, then reverse
> 3 votes

# Answer
# Python 2, 56 bytes

*-2 bytes thanks to xnor. -3 bytes thanks to ovs.*

```
lambda s:reduce(lambda a,c:a.replace(c,'')+c[c in a:],s)

```

Try it online!

Literally just golfed the pseudocode. :P
> 2 votes

# Answer
# , 38 bytes

```
""{$[y in x;except;,][x;y]}/

```
> 2 votes

# Answer
# , 84 bytes

```
y=el(strsplit(scan(,""),""));cat(unique(y[colSums(outer(y,y,"=="))%%2>0],,T),sep="")

```

Try it online!

Another solution, but there are better  answers here.

# , 88 bytes

```
z=table(y<-el(strsplit(scan(,""),"")));cat(setdiff(unique(y,,T),names(z[!z%%2])),sep="")

```

Try it online!

Thanks to Giuseppe for -7 bytes!

There is a shorter answer by duckmayr.

1. `scan(,"")` read input from stdin.
2. `y<-el(strsplit(scan(,""),""))` split input by characters and save as `y`.
3. `z=table(y<-el(strsplit(scan(,""),"")))` compute frequencies of each character and save resulting table as `z`;
4. `unique(y,,T)` take unique characters from the right side.
5. `names(z[!z%%2])` select only even counts and extract names.
6. `setdiff(unique(y,,T),names(z[!z%%2]))` remove characters with even count.
7. `cat(setdiff(unique(y,,T),names(z[!z%%2])),sep="")` print the output.
> 2 votes

# Answer
# , ~~92~~ ~~84~~ 77 bytes

```
for(i in el(strsplit(scan(,y<-''),y)))y=c(y[y!=i],if(!i%in%y)i);cat(y,sep='')

```

Try it online!

-15 bytes thanks to djhurio

### Explanation

djhurio provided an excellent R answer avoiding a `for` loop -- as R programmers instinctively do as a rule (myself included). Here's an R answer that utilizes a `for` loop (and saves a few bytes in the process).

* `x=scan(,'');` -- assign the input into the variable `x`
* `y='';` -- create an empty string in a variable called `y`
* `for(i in el(strsplit(x,'')))` -- for every character `i` in `x`
* `y=c(y[y!=i],if(!i%in%y)i)` -- assign to `y` every element of `y` that is not equal to `i`, appending `i` if `i` was not already in `y`
* `cat(y,sep='')` -- print the elements of `y` with no space between them

### Note

If you click the TIO link above, you'll find in the header `library(methods)`; this is to deal with the error djhurio experienced regarding the `el()` function -- the function is provided by the `methods` package, which in any version of R I've used, is loaded by default, but for whatever reason isn't by TIO. If `library(methods)` is removed from the header and `unlist` is substituted for `el`, I gain four bytes, but so would djhurio, putting our byte counts at ~~96~~ 88 and 99 respectively.
> 2 votes

# Answer
# JavaScript (ES6), 60 bytes

```
s=>[...s].map(c=>s=s.match(c)?s.split(c).join``:s+c,s='')&&s

```

### Test cases

```
let f =

s=>[...s].map(c=>s=s.match(c)?s.split(c).join``:s+c,s='')&&s

console.log(f("ABCDBCCBE"))     // -> ADCBE
console.log(f("ABCXYZCABXAYZ")) // -> A
console.log(f("aAABBbAbbB"))    // -> aAbB
console.log(f("GG"))            // -> (empty)
```
> 1 votes

# Answer
# APL+WIN, 19 bytes

Logic similar to Galen's J solution.

```
(2|+⌿⌽<\⌽c∘.=c)/c←⎕

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
#//.{a___,x_,b___,x_,c___}:>{a,b,c}&

```

Try it online!

Takes input and output as a list of characters.

## How it works

Uses `//.` (alias `ReplaceRepeated`) to find two repeated characters and delete both, until no more repeated characters exist. If the character occurs more than twice, Mathematica will always delete the first two occurrences. So if a character occurs an odd number of times, its last instance will always be the one to survive.
> 1 votes

# Answer
# Perl 5, 28 + 2 (-pF) = 30 bytes

```
$\=~s/$_//g||($\.=$_)for@F}{

```

Try it online
> 1 votes

# Answer
# Prolog 81 byte

```
a([],O,O).
a([I|J],K,O):-delete(K,I,F),(K=F->append(K,[I],M),a(J,M,O);a(J,F,O)).

```

Non-obfuscated version:

```
append_and_eraze([], Output, Output).
append_and_eraze([I | Input], Interim, Output) :-
    delete(Interim, I, Filtered),
    ( Interim = Filtered ->
      append(Interim, [I], Interim1),
      append_and_eraze(Input, Interim1, Output)
    ;
    append_and_eraze(Input, Filtered, Output)
    ).

```
1. `delete/3` ensures that its third argument unifies with its first argument, with all instances of second argument removed from it.
2. If those turn out to be the same, we append the element (it wasn't removed).
3. `append/3` as per its name, appends an element to list.
4. We recur on the elements of the input until we hit the `[]` (empty list), at which point the intermediate result will unify with desired result.

Test:

```
?- append_and_eraze(`ABCDBCCBE`, [], X), string_codes(Y, X).
X = [65, 68, 67, 66, 69],
Y = "ADCBE".

?- append_and_eraze(`ABCXYZCABXAYZ`, [], X), string_codes(Y, X).
X = [65],
Y = "A".

?- append_and_eraze(`aAABBbAbbB`, [], X), string_codes(Y, X).
X = [97, 65, 98, 66],
Y = "aAbB".

?- append_and_eraze(`GG`, [], X), string_codes(Y, X).
X = [],
Y = "".

```

*Some Prologs treat strings in double quotes as lists, SWI can be configured to do the same, but for the sake of simplicity, I used `string_codes/2` to format output nicely.*
> 1 votes

# Answer
# Japt `-h`, 15 bytes

```
;£A=øX ?AkX:ApX

```

Try it online!
> 1 votes

# Answer
# Scala, ~~75..64~~ 49 bytes

*-22 bytes thanks to user!*

```
_./:("")((?,y)=>if(?toSet y)?filter(y!=)else? +y)

```

Try it online!
> 1 votes

# Answer
## Alice, 9 bytes

```
/X&@
\io/

```

Try it online!

### Explanation

Basically a port of Erik's answer. Apart from a bit of IP redirection the code is really just:

```
i&Xo@

```

which does:

```
i   Read all input.
&X  Fold symmetric multiset difference over the input.
o   Output the result.
@   Terminate.

```
> 0 votes

# Answer
# Ruby, 53 bytes

```
->s{s.reverse.uniq.select{|c|s.count(c)%2>0}.reverse}

```

Try it online!

Input and output are both an array of chars. Test code calls `.chars` and `.join` for convenience.

## Explanation

Uses the fact that the letters in the resulting string appear an odd number of times and in the order from right to left.

```
->s{                # lambda function taking char-array argument
    s.reverse           # reverse the input
    .uniq               # get unique characters
    .select{|c|         # select only those which...
        s.count(c)%2>0      # appear in the input array an odd number of times
    }.reverse           # reverse back and return
}

```
> 0 votes

# Answer
# APL (Dyalog), 16 bytes

```
{(,⍨~∩)/⍣(≢⍵)⊖⍵}

```

Try it online!

If errors were allowed, this would've been 9 bytes:

```
(,⍨~∩)/∘⊖

```
> 0 votes

# Answer
# Pyth, 15 bytes

```
Vz?:kN)=-kN=+kN

```

Try it online!
> 0 votes

# Answer
# Pyth, 13 bytes

```
{_xD_Qf%/QT2Q

```

Takes in input as list of characters. Test it out!

```
      f     Q            (f)ilter input (Q)
        /QT              On how many times (/) each character (T) appears in the
                           input (Q)
       %   2             Only allow odd numbers of occurences (when x % 2 = 1)
 _xD_Q                   Sort (D) descending (the first _) by the location (x) of
                           the last (the second _) inde(x) of the target character
                           in the input (Q)
{                        Remove duplicates

```
> 0 votes

# Answer
# Röda, 34 bytes

```
{a=[]a-=_ if[_1 in a]else a+=_1;a}

```

Try it online!

This is a direct translation of the pseudocode. It treats input and output as streams of characters.

Explanation:

```
{                    /* Anonymous function                   */
    a=[]             /* initialize a                         */
                     /* For each character _1 in the stream: */
    a-=_ if[_1 in a] /*  Remove it from a if a contains it   */
    else a+=_1;      /*  Otherwise append it to a            */
    a                /* Push characters in a to the stream   */
}

```
> 0 votes

# Answer
# Python 3, 73 bytes

Not the shortest, but I like this approach.

```
lambda s:''.join(c*(s.count(c)%2)*(i==s.rfind(c))for i,c in enumerate(s))

```

**Try it online!**

Loops through the string, keeping only those characters where:

* `(s.count(c)%2) == 0` \- The character appears an even number of times.
* `(i==s.rfind(c))` \- The current index is the last appearance of the character in question.
> 0 votes

# Answer
# REXX, 102 bytes

```
a=arg(1)
s=''
do while a>''
  b=right(a,1)
  if countstr(b,a)//2 then s=b||s
  a=changestr(b,a,'')
  end
say s

```

Try it online!

How it works: Take the rightmost letter, see if the number of occurrences is even or odd (which also doubles as a truth value) and if odd, add it to the output string. Then remove all occurrences of the letter from the input string. Repeat until input is depleted.
> 0 votes

# Answer
# Perl 5, 22 + 1 (`-p`) = 23 bytes

```
s/(.)(.*?)\1/$2/&&redo

```

Try it online!
> 0 votes

# Answer
# Java 8, 93 bytes

A lambda from `String` to `String`. Just an implementation of the pseudocode in the question.

```
s->{String o="";for(char c:s.toCharArray())o=o.indexOf(c)<0?o+c:o.replace(c+"","");return o;}

```

Try It Online

# Java 8, 182 bytes

Here's another lambda of the same type that uses streams! It's probably more efficient.

```
s->s.join("",s.chars().mapToObj(c->(char)c+"").filter(c->s.replaceAll("[^"+c+"]","").length()%2>0).distinct().sorted((c,d)->s.lastIndexOf(c)-s.lastIndexOf(d)).toArray(String[]::new))

```

Try It Online

## Ungolfed

```
s ->
    s.join(
        "",
        s.chars()
            .mapToObj(c -> (char) c + "")
            .filter(c -> s.replaceAll("[^" + c + "]", "").length() % 2 < 0)
            .distinct()
            .sorted((c, d) -> s.lastIndexOf(c) - s.lastIndexOf(d))
            .toArray(String[]::new)
    )

```
> 0 votes

# Answer
# , 70 bytes

```
function(s){for(i in utf8ToInt(s))F=c(F[F!=i],i*!i%in%F);intToUtf8(F)}

```

Try it online!

I was encouraged by djhurio to post this solution; djhurio's answer can be found here.

This uses the same idea as duckmayr's answer, but it leverages a numeric approach by converting the string to its codepoints rather than splitting it into characters, and is a function rather than a full program so it can return the new string rather than printing to stdout.

```
function(s) {
 for(i in utf8ToInt(s))           # convert string to codepoints and iterate over it
  F=c(F[F!=i],                    # remove duplicates and append
      i*!i%in%F)                  # 0 if in F, i otherwise
 intToUtf8(F)                     # collapse from codepoints to string
}

```

One important observation is that `F` is initialized to `FALSE` or `0` and `utf8ToInt(0)==""`, so this will succeed for the empty string as well as correctly collapsing the codepoints.
> 0 votes

# Answer
# PHP, 71+1 bytes

```
while(~$c=$argn[$i++])$s=strstr($s,$c)?strtr($s,[$c=>""]):$s.$c;echo$s;

```

Run as pipe with `-nR` or try it online.
> 0 votes

# Answer
# Python 3.6, 69 bytes

```
lambda a:"".join({c:1 for c in a[::-1] if a.count(c)%2}.keys())[::-1]

```

Try it online!

Dict insertion order is preserved in Python 3.6 .
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~97~~ 95 bytes

```
	S =INPUT
N	S LEN(1) . C REM . S :F(O)
	O C :S(R)
	O =O C :(N)
R	O C =:S(R)F(N)
O	OUTPUT =O
END

```

Try it online!

```
	S =INPUT			;* read input
N	S LEN(1) . C REM . S :F(O)	;* take the first character of S and assign it to C,
					;* assign the remainder to S, and if S has no characters left, goto O
	O C :S(R)			;* if C matches anything in O, goto R, otherwise go to next line
	O =O C :(N)			;* append C to O and goto N
R	O C =:S(R)F(N)			;* as long as C matches O, replace it with ''
					;* (unassigned variables default to the null string)
					;* then goto N once it fails to match
O	OUTPUT =O			;* output the string
END					;* terminate the program

```
> 0 votes

# Answer
# Julia 0.6, 49 bytes

```
~x=foldl((s,c)->in(c,s)?replace(s,c,""):s*c,"",x)

```

Try it online!

Algorithm from the pseudocode. This does not work like this in tio.run because concatenation of a string with a char using `*` is not defined. It does work in JuliaPro 0.6.1.1 however, where this is defined from *the future™* (0.7 dev).
> 0 votes

# Answer
# C (gcc), ~~95~~ 94 bytes

```
char*f,*g,c[256];F(char*s){for(f=s;*f;++c[*f++]);for(g=f;f>=s;--f)c[*f]&1?c[*g--=*f]=0:0;++g;}

```

Try it online!

```
char *F(char *src);

```

The input is a null terminated string. It must be writeable.

The output is a pointer to the middle of the source string containing the filtered string (done with the return hack). It will also be null terminated.

Uses a similar approach to djhurio's second answer and coltim's answer, where I count the characters, then select only the last characters that appear once.

It is the only viable option, you can't just "remove" a character in C, and there are no fancy builtins that do anything close to what the other algorithms do.

However, unlike those two, I do everything manually because it is ~~torture~~ fun, and I modify the string in place without reversing it.

I initially tried doing something in C++ with `<algorithm>`, but `std::remove_if` moves **forwards**, meaning we would have to `std::reverse` twice.

Ungolfed version with comments:

```
char *append_and_erase(char *src)
{
    // Temp variables
    char *f, *g;
    // Buffer to hold our character count.
    char counts[256] = { 0 };

    // Count the occurrences of each character.
    for (f = src; *f != '\0'; f++)
         ++counts[*f];

    // Go backwards in the string, writing all the characters that appeared an
    // odd number of times, and skipping the ones that repeat.
    //
    // It is basically a backwards std::remove_if.
    //
    // g will point to the start of the trimmed string minus one.
    // It will look like this:
    //    garbageABCDEFG\0
    //    ^src  ^g
    // g will be off by one, so we need to increment it before we are done.
    for (g = f; f >= src; --f) {
        if (counts[*f] % 2 != 0) {
           *g-- = *f;
           // Clear the count so we don't have duplicates
           counts[*f] = 0;
        }
    }
    // More logical version:
    //
    //    f = src;
    //    g++;
    //    // strcpy but guaranteed to be forwards
    //    while ((*f++ = *g++) != '\0');
    //
    // Golf version:
    // Increment g and return it (we use the return hack in the golf)
    return g + 1;
}

```

Thanks to ceilingcat for the -1 byte using a ternary.
> 0 votes

# Answer
# Thunno 2 `t`, 2 bytes

```
Ʋḍ

```

Try it online!

Port of Erik the Outgolfer's Jelly answer.

#### Explanation

```
Ʋḍ  # Implicit input
Ʋ   # Reduce the input by:
 ḍ  #  Symmetric set difference
    # Implicit output

```
> 0 votes

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