Anagrams

Hola

by Jerome De Cuyper

JavaScript

var needle = "bcda";
var haystack = "abdcghbaabcdij";

function findAnagrams(needle, haystack) {
  var hash = hashNeedle(needle);
  var hashCopy = hash.slice();

  for (var i = 0; i < needle.length; i++) {
    hashCopy[needle.charAt(i)] = hash[needle.charAt(i)];
  }

  //for (var i = 0; i < haystack.length; i++) {
  //document.writeln(haystack.charAt(i));
  //}

  for (var i = 0; i < needle.length; i++) {
    document.writeln(needle.charAt(i) + " - " + hash[needle.charAt(i)] + "<br>");
  }

  for (var i = 0; i < needle.length; i++) {
    document.writeln(needle.charAt(i) + " - " + hashCopy[needle.charAt(i)] + "<br>");
  }
  //console.log(hash);
  //console.log(hashCopy);
  return 1;
}

function hashNeedle(needle) {
  var hash = [];
  for (var i = 0; i < needle.length; i++) {
    var char = needle.charAt(i);
    document.writeln(char);
    if (hash.indexOf(char) > -1) {
      hash[char]++;
    } else {
      hash.push(char);
      hash[char] = 1;
    }
    document.writeln(hash[char]);
  }
  return hash;
}

// Test cases

function testCase1() {
  var needle = "bcdaa";
  var haystack = "abdcghbaabcdij";
  var result = findAnagrams(needle, haystack);
  //document.write(result);
}

testCase1();