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;
}
Related
Question -
N numbers are entered by the user (N is also given by the user). Store the numbers in
an array. Write a C function which deletes all the second largest elements and
rearranges the array. The program should appropriately print the new array and the
value of N. For e.g if N=7 and the elements are 7 11 13 11 8 7 4 the output should be
N=5 and the array is 7 13 8 7 4
My Code -
#include<stdio.h>
int secondLargest(int arr[], int n);
int indexOfSecondLargest(int arr[], int n, int max2);
void deleteElement(int arr[], int n, int index);
void deleteSecondLargest(int arr[], int n);
void printArray(int arr[], int n);
int main()
{
static int n;
printf("Enter value of n \n");
scanf("%d", &n);
int arr[100];
printf("Enter n numbers \n");
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
deleteSecondLargest(arr, n);
printf("New value of n = %d and the array is \n", n);
printArray(arr, n);
return 0;
}
int secondLargest(int arr[], int n)
{
int max1 = arr[0], max2 = arr[0];
for (int i = 0; i < n; i++)
{
if (arr[i] > max1)
{
max2 = max1;
max1 = arr[i];
}
if (arr[i] > max2 && arr[i] < max1)
{
max2 = arr[i];
}
}
return max2;
}
int indexOfSecondLargest(int arr[], int n, int max2)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == max2)
{
return i;
}
}
return -1;
}
void deleteElement(int arr[], int n, int index)
{
for (int i = index; i < n - 1; i++)
{
arr[i] = arr[i+1];
}
n = n - 1;
}
void deleteSecondLargest(int arr[], int n)
{
int max2 = secondLargest(arr, n);
int index = indexOfSecondLargest(arr, n, max2);
while (index != -1)
{
deleteElement(arr, n, index);
index = indexOfSecondLargest(arr, n, max2);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}
My Output -
Enter value of n
7
Enter n numbers
7 11 13 11 8 7 4
New value of n = 7 and the array is
7 13 8 7 4 4 4
Even though I am using static keyword before int n, the value of n is not getting updated to 5 in main() function. I even tried putting int n as a global variable but still it doesn't work.
Can someone help me ??
Adding static to int n; says “This n persists through all of program execution.” it does not say “This n is the only n in the whole program.” Where a parameter n is declared, as in void deleteElement(int arr[], int n, int index), that creates an n different from the n in main.
However, even if no parameter is declared with the name n, an n declared inside main is not visible in any other function. To use the same n throughout the program, you need to declare int n; or static int n; outside of any function, anywhere before the first function that uses n, and you need to not declare any other n.
That would likely solve this problem for you. However, it is bad practice to use external identifiers for objects. Instead, you should use int n; in main and modify deleteElement so that it provides main with the updated value. It could do this by returning an int instead of void, or you could modify deleteElement to take a pointer to an int instead of taking an int, by making the parameter int *n. Then you would have to use it inside the function as *n instead of n.
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
}
}
Two integers are stored in the arrays a 1 and a 2, respectively, and the product is calculated by the same procedure as the calculation, but it does not output the correct result.
question is : want to produce 312*321 = 1 0 0 1 5 2 but this first program produce
? 0 9 9 11 5 2
to produce right result 1 0 0 1 5 2, call function name func(c,N*2)
#include <stdio.h>
#include <stdlib.h>
#define N 3
int main()
{
int a1[N]={1,2,3};
int a2[N]={2,1,3};
int b[N][N];
int c[N*2];
int i,j;
for(i=0;i<N;i++){
for(j=0;j<N;j++)
b[i][j]=a1[j]*a2[i];
}
c[0]=b[0][0];
c[1]=b[0][1]+b[1][0];
c[2]=b[0][2]+b[1][1]+b[2][0];
c[3]=b[1][2]+b[2][1];
c[4]=b[2][2];
for(i=N*2-1;i>=0;i--)
{
printf("%d ",c[i]);
}
printf("\n");
return 0;
}
The result:0 9 9 11 5 2
|0|1|2| ->A1
----------------
A2<-| 0|2|4|6|
| 1|1|2|3|
| 2|3|6|9|
this array is the same as 321*312 calculate using hand in paper
Problem: Define the function func () to output the correct result 1 0 0 1 5 2, call func (c, N * 2); below i post the code with the call function func() in bold. any idea?? and also what the logic behind func()? trial and error? is there algorithm behind this?
#include <stdio.h>
#include <stdlib.h>
#define N 3
int main()
{
int a1[N]={1,2,3};
int a2[N]={2,1,3};
int b[N][N];
int c[N*2];
int i,j;
for(i=0;i<N;i++){
for(j=0;j<N;j++)
b[i][j]=a1[j]*a2[i];
}
c[0]=b[0][0];
c[1]=b[0][1]+b[1][0];
c[2]=b[0][2]+b[1][1]+b[2][0];
c[3]=b[1][2]+b[2][1];
c[4]=b[2][2];
**func(c,N*2);**
for(i=N*2-1;i>=0;i--)
{
printf("%d ",c[i]);
}
printf("\n");
return 0;
}
**void func(int a[],int digit)
{
here no idea....
}**
Try with this;
void func(int a[], int digit)
{
int i, c = 0;
for(i = 0; i < digit; i ++)
{
a[i] += c;
c = a[i] / 10;
a[i] = a[i] % 10;
}
}
I think you should change two things:
First initialization the result array
int c[N * 2] = {0}; //initialize
Also the function looks like
void func(int a[], int size) {
int carry = 0;
for (int i = 0; i < size; i++) {
a[i] += carry;
carry = a[i] / 10;
a[i] = a[i] % 10;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
in visuals studio i try to make respectively sum of rows. but first sum multiplied by 4 . i didnt understand this situation
get_sum(int **q, int p, int n);
int main(void)
{
int num[3][5] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 };
get_sum(&num[0][0], 3, 5);
}
get_sum(int **q, int p, int n)
{
/*for (int i = 0; i < ; i++)
printf("%d\n", *(q + i));*/
for (int k = 0; k < p; k++)
{
int sum = 0;
for (int i = 0; i < n; i++)
{
sum =*(q + n*k + i)+sum;
printf("%d\n", sum);
}
}
}
If I understand you simply want to create a function that sums the elements of the array passed as a parameter, along with the dimensions of the array, then you have the right idea, but woefully wrong syntax.
Rather than verbally discussing each change, the simple example contains all the changes. Look over the changes and why they were made:
#include <stdio.h>
int get_sum (int (*q)[5], int p, int n);
int main (void)
{
int num[3][5] = {{ 10, 11, 12, 13, 14 },
{ 15, 16, 17, 18, 19 },
{ 20, 21, 22, 23, 24 }};
int sum = get_sum (num, 3, 5);
printf (" -----------\n sum : %d\n", sum);
return 0;
}
int get_sum (int (*q)[5], int p, int n)
{
int sum = 0;
for (int k = 0; k < p; k++) {
for (int i = 0; i < n; i++)
sum += q[k][i];
printf ("row[%2d] : %d\n", k, sum);
}
return sum;
}
(note: the loop output within get_sum provides are running-total of the sum after the addition of each row elements. You can tailor this to meet your needs.)
Example Use/Output
$ ./bin/get_sum
row[ 0] : 60
row[ 1] : 145
row[ 2] : 255
-----------
sum : 255
Let me know if you have any questions.
You are indexing a 1-D array as if it is a 2-D array, but there is no need to define it as 2-D, and anyway, you initialise it as if it were a 1-D array.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[] = { 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 }; // 1-D linear array
get_sum(num, 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}
Program output
60
85
110
Alternatively if you do want a 2-D array and then index into it as if it were a 1-D array, you can do this. Note I have initialised the array differently but get_sum is the same.
#include <stdio.h>
void get_sum(int *q, int p, int n); // only one start
int main(void)
{
int num[3][5] = {{10,11,12,13,14}, {15,16,17,18,19}, {20,21,22,23,24}};
get_sum(&num[0][0], 3, 5);
return 0;
}
void get_sum(int *q, int p, int n) // added return type
{
int k, i, sum;
for (k = 0; k < p; k++) {
sum = 0;
for (i = 0; i < n; i++) {
sum = *(q + n*k + i) + sum;
}
printf("%d\n", sum); // moved out of inner loop
}
}
I'm trying to write a C program to find all the combinations of an given array and a specified length. This is what I've done so far..
#include <stdio.h>
void com(int* a, int* t, int len, int i) {
int j, k;
if(len == 0) {
for(k=0;k<3;k++) {
printf("%d ",t[k]);
}
printf("\n");
return;
}
for(j = i ; j <= 4-len ; j++) { // 4 = original array size
t[3-len] = a[j];
com(a,t,len-1,i+1);
}
}
main() {
int t[3];
com((int[]){4,1,3,2},&t[0],3,0); // 3 = combination length
}
The problem in this code is that it has no option to skip duplicates, repetitions of combination. e.g for the array {1,2,3,4} it generates
1 2 3
1 2 4
1 3 3
1 3 4
2 2 3
2 2 4
2 3 3
2 3 4
but it was supposed to generate
1 2 3
1 2 4
1 3 4
2 3 4
What can I do for that? I'm not sure how to do that. Any kind of help would be appreciated. Thanks.
Also, if there is an alternative and better optimized solution than this, feel free to share.
sample to fix
void com(int *a, int *t, int len, int i){
if(i == len){
for(int k = 0; k < len; k++)
printf("%d ", t[k]);
printf("\n");
return;
}
while(*a){
t[i] = *a;
com(++a, t, len, i+1);
}
}
int main(void){
int t[3];
com((int[]){1,2,3,4, 0}, t, 3, 0);
// ^end mark
return 0;
}
#include <stdio.h>
int check(int *t)
{
int j,k;
for(k=0;k<3;k++)
{
for(j=k+1;j<3;j++)
{
if(t[k]==t[j])
return 0;
}
}
return 1;
}
void com(int* a, int* t, int len, int i) {
int j, k;
int comb=1;
if(len == 0)
{
comb = check(t);
if(comb)
{
for(k=0;k<3;k++)
{
printf("%d ",t[k]);
}
printf("\n");
}
return;
}
for(j = i ; j <= 4-len ; j++) { // 4 = original array size
t[3-len] = a[j];
com(a,t,len-1,i+1);
}
}
main() {
int t[3];
com((int[]){4,1,3,2},&t[0],3,0); // 3 = combination length
}
Sorry for bad editing..