stadium problem: Provide algorithm to solve the problem - c

In a small stadium there are several thousand people in the stands. Devise a distributed algorithm
enabling the audience to count itself. Do not assume any particular geometry of the stadium except, if you want, that it is bowl shaped. Explicitly state your assumptions, then present your algorithm and analysis
I was assuming the members to be a linked-list and appending the counter and free(ptr)..I may be wrong...Kindly provide some useful insights
Thanks in adv...

Assuming everyone can talk to his/her neighbor (possibly over many empty seats) and that fans of team A are willing to speak to fans of team B, the following could work:
Everyone grabs his/her nearest neighbor, who is not already grabbed by someone else, to form groups of at most two people. Now everyone remembers the size of the group they are in (can be 1 or 2). Now a leader of each group is chosen in a way that he is able to communicate to a member of another group. The leaders of each group try to join their group with one other and each member of the two (now joined) groups remembers the sum of the members of each group (this can be done by broadcasting the new value to be added to the group). This process continues until there is only one group left. Upon termination of this process everyone knows the number of people in the stadium.
Hope this helps.

In a small stadium there are several
thousand people in the stands. Devise
a distributed algorithm enabling the
audience to count itself.
Feynman answer (see round manhole question): Have everyone shout "Several thousand!"

Here is another algorithm:
Let everyone count the others and himself.
Then, at the sound of a horn, each counter shout his count.
Keep the most shouted.
With this algorithm you can cope with errors.

For every column, a leader is chosen with the rule "the person in the row closest to the field is the leader" (these seats are usually filled). The leader initiates a count of the people in that column in the following manner:
1. Shake hand with the person directly sitting behind, and ask, "you?"
2. If no one is behind the person, the response should be 1, or else do step 1 with person behind, and the answer is one more than the answer from the person behind.
3. The leader immediately writes this number on a board, and holds it up
4. Among these leaders, the youngest person should start collecting these boards, and add them. If she meets a person younger than her collecting boards, the count till then is handed over to the other person. If the same age, the taller person would take over.

Everyone drops their dacks, and the "output" is available in the local paper the next day ala "N people arrested at world's first mass-streaker incident". (i.e. the application asks the system to do the work).
Each person picks one other person to fight, and first asks how many people they've knocked out. Winner finds another opponent, adds the defeated opponent's count. Last man (or woman) standing has the answer.
Everyone stands up, plucks a hair, then hands it to someone nearby with at least as many hairs before sitting down again. Standing people continue to seek others to give hairs too. The last person counts the hairs.
You invite people to grab a bag of minties from the canteen, then hand them around until they can't find anyone who hasn't had one, then drop the bag at a central point. Multiply bags * number-of-minties-per-bag - number-of-minties-left-in-bags.

Related

Queue optimizations between two queues

I'll try to explain my problem best I can. I'm having trouble with the final part of a college assignment and got really stuck.
The scenario is this: we have to build a simulation of an airport, in which a thread represents a flight (either departure or arrival), and have to optimize the arrivals and departures to minimize the time that it takes flights to land or depart.
So, onto the problem. I have all structures working, threads being created in the right moment, shared memory fully functional, message queue created and working, etc.
But now, I'm struggling with actually managing the flights. I created two linked lists, one for the arrivals and one for the departures. Each node of the linked list has a pointer to a space in the shared memory. Each of those spaces has the information relative to a flight (eta and fuel for arrivals, desired takeoff for departures). The arrivals linked list is sorted by ETA, and the takeoff linked list is sorted by desired takeoff. These linked lists are supposed to be a queue.
Problem is, I have no clue on how to manage them. There can be two departures or two arrivals at the same time, but there can't be both arrivals and departures at the same time.
I'm thinking of using semaphores, but I'm not sure if that's a good approach. I'd greatly appreciate any pointers in the right direction.
Thanks in advance!
EDIT:
We have a couple of specifications, but I thought this post would become too big as I was just looking for general headlines. In short, we have to minimize the number of times we need to order an arrival to hold (wait in the air), and "alternate between arrivals and departures to improve airport efficiency"
The specification is short. I understand this is for the purpose of keeping question small. But with this limited specification, I can only do some guess work here.
This problem seems to me similar to Old bridge problem.
An old bridge has only one lane and can only hold at most 3 cars at a
time without risking collapse. Create a solution that controls traffic
so that at any given time, there are at most 3 cars on the bridge, and
all of them are going the same direction. A car calls ArriveBridge
when it arrives at the bridge and wants to go in the specified
direction (0 or 1); ArriveBridge should not return until the car is
allowed to get on the bridge. A car calls ExitBridge when it gets off
the bridge, potentially allowing other cars to get on. Don’t worry
about starving cars trying to go in one direction; just make sure cars
are always on the bridge when they can be.
If you think so, you can find the solution to this problem here:
With some modifications you may be able to use it for your air traffic problem.
https://codeistry.wordpress.com/2018/04/18/old-bridge/

Optimal Solution - Programming Theory

I would like someone to explain different approaches to a simple problem and then I am going to try and implement it in PHP for a wider application.
I have five people who are choosing who gets what room in there are five rooms Grand, Large, Medium, Medium and Small.
Person 1 orders the rooms Grand, Large
Person 2 orders the rooms Large, Medium
Person 3 orders the rooms Large, Small
Person 4 orders the room Medium
Person 5 orders the rooms Large, Medium
Where a missing room is one they are not interested in.
What is the fairest way to choose who gets each room?
Use a heuristic to compute the matching value of every situation. E.g. if a person remains without a room, the value would be low or negative. If every person remains with the biggest room they ordered, the value would be the highest.
Compute this value for every situation and then take the situation with the highest value.
Fairness is not always well defined.
However, in this case it seems that a person can either get a room he requests, or not. Thus, one can make a strong argument that all solutions where the same number of people get a room they want are equally fair, and solutions where more people get a room they want are more fair than those where fewer get what they want (we are thus not giving any one person preference).
In your example there appears to be only one solution where everyone gets a room he wants. Thus, that is the 'fairest' solution.
The algorithm to find this isjust a depth-first-search (or, branch-and-bound if you need the speedup) that considers all possible allocations and finds a maximal one.

is there any stock management design pattern?

We want to design an e-commerce application, and we are mental about consitent stock numbers. We don't want our customers finding out, after they have bought an item, that that item is out of stock, that's a big thing here. The average order here has about 60 different items, which will makes things even trickier.
Let's imagine these two scenarios:
1st Scenario:
1) Customer C1 opens the online store and find a product he/she wants to buy;
2) That product is shown as "in stock" (but the current stock is 1);
3) Customer C1 puts 1 item in the basket;
4) Customer C2 gets into the website and select the same item (put in the basket), which is still marked as "in stock" (stock is still 1);
5) Customer C1 goes to checkout and confirms his purchase and the application decreases the current stock for that item to 0;
6) Customer C2 keeps buying items, let's say 35 other distinct items (it took 20 minutes to customer c2 to select the items he wanted);
7) Customer C2 goes to checkout and confirms this purchase, but now, the first item he bought is no longer available (and we CAN NOT sell it);
8) The application warns customer C2 that the first item is no longer available and that he has to check his basket;
9) Customer C2 gets pissed and close the browser without buying anything.
2nd scenario (but I think it is unnecessarily complex and buggy):
1) Customer C1 opens the online store and find a product he/she wants to buy;
2) That product is shown as "in stock" (but the current stock is 1);
3) Customer C1 puts 1 item in the basket (and the application decreases the current stock for that item to 0);
4) Customer C2 gets into the website and see the item he/she wanted is out of stock;
5) Customer C2 leaves the website;
6) Customer C1 keeps buying items (the stock decreases for it of these items);
7) Customer C1 closes the browser;
8) Every now and then some batch routine kicks in to remove the items which had decreased the stock but didn't get bought/confirmed.
We have just a few distinct products, but we have been selling about 30.000.000 items by phone, some products get sold as much as 2.000.000 every day, so the concurrency in the row responsible for the stock of that product might get many updates at the same time, so it's important we get a good performance.
Those are usual scenario, but is there any design pattern which gives the user a better experience while keeping the stock numbers consistent and yet yield a great application performance?
Any help will be much appreciated.
Cheers
First off, taking a step back, do you really need to solve the inventory management problem on the front end? Since you're selling large volumes of a relatively small set of products, it should be relatively easy to manage your inventory so that you are never out of stock or, if you are, it doesn't prevent you from fulfilling orders. There is a great deal of literature and examples that deal with calculating safety stock which requires just a bit of statistics to follow. It would make far more sense to me to focus your attention on giving the company the tools (if it doesn't already have them) to manage their inventory to prevent stock-out situations rather than trying to prevent them from happening in the sales portal.
That being said, I'm not quite sure that I follow your problem with the two scenarios you outline. Even if the database performance was flawless, if you have only 1 of item A in stock and you can't sell an item if it's not in stock, then one of the two customers, by definition, one of the two potential customers is going to lose out. If in the first scenario C2 is going to go away without buying anything if any of his 35 items are not in stock (which seems unlikely if he spent 20 minutes filling his cart), there is nothing you can do in the database to prevent that. Your interface could potentially have some AJAX that alerts them while they're shopping that one of the items in their cart is out of stock much like StackExchange notifies you while you're entering an answer that someone else has entered an answer. It's not at all clear to me, that telling C2 about the problem earlier is going to be beneficial-- if he's going to leave if he can't buy all 35 items in one transaction, he's going to leave no matter when you tell him that C1 bought the item. Realistically, there is no way to design the system so as not to disappoint one of the two customers in that case.
It might help if you can explain a bit more about why your application and your customers are so sensitive to stock-out situations. Most customers and most retailers are relatively accustomed to the fact that sometimes after placing an order they get notified that the retailer isn't going to be able to fulfill the order as quickly as they had expected and are given the option to cancel that part of their order, the whole order (assuming the remaining items haven't shipped yet), or to wait for the item to come back in to stock. Assuming that you do something to notify customers while they're browsing that inventory is relatively low (i.e. Amazon will tell you "N items in stock" if you're looking at an item for which they only have a handful of stock left), most customers are reasonably understanding 20 minutes when they get to the checkout and are told that the item is now out of stock since they knew in advance that they needed to order quickly. And most retailers are comfortable that even if they run out of stock of most popular items, they can still satisfy more requests than they have inventory in hand because they undoubtedly have new inventory arriving in the next day or two or they can rush an order for new inventory.
Your 1st scenario is what most companies do, and that's why stock management systems have the concept of a back order.
Your 2nd scenario is more beneficial to the customer, but will reduce your sales somewhat, as well as be more complicated to manage.
This really isn't a database decision. This is a management decision on how you want to handle your inventory.
Most relational databases supported with sufficient hardware can handle 2 million changes a day.
You could try to find out how other online retailers do it, and emulate them. For example, when Amazon is almost out of a product, they'll often display a notice saying, "Only n left in stock!" Try to find a product like that, then add it to your cart in one browser and use a different browser to see what happens to the inventory.
I am with Justin and Gilbert. This is more about logistics than front-end. There is also the amazon solution of saying "I want all these things shipped in the same packet", (i.e. that will take longer, as all the bits have to wait for the slowest one) or "send them separately, as soon as they are available". Basically, you give yourself time to restock.
I think the most infuriating scenario is booking airline/ferry tickets, and when you get to the paying part, they either time out, do "not have that price available anymore" or some such nonsense. Particularly annoying, as i is not exactly buying cruise boat propellers..
You could do a kan-ban routine, where you basically say that when you have 10 (or whatever) left of something, it is shown as "1 item remaining" in front end. That means that customerA and customerB buying at the same time both gets their stuff. And then the warning goes to procurement within the company: "we are "out" of objectN".
I would be interested in knowing what kind of stuff your client is selling, that most customer buys 60 objects.

What are the arguments against merging contact details into a single field?

