Balance Chemistry Equations - javascript

Lore:
Now that my chemistry class has gone past memorizing equations and whatnot and begun with, example, balancing chemical equations. I could sit down all day long balancing equations, but as programming is my passion I would love to get a program working for me to solve these. This is more or less a pet-project and more for fun rather than giving me an edge in chemistry class. But the more I dwelt into it the more complex it became.
I don't really know how to begin this crusade and have instead worked on the parser and data set, which is in pretty good set to have my head wrapped around it right.
Question:
What I don't know is how to utilize matrices to solve equations (balance equations to conserve mass*) and convert that into whole numbers valid in chemistry.
Code/objects:
class Element {
constructor(name,quantity) {
this.name = name;
this.quantity = quantity;
if (this.quantity == 0) {
this.quantity = 1;
}
}
}
class Molecule {
constructor() {
this.elements = [];
this.multiplier = 1;
}
addElement(newEl) {
this.elements.push(newEl);
}
list() {
this.elements.forEach(el => {
console.log(el.name,el.quantity);
});
}
getMultiplier() {
return this.multiplier;
}
getElements() {
var a = [];
this.elements.forEach(el => {
a.push([el.name,el.quantity*this.multiplier]);
});
return a;
}
}
Code/data structure:
printFormula(moleculeList);
for (var i=0;i<moleculeList[0].length;i++) {
console.log("Mol "+(i+1))
moleculeList[0][i].list();
}
console.log("==>");
for (var i=0;i<moleculeList[1].length;i++) {
console.log("Mol "+(i+1))
moleculeList[1][i].list();
}
Code/output:
'C6H14 + O2 ==> CO2 + H2O'
Mol 1
C 6
H 14
Mol 2
O 2
==>
Mol 1
C 1
O 2
Mol 2
H 2
O 1

I am a chemist and have exactly zero familiarity with Javascript so as to explain it in detail. But the method is fairly simple to show by hand. This link nails it down in a clean manner.
The only reason why I am linking to it without going through the steps in detail is because Stackoverflow does not have LaTeX math in order to make the text easy to follow, so I think you'll benefit better from the text in the link.
Also, I don't think this is a full answer, but I do not have enough reputation to put this on a comment, where it belongs.
I think the hardest bit is finding/coding the appropriate subroutine for row-echelon reduction of the matrix in step-5. But I also believe that there is a vast number of algorithms appropriate for doing that which you can find in the internet. Very handily, this very website has a question related to just that with a python code to sweeten the deal.
I hope this helps you at least wrap your head around it enough to implement the code you need.
Cheers

Related

I am trying to scrape amazon, and stop at a specific number

So this is my code
if (body.included != null && body.included.length > 0) {
let genres = '';
for(let i = 0; i < body.included.length; i++) {
genres += body.included[i].attributes.title;
if(i != body.included.length - 1) {genres += ', ';}
}
embed.addField('GENRES', [`${genres}`,], true);
}
this is the results whenever i search anything with this it gives me this:
Comedy, Kids, Fantasy, Fantasy World, Erotic Torture, Loli, Nudity, Bdsm, Bondage, Sex, Past, Plot Continuity, Violence, Military, Mecha, Historical, Action, Romance, Science Fiction, World War II, Japan, Asia, Piloted Robot, Alternative Past, Steampunk, Gunfights, Alien, War, Robot, Adventure, Space Travel, Cyborg, Crime, Other Planet, Humanoid Alien, Future, Space, Contemporary Fantasy, Vampire, Slice of Life, Detective, Bounty Hunter, Magic, Present, Demon, Super Power, Drama, Anime Influenced, Earth, Love Polygon, Angst, High School, School Life
Has this a example because other types searches comes with 1 or 2 or decent amount of genres where it doesn't have like 40 of them
like this one
Ninja, Fantasy World, Adventure, Action, Comedy, Martial Arts, Super Power, Romance, Disaster, Shounen, Love Polygon, Angst, Plot Continuity, Parallel Universe, Fantasy
So what i need help is how do i make it stop in a certain number where it wont give me 40 of them instead 10 or less
You could change the loop condition but still need to watch out for the length of the body.included array for cases where it has fewer than 10 elements. Try the following:
const MAX_GENRES = 10;
if (body.included && body.included.length) {
const max = Math.min(MAX_GENRES, body.included.length);
const genres = [];
let i = 0;
while (i < max) {
genres.push(body.included[i].attributes.title);
i += 1;
}
embed.addField('GENRES', [genres.join(',')], true);
}
This should achieve what you're after. I don't know the signature for embed.addField() but are you certain that the second argument should be a single-element array containing a string? Could be but seems weird. If the function calls for an array of strings use:
embed.addField('GENRES', genres, true);

how to add numbers with an infinite number of digits using column addition?

I am trying to develop the addition program using column addition in javascript, For e.g: 53,22 , we add numbers from the right 3+2 and 5+2 finally results in 75, the main problem is with large numbers i am trying to develop a program which can implement addition of large numbers.so that i don't get gibberish like 1.26E+9, when adding large numbers. i tried doing it by defining the code like below
function add(a,b)
{
return (Number(a) + Number(b)).toString();
}
console.log(add('58685486858601586', '8695758685'));
i am trying to get the added number without getting the gibberish like 5.8685496e+16
You can add them digit by digit.
function sumStrings(a, b) { // sum for any length
function carry(value, index) { // cash & carry
if (!value) { // no value no fun
return; // leave shop
}
this[index] = (this[index] || 0) + value; // add value
if (this[index] > 9) { // carry necessary?
carry.bind(this)(this[index] / 10 | 0, index + 1); // better know this & go on
this[index] %= 10; // remind me later
}
}
var array1 = a.split('').map(Number).reverse(), // split stuff and reverse
array2 = b.split('').map(Number).reverse(); // here as well
array1.forEach(carry, array2); // loop baby, shop every item
return array2.reverse().join(''); // return right ordered sum
}
document.write(sumStrings('58685486858601586', '8695758685') + '<br>');
document.write(sumStrings('999', '9') + '<br>');
document.write(sumStrings('9', '999') + '<br>');
document.write(sumStrings('1', '9999999999999999999999999999999999999999999999999999') + '<br>');
I would keep all values as numbers until done with all the calculations. When ready to display just format the numbers in any way you want. For example you could use toLocaleString.
There are several libraries for that
A good rule of thumb is to make sure you do research for libraries before you actually go ahead and create you're own proprietary implementation of it. Found three different libraries that all solve your issue
bignumber.js
decimal.js
big.js
Example
This is how to use all three of the libraries, BigNumber coming from the bignumber.js library, Decimal from decimal.js and Big from big.js
var bn1 = new BigNumber('58685486858601586');
var bn2 = new BigNumber('8695758685');
console.log(bn1.plus(bn2).toString());
bn1 = new Decimal('58685486858601586');
bn2 = new Decimal('8695758685');
console.log(bn1.plus(bn2).toString());
bn1 = new Big('58685486858601586');
bn2 = new Big('8695758685');
console.log(bn1.plus(bn2).toString());
The console's output is :
58685495554360271
58685495554360271
58685495554360271

Tallying incorrect answers for Javascript game

