Problem
1 2 3 4 5 6 7 8 |
//----------------------------------------------------------------------------------------------------------- // This is another SDE Job Interview programming problem. // Problem: Given an array of int {1,2,3,4,5,6,7,8,9...} build a function to swap its item. // // input: 1 2 3 4 5 6 7 8 9 0 // output: 0 9 8 7 6 5 4 3 2 1 // //---------------------------------------------------------------------------------------------------- |
Code
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 |
#include #include using namespace std; //define array size here: #define ARRAY_SIZE 101 int* swap (int* arr, int size) { //we are at the middle, return as it is. if (size <= ARRAY_SIZE/2) return arr; //update our location index. int index = size-1; //swap int temp = arr[index]; arr[index] = arr[ARRAY_SIZE-size]; arr[ARRAY_SIZE-size] = temp; //return the new swapped array return swap(arr, size-1); } int main() { //create a dynamic array of size ARRAY_SIZE ^ int* arr = new int[ARRAY_SIZE]; //fill the array for (int i = 0; i < ARRAY_SIZE; i++) { arr[i] = i; cout << arr[i] << "\t"; } cout << endl << endl; //swap the array and assign it to its swap version arr = swap(arr,ARRAY_SIZE); //print array. for (int i = 0; i < ARRAY_SIZE; i++) cout << arr[i] << "\t"; //clean up delete[] arr; //exit. //system("pause"); } |
screen
disclaimer: I did not have these questions during my interview or taken them from others’ interviews. I just found these questions posted online in one of the job blogs and I wanted to explain how would I solve them. I do not guarantee these are the real questions, or if the current question come with same level of difficulty.
Leave a reply