• 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

Garcia

Member
Yeah, Eclipse is horrible. It's the equivalent of your government in an IDE: built by committee, does everything for everyone in 10 different ways, bloated, hard to find your way around and the documentation is incomplete, misleading and inscrutable, when it's not flat-out outdated. : ) Once you know your way around for what you want to do though, it gets the job done. And there are tons of cool plugins.

Sadly, your assessment is right when you say it's pretty common. Its main advantage is the huge community around it. So, it's a good idea to learn it. If you're a student, I recommend getting your hands on IntelliJ, it's the industry favorite. Never heard of DrJava.

Now for the matter at hand. What I do when I want to run a "quick test in Eclipse":
1. I start a Java project : File -> New -> Java Project
2. Type the name, etc.
3. Finish
3. Once the project is created, expand the project folder
4. Right-click on the src folder
5. Choose New... -> Class in the contextual menu
6. Give it a name.
7. Tick the box that says "Generate main method" or something like that.
8. Finish
9 Type your code in the main method of the class that has been generated.
10. When you're ready to run it, right-click in the editor window.
11. From the contextual menu, choose Run As... -> Java Application
12. If you have print outs (or exceptions!), they appear in the Console window below.

I'm still using Eclipse as well for the lessons of Java I'm taking, but I would like to know which would be the best compiler for Java out there. Is there any program that is the most accessible and straightforward to use and understand? Best performance, etc?

Thanks in advance.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I'm still using Eclipse as well for the lessons of Java I'm taking, but I would like to know which would be the best compiler for Java out there. Is there any program that is the most accessible and straightforward to use and understand? Best performance, etc?

Thanks in advance.

My favorite for Java is IntelliJ IDEA. There is a community edition on JetBrains' website that is free to use. Not sure what kind of student setup they have for the paid version though.

http://www.jetbrains.com/idea/
 
My favorite for Java is IntelliJ IDEA. There is a community edition on JetBrains' website that is free to use. Not sure what kind of student setup they have for the paid version though.

http://www.jetbrains.com/idea/

academic license for 13 is $99. Community edition is still pretty neat though, most students I know are using that.

i scored the full version back during the end-of-the-world sale and though i've only just started using it this year, since i spent pretty much all of last year working in C, it's the bomb.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
academic license for 13 is $99. Community edition is still pretty neat though, most students I know are using that.

i scored the full version back during the end-of-the-world sale and though i've only just started using it this year, since i spent pretty much all of last year working in C, it's the bomb.

Ahh, thanks for clearing that up.

I've been using it since before I started school last year, and I haven't had any problems with it yet. Very much enjoy using it.
 

mltplkxr

Member
I'm still using Eclipse as well for the lessons of Java I'm taking, but I would like to know which would be the best compiler for Java out there. Is there any program that is the most accessible and straightforward to use and understand? Best performance, etc?

Thanks in advance.
Do you mean compiler or IDE? Eclipse is not a compiler, it's an IDE, a specialized text editor. When you compile code, it calls the javac compiler, which comes with the JDK.
If you mean IDE, then as others have noted above, IntelliJ is the top IDE.
If you really mean compiler, then I don't know. I never did a comparison of the different JVMs and compilers out there. Have you tried OpenJDK?
 

Garcia

Member
Do you mean compiler or IDE? Eclipse is not a compiler, it's an IDE, a specialized text editor. When you compile code, it calls the javac compiler, which comes with the JDK.
If you mean IDE, then as others have noted above, IntelliJ is the top IDE.
If you really mean compiler, then I don't know. I never did a comparison of the different JVMs and compilers out there. Have you tried OpenJDK?

Thank you for the correction, I meant IDE instead of compiler.

My favorite for Java is IntelliJ IDEA. There is a community edition on JetBrains' website that is free to use. Not sure what kind of student setup they have for the paid version though.

http://www.jetbrains.com/idea/

IntelliJ IDEA gets my vote as well. The community edition is just fine.

Thanks guys!
 

PlayDat

Member
Yeah, Eclipse is horrible. It's the equivalent of your government in an IDE: built by committee, does everything for everyone in 10 different ways, bloated, hard to find your way around and the documentation is incomplete, misleading and inscrutable, when it's not flat-out outdated. : ) Once you know your way around for what you want to do though, it gets the job done. And there are tons of cool plugins.

Sadly, your assessment is right when you say it's pretty common. Its main advantage is the huge community around it. So, it's a good idea to learn it. If you're a student, I recommend getting your hands on IntelliJ, it's the industry favorite. Never heard of DrJava.

Now for the matter at hand. What I do when I want to run a "quick test in Eclipse":
1. I start a Java project : File -> New -> Java Project
2. Type the name, etc.
3. Finish
3. Once the project is created, expand the project folder
4. Right-click on the src folder
5. Choose New... -> Class in the contextual menu
6. Give it a name.
7. Tick the box that says "Generate main method" or something like that.
8. Finish
9 Type your code in the main method of the class that has been generated.
10. When you're ready to run it, right-click in the editor window.
11. From the contextual menu, choose Run As... -> Java Application
12. If you have print outs (or exceptions!), they appear in the Console window below.

Thanks. I'm able to get that far. The trouble I'm having now is figuring out how to organize my directory.

The course I took introduced us to graphics programming. Our teacher provided us with the code for 3 separate classes created by a professor at the University of Roskilde. I had a lot of fun making some simple 2d games (Connect 4, Tic Tac Toe, Hangman) with them.

When I did these in DrJava, I had to make sure that the game I was making (tictactoe.java for example) was in the same folder as the files from the Roskilde professor. I'm not sure if that IDE was looking for the class files or the Java files since DrJava always spits out the class files into the same folder.

When I try running the exact same file in Eclipse (different folder same contents) I get the error "JBox (one of the three from the Roskilde professor) cannot be resolved to a type." One obvious solution would be to copy the professor's code into my tictactoe.java, but that seems kind of sloppy. I'd like to get more comfortable working with multiple separate classes at a time since the object oriented stuff is what I've had the most fun doing.

Yesterday I started working on minesweeper. It'll be as faithful of a recreation as possible of the one that comes with Windows. I've gotten most of the groundwork done, but now when it comes to implementing the GUI, I'm having issues since that involves using the tools the professor made.

This time I'm working in NetBeans and the error I'm getting is "Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: minesweeper.JBox" That happens when I try running the main method in Minesweeper.java

I tried running Minesweeper.java in DrJava. It works just fine in there but only after I comment out the the first line "package minesweeper;" NetBeans included that line automatically. I would have never written that since the courses I've taken so far haven't dealt with packages at all.

I'm assuming that could all be sorted out if I knew how to organize the directory. Any ideas on where JBox.java needs to be saved to so I can create instances and call functions from it? Sorry if this ended up being super long. Hope I was clear.
 
I have a question related to multi-dimensional arrays. I'm not sure if it makes a difference, but I'm working in C.

When I create a multi-dimensional array, the rows are automatically set at a 32 byte offset from each other. Using int (4 bytes), I can have up to 6 columns which leaves 8 bytes of padding between rows. However, if I add a column the offset between rows increases by 16 bytes. This pattern continues with the threshold increasing by 16 bytes whenever there is less than 8 bytes of padding.

The stride of an array is about as close as I've come to solving why this happens. I don't think this is the full answer though as that refers to the offset from the beginning of the rows. Could anybody help point me in the right direction?
 

Water

Member
I have a question related to multi-dimensional arrays. I'm not sure if it makes a difference, but I'm working in C.

When I create a multi-dimensional array, the rows are automatically set at a 32 byte offset from each other. Using int (4 bytes), I can have up to 6 columns which leaves 8 bytes of padding between rows. However, if I add a column the offset between rows increases by 16 bytes. This pattern continues with the threshold increasing by 16 bytes whenever there is less than 8 bytes of padding.

The stride of an array is about as close as I've come to solving why this happens. I don't think this is the full answer though as that refers to the offset from the beginning of the rows. Could anybody help point me in the right direction?

Are you just curious why this is happening, or is the layout something you have an actual need to control?

I'm pretty sure this is something in the hands of the compiler and not dictated by the language standard; it'll do whatever magic that it thinks will make the program faster. That will depend on the architecture the program is being compiled for (for instance: are you compiling for a 64-bit environment?), as well as optional compiler settings. One thing that may be motivating the compiler is that it tries to lay things out so they fit neatly onto cache lines. You could look at your compiler options for packing, try to flip a few of them and see what happens. Another thing you could do is read that "padding" space and see if the compiler is putting something in there for its own purposes.

Someone here who actually knows something about low-level stuff might have a better idea. However I think you should at least specify compiler, settings, and architecture.
 

Cindres

Vied for a tag related to cocks, so here it is.
I have a bit of an issue that I feel's gonna be easy to fix but this is somehow the first time I've ever had to do network stuff in Java. Can't believe in 4 years my degree never taught me this, but anyway.

Basically I have this class called "Broker" which creates Transaction objects and continuously sends them over the network until you manually stop it. The problem I'm having is that after I run it a few times to test it, or not even that, I'll get "No buffer space available (maximum connections reached?)". Now what I'm assuming is that because I'm constantly creating new sockets and closing them it's using up the connections.
Code:
	public void run() {

		Random rand = new Random();
		
		while (true) {
			try {
				
				Socket socket = new Socket("localHost", 1337);
				System.out.println("Broker Connected");
			
				ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
				
				//randomize a value.
				double val = rand.nextInt((140 - 60) + 1) + 60;
				
				//Randomize a sell or buy.
				double typeVal = Math.random();
				char type = 'A';
				if (typeVal > 0.5) {
					type = 'S';
				} else {
					type = 'B';
				}
				
				//Randomize a quantity.
				int quant = rand.nextInt((70 - 20) + 1) + 20;
				quant *= 100;
				
				Transaction transaction = new Transaction(type, quant, val);
				
				System.out.println("Object to be sent = " + transaction.toString());
				outputStream.writeObject(transaction);
				System.out.println("Object sent from: " + id);
			
	
				socket.close();
				
				int randSleep = (int) (Math.random() * 500 + 1500);
				Thread.sleep(0);
				
			} catch (SocketException se) {
				
				se.printStackTrace();
			
			} catch (IOException e) {
				
				e.printStackTrace();
			
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}

There/s the code snippet, it's runnable so I can have as many of these things firing off but after say 10 seconds I've sent ~5-6000 transactions which I can only assume means that many sockets have been opened.

I'm trying to do this in a way that means I only have to create/close the socket once but I'm not having any luck due to the try/catch clauses necessary.
 
I have a bit of an issue that I feel's gonna be easy to fix but this is somehow the first time I've ever had to do network stuff in Java. Can't believe in 4 years my degree never taught me this, but anyway.

Basically I have this class called "Broker" which creates Transaction objects and continuously sends them over the network until you manually stop it. The problem I'm having is that after I run it a few times to test it, or not even that, I'll get "No buffer space available (maximum connections reached?)". Now what I'm assuming is that because I'm constantly creating new sockets and closing them it's using up the connections.
Code:

There/s the code snippet, it's runnable so I can have as many of these things firing off but after say 10 seconds I've sent ~5-6000 transactions which I can only assume means that many sockets have been opened.

I'm trying to do this in a way that means I only have to create/close the socket once but I'm not having any luck due to the try/catch clauses necessary.

You could initialize a static socket in a static { } block in whatever class would be appropriate. I imagine you'd have to synchronize the access to that static socket so that multiple threads don't try to write to it at the same time. Also, not sure if that's intentional, but you're computing a random time to sleep at the end of the function but you actually do Thread.sleep(0).

edit: You could also sublcass Runnable and pass the one socket to it as a constructor argument. Probably more idiomatic than a static socket in some class.
 

Cindres

Vied for a tag related to cocks, so here it is.
You could initialize a static socket in a static { } block in whatever class would be appropriate. I imagine you'd have to synchronize the access to that static socket so that multiple threads don't try to write to it at the same time. Also, not sure if that's intentional, but you're computing a random time to sleep at the end of the function but you actually do Thread.sleep(0).

edit: You could also sublcass Runnable and pass the one socket to it as a constructor argument. Probably more idiomatic than a static socket in some class.

My problem then is that the socket Still needs closing and if I don't then it throws errors. Though I can give it a try.

Also at the moment the random not being used is intentional. Just left it there for later.
 
Are you just curious why this is happening, or is the layout something you have an actual need to control?

I'm pretty sure this is something in the hands of the compiler and not dictated by the language standard; it'll do whatever magic that it thinks will make the program faster. That will depend on the architecture the program is being compiled for (for instance: are you compiling for a 64-bit environment?), as well as optional compiler settings. One thing that may be motivating the compiler is that it tries to lay things out so they fit neatly onto cache lines. You could look at your compiler options for packing, try to flip a few of them and see what happens. Another thing you could do is read that "padding" space and see if the compiler is putting something in there for its own purposes.

Someone here who actually knows something about low-level stuff might have a better idea. However I think you should at least specify compiler, settings, and architecture.

Curiosity. I would like to work low-level so this interests me. All the padding is just zeroed bits on my machine.

Compiler: gcc 4.9.0
Architecture: x86_64
Environment: Arch Linux 3.14-4-1

I'm not specifying any flags other than '-g' for debug.
 

NotBacon

Member
There/s the code snippet, it's runnable so I can have as many of these things firing off but after say 10 seconds I've sent ~5-6000 transactions which I can only assume means that many sockets have been opened.

I'm trying to do this in a way that means I only have to create/close the socket once but I'm not having any luck due to the try/catch clauses necessary.

You have lingering socket connections. Either:

-Use a larger wait like Thread.sleep(1000)

-Or just create your socket outside the loop.

Like
Code:
try {

    // make socket

    while(true) {}

    // close socket

} catch() {}
 

mltplkxr

Member
There/s the code snippet, it's runnable so I can have as many of these things firing off but after say 10 seconds I've sent ~5-6000 transactions which I can only assume means that many sockets have been opened.
Is it because you're never closing that OutputStream? You should have a finally clause at the end of your try/catch to close that stream, or use a try-with-resouces if you're working with Java 7 +.
 

Water

Member
Curiosity. I would like to work low-level so this interests me. All the padding is just zeroed bits on my machine.

Compiler: gcc 4.9.0
Architecture: x86_64
Environment: Arch Linux 3.14-4-1

I'm not specifying any flags other than '-g' for debug.
When I replied last time, I had my C fundamentals horribly mixed up. Now my head is clearer on C but I have no idea what you could possibly do to get that result. Please post the code that creates and initializes your array.
 

Cindres

Vied for a tag related to cocks, so here it is.
You have lingering socket connections. Either:

-Use a larger wait like Thread.sleep(1000)

-Or just create your socket outside the loop.

Like
Code:
try {

    // make socket

    while(true) {}

    // close socket

} catch() {}

That would give me an unreachable code error because it's after the while(true)

Is it because you're never closing that OutputStream? You should have a finally clause at the end of your try/catch to close that stream, or use a try-with-resouces if you're working with Java 7 +.

I'll give that a try when I get back, main issue is that it didn't seem to like writing to the socket again.
 

mltplkxr

Member
When I did these in DrJava, I had to make sure that the game I was making (tictactoe.java for example) was in the same folder as the files from the Roskilde professor. I'm not sure if that IDE was looking for the class files or the Java files since DrJava always spits out the class files into the same folder.

When I try running the exact same file in Eclipse (different folder same contents) I get the error "JBox (one of the three from the Roskilde professor) cannot be resolved to a type." One obvious solution would be to copy the professor's code into my tictactoe.java, but that seems kind of sloppy. I'd like to get more comfortable working with multiple separate classes at a time since the object oriented stuff is what I've had the most fun doing.
This sounds like you didn't configure the build path: configuring where to find the dependencies in your project.

Yesterday I started working on minesweeper. It'll be as faithful of a recreation as possible of the one that comes with Windows. I've gotten most of the groundwork done, but now when it comes to implementing the GUI, I'm having issues since that involves using the tools the professor made.

This time I'm working in NetBeans and the error I'm getting is "Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: minesweeper.JBox" That happens when I try running the main method in Minesweeper.java

I tried running Minesweeper.java in DrJava. It works just fine in there but only after I comment out the the first line "package minesweeper;" NetBeans included that line automatically. I would have never written that since the courses I've taken so far haven't dealt with packages at all.
Sounds like you need to re-read on packages ; )
http://docs.oracle.com/javase/tutorial/java/package/managingfiles.html
 
When I replied last time, I had my C fundamentals horribly mixed up. Now my head is clearer on C but I have no idea what you could possibly do to get that result. Please post the code that creates and initializes your array.

Code:
#include <stdio.h>
#include <stdlib.h>

const static int ROWS = 5;
const static int COLUMNS = 2;
const static int ARCH = sizeof(int);


int main(void){
	int i;
	int** test_list = NULL;

        //----INIT----
	test_list = (int**)malloc(sizeof(int*) * ROWS);
	for(i = 0;i < ROWS;i++){
		*(test_list + i) = (int*)malloc(sizeof(int) * COLUMNS);
	}

        ...

}
 

Water

Member
Okay, my confusion is finally over. Apologies! So this was a dynamic array of pointers to arrays, and the addresses you are talking about are invididual ones returned by successive mallocs. It didn't occur to me that this was the case - I think I just kind of assumed you wouldn't ask this question if it was. Then again, since I figured out your results are impossible on the stack (because C multidimensional arrays on the stack are just one-dimensional arrays with some syntactic sugar, and thus can't have that kind of padding) I should have revisited my earlier assumption.

Turns out the question you are actually asking is "how does the particular implementation of malloc in my standard library work exactly?". I don't think the C standard guarantees you much of anything about malloc's allocation patterns, so it's all about how yours happens to be written. If I understand correctly, most reasonable mallocs tend to put a little extra header or footer at the beginning or end of every allocation, and that's where your extra space is likely going.

Another thing to note is that my earlier random suggestion of reading the padding was bad since I didn't specify you have to do that with a memory debugger. If you try to do it from C code, you are reading from memory you haven't allocated - which is undefined behavior. If the compiler notices that, and it very well might, it's free to just give you the constant 0, bake you some cookies or anything in between. You can't trust anything it does when your code triggers UB.
 
Okay, my confusion is finally over. Apologies! So this was a dynamic array of pointers to arrays, and the addresses you are talking about are invididual ones returned by successive mallocs. It didn't occur to me that this was the case - I think I just kind of assumed you wouldn't ask this question if it was. Then again, since I figured out your results are impossible on the stack (because C multidimensional arrays on the stack are just one-dimensional arrays with some syntactic sugar, and thus can't have that kind of padding) I should have revisited my earlier assumption.

Turns out the question you are actually asking is "how does the particular implementation of malloc in my standard library work exactly?". I don't think the C standard guarantees you much of anything about malloc's allocation patterns, so it's all about how yours happens to be written. If I understand correctly, most reasonable mallocs tend to put a little extra header or footer at the beginning or end of every allocation, and that's where your extra space is likely going.

Another thing to note is that my earlier random suggestion of reading the padding was bad since I didn't specify you have to do that with a memory debugger. If you try to do it from C code, you are reading from memory you haven't allocated - which is undefined behavior. If the compiler notices that, and it very well might, it's free to just give you the constant 0, bake you some cookies or anything in between. You can't trust anything it does when your code triggers UB.

Ah, of course. It never occurred to me that the extra space results from individual allocations. Thank you for working with me on this.

In that case, is there any way to "pack" malloc so you can have a portable, determined-size allocation? Or, alternatively, is there a better way of allocating dynamic multi-dimensional arrays?

EDIT: Belay that request! This GNU libc doc appears to hold my answer. Again, thank you for the help Water.
 

leroidys

Member
I have a bit of an issue that I feel's gonna be easy to fix but this is somehow the first time I've ever had to do network stuff in Java. Can't believe in 4 years my degree never taught me this, but anyway.

Basically I have this class called "Broker" which creates Transaction objects and continuously sends them over the network until you manually stop it. The problem I'm having is that after I run it a few times to test it, or not even that, I'll get "No buffer space available (maximum connections reached?)". Now what I'm assuming is that because I'm constantly creating new sockets and closing them it's using up the connections.
Code:
	public void run() {

		Random rand = new Random();
		
		while (true) {
			try {
				
				Socket socket = new Socket("localHost", 1337);
				System.out.println("Broker Connected");
			
				ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
				
				//randomize a value.
				double val = rand.nextInt((140 - 60) + 1) + 60;
				
				//Randomize a sell or buy.
				double typeVal = Math.random();
				char type = 'A';
				if (typeVal > 0.5) {
					type = 'S';
				} else {
					type = 'B';
				}
				
				//Randomize a quantity.
				int quant = rand.nextInt((70 - 20) + 1) + 20;
				quant *= 100;
				
				Transaction transaction = new Transaction(type, quant, val);
				
				System.out.println("Object to be sent = " + transaction.toString());
				outputStream.writeObject(transaction);
				System.out.println("Object sent from: " + id);
			
	
				socket.close();
				
				int randSleep = (int) (Math.random() * 500 + 1500);
				Thread.sleep(0);
				
			} catch (SocketException se) {
				
				se.printStackTrace();
			
			} catch (IOException e) {
				
				e.printStackTrace();
			
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}

There/s the code snippet, it's runnable so I can have as many of these things firing off but after say 10 seconds I've sent ~5-6000 transactions which I can only assume means that many sockets have been opened.

I'm trying to do this in a way that means I only have to create/close the socket once but I'm not having any luck due to the try/catch clauses necessary.
Even if you close the socket it takes the OS a while to reclaim the resource (port). Try using whatever the java equivalent is of setsockopt(SO_REUSEADDR,...,)
 

Water

Member
Ah, of course. It never occurred to me that the extra space results from individual allocations. Thank you for working with me on this.

In that case, is there any way to "pack" malloc so you can have a portable, determined-size allocation? Or, alternatively, is there a better way of allocating dynamic multi-dimensional arrays?

EDIT: Belay that request! This GNU libc doc appears to hold my answer. Again, thank you for the help Water.

First off, my last post's "oh yeah you should use a memory debugger to look at that memory" part was another piece of misleading or wrong info. Of course you can't read headers/footers left by malloc with a memory debugger when the way most (all? dunno) memory debuggers work is by modifying malloc or replacing it temporarily.

If you just want a tightly packed multi-dimensional array, you make a one-dimensional array and use it as if it was multi-dimensional. For me that's the normal way of doing things in C regardless of if I'm interested in the internal layout, since it results in simpler, less buggy code and is bound to perform same or better than an array of pointers. 6x3 array? malloc(6 * 3 * sizeof(sometype)). If you must have the arr[x][y] bracket syntax, as opposed to e.g. an indexing macro like arr[IDX(x, y, COLS)], you can still set up a separate array of pointers which point to the beginning of rows.
 

NotBacon

Member
That would give me an unreachable code error because it's after the while(true)

I'll give that a try when I get back, main issue is that it didn't seem to like writing to the socket again.

-Well are you planning on this being infinite? You could just put the socket.close() in a finally block.

-And it doesn't like you opening up too many sockets without closing your previous ones fully.
 

Cindres

Vied for a tag related to cocks, so here it is.
Even if you close the socket it takes the OS a while to reclaim the resource (port). Try using whatever the java equivalent is of setsockopt(SO_REUSEADDR,...,)

I'll look into that, would make sense.

-Well are you planning on this being infinite? You could just put the socket.close() in a finally block.

-And it doesn't like you opening up too many sockets without closing your previous ones fully.

I think the problem sounds like what leroidys said. It wouldn't be infinite but it could essentially be.


EDIT: Also, if I have some runnable classes is it only the run method that will run concurrently? Say I call another method in the thread will that still run concurrently with other threads? Basically I need to be able to pass a variable to a thread whenever it's received by the communicator. Say I give that to another method will it still run as a thread or does only the run method do that?
EDIT 2: Scrap that, I figured it out. I'm assuming all methods called from within run() are run concurrently though?
 

Garcia

Member
Hey guys, I have a Java related question:

I wrote a program that calculates every prime number from 2 to N by implementing the Sieve of Eratosthenes. It uses an ArrayList to hold the integer values:

Code:
private void sieveOfEratosthenes() {
		
	//      Start by filling an ArrayList of integers between 2 and N. 
		for (int i = START; i <= END; i++) {
			original.add(i);
		}
		
		for (int i = 0; i < original.size(); i++) {
			
		//	Go through every number in the array, excluding the first element. 
			for (int j = i + 1; j < original.size(); j++) {
				
		        //      Find all multiples of the " i "'th element in the array and 
				if (original.get(j) % original.get(i)== 0) {
					
				//	remove them.  
					original.remove(j);
				}
			}			
		}


Then I print out the list of prime numbers by using another for loop. The program works perfectly fine but significantly slows down if I set N to 100,000 or any number bigger than that. Is this related to a memory cap in Eclipse? Am I running out of virtual memory to hold every heap and stack value of the array? Or maybe this is exclusively related to CPU performance?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I'm going to guess that you're running out of memory because your implementation's time complexity is somewhere between linear and exponential.

You would also remove a lot of overhead if you used the implementation Wiki outlines, since you save on operations like modulo and array removal.
 

Aureon

Please do not let me serve on a jury. I am actually a crazy person.
Hey guys, I have a Java related question:

I wrote a program that calculates every prime number from 2 to N by implementing the Sieve of Eratosthenes. It uses an ArrayList to hold the integer values:

Code:
private void sieveOfEratosthenes() {
		
	//      Start by filling an ArrayList of integers between 2 and N. 
		for (int i = START; i <= END; i++) {
			original.add(i);
		}
		
		for (int i = 0; i < original.size(); i++) {
			
		//	Go through every number in the array, excluding the first element. 
			for (int j = i + 1; j < original.size(); j++) {
				
		        //      Find all multiples of the " i "'th element in the array and 
				if (original.get(j) % original.get(i)== 0) {
					
				//	remove them.  
					original.remove(j);
				}
			}			
		}


Then I print out the list of prime numbers by using another for loop. The program works perfectly fine but significantly slows down if I set N to 100,000 or any number bigger than that. Is this related to a memory cap in Eclipse? Am I running out of virtual memory to hold every heap and stack value of the array? Or maybe this is exclusively related to CPU performance?

100k items shouldn't be more than some megabytes of memory, if we're talking ArrayList (pointer, 64bits, integer, 32 bits = 96*100k, we're at barely 10mb of ram)

Still, you're running a O(n^2) operation. You can expect it to slow down significantly.
Also, poking holes in ArrayLists is generally problematic. (e: Since we're there, if you expect to do a huge amount of not-at-the-end insert\remove, use LinkedList, not ArrayList)

Plus, you aren't really well implementing the Sieve.
You are basically, for every single prime, scrolling down the whole list of integers smaller than N, and checking every single one to see if it's a multiple. This is extremely inefficient.
If you were going in the other direction (and you should), you'd compile a list of the multiples of the number smaller than N (temp list, while that breaks when one item is bigger than N-number).
Multiplication is much heavier than a %== check, but not enough so to go around doing 100k checks on very high primes while you could do ~100 removals straight-out. (Even if some of those removal are misses, that is not that much of a problem.)

Also, since .remove() works on the index, it's probably more efficient to assign-to-zero instead of removing, and then clearing down the list when you're finished.


TL;DR: You're checking all numbers of the list for divisibility instead of calculating the multiples, leading to excessive amounts of divisibility checks.

As a final addition, you should put in an optimization of the Sieve, that is (do not check numbers that are bigger than the square root of N)
 

Garcia

Member
100k items shouldn't be more than some megabytes of memory, if we're talking ArrayList (pointer, 64bits, integer, 32 bits = 96*100k, we're at barely 10mb of ram)

Still, you're running a O(n^2) operation. You can expect it to slow down significantly.
Also, poking holes in ArrayLists is generally problematic. (e: Since we're there, if you expect to do a huge amount of not-at-the-end insert\remove, use LinkedList, not ArrayList)

Plus, you aren't really well implementing the Sieve.
You are basically, for every single prime, scrolling down the whole list of integers smaller than N, and checking every single one to see if it's a multiple. This is extremely inefficient.
If you were going in the other direction (and you should), you'd compile a list of the multiples of the number smaller than N (temp list, while that breaks when one item is bigger than N-number).
Multiplication is much heavier than a %== check, but not enough so to go around doing 100k checks on very high primes while you could do ~100 removals straight-out. (Even if some of those removal are misses, that is not that much of a problem.)

Also, since .remove() works on the index, it's probably more efficient to assign-to-zero instead of removing, and then clearing down the list when you're finished.


TL;DR: You're checking all numbers of the list for divisibility instead of calculating the multiples, leading to excessive amounts of divisibility checks.

As a final addition, you should put in an optimization of the Sieve, that is (do not check numbers that are bigger than the square root of N)

I'm going to guess that you're running out of memory because your implementation's time complexity is somewhere between linear and exponential.

You would also remove a lot of overhead if you used the implementation Wiki outlines, since you save on operations like modulo and array removal.

Thank you so much. This was extremely helpful to me; I've only been programming for less than two months so it is really valuable to receive feedback from people that are experienced enough to find these problems so quickly.

I will follow your suggestions to optimize the program. Much appreciated!
 
I have a simple script which has a few hardcoded paths. My problem is deciding which approach to take. If you had to modify a script written by someone else, which would you prefer? This is basically a test script I'm writing. I've been asked to keep the paths within the script as opposed to using config files. Below is a mix of python and pseudo-code.

#option 1 - list storing each path

PATHS = ['/home', '/home/docs', '/system/res', '/home/library/works']

run_cmd('appBox %s -t %s' % (PATHS[0], PATHS[1]))
run_cmd('appBox %s -t %s -f 4 %s' % (PATHS[0], PATHS[1], PATHS[3]))

#option 2 - define variables for each path

HOME_PATH = '/home'
DOCS_PATH = '/home/docs'
SYS_PATH - '/system/res'
WORKS_PATH = '/home/library/works'

run_cmd('appBox %s -t %s' % (HOME_PATH, DOCS_PATH))
run_cmd('appBox %s -t %s -f %s' % (HOME_PATH, DOCS_PATH, WORKS_PATH))

#option 3 - Use os.path.join() to join paths

HOME_PATH = '/home'
DOCS_PATH = os.path.join(HOME_PATH, 'docs')
SYS_PATH - '/system/res'
WORKS_PATH = os.path.join(HOME_PATH, 'library/works')

run_cmd('appBox %s -t %s' % (HOME_PATH, DOCS_PATH))
run_cmd('appBox %s -t %s -f %s' % (HOME_PATH, DOCS_PATH, WORKS_PATH))
 

usea

Member
I have a simple script which has a few hardcoded paths. My problem is deciding which approach to take. If you had to modify a script written by someone else, which would you prefer? This is basically a test script I'm writing. I've been asked to keep the paths within the script as opposed to using config files. Below is a mix of python and pseudo-code.
If I had to look at that script and figure out what it did and how to modify it, I'd prefer option 2 by far.
 

BreakyBoy

o_O @_@ O_o
I have a simple script which has a few hardcoded paths. My problem is deciding which approach to take. If you had to modify a script written by someone else, which would you prefer? This is basically a test script I'm writing. I've been asked to keep the paths within the script as opposed to using config files. Below is a mix of python and pseudo-code.

Based on the options you've given it seems to me that your actual intent is to have:

- a user-defined absolute home path
- a docs path that consists of a relative user-defined sub-folder/path within the home path
- a user-defined absolute sys path
- a works path that consists of a relative user-defined sub-folder/path within the home path

So a mix of 2 & 3 might be optimal?

Something like:

Code:
# Absolute paths for HOME & SYS
ABS_HOME = '/home'
ABS_SYS = '/system/res

# Relative paths for DOCS & WORKS
REL_DOCS = 'docs'
REL_WORKS = 'library/works'

# Absolute paths for DOCS & WORKS
docs_path = os.path.join(ABS_HOME, REL_DOCS)
works_path = os.path.join(ABS_HOME, REL_WORKS)

run_cmd('appBox %s -t %s' % (ABS_HOME, docs_path))
run_cmd('appBox %s -t %s -f %s' % (ABS_HOME, docs_path, works_path))

Maybe I'm overcomplicating things, but it seems to me you really want to enforce the use of the home path as a base for the docs and work paths. This approach should help make your intent clear while allowing you to set things up in the format you intend.

If I'm wrong, and you want the user to be able to define docs and works paths outside of the home path, then option #2 all the way.
 

VoxPop

Member
stupid question but is there a difference in coding between Windows and OSX?

i.e coding on a macbook pro (not just objective-c)
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I assume paths and stuff will be different.

There might also be lower level architectural differences.

And when it comes to game engine programming you wouldn't be able to use, for example, the DirectX API without bootcamp.
 
If I had to look at that script and figure out what it did and how to modify it, I'd prefer option 2 by far.

Based on the options you've given it seems to me that your actual intent is to have:

- a user-defined absolute home path
- a docs path that consists of a relative user-defined sub-folder/path within the home path
- a user-defined absolute sys path
- a works path that consists of a relative user-defined sub-folder/path within the home path

So a mix of 2 & 3 might be optimal?

Something like:

Code:
# Absolute paths for HOME & SYS
ABS_HOME = '/home'
ABS_SYS = '/system/res

# Relative paths for DOCS & WORKS
REL_DOCS = 'docs'
REL_WORKS = 'library/works'

# Absolute paths for DOCS & WORKS
docs_path = os.path.join(ABS_HOME, REL_DOCS)
works_path = os.path.join(ABS_HOME, REL_WORKS)

run_cmd('appBox %s -t %s' % (ABS_HOME, docs_path))
run_cmd('appBox %s -t %s -f %s' % (ABS_HOME, docs_path, works_path))

Maybe I'm overcomplicating things, but it seems to me you really want to enforce the use of the home path as a base for the docs and work paths. This approach should help make your intent clear while allowing you to set things up in the format you intend.

If I'm wrong, and you want the user to be able to define docs and works paths outside of the home path, then option #2 all the way.


Hey thanks guys for sharing your thoughts. I can see how option# 2 is preferable. I was afraid I was being inefficient if I wasn't putting all the paths in one list called "PATHS", but then I saw that it would be harder to read if I was using these values in other parts of my script (PATHS[0] vs. DATA_PATH).

Breakyboy, I really like your approach to breaking out the paths into relative and absolute paths. I hadn't even thought of that. It's easy to read too. Thanks!
 

NotBacon

Member
stupid question but is there a difference in coding between Windows and OSX?

i.e coding on a macbook pro (not just objective-c)

It'll just be a unix-y environment vs a Windows environment.

Personally I find coding more enjoyable in a unix-y environment. POSIX standards and utilities, better file hierarchy, better handling of input/output as streams, and better handling of permissions/groups. But that's just my opinion.
 

GK86

Homeland Security Fail
I have a question, any help would be greatly appreciated it. I have to do a project for my c++ class, where we take names and scores from a user, have to combined and display them, sort it by lowest score first, and display the sorted list.

I'm using string arrays for both names and scores. My question is, is it possible to sort it by the score? Since it is string array, the scores lose their numerical value, correct?

Which sorting method would you guys recommend I use?

Thanks.
 
stupid question but is there a difference in coding between Windows and OSX?

i.e coding on a macbook pro (not just objective-c)

besides the unix environment, not much. I do know (i could be wrong) apple rolls a slightly different version of OpenGL.

I have a question, any help would be greatly appreciated it. I have to do a project for my c++ class, where we take names and scores from a user, have to combined and display them, sort it by lowest score first, and display the sorted list.

I'm using string arrays for both names and scores. My question is, is it possible to sort it by the score? Since it is string array, the scores lose their numerical value, correct?

Which sorting method would you guys recommend I use?

Thanks.

There is a string to integer function in the string class (stoi) or you can do something like int number = atoi(string.c_str()) and store them as integers so you can sort them.

You could do an array of structs with string name and int score and then just sort based on the score.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Are there some of you that write your programs in a UNIX environment entirely? Whether the end product will be on Windows or any other OS?
 

VoxPop

Member
cool thanks for the answers guys.

I'm actually coming out with an app (other people coding) and i've been trying to learn a bit myself. was just wondering how different it would be working on a PC versus a Mac.
 

GK86

Homeland Security Fail
There is a string to integer function in the string class (stoi) or you can do something like int number = atoi(string.c_str()) and store them as integers so you can sort them.

You could do an array of structs with string name and int score and then just sort based on the score.

Thank you. I will look into it.
 

Aureon

Please do not let me serve on a jury. I am actually a crazy person.
stupid question but is there a difference in coding between Windows and OSX?

i.e coding on a macbook pro (not just objective-c)

Writing with, no.
Writing for, yes. Mostly path differences, some syscalls in low-level stuff, and of course, different libraries being available.

Mainly, if you have to ask, the answer is no.
 
stupid question but is there a difference in coding between Windows and OSX?

i.e coding on a macbook pro (not just objective-c)

This is kind of vague, so the best answer I can give is, "it depends".

What sort of coding are you doing? What is your target application/platform? What language(s) do you plan on using?
 
stupid question but is there a difference in coding between Windows and OSX?

i.e coding on a macbook pro (not just objective-c)
Depends on the language.

Don't know how much coding background you have, but interpreted languages like python, ruby, and javascript are cross platform, with an execution layer beneath them that translates the code into instructions (and handles all the messy platform-dependent bits).

Lower level languages like the C family (C, C++, objective C) require separate system calls and often require coding separate paths to implement the same functionality on different platforms.

Are there some of you that write your programs in a UNIX environment entirely? Whether the end product will be on Windows or any other OS?
Yes, or at least I did at my last job. For example, for non-graphical C++ programs, maintaining a linux version of your code base is just common sense (valgrind! wireshark on localhost! tc! ... etc), and once you're maintaining a linux version of the code, you realize that QtCreator does almost everything as well as Visual Studio does.

For stuff like java/python/etc, you can develop it wherever you want. So I do those in linux as well, because I can't stand using windows.
 

injurai

Banned
stupid question but is there a difference in coding between Windows and OSX?

i.e coding on a macbook pro (not just objective-c)

To expand on what others have said. The C language itself is quite small, but there is a wealth of libraries that you can make use of. You'll end up using some library for probably every piece of C code you ever write. Many of the standard libraries have been ported across platforms, and compilers exist for C on all platforms.

If you write in pure standard C, you should be able to take your source code and the compile it on each platform. Some implementations might have slightly differing behavior such as rand, or the accuracy of system time.

The hope is that porting is trivial as swapping out one system call for a platform specific equivalent. But there can be much more complex issues where the system operates under certain assumptions and you may have to write platform specific wrappers.
 

PFD

Member
I'm currently learning Objective C over the summer because I want to build iOS apps. Only know some very basic Java. I'm progressing slower than I'd like
 

Husker86

Member
I'm currently learning Objective C over the summer because I want to build iOS apps. Only know some very basic Java. I'm progressing slower than I'd like

I've made some Android apps in Eclipse as well as Android/iOS game in Unity. I am still very much a beginner, but the few beginning tutorials I tried on Objective C scared me a bit. Getting my Unity game set up in Xcode was sort of overwhelming as well.

I will go back eventually, as I'd like to do some native development for iOS/Mac, but I am definitely more comfortable in Java and the C# scripting I've done in Unity (not really surprising considering I've spent far more time with those languages).
 
It looks like Amazon is having a recruiting week in my area (Southeastern US.) I've had three recruiters send me messages on Linked In.

Has anyone else worked for Amazon or at least been to one of these events for them? I'm interested but it would mean moving my family to the literal opposite end of the country. I already did it last year to move here from Chicago.
 
Top Bottom