I was wondering if someone could help me understand what I am doing wrong? Below I have posted the assignment question, my code, and then the result I am getting.
Assignment
Here is my code:
function parseScores(scoresString) {
// TODO: Compete the function
let inString = scoresString.split();
return inString;
}
function buildDistributionArray(scoresArray) {
// TODO: Compete the function
let x = 0;
let distributeArray = new Array(5);
distributeArray[0] = 0;
distributeArray1 = 0;
distributeArray2 = 0;
distributeArray3 = 0;
distributeArray[4] = 0;
for(i = 0; i < scoresArray.length; i++){
if(scoresArray[i] >= 90){
distributeArray[0]++;
}
else if(scoresArray[i] >= 80 && scoresArray[i] <= 89){
distributeArray[1]++;
}
else if (scoresArray[i] >= 70 && scoresArray[i] <= 79) {
distributeArray[2]++;
}
else if(scoresArray[i] >= 60 && scoresArray[i] <= 69){
distributeArray[3]++;
}
else if(scoresArray[i] <= 59 && scoresArray[i] >= 0) {
distributeArray[4]++;
}
return distributeArray;
}
}
function setTableContent(userInput) {
// TODO: Compete the function
let myTable = document.getElementById("distributionTable");
if(userInput.length > 0) {
let parsedScores = parseScores(userInput);
let buildArray = buildDistributionArray(parsedScores);
let row = myTable.insertRow(0);
let row2 = myTable.insertRow(1);
let row3 = myTable.insertRow(2);
let cell1 = row2.insertCell(0);
let cell2 = row2.insertCell(1);
let cell3 = row2.insertCell(2);
let cell4 = row2.insertCell(3);
let cell5 = row2.insertCell(4);
cell1.innerHTML = "A";
cell2.innerHTML = "B";
cell3.innerHTML = "C";
cell4.innerHTML = "D";
cell5.innerHTML = "F";
let graphValueArray = [];
let occuranceArray = [];
for(index = 0; index < 5; index++){
occuranceArray[index] = row3.insertCell(index);
occuranceArray[index].innerHTML = buildArray[index];
graphValueArray[index] = row.insertCell(index);
let styleClass = "bar" + index;
let heightValue = (buildArray[index] * 10) + "px";
graphValueArray[index].innerHTML = "<div style = 'height" + heightValue + "class = " + styleClass + "></div>";
}
}
else {
let emptyRow = myTable.insertRow(0);
let emptyCell = emptyRow.insertCell(0);
emptyCell.innerHTML = "No graph to display";
}
}
// The argument can be changed for testing purposes
setTableContent("45 78 98 83 86 99 90 59");
my results:
Result
Here is my HTML
HTML
The problem is where you do .split(). You have to split it on space, so .split(' ')
Another tip, you don't need to include the upper limit in the if statements. The previous if statement takes care of it.
See if this works:
function parseScores(scoresString) {
// TODO: Complete the function
let inString = scoresString.split(' ');
return inString;
}
function buildDistributionArray(scoresArray) {
// TODO: Compete the function
let x = 0;
let distributeArray = new Array();
distributeArray[0] = 0;
distributeArray[1] = 0;
distributeArray[2] = 0;
distributeArray[3] = 0;
distributeArray[4] = 0;
for(i = 0; i < scoresArray.length; i++){
if (scoresArray[i] >= 90){
distributeArray[0]++;
}
else if (scoresArray[i] >= 80){
distributeArray[1]++;
}
else if (scoresArray[i] >= 70) {
distributeArray[2]++;
}
else if(scoresArray[i] >= 60){
distributeArray[3]++;
}
else if(scoresArray[i] <= 59 && scoresArray[i] >= 0) {
distributeArray[4]++;
}
return distributeArray;
}
}
function setTableContent(userInput) {
// TODO: Compete the function
let myTable = document.getElementById("distributionTable");
if(userInput.length > 0) {
let parsedScores = parseScores(userInput);
let buildArray = buildDistributionArray(parsedScores);
let row = myTable.insertRow(0);
let row2 = myTable.insertRow(1);
let row3 = myTable.insertRow(2);
let cell1 = row2.insertCell(0);
let cell2 = row2.insertCell(1);
let cell3 = row2.insertCell(2);
let cell4 = row2.insertCell(3);
let cell5 = row2.insertCell(4);
cell1.innerHTML = "A";
cell2.innerHTML = "B";
cell3.innerHTML = "C";
cell4.innerHTML = "D";
cell5.innerHTML = "F";
let graphValueArray = [];
let occuranceArray = [];
for(index = 0; index < 5; index++){
occuranceArray[index] = row3.insertCell(index);
occuranceArray[index].innerHTML = buildArray[index];
graphValueArray[index] = row.insertCell(index);
let styleClass = "bar" + index;
let heightValue = (buildArray[index] * 10) + "px";
graphValueArray[index].innerHTML = "<div style = 'height" + heightValue + "class = " + styleClass + "></div>";
}
}
else {
let emptyRow = myTable.insertRow(0);
let emptyCell = emptyRow.insertCell(0);
emptyCell.innerHTML = "No graph to display";
}
}
// The argument can be changed for testing purposes
setTableContent("45 78 98 83 86 99 90 59");
I am trying to make a real time chat system. I am sending messages and saving them to the database. But before saving the message into database i need to encrypt it with using NTRU for Integers algorithm. In order to use this algorithm i have to convert text into numbers. I already tried to convert to ASCII code but its creating too big number for algorithm. Is there any way to convert text into small numbers? Saving into database with parent.send_message(chat_input.value)
create_chat(){
var parent = this;
var title_container = document.getElementById('title_container')
var title = document.getElementById('title')
title_container.classList.add('chat_title_container')
title.classList.add('chat_title')
var chat_container = document.createElement('div')
chat_container.setAttribute('id', 'chat_container')
var chat_inner_container = document.createElement('div')
chat_inner_container.setAttribute('id', 'chat_inner_container')
var chat_content_container = document.createElement('div')
chat_content_container.setAttribute('id', 'chat_content_container')
var chat_input_container = document.createElement('div')
chat_input_container.setAttribute('id', 'chat_input_container')
var chat_input_send = document.createElement('button')
chat_input_send.setAttribute('id', 'chat_input_send')
chat_input_send.setAttribute('disabled', true)
chat_input_send.innerHTML = `<i class="far fa-paper-plane"></i>`
var chat_input = document.createElement('input')
chat_input.setAttribute('id', 'chat_input')
chat_input.setAttribute('maxlength', 11)
chat_input.placeholder = `${parent.get_name()}. Say hello..`
chat_input.onkeyup = function(){
if(chat_input.value.length > 0){
chat_input_send.removeAttribute('disabled')
chat_input_send.classList.add('enabled')
chat_input_send.onclick = function(){
chat_input_send.setAttribute('disabled', true)
chat_input_send.classList.remove('enabled')
if(chat_input.value.length <= 0){
return
}
parent.create_load('chat_content_container')
chat_input.value = chat_input.value.toLocaleUpperCase()
parent.send_message(chat_input.value)
chat_input.value = ''
chat_input.focus()
}
I was able to solve my problem with this code
// Vocabulary
let vocabulary = new Array();{
vocabulary[10] = "A";
vocabulary[11] = "B";
vocabulary[12] = "C";
vocabulary[13] = "D";
vocabulary[14] = "E";
vocabulary[15] = "F";
vocabulary[16] = "G";
vocabulary[17] = "H";
vocabulary[18] = "I";
vocabulary[19] = "J";
vocabulary[20] = "K";
vocabulary[21] = "L";
vocabulary[22] = "M";
vocabulary[23] = "N";
vocabulary[24] = "O";
vocabulary[25] = "P";
vocabulary[26] = "Q";
vocabulary[27] = "R";
vocabulary[28] = "S";
vocabulary[29] = "T";
vocabulary[30] = "U";
vocabulary[31] = "V";
vocabulary[32] = "W";
vocabulary[33] = "X";
vocabulary[34] = "Y";
vocabulary[35] = "Z";
vocabulary[36] = " ";
vocabulary[37] = "a";
vocabulary[38] = "b";
vocabulary[39] = "c";
vocabulary[40] = "d";
vocabulary[41] = "e";
vocabulary[42] = "f";
vocabulary[43] = "g";
vocabulary[44] = "h";
vocabulary[45] = "i";
vocabulary[46] = "j";
vocabulary[47] = "k";
vocabulary[48] = "l";
vocabulary[49] = "m";
vocabulary[50] = "n";
vocabulary[51] = "o";
vocabulary[52] = "p";
vocabulary[53] = "q";
vocabulary[54] = "r";
vocabulary[55] = "s";
vocabulary[56] = "t";
vocabulary[57] = "u";
vocabulary[58] = "v";
vocabulary[59] = "w";
vocabulary[60] = "x";
vocabulary[61] = "y";
vocabulary[62] = "z";
vocabulary[63] = "!";
}
// Converting Text into numbers
var number = "";
for(var z = 0 ; z < chat_input.value.length ; z++)
{
for(var i = 10 ; i < 64 ; i++) {
if(chat_input.value.charAt(z) == vocabulary[i]) {
var test = i;
test = test.toString();
number = number + test;
}
}
}
// Seperating numbers into array
var numbers = new Array() ;
var index = 0 ;
while(number.length !== 0) {
if (number.length == 3) {
numbers[index] = number.substring(0, 3);
number = number.substring(3,number.length);
} else if (number.length == 2) {
numbers[index] = number.substring(0, 2);
number = number.substring(2,number.length);
} else if (number.length == 1) {
numbers[index] = number.substring(0, 1);
number = number.substring(1,number.length);
} else
numbers[index] = number.substring(0, 4);
number = number.substring(4,number.length);
index++;
}
//Encrpyting numbers and getting cipher text
var indexofe = 0 ;
var ciphertextz = new Array();
while(indexofe !== numbers.length) {
ciphertextz[indexofe] = parent.Encrypt(numbers[indexofe]);
indexofe++;
}
I am attempting to create a Tic Tac Toe game using Javascript as part of my learning on FreeCodeCamp and after my 5th attempt still haven't managed to get it to work. I think i'm doing the correct thing, but the computer AI is still making very stupid decisions and loosing.
Here is my entire AI function, which can be called using a console log to see the recommended move from the AI. However when i hard code values for moves already taken and ask for the next move, it doesn't pick what i would expect.
/*
Attempt to inplement a Tic Tac Toe minimax game
5th attempt, so hopefully this time it works!
*/
var util = require("util");
//These are all the winning square sequences, as string to make various things easier
var validRows = [
['00','01','02'], // left column
['10','11','12'], // middle column
['20','21','22'], // right column
['00','10','20'], // top row
['01','11','21'], // middle row
['02','12','22'], // bottom row
['00','11','22'], // Diag TL to BR
['20','11','02'] // Diag BL to TR
];
//Our scoring arrays for evaulating moves
var max1 = ['100','010','001'];
var min1 = ['200','020','002'];
var max2 = ['110','011'];
var min2 = ['220','022'];
var max3 = ['111'];
var min3 = ['222'];
//All the valid squares
var validSquaresFactory = ['00','10','20','01','11','21','02','12','22'];
//Store all the moves somewhere
//var computerMoves = ['10','22'];
//var userMoves = ['00','02'];
//Store all the moves somewhere
var computerMoves = ['11','22'];
var userMoves = ['00','01'];
function Board(minOrMax,computerMoves,userMoves){
this.computer = computerMoves;
this.user = userMoves;
this.minOrMax = minOrMax;
this.remaining = this.genRemaining();
this.complete = this.genComplete();
var results = this.getScore();
this.score = results[0];
this.winOrLoose = results[1];
}
Board.prototype.genRemaining = function(){
//Create an array of all moves taken
var takenMoves = this.computer.concat(this.user);
//Calculate all remaining squares
var validSquares = validSquaresFactory.filter(function(object){
return takenMoves.indexOf(object) === -1;
});
return validSquares;
}
Board.prototype.genComplete = function(){
return ((this.computer.length + this.user.length) === 9);
}
Board.prototype.flipMinOrMax = function(){
return (this.minOrMax === 'max') ? 'min' : 'max'
}
Board.prototype.genArrays = function(minOrMax,square){
var tempUser = this.user.slice(0);
var tempComputer = this.computer.slice(0);
if(minOrMax === 'min'){
tempUser.push(square);
} else {
tempComputer.push(square);
}
return [tempComputer,tempUser];
}
Board.prototype.generateBoards = function(minOrMax){
var boards = [];
var that = this;
this.remaining.forEach(function(remainingSquare){
var moves = that.genArrays(minOrMax,remainingSquare);
boards.push(new Board(minOrMax,moves[0],moves[1]));
})
//console.log(boards);
return boards;
}
Board.prototype.getScore = function(){
var that = this;
var winOrLoose = false;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
winOrLoose = true;
finalScore = 100;
} else if(min3.indexOf(score) != -1){
winOrLoose = false;
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
return storage+score;
})
return [condensedReturnScore,winOrLoose];
}
function generateMove(){
var board = new Board('max',computerMoves,userMoves);
var scores = [];
var boards = board.generateBoards('max');
boards.forEach(function(board){
scores.push(testMove(board,4));
});
scores = scores.map(function(score,index){
return [board.remaining[index],score];
});
var returnValue = scores.reduce(function(storage,score){
return (score[1].score > storage[1].score) ? score : storage;
});
return [returnValue[0],returnValue[1].score];
}
function testMove(masterBoard,count){
count --;
var boards = [];
boards = masterBoard.generateBoards(generateMinOrMax(masterBoard.minOrMax));
//console.log('/////////Master Board/////////');
//console.log(masterBoard);
//console.log(boards);
//console.log('//////////////////////////////');
boards = boards.map(function (move) {
if (move.complete === true || count === 0 || move.winOrLoose === true){
return move;
} else {
var returnScore = testMove(move,count);
return returnScore;
}
});
returnBoard = boards.reduce(function(storage,board,index,array){
if(board.minOrMax === 'max'){
return (board.score > storage.score) ? board : storage;
} else {
return (board.score < storage.score) ? board : storage;
}
});
return returnBoard;
}
function generateMinOrMax(minOrMax){
return (minOrMax === 'max') ? 'min' : 'max'
}
I've checked the scoring function and from what i can see it is returning the expected score for any move i try, but because of the shear number of possibilities calculated it's very hard to debug efficiently.
Any help/pointers on this would be most appreciated as i have really hit a brick wall with this, can't see the forrest for the trees e.t.c
If you would like to test this with the GUI, it's on codepen at - http://codepen.io/gazzer82/pen/yYZmvJ?editors=001
So after banging my head against this for day, as soon as i posted this i found the issues. Firstly using the wrong variable for minormax in my reduce function, so it wasn't flipping correctly and not setting the winOrLoose value correctly for a score of -100. Here is the corrected version.
*
Attempt to inplement a Tic Tac Toe minimax game
5th attempt, so hopefully this time it works!
*/
var util = require("util");
//These are all the winning square sequences, as string to make various things easier
var validRows = [
['00','01','02'], // left column
['10','11','12'], // middle column
['20','21','22'], // right column
['00','10','20'], // top row
['01','11','21'], // middle row
['02','12','22'], // bottom row
['00','11','22'], // Diag TL to BR
['20','11','02'] // Diag BL to TR
];
//Our scoring arrays for evaulating moves
var max1 = ['100','010','001'];
var min1 = ['200','020','002'];
var max2 = ['110','011'];
var min2 = ['220','022'];
var max3 = ['111'];
var min3 = ['222'];
//All the valid squares
var validSquaresFactory = ['00','10','20','01','11','21','02','12','22'];
//Store all the moves somewhere
//var computerMoves = ['10','22'];
//var userMoves = ['00','02'];
//Store all the moves somewhere
var computerMoves = ['00','20','01'];
var userMoves = ['10','11','02'];
//01,21,22 - 01//
function Board(minOrMax,computerMoves,userMoves){
this.computer = computerMoves;
this.user = userMoves;
this.minOrMax = minOrMax;
this.remaining = this.genRemaining();
this.complete = this.genComplete();
var results = this.getScore();
this.score = results[0];
this.winOrLoose = results[1];
}
Board.prototype.genRemaining = function(){
//Create an array of all moves taken
var takenMoves = this.computer.concat(this.user);
//Calculate all remaining squares
var validSquares = validSquaresFactory.filter(function(object){
return takenMoves.indexOf(object) === -1;
});
return validSquares;
}
Board.prototype.genComplete = function(){
return ((this.computer.length + this.user.length) === 9);
}
Board.prototype.flipMinOrMax = function(){
return (this.minOrMax === 'max') ? 'min' : 'max'
}
Board.prototype.genArrays = function(minOrMax,square){
var tempUser = this.user.slice(0);
var tempComputer = this.computer.slice(0);
if(minOrMax === 'min'){
tempUser.push(square);
} else {
tempComputer.push(square);
}
return [tempComputer,tempUser];
}
Board.prototype.generateBoards = function(minOrMax){
var boards = [];
var that = this;
this.remaining.forEach(function(remainingSquare){
var moves = that.genArrays(minOrMax,remainingSquare);
boards.push(new Board(minOrMax,moves[0],moves[1]));
})
//console.log(boards);
return boards;
}
Board.prototype.getScore = function(){
var that = this;
var winOrLoose = false;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
winOrLoose = true;
finalScore = 100;
} else if(min3.indexOf(score) != -1){
winOrLoose = true;
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
return storage+score;
})
return [condensedReturnScore,winOrLoose];
}
function generateMove() {
var board = new Board('max', computerMoves, userMoves);
if (board.remaining.length === 1) {
return [board.remaining[0], 0];
} else {
var scores = [];
var boards = board.generateBoards('max');
boards.forEach(function (board) {
scores.push(testMove(board, 4));
});
scores = scores.map(function (score, index) {
return [board.remaining[index], score];
});
var returnValue = scores.reduce(function (storage, score) {
return (score[1].score > storage[1].score) ? score : storage;
});
return [returnValue[0], returnValue[1].score];
}
}
function testMove(masterBoard,count){
count --;
var boards = [];
boards = masterBoard.generateBoards(generateMinOrMax(masterBoard.minOrMax));
boards = boards.map(function (move) {
if (move.complete === true || count <= 0 || move.winOrLoose === true){
return move;
} else {
var returnScore = testMove(move,count);
return returnScore;
}
});
returnBoard = boards.reduce(function(storage,board,index,array){
if(generateMinOrMax(masterBoard.minOrMax) === 'max'){
return (board.score > storage.score) ? board : storage;
} else {
return (board.score < storage.score) ? board : storage;
}
});
return returnBoard;
}
function generateMinOrMax(minOrMax){
return (minOrMax === 'max') ? 'min' : 'max'
}
function getScore(user,computer,minOrMax){
var that = this;
that.computer = computer;
that.user = user;
that.minOrMax = minOrMax;
var returnScore = validRows.reduce(function(storage,row,index,array){
var score = row.reduce(function(storage1,square){
if (that.computer.indexOf(square) !== -1) {
storage1 += '1';
} else if (that.user.indexOf(square) !== -1) {
storage1 += '2';
} else {
storage1 += '0';
}
return storage1;
},'')
var finalScore = 0;
if(max1.indexOf(score) != -1){
finalScore = 1;
} else if(min1.indexOf(score) != -1){
finalScore = -1;
} else if(max2.indexOf(score) != -1){
finalScore = 10;
} else if(min2.indexOf(score) != -1){
finalScore = -10;
} else if(max3.indexOf(score) != -1){
finalScore = 100;
} else if(min3.indexOf(score) != -1){
finalScore = -100;
}
storage.push(finalScore);
return storage;
},[])
var condensedReturnScore = returnScore.reduce(function(storage,score){
if(that.minOrMax === 'max'){
return (score >= storage) ? score : storage;
} else {
return (score <= storage) ? score : storage;
}
})
return condensedReturnScore;
}
I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}