• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

jdavid459

Member
Hey ... was wondering if someone could point me to the best resource for learning programming online. There are so many out now, that I don't know where to begin. I am looking for something that will walk me through the basics, give me some example projects, teach me how to build on my own ideas. There's coursera, udacity, treehouse, w3schools, list goes on and on. What's the BEST?

Also...not sure which language to learn first. I am most concerned with business applications/entrepreneurial ideas...may be in web design or app development...not really sure. Would like to learn both.
 
Hey ... was wondering if someone could point me to the best resource for learning programming online. There are so many out now, that I don't know where to begin. I am looking for something that will walk me through the basics, give me some example projects, teach me how to build on my own ideas. There's coursera, udacity, treehouse, w3schools, list goes on and on. What's the BEST?

Also...not sure which language to learn first. I am most concerned with business applications/entrepreneurial ideas...may be in web design or app development...not really sure. Would like to learn both.

From your second paragraph, Java seems like a pretty good candidate. It is widely used in the enterprise and you can use it to program Android apps. I wouldn't classify web design as programming - it is its own thing. For getting started, I would suggest going through Udacity's Java class, and reading the official Java tutorial. Buying a good book is also a wise investment. Use google and stackoverflow for all the questions you have (And of course this thread).

Also I wouldn't worry too much about selecting the "best" language when you are first starting out. It is far more important that you understand the fundamentals of programming that apply to all languages. More importantly, do not make the classical mistake of picking a language and not sticking to it. Pick one and master it until you feel comfortable building different types of apps. When you get to that level, that is when the ideas for personal projects will come easily. To get there practice, practice, practice. Good luck.
 

-KRS-

Member
So I've been coding on and off for fun and to learn for a while, but haven't really done anything in a long time and never got really good at any particular language. But two weeks ago I wanted to learn C for realsies this time, so I started reading a bunch of tutorials etc and feel like I've gotten the hang on most of the basics now (although pointers still confuse me a little).

Yesterday I thought I should write a simple program that populates a 2D array with unique random numbers just as a test to see if I could with the knowledge i have. I haven't read a whole lot about the best way to go about this, but I came up with a solution that seems to work, IF the array is around 5*5 large. If I set it to be say 9*9 there will sometimes be a couple of duplicate numbers anyway.

Here's the function I wrote to set up the numbers:
Code:
void setNum(int arr[][COLS])
{
    int x,y,i,j;
    int check;
    bool brk;

    /* First set the array elements to zero */
    initArray(arr);

    /* Generate random numbers */
    printf("\nGenerating the numbers...\n");
    for (x=0; x < ROWS; x++) {
        for (y=0; y < COLS; y++) {
            brk = false;
            check = getRandNum();
            /* Check for duplicates */
            for (i=0; i <= x; i++) {
                for (j=0; j <= y; j++) {
                    if (arr[i][j] == check) {
                        printf("Duplicate found at row %d, column %d.\n", x+1, y+1);
                        printf("Regenerating number.\n");
                        y--;
                        brk = true;
                        break;
                    }
                }
                if (brk) {break;}
            }
            if (brk) {continue;}
            arr[x][y] = check;
        }
    }
}

I just can't see what I'm doing wrong here. I assume it has to do with one of the loops but it seems right to me. Anyone know?
The idea is that the two innermost loops (i and j) should traverse the already set numbers in the array and compare them to the "check" variable and if there's a match it should regenerate the number again. If not, "check" should be copied into "arr[x][y]".

Also, if there's a more elegant solution to doing this please let me know. This is just what I thought of myself and it's probably far from the best solution. That many nested loops seems like it might be a bit more complicated than it needs to be.
 
So I've been coding on and off for fun and to learn for a while, but haven't really done anything in a long time and never got really good at any particular language. But two weeks ago I wanted to learn C for realsies this time, so I started reading a bunch of tutorials etc and feel like I've gotten the hang on most of the basics now (although pointers still confuse me a little).

Yesterday I thought I should write a simple program that populates a 2D array with unique random numbers just as a test to see if I could with the knowledge i have. I haven't read a whole lot about the best way to go about this, but I came up with a solution that seems to work, IF the array is around 5*5 large. If I set it to be say 9*9 there will sometimes be a couple of duplicate numbers anyway.

Here's the function I wrote to set up the numbers:
Code:
void setNum(int arr[][COLS])
{
    int x,y,i,j;
    int check;
    bool brk;

    /* First set the array elements to zero */
    initArray(arr);

    /* Generate random numbers */
    printf("\nGenerating the numbers...\n");
    for (x=0; x < ROWS; x++) {
        for (y=0; y < COLS; y++) {
            brk = false;
            check = getRandNum();
            /* Check for duplicates */
            for (i=0; i <= x; i++) {
                for (j=0; j <= y; j++) {
                    if (arr[i][j] == check) {
                        printf("Duplicate found at row %d, column %d.\n", x+1, y+1);
                        printf("Regenerating number.\n");
                        y--;
                        brk = true;
                        break;
                    }
                }
                if (brk) {break;}
            }
            if (brk) {continue;}
            arr[x][y] = check;
        }
    }
}

I just can't see what I'm doing wrong here. I assume it has to do with one of the loops but it seems right to me. Anyone know?
The idea is that the two innermost loops (i and j) should traverse the already set numbers in the array and compare them to the "check" variable and if there's a match it should regenerate the number again. If not, "check" should be copied into "arr[x][y]".

Also, if there's a more elegant solution to doing this please let me know. This is just what I thought of myself and it's probably far from the best solution. That many nested loops seems like it might be a bit more complicated than it needs to be.

Seems right to me. It ran on my computer as expected with all unique numbers. What is the output you are seeing? Is it looping forever?

A few comments regarding the code, I would extract the code that checks if a number is already in the array to it's own function. Also regarding a better way to do it, yes there is. Looking for the elements the way you are doing is very inefficient. Look up run quadratic runtime - O(n^2).

Maybe it's a little too advanced for you, but research a thing called a hash-table. It is a container that can store items like an array. You could use it for an <int, bool> pair where you store an integer that maps to a bool value. For each random number you generate, you store it, and set the value to true. Next time you see the value all you have to do is check whether it's already in the hash-table.
 

Air

Banned
Heyoo programming gaf, newbie here. So I've spent that last 2 weeks or so learning html/ css on codeacademy. After I'm done I would like to learn another language while continuing to fine tune my html/css knowledge. I pretty much want to build websites and maybe get into making apps for the iphone (eventually, not right away). My company also would need a store section and what not, I guess what I'm asking is in order to pull off something of the scale of the steam website (not the downloadable file, just the website) what else would I need to learn? I'm willing to put the time into learning all the possible languages possible and I gather I'll have to learn Java, Jquery and php. Is that all???

Also as an animator, learning to program is surprisingly fun. I was put off of it in highschool because it seems so complicated, but now that I am giving myself time to take it as a step by step process, I'm really enjoying it!

EDIT: Also, roughly how long does it usually take to get a functioning grasp on these languages (enough where I can reliably use it as a second stream of income to build websites)? I've heard a couple of weeks for html and css, and a couple of months for Java. Is that about what I should expect (I know people learn at different rates, just need a quick and dirty ballpark answer given ideal conditions).
 

Chris R

Member
Well if you are already learning HTML and CSS I'd say the next step would be some form of Javascript as it complements the others very nicely.
 

Kinitari

Black Canada Mafia
Heyoo programming gaf, newbie here. So I've spent that last 2 weeks or so learning html/ css on codeacademy. After I'm done I would like to learn another language while continuing to fine tune my html/css knowledge. I pretty much want to build websites and maybe get into making apps for the iphone (eventually, not right away). My company also would need a store section and what not, I guess what I'm asking is in order to pull off something of the scale of the steam website (not the downloadable file, just the website) what else would I need to learn? I'm willing to put the time into learning all the possible languages possible and I gather I'll have to learn Java, Jquery and php. Is that all???

Also as an animator, learning to program is surprisingly fun. I was put off of it in highschool because it seems so complicated, but now that I am giving myself time to take it as a step by step process, I'm really enjoying it!

EDIT: Also, roughly how long does it usually take to get a functioning grasp on these languages (enough where I can reliably use it as a second stream of income to build websites)? I've heard a couple of weeks for html and css, and a couple of months for Java. Is that about what I should expect (I know people learn at different rates, just need a quick and dirty ballpark answer given ideal conditions).

Well, first things first, it would be a good idea to learn javascript. Javascript usually goes hand in hand with html/css to give you dynamic websites. I'd recommend spending some time learning the basics of javascript, and then maybe jumping right to jQuery (think of jQuery as a specialized version of javascript. The term is library). jQuery is fast to learn and get decent at.

So, if you want to get jQuery/Javascript under your belt, you need another month or two of practice to get decent.

BUT

If you want to make web applications, there is a good chance you'll need to learn some backend stuff too.

That means something like mySQL and PHP, or node and mongo, or a whole slew of other options (PHP/mySQL is probably the easiest).

It's a lot of work, but it gets rewarding!
 

Air

Banned
Well if you are already learning HTML and CSS I'd say the next step would be some form of Javascript as it complements the others very nicely.

Well, first things first, it would be a good idea to learn javascript. Javascript usually goes hand in hand with html/css to give you dynamic websites. I'd recommend spending some time learning the basics of javascript, and then maybe jumping right to jQuery (think of jQuery as a specialized version of javascript. The term is library). jQuery is fast to learn and get decent at.

So, if you want to get jQuery/Javascript under your belt, you need another month or two of practice to get decent.

BUT

If you want to make web applications, there is a good chance you'll need to learn some backend stuff too.

That means something like mySQL and PHP, or node and mongo, or a whole slew of other options (PHP/mySQL is probably the easiest).

It's a lot of work, but it gets rewarding!

Thanks dudes! I figured I would need to learn php too, but I guess I'll tackle Java first. Thanks for the frame of time too as that's about what I figured giving really good conditions. I plan to use the rest of this year and up until march dedicating my time and fine-tuning my skills and I am really excited for it! I've always felt that programming was my Achilles heel and to really make the most of technology today you need to learn these things so I'm excited just on that basis.

I'd definitely like to stick around with this community as I learn more about these languages. Also this stuff reminds me of when I took trigonometry in highschool and how much fun I had with understand logic and stuff of that nature.
 

Kinitari

Black Canada Mafia
Thanks dudes! I figured I would need to learn php too, but I guess I'll tackle Java first. Thanks for the frame of time too as that's about what I figured giving really good conditions. I plan to use the rest of this year and up until march dedicating my time and fine-tuning my skills and I am really excited for it! I've always felt that programming was my Achilles heel and to really make the most of technology today you need to learn these things so I'm excited just on that basis.

I'd definitely like to stick around with this community as I learn more about these languages. Also this stuff reminds me of when I took trigonometry in highschool and how much fun I had with understand logic and stuff of that nature.

Quick warning! Java and Javascript are not even kind of related. I know, it's confusing, and it bothered me too at first - but if you go looking for java tutorials, you'll get messed up when you try to work with javascript!
 

Zoe

Member
The order I would go in is

