Sunday, October 11, 2015

In the grasshopper problem, we discussed yesterday, we can now observe that the number of points = 2008 in the given set M happens to be the maximum possible value that  a grasshopper can choose not to land on. For points 1 to 2009, the grasshopper necessarily lands on a point from M.
This follows from the two facts we deduced- First the number of points from M that appear in a permutation of the m+1 th  interval is greater than or equal to two times 1005 - m  because there are two landing points by which a length d can be realized. And Second there are 2008 points in M must be greater than sum of all the points up to and including the m+1 th interval which by our greedy strategy, is m+1 times the value we computed in first. Consequently 2008 is the maximum possible value for M.
Let us now look at an alternate way to solve the problem - one based on induction.
To do this we recognize that the problem implies a strengthening of itself. Instead of saying the cardinality of M = 2008, we can assume that the intersection set of M and (0,s - a(min)) is less than or equal to n where a(min) is the minimum of the number of points a1, a2, .. .an+1,s.
Now we can prove that the grasshopper never lands on a point from M in the following way:
For n = 0, we don't have to prove anything
For n > 1, by our strategy, an+1 < an < an-1 < .. < a2 < a1
Let us call this set of all the points so far as T(n+1) instead of the all inclusive M. Also T(n+1) = s
Now we make a claim that  for some m belonging to 1 to n+1, the grasshopper is  able to do at least m jumps without landing on a point of M and in addition, after these m jumps, he has jumped over at least m points of M.
m cannot be n + 1 because the max number of points in M is n.
Therefore we call n'  = n - m the remaining number of forbidden points which can be carried out in n' + 1 jumps. we shift the origin each time to execute this. This proves the claim.
This set  of points k  from 1 to n+1 such that the grasshopper can skip all the points except  for the last by arranging his jumps can be called 'smooth'.
We know that k = 1 is smooth and evident. If we can prove that k works for largest k* = n + 1, the proof is complete.
We claim that Tk*  belongs to M and the number of points in the intersection of M with (0,Tk*) is greater than or equal to k*
If there were Tk* not belonging to M, any sequence of jumps that verifies the smoothness of k* can be extended by appending ak* + 1, which is a contradiction  to the fact that k* is maximum. The second part of the claim above follows from the fact that if the number of such points were less than k* then there exists k* - 1 instead of n, the grasshopper is able to reach Tk*1 - a1 with k* jumps of lengths without al. Therefore k*+1 is also smooth which is  a contradiction.
The third claim made now is that it is sufficient to consider the case M intersection (0, Tkmin-1)  which should have less than or equal to kmin - 1 points.
This follows from the above claim because we are using the minimum kmin. Although we don't go into the formal proof for claim 3, we can intuitively follow it from the claim 2.
Now with claim 3 and the strengthening mentioned above, we have kmin - 1  instead of n, the grasshopper is able to reach Tkmin + ar - ax by kmin jumps without landing on any point of M. From there he is able to jump to Tkmin + ar and therefore we reach a situation as in claim 1 with m = kmin + 1 which completes the proof.

Saturday, October 10, 2015

A grasshopper jumps along the real axis. He starts at point 0 and makes 2009
jumps to the right with lengths 1; 2; : : : ; 2009 in an arbitrary order. Let M be a set of 2008
positive integers less than 1005 * 2009. Prove that the grasshopper can arrange his jumps in
such a way that he never lands on a point from M.

Let us make a set of landing points for the grasshopper.
We look into the case when M does not contain numbers divisible by 2009.
We fix the numbers 2009k as landing points k = 1, 2, .... 1005
Consider the open interval I-k = (2009(k-1), 2009k)
We show that we can choose exactly one point outside of M as a landing point in 1004 of these intervals such that all lengths from 1 to 2009 are realized.
By excluding one interval from the 1005, we say that 2009 will indeed appear.
And each interval is length 2009 so a number d picked form 1 to 1004 is sufficient to guarantee that 2009-d  will also be picked. therefore 1004 is enough.
We pick these points in a greedy way.
Let n-k be the number of elements that belong to the interval Ik. We order these numbers in a decreasing way, so let p1, p2 ...p1005 be a permutation of 1,2, ...1005 such that the first is greater than the second which in turn is greater than the third and so on.
We leave the first interval out saying that it doesn't have a landing point now assuming that the other intervals have a landing point with d2, ... , dm where m = 1, .. 1004.
We show that there is a point in d2 .. dm that can be implemented with a new landing point in the m+1 th interval.
We do this by assuming the contrary.There are 1004-(m-1) other lengths obstructed by the np-m+1 points of M in the m+1th interval.

Each length d can be realized by two landing points namely the previous hop and the current hop.
This means that the number of elements of M that belong to the m+1 interval are greater than twice the number of points remaining to be chosen from the 1005 and written as twice * (1005-m)

Adding up the number of elements for each of the 1005 intervals equals the sum of 2008
so we know that 2008 is greater the number of points belonging to the interval from all of the m+1 intervals. and since each of these is greater than those chosen for the m+1th interval
we say that 2008 has to be greater than m+1 times the points chosen for the m+1th interval

Together the above two facts show that 2008 is greater than m+1 times twice * (1005-m)
This is minimum only when m = 1004 but the resulting value with m = 1004 is greater than 2008 - a contradiction.
Consequently there is a point in d2 .. dm that can be iplementd with a new landing point in the m+1th interval.

We now look at the other case when M does contain a number divisible by 2009. In this case we can say there is a number for which we can take multiples but it leaves a remainder less than 2009
Also we know from above that we have a landing point between 1005 and 2008.
So there are only two ranges we need to satisfy that they have a landing point
while everything else already has been shown to have it. One of this range is r shy of the multiple of 2009 and the other is 2009-r excess of the next multiple of2009. Note that both of them form a multiple of 2009. Hence we can use a similar logic as above for these ranges as well.
Thus we cover all the cases to show the grasshopper can arrange his jumps such that he can skip all point  from M











Friday, October 9, 2015

We review the book "The Responsible Entrepreneur" written by Carol Sanford. 

She introduces us to the entrepreneur who is responsible - a special breed whochallenge and refine cultural assumptions, laws and regulations and even the process of governance. As Kevin Jones, founder of SoCap said, this book is about being courageous and in fact he dares the readers to read and implement the bolduseful advice. 

Let us take a look at what Carol means by Responsible Entrepreneurs and what theyachieve. She says these entrepreneurs are required to do and think far beyond what is usually required of business leaders. The Responsible Entrepreneurs offers us this'blueprint'. By understanding the archetype  most aligned with their goals,entrepreneurs will learn how to grow their business and even change the game. 

In this book she includes the following: 

Some extraordinary people have changed the game for the better. 

How modern archetypes are altering the future. 
Why new measures of accomplishment are based on the success of the whole. 

She says such entrepreneurs have the courage to take on what they don't yet know how to do and the dedication to build the capability to do it. These entrepreneursare driven by the realization that the society and the planet need something big from them and that, if they don't rise to the challenge, the work may not get done. 

Entrepreneuralism is about personal agency and the development of the will. While entrepreneurs are inventing new products, industries, sources of capital and models of enterprise, the responsible entrepreneurs are doing that and more because they want to create the right platform and support an ecosystem.  They run successful business while deeply caring about the innovation that can not only help them secure their business but also transform the world. 

They enjoy developing the acumen needed to work on all parts of the business. 

They maintain their own motivation, getting stimulus, training and innovation when they need it. They hold a positive attitude. 

They are willing to take on big challenges that stretch them beyond what theycurrently know how to do and to ride the roller coaster of needing to continually rise to the occassion. 

They tend to focus the game changing aspirations in one of four distinct domains 

Industries - where the work is to disrupt and replace the automatic patterns 

Social systems - where the work is to move upstream to the causes of social problems and address them at their source. 

Cultural paradigms - where the enhance the belief systems into something moreholistic and embracing 

Foundational agreements - where the work is to renew and vitalize the deeper intention behind the governing documents, such as a corporate charter. 


From these four domains she draws parallels to four archetypes 

Warrior - The warrior protects the values of a community. In the business world, this work takes place within the industry. 

Clown - The clown pokes fun at collective self-centeredness and unconsciousness,opening space for humility and heartfelt appreciation of others. 
Hunter - The hunter perpetuates life by strengthening the mutual exchange between the tribe and the natural world. 

Headman - The headman awakens the individuals to their potential and inspiresthem to work with others in order to contribute to something larger thanthemselves. 


The four archetypes are all necessary to the healthy functioning of the society. Infact if any one of them is missing, the society becomes vulnerable. 


To the entreprenueur, these archetypes translate into four unique roles as follows: 

The warrior who changes an industry is the realization entrepreneur. He is driven by the vision of an improved reality. 

The clown who changes social systems is the reconnection entrepreneur. She reveals the gap in our cognition regarding the impact of existing social systems 

The hunter who changes cultural paradigms is the reciprocity entrepreneur. She tries to strike a balance between what is taken and what is given. 

The headman or headwoman who changes the connection to foundation agreements is the regenerative entrepreneur.  She seeks to reveal and evolve the inherent potential of founding agreements that create the accepted structures within which the society operates. 


The four roles do different work. For each of them the author takes examples and the principles or pillars that they operate on. 

A realization entrepreneur transforms an industry by renewing its purpose andvalues. The warrior archetype embodies this. Her four pillars are: 


Perfecting an industry: The first thing that a realization entrepreneur transforms is her goal – from making just a better product to one that satisfies the customers and the success of the industry stakeholders. She anticipates what has not been realized or wanted. 


Integrity beyond reproach: A realization entrepreneur must also upgrade thesources from which the business actions originate. By being transparent, she harbors the trust and respect that is needed to fulfil the role of industry transformer. 


Principled Precision: The work of a realization requires rigor and precision.Precision comes from being true to the nature of the work. 


Full dress inspection: This is about readiness to engage in a wider field of action.  This is a sign of maturity if the company is well prepared and able to be at the top of the game and everyone participates in it. 


A reconnection entrepreneur goes beyond the products and services by finding theunderlying causes rather than the symptoms. He goes both upstream and into the
future to see how to bring about a systemic change and to make them accessible andintelligible to us. 


His four pillars are : 


Evoking conscience: He cultivates the virtue of relentless caring because that willgive him the tenacity to work in this arena. 


Relinquishing attachment: Learning to see and relinquish attachments requiresdisciplined practice. Attachments can build walls and run the show, so we must bediligent in controlling it. 


Evolving potential: He tries to understand how the system he wants to affect behaves when it is healthy. 


Destabilizing thinking to invite reflections: He breaks peoples unconscious thoughtpatterns and attachments. 


The reciprocity entrepreneur is an expansionist and a fosterer. He will illuminate the larger whole within which a business is embedded. He will bring into a group whatever is outside it that will improve its health and continued evolution 


His Pillars are  

1) Wholeness: this  is the overarching goal for this entrepreneur 

2) Significance: He has to step up one or two levels of system to meet theexpectations of the shareholders 

3) Destiny : He knows the evolution of the group and that’s what he improves 

4) Camaraderie : He uses this to foster the group for ambitious change effort 


Lastly, a regenerative entrepreneur acts as  a headman or headwoman. She revitalizes the people and is focused on the core purpose of governance that provides structure stability and opportunity to all. 

Her pillars are: 

1) Transformation : This is the overarching goal for this role. 

2) Accomplishment: She enables the accomplishment of her downstreamcustomers 

3) Impossible dream: She dares to think the impossible in order to change the world 

4) Dialogue:  She works on change through skillful engagement rather than top down directives. 


With these four different roles, you target the four different domains that makes youa Responsible Entrepreneur 

node* BuildTree(int values[], int count, int start, int stop)
{
if (start > count) return NULL;
node* current = (node*) malloc(sizeof node);
memset((void*) current, 0, sizeof node);
current->value = values[start];
if (start >= stop) return current;
int left = start + 1;
int right = stop;
for (int k = start+1; k < stop; k++)
if (values[k] > current->value){
right = k;
break;
}
current->left = BuildTree(values, count, left, right-1);
current->right = BuildTree(values, count, right, stop);
return current;
}


int main(int argc, char* argv[])
{
int values[255] = {0};
int count = 0;

readElementsInOrder((int*)values,&count);
for (int i = 0; i < count; i++)
{
printf("%d", values[i]);
}
printf("\r\nOutput:\r\n");

node* root = NULL;
root = BuildTree(values, count, 0, count-1);
printPreOrder(root);

printf("\r\nwith both children\r\n");
node* victim = getNode(root, 7); // with both children
treeDelete(root, victim);
printPreOrder(root);
printf("\r\nwith left child\r\n");
victim = getNode(root, 8); // with left child
treeDelete(root, victim);
printPreOrder(root);
printf("\r\nwith no child\r\n");
victim = getNode(root, 2); // with no child
treeDelete(root, victim);
printPreOrder(root);
printf("\r\nwith right child\r\n");
victim = getNode(root, 4); // with right child
treeDelete(root, victim);
printPreOrder(root);
printf("finish");
}

