Javascript calculate every combination loops - javascript

I'm trying to write a function in javascript that can devide x elements over y elements in every possible combination. I included a picture of what I want to achieve.
It's some basic brute force I guess, but I can't figure out how I should write the loops. I hope somebody can help me.
Thanks in advance
for the code. I don't have much yet, because what I tried didn't work.
But I have a globaly defined empty array which is X long. And I have another array full of THE SAME elements and want every combination of the array of length X containing the elements of array with length Y.

You are looking for combination. In your case n=x and k=y.By borrowing code from here, you can visualize it by this way:
var x = 7;
var y = 3;
comb(y,x).forEach(function(item){
var tr = $('<tr>');
for(var i=0; i<x;++i){
tr.append('<td>');
}
var chunks = item.split(" ");
chunks.pop();
chunks.forEach(function(index){
tr.find("td").eq(+index).addClass("black");
});
$("table").append(tr);
});
DEMO

Related

Sorting with constraint no consecutive equals

I would like to sort a news feed according to created date, which is trivial, but I don't want 2 consecutive posts with the same userId field.
This might not be theoritically possible because what if I have only 2 posts with the same userId field?
I am looking for an algorithm that sorts according to fieldA but doesn't have 2 consecutive elements with the same fieldB.
It would also nice to have a parametrized algorithm about the required number of different posts between same user's different posts. (In the first scenario this parameter is 1)
I'm not looking for performance (O(n^2) would be okay) but a clever & simple way, maybe with 5 lines of code.
Language doesn't matter but Javascript is preferred.
To solve this problem in 5 lines is somewhat difficult,I'm trying to give a short pseudocode and you may translate it to js.
First we group the input to A[1],A[2],...,A[k].A[i] is a container contains all posts of i-th user,this can be easily done via O(n) scanning.
code:
for i = 1 to k
lastOccurPosition[i] = -intervalLength; //that is the interval length specified by parameter
for i = 1 to k
sort(A[i]);
for i = 1 to n
minElement = INF; //find the minimum
minUserId = -1; //record whose post is minimun
for j = 1 to k
if(i - lastOccurPosition[i] <= intervalLength) //if the user has occured within interval length,the user's post shouldn't be choosen
continue;
if(A[j][1] < minElement)
minElement = A[j][1];
minUserId = j;
answer[i] = minElement; //put min element into answer array
lastOccurPosition[minUserId] = i; //update choosen user's last occur position
A[minUserId].pop_front(); //delele first element
It is easy to analyse this algorithm's complexity is O(n^2) and I haven't thought out a more concise solution.
Hope to be helpful.
Put the atributes in an array, and sort that array:
arr.sort();
Put the second atribute in another array and sort that array according to the first one.
var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
if (arr[i]!=arr[i-1]) newarr.push(arr[i]);
}
Now this just remove duplicates.
This all feels kind of trivial, am I missing something?
Hope this helps.
Cheers,
Gijs

JavaScript Global Array?

I'm trying to figure out how to use a Global Array and holding 500 in an array and holding a picture/jpg to be 20x20 in size. Basically the picture would be multiplied on the screen.
For example this is what I have right now.
(function(food) {
food.arr[500];
} ) (this);
if I need to call on a picture to multiple it randomly all the time. How would this be done?
I'm still thinking about just Java, NOT JavaScript.
I dont think that you are need Global array.
Try something like this.
// Step 1 make array
var arrayFoo = ["someImageLink","anotherImageLink"/*,....etc etc*/];
var output = "";
// Step 2 print images to screen
for(var i = 0; i < arrayFoo.length; i++){
output += "<img src='"+arrayFoo[i]+"'></img>"
}
// Output the code to screen what everway you want

Generate a random array in Javascript/jquery for Sudoku puzzle

I want to fill the 9 x 9 grid from the array by taking care of following condition
A particular number should not be repeated across the same column.
A particular number should not be repeated across the same row.
When i execute the below mentioned code it fills all the 9 X 9 grid with random values without the above mentioned condition.How can I add those two condition before inserting values into my 9 X 9 Grid.
var sudoku_array = ['1','2','3','4','6','5','7','8','9'];
$('.smallbox input').each(function(index) {
$(this).val(sudoku_array[Math.floor(Math.random()*sudoku_array.length)]);
});
My JSFIDDLE LINK
Generating and solving Sudokus is actually not as simple as other (wrong) answers might suggest, but it is not rocket science either. Instead of copying and pasting from Wikipedia I'd like to point you to this question.
However, since it is bad practice to just point to external links, I want to justify it by providing you at least with the intuition why naive approaches fail.
If you start generating a Sudoku board by filling some fields with random numbers (thereby taking into account your constraints), you obtain a partially filled board. Completing it is then equivalent to solving a Sudoku which is nothing else than completing a partially filled board by adhering to the Sudoku rules. If you ever tried it, you will know that this is not possible if you decide on the next number by chosing a valid number only with respect to the 3x3 box, the column and the row. For all but the simplest Sudokus there is some trial and error, so you need a form of backtracking.
I hope this helps.
To ensure that no number is repeated on a row, you might need a shuffling function. For columns, you'll just have to do it the hard way (checking previous solutions to see if a number exists on that column). I hope i am not confusing rows for columns, i tend to do it a lot.
It's similar to the eight queens problem in evolutionary computing. Backtracking, a pure random walk or an evolved solution would solve the problem.
This code will take a while, but it'll do the job.
You can the iterate through the returned two dimensional array, and fill the sudoku box. Holla if you need any help with that
Array.prototype.shuffle = function() {
var arr = this.valueOf();
var ret = [];
while (ret.length < arr.length) {
var x = arr[Math.floor(Number(Math.random() * arr.length))];
if (!(ret.indexOf(x) >= 0)) ret.push(x);
}
return ret;
}
function getSudoku() {
var sudoku = [];
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
sudoku.push(arr);
for (var i = 1; i < 9; i++) {
while (sudoku.length <= i) {
var newarr = arr.shuffle();
var b = false;
for (var j = 0; j < arr.length; j++) {
for (var k = 0; k < i; k++) {
if (sudoku[k].indexOf(newarr[j]) == j) b = true;
}
}
if (!b) {
sudoku.push(newarr);
document.body.innerHTML += `${newarr}<br/>`;
}
}
}
return sudoku;
}
getSudoku()
You need to keep track of what you have inserted before, for the following line:
$(this).val(sudoku_array[Math.floor(Math.random()*sudoku_array.length)]);
For example you can have a jagged array (arrays of arrays, its like a 2-D array) instead of 'sudoku_array' you have created to keep track of available numbers. In fact, you can create two jagged arrays, one for column and one for rows. Since you don't keep track of what you have inserted before, numbers are generated randomly.
After you create an array that keeps available numbers, you do the following:
After you generate number, remove it from the jagged array's respective row and column to mark it unavailable for those row and columns.
Before creating any number, check if it is available in the jagged array(check for both column and row). If not available, make it try another number.
Note: You can reduce the limits of random number you generate to available numbers. If you do that the random number x you generate would mean xth available number for that cell. That way you would not get a number that is not available and thus it works significantly faster.
Edit: As Lex82 pointed out in the comments and in his answer, you will also need a backtracking to avoid dead ends or you need to go deeper in mathematics. I'm just going to keep my answer in case it gives you an idea.

How can I set a variable inside a loop without messing up the loop?

I'm quite new to this, so sorry if this is a daft question. I have searched for the answer but I can't find a close enough solution to adapt. This is part of my code:
for (var k = 0; k < (pointstoshow.length-1); k++){
// k looping nicely at this point
u = pointstoshow[k]
//k not looping at this point, only uses the last number
allpoints[u].setMap(map);
}
I am trying to access the numbers inside an array (pointstoshow) to use the number stored as a reference to search another array (allpoints), but I can't get it to work. If I set an alert to show pointstoshow[k] it works fine, it's only once I try and attach them to a variable it doesn't work.
I've been working on this most of today with no joy, so any suggestions appreciated.
Thanks
You missed a semi-colon and you need to declare u. Not entirely sure what needs to happen here so this is a shot in the dark.
var u;
for(var k = 0; k < (pointstoshow.length-1); k++){
u = pointstoshow[k];
allpoints[u].setMap(map);
}

Is it possible to initialize a bidimensional array in javascript like in java?

I want to represent a board game in javascript and for that i need a bidimensional array.
I have different board sizes, so i need to initialize the array with the board size in the beginning. I am a java programmer so i know that in java when you want a bidimensional array you just do:
int board_size = 6;
String board = new String[board_size][board_size];
How can i achieve this with javascript? I have searched and found some ways of doing this, but all much less intuitive than this one.
It is not required like in Java or C#. The Javascript arrays grow dynamically, and they are optimized to work that way, so you don't have to set the size of your matrix dimensions upfront.
However, if you insist, you could do something like the following to pre-set the dimensions:
var board = [];
var board_size = 6;
for (var i = 0; i < board_size; i++) {
board[i] = new Array(board_size);
}
So to summarize you just have three options:
Initialization with a literal (like in #Geohut answer)
Initialization with a loop (like in my example)
Do not initialize upfront, but on-demand, closer to the code that access the dimensions.
With JavaScript it is not a static language like Java. It is dynamic. That means you can create the array without a need to preset the size of the array, but if you want you can procreate an array of the size you want.
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
If you need to add to it just do
items.push([7,8]);
That will add the next element.
Code taken from old stack overflow post: How can I create a two dimensional array in JavaScript?
Edited to properly make I in items same as variable declaration.

Categories