We have a customer that insists on putting contact details, at this time first and last names, into a single field. Take, for example, Mr. Bob Smith and Mrs. Jane Smith. Mr. Bob and Mrs. Jane would be entered into the first name field and Smith would be entered into the last name. It gets messier if the contacts have different last names or if there is a hyphenated name. The customer only wants one contact record so they came up with this system and implemented it on their own.
Our system is designed around contacts and each individual person is intended to be an individual contact, even married. Due to some of the attributes we must assign to people and notes we need to keep, a contact-centric approach is best. The above issue occurs in about 1/3 of the cases we handle.
Internally, my team has discussed how to sell the customer on using the database the way it was designed. We listed form letters and contact lists as being the main reasons for keeping the data clean and in the fields we designed. For example, using our recommendation, the customer will have much more granular control over form letter creation and sorting of data.
Any suggestions for how we sell this to the customer?
Tell them what they can get out of your system is only as good as what gets put in. If they want to enter inconsistent data, the cost they'll pay down the line is the inability to generate letters or mailing lists in the future.
They may need to learn this lesson the hard way for themselves. I see more problems with switching the names, for example, entering Smith as the first name and Bob as the last.
Also, can you make both fields required?
It sounds like what they want to enter is similar to AddressLine1, AddressLine2. It's just a poor design, I thought you had 2 name fields but they would only enter data in one of them (the first name).
All you can do it try to help them when they ask for it. They'll get the system they deserve.
Just show your customer the normal forms for database design:
> http://www.phlonx.com/resources/nf3/
Tell him that these normal forms are designed to make the database more manageable over time and make it more flexible.
Can't you just create a view that holds First and Last name together? For some servers you can also create editable views... So your customer will be happy and data will be stored normalized.
I'd try to put it in terms of money and time. You're going to spend more time trying to keep duplicates out of a db with their design, more time building relevant reports or queries (constantly having to parse a block name field... do they want address all in one too?!?), more money to scrub the data (either themselves or someone else) if they ever want to send the data to a third party for analysis and metrics.
It sounds like they don't want to let go of their design, maybe partly because they understand it. You may want to try and meet them halfway somehow at first, and involve them in the process of making incremental improvements to the design. That way they can see and understand the benefits that right now may just be over their head, pushing them out of their comfort zone. They have to trust you with their baby :)
The best argument is that you won't be responsible for the behavior of the database unless they put things where they belong.
If they want to make a single mailing to each "household", then I'm sure your app can do that. (Probably already does.) Y'all just have to come to terms on what "household" means. Since there may be rented rooms or long-term guests, it doesn't always mean "only one mailing piece per address".
FWIW, I've been doing this stuff for decades, and I still find doctors and attorneys (and their staffs) the hardest people to deal with. One time, I walked out of a meeting (and, of course, lost the chance to bid on the contract) when a doctor's IT guy stood up, pounded his fist on the table, and screamed at me over and over, "Doctors are not people! Doctors are not people!".

How to keep an ordered list on the App Engine DataStore, in a way each entity knows its position on the list?

I have a ranking of people, based on points they earn. I need to tell each participant their position on the game for example,
John (1) - 170 points, Mary (2) - 160 points, Sarah (3) - 110 points
So John's the first one, Mary's the seconds and Sarah's the third. Now if Mary wins 20 more points, she'll be the first and john will be the second.
I'm trying to avoid having to run a task on cron to list and recalculate everybody's position.
My first try was to maintain a separate set of entities (PersonRank) so I wouldn't run into transaction problems, this rank would have the same key name, so I could db.get() by key. This entity would have the person's calculated rank, so when a Person receives points, I'd have to check if the next Person on the line has fewer points than me, and exchange places with me so that's true.
The problem is that Sarah, on the example, may have won 100 points, and is now number one. On the previous algorithm, I'd have to "walk" among a lot of entities, which means a lot of DataStore gets and puts (updating each involved Entity to the new position).
My next guess is maybe some kind of linked list with ReferenceProperties, maybe using the key names to denote the position.
Any clues about how to implement this ?
Much more complex than I though, but hopefully some guys at Google already implemented this solution - http://googleappengine.blogspot.com/2009/01/google-code-jams-ranking-library.html
As you self-answered 3 years ago, Google implemented this solution, but they did that for Python exclusively. There is unofficial solution for java, someone re-writted Python solution and decided to share it:
http://toolongdidntread.com/google-app-engine/using-googles-datastore-to-implement-a-ranked-scoreboard/
People say it works fine, I did not use it yet though. I might decide to use it in next few months so I could write more about it then. Be aware that both Java and Python solutions can deal with 3 requests/sec only (!).
More reading here:
https://cloud.google.com/developers/articles/fast-and-reliable-ranking-in-datastore/
Basically, it says Google upgraded the code so it could deal with 300 requests/sec, and they said if you buy their premium-level support, they could help you with that, but they will not share the ready-to-go solution with the mere mortals. Also, all the code and references are in Python, but thats pretty obvious.
There is still no better solution than those mentioned here, at least I'm not aware of any.

Resources