Thursday, October 8, 2015

#codingquestions
Tree operations
        typedef struct _node{
  int value;
  node* left;
  node* right;
 }node;
 node* treeMinimum(node* root)
 {
  node* current = root;
  while(current->left)
   current = current->left;
  return current;
 }
 node* treeParent(node* root, node* z)
 {
  node* parent = NULL;
  node* current = root;
  while(current){
   if(current == z) return parent;
   if (current->value < z->value){
    parent = current;
    current = current->right;
   }else{
    parent = current;
    current = current->left;
      }
  }
  // z was not found in tree
  if (parent != NULL
      && parent->left != z
      && parent->right != z)
   parent = NULL;
  return parent;
 }
 node* treeSuccessor(node*root, node* z)
 {
  if (z->right)
   return treeMinimum(z->right);
  node* y = treeParent(root, z);
  while (y && z == y->right)
  {
   z = y;
   y = treeParent(root, y);
  }
  return y;
 }
 node* treeDelete(node*root, node* z)
 {
  node* y = NULL;
  node* x = NULL;
  node* px = NULL;
  node* py = NULL;
  if (z->left == NULL || z->right == NULL)
   y = z;
  else
   y = treeSuccessor(root, z);
  if (y->left != NULL)
   x = y->left;
  else
   x = y->right;
  //if (x != NULL)
  // px = py;
  py = treeParent(root, y);
  if (py == NULL)
   root = x;
      // root->value = x->value;
      // root->left = x->left;
      // root->right = x->right;
      // delete x;
  else if (y == py->left)
      py->left = x;
  else
   py->right = x;
  if (y != z)
   z->value = y->value;
  return y;
 }
 bool exists(node* root, int val)
 {
  if (root == NULL) return false;
  node* current = root;
  while(current)
  {
   if (current->value == val) return true;
   if (current->value < val) current = current->right;
   else current = current->left;
  }
  return false;
 }

 void readElementsInOrder(int* pValue, int* pCount)
 {
  char buffer[255] = {'5',' ', '3', ' ','2', ' ', '4', ' ', '7', ' ', '6',' ', '8'};
  sscanf(buffer, "%s");
  char seps[] = " ";
  char* token = NULL;
  //int values[255];
  int* values = pValue;
  token = strtok(buffer, seps);
  int i = 0;
  while (token != NULL)
  {
   values[i] = atoi(token);
   token = strtok(NULL, seps);
   i++;
  }
  *pCount = i;
 }

 for (int i = 0; i < count; i++)
 {
  printf("%d", values[i]);
 }

5324768

Wednesday, October 7, 2015

[IMO Shortlist 2013, C3] 
A crazy physicist discovered a new kind of particle which he called an imon. Some pairs of imons in the lab can be entangled, and each imon can participate in many entanglement relations. The physicist has found a way to perform the following two kinds of operations with these particles, one operation at a time. 
(i) If some imon is entangled with an odd number of other imons in the lab, then the physicist can destroy it. 
(ii) At any moment, he may double the whole family of imons in the lab by creating a copy I’ of each imon I. During this procedure, the two copies I’ and J’ become entangled if and only if the original imons I and J are entangled, and each copy I’ becomes entangled with its original imon I; no other entanglements occur or disappear at this moment.  
Show that after a finite number of operations, he can ensure that no pair of particles is entangled. 

The imons and their cloning are better visualized with a  data structure that represents the entanglements and the imons. We therefore use a graph with vertices as imons and edges as entanglements. Further, in order to differentiate every imon, we color them each differently. From graph coloring we know that a graph with n vertices can be colored with n colors so that every two connected vertices have different colors. 
Now if we could reduce these colors to just one it would mean a graph with no  edges – our desired goal. 
In other words, our strategy is to assume a graph G that admits proper coloring for n colors so that no two connected vertices have different colors and then show that a sequence of operations can result in a graph which admits coloring of n-1.  
To show this we do the following: 
We repeatedly apply operation 1 to any appropriate vertices  until there are no more. This  reduces the number of vertices and results in a graph with all even edges. Since this is a subset, it will still honor a proper coloring in n colors. We fix the colorings. 
Now we apply the second operation to the graph. This doubles the vertices but now we can still color them differently using n colors because for the new vertices around an original vertex of color k,  we color them with  k+1 mod n. The original vertices have different colors. Their clones also have different colors from the original now. Furthermore between the clones the coloring will be different because n > 1.  And finally all the vertices have now od d number of edges. Therefore those vertices that have the color n can now be destroyed leaving the graph with coloring in n – 1 colors. 
When we repeatedly reduce the colors with the above strategy, we are left with vertices and no edges as required. 
#codingexercise
Print count of headers listed in a file

