Page 13 of 13 FirstFirst ... 3111213
Results 121 to 127 of 127

Thread: [Beginner] Programming Challenge: 3

  1. #121
    Join Date
    Aug 2006
    Location
    Boulder
    Beans
    64
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: [Beginner] Programming Challenge: 3

    First of all: Thanks, LaRoza, for doing this.

    I am late, too. But I was just preparing myself for a job interview tomorrow and thought it won't hurt to implement this challenge. I did it in Java. It lacks comments and is not quite readable, but it works.

    Code:
    import java.io.*;
    
    public class Challenge {
    
    	
    	public static void main(String[] args) throws FileNotFoundException, IOException {
    		// in Java 
    		BufferedWriter writer1 = new BufferedWriter(new FileWriter(new File("output.txt")));
    		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new  File("bhaarat.txt")),"UTF-8" ));
    		int counter = 0;
    		while (reader.ready()) {
    			String language = reader.readLine().split(" ")[1]; 
    			if (language.startsWith("S") || language.startsWith("H") ) writer1.write(counter++ + ". " + language +"\n");  
    		}
    		reader.close();
    		writer1.close();
    		BufferedWriter writer2 = new BufferedWriter(new FileWriter(new File("/home/johannes/bhaarat.txt"),true));
    		writer2.write("23. English");
    		writer2.close();		
    	}
    }
    Last edited by jtuchscherer; October 3rd, 2008 at 08:06 AM.

  2. #122
    Join Date
    Sep 2008
    Beans
    148

    Re: [Beginner] Programming Challenge: 3

    Eh a little late but I still want to post it :\
    PHP Code:
    #Opens specified file.
    fileopen open("bhaarat.txt""a")
    outlang open("out.txt""w")
    fileopen.writelines("23. English\n")
    #Close file
    fileopen.close()
    fileopen open("bhaarat.txt")

    for 
    language in fileopen.read().split():

     
    #If a line in file opened starts with said character/s.   
     
    if language.startswith('S') or language.startswith('H'):

         
    #Write languages starting with S and H to a text file.
         
    outlang.writelines(language+"\n")

    #Close bhaarat.txt
    fileopen.close()    
    #Close out.txt     
    outlang.close() 
    I like python makes my programs and doesn't afraid of anything.
    Last edited by ratmandall; October 17th, 2008 at 03:35 PM.

  3. #123
    Join Date
    Feb 2008
    Location
    Denmark
    Beans
    91

    Re: [Beginner] Programming Challenge: 3

    My entry in C. It doesn't check for errors when opening the file.

    PHP Code:
    /* Beginner Programming Challenge 2

       Write a program that reads bhaarat.text, and takes the languages that begin 
       with "H" or "S" and writes them to another file, named "out.text". The output 
       can be more flexible. Then have this program write "23. English" to the end 
       to continue the list in bhaarat.text. */

    #include <stdio.h>
    #include <stdlib.h>

    /* Remove all numbers, punctuations and spaces from the string. */
    void rem_nums(char *string)
    {
        const 
    char *src string;
        
    char *dst string;

        do {
            while (*
    src == '0'
                
    || *src == '1'
                
    || *src == '2'
                
    || *src == '3'
                
    || *src == '4'
                
    || *src == '5'
                
    || *src == '6'
                
    || *src == '7'
                
    || *src == '8'
                
    || *src == '9'
                
    || *src == '.'
                
    || *src == ' ')
                ++
    src;
        } while ((*
    dst++ = *src++) != '\0');
    }

    /* Opens bhaarat.text and while it hasn't reached the end of the file. For each 
       line it reads, it removes the numbers and punctuations and checks if the 
       first letter is S or H. If this is the case, the language name is appended to
       out.text.

       Finally it appends '23. English' to bhaarat.text. */
    int main()
    {    
        
    char *input_file "bhaarat.text";
        
    char *output_file "out.text";
        
    char file_input[50];
        
    FILE *read_append;
        
    FILE *append;

        
    read_append fopen(input_file"r+a");

        while(
    fgets(file_input50read_append) != NULL) {
            
    rem_nums(file_input);

            if(
    file_input[0] == 'H'
            
    || file_input[0] == 'S') {
                
    append fopen(output_file"a");
                
    fputs(file_inputappend);
                
    fclose(append);
            }
        }

        
    fputs("\n23. English"read_append);
        
    fclose(read_append);

        return 
    0;

    While making this I tried to write a function, which would assign a filepointer to fopen(). If it returned NULL, the program should print an error message:

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

    void openfile(FILE *fchar *filenamechar *fileop)
    {
        if((
    fopen(filenamefileop)) == NULL) {
            
    puts("Error.");
            exit(
    1);
        }
    }

    int main()
    {
        
    FILE *f;

        
    openfile(f"filename.txt""r");
        
    fclose(f);

        return 
    0;

    It works fine, when an error is occuring. However if the file exists the program crashes.

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

    Re: [Beginner] Programming Challenge: 3

    Quote Originally Posted by Nemooo View Post
    It works fine, when an error is occuring. However if the file exists the program crashes.
    lol

  5. #125
    Join Date
    Feb 2008
    Location
    Denmark
    Beans
    91

    Re: [Beginner] Programming Challenge: 3

    Now it works, though my openfile function returns the stream instead of passing file pointer. It was more convenient that way. In the above function the first argument should've have been a pointer to a pointer (FILE **f).

    PHP Code:
    /* Beginner Programming Challenge 3

       Write a program that reads bhaarat.text, and takes the languages that begin
       with "H" or "S" and writes them to another file, named "out.text". The output
       can be more flexible. Then have this program write "23. English" to the end
       to continue the list in bhaarat.text. */

    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>

    /* Remove all numbers, periods and spaces from the string. */
    void rem_nums(char *string)
    {
        const 
    char *src string;
        
    char *dst string;

        do {
            while(
    isdigit(*src) == 1
            
    || *src == '.'
            
    || *src == ' ')
                
    src++;
        } while((*
    dst++ = *src++) != '\0');
    }

    /* Open a file with the specified mode. If an error occured print the filename
       which caused the error and exit. Otherwise return the stream. */
    FILE *openfile(char *filenamechar *op)
    {
        
    FILE *stream fopen(filenameop);

        if(
    stream == NULL) {
            
    printf("Error opening %s."filename);
            exit(
    1);
        }

        return 
    stream;
    }

    /* Opens bhaarat.text and while it hasn't reached the end of the file. For each
       line it reads, it removes the numbers and periods and checks if the first 
       letter is S or H. If this is the case, the language name is appended to
       out.text.

       Finally it appends '23. English' to bhaarat.text. */
    int main()
    {
        
    char *input_file "bhaarat.text";
        
    char *output_file "out.text";
        
    char file_input[50];
        
    FILE *read_append;
        
    FILE *append;

        
    read_append openfile(input_file"r+a");

        while(
    fgets(file_input50read_append) != NULL) {
            
    rem_nums(file_input);

            if(
    file_input[0] == 'H'
            
    || file_input[0] == 'S') {
                
    append openfile(output_file"a");
                
    fputs(file_inputappend);
                
    fclose(append);
            }
        }

        
    fputs("\n23. English"read_append);
        
    fclose(read_append);

        return 
    0;

    Last edited by Nemooo; November 2nd, 2008 at 08:54 PM.

  6. #126
    Join Date
    May 2008
    Location
    Stafford
    Beans
    77
    Distro
    Ubuntu 11.04 Natty Narwhal

    Re: [Beginner] Programming Challenge: 3

    Started learning Python at the weekend, and thought I'd stick my first effort at these challenges out there that I know works (my own code didn't hold up to error checks for challenge 2, so had to browse the other code submissions to help me out. )
    Will hopefully have an entry for the next challenges up soon.

    PHP Code:
    #!/usr/bin/python
    #Filename challenge3.py
    #Author: Robert Orr

    import sys

    #check the file exists in same directory as this program.
    try:
        
    langfile open('bhaarat.text''r')
    except IOError:
        print 
    'Cannot locate "bhaarat.text".'
        
    sys.exit()
        
    outfile file('out.text''w')


    while True#while loop checks every line
        
    line langfile.readline()
        if 
    line.find('H') != -1:#look for Capital H
            
    linenumberlinelang line.split('. ')
            
    outfile.write('%d. %s' % (alinelang))
            
    1
        
    if line.find('S') != -1:#look for Capital S
            
    linenumberlinelang line.split('. ')
            
    outfile.write('%d. %s' % (alinelang))
            
    1
        
    if len(line) == 0:
            break

    langfile.close() # it's in read mode at the moment. close and open in write.
    outfile.close()
    langfile file('bhaarat.text''w')
    langfile.seek(02)
    langfile.write('23. English\n')
    langfile.close 
    Last edited by RobOrr; June 2nd, 2009 at 11:12 PM. Reason: put the code up in the wrong tags... duhhh
    I can resist anything except temptation.

  7. #127
    Join Date
    Jan 2008
    Beans
    4,757

    Re: [Beginner] Programming Challenge: 3

    We are hosting new challenges here. You can participate in that competition instead, rather than revive dead programming challenges.

    Regards
    Iain

Page 13 of 13 FirstFirst ... 3111213

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
  •