I have a java-script function that carries out a calculation. I would like to use the answer to that calculation in my php code.
document.write(Fixed((PoissonTerm( X, Y )),8,4))
Both values X and Y come from variables within my php code so
<?php
$valueofx;
$valueofy;
?>
In the ideal world I would like to to look like this
<?php
$thejavascriptvalue = document.write(Fixed((PoissonTerm( $valueofx, $valueofy )),8,4))
?>
I know this can't be done and i have 5 different values i need to pull and use. Is there anyway I can work around it? I dont mind refreshing the page or grabbing it from another page as long as i can have 5 values to use in my php code.
I would need to run the javascript 10 times before redirecting like
document.write(Fixed((PoissonTerm(0.1, 0 )),8,4))
document.write(Fixed((PoissonTerm( 8, 2 )),8,4))
document.write(Fixed((PoissonTerm( 6, 3 )),8,4))
below if the javascript
function Fixed( s, wid, dec ) {
// many combinations of possibilities
// maybe prepare for upcoming truncate
var z = 1
if (dec > 0) {
z /= Math.pow( 10, dec );
if (s < -z) s -= 0.5 * z;
else
if (s > z) s += 0.5 * z;
else
s = 0;
}
// assure a string
s = "" + s;
// chop neg, if any
var neg = 0;
if (s.charAt(0) == "-") {
neg = 2;
s = s.substring( 1, s.length );
}
// chop exponent, if any
var exp = "";
var e = s.lastIndexOf( "E" );
if (e < 0) e = s.lastIndexOf( "e" );
if (e > -1) {
exp = s.substring( e, s.length );
s = s.substring( 0, e );
}
// if dec > 0 assure "."; dp == index of "."
var dp = s.indexOf( ".", 0 );
if (dp == -1) {
dp = s.length;
if (dec > 0) {
s += ".";
dp = s.length - 1;
}
}
// assure leading digit
if (dp == 0) {
s = '0' + s;
dp = 1;
}
// not enough dec pl? add 0's
while ((dec > 0) && ((s.length - dp - 1) < dec))
s += "0";
// too many dec pl? take a substring
var places = s.length - dp - 1;
if (places > dec)
if (dec == 0)
s = s.substring( 0, dp );
else
s = s.substring( 0, dp + dec + 1 );
// recover exponent, if any
s += exp;
// recover neg, if any
if (neg > 0)
s = "-" + s;
// if not enough width, add spaces IN FRONT
// too many places? tough!
while (s.length < wid)
s = " " + s;
return s
}
function Prb( x ) {
if (x < 0) x = 0;
else
if (x > 1) x = 1;
return x;
}
function PosV( x ) {
if (x < 0) x = -x;
return x;
}
// FACTORIALS
function Fact( x ) {
// x factorial
var t=1;
while (x > 1)
t *= x--;
return t;
}
function LnFact( x ) {
// ln(x!) by Stirling's formula
// see Knuth I: 111
if (x <= 1) x = 1;
if (x < 12)
return Math.log( Fact(Math.round(x)) );
else {
var invx = 1 / x;
var invx2 = invx * invx;
var invx3 = invx2 * invx;
var invx5 = invx3 * invx2;
var invx7 = invx5 * invx2;
var sum = ((x + 0.5) * Math.log(x)) - x;
sum += Math.log(2*Math.PI) / 2;
sum += (invx / 12) - (invx3 / 360);
sum += (invx5 / 1260) - (invx7 / 1680);
return sum;
}
}
// POISSON
function PoissonPD( u, k ) {
// Peizer & Pratt 1968, JASA 63: 1416-1456
var s = k + (1/2);
var d1 = k + (2/3) - u;
var d2 = d1 + 0.02/(k+1);
var z = (1 + g(s/u)) / u;
z = d2 * Math.sqrt(z);
z = NormalP( z );
return z;
}
function PoissonTerm( u, k ) {
// by logs
return Math.exp( (k * Math.log(u)) - u - LnFact(k) );
}
function PoissonP( u, k ) {
// term-by-term summation
if (k >= 20) return PoissonPD( u, k );
else {
var sum = 0.0, j = 0;
while (j <= k)
sum += PoissonTerm( u, j++ );
if (sum > 1) sum = 1;
return sum;
}
}
function DoPoi( aform ) {
var u = PosV(parseFloat(aform.u.value));
aform.u.value = Fixed(u,10,4);
var k = PosV(parseInt(aform.k.value));
aform.k.value = Fixed(k,8,0);
aform.tnk.value = Fixed(PoissonTerm( u, k ),8,4);
var t = PoissonP( u, k );
aform.puk.value = Fixed(t,8,4);
aform.quk.value = Fixed(1-t,8,4);
}
This is very generic. You're going to have to modify this to your needs. But this will give you the basic idea:
<form name="thisform" action="phpPage.php" method="POST">
X: <input type="text" name="val_x" id="val_x" value="40" /><br />
Y: <input type="text" name="val_y" id="val_y" value="60" /><br />
<input type="button" onclick="sendForm();" value="send form"/>
</form>
JavaScript:
function sendForm(){
//Choose one of these methods:
//This will generate a string that you can use as a location.
//use $_GET in PHP to retrieve the values
var valofX = document.getElementById("val_x").value;
var valofy = document.getElementById("val_y").value;
generateURL = 'phpPage.php?val_x=' + valofX;
generateURL += '&val_y=' + valofy;
document.location = generateURL;
//This will submit the form.
//use $_POST in PHP to retrieve the values
document.getElementById("thisform").submit();
}
Once the form is submitted, or the location is sent, you'll need to grab the values in PHP:
$val_x = $_POST['val_x'];
$val_y = $_POST['val_y'];
//OR
$val_x = $_GET['val_x'];
$val_y = $_GET['val_y'];
You would use $_GET or $_POST depending on how the values are sent.
Related
I'm trying to implement a function that takes a string as input and returns the longest palindrome subsequence in the string.
I've tried using dynamic programming and have come up with the following code:
function longestPalindromicSubsequence(str) {
let n = str.length;
let dp = Array(n);
for (let i = 0; i < n; i++) {
dp[i] = Array(n);
dp[i][i] = 1;
}
for (let cl = 2; cl <= n; cl++) {
for (let i = 0; i < n - cl + 1; i++) {
let j = i + cl - 1;
if (str[i] === str[j] && cl === 2)
dp[i][j] = 2;
else if (str[i] === str[j])
dp[i][j] = dp[i + 1][j - 1] + 2;
else
dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]);
}
}
return dp[0][n - 1];
}
However, this code doesn't seem to be giving me efficient and better results for all test cases. The Time and Space Complexity is also be reduced. I've been struggling with this for days and can't seem to find the issue. Can someone help me figure out what's going wrong and how to fix it?
Oh, I think Dynamic Programming does not work with this sort of problem, because it does not break down recursively, i.e. to find the longest palindrome in a string, you don't need all second-largest palindromes. You can just check at each position and see if it is the center of a palindrome longer than any before. This can be solved with a greedy algorithm:
const pals = "asd1234321fghjkl1234567887654321qwertzu1234321"
function palindromeAtPos(str, pos, checkEven = false){
let ix = 0
const off = checkEven ? 2 : 1
while(pos-ix-1 >= 0 && pos+ix+1+off < str.length && str[pos-ix-1] === str[pos+ix+off]){
ix++
}
return ix === 0 ? str[pos] : str.substring(pos-ix, pos+ix+off)
}
function longestPalindrome(str){
let longest = ''
for(let i = 1; i < str.length; i++){
const odd = palindromeAtPos(str, i)
longest = odd.length > longest.length ? odd : longest
const even = palindromeAtPos(str, i, true)
longest = even.length > longest.length ? even : longest
}
return longest
}
console.log(longestPalindrome(pals))
On paper (and for a string like aaaaaaaaaa), this has quadratic complexity, but for most strings, it will be almost linear.
/*
* s => string
* return [] of strings witch have the max lenth
*/
function maxLenPalindromes(s) {
const l = s.length
let c, z, zz, a, b, a1, b1, maxl = 0, result = []
if (l < 2) return result
for (c = 0; c < l - 1; c++) {
a = -1
if (maxl>(l-c)*2+1) return result
if (c > 0 && s[c - 1] == s[c + 1]) {
zz = Math.min(c, l - c - 1)
for (z = 1; z <= zz; z++) {
if (s[c - z] != s[c + z]) {
a = c - z + 1; b = c + z
break
}
else if (z == zz) {
a = c - z; b = c + z + 1
break
}
}
if (a >= 0) {
if (b-a > maxl) {
result = [s.slice(a, b)]
maxl = b-a
}
else if (b-a == maxl) {
result.push(s.slice(a, b))
}
}
}
a=-1
if (s[c] == s[c + 1]) {
if (c == 0 || c == l - 2) {
a = c; b = c + 2
}
else {
zz = Math.min(c, l - c - 2)
for (z = 1; z <= zz; z++) {
if (s[c - z] != s[c + z + 1]) {
a = c - z + 1; b = c + z + 1
break
}
else if (z == zz) {
a = c - z; b = c + z + 2
break
}
}
}
if (a >= 0) {
if (b-a > maxl) {
result = [s.slice(a, b)]
maxl = b-a
}
else if (b-a == maxl) {
result.push(s.slice(a, b))
}
}
}
}
return result
}
const s1="112233111222333"
const s2="11_22_33_111_222_333"
const s3="12345_54321xqazws_swzaq_qwertytrewq"
const s4="sdfgsdfg1qqqqqAAAAA_123456789o o987654321_AAAAAqqqqq;lakdjvbafgfhfhfghfh"
console.log(maxLenPalindromes(s1))
console.log(maxLenPalindromes(s2))
console.log(maxLenPalindromes(s3))
console.log(maxLenPalindromes(s4))
can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/
I have Float32Array textures which can be displayed through WebGL correctly. However, when I tried to convert them into Uint16Array, the problem occurs.
Here is my conversion part.
var _floatToHalfFloat = function(input, offset) {
var largestHalf = Math.pow(2, 30-15) * (1 + 1023/1024);
var m = new ArrayBuffer(4);
var n = new Float32Array(m);
var o = new Uint32Array(m);
var f = 0.0;
for (var i = input.length - 1 - offset; i >= 0;i--) {
n[0] = input[i];
f = o[0];
// fast conversion of half
// ref : ftp://www.fox-toolkit.org/pub/fasthalffloatconversion.pdf
if (isNaN(input[i])) {
input[i] = 0x7fff;
} else if(n === Infinity || n > largestHalf) {
input[i] = 0x7c00;
} else if(n === -Infinity || n < -largestHalf) {
input[i] = 0xfc00;
} else if(n === 0) {
input[i] = 0;
} else {
input[i] = ((f>>16)&0x8000)|((((f&0x7f800000)-0x38000000)>>13)&0x7c00)|((f>>13)&0x03ff);
}
}
return new Uint16Array(input);
};
We can see saturated colors (full red, green and/or blue) in the converted image when reaching black color in the original image. I think the function doesn't work very well near 0.
I have done a quick implementation of wikipedia explanation of norm of the float 16 bits.
<html>
<head>
<script>
var _floatToHalfFloat = #### YOUR FUNCTION HERE CUT ####
var _halfFloatToFloat = function(hf) {
var m = new ArrayBuffer(2);
var n = new Uint16Array(m);
n[0] = hf;
var sign = n[0] & 0x8000;
var exp = (n[0] >> 10) & 0x1F;
var mant = n[0]& 0x03FF;
document.getElementById('sign').innerHTML += sign+" - ";
document.getElementById('exp').innerHTML += exp+" - ";
document.getElementById('mant').innerHTML += mant+" - ";
if (exp == 0x1F) {
return 1.0 * Math.pow(-1, sign) * Infinity;
} else if (exp == 0) {
return Math.pow(-1, sign) *
Math.pow(2, -14) *
(mant / Math.pow(2, 10));
} else {
return Math.pow(-1, sign) *
Math.pow(2, exp-15) *
(1+(mant / Math.pow(2, 10)));
}
};
document.addEventListener("DOMContentLoaded", function(event) {
var input = new Float32Array(8);
input[0] = 2.5;
input[1] = 0.25;
input[2] = 0.025;
input[3] = 0.025;
input[4] = 0.0025;
input[5] = 0.00025;
input[6] = 0.000025;
input[7] = 0.0;
var i, s = "Value before = ";
for (i = 0; i < input.length; i++)
s += input[i] + " - ";
document.getElementById('res1').innerHTML = s;
var output = _floatToHalfFloat(input, 0);
s = "Value after = ";
for (i = 0; i < output.length; i++)
s += _halfFloatToFloat(output[i]) + " - ";
document.getElementById('res2').innerHTML = s;
});
</script>
</head>
<body>
<span id="res1">result</span></br>
<span id="res2">result</span></br>
</br></br></br>
<span id="sign">signs =</span></br>
<span id="exp">exponents =</span></br>
<span id="mant">mantissas =</span></br>
</body>
</html>
The test results are shown below :
Value before = 2.5 - 0.25 - 0.02500000037252903 - 0.02500000037252903 - 0.0024999999441206455 - 0.0002500000118743628 - 0.00002499999936844688 - 0 -
Value after = 2.5 - 0.25 - 0.024993896484375 - 0.024993896484375 - 0.002498626708984375 - 0.0002498626708984375 - Infinity - 2 -
signs =0 - 0 - 0 - 0 - 0 - 0 - 0 - 0 -
exponents =16 - 13 - 9 - 9 - 6 - 3 - 31 - 16 -
mantissas =256 - 0 - 614 - 614 - 286 - 24 - 653 - 0 -
This shows that the 2 last information are not coherent. 0.000025 is transformed into Infinity (rather than 0?) and 0 itself is transformed to 2. This doesn't appear to be correct. When you want to code a zero "wikipedia says" your mantissa AND your exponent should be zero. In the code you provided the mantissa is zero but the exponent is 16 which leads to 2 (2^(16-15)).
After tweaking a bit your function it appears that all cases are treated as normal one. This is due to a bug in your if statements. So instead of having :
} else if(n === 0) {
input[i] = 0;
}
You want probably do something like that :
} else if(n[0] === 0) {
input[i] = 0;
}
And the same for all uses of n variable. But you still have the underflow problem.So may be you can find acceptable to do :
} else if(Math.abs(n[0]) < 0.0001) {
input[i] = 0;
}
JavaScript:
var UI; // Number entered by user
var TV; // Number value to be used in calculations
var HITS; // Counter
var DD; // Division denominator
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt("UI", [10]);
HITS = 0;
DD = TV;
while (DD > 0) {
if (TV % DD == 0) {
HITS++
}
HITS--
}
window.document.write(+UI + " is ");
if (HITS > 2) {
window.document.write(" not");
}
window.document.write(" a prime number.");
Can anyone tell me what I'm doing wrong? Everything runs except when it isn't a prime number it the "not" string won't come up. Any help is greatly appreciated.
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt(UI,10);
HITS = 0;
DD = TV;
while(DD>0) {
if (TV%DD===0) {
HITS++; }
DD--;
}
I changed this much of and it works now.
//FOR user FOON
PrimeNumber=function(){
var d, l, primelist;
_isPrimeNumber = function(n){
var result = true;
_setVariables(n);
while( d < l ){
if(n % d == 0){
result = false;
break;
}
do{
d = d + 1;
}while(!_check(d));
primelist.push(d);
l = n/d;
}
return result;
};
_getAllPrimeTill = function(n){
_setVariables(n);
while( d < n ){
d = d + 1;
if(_check(d)){
primelist.push(d);
}
}
return primelist;
};
_setVariables = function(n){
d=2;
l=n/2;
primelist = new Array();
primelist.push(d);
};
_check = function(n){
var result = true;
for(var i = 0; i < primelist.length; i++){
if(n % primelist[i] == 0 ){
result = false;
break;
}
}
return result;
};
return {
isPrimeNumber :_isPrimeNumber,
getAllPrimeTill : _getAllPrimeTill
};
}();
You have:
DD = TV;
// The value of DD is tested, but not modified in the loop
while(DD>0) {
// This part is irrelevant to the test
if (TV%DD == 0) {
HITS++
}
HITS--
}
DD is not modified in the loop, so if the condition is true or false, it will always be true or false. So if DD is any value greater than zero, the condition is always true.
import java.util.ArrayList;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*if you want to find all prime numbers between 2 and n, change loop "while( d < l ){" to "while( d < n ){" and you will get al prime numbers in primelist.
*/
/**
*
* #author hp
*/
public class PrimeNumber {
public static void main(String[] args) {
String result = " IS A PRIME NUMBER";
int n = 127;
int d = 2;
int l = n / 2;
List <Integer> primelist = new ArrayList<Integer>();
while( d < l ){
if(n % d == 0){
//System.out.println();
//System.out.println(n + " can be divided by " + d);
//System.out.println(d + " * " + (n / d) + " = " + n);
result = " IS NOT A PRIME NUMBER";
break;
}
do{
d = d + 1;
}while(!isPrimeNumber(d,primelist));
//System.out.print(d + ", ");
primelist.add(new Integer(d));
l = n/d;
}
//System.out.println();
System.out.println(n + result);
}
private static boolean isPrimeNumber(int n, List <Integer> primelist){
boolean result = true;
for(Integer i : primelist){
if(n % i.intValue() == 0 ){
result = false;
}
}
return result;
}
}
I need to a function to convert an integer to the equivalent alpha ordered list index. For example:
1 = a
2 = b
.
.
.
26 = z
27 = aa
28 = ab
.
.
etc.
Currently I have the following which almost works but there's a small logic error somewhere that makes it not quite get it right (it goes ax, ay, bz, ba, bb, bc...):
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = '',
place,
num,
i;
for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {
place = Math.pow(alphaMax, i);
num = Math.floor( ( int / place ) % alphaMax);
asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
char = String.fromCharCode(asciiCode);
alpha = char + alpha;
}
return alpha;
}
for (i = 1; i < 300; i++) {
console.log( i + ': ' + intToAlpha(i) );
}
This function is used in NVu/Kompozer/SeaMonkey Composer, with a small tweak to generate lower case directly:
function ConvertArabicToLetters(num)
{
var letters = "";
while (num > 0) {
num--;
letters = String.fromCharCode(97 + (num % 26)) + letters;
num = Math.floor(num / 26);
}
return letters;
}
You need to make sure that you use the correct value when taking the mod.
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = "";
while(int > 0) {
char = String.fromCharCode(asciiStart + ((int-1) % alphaMax));
alpha = char + alpha;
int = Math.floor((int-1)/26);
}
return alpha;
}
A while back I needed the same thing in SQL, so I asked (and answered) the question Multi-base conversion - using all combinations for URL shortener.
The thing that is making it complicated is that it's not a straight base conversion, as there is no character representing the zero digit.
I converted the SQL function into Javascript:
function tinyEncode(id) {
var code, value, adder;
var chars = 'abcdefghijklmnopqrstuvwxyz';
if (id <= chars.length) {
code = chars.substr(id - 1, 1);
} else {
id--;
value = chars.length;
adder = 0;
while (id >= value * (chars.length + 1) + adder) {
adder += value;
value *= chars.length;
}
code = chars.substr(Math.floor((id - adder) / value) - 1, 1);
id = (id - adder) % value;
while (value > 1) {
value = Math.floor(value / chars.length);
code += chars.substr(Math.floor(id / value), 1);
id = id % value;
}
}
return code;
}
Demo: http://jsfiddle.net/Guffa/mstBe/