25-11-2008, 21:46
|
מנהל
|
|
חבר מתאריך: 26.07.08
הודעות: 6,473
|
|
אוקי...
כיוון שזה איתגר אותי ניסיתי לכתוב תוכנית.
אני לא מתמצא בשפת C, וגם לא במונחים מקצועיים של תכנות, אבל זה מה שיש לי להציע...
הקוד לא מושלם, נשאר לך עוד 2 תנאים למלא, וכמה פינות לעגל (כמו בדיקות של מספרים קיצוניים כמו 0 או המספר הגבוה ביותר האפשרי, על מנת שלא ייצא לך שגיאה של איבר לא קיים ; או כמו שיפור יעילות).
(מצטער על האנגלית הקלוקלת, ועל אם יש הסברים לא הכי מובנים)
קוד:
#define L 20 // Number of integer pairs (or, Lines...) to receive
#define r 3 // r = return ; How much pairs to return?
#define r_P ((r % 2)? 1 : 0 ) // r is pair?
#define r_H (r/2) // Divide r by 2
int main(void)
{
int num1[L], num2[L], // Contains the data/numbers
idx1[L], idx2[L], // Pointers to data new index
pairs[L][r+1][2]; // The result/final array. The first member in pairs[L] has the data of the pair numbers. The rest members are the closest pair numbers.
for(int i=0; i<L; ++i)
scanf("%d %d", &num1[i], &num2[i]);
int tmp = 0; // Save temporary number
// sort num1[]
for(int i=L-1; --i; )
for(int x=i-1; --x; )
if (num1[i]<num1[x]) {
// Switch places
tmp=num1[i];
num1[i]=num1[x];
num1[x]=tmp;
// Save index
idx1[i]=x;
idx1[x]=i;
}
// sort num2[]
for(int i=L-1; --i; )
for(int x=i-1; --x; )
if (num2[i]<num2[x]) {
// Switch places
tmp=num2[i];
num2[i]=num2[x];
num2[x]=tmp;
// Save index
idx2[i]=x;
idx2[x]=i;
}
// Now we have the sorted numbers, with their new/old index
// So check the closest numbers, according to the new index of both numbers
for(int i=L-1; --i; )
{
int idx_diff = idx1[i] - idx2[i];
if (!idx_diff) // New index for both numbers is equal
{
if (r_P) // r is pair?
// Enter to the final array all the closest numbers
for (c=r_H; --c; )
{
pairs[i][c] = {num1[ idx1[i]+c ], num2[ idx2[i]+c ]};
pairs[i][c] = {num1[ idx1[i]-c ], num2[ idx2[i]-c ]};
}
else // r is NOT pair.
{
// Enter to the final array all the closest numbers
// AND validate the last pair of numbers... (who's greater?)
for (c=1; c<r_H-1; ++c )
{
pairs[i][c] = {num1[ idx1[i]+c ], num2[ idx2[i]+c ]};
pairs[i][c] = {num1[ idx1[i]-c ], num2[ idx2[i]-c ]};
}
if (
// (function abs() returns the absolute value of an integer)
abs( num1[ idx1[i]+r_H ] - num1[ idx1[i] ] ) + abs( num2[ idx2[i]+r_H ] - num2[ idx2[i] ] )
<
abs( num1[ idx1[i]-r_H ] - num1[ idx1[i] ] ) + abs( num2[ idx2[i]-r_H ] - num2[ idx2[i] ] )
)
pairs[i][r+1] = { num1[ idx1[i]+r_H ], num2[ idx2[i]+r_H ] ] };
else
pairs[i][r+1] = { num1[ idx1[i]-r_H ], num2[ idx2[i]-r_H ] ] };
}
}
// In the following cases, check the numbers in the middle location in the array...
// If the difference of locations is fewer than r, enter all the members in the middle
// and return back to the algorithm displayed in the first condition (above)
elseif (idx_diff > 0) // Index of num1 is greater than of num2
{
// EMPTY. Left for you.
}
else // Index of num2 is greater than of num1
{
// EMPTY. Left for you.
}
}
return 0;
}
|