I have the following code:
void sortStrings(char strings[5][32])
{
int i = 0, j = 0, wall = 0;
int min = i;
for (int i = wall; i < 5; i++){
min = i;
for (j = wall; j < 5; j++){
if (strcmp(strings[j], strings[min]) < 0){
min = j;
}
}
swapStrings(strings[min], strings[wall]);
wall++;
}
}
What this code does is sorts a 2d array of strings by alphabetical order, I have tested it and it works correctly, now my question is how could I implement this code WITHOUT using array operations (aka using pointers and pointer operations only).
This is what I have so far and it is crashing when I try to run it so what am I doing wrong?
{
int i = 0, j = 0, wall = 0;
char *p = strings;
int min;
for (i = wall; i < 5; i++){
min = i;
for (j = wall; j < 5; j++){
if (*(p + j) < *(p + min)){
min = j;
}
}
swapStrings(*(p + j),*(p + wall));
wall++;
}
}
Here is the swapStrings method I am using for reference:
void swapStrings(char string1[], char string2[])
{
char temp[32];
strcpy(temp, string1);
strcpy(string1, string2);
strcpy(string2, temp);
}
The expected output is: if I were to enter in 5 strings, lets say they are:
hello
goodbye
how
are
you
It should return:
are
goodbye
hello
how
you
Thank you.
You have two things wrong:
p have to be char** and not char*
Comparing yourself between strings need a loop such:
int t = 0;
while (*(*(p + j)+t) && (*(*(p + j) + t) == *(*(p + min) + t)))
t++;
if (*(*(p + j) + t) < *(*(p + min) + t)) {
min = j;
}
Maybe you want to write your function for compare.
Related
This is the question:
https://www.hackerrank.com/challenges/lisa-workbook/problem.
My code passes all the test cases except one. The message I get is just Run Time Error. Even if I return 0 at the beginning of the function that I am supposed to implement, I still get this error, while in all other test cases I get Wrong Answer.
This is not the only question on hacker rank where this happened. In the last couple of days I encountered 3 or 4 more questions with that one odd case that was always giving a runtime error. In the end, I had to implement a Python 3 solution (with the same logic), which passed all the test cases, to solve these problems.
I wonder if this is a bug on the website or if I am understanding something wrongly. Here is my function implementation for this problem:
int workbook(int n, int k, int arr_count, int* arr)
{
int tmp = 1, specprob = 0;
int *chstart = malloc(n * sizeof(int));
int *chend = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
chstart[i] = tmp;
tmp += arr[i] / k - 1;
if (arr[i] % k != 0) {
tmp++;
}
chend[i] = tmp;
tmp++;
if (!(arr[i] < chstart[i])) {
int qno = 0, chpage = 1, iqno = 0;
for (int j = chstart[i]; j < chend[i] + 1; j++) {
if (chpage * k <= arr[i]) {
qno += k;
} else {
qno += (k - (chpage * k - arr[i]));
}
if (j > iqno && j < qno + 1) {
specprob++;
}
iqno = qno;
chpage++;
}
}
}
return specprob;
}
It looks like a bug, since when you run the empty function with just a return 0; it gives the same runtime error.
For the moment though, if you don't mind too much about the different language, you could make a few minor changes to the code to make it compile for C++ (don't forget to change the language selection too):
int workbook(int n, int k, vector<int> arr)
{
int tmp = 1, specprob = 0;
int *chstart = (int*)malloc(n * sizeof(int));
int *chend = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
chstart[i] = tmp;
tmp += arr[i] / k - 1;
if (arr[i] % k != 0)
{
tmp++;
}
chend[i] = tmp;
tmp++;
if (!(arr[i] < chstart[i]))
{
int qno = 0, chpage = 1, iqno = 0;
for (int j = chstart[i]; j < chend[i] + 1; j++)
{
if (chpage * k <= arr[i])
{
qno += k;
}
else
{
qno += (k - (chpage * k - arr[i]));
}
if (j > iqno && j < qno + 1)
{
specprob++;
}
iqno = qno;
chpage++;
}
}
}
return specprob;
}
i want to rotate the string one place at a time and print all the rotations
Input : S = "abc"
Output : abc
bca
cab
im trying to concatenate the string and then printing it, but the problem is input string can be of size 10^5 so my array would require to be of 10^10 size.
but im unable to declare that size array, so i wanted a to know if there is a better way to do it
void printRotatedString(char str[])
{
int n = strlen(str);
// Concatenate str with itself
char temp[2*n + 1];
strcpy(temp, str);
strcat(temp, str);
// Print all substrings of size n.
for (int i = 0; i < n; i++)
{
for (int j=0; j != n; j++)
printf("%c",temp[i + j]);
printf("\n");
}
}
i expect it to work even for 10^5 sized strings
You can do it, even without concatenation. But why do you need it? It will be better if you provide an actual problem source.
void printRotatedString(char str[]) {
int n = strlen(str);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%c", str[(i + j) % n]);
printf("\n");
}
}
We can come up with another solution using prefix sums. Let's calculate array c where c[i] = the number of letters in our string which are even(or another boolean function) from the beginning. We can calculate it easily if we know c[i - 1], c[i] would be c[i - 1] + 1 if i-th letter is even, c[i] = c[i - 1] otherwise.
So let's use the same idea, let's concatenate our string on its own. And then try to check every substring length of our input string. Having prefix sums, we can easily check if the left-hand side has more even elements than the right-hand side.
Here is the solution code:
int c[100500];
int isEven(char c) {
return c % 2 == 0;
}
int solve(char str[]) {
int n = strlen(str);
char temp[2*n + 1];
strcpy(temp, str);
strcat(temp, str);
for (int i = 0; i < n + n; i++) {
c[i + 1] = c[i] + isEven(temp[i]);
}
int counter = 0;
for (int i = 1; i + n <= n + n; ++i) {
int l = i, r = i + n - 1;
int mid = i + n / 2;
int leftSide = c[mid - 1] - c[l - 1];
int rightSide = c[r] - c[mid - 1];
if (leftSide > rightSide) {
++counter;
}
}
return counter;
}
Task description -> Whole task description is here
I have done part with sorting and got stuck.
How can I combine these arrays in one of already sorted pairs?
printf("\nHeight of boys in descending order\n");
for (i = (LENGTH1 - 1); i >= 0; i--)
{
printf("%d ", heightBoys[i]);
}
for (i = 0; i < LENGTH2; i++)
{
for (j = 0; j < (LENGTH2 - j - 1); j++)
{
if (heightGirls[j] > heightGirls[j+1])
{
temp = heightGirls[j];
heightGirls[j] = heightGirls[j+1];
heightGirls[j+1] = temp;
}
}
}
printf("\nHeight of girls in descending order\n");
for (j = (LENGTH2 - 1); j >= 0; j--)
{
printf("%d ", heightGirls[j]);
}
You have a sort [for the girls], but it is broken. Change:
for (j = 0; j < (LENGTH2 - j - 1); j++)
Into:
for (j = 0; j < (LENGTH2 - i - 1); j++)
To avoid [needless] replication of code, put the sorting code into a separate function.
Sort both arrays.
Take the minimum of the lengths of the two arrays (e.g. minlen).
I'm not sure what you mean [exactly] by "pairing", but the simplest is to print the pairing
Then, just loop on:
for (i = 0; i < minlen; ++i)
printf("Girl:%d Boy:%d\n",heightGirls[i],heightBoys[i]);
If you needed something more complex, you might need an array of structs like:
struct pair {
int boyheight;
int girlheight;
};
This array would need to be at least minlen in length. You could fill it in by adapting the final print loop.
But, if you're just printing, here is some sample code:
#include <stdio.h>
void
print_single(const int *height,int len,const char *sex)
{
printf("\nHeight of %s in descending order\n",sex);
for (int i = (len - 1); i >= 0; i--)
printf(" %d", height[i]);
printf("\n");
}
void
sort_height(int *height,int len)
{
for (int i = 0; i < len; i++) {
for (int j = 0; j < (len - i - 1); j++) {
if (height[j] > height[j + 1]) {
int temp = height[j];
height[j] = height[j + 1];
height[j + 1] = temp;
}
}
}
}
int
main(void)
{
int heightBoys[] = { 5, 8, 7, 9, 6 };
int heightGirls[] = { 3, 1, 2 };
int LENGTH1 = sizeof(heightBoys) / sizeof(heightBoys[0]);
int LENGTH2 = sizeof(heightGirls) / sizeof(heightGirls[0]);
sort_height(heightBoys,LENGTH1);
print_single(heightBoys,LENGTH1,"boys");
sort_height(heightGirls,LENGTH2);
print_single(heightGirls,LENGTH2,"girls");
int minlen = LENGTH1;
if (minlen > LENGTH2)
minlen = LENGTH2;
printf("\n");
printf("Pairing:\n");
for (int i = 0; i < minlen; ++i)
printf("Girl:%d Boy:%d\n",heightGirls[i],heightBoys[i]);
return 0;
}
UPDATE:
Let's say that we input heights and number of them by ourselves. If we have extra heights of boys or girls, how can we output these extra heights apart from the rest?
Two additional for loops appended to the bottom should do the trick. In order for this to work, the iteration variable of the final for loop in the previous example must be defined outside the loop. In other words, notice the definition and usage of ipair below.
If you are creating an array the type of struct that I suggested, these loops can fill it in. The array size would then need to be max(LENGTH1,LENGTH2).
And, in unpaired loops (e.g. for boy 8, the girl value in the struct could be set to 0 or -1 to indicate that the boy is unpaired)
#include <stdio.h>
void
print_single(const int *height,int len,const char *sex)
{
printf("\nHeight of %s in descending order\n",sex);
for (int i = (len - 1); i >= 0; i--)
printf(" %d", height[i]);
printf("\n");
}
void
sort_height(int *height,int len)
{
for (int i = 0; i < len; i++) {
for (int j = 0; j < (len - i - 1); j++) {
if (height[j] > height[j + 1]) {
int temp = height[j];
height[j] = height[j + 1];
height[j + 1] = temp;
}
}
}
}
int
main(void)
{
int heightBoys[] = { 5, 8, 7, 9, 6 };
int heightGirls[] = { 3, 1, 2 };
int LENGTH1 = sizeof(heightBoys) / sizeof(heightBoys[0]);
int LENGTH2 = sizeof(heightGirls) / sizeof(heightGirls[0]);
sort_height(heightBoys,LENGTH1);
print_single(heightBoys,LENGTH1,"boys");
sort_height(heightGirls,LENGTH2);
print_single(heightGirls,LENGTH2,"girls");
int minlen = LENGTH1;
if (minlen > LENGTH2)
minlen = LENGTH2;
int ipair = 0;
printf("\n");
printf("Pairing:\n");
for (; ipair < minlen; ++ipair)
printf("Girl:%d Boy:%d\n",heightGirls[ipair],heightBoys[ipair]);
if (ipair < LENGTH1) {
printf("\n");
printf("Unpaired Boys:\n");
for (int i = ipair; i < LENGTH1; ++i)
printf("Boy:%d\n",heightBoys[i]);
}
if (ipair < LENGTH2) {
printf("\n");
printf("Unpaired Girls:\n");
for (int i = ipair; i < LENGTH2; ++i)
printf("Girl:%d\n",heightGirls[i]);
}
return 0;
}
sir i am a new programmer.So i am facing some new problems which I really need to solve. Like I write a code
#include<stdio.h>
main(){
int ara[] ={10,20,30,40,50,60,70,80,90,100},i,temp,j;
for(i=0,j=9;i<10;i++,j--){
ara[i]=ara[j];
printf("%d\n",ara[i]); }
}
I thought the result would be 100,90,80,70,60,50,40,30,20,10 but the result is not like this...Would anyone please tell me why the result shows 100,90,80,70,60,60,70,80,90,100
After printing value 60, i.e. half of the array when you try to access elements further, actually you will access those elements which are of the locations after mid of the array. because you are assigning them using ara[i] = ara[j]..so you will end up with repetition after half of array.
As:-
ara[0] = ara[9]
ara[1] = ara[8]
ara[2] = ara[7]
ara[3] = ara[6]
ara[4] = ara[5]
ara[5] = ara[4]
The simplest solution may be creating a temporary array:-
#include<stdio.h>
main(){
int ara[] ={10,20,30,40,50,60,70,80,90,100},i,temp[10],j;
for(i = 9, j = 0; i >= 0; i--, j++){
temp[j]=ara[i];
}
for(i = 0; i < 10; i++){
printf("%d\n", temp[i]);
}
}
What you are doing in this code?
reversing an array
Why are you printing 100,90,80,70,60,50,60,70,...
because when you reach the 6th one (ara[4]), you've already swapped it with 4th one (ara[6])
You need to save in the temporary variable the value which is written first
Some examples
char *reverse(char *str)
{
char tmp;
int len;
if (str != NULL)
{
len = strlen(str);
for (int i = 0; i < len / 2; i++)
{
tmp = *(str + i);
*(str + i) = *(str + len - i - 1);
*(str + len - i - 1) = tmp;
}
}
return str;
}
int *reverseints(int *data, size_t size)
{
int tmp;
if (data != NULL)
{
for (int i = 0; i < size / 2; i++)
{
tmp = *(data + i);
*(data + i) = *(data + size - i - 1);
*(data + size - i - 1) = tmp;
}
}
return data;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to code the Waterman algorithm in C.
Now when the length of the sequence exceeds 35 the program just lags.
I have no idea where to start looking, tried but got nothing worked out.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Max Function Prototype.
int maxfunction(int, int);
// Prototype of the random Sequences generator Function.
void gen_random(char *, const int);
int main(int argc, char *argv[]) {
// Looping variable and Sequences.
int i = 0, j = 0, k = 0;
char *X, *Y;
int length1, length2;
// Time Variables.
time_t beginning_time, end_time;
// Getting lengths of sequences
printf("Please provide the length of the first Sequence\n");
scanf("%d", &length1);
printf("Please provide the length of the second Sequence\n");
scanf("%d", &length2);
X = (char*)malloc(sizeof(char) * length1);
Y = (char*)malloc(sizeof(char) * length2);
int m = length1 + 1;
int n = length2 + 1;
int L[m][n];
int backtracking[m + n];
gen_random(X, length1);
gen_random(Y, length2);
printf("First Sequence\n");
for (i = 0; i < length1; i++) {
printf("%c\n", X[i]);
}
printf("\nSecond Sequence\n");
for (i = 0; i < length2; i++) {
printf("%c\n", Y[i]);
}
// Time calculation beginning.
beginning_time = clock();
// Main Part--Core of the algorithm.
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
L[i][j] = 0;
} else
if (X[i-1] == Y[j-1]) {
L[i][j] = L[i-1][j-1] + 1;
backtracking[i] = L[i-1][j-1];
} else {
L[i][j] = maxfunction(L[i-1][j], L[i][j-1]);
backtracking[i] = maxfunction(L[i-1][j], L[i][j-1]);
}
}
}
// End time calculation.
end_time = clock();
for (i = 0; i < m; i++) {
printf(" ( ");
for (j = 0; j < n; j++) {
printf("%d ", L[i][j]);
}
printf(")\n");
}
// Printing out the result of backtracking.
printf("\n");
for (k = 0; k < m; k++) {
printf("%d\n", backtracking[k]);
}
printf("Consumed time: %lf", (double)(end_time - beginning_time));
return 0;
}
// Max Function.
int maxfunction(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Random Sequence Generator Function.
void gen_random(char *s, const int len) {
int i = 0;
static const char alphanum[] = "ACGT";
for (i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
Since you null terminate the sequence in gen_random with s[len] = 0;, you should allocate 1 more byte for each sequence:
X = malloc(sizeof(*X) * (length1 + 1));
Y = malloc(sizeof(*Y) * (length2 + 1));
But since you define variable length arrays for other variables, you might as well define these as:
char X[length1 + 1], Y[length2 + 1];
Yet something else is causing a crash on my laptop: your nested loops iterate from i = 0 to i <= m, and j = 0 to j <= n. That's one step too many, you index out of bounds into L.
Here is a corrected version:
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
The resulting code executes very quickly, its complexity is O(m*n) in both time and space, but m and n are reasonably small at 35. It runs in less than 50ms for 1000 x 1000.
Whether it implements Smith-Waterman's algorithm correctly is another question.