Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm attempting to generate non repeating random numbers between 1-5, 1-10, 1-20, etc. I'm on to the Fisher-Yates Shuffle but I'm not sure I've implemented it in the best way. My plan is to associate each random number to a predetermined variable name. I want to make sure the syntax is correct for assignment of the random values to predetermined variable names. I'm new to JavaScript and would appreciate any insight. Here's my first rendition:
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var ranNums = shuffle([1,2,3,4,5]);
var ranNum1 = ranNums.value;
var ranNum2 = ranNums.value;
var ranNum3 = ranNums.value;
var ranNum4 = ranNums.value;
var ranNum5 = ranNums.value;
try using following code FIDDLE:
var ranNum1 = ranNums[0];
var ranNum2 = ranNums[1];
var ranNum3 = ranNums[2];
var ranNum4 = ranNums[3];
var ranNum5 = ranNums[4];
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am facing a problem with javascript problem-solving.
I am now trying to print out the smallest name from a named array. But I cannot print out it. It shows the different names. Would you mind helping me, please?
see the codes.
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 0; i < tinyFriend.length; i++) {
var char = tinyFriend[i];
if (char < tiny) {
tiny = char;
}
}
console.log(tiny);
please tell me where to make the correction
Just use the Reduce Method
var tinyFriend = ['hasan' , 'md' , 'mdhasan' , 'zahdhasan'];
var tiny = tinyFriend.reduce(function(a, b) {
return a.length <= b.length ? a : b;
});
console.log(tiny)
use the inbuilt sort method
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend.sort((a, b) => a.length - b.length)[0];
console.log(tiny);
fix for original code
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 0; i < tinyFriend.length; i++) {
var char = tinyFriend[i];
if (char.length < tiny.length) { // use length
tiny = char;
}
}
console.log(tiny);
You can simply use for-of loop here to get the smallest string in an array
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
let smallest;
for (let word of tinyFriend) {
if (smallest !== undefined) smallest = word.length < smallest.length ? word : smallest;
else smallest = word;
}
console.log(smallest);
You are making mistake in these two lines for (var i = 0; i <tinyFriend.length; i++) { & if (char < tiny) {
You have assigned tinyFriend[0]; to tiny so no need to start loop from 0. Instead start from 1. Secondly here if (char < tiny) { you need to check length
Here is my solution. Inside the loop just check if the length of the current name is smaller than the previous, then assign that name to tiny
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 1; i < tinyFriend.length; i++) {
tiny = tiny.length > tinyFriend[i].length ? tinyFriend[i] : tiny;
}
console.log(tiny);
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 4 years ago.
Improve this question
I am new to javascript. I am having a little issue here.
Is javascript if / else statement different than other languages (c++, java, python)?
Here is the issue that I am having.
if else statement only accepts i == 0 and i == 1 into my new array from myArray.
Why am I not be able to separate other elements into my new array? I used myArray for an example. In my real problem, I wouldn't know how many elements I have. That is why I have set up variables threetimes and increaseByThree. I am just trying to separate name, zip code, and amount into the different array by using a for loop.
var nameArray = [], zipCodeArray = [], totalAmountArray = [];
var threeTimes = 3;
var increaseByThree = 0;
var myArray = ["Eric ", "94990", "540", "Sam ", "303030", "350"];
for(var i = 0; i < myArray.length; i++) {
threeTimes += 3;
increaseByThree += 3;
if(i == threeTimes || i == 0) {
nameArray.push(myArray[i]);
} else if(i == increaseByThree || i == 1) {
zipCodeArray.push(myArray[i]);
} else {
totalAmountArray.push(myArray[i]);
}
}
console.log(nameArray)
console.log(zipCodeArray)
console.log(totalAmountArray)
Assuming your array will be in the format [a0, b0, c0, ....., aN, bN, cN] where N is the number of 'entries' - 1; you could simplify your logic that you determine where to put the value by:
const myArray = ["Eric ", "94990", "540", "Sam ", "303030", "350"];
const nameArray = [], zipCodeArray = [], totalAmountArray = [];
for(var i = 0; i < myArray.length; i++) {
switch (i % 3) {
case 0:
nameArray.push(myArray[i]);
break;
case 1:
zipCodeArray.push(myArray[i]);
break;
case 2:
totalAmountArray.push(myArray[i]);
break;
}
}
console.log(nameArray)
console.log(zipCodeArray)
console.log(totalAmountArray)
This will work for any size array and cuts out the need for the unnecessary variables and if-else blocks. Here is a helpful link for javascript's switch block
(https://www.w3schools.com/js/js_switch.asp) which are much cleaner as opposed to if-else blocks and show the intent more clearly in this case.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is the problem statement,
You've a bunch of tickets in a stack with departures and destinations. You're given a departure city and a destination city. How can you find from the stack your route.
This is my solution,
"use strict";
function app(){
var stack = [];
var one = new Ticket('London', 'NYC');
var two = new Ticket('Barcelona', 'Athens');
var three = new Ticket('Rio', 'ND');
var four = new Ticket('NYC', 'Barcelona');
var five = new Ticket('Athens', 'Rio');
var six = new Ticket('ND', "Lahore");
stack.push(one);
stack.push(two);
stack.push(three);
stack.push(four);
stack.push(five);
stack.push(six);
var res = sortDestinations(stack, 'London', 'Lahore');
for(var city in res){
console.out(res[city]);
}
}
function Ticket(departure, destination){
this.departure = departure;
this.destination = destination;
}
Ticket.prototype.getDeparture = function(){
return this.departure;
}
Ticket.prototype.getDestination = function(){
return this.destination;
}
function sortDestinations(stack, dep, dest){
var map = {};
for(var i= 0; i<stack.length; i++){
var ticket = stack.pop();
map[ticket.getDeparture()] = ticket.getDestination();
}
var res = [];
var curr = dep;
res.push(curr);
while(true){
if(curr == dest) {
break;
}
var next = map[curr];
res.push(next);
curr = next;
}
}
app();
This program goes into an infinite loop. When I debug I see that the curr variable is undefined. Can someone help me solve the problem. I'm rank new to Javascript.
I was debugging your code for a while and finally identified the reason for infinite loop.
Since you are pop-ing from stack, length of stack keep decreasing and that of i increasing and the loop stops before completion. And your while loop keep looping since curr is never going to equal to dept because map does not contain London.
Change this
for(var i= 0; i<stack.length; i++){
var ticket = stack.pop();
map[ticket.getDeparture()] = ticket.getDestination();
}
To
while(stack.length>0){
var ticket = stack.pop();
map[ticket.getDeparture()] = ticket.getDestination();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
cut the string from last '/' to '.html'
I have a string like that
"/Views/GS/stockView.html"
My need the name "stockView"
How can I cut the name from a string?
Thanks.
a = "/Views/GS/stockView.html";
a.split('/').pop().split(".")[0];
Demo
use indexOf() and lastIndexOf() method, like
var str = "/Views/GS/stockView.html";
var slashPos = str.lastIndexOf('/');
var dotPos = str.indexOf('.', slashPos + 1);
var result = str.substring(slashPos + 1, dotPos);
Try using RegExp:
var view = function(str) {
return str.match(/\/(\w*)\./)[1];//finds a word between `/` and `.`
};
console.log(view("/Views/GS/stockView.html"));
console.log(view("/Views/fs/inventView.html"));
console.log(view("/Views/fs/p1/showView.jsp"));
console.log(view("/Views/fs/p2/showView123.aspx"));
Open console
Try this
var msg = "/Views/GS/stockView.html";
var startIndex = -1;
var endIndex=-1;
var length = msg.length;
for (var i = length - 1; i >= 0; i--) {
if (msg[i] == '/'){
startIndex=i+1;
break;
}
if(msg[i]==".")
endIndex=i;
}
console.log(msg.substr(startIndex,endIndex-startIndex));
Or try this
var msg = "/Views/GS/stockView.html";
var split=msg.split("/");
split=split[split.length-1].split(".");
console.log(split[0]);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to find a math based way to find a password that makes the if statement in the below code true. I have written some stuff that brutes its way to an answer but that does not help me to understand how to solve this problem mathematically. The actual password I need to make the if statement true is irrelevant and not what I am asking for. I specifically want some code to get me started or even complete code that I can study to show me how to reverse engineer this algorithm to arrive at the answer using JavaScript.
var passed = false;
function checkPass(password) {
var total = 0;
var charlist = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < password.length; i++) {
var countone = password.charAt(i);
var counttwo = (charlist.indexOf(countone));
counttwo++;
total *= 17;
total += counttwo;
}
if (total == 248410397744610) {
passed = true;
alert(password);
}
}
Here's a simple code snippet that will do it:
function invertPass(n) {
var all = 'abcdefghijklmnopqrstuvwxyz',
out = '',
offset;
while (n > 0) {
offset = n % 17;
out = all.charAt(offset - 1) + out;
n = (n - offset) / 17;
}
return out;
}
function createPass(password) {
var total = 0;
var charlist = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < password.length; i++) {
var countone = password.charAt(i);
var counttwo = (charlist.indexOf(countone));
counttwo++;
total *= 17;
total += counttwo;
}
return total;
}
var orig = 'gdclhpdhbied',
num = createPass(orig);
console.log(invertPass(num) === orig);
Take a look at what the function actually does to total depending on its input: It multiplies by 17 and adds the position of the current char in the alphabet.
Therefore your expectedTotal (e.g. 248410397744610) will be a number divisible by 17 plus the alphabet position of the password's last letter. Use % (the modulus operator) to find said position (simply put, the number you need to subtract from expectedTotal to make it divisible by 17), then divide by 17 and repeat.