How to replace the value of element which is not found in another array in ascending order? - javascript

let newer = [7,8,10,0,2,3,9,24,1,4,20,19,23,5,21,6,22];
let indices_2= [3,5,0,1,4,6,7,10,**13**,**16**,8,2,9,**14**,**15**,**11**,**12**];
Output should be = [3,5,0,1,4,6,7,10,**21**,**24**,8,2,9,**22**,**23**,**19**,**20**];
Hi guys, this might be tough. If the element in indices_2 is not found in newer, from smallest to largest value, lets say the first smallest number of indices_2 not found in newer is 11, it is replaced by the first smallest number found in newer which is not found in indices_2 which is 19. Then the sequence continues on for the the second smallest number of indices_2 not found in newer.
let newer=[7,8,10,0,2,3,9,24,1,4,20,19,23,5,21,6,22];
let indices_2=[3,5,0,1,4,6,7,10,13,16,8,2,9,14,15,11,12];
let status_indices=[]; let status_indices_stat=[];
for (let i=0;i<newer.length;i++){
status_indices_stat="f"
for (let f=0;f<newer.length;f++){
if (indices_2[i]==newer[f]){
status_indices_stat="t"
//check whether element is found in newer.
}
}
status_indices.push(status_indices_stat)
}
for (let f=0;f<newer.length;f++){
if (status_indices[f]=="f"){
for (let i=0;i<newer.length;i++){
if (indices_2[f]<newer[i]){
console.log(i)
}
}
}
}

You could filter both arrays with the opposite, sort them and take the array with filtered indices as pattern for the index of getting the value of the other filtered and sorted array.
let newer = [7, 8, 10, 0, 2, 3, 9, 24, 1, 4, 20, 19, 23, 5, 21, 6, 22],
indices2 = [3, 5, 0, 1, 4, 6, 7, 10, 13, 16, 8, 2, 9, 14, 15, 11, 12],
temp1 = newer.filter(v => !indices2.includes(v)).sort((a, b) => a - b),
temp2 = indices2.filter(v => !newer.includes(v)).sort((a, b) => a - b),
result = indices2.map(v => newer.includes(v) ? v : temp1[temp2.indexOf(v)]);
console.log(...result);

Related

why it is returning only false? Luhn algorithm

What's wrong with my code? It should return true for this array. The invalid one should return false.
Please explain it to me because i'm just started with JS
//arrays :
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const invalid1 = [4, 5, 3, 2, 7, 7, 8, 7, 7, 1, 0, 9, 1, 7, 9, 5];
const validateCred = Array => {
let cardNum = 0
let reverseArray = Array.reverse()
for (let i = 0; i < reverseArray.length; i++){
let newVar = reverseArray[i]
if (i%2 !== 0){
newVar = reverseArray[i] * 2
if (newVar > 9){
newVar = newVar[i] - 9;
cardNum += newVar
} else {
cardNum += newVar
}
} else {
cardNum += reverseArray[i]
}
}
return(cardNum%10 === 0 ? true : false)
}
console.log(validateCred(valid1))
As you figured out and noted in the comments, this is not going to go well when newVar is a number:
newVar = newVar[i] - 9;
And as Pointy, um, pointed out, Array is a terrible name for a variable, shadowing an important constructor function. More than that, there is a strong convention in JS that InitialCapital variable names are reserved for constructor functions. I would suggest a name that describes what it's for, not its type. Perhaps "creditCard" would be useful, or, depending on your tolerance for short abbreviations, "cc".
But there's another, more subtle, problem with this code. It alters its input:
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
console .log (validateCred (valid1)) //=> true
console .log (valid1) //=> [8, 0, 8, 6, 1, 0, 8, 0, 9, 7, 7, 6, 9, 3, 5, 4]
In a real application, this could cause you all sorts of problems, and maybe far away from this section, always frustrating.
It's easy enough to fix. Just clone the array before reversing it. There are many ways to do it (using myVariable.slice() or myVariable.concat(), for instance.) My preference these days is to spread it into a new array: [...myVariable].
In my answer to another Luhn's Algorithm question, I developed what I think of as an elegant version of this algorithm. If you're new to JS, this may use some features you're not familiar with, but I find it clear and useful. This is a slightly improved version:
const luhn = (ds) => ([...ds]
.filter(d => /^\d$/ .test (d))
.reverse ()
.map (Number)
.map ((d, i) => i % 2 == 1 ? (2 * d > 9 ? 2 * d - 9 : 2 * d) : d)
.reduce ((a, b) => a + b, 0)
) % 10 == 0
It's the same algorithm, just expressed a little more concisely. Between the spreading of the initial value and the filter call (removing non-digits), it allows us to pass various input formats:
const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8];
const valid2 = "4539677908016808"
const valid3 = "4539-6779-0801-6808"
const valid4 = "4539 6779 0801 6808"

how to write a program that prints the largest value that occurs simultaneously in both arrays?

I have to create two 10-elements arrays with random values from 1 to 20 and write a program that prints the largest value that occurs simultaneously in both arrays.
I created two tabs like below. The program should prints the largest value that occurs simultaneously in both arrays. Here it should be 11. I know just how to catch the max value from the array. I appreciate help.
<script>
var max = 0;
var tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
var tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
for (var i = 0; i < tab.length; i++) {
if (max <= tab[i]) {
max = tab[i];
}
}
console.log(max);
</script>
to find the largest value use nested loops to compare each element of both arrays as follow
var tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
var tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
var max = 0;
for (var i = 0; i < tab.length; i++) {
for (var j = 0; j < tab2.length; j++) {
if (tab[i] === tab2[j] && tab[i] > max) {
max = tab[i];
}
}
}
console.log(max);
I'd do this:
// const {intersection,max} require('lodash/fp'}
const { intersection, max } = _;
const tab = [1, 2, 5, 8, 9, 11, 15, 16, 17, 20];
const tab2 = [3, 4, 6, 7, 10, 11, 12, 13, 14, 18];
const res = max(intersection(tab, tab2))
console.log({
intersection: intersection(tab, tab2),
max: max(intersection(tab, tab2)),
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
You can translate that into straight javascript, especially if it's for a homework assignment :).
The approach is as follows ...
get the intersection of both arrays
get the maximum value of the just computed intersection
... which then boils down either to coming up with an own implementation of an intersection functionality or to making use of a third party library / helper functionality.
The below example code features one possible implementation of getIntersection which makes use of ...
Array.from in order to always ensure the processing of array parameters,
Array.prototype.sort in order to help optimally assign the participating arrays for the best computation performance,
Array.prototype.reduce and a Map instance for creating a lookup-table in order to achieve a more performant filter process when it comes to the actual computation of the intersection,
Array.prototype.filter and Map.prototype.has for finally computing the intersection result.
function getIntersection(firstIterable = [], secondIterable = []) {
const [
comparisonBase, // ... compare to the shorter array.
comparisonList, // ... filter from the longer array.
] = [Array.from(firstIterable), Array.from(secondIterable)]
// - ensure two arrays (line above)
// - and sort them according to each array's `length`.
.sort((a, b) => a.length - b.length);
// create a `Set` based lookup from the shorter array.
const itemLookup = new Set(comparisonBase);
// the intersection is the result of following filter task.
return comparisonList.filter(item => itemLookup.has(item));
}
const tab = [1, 2, 4, 5, 8, 9, 11, 15, 16, 17, 20, 21, 0];
const tab2 = [3, 4, 6, 7, 9, 10, 11, 12, 13, 14, 18, 19, 0];
console.log(
'intersection of `tab` and `tab2` ...',
getIntersection(tab, tab2)
);
console.log(
'max value of the intersection of `tab` and `tab2` ...',
Math.max(...getIntersection(tab, tab2))
);

does python have an equivalent to javascript's every and some method?

I was trying to search the docs for a method similar but I was only able to find pythons all() and any(). But that's not the same because it just checks if the val is truthy instead of creating your own condition like in js' every and some method.
i.e
// return true if all vals are greater than 1
const arr1 = [2, 3, 6, 10, 4, 23];
console.log(arr1.every(val => val > 1)); // true
// return true if any val is greater than 20
const arr2 = [2, 3, 6, 10, 4, 23];
console.log(arr2.some(val => val > 20)); // true
Is there a similar method that can do this in python?
Just combine it with a mapping construct, in this case, you would typically use a generator expression:
arr1 = [2, 3, 6, 10, 4, 23]
print(all(val > 1 for val in arr1))
arr2 = [2, 3, 6, 10, 4, 23]
print(any(val > 20 for val in arr2))
Generator comprehensions are like list comprehensions, except they create a generator not a list. You could have used a list comprehension, but that would create an unecessary intermediate list. The generator expression will be constant space instead of linear space. See this accepted answer to another question if you want to learn more about these related constructs
Alternatively, albeit I would say less idiomatically, you can use map:
arr1 = [2, 3, 6, 10, 4, 23]
print(all(map(lambda val: val > 1, arr1)))
arr2 = [2, 3, 6, 10, 4, 23]
print(any(map(lambda val: val > 20, arr2)))
Yes, Python has it.
numbers = [1, 2, 3, 4, 5]
all_are_one = all(elem == 1 for elem in numbers)
some_are_one = any(elem == 1 for elem in numbers)

Get the 5 items before and after the current index in an array

Say I have an array that looks like this
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
These array represents page numbers in my scenario.
Say if I am on page 8, I'd like to create a seperate array that includes the following
The first 5 before page 8 and the first 5 after page 8.
i.e first 11 items array.
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Therefore having 11 items in an array including that page itself.
If the array is smaller than 5, then simply return the rest.
i.e
if the array looks like this [2,3,4,5,6,7,8]
and if the page is 4, since the before does not have 5 items exactly I'd like to get all of it.
You can use the slice method of the Array.
function paginatorNumbers(arr, currentIndex) {
return arr.length > 5 && currentIndex > 5
? arr.slice(currentIndex - 6, currentIndex + 5)
: arr.slice(0, currentIndex + 5)
}
Use the slice function. Given x=8 in your example, the following will create a new array with the indexes you want.
arr.slice(x-5, x+6)
The start index x-5 is inclusive (or it will include index 8-5 = 3). The end index x+6 is exclusive (it will not include index 8+6=14). So you get indices 3 - 13 like you wanted.
EDITED:
This should work now
const getRange = (array, index) => {
// You need constraints if index - 5 is < 0
const startIndex = Math.max(0, index - 5 - 1);
const endIndex = index+ 5;
return array.slice(startIndex, endIndex);
}
You can makeit very simple with Plus and Minus.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
function getRange(current) {
let start = (current -5)
let end = (current + 5)
let res = []
start = start < 0 ? 0 : start
for(start; start <= end; start++) {
res.push(start)
}
return res;
}
console.log(getRange(8)) // starts from 3
console.log(getRange(2)) // starts from 0
Using the slice method, you can get a specific subarray from the whole array. What you need to do is to slice 5 places before the page index, and then slice 5 places after the page index. Then, just concat both subarrays and get the result.
The Math.min and Math.max functions are to avoid range problems when slicing the array. So, when the subarray is smaller than 5, it just returns the rest of the array, and not an empty array.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
let currentPage = parseInt(prompt("Current page"));
// page index
let i = arr.indexOf(currentPage);
// Using Math.max and Math.min to avoid range problems
const subarr = arr.slice(Math.max(i - 5, 0), i).concat(
arr.slice(i, Math.min(i + 6, arr.length)));
console.log(subarr);
This is a universal solution
count of items before and after can be set
.slice() is used for timming the array
checks that start index is not < 0 (otherwise it would be sliced from the end)
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
function getBeforeAfter(arr, index, count) {
let start = index - count -1
if(start < 0) start = 0
let end = index + count
return arr.slice(start, end)
}
console.log(getBeforeAfter(arr,8,5)) // [3,4,5,6,7,8,9,10,11,12,13]
You can use array#slice to generate number in a range relative to index.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
getRangeItem = (arr, index, range) => {
const start = Math.max(index - range - 1, 0),
end = Math.min(index + range, arr.length),
result = arr.slice(start, end);
return result;
}
console.log(getRangeItem(arr, 8, 5));

What is a more optimized solution for this algorithm? I feel i can learn more from this question

First off am a beginner practicing my JavaScript. My solution to this problem will be posted. I think its worth mentioning this took almost two days of pondering to solve
The Problem:
I am required to write an algorithm that will return the mode(s) from the given input array. For example:
mode([4, 5, 6, 6, 6, 7, 7, 9, 10]) ➞ [6]
mode([4, 5, 5, 6, 7, 8, 8, 9, 9]) ➞ [5, 8, 9]
mode([1, 2, 2, 3, 6, 6, 7, 9]) ➞ [2, 6]
Solution:
function mode(nums) {
let array = [...nums]
array = array.sort((a, b) => a - b) //sorts the array from lowest value
// function to figure out the unique numbers and return as an array
function uniqueNums(array) {
let uniques = []
for (let i = 0; i < array.length; i++) {
if (!uniques.includes(array[i])) {
uniques.push(array[i])
}
}
return uniques
}
//function to return the mode of every unique number
function counter(array) {
let modes = []
for (let i = 0; i < array.length; i++) {
let count = 1, // keeps track of occurrence's of a number
track = 1 //variable enables the while loop keep checking
while (array[i] === array[i + track]) {
count++
track++
}
modes.push(count)
i += count - 1
}
return modes
}
//function to return the highest mode(s)
function highestMode(uniques, modes) {
let highest = [],
max = 0 //tracks our highest number in the array
//loops to find highest mode
for (let i = 0; i < modes.length; i++) {
if (max < modes[i]) {
max = modes[i]
}
}
//loops to push position of modes equal to the highest mode
for (let i = 0; i < modes.length; i++) {
if (max === modes[i]) {
highest.push(i)
}
}
//uses the position of highest modes to swap them with their
//actual values
let result = highest.map(a => a = uniques[a])
return result
}
return highestMode(uniqueNums(array), counter(array))
}
console.log(mode([4, 4, 4, 6, 8, 9, 10, 10]))
If you're looking at this as a learning exercise, here's another implementation of the same algorithm from CertainPerformance, but written quite differently.
const mode = (
ns,
counts = ns .reduce ((m, n) => m .set (n, (m .get (n) || 0) + 1), new Map ()),
max = Math .max (... counts .values())
) =>
[...counts] .flatMap (([n, c]) => c == max ? [n] : [])
console .log (mode ([4, 5, 6, 6, 6, 7, 7, 9, 10])) //=> [6]
console .log (mode ([4, 5, 5, 6, 7, 8, 8, 9, 9])) //=> [5, 8, 9]
console .log (mode ([1, 2, 2, 3, 6, 6, 7, 9])) //=> [2, 6]
If it's not clear, my counts matches to grouped and my max to maxCount.
The big difference from the answer by CertainPerformance is that this is written with pure expressions rather than statements. This is a style that I try to follow as much as I can do so practically.
It uses default parameters as a poor-man's substitute for let bindings available in other languages. It's not a perfect substitute and there is at least one potential problem with it, but it can be quite useful. Doing this let me define some helper variables that you can't assign in a function body without statements. There are alternatives, but I find this simplest when I can get away with it.
The reduce call is essentially the same as the other answer. So is the max definition.
But I take advantage of the fact that the default iterator of a Map is the list of entries, to turn the map into [[4, 1], [5, 1], [6, 3] ...] just by using the spread operator (...), without a need to call .entries().
Finally, I replace a call to filter and then to map with a single call to flatMap. This feels more elegant.
I'm not trying to suggest that this code is better than the one from CertainPerformance. It's quite similar in feel, although different in arrangement. But it is a different approach to the problem, and it might have something to offer because of that.
I'd count up the number of occurrences of each element into an Map. Then use Math.max to find the largest value(s) in the map, and then take the keys which are equal to that largest value:
const mode = arr => {
const grouped = new Map();
for (const item of arr) {
grouped.set(item, (grouped.get(item) || 0) + 1);
}
const maxCount = Math.max(...grouped.values());
return [...grouped.entries()]
.filter(([, count]) => count === maxCount)
.map(([key]) => key);
};
console.log(mode([4, 5, 6, 6, 6, 7, 7, 9, 10])) // ➞ [6]
console.log(mode([4, 5, 5, 6, 7, 8, 8, 9, 9])) // ➞ [5, 8, 9]
console.log(mode([1, 2, 2, 3, 6, 6, 7, 9])) // ➞ [2, 6]
A more simpler and optimized approach with single iteration
https://jsfiddle.net/dv7f9nxr/
function mode(items) {
var result = [];
var count = {};
var highest= 0;
items.map((item) => {
var itemCount = (count[item] || 0) + 1;
count[item] = itemCount;
if(itemCount > highest) {
highest = itemCount;
//reset
result = [item];
} else if (itemCount === highest){
result.push(item);
}
})
return result;
}
console.log(mode([2, 3, 9, 6, 9]))
console.log(mode([2, 3,2, 9, 6, 9]))
console.log(mode([2, 3,2, 9, 6, 9,2]))
console.log(mode([2, 3, 9, 6, 9,6,2]))

Categories