Find furthest and closest number to a number in array c# [closed] - c#

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 4 years ago.
Improve this question
I have a exercise where I need to find the furthest and closest number to a certain number (average). Can somebody help me? Here is my code:
Console.WriteLine("Geef 10 gehele positieve getallen.");
Console.WriteLine("Getal 1:");
int g1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 2:");
int g2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 3:");
int g3 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 4:");
int g4 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 5:");
int g5 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 6:");
int g6 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 7:");
int g7 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 8:");
int g8 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 9:");
int g9 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Getal 10:");
int g10 = Convert.ToInt32(Console.ReadLine());
int gemiddelde = (g1 + g2 + g3 + g4 + g5 + g6 + g7 + g8 + g9 + g10)/10;
int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};

If you can use List<int> instead of array it makes things easier to code and probably cleaner depending on who you ask.
let say you change this :
int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
Into a list like this :
List<int> values = new List<int>(){g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
An aggregate will test each elements until the list has been completely tested.
So we can try get the closest and furthest value like so
// value you want to check is the average of the list.
// Average is already implemented for the List
var value = values.Average();
// will keep the closest value in the collection to our value we are looking for
// and keep testing with the following value to end up with the final closest
var closestTo = values.Aggregate((x, y) => Math.Abs(x - value) < Math.Abs(y - value) ? x : y);
// same logic as closest except we keep the furthest
var furthestTo = values.Aggregate((x, y) => Math.Abs(x - value) > Math.Abs(y - value) ? x : y);

I hope this example can help you even if it is in java.
//Your array with the numbers
int[] data = {12, 123, 65, 23, 4, 213, 32, 342, 21, 15};
int testNum = 27; //Your test value
int holderHigh = testNum;
for(int i = 0; i < data.length; i++){//Goes through the array
//If the holder is lower than a value in the array it will get stored
if(holderHigh < data[i]){
holderHigh = data[i];
}
}
int holderLow = testNum;
for(int k = 0; k < data.length; k++){//Goes through the array
//If the holder is higher than a value in the array it will get stored
if(holderLow > data[k]){
holderLow = data[k];
}
}
System.out.println(holderHigh + " and " + holderLow +
" is the number farthest away from " + testNum);stNum);

Related

How can I calculate numbers (for example) from 1 - 10 with the next number. (1+2+3+4+ ...) [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 1 year ago.
Improve this question
Does it have a shorter way than doing something like this:
int[] Summe = new int[6];
Summe[0] = 1;
Summe[1] = 2;
Summe[2] = 3;
Summe[3] = 4;
Summe[4] = 5;
Summe[5] = 6;
Console.WriteLine(Summe[0] + Summe[1] + Summe[2] + Summe[3] + Summe[4] + Summe[5]);
Console.ReadKey();
Using the Enumerable.Sum() method which computes the sum of a sequence of numeric values and Enumerable.Take() which returns a specified number of contiguous elements from the start of a sequence.
Console.WriteLine(Summe.Take(10).Sum());
OR from high school
// sum of integers from 1 to n
int SumNaturalNumbers(int n)
{
return n * (n + 1) / 2;
}
Formula for the general algebraic series starting from a and difference between terms d (Arithmetic progression and series)
sum = n / 2 * (2 * a + (n - 1) * d)
I think using a foreach loop may be helpful here, since you're dealing with an array. Also, you can define your array on one line.
int[] Summe = { 1, 2, 3, 4, 5, 6 };
int total = 0;
foreach (int number in Summe)
{
total += number;
}
Console.WriteLine(total);
Console.ReadKey();
You can simplify this process by simply putting this operation into a while loop.
int i = 0; // tell your program what 'i' should be upon first running the code
while (i < 10) // if 'i' is less than 10, run this block of code. You can change 10 to anything you want
{
Console.WriteLine("i = {0}", i);
i++; // increment
}
This will print each number individually, but you want to calculate the sum of every number, so you could do something like this:
{
public static void Main()
{
int j, sum = 0;
Console.Write("\n\n");
Console.Write("Find the sum of first 10 natural numbers:\n");
Console.Write("----------------------------------------------");
Console.Write("\n\n");
Console.Write("The first 10 natural number are :\n");
for (j = 1; j <= 10; j++)
{
sum = sum + j; // add the previous number to the current one
Console.Write("{0} ",j);
}
Console.Write("\nThe Sum is : {0}\n", sum);
}
}
The above code prints the sum of the first 10 natural numbers. I added some additional lines simply to make the program more legible. Again, you can change the number 10 to whatever number you want.

Calculation position in Fibonacci order

I want to programm a level system for a small game.
The level system would be tied to the score and the levels would get further appart
only 2 score values are given
lvl, score
0, 50 (from 0 - 50)
1, 100 (from 51 to 100)
2, 150
3, 250
4, 400
5, 650
...
How could I elegantly calculate witch level I am in with a given score and 2 start values (50 and 100 in the example)
Or is it best to just calculate the score values in a list or array
With out any formula you can simply compute the whole table in a flash (under 0.0002 sec on a core2). Summing int is pretty fast. That's only 36 computation before hitting the max on int32.
var scoreTable = new []{50, 100, 150, 250, 400, 650, 1050, 1700, 2750, 4450, 7200, 11650, 18850,
30500, 49350, 79850, 129200, 209050, 338250, 547300, 885550, 1432850, 2318400, 3751250,
6069650, 9820900, 15890550, 25711450, 41602000, 67313450, 108915450, 176228900,
285144350, 461373250, 746517600, 1207890850, 1954408450};
For the math to create the table, let's be simple:
var thresholds = new List<int> {50, 100};
var index = 1;
while(true){
var temp = thresholds[cpt] + thresholds[cpt - 1];
if (temp < 0) break;
thresholds.Add(temp);
}
And to know the level:
var score = 51;
// Index is Zero-based numbering. Count is One-based. Index = Count -1;
var level = scoreTable.Where(x => x < score ).Count() - 1;
Binary.Search:
public class SupComparer : IComparer
{
public int Compare(object x, object y)
{
var t1 = UInt64.Parse(x.ToString());
var t2 = UInt64.Parse(y.ToString());
return t1.CompareTo(t2) > 0 ? 1 : 0;
}
}
var cp = new SupComparer();
var level = Array.BinarySearch(scoreTable, score, (IComparer)cp);
There's actually a formula to calculate Fibonacci numbers. That can be transformed into an algorithm to find the index of any given Fibonacci number. There's an example of how to do this in C# here.
You need to adapt that formula for use with your initial conditions of 50 and 100.
I asked a question over on Mathematics SE for help adjusting the original forumula and they suggested using
It's pretty easy to implement this as a C# method.
public int GetScoreIndex(int score)
{
const double phi = 1.61803398875;
const double rad5 = 2.2360679775;
var preLog = (score / 50) * rad5 + (1/2);
var log = Math.Log(preLog, phi);
var floor = (int) Math.Floor(log);
var index = floor - 1;
return index;
}

Issues with looping code and do-while loops (c#)

static double calculateTotals(double a)
{
double transfee = a * .01;
double total = a + transfee;
return total;
}
static void Main(string[] args)
{
Console.WriteLine("How many dontations to process?");
int donations = Convert.ToInt16(Console.ReadLine());
int[] count = new int[] { donations + 1 };
int ct = 1;
int i = -1;
do
{
Console.WriteLine("Enter name: ");
string name = Console.ReadLine();
Console.WriteLine("Enter donation amount: ");
double amount = Convert.ToDouble(Console.ReadLine());
double transfee = amount * .01;
i++;
ct = count[i += 1];
Console.WriteLine(name + "\t" + amount + "\t" + transfee);
} while (i < donations);
Console.WriteLine("TOTALS:" + "\t" + calculateTotals(amount) + "\t" + transfee);
Console.ReadLine();
}
}
Hello. I am a beginner at coding, so I apologize if this is a poor attempt.
I am trying to make an app that records the amount donated by an individual, calculates a transaction fee, and outputs the results for each person. At the end, I am creating a final row of output that will state the total donations and the total transaction fees.
I am currently unsure how to properly implement the array into my loop, and am unsure if the loop is optimized in general.
Again, I am a beginner. I apologize for such code, but I'd love some clarification on these things.
Thank you!
First, your array declaration syntax is wrong. See this link.
So it should be int[] count = new int[donations+1];
Second, you need to declare and instantiate your amount and transfee variables outside of your loop.
double transfee = 0.0F;
double amount = 0.0F;
do
{
...
amount = Convert.ToDouble(Console.ReadLine());
transfee = amount * .01;
...
} while (i < donations);
This should be enough information to get you going again. Since you're learning, I don't think anyone would really unfold an answer for you that does the job you're trying to figure out :)
Your code :
int i = -1;
do
{
...
i++;
ct = count[i += 1];
...
} while (i < donations);
You are actually increase i two times, then get values from count[i] assign to ct variable
See this sample :
int[] count = new int[3];
count[0] = 0;
count[1] = 1;
count[2] = 2;
int i = -1;
do
{
i++;
int x = count[i += 1];
Console.WriteLine(x);
} while (i < 3);
It will cause IndexOutOfRangeException
Explain :
First Loop :
i++; // i increased 1, so i = 0
int x = count[i += 1]; // i increased 1, so i = 1, then get count[1] assign to x, x is 1
Second loop:
i++; // i increased 1, so i = 2
int x = count[i += 1]; // i increased 1, so i = 3, then get count[3] assign to x
count[3] cause IndexOutOfRangeException
Something like count[i += 1] will make your code more difficult to maintain, in my opinion, you should avoid it if possible, try to write it explicity as you can

Why is my for loop stopping before last index? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
I want to read 20 items but only 19 are read through console. Any idea why ?
What I'd like my code to do is :
1st : read the interger k from the standard input buffer (console)
2nd : read 20 integers into the array int x[]
static void Main(string[] args)
{
int k ;
int[] x = new int [20];
int[] y = new int [20];
int[] yval = new int[20];
int i;
Console.WriteLine("Enter k value");
k = Console.Read();
Console.WriteLine("Enter x values\n ");
for (i = 0; i <=19 ; i+=1)
{
x[i] = int.Parse(Console.ReadLine());
yval[i] = (x[i] + k) % 26;
}
}
Jon addressed the root of the problem in the comments, but I wanted to try to answer more fully. Console.Read() will only read a single character and return an integer representing the character, probably not what you want. Any characters after that are immediately read on the first pass, probably not what you expected. The issue can be illustrated by inspecting the values:
static void Main(string[] args)
{
int k;
int[] x = new int[20];
int[] y = new int[20];
int[] yval = new int[20];
int i;
Console.WriteLine("Enter k value");
k = Console.Read();
Console.WriteLine("k = {0}", k);
Console.WriteLine("Enter x values\n ");
for (i = 0; i <= 19; i += 1)
{
var input = Console.ReadLine();
x[i] = int.Parse(input);
yval[i] = (x[i] + k) % 26;
Console.WriteLine("x[{0}] = {1}", i, x[i]);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
If you enter "12" for k, the output looks like:
Enter k value
12
k = 49
Enter x values
x[0] = 2
The first character '1' is saved to k as int value of 49 (ASCII value for '1'). The buffer still has a '2' and a newline to be read. They get read on the first pass through the loop and stored in the first element of the array.
As Jon said, you probably want k = int.Parse(Console.ReadLine()); instead.

Why is this Fibonacci code not correct? [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
Project Euler Question 2.
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
My solution :
int firstNum = 1;
int secondNum = 2;
int resultNum = firstNum + secondNum;
int sum = 0;
for (int i = 0; i < 4000000; i++)
{
firstNum = i;
secondNum = i;
if(resultNum == firstNum + secondNum)
{
sum += resultNum;
Console.WriteLine(sum);
}
}
Why is this not correct and can you guide me into the right way of thinking?
Try this:
int n1, n2, fib;
//n1 = 0;
//n2 = 1;
n1 = 1;
n2 = 1;
fib = n1 + n2;
while (fib < 4000000)
{
n2 = n1;
n1 = fib;
fib = n1 + n2;
}
Then find the even fib numbers and sum it
For a more modular approach (mixed with LINQ):
IEnumerable<Int32> Fibonacci(Int32 limit = 4000000)
{
for (Int32 previous = 0, current = 1, next = 0;
current <= limit; current = next)
{
next = previous + current;
previous = current;
yield return next;
}
}
Then:
var allNumbers = Fibonacci(4000000); // 1,2,3,5,8,13,21
var evenNumbers = allNumbers.Where(x => x % 2 == 0); // 2,8,34,144,610,2584
var sum = evenNumbers.Sum(); // 4613732
The fibonacci series is defined as
A0 = 1,
A1 = 1
An = An-1 + An-2
You are aiming at producing the pattern
1 2 3 5 8 13 etc
While iterating, you are going to want to adjust the input similar to a sliding window and then check to see if you have come across a valid insertion (i.e. < 4M and even)
int sum = 0;
int max = 4000000;
for( int n = 0; n < max ; n++ )
{
//only sum the even numbers
if( second % 2 == 0 ) sum += second;
//adjust
int result = first + second;
first = second;
second = result;
//test for numbers greater than max
if( result > max ) break;
}
//output
Console.WriteLine(sum); //An for all even An values
After looking at this hopefully you can see some of the issues you came across.
You are setting your variables to the iterator i which is not going to produce An as defined but instead something entirely different.
firstNum = i;
secondNum = i;
Further, you only calculate the result once. This needs to be done in the loop. Only calculating once will basically use a static value the entire time.
int resultNum = firstNum + secondNum;
The conditional statement should be testing for an even number in order to properly add to the sum, but this code will only test the static value of resultNum
if(resultNum == firstNum + secondNum)
Also, there needs to be some check on the sum in order to break out when the max is exceeded. 4M iterations will be too many.
There is even more optimization that can occur here though. Looking at the for loop, it is clear that while not used yet, the iterator can be a powerful tool.
The reason being that the fibonacci conforms to the "Golden ratio".
By making the simple observation that the fibonacci series hits an even number ever 3 iterations, the iterator can be used to skip through the series.
double p = (1 + Math.Pow(5,.5)) / 2;
for( int n = 3, sum = 0;;n+=3)
{
double f = ( Math.Pow(p,n) - Math.Pow( 1 - p , n ) ) / Math.Pow(5,.5);
if( f > 4000000 ){
Console.WriteLine(sum);
break;
}
sum += (int)Math.Round(f);
}
Your code does not produce a Fibonacci sequence and does no check for even-valued terms
Try this instead
int firstNum = 1;
int secondNum = 2;
int sum = 0;
while (secondNum <= 4000000)
{
if (secondNum % 2 == 0)
sum += secondNum;
int resultNum = firstNum + secondNum;
firstNum = secondNum;
secondNum = resultNum;
}
Console.WriteLine(sum);

Categories

Resources