C recursive permutations - c

i have been trying to complete figure out this part of my assignment to no avail for the past day, and require some help or guidance to help understand the problem.
so far i have this:
swap(int A, int B){
int temp;
temp = A;
A = B;
B = temp;
}
int max_array(int array[], int arraySize)
{
int i, max=-32000;
for (i=0; i<arraySize; i++)
{
if (array[i]>max)
{
max=array[i];
}
}
printf("%d \n Max array: ", max)
return(max);
}
int nextPermutation(int array[], int arraySize){
int i;
n = max_array(array, arraySize);
if (int i; n == array[i] && i > 1; i++){
swap(array[i], array[i-1]);
}
else if(int i; n == array[i]; i++){
}
}
void main(){
int intArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//int intArray[10] = {1, 10, 3, 9, 8, 6, 7, 2, 4, 5};
nextPermutation(intArray, 10);
int i = 0;
for(i = 0; i < 10; i++){
printf("%d ",intArray[i]);
}
}
But the question that i'm struggling to understand is
"If a1,...,an is an arbitrary permutation (where a1,...,an are the numbers 1, 2, …, n in a probably different order) then the “next” permutation is produced by the
following procedure:
(i) If the maximal element of the array (which is n) is not the first element of the
array, say n=ai , where i>1 , then to produce the "next" permutation you
need to swap ai and ai−1 .
(ii) If the maximal element of the array is in the first position, i.e. n=a1 , then to
produce the “next” permutation to the permutation (a1,...,an)
, first find the “next” permutation to the (n-1)-element permutation (a2,...,an
), and then append a1 to the end of thus obtained array of (n-1) elements."
so it needs to permutate every single possible combination with the array of 1,2,3,4,5,6,7,8,9,10 and then finish when it reaches this point "(n, …, 2, 1). And this is
the only permutation that does not have the "next" permutation to it."
And the function int 'nextPermutation(int array[], int arraySize){' needs to stay the same.
Any help or tips will be excellent!

There are some errors in your program,
swap() function will not affect the program as it doesn't use pass by reference.
max_array() should find the index of the maximum value, not the maximum value itself.
There is no recursion in your program as far as I can see.
main() should return int.
The program fragement given below might give you an idea,
int ct=-1,n=10,temp[10]={0,0,0,0,0,0,0,0,0,0};
int intArray[10]={1,2,3,4,5,6,7,8,9,10};
permute(int k)
{
int i;
temp[k]=++ct;
if(ct==n-1)
{
for(i=0;i<n;i++)
{
printf("%d",intArray[temp[i]]);
}
printf("\n");
}
for(i=0;i<n;i++)
{
if(temp[i]==0)
{
permute(i);
}
}
ct--;
temp[k]=0;
}
int main()
{
permute(0);
}

for swap sample
#include <stdio.h>
void swap(int* A, int* B){
int wk;
wk = *A;
*A = *B;
*B = wk;
}
int main(void){
int array[] = { 1,2,3 };
swap(&array[0], &array[2]);
printf("array[0]=%d, array[2]=%d\n", array[0], array[2]);
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;
}

Properly Partitioning QuickSort Array

I'm a beginner in C and I've been trying to code a Quicksort program that can take a randomly generated array of real numbers and its size as its argument, and then sorts the elements in ascending order. I cannot figure out what to put in the array size field in the first recursive call of the function QuickSort, which is meant to represent the subarray A[0...q-1]. As far as I can tell, the rest of the code is fine because when linked to a driver program that generates the random numbers, the program returns the elements, albeit in the incorrect order. I appreciate any help/suggestions.
int Partition(float *,int);
int QuickSort(float *A,int n)
{
int q;
if(n>1){
q = Partition(A,n);
QuickSort(&A[],q); //Trying to figure out what to put in here.
QuickSort(&A[q+1],(n-1)-q); //This recursion sends the subarray A[q+1...n-1] to QuickSort, I think it works fine.
}
}
int Partition(float *A,int n){
int i,j;
float x;
x = A[n-1];
i=0;
for(j=0;j<=n-2;j++){
if(A[j] <= x){
A[i]=A[j];
i = i+1;
}
}
A[i]=A[n-1];
return i;
}
You're only problem is you seem to confuse:
A[i]=something;
with swapping A[i] and something. Add an auxiliary tmp, or write a swap function:
#include<stdio.h>
int Partition(float *,int);
void QuickSort(float *A,int n) {
int q;
if(n>1){
q = Partition(A,n);
QuickSort(A,q); //Trying to figure out what to put in here.
QuickSort(A+q+1,(n-q-1)); //This recursion sends the subarray A[q+1...n-1] to QuickSort, I think it works fine.
}
}
int Partition(float *A,int n){
int i,j;
float x;
float tmp;
x = A[n-1];
i=0;
for(j=0;j<=n-2;j++){
if(A[j] <= x){
tmp = A[i];
A[i]=A[j];
A[j]=tmp;
i = i+1;
}
}
tmp = A[i];
A[i]=A[n-1];
A[n-1]=tmp;
return i;
}
int main() {
float A[] = {3, 4, -5, 10, 21, -9, -1, 7, 8, 10};
QuickSort(A,10);
for(int i = 0; i < 10; i ++)
printf("%f ",A[i]);
return 0;
}

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

check if array contains all array values from another array in C

I tried to make a program that will check if an an array contains all the array values from another array. So, if that's true, the program will return 1 using a value for it. If it isn't true, it will return 0(I named it p). I failed to make that program though. Could you please help me?
#include <stdio.h>
int isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0;
int j = 0;
for (i=0; i<n; i++)
{
for (j = 0; j<m; j++)
{
if(arr2[i] == arr1[j])
break;
}
/* If the above inner loop was not broken at all then
arr2[i] is not present in arr1[] */
if (j == m)
return 0;
}
/* If we reach here then all elements of arr2[]
are present in arr1[] */
return 1;
}
int main()
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 2, 7, 1};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
if(isSubset(arr1, arr2, m, n))
printf("arr2[] is subset of arr1[] ");
else
printf("arr2[] is not a subset of arr1[]");
getchar();
return 0;
}
Ideone Link up and running : http://ideone.com/4u9oQm

Resources