title: What's my middle name?

text:
# Question
Title: What's my middle name?
> **Note:** The winning answer will be selected on **4/12/17** the current winner is Jolf, 1 byte.

I'm surprised that we haven't had a what's my middle name challenge on this site yet. I did alot of searching but found nothing. If this is a dup, please flag it as such.

## Your challenge

Parse a string that looks like `Jo Jean Smith` and return `Jean`.

## Test cases

```
Input: Samantha Vee Hills
Output: Vee

Input: Bob Dillinger
Output: (empty string or newline)

Input: John Jacob Jingleheimer Schmidt
Output: Jacob Jingleheimer

Input: Jose Mario Carasco-Williams
Output: Mario

Input: James Alfred Van Allen
Output: Alfred Van

```

(That last one is incorrect technically, but fixing that would be too hard.)

## Notes:

* Names will always have at least 2 space-separated parts, with unlimited middle names between them or can be a list/array of strings.
* Names may contain the alphabet (case-insensitive) and - (`0x2d`)
* You may output a trailing newline.
* You may require input to have a trailing newline.
* Input from STDIN, a function parameter, or command-line argument is allowed, but hard-coding it in is not allowed.
* Standard loopholes forbidden.
* Output may be function return value, STDOUT, STDERR, etc.
* Trailing spaces/newlines/tabs in the output are allowed.
* Any questions? Comment below!

**This is , so the shortest anwser in bytes wins!**

# Answer
# Jolf, 1 byte

Gets the inside of the input. Try it here!
> 4 votes

# Answer
# Ohm, 2 bytes (CP437)

Accepts and returns a list of strings.

```
()

```

Explanation:

```
()   Main wire, arguments: a

(    Remove the first element of a
 )   ...and then the last element of that
     Implicit output

```
> 44 votes

# Answer
# Vim, ~~6~~ 5 bytes

```
dW$BD

```

Try it online!

(outputs with a trailing space)

Since Vim is reverse-compatible with V, I have included a TIO link for V.

### Explanation

```
dW                      " Delete up to the next word (removes the first name)
$                       " Go to the end of the line
B                       " Go back one word
D                       " Delete it

```
> 14 votes

# Answer
# Python, 24 bytes

```
lambda n:n.split()[1:-1]

```

Try it online string input!

Input Format: **string**

# Python 2, 16 bytes

```
lambda n:n[1:-1]

```

Try it online list input!

Input Format: **List**
> 14 votes

# Answer
# Brain-Flak, 133 bytes

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

```

Try it online!

132 bytes of code, plus 1 byte for the `-c` flag which allows ASCII input and output.

Unfortunately, this contains lots of duplicated code, but it would be really difficult to reuse. I'll look into it later. Here's an explanation:

```
#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>

#While True
{
    #Pop
    {}

    #Not equals 32
    ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

#Endwhile
}

#Pop the 0
{}

#Reverse Stack
{({}<>)<>}<>

```
> 13 votes

# Answer
## Haskell, ~~23~~, ~~17~~ 9 bytes

```
init.tail

```

Takes and returns a list of strings. Try it online!

Drop first string, drop last string.

Edit: @Generic Display Name noted, that the input can be a list of strings, which saved 6 bytes.

Edit II: return list of strings instead of a single string
> 11 votes

# Answer
# 05AB1E, 2 bytes

```
¦¨

```

Try it online!

If outputting a list of middle names isn't allowed, I'll change it.
> 11 votes

# Answer
## Mathematica, 10 bytes

```
Rest@*Most

