16 януари 2016 г.

Намиране на брой възли в двоично дърво (BST) - в дълбините на рекурсията...

Написах едно обяснение за това как точно работи рекурсията в една проста функция за намиране на брой възли. Нищо особено, просто "вникване на дълбоко" в изпълнението на рекурсията, която може да бъде объркваща понякога...

  1. Функция за намиране на брой възли
  2.  
  3.     int N(node *el)
  4.     {
  5.             if (el == NULL) return 0;
  6.             else return N(el->L) + N(el->R) + 1;
  7.     }
  8.  
  9.     Ако имаме дървото:
  10.  
  11.          5
  12.         / \
  13.        4   3
  14.       / \
  15.      2   1
  16.  
  17.     1. Първо, извикваме функцията със стойността на корена. Т.е -> N(5);
  18.     2. При N(5):
  19.             - el = 5 (не е NULL), затова НЕ връщаме 0
  20.             - връщаме N(el->L) + N(el->R) + 1
  21.  
  22.             Затова остава:
  23.                     return N(4) + N(3) + 1;
  24.  
  25.     3. При N(4) + N(3) + 1;
  26.             - разглеждаме само N(4)
  27.             - el = 4 (не е NULL), затова НЕ връщаме 0
  28.             - връщаме N(el->L) + N(el->R) + 1
  29.             - добавяме и останалата част от предишното извикване, която е 
  30. N(3) + 1
  31.  
  32.             Затова остава:
  33.                     return N(2) + N(1) + 1 + N(3) + 1;
  34.  
  35.     4. При N(2) + N(1) + 1 + N(3) + 1;
  36.             - разглеждаме само N(2)
  37.             - el = 2 (не е NULL), затова НЕ връщаме 0
  38.             - връщаме N(el->L) + N(el->R) + 1
  39. - N(el->L) и N(el->R) са NULL, така че N(2) връща само 1
  40.             - добавяме и останалата част от предишното извикване, която е 
  41. N(1) + 1 + N(3) + 1
  42.  
  43.             Затова остава:
  44.                     return 1 + N(1) + 1 + N(3) + 1;
  45.                
  46.     5. При 1 + N(1) + 1 + N(3) + 1;
  47.             - разглеждаме само N(1)
  48.             - el = 1 (не е NULL), затова НЕ връщаме 0
  49. - връщаме N(el->L) + N(el->R) + 1
  50.             - N(el->L) и N(el->R) са NULL, така че N(1) връща само 1
  51.             - добавяме и останалата част от предишното извикване, която е 
  52. 1 + 1 + N(3) + 1
  53.  
  54.             Затова остава:
  55.                     return 1 + 1 + 1 + N(3) + 1;
  56.  
  57.     6. При 1 + 1 + 1 + N(3) + 1;
  58.             - разглеждаме само N(3)
  59.             - el = 3 (не е NULL), затова НЕ връщаме 0
  60.             - връщаме N(el->L) + N(el->R) + 1
  61. - N(el->L) и N(el->R) са NULL, така че N(3) връща само 1
  62.             - добавяме и останалата част от предишното извикване, която е
  63. 1 + 1 + 1 + 1
  64.  
  65.             Затова остава:
  66.                     return 1 + 1 + 1 + 1 + 1;
  67.  
  68.     7. Броят на възлите е 5.

7 януари 2016 г.

MIND GAMES #4 - Как да спрем да ОТЛАГАМЕ (ефект на Зайгарник)


Когато започнем някаква задача, естествената човешка реакция е да искаме да я завършим. Това се нарича ефект на Зайгарник.

Следователно, за да спрем да отлагаме, просто трябва да ЗАПОЧНЕМ задачата.

Проблемът е, че всеки път когато искаме да започнем, нашият мозък ни залива с мисли като "това ще отнеме прекалено дълго" или "трябва да свърша 1000 неща преди да съм готов".

Решението е просто - трябва да направим само първата стъпка, която е абсурдно лесна. 

Трябва да учите за изпит, но нямате желание? Просто отворете учебника.
Трябва да спортувате, но изглежда прекалено трудно? Просто облечете спортните дрехи.
Трябва да станете от леглото, но гравитацията не ви позволява? Просто махнете одеялото.

Схващате идеята. Ако и първата стъпка ви се струва трудна - намерете още по-лесна такава. Просто започнете и наблюдавайте силата на ефекта на Зайгарник.

Изключението на ефекта е, че той губи своята сила, когато не очакваме да се справим със задачата или просто не виждаме смисъл от постигането и.

Например ако задачата ни е да разберем цялото съдържание на учебник или някакъв голям проект, изискващ повече от едно "започване". В такъв случай може да използвате Pomodoro техниката за продуктивност - работете върху задачата за 25 минути и си почивате 5 минути като повтаряте това колкото пъти е нужно. Тази техника е ефективна, защото сега целта ви няма да е "да прочета целия учебник", а вместо това "да издържа 25 минути четене от учебника". А ако се чудите каква ще е първата стъпка на тази задача - просто пуснете таймера!

Ако по-подробно вникнем в ефекта на Зайгарник, има 2 неща, които можем да научим:
- незавършените задачи стоят в паметта ни по-дълго;
- завършените задачи бързо изчезват от паметта.

MIND GAMES #3 - Принцип на контрастта













Ако направите неизгодна оферта на човек и той откаже, а след това му предложите "по-приемлива" сделка (дори и пак да е неизгодна за него), шансът да се съгласи е много по-голям.

Представете си следната ситуация. Отивате в магазин да си купите телевизор. Първото нещо, което виждате, е най-скъпия възможен телевизор, който магазинът предлага. Едва ли ще си купите точно него, защото е прекалено скъп. Но след като сте видели цената на този телевизор, ще сте много по-склонни да приемете цените на другите по-евтини телевизори и ще сте по-склонни да си купите един от тях. Защо? Защото цената им изглежда напълно нормална, имайки предвид тази на най-скъпия.

Мнението ни за всичко се базира на сравнения с други неща. Например когато кажем, че някой е умен, реално казваме, че е умен в сравнение с тези около него.

MIND GAMES #2 - "Длъжник съм ти" (правило за реципрочност)














Когато някой ни направи услуга, ВИНАГИ изпитваме желанието да я върнем по някакъв начин.

Вероятно сте попадали в ситуация, в която ви предлагат нещо “безплатно”, а след като го приемете ви молят за нещо в замяна и вие се чувствате сякаш не можете да откажете. Дори да са минали месеци от тази незначителна услуга, отново ще се чувстваме задължени да я върнем и вероятно ще сме склонни да я върнем със значително по-голяма услуга от наша страна.

Това е силата на правилото за реципрочност.

Повече може да прочете в книгата Influence: The Psychology of Persuasion на Robert B. Cialdini.

MIND GAMES #1 - "Направи ми услуга..."














Йо! Реших да почна да споделям някои интересни психологически трикове, които научих през годините. Някои от тях са доста манипулативни, но в същото време и изключително полезни, а може би дори и информативни (знаейки за тях ще можете и да се предпазите)!

---

Помолете някого за малка услуга. Това увеличава шанса по-късно да са склонни да ви направят дори ПО-ГОЛЯМА услуга, защото започваме да мислим "ако съм помогнал на този човек, значи има причина да го харесвам и следователно трябва да продължавам с това държание".

6 януари 2016 г.

10 Habits That Will Guarantee Your Long-Term SUCCESS!

Ето една статия, която написах преди няколко месеца, но не успях да публикувам, защото... не струва! :D Беше предназначена за mainstream сайт, така че стилът на писане е малко по-особен, но съдържанието си заслужава!

---

Everyone wants to be successful. But how are we supposed to go about it? We’re constantly bombarded with information – “just do this and you’ll be successful”. But is there really a quick path that is guaranteed to take us to success? Studies have shown that most of our behavior on a day to day basis is automatic – in other words, we don’t even think about most of the things we do, as they’re just a habit. And that’s the key component of success – what we do on a regular basis. As Aristotle said, “We are what we repeatedly do. Excellence, then, is not an act, but a habit.”. So, what are those key habits that every successful person does?

1. Reading
Reading is one of those activities that pretty much everyone knows that they should be doing, yet they dismiss it with a simple “I’ll do it later” excuse. But the fact of the matter is – you need to read. Reading makes you smarter, it inspires you and increases your knowledge of the world. It may even slow down the progression of Alzheimer’s disease. And it’s loads of fun to boot.

Think of it like this – someone sat in a room for hours and hours and they literally wrote down all of the things it took them years to figure out. Above that, they had editors by their side that made their content even more accessible to the average reader. What took the author years to figure out – you can easily absorb in a couple of days (depending on the length of the book) – how amazing is that?

You need to read. If you’re not used to reading, a good way of incorporating it into your daily routine is simply spending 20 minutes a day doing it. Is that too hard? Then start with 10. It’s only difficult in the beginning, but once your mind gets adjusted to it – you’ll be wishing you had started sooner.

Bill Gates claims to read for at least 1 hour  every night before going to sleep.



2. Exercise
It is crucial that you exercise on a regular basis. Your body is your temple and without a properly functioning body – how are you supposed to achieve your dreams? It’s very easy to come up with excuses not to do it, such as “I’m too tired” or “I don’t have the time for it”. Some might argue that it’s not even very wise to do it every day in the first place, because that would be putting too much pressure on your body and wouldn’t give it enough time to recover.

While it’s true that you should give your body some rest, making exercise a daily habit doesn’t mean that you should be going all-out in every session. Instead, whenever you feel like you have energy and time, give it all you’ve got, but on days when you’re just not feeling it – do a light stretch or some cardio to boost your immune system.

Again, the point is to make exercise a priority – small consistent efforts result in big changes over time. It’s better to exercise for 20 minutes 4 days a week than an hour and a half in one day. Consistency is critical.

Barack Obama says he exercises 6 times a week for 45 minutes by lifting weights and doing cardio. If the president can do it, why can’t you?



3. Meditation
If you’re like most people, you’re likely rolling your eyes right now. But meditation brings a lot of benefits – it improves your ability to focus, as well as control your emotions in stressful situations. The activity itself is the perfect stress-reliever. Above all else, meditation allows you to experience life’s tiny everyday moments in a way that you enjoy every bit of them.

How does it work? Simply sit in a comfortable position (contrary to popular belief, you needn’t even cross your legs) and stare at one point for about 20 minutes. To get the full benefit of it – try to not think (or better yet – simply focus on your breath), but if you do start thinking about having to pay your rent – do not judge yourself, but simply accept the thought and go back to the present moment.

Meditation is one of those crucial, yet underrated habits that are slow in delivering results, but if you stick with them long enough, you will be miles ahead of the competition and you will be more emotionally stable.

A lot of successful people start (or end) their day with meditation – Katy Perry, Hugh Jackman, Oprah Winfrey and many others.



4. Socializing
Talking to people every day is something a lot of us do automatically, but its importance cannot be stressed enough. Every day you have to make it your goal to advance your social skills in some manner.

Eye contact, listening to other people or just smiling at a stranger – it all adds up and helps you become a better communicator. Furthermore, human beings are social creatures (and unfortunately for us, that means we have to rely on others’ support occasionally. Socializing also makes you a better person in general, as you become more pleasant company for other people and as a result, you get more opportunities in life.

The main reason you should to this habit is because you won’t always be able to accomplish your goals on your own and therefore you’ll need to learn how to get your point across effectively. No one can do everything on their own. So just make it your goal to talk to as many people as possible throughout your day.

To further cement this idea into your mind – consider the following – every great leader in history was a powerful public speaker (Winston Churchill, Martin Luther King and others). But unfortunately, thanks to their extremely refined social abilities, that meant that even “bad” leaders had huge influence (people such as Adolf Hitler, for example).



5. Professional advancement
Regardless of what your current job is or what you plan to work in the future, you need to make it a habit to always be developing your professional skills. Always be on the lookout for what’s happening in your industry and how you can acquire knowledge that will make you a better, more efficient worker.

Do you aspire to be a computer programmer one day? Practice programming every day. Or perhaps you’re already working? Research every day on what new technology is available and how you can use it to your advantage to make your job and life easier. You’ll be a better and more productive part of your team.

Don’t fall into the trap of thinking that one day you’ll be “put on” and things are just going to happen for you. That’s not how it works for most people, unfortunately. Instead, focus on building your skills at an early age and when the time to shine comes, you’ll be ready and finding a suitable job will be a piece of cake.

Winston Churchill is an excellent example of balancing work and play. His routine allowed him to take breaks, but also to work like a machine, in order to master his craft.



6. Sleeping
“What? Sleep? How would that help with becoming successful?”. Sorry to burst your bubble, but getting at least 8 hours of sleep every night is crucial. Besides making you cranky and lowering your willpower, low sleep can dramatically decrease your productivity during the day.

You should try to sleep in a dark room, without allowing distractions to engage your mind right before it’s time to go to bed. Unfortunately, that means no Facebook or playing games on your phone right before sleep time, unless you want to decrease the quality of your sleep and feel exhausted in the morning.

If you’ve lost some sleep and can’t seem to catch up, consider taking a 20 minute nap during the day to boost your willpower and overall energy.

However, sometimes sleep can indeed be sacrificed, and that is only when you know you’re working towards realizing your dreams. Successful people such as Donald Trump slept for only 4 hours a night, but even though they paid a huge price, it did “pay off” in the end, did it not?



7. Relaxation and having fun
“All work and no play makes Jack a dull boy” (a quote from Stephen King’s The Shining). You need to think of activities that you can do solely for the enjoyment that they bring you, because while working is definitely important, taking a break from all of it is just as critical in the long-term.
Some activities that you can do just chill out include watching a movie (or a TV show), playing an instrument or a videogame, playing with your pet or even just a simple breathing exercise that will allow you to gather your thoughts and bring calmness to your mind, so that you can continue on with your tasks for the day.

Playing is not just for children – it’s something that is absolutely necessary if you plan to make it big! The bottom line is that you need to recharge your batteries or you’re going to burn yourself out.
George W. Bush is an avid painter and billionaire Richard Branson always finds time for his favorite sport – kite diving. Go and find some hobbies already, man.




8. Learn a new language
Learning a new language allows you to experience more of the world, simply because it gives you access to more resources. Unfortunately, it’s one of the most challenging habits to implement, as it takes quite a while for you to see some results.

The key to learning a new language is to be consistent and practice using it whenever possible, preferably every day. Thankfully, thanks to services like Duolingo, learning a language has become a straightforward process, which you can easily implement in your daily routine. Simply spend a couple of minutes each day practicing your language skills and the progress is sure to come faster than you’d expect.

Alternatively, you can try to watch cartoons in the language you’re trying to learn, as the words used there are relatively simple and slowly spoken.

According to statistics, the most popular and useful for business languages are Chinese Mandarin, Spanish and Arabic (and English, obviously).



9. Use a To-Do list
You always need to be thinking about what’s coming ahead. It doesn’t take extraordinary effort, you just need to have a personal to-do list (on paper or perhaps on your smartphone, as long as it’s easily accessible to you throughout the day).

Since pretty much everyone owns a smartphone nowadays, you can try various free Android apps, such as Any.do, Wunderlist and Todoist (also available on iOS). But if you’re not a fan of the whole smartphone craze, you can use sticky notes on your refrigerator or simply writing your daily tasks on a piece of paper and crossing them when they’re completed.

An important factor to consider is that you need to set deadlines for accomplishing these tasks. As they say, “A goal without a deadline is just a wish”. Also, make it a point to finish the hardest tasks first thing in the morning, as that is when you have the most willpower.

This habit is important, because it gives you a clear vision about what’s coming ahead and gives you small, achievable steps that you can do every day, in order to realize your dreams gradually. It also helps you to not feel overwhelmed and makes the whole process of starting much easier.



10. Save money and spend it wisely
For many people, success is defined financially and that’s why you need to become very good at managing your money. What that means is that you should always think whether a purchase you’re about to make is a good decision or not. On an even higher level, you also need to save money for future investments or even just for those “rainy” days.

Furthermore, savings add up over time. You might not see the point right now, but when you get incredibly sick one day unexpectedly or you get the crazy idea of starting your own business – you’ll be happy you started saving early.

The best way to save money is to set it aside as soon as you get it. Rather than waiting to see what’s left after you go on a shopping spree for Christmas, make it your personal goal to leave some aside for future endeavors.


You can use apps such as Expense Manager (Android / iOS) to track your income and expenses.