Graphs and adjacency list practice - javascript

Hey guys so I am currently work on a problem involving graphs and adjacency lists but it is not working. This is for self-study only and it is not for school or homework.
I am given this table of values:
| Start name | End name | Example path found by a search |
|------------|----------|-----------------------------------|
| carrie | carrie | carrie (it's the same node) |
| carrie | humza | carrie -> humza |
| carrie | yervand | carrie -> jun -> silla -> yervand |
| ophelia | ursula | ophelia -> travis -> **FAIL** |
| travis | carrie | travis -> ophelia -> **FAIL** |
| ursula | ophelia | ursula -> travis -> ophelia |
| victor | humza | victor -> **FAIL** |
But my code is just not working it is saying that I am not getting this:
from carrie to carrie
from carrie to humza
And I am doing it with breath-first as recommended by them and Idk what the issue is
if (!adjacencyList[startName]) return null;
const queue = [startName];
let visited = new Set();
let currentVertex;
if (adjacencyList[startName] === adjacencyList[endName]) return adjacencyList[startName]
while(queue.length) {
currentVertex = queue.shift();
if (!visited.has(currentVertex)) {
visited.add(currentVertex);
adjacencyList[currentVertex].forEach(neighbor => queue.push(neighbor))
}
}
if (visited.has(endName)) {
return visited;
}
else {
return null
}
}
Idk what the issue is and how to fix it. I thought that by returning the set I would return the path but apparently not.

Related

Dexiejs - Filtering returns single value

My dexiedb structure looks like below.
const db = new Dexie('shipment-execution');
db.version(1).stores({
root: '++id,shipmentid,stopid',
})
My IndexedDB will look like below
| id| shipmentid| stopid|
| 1 | 6000001 | 10 |
| 2 | 6000001 | 20 |
| 3 | 6000001 | 30 |
| 4 | 6000002 | 10 |
| 5 | 6000002 | 20 |
I am trying to get all the data which has shipmentid equal to 6000001. Each time it is returning only one record (the first record ).
db.root.where({shipmentid : '6000001'}).toArray().then((d)=>{
console.log(d);
})
output is only fetching the first record
| id| shipmentid| stopid|
| 1| 6000001 | 10 |
Please let me know, what I am doing wrong.

How to enable eslint cache for create-react-app which takes too long to start?

I've wondered why my project takes too long, I've checked some topics about it, now I think that it maybe is the eslint cache problem in react-scripts.
This is the result of TIMING=1 eslint .
Rule | Time (ms) | Relative
:----------------------------------------|----------:|--------:
react/no-direct-mutation-state | 1818.923 | 24.9%
react/no-typos | 812.661 | 11.1%
react/require-render-return | 765.499 | 10.5%
unused-imports/no-unused-imports | 592.197 | 8.1%
testing-library/await-async-utils | 233.464 | 3.2%
no-whitespace-before-property | 199.900 | 2.7%
testing-library/no-container | 154.535 | 2.1%
testing-library/no-debug | 145.567 | 2.0%
testing-library/no-promise-in-fire-event | 123.937 | 1.7%
testing-library/await-async-query | 120.638 | 1.7%
I wonder why yarn start, won't generate the eslintcahce.
How can I fix this problem?

When does the call stack get set up in Javascript?

