Archive for August, 2013

Find the nth Prime Number; Exceptions, Threads JAVA example

Tuesday, August 20th, 2013

public class PrimeThreads {
public static void main( String[] arguments ) {
PrimeThreads pt = new PrimeThreads( arguments );
}

public PrimeThreads( String[] arguments ) {
PrimeFinder[] finder = new PrimeFinder[arguments.length];
for( int i = 0; i < arguments.length; i++ ) {
try {
long count = Long.parseLong( arguments[i] );
finder[i] = new PrimeFinder(count);
System.out.println( “Looking for prime “ + count );
} catch ( NumberFormatException nfe ) {
System.out.println( “Error: “ + nfe.getMessage() );
}
}
boolean complete = false;
while( !complete ) {
complete = true;
for( int j=0;  j < finder.length; j++ ) {
if( finder[j]==null ) continue;
if( !finder[j].finished ) {
complete = false;
} else {
displayResult( finder[j] );
finder[j] = null;
}
}
try {
Thread.sleep( 1000 );
} catch ( InterruptedException ie ) {
// do nothing
}
}
}

private void displayResult( PrimeFinder finder ) {
System.out.println( “Prime “ + finder.target + ” is “ + finder.prime );
}
}

 

public class PrimeFinder implements Runnable {
public long target;
public long prime;
public boolean finished = false;
private Thread runner;

PrimeFinder( long inTarget ) {
target = inTarget;
if( runner == null ) {
runner = new Thread( this );
runner.start();
}
}

public void run() {
long numPrimes = 0;
long candidate = 2;
while( numPrimes < target ) {
if( isPrime(candidate) ) {
numPrimes++;
prime = candidate;
}
candidate++;
}
finished = true;
}

boolean isPrime( long checkNumber ) {
double root = Math.sqrt( checkNumber );
for( int i = 2; i <= root; i++ ) {
if( checkNumber % i == 0 )
return false;
}
return true;
}
}

run with command-line arguments, example: 1 10 100 1000

Example from: Sams Teach Yourself Java in 21 Days; 6th Edition Covers Java 7 and Android; Rogers Cadenhead, copyright 2013; chapter 7

jQuery Regex Selector examples ^=Starts with, $=Ends with, is of Class [0-9] threw in an encodeURIComponent for kicks

Monday, August 12th, 2013

Obviously, if your jQuery version is up to date, you should use .on
but I was fixing one of our sites that is stuck in 1.5,
so here are some examples using .delegate and .bind
The regex blocks are the same either way:

$.fn.popSubject = function() {
var menuA = $(“#askMenuA option:selected”).text();
var menuB = $(“#askMenuB option:selected”).text();
$(‘input[id$=”hiddensubject”]‘).val(menuA + ” – ” + menuB);
}

$(‘[id^=rn_FormSubmit_][id$=_Button]‘).bind(‘click’, ‘button’, function(event){
//Call Omniture when SA initial form submitted
s_exp_trackClick( this, ‘a’,”support.faq.sa.first.” + encodeURIComponent($(“#askMenuA option:selected”).text()) );
});

$(“body”).delegate(‘[id^=rnDialog1_Button][id$=[0-9]]‘, ‘click’, function(event){
//Call Omniture when SA dialog box submitted
s_exp_trackClick( this, ‘a’,’support.faq.sa.pop.’+ encodeURIComponent($(“#askMenuB option:selected”).text()) );
});

Rotate an 8×8 image or checkerboard 90 degrees

Wednesday, August 7th, 2013

foreach point (x,y){ //new point is
x = y;
y = 7 – x; }

JAVA LinkedList Class simple example

Wednesday, August 7th, 2013

import java.util.*;

public class LinkedListDemo {

public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add(“F”);
ll.add(“B”);
ll.add(“D”);
ll.add(“E”);
ll.add(“C”);
ll.addLast(“Z”);
ll.addFirst(“A”);
ll.add(1, “A2”);
System.out.println(“Original contents of ll: ” + ll);

// remove elements from the linked list
ll.remove(“F”);
ll.remove(2);
System.out.println(“Contents of ll after deletion: ”
+ ll);

// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println(“ll after deleting first and last: ”
+ ll);

// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + ” Changed”);
System.out.println(“ll after change: ” + ll);
}
}

Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]

credit: http://www.tutorialspoint.com/java/java_linkedlist_class.htm

JAVA count Fibonacci

Wednesday, August 7th, 2013
class Fib {
	public static void main( String[] args ) {
		int f = 0;
		int g = 1;

		for( int i = 1; i <= 10; i++) {
			System.out.print(f + " ");
			f = f + g;
			g = f - g;
		}

		System.out.println();
	}
}

JAVA simple Deque Interface example

Wednesday, August 7th, 2013

import java.util.*;

class Deque {
public static void main(String[] arguments){

ArrayDeque<String> ourDeque = new ArrayDeque<String>();

// fill our deque interface
String[] alph = { “a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”,”i”,”j”,”k”,”l”,”m”,”n”,”o”,”p”,”q”,”r”,”s”,”t”,”u”,”v”,”w”,”x”,”y”,”z” };
for( int i = 0; i < alph.length; i++){
ourDeque.addFirst( alph[i] );
}

// foreach
for (String str : ourDeque) {
System.out.print(str);
}

System.out.println(“\n”);

// iterator
//ArrayDeque<String> ourDeque = new ArrayDeque<String>();
for (Iterator<String> iter = ourDeque.iterator(); iter.hasNext(); ) {
System.out.print(iter.next());
}

System.out.println(“\n”);

// Let’s do it forward though
int holdSize = ourDeque.size();
for ( int j = 0; j < holdSize; j++){
String getOne = ourDeque.removeLast();
System.out.print(getOne);
}

System.out.println(“\n”);
}
}

JAVA simple HashMap (+Generics) syntax example

Wednesday, August 7th, 2013

import java.util.*;

HashMap<String, Float> quality = new HashMap<>();
float price1 = 3.00F;
quality.put(“mint”, price1);
quality.get(“very fine”);
quality.clear();
quality.containsValue(price1);
quality.containsKey(“good”);

JAVA simple ArrayList example

Wednesday, August 7th, 2013

import java.util.*;

public class CodeKeeper {

ArrayList<String> list;
String[] codes = { “alpha”, “lambda”, “gamma”, “delta”, “zeta” };

public CodeKeeper(String[] userCodes) {

list = new ArrayList<>();
// load codes
for (int i = 0; i < codes.length; i++) {

if (!list.contains(code)) {

list.add(codes[i]);

}

}
// display all codes with new for loop
for (String code : list) {

System.out.println(code);

}

}

public static void main(String[] arguments) {

CodeKeeper keeper = new CodeKeeper(arguments);

}

}

reverse a String

Wednesday, August 7th, 2013

JAVA

class Reverso{
	public static void main(String[] args) {
		for (String toReverse: args) {
			int countOf = toReverse.length();
			for(int $i = toReverse.length() - 1; $i >= 0; $i--){
				System.out.print(toReverse.charAt($i));
			}
		}
	}
}

JavaScript

var reverse = function(str) {
    var arr = [];

    for (var i = 0, len = str.length; i <= len; i++) {
        arr.push(str.charAt(len - i))
    }

    return arr.join('');
}

document.writeln(reverse('lorem ipsum dolor'));

JAVA simple Array refresher & some String methods

Wednesday, August 7th, 2013

int[] holiday = { 1, 15, 50, 148, 185, 246, 281, 316, 326, 359 };
for (int i = 0; i < holiday.length; i++ ) {
someFunc(holiday[i]);
}

 

str.length()
str.charAt(6)
str.substring(26, 32)
str.indexOf(‘a’)
str.toUpperCase())

JAVA simple BitSet refresher

Tuesday, August 6th, 2013

import java.util.*;

BitSet connex = new BitSet();
connex.set(3);
connex.get(3);
connex.clear(3);
int numBits = connex.size();

PHP SPL FixedArray example

Monday, August 5th, 2013

// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = “foo”;

// Increase the size of the array
$array->setSize(10);

$array[9] = “asdf”;

// Shrink the array to a size of 2
$array->setSize(2);

PHP DoublyLinkedList example

Monday, August 5th, 2013

/*

* Examples of DoublyLinkedList
*/

$obj = new SplDoublyLinkedList();

// Check wither linked list is empty
if ($obj->isEmpty())
{
echo “Adding nodes to Linked List<br>”;
$obj->push(2);
$obj->push(3);

echo “Adding the node at beginning of doubly linked list <br>”;
$obj->unshift(10);
}

echo “<br>Our Linked List:”;
print_r($obj);

echo “<br>Pick the node from beginning of doubly linked list”;
echo $obj->bottom();

/**
Our Linked List:SplDoublyLinkedList Object ( [flags:SplDoublyLinkedList:private] => 0 [dllist:SplDoublyLinkedList:private] => Array ( [0] => 10 [1] => 2 [2] => 3 ) )
Pick the node from beginning of doubly linked list10
*/

Factorial of n recursive and iterative

Monday, August 5th, 2013

Recursive solution:

public int Factorial ( int n ) {
	if ( n == 0 ) {
		return 1;
	} else {
		return n * Factorial(n-1);
	}
}

Iterative Solution:

public int factorial ( int input ) {
	int x, fact = 1;
	for ( x = input; x > 1; x--) {
		fact *= x;
	}
	return fact;
}

Detect a Palindrome

Monday, August 5th, 2013
function isPalindrome(input)
{
	var len = input.length;

	var isPalindrome = true;

	// iterate through half the length of the string
	for(j = 0; j<len/2; j++)
	{
		if(input[j] != input[len - 1 -j])
		{
			isPalindrome = false;	
			break;
		}
	}

	return isPalindrome;
}
document.writeln(isPalindrome("hello"));
document.writeln(isPalindrome("Anna"));
document.writeln(isPalindrome("deified"));

JAVA simple StringTokenizer example

Sunday, August 4th, 2013

import java.util.StringTokenizer;

class TokenTester {

public static void main(String[] arguments) {

StringTokenizer st1, st2;

String quote1 = “GOOG 604.43 -0.42”;
st1 = new StringTokenizer(quote1);
System.out.println(“Token 1: ” + st1.nextToken());
System.out.println(“Token 2: ” + st1.nextToken());
System.out.println(“Token 3: ” + st1.nextToken());

String quote2 = “RHT@60.39@0.78”;
st2 = new StringTokenizer(quote2, “@”);
System.out.println(“\nToken 1: ” + st2.nextToken());
System.out.println(“Token 2: ” + st2.nextToken());
System.out.println(“Token 3: ” + st2.nextToken());

}

}

Simple JAVA app convert Fahrenheit to Celsius / Celsius to Fahrenheit

Sunday, August 4th, 2013

Really just so that I can quickly search for this formula… 🙂

 

public class Weather {

public static void main(String[] arguments) {

float fah = 86;

System.out.println(fah + ” degrees Fahrenheit is …”);
// To convert Fahrenheit into Celcius
// begin by subtracting 32
fah = fah – 32;
 // Divide the answer by 9
fah = fah / 9;
// Multiply that answer by 5
fah = fah * 5;
System.out.println(fah + ” degrees Celsius\n”);

float cel = 33;
System.out.println(cel + ” degrees Celsius is …”);
// To convert Celsius into Fahrenheit
// begin by multiplying by 9
cel = cel * 9;
// Divide the answer by 5
cel = cel / 5;
// Add 32 to the answer
cel = cel + 32;
System.out.println(cel + ” degrees Fahrenheit”);

}

}