• 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

gcubed

Member
I learned through trudging, but I'm sure there's good tutorials out there somewhere.

Programming in Perl is definitely programming. Don't let anybody tell you different.

thanks. Most of it has been trial and error for me. The majority of my parsing is router configs and command outputs, which every vendor is different, so its basically force feeding me to figure it out, but i can do the coding pretty quick but it takes me all the extra time to figure out the proper regex

i'm sure the coding is ugly and inefficient, i need to force myself to learn how to create and reuse my subroutines.
 

FillerB

Member
I know this might be a bit off-topic and could be considered as stealth marketing (which I'll admit it kinda is) but I just got the following marketing video from the company I work at concerning the release of a new ARM-based chip/development platform.

And it is just so hilariously terrible (the video that is, the chip is pretty nice) that I just have to share it.

http://www.youtube.com/watch?v=IvFpdaDSMQs
 

leroidys

Member
This was voluntary and I was working from home. Just getting caught up on correcting some poor design and writing some (lots of) tests to cover it.



Head First Java and then into Effective Java should probably work well for you. If you're not fully confident in your OOP design skills, think about resources that cover OOP, design patterns*, etc. Head First is also good there (they go for a quirky presentation, but the material is actually pretty good), but also Gang of Four, Robert C. Martin, etc. Lots of good resources.

---

*I always feel the need to accompany the mention of "design patterns" with the cautionary note "don't become a slave to them and thinking in terms of what pattern to use instead of what problem to solve." I have found resources on patterns help introduce and sharpen design skills, but actual pattern usage in your code is better when it emerges almost completely on its own. Short version: don't be that guy that's always asking others "what pattern should I use here?" Shorter version: Especially don't be that "Singleton!" guy.

Thank you!
 

Minamu

Member
Are there any good XNA video tutorials out there? I'm done with my five lesser assignments but now I have a game to make basically. thenewboston.com has 200 C# videos that seem nice but it's not directed at XNA specifically.
 

exfixate

Member
i just started learning PERL (scripting i guess, not technically programming). Its becoming pretty valuable in my field (network engineering) and coming from a c++ background, good lord is it quick to write.

My nemesis though... regex. Any good documentation to help with regex knowledge or is just basically trudge through it and learn by pain?

I use http://rubular.com/ to quickly test the regular expressions I write. I imagine it would be a good learning tool as well. It's Ruby specific, but it'll help you pick up the REGEX fundamentals.
 

gcubed

Member
http://minus.com/lbpXhQEznIQOW1

^I used this tutorial for regex. I think it covers all the stuff you need to know in order to use regex effectively.

great, thanks for sharing

I use http://rubular.com/ to quickly test the regular expressions I write. I imagine it would be a good learning tool as well. It's Ruby specific, but it'll help you pick up the REGEX fundamentals.

yeah. i've found a few on the web (haven't used this one yet, will try, thanks), but the issues i've been working through have been when matching in loops and trying to pull out the proper data. I create a match that i think works well off of one or two static configs and all of a sudden some data changes and i get a different line. Trying to accommodate all possible variables in a certain instance is the pain...

And freaking + vs *. I know that very well know, but it was a pain point while getting aggravated a few weeks ago
 
Does anyone have any resources to better understand data structures like BST's, hash maps, etc both conceptually and in code. Just had my final in Data Structures on Monday and it made me realize how little I understand about how to code with recursion and pointers when it comes to those structures :/
 

cyborg009

Banned
VB or VB.net? Either way post it and I'm sure someone can help!

Well just VB

