Search Results

Search found 4320 results on 173 pages for 'vertex arrays'.

Page 4/173 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Arithmetic Operations in Arrays with PHP

    - by Ajith
    I have two arrays $data1 = array() $data1 = array( '10','22','30') and also another array carries $data2 = array() $data2 = array( '2','11','3'); I need to divide these two arrays(ie,$data1/$data2) and store value to $data3[]. I need to get it as follows $data3[] = array('5','2','10') If someone knows of an easy way to do this would be of great help. Thanks

    Read the article

  • Concatenating an array of arrays in Coffeescript

    - by user380572
    Hi everyone, I'm trying to find an elegant way in Coffeescript to merge an array of arrays, so that [[1,2,3],[4,5,6],[7,8,9]] == [1,2,3,4,5,6,7,8,9]. As you might imagine, I need this because I'm generating arrays from a function in a "for in" construct and need to concatenate the resulting nested array: result = (generate_array(x) for x in arr) Is there an elegant way to handle this? Thanks for any pointers!

    Read the article

  • C# Generic Arrays and math operations on it

    - by msedi
    Hello, I'm currently involved in a project where I have very large image volumes. This volumes have to processed very fast (adding, subtracting, thresholding, and so on). Additionally most of the volume are so large that they event don't fit into the memory of the system. For that reason I have created an abstract volume class (VoxelVolume) that host the volume and image data and overloads the operators so that it's possible to perform the regular mathematical operations on volumes. Thereby two more questions opened up which I will put into stackoverflow into two additional threads. Here is my first question. My volume is implemented in a way that it only can contain float array data, but most of the containing data is from an UInt16 image source. Only operations on the volume can create float array images. When I started implementing such a volume the class looked like following: public abstract class VoxelVolume<T> { ... } but then I realized that overloading the operators or return values would get more complicated. An example would be: public abstract class VoxelVolume<T> { ... public static VoxelVolume<T> Import<T>(param string[] files) { } } also adding two overloading operators would be more complicated: ... public static VoxelVolume<T> operator+(VoxelVolume<T> A, VoxelVolume<T> B) { ... } Let's assume I can overcome the problems described above, nevertheless I have different types of arrays that contain the image data. Since I have fixed my type in the volumes to float the is no problem and I can do an unsafe operation when adding the contents of two image volume arrays. I have read a few threads here and had a look around the web, but found no real good explanation of what to do when I want to add two arrays of different types in a fast way. Unfortunately every math operation on generics is not possible, since C# is not able to calculate the size of the underlying data type. Of course there might by a way around this problem by using C++/CLR, but currently everything I have done so far, runs in 32bit and 64bit without having to do a thing. Switching to C++/CLR seemed to me (pleased correct me if I'm wrong) that I'm bound to a certain platform (32bit) and I have to compile two assemblies when I let the application run on another platform (64bit). Is this true? So asked shortly: How is it possible to add two arrays of two different types in a fast way. Is it true that the developers of C# haven't thought about this. Switching to a different language (C# - C++) seems not to be an option. I realize that simply performing this operation float []A = new float[]{1,2,3}; byte []B = new byte[]{1,2,3}; float []C = A+B; is not possible and unnecessary although it would be nice if it would work. My solution I was trying was following: public static class ArrayExt { public static unsafe TResult[] Add<T1, T2, TResult>(T1 []A, T2 []B) { // Assume the length of both arrays is equal TResult[] result = new TResult[A.Length]; GCHandle h1 = GCHandle.Alloc (A, Pinned); GCHandle h2 = GCHandle.Alloc (B, Pinned); GCHandle hR = GCHandle.Alloc (C, Pinned); void *ptrA = h1.ToPointer(); void *ptrB = h2.ToPointer(); void *ptrR = hR.ToPointer(); for (int i=0; i<A.Length; i++) { *((TResult *)ptrR) = (TResult *)((T1)*ptrA + (T2)*ptrB)); } h1.Free(); h2.Free(); hR.Free(); return result; } } Please excuse if the code above is not quite correct, I wrote it without using an C# editor. Is such a solution a shown above thinkable? Please feel free to ask if I made a mistake or described some things incompletely. Thanks for your help Martin

    Read the article

  • creating objects from trivial graph format text file. java. dijkstra algorithm.

    - by user560084
    i want to create objects, vertex and edge, from trivial graph format txt file. one of programmers here suggested that i use trivial graph format to store data for dijkstra algorithm. the problem is that at the moment all the information, e.g., weight, links, is in the sourcecode. i want to have a separate text file for that and read it into the program. i thought about using a code for scanning through the text file by using scanner. but i am not quite sure how to create different objects from the same file. could i have some help please? the file is v0 Harrisburg v1 Baltimore v2 Washington v3 Philadelphia v4 Binghamton v5 Allentown v6 New York # v0 v1 79.83 v0 v5 81.15 v1 v0 79.75 v1 v2 39.42 v1 v3 103.00 v2 v1 38.65 v3 v1 102.53 v3 v5 61.44 v3 v6 96.79 v4 v5 133.04 v5 v0 81.77 v5 v3 62.05 v5 v4 134.47 v5 v6 91.63 v6 v3 97.24 v6 v5 87.94 and the dijkstra algorithm code is Downloaded from: http://en.literateprograms.org/Special:Downloadcode/Dijkstra%27s_algorithm_%28Java%29 */ import java.util.PriorityQueue; import java.util.List; import java.util.ArrayList; import java.util.Collections; class Vertex implements Comparable<Vertex> { public final String name; public Edge[] adjacencies; public double minDistance = Double.POSITIVE_INFINITY; public Vertex previous; public Vertex(String argName) { name = argName; } public String toString() { return name; } public int compareTo(Vertex other) { return Double.compare(minDistance, other.minDistance); } } class Edge { public final Vertex target; public final double weight; public Edge(Vertex argTarget, double argWeight) { target = argTarget; weight = argWeight; } } public class Dijkstra { public static void computePaths(Vertex source) { source.minDistance = 0.; PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertexQueue.add(source); while (!vertexQueue.isEmpty()) { Vertex u = vertexQueue.poll(); // Visit each edge exiting u for (Edge e : u.adjacencies) { Vertex v = e.target; double weight = e.weight; double distanceThroughU = u.minDistance + weight; if (distanceThroughU < v.minDistance) { vertexQueue.remove(v); v.minDistance = distanceThroughU ; v.previous = u; vertexQueue.add(v); } } } } public static List<Vertex> getShortestPathTo(Vertex target) { List<Vertex> path = new ArrayList<Vertex>(); for (Vertex vertex = target; vertex != null; vertex = vertex.previous) path.add(vertex); Collections.reverse(path); return path; } public static void main(String[] args) { Vertex v0 = new Vertex("Nottinghill_Gate"); Vertex v1 = new Vertex("High_Street_kensignton"); Vertex v2 = new Vertex("Glouchester_Road"); Vertex v3 = new Vertex("South_Kensignton"); Vertex v4 = new Vertex("Sloane_Square"); Vertex v5 = new Vertex("Victoria"); Vertex v6 = new Vertex("Westminster"); v0.adjacencies = new Edge[]{new Edge(v1, 79.83), new Edge(v6, 97.24)}; v1.adjacencies = new Edge[]{new Edge(v2, 39.42), new Edge(v0, 79.83)}; v2.adjacencies = new Edge[]{new Edge(v3, 38.65), new Edge(v1, 39.42)}; v3.adjacencies = new Edge[]{new Edge(v4, 102.53), new Edge(v2, 38.65)}; v4.adjacencies = new Edge[]{new Edge(v5, 133.04), new Edge(v3, 102.53)}; v5.adjacencies = new Edge[]{new Edge(v6, 81.77), new Edge(v4, 133.04)}; v6.adjacencies = new Edge[]{new Edge(v0, 97.24), new Edge(v5, 81.77)}; Vertex[] vertices = { v0, v1, v2, v3, v4, v5, v6 }; computePaths(v0); for (Vertex v : vertices) { System.out.println("Distance to " + v + ": " + v.minDistance); List<Vertex> path = getShortestPathTo(v); System.out.println("Path: " + path); } } } and the code for scanning file is import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class DataScanner1 { //private int total = 0; //private int distance = 0; private String vector; private String stations; private double [] Edge = new double []; /*public int getTotal(){ return total; } */ /* public void getMenuInput(){ KeyboardInput in = new KeyboardInput; System.out.println("Enter the destination? "); String val = in.readString(); return val; } */ public void readFile(String fileName) { try { Scanner scanner = new Scanner(new File(fileName)); scanner.useDelimiter (System.getProperty("line.separator")); while (scanner.hasNext()) { parseLine(scanner.next()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void parseLine(String line) { Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("\\s*,\\s*"); vector = lineScanner.next(); stations = lineScanner.next(); System.out.println("The current station is " + vector + " and the destination to the next station is " + stations + "."); //total += distance; //System.out.println("The total distance is " + total); } public static void main(String[] args) { /* if (args.length != 1) { System.err.println("usage: java TextScanner2" + "file location"); System.exit(0); } */ DataScanner1 scanner = new DataScanner1(); scanner.readFile(args[0]); //int total =+ distance; //System.out.println(""); //System.out.println("The total distance is " + scanner.getTotal()); } }

    Read the article

  • what is the point of heterogenous arrays?

    - by aharon
    I know that more-dynamic-than-Java languages, like Python and Ruby, often allow you to place objects of mixed types in arrays, like so: ["hello", 120, ["world"]] What I don't understand is why you would ever use a feature like this. If I want to store heterogenous data in Java, I'll usually create an object for it. For example, say a User has int ID and String name. While I see that in Python/Ruby/PHP you could do something like this: [["John Smith", 000], ["Smith John", 001], ...] this seems a bit less safe/OO than creating a class User with attributes ID and name and then having your array: [<User: name="John Smith", id=000>, <User: name="Smith John", id=001>, ...] where those <User ...> things represent User objects. Is there reason to use the former over the latter in languages that support it? Or is there some bigger reason to use heterogenous arrays? N.B. I am not talking about arrays that include different objects that all implement the same interface or inherit from the same parent, e.g.: class Square extends Shape class Triangle extends Shape [new Square(), new Triangle()] because that is, to the programmer at least, still a homogenous array as you'll be doing the same thing with each shape (e.g., calling the draw() method), only the methods commonly defined between the two.

    Read the article

  • Problem when copying array of different types using Arrays.copyOf

    - by Shervin
    I am trying to create a method that pretty much takes anything as a parameter, and returns a concatenated string representation of the value with some delimiter. public static String getConcatenated(char delim, Object ...names) { String[] stringArray = Arrays.copyOf(names, names.length, String[].class); //Exception here return getConcatenated(delim, stringArray); } And the actual method public static String getConcatenated(char delim, String ... names) { if(names == null || names.length == 0) return ""; StringBuilder sb = new StringBuilder(); for(int i = 0; i < names.length; i++) { String n = names[i]; if(n != null) { sb.append(n.trim()); sb.append(delim); } } //Remove the last delim return sb.substring(0, sb.length()-1).toString(); } And I have the following JUnit test: final String two = RedpillLinproUtils.getConcatenated(' ', "Shervin", "Asgari"); Assert.assertEquals("Result", "Shervin Asgari", two); //OK final String three = RedpillLinproUtils.getConcatenated(';', "Shervin", "Asgari"); Assert.assertEquals("Result", "Shervin;Asgari", three); //OK final String four = RedpillLinproUtils.getConcatenated(';', "Shervin", null, "Asgari", null); Assert.assertEquals("Result", "Shervin;Asgari", four); //OK final String five = RedpillLinproUtils.getConcatenated('/', 1, 2, null, 3, 4); Assert.assertEquals("Result", "1/2/3/4", five); //FAIL However, the test fails on the last part with the exception: java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.Arrays.copyOf(Arrays.java:2763) Can someone spot the error?

    Read the article

  • [numpy] storing record arrays in object arrays

    - by Peter Prettenhofer
    I'd like to convert a list of record arrays -- dtype is (uint32, float32) -- into a numpy array of dtype np.object: X = np.array(instances, dtype = np.object) where instances is a list of arrays with data type np.dtype([('f0', '<u4'), ('f1', '<f4')]). However, the above statement results in an array whose elements are also of type np.object: X[0] array([(67111L, 1.0), (104242L, 1.0)], dtype=object) Does anybody know why? The following statement should be equivalent to the above but gives the desired result: X = np.empty((len(instances),), dtype = np.object) X[:] = instances X[0] array([(67111L, 1.0), (104242L, 1.0), dtype=[('f0', '<u4'), ('f1', '<f4')]) thanks & best regards, peter

    Read the article

  • whats faster, more efficient, loading a js file with arrays or populating arrays from tables

    - by Leigh
    I am rebuilding an ecom site where the product data is stored in a multidimensional JS array that gets loaded on page load. This data is constantly being accessed with JS due to the nature of the site, to update prices based on user selections. There are many options that affect final price. From a programming standpoint, a DB table is much easier to maintain and update than are JS arrays, and since I am porting the site over to PHP and MYSQL, I have been considering moving these arrays into tables. So, would it be better to populate an array from the DB on load so that the pricing data is always available to the JS, or stay with hard coded JS files? I considered getting data via ajax as needed, but since this site has to constantly update pricing with user interaction, I have pretty much ruled that out. How would you handle it?

    Read the article

  • Get vertex colors from fbx (OpenGL, FBX SDK)

    - by instancedName
    I'm kinda stuck with this one. I managed to get vertex positions, indices, normals, but I don't quite understand how te get vertex colors. I need them to fill my buffer. I tried funcion mesh-GetElementVertexColorCount() and then to iterate trough all of them, but it returns zero. I alse tried to get layer, and then use layer-GetVertexColors(), but it returns NULL pointer. Can anyone help me with this one?

    Read the article

  • How to send multiple MVP matrices to a vertex shader in OpenGL ES 2.0

    - by Carbon Crystal
    I'm working my way through optimizing the rendering of sprites in a 2D game using OpenGL ES and I've hit the limit of my knowledge when it comes to GLSL and vertex shaders. I have two large float buffers containing my vertex coordinates and texture coordinates (eventually this will be one buffer) for multiple sprites in order to perform a single glDrawArrays call. This works but I've hit a snag when it comes to passing the transformation matrix into the vertex shader. My shader code is: uniform mat4 u_MVPMatrix; attribute vec4 a_Position; attribute vec2 a_TexCoordinate; varying vec2 v_TexCoordinate; void main() { v_TexCoordinate = a_TexCoordinate; gl_Position = u_MVPMatrix * a_Position; } In Java (Android) I am using a FloatBuffer to store the vertex/texture data and this is provided to the shader like so: mGlEs20.glVertexAttribPointer(mVertexHandle, Globals.GL_POSITION_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mVertexCoordinates); mGlEs20.glVertexAttribPointer(mTextureCoordinateHandle, Globals.GL_TEXTURE_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mTextureCoordinates); (The Globals.GL_POSITION_VERTEX_COUNT etc are just integers with the value of 2 right now) And I'm passing the MVP (Model/View/Projection) matrix buffer like this: GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mModelCoordinates); (mModelCoordinates is a FloatBuffer containing 16-float sequences representing the MVP matrix for each sprite) This renders my scene but all the sprites share the same transformation, so it's obviously only picking the first 16 elements from the buffer which makes sense since I am passing in "1" as the second parameter. The documentation for this method says: "This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices." So I tried modifying the shader with a fixed size array large enough to accomodate most of my scenarios: uniform mat4 u_MVPMatrix[1000]; But this lead to an error in the shader: cannot convert from 'uniform array of 4X4 matrix of float' to 'Position 4-component vector of float' This just seems wrong anyway as it's not clear to me how the shader would know when to transition to the next matrix anyway. Anyone have an idea how I can get my shader to pick up a different MVP matrix (i.e. the NEXT 16 floats) from my MVP buffer for every 4 vertices it encounters? (I am using GL_TRIANGLE_STRIP so each sprite has 4 vertices). Thanks!

    Read the article

  • Setting uniform value of a vertex shader for different sprites in a SpriteBatch

    - by midasmax
    I'm using libGDX and currently have a simple shader that does a passthrough, except for randomly shifting the vertex positions. This shift is a vec2 uniform that I set within my code's render() loop. It's declared in my vertex shader as uniform vec2 u_random. I have two different kind of Sprites -- let's called them SpriteA and SpriteB. Both are drawn within the same SpriteBatch's begin()/end() calls. Prior to drawing each sprite in my scene, I check the type of the sprite. If sprite instance of SpriteA: I set the uniform u_random value to Vector2.Zero, meaning that I don't want any vertex changes for it. If sprite instance of SpriteB, I set the uniform u_random to Vector2(MathUtils.random(), MathUtils.random(). The expected behavior was that all the SpriteA objects in my scene won't experience any jittering, while all SpriteB objects would be jittering about their positions. However, what I'm experiencing is that both SpriteA and SpriteB are jittering, leading me to believe that the u_random uniform is not actually being set per Sprite, and being applied to all sprites. What is the reason for this? And how can I fix this such that the vertex shader correctly accepts the uniform value set to affect each sprite individually? passthrough.vsh attribute vec4 a_color; attribute vec3 a_position; attribute vec2 a_texCoord0; uniform mat4 u_projTrans; uniform vec2 u_random; varying vec4 v_color; varying vec2 v_texCoord; void main() { v_color = a_color; v_texCoord = a_texCoord0; vec3 temp_position = vec3( a_position.x + u_random.x, a_position.y + u_random.y, a_position.z); gl_Position = u_projTrans * vec4(temp_position, 1.0); } Java Code this.batch.begin(); this.batch.setShader(shader); for (Sprite sprite : sprites) { Vector2 v = Vector2.Zero; if (sprite instanceof SpriteB) { v.x = MathUtils.random(-1, 1); v.y = MathUtils.random(-1, 1); } shader.setUniformf("u_random", v); sprite.draw(this.batch); } this.batch.end();

    Read the article

  • How to store arrays in single array

    - by Jessy
    How can I store arrays in single array? e.g. I have four different arrays, I want to store it in single array int storeAllArray [] and when I call e.g. storeAllArray[1] , I will get this output [11,65,4,3,2,9,7]instead of single elements? int array1 [] = {1,2,3,4,5,100,200,400}; int array2 [] = {2,6,5,7,2,5,10}; int array3 [] = {11,65,4,3,2,9,7}; int array4 [] = {111,33,22,55,77}; int storeAllArray [] = {array1,array2,array3,array2} // I want store all array in on array for (int i=0; i<storeAllArray; i++){ System.out.println(storeAllArray.get[0]); // e.g. will produce --> 1,2,3,4,5,100,200,400 , how can I do this? }

    Read the article

  • struct assignment operator on arrays

    - by Django fan
    Suppose I defined a structure like this: struct person { char name [10]; int age; }; and declared two person variables: person Bob; person John; where Bob.name = "Bob", Bob.age = 30 and John.name = "John",John.age = 25. and I called Bob = John; struct person would do a Memberwise assignment and assign Johns's member values to Bob's. But arrays can't assign to arrays, so how does the assignment of the "name" array work?

    Read the article

  • Problem displaying Vertex Buffer Object (OpenGL and Obj-C)

    - by seaworthy
    Hey, I am having a problem displaying or loading a buffer with an array of vertices. I know that array works fine because I am able to render it using a loop and a glVertex command. I can't figure out what's wrong. Your insight is highly appreciated. GLuint vboId; glGenBuffers( 1, &vboId ); glBindBuffer( GL_ARRAY_BUFFER, vboId); glBufferData( GL_ARRAY_BUFFER, count*sizeof( GLfloat ),array,GL_STATIC_DRAW_ARB ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); printf("%d\n",count); glEnableClientState( GL_VERTEX_ARRAY ); glBindBuffer( GL_ARRAY_BUFFER, vboId ); glVertexPointer( 3, GL_FLOAT, 0, 0 ); glDisableClientState( GL_VERTEX_ARRAY ); printf("vboId: [%hd]",vboId); glDeleteBuffers(1, &vboId); Help?

    Read the article

  • Does C99 guarantee that arrays are contiguous ?

    - by kriss
    Following an hot comment thread in another question, I came to debate of what is and what is not defined in C99 standard about C arrays. Basically when I define a 2D array like int a[5][5], does the standard C99 garantee or not that it will be a contiguous block of ints, can I cast it to (int *)a and be sure I will have a valid 1D array of 25 ints. As I understand the standard the above property is implicit in the sizeof definition and in pointer arithmetic, but others seems to disagree and says casting to (int*) the above structure give an undefined behavior (even if they agree that all existing implementations actually allocate contiguous values). More specifically, if we think an implementation that would instrument arrays to check array boundaries for all dimensions and return some kind of error when accessing 1D array, or does not give correct access to elements above 1st row. Could such implementation be standard compilant ? And in this case what parts of the C99 standard are relevant.

    Read the article

  • merging arrays of hashes

    - by Ben
    I have two arrays of hashes. Array1 => [{attribute_1 = A, attribute_2 = B}, {attribute_1 = A, attribute_2 = B}] Array2 => [{attribute_3 = C, attribute_2 = D}, {attribute_3 = C, attribute_4 = D}] Each hash in the array is holding attributes for an object. In the above example, there are two objects that I'm working with. There are two attributes in each array for each object How do I merge the two arrays? I am trying to get a single array (there is no way to get a single array from the start because I have to make two different API calls to get these attributes). DesiredArray => [{attribute_1 = A, attribute_2 = B, attribute_3 = C, attribute_2 = D}, {attribute_1 = A, attribute_2 = B, attribute_3 = C, attribute_2 = D}] I've tried a couple things, including the iteration methods and the merge method, but I've been unable to get the array I need.

    Read the article

  • Append a parent element to arrays in PHP for a foreach loop

    - by Erik Berger
    print_r of $data = json_decode($src, true); returns data that looks like this: Array ( [0] => Array ( [var1] => blah [var2] => foo ) [1] => Array ( [var1] => lorem [var2] => ipsum ) // goes down to [1936] ) I want to build an html table that shows var1 and var2 next to each other in the same row. I know do to this I need a foreach statement like foreach($data['items'] as $item) but the problem I think I am having is that my many arrays aren't the child of one thing like 'items', right? I looked into array_push but couldn't figure it out. Can someone help my orphaned parentless arrays?

    Read the article

  • I'm having an issue to use GLshort for representing Vertex, and Normal.

    - by Xylopia
    As my project gets close to optimization stage, I notice that reducing Vertex Metadata could vastly improve the performance of 3D rendering. Eventually, I've dearly searched around and have found following advices from stackoverflow. Using GL_SHORT instead of GL_FLOAT in an OpenGL ES vertex array How do you represent a normal or texture coordinate using GLshorts? Advice on speeding up OpenGL ES 1.1 on the iPhone Simple experiments show that switching from "FLOAT" to "SHORT" for vertex and normal isn't tough, but what troubles me is when you're to scale back verticies to their original size (with glScalef), normals are multiplied by the reciprocal of the scale. Natural remedy for this is to multiply the normals w/ scale before you submit to GPU. Then, my short normals almost become 0, because the scale factor is usually smaller than 0. Duh! How do you use "short" for both vertex and normal at the same time? I've been trying this and that for about a full day, but I could only go for "float vertex w/ byte normal" or "short vertex w/ float normal" so far. Your help would be truly appreciated.

    Read the article

  • PostgeSQL: Arrays Data Type with PHP

    - by ArchJ
    I'm working on PostgeSQL with PHP and I know that PosrgeSQL allow columns of a table to be defined as arrays. So let's say I have a table like this: CREATE TABLE sal_emp ( a text ARRAY, b text ARRAY, c text ARRAY, ); These are my arrays: $a = array(aa,bb,cc); $b = array(dd,dd,aa); $c = array(bb,ff,ee); and I want to insert them into respective column each like this: a | b | c -----------+------------+------------ {aa,bb,cc} | {dd,dd,aa} | {bb,ff,ee} Can I insert it this way? $a = implode(',', $a); $b = implode(',', $b); $c = implode(',', $c); $a = array('a' => $a, 'b' => $b, 'c' => $c); pg_insert($dbconn, 'table', $a); Or is there a better way to achieve the same result?

    Read the article

  • two php arrays - sort one array with the value order of another

    - by Tisch
    Hi there, I have two PHP arrays like so: Array of X records containing the ID of Wordpress posts (in a particular order) Array of Wordpress posts The two arrays look something like this: Array One (Sorted Custom Array of Wordpress Post IDs) Array ( [0] => 54 [1] => 10 [2] => 4 ) Array Two (Wordpress Post Array) Array ( [0] => stdClass Object ( [ID] => 4 [post_author] => 1 ) [1] => stdClass Object ( [ID] => 54 [post_author] => 1 ) [2] => stdClass Object ( [ID] => 10 [post_author] => 1 ) ) I would like to sort the array of wordpress posts with the order of the ID's in the first array. I hope this makes sense, and thanks in advance of any help. Tom edit: The server is running PHP Version 5.2.14

    Read the article

  • Can I use the [] operator in C++ to create virtual arrays

    - by Shane MacLaughlin
    I have a large code base, originally C ported to C++ many years ago, that is operating on a number of large arrays of spatial data. These arrays contain structs representing point and triangle entities that represent surface models. I need to refactor the code such that the specific way these entities are stored internally varies for specific scenarios. For example if the points lie on a regular flat grid, I don't need to store the X and Y coordinates, as they can be calculated on the fly, as can the triangles. Similarly, I want to take advantage of out of core tools such as STXXL for storage. The simplest way of doing this is replacing array access with put and get type functions, e.g. point[i].x = XV; becomes Point p = GetPoint(i); p.x = XV; PutPoint(i,p); As you can imagine, this is a very tedious refactor on a large code base, prone to all sorts of errors en route. What I'd like to do is write a class that mimics the array by overloading the [] operator. As the arrays already live on the heap, and move around with reallocs, the code already assumes that references into the array such as point *p = point + i; may not be used. Is this class feasible to write? For example writing the methods below in terms of the [] operator; void MyClass::PutPoint(int Index, Point p) { if (m_StorageStrategy == RegularGrid) { int xoffs,yoffs; ComputeGridFromIndex(Index,xoffs,yoffs); StoreGridPoint(xoffs,yoffs,p.z); } else m_PointArray[Index] = p; } } Point MyClass::GetPoint(int Index) { if (m_StorageStrategy == RegularGrid) { int xoffs,yoffs; ComputeGridFromIndex(Index,xoffs,yoffs); return GetGridPoint(xoffs,yoffs); // GetGridPoint returns Point } else return m_PointArray[Index]; } } My concern is that all the array classes I've seen tend to pass by reference, whereas I think I'll have to pass structs by value. I think it should work put other than performance, can anyone see any major pitfalls with this approach. n.b. the reason I have to pass by value is to get point[a].z = point[b].z + point[c].z to work correctly where the underlying storage type varies.

    Read the article

  • Iterating over two arrays at a time in Javascript

    - by Ankur
    I want to iterate over two arrays at the same time, as the values for any given index i in array A corresponds to the value in array B. I am currently using this code, and getting 'undefined' when I call queryPredicates[i] or queryObjects[i], I know my array is populated as I print out the array prior to calling this, I haven't put all the other code in as it might be confusing, but if you think the problem is not evident from this I will edit the question: function getObjectCount(){ variables = queryPredicates.length; //the number of variables is found by the length of the arrays - they should both be of the same length queryString="count="+variables; for(var i=1; i<=variables;i++){ alert(queryPredicates[i]); alert(queryObjects[i]); } Thanks

    Read the article

  • C++ Adding 2 arrays together quickly

    - by Tom Gullen
    Hello! Given the arrays: int canvas[10][10]; int addon[10][10]; Where all the values range from 0 - 100, what is the fastest way in C++ to add those two arrays so each cell in canvas equals itself plus the corresponding cell value in addon. IE, I want to achieve something like: canvas += another; So if canvas[0][0] =3 and addon[0][0] = 2 then canvas[0][0] = 5 Speed is essential here as I am writing a very simple program to brute force a knapsack type problem and there will be tens of millions of combinations.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >