Advertisement
PifyZ

test.d

Nov 16th, 2016
950
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.91 KB | None | 0 0
  1. import std.stdio: writeln;
  2. import std.array: split;
  3. import std.string: strip, indexOf;
  4. import re = std.regex;
  5.  
  6. struct Atom {
  7.   string name;
  8.   short quantity;
  9. }
  10.  
  11. //struct Molecule {
  12. //  Atom[] atoms;
  13. //}
  14.  
  15. struct Molecule {
  16.   string[] atoms;
  17. }
  18.  
  19. struct ChemicalEquation {
  20.   Molecule[] reactants;
  21.   Molecule[] products;
  22. }
  23.  
  24. void main() {
  25.   auto input = "Al + Fe2O4 -> Fe + Al2O3";
  26.  
  27.   try {
  28.     auto tokens = stringToChemicalEquation(input);
  29.  
  30.     writeln(tokens);
  31.   } catch (Exception e) {
  32.     writeln(e.msg);
  33.   }
  34. }
  35.  
  36. ChemicalEquation stringToChemicalEquation(string str) {
  37.   if (indexOf(str, "->") == -1)
  38.     throw new Exception("Il manque un produit à la réaction !");
  39.  
  40.   auto chemicalEquation = ChemicalEquation();
  41.  
  42.   auto parts = split(str, "->");
  43.   parts = trimArray(parts);
  44.  
  45.   auto reactants = split(parts[0], "+");
  46.   reactants = trimArray(reactants);
  47.  
  48.   auto products = split(parts[1], "+");
  49.   products = trimArray(products);
  50.  
  51.   Molecule[] reactantsMolecules = [];
  52.  
  53.   for (auto i = 0 ; i < reactants.length ; i++) {
  54.     auto product = reactants[i];
  55.     auto molecule = stringToMolecule(product);
  56.  
  57.     reactantsMolecules ~= molecule;
  58.   }
  59.  
  60.   Molecule[] productsMolecules = [];
  61.  
  62.   for (auto i = 0 ; i < products.length ; i++) {
  63.     auto product = products[i];
  64.     auto molecule = stringToMolecule(product);
  65.  
  66.     productsMolecules ~= molecule;
  67.   }
  68.  
  69.   chemicalEquation.reactants = reactantsMolecules;
  70.   chemicalEquation.products = productsMolecules;
  71.  
  72.   return chemicalEquation;
  73. }
  74.  
  75. Molecule stringToMolecule(string str) {
  76.   auto atoms1 = re.matchAll(str, re.regex("[A-Z][a-z]*[0-9]*"));
  77.  
  78.   string[] atoms2 = [];
  79.  
  80.   foreach (atom ; atoms1)
  81.     atoms2 ~= atom.hit;
  82.  
  83.   auto molecule = Molecule();
  84.   molecule.atoms = atoms2;
  85.  
  86.   return molecule;
  87. }
  88.  
  89. string[] trimArray(string[] arr) {
  90.   for (auto i = 0 ; i < arr.length ; i++)
  91.     arr[i] = strip(arr[i]);
  92.  
  93.   return arr;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement