Two Number Is in between range in array jquery - javascript

I have two array and need to check any duplicate range in this how can achieve that
let arrayfrom = ['1', '6.1', '10', '31','6.2',3];
let arrayto = ['2', '9.9', '30', '401','7',5];
How we can test duplicate range? Here the expected result:
1-2 -valid
6.1 - 9.9 -valid
10 - 30-valid
31 - 401 -valid
6.2 - 7 -invalid (between range 6.1 - 9.9)
3-5 - valid
Help me to find this solution

A loop or two will do. We need to compare all pairs to all others.
let arrayFrom = ['1', '6.1', '10', '31', '6.2', 3];
let arrayTo = ['2', '9.9', '30', '401', '7', 5];
function is_pair_included(a, in_b) {
return (a[0] > in_b[0] && a[1] < in_b[1])
}
var to_remove = [];
for (var i = 0; i < arrayFrom.length - 1; i++) {
for (var j = i + 1; j < arrayFrom.length; j++) {
var pair1 = [+arrayFrom[i], +arrayTo[i]];
var pair2 = [+arrayFrom[j], +arrayTo[j]];
if (is_pair_included(pair1, pair2)) {
to_remove.push(i);
}
if (is_pair_included(pair2, pair1)) {
to_remove.push(j);
}
}
}
to_remove.forEach(function(i) {
var pair1 = [+arrayFrom[i], +arrayTo[i]];
console.log("" + pair1, "invalid");
})

Related

fatal javascript invalid size error 188720663

Can someone help me ?
I tried to make a random team maker but that make team that have the same level based on the list of the students from the best to the worst.
#
# Fatal error in , line 0
# Fatal JavaScript invalid size error 188720663
#
#
#
#FailureMessage Object: 000000BA505FE6A0
1: 00007FF6BF759E7F node_api_throw_syntax_error+175967
2: 00007FF6BF67036F v8::CTypeInfoBuilder<void>::Build+11999
3: 00007FF6C04DD182 V8_Fatal+162
4: 00007FF6C001A265 8::internal::FactoryBase<v8::internal::Factory>::NewFixedArray+101
5: 00007FF6BFE9F8E3 v8::internal::FeedbackNexus::ic_state+65795
6: 00007FF6BFEBE460 v8::Context::GetIsolate+15600
7: 00007FF6BFD0AA40 v8::internal::CompilationCache::IsEnabledScriptAndEval+25952
8: 00007FF6C02178B1 v8::internal::SetupIsolateDelegate::SetupHeap+558193
9: 00007FF640351098
my code look like that
let students = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
const numberPerTeam = 4;
let team1 = ['', '', '', ''];
let index1 = 0;
let team2 = ['', '', '', ''];
let index2 = 0;
let team3 = ['', '', '', ''];
let index3 = 0;
let prevIndex;
const randomFromArray = (array) => {
const index = Math.floor(Math.random() * array.length);
prevIndex = index;
const value = array[index];
array[index] = '';
return value;
};
const randomTeams = () => {
let i = '';
let index;
while (index1 != 4 && index2 != 4 && index3 != 4) {
while (i === '') {
i = randomFromArray(students);
}
team1[index1] = i;
index1++;
index = (prevIndex + students.length / 2) / 2;
team1[index1] = students[index];
index1++;
students[index] = '';
while (i === '') {
i = randomFromArray(students);
team2[team2.length] = i;
index = (prevIndex + students.length / 2) / 2;
team2[team2.length] = students[index];
students[index] = '';
}
while (i === '') {
i = randomFromArray(students);
}
team3[team3.length] = i;
index = (prevIndex + students.length / 2) / 2;
team1[index1] = students[index];
index1++;
students[index] = '';
}
};
randomTeams();
console.log(team1);
console.log(team2);
console.log(team3);
I first though it was a problem with node but when i tried to execute it on a browser, it throws me that error : Uncaught out of memory

Find consecutive item count with condition in JS

I have an array and I want to return the maximum consecutive count of the items which are bigger than 60 from the array. Here, the expected output should be 3. My current implementation is like this:
let arr = ['80', '70', '11', '88', '90', '61'];
function processInput(arr) {
var total = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 60) {
total++;
}
console.log(total);
break;
}
return total;
}
processInput(arr);
I'm not sure if I should use break here or not. Thanks in advance.
Presented below is one possible way to achieve the desired objective.
Code Snippet
const maxConsec = (arr = [], limit = 0) => {
// two variables: max-count, and count, both set to initial 0
let cMax = 0, c = 0;
// iterate thru the array
for (const elt of arr) {
// if elt is above "60" (ie, limit)
if (elt > limit) c++; // increment count
else c = 0; // else, reset count back to 0
// if current count greater than "max-count"
if (c > cMax) cMax = c; // store current count as max
}
// return max-count
return cMax;
};
let arr = ['80', '70', '11', '88', '90', '61'];
const limit = 60;
console.log(
'maximum consecutive array elements above', limit,
'are\n', maxConsec(arr, limit)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added to the snippet above.
EDIT
Adding a generic version based on comments (by 3limin4t0r) below:
// get max consecutive elements matching condition
// by default, condition is to check for "n" greater than 0
const maxConsec = (arr = [], checkCondition = n => n > 0) => {
// two variables: max-count, and count, both set to initial 0
let cMax = 0, c = 0;
// iterate thru the array
for (const elt of arr) {
// if elt matches the condition
if (checkCondition(elt)) c++; // increment count
else c = 0; // else, reset count back to 0
// if current count greater than "max-count"
if (c > cMax) cMax = c; // store current count as max
}
// return max-count
return cMax;
};
let arr = ['80', '70', '11', '88', '90', '61'];
const limit = 60;
console.log(
'maximum consecutive array elements above', limit,
'are\n', maxConsec(arr, n => n > limit)
);
// using the generic version to check for max consecutive
// array elements that are greater than lowercase "k"
console.log(
'max consecutive array elements greater than', "k",
'are\n', maxConsec(
['m', 'n', 'k', 'o', 'r', 'q', 'y'],
el => el > 'k'
)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
This should work
let arr = ['80', '70', '11', '88', '90', '61'];
function processInput(arr) {
let initialValue = 0;
const initialValuesArray = [];
arr.reduce((prev,current) => {
if(current > 60)
{
initialValue += 1;
initialValuesArray.push(+initialValue)
}
else
{
initialValue = 0;
}
}, 0);
const maxValue = Math.max(...initialValuesArray)
return maxValue;
}
const result = processInput(arr);
console.log(result);

How I can make this code work faster? I have a time limit of 6.5 seconds

I need this code to work faster. I'm assuming that the problem could be solved by creating correct key:value pairs in "filedics". I guess that it should look something like this:
word: [{ id: 1, count: 1}, { id: 2, count: 1}];
My code is working good in terms of logic, but when it receiving a lot of strings as an input it can`t handled it.
But maybe there are some other mistakes that I don`t see.
const _reader = _readline.createInterface({
input: process.stdin,
});
const _inputLines = [];
let _curLine = 0;
_reader.on("line", (line) => {
_inputLines.push(line);
});
process.stdin.on("end", solve);
function result(reqs, files, n, m) {
const filedics = files.map(() => ({}));
for (let fi = 0; fi < files.length; ++fi) {
const file = files[fi];
const fdic = filedics[fi];
const usedwords = {};
for (let wf = 0; wf < file.length; ++wf) {
const rword = file[wf];
if (usedwords[rword]) continue;
usedwords[rword] = true;
if (fdic[rword] == null) fdic[rword] = numofword(rword, file);
}
}
let rel = 0;
const relfiles = [];
for (let ri = 0; ri < reqs.length; ++ri) {
for (let fi = 0; fi < filedics.length; ++fi) {
const fdic = filedics[fi];
for (let wi = 0; wi < reqs[ri].length; ++wi) {
const wordReq = reqs[ri][wi];
const usedwords = {};
if (usedwords[wordReq]) continue;
usedwords[wordReq] = true;
if (fdic[wordReq]) {
rel += fdic[wordReq];
}
}
if (rel) relfiles.push([rel, fi + 1]);
rel = 0;
}
const sr = relfiles.sort(([rel1], [rel2]) => rel2 - rel1);
for (let i = 0; i < 5 && i < sr.length; ++i)
process.stdout.write(sr[i][1] + " ");
process.stdout.write("\n");
relfiles.length = 0;
}
}
function numofword(word, file) {
let n = 0;
for (let i = 0; i < file.length; ++i) {
if (word === file[i]) n++;
}
return n;
}
function solve() {
const n = readInt();
const files = arrLines(n);
const m = readInt();
const reqs = arrLines(m);
let res = result(reqs, files, n, m);
}
I have for example 2 arrays with 3 subarrays in each.
INPUT
3
[
[ 'i', 'love', 'coffee' ],
[ 'coffee', 'with', 'milk', 'and', 'sugar' ],
[ 'free', 'tea', 'for', 'everyone' ]
]
3
[
[ 'i', 'like', 'black', 'coffee', 'without', 'milk' ],
[ 'everyone', 'loves', 'new', 'year' ],
[ 'mary', 'likes', 'black', 'coffee', 'without', 'milk' ]
]
Goal is to output subarrays by number that have most matches, in descending order. For example the output for this code should be
1 2
3
2 1
(1) I don't see the reason to maintain separate dictionaries for each file if always all entries are checked against all filedicts and the result is summed up. Instead one could just use one filedict for all files.
(2) numofword is extremely inefficient, as for every word in the file the whole file is scanned again, turning this into an O(n^2) algorithm. Simply traversing the file once and counting up turns that into O(n).
(3) Maps can be slightly better for lots of keys than objects.
(4) I'm not quite sure what arrLines does, but usually one can maximize the throughput by reading and processing data in chunks and processing multiple files in parallel.
const occurences = new Map();
for (const file of files) {
for(const word of file) {
occurences.set(word, (occurences.get(word) ?? 0) + 1);
}
}
for (const seq of seqs) {
let score = 0;
const checked = new Set();
for (const word of seq) {
if (checked.has(word)) continue;
checked.add(word);
score +=occurences.get(word) ?? 0;
}
// collect seqs and sort
}

Sort two inter-related arrays (players and scores) and print results?

I would like to enter 3 players with 3 scores in using 2 arrays.
For now I stuck, concerning the ranking; how to do ???
Small example:
Player 1 : Jeremy
Score Jeremy : 12
Player 2 : Julien
Score Julien : 18
Player 3 : Olivia
Score Olivia : 22
For the ranking we should have
The first => Olivia with 22 scores
The second => Julien with 18 scores
The third => Jeremy with 12 scores
Here is my code.
function main() {
var players = new Array();
var scores = new Array();
for(i = 0; i<3; i++) {
players[i] = prompt("Player " + (i+1) + " : ");
scores[i] = prompt("Score " + (players[i]) + " : ");
}
}
Thank you advance.
Splitting data into two arrays is probably not the easiest way to go, but assuming you have no choice, I would use a custom sorting function and an additional array containing indices related to the other arrays :
main();
function main() {
var players = new Array();
var scores = new Array();
var ranking = new Array();
for (var i = 0; i < 3; i++) {
ranking[i] = i;
players[i] = prompt("Player " + (i + 1) + " : ");
scores[i] = prompt("Score " + (players[i]) + " : ");
}
indirectSort(3, ranking, scores);
for (var i = 0; i < 3; i++) {
var ithPlayer = players[ranking[i]];
var ithScore = scores[ranking[i]];
console.log(ithPlayer, ithScore);
}
}
function indirectSort (n, toBeSorted, toBeCompared) {
for (var i = 0; i < n - 1; i++) {
for (var j = i + 1; j < n; j++) {
var a = toBeCompared[toBeSorted[j]];
var b = toBeCompared[toBeSorted[i]];
if (a < b) {
var min = toBeSorted[j];
toBeSorted[j] = toBeSorted[i];
toBeSorted[i] = min;
}
}
}
}
Here is how the above code works :
players = ["John", "Jack", "Bob"];
scores = [2, 1, 3];
ranking = [0, 1, 2];
indirectSort(3, ranking, scores);
console.log(ranking);
// [1, 0, 2]
console.log(players[ranking[0]]);
// "Jack"
console.log(scores[ranking[0]]);
// 1
This will give you a sorted Players array, where each player has a name and a score
function main()
{
var players = new Array();
for(i = 0; i<3; i++){
let player = {};
player.name = prompt("Player " + (i+1) + " : ");
player.score = prompt("Score " + (players[i]) + " : ");
players[i] = player;
}
players.sort(function(a,b){
if (a.score < b.score)
return -1;
if (a.score> b.score)
return 1;
return 0;
})
console.log(players);
}
You could and should be storing each user as an object in an array like this:
function main(){
var players = [];
for(var i = 0;i<3;i++){
var player = {};
player.name = prompt("Enter user name");
var ranking = prompt("Enter user ranking");
player.ranking = parseInt(ranking);
players.push(player)
}
console.log("Players");
players.forEach(function(player){
console.log(player.name,player.ranking);
});
//Now sort based on ranking
players = players.sort(function(pA,pB){
return pA.ranking - pB.ranking;
});
players.forEach(function(player){
console.log(player.name,player.ranking);
});
}
main();
Try following. I am just using push of array(for adding an object to array). And for sorting you can use sort(for sorting array based on the score) of Array.Prototype. See below code.
var array=[];
function add(){
var x={};
x.name=prompt("Player " + (array.length+1) + " : ");
x.score=parseInt(prompt("Score " + (x.name) + " : "));
array.push(x);
array.sort((a,b)=>a.score<b.score)
console.log(array);
}
<button onclick="add()">add</button>
You should use array of objects instead of separate arrays like:
let data = [
{name: 'Jeremy', score: 12},
{name: 'Julien', score: 18},
{name: 'Olivia', score: 22}
];
You can then sort and print result with .sort():
let data = [
{name: 'Jeremy', score: 12},
{name: 'Julien', score: 18},
{name: 'Olivia', score: 22}
];
data.sort((a, b) => b.score - a.score);
console.log(`The first => ${data[0].name} with ${data[0].score} scores`);
console.log(`The second => ${data[1].name} with ${data[1].score} scores`);
console.log(`The third => ${data[2].name} with ${data[2].score} scores`);
However if for some reasons you want to stick with 2 arrays, you can also transform both arrays in single array of object and print result.
let players = ['Jeremy', 'Julien', 'Olivia'];
let score = [12, 18, 22];
function printResult(p, s) {
let a = p.reduce((a, c, i) => (a.push({name: c, score: s[i]}), a), [])
.sort((a, b) => b.score - a.score);
console.log(`The first => ${a[0].name} with ${a[0].score} scores`);
console.log(`The second => ${a[1].name} with ${a[1].score} scores`);
console.log(`The third => ${a[2].name} with ${a[2].score} scores`);
}
printResult(players, score);
Useful Resources:
Array.prototype.sort()
Template literals

How do I convert numbers into letter form, ex. 3 to three, and then className = three?

I am making a dice roller. This code gives the sum of the dice rolled.
function getSumDiceValue(){
var dice = diceWindowWrapper.getElementsByClassName("dice");
var diceTotal = 0;
for(var i = 0; i < dice.length; i++){
diceTotal += Number(dice[i].getAttribute("data-diceValue"));
};
return diceTotal;
};
I want to set the class name of zero to the value of getSumDiceValue(), but in letters.
That is if I roll a 6 then the value of getSumDiceValue() is equal to 6, and then I want zero.className to equal six. That is:
zero.className = six;
Then I would need to "plug it in" to this code:
var zero = document.createElement("li");
zero.className = <here>;
diceToolbarCounterWrapper.appendChild(zero);
I think I need to make an array of some kind. But I am new to javaScript and not sure how I would go about doing that. Please add code to your answer.
I've previously written a function for converting a integer number in the range
-999 999 999 999 999 ... 999 999 999 999 999 to it's full English name (short scale)
var numberWord = (function () {
var words = [
'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
];
words.length = 99;
var i, j, tens = [
'', '', 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
for (i = 2; i < 10; ++i) {
words[10 * i] = tens[i];
for (j = 1; j < 10; ++j) {
words[10 * i + j] = tens[i] + ' ' + words[j];
}
}
var power = [
{e: 1e2, str: 'hundred', and: false},
{e: 1e3, str: 'thousand', and: false},
{e: 1e6, str: 'million', and: false},
{e: 1e9, str: 'billion', and: false},
{e: 1e12, str: 'trillion', and: false},
];
function strAdd(a, b) {
if (a && b) return a + ' ' + b;
return a || b || '';
}
function strAndAdd(a, b) {
if (a && b) return a + ' and ' + b;
return a || b || '';
}
return function numberWord(x) {
var number = '';
x = Math.floor(x);
if (x !== x) return 'NaN';
if (x === 0) return words[0];
if (x < 0) {
number = strAdd(number, 'minus');
x = Math.abs(x);
}
if (x > 999999999999999) throw new RangeError('Number must be in -999999999999999..999999999999999');
var i = power.length - 1, j, substr;
for (; i >= 0; --i) {
if (x >= power[i].e) {
j = Math.floor(x / power[i].e);
substr = numberWord(j) + ' ' + power[i].str;
if (power[i].and) number = strAndAdd(number, substr);
else number = strAdd(number, substr);
x %= power[i].e;
}
}
if (x > 0) {
number = strAndAdd(number, words[x]);
}
return number;
}
}());
Example usage
numberWord(+'-999,999,999,999,999'.replace(/,/g, ''));
// "minus nine hundred and ninety nine trillion nine hundred and ninety nine billion nine hundred and ninety nine million nine hundred and ninety nine thousand nine hundred and ninety nine"
numberWord(1999); // "one thousand nine hundred and ninety nine"
numberWord(2016); // "two thousand and sixteen"
Check this function. It get a numeric value as parameter and returnes this number as text. (Numbers 1 to 6 for the dice):
var diceResult = 6;
var getNumberText = function(num) {
//Create an object that maps the relation between numeric and literal values of numbers
var numTxtSet = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six'
}
//Check if the given parameter is a number
if (num && !isNaN(num)) {
return numTxtSet[num];
}
}
//Call the function passing 'diceResult' as parameter and store it's value to a variable
var res = getNumberText(diceResult);
alert(res);
In case your getSumDiceValue() function, will be returning a numeric value, of a range from 0 to 6, you might be after something like this:
var numTxtSet = "zero,one,two,three,four,five,six".split(",");
zero.className = numTxtSet[ getSumDiceValue() ];

Categories