How to select specific numbers in a multiplication table (JavaScript) - javascript

I have an assignment where I have to create a function that returns the sum of all highlighted numbers from this multiplication table:
We have to use a for-loop to solve this assignment, and haven't learned about stuff like arrays, matrixes, and other more advanced concepts that would make this easier.
Here's what I came up with:
function pitagorica2(){
var x = 0, y = 0;
for (var i = 1; i <=10; i++) {
x += i*5;
y += i*6;
}
x = x*2 - 25 - 30;
y = y*2 - 30 - 36;
return x + y;
}
Is there any better way to get to the same result without using more advanced things?

Related

Looking for more elegant way to solve this simple logic task

This is part of a bigger problem I try to solve in an exercise. It looks like this:
x is 10 times more likely to appear than y.
z appears 2x less often than y.
I solved this by calculating a single unit like this:
const x = 100;
const y = 10;
const z = 5;
const unit = 100 / (x + y + z);
unit equals 0.87
So when I do (0.87) + (0.87 * 10) + (0.87 * 5) I get 100%(almost)
Then I generate a random number between 0 and 1.
const randomNumber = Math.random();
function getValue() {
if (randomNumber <= 0.87) {
console.log('x');
} else if (randomNumber > 0.87 && randomNumber < 95.7) {
console.log('y');
} else console.log('z');
}
getValue();
If value<0.87 then I log out x, if value < 0.87+(0.087*10) I log y etc
Can anyone recommend a more logical and elegant way than this?
Your way looks clean for me except the fact that randomNumber > 0.87 is redundant.
if you store the value x, y and z in an array, you can probably write some cleaner code for example:
let prob = [100, 10, 5];
let sum = prob.reduce((a, b) => a + b, 0);
let normalizedProb = prob.map(p => p / sum);
let cummulativeProb = normalizedProb.map((cummulative => p => cummulative += p)(0));
for (let i = 0; i <= 50; i++) {
let r = Math.random();
console.log(cummulativeProb.filter(p => r >= p).length);
}
Also, you may want to read this post for faster implementation (in python though). However, the code will be more complicated for sure.
Since the weights are small integers, you can duplicate the x, y and z in an array, and just pick one random cell of the array:
let choices = "zyyxxxxxxxxxxxxxxxxxxxx";
console.log(choices[Math.floor(Math.random() * 23)]);
Here the magic number 23 is the number of choices, 1+2+20; and Math.floor(Math.random() * 23) is a random integer uniformly at random in range [0, 22] (both bounds included). See also:
Generating random whole numbers in JavaScript in a specific range?

How do I make my code list all the possibilities of 2 dice being rolled using for loops?

/Write a program that prints all possible dice rolls with 2 dice. To do so, you should use a double for loop. Hint: You can’t use i for both for loops./
var SIDES_ON_DICE = 6;
for(var y = 1; y <=6; y++){
println(y);
}
/ I don't know how I would list all the possible dice rolls with for loops. More specifically, how would I go about solving this? I'm thinking I have to make it so my two variables for the 2 dice (lets call it x and y) have to increment in relation to each other. so for example, the dice rolls will be 1,1 then 1,2 until 1,6. then it goes to 2,1 etc etc. I'm thinking I need to increment the dice in relation to each other, so for example i make it so dice x increments by 1 every time dice y is equal to 6. How would I do this with for loops? Or is there a better way to go about solving this? thank you/
This is how its done :
This will list all the unique possibilities.
var SIDES_ON_DICE = 6;
for(var x = 1; x <= SIDES_ON_DICE; x++){
for(var y = x; y <= SIDES_ON_DICE; y++){
println("x is " + x + " and y is " + y);
}
}
With all possibilities:
var SIDES_ON_DICE = 6;
for(var x = 1; x <= SIDES_ON_DICE; x++){
for(var y = 1; y <= SIDES_ON_DICE; y++){
println("First Dice is " + x + " and Second Dice is " + y);
}
}

Detecting multiple array coordinates in canvas

Hello fellow programmers,
Today I have a question that's related to one of my projects I'm making kinda like Tower Defense using canvas. However, I stuck on trying to detect multiple circles in one coordinate. Here's my example:
for (var a = 0; a < buildArcherX.length; a++) {
for (var a = 0; a < buildArcherY.length; a++) {
if (Math.sqrt(Math.pow(buildArcherX[a] - this.x, 2) + Math.pow(buildArcherY[a] - this.y, 2)) <= arch.radius + 7) {
this.attackedByArcher = true;
} else {
this.attackedByArcher = false;
}
}
}
As you can see in this example, I'm using arrays to put my coordinates in for my "Defenses". The for statements runs through all the "defense" coordinates in the arrays. The if statement in the code calculates if any of the defense coordinates are within "this" coordinates. This returns a boolean if any of the defenses are in range.
However I got to this point, and then got stuck on this problem: What happens if multiple defenses are in range? Then "this" would need to take more damage. So I'm just wondering if I can show the number of defenses in range.
Thanks!
You can use an integer to store the value of how many defenses are in range and increment it whenever a defense has been found in range.
Also, you must use 2 different variables when nesting loops.
this.defensesInRange = 0;
for (var x = 0; x < buildArcherX.length; x++) {
for (var y = 0; y < buildArcherY.length; y++) {
if (Math.sqrt(Math.pow(buildArcherX[x] - this.x, 2) + Math.pow(buildArcherY[y] - this.y, 2)) <= arch.radius + 7) {
this.defensesInRange += 1;
}
}
}

