LeetCode keeps throwing runtime errors - javascript

I'm solving a problem at leetcode, view it from here if you want but it isn't that important. The solution I followed to solve this problem was to reverse two arrays and then convert them to numbers, add them and finally convert them back to an array and reverse them one more time, the solution seems to work fine when I run it on my computer but on leetcode it throws a runtime error.
Here us the code I used
var addTwoNumbers = function(l1, l2) {
var tempL1 =[]
var tempL2 =[]
for (var i = l1.length -1; i >= 0; i--) {
tempL1.push(l1[i])
}
for (var i = l2.length -1; i >= 0; i--) {
tempL2.push(l2[i])
}
var result = Number(tempL1.join("")) + Number(tempL2.join(""))
var array = Array.from(result.toString())
var finalArray = []
for (let i = array.length -1; i >= 0; i--) {
finalArray.push(array[i])
}
return finalArray
};
That's the error thrown in my face
Line 34 in solution.js
throw new TypeError(__serialize__(ret) + " is not valid value for the expected return type ListNode");
^
TypeError: ["0"] is not valid value for the expected return type ListNode
Line 34: Char 20 in solution.js (Object.<anonymous>)
Line 16: Char 8 in runner.js (Object.runner)
Line 18: Char 26 in solution.js (Object.<anonymous>)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47

Related

Hangman case insensesetive

we are in our 3 week of our Bootcamp.
Project is to code the Hangman game, it is running in the terminal.
We got preety far in just 2 days I think.
We are now stucked on the case insensesetivity, meaning if the word we are looking for is Java that if you type j or J, you still would get the same result J_ _ _.
I looked all over the Internet and found the locale.compare method which isn´t working for me. If i type a wrong letter everything is fine but if I type a right one I get a error and also it doesn´t ignore the case of the letter.
We are not using functions yet because we haven´t learned how they work.
const constants = require('./constants');
// In node.js: install a prompt library by running: `npm install prompt-sync` in the current folder
const prompt = require("prompt-sync")();
// Here you see an example how to get your
// constants from constants.js
/*for(let figure of constants.HANGMAN_PICS)
{
console.log(figure);
}
*/
let Answer = [];
var Words = constants.WORDS_TO_GUESS[Math.floor(Math.random() * constants.WORDS_TO_GUESS.length)];
/*console.log(Words.length); //Wortlänge von random Word
*/
for (let i = 0; i < Words.length; i++) {
Answer[i] = "_";
}
console.log(Answer.join(" "));
for (; Answer !== Words;) {
input = prompt(`Finde das Wort.`);
if (Words.includes(input)) {
for (let i = 0; i < Words.length; i++) {
if (Words[i] === input) {
Answer[i] = input;
}
}
console.log(Answer.join(" "));
console.log(Answer.localeCompare(Words, {
sensitivity: `base`
}));
} else if (!Words.includes(input)) {
console.log("Falsche Eingabe - keep trying!");
console.log(Answer.join(" "))
}
}
// how to use the prompt - e.g.:
// const name = prompt('What is your name?');
my way of doing this (which may not be the best) is setting both strings to lower case and comparing them with includes() function.
The for loop afterwards will just collect right position/s that you want to show up after right guess.
const word = 'JavaScript'
const char = 's' //input
const indexes = [] //output
//https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
//includes() function
if(word.toLowerCase().includes(char.toLowerCase())){
//if you need to get the index/es of the latter/s
for (let i = 0; i < word.toLowerCase().length; i++) {
if (word.toLowerCase()[i] === char.toLowerCase()) {
indexes.push(i)
}
}
}
console.log(indexes)
Make sure that Words (which should be word, singular and not capitalized) is in lower case (or upper case) by doing .toLocaleLowerCase() (or .toLocaleUpperCase()) at the end of where you assign it:
var Words = constants.WORDS_TO_GUESS[Math.floor(Math.random() * constants.WORDS_TO_GUESS.length)].toLocaleLowerCase();
// >>> −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^
Then make sure input is lower case (or upper case):
input = prompt(`Finde das Wort.`).toLocaleLowerCase();
At that point, you'll be comparing j and j (or J and J), so you'll find a match.
If you don't want to consistently use one capitalization in your code, it's possible to do it differently, but more complicated.
Basically, you do the .toLocaleLowerCase() (or .toLocaleUpperCase()) everywhere you do a comparison:
for (; Answer !== Words;) {
input = prompt(`Finde das Wort.`).toLocaleLowerCase();
// Get the input in lower case −−−−−−^^^^^^^^^^^^^^^^^^^^
if (Words.toLocaleLowerCase().includes(input)) {
// ^^^^^^^^^^^^^^^^^^^^−−− make Words lower case for the includes call
for (let i = 0; i < Words.length; i++) {
if (Words[i].toLocaleLowerCase() === input) {
// ^^^^^^^^^^^^^^^^^^^^−− make Words[i] lower case for the ===
Answer[i] = Words[i];
// ^^^^^^^^−−− use the one from Words, not the user's input
}
}
// ...
}
}

Converting a JavaScript snippet to C#

I am trying to convert the following JS snippet into C#, but am having a hard time understanding the implicit types being used.
initHuffman = function(size) {
this.huffmanTree = [];
var code = 0;
for (var d = 0; d < (size * 2); d++) {
var count = this.getBits(size);
for (var v = 0; v < count; v++) {
var node = this.huffmanTree;
for (var d1 = d; d1 !== 0; d1--) {
var c = (code >> d1) & 1;
if (!node[c]) node[c] = [];
node = node[c];
if (isNumber(node)) return;
}
node[code & 1] = this.getBits(size);
code++;
}
code <<= 1;
}
}
This is a function to decode a string of bits into a Huffman tree. The issue I am having is with the node object. node is of type any[], and references huffmanTree which is of type any[].
The first confusing part is if (!node[c]) node[c] = []; It seems the code is checking if an index exists in node, and if it doesn't, add an empty array?
The second confusing part is node[code & 1] = this.getBits(size); The getBits() function simply reads a few bits, in this case 4, and returns them as an int. So, it seems node can be indexed with ints and with arrays?
How would I accomplish this in C#? What collection or array type could do this?
Running this through the debugger in FireFox gives the following result:
0: 0
1: [...]
0: 1
1: [...]
0: 2
1: [...]
0: 3
1: 4
I am clearly not understanding what is happening here. Any help would be appreciated.

Issue with iteration "Uncaught Error: coordinates is required"

I am using mapbox and turf.js to allow users to draw a polygon on the map and then in return get the perimeter distance. I am able to get it to do the function I want and I am receiving/displaying the correct measurements, but now I get "Uncaught Error: coordinates is required". I think that it is where I am trying to create a variable to iterate through the coordinates (var to and var from), but I haven't found a solution to fix it.
function measurements(e) {
var data = draw.getAll();
var answer = document.getElementById('calculated-perimeter');
if (data.features.length > 0) {
var coordinates = data.features[0].geometry.coordinates[0];
var calc_distances = []
var i;
for (i = 0; i<coordinates.length; i++){
var from = turf.point(coordinates[i]);
var to = turf.point(coordinates[i+1]);
var options = {units: 'kilometers'};
var distance = turf.distance(from, to ,options);
calc_distances.push(distance);
console.log(calc_distances);
var perimeter = calc_distances.reduce((a, b) => a + b, 0);
var strg_per = perimeter.toString();
var strg_per = Math.round(strg_per * 1000)
answer.innerHTML ='<p><strong>' + strg_per + '</strong></p><p>meters</p>';}
} else {
answer.innerHTML = '';
if (e.type !== 'draw.delete')
alert('Use the draw tools to draw a polygon!');
}
}
-------------------------------
EDIT : here is the full stack trace:
turf.min.js:1 Uncaught Error: coordinates is required
at Object.r [as point] (turf.min.js:1)
at r.measurements ((index):173)
at r.zt.fire (evented.js:119)
at r.i.fire (setup.js:52)
at q.Jt.onStop (draw_polygon.js:81)
at Object.stop (object_to_mode.js:57)
at Object.stop (mode_handler.js:57)
at Object.c [as changeMode] (events.js:169)
at q.changeMode (mode_interface_accessors.js:151)
at q.Jt.onKeyUp (draw_polygon.js:66)
The combination of these two lines looks wrong:
for (i = 0; i<coordinates.length; i++){
...
var to = turf.point(coordinates[i+1]);`
You will be calling turf.point(undefined).
Probably that first line should be:
for (i = 0; i<coordinates.length - 1; i++){

Unexpected behaviour of glob-fs glob.readdirSync

I have the following nodejs code. The client first calls /api/demosounds then call /api/testsounds.
var glob = require('glob-fs')({ gitignore: true });
app.get('/api/demosounds',function(req,res){
var demosounds = []
var demosoundlist = glob.readdirSync('src/assets/demosounds/*.wav');
demosounds = demosounds.concat(demosoundlist)
for (var i = 0; i < demosounds.length; i++) {
demosounds[i] = demosounds[i].replace("src/assets/","/api/static/")
}
demosounds = demosounds.sort()
res.json(demosounds)
})
app.get('/api/testsounds',function(req,res){
var listofsounds = []
var folderlist = ['01_sinus','02_pulse_train','03_contour_le','04_contour_fel','05_variable','06_complex_le','07_complex_fel']
for (var x = 0; x < folderlist.length; x++){
var testsoundlist = glob.readdirSync('src/assets/' + folderlist[x] +'/*.wav');
listofsounds = listofsounds.concat(testsoundlist)
}
When doing glob.readdirSync('src/assets/01_sinus/*.wav') I would expect to get only path starting with src/assets/01_sinus/ and yet testsoundlist starts as the following:
[ 'src/assets/demosounds/electricity.wav',
'src/assets/demosounds/phone.wav',
'src/assets/demosounds/water.wav',
'src/assets/demosounds/wind.wav',
'src/assets/01_sinus/02_sin1_0065_0.16923076923076924.wav',
'src/assets/01_sinus/04_sin1_0065_0.7692307692307693.wav',
'src/assets/01_sinus/05_sin1_0065_1.0615384615384615.wav',
'src/assets/01_sinus/07_sin1_0165_0.07272727272727272.wav',
I have no idea why this is happening :(
UPDATE
Somewhat closer to the problem, the code below
var glob = require('glob-fs')({ gitignore: true });
var folderlist = ['01_sinus','02_pulse_train','03_contour_le','04_contour_fel','05_variable','06_complex_le','07_complex_fel']
for (var x = 0; x < folderlist.length; x++){
console.log((glob.readdirSync('src/assets/' + folderlist[x] +'/*.wav').length))
}
Outputs this, as if glob would remember the previous globs.
49
98
147
196
245
294
343
The library doesn't seem to be maintained anymore and there is a hanging issue with exactly the same problem, so it seems like this is a bug.
A solution is to simply use glob, glob.sync() in this case.

Javascript - Use Variable as Array Index

Trying to use a variable as an array index. Variable addThirteen simply takes i and adds 13 to it. I need to use that result as the array index. Please see my code:
for (var i = 0; i < alphabetArr.length; i ++) {
var addThirteen = (parseInt(i) + parseInt(13));
var newCipher = new cipher(alphabetArr[i].letter, alphabetArr[addThirteen].letter);
}
This results in:
TypeError: undefined is not an object (evaluating
'alphabetArr[addThirteen].letter')
Appreciate any help.
Try printing out the iteration the for loop is on each time:
console.log(i);
console.log(addThirteen);
What seems to be happening here is that when i is alphabetArr.length-13 it is trying to get a character that is outside the array. As it can't do this it throws up the error saying that the letter is undefined, because it is. A solution to this problem is:
for (var i = 0; i < alphabetArr.length - 13; i ++) {
The result you are getting is really depending on what is the alphabetArr variable.
The following is an example where alphabetArr is just an array of strings.
const alphabetArr = "abcdefghejklmnopqrstuvwxyz".split('');
/* If you want to see what alphabetArr really is, uncomment
* the following line an run. (copy snippet to answer to do it)
* The result will be ["a", "b", "c", ..., "z"].
*/
// console.log(alphabetArr);
/* we will always get undefined here because alphabet[i]
* is not an object having the property letter.
* Instead, it is just a string.
*/
for (var i = 0; i < alphabetArr.length; i++) {
console.log(alphabetArr[i].letter);
}
This example gives only undefined because of alphabetArr[i] not being an object whith the property letter but being a string.
Now we will try to see what happens if alphabetArr is an array of objects each having the property letter
const alphabetArr = "abcdefghijklmnopqrstuvwxyz".split('')
.map(letter => ({letter: letter}));
// console.log(alphabetArr);
// result: [ { letter: "a" } , ... , { letter: "z" } ]
/* Here everything works fine until we reach
* the index 13, where the output is m z
*/
for (var i = 0; i < alphabetArr.length; i++) {
// Note that I am not parsing. It's because it is not necessary.
var addThirteen = i + 13;
console.log(alphabetArr[i].letter, alphabetArr[addThirteen].letter);
}
As you see, now we get something, but still, at a certain point, we get the thrown error. This is because the for loop is looping over the entire array.
So when i is 14, addThirteen will be 27. But the length of the array is 26, so alphabetArr[27] is undefined.
Now that we understood the problem, let us solve it.
const alphabetArr = "abcdefghijklmnopqrstuvwxyz".split('')
.map(letter => ({letter: letter}));
for (var i = 0; i < alphabetArr.length - 13; i++) {
// let's skip the addThirteen variable declaration.
console.log(alphabetArr[i].letter, alphabetArr[i + 13].letter);
}
Yes! The solution is to loop over the array minus thirteen, to avoid out of range indexes.
The final code:
const alphabetArr = "abcdefghijklmnopqrstuvwxyz".split('')
.map(letter => ({letter: letter}));
for (var i = 0; i < alphabetArr.length - 13; i++) {
var newCipher = new cipher(alphabetArr[i].letter, alphabetArr[i + 13].letter);
}

Categories