Page 3 of 15 FirstFirst 1234513 ... LastLast
Results 21 to 30 of 141

Thread: Beginner Programming Challenge #9

  1. #21
    Join Date
    Oct 2008
    Location
    Maryland, USA
    Beans
    300
    Distro
    Kubuntu 9.10 Karmic Koala

    Re: Beginner Programming Challenge #9

    I'm impressed by those with the talent and the time to post submissions so quickly. 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?

    Thanks.
    OpenSUSE: Dell Inspiron 8600 and Gateway GT5678
    MacOS X 10.5.8 PowerBook G4 12"
    Linux user #: 501795

  2. #22
    Join Date
    Apr 2008
    Beans
    507

    Re: Beginner Programming Challenge #9

    There is no Perl implementation thus far. This made me sad. Perl is good at this stuff.

    Code:
    use strict;
    use warnings;
    
    my @nums;
    my %chars;
    
    while(<DATA>) {
      chomp && /\d/ ? push(@nums, $_) : $chars{$_}++;
    }
    print "Sum = " . eval(join '+', @nums) . "\n"; # cheating here :)
    for my $c (sort keys %chars) {
      print "$c = $chars{$c}\n";
    }
    
    __DATA__
    5
    a
    n
    7
    4
    n
    6
    1
    0
    y
    w
    a
    Code:
    Sum = 23
    a = 2
    n = 2
    w = 1
    y = 1
    I was too lazy to read from a file. Disqualify me.
    Go you good thing!

  3. #23
    Join Date
    Oct 2007
    Beans
    74

    Re: Beginner Programming Challenge #9

    Quote Originally Posted by Marlonsm View Post
    Here is mine, in Python.
    Very archaic, long and possibly slow, but it works!
    Code:
    file_data = open("input.txt", 'r')  #import file
    number_count = 0        #declare the count for the numbers
    a_count = 0             #declare the count for each letter
    b_count = 0
    c_count = 0
    d_count = 0
    e_count = 0
    f_count = 0
    g_count = 0
    h_count = 0
    i_count = 0
    j_count = 0
    k_count = 0
    l_count = 0
    m_count = 0
    n_count = 0
    o_count = 0
    p_count = 0
    q_count = 0
    r_count = 0
    s_count = 0
    t_count = 0
    u_count = 0
    v_count = 0
    w_count = 0
    x_count = 0
    y_count = 0
    z_count = 0
    for line in file_data:             #test each line individually
    	if line.startswith('a'):   #test all possibilities for each line
    		a_count += 1       #add one to the count every time a certain letter is found
    	elif line.startswith('b'):
    		b_count += 1
    	elif line.startswith('c'):
    		c_count += 1
    	elif line.startswith('d'):
    		d_count += 1
    	elif line.startswith('e'):
    		e_count += 1
    	elif line.startswith('f'):
    		f_count += 1
    	elif line.startswith('g'):
    		g_count += 1
    	elif line.startswith('h'):
    		h_count += 1
    	elif line.startswith('i'):
    		i_count += 1
    	elif line.startswith('j'):
    		j_count += 1
    	elif line.startswith('k'):
    		k_count += 1
    	elif line.startswith('l'):
    		l_count += 1
    	elif line.startswith('m'):
    		m_count += 1
    	elif line.startswith('n'):
    		n_count += 1
    	elif line.startswith('o'):
    		o_count += 1
    	elif line.startswith('p'):
    		p_count += 1
    	elif line.startswith('q'):
    		q_count += 1
    	elif line.startswith('r'):
    		r_count += 1
    	elif line.startswith('s'):
    		s_count += 1
    	elif line.startswith('t'):
    		t_count += 1
    	elif line.startswith('u'):
    		u_count += 1
    	elif line.startswith('v'):
    		v_count += 1
    	elif line.startswith('w'):
    		w_count += 1
    	elif line.startswith('x'):
    		x_count += 1
    	elif line.startswith('y'):
    		y_count += 1
    	elif line.startswith('z'):
    		z_count += 1
    	elif line.startswith('1'):    #now for the numbers
    		number_count += 1
    	elif line.startswith('2'):
    		number_count += 2
    	elif line.startswith('3'):
    		number_count += 3
    	elif line.startswith('4'):
    		number_count += 4
    	elif line.startswith('5'):
    		number_count += 5
    	elif line.startswith('6'):
    		number_count += 6
    	elif line.startswith('7'):
    		number_count += 7
    	elif line.startswith('8'):
    		number_count += 8
    	elif line.startswith('9'):
    		number_count += 9
    print "Sum =", number_count  #print the sum
    if a_count != 0:             #check if the file had this letter
    	print "a =", a_count #print the letter and its count
    if b_count != 0:
    	print "b =", b_count
    if c_count != 0:
    	print "c =", c_count
    if d_count != 0:
    	print "d =", d_count
    if e_count != 0:
    	print "e =", e_count
    if f_count != 0:
    	print "f =", f_count
    if g_count != 0:
    	print "g =", g_count
    if h_count != 0:
    	print "h =", h_count
    if i_count != 0:
    	print "i =", i_count
    if j_count != 0:
    	print "j =", j_count
    if k_count != 0:
    	print "k =", k_count
    if l_count != 0:
    	print "l =", l_count
    if m_count != 0:
    	print "m =", m_count
    if n_count != 0:
    	print "n =", n_count
    if o_count != 0:
    	print "o =", o_count
    if p_count != 0:
    	print "p =", p_count
    if q_count != 0:
    	print "q =", q_count
    if r_count != 0:
    	print "r =", r_count
    if s_count != 0:
    	print "s =", s_count
    if t_count != 0:
    	print "t =", t_count
    if u_count != 0:
    	print "u =", u_count
    if v_count != 0:
    	print "v =", v_count
    if w_count != 0:
    	print "w =", w_count
    if x_count != 0:
    	print "x =", x_count
    if y_count != 0:
    	print "y =", y_count
    if z_count != 0:
    	print "z =", z_count
    The input file should be in the same folder and be called input.txt .

    I'm glad to see another python solution, but oh my! What will happen if the input was changed to use uppercase letters as well? You may want to investigate python's other data structures out there to see if you can condense your solution.

  4. #24
    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.

  5. #25
    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.

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

    Re: Beginner Programming Challenge #9

    I had a go in C as well tonight but I'm such a novice I couldn't even figure out how to sum the numbers in my file.
    Don't think I'll be attempting this one in C so will just leave my PHP one on page 1.

    Interesting language though, it has to handle strings as arrays of chars and a char is really an int (ASCII).
    Pointers are confusing me too but there's tons of tutorials out there and I love getting back to basics with computing.
    http://www.digit4l.net/ - news, tech, gaming and commentary

  7. #27
    Join Date
    Jun 2008
    Location
    England -> Canada
    Beans
    331

    Re: Beginner Programming Challenge #9

    <snip> sorry, i didn't read the rules, I'll post my code again once the competition is over </snip>
    Last edited by BenAshton24; February 17th, 2010 at 07:25 AM.
    Dif-tor heh smusma...
    Registered Linux User #476478 Register At www.counter.li.org
    *Slowly munches on a dead frog*

  8. #28
    Join Date
    Jan 2010
    Beans
    20

    Re: Beginner Programming Challenge #9

    im trying to learn c but im at the very beginning so im tryin just to read code where i can so id love to see a solution of this in c if anyone has one, or if an admin can post one when the contest is over.

  9. #29
    Join Date
    Jul 2006
    Location
    somewhere :)
    Beans
    535
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner Programming Challenge #9

    Here's a solution in C. not very good, but it works (my C-foo is pretty weak atm).

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    typedef struct {
      char letter;
      int frequency;
      struct letterfreq *next;
    } letterfreq;
    
    letterfreq *list;
    
    int freeall() {
      return 1;
    }
    
    int add_letter(char letter) {
      letterfreq *current, *new;
    
      if(list==NULL) {
        list=malloc(sizeof(letterfreq));
        list->letter=letter;
        list->frequency=1;
        list->next=NULL;
        return 1;
      }
      
      current=list;
      
      while(1) {
        if(current->letter==letter) {
          current->frequency++;
          return 1;
        }
        if (current->next != NULL)
          current=current->next;
        else
          break;
      }
    
      new=malloc(sizeof(letterfreq));
      new->letter=letter;
      new->frequency=1;
      new->next=NULL;
      current->next=new;
      return 1;
    } 
    void printall() {
      letterfreq *current;
      current=list;
      while(1) {
        printf("%c = %d\n", current->letter, current->frequency);
        if(current->next != NULL)
          current=current->next;
        else
          break;
      }
    }
    
    int is_numeric(char *str) {
      char c;
      if(str==NULL) return 0;
      if(!*str) return 0;
      while((c=str[0])) {
        if(!isdigit(c))
          return 0;
        str=&str[1];
      }
      return 1;
    }
    
    int main(int argc, char **argv) {
      FILE *fp;
      char line[20];
      int sum=0;
      
      if(argc!=2) return EXIT_FAILURE;
      
      fp=fopen(argv[1], "r");
      while(!feof(fp)) {
        fscanf(fp, "%s", line);
        if(is_numeric(line)) {
          sum+=atoi(line);
        } else {
          add_letter(line[0]);
        }
      }
      
      printf("Sum = %d\n", sum);
      printall();
      
      freeall();
    
      return EXIT_SUCCESS;
    }
    I didn't get around to writing the freeall function, but it would just mean running along the list freeing the individual members.

    --edit--

    i thought i'd add some words of explanation to it because it may not be clear what's going on.

    much of the program is concerned with creating a data structure to store the letters and their frequency. this is the letterfreq structure defined at the top of the code. each instance of letterfreq contains the letter, the frequency and a pointer which may point to the next instance of letterfreq. let's say you have parsed the following input:

    Code:
    a
    c
    b
    then list would look like this:

    Code:
    ---------     ---------     ---------
    | a | 1 | --> | c | 1 | --> | b | 1 |
    ---------     ---------     ---------
    let's say the next line contains the letter 'c'. now the program will start checking each letterfreq in turn to see if the letter field contains a 'c'. in this case, it will check the first letterfreq and then, finding an 'a', move on to the second. here it is successful and increments the value stored in the frequency field of the letterfreq and then returns.

    let's say the next line contains the letter 'd'. now the program will start checking each letterfreq in turn to see if the letter field contains a 'd'. but it won't be successful. instead it will get to the last letterfreq in the chain (which it will recognise because the pointer of the last letterfreq isn't set) and then add a new letterfreq on to the end.

    the one case not yet considered is how the whole thing starts off. if the chain is empty, just create a new letterfreq with the value of the first letter and the frequency set to 1.

    so just as in the scheme example i posted i've designed my own data structure to store the information needed. the problem with the data structure i've used is that it's slower for long lists than a standard implementation of a hashmap or a dictionary in php, python and the like. in general, the amount of time needed to perform an operation on the chain is proportional to the length of the chain. with hashmaps or dictionaries this is not the case.

    an interesting programming challenge would be to implement hashmaps or dictionaries as AVL trees in a programming language of your choice
    Last edited by howlingmadhowie; February 17th, 2010 at 11:56 AM. Reason: add some explanation
    there are 10 types of people in the world: those that understand binary and i don't know who the other F are.

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

    Re: Beginner Programming Challenge #9

    Quote Originally Posted by sharpdust View Post
    I'm glad to see another python solution, but oh my! What will happen if the input was changed to use uppercase letters as well? You may want to investigate python's other data structures out there to see if you can condense your solution.
    The idea itself is very simple, the problem is that the code has to be repeated lots of times.
    I'll try to make it shorter, but first I'll read something about lists, I think it should help.
    Last edited by Marlonsm; February 17th, 2010 at 02:42 PM.
    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

Page 3 of 15 FirstFirst 1234513 ... 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
  •