find sequence of numbers in array and alert highest number - javascript

I have an array that looks like this:
[1,2,3,4,5,6,8,10,12,13,14,15,20,21,22,23,24,25,26,27,28,29,30]
the highest count on one of the found sequences would be: 10
My goal is to loop through the array and identify the sequences of numbers, then find the length of the highest sequence that exists.
So, based on the array above, the length of the longest sequence would be "10"
Does anyone know of quick and easy script to find this?

OK, I think I found a very short way of doing this (only 1 line for the for loop):
var arr = [1,2,3,4,5,6,8,10,12,13,14,15,20,21,22,23,24,25,26,27,28,29,30];
var res = new Array();
res[0] = 0;
for(var i=1;i<arr.length;i++) res[i] = (arr[i] == arr[i-1] + 1) ? (res[i-1] + 1) : 0;
var maxLength = Math.max.apply({},res);
this gives you (10) as the result. if you need (11) (which makes more sense) change the 0 to 1 in the for loop.
jsFiddle link: http://jsfiddle.net/gEzzA/8/

You don't need jQuery for this.
function longestSeq(arr) {
var len = 0, longestLen = -1, prev = null;
for (var i = 0; i < arr.length; ++i) {
if (prev == null || arr[i] - 1 === prev)
++len;
else {
if (len > longestLen) longestLen = len;
len = 1;
}
}
return longestLen > len ? longestLen : len;
}
What that does is keep track of how long it's been since a "break" has been seen. Each time a break is seen, it checks whether the longest so far is shorter than the last good run.

Here's the solution in pseudo code...
First, setup another array with the same number of elements and initialised to zero, to use as counters...
Array01:=[1,2,3,4,5,6,8,10,12,13,14,15,20,21,22,23,24,25,26,27,28,29,30]
Array02:=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Now the logic for filling in the counters...
FOR i:=0 TO LastElement DO
WHILE (Array01[i+1]-Array01[i]=1) AND (i<LastElement) DO Inc(Array02[i]);
Now to scan who's got the highest sequence score...
which:=0; Value:=Array02[0];
FOR i:=0 TO LastElement DO
IF Array02[i]>Value THEN BEGIN Value:=Array02[i]; Which:=i; END;
So, at the end of this the highest sequence is held by Array element "Which" and the count is "Value"!

Related

Sort an array element closest to known element based on it's index

Let's assume an array
Example 1 :
let arr = [101,102,104,103,105]
known_element = 104;
//Output [104,102,103,101,105]
Example 2 :
let arr = [4,6,3,5,1,9,2,7,8]
known_element = 9;
//Output [9,1,2,5,7,3,8,6,4]
Sort the above array in such a way,
known_element should be always at 0th element
second,third.. element should be closest to known_element by it's index not by value
Note: sorting should be done based on index closest to known_element.
It makes sense to find location of known number first
var pos = arr.indexOf(known_element);
Then we are going to loop up and down, getting numbers from closest to farthest. Let's see to which side is longer length.
var length = Math.max(pos, arr.length - pos + 1)
Ok, our result array is ready (to be filled), lets loop
var result = [known_element];
for (var i = 1; i < length; i++) {
if (pos- i >= 0) {
result.push(arr[pos - i])
}
if (pos + i < arr.length) {
result.push(arr[pos + i]);
}
}
I think that's it!
Test and let me know which edge case I forgot.

Remove duplicates from an array in Javascript (without modify the array) - Understand the logic behind

I started using a website called leetcode and one question is to remove all the duplicates in an array without create a new one. Here is the question https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/
My solution was to loop and the check each element against the next one, then if match use splice to remove the duplicated one. it works but not when you have something like [1,1,1,1,1] or [1,1,2,2,2,2,3,3] so I found on github a working code:
var removeDuplicates = function(nums) {
var i = 0;
for (var n in nums)
if (i === 0 || nums[n] > nums[i-1])
nums[i++] = nums[n];
return i;
};
This code works and passes all the 160 tests, but I don't understand clearly what is doing, especially the part in nums[i++] = nums[n]; can someone be so kind to help me to understand what this, simple, code is doing? thanks
Consider this code that creates a new array:
function removeDuplicates(nums) {
var res = [];
var i = 0;
for (var j=0; j<nums.length; j++)
if (i === 0 || nums[j] !== res[i-1])
res[i++] = nums[j];
return res;
}
The line you're asking about assigns nums[j] as new element at res[i] when the value is not the same as the previous one (res[i-1]), then increments i to put the next non-duplicate value in the next position.
Now we use the same algorithm but instead of assigning to a new res array, we modify the original nums array:
function removeDuplicates(nums) {
var i = 0;
for (var j=0; j<nums.length; j++)
if (i === 0 || nums[j] !== nums[i-1])
nums[i++] = nums[j];
nums.length = i; // drop the rest
}
Given that j >= i is guaranteed, we only modify array elements that we've always visited, so there's no harm in writing on the same array that we are reading from.

Algorithm: Next Greater Element I (from leetcode)

can someone please tell me what I'm missing in solving this algorithm? One problem I have is that my first if statement inside the nested loop is not evaluating, but I don't know why it wouldn't evaluate.
Here is the description of the problem:
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
link to original description
And here is my code so far:
var nums1 = [4,1,2];
var nums2 = [1,3,4,2];
var nextGreaterElement = function(findNums, nums) {
var holder = [];
for (var i = 0; i < findNums.length; i++) {
//loop through the 2nd array starting at the index of the first loop's current item.
for (var j = nums.indexOf(findNums[i]); i < nums.length - j; i++) {
if (nums[j+1] > nums[j]) {
holder.push(nums[j+1]);
break;
}
if (nums[nums.length]) {
holder.push(-1);
}
}
}
return holder;
};
nextGreaterElement(nums1, nums2)
Thanks for any help.
Problem: Updating variant i, but not variant j in inner loop (j-loop)
Missing: Debugging Effort
Problem Description
Theoretically, your code design should compare each value in nums1 to related parts of nums2. So, it would turn to a outer for-loop to loop on nums1 and an inner for-loop to loop related parts of nums2 for each iteration of the outer for-loop.
In your code, variant i is the index pointer for findNums (i.e. nums1) while variant j is the index pointer for nums (i.e. nums2). Variant i is always updating in both inner for-loop and outer for-loop while variant j is set once for every iteration of outer for-loop. This contradict to what you are suppose to do.
Debugging (Your Missing Work)
Find a piece of paper and a pen. Sit down, dry run the program and keep recording related info (variant i, variant j, findNums[i], nums[j], ...), you could figure out why your code is not working.
Possible Solution
var nextGreaterElement = function(findNums, nums) {
var holder = [];
for (var i = 0; i < findNums.length; i++) {
var hasNextGreaterElement = false;
// try to serach for next greater element
for (var j = nums.indexOf(findNums[i])+1; j < nums.length; j++) {
// handle case for next greater element is found
if (nums[j] > findNums[i]) {
holder.push(nums[j]);
hasNextGreaterElement = true;
break;
}
}
// handle case for next greater element is not found
if (!hasNextGreaterElement) {
holder.push(-1);
}
}
return holder;
};
var findNums=[4,1,2];
var nums=[1,3,4,2];
console.log(nextGreaterElement(findNums, nums));
You need to sort the array you are looking in to make it easier to find the number. If the array get big you might want a search algorithm to find the index in the array faster. With the array that is going to be looked in sorted you can grab the next number as the number that is one larger and check to see if you are at the end of the array. If you don't do this check the function will error when you can't find the number or when there is no number larger. Finally your second if statement didn't make sense. So I am checking to make sure that we are at the end of the array before outputting the -1 in the array.
var nextGreaterElement = function(findNums, nums) {
var holder = [];
//Should sort the array to make sure you get the next largest number
nums = nums.sort();
for (var i = 0; i < findNums.length; i++) {
//loop through the 2nd array starting at the index of the first loop's current item.
//for (var j = nums.indexOf(findNums[i]); i < nums.length - j; i++) {
for(var j = 0; j < nums.length; j++){
//check for value in array and make sure the value is not at the end
if (findNums[i] == nums[j] && j != nums.length - 1) {
holder.push(nums[j+1]);
break;
}
//check for the last element in array if so output -1
if (j == nums.length - 1) {
holder.push(-1);
}
}
}
return holder;
};

Is this the right way to iterate through an array?

Here is the code in question:
var L1 = [];
var Q1 = [];
function populateListOne() {
var limit = prompt("please enter a number you would like to fill L1 to.");
for (i = 2; i <= limit; i++) {
L1[i] = i;
}
for (n = 2; n <= L1.length; n++) {
var count = 2;
if (n == count) {
var index = L1.indexOf(n);
L1.splice(index, 1);
Q1[n] = n;
count = count + 1;
}
for (j = 0; j <= L1.length; j++) {
if (L1[j] % 2 == 0) {
var secondIndex = L1.indexOf(j);
L1.splice(secondIndex, 1);
}
}
}
document.getElementById("demo").innerHTML = "iteration " + "1" + ": " + L1 + " Q1 = " + Q1;
}
I’m currently working on a homework assignment where I have to setup a queue. All is explained in my JSFiddle.
Problem description
Essentially, the part I’m stuck on is iterating through each instance of the array and then taking the value out if the modulus is identical to 0. However, as you can see when I run the program, it doesn’t work out that way. I know the problem is in the second for loop I just don’t see what I’m doing wrong.
The way I read it is, if j is less than the length of the array, increment. Then, if the value of the index of L1[j] modulus 2 is identical to 0, set the value of secondIndex to whatever the index of j is. Then splice it out. So, theoretically, only numbers divisible by two should be removed.
Input
A single number limit, which will be used to fill array L1.
L1 will be initialized with values 2, 3, ... limit.
Process
Get the starting element of array L1 and place it in array Q1.
Using that element, remove all values in array L1 that are divisible by that number.
Repeat until array L1 is empty.
You're going to have issues with looping over an array if you're changing the array within the loop. To help with this, I tend to iterate from back to front (also note: iterate from array.length - 1 as the length element does not exist, arrays are key'd from 0):
for(j = L1.length - 1; j >=0 ; j--)
For your first loop, you miss the elements L1[0] and L1[1], so I would change the first loop to:
L1 = [];
for(i = 2; i <= limit; i++)
{
L1.push(i);
}
In this section:
for(j = 0; j <= L1.length; j++){
if(L1[j] % 2 == 0)
{
var secondIndex = L1.indexOf(j);
L1.splice(secondIndex, 1);
}
}
you should splice with j instead of secondIndex.
Change L1.splice(secondIndex, 1); to L1.splice(j, 1);
Array indices and putting entries
You initial code used an array that was initialized to start at index 2. To avoid confusion, of what index to start at, start with index 0 and iterate until array.length instead of a predefined value limit to ensure that you go through each element.
The following still works but will be more of a headache because you need remember where to start and when you will end.
for (i = 2; i <= limit; i++) {
L1[i] = i; // 'i' will begin at two!
}
Here's a better way:
for (i = 2; i <= limit; i++) {
// 'i' starts at 2 and since L1 is an empty array,
// pushing elements into it will start index at 0!
L1.push(i);
}
Use pop and slice when getting values
When you need to take a peek at what value is at the start of your array, you can do so by using L1[0] if you followed my advice above regarding array keys.
However, when you are sure about needing to remove the starting element of the array, use Array.slice(idx, amt). idx specifies which index to start at, and amt specifies how many elements to remove beginning at that index (inclusive).
// Go to 1st element in L1. Remove (1 element at index 0) from L1.
var current = L1.splice(0, 1);
Use the appropriate loops
To make your life easier, use the appropriate loops when necessary. For loops are used when you know exactly how many times you will iterate. Use while loops when you are expecting an event.
In your case, 'repeat until L1 is empty' directly translates to:
do {
// divisibility checking
} while (L1.length > 0);
JSFiddle
Here's a complete JS fiddle with in-line comments that does exactly what you said.

add element to ordered array in CoffeeScript

I have a sorted array, which I add elements to as the server gives them to me. The trouble I'm having is determining where to place my new element and then placing it in the same loop
in javascript this would look like this
for(var i = 0; i < array.length; ++i){
if( element_to_add < array[i]){
array.splice(i,0,element_to_add);
break;
}
}
The problem is that in coffee script I dont have access to the counter, so I cant tell it to splice my array at the desired index.
How can I add an element to a sorted array in CoffeeScript?
The default for loop returns the index as well:
a = [1, 2, 3]
item = 2
for elem, index in a
if elem >= item
a.splice index, 0, item
break
You may want to do a binary search instead.
If you are using Underscore.js (very recommended for these kind of array manipulations), _.sortedIndex, which returns the index at which a value should be inserted into an array to keep it ordered, can come very handy:
sortedInsert = (arr, val) ->
arr.splice (_.sortedIndex arr, val), 0, val
arr
If you're not using Underscore, making your own sortedIndex is not that hard either; is's basically a binary search (if you want to keep its complexity as O(log n)):
sortedIndex = (arr, val) ->
low = 0
high = arr.length
while low < high
mid = Math.floor (low + high) / 2
if arr[mid] < val then low = mid + 1 else high = mid
low
If I understood you correctly, why not save the position, like so,
var pos=-1;
for(var i = 0; i < array.length; ++i){
if( element_to_add < array[i]){
pos=i; break;
}
}
if(pos<0)
array.push(element_to_add);
else array.splice(pos,0,element_to_add);

Categories

Resources