Is there a way to code something like this in C? - c

Input 1: 90009
Input 2: 8999
Input 3: 94738
(Output: 90009 94738 8999)
see the pattern
it sorts the value of 3 integer inputs in a such a way one input continues another by matching the starting digit and the ending digit of another integer
#include <stdio.h>
void swap( int *x , int * y)
{
double t = *x;
*x = *y;
*y = t;
}
int sort(int *x, int *y, int *z)
{
int getZ;
getZ = *z;
while(getZ>=10)
getZ=getZ/10;
if(*x % 10 == *y/ 1000)
swap(y,x);
if(*x%10 != *z/1000)
swap(z,y);
if(*y % 10 == getZ)
swap(z,y);
printf("Sorted Version is %d %d %d",*x,*y,*z);
}
For some reason im not getting the order that i want. Is there algorithm to write this code with?

The simplest way is just to check every permutation. This code can be more compactly written, but here's a very straightforward implementation:
#include <stdio.h>
int first_digit(int n) {
while (n > 10) n /= 10;
return n;
}
int last_digit(int n) {
return n % 10;
}
int sort(int *x, int *y, int *z) {
int n[3] = {*x, *y, *z};
int permutations[][3] = {
{0, 1, 2},
{0, 2, 1},
{1, 0, 2},
{1, 2, 0},
{2, 0, 1},
{2, 1, 0},
};
for (int i = 0; i < sizeof(permutations) / sizeof(*permutations); i++) {
int *idx = permutations[i];
if (last_digit(n[idx[0]]) == first_digit(n[idx[1]]) && last_digit(n[idx[1]]) == first_digit(n[idx[2]])) {
*x = n[idx[0]];
*y = n[idx[1]];
*z = n[idx[2]];
return 1;
}
}
return 0;
}
int main() {
int x=126, y=456, z=6001;
if (sort(&x, &y, &z)) {
printf("sorted version is %d %d %d\n", x, y, z);
} else {
printf("sort not possible for %d %d %d\n", x, y, z);
}
return 0;
}

Related

Remove negative numbers and sort an array

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;
}

C code for converting decimal to any base (from 2 to 36)

I have just recently started learning C. I wrote a very short program that converts between decimal and binary. I wanted to try and write a code that converts between decimal and any base (up until 36). However, my code just prints out garbage.
#include <stdio.h>
#include <string.h>
void printBase(int n, int k, int i, char a[])
{
int placeholder;
if (n != 0)
{
//return n % 2 + 10 * printBinary(n / 2);
placeholder=(char)(n%k);
if(placeholder>=10)
{
a[i] = (char)(placeholder - 10) + 'A';
} else {
a[i] = (char)placeholder;
}
i++;
printBase(n/2, k, i, a);
}
for (i=0; a[i]!='\0'; i++)
{
printf("%c", a[i]);
}
return;
}
void reverse(char fromStr[], char toStr[])
{
int i, j=0;
i=getchar();
for (i=0; fromStr[i]!='\0'; i++)
{
j++;
}
i=0;
while (j>=0)
{
toStr[i]=fromStr[j];
i++;
j--;
}
printf("%s", toStr);
}
int main()
{
int n, k;
char a[81], b[81];
setvbuf(stdout, NULL, _IONBF, 0);
printf("Enter a deicmal number you want to convert to binary: ");
scanf("%i", &n);
fflush(stdout);
printf("Enter a base: ");
scanf("%i", &k);
printBase(n, k, 0, a);
//printf("%s", a);
//reverse(a, b);
return 0;
}
I thought the problem was with my reverse function but it works fine outside of this code. Even when I print out string a inside the printBase function it prints out garbage. What is the problem here?
Based on your code, the following does what you want. It places in a a reverse conversion that must still be printed backwards:
void convertBase(int n, int k, char a[])
{
int j, i=0, sign= 0;
if (n==0) a[i++]='0';
if (n<0 ) {sign= -1; n= -n;}
while (n>0) {
j= n%k;
if (j<10)
a[i]= j+'0';
else
a[i]= j+'A';
n= n/k;
i++;
}
if (sign== -1) a[i++]= '-';
a[i]= 0;
}
And here is revert:
void revStr(char *s)
{
char c;
int i=0, j=0;
while (s[i]) i++; i--;
while (i>j) {
c= s[j];
s[j]=s[i];
s[i]= c;
i--; j++;
}
}
With some general implementation of itoa
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
static const char* DIGISTS = "0123456789ABCDEFGHIKLMNOPQRSTVXYZ";
void itoa(long long i, unsigned char radix, char* to) {
char *s = to + 65;
char sign;
unsigned len;
if(i < 0) {
sign = 1;
len = 2;
} else {
sign = 0;
len = 1;
}
*s = '\0';
do {
*(--s)= * ( DIGISTS + abs(i % radix) );
i /= radix;
++len;
} while(i != 0);
if(sign)
*(--s) = '-';
memmove( to, s, len );
}
int main(int argc, const char** argv)
{
char a[65];
itoa( LLONG_MAX, 2, a);
printf("binary: %s \n", a);
itoa(12345, 10, a);
printf("digit: %s \n", a);
itoa(64018, 16, a);
printf("hex : 0x%s \n", a);
itoa(-24, 24, a);
printf("base 24 : base24x%s \n", a);
itoa(LLONG_MAX, 36, a);
printf("base 36 : base36x%s \n", a);
return 0;
}
#define c ('A' - 10)
int n = 4564567; // any number
int b = 16; // any base
int tmp = n < 0 ? -n : n;
int i = 0;
while (tmp)
{
tmp /= b;
++i; // you need to calculate how long will be the number
}
while (i--)
{
a[i] = n % b + ((n % b < 10) ? '0' : c); // you have to check if the remaining is below 10 or not. That is very important
n /= b;
}
I think you forgot to add '0' in the else case
Adapted from an old source file https://github.com/agavrel/42-ft_printf/blob/master/srcs/pf_number.c
An alternative to reversing the array uses recursion.
As the number of digits in some integer type in never so great, recursion will not be excessive.
The below used a do {} while loop to avoid a special case with printBase(0).
It also uses negative values in printBase_helper() where /,% is well defined with C99. This avoids undefined behavior of code like n = -n when n == INT_MIN.
void printBase_helper(int neg, int base) {
if (neg <= -base) {
printBase_helper(neg / base, base);
neg %= base;
}
putchar("0123456789ABCDEFGHIJKLMONOPQSTUVWXYZ"[-neg]);
}
void printBase(int n, int base) {
if (n < 0) {
putchar('-');
} else {
n = -n;
}
printBase_helper(n, base);
}
Test code
int main(void) {
int value[] = {0, 1, -1, 10, INT_MAX, INT_MIN};
int base[] = {10, 2, 36};
for (unsigned v = 0; v < sizeof value / sizeof value[0]; v++) {
for (unsigned b = 0; b < sizeof base / sizeof base[0]; b++) {
printf("Base %2d, value %11d, --> base %2d, value ", 10, value[v], base[b]);
printBase(value[v], base[b]);
printf("\n");
}
}
return 0;
}
Output
Base 10, value 0, --> base 10, value 0
Base 10, value 0, --> base 2, value 0
Base 10, value 0, --> base 36, value 0
Base 10, value 1, --> base 10, value 1
Base 10, value 1, --> base 2, value 1
Base 10, value 1, --> base 36, value 1
Base 10, value -1, --> base 10, value -1
Base 10, value -1, --> base 2, value -1
Base 10, value -1, --> base 36, value -1
Base 10, value 10, --> base 10, value 10
Base 10, value 10, --> base 2, value 1010
Base 10, value 10, --> base 36, value A
Base 10, value 2147483647, --> base 10, value 2147483647
Base 10, value 2147483647, --> base 2, value 1111111111111111111111111111111
Base 10, value 2147483647, --> base 36, value ZIK0ZJ
Base 10, value -2147483648, --> base 10, value -2147483648
Base 10, value -2147483648, --> base 2, value -10000000000000000000000000000000
Base 10, value -2147483648, --> base 36, value -ZIK0ZK
I didn't know that answers to my own question should be posted below, sorry!
But here is the code that I wrote on my own if it helps anyone:
#include <stdio.h>
#include <string.h>
void printBinary(int n, int k, int i, char a[])
{
int placeholder;
if (n != 0)
{
placeholder=(n%k);
if(placeholder>=10)
{
a[i] = (placeholder - 10) + 'A';
} else if(placeholder>=0 && placeholder<=9){
a[i] = placeholder + '0';
}
i++;
a[i]='\0';
printBinary(n/k, k, i, a);
}
return;
}
int main()
{
int n, k;
char a[81], b[81];
setvbuf(stdout, NULL, _IONBF, 0);
printf("Enter a deicmal number you want to convert to binary: ");
scanf("%i", &n);
fflush(stdout);
printf("Enter a base: ");
scanf("%i", &k);
printBinary(n, k, 0, a);
n=strlen(a);
k=0;
n--;
while (n>=0)
{
b[k]=a[n];
n--;
k++;
}
b[k]='\0';
printf("%s", b);
return 0;
}
Try this one.
#include<stdio.h>
int main()
{
int n,b,t1,i=0;
float t2,t3,t4;
int a[10];
scanf("%d%d",&n,&b);
for( i=0; n!=0; i++)
{
t1=n/b;
t2=(float)n/b;
t3=(float)t2-t1;
t1=t3*b;
t2=(float)t3*b;
t4=(float)t2-t1;
if(t4>=0.5)
{
a[i]=t3*b+1;
}
else
{
a[i]=t3*b;
}
n=n/b;
}
for(int j=i; j>0; j--)
{
printf("%d",a[j-1]);
}
return 0;
}

