Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Chemical Equation Balance

Chemical Equation Balance

Scheduled Pinned Locked Moved C#
tutorialcsharphelpquestionlearning
17 Posts 10 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S stephen darling

    Hello. I am still learning C# and as a new project, I wanted to write a simple chemical equation balancer, but dont really know where to start. I am not asking for code, as I really want to have a go at this myself, so if I show my views below on how I would imagine tackling this problem, maybe someone could point me in the correct direction. An example of a chemical equation, a simple one, would be... H2 + O2 = H2O Balanced, we end up with..... 2H2 + O2 = 2H2O I was thinking of the following steps... 1) Parse the left side (reactants) into one string, and the right side (Products) into a seperate string. 2) Loop through the string looking for the letters representing the elements and the numbers to count how many we have 3) ** Havent got a clue how to manage this ** maybe use some kind of matriz to store all the values and then use logic to "balance" the equation. Does anyone have any ideas or tips? Thank you, Regards, Steve

    K Offline
    K Offline
    Keith Barrow
    wrote on last edited by
    #6

    Just my tuppenceworth, the other answers have been good. There is a full balancing method here[^]. It should transfer to an algorithm easily. For the data representation I'd use two dictionaries, one for the number atoms on the LHS, the other for the right. You can make the chemical symbol the key, but you might also like an element class, that way you can do other handy stuff like work out the molar mass of the products etc. I actually think the formula parser might be the hard part, but not having worked on the problem fully I could well be wrong.

    Sort of a cross between Lawrence of Arabia and Dilbert.[^]
    -Or-
    A Dead ringer for Kate Winslett[^]

    1 Reply Last reply
    0
    • S stephen darling

      Hello. I am still learning C# and as a new project, I wanted to write a simple chemical equation balancer, but dont really know where to start. I am not asking for code, as I really want to have a go at this myself, so if I show my views below on how I would imagine tackling this problem, maybe someone could point me in the correct direction. An example of a chemical equation, a simple one, would be... H2 + O2 = H2O Balanced, we end up with..... 2H2 + O2 = 2H2O I was thinking of the following steps... 1) Parse the left side (reactants) into one string, and the right side (Products) into a seperate string. 2) Loop through the string looking for the letters representing the elements and the numbers to count how many we have 3) ** Havent got a clue how to manage this ** maybe use some kind of matriz to store all the values and then use logic to "balance" the equation. Does anyone have any ideas or tips? Thank you, Regards, Steve

      D Offline
      D Offline
      David1987
      wrote on last edited by
      #7

      No trial and error or inelegant algorithms are needed. The problem can be solved by solving a system of linear equations, constructed like this: As2S3 + HNO3 + H2O = H3AsO4 + H2SO4 + NO (unbalanced) Should be turned into the system: (disclaimer: it was really quite late when I did this, so don't look at the numbers too closely the general principle should be sound though)

      2 x0 + 0 x1 + 0 x2 - 1 x3 - 0 x4 - 0 x5 = 0 // for As
      3 x0 + 0 x1 + 0 x2 - 0 x3 - 1 x4 - 0 x5 = 0 // for S
      0 x0 + 1 x1 + 2 x2 - 3 x3 - 1 x4 - 0 x5 = 0 // for H
      0 x0 + 1 x1 + 0 x2 - 0 x3 - 0 x4 - 1 x5 = 0 // for N
      0 x0 + 3 x1 + 1 x2 - 4 x3 - 4 x4 - 1 x5 = 0 // for O

      The variables correspond to how many times the molecule from the unbalanced equation is needed, the coefficients correspond to how many of the element are in the corresponding molecule. If I did the math correctly, it gives: 3 As2S3 + 28 HNO3 + 4 H2O = 6 H3AsO4 + 9 H2SO4 + 28 NO Does that help you any?

      L S 2 Replies Last reply
      0
      • D David1987

        No trial and error or inelegant algorithms are needed. The problem can be solved by solving a system of linear equations, constructed like this: As2S3 + HNO3 + H2O = H3AsO4 + H2SO4 + NO (unbalanced) Should be turned into the system: (disclaimer: it was really quite late when I did this, so don't look at the numbers too closely the general principle should be sound though)

        2 x0 + 0 x1 + 0 x2 - 1 x3 - 0 x4 - 0 x5 = 0 // for As
        3 x0 + 0 x1 + 0 x2 - 0 x3 - 1 x4 - 0 x5 = 0 // for S
        0 x0 + 1 x1 + 2 x2 - 3 x3 - 1 x4 - 0 x5 = 0 // for H
        0 x0 + 1 x1 + 0 x2 - 0 x3 - 0 x4 - 1 x5 = 0 // for N
        0 x0 + 3 x1 + 1 x2 - 4 x3 - 4 x4 - 1 x5 = 0 // for O

        The variables correspond to how many times the molecule from the unbalanced equation is needed, the coefficients correspond to how many of the element are in the corresponding molecule. If I did the math correctly, it gives: 3 As2S3 + 28 HNO3 + 4 H2O = 6 H3AsO4 + 9 H2SO4 + 28 NO Does that help you any?

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #8

        yep, linear equations it is; each different element gives one equation, and the unknowns are the amounts of each of the molecules. the one funny thing is there could be more equations than unknowns, making either some of them redundant, or the problem unsolvable (obviously you can't balance H2O = H2SO4 ). :)

        Luc Pattyn [My Articles] Nil Volentibus Arduum

        Richard Andrew x64R 1 Reply Last reply
        0
        • L Luc Pattyn

          yep, linear equations it is; each different element gives one equation, and the unknowns are the amounts of each of the molecules. the one funny thing is there could be more equations than unknowns, making either some of them redundant, or the problem unsolvable (obviously you can't balance H2O = H2SO4 ). :)

          Luc Pattyn [My Articles] Nil Volentibus Arduum

          Richard Andrew x64R Offline
          Richard Andrew x64R Offline
          Richard Andrew x64
          wrote on last edited by
          #9

          Luc Pattyn wrote:

          yep, linear equations it is

          Geez, man. Is there anything you don't know? :)

          The difficult we do right away... ...the impossible takes slightly longer.

          L 1 Reply Last reply
          0
          • Richard Andrew x64R Richard Andrew x64

            Luc Pattyn wrote:

            yep, linear equations it is

            Geez, man. Is there anything you don't know? :)

            The difficult we do right away... ...the impossible takes slightly longer.

            L Offline
            L Offline
            Luc Pattyn
            wrote on last edited by
            #10

            I only know a tiny fraction of all there is to know, however I try and make up for it by applying simple logic. :-D And chemical formulae are all about preserving the elements...

            Luc Pattyn [My Articles] Nil Volentibus Arduum

            1 Reply Last reply
            0
            • S stephen darling

              Hello. I am still learning C# and as a new project, I wanted to write a simple chemical equation balancer, but dont really know where to start. I am not asking for code, as I really want to have a go at this myself, so if I show my views below on how I would imagine tackling this problem, maybe someone could point me in the correct direction. An example of a chemical equation, a simple one, would be... H2 + O2 = H2O Balanced, we end up with..... 2H2 + O2 = 2H2O I was thinking of the following steps... 1) Parse the left side (reactants) into one string, and the right side (Products) into a seperate string. 2) Loop through the string looking for the letters representing the elements and the numbers to count how many we have 3) ** Havent got a clue how to manage this ** maybe use some kind of matriz to store all the values and then use logic to "balance" the equation. Does anyone have any ideas or tips? Thank you, Regards, Steve

              D Offline
              D Offline
              dasblinkenlight
              wrote on last edited by
              #11

              As others have noted, the problem can be re-stated in terms of a system of linear equations. A particularly easy method to solve such systems (in relative terms, of course - it's a decent homework assignment for a second-year CS student) is the method of Gaussian Elimination[^]. Here is a Java implementation of what you are trying to build[^], conveniently packaged with a source code. The implementation is very easy to follow, even if you do not know Java (but do know some C#). Good luck!

              S 1 Reply Last reply
              0
              • S stephen darling

                Hi, Thank you, this was pretty much what I was thinking. Do you have any ideas of the best way to store and sort the terms? i.e. Should I use a struct for the elements? etc I am still a beginner so any advice is most welcomed. Kind Regards, Stephen

                S Offline
                S Offline
                secorbett
                wrote on last edited by
                #12

                I would probably set this up as two arrays, operands (left side) and results (right side). The arrays would contain structures that have two elements. The first element would be the multiplier for the particular item, and a dictionary with the element symbol as the key and the how much as the value. The Dictionary object has a sort method built in, but you'll probably want to write your own to meet the requirements for sorting the particular elements according the the standard rules of chemistry. For example S comes before O for SO4. I hope you find this approach helpful. If you have any questions, feel free to ask.

                Scott E. Corbett Software Engineer/Analyst

                1 Reply Last reply
                0
                • D David1987

                  No trial and error or inelegant algorithms are needed. The problem can be solved by solving a system of linear equations, constructed like this: As2S3 + HNO3 + H2O = H3AsO4 + H2SO4 + NO (unbalanced) Should be turned into the system: (disclaimer: it was really quite late when I did this, so don't look at the numbers too closely the general principle should be sound though)

                  2 x0 + 0 x1 + 0 x2 - 1 x3 - 0 x4 - 0 x5 = 0 // for As
                  3 x0 + 0 x1 + 0 x2 - 0 x3 - 1 x4 - 0 x5 = 0 // for S
                  0 x0 + 1 x1 + 2 x2 - 3 x3 - 1 x4 - 0 x5 = 0 // for H
                  0 x0 + 1 x1 + 0 x2 - 0 x3 - 0 x4 - 1 x5 = 0 // for N
                  0 x0 + 3 x1 + 1 x2 - 4 x3 - 4 x4 - 1 x5 = 0 // for O

                  The variables correspond to how many times the molecule from the unbalanced equation is needed, the coefficients correspond to how many of the element are in the corresponding molecule. If I did the math correctly, it gives: 3 As2S3 + 28 HNO3 + 4 H2O = 6 H3AsO4 + 9 H2SO4 + 28 NO Does that help you any?

                  S Offline
                  S Offline
                  stephen darling
                  wrote on last edited by
                  #13

                  Dear David1987, Sorry, no, it does not help at all unfortunatly. I can't seem to work out what is going on here, although I suspect if I did it may prove a usefull way of approaching the problem. Is there any chance you could show me what you mean, or maybe simplyfy it a little? Thank you

                  D 1 Reply Last reply
                  0
                  • D dasblinkenlight

                    As others have noted, the problem can be re-stated in terms of a system of linear equations. A particularly easy method to solve such systems (in relative terms, of course - it's a decent homework assignment for a second-year CS student) is the method of Gaussian Elimination[^]. Here is a Java implementation of what you are trying to build[^], conveniently packaged with a source code. The implementation is very easy to follow, even if you do not know Java (but do know some C#). Good luck!

                    S Offline
                    S Offline
                    stephen darling
                    wrote on last edited by
                    #14

                    Thank you everyone for your help. However, I think as a complete beginner, I may have bitten off more than I can chew, as I dont have a clue where to start based on the information provided. Thank you again, Stephen

                    1 Reply Last reply
                    0
                    • S stephen darling

                      Dear David1987, Sorry, no, it does not help at all unfortunatly. I can't seem to work out what is going on here, although I suspect if I did it may prove a usefull way of approaching the problem. Is there any chance you could show me what you mean, or maybe simplyfy it a little? Thank you

                      D Offline
                      D Offline
                      David1987
                      wrote on last edited by
                      #15

                      Ok, let's take O2 + H2 = H2O then. First I'll assign variables to the molecules: O2 = x0 H2 = x1 H2O = x2 Then I build the equations, one for each element, the coefficients are how much of the current element is in the corresponding molecule: H: 0 x0 + 2 x1 - 2 x2 = 0 // there is zero H in O2, 2 H in H2, 2 H in H2O O: 2 x0 + 0 x1 - 1 x2 = 0 // there is 2 O in O2, zero O in H2, 1 O in H2O The smallest solution where all variables are integers is x0 = 1, x1 = 2, x2 = 2, which corresponds to O2 + 2 H2 = 2 H2O

                      S 1 Reply Last reply
                      0
                      • S stephen darling

                        Hello. I am still learning C# and as a new project, I wanted to write a simple chemical equation balancer, but dont really know where to start. I am not asking for code, as I really want to have a go at this myself, so if I show my views below on how I would imagine tackling this problem, maybe someone could point me in the correct direction. An example of a chemical equation, a simple one, would be... H2 + O2 = H2O Balanced, we end up with..... 2H2 + O2 = 2H2O I was thinking of the following steps... 1) Parse the left side (reactants) into one string, and the right side (Products) into a seperate string. 2) Loop through the string looking for the letters representing the elements and the numbers to count how many we have 3) ** Havent got a clue how to manage this ** maybe use some kind of matriz to store all the values and then use logic to "balance" the equation. Does anyone have any ideas or tips? Thank you, Regards, Steve

                        E Offline
                        E Offline
                        Ennis Ray Lynch Jr
                        wrote on last edited by
                        #16

                        If college chemistry can offer me anything it was that no equation balancer should be based on text input. The one I had to use was so bad I dared the prof. to fail me because I wasn't going to waste my time discovering how it wanted me to type. Graphics and numeric up downs in a visually appealing manner are the way to go.

                        Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. I also do Android Programming as I find it a refreshing break from the MS. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost

                        1 Reply Last reply
                        0
                        • D David1987

                          Ok, let's take O2 + H2 = H2O then. First I'll assign variables to the molecules: O2 = x0 H2 = x1 H2O = x2 Then I build the equations, one for each element, the coefficients are how much of the current element is in the corresponding molecule: H: 0 x0 + 2 x1 - 2 x2 = 0 // there is zero H in O2, 2 H in H2, 2 H in H2O O: 2 x0 + 0 x1 - 1 x2 = 0 // there is 2 O in O2, zero O in H2, 1 O in H2O The smallest solution where all variables are integers is x0 = 1, x1 = 2, x2 = 2, which corresponds to O2 + 2 H2 = 2 H2O

                          S Offline
                          S Offline
                          stephen darling
                          wrote on last edited by
                          #17

                          Hi, OK that helps a little better, but I would have no idea how to implement this into code. It has gave me something to think about though. Thank you again, Stephen

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups