I'm a javascript newbie working on a hangman game, I had everything working properly until I realized that my method for comparing my guess to the answer was unable to handle words with multiple letters. I've written a new loop that takes care of this, but that's led to a new problem: I don't know how to work in a counter to keep track of wrong guesses.
This is the loop that I have:
function checkGuess(guess, array) {
for (let i = 0; i < array.length; i++) {
let found = false;
for (let j = 0; j < array.length; j++) {
if (array[i] === guess) {
found = true;
}
}
if (found) {
results += answer[i];
}
}
}
The game will end when the number of wrong guesses reaches a certain count or when results.length = answer.length but I can't figure out how to handle wrong guesses. Any tips would be appreciated.
try this, create a function that return the number of places that the guess exists
function checkGuess(guess, array) {
let found = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] === guess) {
found++;
}
}
return found;
}
then use 2 vars to hold the correct guess and the wrong guess
var correct = 0, wrong = 0
then every time the user is guessing, do the following:
var check = checkGuess(guess, question);
if (check > 0) {
correct += check;
} else {
wrong++;
}
to determine if win or lose
if (wrong >= 3) {
// set it to lose
}
if (correct == question.length) {
// set it to win
}
Is this maybe what you're looking for?
var wrongGuesses = 0;
function checkGuess(guess, array) {
for (let i = 0; i < array.length; i++) {
let found = false;
let go_time = false;
for (let j = 0; j < array.length; j++) {
if (array[i] === guess) {
found = true;
results += answer[i];
}
if(j===(array.length-1)){
go_time = true;
}
}
if (go_time===true&&found!==true) {
wrongGuesses++;
}
}
}
Related
So I'm doing a codewars challenge and I have no clue why my code isn't working. I'm a beginner so please don't hate on me.
This is my code:
function digital_root(n) {
let str = n.toString()
let arr = []
let sum = 0
for (let i = 0; i < str.length; i++) {
arr.push(str.charAt(i))
}
for (let i = 0; i < str.length; i++) {
sum += Number(arr[i])
}
let sumStr = sum.toString()
if (sumStr.length > 1) {
digital_root(sum)
} else if (sumStr.length == 1) {
return sum
}
}
It works when I console.log it but not when I return the value. I'm trying to learn recursion. Thanks for the help!
You need to return digital_root(sum) too, if sumStr.length > 1 in order to access recursive returned value.
you have to write return digital_root(sum) instead of just digital_root(sum).
check below:
function digital_root(n) {
let str = n.toString()
let arr = []
let sum = 0
for (let i = 0; i < str.length; i++) {
arr.push(str.charAt(i))
}
for (let i = 0; i < str.length; i++) {
sum += Number(arr[i])
}
let sumStr = sum.toString()
if (sumStr.length > 1) {
return digital_root(sum)
} else if (sumStr.length == 1) {
return sum
}
}
console.log("Digital Root :", digital_root('123456789'));
Ok, it seems you are missing dealing with the return value of digital_root when you call it recursively. See added "return" statement below.
function digital_root(n) {
let str = n.toString()
let arr = []
let sum = 0
for (let i = 0; i < str.length; i++) {
arr.push(str.charAt(i))
}
for (let i = 0; i < str.length; i++) {
sum += Number(arr[i])
}
let sumStr = sum.toString()
if (sumStr.length > 1) {
// ***** You need to deal with the return value of digital_root when you call it.
return digital_root(sum)
} else if (sumStr.length == 1) {
return sum
}
}
However, while JavaScript's functional coding style does support recursive functions, we need to be aware that most JavaScript compilers are not currently optimized to support them safely. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.
Please read this,
https://www.sitepoint.com/recursion-functional-javascript/#:~:text=However%2C%20while%20JavaScript's%20functional%20coding,parameters%20from%20within%20a%20loop.
I'm a total beginner and I'm stuck completely on this problem. I'm supposed to use a for loop to traverse an array, pushing odd numbers to the 'odd' array, and evens to the 'even' array.
No numbers are showing up in my arrays when I test the code. I've tried writing it the following two ways:
#1
function pickIt(arr){
var odd=[],even=[];
//coding here
for (i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) {
odd.push();
} else {
even.push();
}
console.log(arr[i]);
}
return [odd,even];
#2
function pickIt(arr){
var odd=[],even=[];
//coding here
for (i = 0; i > 0; i++) {
if (i % 2 !== 0) {
odd.push();
} else {
even.push();
}
}
return [odd,even];
}
I've checked out some of the solutions to the problem and with respect to the code I've got in #2, the most common solution I guess has the for condition written like this:
for (i of arr)
and then in the if else statement it's written:
odd.push(i);
even.push(i);
respectively, but I have no idea how people got there especially concerning the 'for' bit. Can anyone help my brain understand this?
function pickIt(arr){
var odd=[],even=[];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) {
odd.push(arr[i]);
} else {
even.push(arr[i]);
}
}
console.log(odd);
console.log(even);
}
pickIt([10,5,6,3,24,5235,31]);
const odds = [];
const evens = [];
function separateOddEven(arr){
for (let i = 0; i < arr.length; i++){
updateArray(arr[i]);
}
}
function updateArray(number){
if (number % 2) {
odds.push(number);
}
else {
evens.push(number);
}
}
separateOddEven([7, 3, 4, 1, 5]);
Today I try to solve a problem on codewars,it requires me give the permutations of a given string.
Firstly,I try to use a recursion function looks like:
function permutate(str) {
var result = [];
if (str.length == 1) {
return [str]
} else {
var preResult = permutate(str.slice(1));
for (var j = 0; j < preResult.length; j++) {
for (var k = 0; k < preResult[j].length + 1; k++) {
var temp = preResult[j].slice(0, k) + str[0] + preResult[j].slice(k);
result.push(temp);
}
}
return result;
}
}
After I click the attemp button,the OJ tells me there is an error caused by heap out memory.Because my function called with a long string:"abcdefghijkl".
Secondly,I rewrite my function by using loop.just like:
function perm(str) {
let result = [],tempArr = [];
let subStr = str;
while (subStr.length !== 0) {
if (result.length === 0) {
result.push(str[0]);
} else {
for (let i = 0; i < result.length; i++) {
let item = result[i];
let itemLen = item.length;
for (let j = 0; j < itemLen+1; j++) {
let temp = item.slice(0, j) + subStr[0] + item.slice(j);
tempArr.push(temp);
}
}
result = tempArr;
tempArr = [];
}
subStr = subStr.slice(1);
}
return result;
}
It works when the given string is short.But still cause Error.
So,I want to know why cause this error and if there is a permutation algorithm can run in Node(v6.11.0) without memory error?
I searched a lot and tried many methods,but nothing works.So I ask my first question on stackoverflow,hoping you can give me some help.Thanks!
Try the module https://github.com/miguelmota/permutations, or even try to use the code from the module
In addition to previous answer as a possible try out, you can try to increase process max memory limit size, for example with node --max-old-space-size=8192 which is in bytes, the node process will run with extended 8GB memory limit.
I am trying to find the largest submatrix that is an identity matrix. I have no idea how to run through all the possible submatrices. I have however, managed to come up with a function that determines if a matrix is identity:
function isIdentityMatrix(matrix) {
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix.length; j++) {
if (matrix[i][j] !== 1 && i === j || matrix[i][j] && i !== j) {
return false;
}
}
}
return true;
}
Any help in looping through all submatrices would be greatly appreciated. Keep in mind that I am a newbie to javascript.
You can try something like this. This program
-Finds a sub-matrix
-Returns true if that martrix is identity or not
Note: This works for nxn matrix only but can be easily tweaked to work with nxm matrix.
let arr=[
[1,1,1,0,0],
[0,1,1,0,0],
[0,0,1,0,0],
[1,0,1,1,0],
[0,0,0,1,1]
];
let finalValue=0;
let n=arr.length;
let N=2;//size of submatrices
function subMatrix(k,n,N,arr)
{
let max_k_x=n-N+1;// per row max value of k
let row=Math.floor(k/max_k_x);
let col=k%max_k_x;
/*
k=6,n=4,N=2
max_k=(4-2+1)*(4-2+1)=9
max_k_x=3
row=2(starting from zero)
col=0
*/
let matrix=new Array();
for(let i=row;i<row+N;i++){
for(let j=col;j<col+N;j++){
matrix.push(arr[i][j]);
}
}
return matrix;
}
function doSomethingWithMatrix(matrix,N){
for(let i=0;i<matrix.length;i++){
if((matrix[i] && (i%(N+1)!==0))||(matrix[i]!==1 && (i%(N+1))===0)){
return false;
}
}
return true;
}
for(let k=0;k<(n-N+1)*(n-N+1);k++){//k can vary from 0 to (((n-N+1)^2)-1)
let matrix=new Array();
matrix=subMatrix(k,n,N,arr);
// console.log(doSomethingWithMatrix(matrix,N));
// console.log(" ");
if(doSomethingWithMatrix(matrix,N)){
finalValue=N;
N++;
k=0;
if(N===n){
N--;
break;
}
}
if(k===(n-N+1)*(n-N+1)-1){
N++;
}
matrix=[];
}
console.log("final N: "+finalValue);
You can change the value N inside the loop to check for NxN sub-matrices.
So I'm trying to find how many of each number from zero to ten is generated in a random array.
I created a random array list
i=0;
var ranList=[];
while (i<20){
i++;
ranList.push(Math.floor(10*Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
/*Then I made a function to count /elements from this array
*/
function ctnumber(array,elem){
var ct=0;
var j =0;
while(j<array.length)
{
j++;
if(array[j]==elem){
ct+=1;}
}
}
return ct;
}
alert(ctnumber(ranList,5));
The second function doesn't execute, any idea why?
Thank you!
First you should avoid using the name array for you variable:
http://www.w3schools.com/js/js_reserved.asp
Your brackets are also wrong. Change your function to this and it should work:
function ctnumber(arr,elem){
var ct=0;
var j =0;
while(j<arr.length)
{
j++;
if(arr[j]==elem){
ct+=1;}
}
return ct;
}
The problem with your code, as stated by Pardeep in his comment, is that you have an extra } after your ct+=1; in your second while loop.
The correct code would be: Fiddle
i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
function ctnumber(array, elem) {
var ct = 0;
var j = 0;
while (j < array.length) {
j++;
if (array[j] == elem) {
ct += 1; // NOTE NO } HERE NOW
}
}
return ct;
}
alert(ctnumber(ranList, 5));
I also suggest a bit of a code cleanup:
var i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random());
}
function countNumbers(list, elem) {
var count = 0;
// For loops are generally more readable for looping through existing lists
for (var i = 0; i < list.length; i++) {
if (list[i] == elem) {
count++;
}
}
return count;
}
alert(countNumber(ranList, 5));
Please note that console.log() is a much better debugging tool, it can be accessed by F12 in Firefox and Chrome/IE.