Partitioning an array into 3 columns with JS - javascript

Given an unknown array of integers of an unknown length, whose values are also unknown, how can I organize them into three columns, so that the sum of the left most group is the largest, the middle the second largest and the third is the smallest with the groups being as close as possible in size.
The actual goal here is to organize <ul> elements by their size (# of <li> elements they contain) into three columns. I'm looking for an answer in javascript, but if someone can explain the logic simply enough that would good enough :)
So in other words given an array such as...
var set = [1, 1, 4, 6, 7, 10, 3, 6]
Would be organized as...
var left = [10, 4]
var middle = [6, 7]
var right = [3, 6, 1, 1]
There are other possibilities. The first column sums to 14, but this could be the outcome of various combinations such as [6, 4, 3, 1]. Being organized in such a way would make it difficult to get the right values for the next column, so preferably use the largest numbers earlier on, as in my example above. *
I'm sure this has been asked and answered before but I didn't know how to look this up. I did some research and found out that this is pretty much the Partitioning Problem, although I'm still at a loss on how to do it or if there is simple one feasible answer here. Anything that works for the simple example I gave should suffice.
* EDIT: On second thought, this may be an incorrect assumption.

Related

Why aren't sizes/lengths standardized on similar objects (Array.length vs. Map.size for instance)? [duplicate]

While looking over new changes to JavaScript I noticed that Set and Map use .size instead of .length like arrays would.
This seems like a pointless diversion from what's normal with arrays - just one more thing to remember.
Was there a good design reason for this?
There's a lot of discussion in the esdiscuss thread "Set length property". This was a hotly debated issue, so it's not surprising that you do not necessarily agree with the resolution.
There is a tremendous amount of arguing about this in esdiscuss. Ultimately, the argument that prevailed (as evidenced by the fact that ES2015's Sets have size and not length) was summarized in a post by David Bruant:
...for me 'length' refers to a measurement with something like a ruler. You start at 0 and see up to where it goes. This is very accurate for an array which is an indexed set (starting at 0 and growing) and for arrays as considered in C (continuous sequence of bytes) which ECMAScript arrays seem inspired of. This is probably less relevant for unordered collections such as sets which I'd tend to consider as a messy bag.
And further discussed in a post by Dean Landolt:
Just wanted to jump in and say non-writable length is consistent with String behavior as well, but David makes a good point about length implying metric topology. David's suggestion of count is nice. ISTM what we're talking about is cardinality, but no need to get too silly w/ precision. Though size is just fine with me, and has plenty of prior art.
While apsillers' Jan 27, 2016 answer adds great links, a code example is missing. The size of a set is a read-only getter while that's not the case for arrays which allow modifying the length to truncate the array.
let arr = [1, 2, 3, 4]
arr.length = 2
console.log("modified length array", arr) // [1, 2]
let mySet = new Set([1, 2, 3, 4])
mySet.length = 2
mySet.size = 2
console.log("modified length set", [...mySet]) // [1, 2, 3, 4]
let str = "1234"
str.length = 2
console.log("modified length string", str) // "1234"

Is there any way of converting OpenCV.Mat to array in JavaScript?

I'm working on Mat in OpenCV. However, I need to manually calculate the Mat by myself. Is there is a way of accessing Mat likes 2D array?
const myMat = cv.matFromArray(cv, 3, 3, cv.CV_64F, [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
const newMat = someProcessThatReturnMat(myMat)
/* OpenCV in JS cannot access Mat like this */
const result = someProcess(newMat[1][2], newMat[2][0])
Thank you in advance
Updated: The problem is cv.matFromArray cannot convert 2D array to Mat. You have to use it as 1D array. That's why it never return the correct values. For example:
const myMat = cv.matFromArray(3, 3, cv.CV_64F, [1,2,3,4,5,6,7,8,9])
And then, you can access the value
const value = myMat.doubleAt(1, 2) // row 1, col 2
You need to use the doubleAt(y,x) method.
It's double because the mat's content is CV_64F, not because you want doubles.
You can also use .data64F to access a flat Float64Array of the Mat's data.
OpenCV.js is... rough. It originated from someone's Google Summer of Code and hasn't received significant care since. Documentation amounts to some tutorials; API docs seem to be missing entirely. The "Mat" interface emulated the at() method from C++, badly, instead of looking at numpy (python) or making this access feel "native" to javascript. Overloading the [] operator is possible using a Proxy but that was not implemented.
Here's an example: https://docs.opencv.org/4.x/de/d06/tutorial_js_basic_ops.html
Feel free to browse OpenCV's issues and maybe suggest some improvements.

Do I need to sort an array to find its median?

I need to create a code where if i for example call func([4, 8, 2, 4, 5]) the method should return the object {max: 8, mean: 4.6, median: 4, min: 2, range: 6}.
Where should I start? Do I need a code for sorting the numbers or is there a code so the computer can find the median without the numbers being sorted first?
You can find a median without sorting the numbers, but that's hard if you want to do that efficiently (for every element count the number of elements less and equal to it, do that till you find element that has correct median count, that means it's in the middle, if number of elements is even then it's even more problematic), plus you can also use sorting for other statistics (max, min etc.) so why not just sort? You can sort array with sort() method.

Check incrementation of adjacent spots in matrix, JavaScript

I've been using CodeFights for a couple days (which I highly recommend as it's a great way to build on to your skills), and today I came across a challenge that I couldn't figure out for the life of me. I hate to give away solutions, but nothing I tried would work.
Generally, the challenge was this: Given any matrix of numbers, such as
[1,4,5,8]
[2,3,6,7]
as a parameter to a function, return true if, starting in the top-left corner, you could traverse all the numbers in the array, incrementing by one each time, by moving only to adjacent spots. So, I start at 1, 2 is adjacent so I can move there, 3 is adjacent to 2 so I can move there, and so on and so forth. If you can't get through the entire matrix then return false. It seems pretty simple until you get down to it.
you must:
– Keep track and compare the number of items checked, against the number of items in the matrix.
– Somehow check each adjacent spot for the value of the current spot +1, and then make that the current spot. Then keep checking until you run out of numbers, otherwise return false.
I tried so many different ways of doing this, using 3 or 4 levels of nested for loops, and nothing I tried would work for all of the test cases. I probably wont ever see the problem again, but just for knowledge's sake, could anyone point me in the right direction? Namely just helping me to understand how to efficiently compare against adjacent spaces in a matrix (to maybe avoid giving away the answer for future CodeFighters)?
Just to clarify:
The function would be set up passing in a matrix:
function traverse(matrix) {
}
and something like this would return true:
[[ 1, 4, 5, 8]
[ 2, 3, 6, 7]]
and something like this would return false:
[[ 1, 3, 5, 8]
[ 2, 4, 9, 7]
[10,12, 6,11]]
Any help just to understand where I may have gone wrong in my execution is greatly appreciated. (Btw I can't post exactly what I tried because I don't believe there's a way to get back to it on the website.)

In what cases do javascript developers use the map() method?

I'm learning about the map() method right now and I understand very basic examples.
var numbers = [2, 4, 6];
var double = numbers.map(function(value) {
return value * 2;
});
My question is, in what cases do developers use the map() method to help solve problems? Are there some good resources with real world examples?
Thanks for the help!
As #Tushar referred:
The map() method creates a new array with the results of calling a
provided function on every element in this array.
So it is basically used when you need to apply certain functionality to every single element of an array and get the result back as an array with the new results.
For example doubling the numbers:
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]
It basically helps to shorten your code eliminating the need of using for loop. But do remember it is used when every element of the array is manipulated because map() generates similar length of array provided.
For eg.- in the example you provided doubles will have [2, 8, 18].
where 2 correspond to 1.
4 correspond to 8.
9 correspond to 18.
I recommend you to watch the whole video but your answer is at the 14th minute:
Asynchronous JavaScript at Netflix by Matthew Podwysowski at JSConf Budapest 2015

Categories