NoOne
Look at that link there? That is the language we have created.
 0of 0 votes
AnswersWhat is the smallest number *n* by which the given number *x* must be divided to make it into a perfect square?
 NoOne in Indian = find_number( x )
 Report Duplicate  Flag
Microsoft Software Engineer / Developer Algorithm  0of 0 votes
AnswersThe original question can be found from here :
 NoOne in India
franklinchen.com/blog/2011/12/08/revisitingknuthandmcilroyswordcountprograms/
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
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
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
Microsoft SDET Algorithm  0of 0 votes
AnswersFrom here : question?id=5660692209205248
 NoOne in United States
Inorder traversal:
A>B>C>D>E>F>H>L>MP>R>S>T
Write a function (pseudocode is fine) that given a starting node, advances to the next inorder node in a binary tree.
Please also provide a datastructure definition of a node. Report Duplicate  Flag
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/Inversesquare_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/deshawinterviewexperienceset19oncampus/ ]
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
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
Amazon SDE3 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Arrays
/*
There are three variations of the problem,
when I used to ask this.
1. A string is actually a sequence of chars.
Those makes whitespaces special.
1.1 'I am cool' > 'cool am I'
1.2 'cool am I'
2. 2.1 'cool am I'
People generally tend to solve the 2.1.
While, 1.1, and 1.2 are where the fun really is.
Now, I present 1 liners, fully declarative form.
*/
// 2.1. The easiest one
str( (tokens( string , '\\S+') ** 1 ), ' ')
/*
Blue is Sky The // String
*/
// 1.1 :: 'I am cool'
spaces = tokens( string , '\\s+')
words = tokens( string , '\\S+')
l = fold ( [size(spaces)1:1 ] , list(words[1]) ) as { $.p += (spaces[$.o] + words[$.o]) }
str(l,'')
// 1.2 trivial. left as exercise .

NoOne
July 24, 2017 See my comments above.
def _recurse_( root, node, path ){
if ( empty(root.children) ){
return ( root == node ? path : '')
}
for ( inx : [0: size(root.children) ] ){
path = _recurse_(root.children[inx], node, path + '/' + inx )
if ( !empty(path) ){
return path
}
}
return ''
}
def find_path(root, node){
_recurse_(root,node,'')
}
def apply_path( root, path ){
if ( empty(path) ) return null
indexes = path.split('/')
cur = root
for ( inx : indexes ){
cur = cur[inx] ?? null
if ( empty(cur) ) return null
}
cur // reuturn
}
def facebook_problem( root_orig, node_orig, root_deep_copy){
path = find_path(root_orig,node_orig)
apply_path( root_deep_copy, path )
}

NoOne
July 23, 2017 Observe the notional xpath as defined as :
index1/index2/index3/.... implies from root, go to the node with index index1, that child's index2 child, then that child's index3 child so on and so forth.
It is obvious that we can have a function :
String find_path(TreeNode root, TreeNode node)
// returns the path to node in root, empty string otherwise.
Once we have that, the deep copy guy must have the xpath. Apply the same xpath to the deep copy tree, and you find the deep copy node.
TreeNode apply_path(TreeNode root, String xPath)
// returns the node to the path in root, null otherwise.
Some smart developer, may, want to combine these two functionalities for optimisations sake  I do not blame them, but they are inherently two distinct functionalities.
Now that the problem is split into 3 more problems, I am good to go. Next comment will have all the answers.
It is better to avoid writing a single line of code, when you can write it in 2 lines.
[ stackoverflow.com/questions/618378/selectuniqueordistinctvaluesfromalistinunixshellscript ]
./yourscript_to_isolate_ip.sh  sort  uniq u
and this, will run no matter how less memory you have.
Aws guys actually run it, so does azure folks. I am pretty sure Apple will do the same.
There is another very neat alternative than creating a large boolean bucket array, radix sort.
// radix_sort is Theta(n)
def radix_sort(meetings){
// all of these, by definition will have same no digits :: max 4
no_digits = size ( meetings[0].start, 10 )
for ( inx : [no_digits1:1] ){
bucket = mset ( meetings ) as { int ( (str($.start))[inx] ?? 0 ) }
meetings = fold( [0:10] ,list() ) as {
continue( $.o !@ bucket )
$.p += bucket[$.o] }
}
meetings // return
}
def is_overlap(meetings){
meetings = radix_sort(meetings)
exists ( [1:size(meetings)] ) where {
meetings[$.o  1].end >= meetings[$.o].start
}
}

NoOne
July 21, 2017 @ChrisK is right, however, we can solve the problem by this too:
Start = [1,3,2,5]
End = [4,5,7, 10]
// there can be multiple in same time
starts = mset( Start )
ends = mset( End )
// sorted set of timings
timings = sset( Start )
timings += End
max = 0 ; cur = 0
for ( inx : timings ){
cur += (inx @ starts ? starts[inx] : 0)
cur = (inx @ ends ? ends[inx] : 0)
max = cur > max ? cur : max
}
println(max)

