Welcome
Welcome to the forums of AntiRTFM's Absolute N00b Spoonfeed C++ Tutorials!

You are currently viewing our boards as a guest, which gives you limited access to view most discussions and access our other features. By joining our free community, you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content, and access many other special features. Registration is fast, simple, and absolutely free, so please, <a href="/profile.php?mode=register">join our community today</a>!

Modulus in C++

C++ Stuff belonging in global scope pretty much

Modulus in C++

Postby Moosader on Wed Oct 07, 2009 12:28 pm

Modulus can be pretty handy, especially when playing with arrays.

I was just talking to Ruddie about loading in strings, and how strings can be accessed like arrays (for example, if "temp" is a string, then "temp[3]" will write out the 3rd character). It is a 1D array, but you can use Modulus to kind of "simulate" it being 2D.

Let's say we have a 1D array of tiles size 12. We want a 4x3 grid.
Modulus will essentially take anything bigger than the width (4), and offset it.
After it gets to index 3, it loops back and 4 begins at the first position on the next row.

I'm feeling really unarticulate today, so I apologize. XD Best way to show is this way...:

Code: Select all
0   1   2   3    <-- Row 0: Goes up to the tile corresponding to the width (0 to 4)
4   5   6   7    <-- Row 1: Treats 4 like 4-width (4-4 = 0), but adds one to the row it's on.
8   9  10  11   <-- Row 2: Treats 8 like 8-(2*width) (8-(2*4) = (8-8 = 0)


So how do we get X and Y coordinates from a 1D array?


With width being 4, you can get the x and y coordinates this way:

x = index % width
y = index / width

So for tile 0:
0 % width = 0
0 / width = 0
coordinates are (0, 0)

For tile 1:
1 % width = 1
1 / width = 0
coordinates are (1, 0)

For tile 3:
3 % width = 3
3 / width = 0
coordinates are (3, 0)

For tile 4:
4 % width = 0
4 / width = 1
coordinates are (0, 1)

For tile 7:
7 % width = 3
7 / width = 1
coordinates are (3, 1)

For tile 9:
9 % width = 1
9 / width = 2
coordinates are (1, 2)


Sorry I'm not feeling very articulate today, I'm having a hard time explaining mod. Maybe I'll edit this later.
User avatar
Moosader
 
Posts: 25
Joined: Mon Jul 06, 2009 5:31 pm
Location: Kansas City

Re: Modulus in C++

Postby glinka57 on Thu Oct 15, 2009 1:39 am

hmmmm.. most intriguing. I will play around with this array methodology you have discovered.
Yes, most interesting indeed. reveiw my combat demo Rachel.
User avatar
glinka57
 
Posts: 195
Joined: Fri Feb 27, 2009 7:32 pm

Re: Modulus in C++

Postby Moosader on Thu Oct 15, 2009 7:44 pm

Guh-
what? o_O


This thing? : post3033.html#p3033
User avatar
Moosader
 
Posts: 25
Joined: Mon Jul 06, 2009 5:31 pm
Location: Kansas City


Return to General

Who is online

Users browsing this forum: No registered users and 0 guests