Unshuffle JavaScript array - javascript

I have a huge array of data that I got from PDF files. The pdfs had 10 data items per page but because it was presented in two columns the data is shuffled. The first and last item of each group of ten items are in the correct position but the rest are not.
The order is now 0,2,4,6,8,1,3,5,7,9,10,12,14,16,18,11...
and i need it to be 0,1,2,3...
I've tried looping through the array and pushing items to a new array using different if statements but just cant get it right.

Here is a function that takes the data as you get it, and two more arguments to indicate the number of columns and number of rows on a page:
function uncolumnize(data, numColumns, numRows) {
let perPage = numColumns * numRows;
return data.map((_, i) =>
data[Math.floor(i / perPage) * perPage
+ Math.floor((i % perPage) / numColumns)
+ (i % numColumns) * numRows]
);
}
let res = uncolumnize([0,2,4,6,8,1,3,5,7,9,10,12,14,16,18,11,13,15,17,19], 2, 5);
console.log(res);
It uses the map Array method, since the result (obviously) has just as many elements as the original data. The callback given to map does not use the value, but only the index. That index is used to determine the page, the row and the column. The latter two are reversed to rebuild a new index, and the data at that new index is returned.

2 columns of 10 elements per page will have groups of 10 as 10n,10n+2,10n+4,10n+6,10n+8,10n+1,10n+3,10n+5,10n+7,10n+9
There will be groups of 10 elements and one group (the last one) which will have 0-9 elements.
N = 5 //numbers of rows
len = numbers.length //numbers is the array
groups_of_2n_len = len/(2*N)
last_group_len = len%(2*N)
//For each group complete group
for(group_i = 0; group_i<groups_of_2n_len ; group_i=group_i +1)
{
//Store those 2N elements in an array
temp_array = numbers.slice(group_i*2*N,group_i*2*N + 2*N)
element = group_i*2*N
//Iterate row wise and fix the numbers
for(temp_i = 0; temp_i< N; temp_i = temp_i+1)
{
numbers[element]=temp_array[temp_i]
numbers[element+1] = temp_array[temp_i + N]
element = element+2
}
}
//For last group
if(last_group_len ==0) return
temp_array = numbers.slice(groups_of_2n_len*2*N,/*Till Last element*/)
element = groups_of_2n_len*2*N
for(temp_i = 0; temp_i< floor(last_group_len/2); temp_i = temp_i+1)
{
numbers[element]=temp_array[temp_i]
numbers[element+1] = temp_array[temp_i + floor(last_group_len/2)+last_group_len%2]
element = element+2
}
//In case of odd number of elements, no need to handle
//last element since it is already in correct place

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Example highlighted:
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
If numbers are in two separate arrays you can do something like this...
const array1 = [0, 4, 6, 5, 7];
const array2 = [1, 3, 2, 8, 9];
const combined = [...array1, ...array2];
console.log(combined);

Related

Javascript - Updating duplicated numbers in an array

I have an unordered list like this;
list1 = [2,3,1,2,1,3,3,1,2]
I want to add +10 to the recurring elements in this list every time. So there should be a list as follows;
list1 = [2,3,1,12,11,13,23,21,22]
At the same time, the list order must remain intact.
In fact, the list is longer than the example here (10 digits repeat 7 times).
I would be grateful for your suggestions.
Just have a lookup which count the frequency of number and then multiply the frequency with 10 and add the number.
const list1 = [2,3,1,2,1,3,3,1,2],
lookup = {},
result = list1.map(number => {
lookup[number] = (lookup[number] || 0) + 1;
return number + (lookup[number] - 1) * 10;
});
console.log(result);
You can do it like this:
var list1 = [2,3,1,2,1,3,3,1,2];
var countObject = {};
list1.forEach(function(item, index) {
if(countObject[item]) {
list1[index] = item + (10 * countObject[item]);
countObject[item] = countObject[item] + 1;
} else {
countObject[item] = 1;
}
});
For a compact version, you could take a closure over an object for counting and assign zero to unknown property and increment this value.
const
list = [2, 3, 1, 2, 1, 3, 3, 1, 2],
result = list.map((o => v => v + 10 * (o[v] ??= 0, o[v]++))({}));
console.log(...result);

Index Values SumUp to Total

I am trying to improve in my Problem Solving Skills and would love to get some explanation on what it is that I am doing wrong or if I can get a hand in the right direction. My code below is what I am stuck on.
My problem, I am trying to check within the array if it contains any numbers that will sum up to a total given value. Pretty simple but a bit complex for a beginner.
My first Step is to setup a function with two parameters that accept the array and total amount we want.
const array = [10, 15, 7, 3];
function sumUpTotal(array, total) {
}
Then I want to iterate through my array to check each value within the array by using the forEach method to output each value
const array = [10, 15, 7, 3];
function sumUpTotal(array, total) {
array.forEach(value => value)
}
Now that I have all the outputs, I am stuck on how I can check if the numbers add up with each other to give out the total we want. Can someone please help.
The Output should be two numbers that add up to the total.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Using forEach() to iterate over each value in the array and includes() to check if any values further ahead in the array sum to your total you can generate an array of unique sum pairs. By only looking forward from the given iteration one avoids generating duplicate pairings. (eg. avoids [[10, 7], [7, 10]] for you example input)
forEach() provides both the value and the index of the current iteration, which makes it simple to use the optional, second fromIndex argument of includes() to only look ahead in the array by passing index+1. If a match is found an array of [value, difference] is pushed to the result array. The return value is an array of sum pairs, or an empty array if there are no matches.
const array = [10, -2, 15, 7, 3, 2, 19];
function sumUpTotal(array, total) {
let result = []
array.forEach((value, index) => {
let diff = total - value;
if (array.includes(diff, index + 1)) result.push([value, diff]);
});
return result;
}
console.log(JSON.stringify(sumUpTotal(array, 17)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this using a Set as follows:
function sumUpTotal(array, total) {
// initialize set
const set = new Set();
// iterate over array
for(let i = 0; i < array.length; i++){
// get element at current index
const num = array[i];
// get the remaining number from total
const remaining = total - num;
// if the remaining is already stored in the set, return numbers
if(set.has(remaining)) return [num, remaining];
// else add number to set
else set.add(num);
}
// return null if no two numbers in array that sum up to total
return null;
}
const array = [10, 15, 7, 3];
const total = 17;
console.log( sumUpTotal(array, total) );

Max Average For All Durations

I want to find all possible maximum contiguous subarray averages from an array of values. Each array value represents the value at a duration, the number of seconds passed.
Ex. Input = [6, 4, 3, 10, 5]
Ex. Output = [5.6, 5.75, 6, 7.5, 10]
Output[0] = 6+4+3+10+5 / 5 = 5.6
Output[1] = 6+4+3+10 / 4 = 5.75
Output[2] = 3+10+5 / 3 = 6
Output[3] = 10+5 / 2 = 7.5
Output[4] = 10 / 1 = 10
The issue is that the real data has length of up to 40,000 values.
The result should have the same length as the input. I‘ve done a reduce on a subarray of specific lengths (only getting 5s, 60s, 3600s, etc. length), but that’s not a viable solution for each possible duration. Is there a way I can partition or otherwise create a specialized data structure to get these values? If not, how can I exclude durations as I go?
You can just take the reverse of the input array, then calculate sum and average incrementally. Then again taking the of output array.
const input = [6, 4, 3, 10, 5].reverse();
let output = [];
let total_sum = 0;
for (var i = 0; i < input.length; i++) {
total_sum += input[i];
let avg = total_sum / (i + 1);
output.push(avg);
}
console.log(output.reverse());
(You can even eliminate the reverse by looping the for loop in reverse order.)
Why not .map()? Mixed with reduce you could do something like this:
const output = [
[1, 2, 3, 4],
[5, 6, 7, 8]
];
const averages = output.map(
subarray =>
subarray.reduce(
(previousValue, currentValue) => previousValue + currentValue,
0
) / subarray.length
);
Where subarray is the collection of values, they're then added together and divided by the length of the subarray.
I hope this is what you mean

how to check each element in an array for a specific condition

I have six integers stored in an array:
[2,3,4,5,6,7]
I would like to use each item in the array to check against a range of other integers 100 - 999 (i.e. all three-digit numbers) to find a number that has a remainder of 1 when divided by all the items in the array individually.
I'm not sure what javascript method to use for this. I'm trying a for loop:
function hasRemainder() {
let arr = [2,3,4,5,6,7];
for (i = 100; i < 999; i++) {
if (i % arr[0] == 1) {
return i;
}
}
}
but it has several problems I need to solve.
Instead of referring to a particular item e.g. arr[0], I need to find a way to loop through all the items in the array.
Currently, this function only returns one number (the loop stops at the first number with a remainder), but I need all the possible values in the given range.
If anyone could help with these two problems, I'd really appreciate it. Thanks.
You could map an array of values and then filter the array by checking every remainder value with one.
function hasRemainder() {
var array = [2, 3, 4, 5, 6, 7];
return Array
.from({ length: 900 }, (_, i) => i + 100)
.filter(a => array.every(b => a % b === 1));
}
console.log(hasRemainder())
This works also;
function hasRemainder() {
const arr = [2, 3, 4, 5, 6, 7];
const remainders = []
for (i = 100; i < 999; i++) {
const isRemainder = arr.every(numb => i % numb === 1)
if (isRemainder) {
remainders.push(i)
}
}
return remainders
}

populating array of arrays with distinct values

I have an array of array with elements for example:
var one = [1span,2span,3span,4span,5span,6span,7span];
var two = [1span,2span,3span,4span,5span,6span,7span];
var three = [1span,2span,3span,4span,5span,6span,7span];
var ...till seven.
var total = [one,two,three ..till 7]
so basically we have 7 arrays and total variable will display 7 elements for each one of all 7 arrays.
now I have a function that should populate my variables with distinct numbers from 1 to 7 on each section.
var bar = [1, 2, 3, 4, 5, 6, 7];
for(var j=0; j<total.length; j++) {
Array.from(total[j]).forEach(function(e, i, a) {
e.textContent = bar[Math.round(Math.random()*(bar.length-1))];
console.log(e,i,k);
});
}
all good my function does that but unfortunately is populating span elements with values from bar variable for each variable from total var 7 times for each and should populate just once for each variable.
So my problem is:
I want to populate each variable from total var with values from bar array just once.
The values should be randomly and unique for each variable.
You could use an copy of the given array and generate random items without repeat.
function generate(count, values) {
return Array.apply(null, { length: count }).map(function () {
var r = [],
array = values.slice();
while (array.length) {
r.push(array.splice(Math.floor(Math.random() * array.length), 1)[0]);
}
return r;
});
}
console.log(generate(7, [1, 2, 3, 4, 5, 6, 7]));
Randomize a single array
function generate(values) {
var r = [],
array = values.slice();
while (array.length) {
r.push(array.splice(Math.floor(Math.random() * array.length), 1)[0]);
}
return r;
}
console.log(generate([1, 2, 3, 4, 5, 6, 7]));
If we would like to extend the question for a general case of an N dimensional array filled with random integers then a reusable approach could be as follows;
We will use two generic functions that i like to use very much; Array.prototype.clone() and Array.prototype.shuffle(). Our arrayND function takes indefinite number of arguments. The last argument will designate the minimum (base) of the random integer to be filled. Previous arguments will give the length of each dimension. So in the particular case as we will need a 2D 7x7 matrice to be filled with random but unique numbers in each starting from 1, we shall invoke our function as arrayND(7,7,1)
Array.prototype.shuffle = function(){
var i = this.length,
j;
while (i > 1) {
j = ~~(Math.random()*i--);
[this[i],this[j]] = [this[j],this[i]];
}
return this;
};
Array.prototype.clone = function(){
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
function arrayND(...n){
return n.reduceRight((p,c) => c = Array(...Array(c)).map((e,i) => Array.isArray(p) ? p.clone().shuffle() : i+p));
}
var arr = arrayND(7,7,1);
console.log(arr);
since you want these Arrays to be processed together you should put them together into a data-structure:
var spans = [ one, two, tree, ..., seven ]
now you want a random order without repetition, put the possible indices into an Array and shuffle that:
var indices = [0,1,2,3,4,5,6];
and some shuffler:
function shuffle(arr){
for(var i=arr.length, j, tmp; i-- > 1; ){
tmp = arr[j = 0|(Math.random()*i)];
arr[j] = arr[i];
arr[i] = tmp;
}
return arr;
}
now if you want the Nodes for total:
var total = shuffle(indices).map((index, n) => spans[n][index]);
at least as far as I understand your question/code/intentions.

Categories