3

I was hoping to get your assistance with this "Is Unique" algorithm in Javascript.

var allUniqueChars = function(string) {

  // O(n^2) approach, no additional data structures used
  // for each character, check remaining characters for duplicates
  for (var i = 0; i < string.length; i++) {
    console.log(i);
    for (var j = i + 1; j < string.length; j++) {
      if (string[i] === string[j]) {
        return false; // if match, return false
      }
    }
  }
  return true; // if no match, return true
};

/* TESTS */
// log some tests here
allUniqueChars('er412344');

I am looking to log some tests, to see it display in the console. How do I call the function with unique strings to test it?

John

JohnNgo
  • 53
  • 4

3 Answers3

3

You can always create an Array with your strings and test like:

var allUniqueChars = function(string) {

  // O(n^2) approach, no additional data structures used
  // for each character, check remaining characters for duplicates
  for (var i = 0; i < string.length; i++) {
    for (var j = i + 1; j < string.length; j++) {
      if (string[i] === string[j]) {
        return false; // if match, return false
      }
    }
  }
  return true; // if no match, return true
};

/* TESTS */
// log some tests here

[
'er412344',
'ghtu',
'1234',
'abba'
].forEach(v => console.log(allUniqueChars(v)));

MDN Array.prototype.foreach

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • @raina77ow since they have no duplicates I guess they are to be considered having all unique chars, so, as true. The function OP provided would return true anyway – Attersson Aug 29 '18 at 23:32
1

Run the snippet multiple times to generate unique random strings and display results:

var allUniqueChars = function(string) {
  for (var i = 0; i < string.length; i++)
    for (var j = i + 1; j < string.length; j++)
      if (string[i] === string[j])
        return false;
  return true;
};

var getUniqueStr = () => Math.random().toString(36).substr(2, 9);

let myStringArray = []; 
for(var i =0 ; i<8; i++) // 8 test cases in this example
  myStringArray.push(getUniqueStr());

console.log(myStringArray.map(e=>e + " : " + allUniqueChars(e)));
Attersson
  • 4,755
  • 1
  • 15
  • 29
0

You can use this function found here to generate random strings for testing (not mine!):

var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
jcroskery
  • 135
  • 2
  • 10