Coding Solutions

Problems and solutions with multiple programming languages.

Singleton: pattern or anti-pattern?

Many people consider the singleton an anti-pattern. Many others think it's part of the creational patterns family. I don't care about its definition and I think a singleton can be useful sometimes in the real world! Singleton design pattern is used when you want to have only one instance of a giv... [...]

Prime Number

Let's find if a number is prime. A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. The first few prime numbers are {2, 3, 5, 7, 11, ….}. Here we have some solutions: PHP: using bcmod and a for loop function isPrimeNumber(int $... [...]

Leap Year

Let's check if a year is a leap year. Rules for determining a Leap Year Most years that can be divided evenly by 4 are leap years. (For example, 2016 divided by 4 = 504: Leap year!) Exception: Century years are NOT leap years UNLESS they can be evenly divided by 400. (For example, 1700, 1800, and 1900 we... [...]

Fibonacci numbers

Let's see how to print the Fibonacci numbers. The formula expects we will have big numbers so we will be ready to print big numbers without any overflow error. Before showing some code, I want to leave some useful links: Fibonacci on Wikipedia Fibonacci Number           [...]

Prime Factors

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus pulvinar pharetra vestibulum. Proin aliquet justo sit amet mauris volutpat pellentesque. Proin facilisis consectetur tellus. In porttitor quis turpis vitae tempus. Aenean eget volutpat purus, vel cursus odio. Maecenas tempus, elit ac feugiat finibus, quam lectus pr... [...]

Factorial

The factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1. Examples: 4! = 4 × 3 × 2 × 1 = 24 7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040 1! = 1 Wikipedia. PHP: using gmp_fact function A native PHP function ca... [...]

Palindrome words

A palindrome is a word, number, phrase, or other sequences of characters which reads the same backward as forward, such as madam or racecar or the number 10801. Sentence-length palindromes may be written when allowances are made for adjustments to capital letters, punctuatio... [...]

FizzBuzz

The FizzFizz buzz is a group word game for children to teach them about division.[1] Players take turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number divisible by five with the word "buzz". Players generally sit in a circle. The player designated to go... [...]

Exchange array keys \ values

Exchange keys with values and vice-versa from an associative array can be a very common problem. Let's how we can solve it: PHP: Using the array_flip function This native function will do the job on the fly! <?php var_dump( array_flip( array('a', 'b', 'c') ) ); Javascript: using an... [...]