Giter VIP home page Giter VIP logo

github-externship-assignment's People

Contributors

mayur-rammer avatar visharma-symbl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

github-externship-assignment's Issues

Github-Externship-Assignment solution by Harsh Jain

Approach

  • Split the equation string to get values of A, B, C, and D.
  • Check the variable having the '?' sign.
  • Calculate the value of the variable by solving the equations.
  • Compare the output value of the variable with the one extracted from the equation.
  • Find the missing digit and return it as Integer.

Methods

findMissingDigit() :

  • parameter - String
  • Method signature : findMissingDigit(equation)
  • return value - Integer
  • It splits the string and then calculates the missing digit by comparing the actual value(got by solving the equations) with the one extracted from the equation.

Solution.js code

class FixEquation {

    findMissingDigit(equation) {
        if (!equation) return -1;

        const values = equation.split(/[+,*,=,]/)

        if (!values) return -1;

        let A = values[0].trim();
        let B = values[1].trim();
        let C = values[2].trim();
        let D = values[3].trim();
        let outputString, desiredString;

        if (D.includes('?')) {
            let pA = parseInt(A);
            let pB = parseInt(B);
            let pC = parseInt(C);
            const result = pA * pB + pC;
            outputString = result.toString();
            desiredString = D;
        } else if (A.includes('?')) {
            let pD = parseInt(D);
            let pB = parseInt(B);
            let pC = parseInt(C);
            if ((pD - pC) % pB === 0) {
                const result = (pD - pC) / pB;
                outputString = result.toString();
                desiredString = A;
            } else {
                return -1;
            }
        } else if (B.includes('?')) {
            let pD = parseInt(D);
            let pA = parseInt(A);
            let pC = parseInt(C);
            if ((pD - pC) % pA === 0) {
                const result = (pD - pC) / pA;
                outputString = result.toString();
                desiredString = B;
            } else {
                return -1;
            }
        } else if (C.includes('?')) {
            let pD = parseInt(D);
            let pA = parseInt(A);
            let pB = parseInt(B);
            if (pD % (pA * pB) === 0) {
                const result = pD / (pA * pB);
                outputString = result.toString();
                desiredString = C;
            } else {
                return -1;
            }
        }

        if (outputString.length === desiredString.length) {
            const missingDigitIndex = desiredString.indexOf('?');
            return outputString[missingDigitIndex];
        } else {
            return -1;
        }
    }
}

const Main = () => {
    let solution = new FixEquation();
    const tests = [
        '42 * 47 + 2 = 1?76',
        '4? * 47 + 2 = 1976',
        '42 * ?7 + 2 = 1976',
        '42 * ?47 + 2 = 1976',
        '2 * 12? + 2 = 247',
    ];

    tests.forEach((test, index) => {
        const answer = solution.findMissingDigit(test);
        if (answer === -1) {
            console.log(`Test Case ${index} :
                Equation : ${test}
                Returns: -1
                No solution for the given equation exists, returned -1\n`);
        } else {
            console.log(`Test Case ${index} :
                Equation : ${test}
                Returns: ${answer}
                Missing digit is : ${answer}\n`);
        }
    });
};

Main();

outputextern

Github Externship Assignment Solution

Proposed Solution:

  • Splited the equation based on space and find the constant which has '?' in it.
  • Then evaluated the value of the constant
  • If the value of the constant turns out to be negative or if it's a decimal returned -1
  • If removing the '?' in constant gave the same evaluated value returned -1
  • Replaced the '?' in constant and if it turns out to be equal to evaluated value solution exist and returns the digit else returns -1
    Have linked the pull request below.
    #32

Externship Assignment Solution by Neha Kumari

Closes: #46
Brief Explanation

Time Complexity - O(N), N = length of expression
Space Complexity - O(1)

  • Declared a function in class FixEquation for finding the missing digit.
  • Created a function to run the given test cases in the documentation.

Approach

  • The equation is split into numbers using regular expression (/[+,*,=,]/)
  • Out of the numbers found out the number which has a missing digit by checking the presence of '?'
  • Found out the Number which has a missing digit with the help of valid Numbers.
  • Checked if the number found is valid or not and returned the result appropriately.
    Link to the solution: https://github.com/neha-93/Github-Externship-Assignment/blob/main/Solution.js

image

Github-Externship-Assignment-RefPR-#19

Problem statement

You are given a String equation containing an equation of the form A * B + C = D, where A, B, C and D are positive integers that don't have leading zeros.
One digit in the equation is missing.
Determine and return the correct digit.
If the missing digit cannot be determined (i.e., there is no solution or there is more than one solution), return -1 instead.

Constraints

  • Equation will have the form A * B + C = D.
  • Each of A, B, C, D will be a non-empty string of 1 to 4 characters, i.e., 1 <= length of A, B, C, D <= 4.
  • Each character in each of A, B, C, D will be either a digit ('0'-'9') or a question mark ('?').
  • There will be exactly one question mark in the equation.
  • The numbers represented by A, B, C, D will not have leading zeros.

Approach Followed For Solution

  • split the equation to get individual terms.
  • check for a term with "?" and calculate the corresponding term
  • convert calculated integer term to string and replace the "?" in original term with a digit at the corresponding index of calculated term
  • compare them if equal return the digit at ith index else return -1

Pull Request Reference: #19

Github Externship Assignment Solution - Steve D James

Name : Steve D James
github username: stevedjames

I have tried solving the problem using python and also commented the steps and the output came out working fine.

def MissingDigit(exp):

# Split the expression 
exp = list(exp.split())

first_operand = exp[0]
second_operand = exp[2]
third_operand = exp[4]

resultant = exp[-1]

# If ? is present in resultant
if '?' in resultant:
	x = resultant
	first_operand = int(first_operand)
	second_operand = int(second_operand)
	third_operand = int(third_operand)

	res = (first_operand * second_operand) + third_operand

