Cable Forum

Cable Forum (https://www.cableforum.uk/board/index.php)
-   General IT Discussion (https://www.cableforum.uk/board/forumdisplay.php?f=19)
-   -   Programming Challenges? (https://www.cableforum.uk/board/showthread.php?t=33653991)

Fobic 17-08-2009 20:27

Re: Programming Challenges?
 
Before we move on too far here's my attempts at the previous challenges
Both are VB.net console Apps.

Mutliples of 3 and 5 without using any type of Modulus functions:

Spoiler: 

Code:

Module MultiplesOf3And5
 
  Sub Main()
      Dim aList As New SortedList
 
      '//iterate through all the possible multiples
      '//and store any previously unfound ones in a Sorted List
      For intFifteens As Integer = 3 * 5 To 100 Step 3 * 5
        aList.Add(intFifteens, " is a multiple of both 3 and 5")
      Next intFifteens
 
      For intFives As Integer = 5 To 100 Step 5
        If Not aList.Contains(intFives) Then aList.Add(intFives, " is a multiple of 5")
      Next intFives
 
      For intThrees As Integer = 3 To 100 Step 3
        If Not aList.Contains(intThrees) Then aList.Add(intThrees, " is a multiple of 3")
      Next intThrees
 
      '//Display the contents of the Sorted List
      For intIndex As Integer = 0 To aList.Count - 1
        Console.WriteLine(aList.GetKey(intIndex) & aList.GetByIndex(intIndex))
      Next intIndex
      Console.ReadKey(True)
 
  End Sub
 
End Module

The For/Next Loops step through each multiple
of 3*5, 5 and 3 and adds the multiples to a Sorted List
if they haven't already been added.

A Sorted List is a list where each item in the list
consists of two parts: a Key part and a Value part.
The list is automatically sorted on the Key part.

We store each iterated multiple in the the Key part
and text explaining the type of multiple is
stored in the corresponding Value part.

Then we just display the contents of the Sorted List.



And a quick and dirty way of calculating the Monty Hall probabilities
(with thanks to Damien for coding tips)

Spoiler: 

Code:

Module MontyHall
 
  Sub Main()
      Dim aRnd As New Random
      Dim Doors() As String = {"Goat", "Goat", "Goat"}  '//put 3 Goats behind 3 doors
 
      Dim intDoorWithCar As Integer                '//Number of the Door with the Car
      Dim intDoorChosen As Integer                '//Number of the Door we choose
      Dim intChosenDoorWinCount As Integer = 0    '//Accumulated wins sticking with original chosen door
      Dim intAlternateDoorWinCount As Integer = 0  '//Accumulated wins swapping to alternate door
      Dim intNumIterations As Integer = 100000
 
      For intI As Integer = 1 To intNumIterations
        intDoorWithCar = aRnd.Next(3)    '//Randomly replace one of the
        Doors(intDoorWithCar) = "Car"    '//  3 Goats with a Car
 
        intDoorChosen = aRnd.Next(3)    '//Choose one of the 3 doors at random
        If intDoorChosen = intDoorWithCar Then intChosenDoorWinCount += 1 Else intAlternateDoorWinCount += 1
 
        Doors(intDoorWithCar) = "Goat"  '//Replace the Car with a Goat
      Next intI                          '// and go around again
 
      Console.WriteLine("Percentage probability of winning Car:")
      Console.WriteLine("Keeping Original Choice of Door  = " & Format(intChosenDoorWinCount / intNumIterations, "Percent"))
      Console.WriteLine("Swapping Choice to the Other Door = " & Format(intAlternateDoorWinCount / intNumIterations, "Percent"))
      Console.ReadKey(True)
 
  End Sub
 
End Module


We choose one of the 3 doors at random.
Monty removes one of the remaining 2 doors
that has a goat behind it.
We don't need to know which door, just that a goat
has been removed and now we only have 2 doors left
- A goat behind one and a Car behind the other, and
that our chosen door is one of them.

The If/THEN/ELSE line of the code works as follows:

If we stick with our choice and win, then
increase the count of wins for the Chosen Door.
(in the "Swapping Doors Scenario" we would have lost)

If we stick with our choice and lose, then in the
"Swapping Doors Scenario" we would have won, so
increase the count of wins for the Alternate Door.


punky 17-08-2009 20:35

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34856194)
Nice Punky. It's only not 'proper' OO because it's limited in scope (i.e the project is too small) to use many features. OO becomes more central to your application structure in bigger applications anyway. I mean all you can do is make door an object really...(which you did, smart).

You probably know this but when accessing a variable outside of it's containing class you should make it a property..

Indeedy. Normally I make all class variables private with the proper accessors (proper encapsulation) but I didn't just because it meant typing lines and lines of code for no real benefits. I would for any "production"-level app.

Here's the Door class with proper encapsulation (I would normally prefix private class variables with _ (like _doorNumber) but that's just convention)

Spoiler: 
Code:

    //class to represent the door
    class Door
    {
        private int doorNumber;
        private Boolean open = false;
        private String prize;

        //constructor, this happens when a door is created
        public Door(int doorNumber, String prize)
        {
            this.doorNumber = doorNumber;
            this.prize = prize;
        }

        //this is called when we Console.WriteLine a door. We have to override the default ToString() method
        public override String ToString()
        {
            String status = open ? "Open" : "Closed";
            return "Door " + doorNumber + ": " + prize + " (" + status + ")";
        }

        public bool Open
        {
            get
            {
                return open;
            }
            set
            {
                open = value;
            }
        }

        public String Prize
        {
            get
            {
                return prize;
            }
            set
            {
                prize = value;
            }

        }

        public int DoorNumber
        {
            get
            {
                return doorNumber;
            }
            set
            {
                doorNumber = value;
            }
        }
    }



I tend to find because I use OO a lot now that unless something is really small (i.e. an algorithm rather than a game) that I start building it in OO first and then scaling back if it really gets unnecessary.

BTW the point being of all that is that you can control what comes in and out of the class. For example for the prize, I can make sure its one of x pre-determined prizes, that a door number is greater than 0, etc.

Damien 17-08-2009 20:55

Re: Programming Challenges?
 
Quote:

Originally Posted by punky (Post 34856229)

I tend to find because I use OO a lot now that unless something is really small (i.e. an algorithm rather than a game) that I start building it in OO first and then scaling back if it really gets unnecessary.

BTW the point being of all that is that you can control what comes in and out of the class. For example for the prize, I can make sure its one of x pre-determined prizes, that a door number is greater than 0, etc.

Yes, Well all app in C# eventually needs to be done via OO. It's all I really work in (other than these apps).

punky 17-08-2009 22:33

Re: Programming Challenges?
 
Here's my mortgage length calculator:

Spoiler: 

I'm sure there's a way to do it without a loop, but can't think of it atm.

Assuming £100,000 with a 4.75% rate and paying off £700/month
Code:

            float mortgage = 100000f;
            float rate = 4.75f; //%
            int repaymentAmount = 700;

            float months = 0;

            while (mortgage > 0)
            {
                mortgage *= (1 + ((rate / 12) / 100));
                mortgage -= repaymentAmount;
                months++;
            }

            Console.WriteLine("Repayment duration: " + months + " months - " + (int)(months/12) + " Years and " + (months%12) + " months.");

Result:

Repayment duration: 211 months - 17 Years and 7 months.

danielf 17-08-2009 22:42

Re: Programming Challenges?
 
Here's my mortgage calculator, using recursion

Spoiler: 

(defun mortgage (balance payment rate months)
(if
(< balance 0)
(print months)
(mortgage (- (+ (* (/ rate 12) balance) balance) payment) payment rate (+ months 1))))


How do you get indentation in the code? My code is indented when I paste it, but I lose indentation in the spoiler tags. Even spaces don't stick...

punky 17-08-2009 23:03

Re: Programming Challenges?
 
I did wonder about recursion...

Spoiler: 

Code:

class Program
    {
        static int months = 0;

        static void Main(string[] args)
        {
            CalculateMortgage(100000f, 4.75f, 700);
            Console.ReadLine();
        }

        static void CalculateMortgage(float mortgage,float rate,int repaymentAmount)
        {

            if (mortgage > 0)
            {
                months++;
                CalculateMortgage((mortgage * (1 + ((rate / 12) / 100)) - repaymentAmount), rate, repaymentAmount);
               
            }
            else
            {
                Console.WriteLine("Repayment duration: " + months + " months - " + (int)(months / 12) + " Years and " + (months % 12) + " months.");
            }

        }
    }

Result:

Repayment duration: 211 months - 17 Years and 7 months.


I'm still sure there must be an equation for it rather than just iterating through.

danielf 17-08-2009 23:16

Re: Programming Challenges?
 
Quote:

Originally Posted by punky (Post 34856342)

I'm still sure there must be an equation for it rather than just iterating through.

Probably, but it is a programming challenge, not a Maths challenge :)

Fobic 18-08-2009 03:40

Re: Programming Challenges?
 
Quote:

Originally Posted by danielf (Post 34856320)
How do you get indentation in the code? My code is indented when I paste it, but I lose indentation in the spoiler tags. Even spaces don't stick...


Try wrapping the code in [Code][/Code] tags inside the [Spoiler][/Spoiler] tags.

i.e.

[Spoiler][Code]
.....
......
[/Code][/Spoiler]

or similar.


Can anyone tell me how to stop my code appearing in colour when I Copy from the standard VB 2005 Express Editor and Paste in here ??

like this:
Code:

PrivateSub StopTheseColours()
Dim aString AsString = "123"
'How to paste this code in Black and White?
EndSub


Druchii 18-08-2009 05:32

Re: Programming Challenges?
 
Paste into Notepad first?
Or, highlight the pasted text and set the font color to black?

Damien 18-08-2009 08:41

Re: Programming Challenges?
 
I did it simply but the results where wrong. I thought interest was a set % amount of the total balance. I take it you need to apply it per month instead?

Druchii 18-08-2009 08:50

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34856457)
I did it simply but the results where wrong. I thought interest was a set % amount of the total balance. I take it you need to apply it per month instead?

From what i can work out, some apply the interest yearly, others monthly. It all depends.

Mine calculates on the yearly balance, however.

punky 18-08-2009 09:50

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34856457)
I did it simply but the results where wrong. I thought interest was a set % amount of the total balance. I take it you need to apply it per month instead?

Yup. Because the longer you take to repay the mortgage, the more interest you pay.

danielf 18-08-2009 10:40

Re: Programming Challenges?
 
Quote:

Originally Posted by Fobic (Post 34856422)
Try wrapping the code in [Code][/Code] tags inside the [Spoiler][/Spoiler] tags.

i.e.

[Spoiler][Code]
.....
......
[/Code][/Spoiler]

or similar.

Cheers!

Spoiler: 
Code:

(defun mortgage (balance payment rate months)
  (if
      (< balance 0)
      (print months)
    (mortgage (- (+ (* (/ rate 12) balance) balance) payment) payment rate (+ months 1))))


Fobic 18-08-2009 16:46

Re: Programming Challenges?
 
Quote:

Originally Posted by Druchii (Post 34856431)
Paste into Notepad first?
Or, highlight the pasted text and set the font color to black?


Thanks for answering :).
I'd already used the Paste to Notepad route which works but unfortunately strips out blank lines between code lines, which means you have to edit the code in Notepad to double every blank line.

Changing the Font colour is a nice thought, but the coloured code in here is also broken code. Spaces between keywords are stripped and the indentation is also stripped.

Guess I'm just looking for the laziest way of doing it (as usual, lol).

punky 18-08-2009 16:49

Re: Programming Challenges?
 
Quote:

Originally Posted by Fobic (Post 34856726)
Thanks for answering :).
I'd already used the Paste to Notepad route which works but unfortunately strips out blank lines between code lines, which means you have to edit the code in Notepad to double every blank line.

Changing the Font colour is a nice thought, but the coloured code in here is also broken code. Spaces between keywords are stripped and the indentation is also stripped.

Guess I'm just looking for the laziest way of doing it (as usual, lol).

Change your Reply To Thread box from HTML WYSIWYG to plain text. You can toggle it by clicking the http://www.cableforum.co.uk/board/im...switchmode.gif button in the top right.


All times are GMT +1. The time now is 05:36.

Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2025, vBulletin Solutions Inc.
All Posts and Content are © Cable Forum