Sum all numbers before specific number (including the number) - c#

I want to write a program which takes an array of size N, loop over it and sum all the numbers before i (including i itself). I haven't done a lot so far because I don't know how to access the indexs before i. When I try for example arr[i - 1], it throws me an error that the index was outside the array bounds.
int N = int.Parse(Console.ReadLine());
int[] arr = new int[N];
// Input
for (int i = 0; i < arr.Length; i++)
arr[i] = int.Parse(Console.ReadLine());
// Here we need to sum
for (int i = 0; i < arr.Length; i++)
//
Example (N = 4)
Before = [1, 2, 3, 4]
After = [1, 3, 6, 10]

I don't know if this helps your learning process, but this is what I would do if I needed to do that logic.
Use Range to generate a collection of consecutive integers, up to n, then do a projection with LINQ of another collection from 1 to each value, then sum and convert to array.
int n = 10;
var result = Enumerable.Range(1, n)
.Select(e => Enumerable.Range(1, e).Sum()).ToArray();

You can initialize the result array with the correct size beforehand and then use a plain loop to calculate the "running sum". You need a variable to track the current value:
int[] result = new int[arr.Length];
int currentSum = 0;
for (int i = 0; i < arr.Length; i++)
{
currentSum += arr[i];
result[i] = currentSum;
}

Related

"rotate" values in array clockwise

Firstly thank you for taking the time to look at my question.
I have a csv file of letters for which i need to get the last letter of the array and move it to the start while "pushing" the other letters across
E.G.
--Source--
a,b,c,d,[e]
--Rotated--
e,a,b,c,d
for (var i = 0; i < Array.Length - 1; i++)
{
temp = Array[Array.Length];
Array[Array.Length] = Array[Array.Length - 1];
Array[i + 1] = Array[i];
Array[i] = temp;
}
For this I am aware that not all characters would be effected but i cant think of a loop to get all values moved
Use Copy method:
int last = arr[arr.Length - 1];
Array.Copy(arr, 0, arr, 1, arr.Length - 1);
arr[0] = last;
You can shift the numbers to right by using the modulo % operator :
int[] arr = { 1, 2, 3, 4, 5 };
int[] newArr = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
newArr[(i + 1) % newArr.Length] = arr[i];
}
newArr = {5,1,2,3,4}
DEMO HERE
EDIT:
Or you could make a method that shifts the numbers in your initial array without the need for creating a new array. The method rightShiftArray takes two parameters, the initial array arr an the number of shifts (shift) you want to perform:
public void rightShiftArray(ref int[] arr, int shift)
{
for (int i = 0; i < shift; i++)
{
int temp;
for (int j = 0; j < arr.Length - 1; j++)
{
temp = arr[j];
arr[j] = arr[arr.Length - 1];
arr[arr.Length - 1] = temp;
}
}
}
For example:
int[] arr = { 1, 2, 3, 4, 5 };
rightShiftArray(ref arr, 2);
The code above shifts the numbers in the initial array arr twice to the right and gives you the following output:
arr = { 4, 5, 1, 2, 3};
DEMO HERE
if you doesn't want to allocate new array, you can use this code :
newValue = Array[Array.Length-1];
for (var i = 0; i < Array.Length; i++)
{
temp = Array[i];
Array[i] = newValue;
newValue = temp;
}

Strand sort in c# using arrays only

i have a homework using strand sort and i must take the growing sequence of numbers from the initial array and merge them together in the array that represents our result (C#)
Like this one http://imgur.com/nQFzJw7
So far i did something like that
public static int[] Str(int[] a)
{
int i, j, x ,temp,k=0,count=1;
int size = a.Length;
int len = a.Length;
Strand = new int[size];
Merged = new int[size];
for (i = k; i < size; i++)
{
x = a[i];
Strand[0] = x;
for (i = k; i < size; i++) //checking if there's a bigger int than the first one
{
if (a[i] > x)
{
x = a[i];
}
}
for (i = k; i < len; i++)
{
if (a[i] == x) // checking if the max appears more than 1 time
{
temp = a[i];
a[i] = a[len];
a[len] = temp;
len--; //swaps the max numbers to the last position
Strand[count] = x;
count++;
}
}
for (i = 0; i < count; i++) // cant find a way to put in the final merged and sorted array
{
}
count = 1;
k++;
}
Any suggestions?
You always need to extract the first element into strand
strand[0] = a[0]
count = 1
Then you need to extract suitable elements into strand, shifting the rest of array
for i = 1 to size - 1
if a[i] >= strand[count - 1]
strand[count++] = a[i]
else
a[i - count] = a[i]
size = size - count
Then you need merge current strand and merged - look for Merge procedure from MergeSort
Repeat these steps until size becomes 0

Better way of inserting numbers into an array while sorting it

Let's say I want to insert values into an array while at the same time sorting it.
This was my solution:
int[] arr = new int[5];
int k;
arr[0] = int.Parse(Console.ReadLine());
for (int i = 1; i < arr.Length; i++)
{
int num = int.Parse(Console.ReadLine());
for (k = i; k > 0 && num < arr[k - 1];--k) arr[k] = arr[k - 1];
arr[k] = num;
}
I know I didn't handle exceptions, I'm just talking about the code itself.
Is there a better way of doing this?
You can use a SortedSet<>, that gets automatically sorted as you add items.
var numbers = new SortedSet<int>()
{
4,
9,
6,
3
};
foreach (var number in numbers)
{
Console.WriteLine(number);
}
If it doesn't have to be array you could do this:
static void Main(string[] args)
{
List<int> list = new List<int>
{
1,
2,
7,
10
};
int k = int.Parse(Console.ReadLine());
list.Add(k);
list.Sort();
}
Edit: if you want to sort when inserting you could do this:
int k = int.Parse(Console.ReadLine());
int i = list.Where(x => x > k).Min();
int index = list.IndexOf(i);
list.Insert(index, k);
You can use a List and convert it into an array. When you maintain your list ordered at all time you can use the list's BinarySearch method to get the insert index:
const int length = 5;
List<int> result = new List<int>(length);
for (int i = 0; i < length; i++) {
int num = int.Parse(Console.ReadLine());
int insertIndex = result.BinarySearch(num);
if (insertIndex < 0) {
insertIndex = ~insertIndex;
}
result.Insert(insertIndex, num);
}
int[] arr = result.ToArray();
The binary search is much faster than the linear search you are currently performing. You won't see that with your current 5 values. You would defenitely see it with larger lists (hundrets or thousands of values).

Starting with the lowest value, print each value in a circular array

I have this situation:
int[] array = new int[] {7, 5, 6}
The value of my index i is 1 and it is pointing at the head of my hypothetical circular list. The value "7" at the zero position is the tail.
My aim is to print:
5,6,7
Do I need a specific structure or can I do it with a simple array?
With a single "for" loop and the modulo operator:
int[] array = new int[] {7, 5, 6};
int start = 1;
for (int idx=0; idx<array.Length; idx++)
Console.Write(array[(idx+start) % array.Length]);
There is nothing out of the box, but the following will wrap around the array.
int[] array = new int[] { 7, 5, 6 };
int startPosition = 1;
string result = "";
// Run from the start position to the end of the array
for (int i = startPosition; i < array.Length; i++)
{
result += array[i] + ",";
}
// Wrapping around, run from the beginning to the start position
for (int i = 0; i < startPosition; i++)
{
result += array[i] + ",";
}
// Output the results
result = result.TrimEnd(',');
Console.WriteLine(result);
Console.Read();
If you want to print 5,6,7 you could use:
int printIndex = 1;
for(int i = 0; i < array.Length; i++)
{
print(print(array[printIndex].ToString());
printIndex++;
if(printindex >= array.Length)
printindex = 0;
}

Display an integer array in a random order without using shuffle [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
newarray[y] = array[rand.Next(n)];
goto case 2;
case 2:
for (int z = y+1; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
}
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
This is the code i have started with but its not displaying any values, is it not filling the array? I'm new to this so any help would be much appreciated
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new IComparer that returns the comparison randomly:
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
Now, sort your array:
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
It's really that simple. See this demonstration at IDEOne.com
It seems to get into an infinite loop. Try changing this bit:
case 2:
for (int z = y; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
The reason you're not seeing any output is because the code isn't running to completion - it ends up bouncing between case 1 and 2 because
if (newarray[y] == newarray[z - 1])
is always true.
My recommendation would be to debug (i.e. step through) your code so you can really see why this is the case, then you'll be able to fix the code yourself :)
You can do it like this:
...
n = Int32.Parse(Console.ReadLine());
// Initial array filled with 1..n values
int[] data = Enumerable.Range(1, n).ToArray();
// data array indice to show, initially 0..n-1
List<int> indice = Enumerable.Range(0, n - 1).ToList();
Random gen = new Random();
for (int i = 0; i < n; ++i) {
if (i != 0)
Console.Write(' ');
index = gen.Next(indice.Count);
Console.Write(data[indice[index]]);
// Index has been shown, let's remove it since we're not going to show it again
indice.RemoveAt(index);
}
...
What you are trying to do is to generate a random permutation. You could try the following:
var rand = new Random();
var left = Enumerable.Range(1, n).ToList();
for(int i=0; i<n; ++i)
{
int j = rand.Next(n-i);
Console.Out.WriteLine(left[j]);
left[j].RemoveAt(j);
}
This is the simplest way to do it using a random comparison.
class Program
{
static Random rnd=new Random();
static void Main(string[] args)
{
int[] array= { 1, 2, 3, 4, 5, 6 };
int[] newarray=new int[array.Length];
array.CopyTo(newarray, 0);
Array.Sort(newarray, (i, j) => rnd.NextDouble()<0.5?-1:1);
// newarray is now randomly ordered
}
}
You can randomly switch the values :
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
newarray[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int r = rand.Next(n);
int tmp = newarray[y];
newarray[y] = newarray[r];
newarray[r] = tmp;
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
use following code
int[] array = new int[n];
int[] randomPosition = new int[n];
Enumerable.Range(0, n ).ToList().ForEach(o => array[o] = o+1);
Random r = new Random();
Enumerable.Range(0, n).ToList().ForEach(o => randomPosition[o] = r.Next(0, n - 1));
foreach (var m in randomPosition)
{
var randomNumber = array[m];
//write randomnumber
}

Categories

Resources