Daily Coding Problem 7MAY2020

I am subscribed to dailycodingproblem.com. From time to time I will share problems I attempt and have a discussion around it. My solution might have bugs or might not be the most efficient but it would be my attempt. Feel free to criticise.

Today's problem I got

This problem was asked by Uber.

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Follow-up: what if you can't use division?

This was my solution in javascript. I am using the Javascript for Android app.

var numbers = [1, 2, 3, 4, 5];
var total = numbers.reduce( (a,b) => a * b );

for (i = 0; i < numbers.length; i++)
console.log(divide(total, numbers[i]));

function divide (a, b) {
if (a == 0) return 0;
if (a < b) return 0;
if (b <= a) return 1 + divide(a-b, b);
}

I remembered from my uni days that division could be done by recursion and subtraction.

Comments

Popular posts from this blog

My notes from the book "Lessons from my life"

My notes from the book "Micro Habits"

Contentment

Mask

My Experience Setting Up FLOW's TG2492LG-FLO WIFI Modem