Modulo operation and circular array

The modulo operation returns the remainder of one number divided by another. Modulo operator is a arithmetical operator, represented as %. One modulo operation example in math, 6 % 4 is 2.

The modulo operation is also used in circular array. When an array index modulo (or mod) the array length, the index that is larger than length will wrap around to the beginning of the array. Therefore an array becomes a circular array.

% is an operator that are the same cross most programming languages such as Java, JavaScript and Python. Here are two examples of modulo operation in programming. One is in math. The other is used in a circular problem.


1. FizzBuzz

A simple example using modulo operation is Fizzbuzz question.

Question:
Write a program that outputs the string representation of numbers from 1 to n. For a number is multiples of three, it should output “Fizz”. For a number is the multiples of five, outputs “Buzz”. For numbers which are multiples of both three and five, outputs “FizzBuzz”.

Java

JavaScript

Python

Output:

O Notation:
Time complexity: O(1)
Space complexity: O(1)


2. Round Robin Tournament Scheduler

Here is an example of using modulo operation in circular array – Round Robin Tournament Scheduler. If there are n competitors in tournament. Each competitor meets all others in turn. The details about how it works can be found in wiki. The basis of the algorithm is using circle method. We exclude the first competitor and make all other competitors to form a circle. after each round, the competitors in the circle move forward in 1 spot and compete with different ones.

Here we apply modulo operation to implement scheduling algorithm. We put all competitors except the first one in a circular array. The index of two competitor are Nth vs. Nth-from-the-last. For the first competitor, it is index 0 vs. roundNumber%circularSize. Please note, If there are odd number of competitors, a dummy competitor can be added to make total number of teams even. Whoever scheduled to play with “dummy” shall skip in this round.


round robin scheduler

Question:
There are 10 soccer teams that will play in the league. Read the names of the teams and develop a round-robin schedule so that every team plays with every other team over the next 9 weeks.

Java

JavaScript

Python

Doodle

round robin scheduler

Output:

O Notation:
Time complexity: O(n^2)
Space complexity: O(1)
n is number of teams


Download RoundRobinScheduler.java
Download RoundRobinScheduler.js
Download RoundRobinScheduler.py
Round Robin Tournament (GitHub)

What is Java modulo?

The modulo operation returns the remainder of one number divided by another. In Java, it uses % as modulo operator. For example, 6 % 4 = 2.

What is JavaScript modulo?

The modulo operation returns the remainder of one number divided by another. In JavaScript, it uses % as modulo operator. For example, 6 % 4 = 2.

Comments are closed