I made a chip8 emulator, but ran into some problems with detecting collision when drawing. Chip8 draws onto the screen by XOR'ing individual pixels onto the screen, and setting a flag if a pixel is turned off. My code is as follows:
_DXYN: function(X, Y, N) {
console.log("_DXYN");
for (var i = 0; i < N; i++) {
for (var j = 0; j < 8; j++) {
var bitBefore = graphics[(i + cpu.registers.V[Y]) * 64 + j + cpu.registers.V[X]];
var bitAfter = bitBefore ^ cpu.getBits(memory[cpu.registers.I + i])[j];
graphics[(i + cpu.registers.V[Y]) * 64 + j + cpu.registers.V[X]] = bitAfter;
if ((bitBefore != bitAfter) && bitBefore == 1)
cpu.registers.V[0xF] = 0x1;
else
cpu.registers.V[0xF] = 0x0;
}
}
}
graphics is a 1-dimensional array of ints, each corresponding to a pixel on the screen. A pixel is on if its corresponding integer in the array is a 1, and off it it is a 0. The cpu object contains all the methods, including this one, as well as the registers. X is the opcode parameter for the register which contains the x coordinate of the sprite to draw, and Y is the opcode parameter for the register with the y coordinate. The I register is the location in memory to read from. The cpu.getBits function is as follows:
getBits: function(opcode) {
var bits = [];
for (var i = 0; i < 8; i++) {
bits.push((opcode >> i) & 1)
}
return bits.reverse();
}
The complete code can be found on github here: https://github.com/ichub/Chip8
Look in chip8cpu.js for the implementation.
I found this website : http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter which explains in detail how to write a Chip-8 interpreter. From that and the Wikipedia aticle on CHIP-8 I think that your routine should be the following:
_DXYN: function(X, Y, N) {
console.log("_DXYN");
cpu.registers.V[0xF] = 0x0;
for (var i = 0; i < N; i++) { // rows of the sprite
for (var j = 0; j < 8; j++) {
var bitBefore = graphics[(i + cpu.registers.V[Y]) * 64 + j +
cpu.registers.V[X]];
var bitAfter = bitBefore ^ cpu.getBits(memory[cpu.registers.I + i])[j];
graphics[(i + cpu.registers.V[Y]) * 64 + j + cpu.registers.V[X]] = bitAfter;
if ((bitBefore != bitAfter) && bitBefore == 1)
cpu.registers.V[0xF] = 0x1;
}
}
}
In your routine you are VF is cleared at each pixel if there is no collision so its value depends solely on the last pixel drawn. You should clear VF before starting to draw, and set it only when there is a collision.
Related
I'm trying to get N ways of solves a N rook problem. The issue I am having is currently, I seem to get n*n solutions while it needs to be N! . Below is my code, I have written it in simple loops and functions, so it's quite long. Any help would be greatly appreciated
Note: Please ignore case for n = 2. I get some duplicates which I thought I would handle via JSON.stringify
var createMatrix = function (n) {
var newMatrix = new Array(n);
// build matrix
for (var i = 0; i < n; i++) {
newMatrix[i] = new Array(n);
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
newMatrix[i][j] = 0;
}
}
return newMatrix;
};
var newMatrix = createMatrix(n);
// based on rook position, greying out function
var collision = function (i, j) {
var col = i;
var row = j;
while (col < n) {
// set the row (i) to all 'a'
col++;
if (col < n) {
if (newMatrix[col][j] !== 1) {
newMatrix[col][j] = 'x';
}
}
}
while (row < n) {
// set columns (j) to all 'a'
row++;
if (row < n) {
if (newMatrix[i][row] !== 1) {
newMatrix[i][row] = 'x';
}
}
}
if (i > 0) {
col = i;
while (col !== 0) {
col--;
if (newMatrix[col][j] !== 1) {
newMatrix[col][j] = 'x';
}
}
}
if (j > 0) {
row = j;
while (row !== 0) {
row--;
if (newMatrix[i][row] !== 1) {
newMatrix[i][row] = 'x';
}
}
}
};
// checks position with 0 and sets it with Rook
var emptyPositionChecker = function (matrix) {
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix.length; j++) {
if (matrix[i][j] === 0) {
matrix[i][j] = 1;
collision(i, j);
return true;
}
}
}
return false;
};
// loop for every position on the board
loop1:
for (var i = 0; i < newMatrix.length; i++) {
var row = newMatrix[i];
for (var j = 0; j < newMatrix.length; j++) {
// pick a position for rook
newMatrix[i][j] = 1;
// grey out collison zones due to the above position
collision(i, j);
var hasEmpty = true;
while (hasEmpty) {
//call empty position checker
if (emptyPositionChecker(newMatrix)) {
continue;
} else {
//else we found a complete matrix, break
hasEmpty = false;
solutionCount++;
// reinitiaze new array to start all over
newMatrix = createMatrix(n);
break;
}
}
}
}
There seem to be two underlying problems.
The first is that several copies of the same position are being found.
If we consider the case of N=3 and we visualise the positions by making the first rook placed red, the second placed green and the third to be placed blue, we get these three boards:
They are identical positions but will count as 3 separate ones in the given Javascript.
For a 3x3 board there are also 2 other positions which have duplicates. The gets the count of unique positions to 9 - 2 - 1 -1 = 5. But we are expecting N! = 6 positions.
This brings us to the second problem which is that some positions are missed. In the case of N=3 this occurs once when i===j==1 - ie the mid point of the board.
This position is reached:
This position is not reached:
So now we have the number of positions that should be found as 9 - 2 - 1 - 1 +1;
There appears to be nothing wrong with the actual Javascript in as much as it is implementing the given algorithm. What is wrong is the algorithm which is both finding and counting duplicates and is missing some positions.
A common way of solving the N Rooks problem is to use a recursive method rather than an iterative one, and indeed iteration might very soon get totally out of hand if it's trying to evaluate every single position on a board of any size.
This question is probably best taken up on one of the other stackexchange sites where algorithms are discussed.
How to extract elements of a matrix in a particular pattern using javascript?
following is the code for generating a 2d matrix of size any
var matrix = [];
for(var i=0; I<size; i++) {
matrix[i] = [];
for(var j=0; j<size; j++) {
matrix[i][j] = undefined;
}
}
so the first one is the original matrix. second one is the matrix made out by removing some elements/ cells.
// don't worry about splicing... this is just a demo.
[[3,5], [4,5], [4,2] ... ].forEach(([i,j], _, arr) => delete arr[i][j])
***** This is where you begin *****
(from the above splices matrix the following has to be done)
so what I want to achieve is that I want to separate or group cells from the above spliced matrix in the following manner. (like concentric circles/squares fashion by keeping in mind the fact that some cells are removed)
first you start at the central element [i,j], then move to the next level 3 x 3 & assign a value to all concentric cells (or separate cell address out)... then move to the next level 4 x 4 assign a value to all concentric cells (or separate cell address out) and so on...
Note that the spliced matrix is the starting point
travel in this fashion outwards (like concentric squares):
the idea is that:\
generate a matrix of size n * n.
remove some elements (that will be any)
... from here the algorithm starts...
separate cells from the above splices matrix in a concentric square fashion. --> this is where I want help (step 3 only)
In simple terms I want to separate out the cells from the matrix in the following order (one level at a time 3 x 3 first then 4 x 4 then 5 x 5 and so on.... ( from the above spliced matrix, which means that some cells will be already removed.)
keep in mind the fact that some cells are already removed (so you'll have to skip them -)
First, figure out the centroid of the square. The center is going to be at {length / 2, width / 2}. We're dealing in integer units, so floor. Using the convention that the top left of the figure is {0, 0} , then ie a 7x7 square has its center at
{floor(7/2), floor(7/2)} === {3,3}
Then, figure out a distance formula. In the pictures, the unit squares in purple are all the squares where either the x coordinate or y coordinate are N units away from the center. In other words
max(x - centerX, y-centerY) === N
I agree with #audzzy, you don't want to delete anything since that actually changes the length of an individual row, which we don't want. Instead just set it to another value.
So the idea is to:
find the center
iterate over each unit square
clear any unit squares which are N distance from the center
const clearCircle = (mat, N) => {
// find the center
const maxI = mat.length, maxJ = mat[0].length,
center = {
i: Math.floor(mat.length / 2),
j: Math.floor(mat[0].length / 2)
};
// iterate over all units
for (let i = 0; i < maxI; i++) {
for (let j = 0; j < maxJ; j++) {
// check if its N units from the center
if (Math.max(Math.abs(center.i - i), Math.abs(center.j - j)) === N) {
mat[i][j] = " ";
}
}
}
return mat;
}
Full example:
/*jshint esnext: true */
const generateMat = size => {
const mat = [];
for (let i = 0; i < size; i++) {
mat[i] = [];
for (let j = 0; j < size; j++) {
mat[i][j] = "[ ]";
}
}
return mat;
}
const mat = generateMat(9);
const logMat = mat => console.log("\n" + mat.map(row => (row).join(" ")).join("\n") + "\n");
const clearCircle = (mat, N) => {
// find the center
const maxI = mat.length, maxJ = mat[0].length,
center = {
i: Math.floor(mat.length / 2),
j: Math.floor(mat[0].length / 2)
};
// iterate over all units
for (let i = 0; i < maxI; i++) {
for (let j = 0; j < maxJ; j++) {
// check if its N units from the center
if (Math.max(Math.abs(center.i - i), Math.abs(center.j - j)) === N) {
mat[i][j] = " ";
}
}
}
return mat;
}
logMat(mat);
logMat(clearCircle(mat, 1));
logMat(clearCircle(mat, 2));
logMat(clearCircle(mat, 3));
Well... you just need exclude squares outside boundaries, after that you can just select elements which are in the most external layer of the matrix!
Something like that:
function extractElements(layer, matrix) {
const elements = []
const n = matrix.length; // matrix NxN
const frontIndex = layer -1;
const backIndex = n - layer;
if(layer <= 0 || layer > Math.ceil(n/2)) {
console.log("invalid layer");
return [];
}
for(let i = 0; i < n; ++i){
if(i < frontIndex || i > backIndex)
continue;
for(let j = 0; j < n; ++j){
if(j < frontIndex || j > backIndex)
continue;
if(i === frontIndex || i === backIndex || j === frontIndex || j === backIndex) {
if(matrix[i][j] !== undefined)
elements.push(matrix[i][j]);
}
}
}
return elements;
}
So, if you want the most external layer of a matrix 5x5, you can call extractElements(1, matrix)
Good code!
here's some basic code to do what you want (here I colored the cells, you could add them to a result array, or do whateve else you want)
notice it has very little iterations- only goes over the "wanted" cells every time- and colors the relevant lines and columns,
(for visual reasons -
'-' is a regular cell,
' ' is deleted cell,
'a' is a "purple" cell)
setMatrix is basically the interesting part that gets the interesting cells of every level..
let setMatrix = (matrix, level, value) => {
let size = matrix.length;
for(let x=Math.floor(size/2)-level;x<=Math.floor(size/2)+level;x++){
matrix[x][Math.floor(size/2)-level] = matrix[x][Math.floor(size/2)-level] == ' ' ? ' ' : value;
matrix[x][Math.floor(size/2)+level] = matrix[x][Math.floor(size/2)+level] == ' ' ? ' ' : value;
if(x!=Math.floor(size/2)-level && x!=Math.floor(size/2)+level){
matrix[Math.floor(size/2)-level][x] = matrix[Math.floor(size/2)-level][x] == ' ' ? ' ' : value;
matrix[Math.floor(size/2)+level][x] = matrix[Math.floor(size/2)+level][x] == ' ' ? ' ' : value;
}
}
}
and here's some code to call it for each level:
function doWork(){
// init
let size = 7;
var matrix = [];
for(var i=0; i<size; i++) {
matrix[i] = [];
for(var j=0; j<size; j++) {
matrix[i][j] = '-';
}
}
// delete
[[1,1], [2,3], [2,5], [5,1], [6,4]].forEach(([i,j])=> matrix[i][j] = ' ');
// go over each level
for(let i=0;i<=Math.floor(size/2);i++){
// set
setMatrix(matrix, i, 'a');
// print
for(let x=0;x<size;x++){
let line='';
for(let y=0;y<size;y++){
line+=matrix[x][y];
}
console.log(line);
}
console.log();
//reset
setMatrix(matrix, i, '-');
}
}
doWork();
Okay so I need the output to print hollow squares and I'm at a loss right now. I don't want the answer but I would like some hints to help get me on the right track. Thanks!
"use strict"
if (process.argv.length < 3) {
console.log("Not enough command-line arguments given.");
console.log("Usage: node lab13_4.js num");
process.exit();
}
var width = parseInt(process.argv[2]);
function makeLine(width) {
var L = "";
for(var w = 0; w < width; w += 1) { // repeated width many times
L = L + ".";
}
return L;
}
// print the line some number of times.
function printLines(line, howMany) {
// print the right number of lines
for (var i = 0; i < howMany; i += 1) { // repeated height many times
console.log(line);
}
}
for (var x = 0; x <= width; x += 1) {
var line = makeLine(x);
printLines(line, x);
}
If LENGTH be the length of the sides of the square.
You have to make nested loop and check boundary conditions.
for (var i = 0; i < LENGTH; i++) {
for (var j = 0; j < LENGTH; j++) {
if (i == 0 || i == LENGTH - 1 || j == 0 || j == LENGTH - 1) {
process.stdout.write("*")
} else {
process.stdout.write(" ")
}
}
process.stdout.write("\n")
}
We are looking for a solution like this:
*****
* *
* *
* *
*****
The top and bottom sides of the square have the full amount of stars.
All lines in between will only have one star in the beginning of the line and one star at the end of the line.
I use the following function:
function square(input) {
// top line
console.log('*'.repeat(input));
// middle lines
for(let i = 1; i < input - 1; i++) {
console.log('*' + ' '.repeat(input-2) + '*');
}
// bottom line
console.log('*'.repeat(input));
};
square(5);
hope this makes sense :)
In principle this question can be answered language-independent, but specifically I am looking for a Javascript implementation.
Are there any libraries that allow me to measure the "identicality" of two strings? More generally, are there any algorithms that do this, that I could implement (in Javascript)?
Take, as an example, the following string
Abnormal Elasticity of Single-Crystal Magnesiosiderite across the Spin
Transition in Earth’s Lower Mantle
And also consider the following, slightly adjusted string. Note the boldface parts that are different
bnormal Elasticity of Single Crystal Magnesio-Siderite across the Spin-Transition in Earths Lower Mantle.
Javascript's native equality operators won't tell you a lot about the relation between these strings. In this particular case, you could match the strings using regex, but in general that only works when you know which differences to expect. If the input strings are random, the generality of this approach breaks down quickly.
Approach... I can imagine writing an algorithm that splits up the input string in an arbitrary amount N of substrings, and then matching the target string with all those substrings, and using the amount of matches as a measurement of identicality. But this feels like an unattractive approach, and I wouldn't even want to think about how big O will depend on N.
It would seem to me that there are a lot of free parameters in such an algorithm. For example, whether case-sensitivity of characters should contribute equally/more/less to the measurement than order-preservation of characters, seems like an arbitrary choice to make by the designer, i.e.:
identicality("Abxy", "bAxy") versus identicality("Abxy", "aBxy")
Defining the requirements more specifically...
The first example is the scenario in which I could use it. I'm loading a bunch of strings (titles of academic papers), and I check whether I have them in my database. However, the source might contain typos, differences in conventions, errors, whatever, which makes matching hard. There probably is a more easy way to match titles in this specific scenario: as you can sort of expect what might go wrong, this allows you to write down some regex beast.
You can implement Hirschberg's algorithm and distinguish delete/insert operations (or alter Levenshtein).
For Hirschbers("Abxy", "bAxy") the results are:
It was 2 edit operations:
keep: 3
insert: 1
delete: 1
and for Hirschbers("Abxy", "aBxy") the results are:
It was 2 edit operations:
keep: 2
replace: 2
You can check the javascript implementation on this page.
'Optimal' String-Alignment Distance
function optimalStringAlignmentDistance(s, t) {
// Determine the "optimal" string-alignment distance between s and t
if (!s || !t) {
return 99;
}
var m = s.length;
var n = t.length;
/* For all i and j, d[i][j] holds the string-alignment distance
* between the first i characters of s and the first j characters of t.
* Note that the array has (m+1)x(n+1) values.
*/
var d = new Array();
for (var i = 0; i <= m; i++) {
d[i] = new Array();
d[i][0] = i;
}
for (var j = 0; j <= n; j++) {
d[0][j] = j;
}
// Determine substring distances
var cost = 0;
for (var j = 1; j <= n; j++) {
for (var i = 1; i <= m; i++) {
cost = (s.charAt(i-1) == t.charAt(j-1)) ? 0 : 1; // Subtract one to start at strings' index zero instead of index one
d[i][j] = Math.min(d[i][j-1] + 1, // insertion
Math.min(d[i-1][j] + 1, // deletion
d[i-1][j-1] + cost)); // substitution
if(i > 1 && j > 1 && s.charAt(i-1) == t.charAt(j-2) && s.charAt(i-2) == t.charAt(j-1)) {
d[i][j] = Math.min(d[i][j], d[i-2][j-2] + cost); // transposition
}
}
}
// Return the strings' distance
return d[m][n];
}
alert(optimalStringAlignmentDistance("Abxy", "bAxy"))
alert(optimalStringAlignmentDistance("Abxy", "aBxy"))
Damerau-Levenshtein Distance
function damerauLevenshteinDistance(s, t) {
// Determine the Damerau-Levenshtein distance between s and t
if (!s || !t) {
return 99;
}
var m = s.length;
var n = t.length;
var charDictionary = new Object();
/* For all i and j, d[i][j] holds the Damerau-Levenshtein distance
* between the first i characters of s and the first j characters of t.
* Note that the array has (m+1)x(n+1) values.
*/
var d = new Array();
for (var i = 0; i <= m; i++) {
d[i] = new Array();
d[i][0] = i;
}
for (var j = 0; j <= n; j++) {
d[0][j] = j;
}
// Populate a dictionary with the alphabet of the two strings
for (var i = 0; i < m; i++) {
charDictionary[s.charAt(i)] = 0;
}
for (var j = 0; j < n; j++) {
charDictionary[t.charAt(j)] = 0;
}
// Determine substring distances
for (var i = 1; i <= m; i++) {
var db = 0;
for (var j = 1; j <= n; j++) {
var i1 = charDictionary[t.charAt(j-1)];
var j1 = db;
var cost = 0;
if (s.charAt(i-1) == t.charAt(j-1)) { // Subtract one to start at strings' index zero instead of index one
db = j;
} else {
cost = 1;
}
d[i][j] = Math.min(d[i][j-1] + 1, // insertion
Math.min(d[i-1][j] + 1, // deletion
d[i-1][j-1] + cost)); // substitution
if(i1 > 0 && j1 > 0) {
d[i][j] = Math.min(d[i][j], d[i1-1][j1-1] + (i-i1-1) + (j-j1-1) + 1); //transposition
}
}
charDictionary[s.charAt(i-1)] = i;
}
// Return the strings' distance
return d[m][n];
}
alert(damerauLevenshteinDistance("Abxy", "aBxy"))
alert(damerauLevenshteinDistance("Abxy", "bAxy"))
Optimal String Alignment has better performance
Optimal String Alignment Distance 0.20-0.30ms
Damerau-Levenshtein Distance 0.40-0.50ms
How do I generate objects on a map, without them occupying the same space or overlapping on a HTML5 Canvas?
X coordinate is randomly generated, to an extent. I thought checking inside the array to see if it's there already, and the next 20 values after that (to account for the width), with no luck.
var nrOfPlatforms = 14,
platforms = [],
platformWidth = 20,
platformHeight = 20;
var generatePlatforms = function(){
var positiony = 0, type;
for (var i = 0; i < nrOfPlatforms; i++) {
type = ~~(Math.random()*5);
if (type == 0) type = 1;
else type = 0;
var positionx = (Math.random() * 4000) + 500 - (points/100);
var duplicatetest = 21;
for (var d = 0; d < duplicatetest; d++) {
var duplicate = $(jQuery.inArray((positionx + d), platforms));
if (duplicate > 0) {
var duplicateconfirmed = true;
}
}
if (duplicateconfirmed) {
var positionx = positionx + 20;
}
var duplicateconfirmed = false;
platforms[i] = new Platform(positionx,positiony,type);
}
}();
I originally made a cheat fix by having them generate in an area roughly 4000 big, decreasing the odds, but I want to increase the difficulty as the game progresses, by making them appear more together, to make it harder. But then they overlap.
In crude picture form, I want this
....[]....[].....[]..[]..[][]...
not this
......[]...[[]]...[[]]....[]....
I hope that makes sense.
For reference, here is the code before the array check and difficulty, just the cheap distance hack.
var nrOfPlatforms = 14,
platforms = [],
platformWidth = 20,
platformHeight = 20;
var generatePlatforms = function(){
var position = 0, type;
for (var i = 0; i < nrOfPlatforms; i++) {
type = ~~(Math.random()*5);
if (type == 0) type = 1;
else type = 0;
platforms[i] = new Platform((Math.random() * 4000) + 500,position,type);
}
}();
EDIT 1
after some debugging, duplicate is returning as [object Object] instead of the index number, not sure why though
EDIT 2
the problem is the objects are in the array platforms, and x is in the array object, so how can I search inside again ? , that's why it was failing before.
Thanks to firebug and console.log(platforms);
platforms = [Object { image=img, x=1128, y=260, more...}, Object { image=img, x=1640, y=260, more...} etc
You could implement a while loop that tries to insert an object and silently fails if it collides. Then add a counter and exit the while loop after a desired number of successful objects have been placed. If the objects are close together this loop might run longer so you might also want to give it a maximum life span. Or you could implement a 'is it even possible to place z objects on a map of x and y' to prevent it from running forever.
Here is an example of this (demo):
//Fill an array with 20x20 points at random locations without overlap
var platforms = [],
platformSize = 20,
platformWidth = 200,
platformHeight = 200;
function generatePlatforms(k) {
var placed = 0,
maxAttempts = k*10;
while(placed < k && maxAttempts > 0) {
var x = Math.floor(Math.random()*platformWidth),
y = Math.floor(Math.random()*platformHeight),
available = true;
for(var point in platforms) {
if(Math.abs(point.x-x) < platformSize && Math.abs(point.y-y) < platformSize) {
available = false;
break;
}
}
if(available) {
platforms.push({
x: x,
y: y
});
placed += 1;
}
maxAttempts -= 1;
}
}
generatePlatforms(14);
console.log(platforms);
Here's how you would implement a grid-snapped hash: http://jsfiddle.net/tqFuy/1/
var can = document.getElementById("can"),
ctx = can.getContext('2d'),
wid = can.width,
hei = can.height,
numPlatforms = 14,
platWid = 20,
platHei = 20,
platforms = [],
hash = {};
for(var i = 0; i < numPlatforms; i++){
// get x/y values snapped to platform width/height increments
var posX = Math.floor(Math.random()*(wid-platWid)/platWid)*platWid,
posY = Math.floor(Math.random()*(hei-platHei)/platHei)*platHei;
while (hash[posX + 'x' + posY]){
posX = Math.floor(Math.random()*wid/platWid)*platWid;
posY = Math.floor(Math.random()*hei/platHei)*platHei;
}
hash[posX + 'x' + posY] = 1;
platforms.push(new Platform(/* your arguments */));
}
Note that I'm concatenating the x and y values and using that as the hash key. This is to simplify the check, and is only a feasible solution because we are snapping the x/y coordinates to specific increments. The collision check would be more complicated if we weren't snapping.
For large sets (seems unlikely from your criteria), it'd probably be better to use an exclusion method: Generate an array of all possible positions, then for each "platform", pick an item from the array at random, then remove it from the array. This is similar to how you might go about shuffling a deck of cards.
Edit — One thing to note is that numPlatforms <= (wid*hei)/(platWid*platHei) must evaluate to true, otherwise the while loop will never end.
I found the answer on another question ( Searching for objects in JavaScript arrays ) using this bit of code to search the objects in the array
function search(array, value){
var j, k;
for (j = 0; j < array.length; j++) {
for (k in array[j]) {
if (array[j][k] === value) return j;
}
}
}
I also ended up rewriting a bunch of the code to speed it up elsewhere and recycle platforms better.
it works, but downside is I have fewer platforms, as it really starts to slow down. In the end this is what I wanted, but its no longer feasible to do it this way.
var platforms = new Array();
var nrOfPlatforms = 7;
platformWidth = 20,
platformHeight = 20;
var positionx = 0;
var positiony = 0;
var arrayneedle = 0;
var duplicatetest = 21;
function search(array, value){
var j, k;
for (j = 0; j < array.length; j++) {
for (k in array[j]) {
if (array[j][k] === value) return j;
}
}
}
function generatePlatforms(ind){
roughx = Math.round((Math.random() * 2000) + 500);
type = ~~(Math.random()*5);
if (type == 0) type = 1;
else type = 0;
var duplicate = false;
for (var d = 0; d < duplicatetest; d++) {
arrayneedle = roughx + d;
var result = search(platforms, arrayneedle);
if (result >= 0) {
duplicate = true;
}
}
if (duplicate = true) {
positionx = roughx + 20;
}
if (duplicate = false) {
positionx = roughx;
}
platforms[ind] = new Platform(positionx,positiony,type);
}
var generatedplatforms = function(){
for (var i = 0; i < nrOfPlatforms; i++) {
generatePlatforms(i);
};
}();
you go big data, generate all possibilities, store each in an array, shuffle the array,
trim the first X items, this is your non heuristic algorithm.