PHP: Commutative operation
The phrase "changing the order of the addends doesn't change the sum" is familiar to everyone from school. This principle is called the commutative law and is one of the fundamental laws of arithmetic.
What is commutativity
An operation is called commutative if the order of the operands doesn't affect the result: swapping the values gives you the same answer. An example of a commutative operation is addition.
<?php
print_r(3 + 2); // => 5
print_r(2 + 3); // => 5The same result confirms that the operation is commutative.
2 + 3 = 5 3 + 2 = 5
└──────────┬─────────┘
same result
2 - 3 = -1 3 - 2 = 1
└──────────┬─────────┘
different resultNon-commutative operations
But not all operations have this property. For example, subtraction is a non-commutative operation:
<?php
print_r(2 - 3); // => -1
print_r(3 - 2); // => 1Swapping the operands gives a different result.
It's all the same in programming
Commutativity in programming works exactly the same way as in arithmetic. PHP strictly follows mathematical rules.
Other non-commutative operations:
- Division: 8 / 2 ≠ 2 / 8
- Exponentiation: 2 3 ≠ 3 2
Examples in code:
<?php
// Division
print_r(8 / 2); // 8 divided by 2 = 4
// Exponentiation
print_r(3 ** 2); // 3 squared = 9Therefore:
- Always carefully check the order of operands, especially when working with unfamiliar operations;
- check commutativity experimentally instead of assuming it in advance.
Instructions
Write a program that solves two problems and sequentially prints the answers to the screen.
- A painter wants to paint 8 sections of a fence, each in one of 2 colors. How many unique coloring options exist? Use the exponentiation operator
**. - You and two friends (3 people in total) bought 9 pastries and want to split them equally. How many does each person get? Use the division operator
/.
Note that the results will be printed "stuck together" on one line without a space. We'll learn how to solve this problem in future lessons.
Tips
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Your exercise will be checked with these tests:
<?php
namespace HexletBasics\Arithmetics\Commutativity;
use HexletBasics\Exercise\TestCase;
class SolutionTest extends TestCase
{
public function test()
{
$expected = '2563';
$this->assertOutput($expected);
}
}Teacher's solution will be available in:
20:00