Find max, min and sum of an array using function

I want to create a programm to find maximum, minimum and summation for a given array, but when I take my code to compiler, it returned expressed expression before 'int' and too few arguments to all the functions.
And here is my code, please tell me why it doesn't work.
#include <stdio.h>
#include <stdlib.h>
void print_array(int array[], int len) {
// print array on screen
int b;
printf("Array: ");
for (b = 0; b < len - 1; b++) {
printf("%d, ", array[b]);
}
if (b >= len - 1) {
printf("%d\n", array[b]);
}
}
// function
int min(int *x, int len) {
int mintemp = x[0], i;
for (i = 1;i < len;i++) {
if(x[i] < mintemp) {
mintemp = x[i];
}
}
return mintemp;
}
int max(int *y, int len) {
int maxtemp = y[0], j;
for (j = 1;j < len;j++) {
if(y[j] > maxtemp) {
maxtemp = y[j];
}
}
return maxtemp;
}
int sum(int *z, int len) {
int sumtemp = 0, k;
for (k = 0;k < len;k++) {
sumtemp = sumtemp + z[k];
}
return sumtemp;
}
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(int *x, int len));
printf("Minimum: %d\n", min(int *y, int len));
printf("Summation: %d\n", sum(int *z, int len));
return 0;
}
The problem was with calling the functions. Function call in C is like this
function_name(argument 1, argument 2, argument 3, ......, argument n);
There is no need to specifying the data type along the parameters in the call like you were doing in your code.
Also you were passing pointers x, y and z that do not point to your array.
I have corrected the code as shown below.
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(array, len)); // pass array and len
printf("Minimum: %d\n", min(array, len));
printf("Summation: %d\n", sum(array, len));
return 0;
}
If you want to pass the array to functions via pointers you can do it like this.
int main() {
int array[] = {3, 9, 1, 2, 5, 8, 7, 6, 4, 10, 11};
int len = 11;
int *x = array;
int *y = array;
int *z = array;
print_array(array, len);
// print other elements on screen
printf("Maximum: %d\n", max(x, len));
printf("Minimum: %d\n", min(y, len));
printf("Summation: %d\n", sum(z, len));
return 0;
}
Also there is no need to declare 3 different pointers and pass it to the functions, you can declare just one and reuse it with subsequent calls.
Hope this helps.!!

Completing my addarray () formula

I apologize for my vagueness in advance-this is my first post and I can really use some help.
The assignment is as follows:
/* Write a function named addarray() that returns the sum of the
elements of an array of int values. Your functions should take two
parameters, the array and the number of elements in the array. Make
your function work with the following program; */
/* arraysum.c
*
* Synopsis - displays the value returned by the function addarray()
* with 2 different sets of parameters.
*
* Objective - To provide a test program for the addarray() function.
* Your answers should be 55 and 0.
*
*/
#include <stdio.h>
int addarray(int [], int, int);
void main() {
int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int array2[4] = {0, 0, 0, 0};
printf("The sum of array1 = %d\n", addarray(array1, 0, 10));
printf("The sum of array2 = %d\n", addarray(array2, 0, 4));
}
This is my solution aid:
int addarray(int s[], int i, int n) {
int sum = 0;
for (i = 0; i < n; i++) {
sum += s[i];
}
return sum;
}
I cant seem to figure out how to get the proper result. Any help would be appreciated.
This is what I have completed so far:
#include <stdio.h>
int addarray(int array1[], int num_elements);
void print_array(int array1[], int num_elements);
void main(void)
{
int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum;
printf("\nArray:\n");
print_array(array1, 10);
sum = addarray(array1, 10);
printf("The sum is %d\n .", sum);
}
int addarray(int array1[], int num_elements)
{
int i, sum=0;
for (i=0; i<num_elements; i++)
{
sum = sum + array1[i];
}
return(sum);
}
void print_array(int array1[], int num_elements)
{
int i;
for(i=0; i<num_elements; i++)
{
printf("%d ", array1[i]);
}
printf("\n");
}
I cant figure out how to get a second array to be summed up.
Such as Array2.
int is a reserved word.you can't give a variable the name int.besides,the assignment says the function should take two parameters,not 3.check this :
#include <stdio.h>
int addarray(int arr[],int size);
void main() {
int array1[10] = {1,2,3,4,5,6,7,8,9,10};
int array2[4] = {0,0,0,0};
printf("The sum of array1 = %d\n", addarray(array1,10));
printf("The sum of array2 = %d\n", addarray(array2,4));
}
int addarray(int arr[],int size)
{
int sum = 0 , n ;
for( n = 0 ; n < size ; n++ )
{
sum += arr[n];
}
return sum;
}

largest sum contiguous sub array using recursion to directly output result

Is is possible to find the largest sum contiguous sub array using recursion such that the function would directly return the output.
Below is my solution where I store the max subarray ending at each index and then find the largest among those in the print() function. However, I want the following
Use recursion
Use the recursive function to directly output the final result.
My code which uses a recursive function and a helper print() function to find the largest among those numbers
#include <stdio.h>
//int a[] = {-6,60,-10,20};
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int len = sizeof(a)/sizeof(*a);
int maxherearray[10];
int main(void)
{
fun(len-1);
printf("max sub array == %d\n",print(maxherearray));
printf("\n");
return 0;
}
int fun(int n)
{
if(n==0)
return a[n];
maxherearray[n] = max(a[n], a[n]+fun(n-1));
return maxherearray[n];
}
int max(int a, int b)
{
return (a > b)? a : b;
}
EDIT : Posting the print() function which I somehow missed out
//Please make sure that #include <limits.h> is added
int print(int a[])
{
int i = 0;
int largest = INT_MIN;
printf("largest == %d\n",largest);
for(i=0;i<len;i++)
{
if(a[i] > largest)
largest = a[i];
}
return largest;
}
Generally, your algorithm logic is OK. It's like,
f(0) = a(i);
f(i) = max(f(i-1) + a(i), a(i));, get the middle result array
max(0, f(1), f(2), ... , f(n-1)), get the final max_sub result
And you designed a function namedfun for #2, and a helper print() for #3.
Now, (I guess ) what you'd like is to combine #2 and #3 together, i.e., to utilise the middle results of #2 to avoid extra computing/memory space. In terms of your original algorithm logic, here are some possible ways, such as
Add a parameter in your fun to keep max_sub result
int fun(int n, int *result)// add int *result to return max_sub
{
int max_here = 0;
if(n==0){
return a[n];
}
max_here = max(a[n],a[n]+fun(n-1, result));
*result = max(*result, max_here);
return max_here;
}
//...
int main(void)
{
int result = 0;
fun(len-1, &result);
printf("max sub : %d\n", result);
}
Use a global variable (Oh!) to get max_sub in time
int g_maxhere = 0;
int fun2(int n)
{
if(n==0){
return a[n];
}
g_maxhere = max(g_maxhere, max(a[n],a[n]+fun2(n-1)));
return max(a[n], a[n]+fun2(n-1));
}
//...
int main(void)
{
fun2(len-1);
printf("max sub:%d\n",g_maxhere)
}
In fact, your original solution of using a helper function can make your algorithm more clear.
Introduce two global variables, start_idx and end_idx to track the start and end indices of the largest contiguous subarray. Update these variables accordingly in the recursive function.
#include <stdio.h>
/* int a[] = {-6,60,-10,20}; */
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int len = sizeof(a)/sizeof(*a);
int maxherearray[10];
int fun(int n);
int max(int a, int b);
int find_max(int a[], int len);
void print_array(int a[], int start_idx, int end_idx);
int start_idx = 0; // Start of contiguous subarray giving max sum
int end_idx = 0; // End of contiguous subarray giving max sum
#define NEG_INF (-100000)
int max_sum = NEG_INF; // The max cont sum seen so far.
int main(void)
{
start_idx = 0;
end_idx = len - 1;
maxherearray[0] = a[0];
printf("Array a[]: ");
print_array(a, 0, len-1);
printf("\n");
// Compute the necessary information to get max contiguous subarray
fun(len - 1);
printf("Max subarray value == %d\n", find_max(maxherearray, len));
printf("\n");
printf("Contiguous sums: ");
print_array(maxherearray, 0, len - 1);
printf("\n");
printf("Contiguous subarray giving max sum: ");
print_array(a, start_idx, end_idx);
printf("\n\n");
return 0;
}
int fun(int n)
{
if(n==0)
return a[0];
int max_till_j = fun(n - 1);
// Start of new contiguous sum
if (a[n] > a[n] + max_till_j)
{
maxherearray[n] = a[n];
if (maxherearray[n] > max_sum)
{
start_idx = end_idx = n;
max_sum = maxherearray[n];
}
}
// Add to current contiguous sum
else
{
maxherearray[n] = a[n] + max_till_j;
if (maxherearray[n] > max_sum)
{
end_idx = n;
max_sum = maxherearray[n];
}
}
return maxherearray[n];
}
int max(int a, int b)
{
return (a > b)? a : b;
}
// Print subarray a[i] to a[j], inclusive of end points.
void print_array(int a[], int i, int j)
{
for (; i <= j; ++i) {
printf("%d ", a[i]);
}
}
int find_max(int a[], int len)
{
int i;
int max_val = NEG_INF;
for (i = 0; i < len; ++i)
{
if (a[i] > max_val)
{
max_val = a[i];
}
}
return max_val;
}

Resources