HTML -> JavaScript -> frontend (ex. PHP) -> SQL -> backend (ex. Java, C#)
 

Air

Banned
Quick warning! Java and Javascript are not even kind of related. I know, it's confusing, and it bothered me too at first - but if you go looking for java tutorials, you'll get messed up when you try to work with javascript!

Thanks for the clarification! I should have known better.

The order I would go in is

HTML -> JavaScript -> frontend (ex. PHP) -> SQL -> backend (ex. Java, C#)

Thanks. This actually helps me out a lot in figuring out where the line is between front and backend stuff.
 

hateradio

The Most Dangerous Yes Man
The order I would go in is

HTML -> JavaScript -> frontend (ex. PHP) -> SQL -> backend (ex. Java, C#)
By front end I'd say JS*/CSS/HTML. PHP is technically used for the back end.



*Unless you're doing some node stuff or w/e.
 

ominator

Neo Member
ok, i need some help with python and the SRS-programm Anki.

i want (have to because university, but i chose this projekt) to write an addon for this program. the program should be able to let the user draw a kanji, then compare it with the actual kanji. so it is an image comparison program. therefore i need a QImage. but i can't get it to work. drawing with the QPainter on the widget works. but not creating a qimage, neither from loading an existing picture nor creating one and drawing in it. here is the code:
Code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui, QtCore
from aqt import mw

class KanjiPainter(QWidget):

    def __init__(self, parent=None):
        super(KanjiPainter, self).__init__(parent)
        self.setFocusPolicy(Qt.WheelFocus)
        self.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed))
        layout = QHBoxLayout()
        self.setLayout(layout)
        self.setWindowTitle("test >:O")
        self.setMouseTracking(True)     

    def sizeHint(self):
        return self.minimumSizeHint()
        
    def minimumSizeHint(self):
        return QSize(800,800)
        
    def paintEvent(self, event):
       # if self.draw:
            super(KanjiPainter, self).paintEvent(event)
            
            painter = QPainter(self)
          #  painter.begin(self)
            painter.setPen(QtGui.QColor(0, 234, 3))
            #neither creating an empty QImage nor loading an existing picture works
            #image = QImage(QSize(400,400))   
            image = QImage(":/pic.png")
            imgpainter = QPainter(image)
            imgpainter.setPen(QtGui.QColor(168, 34, 3))
            imgpainter.drawRect(10,10, 50, 50)
            painter.setPen(QtGui.QColor(168, 34, 3))
            painter.drawRect(200,200, 50, 50)
            painter.drawImage(QPoint(80,80),image)
           # painter.end()
           
def testFunction():
    # show a message box
    mw.myWidget = kp = KanjiPainter()
    kp.show()

# create a new menu item, "test"
action = QAction("test", mw)
# set it to call testFunction when it's clicked
mw.connect(action, SIGNAL("triggered()"), testFunction)
# and add it to the tools menu
mw.form.menuTools.addAction(action)

if anyone wants to test this: download Anki, go to the addon folder, create a file named KanjiPainter.py und paste the code above. start anki, goto Tools -> test
 

KageZero

Member
Hi, it's me again.

I'm doing my own web page but i got stuck with it. I finished the "design" part (html, css) and i did some stuff with js but i cannot mange to get jquery working as i would like. The thing i wanted to do is to make a slide panel (you hover over a link and a "popup" with other links appears, i think you get what i mean) with link's but i only got it working when i defined each "main" link different class id but that makes too much code so i wanted to make it all work with one function but i cannot accomplish that. When i hover over one link all other go off as well or none of them works :(. I was messing so much over the html page that i have to start from 0 again because it's all messed up. So i wanted to know is there any way i could obtain files from other pages that are working ( i mean source files like html, css, js) where i could read the code how did they do it, that would help me a lot.
 

-KRS-

Member
Seems right to me. It ran on my computer as expected with all unique numbers. What is the output you are seeing? Is it looping forever?

A few comments regarding the code, I would extract the code that checks if a number is already in the array to it's own function. Also regarding a better way to do it, yes there is. Looking for the elements the way you are doing is very inefficient. Look up run quadratic runtime - O(n^2).

Maybe it's a little too advanced for you, but research a thing called a hash-table. It is a container that can store items like an array. You could use it for an <int, bool> pair where you store an integer that maps to a bool value. For each random number you generate, you store it, and set the value to true. Next time you see the value all you have to do is check whether it's already in the hash-table.

Hmm that's strange. No it's not looping forever, sometimes there are simply duplicates in the array even though I check for them and regenerate the number. Especially if it's a somewhat larger array like a 9*9 array or so. When I set it up to be a 5*5 array it seems to always work. The getRandNum() function I wrote just returns a number between 1 and 99 using the standard rand() function which I seed with the current time at the start of the program.

Here's an example output using a 9*9 array where I've bolded some duplicates I noticed glancing over it:
Code:
 98 90 40 66 95 20 [B]48[/B] 52 15
 [B]48[/B] 99 76 47 15 43 71 [B]92[/B]  3
  4 29 93 [B]92[/B] 51 14 59 85 41
 56 81 31 25 [B]12[/B] 26 74  2 84
 88 42 53 78 45  5 [B]38[/B] 55 49
 40 13 41 33 97 80 86 [B]11[/B] 23
 35 89 16 [B]12[/B] 83 [B]38[/B] 49 91  [B]7[/B]
 81 17 21 60  1 44 87 22  9
 46 [B]11[/B] 22 55 24 74 10  [B]7[/B] 30
There might be more but you get the idea.
Also it seems to always be only one duplicate per number, never two or more, for some reason. I guess it doesn't really matter since the method I'm using is not an optimal one anyway but it'd be nice to know why it happens.

And thanks for the tips. I'll definitely be looking into them. I looked a bit at hashtables and it seems that C doesn't have anything like that built into the language or standard library, so I'd have to use a third party library or create my own. Creating my own is probably a bit above me right now so a third party one will do. Do you have any recommendations regarding that? I'm using Linux, but one that is reasonably portable would be the best in the long run I think.

Edit: Correction: I just noticed three instances of the same number in a 5*5 array. So scratch the part where I said it works on 5*5 arrays and only seems to be one duplicate per number. But it's rare that there are duplicates in a 5*5 array compared to larger ones where it seems to happen pretty much every time.
 
Anyone have any programmer horror stories? I sometimes feel like my entire job is one at certain times.

About three years ago my company was like super close to going under. We had no contracts, no money coming in, and really sort of didn't have a product. Completely teetering on the brink. Anyway, we had some interest in our product from a potential customer and they paid for a year long demo, and that was the only income we had. Anyway, the CTO/Project Manager at the time got it into his head that instead of maintaining or re-architecturing the current product he wanted to expand the scope to something ridiculous and work on that.

Basically the idea was to take what our product currently did in a very specific realm (maritime domain security) and expand it to basically be customized to any sort of security realm. The goal was to make it web-based. Well there were a few things wrong with this. First of all the scope of what he had in mind was sort of ridiculous. Just as an example, he wanted the system to be able to hook into any database technology, so he decided we should write an intermediate instruction set that could then be abstracted to fit the SQL particulars of any RDBMS out there. The system was to be able to accept any table of information and let the users customize the data access to organize that into usable information that we could then run an analysis on. It's sort of hard to explain. Included in this was an entirely new jquery/ajax etc based UI that had to be built from the ground up.

But, he wanted to do all of this with a team of four (including himself). At the time I was about a year or so out of college, and had gotten a friend of mine who graduated a year before me a job at the company as well. So we had basically two experienced programmers and two juniors. He also didn't find out if our prospective client could use a modern browser. So we got to work on this thing, and about three or four months in he calls us into a meeting and tells us that the prospective client could only use IE 5 and that basically none of the UI work we had done would really function in their environment and we basically lost three or four months of work. I was on the UI specifically, so it impacted me the most. Anyway, another month into this and the other senior level guy was basically at the project managers throat every other day because he had realized the project wasn't feasible and was already six months behind schedule.

We had started in January, and by August we found out that our boss couldn't pay us on time anymore. We basically got paid once every two months, but he paid us all the back pay. By like October we found out that the project manager was jumping ship and leaving for a different company. There was a sort of bright side to this. At about the same time we found out that the customer that had demoed our product wanted to go ahead and buy it. That was great. The problem was they wanted it by March. And our most senior person was leaving. We basically decided to scrap the 9 months of work we had done on the new software and just implement a lot of fixes on the version they had demoed.

The problem was there was an entire module that they wanted that was basically nothing but prototype code. And we were mostly a Java shop and the entire prototype was written in C# and .NET. Me and my buddy I got hired basically got assigned to get that prototype code up to a working state by March. Problem was that NEITHER of us had done C# before. So we had to learn it, then fix the prototype, while the senior guy fixed like 1000 bugs in the other module.

Somehow, I have no clue how, we duct taped this thing together in six months (thankfully the customers schedule slipped back to June/July giving us a few more months to work on the project). Then we went out to do the installation. At the time there was absolutely no automated process for configuring the system, so installation basically came down to me and the Senior guy on site manually editing configuration files trying to get the thing to work. Somehow we got it work, then we did the user training and so on and so forth. It was the most stressful time in my life. My boss, the owner, had us click through every button in the application in order to train the users, and every time I clicked something I basically just waited for the entire system to crash or throw up error messages. But it didn't. There were a few small but noticeable bugs but we fixed them with a patch once we flew home. I honestly have no idea how we pulled it off. They signed the contract and the company had some money coming in, but had taken on so much debt during the period we had no income that we still were only getting paid once every month or two for a full year afterward.

It's sort of amazing the company survived and how far we've come since then. I was given a 5% share or the company, and basically became the de facto system architect even though I only had three years of experience, while the senior guy that was still around became the Project Manager/Business liaison. We're still only running on a small number of contracts but our business is set to triple in the next two years if things go perfectly. I doubt they will, but it would be nice. Since then we've fully refreshed the entire architecture, all processes for installation are completely automated, and I'm currently rewriting the last bit of legacy code in the system. It feels good to have been here for the entirety of the turn around of what was basically a rapidly sinking ship.
 

usea

Member
Hmm that's strange. No it's not looping forever, sometimes there are simply duplicates in the array even though I check for them and regenerate the number. Especially if it's a somewhat larger array like a 9*9 array or so. When I set it up to be a 5*5 array it seems to always work. The getRandNum() function I wrote just returns a number between 1 and 99 using the standard rand() function which I seed with the current time at the start of the program.

Here's an example output using a 9*9 array where I've bolded some duplicates I noticed glancing over it:

There might be more but you get the idea.
Also it seems to always be only one duplicate per number, never two or more, for some reason. I guess it doesn't really matter since the method I'm using is not an optimal one anyway but it'd be nice to know why it happens.

And thanks for the tips. I'll definitely be looking into them. I looked a bit at hashtables and it seems that C doesn't have anything like that built into the language or standard library, so I'd have to use a third party library or create my own. Creating my own is probably a bit above me right now so a third party one will do. Do you have any recommendations regarding that? I'm using Linux, but one that is reasonably portable would be the best in the long run I think.

Edit: Correction: I just noticed three instances of the same number in a 5*5 array. So scratch the part where I said it works on 5*5 arrays and only seems to be one duplicate per number. But it's rare that there are duplicates in a 5*5 array compared to larger ones where it seems to happen pretty much every time.
The best way to fix your code as-is is to step through it with a debugger. Change getRandNum() to return only 1-3 and then step through it to see what happens when it generates duplicates. Just looking at the code I can't figure out what's wrong with it.

The best way to fix the code period is to redo it. It's very complex for such a simple task, because all the steps are interwoven. Try generating unique numbers first in a totally separate step, and then fill the array with them. Store them somewhere that's easier to check for duplicates. A hashtable/map would work best, but you could just use a vector or array or whatever too.

Here's how that would look in C#, using in a familiar style:
Code:
void Main()
{
    int dimension = 9;
    int[,] grid = MakeGrid(dimension);
}

private int[,] MakeGrid(int dimension)
{
    int[] uniques = GenerateUniqueNumbers(1, 100, dimension*dimension);
    int[,] result = new int[dimension,dimension];
    for (int i = 0; i < dimension; i++)
    {
        for (int j = 0; j < dimension; j++)
        {
            result[i,j] = uniques[i*dimension + j];
        }
    }
    return result;
}

private int[] GenerateUniqueNumbers(int min, int max, int size)
{
    if(max-min < size)
    {
        return null;
    }
    Random r = new Random();
    int[] result = new int[size];
    for (int i = 0; i < size; i++)
    {
        int num = r.Next(min, max);
        if(!Contains(result, num, i))
        {
            result[i] = num;
        }
        else
        {
            i--;
        }
    }
    return result;
}

private bool Contains(int[] array, int num, int maxIndex)
{
    for (int i = 0; i < maxIndex; i++)
    {
        if(array[i] == num)
        {
            return true;
        }
    }
    return false;
}

Output:
Code:
22  78  97  11  28  96  32  31  75
50  89  56  19  93  63  42  43  84
 7  20  83  71  61  27  53  18  73
 6  95  62   2   0  65  99  15  47
41  55  46  38   8  79  74  90  57
70  54  16  13  29  21  68  24  34
58  33  17  44   9  77  85  51  39
92   1  59  25  26  76  81  94   4
66  30  12  35  88  80  87  14  64
edit: I generated the above grid using a minimum of 0, but then I saw you asked for 1-99 so I changed the code without generating another grid. That's why there's a 0 in there.

It won't work with dimension above 9, since there aren't enough unique numbers. You could choose a max number based on the dimension, but that seemed more than was required.

Once you're generating your unique numbers in a separate step, you have a lot of options about how you want to do it. For example you could just generate all the numbers 1-100, shuffle them, and then take the first 9*9 of them.
 

Chris R

Member
Once you're generating your unique numbers in a separate step, you have a lot of options about how you want to do it. For example you could just generate all the numbers 1-100, shuffle them, and then take the first 9*9 of them.

This is what I'd do.
 

tokkun

Member
So I've been coding on and off for fun and to learn for a while, but haven't really done anything in a long time and never got really good at any particular language. But two weeks ago I wanted to learn C for realsies this time, so I started reading a bunch of tutorials etc and feel like I've gotten the hang on most of the basics now (although pointers still confuse me a little).

Yesterday I thought I should write a simple program that populates a 2D array with unique random numbers just as a test to see if I could with the knowledge i have. I haven't read a whole lot about the best way to go about this, but I came up with a solution that seems to work, IF the array is around 5*5 large. If I set it to be say 9*9 there will sometimes be a couple of duplicate numbers anyway.

Here's the function I wrote to set up the numbers:
Code:
void setNum(int arr[][COLS])
{
    int x,y,i,j;
    int check;
    bool brk;

    /* First set the array elements to zero */
    initArray(arr);

    /* Generate random numbers */
    printf("\nGenerating the numbers...\n");
    for (x=0; x < ROWS; x++) {
        for (y=0; y < COLS; y++) {
            brk = false;
            check = getRandNum();
            /* Check for duplicates */
            for (i=0; i <= x; i++) {
                for (j=0; j <= y; j++) {
                    if (arr[i][j] == check) {
                        printf("Duplicate found at row %d, column %d.\n", x+1, y+1);
                        printf("Regenerating number.\n");
                        y--;
                        brk = true;
                        break;
                    }
                }
                if (brk) {break;}
            }
            if (brk) {continue;}
            arr[x][y] = check;
        }
    }
}

I just can't see what I'm doing wrong here. I assume it has to do with one of the loops but it seems right to me. Anyone know?
The idea is that the two innermost loops (i and j) should traverse the already set numbers in the array and compare them to the "check" variable and if there's a match it should regenerate the number again. If not, "check" should be copied into "arr[x][y]".

Also, if there's a more elegant solution to doing this please let me know. This is just what I thought of myself and it's probably far from the best solution. That many nested loops seems like it might be a bit more complicated than it needs to be.

The problem is the upper bounds on your check loops.

Say you put the number 99 int array[0][9].

Now you are on array[1][0]. What happens if you generate 99 again?

Fill in the values of x and y, and your search loop looks like this:

Code:
for (i <= 0; i < [B]1[/B]; i++) {
  for (j <= 0; j < [B]0[/B]; j++) {
  // ...
  }
}

Clearly, you will never check entry [0][9].

What you want to do is search the entire row for j < y, and only search the partial row for j == y.
 

tokkun

Member
By the way, here is what I would consider more elegant if performance is not important (assume you only want 2-digit numbers):

Code:
assert(num_rows * num_cols < 100);

bool used_already[100];
for (int i = 0; i < 100; ++i) {
  used_already = false;
}

for (int x=0; x < num_rows; ++x) {
  for (int y=0; y < num_cols; ++y) {
    int next_val;
    do { next_val = rand() % 100; } while (used_already[next_val]);
    used_already[next_val] = true;
    array[x][y] = next_val;
  }
}

This example requires C99.
 

usea

Member
For fun, here's a linq query to generate a 9x9 grid as IEnumerable<IEnumerable<int>> of unique ints 1-99
Code:
var dimension = 9;
var grid = Enumerable.Range(1, 99).OrderBy(x => Guid.NewGuid()).Take(dimension * dimension).Select((n,i) => new{i=i, n=n}).GroupBy(x => x.i / dimension).Select(x => x.Select(z => z.n));
 

ominator

Neo Member
ok, I tried an other example it without anki and it worked. but using anki to load the script leads again in not displaying the image, but no errors occurs. so i really don't know where the problem lies.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Writing a Java plugin for Unity is so complicated it's fucking my mind.

I am so out of my depth here I don't even know where to start.

All this just to save a screenshot to the SD card.
 

sirap

Member
I don't know shit about programming, but I'm interested to learn for the purpose of developing my own IOS/Android Apps.

GAF gods show me the light, point me in the right direction!
 
For fun, here's a linq query to generate a 9x9 grid as IEnumerable<IEnumerable<int>> of unique ints 1-99
Code:
var dimension = 9;
var grid = Enumerable.Range(1, 99).OrderBy(x => Guid.NewGuid()).Take(dimension * dimension).Select((n,i) => new{i=i, n=n}).GroupBy(x => x.i / dimension).Select(x => x.Select(z => z.n));

This here got me thinking, is your approach (shuffle a range of numbers and take a subset of it) equivalent to iterate over the grid, assign a random number to each field and manually check for and replace duplicates? Does it add any statistical bias to the distribution, compared to the usual approach?

Here's a Scala version of the above code:
Code:
val dimension = 9
val grid = util.Random.shuffle((1 to 99).toList).take(dimension * dimension).grouped(dimension)
grid.map(_.mkString(" ")).mkString("\n")
The third line is just for prettier output.
 
Jobs:

Gotten 2 offers but they're low balling me. Have 3 interviews this coming week. All in the range I'm asking for. We'll see!

Anyone have any programmer horror stories? I sometimes feel like my entire job is one at certain times.

About three years ago my company was like super close to going under. We had no contracts, no money coming in, and really sort of didn't have a product. Completely teetering on the brink. Anyway, we had some interest in our product from a potential customer and they paid for a year long demo, and that was the only income we had. Anyway, the CTO/Project Manager at the time got it into his head that instead of maintaining or re-architecturing the current product he wanted to expand the scope to something ridiculous and work on that.

Basically the idea was to take what our product currently did in a very specific realm (maritime domain security) and expand it to basically be customized to any sort of security realm. The goal was to make it web-based. Well there were a few things wrong with this. First of all the scope of what he had in mind was sort of ridiculous. Just as an example, he wanted the system to be able to hook into any database technology, so he decided we should write an intermediate instruction set that could then be abstracted to fit the SQL particulars of any RDBMS out there. The system was to be able to accept any table of information and let the users customize the data access to organize that into usable information that we could then run an analysis on. It's sort of hard to explain. Included in this was an entirely new jquery/ajax etc based UI that had to be built from the ground up.

But, he wanted to do all of this with a team of four (including himself). At the time I was about a year or so out of college, and had gotten a friend of mine who graduated a year before me a job at the company as well. So we had basically two experienced programmers and two juniors. He also didn't find out if our prospective client could use a modern browser. So we got to work on this thing, and about three or four months in he calls us into a meeting and tells us that the prospective client could only use IE 5 and that basically none of the UI work we had done would really function in their environment and we basically lost three or four months of work. I was on the UI specifically, so it impacted me the most. Anyway, another month into this and the other senior level guy was basically at the project managers throat every other day because he had realized the project wasn't feasible and was already six months behind schedule.

We had started in January, and by August we found out that our boss couldn't pay us on time anymore. We basically got paid once every two months, but he paid us all the back pay. By like October we found out that the project manager was jumping ship and leaving for a different company. There was a sort of bright side to this. At about the same time we found out that the customer that had demoed our product wanted to go ahead and buy it. That was great. The problem was they wanted it by March. And our most senior person was leaving. We basically decided to scrap the 9 months of work we had done on the new software and just implement a lot of fixes on the version they had demoed.

The problem was there was an entire module that they wanted that was basically nothing but prototype code. And we were mostly a Java shop and the entire prototype was written in C# and .NET. Me and my buddy I got hired basically got assigned to get that prototype code up to a working state by March. Problem was that NEITHER of us had done C# before. So we had to learn it, then fix the prototype, while the senior guy fixed like 1000 bugs in the other module.

Somehow, I have no clue how, we duct taped this thing together in six months (thankfully the customers schedule slipped back to June/July giving us a few more months to work on the project). Then we went out to do the installation. At the time there was absolutely no automated process for configuring the system, so installation basically came down to me and the Senior guy on site manually editing configuration files trying to get the thing to work. Somehow we got it work, then we did the user training and so on and so forth. It was the most stressful time in my life. My boss, the owner, had us click through every button in the application in order to train the users, and every time I clicked something I basically just waited for the entire system to crash or throw up error messages. But it didn't. There were a few small but noticeable bugs but we fixed them with a patch once we flew home. I honestly have no idea how we pulled it off. They signed the contract and the company had some money coming in, but had taken on so much debt during the period we had no income that we still were only getting paid once every month or two for a full year afterward.

It's sort of amazing the company survived and how far we've come since then. I was given a 5% share or the company, and basically became the de facto system architect even though I only had three years of experience, while the senior guy that was still around became the Project Manager/Business liaison. We're still only running on a small number of contracts but our business is set to triple in the next two years if things go perfectly. I doubt they will, but it would be nice. Since then we've fully refreshed the entire architecture, all processes for installation are completely automated, and I'm currently rewriting the last bit of legacy code in the system. It feels good to have been here for the entirety of the turn around of what was basically a rapidly sinking ship.

that's an awesome story. life man, stranger things.
 

Kinitari

Black Canada Mafia
Hi, it's me again.

I'm doing my own web page but i got stuck with it. I finished the "design" part (html, css) and i did some stuff with js but i cannot mange to get jquery working as i would like. The thing i wanted to do is to make a slide panel (you hover over a link and a "popup" with other links appears, i think you get what i mean) with link's but i only got it working when i defined each "main" link different class id but that makes too much code so i wanted to make it all work with one function but i cannot accomplish that. When i hover over one link all other go off as well or none of them works :(. I was messing so much over the html page that i have to start from 0 again because it's all messed up. So i wanted to know is there any way i could obtain files from other pages that are working ( i mean source files like html, css, js) where i could read the code how did they do it, that would help me a lot.

Could you share the code? Without looking, it sounds like you want to create a drop down menu - and those can be a bit tricky sometimes.
 

Water

Member
This here got me thinking, is your approach (shuffle a range of numbers and take a subset of it) equivalent to iterate over the grid, assign a random number to each field and manually check for and replace duplicates? Does it add any statistical bias to the distribution, compared to the usual approach?
It's bias-free, even more obviously than the manual check and replace approach. And very efficient in this case.

If you needed unique random numbers from a large range, checking and replacing one by one is bad for performance. Using a hashtable or search tree would be the most clean and straightforward way to check what numbers are present already. If neither is available or space is at a premium, you could generate all numbers plus a few extra to account for possible duplicates, sort, remove all duplicates in one go, and shuffle. These can all be done in place.
 

ominator

Neo Member
good news everyone. after raging hard for an hour I finally managed it to work. ok, it's just an rectangle which i'm drawing. but if load it with anki. it shows it in a weird color. but whatever, I#m happy now.
 

hateradio

The Most Dangerous Yes Man
This here got me thinking, is your approach (shuffle a range of numbers and take a subset of it) equivalent to iterate over the grid, assign a random number to each field and manually check for and replace duplicates? Does it add any statistical bias to the distribution, compared to the usual approach?

Here's a Scala version of the above code:
Code:
val dimension = 9
val grid = util.Random.shuffle((1 to 99).toList).take(dimension * dimension).grouped(dimension)
grid.map(_.mkString(" ")).mkString("\n")
The third line is just for prettier output.
I wish I could work with Scala. :(


I still find it tricky when I can displace the dot.

Code:
// works
grid map (_.mkString(" ")) mkString "\n"

// nope
grid map (_.mkString " ") mkString "\n"

// works
grid map (_ mkString " ") mkString "\n"
Is it because both the period and the parenthesis need to be removed? But then grid.map does need parenthesis, but you can omit the period.
 

ominator

Neo Member
wow, i think i start to hate python. first of all, i can't start python scripts via the python launcher anymore. starting the script with anki works. but anki gives renders some strange colors into my programm.
first this:
AcxYOkc.png


when i started it standalone (when i still could) it would just draw the rectangle. but anki draws this weird green lines onto it.
so this rectangle was always drawn when the program startet. therefore i implementet an if-statement to only draw if the user clicked in a specific location. but then i got this:
5YxWVAe.png


ok, i don't have this strange green lines anymore, but where the hell are those dots coming from?

well, if anybody cares i, here is the script. if i can't resolve this in the next few this, i will just do it with java....
 

tokkun

Member
This here got me thinking, is your approach (shuffle a range of numbers and take a subset of it) equivalent to iterate over the grid, assign a random number to each field and manually check for and replace duplicates? Does it add any statistical bias to the distribution, compared to the usual approach?

That's a complex question that would require detailed knowledge about the pseudo-random number generators being used in each approach to attempt an answer.

If you assume that the RNG backing both the random permutation and the number generator are perfect, then the two approaches should be equivalent in terms of statistical bias.
 

phoenixyz

Member
wow, i think i start to hate python. first of all, i can't start python scripts via the python launcher anymore.
Python probably hates you back for deleting ex.show() from the main function ;)

starting the script with anki works. but anki gives renders some strange colors into my programm.
first this:
AcxYOkc.png


when i started it standalone (when i still could) it would just draw the rectangle. but anki draws this weird green lines onto it.
so this rectangle was always drawn when the program startet. therefore i implementet an if-statement to only draw if the user clicked in a specific location. but then i got this:
5YxWVAe.png


ok, i don't have this strange green lines anymore, but where the hell are those dots coming from?

well, if anybody cares i, here is the script. if i can't resolve this in the next few this, i will just do it with java....

I have no idea what anki is, but this code works perfectly for me (I use PySide, just change the import, should work fine). Well, assuming having a rectangle following your cursor is what you want (you didn't exactly say what your task is).
 
It's bias-free, even more obviously than the manual check and replace approach. And very efficient in this case.

If you needed unique random numbers from a large range, checking and replacing one by one is bad for performance. Using a hashtable or search tree would be the most clean and straightforward way to check what numbers are present already. If neither is available or space is at a premium, you could generate all numbers plus a few extra to account for possible duplicates, sort, remove all duplicates in one go, and shuffle. These can all be done in place.

That's a complex question that would require detailed knowledge about the pseudo-random number generators being used in each approach to attempt an answer.

If you assume that the RNG backing both the random permutation and the number generator are perfect, then the two approaches should be equivalent in terms of statistical bias.

Cool, thanks. Sadly, the statistics course I took didn't cover random number generation at all (it was even aimed at CS students only) and it's not really the kind of subject I read up on my spare time for fun.

I wish I could work with Scala. :(


I still find it tricky when I can displace the dot.

Code:
// works
grid map (_.mkString(" ")) mkString "\n"

// nope
grid map (_.mkString " ") mkString "\n"

// works
grid map (_ mkString " ") mkString "\n"
Is it because both the period and the parenthesis need to be removed? But then grid.map does need parenthesis, but you can omit the period.

I still haven't understood that either. If I'm not using an IDE, I just put dots everywhere, if I am, I just let IntelIiJ figure it out.
 

ominator

Neo Member
Python probably hates you back for deleting ex.show() from the main function ;)

Ha, oh man. but got it working with calling ex.show() in the initGUI().
still, calling it in the mainfunction is much better (and should be a nobrainer),, thanks.

I have no idea what anki is, but this code works perfectly for me (I use PySide, just change the import, should work fine). Well, assuming having a rectangle following your cursor is what you want (you didn't exactly say what your task is).

yes, this version I had before and worked. but I need to display it in a QPixmap/QImage, athorwise i can't read the pixeldata which i need for image comparison.

here is what i want to do: anki is a space repition card system. whith that you you create flashcards and learn languages,math or whatever you want. I want to create a Plugin in which the user is asked to draw a certain japanese kanji (oder chinese Hanzi or whatever the user wants to draw). the user should draw it with the mouse and the program checks via image comparison if he drew it correctly.

so, now i managed to create a pixmap and draw on it. next step is either to set up the gui/questions/paint panel or directly go to the image comparison function. but i think it will be the GUI.

thing is: I start the script alone and everything is fine. I start the script with anki and I get those strange colors. Howeve, I will continue programming it standalone and look for the anki-thing at the end.
 

Water

Member
Cool, thanks. Sadly, the statistics course I took didn't cover random number generation at all (it was even aimed at CS students only) and it's not really the kind of subject I read up on my spare time for fun.
This doesn't require any formal understanding of statistics (which I personally suck at!) to reason about. You just have to notice that in the process of generating all numbers of the range, performing a random shuffle, and picking whichever numbers happen to be first, every individual number is being treated the same way as every other number. If so, they must all have the same chance of ending up in the result set. There's just no opportunity for bias to come in.
 
I am looking for some general advice I would like to get into web development as a personal hobby over the next few months I have an idea for a Chrome extension I would like to write, can anyone suggest good web development / HTML /CSS books or anything which can guide me on my way to writing extensions.

I am not a programmer as a profession but I have written code previously I, so I am familiar with the basic concepts.
 
I'm having some annoying problems with Django, and it doesn't make it any better that I don't know the language at all... Anyway, I was given as a task to update the looks of a site a bit, just a simple HTML/CSS thing. From what I can see the site is built up from a template site that uses a lot of {% include "[part of site].html" %} tags inside of div tags. I've searched all the code and haven't found any mentions of those files anywhere else, it's stuff like header, menu, footer and so on. This has led me to believe that it's simply a matter of writing

<div id="whatever">
{% include "whatever.html" %}
</div>

and then it should load whatever.html into that part of the site. However, when I try to add new files it doesn't work, and as I said I can't see them mentioned anywhere else. Can anyone help me?

EDIT: I kind of found a solution. The only thing I wanted to do with that div tag was to put an image in it, and I managed to create an empty div tag and set the image as a background in the CSS file instead. But I might have to do more modifications to the site in the futures, so it'd be great if anyone had a solution to my original problem.
 

John_B

Member
I'm working on schema for a sports-like database (for a site where some friends and I compete in simple fantasy sports-like tournaments).

There are many matches in many tournaments in many seasons. And we play several seasons in a year. I'm a little unsure on how to design the season table. I need a simple way to retrieve the current season we play in.


  • 1. Have a season "start_date" and "end_date". Write a function that returns the season where the current date is within range of (overlapping dates could be a problem).
  • 2. Have a season boolean status. When a new season is created all the old seasons are updated to false and the new one is true (or have a manual switch on the site).
Any suggestions?
 

usea

Member
I am looking for some general advice I would like to get into web development as a personal hobby over the next few months I have an idea for a Chrome extension I would like to write, can anyone suggest good web development / HTML /CSS books or anything which can guide me on my way to writing extensions.

I am not a programmer as a profession but I have written code previously I, so I am familiar with the basic concepts.
I know that gaffer Andrex is pretty familiar with chrome extensions, but I don't think he looks at this thread. I know they're written in javascript, but I couldn't really tell you anything beyond what I'd glean from googling how to write chrome extensions.

I'm working on schema for a sports-like database (for a site where some friends and I compete in simple fantasy sports-like tournaments).

There are many matches in many tournaments in many seasons. And we play several seasons in a year. I'm a little unsure on how to design the season table. I need a simple way to retrieve the current season we play in.


  • 1. Have a season "start_date" and "end_date". Write a function that returns the season where the current date is within range of (overlapping dates could be a problem).
  • 2. Have a season boolean status. When a new season is created all the old seasons are updated to false and the new one is true (or have a manual switch on the site).
Any suggestions?
Are those parts of an assignment you have to do? Or are they possible approaches you've come up with?

Why are overlapping dates a problem? If seasons can overlap, then can't there be more than one current season?

The boolean option is not a good one. You're storing the current season across every row instead of only in one place. That sort of approach is better by having a current season table with one row in it, that points to the current season.

You should probably have dates on the seasons either way. Remember to consider time zones. Personally I only store dates as UTC everywhere.
 

John_B

Member
Are those parts of an assignment you have to do? Or are they possible approaches you've come up with?

Why are overlapping dates a problem? If seasons can overlap, then can't there be more than one current season?
Those were my own approaches. It's my personal site that is used by 20 friends.

Seasons are not supposed to overlap, but say a wrong date was entered. I guess I just have to check that a new season does not collide with the existing seasons before inserting it.

I think this works pretty well. I have to look into the UTC stuff.

Code:
CREATE TABLE `season` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `number` smallint(6) NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `number` (`number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SELECT * FROM season WHERE CURDATE() BETWEEN start_date AND end_date;
 
Totally forgot about this thread/community.

Since I haven't posted in ages I'll reintroduce myself.

I am 22 years old, graduated from a university of California this past June with a degree in CS. I was finally able to land a job in Quality Assurance. I was aiming for Software Development, but I think I might like this. Basically I'll be writing scripts that automate user input in a browser that tests our website and tries to find bugs.

ASAIK we're using Jscrpit (no not JavaScript), which is a language by Microsoft. We'll also be using a program called TestComplete.

Does anybody have experience in these two, or Q/A in general?
 
I'm working on a Level Editor in C++/SDL, but I can't think of how to organize my GUI Components in a nice OOP way.

The base class that every other GUI component is derived from is an MComponent which contains just basic information like its position, length, and width; also it will have virtual functions to Load, Update, Render, and Cleanup the component which will be implemented by the derived classes. However, not every GUI element will take in the same argument list for my load function. Some may have more than two states, some may display text ( and therefore need a font object ), and some may have multiple buttons/thumbs/otherGUIstuff.

Edit3: Searched around for a bit and I guess can just make the change the protection on the base class functions that I don't want accessed from public to private and not have to worry about any confusion. Still going to handle all my font changes in a separate class, but at least this way I'll be able to detail all the variable names in my function signature.



Nother question. Is it better to group parameters with structs or classes or would it be better to list out each argument even if the list may get WinAPI CreateWindow sized?

Edit: Came up with another solution myself. Probably just going to go the spritesheet route so I don't have a bajillion image files to load. Initially heard that it was probably better to load a bunch of smaller images than to blit only a small portion of a large surface, but it's not like my surfaces are going to be crazy huge anyway.
 

usea

Member
Those were my own approaches. It's my personal site that is used by 20 friends.

Seasons are not supposed to overlap, but say a wrong date was entered. I guess I just have to check that a new season does not collide with the existing seasons before inserting it.

I think this works pretty well. I have to look into the UTC stuff.

Code:
CREATE TABLE `season` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `number` smallint(6) NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `number` (`number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SELECT * FROM season WHERE CURDATE() BETWEEN start_date AND end_date;
Well, unless people from different time zones are going to be using it then the timezone thing is probably not that important.

Yeah, one approach is to not allow overlapping seasons. Another is to arbitrarily choose a season when they overlap (say, the later one). And optionally show a message.

I think your approach is pretty good, personally.
 

VoxPop

Member
Hey guys. I kinda wanted to do some programming as a hobby. I know absolutely nothing atm. Is there somewhere I should start? I did a couple of codecademy lessons though. Should I move onto somewhere else or stick with it?
 

Slavik81

Member
Hey guys. I kinda wanted to do some programming as a hobby. I know absolutely nothing atm. Is there somewhere I should start? I did a couple of codecademy lessons though. Should I move onto somewhere else or stick with it?

Code Academy is pretty good. I enjoyed doing some of the Project Euler questions. They're a rather clever set of math/programming puzzles.
 
Top Bottom