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

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

Related

Paginate HTML textarea content from a text array in a loop

I need to paginate an array using previous and next or by specifying the position, onchange of the index the value associated with the corresponding must be displayed.
I have tried with the below code, however i fail to achive
I need to paginate an array using previous and next or by specifying the position, onchange of the index the value associated with the corresponding must be displayed.
I have tried with the below code, however i fail to achive
var resultBox = $('#result')
var messages = ["cat", "dog", "fish"];
var idx = $("#pageNumber").val();
var length = messages.length;
var getNextIdx = (idx = -1, length, direction) => {
switch (direction) {
case '1':
{
$("#pageNumber").val((idx + 1) % length + 1)
return (idx + 1) % length;
}
case '-1':
{
$("#pageNumber").val(((idx == 0) && length - 1 || idx - 1) + 1);
return (idx == 0) && length - 1 || idx - 1;
}
default:
{
return idx;
}
}
}
var getNewIndexAndRender = function(direction) {
idx = getNextIdx(idx, length, direction);
console.log(idx)
$("#result").val(messages[idx])
}
$(document).ready(function() {
$("#pageNumber").change(function() {
getNewIndexAndRender()
});
});
getNewIndexAndRender()
$( "#prev" ).trigger( "click" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="result"></textarea>
<input type="text" id="pageNumber" value="0"></input>
<button id="prev" onclick="getNewIndexAndRender('-1')">prev</button>
<button id="next" onclick="getNewIndexAndRender('1')">next</button>
In your change function, you need to reassign idx with the current input value - 1.
$("#pageNumber").change(function() {
idx = $(this).val() - 1;
getNewIndexAndRender();
});
Demo:
var resultBox = $('#result')
var messages = ["cat", "dog", "fish"];
var idx = $("#pageNumber").val();
var length = messages.length;
var getNextIdx = (idx = -1, length, direction) => {
switch (direction) {
case '1':
{
$("#pageNumber").val((idx + 1) % length + 1)
return (idx + 1) % length;
}
case '-1':
{
$("#pageNumber").val(((idx == 0) && length - 1 || idx - 1) + 1);
return (idx == 0) && length - 1 || idx - 1;
}
default:
{
return idx;
}
}
}
var getNewIndexAndRender = function(direction) {
idx = getNextIdx(idx, length, direction);
$("#result").val(messages[idx]);
}
$(document).ready(function() {
$("#pageNumber").change(function() {
idx = $(this).val() - 1;
getNewIndexAndRender();
});
});
getNewIndexAndRender()
$("#prev").trigger("click");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="result"></textarea>
<input type="text" id="pageNumber" value="0"></input>
<button id="prev" onclick="getNewIndexAndRender('-1')">prev</button>
<button id="next" onclick="getNewIndexAndRender('1')">next</button>

Game over return

I am during writing game. When condition (playerlife < 1) is meet, game should stop. Whole game is in singlePlayer function. The problem is, I don't know how to end this function. Simple placing condition inside singlePlayer function doesn't work because it is checked only once during starting a game.
if (playerlife < 1) {
return;
}
I also tried to put this condition in interval and check if condition is meet continously but I doesn't work and anyway it doesn't looks like a good idea.
Below is part of code where after moving player there are checked some conditions. Game is similar to old school "Frogger". When player jump in to the water then he lost 1 life. After loosing 3 lives game should be over.
$(function() {
function singlePlayer() {
checkPosition(x, y) {
for (var i = 0; i < raftsTab.length; i++) {
if (x == raftsTab[i].PosX && y == raftsTab[i].PosY) {
let thisRaft = raftsTab[i];
console.log(x, y);
console.log(thisRaft);
clearInterval(MoveToPlayer);
movePlayer(thisRaft);
return;
}
}
for (var i = 0; i < raftsTab.length; i++) {
if (x !== raftsTab[i].PosX && y !== raftsTab[i].PosY && y !== 0 && y !== 5 && y !== 10) {
player1.lifes = player1.lifes - 1;
//player dead after loosing 3 lives - it would be perfect if game could be ended from here
$('.lifes').text("Player lifes: " + player1.lifes);
for (var i = 0; i < trophiesTab.length; i++) {
if (player1.trophie - 1 == i) {
trophiesTab[i].show();
player1.trophie = -1;
}
}
player1.PosX = 5;
player1.PosY = 10;
clearInterval(MoveToPlayer);
changePosition();
return;
}
}
for (var i = 0; i < trophiesTab.length; i++) {
if (x == trophiesTab[i].PosX && y == trophiesTab[i].PosY && player1.trophie == -1) {
trophiesTab[i].hide();
}
}
if (x == 5 && y == 0 && player1.trophie !== -1) {
tresure1 = tresure1 + player1.trophie;
player1.items = player1.items + 1;
$('.items').text("Gathered items: " + player1.items + "/3");
player1.trophie = -1;
console.log(tresure1);
}
clearInterval(MoveToPlayer);
}
}
});

Last item in for loop executes multiple times in Javascript

I'm making a JavaScript/jQuery version of a dice game my buddies and I play. Here's a 3 player version of the game:
http://codepen.io/jwnardini/pen/jmygqd
I'm trying to make a version of the game where the user can select how many players are playing, and have the game function in the same way:
http://codepen.io/jwnardini/pen/ZKLVqW
Every time the "Go" button is pressed, it's supposed to move on to the next person's turn, and I use a modular operator if condition in a for loop to check whose turn it is, so i can perform a specific action on their turn.
var turn = 0;
$(".goButton").click(function() {
turn = turn + 1;
var playerCount = $('#input-number').val();
for (i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
});
This works great for every player I've created, except the last one (player# playerCount). This is because playerCount % playerCount = 0, and i is never 0, so the last player is always skipped.
I tried to work around this with an else statement for when turn % playerCount = 0 :
var turn = 0;
$(".goButton").click(function() {
turn = turn + 1;
var playerCount = $('#input-number').val();
for (i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
} else if (turn % playerCount == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
}
});
However, when I reach player# playerCount's turn, I get playerCount times "hi!" appended. For example, for 5 players, this is the output in browser:
Player 1
$3Hi!
Player 2
$3Hi!
Player 3
$3Hi!
Player 4
$3Hi!
Player 5
$3Hi!Hi!Hi!Hi!Hi!
Is this a classic "off by 1" error on my part? Or is my else statement flawed in some way?
The problem is your loop, when you iterate over playerCount and try to get the class name to append to.
Instead of the entire loop, try to do the following:
var m = turn % playerCount;
if (m==0) {m = playerCount};
$(".player" + m + "dollars").append("Hi!");
take out the 4th player condition outside the loop. the problem is when turn ==playercount, u dont have to enter the loop because that condiiotn is independant of i and will always be true hence hgetting executed times.
for (var i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
if (turn % playerCount == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
here is the code working code snippet :
var turn = 0;
var pot = 0;
$("form").submit(function(event){
var i = 0
var playerCount = $('#input-number').val();
var dollarCounts = [];
$(".players").empty();
for (var i=1; i <= playerCount; i++) {
var player= "player";
player = player + i.toString();
$(".players").append(
'<div class="player-wrap"><div class="player' + i.toString() + ' clearable">Player '
+ i +
'</div>$<span class="' + player + 'dollars clearable"></span><br><br><br></div>');
dollarCounts[i] = 3;
$("." + player + "dollars").empty().append(dollarCounts[i]);
}
event.preventDefault();
});
//TURN
$(".goButton").click(function() {
turn = turn + 1;
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
var dice3 = Math.floor(Math.random() * 6) + 1;
$(".turn").empty().append(turn);
//Print "Left", "Right", "Center"
if (dice1 == 1) {
$(".d1").empty().append("LEFT");
}
if (dice2 == 1) {
$(".d2").empty().append("LEFT");
}
if (dice3 == 1) {
$(".d3").empty().append("LEFT");
}
if (dice1 == 2) {
$(".d1").empty().append("RIGHT");
}
if (dice2 == 2) {
$(".d2").empty().append("RIGHT");
}
if (dice3 == 2) {
$(".d3").empty().append("RIGHT");
}
if (dice1 == 3) {
$(".d1").empty().append("CENTER");
}
if (dice2 == 3) {
$(".d2").empty().append("CENTER");
}
if (dice3 == 3) {
$(".d3").empty().append("CENTER");
}
if (dice1 == 4 || dice1 == 5 || dice1 == 6) {
$(".d1").empty().append("SAFE");
}
if (dice2 == 4 || dice2 == 5 || dice2 == 6) {
$(".d2").empty().append("SAFE");
}
if (dice3 == 4 || dice3 == 5 || dice3 == 6) {
$(".d3").empty().append("SAFE");
}
var playerCount = $('#input-number').val();
for (var i=1;i < playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
if (turn % i == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
});
//RESET
$(".resetButton").click(function() {
turn = 0;
pot = 0;
$(".players").empty();
var playerCount = 0;
var dollarCounts = [];
$(".turn").empty().append(turn);
$(".pot").empty().append(pot);
$(".d1").empty();
$(".d2").empty();
$(".d3").empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="start-form">
<label for="input-number">Number of players:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Set Player Count</button>
</form>
<button class="goButton" type="submit">Go</button>
<button class="resetButton" type="submit">Reset</button>
<br><br>
<div class="players"></div>
<h1>Turn count: <span class="turn"></span></h1>
<h2>Rolls:
<span class="d1"></span>
<span class="d2"></span>
<span class="d3"></span>
</h2>
<br>
<br>
<br>
<br>
<br>
<h1>POT</h1>
<div class="pot"></div>

Wait till user completes Multiple choice quiz or check form again in jQuery .change()

I'm writing a multiple choice quiz in jQuery that shows a total score at the end and shows a user a message based on the total score. The odd part about it is that there are 2 questions that depending on if the user selects 6a, 6b, or 6c for example, they cannot answer questions 7 or 8 or both. I coded if/else statements in .change() to block or allow the next questions. The problem is that with adding .change() the scoring does not work (all the questions are not counted to the score variable).
For some reason as soon as the page loads it is counting all the questions before the user even selects any question and I cannot use .change() if I call a function holding it using .click();
How do I have the program check or wait till the user completes the quiz (user doesnt have to answer all questions) and count all the questions answered for scoring and still allow the question using the if else statement in .change() to be used on the fly?
jQuery(document).ready(function(){
var score = 0;
var scoreQ1 = 0;
var scoreQ2 = 0;
var scoreQ3 = 0;
var scoreQ4 = 0;
//QUESTION 1
if (jQuery("input#question_1a").is(":checked")) {
scoreQ1 = 0;
}
else if (jQuery("input#question_1b").is(":checked")) {
scoreQ1 = 1;
}
else if (jQuery("input#question_1c").is(":checked")) {
scoreQ1 = 2;
} else if (jQuery("input#question_1d").is(":checked")) {
scoreQ1 = 3;
//FIND HIGHEST NUMBER OF QUESTIONS 1 - 4
if(scoreQ1 === 3 || scoreQ2 === 3 || scoreQ3 === 3 || scoreQ4 === 3 ){
score = score + 3;
}
else if(scoreQ1 === 2 || scoreQ2 === 2 || scoreQ3 === 2 || scoreQ4 === 2){
score = score + 2;
}
else if(scoreQ1 === 1 || scoreQ2 === 1 || scoreQ3 === 1 || scoreQ4 === 1){
score = score + 1;
}else if(scoreQ1 === 0 || scoreQ2 === 0 || scoreQ3 === 0 || scoreQ4 === 0){
score = score + 0;
}else {
score = score + 0;
}
//QUESTION 6 (do not score, choose next question)
jQuery("input[name=R6]").change(function()
{
if (jQuery("input#question_6a").is(":checked")) {
jQuery("input[name=R7]").removeAttr("checked");
jQuery('input[name=R7]').attr("disabled",true);
jQuery("input[name=R8]").removeAttr("checked");
jQuery('input[name=R8]').attr("disabled",true);
} else if(jQuery("input#question_6b").is(":checked"))
{
jQuery("input[name=R7]").removeAttr("checked");
jQuery('input[name=R7]').attr("disabled",false);
jQuery("input[name=R8]").removeAttr("checked");
jQuery('input[name=R8]').attr("disabled",false);
} else if(jQuery("input#question_6c").is(":checked")){
jQuery("input[name=R7]").removeAttr("checked");
jQuery('input[name=R7]').attr("disabled",false);
jQuery("input[name=R8]").removeAttr("checked");
jQuery('input[name=R8]').attr("disabled",true);
}
})
//Questions 7 and 8 look like question 1
var scoreQ7 = 0;
var scoreQ8 = 0;
var scoreQ9 = 0;
var scoreQ10 = 0;
var scoreQ11 = 0;
//QUESTION 7
if (jQuery("input#question_7a").is(":checked")) {
scoreQ7 += 1;
} else if(jQuery("input#question_7b").is(":checked")){
scoreQ7 += 2;
} else if(jQuery("input#question_7c").is(":checked")){
scoreQ7 += 3;
} else if( jQuery("input[name=R7]:checked").val()=="" ){
scoreQ7 += 0;
}
//QUESTION 8
if (jQuery("input#question_8a").is(":checked")) {
scoreQ8 += 1;
} else if(jQuery("input#question_8b").is(":checked")){
scoreQ8 += 2;
} else if(jQuery("input#question_8c").is(":checked")){
scoreQ8 += 3;
} else if( jQuery("input[name=R8]:checked").val()=="" ){
scoreQ8 += 0;
}
jQuery("input#Submit1").click(function(){
//RESULTS
if( !jQuery("input[name=lastquestion]:checked").val()=="" ){
if(score <= 5){
jQuery( "#container" ).hide();
jQuery( "div#divScore" ).html("display some text");
} else if( (score > 5 )&& (score < 11) ){
jQuery( "#container" ).hide();
jQuery( "div#divScore" ).html("display some text");
}
}
});

Finding out how many times an array element appears

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

Categories