Facebook Interview Question
SDE1sCountry: United States
function letterSolver(str) {
str = str.split(' ')
numbers = str[0].split('')
operation = str[1].split('')
for (var i=0; i<operation.length; i++) {
if (operation[i] !== "+" && operation[i] !== '-') {
code = operation[i].charCodeAt() - 97
operation[i] = numbers[code]
}
}
console.log(operation)
return eval(operation.join(''))
}
letterSolver("1234567 abc+efg")
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*
* make a number starting at str[0] while characters starting at
* spc are alhpabets, store the operator if oper is not zero,
* also store the number of digits converted ijn nlen.
*/
int get_num(const char *str, const char *spc, int *nlen, char *oper)
{
int num = 0, i = 0;
while (*spc && isalpha(*spc)) {
num = num * 10 + (str[i] - '0');
++i;
++spc;
}
if (oper && (*spc == '+' || *spc == '-')) {
*oper = *spc;
}
*nlen = i;
return num;
}
/*
* map the numeric part of the string to two numbers and do the specified
* arithmetic operation and return the result.
* NOTE: No validation is attempted: the numeric parts have to be of same
* length as the character string parts etc.
* The only validation is to check if the operator is + or -, if not returns
* -1.
*/
int do_map(const char *str, int len)
{
char oper = 0;
int nstart = 0, nlen = 0;
const char *spc = strchr(str, ' ');
while (*spc && !isalpha(*spc))
++spc;
if (!spc || !*spc)
return -1;
int num1 = get_num(str, spc, &nlen, &oper);
int add = 0, sub = 0;
if (oper == '+')
add = 1;
else if (oper == '-')
sub = 1;
else
return -1;
// str starts at str + nlen, and alpla starts at spc + nlen + 1
int num2 = get_num(str + nlen, spc + nlen + 1, &nlen, 0);
int res;
if (add)
res = num1 + num2;
else
res = num1 - num2;
return res;
}
int main(int ac, const char *av[])
{
if (!av[1]) {
printf("Enter an expression string like \"1234567 abc+/-defg\"\n");
return -1;
}
int res = do_map(av[1], strlen(av[1]));
printf("str = %s, result = %d\n", av[1], res);
return 0;
}
import java.util.*;
class StringToMath{
public static void main(String... args){
String s = "123456123 abc+efg+qer";
int indexOf = s.indexOf(" ");
StringBuilder b = new StringBuilder();
Stack<String> operandStack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
int literalIndex = indexOf+1;
for(int i=0;i<indexOf;i++){
boolean isOperator = isOperator(s,literalIndex);
if(isOperator){
operatorStack.push(s.charAt(literalIndex));
literalIndex++;
operandStack.push(b.toString());
b.delete(0,b.length());
}
b.append(s.charAt(i));
literalIndex++;
}
if(b.length()!=0){
operandStack.push(b.toString());
}
while(!operatorStack.isEmpty()){
int num2 = Integer.parseInt(operandStack.pop());
int num1 = Integer.parseInt(operandStack.pop());
char operator = operatorStack.pop();
operandStack.push(String.valueOf(getResult(num1,operator,num2)));
}
System.out.println(operandStack.pop());
}
public static boolean isOperator(String s, int ind){
return s.charAt(ind)=='-' || s.charAt(ind) == '+';
}
public static int getResult(int num1,char operator,int num2){
if(operator=='-'){
num2 = num2- num1;
}else{
num2 = num2 + num1;
}
return num2;
}
}
General solution for number of math operations:
package com.cracking.facebook;
public class CalculateMappedStringEquation {
public final static String Equation = "1234567 abc+efg";
public static void main(String[] args) {
String translatedEquation = TranslateEquation(Equation);
int result = CalculateEquation(translatedEquation);
System.out.println("Input = " + Equation);
System.out.println("Translated = " + translatedEquation);
System.out.println("Result = " + result);
}
public static String TranslateEquation(String equation) {
char[] values = equation.substring(0, equation.indexOf(" ")).toCharArray();
char[] result = equation.substring(equation.indexOf(" ") + 1).toCharArray();
for(int i=0, j=0; i<result.length; i++) {
if( Character.isLetter(result[i]) ) {
result[i] = values[j++];
}
}
return new String(result);
}
public static int CalculateEquation(String equation) {
int result = 0;
int opIndex = IndexOfOperation(equation);
int left = Integer.parseInt( equation.substring(0,opIndex) );
int right = Integer.parseInt( equation.substring(opIndex+1) );
char opChar = equation.charAt(opIndex);
switch(opChar) {
case '+':
result = left + right;
break;
case '-':
result = left - right;
break;
case '*':
result = left * right;
break;
case '/':
result = left / right;
break;
default:
break;
}
return result;
}
public static int IndexOfOperation(String equation) {
int i=0;
while( Character.isDigit(equation.charAt(i)) ) {
i++;
}
return i;
}
}
Output:
Input = 1234567 abc+efg
Translated = 123+456
Result = 579
#include <stdio.h>
int parseandadd(char* str)
{
int spc = 0;
while(str[spc++] != ' ') { }
int ch=spc, num1=0, num2=0, sum=0, numi=0, op=0;
while(!(str[ch] == '+' || str[ch] == '-'))
{
num1 = (num1*10)+(str[numi++] - '0');
++ch;
}
if(str[ch] == '-') op = 1;
else if(str[ch] == '+') op = 0;
else return -1;
ch++;
while(str[ch++] != '\0' && numi < spc)
{
num2 = (num2*10)+(str[numi++] - '0');
}
op?(sum = num1-num2):(sum = num1+num2);
printf("%d %d = %d\n", num1, num2, sum);
//scanf("%d", &spc);
return sum;
}
int main()
{
parseandadd("456123 abc+cde");
return 0;
}
public class MappingNumber {
private static String givenString = "123456 abc+efg";
//Only two operations + or -
private static void mappingResult(String givenString){
String[] givenSplitArr = givenString.split(" ");
String numberString = givenSplitArr[0];
String operatorString = givenSplitArr[1];
if(!operatorString.contains("+") && !operatorString.contains("-")){
System.out.println("No Operator exists");
return;
}
int i =0;
int j =0;
String operand1="", operand2 = "";
boolean isOPeratorFound = false;
while(i<numberString.length() && j<operatorString.length()){
if(operatorString.charAt(j)!='+' && operatorString.charAt(j)!='-'){
if(!isOPeratorFound)
operand1 = operand1+numberString.charAt(i);
else
operand2 = operand2+numberString.charAt(i);
i++;
}else{
isOPeratorFound = true;
}
j++;
}
System.out.println(Integer.parseInt(operand1)+Integer.parseInt(operand2));
}
public static void main(String[] args) {
mappingResult(givenString);
}
}
public class MappingNumber {
private static String givenString = "123456 abc+efg";
//Only two operations + or -
private static void mappingResult(String givenString){
String[] givenSplitArr = givenString.split(" ");
String numberString = givenSplitArr[0];
String operatorString = givenSplitArr[1];
if(!operatorString.contains("+") && !operatorString.contains("-")){
System.out.println("No Operator exists");
return;
}
int i =0;
int j =0;
String operand1="", operand2 = "";
boolean isOPeratorFound = false;
while(i<numberString.length() && j<operatorString.length()){
if(operatorString.charAt(j)!='+' && operatorString.charAt(j)!='-'){
if(!isOPeratorFound)
operand1 = operand1+numberString.charAt(i);
else
operand2 = operand2+numberString.charAt(i);
i++;
}else{
isOPeratorFound = true;
}
j++;
}
System.out.println(Integer.parseInt(operand1)+Integer.parseInt(operand2));
}
public static void main(String[] args) {
mappingResult(givenString);
}
}
func getSolution(s string) int64 {
spaceIndex := 0
operatorIndex := 0
for s[spaceIndex] != ' ' {
spaceIndex += 1
}
var operator = SUM
i := spaceIndex + 1
for s[i] != SUM && s[i] != SUB {
i += 1
}
operatorIndex = i
if s[i] == SUB {
operator = SUB
i += 1
}
op1, _ := strconv.ParseInt(s[:operatorIndex-spaceIndex-1], 10, 64)
op2, _ := strconv.ParseInt(s[operatorIndex-spaceIndex-1:spaceIndex], 10, 64)
if operator == SUM {
return op1 + op2
}
return op1 - op2
}
func getSolution(s string) int64 {
spaceIndex := 0
operatorIndex := 0
for s[spaceIndex] != ' ' {
spaceIndex += 1
}
var operator = SUM
i := spaceIndex + 1
for s[i] != SUM && s[i] != SUB {
i += 1
}
operatorIndex = i
if s[i] == SUB {
operator = SUB
i += 1
}
op1, _ := strconv.ParseInt(s[:operatorIndex-spaceIndex-1], 10, 64)
op2, _ := strconv.ParseInt(s[operatorIndex-spaceIndex-1:spaceIndex], 10, 64)
if operator == SUM {
return op1 + op2
}
return op1 - op2
}
@majia168 - are these actual FB interview questions? How many times are you interviewing at FB :) you have at least 5-6 a day.
- nomadicdude October 27, 2017Good questions though.