• 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

Just a note, it's more common to use < as your end condition rather than <=

When you're dealing with multi-dimensional arrays, you need nested loops.

I understand that I'll need nested loops, but how do I go about getting the sum of a row in a two-dimensional array in Java? I cant really seem to find anything online that I can understand well enough to implement myself.
 

Zoe

Member
I understand that I'll need nested loops, but how do I go about getting the sum of a row in a two-dimensional array in Java? I cant really seem to find anything online that I can understand well enough to implement myself.

I'm not really clear on what you're trying to do. Do you need an average for each row or an average for the entire multi-dimension array? How are you presenting the results?
 
I'm not really clear on what you're trying to do. Do you need an average for each row or an average for the entire multi-dimension array? How are you presenting the results?

Here is what I have.

Code:
		case 1: 
			for(int row=0; row<grades.length; row++){
				for(int col=0; col<grades[0].length; col++){
					sum+=grades[row][col];
				}//end inner
			}//end outer
			System.out.println("The average of Row 1 is" + (sum/2));

I want to get the sum of the rows in a two-dimensional array. I know that there will only be 2 numbers in each row, so I am dividing by 2.

So say if I have This array:
Code:
Row 0   50    50
Row 1   100   100
Row 2   75    75
Row 3   25   25
Row 4   30   30

When I process through this, I want it to give me the specific row I pick, for example Row 0, to print out "The Average of Row 0 is 50".


EDIT: With my code I am getting 54.0 for Row 0. Which is obviously not right.
 

Zoe

Member
If you're only looking for the average of an individual row, why do you need the nested loop?

You're processing all rows and columns in the code above.
 

SolKane

Member
Here is what I have.

Code:
		case 1: 
			for(int row=0; row<grades.length; row++){
				for(int col=0; col<grades[0].length; col++){
					sum+=grades[row][col];
				}//end inner
			}//end outer
			System.out.println("The average of Row 1 is" + (sum/2));

I want to get the sum of the rows in a two-dimensional array. I know that there will only be 2 numbers in each row, so I am dividing by 2.

So say if I have This array:
Code:
Row 0   50    50
Row 1   100   100
Row 2   75    75
Row 3   25   25
Row 4   30   30

When I process through this, I want it to give me the specific row I pick, for example Row 0, to print out "The Average of Row 0 is 50".


EDIT: With my code I am getting 54.0 for Row 0. Which is obviously not right.


OK, I don't know Java but what you need to do is have a variable in the inner loop which adds the values in the column. Then, at the end of the inner loop divide this value by the number of columns (that would be 2) for the average, and print that value to the console. Then reset this value to zero, so in the next run of the outer loop it will average the values of the next set of columns. These operations should all be within the scope of the outer loop.

Pseudocode:
Code:
for i in NUM_ROWS:
    for j in NUM_COLUMNS:
        column_sum += array[i][j]
    end
    column_sum /= NUM_COLUMNS
    print column_sum
    column_sum = 0
end
 
If you're only looking for the average of an individual row, why do you need the nested loop?

You're processing all rows and columns in the code above.

Gotcha, thats why I kept getting weird numbers I removed it and I have this now:
Code:
case 1: 
			for(int col=0; col<2; col++){
					sum+=grades[0][col];
				}

This appears to be getting me the correct average. Thanks for the help Zoe!
 

Zoe

Member
Now think about how else you could make it better. Why are you using case statements? Don't you think there's a more efficient way of doing it?
 
Now think about how else you could make it better. Why are you using case statements? Don't you think there's a more efficient way of doing it?

There probably is, I don't think I've learned it though. Are you suggesting charAt? They are the only 2 ways I currently know how to introduce choice.


QUick edit. Thank you also SolKane.
 
What is the best way to handle Python situations where you would normally use (in other languages) case/switch statements?

