Archive for the 'Javascript' Category

01
May
09

[Javascript/Php] Neopets Auction Bot Project (3)

The latest update to the auction bot.

*IF YOU WANT TO USE THIS, YOU HAVE TO CONTACT ME*
The reason for it being private, is nothing to do with me being selfish or anything, but the fact that this script queries my MySQL database between 6-10 times a minute, and I dont want it to run too slowly. Ive posted everything required to set it up here, however, if you need help, feel free to contact me (Details: my contact details -> about)

Its almost fully automated now, refreshing, opening, closing pages correctly.
There are only a few things to sort out, but to the average user these problems aren’t noticeable (check the grease monkey var for the script after running it for a while -_-)

Source for the PHP remains the same, so check the other posts.
Below is the greasemonkey script:

// ==UserScript==
// @name           Aucti0n b0t - sim0n
// @namespace      Neopets
// @description    https://sim0n.wordpress.com
// @include        http://www.neopets.com/auctions.phtml*
// ==/UserScript==

//Functions
//------------------------------
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
	var oCurrent;
	var oAttribute;
	for(var i=0; i<arrElements.length; i++){
		oCurrent = arrElements[i];
		oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
		if(typeof oAttribute == "string" && oAttribute.length > 0){
			if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
				arrReturnElements.push(oCurrent);
			}
		}
	}
	return arrReturnElements;
}
function createErrorBox(docTitle, boxHeight, content, contentSize) {
	if(docTitle != "") { document.title = docTitle };
	var size = "100px;";
	if(boxHeight != '') { size = boxHeight + "px"; }
	var darkenScreen = document.createElement('div');
	darkenScreen.setAttribute('style', 'position:fixed;left:0;top:0;width:100%;height:100%;background:#000000;opacity:0.8');
	document.body.appendChild(darkenScreen);
	var errorBox = document.createElement('div');
	var left = (document.documentElement.clientWidth /2)-150;
	errorBox.setAttribute('style', 'width:300px; ' + size + ' border:#990000 thick solid; background:#CCCCCC;padding:6px;position:fixed;left:' + left + 'px;top:100px;');
	for(var i = 1; i<contentSize; i++) {
		errorBox.appendChild(content[i]);
	}
	document.body.appendChild(errorBox);
}
function closeWindow() {
	var errorTitle = document.createElement('span');
	errorTitle.setAttribute('style', 'font-family:Georgia; text-align:center; font-weight:bold;z-index:9999');
	errorTitle.appendChild(document.createTextNode('Error'));
	var errorBold = document.createElement('b');
	var errorItalic = document.createElement('i');
	errorItalic.appendChild(document.createTextNode('dom.allow_scripts_to_close_windows'));
	errorBold.appendChild(errorItalic);

	var elemArray = {
		1 : errorTitle,
		2 : document.createElement('br'),
		3 : errorBold,
		4 : document.createTextNode(' is false.'),
		5 : document.createElement('br'),
		6 : document.createTextNode('To enable it, navigate to about:config and change the value from False to True')
	}

	createErrorBox('Close error - click for details', '', elemArray, 7);
	window.close();
}
function removeImages() {
	var images=document.images;
	for(var x=0;x<images.length;i++){
		images[x].parentNode.removeChild(images[x]);
	}
}
function parseUrl(max_price) {
	return String(document.location).substring(String(document.location).lastIndexOf("=")+1);
}
function removeBidCookie(link) {
	var curID = link.replace(/.*auction_id=(\d*).*/, "$1");
	var cur = String(GM_getValue('currentAuctions'));
	cur = cur.replace(curID + "|", "");
	GM_setValue('currentAuctions', cur);
}

//Main Page Functions
//------------------------------
function queryNeopetItem(item, complete) {
	//Create a httpRequest, the php script returns a list of items max price + sell price
	//Format:
	//maxprice[0]	sellprice[0]
	//maxprice[1]	sellprice[1]
	//maxprice[n-1]	sellprice[n-1]
	//maxprice[n]	sellprice[n]
	//complete is a function that parses the responseText
	url = "http://myhost.com/queryv2.php?items=" + item;
	GM_xmlhttpRequest({
		method: "POST",
		url: url,
		headers:{'Content-type':'application/x-www-form-urlencoded'},
		data:encodeURI(""),
		onload: function(xhr) { complete(xhr.responseText); }
	});
}
function comp(text) {
	//Splits each line
	var items = text.split("\n");
	//We only want 20 lines (20 items per page)
	for(var i = 0;i<20;i++) {
		if(items[i] == "" || String(items[i]) == "undefined") {
			//Item not in database
			table[0].rows[i+1].setAttribute("bgcolor","#ccffd0");
		} else {
			//Split max/min price
			var item = items[i].split("\t");
			//Get the items current price, check its less
			var cur_price = table[0].rows[i+1].cells[6].innerHTML.replace(/<b>(\d*)<\/b> NP/, "$1");
			if(Number(cur_price)<=Number(item[0])) {
				//If it is less, check if its a NF auction or not
				if(table[0].rows[i+1].cells[3].innerHTML.toLowerCase().indexOf("<b>[nf]</b>") != -1) {
					//If it is, ignore it
					table[0].rows[i+1].setAttribute("bgcolor","#aaafa0");
				} else {
					//Else, open the page in a new tab
					table[0].rows[i+1].setAttribute("bgcolor","#00ffff");
					doAuction(table[0].rows[i+1].cells[2].getElementsByTagName('a')[0], item[0]);
				}
			} else {
				table[0].rows[i+1].setAttribute("bgcolor","#aaffd0");
			}
		}
	}
}
function doAuction(link, max_price) {
	//Used to open the selected auction in a new tab with max price in the url
	var curID = link.href.replace(/.*auction_id=(\d*)/, "$1");
	var cur = String(GM_getValue('currentAuctions'));
	if(cur=="undefined") {cur="";}
	if(cur.indexOf(curID) == -1) {
		var x = cur + curID + "|";
		GM_setValue('currentAuctions', x);
		GM_openInTab(link.href + "&maxprice=" + max_price);
		GM_log("Opened: " + curID);
	}
}

//Script testing
//------------------------------

