Sorting a series of Tickets [closed] - javascript

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

Related

Becoming More OO Multiple For Loops JS [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 6 years ago.
Improve this question
I have been wanting to become more OO. I develop a little in NetSuite and their APIs are in JS. I have the code below. Here is what is does.
1) search APIs does search on all transactions that are on the water.
2) Loops through all of the transactions and then searches for everyone of these transactions it does another search on them. The reason is because NetSuite's API governance only allows a 1000 lines with search APIs (this can be worked around other ways as well). Also want to do it this way because will be working in other logic that will make this way necessary.
3) Then pushes these values, item, quantity, created from record into three arrays.
4) The last loop loops through the three arrays, but then prints out the item and the created from transaction the number of times of the quantity value. This is because we are going to print these as labels for each item.
Now have been wanting to become more OO. I did another thing similar where I looped through object with keys and values. Thought that was neat. My question is how would you make this more OO. I have some ideas on what I would do but would like to hear some ideas.
1) Create some functions that will call step 3 and step 4. So each time it looped it called functions
2) I would like to do something with callbacks or promises. Might not be the use for them in this scenario, but
3) Push the items into an object then run forEach method on those objects.
So the question is how to make this more OO style with JavaScript.
// search APIs
filters = [];
filters[0] = new nlobjSearchFilter('location', null, 'anyof', ['23','25','20','24']);
filters[1] = new nlobjSearchFilter('mainline', null, 'is', 'true');
var columns = [];
columns[0] = new nlobjSearchColumn('tranid');
columns[1] = new nlobjSearchColumn('createdfrom');
var searchResults =[];
var searchResults = nlapiSearchRecord('itemreceipt', null, filters, columns);
tranId = [];
createdFrom = [];
quantity = [];
item = [];
data = '';
if(searchResults){
for (var i = 0; i < 5; i++){
// gets all internal IDs
var tranId = searchResults[i].getValue(columns[0]);
filtersLine = [];
filtersLine[0] = new nlobjSearchFilter('tranid', null, 'is', tranId);
filtersLine[1] = new nlobjSearchFilter('mainline', null, 'is', 'false');
var columnsLine = [];
columnsLine[0] = new nlobjSearchColumn('item');
columnsLine[1] = new nlobjSearchColumn('createdfrom');
columnsLine[2] = new nlobjSearchColumn('quantity');
var searchResultsLine =[];
var searchResultsLine = nlapiSearchRecord('itemreceipt', null, filtersLine, columnsLine);
for (var j = 0; j < searchResultsLine.length; j++){
item.push(searchResultsLine[j].getText(columnsLine[0]));
createdFrom.push(searchResultsLine[j].getText(columnsLine[1]));
quantity.push(searchResultsLine[j].getValue(columnsLine[2]));
for (var x = 0; x < quantity[j]; x++){
if(createdFrom[j] != 'undefined'){
data += item[j] + createdFrom[j] + '\n';
console.log(item[j] + ' ' + createdFrom[j].substring(16) + '\n');
}
}
}
}
}
You are running a search per each search result, that's gonna take a hit on your governance points. I checked the code and I see no real need to use that many searches. I have refactored the code to use more functions, also I nested the functions, this should make it more readable and scalable. I also added a couple of filters to avoid getting more data than what you need. Anyways, here's the code, you are welcome to optimize it further.
var itemsToProcess = getItemsToProcess();
var data = getDataString(itemsToProcess);
//**** HELPER FUNCTIONS ****//
function getItemsToProcess(){
// search APIs
var filters = [];
filters.push(new nlobjSearchFilter('location', null, 'anyof', ['23','25','20','24']));
filters.push(new nlobjSearchFilter('createdfrom', null, 'isnotempty'));
filters.push(new nlobjSearchFilter('quantity', null, 'greaterthan', 0)); //Filtering out items with no quantity
filters.push(new nlobjSearchFilter('mainline', null, 'is', 'F')); //Dont want to get any extra info
filters.push(new nlobjSearchFilter('shipping', null, 'is', 'F')); //Dont want to get any extra info
filters.push(new nlobjSearchFilter('cogs', null, 'is', 'F')); //Dont want to get any extra info
filters.push(new nlobjSearchFilter('taxline', null, 'is', 'F')); //Dont want to get any extra info
var columns = [];
columns.push(new nlobjSearchColumn('item'));
columns.push(new nlobjSearchColumn('createdfrom'));
columns.push(new nlobjSearchColumn('quantity'));
var searchResults = fullSearch('itemreceipt', filters, columns);
var rows = [];
for(var i in searchResults){
var result = {};
result.item = searchResults[i].getText(columnsLine[0]);
result.createdFrom = searchResults[i].getText(columnsLine[1]);
result.quantity = searchResults[i].getValue(columnsLine[2]);
rows.push(result);
}
return rows;
//**** HELPER FUNCTIONS ****//
function fullSearch(type, filters, columns){
var search = nlapiCreateSearch(type, filters, columns);
var resultset = search.runSearch();
var resultsets = [];
var returnSearchResults = [];
var searchid = 0;
var startdate, enddate, resultslice;
/* Grabs results first */
do {
resultslice = getResultSlice(resultset, searchid);
for (var rs in resultslice) {
returnSearchResults.push(resultslice[rs]);
searchid++;
}
} while (resultslice.length == 1000);
return returnSearchResults;
//*********** HELPER FUNCTION ***********/
function getResultSlice(resultset, searchid){
var resultslice = resultset.getResults(searchid, searchid + 1000);
return resultslice || [];
}
}
}
function getDataString(itemsToProcess){
var data = '';
for(var i in itemsToProcess){
data += printItem(itemsToProcess[i].item, itemsToProcess[i].createdFrom, itemsToProcess[i].quantity);
}
return data;
//**** HELPER FUNCTIONS ****//
function printItem(item, createdFrom, quantity){
var tempString = '';
for (var x = 0; x < quantity; x++){
console.log(item + ' ' + createdFrom.substring(16));
tempString += item + createdFrom + '\n';
}
return tempString;
}
}

insert a string at a specific position [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 6 years ago.
Improve this question
i have an array and i want to insert "ZZ" if the current array value(string) contains "ata", the code should replace at the end of "ata" word.
var duplicatesArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"
];
var uniqueArray = duplicatesArray.filter(function(elem, pos) {
return duplicatesArray.indexOf(elem) == pos;
});
for (var i = 0; i < uniqueArray.length; i++) {
var st = uniqueArray[i];
if((st.endsWith("mak")==false) && (st.endsWith("mek")== false) && (st.length>3))
{
var b = "ata";
var insert = "ZZ";
var position = st.indexOf("b");
st = st.slice(0, position) + insert + st.slice(position);
document.writeln(st);
document.write("<br>");
}
}
I may need to edit this answer later once some details have been clarified, but it seems like you should use the .map() method on your uniqueArray.
This code will walk through each word in the list and either let it unchanged or apply the replacement if all conditions are fulfilled.
// using a shorter, already deduplicated list for sake of clarity
var uniqueArray = [
"abıca","gelmek","ata","atabeg","at","eri","yir","atalar","tutmak"
];
var result = uniqueArray.map(function(word) {
return (
!word.endsWith("mak") &&
!word.endsWith("mek") &&
word.length > 3 ?
word.replace(/ata/, "ataZZ") : word
);
});
console.log(result);
I am right or wrong? :)
var initialArray = ["abıca","abrık","apşak","abbak","abu","aparma","apalisına","appak","aparmadutı","apşak","apışık","apşak","apışıklık","apışık","apalak","apılamak","apul","apul","apulamak","aparmak","at","arkasına","gelmek","ata","atabeg","at","eri","at","ağaç","at","oğlanı","at","akdarıcı","at","otayıcı","at","uşağı","at","oğlanı","at","oynağı","at","bırakmak","at","boynuna","düşmek","at","boynuna","düşmek","at","cıvlandurmak","at","çapmak","at","çapmak","at","depretmek","at","depmek","atı","doldurmak","at","segirtmek","ateş","evi","ateş","göyniigi","atışmak","ateşe","urmak","ateşe","nal","komak","at","şalmak","at","şalmak","at","tonı","at","kaşnısı","at","kaldırmak","at","kulağı","at","koparmals","at","koşmak","at","kulağı","götliği","atlaz","atlandurmak","atlandurmak","atlanmak","atlu","azuğı","atımı","yir","ata","atalar","atıcıduğı","aç","itmek","acıtğan","acıtmak","aç","dirilmek","acır","acırak","acışıklık","acışmak","aç","tutmak"];
var newArray = []
var regexp = /(ata)(.*)?/;
for (var i = 0; i< initialArray.length; i += 1) {
newArray.push(initialArray[i].replace(regexp, "$1ZZ$2"))
}
console.log(newArray)
// ... "gelmek", "ataZZ", "ataZZbeg" ...

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

How To Reverse an Algorithm [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 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.

Categories