Posts

Showing posts with the label Arrays

Array Of Object Deep Comparison With Lodash

Answer : You can make use of differenceWith() with an isEqual() comparator, and invoke isEmpty to check if they are equal or not. var isArrayEqual = function(x, y) { return _(x).differenceWith(y, _.isEqual).isEmpty(); }; var result1 = isArrayEqual( [{a:1, b:2}, {c:3, d:4}], [{b:2, a:1}, {d:4, c:3}] ); var result2 = isArrayEqual( [{a:1, b:2, c: 1}, {c:3, d:4}], [{b:2, a:1}, {d:4, c:3}] ); document.write([ '<div><label>result1: ', result1, '</label></div>', '<div><label>result2: ', result2, '</label></div>', ].join('')); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script> UPDATE June 22, 2018 This update is in response to the comment below: @ryeballar if any of the array is undefined it returns true. How would you solve this. Thanks in advance buddy As stated in the differenceWith documentation: ...

Can PostgreSQL Index Array Columns?

Answer : Yes you can index an array, but you have to use the array operators and the GIN-index type. Example: CREATE TABLE "Test"("Column1" int[]); INSERT INTO "Test" VALUES ('{10, 15, 20}'); INSERT INTO "Test" VALUES ('{10, 20, 30}'); CREATE INDEX idx_test on "Test" USING GIN ("Column1"); -- To enforce index usage because we have only 2 records for this test... SET enable_seqscan TO off; EXPLAIN ANALYZE SELECT * FROM "Test" WHERE "Column1" @> ARRAY[20]; Result: Bitmap Heap Scan on "Test" (cost=4.26..8.27 rows=1 width=32) (actual time=0.014..0.015 rows=2 loops=1) Recheck Cond: ("Column1" @> '{20}'::integer[]) -> Bitmap Index Scan on idx_test (cost=0.00..4.26 rows=1 width=0) (actual time=0.009..0.009 rows=2 loops=1) Index Cond: ("Column1" @> '{20}'::integer[]) Total runtime:...

Are Arrays Passed By Value Or Passed By Reference In Java?

Answer : Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value). When you pass an array to other method, actually the reference to that array is copied. Any changes in the content of array through that reference will affect the original array. But changing the reference to point to a new array will not change the existing reference in original method. See this post: Is Java "pass-by-reference" or "pass-by-value"? See this working example: public static void changeContent(int[] arr) { // If we change the content of arr. arr[0] = 10; // Will change the content of array in main() } public static void changeRef(int[] arr) { // If we change the reference arr = new int[2]; // Will not change the array in main() arr[0] = 15; } public static void main(String[] args) { int [] arr = new int[2]; arr[0] = 4; ...

Array.groupBy In TypeScript

Answer : You can use the following code to group stuff using Typescript. const groupBy = <T, K extends keyof any>(list: T[], getKey: (item: T) => K) => list.reduce((previous, currentItem) => { const group = getKey(currentItem); if (!previous[group]) previous[group] = []; previous[group].push(currentItem); return previous; }, {} as Record<K, T[]>); So, if you have the following structure and array: type Person = { name: string; age: number; }; const people: Person[] = [ { name: "Kevin R", age: 25, }, { name: "Susan S", age: 18, }, { name: "Julia J", age: 18, }, { name: "Sarah C", age: 25, }, ]; You can invoke it like: const results = groupBy(people, i => i.name); Which in this case, will give you an object with string keys, and Person[] values. There are a few key concepts here: 1- You can use function to get the key, this way you can use TS...

Class-validator - Validate Array Of Objects

Answer : Add @Type(() => AuthParam) to your array and it should be working. Type decorator is required for nested objects(arrays). Your code becomes import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator'; import { AuthParam } from './authParam.model'; import { Type } from 'class-transformer'; export class SignInModel { @IsArray() @ValidateNested({ each: true }) @ArrayMinSize(2) @ArrayMaxSize(2) @Type(() => AuthParam) authParameters: AuthParam[]; } Be careful if you are using any exception filter to modify the error reponse. Make sure you understand the structure of the class-validator errors. You can use the following: validator.arrayNotEmpty(array); // Checks if given array is not empty. validator.arrayMinSize(array, min); // Checks if array's length is at least `min` number. (https://github.com/typestack/class-validator#manual-validation) You may want to consider writing custom validator w...

C Char Array Initialization

Answer : This is not how you initialize an array, but for: The first declaration: char buf[10] = ""; is equivalent to char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; The second declaration: char buf[10] = " "; is equivalent to char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0}; The third declaration: char buf[10] = "a"; is equivalent to char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0}; As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0 . This the case even if the array is declared inside a function. Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer. Your code will result in compiler errors. Your first code fragment: char buf[10] ; buf = '' is doubly illegal. First, in C, there is no such thing as an empty char . You can use double quote...

Appending An Element To The End Of A List In Scala

Answer : List(1,2,3) :+ 4 Results in List[Int] = List(1, 2, 3, 4) Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer). That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this: (4 :: List(1,2,3).reverse).reverse or that: List(1,2,3) ::: List(4) Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List ; it's an immutable data structure , like a Java String. What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List . (Source) Instead of using lists for such use cases, I suggest to either use an ArrayBuffer or a ListBuffer . Those data...

Change $key Of Associative Array In A Foreach Loop In Php

Answer : unset it first in case it is already in the proper format, otherwise you will remove what you just defined: foreach($array as $key => $value) { unset($array[$key]); $array[ucfirst($key)] = $value; } You can't modify the keys in a foreach , so you would need to unset the old one and create a new one. Here is another way: $array = array_combine(array_map('ucfirst', array_keys($array)), $array); Get the keys using array_keys Apply ucfirst to the keys using array_map Combine the new keys with the values using array_combine The answers here are dangerous, in the event that the key isn't changed, the element is actually deleted from the array. Also, you could unknowingly overwrite an element that was already there. You'll want to do some checks first: foreach($array as $key => $value) { $newKey = ucfirst($key); // does this key already exist in the array? if(isset($array[$newKey])){ // yes, sk...

Absolute Difference Of Two NumPy Arrays

Answer : If you want the absolute element-wise difference between both matrices, you can easily subtract them with NumPy and use numpy.absolute on the resulting matrix. import numpy as np X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = np.absolute(np.array(X) - np.array(Y)) Outputs : [[7 1 2] [2 2 3] [3 3 0]] Alternatively ( although unnecessary ), if you were required to do so in native Python you could zip the dimensions together in a nested list comprehension. result = [[abs(a-b) for a, b in zip(xrow, yrow)] for xrow, yrow in zip(X,Y)] Outputs : [[7, 1, 2], [2, 2, 3], [3, 3, 0]] Doing this becomes trivial if you cast your 2D arrays to numpy arrays: import numpy as np X = [[12, 7, 3], [4, 5, 6], [7, 8, 9]] Y = [[5, 8, 1], [6, 7, 3], [4, 5, 9]] X, Y = map(np.array, (X, Y)) result = X - Y Numpy is designed to work easily and efficiently with matrices. Also, you spoke about subtracting mat...

Advantages Of Using Arrays Instead Of Std::vector?

Answer : In general, I strongly prefer using a vector over an array for non-trivial work; however, there are some advantages of arrays: Arrays are slightly more compact: the size is implicit. Arrays are non-resizable; sometimes this is desirable. Arrays don't require parsing extra STL headers (compile time). It can be easier to interact with straight-C code with an array (e.g. if C is allocating and C++ is using). Fixed-size arrays can be embedded directly into a struct or object, which can improve memory locality and reducing the number of heap allocations needed. Because C++03 has no vector literals. Using arrays can sometime produce more succinct code. Compared to array initialization: char arr[4] = {'A', 'B', 'C', 'D'}; vector initialization can look somewhat verbose std::vector<char> v; v.push_back('A'); v.push_back('B'); ... I'd go for std::array available in C++0x instead of plain arrays which can...

2D Peak Finding Algorithm In O(n) Worst Case Time?

Answer : Let's assume that width of the array is bigger than height, otherwise we will split in another direction. Split the array into three parts: central column, left side and right side. Go through the central column and two neighbour columns and look for maximum. If it's in the central column - this is our peak If it's in the left side, run this algorithm on subarray left_side + central_column If it's in the right side, run this algorithm on subarray right_side + central_column Why this works: For cases where the maximum element is in the central column - obvious. If it's not, we can step from that maximum to increasing elements and will definitely not cross the central row, so a peak will definitely exist in the corresponding half. Why this is O(n): step #3 takes less than or equal to max_dimension iterations and max_dimension at least halves on every two algorithm steps. This gives n+n/2+n/4+... which is O(n) . Important detail: we split...

Array Of JSON Object To Java POJO

Image
Answer : This kind of question is very popular and needs general answer. In case you need generate POJO model based on JSON or JSON Schema use www.jsonschema2pojo.org. Example print screen shows how to use it: How to use it: Select target language. Java in your case. Select source. JSON in your case. Select annotation style. This can be tricky because it depends from library you want to use to serialise/deserialise JSON . In case schema is simple do not use annotations ( None option). Select other optional configuration options like Include getters and setters . You can do that in your IDE as well. Select Preview button. In case schema is big download ZIP with generated classes. For your JSON this tool generates: public class Person { private String ownerName; private List <Pet> pets = null; public String getOwnerName() { return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public List < Pet ...

Alternative For Define Array Php

Answer : From php.net... The value of the constant; only scalar and null values are allowed . Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior. But You can do with some tricks : define('names', serialize(array('John', 'James' ...))); & You have to use unserialize() the constant value (names) when used. This isn't really that useful & so just define multiple constants instead: define('NAME1', 'John'); define('NAME2', 'James'); .. And print like this: echo constant('NAME'.$digit); This has changed in newer versions of PHP, as stated in the PHP manual From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant .
Answer : Two errors here: first, you're trying to declare arrays[63] for storing 64 elements, as you've probably confused the size of array ( n ) with the maximum possible index value (that's n - 1 ). So it definitely should be litera[64] and liczba[64] . BTW, you have to change this line too - while (i<=64) : otherwise you end up trying to access 65th element. And second, you're trying to fill char value with %s format specifier for scanf, while you should have used %c here. Also, can't help wondering why you declare liczba array as one that stores int s, that initialize it with array of char s. All these '1', '2', etc... literals represent NOT the corresponding digits - but the charcodes for them. I doubt that was your intent.

Any Way To Make JQuery.inArray() Case Insensitive?

Answer : In case anyone wanted a more integrated approach using jquery: (function($){ $.extend({ // Case insensative $.inArray (http://api.jquery.com/jquery.inarray/) // $.inArrayIn(value, array [, fromIndex]) // value (type: String) // The value to search for // array (type: Array) // An array through which to search. // fromIndex (type: Number) // The index of the array at which to begin the search. // The default is 0, which will search the whole array. inArrayIn: function(elem, arr, i){ // not looking for a string anyways, use default method if (typeof elem !== 'string'){ return $.inArray.apply(this, arguments); } // confirm array is populated if (arr){ var len = arr.length; i = i ? (i < 0 ? Math.max(0, len + i) : i) : 0; elem = elem.toLowerCa...

Adding Custom Functions Into Array.prototype

Answer : Modifying the built-in object prototypes is a bad idea in general, because it always has the potential to clash with code from other vendors or libraries that loads on the same page. In the case of the Array object prototype, it is an especially bad idea, because it has the potential to interfere with any piece of code that iterates over the members of any array, for instance with for .. in . To illustrate using an example (borrowed from here): Array.prototype.foo = 1; // somewhere deep in other javascript code... var a = [1,2,3,4,5]; for (x in a){ // Now foo is a part of EVERY array and // will show up here as a value of 'x' } Unfortunately, the existence of questionable code that does this has made it necessary to also avoid using plain for..in for array iteration, at least if you want maximum portability, just to guard against cases where some other nuisance code has modified the Array prototype. So you really need to do both: you should avoid...

Array.prototype.fill() With Object Passes Reference And Not New Instance

Answer : You can first fill the array with any value (e.g. undefined ), and then you will be able to use map : var arr = new Array(2).fill().map(u => ({})); var arr = new Array(2).fill().map(Object); The accepted answer is good and would work in 90% of cases. But if you are making high-performance JS application, and if you work with big/huge arrays, Array.map(..) creates big overload in both - memory and processor use, as it creates a copy of an array. I recommend to use the classic for loop: a = new Array(ARRAY_SIZE); for (var i = 0; i < ARRAY_SIZE; i++) { a[i] = []; } I tested six alternatives and got this: Array.map() , as proposed above ( 11x times!!! slower): a = new Array(ARRAY_SIZE).fill().map(u => { return []; }); for loop , the best one ( fastest ): a = new Array(ARRAY_SIZE); for (var i = 0; i < ARRAY_SIZE; i++) { a[i] = []; } forEach ( 6x time slower): a = new Array(ARRAY_SIZE).fill(); a.forEach((val, i) ...

Android: How Do You Access A String-array From Strings.xml In A Custom Class?

Answer : Pass the context to the constructor of custom class and use the same new CustomClass(ActivityName.this); Then Context mContext; public CustomClass(Context context) { mContext = context; } use the context String[] foo_array = mContext.getResources().getStringArray(R.array.foo_array); Also keep in mind Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself) http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html Also check this android getResources() from non-Activity class Edit: Change this public class CustomClass(Context context) { } To public class CustomClass { Context mContext; public CustomClass(Context context) // constructor { mContext = context; } } try this, Context context=getApplicationContext(); String[] foo_array = context.getResources().getStringArray(R.array.foo_array); And, do not use Activity Context a...