Finding out how many times an array element appears - javascript

I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.
For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.
How could I possibly ask my computer to tell me how many times an array element appears?
Solved, here's the final product.
<script type="text/javascript">
var deck = [];
var cards = [];
var convertedcards = [];
var kinds = [];
var phase = 1;
var displaycard = [];
var options = 0;
var endgame = false;
// Fill Deck //
for(i = 0; i < 52; i++){
deck[deck.length] = i;
}
// Distribute Cards //
for(i = 0; i < 7; i++){
cards[cards.length] = Number(Math.floor(Math.random() * 52));
if(deck.indexOf(cards[cards.length - 1]) === -1){
cards.splice(cards.length - 1, cards.length);
i = i - 1;
}else{
deck[cards[cards.length - 1]] = "|";
}
}
// Convert Cards //
for(i = 0; i < 7; i++){
convertedcards[i] = (cards[i] % 13) + 1;
}
// Cards Kind //
for(i = 0; i < 7; i++){
if(cards[i] < 13){
kinds[kinds.length] = "H";
}else if(cards[i] < 27 && cards[i] > 12){
kinds[kinds.length] = "C";
}else if(cards[i] < 40 && cards[i] > 26){
kinds[kinds.length] = "D";
}else{
kinds[kinds.length] = "S";
}
}
// Card Display //
for(i = 0; i < 7; i++){
displaycard[i] = convertedcards[i] + kinds[i];
}
// Hand Strenght //
var handstrenght = function(){
var usedcards = [];
var count = 0;
var pairs = [];
for(i = 0, a = 1; i < 7; a++){
if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
pairs[pairs.length] = convertedcards[i];
usedcards[a] = "|";
}else if(a > 6){
i = i + 1;
a = i;
}
}
// Flush >.< //
var flush = false;
for(i = 0, a = 1; i < 7; i++, a++){
if(kinds[i] === kinds[a] && kinds[i] != undefined){
count++;
if(a >= 6 && count >= 5){
flush = true;
count = 0;
}else if(a >= 6 && count < 5){
count = 0;
}
}
}
// Straight >.< //
var straight = false;
convertedcards = convertedcards.sort(function(a,b){return a-b});
if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
convertedcards[0] = 14;
convertedcards = convertedcards.sort(function(a,b){return a-b});
}
alert(convertedcards);
if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
straight = true;
}else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
straight = true;
}else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
straight = true;
}
// Royal Flush, Straight Flush, Flush, Straight >.< //
var royalflush = false;
if(straight === true && flush === true && convertedcards[6] === 14){
royalflush = true;
alert("You have a Royal Flush");
}
else if(straight === true && flush === true && royalflush === false){
alert("You have a straight flush");
}else if(straight === true && flush === false){
alert("You have a straight");
}else if(straight === false && flush === true){
alert("You have a flush");
}
// Full House >.< //
if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}
// Four of a kind >.< //
else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
alert("You have four of a kind");
}
// Three of a kind >.< //
else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
alert("You have three of a kind");
}
// Double Pair >.< //
else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
alert("You have a double pair");
}
// Pair >.< //
else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
alert("You have a pair");
}
alert(pairs);
};
while(endgame === false){
if(phase === 1){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 2){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 3){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 4){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}
switch(options){
case 1:
if(phase === 5){
handstrenght();
endgame = true;
}else{
phase++;
}
break;
case 2:
endgame = true;
break;
default:
endgame = true;
break;
}
}
</script>

Keep a variable for the total count
Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
After the loop, total count contains the number of times the number you were looking for is in the array
Show your code and we can help you figure out where it went wrong
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented as
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array.

With filter and length it seems simple but there is a big waste of memory.
If you want to use nice array methods, the appropriate one is reduce:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3

Well..
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
from here:
Counting the occurrences of JavaScript array elements
Or you can find other solutions there, too..

When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)
var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;
You can even abstract over the filtering function as this:
// Creates a new function that returns true if the parameter passed to it is
// equal to `x`
function equal_func(x) {
return function(it) {
return it === x;
}
}
//...
var result = items.filter(equal_func(4)).length;

Here's an implementation of Juan's answer:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; ) {
if ( list[ l ] === x ) {
c++;
}
}
return c;
}
Even shorter:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
return c;
}

Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:
Array.prototype.count = function(lit = false) {
if ( !lit ) { return this.length}
else {
var count = 0;
for ( var i=0; i < this.length; i++ ) {
if ( lit == this[i] ){
count++
}
}
return count;
}
}
This has an extremely simple useage, and is as follows:
var count = [1,2,3,4,4].count(4); // Returns 2
var count = [1,2,3,4,4].count(); // Without first parameter returns 5

Related

recursive function returns the same value each time

So I have a checkers game, and I am trying to get it so that you can jump over multiple spaces. It works if you jump the max amount of spaces, but if you don't, say you can jump over two spaces, and you choose to jump over only one, it still removes both pieces even though you only jumped over one of the pieces. I think the problem has is inside the checkForJump() function, and it seems like every time the function is called, it returns the same array, any help would be appreciated.
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
Here is some of the other code, relating to that could also be the source of the problem
function jumpTile(tileID) {
this.tilesToRemove = [];
this.tileID = tileID;
};
let numBlackPieces = 12;
let numWhitePieces = 12;
let adjacentTileValues = [7, 9, -7, -9];
let availableSpaces = [
[],
[],
[],
[]
];
function checkValidSpace(buttonPressed, piece) {
// if button is adjacent to selectedbutton
if (buttonPressed == selectedButton + 7 || buttonPressed == selectedButton + 9 || buttonPressed == selectedButton - 9 || buttonPressed == selectedButton - 7) {
return true;
} else {
let valid = false;
// checks if there is a valid jump
checkForJump(selectedButton,[],true);
// foreach of the possible tiles, if the button pressed is one of them than remove all pieces in that tiles remove list
for (let i = 0; i < availableSpaces.length; i++) {
for (let j = 0; j < availableSpaces[i].length; j++) {
if (buttonPressed == availableSpaces[i][j].tileID) {
valid = true;
console.log("availableSpaces[" + i + j + "] is " + availableSpaces[i][j].tileID + "");
remove(availableSpaces[i][j].tilesToRemove);
return true;
}
}
}
if (valid == false)
return false;
}
}
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
function isSpaceAlreadyInArray(spot, arrayIndex) {
let SpaceAlreadyInArray = false;
for (let j = 0; j < availableSpaces[arrayIndex].length; j++) {
if (availableSpaces[arrayIndex][j].tileID == spot) {
SpaceAlreadyInArray = true;
}
}
return SpaceAlreadyInArray;
}
function clearAvailableMoves() {
for (let i = 0; i < availableSpaces.length; i++) {
availableSpaces[i].pop();
}
}
function remove(removeList, button) {
for (let i = 0; i < removeList.length; i++) {
board.value[removeList[i]] = empty;
board.buttons[removeList[i]].textContent = empty;
if (piece == black) {
numBlackPieces--;
checkForWin(numBlackPieces);
} else if (piece == white) {
numWhitePieces--;
checkForWin(numWhitePieces);
}
}
clearAvailableMoves();
};

Function to change colors multiple buttons colors only works fine in the same button

Im doing two functions "getBetNumbers" to get multiple buttons and "changeButtonColor" to change multiple button colors, i dont get any erros if i click in the same button multiple times, but whenever i click a button then another one goes to the last else from changeButtonColor. Does anyone know how can i fix it or a better way to do this?
function getBetNumbers(num) {
var ext = document.getElementById('ext');
ext.innerHTML = '';
for (i = 1; i <= num; i++) {
if (i < 10) {
ext.innerHTML +=
'<div onclick="changeButtonColor(' +
i +
')" class="quina" data-numbers="data' +
i +
'" id="ext' +
i +
'">' +
0 +
i +
'</div>';
} else {
ext.innerHTML +=
'<div onclick="changeButtonColor(' +
i +
')" class="quina" data-numbers="data' +
i +
'" id="ext' +
i +
'">' +
i +
'</div>';
}
}
}
const changeButtonColor = function (number) {
getDescription('games.json', function (err, data) {
var ext = document.getElementById('ext' + number);
if (err === null) {
console.log('Ocorreu um erro' + err);
} else if (counterr === 0) {
ext.style.backgroundColor = '#ADC0C4';
counterr = 1;
counterNumbers = counterNumbers - 1;
totalNumbers.splice(-1, 100, ext.innerText);
} else if (
counterr === 1 &&
counterNumbers <= 15 &&
whichLoteriaIs === 'lotofacil'
) {
ext.style.backgroundColor = data.types[0].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
} else if (
counterr === 1 &&
counterNumbers <= 6 &&
whichLoteriaIs === 'megasena'
) {
ext.style.backgroundColor = data.types[1].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
} else if (
counterr === 1 &&
counterNumbers <= 20 &&
whichLoteriaIs === 'lotomania'
) {
ext.style.backgroundColor = data.types[2].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
} else if (
counterr === 1 &&
counterNumbers !== 5 &&
whichLoteriaIs === 'quina'
) {
ext.style.backgroundColor = data.types[3].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
}
});
};
While it's impossible to help with the change button color code (because it relies on many variables and other functions that we don't have access to), there is a more efficient and reliable way to create your number divs. In this example, I used backticks and template literals ( ${variable} ) to create your number divs - more readable and less code. For the 'onclick', I moved those to an event listener. Just one event listener is needed for all those button actions, but because those divs get created after the page loads, we put the listener on something that won't be created and destroyed, like body and check to see if we clicked on a quina div. In the context of the event listener, you can get to the item clicked with e.target
window.addEventListener('load', () => {
document.querySelector('body').addEventListener('click', e => {
if (e.target.classList.contains('quina')) {
changeButtonColor(e.target)
}
})
})
const getBetNumbers = num => {
let str = '',
i = 0;
while (++i <= num) str += `<div class="quina" data-numbers="data${i}" id="ext${i}">${("0"+i).slice(-2)}</div>`;
document.getElementById('ext').innerHTML = str;
}
const changeButtonColor = ext => {
console.log('changeButtonColor for ', ext.id)
return // because it would error in this snippet. you can take this out.
getDescription('games.json', function(err, data) {
if (err === null) {
console.log('Ocorreu um erro' + err);
} else if (counterr === 0) {
ext.style.backgroundColor = '#ADC0C4';
counterr = 1;
counterNumbers = counterNumbers - 1;
totalNumbers.splice(-1, 100, ext.innerText);
} else if (
counterr === 1 &&
counterNumbers <= 15 &&
whichLoteriaIs === 'lotofacil'
) {
ext.style.backgroundColor = data.types[0].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
} else if (
counterr === 1 &&
counterNumbers <= 6 &&
whichLoteriaIs === 'megasena'
) {
ext.style.backgroundColor = data.types[1].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
} else if (
counterr === 1 &&
counterNumbers <= 20 &&
whichLoteriaIs === 'lotomania'
) {
ext.style.backgroundColor = data.types[2].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
} else if (
counterr === 1 &&
counterNumbers !== 5 &&
whichLoteriaIs === 'quina'
) {
ext.style.backgroundColor = data.types[3].color;
counterNumbers = counterNumbers + 1;
counterr = 0;
totalNumbers.push(ext.innerText);
}
});
};
<div id='ext'></div>
<button onclick='getBetNumbers(10)'>Get Bet Numbers</button>

Compare two array elements using if() statment [closed]

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 3 years ago.
Improve this question
Code bellow works fine, though as u can see, everything is hand wrote and if i want to push something to that arrays i will have to change whole code.
working example:
for (var s = 0; s < myButtons.length; s++) {
if (
(myButtons[s].className == "1" && colorIndex[0] > 1)
||
(myButtons[s].className == "2" && colorIndex[1] > 1)
||
(myButtons[s].className == "3" && colorIndex[2] > 1)
||
(myButtons[s].className == "4" && colorIndex[3] > 1)
||
(myButtons[s].className == "5" && colorIndex[4] > 1)
||
(myButtons[s].className == "6" && colorIndex[5] > 1)
) {continue;}
alert("things need to be done")
}
the best solution came to my mind(not working one):
for (var s = 0; s < myButtons.length; s++) {
for (var i = 0; i < colorIndex.length; i++) {
if ((myButtons[s].className == (i + 1) && colorIndex[i] > 1)) {
continue;
}
alert("things need to be done")
}
}
So what i want is: to check if all elements of array myButtons.classname==variable from cycle && colorIndex[variable from cycle]>1 OR same thing again but on next step
working code for the first algorithm
const colorIndex = []
colorIndex[0] = 201
colorIndex[1] = 30002
colorIndex[19] = -25
colorIndex[3] = 89
colorIndex[-7] = 89
colorIndex[-9] = -26
const myButtons = [...document.querySelectorAll("button")]
for (var s = 0; s < myButtons.length; s++)
{
if ( (myButtons[s].className == "1" && colorIndex[0] > 1)
|| (myButtons[s].className == "2" && colorIndex[1] > 1)
|| (myButtons[s].className == "3" && colorIndex[2] > 1)
|| (myButtons[s].className == "4" && colorIndex[3] > 1)
|| (myButtons[s].className == "5" && colorIndex[4] > 1)
|| (myButtons[s].className == "6" && colorIndex[5] > 1)
)
{ continue }
alert("things need to be done")
}
console.log('test ending')
<button class="1">1</button>
<button class="2">2</button>
<button class="4">3</button>
<button class="4">4</button>
<button class="4">5</button>
<button class="4">6</button>
<button class="4">7</button>
<button class="2">8</button>
<button class="4">9</button>
Here a pretty short and less hard coded version of the original code
var myButtons = document.querySelectorAll("button");
var colorIndex = [0, 1, 2, 0, 2, 1];
for (var index = 0; index < myButtons.length; index++) {
if (myButtons[index].className == String(index + 1)
&& colorIndex[myButtons[index].className - 1] > 1) continue;
console.log("Button at index '" + index + "' needs to get fixed");
}
<button class="1">1</button>
<button class="2">2</button>
<button class="3">3</button>
<button class="4">4</button>
<button class="5">5</button>
<button class="6">6</button>
Full code attempt:
// Create Buttons Start
var buttonDom = document.getElementById("a1");
var buttonList = [],
buttonCount = 12;
while (buttonList.length < buttonCount) {
var newInput = document.createElement("input");
newInput.type = "button";
buttonList.push(newInput);
buttonDom.appendChild(newInput);
}
var randomList1 = [];
while (randomList1.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList1.indexOf(random) === -1) randomList1.push(random);
}
var randomList2 = [];
while (randomList2.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList2.indexOf(random) === -1) randomList2.push(random);
}
randomList1.forEach((random, index) => buttonList[index].setAttribute("class", random));
randomList2.forEach((random, index) => buttonList[index + buttonCount / 2].setAttribute("class", random));
// Game Start
var myButtons = document.querySelectorAll("input[type='button']");
var click = 1;
var colorIndex = "0".repeat(6).split("").map(Number);
var color = ["red", "blue", "green", "black", "gold", "grey"];
myButtons.forEach(button => button.addEventListener("click", game));
function clickTrun() {
click = !click | 0;
}
function win() {
if (colorIndex.every(i => i == 2)) {
alert("YOU WON mdfker!");
location.reload();
}
}
function resetColorIndex() {
if (click === 1) {
colorIndex = colorIndex.map(function(colorValue) {
return colorValue < 2 ? 0 : colorValue;
});
}
}
function mainGameRules() {
setTimeout(function() {
resetColorIndex();
if (click === 1) {
myButtons.forEach(function(button) {
if (colorIndex[button.className - 1] > 1) return;
button.setAttribute("style", "background-color: none;");
button.disabled = false;
});
}
}, 700);
}
function game() {
this.disabled = true;
var index = this.className - 1;
if (index in colorIndex) {
this.setAttribute("style", "background-color:" + color[index]);
colorIndex[index]++;
mainGameRules();
clickTrun();
}
win();
}
<div id="a1">
</div>
You just need to formulate what you want to do and express it in code. Without sticking to concrete index, try to figure out how any possible index corresponds to particular color. Looking at your example you want to take className for every button, subtract 1 and take color from colorIndex and do something if that color is less than or equal to 1
for (let i = 0; i < myButtons.length; i++) {
// className for current button
const className = myButtons[i].className
// parse it into number
const num = Number(className)
// if number is valid, take element from colorIndex at number-1 position
// and see if that's not bigger than 1
if (num && colorIndex[num - 1] <= 1) {
console.log('things need to be done for index ' + i)
}
}
but my suggestion would be to reconsider your existing setup with myButtons and colorIndex into something more sophisticated

Javascript Minimax Function Exceedingly Slow

After initiating the tic-tac-toe AI move (it's currently written only to assess if miniMax can successfully run), it takes about 1 - 1.5 minutes to complete in firefox or chrome. Other tic-tac-toe game's minimax functions run on my computer in a fraction of the time.
Logging output has not led closer to the solution. Have verified that all terminal states return a score. Is there an obvious error here?
Codepen
$(document).ready(function() {
var state = {
status: "inProgress",
turn: "human", //can be human or AI
game: 1,
turnSwitch: function() {
if (this.turn == "human") {
return (this.turn = "AI");
} else if (this.turn == "AI") {
return (this.turn = "human");
}
}
};
//AI will use minimx algorithm to determine best possible move
function player(name, symbol) {
this.name = name;
this.symbol = symbol;
}
var human = new player("human", "X");
var AI = new player("AI", "O");
var board = {
board: [],
createBoard: function() {
for (let i = 0; i < 9; i++) {
this.board.push(i);
}
return this.board;
},
resetBoard: function() {
this.board = [];
createBoard();
},
//checks board for terminal state
terminalTest: function() {
for (let i = 0; i < 7; i += 3) {
if (
this.board[i] == this.board[i + 1] &&
this.board[i] == this.board[i + 2]
) {
if (typeof this.board[i] !== "number") {
return this.board[i];
}
}
}
for (let j = 0; j < 3; j++) {
if (
this.board[j] == this.board[j + 3] &&
this.board[j] == this.board[j + 6]
) {
if (typeof this.board[j] !== "number") {
return this.board[j];
}
}
}
if (
(this.board[0] == this.board[4] && this.board[0] == this.board[8]) ||
(this.board[2] == this.board[4] && this.board[2] == this.board[6])
) {
if (typeof this.board[4] !== "number") {
return this.board[4];
}
}
},
//checks for possible moves
findEmptyIndicies: function() {
return this.board.filter(a => typeof a == "number");
}
};
function miniMax(boardCurrent, player) {
//store all possible moves
var availableMoves = boardCurrent.findEmptyIndicies();
console.log("available moves length " + availableMoves.length);
//if terminal state, return score
var terminalCheck = boardCurrent.terminalTest();
if (terminalCheck === "X") {
//console.log(boardCurrent.board + " X wins score: -10")
return human.symbol == "X" ? { score: -10 } : { score: 10 };
} else if (terminalCheck === "O") {
//console.log(boardCurrent.board + " ) wins score: 10")
return human.symbol == "X" ? { score: 10 } : { score: -10 };
} else if (availableMoves.length === 0) {
console.log("availmoves length 0 " + availableMoves.length);
//console.log(boardCurrent.board + " score: 0")
return { score: 0 };
}
//array to store objects containing index and score through each iteration of available moves
var movesArray = [];
for (var i = 0; i < availableMoves.length; i++) {
//create object to store return score from each index branch
var move = {};
move.index = boardCurrent.board[availableMoves[i]];
boardCurrent.board[availableMoves[i]] = player.symbol;
//returned score from leaf node if conditionials at top of function are met
if (player.name == "AI") {
var miniMaxReturn = miniMax(boardCurrent, human);
move.score = miniMaxReturn.score;
console.log("move score " + move.score);
} else {
var miniMaxReturn = miniMax(boardCurrent, AI);
move.score = miniMaxReturn.score;
console.log("move score " + move.score);
}
boardCurrent.board[availableMoves[i]] = move.index;
movesArray.push(move);
}
var bestMove;
console.log("moves array length " + movesArray.length);
if (player.name === "AI") {
let bestScore = -1000;
for (let i = 0; i < movesArray.length; i++) {
if (movesArray[i].score > bestScore) {
bestScore = movesArray[i].score;
bestMove = i;
}
}
} else if (player.name === "human") {
let bestScore = 1000;
for (let i = 0; i < movesArray.length; i++) {
if (movesArray[i].score < bestScore) {
bestScore = movesArray[i].score;
bestMove = i;
}
}
}
return movesArray[bestMove];
}
/**function AIMove() {
console.log("ai move initiated");
var AIPosition = miniMax(board, AI);
//var index = AIposition.index;
//console.log(AIposition);
//$("#" + index).html(AI.symbol);
}**/
$(".cell").click(displayMove);
function displayMove() {
if (state.turn == "human") $(this).html(human.symbol);
board.board[this.id] = human.symbol;
state.turn = "AI";
miniMax(board, AI);
//AIMove();
console.log("AI move complete");
}
$(".cell").click(displayMove);
//on window load create board
board.createBoard();
});

Javascript loop within a loop-only executes first time

Please see my js validation function below.
function validate_submit(PassForm) {
var bGo = false;
var rankcount = document.getElementById('rankCount').value;
var j = 0;
var iRankcount0 = document.getElementById('indRankcount0').value;
var iRankcount1 = document.getElementById('indRankcount1').value;
var iRankcount2 = document.getElementById('indRankcount2').value;
var ijs = 0;
var itemp = ijs;
for (i = 0; i < rankcount; i++) {
alert("begin i = " + i);
if (i == 0) {
indRankcount = iRankcount0;
}
else if (i == 1) {
alert('indRankcount: ' + indRankcount);
indRankcount = iRankcount1;
alert('iRankcount1: ' + iRankcount1);
alert('indRankcount: ' + indRankcount);
}
else if (i == 2) {
indRankcount = iRankcount2;
}
alert('before sec loop indRank: ' + indRankcount);
alert('before sec loop itemp: ' + itemp);
for (k = itemp; k < indRankcount; k++) {
alert('in check bGo');
if (document.getElementById("selectedScore" + i + k).checked) {
bGo = true;
j++;
} //if
} //for indRankcount - k loop
if (bGo) {
if (i == 0) {
par = (Math.ceil(indRankcount / 4));
}
else if (i == 1) {
par = (Math.ceil((iRankcount1 - iRankcount0) / 4));
alert('1: ' + par);
}
else if (i == 2) {
par = (Math.ceil((indRankcount2 - iRankcount1) / 4));
}
if (j == par) {
j = 0;
bGo = false;
itemp = indRankcount;
alert("itemp = " + itemp);
continue;
}
else {
alert('25% criteria not met.');
return false;
}
}
else { //else to check bGo
alert('Atleast one box need to be selected.');
return false;
}
j = 0;
bGo = false;
itemp = indRankcount;
alert("loop ends: i =" + i);
} //for rankcount - i loop
res = window.confirm('Are you sure you want to proceed with the selection?');
if (res) {
return true;
}
else {
return false;
}
} //end of validate
Problem is when i=0, it executes fine. But when i=1, second loop (K) doesn't execute(we switched the variable to constant- it works for either itemp or indRankcount.Just one number did it.) It totally skips. Help please! Thank you!
After the inner loop (which uses "k"), there is a "itemp = indRankcount;" line. I guess this cause the issue.
On the first run the "itemp" is 0 so the inner loop step in, but on the second run this value more or equal with the "indRankcount", because you call the code before.
What values are stored in "iRankcount0", "iRankcount1" and "iRankcount2"?
Try to print the "itemp" and "indRankcount" values before the 2. loop.
Updated, try this before the k loop, it will show why the k not starts on the 2. execution.
Console.log(i + "loop:: " + itemp + " val (k first val), " + " indRankcount " + val (k end val));

Categories