Last active
February 17, 2018 18:10
-
-
Save aragorn2308/ce13cafc3fb5ecd3a46bd7bb3651704d to your computer and use it in GitHub Desktop.
Find the minimum time in HH:MM:SS format given a string of 6 digits.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<string.h> | |
#include<stdlib.h> | |
char strings[1000][7]; | |
int comparator(const void *p, const void *q) | |
{ | |
int l = *((char *)p); | |
int r = *((char *)q); | |
return (l - r); | |
} | |
void swap(char *x, char *y) | |
{ | |
char temp; | |
temp = *x; | |
*x = *y; | |
*y = temp; | |
} | |
int findCeil (char str[], char first, int l, int h) | |
{ | |
int ceilIndex = l; | |
for (int i = l+1; i <= h; i++) | |
if (str[i] > first && str[i] < str[ceilIndex]) | |
ceilIndex = i; | |
return ceilIndex; | |
} | |
int ptr = 0; | |
void sortedPermutations ( char str[] ) | |
{ | |
int size = strlen(str); | |
qsort( str, size, sizeof( str[0] ), comparator ); | |
bool isFinished = false; | |
while ( ! isFinished ) | |
{ | |
strcpy(strings[ptr++],str); | |
int i; | |
for ( i = size - 2; i >= 0; --i ) | |
if (str[i] < str[i+1]) | |
break; | |
if ( i == -1 ) | |
isFinished = true; | |
else | |
{ | |
int ceilIndex = findCeil( str, str[i], i + 1, size - 1 ); | |
swap( &str[i], &str[ceilIndex] ); | |
qsort( str + i + 1, size - i - 1, sizeof(str[0]), comparator ); | |
} | |
} | |
} | |
int hour_check(char *hr){ | |
if((hr[0]=='0'||hr[0]=='1')&&(hr[1]>='0'&&hr[1]<='9')){ | |
return 1; | |
}else if(hr[0]=='2'&&hr[1]>='0'&&hr[1]<='3'){ | |
return 1; | |
}else { | |
return 0; | |
} | |
return 0; | |
} | |
int minute_check(char *hr){ | |
if((hr[2]>='0'&&hr[2]<='5') && (hr[3]>='0'&&hr[3]<='9')){ | |
return 1; | |
}else { | |
return 0; | |
} | |
return 0; | |
} | |
int seconds_check(char *hr){ | |
if((hr[4]>='0'&&hr[4]<='5') && (hr[5]>='0'&&hr[5]<='9')){ | |
return 1; | |
}else { | |
return 0; | |
} | |
return 0; | |
} | |
int main() | |
{ | |
char str[] = "000789"; | |
int n = strlen(str); | |
sortedPermutations(str); | |
int len = ptr; | |
for(int t = 0; t<len; t++){ | |
if(hour_check(strings[t]) && minute_check(strings[t]) && seconds_check(strings[t])){ | |
printf("%s\n", strings[t]); | |
return 0; | |
}else{ | |
continue; | |
} | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment