Skip to content

Instantly share code, notes, and snippets.

@hueitan
Last active April 22, 2017 02:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hueitan/abdc784cdd07efaa821d to your computer and use it in GitHub Desktop.
Save hueitan/abdc784cdd07efaa821d to your computer and use it in GitHub Desktop.
function numberOfAnagrams(S) {

  // S.length!/repeat!
  
  var total = factorial(S.length),
	repeat = 1,
      array = S.split('').sort();
  
  for (var i=1;i<array.length;i++) {
    if (array[i] == array[i-1]) {
      repeat+=1
    } else {
      total = total / factorial(repeat);
      repeat = 1
    }
  }
 
                   
  return total/factorial(repeat)
}

function factorial(num)
{
    // If the number is less than 0, reject it.
    if (num < 0) {
        return -1;
    }
    // If the number is 0, its factorial is 1.
    else if (num == 0) {
        return 1;
    }
    var tmp = num;
    while (num-- > 2) {
        tmp *= num;
    }
    return tmp;
}

// factorials
// f = function(n) {
//   return n ? n * f(n - 1) : 1
//}

140 char

f = function(n) {
  return n ? n * f(n - 1) : 1
}
S = arguments[0]
t = f(S.length)
i=r = 1
a = S.split('').sort()
  
for (;S[i];) 
  a[i-1] == a[i++] ? r++ : (t /= f(r), r=1)
 
return t/f(r)

my answer is so stupid after reviewing other's work

  r = 1
  v = {}
  n = 0
  for (;l = arguments[0][n];) {
    v[l] = v[l] || 0
    r *= ++n
    r /= ++v[l]
  }

  return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment