Rectangle 27 11

If you're looking for reversing NULL terminated buffers, most solutions posted here are OK. But, as Tim Farley already pointed out, these algorithms will work only if it's valid to assume that a string is semantically an array of bytes (i.e. single-byte strings), which is a wrong assumption, I think.

Take for example, the string "ao" (year in Spanish).

The Unicode code points are 0x61, 0xf1, 0x6f.

The result is gibberish and an illegal UTF-8 sequence

The first byte will be treated as a NUL-terminator. No reversing will take place.

The second byte will be treated as a NUL-terminator. The result will be 0x61, 0x00, a string containing the 'a' character.

std::reverse will work for two-byte unicode types, as long as you're using wstring.

I'm not very familiar with C++, but my guess is that any respectable standard library function dealing with strings will be able to handle different encodings, so I agree with you. By "these algorithms", I meant the ad-hoc reverse functions posted here.

Unfortunately, there's no such thing as "respectable function dealing with strings" in standard C++.

@Eclipse If it reverses a surrogate pair, the result won't be correct anymore. Unicode is not actually a fixed-width charset

How do you reverse a string in place in C or C++? - Stack Overflow

c++ c string reverse
Rectangle 27 1

You can store each digit in an array:

and then print the string using a recursive function (it will reverse the output):

void print_rev(const char *s)
{
    if (*s) {
        print_rev(s + 1);
        printf("%c", *s);
    }
}
} else {
    char arr[32];
    int counter = 0;
    while (d != 0) {
        int radix;
        radix = d % b;
        d = d / b;
        char basechars[] = "0123456789ABCDEF";
        arr[counter++] = basechars[radix];
    }
    if (counter == 0) {
        printf("0");
    else {
        while (counter--)
            printf("%c", arr[counter]);
    }
    printf("\n");
}
d == 0
while (d != 0) { ...}
do { ... } while (d != 0);
d==0
if (counter == 0)

How to print character array in reverse order of C program - Stack Ove...

c arrays decimal converter radix
Rectangle 27 1

You can store each digit in an array:

and then print the string using a recursive function (it will reverse the output):

void print_rev(const char *s)
{
    if (*s) {
        print_rev(s + 1);
        printf("%c", *s);
    }
}
} else {
    char arr[32];
    int counter = 0;
    while (d != 0) {
        int radix;
        radix = d % b;
        d = d / b;
        char basechars[] = "0123456789ABCDEF";
        arr[counter++] = basechars[radix];
    }
    if (counter == 0) {
        printf("0");
    else {
        while (counter--)
            printf("%c", arr[counter]);
    }
    printf("\n");
}
d == 0
while (d != 0) { ...}
do { ... } while (d != 0);
d==0
if (counter == 0)

How to print character array in reverse order of C program - Stack Ove...

c arrays decimal converter radix
Rectangle 27 33

A solution in C/C++:

void swap(char* str, int i, int j){
    char t = str[i];
    str[i] = str[j];
    str[j] = t;
}

void reverse_string(char* str, int length){
    for(int i=0; i<length/2; i++){
        swap(str, i, length-i-1);
    }
}
void reverse_words(char* str){
    int l = strlen(str);
    //Reverse string
    reverse_string(str,strlen(str));
    int p=0;
    //Find word boundaries and reverse word by word
    for(int i=0; i<l; i++){
        if(str[i] == ' '){
            reverse_string(&str[p], i-p);
            p=i+1;
        }
    }
    //Finally reverse the last word.
    reverse_string(&str[p], l-p);
}

This should be O(n) in time and O(1) in space.

The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm.

hi, i was curious if the complexity of second pass is n+all words/2, coz for every pass in the second time you are doing a lenght/2 computations, so it shud be word length * wordlength/2 + so on....correct me if i am wrong..

@sriks: In this case you can not multiply the complexity of the outer for with the inner work. By using Amortized_analysis you can see that the total cost of the entire reverse_words operation is linear. Note that the reverse_string operations in the for loop is executed for each word and has complexity linear to the word length. That will never be greater that the total string length.

@AnkitSablok: I don't follow how you go from "In each reversal you perform x/2 operations per word, hence total reversal cost = kx/2" to "the cost of the algorithm is roughly (k*x)^2" If you agree that each word is reversed exactly once and that the algorithmic complexity of reversing each word is linear, then it is easy to conclude that the entire algorithm is lineaer.

Wt about the outer loop then, where are you considering the outer loop cost in your formula?

algorithm - Efficiently reverse the order of the words (not characters...

algorithm language-agnostic reverse puzzle
Rectangle 27 30

-[NSArray reverseObjectEnumerator]
NSArray * a = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
NSArray * reverse = [[a reverseObjectEnumerator] allObjects];
NSLog(@"%@", reverse);  //logs "c, b, a"

iphone - How to display an array in reverse order in objective C - Sta...

iphone objective-c
Rectangle 27 15

Well i dont know what your code is but you can do something like this

cell.title = [anarray objectAtIndex:(anarray.count - indexPath.row - 1)];

Fixed formatting and changed an erroneous set of [...] to (...)

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

iphone - How to display an array in reverse order in objective C - Sta...

iphone objective-c
Rectangle 27 1

#include <stdio.h>
#include <string.h>

void reverseString(char* string, int length)
{
    char swap;
    for (int i = 0; i < length/2; i++)
    {
        swap = string[length - 1 - i];
        string[length - 1 - i] = string[i];
        string[i] = swap;
    }   
}

int main (int argc, const char * argv[]) {
    char teststring[] = "Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.";
    printf("%s\n", teststring);
    int length = strlen(teststring);
    reverseString(teststring, length);
    int i = 0;
    while (i < length)
    {
        int wordlength = strspn(teststring + i, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
        reverseString(teststring + i, wordlength);
        i += wordlength + 1;
    }
    printf("%s\n", teststring);
    return 0;
}

Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

.it in )characters not( words the of order the reverse to algorithm efficient an give ,words of sentence a form which characters of array an Given

algorithm - Efficiently reverse the order of the words (not characters...

algorithm language-agnostic reverse puzzle
Rectangle 27 1

There are several ways you could go about doing this if you don't want to use the built-in facilities. For example, you could create an array, reverse the array (with an explicit loop rather than Array.Reverse), and then create a new string from the array:

char[] txt = myString.ToArray();
int i = 0;
int j = txt.Length - 1;
while (i < j)
{
    char t = txt[i];
    txt[i] = txt[j];
    txt[j] = t;
    ++i;
    --j;
}
string reversed = new string(txt);

Another way is to use a stack. Push the individual characters on the stack, then pop them off to populate a StringBuilder:

Stack<char> charStack = new Stack<char>();
foreach (var c in myString)
{
    charStack.Push(c);
}
StringBuilder sb = new StringBuilder(myString.Length);
while (charStack.Count > 0)
{
    sb.Append(charStack.Pop());
}
string reversed = sb.ToString();

Another way would be to walk through the string backwards, populating a StringBuilder:

StringBuilder sb = new StringBuilder(myString.Length);
for (int i = myString.Length-1; i >= 0; --i)
{
    sb.Append(myString[i]);
}
string reversed = sb.ToString();

And of course there are many variations to the above.

string - How do I reverse text in C#? - Stack Overflow

c# string reverse
Rectangle 27 39

Non-evil C, assuming the common case where the string is a null-terminated char array:

#include <stddef.h>
#include <string.h>

/* PRE: str must be either NULL or a pointer to a 
 * (possibly empty) null-terminated string. */
void strrev(char *str) {
  char temp, *end_ptr;

  /* If str is NULL or empty, do nothing */
  if( str == NULL || !(*str) )
    return;

  end_ptr = str + strlen(str) - 1;

  /* Swap the chars */
  while( end_ptr > str ) {
    temp = *str;
    *str = *end_ptr;
    *end_ptr = temp;
    str++;
    end_ptr--;
  }
}

You don't need the stddef.h and string.h headers.

I need stddef, but not stdio.

Rather than using a while loop to find the end pointer, can't you use something like end_ptr = str + strlen (str); I know that will do practically the same thing, but I find it clearer.

Fair enough. I was trying (and failing) to avoid the off-by-one error in @uvote's answer.

Aside from a potential performance improvement with maybe int temp, this solution looks best. +1

How do you reverse a string in place in C or C++? - Stack Overflow

c++ c string reverse
Rectangle 27 1

Okay, I give you points for actually trying and not just asking us to write this for you, but I must say you're doing too much. The code you need, based on your description, can be much simpler. I don't want to do it for you, though, so I'll give you some pointers:

So I dont need to copy the array into a new array? I would need to modify the array using a pointer in a function right?Also Thank you for the help so far, especially the suggestions with the loops.

There is no need to modify the array. You can just traverse it backwards and print each value from it as you go.

I need to write a program in C that takes command line input, puts it ...

c arrays string command-line-arguments
Rectangle 27 1

Okay, I give you points for actually trying and not just asking us to write this for you, but I must say you're doing too much. The code you need, based on your description, can be much simpler. I don't want to do it for you, though, so I'll give you some pointers:

So I dont need to copy the array into a new array? I would need to modify the array using a pointer in a function right?Also Thank you for the help so far, especially the suggestions with the loops.

There is no need to modify the array. You can just traverse it backwards and print each value from it as you go.

I need to write a program in C that takes command line input, puts it ...

c arrays string command-line-arguments
Rectangle 27 1

How does your program get out of the for (; n > 0;) loop? Won't counter simply increase until you get a bus error?

Respectfully, I think the claim that "i've got the logic figured out" is a little optimistic. :^) Doubtless someone will post the way it should have been done by the time I'm done writing this, but it's probably worth drawing attention to what went wrong (aside from the memory allocation problems noted elsewhere):

Your first loop, "for (; n > 0;)", is strange because you're printing the entire number n into the buffer at counter. So why would you need to do this more than once? If you were selecting individual digits you might, but you're not, and obviously you know how to do this because you already used "sprintf(charIt, "%d", giveStr);". [Aside: giveStr isn't a great name for an unsigned integer variable!]

Your second loop also has strange conditions: you set counter to 0, set the condition that counter > 0, and then decrease counter inside. This obviously isn't going to loop over the characters in the way you want. Assuming you thought the first loop was character-by-character, then maybe you were thinking to loop down from counter-1 to 0?

reversing a string of integers user enters (C) - Stack Overflow

c string reverse
Rectangle 27 1

There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator method on NSArray, and the allObjects method of NSEnumerator:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

That is a pretty good solution, but I notice that Dave DeLong suggested the same thing 2.5 years ago. Did you miss his answer?

Its also an exact copy and paste of this answer by somebody else from almost 4 years ago here: stackoverflow.com/a/586529/1026573

iphone - How to display an array in reverse order in objective C - Sta...

iphone objective-c
Rectangle 27 1

1) In your first for loop, you have to reach 0 (i>=0)

for(int i=p-1;i>=0;i--){

2) The a[p-1] contains the null termination('\0') of your string a[]. And the null termination should not be included in the array reverse procedure. So in your first loop you should start from p-2 and not from p-1.

And after finishing the reversing you have to add a '\0' (null terminator) at the end of your b array

b[j]='\0'; // add this
printf("array is %s",b);
return 0;

3) And as said in the other answers, you have to use only one loop and not 2 loops.

int i,j;
for (i=p-2, j=0; i>=0; i--,j++) {
    b[j]=a[i];
}
b[j]='\0';
printf("array is %s",b);

string reverse with loop and array in c - Stack Overflow

c arrays for-loop
Rectangle 27 1

#include<stdio.h>

int main(){

char str[] = "str to rev";
char revstr[12]={'\0'};
int i, j;
int length = strlen(str);
j = 0;
for(i = length-1; i>=0; i--){
  revstr[j] = str[i];
  j = j + 1;
}

printf("%s", revstr);

return 0;
}

What is myStrLen? You should define that as well, else this code will not link.

@Anishsane: the person don't want to use built in function so he can make up his own version of myStrLen I believe

string reverse with loop and array in c - Stack Overflow

c arrays for-loop
Rectangle 27 13

Less headaches when it comes to interpreted languages. Python, perl, ruby, and prolog come pre-installed (as they do on most *NIX systems). Much better UI than many Linux systems, imho. Headaches do occur when trying to build system-specific C programs (anyone tried building their own thread scheduler in C, in OS X? Not fun). On Windows, python, perl, and prolog are not pre-installed. Much of Windows comes with *ware you never use. That being said I don't use a lot of the pre-installed applications on Mac (I don't use Mail, Address Book, Font Book, Garageband, iPhoto, iDVD, iWeb, TextEdit, etc). Macs offer the flexibility of installing Windows, whereas the reverse is not true (no fault of MS... blame Apple, here).

In short, it offers many of the great programming utilities and languages found in Linux distros and leaves the headaches of Windows behind, all while providing a world-class, flexible, UI. But, I'd agree with you in questioning why people would prefer solely OS X for general programming. Not very good for that.

I tend to use whatever is at hand or the best tool for the job, be it Windows, OS X, or a flavor of Linux.

Amen on your last point. Once you know what are the general tools for your development environment, I don't think there is too much difference. People figured out how to install Python, PHP, Sandbox-Apache, etc. on Windows with a great ease now that the advantage Mac OSX has doesn't look as great as before.

Many of your reasons can be solved in a trivial amount of time on Windows though. Windows does come with a lot of crap-ware pre-installed, but I can just remove it. The interpreted languages you cite can be installed in a matter of minutes. I write a lot of C++ code, so I use VS on Windows. I don't have anything that even approaches VS in terms of quality and ease of use on the MacBook that I type this from. I like my Mac a lot, but I have a much easier time developing on Windows.

@Ed: I actually do C ("serious") development in a Linux environment. And you're completely right. I was just giving some reasons as to why other people prefer using a Mac for development. Windows does support python and perl (unsure about prolog) but it's not as friendly to the command line (just my opinion). I'm must more comfortable working in a bash shell rather than the Command Prompt, and Macs offer the nicer option.

No it's not as friendly on that end of things, you're right. I would love to be able to switch over more of my development work to my Mac, I have just found it really painful. I've been spoiled a bit.

Don't use the preinstalled versions. They are obsolete, unpatched and have 'improvements', like annoying pop-up whenever they throw exception. For example Python's community recommendation is very clear: download Python, python.org/download/mac

windows linux comparison mac
Rectangle 27 1

From some of your comments it looks like you want to reverse the order of the lines in a text file. Unfortunately you're not going to get that with such a simple program. There are several approaches you can take, depending on how complicated you want to get, how big the files are, how much memory is on hand, how fast you want it to be, etc.

Here are some different ideas off the top of my head:

There may be more elaborate/clever tricks, but those are the more obvious, straightforward approaches.

unistd.h - C copy file contents from EOF to SOF - Stack Overflow

c unistd.h lseek
Rectangle 27 32

The assembly you would write by hand and the assembly generated by a compiler are often very different when viewed from a high level. Of course, the innards of the program will be very similar (there are only so many different ways to encode a = b + c, after all), but they're not the trouble when you're trying to reverse engineer something. The compiler will add a ton of boilerplate code to even simple executables: last time I compared, "Hello World" compiled by GCC was about 4kB, while if written by hand in assembly it's around 100 bytes. It's worse on Windows: last time I compared (admittedly, this was last century) the smallest "Hello World" I could get my Windows compiler of then-choice to generate was 52kB! Usually this boilerplate is only executed once, if at all, so it doesn't much affect program speed -- like I said above, the core of the program, the part where most execution time is spent, is usually pretty similar whether compiled or written by hand.

At the end of the day, this means that an expert assembly programmer and an expert disassembler are two different specialties. Commonly they're found in the same person, but they're really separate, and learning how to be an excellent assembly coder won't help you that much to learn reverse engineering.

What you want to do is grab the IA-32 and AMD64 (both are covered together) architecture manuals from Intel and AMD, and look through the early sections on instructions and opcodes. Maybe read a tutorial or two on assembly language, just to get the basics of assembly language down. Then grab a small sample program that you're interested in and disassemble it: step through its control flow and try to understand what it's doing. See if you can patch it to do something else. Then try again with another program, and repeat until you're comfortable enough to try to achieve a more useful goal. You might be interested in things like "crackmes", produced by the reverse engineering community, which are challenges for people interested in reverse engineering to try their hand at, and hopefully learn something along the way. They range in difficulty from basic (start here!) to impossible.

I know that when you compile anything with a high level language, you will get a lot of "garbage" code that wouldn't be needed it it was coded directly in assembly. I also do understand that there's a difference between an expert assembly programmer and expert disassembler. But the same could be said about almost everything else.

My concern is that while in theory I could read the papers and get a grasp of what they mean, until I start writting things myself I don't believe I'll truly understand it. You say I can start by changing small parts of code, but to do that I first must know what kind of assembly "flavour" IDA pro, for example, uses.

Also, what does MSVC++ use for the inline assembly code? MASM?

Learning assembly - Stack Overflow

assembly
Rectangle 27 32

The assembly you would write by hand and the assembly generated by a compiler are often very different when viewed from a high level. Of course, the innards of the program will be very similar (there are only so many different ways to encode a = b + c, after all), but they're not the trouble when you're trying to reverse engineer something. The compiler will add a ton of boilerplate code to even simple executables: last time I compared, "Hello World" compiled by GCC was about 4kB, while if written by hand in assembly it's around 100 bytes. It's worse on Windows: last time I compared (admittedly, this was last century) the smallest "Hello World" I could get my Windows compiler of then-choice to generate was 52kB! Usually this boilerplate is only executed once, if at all, so it doesn't much affect program speed -- like I said above, the core of the program, the part where most execution time is spent, is usually pretty similar whether compiled or written by hand.

At the end of the day, this means that an expert assembly programmer and an expert disassembler are two different specialties. Commonly they're found in the same person, but they're really separate, and learning how to be an excellent assembly coder won't help you that much to learn reverse engineering.

What you want to do is grab the IA-32 and AMD64 (both are covered together) architecture manuals from Intel and AMD, and look through the early sections on instructions and opcodes. Maybe read a tutorial or two on assembly language, just to get the basics of assembly language down. Then grab a small sample program that you're interested in and disassemble it: step through its control flow and try to understand what it's doing. See if you can patch it to do something else. Then try again with another program, and repeat until you're comfortable enough to try to achieve a more useful goal. You might be interested in things like "crackmes", produced by the reverse engineering community, which are challenges for people interested in reverse engineering to try their hand at, and hopefully learn something along the way. They range in difficulty from basic (start here!) to impossible.

I know that when you compile anything with a high level language, you will get a lot of "garbage" code that wouldn't be needed it it was coded directly in assembly. I also do understand that there's a difference between an expert assembly programmer and expert disassembler. But the same could be said about almost everything else.

My concern is that while in theory I could read the papers and get a grasp of what they mean, until I start writting things myself I don't believe I'll truly understand it. You say I can start by changing small parts of code, but to do that I first must know what kind of assembly "flavour" IDA pro, for example, uses.

Also, what does MSVC++ use for the inline assembly code? MASM?

Learning assembly - Stack Overflow

assembly
Rectangle 27 1

It looks like Yuri already found your problem, but might I suggest a shorter version of your program? It avoids using stuff like log which might be desirable.

#include <stdio.h>

int rev (int n) {
    int r = 0;
    do {
        r *= 10;
        r += n % 10;
    } while (n /= 10);
    return r;
}

int main (void) {
    int i,a,b;
    scanf("%d",&i);

    while (i--) {
        scanf("%d %d",&a,&b);
        printf("%d\n",rev(rev(a) + rev(b)));
    }       
    return 0;
}

Hopefully you can find something useful to borrow! It seems to work okay for negative numbers too.

c - Reverse two numbers and obtain the reverse of the sum - Stack Over...

c debugging