Code:
Dim returnDialogResult As DialogResult
        Dim messageString As String

        ' Confirm clear of current order.
        If AddShirtButton.Enabled = False Then
            messageString = "Is your order complete?"
            returnDialogResult = MessageBox.Show(messageString, "Clear order", _
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                MessageBoxDefaultButton.Button2)
        ElseIf returnDialogResult = DialogResult.Yes Then     'User said Yes.
            SmallRadioButton.Enabled = True
            SummaryButton.Enabled = True
            NameTextBox.Enabled = True
            OrderTextBox.Enabled = True
            ClearButton.Enabled = False
            CompleteButton.Enabled = False
            ExitButton.Enabled = True
            AddShirtButton.Enabled = False
            ' Clear the appropriate controls.
            NameTextBox.Clear()
            OrderTextBox.Clear()
            QuantityTextBox.Clear()
            ShirtPriceLabel.Text = String.Empty
            ExtendedPrieLabel.Text = String.Empty
            OrderTotalLabel.Text = String.Empty
            'rest order total
            OrderTotalDecimal = 0D
            'Calcuate customers
            CustomerCountInteger += 1
            With NameTextBox
                .Clear()
                .Enabled = True
                .Focus()
            End With


        End If

        If AddShirtButton.Enabled = True Then
            messageString = "Do you wish to discard these changes?"
            returnDialogResult = MessageBox.Show(messageString, "Clear order", _
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                MessageBoxDefaultButton.Button2)
        ElseIf returnDialogResult = DialogResult.Yes Then      'User said Yes.
            SmallRadioButton.Enabled = True
            SummaryButton.Enabled = True
            NameTextBox.Enabled = True
            OrderTextBox.Enabled = True
            ClearButton.Enabled = False
            CompleteButton.Enabled = False
            ExitButton.Enabled = True
            AddShirtButton.Enabled = False
            ' Clear the appropriate controls.
            NameTextBox.Clear()
            OrderTextBox.Clear()
            QuantityTextBox.Clear()
            ShirtPriceLabel.Text = String.Empty
            ExtendedPrieLabel.Text = String.Empty
            OrderTotalLabel.Text = String.Empty
            'rest order total
            OrderTotalDecimal = 0D
            'Calcuate customers
            CustomerCountInteger += 1
            With NameTextBox
                .Clear()
                .Enabled = True
                .Focus()
            End With
        End If

I swear this was working the other day... but apparently the second IF in the code only does the message box but doesn't process the enable/disable and clearing and etc...
 

usea

Member
Well just VB

I swear this was working the other day... but apparently the second IF in the code only does the message box but doesn't process the enable/disable and clearing and etc...
What is it supposed to do? What part of that is working, and what part isn't? Do you get an error message, or does it just not do what you want?

Gotta communicate these things or nobody has any idea what's up :)
 

cyborg009

Banned
What is it supposed to do? What part of that is working, and what part isn't? Do you get an error message, or does it just not do what you want?

Gotta communicate these things or nobody has any idea what's up :)

Sorry I'm pretty new to programming

The program itself is suppose to be used to calculate orders for shirts(includes Radio button for sizes, text box for quantity and checkboxes for extra stuff). The code above is to complete a customer order. When the button is press it completes the order and starts the program like new again. But the thing about the button is that it displays two different message boxes depending if another button is enable or disable.

The button works fine for one situation but other one doesn't process anything for the other.
 

CrankyJay

Banned
Well just VB

Code:
Dim returnDialogResult As DialogResult
        Dim messageString As String

        ' Confirm clear of current order.
        If AddShirtButton.Enabled = False Then
            messageString = "Is your order complete?"
            returnDialogResult = MessageBox.Show(messageString, "Clear order", _
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                MessageBoxDefaultButton.Button2)
        ElseIf returnDialogResult = DialogResult.Yes Then     'User said Yes.
            SmallRadioButton.Enabled = True
            SummaryButton.Enabled = True
            NameTextBox.Enabled = True
            OrderTextBox.Enabled = True
            ClearButton.Enabled = False
            CompleteButton.Enabled = False
            ExitButton.Enabled = True
            AddShirtButton.Enabled = False
            ' Clear the appropriate controls.
            NameTextBox.Clear()
            OrderTextBox.Clear()
            QuantityTextBox.Clear()
            ShirtPriceLabel.Text = String.Empty
            ExtendedPrieLabel.Text = String.Empty
            OrderTotalLabel.Text = String.Empty
            'rest order total
            OrderTotalDecimal = 0D
            'Calcuate customers
            CustomerCountInteger += 1
            With NameTextBox
                .Clear()
                .Enabled = True
                .Focus()
            End With


        End If

        If AddShirtButton.Enabled = True Then
            messageString = "Do you wish to discard these changes?"
            returnDialogResult = MessageBox.Show(messageString, "Clear order", _
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                MessageBoxDefaultButton.Button2)
        ElseIf returnDialogResult = DialogResult.Yes Then      'User said Yes.
            SmallRadioButton.Enabled = True
            SummaryButton.Enabled = True
            NameTextBox.Enabled = True
            OrderTextBox.Enabled = True
            ClearButton.Enabled = False
            CompleteButton.Enabled = False
            ExitButton.Enabled = True
            AddShirtButton.Enabled = False
            ' Clear the appropriate controls.
            NameTextBox.Clear()
            OrderTextBox.Clear()
            QuantityTextBox.Clear()
            ShirtPriceLabel.Text = String.Empty
            ExtendedPrieLabel.Text = String.Empty
            OrderTotalLabel.Text = String.Empty
            'rest order total
            OrderTotalDecimal = 0D
            'Calcuate customers
            CustomerCountInteger += 1
            With NameTextBox
                .Clear()
                .Enabled = True
                .Focus()
            End With
        End If

