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

การพิมพ์ดัชนีคอลัมน์ที่จัดเรียงตามจำนวนศูนย์ในเมทริกซ์ที่กำหนดในโปรแกรม C


ได้รับอาเรย์ขนาด NxM โดย N แถว M คอลัมน์ งานคือพิมพ์จำนวนศูนย์ในแต่ละคอลัมน์หลังจัดเรียงตามจำนวนศูนย์ในคอลัมน์

เช่น คอลัมน์ 1 มี 1 ศูนย์ คอลัมน์ 2 ไม่มีศูนย์ คอลัมน์ 3 มี 2 ศูนย์ ผลลัพธ์คือ 3 1 2

ตัวอย่าง

Input:
0 0 0
1 1 1
1 0 1
Output: 1 3 2

คำอธิบาย

การพิมพ์ดัชนีคอลัมน์ที่จัดเรียงตามจำนวนศูนย์ในเมทริกซ์ที่กำหนดในโปรแกรม C

หมายเหตุ - เมทริกซ์ถือว่ามีดัชนีเริ่มจาก 1

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

#include 
#define row 3
#define col 3
using namespace std;
void sorting(int arr[row][col]){
    vector >count_zero;
    for (int i = 0; i < col; i++){
        int count = 0;
        for (int j = 0; j < row; j++){
            if (arr[j][i] == 0)
                count++;
        }
        count_zero.push_back(make_pair(count, i));
    }
    sort(count_zero.begin(), count_zero.end());
    for (int i = 0; i < col; i++)
        cout<< count_zero[i].second + 1 << " ";
}
int main(){
    int array[row][col] = {
        { 0, 0, 0 },
        { 1, 1, 1 },
        { 1, 0, 1 }
    };
    cout<<"sorted order of zeroes count is : ";
    sorting(array);
    return 0;
}

ผลลัพธ์

การรันโปรแกรมจะได้ผลลัพธ์ดังนี้:

sorted order of zeroes count is : 1 3 2