Method return error - c#

Hi I am getting an error at return avg; saying return key must not be followed by object expression if anyone could help me with my problem I be very thankful.
static void Pos(int[] array)
{
Random rand = new Random();
float sum = 0;
int counter = 0;
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(-100, 100);
if(sum >= 0)
{
sum += array[i];
counter++;
}
float avg = sum / counter;
return avg; <<< error?
}
}

You cannot return anthing since your return type is void
Change this static void Pos(int[] array) to static float Pos(int[] array)
And also you may get "not all code path returns";
Do this:
static float Pos(int[] array)
{
Random rand = new Random();
float sum = 0;
int counter = 0;
float avg;
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(-100, 100);
if(sum >= 0)
{
sum += array[i];
counter++;
}
avg = sum / counter;
}
return avg;
}

You're using a void which doesn't allow you to return anything.

Your method's return type is void, and you are returning a value from it.
Do it like this:
static float Pos(int[] array)
{
Random rand = new Random();
float sum = 0;
int counter = 0;
float avg = 0;
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(-100, 100);
if(sum >= 0)
{
sum += array[i];
counter++;
}
avg = sum / counter;
}
return avg;
}
When you set the return type to void, it means you don't want the method to return anything.

Related

ArrayIndexOutOfBounds exception in hackerrank Cut the sticks

I am trying to implement a problem in Hackerrank Cut the sticks. Problem can be found here
my code is this
static int[] cutTheSticks(int[] arr)
{
int n = arr.Length, k = 0;
int[] result = new int[n];
Array.Sort(arr);
Array.Reverse(arr);
while(arr.Length != 0)
{
result[k] = arr.Length;
k++;
for(int i = 0; i < n; ++i)
{
arr[i] -= arr[arr.Length - 1];
}
}
return result;
}
it shows error as-
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Solution.cutTheSticks (System.Int32[] arr) [0x00020] in solution.cs:24
line 24 is:
result[k] = arr.Length;
How to remove this?
There are several problems with your code. To name a few:
You are giving the result array a fixed size (int[] result=new int[n];), but it's size depends entirely on how many duplicate values are contained in the list.
You are supposed to remove from the array the smallest value(s) in each iteration. However you are just modifying the values (arr[i] -= arr[arr.Length - 1];), not removing them, so the array length will remain the same, and thus while (arr.Length != 0) will always be true, creating an endless loop. This causes k++ to keep incrementing until it reaches a value greater than the array length, which then results in the exception you are getting.
Since you are supposed to change the size of the input array, I suggest using List<int> instead, here's an example:
List<int> output = new List<int>();
List<int> input = new List<int>(arr);
while (input.Count > 0)
{
output.Add(input.Count);
int min = input.Min();
input.RemoveAll(x => x == min);
input.ForEach(x => x -= min);
}
return output.ToArray();
It is necessary to add condition k < n before assigning value to avoid IndexOutOfRangeException exception. In addition, there is a strong need a condition to avoid infinite while loop :
static int[] cutTheSticks(int[] arr) {
int n = arr.Length,
k = 0;
int[] result = new int[n];
Array.Sort(arr);
Array.Reverse(arr);
while (arr.Length != 0)
{
if (k < n)
result[k] = arr.Length;
else
break;
k++;
for (int i = 0; i < n; ++i)
{
arr[i] -= arr[arr.Length - 1];
}
}
return result;
}
UPDATE:
It is possible to pop out one element after every iteration like this:
static int[] cutTheSticks(int[] arr)
{
int n = arr.Length,
k = 0;
int[] result = new int[n];
var arrToBeRemoved = arr.ToList();
Array.Sort(arr);
Array.Reverse(arr);
while (arr.Length != 0)
{
if (k < n)
result[k] = arr.Length;
else
break;
if (k < arrToBeRemoved.Count)
arrToBeRemoved.RemoveAt(k);
arr = arrToBeRemoved.ToArray();
k++;
for (int i = 0; i < arr.Length; ++i)
{
arr[i] -= arr[arr.Length - 1];
}
}
return result;
}
I would do it that way:
static int[] cutTheSticks(int[] arr)
{
List<int> results = new List<int>();
int cutted = 0;
while (cutted != 1)
{
cutted = 0;
int min = GetMin(arr);
if (min == 0)
{
break;
}
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] >= min)
{
arr[i] -= min;
cutted++;
}
}
results.Add(cutted);
}
return results.ToArray();
}
static int GetMin(int[] arr)
{
int min = int.MaxValue;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != 0 && arr[i] < min)
{
min = arr[i];
}
}
return min;
}

Raising a number to a power using only addition

