I need to subtract value from the array [closed] - c#

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 1 year ago.
Improve this question
I need to substract given sum from array of elements. I.e. if given value is 15 and array starts with [10, 20,...] I need to substract 10 from the first elements (resulting with 0 for it) and the rest continue to subsequent elements - so second would be decreased by 5 (15 - 10), and the rest stay untouched.
int[] myNum = { 10, 20, 30, 40 };
if given value is 15 then I need to subtract value from the array. The new array will be
int[] myNum=[0,5,30,40]
I can easily create new array with all elements of the array decreased by the given number with basic for loop, but I don't know how to change that number based on how much I already substracted.

Your best bet is a for loop.
This will allow you to perform an action (I.E subtraction) on each 'element' of an array.
By using a return statement, you can return the new array that has had each element modified
EDIT As per #AlexeiLevenkov's comment, I have updated my answer to keep a count of the remaining subtraction.
Using this to test :
using System;
public class Program
{
public static void Main()
{
int[] array = new int[]{5,10,15,20,25,30,35};
array=SubtractArray(array,25);
Console.WriteLine("Output is:");
foreach(int v in array){
Console.WriteLine(v+", ");
}
}
public static int[] SubtractArray(int[] array , int subtraction){
for(int i=0; i< array.Length;i++){
if(subtraction>0){
int newValue=array[i]-subtraction;
if(newValue<1){
newValue=0;
subtraction=subtraction-array[i];
}
array[i]=newValue;
}
}
return array;
}
}

I don't know wath you said but I think it that :
The Arrays work 0,1,2,3,4,5,6
if I made a arrays like that
int[] _int = {10, 50, 30};
for go to the fist (10) and substract I need to do that
Sorry for my english I'm french
_int[0] -= 10;
becose it will select automatic the first (0)

Related

Integer array Get difference between two highest numbers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a List<int[]> that I populated by splitting an integer array into 4 groups. Now I need to get the difference of the two highest numbers in the array. I tried Array.Sort but I am stuck on how to continue.
What I have done so far?
public static void solution(int[] T)
{
List<int[]> splitted = new List<int[]>();//This list will contain all the splitted arrays.
int lengthToSplit = T.Length / 4;
int arrayLength = T.Length;
for (int i = 0; i < arrayLength; i = i + lengthToSplit)
{
int[] val = new int[lengthToSplit];
if (arrayLength < i + lengthToSplit)
{
lengthToSplit = arrayLength - i;
}
Array.Copy(T, i, val, 0, lengthToSplit);
splitted.Add(val);
}
//this is the part where I must get the difference between the two highest numbers in an integer array and put into another list.
foreach (int[] integerarray in splitted)
{
//get the difference of the two highest numbers per integer array and place it on another List<int>
}
}
get the difference between the two highest numbers in an integer array
and put into another list
You can use LINQ and Math.Abs:
List<int> differenceList = splitted
.Select(list => list.OrderByDescending(i => i).Take(2).ToArray())
.Select(highestTwo => Math.Abs(highestTwo[0] - highestTwo[1]))
.ToList();

3 random numbers into array [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am writing the beginning of my program which is to have the computer generate 3 random numbers on the console.
They need to be 1-9 (including both), no numbers can repeat, and I need to put this answer into an array. What's needed in the main method class vs the class.
You should try it out yourself first (site rules say so), but some hints may be provided:
1) integer random numbers can be generated using Random class. More details can be found here and an answer has been already provided about generation
2) to avoid duplicates each number should be tested against the existing list of numbers:
array.Contains(generatedNumber)
3) For your particular request, an elegant option is to generate all numbers between 1 and 9, shuffle the array and pick the first three elements:
var initArray = Enumerable.Range(1, 9).ToArray();
var randomArray = initArray.OrderBy(x => rnd.Next()).ToArray();
Get first three elements and those are random and distinct.
Generally, you can a subarray using the method specified here.
Try this:
Random rnd = new Random();
int[] arr = Enumerable.Range(0, 10).OrderBy(n => rnd.Next()).Take(3).ToArray();
foreach (var n in arr)
{
Console.WriteLine(n);
}
Try this code below :
//range set 0 to 9
int Min = 0;
int Max = 10;
//declare an array which store 3 random number
int[] arr = new int[3];
Random randNum = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr[i] = randNum.Next(Min, Max);
Console.WriteLine(arr[i]);
}

