I am trying to sort an array and remove duplicates.This is the function i am using in c
this code is errorfree but gives me wrong output as there are 0's in the output array. whereas there were no zeros originally
sort(int tab[], int k)
{
int temp,i,j,m;
for(i=0; i<k; i++){
for(j =i+1; j<k; j++)
{
if(tab[i] > tab[j])
{
int temp = tab[i];
tab[i]=tab[j];
tab[j]=temp;
}
else if (tab[i] == tab[j]){
for (m =j; m<k; m++){
tab[m] = tab[m+1];
}
}
}
}
}
what is the logical error in this code?I am getting 0's in my output
your code is correct... but you forgot to do a k--;
since you are removing a duplicate each time the size will decrease by 1..
sort(int tab[], int k)
{
int temp,i,j,m;
for( i=0;i<k;i++)
for( j =i+1;j<k;j++)
{
if(tab[i]>tab[j])
{
int temp = tab[i];
tab[i]=tab[j];
tab[j]=temp;
}
else if (tab[i]==tab[j])
{
for ( m =j ; m<k;m++)
tab[m]=tab[m+1];
k--;
} //end of else if
}// end of for
}
Related
I am having trouble achieving the wanted results. The program should ask for 20 inputs and then go over each to see if they appear more than once. Then only print out those that appeared once.
However currently my program prints out random numbers that are not inputted.
For example:
array = {10,10,11,12,10,10,10.....,10} should return 11 and 12
#include <stdio.h>
void main() {
int count, size=20, array[size], newArr[size];
int number=0;
for(count = 0; count < size; count++) {
// Ask user for input until 20 correct inputs.
printf("\nAnna %d. luku > ", count+1);
scanf("%d", &number);
if( (number > 100) || (number < 10) ) {
while(1) {
number = 0;
printf("Ei kelpaa.\n");//"Is not valid"
printf("Yrita uudelleen > ");//"Try again >"
scanf("%d", &number);
if ( (number <= 100) && (number >= 10) ) {
break;
}
}
}
array[count] = number;
}
for(int i=0; i < size; i++) {
for(int j=0; j<size; j++){
if(array[i] == array[j]){
size--;
break;
} else {
// if not duplicate add to the new array
newArr[i] == array[j];
}
}
}
// print out all the elements of the new array
for(int k=0; k<size; k++) {
printf("%d\n", newArr[k]);
}
}
You don't need the newArr here, or the separate output loop. Only keep a count that you reset to zero at the beginning of the outer loop, and increase in the inner loop if you find a duplicate.
Once the inner loop is finished, and the counter is 1 then you don't have any duplicates and you print the value.
In code perhaps something like:
for (unsigned i = 0; i < size; ++i)
{
unsigned counter = 0;
for (unsigned j = 0; j < size; ++j)
{
if (array[i] == array[j])
{
++counter;
}
}
if (counter == 1)
{
printf("%d\n", array[i]);
}
}
Note that the above is a pretty naive and brute-force way to deal with it, and that it will not perform very well for larger array sizes.
Then one could implement a hash-table, where the value is the key, and the count is the data.
Each time you read a value you increase the data for that value.
Once done iterate over the map and print all values whose data (counter) is 1.
Use functions!!
Use proper types for indexes (size_t).
void printdistinct(const int *arr, size_t size)
{
int dist;
for(size_t s = 0; s < size; s++)
{
int val = arr[s];
dist = 1;
for(size_t n = 0; n < size; n++)
{
if(s != n)
if(val == arr[n]) {dist = 0; break;}
}
if(dist) printf("%d ", val);
}
printf("\n");
}
int main(void)
{
int test[] = {10,10,11,12,10,10,10,10};
printdistinct(test, sizeof(test)/sizeof(test[0]));
fflush(stdout);
}
https://godbolt.org/z/5bKfdn9Wv
This is how I did it and it should work for your:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stdarg.h>
void printdistinct(const int *muis, size_t size);
int main()
{
int loop=20,i,muis[20],monesko=0;
for(i=0; i<loop; i++){
monesko++;
printf ("Anna %d. luku: \n",monesko);
scanf("%d", &muis[i]);
if (muis[i]<10 || muis[i]>100){
printf("Ei kelpaa!\n");
muis[i] = muis[i + 1];
printf("YRITÄ UUDELLEEN:\n ");
scanf("%d", &muis[i]);
}
}
printdistinct(muis, sizeof(muis)/sizeof(muis[0]));
fflush(stdout);
return 0;
}
void printdistinct(const int *muis, size_t size)
{
for(size_t s = 0; s < size; s++)
{
int a = muis[s];
int testi = 1;
for(size_t n = 0; n < size; n++){
if(s != n) {
if(a == muis[n]){
testi = 0;
break;
}
}
}
if(testi) {
printf("%d \n", a);
}
testi = 1;
}
printf("\n");
}
This approach uses some memory to keep track of which elements are duplicates. The memory cost is higher, but the processor time cost is lower. These differences will become significant at higher values of size.
char* duplicate = calloc(size, 1); // values are initialized to zero
for (unsigned i = 0; i < size; ++i)
{
if(!duplicate[i]) // skip any value that's known to be a duplicate
{
for (unsigned j = i + 1; j < size; ++j) // only look at following values
{
if (array[i] == array[j])
{
duplicate[i] = 1;
duplicate[j] = 1; // all duplicates will be marked
}
}
if (!duplicate[i])
{
printf("%d\n", array[i]);
}
}
}
What you can do is you can initialize a hashmap that will help you store the unique elements. Once you start iterating the array you check for that element in the hashmap. If it is not present in the hashmap add it to the hashmap. If it is already present keep iterating.
This way you would not have to iterate the loop twice. Your time complexity of the algorithm will be O(n).
unordered_map < int, int > map;
for (int i = 0; i < size; i++) {
// Check if present in the hashmap
if (map.find(arr[i]) == map.end()) {
// Insert the element in the hash map
map[arr[i]] = arr[i];
cout << arr[i] << " ";
}
}
I have experimented with my code a bit by commenting out specific parts of my code. I have found out that no segmentation fault occurs when i comment out the for loops with the variable j( shown in code). Also, when i comment out the recursive part in the function ( the lines where the function calls itself), no seg fault occurs even when the for loops are present. So clearly the for loops are causing problems in the second or higher iterations of the function, but I have no idea why. One possible reason i could think of is that infinite recursion occurs, but as far as i know no infinite recursion occurs here.
I have been trying to solve the following problem: https://www.codechef.com/problems/H1
#include<stdio.h>
int prime1[]={3,5,7,11,13,17};
int min=1000000000; //just some large number
void check(int *, int);
void swap(int*, int, int);
int prime(int);
int main()
{
int T;
scanf("%d", &T);
for(int i=0; i<T; i++)
{
printf("\n");
int arr[9];
for(int j=0; j<9; j++)
scanf("%d", &arr[j]);
check(arr, 0);
if(min==1000000000)
min=-1;
printf("%d\n", min);
}
}
void check(int arr[],int step) //step indicates the level of
//iteration
{
int k, a[9];
for(k=0; k<9; k++)
{
if(arr[k]!=k+1)
break;
}
if(k==9)
{
if(step<min)
min=step;
}
else
{
for(int i=0; i<8; i++)
{
if(i%3!=2)
{
if(prime(arr[i]+arr[i+1]))
{
for(int j=0; j<9; j++) // segmentation fault
a[j]=arr[j];
swap(a, i, i+1);
check(a, step+1);
}
}
if(i<=5)
{
if(prime(arr[i]+arr[i+3]))
{
for(int j=0; j<9; j++) // segmentation fault
a[j]=arr[j];
swap(a, i, i+3);
check(a, step+1);
}
}
}
}
}
int prime(int a)
{
for(int i=0; i<6; i++)
{
if(a==prime1[i])
return 1;
}
return 0;
}
void swap( int a[], int b, int c)
{
int temp;
temp=a[b];
a[b]=a[c];
a[c]=temp;
}
Your algorithm runs forever switching the first two tiles.
I removed some loops, i=0, k=0 and arr[] = {4,3,} we are left with:
void check(int arr[], int step)
{
int k, a[9];
// arr[0] != 1, so k != 9, we fall in else { ... }
// for (k = 0; k < 9; k++) {
// if (arr[k] != k+1)
// break;
// }
// printf("\n");
// if (k == 9) {
// if (step < min)
// min = step;
// } else {
int i = 0;
// for (int i = 0; i < 8; i++) {
// if (i%3 != 2) {
// if (prime(arr[i] + arr[i+1])) {
// i = 0, so i%3 != 2, so we fall in the first if
for (int j = 0; j < 9; j++)
a[j] = arr[j];
// you swap arr[0] with arr[1]
swap(a, i, i+1);
// and then you check again
check(a, step+1);
// and it runs so forever, never reaching this point
// }
// }
// if (i <= 5) {
// if (prime(arr[i] + arr[i+3])) {
// for (int j = 0; j < 9; j++)
// a[j] = arr[j];
// swap(a, i, i+3);
// check(a, step+1);
// }
// }
}
}
}
This algorithm needs rethinking. You need to differentiate the algorithm when run with different step number. The easiest is to switch a random title on each check, the better is to build a proper decision tree, where you remember which titles were switched.
You may interest yourself in some proper indentation,
I need to add two 3x3 matrices together using while loops. I am able to read and print both matrices using while loops but cannot work out how to add the matrices with while loops.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0,j=0,k=0,l=0,m=0,n=0;
int a[3][3],b[3][3],c[3][3];
printf("Enter the first matrix \n \n");
while(i<3)
{
j=0;
while(j<3)
{
scanf("%d",&a[i][j]);
j++;
}
i++;
}
printf("\n");
printf("The first matrix is \n\n");
i=0;
while(i<3)
{
j=0;
while(j<3)
{
printf("%d ",a[i][j]);
j++;
}
printf("\n");
i++;
}
printf("\n");
//////////////////////////////////////////////////////////////////////////
printf("Enter the second matrix \n \n");
while(k<3)
{
l=0;
while(l<3)
{
scanf("%d",&b[k][l]);
l++;
}
k++;
}
printf("\n");
printf("The second matrix is \n\n");
k=0;
while(k<3)
{
l=0;
while(l<3)
{
printf("%d ",b[k][l]);
l++;
}
printf("\n");
k++;
}
printf("\n");
///////////////////////////////////////////////////////////////////////////////
printf("The sum of the matrix's is \n \n");
return 0;
}
int matrix_a [3][3] = {{1,2,3},{3,4,5},{4,5,6}};
int matrix_b [3][3] = {{5,6,7},{6,7,8},{7,8,9}};
int i = 0;
while (i < 3) {
j = 0;
while (j < 3) {
matrix_a[i][j] += matrix[i][j];
++ j;
}
++ i;
}
for loops are a much better choice:
for (int i = 0; i < 3; ++ i) {
for (int j = 0; j < 3; ++ j) {
matrix_a[i][j] += matrix_b[i][j];
}
}
Superoptimal pointer-arithmetic alternative:
int* ptr_a = matrix_a;
int* ptr_b = matrix_b;
int size = 3 * 3;
while (size --) {
* ptr_a++ += * ptr_b++;
}
Break your problem down into smaller sub problems to help solve it.
EXAMPLE:
How to loop through a 2-D array?
How to get values and assign them to a variable from looping through the array?
How to manipulate the values to are obtaining (In your case adding them to something else)
How to insert these values into the correct position in a new array.
You can add the below code to do the addition:
k=0;
while(k<3)
{
l=0;
while(l<3)
{
c[k][l] = a[k][l]+b[k][l];
l++;
}
k++;
}
And, to display your matrix, you can use for loop instead of while.
Example:
for(int p =0;p<3;p++){
for(int q=0;q<3;q++){
c[p][q] = a[p][q] + b[p][q] ;
}
}
for(int p =0;p<3;p++){
for(int q=0;q<3;q++){
printf("%d \t",c[p][q]) ;
}
printf("\n");
}
I am trying to create a function that will rearrange an array so it is in descending order. The array is made up from positive integers, with no two equal elements. This is what I have:
int check (int *v, int n){
int i;
for (i=0; i<n; i++){
if (v[i] != -1){
return -1;
break;
}
else return 1;
}
}
void sortVector (int *v, int n){
int i, k, j=0, vp[n];
while (check(v,n) == -1){
for (i=0; i<n; i++){
for (k=i+1; k<n; k++){
if (v[k] > v[i]) break;
else if (k == n-1){
vp[j] = v[i];
v[i] = -1;
j++;
}
}
}
}
for (i=0; i<n; i++)
v[i] = vp[i];
}
Which is not working correctly. I've been thinking about this for the past week so some pointers would be great. Thanks.
I tried to follow the idea that you have stated in your comment by starting from your code above and made few changes and here is the two final functions
#include <stdio.h>
int check (int *v, int n)
{
int i;
for (i=0; i<n; i++)
{
if (v[i] != -1)
{
return -1; // break is useless because return has the same effect
}
}
return 1; // you need to add a return here to handle all the cases
// the case if the loop is not entered you need to return a value
}
void sortVector (int *v, int n)
{
int i, k, j=0, vp[n];
int maxIndex=0;//you need to add this variable in order to keep track of the maximum value in each iteration
while (check(v,n) == -1)
{
for (i=0; i<n; i++)
{
maxIndex=i; //you suppose that the maximum is the first element in each loop
for (k=i+1; k<n; k++)
{
if (v[k] > v[maxIndex])
maxIndex=k; // if there is another element greater you preserve its index in the variable
}
//after finishing the loop above you have the greatest variable in the array which has the index stored in maxIndex
vp[i] = v[maxIndex]; // put it in vp array
v[maxIndex]=v[i];//put it in treated elements zone
v[i]=-1;// make it -1
j++;
}
}
for (i=0; i<n; i++)
v[i] = vp[i];
}
This is the test
int main()
{
int tab[]= {1,152,24,11,9};
sortVector (tab, 5);
int i=0;
for(i=0; i<5; i++)
{
printf("%d ",tab[i]);
}
return 0;
}
which gives the desired output
152 24 11 9 1
Note: You can improve your code by making swaps on the same array instead of allocating another array !
There are really lots of algorithms for sorting. A simple algorithm is to find the minimum element in your array and put it in the first position by swapping it with whatever item was in the first position and then recursively sorting the array but this time starting at the next position.
void sort(int a[], int l, int r)
{ if(l == r) return; /* 1-elemnt array is already sorted */
int min = l;
for(int i = l+1; i <= r; i++)
{ if(a[i] < a[min])
{ min = i;
}
}
swap(a[l], a[min]);
sort(a, l+1, r);
}
You can also do it iteratively.
Perhaps, the intention like following
int check (int *v, int n){
int i;
for (i=0; i<n; i++){
if (v[i] != -1){
return -1;
//break; //This code that does not reach
}
//else return 1; //move to after for-loop
}
return 1;
}
void ordenaVetor (int *v, int n){
int i, k, j=0, vp[n];
while (check(v,n) == -1){
for (i=0; i<n; i++){
if(v[i]<0) continue;//Element of -1 excluded. v[k] too.
for (k=i+1; k<n; k++){
if (v[k]>=0 && v[i] < v[k]) break;
}
if (k == n){
vp[j] = v[i];
v[i] = -1;
j++;
break;//start over
}
}
}
for (i=0; i<n; i++){
v[i] = vp[i];
}
}
You could use an existing sort implementation instead of reinventing the wheel:
#include <stdlib.h>
int desc(void const *a, void const *b)
{
if ( *(int *)a < *(int *)b ) return 1;
return -1;
}
void sortVector (int *v, int n)
{
qsort(v, n, sizeof *v, desc);
}
I am working on a program that removes duplicate values from an array by ordering it and then removing duplicate, consecutive values. First I execute a selection sort sorting method, and then call a function removedup() that modifies the array and returns the size. Then I basically print the values in the array up to that size. However, when I execute it, it only prints the original array and then a bunch of blank space. Does anyone know why this is occurring?
My code: http://pastebin.com/uTTnnMHN
Just the de-duplication code:
int removedup(int a[])
{
int i, count, j;
count = n;
for (i = 0; i < (n - 1); i++) {
if (a[i] == a[i + 1]) {
for (j = 0; j < (n - i); j++) {
a[j] = a[j + 1];
}
count--;
i--;
}
}
return count;
}
-1 for(j=0;j<(n-i);j++)
Is your loop to shift left your array (thus removing the duplicate value), j should not be init to j but to i, and the condition does not seem right
A correct one could be:
for(j=i;j<n-1;j++)
{
a[j]=a[j+1];
}
a[n-1] = 0; // Because you shift your table to the left, the last value should not be used
first if i=0 and if a[i]==a[i+1] then i=-1
for(i=0;i<(n-1);i++)
{
if(a[i]==a[i+1])
{
for(j=0;j<(n-i);j++)
{
a[j]=a[j+1];
}
count--;
i--; //i=-1 if(a[i]==a[i+1]) && if(i==0)
}
}
In your duplicate removal function, you need to start the moving loop at i, as has been mentioned, and you must use count - 1 as the loop bound for both loops, otherwise you will have an infinite loop whenever there are duplicates, because then a[n-2] == a[n-1] always after the first moving loop.
int removedup(int a[])
{
int i, count, j;
count = n;
for(i = 0; i < (count-1); i++)
{
if(a[i] == a[i+1])
{
for(j = i; j < (count-1); j++)
{
a[j]=a[j+1];
}
count--;
i--;
}
}
return count;
}
works correctly.
Since you're creating another array anyway, why not simplify your function?
int removedup(int a[], int b[])
{
int i;
int count = 1;
b[0] = a[0]
for(i=1;i<(n-1);i++){
if(a[i-1] != a[i]){
b[count++] = a[i];
}
}
return count;
}
Then when you call the function,
count=removedup(a, OutArray);
int removedup(int a[])
{
int i;
count = n;
for (i = 0; i < (count-1); ++i) {
if (a[i] == a[i+1]) { /* found a duplicate */
int d = 0; /* count the duplicates */
do {
++d;
} while ((i+1+d) < count && a[i] == a[i+1+d]); /* probe ahead again for a duplicate */
/* at this point we have either run out of duplicates or hit the end of the array */
if ((i+1+d) < count)
memmove(&a[i+1], &a[i+1+d], sizeof(int)*(count-(i+1+d))); /* shift down rest of the array if there's still elements to look at */
count -= d; /* adjust the count down by the number of duplicates */
}
}
return count;
}
what about this one,without sort but traverse.finally print the effective values of the array and return its size.
int removedup(int a[])
{
int i, count, j;
count = n;
int b[n];
memset(b,0,sizeof(b));
for (i = 0; i < (n - 1); i++)
{
if (-1 != b[i])
{
for(j=i+1;j<n-1;j++)
{
if( a[i]==a[j])
{
b[j]=-1;
count--;
}
}
}
}
for(i=0;i<n-1;i++)
{
if(-1 != b[i])
{
printf("%d ",a[i]);
}
}
return count;
}