isPermutation

Check whether array N is a permutation

by Hugh Chapman

HTML

<label for="Arr">Array: 
    <input id="Arr" type="text"/> (comma seperated)
</label> 
<label for="Perm">Permutation: 
    <input id="Perm" type="text"/> (comma seperated)
</label>
<button type="button" id="Test">Test</button>
<div id="Result"></div>

CSS

label, button, #Result {
  display: block;
  margin-top: 10px;
}

JavaScript

/*  
   Elements seen twice or out of bounds of the size indicate that the list is no permutation. 
   This solution works by reducing the arrays to zero elements. 
   If they both get to zero elements it is a permutation. 
   This solution works for any kind of set.
   Important to note that this is for a Permutation - not a Combination. (must be equal # of elements)
*/

var resultElem = document.querySelector('#Result');
var testBtn = document.querySelector('#Test');

resultElem.textContent = '';
testBtn.addEventListener("click", isPermutation, false);

function isPermutation() {
	// create constant arrays from the input fields
	var set = document.querySelector('#Arr').value.split(',');
  var permutation = document.querySelector('#Perm').value.split(',');
  var result = false;
  
  // if they're not the same length it not a permutation
  if ( !testLength(set.length,permutation.length) ) {
  	resultElem.textContent = 'This is NOT a permutation.';
    return;
  }
  console.log('Arrays are the same length ' + set.length + ':' + permutation.length );
  
  // for each element in set... 
  for (var i = set.length; i > 0 ; i--) {
  	// pop the value from set array
    var A = set.pop();
  	// test for equal in permutation
    for (var j = 0; j < permutation.length; j++) {
    	console.log('Testing value: ' + permutation[j]);
    	// if so, splice that value from the permutation array
      if ( permutation[j] === A ) {
      	console.log('Found ' + permutation[j] + ' in Array');
      	permutation.splice(j,1);
      }
    }
    // test array lengths
    if ( !testLength(set.length,permutation.length) ) {
  		resultElem.textContent = 'This is NOT a permutation.';
    	return;
  	} 
    console.log('Arrays are still the same length');
  }
  
  // Array lengths should be zero indicating a correct permutation
	resultElem.textContent = 'Permutation is correct.';
}

function testLength(A,B) {
	console.log('set length = ' + A);
  console.log('permutation length = ' +...