Home > OS >  Sorting strings by number of identical characters
Sorting strings by number of identical characters

Time:09-11

There is a file where there are many lines with a random set of letters. Scanning each line, you need to find the number of lines that contain exactly two letters of any letter, and then separately count the lines that contain exactly three letters of any letter. You need to get the result of multiplying the rows from the first case by the number of rows in the second.

How can I optimize this code or make it better??

Strings in file example (we need sort it all and file can has infiniy amout of strings) : "prtkqyluibmtcwqaezjmhgfndx prtkqylusbsmcwvaezjmhgfndt prgkqyluibsocwvamzjmhgkndx prjkqyluibsocwvahzjmhgfnsx prtkqylcibsocwvzezjohgfndx prtkqyluiksocwziezjmhgfndx prikqyluiksocwvaezjmkgfndx prtkgyluibsocwvwezjehgfndx prtkqyluiysocwvaezjghxfndx prtkqwluibsoxwvaezjmhgfhdx prtkqylgibsocwvabzjmhzfndx prtknyltibnocwvaezjmhgfndx prdkqyluibrocwvaezjmhgnndx prtwqyluibsoctvcezjmhgfndx mrtkqyluibgocwvakzjmhgfndx"

My code:

function solution(arrOfStrings) {
  let sumOfTwo = 0;
  let sumOfThree = 0;

  for (const string of arrOfStrings) {
    const chars = {};
    for (const char of string) {
      chars[char] = (chars[char] || 0)   1;
    }
    console.log(chars);
    if (
      Object.entries(chars)
        .filter((char) => char[1] == 2)
        .map((char) => char[0]).length > 0
    ) {
      sumOfTwo  = 1;
    }
    if (
      Object.entries(chars)
        .filter((char) => char[1] == 3)
        .map((char) => char[0]).length > 0
    ) {
      sumOfThree  = 1;
    }
  }

  return sumOfTwo * sumOfThree;
}

let fs = require("fs");
const text = fs.readFileSync("./someTextFile.txt").toString("utf-8");
const arr = text.split("\n");

solution(arr);

CodePudding user response:

Here is one of possible optimizations:

function solution(arrOfStrings) {
  const out = arrOfStrings.reduce((o, s) =>
    (o[s.length]   || (o[s.length] = 1), o), {});
  return (out[2] ?? 0) * (out[3] ?? 0);
}

let fs = require("fs");
const text = fs.readFileSync("./someTextFile.txt").toString("utf-8");
const arr = text.split("\n");

solution(arr);
  • Related