NoOne
July 19, 2017 Cheating using ZoomBA, avoiding all of recursion... and
movies = { "Shining" : [14, 15, 16],
"kill bill" : [14, 15],
"Pulp fiction": [14, 15] }
args = list ( movies.entries ) as { name = $.key ; list( $.value ) as { [ name, $.o ] } }
movie_size = size(movies)
all_sched = join( @ARGS = args ) where {
items = list ( $.o )
sorta ( items ) where { $.left[1] < $.right[1] }
!exists ( [1:movie_size] ) where { items[$.o][1]  items[$.o1][1] < 1 }
}
println(str(all_sched,'\n'))
And just to showcase that it did find the results, here are the results :
➜ wiki git:(master) ✗ zmb tmp.zm
@[ @[ Shining,16 ],@[ Pulp fiction,14 ],@[ kill bill,15 ] ]
@[ @[ Shining,16 ],@[ Pulp fiction,15 ],@[ kill bill,14 ] ]
➜ wiki git:(master) ✗

NoOne
July 16, 2017 Why make it more complex, this is clean, neat... and works.
def div_wo(a,b){
panic( b == 0 , 'Terrible parameter!')
printf('%d/%d%n', a,b)
sign_change = false
if ( a < 0 ){
sign_change = true
a = a
}
if ( b < 0 ){
sign_change ^= true
b = b
}
res = 0
while ( a >= b ){
res += 1
a = b
}
sign_change ? res : res
}
println( div_wo(0,1) )
println( div_wo(1,1) )
println( div_wo(1,2) )
println( div_wo(2,1) )
println( div_wo(2,1) )
println( div_wo(2,1) )
println( div_wo(2,1) )
println( div_wo(3,2) )

NoOne
July 16, 2017 This is a Directed Acyclic Graph, and the list given here is an adjacency list. Thus, standard BFS or DFS techniques work. There is no guarantee that it would be a tree ( there can be multiple managers to an employee ( what surprise) ). Matters not.
org_map = { 1: [2, 3, 4],
3: [5, 6, 7],
5: [8, 9, 10] }
def find_all_minions( gru ){
// gru before the minions ?
if ( !(gru @ org_map) ){ return [] }
minions = list()
// cool, let gru get's his groove back
despicable_me = list ( org_map[gru] )
while ( !empty(despicable_me) ){
// yes, bob was always faithful
bob = despicable_me.dequeue()
if ( bob @ org_map ){
// enqueue all the lesser minions
despicable_me += org_map[bob]
}
minions += bob // add bob the minions
}
minions // return value
}
printf( '%s > %s %n', 1, find_all_minions( 1 ) )
printf( '%s > %s %n', 2, find_all_minions( 2 ) )
printf( '%s > %s %n', 3, find_all_minions( 3 ) )

NoOne
July 15, 2017 There are cleaner solutions. Suitably change it into Java.
def reverse_vowels_declarative(word){
vowels = set( 'aeiou'.value ) // get into a set
vowels_in_word = select( word.value ) where { $.o @ vowels }
// put back
fold ( word.value , 1 ) as {
continue( !($.o @ vowels) )
word.value[$.i] = vowels_in_word[$.p]
$.p = 1
}
word
}
def reverse_vowels_imperative(word){
vowels = set( 'aeiou'.value ) // get into a set
lp = 0 ; rp = size(word)  1
while ( true ){
while ( lp < rp && !(word[lp] @ vowels) ){ lp += 1 }
while ( lp < rp && !(word[rp] @ vowels) ){ rp = 1 }
break(lp >= rp )
t = word[rp]
word.value[rp] = word[lp]
word.value[lp] = t
lp +=1 ; rp = 1
}
word // done
}
println( reverse_vowels_imperative('vowels') )

NoOne
July 11, 2017 The solution examples are obviously wrong.
Formally, the question can be any of these two :
1. Is a set x, subset of *any* of the sets contains in a list?
2. Is a set x, subset of *all* of the sets contains in a list?
If the question was [1], then "But checking for {1,2} in {1,5,6}, {2,3,1} should return false as {1,5,6} does not contain all elements of {1,2} 2 is missing" is wrong. Obviously.
If the question was [2], then "For example checking for set1 = {1,2} in {1,2,3}, {5,6} should return true" would be wrong.
The other fancy things I can think of are:
[3] Is a set x, subset of union of the sets contains in a list?
That would not work also.
See solutions...
To @ChrisK.
This should clear you out on what precisely ZoomBA is all about :
words = [ [3,2] , [4,3,2] , [4,1,1] , [1, 2] , [1, 1] ]
letters = words.flatten()
ms = mset(letters)
l = list( ms ) > { [$.key,$.value] }
sorta(l) :: { $.left[1] < $.right[1] }
alpha = list ( l ) >{ $.0 }
println(alpha)

NoOne
July 08, 2017 mix = { 'Cust1' : [ 'n3', 'n7', 'n5', 'n2' , 'n9' ],
'Cust2' : [ 'n5' ],
'Cust3' : [ 'n2' , 'n3' ],
'Cust4' : [ 'n4' ],
'Cust5' : [ 'n3' , 'n4' , 'n3' , 'n5' , 'n7' , 'n4' ] }
// what drinks serves who?
serving = fold( mix.keys , dict() ) as {
values = mix[$.o]
for ( v : values ){
if ( v @ $.p ){
$.p[v] += $.o
} else {
$.p[v] = set($.o)
}
}
$.p // return
}
// next, sort by no of customer a drink serves, and union off,
// go with greedy mode. if adding a drink does not increase customer base
// no need to add it.. thus...
l = list ( serving ) as { [ $.key , $.value ] }
sortd(l) where { size($.left[1]) < size($.right[1]) }
drinks = set( l[0][0] )
catered = set( l[0][1] )
n = size(catered)
i = 1
while ( n != size( mix ) ){
catered = l[i][1]
if ( size(catered) > n ){
n = size(catered)
drinks += l[i][0]
}
i += 1
}
println(drinks)
// caution, the problem is bin packing. Greedy is NOT a gurantee.
// en.wikipedia.org/wiki/Bin_packing_problem#Exact_algorithm
// A gurantee is, of course NP Hard.

NoOne
July 02, 2017 I was thinking about it for a long time. This is a classic case of discretisation making itself away into scale variance. What does that mean? Here is how it works out.
Here, I present two ways to solve the same problem [1].
Continuous Algorithm.
1. Make uniform distribution rain falling as in a point between [0,1].
2. Widen the point, to create an interval to [p  0.005, p + 0.005 ] to make the drop fall.
3. This way, we are creating intervals, and they are kept sorted  and then they are merged.
4. Continue till the intervals merged into a some intervals such that the total length is very close
to 1.000.
5. All while count the no of rain drops ( intervals ) fell.
> Observation, there is a clear mode near about 500 to 800.
Discrete Algorithm.
1. Create pixelated buckets with scale number of pixels per rain drop.
2. That makes the length L ( 1 m ) into 100 * scale.
3. Let the rain drop uniformly between [ 0, 99*scale + 1] , and then
4. Once the rain drop falls, in position pos, mark the buckets [pos, pos + scale) filled.
5. Check if all buckets are marked. That, gives you  whole road is wet.
Now, this is where fractal nature of world comes in. This simulation discretised the world, and thus, does not have a fixed mean, with scale, the mean increases.
Here are the codes.
This is for the discrete simulation. It is amazing how simply you can think about it after pixelation.
// This is discrete simulate
def discrete_simulate(){
scale = 10
count = 0
s = set()
max = 100 * scale
span = max  scale + 1
while ( size(s) != max ){
pos = random(span)
for ( [pos:pos + scale ] ){ s+= $ }
count += 1
}
count // return this
}
Here is *real* continuous one. Interestingly, these two distributions of number of rain drops will not match.
def merge2(slice1, slice2 ){
if ( slice1.x2 < slice2.x1  slice2.x2 < slice1.x1 ) {
return null // not overlap
}
if ( slice1.x1 <= slice2.x1 ){
#(min,max) = minmax( slice1.x2 , slice2.x2 )
return { 'x1' : slice1.x1 , 'x2' : max }
} else {
#(min,max) = minmax( slice1.x2 , slice2.x2 )
return { 'x1' : slice2.x1 , 'x2' : max }
}
}
def merge_into( new_slice, sorted_slices ){
if ( empty(sorted_slices) ){
sorted_slices += new_slice
return sorted_slices
}
// from left
i = index ( sorted_slices ) where { new_slice.x1 <= $.o.x2 }
if ( i < 0 ){
sorted_slices += new_slice
return sorted_slices
}
slice = merge2 ( new_slice, sorted_slices[i] )
if ( slice == null ){
sorted_slices.add(i, new_slice )
return sorted_slices
}
sorted_slices[i] = slice
if ( i + 1 < size(sorted_slices) ){
slice = merge2 ( sorted_slices[i], sorted_slices[i+1])
if ( slice != null ){
sorted_slices[i] = slice
sorted_slices.remove(i+1)
}
}
sorted_slices
}
def simulate(){
sorted_slices = list()
tot = 0.0
count = 0
while ( 1.0  tot > 0.0001 ){
pos = random(0.0)
x1 = pos  0.005
x1 = x1 < 0.0 ? 0.0 : x1
x2 = pos + 0.005
x2 = x2 > 1.0 ? 1.0 : x2
slice = { 'x1' : x1, 'x2' : x2 }
sorted_slices = merge_into( slice, sorted_slices )
//println(slice)
//println(sorted_slices)
//thread().sleep(10)
tot = sum( sorted_slices ) as { $.o.x2  $.o.x1 }
count += 1
//printf('>>>>> Count : %d Total %f %n', count, tot)
}
//println( sorted_slices )
return count // well
}
This is a pretty non trivial problem, and I see why PHD folks were asked this. The nature of simulation is, here, getting fractalised.
 NoOne June 27, 2017/* Balance Parentheris */
def is_balanced(string){
!exists([0: size(string)/2 ] ) where {
// when s[index] != s[1index]
string[$.o] != string[1$.o]
}
}
def balance_paren(string){
if ( is_balanced(string) ) { return string }
// now, here... generates a multi set
m = mset(string.value)
left_count = m[_'(']
right_count = m[_')']
#(min,max) = minmax(left_count,right_count)
// extract the bracket less string
s = fold(m.keys,'') as {
continue( $.o == _'('  $.o == _')' )
$.p += ( str($.o) ** m[$.o] )
}
// duplicate bracketness and... creare a balanced string
( '(' ** max ) + s + ( ')' ** max )
}
println( balance_paren(@ARGS[0]) )

NoOne
June 26, 2017 Singleton with respect to what?
1. Virtual Machine level?
2. User Level?
3. OS Level?
4. Network Level?
5. WAN level?
6. .. Internet level?
=====
You can have singleton for all of it, really. Perhaps not [6], enforcing is a huge problem, so may be not [6].

Let's see.
1. Given something is reflective, you can not have true singleton. The only way to achieve singleton in JVM is either use static final classes, or use enums.
2. User level Singleton. Try running two windows media player. Try it. Hmm. You can not. We were taught about this one.
3. OS level  there are plenty examples of singleton process  you can implement that as a class  but... well.
You got the idea.
====
Only one instance exists is not even a pattern, it is a property, and not so much easily implemented.
[ stackoverflow.com/questions/12755539/whyissingletonconsideredanantipattern ]
=========
In short, the singleton pattern makes code more complex, less useful, and a real pain to reuse or test. Eliminating singletons can be tricky, but it’s a worthwhile endeavour.
==========
@Jerm, good point.
====
how this isn't as simple as sorting the array and then returning the (percent * array length)th element in the array? Maybe I'm not understanding the problem correctly.
=====
because, the problem is about getting it done from a stream.
======
Give you an unsorted integer ***iterator***
=====
What is one thing that is certain about iterator? They can be iterated upon. What is not certain about an iterator? That, they will end.
Surprised? Not so. For example, if we create an iterator, that returns you next prime number, where do you think the iterator ends? Well, nowhere.
primes = seq ( 2 ) >{
prime_cache = $.prev
last = prime_cache[1] + 1
// en.wikipedia.org/wiki/Bertrand%27s_postulate
end = last * 2
last + index( [ last : end ] ) :: { !exists ( prime_cache ) :: { $.item /? $.$.item } }
}
That is an iterator, so... how you are going to find the % stuff right at any iteration? You would be out of memory very soon.
In fact, here is an trivial god knows what it would do iterator :
god_knows = seq( random(100) ) > { random(100 ) }
This generates in infinite stream of random numbers between [0,100). Now?
:)
/*
Now, for the health concious, who eats only one item.
Surprize, same code, almost!
*/
_options_ = [ 'breadbutter' , 'pizza' , 'burger' ]
// is the combination valid
def is_valid_combination( item , history ){
if ( empty(history) ) return true
if ( 'pizza' == item && 'pizza' == history[1] ) return false
if ( 'burger' == item ){
if ( 'burger' == history[1] ) return false
if ( size(history) > 1 && 'burger' == history[2] ) return false
}
return true
}
// the recursive definition
def _recurse_(days, history){
if ( size(history) == days ){
printf('%s\n', history )
return
}
for ( c : _options_ ){
if ( is_valid_combination( c, history ) ){
h = list(history)
h.add( c )
_recurse_(days,h)
}
}
}
// call it
def gen_combo( days ){
_recurse_( days,[])
}
gen_combo(3)

NoOne
June 19, 2017 /*
Assuming I can have any items, for breakfast.
That is, I can have breadbutter, as well as Pizza together
I know, I am a foodie.
*/
_options_ = [ 'breadbutter' , 'pizza' , 'burger' ]
_combinations_ = list ( sequences(_options_) ) // yep, neat!
println(_combinations_)
// is the combination valid
def is_valid_combination( items, history ){
if ( empty(history) ) return true
if ( 'pizza' @ items && 'pizza' @ history[1] ) return false
if ( 'burger' @ items ){
if ( 'burger' @ history[1] ) return false
if ( size(history) > 1 && 'burger' @ history[2] ) return false
}
return true
}
// the recursive definition
def _recurse_(days, history){
if ( size(history) == days ){
printf('%s\n', history )
return
}
for ( c : _combinations_ ){
if ( is_valid_combination( c, history ) ){
h = list(history)
h.add( c )
_recurse_(days,h)
}
}
}
// call it
def gen_combo( days ){
_recurse_( days,[])
}
gen_combo(3)

NoOne
June 19, 2017 What you are looking for : [ cs.stackexchange.com/questions/57542/findpthpercentileofastreamofnumbers ]
However, there is a neat other way. If the numbers are within a range ( well, all integers supported by machine naively will be ), then you can have a sorted dictionary with integers as key, and count of the integers as value.
That will compress the data, and any time, you want to calculate a certain %, it can be easily doable ( there is a formula ).
Not exactly proud of it, but:
def BST : {
$$ : def(){
$.root = null
},
add_node : def(v){
new_node = {'v' : v , 'l' : null , 'r' : null }
if ( empty($.root) ){
$.root = new_node
return $.root
}
parent = $.root
current = v < parent.v ? parent.l : parent.r
while ( current != null ){
parent = current
current = v < parent.v ? parent.l : parent.r
}
if ( v < parent.v ){
parent.l = new_node
} else if ( parent.v < v ){
parent.r = new_node
}
},
find_abc : def(key){
current = $.root
path = ''
while ( current != null && current.v != key ){
if ( key < current.v ){
path += '0'
current = current.l
} else if ( current.v < key ){
path += '1'
current = current.r
}
}
(!empty(current) && current.v == key)? path : 'Not Found'
}
}
//now play
bst = new ( BST )
values = [5,2,8,3,6,9,1]
// add nodes
for ( v : values ){ bst.add_node(v) }
keys = [6, 1, 10, 2]
// print ABC ...
for ( v : keys ){ printf( '%s > %s%n', v, bst.find_abc(v) ) }

NoOne
June 17, 2017 Here you go. The algorithm is pretty neat, but recursive. I don't like the recursion, but  it should work well.
/*
Should be pretty neat,
Taking a number and making it word by word
Using recursion, next step  removing that
*/
_names_ = [[1,'one'], [2,'two' ], [3,'three'],[ 4 , 'four' ] , [5,'five'] ,
[6,'six'], [7,'seven' ], [8,'eight'],[ 9 , 'nine' ] , [10,'ten'],
[11,'eleven'], [12,'twelve' ], [13,'thirteen'],[ 14 , 'fourteen' ] , [15,'fifteen'],
[16,'sixteen'], [17,'seventeen' ], [18,'eighteen'],[ 19 , 'nineteen' ] ,
[20,'twenty'], [30,'thirty'], [40,'forty'], [50,'fifty'], [60,'sixty'], [70,'seventy'],
[80,'eighty'], [90,'ninety'], [100,'hundred'] , [1000, 'thousand' ] ,
[ 1000000 , 'million' ], [1000000000, 'billion' ] , [1000000000000 , 'trillion' ] ]
_keys_ = dict( _names_ )
def in_words( n ){
if ( n == 0 ) return 'zero'
// try to find the index of the item from the right side
// which has the property that division by that item > 0
i = rindex( _names_ ) :: { (n / $.0 ) > 0 }
// i would have the index , get result and reminder
res = (n / _names_[i][0] )
rem = (n % _names_[i][0] )
// recursion, string rep of result is given by ...
s_res = ( res @ _keys_ ) ? ( (res != 1  n >=100 ) ? _keys_[res] : '' ) : in_words(res)
// recursion, string rep of the reminder is given by ...
s_rem = ( rem @ _keys_ ) ? _keys_[rem] : (rem != 0 ? in_words(rem) : '' )
// finally merge them, and we have our answer  careful not to merge empty strings
s_res + (empty(s_res)?'' : ' ') + _names_[i][1] + (empty(s_rem)?'' : ' ') + s_rem
}
println( in_words(0) )
println( in_words(10) )
println( in_words(1012) )
println( in_words(983) )
println( in_words(87891729817981987) )
println( in_words(4312112121121) )
The results of course are:
zero
ten
one thousand twelve
nine hundred eighty three
eighty seven thousand eight hundred ninety one trillion seven hundred twenty nine billion eight hundred seventeen million nine hundred eigh
ty one thousand nine hundred eighty seven
four trillion three hundred twelve billion one hundred twelve million one hundred twenty one thousand one hundred twenty one

NoOne
June 12, 2017 Based on @ChrisK s comment, I have heavily commented the code. @ChrisK, start using ZoomBA. :)
/* Make times calls to print stats on a static url
Making it heavily documented so that ChrisK
can read ZoomBA. It is trivial, once you master
what > , :: , $ are.
> is "as" that is a mapper function
:: is "where" that is a predicate, a condition
$ is the iteration variable, holding
$.o > object of iteration , the item
$.i > the index of the current iteration
$.c > the context, the iterable on which iteration is happening
$.p > partial, the result of the iteration, as of now
*/
def analyze ( url, times=10) {
percentiles = [ 0.99, 0.95, 0.9 , 0.5, 0.1 ]
// an inner function
def timing( url ){
// gets the pair, timing in sec, output of the call
// using clock statetement
// which has the read function to readf from the url
#(t,o) = #clock { read ( url ) }
t // return value are implicit like scala, no point saying return
// side effect, there is really no truly void function in ZoomBA
}
def parallelize( url , times ){
// create a list of *times* threads
// each thread has a body of function call timing()
// zoomba threads have a field :value, which stores the thread functions return value
// this is massive improvement from Java, see similar code and the pain below
threads = list([0:times] ) > { thread() > { timing( url ) } }
// polls num tries, pollinterval, until condition is true
// returns true if condition was true, else returns false
// :: (such that) is a short form of where clase in zoomba
// the code waits till no alive thread
// shorthand of java function isXxx() > xxx in zoomba
// making it way more succint
// could easily be done using a .join() but, why care?
poll(300,50) :: { !exists( threads ) :: { $.o.alive } }
// extracting the return value of the threads into another list
// > is the 'as' symbol
// it reads create a list from ( threads ) as ( mapping ) thread.value as the item
// $ is the iteration construct, more like *this* for a loop.
// $.o stores the iteration object for the loop, this this case, a thread object
list( threads ) > { $.o.value }
}
def stats( data ){
// sum
mean = sum(data) / size(data)
// sum over item  mean whole squared, right?
variance = sum( data ) > { ($.o  mean) ** 2 }
sd = variance ** 0.5
printf( 'mean: %s\n', mean )
printf( 'sd: %s\n', sd )
// now percentile calculations
// sorta > sort ascending the data values
sorta(data)
// another iteration  for() would be same
fold ( percentiles ) >{
printf( '%.2fp: %s\n', $.o , data[floor( size(data) * $.o )] )
}
}
println('url > ' + url )
println('num of times > ' + times )
println('All in secconds.')
data = parallelize( url, times )
stats(data)
}

NoOne
June 12, 2017 (zoomba)m = { 1 : [ 'a' , 'x' ] , 2 : ['b','y'] }
{1=@[ a,x ], 2=@[ b,y ]} // ZMap
(zoomba)join( @ARGS = list( '12'.value ) > { m[int($.o)]} ) >{str($.o,'') }
[ ab,ay,xb,xy ] // ZList
Hmm. Not that hard. Probably a standard recursive solution would help here, to make it harder and *interview* class:
/* standard recursion */
map = { 1 : [ 'a' , 'x' ] , 2 : ['b','y'] }
def _recurse(string, options, tmp='') {
if ( empty(string) ){ options+= tmp ; return }
head = string[0]
tail = string[1:1]
for ( o : map[ int(head) ] ){
_recurse( tail, options, tmp + o )
}
}
def mapper( string ){
options = list()
_recurse(string,options)
options // return
}
println( mapper('12') )

NoOne
June 11, 2017 This can be broken down to two parts.
1. Get a frequency count for every unique number. This is unavoidable step.
====
2. Now, those buckets can be sorted in decreasing order of frequency, and then top n can be selected. But that requires sorting those many buckets, one per unique no.
===
2. Now, those buckets can be safely inserted inside a heap with size n.
Your problem is solved.
=====
Given the total no of unique elements are less than 100, I would suggest sorting is a better solution. As the frequency will be integer, radix sort is in fact a faster solution.
[ geeksforgeeks.org/radixsort/ ]
So, generic pet answer of *heap* might not be actually a good idea. But then... your call.
You are precisely looking at this:
[ stackoverflow.com/questions/10657503/findrunningmedianfromastreamofintegers ]
It has a nice name :
[ en.wikipedia.org/wiki/Reservoir_sampling ]
[ reddit.com/r/algorithms/comments/2ca33v/is_there_an_algorithm_to_find_the_median_of_a/ ]
There are many ways to solve it, depends on how large is the phone book.
Assuming it is not more than N= 10,000 entries ( I mean, seriously ? ) and none of the entries are more than m= 30 character long on the average  we can have an exact (mN) algorithm.
====
1. split input words into characters
2. generate a regex like ^(c.*)+$
3. Match this regex against all entries > matches are the result.
Example:
J => ^J.*$
JD => ^J.*D.*$
====
Another way of doing it ( slightly optimally ) is imagining a prefix tree structure.
There, the problem is find all where ( same from previous ) in xpath language :
====
1. split input words into characters
2. generate an xpath like //c/*/c/*/
3. Find all that matches that.
====
They are equivalent approaches, however, once you reach a subtree, the second approach drastically reduces the no of nodes one needs to look for, it is much better than [1].
However, for an interview and practicality perspective:
/* search words */
_words_ = [ "John", "JohnDavis", "Ted", "JackMay" ]
// the mumbo jumbo
def search( word ){
// we have a bug here, what about $.o is a regex?
// we need to escape that, but...well...
regex = "^" + str(word.value, '') as { str($.o) + ".*" } + "$"
println(regex)
select ( _words_ ) where { $.o =~ regex }
}
// now take for a spin
println( search( 'J' ) )
println( search( 'JD' ) )
The result is not so bad:
➜ zoomba99 git:(master) ✗ zmb tmp.zm
^J.*$
[ John,JohnDavis,JackMay ]
^J.*D.*$
[ JohnDavis ]
➜ zoomba99 git:(master) ✗

NoOne
June 11, 2017 Here is something in Java.
package com.zeroturnaround.callspy;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*/
public class CareerCup {
static class IThread implements Runnable{
static double timing(String url) {
try {
URL myUrl = new URL(url);
long l = System.currentTimeMillis();
BufferedReader in = new BufferedReader(
new InputStreamReader(myUrl.openStream()));
while ((in.readLine()) != null);
in.close();
double spentMS = System.currentTimeMillis()  l;
return spentMS/1000;
}catch (Throwable t){
return Double.MAX_VALUE ;
}
}
static List<IThread> makePool(int times, String url){
List<IThread> pool = new ArrayList<>(times);
for ( int i = 0 ; i < times; i++ ){
IThread it = new IThread(url);
Thread t = new Thread( it);
pool.add(it);
t.start();
}
return pool;
}
double timing;
final String url;
Thread myThread;
IThread(String url){
this.url = url;
timing = Double.MAX_VALUE ;
}
@Override
public void run() {
this.myThread = Thread.currentThread();
timing = timing(url);
}
}
public static void analyze(int times, String url){
List<IThread> pool = IThread.makePool(times,url);
// wait for all to complete execution :: poll()
while ( true ){
boolean oneAlive = false ;
for ( IThread t : pool ){
oneAlive = t.myThread.isAlive();
}
if ( !oneAlive ){ break; }
}
List<Double> data = new ArrayList<>();
for ( IThread t : pool ){
data.add(t.timing);
}
// now we have the data, do mean, sd, what not...
Collections.sort(data);
int _90 = (int)Math.floor(times * 0.9);
System.out.printf("90p is : %f", data.get(_90 ) );
}
public static void main(String[] args){
analyze(20, "give your url here" );
}
}
Please get over Java. It shows you how lame as a language it really is.
 NoOne June 10, 2017/*
Prime factors
Automatic finding of primes and then factors.
So, here, we go.
*/
def prime_factors_str( n ){
// basic stuff
upto = ceil( n ** 0.5 )
// should be pretty easily understandable
#(primes, factors) = fold( [2:upto], [ list(), list() ] ) > {
// is my current no prime ?
pp = $.o // possible prime
#(primes,factors) = $.p
continue ( exists( primes ) :: { $.o /? pp } )
// now it is prime
primes += pp
// now, is it a factor ?
while ( pp /? n ){ n /= pp ; factors += pp }
$.p // return
}
// print factors
str ( factors , '*' )
}
println( prime_factors_str(90) )

NoOne
June 09, 2017 Caching will definitely help. Here is how to do it in ZoomBA:
removed_9 = seq ( 0 ) >{
next = $.p[1] + 1
while ( '9' @ str(next) ){ next += 1 }
next //return
}
def newNumber(inx){
if ( inx <= 0 ) return ''
while ( inx >= size ( removed_9.history ) ){
removed_9.next
}
removed_9.history[inx]
}
println( newNumber(1) )
println( newNumber(8) )
println( newNumber(9) )
println( removed_9.history )
The result:
➜ zoomba99 git:(master) ✗ zmb tmp.zm
1
8
10
[ 0,1,2,3,4,5,6,7,8,10 ]
➜ zoomba99 git:(master) ✗