I want to understand the inner working of a Collections.List<T> [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've created my own list with a static int as length. How are these things done when you don't know the size of a collection and you want to construct it. I know there is a build in list but I want to build my own to understand the inner working of it. I defined it as size = int 5 in the constructor so it will output now 1 2 3 0 0 and I want to know how to resize it and using a constructor with undefined length. I can't figure it out myself some help is appreciated.
I fixed it. Thanks for the answers guys really fast and easy to understand I never heard from the .net reference so thanks for the site.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List l = new List();
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);
foreach (int n in l)
{
Console.WriteLine(n);
}
Console.Read();
}
}
class List
{
private int _lLength;
private int[] _lArray;
private int _lPos;
public List()
{
/*
* Create an array with a default size
* If it doesn't fit anymore create a new one and copy it
* to a new array and double the size
*/
this._lArray = new int[2];
}
public List(int c)
{
this._lLength = c;
this._lArray = new int[this._lLength];
this._lPos = 0;
}
public void Add(int n)
{
if (this._lArray.Length <= this._lPos)
{
// So now is the array < then the array we want to return
int[] tmp = this._lArray;
this._lArray = new int[tmp.Length * 2];
Array.Copy(tmp, this._lArray, tmp.Length);
}
this._lArray[this._lPos++] = n;
}
public IEnumerator<int> GetEnumerator()
{
foreach (int n in this._lArray)
yield return n;
}
}
}
Internally, the List<T> object keeps an array with a default size (0, according to the reference source). When the array is full, a new array is created, double size of the previous one, and all items from the first array are moved to the new array.
So adding an item to this list (array size = 2):
item 1
item 2
Causes the array behind the list to become (array size = 4):
item 1
item 2
item 3
null
If you know the probable size of the list on beforehand, you could opt to pass the expected number to the constructor of List<T>. The array size will be set to that length, which may give you better performance overall, since it doesn't have to recreate arrays.

How do I find number of values in array [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 9 years ago.
Improve this question
I have an array and am trying to extract the vlaues. I have tried to find the length of the array, but as the array isnt always full the .length doesnt work for me. How do i work out how many values are stored in the array?
Heres the code;
int length = numbers.Length;
I have created the array in the main section of the code, I am trying to make a function that can get the values out of the code using a for loop. E.G
int number(i) = numbers[i]
so that the variable number[i] will become number0, and then assigned the value in the first row of the array
If you want to use array which is not always full, then you definitely should use List<T> instead of array, because list can contain variable number of items. With array you never can tell if default value (zero for integer) was assigned to array item, or item was not assigned at all. Getting list items count will look like list.Count.
Of course, you can get number of array items which have non-default value (but see above why it might be not good approach):
int[] array = { 1, 2, 0, 1, 5 };
int count = array.Count(i => i != default(int)); // 4
try foreach you do not need the length. Here is code:
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
foreach (int element in numbers)
{
System.Console.WriteLine(element);
}

Getting average values from one Array to another Array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I’m no programmer but I’m learning C# to build a foreign exchange trading system and Arrays are being a struggle…
The problem I have is the following…
I have a one dimensional Array with, let’s say, 100 elements in it.
Now I need to build another one dimensional array with a 10 elements rolling average based on the first Array.
Said in another way, I need to take the elements from the first Array starting in i = 0 up to i = 9 and average them and save the average in a new array. Than move one step forward and take i = 1 up to i = 10 from the original Array and average them and save the result in the new Array….and so forth….in Excel this would be extremely easy….
My need to have the data in Arrays is because later I will need to compare the last 10 elements rolling average with historical data….
Please, can anyone build a sample code that I can work with?
Many thanks
Paulo
Maybe something like this could work... Did this on my mac in sublime text so you'll still have to work with. Should get the point though.
public class Foo
{
List<int> main = new List<int>(100);
List<int> rollingAverages = new List<int>(100);
public void Add(int score)
{
main.Add(score);
if(main.Count > 10)
{
int rollingAverage = AverageLast10();
rollingAverages.Add(rollingAverage);
}
}
public int AverageLast10()
{
int sum = 0;
for(int i = main.Count - 10; i < 10; i++)
{
sum += main[i];
}
return sum / 10;
}
}
Somewhere else in the code
Foo foo = new Foo();
foo.Add(94);
foo.Add(94);
...
yadda yadda yadda

Categories