How to randomly pick elements from an array in C? - c

I have an array of 6 rows and 20 columns :
char name[6][20];
And I enter the names with for :
puts("Enter with 6 names :");
for(i=0; i< 6 ; i++)
{
scanf("%19[^\n]%*c",name[i]);
}
After that, I need to randomly choose three names of the array and display them in the screen. How can I do that ?
PS : Different from the other questions similar to that, I want not to take just one word, but the full word of the array.

Here's a possible solution to your problem, assuming you've stored the array of names, just create an array of positions and then shuffle it few times so the positions will be random ones, finally pick 3 positions (for instance, the first 3 ones):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 6
#define COL 20
#define RND_NAMES 3
void shuffle(int *array, int n, int num_shuffles) {
srand((unsigned)time(NULL));
for (int j = 0; j < num_shuffles; j++) {
for (int i = 0; i < n - 1; i++) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}
int main() {
int i;
char name[ROWS][COL] = {"name1", "name2", "name3",
"name4", "name5", "name6"};
int positions[ROWS] = {0, 1, 2, 3, 4, 5};
shuffle(positions, ROWS, 100);
printf("%s\n", name[positions[0]]);
printf("%s\n", name[positions[1]]);
printf("%s\n", name[positions[2]]);
return 0;
}
With this way, you're guaranteed to pick up 3 random non-repeated names.

Here I wrote a simple solution for what you're trying to achieve.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 6
#define COL 20
#define RND_NAMES 3
int main()
{
int i;
char name[ROWS][COL];
// init pseudo-random number generator
srand((unsigned)time(NULL));
puts("Enter with 6 names: ");
for (i=0; i < ROWS; i++) {
scanf("%19[^\n]%*c", name[i]);
}
puts("Random names: ");
for (i=0; i < RND_NAMES; i++) {
printf("%s\n", name[rand() % ROWS]);
}
return 0;
}

Related

how to create an array of random number, all different from each other?

The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0; i<N; i++)
arr[i]=10+rand()%20;
for(i=0; i<N; i++)
{
for(j=N-1; j == 0; j--)
{
do
{
arr[i]=10+rand()%20;
if(arr[i]!=arr[j])
break;
}
while(arr[i]==arr[j]);
}
printf(">>%d\n",arr[i]);
}
return 0;
}
The fact that the numbers need to be different from one another means that they are not truly random. You can create another set of numbers with elements 10 through 30 in them. Randomize that list and pull them into your array.
C++ version:
const int begin = 10;
const int end = 30;
// creates a vector of 30-10 zeroes
std::vector<int> v(begin-end);
// fill vector with 10, 11, ..., 30.
std::iota (std::begin(v), std::end(v), begin);
// a source for random seed
std::random_device rd;
// seed this generator with 32-bit number
std::mt19937 g(rd());
// randomly shuffle a vector
std::shuffle(std::begin(v), std::end(v), g);
const int N = 12;
std::vector<int> result(v.begin(), v.begin() + N);
C version:
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/a/6127606/1953079
void shuffle(int *array, size_t n)
{
if (n <= 1) { return; }
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
int main(){
const int begin = 10;
const int end = 30;
const int N = 12;
srand(time(0));
// array that contains elements 10, 11...30
int nums[end-begin];
for(int i=0;i<end-begin; i++){
nums[i] = begin+i;
}
// randomly shuffle array
shuffle(nums, end-begin);
// take first N elements
int result[N];
for(int i=0;i<N;i++){
result[i] = nums[i];
printf("%d ", result[i]);
}
}
Thanks for the help but after some more looking I found what I was doing wrong and now works.
code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
{
arr[i]=10+rand()%30;
}
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(arr[i]==arr[j])
{
do
{
arr[i]=10+rand()%30;
}
while(arr[i]==arr[j]);
}
}
printf(">>%d\t",arr[i]);
}
return 0;
}

How can I create a multidimensional array of random integers printed using a function?

Baby programmer here! I am stumped. I need help with an assignment and as concluded in my last question, my professor is no help, and I have done lots of research and I cannot find any examples or answers in my book or YouTube. In C, I have to use a loop to load random integer values into a 1 dimensional array and a multidimensional array, and use functions to print the contents of each array. I've taught myself how to load random integers into a 1 dimensional array, but I'm having trouble figuring out how to call it to a function to print the results. Similarly, I can create a multidimensional array and print the results through a function, but I can't figure out how to make the integers in a multidimensional array random.
Here is what I've created and understand so far (It is a MESS and I thank you for patience in advance):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printArray(int a[], size_t size); //prototype
void printArray(int b[2][3]); //prototype
int main(void)
{
int n[10]; // n is an array of 10 integers
int i;
srand(time(NULL)); //uses time to make integers random
printf("One-Dimensional Array\n");
for (i = 0; i < 10; i++) //loop 10 times
{
n[i] = i + 1;
printf("%d ", (rand() % 50) + 1); //print random int from 1-100
}
printf("\nMulti-Dimensional Array\n");
int array1[2][3] = { {1, 2, 3}, {4, 5, 6} };
printArray(array1);
}
void printArray(int a[], size_t size)
{
//insert function for printing 1d array
}
void printArray(int b[][3])
{
for (size_t i = 0; i <= 1; ++i)
{
for (size_t j = 0; j <= 2; ++j)
{
printf("%d ", b[i][j]);
}
printf("\n");
}
}
Use nested loops, just like you do when printing the array.
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
array1[i][j] = rand() % 50 + 1; // random int from 1 to 50
}
}

C access 2 dimensional array from function with MAX_SIZE