Maybe this is a noob question, but it seems like there is probably a more elegant solution than a bunch of 'if' statements. Is there a better way?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I would advise against buying programming books on an ereader. It just doesn't translate all that well.
 

r1chard

Member
What is the best way to handle Python situations where you would normally use (in other languages) case/switch statements?
In the simplest case you can use dictionaries (map value to callable action.) Otherwise you're going to be using if / elif which usually isn't *that* much more typing (though loses some of the semantics that are usually only used by people in error ;-)
 

injurai

Banned
Okay so I want to start a multiplat C++ projecct in Visual Studio 2010. What project do I use to create it.

Some options include:
Win32 Console Application
Win32 Project
Empty Project
CLR Console Application
CLR Empty Project

I love Sublime Text 2, but I prefer the development environment of IDEs when It comes to fast testing and prototyping.
 

nan0

Member
Okay so I want to start a multiplat C++ projecct in Visual Studio 2010. What project do I use to create it.

Some options include:
Win32 Console Application
Win32 Project
Empty Project
CLR Console Application
CLR Empty Project

I love Sublime Text 2, but I prefer the development environment of IDEs when It comes to fast testing and prototyping.

There's a bit more to it, since VS doesn't use makefiles (assuming you are talking about cross compiling it for Linux or something).
See here: http://stackoverflow.com/questions/...isual-studio-for-cross-platform-c-development
 

injurai

Banned
There's a bit more to it, since VS doesn't use makefiles (assuming you are talking about cross compiling it for Linux or something).
See here: http://stackoverflow.com/questions/...isual-studio-for-cross-platform-c-development

mmm, looks like this may be more trouble than its worth. Does Sublime Text 2 offer any sort of checkbug plug-ins?

edit: I guess another question would be. Couldn't I develop a Win32 application and just copy over the entire source code into another OS and recompile it there? Or maybe that is a bad practice...
 

nan0

Member
edit: I guess another question would be. Couldn't I develop a Win32 application and just copy over the entire source code into another OS and recompile it there? Or maybe that is a bad practice...

I guess that wouldn't work if you use .Net libraries, and I don't know if Microsoft's standard C++ libraries are compatible with other platforms. I did C++ on Windows and Unix with Eclipse and the CDT plugin, which worked quite well, but I don't know how good testing and prototyping is.
 

injurai

Banned
Anyone here use QT Creator for their C++ projects? I'm about to give up creating a multiplatform environment in windows out of frustration.

edit: Finally got MinGW to work how I wanted it to. What a bitch. Although discovering QT Creator has me intrigued.
 

Bollocks

Member
Anyone here use QT Creator for their C++ projects? I'm about to give up creating a multiplatform environment in windows out of frustration.

edit: Finally got MinGW to work how I wanted it to. What a bitch. Although discovering QT Creator has me intrigued.

here!
It has a very nice API and it's my goto framework if I want to write a C++ GUI application. Cross platform is just a bonus. I've used wxWidgets but nothing comes close to Qt creator.
Have fun
 

Risette

A Good Citizen
http://www.amazon.com/gp/product/B006GFZ288/?tag=neogaf0e-20

I have that one. Pretty good book. The ebook is actually fairly cheap.

Although if you want, you might be better off learning straight C initially. Objective-C is a superset of C, so it's just a layer on C itself. You can use C constructs with it. Especially if you feel like iOS development.
This one (Objective-C Programming: The Big Nerd Ranch Guide) is pretty cool too. It actually starts by going through some C before jumping into Objective-C.
I've used the Big Nerd Ranch iOS book and it was really good so I'd second looking into this one for getting some Obj-C knowledge.
Thanks, I'll check these out.

Is GNUstep good enough to use until I can get a Mac and get access to Cocoa? Mostly meaning, will there be any conflicts with what the book is trying to tell me to do if I'm not in a Mac environment? I'm running Linux (Debian Wheezy) on a PC at the moment.
 
A quick question for the experts here. I have a code snippet which obviously compiles fine but causes an exception during runtime because *pTest does not have a value yet:

Code:
#include <iostream>

int main()
{
	int *pTest = nullptr;
	std::cout << "pointer value: " << pTest << " value at this address: " << *pTest;
        return 0;
}

Is there a way to assign something similar to a nullptr/NULL/0 for the value for safety reasons? Of course if I start using the pointer and assign the address/value to a proper variable my problem goes away but I somehow feel not satisfied with this solution.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
You are not supposed to dereference nullptr/NULL, I think that's the problem here.
 

Roquentin

Member
Is there a way to assign something similar to a nullptr/NULL/0 for the value for safety reasons? Of course if I start using the pointer and assign the address/value to a proper variable my problem goes away but I somehow feel not satisfied with this solution.
No, that's how pointers work - NULL pointer means there's no value assigned.

You have to check the pointer before dereferencing it:
Code:
#include <iostream>

int main()
{
	int *pTest = NULL;
	std::cout << "pointer value: " << pTest << " value at this address: ";
	if (pTest != NULL)
		std::cout << *pTest;
	else
		std::cout << "NULL";
        return 0;
}

EDIT: Of course the fact that a pointer is != NULL doesn't mean the address it points to is valid.
 
You are not supposed to dereference nullptr/NULL, I think that's the problem here.

Well in a small program it is not a problem but within a bigger example I rather have dereference it to a value instead of throwing an exception sometimes during execution which I might not catch. I just thought that there might be something like NULL for dereferencation aswell.

No, that's how pointers work - NULL pointer means there's no value assigned.

You have to check the pointer before dereferencing it:
Code:
#include <iostream>

int main()
{
	int *pTest = NULL;
	std::cout << "pointer value: " << pTest << " value at this address: ";
	if (pTest != NULL)
		std::cout << *pTest;
	else
		std::cout << "NULL";
        return 0;
}

EDIT: Of course the fact that a pointer is != NULL doesn't mean the address it points to is valid.

I thought about that solution - and the even easier way where I just assign:

int aTest = 10;

int *pPointer = &aTest;

So I get a valid address and value back. I just thought if there is nullptr initialization for the address there might be one for the value aswell in the case I forget that the pointer was not used properly. It was just something I wanted to know because of curiosity. In the end a exception is better than just using "int pPointer;" and using it because that might even give back a valid address and value - debugging something like that can be a pain in the *bleep*. So basicly I asked for something which could end up causing more trouble than help. For my problem I would just use a test case with a list of my pointers and their address/values so if I see "00000000" for address and "0" for value I knew they are "empty"/not used.
 
Ever get that itch to code something but you're so creatively bankrupt you can't get the ball rolling? I get that a lot. I've been wanting to learn node.js for a while but for the life of me i can't come up with any ideas that'll motivate me to actually do it.
 

Tashi

343i Lead Esports Producer
Can someone explain how this Syntax works for Get/Set methods in C#?

Code:
public float size
{
get;
private set;
}

I've never seen it before today. How would I actually use these methods? Is it even technically a method?
 

mike23

Member
That is just an automatic property (added in C# 3.0?). Most people would just make that a single line seeing as you have no additional logic in your getter or setter yet.

http://msdn.microsoft.com/en-us/library/bb308966.aspx#csharp3.0overview_topic22

Plus, standard naming convention says that properties should be CamelCase


Code:
public float Size { get; private set; }

It's equivalent to:

Code:
// the compiler creates a hidden variable with an invalid name and it is hidden from you
// you can't access it through normal means
hidden float _size; 


public float Size
{
      get { return _size; }
      private set { _size = value; }
}
 

Tashi

343i Lead Esports Producer
Oh ok, thanks. I'm actually not used any of those. I've always done this:

Code:
public float getSize()
{
return size;
}

private void setSize(float size)
{
this.size = size;
}

I guess it's easier and cleaner but this way just makes more sense when I look at it.
 

Spoo

Member
Oh ok, thanks. I'm actually not used any of those. I've always done this:

Code:
public float getSize()
{
return size;
}

private void setSize(float size)
{
this.size = size;
}

I guess it's easier and cleaner but this way just makes more sense when I look at it.

The advantage of using the Get; Set; properties is that the client avoids writing what would look like a function call (it obviously is, but to them it appears like a simple public assignment). I actually avoid using them and write the way you do; mostly because I come from a C++ background, but also because I like to know when I'm calling a function vs. interacting with a public value. As far as encapsulation goes, though, it's a nice feature.
 
In the simplest case you can use dictionaries (map value to callable action.) Otherwise you're going to be using if / elif which usually isn't *that* much more typing (though loses some of the semantics that are usually only used by people in error ;-)

Thanks!
 

Harpuia

Member
Argh! I hate having to ask for help so much, but I haven't a clue, once again, what is wrong here:

Code:
#include <iostream>
#include <string>
using namespace std;

void plus()
{
	string plus="+";
	const int TEST=10;

	for(int count=1;count<=TEST;count++)
	{
	 cout<<plus<<endl;
	 plus=plus+"+";
	}
}

int main()
{
	plus();
	return 0;
}

basically when I compile it, for some reason I'm being told that that the reference to "plus" is ambiguous. Isn't the whole purpose of the void function type so that you don't have to enter parameters and it just executes?
 

dabig2

Member
Argh! I hate having to ask for help so much, but I haven't a clue, once again, what is wrong here:

basically when I compile it, for some reason I'm being told that that the reference to "plus" is ambiguous. Isn't the whole purpose of the void function type so that you don't have to enter parameters and it just executes?

It's because your function name and variable name are the same. This wouldn't be a problem in Java, but in C++ it is.

It's basically due to fact that C++ doesn't have separate name spaces for variable names and function names in memory.
 

SolKane

Member
Argh! I hate having to ask for help so much, but I haven't a clue, once again, what is wrong here:

basically when I compile it, for some reason I'm being told that that the reference to "plus" is ambiguous. Isn't the whole purpose of the void function type so that you don't have to enter parameters and it just executes?

dabig2 has cleared this up, but to clear up something which you said: the point of a void function is that it returns no values, not that it takes no parameters. Parameters are what is known to the function (in other words, they are the arguments you send to the function).
 

Minamu

Member
I have a C# quicksort that works but now I need to tweak it to support multithreading. The most obvious place for threading seems to be during the array splitting so both halves are sorted simultaneously but I'm not sure how to break it apart. I don't know how efficient my code is, I based it on something I googled. I assume that the palce to start at would be to decide on a pivot point, then split the array into two temporary arrays with the pivot in one of them, and then call the sorting algorithms on both arrays in different threads and then join them? But while that makes sure that the halves are sorted, they may not be when put together, right?
Code:
namespace ThreadedSort
{
	class Top
	{
		public static void Main()
		{
			QuickSort QSorter = new QuickSort();

			int[] UnsortedArray = { 2, 6, 9, 4, 5, 1, 7, 3, 8 };
			Console.WriteLine("Unsorted list:");
			Console.Write(string.Join("", UnsortedArray));
			Console.WriteLine();
			QSorter.MyArray = UnsortedArray;
			QSorter.tempElements = QSorter.MyArray.Length;

			QSorter.QuickSorter();
			Console.WriteLine("Threaded quicksort list:");
			for (int i = 0; i < QSorter.tempElements; i++)
			{
				Console.Write(QSorter.MyArray[i]);
			}
			Console.ReadKey();
		}
	}
}

Code:
namespace ThreadedSort
{
	public class QuickSort
	{
		public int[] MyArray = new int[9];
		public int tempElements;

		public void QuickSorter()
		{
			sort(0, tempElements - 1);
		}

		public void sort(int left, int right)
		{
			int pivot, leftSide, rightSide;
			leftSide = left;
			rightSide = right;
			pivot = MyArray[left];

			while (left < right)
			{
				while ((MyArray[right] >= pivot) && (left < right))
				{
					right--;
				}

				if (left != right)
				{
					MyArray[left] = MyArray[right];
					left++;
				}

				while ((MyArray[left] <= pivot) && (left < right))
				{
					left++;
				}

				if (left != right)
				{
					MyArray[right] = MyArray[left];
					right--;
				}
			}

			MyArray[left] = pivot;
			pivot = left;
			left = leftSide;
			right = rightSide;

			if (left < pivot)
			{
				sort(left, pivot - 1);
			}

			if (right > pivot)
			{
				sort(pivot + 1, right);
			}
		}
	}
}
 
Threading at the recursive calls seems fine. Since all the leftArray ones will be less than the pivot then they will still be sorted when you recombine. You can also multithread the for each statement if you want. This will mean each thread will have a different section of the array to test against the pivot - using OpenMP to do that is really easy.
 

injurai

Banned
Wow, I just learned private methods can't be reached from a subclass extending the parent class... I had no idea...

looks like you can just use package visibility, but I feel their should be an intermediate visibility level for private + extending classes.
 
Wow, I just learned private methods can't be reached from a subclass extending the parent class... I had no idea...

looks like you can just use package visibility, but I feel their should be an intermediate visibility level for private + extending classes.

Doesn't protected-class do just that? Or am I understanding that statement wrong...


Also, fuck Flex and fuck PureMVC
 
Protected is the entire package visibility + extension. There is nothing that is Private only to a class and it's extensions.

This is true in Java but afaik, C++ and C# treat protected like it should be done. Java has lots of weird design decisions like that. Although I guess the flipside of the argument is that a client should only be using the package of your api like a black box anyway, so it doesn't really matter from an external interface perspective. Protected may as well be base class and derived class only.

I hate java
 
Hey! Do you know any Java in here? I just started a course in Java programming and it's tough as shit. Do you think you could help me with two things?

This is the first: I have to create a program that every third second writes out the number 3. After 20 seconds this program is supposed to shut down.


This is the second: I have to write a program that through the ordinary scanner (java.util.Scanner in = new java.util.Scanner (System.in); I guess) lets me write in a bunch of integers and then saves them in binary in a file. Then the program wants to read the file with the integers in binary and show the integers and the sum of them.

Are these to doable? I'm so fucking lost and I would send a virtual BJ to anyone who can show me how these should be done in the easiest way possible.
 

injurai

Banned
This is true in Java but afaik, C++ and C# treat protected like it should be done. Java has lots of weird design decisions like that. Although I guess the flipside of the argument is that a client should only be using the package of your api like a black box anyway, so it doesn't really matter from an external interface perspective. Protected may as well be base class and derived class only.

I hate java

It seems every language has a bunch of poor design decisions. I'm not even sure what is considered the closest to a perfect language. Though java is nice to ease into OOP. I know we have enough language already, but I would like to see a new master race program come along that is developed by a whole bunch of universities and companies.
 
Hey! Do you know any Java in here? I just started a course in Java programming and it's tough as shit. Do you think you could help me with two things?

This is the first: I have to create a program that every third second writes out the number 3. After 20 seconds this program is supposed to shut down.


This is the second: I have to write a program that through the ordinary scanner (java.util.Scanner in = new java.util.Scanner (System.in); I guess) lets me write in a bunch of integers and then saves them in binary in a file. Then the program wants to read the file with the integers in binary and show the integers and the sum of them.

Are these to doable? I'm so fucking lost and I would send a virtual BJ to anyone who can show me how these should be done in the easiest way possible.

Both are doable. Post some code.

If you need a start for number one I would look into the currentTimeMillis function and for number 2 this should put you in the right direction.
 
Top Bottom