อาร์เรย์คือคอนเทนเนอร์ขององค์ประกอบประเภทข้อมูลเดียวกัน ในอาร์เรย์ผลิตภัณฑ์ Puzzle จะพบผลิตภัณฑ์ขององค์ประกอบทั้งหมด
ใน Product Array Puzzle นี้ เราจำเป็นต้องค้นหาผลคูณขององค์ประกอบทั้งหมดในอาร์เรย์ยกเว้นองค์ประกอบ เงื่อนไขคือคุณไม่สามารถใช้ส่วน ตัวดำเนินการ และเก็บไว้ที่อาร์เรย์อื่น
สำหรับการแก้ปัญหานี้ เราจะสร้างผลิตภัณฑ์สองรายการ ผลิตภัณฑ์หนึ่งสำหรับองค์ประกอบด้านซ้ายทั้งหมด และอีกรายการสำหรับองค์ประกอบที่ถูกต้องทั้งหมด แล้วเพิ่มผลิตภัณฑ์ด้านซ้ายและขวานี้เพื่อให้ได้ผลิตภัณฑ์ที่ต้องการ
ตัวอย่าง
#include<stdio.h>
#include<stdlib.h>
void productfind(int arr[], int n) {
int *left = (int *)malloc(sizeof(int)*n);
int *right = (int *)malloc(sizeof(int)*n);
int *prod = (int *)malloc(sizeof(int)*n);
int i, j;
left[0] = 1;
right[n-1] = 1;
for(i = 1; i < n; i++)
left[i] = arr[i-1]*left[i-1];
for(j = n-2; j >=0; j--)
right[j] = arr[j+1]*right[j+1];
for (i = 0; i < n; i++)
prod[i] = left[i] * right[i];
for (i = 0; i < n; i++)
printf("%d ", prod[i]);
return;
}
int main() {
int arr[] = {10, 3, 5, 6, 2};
printf("The array is : \n");
int n = sizeof(arr)/sizeof(arr[0]);
for(int i = 0;i < n; i++){
printf("%d ",arr[i]);
}
printf("The product array is: \n");
productfind(arr, n);
} ผลลัพธ์
The array is : 10 3 5 6 2 The product array is: 180 600 360 300 900