*** i am try to this count two string match character ***
var s1 = "abcd";
var s2 = "aad";
function match(s1,s2){
var obj = {}
var spilt1 = s1.split("")
var spilt2 = s2.split("")
for(let i =0;i<spilt1.length;i++){
let th = spilt2.includes(spilt1[i])
if(!obj[th[i]]){
obj[th[i]] = 0
}else{
obj[th[i]]++
}
}
return obj
}
console.log(match(s1,s2))
*** output like this ***
{
a:1,
d:1
}
function match(str1, str2) {
const str1Obj = {};
const resultObj = {};
for (let i = 0; i < str1.length; i++) {
str1Obj[str1[i]] = str1Obj.hasOwnProperty(str1[i])
? str1Obj[str1[i]] + 1
: 1;
}
for (let i = 0; i < str2.length; i++) {
if (str1Obj.hasOwnProperty(str2[i]) && str1Obj[str2[i]] >= 1) {
resultObj[str2[i]] = resultObj.hasOwnProperty(str2[i])
? resultObj[str2[i]] + 1
: 1;
str1Obj[str2[i]] -= 1;
}
}
return resultObj;
}
Related
I am trying to create a bingo game.
It's an assignment that was given to us. I wrote all the functions I need however the "main" function which runs the entire thing, it has a loop which doesn't stop.
I don't seem to know what makes it infinite since I gave a condition for it to stop at the end.
The code is a bit long. I hope you can help me out.
var gNums = []
var gPlayers = [
{
name: 'player1',
hitCounts: 0,
board: creatBingoBoard()
},
{
name: 'player2',
hitCounts: 0,
board: creatBingoBoard()
}
]
// var check=gPlayers[0].board[0][0].isHit = true
// console.table(printBingoBoard(gPlayers[0].board))
// console.table(printBingoBoard(gPlayers[1].board))
// var check = gPlayers[0].board[0][0].isHit = true
playBingo()
// console.table(gPlayers[0].board)
function playBingo() {
// debugger
resetNums()
var isVictory = false
while (!isVictory) {
// console.log('still running!')
var calledNum = drawNum(gNums)
// console.log(calledNum)
for (var i = 0; !isVictory && i < gPlayers.length; i++) {
var player = gPlayers[i]
markBoard(player, calledNum)
isVictory = checkBingo(player)
}
}
}
function creatBingoBoard() {
resetNums()
var board = [];
const SIZE = 5;
for (var i = 0; i < SIZE; i++) {
board[i] = [];
for (var j = 0; j < SIZE; j++) {
board[i][j] = {
value: getRandomIntInclusive(0, 25),
isHit: false
}
}
}
return board;
}
function printBingoBoard(board) {
var bingoBoardCopy = []
var size = board.length
for (var i = 0; i < size; i++) {
bingoBoardCopy[i] = []
for (var j = 0; j < size; j++) {
if (board[i][j].isHit === true) {
bingoBoardCopy[i][j] = board[i][j].value + 'v'
} else bingoBoardCopy[i][j] = board[i][j].value
}
}
return bingoBoardCopy
}
function resetNums() {
gNums = []
for (var i = 0; i < 25; i++) {
gNums.push(i)
}
return gNums
}
function drawNum(nums) {
var index = getRandomIntInclusive(0, nums.length);
var num = nums[index];
nums.splice(index, 1);
return num;
}
function markBoard(player, calledNum) {
for (var i = 0; i < player.board.length; i++) {
for (var j = 0; j < player.board.length; j++) {
var cell = player.board[i][j]
if (cell === calledNum) {
player.hitCounts++
cell.isHit = true
}
}
}
printBingoBoard(player.board)
}
function checkBingo(player) {
// for (var i = 0; i < player.length; i++) {
// if (player.hitsCount === 25) return true
if (player.hitCounts === 25) {
return true
}
return false;
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
In markBoard, you check the value of player.board[i][j]. That's an object, yet you're comparing it to a number. The numeric value you're after appears to be player.board[i][j].value.
As others have stated in the comments, the best way to approach this type of problem is to use a debugger. Chrome Developer Tools allows you to attach breakpoints and inspect the value of your objects in code. However, logging the values of your variables is also a good debugging tool.
Got it to work!
I tried not to mess with your code too much.
My changes are marked with // <- fix.
Just showing who's the winner :)
You never pushed 25.
Off-by-one.
You were comparing the drawn number with the cell, instead of the cell's value.
var gNums = []
var gPlayers = [
{
name: 'player1',
hitCounts: 0,
board: creatBingoBoard()
},
{
name: 'player2',
hitCounts: 0,
board: creatBingoBoard()
}
]
// var check=gPlayers[0].board[0][0].isHit = true
// console.table(printBingoBoard(gPlayers[0].board))
// console.table(printBingoBoard(gPlayers[1].board))
// var check = gPlayers[0].board[0][0].isHit = true
playBingo()
// console.table(gPlayers[0].board)
function playBingo() {
// debugger
resetNums()
var isVictory = false
let totalNumbersCalled = 0;
while (!isVictory) {
var calledNum = drawNum(gNums)
console.log(++totalNumbersCalled, '->', calledNum);
for (var i = 0; !isVictory && i < gPlayers.length; i++) {
var player = gPlayers[i]
markBoard(player, calledNum)
isVictory = checkBingo(player)
}
}
console.log('Player', i - 1, 'wins!'); // <- fix 1
}
function creatBingoBoard() {
resetNums()
var board = [];
const SIZE = 5;
for (var i = 0; i < SIZE; i++) {
board[i] = [];
for (var j = 0; j < SIZE; j++) {
board[i][j] = {
value: getRandomIntInclusive(0, 25),
isHit: false
}
}
}
return board;
}
function printBingoBoard(board) {
var bingoBoardCopy = []
var size = board.length
for (var i = 0; i < size; i++) {
bingoBoardCopy[i] = []
for (var j = 0; j < size; j++) {
if (board[i][j].isHit === true) {
bingoBoardCopy[i][j] = board[i][j].value + 'v'
} else bingoBoardCopy[i][j] = board[i][j].value
}
}
return bingoBoardCopy
}
function resetNums() {
gNums = []
for (var i = 0; i <= 25; i++) { // <- fix 2
gNums.push(i)
}
return gNums
}
function drawNum(nums) {
var index = getRandomIntInclusive(0, nums.length - 1); // <- fix 3
var num = nums[index];
nums.splice(index, 1);
return num;
;
}
function markBoard(player, calledNum) {
for (var i = 0; i < player.board.length; i++) {
for (var j = 0; j < player.board.length; j++) {
var cell = player.board[i][j]
if (cell.value === calledNum) { // <- fix 4
player.hitCounts++
cell.isHit = true
}
}
}
printBingoBoard(player.board)
}
function checkBingo(player) {
// for (var i = 0; i < player.length; i++) {
// if (player.hitsCount === 25) return true
if (player.hitCounts === 25) {
return true
}
return false;
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
//The maximum is inclusive and the minimum is inclusive
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var gNums = []
var gPlayers = [
{
name: 'player1',
hitCounts: 0,
board: creatBingoBoard()
},
{
name: 'player2',
hitCounts: 0,
board: creatBingoBoard()
}
]
// var check=gPlayers[0].board[0][0].isHit = true
console.table(printBingoBoard(gPlayers[0].board))
console.table(printBingoBoard(gPlayers[1].board))
// var check = gPlayers[0].board[0][0].isHit = true
playBingo()
// console.table(gPlayers[0].board)
function playBingo() {
// debugger
resetNums()
var isVictory = false
while (!isVictory) {
// console.log('still running!')
var calledNum = drawNum();
//<-- Fix 1 for some reason callednum is coming as Undefined
if(calledNum){
// console.log(calledNum)
for (var i = 0; !isVictory && i < gPlayers.length; i++) {
var player = gPlayers[i]
markBoard(player, calledNum)
isVictory = checkBingo(player)
}
}
//<-- Fix 2 I am stopping fo gNums is empty
if(gNums.length == 0) isVictory=true;
}
console.table(printBingoBoard(gPlayers[0].board))
console.table(printBingoBoard(gPlayers[1].board))
}
function creatBingoBoard() {
resetNums()
var board = [];
const SIZE = 5;
for (var i = 0; i < SIZE; i++) {
board[i] = [];
for (var j = 0; j < SIZE; j++) {
board[i][j] = {
value: getRandomIntInclusive(0, 25),
isHit: false
}
}
}
return board;
}
function printBingoBoard(board) {
var bingoBoardCopy = []
var size = board.length
for (var i = 0; i < size; i++) {
bingoBoardCopy[i] = []
for (var j = 0; j < size; j++) {
if (board[i][j].isHit === true) {
bingoBoardCopy[i][j] = board[i][j].value + 'v'
} else bingoBoardCopy[i][j] = board[i][j].value
}
}
return bingoBoardCopy
}
function resetNums() {
gNums = []
for (var i = 0; i < 25; i++) {
gNums.push(i)
}
return gNums
}
function drawNum() {
var index = getRandomIntInclusive(0, gNums.length);
var num = gNums[index];
gNums.splice(index, 1);
return num;
}
function markBoard(player, calledNum) {
for (var i = 0; i < player.board.length; i++) {
for (var j = 0; j < player.board.length; j++) {
var cell = player.board[i][j]
//<-- Fix3 Cell is a object so we need to check with value
if (cell.value === calledNum) {
player.hitCounts++
cell.isHit = true
}
}
}
printBingoBoard(player.board)
}
function checkBingo(player) {
// for (var i = 0; i < player.length; i++) {
// if (player.hitsCount === 25) return true
if (player.hitCounts === 25) {
return true
}
return false;
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
here is the question:
Imagine the String() constructor didn't exist. Create a constructor
function, MyString(), that acts like String() as closely as possible.
You're not allowed to use any built-in string methods or properties,
and remember that String() doesn't exist. You can use this code to
test your constructor:
I created constructor however I have no clue how to re-create split method, how to implement that functionality.
If you could give an idea how to implement split method, I would be grateful
function MyString(str) {
var thisObj = this;
var innerLength = 0;
this.length;
function updateLength() {
innerLength = 0;
for (var i = 0; str[i] != undefined; i++) {
innerLength++;
thisObj[i] = str[i];
}
thisObj.length = innerLength;
}
updateLength();
this.toString = function() {
return str;
}
this.charAt = function(i) {
if (isNaN(parseInt(i))) {
return this[0]
} else {
return this[i]
}
}
this.concat = function(string) {
str += string;
updateLength();
}
this.slice = function(start, end) {
var slicedString = "";
if (start >= 0 && end >= 00) {
for (start; start < end; start++) {
slicedString += str[start];
}
}
return slicedString;
}
this.reverse = function() {
var arr = str.split("");
arr.reverse();
var reversedString = "",
i;
for (i = 0; i < arr.length; i++) {
reversedString += arr[i];
}
return reversedString;
}
}
var ms = new MyString("Hello, I am a string")
console.log(ms.reverse())
You can convert the string to an array and use Array.prototype and RegExp.prototype methods.
this.split = function(re) {
var arr = Array.prototype.slice.call(this.toString());
if (re === "") {
return arr
}
if (re === " ") {
return arr.filter(function(el) {
return /[^\s]/.test(el)
})
}
if (/RegExp/.test(Object.getPrototypeOf(re).constructor)) {
var regexp = re.source;
return arr.filter(function(el) {
return regexp.indexOf(el) === -1
})
}
}
function MyString(str) {
var thisObj = this;
var innerLength = 0;
this.length;
function updateLength() {
innerLength = 0;
for (var i = 0; str[i] != undefined; i++) {
innerLength++;
thisObj[i] = str[i];
}
thisObj.length = innerLength;
}
updateLength();
this.toString = function() {
return str;
}
this.split = function(re) {
var arr = Array.prototype.slice.call(this.toString());
if (re === "") {
return arr
}
if (re === " ") {
return arr.filter(function(el) {
return /[^\s]/.test(el)
})
}
if (/RegExp/.test(Object.getPrototypeOf(re).constructor)) {
var regexp = re.source;
return arr.filter(function(el) {
return regexp.indexOf(el) === -1
})
}
}
this.charAt = function(i) {
if (isNaN(parseInt(i))) {
return this[0]
} else {
return this[i]
}
}
this.concat = function(string) {
str += string;
updateLength();
}
this.slice = function(start, end) {
var slicedString = "";
if (start >= 0 && end >= 00) {
for (start; start < end; start++) {
slicedString += str[start];
}
}
return slicedString;
}
this.reverse = function() {
var arr = str.split("");
arr.reverse();
var reversedString = "",
i;
for (i = 0; i < arr.length; i++) {
reversedString += arr[i];
}
return reversedString;
}
}
var ms = new MyString("Hello, I am a string")
console.log(ms.split(""), ms.split(" "), ms.split(/l/))
Iterate and search:
MyString.prototype.split = function(splitter){
var tmp="", result = [];
for(var i = 0; i < this.length; i++){
for(var offset = 0; offset < this.length && offset < splitter.length;offset++){
if(this[i+offset] !== splitter[offset]) break;
}
if(offset === splitter.length){
result.push( tmp );
tmp="";
i += offset -1;
}else{
tmp+=this[i];
}
}
result.push(tmp);
return result;
};
So now you can do:
new MyString("testtest").split("t") //['','es','','','es','']
In action
I'm having trouble with this "TypeError: Cannot read property 'push' of undefined" when I try to run with node.
I already defined the header and index that need to be pushed to them. Here is the code :
var fs = require("fs");
var sys = require('sys');
var neo4j = require('node-neo4j');
const q = require('q');
const exec = require('child_process').exec;
db = new neo4j('http://neo4j:datasci#localhost:7474');
var neo4jCreateNode = [];
var len;
var lenSub;
var tableName = ["category","customer","lot","minorproduct","part","product","productpart","supplier","transaction"];
var attributeName = [["categoryid","categoryname","description"],
["city","country","customerid","customername","phone","postalcode","streetaddr"],
["lotid","partid"],
["minorproductid","productid"],
["partid","partname","supplierid"],
["categoryid","productid","productname"],
["lotid","minorproductid","partid","productid"],
["city","contactname","country","phone","postalcode","streetaddr","supplierid","suppliername"],
["customerid","minorproductid","productid","transactionid"]];
var data = "";
var char;
var headtrigger = 0;
var headallow = 0;
var counter = 0;
var productID;
var productname;
var tmp = "";
var header = [];
var index = [];
var neoQuery =[];
var countI = 0;
var countJ = 1;
var countK = 0;
var countL = 0;
var path = "/root/datasci/webserver/src/neo4j/Neo4jlog.txt";
fs.writeFile(path, "Hello", function(error) {});
This is the function to push the element to the arrays :
function moveToArray()
{
fs.appendFile(path, "---------------------------------", function(error) {});
console.log("---------------------------------");
var dfd = q.defer();
while(index.length>0){
index.pop();
}
while(header.length>0){
header.pop();
}
headtrigger = 0;
headallow = 0;
fs.appendFile(path, data, function(error) {});
console.log(data);
for (var i = 0; i < data.length; i++)
{
char = data[i];
if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z"))
{
headtrigger = 1;
headallow = 2;
tmp += char;
}
else if (char == " " && headtrigger == 1)
{
//console.log("hello " + i);
header.push(tmp);
tmp = "";
headtrigger = 0;
}
else if (char == "+" && headallow == 2)
break;
else
continue;
}
headtrigger = 0;
headallow = 0;
//var index = new Array(header.length);
for(var l=0;l<header.length;l++)
index.push([]);
for (var j = i; j < data.length; j++)
{
char = data[j];
if (char != "|" && char != "+" && char != "-" && char != "\n")
{
if(data[j] == " " && data[j+1] == " ")
continue;
if(data[j-1] != "|" && data[j+1] != "|")
{
headtrigger = 1;
headallow = 2;
tmp += char;
}
}
else if (char == "|" && headtrigger == 1)
{
index[counter].push(tmp);
//console.log(tmp);
tmp = "";
headtrigger = 0;
counter++;
if(counter == header.length)
counter = 0;
}
else if (char == "+" && headallow == 2)
{
break;
}
}
//console.log(header);
fs.appendFile(path, index, function(error) {});
console.log(index);
dfd.resolve();
return dfd.promise;
}
I really need this to be done but still having this problem. Please help.
index[counter].push(tmp);
Can it be because index[counter] is undefined?
I want to print in the console the result from the function printNewObject(). How I can print with console.log in Javascript the result from the object? In the output I get the result Set {"1", "3", "4"}, but I want to look like a string, like 134.
Here is the code:
window.onload = function(){
inputBox = document.getElementById("myText");
btn = document.getElementById('sub');
inputBox2 = document.getElementById("myText2");
btn2 = document.getElementById('sub2');
btn.addEventListener("click",function(event){
event.preventDefault();
toObject(inputBox.value);
});
btn2.addEventListener("click",function(event){
event.preventDefault();
printNewObject(inputBox.value, inputBox2.value);
});
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
function printNewObject(rv, number) {
var mySet = new Set(rv);
for (var i = 0; i <= rv.length; i++) {
if (rv[i] == number) {
mySet.delete(rv[i]);
}
}
console.log(mySet);
}
}
function printNewObject(rv, number) {
var mySet = new Set(rv);
var st = "";
for (var i = 0; i <= rv.length; i++) {
if (rv[i] == number) {
mySet.delete(rv[i]);
}
}
var array = Array.from(mySet);
for (var i = 0; i < array.length; i++){
st += array[i];
}
console.log(st);
}
I have a for loop like this:
for(var i = 0; i < woord.length; i++) {
if(woord[i] === letter) {
goed = true;
woordContainer.innerHTML[i] = woord[i];
}
}
But the text in the woordContainer doesn't change on the page. I tried logging woord[i] to the console and it show the correct letter.
EDIT:
Let me share the complete code, so you can understand it better:
(it is a hangman game)
var store,
woord,
wrapper,
woordContainer,
letterInput,
gokButton,
pogingen,
pogingenText;
window.onload = function() {
store = new Persist.Store("galgje");
woord = store.get("woord");
pogingen = 10;
wrapper = document.getElementById("wrapper");
woordContainer = document.getElementById("woordContainer");
letterInput = document.getElementById("letterInput");
gokButton = document.getElementById("gokButton");
pogingenText = document.getElementById("pogingenText");
if (!woord) {
document.location.href = "./index.html";
}
for (var i = 0; i < woord.length; i++) {
woordContainer.innerHTML += ".";
}
wrapper.appendChild(woordContainer);
gokButton.onclick = function() {
var letter = letterInput.value.toLowerCase();
var goed = false;
if(letter) {
for(var i = 0; i < woord.length; i++) {
if(woord[i] === letter) {
goed = true;
woordContainer.innerHTML = woord[i];
}
}
if(!goed) {
pogingen--;
if(pogingen === 0) {
document.location.href = "./af.html";
}
pogingenText.innerHTML = "Pogingen: " + pogingen;
}
letterInput.value = "";
}
return false;
}
}
If you want to replace the character int woordContainer.innerHTML at index i, with the one in woord[i], you can do it like this:
if(woord[i] === letter) {
goed = true;
var temp = woordContainer.innerHTML
woordContainer.innerHTML = temp.substr(0, i) + woord[i] + temp.substr(i + woord[i].length);
}