NoOne
BAN USERLook at that link there? That is the language we have created.
- 1of 1 vote
AnswerSuppose there is a function given to you that:
def get_friends( person_id ) { /* returns friends of person */ }
How you are now going to recommend friends to a person based on number of mutual friends? So, come up with the function:
- NoOne in Indiadef friend_reco( person_id, max_no_of_friends ){ }
| Report Duplicate | Flag | PURGE
Amazon SDE-3 Algorithm - 0of 0 votes
AnswersGiven billions of Identity cards of the form :
card : { my_id : "my id", "moms_id" : "mom id", "dad_id" : "dads id" }
If one gives you two Person's id, how can you tell if these 2 persons are blood related.
So, write a function that is:
- NoOne in Indiadef is_blood_related( person_id_1, person_id_2 ) // go on..
| Report Duplicate | Flag | PURGE
Amazon SDE-3 Algorithm - 2of 2 votes
AnswersGiven an unsorted array of integers, find the length of the longest consecutive elements sequence.
- NoOne in India
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4].
Return its length: 4.
Your algorithm should run in O(n) complexity.| Report Duplicate | Flag | PURGE
Uber Senior Software Development Engineer Algorithm - 1of 1 vote
AnswersThe stock exchanges work with price matching. A seller comes with a price, and a buyer, given asking for the exact same price are matched, and in quantity.
- NoOne in India
Design a system that works.
Considerations:
1. More than a million buy/sale happens in a second.
2. One needs to show a ticker prices - last sold price of a stock.| Report Duplicate | Flag | PURGE
Myntra Software Architect Algorithm - 0of 0 votes
AnswersCreate a data structure that stores integers, let then add, delete. It also should be be able to return the minimum diff value of the current integers.
- NoOne in India
That is,
min_diff = minimum ( | x_i - x_j | )
Example:
-1,3,4,10,11,11
min_diff = 0
-1,3,4,10,11,14
min_diff = 1| Report Duplicate | Flag | PURGE
Uber Senior Software Development Engineer Algorithm - 0of 0 votes
AnswersThe original question can be found from here :
- NoOne in India
franklinchen.com/blog/2011/12/08/revisiting-knuth-and-mcilroys-word-count-programs/
Read a file of text, determine the *n* most frequently used words, and print out a sorted list of those words along with their frequencies.
In the same spirit of the history:
1. Do it using pure shell scripting
2. Do it in the favourite language of your choice
Try to minimise code and complexity.| Report Duplicate | Flag | PURGE
Deshaw Inc Software Developer Algorithm - 0of 0 votes
Answer1. If I say quick sort takes O(e^n ) on the average, would I be wrong?
- NoOne in India
2. Do you think O( f ) is a good idea for real engineering?
3.Given a choice, what other 'order of' measure would you propose to use ?
4. Do you see a real problem with the modified *order of* ?
5. If you were to sort 10 elements, what sorting method would you have used?
6. If you were to sort 1 trillion unicode characters, what sorting method you would have used?| Report Duplicate | Flag | PURGE
Microsoft SDET Algorithm Math & Computation - 0of 0 votes
AnswersThe actual problem from question?id=6289136497459200
Implement pow, with :// Assume C/C++, as of now double pow ( double x, double power )
No library functions allowed.
Should return : x^power
=== Edit ===
People took it a bit trivially, thus examples should help :
- NoOne in United Statesx = pow ( 4, 0.5 ) // x = 2.0 x = pow ( 8, 0.333333333 ) // 1.99999999986137069 x = pow ( 10.1 , 2.13 ) // 137.78582031242644
| Report Duplicate | Flag | PURGE
Microsoft SDET Algorithm - 0of 0 votes
AnswersFrom here : question?id=5660692209205248
- NoOne in United States
In-order traversal:
A->B->C->D->E->F->H->L->M-P->R->S->T
Write a function (pseudo-code is fine) that given a starting node, advances to the next in-order node in a binary tree.
Please also provide a data-structure definition of a node.| Report Duplicate | Flag | PURGE
Arista Networks Software Developer Algorithm Trees and Graphs - 0of 0 votes
AnswersApparently DESCO asked it. It was faulty, and I am fixing it. The physics was wrong. A mono pole is an abstract magnet with either the north or the south pole of the magnet.
[ en.wikipedia.org/wiki/Magnetic_monopole ]
Imagine you are given such *n* monopoles, all of the same type, say North type. Thus, all of these repel one another. The force of repulsion follows inverse square law :
[ en.wikipedia.org/wiki/Inverse-square_law ]
That is, given two such monopoles with a distance *r* between them, the force of repulsion between them is given by :F = ( 1.0 ) / ( r ** 2 )
Now, suppose you are also given an array of *n* number of positions over X axis, like : [ 0, 1, 4, 10 , 21 , .. ] where you need to place the monopoles ( imagine they are hold tight there, and do not move away ).
- NoOne in United States
After placement, you are given another monopole, of different type S, say. Find positions to place the monopole so that it is stable.
Fixes from the original question :
[geeksforgeeks.org/d-e-shaw-interview-experience-set-19-on-campus/ ]
1. Monopoles exhibit inverse square law, not inverse law.
2. It is impossible to have stable configuration using same type monopole, so one must use another type, repulsion is not stable, attraction is.
( Terrible physics mistakes )
PS. Do not try to do binary search here. Binary search assumption is underlying linearity of the structure, thus, effectively there are proportionate elements in left and right. In the classic cases of sorted array, the expectation is 50/50. But here due to non linearity (inverse square) , it won't work.| Report Duplicate | Flag | PURGE
Deshaw Inc Software Developer Algorithm - 0of 0 votes
AnswersGiven a set of numbers, find out all subsets of the set such that
the sum of all the numbers in the subset is equal to a target number.s = [ 1, 2, 3, 4, 5 ] target = 5 op = [ [ 1,4 ] , [2,3] , [5] ]
Application: Given a fixed budget, and work items we are doing back filling to check what all we can attain with the budget.
Continuation. Imagine the set is actually a set of work items, with cost and utility involved :def work_item : { name : 'foo bar' , cost : 10 , utility : 14 }
Now, solve this to maximise utility.
Continuation. Imagine that the work items are related, so that, if work item w1 is already in the
subset of the work items selected, w2 's utility increases further!.
( Can you imagine how it can happen? Effectiveness of Mesi increases when he plays for Barca)
So, you are given a list like this :w1 -> normal utility 14, with w2 20, ....
Now maximize payoff.
NOTE: Payoff is a matrix. This comes from game theory.
Hence, a payoff matrix looks like :w1 w2 w3 w4 .... w1 w1 w2 w2 w3 w3 w4 w4
A cell ( i,j) is filled up with if a list contains both wi and wj, then how much the payoff would be. It is a symmetric matrix.
- NoOne in United States| Report Duplicate | Flag | PURGE
Amazon SDE-3 Algorithm - 0of 0 votes
AnswersWe tend to use computer to solve practical problems that actually earns or save dollars. Here is something that happens across the stock exchanges : people buy and sell stocks.
- NoOne in India
We generally use automated intelligent systems to buy and sell stocks. That part is too much mathematics, and beyond scope of this interview. There is another part. Suppose the system issues a buy order : buy 1000 Microsoft stock. Now, there are more than 1 ( in fact 10 ) active exchanges from where we can buy MSFT. There is a slight price delta, which keeps changing over time. There is another problem. In each stock exchange, prices are stacked, that is :
1. For first 100 stocks prices are 55$.
2. Next 200 stocks, prices are 55.2$.
... etc, and you got the idea. Even this stacks are changing over time.
Thus, here is the problem to solve. Design and implement a system such that one can buy n stocks with minimal price.
Also, in the same spirit, the same system should be able to sell n stocks with maximum payoff possible.
This is a non trivial problem, for Quant systems.
There are always k no of exchanges to hit.| Report Duplicate | Flag | PURGE
Goldman Sachs Software Engineer / Developer Algorithm Cache Computer Architecture & Low Level Computer Science Distributed Computing Large Scale Computing Math & Computation Software Design - 0of 0 votes
AnswersAs you know, Computers were invented to solve practical business problems, we tend to ask practical applied questions. One of the key areas where we want to apply computers is simulation. As most of the people working in software are Engineers, here is the problem. It is called 3 body problem.
- NoOne in India
3 Bodies with masses [ m1, m2, m3 ] are initially positioned in the 3 points in the space, thus, having positions [ P1, P2, P3 ].
Observe that each Pi is nothing but [ xi, yi, zi ].
Once the initial condition is set, definitely gravity would work and they would start falling against each other. Write code to simulate this problem. Imagine G, the constant of gravity as 1.
How do you go about simulating it?
Hint : feynmanlectures.caltech.edu/I_09.html see 9.5
Face to face. Pen and Paper. Panel Interview, 2 person Panel. 60 Minutes. For Engineers only, was specifically told about it.| Report Duplicate | Flag | PURGE
Software Developer Algorithm Computer Science Graphics Math & Computation Programming Skills - 0of 0 votes
AnswersGiven a convex polygon ( is planer as opposed to a polytope) and a point one had to tell if the point lies inside the polygon or outside the polygon.
- NoOne in India
To understand convexity : mathopenref.com/polygonconvex.html
Thus the question comprise of 3 sub problems :
1. How to store a polygon.
2. How to define inside and outside of a polygon.
3. How to solve the actual one, given 1,2 ?| Report Duplicate | Flag | PURGE
Deshaw Inc Software Developer Algorithm - 0of 0 votes
AnswersAs you guys know, C did not have,and does not have anything called class. C++ has them. Now, C++ was written using C. In fact, C++ initially was called C with classes.
- NoOne in India
Thus, here is the problem for you.
Given you have C, and you need to implement class like behaviour, how you would do it? Specifically, implement the following in C :
1. A Simple Hello class with hello() function printing "Hello, World" .
2. A new operator which enables creating this constructor less class.
3. A delete operator that deletes the pointer.
How would you do it?| Report Duplicate | Flag | PURGE
Deshaw Inc SDET C - 0of 0 votes
AnswersLinux has this nice command called *tree*.
- NoOne in India
If you did not use it, please take a look around.
You do not have to write one. BUT, you have to do something similar. Given a file name ( not a path ), and an initial directory, you have to list all the file paths, which matches the file name, case should not be considered.
Also allow regex match.
Again, the problem is non trivial.
It was expected to ask the right questions.| Report Duplicate | Flag | PURGE
SDET Algorithm Operating System - 0of 0 votes
AnswersThere is this nice tiny *nix utility called *wc*.
The idea here is :wc file_name
prints :
- NoOne in India
character count of the file.
Word count of the file.
Line count of the file.
You have to implement your own *wc* program.
NOTE: The problem is non trivial for 3 reasons.
It was expected to ask about the non triviality.| Report Duplicate | Flag | PURGE
SDET Algorithm Operating System - 0of 0 votes
AnswersNone actually understands how garbage collection works, albeit people ask this in the interviews. Nonetheless, we are going to ask you something very similar. Here is the problem.
Take an array of bytes, perhaps 1MB in size.
Implement these two operations:ptr_structure = alloc ( amount_of_storage ) freeed = free ( ptr_structure )
Now, here is your problem. alloc must allocate contiguous storage. If it is not possible, you need to compact ( defragment ) memory. So, you need to implicitly write a :
defragment() // defragments memory
Worse is coming. Even imagining you have written a stop the world defragmenter, after you reallocate, how the ptr_structures would actually work?
- NoOne in India
Solve this whole problem.
Time allocated was 1 hour. Face to face, panel with 2 interviewers.| Report Duplicate | Flag | PURGE
SDET Algorithm Assembly Computer Architecture & Low Level Computer Science Data Structures - 0of 0 votes
AnswersImagine there are brick boulders, all of integer size.
Their sizes are stored in an array.
The figure looks something like this :
peltiertech.com/Excel/pix2/Histogram2.gif
Now, suppose someone is pouring water into it till water starts spilling.
You have to answer how much water the boulders are holding up.
- NoOne in Indiadef water_holding( arr ) { /* answer this */ }
| Report Duplicate | Flag | PURGE
Deshaw Inc SDET Algorithm - 0of 0 votes
AnswersXPATH implementation problem.
- NoOne in India
Here is the problem.
Implement XPATH expressions, given there is a DOM tree :
1. $x('//*[text() = "abc"])
How do you think it is implemented? Write code, imagine you have a general purpose tree.
2. $x('//span[text() = "abc"])
How do you think it is implemented? Write code, imagine you have a general purpose tree.
Now, explain which one would be faster, and why?
Explain from the design and the code you have written.| Report Duplicate | Flag | PURGE
SDET Algorithm Application / UI Design - 0of 0 votes
AnswerAs you know, every OS comes up with this tiny application called the calculator. It is good. Now, here is our problem. If we try to implement the function
def calculate( operand, operator, operand ) { /* Do Interviewers bidding here */ }
I have to write if upon if upon if upon if to do for all operators. Moreover, some operators are not even binary! Take example the abs() or say the negate()!
- NoOne in India
Bigger problem persists. With the if mode, we can not even add operators as we wish to without changing code!
But that is a sin. So, what do we do? That is question 1.
In question 2, as a software tester, how do you propose to test and automate the above? Writing more if than the developer is not allowed.| Report Duplicate | Flag | PURGE
SDET Algorithm Data Structures Object Oriented Design Programming Skills Software Design - 0of 0 votes
AnswersWe all know databases are very very slow. In fact they are so slow that very serious people who wants to do volumes of read operation and search operations write their own implementation. In this question, you would be asked to do the same, for a very limited operation - select.
Every item stored has this field called timestamp.
Now, here is the problem you need to solve :select items where time < some_time select items where time < some_time and time < another_time select items where time > some_time
Imagine you have millions of data rows. How to store it in HDD, and how to load, entirely your problem. None is going to insert anything on existing data - only read.
- NoOne in India
Write an algorithm that solves this problem, and a data structure that works as storage for the data.| Report Duplicate | Flag | PURGE
SDET Algorithm Database - 0of 0 votes
AnswersImagine you are given the instructions :
GOTO <LABEL> WHEN <CONDITION> NOP ; no operation
Implement the following using it:
- NoOne in India
1. If condition.
2. If else condition.
3. If else if else condition.
4. While loop
5. for loop.| Report Duplicate | Flag | PURGE
SDET Assembly - 0of 0 votes
AnswersGiven brackets, e.g. '(' and ')' as the only symbols, write a function that would generate : true, if the brackets are matching, false if the brackets are not matching.
- NoOne in India
Almost everyone can do the above.
Now, prove that it works.
Also tell which class of grammar the string belongs to.
Showcase why your algorithm is a language recogniser for the same.| Report Duplicate | Flag | PURGE
SDET Automata - 0of 0 votes
AnswersYou are given 20 questions to solve in 20 minutes.
- NoOne in India
If you successfully solve the question, you would receive 2 marks.
If you failed to solve the question, and you do not try it ( let it untouched ) , you would receive 0 marks. If you solve it wrong ( i.e. not the correct answer ) - you would receive -1 ( negative) .
With the story, here are the problems:
1. Write an algorithm, which, given an input array ( set ) of questions, and varying probability ( 0 <= p <= 1 ) of can do and can not do per question, generates a strategy for solving the paper to generate maximum expected pay off.
2. Given the question paper is multiple choice, between 4 choices ( a,b,c,d ) do a bias analysis ( e.g. if more a's are coming than 'c's ), and decide if you would like to probabilistically take risk and mark some to increase pay off.
Obviously, you can get a maximum 40, and a minimum -20.
3. Now, put yourself in the position of the examiner, and try to ensure it is almost impossible to increase payoff by random selection over the questions. Try to negate the bias. That is question 3.
In all 3 cases write an algorithm. Face to face interview, time allocated was 60 minutes. Panel Interview.| Report Duplicate | Flag | PURGE
unknown SDET Algorithm - 0of 0 votes
AnswersFind the n'th Ugly no. An ugly no. is defined as a no. which are of the form :
n = ( 2 ** p ) * ( 3 ** q ) * ( 5 ** r )
with p,q,r >= 0 and are integers not all equal to zero.
- NoOne in United States
You must not memorise the whole sequence, as n can be really large.
Hint : use number theory to figure out the pattern of the increasing sequence.| Report Duplicate | Flag | PURGE
Algorithm - 0of 0 votes
AnswersGiven an array, move the smaller no to the left and the larger nos to the right. The relative positioning between the small no's and the relative positions between the large nos should not change.
The original ( ill formulated ) question can be found here :
question?id=5756583549075456.
Example :a = [ 6 4 5 0 2 1 11 -1 ] after_a = [ 0 , 2, 1, -1, 6, 4, 5, 11 ]
Note, for lack of good explanation, please do not laugh at the poster in the solutions. After all, they are trying to help or get help.
- NoOne in United States| Report Duplicate | Flag | PURGE
Arrays
We can do this by combinations.
Observe that we have 64 * 63 possibilities for two queens, and we can change the order.
That is : 2 * 64 * 63 ways one can arrange 2 queens : T
Now, out of them, how many won't be stable?
Observe that a configuration is unstable iff The queens are in the same :
1. vertical
2. horizontal
3. diagonal.
1. Is possible by : 8 * P(8,2) ways : H
2. Is possible by : 8 * P(8,2) ways : V
3. Is possible by : 4 * ( P(8,2) + P(7,2) + ... P(2,2) ) : D
number of ways = T - H - V - D
In ZoomBA lang, you can be as declarartive as you want, and you can mix style.
events = [ ["Jane", 1.2, 4.5], ["Jin", 3.1, 6.7], ["June", 8.9, 10.3] ]
// sort them with field index 1 : e.g. start time
sorta( events ) :: { $.left.1 < $.right.1 }
// create a list of time slots
left = { 's' : events[0].1 , 'e' : events[0].2 , 'c' : 1 } // first one
col = fold ( [1 : #|events| ], list( left ) ) -> {
right = events[$.o]
/* There can be two cases.
1. right is included in left
2. right and left are independent, with no overlap
*/
left = $.p[-1] // last one is the left
if ( left.e >= right.1 ) { // overlap
// completely included
continue ( left.e >= right.2 ){ left.c += 1 }
// split the interleaving
left_half = { 's' : left.s , 'e' : right.1 , 'c' : left.c }
middle_half = { 's' : right.1 , 'e' : left.e , 'c' : left.c + 1 }
right_half = { 's' : left.e , 'e' : right.2 , 'c' : 1 }
$.p.pop() // pop the last item added to the list
// add them up
$.p += [ left_half , middle_half , right_half ]
}else{ // non overlap
$.p += { 's' : left.e , 'e' : right.1 , 'c' : 0 }
$.p += { 's' : right.1 , 'e' : right.2 , 'c' : 1 }
}
// return partial
$.p
}
col += { 's' : col[-1].e , 'e' : num('inf') , 'c' : 0 }
// now print
println( str( col , ' , ' ) -> { str('(%s,%s)', $.o.s, $.o.c ) } )
// Shows the full declarative power of ZoomBA
tel_dict = { 2 : [ 'a','b','c' ] , 3 : ['d' ,'e' ,'f' ],
4 : [ 'g' , 'h' ,'i' ], 5 : [ 'j', 'k', 'l' ],
6 : ['m','n','o' ], 7 : [ 'p', 'q','r' ,'s' ],
8 : [ 't' ,'u','v' ], 9 : [ 'w' , 'y' ,'z' ] }
// meaningful words?
words = select( file('/usr/share/dict/words') ) :: { #|$.o| == 7 } -> { $.o.toLowerCase }
ph_no = 2742538 // your input : cricket
args = list( str(ph_no).value ) -> { tel_dict[ int($.o) ] }
meaningful = join( @ARGS = args ) :: {
word = str( $.o ,'' )
word @ words } -> { str( $.o ,'' ) }
println ( meaningful )
/* ZoomBA
Note that sivapraneethalli is kind of correct.
A much better way to achieve this is to see this :
xy is a palindrome iff :
y = ( x ** -1 ) or
y = ( x[0:-2] ** -1 )
As an example :
1. x = abc
y = cba
2. x = abc
y = ba
Thus, a better algo is to store the potential y's as keys to
to a map, and value being that of x in a list.
Hence, we can get it done in two passes.
*/
def find_pair_palindromes( strings ){
map = fold( strings , dict() ) -> {
x = $.o
key = str( x ** -1 )
$.p[ key ] = $.i // store index
if ( size(x) > 1 ){
key = str( x[0:-2] ** -1 )
$.p[ key ] = $.i // store index
}
$.p // return
}
fold ( strings ) -> {
y = $.o
if ( y @ map ){ printf( '%s %s\n', strings[ map[y] ] , y ) }
}
}
listOfWords = list( "shiva" , "and" , "are" , "vihs" , "avihs" )
find_pair_palindromes( listOfWords )
Here seems to be a Theta(n+k) solution.
/*
Note that to way to do it most optimally is
to generate a indices map from the ranges,
which does not require a sorting.
Once the dictionary is created,
all we do is traverse over the indices range given
[0,k] ; or in ZoomBA [0:k+1] -> and print counts
or zero if the index is not found.
*/
range = [ [5,7],[1,4],[2,3],[6,8],[3,5] ]
// this takes ( min to max )
d = fold( range , dict() ) -> {
#(b,e) = $.o // items are tuples
for ( i : [b:e+1] ){
// add indices and store counts
if ( i @ $.p ){
$.p[i] += 1
}else{
$.p[i] = 1
}
}
$.p
}
println ( d )
// produce the result
ar = [0:9] // from 0 to 8 indices
fold ( ar ) -> { printf ( '%d -> %d\n', $.o , $.o @ d ? d[$.o] : 0 ) }
Simplest is storing into a file, and then use standard sorting techniques to sort them later.
Given the digits are fixed, we can create a directory tree with LSB at the top, and MSB in the leaf, while the leaf storing the number of repetitions.
So, 1023456 would be stored as :
/6/5/4/3/2/0/1/[count=1]
while 1024 would be stored as :
/4/2/0/1[count=1]
Now, what happens when we do postorder traversal on the tree with children in sorted order? All one needs to do is to store the path from root, and reverse it, and then we have our answer. For multiple occurrence, simply repeat the same count no of times, and we are good.
The max depth of that tree would be 8 ish in base 10.
To do Uniform stuff, one needs to do these steps.
1. Get a function -> next_higher_permutation( array ) : available from here :
stackoverflow.com/questions/1622532/algorithm-to-find-next-greater-permutation-of-a-given-string
2. A random no generator to pick large integers from range [0,N)
3. A really large integer container for storing n! ( n factorial ).
Now, the algorithm.
1. Use [2] to generate a number between 0 and n! ( n factorial ) say it is N.
2. Start with the sorted permutation : [ 0,1,2,...n-1 ] as array and then apply
next_higher_permutation on the array N times.
// These sort of problems are kids play in ZoomBA
// We first create a regular expression match from the templates given
// Here, we replace 0 -> .? to ensure only one char matches for 0
def matching_rows( template_row , all_permutations ){
template = str(template_row,'').replace('0','.?')
select( all_permutations ) :: { str($.item,'') =~ template }
}
// A join result sudoku is valid if and only if
// the column splitting are all unique
def valid_sudoku( m , n ){
!exists ( [0:n] ) :: {
s = set ( [0:n] ) -> { m[$.item][$.$.item] }
#|s| != n
}
}
// get the template
my_template = [ [1, 2, 0], [0, 1, 0], [0, 0, 1] ]
// generate the permutations
perms = join( @ARGS = list([1:4]) -> { [1:4].list } ) :: {
#|set($.item)| == #|$.item|
}
// from the templates, get the permutations which can be used for
// generating the input argument for the join
args = list ( my_template ) -> {
matching_rows( $.item , perms )
}
// finally join the options to solve the sudoku as a join problem
results = join ( @ARGS = args ) :: {
valid_sudoku ( $.item , 3 )
}
println( results )
// and it is still less than 42 lines of code.
This is so obvious that comments are really not needed.
// ZoomBA
def sanitize( range ){
#(l,r) = range.split('-')
return ( l == r ? l : range )
}
def split_range( range , n ){
#(l,r) = range.split('-')
if ( n == l ){
return sanitize( str( int(l) + 1 ) + '-' + r )
}
if ( n == r ){
return sanitize ( l + '-' + str( int(r) - 1 ) )
}
[ sanitize(l + '-' + ( n - 1) ) , sanitize( str(n+1) + '-' + r ) ]
}
def do_fancy_stuff( l ){
fold ( l , list( '0-99' ) ) ->{
res = split_range ( $.prev[-1] , $.item )
$.prev.remove( #|$.prev| - 1 )
$.prev += res // cool ?
}
}
println( do_fancy_stuff( [ 0,1,2,50,52,75 ] ) )
/*
Everyone solved it right.
Thus, I am flexing some muscle power of ZoomBA,
to showcase the full declarative nature of the language :
*/
def find_pivot_index( arr ){
if ( empty(arr) ) return -1
if ( size(arr) == 1 ) return 0
sums = [ 0 , sum( arr ) - arr[0] ]
x = index ( [ 1 : #|arr| ] ) :: {
sums.0 += arr[ $.item - 1]
sums.1 -= arr[ $.item ]
sums.0 == sums.1
}
x < 0 ? x : x + 1
}
println ( find_pivot_index( [ 0,6,4,1,2,3 ] ) )
gekko is correct, it is meaningless. But..
In any case, given this json :
{
"value" : 1 , "children" : [
{ "value" : 2 , "children" : [
{ "value" : 4 , "children" : [] },
{ "value" : 5 , "children" : [] }
] } ,
{ "value" : 3 , "children" : [
{ "value" : 6 , "children" : [] },
{ "value" : 7 , "children" : [] }
] }
]
}
This code is going to work out well for the reverse God knows what level order thing:
/*
A Level order traversal.
The key is to understand that,
you need to maintain two queues, one for current,
another for next level.
After a level is exhausted,
one needs to replace that queue by the one from built up.
As we can see, this won't solve Amazon's problem,
Which is a reverse level order traversal.
So, we need to use a stack to store the per level nodes
which are to be stored in a queue! Thus,
The solution becomes , storing the queue in a stack!
But then, who needs queues? We can simply use a list!
*/
def reverse_level_order( root ){
cur = list( root ) // current level
stack = list() ; stack.push( list( cur ) )
while ( !empty(cur) ){
next = list()
for ( node : cur ){
for ( child : node.children ){
next += child
}
}
// push the level into the stack
stack.push ( list( next) )
cur = next
}
// now unwind the stack
while ( !empty(stack) ){
level = stack.pop()
for ( node : level ){
printf( ' %s ' , node.value )
}
}
println()
}
// call it
reverse_level_order( json( 'tree.json' ,true ) )
I am using imperative paradigm - to ensure that it stays comprehensible.
- NoOne November 10, 2016/* ZoomBA.
Level order traversal.
The key is to understand that,
you need to maintain two queues, one for current,
another for next level.
After a level is exhausted,
one needs to replace that queue by the one from built up
*/
def level_order( root ){
cur = list( root ) // current level
while ( !empty(cur) ){
// get one and go along with it
node = cur.dequeue()
printf(' %s ', node.value ) // print it
next = list()
for ( child : node.children ){
next.enqueue( child ) // queue it
}
println() // completes the level
cur = next // switch the level
}
}
// ZoomBA
def all_comb_words( string ){
len = #|string|
words = fold ( [ 0: 2 ** len ] , set() ) -> {
s = str( $.o,2)
s = ('0' ** ( len - #|s| ) + s )
opt = fold ( s.value , '' ) -> {
$.p += ( $.o == _'1' ? string[ $.i ] : '' ) }
opt = str(opt) ; sorta(opt.value)
$.p += opt
}
println( words )
}
all_comb_words ( 'aabcc' )
/* ZoomBA.
Observe the problem can be solved fully declaratively.
Observe we can index the chars from the
1. first string as : 0,1,2,3,4...
2. second string as : -1,-2,-3,...
Now, join with condition:
all -ve should be sorted descending
all +ve should be sorted ascending .
then, map back to generate the merged string
*/
def merge_strings( s1, s2 ){
r1 = [ 0 : #|s1| ]
r2 = [ -1 : -#|s2| - 1: -1]
l = r1.list + r2.list
join_args = list( [0:#|l|] ) -> { l }
join ( @ARGS = join_args ) :: {
// must be unique
continue( #|set($.o)| != #|$.o| )
#(pos,neg) = partition( $.o ) :: { $.o >= 0 }
// sorted ascending? if previous > current then it is not
last = reduce( pos ) -> { break( $.p > $.o ){ null } ; $.o }
continue ( last == null )
// sorted descending? if previous < current then it is not
last = reduce( neg ) -> { break( $.p < $.o ){ null } ; $.o }
continue ( last == null )
// now map back the string as word
true } -> { fold( $.o , '' ) -> {
$.p += ( $.o >= 0 ? s1[ $.o ] : s2[ -$.o - 1] ) }
}
}
println( merge_strings( 'hey', 'sam' ) )
/*
ZoomBA : Using Level Order Traversal
stackoverflow.com/questions/1894846/printing-bfs-binary-tree-in-level-order-with-specific-formatting
*/
def traverse(rootnode){
thislevel = list( rootnode )
height = 1
while ( !empty( thislevel ) ){
nextlevel = fold( thislevel , list() ) ->
$.p += list( $.o.children )->{ $.o }
}
thislevel = nextlevel
height += 1
}
height
}
/* ZoomBA : with Join */
A = ['a':'z'].string
def decode(string){
len = #|string|
join_args = fold( [ 0:len ] , list() ) -> {
inx = int ( string[$.o] )
continue( inx == 0 )
options = list('')
options += A[inx-1]
if ( $.o + 1 < len ){
inx = int( str(string[$.o]) + string[$.o + 1] )
if ( inx < 27 ){ options += A[inx-1] }
}
$.p.add ( options ) ; $.p
}
join( @ARGS = join_args ) :: {
w = str($.o,'')
str( w.value ,'' ) -> { $.o - 96 } == string
} -> { str($.o,'') }
}
ip = '1123'
words = decode(ip)
println( words )
And we have Quora.
quora.com/You-have-1000-wine-bottles-one-of-which-is-poisoned-You-want-to-determine-which-bottle-is-poisoned-by-feeding-the-wines-to-the-rats-The-poisoned-wine-takes-one-hour-to-work-How-many-rats-are-necessary-to-find-the-poisoned-bottle-in-one-hour
/* ZoomBA : Recursive */
A = ['a':'z'].string
$count = 0
def decode( string , result ){
if ( (len = #|string|) == 0 ) {
$count += 1 ; println( result )
return
}
if ( (inx = int(string.0) ) == 0 ) return
// now the rest
decode ( string[1:-1] , result + A[inx - 1] )
if ( len > 1 ){
two = string[0:1] ; inx = int(two)
if ( inx < 27 ){
decode ( string[2:-1] , result + A[inx - 1] )
}
}
}
ip = '1123'
decode(ip,'')
// ZoomBA : Bad, elementary, declarative.
LL = [ [4, 10, 15, 24, 26] ,
[0, 9, 12, 20] ,
[5, 18, 22, 30] ]
range = reduce( LL ) -> {
min = $.prev[0] ; max = $.prev[-1]
if ( min > $.item[0] ){ min = $.item[0] }
if ( max < $.item[-1] ){ max = $.item[-1] }
[ min, max ]
}
r = [range.0 : range.1 + 1]
join ( r, r ) :: {
#(min,max) = $.o // tuple
continue ( min > max )
out_of_range = exists ( LL ) :: {
!exists( $.item ) :: { min <= $.item && $.item <= max }
}
continue ( out_of_range || ( max - min > range.1 - range.0 ) )
range.0 = min ; range.1 = max
false
}
println( range )
// ZoomBA uLanguage. Simple.
paths = [ '', '' ]
def find_paths( key1, key2, node , path ){
if ( !empty(path.0) && !empty(path.1) ) return
if ( node == null ) {
if ( path #$ key1 ){ paths.0 = path }
if ( path #$ key2 ){ paths.1 = path }
return
}
find_paths ( node.left, path + '/' + node.key )
find_paths ( node.right, path + '/' + node.key )
}
// find paths
find_paths( key1, key2, root, '' )
// split and now match
paths.0 = paths.0.split('/')
paths.1 = paths.1.split('/')
#(s,l) = minmax ( paths ) :: { #|$.left| < #|$.right| }
inx = index ( [ #|s|-1:-1 ] ) :: {
paths[0][$.item] != paths[1][$.item]
}
println( s[0][inx] )
// ZoomBA
def conforms( demand, supply ){
// write code here
// this is a predicate filter
// should it subtract too? No idea
demand.quantity <= supply.quantity &&
time ( supply.expirationDate ) - "P3D" > demand.expirationDate
// note the use of en.wikipedia.org/wiki/ISO_8601#Durations
}
// this template code, does not need to change
dict ( demands ) -> {
demand = $.item
// read : select all supplies such that they conform to the demand
conformed_supplies = select ( supplies ) :: { conforms ( demand , $.item ) }
[ demand , conformed_supplies ]
}
// this is how business should code it. ALAS.
// ZoomBA
paren_arr = [ { _'<' : 1 , _'>' : -1 , 'c' : 0 },
{ _'(' : 1 , _')' : -1 , 'c' : 0 },
{ _'{' : 1 , _'}' : -1 , 'c' : 0 },
{ _'[' : 1 , _']' : -1 , 'c' : 0 } ]
// now the indexing
parens = { _'<' : 0 , _'>' : 0 ,
_'(' : 1 , _')' : 1 ,
_'{' : 2 , _'}' : 2 ,
_'[' : 3 , _']' : 3 }
def match_paren(string){
fold ( string.value , true ) -> {
matcher = paren_arr[ parens[ $.item ] ]
matcher.c += matcher[ $.item ]
break ( matcher.c < 0 ){ false }
true
} && ! ( exists ( paren_arr ) :: { $.item.c != 0 } )
}
println ( match_paren ( "<({()})[]>" ) )
println ( match_paren ( "<({([)})[]>" ) )
This is fully declarative. The logic is actually implemented in the maps, while the engine simply runs it through, also fully extensible.
- NoOne October 30, 2016Sergey is right. Just adding another interesting mix :
/*
With extra space, again exact in 2n
Given array not sorted
*/
def single_pass( arr , S ){
s = set( arr ) // create a set out of it
// find item x in arr such that S -x is in the set!
v = find ( arr ) :: { (S - $.item) @ s }
v.nil ? 'Nothing' : v.value
}
// ZoomBA
// Tree Node schema
def t_node : { v : 0 , l : left_node , r : right_node }
paths = list()
def find_paths( node , path ){
if ( empty(node) ){
paths.add ( path.split('/') )
return
}
if ( !empty( node.left ) ){
find_paths ( node.left , path + '/' + node.left.v )
}
if ( !empty( node.right ) ){
find_paths ( node.right , path + '/' + node.right.v )
}
}
// call this way
find_paths ( root, '/' + root.v )
// ZoomBA
/*
A replacement of '*' -> '(' implies +1
A replacement of '*' -> ')' implies -1
At any point, if the count is < 0, drop the path.
Finally, if the count is == 0, accept the path.
As we have three options, the choices can be made in ternary,
Thus, given k choice locations, there are 3 ** k options
Hence, we can reduce the recursion to iteration.
Using a mixture of imp/dec because of readability
*/
def count_options( s ){
num_stars = sum( s.value ) -> { $.item == _'*' ? 1 : 0 }
options = set() ; len = #|s|
map = { _'0' : '', _'1' : '(' , _'2' : ')' , _'(' : 1, _')' : -1 }
for ( select_pattern : [0: 3 ** num_stars ] ){
star_count = -1
ter_pattern = str( select_pattern , 3 )
ter_pattern = '0' ** ( #|ter_pattern | - num_stars ) + ter_pattern
transformed = fold( s.value ,'' ) -> {
$.prev + ( $.item == _'*' ? map[ter_pattern[ star_count += 1 ]] : $.item )
}
continue( transformed @ options ) // avoid unnecessary stuff
res = sum ( transformed.value ) -> {
break( $.prev < 0 ){ -len } ; map[$.item]
}
if ( res == 0 ){ options += transformed }
}
println( str( options,'\n' ) )
size( options ) // return size of options
}
println( count_options( '(*(*)*)' ) )
// ZoomBA
def sales_force( s ){
len = #|s|
if ( len == 0 ) return ''
#(last,cnt, ret) = fold ( [1:len] , [s[0], 1, '' ] ) -> {
#(prev, count, res ) = $.prev
if ( prev != s[$.item] ){
res += ( str( prev ) + count )
count = 1
}else{
count +=1
}
[ s[$.item] , count , res ]
}
ret += ( str( last ) + cnt )
}
s = 'aaabbdcccccf'
println( sales_force( s ) )
// ZoomBA avoids coding... thus :
def do_fb( l ){
sorta ( l ) :: { $.left.0 < $.right.0 }
// merge and sum intervals
#(s,last) = fold ( [1:#|l|] , [ 0 , l[0] ] ) -> {
prev = $.prev[1] ; cur = l[$.item]
if ( prev.1 >= cur.0 ){ // there is overlap
// but, is current fully inside previous?
if ( prev.1 < cur.1 ){
// merge them
$.prev[1] = [ prev.0 , cur.1 ]
}
} else {
// update sum
$.prev.0 += ( prev.1 - prev.0 )
$.prev.1 = cur
}
$.prev
}
s += ( last.1 - last.0 )
}
input = [[1,4], [6,8], [2,4], [7,9], [10, 15]]
println ( do_fb( input ) )
// ZoomBA
def first_non_repeat(string){
// use sorted dictionary to keep insertion order
d = fold ( string.value , sdict() ) ->{
if ( $.item @ $.partial ){ $.partial[ $.item] += 1
} else { $.partial[ $.item] = 1 }
$.partial
} // this is now an multi set : search for first entry with count 1
r = find ( d ) :: { $.item.value == 1 }
// Option Monad, either exists or does not
println ( r.nil ? 'Nothing' : r.value.key )
}
first_non_repeat ( "aaaabbbbacccdbbbbeeeg" )
As our previous code was grossly complex, this one does crack the algo fine. nJoy, ZoomBA
/*
1. Start with the substring from start which is anagram of a word
2. Now match recursively the rest
3. Test if everyone can generate a non empty word list or not
Doing it recursively, push to stack if need be : string, words_until_now
*/
def do_googles_bidding( string , sorted_dict , words_until_now ){
for ( end : [0:#|string|] ){ // making it non trivial
s = string[0:end] // splice
sorta( s.value ) // sort and gen key
if ( s @ sorted_dict ){
if ( end == #|string| - 1 ){ // in this case, we have found a match
// note : I am not translating back the actual words, that is trivial
println ( words_until_now + ',' + s ) ; return }
// now, do on the suffix string
do_googles_bidding( string[end+1:-1] , sorted_dict , words_until_now + ',' + s )
}
}
}
// generate the sorted dict
sorted_dict = mset ( file( '/usr/share/dict/words' ) ) -> {
lc = $.o.toLowerCase() ; sorta( lc.value ) ; lc }
do_googles_bidding( 'elhloothtedrowl' , sorted_dict , '')
// ZoomBA : Imperative solution, because people may not like the declarative one
/*
Two phases to do it.
1. Generate all possible splitting - partition of the input string
2. Given a partition, sort the individual words in the split
3. Check if all the words belongs to the dictionary by matching them
4. Against a pre word sorted dictionary
*/
def do_googles_bidding( string , sorted_dict ){
len = #|string|
for ( n : [ 0 : 2 ** (len - 1)] ){
sn = str(n,2)
sn = '0' ** ( len - #|sn| ) + sn // 0 padded
end = len - 1 ; start = end
partitions = list()
failed = false
while ( start >= 0 ){
if ( sn[start] == _'1' ){
p = string[start:end]
// generate the key by sorting chars, and checking
lc = p.toCharArray() ; sorta(lc) ; lc = str(lc,'')
break ( !(lc @ sorted_dict) ) { failed = true }
partitions.add(0, lc ) // add the sorted key
end = start - 1
}
start -= 1
}
if ( !failed && end >= 0 ){
p = string[0:end]
lc = p.toCharArray() ; sorta(lc) ; lc = str(lc,'')
if ( lc @ sorted_dict ) {
partitions.add(0, lc )
println( partitions )
return partitions
}
}
}
return []
}
// generate the sorted dict
sorted_dict = mset ( read( '/usr/share/dict/words' ) ) -> {
lc = $.o.toLowerCase() ; sorta( lc.value ) ; lc }
result = do_googles_bidding( 'elhloothtedrowl' , sorted_dict )
println ( result )
// ZoomBA
def max_palindrome( string ){
// create a mapping of char -> count
cb = mset ( string.value )
#(m,M) = minmax( cb ) :: {
#(l,r) = $.item ; (2 /? l.value) || (l.value < r.value) }
middle = (2 /? M.value) ? '' : str( M.key )
// generate palindrome by appending v to left and right
fold ( cb , middle ) -> {
// no need to take care of even n odd because, (2x+1)/2 -> x anyways
v = str( $.item.key ) ** ($.item.value /2 )
v + $.partial + v
}
}
s = 'akjhadajsoadjaoiwjewaodjaosid'
println ( max_palindrome( s ) )
/*
Binary Tree :
a
/ \
/ right_tree
/
left_tree
*/
tree_pre = "(a (left_tree)(right_tree))"
tree_in = "((left_tree) a (right_tree))"
tree_post = "((left_tree) (right_tree) a)"
/* use () to define non existing node */
Any of them would simply work out well. This is a very simple form, isomorphic to a JSON encoding of the same as map of maps.
- NoOne October 22, 2016// ZoomBA
def group( s, k ){
s = s.replace('-','')
len = #|s|
rreduce ( s.value ) -> {
(( $.index != 0 && k /? ( len - $.index) )?'-':'') +
$.item + $.prev }
}
s = "2-4a0r7-4k"
println ( group ( s, 2 ) )
println ( group ( s, 3 ) )
println ( group ( s, 4 ) )
println ( group ( s, 5 ) )
/* ZoomBA
1. When both strings have same length
> Check if they differ in only one char
2. When both strings differ in length
> Check if they differ only by 1 size
> larger can be created by a split of the smaller:
> larger = smaller_1 new_char smaller_2
*/
def same_length(string1, string2){
counter = 0
!exists ( [0: #|string1| ] ) :: {
counter += ( ( string1[$.o] != string2[$.o] ) ? 1 : 0 )
counter > 1 // updates local, seeded by global
}
}
def diff_length( smaller , larger ){
first_diff = index ( [0:#|smaller|] ) :: {
smaller[$.o] != larger[$.o] }
// from first diff, everything else should match
!exists ( [first_diff : #|smaller| ] ) :: {
smaller[$.o] != larger[$.o + 1 ] }
}
def one_distant_apart( s1, s2 ){
l1 = #|s1| ; l2 = #|s2|
if ( #|l1 -l2 | > 1 ) return false
if ( l1 == l2 ) { return same_length( s1, s2 ) }
if ( l1 < l2 ){ return diff_length ( s1, s2 ) }
return diff_length ( s2, s1 )
}
// ZoomBA : Much better optimised code.
board = [ [ 'h', 'i', 'c', 'f'],
[ 'g', 's', 'b', 'k'],
[ 't', 'z', 't', 'v'],
[ 'n', 'e', 'd', 'u'] ]
map = fold ( board , dict() ) -> {
row = $.item ; row_index = $.index
$.partial |= dict( row ) -> {
[ board[row_index][$.index] , [ row_index , $.index ] ] }
}
def is_found( positions ){
fold ( [1: #|positions| ] , [ true, true, true ] ) :: {
#(p_r, p_c) = positions[ $.item - 1]
#(r, c) = positions[ $.item ]
#(h,v,d) = $.partial
// horizontal
h &= ( (p_r == r ) && ( c - p_c == 1 ) )
// vertical
v &= ( ( r - p_r == 1 ) && ( c == p_c ) )
// diagonal
d &= ( ( r - p_r == 1 ) && ( c - p_c == 1 ) )
[ h, v, d]
}
}
def word_exists( word ){
if ( empty(word) ) return false
#(positions ? e ) = list ( word.value ) -> { map[str($.item)] }
if ( empty(positions) ) return false
#(h,v,d) = is_found( positions )
( h || v || d )
}
println( word_exists ( 'hi') )
println( word_exists ( 'is') )
You are almost right Chris brackets matching are not regular.
They are (Non deterministic) Context Free at best.
And yea I give n take interviews fairly regularly.
Appeared for : 50+ , Taken : 600+. There were days where I used to take 10 interviews a day, and there are days where I used to appear for 3 full panel interview a day. It is a fun activity.
// ZoomBA
def term_parse( s ){
term = [ 0.0 , '' ]
p = tokens('^[\+\-]?(\d+(\.\d+)?)?')
m = p.matcher( s ) ; m.find() // true always
opts = { '' : 1.0 , '+' : 1.0 , '-' : -1.0 }
if ( m.group @ opts ) {
term[0] = opts[ m.group ]
} else {
term[0] = float( m.group )
}
inx = index ( s.value ) :: { str($.item) =~ '[a-zA-Z]' }
term[1] = s[ (inx < 0 ? 0 : inx) : -1 ]
if ( inx < 0 ){ term[1] = '' }
term
}
def gen_expr( s ){
l = tokens(s, '[\+\-]?[^\+\-]+') -> { term_parse( $.item ) }
d = mset ( l ) -> { $.item.1 }
}
def normalize( s ){
s = s.replace(' ','')
#(l,r) = s.split('=')
ld = gen_expr ( l )
rd = gen_expr ( r )
// merge
u = ld.keys | rd.keys // union
poly = list ( u ) -> {
k = $.item ; coeff = 0.0
if ( k @ ld ){ coeff += sum ( ld[k] )->{ $.item[0] } }
if ( k @ rd ){ coeff -= sum ( rd[k] )->{ $.item[0] } }
[ k , coeff ]
}
sortd ( poly ) :: { #(l,r) = $.item ; l.0 < r.0 }
str( poly , '' ) -> { #(k,c) = $.item ; str( '%+f%s' , c , k ) }
}
x = normalize ( 'x^2 + 3.5xy + y = y^2 - xy + y + 10' )
println ( x )
Very imprecise formulation. Given the problem is :
1. False positives are not allowed : --> Do not say found, when it is not actually there.
2. False negatives are allowed --> Can say not found, when it is there.
These two axioms trivialises the problem. Just store the portion of the list as set what is possible in the memory.
Say "yes" when it exists in the set, otherwise say "No".
Was it a trick question?
// ZoomBA : Better optimised code
def is_palindrome( s, i, j ){
!exists ( [i : (j - i)/2 + i + 1 ] ) :: {
s[ $.item ] != s[ i + j - $.item ]
}
}
def find_max_palindrome( string ){
max_palindrome = [0,0] ; r = [0:#|string|]
join ( r, r ) :: {
i = $.item.0 ; j = $.item.1
continue( max_palindrome.1 - max_palindrome.0 > j - i ||
!is_palindrome( string , i, j ) )
max_palindrome.0 = i ; max_palindrome.1 = j
false
}
string[ max_palindrome.0 : max_palindrome.1 ]
}
s = "DEFABCBAYT"
r = find_max_palindrome( s )
println(r)
From the same Java Code. My first code is a sham, and should be avoided.
This, on the other hand is very concise. Abhinav, note that 1-1 mapping with ZoomBA land and Java island are possible, see code in both the languages :
def path_2_root( emp, tree ){
path = ''
while ( emp @ tree ){
path += ( emp + '\t' )
emp = tree[emp]
}
path += emp
return path.split('\t')
}
def do_ibm( s ){
values = s.split(",")
tree = dict ( [0: size(values) - 2 ] ) -> {
pair = values[ $.item ].split('->')
[ pair[1] , pair[0] ]
}
emp1 = values[-2]
emp2 = values[-1]
path1 = path_2_root( emp1 , tree )
path2 = path_2_root( emp2 , tree )
len = size( path1 ) > size( path2 ) ? size( path1 ) : size( path2 )
resolver = fold( [1:len] , '' ) -> {
break ( path1[ - $.item ] != path2[ - $.item ] )
$.prev = path1[ - $.item ]
}
}
import java.util.HashMap;
import java.util.Map;
/**
* Created by NoOne on 18/10/16.
*/
public class Main {
static String s = "Frank->Mary,Mary->Sam,Mary->Bob,Sam->Katie,Sam->Pete,Bob->John,Bob,Katie" ;
static Map<String,String> createDict(String[] items){
Map<String,String> m = new HashMap();
for ( int i = 0 ; i < items.length - 2 ; i++ ){
String[] pair = items[i].split("->");
m.put( pair[1], pair[0] );
}
return m;
}
static String[] pathToRoot( String employee, Map<String,String> tree){
StringBuffer buf = new StringBuffer();
while ( tree.containsKey( employee ) ){
buf.append( employee ).append( "\t") ;
employee = tree.get( employee );
}
buf.append( employee );
return buf.toString().split( "\t" );
}
static void doIBM( String s ){
String[] values = s.split(",");
Map<String,String> tree = createDict( values );
String emp1 = values[ values.length -2 ] ;
String emp2 = values[ values.length -1 ] ;
String[] path1 = pathToRoot( emp1 , tree ) ;
String[] path2 = pathToRoot( emp2 , tree ) ;
int len = path1.length > path2.length ? path1.length : path2.length ;
String resolver = "" ;
for ( int i = 0; i < len ; i++ ){
if ( !path1[ path1.length - 1 - i ].equals( path2[ path2.length -1 - i] ) ) {
break;
}
resolver = path1[ path1.length - 1 - i ];
}
System.out.println(resolver);
}
public static void main(String[] args){
doIBM(s);
}
}
Due to peoples request. Guys, I think it is good to learn pseudocoding on functional style.
Then, you can apply that to get faster, better imperative coding. NOTE: Java is not a very decent language for learning coding, python is much better.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by NoOne on 17/10/16.
*/
public class Main {
static String[] s = new String[] { "IBM cognitive computing" , "IBM \"cognitive\" computing is a revolution" ,
"ibm cognitive computing" , "'IBM Cognitive Computing' is a revolution?" };
static List<String> tokenize(String text, String regex){
Pattern p = Pattern.compile( regex , Pattern.DOTALL);
Matcher m = p.matcher( text );
List<String> l = new ArrayList<>();
while ( m.find() ){
l.add(m.group());
}
return l;
}
static String keyString( List l, String sep){
StringBuffer buf = new StringBuffer();
for ( Object o : l ){
buf.append( o ).append(sep);
}
String s = buf.toString();
return s.substring(0,s.length());
}
static void doIBM( String[] s ){
String previousKey = "" ;
String previousValue = "" ;
for ( String item : s ){
List words = tokenize( item.toLowerCase() , "[a-z0-9]+");
String key = keyString( words , " " );
if ( key.indexOf( previousKey ) < 0 ||
( previousKey.equals(key) && item.length() > previousValue.length() ) ){
continue;
}
previousKey = key ;
previousValue = item ;
}
System.out.println(previousValue);
}
public static void main(String[] args){
doIBM(s);
}
}
Here is how you go about it.
First the theory, and then the ZoomBA dance.
- NoOne December 03, 2016