[Question]
  [
## Definition
The rank of a word is defined as the position of the word when all the possible permutations (or arrangements) of its letters are arranged alphabetically, like in a dictionary, no matter if the words are meaningful or not.
Let us consider these two words - "blue" and "seen". To begin with, we would write all the possible arrangements of the letters of these words in alphabetical order:
```
"blue": "belu","beul","bleu","blue","buel","bule","eblu","ebul","elub","elbu","eubl",
        "eulb","lbeu","lbue","lebu","leub","lube","lueb","ubel","uble","uebl","uelb",
        "ulbe","uleb"
"seen": "eens","eesn","enes","ense","esen","esne","nees","nese","nsee","seen",
        "sene","snee"
```
Now let's look from the left and find the position of the words we need. We see that the word "blue" is at the 4th position and "seen" is at 10th position. So the rank of the word "blue" is 4, and that of "seen" is 10. This is the general way of calculating the rank of a word. Make sure you start counting from 1 only.
## Task
Your task is to write a code to take any word as an input and display its rank. The rank should be the output.
Be careful about words containing repeated letters.
## Examples
```
"prime" -> 94
"super" -> 93
"bless" -> 4
"speech" -> 354
"earth" -> 28
"a" -> 1
"abcd" -> 1
"baa" -> 3    
```
You can assume the input to be completely in lowercase and the input will only contain **alphabetical characters**. Also if a blank space or an invalid string is entered, you may return anything.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") , so the shortest code wins!
  
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
lambda s:sum(t<=(*s,)for t in{*permutations(s)})
from itertools import*
```
[Try it online!](https://tio.run/##HY27DoMwDEXn8hXekiA6IXWISr@kS4BERCIP2WaoEN@ehizW8dU9dv7xluJYHEzwLbsJ82qANB1B8nuSPQ3KJQQGH88@WwwHG/YpkiR1qc5hCuDZIqe0E/iQE3JfbqVuEURGH6wYQNBR7Rvm3RK1JFu7bDdZg9zAtDEvaysaI3T3qBciSydO0q8Lnh84Xf2tx0uo8gc "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
œêsk>
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6OTDq4qz7f7/T8pJLS4GAA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVln5/@jkw6uKs@3@Vyod3m@lcHi/ks7/gqLM3FSu4tKC1CKupJzU4mKu4oLU1OQMrtTEopIMrkSuxKTkFK6kxEQA)
**Explanation**
```
œ       # get permutations of input
 ê      # sort and remove duplicates
  s     # swap input to top of stack
   k    # get index of input in the list
    >   # increment
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 4 bytes
```
fuȯI
```
[Try it online!](https://tio.run/##S0/MTPz/P630xHrP//@LC1JTkzMA "Gaia – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 6 bytes
```
hxS{.p
```
**[Test suite.](https://pyth.herokuapp.com/?code=hxS%7B.p&input=%22earth%22&test_suite=1&test_suite_input=%22prime%22%0A%22super%22%0A%22bless%22%0A%22speech%22%0A%22earth%22%0A%22a%22%0A%22abcd%22%0A%22baa%22&debug=0)**
## Explanation
```
hxS{.p || Full program.
    .p || All the permutations of the input.
   {   || Deduplicate.
  S    || Sort.
 x     || Index of the input into this list.
h      || Increment.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Œ!ṢQi
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWHOxcFZv7//1@puCA1NTlDCQA "Jelly – Try It Online") or see the **[test suite](https://tio.run/##y0rNyan8///oJMWHOxcFZv4/uudw@6OmNVlA/KhhjoKuncKjhrmR//9HKxUUZeamKulwKRWXFqQWgRhJOanFxWCRgtTU5AwQKzWxqATMSAQTSckpYIWJiUqxAA "Jelly – Try It Online")**
## How it works
```
Œ!ṢQi - Main link. Argument: s (string)      e.g. 'baa'
Œ!    - All permutations                          ['baa', 'baa', 'aba', 'aab', 'aba', 'aab']
  Ṣ   - Sort                                      ['aab', 'aab', 'aba', 'aba', 'baa', 'baa']
   Q  - Deduplicate                               ['aab', 'aba', 'baa']
    i - 1-based index of s                        3
```
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
lambda s:-~sorted(set(permutations(s))).index(tuple(s))
from itertools import*
```
[Try it online!](https://tio.run/##bdDNSsUwEAXgfZ5i6CoVLNpewXuhr@ATuEnbKQ00P8xMQDe@eo00YMS7/c7JcEj8lC34/ljH92M3bloM8O3xiwMJLppRdERySYzY4Flz27ad9Qt@aElxxx9QKwUHVpAkhJ3BuphfPxyGOROsupn2hE0L4wgX9auM6E99flKVR7Ku1K9/@ilPKT6o@joy3zkfEeft9OGlTtCQlKB/rdyUNTVN8/JfJ1Oqg1J5rRdo3gKcef4mQKJA3DXHNw "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 73 bytes
* Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for choosing Python 3; saving five bytes.
```
lambda s:-~sorted({*permutations(s)}).index((*s,))
from itertools import*
```
[Try it online!](https://tio.run/##bdBNCsIwEAXgfU4RukqKFrUKKvQKnsBNaqcYaH6YSUERvXoNNGBEt997GR7x93B1tp765jwNyrSd4nRcvshhgE48Sg9oxqCCdpYEyaestO3gJkRJCylZj85wHQCDcwNxbXx8WE6KKBLvRdEOIxSSNw3fso8SgJ11vWKZe9Qm1Q9f/THuSF6z/DoQ/TnvAS7X2etdnoDCkILNPnOV1uTUXrpfbVWq1ozFtTaI4uT4nMc/4oDokKpCTm8 "Python 3 – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
q_e!\a#)
```
[Try it online!](https://tio.run/##S85KzP3/vzA@VTEmUVnz///igtTU5AwA "CJam – Try It Online")
+1 byte due to 1-indexed requirement.
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
import Data.List
elemIndex<*>([]:).nub.sort.permutations
```
[Try it online!](https://tio.run/##RYyxDoMwDER3vsLKBFWVD6hKpy6VyhcgBgeMiJqEKDZS/z6NOpCb7t3ZtyF/yLmcrY97EniioH5blmbtyZF/hYW@98ujHadbp8NhNJczHSn5Q1DsHjh7tAF68BgHaGOyQUDD2kEDRSOoEnlSf7qC4qM8n2QcMdcuEs3biYRJKmF1Zl7qAqKCKf8A "Haskell – Try It Online")
+6 bytes because of 1-indexing requirement. :(
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~8~~ 10 bytes
~~0-indexed.~~ Poxy, unnecessary 1-indexing, increasing my byte count by 25%!
```
á â n bU Ä
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=4SDiIG4gYlUgxA==&input=InNwZWVjaCI=)
---
## Explanation
`á` gets all the permutations of the input, `â` removes duplicates, `n` sorts them and `b` gets the index of the first occurrence of the input, `U`.
[Answer]
# [J](http://jsoftware.com/), 28 23 bytes
-5 bytes thanks to FrownyFrog
```
1+/:~@~.@(A.~i.@!@#)i.]
```
## How it works?
```
                      ] - the argument
         (A.~      )    - permutations in the 
             i.@!@#     - range 0 to factorial of the arg. length
  /:~@~.@               - remove duplicates and sort
                    i.  - index of arg. in the sorted list
1+                      - add 1 (for 1-based indexing)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbX1reoc6vQcNBz16jL1HBQdlDUz9WL/a3JxpSZn5CukKagXFGXmpqorKMAFiksLUouQBZJyUouLUVQUpAKZyCKpiUUlQAEY31DBUEU9EcFXT0xKTkHiJiUCJcHgPwA "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
S€(OuP
```
[Try it online!](https://tio.run/##yygtzv7/P/hR0xoN/9KA////KyUlJioBAA "Husk – Try It Online") I feel like there should be a way to drop `(`.
**Explanation:**
```
 €     -- return index of the input 
S (    -- in the list generated by applying the following functions to the input:
     P -- permutations
    u  -- remove duplicates
   O   -- sort
```
[Answer]
# Tcl, 196 bytes
```
proc p {a p} {if {$a eq {}} {lappend ::p $p} {while {[incr n]<=[llength $a]} {p [lreplace $a $n-1 $n-1] $p[lindex $a $n-1]}}}
p [split $argv ""] ""
puts [expr [lsearch [lsort -unique $p] $argv]+1]
```
Tcl has no built-in method to compute the next lexicographic permutation, so we have to do it ourselves. But wait... it is *shorter* to do it with a simple recursive function that computes *all* possible permutations in any order.
Ungolfed:
```
# Compute all possible permutations of the argument list
# Puts the result in ::all_permutations
proc generate_all_permutations {xs {prefixes ""}} {
  if {$xs eq {}} {
    lappend ::all_permutations $prefixes
  } else {
    while {[incr n] <= [llength $xs]} {
      generate_all_permutations [lreplace $xs $n-1 $n-1] $prefixes[lindex $xs $n-1]
    } 
  }
}
# Get our input as command-line argument, turn it into a list of letters
generate_all_permutations [split $argv ""]
# Sort, remove duplicates, find the original argument, and print its 1-based index
puts [expr [lsearch [lsort -unique $all_permutations] $argv]+1]
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ 18 bytes
**Solution:**
```
1+*&x~/:?x@prm@<x:
```
[Try it online!](https://tio.run/##y9bNz/7/31BbS62iTt/KvsKhoCjXwabCSqm4IDU1OUPp/38A "K (oK) – Try It Online")
**Examples:**
```
1+*&x~/:?x@prm@<x:"seen"
10
1+*&x~/:?x@prm@<x:"blue"
4
```
**Explanation:**
Generate permutations of the indices of the sorted input string, use them to index back into the input string, take the distincts, see where the original string matched, and add one.
```
1+*&x~/:?x@prm@<x: / the solution
                x: / save input string as x
               <   / return indices when sorting x ascending
           prm@    / apply (@) function prm
         x@        / index into x with these permutations
        ?          / distinct (remove duplicates)
    x~/:           / apply match (~) between x and each-right (/:)
   &               / return indexes where true (ie the match)
  *                / take the first one
1+                 / add 1 due to 1-indexing requirement
```
[Answer]
# Java 8, 211 bytes
```
import java.util.*;TreeSet q=new TreeSet();s->{p("",s);return-~q.headSet(s).size();}void p(String p,String s){int l=s.length(),i=0;if(l<1)q.add(p);for(;i<l;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,l)));}
```
**Explanation:**
[Try it online.](https://tio.run/##pVLdasIwGL33KT68StYa3XXXwR5gMnB3Yxdp@mnj0jQmXx1Ould3qdMxxkCwhRDOIeeHQ9dyKyeNQ7su3w66do0nWEdOtKSNuMkgftMpPMnIN0ugCqHYEU5U01oaKSNDgEep7X4EoC2hX0qFMO/hkQDFFuS1XUHgWSS7eJ494gIJNrnF9zNi/EIWwBws5HAIk/u9Y@NxGh09Uuvt5HMjKpRlbxO4CPoDo103OjvOGwL3v@u20SW4c0eX/pTd9@VNHoRBu6KK8VTns0wvmbm75Rshy5I5ni0bzzJ9ZzLHXBKEqqR/IKZ5GkRoi3A0Y7NU8@Q3kSQ6NZzHigcA1xZGKwgkKV7HPnUc9FTp5VXy7zH7laGOA/Sj9YAdBwVY7AJhLZqWhIsSMpbVwgrFxoVpccxPz2rxd@8L6oBor1dHWA8Jbx366@WFwRAGpDtEVV2vx/izDZDLAdJClQNmk@fobtQdvgA)
```
import java.util.*;        // Required import for TreeSet
TreeSet q=new TreeSet();   // Sorted Set on class-level
s->{                       // Method with String parameter and integer return-type
  p("",s);                 //  Save all unique permutations of the String in the sorted set
  return-~q.headSet(s).size();}
                           //  Return the 0-indexed index of the input in the set + 1
void p(String p,String s){ // Separated method with 2 String parameters and no return-type
  int l=s.length(),        //  The length of the String `s`
      i=0;                 //  Index integer, starting at 0
  if(l<1)                  //  If String `s` is empty
    q.add(p);              //   Add `p` to the set
  for(;i<l;                //  Loop from 0 to `l` (exclusive)
    p(                     //   Do a recursive call with:
      p+s.charAt(i),       //    `p` + the character at the current index of `s` as new `p`
      s.substring(0,i)+s.substring(++i,l)));}
                           //    And `s` minus this character as new `s`
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~183~~ 182 bytes
The first answer that run in polynomial time!
```
a=[*map(ord,input())]
f=lambda x:x and x*f(x-1)or 1
c=[0]*98
for C in a:c[C]+=1
l=len(a)
F=f(l)
for i in c:F//=f(i)
r=1
for x in a:F//=l;l-=1;r+=sum(c[:x])*F;F*=c[x];c[x]-=1
print(r)
```
[Try it online!](https://tio.run/##JYtBC8IgHMXvfgqP6hprdCnlfxoJHYLoKh7MJQnODdvAPv1ydXnwfu/3ps/8GuNhXQ0oNpiJjKnf@TgtM6FUIwfBDI/e4MwzNrHHmTmS65aOCbfIgtprdjoiV2qHfcSGW9XpCloUIDwjMRRJcCTQn@I3xXLZNIV5ilLxNp7/140HEWpoRargvQzEKp41ZVJIBlZlLbYoO5qSjzNJdF1v98v1/AU "Python 3 – Try It Online")
Require the input to be all upper-case, because... it saves a byte.
Full program, takes input from `stdin` and output to `stdout`.
---
Variable names: (sort of ungolfed code)
```
a : permu
f : factorial
c : count_num
C : char
l : n_num_left
F : factor
r : result
```
Unfortunately, `from math import factorial as f` takes exactly 1 more byte.
---
(Unrelated note: I checked the `Combinatorica`` package of Mathematica, nothing useful, including `RankPermutation`)
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~113~~ 111 bytes
```
import StdEnv,StdLib
?s=elemIndex s[[]:removeDup(foldr(\a b=sort[insertAt i a x\\x<-b,i<-[0..length x]])[[]]s)]
```
[Try it online!](https://tio.run/##JY49C4MwFEX3/oq3qaDSuShSaAfBzTFmiOZpA/mQJEr655sGnC53OPfcRSLTURl@SATFhI5C7cZ6GD1/67NMMYj51rkWJapecwzgCKEPi8qc@Dr2fDWS23xiMLcukURoh9Y/PQhgEKYpNNVciqYi97qWqDf/gUBpkUaoK2gcPUu6Fjog2SwPzGj8Latkm4tVP8TXVzMllqtcb/4 "Clean – Try It Online")
+3 bytes to handle 1-indexing :/
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 33 bytes (SBCS)
```
⎕CY'dfns'
{∪⊃∘(⍵[⍋⍵])¨¨↓pmat≢⍵}⍳⊂
```
[Try it online!](https://tio.run/##nVFNS8NAEL3nV4y9RKHtD/AqHv049CLiYZJMmpXNbshsKEG8KBStRAQRvHjxJF7FP9Cfsn9EJ6lNexZCsm923nvzJljoUVKjttOfH9@8wSQj4CrKFbOyBmI0oYOIgIyjkhLI5D0EJpKitrOdFev4ZHK4L1zFII8TjZJQbwntB0Hb5x9fDs7CJDUcdvjK3336xa2/e931zfe5bx7kc7G3/Fh@@PlzkaPz9@9SuvbNl1/crESOUBlIKxO7dsLdjcme3G8ZpODnT/@zmBBL3N5kVTzVhExgrCOJiA5SWwIrM9U0ijOUsysFscSOM0CGEEOobQUzW@lEeGWOWtdgiJJO0FlwdUEwGErnAJQRU0zApnBZsYNBWx2vttpy2tXmyqkpOgFR3e3ZdZN2cutpx0HQVrv0fvE@TCX7cJNL/ikT//WERalyCv8AVwWVaxBpYu5vCqI4WyPC0vUA@0MUJz0ZMfwF "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~105~~ ~~104~~ 103 bytes
```
f=lambda s:s==s*2or f(s[1:])+sum(f(sorted(s[:s.index(c)]+s[s.index(c)+1:])[::-1])for c in{*s}if c<s[0])
```
[Try it online!](https://tio.run/##RY7LCsMgEEXX7Ve4U5OmNC10IU1/JLgwPkggMeIYaAn5dqtuuhnOPVwu475hXO0jRtPNYhmUQMCg66C6rx4ZAn3LOK1hW0gKqw9aJcfgOlmlP0RSXkP/T3Vu94w1LacmDUg02b2CYzJIvqC/cRqzhqQRdn5aNL4gDJvTPsMwa4BinNZyzKSFDwVEOYNUpSgEZudTWrCBGLwDex6oeaM9PUnZ48A0/gA "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->w{c=w.chars
1+c.sort.permutation.uniq.index(c)}
```
[Try it online!](https://tio.run/##XctBDoIwFATQPadocKMxNMFqogu4iHHRfj6hiUD9bYPGePZKhHbh7OZlhrx6hbYKRT29oZo4dJJsVu6B25EcN0i9d9LpceB@0A@uhwafW9h9gmHtNTeke8xvbMOKml2O2Q@tn28JxYLqjtZGjEODCF1EcVoZJbmkh/OCMkK5dgXNHymZRoLNCV8 "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), ~~106~~ 100 bytes
```
w=>(P=(a,s)=>a[0]?a.map((_,i)=>P(b=[...a],s+b.splice(i,1))):P[s]=P[s]||++k)[P([...w].sort(),k=''),w]
```
### Test cases
```
let f =
w=>(P=(a,s)=>a[0]?a.map((_,i)=>P(b=[...a],s+b.splice(i,1))):P[s]=P[s]||++k)[P([...w].sort(),k=''),w]
console.log(f("prime"))  // 94
console.log(f("super"))  // 93
console.log(f("bless"))  // 4
console.log(f("speech")) // 354
console.log(f("earth"))  // 28
console.log(f("a"))      // 1
console.log(f("abcd"))   // 1
console.log(f("baa"))    // 3
```
### How?
**P()** is our recursive permutation function. But the encompassing object of **P** is also used to store the ranks of the permutations.
```
P = (a, s) =>               // given an array of letters a[] and a string s
  a[0] ?                    // if a[] is not empty:
    a.map((_, i) =>         //   for each entry at position i in a[]:
      P(                    //     do a recursive call to P() with:
        b = [...a],         //       a copy b[] of a[], with a[i] removed
        s + b.splice(i, 1)  //       the extracted letter appended to s
      )                     //     end of recursive call
    )                       //   end of map()
  :                         // else:
    P[s] = P[s] || ++k      //   if P[s] is not already defined, set it to ++k
```
The wrapping code now reads as:
```
w =>                        // given the input word w
  P[                        // return the permutation rank for w
    P(                      //   initial call to P() with:
      [...w].sort(),        //     the lexicographically sorted letters of w
      k = ''                //     s = k = '' (k is then coerced to a number)
    ),                      //   end of call
    w                       //   actual index used to read P[]
  ]                         // end of access to P[]
```
[Answer]
# C++, 230 bytes
```
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;void R(string s){int n=1;auto p=s;sort(begin(p),end(p));do if(p==s)cout<<n;while(++n,next_permutation(begin(p),end(p)));}int main(int n,char**a){R(a[1]);}
```
As per my asking, the code definitely need to be executable as-is. The function-only clause is basically rubbish. :-@
Thank you to those who kindly answered the question of what can be cut out for me. In the interest of *valid* code, I’ve avoided the popular GCC-ism of including <bits/stdc++.h>, which I have always considered a bad loophole cheat. 
What follows is what remains of my original posting:
---
I am always unsure when using C and C++ what counts towards the byte total. According to [Program, Function, or Snippet?](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) the answer is still vague (as long as it isn’t a snippet, I guess). So I am going with the shortest of the two possibilities.
Here it is ungolfed *with necessary headers, etc:*
```
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
void R( string s )
{
  int n = 1;
  auto p = s;
  sort( begin(p), end(p) );
  do if (p == s) cout << n;
  while (++n, next_permutation( begin(p), end(p) ));
}
int main( int n, char** a )
{
  R( a[1] );
}
```
That golfs down to 230 bytes, a third of that standard boilerplate required by *every* C++ program. (So, I don’t feel too bad not counting it, but as I haven’t ever seen a firm complaint either way, OP will have to tell me which he prefers to satisfy “write a code to take any word as an input and display its rank.”)
I am also unsure if this satisfies “the rank should be output.”
[Answer]
# [Perl 5](https://www.perl.org/), 98 + 3 (`-pF`) = 101 bytes
```
$"=',';@a=grep{++$k{$_}<=1&&"@F"eq join$",sort/./g}sort glob"{@F}"x(@F=sort@F);1while!/$a[$\++]/}{
```
[Try it online!](https://tio.run/##FcjBCsIgGADgV1kiW@E2t8NOS/DkrSeoiBU/zpJpOigQX70/dvv4PAQ7IFIiqroa5SR0AJ8Yo69Eb/ko@rIkUhF4F09nFkrq6MLKW67zhkJbdydJqky@e6nEdlIdxv4zGws7TqczvTB25TkhRg/wmH/Or8YtEZvT0HZ9h41Xfw "Perl 5 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 43 bytes
```
@(s)find(all(unique(perms(s),'rows')==s,2))
```
[**Try it online!**](https://tio.run/##LcvBCoAgDMbxey/iBuGhu9CrLJskmJrLenwT8rQff74le9PDzRmtdVtB0Pm4A4UANfqrMmQup/Q@q5JeUWiMzAtic6By8ScrnDql9t3PLbDIqJnZHr@Zyj1I42x2Hy/UU/sA "Octave – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 53 bytes
```
{1+first :k,$_,.comb.permutations».join.unique.sort}
```
[Try it online!](https://tio.run/##DcxNDoIwEAbQq3whxI2kiRsXKlyFTHEaqvTHTrsghJO582KV3Vu9yGm5VrfiZNDX7XI2NknG7d21Y6em4LSKnFzJlG3w8vuqV7BeFW8/hZWElPcqtKJpR/QDNoN23BuYkPDQS2EIs0dM1h0sRwW9sAgkMk8zmFKeQSA9PaGJhnv9Aw "Perl 6 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 275 bytes
```
param($s)function n($a){if($a-eq1){return}0..($a-1)|%{n($a-1);if($a-eq2){$b.ToString()}$p=($j-$a);[char]$t=$b[$p];for($z=($p+1);$z-lt$j;$z++){$b[($z-1)]=$b[$z]}$b[($z-1)]=$t}}if($s.length-eq1){1;exit}$b=New-Object Text.StringBuilder $s;(n($j=$s.length)|sort -u).indexOf($s)+1
```
[Try it online!](https://tio.run/##TY7BboMwEER/hcNWsYVslV4Rl35Ac2huiAOQJRg5htqLgiD@dtcUteppVzOzb2caH2hdj1qHMNW2vjNwvJtNS2o0iWFQ8011cQj8yvhmkWZr/KuUu5Tx58tmji3/Tb3xDRp5GT/JKnNj3MNUMBhEJOVl29e2AiqgKWGq8m60DNZoT2kkwCo0wRBnmu6QMnqRXP2k18r/V8j7/aGTGs2N@qNdluOiKOaKD3yIczNgS8kFF5JHmfdZ6SvaBFzOYu2h@LvnTzdaSsTMpTJXXM47m6dZCOHU1nT6Bg "PowerShell – Try It Online")
So, this is a bloody mess.
*PowerShell doesn't have any permutations built-in, so this code uses the algorithm from [here](https://learn-powershell.net/2013/02/21/fun-with-powershell-and-permutations/) (golfed heavily), which is available under the Microsoft Limited Public License ([Exhibit B](https://technet.microsoft.com/en-us/cc300389.aspx#P) on this licensing page).*
The program takes input `$s` as a string, then the actual program starts with `$b=New-Object ...`. We're constructing a new [StringBuilder](https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx) object, which is (essentially) a mutable string of characters. This will allow us to handle the permutations more easily. We then call the function `n` (setting `$j` along the way to be the length of the input string), `sort` with the `-u`nique flag the output, take the `.indexOf()` to find the input string, and add `1` because PowerShell is zero-indexed.
The function is the main part of the program. It takes as input a number, and will each iteration count down until we reach `1` (i.e., a single letter). The rest of the function essentially recursively calls the function as well as takes the current letter and iterates it through every position.
There's a single bit of additional logic `if($s.length-eq1){1;exit}` to account for input strings of length `1` due to how the permutations function works.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 5 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
ĐᒆỤ≥Ʃ
```
Explanation:
```
            Implicit input
Đ           Duplicate input
 ᒆ         Get list of all permutations of input
  Ụ         Get unique permutations
   ≥        Does each permutation come before or is equal to the input?
    Ʃ       Sum of result of previous step (converts booleans to ints)
```
[~~Try it online!~~](https://tio.run/##ARoA5f9weXT//8SQ4ZKG4buk4omlxqn//3NwZWVjaA)
]