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)

Raistlin 12-08-2009 18:22

Programming Challenges?
 
Afternoon All,

I could do with getting some programming practice, and (whilst I'm at it) gaining at least a passing familiarity with a few different programming languages.

I know that there are a few sites out there that have daily/weekly/monthly programming challenges, but are there any that you would recommend?

Also, anybody got any thoughts on some little programming type tasks that might give me a little practice?

Damien 12-08-2009 18:35

Re: Programming Challenges?
 
What language?

I'll start with an easy one. (Don't look it up online ;))

Program something that will print to console/throw an alert for every multiple of 5 and 3 between 1 and 100. For numbers that are both multiples of 3 and 5 do something special. It's a common test.

Raistlin 12-08-2009 18:37

Re: Programming Challenges?
 
Any language really, doesn't matter.

Will have a go at your challenge tomorrow at work, thanks for that :tu:

Damien 12-08-2009 18:41

Re: Programming Challenges?
 
I gonna try to do it in C# later in the shortest/most elegant way I can. I'll wack it here in spoiler tags.

Raistlin 12-08-2009 18:46

Re: Programming Challenges?
 
Cool, thanks.

I'll probably start with Python or something like that.

Damien 13-08-2009 21:00

Re: Programming Challenges?
 
Spoiler: 

for (Int32 i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
Console.WriteLine(i + " is a multiple of both 3 AND 5!");
if (i % 3 == 0)
Console.WriteLine(i + " is a multiple of 3");
if (i % 5 == 0)
Console.WriteLine(i + " is a multiple of 5");

}

haydnwalker 13-08-2009 21:13

Re: Programming Challenges?
 
You could try PERL, C-sharp (just noticed my Mac doesn't have a hash key :() or JAVA as they seem to be popular languages lately.

punky 13-08-2009 21:13

Re: Programming Challenges?
 
I did more or less the same. Just one suggestion i'd make regarding your code Damien:

Spoiler: 
I'd use else ifs instead of ifs otherwise you'd get unnecessary repitition.

for (Int32 i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
Console.WriteLine(i + " is a multiple of both 3 AND 5!");
else if (i % 3 == 0)
Console.WriteLine(i + " is a multiple of 3");
else if (i % 5 == 0)
Console.WriteLine(i + " is a multiple of 5");

}

i.e you get:

12 is a multiple of 3
15 is a multiple of both 3 AND 5!
18 is a multiple of 3

instead of this:

12 is a multiple of 3
15 is a multiple of both 3 AND 5!
15 is a multiple of 3
15 is a multiple of 5
18 is a multiple of 3

Ben B 13-08-2009 21:19

Re: Programming Challenges?
 
Quote:

Originally Posted by haydnwalker (Post 34853484)
(just noticed my Mac doesn't have a hash key :()

Alt + 3 ;)

punky 13-08-2009 21:27

Re: Programming Challenges?
 
BTW the absolute classic programming challenge is to generate an array of random numbers and then sort it manually. Once you do it, then you can refine it to make it as efficient as possible.

I guarantee every programming course has that exercise.

Damien 13-08-2009 21:29

Re: Programming Challenges?
 
Quote:

Originally Posted by punky (Post 34853485)
I did more or less the same. Just one suggestion i'd make regarding your code Damien:

Spoiler: 
I'd use else ifs instead of ifs otherwise you'd get unnecessary repitition.

for (Int32 i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
Console.WriteLine(i + " is a multiple of both 3 AND 5!");
else if (i % 3 == 0)
Console.WriteLine(i + " is a multiple of 3");
else if (i % 5 == 0)
Console.WriteLine(i + " is a multiple of 5");

}

i.e you get:

12 is a multiple of 3
15 is a multiple of both 3 AND 5!
18 is a multiple of 3

instead of this:

12 is a multiple of 3
15 is a multiple of both 3 AND 5!
15 is a multiple of 3
15 is a multiple of 5
18 is a multiple of 3

Opps! Miss that. Indeed.

---------- Post added at 21:29 ---------- Previous post was at 21:28 ----------

Quote:

Originally Posted by punky (Post 34853497)
BTW the absolute classic programming challenge is to generate an array of random numbers and then sort it manually. Once you do it, then you can refine it to make it as efficient as possible.

I guarantee every programming course has that exercise.

Let's do that one next then. An array of 10 random numbers should be fine...

I'll try tomorrow.

haydnwalker 14-08-2009 09:13

Re: Programming Challenges?
 
Quote:

Originally Posted by Ben B (Post 34853490)
Alt + 3 ;)

Thanks for that!! Will be much use in the coming Mac usage years :D

LemonyBrainAid 14-08-2009 10:06

Re: Programming Challenges?
 
Quote:

Originally Posted by punky (Post 34853485)
I did more or less the same. Just one suggestion i'd make regarding your code Damien:

Spoiler: 
I'd use else ifs instead of ifs otherwise you'd get unnecessary repitition.

for (Int32 i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
Console.WriteLine(i + " is a multiple of both 3 AND 5!");
else if (i % 3 == 0)
Console.WriteLine(i + " is a multiple of 3");
else if (i % 5 == 0)
Console.WriteLine(i + " is a multiple of 5");

}

i.e you get:

12 is a multiple of 3
15 is a multiple of both 3 AND 5!
18 is a multiple of 3

instead of this:

12 is a multiple of 3
15 is a multiple of both 3 AND 5!
15 is a multiple of 3
15 is a multiple of 5
18 is a multiple of 3

I'll just point out a few things:

Int32 is actually the structure that contains "int" - so you can just as easily use 'int' or actually use an implicitly typed local variable - 'var' as it will actually pick up that your variable type is an integer.
Int32 is generally used to parse or switch another variable type into the integer type (Int32.Parse) or set the maximum or minimum value of a specified integer.

Good job with the if statements though - I like how you ignored the curly braces as they're not necessary when you only have the one line of code being executed.

However - your code will simply run through and then close when it's finished calculating all of the multiples, what you may want to do is stick
Code:

Console.ReadKey(true);
after your for loop - this will then only exit on keypress.

---------- Post added at 10:06 ---------- Previous post was at 09:54 ----------

Quote:

Originally Posted by Damien (Post 34853499)
Opps! Miss that. Indeed.

---------- Post added at 21:29 ---------- Previous post was at 21:28 ----------



Let's do that one next then. An array of 10 random numbers should be fine...

I'll try tomorrow.


For this, you can just use, in C#:
Code:

Array.Sort(yourArray);
but... that's cheating!

Seeing as you're only using 10 random numbers, I suggest you actually create your own code for a bubble sort algorithm - http://en.wikipedia.org/wiki/Bubble_sort

Damien 14-08-2009 10:24

Re: Programming Challenges?
 
Quote:

Originally Posted by LemonyBrainAid (Post 34853736)
Int32 is actually the structure that contains "int" - so you can just as easily use 'int' or actually use an implicitly typed local variable - 'var' as it will actually pick up that your variable type is an integer.

I prefer using Int32 because I prefer the highlighting in Visual Studio for it ;). As for var, there is little point in this case because I know the type of the variable, for the sake of clear code it is easier to explicitly declare it. Anyone reading the code will be very clear on what data type this is. (Also, Not everyone uses C# 3.5, which introduced Implicitly typed variables)

Quote:

However - your code will simply run through and then close when it's finished calculating all of the multiples, what you may want to do is stick
Code:

Console.ReadKey(true);
after your for loop - this will then only exit on keypress.
My example was writing to a String Builder which had a debug at the end. I changed it to console at the end. Probably should have added that.

danielf 14-08-2009 10:40

Re: Programming Challenges?
 
Quote:

Originally Posted by LemonyBrainAid (Post 34853736)

Seeing as you're only using 10 random numbers, I suggest you actually create your own code for a bubble sort algorithm - http://en.wikipedia.org/wiki/Bubble_sort

For large Ns, try quicksort.

Spoiler: 

(defun quick-sort (a-list)
(let ((pivot nil)
(lesser nil)
(greater nil))
(when a-list
(cond ((= (length a-list) 1)
(list (first a-list)))
(t
(setf pivot (first a-list))
(dolist (item (rest a-list))
(if (<= item pivot)
(push item lesser)
(push item greater)))
(append (quick-sort lesser) (list pivot) (quick-sort greater))
)))))


http://en.wikipedia.org/wiki/Quicksort

LemonyBrainAid 14-08-2009 10:46

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34853752)
I prefer using Int32 because I prefer the highlighting in Visual Studio for it ;). As for var, there is little point in this case because I know the type of the variable, for the sake of clear code it is easier to explicitly declare it. Anyone reading the code will be very clear on what data type this is. (Also, Not everyone uses C# 3.5, which introduced Implicitly typed variables)

At the end of the day, it's your code, your choice, this is just how I've been taught by SAMS, Microsoft and tutorials across the web ;)

The main advantage of using var is that unlike VB, it doesn't mean 'Variant' - CSC actually determines the most appropriate type for it based on your code - meaning less error margin. (i.e. say I used an integer then later in the code parsed values of over 2,147,483,648, it would auto assign it to be a double)

And I think you're getting your version numbers mixed, .NET 3.0 introduced C# 3.0 and .NET 3.5 is the most current version.

Quote:

Originally Posted by Damien (Post 34853752)
My example was writing to a String Builder which had a debug at the end. I changed it to console at the end. Probably should have added that.

That's fair enough :)

---------- Post added at 10:46 ---------- Previous post was at 10:44 ----------

Quote:

Originally Posted by danielf (Post 34853756)
For large Ns, try quicksort.

Spoiler: 

(defun quick-sort (a-list)
(let ((pivot nil)
(lesser nil)
(greater nil))
(when a-list
(cond ((= (length a-list) 1)
(list (first a-list)))
(t
(setf pivot (first a-list))
(dolist (item (rest a-list))
(if (<= item pivot)
(push item lesser)
(push item greater)))
(append (quick-sort lesser) (list pivot) (quick-sort greater))
)))))


http://en.wikipedia.org/wiki/Quicksort

Yeah - I chose Bubble Sort because from the basic programming challenges that were requested it's one of the simplest algorithms to use. By far not the fastest, but simple and easy to understand.

Damien 14-08-2009 10:48

Re: Programming Challenges?
 
Quote:

And I think you're getting your version numbers mixed, .NET 3.0 introduced C# 3.0 and .NET 3.5 is the most current version.
Yeah Sorry. C# 3.0. Either way, The latest release.

punky 14-08-2009 10:51

Re: Programming Challenges?
 
Quote:

Originally Posted by LemonyBrainAid (Post 34853736)
Seeing as you're only using 10 random numbers, I suggest you actually create your own code for a bubble sort algorithm - http://en.wikipedia.org/wiki/Bubble_sort

I remember doing a bubble sort at university. Its very inefficient. The way I did it at university (and last night) was on usually about twice as efficient. I did it both ways for fun last night anyway. I'll post both later if people want.

Quote:

Originally Posted by heero_yuy (Post 34853747)
Try coding the divisibility test without using the "%" operator.

Excellent idea for test #3. :tu:

BTW remember my post on this before: http://www.cableforum.co.uk/board/34528914-post11.html

Damien 14-08-2009 10:54

Re: Programming Challenges?
 
Quote:

I remember doing a bubble sort at university. Its very inefficient. The way I did it at university (and last night) was on usually about twice as efficient. I did it both ways for fun last night anyway. I'll post both later if people want.
We should probably decide on the size of the array and measure the performance for each different implementation.

Raistlin 14-08-2009 11:02

Re: Programming Challenges?
 
Keep these coming guys, they're really helping my enthusiasm :)

Have to confess that I'm starting small and just going through the basics with some course materials that I've got to get myself back up to speed - I haven't even tried the challenges that you're posting above :)

I'm tempted to suggest a monthly coding challenge, but I'm not sure how we would judge who the winner was (there are so many 'correct' answers to these sorts of things.....answers on a postcard please :)

Damien 14-08-2009 11:05

Re: Programming Challenges?
 
Quote:

Originally Posted by Rob M (Post 34853767)
I'm tempted to suggest a monthly coding challenge, but I'm not sure how we would judge who the winner was (there are so many 'correct' answers to these sorts of things.....answers on a postcard please :)

Could either have a vote, or simply just get feedback from other people.

I mean the following requirements are all important:

  • Readability (Can I understand it?)
  • Performance (How quick is it compared to other implementations?)
  • Elegance (Is it frakking Cool?)
  • Do they Support Spurs (Automatic Point Deduction)

punky 14-08-2009 11:13

Re: Programming Challenges?
 
As I have my code I might as well post it now. I've not beautified or robustified it yet:

Creating the initial random array:

Spoiler: 
Code:

           
            int[] unsorted = new int[10];
            Random random = new Random();

            for (int i = 0; i < 10; i++)
            {
                unsorted[i] = random.Next(0, 10);
            }



The way I did it at university and how it initially last night:

Spoiler: 
Code:

            int[] sorted = new int[10];
            int temp = 99;
            int loc = 0;


            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    if (unsorted[j] < temp)
                    {
                        temp = unsorted[j];
                        loc = j;
                    }
                }
                sorted[i] = temp;
                unsorted[loc] = 99;
                temp = 99;
            }



And my bubble sort:

Spoiler: 
Code:

            int[] sorted = (int[])unsorted.Clone();
            Boolean swapped;
            int temp = 0;
            int i = 0;

            do
            {
                swapped = false;
                i = 0;
                while (!swapped && i < 10 - 1)
                {

                    if (sorted[i] > sorted[i + 1])
                    {
                        temp = sorted[i];
                        sorted[i] = sorted[i + 1];
                        sorted[i + 1] = temp;
                        swapped = true;
                    }
                    else
                    {
                        i++;
                    }
                }

            } while (swapped);



---------- Post added at 11:13 ---------- Previous post was at 11:08 ----------

Quote:

Originally Posted by Damien (Post 34853768)
Could either have a vote, or simply just get feedback from other people.

I mean the following requirements are all important:

  • Readability (Can I understand it?)
  • Performance (How quick is it compared to other implementations?)
  • Elegance (Is it frakking Cool?)

That's decent criteria. We could also get an experienced developer to act as a judge but maybe rotate the position so everyone gets a go.

LemonyBrainAid 14-08-2009 11:15

Re: Programming Challenges?
 
Quote:

Originally Posted by Rob M (Post 34853767)
Keep these coming guys, they're really helping my enthusiasm :)

Have to confess that I'm starting small and just going through the basics with some course materials that I've got to get myself back up to speed - I haven't even tried the challenges that you're posting above :)

I'm tempted to suggest a monthly coding challenge, but I'm not sure how we would judge who the winner was (there are so many 'correct' answers to these sorts of things.....answers on a postcard please :)

This sounds like a great idea and I like the ideas that Damien outlined, here are a few other suggestions:

  1. Some people think code is the best if it can get the job done in the least amount of lines - this isn't always the case, so that's not a great one.
  2. Elegance is one I really like - if it's a new piece of code - using cutting edge technology such as LINQ in C# - then that's great and should be given more marks. Other examples: Boo, Spark, etc
  3. Voting would be a good idea - Perhaps having a programming challenge and then also giving the permission to expand on some previous code or develop new, intuitive ideas for it.
  4. Perhaps having a beginner, intermediate and advanced classes for the challenge would be a good one? :)
Seems like we actually have a nice number of developers on CF, this could turn out quite nicely!

danielf 14-08-2009 11:23

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34853768)
Could either have a vote, or simply just get feedback from other people.

I mean the following requirements are all important:

  • Readability (Can I understand it?)
  • Performance (How quick is it compared to other implementations?)
  • Elegance (Is it frakking Cool?)
  • Do they Support Spurs (Automatic Point Deduction)

Those are decent criteria, but the problem with the first one is that we may not all be using the same language (My quick-sort was in LISP; I don't do C). The second is best judged by runnning the different implementations on one machine, which again might cause compatibility issues. Three is cool. Four: what's Spurs?

Raistlin 14-08-2009 11:25

Re: Programming Challenges?
 
Ok, this thread appears to be deviating somewhat from my original intention, but that's cool as I think it's moving in an interesting direction.

With regards to the 'judging' how about if it were up to the person that set the task for that month to decide on the winner? Obviously they wouldn't be able to take part in their own task, but that's not always a bad thing..... A poll would be another good option, peer review is always a good way of telling how well you're doing. Given that a poll can be added to a thread at any time this could be added after a specified time has passed and then people just vote on the submissions (also saves cluttering everything up with loads of threads). Once the voting's over and the winners announced we could then allow alternative solutions, or discussions of the solutions that have been posted.

On that note, how would the submissions be handled? If they were posted up as people put them in using the [spoiler][/spoiler] tags then other people could potentially copy the entries.

Also, there's the issue of people submitting stuff that isn't actually their work.

I like the idea of multiple classes (might give me a chance of winning something :LOL:), but fear it could be complicated to organise and judge.

LemonyBrainAid 14-08-2009 11:31

Re: Programming Challenges?
 
Quote:

Originally Posted by Rob M (Post 34853785)
Ok, this thread appears to be deviating somewhat from my original intention, but that's cool as I think it's moving in an interesting direction.

With regards to the 'judging' how about if it were up to the person that set the task for that month to decide on the winner? Obviously they wouldn't be able to take part in their own task, but that's not always a bad thing..... A poll would be another good option, peer review is always a good way of telling how well you're doing. Given that a poll can be added to a thread at any time this could be added after a specified time has passed and then people just vote on the submissions (also saves cluttering everything up with loads of threads). Once the voting's over and the winners announced we could then allow alternative solutions, or discussions of the solutions that have been posted.

On that note, how would the submissions be handled? If they were posted up as people put them in using the [spoiler][/spoiler] tags then other people could potentially copy the entries.

Also, there's the issue of people submitting stuff that isn't actually their work.

I like the idea of multiple classes (might give me a chance of winning something :LOL:), but fear it could be complicated to organise and judge.


Submissions could be PM'd to the judge or a neutral member. Multiple classes wouldn't be too hard and we could simply have one experienced developer judge them all, or voting.

You're never going to get around the submitting other people's work, but you can however tell if they've entered a beginner contest, they aren't going to be able to push out the same standard as advanced, if we go with that idea.

Damien 14-08-2009 11:43

Re: Programming Challenges?
 
We should:

  • Instead of 3 levels just have two. Beginner and Advanced. The Same Judge for both?
  • Guest Judges who set and judge the competition. A Judge must provide feedback on their decision process. A Calendar Month to do the code, 10 days for judging while the next judge starts the next one.
Maybe:
  • Contest will be to create something practical? A combination of elements rather than a quick puzzle? Mostly because programming is a combination of skills in which a quick puzzle is but one.

punky 14-08-2009 12:14

Re: Programming Challenges?
 
TBH this competition thing should only be a bit of fun away. I'd only be interested in doing it casually, if it gets too regimented then it might not be worth it. We can't turn this into Google's Summer Of Code or something.

Damien 14-08-2009 12:21

Re: Programming Challenges?
 
Quote:

Originally Posted by punky (Post 34853808)
TBH this competition thing should only be a bit of fun away. I'd only be interested in doing it casually, if it gets too regimented then it might not be worth it. We can't turn this into Google's Summer Of Code or something.

Well a Judge sets the two competitions and judges them. It will be akin to the Photo contents.

punky 14-08-2009 16:02

Re: Programming Challenges?
 
I've had a bash at the modulus one:

Spoiler: 

Code:

        static void Main(string[] args)
        {
            for (int i = 1; i <= 100; i++)
            {
                if (Modulus(i, 3) == 0 && Modulus(i, 5) == 0)
                    Console.WriteLine(i + " is a multiple of both 3 AND 5!");
                else if (Modulus(i, 3) == 0)
                    Console.WriteLine(i + " is a multiple of 3");
                else if (Modulus(i, 5) == 0)
                    Console.WriteLine(i + " is a multiple of 5");
                else
                    Console.WriteLine(i + " is not a multiple of 3 (remainder " + Modulus(i, 3) + ") or a multiple of 5 (remainder " + Modulus(i, 5) + ")");
            }


            Console.In.ReadLine();
        }

        public static int Modulus(int num, int divisor)
        {
            while (num > divisor)
            {
                num -= divisor;
            }

            if (num == divisor)
                num = 0;

            return num;
        }

Which produces:

1 is not a multiple of 3 (remainder 1) or a multiple of 5 (remainder 1)
2 is not a multiple of 3 (remainder 2) or a multiple of 5 (remainder 2)
3 is a multiple of 3
4 is not a multiple of 3 (remainder 1) or a multiple of 5 (remainder 4)
5 is a multiple of 5
6 is a multiple of 3
7 is not a multiple of 3 (remainder 1) or a multiple of 5 (remainder 2)
8 is not a multiple of 3 (remainder 2) or a multiple of 5 (remainder 3)
9 is a multiple of 3
10 is a multiple of 5
11 is not a multiple of 3 (remainder 2) or a multiple of 5 (remainder 1)
12 is a multiple of 3
13 is not a multiple of 3 (remainder 1) or a multiple of 5 (remainder 3)
14 is not a multiple of 3 (remainder 2) or a multiple of 5 (remainder 4)
15 is a multiple of both 3 AND 5!
...


Speaking of operators, in some OO (Object-Orrientated) languages like C# and Java you can actually overload operators (re-code them to do some different). I had to do this in university once - write a Matrix class (a matrix is like a grid/table of values) including defining the + - * / operations for them.

So there's another good educational challenge if someone wants. Don't complain, you're getting a programming degree for free in thread :p:

danielf 14-08-2009 22:46

Re: Programming Challenges?
 
Here's an interesting one, well I think it's interesting if only from a counter-intuitive statistical perspective.

The 'Monty Hall problem'.

Today's challenge (if you're interested) is to implement the conditions: there's a Ferrari hidden randomly behind one of 3 doors, and a goat behind the other two. You want the Ferrari. You choose one door, and the host then eliminates one of the goats (the host knows where the Ferrari is). So now there's two choices left. The statistical conundrum is: should you stick with your choice or change to the other door? Which one has the best odds?

Run the program in both conditions (switch/no switch) for a decent number of trials, and record the probabilities of getting the car.

You'll be surprised.

BTW: I've done this one before, and it really is quite simple. My code is about 30 lines, but a third of that is variable declaration and printing. It prints "Hello World" as well... :)

webcrawler2050 14-08-2009 22:48

Re: Programming Challenges?
 
Quote:

Originally Posted by Rob M (Post 34852615)
Afternoon All,

I could do with getting some programming practice, and (whilst I'm at it) gaining at least a passing familiarity with a few different programming languages.

I know that there are a few sites out there that have daily/weekly/monthly programming challenges, but are there any that you would recommend?

Also, anybody got any thoughts on some little programming type tasks that might give me a little practice?

If you want a real language to learn and be challenge - PEARL

Hugh 14-08-2009 22:57

Re: Programming Challenges?
 
When I were't lad.........

My first programming language in 1980 was IBM Mainframe Assembler, with 2, 4, and 6 byte instructions, and if you weren't careful, you could overwrite the instruction, which would result in "interesting" outputs (and the code was input in punch cards.....).

Mr_love_monkey 15-08-2009 06:39

Re: Programming Challenges?
 
Quote:

Originally Posted by foreverwar (Post 34854338)
When I were't lad.........

My first programming language in 1980 was IBM Mainframe Assembler, with 2, 4, and 6 byte instructions, and if you weren't careful, you could overwrite the instruction, which would result in "interesting" outputs (and the code was input in punch cards.....).

Wow - they had computers back then????? :)

---------- Post added at 06:39 ---------- Previous post was at 06:37 ----------

Quote:

Originally Posted by webcrawler2050 (Post 34854321)
If you want a real language to learn and be challenge - PEARL

Is that anything like Perl then? :angel:

I like perl, it's useful for writing code that looks like characters from comics when they swear.

Fred_Smith 15-08-2009 07:39

Re: Programming Challenges?
 
Well when I started in the 1980's I was writing code on ICL Mainframes using COBOL. Can't beat that language.....

Mr_love_monkey 15-08-2009 08:28

Re: Programming Challenges?
 
My java version of the 3&5 divisor in one line (ignoring all the usual boilerplate java
Spoiler: 

for (int i=0;i<=100;System.out.print(++i%3 == 0 && i%5 ==0 ? (i+" is a multiple of 3 and 5\n") : i%5 == 0 ? (i+" is a multiple of 5\n") : i%3 == 0 ? (i+" is a multiple of 3\n") : ""));

Hugh 15-08-2009 09:39

Re: Programming Challenges?
 
Quote:

Originally Posted by Fred_Smith (Post 34854433)
Well when I started in the 1980's I was writing code on ICL Mainframes using COBOL. Can't beat that language.....

Unless you used RPG2 - we had a in-house competition, writing a number of programmes in Cobol and RPG2; we could usually write the RPG2 programmes (from the same spec, using programmers with the same experience in both languages) in about a quarter to a fifth of the time. ;)

Raistlin 15-08-2009 09:56

Re: Programming Challenges?
 
Quote:

Originally Posted by danielf (Post 34854319)
The statistical conundrum is: should you stick with your choice or change to the other door? Which one has the best odds?



I can answer that question if it will help anybody with the code? :D

Damien 15-08-2009 11:12

Re: Programming Challenges?
 
Quote:

Originally Posted by Mr_love_monkey (Post 34854436)
My java version of the 3&5 divisor in one line (ignoring all the usual boilerplate java
Spoiler: 

for (int i=0;i<=100;System.out.print(++i%3 == 0 && i%5 ==0 ? (i+" is a multiple of 3 and 5\n") : i%5 == 0 ? (i+" is a multiple of 5\n") : i%3 == 0 ? (i+" is a multiple of 3\n") : ""));

Nice use of the conditional operator.

I should really do the sorting challenge and the Monty Hall Problem one. (P.S It's a pretty famous one, you always change). If you program all week it's tiring :P

Paddy1 15-08-2009 12:51

Re: Programming Challenges?
 
Apologies for the lack of indentation but I couldn't get it to look right. Anyway, here's my effort -

Spoiler: 

import java.util.Random;

public class MontyHall {

private enum Door { CAR, GOAT }

public static void main(String[] args) {

int switchWins = 0;
int iterations = 100000;


for (int i=1;i<=iterations;i++) {
if (doMontyHall())
switchWins++;
}

System.out.println("Switch wins = " + switchWins +
", No Switch wins = " + (iterations - switchWins) +
", Percentage wins from switching = " + ((float)(switchWins * 100) / iterations));


}

public static boolean doMontyHall() {
Door[] doors = new Door[3];
doors[0] = Door.GOAT;
doors[1] = Door.GOAT;
doors[2] = Door.GOAT;

Random r = new Random();
int carPosition = r.nextInt(3);
doors[carPosition] = Door.CAR;

int contestantSelection = r.nextInt(3);
boolean switchToWin = false;

if (doors[contestantSelection] == Door.GOAT)
switchToWin = true;

// This next step is not at all necessary to establish whether or not switching is beneficial
// and illustrates the point that once a door has been selected, the problem becomes a
// simple issue of only picking the correct door 1/3 times and the whole Host opening
// a door and asking is actually just a charade that serves to confuse people into thinking
// they now have a 50/50 chance of picking the correct door, which, of course they do, but
// 2/3 is always better than 50/50.

int hostSelection = r.nextInt(3);
while (hostSelection == contestantSelection || doors[hostSelection] == Door.CAR)
hostSelection = r.nextInt(3);

System.out.println("Contestant picked door " + contestantSelection +
", Host opened door " + hostSelection +
", Car was in door " + carPosition + ", Switch to win = " + switchToWin);

return switchToWin;

}
}


LemonyBrainAid 15-08-2009 12:57

Re: Programming Challenges?
 
Quote:

Originally Posted by webcrawler2050 (Post 34854321)
If you want a real language to learn and be challenge - PEARL

Hmmm... Is that based on your experience with your hosting websites? ;)

Quote:

Originally Posted by Fred_Smith (Post 34854433)
Well when I started in the 1980's I was writing code on ICL Mainframes using COBOL. Can't beat that language.....

I think it's down at the moment, but here's a pretty funny article on COBOL: http://www.codinghorror.com/blog/archives/001294.html

Jon T 15-08-2009 13:01

Re: Programming Challenges?
 
Quick and dirty 3 and 5 divisibility test in vbscript

Spoiler: 
Code:

Option Explicit

Dim intCount,intDividedBy3,intDividedBy5,strDecPoint

    For intCount=1 To 100
    intDividedBy3=intCount/3
    intDividedBy5=intCount/5
    strDecPoint="."

        If InStr(intDividedBy3,strDecPoint)=0 And InStr(intDividedBy5,strDecPoint)=0 Then
            WScript.Echo  intCount & " is divisible by 3 and 5"
                ElseIf InStr(intDividedBy3,strDecPoint)=0 Then WScript.Echo  intCount & " is divisible by 3"
                    ElseIf InStr(intDividedBy5,strDecPoint)=0 Then WScript.Echo  IntCount & " is divisible by 5"
                        End If

    Next
   
    Set intCount=Nothing
    Set intDividedBy3=Nothing
    Set intDividedBy5=Nothing
    Set strDecPoint=Nothing
   
WScript.Quit


Reedy 15-08-2009 13:08

Re: Programming Challenges?
 
Excel vba.

Spoiler: 
Code:

Sub test()

Cells(1, 1).Select

For i = 1 To 100

three = i / 3
five = i / 5

If (three - Int(three)) = 0 And (five - Int(five)) = 0 Then
    ActiveCell.Value = "div by 3 and 5 - " & i
    ActiveCell.Offset(1, 0).Select
ElseIf (three - Int(three)) = 0 Then
    ActiveCell.Value = "div by 3 - " & i
    ActiveCell.Offset(1, 0).Select
ElseIf (five - Int(five)) = 0 Then
    ActiveCell.Value = "div by 5 - " & i
    ActiveCell.Offset(1, 0).Select
End If

Next i

Cells(1, 1).Select

End Sub


Raistlin 15-08-2009 13:45

Re: Programming Challenges?
 
I've added spoiler tags to the last two just to maintain the convention and so as not to spoil the fun for anybody else that's playing along :)

Reedy 15-08-2009 14:34

Re: Programming Challenges?
 
Cool ... I didn't know how to do them! :)

Damien 15-08-2009 14:47

Re: Programming Challenges?
 
Quote:

Originally Posted by LemonyBrainAid (Post 34854558)
Hmmm... Is that based on your experience with your hosting websites? ;)



I think it's down at the moment, but here's a pretty funny article on COBOL: http://www.codinghorror.com/blog/archives/001294.html

Jeff Atwood is a very good blogger! His latest podcast about COBOL was quite funny.

Raistlin 15-08-2009 15:18

Re: Programming Challenges?
 
Quote:

Originally Posted by Reedy (Post 34854589)
Cool ... I didn't know how to do them! :)

No worries, for reference you just add [spoiler] and [/spoiler] tags around everything you want to put in the spoiler :)

Damien 16-08-2009 09:16

Re: Programming Challenges?
 
Monty Hall Problem:

Spoiler: 

Code:

class Program
    {
        const string CAR = "CAR";
        const string GOAT = "GOAT";

        static void Main(string[] args)
        {
            Random random = new Random();
            Double DidntChangeSuccessRate = 0;
            Double DidChangeSuccessRate = 0;
            Int32 doorToOpen;
            IList<String> doors = new List<String>()
            {
                    GOAT, GOAT, GOAT
            };

            for (Int32 round = 1; round <= 10000; round++)
            {

                doors[random.Next(0, 3)] = CAR;
                doorToOpen = random.Next(3); //Choose a Door
               
                if (round % 2 == 0) //Is Even
                {
                  doors.Remove(GOAT);
                    if (doors[random.Next(2)] == CAR) //Did they get the car
                        DidChangeSuccessRate++;
                    doors.Add(GOAT);
                }
                else
                {
                    if (doors[doorToOpen] == CAR) //Don't change, did they get the car.
                        DidntChangeSuccessRate++;
                }
             
                doors[doors.IndexOf(CAR)] = GOAT; //Reset car door to goat. Faster than creating new list class each time
            }

            Console.WriteLine(String.Format("Didn't Change: {0}%", (DidntChangeSuccessRate / 5000) * 100));
            Console.WriteLine(String.Format("Did Change: {0}%", (DidChangeSuccessRate / 5000) * 100));
            Console.ReadKey(true);
        }

    }


nffc 16-08-2009 19:14

Re: Programming Challenges?
 
Quote:

Originally Posted by LemonyBrainAid (Post 34853736)
Good job with the if statements though - I like how you ignored the curly braces as they're not necessary when you only have the one line of code being executed.

personally, i wouldnt recommend leaving the {}s out even for a single line. It can cause issues if someone decides to add other lines, and with nested if statements. Most tutorials I've read also recommend always using them.

Damien 16-08-2009 19:17

Re: Programming Challenges?
 
Quote:

Originally Posted by nffc (Post 34855506)
personally, i wouldnt recommend leaving the {}s out even for a single line. It can cause issues if someone decides to add other lines, and with nested if statements. Most tutorials I've read also recommend always using them.


If someone wants to add lines they can easily add them. It's just personal choice. Neither is better than the other.

Raistlin 16-08-2009 20:21

Re: Programming Challenges?
 
Doesn't anybody comment their code any more :erm: :D :D

Damien 16-08-2009 20:28

Re: Programming Challenges?
 
Quote:

Originally Posted by Rob M (Post 34855555)
Doesn't anybody comment their code any more :erm: :D :D

Then the Terrorists win. Do you want the terrorists to win Rob?

Fobic 16-08-2009 20:39

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34855113)
Monty Hall Problem:

Interesting code: made me think .... always a good thing.
Liked your shortcut for resetting the list.

However, i dont think the code works the way it should for the case when the contestant changes their choice.

Quote:

Originally Posted by Damien (Post 34855113)
Code:

                {
                  doors.Remove(GOAT);
                    if (doors[random.Next(2)] == CAR) //Did they get the car
                        DidChangeSuccessRate++;
                    doors.Add(GOAT);
                }


You seem to be removing the first door you come across with a Goat behind it (which may even be the contestant's chosen door) and then choosing at random from the 2 remaining doors, rather than swapping to the unchosen door.

I suspect this will give results of 33% and 50% in your output which is not the correct answer.

nffc 16-08-2009 20:45

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34855510)
If someone wants to add lines they can easily add them. It's just personal choice. Neither is better than the other.

Well, I can't see the extra 2 characters making much difference performance wise but heh, it was just something I have always seen recommended as good practice.
Quote:

Originally Posted by Rob M (Post 34855555)
Doesn't anybody comment their code any more :erm: :D :D

I usually do... Makes it easier for me to read back if nothing else. :D

Damien 16-08-2009 21:39

Re: Programming Challenges?
 
Quote:

Originally Posted by Fobic (Post 34855564)
Interesting code: made me think .... always a good thing.
Liked your shortcut for resetting the list.

However, i dont think the code works the way it should for the case when the contestant changes their choice.



You seem to be removing the first door you come across with a Goat behind it (which may even be the contestant's chosen door) and then choosing at random from the 2 remaining doors, rather than swapping to the unchosen door.

I suspect this will give results of 33% and 50% in your output which is not the correct answer.

I think 33% and 50% are the correct answers. If they choose to change they have a 50% chance of winning the car

Wait just figured it out. Tis Wrong.

---------- Post added at 21:39 ---------- Previous post was at 21:00 ----------

The CORRECT Answer:

Spoiler: 
Code:

class Program
    {
        const string CAR = "CAR";
        const string GOAT = "GOAT";

        static void Main(string[] args)
        {
            Random random = new Random();
            Double DidntChangeSuccessRate = 0;
            Double DidChangeSuccessRate = 0;
            Int32 doorToOpen;
            Int32 IndexOfCar;
            Int32 doorForHostToOpen;

            IList<String> doors = new List<String>()
            {
                    GOAT, GOAT, GOAT
            };

            for (Int32 round = 1; round <= 10000; round++)
            {

                doors[random.Next(0, 3)] = CAR; //Randomly assign a car door (thus killing a goat. Happy Times)
                IndexOfCar = doors.IndexOf(CAR); //The Host needs to know which is the car door
                doorToOpen = random.Next(3); //Choose a Door
                doorForHostToOpen = random.Next(3); //Host Chooses door to open

              //Now a door has been chosen Noel 'I believe in rubbish' Edmonds needs to remove a door
                //Choose the one that is not a car and not one the user has chosen.
                while (doorForHostToOpen == IndexOfCar || doorForHostToOpen == doorToOpen)
                    doorForHostToOpen = random.Next(3);


                if (round % 2 == 0) //Is Even do a switch, otherwise do a didn't switch
                {
                    //Switch door. So choose the door that hasn't been opened and was not the
                    //previously chosen one.
                    Int32 SwitchedDoor = random.Next(3);
                    while (SwitchedDoor == doorForHostToOpen || SwitchedDoor == doorToOpen)
                        SwitchedDoor = random.Next(3);

                    if (doors[SwitchedDoor] == CAR) //Did they get the car
                        DidChangeSuccessRate++;

                }
                else
                {
                    if (doors[doorToOpen] == CAR) //Don't change, did they get the car.
                        DidntChangeSuccessRate++;
                }

                //Reset car door to goat. Faster than creating new list class each time
                doors[doors.IndexOf(CAR)] = GOAT;
            }

            Console.WriteLine(String.Format("Didn't Change: {0}%", (DidntChangeSuccessRate / 5000) * 100));
            Console.WriteLine(String.Format("Did Change: {0}%", (DidChangeSuccessRate / 5000) * 100));
            Console.ReadKey(true); //And so we end our magical story. The Code goes on.
        }



Didn't change: 33.5% chance of winning
Did Change: 66.78% chance of winning

Also got to remove the nasty loop adding/removing. Bonus points for spotting the Beatles reference.

Mr_love_monkey 16-08-2009 22:19

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34855510)
If someone wants to add lines they can easily add them. It's just personal choice. Neither is better than the other.

With java the sun coding standards say you should have the braces even if it's just one line.

Though that said they also say you should avoid the compound if statement because some programmers find it hard to understand - my opinion is if you can't understand it then you shouldn't be a programmer...

Damien 16-08-2009 22:27

Re: Programming Challenges?
 
Quote:

Originally Posted by Mr_love_monkey (Post 34855625)
With java the sun coding standards say you should have the braces even if it's just one line.

Though that said they also say you should avoid the compound if statement because some programmers find it hard to understand - my opinion is if you can't understand it then you shouldn't be a programmer...

I find it's a space thing, if it's one line it's just ugly.

Code:

if (ProductType == ProductType.Software)
{
    // do something

}
else
{
  //do something else
}

or

Code:

if (ProductType == ProductType.Software)
    // do something
 else
    //do something else

Anyhoo, The Monty Hall Problem was good. I think one like that a month would be good for a monthly challenge. Any word on that Rob?

nffc 16-08-2009 22:31

Re: Programming Challenges?
 
I tend to prefer

Code:

if (this == whatever) {
  do this;
}
else {
  meh2u2;
}

TCL is really anal about the positions of the brackets with the else - the } needs to be on the same line!

danielf 16-08-2009 23:22

Re: Programming Challenges?
 
Here's my Monty Hall. It's in LISP again, but nobody speaks LISP :(

Spoiler: 
(defun monty-hall (times)
(let ((change-hits 0)
(change-misses 0)
(no-change-hits 0)
(no-change-misses 0)
(n-change-trials 0)
(doors '(nil nil nil)))
(dotimes (n times)
(dotimes (x 3)
(setf (nth x doors) 0))
(setf (nth (random 3) doors) 1)
(let* ((choice (random 3))
(choice-set (remove choice '(0 1 2)))
(alternative nil)
(change-trial (random 2)))
(if (equal (nth choice doors) 1)
(setf alternative (nth (random 2) choice-set))
(progn
(if (equal (nth (first choice-set) doors) 0)
(setf alternative (second choice-set))
(setf alternative (first choice-set)))))
(if (equal change-trial 1)
(progn
(incf n-change-trials)
(if (equal (nth alternative doors) 1)
(incf change-hits)
(incf change-misses)))
(if (equal (nth choice doors) 1)
(incf no-change-hits)
(incf no-change-misses)))))
(format t "~% change-hits ~A ~A" change-hits (float (/ change-hits n-change-trials)))
(format t "~% no-change-hits ~A ~A" no-change-hits (float (/ no-change-hits (- times n-change-trials))))
))

Reedy 17-08-2009 00:39

Re: Programming Challenges?
 
What the hell is THAT language!!:confused:

Raistlin 17-08-2009 06:54

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34855632)
Any word on that Rob?

No word from me, but then I'm still waiting for the terrorists to win :D

Seriously though, still thinking about the format - gonna sit and take a look at it today :)

Mr_love_monkey 17-08-2009 07:27

Re: Programming Challenges?
 
Quote:

Originally Posted by danielf (Post 34855679)
Here's my Monty Hall. It's in LISP again, but nobody speaks LISP :(

Spoiler: 
(defun monty-hall (times)
(let ((change-hits 0)
(change-misses 0)
(no-change-hits 0)
(no-change-misses 0)
(n-change-trials 0)
(doors '(nil nil nil)))
(dotimes (n times)
(dotimes (x 3)
(setf (nth x doors) 0))
(setf (nth (random 3) doors) 1)
(let* ((choice (random 3))
(choice-set (remove choice '(0 1 2)))
(alternative nil)
(change-trial (random 2)))
(if (equal (nth choice doors) 1)
(setf alternative (nth (random 2) choice-set))
(progn
(if (equal (nth (first choice-set) doors) 0)
(setf alternative (second choice-set))
(setf alternative (first choice-set)))))
(if (equal change-trial 1)
(progn
(incf n-change-trials)
(if (equal (nth alternative doors) 1)
(incf change-hits)
(incf change-misses)))
(if (equal (nth choice doors) 1)
(incf no-change-hits)
(incf no-change-misses)))))
(format t "~% change-hits ~A ~A" change-hits (float (/ change-hits n-change-trials)))
(format t "~% no-change-hits ~A ~A" no-change-hits (float (/ no-change-hits (- times n-change-trials))))
))


ah..... lisp.....next thing we know we'll have code in Occam and Prolog

---------- Post added at 07:27 ---------- Previous post was at 07:25 ----------

Quote:

Originally Posted by Damien (Post 34855632)
I find it's a space thing, if it's one line it's just ugly.

Code:

if (ProductType == ProductType.Software)
{
    // do something

}
else
{
  //do something else
}

or

Code:

if (ProductType == ProductType.Software)
    // do something
 else
    //do something else



well, again, Sun coding standards say that you should do :

Code:


 if (true) {
  // something
} else {
  //something else
}

which is slightly less bulky..

Damien 17-08-2009 08:54

Re: Programming Challenges?
 
Quote:

Originally Posted by Mr_love_monkey (Post 34855787)

well, again, Sun coding standards say that you should do :

Code:


 if (true) {
  // something
} else {
  //something else
}

which is slightly less bulky..

I'm not scared of Sun :D Plus I program in C#

Mr_love_monkey 17-08-2009 12:07

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34855810)
I'm not scared of Sun :D Plus I program in C#

Yeah but C# is just a hacked version of java, so technically sun owns your ass :)

gazzae 17-08-2009 12:37

Re: Programming Challenges?
 
Probably better ways to do it.

Spoiler: 


Code:


BEGIN
DECLARE @i FLOAT --Counter
DECLARE @t FLOAT --Three
DECLARE @f FLOAT --Five
SET @i = 1

WHILE @i <= 100
BEGIN
SET @t = @i /3
SET @f = @i /5
IF CHARINDEX('.',@t) = 0 and CHARINDEX('.', @f) = 0
BEGIN
PRINT CAST(@i AS VARCHAR) + ' is a multiple of 3 and 5'
END
ELSE IF CHARPRINT('.',@t) = 0
BEGIN
PRINT CAST(@i AS VARCHAR) + ' is a multiple of 3'
END
ELSE IF CHARINDEX('.',@f) = 0
BEGIN
PRINT CAST(@i AS VARCHAR) + ' is a multiple of 5'
END
SET @i = @i + 1
END
END


nffc 17-08-2009 13:04

Re: Programming Challenges?
 
Quote:

Originally Posted by Mr_love_monkey (Post 34855894)
Yeah but C# is just a hacked version of java, so technically sun owns your ass :)

What about if he doesn't have a donkey?

Anyway, they're both essentially hacked versions of C...

Damien 17-08-2009 13:23

Re: Programming Challenges?
 
I think hacked is a unfair description..

Hugh 17-08-2009 13:31

Re: Programming Challenges?
 
Quote:

Originally Posted by Mr_love_monkey (Post 34855894)
Yeah but C# is just a hacked version of java, so technically sun owns your ass :)

I think you will find that Oracle owns Sun's burro (or very soon will), so you are now all Larry's beyatches....;)

LemonyBrainAid 17-08-2009 13:34

Re: Programming Challenges?
 
C#:

Spoiler: 
Code:

for (var i = 1; i < 100; i++)
{
    if (i % 3 && i % 5 == 0)
        Console.WriteLine(i + " is a multiple of both 3 and 5");
    if (i % 3 == 0)
        Console.WriteLine(i + " is a multiple of 3");
    if (i % 5 == 0)
        Console.WriteLine(i + " is a multiple of 5");
}



VB.NET:
Spoiler: 
Code:

Dim i As Integer

For i = 1 To 100
    If i Mod 3 AndAlso i Mod 5 = 0 Then
        Console.WriteLine(i + " is a multiple of both 3 and 5")
    End If
    If i Mod 3 = 0 Then
        Console.WriteLine(i + " is a multiple of both 3")
    End If
    If i Mod 5 = 0 Then
        Console.WriteLine(i + " is a multiple of both 3")
    End If
Next i



PHP:
Spoiler: 

PHP Code:

<?php
for ($i=1$i<100$i++)
  {
    if (
$i == 0)
    {
        if (
$i == 0)
        {
            echo(
$i." is a multiple of both 3 and 5<br />");
        }
        else
        {
            echo(
$i." is a multiple of 3<br />");
        }
    }
    if (
$i == 0)
    {
        if (
$i == 0)
        {
        echo(
$i." is a multiple of both 3 and 5<br />");
        }
        else
        {
        echo(
$i." is a multiple of 5<br />");
        }
    }
  }
?>


BASIC: (Not actually 100% this works, hah!)
Spoiler: 
Code:

10 FOR I$ = 1 TO 100
20 IF I$ % 3 AND I$ % 5 = 0 THEN GOTO 60
30 IF I$ % 3 = 0 THEN GOTO 70
40 IF I$ % 5 = 0 THEN GOTO 80
50 NEXT I$
60 PRINT I$ "is a multiple of both 3 and 5"
70 PRINT I$ "is a multiple of 3"
80 PRINT I$ "is a multiple of 5"
90 END


Damien 17-08-2009 14:00

Re: Programming Challenges?
 
We need another challenge, of the Monty Hall Type...

danielf 17-08-2009 14:06

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34855952)
We need another challenge, of the Monty Hall Type...

I've got another one. It's a mortgage calculator. Say you have a mortgage of £100,000. Specify an interest rate and monthly repayment amount. What you want to determine is the number of months required to pay off the balance, keeping in mind that you will accrue interest on the outstanding balance. My solution is 8 lines long. You can check your solution against the calculators floating around on the web.

Damien 17-08-2009 14:12

Re: Programming Challenges?
 
Quote:

Originally Posted by danielf (Post 34855955)
I've got another one. It's a mortgage calculator. Say you have a mortgage of £100,000. Specify an interest rate and monthly repayment amount. What you want to determine is the number of months required to pay off the balance, keeping in mind that you will accrue interest on the outstanding balance. My solution is 8 lines long. You can check your solution against the calculators floating around on the web.

Cool. I'll do that soonish. Is this flat rate interest or is this ongoing? So is the interest calculated by a percentage of the total amount? (i.e 10% of 100,000)?

punky 17-08-2009 18:13

Re: Programming Challenges?
 
BTW, Here's my attempt at the Monty Hall solution. I did via Object-Orientated programming, but its probably a bit more cumbersome than Damien's attempt. Still at least its good simple intro it using it as most of the important base principals are used. Its not pure OO though but thereabouts

Spoiler: 
Code:

namespace PCTestMontyHall
{

    //class to represent the door
    class Door
    {
        public int doorNumber;
        public Boolean open = false;
        public 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()
        {
            //conditional shorthand. If open is true then it sets "Open" to status. If not it sets "Closed" to status
            String status = open ? "Open" : "Closed";
            return "Door " + doorNumber + ": " + prize + " (" + status + ")";
        }
    }

    class Program
    {
        //create a random number generator
        public static Random random = new Random();

        static void Main(string[] args)
        {
            //set initial counters and parameters
            int ferraris = 0;
            int goats = 0;
            int gamesToPlay = 1000;
            bool contestantSwapping = false;

            //play the game
            for (int i = 0;i<gamesToPlay;i++)
            {
                //true parameter means contestant will swap, false means he doesn't.
                string result = PlayGame(contestantSwapping);

                if (result == "Ferrari")
                {
                    ferraris++;
                }
                else
                {
                    goats++;
                }
            }

            //print out statistics
            Console.WriteLine("Contestant swapping? " + contestantSwapping);
            float ferrariPercentage = ((float)ferraris / gamesToPlay) * 100;
            float goatPercentage = ((float)goats / gamesToPlay) * 100;
            Console.WriteLine(String.Format("\n\nFerraris: {0} {1}%\nGoats: {2} {3}%", ferraris, ferrariPercentage, goats, goatPercentage));
           
            //Hit enter to quit
            Console.ReadLine();


        }

        //the actual game
        static string PlayGame(Boolean swapChoice)
        {

            //create an array to hold the doors
            Door[] doors = new Door[3];

            //set contestant's choice of door randomly
            int contestantsChoice = random.Next(0, 3);

            //add door objects to the array of doors
            for (int i = 0;i < doors.Length; i++)
            {
                doors[i] = new Door(i+1,"Goat");
            }

            //choose which door a Ferrari should be behind
            int ferrari = random.Next(0, 3);
            doors[ferrari].prize = "Ferrari";

            //host has to remove a choice
            int removeChoice;
            //keep chosing a door at random until the door contains a goat and isn't the same as the contestants choice
            do
            {
                removeChoice = random.Next(0, 3);
            } while ((doors[removeChoice].prize == "Ferrari")|| (removeChoice == contestantsChoice));

            //"open" the door
            doors[removeChoice].open = true;

            //if contestant is swapping, then choose the other door with a goat
            int oldChoice = contestantsChoice;
            if (swapChoice)
            {

                do
                {
                    contestantsChoice = random.Next(0, 3);
                } while ((doors[contestantsChoice].open == true) || (contestantsChoice == oldChoice));


            }

            //return the prize as a result
            return doors[contestantsChoice].prize;

        }

        //print out the status of the doors. I added this as a debug whilst writing but illustrates overriding the default ToString method
        static void ShowDoors(Door[] doors)
        {
            Console.WriteLine("Doors:");
            for (int i = 0; i < doors.Length; i++)
            {
                Console.WriteLine(doors[i]);
            }
        }

    }
}

Result:

Contestant swapping? False


Ferraris: 330 33%
Goats: 670 67%

Contestant swapping? True


Ferraris: 671 67.1%
Goats: 329 32.9%


I'll have a go at the mortgage calculator tonight probably.

Damien 17-08-2009 19:40

Re: Programming Challenges?
 
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..

Druchii 17-08-2009 19:58

Re: Programming Challenges?
 
Got this so far, it appears to work...

Spoiler: 
Code:

//c++
#include <iostream>
using namespace std;

int main() {
float interest;
float mortgage=100000;
float repayment;
long i=1;
cout << "Please enter the interest rate in number format sans % mark.\n";
cin >> interest;
cout << "Ok, Interest rate is set to " << interest << "% \nPlease enter the Mortgage payback amount per month sans delimiters.\n";
cin >> repayment;
do {
mortgage = mortgage - repayment;
if (i % 12 == 0){
mortgage = mortgage*(1+(interest/100));
}
++i;
} while (mortgage > 0);
cout << "100,000 repaid at " << repayment << " per month would take " << i << " months to pay off";
}


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.

Fobic 18-08-2009 18:44

Re: Programming Challenges?
 
Quote:

Originally Posted by punky (Post 34856729)
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.


That does the trick. Many thanks.

Never noticed the stuff in the top right before. Must be old age :o:

Waldo Pepper 19-08-2009 07:18

Re: Programming Challenges?
 
When I was learning C in the 80's, I used to write programs to prove or disprove if a number is prime. Specifically the Lucas Lehmer test.
Easy to do in C. Re-writing in 8051 assembler will make you a real programmer. Moreso if you then re-write code to get your graphics card to do it using ultrafast VRAM.
Dissassembling programs is also good practise. Compile a program to multiply two numbers, go and look at the generated code and try to work out what's going on.
I personally always find assembly programming more challenging. Getting a floating point divide to work is easy. Not in 128bytes of stack in 512bytes of reserved code space it isn't.

Damien 19-08-2009 08:35

Re: Programming Challenges?
 
Quote:

Originally Posted by Waldo Pepper (Post 34857030)
I personally always find assembly programming more challenging. Getting a floating point divide to work is easy. Not in 128bytes of stack in 512bytes of reserved code space it isn't.

Thankfully we have better languages to abstract tasks like that away from us ;)

Hugh 19-08-2009 12:00

Re: Programming Challenges?
 
Quote:

Originally Posted by Damien (Post 34857050)
Thankfully we have better languages to abstract tasks like that away from us ;)

Yup - machine time/hardware cheap, people time expensive (which does not excuse carp/inefficient code).

Damien 19-08-2009 12:33

Re: Programming Challenges?
 
Quote:

Originally Posted by foreverwar (Post 34857123)
Yup - machine time/hardware cheap, people time expensive (which does not excuse carp/inefficient code).

Nope for a start others need to maintain it, inefficiency is avoided but I don't think it's as massive a problem as people make out. Often the areas you think a inefficient are not so while other areas may be. Anything web based then bandwidth is probably your most precious resource which you need to optimise.

For example the optimisations we were doing on Month Hall would have no noticeable effect, if you were doing a website and sending too much kb to the client it would be very notable.

Raistlin 20-08-2009 10:19

Re: Programming Challenges?
 
What's wrong with this c code?

Code:

#include <stdio.h>
int main()
{
    printf("Hello World\n");
    return 0;
}



---------- Post added at 10:19 ---------- Previous post was at 10:10 ----------

NVM - nothing wrong with the code, something wrong with Ubuntu.

It doesn't include the standard libraries as part of the install, which means that the code above won't compile.

Sorted now.

handyman 20-08-2009 17:19

Re: Programming Challenges?
 
This may be a good place to ask this question which is probably too simples to have a thread of it's very own. Working on upgrading our current flat db to a more complex relational db in order to speed things up both in use and data entry. This bit of code is the index of dates.
I have 2 tables - courses and dates and each course can be associated with many dates.

This went well till a 4th date was added now I get an error.
Quote:

Warning: mysql_result() [function.mysql-result]: Unable to jump to row 1 on MySQL result index 9 in /home/purple/public_html/test/date_index.php on line 24

Warning: mysql_result() [function.mysql-result]: Unable to jump to row 1 on MySQL result index 9 in /home/purple/public_html/test/date_index.php on line 25

Warning: mysql_result() [function.mysql-result]: Unable to jump to row 1 on MySQL result index 9 in /home/purple/public_html/test/date_index.php on line 26
Start Date: 22/08/09
Course:
As I understand my code it gets an array of the dates and for each one it uses the course_id to get the course_name from the courses db.

Can anyone explain what I'm doing wrong?

Code:

<?php
include("menu.php");
include("connect.php");
$query="SELECT * FROM date ";
$result=mysql_query($query);
$num = mysql_num_rows ($result);
mysql_close();
if ($num > 0 ) {
$i=0;
while ($i < $num) {
$date_start = mysql_result($result,$i,"date_start");
$course_id = mysql_result($result,$i,"course_id");
$id = mysql_result($result,$i,"id");
$date = date("d/m/y",strtotime($date_start));
include("connect.php");
$query2="SELECT * FROM course WHERE (`id`='$course_id') ";
$result2=mysql_query($query2);
$num2 = mysql_num_rows ($result2);
mysql_close();
$i2=0;
$code = mysql_result($result2,$i2,"code");
$name = mysql_result($result2,$i2,"name");
$id = mysql_result($result2,$i2,"id");
echo "<b>Start Date:</b> $date<br>";
echo "<b>Course:</b> $name<br>";
echo "<a href=\"date_update.php?id=$id\">Update Date</a> - <a href=\"date_delete.php?id=$id\">Delete Date</a>";
echo "<br><br>";
++$i; } } else { echo "The database is empty"; }?>

The Error is

punky 31-08-2009 09:21

Re: Programming Challenges?
 
I remember what heero was saying about microprogramming, so I thought this was worth posting. Its an IP stack (sort of) that fits inside a Twitter tweet.

http://www.sics.se/~adam/twip.html

Code:

char b[140];unsigned short *s=b;*l=b;t;main(){while(1){read(0,b,140);b[20]=0;s[11]+=8;t=l[4];l[4]=l[3];l[3]=t;write(1,b,140);}}

punky 16-09-2009 22:20

Re: Programming Challenges?
 
Bit of a bump, I stumbled on a great programming blog today (well judgng by the latest few articles anyway)

http://cafe.elharo.com/

Its aimed at experienced programmers but novice ones can learn a lot from those more experienced.

tweetiepooh 17-09-2009 12:28

Re: Programming Challenges?
 
Try Perl, nice easy and big following. Head over to Perlmonks for support, help and Perl chat.


All times are GMT +1. The time now is 03:40.

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