Right shift elements in an array by n - c#

I want to shift elements in one array to right by only changing the index. Also I don't want to use built-in functions
For example, if we have
8,6,5,3,9
Then We will have
9,8,6,5,3
If the array doesn't have enough length. the rest of the elements shift will start from the first index of array.
int index = 0, temp = 0;
int[] myarray = new int[int.Parse(Console.ReadLine())];
for (int i = 0; i < myarray.Length; i++)
{
myarray[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < myarray.Length; i++)
{
if (myarray.Length <= i + 5)
{
index = ((i + 5) % 5);
temp = myarray[index];
myarray[index] = myarray[i];
myarray[i] = temp;
}
else
{
temp = myarray[i + 5];
myarray[i + 5] = myarray[i];
myarray[i] = temp;
}
}
this is what i have tried but its not working

If shift count is less than or equal array size you can use this code (I edited answer by this link):
using System;
int M = 5;//shift count
int size; //size of array
int[] myarray = new int[int.Parse(Console.ReadLine())];
for (int i = 0; i < myarray.Length; i++)
{
myarray[i] = int.Parse(Console.ReadLine());
}
size = myarray.Length;
if (size >= M)
{
Array.Reverse(myarray, 0, size);
Array.Reverse(myarray, 0, M);
Array.Reverse(myarray, M, size - M);
for (int i = 0; i < myarray.Length; i++)
{
Console.Write(myarray[i]+"\t");
}
Console.Read();
}

Related

The Snake in the 2D array

I have to write a program that creates a two dimensional array and fills it like a snake. Here is the task itself:
Blockquote write a program that creates a two-dimensional numeric array and this array is filled with a "snake": first the first row (from left to right), then the last column (from top to bottom), the last row (from right to left), the first column (from bottom to top), the second row ( left to right), etc.
I tried to write something, but bugs constantly appear. Please help to shorten this code and make it correct.
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int len = rand.Next(5, 20);
int wid = rand.Next(5, 20);
int[,] arr = new int[len, wid];
int num = 10;
int line = 0;
int line2 = len;
int col = wid - 1;
int col2 = 0;
for (int i = 0; i <= (len > wid ? len : wid); i++)
{
for (int k = 0; k < wid; k++, num++)
{
arr[line, k] = num;
}
line++;
for (int k = 0; k < len; k++, num++)
{
arr[k, col] = num;
}
col++;
for (int k = (wid - 1); k >= 0; k--, num++)
{
arr[line2, k] = num;
}
line2++;
for (int k = 0; k < (len - 1); k++, num++)
{
arr[k, col2] = num;
}
col2++;
}
for (int i = 0; i <= len; i++)
for (int q = 0; q <= wid; q++)
{
Console.WriteLine(arr[i, q] + " ");
}
}
}

Improved Selection Sort Out of Bounds Error

I have a method that is an "Improved version of Selection Sort". However, the code is not running as " temp[x] = 0;" this line gives an out of bounds of the array error. I do not want to use an ArrayList. How would I change this line to be in bounds of the array?
public static void ImprovedSelectionSort(int[] Array)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int[] temp = new int[Array.Length];
for (int x = 1; x <= Array.Length; x++)
{
//OtherList.Add(0); -- what I want to do
temp[x] = 0;
}
int n = Array.Length;
int i = 0;
while (i < n)
{
int rear = 0;
int curMax = Array[i];
temp[rear] = i;
int j = i + 1;
while (j < n)
{
if (curMax < Array[j])
{
curMax = Array[j];
rear = -1;
}
if (curMax == Array[j])
{
rear = rear + 1;
temp[rear] = j;
}
j++;
}
int front = 0;
int p = Array[temp[front]];
while (front <= rear)
{
int temporary = p;
Array[temp[front]] = Array[i];
Array[i] = temporary;
i++;
front += 1;
}
}
for (int x = 1; x <= Array.Length; x++)
This is most likely the issue. The last index in an array is the length minus 1 (so, a 52-card deck goes from 0..51). Changing the "x <= Array.Length" component to "x < Array.Length" should fix the issue.
Change the <= to < in the for loop. This is a common mistake among novice devs, and not something you should sweat. But it's a good thing to keep in mind for the future.

How to find the maximal (longest) sequence of increasing elements in an array arr[n]?

