I’m new here, and so on coding.
I friend of mine suggests me to learn JavaScript and Python, because I love riddles that I can’t solve (so this languages could help me).
Let me explain: I want to create a JS script starting from this real-life problem.
I have a padlock which have a code of three numbers to be unlocked (you have to turn upside down these numbers to obtain the “Open sesame”), the code goes to 000 to 999, obviously.
I need to create a script that lists all the possible numbers and, at the end, also tell me how many different numbers I have (I suppose 1000 if my math isn’t bad as my english).
I started the learning path, but I’m not able to create this script.
I need to check all the different combinations that i have done for unlock the padlock
Can someone help me?
Thank you so much
ps: it could be nice also the same script in bash, which it's more familiar to me
x 0stone0: I have non familarity with JavaScript, I've only done an online course, so I made no attempt, just asking.
For bash, I found right here a "skeleton" of permutation script like this:
for X in {a..z}{a..z}{0..9}{0..9}{0..9}
do echo $X;
done
but I really don't know ho to edit it, cause I don't know hot to save the output of three numbers YYY from 0 to 9
Javascript
let i = 0;
while (i <= 999) {
console.log(String(i).padStart(3, '0'));
i++;
}
Pad a number with leading zeros in JavaScript
Bash
for X in {0..9}{0..9}{0..9}; do
echo $X;
done
Try it online!
Using js, you can do:
let count = 0;
for (let i = 0; i <= 999; i++) {
count++ // count++ is the same as count = count + 1, count is used to count the number of times the loop has run
if (i < 10) { // if i is less than 10 add two zero before it, for it to look like (009)
console.log('00' + i);
} else if (i < 100) { // if i is less than 100 add one zero before it, for it to look like (099)
console.log('0' + i);
} else if (i < 1000) { // if i is less than 1000 add nothing before it, for it to look like (999)
console.log(i);
} else {
console.log(i);
}
}
// then we console.log() the count variable
console.log(`There is ${count} possibilities`);
The program is made to show 3 digits, so if it's 9, it will show 009 and same for 99 => 099
Related
I am trying to get every single combination of elements into an array. Now I can use the method below, and remove the duplicates, but this way is far to slow for my use.
The code below would find every possible combination for 2 digits below 4. Now in the code I actually want to use this for, the least possible code would be 6 for loops (within each other) with the amount being 18 (rememeber this is the minimum).
The code below would execute amount^[amount of for loops], or amount^2 which in this case is 16. That means that in the code I want to use this for, it executes 18^6 times, or 34 million times. And this is the minimum, which would get much higher.
After trying to run my code (with 6 foor loops in which amount = 18), it crashed my browser... My question is: Is there any faster and more efficient (not elegant. I don't care how elegant it is) in which my browser won't crash?
Note: This question is not a duplicate question. All the other questions simply ask for a way to do this, however I already have a way. I am just trying to make it more efficient and faster so that it actually works correctly.
let combinations = [];
let amount = 4;
for (let a = 0; a < amount; a++) {
for (let b = 0; b < amount; b++) {
combinations.push(`${a}${b}`);
}
}
console.log(combinations);
Below is a snippet providing a possible example for how my code would work.
let possibilities = [];
let amount = 6; //Amount is set by me, so don't worry about it being incorrect
for (let a = 0; a < amount; a++) {
for (let b = 0; b < amount; b++) {
possibilities.push(a + b);
}
}
possibilities = [...new Set(possibilities)]; //Removes duplicates
possibilities.sort((a, b) => b - a); //Sorts in descending order
possibilities = possibilities.slice(0, 3); //Gets top 3 values
console.log(possibilities);
Ok, as discussed in the comments, if you need top 3 values for a particular amount, you could just do something simple like below:
let amount = 6;
let highest = amount - 1,second_highest = amount - 2,third_highest = amount - 3;
let possibilities = [
highest + highest,
highest + second_highest,
highest + third_highest
];
console.log(possibilities);
I don't know the any better solution for this, but yes there are some conditions you need to check first.
If(amount <= 0) return 'Invalid amount, Please enter a valid amount"
So if somebody enters a negative or zero value your loop will goes into infinite loop, and make the situation more worst.
if(amount === 1) return '1 possible combination'
As amount less than 1 is 0 only and combinations for 0 is 1 only, you need not to parse whole loop for 6 digits or n digits for 0 so it will get solve in complexity of 1 instead of N(no. of digits).
And for amount greater then 1 you can create manual loops, like here you created 2 loops for 2 digits, you create 6 loops for 6 digits, better create dynamic logic for this to create number of loops automatically.
You need to consider 1111, 1112 this type of combinations as well right?
Or if only 1234, 2134, 2314 this kind of scenarios are required? This can be done in very less complexity.
For duplication you can store combinations as a key value pair. and then Object.Keys will be your combinations.
I am a "new" developer into the foray of Web Development and I have come across an issue I was hoping that you fine people on Stack Overflow would be able to help me with. I have asked several Cadre and Instructors in my class and we are all stumped by it.
To start with I have decided to put all of my code on a Gitlab repo so if you want to look at the whole thing (or if you want to add to it let me know): Link to Github Repo. I fiqured you guys don't want the whole thing posted as a wall of text and rather some snip-its of what in the file I specifically. But it is relitively small file
I am useing simple JavaScript as well as Node.Js to be able to build a working calculator in the back end that I can use as a template for any other project I will need to work on in the future. For now I am trying to just get it working by imputing things via the console.
I have made a way for what is imputed in Node and to an imputArray var I have set up and the Array goes something like this:
[(command), (num1), (num2), (num3), ...]
I set up a switch function that runs a block of code based on what command was given (add, subtract, divide, etc..). As well as separating the command from the number and putting them inside another array.
The part I need some help with is with getting the block of code to work for what I want it to do. I have got it set up to run rather easily on two numbers but I want it to handle as many numbers as I want to throw at it. I tried various forms of for loops as well as forEach loops and I cant seem to get it working.
case 'divide':
for (i = 1; i < numArray.length; i++) { // If any number besides the first is 0 spit out this
if (numArray[i] === 0) {
consol.log("You canot divide by zero!");
}
else {
var previousTotal = numArray[0]; //Inital number in array
for (i = 1; i < numArray.length; i++) {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal // Pushes end total to result
}
break;
I have gone through several different versions of the above code (such as using for loops instead) but this is pretty much what I ended up with. I'm sure there is an easier way and more sane way to do what I am trying to do, but if I knew how I wouldn't be here.
Essentially this is the ideal thing I want to do but I cant find a way to do it: I want to run a small block of code the index of the number array, minus one. In this case it is dividing the previous number by the next number in the array.
So it only runs if there are more then one in the array and it does the function to the previous number, or total from the last one in the array.
This is pretty much the only thing holding me back from finishing this so if someone can take the time to look at my crapy code and help it do what I want it to do that would be awesome.
Your code is reseting result each time the outer loop iterates so it will just equal what ever the last prev Total is. Basically every loop but the last is irrelevant. Do you want to add them to result? If so you want:
result += previousTotal
Or if you want an array of the answers you want:
result.push(reviousTotal)
Sorry not 100% what you want. Hope this helps!
You just need one loop, and you probably want to stop iterating if a 0 occurs:
result = numArray[0]; //no need for another variable
for (var i = 1; i < numArray.length; i++) { // declare variables!
if (numArray[i] === 0) {
console.log("You canot divide by zero!"); // typo...
break; // exit early
}
result = result / numArray[i];
}
For sure that can be also written a bit more elegantly:
const result = numArray.reduce((a, b) => a / b);
if(isNaN(result)) {
console.log("Can't divide by zero!");
} else {
console.log(`Result is ${result}`);
}
I assume you want the divide command to do ((num1/num2)/num3)/...
There are couple of issues in the code you posted, I will post a version that does the above. You can inspect and compare it your version to find your mistakes.
// divide, 10, 2, 5
case 'divide':
if (numArray.length < 2) {
console.log("no numbers in array")
break;
}
// previousTotal starts with 10
var previousTotal = numArray[1];
// start from the second number which is 2
for (i = 2; i < numArray.length; i++) {
if (numArray[i] === 0) {
console.log("You canot divide by zero!");
}
else {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal;
// result will be (10/2)/5 = 1
break;
I'm working on the Project Euler problems (currently question 13).
For this question I have to find the first 10 digits of the sum of 100 numbers all of a size similar to this:
91,942,213,363,574,161,572,522,430,563,301,811,072,406,154,908,250
I think I could use something like Java's BigInteger, but I started solving the problems in JavaScript (I'm trying to boost my js abilities for work), and I would like to continue using it, even to solve this problem.
I'd like to stick to pure JS if possible.
Javascript recently got a new primitive data type BigInt (stage 4 proposal as of January 2020).
https://github.com/tc39/proposal-bigint
Chrome, Firefox and few other browsers have started supporting this in newer versions (check compatibility here), while other browsers are still implementing it.
https://developers.google.com/web/updates/2018/05/bigint
Basically it can be declared using either literals like
var a = 1n;
or
var b = BigInt('22222222222222222222222222222222');
Math operators don't do auto conversion between BigInt and Number, so
1 + 1n
will throw an error.
You are going to need a javascript based BigInteger library. There are many to choose from. Here is one https://github.com/peterolson/BigInteger.js
You can use it like this
var n = bigInt("91942213363574161572522430563301811072406154908250")
.plus("91942213363574161572522430563301811072406154908250");
Surprisingly, sticking all the values in an array and adding them all together and just taking the first 10 digits worked. I must have had a typo somewhere in my code when it didn't work before.
I'm sure that doing something this simple wouldn't work in all cases (like those #AlexMcmillan and #zerkms have been debating about). I think the safest bet is the BigInteger library mentioned by #bhspencer, but it seems like adding the first x significant digits with y digits as a buffer might also be worth a shot in some cases.
I did this using an array and updating all entries with a function.
function f(a) {
for (let i = 0; i < a.length - 1; i++) {
a[i + 1] = a[i + 1] + parseInt(a[i] / 10);
a[i] = a[i] % 10;
}
return a;
}
// remember to init the array with enough elements for all digits
var a = Array(200);
a.fill(0);
a[0] = 1;
Here is a JSFiddle with the code for problem 20.
You could always convert your sum to a string, rip out the . and grab the result - something like this:
var sum = 2384762348723648237462348;
sum = sum.toString(); // "2.3847623487236483e+24"
// Rip out the "."
sum = sum.substr(0, 1) + sum.substr(2);
// Grab the first 10 characters
var firstTen = sum.substr(0, 10);
I am currently doing program 2 for the startup engineering course offered on coursera
I'm programming using and ubuntu instance using Amazon web services and my programming is constantly hanging. There might be something wrong with my node.js program but I can't seem to locate it.
This program is meant to produce the first 100 Fibonacci numbers separated with commas.
#! /usr/bin/env node
//calculation
var fibonacci = function(n){
if(n < 1){return 0;}
else if(n == 1 || n == 2){return 1;}
else if(n > 2){return fibonacci(n - 1) + fibonacci(n-2);}
};
//put in array
var firstkfib = function(k){
var i;
var arr = [];
for(i = 1; i <= k; i++){
arr.push(fibonacci(i));
}
return arr
};
//print
var format = function(arr){
return arr.join(",");
};
var k = 100;
console.log("firstkfib(" + k +")");
console.log(format(firstkfib(k)));
The only output I get is
ubuntu#ip-172-31-30-245:~$ node fib.js
firstkfib(100)
and then the program hangs
I don't know if you are familiar with Time complexity and algorithmic analysis, but, it turns out that your program has an exponential running time. This basically means that, as the input increases, the time it takes to run your program increases exponentially. (If my explanation is not very clear, check this link)
It turns out that this sort of running time is extremely slow. For example, if it takes 1 ms to run your program for k=1, it would take 2^100 ms to run it for k=100. This turns out to be a ridiculously big number.
In any case, as Zhehao points out, the solution is to save the value of fib(n-1) and fib(n-2) (in an array, for example), and reuse it to compute fib(n). Check out this video lecture from MIT (the first 15 mins) on how to do it.
You may want to try printing out the numbers as they are being computed, instead of printing out the entire list at the end. It's possible that the computation is hanging somewhere along the line.
On another note, this is probably the most inefficient way of computing a list of fibonacci numbers. You compute fibonacci(n) and then fibonacci(n+1) without reusing any of the work from the previous computation. You may want to go back and rethink your method. There's a much faster and simpler iterative method.
writing intense computational code in nodeJS leads to blocking. since Fibonacci is an intense computational code so might end up blocking.
For some reason after the user guesses the right number and follows the confirm to play the game again but with fewer guesses (2 less than original), each time a user guesses a number the guesses remaining is deducted by 2 and sometimes just random numbers instead of the usual 1. I tried changing the code to deduct in various different ways but to no avail:
j--;
j -= 1;
j = j - 1;
Full code in Fiddle, if anyone could help that would be awesome I've been at this for hours! Thanks
partial for guess button click event
if (currentGuess < numberToGuess) {
$hintBox.html('<p class="blue">Try higher</p>');
} else {
$hintBox.html('<p class="blue">Go lower</p>');
}
j = j - 1;
$('.numberGuesses').html(j);
} // end of if guess is not correct
else if (currentGuess === numberToGuess) {
alert('Well done the correct number was '+ numberToGuess);
var playAgain = confirm("Let's see if you can do that again with less guesses.");
if (playAgain){
$('#gameDiv').hide('pulsate', 100, function(){
$('#mode').delay(200).show('pulsate', 500);
});
lowerGuesses = lowerGuesses - 2;
$('.numberGuesses').html(lowerGuesses);
} else {
location.reload();
}
}
You don't reset the counter j to lowerGuesses after you get the number right.
The code is very difficult to follow, and IMO a bit broken. Things need to be broken out much better. Isolate the "new game" code into something you call when there's actually a new game. Create a new random number. Clear out the numbers it remembers; after I fixed it it was the same number again (possible but unlikely, so I'm assuming that logic is also broken) so it both warned me that I'd already guess the number, and told me I guessed the number correctly.
Basically your game loop should be just for the game, not for preparing a new game, etc. Consider passing in the number of guesses the player should get into a newGame function (along with many other refactorings).