Home > OS >  Find unique characters in a string and the count of their occurrences
Find unique characters in a string and the count of their occurrences

Time:07-12

I need to count the occurrence of characters in a given string and print out the unique characters and the number of how many times they appeared. So, for example, if I receive a string of 'HELLO' it should print out:

H: 1, E: 1, L: 2, O: 1

This is a much-simplified version of a problem, but the answer should put me in the right direction. How can I approach this problem?

Thank you in advance.

CodePudding user response:

This is more or less what it should look like in order to make it easier it prints it in JSON you can already convert it to String yourself if you want.

function count_occurrence(text = "") {
    const array_from_text = text.split("");
    const result = {};
    Array.from(new Set(array_from_text)).forEach(word => {
        const { length } = array_from_text.filter(w => w === word);
        result[word] = length;
    });
    return result;
};
const occurences = count_occurence("HELLO");
console.log(occurences); // {H: 1, E: 1, L: 2, O: 1}

CodePudding user response:

You could use Array.reduce() to get a count of each occurrence in the input word.

We convert the word to an array using the ... operator, then .reduce() to create an object with a property for each unique letter in the word.

const input = 'HELLO';
const result = [...input].reduce((acc, chr) => { 
    acc[chr] = (acc[chr] || 0)   1;
    return acc;
}, {});

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

const countChars = (str) => {
  const charCount = {} ;
  for (const c of [...str]) {
    charCount[c] = (charCount[c] || 0)   1 ;
  }
  return charCount ;
}
console.log(countChars('HELLO')) ; // {H: 1, E: 1, L: 2, O: 1}

CodePudding user response:

My approach to this problem is:

let str = "HELLO";

// An object for the final result {character:count}
let counts = {};

// Loop through the str...
for (let index = 0; index < str.length;   index) {
  // Get each char
  let ch = str.charAt(index);
  // Get the count for that char
  let count = counts[ch];
  // If we have one, store that count plus one;
  if (count) {
    counts[ch]  = 1;
  } else {
    // if not, store one
    counts[ch] = 1;
  }
  // or more simply with ternary operator
  //   counts[ch] = count ? count   1 : 1;.
}
console.log(counts);

CodePudding user response:

Maybe the easiest answer is just split to char and put it into the map.

const count={}
"HELLO".split("").forEach(e=>{
count[e]??=0;
    count[e]  ;
})

count is what you want.

CodePudding user response:

Use a dictionary like datastructure that gives you O(1) access and update times. In JS you can use an Object literat (not recommended) or a Map.

Iterate over the characters of your string and update the dictionary by incrementing the character count of the current character. If it isn't in your dictionary add it and set the count to one.

When done with the iteration, iterate over the keys of your dictionary, where the values are the the number of occurence of that specific character, and output them in any format of your liking.

const myStr = "Hello"

const myMap = new Map()

for (let c of myStr) {
    if (myMap.has(c)) {
        myMap.set(c, myMap.get(c) 1)
    } else {
        myMap.set(c, 1)
    }
}

for (let k of myMap.keys()) {
    console.log(`${k} occures ${myMap.get(k)} times`)
}

  • Related