*Technically, this post could also go into #mental-calculation but since it involves computer code…*

The **Duplex method** aka **Dvanda yoga** is a **Vedic Maths** algorithm used primarily to compute **squares** or **square roots** mentally. You can find a forum post here that describes this process in more detail.

The below is an implementation in Swift 5.1. **I hope this will help some folks that have an easier time reading algorithms this way.** Also you can copy/paste and try out a few values to get a feel for the algorithm.

*If you decide to write your own solution in C++, Perl, Python, JavaScript, etc. please post it here for others, who are not familiar with Swift but might know your language.*

```
func duplex(_ values: [Int]) -> Int {
if values.isEmpty {
return 0
} else {
var array = values
var total = (array.count % 2 != 0)
? array[array.count / 2] * array.remove(at: array.count / 2)
: 0
while !array.isEmpty {
total += array.removeFirst() * array.removeLast() * 2
}
return total
}
}
```

### Examples

#### 1. print(duplex([]))

The condition `value.isEmpty`

will be true and the algorithm will terminate and return 0, as there is nothing to compute.

#### 2. print(duplex([3]))

The total is assigned the middle value of the array squared. This middle value is then removed and the condition `!array.isEmpty`

will be false and the algorithm will terminate, returning the initial value of 3^2=9 that is stored in `total`

.

#### 3. print(duplex([5, 3]))

There is no middle value, so the initial value of `total`

is 0. The first and last element of the array are multiplied and then doubled. After that the array is empty and the algorithm returns 5*3*2=30

#### 4. print(duplex([2, 5, 3]))

The middle value is squared (5^2=25) as in **case 2** above and removed from the array. Then the first and the last value are multiplied and doubled (2*3*2=12) as in **case 3**; the algorithm will terminate returning 25+12=37

### After that…

…cases will fall into either odd or even number of items passed in the array. If odd the item is squared and used to initialize `total`

and then removed; or there is nothing to do. Afterwards, we have an even number of items and multiply and double and finally remove the first and last item until the array is empty.