Page 2 of 15 FirstFirst 123412 ... LastLast
Results 11 to 20 of 141

Thread: Beginner Programming Challenge #9

  1. #11
    Join Date
    Dec 2007
    Location
    Behind you!!
    Beans
    978
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner Programming Challenge #9

    Here is my python solution. It expects a file in the cwd called Challenge_9.txt

    PHP Code:
    #! /usr/bin/env python 

    file "./Challenge9.txt"       # Define the name of the file
    fileObj open(file"r")       # Open the file for reading
    lines fileObj.readlines()     # Read each line into a list
    fileObj.close()                 # Close the file

    ints = []                       # A list that will be used to hold the numbers
    chars = []                      # A list that will be ised to hold the characters
    word ""                       # Will be used to concatenate our strings for counting

    for i in lines:
        
    i.strip()               # Remove newline chars from the strings
        
    try:                      ###
            
    temp int(i)           #   This block checks if the entry
        
    except ValueError:          #    is an int or a str
            
    temp ""             ###

        
    if temp == "":            ###
            
    word += i               #    This block puts the value into the char list if its a str
            
    if i not in chars:      #     or into the ints list if it is an int
                
    chars.append(i)     #
                                    #
        
    else:                       #
            
    ints.append(temp)     ###

    sum 0                         
    for i in ints:                  # Add up the numbers and print
        
    sum += i

    print "Sum ="sum

    counter 
    = -1                    # Counter for printing correct entry in list
    for i in chars:
        
    counter += 1                # Increment counter to be at the beginning of the list (0)
        
    print "%s = %s" % (chars[counter],  word.count(chars[counter]))     # Refer to http://docs.python.org/library/stdtypes.html#string-methods 
    Bodsda
    Last edited by Bodsda; February 16th, 2010 at 07:42 PM.
    computer-howto
    Linux is not windows
    Fluxbox & Flux menu how to
    Programming is an art. Learn it, Live it, Love it!


  2. #12
    Join Date
    Nov 2005
    Location
    Sendai, Japan
    Beans
    11,296
    Distro
    Kubuntu

    Re: Beginner Programming Challenge #9

    Haskell. I broke it into three functions (plus main) to help readability:

    PHP Code:
    import Data.Char

    digitsSum                   
    :: String -> Int
    lettersCount                
    :: String -> [(CharInt)]
    printLettersCount           :: [(CharInt)] -> IO ()


    digitsSum s         sum [digitToInt c <- isDigit c]

    lettersCount []     = []
    lettersCount (x:xs)
                        | 
    isLower x     = (x1+length [<- xs == x]):otherLettersCount
                        
    otherwise     otherLettersCount
                        where otherLettersCount 
    lettersCount [<- xs /= x]

    printLettersCount []      = putStr ""
    printLettersCount (x:xs)  = do putStr [fst x]
                                   
    putStr " = "
                                   
    putStrLn (show (snd x))
                                   
    printLettersCount xs

    main 
    = do
            -- 
    Store the contents of the file as a string in the "file" variable.
            
    file <- readFile "bpc9.txt"

            
    -- Print the sum
            putStrLn 
    ("Sum = " ++ show(digitsSum file))

            -- Print 
    the letters counts
            printLettersCount 
    (lettersCount file
    It expects a file named "bpc9.txt" in the current working dir.

    Code:
    firas@iori ~ % cat bpc9.txt 
    0                           
    i                           
    1                           
    c                           
    a                           
    n                           
    2                           
    h                           
    a                           
    s                           
    3                           
    c                           
    h                           
    e                           
    e                           
    z                           
    b                           
    u                           
    r                           
    g                           
    e                           
    r                           
    5                           
    6                           
    8                           
    firas@iori ~ % ghc -o bpc9 bpc9.hs  
    firas@iori ~ % ./bpc9             
    Sum = 25                          
    i = 1                             
    c = 2                             
    a = 2                             
    n = 1                             
    h = 2                             
    s = 1                             
    e = 3                             
    z = 1                             
    b = 1                             
    u = 1
    r = 2
    g = 1
    Last edited by Bachstelze; February 16th, 2010 at 10:35 PM.

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

    Re: Beginner Programming Challenge #9

    here's a solution in scheme:
    Code:
    #! /usr/bin/guile -s
    !#
    (use-modules (ice-9 rdelim) (ice-9 format))
    
    (define count-stuff
      (lambda (file)
        (let ((letters (cons '() '()) ))
          (define add-to-letters
            (lambda (input l)
              (cond ((null? (car l))
                     (set-car! letters (cons input 1)))
                    ((equal? (caar l) input)
                     (set-cdr! (car l) (+ 1 (cdar l))))
                    ((null? (cdr l))
                     (set-cdr! l (cons (cons input 1) '())))
                    (else (add-to-letters input (cdr l))))))
    
          (define loop
            (lambda (file sum)
              (let ((input (read-line file)))
                (cond ((eof-object? input)
                       (list sum letters))
                      ((string->number input)
                       (loop file (+ sum (string->number input))))
                      (else
                       (add-to-letters input letters)
                       (loop file sum))))))
          (loop file 0))))
    
    (define display-stuff
      (lambda (stuff)
        (define display-loop
          (lambda (letters)
            (if (not (null? letters))
                (begin
                  (format #t "~a = ~d\n" (caar letters) (cdar letters))
                  (display-loop (cdr letters))))))
    
        (format #t "Sum = ~d\n" (car stuff))
        (display-loop (cadr stuff))))
    
    (define stuff (count-stuff (open-file (cadr (command-line)) "r")))
    (display-stuff stuff)
    it expects the name of the file as the second argument:
    Code:
    howie-laptop% ./pc09.scm test.data
    Sum = 240
    a = 4
    c = 1
    q = 1
    d = 4
    howie-laptop%
    I made it a lot more complicated than it needed to be because i created the dictionary implementation from scratch.
    there are 10 types of people in the world: those that understand binary and i don't know who the other F are.

  4. #14
    Join Date
    Sep 2007
    Beans
    163

    Re: Beginner Programming Challenge #9

    Well, I'll post my sorry little excuse mainly for the entertainment of others. You all need a laugh sometimes

    It works but I couldn't quite get the second part perfect (it prints the letters in the array but does it in a loop and I couldn't figure out how to keep it from printing the valid letters multiple times)

    The text file:
    Code:
    5
    g
    f
    6
    h
    j
    n
    5
    f
    2
    d
    7
    8
    k
    6
    h
    1
    f
    3
    s
    5
    v
    v
    b
    d
    5
    n
    9
    k
    The program:

    PHP Code:
    # file was written in IDLE 3.1

    open('test.txt''r')                   # Opens file for parsing

    array = f.readlines()                       # Adds contents of file to a list

    numcount 0                                # Initializes variable to sum
                                                # the digits in the file
                                                
    letters 'abcdefghijklmnopqrstuvwxyz'      # Initializes variable to check for
                                                # letters in file

    print ('\n\n')          



    for 
    x in range (len(array)):                # Strips out the newline characters
        
    array[x] = array[x].strip('\n')


    for 
    x in range (len(array)):                # Scans the length of the array
        
        
    if array[x] >= '0' and array[x] <= '9'# Tests if the element is a digit
            
    numcount numcount int(array[x]) # Adds the digit value to numcount

    print ('Sum ='numcount)                   # Prints the sum

    print ('\n\n')          

    for 
    y in range (len(letters)):              # Runs through the alphabet
                                                # checking to see if the current
                                                # letter is in the array

        
    lettercount 0                         # Initializes the current letter
                                                # count to 0:
                                                
        
    for x in range (len(array)):            # Runs through the array to see
            
    if letters[y] == array[x]:          # if the letter exists in the array.
                
                
    lettercount lettercount +1    # If it does, lettercount is
                                                # incremented by one.
                                                
                
    print (array[x], lettercount)   # Prinst the letter in the array with
                                                # how many times it occurs. 
    And the output:

    Code:
    Sum = 62
    
    
    
    b 1
    d 1
    d 2
    f 1
    f 2
    f 3
    g 1
    h 1
    h 2
    j 1
    k 1
    k 2
    n 1
    n 2
    s 1
    v 1
    v 2
    I'm a Python newbie. Had to look up an example on the net for how to read a file in to the program. I figured I'd post it and then look at what the other fellows did in Python so's I could learn from my mistakes.

  5. #15
    Join Date
    Dec 2007
    Location
    Behind you!!
    Beans
    978
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner Programming Challenge #9

    Quote Originally Posted by raydeen View Post
    Well, I'll post my sorry little excuse mainly for the entertainment of others. You all need a laugh sometimes

    It works but I couldn't quite get the second part perfect (it prints the letters in the array but does it in a loop and I couldn't figure out how to keep it from printing the valid letters multiple times)

    I'm a Python newbie. Had to look up an example on the net for how to read a file in to the program. I figured I'd post it and then look at what the other fellows did in Python so's I could learn from my mistakes.
    Learning from others is a good move. I ran into the same problem, how do you stop it from printing each instance of the letter. My solution was to have a string containing all of the letters in order and a list of just one instance of the letters. You can use something like

    Code:
    if letter in list:
        dont append to list
    else:
        append to list
    To get the one instance list. Then I used the string.count method on the string in a for loop of the list to get the counts of all the letters. Check my code a few posts before yours. It is heavily commented.

    Hope it helps,
    Bodsda
    computer-howto
    Linux is not windows
    Fluxbox & Flux menu how to
    Programming is an art. Learn it, Live it, Love it!


  6. #16
    Join Date
    May 2006
    Location
    St. Louis, MO
    Beans
    43
    Distro
    Ubuntu

    Re: Beginner Programming Challenge #9

    Here it is in C++ using vectors. I'm pretty new to the language so feel free to tell me where I can improve the code.

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    void readFile(const string, vector<char>&);
    void displaySum(vector<char>&);
    void displayLetterCount(vector<char>&);
    
    void readFile(const string filename, vector<char>& myVector)
    {
    	char ch;
    	ifstream inFile(filename.c_str());
    	if (!inFile)
    	{
    		cerr << "File could not be opened" << endl;
    		exit(1);
    	} // end if
    	while(!inFile.eof())
    	{
    		inFile >> ch;
    		myVector.push_back(ch);
    	} // end while
    	myVector.pop_back(); // while loop adds an extra character at the end
    } // end readFile		// pop_back fixes this - there's probably a better way
    
    void displaySum(vector<char>& myVector)
    {
    	int sum = 0;
    	vector<char>::iterator myIterator;
    	for (myIterator = myVector.begin(); myIterator != myVector.end(); myIterator++)
    	{
    		if (isdigit(*myIterator))
    			sum += *myIterator - '0';	
    	} // end for
    	cout << "Sum is " << sum << endl;
    } // end displaySum
    
    void displayLetterCount(vector<char>& myVector)
    {
    	vector<char> usedList;
    	vector<char>::iterator myIterator;
    	for (myIterator = myVector.begin(); myIterator != myVector.end(); myIterator++)
    	{
    		if (!isdigit(*myIterator) && count(usedList.begin(), usedList.end(), *myIterator) == 0)
    		{
    			int letterCount = count(myVector.begin(), myVector.end(), *myIterator);
    			cout << *myIterator << " = " << letterCount << endl;
    			usedList.push_back(*myIterator);
    		} // end if
    	} // end for
    } // end displayLetterCount
    
    int main()
    {
    	vector<char> myVector;	
    	readFile("test.txt", myVector);	
    	displaySum(myVector);
    	displayLetterCount(myVector);
    	return 0;
    } // end main

  7. #17
    Join Date
    Sep 2007
    Beans
    163

    Re: Beginner Programming Challenge #9

    Quote Originally Posted by Bodsda View Post
    Learning from others is a good move. I ran into the same problem, how do you stop it from printing each instance of the letter. My solution was to have a string containing all of the letters in order and a list of just one instance of the letters. You can use something like

    Code:
    if letter in list:
        dont append to list
    else:
        append to list
    To get the one instance list. Then I used the string.count method on the string in a for loop of the list to get the counts of all the letters. Check my code a few posts before yours. It is heavily commented.

    Hope it helps,
    Bodsda
    Thanks for the insight. I'm just starting to really tackle Python and I'm really enjoying it but unfortunately I still have some of the ol' BASIC in me (as my code no doubt shows). Any good examples are much appreciated.

    Edit: It occurred to me last night I probably could have used a dictionary for the letters bit. Checked to see if the letter was in the dictionary and if not, add it as a key, then add a value of 1, or if it was in the dict, increase the value by 1. Ah well.
    Last edited by raydeen; February 17th, 2010 at 11:44 AM.

  8. #18
    Join Date
    Mar 2008
    Location
    127.0.0.1
    Beans
    193
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: Beginner Programming Challenge #9

    Here's my python solution:
    Code:
    #!/usr/bin/env python
    
    file = open("text.txt", "r")
    lines = file.readlines()
    file.close()
    
    sum = 0
    uniquechars = {}
    
    for line in lines:
        line = line.strip()
        if line.isdigit():
            sum += int(line)
    
        if uniquechars.get(line):
            uniquechars[line] += 1
        else:
            uniquechars[line] = 1
    
    print sum
    
    for char in uniquechars:
        print char, uniquechars[char]
    I'm pretty happy with it
    I am currently unable to come up with a witty statement to put in my signature. Please check back later.

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

    Re: Beginner Programming Challenge #9

    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 .
    EDIT: Rewritten mine, it's on post #33.
    Last edited by Marlonsm; February 17th, 2010 at 08:44 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

  10. #20
    Join Date
    Mar 2009
    Beans
    109

    Re: Beginner Programming Challenge #9

    Don't include me in the challenge judging, I just wanted to give it a quick try. Does not include any kind of error handling or parameter checks!

    PHP Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Text.RegularExpressions;

    namespace 
    CodingChallenge
    {
        class 
    Program
        
    {

            static 
    void Main(string[] args)
            {
                
    // use dictionary to store character appearance counts
                
    Dictionary<stringintdict = new Dictionary<stringint>();
                
                
    // regular expressions for the types in question
                
    Regex digit = new Regex("^[0-9]+"RegexOptions.Multiline);
                
    Regex character = new Regex("^[a-z]"RegexOptions.Multiline);

                
    // read file into buffer
                
    StreamReader reader = new StreamReader(args[0]);
                
    string data reader.ReadToEnd();

                
    // get sum
                
    long sum = (from Match h in digit.Matches(dataselect long.Parse(h.Value)).Sum();

                
    // get characters
                
    Match[] matches = (from Match h in character.Matches(dataselect h).ToArray();
                foreach (
    Match match in matches)
                {
                    if (
    dict.ContainsKey(match.Value) == false)
                    {
                        
    // find character count
                        
    int count matches.Count(=> a.Value == match.Value);
                        
    // add pairing to dictionary
                        
    dict.Add(match.Valuecount);
                    }
                }

                
    // write sum
                
    Console.WriteLine(string.Format("Sum is {0}"sum));

                
    // write character appearances
                
    foreach (KeyValuePair<stringintpair in dict)
                {
                    
    Console.WriteLine(string.Format("Character {0} count is {1}",
                        
    pair.Keypair.Value));
                }
            }
        }

    Last edited by gtr32; February 17th, 2010 at 04:43 PM.

Page 2 of 15 FirstFirst 123412 ... 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
  •