moving every int in the array one place backwards - c#

I'm trying to move every int in array one "cell" (position) backwards (and take the first int to the last position) in a for loop. (example: if i have array of 5,6,9 the result will be 6,9,5).
Here is my code:
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length-1; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length - 1; i++)
{
Console.WriteLine(arr[i]);
}
Instead of getting
2,3,4,5,6,1
I'm getting
2,3,4,5,5.
Why is my code not working? What is the right way to do such process?

This code does what you need. Sort the array.
int[] arr = { 1, 2, 3, 4, 5, 6 };
//int[] arr = { 5, 6, 9 };
//string[] arr = { "A", "B", "C" };
var result = Enumerable.Range(1, arr.Length).Select(i => arr[i % arr.Length]).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
Input data and Results:
//Input: { 1, 2, 3, 4, 5, 6 };
//Result: 2,3,4,5,6,1
//Input: { 5, 6, 9 };
//Result: 6,9,5
//Input: { "A", "B", "C" };
//Result: B,C,A

Remove the -1 :
for (int i=1; i < arr.Length-1; i++)
in both loops and let the loops run until the end. The condition should be i < arr.Length You never reach the last position.
Although you use arr[arr.Length - 1] to Index the last element, it is different with the loop. If you take a closer look at the finishing condition it says: < that means that i will never get the value of Length - 1 the loop will end one iteration before that. Another way to fix your code would be to change the condition and let i run until it gets this value. You can achieve it by: i <= arr.Length - 1. The little difference should also do the trick. This time the loop will end exactly after I has reached the value of the index of the last element

All you need to do is remove the - 1 from your for loop condition, as it is not iterating over all the elements in your array.
If iterating over an array of 6 elements, the indices are from 0 -> 5. So, for your example, you want your loop to go from index 1 to 5 (what you had been doing is iterating over indices 1-4 (since you were subtracting by 1).
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}

Related

How to reverse 2d arrays in c#

array :
int[,] nums = new int[3,4]{
{6,7,9,8},
{4,2,1,3},
{9,7,0,4}
};
I need to print out the rows in reverse but keep the columns in same order.
Iooked all over the internet I don't even know where to start my code, all I have is a for loop that prints in reverse but when I run my code nothing shows up.
for (row = 3; row >= 0; row--)
{
for (column = 0; column < 4; column++)
{
Console.Write("{0} ",nums[row,column]);
}
}
I'm definitely missing something and the only error I get is the index out of bounds.
Please, do not use magic numbers like 3, 4, but actual array lengths, GetLength(...):
int[,] nums = new int[3, 4] {
{ 6, 7, 9, 8 },
{ 4, 2, 1, 3 },
{ 9, 7, 0, 4 },
};
for (int row = nums.GetLength(0) - 1; row >= 0; --row) {
for (int column = 0; column < nums.GetLength(1); ++column)
Console.Write($"{nums[row, column]} ");
if (row > 0)
Console.WriteLine();
}
Fiddle
As you know indexes in an array go from 0 to upper bound so when cycling through you should consider that for an array with 3 elements you will have indexes 0, 1 and 2, you are trying to access index 3 which does not exist.
High level languages have safeguards to avoid this, here an out of range type exception is thrown to let you know you are accessing memory that does not belong to the array.
You should avoid direct indexing because it's very easy to get these off-by-one errors, you should always try to use range based loops, if that's not possible get the length of the array by code, don't use hard coded dimensions unless you have to. Here you can use member methods to figure out the bounds of the array:
int[,] nums = {
{6,7,9,8},
{4,2,1,3},
{9,7,0,4}
};
for (var row = nums.GetUpperBound(0); row >= 0; row--)
{
for (var column = 0; column < nums.GetLength(1); column++)
{
Console.Write("{0} ",nums[row,column]);
}
Console.WriteLine(); // line break for tiddy print
}
This should work
for (row = 2; row >= 0; row--)
{
for (column = 0; column < 4; column++)
{
Console.Write("{0} ",nums[row,column]);
}
}
for (row = 3; row >= 0; row--)
The program is throwing OutOfRangeEception, because when you have an array[3,4], the last index of row is 2. Your program was trying to find an element with too large index number(3).
Here you have working code
int[,] nums = new int[3, 4] { { 6, 7, 9, 8 }, { 4, 2, 1, 3 }, { 9, 7, 0, 4 } };
for (int **row = 2**; row >= 0; row--)
{
for (int column = 0; column < 4; column++)
{
Console.Write("{0} ", nums[row,column]);
}
Console.WriteLine();
}
As you can see, changing value in for loop from 3 to 2 fixed the problem.
And one important note from me - try to declare counter variables inside for - do not make it "global" if you don't need to. In bigger project it could use more memory than necessary. When it's inside for, garbage collector will destroy the variable after all loops