#include "stdafx.h"
#include "stdio.h"
#include "string.h"

static int Hash (const char * pSrc, size_t len);

int main(int argc, char* argv[])
{
static const char filename[] = "foo.txt";

static const int MAX_COUNT = 255;

static int frequency[MAX_COUNT] = {0};

FILE* fd = fopen(filename, "r");

if ( fd != NULL )
{
char line[MAX_COUNT + 1];

while ( fgets(line, sizeof line, fd) != NULL )
{
char* p = strchr(line, ':');

if (p != NULL)
{
frequency[Hash(_strlwr(line), (size_t)(p-line))%MAX_COUNT] += 1;
}
}

fclose(fd);

char header[MAX_COUNT + 1] = {0};

printf( "Enter the header:\n " );

scanf("%255s", header);

header[MAX_COUNT] = '\0';

printf( "%s occurs %d times.\n", header, frequency[Hash(_strlwr(header), strlen(_strlwr(header)))%MAX_COUNT] );
}

return 0;
}

static int Hash (const char * pSrc, size_t len)
{
  size_t res = 0;

  while (len--) res = (res << 1) ^ *pSrc++;

  return (int)res;
}


If we want to print all headers by sorted order, we could do something like this:
#dirty
typedef struct _headers {
char header[MAX_COUNT+1];
int hash;
int frequency;
} headers;
int comp (const header * elem1, const header * elem2)
{
    int f = elem1->frequency;
    int s = elem2->frequency;
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}
int main(int argc, char* argv[])
{
    headers* x  = (header*) malloc(MAX_COUNT * sizeof(headers));
    memset((void*)x, 0, sizeof headers);
    
    qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);

    for (int i = 0 ; i < MAX_COUNT ; i++){
        headers[i] = malloc(sizeof(struct headers));
        // populate header and frequency
    }
    qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);
    // print headers encountered in sorted order
    for (int i = 0 ; i < MAX_COUNT ; i++){
        if (x[i]){
           printf("%s",x[i]->header);
        }
    }     
    return 0;

}

Tuesday, October 6, 2015

[Bulgaria 2005]

For positive integers t, a, b, a (t, a, b)-game is a two player game defined by the following rules. Initially, the number t is written on a blackboard. In his first move, the first player replaces t with either t – a or t – b. Then, the second player subtracts either a or b from this number, and writes the result on the blackboard, erasing the old number. After this, the first player once again erases either a or b from the number written on the blackboard, and so on. The player who first reaches a negative number loses the game. Prove that there exist infinitely many values of t for which the first player has a winning strategy for all pairs (a, b) with (a + b) = 2005.

Note that the players subtract a or b from the given number so if they were to alternate the number would keep reducing by 2005 each time. Its easy for any player to know whether the number substracted was a or b because the previous number and the new number are both on the board one after the other. The winning player has to ensure that the number reduces by 2005 by alternating a or b as per the previous move of the opponent.

In other words, if the winning player has a strategy for x then he has a winning strategy for x + 2005k
Since k can be a multiple of 2005, there are infinitely many numbers possible for this player with the above winning strategy.

The players reduce the numbers by a or b so ultimately there is a value v1 or v2 possible before the number becomes negative. Every other number on the board is therefore a multiple of v1 + a , v1 + b, v1 + a+ b or v2 +a , v2 + b and v2 +a + b.

If it is v2, we call it a favorable position and the first player wins for v2. we say that the strategy works for him.

If it is v1 then the first player. he will win only if v1 +a + b = v2 and v1+a and v1+b are not favorable but that means v1 + a - b and v1 + b - a are favorable but that means v1 + a and v1 + b are favorable which is a contradiction.