Archive for the ‘Java’ Category

Square root   Leave a comment


Integer square root should work only if the given number has an integer square root

import java.math.BigInteger;

public class SquareRoot {
	public static BigInteger squareRoot(BigInteger num) {
		BigInteger high = num;
		BigInteger low = BigInteger.ONE;
		BigInteger two = BigInteger.valueOf(2);
		BigInteger res;
		BigInteger mid;
		do {
			mid = high.add(low).divide(two);
			if ((res = mid.multiply(mid)).compareTo(num) < 0)
				low = mid;
			else
				high = mid;
		} while (res.compareTo(num) != 0);
		return mid;
	}

	public static double squareRoot(double d) {
		double high = Math.ceil(d);
		double low = 0;
		double mid = 0;
		do {
			mid = (high + low) / 2;
			if (mid * mid > d)
				high = mid;
			else
				low = mid;

		} while (Math.abs(mid * mid - d) > 1e-15);
		return mid;
	}
}

Posted August 21, 2011 by epicrado in Java

Audioclip grabber   Leave a comment


call Sound.getClip(String path); with the path of the sound file

import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
public class Sound
{
	public static String getUrl(File f)
	{
		String url = f.getAbsolutePath();
		String res = "";
		for (int i = 0; i < url.length(); i++)
		{
			if (url.charAt(i) == '\\')
			{
				res += '/';
			} else
				res += url.charAt(i);
		}
		url = "file:///" + res;
		return url;
	}

	public static AudioClip getClip(String path) throws MalformedURLException
	{
		return java.applet.Applet.newAudioClip(new java.net.URL(
				getUrl(new File(path))));
	}

}

Posted July 17, 2011 by epicrado in Java