I am trying to do 2 different sorting algorithms on 2 exactly similar arrays (numbers and numbers2) that are generated through the Random class. I declare my 2 arrays and fill them with Random.NextBytes.
After that I do my first algorithm on numbers and then my second sorts on numbers2.
But I notice that numbers2 just seems to be a pointer to numbers because by the time I want to sort numbers2 it is already sorted.
How do I fill numbers2 with exactly the same numbers as numbers? Do I need to do it by hand with a for loop? Thank you!
class FillArray
{
public byte[] numbers;
public byte[] numbers2;
//instantiate MS Random object
Random Generator = new Random();
//Constructor which takes array size
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
numbers2 = numbers;
amount = amountx;
}
Arrays are reference types, so if you want to clone the array you'll need to copy it via Array.Copy.
int[] first = new int[] { 1, 2, 3, 4, 5 };
int[] second = new int[first.Length];
Array.Copy( first, second, first.Length );
first[0] = 10;
// prints 10
Console.WriteLine( first[0] );
// prints 1
Console.WriteLine( second[0] );
You can also use Array.CopyTo. If you don't have a pre-existing array you can use the Clone() method as well to create a new one with shallow copies of all elements.
try
numbers2 = (byte[])numbers.Clone();
instead of
numbers2 = new byte[amountx];
numbers2 = numbers;
use Array.Copy method: Array.Copy Method
int[] source = new int[5];
source[0] = 1;
source[1] = 2;
source[2] = 3;
source[3] = 4;
source[4] = 5;
int[] target = new int[5];
Array.Copy(source, target, 5);
You are assigning the reference for numbers to numbers2 instead of the values. Try this:
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
Array.Copy(numbers, numbers2, amountx);
amount = amountx;
}
As Ed says, arrays are reference types. Your error is below:
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
numbers2 = numbers; // this line is why the arrays are the same
amount = amountx;
}
However, I have a different solution than the other 2 presented. If you include the System.Linq namespace, you can use .ToList() and .ToArray():
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = numbers.ToList().ToArray();
amount = amountx;
}
You will then have 2 separate copies of the array to sort independently.
Since arrays are reference types, you will need to create a clone of the array:
class FillArray
{
public byte[] numbers;
public byte[] numbers2;
//instantiate MS Random object
Random Generator = new Random();
//Constructor which takes array size
public FillArray(int amountx)
{
numbers = new byte[amountx]
Generator.NextBytes(numbers);
numbers2 = new byte[amountx];
// Array Copy solution
Array.CopyTo(numbers2, 0);
// Or a LINQ solution
numbers2 = numbers.ToArray();
// Or a Clone solution
numbers2 = (byte[])numbers.Clone();
amount = amountx;
}
}
Related
I want to make an array which one dimension's length is defined but the other one is undefined
I try to do it with "LIST" and I dont know how to make a two dimension array which I already know how much is the length of one dimension
Make an array of lists. But make sure you include System.Collections.Generic in your class:
using System;
using System.Collections.Generic;
in the body of the method or class where you need this:
var arrayOfList = new List<int>[10];
for (var i = 0; i < 10; i++)
{
// initialize each entry of the array
arrayOfList[i] = new List<int>();
}
// add some stuff to entry one at a time
arrayOfList[0].Add(1);
// add some integers as a range
arrayOfList[0].AddRange(new [] {2, 3, 4});
// add some stuff to entry 1
arrayOfList[1].AddRange(new [] {5, 6});
If you don't want to use the generic list class, you can do a jagged array but it isn't as nice to deal with.
int[][] jaggedArray = new int[3][];
// initialize before using or else you'll get an error
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
// populate them like this:
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
See more here: http://msdn.microsoft.com/en-us/library/2s05feca.aspx
Lets say I have
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
Is there anyway to pass them into a one dimensional array by reference?
int[] array = new int[21];
//Could I now make the arraySegment1 be passed in array[0] - array[10] by reference?
//And arraySegment2 in array[11] - array[21] passed by reference?
//Then when executing:
array[0] = 10000000;
System.Console.WriteLine(arraySegment1[0]);
//It should display 10000000
//By putting the arraySegment1 as reference in the one dimensional array: array?
Checkout the Array.Copy method which allows you to copy segments of arrays to a destination array:
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
// TODO: populate the arraySegment1 and arraySegment2 with some values
int[] array = new int[20];
Array.Copy(arraySegment1, 0, array, 0, arraySegment1.Length);
Array.Copy(arraySegment2, 0, array, arraySegment1.Length, arraySegment2.Length);
Also 20 is enough of a Length for the resulting array, not 21 if the 2 source arrays are 10 each.
Try this one..
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
int[] array = new int[21];
arraySegment1.CopyTo(array,0);
arraySegment2.CopyTo(array,(arraySegment1.Length));
No. It's not possible with standart arrays. But with generics you can do something like this:
int[] arraySegment1 = new int[10];
int[] arraySegment2 = new int[10];
// populate arrays
List<int[]> lists = new List<int[]>();
lists.Add(arraySegment1);
lists.Add(arraySegment2);
lists[0][0] = 100000;
System.Console.WriteLine(arraySegment1[0]); // then it will display 100000
you typing wrong object
change the arraySegment1 in the write line to be array
System.Console.WriteLine(array[0]);
I have the following array:
int[] numbers;
Is there a good way to add a number to the array? I didn't find an extension method that concats 2 arrays, I wanted to do something like:
numbers = numbers.Concat(new[] { valueToAdd });
To concatenate 2 ararys look at: How do I concatenate two arrays in C#?
The best solution I can suggest is to simply use
List<int> numbers
And when needed call the ToArray() extension method (and not the opposite).
you can try this..
var z = new int[x.length + y.length];
x.CopyTo(z, 0);
y.CopyTo(z, x.length);
or
List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();
or
int[] array1 = { 1, 3, 5 };
int[] array2 = { 0, 2, 4 };
// Concat array1 and array2.
var result1 = array1.Concat(array2);
for (int i = 0; i < People.Length; i++) {
People[i] = new Person(first[i], last[i], birth[i]);
}
Now first and last contain 20 strings and birth is a DateTime object that again populates the array people with 20 birthdates. I just need to know how to correctly initialize my array.
You have to use Jagged Array
ex:
You can initialize jagged arrays like this example:
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
You can also omit the size of the first array, like this:
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
You initialize your array with the desired size:
Person[] people = new Person[20];
To automatically use the length of, for example, first:
Person[] people = new Person[first.Length];
I build my MyObject array with :
MyObject[] myObject = (from MyObject varObj in MyObjects
select varObj).ToArray();
and now, I'd like to extract 3 random MyObject from this array! How can I do it on C#?
Of course, if array lenght is <3 I need to extract all objects!
You can do this via Linq:
Retrieve the items in random order (see Jon Skeet's answer to this SO question)
Select Top(3) of the resulting list using the Take operator
As an example, select 3 processes at random:
var ps = (from p in Process.GetProcesses() orderby Guid.NewGuid() select p).Take(3);
You can also use random.Next() instead of Guids (since strictly speaking, as pointed out by LukeH, Guids are unique, but not random).
MyObject[] myObject = ...;
int upper = 1;
if (myObject.Length > 1)
{
Random r = new Random();
upper = Math.Min(3, myObject.Length);
for (int i = 0; i < upper; i++)
{
int randInd = r.Next(i, myObject.Length);
MyObject temp = myObject[i];
myObject[i] = myObject[randInd];
myObject[randInd] = temp;
}
}
now take elements of the array from 0 to upper.
using Random class of C# you can get random int which are less than a particular number which in your case will be the size of myObject
I am not sure you want unique or they can duplicate.
How about?
Random r = new Random();
int item1 = r.Next(0, myObject.Length);
int item2 = r.Next(0, myObject.Length);
int item3 = r.Next(0, myObject.Length);
var result1 = myObject[item1];
var result2 = myObject[item2];
var result3 = myObject[item3];
No Linq or anything, but it gets the job done.
What about this:
var random = new Random();
var objs = new Object[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var result = objs.OrderBy(o => random.Next(Int32.MaxValue)).Take(3);
A little bit more creative.
var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 1, 2, 3, 44, 5, 6 };
Random random = new Random();
var results = list.OrderBy(i => random.Next()).Take(3);
Output:
results: {int[3]}
[0]: 3
[1]: 2
[2]: 5