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 SDE3 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 SDE3 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/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  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
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  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/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  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 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  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
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 A naive recursionless code is possible:
/*
A nice trick to find permutations is use integers with base b.
Suppose there is a string of length b, with all unique characters.
Now, that means, the string can be represented as a base b integer.
Permutaions, of the string can be now found by incrementing the number,
such that all digits are unique.
Now a demonstration:
abc : 3 chars.
3 digit number, and base 3.
The digits are: a:0, b:1, c:2
012 021 102 120 201 210
> map_back to >
abc acb bac bca cab cba
and we are done.
This can be easily implemented:
*/
def map_back(encoded, string){
str( encoded.value ,'' ) > { string[int($.o)] }
}
def permutations( string ) {
// imagine all chars are unique, else there will be repeatation
b = size(string)
// start with min.
min_str = '0' + str( [1:b] , '' ) > { str($.o,b) }
max_str = min_str ** 1
min = int(min_str,b,0)
max = int(max_str,b,0)
perms = list()
perms += map_back(min_str,string)
for ( x : [ min + 1 : max ] ){
str_x = str(x,b)
if ( size(str_x) < b ){ str_x = '0' + str_x }
if ( size( set(str_x.value) ) == b ){
// all different  map it
perms += map_back(str_x,string)
}
}
perms += map_back(max_str,string)
}
p = permutations( "abc" )
println(p)

NoOne
May 26, 2017 /*
Essentially  generate a datetime range,
with spacing of 1 sec, each,
and then check if the string rep has 2 or less unique chars.
That is how one does a fully declarative coding.
Observe : en.wikipedia.org/wiki/ISO_8601
*/
def compute_interesting_times( s1, s2 ){
input_time_format = 'HH:mm:ss'
time_range = [ time(s1,input_time_format) : time(s2,input_time_format) + 'PT1S' : 'PT1S' ]
output_time_format = 'HHmmss'
x = select( time_range ) where {
s = str($.o, output_time_format)
size(set(s.value)) <= 2
}
size(x)
}
println( compute_interesting_times("15:15:00", "15:15:12") )
println( compute_interesting_times("22:22:21", "22:22:23") )

NoOne
May 24, 2017 There are many ways to do it, here is one.
/*
The regex is :
n2 = (\d)?x(\d)?y...(\d)?
under string_n1 = string_n2 + 1
*/
def get_number( sum_value ){
list ( [ 1: sum_value /2 + 1 ] ) > {
n2 = $.o
n1 = sum_value  n2
// when the digits are not one up
s_n1 = str(n1)
s_n2 = str(n2)
continue ( size(s_n2) + 1 != size(s_n1) )
decorated_n2 = fold( s_n2.value , '(\d)?' ) > { $.p + $.o + '(\d)?' }
continue( s_n1 !~ str(decorated_n2) )
[ n1, n2 ]
}
}
ns = get_number ( int(@ARGS[0]) )
println(ns)

NoOne
May 22, 2017 /*
Showing Idiomatic ZoomBA
*/
input = [4,2,8,5,20,1,40,13,23]
#(m,M) = minmax(input)
fib = seq ( 0, 1 ) > { $.item[1] + $.item[2 ] }
while ( fib.next <= M );
result = input & fib.history
println(result)
Now the result:
➜ wiki git:(master) ✗ zmb tmp.zm
[ 1,2,5,8,13 ]
➜ wiki git:(master) ✗