# If ? in present in operands
else:

	resultant = int(resultant)

	# If ? in the first operand
	if '?' in first_operand:

		x = first_operand
		second_operand = int(second_operand)
		third_operand = int(third_operand)

		res = int((resultant - third_operand)//second_operand)
	# If ? is in the second operand
	elif '?' in second_operand:

		x = second_operand
		first_operand = int(first_operand)
		third_operand = int(third_operand)

		res = int((resultant-third_operand)/first_operand)
	# If ? is in the third operand
	else:
	    x= third_operand
	    first_operand = int(first_operand)
	    second_operand = int(second_operand)
	    
	    res = int(resultant - (first_operand*second_operand))

res = str(res)
k = 0
for i in x:
	if i == '?':
		result = res[k]

print(res)

		final_res = x.replace('?',str(result))

print(final_res)

		if(int(final_res)==int(res)):
		    return result
		else:
		    return -1
		break
	else:
		k = k + 1

main

if name == 'main':
# input
exp = "42 * 47 + 2 = 179?"

print(MissingDigit(exp))

Solution for Github-Externship-Assignment

Approach :

Extracting values of A, B, C, D from the equation using split and trim method and then using simple mathematics for solving the equation.

Code :

const findMissingDigit = (equation) => {
  let equa = equation.split(/[+,*,=]/);
  let sol;
  const [A, B, C, D] = equa.map((e) => e.trim());

  //Function for returning result
  const returnResult = (sol, ele) => {
    const indexOfMark = ele.indexOf("?");
    if (
      sol == ele.replace("?", "") ||
      sol != ele.replace("?", sol[indexOfMark])
    ) {
      return -1;
    }
    return parseInt(sol[indexOfMark]);
  };

  if (A.includes("?")) {
    sol = ((parseInt(D) - parseInt(C)) / parseInt(B)).toString();
    return returnResult(sol, A);
  } else if (B.includes("?")) {
    sol = ((parseInt(D) - parseInt(C)) / parseInt(A)).toString();
    return returnResult(sol, B);
  } else if (C.includes("?")) {
    sol = (parseInt(A) * parseInt(B) - parseInt(D)).toString();
    return returnResult(sol, C);
  } else if (D.includes("?")) {
    sol = (parseInt(A) * parseInt(B) + parseInt(C)).toString();
    return returnResult(sol, D);
  }
};

//All the Testcases
const testCases = [
  "42 * 47 + 2 = 1?76",
  "4? * 47 + 2 = 1976",
  "42 * ?7 + 2 = 1976",
  "42 * ?47 + 2 = 1976",
  "2 * 12? + 2 = 247",
];
testCases.forEach((Case) => {
  console.log(findMissingDigit(Case));
});

TestCases Result:

image

Thank You for the opportunity.

SymblAi open-source assignment solution by Tushar Sachan (Cyberghost2023) - PR #81

Pull Request Reference: #81
Link for solution - https://github.com/CyberGhost2023/Github-Externship-Assignment/blob/feat/sol-branch/Solution.js

Screenshot from 2021-12-12 00-18-33
Screenshot from 2021-12-12 00-18-19

Algorithm Used-

  1. Spilt the string and store the number's string in variables A, B, C and D respectively.
  2. Check for each A, B, C and D for '?'
  3. If A contains '?' ,
    i) parse B,C, and D into integer.
    ii) check if (D-C)>0 and (D-C)%B==0, if true compare the string form of (D-C)/B with A and if digit possible return digit, else for all other cases return -1.
  4. If B contains '?' ,
    i) parse A,C, and D into integer.
    ii) check if (D-C)>0 and (D-C)%A==0, if true compare the string form of (D-C)/A with B and if digit possible return digit, else for all other cases return -1.
  5. If C contains '?' ,
    i) parse A,B, and D into integer.
    ii) check if (D-AB)>0 , if true compare the string form of (D-AB) with C and if digit possible return digit, else for all other cases return -1.
  6. If D contains '?' ,
    i) parse A,B, and C into integer.
    ii) compare the string form of (A*B+C) with D and if digit possible return digit, else for all other cases return -1.
  7. To compare two strings, check whether their length is equal or not and indexes of strings other than index of '?' are same or not. If true, answer is digit at index of '?' in compared string.

Github-Externship-Assignment Solution - Akshat Sharma

Algorithm

  1. Extract A, B, C, and D variables from the equation.
  2. Find the location of the variable containing '?' and the location of '?' in that variable.
  3. Depending upon the location of the variable containing '?' solve the equation to find the value of variable having '?'.
  4. Compare the length of the calculated value with the length of the variable having '?'.
  5. If different then return -1.
  6. Now, replace the '?' with the correct digit.
  7. Compare both the numbers . If same then return the missing digit else return -1.

Functions

1. findMissingDigit

Parameter - String
Returns - Integer
This function finds the missing digit and returns -1 if the missing digit cannot be determined else returns the missing digit.

2. parseString

Parameter - String
Returns - Array
This function returns the value of A, B, C, and D from the equation in the form of an array.

3. checkLocation

Parameter - Array
Returns - Array
This function finds the location of the variable having '?' from an array and also finds out the location of '?' in that variable.

Code

class FixEquation {
  findMissingDigit(equation) {
    const values = this.parseString(equation);
    const [location, markLocation] = this.checkLocation(values);
    let convertedValues = [];
    let number;

    for (let i = 0; i < values.length; i++) {
      if (i !== location) {
        convertedValues.push(Number(values[i]));
      }
    }

    if (location === 0 || location === 1) {
      number = (convertedValues[2] - convertedValues[1]) / convertedValues[0];
    } else if (location === 2) {
      number = convertedValues[2] / (convertedValues[1] * convertedValues[0]);
    } else {
      number = convertedValues[0] * convertedValues[1] + convertedValues[2];
    }

    number = number.toString();
    if (values[location].length !== number.length) {
      return -1;
    }

    values[location] = values[location].replace("?", number[markLocation]);

    if (values[location] === number) {
      return Number(number[markLocation]);
    }

    return -1;
  }

  parseString(eqn) {
    let num = "";
    let values = [];
    for (let char of eqn) {
      if (char === "*" || char === "+") {
        values.push(num);
        num = "";
      } else if (char === "=") {
        values.push(num);
        num = "";
      } else if (char !== " ") {
        num += char;
      }
    }
    values.push(num);

    return values;
  }
  checkLocation(values) {
    let location;
    let markLocation;
    for (let i = 0; i < values.length; i++) {
      if (isNaN(Number(values[i]))) {
        location = i;
        break;
      }
    }

    for (let i = 0; i < values[location].length; i++) {
      if (values[location][i] === "?") {
        markLocation = i;
      }
    }

    return [location, markLocation];
  }
}

function main() {
  fix = new FixEquation();

  const tests = [
    "42 * 47 + 2 = 1?76",
    "4? * 47 + 2 = 1976",
    "42 * ?7 + 2 = 1976",
    "42 * ?47 + 2 = 1976",
    "2 * 12? + 2 = 247",
  ];
  tests.forEach((test, idx) => {
    console.log(`Test Case # ${idx}:\nOutput:`);
    console.log(fix.findMissingDigit(test));
  });
}

main();

Output

image

Github Externship Assignment - Harshal Kaigaonkar (Also Have a Live Version of it)

Hey, It was a great problem have some nice base cases.

Here's the live deployed version: https://GithubExternshipAssignmentharshalkaigaonkar.harshalkai.repl.co
Here's the JS Snippet for HTML, CSS, and Vanilla JS version: https://replit.com/@harshalkai/GithubExternshipAssignmentharshalkaigaonkar#script.js
Here's the Java Version of it (just had a curiosity to code in it): https://replit.com/@harshalkai/symblai-Github-externship-challenge#Main.java

Here's my Approach:

  1. Firstly, Split the main input equation string using regex as " ".
  2. Then, Iterate over the whole string looking for "?" or "=" earlier which will tell us that does "?" comes from L.H.S. side or
    R.H.S.
    Side and according to it follows some conditionals.
  3. Now, if "?" comes at the R.H.S. side, we find the d's value in Number and compare it with the actual string value to get value
    at "?". Here also, there are some base cases that are taken care of.
  4. If the earlier condition fails, there are more conditionals to check if the "?" contains in a / b / c and according to it, the
    output is being generated using the same function. With also some base cases generated due to the entrance of the
    Division of numbers.

Thank you.

Really Looking forward to hearing from you.
It refers #16

Github-Externship-Assignment solution by Govind Singh Bisht

Problem Statement:
Given a String equation containing an equation of the form A * B + C = D, where A, B, C, and D are positive integers that don't have leading zeros. One digit in the equation is missing.

Example: 42 * 47 + 2 = 1?76 in this equation one digit is missing that is 9.

Expected behavior:
Determine and return the correct digit and if the missing digit cannot be determined (i.e., there is no solution or there is more than one solution), return -1 instead.

Approach:
step 1- split the string around white space using split method that will give us array of ['A','*','B','+','C','=','D']

step-2 find the Number with question mark and its index in the above array

step-3 Convert strings A,B,C,D into integers(except the number which has "?")

step-4 find the actual number which has to be there in place of string with ?

step-5 compare the actual string which we found above and the string with "?" and hence find the value "?"

--PR is generated with the solution of the assignment. #17

Github_Externship_Solution by Monu - PR #76

problem State
Screenshot 2021-12-11 180700

Concept Used:

  • Breaking down the given string containing "?" into digits and comparing it with the other evaluated string
  • Calculate the value of the variable by solving the equations.
  • Compare the output value of the variable with the one extracted from the equation.
  • Find the missing digit and return it as Integer.
  • Cases when we return -1
    • missing number comes out to be negative or a decimal number.
    • missing number comes out to be a leading zero digit.

