Solve this, Sup Forums

>At interview
>Get this problem to solve

"Transform the number written in words into an integer number, using only 3 if statements"
Ex: One thousand thirty three = 1033

The "and" keyword is omitted

>Solve it with some hints, whiteboard programming is more difficult than it seems

How fast can you solve this, Sup Forums?

Other urls found in this thread:

stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
twitter.com/SFWRedditGifs

I walk out of the interview because they gave me a whiteboard coding question.

How else would you ask the applicant to show their skill if you were an interviewer?

Trial period working in the office e.g. a week

This is the only correct answer.

That's a lot of logistic work. Their don't have time for that shit.

It's not like they'd set it up the day the interviewee comes in. For quality positions it's definitely worth the time.

KEK
Anons cannot solve it, so they write all the shit above.
That's why you are all going to remain the NEETS you are

Switch Case :^)

But they'd still have to decide which candidates to offer the trial period to. There'd still be need for testing practical coding in the interview itself.

And for some positions time is of the essence, they simply don't have time to mess around with trials, they need to hire someone to start on an actual project ASAP.

The applicant provides evidence of related experience.

>they need to hire someone to start on an actual project ASAP
That's what contractors are for.

>"Transform the number written in words into an integer number, using only 3 if statements"
Not possible without very clever tricks

No tricks, I assure you.
Hint: use a hash table

what if i write one million and forty two? It will need more than three if. Also can i for?

This question is stupid.
"Using only 3 if statements" is that a maximum of 3 if statements, or should my could just be 3 if statements?
If the latter, what restrictions are there on the blocks in the then/else branch?
If the former, can I use haskell?

I think you can do this with just one in Python.

If you can do it in less than 3 if statements, than you are better than the interviewer.

>Python
i thought it was a serious question, sorry

for (; ;) {

// code

break;
}

Int32.TryCast("1033");
just c# things

OP has been asked the opposite, you imbecile.

I turn 360° degrees and walk away because I am a Java enterprise fullstack developer with an expertise in JPA, (Oracle-, My, HSQLDB)-SQL, Spring, maven, jenkins, git, vue/angular/react SPAs and apparently mistakenly applied for a computer scientist job instead of a software engineer job.

Even for a CS job whiteboard programming is outright insulting.

digits = ['zero', 'one', 'two', ... ,'nine'];
teens = ['ten', 'eleven', 'twelve', ... 'nineteen']
tens = ['twenty', 'thirty', 'forty'... 'ninety'];
powers = ['thousand', 'million', 'billion', ... ];


function question(string) {
result = 0;
nextword = string.nextToken();
while (nextword) {


if (nextword in tens) {
result += (tens.indexOf(nextword)+2)*10;
(nextword = string.nextToken() && result += digits.indexOf(nextword));
return;
}

if (nextword in digits)
mult = digits.indexOf(nextword);

if ((nextword = string.nextToken()) {
result += mult * exp(10, 3 * (powers.indexOf(nextword)+1));
}

}

This would be the opposite

((Int)1033).ToString()
imbeshchill

Does that mean that you must solve it by using only 3 functions which all must be if()-s, or are you allowed to use any number of functions and methods where the maximum number of allowed if()-s are 3?

(Does asking such question at an interview make you immediately fail or generally considered as a bad point?)

if (a[0] == 'O' &&
a[1] == 'n' &&
a[2] == 'e' &&
a[3] == ' ' &&
...

So efficient I only need one if statement, I'll take my job now cuckboy

It would probably take me a while. There are a few edge cases to consider.

Java BigInteger :^)

Good luck with the number "one thousand two hundreds".

oh fuck I forgot about hundreds

values = {
'one' => 1,
'two' => 2,
'thirty' => 30,
...
}

mods = {
'hundred' => 100,
'thousand' => 1000,
...
}

arr = strsplit(' ', input)
reverse(arr)

sum = 0
mod = 1
for(word in arr){
if mods[word]
mod = mods[word]
else
sum += mod*values[word]
}

didn't give it much thought

Replace stuff:
nineteen -> one ten nine
twenty -> two ten

i like the elegance and simplicity of anaconda
good job user

Dictionary of every word to number (0-9)
Dictionary of how many zeroes one, one hundred, one thousand etc contains

read until you reach a hundred, thousand or a million etc
create an array or something like that with the amount of total digits you need based on what you read using the dictionary of zero counts
read the next word
insert it into the array
if the next word isn't a number, rather a thousand, hundred etc skip the zeroes
else insert the number
repeat

Give me a job

I would probably solve it with Regex, and recursion.

You can't parse numbers with regex. Because numbers can't be parsed by regex. Regex is not a tool that can be used to correctly parse numbers. As I have answered in numbers-and-regex questions here so many times before, the use of regex will not allow you to consume numbers. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by numbers. numbers is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down numbers into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing numbers. You will never make me crack. numbers is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse numbers using regular expressions. Every time you attempt to parse numbers with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing numbers with regex summons tainted souls into the realm of the living. numbers and regex go together like love, marriage, and ritual infanticide. The cannot hold it is too late. The force of regex and numbers together in the same conceptual space will destroy your mind like so much watery putty.

If you parse numbers with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. numbers-plus-regexp will liquify the nerves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based numbers parsers are the cancer that is killing Sup Forums it is too late it is too late we cannot be saved the trangession of a chi͡ld ensures regex will consume all living tissue (except for numbers which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse numbers has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process numbers establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of regex parsers for numbers will instantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection will devour your numbers parser, application and existence for all time like Visual Basic only worse he comes he comes do not fight he com̡e̶s, ̕h̵is un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment, numbers tags lea͠ki̧n͘g fr̶ǫm ̡yo͟ur eye͢s̸ ̛l̕ik͏e liquid pain, the song of re̸gular expression parsing will extinguish the voices of mortal man from the sphere I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful the final snuffing of the lies of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL IS LOST the pon̷y he comes he c̶̮omes he comes the ichor permeates all MY FACE MY FACE ᵒh god no NO NOO̼OO NΘ stop the an*̶͑̾̾̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e not rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ

Is this copypasta?

It's about parsing HTML with regex.

/thread

stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

I like this one

String number = "1031";
Int number_int = Integer.parseInt(number);
._.

Why is this such a bad thing? Seriously, is this considered an insulting task, and why? I'm not a programmer, so I don't really understand.

Is it because they're trying to put you though a kind of childish high-school/college tier exam/pop quiz type thing?

How do you write like this?
sauce?

H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ

Are you fucking retarded, faggot?
Read OP's post again

Impossible. Without bounds, it would require support for an infinite number of conversions in your lookup tables.

How is 2^31 - 1 for a bound

Solve for:
one thousand thirty fifty sixty one thousand

This

Nothing pisses me off than stupid interviewers who think you're a bad programmer because you can't remember some shitty algorithm that only a bookworm college graduate would remember

YOU'RE ASKING THE WRONG QUESTIONS, MEMORIZING ALGORITHMS DOES NOT MAKE YOU A GOOD PROGRAMMER, ASK ME ABOUT ARCHITECTURE OR WHAT TECHNOLOGY TO USE TO SOLVE A SPECIFIC PROBLEM, OR HOW TO APPROACH A CERTAIN PROBLEM

But no, let's ask about some shitty language related syntax or sorting algorithm. I'm not a fucking encyclopedia, we have google for that, we are paid to think, design and solve, not memorize

that's not a valid number though.

Tell us what exactly do you see in this problem that is about memorizing. This is a thinking problem, which you obviously fail at.
It also seems like most of Sup Forums pisses its pants at the sight of a cute little problem like this one.
Also, is incorrect

I would tell them right away that I would first Google it, because I could no way come up with the most efficient solution. If they forced me to do it, maps, but it would barely work and not for many cases. Dealing with two digit numbers s a pain in the ass.

For something crudely thrown together in 20 minutes, it works okay.

I did it, OP.

My code is not very beautiful, but it works..

simple_digit = {"one" => 1, "two" => 2, "three" => 3}
digit = {"eleven" => 11, "twelve" => 12, "twenty" => 20, "thirty" => 30}
multiply = {"million" => 1_000_000, "thousand" => 1_000, "hundred" => 100}

input = "one million two hundred thousand twenty three"
output = 0
flag_new_number = true
new_number = 0

input.split.each do |w|

if simple_digit.key? w
output += new_number
new_number = simple_digit[w]
else
new_number += digit[w] if digit.key? w
new_number *= multiply[w] if multiply.key? w
end
end
output += new_number

puts output
# 1200023

But it was more difficult than I thought..

Obviously I didn't type in every possible digit, but you get how it works..

whoops, I forgot to delete this line here:

>flag_new_number = true

Yeah, that's it.
I solved it a bit differently.
A single dictionary
take the number
compare it in three if statements:
is it less than 100
is it == 100
is it bigger than 100(as in 1000, 10000 etc)
I also had a temp variable which I added to the final sum only in the third if statement or at the end

Full disclosure:
This question was at Microsoft for an internship
They do tend to give easy problems which require good thinking on the spot. Oh, and they really care about the edge cases in their interviews. Even if you think you solved it, they almost always find a test case to fuck with your code. The people interviewing you are crazy smart, at least the Visual Studio team
Microsoft shilling: off

Yup, your approach looks nicer:

muh_dic = {"one" => 1, "two" => 2, "three" => 3,
"eleven" => 11, "twelve" => 12, "twenty" => 20, "thirty" => 30,
"million" => 1_000_000, "thousand" => 1_000, "hundred" => 100}

input = "one million two hundred thousand twenty three"
output = tmp = 0

input.split.each do |w|
if muh_dic[w] < 10
output += tmp
tmp = muh_dic[w]
elsif muh_dic[w] < 100
tmp += muh_dic[w]
else
tmp *= muh_dic[w]
end
end
output += tmp

puts output

Pretty tough..

I guess they don't expect you to solve it perfectly.

But it took me a few trials to get that you have use a temp variable. And even though I was doing this for fun and not with huge motivation, I'm relaxed and comfy right now.

To solve this when you are under pressure and surveillance.. pretty intense.

Here's a series of replacements. It is not code or pseudocode, but it should help you guys. It's verbose as fuck for didactic.

0. Example number - 26 304 516 260
>Twenty-six billions, three hundreds and four millions, five hundreds and sixteen thousands, two hundred and sixty

1. Remove the crap.
>twenty six billion three hundred four million five hundred sixteen thousand two hundred sixty

2. Replace nineteen=one ten nine, ninety=nine ten, etc.
>two ten six billion three hundred four million five hundred one ten six thousand two hundred six ten

3. Replace one=1, two=2, etc.
>2 ten 6 billion 3 hundred 4 million 5 hundred 1 ten 6 thousand 2 hundred 6 ten

4. Encircle.
>(2 ten 6 billion 3 hundred 4 million 5 hundred 1 ten 6 thousand 2 hundred 6 ten)

5. Replace thousand=)*1000+(, million=)*1000000+(, etc.
>(2 ten 6)*1000000000+(3 hundred 4)*1000000+(5 hundred 1 ten 6)*1000+(2 hundred 6 ten)

6. Replace ten=*10+ and hundred=*100+
>(2*10+6)*1000000000+(3*100+4)*1000000+(5*100+1*10+6)*1000+(2*100+6*10)

7. SOLVE THE FUCKING MATH.

Pretty good.

I'm shit as fuck at programming so it's always interesting to see how people solve problems I would probably spend hours, if not days, to solve if I can't find an example or something similar online.

2hard im no genius

Actually, the list of replacements after the step 1 can be simpler (slash means replacement)
,[space] / [space]
[space]and[space] / [space]
s[space] / [space]
s[word end] / [word end]
- / [space]
[word start] / [word start](
[word end] / )[word end]
eleven / 11
twelve / 12
teen / +10
ty / *10+
one / 1
two / 2
three / 3
thir / 3
[...]
nine / 9
hundred / *100+
thousand / )*1000+(
[...]
+) / )
+() / [nothing]

The last two rules are for cases like a number ending in a ty and a power of 1000 respectively.

This should generate a simple equation from any English number name, with no exceptions.

From the way OP formulated the problem I'd say we can expect well-defined input.

This "replacements" of yours doesn't really make the problem more difficult or a challenge, it's just more annoying becasue we have to sanitize the input first. It's literally just the reverse operation of what you did, just a littel bit of fucking arround with the input.

In this case I'd just throw a few replacements at it. And then check if there's any element that's not know - if so, it's not a well-defined input and we throw an exception at the impolite user.


>I'm shit as fuck at programming

We are all on our way to get better, user.

I'm genuinely curious too.

You need neural language networks for that.

did you do a 360 before walking away?

I can do it with only 1.
if words == "One thousand thirty three":
return 1033

>3 if statements
>implying all you fags using dicts and hashmaps even understand that your implementations does way more than 3 conditional branches

You failed the moment you declared your arrays.

Trips'o truth m80

I'm actually more concerned about doing it in a bash-friendly way to avoid proper programming. Yes, I'm that lazy.

Autists will not grasp that words are meaningless without context.

If somebody says "write a programm with three if -statements" he doesn't mean "write a programm that has a bytcode with three if statements". It's about using the if-statement (including stuff like elseif, switch case..) in your code only three times.

Those criteria are only there to point you in the right direction, because they DON'T want a solution that goes like "if text = 'one hundred twenty' then.."


Sigh, it all depends..

Whitboard coding is a pain in the arse because it's something you don't usually do. It's like saying you want to make a job interview for musicians but they have to play their instrument with the left hand.

However, if the interviewers are cool and are more interested in your general problem solving skills (instead of nitpicking about tiny syntax details) it's all fine.

I guess most people just don't like the pressure you feel when doing coing on a whiteboard. Not that I think whiteboard coding is such a godd idea, but it's also not that terrible if you are prepared.

OP hasn't specified a langage, so I'm assuming there's a solution for every langage.

>he doesn't mean "write a programm that has a bytcode with three if statements".

How would you do it in C, then?

If we're going down this path I'm pretty sure there's a language down here on the internet with a built-in statement to do just that :/

OK, my bad.

You want to solve it by gradually changing the input..

Don't know if this will work out, but interesting thought.

That's the idea. And I've done it as far as

./number

Whiteboard coding isn't terribly reflective of actual programming (this is also what screwed me up in pencil-and-paper programming exams), but having been in many engineering interviews whiteboards are better than the alternative.

>go to interview
>"tell me about yourself"
>"tell me about a time where you..."
>"why are you interested in our company?
>get rejected for "not being a fit" or some shit

Human resources was a mistake.

Isn't bash capable of basic math?

>Sigh,

Fucking pen and paper logic
I hate fucking having to write my logic painfully, line by line, only to be sworn at when "It doesn't work that way you can't even do basic programming user"

Tell that to the 22 Fuckers out of 36 who completely failed the exam

>using only 3 if statements
how about no

You are probably one of those autists that have no clue about the company where they are applying ("well, google made this search engine, right?") and don't even understand what people want to hear when they ask you something.

Let me guess: you also don't have a girlfriend because "wow, nice boobs" somehow never hits home, right?

The problem is that even experienced programmers make silly errors the first time through, and correct them after the compiler or interpreter yells at them.

I wasn't even taking a real programming class, I was just taking the mandatory Excel (seriously) and MATLAB freshman courses (the whole freshman general engineering program at my school is dumb, at best you learn basic SolidWorks).

for loop or while loop can be used for this too

I remember when I was around 16 we had "Excel classes".
We had to write excel functions on paper, the longest one I can remember was eight fucking functions long.

well you would have to store all the words at some point, so why not just have a 10 element array for each digit filled with strings, iterate through each digit starting at the least significant, append the element of each digit to a string and return the string

is everyone that uses c# that stupid or just you?
the OP asked to convert "One thousand thirty three" to int, not "1033"

>and don't even understand what people want to hear when they ask you something

That's the thing, of course I get that I'm supposed to give some flattering bullshit, I just don't know their preferred flavor.

There was one company where I actually did pretty well and came close, but from what I know they halted hiring to redirect resources to impressing GE (they were still on venture capital).

You see, an interview is pretty similar to flirting with someone at the disco:

They expect you to tell lies and try to find your weak spot. You have to be:
-cool (friendly, nice, confident, professional) as fuck
-you need to show social skills (you can talk smoothly, be funny, you know the company, you know your strengths and weaknesses)
-you have the "je ne sais quois" (maybe you aren't talkative but know your devops inside out? maybe you aren't the best coder ever but a real work horse? maybe you are lazy but brilliant in some field? maybe you are pretty average but have a lot of passion?)

I'm able to consistently get laughs from interviewers if nothing else. I recall one evaluation said I had strong self-confidence and appearance, so it's reasonable to say I'm not fucking up my suit. They did say I have weak communication, though, so yeah I probably am still a fucking autist.

I know almost for a fact that I'm much worse at personality-gauging questions than anything job-related. There's also the possibility everyone else has engineering-related connections (my family is liberal arts professors) or I'm basically competing with a bunch of guys who fix cars for fun (hell that's pretty much what cost me a job with a power tool company).