In trying to solve the following problem:
Generate all combinations of an array of string.
Ex: Input: ['A', 'T', 'C', 'K']
Output: [
'ATCK', 'ATC', 'ATK',
'AT', 'ACK', 'AC',
'AK', 'A', 'TCK',
'TC', 'TK', 'T',
'CK', 'C', 'K',
''
]
I have the following code:
function getSpellableWords(arr) {
const res = [];
// helper(arr, res, 0, '');
helper(arr, res, 0, []);
return res;
}
function helper(arr, res, i, slate) {
const char = arr[i];
console.log(i, 'i')
if(i === arr.length) {
res.push(slate.join(''));
return;
}
// slate = slate + char;
slate.push(char)
console.log(slate, 'slate')
helper(arr, res, i+1, slate);
slate.pop()
helper(arr, res, i+1, slate);
}
getSpellableWords(['A', 'T', 'C', 'K']);
My questions is:
If I remove the following lines in the code:
helper(arr, res, i+1, slate);
Once i is equal to 5 (which is the array.length), the code will stop after it pushes slate into res. However, if I leave that line in, a call stack is set up and so i will go up from 1->5, then pop out gradually to 4 then 3 then back to 4 and so on. Why does that happen?
Clarification: So I understand that for each recursion call, another i variable is generated. However, I was expecting the second recursion call to also generate i from 1->4 again, but this time instead of incrementing it linearly, there's backtracking going on as well. Why wasn't there backtracking in the first call, and why does the second call generate the rest of the results when the first call only generates the first result?
Each recursive call of helper will indeed add a level on the call stack, so that when a recursive call returns back to its caller, that calling code can continue with its own local execution context.
Each execution of helper has its own execution context, which includes a local variable i which is only visible to that execution context. It only plays a role at that level in the call stack.
Note that the helper code never changes the value of its i variable. It gets initialised with whatever value is passed as third argument when it gets called, and that is the only value it will ever have.
The change to i that you notice is in fact no change. Every different value you see for i is in fact about a different variable that just happens to have the same name.
Here is a little schema on the life of these i variables for when the res variable has length 2 (just to not make it too lengthy!):
helper(arr, res, 0, []); // The initial call
+--------top level helper execution context----+
| i = 0 |
| .... |
| slate.push(char) |
| helper(arr, res, i+1, slate); |
| +---nested helper execution context---+ |
| | i = 1 | |
| | .... | |
| | slate.push(char) | |
| | helper(arr, res, i+1, slate); | |
| | +--deepest exec. context-----+ | |
| | | i = 2 | | |
| | | ... | | |
| | | res.push(slate.join('')); | | |
| | | return; | | |
| | +----------------------------+ | |
| | // i is still 1 | |
| | slate.pop() | |
| | helper(arr, res, i+1, slate); | |
| | +----------------------------+ | |
| | | i = 2 | | |
| | | ... | | |
| | | res.push(slate.join('')); | | |
| | | return; | | |
| | +----------------------------+ | |
| | // i is still 1 | |
| +-------------------------------------+ |
| // i is still 0 |
| slate.pop() |
| helper(arr, res, i+1, slate); |
| +-------------------------------------+ |
| | i = 1 | |
| | .... | |
| | slate.push(char) | |
| | helper(arr, res, i+1, slate); | |
| | +----------------------------+ | |
| | | i = 2 | | |
| | | ... | | |
| | | res.push(slate.join('')); | | |
| | | return; | | |
| | +----------------------------+ | |
| | // i is still 1 | |
| | slate.pop() | |
| | helper(arr, res, i+1, slate); | |
| | +----------------------------+ | |
| | | i = 2 | | |
| | | ... | | |
| | | res.push(slate.join('')); | | |
| | | return; | | |
| | +----------------------------+ | |
| | // i is still 1 | |
| +-------------------------------------+ |
| // i is still 0 |
+----------------------------------------------+
So we see that, in this particular algorithm, the size of the call stack (i.e. the depth of the recursion tree) corresponds exactly to the value of the variable i in the current execution context. When a function returns, the size of the call stack is reduced (i.e. the recursion depth decreased), and so we arrive in a state (popped from the stack) where there is another instance of i that also has a value that matches the now current size of the call stack.
Trincot gave a helpful detailed response on how that function works internally. I'd just like to point out a significant simplification you could write:
const getSpellableWords = ([x, ...xs]) =>
x == undefined
? ['']
: ((ps = getSpellableWords (xs)) => [...ps .map (p => x + p), ...ps]) ()
console .log (
getSpellableWords (['A', 'T', 'C', 'K'])
)
.as-console-wrapper {max-height: 100% !important; top: 0}
Here we note that the words we can make either include the first character or they don't. We can recursively calculate all the words from the remainder and then return the result of combining that array of words with those ones found by prepending the first character to each. And of course our recursion bottoms out if there are no characters left, in which our array returned contains only the empty string.
There is a slight bit of syntactic trickery here, with an IIFE in the recursive branch. We might prefer to use a call helper function, which takes a function and any arguments and calls that function with those arguments. Sometimes that's clearer:
const call = (fn, ...args) => fn (...args)
const getSpellableWords = ([x, ...xs]) =>
x == undefined
? ['']
: call (
(ps) => [...ps .map (p => x + p), ...ps],
getSpellableWords (xs)
)

Get the sibling value of a SQLITE value

I have a SQLite Table:
+---------+-----------+-----------+-----------+
| userID | balance | ledger | lasttopup |
+---------+-----------+-----------+-----------+
| 1 | 90 | 780 | 12/10/18 |
| 2 | 180 | 0 | 4/11/18 |
| 3 | 270 | 12 | 13/10/18 |
| 4 | 360 | 109 | 11/10/18 |
+---------+-----------+-----------+-----------+
And I am accessing the column ledger via:
const conn = new require('better-sqlite3')('../../data/databases/casino.sqlite3');
const balances = conn.prepare(`SELECT * FROM "${msg.guild.id}"`).all().map(e => e.ledger)
And I want to get the userID which pertains to the respective ledger entry.
Visual:
Visualization
And then perform an action on the ledger value.
But I am unsure of how to retrieve the userID.
Any help will we appreciated!
[LIBRARIES]
DiscordJS
better-sqlite3
~Thanks

How to parse data from a mysql tracking db?

I have a working event tracker that writes every event in a mysql table.
Table
id date userid event
5100 2014-03-25 14:18:55 user333 AI
5101 2014-03-25 14:19:02 user333 Click
5102 2014-03-25 14:19:02 user333 Click
...
Thats works so far very good. But now, I want to write a little report tool in node.js
I try to get the values with this SQL Query:
SELECT DATE_FORMAT(date,"%Y%m%d") AS date, event, count(*) AS count FROM databasetest WHERE date>="'+ daystartdate +'" AND date<="'+ dayenddate +'" GROUP BY YEAR(date), MONTH(date), DAY(date), event
Giving me this:
+----------+----------+-------+
| date | event | count |
+----------+----------+-------+
| 20140320 | AI | 6 |
| 20140320 | Click | 2 |
| 20140320 | swipe | 2 |
| 20140321 | Click | 6 |
| 20140321 | error | 5 |
| 20140321 | swipe | 2 |
| 20140321 | touch | 3 |
| 20140322 | AI | 3 |
| 20140322 | Click | 3 |
| 20140322 | error | 1 |
| 20140322 | mapsload | 3 |
| 20140322 | touch | 1 |
| 20140323 | AI | 2 |
| 20140323 | Click | 2 |
| 20140323 | touch | 5 |
| 20140324 | AI | 3 |
| 20140324 | Click | 1 |
| 20140325 | AI | 25 |
| 20140325 | Click | 48 |
| 20140325 | error | 16 |
| 20140325 | mapsload | 7 |
| 20140325 | swipe | 15 |
| 20140325 | touch | 32 |
+----------+----------+-------+
But I need the data in this form:
+----------+----------+-------+-----
| date | Click | AI | ....
+----------+----------+-------+-----
| 20140320 | 0 | 6 |
| 20140321 | 2 | 2 |
| 20140321 | 2 | 5 |
Is this possible with a SQL query or do I need to loop through the results in my javascript code. I tried many possible solution but didnt get it to work.
Thank you.
This is a very common question, keywords to search are "transpose" and "pivot". To save you the trouble, this is something that MySQL is not able to do. SQL Server (a MS product) can do this, though.
You will need to loop through the output and build the result set yourself.
var results = []
data.forEach(function(row, rowidx) {
results[row.date] = results[row.date] || {};
results[row.date][row.event] = results[row.date][row.event] || 0;
results[row.date][row.event] += row.count;
});

Categories

Resources