Programming Problems

Want to just shoot the breeze? Forum 42 is the place!

Moderator: Moderators

Post Reply
joevennix
Portablizer
Posts: 999
Joined: Sat Jan 14, 2006 9:34 am
Location: On permanent vacation from reality.

Programming Problems

Post by joevennix »

Here's the example problem I posted last week:

Code: Select all

Create a class called RomanConverter that will take in a regular, Arabic number, and output it in Roman numeral form. Input will be an integer greater than 0 and less than 2500. Hopefully this will help: 

RN   Number 
I   1 
V   5 
X   10 
L   50 
C   100 
D   500 
M   1000 

Sample input/output: 
Enter Arabic number: 152 
Equivalent Roman numeral: CLII 
Two people came up with responses, here's gannon's in PHP:

Code: Select all

<?php 
function read() { 
 $fp = fopen('php://stdin','r'); 
 $line = fgets($fp, 4); 
 fclose($fp); 
 return trim($line); 
} 
function numeralizer($int) { 
 if (!preg_match('/^\d+$/', $int) || $int <= 0 || $int > 2500) return false; 
 $int_str = ''; 
 while ($int > 0) { 
  if ($int >= 1000) { 
   $int_str .= 'M'; 
   $int -= 1000; 
  } elseif ($int >= 500) { 
   $int_str .= 'D'; 
   $int -= 500; 
  } elseif ($int >= 100) { 
   $int_str .= 'C'; 
   $int -= 100; 
  } elseif ($int >= 50) { 
   $int_str .= 'L'; 
   $int -= 50; 
  } elseif ($int >= 10) { 
   $int_str .= 'X'; 
   $int -= 10; 
  } elseif ($int >= 5) { 
   $int_str .= 'V'; 
   $int -= 5; 
  } elseif ($int >= 1) { 
   $int_str .= 'I'; 
   $int -= 1; 
  } 
 } 
 return $int_str; 
} 
$output = numeralizer(read()); 
echo (($output === false || $output == '') ? 'Input invalid or an error occured' : $output)."\n"; 
?>
He said his code would do just about everything except creating 4's and 9's, etc. (IV and IX in Roman Numerals). I think a few substr statements would have done the trick.

Here is user peedek's solution. He used Java's maps, which was a good idea I never even considered. Input is done via the String[] argument of the main method. A bit long, but it's a neat trick:

Code: Select all

import java.util.Map; 
import java.util.HashMap; 

/** 
 * RomanConverter class. 
 * Converts a given positive integer into its roman numeral equivalent. 
 * @author peedekk - Paul Dekker 
 */ 
public class RomanConverter { 

    private static Map<Integer, Character> romanMap; 

    static { 
        // Initialise roman numeral map 
        romanMap = new HashMap<Integer, Character>(); 
        romanMap.put(1000, 'M'); 
        romanMap.put(500, 'D'); 
        romanMap.put(100, 'C'); 
        romanMap.put(50, 'L'); 
        romanMap.put(10, 'X'); 
        romanMap.put(5, 'V'); 
        romanMap.put(1, 'I'); 
    } 

    public static String convert(int number) { 
        StringBuffer romanNumeral = new StringBuffer(); 

        int theOneNum = 1000; 
        for (int i = 0; i < 4; i++) {   // run through four times (1000, 100, 10, 1) 
            for (int j = 0; j < number/theOneNum; j++) { 
                romanNumeral.append(romanMap.get(theOneNum)); 
            } 
            number = number % theOneNum; 

            if (theOneNum == 1) break;  // check if just added the I's, & break out if so 

            int theNineNum = theOneNum - (theOneNum/10);        //900, 90, 9 
            int theFiveNum = theOneNum / 2;                     //500, 50, 5 
            int theFourNum = theFiveNum - (theOneNum/10);       //400, 40, 4 
            if (number >= theNineNum) { 
                romanNumeral.append(romanMap.get(theOneNum/10)).append(romanMap.get(theOneNum)); 
                number -= theNineNum; 
            } else if (number >= theFiveNum) { 
                romanNumeral.append(romanMap.get(theFiveNum)); 
                number -= theFiveNum; 
            } else if (number >= theFourNum) { 
                romanNumeral.append(romanMap.get(theOneNum/10)).append(romanMap.get(theFiveNum)); 
                number -= theFourNum; 
            } 
            
            theOneNum /= 10;    // divide theOneNum by 10 - move to next number (1000, 100, 10, 1) 
        } 

        return romanNumeral.toString(); 
    } 

    /** 
     * After compiling the program (javac RomanConverter.java) 
     * Run the program with the positive integer as an argument 
     *  (java RomanConverter [positive_integer]) 
     *  e.g. java RomanConverter 152 
     * 
     * @param args The positive integer to convert into Roman Numerals. 
     */ 
    public static void main(String[] args) { 
        if (args.length != 1) { 
            System.out.println("Invalid syntax.\njava RomanConverter arabic-number\nExample: java RomanConverter 152");
            System.exit(1); 
        } 
        if (!args[0].matches("\\d+")) { 
            System.out.println("Error: Data entered is not a positive integer. '" + args[0] + "'"); 
            System.exit(1); 
        } 

        int arabicNumber = Integer.parseInt(args[0]); 
        String romanNumeral = RomanConverter.convert(arabicNumber); 

        System.out.println("Resulting Roman Numeral: " + romanNumeral); 

        System.exit(0); 
    } 

}
And finally here's mine. Written in java, uses Scanner to get console input:

Code: Select all

import java.util.Scanner;

public class RomanConverter
{
    public static void main(String[] args)
    {
        System.out.println("Equivalent Roman numeral: "+convertToRoman(readInput()));  
    }
    
    public static int[] readInput()
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter Arabic number: ");
        String line = scan.nextLine();
        if (Integer.parseInt(line) >= 4000 || Integer.parseInt(line) <= 0)
        {
            System.out.println("Invalid input");
            return new int[]{};
        }
        int[] output = new int[line.length()];
        for (int i = 0; i < output.length; i++)
            output[i] = Character.getNumericValue(line.charAt(line.length()-1-i)); 
        return output;                              
    }
    
    public static String convertToRoman(int[] nums)
    {
        String[] romanTenValues = {"I", "X", "C", "M"}; 
        String output = "";                        
        for (int i = 0; i < nums.length; i++)
        {
            for (int j = 0; j < nums[i]; j++)
                output += romanTenValues[i];
        }
        output = flipString(output);
        output = output.replaceAll("IIIIIIIII", "IX"); 
        output = output.replaceAll("IIIII", "V");       
        output = output.replaceAll("IIII", "IV");
        output = output.replaceAll("XXXXXXXXX", "XC");  
        output = output.replaceAll("XXXXX", "L");       
        output = output.replaceAll("XXXX", "XL");
        output = output.replaceAll("CCCCCCCCC", "CM");
        output = output.replaceAll("CCCCC", "D");
        output = output.replaceAll("CCCC", "CD");
        return output;                  
    }  
    
    public static String flipString(String in)  
    {
        String out = "";
        for (int i = in.length()-1; i >= 0; i--)
            out += in.charAt(i);
        return out;
    }
}

And that's it for last week. Now for the current contest:

Code: Select all

Programming Challenge: Challenge 1 - Monday, May 14, 2007

Calendar Generator
Many times you will need to check what day of the week a certain date lies on, and you find yourself without a calendar. You think to yourself, man I knew I should've coded a calendar generator last week, and you end up having to get off your ass and look through every drawer in the house to find one.

Today we will put an end to this extremely widespread problem. Here is this week's challenge: 

Given a MM/DD/YYYY input, generate a calendar of the month given, the previous month, and the following month. Also, print out what day of the week the given date is on. Here is some sample in/output.

	Enter the date (MM/DD/YYYY): 05/14/1887
	
	May 14, 1887 is a Saturday. Here is a very handy calendar: 

	April                         May                           June                          
	S  M  T  W  T  F  S           S  M  T  W  T  F  S           S  M  T  W  T  F  S           
	               1  2           1  2  3  4  5  6  7                    1  2  3  4           
	3  4  5  6  7  8  9           8  9  10 11 12 13 14          5  6  7  8  9  10 11          
	10 11 12 13 14 15 16          15 16 17 18 19 20 21          12 13 14 15 16 17 18          
	17 18 19 20 21 22 23          22 23 24 25 26 27 28          19 20 21 22 23 24 25          
	24 25 26 27 28 29 30          29 30 31                      26 27 28 29 30          

Good luck 
-Joe
Make sure to PM me code or questions. If you feel like the problem is too long, just do a one month calendar.
Image
Gamelver
Moderator
Posts: 3352
Joined: Sun Apr 04, 2004 9:03 pm
Location: in my basement, to forever work on portables ;)

Post by Gamelver »

huh...pretty fun :).

in the 30-40 minutes I've worked on it, I've been able to get the day when the year is 2007 or after 2007, and now just have to do all the years before :P. I'll finish it up tomorrow and PM it to you.
Without games my life would have no meaning.
Well, I guess it would, but it would be a lot less fun!!!!!!!

Image
gannon
Moderator
Posts: 6974
Joined: Sun Apr 04, 2004 4:48 pm
Location: Near that one big lake
Contact:

Post by gannon »

Got my entry in...oh..forgot to mention, only works on dates past the Unix epoch
Skyone
Moderator
Posts: 6390
Joined: Tue Nov 29, 2005 8:35 pm
Location: it is a mystery
Contact:

Post by Skyone »

I'll work on mine tomorrow, should be in C++. I might do a VB one later on, though - just for the looks. :P
peedekk
Posts: 77
Joined: Mon Feb 19, 2007 8:20 pm
Location: Wellington, New Zealand.
Contact:

Re: Programming Problems

Post by peedekk »

Got my entry in.
joevennix wrote:A bit long, but it's a neat trick
For my defence, not counting blank or comment lines, my code comes to 55 lines, where yours would come to 51 :D maybe thats why its just a bit long

althou this latest entry comes to 199 lines.. whoops
Progress on portable SMS2 - 0%
gannon
Moderator
Posts: 6974
Joined: Sun Apr 04, 2004 4:48 pm
Location: Near that one big lake
Contact:

Post by gannon »

Mine is34 counting the script tags (the current calender code that is) :P
Nonsense Man
Posts: 896
Joined: Wed Dec 28, 2005 10:03 am
Location: somewhere

Post by Nonsense Man »

I have never coded and i want to learn so what is a easy language to understand?? I just posted this here because it has to do with coding. SO can someone please help me??
gannon
Moderator
Posts: 6974
Joined: Sun Apr 04, 2004 4:48 pm
Location: Near that one big lake
Contact:

Post by gannon »

It really depends on what you want to do. I mainly do web & cli programming, so I use php since it's not too bad at either.
joevennix
Portablizer
Posts: 999
Joined: Sat Jan 14, 2006 9:34 am
Location: On permanent vacation from reality.

Re: Programming Problems

Post by joevennix »

peedekk wrote:Got my entry in.
joevennix wrote:A bit long, but it's a neat trick
For my defence, not counting blank or comment lines, my code comes to 55 lines, where yours would come to 51 :D maybe thats why its just a bit long
You're right. Once I deleted all unnecessary lines/comments, it looked exactly the same length as min. :oops:
peedekk wrote:althou this latest entry comes to 199 lines.. whoops
Don' worry, mine is up there somewhere. :-/

For those who haven't finished. Since it is more than halfway through the week, I thought I'd give you a little hint. To figure out the first day of a month, you can use this bit of math.
Image
joevennix
Portablizer
Posts: 999
Joined: Sat Jan 14, 2006 9:34 am
Location: On permanent vacation from reality.

Post by joevennix »

Okay, well another week's gone by. I think this first challenge took way to long to do, which I came to realize after finishing my own solution. Most people, I realize, just don't have this much time. Anyways, on to the entries.

Peedek again with a Java entry, using Java's built-in calendar and date classes. I've never messed with those before, I think I'll check the API later to have a look:

Code: Select all

import java.text.ParseException; 
import java.text.SimpleDateFormat; 

import java.util.Calendar; 
import java.util.Date; 
import java.util.GregorianCalendar; 
import java.util.Scanner; 

/** 
 * Calendar Generator. 
 * Uses Scanner to read date input from System.in 
 * Based on Doomsday rule/algorithm to workout first day of month. 
 * 
 * @author peedekk - Paul Dekker 
 */ 
public class CalendarGenerator { 
    public static String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; 
    public static String[] months = {"January", "February", "March", "April", "May", "June", 
                                "July", "August", "September", "October", "November", "December"}; 
    
    public static void main(String[] args) { 
        System.out.println(generateCalendar()); 
    } 
    
    public static String generateCalendar() { 
        Scanner scan = new Scanner(System.in); 
        System.out.println("Enter date (MM/DD/YYYY): "); 
        Date date = null; 
        while (date == null) { 
            String line = scan.nextLine(); 
            if (line != null && line.equals("exit")) { 
                return "exited."; 
            } 
            try { 
                date = new SimpleDateFormat("MM/dd/yyyy").parse(line); 
            } catch (ParseException e) { 
                System.err.println("Date entered not in format: MM/DD/YYYY! Type 'exit' to cancel."); 
            } 
        } 
        GregorianCalendar theDate = new GregorianCalendar(); 
        theDate.setTime(date); 
        Integer prevYear = null, nextYear = null; 
        Integer year = theDate.get(Calendar.YEAR); 
        boolean leapYear = theDate.isLeapYear(year); 
        Integer month = theDate.get(Calendar.MONTH); 
        Integer prevMonth = month - 1; 
        Integer nextMonth = month + 1; 
        if (prevMonth < 0) { 
            prevYear = year - 1; 
            prevMonth += 12; 
        } 
        if (nextMonth > 11) { 
            nextYear = year + 1; 
            nextMonth -= 12; 
        } 
        if ((year > 9999 || year < 0) || 
                (prevYear != null && prevYear < 0) || 
                (nextYear != null && nextYear > 9999)) { 
            System.err.println("Can only generate calendars for years 0-9999"); 
            System.exit(1); 
        } 
        Integer prevDoomsday = getDoomsday(prevYear); 
        Integer doomsday = getDoomsday(year); 
        Integer nextDoomsday = getDoomsday(nextYear); 
        
        String enteredDay = days[((getFirstDay(month, doomsday, leapYear)) 
                                + theDate.get(Calendar.DAY_OF_MONTH)-1)%7]; 
        System.out.println("\n" + new SimpleDateFormat("MMM dd, yyyy").format(date) + " is a " 
                            + enteredDay + ". Here is a very handy calendar:\n"); 
        
        String monthLine = months[prevMonth]; 
        for (int i = months[prevMonth].length(); i < 30; i++) { 
            monthLine += " "; 
        } 
        monthLine += months[month]; 
        for (int i = months[month].length(); i < 30; i++) { 
            monthLine += " "; 
        } 
        monthLine += months[nextMonth]; 
        String tenSpaces = "          "; 
        System.out.println(monthLine); 
        
        int prevFirstDay = getFirstDay(prevMonth, (prevDoomsday != null ? prevDoomsday : doomsday), leapYear); 
        int firstDay = getFirstDay(month, doomsday, leapYear); 
        int nextFirstDay = getFirstDay(nextMonth, (nextDoomsday != null ? nextDoomsday : doomsday), 
                            (nextYear != null ? theDate.isLeapYear(nextYear) : leapYear)); 
        int prevCount = 1, count = 1, nextCount = 1; 
        
        String[] prevMonthCal = getCalendar(prevMonth, prevFirstDay, leapYear); 
        String[] monthCal = getCalendar(month, firstDay, leapYear); 
        String[] nextMonthCal = getCalendar(nextMonth, nextFirstDay, 
                                (nextYear != null ? theDate.isLeapYear(nextYear) : leapYear)); 

        String calendar = ""; 
        
        for (int i = 0; i < 6; i++) { 
            calendar += prevMonthCal[i] + tenSpaces + monthCal[i] 
                        + tenSpaces + nextMonthCal[i] + "\n"; 
        } 
        
        return calendar; 
    } 

    private static Integer getDoomsday(Integer year) { 
        if (year == null) { 
            return null; 
        } 
        int[] anchors = {2, 0, 5, 3}; 
        int anchorDay = anchors[((year/100)%4)]; 
        
        int y = year % 100; 
        
        return ((((y/12) + (y%12) + ((y%12)/4))%7) + anchorDay)%7; 
    } 
    
    private static Integer getFirstDay(int month, int doomsday, boolean leapYear) { 
        Integer returnDay = null; 
        if (month == 0) { 
            if (leapYear) { 
                returnDay = (doomsday - 3)%7; 
            } else { 
                returnDay = (doomsday - 2)%7; 
            } 
        } else if (month == 1) { 
            if (leapYear) { 
                returnDay = doomsday; 
            } else { 
                returnDay = (doomsday + 1)%7; 
            } 
        } else if (month == 2) { 
            returnDay = (doomsday + 1)%7; 
        } else if (month == 3) { 
            returnDay = (doomsday - 3)%7; 
        } else if (month == 4) { 
            returnDay = (doomsday - 1)%7; 
        } else if (month == 5) { 
            returnDay = (doomsday - 5)%7; 
        } else if (month == 6) { 
            returnDay = (doomsday  - 3)%7; 
        } else if (month == 7) { 
            returnDay = doomsday; 
        } else if (month == 8) { 
            returnDay = (doomsday - 4)%7; 
        } else if (month == 9) { 
            returnDay = (doomsday - 2)%7; 
        } else if (month == 10) { 
            returnDay = (doomsday + 1)%7; 
        } else if (month == 11) { 
            returnDay = (doomsday - 4)%7; 
        } 
        if (returnDay != null && returnDay < 0) { 
            returnDay += 7; 
        } 
        return returnDay; 
    } 
    
    private static String[] getCalendar(int month, int firstDay, boolean leapYear) { 
        String calendar = "S  M  T  W  T  F  S \n"; 
        String twentySpaces = "                    "; 
        int lastDayOfMonth = getLastDayOfMonth(month, leapYear); 
        int dayCount = 1; 
        
        int wrapDays = 0; 
        if (firstDay >= 5 && lastDayOfMonth >= 30) { 
            if (firstDay == 5 && lastDayOfMonth == 30) { 
                calendar += "30 "; 
                wrapDays = 1; 
            } else if (firstDay == 6) { 
                if (lastDayOfMonth == 30) { 
                    calendar += "30 "; 
                    wrapDays = 1; 
                } else { 
                    calendar += "30 31 "; 
                    wrapDays = 2; 
                } 
            } 
        } 
        
        for (int i = wrapDays * 3; i < (firstDay * 3); i++) { 
            calendar += " "; 
        } 
        calendar += dayCount++ + "  "; 
        while (dayCount <= lastDayOfMonth) { 
            if ((firstDay + (dayCount - 1))%7 == 0) { 
                calendar = calendar.substring(0, calendar.length()-1) + "\n"; 
            } 
            calendar += dayCount++ + " "; 
            if (dayCount <= 10) { 
                calendar += " "; 
            } 
        } 
        
        String[] calendarSplit = calendar.split("\n"); 
        if (calendarSplit.length == 5) { 
            String[] newCalSplit = new String[6]; 
            for (int i = 0; i < 5; i++) { 
                newCalSplit[i] = calendarSplit[i]; 
            } 
            newCalSplit[5] = twentySpaces; 
            calendarSplit = newCalSplit; 
        } 
        
        if (calendarSplit[5].length() != 20) { 
            for (int i = calendarSplit[5].length(); i < 20; i++) { 
                calendarSplit[5] += " "; 
            } 
        } 
        
        return calendarSplit; 
    } 
    
    private static int getLastDayOfMonth(int month, boolean leapYear) { 
        if (month == 0 || month == 2 || month == 4 || month == 6 
                || month == 7 || month == 9 || month == 11) { 
            return 31; 
        } else if (month == 3 || month == 5 || month == 8 || month == 10) { 
            return 30; 
        } else if (month == 1) { 
            if (leapYear) { 
                return 29; 
            } else { 
                return 28; 
            } 
        } else { 
            return -1; 
        } 
    } 

}
Gannon, written again in PHP, generates a one month calendar. Let's have a look:

Code: Select all

<?php 
function read() { 
 $fp = fopen('php://stdin','r'); 
 $line = fgets($fp, 11); 
 fclose($fp); 
 return trim($line); 
} 
function make_calender($month, $year) { 
 $time = mktime(0, 0, 0, $month, 1, $year); 
 $day = date('w', $time); 
 $days = date('t', $time); 
 echo date('F', $time).' - '.$year."\n"; 
 echo "S\tM\tT\tW\tT\tF\tS\n"; 
 for ($i=0; $i<$day; $i++) echo "\t"; 
 for ($tmp = 1; $tmp <= $days; $tmp++) { 
  echo $tmp."\t"; 
  if  ($day == 6) { 
   echo "\n"; 
   $day = -1; 
  } 
  $day++; 
 } 
} 
$input = read(); 
list($month, $day, $year) =  explode('/', $input); 
if (!checkdate($month, $day, $year) || $month == '' || $day == '' || $year == '') exit('Input invalid'."\n"); 
$prev = ($month == 1) ? array('1',$year-1) : array($month-1, $year); 
$next = ($month == 12) ? array('1', $year+1) : array($month+1, $year); 
make_calender($prev[0], $prev[1]); 
echo "\n\n"; 
make_calender($month, $year); 
echo "\n\n"; 
make_calender($next[0], $next[1]); 
?>
Here's my solution. It uses the equation found here to figure out what day of the week a day falls on. Here is the specific method:

Code: Select all

private int calculateFirstDay(int month, int day, int year)
    {
        int[] months = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};
        if (year%4 == 0)
        {
            months[0] = 6;
            months[1] = 2;
        }
        month = months[month-1];
        return ((year / 4) + year - (year/100) + (year/400) + day - 1 + month) % 7;
    }
And here is the rest of the program:

Code: Select all

import java.util.Scanner;

class CalLogic
{
    private int[] dayCount = {1, 1, 1}; //for generating calendar, tells what day of each month the for loops is on
    
    public void readInput()
    {        
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the date (MM/DD/YYYY): ");
        String line = scan.nextLine().trim();       //read input as a string
        if (line.length() != 10) {                  //check if input is 10 chars long
            System.out.println("Incorrect input");
            System.exit(0);
        }
        String[] date = line.split("/");            //split input into string array using '/' as a delimiter
        int day=0, month=0, year=0;
        if (date[0].substring(0, 1).equals("0"))                    //parse day, month, and year, removing leading 0 as necessary (05/05/1991 = 5/5/1991) 
            month = Integer.parseInt(date[0].substring(1, 2));
        else
            month = Integer.parseInt(date[0]);
        if (date[1].substring(0, 1).equals("0"))
            day = Integer.parseInt(date[1].substring(1, 2));
        else
            day = Integer.parseInt(date[1]);
        year = Integer.parseInt(date[2]);
        if (month > 12 || month < 1 || day > 31 || day < 1 || year < 1) {       //make sure day, month, and year are in the correct range
            System.out.println("Incorrect input");
            System.exit(0);
        }
        printDayTeller(month, day, year);                 //tell user what day the date falls on
        generateCalendar(month, day, year);                 //generate calendar
    }
    
    private void generateCalendar(int month, int day, int year)
    {
        printMonthsAndDays(month, day, year);
        printFirstDayLine(month, day, year);
        int[] monthDays = {0, 31, 38, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int[] months = {month-1, month, month+1};
        if (months[0] == 0)     months[0] = 12;
        if (months[2] == 13)    months[3] = 1;
        boolean[] b = {true, true, true};
        String temp = "";
        for (int i = 0; i < 5; i++)
        {
            for (int k = 0; k < 3; k++)
            {
                for (int h = 0; h < 7; h++)
                {
                    if (b[k])                               //while the day for each month is less than the number of days in each month, the loop adds this day to the calendar
                    {
                        if (dayCount[k] >= 10)  
                            temp += dayCount[k] + " ";
                        else
                            temp += dayCount[k] + "  ";
                    }
                    if (dayCount[k] == monthDays[months[k]])
                        b[k] = false;
                    dayCount[k]++;
                }
                System.out.print(space(temp));
                temp = "";
            }
            System.out.println();
        }
    }
    
    private String space(String in)    //used to space each month evenly
    {
        String out = "";
        for (int i = 0; i < 30-in.length(); i++)
            out += " ";
        return in+out;
    }
    
    private int calculateFirstDay(int month, int day, int year)     //formula to calculate the day a date falls on
    {
        int[] months = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};
        if (year%4 == 0)
        {
            months[0] = 6;
            months[1] = 2;
        }
        month = months[month-1];
        return ((year / 4) + year - (year/100) + (year/400) + day - 1 + month) % 7;
    }
    
    private void printMonthsAndDays(int month, int day, int year)        //prints first 2 lines of calendar (month line and day line)
    {
        String monthsLine = "";
        String[] months = {"", "January", "February", "March", "April", "May", 
                "June", "July", "August", "September", "October", "November", "December"};
        if (month > 1 && month < 12)
            monthsLine = space(months[month-1]+" "+year) + space(months[month]+" "+year) + space(months[month+1]+" "+year);
        else if (month == 12)
            monthsLine = space(months[11]+" "+year) + space(months[12]+" "+year) + space(months[1]+" "+(year+1));
        else if (month == 1)
            monthsLine = space(months[12]+ " "+(year-1)) + space(months[1]+" "+year) + space(months[2]+" "+year);
        String daysLine = space("S  M  T  W  T  F  S") + space("S  M  T  W  T  F  S") + space("S  M  T  W  T  F  S");
        System.out.println("\n"+monthsLine + "\n" + daysLine);
    }    
    
    private void printDayTeller(int month, int day, int year)   //prints first statement of which day date falls on
    {
        int d = calculateFirstDay(month, day, year);
        String[] months = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
        String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        System.out.println("\n"+months[month]+" "+day+", "+year+" is a "+days[d]+". Here is a very handy calendar: ");
    }
    
    private void printFirstDayLine(int month, int day, int year)   //prints first line of days, starting at the day the month starts at
    {
        int prevMonth = month - 1;
        if (prevMonth == 0)     prevMonth = 12;
        int nextMonth = month + 1;
        if (nextMonth == 13)    nextMonth = 1;
        int[] firstDay = {1, 1, 1};
        firstDay[0] = calculateFirstDay(prevMonth, 1, year);
        firstDay[1] = calculateFirstDay(month, 1, year);
        firstDay[2] = calculateFirstDay(nextMonth, 1, year);
        String temp = "";
        for (int i = 0; i < firstDay.length; i++)
        {
            for (int k = 0; k < 7; k++)
            {
                if (k >= firstDay[i])   {
                    temp += dayCount[i]+"  ";
                    dayCount[i]++;
                }
                else
                    temp += "   ";
            }
            if (temp.equals("                     "))   {
                System.out.print(space("1  2  3  4  5  6  7"));
                dayCount[i] = 8;
            }
            else
                System.out.print(space(temp));
            temp = "";
        }
        System.out.println();
    }
}

public class CalendarGenerator              //static class used to instantiate previous class and execute previous methods
{
    public static void main(String[] args)
    {
        CalLogic c = new CalLogic();
        c.readInput();
    }
}
Not very short, still 150+ lines with spacing.

Okay, now on to the newest challenge. This one is going to be much shorter and easier. The problem is this:

Code: Select all

In the United States, a comma is used to separate thousands of a number. The program will do just that: take in a number as an int, and output it as a String with commas/periods inserted in the correct positions. Here is some sample i/o:

Enter number: 112314123
Output: 112,314,123

Good luck, and bonus points to anyone who uses recursion to solve the problem (its an easy one!)
More entries this week :)

-Joe
Image
gannon
Moderator
Posts: 6974
Joined: Sun Apr 04, 2004 4:48 pm
Location: Near that one big lake
Contact:

Post by gannon »

Done...oh, and I just noticed a bug in my calendar program, if the month entered is January, the previous month shown will be January of the previous year instead of December (put a 1 instead of a 12 :P)
Edit: Also, I might be able to add functionality for pre-Unix Epoch dates by using that equation to make a mapping function that does a year shift
peedekk
Posts: 77
Joined: Mon Feb 19, 2007 8:20 pm
Location: Wellington, New Zealand.
Contact:

Post by peedekk »

I didn't get time to do last weeks one, how did people go?
Progress on portable SMS2 - 0%
Skyone
Moderator
Posts: 6390
Joined: Tue Nov 29, 2005 8:35 pm
Location: it is a mystery
Contact:

Post by Skyone »

Same thing for me, no time to do it... packed with school work!
gannon
Moderator
Posts: 6974
Joined: Sun Apr 04, 2004 4:48 pm
Location: Near that one big lake
Contact:

Post by gannon »

Almost forgot about this :P
So, what's up? I know I'm busy until next week :P
peedekk
Posts: 77
Joined: Mon Feb 19, 2007 8:20 pm
Location: Wellington, New Zealand.
Contact:

Post by peedekk »

I've got time to code, any new programming problems coming up?
Progress on portable SMS2 - 0%
Post Reply