I swear this was working the other day... but apparently the second IF in the code only does the message box but doesn't process the enable/disable and clearing and etc...

This shouldn't work because the only way returnDialogResult is going to get set is in the IF...and you're trying to reference it again in the else if.

Try this:

Code:
  If AddShirtButton.Enabled = True Then
            messageString = "Do you wish to discard these changes?"
            returnDialogResult = MessageBox.Show(messageString, "Clear order", _
                MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                MessageBoxDefaultButton.Button2)
        If returnDialogResult = DialogResult.Yes Then      'User said Yes.
            SmallRadioButton.Enabled = True
            SummaryButton.Enabled = True
            NameTextBox.Enabled = True
            OrderTextBox.Enabled = True
            ClearButton.Enabled = False
            CompleteButton.Enabled = False
            ExitButton.Enabled = True
            AddShirtButton.Enabled = False
            ' Clear the appropriate controls.
            NameTextBox.Clear()
            OrderTextBox.Clear()
            QuantityTextBox.Clear()
            ShirtPriceLabel.Text = String.Empty
            ExtendedPrieLabel.Text = String.Empty
            OrderTotalLabel.Text = String.Empty
            'rest order total
            OrderTotalDecimal = 0D
            'Calcuate customers
            CustomerCountInteger += 1
            With NameTextBox
                .Clear()
                .Enabled = True
                .Focus()
            End With
        End If
    End If
 

cyborg009

Banned
This shouldn't work because the only way returnDialogResult is going to get set is in the IF...and you're trying to reference it again in the else if.

Try this:

Code:

Aww man thank you!

mind-blown-2.gif
 

hateradio

The Most Dangerous Yes Man
I started using Coffee Script today. I had been holding off on it since I genuinely like JS.

So far it's alright. I like how they imitated Ruby/Python, which makes code a bit cleaner. I don't like some of the ways the code is output, but ultimately it's fine.

I think I'll keep using it, especially for projects that I'll put on GitHub. However, I'll have to port them to CS first, and who knows how long that'll take.
 
Does anyone have any resources to better understand data structures like BST's, hash maps, etc both conceptually and in code. Just had my final in Data Structures on Monday and it made me realize how little I understand about how to code with recursion and pointers when it comes to those structures :/

I haven't used any particular resource other than wikipedia and the odd lecture note or programming text book, my recommendation is to just google something and attempt to build a structure or two yourself.

Start with simple structures like a linked list, and explore the use of recursion in accomplishing tasks like finding a particular element or deleting all the nodes on a list. EG deleting could be very simply accomplished like so:

Code:
void deleteNode(NodeType *node)
{
      if(node->nextNode != null)
      {
          deleteNode(node->nextNode);
      }
      free(node);
}

for tasks on BST's and HashMaps where you intend to iterate over the entire set (ie. deleting all nodes) the concept is no different. For a hashmap you'd iterate over the key set to get the pointers to the data memory allocations, free the data memory, then free the key. The exact implementation of this would depend on how your map was created, if the keys are stored in a linked list then it's just an extension of above to include free'ing the values.

Free'ing a BST would look something like:

Code:
void freeBST(BSTNode* node)
{
      if (node->leftNode != null)
      {
           freeBST(node->leftNode);
      } 
      
       if (node->rightNode != null)
      {
           freeBST(node->rightNode);
      }
      free(node)
}