So I am trying to make a javascript game for my geography class but I have run into some trouble, I can ask the questions and tell you if you're wrong or not but I would like to be able to keep track of the wrongs answers. I want to keep track using for loops but I'm not good at them, some help would be greatly appreciated!
This is the basis of what every question looks like, it's just that && is where I need to add a single mark to the incorrect tally which I am sure I need to use for loops for.
var y = "You are correct!!!"
var n = "You are incorrect!!!"
alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life.
They are children, working adults, and older adults. What is the age
range for children? 0-13, 0-15, 0-18")
if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
}
If someone could help me out with this it would be sooo helpful, and don't worry this is past do anyways but I still want to know how to do it for future projects!
p.s. I already have the script HTML so I don't need help with that.
var correct = [], // well store the index of the correctly answered questions here
wrong = [], // well store the index of the incorrectly answered questions here
questions = [
{
"question": "Demographers identify three different stages of life. They are children, working adults, and older adults. What is the age range for children?",
"answers": ["0-13", "0-15", "0-18"],
"correct": 0 // correct answer is item of index 0 in property "answers" (0-13)
},
{
"question": "whats your favorite color?",
"answers": ["red", "yellow", "blue", "purple"],
"correct": 2 // blue
}
];
for (var i in questions){
var answer = prompt(questions[i].question + questions[i].answers.join(','));
if (answer == questions[i].answers[questions[i].correct]){
correct.push(i);
}else{
wrong.push(i);
}
}
alert('wrong number of answers: ' + wrong.length);
alert('correct number of answers: ' + correct.length);
alert('first wrong question: ' + questions[wrong[0]].question);
I know this is practically overwngineering what you asked for but it might give you better flexibility and knowledge as to how js for loops work. Hope it helps.
Add a variable to keep track of incorrect answers:
var y = "You are correct!!!"
var n = "You are incorrect!!!"
var incorrectCount = 0;
alert("Chapter 1, Human Cultural Connections. 1-10")
//==================================================
var Q1 = prompt("Demographers identify three different stages of life.
They are children, working adults, and older adults. What is the age
range for children? 0-13, 0-15, 0-18")
if (Q1 === "0-13")
{
alert(y)
}
else
{
alert(n) //&& add 1 tally to incorrect list
incorrectCount++;
}

High school level Spanish 1 & 2 translator bug(made using labs.codeacademy.com)

I am making a high school level Spanish 1 & 2 translator but I have run into a bug; After you are prompted for the word, instead of just giving you the translation it prints out the entire list of translations.
I am using my basic java knowledge gained from the site Codeacademy.com and can not figure out what causes this bug.
P.S. If you can help me in making this process with the if statements easier and quicker I would greatly appreciate it.
Code:
var word = prompt("Word to translate(lower case only):");
//English
var hi;
var white;
//Translate
var hola = hi;
var blanco = white;
var translate = function(word)
{
return word;
};
//Spanish to English
if(translate() === hola)
{
console.log("hi");
}
if(translate() === blanco)
{
console.log("white");
}
//English to Spanish
if(translate() === hi)
{
console.log("hola");
}
if(translate() === white)
{
console.log("blanco");
}
You should brush up on your understanding of variables and functions. You are doing two seemingly confused things.
Firstly, the following code sets all your variables to undefined, and so they all equal each other:
var hi;
var white;
var hola = hi;
var blanco = white;
You should being using statements like var hi = "hi";, which sets the value of the variable hi to the string "hi".
Secondly, when you invoke your translate function, you need to pass it a variable because you defined it as taking a variable word. So you would say translate("hi") for example. You also need to have your translate function actually do something. Right now, it just returns the same string that is passed into it.
The following is a solution, using the simpler techniques you should probably be familiar with based on the lesson. There are more complicated solutions for this kind of problem, but I assumed they are out of scope here.
Codeacademy does an excellent job teaching, so you should really go over the material again to understand what you were doing incorrectly. Good luck!
// English
var hi = "hi";
var white = "white";
// Spanish
var hola = "hola";
var blanco = "blanco";
var translate = function(word)
{
// Spanish to English
if (word === hola)
console.log(hi);
else if (word === blanco)
console.log(white);
// English to Spanish
else if (word === hi)
console.log(hola);
else if (word === white)
console.log(blanco);
};
// Ask for word
var word = prompt("Word to translate(lower case only):");
// Run translation
translate(word);
Demo: http://jsfiddle.net/W8eFp/1 (I have the demo using alert instead of console.log. You can click RUN up at the top to run the prompt again.)

Masked Edit two code formats for a single input text box

I have two masks G999-9 and H99-9 which stand for graduates and honor which both need to be entered for a single input text html control.
While first typing, if it hits a G I would like it to show the format for the Graduate format, and for the Honors, I would like it to show the format for the Honors format while typing it out. Is there a simple way to do this in javascript or jQuery?
Examples:
G111-1
H91-5
G001-3
G___-_ (If you hit G it should show the Graduate format)
H__-_ (If you hit H it should show the Honors format.)
____-_ (Type anything else, or nothing do this.)
Thanks,
Marc
Regex Based Demo
Yay! regex! Yes, like every other (non-HTML) parsing questions there's a regex for that. :)
$("input").keyup(function(e){
if(e.keyCode > 40 || e.keyCode < 37)
{
var validInput = $(this).val().match(/(([G])(([0-9]{3}[-]([0-9]{0,1})?|[0-9]{0,3})?)?|([H])(([0-9]{2}[-]([0-9]{0,1})?|[0-9]{0,2})?)?)/);
$(this).val(validInput?validInput[0]:"")
}
});
It's a bit convoluted (help in optimizing it would be much appreciated), but it works.
Simple way? You're either going to have to walk the string or use some fancy regex.
Normally, we'd use regexes for this, but with the assumption that you don't know so much about regexes (perhaps a bad assumption, but most people that can read them will gravitate towards them first) and in the hopes of keeping you following what is happening, I wrote it more procedurally:
<input type="text" class="formatted" />
$(document).ready(function(){
function applyMask(instr){
var pOut = [], delimitter = '-', format = 0, pSplit = 4, pMax = 6;
// There are a lot of ways to express this. I just chose one that should
// be understandable.
if ((instr.length > 0) && (instr[0].toUpperCase() == 'H'))
{
pSplit = 3;
pMax = 5;
}
pMax = Math.min(pMax, instr.length);
for (var i=0; i < pMax; i++)
{
if ((i==pSplit) && (instr[i] != delimitter))
{
pOut.push(delimitter);
}
else
{
pOut.push(instr[i]);
}
}
return pOut.join('');
}
$('.formatted').keyup(function(){
$(this).val(applyMask($(this).val()).toUpperCase());
});
});
Here's a fiddle, even: http://jsfiddle.net/UdcND/
There are some jQuery plugins for easily converting a text input to a mask edit:
a simple but useful plugin: http://www.pengoworks.com/workshop/js/mask/
another good option: http://digitalbush.com/projects/masked-input-plugin/

Categories