```

An unnamed function that accepts and returns a list of strings.

`Rest` discards the the last element, `Most` discards the first element, `@*` is function composition. Swapping `Rest` and `Most` or using right-composition `/*` instead would also work. This beats indexing via `#[[2;;-2]]&` by one byte.
> 10 votes

# Answer
# Brain-Flak, 86 bytes

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

```

Try it online!

Most of this code comes from this answer. If you like my solution you should upvote that one as well.

```
#Push 2
(()())

#Loop twice
{({}[()]<

  #While not a space
  {
      #Pop
      {}

      #Not equals 32
      ((((()()()()){}){}){}[{}](<()>)){{}{}(<(())>)}{}

  #Endwhile
  }

  #Pop the 0
  {}

  #Reverse Stack
  {({}<>)<>}<>

#End loop twice
>)}{}

```
> 9 votes

# Answer
# AWK, ~~17~~ 10 bytes

*Saved 7 bytes thanks to @steve!*

```
$NF=$1=x;1

```

Try it online!

Explanation:

```
$NF=    set last word to
$1=     set first word to
x       an empty variable, ie empty string
1       default action, ie print everything

```
> 7 votes

# Answer
# Java 7, 74 bytes

```
String f(String s){return s.substring(s.indexOf(' '),s.lastIndexOf(' '));}

```

# Java 8, 49 bytes

```
s->s.substring(s.indexOf(' '),s.lastIndexOf(' '))

```

Function which identifies the first occurrence of the space character and the last one and extracts the middle. The resulting string is prefixed by a space character (at the time of the posting, OP hasn't clarified if leading spaces are allowed), which can be eliminated by adding `.trim()` to the code for an extra cost of 7 bytes.

Compared to C#, Java has the advantage of specifying the end index instead of sub-string length, which brings down the byte count.
> 7 votes

# Answer
## JavaScript (ES6), 22 bytes

Takes and outputs an array of strings.

```
([_,...a])=>a.pop()&&a

```

### Test cases

```
let f =

([_,...a])=>a.pop()&&a

console.log(f(["Samantha", "Vee", "Hills"]))
console.log(f(["Bob", "Dillinger"]))
console.log(f(["John", "Jacob", "Jingleheimer", "Schmidt"]))
console.log(f(["Jose", "Mario", "Carasco-Williams"]))
```

### String version (27 bytes)

Takes and outputs a string. The output string is either a single space if no middle name was found, or the middle names with leading and trailing spaces.

```
s=>(/ .* /.exec(s)||' ')[0]

```

```
let f =

s=>(/ .* /.exec(s)||' ')[0]

console.log(f("Samantha Vee Hills"))
console.log(f("Bob Dillinger"))
console.log(f("John Jacob Jingleheimer Schmidt"))
console.log(f("Jose Mario Carasco-Williams"))
```
> 6 votes

# Answer
# Groovy, 19 bytes

```
{it.split()[1..-2]}

```

Explanation:

```
{
 it                  all closures have an implicit argument called "it"
   .split()          splits by spaces by default. Returns an array of words
           [1..-2]   take the whole array from the second index (1) to the penultimate index (-2). Implicitly return
                  }

```

A closure / anonymous function
> 5 votes

# Answer
# PHP, 37 Bytes

```
<?=join(" ",array_slice($argv,2,-1));

```

-4 bytes for an output as array

```
print_r(array_slice($argv,2,-1));

```

## PHP, 42 Bytes

```
echo trim(trim($argn,join(range("!",z))));

```

## PHP, 50 Bytes

```
echo preg_filter("#(^[^\s]+ |[^\s]+$)#","",$argn);

```
> 4 votes

# Answer
# Perl 5, 27 18 bytes

Need to run with `-n` option.

```
/ (.+) /&&print$1

```

Try it online!

Wanted to do something similar in sed first, but, unfortunately, it doesn't support non-greedy quantifier. It is needed in case middle name is more than one word.

**Edit**

-9 bytes thanks to **Dada**.

Non-greedy quantifier is not needed anymore, among with some other things.
> 4 votes

# Answer
# sed, ~~21~~ ~~19~~  ~~17~~  15 bytes + `-E`

new:

*idea thanks to @user41805*

*-2 thanks to @xigoi*

*-2 thanks to @ user41805*

```
s/^\S+ |\S+$//g

```

old:

*-1 thanks to @user41805*

```
s/\S+ ((.+ )*).+/\1/

```

Try it online!
> 4 votes

# Answer
## Retina, 11 bytes

```
^\S+ |\S+$

```

Try it online!

Matches the first word (including the space after it) and the last word, and removes both of them.

If I/O can be a linefeed-separated list, it can be done in 8 bytes instead:

```
A1`
G-2`

```

Try it online!
> 3 votes

# Answer
# Javascript (ES6) ~~49~~ 16 bytes

## **Edit:**

```
a=>a.slice(1,-1)

```

Try it online!

**ungolfed:**

```
function(name) {
  return a.slice(1, -1); //start at the second item and end at the second to last item
};

```

I forgot some of the simple properties of `slice`, and that the input can be an array. Thanks to @Neil and @fəˈnɛtɪk I was able to remove 27 bytes. Still not really competing.

## **Original:**

This isn't really competing but here's a Javascript solution:

```
a=>{a=a.split(' ');return a.slice(1, a.length-1)}

```

This creates an anonymous function equal to:

```
function(name) {
  let name = name.split(' '); //first middle last -> [first, middle, last]
  return name.slice(1, name.length - 1); //get the second item to the second to last item in the array.
}

```

### How I golfed it

This is a pretty simple golf. I turned the function into an arrow function. Then I "minified" the code. This included renaming `name` into a single character(`a` in this case) and removing the `let` decloration of the variable.

### Snippet

```
var a=b=>b.slice(1,-1)

//example code

let form = document.querySelector('#form'),
    input = document.querySelector('#input'),
    result = document.querySelector('#result');

form.addEventListener('submit', (event) => {
  event.preventDefault();
  let value = input.value.split` `;
  result.textContent = a(value).join(' ');
});
```

```
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form id="form">
  <div class="input-group">
    <input id="input" class="form-control" />
    <div class="input-group-btn">
      <button class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

<p id="result"></p>
```

Hope this helps anyone who is stuck on the challenge.
> 3 votes

# Answer
# Arn, 4 bytes

```
†Û⁺%

```

Try it!

# Explained

Unpacked: `.{.}`

```
_ Variable initialized to STDIN; implied
  .{ Take
    .} Then drop
         Output implicit

```

Strings are split on spaces if any or ever character if there are non (when casted to an array).
> 3 votes

# Answer
# Husk, ~~6~~ 4 bytes

```
;htw

```

Try it online!

-2 bytes from Zgarb.
> 3 votes

# Answer
# Röda, 9 bytes

```
{_[1:-1]}

```

Try it online!

Not a very interesting solution. Takes a list from the stream and returns the middle names.

21 bytes and I/O:

```
{[(_/" ")[1:-1]&" "]}

```

Try it online!

This uses `/` (split) and `&` (join).
> 2 votes

# Answer
# Matlab, ~~81~~, ~~79~~, ~~78~~, 55 Bytes

```
function x=a(s)
s=strsplit(s);x=strjoin(s(2:end-1));end

```

Takes in an input string, `s`, is split (by the default delimiter, whitespace char) into a cell array, from which the middle element is accessed. Then the middle elements are concatenated, or an empty string is returned.

Edit: thanks to Luis Mendo for saving 3 bytes!

Edit 2: Better solution from Ankit!
> 2 votes

# Answer
# Jelly, 2 bytes

```
ḊṖ

```

Try it online!

This works as a non-inline link (i.e. function), not a full program.

`'John','Jacob','Jingleheimer','Schmidt'``'Jacob','Jingleheimer'`

As a full program, it would be 3 bytes: `ḊṖK`, which prints a space-separated middle name.
> 2 votes

# Answer
# Pyth, 2 bytes

```
Pt

```

Online interpreter
> 2 votes

# Answer
# C#, 67 bytes

```
s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

```

Anonymous function which identifies the first occurrence of the space character and the last one and extracts the middle. It also extracts a trailing space, which can be removed at the cost of 2 bytes.

Full program with test cases:

```
using System;

namespace WhatsMyMiddleName
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string> f =
            s=>s.Substring(s.IndexOf(' ')+1,s.LastIndexOf(' ')-s.IndexOf(' '));

            Console.WriteLine(f("Jo Jean Smith"));          // "Jean"
            Console.WriteLine(f("Samantha Vee Hills"));     // "Vee"
            Console.WriteLine(f("Bob Dillinger"));          // ""
            Console.WriteLine(f("John Jacob Jingleheimer Schmidt"));// "Jacob Jingleheimer"
            Console.WriteLine(f("Jose Mario Carasco-Williams"));    // "Mario"
            Console.WriteLine(f("James Alfred Van Allen")); // "Alfred Van"
        }
    }
}

```
> 2 votes

# Answer
# Ruby, ~~24~~ 13 bytes

```
p ARGV[1..-2]

```

*Saved 11 bytes thanks to Piccolo pointing out that array-like output is allowed.*

Takes the name as separate command line arguments, e.g.:

```
$ ruby script.rb John Jacob Jingleheimer Schmidt

```

or

```
$ ruby -e 'p ARGV[1..-2]' John Jacob Jingleheimer Schmidt

```

---

Previous code (outputs a proper string):

```
puts ARGV[1..-2].join" "

```
> 2 votes

# Answer
# Kotlin, 39 bytes

```
s.filterIndexed{i,j->i!=0&&i!=s.size-1}

```

Try it online!

i.e.

```
s.filterIndexed{ index, value -> index != 0 && index != (s.size - 1) }

```
> 2 votes

# Answer
# VBA, 69 bytes

```
Sub m(n)
f=InStr(1,n," ")
Debug.?Mid(n,f+1,InStrRev(n," ")-f)
End Sub

```
> 2 votes

# Answer
# R, ~~30~~ ~~27~~ 22 bytes

Current solution due to user11599!

```
head(scan(,''),-1)[-1]

```

Takes input from stdin, returns each middle name as a separate string. Returns `character()` in the case of no middle name; that is, a vector of class `character` of length `0`.

**Explanation:**

Read stdin into a list of strings, separated by spaces

```
     scan(,'')

```

Remove the last element. `head` returns the first `n` elements of a list, with `n` defaulting to `6`. If `n` is `-1` it returns all but the last element.

```
head(scan(,''),-1)

```

Now, remove the first element of this list.

```
head(scan(,''),-1)[-1]

```

This yields the middle name(s).
> 2 votes

# Answer
## Grime, 6 bytes

```
<\ 0\

```

Try it online! Note the trailing space.

## Explanation

```
        Match a substring S that satisfies:
<       S is contained in a string of the form
 \      a space
   0    then S
    \   then another space.

```

This matches a substring that's surrounded by spaces. By default, Grime prints the longest match it finds (without the spaces). If no match exists, nothing is printed.
> 2 votes

# Answer
## C, 42 bytes

```
f(char**b){for(;b[2];printf("%s ",*++b));}

```

The parameter is a NULL terminated array of pointers to char.

See it work here.

The command line arguments may also be used with the same function.

## C, 51 bytes

```
main(a,b)char**b;{for(;b[3];printf("%s ",b++[2]));}

```

A full program. Input is done through command line arguments.

See it work here.

## C, 54 bytes

```
f(char**b){*strrchr(*b=strchr(*b,32),32)=0;*b+=!!**b;}

```

The parameter is an in/out parameter.

See it work here.
> 2 votes

# Answer
# **Golang**, ~~152~~ 81 bytes

```
import ."strings"
func f(x string)[]string{var k=Fields(x);return k[1:len(k)-1];}

```

It takes input as "Samantha Vee Hills" (with double quotes) and return the middle name to the stdout.

Try it Online!

Edit: @Dada, note that the "function as answer is allowed" shorten my code 71 bytes. a big thanks!
> 2 votes

# Answer
# Clojure, 43 bytes:

```
#(drop 1(butlast(read-string(str"("%")"))))

```

Here we read string as an edn data, then choosing its center.

# Or for stdout, 57 bytes:

```
#(apply pr-str(drop 1(butlast(read-string(str"("%")")))))

```

You can also check it here.
> 2 votes

# Answer
# Powershell, 32 bytes

```
''+($args|sls ' .+ '|% m*)|% t*m

```

Test script:

```
$f = {
''+($args|sls ' .+ '|% m*)|% t*m
}

@(
    ,("Samantha Vee Hills"    ,"Vee")
    ,("Bob Dillinger"    ,"")
    ,("John Jacob Jingleheimer Schmidt"    ,"Jacob Jingleheimer")
    ,("Jose Mario Carasco-Williams"    ,"Mario")
    ,("James Alfred Van Allen"    ,"Alfred Van")
) | % {
    $name,$expected = $_
    $result = &$f $name
    "$($result-eq$expected): $expected"
}

```

Output:

```
True: Vee
True:
True: Jacob Jingleheimer
True: Mario
True: Alfred Van

```
> 2 votes

# Answer
# Brainfuck, 98 bytes

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

```

## Explanation

```
>+[,>++++[<-------->-]<] Skip input until first space

>++++[<++++++++>-]< Store a Space char incase there is no middle name
[>,] Store input to a char array

++++[<-------->-]<[[-]++++[<-------->-]<] Goto the last space and zero the last space

<[<] Goto the start of the char array
>>[.>] Print the char array

```
> 2 votes

# Answer
# Factor, ~~17~~ 16 bytes

```
[ rest 1 head* ]

```

(-1 byte as `1 head*` is 1 byte shorter than `but-last`.)

## Explanation:

It's a quotation (anonymous function) that takes a sequence of strings as input and leaves a sequence of strings as output.

* `rest` Take all elements of a sequence but the first.
* `1 head*` Take all elements of a sequence but the last.
> 2 votes

# Answer
# AWK, 9 bytes

```
NF--,$1=a

```

Try it online!

```
NF--,     - Cut out the last argument (also eval's to "true")
     $1=a - Blank out the first argument

```

Since there's always at least 2 input fields `NF--1` is always truthy, so the code prints `$0`.

In case the leading space isn't allowed (the question was asked in the comments under the initial posting but there was no response), then this is the shortest I've come up with.

# AWK, 15 bytes

```
NF-=sub($1FS,a)

```

Try it online!

```
    sub($1FS,a)  - Remove the first field, plus space from the input
NF-=             - Decrement "NF" by one (the return from "sub")

```
> 2 votes

# Answer
# Fig, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
pq

```

Try it online!

```
pq
 q # Remove the tail
p  # Remove the head

```
> 2 votes

# Answer
# Python 2, ~~42~~ ~~19~~ 16 Bytes

```
lambda n:n[1:-1]

```

Try it online! Thanks to @Kritixi Lithos for saving 23 bytes! Thanks @math\_junkie for saving 3 more bytes. For input, put each part of the name as a string within a list like so:

```
["Samantha", "Vee", "Hills"]

```

And yes, the OP has approved a list to be a valid input.

**Explanation**

```
lambda n:n[1:-1]    # Returns only the middle elements... pretty literal here

```
> 1 votes

# Answer
# APL (Dyalog), ~~8~~ 6 bytes

```
¯1↓1↓⊢

```

Try it online!

This is a tacit train.

### Explanation

When  is a dyad, it returns all but the first/last *n* elements of its vector argument.

```
   1↓                  ⍝ Remove the first element in the
     ⊢                 ⍝ right argument
¯1↓                    ⍝ and remove the last element

```
> 1 votes

# Answer
# C++, 91 bytes

```
#import<list>
#import<string>
void f(std::list<std::string>&n){n.pop_front();n.pop_back();}

```

Takes input as a reference to a list of strings and modifies the list directly.

Try it online!
> 1 votes

# Answer
# Bash, 31 19 bytes

```
echo ${@:2:$[$#-2]}

```

Try it online!

**Breakdown:**

Prints parameter expansion from second to second last element.

**Edit**

Removed commented code from breakdown section, since it's now just one line long.

-12 bytes thanks to **Neil**
> 1 votes

# Answer
# C (gcc), ~~144~~ ~~139~~ ~~91~~ 86 bytes

```
y,z;char*f(char*s){for(y=0;*++s-32;);for(;s[y];y++)z=s[y]-32?z:y;z[s]=0;return!!*s+s;}

```

Try it online!

-48 bytes by learning C over the past year and a half since I first posted this

-7 bytes from Jonathan Frech

A function that takes in a `char*` and outputs a `char*` corresponding to the (character after the) first space in the string, but also edits the string so that it's last space is replaced with `\0`.

Note: this function will segfault if given a string without a space in it.

Full program:

```
y;z;char*f(char*s){y=0;while(*++s-32);while(s[y]){z=s[y]-32?z:y;y++;}s[z]=0;return s+!!*s;}
int main(int argc, char *argv[]){
	for (int i = 1; i < argc; ++i)
		printf("%s\n",f(argv[i]));
}

```

Un-golfed:

```
char *middle(char* name) {
	int index = 0, lastspace;
	while(name[0] != ' ') // move name pointer forward to the first space
		++name;
	while(name[index] != '\0') { // find the index in the (new) string of the last space
		if (name[index] == ' ') lastspace = index;
		index++;
	}
	name[lastspace] = '\0'; // Terminate the string at the last space
	if (name[0] == '\0') return name; // If the last space was the first space, return the empty string
	else return name + 1; // Else, return the new string
}

```

Try it online!
> 1 votes

# Answer
# CJam, 6 bytes

```
{1>W<}

```

Anonymous block that expects an array of strings on the stack, and leaves an array of strings after.

Try it online!

**Explanation**

```
1>    e# Slice the array after the first element
  W<  e# Slice the array before the last element

```
> 1 votes

# Answer
# Ruby, 13 bytes

```
->s{s[1..-2]}

```

The author confirmed in comments that the input and output can be arrays.
> 1 votes

# Answer
## REXX, 42 bytes

```
arg a
say delword(delword(a,words(a)),1,1)

```
> 1 votes

# Answer
# Japt, 3 bytes

```
Å¯J

```

Try it or run all test cases
> 1 votes

# Answer
# Pip `-s`, 8 bytes

```
@<@>Ya^s

```

Try it online!

-1 from DLosc.
> 1 votes

# Answer
# Perl 5 \+ `-p040`, 13 bytes

```
$_ x=$.>1&/ /

```

Try it online!

## Explanation

With `-p`, input is implicitly stored in `$_`, the `040` flag makes space the line terminator which means the code is called for each word/name in the input. `x=` is the in-place string repetition operator which modifies the string in place (e.g. `$_="abc";$_ x=3;# "abcabcabc"`) and the condition is `$.>1` (`$.` is set to the current 'line' number, although since space is our line end character this is word/name number) `&`ed with `/ /` (if `$_` `m//`atches , which it will for all but the last word/name). Because of `-p` the result (the string repeated zero or one times depending on the conditional) is implicitly printed.
> 1 votes

# Answer
# GolfScript, 6 bytes

```
~(;);`

```

Try it online!

Input is taken in the form of `["name""name""name"]`. Input string is converted to an array, then the first and last elements are separated and discarded, and the result is formatted and outputted.
> 1 votes

# Answer
# Dash, 24 bytes

```
g=\ ${*#* };echo ${g% *}

```

Try it online!

Input via args.

Also handles the unmentioned case of a single name being provided, returning nothing.

While this feels not *that* clever compared to the posted bash answer, that answer doesn’t work in Dash and this is the best I could muster within its restrictions.
> 1 votes

# Answer
# Vyxal `S`, 2 bytes

```
ḢṪ

```

Try it Online!

Removes head and tail of list. `S` flag joins by spaces.
> 1 votes

# Answer
# K (ngn/k), ~~25~~ 24 bytes

```
{" "/*(1;-1+#t)_t:" "\x}

```

Try it online!

*Down 1 byte by using assignment in expressions*

Does the same thing as the APL answer.

Explanation:

```
{" "/*(1;-1+#t)_t:" "\x}    Main function. Takes x as input
                  " "\x     Split x by whitespace
                t:          Assign to variable t
      (       )_            Then delete the following elements in t:
       1;                   The first element, followed by
            #t              The length of t
         -1+                - 1
                            Delete returns back the string as an array, so we need to
     *                      Get the first element of the array
 " "/                       And joined each element in the sub-array by whitespace
                            This is to handle cases like "James Alfred Van Allen",
                            where the result after delete will be ["Alfred", "Van"]

```
> 1 votes

# Answer
# Ruby `-p`, 20 bytes

Basically identical to Yelp’s sed answer and others.

```
gsub /^\S+ |\S+$/,""

```

Attempt This Online!
> 1 votes

# Answer
# Go, 106 bytes

```
import."strings"
func f(s string)(o string){l:=Split(s," ")
if k:=len(l);k>2{o=Join(l[1:k-1]," ")}
return}

```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2 , 2 bytes

```
ḣṫ

```

Attempt This Online!

```
ḣ   # head remove
 ṫ  # tail remove
    # Ṡ flag joins by spaces

```
> 1 votes

# Answer
## Batch, 70 bytes

```
@set s=.
:l
@if not "%3"=="" set s=%s% %2&shift&goto l
@echo(%s:~2%

```

The loop concatenates arguments starting with the second, shifting them until the third argument is empty. This results in a leading space, so to remove that I prepend with a `.` so that I can slice the string (slicing an empty string produces an erroneous result in Batch). If a trailing space on output is acceptable, then for 66 bytes:

```
@set s=
:l
@if not "%3"=="" set s=%s%%2 &shift&goto l
@echo(%s%

```
> 0 votes

# Answer
## Ruby, 33 bytes

```
->s{$><<s.split[1..-2].join(' ')}

```
> 0 votes

# Answer
# TI-Basic (TI-84 Plus CE), 131 bytes

```
Prompt Str0
inString(Str0," →A
length(Str0)–A→L
sub(Str0,A,L→Str0
" →Str2
For(B,1,L
sub(Str0,B,1)+Str2→Str2
End
inString(Str2," →A
L-A→L
sub(Str2,A,L→Str2
" →Str0
For(B,1,L
sub(Str2,B,1)+Str0→Str0
End
Disp Str0

```

Explanation:

```
Prompt Str0              # 4 bytes, input user string
inString(Str0," →A       # 10 bytes, store the index of the first space in A
length(Str0)–A→L         # 10 bytes, store the length of the string (after removing the first A characters) in L
sub(Str0,A,L→Str0        # 12 bytes, remove first A-1 and last characters of Str0
" →Str2                  # 6 bytes, temporary string to reverse Str0
For(B,1,L                # 7 bytes, reverse Str0 into Str2
sub(Str0,B,1)+Str2→Str2  # 16 bytes
End                      # 2 bytes
inString(Str2," →A       # 10 bytes, store the index of the first space in A
L-A→L                    # 6 bytes, get new length
sub(Str2,A,L→Str2        # 12 bytesremove first A-1 and last characters of Str2
" →Str0                  # 6 bytes, temporary string to reverse Str2
For(B,1,L                # 7 bytes, reverse Str2 into Str0
sub(Str2,B,1)+Str0→Str0  # 16 bytes
End                      # 2 bytes
Disp Str0                # 3 bytes, display final string with (2 trailing spaces)

```
> 0 votes

# Answer
# Sed, ~~23~~ 20 bytes

```
s/\w* (.*) \w*$/\1/

```

Unlike my last sed entry which involved a pipeline from one sed command to another, this one is just a simple, single command, so I'm only counting the bytes of the sed script.

Edited: Plus a 1-byte penalty for the `-r` flag. Thank you, Krixti Lithos, for pointing that out!
> 0 votes

# Answer
# Python 3, 28 bytes

```
print(input().split()[1:-1])

```

Try it online!
> 0 votes

# Answer
# Clojure, 107 bytes

```
(fn[f](clojure.string/join" "(map #(apply str %)(drop 1(drop-last(take-nth 2(partition-by #(= % \ )f)))))))

```

Unfortunately `drop`/`drop-last` was shorter than `subvec`.

```
(defn middle-name [full-name]
  ; Partition the string into a list of names split on spaces, then take every second element
  ;  since partition keeps the spaces
  (let [sub-names (take-nth 2
                    (partition-by #(= % \ ) full-name))]

    ; ... then join the middle names together on a space.
    (clojure.string/join " "
      ; Drop returns list of chars, so turn them back into strings...
      (map #(apply str %)
           ; Drop the first and last name
           (drop 1
             (drop-last sub-names))))))

```
> 0 votes

# Answer
# Ruby, 17 bytes

```
$><<$*[1..-2]*' '

```

Full program, takes input as command line arguments, e.g.:

```
$ ruby middle.rb john jacob jingleheimer shmidt
jacob jingleheimer

```

If we don't mind having the result wrapped in quotation marks, can just use:

```
p$*[1..-2]*' '
$ ruby middle2.rb john jacob jingleheimer shmidt
"jacob jingleheimer"

```

Of course, we can also just take a list and return a list, which can be as short as a 13 byte lambda.

```
->s{s[1..-2]}
# usage:
y = ->s{s[1..-2]};
y.call ["john","jacob","jingleheimer","shmidt"] #=> ["jacob", "jingleheimer"]

```
> 0 votes

# Answer
# Japt, ~~7~~ 3 bytes

```
s1J

```

Try it online!

This is essentially `Input.slice(1,-1)`. The `-1` wraps around to the last item in the input.
> 0 votes

# Answer
# C#, ~~72~~ 69 bytes

Takes a string, returns a string...

```
s=>string.Join(" ",s.Split(' ').Skip(1).TakeWhile(n=>!s.EndsWith(n)))

```

# C# 43 bytes

Takes a string array, returns a string array...

```
s=>s.Skip(1).TakeWhile((n,i)=>i<s.Length-2)

```
> 0 votes

# Answer
# Pushy, 17 bytes

```
32K-$.;@$.;.@32+"

```

**Try it online!**

```
32 K-    \ Take away 32 from every character.
         \ Now we have the value 0 where there were spaces.
$        \ Until we reach a zero:
 .;      \   Pop a character from the end
         \ Everything after the last space is now removed
@        \ Reverse stack
$.;      \ Do the same
.        \ Pop the leading space
32+      \ Add 32 to everything to map the numbers back to their original characters
@"       \ Reverse and print

```

This is the first method I thought of, and looks like the shortest.
> 0 votes

# Answer
# c, 72 bytes

```
g(char*p){char*e,*s=0;for(;*p;p++)*p-32?0:s?(e=p):(s=p);*e=0;puts(s+1);}

```

Try it online
> 0 votes

# Answer
# JavaScript (ES6), 16 Bytes

```
x=>x.slice(1,-1)

```

Simple. Return the array passed from the second element to the second from last.
> 0 votes

# Answer
# Lua, 39 bytes

```
print(io.read("*l"):match(" (.+) .+$"))

```
> 0 votes

# Answer
# c, 53 bytes

```
main(a,b)char**b;{for(++b;--a>2;printf("%s ",*++b));}

```

Try it online
> 0 votes

# Answer
# Noodel, 5 bytes

Input must be an array of the names.

```
Ẹ⁻2¤İ

```

Try it:)

---

## How it works

```
      # Pushes the input on implicitly.
Ẹ⁻2¤İ
Ẹ     # Takes the last item of an array and pushes it to the back.
 ⁻2   # Pop the first two items off of the array.
   ¤  # Push the string "¤" onto the stack which represents a space.
    İ # Concatenates the array elements by the "¤" string.
      # Implicitly output the top of the stack to the screen.

```

```
<div id="noodel" code="Ẹ⁻2¤İ" input='["James", "Alfred", "Van", "Allen"]' cols="10" rows="2"/>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 0 votes

# Answer
# Javascript ES6 23Bytes

`x=>x.pop()*x.shift()||x`

use * instead of && to save 1 byte

Try it online
> 0 votes

# Answer
# Tcl, 28 bytes

```
proc R n {lrange $n 1 end-1}

```

Try it online!
> 0 votes

# Answer
# Gambit Scheme (gsi), 48 bytes

```
(lambda(x)(if(>(length x)2)(cadr(reverse x))""))

```

Try it online!
> 0 votes

# Answer
# Arturo, 29 bytes

```
$->a[take drop a 1(size a)-2]

```

Try it
> 0 votes

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


title: Type uniqchars!

text:
# Question
Title: Type uniqchars!
Given a string consisting of **printable ASCII chars**, produce an output consisting of its **unique chars in the original order**. In other words, the output is the same as the input except that a char is removed if it has appeared previously.

**No built-ins** for finding unique elements in an array can be used (for example, MATLAB has a `unique` function that does that). The idea is to do it manually.

Further details:

* Either **functions or programs** are allowed.
* Input and output can be in the form of **function arguments, stdin/stdout** (even for functions), or a mix of those.
* If stdin or stdout are used, a string is understood as just the **sequence of chars**. If function arguments are used, the sequence of chars may need to be **enclosed** in quotation marks or equivalent symbols that the programming language of choice uses for defining strings.
* The output should be a string **containing only** the unique characters of the input. So no extra linebreaks, spaces etc. The only exception is: if the output is displayed in stdout, most displaying functions add a trailing `\n` (to separate the string from what will come next). So **one trailing `\n` is acceptable in stdout**.
* If possible, post a link to an **online** interpreter/compiler so that others can try your code.

This is **code golf**, so shortest code in bytes wins.

Some **examples**, assuming stdin and stdout:

1. Input string:

```
Type unique chars!

```

Output string:

```
Type uniqchars!

```
2. Input string

```
"I think it's dark and it looks like rain", you said

```

Output string

```
"I think'sdarloe,yu

```
3. Input string

```
3.1415926535897932384626433832795

```

Output string

```
3.14592687

```

# Answer
> 18 votes
# GolfScript, 2 bytes

```
.&

```

or, alternatively:

```
.|

```

I posted this a while ago in the Tips for golfing in GolfScript thread. It works by duplicating the input string (which is put on the stack automatically by the GolfScript interpreter, and which behaves in most ways like an array of characters) and then taking the set intersection (`&`) or union (`|`) of it with itself. Applying a set operator to an array (or string) collapses any duplicates, but preserves the order of the elements.

# Answer
> 24 votes
# CJam, 3 bytes

```
qL|

```

Setwise or of the input with an empty list. CJam set operations preserve element order.

Try it online

# Answer
> 20 votes
# C# 6, 18 + 67 = 85 bytes

Requires this `using` statement:

```
using System.Linq;

```

The actual method:

```
string U(string s)=>string.Concat(s.Where((x,i)=>s.IndexOf(x)==i));

```

This method saves some chars by defining the function as a lambda, which is supported in C# 6. This is how it would look in C# pre-6 (but ungolfed):

```
string Unique(string input)
{
    return string.Concat(input.Where((x, i) => input.IndexOf(x) == i));
}

```

How it works: I call the `Where` method on the string with a lambda with two arguments: `x` representing the current element, `i` representing the index of that element. `IndexOf` always returns the first index of the char passed to it, so if `i` is not equal to the first index of `x`, it's a duplicate char and mustn't be included.

# Answer
> 15 votes
# Retina, 14 bytes

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

```

Each line should go in its own separate file, or you can use the `-s` flag to read from one file.

To explain it, we'll use this longer but simpler version:

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

```

The first line is the regex to match with (`+`` is the configuration string that keeps running until all replacements have been made). The regex looks for a character (we'll call it C), followed by zero or more arbitrary characters, followed by C. The parentheses denote capturing groups, so we replace the match with C (`$1`) and the characters in between (`$2`), removing the duplicate of C.

For example, if the input string was `unique`, the first run would match `uniqu`, with `u` and `niq` as `$1` and `$2`, respectively. It would then replace the matched substring in the original input with `uniq`, giving `uniqe`.

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

Saved 1 byte thanks to @kos and 1 byte thanks to @Xcali!

```
s/./$&x!$h{$&}++/eg

```

Try it online!

# Answer
> 12 votes
# JavaScript ES7, ~~37~~ ~~33~~ 25 bytes

Pretty simple approach using ES6 `Set` and ES7 ~~Array comprehensions~~ spread operator:

```
s=>[...new Set(s)].join``

```

22 bytes less than the `indexOf` approach. Worked on a handful of test cases.

# Answer
> 11 votes
## Macaroni 0.0.2, 233 bytes

```
set i read set f "" print map index i k v return label k set x _ set _ slice " " length index f e 1 1 set f concat f wrap x return label e set _ slice " " add _ multiply -1 x 1 1 return label v set _ unwrap slice i _ add 1 _ 1 return

```
* create "anti-golfing" language: check
* golf it anyway: check

This is a full program, which inputs from STDIN and outputs on STDOUT.

Wrapped version, for aesthetic value:

```
set i read set f "" print map index i k v return label k set x _ set _ slice "
" length index f e 1 1 set f concat f wrap x return label e set _ slice " " add
_ multiply -1 x 1 1 return label v set _ unwrap slice i _ add 1 _ 1 return

```

And a heavily "commented" and ungolfed version (there are no comments in Macaroni, so I just use bare string literals):

```
set input read                  "read line from STDIN, store in 'input' var"
set found ""                    "we need this for 'keep' below"
print map index input keep val  "find indeces to 'keep', map to values, print"
return

label keep
    "we're trying to determine which indeces in the string to keep. the special
     '_' variable is the current element in question, and it's also the value
     to be 'returned' (if the '_' variable is '0' or empty array after this
     label returns, the index of the element is *not* included in the output
     array; otherwise, it is"
    set x _ set _ slice
        " "
        length index found exists
        1
        1
    "now we're using 'index' again to determine whether our '_' value exists in
     the 'found' array, which is the list of letters already found. then we
     have to apply a boolean NOT, because we only want to keep values that do
     NOT exist in the 'found' array. we can 'invert' a boolean stored as an
     integer number 'b' (hence, 'length') with 'slice(' ', b, 1, 1)'--this is
     equivalent to ' '[0:1], i.e. a single-character string which is truthy, if
     'b' was falsy; otherwise, it results in an empty string if 'b' was truthy,
     which is falsy"
    set found concat found wrap x  "add the letter to the 'found' array"
return

label exists
    set _ slice
        " "
        add _ multiply -1 x
        1
        1
    "commentary on how this works: since 0 is falsy and every other number is
     truthy, we can simply subtract two values to determine whether they are
     *un*equal. then we apply a boolean NOT with the method described above"
return

label val
    set _ unwrap slice input _ add 1 _ 1  "basically 'input[_]'"
return

```

(This is the first real Macaroni program (that actually does something)! \o/)

# Answer
> 8 votes
# Beam, ~~23~~ 18 bytes

```
v<H
vs)
rS
g@S
>u^

```

Try it online!

# Answer
> 8 votes
# C# 6 - 18+46=64

```
using System.Linq;

```

and then

```
string f(string s)=>string.Concat(s.Union(s));

```

The `Enumerable.Union` extension method specifies that elements are returned in the original order:

> When the object returned by this method is enumerated, Union enumerates *first* and *second* in that order and yields each element that has not already been yielded.

Set operations that aren't specifically intended to find unique values appear to be allowed judging by the other answers.

# Answer
> 8 votes
# Python 2, 42 bytes

Uses a couple anonymous functions and `reduce`.

```
lambda s:reduce(lambda x,y:x+y[y in x:],s)

```

**Try it online**

# Answer
> 7 votes
# JavaScript ES6, 47 bytes

```
f=s=>s.replace(/./g,(e,i)=>s.indexOf(e)<i?'':e)

```

The test below works on all browsers.

```
f=function(s){
  return s.replace(/./g,function(e,i){
    return s.indexOf(e)<i?'':e
  })
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run()
```

```
<input type="text" id="input" value="Type unique chars!" /><button id="run">Run</button><br />
<pre id="output"></pre>
```

# Answer
> 7 votes
# MATLAB, 23

```
 @(n)union(n,n,'stable')

```

Does the "set union" of the input string with itself, using the 'stable' method which does not sort, and then prints.

This works because `union` returns only non-duplicate values after the merge. So essentially if you `union` the string with itself, it first produces a string like `Type unique chars!Type unique chars!`, and then removes all duplicates without sorting.

No need for `unique` :)

# Answer
> 7 votes
# \>\<\>, 16 bytes

```
i:0(?;:::1g?!o1p

```

\>\<\> doesn't have strings, so we make use of the codebox. Due to the toroidal nature of \>\<\>, the following runs in a loop:

```
i         Read a char
:0(?;     Halt if EOF
:::       Push three copies of the char
1g        Get the value at (char, 1), which is 0 by default
?!o       Print the char if the value was nonzero
1p        Set the value at (char, 1) to char

```

Note that this uses the fact that the input only contains printable ASCII, as this would not work if ASCII 0 was present.

# Answer
> 7 votes
## Python 3, 44

```
r=''
for c in input():r+=c[c in r:]
print(r)

```

Builds the output string `r` character by character, including the character `c` from the input only if we haven't seen it already.

Python 2 would be 47, losing 4 chars with `raw_input` and saving 1 on not needing parers for `print`.

# Answer
> 6 votes
# Element, ~~22~~ ~~19~~ 18 bytes

```
_'{"(3:~'![2:`];'}

```

Example input/output: `hello world` -\> `helo wrd`

This works by simply processing the string one character at a time and keeping track which ones it has seen before.

```
_'{"(3:~'![2:`];'}
_                        input line
 '                       use as conditional
  {              }       WHILE loop
   "                     retrieve string back from control (c-) stack
    (                    split to get the first character of (remaining) string
     3:                  a total of three copies of that character
       ~                 retrieve character's hash value
        '                put on c-stack
         !               negate, gives true if undef/empty string
          [   ]          FOR loop
           2:`           duplicate and output
               ;         store character into itself
                '        put remaining string on c-stack as looping condition

```

# Answer
> 6 votes
## APL, 3

```
∊∪/

```

This applies union (∪) between each element of the vector, obtaining an iteration that has the effect of removing duplicates.

Test it on tryapl.org

Old One:

```
~⍨\

```

This uses ~ (with reversed arguments, using ⍨) applied between each element of the argument. The result is that for each element, if it's already in the list, it gets erased.

# Answer
> 5 votes
# Julia, ~~45~~ 42 bytes

```
s->(N="";[i∈N?N:N=join([N,i])for i=s];N)

```

Old version:

```
s->(N={};for i=s i∈N||(N=[N,i])end;join(N))

```

Code builds the new string by appending new characters onto it, then `join`s them together to a proper string at the end. New version saves some characters by iterating via array comprehension. Also saves a byte by using `?:` rather than `||` (as it removes the need for brackets around the assignment).

Alternate solution, 45 bytes, using recursion and regex:

```
f=s->s!=(s=replace(s,r"(.).*\K\1",""))?f(s):s

```

### Julia, 17 bytes

(Alternate version)

```
s->join(union(s))

```

This uses `union` as basically a substitute for `unique` \- I don't consider this the "real" answer, as I interpret "don't use `unique`" to mean "don't use a single built-in function that has the effect of returning the unique elements".

# Answer
> 5 votes
# TI-BASIC, 49 bytes

```
Input Str1
"sub(Str1,X,1→Y₁
Y₁(1
For(X,2,length(Str1
If not(inString(Ans,Y₁
Ans+Y₁
End
Ans

```

The equation variables are rarely useful since they take 5 bytes to store to, but `Y₁` comes in handy here as the `X`th character of the string, saving 3 bytes. Since we can't add to empty strings in TI-BASIC, we start the string off with the first character of Str1, then loop through the rest of the string, adding all characters not already encountered.

```
prgmQ
?Why no empty st
rings? Because T
I...
Why noemptysrig?Bcau.

```

# Answer
> 5 votes
# Pyth, 7 bytes

```
soxzN{z

```

Pseudocode:

z = input

sum of order-by index in z of N over set of z.

# Answer
> 4 votes
# Ruby, ~~30~~ 24 characters

(23 characters code + 1 character command line option.)

```
gsub(/./){$`[$&]?"":$&}

```

Sample run:

```
bash-4.3$ ruby -pe 'gsub(/./){$`[$&]?"":$&}' <<< 'hello world'
helo wrd

```

# Answer
> 4 votes
## Perl, 54 27 bytes

```
map{$h{$_}||=print}<>=~/./g
123456789012345678901234567

```

Test:

```
$ echo Type unique chars! | perl -e 'map{$h{$_}||=print}<>=~/./g'
Type uniqchars!
$

```

# Answer
> 4 votes
# PHP, 72 Bytes ~~84 Bytes~~

```
<?foreach(str_split($argv[1])as$c)$a[$c]=0;echo join('',array_keys($a));

```

Uses the characters as keys for an associative array, then prints the keys. Order of array elements is always the order of insertion.

Thanks Ismael Miguel for the `str_split` suggestion.

# Answer
> 4 votes
# Java, 78 bytes

```
String f(char[]s){String t="";for(char c:s)t+=t.contains(c+"")?"":c;return t;}

```

A simple loop while checking the output for characters already present. Accepts input as a `char[]`.

# Answer
> 4 votes
# C - 58

Thanks to @hvd and @AShelly for saving a bunch of characters. There were multiple ways suggested of making it much shorter than the original:

```
// @hvd     - always copy to q but only increment q if not found
g(char*s,char*r){char*q=r;for(;*q=*s;q+=q==strchr(r,*s++));}

// @AShelly - keep a histogram of the usage of each character
h(char*s){int a[128]={0};for(;*s;s++)a[*s]++||putchar(*s);}

// @hvd     - modify in place
i(char*s){char*q=s,*p=s;for(;*q=*p;q+=q==strchr(s,*p++));}

// original version - requires -std=c99
void f(char*s,char*r){for(char*q=r;*s;s++)if(!strchr(r,*s))*q++=*s;}

```

As you can see modifying in place seems to be the shortest (so far!) The test program compiles without warnings using `gcc test.c`

```
#include <stdlib.h> // calloc
#include <string.h> // strchr
#include <stdio.h>  // puts, putchar

// 000000111111111122222222223333333333444444444455555555556666666666
// 456789012345678901234567890123456789012345678901234567890123456789

// @hvd     - always copy to q but only increment q if not found
g(char*s,char*r){char*q=r;for(;*q=*s;q+=q==strchr(r,*s++));}

// @AShelly - keep a histogram of the usage of each character
h(char*s){int a[128]={0};for(;*s;s++)a[*s]++||putchar(*s);}

// @hvd     - modify in place
i(char*s){char*q=s,*p=s;for(;*q=*p;q+=q==strchr(s,*p++));}

/* original version - commented out because it requires -std=c99
void f(char*s,char*r){for(char*q=r;*s;s++)if(!strchr(r,*s))*q++=*s;}
*/

// The test program:
int main(int argc,char*argv[]){
  char *r=calloc(strlen(argv[1]),1); // make a variable to store the result
  g(argv[1],r);                      // call the function
  puts(r);                           // print the result

  h(argv[1]);                        // call the function which prints result
  puts("");                          // print a newline

  i(argv[1]);                        // call the function (modifies in place)
  puts(argv[1]);                     // print the result
}

```

Thanks for all the help. I appreciate all the advice given to shorten so much!

# Answer
> 4 votes
# Haskell, 29 bytes

Nestable, no-variable-name one-liner:

```
foldr(\x->(x:).filter(x/=))[]

```

Same count, saved into a function named `f` as a top-level declaration:

```
f(x:t)=x:f[y|y<-t,x/=y];f_=[]

```

Note that there is a slightly-cheating optimization which I haven't made in the spirit of niceness: it is technically still allowed by the rules of this challenge to use a different input and output encoding for a string. By representing any `string` by its partially-applied Church encoding `\f -> foldr f [] string :: (a -> [b] -> [b]) -> [b]` (with the other side of the bijection provided by the function `($ (:))`) this gets golfed down to `($ \x->(x:).filter(x/=))`, only 24 characters.

I avoided posting the 24-character response as my official one because the above solution could be tried on the above interpreter as `foldr(\x->(x:).filter(x/=))[]"Type unique chars!"`whereas the golfed solution would be written instead:

```
($ \x->(x:).filter(x/=))$ foldr (\x fn f->f x (fn f)) (const []) "Type unique chars!"

```

as a shorthand for the literal declaration which would be the more-insane:

```
($ \x->(x:).filter(x/=))$ \f->f 'T'.($f)$ \f->f 'y'.($f)$ \f->f 'p'.($f)$ \f->f 'e'.($f)$ \f->f ' '.($f)$ \f->f 'u'.($f)$ \f->f 'n'.($f)$ \f->f 'i'.($f)$ \f->f 'q'.($f)$ \f->f 'u'.($f)$ \f->f 'e'.($f)$ \f->f ' '.($f)$ \f->f 'c'.($f)$ \f->f 'h'.($f)$ \f->f 'a'.($f)$ \f->f 'r'.($f)$ \f->f 's'.($f)$ \f->f '!'.($f)$ const[]

```

But it's a perfectly valid version of the data structure represented as pure functions. (Of course, you can use `\f -> foldr f [] "Type unique chars!"` too, but that is presumably illegitimate since it uses lists to actually store the data, so its foldr part should then presumably be composed into the "answer" function, leading to more than 24 characters.)

# Answer
> 4 votes
# Python 3, 26 bytes

```
lambda s:[*dict(zip(s,s))]

```

Try it online!

Reviving an ancient question with a new idea, inspired by Noodle9's solution to "Special String reformatting" and my further refinement.

Because Python 3's dictionaries automatically remove duplicate keys beyond the first appearance while keeping them in order, we convert the the input string to a dictionary as keys. We then convert the dictionary back to a list with iterable unpacking, which extracts its keys. (The challenge seems to be fine with a list of characters in lieu of a string, asking for a "sequence of chars".)

While we could make the dictionary via a comprehension like `{c:1for c in s}`, it's one byte shorter to use the `dict` constructor as `dict(zip(s,s))`, which each character is both the key and the values. A same-length alternative is `{}.fromkeys(s)`.

Note that while `set` does also remove duplicates, it fails to keep them in order, and is also disallowed by the challenge.

# Answer
> 3 votes
# Java, 79 bytes

It's java, and it may be a little bit shorter than some of the more wordy esoteric languages.

But still, java.

```
s->{String r="";for(char c:s.toCharArray())r+=(r.indexOf(c)>-1)?"":c;return r;}

```

Explanation:

```
s->{ //Lambda expression opening, note that java can infer the type of s

    String r=""; //Initializes String r

    for(char c:s.toCharArray()) //Iterates through the string

        r+=(r.indexOf(c)>-1)?"":c; //indexOf(c) returns -1 if there are no occurrences

    return r;

}

```

# Answer
> 3 votes
## Befunge-93, 124 bytes

```
v
<v1p02-1
0_v#`g00: <0_@#+1::~p
 1>:1+10p2+0g-!#v_v
g `#v_10g0^       >:10g00
 ^0g 00$        <
 ^  >:,00g1+:00p1+:1+01-\0p

```

Test it in this online interpreter.

---

This was more difficult than I expected. I'll post a fuller explanation tomorrow if anyone wants me to, but here's an overview of what my code does.

* Unique characters seen so far are stored on the first row, starting from `2,0` and extending to the right. This is checked against to see if the current character is a duplicate.
* The number of unique characters seen so far is stored in `0,0` and the check-for-duplicate loop counter is stored in `1,0`.
* When a unique character is seen, it is stored on the first row, printed out, and the counter in `0,0` is incremented.
* To avoid problems with reading in the spaces present (ASCII 32), I put the character corresponding to -1 (really, 65536) in the next slot for the next unique character.

# Answer
> 3 votes
# Scala, 118114 bytes

```
def f(a:String):String=a.zipWithIndex.groupBy(_._1.toLower).map(_._2.head).toList.sortBy(_._2).map(_._1).mkString

```

# Answer
> 3 votes
## C, 96 bytes

```
#include<stdio.h>
int c,a[128];main(){while((c=getchar())-'\n')if(!a[c])a[c]=1,putchar(c);}

```

This uses an array of integers, indexed by ASCII character number. The characters are only printed if that place in the array is set to FALSE. After each new character is found that place in the array is set to TRUE. This takes a line of text from standard input, terminated by a newline. It ignores non-ASCII characters.

---

Ungolfed:

```
#include<stdio.h>
#include<stdbool.h>

int main(void)
{
  int i, c;
  int ascii[128];
  for (i = 0; i < 128; ++i) {
    ascii[i] = false;
  }
  while ((c = getchar()) != '\n') {
    if (ascii[c] == false) {
      ascii[c] = true;
      putchar(c);
    }
  }
  puts("\n");
  return(0);
}

```

# Answer
> 3 votes
# PHP, ~~56~~ 54

```
// 56 bytes
<?=join('',array_flip(array_flip(str_split($argv[1]))));

// 54 bytes
<?=join(!$a='array_flip',$a($a(str_split($argv[1]))));

```

Edging out @fschmengler's answer using `array_flip` twice - second version uses variable method and relies on casting the string to true, negating it to false, then casting it back to the empty string in the first argument to save a couple of bytes in the second. Cheap!

# Answer
> 3 votes
# C, 47 bytes

```
a[];main(c){for(;read(0,&c,1);write(!a[c]++));}

```

# Answer
> 3 votes
# Simplex v.0.7, ~~22~~ 10 bytes

```
s^oR^l^Ryg
s          ~~ string input
 ^o        ~~ convert to tuple
   R       ~~ go right
    ^l     ~~ unicode tuple
      ^R   ~~ take intersection
        yg ~~ convert to string and output

```

~~*sigh* Minkolang is kicking Simplex's butt.~~

~~```
s^[oZ%_Q]n?[^_s^~M^=]]
s                      ~~ string input
 ^[     ]              ~~ postfixes each of the inner with a ^
   o                   ~~ convert to tuple
    Z                ] ~~ fold
     %                 ~~ tuple w/out current character + increment
      _                ~~ current character
       Q               ~~ membership
         n?[        ]  ~~ if current character not in tuple
            ^_s^~M^=   ~~ print that character

```~~

# Answer
> 3 votes
# Vim, 23 keystrokes

```
qq:s/\v(.).*\zs\1<cr>@qq@q

```

Explanation:

```
qq                           " Start recording into register 'q'
  :s/                        " Search and replace:
      \v                     " Enable 'magic', which just makes regexes a littl shorter
        (.)                  " Any symbol, captured in group one
           .*                " Anything
             \zs\1           " Start selection, group one
                             " Replace with nothing
                  <cr>       " Globally
                      @q     " Call macro q. Since we are still recording, this will not do anything the first time, and create a loop the next time
                        q    " Stop recording.
                         @q  " Start the loop. This will run until there is no match.

```

Since V is backwards compatible, you can Try it online!

# Answer
> 3 votes
# 05AB1E, ~~5~~ 4 bytes

```
ʒkNQ

```

Try it online or verify all test cases.

Slightly more interesting previous 5 bytes version:

```
SkāαÏ

```

Try it online or verify all test cases.

**Explanation:**

```
ʒ     # Filter the characters in the (implicit) input-string by:
 k    #  Get the first index of the current character in the (implicit) input-string
  NQ  #  Check if it's equal to the filter-index
      # (after which the result is output implicitly)

S     # Convert the (implicit) input-string to a list of characters
 k    # Get the first 0-based index of each character in the (implicit) input-string
  ā   # Push a list in the range [1, list-length] (without popping)
   α  # Get the absolute difference between the values at the same positions in the lists
    Ï # Keep the characters of the (implicit) input-string at the truthy (==1) indices
      # (after which the result is output implicitly)

```

With builtins allowed, this would of course be a single byte: `Ù`
Try it online or verify all test cases.

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

```
{x@&(!#x)=x?x}

```

Try it online!

A ngn/k implementation of the classic APL idiom for unique-ifying a list.

* `x?x` find the indices of the first time each character appears in the input
* `(!#x)` generate 0..n, where n is the length of the input
* `(...)=...` build boolean list storing whether or not the first index of each character in the input is the same as the index of each character
* `x@&` filter input to the indices where the above is true

# Answer
> 3 votes
# GNU AWK, 35 34 bytes

```
BEGIN{RS=".|";ORS=e}!a[RT]++,$0=RT

```

Try it online!

This is a major edit of my first version. In fact, it changed entirely. Only works in GNU AWK, due to the `RT` variable.

```
BEGIN{RS=".|";ORS=e}

```

`RS=".|"` works like the `/./` regex, so every character of the input is considered a record separator. The practical use is that `RT` returns each character at a time. `ORS=e` prevents newlines from appearing.

```
!a[RT]++,$0=RT

```

A simple AND gate. This is a range pattern. The left part: current `RT` element of the `a` array is incremented by 1, but it is evaluated by the NOT gate before the increment. Returns TRUE only the first time a character appears. The right part: assigns the current character (`RT`) to the input/output `$0`; only happens when beginning pattern is true, i.e., the first time a character appears.

### AWK, 48 bytes (former answer)

```
split($0,a,e){for(i in a)printf a[j=a[i]]++?e:j}

```

Try it online!

```
{
split($0,a,e); # Splits the input into the _a_ array, one char for each element.
               # _e_ variable is not assigned, and returns "".

for(i in a)            # For each element _i_ of the array _a_,
  printf
         a[j=a[i]]++?  # if the element a[i] (AKA j) is positive (i.e, true),
                  ^--- (This also increments this element by 1 after evaluating it)
                   e:  # prints _e_ (AKA "")
                   j   # if it's zero (AKA not assigned, AKA false), prints a[i].
}

```

# Answer
> 3 votes
# i386 machine code, ~~22~~ 21 bytes

Machine code:

```
00000034  6a 20 59 6a ff e2 fc 91  ac d0 2c 04 71 01 aa e2  |j Yj......,.q...|
00000044  f7 83 ec 80 c3                                    |.....|
00000049

```

Commented assembly:

```
        .intel_syntax noprefix
        .globl .type_uniqchars
        // dst: EDI: output buffer (must be big enough)
        // src: ESI: input string
        // len: EAX: length of string
.type_uniqchars:
        // Set ECX to 32
        push    32
        pop     ecx
        // Create a 128 byte buffer on the stack of all 1 bits
        // by pushing -1 32 times.
        // We only need 128 bytes because we know that
        // we are only dealing with ASCII.
.Lpush_loop:
        push    -1
        loop    .Lpush_loop
.Lpush_loop.end:
        // ECX = len
        // EAX = 0 (because of the loop)
        xchg    ecx, eax
.Lloop:
        // AL = *src++;
        lodsb   al, byte ptr [esi]
        // This is taking advantage of this quirk with SHR:
        //
        //   The OF flag is affected only on 1-bit shifts [...]
        //   For the SHR instruction, the OF flag is set to the
        //   most-significant bit of the original operand.
        //
        // So basically, we do this:
        //
        //     unique     duplicate
        //   0b11111111  0b01111111
        //     |\\\\\\\    |\\\\\\\
        //  OF:1||||||| OF:0|||||||
        //   0b01111111  0b00111111
        //
        // I chose this over INC+JNZ because this will never
        // overflow: it will just stay at zero.
        shr     byte ptr [esp + eax]
        // No overflow means duplicate
        jno     .Lloop.duplicate
.Lloop.unique:
        // *dst++ = AL
        stosb   byte ptr [edi], al
.Lloop.duplicate:
        // Loop while there is still data
        loop    .Lloop
.Lloop.end:
        // Clean up the stack and return.
        // Note that sub esp, -128 is smaller than add esp, 128.
        sub     esp, -128
        ret

```

Try it online!

```
char *.type_uniqchars(char *dst {edi}, const char *src {esi}, size_t len {eax})

```
* `src` is a pointer to the input string
* `dst` is a pointer to an output buffer, it must be large enough
* `len` is the length of `src` in bytes.

A pointer one byte past the end of the output string will be returned in `edi`. However, in the test code, I just null terminate because it is easier to print that way.

Doesn't follow standard calling convention, hence the leading dot.

### Explanation (see comments for more)

This uses a lookup table on the stack, which is set to `-1`. It is 128 bytes because we are only dealing with ASCII.

Then, this magic is used:

```
        shr     byte ptr [esp + eax]
        jno     .Lloop.duplicate

```

This uses the fact that a one bit `shr` will put the *most* significant bit in the overflow flag. The first time, the overflow flag will be set since all bits are set, but then that most significant bit will be shifted out.

Unlike something like this:

```
        inc     byte ptr [esp + eax]
        jnz     .Lloop.duplicate

```

You could run this 1, 10, 100000 times, and it will never fail. That `inc` solution will fail after 256 duplicates as it wraps around to zero. Shifting right will just end up at zero and stay there indefinitely.

Other than that, it is a pretty straightforward string copy routine.

# Answer
> 3 votes
# ngn/k (2 bytes)

```
!=

```

`=` produces a dict that shows where each element is located, `!` takes the keys.

# Answer
> 3 votes
# Vyxal, 2 bytes

```
ƒ∪

```

Try it Online!

Reduce by set union. Port of caird's answer.

# Vyxal, 3 bytes

```
ÞU*

```

Try it Online!

Multiply by uniquify mask.

# Answer
> 3 votes
## C - 88 Bytes

```
r[99];b;a;main(i){for(;read(i=0,&b,1);99-i?b=0:putchar(r[a++]=b))for(;i<99&&b-r[i++];);}

```

Thanks to @ceilingcat because I saved 20 bytes with his modification.

**Ungolfed**

```
r[99]; b; a;

main(i) {
    for(; read(0, &b, 1); 99 - i?b = 0: putchar(r[a++] = b))
       for(i = 0; i < 99 && b - r[i++]; ); }

```

**Explanation**

Characters are read from the console, which are searched for within a list containing all the repeated characters found so far, as the characters are read, the list is updated, with new characters being added at the end of the list. If a character is repeated it is not printed.

This code was tested on GCC and it generates some warnings but it compiles and works fine (although it is not the most optimized code).

# Answer
> 2 votes
# Matlab, 46 bytes

It uses an anonymous function, with function arguments as input and output:

```
@(s)eval('s(~any(triu(bsxfun(@eq,s,s''),1)))')

```

(I couldn't get this to work in an Octave online interpreter.)

Example use:

```
>> @(s)eval('s(~any(triu(bsxfun(@eq,s,s''),1)))')
ans =
    @(s)eval('s(~any(triu(bsxfun(@eq,s,s''),1)))')

>> ans('Type unique chars!')
ans =
Type uniqchars!

```

# Answer
> 2 votes
# AutoIt, 107

```
Func _($0)
$1=''
For $2 In StringSplit($0,'',3)
$1&=StringInStr($1,$2,1)?'':$2
Next
Return $1
EndFunc

```

Call it like any function:

```
ConsoleWrite(_("Type unique chars!"))

```

# Answer
> 2 votes
# CJam, 9

```
Lq{1$-+}/

```

This doesn't convert a string to a set, but it performs a kind of set difference to determine whether a character is found in a string. Try it online

**Explanation:**

```
L       push an empty array/string
q       read the input
{…}/    for each character in the input
  1$    copy the previous string
  -     subtract from the character (set difference),
         resulting in the character or empty string
  +     append the result to the string

```

### Another version, 13 bytes:

```
Lq{_2$#)!*+}/

```

This doesn't do anything related to sets. Try it online

**Explanation:**

```
L       push an empty array/string
q       read the input
{…}/    for each character in the input
  _     duplicate the character
  2$    copy the previous string
  #)    find the index of the character in the string and increment it
  !     negate, resulting in 0 if the character was in the string and 1 if not
  *     repeat the character that many times
  +     append the result to the string

```

# Answer
> 2 votes
# Haskell, 50

```
f=concat.(tail>>=zipWith(\x y->[last x]\\y)).inits

```

# Answer
> 2 votes
# Delphi, 111 bytes

```
procedure u(var s:string);var i:word;begin for i:=length(s) downto 1 do if pos(s[i],s)<i then delete(s,i,1)end;

```

Using the procedure to alter the passed in string - saves a few bytes in comparison to declaring the function. Moving backwards through the string, delete the current character if it is not the first location of that character

# Answer
> 2 votes
# JavaScript (ES6) 46

```
f=s=>[...s].map(c=>s[c]?'':s[c]=c,s=[]).join``

```

Unexpectedly, this time the flag array is one byte shorter than the indexOf approach.

# Answer
> 2 votes
## Haskell, 33 bytes

```
foldl(\r c->r++[c|notElem c r])[]

```

Uses `foldl` to iterate through the string appending characters that are not in the current result, starting with the empty string (list).

# Answer
> 2 votes
# Powershell, 30

```
$args-replace'(.)(?<=\1.+)',''

```

I feel there's likely to be a better regex than this, and I can't work out what it is

# Answer
> 2 votes
# SED, 61 bytes

```
s/^/\a/
:
s/\a\(\(.\).*\)\2/\a\1/
t
s/\a\(.\)/\1\a/
t
s/\a//

```

# Answer
> 2 votes
# Perl 5.10+, 21 bytes

```
perl -pe '1while s/(.).*\K\1//'

```

20 bytes + 1 byte for `-p`. Note that Perl 5.10 or above is required for `\K`.

Takes input from stdin:

```
$ echo 'Type unique chars!' | perl -pe '1while s/(.).*\K\1//'
Type uniqchars!

$ echo \"I think it\'s dark and it looks like rain\", you said | perl -pe '1while s/(.).*\K\1//'
"I think'sdarloe,yu

$ echo 3.1415926535897932384626433832795 | perl -pe '1while s/(.).*\K\1//'
3.14592687

```

Online demo

---

Inspired by NinjaBearMonkey's Retina answer. Perl may not have a compact way to re-run a substitution until nothing changes, but it does have `\K`, which causes the regex engine to "keep" everything to its left. This allows you to drop a set of parentheses on the LHS and a capture variable on the RHS:

```
s/(.).*\K\1//   # 13 bytes

```

vs.

```
s/((.).*)\2/$1/ # 15 bytes

```

# Answer
> 2 votes
## Minkolang 0.10, 13 bytes

This language was made after this challenge but not *for* this challenge.

Much thanks to **Sp3000** for pointing me the way to this much shorter solution.

```
od?.dd0q?Od0p

```

Try it here.

### Explanation

```
od               Read character from input and duplicate it (for the conditional)
  ?.             Stop if 0 (i.e., input is empty)
    dd           Duplicate twice (for q and for possible output)
      0q         Gets value stored in (character,0) in the codebox (0 if empty)
        ?O       Outputs character if it's unique (i.e. the previous value was 0)
          d0p    Puts the value of the character at (value,0) in the codebox

```

# Answer
> 2 votes
# AppleScript, ~~143~~ 142 Bytes

```
set x to(display dialog""default answer"")'s text returned's characters
set o to""
repeat with i in x
if not i is in o then set o to o&i
end
o
```

Not a language for golfing, but it's very readable.

# Answer
> 2 votes
# Octave, 25 bytes

```
@(s)s(sum(triu(s'==s))<2)

```

# Answer
> 2 votes
# Javascript (ES6), 47 bytes

```
a=>[...a].filter((b,c)=>a.indexOf(b)==c).join``

```

**Test it here**

Some code is added to have a better input and to write to the console the result.

```
d=document,g=d.getElementById.bind(d);g("s").onclick=e=>console.log((a=>[...a].filter((b,c)=>a.indexOf(b)==c).join``)(g("t").value))
```

```
<input id="t"><button id="s">Convert</button>
```

# Answer
> 2 votes
# Ruby, 19 + 1 = 20 bytes

Uses the `-p` flag. Uses set operations like the GolfScript answer, which is *totally* not a built-in like `uniq`. (Performing set `or` on a list and an empty list purges the list of duplicates, just like calling `and` against a copy of itself.)

```
$_=($_.chars|[])*""

```

# Answer
> 2 votes
# Jelly, 3 bytes

```
œ|/

```

Try it online!

Simply reduces by set union

Slightly more creative, but relies on "unique sieve" functions not being banned:

```
xŒQ

```

Try it online!

## How it works

```
xŒQ - Main link. Takes a string S on the left
 ŒQ - Unique sieve; For each character in S, replace it with 1 if it hasn't occurred yet, else 0
x   - Repeat each character in S according to the corresponding value in the sieve
    - Implicitly print, mashing empty strings into the output

```

# Answer
> 2 votes
# Pyth, 8 bytes

```
s.gxQk.|

```

Try it online!

1. Bitwise Or the input
2. Group the input by:
3. It's index in the original input
4. Join list and print.

# Answer
> 1 votes
# Python 3, ~~132~~ ~~109~~ 105 bytes

```
u=[]
def t(l):
 if l in u:return''
 else:
  u.append(l);return l
print(''.join([t(l)for l in input()]))

```

**Ungolfed:**

```
used_chars = []
def test(letter):
    if letter in used_chars:
        return '' # skip
    else:
        used_chars.append(letter)
        return letter
print(''.join([test(letter) for letter in input()]))

```

# Answer
> 1 votes
# Python 2, 79

```
def S(s):
 s=s[::-1]
 for c in s:s=s.replace(c,'',s.count(c)-1)
 return s[::-1]

```

It reverses the input string, cycles through it, replaces any extra characters with null ones and returns the reverse of that. The reverse is so the last characters are removed, not the first.

```
>>> S('''"I think it's dark and it looks like rain", you said''')
'"I think\'sdarloe,yu'
>>> S("3.1415926535897932384626433832795")
'3.14592687'
>>> S("Type unique chars!")
'Type uniqchars!'

```

# Answer
> 1 votes
# MUMPS, 54 bytes

```
f(s) f i=1:1:$L(s) s c=$E(s,i) s:t'[c o=o_c,t=t_c
    q o

```

Not terribly exciting - it just keeps a running list of already-viewed characters and only appends to the output string if the current character isn't in that list.

# Answer
> 1 votes
# Ceylon, 98 bytes (stdio) / 69 bytes (function)

This version is using stdio and a HashSet, 98 bytes:

```
import ceylon.collection{H=HashSet}shared void u(){print(String(H{*(process.readLine()else"")}));}

```

This is just a function String → String (also using a HashSet), 69 bytes:

```
import ceylon.collection{H=HashSet}String n(String i)=>String(H{*i});

```

Ungolfed version:

```
import ceylon.collection {
    HashSet
}
void uniq() {
    value input = process.readLine() else "";
    value set = HashSet { elements = input; };
    print(String(set));
}

```

A Ceylon HashSet by default is linked (i.e. conserves the insertion order as iteration order). We use here the named-argument syntax to pass the `elements` argument to the HashSet constructor.

A string is also an iterable of characters, and as such can be passed to the elements parameter. A string can also be constructed from such a sequence, which is what we do in the last command.

The golfed version again: `import ceylon.collection{H=HashSet}shared void u(){print(String(H{*(process.readLine()else"")}));}`

Some used tricks:

* Variable inlining
* If we have to import HashSet anyways, give it a shorter name.
* The named-argument syntax accepts also a "normal" argument list. Any arguments in that list will be, if they don't fit the other arguments, be wrapped in an Iterable and passed to an Iterable argument (if there is one). To spread our existing iterable (the input string) into such an argument list, we use the "spread operator `*`".

If we don't have to handle standard-input and output and just need a function, this is shorter:

```
import ceylon.collection{HashSet}
String n(String i) => String(HashSet{*i});

```

The explanations from above are still valid.

# Answer
> 1 votes
# Ceylon, 98 bytes (stdio) / 68 bytes (function)

Here is a version without using Set or similar stuff, as a function (68 bytes):

```
String i(String s)=>String{for(x->c in s.indexed)if(!c in s[0:x])c};

```

The same with stdio (reading just one line) (98 bytes):

```
void q(){value s=process.readLine()else"";print(String{for(x->c in s.indexed)if(!c in s[0:x])c});}

```

The first one ungolfed (117 bytes):

```
String i(String s) => String{
        for (x->c in s.indexed)
            if (!c in s[0:x])
                c
    };

```

This uses the feature to build a string from an iterable of characters, but this time the iterable is build from a comprehension, which is passed to the string-constructor using the named-argument-list syntax. (This could also have been written as `String({...});`, using a positional argument list and an iterable-constructor, but that would have been two bytes more).

The comprehension consists of a for-clause (which iterates over an indexed version of the input string, i.e. x is the index corresponding to the character `c`) and an if-clause (which filters the character by checking if it appears in the substring up to the index).

We see here two different uses of the keyword `in` – once as part of the syntax of the `for` clause of comprehensions, and once as the `in` operator, which maps to `s[0:x].contains(c)`.

The "thin arrow" in `x->c` is the syntax for an Entry made of `x` and `c` (as key and value). As an expression one can build an entry this way from its constituents, but here it is a part of the comprehension syntax (and also the syntax of the for-loop), and deconstructs the entry which is returned by the iterator of the iterable `s.indexed`.

The "fat arrow" `=>` is a shorthand for defining a function whose body consists of just one expression (which is evaluated and returned) – that saves us the `return` and a pair of braces.

The variant which uses stdio:

```
void q() {
    value s = process.readLine() else "";
    print(String { for (x->c in s.indexed)
                if (!c in s[0:x])
                    c });
}

```

Unfortunately we need a variable here to store the string, because we need to access it twice (in the loop and in the filter).

---

Instead of using an Iterable comprehension, we can also use the stream-manipulating method `filter` together with the spread attribute operator `*.` and a lambda expression `(e)=>!e.item in s[0:e.key]` inbetween:

```
String j(String s)=>String(s.indexed.filter((e)=>!e.item in s[0:e.key])*.item);

```

This is even longer with 79 bytes.

# Answer
> 1 votes
# Rust, 318 Bytes

not really a competitor, but rust needs a bit more love. As always, comments and advice welcome.

```
use std::io;fn main(){let mut s=io::stdin();let mut b=String::new();s.read_line(&mut b).unwrap();let mut n: Vec<char>=b.chars().collect();for i in 0..n.len()-2{let mut j=i+1;let mut p = true;while j<n.len(){if j<n.len(){if n[i]==n[j]{n.remove(j);p=false;}}if p{j+=1;}p=true;}}for i in 0..n.len()-2{print!("{}",n[i]);}}

```

Try it online here (first compile, then execute, then click into the proper area to enter user input)

ungolfed:

```
use std::io;
fn main() {
let mut s = io::stdin();
let mut b=String::new();
s.read_line(&mut b).unwrap();
let mut chars: Vec<char> = b.chars().collect();
for i in 0..chars.len()-2 {
    let mut j=i+1;
    let mut inc = true;
    while j<chars.len() {
        if j<chars.len()
        {
            if chars[i]==chars[j] {
                chars.remove(j);
                inc = false;
            }
        }
        if inc {
            j+=1;
        }
        inc = true;
    }
}
for i in 0..chars.len()-2 {
    print!("{}",chars[i]);
}
}

```

# Answer
> 1 votes
# Python 2, 62 bytes

```
s=set();print filter(lambda i:not(i in s or s.add(i)),input())

```

# Answer
> 1 votes
# Python, 62 bytes

```
lambda s:''.join([c for i,c in enumerate(s)if c not in s[:i]])

```

# Answer
> 1 votes
# Scala, ~~79~~, 66 bytes

Inspired by the Haskell version using foldLeft

```
def f(s:String)=s.foldLeft("")((a,c)=>if(a.contains(c))a else a+c)

```

Previous version using zipWithIndex and collect

```
def f(s:String)=s.zipWithIndex.collect{case(c,i)if s.indexOf(c)==i=>c}.mkString

```

# Answer
> 1 votes
## Perl 6, 32 bytes

The way you would normally write this would be:

```
$*IN.comb.unique.print # it would have been 22

```

Which would have had the benefit of being obviously correct.

---

Instead I have to write something like the following

```
print $*IN.comb.grep:{!.{$^a}++} # 32

```

# Answer
> 1 votes
# Gema, 18 characters

```
?=${?;$0}@set{$0;}

```

Sample run:

```
bash-4.3$ gema '?=${?;$0}@set{$0;}' <<< 'hello world'
helo wrd

```

# Answer
> 1 votes
## R, 52 bytes

```
cat(union(a<-strsplit(readline(),"")[[1]],a),sep="")

```

Test examples:

```
Type uniqchars!
"I think'sdarloe,yu
3.14592687

```

# Answer
> 1 votes
# RProgN, 85 Bytes

```
S i 'a' = s 'n' = a L while a pop 'b' = n b hasvalue ! if n b push end a L end n i ++

```

# Explanation

```
S i                     # Take the implicit string input, convert it to a stack such that the first letter is at the bottom, invert the stack such that the first letter is at the top.
'a' =                   # Associate it with 'a'
s 'n' =                 # Create a new stack, associate it with 'n'
a L                     # Push the size of a
while                   # While the top of the stack contains a truthy value
    a pop 'b' =         # Pop the top of a, associate it with 'b'
    n b hasvalue !      # Push if the stack 'n' does not contain b
    if                  # If the top of the stack is truthy
        n b push        # Push b to the stack n
    end                 #
    a L                 # Push the length of a
end                     # loop
n i ++                  # Push the n, inverts it, sums it, which acts to concatenate it, implicitly print the result.

```

# Answer
> 1 votes
## REXX, 79 bytes

```
a=arg(1)
o=
do while a>''
  parse var a b+1 a
  if pos(b,o)=0 then o=o||b
  end
say o

```

# Answer
> 1 votes
# Python, ~~61~~ 59 bytes

```
lambda s:''.join(i for c,i in enumerate(s)if s.index(i)==c)

```

`str.index` always returns the first occurrence, so only output the character if the current occurrence is the first occurrence.

Edit: The square brackets were unnecessary.

# Answer
> 1 votes
# PHP, 47 Bytes

```
for(;a&$c=$argn[$i++];)$r[$c]=$c;echo join($r);

```

Try it online!

# Answer
> 1 votes
# sed -E, 21 bytes

```
:L;s/((.).*)\2/\1/;tL

```

Try it online!

# Answer
> 1 votes
# Stax, 5 bytes

```
╤•╗jP

```

Run and debug it

# Answer
> 1 votes
# Red, 23 bytes

```
func[s][union/case s s]

```

Try it online!

## Using a `map!`, 58 bytes

```
func[s][m: copy #()foreach c s[put m c c]rejoin keys-of m]

```

Try it online!

## A naive implementation, 69 bytes

```
func[s][rejoin collect[foreach c s[unless find collected c[keep c]]]]

```

Try it online!

# Answer
> 1 votes
# Lua, 70 bytes

```
l={}print(((...):gsub('.',function(c)c=l[c]or c;l[c]=''return c end)))

```

Attempt This Online! Stores the characters in the table after gsub walks through the whole string. Strings are truthy values in Lua so when `list[character]` is nil, the character is returned the first time then it is replaced with an empty string after the assignment.

# Answer
> 1 votes
# Lexurgy, 30 bytes

Due to how Lexurgy handles whitespace, it expects whitespace to be replaced with some other character, such as `_`.

```
a propagate:
[]$1=>*/$1 []* _

```

### Explanation

```
a propagate:        # rule a: while the current string changed last run...
[]$1                # match anything...
    =>              # and replace with...
      *             # empty string
       /            # when the input...
        $1          # starts with the captured char
          []*       # followed by any number of anything
             _      # then a captured char

```

# Answer
> 1 votes
# nanoMIPS machine code, 34 bytes

```
00000000: 80 1c a0 d3 fc 90 a7 23 87 04 80 bb c0 5f 89 90  .......#....._..
00000010: a7 23 07 30 00 bb a7 23 87 38 d4 5f a9 90 80 bb  .#.0...#.8._....
00000020: 80 1d                                            ..

```

Commented assembly:

```
    .globl uniqchars
    # Type uniqchars! for nanoMIPS, Yet Another Weird MIPS Extension
    # Follows C calling convention
    #    void uniqchars(const char *input, char *output);
    # Input:
    #    a0: pointer to a null terminated ASCII string
    #    a1: pointer to an adequately sized buffer
    # Output:
    #    Null terminated ASCII string stored to a1
uniqchars:
    # Create a 128 byte stack buffer for a lookup table
    # Equivalent normieMIPS:
    #  addiu $sp, -128
    save     128
    # Clear the buffer
    li       $a3, 128 / 4
.Lclear:
    # Decrement index
    addiu    $a3, -4
    # Behold! MIPS finally added register-register addressing!
    # And only like 31 years late!
    #  addiu $at, $sp, $a3
    #  sw    $zero, ($at)
    swx      $zero, $a3($sp)
    # Loop if not zero
    bnez     $a3, .Lclear
    # Loop through the string
.Lloop:
    # Load byte from a0
    lb       $a3, ($a0)
    # Increment pointer
    addiu    $a0, 1
    # Load byte from lookup table
    lbx      $a2, $a3($sp)
    # If it is nonzero, this char is not unique. Try the next one.
    bnez     $a2, .Lloop
    # Store the char itself to the lookup table
    sbx      $a3, $a3($sp)
    # Store the char to the output string
    sb       $a3, ($a1)
    addiu    $a1, 1
    # Loop if it was not a null terminator
    bnez     $a3, .Lloop
    # Clean up the stack and return
    #  addiu $sp, 128
    #  jr    $ra
    restore.jrc 128

```

This uses the new nanoMIPS calling convention, and can be called from C with the following prototype:

```
void uniqchars(const char *input, char *output);

```

Yes. This is the *third* compressed variant of the MIPS instruction set. All three of which are incompatible.

> At least it golfs decently.

Aside from a few "hybrid instructions" added, it is just normal MIPS in shorthand.

A GCC toolchain, QEMU port, and documentation links are in the link above. Note that for some reason the Windows port lacks `qemu-nanomips` and both Linux and Windows versions crash on my system unless I run it in `qemu-x86_64` itself.

# Answer
> 1 votes
# Thunno 2 `J`, 1 byte

```
ċ

```

Attempt This Online!

Takes the set union with itself (set operations were allowed by OP).

### Thunno 2 `J`, 11 bytes

```
{DȤsƇ¬?ȥ;}Ȥ

```

Attempt This Online!

A different answer that doesn't use sets.

#### Explanation

```
{DȤsƇ¬?ȥ;}Ȥ  # Implicit input
{        }   # For each character in the input:
 D           #  Duplicate it
  Ȥs         #  Push the global array and swap
    Ƈ¬?      #  If it's not in the global array:
       ȥ;    #   Add it to the global array
          Ȥ  # After the loop, push the global array
             # Implicit output, joined

```

# Answer
> 1 votes
# Rockstar, 126 bytes

```
Listen to I
Cut I
O's ""
While I
Roll I in C
X's 0
P's 1
While O at X
If C's O at X
P's 0

Build X up

If P
Let O be+C

Say O

```

Try it (Code will need to be pasted in)

Or, if we can output each character individually, on a separate line ...

## 124 bytes

```
Listen to I
Cut I
O's ""
While I
Roll I in C
X's 0
P's 1
While O at X
If C's O at X
P's 0

Build X up

If P
Let O be+C
Say C

```

# Answer
> 0 votes
# Z80Golf, 13 bytes

```
00000000: cd 03 80 38 04 26 ff 6f cb 76 74 c5 c0           ...8.&.o.vt..

```

Try it online!

Commented assembly:

```
start:
.loop:
    call  0x8003         ; CD 0380  Read from stdin to A, C is success
    jr    c, .end + 1    ; 38 04    Jump to the 76 in the middle of the bit opcode to halt
    ld    h, 0xFF        ; 26 FF    HL = 0xFFxx
    ld    l, a           ; 6F       HL = 0xFF00+A, address + offset of LUT
.end:
    bit   6, (hl)        ; CB 76    Test bit 6 of the table
    ; halt               ;   (76)      Exit the program with halt (overlaps)
    ld    (hl), h        ; 74       Mark the LUT to 0xFF
    push  bc             ; C5       Push address of .loop for ret (BC is 0x0000)
    ret   nz             ; C0       If bit 6 was set (not unique), ret to .loop
                         ;          otherwise fall through to putchar

```

This uses the LUT method in my other answers. However it is much easier on Z80Golf because I know the full state of the machine and can optimize for it.

Specifically, I know that the 128 bytes at `0xFF00-0xFF7F` will be 0, so I can use that by setting the high byte of HL and the low byte of A.

There are some weird optimizations to make this smaller. I could get `0xFF` in `h` in one byte by `dec h`, but that introduces a state I have to check. Instead, I suck up the byte for `ld h, 0xFF` in favor of the entire program being stateless outside of the table. Then, I can use `push bc` followed by `ret nz` to loop if nonzero or fall through the nop sled to putchar otherwise.

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


# Question
Title: How powerful must this e approximation be?
This challenge was inspired by this non-challenge about the natural logarithm base \\$e\\$ and the following pandigital approximation to \\$e\\$ appearing on a Math Magic page: $$\left|(1+9^{-4^{7×6}})^{3^{2^{85}}}-e\right|$$ $$\approx2.01×10^{-18457734525360901453873570}$$ It is fairly well-known that $$e=\lim\_{n\to\infty}\left(1+\frac1n\right)^n$$ It is less well-known that the limit expression is strictly monotonically increasing over the positive real numbers. These facts together imply that for every nonnegative integer \\$d\\$ there is a **least** positive integer \\$n=f(d)\\$ such that the first \\$d\\$ decimal places of \\$(1+1/n)^n\\$ agree with those of \\$e\\$. \\$f(d)\\$ is OEIS A105053.

For example, \\$(1+1/73)^{73}=2.69989\dots\\$ and \\$(1+1/74)^{74}=2.70013\dots\\$, so \\$f(1)=74\\$.

## Task

Given a nonnegative integer \\$d\\$, output \\$n=f(d)\\$ as described above. Your code must theoretically be able to give the correct answer for any value of \\$d\\$.

This is ; fewest bytes wins.

## Test cases

The corresponding digits of \\$e\\$ are given for reference.

```
    d, n
(2. 0, 1
(7) 1, 74
(1) 2, 164
(8) 3, 4822
(2) 4, 16609
(8) 5, 743325
(1) 6, 1640565
(8) 7, 47757783
(2) 8, 160673087
(8) 9, 2960799523
(4) 10, 23018638268
(5) 11, 150260425527
(9) 12, 30045984061852
(0) 13, 30045984061852
(4) 14, 259607904633050
(5) 15, 5774724907212535

```

# Answer
# Python, 126 bytes

```
f=lambda k,s=2,r=0:(P:=10**k*(t:=s+1)**t//s**s,p:=P//t,s%2*((x:=p<r)+s)or f(k,s+[s,x*(S:=s&-s)-S//2][r>0],r or(p==P//s)*p))[2]

```

Attempt This Online!

#### Previous Python, 144 bytes

```
def f(k):
 o=p=0;P=n=1
 while p<P//n:n*=2;m=n+1;P=10**k*m**m//n**n;p=P//m
 while n+~o:T=n+o>>1;o,n,*_=[o,T,n][10**k*(T+1)**T//T**T<p:]
 return n

```

Attempt This Online!

Not the golfiest, but should, in theory, give exact values for arbitrary inputs. In practice, times out for d\>4 on ato.

### How?

Takes advantage of Python's inbuilt bigints. Uses

\\$(1+1/n)^n\<e\<(1+1/n)^{n+1}\\$

to compute the correct digits and an upper bound for n and then pinpoints n by bisection. As we always have to first compute the nth power of n+1 and only then can divide by the nth power of n this is still expensive.
> 7 votes

# Answer
# Wolfram Language (Mathematica), ~~34~~ ~~33~~ 28 bytes (~~26~~ ~~25~~ 24 characters)

```
⌊E/2/Mod[E,10^-#]+1/12⌋&

```

Try it online!

–5 bytes thanks to @CommandMaster

The exact formula is $$ n(\zeta)=\left\lceil\frac{\zeta}{e^{-W\_{-1}\left(-\frac{\ln\zeta}{\zeta}\right)}-\zeta}\right\rceil=\left\lceil\frac{e}{2(e-\zeta)}-\frac{11}{12}+O(e-\zeta)\right\rceil \approx\left\lfloor\frac{e}{2(e-\zeta)}+\frac{1}{12}\right\rfloor $$ with $$ \zeta=10^{-d}\lfloor10^de\rfloor $$ being Euler's number rounded down to *d* digits, and *W* the Lambert function. The given series-expansion of *n(ζ)* seems to be good enough to evaluate the task.

Note that we can freely replace the ceiling function `⌈…⌉` with the shifted floor function `⌊…⌋+1` because the argument cannot be an exact integer because *e* is irrational.

Here's the exact formula, golfed to 54 bytes (46 characters), to verify that the above series expansion gives correct results:

```
⌈#/(E^(-LambertW[-1,-Log@#/#])-#)⌉&@⌊E,10^-#⌋&

```

Try it online to verify up to *d*=2000. For higher values of *d*, let's estimate the probability of failure. The series expansion of *n(ζ)* underestimates the true *n(ζ)* by about 5(*e*-*ζ*)/(72 *e*), which is the next term in the series-expansion of *n(ζ)*. But *e*-*ζ*\<10^(-*d*), and so the probability of this underestimation crossing an integer (and thus fouling up the ceiling function) is less than 5×10^(-*d*)/(72 *e*). Summing these probabilities (assumed independent!) from *d*=2001 to infinity, we get a failure probability of around 3×10^(-2003). There were a lot of assumptions in this derivation (assuming independence, irrationality, ergodicity, etc.); but I think it indicates that we cannot expect any failures as *d* becomes large.

NB: I've checked up to *d*=10000 and found no deviations, thus pushing the expected failure probability to 3×10^(-10003).

PS: I've got `°Džr*ïs/žrD;r-/TÌz+ï` as a 05AB1E translation, but it does not seem very golfed (20 bytes). Help would be appreciated!
> 7 votes

# Answer
# , ~~59~~ 52 bytes

```
\(d){while(exp(1)%/%10^-d-(1+1/F)^F%/%10^-d)F=F+1;F}

```

Attempt This Online! Only works up to `d = 4` in practice, afterwards produces different results due to numerical precision issues.

Credit for -7 bytes to Dominic van Essen.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 51 bytes

```
(k=0;While[⌊10^#(1+1/++k)^k⌋!=⌊E*10^#⌋];k)&

```

Try it online!

-2 bytes from @Roman
> 4 votes

# Answer
# Vyxal, 124 bitsv1, 15.5 bytes

```
Ė›$eke"$↵vḞ?⇧vẎ≈)ṅ

```

Try it Online!

Times out for all `d` except 0. Might be due to the fact that to even find the right number for `d > 0` a minimum of \\$10^{74}\\$ digits of \\$e\\$ and the approximation need to be calculated.

## Explained

```
Ė›$eke"n↵vḞ?⇧vẎ≈)ṅ
                )ṅ # find the first positive integer n where
Ė›$e               # (1 + 1/n) ^ n
    ke"            # paired with the exact value of e
       ?n↵vḞ        # both evaluated to 10 ** n decimal places - guarantees enough digits will be generated to avoid rounding errors
           ?⇧vẎ    # each sliced to the first d + 2 characters (the 2, then the dot point, then d decimals)
               ≈   # are all the same

```
> 3 votes

# Answer
# Haskell, 63 bytes

```
n d=[n|n<-[1..],floor(10**d*(1+1/n)**n)==floor(10**d*exp 1)]!!0

```

Try it online!

# Haskell, 204 bytes, fast

```
n d=b.(\(v,w)->(last v,head w)).break p$map(2^)[0..]where
 i=fromInteger
 f=floor.(*10**i d)
 e=f$exp 1
 p n=e==f((1+1/i n)**i n)
 b(a,z)|let m=div(a+z)2=if m==a then z else if p m then b(a,m) else b(m,z)

```

Try it online!

# Haskell, 299 bytes, unlimited by `f64`

```
import Data.Ratio
n d=b.(\(v,w)->(last v,head w)).break p$map(2^)[0..]where
 f=floor.(*10^d)
 e=f.sum.scanl1(*).map(1%)$1:[1..until(\i->product[1..i]>10^d)(1+)1]
 p n=(e==).f.sum.take(16+d)$scanl(*)1[(n-k+1)%(k*n)|k<-[1..n]]
 b(a,z)|let m=div(a+z)2=if m==a then z else if p m then b(a,m) else b(m,z)

```

Try it online!
> 3 votes

# Answer
# Charcoal, 46 bytes

```
ＮθＰ×ψ⁺²θ¤≕E≔¹ηＷ‹÷×ＸχθＸ⊕ηηＸηηＩ⪫ΦＫＤ⁺²θ→⊖λω≦⊕η⎚Ｉη

```

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

```
Ｎθ

```

Input `d`.

```
Ｐ×ψ⁺²θ¤≕E

```

Write `e` to `d` decimal places to the canvas. (I don't know a better way of extracting arbitrary numbers of decimal places of `e` in Charcoal.)

```
≔¹η

```

Start with `n=1`.

```
Ｗ‹÷×ＸχθＸ⊕ηηＸηηＩ⪫ΦＫＤ⁺²θ→⊖λω

```

While `10ᵈ(1+⅟ₙ)ⁿ` is less than `10ᵈe`...

```
≦⊕η

```

... increment `n`.

```
⎚Ｉη

```

Remove `e` from the canvas and output the final value of `n`.

73 bytes for a less inefficient version based on @loopywalt's original Python answer:

```
≔ＸχＮθ≔¹η≔⁰ζＷ↨÷÷×θＸ⊕η⊕ηＸηη⟦⊕ηη⟧±¹≦⊗ηＷ∧⊖⁻ηζ÷⁺ηζ²¿↨Ｅ⟦ηι⟧÷×θＸ⊕κκＸκκ±¹≔ιζ≔ιηＩη

```

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

```
≔ＸχＮθ

```

Input `10ᵈ`.

```
≔¹η≔⁰ζ

```

Start with bounds of `0` and `1`.

```
Ｗ↨÷÷×θＸ⊕η⊕ηＸηη⟦⊕ηη⟧±¹≦⊗η

```

Double the bounds until the first `d` decimal places of `10ᵈ(1+⅟ₙ)ⁿ` are the same for both `n` and `n+1`.

```
Ｗ∧⊖⁻ηζ÷⁺ηζ²¿↨Ｅ⟦ηι⟧÷×θＸ⊕κκＸκκ±¹≔ιζ≔ιη

```

Binary search to find the smallest value of `n` with the same first `d` decimal places.

```
Ｉη

```

Output the resulting `n`.
> 3 votes

# Answer
# APL, 44 bytes (SBCS)

```
{1∘+⍣((⊢*⍨1+÷)⍤⊣=⍥((10*⍵)∘(÷⍤⊣×⌊⍤×))(*1⍨))1}

```

Explanation:

```
                                        1   Starting from 1,
1∘+                                         increment
   ⍣                                        until
     (⊢*⍨1+÷)⍤⊣                             (1+1/n)^n
               =                            is equal to
                                    *1⍨     e
                ⍥                           after both arguments to equal are processed by
                  (10*⍵)∘(÷⍤⊣×⌊⍤×)          rounding to input significant figures

```

Tested until d = 7, afterwards it gets too slow. Will probably eventually fail because of precision issues.
> 3 votes

# Answer
# 05AB1E, 17 (or 15) bytes

```
∞.Δz>ymþSžt‚I>δ£Ë

```

In theory works for an arbitrary value of \\$n\\$, but in practice times out for \\$n\geq5\\$ on TIO.

Try it online or verify the first few test cases.

Here a 2 bytes shorter approach which works up to \\$n=15\\$ (in theory again, in practice it also times out at \\$n\geq5\\$):

```
∞.Δz>ymžr‚IÌδ£Ë

```

Try it online or verify the first few test cases

**Explanation:**

```
∞.Δ            # Find the first positive integer `n` that's truthy for:
   z           #  Pop and push 1/n
    >          #  Increase it by 1
     ym        #  Take that to the power n
   þ           #  Remove the dot by only leaving its digits
    S          #  Convert this integer to a list of digits
       ‚       #  Pair it with
     žt        #  The infinite list of e: [2,7,1,...]
          δ    #  Map over the pair,
        I>     #  using the input+1 as argument:
           £   #   Only leave that many digits from both lists
            Ë  #  Check if the lists in the pair are the same
               # (after which the found integer is output implicitly as result)

```

In the 15-bytes answer, `þS` are both removed; the infinite list of digits of \\$e\\$ `žt` is replaced with its decimal value `žr` (\\$2.718281828459045\\$); and the input+1 `I>` is replaced with the input+2  to account for the dot.
> 1 votes

# Answer
# Scala, 91 bytes

Golfed version. Try it online!

```
d=>Stream.from(1).find(n=>floor(pow(10,d)*pow(1+1.0/n,n))==floor(pow(10,d)*E)).getOrElse(0)

```

Ungolfed version. Try it online!

```
import scala.math._

object Main extends App {
  def n(d: Int): Int = {
    Stream.from(1).find(n => {
      val lhs = floor(pow(10, d) * pow(1+1.0/n, n))
      val rhs = floor(pow(10, d) * E)
      lhs == rhs
    }).getOrElse(0)
  }

  (1 to 5).foreach(d => println(n(d)))
}

```
> 1 votes

# Answer
# 05AB1E, 14 bytes

```
(°žrDr%/;12z+ï

```

Try it online!

Direct translation of my Mathematica solution, with help from @CommandMaster. Works only up to *d*=7 because of machine-precision issues.

disassembly:

```
      stack
----------------------------------
      n
(     -n
°     10^(-n)
žr    10^(-n)  e
D     10^(-n)  e  e
r     e  e  10^(-n)
%     e  e%10^(-n)
/     e/(e%10^(-n))
;     e/(e%10^(-n))/2
12    e/(e%10^(-n))/2  12
z     e/(e%10^(-n))/2  1/12
+     e/(e%10^(-n))/2+1/12
ï     floor(e/(e%10^(-n))/2+1/12)

```
> 1 votes

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