Why cube is faster than square

I wrote this:
var max = 0xffffff * 4;
var step = 1 / max;
function cube() {
var result = 0.;
for (var x = 0.; x < 1; x += step) {
result += x * x * x;
}
return result;
}
function mul() {
var result = 0.;
for (var x = 0.; x < 1; x += step) {
result += x * x;
}
return result;
}
function go() {
var r = '';
r += cube() + ' \n';
r += mul() + ' \n';
alert(r);
}
and see the result in Chrome profiler:
mul: 106ms
cube: 87ms
How is that possible?
Your assertion is plain wrong. cube is not faster than mul and your example does not prove it.
In fact, what happens is that the internals of Javascript execution take more time than the actual multiplication, resulting in very similar times for mul and cube. I ran the two functions in a loop, just to increase the difference and the profiler shows 20219 vs 20197, which is insignificant. And BTW, cube is the "slower" one here.
Moreover, this method of profiling doesn't work because both Chrome and Firefox are optimizing a lot before doing maths inside loops. What you think is a loop may very well use a cached value or even a mathematical function that the optimization knows returns the same result.
Here is the code I used:
<script>
var max = 0xffffff * 4;
var step = 1 / max;
function cube() {
var result = 0.;
for (var x = 0.; x < 1; x += step) {
result += x * x * x;
}
return result;
}
function mul() {
var result = 0.;
for (var x = 0.; x < 1; x += step) {
result += x * x;
}
return result;
}
function go() {
var s='';
for (var i=0; i<100; i++) {
s+=cube();
s+=mul();
}
console.log(s);
}
go();
</script>
Also, as a reference only, watch the video here: https://fosdem.org/2016/schedule/event/mozilla_benchmarking_javascript_tips/ where a Firefox guy explains why microbenchmarking doesn't really mean much.
maybe the optimizer decides one of them could be executed with vector instructions while the other uses plain old fmul. I'm speculating that 'square' uses fmul and cube uses vector instruction mulpd which can multiply up to 4 doubles in one instruction. I added a 'quad' which did 4 multiplies and its time is pretty close to cube. but when i went to 'five' it slowed down slower than square. That is some indirect evidence that vector instructions are in use for cube and quad.
It would be interesting to see the results on an intel cpu vs arm on a tablet.
This is likely because since all your numbers are below 1 the cube function is adding smaller numbers than the square and (I'm not sure if this is actually how it works) therefore taking less time. This is just a guess. And because the numbers are so small this could also be due to inadequate precision. Also I tested with numbers over one the cube is slower with them.
On some browsers, javascript starts out as interpreted while the JIT compiles it in the background. Once the javascript is compiled, it starts running faster.

Combinations Of Numbers To Equal One Total

In javascript I get two numbers let's call them x & y and an array of integers with random int's from 0 - 10 arrayints.
x is the number I'm trying to get by combining y with any of the numbers in arrayints.
for example: lets say x = 8 and y = 3 and arrayints consists of numbers arrayints(1,7,2,7,4,5)
so x could equal = y + 5
or
x = y + 1 + 4
All the values in x, y and arrayints will be random and always <= 10.
Please advise if more information is needed and everything will be in javascript or jquery no fuss as far as my code goes I will copy and paste but it will just be one blob of incromprehensible letters which are giving me an headache.
function makex(x,y) {
//this is how I get the array of random ints <=10
$("#div").children().each(function(n, i) {
var id = parseInt(this.id+"");
});
}
Here's a recursive solution that returns an array of the integers that add up to x, including y (or an empty array if it doesn't exist). If you want to exclude y, then feel free to make a wrapper for this.
function make(x, y, intOptions) {
var z = x - y
if (intOptions.indexOf(z) !== -1) {
return [y, z];
} else if (intOptions.length > 1){
var i = intOptions.length;
var ans;
while (i--) {
ans = make(z, intOptions[i], intOptions.slice(0, i))
if (ans.length) {
return [y].concat(ans);
}
}
}
return [];
}

Categories

Resources