Page 1 of 2 12 LastLast
Results 1 to 10 of 141

Thread: Beginner Programming Challenge #9

Hybrid View

  1. #1
    Join Date
    Nov 2007
    Beans
    706
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Beginner Programming Challenge #9

    Beginner Programming Challenge #9

    Welcome to the 9th programming challenge for beginners, sponsored by The Ubuntu Beginners Team Development Focus Group. Let's dive right into things.

    Task:

    Your program should be able to open a text file and read its contents. The file will consist only of LOWERCASE letters and numbers 0-9. The file will be formatted such that there is only one alphanumeric character per line. Example file:
    Code:
    5
    a
    n
    7
    4
    n
    6
    1
    0
    y
    w
    a
    Your program must read each line and store the data in a data structure of your choice. Parse through your structure and print out the following information:

    1. The sum of all the individual digits.
    2. How many times each character appeared in the file.

    Example output for the example above would be:
    Code:
    Sum = 23
    a = 2
    n = 2
    w = 1
    y = 1
    The data file used for testing will be one of my own, so you don't know what's on it before I test. Conveniently, the way this program should be written makes that fact irrelevant. Your program should work with any size file. The one I use will be hundreds of lines long.

    Bonus Points:

    Code this in a programming language you've never used before!

    Other Information:

    Please read the bottom portion of Bodsda's post of BPC #8: http://ubuntuforums.org/showthread.php?t=1386478

    All of those rules apply here as well. No obfuscated code. If you're a non-beginner, please wait until after the competition is judged to post your solution. We'd all love to learn something from the more advanced coders!

    Go to this channel for help: irc.freenode.net #ubuntu-beginners-dev

    EDIT: Please provide instructions for how to run your program along with your submission. ANY LANGUAGE IS ALLOWED!
    Last edited by Sinkingships7; February 16th, 2010 at 08:55 AM.
    Programming is an art. Learn it. Live it. Love it.

  2. #2
    Join Date
    Jun 2009
    Beans
    355

    Re: Beginner Programming Challenge #9

    Just curious, what qualifies as a beginner? I have a minor in CS, learning basic concepts and I write games as a hobby. However, I only come to this part of the forum to ask questions, and this particular problem is not one that I could finish just like that (I consider myself a beginner at least).

  3. #3
    Join Date
    Nov 2007
    Beans
    706
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Beginner Programming Challenge #9

    Quote Originally Posted by JDShu View Post
    Just curious, what qualifies as a beginner? I have a minor in CS, learning basic concepts and I write games as a hobby. However, I only come to this part of the forum to ask questions, and this particular problem is not one that I could finish just like that (I consider myself a beginner at least).
    If you can't immediately envision a solution to this problem, then I'd say you qualify as a beginner. Have at it! Since you're skeptical as to just how good you are, I encourage you to write this in a language you don't know to provide that extra challenge.
    Programming is an art. Learn it. Live it. Love it.

  4. #4
    Join Date
    May 2009
    Beans
    16
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: Beginner Programming Challenge #9

    what's the deadline?

  5. #5

    Re: Beginner Programming Challenge #9

    My attempt in PHP:

    PHP Code:
    <?php
    //Set Sum to 0
    $sum 0;
    //Specify data file
    $myFile "data.txt";
    $file_array file($myFile);
    //Read in the text file line by line
    foreach ($file_array as $line){
        
    //Tidy up $line a bit because txt file
        
    $line str_replace("\n"''"$line");
        
    $line str_replace("\r"''"$line");
        
    //Sort out numbers and text
        
    if (is_numeric($line)) {
            
    //keep running total of numbers
            
    $sum $sum $line;
        }else{
            
    //Create seperate var containing only letters
            
    $data.= $line;
        }  
    }  
    if (
    $sum != 0){
        
    //Display running total if numbers present
        
    echo 'Sum = '.$sum."<br/>";
    }
    foreach (
    count_chars($data1) as $i => $val) {
        
    //Display count of each letter
        
    echo chr($i). ' = '.$val."<br/>";

    ?>
    -Silver Fox
    Last edited by s.fox; February 17th, 2010 at 12:24 AM.
    Me on the web:

  6. #6
    Join Date
    Mar 2009
    Location
    Brazil
    Beans
    475
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: Beginner Programming Challenge #9

    I'll give it a try... although I still have no idea of how to do it.
    Ubuntu User #27453 | Linux User #490358
    "Don't preach Linux, mention it"
    "Linux is not Windows"
    73% of statistics in forums are made up on the spot

  7. #7
    Join Date
    Oct 2007
    Beans
    74

    Re: Beginner Programming Challenge #9

    Here it is in python:

    Code:
    #!/usr/bin/env python
    
    def main():
        theFile = open("input_9.txt", "r")
    
        theSum = 0
        theCharDict = {}
        for theLine in theFile:
            theLine = theLine.strip()
            if theLine.isdigit():
              theSum = theSum + int(theLine)
            else:
              theCharDict[theLine] = theCharDict.get(theLine, 0) + 1
    
        print "Sum = " + str(theSum)
        for theKey, theValue in sorted(theCharDict.items()):
            print theKey + " = " + str(theValue)
    
    if __name__ == "__main__":
        main()

  8. #8
    Join Date
    Nov 2007
    Beans
    706
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Beginner Programming Challenge #9

    Quote Originally Posted by thedarklaith View Post
    what's the deadline?
    Quote Originally Posted by GregBrannon
    Please give those of us who are a little slower enough time to program an entry. Say through the end of the weekend at least?
    No worries. There's no real deadline for this challenge. In about a week I'll post a quick warning, and anyone who is still attempting the challenge can message me privately and the "deadline" will be extended.
    Programming is an art. Learn it. Live it. Love it.

  9. #9
    Join Date
    May 2007
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: Beginner Programming Challenge #9

    Well I ended up doing a bit more than I originally intended, so it's not nearly as short and straightforward as it could be. This validates inputs, checks for exceptions, and even has a reusable logger to go with it. To use, just feed it a filename or path to file as the first parameter. Enjoy:

    Code:
    java Challenge9 /path/to/input/file
    Challenge9.java
    Code:
    /*
     * Available under Creative Commons - Attribution Non-Commercial Share Alike
     * http://creativecommons.org/about/licenses/
     * cc by-nc-sa
     */
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * Beginner Programming Challenge #9 -
     * http://ubuntuforums.org/showthread.php?t=1407897
     * 
     * @author Connor Imes
     */
    public class Challenge9 {
      private static final SimpleLogger LOG = new SimpleLogger(Challenge9.class);
      private int sum = 0;
      private final Map<Character, Integer> existingLettersCount = new HashMap<Character, Integer>();
    
      /**
       * The first and only argument should be the path to the input file.
       * 
       * @param args
       */
      public static void main(String[] args) {
        if (args.length > 0) {
          try {
            new Challenge9().doWork(args[0]);
          } catch (IOException e) {
            LOG.error(e);
          }
        } else {
          LOG.error("No filename given.");
        }
      }
    
      private void doWork(String fileName) throws IOException {
        for (final String s : readFile(fileName)) {
          if (s.length() == 1) {
            final char ourChar = s.charAt(0);
            if (Character.isDigit(ourChar)) {
              sum += Integer.parseInt(String.valueOf(ourChar));
            } else if (Character.isLowerCase(ourChar)) {
              Integer curValue = existingLettersCount.get(ourChar);
              existingLettersCount.put(ourChar, curValue == null ? 1 : ++curValue);
            } else {
              LOG.error("Not a digit or lowercase alphabetic char: \"" + ourChar
                  + "\"");
            }
          } else {
            LOG.error("Not a single character, ignoring line: \"" + s + "\"");
          }
        }
        LOG.info("Sum = " + sum);
        for (Character c : existingLettersCount.keySet()) {
          LOG.info(c + " = " + existingLettersCount.get(c));
        }
      }
    
      private static List<String> readFile(String fileName) throws IOException {
        final List<String> fileContents = new ArrayList<String>();
        if (new File(fileName).exists()) {
          final BufferedReader bReader = new BufferedReader(
              new FileReader(fileName));
          for (String line; (line = bReader.readLine()) != null;) {
            fileContents.add(line);
          }
        } else {
          throw new FileNotFoundException(fileName);
        }
        return fileContents;
      }
    }
    SimpleLogger.java
    Code:
    /*
     * Available under Creative Commons - Attribution Non-Commercial Share Alike
     * http://creativecommons.org/about/licenses/
     * cc by-nc-sa
     */
    
    /**
     * A simple logger with no concept of logging levels or other configuration.
     * 
     * @author Connor Imes
     */
    public class SimpleLogger {
      private Class<? extends Object> ownerClass;
    
      public SimpleLogger(Class<? extends Object> c) {
        ownerClass = c;
      }
    
      public void error(String s) {
        error(s, null);
      }
    
      public void error(Throwable t) {
        error(null, t);
      }
    
      public void error(String s, Throwable t) {
        printError(s, t);
      }
    
      public void info(String s) {
        print(s);
      }
    
      protected void printError(String s, Throwable t) {
        final String prefix = "ERROR: [" + ownerClass.getSimpleName() + "] ";
        if (s != null) {
          System.err.println(prefix + s);
        }
        if (t != null) {
          System.err.println(prefix + t.getClass().getSimpleName() + ": "
              + t.getMessage());
          boolean isFirst = true;
          for (StackTraceElement ste : t.getStackTrace()) {
            if (isFirst) {
              System.err.println(prefix + ste.toString());
              isFirst = false;
            } else {
              System.err.println(prefix + "\t" + ste.toString());
            }
          }
        }
      }
    
      protected void print(String s) {
        System.out.println("INFO : [" + ownerClass.getSimpleName() + "] " + s);
      }
    }
    Last edited by Rocket2DMn; February 17th, 2010 at 04:15 AM.

  10. #10
    Join Date
    Nov 2009
    Beans
    125
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner Programming Challenge #9

    I'm learning C but am really at the beginner stage - I do know PHP well though.
    Might have a go at this (if PHP is allowed).
    http://www.digit4l.net/ - news, tech, gaming and commentary

Page 1 of 2 12 LastLast

Bookmarks

Posting Permissions

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