const calculate = (s) => {
let code;
let index;
let startIndex;
let stackSign = [];
let result = [0];
let numberSign = 1;
for (var i = 0; i < s.length; i++) {
if (s[i] === ' ') {
continue;
} else if (s[i] === '(') {
stackSign.push(numberSign);
result.push(0);
numberSign = 1;
} else if (s[i] === ')') {
result[result.length - 2] += result.pop() * stackSign.pop();
} else if (s[i] === '+') {
numberSign = 1;
} else if (s[i] === '-') {
numberSign = -1;
} else if (s[i] === '/') {
numberSign = result / 1;
} else if (s[i] === '*') {
numberSign = result * 1;
} else {
startIndex = i;
while (
(index = i + 1) < s.length &&
(code = s[index].charCodeAt()) > 47 &&
code < 58
) {
i++;
}
result[result.length - 1] +=
+s.substring(startIndex, i + 1) * numberSign;
}
}
return result.pop();
};
Hello guys i made this algorithm to create a calculator without javascript "eval" but im struggling to add the * and / operators, can you guys help me with that? thanks
How i'm using it:
calculate('50 + 50');
Related
Its works well when converting to string except binary with prefix 0.
My code:
function dec2bin(dec) {
return dec.toString(2);
}
function getRndInteger(min, max) {
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
const min = 1;
const max = 2147483647;
const nilai = dec2bin(getRndInteger(min, max));
function solution(N) {
**const nilaiArr = Array.from(String(N), Number);**
let temporer = 0;
let save = \[\];
for (let i = 0; i \< nilaiArr.length - 1; i++) {
if (nilaiArr\[i\] == 1 && nilaiArr\[i + 1\] == 0) {
for (let j = i + 1; nilaiArr\[j\] == 0; j++) {
temporer++;
if (nilaiArr\[j + 1\] == 1) {
save.push(temporer);
temporer = 0;
} else if (nilaiArr\[j + 1\] == undefined) {
break;
}
}
} else {
continue;
}
}
if (save.length === 0) {
console.log(0);
} else {
save.sort();
save.reverse();
console.log(save\[0\]);
}
}
solution(nilai);
Problem sample : 010000010001 became 1073745921.
Expected output same as origin binary number. I cant find the answer as long as I scroll in this forum lol. I
function calculateBinary(bits) {
var bitValue = 0;
for(var i=0; i<bits.length; i++) {
if(bits[0] === '1') {
bitValue += 128;
} else if (bits[1] === '1') {
bitValue += 64;
} else if (bits[2] === '1') {
bitValue += 32;
} else if (bits[3] === '1') {
bitValue += 16;
} else if (bits[4] === '1') {
bitValue += 8;
} else if (bits[5] === '1') {
bitValue += 4;
} else if (bits[6] === '1') {
bitValue += 2;
} else if (bits[7] === '1') {
bitValue += 1;
}
}
return bitValue;
}
calculateBinary('11111111');
// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Why is my for loop treating every iteration of the bits string as bits[0]? The returned value is '1028' or 12 * 8. What am I doing wrong to cause this in my For loop?
Consider
for(var i=0; i<bits.length; i++) {
if(bits[0] === '1') {
bitValue += 128;
} else if
You aren't checking the index inside the loop - you're always checking bits[0], and then if that condition doesn't succeed, you're going onto bits[1], etc, without regard to the index.
Remove the loop.
function calculateBinary(bits) {
var bitValue = 0;
if (bits[0] === '1') {
bitValue += 128;
}
if (bits[1] === '1') {
bitValue += 64;
}
if (bits[2] === '1') {
bitValue += 32;
}
if (bits[3] === '1') {
bitValue += 16;
}
if (bits[4] === '1') {
bitValue += 8;
}
if (bits[5] === '1') {
bitValue += 4;
}
if (bits[6] === '1') {
bitValue += 2;
}
if (bits[7] === '1') {
bitValue += 1;
}
return bitValue;
}
console.log(calculateBinary('11111111'));
// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Or use the index inside the loop to calculate the amount to add.
function calculateBinary(bits) {
return [...bits].reverse().reduce(
(a, bit, i) => bit === '0' ? a : a + 2 ** i,
0
);
}
console.log(calculateBinary('11111111'));
console.log(calculateBinary('1000'));
(or, even better, don't reinvent the wheel)
hey I have been trying this problem from the past few hours. i just can't get 10 random test cases right out of 100
it would be great if anyone would help me out
problem - https://www.codewars.com/kata/59604925a68b04598e00001e/train/javascript
ps there might be better way to solve the problem I just went with whatever came up in my mind.
code-
function conquerIsland(map) {
let path=[];
let mar=[];
let len=0,len1=0;
for(let i=1;i<8;i++)
{
for( let j=0;j<i;j++)
{
if(map[j][i]=='u')
{
if(len1===0 || len1==i+j)
{
path.push([j,i]);
len1=i+j;
}
}
if(map[i][j]=='u')
{
if(len1===0 || len1==i+j)
{
path.push([i,j]);
len1=i+j;
}
}
if(map[j][i]=='m')
{
if(len==0 || len==i+j)
{
mar.push([j,i]);
len=i+i;
}
}
if(map[i][j]=='m')
{
if(len==0 || len==i+j){
mar.push([i,j]);
len=i+j;
}
}
}
if(map[i][i]=='m')
{
if(len==0 || len==i+i)
{
mar.push([i,i]);
len=i+i;
}
}
if(map[i][i]=='u')
{
if(len1==0 || len1==i+i)
{
path.push([i,i]);
len1=i*2;
}
}
}
if(path.length>0)
{
if(path.length==1)
{ let path1;
path1 = [].concat.apply([], path);
return path1;
}
else
{
path.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
return path;
}
}
else
if(mar!=[])
{
if(mar.length==1)
{ let mar1;
mar1 = [].concat.apply([], mar);
return mar1;
}
else
{
mar.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
return mar;
}
}
else {
return [];
}
}
Please refer to the following code (hopefully the comments are enough, if you're still confused feel free to ask):
function conquerIsland(map) {
// a list of all the us
var us = [];
// a list of all the ms
var ms = [];
// our position
var pos;
for (var i = 0; i < map.length; i ++) {
for (var j = 0; j < map.length; j ++) {
if (map[i][j] == "u") {
// found a u: push to us
us.push([i, j]);
} else if (map[i][j] == "m") {
// found an m: push to ms
ms.push([i, j]);
} else if (map[i][j] == "p") {
// found ourselves: update our position
pos = [i, j];
}
}
}
// figure out which array to search from
var search;
if (us.length > 0) {
search = us;
} else if (ms.length > 0) {
search = ms;
} else {
// no us or ms, return empty array
return [];
}
var mindist = Infinity;
var coords = [];
for (var i = 0; i < search.length; i ++) {
// manhattan distance since no diagonals
var dist = search[i][0] - pos[0] + search[i][1] - pos[1];
if (dist == mindist) {
// multiple things tied for shortest distance
coords.push(search[i]);
} else if (dist < mindist) {
// new shortest distance, reset array
mindist = dist;
coords = [search[i]];
}
}
if (coords.length == 1) {
return coords[0];
}
return coords.sort(function(a, b) {
// this basically accomplishes the sort they want
for (var i = 0; i <= 1; i ++) {
if (a[i] > b[i]) {
return -1;
}
if (b[i] > a[i]) {
return 1;
}
}
return 0;
});
}
I have created a functioning maze with arrow movement and coins to collect, however I'm breaking the game when trying to display a message that comes up once the user has collected all 6 rewards.
I have tried to copy someone's alert from github and apply it as best as I think I can to my work but it just breaks the canvas and nothing actually appears in the browser.
My code is below:
character = {
x: 6,
y: 4
}
var el = document.getElementById('game');
function drawWorld() {
el.innerHTML = '';
for (var y = 0; y < map.length; y = y + 1) {
for (var x = 0; x < map[y].length; x = x + 1) {
if (map[y][x] === 1) {
el.innerHTML += "<div class='borders'></div>";
} else if (map[y][x] === 2) {
el.innerHTML += "<div class='reward'></div>";
} else if (map[y][x] === 3) {
el.innerHTML += "<div class='ground'></div>";
} else if (map[y][x] === 5) {
el.innerHTML += "<div class='character'></div>";
}
}
el.innerHTML += "<br>";
}
winGame();
}
function winGame() {
if (!map[5].includes(2))
alert("Well done!");
}
drawWorld();
document.onkeydown = function(event) {
if (event.keyCode === 37) {
if (map[character.y][character.x - 1] !== 1) {
map[character.y][character.x] = 3;
character.x = character.x - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 38) {
if (map[character.y - 1][character.x] !== 1) {
map[character.y][character.x] = 3;
character.y = character.y - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 39) {
if (map[character.y][character.x + 1] !== 1) {
map[character.y][character.x] = 3;
character.x = character.x + 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 40) {
if (map[character.y + 1][character.x] !== 1) {
map[character.y][character.x] = 3;
character.y = character.y + 1;
map[character.y][character.x] = 5;
drawWorld();
}
}
console.log(map)
}
I get my password spec from an API which then I split the object into the needed fields and check that I have the required number of lower, upper, special and length of my password.
function isStrong(passwordChecker) {
if (!passwordChecker) {
return false;
}
debugger;
var securityOption = JSON.parse(localStorage.getItem("Security"));
var MinLength = securityOption.PasswordMinRequiredLength;
var SpecialChars = securityOption.PasswordMinRequiredNonalphanumericCharacters;
var MinLowercase = securityOption.PasswordMinRequiredLowercase;
var MinUppercase = securityOption.PasswordMinRequiredUppercase;
//LenghtCheck
if (passwordChecker.length < MinLength);
return false;
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
if (MinLowercase > 0) {
if (!CountLowerCase(passwordChecker) > MinLowercase) {
return false;
}
}
if (MinUppercase > 0) {
if (!CountUpperCase(passwordChecker) > MinLowercase) {
return false;
}
}
}
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
function MinLowercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 97 && text[i] <= 122) {
Count++;
}
}
}
function MinUppercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 65 && text[i] <= 90) {
Count++;
}
}
}
Now what I want to do is, check the different conditions as a whole and if all of the conditions are true then change the class to green..
$(pageId + ' #password').bind('keyup', function () {
var currentpassword = $(pageId + ' #password').val();
if (isStrong(currentpassword)) {
$(pageId + ' #password').addClass('green');
} else {
$(pageId + ' #password').addClass('red');
}
});
I am not sure how to check the conditions as a whole and return an overall true because as I start trying in my password it instantly changes to green as in my password spec you do not need any UpperCase or LowerCase letters so on any input of a char it returns true..
You should refactor your functions so that they accept both the string and the parameter and return true or false. For example:
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
Should instead be:
function CountSpecialChars(text, min) {
var count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
count++;
}
}
return count > min;
}
return CountSpecialChars(passwordChecker, SpecialChars);
Also, as a bonus, you could also avoid that for loop for those functions by using replace, like so:
function MinChars(text, min) {
return text.length > min;
}
function MinUppercase(text, min) {
var non_uppers = /[^A-Z]/g;
var uppers = text.replace(non_uppers, text);
return uppers.length > min;
}
function MinLowercase(text, min) {
var non_lowers = /[^a-z]/g;
var lowers = text.replace(non_lowers, text);
return lowers.length > min;
}
function MinSpecialChars(text, min) {
var non_specials = /[^!-\?]/g;
var specials = text.replace(non_specials, text);
return specials.length > min;
}
Now with those functions, you can have:
if !MinChars(pw, MinLength) return false;
if !MinSpecialChars(pw, SpecialChars) return false;
if !MinLowercase(pw, MinLowercase) return false;
if !MinUppercase(pw, MinUppercase) return false;
return true;