getting dimension of a 2d array in node js - arrays

I'm working on a discord bot in node js and i need to get the length of the 2 dimentions of a 2d array.
My array is structurated like this, that algo get expanded at the bottom when needed:
var users = [["","","","",""]];
now i need to know how to get the dimentions.
i was originaly doing like this, but it didn't work 🙃.
// for the y length
users.length
// for the x length
users[i].length
hope you can help
thanks in advance
Enrico 😊

Actually you almost are correct:
var users = [[1,2],[3,4]]
users.length // y
users[0].length // x
Just keeps in mind that index for each X demantion statred since zero , and might be different for each row.

Your array var users = [["","","","",""]]; is a 2d array where only the 0th index is occupied. In your case, users[i].length would probably throw a length not defined error of some sort at index 1 and beyond. You should used users[0].length to get the length of the 2d element

Assuming that none of the elements in the array varies its length from the first one you could just get the length of the first element with
var dimensions = [users.length, users[0].length]
// returns [1, 5]
In a more practical world, probably is better for you to get the dimensions on each of the elements on the array users and decide on whether to use the biggest or the smallest, naturally I'll chose the biggest.
var users = [["", "", ""], ["", ""], ["", "", "", ""]];
var elementsLength = users.map((user) => (user.length));
var lengthY = Math.max(...elementsLength);
var lengthX = users.length;
var dimensions = [lengthX, lengthY];
// returns [3, 4]
It all depends on what you want.

Related

Sort an array of type UnitMass

So i want to sort an array of UnitMass, but i want to sort it in a specific layout. I know how to sort it alphabetically, but that's not quite what i want anyone that know how i can do this?
Is it possible to sort an array like this, and how can i do this or could i define a way that the array should look?
let spesificLayoutOfUnits =[ UnitMass.grams, UnitMass.kilograms, UnitMass.metricTons, UnitMass.stones, UnitMass.pounds, UnitMass.ounces ]
var toBeSorted = [ UnitMass.kilograms, UnitMass.pounds, UnitMass.metricTons, UnitMass.ounces, UnitMass.grams ]
I use the spesificLayoutOfUnits array as an array of all of the options the user has. Then add units form this array to the toBeSorted array which is the array of the chosen units.
var options = spesificLayoutOfUnits as! [UnitMass]
var tempArray = [UnitMass]()
while toBeSorted.endIndex > positionOfUnit {
tempArray.append(toBeSorted.removeLast())
}
toBeSorted.append(options.remove(at: positionOfUnit))
while !tempArray.isEmpty {
toBeSorted.append(tempArray.removeLast())
}
I'd suggest building up a dictionary that maps UnitMass to its desired position and then using that for the sort:
let specificLayoutOfUnits = [ UnitMass.grams, UnitMass.kilograms, UnitMass.metricTons, UnitMass.stones, UnitMass.pounds, UnitMass.ounces ]
// Create a dictionary to map UnitMass to Int position
var position = [UnitMass : Int]()
for (idx, um) in specificLayoutOfUnits.enumerated() {
position[um] = idx
}
var toBeSorted = [ UnitMass.kilograms, UnitMass.pounds, UnitMass.metricTons, UnitMass.ounces, UnitMass.grams ]
// Sort the array by position. Use Int.max if the UnitMass has no
// position to sort it to the end of the array
let sorted = toBeSorted.sorted { position[$0, default: Int.max] < position[$1, default: Int.max] }
Explanation:
calling .enumerated() on the specificLayoutOfUnits creates a list of tuples where the first element is the position and the second is the unit: [(0, UnitMass.grams), (1, UnitMass.kilograms), (2, UnitMass.metricTons), ...].
Next, we iterate through this list to build up a dictionary that maps the unit to its position: [UnitMass.grams: 0, UnitMass.kilograms: 1, UnitMass.metricTons: 2, ...]
This dictionary is used to sort the second array by the elements position in the first. .sorted(by:) takes a closure that compares two elements and returns a Bool which says if the first element is ordered before the second. Here, we use the position of the two elements in the first array to decide the order. Note that it is possible to have an element in the second array that doesn't appear in the first. In that case, we use the special version of the dictionary lookup to return Int.max for the position. This will cause all UnitMass values without a position to be sorted to the end of the array.

Find all similar values in an array and group together into a new array

The problem: I have an array of objects, where the object has an x value. Each object also needs a y value, to be plotted on a Scatterplot. The y value needs to be a number between a min height(.3) and a max height(.6), and be evenly spaced based on the number of equal x values.
For example, if I have an array of objects where [(x=3)(x=4)(x=3)(x=4)(x=5)(x=3)], after iterating through the array I should have a new array of objects that looks like this: [(x=3, y=.3)(x=3, y=.45)(x=4, y=.6)(x=4, y=.3)(x=4, y=.6)(x=5, y=.45)].
The Question: What is the best way to accomplish this performance wise? Are there any packages out there that will help me iterate through the array.
Currently I've created a nested forEach loop, but the code for this is long and feels dirty to me. Any suggestions would be great :)
This is in an angular 4 project (typescript).
You definitely need the map function:
Check documantation at https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/map
With map you can transform you array into a new array, this way:
var array = [{"x" : 3}, {"x" : 4}, {"x": 5}, {"x" : 3}];
var counter = 1;
var newArray = array.map(object => {
var calculatedY = counter;
counter++;
//just an example, you have to calculate your y based on your conditions
return { x : object.x, y : calculatedY }
})
console.log(newArray);

Store value in an array

I am fairly new to Go. I have coded in JavaScript where I could do this:
var x = [];
x[0] = 1;
This would work fine. But in Go, I am trying to implement the same thing with Go syntax. But that doesn't help. I need to have a array with unspecified index number.
I did this:
var x []string
x[0] = "name"
How do I accomplish that?
When you type:
var x []string
You create a slice, which is similar to an array in Javascript. But unlike Javascript, a slice has a set length and capacity. In this case, you get a nil slice which has the length and capacity of 0.
A few examples of how you can do it:
x := []string{"name"} // Creates a slice with length 1
y := make([]string, 10) // Creates a slice with length 10
y[0] = "name" // Set the first index to "name". The remaining 9 will be ""
var z []string // Create an empty nil slice
z = append(z, "name") // Appends "name" to the slice, creating a new slice if required
More indepth reading about slices:
Go slices usage and internals
In JavaScript arrays are dynamic in the sense that if you set the element of an array using an index which is greater than or equal to its length (current number of elements), the array will be automatically extended to have the required size to set the element (so the index you use will become the array's new length).
Arrays and slices in Go are not that dynamic. When setting elements of an array or slice, you use an index expression to designate the element you want to set. In Go you can only use index values that are in range, which means the index value must be 0 <= index < length.
In your code:
var x []string
x[0] = "name"
The first line declares a variable named x of type []string. This is a slice, and its value will be nil (the zero value of all slice types, because you did not provide an initialization value). It will have a length of 0, so the index value 0 is out of range as it is not less that the length.
If you know the length in advance, create your array or slice with that, e.g.:
var arr [3]string // An array with length of 3
var sli = make([]string, 3) // A slice with length of 3
After the above declarations, you can refer to (read or write) values at indicies 0, 1, and 2.
You may also use a composite literal to create and initialize the array or slice in one step, e.g.
var arr = [3]string{"one", "two", "three"} // Array
var sli = []string{"one", "two", "three"} // Slice
You can also use the builtin append() function to add a new element to the end of a slice. The append() function allocates a new, bigger array/slice under the hood if needed. You also need to assign the return value of append():
var x []string
x = append(x, "name")
If you want dynamic "arrays" similar to arrays of JavaScript, the map is a similar construct:
var x = map[int]string{}
x[0] = "name"
(But a map also needs initialization, in the above example I used a composite literal, but we could have also written var x = make(map[int]string).)
You may assign values to keys without having to declare the intent in prior. But know that maps are not slices or arrays, maps typically not hold values for contiguous ranges of index keys (but may do so), and maps do not maintain key or insertion order. See Why can't Go iterate maps in insertion order? for details.
Must read blog post about arrays and slices: Go Slices: usage and internals
Recommended questions / answers for a better understanding:
Why have arrays in Go?
How do I initialize an array without using a for loop in Go?
How do I find the size of the array in go
Keyed items in golang array initialization
Are golang slices pass by value?
Can you please use var x [length]string; (where length is size of the array you want) instead of var x []string; ?
In Go defining a variable like var x=[]int creates a slice of type integer. Slices are dynamic and when you want to add an integer to the slice, you have to append it like x = append(x, 1) (or x = append(x, 2, 3, 4) for multiple).
As srxf mentioned, have you done the Go tour? There is a page about slices.
I found out that the way to do it is through a dynamic array. Like this
type mytype struct {
a string
}
func main() {
a := []mytype{mytype{"name1"}}
a = append(a, mytype{"name 2"})
fmt.Println(a);
}
golang playground link: https://play.golang.org/p/owPHdQ6Y6e

Swift - array of strings to multiple subarrays with constant number of strings

Let's say I have this array of strings:
let Vehicles = ["Aeroplane", "Bicycle", "CarVehicle", "Lorry", "Motorbike", "Scooter", "Ship", "Train"]
What I want is this result:
let resultArray = [["Aeroplane", "Bicycle", "CarVehicle", "Lorry"], ["Motorbike", "Scooter", "Ship", "Train"]]
I know I could do this by for but I want to use Higher Order functions in Swift. I mean functions like map, reduce, filter. I think it's possible to do this way and it could be better. Can anyone help me with this? Thanks
A possible solution with map() and stride():
let vehicles = ["Aeroplane", "Bicycle", "CarVehicle", "Lorry", "Motorbike", "Scooter", "Ship", "Train"]
let each = 4
let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
vehicles[$0 ..< advance($0, each, vehicles.count)]
}
println(resultArray)
// [[Aeroplane, Bicycle, CarVehicle, Lorry], [Motorbike, Scooter, Ship, Train]]
The usage of advance() in the closure guarantees that the code
works even if the number of array elements is not a multiple of 4
(and the last subarray in the result will then be shorter.)
You can simplify it to
let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
vehicles[$0 ..< $0 + each]
}
if you know that the number of array elements is a multiple of 4.
Strictly speaking the elements of resultArray are not arrays
but array slices. In many cases that does not matter, otherwise you
can replace it by
let resultArray = map(stride(from: 0, to: vehicles.count, by: each)) {
Array(vehicles[$0 ..< advance($0, each, vehicles.count)])
}

swift getting an array from something like array[0..<10]

I want to get a range of objects from an array. Something like this:
var array = [1,3,9,6,3,4,7,4,9]
var newArray = array[1...3] //[3,9,6]
The above would access elements from index 1 to 3.
Also this:
newArray = array[1,5,3] // [3,4,6] would be cool
This would retrieve elements from index 1, 5 and 3 respectively.
That last example can be achieved using PermutationGenerator:
let array = [1,3,9,6,3,4,7,4,9]
let perms = PermutationGenerator(elements: array, indices: [1,5,3])
// perms is now a sequence of the values in array at indices 1, 5 and 3:
for x in perms {
// iterate over x = 3, 4 and 6
}
If you really need an array (just the sequence may be enough for your purposes) you can pass it into Array's init method that takes a sequence:
let newArray = Array(perms)
// newArray is now [3, 4, 6]
For your first example - with arrays, that will work as-is. But it looks from your comments like you're trying it with strings as well. Strings in Swift are not random-access (for reasons relating to unicode). So you can't use integers, they have an String-specific bidirectional index type:
let s = "Hello, I must be going"
if let i = find(s, "I") {
// prints "I must be going"
println(s[i..<s.endIndex])
}
This works :
var n = 4
var newArray = array[0..<n]
In any case in
Slicing Arrays in Swift you'll find a very nice sample of the Python slice using a extension to Arrays in Swift.

Resources