ruju11235 / csp

Small programs using the JavaScript syntax. I'm just starting to learn :)
0 stars 1 forks source link

Explore the versatility of an array by using it as a histogram! #14

Open kedarmhaswade opened 6 days ago

kedarmhaswade commented 6 days ago

An array is a simple "data structure." But it is versatile. Its "indexed" nature (you can access any element simply by an integer that acts like its index) is powerful. Here's a zero-indexed n-element array named xs. The indices run from 0 to n-1.

image

Its power is revealed when we analyze its structure closely: xs[i] is the element at the index i.

Use an array to write this function, let's call it histogram:

1) It is applied to an argument that is a string; a string is a sequence of UTF-16 code units (characters) in JavaScript. 2) The string contains only lower-case ASCII characters (from 'a' to 'z'). Fortunately, they are arranged sequentially in UTF-16. You can easily verify that by using the charCodeAt(index) method. For example, that method returns the integer 97 for a. 3) The function should return an array that tells us how many of each of the characters ('a' to 'z') are in that string. Thus, the array is the histogram of the given string as far as the characters ('a' to 'z') are concerned.

Try to get the abstraction right!