so it will recurse down a branch until it hits a node with no left or right, free that node, then the recursion drops back to the previous node, if that has an unexplored branch it goes there and continues, otherwise it deletes the current node and falls back again.
 
Does anyone have any resources to better understand data structures like BST's, hash maps, etc both conceptually and in code. Just had my final in Data Structures on Monday and it made me realize how little I understand about how to code with recursion and pointers when it comes to those structures :/

Conceptually, most data structures are quite simple (Until it comes to self-balancing trees). If you don't understand the concepts, try some videos, or wikipedia, but most importantly, implement them yourself. Read about traversal with recursion, such as pre-order:

Code:
boolean BSTSearch(T item, Node current) {
    if (current == null) 
        return false;
    if (item.compareTo(current.item) == 0)
        return true;
    else if (item.compareTo(current.item) < 0)
        return BSTSearch(item, current.left);
    else
        return BSTSearch(item, current.right);
}
 
Would the following code (assuming faculty is implemented correctly) be valid to show the proper speedup by parallel computing? I currently get a speedup of 2 by using the Parallel.For in C#. I just used faculty because I couldn't think of something better. I started off with a primitive sorting algorithm - it took me a few minutes for my facepalm ;-)

Code:
Stopwatch Start
For-loop 10000 iterations
{
  For-loop 10000 iterations
    {
      faculty(10)
    }
}
Stopwatch End

Stopwatch Start
Parallel-For-loop 10000 iterations
{
  Parallel-For-loop 10000 iterations
    {
      faculty(10)
    }
}
Stopwatch End
 

usea

Member
What does faculty do? Does it have any side effects, or operate/depend on any data other than its input? Why are you doing nested loops instead of just a single for loop?

With the input being the same every time, it's kind of silly. You're probably going to get more benefit from the cpu cache in the first example, which would account for the only minor speedup. I mostly use parallel.foreach on occasions where I need to do some operation on a collection of items, and those operations are independent of each other.

For example, this would be a bad demonstration. Because you could obviously find the Fibbonacci sequence from 1 to 40 in a much better way.
Code:
Parallel.ForEach(Enumerable.Range(1,40), (i) =>
{
	Console.WriteLine(Fibbonacci(i));
});

But this might be a good one, though you need to be careful that any operations that could go wrong concurrently are synchronized, like adding/removing from lists or whatever:
Code:
Parallel.ForEach(particles, (p) =>
{
	p.Update(timeDelta);
});

FYI Parallel.Foreach doesn't necessarily run in parallel. The Task Scheduler determines to what degree of concurrency to execute the code, and may just do it one at a time instead of concurrently, if it decides it will get done more quickly that way. (this is usually not the case though) http://msdn.microsoft.com/en-us/library/dd537608.aspx
 
What does faculty do? Does it have any side effects, or operate/depend on any data other than its input? Why are you doing nested loops instead of just a single for loop?

With the input being the same every time, it's kind of silly. You're probably going to get more benefit from the cpu cache in the first example, which would account for the only minor speedup. I mostly use parallel.foreach on occasions where I need to do some operation on a collection of items, and those operations are independent of each other.

Faculty calculates in that case "10!" - 3 628 800, I just used that so I have something that takes some time otherwise I get not very comparable Stopwatch results. The loops just have been from something I tried previously. I could use any bogus function in the loop - I just want to see the speedup. It is not some real work I do - just fooling around with C#.

So if I understood you correctly the better thing would be to call fac(random number) each time so that cache doesn't have any influence on the time? I thought that with each iteration everything gets cleared anyway so it doesn't matter wether I calculate the same thing over and over again.
 

Chris R

Member
You might also want to see what the speed difference is if you only use Parallel for the outer loop. I threw together a quick little ditty and found a 2.67x speed improvement with the outer loop only being Parallel vs both loops being Parallel for a 1.99x improvement over plain for loops.

It really depends on what you are doing though.
 
You might also want to see what the speed difference is if you only use Parallel for the outer loop. I threw together a quick little ditty and found a 2.67x speed improvement with the outer loop only being Parallel vs both loops being Parallel for a 1.99x improvement over plain for loops.

It really depends on what you are doing though.

Wow just noticed the same:

4s versus 1.6 (only the outer loop is parallel) versus 2s versus both loops. Any ideas why?
 

RiccochetJ