I write this function but when I print the array a get incorrect numbers:
the problem is because the MAX_SIZE, how can I solve this without change MAX_SIZE?
#include <stdio.h>
int MAX_SIZE = 3;
void print(int arr[MAX_SIZE][MAX_SIZE],int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
printf("%d ", arr[i][j]);
}
int main()
{
int arr[][2] = {{1, 2}, {4, 5}};
print(arr,2); // 1 2 5 0
return 0;
}
First of all, you should declare constants in C like:
#define MAX_SIZE <value>
Your problem will be solved if you set MAX_SIZE to 2 since you're trying to access arr[][2] not arr[][3].
Correct syntax:
#define MAX_SIZE 2
Output:
1 2 4 5
That's it.

Change position of an exact number of elements in an array

Let's say we have an array of m elements and we want to change randomly the position of exactly n of them, where of course 2 <= n <= m.
For example: if we have this array of 10 ints {1 2 3 4 5 6 7 8 9 10} and we ask for 4 of its elements to change positions randomly, a result could be {3 2 1 4 5 6 10 8 9 7}
What is the simplest way to program this in ANSI C? (pseudocode will also be just fine)
Step1). Generate a list of n random unique numbers between 1 and m. This list should NOT be sorted. Eg, for your example, the list could have been [10,7,1,3]
Step 2) do something like :
int save = array[list[0]];
For (i=0; i<n-1; i++) {
Array[list[i]] = array[list[i+1]];
}
Array[list[n-1]] = save;
Edit: actually, you'll have to have subtract 1 from each list[whatever] to allow for zero-based arrays - but I'm sure you get the idea :)
since at least two numbers must be swapped, i would pick two random numbers from array first and then swap them. they are added to array that holds swapped indexes. if there's more to swap, pick another number different than swapped ones and swap it with one of the previously swapped numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void print_arr(int a[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ",a[i]);
}
printf("\n");
}
void swap(int a[], int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
int next_idx(int swapped[], int s_count, int size) {
int n, i;
char in_arr;
while (1) {
in_arr = 0;
n = rand() % size;
for (i = 0; i < s_count; i++) {
if (swapped[i] == n) {
in_arr = 1;
break;
}
}
if (!in_arr) {
break;
}
}
return n;
}
void swap2_or_more(int a[], int size,int count) {
srand(time(NULL));
int i, j, s_count = 0;
int swapped[size];
i = rand() % size;
swapped[s_count] = i;
s_count++;
do {
j = rand() % size;
} while (i == j); // make sure indexes are different
swapped[s_count] = j;
s_count++;
swap(a, i, j);
count -= 2;
while (count) {
i = next_idx(swapped, s_count, size);
j = rand() % s_count;
swap(a, i, swapped[j]);
swapped[s_count] = i;
s_count++;
count--;
}
printf("swapped indexes:\n");
print_arr(swapped, s_count);
}
int main(void)
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
swap2_or_more(a, 10, 5);
printf("array after swap:\n");
print_arr(a, 10);
return 0;
}

Moving parts right in two - dimensional matrix

I would like to get your help to understand and finish my program.
This is what I have to do:
"You must exercise program that:
First. An absorbing two - dimensional integer arr [M] [N]. M - number of rows N - number of columns. (Matrix size was received from the user)
Two. The program uses auxiliary functions "shift" moves the values ​​of the matrix to the right one place, as shown in the picture (2 entered instead of 1, 3 instead of 2, 4 instead of 3, ... 20 instead of 19, first place 20).
Shift have to write a function and call her three times in the sample matrix loop .."
Example
My problems are:
I don't know how to do the matrix two - dimensional integer arrays that there size is entered by the user. I only know by DEFINE SIZE of the row and the cols
My function isn't close to the real deal so I would like to get help finish my function.
My output:
My code:
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#define M 4
#define N 5
void shift (int arr[M][N], int length);
void main()
{
int arr[M][N];
int i,j,length;
printf("Enter %d rows \n",M);
for (i=0 ; i<M ; i++ )
{
printf("Enter %d numbers:\n",N);
for(j=0 ; j<N ; j++ )
{
scanf("%d" , &arr[i][j] );
}
length=N+M;
}
shift (arr,length);
system("pause");
return ;
}
void shift (int arr[M][N], int length)
{
int i,j,temp;
temp=arr[0][0];
for(i=0; i<M; i++)
{
for(j=0; j<N-1 ; j++)
{
printf("%d ",arr[i][j]);
}
arr[i][j]=temp;
printf("\n");
}
}
Edit: pictures resized
Shifts all columns to the right.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void shift_columns_right(int M[100][100], int rows, int cols) {
int tmp_lastcol;
int j, k;
for (j = 0; j<rows; j++){
tmp_lastcol = M[j][cols-1];
for (k = cols-1; k > 0; k-- ){
M[j][k] = M[j][k-1];
}
M[j][0] = tmp_lastcol;
}
}
int main(void){
int B[100] [100] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16},
{17,18,19,20},
};
shift_columns_right(B,5,4);
return 0;
}
I will you give a hint as how to shift the elements. The logic is to swap the elements between the current and last element in the row as you iterate. I will show you a working example on 1D array.
#include <stdio.h>
#define ARRAY_SIZE 5
int main()
{
int a[ARRAY_SIZE] = {11,22,33,44,55};
int i;
for (i=0; i<ARRAY_SIZE; ++i)
{
int temp = a[i];
a[i] = a[ARRAY_SIZE-1];
a[ARRAY_SIZE-1] = temp;
}
for(i=0; i<ARRAY_SIZE; ++i)
{
printf("%d\t",a[i]);
}
return 0;
}
Output: 55 11 22 33 44
To dynamically allocate the memory for array, use malloc. Hope it helps !

Resources