NoOne
May 20, 2017 mapping = { "p" : [ "$", "P" ],
"a" : [ "A" ],
"s" : [ "/" ,"S" , "&" ] }
def solutions(word, mapping){
arg = list( word.value ) > { mapping[str($.o)] }
join(@ARGS=arg) > { str($.o,'') }
}
println( solutions('pass', mapping) )
and the result:
careercup git:(master) ✗ zmb tmp.zm
[ $A//,$A/S,$A/&,$AS/,$ASS,$AS&,$A&/,$A&S,$A&&,PA//,PA/S,PA/&,PAS/,PASS,PAS&,PA&/,PA&S,PA&& ]
➜ careercup git:(master) ✗

NoOne
May 18, 2017 /*
What you want is cardinal product
Given a string is c_0,c_1,c_2, ....
We need a cardinal product of
[lower(c_0),upper(c_0)] X [lower(c_1),upper(c_1)] X ...
*/
word = 'ab'
// generate the options
args = list( word.value ) as { [ str($.o).toLowerCase(), str($.o).toUpperCase() ] }
// use the options for join  and map the tuple into a word by using str with seperator ''
result = join( @ARGS = args ) as { str($.o,'') }
println(result)

NoOne
May 15, 2017 @Flash < Try finding anagrams of "speedstar". You would find that there will be too many repetitions. Consider adding them to a set. In ZoomBA, this is what we do.
def anagrams( word ){
indices = [0:size(word)].asList()
// permutate the indices
// use the index to map to a word ( a tuple is index tuple )
// collect into a set
from ( perm( indices ) , set() ) as { str($.o,'') as { word[$.o] } }
}
println( anagrams('test') )
Also note that, for a practical point of view, you can not use recursion. The depth would become too high, better to use next_higher_permutation, which is implicit in ZoomBA.
 NoOne May 15, 2017Guys, use heap.
[ en.wikipedia.org/wiki/Heap_(data_structure) ]
You should be good to go. Get a kheap, distance metric is Euclidean, I guess everyone knows that  and you should be good.
The code is so so trivial.
In Java, use a [ docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html ]
This is how you do it  in a fully declarative paradigm.
__mapping__ = {
1 : [ 'A', 'B', 'C' ], 2 : [ 'D', 'E', 'F' ],
3 : [ 'G', 'H', 'I' ], 4 : [ 'J', 'K', 'L' ],
5 : [ 'M', 'N', 'O' ], 6 : [ 'P', 'Q', 'R' ],
7 : [ 'S', 'T', 'U' ], 8 : [ 'V', 'W', 'X' ],
9 : ['Y', 'Z'] }
def map_back(n){
args = list( str(n).value ) as { __mapping__[int($.o)] }
join(@ARGS = args ) where { true } as { str($.o,'') }
}
println(map_back(12))
The result:
zmb tmp.zm
[ AD,AE,AF,BD,BE,BF,CD,CE,CF ]

NoOne
May 10, 2017 /*
Imagine the problem as finding all integers with
n 1s and m 0 s such that in the binary representation
There is no '*11*'. And we are good. So....
*/
def do_garbled(m,n){
range = [0 : 2 ** ( m + n )]
count = 0
for ( x : range ){
s = str(x,2)
s = '0' ** (size(s)  m  n) + s
continue ( n != sum(s.value) > { _'1' == $.o ? 1 : 0 } )
continue ( s =~ '.*11.*')
count += 1
}
}
// now in full ZoomBA mode, we can write this:
m = 2
n = 2
res = from ( [0 : 2 ** ( m + n )] , set() ) as {
s = str($.o,2)
s = '0' ** (size(s)  m  n) + s
} where {
n == sum($.o.value ) as { _'1' == $.o ? 1 : 0 } } where {
$.o !~ '.*11.*'
}
println ( res )
println ( size(res) )

NoOne
April 29, 2017 I abhor code so.. what these guys said, they are going to get exactly that:
/*
4 digit Even.
That gives :
A  B  C  D = [0 2 4 6 8]
Such that D != C etc etc.
*/
__digits__ = list ( [0:10] )
__l_digits__ = list ( [1:10] )
def four_digit_even_unopt(){
D = random( [0,2,4,6,8] )
C = random( __digits__  D )
B = random( __digits__  C )
A = random( __l_digits__  B )
1000 * A + 100 * B + 10 * C + D
}
println( four_digit_even_unopt() )

NoOne
April 28, 2017 Cool to see @ChrisK back. Welcome back dude. However, as a welcome gesture,
I will love to rub something in... and here we go:
/* This is how to ZoomBA */
a = [1, 1, 3, 4, 1, 1, 2, 3]
target = 4
range_a = [0:size(a)].asList
// sequences generates all possible subset of a set
options = from ( sequences( range_a ), set() ) as {
// map back the opt to actual
list( $.o ) > { a[$.o] }
// the where clause filter around it
} where { sum($.o) == target }
// prints it
println(options)

NoOne
April 27, 2017 You want to find set intersection. Here is how we do it in ZoomBA.
(zoomba)userA = [ 2, 3, 1 ]
@[ 2,3,1 ] // ZArray
(zoomba)userB = [ 2, 5, 3 ]
@[ 2,5,3 ] // ZArray
(zoomba)userC = [ 7, 3, 1 ]
@[ 7,3,1 ] // ZArray
(zoomba)s = set()
{ } // ZSet
(zoomba)s += userA
{ 1,2,3 } // ZSet
(zoomba)s &= userB
{ 2,3 } // ZSet
(zoomba)s &= userC // &= mutable intersection
{ 3 } // ZSet
(zoomba)

NoOne
April 26, 2017 Too much code. I don't like to code at all. Be lazy.
/*
For a given Sum and N print all the combinations .
This is integer partition problem.
Constrained to number of partitions := N
Given an integer is n, imagine
1 1 1 1 ... 1 ( n 1's)
Now, there can be n1 cut positions.
Choosing or not choosing a cut position
will create a partition.
Thus, create a binary string with n1 digits.
When 1, we choose the cut, when 0, we do not.
This will produce all the cuts and thus, all partitions.
The problem is constrained by number of cuts := N1
*/
def partition_int( n , N ){
n_splits = n  1
max = 2 ** n_splits
partitions = set()
for ( x : [1:max] ) {
bs = str(x,2)
// do 0 padding on left
bs = '0' ** ( n_splits  size(bs) ) + bs
nums = list()
c = 1
for ( b : bs.value ){
if ( b == _'1' ){
nums += c
c = 1
} else {
c += 1
}
}
nums += c
continue ( size(nums) != N )
// to make the partitions unique
sorta(nums)
ps = str(nums,',')
continue ( ps @ partitions )
// only when does not exist
partitions += ps
// now print
printf('%s > %s \n', bs, ps )
}
}
partition_int( @ARGS = list( @ARGS ) > { int($.o) } )
The result if you run it :
zmb tmp.zm 16 2
000000000000001 > 1,15
000000000000010 > 2,14
000000000000100 > 3,13
000000000001000 > 4,12
000000000010000 > 5,11
000000000100000 > 6,10
000000001000000 > 7,9
000000010000000 > 8,8
Let's try another one:
zmb tmp.zm 10 4
000000111 > 1,1,1,7
000001011 > 1,1,2,6
000010011 > 1,1,3,5
000010101 > 1,2,2,5
000100011 > 1,1,4,4
000100101 > 1,2,3,4
000101010 > 2,2,2,4
001001001 > 1,3,3,3
001001010 > 2,2,3,3
Hope this should do fine.
 NoOne April 25, 2017// ZoomBA
def is_isomorphic( s1, s2 ){
if ( (l = size(s1))!= size(s2) ) return false
m = dict()
for ( i : [0:l] ){
if ( s1[i] @ m ){
y = m[ s1[i] ]
} else {
y = m[ s1[i] ] = s2[i]
}
if ( y != s2[i] ) return false
}
true
}
println( is_isomorphic('','' )) // true
println( is_isomorphic('aabaac','xxtxxw' )) // true
println( is_isomorphic('ac','xxt' )) // false
println( is_isomorphic('acaa','xxtw' )) // false

NoOne
April 22, 2017 I am hungry, SRH lost so frustrated, but this should do the trick :
/*
The find next lower tidy number is
not a classically trivial one.
Obvious trivial solution is :
def find_unoptimal( n ){ while( !is_tidy(n) ){ n = 1 } }
But that is a mess.
A better solution will be:
1. Search for inversion of order ( d[i] > d[i+1] ) from left.
2. If on the inversion, we can down the digit:
Down(x) = x  1
and d[i1] < d[i]  1 then we can down the digit, replace rest by 9.
3. If we can not do that ( 12222334445555123 ),
we search for a digit change from right: ( d[i]<d[i+1] )
where we can change d[i+1] to d[i] and replace all right digits by 9
*/
def find_last_tidy( n ){
sn = str(n)
l = size(sn)
i = index( [0:l1] ) :: { sn[$.o] > sn[$.o+1] }
if ( i < 0 ) return n // this is first step
// is there a left digit? if not...
if ( i == 0 ) return int( '' + ( int(sn[0])  1 ) + ( '9' ** (l  1) ) )
// there is
// if it is like 12222334445555123 ?
// then we need to check j is the repeat size
j = index( [i:1] ) :: { sn[$.o] != sn[i] }
ns = sn[0:ij] + ( int(sn[i])  1 ) + ( '9' ** (l  i + j  2 ) )
int ( ns )
}
println( find_last_tidy(@ARGS[0]) )

NoOne
April 22, 2017 @rajendra : I actually gave you an up vote. Later, I found, almost there but not there.
Observe this :
Input : 332 Expected : 299
Actual : 229
I was looking for branch conditions. Gotha.
I guess the dumb approach wins here :)
def find_unoptimal( n ){
while( !is_tidy(n) ){ n = 1 }
n // return
}
Obviously I will try to improve, but there are some very interesting edge scenarios.
 NoOne April 22, 2017/*
This is the one which should do it
*/
def has_3_consecutive( dates ){
if ( size(dates) < 3 ) return false
ld = list(dates)
// in long form 3 consecutive date are (D  d), D, (D + d)
exists([2: size(dates)]) where { 2 * ld[$.o 1 ] == ( ld[$.o2] + ld[$.o] ) }
}
ms = mset( file( 'logfile.txt' ) ) as { #(date,key) = $.o.split('\t') ; key }
users_cons = select( ms ) where {
dates = sset ( $.o.value ) as { #(date,key) = $.o.split('\t') ; int( time(date,'MM/dd/yyyy') ) }
has_3_consecutive( dates )
} as { $.o.key }

NoOne
April 19, 2017 (zoomba)input=[2,3,5,3,7,9,5,3,7]
@[ 2,3,5,3,7,9,5,3,7 ] // ZArray
(zoomba)ms = mset(input)
{2=1, 3=3, 5=2, 7=2, 9=1} // HashMap
(zoomba)l = list(ms.entries)
[ 2=1,3=3,5=2,7=2,9=1 ] // ZList
(zoomba)sortd(l) :: { $.l.value < $.r.value }
true // Boolean
(zoomba)l
[ 3=3,5=2,7=2,2=1,9=1 ] // ZList
(zoomba)x = fold(l,list()) > { for(i:[0:$.o.value] ){ $.p += $.o.key } }
[ 3,3,3,5,5,7,7,2,9 ] // ZList

NoOne
April 18, 2017 Open Chat in New Window
Here you go. The algorithm is pretty neat, but recursive. I don't like the recursion, but  it should work well.
The results of course are:
 NoOne June 12, 2017