Program to parse the Molecules and get the Atoms count
Last Updated :
17 Mar, 2023
Given a chemical formula as a string, the task is to get the count of atoms in this chemical formula.
Examples:
Input: str = "Fe2H3OH"
Output: Fe 2
H 4
O 1
Input: str = "NaCl2NaO2"
Output: Na 2
Cl 2
O 2
Approach: The below approach work in Java programming language:
- Take LinkedHashMap to store atom name(Key) and count(value) in insertion order.
- Check if the string character is lowercase then add to the previous uppercase string character.
- Check if the string contains the number then add to the count(value) to their particular atom name(key).
- Print the atom name(key) as well as count(value).
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
void getCount(string str)
{
// Use LinkedHashmap to store
// elements in insertion order
map<string, int> mp;
for (int i = 0; i < str.length(); i++) {
int count = 0;
// Convert the string element into character
char c = str.at(i);
string a = " ";
// Convert the character element
// into string element
a = string(1, c);
// Check string contains the Capital A - Z value.
if (a.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ") != string::npos) {
for (int j = i + 1; j < str.length(); j++) {
char d = str.at(j);
string b = string(1, d);
// Check string contains the small a-z value.
if (b.find_first_of("abcdefghijklmnopqrstuvwxyz") != string::npos) {
a += b;
if (mp.find(a) == mp.end())
mp[a] = 1;
else
mp[a] += 1;
count = 1;
}
// Check string contains the number value.
else if (b.find_first_of("0123456789") != string::npos) {
int k = stoi(b);
mp[a] = k;
count = 1;
}
else {
i = j - 1;
break;
}
}
if (count == 0) {
if (mp.find(a) == mp.end())
mp[a] = 1;
else
mp[a] += 1;
}
}
}
cout << "\nAtom count:" << endl;
for (auto entry : mp)
cout << entry.first << " " << entry.second << endl;
mp.clear();
}
// Driver code
int main()
{
string str = "Fe2H3OH";
cout << "Given molecule: " << str << endl;
getCount(str);
return 0;
}
// This code is contributed by surajrasr7277.
Java
// Java program to parse the molecule
// and get the atoms count
import java.io.*;
import java.util.*;
class GFG {
static void getCount(String str)
{
// Use LinkedHashmap to store
// elements in insertion order
Map<String, Integer> mp
= new LinkedHashMap<String, Integer>();
for (int i = 0; i < str.length(); i++) {
int count = 0;
// Convert the string element into character
char c = str.charAt(i);
String a = " ";
// Convert the character element
// into string element
a = String.valueOf(c);
// Check string contains the Capital A - Z value.
if (a.matches("[A-Z]")) {
for (int j = i + 1; j < str.length(); j++) {
char d = str.charAt(j);
String b = String.valueOf(d);
// Check string contains the small a-z value.
if (b.matches("[a-z]")) {
a += b;
if (mp.get(a) == null)
mp.put(a, 1);
else
mp.put(a, mp.get(a) + 1);
count = 1;
}
// Check string contains the number value.
else if (b.matches("[\\d]")) {
int k = Integer.parseInt(b);
mp.put(a, k);
count = 1;
}
else {
i = j - 1;
break;
}
}
if (count == 0) {
if (mp.get(a) == null)
mp.put(a, 1);
else
mp.put(a, mp.get(a) + 1);
}
}
}
System.out.println("\nAtom count:");
for (Map.Entry<String, Integer>
entry : mp.entrySet())
System.out.println(entry.getKey()
+ " "
+ entry.getValue());
mp.clear();
}
// Driver code
public static void main(String[] args)
{
String str = "Fe2H3OH";
System.out.println("Given molecule: "
+ str);
getCount(str);
}
}
Python3
# Python program to parse the molecule
# and get the atoms count
def get_count(s):
# Use dictionary to store elements in insertion order
mp = {}
i = 0
while i < len(s):
count = 0
# Convert the string element into character
c = s[i]
# Check string contains the Capital A - Z value.
if c.isupper():
a = " "
# Convert the character element
# into string element
a += c
j = i + 1
while j < len(s):
d = s[j]
# Check string contains the small a-z value.
if d.islower():
a += d
if a not in mp:
mp[a] = 1
else:
mp[a] += 1
count = 1
# Check string contains the number value.
elif d.isdigit():
k = int(d)
mp[a] = k
count = 1
else:
i = j - 1
break
j += 1
if count == 0:
if a not in mp:
mp[a] = 1
else:
mp[a] += 1
i += 1
print("\nAtom count:")
for key, value in mp.items():
print(key, value)
mp.clear()
# Driver code
str = "Fe2H3OH"
print("Given molecule:", str)
get_count(str)
C#
using System;
using System.Collections.Generic;
namespace GFG
{
class Program
{
// Method to get the count of atoms
static void getCount(String str)
{
// Use LinkedHashmap to store
// elements in insertion order
Dictionary<String, int> mp
= new Dictionary<String, int>();
for (int i = 0; i < str.Length; i++)
{
int count = 0;
// Convert the string element into character
char c = str[i];
String a = " ";
// Convert the character element
// into string element
a = c.ToString();
// Check string contains the Capital A - Z value.
if (System.Text.RegularExpressions.Regex.IsMatch(a, "[A-Z]"))
{
for (int j = i + 1; j < str.Length; j++)
{
char d = str[j];
String b = " ";
// Convert the character element
// into string element
b = d.ToString();
// Check string contains the small a-z value.
if (System.Text.RegularExpressions.Regex.IsMatch(b, "[a-z]"))
{
a += b;
if (!mp.ContainsKey(a))
mp.Add(a, 1);
else
mp[a] += 1;
count = 1;
}
// Check string contains the number value.
else if (System.Text.RegularExpressions.Regex.IsMatch(b, "[\\d]"))
{
int k = Convert.ToInt32(b);
mp[a] = k;
count = 1;
}
else
{
i = j - 1;
break;
}
}
if (count == 0)
{
if (!mp.ContainsKey(a))
mp.Add(a, 1);
else
mp[a] += 1;
}
}
}
Console.WriteLine("\nAtom count:");
foreach (KeyValuePair<String, int> entry in mp)
Console.WriteLine(entry.Key
+ " "
+ entry.Value);
mp.Clear();
}
// Driver code
public static void Main(String[] args)
{
String str = "Fe2H3OH";
Console.WriteLine("Given molecule: "
+ str);
getCount(str);
}
}
}
// This code added By Ajax
JavaScript
// Javascript program to parse the molecule
// and get the atoms count
function get_count(s) {
// Use Map to store elements in insertion order
let mp = new Map();
let i = 0;
while (i < s.length) {
let count = 0;
// Convert the string element into character
let c = s.charAt(i);
// Check string contains the Capital A - Z value.
if (c.match(/[A-Z]/)) {
let a = " ";
// Convert the character element
// into string element
a += c;
let j = i + 1;
while (j < s.length) {
let d = s.charAt(j);
// Check string contains the small a-z value.
if (d.match(/[a-z]/)) {
a += d;
if (!mp.has(a)) {
mp.set(a, 1);
} else {
mp.set(a, mp.get(a) + 1);
}
count = 1;
}
// Check string contains the number value.
else if (d.match(/[0-9]/)) {
let k = parseInt(d);
mp.set(a, k);
count = 1;
} else {
i = j - 1;
break;
}
j += 1;
}
if (count == 0) {
if (!mp.has(a)) {
mp.set(a, 1);
} else {
mp.set(a, mp.get(a) + 1);
}
}
}
i += 1;
}
console.log("\nAtom count:");
for (let [key, value] of mp) {
console.log(key, value);
}
mp.clear();
}
// Driver code
let str = "Fe2H3OH";
console.log("Given molecule:", str);
get_count(str);
Output: Given molecule: Fe2H3OH
Atom count:
Fe 2
H 4
O 1
Time Complexity: O(N), Here N is the length of the string.
Auxiliary Space: O(N), The extra space is used in HashMap.
Similar Reads
Count of words that are present in all the given sentences Given n sentences. The task is to count the number of words that appear in all of these sentences.Note that every word consists of only lowercase English alphabets. Examples: Input: arr[] = { "there is a cow", "cow is our mother", "cow gives us milk and milk is sweet", "there is a boy who loves cow"
15 min read
Lex Program to count number of words Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Examp
1 min read
Counting the number of words in a Trie A Trie is used to store dictionary words so that they can be searched efficiently and prefix search can be done. The task is to write a function to count the number of words. Example : Input : root / \ \ t a b | | | h n y | | \ | e s y e / | | i r w | | | r e e | r Output : 8 Explanation : Words for
7 min read
Count of substrings that start and end with 1 in given Binary String Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
12 min read
Count Uppercase, Lowercase, special character and numeric values Given a string, write a program to count the occurrence of Lowercase characters, Uppercase characters, Special characters, and Numeric values. Examples: Input : #GeeKs01fOr@gEEks07 Output : Upper case letters : 5 Lower case letters : 8 Numbers : 4 Special Characters : 2 Input : *GeEkS4GeEkS* Output
5 min read