How to reverse an array using three separate methods in C# - c#

I'm currently going through an ebook in order to learn C# and I am currently at a place where I am stuck. I feel that once I have pushed through and understand this next bit, it will really accelerate my understanding and learning as I move on to classes next.
The current challenge I face I must do the following :
Make a program that uses methods to reverse an array.
Create three methods: one to create the array, one to print the array and one to reverse the array.
Ideally it would allow the user to input the desired length of the array.
Not allowed to use the reverse array method.
This is the code I have gotten so far but I'm extremely stuck on how to create the reverse method and I feel like what I currently have isn't what is required either. I just need that extra push here for it to click in place and for me to get the understanding I need. Feel free to just positions hints / tips / advice as oppose to the solution if you so wish.
Thank you all.
using System;
namespace Using_methods_to_reverse_an_array
{
class Program
{
static int[] CreateArray()
{
int[] array = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return array;
}
static void PrintNumbers()
{
foreach (int numbers in CreateArray())
{
Console.WriteLine(numbers);
}
}
static void Main(string[] args)
{
int[] numbers = CreateArray();
PrintNumbers();
Console.ReadLine();
}
}
}

static int[] Reverse(int[] arr){
int [] arr2 = new int[arr.Length];
for (int i = arr.Length - 1, i2 = 0; i >= 0; i--, i2++)
{
arr2[i2] = arr[i];
}
return arr2;
}
static void PrintNumbers(int[] arr)
{
foreach (int numbers in arr)
{
Console.WriteLine(numbers);
}
}
static void Main(){
int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] arr2 = Reverse(arr);
PrintNumbers(arr2);
}
prints
10
9
8
7
6
5
4
3
2
1

Thanks a ton for the help everyone, after doing some more Googling and tests my final product is this :
using System;
namespace Using_methods_to_reverse_an_array
{
class Program
{
static int[] CreateArray()
{
int[] array = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return array;
}
static void PrintNumbers(int[] array)
{
foreach (int numbers in array )
{
Console.WriteLine(numbers);
}
}
static void ReverseNumbers(int[] array)
{
for (int i = 0; i < array.Length/2; i++)
{
int temp = array[i];
array[i] = array[array.Length - i - 1];
array[array.Length - i - 1] = temp;
}
}
static void Main(string[] args)
{
int[] numbers = CreateArray();
ReverseNumbers(numbers);
PrintNumbers(numbers);
Console.ReadLine();
}
}
}

Maybe I misunderstood, but I think this should do it:
class Program
{
static int[] CreateArray()
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
return array;
}
//I changed this to receive an input array
static void PrintNumbers( int[] inputArray)
{
foreach (int numbers in inputArray)
{
Console.WriteLine(numbers);
}
}
//this function should reverse any array passed to it
static void ReverseArray(int[] inputArray)
{
int len = inputArray.Length;
int[] newArray = new int[len];
foreach (int i in inputArray)
{
newArray[i] = inputArray[len - 1];
len--;
}
}
static void Main(string[] args)
{
int[] numbers = CreateArray();
PrintNumbers(numbers);
ReverseArray(numbers);
//Console.ReadLine();
}
}

Related

How can find the repeated values in the given two arrays without nested foreach loops?

I want to find the repeated values in two different arrays.
I'm trying not to repeat code and am always interested in shorter ways to implement things. As I mentioned at the title in the method that I wrote below, a foreach loop is used twice and they are nested.
Can I write this code without nesting the foreach loops in way that's as short or shorter?
static void Main(string[] args)
{
//Arrays to find the repeated values in both arrays
int[] array1 = new int[5] { 1, 2, 3, 4, 5 };
int[] array2 = new int[8] { 3, 5, 5, 9, 11, 13, 15, 17 };
//Final Array
int[] array3 = findTheIntersect(array1, array2);
foreach (int item in array3)
{
Console.WriteLine($"{item}, Array Length: {array3.Length}");
}
Console.ReadKey();
}
public static int[] findTheIntersect(int[] arr1, int[] arr2)
{
//Size of the final array
int arrSize = 0;
//Item variable that we will add to final array
int arrItem = 0;
//Temporary List to store repeated items
List<int> arrList = new List<int>();
foreach (int number in arr1)
{
int x = number;
foreach (int number1 in arr2)
{
int y = number1;
if (y == x && !arrList.Contains(number1))
{
arrSize++;
arrItem = number1;
arrList.Add(arrItem);
}
}
}
int[] finalArr = new int[arrSize];
finalArr = arrList.ToArray();
return finalArr;
}
When I searched for existing solutions, I only found answers for repeating values in just one array, rather than comparing two different arrays.
Using the LINQ (System.Linq) one-liner, use Intersect. Just remember that the position of the element in the list isn't taken into account.
int[] duplicates = array1.Intersect(array2).ToArray();

Return an array of ints containing the number of elements of each inner array c#

I want to write a function which, given an array of arrays of integers in input, returns an array of integers in output, containing the number of elements of each inner array.
This is my current implementation:
public static int[] countEach(int[][] a) {
int[] count = new int[3];
for(int i = 0; i < a.Length; i++){
count[i] = a[i].Length;
}
return count;
}
public static void Main(string[] args){
int[][] a = new int[][]{
new int[] {1, 2, 3},
new int[] {1, 2, 3, 4, 5},
new int[] {1}
};
int[] result = countEach(a);
}
It works, however i dont want to define a fixed length of 3 beforehand. So how do i rewrite this so that it can take any input array? I cant think of any, and is there a better way to code this? So i can better grasp the programming concepts of c#. Thanks
You can use Linq, by Selecting length of nested arrays and call .ToArray() to convert IEnumerable to array :
int[] result = a.Select(x => x.Length).ToArray();
Namespace :
using System.Linq;
I hope you find this helpful.
public static int[] countEach(int[][] a) {
int[] count = new int[a.Length];
for(int i = 0; i < a.Length; i++){
count[i] = a[i].Length;
}
return count;
}

How to input and output values in array [][,] and [,][] (mix of jagged array and multidimensional array)

I am trying to improve my code on how to find items in my multidimensional array, because I want to avoid possible future performance issues when I increase the data volume. I am a newbie to programming, so there are lots of stuff I do not know. I have been searching a lot around topics multidimensional array, jagged arrays, sorting. I think I need to use jagged array because I need to sort in order to locate third largest and 6.largest number. But I realize that I have to ask for some assistance on examples or link to more information because I am having problems making progress in defining my jagged array. I will try to isolate each issue because I get stuck on things I believe might be easy for people that are more familiar with arrays than me. It should be possible to mix jagged and multidimensional arrays according to jagged-arrays
Here is example of [][] which is working
using System;
using System.Collections;
namespace SortJaggedArray
{
class host
{
[STAThread]
static void Main(string[] args)
{
int[][] arr = new int[2][];
arr[0] = new int[3] {1,5,3};
arr[1] = new int[4] {4,2,8,6};
// Write out a header for the output.
Console.WriteLine("Array - Unsorted\n");
for (int i = 0; i < arr.Length; i++)
{
System.Console.WriteLine("Outer array " + i);
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j] + " ");
}
System.Console.WriteLine(" ");
System.Console.WriteLine(" ");
}
Console.ReadLine();
}
}
}
//Output:
//Outer array 0
//1 5 3
//Outer array 1
//4 2 8 6
Here is my example of [][,] where the input is working, but I struggle with how to write the output:
using System;
using System.Collections;
namespace SortJaggedArray
{
class host
{
[STAThread]
static void Main(string[] args)
{
int[][,] arr = new int[2][,]
{
new int[,] { { 1, 3 }, { 5, 2 }, { 3, 9 } },
new int[,] { { 4, 1 }, { 2, 7 }, { 8, 5 }, { 6, 3 } }
};
// Write out a header for the output.
Console.WriteLine("Array - Unsorted\n");
foreach (int i in arr)
Console.WriteLine(i);
Console.ReadLine();
}
}
}
Wanted output:
Nr 0:
1, 3
5, 2
3, 9
Nr 1:
4, 1
2, 7
8, 5
6, 3
Question 1:
How to write the WriteLine / for / foreach in order to see the content of the jagged array [][,] ?
Question 2:
I want to change this into [,][] but then I get problems in how to input/output data in such jagged array. How to input data? How to Writeline / for / forearch to see the content of jagged array [,][] ?
You need to iterate over every dimension:
for(int i=0; i<arr.Length; i++){
Console.WriteLine($"Nr {i}:");
for(int j=0;j<arr[i].GetLength(0);j++){
for(int k=0;k<arr[i].GetLength(1);k++){
Console.Write($"{arr[i][j,k]} ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Outputs:
Nr 0:
1 3
5 2
3 9
Nr 1:
4 1
2 7
8 5
6 3
package array;
import java.util.Scanner;
public class multiDimensionalArray {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i, j;
int values[][]=new int [3][3];
System.out.println("Enter array values");
for(i=0; i<3; i++) {
for(j=0; j<3; j++) {
values[i][j]=sc.nextInt();
}
}
System.out.println("Entered values are: \t");
for(i=0; i<3; i++) {
for(j=0; j<3; j++) {
System.out.print("\t"+values[i][j]);
}
System.out.print("\n");
}
}
}
In case other readers have the same question, I want to add code example on how Magnetron's example also helped me to solve the same issue for array [,][]
using System;
using System.Collections;
namespace SortJaggedArray
{
class host
{
[STAThread]
static void Main(string[] args)
{
int[,][] arr = new int[2,3][];
arr[0,0] = new int[3] { 1, 5, 3 };
arr[0,1] = new int[4] { 4, 2, 8, 6 };
arr[0,2] = new int[2] { 2, 8 };
arr[1,0] = new int[2] { 7, 5 };
arr[1,1] = new int[5] { 8, 7, 5, 9, 2 };
arr[1,2] = new int[2] { 1, 4};
// Write out a header for the output.
Console.WriteLine("Array - Unsorted\n");
for (int i = 0; i < arr.GetLength(0); i++)
{
Console.WriteLine($"Nr {i}:");
for (int j = 0; j < arr.GetLength(1); j++)
{
for (int k = 0; k < arr[i,j].Length; k++)
{
Console.Write($"{arr[i,j][k]} ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
//Output:
//Nr 0:
//1 5 3
//4 2 8 6
//2 8
//Nr 1:
//7 5
//8 7 5 9 2
//1 4

In c#, how can i rotate a list a specific amount of places?

I wrote a code to rotate a list a specific amount of places, the code I have below works but i would like to know if there is a more efficient way to do this.
public void Test8(List<int> items, int places)
{
int nums;
for (int i = 0; i < places; i++)
{
nums = items[items.Count() - 1];
items.RemoveAt(items.Count - 1);
items.Insert(0, nums);
}
}
This is a classic computer science problem. One technique that's slightly faster is to reverse the entire array, then reverse the two chunks of the array:
// If we want to shift two places, start with an array
[1, 2, 3, 4, 5, 6, 7, 8]
// Then reverse the entire array
[8, 7, 6, 5, 4, 3, 2, 1]
// Then reverse the first n elements, two in our case
[7, 8, 6, 5, 4, 3, 2, 1]
^^^^
// Then reverse the remaining items
[7, 8, 1, 2, 3, 4, 5, 6]
^^^^^^^^^^^^^^^^
Or, as code:
static void Reverse(List<int> items, int posFrom, int posTo)
{
// Helper to reverse a sub portion of an array in place
while (posFrom < posTo)
{
// Swap the first and last items
int temp = items[posFrom];
items[posFrom] = items[posTo];
items[posTo] = temp;
// Shrink down to the next pair of items
--posTo;
++posFrom;
}
}
static void Test8(List<int> items, int places)
{
// Sanity, if we try to rotate more than there are
// items in the array, it just loops around
places %= items.Count;
// Reverse the entire array
Reverse(items, 0, items.Count - 1);
// Reverse the first group of items
Reverse(items, 0, places - 1);
// Reverse the second group of items
Reverse(items, places, items.Count - 1);
}
This is O(n) time, irregardless of the shift size.
It can be faster if you implement it using Circular Array QUEUE (which theoritically have better memory management than the list). This does not need physically rotating the existing data, so it should be faster than your original code.
BTW, you can read other references in StackOverflow to enrich your knowledge, for ex:
Easiest way to Rotate a List in c#
Performance differences... so dramatic?
You are inserting and removing list elements. There is some overhead associated with that. A list can be accessed by index. You can therefore loop through the list, moving elements to the position they should be in. You will need to use a temporary integer variable to avoid overwriting any list data.
Also good to check and make sure the rotation isn't nonsensical, i.e. rotating a list of length 3 right 5K by removing and adding items 5K times doesn't make sense, you can do that by doing something like places%=items.Count; before you start rotating.
Here is a similar question:
C# Collection - Order by an element (Rotate)
Also, try this:
static void Main(string[] args)
{
var items = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var rotatedItems = Rotate(items, 4);
// rotated is now {5, 6, 7, 8, 9, 1, 2, 3, 4}
Console.WriteLine(string.Join(", ", rotatedItems));
Console.Read();
}
public static IEnumerable<int> Rotate(IEnumerable<int> items, int places)
{
return items.Skip(places).Concat(items.Take(places));
}
You can write a user defined extension of List<int> that does the rotation by using List<T>.Reverse().
I took the basic idea from the C++ Standard Template Library which basically uses Reverse in three steps:
Reverse(first, mid)
Reverse(mid, last)
Reverse(first, last)
As far as I know, this is the most efficient and fastest way. I tested with 1 billion elements and the rotation Rotate(0, 50000, 800000) takes 0.00097 seconds.
(By the way: adding 1 billion ints to the List already takes 7.3 seconds)
Here's the extension you can use:
public static class Extensions
{
public static void Rotate(this List<int> me, int first, int mid, int last)
{
//indexes are zero based!
if (first >= mid || mid >= lastIndex)
return;
me.Reverse(first, mid - first + 1);
me.Reverse(mid + 1, last - mid);
me.Reverse(first, last - first + 1);
}
}
The usage is like:
static void Main(string[] args)
{
List<int> iList = new List<int>{0,1,2,3,4,5,6,7,8,9};
Console.WriteLine("Before rotate:");
foreach (var item in iList)
{
Console.Write(item + " ");
}
Console.WriteLine();
int firstIndex = 0, midIndex = 3, lastIndex = 5;
iList.Rotate(firstIndex, midIndex, lastIndex);
Console.WriteLine($"After rotate {firstIndex}, {midIndex}, {lastIndex}:");
foreach (var item in iList)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
Circular Right-Shift Array with specified number of times in ArrayList.
Specified Range of array elements and circular shift.
become faster code as compare with array implementation
Code
using System;
using System.Collections;
public class Program
{
// Circular Array repeting logic in ArrayList
public static ArrayList CircularshiftArry(ArrayList a, int circularrep)
{
int I = 1;
while (I <= circularrep)
{
int n = a.Count;
a.Insert(0, a[n - I]);
I++;
}
return a;
}
public static void Main()
{
Console.WriteLine("ENTER HOW MANY CIRCULAR REPETATION YOU WANT");
int circularrep = int.Parse(Console.ReadLine());
ArrayList a = new ArrayList();
Console.WriteLine("HOW MANY ARRAY ELEMENTS YOU WANT TO ENTER");
int num = int.Parse(Console.ReadLine());
for (int i = 0; i < num; i++)
{
Console.WriteLine("ENTER ARRAY ELEMENTS:{0}", i);
int p = int.Parse(Console.ReadLine());
a.Add(p);
}
Console.WriteLine("\n");
Console.WriteLine("The enterd array is :");
for (int i = 0; i < num; i++)
{
Console.Write("{0}\t", a[i]);
}
ArrayList b = CircularshiftArry(a, circularrep);
Console.WriteLine("\n");
int N = b.Count;
Console.WriteLine("The {0}times circular shifted array is :", circularrep);
for (int i = 0; i < N - circularrep; i++)
{
Console.Write("{0}\t", b[i]);
}
Console.ReadLine();
}
}
This is the output in console window

How to repeat the array elements with specific sequence according to some number?

If I have this array of integers :
int[] columns_index = { 2, 3, 4};
How can i repeat this sequence according to given number (size)?
For example :
if i give u 4 as a size then the array will be
{2,3,4,2}
if i give u 5 as a size then the array will be
{2,3,4,2,3}
if i give u 6 as a size then the array will be
{2,3,4,2,3,4}
if i give u 7 as a size then the array will be
{2,3,4,2,3,4,2}
And so on ...
Just use the modulo operator to iterate through the columns_index
int input = 7; // change this to user input of whatever it needs to be
int[] numbers = new int[ input ];
for ( int i = 0; i < input; i++ ){
int index = i % ( columns_index.length )
numbers[i] = columns_index[ index ];
}
public static class Extensions
{
public static T[] Multiply<T>(this T[] array, int length)
{
if ( array == null || array.Length == 0 || length <= array.Length )
return array;
var x = length % array.Length;
var y = length / array.Length;
return Enumerable.Range(1,y)
.SelectMany(c=>array)
.Concat(array.Take(x))
.ToArray();
}
}
One can use the Linq Repeat() and Take() functions to get the result.
private readonly static int[] Source = { 2, 3, 4 };
[TestMethod]
public void TestMethod1() {
Assert.IsTrue(new []{ 2, 3, 4, 2}.SequenceEqual(GetSequence(Source,4)));
Assert.IsTrue(new[] { 2, 3, 4, 2, 3 }.SequenceEqual(GetSequence(Source, 5)));
Assert.IsTrue(new[] { 2, 3, 4, 2, 3, 4 }.SequenceEqual(GetSequence(Source, 6)));
Assert.IsTrue(new[] { 2, 3, 4, 2, 3, 4, 2 }.SequenceEqual(GetSequence(Source, 7)));
}
private static int[] GetSequence(IEnumerable<int> src, int count) {
var srcRepeatCount = count / src.Count() + 1;
return Enumerable.Repeat(src, srcRepeatCount).SelectMany(itm => itm).Take(count).ToArray();
}
If you preferred to seperate the part where you use all in columns_index with the rest
int input = 1000001;
int[] columns_index = { 2, 3, 4 };
int[] numbers = new int[input];
// Times we can use everything in columns_index
int times = input/columns_index.Length; // 333333
List<int> numbersList = new List<int>();
for (int i = 0; i < times; i++)
{
numbersList.AddRange(columns_index);
}
// numbersInt.Count is now 999999..
// Times for the rest
int modTimes = input%(columns_index.Length); // 2
for (int j = 0; j < modTimes; j++)
{
numbersList.Add(columns_index[j]);
}
numbers = numbersList.ToArray();

Categories

Resources