Forum Moderators: coopster

Message Too Old, No Replies

Quite Simple Logic

But it has me

         

ukgimp

7:30 am on Jun 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hello

I have a situation where I need to assign what should be some qute simple logic, bun tI am thinking that I am looking too deep into the problem

Imagine I have an array that consists of values a,b,c,. Now the number of values in the array is 3 (n=3)

Now If I have another array or set of numbers from 1 - 9 the following relationship is set up

1 = a
2 = b
3 = c
4 = a
5 = b
up to 9
9 = c

So I would like to be able to change n to just about any whole number then give any number and get the corresponding letter.

So if n=5, the letter = e.

I seem to be going round in circles, I came up with what seems like it should work.

1/n gives the fraction of each whole numver so for n = 3

0.33

Then I thought that I would have to set up a load of inequalities

if (number/n) < .33 then letter = a
if (number/n) > .33 <.66 then letter = b
else letter = c

Is there a better way than this, that I am missing.

Cheers

mykel79

9:17 am on Jun 15, 2004 (gmt 0)

10+ Year Member



How about using the % operator? It returns the remainder of division.
So:
6%3=0
7%3=1
8%3=2
9%3=0

You could do:

$num_of_letters=5;
$number=7;
$which_letter=$number%$num_of_letters;
if ($which_letter==0) $which_letter=$num_of_letters;
//97 is the ASCII code for 'a', so chr(97)='a'
$letter=chr(96+$which_letter);
echo $letter;

This prints out 'b'

ukgimp

1:33 pm on Jun 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



will that work changing N?

Never seen thatr used before the %

ukgimp

2:43 pm on Jun 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just tried that out. Works,

That great, so easy.

Cheers

dcrombie

2:47 pm on Jun 15, 2004 (gmt 0)



It's called the "mod" or "modulus" operator - appears in just about every programming language in some form.

PHP: Arithmetic Operators [php.net]