I need to write a program, which finds the maximal sequence of increasing elements in an array arr[n]. It is not necessary the elements to be consecutively placed. E.g.: {9, 6, 2, 7, 4, 7, 6, 5, 8, 4} -> {2, 4, 6, 8}.
I have some guidelines to use 2 nested loops and one additional array.
So far i know how to use if statements, loops and little arrays.
Any suggestions pls...?
This is my start so far (am I on a good track?):
Console.Write("Elements in array: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
int[] result;
for (int index = 0; index < arr.Length; index++)
{
Console.Write("Array [{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
for (int indexOut = 0; indexOut < n; indexOut++)
{
for (int indexIn = 1; indexIn < n; indexIn++)
{
}
}
nested loops are 1 loop inside another:
for (int 1 = 0; i < something.length; i++) {
for ( int j = 0; j < somethingElse.length; j++) {
// code
}
}
I think I found your solution here:
http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/
/* Dynamic Programming C/C++ implementation of LIS problem */
#include<stdio.h>
#include<stdlib.h>
/* lis() returns the length of the longest increasing
subsequence in arr[] of size n */
int lis( int arr[], int n )
{
int *lis, i, j, max = 0;
lis = (int*) malloc ( sizeof( int ) * n );
/* Initialize LIS values for all indexes */
for ( i = 0; i < n; i++ )
lis[i] = 1;
/* Compute optimized LIS values in bottom up manner */
for ( i = 1; i < n; i++ )
for ( j = 0; j < i; j++ )
if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for ( i = 0; i < n; i++ )
if ( max < lis[i] )
max = lis[i];
/* Free memory to avoid memory leak */
free( lis );
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LIS is %d\n", lis( arr, n ) );
return 0;
}
You will have to modify it a little to generate the actual array.
My code:
// Arr[]
int n = 10;
int[] arr = new int[n];
for (int index = 0; index < n; index++)
{
Console.Write("Array[{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
// Len[]
int[] len = new int[n];
for (int index = 0; index < n; index++)
{
len[index] = 1;
}
// Correct len[]
for (int indexCount = 1; indexCount < n; indexCount++)
{
for (int indexNumber = 0; indexNumber < indexCount; indexNumber++)
{
if (arr[indexCount] > arr[indexNumber] && len[indexCount] < len[indexNumber] + 1)
{
len[indexCount] = len[indexNumber] + 1;
}
}
}
// Print new len[]
// Just to keep track of numbers
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < n; index++)
{
Console.Write(" " + len[index] + " ");
}
Console.WriteLine("}");
// Search for the max number in len[]
int max = int.MinValue;
int maxPosition = 0;
for (int index = 0; index < len.Length; index++)
{
if (len[index] > max)
{
max = len[index];
maxPosition = index;
}
}
// Create the result in result[]
int[] result = new int[max];
int i = (max - 1);
int maxCount = max;
for (int index = maxPosition; index >= 0; index--)
{
if (len[index] == max)
{
result[i] = arr[index];
max--;
i--;
}
}
// Print the result[]
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < maxCount; index++)
{
Console.Write(" " + result[index] + " ");
}
Console.WriteLine("}");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int maincount = 0;
int indices = 0;
int increment = 0;
int count = 0;
int finalcount = 0;
int checkvalue = 0;
string consincval = null;
string consincval1 = null;
string finalconsincval = null;
Console.WriteLine("Enter number of rows of the array");
int len = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns of the array");
int wid = int.Parse(Console.ReadLine());
int[,] consecincrease = new int[len, wid];
Console.WriteLine("Enter the Values of array");
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
consecincrease[index, index1] = int.Parse(Console.ReadLine());
Console.Write("The value of the {0} {1}" + ":" + " " + "{2}", index, index1, consecincrease[index, index1]);
Console.WriteLine();
}
}
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
increment = 0;
checkvalue = consecincrease[index, index1];
for ( indices = increment; indices < consecincrease.GetLength(1)-1; indices++)
{
if (checkvalue < consecincrease[index, indices +1])
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
checkvalue = consecincrease[index, indices+1];
consincval1 = consincval1 + " " + consincval + " ";
}
}
if (count == 0)
{
}
else if (count >= 1)
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
consincval1 = consincval1 + " " + consincval + " ";
}
if (finalcount < maincount)
{
finalcount = maincount;
finalconsincval = consincval1;
count = 0;
consincval1 = null;
consincval = null;
}
else
{
count = 0;
consincval1 = null;
consincval = null;
}
increment ++;
}
}
Console.WriteLine();
Console.WriteLine(finalconsincval);
Console.ReadLine();
}
}
}

how to remake 2d array random unique numbers as 3d?

static void Main(string[] args)
{
Random r = new Random();
int[,] x = new int[10,8];
int[] temp = new int[x.Length];
// two dimensional array and i want for three dimensional array
for(int i = 0; i < temp.Length; i++)
{
temp[i] = r.Next(10, 100);
for(int j = 0; j < i; j++)
{
if(temp[i] == temp[j])
{
i--;
break;
}
}
}
for(int i = 0, index = 0; i < x.GetLength(0); i++)
{
for(int j = 0; j < x.GetLength(1); j++)
{
x[i, j] = temp[index++]; //two dimensional array unique numbers
Console.Write(x[i, j] + " ");
}
}
// i want do it as for 3D and 4 D array unique numbers like that method what can i change or add?
It's pretty straight forward to do what you're doing for higher dimensions.
Here's my code for 3D:
var r = new Random();
int [,,] x = new int[10, 8, 8];
var count =
Enumerable
.Range(0, x.Rank)
.Select(y => x.GetLength(y))
.Aggregate((y, z) => y * z);
var values =
Enumerable
.Range(10, count)
.OrderBy(y => r.Next())
.ToArray();
var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
x[i, j, k] = values[v++];
To change it to 4D these lines change:
int [,,,] x = new int[10, 8, 8, 12];
// ...
var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
for (var l = x.GetLowerBound(3); l <= x.GetUpperBound(3); l++)
x[i, j, k, l] = values[v++];
Now, in this code I have explicitly called GetLowerBound as well as GetUpperBound as it is possible in .NET code to have a non-zero based array.
Also, rather than repeatedly re-try getting random numbers until you have unique numbers I simply generated a sequence of unique numbers and then randomly sorted them. That's a little different from your original code. You needed 80 (10 x 8) random values and you were choosing from values ranging from 10 to 99 inclusive. So you had some holes in your numbers.
Random r = new Random();
int[,,] x = new int[10, 8, 8];
int[] temp = new int[x.Length];
#region one dimensional array unique numbers.
for (int i = 0; i < temp.Length; i++)
{
temp[i] = r.Next(10, 650);
for (int j = 0; j < i; j++)
{
if (temp[i] == temp[j])
{
i--;
break;
}
}
}
#endregion
for (int i = 0, index = 0; i < x.GetLength(0); i++)
{
for (int j = 0; j < x.GetLength(1); j++)
{
for (int k = 0; k < x.GetLength(2); k++)
{
x[i, j, k] = temp[index++];
Console.Write(x[i, j, k] + " ");
}
Console.WriteLine();
}
}// i think it's correct code i've changed it

Arranging values of array in Ascending order

I couldn't get it to work, I am trying to arrange the values of the array in ascending order by using for loop.
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
for (int i = 0; i <= arr.Length; i++)
{
if (arr[i] > arr[i + 1])
{
int temp = arr[i + 1];
arr[i] = arr[i + 1];
arr[i] = temp;
}
Console.Write(arr[i]);
}
I am assuming that you are not using Array.Sort because you are doing this as a learning exercise; there is no other way to avoid this very common library function.
The reason your algorithm does not work is that it is not enough to go through an array once, and swap items that are out of order. Try doing this as a mental experiment, when the array is almost sorted, but the first element is at the end, like this:
2 3 4 5 6 7 1
A single path would bring you closer, but it wouldn't bring you all the way to a sorted array:
2 3 4 5 6 1 7
As you can see, you have to repeat this process multiple times, until the array is sorted. How do you know that the array is sorted? You know that when the entire inner loop did not have a single swap.
Here is how you can implement this:
bool didSwap;
do {
didSwap = false;
for (int i = 0; i < arr.Length-1; i++)
{
if (arr[i] > arr[i + 1])
{
int temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
didSwap = true;
}
}
} while (didSwap);
for (int i = 0; i != arr.Length ; i++) {
Console.Write(arr[i]);
}
Note several changes from your code:
The printing is done in the separate loop, after the sorting is complete
The loop goes to arr.length-1, not to arr.length, because otherwise your last check will go outside the bounds of the array.
This sorting algorithm is called Bubble Sort. There are various optimizations to this algorithm that can make it go slightly faster.
In general, bubble sort is among the slower sorting algorithms. When the number of items to sort is high, you should consider an advanced algorithm, or use the library implementation.
int[] Array = { 11, 33, 5, -3, 19, 8, 49 };
int temp;
for (int i = 0; i < Array.Length - 1; i++)
{
for (int j = i + 1; j < Array.Length; j++)
{
if (Array[i] > Array[j])
{
temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
Console.Write("Sorted:");
foreach (int sort in Array)
Console.Write("{0} ", sort);
If you want to make your own sorting, then it's not enough to just loop through the items once and swap them. The closest to that is the bubble sort algorithm, where you loop over the array repeatedly until there is no more items to swap:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
bool swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i < arr.Length - 1; i++) {
if (arr[i] > arr[i + 1]) {
swapped = true;
int temp = arr[i + 1];
arr[i] = arr[i + 1];
arr[i] = temp;
}
}
}
for (int i = 0; i < arr.Length - 1; i++) {
Console.Write(arr[i]);
}
There are also built in methods to sort data, which is easier to use, more efficient, and already thoroughly tested:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
Array.Sort(arr);
Use Linq Order by:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
int[] ascOrderedArray = (from i in arr orderby i ascending select i).ToArray();
I think it could be easy and why do you need for loop.
using System;
namespace bubble_sort
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
int[] arr = new int[50];
int n;
Console.WriteLine("Enter no of elements you want to store in an array");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter elements in an array");
for (int i = 1; i <= n; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
p.bubblesort(arr, n);
Console.ReadKey();
}
public void bubblesort(int[] arr, int n)
{
int temp;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Console.WriteLine("Array after sorting");
for (int i = 1; i <= n; i++)
{
Console.WriteLine(arr[i]);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace basicsorting
{
public class Program
{
public static void Main(string[] args)
{
int i2, k, j;
Console.WriteLine("How many elements you want to sort? ");
i2 = Convert.ToInt32(Console.ReadLine());
int[] values = new int[i2];
int n1 = 0;
int n = 0; ;
int i;
Console.WriteLine("Enter the elements of array {0}", n1);
for (i = 0; i < i2; i++)
{
Console.WriteLine("Enter the elements of array {0}");
n = Convert.ToInt32(Console.ReadLine());
Convert.ToInt32(values[i] = n);
}
for (i = 0; i < i2; i++)
{
k = Convert.ToInt32(values[i]);
for (j = i - 1; j >= 0 && k < values[j]; j--)
values[j + 1] = values[j];
values[j + 1] = k;
}
for (i = 0; i < i2; i++)
{
Console.WriteLine("sorting elements {0}", values[i]);
}
Console.ReadLine();
}
}
}
int[] array = new int[] { 8, 9, 5, 6, 7, 4, 3, 2, 1 };
int[] outPut = new int[] { };
int temp = 0;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
var first = array[i];
var second = array[j];
if (array[i] < array[j]) {
temp = first;
array[i] = second;
array[j] = temp;
}
}
}
foreach (var item in array) {
Console.WriteLine(item);
}
Console.ReadKey();
}
foreach (var item in array) {
Console.WriteLine(item);
}
Console.ReadKey();
int temp = 0;
int[] arr = new int[] { 5, 6, 2, 4, 1 };
for (int i = 0; i <= arr.Length - 1; i++)
{
for (int j = i + 1; j <= arr.Length - 1; j++)
{
if (arr[i] > arr[j]) //> Asecnding Order < Desending Order
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Console.Write(arr[i]);
}
Console.ReadLine();
public int[] sortArray(params int[] numbers)
{
for(int i = 0; i < numbers.Length; i++)
{
for(int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] < numbers[j])
{
continue;
}else if (numbers[i] > numbers[j])
{
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
return numbers;
}
You should do like :
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
for (int i = 0; i < arr.Length-1; i++)
{
if (arr[i] < arr[i + 1])
{
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
// to verify sorted Array
for (int i = 0; i < arr.Length; i++)
{
console.write( arr[i].ToString());
}
For last 1 you need not to check it will be automatically ordered.
#Jon Skeet They wanted to use a for loop.
There are numerous types of sorts. The simplest is Bubble Sort.
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
//bubble sort
for (int i = arr.Length - 1; i > 0; i--)
{
for (int j = 0; j <= i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int highValue = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = highValue;
}
}
}
foreach(int i in arr) Console.Write(i);

Categories

Resources