My task is: If we look at any two neighbour values in an array, if the one on the right is two times greater than the one on the left, their average should be inserted between them and the new array consisting of old and new elements should be printed. I have a problem with moving the other elements after average.And using special functions or libraries is not allowed.I am beginner, and I hope you could help.
#include <stdio.h>
int main() {
int n, i, j;
double a[100], average;
printf("Enter the number of elements: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%lf", &a[i]);
}
for (i = 0; i < n; i++) {
if ((a[i + 1] / a[i]) == 2) {
for (i = j = 0; i < n; ++i)
b[j++] = a[i];
if (a[i + 1] / a[i] == 2)
average = (a[i + 1] + a[i]) / 2;
b[j++] =average;
}
}
for (i = 0; i < j; ++i) {
printf("%lf\n", b[i]);
}
}
A simple way to solve your problem is adding double b[199];, and copying everything over:
for (i = j = 0; i < n; ++i) {
b[j++] = a[i];
if (...) b[j++] = ...; /* Append the average to b. */
}
for (i = 0; i < j; ++i) {
printf("%lf\n", b[i]);
}
If you really want to move the elements forward within a itself, then you can do it by adding an inner for loop (and an additional loop variable int k;) which copies the elements one-by-one:
for (k = n++; k > i; --k) {
a[k] = a[k - 1];
}
In order to insert an element in an array, you must copy the elements with higher index from the last one down.
Also avoid dividing by a[i] that can be zero, and properly handle 0,0 that match the criteria for inserting the average, and skip the inserted value to avoid inserting more zeros.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, j;
printf("Enter the number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0)
return 1;
double *a = malloc(sizeof(*a) * (2 * n - 1)); // allocate the array to the maximum size
if (a == NULL)
return 0;
for (i = 0; i < n; i++) {
if (scanf("%lf", &a[i]) != 1)
return 1;
}
for (i = 1; i < n; i++) {
if (a[i] == a[i - 1] * 2) {
for (j = n; j > i; j--)
a[j] = a[j - 1];
a[i] = (a[i - 1] + a[i]) / 2;
n++; // increase number of elements
i++; // skip the new value
}
}
for (i = 0; i < n; ++i) {
printf("%f\n", a[i]);
}
free(a);
return 0;
}
To insert an element in a specific position you would need to move the rest of the array. However doing it many times is expensive and you may prefer to use an array to store the position at which you want to insert the elements and then insert them all at once.
Alternatively you can create a new array where to copy the original plus the new values.
However there's an easier and faster way, that is adding the new values straight away, while you fill the original array. Here's a program that does that.
#include <stdio.h>
#define SIZE 100
int main() {
int i, n, avg = 0;
double a[SIZE];
while( puts("Enter the number of elements:") && (scanf("%d", &n) != 1 || n < 1 || n > SIZE) );
scanf("%lf", &a[0]);
for(i = 1; i < n+avg && i < SIZE-1 && scanf("%lf", &a[i]) == 1; i++) {
if( a[i] == a[i-1] * 2 ) {
a[i+1] = a[i];
a[i] = (a[i] + a[i-1]) / 2;
++avg;
++i;
}
}
for(i = 0; i < n+avg; i++) {
printf("%lf\n", a[i]);
}
return 0;
}
Related
I want to randomize a to p without repetition.
int main(){
int array2[4][4];
bool arr[100]={0};
int i;
int j;
srand(time(NULL));
for(i=0; i<=3; i++){
for(j=0; j<=3; j++){
int randomNumber1;
randomNumber1 = (rand() % (82-65+1))+65;
if (!arr[randomNumber1])
{
printf("%c ",randomNumber1);
array2[i][j]=randomNumber1;
}
else
{
i--;
j--;
arr[randomNumber1]=1;
}
}
printf("\n");
}
return;
the output still has repeat alphabet. I want to have the output in 4x4 with with all a to p without it repeating.
There are some errors in your code. IMHO the most serious is that arr[randomNumber1]=1; is is the wrong branch of the test. That means that your current code does not invalidate once a number was used but only if it has already been invalidated => if you control the arr array at the end of the program all value are still 0.
That is not all. When you get a duplicate, you should only reset the inner loop, and you are currently off by 2 in your maximum ascii code: you go up to R when you want to stop at P.
Your code should be:
for (i = 0; i <= 3; i++) {
for (j = 0; j <= 3; j++) {
int randomNumber1;
randomNumber1 = (rand() % (81 - 65)) + 65;
if (!arr[randomNumber1])
{
printf("%c ", randomNumber1);
array2[i][j] = randomNumber1;
arr[randomNumber1] = 1;
}
else
{
//i--;
j--;
}
}
printf("\n");
}
But this kind of code is terribly inefficient. In my tests it took 30 to 60 steps to fill 16 values, because random can return duplicates. This is the reason why you were advised in comments to use instead the modern algorithm for Fisher-Yates shuffle:
int main() {
int array2[16];
unsigned i, j, k=0;
// initialize array with alphabets from A to P
for (i = 0; i < sizeof(array2); i++) {
array2[i] = 'A' + i;
}
// Use Fisher-Yates shuffle on the array
srand(time(NULL));
for (i = 15; i > 0; i--) {
j = rand() % (i + 1);
if (j != i) {
int c = array2[i];
array2[i] = array2[j];
array2[j] = c;
}
}
// Display a 4x4 pattern
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
printf("%c ", array2[k++]);
}
printf("\n");
}
return 0;
}
Which shuffles the array in only 16 steps.
Here is the outline
// Need some #includes here - exercise for the reader
char items[] = "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(items);
srand(time(NULL));
while (len > 0) {
int r = rand() % len;
printf("%c", items[r]);
len--;
items[r] = items[len];
}
This should do the trick to print the whole alphabet in random order without repeats. Modify to do what you need it to do
I am doing the following problem:
Giving the sequence a consisting of n integer numbers and the sequence b consisting of m integer numbers, two sequences are arranged in increasing order. Combining two above sequences into a new sequence c such that c is also an increasing sequence. Printing c.
Input:
3
1 3 4
4
1 2 3 5
Output:
1 1 2 3 3 4 5
My idea is first combining two sequences into sequence c, then sorting sequence c in increasing order. This is my code:
#include <stdio.h>
int main() {
//Inputting sequence a and b
int n, m;
int a[1001], b[1001];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &b[i]);
}
//Combine two sequence into c
int c[1001];
for (int i = 0; i < n; i++) {
c[i] = a[i];
}
for (int i = 0; i < m; i++) {
c[i + n] = b[i];
}
//Arrange sequence c in increasing order
int mid;
for (int i = 0; i < (n + m - 1); i++) {
for (int j = 1; j < (n + m); j++) {
if (c[i] > c[j]) {
mid = c[i];
c[i] = c[j];
c[j] = mid;
}
}
}
//Printing c
for (int i = 0; i < (n + m); i++) {
printf("%d ", c[i]);
}
return 0;
}
However, when I test with the test case [1,2,4],[1,2,5], the result is 1 4 2 2 1 5. Can anyone point out the error in my code? I truly appreciate that.
It is wrong to search for the minimum value in the range of 1 to n+m-1 regardless of the value i. This may move the minimum value to the latter part of the array.
The line
for (int j = 1; j < (n+m); j++)
should be
for (int j = i + 1; j < (n+m); j++)
To merge 2 sorted arrays, you can write 3 loops as in the classic implementation of mergesort:
#include <stdio.h>
int main() {
//Inputting sequence a and b
int a[1000], b[1000], c[2000];
int n, m, i, j, k;
if (scanf("%d", &n) != 1 || n <= 0 || n > 1000)
return 1;
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1)
return 1;
}
if (scanf("%d", &m) != 1 || m <= 0 || m > 1000)
return 1;
for (i = 0; i < m; i++) {
if (scanf("%d", &b[i]) != 1)
return 1;
}
//Combine both sequences into c
i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (a[i] <= b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
}
while (i < n) {
c[k++] = a[i++];
}
while (j < m) {
c[k++] = a[j++];
}
//Printing c
for (i = 0; i < n + m; i++) {
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
I want here to implement the value of array[i][j] into itself, but firstly I have to check if it is in range between example: -99 and 99. If the input is out of these boundaries, it should stop the program.
I tried it with a do-while loop and just now I tried while loop.
#include <stdio.h>
#include <stdlib.h>
int main(){
int array[2][2], i, n, j;
/*
do
{
printf("Value= ");
scanf("%d", &n);
array[i][j] = n;
i++;
j++;
}
while(n < 99 && n > -99);
*/
while(array[i][j] < 99 && array[i][j] > -99){
for(i = 0; i < 2; ++i){
for(j = 0; j < 2; ++j){
printf("Value= ");
scanf("%d", &array[i][j]);
}
}
}
// Print the result
for(i = 0; i < 2; ++i){
for(j = 0; j < 2; ++j){
printf("\n[%d][%d]: ", array[i][j]);
}
}
}
I got a endless loop which doesn't exit if the value is incorrect (out of these boundaries).
Try this, tested and works:
int *array, i, val, n, m;
printf("Put in array size in the form of n-m where n is number of rows and m is number of columns: ");
scanf("%d-%d", &n, &m);
array = (int *) malloc(sizeof(int) * n * m);
i = 0;
while (i < n * m) {
printf("Value for row: %d, column: %d: ", i / m + 1, i % m + 1);
scanf("%d", &val);
if (val > 99 || val < -99) continue;
*(array + i) = val;
i++;
}
for (i = 0; i < n * m; i++) {
if (i > 0 && i % n == 0) printf("\n");
printf("%d\t", *(array + i));
}
free(array);
Without pointers (Variable sized arrays does not work on C90, needs newer standard, or you may use fixed sized arrays):
int i, val, n, m;
printf("Put in array size in the form of n-m where n is number of rows and m is number of columns: ");
scanf("%d-%d", &n, &m);
int array[n][m];
i = 0;
while (i < n * m) {
printf("Value for row: %d, column: %d: ", i / m + 1, i % m + 1);
scanf("%d", &val);
if (val > 99 || val < -99) continue;
array[i / m][i % m] = val;
i++;
}
for (i = 0; i < n * m; i++) {
if (i > 0 && i % n == 0) printf("\n");
printf("%d\t", array[i / m][i % m]);
}
In your array undefeated values, in the first while you try to check random number in your memory. And so your i j will be random number.
Put if statement in your for loop to check the value in array, and delete while loop
Hello i am trying to use counting sort to sort numbers that i read from a file. this is my code:
void CountingSort(int array[], int k, int n)
{
int i, j;
int B[100], C[1000];
for (i = 0; i <= k; i++)
{
C[i] = 0;
}
for (j = 1; j <= n; j++)
{
C[array[j]] = C[array[j]] + 1;
}
for (i = 1; i <= k; i++)
{
C[i] = C[i] + C[i-1];
}
for (j = 1; j <= n; j++)
{
B[C[array[j]]] = array[j];
C[array[j]] = C[array[j]] - 1;
}
printf("The Sorted array is : ");
for (i = 1; i <= n; i++)
{
printf("%d ", B[i]);
}
}
void max(int array[],int *k,int n){
int i;
printf("n je %d\n",n);
for (i = 0; i < n; i++)
{
if (array[i] > *k) {
*k = array[i];
}
}
}
int main(int brArg,char *arg[])
{
FILE *ulaz;
ulaz = fopen(arg[1], "r");
int array[100];
int i=0,j,k=0,n,x,z;
while(fscanf(ulaz, "%d", &array[i])!=EOF)i++;
fclose(ulaz);
n=i;
max(array,&k,n);
printf("Max je %d\n",k);
CountingSort(array,k,n);
return 0;
}
i have no errors but when i start my program i get Segmentation fault error. pls help! (dont read this bot is asking me to write some more details but i have none so i just write some random words so i can post my question and hopefully get an answer)
The problem is that your implementation of the counting sort is incorrect: it uses arrays as if they were one-based, while in C they are zero-based.
After carefully going through your loops and fixing all situations where you use a for loop that goes 1..k, inclusive, instead of the correct 0..k-1, the code starts to work fine:
int i, j;
int B[100], C[1000];
for (i = 0; i <= k; i++){
C[i] = 0;
}
for (j = 0; j < n; j++){
C[array[j]]++;
}
for (i = 1; i <= k; i++){
C[i] += C[i-1];
}
for (j = 0; j < n; j++) {
B[--C[array[j]]] = array[j];
}
printf("The Sorted array is : ");
for (i = 0; i < n; i++) {
printf("%d ", B[i]);
}
Demo.
Note: I modified some of the operations to use C-style compound assignments and increments/decrements, e.g. C[array[j]]++ in place of C[array[j]] = C[array[j]] + 1 etc.
The problem most likely is here
int B[100], C[1000]; // C has space for numbers up to 999
...
for (i = 1; i <= k; i++)
C[i] = C[i] + C[i-1]; // adding up till C[k] == sum(array)
for (j = 0; j < n; j++)
B[C[array[j]]] = array[j]; // B has space up to 99, but C[k] is sum(array)
so you're reserving space for C for a highest value of 999 but in B you're assuming that the sum of all input values is less than 100...
the resolution of your problem is to first probe the input array and get the maximum and the sum of all input values (and minimum if the range may be negative) and allocate space accordingly
edit: you probably meant j < n and not j <= n
Adding to dasblinkenlight's spot-on answer:
Is your input data guaranteed to be in the range [0, 999]? If it isn't, it's obvious that segmentation faults can and will occur. Assume that the maximum value of array is 1000. C is declared as
int C[1000];
which means that C's valid indices are 0, 1, 2, ... 999. But, at some point, you will have the following:
C[array[j]] = ... /* whatever */
where array[j] > 999 so you will be attempting an out-of-bounds memory access. The solution is simple: probe array for its maximum value and use dynamic memory allocation via malloc:
/* assuming k is the maximum value */
int * C = malloc((k + 1) * sizeof(int));
Note: an alternative to this, which would also nullify the need for an initialization loop to make all elements of C equal to 0, would be to use calloc, which dynamically allocates memory set to 0.
// allocate C with elements set to 0
int * C = calloc(k + 1, sizeof(int);
Another important factor is the range of your running indices: you seem to have forgotten that arrays in C are indexed starting from 0. To traverse an array of length K, you would do:
for (i = 0; i < K; ++i)
{
processArray(array[i]);
}
instead of
for (i = 1; i <= K; ++i)
{
processArray(array[i]);
}
I'm trying to implement this excercise but it doesn't work very well. It should tell me if the sequence in array B is contained in A. Any ideas? I have a problem getting it to work for every sequence.
#include <stdio.h>
#include <stdlib.h>
#define N 6
#define M 3
int contains(int v[], int n);
/*
*
*/
int main(int argc, char** argv)
{
int A[N], B[M];
int i, j = 0, flag = 0, contained = 1;
printf("Array A\n");
for (i = 0; i < N; i++)
{
printf("Insert element: ");
scanf("%d", &A[i]);
}
printf("Array B\n");
for (i = 0; i < M; i++)
{
printf("Insert element: ");
scanf("%d", &B[i]);
}
for (i = 0; i < (N - M + 1); i++)
{
flag = 0;
if (A[i] == B[j])
{
flag = 1;
j++;
}
if (flag == 0 && (i == N-M))
{
contained = 0;
printf("The sequence B is not contained in A!\n");
break;
}
}
if (contained == 1)
{
printf("The sequence B is contained in A\n");
}
return (EXIT_SUCCESS);
}
When you have a non match in the sequence, you never reset j so you start looking for the rest of the sequence starting to what ever value j was left at. Your program looks for the sequence B but doesn't require it to be contiguous.
You also don't check for when the sequence is completed so it for example B is at the start of A the j will keep incrementing and B[j] will overflow into unknown memory which is unlikely to match A so will give you an incorrect result. To fix this just check for when the whole of B is found and exit the loop.
Substituting the following will fix this:
if (j == M) break; // Break the loop when B sequence is found
if (flag == 0)
{
j = 0; // This was missing
if (i == N-M)
{
contained = 0;
printf("The sequence B is not contained in A!\n");
break;
}
}
For the third for loop when you're doing the check, you're (1) not actually checking every element of B against the corresponding element of A and (2) not checking the different start indices. What you probably meant to do is something like
for (i = 0; i < (N - M + 1); i++) {
for (j = 0; j < M; j++) {
if (A[i + j] != B[j]) {
break;
}
}
if (j == M) {
printf("Found a match!");
}
}
as your spinning through A if you find that an element of B does not match A then you need to set j back to 0
for (i = 0; i < (N - M + 1); i++)
{
int j;
for(j = 0; j < M; j++)
{
if(B[j] != A[j + i])
break;
}
/* sequence found */
if(j == M)
{
return true;
}
}
return false;
For searching B in A you may want to do something like following:
for (i = 0; i < (N - M + 1) ; i++)
if (A[i] == B[0])
{ j=0;
while (A[++i] == B[++j] && j<M);
break;
}
if (j == M)
{
printf("The sequence B is contained in A\n");
}
else{
printf("The sequence B is not contained in A\n");
}
GCC has the memmem() extention function (which is basically strstr(), but does not rely on NUL-terminated strings)
if (memmem(A, N * sizeof *A, B, M * sizeof *B)) {
printf("Found\n" );
} else {
printf("Not Found\n" );
}