Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. (100 pts) Write a program to shuffle the elements of a 2-dimensional array an

ID: 643137 • Letter: 1

Question

1. (100 pts) Write a program to shuffle the elements of a 2-dimensional array and check if there are any duplicates in the array. (a) Declare a 2-dimensional array of loo integers with 10 rows and lo columns and insert numbers from 0-98 in order into the first 99 positions. First row should contain numbers 0-9 and second row 10-19 and so on. (b) Read an integer from the user and insert into the last position in the array. (c) Shuffle the array elements. You can do this by repeatedly picking two elements in the array and swapping them. You can pick a random row and a random column to randomly pick an element. Randomly pick 2 elements and swap them. Repeat the swap operation 100 times. Since we have 100 elements and we pick 2 at a time, doing time swap 100 times guarantees that very few elements will be in their original place after the shuffle. (d) Check if the array has any duplicate elements in it and print the indexes and values of duplicate elements if there are any. . You can work in groups of 2-4 . You can work on this during two weeks of recitations. . ?Write functions to shuffle the array and to check for duplicates. . Use scan f() and print f() only in main function Sample outputs for this recitation is provided below, if the user enters a number > 48. there won?t be any duplicates. Enter a number for last array location 120 There are no duplicates If the user enters a number 0-98, there will be a duplicate pair. Enter a number for last array location

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
   srand(time(NULL));
   int arr[10][10];
   int r1, c1, r2, c2, temp;
   int flag = 0, i, j;
   for(i = 0; i < 10; ++i){
       for(j = 0; j < 10; ++j){
           arr[i][j] = 10 * j + i;
       }
   }
   printf("Enter a number for last array location ");
   scanf("%d", &arr[9][9]);
   int val = arr[9][9];
   for(i = 0; i < 100; ++i){
       r1 = rand() % 10;
       r2 = rand() % 10;
       c1 = rand() % 10;
       c2 = rand() % 10;
       temp = arr[r1][c1];
       arr[r1][c1] = arr[r2][c2];
       arr[r2][c2] = temp;
   }
   for(i = 0; i < 10; ++i){
       for(j = 0; j < 10; ++j){
           if(arr[i][j] == val){
               if(flag == 0){
                   r1 = i;
                   c1 = j;
                   flag = 1;
               }
               else{
                   printf("data[%d][%d] = %d ", r1, c1, arr[r1][c1]);
                   printf("data[%d][%d] = %d ", i, j, arr[i][j]);
                   flag = 2;
                   break;
               }
           }
       }
   }
   if(flag < 2){
       printf("There are no duplicates ");
   }
   return 0;
}