Monday, November 19, 2018

Better Search Strategy for Linear Complexity

Search is always an interesting question to solve depending upon the constraints of the problem.

Let's take up the following problem for discussion: You need to find within a given number of integers whether the sum of 2 integers is equal to a given sum.

A naive solution to this problem would be 

for (int i= 0; i less than n; i++ )
          for (int j=0; j  less than n; j++)         
               if(arr[i]]+arr[j] == sum)
             return true;
      }
}

The above solution would be of complexity O(n^2). Suppose if you have a large set of numbers the overhead would be huge;

The second alternative could be to sort the numbers and then have 2 pointers one moving from '0' other from 'n-1' both approaching each other with a logic that n-1 would move till the rightmost number is less than the sum while the leftmost would move from 0 towards the right so that

a[leftmost]+a[rightmost] == sum;

This strategy would have issues where you need to sort the numbers first which has its own complexity and the total complexity would be

sortComplexity + n log(n) .. where the binary search would cut the number by half each time which is logarithmic in nature.

If we were looking for a linear solution, we can have another alternative like,



  1. Take converse of each number (sum - current) 
  2. Store in a set (Hash Set in some cases) // which holds unique values
  3. Check if the coming numbers exist in the set already. 
  4. if the number exists return true else false.

This strategy would have a linear complexity since the search is linear and the lookup in a set as well is constant.

The implementation for this idea in python is below.

def search(givenList, s):
    complements = set()
    for i in range(len(givenList)):
         if givenList[i] in complements:
             return True
         complements.add(s - givenList[i])
     
    return False 


if __name__ == '__main__':
    given = [10, 7, 8, 24, 46, 3 , 86, 35]
    result = search(given,93)
    print(result)
    pass

Sunday, February 07, 2016

Polytheism in Hinduism


I observed the following while taking to this generation kids of Hindu parents.
  • The "rationality" induced by science into their minds without perspective for their religion / philosophy - largely since they are not indoctrinated like in case of other religions; Which is good and bad as well (I will talk about this as content of my writings)
  • Atheistic overtures or to say the least Agnostic assertions; 
While I respect their rationality and assertions, I found that its not based on understanding of Hinduism; The first questions I often encounter 
  • Why do we have so many gods?
  • Why do they have so many different forms?
I will try to answer these questions as per my understanding; Hindu religion as I see is purely scientific and firmly ecological in its roots, let's delve into verses and facts..

'Ekam sad vipra bahudha vadanti' - Rig Veda, 1-164-146.
- "One alone exists, Sages call it by various names."

Bhagavadgita Chapter 6 : 30:
yo mam pasyati sarvatra sarvam ca mayi pasyati
tasyaham na pranasyami sa ca me na pranasyati  

- For one who sees Me everywhere and sees everything in Me, I am never lost, nor is he ever lost to Me.

“Akashat patitam toyam sagaram prati gacchati | 
sarva deva namaskaram Keshavam prati gacchati |”

- All the water fallen from the sky goes to the sea, similarly salutations to all the gods reaches to the one Lord Keshava;


"Shritischa Bhinnah smritayascha bhinnah 
maharishinam matayascha bhinnah"

Mind is not one. It perceives different things differently at different points of time; Also each mind finds it answers its own way. 


Dasavatara if you closely look is the evolution of the live from Matsya (fish, waterborne), Kurma (Amphibian), Varaha (One resides on Land), Narasimha (Neanderthal form), Vamana (lesser height), Parasurama, Rama, Krishna, (Balarama / Buddha), Kalki; 

We see close bonding with other forms as well in Hindu scriptures w.r.t. Trees like Neem, Pipal, Tulsi etc.. and the deities have different animals either as their vahana's (vehicles) or companions; We have names for them even; To say a few

  • Nandi - Bull of Shiva
  • Anindya (Rat - Vahan of Vinayaka)
  • Mayura / Ghana - Kartikeya
  • Dharma - Maa Durga
  • Garutmanta  - Lord Vishnu.
  • Megha (Cloud) - Lord Indra
At many instance we see that the Hindu texts talks about the all pervading soul including animate and inanimate. In fact Soundarya Lahari 1st shloka says 

śivaḥ śaktyā yukto yadi bhavati śaktaḥ prabhavituṃ
na cedevaṃ devo na khalu kuśalaḥ spanditumapi| - 

Lord Shiva, only becomes able, to do creation in this world along with Shakthi Without her, even an inch he cannot move; - The same is visualized by Oppenheimer while the nuclear bomb exploded over Nagasaki as the "Dance of Shakti";  

Includes even Charvaka's who are materialists and atheists; It doesn't say that the non-confidant shall go to hell; It always says we travel from a lesser truth to higher truth; In order to encompass all we have god in many forms. 

It raises to the next level while saying "Aham Brahma Asmi" - Brihadaranyaka Upanishad of the Shukla Yajurveda;
 Vidyaranya in his Panchadasi (V.4) explains:
स्वतः पूर्णः परात्माऽत्र ब्रह्मशब्देन वर्णितः |
अस्मीत्यैक्य-परामर्शः तेन ब्रह्म भवाम्यहम् ||
"Infinite by nature, the Supreme Self is described here by the word Brahman; the word asmi denotes the identity of aham and Brahman. Therefore, (the meaning of the sentence is) "I am Brahman."
But comprehending the concept is tough and not easy for everyone. Hence while it says Brahman is one, Hinduism lays down the path to realization for each in their own way and form;  It says the soul is immortal and it is the same soul which goes through many lives and forms (including animals) to realize that it is the same Brahman or part of Paramatma;

The Abrahamic religions while agrees that Animals might as well have soul; The soul of the God is not the same as that of Humans let alone the animals. The word used in the Quran to signify a human's innate non-physical essence or soul, is 'nafs', not 'ruh'. Ruh refers to devine soul and nafs that of the Human's. Animal and vegetable souls are dependent entirely on matter for their operation and being. They cease to exist at death. (There's no "doggie heaven.") Only man is made in the image of God, partaking of the divine nature:

  • “Then God said, “Let Us make man in Our image, according to Our likeness; and let them rule over the fish of the sea and over the birds of the sky and over the cattle and over all the earth, and over every creeping thing that creeps on the earth.” God created man in His own image, in the image of God He created him; male and female He created them.” (Genesis 1:26–27)
  • Man can kill animals, but not man because of this difference of image:
    • Whoever sheds man’s blood, By man his blood shall be shed, For in the image of God He made man.” (Genesis 9:6)
    • “But these, like unreasoning animals, born as creatures of instinct to be captured and killed, reviling where they have no knowledge, will in the destruction of those creatures also be destroyed,” (2 Peter 2:12)
    • “But these men revile the things which they do not understand; and the things which they know by instinct, like unreasoning animals, by these things they are destroyed.” (Jude 10)
Going by the above you can clearly see that Hinduism is firmly scientific and it follows Newton's 3rd law and the law of equilibrium in the sense of karma for all souls. // Another topic in series.

I hope this note has brought out the  logically answers the questions above.  Feel free to share your thoughts and questions.

Tuesday, February 22, 2011

Principles vs Rules

 

Recently I had an interesting question.. “We heard about design patterns but what are design principles?”

I would try to answer this question in a 2*2 matrix..

principles vs rules

The above matrix essentially talks about 2 things.

  1. Principles: They revolve around the primary focus of the project. These are like
    1. QOS – Quality of Service concerns, they focus around how many number of concurrent users, how many transactions per sec., whats the allowable downtime etc.. this essentially talks about each layer and what the project is looking in terms of numbers
    2. Functionality of the system that is developed – whether captured perfectly or not.
    3. Is the architecture extendable
    4. Are we giving plugging points
    5. How is the risk being mitigated in the project at several points
    6. What are the back up / back out plans
    7. How is the client satisfaction safe guarded for  repeatable business
  2. Patterns : The rules or patterns of good standards.
    1. What are the patterns at each layer
    2. These can be OO related / Database related / libraries related
    3. Reference architecture wise..
    4. Agreed upon development environment i.e. Code Coverage / Unit test coverage etc.

So essentially these are orthogonal, even if I have a very well defined architecture, that might get the QOS screwed. Once the QOS is screwed then its as good as dead since we can’t make ahead way with the project and the client can’t use the product.

I see that QOS must be the heart of the system that’s being developed. With Functionality being safeguarded. These 2 things when are backed with the Rules that make a perfect project.