Gold Member
Hey all,

I have a SQL Server question:

What's going to happen with my db growth when I have something happening like this?

Code:
BEGIN TRANSACTION
SELECT * INTO foo
FROM bar
DROP TABLE foo

SELECT * INTO foo
FROM bar
DROP TABLE foo
--COMMIT
I'm keeping it an open transaction for this example.
Say the table 'bar' has say 10MB of information. Will SQL hold onto an extra 20mb of information that happened when I wrote into that new table twice until the commit happens?

Edit: Figured out how to test this. Yup it does. Figured out how to test this with some data I had.
 

Kinitari

Black Canada Mafia
I really love jQuery, and it feels like there is always more I can do with it. That being said, it's giving me trouble right now. I won't go into details, I just wanted to vent - but basically I am trying to do a very convoluted selection, and while I know it's technically possible with jQ, I can't figure out where I am fucking up. Really what I need is better node structure, but this is a quick patch-job project and I don't have the time or energy for that. Sigh.

edit: alright, I'm officially stumped, so I'm going to ask for some help. Trying to select an attribute in a nearby node, and it's just not working out. This is the layout:

Code:
<li>
<a href="/whatever">
<img style="width: 160px; height: 120px;" alt="Beauty" title="Beauty" src="/whatever">
<div class="floatingBox">
<h1 class="thumbTitle">**Where I want the Title to appear**</h1>
</div>
</a>
</li>

essentially, the query I want to use would look like:

$j('.thumbTitle').append($j(this).parent().siblings('img').attr('title'));

I've tried a few different traversing methods, to no avail. I mean:

$j('.thumbTitle').append($j('img[title]').attr('title'));

Works - but it just finds the first img with a title in the DOM and puts that in all my "thumbTitle" boxes. So I figure moving up in the tree from each individual "thumbTitle" would be the better approach... just not working out.

edit: Worked around my issues, I just used an each loop on the list and worked from there. I guess it's neater/prettier this way but... fuck, I wish I knew why my other method wasn't working.
 
JQuery stuff.

You can do this if you define a function that extracts the needed element from the dom for each object in the jquery selector set:

Code:
var getImageTitle = function() 
{
    return $(this).parent().prev().attr('title');
}
$('.thumbTitle').text(getImageTitle);

Or you could inline it, but harder to read:

Code:
$('.thumbTitle').text(function(){return $(this).parent().prev().attr('title');});

.append() and .text() and all those methods can take a function that returns a string, html object or jquery object as an argument.
 

KageZero

Member
Hello, i have a problem with code for my homework. I had to implement queue with pointers and arrays(header files). The program is working for 99% percent but i have a problem with array implementation. It fails in recursion, but whats interesting is that it always happens after it calls itself for the 4 time. It works for 3 times but above that it always crashes at this point. With pointers it works without any problems and i can't find the error... Here are the header files and the recursion function from main program.
Code:
Header file array
struct klijent{
       unsigned short ai,bi,ci,di;
       char ime [20],prezime[20];
       unsigned short dan,mjesec,godina;
       float tekuci,devizni;
       };

struct banka{
       klijent el[10000];
       int front,rear;
       };

banka red,red_c,red_e;

int AddOne(int n) {
return((n+1)%10000);
}

klijent FrontQ (banka red) {
      return red.el[red.front];
}

void EnQueueQ (klijent x, banka &red) {
     red.rear=AddOne(red.rear);
     red.el[red.rear]=x;
}

void DeQueueQ (banka &red){
red.front=AddOne(red.front);}

bool IsEmptyQ (banka red) {
     if (AddOne(red.rear)==red.front) return true;
     return false;
}

void InitQ (banka &red) {
     red.front=0;
     red.rear=9999;
}

Code:
the function in main program
void zad_e(){
     if(IsEmptyQ(red)){cout<<"test return";return;}
     cout<<"AAA";
     klijent tekuci=FrontQ(red);
     cout<<"ZZZ!";
     DeQueueQ(red);
     cout<<"-------------";
     zad_e();
     cout<<endl<<"UDRIA SAN "<<endl;
     if(pom>0){
               pom--;
               cout<<"-------------- ";
               EnQueueQ(tekuci,red_e);
               }
     else EnQueueQ(tekuci,red);
     }
 
