i am so newbie in programming. i had problem how to count the area and around of triangle.
i had code code some, but the output results are always wrong calculate.
function fungsiLuasSegitiga(a, b) {
var luas = (1 / 2) * a * b;
return luas;
}
function fungsiKllSegitiga(a, b) {
var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
var kll = a + b + c;
return kll;
}
var x = prompt("masukkan nilai alas segitiga!");
var y = prompt("masukkan nilai tinggi segitiga!");
var d = fungsiLuasSegitiga(x, y);
var e = fungsiKllSegitiga(x, y);
alert("luas segitiga adalah " + d);
alert("keliling segitiga adalah " + e);
when i put number 3 and 4, the function fungsiLuasSegitiga count it be 345, but the result must be 12 (3+4+5).
prompt returns a string and not a number. So, kll calculation ends up being "3" + "4" + 5. This concatenates the string instead of summing the numbers. You need to parse it to a number before assigning it to x and y either by using unary plus operator or parseInt
function fungsiLuasSegitiga(a, b) {
var luas = (1 / 2) * a * b;
return luas;
}
function fungsiKllSegitiga(a, b) {
var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
var kll = a + b + c;
return kll;
}
var x = +prompt("masukkan nilai alas segitiga!");
var y = +prompt("masukkan nilai tinggi segitiga!");
var d = fungsiLuasSegitiga(x, y);
var e = fungsiKllSegitiga(x, y);
alert("luas segitiga adalah " + d);
alert("keliling segitiga adalah " + e);
Related
So I'm trying to understand how to properly use apply with objects and arguments, instead of using if else statements.
My current code:
var log = function(call, name) {
return function(a, b, c) {
if (c === undefined) {
console.log(name + "(" + a + b + ")" + "=" + call(a, b));
} else {
console.log(name + "(" + a + b + c + ")" + "=" + call(a, b, c));
}
}
};
//Includes two call functions
EDIT: More readable
If you want to use apply, then you would just call apply with the first parameter as null and the second parameter as a list of the arguments:
console.log(name + "(" + a + "," + b + "," + c + ")" + "=>" + callback.apply(null, [a, b, c]));
var wrapLog = function(callback, name) {
return function(a, b, c) {
console.log(name + "(" + a + "," + b + "," + c + ")" + "=>" + callback.apply(null, [a, b, c]));
}
};
var area = function(x, y) { //don't change this function
return x * y;
};
var logArea = wrapLog(area, "area");
logArea(5, 3); // area(5, 3) => 15
logArea(3, 2); // area(3, 2) => 6
var volume = function(x, y, z) { //don't change this function
return x * y * z;
};
var logVolume = wrapLog(volume, "volume");
logVolume(5, 3, 2); // volume(5, 3, 2) => 30
logVolume(3, 2, 4); // volume(3, 2, 4) => 24
But you might consider converting the arguments in the function returned by wrapLog to an array in the parameters themselves for the least syntax noise:
return function(...args) {
console.log(`${name}(${args}) => ${callback.apply(null, args)}`);
}
var wrapLog = function(callback, name) {
return function(...args) {
console.log(`${name}(${args}) => ${callback.apply(null, args)}`);
}
};
var area = function(x, y) { //don't change this function
return x * y;
};
var logArea = wrapLog(area, "area");
logArea(5, 3); // area(5, 3) => 15
logArea(3, 2); // area(3, 2) => 6
var volume = function(x, y, z) { //don't change this function
return x * y * z;
};
var logVolume = wrapLog(volume, "volume");
logVolume(5, 3, 2); // volume(5, 3, 2) => 30
logVolume(3, 2, 4); // volume(3, 2, 4) => 24
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
EDIT: Apolgies for the duplicate question but searching for " '()' Javascript " yielded no result for me.
Here goes ... I am doing some pixel manipulation on an image in PHP and porting some Javascript logic into PHP to achieve an effect that I have seen on a html5 canvas. The Javascript uses some curves calculation to achieve a "vintage effect". The pixel calculations get called within a loop:
Javascript:
for (var i = (width * height); i >= 0; --i) {
idx = i << 2;
// curves
if (!!_effect.curves) {
_imageData[idx ] = _effect.curves.r[ _imageData[idx ] ]; // r
_imageData[idx + 1] = _effect.curves.g[ _imageData[idx + 1] ]; // g
_imageData[idx + 2] = _effect.curves.b[ _imageData[idx + 2] ]; // b
}
}
The effect.curves object looks like:
var _effect = {
curves: (function() {
var rgb = function (x) {
return -12 * Math.sin( x * 2 * Math.PI / 255 ) + x;
},
r = function(x) {
return -0.2 * Math.pow(255 * x, 0.5) * Math.sin(Math.PI * (-0.0000195 * Math.pow(x, 2) + 0.0125 * x ) ) + x;
},
g = function(x) {
return -0.001045244139166791 * Math.pow(x,2) + 1.2665372554875318 * x;
},
b = function(x) {
return 0.57254902 * x + 53;
},
c = {r:[],g:[],b:[]};
for(var i=0;i<=255;++i) {
c.r[i] = r( rgb(i) );
c.g[i] = g( rgb(i) );
c.b[i] = b( rgb(i) );
}
return c;
})(), // <-- THIS PART
};
My question is: is the () at the line noted just above telling the curves function to run when it's called from within the _imageData loop?
No, the function call happens as part of the initialization of that object ("_effect"). The value of the property "curves" will be the return value from invoking that function. The function builds up an object and returns it.
In JavaScript, a reference to a function followed by a parenthesized argument list is always a function call.
To make it more clear, imagine that that function had be declared as an ordinary function:
function makeCurves() {
var rgb = function (x) {
return -12 * Math.sin( x * 2 * Math.PI / 255 ) + x;
},
r = function(x) {
return -0.2 * Math.pow(255 * x, 0.5) * Math.sin(Math.PI * (-0.0000195 * Math.pow(x, 2) + 0.0125 * x ) ) + x;
},
g = function(x) {
return -0.001045244139166791 * Math.pow(x,2) + 1.2665372554875318 * x;
},
b = function(x) {
return 0.57254902 * x + 53;
},
c = {r:[],g:[],b:[]};
for(var i=0;i<=255;++i) {
c.r[i] = r( rgb(i) );
c.g[i] = g( rgb(i) );
c.b[i] = b( rgb(i) );
}
return c;
}
Then the initialization would look like:
var _effect = {
curves: makeCurves()
};
It means the function is being called immediately after being created and being assigned to the curves variable.
So I have a polynomial equation equivalent in js in a string which I can eval. (assuming the eval execution is safe) for example
2 * x + 3 * y - z = 0;
The above is a string and with appropriate scope where x, y and z are defined, I can eval the above string and it will give me the result. I want to make it so that I can find the value of x where others are given. So my desired output would be.
x = (z - 3 * y) / 2;
Is it possible to get the above string? if not then is it possible to just find the value of x when y and z are given? I know this sounds like homework but it isn't.
var x, y, z, r1, r2, a, b,
eq = "2 * x + 3 * y - z = 0;";
console.clear();
eq = eq.replace(" = 0;", "");
y = 12; z = 34;
x = 1; r1 = eval(eq);
x = 2; r2 = eval(eq);
a = r2 - r1; b = r1 - a; x = -b / a;
console.log(x);
Or, if you need the solution formula as a string:
var eq = "2 * x + 3 * y - z = 0;", eq2,
match, a, b, c, x, y, z;
function process(prefix) {
prefix = prefix.replace(/[\s\*]/g, "");
switch (prefix) {
case "" : return +1;
case "+": return +1;
case "-": return -1;
default : return +prefix;
}
}
console.clear();
match = eq.match(/^([^x]*)x([^y]*)y([^z]*)z ?= ?0;$/);
if (match === null || match.length !== 4)
console.log("Invalid equation");
else {
a = process(match[1]);
b = process(match[2]);
c = process(match[3]);
eq2 = "(" + (-b) + " * y + " + (-c) + " * z) / " + a;
console.log(eq2);
y = 12; z = 34;
x = eval(eq2);
console.log(x);
}
eq2 will be (-3 * y + 1 * z) / 2
If I have understood your question correctly,
To find the value of x:
Evaluate the remaining expression, change its sign, and divide it by x's coefficient (if it's not zero).
To get the string array,
Change the sign of each of the remaining coefficients and divide each by x's coefficient.
EDIT: As already suggested,
say b = exp(0,y,z), a = exp(1,0,0).
x = -b/a
I'm trying to solve the Project Euler Problem 9 :
A Pythagorean triplet is a set of three natural numbers, a < b < c,
for which, a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c =
1000. Find the product abc.
I looked on Wikipedia for the formula to find Pythagorean triples and tried to translate it into code. The problem is that the code is outputting the wrong answer, but I think that the code is correct.
var a, b, c;
var pos1, pos2, pos3;
var ans1, ans2, ans3;
for(var n=2; n<=20000; n++) {
a = 2 * n + 1;
b = 2 * n * (n +1);
c = 2 * n * (n +1) + 1;
if(a<b<c) {
if(a^2 + b^2 === c^2) {
pos1 = a;
pos2 = b;
pos3 = c;
}
if(a + b + c ===1000) {
ans1 = a;
ans2 = b;
ans3 = c;
}
}
}
console.log(ans1 + " " + ans2 + " " + ans3);
This is a solution
var a;
var c;
for (var b = 1; b < 1000; b += 1) {
a = (500000 - 1000 * b) / (1000 - b);
if (Math.floor(a) === a) {
c = 1000 - a - b;
break;
}
}
console.log(a, b, c);
Result is 375 200 425
on jsfiddle
Pythagoras
a2 + b2 = c2
Also we have
a + b + c = 1000
algebra, rearrange c to left
c = 1000 - (a + b)
insert c back in pythagoras
a2 + b2 = (1000 - (a + b))2
multiply out
a2 + b2 = 1000000 - 2000 * (a + b) + (a + b)2
multiply out
a2 + b2 = 1000000 - 2000 * (a + b) + a2 + 2 * a * b + b2
rearrange a2 + b2 to simplify
0 = 1000000 - 2000 * (a + b) + 2 * a * b
rearrange unknowns to left
2000 * (a + b) - 2 * a * b = 1000000
simplify, / 2
1000 * (a + b) - a * b = 500000
factorsize
a(1000 - b) + 1000 * b = 500000
rearrange
a(1000 - b) = 500000 - 1000 * b
a = (500000 - 1000 * b) / (1000 - b)
now input b, calculate a and test if a is an integer as required by Pythagorean Triples
TGarr, here is an explanation to Xotic750's answer.
I don't really understand how you created the algorithm. Why is a = to (500000 - 1000 * b) / (1000 - b) ...
He started with a^2 + b^2 = c^2, and a + b + c = 1000, and combined them because the problem on projecteuler states that there is only 1 set of numbers where both of these statments will be true. Here's how he combined them. He solved the second equation for c to be c = 1000 - (a + b). Then he plugged that into the first equation so that it became a^2 + b^2 = (1000 - (a + b))^2. He continued until he was able to solve the entire equation for a. Once he was able to do that, he was able to make a single for loop that increases b, which is much simpler and more elegant than many other options.
why is the if statement's conditions set to Math.floor(a) === a?
This just means "is a, rounded down to its nearest integer, the same as a?" In other words, is a an integer? (copy his code, and add console.log ( a ); above the if statement. That might help you understand that bit of code) Since he was able to solve the equation for a, all he had to do was plug in different numbers for b, and as soon as the outcome was an integer, he'd have the answer. Or at least he'd know what a and b c = 1000 - a - b; tells him what c is, and that's all she wrote.
Here is another solution with less code:
for(var a = 1; a < 500; a++){
for(var b = a; b < 1000; b++){
var c = Math.sqrt(a * a + b * b);
if(c > b && Number.isInteger(c) && a + b + c == 1000){
console.log(a * b * c);
}
}
}
The result is: 31875000 :)
You can't calculate powers like that.
Use Math.pow(a,2) to calculate a^2
var a, b, c;
var pos1, pos2, pos3;
var ans1, ans2, ans3;
for(var n=2; n<=20000; n++) {
a = 2 * n + 1;
b = 2 * n * (n +1);
c = 2 * n * (n +1) + 1;
if(a<b<c) {
if(Math.pow(a,2) + Math.pow(b,2) === Math.pow(c,2)) {
pos1 = a;
pos2 = b;
pos3 = c;
}
if(a + b + c ===1000) {
ans1 = a;
ans2 = b;
ans3 = c;
}
}
}
console.log(ans1 + " " + ans2 + " " + ans3);
eq 1 : a2 + b2 = c2
eq 2 : a + b + c = 1000
From eq 1 and eq 2 we can have
eq 3 : c = 1000 - a - b
Substitute the value of c from eq 3 into eq 1 we get :
eq 4 : a2 + b2 = (1000 - a - b)2
R.H.S of eq 4 is a trinomial squared. We know that square of a trinomial of such kind is
(a - b - c)2 = a2 + b2 + c2 – 2ab + 2bc – 2ca
We get :
a2 + b2 = 10002 + a2 + b2 – 2*1000*a + 2*a*b – 2*b*1000
Now we simplify to get a to the L.H.S
a = (10002 - 2*1000*b)/(2*1000*b)
Now I can use this to find out value of a where it is an integer and then use Math.sqrt( aa + bb ) to calculate the value of c. Then I can check if a+b+c==1000 holds to be true.
My solution:
public class ProjectEuler9 {
public static void main(String[] args) {
long start = System.nanoTime();
double a;
for(int b=1; b<1000; b++){
a = ( (Math.pow(1000, 2) - 2000*b ) / (2000- 2*b) );
if(Math.floor(a) == a) {
// a is an integer
double c = Math.sqrt((a*a + b*b));
System.out.println("a : " + a + " b :" + b + " c : " + c);
long product = (long) (a*b*c);
System.out.println("product abc : " + product);
break;
} else {
//a is not an integer.
}
}
long stop = System.nanoTime();
System.out.println("\nTime: " + (stop - start) / 1000 + " ns");
}
}
Output :
a : 375.0 b :200 c : 425.0
product abc : 31875000
Time: 3714 ns
Hi I was playing around with math random the other day and made an RGB color generator and successfully was able to use a text input to limit the roof of the random number, but was unable to get the floor working. Here is the JSFiddle
http://jsfiddle.net/synthet1c/3KR83/
and here is the Javascript function I made
function randomColor(){
var roof = document.getElementById('textRoof').value,
floor = document.getElementById('textFloor').value;
var r = Math.floor((Math.random()*roof)+floor);
var g = Math.floor((Math.random()*roof)+floor);
var b = Math.floor((Math.random()*roof)+floor);
if (r < 10) { var r = "0" + r}
if (r < 100) { var r = "0" + r};
if (g < 10) { var g = "0" + g};
if (g < 100) { var g = "0" + g};
if (b < 10) { var b = "0" + b};
if (b < 100) { var b = "0" + b};
document.getElementById('header').style.color= "rgb("+r+","+g+","+b+")"
document.getElementById('text').value = "rgb("+r+","+g+","+b+")"
}
This is just for the sake of learning it, but any help is appreciated.
Cheers
var roof = document.getElementById('textRoof').value,
floor = document.getElementById('textFloor').value;
// convert the string values to integer values
roof = parseInt(roof);
floor = parseInt(floor);
var r = Math.floor((Math.random()*(roof-floor))+floor);
var g = Math.floor((Math.random()*(roof-floor))+floor);
var b = Math.floor((Math.random()*(roof-floor))+floor);
live example
Your floor was a text. You need a integer - parseInt.
You can simplify your color getting by using bit shift.
function randomColor(){
var roof = parseInt(document.getElementById('textRoof').value),
floor = parseInt(document.getElementById('textFloor').value);
var r = floor + Math.floor(Math.random()*(roof-floor));
var g = floor + Math.floor(Math.random()*(roof-floor));
var b = floor + Math.floor(Math.random()*(roof-floor));
var color = ((r << 16) + (g << 8) + b).toString(16);
document.getElementById('header').style.color=
"#000000".replace(new RegExp(".{"+color.length+"}$"), color);
document.getElementById('text').value = "rgb("+r+","+g+","+b+")"
}