Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Daily Coding Problem: Problem #2
/*Good morning! Here's your coding interview problem for today. 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?*/ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { Console.WriteLine(AreEqual(MakeArray(new List<int>(){ 1, 2, 3, 4, 5 }), new List<long>(){ 120, 60, 40, 30, 24 })); Console.WriteLine(AreEqual(MakeArray(new List<int>(){ 3, 2, 1 }), new List<long>(){ 2, 3, 6 })); Console.WriteLine(AreEqual(MakeArray(new List<int>(){ 1, 2 }), new List<long>(){ 2, 1 })); Console.WriteLine(AreEqual(MakeArray(new List<int>(){ 1 }), new List<long>(){ })); } static List<long> MakeArray(List<int> list) { if(list.Count == 1) { return new List<long>(); } var upTo = Enumerable.Range(0, list.Count).Select(f => (long)f).ToList<long>(); var downTo = Enumerable.Range(0, list.Count).Select(f => (long)f).ToList<long>(); for(int i=0; i<list.Count; i++) { upTo[i] = i > 0 ? list[i] * upTo[i-1] : list[i]; } for(int i=list.Count - 1; i >= 0; i--) { downTo[i] = i < list.Count - 1 ? list[i] * downTo[i+1] : list[i]; } var result = Enumerable.Range(0, list.Count).Select(f => (long)f).ToList<long>(); for(int i=0; i<list.Count; i++) { if(i == 0) { result[i] = downTo[1]; continue; } if(i == list.Count - 1) { result[i] = upTo[list.Count - 2]; continue; } result[i] = upTo[i-1] * downTo[i+1]; } return result; } static bool AreEqual(List<long> a, List<long> b) { for(int i=0; i<a.Count; i++) { if(a[i] != b[i]) { return false; } } return true; } } }
run
|
edit
|
history
|
help
1
SQL import
.heap sort
Великий и могучий РУСЯЗ
Finding a Substring in a Main String
Sum of numbers in string
Main3
asxsd
extrefGenerate
CommandForce
uzyskanie daty poniedziałku