I've always used gcc via mingw (I'm on windows). I know a lot of people just use visual studio though.

I don't think it matters much for simple things.

All of the interesting work in C family languages is happening in Clang these days. You should write some dodgy code and compare the warnings you get at various levels in clang, gcc, and cl (visual studio), should be an interesting experiment. Comparing code-gen at various optimization levels would also be educational.

The visual studio compiler has a number of oddities. For example, it mangles class and struct names differently, which has unfortunate implications. Its warnings are also a bit unfortunate: it's missing some good ones, and will warn about some perfectly reasonable things. It doesn't have much in the way of c99 support, and the C++11 support is lacking. However, it's nicely integrated with Visual Studio so it's probably the easiest to start using. Microsoft's suite of tools are definitely its greatest strength.

gcc is quite good. It has ok C++11 support, and good warnings. It's the standard for Linux and is usable on Windows with mingw.

clang is new, but its focus on understandable error messages and C++11 support has found it quite a few fans. I'm not sure its optimizations are as good as gcc or msvc, but unless you're writing commercial software that's unlikely to matter.

There's a few more, like Intel's compiler. But I'd say those are the big three.

Hella late response, but thanks for this. I actually only just got around to choosing a compiler.

I settled on gcc with mingw, but I'm already having problems right out the gate.

I can compile something fine, but when I try to run it I get a libgcc_s_dw2-1.dll is missing error. I found a few answers online, but I can't understand any of them. Apparently linking statically to the library would fix the problem, but they're talking about changing options in code blocks, which I'm not using.
 

SolKane

Member
Hello, i have a problem with code for my homework. I had to implement queue with pointers and arrays(header files). The program is working for 99% percent but i have a problem with array implementation. It fails in recursion, but whats interesting is that it always happens after it calls itself for the 4 time. It works for 3 times but above that it always crashes at this point. With pointers it works without any problems and i can't find the error... Here are the header files and the recursion function from main program.
Code:
Header file array
struct klijent{
       unsigned short ai,bi,ci,di;
       char ime [20],prezime[20];
       unsigned short dan,mjesec,godina;
       float tekuci,devizni;
       };

struct banka{
       klijent el[10000];
       int front,rear;
       };

banka red,red_c,red_e;

int AddOne(int n) {
return((n+1)%10000);
}

klijent FrontQ (banka red) {
      return red.el[red.front];
}

void EnQueueQ (klijent x, banka &red) {
     red.rear=AddOne(red.rear);
     red.el[red.rear]=x;
}

void DeQueueQ (banka &red){
red.front=AddOne(red.front);}

bool IsEmptyQ (banka red) {
     if (AddOne(red.rear)==red.front) return true;
     return false;
}

void InitQ (banka &red) {
     red.front=0;
     red.rear=9999;
}

I don't know what the exact bug is, but there are some things you could think about. In your FrontQ and IsEmptyQ functions you're passing by value instead of reference, but I'm not sure why you do it in these functions but not the others. It seems like it would improve your code if you changed these to pass by reference, so you don't have to make a copy every time you call these functions.

I think there may be a bug in your InitQ function. So, here you initialize the front to the 0th place and the rear to 9999th place, or the very end. But when you enqueue a 'klijent' struct, you increment the rear by 1. So, when you enqueue the first klijent, your front and rear indexes will both be 0, meaning it will appear to be empty if you call the IsEmptyQ function. When I was learning array-based queues we initialized front and back both to 0.
 

KageZero

Member
Thx, but the code works it seems like it was a bug in code block compiler. A friend tried the code in visual studio and it works fine there..
 
Probably (another) stupid question. I want to sort the same array with different algorithms - I just created 1 random array and wanted to save that in multiple others, so I can use them wheneve I want and in the end for comparison.


Code:
            Console.WriteLine("How many random numbers you want to sort: ");
            string userInput = Console.ReadLine();
            int input = Convert.ToInt32(userInput);

            // array creation
            int[] array = new int[input];

            // random data creation
            Random element = new Random();

            for (int i = 0; i < input; i++)
            {
                array[i] = element.Next(0, 10000);           
            }

            // saving the same array for every algorithm
            int[] testData0 = new int[input];
            int[] testData1 = new int[input];
        
            testData0 = array;
            testData1 = array;
                      
            Array.Sort(testData0);

Why are both testData0 and testData1 sorted after the last line? I debugged it and both arrays are created, first NULL and then they have the unsorted values stored in them. After that internal C# sort method both are sorted. C# magic or is my hangover clouding my judgement? Is testData0 = array just some reference instead of a own copy.
 
Probably (another) stupid question. I want to sort the same array with different algorithms - I just created 1 random array and wanted to save that in multiple others, so I can use them wheneve I want and in the end for comparison.


-snip-

Why are both testData0 and testData1 sorted after the last line? I debugged it and both arrays are created, first NULL and then they have the unsorted values stored in them. After that internal C# sort method both are sorted. C# magic or is my hangover clouding my judgement?

Uh, arrays are Objects, so, when you set testData0 and testData1 to variable array, testData0 and testData1 become aliases. Thus, everything you do testData0 or array is done to testData1 and vice versa.
 

CrankyJay

Banned
Probably (another) stupid question. I want to sort the same array with different algorithms - I just created 1 random array and wanted to save that in multiple others, so I can use them wheneve I want and in the end for comparison.


Code:
            Console.WriteLine("How many random numbers you want to sort: ");
            string userInput = Console.ReadLine();
            int input = Convert.ToInt32(userInput);

            // array creation
            int[] array = new int[input];

            // random data creation
            Random element = new Random();

            for (int i = 0; i < input; i++)
            {
                array[i] = element.Next(0, 10000);           
            }

            // saving the same array for every algorithm
            int[] testData0 = new int[input];
            int[] testData1 = new int[input];
        
            testData0 = array;
            testData1 = array;
                      
            Array.Sort(testData0);

Why are both testData0 and testData1 sorted after the last line? I debugged it and both arrays are created, first NULL and then they have the unsorted values stored in them. After that internal C# sort method both are sorted. C# magic or is my hangover clouding my judgement?

Because I don't think testData0 and testData1 are copies, I believe they're just pointing to where "array" is in memory.

Try using array.Copy()...so try the below and see if that gives you the output you were expecting

testData0 = array.Copy();
testData1 = array.Copy();

edit: Sorry, looks like Array.Copy() is a static function where you can put your input/output
 

usea

Member
Why are both testData0 and testData1 sorted after the last line? I debugged it and both arrays are created, first NULL and then they have the unsorted values stored in them. After that internal C# sort method both are sorted. C# magic or is my hangover clouding my judgement? Is testData0 = array just some reference instead of a own copy.
You only make one array. So, it doesn't matter how many variables you point at it, there's still only the one array in existence.
 
Thanks mugurumakensei, CrankyJay and usea - 2 aspirin later it all makes sense now. Luckily I still feel a bit sick that makes the embarrassment easier to bare.

Edit: I now used Array.Copy(array, testData0, input); where array is the original source, testData0 is the target and input is the number of elements you want to copy. On first glance that seems to work - C# internal (unstable QuickSort) sort is the fastest, followed by heapsort and last is bubblesort (assuming the array is not already sorted that should be true).
 

Cindres

Vied for a tag related to cocks, so here it is.
Aha! This will be the best place to ask.

Anyone here know of any genuinely good XNA and/or Kinect programming books that are available on Kindle? Getting one for Xmas and I really need some good books on the matter so Kindle ones would be fantastic.
 
Java/Network gaf i need your help:

I wrote a little java program that establishes a socket connection (port 23456) over TCP between a server (pong.java) and a client (ping.java). I start the server and then the client which sends ping and the server responds with pong. This happens 50 times.

This works all fine but now i want to shut this down using a SYN Flood DoS attack with hping3, but i can't get it to work. I can easily stop a file transfer running between the client and the server over SMB with the same DoS program. The server definitely gets the SYN packages- When i attack the same port the java socket connection uses it just shuts the attack down and the java program happily finishes the 50 loops. i can't figure out why. is there some protection in java or do sockets in java work different than a TCP exchange over SMB?

I do this for a network class and i just can't figure it out. I just attack myself between 3 VMs so no one will get harmed.

I can provide the source code or further information if needed. This is not graded homework or anything so you won't do my homework for me :).


Thanks a lot if anyone can help.

edit: edited out a lot of typos.
 

leroidys

