/*
The program must accept N integers as the input. Each integer is
given a weight. The program must sort the integers in ascending
order based on their weight and print the integers along with their
weights as the output as given in the Example Input/Output
sections. The weight of each integer is calculated based on the
conditions given below.
Conditions:
Weight = 5 if it is a perfect cube.
Weight = 4 if it is a multiple of 4 and divisible by 6.
Weight = 3 if it is a prime number.
Hint: Use stable sort (insertion sort, bubble sort or merge sort).
Boundary Conditions:
1 <= N <= 1000
Input Format:
The first line contains N.
The second line contains N integers separated by a space.
Output Format:
The first line contains integers with their weight as given in the Example Input/Output sections.
Example Input/Output 1:
Input:
7
10 36 54 89 12 216 27
Output:
<10,0>,<54,0>,<89,3>,<36,4>,<12,4>,<27,5>,<216,9>
Example Input/Output 2:
Input:
10
12 18 16 64 14 30 37 27 343 216
Output:
<18,0>,<16,0>,<14,0>,<30,0>,<37,3>,<12,4>,<64,5>,<27,5>,<343,5>,<216,9>
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int perfcube(int n)
{
int cubert = cbrt(n);
if (cubert * cubert * cubert == n)
{
return 1;
}
else
return 0;
}
int divis(int n)
{
if (n % 4 == 0 && n % 6 == 0)
{
return 1;
}
return 0;
}
int prime(int n)
{
int count = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
count++;
}
}
if (count == 2)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int n;
scanf("%d", &n);
int a[n];
int b[n][2];
// scanning n variables into array a
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// copying rows of a(1d array) to b(2d array)
int l = 0; // variable to traverse 1d array without its own loop
// traverse 2d array
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 2; k++)
{
if (k == 0)
{
// if k = 0 that is first col then store 1st col value of 1d array to 2d array
b[j][k] = a[l++];
}
else
{
// if other cols come then skip it
continue;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
if (j == 0)
{
if (perfcube(b[i][j]))
{
b[i][j + 1] += 5;
}
if (divis(b[i][j]))
{
b[i][j + 1] += 4;
}
if (prime(b[i][j]))
{
b[i][j + 1] += 3;
}
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
printf("<%d,>", b[i][j]);
}
printf("\n");
}
return (0);
}
我尝试像这样解决问题,最终得到这样的输出。 请帮助我从这里继续。
Output
<10,><0,>
<36,><4,>
<54,><0,>
<89,><3,>
<12,><4,>
<216,><9,>
<27,><5,>
我是编程新手
我尝试过这样解决问题,最终得到了这样的输出。
请帮助我从这里继续。
我不允许使用指针或像 qsort 这样的函数
如何以该格式对这些进行排序并打印 我最终得到的程序的输出。
输出应该与问题相符。
排序的核心是对两个项目进行比较。例如,如果 A < B, then A should come before B.
例如,我们可以重新排序
3 5 2 1 4
到
1 2 3 4 5
我们可以看到它是正确的,因为每个相邻对都保持 ≤ 关系。
这种关系是一个比较函数。用于标准排序的看起来像这样:
int compare( int a, int b )
{
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
您的作业要求您做的是将比较函数更改为不是直接比较值,而是比较应用于它们的函数的结果:
int compare( int a, int b )
{
a = weight_function( a );
b = weight_function( b );
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
您必须编写并实现权重函数,然后在排序算法中使用它。