>yet another "do my homework" thread Sup Forums falls for
Sigh. Please just let people that can't do simple goddamn homework assignments fail their goddamn classes so they can just go ahead and fall back into some retarded easymode major like business or drop out and work at a McJob the rest of their lives.

Go back to your desktop/speccy thread and let the big guys code, will you?

Well aren't you the smart one.
kys spergm nobody likes you

Why don't you have lists with the strings "one" "two" "three" and so on and then index them

Yes, but I was struggling with the syntax. This now works:

#!/bin/bash
e=$(sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
s/, / /g
s/ and//g
s/s / /g
s/s$//g
s/-/ /g
s/^/(/g
s/$/)/g
s/teen/+10/g
s/ty/\*10+/g
s/one/1/g
s/two/2/g
s/twen/2/g
s/three/3/g
s/thir/3/g
s/four/4/g
s/five/5/g
s/six/6/g
s/seven/7/g
s/eight/8/g
s/nine/9/g
s/ten/10/g
s/eleven/11/g
s/twelve/12/g
s/hundred/\*100+/g
s/thousand/)\*1000+(/g
s/million/)\*1000000+(/g
s/billion/)\*1000000000+(/g
s/trillion/)\*1000000000000+(/g
s/+)/)/g
s/+()//g
s/ //g' $1)

