Jump to content

Check out our Community Blogs


Member Since 12 Mar 2008
Offline Last Active Jan 22 2017 06:13 PM

#636771 How to practice C++

Posted by chili5 on 23 August 2012 - 10:18 PM

In games, memory management can be crucial. Depending on the types of games you are interested in, threading, networking and graphics are important also.

It would do you good to learn about the STL also. The STL provides standard algorithms and data structures for common tasks. :) These algorithms and data structures are highly optimized and using them would help in making your game much more efficient. Lagging games are bad. Knowledge of the STL will serve you well in other types of programs also.
  • 1

#635800 Prime number formula

Posted by chili5 on 11 August 2012 - 06:09 PM

Cool, didn't know that. I found this: en.wikipedia.org/wiki/Formula_for_primes
Look at the recurrence relation. The article claims that the sequence contains only primes and 1s. It linked to a proof which I haven't looked at but assuming this is true then you can use the reccurence to generate so many numbers and put them into a set. Put the numbers into a set and remove 1 from that set to get a set of primes.

This is neat - though it doesn't appear useful if you want all prime numbers up to some number n.
  • 1

#635464 Where do you get your programming news?

Posted by chili5 on 07 August 2012 - 06:12 PM

I use http://www.codeproject.com/ occasionally...
  • 2

#632473 Whats The Best Editor / Ide?

Posted by chili5 on 26 June 2012 - 09:52 AM

Netbeans is good - just really sluggish. Visual Studio is also good. There are some PHP extensions for Visual Studio.
  • 1

#632308 [Java] Reverse Char Array?

Posted by chili5 on 24 June 2012 - 03:58 PM

char result = int[0];

This line in your reverseIt function doesn't work since result is a char but you are initiializing it as an array. Also, why create an array of size 0?

To reverse a list you can either:

(1) Make a new array and loop backwards creating a new array:

int idx = 0;
char[] newArr = new char[A.length];
for (int i = A.length - 1; i >= 0; i--) {
   newArr[idx] = A[i];

The other option, which is much faster and uses 0(1) memory is to do the swap in place. Basically you start at the far right and swap with the first element. Then move a pointer at the end closer to the front and a point at the front closer to the end and do another swap. Once the two pointers swap (which will happen halfway through the list) you stop. This means that you only need to iterate over half of the array and you don't need a second array.

public static void reverseIT(char[] A) {
		int idx = 0;
		for (int i = A.length - 1; i >= A.length / 2; i--) {

			char temp = A[i];
			A[i] = A[idx];
			A[idx] = temp;

  • 1

#631355 C# String Builders

Posted by chili5 on 08 June 2012 - 05:31 PM

if (pizza = cheese)
System.Windows.Messagebox.Show("You sir, have a cheese pizza.")

This is wrong:
You should do pizza == cheese not pizza = cheese.
  • 1

#625777 Which Of Programming Language Learn First, Vb6 Or C++

Posted by chili5 on 07 April 2012 - 04:19 AM

You will get more out of learning C++. VB6 is pretty awful. I'm not sure how much VB6 gets used today but judging by how old it is, highly doubt it is a very employable skill these days.
  • 1

#624126 Reading only integers from a file

Posted by chili5 on 16 March 2012 - 04:20 PM

Yes. You got it! :D
  • -1

#622923 PHP Register Page

Posted by chili5 on 27 February 2012 - 05:18 PM


if (preg_match("/[A-Za-z].+/",$_POST["username"]))

That should work but I didn't test it. To match a letter at the beginning use the pattern [A-Za-z]. Let me know if that works. I'm not familar with the exact semantics of preg_match but fairly familar with regex.

This regex [A-Za-z].+ matches any string that starts with a letter followed by 1 or more characters.
  • -1

#608731 Ruby, Vectors

Posted by chili5 on 03 September 2011 - 06:37 AM

You can simplify the add function slightly. Why did you choose to manually calculate c[0] when you can let the loop do this...

def add a, b 
    if a.length != b.length 
        return false 

    c= [a[0] + b[0]] 
    for i in 1..(a.length - 1)   
        c[i]= a[i] + b[i] 


Like this:

def add a, b 
    if a.length != b.length 
        return false 

    c= []
    for i in 0..(a.length - 1)   
        c[i]= a[i] + b[i] 


Just start the loop at zero instead of 1.

Also you don't know about cross products? The dot product operation gives you a scalar as the result. The cross product which is also known as the vector product gives you a vector as the answer. The vector that is produced when you do a x b (read a cross B) is a vector that is perpendicular to both a and b. In the general case this is a very complicated function to implement. Cross product is calculated using determinants. One method to calculate this is to use a cofactor expansion.

One practical use of this is determining if an object is inside a region.
  • 1

#607923 C# String Builders

Posted by chili5 on 21 August 2011 - 07:21 AM

C# String Builders

Back when I talked about strings, I mentioned how they are immutable. This means that once a string is created you cannot change it. When you desire to make changes to a string you can either remake the string or use the string builder class.
Creating a String Builder
To create a string builder simply use the String Builder constructor passing to it the original string that you want to represent.


StringBuilder s = new StringBuilder("welcome to codecall");

If you do Console.WriteLine(s) the output will be welcome to codecall.

Appending Characters

There are several ways of appending characters to the end of a string builder. The simple method is to just add one character to the end of the string builder.


The output will be:

welcome to codecallx

We can also add a character more than one time. Using the method overload Append(char, int) we specify a char and the number of times to append it to the end of the string.


s.Append('x', 3);

This will add 3 x’s to the end of s.

Appending Strings

Two more overloads of append are:

  • Append(char[])
  • Append(string)

The first overload adds the contents of a character array to the end of the string.


StringBuilder s = new StringBuilder("welcome to codecall");
s.Append(new[] {'a', 'b', 'c'});

The output is:

welcome to codecallabc

A neat fact to note here is how we didn’t have to specify the type of array. C# is smart enough to figure out that this is a character array. Occasionally I may use var for variable declarations because C# is smart enough to figure out the type of variable based on its usage.

You can also append a string like this:

StringBuilder s = new StringBuilder("welcome to codecall");

Replacing Characters

The Replace methods replaces all instances of a character with a new character. Example:

StringBuilder s = new StringBuilder("welcome to codecall");
s = s.Replace('e', 'o');

The output of this code is:

wolcomo to codocall

Deleting Characters

The method to delete characters is Remove(startIndex, length). When using this method it is important to make sure that startIndex actually references a character in the string and that there are length-1 characters after startIndex. If this isn’t true then you’re program is going to crash.


 s = s.Remove(5, 3);

This code deletes the characters at index 5, 6 and 7. Then the new string builder is produced without these characters.

The output will be:

welcoto codecall

Adding Characters

To add characters we use the Insert method.


s = s.Insert(5, 'C');

This code inserts character C at index 5. Whatever was at index 5 and above gets pushed over one to make room for the new character.

Output is then:

welcoCme to codecall

  • 3

#607253 Scheme Structures

Posted by chili5 on 14 August 2011 - 04:30 AM

Scheme Structures

Table of Contents
1. Scheme Functions and Constants
2. Scheme Structures
3. Scheme Defining Structures
4. Scheme Conditonals
5. Scheme Lists
6. Scheme Local Definitions

Structures provide a means of grouping related data into an entity. Most modern languages contain a context similar to structures. Languages such as C and C++ also support structures where as languages like Java and C# support classes. Note: structures are not classes. Classes are much more flexible as they support features such as information hiding, inheritance and allow you to define your own methods. Structures do not have these features.
Structures are useful for implementing data structures in Scheme.

Built-in Scheme Structures – Posn

Posn is a built-in Scheme structure that has two fields x and y. In other words, this structure is meant to represent a point on a Cartesian grid.
We create a posn like this:

(make-posn 3 2)

This is the constructor function which takes 2 parameters x followed by y. So in this case the x coordinate is 3 and the y-coordinate is 2.
It is important at this point to mention that Scheme is not a strongly typed language. It is syntactically valid to write:

(make-posn 'Hi 'CodeCall’)

But in a logistic sense this doesn’t make any sense. You may recall that a posn represents a point on a grid. (‘Hi, ‘CodeCall) doesn’t represent any point on a Cartesian grid. This is why when we write structures and functions we write a contract that the programmer must adhere to. If the contract is broken then bad things can happen. We want to write our programs so that if the contract is adhered to then the program will function properly.
We can write checks to ensure that types passed to our function are valid if we want. We will see how to do this in a later tutorial.

Now let us look at selectors.


When a structure is created a selector function is created for every field. The selector function takes the form: (structname-fieldname struct)
So in the posn example if we want the x-value we can do the follow:

 (posn-x posn) ;; returns the x value of the posn
 (posn-y posn) ;; returns the y value of the posn


(posn-x (make-posn 3 2))

This code produces the x value of the posn which in this case is 3. If we did (posn-y (make-posn 3 2)) the value produced would be 2.

Predicate function

Another function created when we create a structure is a predicate function named struct-name? which returns true if a value is that particular structure. As we will see later this is useful when dealing with recursive structures.


(posn? 5) ;; false
 (posn? (make-posn  3 2));; true

Next time we look at creating our own structures! Any questions, post below! :)

Table of Contents
1. Scheme Functions and Constants
2. Scheme Structures
3. Scheme Defining Structures
4. Scheme Conditonals
5. Scheme Lists
6. Scheme Local Definitions

  • 1

#525117 Java Result Sets

Posted by chili5 on 14 November 2009 - 03:20 AM

Your code works for me. I think the problem is that you don't have the mysql connector set up correctly.

Have a look at this: Installing and Configuring MySQL Database and Connector/J JDBC Driver on Microsoft Windows and try following that and see if that fixes your problem.

Your code runs perfectly on my computer.

package test;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
	public static void main(String[] args) {
		String[] header = new String[]{"Name", "Last Name",
		Object[][] data = null;
		Connection con = null;
			con = DriverManager.getConnection("jdbc:mysql:///test",
			        "root", "james");
				String sqlUpit = "SELECT * FROM someTable";
				Statement s = con.createStatement();
				ResultSet rs = s.executeQuery(sqlUpit);
				int numRows;
				numRows = rs.getRow();
				data = new Object[numRows][3];

				for(int i = 0; i < numRows; i++){
					for(int j = 0; j < 3; j++){
						data[i][j] = rs.getString(j + 2);
		catch(ClassNotFoundException ex){
			System.err.println("Exception: " + ex.getMessage());
		catch(SQLException ex){
			System.err.println("Exception: " + ex.getMessage());
		JTable table = new JTable(data, header);
		JFrame frame = new JFrame("Database2Table");
		frame.getContentPane().add(new JScrollPane(table));
		frame.setSize(500, 350);

  • -1

#524583 Priority Queues I

Posted by chili5 on 11 November 2009 - 04:59 PM

Priority Queues

A priority queue is similar to a Queue. Items are removed from the queue in a certain order. In a queue the order is FIFO (meaning first-in, first-out). The first item added to the queue is the first item to be removed from the queue.

A priority queue removes items in an order defined by a comparator. A comparator is an object that defines how objects should be ordered. You might have seen this is if you have looked at sorting objects.

Let us look at this compare to method:

public int compareTo(Golfer g) {
        if (g.nScore > nScore) {
            return -1;

        if (g.nScore < nScore) {
            return 1;

        return -g.sName.compareTo(sName);

If we had objects in a priority queue that had this compareTo method, the next item removed would be the one with the lowest score. However, if the scores are equal, then the player in alphabetical order will be returned.

This is a nice way to do some sorting without actually calling Arrays.sort or Collections.sort.

Creating a Priority Queue

A priority queue is a generic class that can only hold objects. It is created like this:

PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

Adding to a Priority Queue

Adding an item is as simple as calling the .add method of the PriorityQueue class.


Removing Items

We simply call the remove method and the next item is removed. The next item is determined by the comparator.

Try this code:

 while (!pq.isEmpty()) {

The output is:


Noticed, how it is sorted? This makes for a really great way to do some sorting.

Other uses?

Another use for this class is in implementing Dijkstra's Single Pair Shortest Path Algorithm. This is something I will discribe later. Basically Dijkstra's Algorithm allows us to find the shortest path between any two nodes. We would use a priority queue to choose the next node that is a shortest distance from the starting node.

It is called the Single Pair Shortest Path Algorithm because it finds all the shortest paths from a start node to all other nodes.

Dijkstra's Algorithm is just one use of this algorithm.
  • 4

#520811 Sorting Arrays of Objects with Comparable

Posted by chili5 on 02 November 2009 - 01:55 PM

Sorting Objects

The java.util packages contains a class Array that contains methods for sorting arrays. It can sort arrays of any type and uses a modified quick sort algorithm to sort the array.

Let us take a look at sorting objects. To do this we have to lean about the Comparable interface. The comparable interface describes how two objects should be compared. This interface is what allows us to sort arrays.

First we have to create a class. For the purpose of this tutorial we will create a Person class with three fields name, age, and height.

class Person {
	int age;
	int height;
	String name;

	Person(int age, int height, String name) {
		this.age = age;
		this.height = height;
		this.name = name;

This code is very simple. It is a template to create a bunch of Person objects. We need an array of them so we will create an array of people.

Person[] aroPeople = new Person[4];

aroPeople[0] =new Person(17,100,"James");
aroPeople[1] = new Person(18,94,"John");
aroPeople[2] = new Person(16,120,"Chris");
aroPeople[3] = new Person(17,89,"Bob");

We populate an array of Person objects. Now we want to sort this array and output some information about it.

First let us look at how we are going to do some outputting.

Add this method to the Person class.

public String toString() {
	return name + " is " + age + " years old and has a height of " + height;

Whenever we pass an object to the System.out.println method the toString method is called and that is what is outputted.




James is 17 years old and has a height of 100

Now that we have output down, all we have left to do is tell Java how we want to sort the array. This is what we need the Comparable interface for.

Change this line:

class Person {


class Person implements Comparable<Person> {

This tells Java that we are going to be comparing Person objects. Now we have to implement the compare to method which tells us how we want to do some sorting.

public int compareTo(Person p) {
        return 0;

Add that method to the class declaration. We will return 1 if the object we are comparing to is greater than the current object, -1 if the object we are comparing to is less than the current object. Otherwise, we will return 0 (indicating that they are equal).

Returning 1 will sort in ascending order, returning -1 will sort in descending order. This approach allows us to sort by more than one field.

We want to sort in ascending order by age, then descending order by height. Only if age is equal do we want to sort by height.

Change the compare to method to this:

public int compareTo(Person p) {

        if (age < p.age) {
            return -1;

        if (age > p.age) {
            return 1;

        // only sort by height if age is equal
        if (height > p.height) {
            return -1;

        if (height < p.height) {
            return 1;

        return 0;

This gives you a very fast and quick way to sort an array of objects by any fields in any order that you want.

Now to do the sorting and outputting:

for (int i=0;i<aroPeople.length;i++) {

All the details of the sorting is handled by Java and you don't need to know why it works. Hope this helps!
  • -1