Friday, June 27, 2014

First Practice Problem: String Indexer

For my first problem, I found a problem on the subreddit /r/dailyprogrammer.  I was tasked with indexing words in a string.  A word was defined by "[a-zA-Z0-9]+" and anything else is considered a blank space.  The method should then accept an array of integers and print out the corresponding words.  If the integer is too high/low the method should return an empty string.

My Solution:
This problem was rather straight forward.  I decided to use Java as I've become quite rusty.  My only real issue was getting rid of the new line characters (\n).  Java treats /n as two separate characters.  I decided to simply replace any occurrence of a new line character, instead of messing with the given regex.

My Code:
 /* 
  * Name: Kevin Achenbach 
  * Program: Challenge #168[EASY] on /r/dailyprogrammer createIndex() should label 
  * each word should be indexed as a number(see: http://www.reddit.com/r/dailyprogrammer/comments/299hvt/6272014_challenge_168_easy_string_index/) 
  * for more info 
  * Date: 6/27/2014 
  */ 
 package stringindexer; 
 public class StringIndexer { 
   static String input = "...You...!!!@!3124131212 Hello have this is a --- string Solved !!...? to test @\\n\\n\\n#!#@#@%$**#$@ Congratz this!!!!!!!!!!!!!!!!one ---Problem\\n\\n"; 
   static String newInput = input.replace("\\n", ""); 
   static String[] word = newInput.split("[^a-zA-Z0-9]+"); 
   static int getTheseWords[] = {12,-1,1,-100,4,1000,9,-1000,16,13,17,15}; 
   public static void main(String[] args) { 
     int i; 
     for (i=0;i<getTheseWords.length;i++) { 
       String newWord = returnWords(getTheseWords[i]); 
       if(newWord != "") { 
         System.out.print(newWord + " "); 
       } 
     } 
   } 
  static String returnWords(int index) { 
    if(index > 0 && index < word.length) { 
      return word[index]; 
     } 
     return ""; 
   } 
 } 

No comments:

Post a Comment