Appearance
question:Write a Java program to find the sum of two arrays of length 10
answer:public static int[] sumArrays(int[] arr1, int[] arr2){ int[] result = new int[arr1.length]; for(int i=0; i<arr1.length; i++){ result[i] = arr1[i] + arr2[i]; } return result; }
question:Write a C program to simulate the producer-consumer problem.
answer:#define MAX_BUFFER_SIZE 10 // structure of buffer typedef struct { int buffer[MAX_BUFFER_SIZE]; int counter; } buffer_t; // initialize buffer void init_buffer(buffer_t *buffer) { buffer->counter = 0; } // produce an item and add it to the buffer void produce(buffer_t *buffer, int item) { if (buffer->counter < MAX_BUFFER_SIZE) { buffer->buffer[buffer->counter++] = item; } } // consume an item from the buffer int consume(buffer_t *buffer) { if (buffer->counter > 0) { int item = buffer->buffer[--buffer->counter]; return item; } return -1; }
question:Write a code that migrates data from one database to another
answer:import MySQLdb import pymongo # Establishing the connection mysql mysql_con = MySQLdb.connect( <MySQL connection details> ) cursor = mysql_con.cursor() # Establishing the connection mongodb mongo_con = pymongo.MongoClient( <MongoDB connection details> ) db = mongo_con.mydatabase # Migrating the data cursor.execute( "SELECT * FROM users" ) records = cursor.fetchall() for record in records: db.users.insert_one({ 'name': record[0], 'age' : record[1], 'email': record[2] })
question:mplementation the quicksort algorithm using c++.
answer:// C++ code for quick sort #include <bits/stdc++.h> using namespace std; // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition (int arr[], int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) cout << arr[i] << " "; cout << endl; }