Problem of the Day
A new programming or logic puzzle every Mon-Fri

Reverse Reverse

Welcome back to another fantastic Monday! Let's get right in to it.

Given a string and a delimiter, reverse every other delimited string. For example:

revrev('hello world taco', ' ');

hello dlrow taco

Permalink: http://problemotd.com/problem/reverse-reverse/

Comments:

  • Anonymous - 10 years, 5 months ago

    Quick and dirty haskell solution:

    revrev :: String -> Char -> String
    revrev [] _ = []
    revrev (x:xs) c 
        | x == c = (x): (revrev' xs [] c)
        | otherwise = (x):(revrev xs c)
    
    
    revrev' :: String -> String -> Char -> String
    revrev' [] ys _ = ys
    revrev' (x:xs) ys c
        | x == c = ys ++ [x] ++ (revrev xs c)
        | otherwise = revrev' xs (x:ys) c
    

    Btw i like that you use "mom" in an example for reversing strings :D

    reply permalink

  • Max Burstein - 10 years, 5 months ago

    lol I didn't even realize it was a palindrome. I was talking to my mom at the time and wanted to add a third word. I updated the problem.

    reply permalink

  • Nick Krichevsky - 10 years, 5 months ago

    C++ solution

    #include <iostream>
    #include <string>
    
    std::string revrev(std::string s, char c);
    int main(){
        std::string subString = "hello!";
        std::cout<<revrev("hello world taco",' ')<<std::endl;
        return 0;
    }
    
    std::string revrev(std::string s,char c){
        int pos = 0;
        int subCount = 0;
        s+=c; //Add the char to the end of our string, in order to catch the end.
        std::string newString = "";
        for (int i=0; i<s.length(); i++){
            if (s[i] == c){
                subCount++;
                std::string subString = s.substr(pos,i-pos);
                if (subCount%2==0){
                    //Switch the characters around
                    for (int j = subString.length()-1; j>subString.length()/2; j--){
                        char temp = subString[subString.length()-j];
                        subString[subString.length()-j] = subString[j];
                        subString[j]=temp;
                    }
                }
                pos = i+1;
                newString+=(subString+" ");
            }
        }
        return newString;
    }
    

    reply permalink

  • bumbleguppy - 10 years, 5 months ago

    Should the last line in the outer loop be

    newString+=(subString+c); ?

    reply permalink

  • Nick Krichevsky - 10 years, 5 months ago

    Whoops. Yeah you're right.

    reply permalink

  • Eric - 10 years, 5 months ago

    JS

    function revrev(input, delim){ 
    
        var q = input.split(delim); 
    
        for(var i = 1; i < q.length; i+=2){ 
    
            q[i] = q[i].split("").reverse().join(""); 
    
        }
    
        return q.join(delim);
    
    }
    

    reply permalink

Content curated by @MaxBurstein