Skip to content

Instantly share code, notes, and snippets.

@claytonjwong
Last active September 12, 2023 13:33
Show Gist options
  • Save claytonjwong/2e6f12c1504f169ed98979ce91826184 to your computer and use it in GitHub Desktop.
Save claytonjwong/2e6f12c1504f169ed98979ce91826184 to your computer and use it in GitHub Desktop.
Create a map `m` to count the frequency of each character `c` of the string `s`.

Create a map m to count the frequency of each implicit character c of the string s.

  • Note: The character c is explicit in Rust and C++

Kotlin

var m = s.groupingBy{ it }.eachCount()

Java

Map<String, Long> m = Stream.of(s.split("")).collect(Collectors.groupingBy(it -> it, Collectors.counting()));

Javascript

let m = new Map(Object.entries(_.countBy(s.split(''))));

Python3

m = Counter(s)

Rust

let m = s.chars().fold(HashMap::new(), |mut m, c| { *m.entry(c).or_insert(0) += 1; m });

C++

using Map = unordered_map<char, int>;
Map m;
for (auto c: s) ++m[c];
@jainismvivek
Copy link

Java
Map<Character , Integer> frequencies = new Hashmap<>();
For(char ch : input.toCharArray())
Frequency.put(ch, frequencies.getOrDefault(ch , 0) +1);

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