How to insert english alphabets as incremental order - php

Hi i have the table structure as follows
id --auto increment id
alphabet
user_id
name
and while adding i needs to insert the english alphabets to users as incremental order like this A,B,C,....Z,AA,AB,AC,...AZ,BA,BB,BC,.....BZ.
I need to get like this
id alphabet user_id name
------------------------------------------
1 A 1 name-1
2 B 1 name-2
. . . .
. . . .
26 Z 1 name-n
27 A 2 name-1
28 B 2 name-2
. . . .
. . . .
52 Z 2 name-52
53 AA 2 name-53
. . . .
. . . .
. . . .
. AZ 2 .
Thanks for your time.

It's quite easy that you use php to implement this,
please check codes below
$i = 'A';
echo $i;
echo PHP_EOL;
while($i != 'ZZ')
{
echo ++$i;
echo PHP_EOL;
}
or see the results in http://codepad.org/QB4kyV7U

Check this similar article:
Algorithm to get the excel-like column name of a number
Here's a nice simple recursive function (Based on zero indexed numbers, meaning 0 == A, 1 == B, etc)...
function getNameFromNumber($num) {
$numeric = $num % 26;
$letter = chr(65 + $numeric);
$num2 = intval($num / 26);
if ($num2 > 0) {
return getNameFromNumber($num2 - 1) . $letter;
} else {
return $letter;
}
}
And if you want it one indexed (1 == A, etc):
function getNameFromNumber($num) {
$numeric = ($num - 1) % 26;
$letter = chr(65 + $numeric);
$num2 = intval(($num - 1) / 26);
if ($num2 > 0) {
return getNameFromNumber($num2) . $letter;
} else {
return $letter;
}
}
Tested with numbers from 0 to 10000...

Sounds a lot like this SO article
MYSQL: how to "reorder" a table
Is there an absolute necessity to do what you are wanting when you can use sorting to output your data however you want?

Related

How would I find the imaginary roots given a quadratic?

This code finds the two roots of a quadratic equation in the form ax^2+bx+c
Is my solution good time/space-complexity wise, and how I would go about allowing users to see the imaginary roots if the quadratic has any?
public function factor($a=0, $b=0, $c=0) {
$positive_solution = (-$b + sqrt($b**2-4*$a*$c))/2*$a;
$negative_solution = (-$b - sqrt($b**2-4*$a*$c))/2*$a;
if($b**2-4*$a*$c < 0) {
return "Solutions are imaginary";
}
$factor_one = $positive_solution * -1;
$factor_two = $negative_solution * -1;
$factor_one > 0 ? $factor_one = "+ " . $factor_one : $factor_one = "- " . $factor_one;
$factor_two > 0 ? $factor_two = "+ " . $factor_two : $factor_two = "- " . $factor_two;
return "Your roots are located at (0, " . $positive_solution . ")(0, " . $negative_solution . "),
Thus, the problem can be factored into (x " . $factor_one . ")(x " . $factor_two . ")";
}
the if($b**2-4*$a*$c < 0) is too late
You already used the sqrt so domain error might be thrown move the if to start
for imaginary part you just use negation or abs value
simply sqrt(-($b**2-4*$a*$c)) or sqrt(abs($b**2-4*$a*$c)) not sure if php uses abs or fabs for floats or if you even use floats... (havent code in php for ages)
I would combine this to something like this (just pseudo code as the var $ makes me dizzy :) ):
q = b*b-4*a*c
d = sqrt(abs(q))
if (q<0)
{
a0 = -b/(2*a);
b0 = +d/(2*a);
a1 = -b/(2*a);
b1 = -d/(2*a);
}
else
{
a0 = (-b + d)/(2*a);
b0 = 0
a1 = (-b - d)/(2*a);
b1 = 0
}
Where a0+i*b0 and a1+i*b1 are the 2 solutions where i=sqrt(-1)

PHP String Comparision

I am using below PHP function in Behat Mink to check the Email column values are in ascending or descending order.But the problem is its always fails.I just want to check if the subject or From of Email column in all rows are in ascending and descending order.Is there are any other way to do this?
public function ValidateColumnSorting($Column, $order) {
$nodes = // Logic goes to retrieve all rows subject or from column value
if (strcasecmp($order, "asc") == 0)
{
for ($i = 1; $i < $sizeof($nodes); $i++)
{
if (strcasecmp($nodes[$i], $nodes[$i - 1]) >= 0)
{
print_r("Row " . $i - 1 . " val is " . $nodes[$i - 1]);
}
else if (strcasecmp($nodes[$i], $nodes[$i - 1]) < 0)
{
throw new Exception($Column . " column ascending sort order failed.".$nodes[$i] . " is less than " . $nodes[$i - 1]);
}
}
}
else
{
for ($i = 1; $i < $sizeof($nodes); $i++)
{
print_r($Column . " column row " . $i . " value is " . $nodes[$i]);
if (strcasecmp($nodes[$i], (string) $nodes[$i - 1]) <= 0) {
print_r($Column . " of Email is same");
} else if (strcasecmp($nodes[$i], $nodes[$i - 1]) > 0) {
throw new Exception($Column . " column descending sort order failed." . $nodes[$i] . " is greater than " . $nodes[$i - 1]);
}
}
}
}
Instead of checking for its order, you can directly sort it in ascending or descending order.
Pass subject or email array to sort() function
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
It will return the sorted array
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
You don't need to do it manually.
Read more here http://in2.php.net/sort
Without thinking if there is a more Behat appropriate way of validating the order of elements, your code would probably fail due to $sizeof($nodes), try sizeof($nodes) instead.
In Behat, the approach I would take would be to create a generic step definition which could be re-used elsewhere...
Then I should see the "css_to_some_elements" ordered as:
| apple |
| banana |
| lemon |

Parallel HTML Rows

I have a HTML table with more than 1000 rows. Now i want to show these records in parallel manner.
Like 30 rows in left side and 30 in right side
1 xyz 120 00:10:01 31 xyz 120 00:10:01
1 xyz 120 00:10:01 32 mxy 20 00:10:01
2 mxy 20 00:10:01 . . . ........
. . . ........ . . . ........
. . . ........ . . . .........
. . . ........ . . . .........
30 mld 2 00:05:01 60 mld 2 00:05:01
I am going to generate PDF so i want to show 60 records per page. 30 left and 30 right.
It will probably be easiest to display two tables side by side (set each to a width of about half the page and float one to the left or right).
Then your loop can be simple:
$i = -1;
$totalRows = count($rows);
$halfRows = round($numRows / 2);
//construct $headerRow HTML here
foreach ($rows as $row) {
$i++;
if ($i == 0 || $i == $halfRows) {
echo '<table class="'. ($i==0 ? 'floatLeft': '').'">';
echo $headerRow;
}
//Code to output column values here
if ($i == ($halfRows - 1)) {
echo '</table>';
}
}
echo '</table>';

PHP: Can array of numbers add up to number

This is more of a puzzle than anything. I've actually found a solution but it is so slow I thought I lost my internet connection (see below).
Here's the problem:
Let's say I have an array of numbers, like so:
$numbers_array = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
Let's also say that I have a number some numbers, stored in variables like so:
$sum = 15;
$sum2 = 24;
$sum3 = 400;
I am trying to create a function that will return true if any of the numbers in $numbers_array can be added together (each only used once) to form the sums:
function is_summable($array_of_nums, $sum_to_check) {
//What to put here?
}
var_dump(is_summable($numbers_array, $sum));
var_dump(is_summable($numbers_array, $sum2));
var_dump(is_summable($numbers_array, $sum3));
The above should output:
bool(true)
bool(true)
bool(false)
Because 7 + 8 = 15, 7 + 8 + 9 = 24, but no combination of 1-9 can create 200.
Here's my EXTREMELY slow solution:
function is_summable($numbers, $sum) {
//Sort provided numbers and assign numerical keys.
asort($numbers);
$numbers = array_values($numbers);
//Var for additions and var for number of provided numbers.
$total = 0;
$numbers_length = count($numbers);
//Empty var to fill below.
$code = '';
//Loop and add for() loops.
for ($i = 0; $i < $numbers_length; $i++) {
$code .= 'for ($n' . $i . ' = 0; $n' . $i . ' < ' . $numbers_length . '; $n' . $i . '++) {';
if ($i != 0) {
$code .= 'if ($n' . $i . ' != $n' . ($i - 1) . ') {';
}
$code .= '$total += intval($numbers[$n' . $i . ']);';
$code .= 'if ($total == $sum) {';
$code .= 'return true;';
$code .= '}';
}
//Add ending bracket for for() loops above.
for ($l = 0; $l < $numbers_length; $l++) {
$code .= '$total -= intval($numbers[$n' . $i . ']);';
if ($l != 0) {
$code .= '}';
}
$code .= '}';
}
//Finally, eval the code.
eval($code);
//If "true" not returned above, return false.
return false;
}
$num_arr = array(1,2,3,4,5,6,7,8,9);
var_dump(is_summable($num_arr, 24));
http://pastebin.com/1nawuwXK
As always, help is appreciated!!
Your problem is in fact a standard algorithmic problem (as Jon mentioned knapsack problem), more specifically Subset sum problem. It can be solved in polynomial time (have look on wiki page).
Pseudocode:
initialize a list S to contain one element 0.
for each i from 1 to N do
let T be a list consisting of xi + y, for all y in S
let U be the union of T and S
sort U
make S empty
let y be the smallest element of U
add y to S
for each element z of U in increasing order do
//trim the list by eliminating numbers close to one another
//and throw out elements greater than s
if y + cs/N < z ≤ s, set y = z and add z to S
if S contains a number between (1 − c)s and s, output yes, otherwise no

Problems using GROUP BY in MySQL in a query that does a JOIN on two tables

I have two MySQL tables, $database1 and $database2. Both have a field in them called ID. I am passing the name of a town to the file using GET (i.e. it's in the URL of the PHP file that holds this code).
I can run this query...
$PlaceName = $_GET['townName'];
$PlaceName = mysql_real_escape_string($PlaceName);
$sql="SELECT * from $database1 LEFT JOIN $database2 on $database1.ID = $database2.ID WHERE PlaceName='$PlaceName'";
$query = mysql_query($sql);
echo '<h1>People who are searching for '.$PlaceName.':</h1>';
echo '<ul>';
while ($row = mysql_fetch_array($query)) {
echo "<li>ID #",$row['ID'],": ",$row['MemberPersonalName']," ",$row['MemberSurname']," -- searching for ",$row['SurnameBeingSearched'],"</li>";
}
echo '</ul>';
...and it works and all is well. Right now the output looks like this...
People who are searching for Hogwarts:
ID #137: Hermione Granger -- searching for Stern
ID #137: Hermione Granger -- searching for Engelberg
ID #503: Harry Potter -- searching for Kreindler
ID #549: Ron Weasley -- searching for Kreindler
ID #1062: Draco Malfoy -- searching for Engelberg
ID #1155: Ginny Weasley -- searching for Kreindler
ID #1155: Ginny Weasley -- searching for Streisand
But the output needs tweaking, and I'm having trouble writing my SQL query statement to reflect the changes. What I really want is for the output to look like this...
People who are searching for Hogwarts:
Engelberg is being searched by Hermione Granger (id #137) and Draco Malfoy (id #1062)
Kreindler is being searched by Harry Potter (id #503), Ron Weasley (id #549), and Ginny Weasley (id #1155)
Stern is being searched by Hermione Granger (id #137)
Streisand is being searched by Ginny Weasley (id #1155)
In other words, I need to group the output together by the field 'SurnameBeingSearched', I need to list the names of the people doing the searching in an "X, Y, and Z" output format (where it knows where to add a comma, if necessary, depending on the number of results), and I need to order the results by the 'SurnameBeingSearched' field.
Help? Thanks!
You need to list the names so this isn't an aggregation (in the SQL sense) problem. Keep your current query. You're going to have to do the grouping in code.
So something like:
$rows = array();
$last = '';
while ($row = mysql_fetch_array($query)) {
$surname = $row['SurnameBeingSearched'];
$id = $row['ID'];
$name = $row['MemberPersonalName'];
if ($last != $surname) {
$last = $surname;
$rows[] = array();
}
$rows[count($rows)-1][$id] = $name;
}
foreach ($rows as $row) {
// now display each group of names
}
You might also be able to use the MySQL GROUP_CONCAT() function.
It would look something like this...
SELECT places_tbl.name, GROUP_CONCAT(people_tbl.name)
FROM places_tbl
LEFT JOIN people_tbl ON (places_tbl.id = people_tbl.id)
GROUP BY places_tbl.id
GROUP_CONCAT() by default returns the values as comma delimited. You can probably split them up to get the formatting as you need it or use the SEPARATOR keyword. GROUP_CONCAT(fieldname SEPARATOR '-')
$PlaceName = $_GET['townName'];
$PlaceName = mysql_real_escape_string($PlaceName);
// note - added order to the query
$sql="SELECT * from $database1 LEFT JOIN $database2 on $database1.ID = $database2.ID WHERE PlaceName='$PlaceName'
ORDER BY SurnameBeingSearched, MemberSurname, MemberPersonalName";
$query = mysql_query($sql);
echo '<h1>People who are searching for '.$PlaceName.':</h1>';
echo '<ul>';
$cntr = mysql_num_rows($query);
if ($cntr > 0) {
$i = 0;
$srchd = mysql_result($query, $i, 'SurnameBeingSearched');
$mbr = mysql_result($query, $i, 'MemberPersonalName');
$mbr = $mbr . " " . mysql_result($query, $i, 'MemberSurname');
$mbr = $mbr . " (id #" . mysql_result($query, $i, 'ID') . ")";
$lin = $srchd . " is being searched by " . $mbr;
$prev = $srchd;
if ($cntr == 1) {
echo "<li>" . $lin . "</li>";
} else {
for ($i = 1; $i< $cntr; $i++) {
$srchd = mysql_result($query, $i, 'SurnameBeingSearched');
$mbr = mysql_result($query, $i, 'MemberPersonalName');
$mbr = $mbr . " " . mysql_result($query, $i, 'MemberSurname');
$mbr = $mbr . " (id #" . mysql_result($query, $i, 'ID') . ")";
if ($srchd == $prev) { // common search
$j = $i + 1;
if ($j < $cntr) { // still have data
$nxt = mysql_result($query, $j, 'SurnameBeingSearched');
if ($prev == $nxt) { // another one coming -- use the comma
$lin = $lin . ", " . $mbr;
} else {
$lin = $lin . ", and " . $mbr; // last member add the 'and' - line is done
echo "<li>" . $lin . "</li>";
}
$prev = $srchd;
} else { // ran out of data - need to finish the line
$lin = $lin . ", and " . $mbr; // last member add the 'and' - line is done
echo "<li>" . $lin . "</li>";
} else { // new search - need to print this line and start a new one
echo "<li>" . $lin . "</li>";
$lin = $srchd . " is being searched by " . $mbr;
$prev = $srchd;
} // test searched = previous
} // next i
} // only one row
} // cntr > 0
echo '</ul>';
/* note: this is not tested
I would recommend using table1 and table2 instead of database1 and database2
or better give the tables meaningful names
I would use active voice instead of passive voice
*/

Categories