Screenshot 2021-12-11 175806

Check the Code Here

Github-Externship-Assignment solution by Monu #76

Review and Merge the pull request #82

I have solved the assignment and will be linking this issue with my PR for the GitHub Externship 2021: Winter Cohort.

Candidate's Name: Sahil Gupta
GitHub I'd: @sahilg50
Task performed: Solved the assignment.
Project: Open Source Contribution
PR: #82

Github Externship solution by Apoorv Dwivedi

Methods implemented in FixEquation class

  1. extractValues : It extracts the values A, B, C and D from the given equation and returns a combined object.

  2. findMissingDigit: It does some null checks and then calculates the missing digit in the equation on the basis of values returned by extractValues and returns the answer.

Approach

  • The values are extracted from the given equation by extractValues method
  • These values are checked one by one for finding the value which contains a ?
  • On the basis of variable with ?, other variables are processed to find the answer for the corresponding variable
  • The length of answer and variable with ? are compared, if it is same then digit corresponding to ? is returned

Solution.js Code

class FixEquation {
  extractValues(equation) {
    // This method extracts the respective values of A, B, C and D and return a combined object.

    let locationOfStar = equation.indexOf('*');
    let locationOfPlus = equation.indexOf('+');
    let locationOfEqualsTo = equation.indexOf('=');

    if (
      locationOfStar !== -1 &&
      locationOfPlus !== -1 &&
      locationOfEqualsTo !== -1
    ) {
      return {
        A: equation.substring(0, locationOfStar).trim(),
        B: equation.substring(locationOfStar + 1, locationOfPlus).trim(),
        C: equation.substring(locationOfPlus + 1, locationOfEqualsTo).trim(),
        D: equation.substring(locationOfEqualsTo + 1).trim(),
      };
    } else {
      return null;
    }
  }

  findMissingDigit(equation) {
    if (!equation) return -1;

    const values = this.extractValues(equation);

    if (!values) return -1;

    const { A, B, C, D } = values;
    let resultString, searchingString;

    if (D.includes('?')) {
      const result = parseInt(A) * parseInt(B) + parseInt(C);
      resultString = result.toString();
      searchingString = D;
    } else if (A.includes('?')) {
      if ((parseInt(D) - parseInt(C)) % parseInt(B) === 0) {
        const result = (parseInt(D) - parseInt(C)) / parseInt(B);
        resultString = result.toString();
        searchingString = A;
      } else {
        return -1;
      }
    } else if (B.includes('?')) {
      if ((parseInt(D) - parseInt(C)) % parseInt(A) === 0) {
        const result = (parseInt(D) - parseInt(C)) / parseInt(A);
        resultString = result.toString();
        searchingString = B;
      } else {
        return -1;
      }
    } else if (C.includes('?')) {
      if (parseInt(D) % (parseInt(A) * parseInt(B)) === 0) {
        const result = parseInt(D) / (parseInt(A) * parseInt(B));
        resultString = result.toString();
        searchingString = C;
      } else {
        return -1;
      }
    }

    if (resultString.length === searchingString.length) {
      const missingNumber = searchingString.indexOf('?');
      return resultString[missingNumber];
    } else {
      return -1;
    }
  }
}

const runTestCases = () => {
  solution = new FixEquation();
  const tests = [
    '42 * 47 + 2 = 1?76',
    '4? * 47 + 2 = 1976',
    '42 * ?7 + 2 = 1976',
    '42 * ?47 + 2 = 1976',
    '2 * 12? + 2 = 247',
  ];

  tests.forEach((test, index) => {
    const answer = solution.findMissingDigit(test);
    console.log(`Test Case ${index} :
      Test Equation : ${test}
      ${
        answer === -1
          ? `No solution for the given equation exists, returned -1`
          : `Missing digit is : ${answer}`
      }\n`);
  });
};

// runTestCases();
// To check and run test cases uncomment the above line

TestCases

The TestCases function can be used to run and check the above implemented class for the testcases provided in the documentation.

image

Link to Solution : #43

Mugdha's Solution to GitHub Externship Assignment

Hi!

This is Mugdha Kurkure
This pull request contains my solution for the problem statement given.

How I approached the problem

  • Separate the equation into tokens and extract A B C and D
  • Parse the numbers without the unknown digit into integer
  • Rearrange the equations to find the complete value of the unknown number, let us consider it as projected
  • If projected is not an integer, return -1 (no valid solution)
  • If projected is a complete substring of the unknown number, return -1 (? is a leading zero)
  • Compare corresponding characters of projected and the unknown number, and return the number in projected which is at the same index as ? in the unknown number.

You can find the implementation of this approach in my pull request #100

Github Externship Assignment Solution - Krutika Bhatt

Hello!

This Issue is regarding my solution for the given problem statement

Name : Krutika Bhatt
Github ID : @KrutikaBhatt
Project : Open Source Contribution
Pull Request : #112

Proposed Solution:

  1. Read the equation from the user
  2. Split and extract A,B,C,D from the given equation
  3. Parse the numbers without the missing digit to Integer
  4. Find the complete value of the missing digit by rearranging and evaluating the equation.Let us consider this value to be 'rearranged'
  5. If rearranged is negative or floating number, return -1 (no valid solution)
  6. Return -1 if ? is a leading zero. This case is checked by removing ?. If there is no effect, that means ? is a leading zero
  7. Compare characters of variable rearranged and the missing number, and return the number in rearranged which have the same index as ? in the unknown number; else return -1

Please find the elaborated solution and driver code mentioned in the Pull Request here - #112

Github-Externship-Assignment Submission by Nikzero6: PR#74

Pull request reference: #74

Algorithm:

  1. Create class FixEquation with a constructor function that initializes private variable terms_array with an empty array.
  2. Create method find_missing_digit(), which takes equation as a string parameter and returns integer missing digit.
  3. Logic:
    • Extract and store numeric terms from equation string by splitting it using regex expression: /[*+=]/ into terms_array.
    • Find term with ? mark among 4 elements in terms_array.
    • Also find the position of ? mark in that unknown_term.
    • Convert all string elements in terms_array to int for calculation purposes except the unknown term with ? mark.
    • Calculate the value of unknown_term solving the linear equation depending upon cases like case 1: when A is unknown.
    • Convert unknown_term_value to string.
    • Check if unknown_term_value is defined and its length is equal to the length of the unknow_term string with ? mark.
    • If true, then return digit at the index of unknown_term_value where ? mark is there in unknown_term string.
    • Else return -1.

Output:

Screenshot-from-2021-12-11-16-08-52

Check in this jsfiddle

Assignment solution By Lavakush

Approach

  1. Extract the variables and the operators from the equation.
  2. check the variable having ? sign.
  3. calculate its actual value after arranging the equation.
  4. compare the original value of the variable with the one extracted from the equation.
  5. Find the digit and return it as integer.

Methods

  1. findMissingDigit
  • parameter-string(equation)
  • return value- integer
  • Extracts the variables from equation and then finds the solution
  1. Search
  • parameter- string value
  • return value-string
  • Finds the variable having the ? sign else return None
  1. Check
  • parameter-string values
  • return value-Integer
  • Compare the actual value of the variable

Solution.js

