Filling up a 2D array with random numbers in javascript - javascript

I'm really sorry if anything like this has been posted here before but I couldn't find anything, I'm kinda new to the site still!
So for a while now I've been learning a bit about game development through html5 and javascript and I stumbled upon making tileset maps, I now have a tileset and an 2D array that I want to put certain tiles in (the number varies between 6 and 10 in this case).
I figured it could be a cool function to make the map choose between a small set of similar tiles so I don't have to specifically number every tile in the array(just define the type)
The method I have currently is probably the best for being able to define types but I want something that looks a bit cleaner and/or information to why my "cleaner" version dosen't work.
var ground = [
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()]];
function tile() {
var y = (Math.random() * 5 | 0) + 6;
return y;
}
This is the code I've been using so far, I have to edit every element of the code with the tile() function to get a random number in each one, what I wanted to have was something like this:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; j++) {
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
}
}
to fill the array without having to add the function to each spot.
I have a feeling that I'm missing a return function or something along those lines but honestly I have no idea.

You were thinking in the right direction but there are some errors in your code ;)
You have to initialize the array first before you can push elements into it.
And you were counting i++ twice
Javascript
var ground = []; // Initialize array
for (var i = 0 ; i < 15; i++) {
ground[i] = []; // Initialize inner array
for (var j = 0; j < 9; j++) { // i++ needs to be j++
ground[i][j] = (Math.random() * 5 | 0) + 6;
}
}
Maybe even better (reusable)
function createGround(width, height){
var result = [];
for (var i = 0 ; i < width; i++) {
result[i] = [];
for (var j = 0; j < height; j++) {
result[i][j] = (Math.random() * 5 | 0) + 6;
}
}
return result;
}
// Create a new ground with width = 15 & height = 9
var ground = createGround(15, 9);

Here's a quick example. I've created a function that will take in a width and height parameter and generate the size requested. Also I placed your tile function inside generate ground to keep it private, preventing other script from invoking it.
var ground = generateGround(10, 10); //Simple usage
function generateGround(height, width)
{
var ground = [];
for (var y = 0 ; y < height; y++)
{
ground[y] = [];
for (var x = 0; x < width; x++)
{
ground[y][x] = tile();
}
}
return ground;
function tile()
{
return (Math.random() * 5 | 0) + 6;
}
}
http://jsbin.com/sukoyute/1/edit

Try removing the comma from...
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
...in your 'clean' version. Also, your incrementing 'i' in both for loops:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; i++) {
Hopefully these changes make it work for you :)

Related

Javascript Multiplication table in 2D array

I've a task to write a program that creates a multiplication table for the given variable n.
The results need to be saved to a two-dimensional array. In the console I need to display the entire table with appropriate data formatting (as below). I'm starting with Javascript and already know loops and arrays only, I haven't learnt functions yet so I need some really basic solution.
This is how the result should look like:
Here is my code that I wrote so far and I don't know what to do next:
const n = 3;
const calc = []
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
calc.push(i + " * " + j + " = " + (i * j));
}
console.log(calc)
}
You're almost there:
Not sure that you need the array calc if your aim is to print the table
Define a new variable row inside the outer loop as an empty array, [];
In the inner loop, instead of calc.push, use row.push
After the inner loop, you have a complete row, which you can output using the array .join() method
If you need to, then add the row to calc with calc.push(row); not necessary in my view.
const n = 3;
//const calc = []; //may not be necessary
for (let i = 1; i <= n; i++) {
const row = [];
for (let j = 1; j <= n; j++) {
row.push(i + " x " + j + " = " + (i * j));
}
console.log( row.join(' | ') );
//calc.push(row);//not sure if you still need this
}
/* OUTPUT
1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9
*/
From the code you've presented, it appears that you're yet to understand what a 2d array really is. The way you've done it, everything's just stuffed into a single 1d array.
You may think of the pixels on a screen as being part of a 2d array. The first array holds all of the horizontal lines. The horizontal lines contain the pixels.
So.. let's concentrate on that part first.
let result = [];
for (var y=0; y<n; y++)
{
result.push( [] );
for (var x=0; x<n; x++)
{
result[y].push( (x+1) * (y+1) );
}
}
First we create a result array, and then for every row in our table, we add an array that will hold the columns, then for each column in that row, we add the values.
Next, we just step through that table and turn the values into the original equations. We start by ascertaining the dimensions of the array, before we create a table the same size.
function printTable( tbl )
{
let nRows = tbl.length;
let nCols = tbl[0].length;
for (var y=0; y<nRows; y++)
{
let rowStr = '';
for (var x=0; x<nCols; x++)
{
if (x!=0) rowStr += " | ";
rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
}
console.log(rowStr);
}
}
Chucking it all together, I present the following code. Yes, I know you're not using functions yet - but you can still see the important concepts. You can change it so that the whole equation for each entry in the table is saved, instead of just the answer.
window.addEventListener('load', init, false);
function init()
{
let result = makeMultTable(3);
printTable(result);
}
function makeMultTable(n)
{
let result = [];
for (var y=0; y<n; y++)
{
result.push( [] );
for (var x=0; x<n; x++)
{
result[y].push( (x+1) * (y+1) );
}
}
return result;
}
function printTable( tbl )
{
let nRows = tbl.length;
let nCols = tbl[0].length;
for (var y=0; y<nRows; y++)
{
let rowStr = '';
for (var x=0; x<nCols; x++)
{
if (x!=0) rowStr += " | ";
rowStr += `${y+1} x ${x+1} = ${tbl[y][x]}`;
}
console.log(rowStr);
}
}
Here is a short version of putting those multiplications into a 2D array:
const arr=[...Array(4)].map((_,i)=>i+1),
arr2=arr.map(i=>arr.map(j=>`${i}*${j}=${i*j}`));
console.log(arr2);
Multiplication of table in two dimension array
Function name: multiplyNumber
Syntex multiplyNumber(n)
n Number to be passed to function to create table upto that number.
Snippet
function multiplyNumber(n){
let table = [];
let data = [];
for (var i = 1; i <= n; i++){
for (var j = 1; j <= n; j++){
data.push(`${i} x ${j} = ${i * j}`);
}
table.push(data); // pushing data to table.
data = []; //Resetting data array to store new data each time.
}
return table;
}
var result = multiplyNumber(3);
console.log(result);
For every line I created an array line, filling it with the calculations. after the line loop I pushed it into calc.
const n = 3;
const calc = [];
for (let i = 1; i <= n; i++) {
const line = [];
for (let j = 1; j <= n; j++) {
line.push(i + " * " + j + " = " + (i * j));
}
calc.push(line);
}
console.log(calc);

Neural network in JS does not train

I am trying to create a simple neural network in javascript with 2 inputs, 3 hidden and 1 output neurons that use matrixes of neurons and weights to pass forward, and backpropagation training to solve XOR problem for example. The problem is I get weights always fading to 0 fast and as a result I thing outputs equal to sigmoid(0) 0.5 value or really close. I am using a sigmoid function for activation while finding neuron values like this:
var multyplayMatrix = (a,b) => {
if(a.length !== b.length) return "length of matrix1 !== height of matrix2 :(";
let c = [];
let temp = 0;
for(var n = 0; n < b[0].length; n++){
for(var nn = 0; nn < a.length; nn++){
temp = temp + (a[nn] * b[nn][n]);
}
//sigmoid
c.push( 1 / (1 + Math.exp(-temp)) );
temp = 0;
}
return c;
}
After finding output from training data input I compare it with training data desired output and calculate error and weights delta with this:
var getError = () => {
let predicted;
if(desiredOutput !== undefined){
predicted = net.neurons[net.neurons.length-1][0]
}else{
return console.log("desired output not defined")
}
let error = predicted - desiredOutput[0];
let weights_delta = error * (predicted * (1 - predicted));
console.log("output error weight delta = " + weights_delta)
propogateBackward(weights_delta);
};
and start backpropagating with some learning rate - My backdrop function looks like this:
var learningRate = 0.5;
var propogateBackward = (output_weights_delta) => {
for(var n = 0; n < 3; n ++ ){
net.weights[net.weights.length-(1 + n)][0] = (net.weights[net.weights.length-(1 + n)][0] - net.neurons[net.neurons.length-2][2-n]) * output_weights_delta * learningRate;
}
let neuronErrors = [];
for(var n = 0; n < 3; n ++ ){
let hiddenError = output_weights_delta * net.weights[net.weights.length-(1 + n)][0];
let hidden_weights_delta = hiddenError * (net.neurons[net.neurons.length-2][2-n] * (1 - net.neurons[net.neurons.length-2][2-n]));
neuronErrors.push(hidden_weights_delta);
}
for(var n = 0; n < 3; n++){
for(var nn = 0; nn < 2; nn++){
net.weights[net.weights.length-(4 + nn)][n] = (net.weights[net.weights.length-(4 + nn)][0] - net.neurons[net.neurons.length-3][1-nn]) * neuronErrors[n] * learningRate;
}
}
draw();
}
Im using this function and XOR dataset to make a iteration/training loop like this and just after some iterations it already coverges close to 0.5
var train = (iterations) => {
for(var it = 0; it < iterations;it++){
for(var n = 0; n < dataset.length; n++){
addInput(dataset[n].inputs);
addOutput(dataset[n].outputs);
activate();
getError();
}
}
}
After googling most similar problems are connected with weight initiation in longer/deeper neural networks but that does not help here, and I did a couple of different variants of this net all get similar result so I'm probably loose on my theory/math..but where?:(
I'm just learning stats and this can be confusing, for me so excuse me if I didn't make 2 much sense - You can check the js live implementation here: https://codepen.io/sanchopanza/pen/MWaZJJe

Javascript collision explanation for b-tree (Birthday Paradox)?

I want to create a b-tree for storing some data in local storage. I was thinking of using this to find the index of an ID in a sorted list.
If I index an array normally (i.e. to append like array[20032] = 123, what's the big-O of that in Javascript arrays?).
function sortedIndex(array, value) {
var low = 0,
high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
if (array[mid] < value) low = mid + 1;
else high = mid;
}
return low;
}
When I test this with random numbers, I get some collision and it exits before 10k.
for (i = 0; i < 10000; i++) {
var r = Math.random();
array[sortedIndex(array,r)] = r;
}
This exits after a certain time (I'm assuming because of a collision).
I'm thinking it's a birthday paradox kind of thing because the collisions seem to be more likely when the list is already populated (see graph link) (but no exception is thrown...).
I wanted to see the final length of the array after many iterations, I get distribution of final lengths that look like this:
sortedList = []
listLengths = []
for (j = 0; j < 100; j++) {
for (i = 0; i < 10000; i++) {
var r = Math.random();
sortedList[sortedIndex(sortedList,r)] = r;
}
listLengths.push(sortedList.length);
}
graph of final lengths of sorted array after 1-100 iterations of appending attempts
I honestly don't want to deal with this and would also appreciate some pointers on efficient localStorage libraries.
The problem is that you're not shifting all the old elements up when you insert a new element in the array. So you'll extend the array by 1 when the new item is higher than anything else, but just overwrite an existing element when it's less than or equal to the maximum element.
array.splice will insert and move everything over to make room.
array = [];
listLengths = [];
for (j = 0; j < 100; j++) {
for (i = 0; i < 100; i++) {
var r = Math.random();
array.splice(sortedIndex(array, r), 0, r);
}
listLengths.push(array.length);
}
console.log(listLengths);
function sortedIndex(array, value) {
var low = 0,
high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
if (array[mid] < value) low = mid + 1;
else high = mid;
}
return low;
}

Javascript syntax issue in code

Can someone tell me why this bit of JavaScript is buggy?
I have HTML also, but I don't want to make this a massive code dump.
<script type = 'text/javascript'>
var playerCards = [];
var dealerCards = [];
function deal() {
var newCard = Math.random() % 12;
var newCard2 = Math.random() % 12;
playerCards += newCard;
playerCards += newCard2;
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
document.getElementById("playerTotal").innerHTML = counter;
var dCounter = 0;
for (var j = 0; j < playerCards.length; ++j) {
dCounter += j;
}
document.getElementById("dealerTotal").innerHTML = dCounter;
}
</script>
I'm gonna assume this is a silly syntax error someplace, but I can't find it.
I'm guessing that this isn't doing what you expect it to:
playerCards += newCard;
playerCards += newCard2;
Try this instead:
playerCards.push(newCard);
playerCards.push(newCard2);
The first snippet is trying to "add" a number to an array, which doesn't exactly make sense. Through some arcane JavaScript rules, this turns the result into a string.
I'm guessing that you want to concatenate to an array instead.
Math.random returns a number between 0 and 1 - so Math.random() % 12 will probably be zero
var playerCards = [];
playerCards += newCard; //
what are you even trying to do there?
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
if playerCards had a length, this loop would result in counter having value of 0, 1, 3, 6, 10 .. n(n+1) / 2 - probably not what you intended, but who knows

Project Euler number 8

They asked me to learn JavaScript for work, so I'm doing some of the solutions on Project Euler to help me learn.
My solution for problem 8 works for the 4 number example they give, if I change the 13s to 4s, but it doesn't get the right answer for 13 digits as the question wants.
I solved this problem forever ago in C and don't remember it giving me this much trouble. Am I doing something wrong with JavaScript or is this a error with my code? In either case, please point me in the right direction.
My code:
var numbas = "\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450";
var biggestProduct = 0;
var currentProduct = 0;
var currentNumbas = {};
function product (proddedNumbas){
var productHolda = 1;
for (var i = 0; i < 13; i++)
productHolda *= proddedNumbas[i];
return productHolda;
}
for (var j = 0; j < 1000; j++)
for (var i = 0; i < 13; i++){
currentNumbas[i] = numbas[j+i];
currentProduct = product(currentNumbas);
if (currentProduct > biggestProduct)
biggestProduct = currentProduct;
}
console.log(biggestProduct);
Your loop should be
for (var j = 0; j < 1000; j++) {
for (var i = 0; i < 13; i++) {
currentNumbas[i] = numbas[j+i];
currentProduct = product(currentNumbas);
}
if (currentProduct > biggestProduct)
biggestProduct = currentProduct;
}
You just needed to move the if clause outside of the inner loop; this compares the product after it is complete.
This gives the expected answer 23514624000.

Categories

Resources