How to solve a variation to the maximum subarray problem, so that the sum should be between two bounds?

Let's say I have an array with integers, which represent the daily changes in the price of a stock, as an example the following array:
[3, -1, -4, 1, 5, -9, 2, 6].
How would I find the amount of subarrays which have a sum between two values (lower and upper, so l <= s <= u), such as -1 (=lower) and 0 (=upper)? In this case, the answer would be 5. You can have the subarrays
[3, -1, -4, 1]
[-1]
[-1, -4, 1, 5, -9, 2, 6]
[1, 5, -9, 2]
[-9, 2, 6]
Another example array would be:
[4, 2, 2, -6, 7]
with lower bound 3, upper bound 4. The answer to this would be 3. I have tried the following very naïve approach, which I'm certain there are many faster alternatives for. I'm wondering how I can solve this problem faster, with divide-and-conquer or possibly through dynamically programming.
Class
public class Stock
{
public int sequenceLength;
public int[] prices;
public int lowerBound;
public int upperBound;
public int count = 0;
public Stock()
{
sequenceLength = Int32.Parse(Console.ReadLine());
prices = new int[sequenceLength];
var split = Console.ReadLine();
var splitSpace = split.Split(' ');
for (int i = 0; i < sequenceLength; i++)
prices[i] = Int32.Parse(splitSpace[i]);
lowerBound = Int32.Parse(Console.ReadLine());
upperBound = Int32.Parse(Console.ReadLine());
}
}
Usage
static void Main(string[] args)
{
int testcases = Int32.Parse(Console.ReadLine());
Stock[] stock = new Stock[testcases];
for (int i = 0; i < testcases; i++)
stock[i] = new Stock();
int count = 0;
for (int i = 0; i < stock.Length; i++)
{
for (int j = 0; j < stock[i].sequenceLength - 1; j++)
{
int sum = stock[i].prices[j];
if (sum >= stock[i].lowerBound && sum <= stock[i].upperBound)
count++;
for (int k = j + 1; k < stock[i].sequenceLength; k++)
{
sum += stock[i].prices[k];
if (sum >= stock[i].lowerBound && sum <= stock[i].upperBound)
count++;
}
}
if (stock[i].prices[stock[i].sequenceLength - 1] >= stock[i].lowerBound && stock[i].prices[stock[i].sequenceLength - 1] <= stock[i].upperBound)
count++;
stock[i].count = count;
count = 0;
}
Console.Clear();
for (int i = 0; i < stock.Length; i++)
Console.WriteLine(stock[i].count);
}
There's already an answer with O(N^2) complexity, I'll propose a O(NlogN) solution.
Create an array sums, where sums[0] = array[0] and sums[i] = sums[i-1]+array[i]. Now, for each index i in sums, you need to find number of indexes j such that sums[i] - sums[j] is in range [lower, upper]. But how to find number of indexes j?
Create a balanced binary search tree (AVL tree). Insert sums[0] in it. Start processing nodes from left to right. After processing a node, add it to the tree. You can search for the number of indexes in range [lower, upper] in O(logN) complexity, and same applies for the insertion as well. That will give you a total time complexity of O(NlogN).
If I understand the problem (and the jury is out)
The premise is, the first loop works its way across the array. The second loop is in charge of keeping a sum and checking the range, then yielding the result
Obviously this is O(n2) time complexity
Given
public static IEnumerable<int[]> GetSubs(int[] source, int lower, int upper)
{
for (var i = 0; i < source.Length; i++)
for (int j = i, sum = 0; j < source.Length; j++)
{
sum += source[j];
if (sum >= lower && sum <= upper)
yield return source[i..(j+1)];
}
}
Usage
var array = new[] { -5, -4, -3, -2, -1, 0, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (var sequence in GetSubs(array,2,5))
Console.WriteLine($"{sequence.Sum()} : [{string.Join(", ", sequence)}]");
Output
5 : [-5, -4, -3, -2, -1, 0, 2, 3, 4, 5, 6]
4 : [-4, -3, -2, -1, 0, 2, 3, 4, 5]
3 : [-3, -2, -1, 0, 2, 3, 4]
2 : [-2, -1, 0, 2, 3]
4 : [-1, 0, 2, 3]
2 : [0, 2]
5 : [0, 2, 3]
2 : [2]
5 : [2, 3]
3 : [3]
4 : [4]
5 : [5]
Full Demo Here
Note : You could probably do this in linq with Enumerable.Range, however this is pretty easy to understand
If you just wanted the count, you could remove the iterator all together, and just increment a counter when the if condition is true
public static int GetSubs(int[] source, int lower, int upper)
{
var result = 0;
for (var i = 0; i < source.Length; i++)
for (int j = i, sum = 0; j < source.Length; j++)
{
sum+= source[j];
if (sum >= lower && sum <= upper)
result++;
}
return result;
}

Fill array out with loop

Hi i have been trying to use a for loop to print out 7, 6, 5, 4, 3, 2, 1
int[] numbers = new int[7];
for (int i = 7; i < numbers.Length; i--)
{
numbers[i] = i - 1;
Console.WriteLine(numbers[i]);
}
Also been trying to use a while look to print out 1, 2, 3, 4, 5, 6, 7
int[] numbers2 = new int[7];
int j = 1;
while (j > numbers2.Length)
{
Console.WriteLine(array[j]);
j++;
}
Somebody that can point me in the right direction?
Try this:
int[] numbers = new int[7];
for (int i = 7; i > 0; i--)
{
numbers[i - 1] = i;
Console.WriteLine(numbers[i - 1]);
}
Since you are going down you must also modify your loop condition to stop when i gets too low, 0 in this case.
You can also iterate over reversed range:
var range = Enumerable.Range(1, 7).Reverse();
foreach (var number in range)
{
Console.WriteLine(number);
}
Or using while:
var currentNumber = 7;
while (currentNumber > 0)
{
Console.WriteLine(currentNumber--);
}
Of course with using break points and trace your code step by step, you can find the misbehaved parts of your code easily.
In this way you can learn new things instead of solving just your problems.
I think the below link will help you:
https://learn.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019

Getting a two dimensional array of all possible unique combination of numbers lower than a mixmum for each cell starting from 1

Hello and thanks for your attention.
(my mathematical vocabulary for English language is rather limited, if you can think of a better title for this question please feel free to edit and thanks for help.)
I am trying to write a function that takes a One-dimensional array of numbers as an input and then returns a two dimensional array that contains all the potential combination of the all numbers lower or equal than their equivalent in input array starting from 1.
let me try to explain this better in two examples:
example one:
Input: [2,3]
Output:
[1,1]
[1,2]
[1,3]
[2,1]
[2,2]
[2,3]
example two:
Input: [2,3,2]
Output:
[1,1,1]
[1,1,2]
[1,2,1]
[1,2,2]
[1,3,1]
[1,3,2]
[2,1,1]
[2,1,2]
[2,2,1]
[2,2,2]
[2,3,1]
[2,3,2]
Also it would be great that you code returns order of arrays in the output in similar order of arrays in outputs in examples but that's not necessary.(the order of numbers inside arrays that are in the output is of course important!)
Note: the length of input array is unspecified and can contain any number of numbers.
Note: there is no need for output to be in array form and can be in form of common .NET collection like List<double[]> or List<List<double>> same goes for input.
If i can clarify the question better please tell in comment.
The following code is our attempt at solving this but it does not return all combinations and contain repetitions of arrays:
public class ArrayGenerator
{
private int mainCounter;
int count = 1;
int counter = 0;
private int movingCounter;
public Dictionary<int, List<int>> series = new Dictionary<int, List<int>>();
public ArrayGenerator(params int[] args)
{
ConcurrentDictionary<int, int> listsCounter = new ConcurrentDictionary<int, int>();
for (int i = 0; i < args.Length; i++)
{
listsCounter.TryAdd(i, 0);
count *= args[i];
var l = new List<int>();
for (int j = 1; j <= args[i]; j++)
{
l.Add(j);
}
series.Add(i, l);
}
List<string> strs = new List<string>();
while (mainCounter<count)
{
string str = "";
counter = 0;
while (counter < args.Length)
{
if (listsCounter[counter] < series[counter].Count)
{
str += series[counter][listsCounter[counter]];
int c, d;
c = listsCounter[counter];
d = c + 1;
listsCounter.TryUpdate(counter, d, c);
}
else
{
int c = listsCounter[counter];
listsCounter.TryUpdate(counter, 0,c);
str += series[counter][listsCounter[counter]];
}
counter++;
}
strs.Add(str);
mainCounter++;
}
}
}
It's much easier to create jagged array (i.e. array of array), int[][] then 2D one int[,]:
using System.Linq;
...
private static IEnumerable<int[]> Solution(int[] maxes) {
if (null == maxes || maxes.Length <= 0 || maxes.Any(item => item < 1))
yield break; // Or throw exception(s)
int[] current = Enumerable
.Repeat(1, maxes.Length)
.ToArray();
do {
yield return current.ToArray(); // copy of current
for (int i = current.Length - 1; i >= 0; --i)
if (current[i] < maxes[i]) {
current[i] += 1;
break;
}
else
current[i] = 1;
}
while (!current.All(item => item == 1));
}
...
// Having an enumeration, we materialize it as an array, i.e. array of array
int[][] demo = Solution(new int[] { 2, 3, 2})
.ToArray();
// Let's have a look at the results
Console.Write(string.Join(Environment.NewLine,
demo.Select(line => string.Join(", ", line))));
Outcome:
1, 1, 1
1, 1, 2
1, 2, 1
1, 2, 2
1, 3, 1
1, 3, 2
2, 1, 1
2, 1, 2
2, 2, 1
2, 2, 2
2, 3, 1
2, 3, 2
If you insist on 2D array, you can convert:
int[,] data2D = new int[demo.Length, demo.Length > 0 ? demo[0].Length : 0];
for (int y = 0; y < demo.Length; ++y)
for (int x = 0; x < demo[0].Length; ++x)
data2D[y, x] = demo[y][x];

Passing array value to another array in reverse order

I want to pass int a[] values into int b[]. but I'm facing confusion. Can anyone correct me out. The output of b is 0,0,0,45,4,2,1. it supposed to be like 7,6,5,4,45,2,1.
static void Main()
{
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = new int[7];
int temp = 0;
for (int i = 0; i <= a.Length - 1; i++)
{
b[(b.Length - i) - 1] = a[i];
Console.WriteLine(b[i]);
}
}
The problem here is that you're inserting items starting from the last index of b, but you're outputting them starting from the first index. The code to copy the items is correct, but you need to adjust your line that outputs the result to the console to show the items in b using the same index that you just used to insert the item.
Note there are a couple of other improvments you can make, such as using array initializer syntax for a, using a.Length to instantiate b instead of a hard-coded number, removing the unused temp variable, using i < a.Length for the for condition (instead of i <= Length - 1, which does a subtraction operation on each iteration), and storing the b index in a variable instead of calculating it twice:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
int bIndex = b.Length - i - 1;
b[bIndex] = a[i];
Console.WriteLine(b[bIndex]);
}
Console.ReadLine();
}
However, this will still output the items in the order in which you insert them, which will be the same order as they appear in a. If you want to show that the items in b are the reverse of a, the easiest way is to do it after you've populated b. Note we can make use of the string.Join method here to join each item with a comma:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
b[b.Length - i - 1] = a[i];
}
Console.WriteLine($"'a' array: {string.Join(",", a)}");
Console.WriteLine($"'b' array: {string.Join(",", b)}");
Console.ReadLine();
}
Output
If you want to create a reverse array from an existing array, you can use Reverse extension method:
//using System.Linq;
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = a.Reverse().ToArray();
You can learn more about Extension Methods.
You can have this syntax
int[] a = {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[7];
for (int i = 0, j = b.Length - 1; i < a.Length; i++, j--)
{
b[i] = a[j];
Console.WriteLine(b[i]);
}

Categories