Skip to content

Instantly share code, notes, and snippets.

@elishaking
Created February 19, 2020 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elishaking/01aa04163d5969da9f7d1aee7350ce3e to your computer and use it in GitHub Desktop.
Save elishaking/01aa04163d5969da9f7d1aee7350ce3e to your computer and use it in GitHub Desktop.

Counting Elements

A numerical sequence can be represented by an array in two ways

// an arbitrary sequence can be represented like this
const A = [1, 1, 2, 2, 2, 4, 4, 8, 8];

The same sequence cn be represented by counting the number of occurrences of each element. The above sequence can be represented like this

// A[n] = number of n's in the sequence
const A = [0, 2, 3, 0, 2, 0, 0, 2];
  • 0 occurs 0 times
  • 1 occurs 2 times
  • 2 occurs 3 times
  • and so on until number 8

If the sequence contains negative numbers, all the elements should be shifted by a number large enough to make them all greater than or equal to zero. Or the negative numbers can be added to another array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment