CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Sep 2010
    Posts
    1

    Really hard to solve

    we got an question in class today that's stuck on my mind and i can't get it solved anyway i try.
    the question was:
    you get by input a char between 'a' to 'z'.
    how do you return the next char (a->b, f->g) in the alphabetical cycle (not capital) without the use of "if"s...
    i broke my brain trying to solve this and with no luck.
    any ideas? (:

  2. #2
    Join Date
    Oct 2006
    Posts
    616

    Re: Really hard to solve

    The problem you encounter is with the character 'z' right? because with all other chars, you just need to return (char)(c+1).
    There might be several solutions, dependent on the programming language.
    A "too clever" answer would be to use a switch statement or the ? : trinary operator, but this would be semantically identical to using an "if ... else ..." statement.

    I have a hunch you will need to use the modulo operator (%) to solve this one...

    Regards,
    Zachm

  3. #3
    Join Date
    May 2006
    Location
    Dresden, Germany
    Posts
    458

    Re: Really hard to solve

    Hi,

    What about this:

    Code:
    char GetTheNextCharWithoutAnyIf(const char cIn)
    {
        char chars['z'-'a'+2] = "bcdefghijklmnopqrstuvwxyza";
        return chars[cIn-'a'];
    }
    ?

    With regards
    Programartist

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Really hard to solve

    Quote Originally Posted by ProgramArtist
    What about this: (...)?
    It should work, though it uses a little more space than Zachm's hunch and still depends on the letters being contiguous and in alphabetical order in the character set. You could simplify to:
    Code:
    char chars[] = "bcdefghijklmnopqrstuvwxyza";
    return chars[cIn - 'a'];
    or even:
    Code:
    return "bcdefghijklmnopqrstuvwxyza"[cIn - 'a'];
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    Sep 2010
    Posts
    7

    Re: Really hard to solve

    Quote Originally Posted by laserlight View Post
    It should work, though it uses a little more space than Zachm's hunch and still depends on the letters being contiguous and in alphabetical order in the character set. You could simplify to:
    Code:
    char chars[] = "bcdefghijklmnopqrstuvwxyza";
    return chars[cIn - 'a'];
    or even:
    Code:
    return "bcdefghijklmnopqrstuvwxyza"[cIn - 'a'];
    I dont think so mate, else what what will happen if the user types "a"? u changed the arrangement for nothing. programArtist's original code seems good.

  6. #6
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Really hard to solve

    Quote Originally Posted by HappyNerd
    I dont think so mate, else what what will happen if the user types "a"?
    'b' will be returned, of course, since 'a' - 'a' == 0. What did you think will happen?

    Quote Originally Posted by HappyNerd
    u changed the arrangement for nothing.
    I changed the arrangement as a simplification.

    Quote Originally Posted by HappyNerd
    programArtist's original code seems good.
    It is, except that during review you are forced to check that the expression 'z'-'a'+2 is correct, when you could just let the compiler compute the size for you.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  7. #7
    Join Date
    May 2006
    Location
    Dresden, Germany
    Posts
    458

    Re: Really hard to solve

    Hi,

    my code is working as laserlight's does too.
    He tried to improve the code (and succeeded).
    The only intention of my post was to present a solution for the given task from the OP.
    With regards
    Programartist

  8. #8
    Join Date
    Mar 2006
    Posts
    151

    Re: Really hard to solve

    I tend to avoid lookup tables. Following up on Zachm's suggestion of using modulo:

    Code:
    return (cIn + 1 - 'a') % ('z' - 'a' + 1) + 'a';
    In this case the lookup is probably faster.

  9. #9
    Join Date
    Oct 2010
    Posts
    15

    Re: Really hard to solve

    We java people have twisted minds, I prefix my solution thus because what I present to you isn't pretty but it does the job and fulfills the requirements... yep...
    Code:
    public class CharGetter {
    	public char getTheNextCharWithoutAnyIf(char cIn) throws Exception {
    		try {
    			return (Character)this.getClass().getMethod("" + cIn, null).invoke(this, null);
    		} catch(NoSuchMethodException e) {
    			throw new Exception("Big trouble!", e);
    		} catch(IllegalAccessException e) {
    			throw new Exception("Big big trouble!", e);
    		}
    	}
    
    	private char a() {
    		return 'b';
    	}
    	private char b() {
    		return 'c';
    	}
    	private char c() {
    		return 'd';
    	}
    	private char d() {
    		return 'e';
    	}
    	private char e() {
    		return 'f';
    	}
    	private char f() {
    		return 'g';
    	}
    	private char g() {
    		return 'h';
    	}
    	private char h() {
    		return 'i';
    	}
    	private char i() {
    		return 'j';
    	}
    	private char j() {
    		return 'k';
    	}
    	private char k() {
    		return 'l';
    	}
    	private char l() {
    		return 'm';
    	}
    	private char m() {
    		return 'n';
    	}
    	private char n() {
    		return 'o';
    	}
    	private char o() {
    		return 'p';
    	}
    	private char p() {
    		return 'q';
    	}
    	private char q() {
    		return 'r';
    	}
    	private char r() {
    		return 's';
    	}
    	private char s() {
    		return 't';
    	}
    	private char t() {
    		return 'u';
    	}
    	private char u() {
    		return 'v';
    	}
    	private char v() {
    		return 'w';
    	}
    	private char w() {
    		return 'x';
    	}
    	private char x() {
    		return 'y';
    	}
    	private char y() {
    		return 'z';
    	}
    	private char z() {
    		return 'a';
    	}
    }

  10. #10
    Join Date
    Oct 2006
    Posts
    616

    Re: Really hard to solve

    If we're going for an overkill, there are many funny ways of doing stuff .
    For instance, this some what odd way of approximating Pi :
    Code:
    #include <stdio.h>
    #define _ F-->00 || F-OO--;
    long F=00,OO=00;
    
    void F_OO();
    
    int main()
    {
    	F_OO();
    	printf("%1.3f\n", 4.*-F/OO/OO);
    	return 0;
    }
    
    void F_OO()
    {
                _-_-_-_
           _-_-_-_-_-_-_-_-_
        _-_-_-_-_-_-_-_-_-_-_-_
      _-_-_-_-_-_-_-_-_-_-_-_-_-_
     _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
     _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
     _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
     _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
      _-_-_-_-_-_-_-_-_-_-_-_-_-_
        _-_-_-_-_-_-_-_-_-_-_-_
           _-_-_-_-_-_-_-_-_
                _-_-_-_
    
    }
    Regards,
    Zachm

  11. #11
    Join Date
    Oct 2010
    Posts
    15

    Re: Really hard to solve

    Yeah, I know, that's Westley's 1988 obfuscated c contest entry, plenty more there for those interested: http://www0.us.ioccc.org/years.html#1988_westley
    I think there ought to be an obfuscated java contest though -- there's so much boring java code in the world it's about time someone spiced it up a little. My personal favorite way is to use something like the class below and start having your code compile more code that compiles more code -- pretty soon no one but you has any idea where all the code in your program is coming from (of course the downside is after a while, neither do you...)
    Code:
    public class MyLoader extends ClassLoader {
    
    	/**
    	 * Compiles given class, or returns null if unsuccessful.
    	 * @param name
    	 * @param source
    	 * @return
    	 * @throws Exception
    	 */
    	public Class<?> load(String name, String source) throws Exception {
    		JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    		StringFileObject sourceFO
    				= new StringFileObject(name, source);
    		VirtualFileManager fileManager
    				= new VirtualFileManager(
    				jc.getStandardFileManager(null, null, null));
    		JavaCompiler.CompilationTask ct = jc.getTask(
    				null, fileManager, null, null, null, Arrays.asList(sourceFO));
    		boolean success = ct.call();
    
    		if(success) {
    			VirtualFileObject[] files = fileManager.getFiles();
    			if(files.length != 1) {
    				throw new IllegalStateException(
    						"Unexpected number of virtual files created: "
    						+ files.length
    						+ ", expected: 1.");
    			} else {
    				byte[] bytes = files[0].getBytes();
    				Class<?> result	= load(bytes);
    				return result;
    			}
    		} else {
    			return null;
    		}
    	}
    
    	/**
    	 * Loads a class defined by a string of text contained inside
    	 * the bytes array.
    	 * 
    	 * @param bytes
    	 * @return
    	 */
    	public Class<?> load(byte[] bytes) {
    		return super.defineClass(null, bytes, 0, bytes.length);
    	}
    }

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured