freeCodeCamp/curriculum/challenges/chinese/10-coding-interview-prep/rosetta-code/compare-a-list-of-strings.md

2.2 KiB

id title challengeType forumTopicId dashedName
596e457071c35c882915b3e4 Compare a list of strings 5 302235 compare-a-list-of-strings

--description--

Given a list of arbitrarily many strings, implement a function for each of the following conditions:

  • test if they are all lexically equal
  • test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)

--hints--

allEqual should be a function.

assert(typeof allEqual === 'function');

azSorted should be a function.

assert(typeof azSorted === 'function');

allEqual(["AA", "AA", "AA", "AA"]) should return true.

assert(allEqual(testCases[0]));

azSorted(["AA", "AA", "AA", "AA"]) should return false.

assert(!azSorted(testCases[0]));

allEqual(["AA", "ACB", "BB", "CC"]) should return false.

assert(!allEqual(testCases[1]));

azSorted(["AA", "ACB", "BB", "CC"]) should return true.

assert(azSorted(testCases[1]));

allEqual([]) should return true.

assert(allEqual(testCases[2]));

azSorted([]) should return true.

assert(azSorted(testCases[2]));

allEqual(["AA"]) should return true.

assert(allEqual(testCases[3]));

azSorted(["AA"]) should return true.

assert(azSorted(testCases[3]));

allEqual(["BB", "AA"]) should return false.

assert(!allEqual(testCases[4]));

azSorted(["BB", "AA"]) should return false.

assert(!azSorted(testCases[4]));

--seed--

--after-user-code--

const testCases = [['AA', 'AA', 'AA', 'AA'], ['AA', 'ACB', 'BB', 'CC'], [], ['AA'], ['BB', 'AA']];

--seed-contents--

function allEqual(arr) {

  return true;
}

function azSorted(arr) {

  return true;
}

--solutions--

function allEqual(a) {
  let out = true;
  let i = 0;
  while (++i < a.length) {
    out = out && (a[i - 1] === a[i]);
  } return out;
}

function azSorted(a) {
  let out = true;
  let i = 0;
  while (++i < a.length) {
    out = out && (a[i - 1] < a[i]);
  } return out;
}