How To Reverse an Algorithm [closed] - javascript

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.

Related

Print smallest name with javascript [closed]

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);

javascript - if else not resulting in expected comparision [closed]

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.

Random Non Repeating Number Generation Assignment to Variables [closed]

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];

Improving performance while iterating two nested loops [closed]

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 7 years ago.
Improve this question
I calculate a "Top-5-List" of Birthplaces organized in an array of objects in this form
var myObjArr =[
{
"birth":
{
"year": 2012,
"name": "Manchester, Vermont, USA",
}
} , (and so on)
];
My approach however does not seem to be much performant:
for (var i = 0; i < myObjArr.length; i++) {
var alreadyListed = -1;
for (var j = 0; j < resultData.length; j++) {
if(resultData[j].key == myObjArr[i]['birth']['name']) { // birthname already in resultData
alreadyListed = j;
break;
}
}
if(alreadyListed != -1 ) { // birthname already in resultData -> raise count
resultData[alreadyListed].count += 1;
}else { // birthname not yet in resultData -> add to resultData
resultData.push({key: myObjArr[i]['birth']['name'], count: 1 });
}
}
}
Neiter javascript's forEach nor angulars angular.forEach seem to improve the performance. Any Suggestions?
You can use an object as a dictionary instead of using an array and looking for a key by iterating, this way the second "loop" is done by the Javascript implementation when looking for object keys (also it's probably not a linear scan but an hash table lookup):
var result = {};
myObjArr.forEach(function(obj) {
var key = "!" + obj.birth.name;
result[key] = 1 + (result[key] || 0);
});
I'm always adding a "!" in front of the key when using objects as dictionaries because all Javascript objects do have an inherited constructor property and I don't want to interfer with that.
The (x || 0) trick is to start with a 0 when a name has not seen before (undefined is falsy in Javascript). Adding 1 to undefined instead results in NaN.
If you really need an array as result the code is only slightly more complex:
var result = [];
var index = {};
myObjArr.forEach(function(obj) {
var key = "!" + obj.birth.name;
var ix = index[key];
if (ix === undefined) {
// Allocate a new entry
index[key] = result.length;
result.push({key:key, count:1});
} else {
result[ix].count += 1;
}
});

Using a Javascript switch statement, how can I count the number of elements (numbers only) in an array? [closed]

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 count the number of elements (numbers only) in an array using a switch statement in the function. I honestly don't know exactly what this code would look like. But this is what I have so far
<script language="JavaScript">
//an array of numbers
var number = [1,"o",2,3,"a",0];
//a switch statement
switch (number) {
//Not sure what would go here....
break;
}
//display result of count
alert(count)
</SCRIPT>
using a switch statement
if you insist:
var count = 0;
for( var i=0 ; i<number.length ; ++i )
switch( typeof(number[i]) ) {
case "number": ++count; break;
}
count has value 4.
Note: NaN, Number.NEGATIVE_INFINITY, and Number.POSITIVE_INFINITY are also "number"s, so if you don't want to count these then do
var count = 0;
for( var i=0 ; i<number.length ; ++i )
switch( typeof number[i] ) {
case "number":
if( !isNaN(number[i]) && isFinite(number[i]) )
++count;
}
I think the current answers are not very compact.
Here is my take, using .reduce:
var number = [1,"o",2,3,"a",0];
var count = number.reduce(function(accum,cur){
return accum+(typeof cur === "number");
});
Here is a take using the required switch
var number = [1,"o",2,3,"a",0];
var count = number.reduce(function(accum,cur){
return accum+(typeof cur === "number");
switch(true){} // this switch's name is Alfred, after Batman's butler
});
var a = [1,"o",2,3,"a",0];
var nums = 0;
for(var i = 0;i<a.length;i++){
if(typeof a[i] == "number") nums++;
}
alert(nums);
Edit: Okay! A switch! Let's do it!
var count = 0;
for(var i = number.length; i--;){
switch(true){
case typeof number[i] == 'number':
count++;
}
}
alert(count);

Categories