View unanswered posts | View active topics It is currently Mon May 20, 2024 7:12 pm



Reply to topic  [ 5 posts ] 
Programming, Math, Algorithms and such. 
Author Message
Best Supporting Actress
User avatar

Joined: Thu Jul 08, 2010 6:13 pm
Posts: 6423
Location: Trendyhipstertonville
Post Programming, Math, Algorithms and such.
Took a break from programming my game to practice on some math (a definite weak point of mine) and problem-solving.

So I thought I'd share some of it because fuckyouwhatever.

This first one is a common problem based off of some schoolkid number game. It requires you to print the numbers 1- 50 (or whatever), but when a number is a multiple of 3 print "Fizz", a multiple of 5 print "Buzz" or a multiple of 3 and 5 print "FizzBuzz".

So here is how I did it (in C#):

Code:
using System;

namespace FizzBuzz
{
    class Program
    {
        static void Main()
        {
            // Loops from 1 through 50
            for (var i = 1; i <= 50; i++)
            {
                // Print "Fizz" if the number is divisible by 3
                if (i % 3 == 0)
                    Console.Write("Fizz");

                // Print "Buzz" if the number is divisible by 5
                if (i % 5 == 0)
                    Console.Write("Buzz");

                // Print the number if it is not divisible by 5 or 3
                if (i % 3 != 0 && i % 5 != 0)
                    Console.Write(i);

                // Finish line
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}


Well actually not really. That is kind of the easy/longer way to do it. I'll show another way later. For now lets talk about this code. First off, I printed the entire program above, so if you pasted that into a C# compiler (like this one) you can see the program at work.

But, the real part of the code we need to focus on is this bit:

Code:
static void Main()
        {
            // Loops from 1 through 50
            for (var i = 1; i <= 50; i++)
            {
                // Print "Fizz" if the number is divisible by 3
                if (i % 3 == 0)
                    Console.Write("Fizz");

                // Print "Buzz" if the number is divisible by 5
                if (i % 5 == 0)
                    Console.Write("Buzz");

                // Print the number if it is not divisible by 5 or 3
                if (i % 3 != 0 && i % 5 != 0)
                    Console.Write(i);

                // Finish line
                Console.WriteLine();
            }

            Console.ReadKey();
        }


The program starts by initiating a for loop:

Code:
for (var i = 1; i <= 50; i++)


Which essentially reads: given (A variable we are declaring; meets a criteria; perform a function)

So in this instance we are declaring a variable (using the "var" declaration, which is an implicit declaration that basically says "a variable whose type I am going to declare right now") called i, which is an integer equal to 1. We declare it as 1 because this is where we want our loop to begin.

Next we say if the variable i is less-than-or-equal-to 50 (the highest number in our range), perform the function below; furthermore, each time the function is performed increment the variable i by one (using the short-hand operator i++) and restart the loop.

The function we want the loop to perform is a series of checks. Each of these checks is an if statement, such as:

Code:
if (i % 3 == 0)


This specific statement reads: if (the remainder of variable i divided by 3 is-equal-to 0) perform the below function.

So we check to see if the number represented by variable i is divisible by 3, and if so we print "Fizz" (without continuing to the next line in the console). We perform a similar check to see if the number is divisible by 5, and if so we print "Buzz".

If neither of the above is true, we simply print the number.

Once we have finished all of the above checks, we use "Console.WriteLine();" to continue to the next line.

Each time the function is completed, the number represented by variable by i is incremented and we start the function over again checking the next number. Once we finish checking the number 50, the loop is completed and we carry on.

Since we want to see the results of the checks, we use "Console.ReadKey();" to hold the program from completing until we press any key.

The results should be:

Code:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz


A shorter solution I came up with uses a series of 3 tertiary statements. Tertiary statements are formatted as so:

if statement ? true function : false function

Or can be read as: if this ? do this : or else do this.

Here is the solution:

Code:
            for (var i = 1; i <= 50; i++)
            {
                Console.WriteLine(
                    // Print "Fizz Buzz" if the number is divisible by 15
                    i % 15 == 0 ? "Fizz Buzz" :
                    // Print "Fizz" if the number is divisible by 3
                    i % 3 == 0 ? "Fizz" :
                    // Print "Buzz" if the number is divisible by 5
                    i % 5 == 0 ? "Buzz" :
                    // Print the number if it is not divisible by 5 or 3
                    i.ToString());
            }


Within the loop, our checks can be read as:

if the remainder of i divided by 15 is-equal-to 0 ? Print "Fizz Buzz" : or else if the remainder of i divided by 3 is-equal-to 0 ? Print "Fizz" : or else if the remainder of i is divisible by 5 ? Print "Buzz" : or else print the number (converted to a string of text).

Without the comments and formatting for the sake of demonstration, the actual solution can be written as:

Code:
            for (var i = 1; i <= 50; i++)
                Console.WriteLine(
                    i % 15 == 0 ? "Fizz Buzz" :
                    i % 3 == 0 ? "Fizz" :
                    i % 5 == 0 ? "Buzz" :
                    i.ToString());


And that is how we can check the a range of numbers for specific multiples using C#.

_________________
Dinosaurier live vor langer Zeit
Sie waren schrecklichen Echsen weißt du nicht,
Einige aßen Pflanzen und einigen Fleisch gegessen
Einige aßen Fisch und einige aßen Tiere


Sun Apr 14, 2013 11:25 pm
Profile WWW
Winston Wolf
User avatar

Joined: Wed Jun 16, 2010 7:32 pm
Posts: 11362
Location: ruining everything.
Yes/No: No
Less/More: More
Post Re: Programming, Math, Algorithms and such.
This sort of shit almost works with my brain. I like the organizing, the building of simple logical routes to relatively more complex destinations, the advantages provided by the seeking/finding of elegant and efficient solutions, etc.

But in the end, the properly programming side just isn't quite my flavor. I just so much prefer to work with someone else's code and make it do more than expected through how it can be pushed. I wonder if the actual coding part maybe provides too many options to me? And it is just easier for me to work when i know what the limitations are? I guess i am just more of a modder-type than a programmer-type. I would say that it was laziness, but it is really just as much work to do it my wrong way as it would be to do it the right way from scratch, so i guess it might really be more about stubbornness and/or just what/how my brain likes to be fed for interesting things to come out.

Which is completely a tangent mostly unrelated to what you have going on here. This is definitely one of the things on a short list of things that i would consider Absolutely School-Worthy Endeavors. Meaning, things that going to school for, would actually be a really good idea, unlike for instance how i feel about 99% of all other creative processes, where for instance, i have sort of wound up feeling that school is generally only a detriment to the process, being that the curriculum is designed to train folks primarily in the non-creative aspects of their intended 'creative' professions. I.e. that generally school makes artists who come in thinking/working like artists(a sort of instinctual process) wind up leaving, thinking/working like accountants.

Which is kind of again another tangent. I guess that is just the mode i am in today. Dick cakes and tangents.

_________________
STOP FIXING ROCK RECORDS.

START YOUR OWN RELIGION TODAY.


Mon Apr 15, 2013 9:49 am
Profile
Best Supporting Actress
User avatar

Joined: Thu Jul 08, 2010 6:13 pm
Posts: 6423
Location: Trendyhipstertonville
Post Re: Programming, Math, Algorithms and such.
That's kind of part of the learning curve. I started with following along with videos of other people programming tutorials and such, so it was less problem-solving and more language-learning. Then I was able to look at other people's code, follow along with it and reproduce/edit it to my purposes.

These math problems I am working on are my first non-game-related problems that I am solving without using someone else's code.

I also agree that programming is one field where academics actually can be helpful ... to an extent. The technology moves fast so you spend less time on actual programming and more time on theory, math, algorithms, data structures and design patterns. You mostly write in C and C++ (depending on your focus, you might get some Java and other languages in there as well) as they aren't changing.

So even with formal training you still have to practice your programming to become comfortable with different languages, especially popular ones like Python, Java and C# (popularity is arguable for C#, but I fucking love it). So I am kind of on the backwards track, I started learning languages and task-specific things and am now working backwards on my theory. I am also planning on going back to school here soon.

I got some other fun math programs too. I am actually going to convert all of these programs (about 10 or so so far) into little games for Unity, and create a little "Learn to Program in Unity" tutorial blog.






EDIT: If this stuff seems slightly interesting to anyone, check out http://www.codecademy.com/tracks/python which is an online class that will teach you the basic syntax of programming using python, a super-user-friendly language that is simple to understand. The syntax for python and c# are fairly similar so if you can get through the python programming tracks on Code Academy you should have an easier time understanding what the hell I am talking about.

_________________
Dinosaurier live vor langer Zeit
Sie waren schrecklichen Echsen weißt du nicht,
Einige aßen Pflanzen und einigen Fleisch gegessen
Einige aßen Fisch und einige aßen Tiere


Mon Apr 15, 2013 10:25 am
Profile WWW
Winston Wolf
User avatar

Joined: Tue Jun 15, 2010 11:10 am
Posts: 7283
Location: in the valley of the shadow of death
Post Re: Programming, Math, Algorithms and such.
I did a few courses in C#, loved it, but it got to be too much with working and banding to keep up on it.

_________________
Member of the Radium Water Gentlemen's League Of Luxury


Mon Apr 15, 2013 1:44 pm
Profile
Best Supporting Actress
User avatar

Joined: Thu Jul 08, 2010 6:13 pm
Posts: 6423
Location: Trendyhipstertonville
Post Re: Programming, Math, Algorithms and such.
I actually like this one a a bit.

The following code takes 2(1000th power), separates it into an array of digits and adds all of those digits together.

Code:
var result = new BigInteger(Math.Pow(2, 1000))  // Create number big enough to store 2(1000th power)
                .ToString()                                 // Convert that number to a string of text
                .ToCharArray()                              // Convert that string to an array of characters
                .Select(c =>                                // For every element of the array
                    int.Parse(c.ToString()))                // Convert the character to a string, then parse the string to an int
                    .Sum();                                 // Find the sum of each element of the list


If you don't format it for readability, it is actually one line of code:

Code:
var result = new BigInteger(Math.Pow(2, 1000)).ToString().ToCharArray().Select(c => int.Parse(c.ToString())).Sum();


Here is the full program if you want to compile it and mess with different numbers:

Code:
using System;
using System.Linq;
using System.Numerics;

namespace PowerDigitSum
{
    class Program
    {
        static void Main()
        {
            var result = new BigInteger(Math.Pow(2, 1000))
                             .ToString()
                             .ToCharArray()
                             .Select(c => int.Parse(c.ToString()))
                             .Sum();

            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

_________________
Dinosaurier live vor langer Zeit
Sie waren schrecklichen Echsen weißt du nicht,
Einige aßen Pflanzen und einigen Fleisch gegessen
Einige aßen Fisch und einige aßen Tiere


Tue Apr 16, 2013 1:42 pm
Profile WWW
Display posts from previous:  Sort by  
Reply to topic   [ 5 posts ] 

Who is online

Users browsing this forum: No registered users and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by STSoftware.