I'm trying to find the union of two sets of 10 digit numbers, I'm passing along three int arrays: first, second, and comp (this will hold the union set).
So far, I've added first and second into one array. I was thinking about finding the matching indices in comp[] then filter through deleting them. I figure there's a much easier way. Can anyone give me a hint?
Basically I'm taking
first[] = [1,2,3,4,5,6,7,8,9,10];
second[] = [1,2,3,4,11,12,13,14,15,16];
and I want to return
comp[] = [5,6,7,8,9,10,11,12,13,14,15,16];
The numbers won't necessarily be in order.
int compound(int first[],int second[],int comp[]){
int i=0;
int indicies[20];
for(int j = 0; j<SIZE; j++){
comp[i]=first[j];
i++;
}
for(int k = 0; k<SIZE; k++){
comp[i]=second[k];
i++;
}
int z=0;
for(int l = 0; l<SIZE*2; l++){
for(int m = 0; m<SIZE*2; m++){
if(comp[l]==comp[m]){
indicies[z]=m;
z++;
}}}
return 0;
}
A first good step is (nearly) always sorting.
Sort both input-sets (unless you know they are already sorted).
Then iterate over both at once (two indices) and only add those elements to the output which fulfill your criteria (seems to be union minus intersection, thus only in one).
Bonus: The output-set will be sorted.
I suggest you start by writing a contains(int[], int) method like
#include <stdio.h>
#include <stdbool.h>
bool contains(int arr[], int val) {
int offset;
for (offset = 0; arr[offset] != '\0'; offset++) {
if (arr[offset] == val) return true;
}
return false;
}
Then your compound method could be implemented using it with something like
int compound(int first[],int second[],int comp[]){
int i=0;
int j;
for(j = 0; first[j] != '\0'; j++){
int val = first[j];
if (contains(second, val) && !contains(comp, val))
comp[i++] = val;
}
return i;
}
Finally, you can test it like
int main(int argc, char *args[]) {
int a[] = {1,2,3,'\0'};
int b[] = {2,3,4,'\0'};
int c[3];
int count = compound(a,b,c);
int i;
for (i = 0; i < count; i++) {
printf("%i\n", c[i]);
}
}
Output is
2
3
If the numeric range is small you could do this:
#include <stdio.h>
#define MAX 20 // small numeric range
#define sz(a) (sizeof(a)/sizeof(*(a)))
int xunion(int *a, int sa, int *b, int sb, int *c) {
int n[MAX] = {0};
for (int i=0; i<sa; i++) n[a[i]] = 1;
for (int i=0; i<sb; i++) n[b[i]] = 1;
int j=0;
for (int i=0; i<MAX; i++) if (n[i]) c[j++] = i;
return j;
}
void prn(int *a, int s) {
while (s-- > 0) printf("%d ", *a++);
putchar('\n');
}
int main() {
int a[] = {6, 3, 4, 7, 5};
int b[] = {2, 4, 5, 7, 6, 3};
int c[MAX];
prn(a, sz(a));
prn(b, sz(b));
int n = xunion(a, sz(a), b, sz(b), c);
prn(c, n);
return 0;
}
Related
Good day everyone,
my task is to remove all negative numbers from an array, and shorten it (return the new length as the amount of positive numbers). I tried doing that by BubbleSort all negative number to the right, and new length would be (old length - number of swap). My code simply freezes up the system.
I would be grateful if you guys could help.
void swap(int *p, int *q) {
int h = *p;
*p = *q;
*q = h;
}
int remove_negatives(int *array, int length) {
int *a;
int n = length;
a = &array[n - 1];
for (int i = 0; i <= n - 1; i++) {
while (array < a) {
if (*array < 0) {
swap(a, array);
a--;
array++;
length--;
}
}
}
printialn(array, n);
return length;
};
int main(void) {
int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
int l = sizeof(a) / sizeof(a[0]);
printiln(remove_negatives(a, l));
return 0;
}
The while loop never stops, that's probably the reason your code freezes.
Your code only changes the address when the if statement is true. Which the array in your main() will stuck on the second (a[1]) element. So if we change change the address when the if statement is false...
#include<stdio.h>
#include<stdlib.h>
void swap(int *p, int *q) {
int h = *p;
*p = *q;
*q = h;
}
int remove_negatives(int *array, int length) {
int *a, *head;
int n = length;
head = array;
a = &array[n - 1];
for (int i = 0; i <= n - 1; i++) {
while (array < a) {
if (*array >= 0) {
array++;
continue;
}
swap(a, array);
a--;
array++;
length--;
}
}
for (int i=0; i<length; i++) {
printf("%d ", *head);
head++;
}
puts("");
return length;
}
int main(void) {
int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
int l = sizeof(a) / sizeof(a[0]);
remove_negatives(a, l);
return 0;
}
Now the while loop works, buts as #wovano said, the answer is still wrong. Your code isn't exactly a "bubble sort". you swap all the negative number to the end of the array and didn't actually sort the array.
So, let's start from the beginning.
To simplify the process, let bubble sort first, and then find the new array length.
#include<stdio.h>
#include<stdlib.h>
void swap(int *p, int *q) {
int h = *p;
*p = *q;
*q = h;
}
int bubble_sort(int *array, int length) {
int i, j;
// Bubble sort
for (i=0; i<length-1; i++) {
for (j=i+1; j<length; j++) {
if (array[i]<array[j]) swap(&array[i], &array[j]);
}
}
// Find new array length
for (i=length-1; i>=0; i--) {
if (array[i]>=0) break;
length--;
}
return length;
}
int main(void) {
int a[] = {-1, 2, 4, -8, 3, 7, -8, 9, 3};
int l = sizeof(a) / sizeof(a[0]);
l = bubble_sort(a, l);
for (int i=0; i<l; i++) printf("%d ", a[i]);
puts("");
return 0;
}
I have this code for permutation WITH repetition. Would anyone help to modify it to be WITHOUT repetition. I can't figure it out.
int array1[] = {1, 2, 3}; //array can be {1,1,2,3} for example also
int array2[3];
void permWithRep (int array1[], int array2[], int last, int index){
int i, len = last+1;
enter code here
for ( i=0; i<len; i++ )
{
array2[index] = array1[i] ;
if (index == last){
for(int i = 0; i < 3; i++) {
printf("%d ", array2[i]);
}
printf("\n");
}
else // Recur for higher indexes
permWithRep (array1, array2, last, index+1);
}
}
int main()
{
int len = sizeof(array1)/sizeof(int);
permWithRep (array1, array2, len-1, 0);
return 0;
}
I tested this on few inputs and it works.
There is certainly a better way to do it, but that's what i did:
#include <stdio.h>
int array1[] = {1, 2, 3}; //array can be {1,1,2,3} for example also
int array2[3];
int fixed[3];
void permWithRep(int array1[], int array2[],int fixed_index[], int size , int level){
if(level == size) return print_array(array2,size);
for(int k = 0; k< size; k++){
if(!is_present_in_fixed(fixed_index,level,k)){
fixed_index[level] = k;
array2[level] = array1[k];
permWithRep(array1,array2,fixed_index,size,level+1);
}
}
}
void print_array(int array[], int size){
for(int k = 0; k < size; k++)printf("%d ",array[k]);
printf("\n");
}
int is_present_in_fixed(int array[], int size, int element ){
for(int k =0; k<size;k++)
if(element == array[k]) return 1;
return 0;
}
int main()
{
int len = sizeof(array1)/sizeof(int);
permWithRep (array1, array2, fixed, len, 0);
return 0;
}
What I did:
Add an array (fixed_index[]) that keep track of the already visited indexes for one permutation.
In the loop, check if the index of current element belongs to the index already visited in that permutation (is_present_in_fixed(fixed_index,level,k)).
If so, it just skip that element (it does not enter the if statement).
Otherwise adds that element to the visited for that permutation and go on with recursive call.
When all array has been iterated on (level == size), just print the results contained in array2.
I want to a fill a small 2 d array with arbitrary values before moving onto a bigger array. However, when I compile and run my program, I get some weird output. It is not perfectly square. if someone could point out what im doing wrong that would be great.
void startarray(char (*arr)[10], int y_length, int x_length);
void printarray(char (*arr)[10], int y_length);
int main()
{
char arr[10][10];
startarray(arr, 10,10);
printarray(arr, 10);
return 0;
}
void startarray(char (*arr)[10], int y_length, int x_length)
{
int i;
int j;
for(i = 0; i <= y_length; i++)
{
for(j = 0; j < x_length; j++)
{
arr[i][j] = 'a';
}//end for
arr[i][j] = '\0';
}//end for
}
void printarray(char (*arr)[10], int y_length)
{
int i = 0;
while(i < y_length)
{
printf("\n%s", arr[i]);
i++;
}//end while
}
In my code the following function exists:
int Count_border(int loc[], int search[], int search_c){
int count = 0, i, j;
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0] + j][loc[1]], search, search_c) == 1) count++;
}
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0]][loc[1] + j], search, search_c) == 1) count++;
}
return count;
}
In this function I am searching for values in the array search. How it is done doesn't matter for this question. My question is however, how can I input a "manual" array, like this: Count_border(con_input, {-1, 0, 1}, 3);
This syntaxis isn't allowed by the compiler. And I don't want to create an array before the function, I really want to hardcode it.
Thank you for your help!
EDIT:
Now I am getting this error:
In function 'main':
file.c:40:1: error: expected ';' before '}' token
}
^
file.c:85:1: error: expected declaration or statement at end of input
}
Where this is my whole code, PLEASE help me out.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void Put(int letter, int number);
void Set(int letter, int number, int who);
void Init_board();
int Count_border(int loc[], int search[], int search_c);
int In_array(int val, int arr[], int size);
int BOARD[9][9]; // 0 = empty, 1 = me, 2 = enemy
int STONES[2][81][9][9], STONE_COUNTER[2];
int main(void){
char input[5];
int con_input[2], t;
Init_board();
memset(STONES, 0, sizeof(STONES));
memset(STONE_COUNTER, 0, sizeof(STONE_COUNTER));
scanf("%s", input);
if(strcmp(input,"Start") == 0){
Put(4, 4);
}
scanf("%s", input); //get the first input after start
do{
con_input[0] = input[0]-'a'; /* Convert the input */
con_input[1] = input[1];
Set(con_input[0], con_input[1], 2);
t = Count_border(con_input, (int[]){-1, 0, 1}, 3);
printf("%i\n", t);
scanf("%s", input); /* Get the next input */
} while(strcmp(input, "Quit") != 0)
}
void Init_board(){
int i,j;
memset(BOARD, -1, sizeof(BOARD));
for(i = 0; i < 9; i++){
for(j = 0; j < 9; j++){
BOARD[i][j] = 0;
}
}
}
void Put(int letter, int number){
char t = letter + 'a';
printf("%c%i\n", t, number);
//fflush(stdout);
Set(letter, number, 1);
}
void Set(int letter, int number, int who){
BOARD[letter][number] = who;
}
int Count_border(int loc[], int search[], int search_c){
int count = 0, i, j;
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0] + j][loc[1]], search, search_c) == 1) count++;
}
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0]][loc[1] + j], search, search_c) == 1) count++;
}
return count;
}
int In_array(int val, int arr[], int size){
int i;
for (i=0; i < size; i++) {
if (arr[i] == val)
return 1;
}
return 0;
}
/* notes:
fflush(stdout);
*/
If you have a C99 (or newer) compiler just do
Count_border(con_input, (int[]){-1, 0, 1}, 3);
this (int[]){ something } is called a compound literal in C jargon and defines a temporary object (here an int array with 3 elements) that you can pass to your function.
Something like this?
#include <stdio.h>
void f(char arr[]);
int main(int argc, char *argv[])
{
f((char [4]){'1', '2', '3', '5'});
return 0;
}
void f(char arr[4])
{
int i;
for (i = 0; i < sizeof(arr)/sizeof(*arr); i++)
printf("%c ", arr[i]);
putchar('\n');
}
I am trying to find the max number in an array. I have created a function and I am using the following code:
int maxValue( int myArray [], int size)
{
int i, maxValue;
maxValue=myArray[0];
//find the largest no
for (i=0;i)
{
if (myArray[i]>maxValue)
maxValue=myArray[i];
}
return maxValue;
}
However I get a syntax error before ) token. What am I doing wrong and am I even doing this right? Any help would be greatly appreciated.
You must pass a valid array with at least one member to this function:
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int
maxValue(int myArray[], size_t size) {
/* enforce the contract */
assert(myArray && size);
size_t i;
int maxValue = myArray[0];
for (i = 1; i < size; ++i) {
if ( myArray[i] > maxValue ) {
maxValue = myArray[i];
}
}
return maxValue;
}
int
main(void) {
int i;
int x[] = {1, 2, 3, 4, 5};
int *y = malloc(10 * sizeof(*y));
srand(time(NULL));
for (i = 0; i < 10; ++i) {
y[i] = rand();
}
printf("Max of x is %d\n", maxValue(x, sizeof(x)/sizeof(x[0])));
printf("Max of y is %d\n", maxValue(y, 10));
return 0;
}
By definition, the size of an array cannot be negative. The appropriate variable for array sizes in C is size_t, use it.
Your for loop can start with the second element of the array, because you have already initialized maxValue with the first element.
A for loop has three parts:
for (initializer; should-continue; next-step)
A for loop is equivalent to:
initializer;
while (should-continue)
{
/* body of the for */
next-step;
}
So the correct code is:
for (i = 0; i < size; ++i)
the paren after the for seems to be missing some contents.
normally it should be something like
for (i=0; i<size; i++)
include:
void main()
{
int a[50], size, v, bigv;
printf("\nEnter %d elements in to the array: ");
for (v=0; v<10; v++)
scanf("%d", &a[v]);
bigv = a[0];
for (v=1; v<10; v++)
{
if(bigv < a[v])
bigv = a[v];
}
printf("\nBiggest: %d", bigv);
getch();
}