class FixEquation {
findMissingDigit(equation) {
// get A, B, C, D from equation
let A = equation.substring(0, equation.indexOf(''));
let B = equation.substring(equation.indexOf('
') + 1, equation.indexOf('+'));
let C = equation.substring(equation.indexOf('+') + 1, equation.indexOf('='));
let D = equation.substring(equation.indexOf('=') + 1);

    // which of A, B, C, D has ?
    let missingDigit = -1;
    if (A.indexOf('?') !== -1) {
        missingDigit = this.getMissingDigit(A, B, C, D, 'A');
    } else if (B.indexOf('?') !== -1) {
        missingDigit = this.getMissingDigit(A, B, C, D, 'B');
    } else if (C.indexOf('?') !== -1) {
        missingDigit = this.getMissingDigit(A, B, C, D, 'C');
    } else if (D.indexOf('?') !== -1) {
        missingDigit = this.getMissingDigit(A, B, C, D, 'D');
    }
    return missingDigit;
}

getMissingDigit(a, b, c, d, missingDigitIn) {
    let missingNumber = -1;
    let missingDigit = -1;
    let temp = -1;

    switch (missingDigitIn) {
        case 'A':
            // convert b, c, d to integer
            b = parseInt(b);
            c = parseInt(c);
            d = parseInt(d);

            // get missing number i.e a from a*b + c = d
            temp = d - c;
            // taking modulo of temp with b since missing number should be integer
            temp % b === 0 ? missingNumber = temp/b : missingNumber = -1;
            missingDigit = this.getMissingDigitUtil(a, missingNumber.toString());
            break;

        case 'B':
            a = parseInt(a);
            c = parseInt(c);
            d = parseInt(d);

            temp = d - c;
            temp % a === 0 ? missingNumber = temp/a : missingNumber = -1;
            missingDigit = this.getMissingDigitUtil(b, missingNumber.toString());
            break;
        
        case 'C':
            a = parseInt(a);
            b = parseInt(b);
            d = parseInt(d);

            missingNumber = d - (a*b);
            missingDigit = this.getMissingDigitUtil(c, missingNumber.toString());
            break;
        case 'D':
            a = parseInt(a);
            b = parseInt(b);
            c = parseInt(c);

            missingNumber = (a*b) + c;
            missingDigit = this.getMissingDigitUtil(d, missingNumber.toString());
            break;
    }
    return missingDigit;
}
getMissingDigitUtil(number, missingNumber) {
    // remove trailing and leading spaces from number
    number = number.trim();
    
    // if length is not equal then return -1
    // This also handles the case where missing digit is the first digit and is 0
    // but according to the constraints, there cannot be 0 at the start of the number
    if(number.length !== missingNumber.length) {
        return -1;
    }
    let missingDigit = -1;
    // find index of missing digit ?
    let index = number.indexOf('?');
    missingDigit = missingNumber.charAt(index);

    return parseInt(missingDigit);
}

}
let FixEquationObj = new FixEquation();
let testcases = ["42 * 47 + 2 = 1?76","4? * 47 + 2 = 1976","42 * ?7 + 2 = 1976","42 * ?47 + 2 = 1976", "2 * 12? + 2 = 247"];

for(let i = 0; i < testcases.length; i++) {
console.log(testcases[i]);
console.log(FixEquationObj.findMissingDigit(testcases[i]));
console.log();
}

Screenshot (2)

Github-externship-solution-rohit-raje-786

Approach :
.Taking the testcase and string as input from the user.
.Then spliting the string using regex.
.The splitted element will be stored in array.
.Traversing the array and if '?' exit we stop over there and start manipulating the equation and taking the one which contain '?' as x.
.Solving the equation will give the required result.
.After that checking the result length is equal to the element containing '?'.
.If yes then we compare the result with the one containing '?' and after not finding the match we print the char at the pos where '?' exits.
.If no then the solution doesn't exit then we print just -1.
TestCases :
Screenshot 2021-12-12 at 9 38 50 AM
pr:#88

Github-Externship-Assignment Solution

Step 1: Spilt the equation into four variables A,B,C,D omitting the tokens.
Step 2: Check which variable contains the "?" token.
Step 3: Then solve the equation to find the actual value of the variable.
Step 4: Compare the lengths of the actual value and variable, if they don't match return -1
Step 4: Loop through each digit of the variable and check if its "?" token, if yes. return the corresponding digit from the actual value.

// function to replace the character at a positions in string
 function replaceAt(str,index, character) {
     return str.substr(0, index) + character + str.substr(index+character.length);
 };

 class FixEquation{

     //to find the missing value in the equation

     findMissingDigit(equation){
         // To seperate the equations in different part
         let params=equation.split(" ");
         let [a,b,c,d] = [params[0],params[2],params[4],params[6]];
         // count variable to get the variable which has missing value
         let count=0;
         for(let i=0;i<params.length;i+=2){
             if(params[i].includes("?")) 
               break;
             count++;
         }

         // if count is 0 then missing character is in A
         // if count is 1 then missing character is in B
         // and so on

         switch(count){
             case 0:{
                 // converting all the string in number for easy calculations
                 b=parseInt(b);
                 c=parseInt(c);
                 d=parseInt(d);
                 // if b==0 then return -1
                 if(b===0) return "-1";
                 let temp=(d-c)/b;
                 // find the index of ? in a variable
                 let index=a.indexOf("?");
                 temp=temp.toString();
                 //replace ? in a with index of temp
                 a=replaceAt(a,index,temp[index])
                 return temp===a ? temp[index] : "-1"
             }
             break;
             case 1:{
                 a=parseInt(a);
                 c=parseInt(c);
                 d=parseInt(d);
                 if(a===0) return "-1";
                 let temp=(d-c)/a;
                 let index=b.indexOf("?");
                 temp=temp.toString();
                 b=replaceAt(b,index,temp[index])
                 return temp===b ? temp[index] : "-1"
             }
             break;
             case 2:{
                 a=parseInt(a);
                 b=parseInt(b);
                 d=parseInt(d);
                 let temp=d-a*b;
                 let index=c.indexOf("?");
                 temp=temp.toString();
                 c=replaceAt(c,index,temp[index])
                 // console.log(temp,c);
                 return temp===c ? temp[index] : "-1"
             }
             break;
             case 3:{
                 a=parseInt(a);
                 b=parseInt(b);
                 c=parseInt(c);
                 let temp=a*b+c;
                 let index=d.indexOf("?");
                 temp=temp.toString();
                 d=replaceAt(d,index,temp[index])
                 // console.log(temp,d);
                 return temp===d ? temp[index] : "-1"
             }
             break;
             default:
                 return "-1";
         }
     }
 }


 const FixEquationObj= new FixEquation();

 console.log(FixEquationObj.findMissingDigit("42 * ?47 + 2 = 1976"))

Github-externship-assignment solution-Rishab Bibhuty

Code

class FixEquation{
FixMissingDigit=(string)=>{
string=string.split(" ")
var A,B,C,D;
var last

for(let i=0;i<string.length;i++){
if(string[i]=="*"){
A=string.slice(0,i).join("");
last=i+1;
}
else if(string[i]=="+"){
B=string.slice(last,i).join("")
C=string.slice(i+1,i+2).join("")
}
else if(string[i]=="="){
D=string.slice(i+1,string.length).join("")

   }

}

if(A && A.includes("?")){
var sum=(D-C)/B
sum=sum+""
return sum.length === A.length ? sum[A.indexOf("?")] : -1
}

if(B && B.includes("?")){
var sum=(D-C)/A
sum=sum+""
return sum.length===B.length ? sum[B.indexOf("?")] : -1
}

if(C && C.includes("?")){
var sum=(D-"0")-A*B
sum=sum+""
return sum.length === C.length ? sum[C.indexOf("?")] : -1
}

if(D && D.includes("?")){
var sum=A*B+(C-'0')
sum=sum+""
return sum.length===D.length ? sum[D.indexOf("?")] : -1

 }
 return -1
}

}

const fix=new FixEquation()
console.log("Testcase-1")
console.log(fix.FixMissingDigit("42 * 47 + 2 = 1?76"))
console.log("Testcase-2")
console.log(fix.FixMissingDigit("4? * 47 + 2 = 1976"))
console.log("Testcase-3")
console.log(fix.FixMissingDigit("42 * ?7 + 2 = 1976"))
console.log("Testcase-4")
console.log(fix.FixMissingDigit("42 * ?47 + 2 = 1976"))
console.log("Testcase-5")
console.log(fix.FixMissingDigit("2 * 12? + 2 = 247"))

Output

Screenshot_20211210_151956

Github-Externship-Assignment-solution - Dishant Kumawat

My Approach :)

