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 1-9 of 9 total  RSS 

Simple integer expression interpreter

This is a simple integer expression interpreter.

#include <iostream>
#include <string>
#include <map>
#include <cctype>

char look;
std::map<std::string, int> table;

void getChar() {
    look = std::cin.get();
}

void error(const std::string &s) {
    std::cout << std::endl;
    std::cout << "Error: " << s << "." << std::endl;
}

void abort(const std::string &s) {
    error(s);
    exit(1);
}

void expected(const std::string &s) {
    abort(s + " Expected");
}

bool isAlpha(char c) {
    return isalpha(c);
}

bool isDigit(char c) {
    return isdigit(c);
}

bool isAlNum(char c) {
    return isalnum(c);
}

bool isAddop(char c) {
    return ((c == '+') || (c == '-'));
}

bool isMulop(char c) {
    return (('*' == c) || ('/' == c));
}

bool isWhite(char c) {
    return ((' ' == c) || ('\t' == c));
}

void skipWhite() {
    while (isWhite(look))
        getChar();
}

void match(char x) {
    if (look != x)
        expected(std::string("\"") + x + "\"");
    else {
        getChar();
        skipWhite();
    }
}

void emit(const std::string &s) {
    std::cout << "\t"  << s;
}

void emitLn(const std::string &s) {
    emit(s);
    std::cout << std::endl;
}

void newLine() {
    if (look == '\n')
        getChar();
}

std::string getName() {
    if (!isAlpha(look))
        expected("Name");

    std::string name;
    while (isAlNum(look)) {
        name += look;
        getChar();
    }
    skipWhite();

    return name;
}

int getNum() {
    int value(0);

    if (!isDigit(look))
        expected("Integer");

    while (isDigit(look)) {
        value = value * 10 + look - '0';
        getChar();
    }
    skipWhite();

    return value;
}

int expression();

int factor() {
    int ret;

    if (look == '(') {
        match('(');
        ret = expression();
        match(')');
    } else if (isAlpha(look)) {
        std::string name = getName();
        if (table.count(name) == 0)
            table.insert(std::pair<std::string, int>(name, 0));
        ret = table[name];
    } else
        ret = getNum();

    return ret;
}

int term() {
    int value = factor();

    while (isMulop(look)) {
        if (look == '*') {
            match('*');
            value *= factor();
        } else if (look == '/') {
            match('/');
            value /= factor();
        }
    }

    return value;
}

int expression() {
    int value(0);

    if (!isAddop(look))
        value = term();

    while (isAddop(look)) {
        if (look == '+') {
            match('+');
            value += term();
        } else if (look == '-') {
            match('-');
            value -= term();
        }
    }

    return value;
}

void assignment() {
    std::string name = getName();
    match('=');
    if (table.count(name) == 1)
        table[name] = expression();
    else
        table.insert(std::pair<std::string, int>(name, expression()));

    std::cout << name << " = " << table[name] << std::endl;
}

void init() {
    getChar();
    skipWhite();
}

int main(int argc, char *argv[]) {
    init();

    do {
        assignment();
        newLine();
    } while ((look != '.') && (look != '\n'));

    return 0;
}

convert between characters and values

// character to ASCII value: use ?
?a     # => 97
?\n    # => 10


// string to integer: use []
'a'[0]        # => 97
'hallo'[1]    # => 97


// integer / number to character: use .chr
97.chr     # => "a"
10.chr     # => "\n"


//more info: "Ruby Cookbook", O'Reilly

Javascript: convert integer to word (e.g. 18 -> "eighteen")

// Convert a positive integer less than 1000 to its word representation.

var units = new Array ("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
var tens = new Array ("Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety");

function num(it) {
	var theword = "";
	var started;
	if (it>999) return "Lots";
	if (it==0) return units[0];
	for (var i = 9; i >= 1; i--){
		if (it>=i*100) {
			theword += units[i];
			started = 1;
			theword += " hundred";
			if (it!=i*100) theword += " and ";
			it -= i*100;
			i=0;
		}
	};
	
	for (var i = 9; i >= 2; i--){
		if (it>=i*10) {
			theword += (started?tens[i-2].toLowerCase():tens[i-2]);
			started = 1;
			if (it!=i*10) theword += "-";
			it -= i*10;
			i=0
		}
	};
	
	for (var i=1; i < 20; i++) {
		if (it==i) {
			theword += (started?units[i].toLowerCase():units[i]);
		}
	};
	return theword;
}

Integer Sqrt

This code calculate the square root of a integer.

unsigned int sqrt(unsigned int n){
    unsigned int a;
    for (a=0;n>=(2*a)+1;n-=(2*a++)+1);
    return a;
}

BigNumber //JavaScript Class


Offers a extremely high precision level to make mathematical operations. For integers there is no limits and for floating point numbers, the class allows setting the maximum precision.

[UPDATED CODE AND HELP CAN BE FOUND HERE]

The class always returns new instances of BigNumber on the operations, so to the set value of a object, use the "set" method.


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/bignumber [v1.0]

BigNumber = function(n, p, r){
    var o = this, i;
    if(n instanceof BigNumber){
        for(i in {precision: 0, roundType: 0, _sign: 0, _dec: 0}) o[i] = n[i];
        o._buffer = n._buffer.slice();
        return;
    }
    o.precision = isNaN(p = Math.abs(p)) ? BigNumber.defaultPrecision : p;
    o.roundType = isNaN(r = Math.abs(r)) ? BigNumber.defaultRoundType : r;
    o._sign = (n += "").charAt(0) == "-";
    o._dec = ((n = n.replace(/[^\d.]/g, "").split(".", 2))[0] = n[0].replace(/^0+/, "") || "0").length;
    for(i = (n = o._buffer = (n.join("") || "0").split("")).length; i; n[--i] = +n[i]);
    o.round();
};
with({$: BigNumber, o: BigNumber.prototype}){
    $.ROUND_HALF_EVEN = ($.ROUND_HALF_DOWN = ($.ROUND_HALF_UP = ($.ROUND_FLOOR = ($.ROUND_CEIL = ($.ROUND_DOWN = ($.ROUND_UP = 0) + 1) + 1) + 1) + 1) + 1) + 1;
    $.defaultPrecision = 40;
    $.defaultRoundType = $.ROUND_HALF_UP;
    o.add = function(n){
        if(this._sign != (n = new BigNumber(n))._sign) return n._sign = !n._sign, this.subtract(n);
        var o = new BigNumber(this), a = o._buffer, b = n._buffer, la = o._dec,
        lb = n._dec, n = Math.max(la, lb), i, r;
        la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length;
        for(r = 0; i; r = (a[--i] = a[i] + b[i] + r) / 10 >>> 0, a[i] %= 10);
        return r && ++n && a.unshift(r), o._dec = n, o.round();
    };
    o.subtract = function(n){
        if(this._sign != (n = new BigNumber(n))._sign) return n._sign = !n._sign, this.add(n);
        var o = new BigNumber(this), x = o.compare(n) + 1, a = x ? o : n, b = x ? n : o, la = a._dec, lb = b._dec, n = la, i, j;
        a = a._buffer, b = b._buffer, la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb, 1) : o._zeroes(a, -lb, 1));
        for(i = (la = a.length) == (lb = b.length) ? a.length : ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb)).length; i;){
            if(a[--i] < b[i]){
                for(j = i; j && !a[--j]; a[j] = 9);
                --a[j], a[i] += 10;
            }
            b[i] = a[i] - b[i];
        }
        return o._sign = !x, o._dec = n, o._buffer = b, o.round();
    };
    o.multiply = function(n){
        var o = new BigNumber(this), r = o.compare(n = new BigNumber(n)) + 1, a = (r ? o : n)._buffer,
        b = (r ? n : o)._buffer, la = a.length, lb = b.length, x = new BigNumber, i, j, s;
        for(i = lb; i; x.set(x.add(new BigNumber(s.join("")))))
            for(s = (new Array(lb - --i)).join("0").split(""), r = 0, j = la; j;
            r += a[--j] * b[i], s.unshift(r % 10), r = r / 10 >>> 0);
        return r && x._buffer.unshift(r), o._dec = (o._buffer = x._buffer).length - la - lb + o._dec + n._dec, o.round();
    };
    o.divide = function(n){
        if((n = new BigNumber(n)) == "0") throw new Error("division by 0");
        var o = new BigNumber(this), a = o._buffer, b = n._buffer, la = a.length - o._dec,
        lb = b.length - n._dec, s = a._sign != b._sign, dec = 0, buffer = [], x = new BigNumber, y, i;
        la != lb && ((lb = la - lb) > 0 ? o._zeroes(b, lb) : o._zeroes(a, -lb));
        o._dec = a.length, n._dec = b.length;
        b = n, a._sign = false, b._sign = false;
        while(o != 0 && (buffer.length - dec) <= o.precision){
            x.set(0);
            for(i = 0; o.compare(y = x.add(b)) + 1 && ++i; x.set(y));
            if(!i){
                do ++i, o._buffer.push(0), ++o._dec;
                while(o.compare(b) < 0);
                !dec && (!buffer.length && buffer.push(0), dec = buffer.length);
                o._zeroes(buffer, --i);
                continue;
            }
            o.set(o.subtract(x)), buffer.push(i);
        }
        return o._buffer = buffer, o._dec = dec ? dec : buffer.length, o.round();
    };
    o.mod = function(n){
        return this.subtract(this.divide(n).intPart().multiply(n));
    };
    o.pow = function(n){
        var o = new BigNumber(this), i;
        if(n == 0) return o.set(1);
        for(i = Math.abs(n); --i; o.set(o.multiply(this)));
        return n < 0 ? o.set((new BigNumber(1)).divide(o)) : o;
    };
    o.set = function(n){
        return this.constructor(n), this;
    };
    o.compare = function(n){
        var a = this, la = this._dec, b = n, lb = n._dec, i, l;
        if(la != lb) return la > lb ? 1 : -1;
        for(la = (a = a._buffer).length, lb = (b = b._buffer).length, i = -1, l = Math.min(la, lb); ++i < l;)
            if(a[i] != b[i]) return a[i] > b[i] ? 1 : -1;
        return la != lb ? la > lb ? 1 : -1 : 0;
    }
    o.negate = function(){
        var n = new BigNumber(this); return n._sign ^= 1, n;
    };
    o.abs = function(){
        var n = new BigNumber(this); return n._sign = 0, n;
    };
    o.intPart = function(){
        return new BigNumber((this._sign ? "-" : "") + (this._buffer.slice(0, this._dec).join("") || "0"));
    };
    o.valueOf = o.toString = function(){
        var o = this;
        return (o._sign ? "-" : "") + (o._buffer.slice(0, o._dec).join("") || "0") + (o._dec != o._buffer.length ? "." + o._buffer.slice(o._dec).join("") : "");
    };
    o._zeroes = function(n, l, t){
        var s = ["push", "unshift"][t || 0];
        for(++l; --l;  n[s](0));
        return n;
    };
    o.round = function(){
        if("_rounding" in this) return this;
        var $ = BigNumber, r = this.roundType, b = this._buffer, d, p, n, x;
        for(this._rounding = true; this._dec > 1 && !b[0]; --this._dec, b.shift());
        for(d = this._dec, p = this.precision + d, n = b[p]; b.length > d && !b[b.length -1]; b.pop());
        x = (this._sign ? "-" : "") + (p - d ? "0." + this._zeroes([], p - d - 1).join("") : "") + 1;
        if(b.length > p){
            n && (r == $.DOWN ? false : r == $.UP ? true : r == $.CEIL ? !this._sign
            : r == $.FLOOR ? this._sign : r == $.HALF_UP ? n >= 5 : r == $.HALF_DOWN ? n > 5
            : r == $.HALF_EVEN ? n >= 5 && b[p - 1] & 1 : false) && this.add(x);
            b.splice(p, b.length - p);
        }
        return delete this._rounding, this;
    };
}


Usage

<script type="text/javascript">

var x = new BigNumber("10"), y = new BigNumber("-2");
alert(x.pow(y));
alert(x.pow(1234));

alert((new BigNumber("99999999999999999999999999999999999")).add("999999999999999999999999999.99999999999999999"));

</script>

Splitting an integer list in TSQL

Revised: 2006-02-23 - fixed various bugs by using new algorithm
Often times I have a list of integers I need to pass to the database to get worked on. Such as checkboxes on a web page or some other list. I needed some TSQL that would take a text string and split it by a separator, in this case a comma. The following is the result of that need.
The way I normally use it is in a stored procedure like the one below with several text type arguments. Sometimes I use a variation designed to split a list of strings separated by a special character sequence. Image two lists, one of the ids and one of the data. You parse the first list to get a table of the ids and you parse the second list to get the data and insert/update as appropriate.

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[uspSplitIntegerList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
   DROP PROCEDURE [dbo].[uspSplitIntegerList]
GO
                                      
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-- uspSplitIntegerList
--
-- Description:
--		splits a comma separated list of integers and returns the integer list
--
-- Arguments:
--		@list_integers					- list of integers
--
-- Notes:
-- 02/22/2006 - WSR : use DATALENGTH instead of LEN throughout because LEN doesn't count trailing blanks
--
-- History:
-- 02/22/2006 - WSR : revised algorithm to account for items crossing 8000 character boundary
--
CREATE PROCEDURE uspSplitIntegerList
	@list_integers			text
AS

SET NOCOUNT ON

DECLARE @InputLen			integer			-- input text length
DECLARE @TextPos			integer			-- current position within input text
DECLARE @Chunk				varchar(8000)	-- chunk within input text
DECLARE @ChunkPos			integer			-- current position within chunk
DECLARE @DelimPos			integer			-- position of delimiter
DECLARE @ChunkLen			integer			-- chunk length
DECLARE @DelimLen			integer			-- delimiter length
DECLARE @Delimiter      varchar(3)		-- delimiter
DECLARE @ItemBegPos		integer			-- item starting position in text
DECLARE @ItemOrder		integer			-- item order in list

-- create table to hold list items
-- actually their positions because we may want to scrub this list eliminating bad entries before substring is applied
CREATE TABLE #list_items ( item_order integer, item_begpos integer, item_endpos integer )

-- process list
IF @list_integers IS NOT NULL
   BEGIN

	-- initialize
   -- notice that this loop assumes a delimiter length of 1
   -- if the delimiter is longer we have to deal with stuff like delimiters straddling the chunk boundaries
   SET @InputLen = DATALENGTH(@list_integers)
   SET @TextPos = 1
	SET @Delimiter = ','
	SET @DelimLen = DATALENGTH(@Delimiter)
   SET @ItemBegPos = 1
   SET @ItemOrder = 1
   SET @ChunkLen = 1

   -- cycle through input processing chunks
   WHILE @TextPos <= @InputLen AND @ChunkLen <> 0
      BEGIN

      -- get current chunk
      SET @Chunk = SUBSTRING(@list_integers, @TextPos, 8000)

      -- setup initial variable values
      SET @ChunkPos = 1
      SET @ChunkLen = DATALENGTH(@Chunk)
      SET @DelimPos = CHARINDEX(@Delimiter, @Chunk, @ChunkPos)

      -- loop over the chunk, until the last delimiter
      WHILE @ChunkPos <= @ChunkLen AND @DelimPos <> 0
         BEGIN

			-- insert position
         INSERT INTO #list_items (item_order, item_begpos, item_endpos)
         VALUES (@ItemOrder, @ItemBegPos, (@TextPos + @DelimPos - 1) - 1)
         
         -- adjust positions
         SET @ItemOrder = @ItemOrder + 1
         SET @ItemBegPos = (@TextPos + @DelimPos - 1) + @DelimLen
         SET @ChunkPos = @DelimPos + @DelimLen
      
         -- find next delimiter      
         SET @DelimPos = CHARINDEX(@Delimiter, @Chunk, @ChunkPos)

         END

      -- adjust positions
      SET @TextPos = @TextPos + @ChunkLen

      END

	-- handle last item
   IF @ItemBegPos <= @InputLen
      BEGIN

      -- insert position
      INSERT INTO #list_items (item_order, item_begpos, item_endpos)
      VALUES (@ItemOrder, @ItemBegPos, @InputLen)

      END

	-- delete the bad items
   DELETE FROM #list_items
   WHERE item_endpos < item_begpos

   -- return list items
	SELECT CAST(SUBSTRING(@list_integers, item_begpos, (item_endpos - item_begpos + 1)) AS integer) AS item_integer, item_order, item_begpos, item_endpos
   FROM #list_items
   WHERE ISNUMERIC(SUBSTRING(@list_integers, item_begpos, (item_endpos - item_begpos + 1))) = 1
   ORDER BY item_order

   END

DROP TABLE #list_items

RETURN

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

Javascript IntegerBoxControl

In input forms on web pages you often have to validate input as an integer or more precisely a positive integer greater than zero. Here is a control implementation of sorts.

// Integer Box Control
// 
// Notes
// To create an integer box control, call the SetupIntegerBoxControl function.
// It should be passed an input element with type of text.
// The onchange event of the input element will invoke the validation function.
// The validation function ensures only positive integer data is entered.
//
// History
// 09/08/2005 - WSR : created based on dateboxcontrol

// hooks functionality up to given textbox
function SetupIntegerBoxControl( ctlIntegerBox )
   {

   // if a valid object was given
   if (ctlIntegerBox)
      {

      // validate current contents
      IntegerBoxControl_Validate( ctlIntegerBox );

      // hook up event handlers
      ctlIntegerBox.onchange = function () { IntegerBoxControl_Validate(this); };
      
      }

   }


// validates the input
function IntegerBoxControl_Validate( ctlIntegerBox )
   {

   // parse the input as an integer
   var intValue = parseInt(ctlIntegerBox.value, 10);

   // if this is not an integer
   if (isNaN(intValue))
      {

      // clear text box
      ctlIntegerBox.value = '';

      }
   // if this is an integer
   else
      {
   
      switch (true)
         {
         case (intValue == 0) :

            // clear text box
            ctlIntegerBox.value = '';

            break