//Script
//------------------------------
var url = String(document.location);
if(url.indexOf('placebid') == -1 && url.indexOf('bids') == -1) {

	//The main auction page - Create list of items
	removeImages();
	var table = getElementsByAttribute(document.body, "table", "align", "center");
	var queryString = "";
	for(var i=1;i<table[0].rows.length - 1;i++) {
		queryString = queryString + table[0].rows[i].cells[2].innerHTML.replace(/<a href=\".*\">(.*)<\/a>/, "$1") + "|";
	}
	queryString = queryString + table[0].rows[table[0].rows.length-1].cells[2].innerHTML.replace(/<a href=\".*\">(.*)<\/a>/, "$1")
	//Query the database
	queryNeopetItem(queryString, comp);

	var minTime = 6;
	var maxTime = 10;
	var PERIOD = (maxTime * 1000 - minTime * 1000) * Math.random() + minTime * 1000;
	setTimeout('location.reload(true)', PERIOD);

} else if(url.indexOf('bids') != -1 && url.indexOf('maxprice') != -1) {

	//Place bid
	if ((window.find("Time Left in Auction :  Closed" , false, true) == false) && (window.find("Oops! - Invalid Auction ID") == false)) {
		//Valid auction
		var max_price = parseUrl();
		var name = getElementsByAttribute(document.getElementById('header'), 'td', 'class', 'user medText')[0].firstChild.nextSibling.textContent;
		var table = getElementsByAttribute(document.body, 'table', 'cellpadding', 4)[0];
		var lastbidder = "";
		if(table) {
			lastbidder = table.rows[1].cells[0].textContent.substring(1);
		}
		if(lastbidder==name) {
			//If last bidder was user reload after 2 seconds
			setTimeout('location.reload(true)', 3);
		} else {
			//Else, check to make sure its worth paying for
			if(Number(document.getElementsByName('amount')[0].value) <= Number(max_price)) {
				//Modify the form to add our max price
				var forms = document.getElementsByTagName("form");
				for(var i=0;i<forms.length;i++) {
					if(forms[i].getAttribute('action') == "auctions.phtml?type=placebid") {
						forms[i].setAttribute('action', "auctions.phtml?type=placebid&maxprice=" + max_price)
					}
				}
				//Submit the form
				var button = getElementsByAttribute(document.body, 'input', 'value', 'Place a Bid')[0];
				button.form.submit();
			} else {
				//too expensive */.
				GM_log("Closed: " + url);
				removeBidCookie(url)
				closeWindow();
			}
		}
	} else {
		// Will need to add in checking later on for who won the bid */.
		removeBidCookie(url);
		GM_log("Closed: " + url);
		closeWindow();
	}
} else if(url.indexOf('placebid') != -1) {

	//After placing bid
	var max_price = parseUrl();
	if(document.body.innerHTML.indexOf("BID SUCCESSFUL") != -1) {
		//Bid worked
		var link = document.getElementsByTagName('a');
		var s = 'http://www.neopets.com/auctions.phtml?type=bids&auction_id='
		for(var i = 0; i < link.length; i++) {
			var str = link[i].href;
			str = str.substr(0, 59)
			if(str == s) { document.location = link[i].href + "&maxprice=" + max_price; }
		}
	} else if(document.body.innerHTML.indexOf("The current asking price for this item") != -1) {
		//Bid not enough error
		var link = document.getElementsByTagName('a');
		var s = 'http://www.neopets.com/auctions.phtml?type=bids&auction_id='
		for(var i = 0; i < link.length; i++) {
			var str = link[i].href;
			str = str.substr(0, 59)
			if(str == s) { document.location = link[i].href + "&maxprice=" + max_price; }
		}
	} else if(document.body.innerHTML.indexOf("You must wait a few more seconds") != -1) {
		//Too fast
		history.go(-1);
	} else if(document.body.innerHTML.indexOf("You don't have enough money to place that bid") != -1 || document.body.innerHTML.indexOf("This auction is closed") != -1 || document.body.innerHTML.indexOf("Invalid Auction ID") != -1) {
		//Not enough money or auction is over */.
		closeWindow();
	}

}

Theres also a clue in this post as to how you can easily access my host if you want, its kinda… obvious.

Remember, this isnt the final product. Its still being worked on.

Advertisements
28
Apr
09

[Javascript/Php] Neopets Auction Bot Project (2)

A much faster script than my previous version. Instead of querying each item individually, it loops through the items in the list and uses the queryNeopetItem to send the data to another php page, which pareses the items and returns the prices of each of them. When the data is returned, it is then split and the table is formatted depending on what action should be taken (light green=no data, medium green=more expensive than data, grey = neofriend only, blue = make profit)

Neopets auction highlight


And below is the source for the greasemonkey script:

// ==UserScript==
// @name           AuctionBot test v2
// @namespace      Sim0n NeoPets
// @include        http://www.neopets.com/auctions.phtml
// ==/UserScript==

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
	var oCurrent;
	var oAttribute;
	for(var i=0; i<arrElements.length; i++){
		oCurrent = arrElements[i];
		oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
		if(typeof oAttribute == "string" && oAttribute.length > 0){
			if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
				arrReturnElements.push(oCurrent);
			}
		}
	}
	return arrReturnElements;
}

function queryNeopetItem(item, complete) {
	url = "myphpquery.php?items=" + item;
	GM_xmlhttpRequest({
		method: "POST",
		url: url,
		headers:{'Content-type':'application/x-www-form-urlencoded'},
		data:encodeURI(""),
		onload: function(xhr) { complete(xhr.responseText); }
	});
}
function comp(text) {
	var items = text.split("\n");
	for(var i = 0;i<20;i++) {
		if(items[i] == "") {
			table[0].rows[i+1].setAttribute("bgcolor","#ccffd0");
		} else {
			var item = items[i].split("\t");
			var cur_price = table[0].rows[i+1].cells[6].innerHTML.replace(/<b>(\d*)<\/b> NP/, "$1");
			if(Number(cur_price)<=Number(item[0])) {
				if(table[0].rows[i+1].cells[3].innerHTML.toLowerCase().indexOf("<b>[nf]</b>") != -1) {
					table[0].rows[i+1].setAttribute("bgcolor","#aaafa0");
				} else {
					alert(table[0].rows[i+1].cells[3].innerHTML)
					table[0].rows[i+1].setAttribute("bgcolor","#00ffff");
				}
			} else {
				table[0].rows[i+1].setAttribute("bgcolor","#aaffd0");
			}
		}
	}
}
var table = getElementsByAttribute(document.body, "table", "align", "center");
var queryString = "";
for(var i=1;i<table[0].rows.length - 1;i++) {
	queryString = queryString + table[0].rows[i].cells[2].innerHTML.replace(/<a href=\".*\">(.*)<\/a>/, "$1") + "|";
}
queryString = queryString + table[0].rows[table[0].rows.length-1].cells[2].innerHTML.replace(/<a href=\".*\">(.*)<\/a>/, "$1")
queryNeopetItem(queryString, comp);

And for the php query:

<?php
	$dbhost = 'a';
	$dbuser = 'b';
	$dbpass = 'd';
	$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('0');
	$dbname = 'e';
	mysql_select_db($dbname);

	$items = explode("|", $_GET['items']);
	for($i=0;$i<count($items);$i++) {
		$sqlQuery = "ITEM_NAME = '$items[$i]'";
		$result = mysql_query("SELECT * FROM  Neopets_Items WHERE $sqlQuery");
		$any = false;
		while($row = mysql_fetch_array($result))
  		{
			$any = true;
  			echo $row['MAX_PRICE'] . "\t" . $row['SELL_PRICE'] . "\n";
  		}
		if($any==false) {
			echo "\n";
		}
	}
	mysql_close($conn);
?> 
28
Apr
09

[Javascript/Php] Neopets Auction Bot Project (1)

Ive been asked by somebody to create a bot for the game Neopets that will view the most recent auctions and bid upon items which on which money can be easily made. One of the constraints for this project, was that it must be made using Javascript + Greasemonkey, so no Perl or Python (or whatever it is people use to code bots on the net these days! Like I know -_-).
My initial attempt (below) uses the GM_xmlhttpRequest to query a database of items (that’s another project ^_^ – lots of faces today?), and it works very nicely, except for one small thing. Its ridiculously slow. It query the database for each of the items, and then either marks it with a green colour to indicate that it is loaded, but you will not make money off it, or will highlight the row brown to show that you will make money off the auction.
Remeber, its v. slow!
Still, here is the source code as it is a nice example of a recursive function and sending & retrieving data to other websites using Greasemonkey.

// ==UserScript==
// @name           Auc7i0nb0t t3s7
// @namespace      n30p375
// @include        http://www.neopets.com/auctions.phtml
// ==/UserScript==

//Some function from google - kinda overkill, but meh.
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
	var oCurrent;
	var oAttribute;
	for(var i=0; i<arrElements.length; i++){
		oCurrent = arrElements[i];
		oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
		if(typeof oAttribute == "string" && oAttribute.length > 0){
			if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
				arrReturnElements.push(oCurrent);
			}
		}
	}
	return arrReturnElements;
}