NoOne
June 09, 2017 Here is the basic idea. Yes, you can optimize, but... well.. that would mean amazingly bad  undebuggable code.
// create a name lookup table
_names_ = { 'zero' : 0 , 'one' : 1 , 'two' : 2 ,
'three' : 3 , 'four' : 4 , 'five' : 5 ,
'six' : 6 ,'seven' : 7 ,'eight' : 8 ,
'nine' : 9 }
// a regex like zeroninesixfouroneseventwothreefiveeight
_int_pattern_ = str( _names_.keys , '' ) > { $.o }
// regex (minus)?(zeroninesixfouroneseventwothreefiveeight)+
_base_pattern_ = '(minus)?(' + _int_pattern_ +')+'
// convert the word into integer
def convert_int( word ){
sign_num = 1
// if the word starts with minus then
if ( word #^ 'minus' ){
sign_num = 1 // change sign
word = word[5:1] // substring
}
// extracts digits by simple mapper  when a word match a digit
digits = tokens( word , _int_pattern_ ) > { _names_[$.o] }
// convert the digits into integer and multiply by sign
int( str(digits,'') ) * sign_num
}
// the actual function
def count_nums_as_words_in_string( string ){
// sum of generated integers out of matched tokens
sum( tokens( string, _base_pattern_ ) > { convert_int($.o) })
}
input = "xyzonexyztwothreeeabrminusseven"
println( count_nums_as_words_in_string( input ) )

NoOne
June 07, 2017 In case you do not want to use the literal 'b', but assume any key, there is still a way:
(zoomba)x = [{'b':2},{'b':1},{'b':5},{'b':4}]
@[ {b=2},{b=1},{b=5},{b=4} ] // ZArray
(zoomba)sorta(x) :: { $.l.entrySet().iterator.next.value < $.r.entrySet().iterator.next.value }
true // Boolean
(zoomba)x
@[ {b=1},{b=2},{b=4},{b=5} ] // ZArray
(zoomba)

NoOne
June 02, 2017 More interestingly, here is a very simple approach that solves the problem.
[stackoverflow.com/questions/4137481/detectingthesinkinadirectedacyclicgraph]
====
As there are no cycles in the graph, and all vertex connect with the sink, just select any starting node and start walking randomly. When you can't continue walking, you are at the sink, in at most n steps.
======
In Java, you want to use a :
[ docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html ]
to maintain objects as keys and their count as values And you are good.
====
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doublylinked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertionorder). Note that insertion order is not affected if a key is reinserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
=====
def find_max_repeated_elem(a){
m = mset(a)
#(min,max) = minmax(m){ $.l.value < $.r.value }
max.value
}
def find_max_repeated_elem_sorted(a){
p = { 'item': a[0] , 'count' : 0, 'max' : 0 }
p = fold ( a , p ) > {
if( $.o == $.p.item ){
$.p.count += 1
} else {
if ( $.p.count > $.p.max ){
$.p.max = $.p.count
}
$.p.count = 1
$.p.item = $.o
}
$.p // return
}
p.item
}

NoOne
May 29, 2017 Could not resist a much cleaner  always controlled expansion on the area.
/* Starting point is (0,0).
Given the new point (x,y) is not already visited,
add 1 to the area. Else fallback.
Bonus should be, print the Area properly */
def Robot : {
$$ : def(max=100){
$.max_area = max
$.cur_area = 1
},
move : def ( dir ){
/*
spread of the area can be controlled by a global variable */
$.cur_area += 1
$.cur_area < $.max_area && random(true)
}
}
robot = new ( Robot )
// The function, with recursion removal
def find_area(){
// positions: x#y > visited
positions = dict()
positions['0#0'] = false
while ( true ){
not_traversed = find ( positions ) :: { !$.value }
break ( not_traversed.nil ) // not found such position
#(sx,sy) = not_traversed.value.key.split('#')
positions[not_traversed.value.key] = true // traversed it
x = int(sx) ; y = int(sy)
printf('%d,%d\n',x,y)
if ( robot.move( 0 ) ){ positions[str('%d#%d', x,y+1)] = false }
if ( robot.move( 1 ) ){ positions[str('%d#%d', x,y1)] = false }
if ( robot.move( 2 ) ){ positions[str('%d#%d', x+1,y)] = false }
if ( robot.move( 3 ) ){ positions[str('%d#%d', x1,y)] = false }
}
println( positions.keys )
size(positions)
}
// every time, different results
a = find_area()
println( 'Area is :' + a)

NoOne
May 27, 2017 Open Chat in New Window
@ChrisK:
approach 2:
===
approach 1 is fine, it works, but the HT will eventually grow large, consuming a lot of memory, whereas we actually only need the messages from unique user_ids from the last second, which I assume, is considerably less than the set of users over a longer period (mustn't be, but for most system it's a good assumption).
===
You were there, but then the question is why don't you expire the hashtable entries? :)
That is, of course another cleaner, meaner alternative approach.
Now the algorithm looks like:
 NoOne July 26, 2017