Determining array's coordinates with a string - javascript

The title is already saying. I need to determinate array's coordinates with a string.
As for example: if I want to move the value 1 to the right twice, I'm going to write in my seed variable: "rr". The r means that the value will be moved one index to the right.
In this link: http://jsfiddle.net/Kike/hVczZ/ I'm explaining better.

This works if the movement is possible :
for(var t = array.length; t >= 0; t--){
if(array[t]==1){
move(t,seed);
break;
}
}
function move(index,movements){
var size=5;
var x=index % size;
var y= Math.floor(index / size);
for(var i=0;i<movements.length;i++){
var pos=movements[i];
if(pos=='r'){
if(x+1 == size){
x=0;
y+=1;
}else{x+=1;}
}else if(pos=='l'){
if(x==0){
y-=1;
x=size-1;
}else{x-=1;}
}else if(pos=='u'){
y-=1;
}else if(pos=='d'){
y+=1;
}
}
array[index]=0;
array[size*y+x]=1;
}
console.log(array) // 1 is in fourth position

Related

Can anyone explain to me this code the i++ and y++ areas mostly the else part cause I just can't understand what's happening to get the result

This is the code to do a Fibonacci Generator. I cannot understand what the i++ and y++ are doing and how all this is resulting in giving us the sequence. :(
function fibonacciGenerator(n) {
var fib = [0, 1];
var i = 0;
var y = 1;
if (n === 1) {
fib.pop();
} else {
for (var i = 0; fib.length < n; i++) {
fib.push(fib[i] + fib[y]);
y++;
}
}
return fib;
}
i is always fib.length - 2, and y is always fib.length - 1. Every iteration increases the size of the array, so these two counters must be incremented to always point to the last two slots.

Javascript print square using for loop and conditional statement only

Just started my uni course, struggling a little with javascript. I have been asked to display a square using any character, however, the solution must combine for loops and if statements.
This is what I have so far and I feel pretty close but I just can't get the second line to display. I know this can be done via two for loops, (one for iteration of the variable and another for spaces). But this is not how I have been asked to solve this problem.
Here is my code:
var size = 3;
let i;
for(i = 0; i < size; i++) {
print ("*");
if (size === i){
println ("");
}
}
For context, this is all taking place int he professors homemade learning environment.
You could use nested for loops and take a line break after each filled line.
function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }
var size = 5,
i, j;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
print("*");
}
println("");
}
<pre id="out"></pre>
Single loop with a check if i is unequal to zero and if the remainder is zero, then add a line break.
Using:
=== identity/strict equality operator checks the type and the value, for example if both are numbers and if the value is the same,
!== non-identity/strict inequality operator it is like above, but it checks the oposite of it,
% remainder operator, which returns a rest of a number which division returns an integer number.
&& logical AND operator, which check both sides and returns the last value if both a truthy (like any array, object, number not zero, a not empty string, true), or the first, if it is falsy (like undefined, null, 0, '' (empty string), false, the oposite of truthy).
function print(s) { document.getElementById('out').innerHTML += s; }
function println(s) { document.getElementById('out').innerHTML += s + '\n'; }
var size = 5,
i;
for (i = 0; i < size * size; i++) {
if (i !== 0 && i % size === 0) {
println("");
}
print("*");
}
<pre id="out"></pre>
Well the for loop is only iterating 3 times, printing the first line. If you want a square you'll have to print 9 stars total, right? So i'm assuming, is this is the approach you'd go for, you would need to iterate not until size, but until size * size.
I'm using console.log to 'print' the square:
var dimension = 10;
var edge = '*';
var inside = ' ';
var printLine;
for (var i = 1; i <= dimension; i++) {
if (i === 1 || i === dimension) {
printline = Array(dimension + 1).join(edge);
} else {
printline = edge + Array(dimension - 1).join(inside) + edge;
}
console.log(printline);
}
Note that in the following example, an array of length 11 gets you only 10 "a"s, since Array.join puts the argument between the array elements:
Array(11).join('a'); // create string with 10 as "aaaaaaaaaa"
You wanna make a square of * where the size is the number of * on its sides?
Let's split a task into 3 parts:
where you print top side like *****
where you print middle (left and right sides) like * *
where you print bottom (same as top)
Now let's code that, I kept the code as simple as possible, this can be done in fewer lines but I think this will be easier to understand for beginners:
var size = 5;
var i = 0;
// top
for (i = 0; i < size; i++)
console.log("*");
//middle
for (var j = 0; j < size - 2; j++){
console.log("\n"); // go to next row
// middle (2 on sides with size-2 in between)
console.log("*");
for (i = 0; i < size-2; i++)
console.log(" ");
console.log("*\n"); // goes to new row as well
}
// same as top
for (i = 0; i < size; i++)
console.log("*");
Full square is even simpler:
var size = 5;
var i = 0;
for (var i = 0; i < size; i++){ // iterates rows
for (var j = 0; j < size; j++) // iterates * in row
console.log("*");
console.log("\n") // moves to new row
}
In order to print a row, you print same sign X times. Well, to print X rows we can use just that 1 more time (only this time we are iterating over a different variable (j is * in a row, i is a number of rows).
After a row is made we go to go to next row with \n.
As for
it must contain if statement
Put this at the end:
if (youCanHandleTheTruth) console.log("It's a terrible practice to tell students their solution MUST CONTAIN CODEWORDS. If you need them to showcase something, write appropriate task that will require them to do so.");

how to check which elements of an array match relative to position

Trying to create a function or two that will be able to check the elements of an array and output wheater the elements of the two arrays are identical (ie same number and identical position is present), or the number is present but does not match the same position as the other array. Basically, I'm attempting to recreate a simple game called mastermind. The main problem im having is a case senarior when say the right answer is [1,2,3,4] and the user will guess [0,1,1,1], my function will out put that the number 1 is present 3 times, and I need to figure out how to just have it say the number 1 is present 1 time. Here is the function that checks the arrays:
function make_move(guess, answ){
var myguess = document.getElementById("mymoves");
var correct_number_correct_spot= 0;
var correct_number_wrong_spot= 0;
for(var i = 0; i < 4; ++i)
{
if(answ[i] == guess[i]){
++correct_number_correct_spot;
}
else if(answ[i] !== guess[i] && $.inArray(guess[i], answ) !== -1){
++correct_number_wrong_spot;
}
}
console.log(answ);
console.log(guess);
myguess.innerHTML += correct_number_correct_spot + " were right!" +correct_number_wrong_spot+ "there but not in the right order";
}
You can keep the count of missed numbers in an object, and subtract the guessed ones that appear in the answer. Then you can calculate the correct_number_wrong_spot subtracting the number of correct_number_correct_spot and the missed ones.
function make_move(guess, answ){
var myguess = document.getElementById("mymoves");
var correct_number_correct_spot = 0;
// Initialize missed counts to the numbers in the answer.
var correct_number_wrong_spot = answ.length;
var missed = {};
for (var j = 0; j < answ.length; j++) {
missed[answ[j]] = (missed[answ[j]] || 0) + 1;
}
for(var i = 0; i < answ.length; ++i)
{
if(answ[i] == guess[i]){
++correct_number_correct_spot;
}
// Subtract the guessed numbers from the missed counts.
if (guess[i] in missed) {
missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);
}
}
// Subtract the correctly spotted numbers.
correct_number_wrong_spot -= correct_number_correct_spot;
// Subtract the remaining missed numbers.
for (var number in missed) {
correct_number_wrong_spot -= missed[number];
}
console.log(answ);
console.log(guess);
myguess.innerHTML += correct_number_correct_spot + " were right!" +correct_number_wrong_spot+ "there but not in the right order";
}
Check demo
EDIT: My try to explain doubts exposed in the comments:
would you mind explining how this code works: for (var j = 0; j < answ.length; j++) { missed[answ[j]] = (missed[answ[j]] || 0) + 1; }
missed[answ[j]] = (missed[answ[j]] || 0) + 1;
This is a quick way to increment the count for a number or initialize it to 0 if it doesn't exists yet. More or less the statement works like this:
If missed[answ[j]] is undefined then it is falsy and hence the || (or operator) evaluates to the 0. Otherwise, if we already have a value greater than 0, then it is truthy and the || evaluates to the contained number.
If it looks weird, you can replace this line with:
if (!(answ[j] in missed)) {
missed[answ[j]] = 0;
}
missed[answ[j]] += 1;
also if (guess[i] in missed) { missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);
missed[guess[i]] = Math.max(0, missed[guess[i]] - 1);
In this case I use Math.max to make sure we don't subtract below 0. We don't want repeated numbers in the guess that exceeds the number of those present in the answer count. I mean, we subtract at most until the number of repeated numbers in the answer.
if (missed[guess[i]] > 0) {
missed[guess[i]] -= 1;
}
Try this fiddle!
Without changing your original function too much, you can use an object as a map to keep track of which numbers you have already matched.
var number_matched = {};
// ...
if(!number_matched[guess[i]]) {
number_matched[guess[i]] = true;
}

More Efficient Way to Accomplish This?

I need to know the level of a player using the amount of exp he has and the exp chart. I want to do it the most efficient way possible. This is what I got. Note: The real expChart has thousands of levels/index. All the values are in increasing order.
var expChart = [1,10,23,54,65,78,233,544,7666,22224,64654,456456,1123442];
/*
lvl 0: //0-1[ exp
lvl 1: //[1-10[ exp
lvl 2: //[10-23[ exp
*/
getLvlViaExp = function(exp){
for(var i = 0 ; i < expChart.length ; i++){
if(exp < expChart[i]) break;
}
return i;
}
This is a more efficient way to do it. Every x steps, (6 i the example, probably every hundreds with real chart), I do a quick comparation and jump to approximative index, skipping many indexes.
getLvlViaExp = function(exp){
var start = 0;
if(exp > 233) start = 6;
if(exp > 1123442) start = 12;
for(var i = start ; i < expChart.length ; i++){
if(exp < expChart[i]) break;
}
return i;
}
Is there an even better way to do this?
SOLUTION:
Array.prototype.binarySearch = function(value){
var startIndex = 0,
stopIndex = this.length - 1,
middle = Math.floor((stopIndex + startIndex)/2);
if(value < this[0]) return 0;
while(!(value >= this[middle] && value < this[middle+1]) && startIndex < stopIndex){
if (value < this[middle]){
stopIndex = middle - 1;
} else if (value > this[middle]){
startIndex = middle + 1;
}
middle = Math.floor((stopIndex + startIndex)/2);
}
return middle+1;
}
The best algorithm for searching is binary search which is O(lg n) (unless you can do it with a hashing search which is O(c).
http://www.nczonline.net/blog/2009/09/01/computer-science-in-javascript-binary-search/
Basically jump to the middle of your chart ( n / 2). Is you experience higher or lower from that number. If higher jump to the middle higher half. If lower jump to the middle of the lower half: Compare and repeat until you find what you're looking for.
var expChart = [1,10,23,54,65,78,233,544,7666,22224,64654,456456,1123442];
getLvlViaExp = function(exp){
var min=0;
var max=expChart.length-1;
var i;
while(min <=max){
i=Math.round((min+max)/2);
//document.write("<br />"+i+":"+min+":"+max+"<br />");
if(exp>=expChart[i] && exp <=expChart[i+1]) {
break;
}
if(exp>=expChart[i]){
min=i+1;
}
if(exp<=expChart[i]){
max=i-1;
}
}
return i;
}
document.write(getLvlViaExp("10"));
I have tested it and it seems to work pretty well. If you want to see how many steps it actually goes through to get to the answer, uncomment the document.write in the while loop. It was kind of fascinating watching it.

Resetting the iterator in a for...in loop

This is part of the code I am using to draw some random circles:
if(circles.length != 0) { //1+ circles have already been drawn
x = genX(radius);
y = genY(radius);
var i = 0;
iCantThinkOfAGoodLabelName:
for(i in circles) {
var thisCircle = circles[i];
if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) {
//overlaps
} else {
//overlaps
x = genX(radius);
y = genY(radius);
continue iCantThinkOfAGoodLabelName;
}
if(i == circles.length - 1) { //Last iteration
//Draw circle, add to array
}
}
}
The problem is that when there is an overlap, the circle with the newly generated coordinates is not checked for overlap with the circles that the overlapping circle had already been checked with. I have tried setting i to 0 before using the continue statement but that did not work. Please help, I am really confused.
You should not use for ... in on arrays.
Use for(var i = 0; i < circles.length; ++i) instead. Then you can reset by setting i = 0.
Why not use a standard for loop
for (var i=0,l = circles.length;i < l; i++) {
....
if (i === l) {
// draw
}
}
I'm not fully understanding the question, but I do not believe you can reset the iterations of a for..in. You'll need to go to a for(var i=0;...;i++).

Categories

Resources