Skip to content

Commit

Permalink
add product of array except selft problem
Browse files Browse the repository at this point in the history
  • Loading branch information
jaroslaw-weber committed May 16, 2024
1 parent 6457f76 commit f1b5b7a
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 124 deletions.
4 changes: 2 additions & 2 deletions src/problem/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { editDistanceProblem } from "./list/editDistance";
import { coinChangeProblem } from "./list/coinChange";
import { longestIncreasingSubsequenceProblem } from "./list/longestIncreasingSubsequence";
import { minPathSumProblem } from "./list/minimumPathSum";
import { knapsackProblem } from "./list/knapsackProblem";
import { uniquePathsProblem } from "./list/uniquePaths";
import { twoSumProblem } from "./list/two-sum";
import { maxAreaProblem } from "./list/container-with-most-water";
Expand All @@ -16,6 +15,7 @@ import { maxSubArrayProblem } from "./list/maximum-subarray";
import { missingNumberProblem } from "./list/missing-number";
import { sumOfTwoIntegersProblem } from "./list/sum-of-two-integers";
import { numIslandsProblem } from "./list/number-of-islands";
import { productExceptSelfProblem } from "./list/product-of-array-except-self";

export const problems = [
maxProfitProblem,
Expand All @@ -26,7 +26,6 @@ export const problems = [
editDistanceProblem,
longestIncreasingSubsequenceProblem,
minPathSumProblem,
knapsackProblem,
uniquePathsProblem,
twoSumProblem,
maxAreaProblem,
Expand All @@ -37,4 +36,5 @@ export const problems = [

sumOfTwoIntegersProblem,
numIslandsProblem,
productExceptSelfProblem
].filter((x) => !x.hide);
83 changes: 0 additions & 83 deletions src/problem/list/knapsackProblem.ts

This file was deleted.

97 changes: 58 additions & 39 deletions src/problem/list/product-of-array-except-self.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@

// Imports specific utility functions and type definitions from the relative paths
import { Problem, ProblemState } from "../types";
import {
asArray,
as2dArray,
asSimpleValue,
asStringArray,
asValueGroup,
} from "../utils";
import { Problem, ProblemState, Variable } from "../types";
import { asArray, asSimpleValue, asValueGroup } from "../utils";

// Defines the interface for the input expected by the productExceptSelf function
interface ProductExceptSelfInput {
Expand All @@ -22,63 +15,86 @@ interface ProductExceptSelfInput {
export function productExceptSelf(p: ProductExceptSelfInput): ProblemState[] {
const { nums } = p;
const steps: ProblemState[] = [];
const length = nums.length;
const output: number[] = new Array(length).fill(1);
// Create the left (prefix) and right (suffix) products arrays
const productsLeft: number[] = new Array(length).fill(1);
const productsRight: number[] = new Array(length).fill(1);

// Helper function to create and log each step's computational state
function log(point: number, product?: number, result?: number[]) {
function log(p: {
point: number;
numsIndex?: number[];
leftIndex?: number[];
rightIndex?: number[];
outputIndex?: number[];
}) {
const v: Variable[] = [];
const { point, numsIndex, leftIndex, rightIndex, outputIndex } = p;
const step: ProblemState = {
variables: [asArray("nums", nums)],
variables: v,
breakpoint: point,
};
if (product !== undefined) {
step.variables.push(
asValueGroup("product", { product }, { min: 0, max: nums.reduce((a, b) => a * b, 1) })
);
v.push(asArray("nums", nums, ... (numsIndex??[])))
if (productsLeft) {
v.push(asArray("productsLeft", productsLeft, ...(leftIndex??[])))
}
if (productsRight) {
v.push(asArray("productsRight", productsRight, ...(rightIndex??[])))
}
if (result) {
step.variables.push(...asSimpleValue({ result: JSON.stringify(result) }));
if (output) {
v.push(asArray("output", output, ...(outputIndex??[])));
}
steps.push(step);
}

// Initial state log before the loop starts
log(1);
log({ point: 1 });

// Calculate the total product
let totalProduct = nums.reduce((a, b) => a * b, 1);
log(2, totalProduct);
// Fill productsLeft array (prefix products)
for (let i = 1; i < length; i++) {
productsLeft[i] = productsLeft[i - 1] * nums[i - 1];
log({ point: 2, leftIndex: [i, i - 1], numsIndex: [i - 1] });
}

// Create the output array
const output: number[] = new Array(nums.length);
// Fill productsRight array (suffix products)
for (let i = length - 2; i >= 0; i--) {
productsRight[i] = productsRight[i + 1] * nums[i + 1];
log({ point: 3, rightIndex: [i, i + 1], numsIndex: [i + 1] });
}
log({ point: 4 });

// Main loop to calculate the product except self
for (let i = 0; i < nums.length; i++) {
output[i] = totalProduct / nums[i];
log(3, totalProduct, output);
// Calculate the output array by combining prefix and suffix products
for (let i = 0; i < length; i++) {
output[i] = productsLeft[i] * productsRight[i];
log({ point: 5, outputIndex: [i], leftIndex: [i], rightIndex: [i] });
}

// Logs the final state with the output array
log(4, undefined, output);
log({ point: 6 });

return steps;
}

// Example implementation of the productExceptSelf function for demonstration and testing
const code = `function productExceptSelf(nums: number[]): number[] {
// Calculate the total product of the input array
let totalProduct = 1;
for (let num of nums) {
totalProduct *= num;
const length = nums.length;
const output = new Array(length).fill(1);
const productsLeft = new Array(length).fill(1);
const productsRight = new Array(length).fill(1);
for (let i = 1; i < length; i++) {
productsLeft[i] = productsLeft[i - 1] * nums[i - 1];
}
//#1 Initialize the output array
const output = new Array(nums.length);
for (let i = length - 2; i >= 0; i--) {
productsRight[i] = productsRight[i + 1] * nums[i + 1];
}
//#2 Calculate the product except self for each number in the array
for (let i = 0; i < nums.length; i++) {
output[i] = totalProduct / nums[i];
for (let i = 0; i < length; i++) {
output[i] = productsLeft[i] * productsRight[i];
}
//#3 Return the output array
return output;
}`;

Expand All @@ -89,7 +105,10 @@ const getInput = () => ({
});

// Export the complete problem setup including the input function, the computational function, and other metadata
export const productExceptSelfProblem: Problem<ProductExceptSelfInput, ProblemState> = {
export const productExceptSelfProblem: Problem<
ProductExceptSelfInput,
ProblemState
> = {
title,
code,
getInput,
Expand Down

0 comments on commit f1b5b7a

Please sign in to comment.