Posts

Showing posts with the label Arrays

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 .

Copy Const Array To Dynamic Array In Delphi

Answer : This will copy constAry1 to dynAry . SetLength(dynAry, Length(constAry1)); Move(constAry1[Low(constAry1)], dynAry[Low(dynAry)], SizeOf(constAry1)); function CopyByteArray(const C: array of Byte): TByteDynArray; begin SetLength(Result, Length(C)); Move(C[Low(C)], Result[0], Length(C)); end; procedure TFormMain.Button1Click(Sender: TObject); const C: array[1..10] of Byte = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); var D: TByteDynArray; I: Integer; begin D := CopyByteArray(C); for I := Low(D) to High(D) do OutputDebugString(PChar(Format('%d: %d', [I, D[I]]))); end; procedure TFormMain.Button2Click(Sender: TObject); const C: array[1..10, 1..10] of Byte = ( (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (1, 2, ...

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...

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:...

Creating An Associative Array In JavaScript Using The Map Function

Answer : You may use Array.prototype.reduce for your task. It allows a return value in the callback function for the next call. var data = [ { 'list': 'one', 'item': 1 }, { 'list': 'one', 'item': 2 }, { 'list': 'one', 'item': 3 }, { 'list': 'two', 'item': 1 }, { 'list': 'two', 'item': 2 } ], flat = data.reduce(function (r, a) { r[a.list] = r[a.list] || []; r[a.list].push(a.item); return r; }, {}); document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');

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...

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...

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...

Convert Javascript Array To String

Answer : If value is associative array, such code will work fine: var value = { "aaa": "111", "bbb": "222", "ccc": "333" }; var blkstr = []; $.each(value, function(idx2,val2) { var str = idx2 + ":" + val2; blkstr.push(str); }); console.log(blkstr.join(", ")); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> (output will appear in the dev console) As Felix mentioned, each() is just iterating the array, nothing more. Converting From Array to String is So Easy ! var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday'] array = A + "" That's it Now A is a string. :) You can use .toString() to join an array with a comma. var array = ['a', 'b', 'c']; array.toString(); // result: a,b,c Or, set the separator with array.join('; '); // r...

Convert Map To JSON Object In Javascript

Answer : Given in MDN, fromEntries() is available since Node v12: const map1 = new Map([ ['foo', 'bar'], ['baz', 42] ]); const obj = Object.fromEntries(map1); // { foo: 'bar', baz: 42 } For converting object back to map: const map2 = new Map(Object.entries(obj)); // Map(2) { 'foo' => 'bar', 'baz' => 42 } I hope this function is self-explanatory enough. This is what I used to do the job. /* * Turn the map<String, Object> to an Object so it can be converted to JSON */ function mapToObj(inputMap) { let obj = {}; inputMap.forEach(function(value, key){ obj[key] = value }); return obj; } JSON.stringify(returnedObject) You could loop over the map and over the keys and assign the value function createPaths(aliases, propName, path) { aliases.set(propName, path); } var map = new Map(), object = {}; createPaths(map, 'paths.aliases.server.entry', 'src/test'); createPaths(ma...
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.

Convert List To Array In Java

Answer : Either: Foo[] array = list.toArray(new Foo[0]); or: Foo[] array = new Foo[list.size()]; list.toArray(array); // fill the array Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way: List<Integer> list = ...; int[] array = new int[list.size()]; for(int i = 0; i < list.size(); i++) array[i] = list.get(i); Update: It is recommended now to use list.toArray(new Foo[0]); , not list.toArray(new Foo[list.size()]); . From JetBrains Intellij Idea inspection: There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()]) ) or using an empty array (like c.toArray(new String[0]) . In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty a...

Convert A PHP Object To An Associative Array

Answer : Just typecast it $array = (array) $yourObject; From Arrays : If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. Example: Simple Object $object = new StdClass; $object->foo = 1; $object->bar = 2; var_dump( (array) $object ); Output: array(2) { 'foo' => int(1) 'bar' => int(2) } Example: Complex Object class Foo { private $foo; protected $bar; public $baz; public function __construct() { $this->foo = 1; $this->bar = 2; $this->baz = new StdClass; } } var_dump( (array) new Foo ); Output (with \0s edited in for clarity): array(3) { ...

Convert ByteBuffer To Byte Array Java

Answer : ByteBuffer exposes the bulk get(byte[]) method which transfers bytes from the buffer into the array. You'll need to instantiate an array of length equal to the number of remaining bytes in the buffer. ByteBuffer buf = ... byte[] arr = new byte[buf.remaining()]; buf.get(arr); If hasArray() reports false then, calling array() will throw an exception. In that case, the only way to get the data in a byte[] is to allocate a byte[] and copy the bytes to the byte[] using get(byte) or similar.

Convert StdClass Object To Array In PHP

Answer : The easiest way is to JSON-encode your object and then decode it back to an array: $array = json_decode(json_encode($object), true); Or if you prefer, you can traverse the object manually, too: foreach ($object as $value) $array[] = $value->post_id; Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative. Take that result and decode with an extra parameter of true, where it will convert to associative array $array = json_decode(json_encode($oObject),true); Try this: $new_array = objectToArray($yourObject); function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); } e...

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...

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...