I am trying to raise a number to a power using only addition but it does not work, it just raises a number bigger than the original.Here is my code:
private void ExpOperation()
{
result = 0;
num01 = Int32.Parse(inpu01.Text);
num02 = Int32.Parse(inpu02.Text);
int a = num02;
num02 = num01;
int i = 1;
while (i <= a)
{
result = SimpleMulti(num01,num02);
num01 = result;
i++;
}
result_Text.Text = result.ToString();
}
private int SimpleMulti (int num1, int num2)
{
int c = 0;
int i = 1;
while (i <= num2)
{
c += num1;
i++;
}
return c;
}
private int SimpleMulti (int x, int y)
{
int product = 0; //result of multiply
for (int i = 0; i<y; i++){
product += x;
}
//multiplication is repeated addition of x, repeated y times
//the initial solution with a while loop looks correct
return product;
}
private int ExpOperation(int x, int exponent)
{
int result = 1;
if (exponent == 0) {
return result; //anything that powers to 0 is 1
}
else
{
for (int i = 0; i < exponent; i++){
result = SimpleMulti(result, x);
//loop through exponent, multiply result by initial number, x
//e.g. 2^1 = 2, 2^2 = result of 2^1 x 2, 2^3 = result of 2^2 x 2
}
}
return result;
}
Keep in mind that this method does not support negative exponent, which deals with division, but instead of using SimpleMulti, you can create a method for SimpleDivide which uses subtraction instead. The principle is the same
I don't think this question is quite relevant to the main reason of this site, however I got a solution:
public long ExpOperation(int a, int b)
{
long result = 0;
long temp = 0;
for (int i = 1; i <= b; i++) // Executes a full loop when we have successfully multiplied the base number "a" by itself
{
for (int j = 1; j <= a; j++) // Increase the result by itself for a times to multiply the result by itself
result += temp;
temp = result:
}
return result;
}
Because x^y = x * x^(y-1), it can be solved recursively. Since SimpleMulti in question returns integer, I assume both base and exponent are non-negative integer.
private static int PowerWithAddition(int x, int y)
{
if(y == 0){
return 1;
}
var y1 = PowerWithAddition(x, y - 1);
var sum = 0;
for (int i = 0; i < y1; i++)
{
sum += x;
}
return sum;
}

passing methods working with arrays to main

If I have a method that finds the greatest integer in an array. How do I pass the result back to main?
public static int maxNumber(int[] Array) {
int maxNumber = Array[0];
for (int i = 1; i < Array.length; i++) {
if (List[i] > maxNumber) {
maxNumber = Array[i];
}
return maxNumber;
}
}
Return the result outside the loop, it should be this way
public static int maxNumber(int[] Array)
{
int maxNumber = Array[0];
for (int i = 1; i < Array.length; i++)
{
if (List[i] > maxNumber)
{
maxNumber = Array[i];
}
}
return maxNumber;
}
if you want to get the number as output, call like this
int max = maxNumber(yourArray);

2D-array display error

How am I supposed to display my 2D array? Or the average sum of my array? It won't let me.
The code is supposed to display a 2D array, add all those numbers, calculate the average and display the average.
// It gives me a richTextBox error. I tried to change 'float' to 'void' - gives
// me a return error.
//
// It says the object require non static field?
richTextBox1.AppendText(array[ i, j] + " ");
richTextBox1.AppendText(" "+ sum.ToString());
return avg; // <<< Error here
static float Avg(int[,] array)
{
return (float)array.OfType<int>().Average();
richTextBox1.Clear(); // <<<<==================== Here
Random rand = new Random();
float sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < cols; j++)
{
int value = rand.Next(-100, 100);
array[i, j] = value;
richTextBox1.AppendText(value + " "); // <<<<<<<===== Here
if (value <= 0)
sum += value;
float avg = sum / value;
}
return avg;//<<<========here
}
richTextBox1.AppendText(" Total Average is: " + avg.ToString()); // <<<==== Here
}
private void button6_Click(object sender, EventArgs e)
{
Avg(A);
}
Try this:
static float Avg(int[,] array)
{
return (float)array.OfType<int>().Average();
}
Then you use it like this:
var array = new int [2,3] {{1,2, 3}, {4,5, 6}};
Console.WriteLine(Avg(array));
Update - for jagged arrays
static float Avg(int[][] array)
{
return (float)array.SelectMany(a => a).Average();
}
void Main()
{
int[][] array =
{
new int[] {1,2,3},
new int[] {4,5}
};
Console.WriteLine(Avg(array));
}
Update 2
if you want to do it your way try this:
private void Avg(int [,] array)
{
richTextBox1.Clear();
float sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
richTextBox1.AppendText(array[i,j] + " ");
sum += array[i,j];
}
}
richTextBox1.AppendText(" Total Average is: " + (float)sum/(rows*cols));
}
Because we do not really know, what do you try to make with the Avg method. I just try to sumarize:
static float Avg: you cannot use static where you use Form instance members (like richTextBox1). Please remove 'static' or move usage of richTextBox1 just in the OnClick method.
Don't use return where you want. Everything after it will not process (if not using try/finally). If you want to use the returned value, call it on the last line after everything in method processed.
return avg: avg is not known in the current context, whether is defined in the previous closure (do you know what have your neighbour behind the closed doors?)
For the final solution, refer to Ned's answer.

Array method Random number display

So I am trying to make an array that call a method to randomize 100 numbers from -100 to 100
And display the Average Negative number. I keep staring at it and I cant find the error or a solution maybe I am tired but if anybody could help me I would be very thankful.
private void button1_Click(object sender, EventArgs e)
{
int[] P = new int[100];
Random rand = new Random();
float enAvg = AvgNeg(P);
textBox1.Text = (enAvg).ToString("");
}
static float AvgNeg(int[] array)
{
float sum = 0;
int counter = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] < 0)
{
sum += array[i];
counter++;
}
}
float avg = sum / counter;
return avg;
}
You can do this in three lines:
Random r = new Random();
int[] num = Enumerable.Range(0, 100).Select(x => r.Next(-100, 101)).ToArray();
double avg = num.Where(n => n < 0).Average();
The problem is because all your values is zero (0), so, your counter variable is zero (0).
You can't divide by zero. So the float value of avg is NaN.
Start counter with value 1.
int counter = 1;
or verify if counter is zero before divide:
if(counter == 0)
return 0;
else
{
float avg = sum / counter;
return avg;
}

Categories

Resources