Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 55 total

Two-Dimensional Table

Used for two-dimensional arrays with the nested loops. This example outputs a multiplication table. Ending with 9*9 = 81. Good for general output which must be formatted in a table.

// Loop used for two-dimensional iterations for a table
// useful for tabular output
 for(int x = 1;x<=9;x++)
 {
 	cout<<endl;
 	for(int i = 1;i<=9;i++)
 	{
   	cout<<"\t"<<x*i;
 	}
 }

Sorting Algorithms

This code uses a variety of sorting methods. This code compiles with Borland C++ 5.0 it's useful for seeing how to duplicate the algorithms in other languages. Each sort is found in a separate function called in the main function. This version uses a vector and can sort up to 5 million numbers(possibly more). I suggest larger vectors use the quicksort, unless you want to wait a few days. I find the code fairly concise it makes random numbers depending on the amount you specify for sorting and then outputs the time in seconds to sort the number vector.

It uses an option menu and makes use of
-Bubble Sort
-Selection Sort
-Insertion Sort
-Shell Sort
-Quick Sort

#include "iostream.h"
#include "stdlib.h"
#include "time.h"
#include "conio.h"
#include "vector.h"
using namespace std;
// VIEW RESULTS
void view_sort(vector <int> arr, long max)
{
    for(long x=0;x<max;x++)
    {
        cout<<arr[x]<<"\t";
    }
}
// BUBBLE SORT
vector <int> bubble(vector <int> arr, long max){
int tmp;
for(long i=0;i<max;i++)
{
 for(long x=0; x<max-1-i; x++)
 {
  if(arr[x] > arr[x+1])
    {
    //r.push_back(rnd);
   tmp = arr[x];
   arr[x] = arr[x+1];
   arr[x+1] = tmp;
  }
 }

}
return  arr;
}
// SELECTION SORT
vector <int> select(vector <int> arr, long max){
int tmp;
int min;
for(long i=0;i<max;i++)
{
min = i;
   for(long x=i; x<max; x++)
   {
    if(arr[x] < arr[min])
     {
  min = x;
    }
   }
  tmp = arr[i];
  arr[i] = arr[min];
  arr[min] = tmp;
 }
 return arr;
}
// INSERTION SORT
vector <int> insert(vector <int> arr, long max)
{
int i, j, index;
for(i=1; i < max;i++)
{
    index  = arr[i];
    j = i;
    while((j > 0) && (arr[j-1] > index))
       {
        arr[j] = arr[j-1];
        j = j-1;
       }
   arr[j] = index;
}
return arr;
}
// SHELL SORT
vector <int> shell(vector <int> arr, long max){

int index, i, j;
for(i=1; i < max;i++)
{
    index  = arr[i];
    j = i;
    while((j > 0) && (arr[j-1] > index))
       {
        arr[j] = arr[j-1];
        j = j-1;

      }
   arr[j] = index;
}
return arr;
}
/* ######## QUICK SORT ######### */
void quicksort(vector <int> & arr, int start, int end){
int pivot, starth, endh; // store pivot # keep start & end in memory for split
starth = start;
endh = end;
pivot = arr[start];

while(start < end)
{
 while((arr[end] >= pivot) && (start < end))
  end--;
    if (start != end)
    {
      arr[start] = arr[end];
      start++;
    }
  while ((arr[start] <= pivot) && (start < end))
      start++;
    if (start != end)
    {
      arr[end] = arr[start];
      end--;
    }
}
arr[start] = pivot;
pivot = start;
start = starth;
end = endh;
if(start < pivot)
quicksort(arr, start, pivot-1);
if(end > pivot)
quicksort(arr, pivot+1, end);
}

/* BEGIN MAIN */
int main(){
time_t start;
long rnd = rand()%1000+1;
vector <int> r;
//long r[200001];
long tmp;
long maxnum; // if you overload this variable, beware!
int option;
bool stop = false;
bool view = false;
while(!stop){
cout<<"\t\t\tAlgorithms For Sorting Numbers\n"<<endl;

cout<<"Choose Method:\n[1] Bubble\n[2] Selection\n[3] Insertion\n[4] Shell Sort\n[5] Quick Sort";
cin>>option;

// ARRANGE ARRAY
cout<<"Length (<=5000000 )\n";
cin>>maxnum;

if(maxnum == 1)
maxnum = 1000000;

for(long x=0;x<maxnum;x++)
{
long rnd = rand()%1000+1;
//cout<<rnd<<"\t";
r.push_back(rnd);
}
// END ARRANGE ARRAY

start = time(NULL);
if(option == 1)
r = bubble(r,maxnum);
if(option == 2)
r = select(r,maxnum);
if(option == 3)
r = insert(r,maxnum);
if(option == 4)
r = shell(r,maxnum);
if(option==5)
quicksort(r,0,maxnum-1);
time_t stopclock;
stopclock = time(NULL);
// print time result

cout<<endl<<double(stopclock)-start<<"[seconds]";
// view sort results?
cout<<"\nView the sorted numbers? [1=yes||0=no]";
int v;
cin>>v;
if(v == 1)
{
view = true;
view_sort(r,maxnum);
}
// end program?
cout<<endl<<"Press 0 to quit any key to continue";
int s;
cin>>s;
if(s == 0)
stop = true; clrscr();
}
}

Call Total Number From MySQL Row

// Call total count from MySQL row

<?
// Query the database and get the count
$result = mysql_query("SELECT * FROM TABLE_NAME");
$num_rows = mysql_num_rows($result);

// Display the results
echo $num_rows;
?>

Connect to MySQL

// Connect to MySQL Database

//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","username","password"); //(host, username, password)

//specify database ** EDIT REQUIRED HERE **
mysql_select_db("database") or die("Unable to select database"); //select which database we're using

Local Time & Date

// description of your code here

<?php
$timezone = "the UK";
$time_diff = "0";
$alter = ($time_diff * 60 * 60);
$date_today = date ("l F jS Y", time () + $alter);
$time_now = date ("h:ia", time () + $alter);

echo "It's currently <strong>$time_now</strong> on <strong>$date_today</strong> in <strong>$timezone</strong>.";
?>

Back to Top

// description of your code here

<a href="#" onclick="window.scrollTo(0,0); return false">Back to Top</a>

Forward, Top & Back

// Link forward, top and back on your pages

<a href="javascript:history.back();">Back A Page</a> | <a href="#" onclick="window.scrollTo(0,0); return false">Back to Top</a> | <a href="javascript:history.forward();">Forward A Page</a>

Javascript Image PreLoad

// Javascript Image Preload
<script type="text/javascript">
    <!--

    if (document.images)
    {
      preload_image_object = new Image();
      // set image url
      image_url = new Array();
      image_url[0] = "http://mydomain.com/image0.gif";
      image_url[1] = "http://mydomain.com/image1.gif";
      image_url[2] = "http://mydomain.com/image2.gif";
      image_url[3] = "http://mydomain.com/image3.gif";

       var i = 0;
       for(i=0; i<=3; i++) 
         preload_image_object.src = image_url[i];
    }

    //-->
    </script> 

Page Last Modified

// PHP snippet to output the date a file was last updated

<?
$last_modified = filemtime("pagename.php");
print("Last Modified");
print(date("j/m/y h:i", $last_modified));
?>

PHP Recursive Directory Traversal

This an unstyled script which is useful for viewing directories and sub-directories. It's easy to style making it a nice script. I tried to comment things out as clearly as I could. This script should work as is, but if you are reading a remote directory the $start_dir variable should be edited.
<?
#############################################
#This codes holds no license.               #
#Created in part by harkey of harkeyahh.com #
#############################################
/* Edited from PHPBuilder.com */
function readpath($dir,$level,$last,&$dirs,&$files){
	//print $dir." (DIR)<br/>\n";
	$dp=opendir($dir);
	while (false!=($file=readdir($dp)) && $level == $last){
		if ($file!="." && $file!="..")
                {
			if (is_dir($dir."/".$file))
			{
				readpath($dir."/".$file,$level+1,$last,$dirs,$files); // uses recursion
				$dirs[] = "$dir/$file";  // reads the dir into an array
			}
			else{
				$files[] = "$dir/$file"; // reads the file into an array
			}
		}
	}
}
/* From PHP.NET */
function get_size($path)
   {
       if(!is_dir($path))return filesize($path);
       $dir = opendir($path);
       while($file = readdir($dir))
       {
           if(is_file($path."/".$file))$size+=filesize($path."/".$file);
           if(is_dir($path."/".$file) && $file!="." && $file !="..")$size +=get_size($path."/".$file);
          
       }
       return $size;
   }
#####################
/* BEGIN MAIN CODE */
#####################
if(isset($_GET['i'])){
$start_dir = $_GET['i']; // this fetches the i or directory name through a link specified via the url.
}
else{    // else if no name is specified by link, then use the default
$start_dir = ".";   // . means the current directory or whatever name you specify
}

$level=1;  // level is the first level started at
$last=1; //this is set the same as level so the script does not read all directories, and only one at a time
$dirs = array();  // SET dirs as an ARRAY so it can be read
$files = array(); //SET files as an ARRAY so it can be read

readpath($start_dir,$level, $last, $dirs,$files);
?>

<strong>Sub Directories in <?=$start_dir?></strong><br/>
<?php
sort($dirs);

if(empty($dirs))   // checks if the dirs array is empty. if so, then display "empty"
{
echo"empty";
}
/* SHOWS THE DIRECTORIES FROM ARRAY */
foreach($dirs as $dir)
{
echo "<a href=\"$PHP_SELF?i=$dir\">$dir</a><br/>\n";//Creates a link to the dir through the script so it will be shown.
}
?>

<?php
/* SHOWS FILES FROM ARRAY*/
$tf = count($files);
echo "Local Files Total: $tf"; /* Display total in directory*/

sort($files);   // Sort the files alphabetically

foreach($files as $file)
{     //Below PHP functions are used to display file stats such as creation time, permissions etc.
echo "<br/><a href=\"$file\">$file</a> <strong>mtime:</strong>".date("U",@filemtime($file))." || ".date("(F)m.d.y",@filemtime($file));
echo " <strong>size:</strong>".get_size($file);
echo " <strong>mode:</strong>".substr(sprintf('%o', @fileperms($file)), -3);
echo "<br/>\n";
}
?>
« Newer Snippets
Older Snippets »
Showing 11-20 of 55 total