Search Results

Search found 513 results on 21 pages for 'arr'.

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

  • vba: a forever loop

    - by I__
    Sub something(tecan) On Error Resume Next Dim arr As New Collection, a Dim aFirstArray() As Variant Dim i As Long aFirstArray() = Array(Dir(tecan & "*.ESY", vbNormal)) aFirstArray(0) = Mid(aFirstArray(0), 1, 4) Do While Dir <> "" ReDim Preserve aFirstArray(UBound(aFirstArray) + 1) aFirstArray(UBound(aFirstArray)) = Mid(Dir, 1, 4) Loop On Error Resume Next For Each a In aFirstArray arr.Add a, a Next For i = 1 To arr.Count Cells(i, 1) = arr(i) 'open_esy (tecan & arr(i) & "*") Next Erase aFirstArray For i = 1 To arr.Count arr.Remove i Next i here is how i call this sub: something (tecan1) something (tecan2) on the first call it works and does what it is supposed to but on the second call it gets stuck in this loop: Do While Dir <> "" ReDim Preserve aFirstArray(UBound(aFirstArray) + 1) aFirstArray(UBound(aFirstArray)) = Mid(Dir, 1, 4) Loop why does it get stuck in the loop?

    Read the article

  • : for displaying all elements in a multidimensional array in python 3.1.

    - by Leif Andersen
    I have a multidimensional array in python like: arr = [['foo', 1], ['bar',2]] Now, if I want to print out everything in the array, I could do: print(arr[:][:]) Or I could also just do print(arr). However, If I only wanted to print out the first element of each box (for arr, that would be 'foo', 'bar'), I would imagine I would do something like: print(arr[:][0]) however, that just prints out the first data blog (['foo', 1]), also, I tried reversing it (just in case): print(arr[0][:]) and I got the same thing. So, is there anyway that I can get it to print the first element in each tuple (other than: for tuple in arr: print(tuple[0]) )? Thanks.

    Read the article

  • Coming Up with a Good Algorithm for a Simple Idea

    - by mkoryak
    I need to come up with an algorithm that does the following: Lets say you have an array of positive numbers (e.g. [1,3,7,0,0,9]) and you know beforehand their sum is 20. You want to abstract some average amount from each number such that the new sum would be less by 7. To do so, you must follow these rules: you can only subtract integers the resulting array must not have any negative values you can not make any changes to the indices of the buckets. The more uniformly the subtraction is distributed over the array the better. Here is my attempt at an algorithm in JavaScript + underscore (which will probably make it n^2): function distributeSubtraction(array, goal){ var sum = _.reduce(arr, function(x, y) { return x + y; }, 0); if(goal < sum){ while(goal < sum && goal > 0){ var less = ~~(goal / _.filter(arr, _.identity).length); //length of array without 0s arr = _.map(arr, function(val){ if(less > 0){ return (less < val) ? val - less : val; //not ideal, im skipping some! } else { if(goal > 0){ //again not ideal. giving preference to start of array if(val > 0) { goal--; return val - 1; } } else { return val; } } }); if(goal > 0){ var newSum = _.reduce(arr, function(x, y) { return x + y; }, 0); goal -= sum - newSum; sum = newSum; } else { return arr; } } } else if(goal == sum) { return _.map(arr, function(){ return 0; }); } else { return arr; } } var goal = 7; var arr = [1,3,7,0,0,9]; var newArray = distributeSubtraction(arr, goal); //returned: [0, 1, 5, 0, 0, 7]; Well, that works but there must be a better way! I imagine the run time of this thing will be terrible with bigger arrays and bigger numbers. edit: I want to clarify that this question is purely academic. Think of it like an interview question where you whiteboard something and the interviewer asks you how your algorithm would behave on a different type of a dataset.

    Read the article

  • BST insert operation. don't insert a node if a duplicate exists already

    - by jeev
    the following code reads an input array, and constructs a BST from it. if the current arr[i] is a duplicate, of a node in the tree, then arr[i] is discarded. count in the struct node refers to the number of times a number appears in the array. fi refers to the first index of the element found in the array. after the insertion, i am doing a post-order traversal of the tree and printing the data, count and index (in this order). the output i am getting when i run this code is: 0 0 7 0 0 6 thank you for your help. Jeev struct node{ int data; struct node *left; struct node *right; int fi; int count; }; struct node* binSearchTree(int arr[], int size); int setdata(struct node**node, int data, int index); void insert(int data, struct node **root, int index); void sortOnCount(struct node* root); void main(){ int arr[] = {2,5,2,8,5,6,8,8}; int size = sizeof(arr)/sizeof(arr[0]); struct node* temp = binSearchTree(arr, size); sortOnCount(temp); } struct node* binSearchTree(int arr[], int size){ struct node* root = (struct node*)malloc(sizeof(struct node)); if(!setdata(&root, arr[0], 0)) fprintf(stderr, "root couldn't be initialized"); int i = 1; for(;i<size;i++){ insert(arr[i], &root, i); } return root; } int setdata(struct node** nod, int data, int index){ if(*nod!=NULL){ (*nod)->fi = index; (*nod)->left = NULL; (*nod)->right = NULL; return 1; } return 0; } void insert(int data, struct node **root, int index){ struct node* new = (struct node*)malloc(sizeof(struct node)); setdata(&new, data, index); struct node** temp = root; while(1){ if(data<=(*temp)->data){ if((*temp)->left!=NULL) *temp=(*temp)->left; else{ (*temp)->left = new; break; } } else if(data>(*temp)->data){ if((*temp)->right!=NULL) *temp=(*temp)->right; else{ (*temp)->right = new; break; } } else{ (*temp)->count++; free(new); break; } } } void sortOnCount(struct node* root){ if(root!=NULL){ sortOnCount(root->left); sortOnCount(root->right); printf("%d %d %d\n", (root)->data, (root)->count, (root)->fi); } }

    Read the article

  • Criticize my code, please

    - by Micky
    Hey, I was applying for a position, and they asked me to complete a coding problem for them. I did so and submitted it, but I later found out I was rejected from the position. Anyways, I have an eclectic programming background so I'm not sure if my code is grossly wrong or if I just didn't have the best solution out there. I would like to post my code and get some feedback about it. Before I do, here's a description of a problem: You are given a sorted array of integers, say, {1, 2, 4, 4, 5, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 13 }. Now you are supposed to write a program (in C or C++, but I chose C) that prompts the user for an element to search for. The program will then search for the element. If it is found, then it should return the first index the entry was found at and the number of instances of that element. If the element is not found, then it should return "not found" or something similar. Here's a simple run of it (with the array I just put up): Enter a number to search for: 4 4 was found at index 2. There are 2 instances for 4 in the array. Enter a number to search for: -4. -4 is not in the array. They made a comment that my code should scale well with large arrays (so I wrote up a binary search). Anyways, my code basically runs as follows: Prompts user for input. Then it checks if it is within bounds (bigger than a[0] in the array and smaller than the largest element of the array). If so, then I perform a binary search. If the element is found, then I wrote two while loops. One while loop will count to the left of the element found, and the second while loop will count to the right of the element found. The loops terminate when the adjacent elements do not match with the desired value. EX: 4, 4, 4, 4, 4 The bold 4 is the value the binary search landed on. One loop will check to the left of it, and another loop will check to the right of it. Their sum will be the total number of instances of the the number four. Anyways, I don't know if there are any advanced techniques that I am missing or if I just don't have the CS background and made a big error. Any constructive critiques would be appreciated! #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> /* function prototype */ int get_num_of_ints( const int* arr, size_t r, int N, size_t* first, size_t* count ); int main() { int N; /* input variable */ int arr[]={1,1,2,3,3,4,4,4,4,5,5,7,7,7,7,8,8,8,9,11,12,12}; /* array of sorted integers */ size_t r = sizeof(arr)/sizeof(arr[0]); /* right bound */ size_t first; /* first match index */ size_t count; /* total number of matches */ /* prompts the user to enter input */ printf( "\nPlease input the integer you would like to find.\n" ); scanf( "%d", &N ); int a = get_num_of_ints( arr, r, N, &first, &count ); /* If the function returns -1 then the value is not found. Else it is returned */ if( a == -1) printf( "%d has not been found.\n", N ); else if(a >= 0){ printf( "The first matching index is %d.\n", first ); printf( "The total number of instances is %d.\n", count ); } return 0; } /* function definition */ int get_num_of_ints( const int* arr, size_t r, int N, size_t* first, size_t* count ) { int lo=0; /* lower bound for search */ int m=0; /* middle value obtained */ int hi=r-1; /* upper bound for search */ int w=r-1; /* used as a fixed upper bound to calculate the number of right instances of a particular value. */ /* binary search to find if a value exists */ /* first check if the element is out of bounds */ if( N < arr[0] || arr[hi] < N ){ m = -1; } else{ /* binary search to find a value, if it exists, within given parameters */ while(lo <= hi){ m = (hi + lo)/2; if(arr[m] < N) lo = m+1; else if(arr[m] > N) hi = m-1; else if(arr[m]==N){ m=m; break; } } if (lo > hi) /* if it doesn't we assign it -1 */ m = -1; } /* If the value is found, then we compute the left and right instances of it */ if( m >= 0 ){ int j = m-1; /* starting with the first term to the left */ int L = 0; /* total number of left instances */ /* while loop computes total number of left instances */ while( j >= 0 && arr[j] == arr[m] ){ L++; j--; } /* There are six possible outcomes of this. Depending on the outcome, we must assign the first index variable accordingly */ if( j > 0 && L > 0 ) *first=j+1; else if( j==0 && L==0) *first=m; else if( j > 0 && L==0 ) *first=m; else if(j < 0 && L==0 ) *first=m; else if( j < 0 && L > 0 ) *first=0; else if( j=0 && L > 0 ) *first=j+1; int h = m + 1; /* starting with the first term to the right */ int R = 0; /* total number of right instances */ /* while loop computes total number of right instances */ /* we fixed w earlier so that it's value does not change */ while( arr[h]==arr[m] && h <= w ){ R++; h++; } *count = (R + L + 1); /* total number of instances stored as value of count */ return *first; /* first instance index stored here */ } /* if value does not exist, then we return a negative value */ else if( m==-1) return -1; }

    Read the article

  • How to get a number closest to the average in c++?

    - by Alex Zielinski
    What I'm trying to achieve is to take the average of the numbers stored in the array and find the number which is closest to it. My code compiles, but has an error just after starting. I think it's something to do with the memory handling (I don't feel confident with pointers, etc. yet) Could some nice guy take a look at my code and tell me what's wrong with it? (don't be hard on me, I'm a beginner) #include <iostream> #include <cmath> using namespace std; double* aver(double* arr, size_t size, double& average); int main() { double arr[] = {1,2,3,4,5,7}; size_t size = sizeof(arr)/sizeof(arr[0]); double average = 0; double* p = aver(arr,size,average); cout << *p << " " << average << endl; } double* aver(double* arr, size_t size, double& average){ int i,j,sum; double* m = 0; int tmp[7]; for(i=0;i<size;i++) sum += arr[i]; average = sum/size; for(j=0;j<size;j++){ tmp[j] = arr[j] - average; if(abs(tmp[j])>*m) *m = tmp[j]; } return m; }

    Read the article

  • How to handle array element between int and Integer

    - by masato-san
    First, it is long post so if you need clarification please let me know. I'm new to Java and having difficulty deciding whether I should use int[] or Integer[]. I wrote a function that find odd_number from int[] array. public int[] find_odd(int[] arr) { int[] result = new int[arr.length]; for(int i=0; i<arr.length; i++) { if(arr[i] % 2 != 0) { //System.out.println(arr[i]); result[i] = arr[i]; } } return result; } Then, when I pass the int[] array consisting of some integer like below: int[] myArray = {-1, 0, 1, 2, 3}; int[] result = find_odd(myArray); The array "result" contains: 0, -1, 0, 1, 0, 3 Because in Java you have to define the size of array first, and empty int[] array element is 0 not null. So when I want to test the find_odd() function and expect the array to have odd numbers (which it does) only, it throws the error because the array also includes 0s representing "empty cell" as shown above. My test code: public void testFindOddPassValidIntArray() { int[] arr = {-2, -1, 0, 1, 3}; int[] result = findOddObj.find_odd(arr); //check if return array only contain odd number for(int i=0; i<result.length; i++) { if(result[i] != null) { assert is_odd(result[i]) : result[i]; } } } So, my question is should I use int[] array and add check for 0 element in my test like: if(result[i] != 0) { assert is_odd(result[i] : result[i] } But in this case, if find_odd() function is broken and returning 0 by miscalculation, I can't catch it because my test code would only assume that 0 is empty cell. OR should I use Integer[] array whose default is null? How do people deal with this kind of situation?

    Read the article

  • Rotate two dimensional array 90 degrees clockwise

    - by user69514
    I have a two dimensional array that I need to rotate 90 degrees clockwise, however I keep getting arrayindexoutofbounds... public int[][] rorateArray(int[][] arr){ //first change the dimensions vertical length for horizontal length //and viceversa int[][] newArray = new int[arr[0].length][arr.length]; //invert values 90 degrees clockwise by starting from button of //array to top and from left to right int ii = 0; int jj = 0; for(int i=0; i<arr[0].length; i++){ for(int j=arr.length-1; j>=0; j--){ newArray[ii][jj] = arr[i][j]; jj++; } ii++; } return newArray; }

    Read the article

  • Allocate constant memory

    - by Vlad
    I'm trying to set my simulation params in constant memory but without luck (CUDA.NET). cudaMemcpyToSymbol function returns cudaErrorInvalidSymbol. The first parameter in cudaMemcpyToSymbol is string... Is it symbol name? actualy I don't understand how it could be resolved. Any help appreciated. //init, load .cubin float[] arr = new float[1]; arr[0] = 0.0f; int size = Marshal.SizeOf(arr[0]) * arr.Length; IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.Copy(arr, 0, ptr, arr.Length); var error = CUDARuntime.cudaMemcpyToSymbol("param", ptr, 4, 0, cudaMemcpyKind.cudaMemcpyHostToDevice); my .cu file contain __constant__ float param;

    Read the article

  • Rotate array clockwise

    - by user69514
    I have a two dimensional array that I need to rotate 90 degrees clockwise, however I keep getting arrayindexoutofbounds... public int[][] rorateArray(int[][] arr){ //first change the dimensions vertical length for horizontal length //and viceversa int[][] newArray = new int[arr[0].length][arr.length]; //invert values 90 degrees clockwise by starting from button of //array to top and from left to right int ii = 0; int jj = 0; for(int i=0; i<arr[0].length; i++){ for(int j=arr.length-1; j>=0; j--){ newArray[ii][jj] = arr[i][j]; jj++; } ii++; } return newArray; }

    Read the article

  • Index, assignment and increment in one statement behaves differently in C++ and C#. Why?

    - by Ivan Zlatanov
    Why is this example of code behaving differently in c++ and C#. [C++ Example] int arr[2]; int index = 0; arr[index] = ++index; The result of which will be arr[1] = 1; [C# Example] int[] arr = new int[2]; int index = 0; arr[index] = ++index; The result of which will be arr[0] = 1; I find this very strange. Surely there must be some rationale for both languages to implement it differently? I wonder what would C++/CLI output?

    Read the article

  • Read tab delimited text file into MySQL table with PHP

    - by Simon S
    I am trying to read in a series of tab delimited text files into existing MySQL tables. The code I have is quite simple: $lines = file("import/file_to_import.txt"); foreach ($lines as $line_num => $line) { if($line_num > 1) { $arr = explode("\t", $line); $sql = sprintf("INSERT INTO my_table VALUES('%s', '%s', '%s', %s, %s);", trim((string)$arr[0]), trim((string)$arr[1]), trim((string)$arr[2]), trim((string)$arr[3]), trim((string)$arr[4])); mysql_query($sql, $database) or die(mysql_error()); } } But no matter what I do (hence the casting before each variable in the sprintf statement) I get the "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1" error. I echo out the code, paste it into a MySQL editor and it runs fine, it just won't execute from the PHP script. What am I doing wrong?? Si

    Read the article

  • Sort a set of multidimensional arrays by array elements

    - by Joseph Carrington
    Let's say I've started here: $arr[0] = array('a' => 'a', 'int' => 10); $arr[1] = array('a' => 'foo', 'int' => 5); $arr[1] = array('a' => 'bar', 'int' => 12); And I want to get here: $arr[0] = array('a' => 'foo', 'int' => 5); $arr[1] = array('a' => 'a', 'int' => 10); $arr[1] = array('a' => 'bar', 'int' => 12); How can I sort the elements in an array by those elements elements? Multidimensional arrays always feel like a little bit more than my brain can handle (-_-) (until I figure them out and they seem super easy)

    Read the article

  • Objective c key path operators @avg,@max .....

    - by davide
    arr = [[NSMutableArray alloc]init]; [arr addObject:[NSNumber numberWithInt:4]]; [arr addObject:[NSNumber numberWithInt:45]]; [arr addObject:[NSNumber numberWithInt:23]]; [arr addObject:[NSNumber numberWithInt:12]]; NSLog(@"The avg = %@", [arr valueForKeyPath:@"@avg.intValue"]); This code works fine, but why? valueForKeyPath:@"@avg.intValue" is requesting (int) from each NSNumber, but we are outputting a %@ string in the log. If i try to output a decimal %d i get a number that possibly is a pointer to something. Can somebody explain why the integers become NSNumbers when i call the @avg operator?

    Read the article

  • Need help understanding .net ThreadPool

    - by Meredith
    I am trying to understand what ThreadPool does, I have this .NET example: class Program { static void Main() { int c = 2; // Use AutoResetEvent for thread management AutoResetEvent[] arr = new AutoResetEvent[50]; for (int i = 0; i < arr.Length; ++i) { arr[i] = new AutoResetEvent(false); } // Set the number of minimum threads ThreadPool.SetMinThreads(c, 4); // Enqueue 50 work items that run the code in this delegate function for (int i = 0; i < arr.Length; i++) { ThreadPool.QueueUserWorkItem(delegate(object o) { Thread.Sleep(100); arr[(int)o].Set(); // Signals completion }, i); } // Wait for all tasks to complete WaitHandle.WaitAll(arr); } } Does this run 50 "tasks", in groups of 2 (int c) until they all finish? Or I am not understanding what it really does.

    Read the article

  • how free of memory happen in this case???

    - by Riyaz
    #include <stdio.h> void func(int arr[],int xNumOfElem) { int j; for(j=0; j<xNumOfElem; j++) { arr[j] = j + arr[j]; printf("%d\t",arr[j]); } printf("\n"); } int main() { int *a,k; a = (int*) malloc(sizeof(int)*10); for(k = 0; k<10; k++) { a[k] = k; printf("%d\t",a[k]); } printf("\n"); func(a,10); //Func call free(a); } Inside the the function "func" who will allocate/deallocate memory for dynamic array "arr". arr is an function argument.

    Read the article

  • Subterranean IL: Generics and array covariance

    - by Simon Cooper
    Arrays in .NET are curious beasts. They are the only built-in collection types in the CLR, and SZ-arrays (single dimension, zero-indexed) have their own commands and IL syntax. One of their stranger properties is they have a kind of built-in covariance long before generic variance was added in .NET 4. However, this causes a subtle but important problem with generics. First of all, we need to briefly recap on array covariance. SZ-array covariance To demonstrate, I'll tweak the classes I introduced in my previous posts: public class IncrementableClass { public int Value; public virtual void Increment(int incrementBy) { Value += incrementBy; } } public class IncrementableClassx2 : IncrementableClass { public override void Increment(int incrementBy) { base.Increment(incrementBy); base.Increment(incrementBy); } } In the CLR, SZ-arrays of reference types are implicitly convertible to arrays of the element's supertypes, all the way up to object (note that this does not apply to value types). That is, an instance of IncrementableClassx2[] can be used wherever a IncrementableClass[] or object[] is required. When an SZ-array could be used in this fashion, a run-time type check is performed when you try to insert an object into the array to make sure you're not trying to insert an instance of IncrementableClass into an IncrementableClassx2[]. This check means that the following code will compile fine but will fail at run-time: IncrementableClass[] array = new IncrementableClassx2[1]; array[0] = new IncrementableClass(); // throws ArrayTypeMismatchException These checks are enforced by the various stelem* and ldelem* il instructions in such a way as to ensure you can't insert a IncrementableClass into a IncrementableClassx2[]. For the rest of this post, however, I'm going to concentrate on the ldelema instruction. ldelema This instruction pops the array index (int32) and array reference (O) off the stack, and pushes a pointer (&) to the corresponding array element. However, unlike the ldelem instruction, the instruction's type argument must match the run-time array type exactly. This is because, once you've got a managed pointer, you can use that pointer to both load and store values in that array element using the ldind* and stind* (load/store indirect) instructions. As the same pointer can be used for both input and output to the array, the type argument to ldelema must be invariant. At the time, this was a perfectly reasonable restriction, and maintained array type-safety within managed code. However, along came generics, and with it the constrained callvirt instruction. So, what happens when we combine array covariance and constrained callvirt? .method public static void CallIncrementArrayValue() { // IncrementableClassx2[] arr = new IncrementableClassx2[1] ldc.i4.1 newarr IncrementableClassx2 // arr[0] = new IncrementableClassx2(); dup newobj instance void IncrementableClassx2::.ctor() ldc.i4.0 stelem.ref // IncrementArrayValue<IncrementableClass>(arr, 0) // here, we're treating an IncrementableClassx2[] as IncrementableClass[] dup ldc.i4.0 call void IncrementArrayValue<class IncrementableClass>(!!0[],int32) // ... ret } .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } And the result: Unhandled Exception: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. at IncrementArrayValue[T](T[] arr, Int32 index) at CallIncrementArrayValue() Hmm. We're instantiating the generic method as IncrementArrayValue<IncrementableClass>, but passing in an IncrementableClassx2[], hence the ldelema instruction is failing as it's expecting an IncrementableClass[]. On features and feature conflicts What we've got here is a conflict between existing behaviour (ldelema ensuring type safety on covariant arrays) and new behaviour (managed pointers to object references used for every constrained callvirt on generic type instances). And, although this is an edge case, there is no general workaround. The generic method could be hidden behind several layers of assemblies, wrappers and interfaces that make it a requirement to use array covariance when calling the generic method. Furthermore, this will only fail at runtime, whereas compile-time safety is what generics were designed for! The solution is the readonly. prefix instruction. This modifies the ldelema instruction to ignore the exact type check for arrays of reference types, and so it lets us take the address of array elements using a covariant type to the actual run-time type of the array: .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 readonly. ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } But what about type safety? In return for ignoring the type check, the resulting controlled mutability pointer can only be used in the following situations: As the object parameter to ldfld, ldflda, stfld, call and constrained callvirt instructions As the pointer parameter to ldobj or ldind* As the source parameter to cpobj In other words, the only operations allowed are those that read from the pointer; stind* and similar that alter the pointer itself are banned. This ensures that the array element we're pointing to won't be changed to anything untoward, and so type safety within the array is maintained. This is a typical example of the maxim that whenever you add a feature to a program, you have to consider how that feature interacts with every single one of the existing features. Although an edge case, the readonly. prefix instruction ensures that generics and array covariance work together and that compile-time type safety is maintained. Tune in next time for a look at the .ctor generic type constraint, and what it means.

    Read the article

  • Nested loops break out unexpectedly

    - by Metju
    Hi guys, I'm trying to create a sudoku game, for those that do not know what it is. You have a 9x9 box that needs to be filled with numbers from 1-9, every number must be unique in its row and column, and also in the 3x3 box it is found. I ended up doing loads of looping within a 2 dimensional array. But at some point it just stops, with no exceptions whatsoever, just breaks out and nothing happens, and it's not always at the same position, but always goes past half way. I was expecting a stack overflow exception at least. Here's my code: public class Engine { public int[,] Create() { int[,] outer = new int[9, 9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { outer[i, j] = GetRandom(GetUsed(outer, i, j)); } } return outer; } List<int> GetUsed(int[,] arr, int x, int y) { List<int> usedNums = new List<int>(); for (int i = 0; i < 9; i++) { if (arr[x, i] != 0 && i != y) { if(!usedNums.Contains(arr[x, i])) usedNums.Add(arr[x, i]); } } for (int i = 0; i < 9; i++) { if (arr[i, y] != 0 && i != x) { if (!usedNums.Contains(arr[i, y])) usedNums.Add(arr[i, y]); } } int x2 = 9 - (x + 1); int y2 = 9 - (y + 1); if (x2 <= 3) x2 = 2; else if (x2 > 3 && x2 <= 6) x2 = 5; else x2 = 8; if (y2 <= 3) y2 = 2; else if (y2 > 3 && y2 <= 6) y2 = 5; else y2 = 8; for (int i = x2 - 2; i < x2; i++) { for (int j = y2 - 2; j < y2; j++) { if (arr[i, j] != 0 && i != x && j != y) { if (!usedNums.Contains(arr[i, j])) usedNums.Add(arr[i, j]); } } } return usedNums; } int GetRandom(List<int> numbers) { Random r; int newNum; do { r = new Random(); newNum = r.Next(1, 10); } while (numbers.Contains(newNum)); return newNum; } }

    Read the article

  • Simulating pass by reference for an array reference (i.e. a reference to a reference) in Java

    - by Leif Andersen
    I was wondering, in java, is it possible to in anyway, simulate pass by reference for an array? Yes, I know the language doesn't support it, but is there anyway I can do it. Say, for example, I want to create a method that reverses the order of all the elements in an array. (I know that this code snippet isn't the best example, as there is a better algorithms to do this, but this is a good example of the type of thing I want to do for more complex problems). Currently, I need to make a class like this: public static void reverse(Object[] arr) { Object[] tmpArr = new Object[arr.length]; count = arr.length - 1; for(Object i : arr) tmpArr[count--] = i; // I would like to do arr = tmpArr, but that will only make the shallow // reference tmpArr, I would like to actually change the pointer they passed in // Not just the values in the array, so I have to do this: count = arr.length - 1; for(Object i : tmpArr) arr[count--] = i; return; } Yes, I know that I could just swap the values until I get to the middle, and it would be much more efficient, but for other, more complex purposes, is there anyway that I can manipulate the actual pointer? Again, thank you.

    Read the article

  • Simulating pass by reference for an array in Java

    - by Leif Andersen
    I was wondering, in java, is it possible to in anyway, simulate pass by reference for an array? Yes, I know the language doesn't support it, but is there anyway I can do it. Say, for example, I want to create a method that reverses the order of all the elements in an array. (I know that this code snippet isn't the best example, as there is a better algorithms to do this, but this is a good example of the type of thing I want to do for more complex problems). Currently, I need to make a class like this: public static void reverse(Object[] arr) { Object[] tmpArr = new Object[arr.length]; count = arr.length - 1; for(Object i : arr) tmpArr[count--] = i; // I would like to do arr = tmpArr, but that will only make the shallow // reference tmpArr, I would like to actually change the pointer they passed in // Not just the values in the array, so I have to do this: count = arr.length - 1; for(Object i : tmpArr) arr[count--] = i; return; } Yes, I know that I could just swap the values until I get to the middle, and it would be much more efficient, but for other, more complex purposes, is there anyway that I can manipulate the actual pointer? Again, thank you.

    Read the article

  • What is the header of an array in .NET

    - by Thomas
    Hi all, I have a little bit seen the representation of an array in memory with Windbg and SOS plugin. Here it is the c# : class myobj{ public int[] arr; } class Program{ static void Main(string[] args){ myobj o = new myobj(); o.arr = new int[7]; o.arr[0] = 0xFFFFFF; o.arr[1] = 0xFFFFFF; o.arr[2] = 0xFFFFFF; o.arr[3] = 0xFFFFFF; o.arr[4] = 0xFFFFFF; } } I break at final of Main, and I observ : 0:000> !clrstack -l OS Thread Id: 0xc3c (0) ESP EIP 0015f0cc 0043d1cf test.Program.Main(System.String[]) LOCALS: 0x0015f0d8 = 0x018a2f58 0:000 !do 0x018a2f58 Name: test.myobj MethodTable: 0026309c EEClass: 00261380 Size: 12(0xc) bytes (C:\Users\admin\Documents\Visual Studio 2008\Projects\test\test\bin\Debug\test.exe) Fields: MT Field Offset Type VT Attr Value Name 01324530 4000001 4 System.Int32[] 0 instance 018a2f64 tab 0:000 dd 018a2f64 018a2f64 01324530 00000007 00ffffff 00ffffff 018a2f74 00ffffff 00ffffff 00ffffff 00000000 018a2f84 00000000 00000000 00000000 00000000 018a2f94 00000000 00000000 00000000 00000000 018a2fa4 00000000 00000000 00000000 00000000 018a2fb4 00000000 00000000 00000000 00000000 018a2fc4 00000000 00000000 00000000 00000000 018a2fd4 00000000 00000000 00000000 00000000 I can see that the header contains the size of the array (00000007) but my question is : what is the value 01324530 ? Thanks !

    Read the article

  • Storing array as value in associative array

    - by Jagannath
    i have a problem where I need to have an array as value in associative array. Go through the code below. Here I am trying to loop the files in a directory and it is more likely that more than 1 file can have the same ctrno. So, I would like to see what are all the files having the same ctrno. The code below gives error at "$ctrno_hash[$ctrno] = @arr;" in the else condition. The same case would be for if condition as well. Am I following the right approach or could it be done diffently? sub loop_through_files { $file = "@_"; open(INPFILE, "$file") or die $!; #print "$file:$ctrno\n"; while (<INPFILE>) { $line .= $_; } if ($line =~ /$ctrno/ ) { print "found\n"; if ( exists $ctrno_hash[$ctrno]) { local @arr = $ctrno_hash[$ctrno]; push (@arr, $file); $ctrno_hash[$ctrno] = @arr; } else { local @arr; push(@arr, $file); $ctrno_hash[$ctrno] = @arr; } } }

    Read the article

  • Error in creating template class

    - by Luciano
    I found this vector template class implementation, but it doesn't compile on XCode. Header file: // File: myvector.h #ifndef _myvector_h #define _myvector_h template <typename ElemType> class MyVector { public: MyVector(); ~MyVector(); int size(); void add(ElemType s); ElemType getAt(int index); private: ElemType *arr; int numUsed, numAllocated; void doubleCapacity(); }; #include "myvector.cpp" #endif Implementation file: // File: myvector.cpp #include <iostream> #include "myvector.h" template <typename ElemType> MyVector<ElemType>::MyVector() { arr = new ElemType[2]; numAllocated = 2; numUsed = 0; } template <typename ElemType> MyVector<ElemType>::~MyVector() { delete[] arr; } template <typename ElemType> int MyVector<ElemType>::size() { return numUsed; } template <typename ElemType> ElemType MyVector<ElemType>::getAt(int index) { if (index < 0 || index >= size()) { std::cerr << "Out of Bounds"; abort(); } return arr[index]; } template <typename ElemType> void MyVector<ElemType>::add(ElemType s) { if (numUsed == numAllocated) doubleCapacity(); arr[numUsed++] = s; } template <typename ElemType> void MyVector<ElemType>::doubleCapacity() { ElemType *bigger = new ElemType[numAllocated*2]; for (int i = 0; i < numUsed; i++) bigger[i] = arr[i]; delete[] arr; arr = bigger; numAllocated*= 2; } If I try to compile as is, I get the following error: "Redefinition of 'MyVector::MyVector()'" The same error is displayed for every member function (.cpp file). In order to fix this, I removed the '#include "myvector.h"' on the .cpp file, but now I get a new error: "Expected constructor, destructor, or type conversion before '<' token". A similar error is displayed for every member as well. Interestingly enough, if I move all the .cpp code to the header file, it compiles fine. Does that mean I can't implement template classes in separate files?

    Read the article

  • Duplicating an array of strings.

    - by Jon
    arr = ["red","green","yellow"] arr2 = arr.clone arr2[0].replace("blue") puts arr.inspect puts arr2.inspect produces: ["blue", "green", "yellow"] ["blue", "green", "yellow"] Is there anyway to do a deep copy of an array of strings, other than using Marshal as i understand that is a hack. I could do: arr2 = [] arr.each do |e| arr2 << e.clone end but it doesn't seem very elegant, or efficient. Thanks

    Read the article

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