Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สร้าง Frequency Array ของหลักตัวเลขจาก x^1, x^2, ..., x^n ใน C++

คำอธิบายปัญหา

สมมติว่าเรามีจำนวนเต็มสองจำนวน x และ n เราต้องหาอาร์เรย์ที่มีความถี่ของตัวเลขดัชนีที่เกิดขึ้นใน (x^1, x^2,... x^(n-1), x^n) ดังนั้นถ้า x = 15 และ n = 3 ผลลัพธ์จะเป็น [0, 1, 2, 2, 0, 3, 0, 1, 0, 0] เนื่องจากเรารู้ว่า x^1 ถึง x^n ค่าคือ 15, 225 และ 3375 ดังนั้น frequency array คือ 0, 1, 2, 2, 0, 3, 0, 1, 0, 0

เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้:

  • รักษา frequency count array ไว้เพื่อเก็บจำนวนของหลัก 0 ถึง 9

  • เดินทางผ่านแต่ละหลักของ x^1 ถึง x^n สำหรับแต่ละหลัก ให้เพิ่ม 1 ไปที่ดัชนีที่ตรงกันใน frequency count array

  • แสดงอาร์เรย์

ตัวอย่างโค้ด

#include <iostream> #include <cmath> using namespace std; void digitCount(double val, long arr[]) {    while ((long)val > 0) {       long digit = (long)val % 10;       arr[(int)digit]++;       val = (long)val / 10;    } } void generateFreqArray(int x, int n) {    long freq_count[10]={0};    for (int i = 1; i <= n; i++){       double val = pow((double)x, (double)i);       digitCount(val, freq_count);    }    cout << "[";    for (int i = 0; i <= 9; i++){       cout << freq_count[i] << " ";    }    cout << "\b]"; } int main() {    int x = 15, n = 3;    cout << "The frequency array is: ";    generateFreqArray(x, n); }

ผลลัพธ์

The frequency array is: [0 1 2 2 0 3 0 1 0 0]