  • Split the given equation into tokens (using slicing/slice)
  • Find the token which contains the '?' character (using indexOf method)
  • Find the answer wrt to the missing token and check the validity of the equation to avoid any floating point mistakes. For ex. if the equation is 2 * 12? + 2 = 247 then the token 12? will be replaced by a float number while calculating the answer ie ((247-2)/2) so a validation of the equation will make sure to avaoid such problems.
  • Now we will compare our ans and the token which contains '?' and extract the number which will replace '?'.
  • We will also check the length of both answer and '?' containing token for avoiding leading zero problem.

My code : )

const readline = require('readline');
const r1 = readline.Interface({
    input : process.stdin,
    output: process.stdout
})
class FixEquation{
    constructor(){}
    
    static findMissingDigit(Equation){

        // ***removing the spaces if its there between the variables***
        
        Equation = Equation.split(' ').join('');
        
        //extracting each variable in a,b,c,d
        
        let a = Equation.slice(0,Equation.indexOf('*'));
        let b = Equation.slice(Equation.indexOf('*') + 1, Equation.indexOf('+'));
        let c = Equation.slice(Equation.indexOf('+') + 1, Equation.indexOf('='));
        let d = Equation.slice(Equation.indexOf('=') + 1);
        
        // Original variable for the variable which contain the '?' character.
        
        let original;
        
        // answer variable for the replacement of the variable which contains '?' character.
        
        let answer;

        // first find out which variable contains '?'
        // the perform arithmatics accodingly 
        
        if(d.indexOf('?') != -1){
            original = d;
            let aint = parseInt(a);
            let bint = parseInt(b);
            let cint = parseInt(c);

            let tans = aint * bint + cint;
            answer = tans;
            if(!FixEquation.checkEquation(aint,bint,cint,answer)) answer = -1;
        }
        else if(a.indexOf('?') != -1){
            original = a;
            let dint = parseInt(d);
            let bint = parseInt(b);
            let cint = parseInt(c);
            let tans;
            if(bint != 0)
                tans = (dint - cint)/bint;
            else
                tans = -1;
            answer = tans;
            if(tans != -1 && !FixEquation.checkEquation(answer,bint,cint,dint)) answer = -1;
        }
        else if(b.indexOf('?') != -1){
            original = b;
            let dint = parseInt(d);
            let aint = parseInt(a);
            let cint = parseInt(c);
            let tans;
            if(aint != 0)
                tans = (dint - cint)/aint;
            else
                tans = -1;
            answer = tans;
            if(tans != -1 && !FixEquation.checkEquation(aint,answer,cint,dint)) answer = -1;
        }
        else if(c.indexOf('?') != -1){
            original = c;
            let dint = parseInt(d);
            let bint = parseInt(b);
            let aint = parseInt(a);
            let tans;
            tans = (dint - (aint * bint));
            answer = tans;
            if(!FixEquation.checkEquation(aint,bint,answer,dint)) answer = -1;
        }
        return FixEquation.compareAns(original,answer);
    }
    
    //extracting the value which will replace '?'.
    
    static compareAns(original,answer){
        if(answer === -1) return -1;
        answer = answer.toString();
        if(original.length != answer.length)
        return -1; 
        else return answer.charAt(original.indexOf('?'));
    }
    
    // for checking the found solution is wheather correct of not for removing the floating point error.
    
    static checkEquation(a,b,c,d){
        let lhs = a*b + c;
        return lhs === d;
    }
}


// taking input from the console.

let stdin_input = "";
r1.question("Equation: ",(data)=>{
    stdin_input = data;
    r1.close();
})
r1.on("close",()=>{
    console.log(FixEquation.findMissingDigit(stdin_input));
})

Screenshots for the testcases

symbl-1
symbl-2
symble-3
symbl-4
symbl-5
png)

Links and Contact

feat: symblai assignment solution for github externship

Describe the bug
Given a String equation containing an equation of the form A * B + C = D, where A, B, C, and D are positive integers that don't have leading zeros. One digit in the equation is missing.

Example: 42 * 47 + 2 = 1?76 in this equation one digit is missing that is 9.

Expected behavior
Determine and return the correct digit.

Additional context
If the missing digit cannot be determined (i.e., there is no solution or there is more than one solution), return -1 instead.

Github-Externship-Assignment solution

PROBLEM STATEMENT:

link to problem statement

OBJECTIVE:

implement class "FixEquation" in Solution.js

ALGORITHM :

  • According to the constraints of the input equation, only one of the operands (A, B, C, D) contains the '?' character.
  • Therefore if any solution exists for the input equation, the '?', must be replaced by digits form '0' to '9'.
    • In other words, 10 possible strings can be obtained form a string containing one '?', by replacing '?' with digits '0', '1', '2' … up to '9' in each turn.
    • if none of the above strings does satisfy the equation, then NO SOLUTION EXISTS for the input equation.

IMPLEMENTATION:

  • class FixEquation contains 3 member functions:
    • getAllProbables()
    • checkEquation()
    • findMissingDigit()

DESCRIPTION OF MEMBER FUNCTIONS:

  • findMissingDigit() : receives a equation string as an input. The Equation must have the format: A * B + C = D
  • getAllProbables() : receives a input string. Depending on the
    string characeristics returns an array of strings.
    • if the string contains no '?', then returns an array having
      only one string equals to the input string.
    • if the string contains one '?', then in each turn replaces '? with the digits from '0' to '9', and the generated string gets appended to the returning array.
  • checkEquation() : receives 4 decimal integers in string format as the input. Then converts them to their integer form and checks if the corresponding integers satisfy the equation: A * B + C = D

IMPLEMENTATION STEPS:

  • step 1:

    findMissingDigit() receives the input equation as a string. Then to separate the 4 operands(A, B, C, D) and 3 operators(+, *, =), which are separated from each other by a whitespace, string.split(" ") method is used. After splitting, the entities gets stored in an array of strings operatorOperandArray.

  • step 2:

    For each of the operands (A, B, C, D), irrespective of one contains '?' character in it or not, provided as an input to getAllProbables(), to get all the possible strings that one can generate.

    NOTICE: read the description of the getAllProbables() to get fair idea about the function.
  • step 3:

    for each of the characters from '0' to '9', check if the probables obtained by getAllProbables(), satisfy the equation A * B + C = D.

    • if all of digits failed to replace the '?' then no solution exists and the function findMissingDigit() returns -1;
    • else it is again checked that, if the obtained solution has leading zeros, then return -1. Otherwise return the the digit satisfying the equation.

IMPLEMENTATION DEMONSTRATION:

  • create an additional folder named driver.jsin the same directory as Solution.js
  • driver.js receives the equation from console window and displays the returned value form the _findMissingDigit_funtions contained in the FixEquation class.
  • the content of the driver.js file should be
const { FixEquation } = require('./Solution.js');

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

readline.question("Enter the equation: ", (equation) => {
    let eq = new FixEquation();
    let returnResult = eq.findMissingDigit(equation);
    console.log("result: ", returnResult);
    readline.close();
});
  • open the terminal and navigate to the directory in which Solution.js and driver.js exists.
NOTICE: make sure node is installed in your system. or visit official node.js website to download and install
  • Enter the command and press enter.
node driver.js
  • The prompt will ask you to enter the equation. After writing the equation in A * B + C = D format, press enter and the result will be displayed in the console window.

screenshot of the outputs for sample inputs:

image

Github-Externship-Assignment solution by Rupam Shil