function queryNeopetItem(item, complete) {
	url = "url to my item query page.php?item=" + item;
	GM_xmlhttpRequest({
		method: "POST",
		url: url,
		headers:{'Content-type':'application/x-www-form-urlencoded'},
		data:encodeURI(""),
		onload: function(xhr) { complete(xhr.responseText); }
	});
}
var x = 1;
var table = getElementsByAttribute(document.body, "table", "align", "center");
var item_name = table[0].rows[x].cells[2].innerHTML.replace(/<a href=\".*\">(.*)<\/a>/, "$1");
function comp(text) {
	var ta = text.split("\n");
	max_price = ta[1];
	sell_price = ta[2];
	if(x<table[0].rows.length) {
		item_name = table[0].rows[x].cells[2].innerHTML.replace(/<a href=\".*\">(.*)<\/a>/, "$1");
		queryNeopetItem(item_name, comp)
		table[0].rows[x-1].setAttribute("bgcolor","#ccffd0");
		if(ta[1].indexOf("www.mywebhostsname.com") == -1) {
			var str = table[0].rows[x-1].cells[6].innerHTML.replace(/<b>(\d*)<\/b> NP/, "$1");
			if(Number(str)<=Number(max_price)) {
				table[0].rows[x-1].setAttribute("bgcolor","#dc9423");
			}
		}
		x++;
	} else {
		item_name = table[0].rows[x-1].cells[2].innerHTML.replace(/<a href=\".*\">(.*)<\/a>/, "$1");
		table[0].rows[x-1].setAttribute("bgcolor","#ccffd0");
		if(ta[1].indexOf("www.mywebhostsname.com") == -1) {
			var str = table[0].rows[x-1].cells[6].innerHTML.replace(/<b>(\d*)<\/b> NP/, "$1");
			if(str<=max_price) {
				table[0].rows[x-1].setAttribute("bgcolor","#dc9423");
			}
		}
		table[0].appendChild(document.createTextNode("Complete"));
	}
}
queryNeopetItem(item_name, comp);

url to my item query page.php?item is a page that querys the database and returns the items details (Max Price and Sell Price). The above function is recursive, as queryNeopetItem calls the function comp (which parses the text returned from the httpRequest) which, in turn calls queryNeopetItem again, until all the rows items have been queried.

<php
	$dbhost = 'x';
	$dbuser = 'y';
	$dbpass = 'z';
	$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('0');
	$dbname = 'a';
	mysql_select_db($dbname);

	$item = $_GET['item'];
	$max = $_GET['max'];
	$sell = $_GET['sell']; 

	$sqlQuery = "";

		if($item != "") {
			$sqlQuery = "ITEM_NAME = '$item'";
		}
		if($max != "") {
			if($sqlQuery != "") {
				$sqlQuery = $sqlQuery . " AND MAX_PRICE = '$max'";
			} else {
				$sqlQuery = "MAX_PRICE = '$max'";
		}
		}
		if($sell != "") {
			if($sqlQuery != "") {
				$sqlQuery = $sqlQuery . " AND SELL_PRICE = '$sell'";
			} else {
				$sqlQuery = "SELL_PRICE = '$sell'";
			}
		}

		$result = mysql_query("SELECT * FROM  Neopets_Items WHERE $sqlQuery");

		while($row = mysql_fetch_array($result))
  		{
  			echo $row['ITEM_NAME'] . "\n" . $row['MAX_PRICE'] . "\n" . $row['SELL_PRICE'];
  		}

	mysql_close($conn);
?> 

That code is kind of overkill for the query that the script makes, however it also allows you to query by a combination of the items properties which will be used later on in the project (probably)

04
Apr
09

[Javascript] Synthetic Division

An easier method of dividing polynomials.
This function uses synthetic division to divide a polynomial by a simple ax+b
The polynomial must be in the format of a1x^n + a2x^(n-1) + a3x^(n-2)…aix^(nn)

function syntheticDivision(poly, division) {
	//Format the equations correctly
	poly = poly.replace(/(--|\+\+)/g, "+");
	poly = poly.replace(/(-\+|\+-)/g, "-");
	poly = poly.replace(/^\+/g, "");
	poly = poly.replace(/\s/g, "");
	division = division.replace(/(--|\+\+)/g, "+");
	division = division.replace(/(-\+|\+-)/g, "-");
	division = division.replace(/^\+/g, "");
	division = division.replace(/\s/g, "");
	//Remove all x's and powers
	poly = poly.replace(/x\^?\d?/g, "");
	//Add spaces to the equation to break it apart
	poly = poly.replace(/([+-])/g, " $1");
	//Split the equation at the spaces
	var equ = poly.split(" ");
	//Rearrange division to equal 0
	var divide = division.split("x")[0]
	if(divide==""){ divide="1"; }
	division = (~Number(division.split("x")[1])+1)/divide;
	//Begin division
	var output = ""
	var lastTerm = "0"
	for(var i=0;i<equ.length-1;i++) {
		if(equ[i].split("x")=="+" || equ[i].split("x")=="-") { equ[i] = equ[i]+"1" }
		var dt = Number(Number(equ[i]) + Number(lastTerm));
		var x = (dt/divide);
		output += x + "x^" + (equ.length-i-2) + "+";
		lastTerm = dt * division;
	}
	//Format output
	output = output.replace(/\+([+-])/g, "$1");
	output = output.replace(/0x\^\d/g, "");
	output = output.replace(/(x\^0)?\+$/g, "");
	output = output.replace(/x\^1/g, "x");
	//Calculate remainder
	output += " : Remainder [" + String(Number(equ[equ.length-1]) + Number(lastTerm)) + "]";
	return(output);
}

Usage:

<script language="javascript" type="text/javascript">
var poly = "14x^4-5x^3-11x^2-11x+8";
var division = "2x-1";
alert(syntheticDivision(poly, division));
</script>

Would output:
7x^3 + 1x^2 – 5x -8 : Remainder [0]

04
Apr
09

[Javascript] Simple Polynomial Long Division

This function uses long division to divide a polynomial by a simple ax+b

The polynomial must be in the format of ax^n + bx^(n-1) + cx^(n-2)…zx^(nn)

The function itself relies upon 4 other functions in order to work, these are used to carry out basic operations on the terms in the polynomail:

//Used to break an { ax^n } into its compontents
function extractCompontents(Term, constantChar) {
	var Comps = new Array();
	Comps[0] = Term.split(constantChar)[0];
	Comps[1] = Term.split("^")[1];
	if(Comps[0] == "") { Comps[0]=1; }
	if(String(Comps[1]) == "undefined") { Comps[1]=1; }
	return Comps;
}
function divideTerm(Term1, Term2, constantChar) {
    var extTerm1 = extractCompontents(Term1, constantChar)
	var extTerm2 = extractCompontents(Term2, constantChar)
	return String(extTerm1[0]/extTerm2[0]) + constantChar + "^" + String(extTerm1[1]-extTerm2[1]);
}
function multiplyTerm(Term1, Term2, constantChar) {
	var extTerm1 = extractCompontents(Term1, constantChar)
	return String(extTerm1[0] * Term2) + constantChar + "^" + String(extTerm1[1]);
}
function subtractTerm(Term1, Term2, constantChar) {
    var extTerm1 = extractCompontents(Term1, constantChar)
	var extTerm2 = extractCompontents(Term2, constantChar)
	if(extTerm1[1] != extTerm2[1]) { return null; }
	return String(extTerm1[0]-extTerm2[0]) + constantChar + "^" + String(extTerm1[1]);
}

The function itself is as follows:

function longAlgebraicDivision(poly, division) {
	//Format the equations correctly
	poly = poly.replace(/(--|\+\+)/g, "+");
	poly = poly.replace(/(-\+|\+-)/g, "-");
	poly = poly.replace(/^\+/g, "");
	poly = poly.replace(/\s/g, "");
	division = division.replace(/(--|\+\+)/g, "+");
	division = division.replace(/(-\+|\+-)/g, "-");
	division = division.replace(/^\+/g, "");
	division = division.replace(/\s/g, "");
	//Add spaces to the equation to break it apart
	poly = poly.replace(/([+-])/g, " $1");
	//Split the equation at the spaces
	var equ = poly.split(" ");
	//Begin the division
	var output = ""
	var lastTerm = ""
	for(var i=0;i<equ.length-1;i++) {
		var term = equ[i];
		if(i==0) {
			var dt = divideTerm(term, division.split("x")[0], "x");
			output += dt + "+";
			dt = multiplyTerm(dt, division.split("x")[1], "x");
			lastTerm = dt;
		}else{
			var dt = subtractTerm(term, lastTerm, "x");
			dt = divideTerm(dt, division.split("x")[0], "x");
			output += dt + "+";
			dt = multiplyTerm(dt, division.split("x")[1], "x");
			lastTerm = dt;
		}
	}
	//Format output
	output = output.replace(/\+([+-])/g, "$1");
	output = output.replace(/x\^0\+$/g, "");
	output = output.replace(/x\^1/g, "x");
	//Calculate remainder
	lastTerm = lastTerm.replace(/x\^0/g, "");
	output += " : Remainder [" + String(Number(equ[equ.length-1]) - Number(lastTerm)) + "]";
	return output;

Usage:

<script language="javascript" type="text/javascript">
var poly = "14x^4-5x^3-11x^2-11x+8";
var division = "2x-1";
alert(longAlgebraicDivision(poly, division));
</script>

Would output:

7x^3 + 1x^2 – 5x -8 : Remainder [0]

04
Apr
09

[Javascript] Divide Simple Algebraic Terms

Been working on some maths things today, and wrote this function to divide basic terms.
Will work on any string in the format of:
ax^n; where a = any number, x = any constant character, n = any number

function divideTerm(Term1, Term2, constantChar) {
	//The coefficient of the first Term
	var Term1coeff = Term1.split(constantChar)[0];
	//The power of the first Term
	var Term1power = Term1.split("^")[1];
	//The coefficient of the second Term
	var Term2coeff = Term2.split(constantChar)[0];
	//The power of the second Term
	var Term2power = Term2.split("^")[1];
	//If no coefficient, set to 1
	if(Term1coeff==""){Term1coeff=1;}
	//If no power, set to 1
	if(String(Term1power)=="undefined"){Term1power=1;}
	//If no coefficient, set to 1
	if(Term2coeff==""){Term2coeff=1;}
	//If no power, set to 1
	if(String(Term2power)=="undefined"){Term2power=1;}
	//Divide the two coefficients, add the character and claret, subtract the two powers
	return String(Term1coeff/Term2coeff) + constantChar + "^" + String(Term1power-Term2power);
}

Usage:
Sample project:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dividing Alg Terms</title>
<script language="javascript" type="text/javascript">
function divideTerm(Term1, Term2, constantChar) {
	var Term1coeff = Term1.split(constantChar)[0];
	var Term1power = Term1.split("^")[1];
	var Term2coeff = Term2.split(constantChar)[0];
	var Term2power = Term2.split("^")[1];
	if(Term1coeff==""){Term1coeff=1;}
	if(String(Term1power)=="undefined"){Term1power=1;}
	if(Term2coeff==""){Term2coeff=1;}
	if(String(Term2power)=="undefined"){Term2power=1;}
	return String(Term1coeff/Term2coeff) + constantChar + "^" + String(Term1power-Term2power);
}

function divide() {
	document.getElementById("result").value = divideTerm(
		document.getElementById("trm1").value,
		document.getElementById("trm2").value,
		document.getElementById("char").value);
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <table width="297" border="0">
    <tr>
      <td width="143"><strong>Term 1: </strong></td>
      <td width="144"><input name="textfield3" type="text" id="trm1" value="147x^23" /></td>
    </tr>
    <tr>
      <td><strong>Term 2: </strong></td>
      <td><input name="textfield4" type="text" id="trm2" value="24.5x^19" /></td>
    </tr>
    <tr>
      <td><strong>Constant Character: </strong></td>
      <td><input name="textfield" type="text" id="char" value="x" /></td>
    </tr>
    <tr>
      <td colspan="2"><div align="center">
        <br />
	    <input name="button" type="button" value="Divide" onclick="divide()" />
      </div></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td><strong>Result:</strong></td>
      <td><input type="text" name="textfield2" readonly="true" id="result"/></td>
    </tr>
  </table>
  </form>
</body>
</html>

E.g.
147xy^23/24.5xy^19 = 6xy^4

01
Apr
09

[Javascript] Number Format String (2)

Second one, similar to the last but instead of reversing twice, it builds the string backwards then reverses it.

function numberFormat_2(text) {
	//Loop backwards through the string
	//Add every character
	//If index = 3, add comma
	//Reverse string;
	var i = text.length;
	var output = "";
	var k=0;
	var j=-1;
	while (i > -1) {
		output += text.charAt(i);
		j++;
		if(j==3 && i !=0) {
			output += ",";
			j=0;
		}
		i--;
	}
	output = output.split("").reverse().join("");
	return output
}

Usage:

	var text = "123456789123456789";
	text = numberFormat_2(text);
	alert(text);

Would Output:

123,456,789,123,456,789