perry.anderson
BAN USER//
// Given an array A = [3, 7, 2,5,6,4] for a number N, print the pairs
// from that array A that sums up to N. You should print each pair once.
//
// -- nonameno October 29, 2015 in England
// Bloomberg LP Interview Question for Software Engineer Interns
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.Vector;
/*
* The AWT Point class could have been used removing the
* need to replicate much of the functionality here. However,
* adding our own Pair class allows us to customize this
* class for our purposes such that we override the toString()
* method to show a preferred pair display.
*/
class Pair<L,R> {
private L l;
private R r;
public Pair(L l, R r){
this.l = l;
this.r = r;
}
public L getL(){ return l; }
public R getR(){ return r; }
public void setL(L l){ this.l = l; }
public void setR(R r){ this.r = r; }
public String toString() { return "{ " + l + ", " + r + " }"; }
}
public class LPMain009 {
/*
* The specification says "pairs from that array" so we
* can only assume that a single selection cannot be used
* twice to be considered a pair. We also have to print
* each pair once implying that we only need to store
* each pair once.
*/
static boolean duplicateFound(Vector<Pair<Integer,Integer>>
pairs, Pair<Integer,Integer> newPair) {
for ( Pair<Integer,Integer> pair : pairs ) {
if ( pair.getL() == newPair.getR()
&& pair.getR() == newPair.getL() )
return true;
}
return false;
}
static Integer[][] sortPairs(Integer[] data, int N) {
Vector<Pair<Integer,Integer>> pairs
= new Vector<Pair<Integer,Integer>>();
/*
* First we take each two number combination except
* for the same number compared against itself and
* see if the total is equal to N
*/
for (int x = 0; x < data.length; x++) {
for (int y = 0; y < data.length; y++) {
if ( data[x] != data[y] )
if ( data[x] + data[y] == N ) {
Pair<Integer, Integer> newPair
= new Pair<Integer, Integer>(data[x],data[y]);
if ( !duplicateFound(pairs,newPair))
pairs.add(newPair);
}
}
}
/*
* Then, it is good programming practice to return the same type
* of data in a container as was used to pass the parameters.
*/
Integer[][] results = new Integer[pairs.size()][2];
int i = 0;
for ( Pair<Integer,Integer> pair : pairs ) {
Integer[] dual = { pair.getL(), pair.getR() };
results[i++] = dual;
}
return results;
}
public static void main(String[] args) {
Integer[] data1 = new Integer[] { 3,7,2,5,6,4 };
Integer result1 = 10;
Integer[][] test1 = new Integer[][] { { 3, 7 } , { 6, 4 } };
/*
* Due to a glitch in the JVM we have to compare the arrays
* using a manual approach;
*/
// assert Arrays.equals(sortPairs(data1,result1), test1);
// assert !Arrays.equals(sortPairs(data1,result1), test1);
Integer[][] check = sortPairs(data1,result1);
for ( int i=0; i<test1.length; i++ )
if ( check[i][0] != test1[i][0]
|| check[i][1] != test1[i][1] )
System.out.println("Different");
/*
* As per specification we need to print out the result.
*/
for ( int i=0; i<check.length; i++ ) {
System.out.println(
new Pair<Integer,Integer>(check[i][0],check[i][1]));
}
}
}
//
// Given an array A = [3, 7, 2,5,6,4] for a number N, print the pairs
// from that array A that sums up to N. You should print each pair once.
//
// -- nonameno October 29, 2015 in England
// Bloomberg LP Interview Question for Software Engineer Interns
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.Vector;
class Pair<L,R> {
private L l;
private R r;
public Pair(L l, R r){
this.l = l;
this.r = r;
}
public L getL(){ return l; }
public R getR(){ return r; }
public void setL(L l){ this.l = l; }
public void setR(R r){ this.r = r; }
public String toString() { return "{ " + l + ", " + r + " }"; }
}
public class LPMain009 {
static boolean duplicateFound(Vector<Pair<Integer,Integer>>
pairs, Pair<Integer,Integer> newPair) {
for ( Pair<Integer,Integer> pair : pairs ) {
if ( pair.getL() == newPair.getR()
&& pair.getR() == newPair.getL() )
return true;
}
return false;
}
static Integer[][] sortPairs(Integer[] data, int N) {
Vector<Pair<Integer,Integer>> pairs
= new Vector<Pair<Integer,Integer>>();
/*
* First we take each two number combination except
* for the same number compared against itself and
* see if the total is equal to N
*/
for (int x = 0; x < data.length; x++) {
for (int y = 0; y < data.length; y++) {
if ( data[x] != data[y] )
if ( data[x] + data[y] == N ) {
Pair<Integer, Integer> newPair
= new Pair<Integer, Integer>(data[x],data[y]);
if ( !duplicateFound(pairs,newPair))
pairs.add(newPair);
}
}
}
Integer[][] results = new Integer[pairs.size()][2];
int i = 0;
for ( Pair<Integer,Integer> pair : pairs ) {
Integer[] dual = { pair.getL(), pair.getR() };
results[i++] = dual;
}
return results;
}
public static void main(String[] args) {
Integer[] data1 = new Integer[] { 3,7,2,5,6,4 };
Integer result1 = 10;
Integer[][] test1 = new Integer[][] { { 3, 7 } , { 6, 4 } };
/*
* Due to a glitch in the JVM we have to compare the arrays
* using a manual approach;
*/
// assert Arrays.equals(sortPairs(data1,result1), test1);
// assert !Arrays.equals(sortPairs(data1,result1), test1);
Integer[][] check = sortPairs(data1,result1);
for ( int i=0; i<test1.length; i++ )
if ( check[i][0] != test1[i][0]
|| check[i][1] != test1[i][1] )
System.out.println("Different");
/*
* As per specification we need to print out the result.
*/
for ( int i=0; i<check.length; i++ ) {
System.out.println(
new Pair<Integer,Integer>(check[i][0],check[i][1]));
}
}
}
//
// Given an array A = [3, 7, 2,5,6,4] for a number N, print the pairs
// from that array A that sums up to N. You should print each pair once.
//
// -- nonameno October 29, 2015 in England
// Bloomberg LP Interview Question for Software Engineer Interns
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.Vector;
class Pair<L,R> {
private L l;
private R r;
public Pair(L l, R r){
this.l = l;
this.r = r;
}
public L getL(){ return l; }
public R getR(){ return r; }
public void setL(L l){ this.l = l; }
public void setR(R r){ this.r = r; }
public String toString() { return "{ " + l + ", " + r + " }"; }
}
public class LPMain009 {
static boolean duplicateFound(Vector<Pair<Integer,Integer>>
pairs, Pair<Integer,Integer> newPair) {
for ( Pair<Integer,Integer> pair : pairs ) {
if ( pair.getL() == newPair.getR()
&& pair.getR() == newPair.getL() )
return true;
}
return false;
}
static Integer[][] sortPairs(Integer[] data, int N) {
Vector<Pair<Integer,Integer>> pairs
= new Vector<Pair<Integer,Integer>>();
/*
* First we take each two number combination except
* for the same number compared against itself and
* see if the total is equal to N
*/
for (int x = 0; x < data.length; x++) {
for (int y = 0; y < data.length; y++) {
if ( data[x] != data[y] )
if ( data[x] + data[y] == N ) {
Pair<Integer, Integer> newPair
= new Pair<Integer, Integer>(data[x],data[y]);
if ( !duplicateFound(pairs,newPair))
pairs.add(newPair);
}
}
}
Integer[][] results = new Integer[pairs.size()][2];
int i = 0;
for ( Pair<Integer,Integer> pair : pairs ) {
Integer[] dual = { pair.getL(), pair.getR() };
results[i++] = dual;
}
return results;
}
public static void main(String[] args) {
Integer[] data1 = new Integer[] { 3,7,2,5,6,4 };
Integer result1 = 10;
Integer[][] test1 = new Integer[][] { { 3, 7 } , { 6, 4 } };
/*
* Due to a glitch in the JVM we have to compare the arrays
* using a manual approach;
*/
// assert Arrays.equals(sortPairs(data1,result1), test1);
// assert !Arrays.equals(sortPairs(data1,result1), test1);
Integer[][] check = sortPairs(data1,result1);
for ( int i=0; i<test1.length; i++ )
if ( check[i][0] != test1[i][0]
|| check[i][1] != test1[i][1] )
System.out.println("Different");
/*
* As per specification we need to print out the result.
*/
for ( int i=0; i<check.length; i++ ) {
System.out.println(
new Pair<Integer,Integer>(check[i][0],check[i][1]));
}
}
}
**
* The first version of the class only needed to update the
* steps member by one. In a theorectial future version of the
* class perhaps things are much more complicated. The following
* is a graphic example of how complicated things can get for
* the purpose of illustration. But it shows the benefits of
* making things private as the changes made to the new
* version of the class have no effect on how the class
* is used via it's public interface.
*
*/
class Person {
private:
int steps;
void howWeReallyWalk() {
int a = 123, b (456), sum = a + b;
cout << "The sum of " << a << " and " << b << " is " << sum << endl;
int x = 3, y = 5;
cout << a << '+' << b << '=' << (a+b);
cout << "vector demo" << endl;
vector<int> left(7);
vector<int> right(7);
left[5] = 7;
right[5] = 8;
cout << left[5] << endl;
cout << right[5] << endl;
vector<int> biggest(
pick_vector_with_biggest_fifth_element( left, right )
);
cout << biggest[5] << endl;
steps = a + b + c;
}
public:
Person() : steps(0)
{
}
void walk() {
howWeReallyWalk();
}
};
int main() {
Person instance;
// compiles, no problem and the number of steps
// are increased by one
instance.walk();
}
//
// In C++, what's the difference between public and private?
// what's the purpose of this and please illustrate a design
// example with this.
//
// -- ycw March 07, 2015 in United States
// Bloomberg LP Interview Question
//
// The whole purpose of private, protected, friend and public in
// a C++ program is to reduce code management complexities that
// are often associated with large software projects. Typically,
// the more code you write, the more complex the code becomes.
// One method developed to act as a counter-measure to coding
// complexity which grows exponentially with each modification
// and addition to the code base is to hide as many details in
// a given module or component of software from all other given
// modules or components of software as possible.
//
// In C++ we have the ability to hide how a module gets things done
// internally from how the the module can be used externally.
// This is known as loose-coupling as oppose to tight-coupling with
// the idea of giving the developer better ways of upgrading code
// or fixing code without having to worry about issues in other
// parts of the software base. In effect, more cleaner your public
// interface and the more seperate the public interface is from
// it's private behavior, the more the same or another developer
// can make changes or correct code behavior over time.
//
// The hiding details of a class's implementation is called
// Encapsulation.
//
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
/**
* In it's simplest incarnation you would hide as many
* details of the class inside and private away from
* it's public interface. Here we make int steps a private
* member, the only way to increase the amount of steps
* a person takes it to call it's public method walk().
*
* Trying to access the private member from outside the
* class will result in a C++ compiler error. The program
* won't even compile as the compiler is trying to tell you
* that you trying to access a member marked as private.
*
*/
class Person {
private:
int steps;
public:
Person() : steps(0)
{
}
void walk() {
steps++;
}
};
int main() {
Person instance;
// compiles, no problem and the number of steps
// are increased by one
instance.walk();
// this will not compile as the class specification
// has marked the member int steps as private and not
// publically available
instance.steps = instance.steps + 1;
}
//
// How do you decide whether we should use Java or C++ for a
// particular project . what are pros and cons
//
// -- chad August 01, 2015 in United States
// Bloomberg LP Interview Question
//
//
// Java : Quick Development
// C++: Efficient Development
// Java: Safe Programming
// C++: System Programming
// Java: Portable for OS
// C++: More Control
//
// -- spiderman August 30, 2015 | Flag
//
// What he said.
//
// Where possible I try to use Java. The container classes as per
// the standard container library in java.util.* meet most application
// needs with ease. Of course, being familiar with all the nitty gritty
// details as to how to use Vector<type>, HashMap<type> and List<type>
// effectively comes in really handy. The number one reason why I like
// Java where possible is because of the strong type checking and the
// more efficient handling of memory allocation issues. You can still
// have memory leaks in Java but it happens much more rarely.
//
// But whatever you can do in Java you can do in C++ by way of effective
// use of the STL. You would use C++ when memory and performance issues
// are required over portability. The big issue with C++ is that your
// responsible for memory management much more than inside Java.
//
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
//
//
// A client wants to build a software phone book that contains
// everyone in the world (7 billion people). Every person has only
// the first name and the name is unique. What data structure would
// you use to store the data?
//
// -- rv July 14, 2015 in United States | Report
// Bloomberg LP Interview Question
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.*;
import java.util.zip.CRC32;
/*
* ---- Beginning of Answer ---
*
* In any typical database real world application you have to take
* into consideration available ram versus database not to mention
* database servers and the like. But what really makes such a large
* database application manageable is to make use of the CRC32
* coding algorithm to minimize indexing demands. The CRC32 method
* produces a number that is at least 99.9999% effective such that
* the possibilities of a duplicate is exceedingly low for two
* different strings. For example, like trying to pick out the Planet
* Earth out of 10,000 galaxies the size of the Milky Way.
*
* So the data structure that I would use to store the data would be
* a simple hash map implementation based on the CRC key value which
* keeps the size of the hash map key to a mere 4 bytes compared to
* the incredible database demands required to store duplicate name
* strings in an index database. In other words, very few people use
* four bytes to represent their first name. Hence the storage costs
* are minimized and performance gains are maximized.
*
* ---- End of Answer ----
*
* What you see below is the skeleton of what would be required to
* coordinate such a large database in a typical distributed server
* application.
*
* This example also shows the effective use of interfaces in Java
* to coordinate changes amongst a large number of classes. The same
* effect can be implemented in C++ use Abstract Classes.
*
*
*/
class PhoneBookEntry implements Comparable<PhoneBookEntry> {
static CRC32 checksum = new CRC32();
String name;
String number;
long key;
public PhoneBookEntry(String name, String number) {
this.name = name;
this.number = number;
checksum.reset();
checksum.update(name.getBytes(),0,name.getBytes().length);
this.key = checksum.getValue();
}
@Override
public int compareTo(PhoneBookEntry o) {
return (int)(key - o.key);
}
}
/**
* interface PhoneBookInterface
*
* Defines the interface to the PhoneBook conceptual database for
* use by all implementations of the actual PhoneBook database.
* @author perry
*
*/
interface PhoneBookInterface {
PhoneBookEntry create(String name, String number);
PhoneBookEntry retrieve(String name);
PhoneBookEntry update(String name, String number);
PhoneBookEntry delete(String name);
PhoneBookEntry put(PhoneBookEntry entry);
}
/*
* Typically, you would need a cache for use by applications to
* read in whatever phone book entries needed during a session.
*/
class PhoneBookCache implements PhoneBookInterface {
static CRC32 checksum = new CRC32();
HashMap<Long, PhoneBookEntry> cache = new HashMap<Long, PhoneBookEntry>();
@Override
public PhoneBookEntry retrieve(String name) {
checksum.reset();
checksum.update(name.getBytes(),0,name.getBytes().length);
long searchkey = checksum.getValue();
return cache.get(searchkey);
}
@Override
public PhoneBookEntry create(String name, String number) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry update(String name, String number) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry delete(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry put(PhoneBookEntry entry) {
// TODO Auto-generated method stub
return null;
}
}
/*
* Typically, you would store all phone book entries into a
* professional database like Oracle or MySQL. This class
* specializes in converting application requests into
* the vendor's implementation. Here, the CRC32 value key
* greatly simplies the need for indexing.
*
*/
class PhoneBookDatabase implements PhoneBookInterface {
static CRC32 checksum = new CRC32();
HashMap<Long, PhoneBookEntry> database = new HashMap<Long, PhoneBookEntry>();
@Override
public PhoneBookEntry retrieve(String name) {
long searchkey = getSearchKey(name);
return database.get(searchkey);
}
Long getSearchKey(String name) {
checksum.reset();
checksum.update(name.getBytes(),0,name.getBytes().length);
long searchkey = checksum.getValue();
return searchkey;
}
@Override
public PhoneBookEntry create(String name, String number) {
long searchkey = getSearchKey(name);
PhoneBookEntry entry = new PhoneBookEntry(name, number);
database.put(searchkey,entry);
return entry;
}
@Override
public PhoneBookEntry update(String name, String number) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry delete(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry put(PhoneBookEntry entry) {
// TODO Auto-generated method stub
return null;
}
}
/*
* Assuming that a server can have more than one database
* we use the mod operation on the key value to find out which
* database the phone entry has been assigned.
*
*/
class PhoneBookServer implements PhoneBookInterface {
static CRC32 checksum = new CRC32();
static int maxDatabasePerServer = 100;
HashMap<Long, PhoneBookDatabase> databases = new HashMap<Long, PhoneBookDatabase>();
@Override
public PhoneBookEntry retrieve(String name) {
long searchkey = getSearchKey(name);
PhoneBookDatabase actualDatabase = databases.get(searchkey);
return actualDatabase.retrieve(name);
}
Long getSearchKey(String name) {
checksum.reset();
checksum.update(name.getBytes(),0,name.getBytes().length);
long searchkey = checksum.getValue() % maxDatabasePerServer;
return searchkey;
}
PhoneBookDatabase getDatabase(String name) {
long searchkey = getSearchKey(name);
PhoneBookDatabase actualDatabase = databases.get(searchkey);
if ( actualDatabase == null ) {
actualDatabase = new PhoneBookDatabase();
databases.put(searchkey, actualDatabase);
}
return actualDatabase;
}
@Override
public PhoneBookEntry create(String name, String number) {
PhoneBookDatabase actualDatabase = getDatabase(name);
return actualDatabase.create(name, number);
}
@Override
public PhoneBookEntry update(String name, String number) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry delete(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry put(PhoneBookEntry entry) {
// TODO Auto-generated method stub
return null;
}
}
/*
* To find where the server holding the database is located
* we assume a fixed value of 10,000 servers online at any time
* and use a mod operation on the CRC32 value to know where the
* actual database for that particular phone book entry is.
*
*/
class PhoneBookServerCache implements PhoneBookInterface {
static CRC32 checksum = new CRC32();
static int maxServers = 10000;
HashMap<Long, PhoneBookServer> servers = new HashMap<Long, PhoneBookServer>();
static PhoneBookServerCache singleton = new PhoneBookServerCache();
private PhoneBookServerCache() {
}
public static PhoneBookServerCache getInstance() {
return singleton;
}
Long getSearchKey(String name) {
checksum.reset();
checksum.update(name.getBytes(),0,name.getBytes().length);
long searchkey = checksum.getValue() % maxServers;
return searchkey;
}
PhoneBookServer getServer(String name) {
long searchkey = getSearchKey(name);
PhoneBookServer actualServer = servers.get(searchkey);
if ( actualServer == null ) {
actualServer = new PhoneBookServer();
servers.put(searchkey, actualServer);
}
return actualServer;
}
@Override
public PhoneBookEntry retrieve(String name) {
PhoneBookServer actualServer = getServer(name);
return actualServer.retrieve(name);
}
@Override
public PhoneBookEntry create(String name, String number) {
PhoneBookServer actualServer = getServer(name);
return actualServer.create(name, number);
}
@Override
public PhoneBookEntry update(String name, String number) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry delete(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry put(PhoneBookEntry entry) {
return null;
}
}
/*
* Typically, you would need a cache for use by applications to
* read in whatever phone book entries needed during a session.
*/
class PhoneBookApp implements PhoneBookInterface {
PhoneBookCache cache = new PhoneBookCache();
PhoneBookServerCache server = PhoneBookServerCache.getInstance();
@Override
public PhoneBookEntry retrieve(String name) {
PhoneBookEntry entry = cache.retrieve(name);
if ( entry == null ) {
entry = server.retrieve(name);
cache.put(entry);
}
return entry;
}
@Override
public PhoneBookEntry create(String name, String number) {
return server.create(name,number);
}
@Override
public PhoneBookEntry update(String name, String number) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry delete(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public PhoneBookEntry put(PhoneBookEntry entry) {
// TODO Auto-generated method stub
return null;
}
}
public class LPMain007 {
public static void main(String[] args) {
PhoneBookApp app = new PhoneBookApp();
String[] entry1 = { "Jack", "800-555-1212" };
PhoneBookEntry test1 = new PhoneBookEntry("Jack", "800-555-1212");
String[] entry2 = { "Bill", "888-555-1212" };
PhoneBookEntry test2 = new PhoneBookEntry("Bill", "888-555-1212");
assert app.create(entry1[0],entry1[1]).compareTo(test1)==0;
assert app.create(entry2[0],entry2[1]).compareTo(test2)==0;
assert app.retrieve(entry1[0]).compareTo(test1)==0;
assert app.retrieve(entry1[0]).compareTo(test2)!=0;
assert app.retrieve(entry2[0]).compareTo(test2)==0;
assert app.retrieve(entry2[0]).compareTo(test1)!=0;
}
}
It doesn't hurt to have an extensive background in GPS applications, knowing right where to look!
- perry.anderson November 25, 2016/**
* public int compareTo(Plane o)
*
* Compares two planes relative to the radar by converting
* the aircraft's x & y 2D coordinates into two Pythagorean values
* and converting the difference between the two aircraft relative
* to the radar station into a +-1 or 0 value.
*
*/
@Override
public int compareTo(Plane o) {
double p = Math.sqrt((x*x)+(y*y));
double po = Math.sqrt((o.x*o.x)+(o.y*o.y));
return (int)(p - po);
}
static Plane[] scan(Plane[] planes) {
List<Plane> list = new ArrayList<Plane>();
for ( Plane product : planes )
list.add(product);
Collections.sort(list);
Plane[] report = list.toArray(new Plane[planes.length]);
return report;
}
//
//
// Imagine an airport with the control tower having a constantly
// rotating radar scanning for airplanes. The radar's coordinates
// in the 2-d plane are (0,0).
//
// The radar has an API: void scan(const Plane &P)
// that is called periodically whenever the radar detects a plane.
// You can imagine that the Plane structure has x,y coordinates
// for that plane. You should fill in the function Scan, such that
// at any given time you are able to return the 100 closest planes
// to the tower (0,0).
//
// -- Johnybegood December 24, 2015
// in United States for Derivatives
// Bloomberg LP Interview Question
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.*;
class Plane implements Comparable<Plane> {
String airline;
int flightNumber;
int x;
int y;
int speed;
Plane(String a, int b, int c, int d, int e) {
this.airline = a;
this.flightNumber = b;
this.x = c;
this.y = d;
this.speed = e;
}
/**
* public int compareTo(Plane o)
*
* Compares two planes relative to the radar by converting
* the aircraft's x & y 2D coordinates into two Pythagorean values
* and converting the difference between the two aircraft relative
* to the radar station into a +-1 or 0 value.
*
*/
@Override
public int compareTo(Plane o) {
double p = Math.sqrt((x*x)+(y*y));
double po = Math.sqrt((o.x*o.x)+(o.y*o.y));
System.out.println(p - po+" : "+getFlightName());
return (int)(p - po);
}
public String getFlightName() {
return airline+" "+flightNumber;
}
}
public class LPMain006 {
static Plane[] getReport(Plane[] planes) {
List<Plane> list = new ArrayList<Plane>();
for ( Plane product : planes )
list.add(product);
Collections.sort(list);
Plane[] report = list.toArray(new Plane[planes.length]);
return report;
}
public static void main(String[] args) {
Plane[] test1 = {
new Plane("WestJet",205,50,50,50),
new Plane("United Airlines",99,25,25,25),
new Plane("Canadiar",310,-45,-45,45),
new Plane("NorthWest",202,35,-35,35),
new Plane("SouthWest",500,-60,60,25)
};
Plane[] results1 = {
new Plane("United Airlines",99,25,25,25),
new Plane("NorthWest",202,35,-35,35),
new Plane("Canadiar",310,-45,-45,45),
new Plane("WestJet",205,50,50,50),
new Plane("SouthWest",500,-60,60,25)
};
/*
* Due to a glitch in the JVM we have to compare the arrays
* using a manual approach;
*/
// assert Arrays.equals(getReport(test1), results1);
// assert !Arrays.equals(getReport(test1), test1);
Plane[] report = getReport(test1);
for ( int i=0; i<test1.length; i++ )
if ( !report[i].getFlightName().equals(results1[i].getFlightName()) )
System.out.println("Different");
}
}
//
//
// THERE ARE SEVERAL LOG FILES COMING BY DATE WITH PRODUCT IDS
// AND I NEED TO REPORT THE TOP 10 (PRODUCT IDS) DURING A MOVING
// PERIOD OF 1 MONTH. DISCUSSED ABOUT THE DATA STRUCTURES NEEDED
// TO IMPLEMENT THE SOLUTION.
//
// -- bhardwaj.cs February 23, 2016 in United States
// Bloomberg LP Interview Question
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.*;
/*
* From what I can glean from the problem description the question
* being asked is how I would get information from an inventory
* database and sort the results on two attributes, when the
* products were stocked and how much of the product was stocked.
*
*/
class Product implements Comparable<Product> {
String id;
int count;
Date stocked;
Product(String id, int count, Date stocked) {
this.id = id;
this.count = count;
this.stocked = stocked;
}
@Override
public int compareTo(Product o) {
if ( o.stocked == stocked )
return o.count - count;
else
return (int)(o.stocked.getTime() - stocked.getTime());
}
}
public class LPMain005 {
static Product[] getReport(Product[] products) {
PriorityQueue<Product> queue =
new PriorityQueue<Product>(10);
for ( Product product : products )
queue.add(product);
Product[] report = new Product[products.length];
for ( int i=0; i<products.length; i++ )
report[i] = queue.poll();
return report;
}
public static void main(String[] args) {
Calendar calender = Calendar.getInstance();
calender.add(Calendar.MONTH, -1);
Date lastMonth = calender.getTime();
Date thisMonth = new Date();
Product[] test1 = {
new Product("Bananas",5,lastMonth),
new Product("Blackberries",15,thisMonth),
new Product("Yellowberries",7,thisMonth),
new Product("Apples",10,lastMonth),
new Product("Limes",3,lastMonth),
new Product("Blueberries",20,thisMonth),
new Product("Redberries",12,thisMonth)
};
Product[] results1 = {
new Product("Apples",10,lastMonth),
new Product("Bananas",5,lastMonth),
new Product("Limes",3,lastMonth),
new Product("Blueberries",20,thisMonth),
new Product("Blackberries",15,thisMonth),
new Product("Redberries",12,thisMonth),
new Product("Yellowberries",7,thisMonth)
};
/*
* Due to a glitch in the JVM we have to compare the arrays
* using a manual approach;
*/
// assert Arrays.equals(getReport(test1), results1);
// assert !Arrays.equals(getReport(test1), test1);
Product[] report = getReport(test1);
for ( int i=0; i<test1.length; i++ )
if ( !report[i].id.equals(results1[i].id) )
System.out.println("Different");
}
}
//
//
// Given a string find biggest palindrome substring. For example for
// given string "AABCDCBA" output should be "ABCDCBA" and for given string
// "DEFABCBAYT" output should be "ABCBA".
//
// -- Preeti May 24, 2016 in United Kingdom,
// Bloomberg LP Interview Question for Financial Software Developers
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
public class LPMain004 {
/**
*
* int findMidpoint(String text)
*
* I admit, it took a while longer than average to figure out
* the right way to go about this. So in an interview situation,
* a question like this might take me a bit longer. Bit with all
* such seemingly difficult talks, when you take the time to break
* the task into smaller tasks, the ideal solution sort of
* presents itself on it's own. In this case, taking the time to find
* the mid point first, then figuring out how big the palindrome is
* made this simple solution possible and understandable.
*
* @param text of string to search
* @return location of midpoint
*/
static int findMidpoint(String text) {
// First reject any string less than 3 characters
if (text.length() > 2) {
// second try to find the midpoint
for (int x = 1; x < text.length() - 1; x++) {
char c1 = text.charAt(x - 1);
char c2 = text.charAt(x + 1);
if (c1 == c2)
return x;
}
}
return -1;
}
/**
*
* int findPalindrome(String text)
*
* This method merely takes the midpoint and then checks successive
* characters from the midpoint until the end of the string is
* reached or the characters being compared are no longer the same.
*
* @param text of string to search
* @return text of the palindrome
*/
static String findPalindrome(String text) {
// First: Find midpoint if there is one ...
int x = findMidpoint(text);
if (x == -1)
return "";
// using the midpoint, find out how big the palindrome is
String palindrome = text.charAt(x) + "";
int offset = 1;
while (true) {
try {
char c1 = text.charAt(x - offset);
char c2 = text.charAt(x + offset);
if (c1 != c2)
break;
palindrome = c1 + palindrome + c2;
offset++;
} catch (IndexOutOfBoundsException e) {
break;
}
}
return palindrome;
}
public static void main(String[] args) {
String test1 = "AABCDCBA";
String results1 = "ABCDCBA";
String test2 = "DEFABCBAYT";
String results2 = "ABCBA";
assert findPalindrome(test1).equals(results1);
assert !findPalindrome(test1).equals(test1);
assert findPalindrome(test2).equals(results2);
assert !findPalindrome(test2).equals(test2);
}
}
//
//
// Given a string find biggest palindrome substring. For example for
// given string "AABCDCBA" output should be "ABCDCBA" and for given string
// "DEFABCBAYT" output should be "ABCBA".
//
// -- Preeti May 24, 2016 in United Kingdom,
// Bloomberg LP Interview Question for Financial Software Developers
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
public class LPMain004 {
/**
*
* int findMidpoint(String text)
*
* I admit, it took a while longer than average to figure out
* the right way to go about this. So in an interview situation,
* a question like this might take me a bit longer. Bit with all
* such seemingly difficult talks, when you take the time to break
* the task into smaller tasks, the ideal solution sort of
* presents itself on it's own. In this case, taking the time to find
* the mid point first, then figuring out how big the palindrome is
* made this simple solution possible and understandable.
*
* @param text of string to search
* @return location of midpoint
*/
static int findMidpoint(String text) {
// First reject any string less than 3 characters
if (text.length() > 2) {
// second try to find the midpoint
for (int x = 1; x < text.length() - 1; x++) {
char c1 = text.charAt(x - 1);
char c2 = text.charAt(x + 1);
if (c1 == c2)
return x;
}
}
return -1;
}
/**
*
* int findPalindrome(String text)
*
* This method merely takes the midpoint and then checks successive
* characters from the midpoint until the end of the string is
* reached or the characters being compared are no longer the same.
*
* @param text of string to search
* @return text of the palindrome
*/
static String findPalindrome(String text) {
// First: Find midpoint if there is one ...
int x = findMidpoint(text);
if (x == -1)
return "";
// using the midpoint, find out how big the palindrome is
String palindrome = text.charAt(x) + "";
int offset = 1;
while (true) {
try {
char c1 = text.charAt(x - offset);
char c2 = text.charAt(x + offset);
if (c1 != c2)
break;
palindrome = c1 + palindrome + c2;
offset++;
} catch (IndexOutOfBoundsException e) {
break;
}
}
return palindrome;
}
public static void main(String[] args) {
String test1 = "AABCDCBA";
String results1 = "ABCDCBA";
String test2 = "DEFABCBAYT";
String results2 = "ABCBA";
assert findPalindrome(test1).equals(results1);
assert !findPalindrome(test1).equals(test1);
assert findPalindrome(test2).equals(results2);
assert !findPalindrome(test2).equals(test2);
}
}
/*
* If you were pressed for time and did not have the
* luxury to implement a really cool Roman Numerals to
* Decimal evaluator, you could use this very same
* technique just take the time to fill in all the values
* between 1 thru 50 in Roman Numerals.
*
* ;)
*
*/
static String ranks =
"I II III IV V VI VII VIII IX X" +
"XI XII XIII XIV XV XVII XVIII XIX XX" +
"XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX" +
"XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XXXX" +
"XXXXI XXXIII XXXIIII XXXXIV XXXXV XXXXVI XXXXVII XXXXVIII XXXXIX XXXXX";
@Override
public int compareTo(RomanTitle o) {
if ( name.compareToIgnoreCase(o.name) != 0 )
return name.compareToIgnoreCase(o.name);
else {
int r1 = ranks.indexOf(rank);
int r2 = ranks.indexOf(o.rank);
return r1 - r2;
}
}
//
// Royal titles consist of name followed by space and a Roman numeral.
//
// Example:
//
// Richard IV. The Roman numeral in the title can go
// to L (50). You are given the Roman numerals from 1 to 10:
// I II III IV V VI VII VIII IX X. And you are given the 10
// multiples up to 50: XX XXX IL L. Numbers between 10 and 50
// that are not given can be formed from 10 multiples and a
// numeral b/w 1 and 9. Example: 48 is XLVIII which is XL (40)
// plus VIII (8).
//
// You are given an array of Roman titles sort it as follows:
// sort it on the name unless the names are equal, in which
// case you have to sort it on the ordinal of the numerals.
//
// Examples:
//
// Henry II, Edward VIII => Edward VII, Henry II
// Richard V, Richard II, Richard X => Richard II,
// Richard V, Richard X
//
// -- haldokan August 12, 2016
// Bloomberg LP Software Analyst C++
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.*;
class RomanTitle implements Comparable<RomanTitle> {
String name;
String rank;
/*
* In a production environment, an exception would be thrown
* for an ill formed Roman Title.
*
*/
public RomanTitle(String romanTitle) {
String[] splited = romanTitle.split("\\s");
this.name = splited[0];
this.rank = splited[1];
}
public String toString() {
return name+" "+rank;
}
/**
* This solution shows the ability to easily test between
* Roman Numberals 1 thru 10. A slightly more extensive
* algorithm would be needed to do 1 thru 50. But this basic
* design conveys the essence of this problem demonstrating
* an effective use of built-in java.io.* classes to resolve
* the problem in a manner that's easily readable.
*
* In other words: All the logic needed to figure out to
* compare Roman Numerals between 1 thru 50 can be either
* concentrated in this compareTo() method or imported from
* a library dedicated to comparing Roman Numerals from here.
*
* Everything else would remain the same!
*
*/
static String ranks = "I II III IV V VI VII VIII IX X";
@Override
public int compareTo(RomanTitle o) {
if ( name.compareToIgnoreCase(o.name) != 0 )
return name.compareToIgnoreCase(o.name);
else {
int r1 = ranks.indexOf(rank);
int r2 = ranks.indexOf(o.rank);
return r1 - r2;
}
}
}
public class LPMain003 {
static String[] sortNames(String[] romanTitles) {
Vector<RomanTitle> titles = new Vector<RomanTitle>();
for( String title : romanTitles )
titles.add(new RomanTitle(title));
Collections.sort(titles);
String[] results = new String[titles.size()];
int i = 0;
for( RomanTitle title : titles )
results[i++] = title+"";
return results;
}
public static void main(String[] args) {
String[] names1 = { "Henry II", "Edward VIII" };
String[] test1 = { "Edward VIII", "Henry II" };
String[] names2 = { "Richard V", "Richard II", "Richard X" };
String[] test2 = { "Richard II", "Richard V", "Richard X" };
assert Arrays.equals(sortNames(names1), test1);
assert !Arrays.equals(sortNames(names1), names1);
assert Arrays.equals(sortNames(names2), test2);
assert !Arrays.equals(sortNames(names2), names2);
}
}
//
// " The output is looking like: 0 0 0 0 1 0
// To me the output should be: 0 0 0 0 0 0
//
// But, how come 1 is coming in ? "
//
// - rasmiranjanbabu July 12, 2016 in United States
// Bloomberg LP Software Analyst C++
//
// By way of the xcode debugger it was observed that
// the address size of the first display() function was
// assuming that the size of all objects passed to it were
// always the base class size. When the display() function
// is passed a derived class it does not take into
// consideration the larger sized object in it's pointer
// calculations.
//
// There are two ways to resolve the issue. One is to place
// make the base::getA() method virtual. This allows the compiler
// to take into account the actual size of the object at runtime.
//
// The slightly larger but more elegant approach would be to
// write a dedicated (albeit duplicate) function for the der
// class of the function display()
//
// In order to compile this source code under xcode 7.x however
// the "int i = 3" has to changed to a "const int i=3" otherwise
// the original source will not even compile as the size of arrays
// require a constant upon declaration.
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
#include <iostream>
#include <typeinfo>
using namespace std;
class base {
public:
int a;
base() : a(0) {}
// solution #1: add 'virtual' here
virtual int getA() { return a; }
};
class der : public base {
public:
int b;
der() : b(1) {}
int getB() { return b; }
};
void display(base* obj, int ele) {
for (int i = 0; i < ele; i++) {
cout << (obj + i)->getA() << endl;
}
}
// solution #2: write a dedicated function here
void display(der* obj, int ele) {
for (int i = 0; i < ele; i++) {
cout << (obj + i)->getA() << endl;
}
}
int main() {
// glitch: change "int i = 3" to "const int i=3"
const int i = 3;
base arrb[i];
display(arrb, 3);
der arrd[i];
display(arrd, 3);
return 0;
}
//
// Given an unsorted integer array, place all zeros to the
// end of the array without changing the sequence of non-zero
// elements. ( ie. [1,3,0,8,12,0,4,0,7] => [1,3,8,12,4,7,0,0,0] )
//
// Run with VM arguments -ea to enable assert testing
//
// (c) 2016 Perry Anderson, All Rights Reserved, worldwide.
//
//
import java.util.Vector;
import java.util.Arrays;
public class LPMain002 {
static Integer[] sortOut(Integer[] data) {
Vector<Integer> results = new Vector<Integer>();
int zeroCount = 0;
for (int i = 0; i < data.length; i++) {
if ( data[i]==0)
zeroCount++;
else
results.add(data[i]);
}
while (zeroCount-->0)
results.add(new Integer(0));
return results.toArray(new Integer[results.size()]);
}
public static void main(String[] args) {
Integer[] data1 = new Integer[] { 1, 3, 0, 8, 12, 0, 4, 0, 7 };
Integer[] data2 = new Integer[] { 1, 3, 8, 12, 4, 7, 0, 0, 0 };
assert Arrays.equals(sortOut(data1), data2);
assert !Arrays.equals(sortOut(data1), data1);
assert Arrays.equals(sortOut(data2), data2);
assert !Arrays.equals(sortOut(data2), data1);
}
}
//
// Returns the zero based index of the first occurance of
// any character of str2 in str1
//
// (c) 2016 Perry Anderson
// http://perryanderson.com/
//
public class LPMain001 {
static int indexOf(String str1, String str2 ) {
for (int i=0; i<str2.length(); i++ ) {
char c = str2.charAt(i);
if ( str1.indexOf(c)>-1 ) {
return str1.indexOf(c);
}
}
return -1;
}
public static void main(String[] args) {
String str1 = "adf6ysh";
String str2 = "123678";
String str3 = "12378";
assert indexOf(str1,str2) == 3;
assert indexOf(str1,str3) == -1;
}
}
- perry.anderson November 30, 2016