{"id":258,"date":"2020-01-10T17:15:47","date_gmt":"2020-01-10T17:15:47","guid":{"rendered":"https:\/\/www.samarthya.me\/wps\/?p=258"},"modified":"2020-01-10T17:15:47","modified_gmt":"2020-01-10T17:15:47","slug":"maths-problem-in-js","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2020\/01\/10\/maths-problem-in-js\/","title":{"rendered":"Maths problem in JS"},"content":{"rendered":"<h2>Objective<\/h2>\n<p>Solve a simple math problem.<\/p>\n<blockquote>\n<p>Parse and evaluate simple math word problems returning the answer as an integer.<\/p>\n<\/blockquote>\n<h2>RegularExpression (JS)<\/h2>\n<p>We will utilize regular expression to identify and parse the elements from the input string.<\/p>\n<blockquote>\n<p>Regular expressions are patterns used to match character combinations in strings.<\/p>\n<\/blockquote>\n<h3>Defining<\/h3>\n<hr \/>\n<p>You can define a regular expression to be evaluated by using either of the two approaches mentioned below.<\/p>\n<h4>Slashes<\/h4>\n<pre>let exp = \/[0-9]*\/;<\/pre>\n<h4>Constructor<\/h4>\n<p>let exp = new RegExp(&#8216;[0-9]*&#8217;);<\/p>\n\n\n<p>First lets define the patterns to identify thee numerals.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>It can be positive or negative<\/li><li>It can be single digit or more than one.<\/li><\/ol>\n\n\n\n<pre class=\"wp-block-preformatted\">const Numeric = \/-?\\d+\\b\/g; \/\/ Matches any digital numeric.<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Elements<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Numeric<\/h3>\n\n\n\n<p>Numeric defined above allows you match for any 1 or more (+) digits (\\d) ending at a words boundary (\\b) and starting with an optional (-?) negative symbol to denote a negative number.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>You can find more information <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Regular_Expressions\">here<\/a>.<\/p><\/blockquote>\n\n\n\n<p>The regular expression can be evaluated against any string input. I used a method called <em>match()<\/em><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>String.match(regular_expression)<\/p><\/blockquote>\n\n\n\n<p>This method returns<\/p>\n\n\n\n<p>An <em>Array<\/em> whose contents depend on the presence or absence of the global (<code>g<\/code>) flag, or null <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/null\"><\/a>if no matches are found.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>If the <code>g<\/code>&nbsp;flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.<\/li><li>if the <code>g<\/code> flag is not used,&nbsp;only the first complete \nmatch and its related capturing groups are returned. In this case, the \nreturned item will have additional properties as described below.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Operations<\/h3>\n\n\n\n<p>Likewise we can employ a similar regular expression to identify the operations.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>const ADDITION = \/\\bplus\\b\/ig;<\/p><p>const SUBTRACTION = \/\\bminus\\b\/ig;<\/p><p>const DIVIDE = \/\\bdivided\\b\/ig;<\/p><p>const MULTIPLICATION = \/\\bmultiplied\\b\/ig;<\/p><\/blockquote>\n\n\n\n<p>The &#8216;i&#8217; is for ignoring the case.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Parsing<\/h2>\n\n\n\n<p>Before we write our logic to compute the Mathematical equivalent, we need to parse the information from the input string (question).<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>this.numbers = this.question.match(Numeric).map((ele, i, arr) => parseInt(ele));<\/p><\/blockquote>\n\n\n\n<ul class=\"wp-block-list\"><li>this.numbers: Identifies the numerals present in the input string; All of them.<\/li><li>this.question: It is the input string.<\/li><li>Method match(): Takes the RegEx Numeric defined above.<\/li><li>Map() allows mapping of the string parsed into a integer. <\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Logic<\/h2>\n\n\n\n<p>The v1.0 I wrote is very basic, without much optimization. It simply splits the question (separated by &#8221; &#8220;) and passed over each token to identify the operation and performs the operation on the Numerals identified in the previous step.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">1. if (this.question != null) {      \n2.          const elements = this.question.split(\" \");\n3.          for (const element of elements) {<\/pre>\n\n\n\n<p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/String\/split\">split<\/a>(seperator) is a method that tokenizes the input string.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>It returns an Array of strings, split at each point where the separator occurs in the given string.<\/p><\/blockquote>\n\n\n\n<pre class=\"wp-block-preformatted\">4. if (element.match(ADDITION) != null) {\n5.          if (index+1 &lt;= this.numbers.length) {\n6.            sum += (this.numbers[index] + this.numbers[index-1]);\n7.          } else {\n8.            sum += this.numbers[index-1]\n9.          }\n10.          index += 2;\n11.       }<\/pre>\n\n\n\n<p>While we iterate through the individual element of the tokenized string. We can evaluate the operation found by matching the operation found. In 4. above we are looking for operation ADDITION if present we will move to check how many numerals were found.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>We have also defined a variable index that start at 1, it allows us to ensure we perform binary operation. It will just be clear why.<\/p><\/blockquote>\n\n\n\n<p>If the operation is found we need to perform x + y, where x is the first element found and y will be the second element if present.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Checks<\/h3>\n\n\n\n<p>Loops starts with index at 1, assume we send in a statement<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>What is 50 plus 3?<\/p><\/blockquote>\n\n\n\n<p>The operation is plus and the numerals identified are [53, 2]<\/p>\n\n\n\n<p>When line 5. is executed the first time<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">index = 1;\nso\nindex + 1 = 2 is &lt;= 2 which is [53, 2]\nso sum is calculated to be\nnumbers[0] + numbers[1]\n= 50 + 3\n= 53<\/pre>\n\n\n\n<p>If it was just one number instead of two assuming just 50, then for the same loop<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">index = 1;\nindex + 1 = 2 is not &lt;= 1 so the loop else is evaluated\nsum = numbers[1-1 = 0]\nsum = 50.<\/pre>\n\n\n\n<p class=\"has-text-align-center\">&#8212; THE &#8211; END &#8212;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Objective Solve a simple math problem. Parse and evaluate simple math word problems returning the answer as an integer. RegularExpression (JS) We will utilize regular expression to identify and parse the elements from the input string. Regular expressions are patterns used to match character combinations in strings. Defining You can define a regular expression to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":259,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[1],"tags":[19,28,27],"class_list":["post-258","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-others","tag-js","tag-maths","tag-regularexpression"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/258","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=258"}],"version-history":[{"count":0,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/258\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media\/259"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=258"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=258"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=258"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}