I setup an array and i would like to create a method that will return an array with the elements in reverse. e.g. if there are 10 slots then array1[9] = 6 so then array2[0] = 6.
I suppose i have to return an array - how would i do that? And i dont know how to reverse and add to another array.
Thank you!
int[] arr = {43, 22, 1, 44, 90, 38, 55, 32, 31, 9};
Console.WriteLine("Before");
PrintArray(arr);
Console.WriteLine("After");
Reverse(arr);
Console.ReadKey(true);
}
static int[] Reverse(int[] array)
{
for (int i = array.Length; i < 1; i--)
{
int x = 0;
array[i] = array[x++];
Console.WriteLine(array[i]);
}
}
static void PrintArray(int[] array)
{
for (int j = 0; j < array.Length; j++)
{
Console.Write(array[j] + " ");
}
Console.WriteLine("");
You can use Array.Reverse
Example from above line
public static void Main() {
// Creates and initializes a new Array.
Array myArray=Array.CreateInstance( typeof(String), 9 );
myArray.SetValue( "The", 0 );
myArray.SetValue( "quick", 1 );
myArray.SetValue( "brown", 2 );
myArray.SetValue( "fox", 3 );
myArray.SetValue( "jumps", 4 );
myArray.SetValue( "over", 5 );
myArray.SetValue( "the", 6 );
myArray.SetValue( "lazy", 7 );
myArray.SetValue( "dog", 8 );
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintIndexAndValues( myArray );
// Reverses the sort of the values of the Array.
Array.Reverse( myArray );
// Displays the values of the Array.
Console.WriteLine( "After reversing:" );
PrintIndexAndValues( myArray );
}
public static void PrintIndexAndValues( Array myArray ) {
for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
}
You should be able to use the extension method Reverse
int[] arr = { 43, 22, 1, 44, 90, 38, 55, 32, 31, 9 };
Console.WriteLine("Before");
PrintArray(arr);
Console.WriteLine("After");
PrintArray(arr.Reverse().ToArray());
Or if you don't mind modifing the original sequence you can use Array.Reverse
int[] arr = { 43, 22, 1, 44, 90, 38, 55, 32, 31, 9 };
Console.WriteLine("Before");
PrintArray(arr);
Array.Reverse(arr);
Console.WriteLine("After");
PrintArray(arr);
You can reverse an array by swapping elements from both ends of the array till you reach the middle.
for(int start = 0, end = arr.Length - 1; start < arr.Length/2; start++, end--)
{
swap(arr[start], arr[end]);
}
int a;
Console.WriteLine("Enter the array length");
a=int.Parse(Console.ReadLine());
Console.WriteLine("enter the array element");
int[] sau = new int[a];
for (int i = 0; i < a; i++)
{
sau[i] = int.Parse(Console.ReadLine());
}
for (int i =a.Length-1 ; i < 0;i--)
{
Console.WriteLine(sau[i]);
}
Console.ReadLine();
}
}
}
Create a new array that has the same length as the old array and reverse is done like this
index -> new index
0 -> length - 1
1 -> length - 1 - 1
2 -> length - 1 - 2
..
i -> length - 1 - i
so this translates to this code
int[] myVariable = new int[] { 1, 2, 3, 4, 5 };
int[] reversedVariable = new int[myVariable.Length]();
for (int i = 0; i < myVariable.Length ; i++)
{
reversedVariable[myVariable.Length - 1 - i] = myVariable[i];
}
return reversedVariable;
public class MyList<T> : IEnumerable<T>
{
private T[] arr;
public int Count
{
get { return arr.Length; }
}
public void Reverse()
{
T[] newArr = arr;
arr = new T[Count];
int number = Count - 1;
for (int i = 0; i < Count; i++)
{
arr[i] = newArr[number];
number--;
}
}
}
Related
I try to take only positive numbers from the array and display them in the second array. I copy one array to another but at the output I get only 0.
I’m a beginner in C#, so this is probably an easy thing to do
int[] array = { 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };
int[] positive = new int[array.Length];
int positiveCounter = 0;
int[] source = new int[7];
Array.Copy(positive, source, 7);
for (int i = 0; i < array.Length; i++)
{
if (array[i] > 0)
{
positive[positiveCounter] = array[i];
positiveCounter++;
}
}
Console.WriteLine("Positive numbers are: ");
foreach (var item in positive)
{
Console.WriteLine(item);
}
You can query initial array with a help of Linq:
using System.Linq;
...
int[] array = ...
int[] positive = array.Where(item => item > 0).ToArray();
To show positive array in one go you can try string.Join:
Console.WriteLine(string.Join(", ", positive));
You can solve the problem with a help of loops (no Linq solution):
int[] array = ...
int positiveCounter = 0;
foreach (int item in array)
if (item > 0)
positiveCounter += 1;
int[] positive = new int[positiveCounter];
int index = 0;
for (int i = 0; i < array.Length; ++i)
if (array[i] > 0)
positive[index++] = array[i];
please note, that Array.Copy copies consequent items which is not guaranteed.
As your request it will take all the positive number from 1st array and store in second array
static void Main(string[] args)
{
ArrayList array =new ArrayList{ 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };
ArrayList array2 = new ArrayList { };
foreach(int item in array)
{
Console.WriteLine(item);
if (item > 0)
{
array2.Add(item);
}
}
Console.WriteLine("-----------------------------");
foreach (int item in array2)
{
Console.WriteLine(item);
}
}
Let's say i have an array of 6 elements of int type.
It looks like this
var array = new int [] { 0, 1, 2, 3, 4, 5 };
How can I randomly shuffle my array ensuring every index have a new value.
// Bad
// The number at index 3 did not change and still has a value of 3
new int [] { 1, 0, 5, 3, 2, 4 }
// Good:
// All the index have a new value
new int [] { 4, 2, 0, 5, 3, 1 }
I've tried to Shuffle, but sometimes some values will have the same index position
You could iterate over the array and always swap with a randomly choosen index which is bigger than the current one. That way the numbers get shuffled, but no element can be shuffled back.
Edit: This acutally works, try it:
using System;
class Program {
private static Random rnd = new Random();
public static void Main() {
for (var i = 0; i < 10000; i++) {
int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Shuffle(array);
Console.WriteLine(String.Join(", ", array));
}
}
public static void Shuffle(int[] array) {
for (var i = 0; i + 1 < array.Length; i++) {
// generate j so that i < j < length
int j = rnd.Next(i + 1, array.Length);
// swap elements at i and j
var tmp = array[j];
array[j] = array[i];
array[i] = tmp;
// check
if (array[i] == i) {
throw new Exception(":(");
}
}
}
}
Also its very similar to Sattolo's algorithm, which would also work.
How find template in array ?
Template
int[] = {X, X, X}; //(example 3,3,3)
, or template
int[,] temp2 =
{
{X, X, ?}
{?, X, X}
}
Example
int[,] temp2 =
{
{3, 3, 1}
{2, 3, 3}
}
For example, in such an array?
int[,] a = new int[,]
{
{ 1, 4, 5, 3, 4 },
{ 1, 2, 3, 1, 3 },
{ 1, 1, 2, 4, 4 },
{ 4, 4, 3, 3, 3 },
{ 3, 4, 4, 5, 5 }
};
Is there a faster way than searching each cell and its neighboring cells?
If you are looking for patterns inside a bigger array, probably checking cell by cell is the only way to do it. You could do some complex optimizations for skipping the ? values and speedup a little, but I don't think it would easily work.
A sample code that should do what you asked:
// null means anything is ok, X is 0, Y is 1, Z is 2...
int?[,] temp = new int?[,]
{
{0, 0, null},
{null, 0, 0}
};
int[,] a = new int[,]
{
{ 0, 1, 1, 2, 4, 4, 1 },
{ 0, 1, 4, 4, 3, 3, 3 },
{ 0, 2, 3, 4, 4, 5, 5 }
};
int row, col;
bool success = CheckPattern(temp, a, out row, out col);
Console.WriteLine("Success: {0}, row: {1}, col: {2}", success, row, col);
and then
private static bool CheckPattern(int?[,] temp, int[,] data, out int row, out int col)
{
int rowsT = temp.GetLength(0);
int colsT = temp.GetLength(1);
int rowsD = data.GetLength(0);
int colsD = data.GetLength(1);
// Find the "maximum" value of the template (how many different
// condition are there... If there is only "X" then 1, "X", "Y" then 2,
// "X", "Y", "Z" then 3...
int max = -1;
for (int i = 0; i < rowsT; i++)
{
for (int j = 0; j < rowsT; j++)
{
if (temp[i, j] != null)
{
max = Math.Max(temp[i, j].Value, max);
}
}
}
// We save in an array the "current" values of "X", "Y", "Z", ...
int?[] values = new int?[max + 1];
for (int i = 0; i < rowsD - rowsT + 1; i++)
{
for (int j = 0; j < colsD - colsT + 1; j++)
{
Array.Clear(values, 0, values.Length);
bool success = true;
// Check the template
for (int k = 0; k < rowsT; k++)
{
for (int r = 0; r < colsT; r++)
{
if (temp[k, r] != null)
{
int? curr = values[temp[k, r].Value];
if (curr == null)
{
// If this is the first time we check this
// condition, then any value is good
values[temp[k, r].Value] = data[i + k, j + r];
}
else if (curr.Value == data[i + k, j + r])
{
// For subsequent instances we check this
// condition, then the data must have the
// value found in the previous instance
}
else
{
success = false;
break;
}
}
}
if (!success)
{
break;
}
}
if (success)
{
row = i;
col = j;
return true;
}
}
}
row = 0;
col = 0;
return false;
}
This piece of code should work even for multiple conditions "X", "Y"...
I dont't have any code for this, but I do want to know how I could do this. I use visual studio 2010 C# if that matters.
Thanks
Jason
public static void Print2DArray<T>(T[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i,j] + "\t");
}
Console.WriteLine();
}
}
you can print it all on one line
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Console.WriteLine(String.Join(" ", array2D.Cast<int>()));
output
1 2 3 4 5 6 7 8
You should read MSDN:Using foreach with Arrays
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55
//The following are three ways to print any 2d arrays to console:
int[,] twoDArray = new int[3, 4]{ {2,5,55,44},{10,45,5,22 },{ 67,34,56,77} };
Console.WriteLine("Array Code Out Method:1");
int rows = twoDArray.GetLength(0); // 0 is first dimension, 1 is 2nd
//dimension of 2d array
int cols = twoDArray.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write("\t" + twoDArray[i, j]);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
}
Console.WriteLine("Array Code Out Method: 2");
for (int x = 0; x <= twoDArray.GetUpperBound(0); x++)
{
for (int y = 0; y <= twoDArray.GetUpperBound(1); y++)
{
Console.Write("\t"+ twoDArray[x,y]);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
}
Console.WriteLine("Array Code Out Method:3");
foreach (int items in twoDArray)
{
Console.Write(""+ "\t" +items);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
//string example
string[,] friendNames = new string[,] { {"Rosy","Amy"},
{"Peter","Albert"}
};
foreach (string str in friendNames)
{
Console.WriteLine(str);
}
The following is an example...
static void Main()
{
// A. 2D array of strings.
string[,] a = new string[,]
{
{"ant", "aunt"},
{"Sam", "Samantha"},
{"clozapine", "quetiapine"},
{"flomax", "volmax"},
{"toradol", "tramadol"}
};
// B. Get the upper bound to loop.
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
string s1 = a[i, 0]; // ant, Sam, clozapine...
string s2 = a[i, 1]; // aunt, Samantha, quetiapine...
Console.WriteLine("{0}, {1}", s1, s2);
}
Console.WriteLine();
}
int[,] matrix = new int[2, 2] { {2, 2}, {1, 1} };
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int k = 0; k < matrix.GetLength(1); k++ )
{
//put a single value
Console.Write(matrix[i,k]);
}
//next row
Console.WriteLine();
}
private int[,] MirrorH(int[,] matrix)
{
int[,] MirrorHorizintal = new int[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j ++)
{
MirrorHorizintal[i, j] = matrix[i, 3 - j];
}
}
return MirrorHorizintal;
}
Try like this..
int[,] matrix = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
int rowLength = matrix.GetLength(0);
int colLength = matrix.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.Read();
Below is multiple solution to how to implement multidimentional array, I think it is pretty straight forward in c#.
using System;
using System.Collections.Generic;
namespace DataStructure
{
class Program : SortedZeros
{
static void Main(string[] args)
{
// Two-Dimensional Array
int[,] numbers2D = new int[3, 2]
{
{ 9, 99 },
{ 3, 33 },
{ 5, 55 }
};
// 3 * 3
int[,] dataTest2D = new int[3, 3]
{
{3, 5, 7},
{4, 3, 8},
{9, 6, 9},
};
// A similar array with string elements.
int[,] matrix = new int[4, 4]
{
{1, 2, 3, 6},
{4, 5, 6, 4},
{7, 8, 9, 6},
{7, 8, 9, 2},
};
int rowLength = matrix.GetLength(0);
int colLength = matrix.GetLength(0);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
// using foreach to print out the 2 * 2 in one straightline
foreach (int i in numbers2D)
{
Console.Write("{0} ", i);
}
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i < dataTest2D.GetLength(0); i++)
{
for (int j = 0; j < dataTest2D.GetLength(1); j++)
{
Console.Write(string.Format("{0} ", dataTest2D[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
}
}
}
Explanation:
1. create an array
2. Create 2 for loops (one inside the other)
3. In "j" loop, pass matrix (roomString in our case) as parameter.
4. Add a "+" symbol (concatenate) it with a " " (empty space)
5. In "i" loop, have a "cw tab tab" --> Console.WriteLine();
Code:
string[,] roomString = new string[4, 4]
{
{"0","0","0","0" },
{"0","0","0","0" },
{"0","0","0","0" },
{"0","0","0","0" }
};
for (int i = 0; i < roomString.GetLength(0); i++)
{
for (int j = 0; j < roomString.GetLength(1); j++)
{
Console.Write(roomString[i,j]+" ");
}
Console.WriteLine();
}
Helper function to get any row:
public static int[] GetRow(int[,] mat, int rowNumber)
=> Enumerable.Range(0, mat.GetLength(1))
.Select(i => mat[rowNumber, i])
.ToArray();
Print row values in new line:
int[,] mat = new int[2,2];
for (int i =0; i < mat.GetLength(0); i++)
{
Console.WriteLine(string.Join(",", GetRow(mat, i)));
}
Do it like this:
static public void Print2DArray(int[][] A)
{
foreach (int[] row in A)
{
foreach (int element in row)
{
Console.Write(element.ToString() + " ");
}
Console.WriteLine();
}
}
Given an array say nums = { 1,2,5,3,6,-1,-2,10,11,12}, using max no of elements (say maxNums=3)
find the elements whose sum (say sum =10) = K
so if maxNums to be used = 3
sum to find = 10
the the answer is
{1 3 6}
{1 -1 10}
{1 -2 11}
{2 5 3}
{2 -2 10}
{5 6 -1}
{-1 11}
{-2 12}
{10}
I wrote a recursive function which does the job. How do I do it without recursion?
and/or with less memory ?
class Program
{
static Int32[] nums = { 1,2,5,3,6,-1,-2,10,11,12};
static Int32 sum = 10;
static Int32 maxNums = 3;
static void Main(string[] args)
{
Int32[] arr = new Int32[nums.Length];
CurrentSum(0, 0, 0, arr);
Console.ReadLine();
}
public static void Print(Int32[] arr)
{
for (Int32 i = 0; i < arr.Length; i++)
{
if (arr[i] != 0)
Console.Write(" " +arr[i]);
}
Console.WriteLine();
}
public static void CurrentSum(Int32 sumSoFar, Int32 numsUsed, Int32 startIndex, Int32[] selectedNums)
{
if ( startIndex >= nums.Length || numsUsed > maxNums)
{
if (sumSoFar == sum && numsUsed <= maxNums)
{
Print(selectedNums);
}
return;
}
**//Include the next number and check the sum**
selectedNums[startIndex] = nums[startIndex];
CurrentSum(sumSoFar + nums[startIndex], numsUsed+1, startIndex+1, selectedNums);
**//Dont include the next number**
selectedNums[startIndex] = 0;
CurrentSum(sumSoFar , numsUsed , startIndex + 1, selectedNums);
}
}
You function looks fine but possible a bit optimize:
class Program
{
static Int32[] nums = { 1, 2, 5, 3, 6, -1, -2, 10, 11, 12 };
static Int32 sum = 10;
static Int32 maxNums = 3;
static Int32[] selectedNums = new Int32[maxNums];
static void Main(string[] args)
{
CurrentSum(0, 0, 0);
Console.ReadLine();
}
public static void Print(int count)
{
for (Int32 i = 0; i < count; i++)
{
Console.Write(" " + selectedNums[i]);
}
Console.WriteLine();
}
public static void CurrentSum(Int32 sumSoFar, Int32 numsUsed, Int32 startIndex)
{
if (sumSoFar == sum && numsUsed <= maxNums)
{
Print(numsUsed);
}
if (numsUsed >= maxNums || startIndex >= nums.Length)
return;
for (int i = startIndex; i < nums.Length; i++)
{
// Include i'th number
selectedNums[numsUsed] = nums[i];
CurrentSum(sumSoFar + nums[i], numsUsed + 1, i + 1);
}
}
}
Also I fixed a bug in your function.
It fails on following testcase:
{10, 2, -2}
Sum = 10
K = 3
Your functions returns only {10} instead of {10} and {10, 2, -2}
And the Haskell solution...
import Data.List
listElements max_num k arr =
filter (\x -> sum x == k && length x == max_num) $ subsequences arr
*Main> listElements 3 10 [1,2,5,3,6,-1,-2,10,11,12]
[[2,5,3],[1,3,6],[5,6,-1],[1,-1,10],[2,-2,10],[1,-2,11]]