Code:

class FixEquation {
    /**
     * @property {Function} findMissingDigit - Returns the missing digit from the given equation of the form A * B + C = D
     * @param {String} equation - String equation containing an equation of the form A * B + C = D
     * @returns {Number} - returns the missing digit if it is a valid equation else returns -1
     */
    findMissingDigit(equation){
        // split the equation based on the integer strings 
        const eachVal = equation.trim().split(/\+|\*|\=/g).map((each)=>each.trim());
        // Destructing for forming the equation later
        let [A, B, C, D] = eachVal
        // variables to store the missing digit index in the eachVal array, the missing digit integer, missing index position in the integer string
        let toFind, val,missingIndex;
        // to check if  A, B, C, D will be a nonempty string of 1 to 4 characters, and get the missing index position
       for(let i = 0; i<4;i++){
         if(eachVal[i].length > 4 || eachVal[i].length ===0){
             return -1
         }
         if(eachVal[i].includes('?')){
             toFind = i
             missingIndex = eachVal[i].indexOf('?')
         }
       }
       // based on the missing index we form the equation
       switch (toFind){
        case 0:
            val = (parseInt(D) - parseInt(C)) / (parseInt(B))
            break;
        case 1:
            val = (parseInt(D) - parseInt(C)) / (parseInt(A))
            break;

        case 2:
            val = parseInt(D) / (parseInt(C)*parseInt(A))
            break;

        case 3:
            val = (parseInt(A) * parseInt(B)) + (parseInt(C))   
            break;

        }       
    // if the value we are getting has less characters than the missing digit integer itself then return -1 
    if(eachVal[toFind].length !== val.toString().length) return -1
    //if the value if float return -1 else split the missing integer and return the missing digit index's value
    return (!Number.isInteger(val)) ? -1 : val.toString().split('')[missingIndex];
    }
}

const eq = new FixEquation()
// Test cases:
console.log(eq.findMissingDigit('42 * 47 + 2 = 1?76'));  //9
console.log(eq.findMissingDigit('4? * 47 + 2 = 1976'));  //2
console.log(eq.findMissingDigit('42 * ?7 + 2 = 1976'));  //4
console.log(eq.findMissingDigit('42 * ?47 + 2 = 1976')); //-1
console.log(eq.findMissingDigit('2 * 12? + 2 = 247'));   //-1

Result:

Screenshot 2021-12-09 091413

Result:

Github-Externship-Assignment Solution

class FixEquation {
    constructor(equation) {
      this.equation = equation
    }

    validMissing(result, missingResult, nullIndex){
        /*
        eg: for 42 * 47 + 2 = 1?76
        result = 1976: String
        missingResult = 1?76: String
        nullIndex = 1: Integer

        returns the missing digit as a string if a valid solution exists else returns -1
        */
        let check = true
        if (result.length != missingResult.length || result % 1 !== 0 || result <= 0) {
            // set check to false if leading zeroes are present or the result is not a positive integer
            check = false
        } else {
            for(let i = 0;i<result.length; i++){
                if (result[i] != missingResult[i] && i!=nullIndex){
                    // ensure that the result and the missingResult only differ for the nullIndex
                    check = false
                }
            }
        }
        if (check) {
            return result[nullIndex]
        } else {
            return -1
        }
    }

    findMissingDigit (equation) {
        // splitting the string to extract the 4 variables
        equation = equation.split(/[+,*,=,]/)
        let A = equation[0].trim()
        let B = equation[1].trim()
        let C = equation[2].trim()
        let D = equation[3].trim()
        
        let nullIndex = null
        let check = null

        if (A.includes("?")){
            nullIndex = A.indexOf("?") // find index of ? in the missing variable string
            // cast to integers to find the real solution
            const result = (parseInt(D) - parseInt(C)) / parseInt(B)
            check = this.validMissing(result.toString(), A, nullIndex)
        } else if (B.includes("?")) {
            nullIndex = B.indexOf("?")
            const result = (parseInt(D) - parseInt(C)) / parseInt(A)
            check = this.validMissing(result.toString(), B, nullIndex)
        } else if (C.includes("?")) {
            nullIndex = C.indexOf("?")
            const result = parseInt(D) - (parseInt(A) * parseInt(B))
            check = this.validMissing(result.toString(), C, nullIndex)
        } else {
            nullIndex = D.indexOf("?")
            const result = (parseInt(A) * parseInt(B)) + parseInt(C)
            check = this.validMissing(result.toString(), D, nullIndex)
        }
        if (check == -1){
            // invalid equation
            return -1
        } else {
            return check
        }
    }
}

// provided test cases
const testCases = [
    "42 * 47 + 2 = 1?76", 
    "4? * 47 + 2 = 1976", 
    "42 * ?7 + 2 = 1976", 
    "42 * ?47 + 2 = 1976", 
    "2 * 12? + 2 = 247"
]

testCases.map(tc => {
    const eq = new FixEquation(tc)
    console.log(eq.findMissingDigit(eq.equation))
})

image

Github Externship Assignment Solution

Problem Statement:
Given a String equation containing an equation of the form A * B + C = D, where A, B, C, and D are positive integers that don't have leading zeros. One digit in the equation is missing.

Example: 42 * 47 + 2 = 1?76 in this equation one digit is missing that is 9.

Result Expected:
Determine and return the correct digit and if the missing digit cannot be determined (i.e., there is no solution or there is more than one solution), return -1 instead.

Followed all the norms and edge cases given.

Solution for GitHub Externship Assignment

Hi,
Thank you for allowing me to make a contribution to this repository. I really enjoyed resolving this major problem.

My Algorithm:

  1. Create a class named FixEquation
  2. Create method findMissingDigit() inside class FixEquation which gets string as an argument.
  3. Split the string using regular expression /[+,*,=,]/ and store it in an array.
  4. Declare two variables one for storing position in which ‘?’ is present and another for returning the result.
  5. Trim unwanted white spaces in all strings present in the array.
  6. Find the position of ‘?’. Leave the string that has ‘?’ and convert every string to an integer.
  7. Find the integer value of the string that has ‘?’ using other integers. We know that equation is of the form A * B + C = D.
  8. Store the value as a result that we created earlier.
  9. Convert the result to a string.
  10. If the length of the result is greater than the string return -1 else return the correct digit by comparing the place of the question mark with the result string.

Link to my solution: Link to my solution

#70

Github Externship Assignment

// Github Externship Assignment

// 1. Use split function to find values of a,b,c,d.
// 2. Check which variable conatins '?'.
// 3. Follw basic calculation steps to find value of variable of which conatins '?'.
// 4. Find index of '?' in the variable and return digit at the index in of the calculated value.
// 5. If length and value of variable doesn't match return -1.

// Write your code here

class FixEquation {
findMissingDigit(equation){

    let values=equation.split(" ");
    let [a,b,c,d] = [values[0],values[2],values[4],values[6]];
    
    
    // Checking wether a conatains '?'
    if(a.includes('?'))
    {
        let b1 = parseInt(b);
        let c1 = parseInt(c);
        let d1 = parseInt(d);
        let temp;
        temp = (d1 - c1)/b1;
        
        temp = temp.toString();
        if(a.length!=temp.length)
        {
            return -1;
        }
        else
        {
            let idx = a.indexOf('?');
            return temp[idx];    // returnning digit at '?' index
        }
        
    }
    else if(b.includes('?'))     // Checking wether b conatains '?'
    {
        let a1 = parseInt(a);
        let c1 = parseInt(c);
        let d1 = parseInt(d);
        let temp;
        temp = (d1 - c1)/a1;

        temp = temp.toString();
        if(b.length!=temp.length)
        {
            return -1;
        }
        else
        {
            let idx = b.indexOf('?');
            return temp[idx];           // returnning digit at '?' index
        }

        
    }
     else if(c.includes('?'))   // Checking wether c conatains '?'
    {
        let a1 = parseInt(a);
        let b1 = parseInt(b);
        let d1 = parseInt(d);
        let temp;
        
        temp = d1 - (a1 * b1);
        
         temp = temp.toString();
        if(c.length!=temp.length)
        {
            return -1;
        }
        else
        {
            let idx = c.indexOf('?');
            return temp[idx];      // returnning digit at '?' index
        }
        
    }
     else     // Checking wether d conatains '?'
    {
        let a1 = parseInt(a);
        let b1 = parseInt(b);
        let c1 = parseInt(c);
        let temp;
        temp = (a1 * b1) + c1;
        
         temp = temp.toString();
        if(d.length!=temp.length)
        {
            return -1;
        }
        else
        {
            let idx = d.indexOf('?');
            return temp[idx];      // returnning digit at '?' index
        }
    }
    
    
    
    
}

}

const FindDigit= new FixEquation();
console.log(FindDigit.findMissingDigit("42 * 4? + 2 = 1976"))

// Code written by Srajan Sharma

Github-Externship-Assignment Solution

Problem Statement

You are given a String equation containing an equation of the form A * B + C = D, where A, B, C and D are positive integers that don't have leading zeros.
One digit in the equation is missing.
Determine and return the correct digit.
If the missing digit cannot be determined (i.e., there is no solution or there is more than one solution), return -1 instead.

Test Cases

1️⃣

Equation: 42 * 47 + 2 = 1?76

Returns: 9

We know that 42 * 47 + 2 = 1974, so the missing digit is 9.

2️⃣

Equation: 4? * 47 + 2 = 1976

Returns: 2

The same equation, another missing digit.

3️⃣

Equation: 42 * ?7 + 2 = 1976

Returns: 4

And again the same equation.

4️⃣

Equation: 42 * ?47 + 2 = 1976

Returns: -1

This test case has no valid solution. The numbers cannot have leading zeros, so we cannot fill in a zero in front of 47.

5️⃣

Equation: 2 * 12? + 2 = 247

Returns: -1

Two times something + 2 will never be 247, so this test case has no solution either.

Approach

  • Solution.js: Implementations of
    • class: FixEquation
      • Method: getVariables(equation): Extracts variables A,B,C,D from equation. Creates a variables Array.
        • Parameters: String(equation)
        • Returns: string Array[A,B,C,D]
      • Method: findMissingNumberPosition(equation): Finds Number with missing digit in Array.
        • Parameters: String Array[A,B,C,D]
        • Returns: Integer(Position of missing digit number in [A,B,C,D])
      • Method: getMissingNumber(variables,index): Calculates possible value of the variable with a missing digit
        • Parameters: Array[A,B,C,D],Integer(index)
        • Returns: Integer(A/B/C/D)
      • Method: findMissingDigit(equation): Extracts variables A,B,C,D from equation.
        • Parameters: String(equation)
        • Returns: Missing Digit/-1

##Code

// Write your code here
class FixEquation {
  getVariables(equation) {
    const temp = equation.split(/[+,*,=,]/);
    return [temp[0].trim(), temp[1].trim(), temp[2].trim(), temp[3].trim()];
  }
  findMissingNumberPosition(variables) {
    return variables.findIndex((element) => {
      return element.includes("?");
    });
  }
  getMissingNumber(variables, index) {
    if (index === 3) {
      return (
        parseInt(variables[0]) * parseInt(variables[1]) + parseInt(variables[2])
      );
    } else if (index === 2) {
      return (
        parseInt(variables[3]) - parseInt(variables[0]) * parseInt(variables[1])
      );
    } else if (index == 1) {
      return (
        (parseInt(variables[3]) - parseInt(variables[2])) /
        parseInt(variables[0])
      );
    } else {
      return (
        (parseInt(variables[3]) - parseInt(variables[2])) /
        parseInt(variables[1])
      );
    }
  }
  findMissingDigit(equation) {
    const variables = this.getVariables(equation);
    const indexOfVariable = this.findMissingNumberPosition(variables);
    const variable = this.getMissingNumber(
      variables,
      indexOfVariable
    ).toString();
    const missingDigitVariable = variables[indexOfVariable];
    if (variable.length !== missingDigitVariable.length) {
      return -1;
    }
    const indexOfDigit = missingDigitVariable.indexOf("?");
    return parseInt(variable[indexOfDigit]);
  }
}

module.exports = {
  FixEquation,
};
  • test.js: imports solution.js and runs test coditions.

##Code

const { FixEquation } = require("./Solution");

const obj = new FixEquation();
let result;
result = obj.findMissingDigit("42 * 47 + 2 = 1?76");
console.log(
  `Test Case 0:\n\t Equation: 42 * 47 + 2 = 1?76\n\t Returns: ${result}`
);
result = obj.findMissingDigit("4? * 47 + 2 = 1976");
console.log(
  `Test Case 1:\n\t Equation: 4? * 47 + 2 = 1976\n\t Returns: ${result}`
);
result = obj.findMissingDigit("42 * ?7 + 2 = 1976");
console.log(
  `Test Case 2:\n\t Equation: 42 * ?7 + 2 = 1976\n\t Returns: ${result}`
);
result = obj.findMissingDigit("42 * ?47 + 2 = 1976");
console.log(
  `Test Case 3:\n\t Equation: 42 * ?47 + 2 = 1976\n\t Returns: ${result}`
);
result = obj.findMissingDigit("2 * 12? + 2 = 247");
console.log(
  `Test Case 4:\n\t Equation: 2 * 12? + 2 = 247\n\t Returns: ${result}`
);

###Output

Screenshot (172)

SymblAi open-source assignment solution by Doddi Puna Gana Ramakrishna

Approach :

Missing numbers can be found simply using the equation A * B + C = D . First, we will find two known numbers from the given equation(read as a string in the program) and convert them into integers, and put into the equation. In this way, we can find the third missing number. We can implement it by storing the equation into the string.

Algorithm :

  1. Extract A, B, C, and D variables from the equation.
  2. Find the location of the variable containing '?' and the location of '?' in that variable.
  3. Depending upon the location of the variable containing '?' solve the equation to find the value of variable having '?'.
  4. Compare the length of the calculated value with the length of the variable having '?'.
  5. If different then return -1.
  6. Now, replace the '?' with the correct digit.
  7. Compare both the numbers . If same then return the missing digit else return -1.

Answer :

Solution.txt

Output :

Capture

GitHub Externship Assignment Solution by Vamshi Addanki

Problem statement

You are given a String equation containing an equation of the form A * B + C = D, where A, B, C and D are positive integers that don't have leading zeros. One digit in the equation is missing. Determine and return the correct digit. If the missing digit cannot be determined (i.e., there is no solution or there is more than one solution), return -1 instead.

Definition

Class: FixEquation Method : findMissingDigit Parameters : String Returns : Integer Method signature : function findMissingDigit(equation) Note: A digit is correct if and only if it produces a valid equation in which A, B, C and D are positive integers with no leading zeros.

Constraints

Equation will have the form A * B + C = D. Each of A, B, C, D will be a nonempty string of 1 to 4 characters, i.e., 1 <= length of A, B, C, D <= 4. Each character in each of A, B, C, D will be either a digit ('0'-'9') or a question mark ('?'). There will be exactly one question mark in equation. The numbers represented by A, B, C, D will not have leading zeros.