Member
F#$& YEAH! I got a B in my waking-nightmare systems programming course that was failed by 50% of the class.

With that out of the way, I'm looking for internships to apply to (western washington area), specifically for this coming summer.

Does anyone have any good resources or advice for searching for internships? (Or any possible leads)?
 
F#$& YEAH! I got a B in my waking-nightmare systems programming course that was failed by 50% of the class.

With that out of the way, I'm looking for internships to apply to (western washington area), specifically for this coming summer.

Does anyone have any good resources or advice for searching for internships? (Or any possible leads)?

Best resource will likely be your university. My alma mater, UTD, had a nice internship and co-op program specially for engineering and comp sci guys.
 

Tashi

343i Lead Esports Producer
Are there any good XNA video tutorials out there? I'm done with my five lesser assignments but now I have a game to make basically. thenewboston.com has 200 C# videos that seem nice but it's not directed at XNA specifically.

https://www.youtube.com/user/Whiplashx86/videos?flow=grid&view=1

There are some decent ones here. I'm in a similar boat right now. Building a game and learning XNA as I go. I mainly get all my resources from videos and my books. Also, the Indie Development Thread on GAF is a great community.
 
F#$& YEAH! I got a B in my waking-nightmare systems programming course that was failed by 50% of the class.

With that out of the way, I'm looking for internships to apply to (western washington area), specifically for this coming summer.

Does anyone have any good resources or advice for searching for internships? (Or any possible leads)?

Hm, this almost makes me want to advertise for our internships on GAF. It's hardcore systems programming though, we had two phd candidates last year, but we've had talented undergraduates before. If any of ProgrammingGAF is interested in interning in the games industry shoot me a PM.
 
C#. I need to flip the parallelogram vertically when 'R' is pressed. I'm told to use matrices but I have no idea how to do that. I don't know if I should expect anything from here because most of the questions I've seen are pretty basic, but who knows.
http://pastebin.com/UawaHEGF
 

gblues

Banned
Hello, i have a problem with code for my homework. I had to implement queue with pointers and arrays(header files). The program is working for 99% percent but i have a problem with array implementation. It fails in recursion, but whats interesting is that it always happens after it calls itself for the 4 time. It works for 3 times but above that it always crashes at this point. With pointers it works without any problems and i can't find the error... Here are the header files and the recursion function from main program.
Code:
Header file array
struct klijent{
       unsigned short ai,bi,ci,di;
       char ime [20],prezime[20];
       unsigned short dan,mjesec,godina;
       float tekuci,devizni;
       };

struct banka{
       klijent el[10000];
       int front,rear;
       };

banka red,red_c,red_e;

int AddOne(int n) {
return((n+1)%10000);
}

klijent FrontQ (banka red) {
      return red.el[red.front]; [b]// potential null pointer deference if red is null or red.el is null[/b]
}

void EnQueueQ (klijent x, banka &red) {
     red.rear=AddOne(red.rear);[b]// no range checking done. potential overflow if trying to queue >10000 entries.[/b]
     red.el[red.rear]=x;
}

void DeQueueQ (banka &red){
red.front=AddOne(red.front);
}

bool IsEmptyQ (banka red) {
     if (AddOne(red.rear)==red.front) return true;
     return false;
}

void InitQ (banka &red) {
     red.front=0;
     red.rear=9999;[b]// shouldn't the "rear" be the index of the last item in the queue? This seems to be initializing the queue to be completely full, so that the first entry triggers an overflow. It might work in practice, but logically it does not make sense because now you have no way to catch when your list is actually full.[/b]
}

Code:
the function in main program
void zad_e(){
     if(IsEmptyQ(red)){cout<<"test return";return;}
     cout<<"AAA";
     klijent tekuci=FrontQ(red);
     cout<<"ZZZ!";
     DeQueueQ(red);
     cout<<"-------------";
     zad_e();
     cout<<endl<<"UDRIA SAN "<<endl;
     if(pom>0){
               pom--;
               cout<<"-------------- ";
               EnQueueQ(tekuci,red_e);
               }
     else EnQueueQ(tekuci,red);
     }

See my comments in bold. I suspect the reason it works in another compiler is due to platform-specific ways that memory is initialized, which allows it to work in one case but fails in the other.
 
Top Bottom