1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | #include <Windows.h> // rand #include <iostream> // cout #include <iomanip> // setw, setfill using namespace std; void RandomSeed(void); void RandomizeArray(int *ary, const int& size, const int& range); struct valLoc { int val; int loc; }; valLoc SearchNearestArray(int *arry, const int& stroke, const int& size); int main(void) { #define ArraySize 20 RandomSeed(); register int i = 0; int ary[ArraySize] = { 0 }; register int arySize = sizeof(ary) / sizeof(ary[0]); { cout << setw(20) << setfill(' ') << "Initial Array : "; for (i = 0; i < arySize; ++i) cout << ary[i] << " "; cout << endl; } RandomizeArray(ary, arySize, 10); { cout << setw(20) << setfill(' ') << "Randomized Array : "; for (i = 0; i < arySize; ++i) cout << ary[i] << " "; cout << endl; } valLoc found = SearchNearestArray(ary, 10, arySize); { cout << endl << endl; } return 0; } valLoc SearchNearestArray(int *ary, const int& stroke, const int& size) { register int dist, minDist = abs(stroke - ary[0]), loc; valLoc found; register int isMatched = false; for (register int i = 0; i < size; ++i) { if (stroke == ary[i]) { isMatched = true; loc = i; break; } dist = abs(stroke - ary[i]); if (dist < minDist) { minDist = dist; loc = i; } } found.loc = loc; if(isMatched) { found.val = stroke; cout << ">> Matched number " << found.val << " at [" << found.loc << "]" << endl << endl; } else { found.val = ary[loc]; cout << endl << ">> Failed to locate " << stroke << ". Nearest number is " << found.val << ", at [" << found.loc << "]"<< endl << endl; } return found; } void RandomizeArray(int *ary, const int& size, const int& range) { for (register int i = 0; i < size; ++i) ary[i] = rand() % range; } void RandomSeed(void) { LARGE_INTEGER SEED; ::QueryPerformanceCounter(&SEED); srand(static_cast<UINT>(SEED.QuadPart)); } | cs |
12/12/2015
[swift] c++, SearchNearestArray
피드 구독하기:
댓글 (Atom)
댓글 없음:
댓글 쓰기