## Partial Products Of An Array

### October 20, 2017

We have another homework problem today:

Replace each element of an array with the product of every other element of the array, without using the division operator. For instance, given array (5 3 4 2 6 8), the desired output is (1152 1920 1440 2880 960 720).

Your task is to write a program to replace each element of an array with the product of every other element of the array, without performing division. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisements

Pages: 1 2

The algorithm is essentially the same as in the sample solution,

but this implementation exercises a few SRFI 133 procedures on

vectors.

Haskell also has

`scanr`

. Here’s my golfed version:a c solution by a noob:

Another Haskell solution that (it turns out) is almost identical to Graham Enos’ version. A minor difference is that I don’t use the init function, since tail will ensure that the second list is one element shorter than the first, so zipwith will never look at the last element of the first list.

Here’s a solution in x86 assembly.

Here’s a C program that calls the function.

Here’s example usage and output.

<

pre>

array:

[5, 3, 4, 2, 6, 8]

partial_products(array):

[1152, 1920, 1440, 2880, 960, 720]

<

pre>

Here’s the output again, hopefully formatted properly this time:

In Ruby.

Python 3, in the REPL.

a simple java solution below ..

//package com.mayank.randompractice;

import java.util.*;

public class CodeDay1_IDZ {

}

Simple recursive solution in Guile Scheme:

@Bavier: Very nice!

My solution:

array1 = [5, 3, 4, 2, 6, 8]

array2 = []

length = len(array1)

for i in range(length):

print(array2)

import java.util.*;

class partial_array_product {

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println("Please enter the size of your array : ");

int k = in.nextInt(), arr[] = new int[k], product = 1;

`}`