Approach

  • Extracting variables from equation
  • Identifying variable which has missing digit
  • Finding value of missing variable using other variables
  • Finding missing digit by comparing given and calculated values
  • Solution

    Code

    Test

    test

    Github-Externship-Assignment Submission by Vishruth-S: PR#84

    Ref: PR #84

    Approach used

    1. Extract the numbers A,B,C,D from the equation
    2. Find which of the numbers has the missing digit, ie, '?'
    3. Calculate the value of the number with the missing digit using the rest of the numbers.
      Given equation is A * B + C = D
      If the missing digit is in C, then the value of C can be calculated as C = D - (A * B)
      Note: If the missing digit is in A or B, then the above step involves division.
      Since A and B are said to be integers, we return -1 if there is a remainder while dividing.
    4. Now we have the actual value of the number and the given number with the missing digit.
      We can compare and find the missing digit. Here, we have to take care of the following cases
      • Numbers are not of the same length => return -1
      • Numbers differ by another digit, apart from the missing digit => return -1
    5. If the above conditions are false, then we have found the missing digit, return it.

    Time complexity: O(n), where n is the length of equation

    Output

    Screenshot (1018)

    Github_externship_assignment_solutionByAastha

    Problem Statement:
    Given a String equation containing an equation of the form A * B + C = D, where A, B, C, and D are positive integers that don't have leading zeros. One digit in the equation is missing.

    Example: 42 * 47 + 2 = 1?76 in this equation one digit is missing that is 9.

    Expected behavior:
    Determine and return the correct digit and if the missing digit cannot be determined (i.e., there is no solution or there is more than one solution), return -1 instead.

    GitHub Externship Assignment Solution by Anshika Agrawal

    Approach

    • Extract the variables and the operators from the equation.
    • Check the variable having the '?' sign.
    • Calculate its actual value after arranging the equation accordingly.
    • Compare the actual value of the variable with the one extracted from the equation.
    • Find the digit and return it as Integer.

    Methods

    • findMissingDigit

      parameter - String ( equation )
      return value - Integer
      Extracts the variables from the equation and then finds the required solution digit for the given equation if possible else return -1.
    • search

      parameter - String values ( A, B, C, D)
      return value - String
      Finds the variable having the '?' sign else return 'None'.
    • calculate

      parameter - String values ( A, B, C, D, choice)
      return value - Integer
      Uses Switch case statement and finds the correct solution of the equation after rearranging it and returns the missing digit using the check function else return -1.
    • check

      parameter - String values ( toBeChecked, answer)
      return value - Integer
      Compares the actual value of the variable with the one extracted from the equation and returns the missing digit else return -1.

    Output

    Untitled

    Github Externship Assignment Solution

    PR Link: #42

    Approach

    Time Complexoty: O(n)
    Space Complexity: O(1)

    1. Get separate numbers A, B, C, D from equation

    2. Find which of A, B, C, D has ?

    3. Solve the rest of the equation keeping the variable that has ? on one side.
      For e g: if equation is 4? * 47 + 2 = 1976
      then A = 4?, B = 47, C = 2, D = 1976
      and A contains ?

      so we solve the rest of the equation except for A
      i.e. A = D - C / B.

    4. If A or B contains ? then the above equation solving will involve division.
      So we check whether the division is possible or not if there is a remainder then return -1.

    5. Once we have the missingNumber then we iterate over the original number that has ?
      and replace the ? with the digit at same position in missingNumber.

    6. Finally return missing digit

    Solution.js

    class FixEquation {
        findMissingDigit(equation) {
            // get A, B, C, D from equation
            let A = equation.substring(0, equation.indexOf('*'));
            let B = equation.substring(equation.indexOf('*') + 1, equation.indexOf('+'));
            let C = equation.substring(equation.indexOf('+') + 1, equation.indexOf('='));
            let D = equation.substring(equation.indexOf('=') + 1);
    
            // which of A, B, C, D has ?
            let missingDigit = -1;
            if (A.indexOf('?') !== -1) {
                missingDigit = this.getMissingDigit(A, B, C, D, 'A');
            } else if (B.indexOf('?') !== -1) {
                missingDigit = this.getMissingDigit(A, B, C, D, 'B');
            } else if (C.indexOf('?') !== -1) {
                missingDigit = this.getMissingDigit(A, B, C, D, 'C');
            } else if (D.indexOf('?') !== -1) {
                missingDigit = this.getMissingDigit(A, B, C, D, 'D');
            }
            return missingDigit;
        }
    
        getMissingDigit(a, b, c, d, missingDigitIn) {
            let missingNumber = -1;
            let missingDigit = -1;
            let temp = -1;
    
            switch (missingDigitIn) {
                case 'A':
                    // convert b, c, d to integer
                    b = parseInt(b);
                    c = parseInt(c);
                    d = parseInt(d);
    
                    // get missing number i.e a from a*b + c = d
                    temp = d - c;
                    // taking modulo of temp with b since missing number should be integer
                    temp % b === 0 ? missingNumber = temp/b : missingNumber = -1;
                    missingDigit = this.getMissingDigitUtil(a, missingNumber.toString());
                    break;
    
                case 'B':
                    a = parseInt(a);
                    c = parseInt(c);
                    d = parseInt(d);
    
                    temp = d - c;
                    temp % a === 0 ? missingNumber = temp/a : missingNumber = -1;
                    missingDigit = this.getMissingDigitUtil(b, missingNumber.toString());
                    break;
                
                case 'C':
                    a = parseInt(a);
                    b = parseInt(b);
                    d = parseInt(d);
    
                    missingNumber = d - (a*b);
                    missingDigit = this.getMissingDigitUtil(c, missingNumber.toString());
                    break;
                case 'D':
                    a = parseInt(a);
                    b = parseInt(b);
                    c = parseInt(c);
    
                    missingNumber = (a*b) + c;
                    missingDigit = this.getMissingDigitUtil(d, missingNumber.toString());
                    break;
            }
            return missingDigit;
        }
        getMissingDigitUtil(number, missingNumber) {
            // remove trailing and leading spaces from number
            number = number.trim();
            
            // if length is not equal then return -1
            // This also handles the case where missing digit is the first digit and is 0
            // but according to the constraints, there cannot be 0 at the start of the number
            if(number.length !== missingNumber.length) {
                return -1;
            }
            let missingDigit = -1;
            // find index of missing digit ?
            let index = number.indexOf('?');
            missingDigit = missingNumber.charAt(index);
    
            return parseInt(missingDigit);
        }
    }
    
    
    let FixEquationObj = new FixEquation();
    let testcases = ["42 * 47 + 2 = 1?76","4? * 47 + 2 = 1976","42 * ?7 + 2 = 1976","42 * ?47 + 2 = 1976", "2 * 12? + 2 = 247"];
    
    for(let i = 0; i < testcases.length; i++) {
        console.log(testcases[i]);
        console.log(FixEquationObj.findMissingDigit(testcases[i]));
        console.log();
    }

    Output

    image

    GitHub Externship Assignment Submission - harsh-solanki21 - PR#69

    Solution Approach

    • Take equation as an input
    • Convert the equation into array which contains values
    • Find the index of the missing digit(?)
    • Find the missing number
    • Find the missing digit in the missing number by its index
    • If missing digit and missing value doesn't contain the same digits then return -1
    • If they have the same no. of digits then return the missing digit

    Pull Request Ref. #69

    Github-Externship-Assignment Solution - Gaurav Chadha

    Key pointers for the solution explanation

    • Defined all the notations using JSDoc for clarity with the naming conventions.
    • Used Regex to split the equation and then mapped and trimmed the values.
    • passed the values with if and if-else conditions to determine the answers at each case formation of the equation
    • comparing and iterating through the values based on conditions
    • Tested them on certain test cases.

    Note: steps and JS methods are explained in the code in form of comments.
    PR attached #93

    GitHub Externship Assignment Solution - Ravisha Sharma

    Worked around the solution with straightforward intuitive steps. Handled the case where the number having a missing digit might have mismatched other digits. For example, the number should be 1976 but the equation has 1?36. This should return -1.

    Would submit my PR and am open to any feedback.

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.