Page 2 of 13 FirstFirst 123412 ... LastLast
Results 11 to 20 of 127

Thread: [Beginner] Programming Challenge: 3

  1. #11
    Join Date
    Sep 2006
    Beans
    2,914

    Re: [Beginner] Programming Challenge: 3

    Quote Originally Posted by slavik View Post
    I don't think it would be a good idea to use $.
    why not?

  2. #12
    Join Date
    Jul 2008
    Beans
    28

    Re: [Beginner] Programming Challenge: 3

    Although I was tempted to use perl for this exercise, I do want to continue to use a new language and become more familiar with OO programming. So here is another ruby entry:

    Code:
    #!/usr/bin/ruby
    
    class Language
      def initialize (file_in, file_out)
        @in = File.new(file_in, 'r+')
        @out = File.new(file_out, 'w')
        @in_count 
        @out_count = 1
      end
      def process
        @in.each_line do |line|
          @in_count, name = line.chomp.split('. ')
          if name =~ /^(H|S)/
    	@out.puts @out_count.to_s + '. ' + name 
      	@out_count += 1	
          end
        end
      end
      def add_entry (name)
        @in_count = @in_count.to_i + 1
        @in.puts @in_count.to_s + '. ' + name
      end
    end
    
    language = Language.new('bhaarat.text', 'out.text')
    language.process
    language.add_entry('English')
    
    puts "Done!"

  3. #13
    Join Date
    Feb 2007
    Location
    St. Louis, MO
    Beans
    4,930
    Distro
    Ubuntu 20.04 Focal Fossa

    Re: [Beginner] Programming Challenge: 3

    Here is my version of the program written in C.

    PHP Code:
    #include <stdio.h>
    #include <string.h>

    int main(int argcchar *argv[])
    {
           
        
    /* file pointer declaration */
        
    FILE *fileout, *filein;
        
        
    /* variables declaration */
        
    short end_of_file 0;
        
    char line_num[10];
        
    char Lang[30];

        
    /* start of code */
        
    if(argc != 3)
        {
            
    printf("Usage:\n");
            
    printf("ch3 <input file> <output file>\n");
            return 
    1;
        }
        
        
    /* open file */
        
    if((filein fopenargv[1], "r" ) ) == NULL)
        {
            
    printf("Cannot Open Input file %s\n"argv[1]);
            return 
    1;
        }
        
        
    /* open file for writing */
        
    if((fileout fopenargv[2], "w" ) ) == NULL)
        {
            
    printf("Cannot Open Output file %s\n"argv[2]);
            return 
    1;
        }
        
        
    /* assume the file is populated */    
        
    end_of_file 1

        
    /* start scanning in all the lines from the file using fscanf
        fscanf returns 0 when EOF is encountered */
        
    while( end_of_file == )
        {
            
            
    end_of_file fscanf(filein"%s", &line_num);
            
    end_of_file fscanf(filein"%s", &Lang);
                    
            
    /* scan each Country to see if there is an "H" or "S" as their first letter */
            
    if( Lang[0] == 'H' || Lang[0] == 'S')
            {
                
    fprintf(fileout"%s  %s\n"line_numLang);
            }

        } 
    /* end while */
        
        /* close files */
        
    fclose(filein);
        
    fclose(fileout);
        
        return (
    0);


    Compile using gcc:
    Code:
    gcc -o challenge3 -challenge3.c
    You run the program by doing the following:

    Code:
    challenge3 <input filename with path> <output file with path>
    I have compiled the program and it gives you line numbers in which the 'H' or 'S' occur as the first letter of the language. Of course choose out.txt for the output filename.

    Cheers.
    Last edited by stchman; August 9th, 2008 at 11:30 AM.
    Windows, only good for gaming.

  4. #14
    Join Date
    Jul 2008
    Beans
    1,706

    Re: [Beginner] Programming Challenge: 3

    do we have to create a new text file for the output in the program or is that done manually

    also do you mean save it as bhaarat.text or bhaarat.txt?
    Last edited by jimi_hendrix; August 9th, 2008 at 12:31 PM.

  5. #15
    Join Date
    Feb 2007
    Location
    Edinburgh, Scotland
    Beans
    391

    Re: [Beginner] Programming Challenge: 3

    Last edited by bobbocanfly; August 10th, 2008 at 02:33 PM.
    Today we have 15 minutes of fame, tomorrow 15 minutes of anonymity.
    My Blog | Veza - Opensource TinyURL clone with sensible URLs

  6. #16
    Join Date
    Sep 2006
    Beans
    2,914

    Re: [Beginner] Programming Challenge: 3

    Quote Originally Posted by bobbocanfly View Post
    Much longer than the other python entries i have seen, but I wanted to keep it as readable as possible.
    its indeed very long. Some of them are unnecessary, like calling touch. If you want to simulate touching an empty file, there's also no need to use system touch.
    Code:
    open("empty_file","w").write("")
    Last edited by ghostdog74; August 9th, 2008 at 12:58 PM.

  7. #17
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: [Beginner] Programming Challenge: 3

    Python

    A nice exercise for a language I'm just beginning to learn. This script prints line numbers into the output file and, as a special feature, prevents the input file to append "23. English" more than once (if you, for example, run the script twice consecutively).

    Released into Public Domain.

    EDIT: Changed filenames (bhaarat.txt, out.txt) to the correct ones (bhaarat.text, out.text)!

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

    # Beginner Programming Challenge 3
    #
    # Copyright (C) 2008 Eugenio M. Vigo (aka "nvteighen")
    #
    # Released into the public domain in countries where this is legally possible. 
    # Where not, I grant explicit permission to use this work for any purpose, in 
    # any medium with no conditions.

    try:
        
    inputfile open("bhaarat.text""r+")
    except IOError:
        print 
    "Ouch! File doesn't exist!"
        
    quit()
        
    outputfile open("out.text""w")
    out_line_num 0
        
    for line in inputfile:
        
    line_numline_string line.split(". ")
        if 
    line_string[0] == "H" or line_string[0] == "S":
            
    out_line_num += 1
            outputfile
    .write(str(out_line_num) + ". " line_string)

    outputfile.close()
                
    inputfile.seek(02# Go to the file's end.

    if int(line_num) < 23# Don't repeat English if already included.
        
    inputfile.write("23. English\n")
                
    inputfile.close() 
    Last edited by nvteighen; August 12th, 2008 at 02:58 PM.

  8. #18
    Join Date
    Jul 2008
    Beans
    11

    Re: [Beginner] Programming Challenge: 3

    Code:
    cat bhaarat.text | tr -d [1-9.' '] | grep -E 'H|S' > out.text && echo "23. English" >> bhaarat.text

  9. #19
    Join Date
    Nov 2005
    Location
    Sendai, Japan
    Beans
    11,296
    Distro
    Kubuntu

    Re: [Beginner] Programming Challenge: 3

    My C version. For the sake of learning, I used only the low-level functions (read/write) for file operation. Obviously, fscanf/fprintf would have been more efficient here.

    PHP Code:
    #include <stdio.h>                
    #include <stdlib.h>               
    #include <fcntl.h>                
    #include <unistd.h>               
    #include <string.h>               

    #define MAX_LINE_LENGTH 50


    int readNextLine(int fdcharnextLine)
    {                                       
        
    /*  Reads the next line from the file pointed by the descriptor fd
         *  and stores it at the location pointed by nextLine, including the
         *  new line character (if any).                                    
         *  Returns zero on success, non-zero on failure.                   
         */                                                                 

        
    int ok 0curPos 0;

        do
        { 
            
    charnextChar calloc(1sizeof(char));

            
    ok read(fdnextCharsizeof(char));
            if(
    ok == -1)                          
                
    perror("read");                   

            
    nextLine[curPos] = *nextChar;

            if(*
    nextChar == '\n')
            {                    
                
    free(nextChar);  
                return 
    0;        
            }                    

            
    curPos += 1;
            
    free(nextChar);
        }                  
        while(
    ok != 0);    

        return -
    1;
    }             


    int processLine(charinputLineint lineNumber)
    {                                               
        
    charlanguageName calloc(MAX_LINE_LENGTHsizeof(char));
        
    int tmp 0;                                               
        
    int ok;                                                    

        
    sscanf(inputLine"%u. %s", &tmplanguageName);

        if(
    languageName[0] == 'H' || languageName[0] == 'S')
        {                                                   
            
    sprintf(inputLine"%u. %s\n"lineNumberlanguageName);
            
    ok 0;                                                  
        }                                                            
        else                                                         
            
    ok 1;                                                  
        
    free(languageName);                                          
        return 
    ok;                                                   
    }                                                                


    int main(void)
    {             
        
    int inputFileoutputFile;

        
    inputFile open("bhaarat.text"O_RDWR);
        if(
    inputFile == -1)                      
        {                                        
            
    perror("open");
            exit(-
    1);
        }

        
    outputFile open("out.text"O_WRONLY O_CREAT0644);
        if(
    outputFile == -1)
        {
            
    perror("open");
            exit(-
    1);
        }

        
    int curLineNumber 1;
        
    charnextLine calloc(MAX_LINE_LENGTHsizeof(char));

        while(!
    readNextLine(inputFilenextLine))
        {
            if(!
    processLine(nextLinecurLineNumber))
            {
                
    write(outputFilenextLinestrlen(nextLine)*sizeof(char));
                
    curLineNumber += 1;
            }
        }

        
    sprintf(nextLine"%s""23. English\n");
        
    write(inputFilenextLinestrlen(nextLine)*sizeof(char));

        
    close(inputFile);
        
    close(outputFile);
        
    free(nextLine);
        return 
    0;

    It's funny to compare it to the Bash one-liner above I guess now you know why it's so important to know your way around it.
    Last edited by Bachstelze; August 9th, 2008 at 07:15 PM.
    「明後日の夕方には帰ってるからね。」


  10. #20
    Join Date
    Sep 2006
    Beans
    2,914

    Re: [Beginner] Programming Challenge: 3

    Quote Originally Posted by iofthemourning View Post
    Code:
    cat bhaarat.text | tr -d [1-9.' '] | grep -E 'H|S' > out.text && echo "23. English" >> bhaarat.text
    then you are deleting off the numbers.
    Code:
    awk '$2 ~ /^(H|S)/{print d++". "$2 }END{ print "23. English" >> "bhaarat.text"}' bhaarat.text > out.text

Page 2 of 13 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
  •