Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ============================================================
- String reversal challenge but it's cursed
- ============================================================
- Write a function that reverses a null-terminated string in-place, but with a few constraints :
- 1. You only get a single char*, which is initially at the start of the string.
- 2. No extra variables can be declared. You only have your one blessed char*.
- 3. No std functions.
- 4. You can only write helper functions that take a single char** to your blessed char*.
- ============================================================
- */
- #include <stdio.h>
- // helpers
- void swapWithNext(char** ptrRef)
- {
- (*ptrRef)[0] = (*ptrRef)[0] + (*ptrRef)[1];
- (*ptrRef)[1] = (*ptrRef)[0] - (*ptrRef)[1];
- (*ptrRef)[0] = (*ptrRef)[0] - (*ptrRef)[1];
- }
- void rewindToStart(char** ptrRef)
- {
- (*ptrRef)--;
- for( ; **ptrRef >= 0; (*ptrRef)--) {}
- }
- void markEnds(char** ptrRef)
- {
- **ptrRef *= -1;
- for( ; (*ptrRef)[1] != '\0'; (*ptrRef)++) {}
- **ptrRef *= -1;
- rewindToStart(ptrRef);
- }
- void leftShiftTillEndCh(char** ptrRef)
- {
- swapWithNext(ptrRef);
- **ptrRef *= -1;
- (*ptrRef)++;
- **ptrRef *= -1;
- while(1)
- {
- swapWithNext(ptrRef);
- if(**ptrRef < 0)
- {
- break;
- }
- (*ptrRef)++;
- }
- rewindToStart(ptrRef);
- }
- // the actual function
- void cursedReverse(char* ptr)
- {
- if(ptr[0] == '\0')
- {
- return;
- }
- if(ptr[1] == '\0')
- {
- return;
- }
- markEnds(&ptr);
- while(1)
- {
- if(ptr[0] < 0 && ptr[1] < 0)
- {
- swapWithNext(&ptr);
- ptr[0] *= -1;
- ptr[1] *= -1;
- break;
- }
- leftShiftTillEndCh(&ptr);
- }
- }
- // test
- void main(int argc, char* argv[])
- {
- cursedReverse(argv[1]);
- printf("%s", argv[1]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement