Not sure what i'm doing wrong here. I'm trying to circularly shift elements of a char array left by one. It seems to work, but not persist. I assume it's a pointer issue, but I still don't get how pointers work so i'm not sure where to begin. Problem is, it only seems to change the value inside the for loop and reset afterwards.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void ip();
int main(){
char d[10] = "010";
char k[10] = "1010000010";
initialPermutation(d, k);
return(0);
}
void ip(char * data, char* key){
int i;
// P10(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k3, k5, k2, k7, k4, k10, k1, k9, k8, k6)
char P10[10] = {key[2],key[4],key[1],key[6],key[3],key[9],key[0],key[8],key[7],key[6]};
// split P10 into two segments
char left5[5] = {P10[0],P10[1],P10[2],P10[3],P10[4]};
char right5[5] = {P10[5],P10[6],P10[7],P10[8],P10[9]};
// pre shift binary string
printf("Pre-shift: ");
for(i=0;i<5;i++)
printf("%c",left5[i]);
for(i=0;i<5;i++)
printf("%c",right5[i]);
printf("\n");
// circular shift left one bit (here is where the problem is)
for(i=0;i<5;i++){
char templ = left5[4-i];
left5[4-i] = left5[i];
left5[i] = templ;
char tempr = right5[4-i];
right5[4-i] = right5[i];
right5[i] = tempr;
}
printf("Post- (outside for loop): ");
for(i=0;i<5;i++)
printf("%c",left5[i]);
for(i=0;i<5;i++)
printf("%c",right5[i]);
printf("\n");
}
Your loop is not shifting values, it is reversing the array twice.
It swaps index 0 with index 4, then 1 with 3, then 2 with 2, then 3 with 1, and finally 4 with 0. At this point the array is exactly as when you started.
This code does an actual rotary left shift:
char tmp = left5[0];
for(i = 1; i < sizeof(left5); ++i){
left5[i-1] = left5[i]
}
left5[4] = tmp;
If you actually declare the arrays one element too large you can write:
char left5[6] = {P10[0],P10[1],P10[2],P10[3],P10[4]};
left5[5] = left5[0]
for(i=0; i < 5; ++i){
left5[i] = left5[i+1];
}
Related
I updated the code to find top 5 indices of a float array. Some
how it is only updating top[0]th element for max indices. In the
mentioned example below max indices is like below top[0] = 9, top[1]
=7, top[2]=5 and so on. But it is updating top[0] only.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
double *arr =malloc(sizeof(double)*10);
int N=10;
int n =5;
int *top =malloc(sizeof(int)*10);
arr[0] = 0.123;
arr[1] = 0.345;
arr[2] = 0.445;
arr[3] = 0.545;
arr[4] = 0.645;
arr[5] = 0.745;
arr[6] = 0.542;
arr[7] = 0.945;
arr[8] = 0.145;
arr[9] = 0.995;
int top_count = 0;
int i;
for (i=0;i<N;++i) {
// invariant: arr[top[0]] >= arr[top[1]] >= .... >= arr[top[top_count-1]]
// are the indices of the top_count larger values in arr[0],...,arr[i-1]
// top_count = max(i,n);
int k;
for (k=top_count;k>0 && arr[i]>arr[top[k-1]];k--);
// i should be inserted in position k
if (k>=n) continue; // element arr[i] is not in the top n
// shift elements from k to top_count
printf("6:: Iam here\n");fflush(stdout);
int j=top_count;
if (j>n-1) { // top array is already full
j=n-1;
} else { // increase top array
top_count++;
}
for (;j>k;j--) {
top[j]=top[j-1];
}
// insert i
top[k] = i;
printf("top[%0d] = %0d\n",k,top[k]);
printf("top_count=%0d\n",top_count);
}
return top_count;
}
int top_elems(double *arr, int N, int *top, int n);
int top_count = top_elems(&output, 10, top,5);
output already decomposes to double * do you are passing the address_ of a pointer to double into a function that should take a pointer to double
top is not initialised before the function call so is undefined the first use of it dereferences this undefined pointer
... yeah, I'm not going to go further. your code has some serious but simple to spot issues. If you had made a MCV example, you should have seen some of of them, instead of just dumping your code here.
After code changes:
I updated question to update the top five indices of float array into top[] array. but it is only updating top[0]th element. anything wrong with the code?
Well, I updated the indentation of the code in the question to make it more readable.
You will notice that there is no indentation after this for loop:
for (k=top_count;k>0 && arr[i]>arr[top[k-1]];k--);
This is because the loop body of this loop is:
;
That's it. it is just an empty statement that does nothing. All the loop does is set variables, which are then modified in the rest of the code that follows, but as they are not within a loop, they are only executed the once.
As the loop goes from top_count down to 0, it should be obvious why it is just the first index that is modified.
I am trying to find a way to find the minimum amount of lane to go through. For this program, I must go through all the class in the struct in the according direction as shown in the diagram in the following link:
Direction instruction diagram
In the program provided as example:
I must go through a, b, d and e lane. However, based on the direction, the minimum amount of lane needs to go through is 6. As I need to goes down before goes up on d and I need to goes back up after e.
#include <stdio.h>
#include <stdlib.h>
#define MAX_CLASSES 4
typedef struct{
char alpha;
}class_t;
int
main(int argc, char *argv[]) {
int i, n=MAX_CLASSES;
class_t classes[MAX_CLASSES] = {
[0]={.alpha = 'a'},
[1]={.alpha = 'b'},
[2]={.alpha = 'd'},
[3]={.alpha = 'e'},
};
printf("the letters are:");
for (i=0; i<n; i++){
printf(" %c", classes[i].alpha);
}
printf("\n");
printf("minimum lane is.....?");
return 0;
}
Another example, if I got b and c. Then I must go down first to go up at b and after goes down at c, I need to go back up after so the minimum amount of lane is 4.
And another example, if I got a and b then the minimum amount of lane is 2 as I can just go down at a and goes back up at b.
Something about the alphabet in the struct:
There will not be redundant alphabet
They are in ascending order
They can be in any length (n could be any positive integer)
Any idea how can I calculate the minimum amount of lane in c? Should I use comparison if so how?
This is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CLASSES 3
typedef struct{
char alpha;
}class_t;
int
main(int argc, char *argv[]) {
int i, j, lane, n=MAX_CLASSES;
class_t classes[MAX_CLASSES] = {
[0]={.alpha = 'a'},
[1]={.alpha = 'b'},
[2]={.alpha = 'c'},
};
printf("the letters are:");
for (i=0; i<n; i++){
printf(" %c", classes[i].alpha);
}
printf("\n");
if(n==1){
lane = 2;
}
if(n>1){
lane = 0;
for(i=0; i<j; i++){
for(j=i+1; j<n; j++){
if(classes[i].alpha%2==1){
if(classes[j].alpha%2==1){
lane += 4;
}else{
lane += 2;
}
}else{
lane = 1;
if(classes[j].alpha%2==1){
lane += 4;
}else{
lane += 2;
}
}
}
}
}
if(classes[n-1].alpha%2==1){
lane +=1;
}
printf("minimum lane is %d", lane);
return 0;
}
here is a proposed version of the code that:
cleanly compiles
does not contain 'magic' numbers
properly calculates the value for the variable n
and now the code:
#include <stdio.h>
struct lanes
{
char alpha;
};
typedef struct lanes class_t;
int main( void )
{
int min_lane = 6;
class_t classes[] =
{
[0]={.alpha = 'a'},
[1]={.alpha = 'b'},
[2]={.alpha = 'd'},
[3]={.alpha = 'e'},
};
int n = sizeof( classes ) / sizeof( class_t );
printf("the letters are:");
for (int i=0; i<n; i++)
{
printf(" %c", classes[i].alpha);
}
printf("\n");
printf("minimum lane is %d", min_lane);
return 0;
}
However, the code is meaningless as there is no concept of lane, nor a clear definition of how a lane is to be traversed.
Please re-word the question to indicate what your trying to accomplish.
I am trying to solve two different C problems and would like some help and advice in order to better understand how C works and if I'm on the right track with these.
First problem is: To write a function that counts the number of times the value (x) appears among the first (n) elements of an array and returns that count as the frequency of x in theArray. So, an example would be if the array being passed contained the values {5, 7, 23, 8, 23, 67, 23}. And n was 7 and x was 23, then it would return a value of 3 since 23 occurs 3 times within the first 7 elements of the array.
Here is what I have so far:
#include <stdio.h>
#define SIZE 20 /* just for example - function should work with array of any size */
int frequency (int theArray[], int n, int x)
{
int i;
int count = 0;
for (i = 0; i < n; i++)
{
if (theArray[i] == x)
{
count = count++;
}
}
return (count);
}
int main(void)
{
/* hard code n and x just as examples */
int n = 12; /* look through first 12 items of array */
int x = 5; /* value to find */
int numberFrequency;
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
numberFrequency = frequency (theArray[SIZE], n, x);
printf ("%i", numberFrequency);
return 0;
}
Currently I'm getting a run time error message and believe it has something to do with the for loop function.
Second problem is: Write a function that raises an integer to a positive integer power. Have the function return a long int, which represents the results of calculating x to the nth power. Do not use the C pow library function and do not use recursion!
My code so far:
#include <stdio.h>
int x_to_the_n (int x, int n)
{
int i;
long int result = 1;
if (n == 0)
{
return(result);
}
else
{
for (i = 0; i < n ; ++i)
{
/* equation here - How can I make (x*x*x*x*x*x,etc...? */
result = x*(n*x);
}
}
return (result);
}
int main(void)
{
int x =4;
int n =5;
long int result;
result = x_to_the_n (x, n);
printf ("%i", result);
return 0;
}
I can't use recursion so that is out of the question. So, I thought the next best thing would be a for loop. But I'm a little stuck in how I would go about making a for loop do (xxx*x....) based on value of (n). Any help and advice would be appreciated!
In the first problem you give an element after the array as a parameter to your function.
You define a long int array, and pass it into a function expecting an int array.
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
should be
int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
Instead of this:
numberFrequency = frequency (theArray[SIZE], n, x);
try this:
numberFrequency = frequency (theArray, n, x);
And replace:
count = count++;
with:
count++;
I'm analyzing an array and, using an struct to save the position and the value of each item, I want to get the three minimum values of this array. The problem with this is that I've to ignore a value, '-5' in this case. And if I try to ignore this value, the index messes up and I don't know how to do it.
This is my try:
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
typedef struct pair {
int value, column;
} Pair;
int cmp(const void *a, const void *b);
int main(int argc, char** argv) {
Pair data_pair[8];
int row[8] = {0, 3, 1, -5, 1, 2, 3, 4};
for (int i=0;i<8;++i){
if (row[i] != -5){ // Ignore the value -5 from the array
data_pair[i].value = row[i];
data_pair[i].column = i;
}
}
printf("\n\nThe three minimum values of this line are:");
qsort(data_pair, 8, sizeof(Pair), cmp);
for(int i=0;i<3;++i)
printf("\nvalue = %d, column = %d", data_pair[i].value, data_pair[i].column);
return 0;
}
int cmp(const void *a, const void *b){
Pair *pa = (Pair *)a;
Pair *pb = (Pair *)b;
return pa->value - pb->value; }
This is the exit I'm having:
The three minimum values of this line are:
value = 0, column = 0
value = 0, column = 0
value = 1, column = 4
When the desired solution is:
The three minimum values of this line are:
value = 0, column = 0
value = 1, column = 2
value = 1, column = 4
What I'm doing wrong? I would like to have a solution just changing some parts of the exposed code. Thanks in advance
Your issue at hand stems from using a shared index i and sorting the array regardless of how many items you actually have in the array (e.g. passing 8 unconditionally as the size).
By not setting the values at all indexes in data_pair, you're sorting some garbage results in the mix!
So you can use a second indexer with data_pair to help filter the results:
/* somewhere above: int j; */
for (i=0, j=0;i<8;++i){
if (row[i] != -5){ // Ignore the value -5 from the array
data_pair[j].value = row[i];
data_pair[j].column = i;
j++; /* indexes data_pair */
}
}
Now j will contain the count of found Pairs in data_pairs:
/* j substitutes for an explicit 8 */
qsort(data_pair, j, sizeof(Pair), cmp);
if (row[i] != -5){ // Ignore the value -5 from the array
data_pair[i].value = row[i];
data_pair[i].column = i;
} else {// add
data_pair[i].value = INT_MAX;//#include <limits.h>
data_pair[i].column = i;
}
I was writing a program to concatenate two arrays in C. I am allocating memory for a third array and using memcpy to copy the bytes from the two arrays to the third. The test output is:
1 2 3 4 5 0 0 0 0 0
Is there anything wrong with this approach?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int *array_concat(const void *a, int an,
const void *b, int bn)
{
int *p = malloc(sizeof(int) * (an + bn));
memcpy(p, a, an*sizeof(int));
memcpy(p + an*sizeof(int), b, bn*sizeof(int));
return p;
}
// testing
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };
int main(void)
{
unsigned int i;
int *c = array_concat(a, 5, b, 5);
for(i = 0; i < 10; i++)
printf("%d\n", c[i]);
free(c);
return 0;
}
memcpy(p + an*sizeof(int),...
this second memcpy, you are trying to add 5 * sizeof(int) to an int pointer, p. However, when you add to a pointer, it already knows that it has to deal with sizeof(type), so you don't have to tell it.
memcpy(p + an,...
Remove the multiplication *sizeof(int) from the 1st argument of memcpy. Keep it in the argument of malloc and the 3rd argument of memcpy.
This is because p + an points to an int which is an ints to the right from p -- that is, the int which is an*sizeof(int) bytes to the right from p.
p is a pointer to int. When you add an integer to a pointer to an int, the compiler multiplies the integer by the size of an integer. The net result is to multiply by the size of an integer twice: what you're getting is "p + an*sizeof(int)" is p + (number of elements in a) * (number of bytes in an int) * (number of bytes in an int).
memcpy(p + an*sizeof(int), b, bn*sizeof(int));
should be:
memcpy(p + an, b, bn*sizeof(int));
You should remove sizeof(int) from second memcpy where you use pointer arithmetic (+).
Compiler doing this by itself depending on type of pointer.
you should see the definition of the memcpy, which copy's n "bytes" from the src to the dst area. so,you just need to times sizeof(int) only for the 3rd argument. and for "c", it's a pointer of int type, so, it does know that "+an" means move p forward to the an+1 int position.
Merging can be done by sorting the elements of the elements which are going to be merged code for merging two arrays
#include<stdio.h>
void sort(int arr[],int size){ // sorting function
int i,j,temp;
for(i=0;i<size;i++){
for(j=i;j<size;j++){
if(arr[i]>arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main(){
int a[10],b[10],c[10];
int n,i,k=0,j=0;
printf("Enter the size of the array:");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter the element of array A at index %d:",i); //input array A
scanf("%d",&a[i]);
}
sort(a,n);
for(i=0;i<n;i++){
printf("Enter the element of array B at index %d:",i); //Input array B
scanf("%d",&b[i]);
}
sort(b,n);
for(i=0;i<(n+n);i++){ // merging the two arrays
if(a[k]<b[j]){
c[i] = a[k];
k++;
}
else{
c[i] = b[j];
j++;
}
}
printf("Merged Array :\n");
for(i=0;i<(n+n);i++){
printf("c -> %d ",c[i]);
}
return 0;
}
Reference C program to Merge Two Arrays after Sorting