Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 hours ago.
Improve this question
We have a pattern
5 6 7 0
4 1 8 0
3 2 9 0
12 11 10 0
in javascript how can we create this pattern user define we have to create mean user give you a number for how much number should we print.
I tries my best but I didn't found the suitable answer
const input = document.querySelector('input')
const result = document.querySelector('pre')
input.addEventListener('input', () => {
if (Number.isNaN(input.valueAsNumber)) {
result.textContent = ''
return
}
const matrix = getMatrix(input.valueAsNumber)
const formatted = matrix.map(row => row.join('\t')).join('\n')
result.textContent = formatted
})
function getMatrix(count) {
const dirs = [
[0, 1], // down
[-1, 0], // left
[0, -1], // right
[1, 0] // up
]
let dirIndex = 0
// side of the matrix
const side = Math.ceil(Math.sqrt(count))
// initialize the matrix with 0
const matrix = [...Array(side)].map(() => Array(side).fill(0))
// initial position
let x = Math.floor(side / 2)
let y = Math.floor((side - 1) / 2)
// length of the side of the spiral
let length = 1
for (let i = 1; i <= count;) {
for (let j = 0; j < Math.floor(length) && i <= count; j += 1, i += 1) {
matrix[y][x] = i
x += dirs[dirIndex][0]
y += dirs[dirIndex][1]
}
// 0.5 because side is longer by 0 every two turns
length += 0.5
dirIndex = (dirIndex + 1) % dirs.length
}
return matrix
}
<input type="number">
<pre></pre>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
I need a simple algorithm to find the number of occurrences of 0 between 1 in an array, for example, after performing certain operations on these arrays:
var mas1 = [0,1,0,0,1]
var mas2 = [1,0,0,0,1]
var mas3 = [0,1,0,1,0]
var mas4 = [0,0,0,0,1]
var mas4 = [1,0,1,0,1]
We have to get:
result = 2
result = 3
result = 1
result = 0
result = 2
We can have any number of 1's or 0's in an unlimited array
Any ideas?
You can continuously use indexOf to find the next 1 while accumulating the size of ranges in between consecutive ones.
let arr = [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1];
let count = 0;
for(let i = arr.indexOf(1); i != -1; ){
const next = arr.indexOf(1, i + 1);
if (next !== -1) count += next - i - 1;
i = next;
}
console.log(count);
function MergeSortCaller() {
let array = [7, 2, 9, 3]
const auxiliaryArray = array.slice();
partition (array, 0, array.length - 1, auxiliaryArray);
}
function partition(
mainArray,
startIdx,
endIdx,
auxiliaryArray,
) {
if (startIdx === endIdx) return;
const middleIdx = Math.floor((startIdx + endIdx) / 2);
partition (auxiliaryArray, startIdx, middleIdx, mainArray);
partition (auxiliaryArray, middleIdx + 1, endIdx, mainArray);
doMerge (mainArray, startIdx, middleIdx, endIdx, auxiliaryArray);
}
function doMerge(
mainArray,
startIdx,
middleIdx,
endIdx,
auxiliaryArray,
) {
let k = startIdx;
let i = startIdx;
let j = middleIdx + 1;
while (i <= middleIdx && j <= endIdx) {
if (auxiliaryArray[i] <= auxiliaryArray[j]) {
mainArray[k++] = auxiliaryArray[i++];
} else {
mainArray[k++] = auxiliaryArray[j++];
}
}
while (i <= middleIdx) {
mainArray[k++] = auxiliaryArray[i++];
}
while (j <= endIdx) {
mainArray[k++] = auxiliaryArray[j++];
}
console.log(auxiliaryArray, mainArray)
}
MergeSortCaller()
Output:-
Aux -> 7 2 9 3
Main -> 2 7 9 3
Aux -> 7 2 9 3
Main -> 2 7 3 9
Aux -> 2 7 3 9
Main -> 2 3 7 9
This is working code of Merge Sort. But I am not able to get that how in the 3rd call of doMerge(), the auxilaryArray get changed even I don't make any change to it.
In the code all the changes are happening to mainArray.
PLZ help me...
Thanks...
Visit Graphical Structure for Visualization of mergesort it may help you.
I'm currently programming a Web game for my APCS end-of-year project. I'm trying to find the closest number in an array that is full of coords for towns. Since it is coords, I need to do this for an X and Y array. For example, x=[10, 20, 30], y=[20, 10, 23], the first town would be at [10, 20]. But since exactly finding this exact location would be hard, there is a area of 10 coords around it that you can be in, in order to discover the town.
Here's my current code:
function setTowns() {
for(i = 0; i < 9000; i++){
townLocations.x.push(random(-1000, 1000));
townLocations.y.push(random(-1000, 1000));
}
}
function checkTown() {
var townX = townLocations.x;
var townY = townLocations.y;
for(i = 0; i < townX.length; i++){
if((Math.abs(townX[i]) - Math.abs(bb.location.x)) < 10){
console.log(townX[i]);
for(i = 0; i < townY.length; i++){
if((Math.abs(townY[i]) - Math.abs(bb.location.y)) < 10){
console.log(townY[i]);
return true;
}
else {
return false;
}
}
}
}
}
checkTown() is called every time the player moves.
Imaging a map looking like this:
1 0 0 0 0 0
0 0 1 0 0 1
0 0 πΆπ½ββοΈ0 0 0
0 1 0 0 0 1
0 0 0 0 0 0
Ones are a town, and zeros contains nothing. πΆπ½ββοΈ marks the player.
You can use Pythagorean theorem to spot any kind of "collision". Let say the player is close to two towns (the ones) and each town has it's own coordinate (X, Y), as well as the player. Draw a triangle in your mind, where the Y coordinates for both places creates one side of the triangle, and the X coordinates are another side. The distance is the hypotenuse.
Let say that the distance for collision (read: detection) is 1. If the player is on coordinate (3, 3), would a town with coordinate (2, 4) be close enough? One side of the triangle would go from 3 to 2 and the other from 3 to 4. What's the hypotenuse, aka the distance?
OK, that's math for children, because you can probably see it straight away, but lets see the math behind it.
let playerXCoordinate = 3;
let playerYCoordinate = 3;
let townXCoordinate = 2;
let townYCoordinate = 4;
let xDifference = playerXCoordinate - townXCoordinate; // 3 - 2
let yDifference = playerYCoordinate - townYCoordinate; // 3 - 4
// Pythagorean theorem
let hypotenuseAsDistance = Math.sqr( Math.pow(xDifference, 2) + Math.pow(yDifference, 2))
// β(1^2 + 1^2) = β1 = 1
let isWithinDistance = hypotenuseAsDistance <= 1 // true
Lets take another example. This time with a town located at (5, 4).
let xDifference = 3 - 5;
let yDifference = 3 - 4
let hypotenuseAsDistance = Math.sqr( Math.pow(xDifference, 2) + Math.pow(yDifference, 2))
// β((3-5)^2 + (3-4)^2) = β(2^2+1^2) = β(4+1) = β5 = 2.23606797749979
let isWithinDistance = hypotenuseAsDistance <= 1 // false
A shorter version is, however, available as part of the Math object.
let xDifference = 3 - 5;
let yDifference = 3 - 4;
let hypotenuseAsDistance = Math.hypot(xDifference, yDifference);
So as for your example, it would be something like this.
let playerXPos = 3; // just an example
let playerXPos = 4; // just an example
let townArrLength = townLocations.x;
let detectionRange = 10;
let townXPos = 0;
let townYPos = 0;
let distance = 0;
for (let i = 0; i < townArrLength; i++) {
townXPos = townLocations.x[i];
townYPos = townLocations.y[i];
distance = Math.hypot(playerXPos - townXPos, playerYPos - townYPos);
if (distance <= detectionRange) {
// do something
}
}
For more reading:
https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How to create matrix, output have to looks like:
1, 3, 5, 7, 9
2, 4, 6, 8, 10
11, 13, 15, 17, 19
20, 22, 24, 26, 28
Expecting for answer on JS, but this is not the point because I`m looking for an algorithm.
Thanks.
I have tried something like this:
let arr = [];
for(let i = 0; i < 2; i++){
arr[i] = []
for(let j = 0; j < 5; j++){
if(j % 2 ==0){
arr[j] = i
}
}
}
console.log(arr)
As you can see there's a common digit 2 is added each time once you fix the starting point. so here i fixed two starting point one is even at 2 and another one is odd at 1. Now in each iteration increment both values by 2 and add both the evenArray and oddArray to final output.
Don't forget to reset evenArray and oddArray after each iteration of inner for loop.
let even = 2;
let odd = 1;
let arr = [];
for(let i = 0; i < 2; i++){
let evenArr = []
let oddArr = []
for(let j = 0; j < 5; j++){
evenArr[j] = even;
oddArr[j] = odd;
even +=2;
odd +=2;
}
even = (even-2) * 2; // to take care of point where even starts with double of last inserted value.
arr.push(oddArr.join(' '),evenArr.join(' '))
}
console.log(arr)
First, try to get the building rule
row start comment
---- ---- ---- ---- ---- ------ ------ -------------------
1 3 5 7 9 odd 1
2 4 6 8 10 even 2
11 13 15 17 19 odd 10 needs an adjustment
20 22 24 26 28 even 20
Then create an array with the wanted rows and fill it with the value. Swich the start value for each line either with 2 or 5, depending on the row's index.
Inside of each row take the start value, an adjustment for not even or odd numbers and add the double of the inner index.
var array = Array.from(
{ length: 4 },
(start => (_, i) => Array.from(
{ length: 5 },
(v => (_, j) => v + (v % 2 === i % 2) + j * 2)
(start *= (i % 2 ? 2 : 5))
))
(0.2)
);
console.log(array.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How do i calculate the number of trailing zeros in a factorial of a given number.
N! = 1 * 2 * 3 * 4 ... N
Any Help on this?
Because zeros come from factors 5 and 2 being multiplied together, iterate over all numbers from 1 to the input number, adding to a cumulative count of fives and twos whenever those factors are found. Then, return the smaller of those two counts:
function zeroCount(n) {
let fives = 0;
let twos = 0;
for (let counter = 2; counter <= n; counter++) {
let n = counter;
while (n % 2 === 0) {
n /= 2;
twos++;
}
while (n % 5 === 0) {
n /= 5;
fives++;
}
}
return Math.min(fives, twos);
}
console.log(zeroCount(6)); // 720
console.log(zeroCount(10)); // 3628800
It is very simple, This will help you.
function TrailingZero(n)
{
var c = 0;
for (var i = 5; n / i >= 1; i *= 5)
c += parseInt(n / i);
return c;
}
Let me know if you need help to understand this function.