let n=$e
echo $n

Running it:
/path/where/you/saved/it

If you have the patience to do this until 999 trillion then be my guest.
Smart people only have to know about 30 words.

Haskell doesn't have any statements at all, much less if statements. Is that still okay?

import Data.Char(isAlpha)

unitsW = words "one two three four five six seven eight nine"
teensW = words "eleven twelve thirteen forteen fifteen " ++
words "sixteen seventeen eighteen nineteen"
tensW = words "ten twenty thirty forty fifty sixty seventy eighty ninety"
millsW = words "units thousand million billion trillion"

valsA = ("oh", 0) : concat [zip unitsW [1..], zip teensW [11..], zip tensW [10,20..]]
millsA = zip millsW (iterate (* 1000) 1)

val word = maybe undefined id (lookup word valsA)
mill word = maybe undefined id (lookup word millsA)

number = parse . lex
where lex = ("units" :) . reverse . words . map alphasOnly
parse = sum . map group . toGroups
group (power, words) = mill power * triple words
alphasOnly c = if isAlpha c then c else ' '

triple [] = 0
triple ("hundred" : words) = 100 * triple words
triple (word : words) = val word + triple words

toGroups [] = []
toGroups (power : rest) = (power, group) : toGroups rest'
where (group, rest') = break (`elem` millsW) rest

{-
*Main> number "one"
1
*Main> number "twenty"
20
*Main> number "three thousand"
3000
*Main> number "three thousand twenty-five"
3025
*Main> number "one million two hundred thousand"
1200000
-}

Also, fucking Haskell. The moment I got it to compile, it just worked, correctly.