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
// ZoomBA : non optimal Theta(n^2)
arr = [ -1, 0 , 1, 0 , 2, - 2 , 3 , 10 ]
r = [0:#|arr|]
pairs = join( r, r ) :: {
continue ( $.o.0 >= $.o.1 )
arr[$.o.0] + arr[$.o.1] == 0
} -> { [ arr[$.o.0] , arr[$.o.1] ] }
println( pairs )
// ZoomBA : optimal Theta(n) with Theta(n) space
#(s,l) = lfold( arr , [ set() , list() ] ) ->{
s = $.p.0 ; l = $.p.1
if ( -$.o @ s ){ l.add ( [ $.o, -$.o ] ) ; continue }
s += $.o
$.p = [ s, l ]
}
println(l)
/*
Showcasing ZoomBA iterator proto-object types
Try beating this one on elegance and aesthetics
*/
def Iter : { obj : null , times : 0 ,
$next : def(){
break ( $.times <= 0 )
$.times -= 1
$.obj
}
}
my_iter = new ( Iter , obj = 'ZoomBA' , times = 5 )
for ( my_iter ){
println( $ )
}
/*
en.wikipedia.org/wiki/Arithmetic_progression
x = na + n*( n - 1 )/2
examples :
x = 6
a = 1 , n = 3
6 = 1*3 + 3*(3-1)(3-2)/2
x = 10
a = 1, n = 4
10 = 1 * 4 + (4 -1)(4)/2
Thus in ZoomBA :: We have this identity
*/
def find_ap( x ){
upto = ciel ( x ** 0.5 )
solved = join ( [1 : upto + 1 ] , [ 2 : upto + 1 ] ) :: {
a = $.o.0 ; n = $.o.1
break ( n * ( a + ( n - 1 )/ 2.0 ) == x ) {
printf ( 'a :%d, n: %d\n', a , n )
[ a , n ]
}
}
if ( empty(solved) ){ println('Impossible' ) }
}
find_ap( 10 )
// ZoomBA :: reverse consecutive +ve no within -ve :: better style
def reverse_between_indices( arr , i, j){
len = ( j - i + 1 )/2
lfold( [i : i + len ] ) ->{
l = arr[$.o]
arr[$.o] = arr[ j - $.i ]
arr[ j - $.i ] = l
}
}
def reverse_pos( arr ){
end = 0
while ( true ){
previous = index ( [end:#|arr|] ) :: { arr[$.o] >= 0 }
break ( previous < 0 )
previous += end
end = index ( [previous:#|arr|] ) :: { arr[$.o] < 0 }
break ( end < 0 )
end += previous
reverse_between_indices ( arr, previous, end - 1 )
}
if ( previous >= 0 ){
reverse_between_indices ( arr, previous, #|arr| - 1 )
}
}
arr = [4, 3, 8, 9, -2, 6, 10, 13, -1, 2, 3]
println( arr )
reverse_pos( arr )
println( arr )
// ZoomBA :: reverse consecutive +ve no within -ve
def reverse_between_indices( arr , i, j){
len = ( j - i + 1 )/2
lfold( [i : i + len ] ) ->{
l = arr[$.o]
arr[$.o] = arr[ j - $.i ]
arr[ j - $.i ] = l
}
}
def reverse_pos( arr ){
previous = 0
in_ve = false
for( [0:#|arr|] ) {
continue ( !in_ve && arr[$] < 0 ){
in_ve = true
reverse_between_indices( arr, previous, $ - 1)
previous = #|arr| - 1 // set to last
}
continue ( in_ve && arr[$] >= 0 ){
previous = $
in_ve = false
}
}
reverse_between_indices( arr, previous, #|arr| -1 )
}
arr = [4, 3, 8, 9, -2, 6, 10, 13, -1, 2, 3]
reverse_pos ( arr )
println( arr )
// ZoomBA :: Simple but non-optimal way to solve it
def find_nearest ( arr , i ){
li = index ( [0:i] ) :: { arr[ $.o ] > arr[i] }
ri = rindex ( [i+1: #|arr|] ) :: { arr[ $.o ] > arr[i] }
if ( li == -1 && ri == -1 ) return -1
if ( li == -1 ) return ri
return li
}
lfold ( arr ){
printf ('%d -> %d\n', $.i, find_nearest(arr, $.i))
}
// ZoomBA : Using Anonymous answer - fixing bugs
node = { 'value' : 0 , 'children' = list() }
def dse(node, current_sum , target_sum) {
current_sum += node.value;
if ( empty( node.children ) ) {
// only when the leaf
return current_sum == target_sum
}
for ( child : node.children) {
if ( dse(child, current_sum , target_sum) ) {
return true; // no need to pursue other paths
}
}
return false
}
//ZoomBA : Imperative Style , almost
def part_word( word , dictionary ){
len = #|word|
for ( n : [ 0 : 2 ** ( len-1) ] ){
bm = str(n,2)
bm = '0' ** ( len - #|bm| -1 ) + bm
println( bm )
last = len - 1
start = 0
splits = list()
for ( i = len-2 ; i >=0 ; i -= 1){
if ( bm[i] == '1' ){
splits += word [ i + 1: last ]
last = i
}
}
splits += word[ start : last ]
println ( splits )
successful = !exists(splits) :: { ! ( $.o @ dictionary ) }
if ( successful ) return true
}
return false
}
// ZoomBA
emp_list = [ "Mc Grill,Mc,Grill,Karmon",
"Karmon,Zech,Karmon,Joe","Mithun,Try,Mithun,Joe",
"Joe,Top,Joe,","Zara,Aman,Zara,Mc Grill",
"Fizzy,Dude,Fizzy,Mc Grill" ]
def create_node( string ){
fields = string.split( ',' ,-1)
{ 'id' : fields[0] , 'fname' : fields[1] ,
'lname' : fields[2] , 'mgr' : fields[3] , 'children' : set() }
}
def print_node( node_id ){
node = nodes[node_id]
printf( '%s %s\n', node.fname, node.lname )
for ( node.children ){
print_node ($)
}
}
nodes = dict ( emp_list ) -> {
e = create_node( $.o )
[ e.id , e ]
}
root = lfold(nodes, '' ) ->{
node = $.o.value
continue ( empty(node.mgr) ){ $.p = node.id }
parent = nodes[node.mgr]
parent.children += node.id
$.p
}
print_node( root )
// ZoomBA : Showcasing the recursion. Minimal, and effective.
def traverse(path, destination){
current = (path.split("#"))[-1]
if ( current == destination ){
println ( path.replace('#', '->') )
return
}
#(l,r) = current.split(':')
#(L,R) = destination.split(':')
if ( int(l) > int(L) || int(r) > int(R) ){ return }
// notice conformance : left casting of integer from string
traverse ( str('%s#%s:%s' , path , l , 1 + r ) , destination )
traverse ( str('%s#%s:%s' , path , 1 + l , r ) , destination )
}
traverse ( '0:0' , '2:2' )
// ZoomBA : Not optimal this. But shows the power of expression
words = ["ABCW", "BAZ", "FOO", "BAR", "XTFN", "ABCDEF" ]
max_tuple = [ num("-inf") , null, null ]
r = [ 0 : #|words| ]
join( r , r ) :: {
continue ( $.o.0 >= $.o.1 )
left = words[ $.o.0 ] ; right = words[ $.o.1 ]
continue ( !empty( left.value & right.value ) )
val = #|left| * #|right|
continue ( max_tuple.0 >= val )
max_tuple.0 = val ; max_tuple.1 = left ; max_tuple.2 = right
false
}
println( max_tuple )
No need to code. We know the nearest star is the sun.
We also know the next nearest star system is : en.wikipedia.org/wiki/Alpha_Centauri.
However, given an arbitrary point in space, and arbitrary other points, min should do the trick :
// ZoomBA
#(min,max) = minmax(stars) :: {
$.o.0.distance_from_earth < $.o.1.distance_from_earth
}
println( min )
// ZoomBA, showcasing iterator object creation.
// This is infinite iterator.
def FibGen :{ previous : [ 0, 1] ,
$next : def(){
cur = $.previous[0] + $.previous[1]
$.previous[0] = $.previous[1]
$.previous[1] = cur
}
}
fg = new ( FibGen )
n = 6
count = lfold ( fg, 2 ) -> { break( $.o >= n ) ; $.p += 1 }
println( count )
login_info = { 'tries' : 0 , 'last_successful' : time() }
def is_account_hacked( user_name , max_tries ){
login_info = LOGIN_INFO[ user_name ]
#atomic {
success = login( user_name )
current = time()
if ( success ){
login_info.last_successful = current
login_info.tries = 0
return false
}
login_info.tries += 1
return ( current - login_info.last_successful <= 36000000 &&
login_info.tries >= n )
}
}
// ZoomBA
config = { '(' : 0 , '{' : 0 , '[' : 0 }
match = { ')' : '(' , '}' : '{' , ']' : '[' }
lfold( string.value ) -> {
c = str($.o)
continue ( c @ config ){ config[c] += 1 }
continue ( !(c @ match) )
config[ match[c] ] -= 1
break ( config[ match[c] ] < 0 )
}
!exists ( config ) :: { $.o.value != 0 }
// ZoomBA
s = "test"
l = s.value
r = [0:#|l|]
permutations = set()
join( @ARGS = list(r) as { l } ) where {
continue ( #|set($.o)| != #|l| ) // mismatch and ignore
v = str($.o,'') as { l[$.o] }
continue ( v @ permutations ) // if it already occurred
permutations += v // add them there
false // do not add
}
println( permutations )
//ZoomBA : Imperative Style , almost
def part_word( word , dictionary ){
len = #|word|
for ( n : [ 0 : 2 ** ( len-1) ] ){
bm = str(n,2)
bm = '0' ** ( len - #|bm| -1 ) + bm
println( bm )
last = len - 1
start = 0
splits = list()
for ( i = len-2 ; i >=0 ; i -= 1){
if ( bm[i] == '1' ){
splits += word [ i + 1: last ]
last = i
}
}
splits += word[ start : last ]
println ( splits )
successful = !exists(splits) :: { ! ( $.o @ dictionary ) }
if ( successful ) return true
}
return false
}
// ZoomBA
wl = list( numbers ) ->{
n = $.o
w = 0 // a /? b => a divides b ? boolean
w += (((sr = n ** 0.5) == int(sr) ) ? 5 : 0 )
w += ((( 4 /? n ) && ( 6 /? n ) ) ? 4 : 0 )
w += ((2 /? n) ? 3 : 0 )
[n,w]
}
sorta( wl ) :: { $.o.0.1 < $.o.1.1 }
for ( wl ){ printf ( '<%d,%d>' , $.0, $.1 ) }
println()
bin_tree_node = { 'value' : value , 'left' : l , 'right' : r }
all_nodes = list()
def serialize ( node ){
if ( node == null ) return
all_nodes += node
serialize ( node.left )
serialize ( node.right )
}
// to a list
serialize ( root )
// now randomize
shuffle( all_nodes )
// now randomize
def randomize ( node ){
if ( !empty(all_nodes) ){
node.left = all_nodes.remove(0)
}else{
node.left = null;
}
if ( !empty(all_nodes) ){
node.right = all_nodes.remove(0)
}else{
node.right = null;
}
randomize ( node.left )
randomize ( node.right )
}
root = all_nodes.remove(0)
randomize(root)
// ZoomBA
def get_hotels( scores_file, avg_score ){
scores = json ( scores_file , true )
listing = mset ( scores ) -> { $.o.hotel_id }
avg_listing = dict ( listing ) -> {
key = $.o.key
items = $.o.value
total = sum ( items ) -> { $.o.score }
[ key, total / float( #|items| ) ] // do average
}
selected_hotels = select ( avg_listing ) :: {
$.o.value >= avg_score } -> { $.o.key }
}
// ZoomBA
def block_user( user_id ) {
user_session = session[ user_id ]
if ( size ( user_session.requests ) < 10 ) return false
last_10 = user_session.requests[-10:-1] // splice the last 10 requests
// ZoomBA time subtraction gives millisecs
return ( last_10[-1].call_time - last_10[0].call_time < 300000 )
}
// ZoomBA
//gitlab.com/non.est.sacra/zoomba/wikis/09-samples#book-meeting-room
// find meeting rooms
def find_meetin_rooms( start_time, end_time ){
possible_rooms = dict( rooms ) :: {
room = $.o
continue ( empty(room.schedules) ) { [ room.name , 0 ] }
continue( end_time <= room.schedules[0][0] ){ [ room.name , 1 ] }
// only when more than 1 at least
sorta(room.schedules) :: { $.o.0 < $.o.1 }
pos = index ( [1: #|room.schedules|] ) :: { cur_inx = $.o
room.schedules[cur_inx-1].1 <= start_time && end_time <= room.schedules[cur_inx].0
}
continue ( pos < 0 )
[ room.name , pos ]
}
}
//ZoomBA : gitlab.com/non.est.sacra/zoomba/wikis/09-samples#permutation-of-a-list-containing-repeated-items
l = string.toCharArray()
r = [0:#|l|]
permutations = set()
join( @ARGS = list(r) as { l } ) where {
continue ( #|set($.o)| != #|l| ) // mismatch and ignore
v = str($.o,'') as { l[$.o] }
continue ( v @ permutations ) // if it already occurred
continue ( exists( [0 : #|v|/2 ] ) :: { v[$.o] != v[-1 - $.o] } )
permutations += v // add them there
false // do not add
}
- NoOne October 08, 2016