C# Get max difference from 7 integers [closed] - c#

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 6 years ago.
Improve this question
I have problem with getting the difference between the lowest and highest entered integer. This is my code so far, but I don't understand why I keep getting error messages.
using System;
class Program
{
public static int array(int[] numbers)
{
int minint = array(numbers);
int maxint = array(numbers);
foreach (int value in array(numb)
{
if (value < minint) minint = value;
if (value > maxint) maxint = value;
}
return maxint - minint;
}
static void Main(string[] args)
{
int[] numbers = new int[7];
for (int i = 0; i < 7; i++)
{
Console.Write("Enter number {0}: ", i + 1);
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Difference between min and max is: {0} ", array(numbers));
Console.ReadLine();
}
}

i'd go with the existing methods Min() and Max()
public static int array(int[] numbers)
{
return numbers.Max() - numbers.Min();
}
otherwise your array method should look like this
public static int array(int[] numbers)
{
int minint = numbers[0];
int maxint = numbers[0];
foreach (int value in numbers)
{
if (value < minint) minint = value;
if (value > maxint) maxint = value;
}
return maxint - minint;
}
usually the difference is ment to be a positive value - so you should take the absolute value Math.Abs() or item = item < 0 ? -item : item; in case of negative numbers within your array

Related

How do you find the positive sum of an array that also has negative numbers? [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 2 years ago.
Improve this question
public static int PositiveSum(int[] arr)
{
int sum = 0;
for(int i = 0; i > arr.Length; i++)
{
sum+=arr[i];
}
return sum;
}
Example:
[1,-4,7,12] => 1 + 7 + 12 = 20
Note: if there is nothing to sum, the sum defaults to 0.
One way, with minimum changes to your code, is to add a condition inside the for loop that sums the values allowing only positive numbers to be added.
Something you must change is the condition in the loop, i > arr.Length will break the cycle immediately, even if Length is 0, it needs to be i < arr.Length.
public static int PositiveSum(int[] arr)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] > 0)
sum += arr[i];
}
return sum;
}
I would try filtering the arr to only contain positive numbers, then use sum on that new list:
public static int PositiveSum(int[] arr)
{
var pos = arr.Where(x => x > 0);
int sum = pos.Sum();
return sum;
}

Sum the increment and return the next number [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 6 years ago.
Improve this question
Is there a way to calculate how many time increment of the value and return the next value.
eg 0001 + 0002 + 0003
when it return the result is 0004
i did this
int num = 77;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
but this method sum up the int num to '14'
i want is int num '0001' than it continue to increase to '0002','0003'
Not directly but you can wrap with properties:
public int Counter { get; private set; }
private int _number;
public int Number
{
get { return _number; }
set
{
_number = value;
Counter++;
}
}
Let the method will give you the next result which is defined as like the following:
public static string GetTheNextResult(ref int number)
{
return (++number).ToString("0000");
}
Let numberInput be the number then you can use the following call to get next results:
int numberInput = 1;
var result1 = GetTheNextResult(ref numberInput); // Gives you 0002
var result2 = GetTheNextResult(ref numberInput); // Gives you 0003
var result3 = GetTheNextResult(ref numberInput); // Gives you 0004

C# % throws DivideByZeroException [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
public static List<int> getDenoms(long n)
{
List<int> result = new List<int>();
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
result.Add(i);
}
}
return result;
}
public static int getHighestPrime(List<int> seq)
{
int currentHigh = 1;
foreach (int number in seq)
{
List<int> temp = getDenoms(number);
if (temp.Count == 1)
{
if (number > currentHigh)
{
currentHigh = number;
}
}
}
return currentHigh;
}
I have the current code going in C#. So, I have the two methods. In the getDenoms method, I assumed that the statement n%i would not throw any errors since i is greater than or equal to 1, but it does indeed throw that error.
I used the two methods in the following manner:
Console.WriteLine(getHighestPrime(getDenoms(600851475143)));
Any insight on why the code is throwing that error?
The reason is that 600851475143 is too big for an int!
Your looping variable i is an int, but you compare it to a long. 600851475143 is greater than int.MaxValue, so i eventually overflows and restarts at int.MinValue. Then it increases until it's 0 again and voilá:
DivideByZeroException
To solve this change the type of your loop variable to long, too:
for (long i = 1; i < n; i++)
'i' is a int as 'n' is long, so in the for cicle 'i' overflows and after a while reaches the '0' value.
Fix:
for (long i = 1; i < n; i++)
I have not tested this myself, but when I look at your code I see that your loop is using an int variable while your input is a long. The number that you are testing your function with, namely 600851475143, is larger than what an 32-bit int can represent. Try changing your variable i to long.
The reason for the failure is that your value 600851475143 is larger than int.MaxValue to solve this problem go ahead and use long instead of int
Note that long.MaxValue is: 9223372036854775807
See code below
public static List<long> getDenoms(long n)
{
List<long> result = new List<long>();
for (long i = 1; i < n; i++)
{
if (n % i == 0)
{
result.Add(i);
}
}
return result;
}
public static long getHighestPrime(List<long> seq)
{
int currentHigh = 1;
foreach (long number in seq)
{
List<long> temp = getDenoms(number);
if (temp.Count == 1)
{
if (number > currentHigh)
{
currentHigh = number;
}
}
}
return currentHigh;
}

List of Non-Negative Integers - concatenate into largest possible nr - e.g. [1,2,5] = 521 [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 7 years ago.
Improve this question
I'm following this blog asking
Five programming problems every Software Engineer should be able to solve in less than 1 hour
I am absolutely stumped by question 4 (5 is a different story too)
Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021.
Now the author posted a answer, and I saw an python attempt too:
import math
numbers = [50,2,1,9,10,100,52]
def arrange(lst):
for i in xrange(0, len(lst)):
for j in xrange(0, len(lst)):
if i != j:
comparison = compare(lst[i], lst[j])
if lst[i] == comparison[0]:
temp = lst[j]
lst[j] = lst[i]
lst[i] = temp
return lst
def compare(num1, num2):
pow10_1 = math.floor(math.log10(num1))
pow10_2 = math.floor(math.log10(num2))
temp1 = num1
temp2 = num2
if pow10_1 > pow10_2:
temp2 = (temp2 / math.pow(10, pow10_2)) * math.pow(10, pow10_1)
elif pow10_2 > pow10_1:
temp1 = (temp1 / math.pow(10, pow10_1)) * math.pow(10, pow10_2)
print "Starting", num1, num2
print "Comparing", temp1, temp2
if temp1 > temp2:
return [num1, num2]
elif temp2 > temp1:
return [num2, num1]
else:
if num1 < num2:
return [num1, num2]
else:
return [num2, num1]
print arrange(numbers)
but I'm not going to learn these languages soon. Is anyone willing to share how they would sort the numbers in C# to form the largest number please?
I've also tried straight conversion to C# in VaryCode but when the IComparer gets involved, then it causes erroneous conversions.
The python attempt uses a bubble sort it seems.
Is bubble sort a starting point? What else would be used?
The solution presented uses the approach to sort the numbers in the array in a special way. For example the value 5 comes before 50 because "505" ("50"+"5") comes before "550" ("5"+"50"). The thinking behind this isn't explained, and I'm not convinced that it actually works...
When looking that the problem, I came to this solution:
You can do it recursively. Make a method that loops through the numbers in the array and concatenates each number with the largest value that can be formed by the remaining numbers, to see which one of those is largest:
public static int GetLargest(int[] numbers) {
if (numbers.Length == 1) {
return numbers[0];
} else {
int largest = 0;
for (int i = 0; i < numbers.Length; i++) {
int[] other = numbers.Take(i).Concat(numbers.Skip(i + 1)).ToArray();
int n = Int32.Parse(numbers[i].ToString() + GetLargest(other).ToString());
if (i == 0 || n > largest) {
largest = n;
}
}
return largest;
}
}
If you want to do it by bubble sort, try this:
public static void Main()
{
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < VALUES.Length - 1; i++)
{
if (Compare(VALUES[i], VALUES[i + 1]) > 0)
{
int temp = VALUES[i];
VALUES[i] = VALUES[i + 1];
VALUES[i + 1] = temp;
swapped = true;
}
}
}
String result = "";
foreach (int integer in VALUES)
{
result += integer.ToString();
}
Console.WriteLine(result);
}
public static int Compare(int lhs, int rhs)
{
String v1 = lhs.ToString();
String v2 = rhs.ToString();
return (v1 + v2).CompareTo(v2 + v1) * -1;
}
The Compare method compares the order of two numbers that would create the largest number. When it returns value larger than 0, that means you need to swap.
This is the sorting part:
while (swapped)
{
swapped = false;
for (int i = 0; i < VALUES.Length - 1; i++)
{
if (Compare(VALUES[i], VALUES[i + 1]) > 0)
{
int temp = VALUES[i];
VALUES[i] = VALUES[i + 1];
VALUES[i + 1] = temp;
swapped = true;
}
}
}
It checks to consecutive values in the array and swaps if necessary. After one iteration without swapping, the sort is finished.
Finally, you concatenate the values in the array and print it out.

How to compute the average for every n number in a list [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 7 years ago.
Improve this question
Having a List of numbers, I want to take every n(e.g. 5 , 10 , etc.) element, compute their average and put the average in a new list. As an example lets assume we have the following list:
1 , 2 , 3 , 4 , 5 , 6 , 7 , 8
Now we compute the average every 2 elements and we will get the following list as output:
1.5 , 3.5 , 5.5 , 7.5
How can I do that?
You could use a for-loop and Enumerable.Average:
var averages = new List<double>();
for (int i = 0; i < ints.Length; i += 2)
{
int thisInt = ints[i];
int nextInt = i == ints.Length - 1 ? thisInt : ints[i + 1];
averages.Add(new[] { thisInt, nextInt }.Average());
}
Here's a dynamic approach that works with any length:
int take = 2;
for (int i = 0; i < ints.Length; i += take)
{
if(i + take >= ints.Length)
take = ints.Length - i;
int[] subArray = new int[take];
Array.Copy(ints, i, subArray, 0, take);
averages.Add(subArray.Average());
}
This problem is just testing your use of iteration and the modulus operator. Modulus gives you the remainder of division, you can use it to check whether or not the current number should be included in the average as you iterate the array. Here is a sample method;
public float nthsAverage(int n, int[] numbers)
{
// quick check to avoid a divide by 0 error
if (numbers.Length == 0)
return 0;
int sum = 0;
int count = 0;
for (int i = 0; i < numbers.Length; i++)
{
// might want i+1 here instead to compensate for array being 0 indexed, ie 9th number is at the 8th index
if (i % n == 0)
{
sum = sum + numbers[i];
count++;
}
}
return (float)sum / count;
}
public List<double> Average(List<double> number, int nElement)
{
var currentElement = 0;
var currentSum = 0.0;
var newList = new List<double>();
foreach (var item in number)
{
currentSum += item;
currentElement++;
if(currentElement == nElement)
{
newList.Add(currentSum / nElement);
currentElement = 0;
currentSum = 0.0;
}
}
// Maybe the array element count is not the same to the asked, so average the last sum. You can remove this condition if you want
if(currentElement > 0)
{
newList.Add(currentSum / currentElement);
}
return newList;
}

Categories

Resources