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);
Related
I have two arrays that have 20 randomly assigned elements and I need to create a method that replaces the duplicate numbers in an array with zeros but when I display the output nothing is changed.
This is the method for removing the repeating numbers. Is there a problem with the way the for loop is set up?
public static void RemoveDuplicates (int [] xArray){
for (int i = 0; i > xArray.Length-1; i++){
if (xArray[i] == xArray[i+1])
xArray[i] = 0;
}
}
and this is the whole thing
using System;
class MainClass {
public static void Main (string[] args) {
int [] student1 = new int [20];
int [] student2 = new int [20];
//int [] both = new int [40];
FillArray(student1);
FillArray(student2);
//Console.WriteLine("---------- Unsorted ----------");
//DisplayOutput(student1,student2);
Sort2Arrays(student1,student2);
//Console.WriteLine("---------- Sorted ----------");
//DisplayOutput(student1,student2);
RemoveDuplicates(student1);
RemoveDuplicates(student2);
DisplayOutput(student1, student2);
Sort2Arrays(student1,student2);
Console.WriteLine("---------- 1 and 2 no duplicates ----------");
DisplayOutput(student1, student2);
Console.WriteLine("done");
}//end main
public static void FillArray (int [] xArray){
Random rnd = new Random();
for(int i = 0; i< xArray.Length; i++){
xArray.SetValue (rnd.Next(80, 101),i);
}//end for
}//end FillArray
public static void Sort2Arrays (int [] xArray, int [] yArray){
Array.Sort(xArray);
Array.Sort(yArray);
}//end Sort2Arrays
public static void DisplayOutput (int [] xArray, int [] yArray){
for(int i = 0; i< 20; i++){
Console.WriteLine("{0}-{1}",xArray.GetValue(i),yArray.GetValue(i));
}//end for
}//end DisplayOutput
public static void RemoveDuplicates (int [] xArray){
for (int i = 0; i > xArray.Length-1; i++){
if (xArray[i] == xArray[i+1])
xArray[i] = 0;
}
}
}
Your for-loop condition is wrong, not >:
for (int i = 0; i > xArray.Length - 1; i++){
but <
for (int i = 0; i < xArray.Length - 1; i++)
with your version you will never enter the loop.
May i suggest you a different way to replace the duplicates(what you actually do), which is more efficient, more readable and more reusable:
public static void ReplaceDuplicates<T>(IList<T> xArray, T replaceWith)
{
HashSet<T> set = new HashSet<T>();
for (int i = 0; i < xArray.Count; i++)
{
if(!set.Add(xArray[i]))
{
xArray[i] = replaceWith;
}
}
}
It also doesn't need to sort the collection.
You use it in this way:
ReplaceDuplicates(student1, 0);
ReplaceDuplicates(student2, 0);
the > shouldve been <
public static void RemoveDuplicates (int [] xArray){
for (int i = 0; i < xArray.Length - 2; i++){
if (xArray[i] == xArray[i+1])
xArray[i] = 0;
}//end for
}//end RemoveDuplicates
public static void RemoveDuplicates(int[] array)
{
var foundValues = new HashSet<int>();
for (var index = 0; index < array.Length; index++)
{
var currentValue = array[index];
if (foundValues.Contains(currentValue))
{
array[index] = 0;
}
else
{
foundValues.Add(currentValue);
}
}
}
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;
}
I want to develop method that will return the length of largest substring composed of identical characters form string that is passed as argument, but without using any of .NET libraries.
For example if we pass aaacccccdefffgg as parameter the biggest substring is ccccc and method should return 5.
Here is my working solution :
public static int GetMaxSubstringLenght(char[] myArray)
{
int max = 0;
for (int i = 0; i < myArray.Length-1; i++)
{
if (myArray.Length == 0)
{
return 0;
}
else
{
int j = i + 1;
int currentMax = 1; // string has some value, so we start with 1
while (myArray[i] == myArray[j])
{
currentMax++;
if (max < currentMax)
{
max = currentMax;
}
j++;
}
}
}
return max;
}
The code above will return expected result, but there will be some unnecessary iteration in for loop that I want to avoid. In first iteration when i=0it will compare it until j=2 and then will get out of while loop and start second iteration in for loop comparing the one at [1] index with [2], which we already did in previous iteration.So basically, when first iteration is completed, next one should start from the last value of j. How can I achieve that ?
Thank You in advance.
Since you want "Largest substring..." let's take String as argument and return String
public static String GetMaxSubstring(String value) {
if (String.IsNullOrEmpty(value))
return "";
int bestCount = 0;
char bestChar = '\0';
int currentCount = 0;
char current = '\0';
for (int i = 0; i < value.Length; ++i) {
if ((i == 0) || (value[i] != current))
currentCount = 0;
currentCount += 1;
current = value[i];
if (currentCount > bestCount) {
bestCount = currentCount;
bestChar = current;
}
}
return new String(bestChar, bestCount);
}
....
// "ccccc"
String result = GetMaxSubstring("aaacccccdefffgg");
// 5
int length = result.Length;
Another approach:
public static int MaxSubstringLength(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
int max = 0, cur = 1;
for (int i = 1; i < s.Length; ++i, ++cur)
{
if (s[i] != s[i-1])
{
max = cur > max ? cur : max;
cur = 0;
}
}
return cur > max ? cur : max;
}
[EDIT] Simplified the code.
[EDIT2] Simplified the code further.
you also can do it with one loop:
public static int GetMaxSubstringLenght(char[] myArray)
{
int max = 0;
char currentchar = myArray[0];
int count = 1;
for each(char c in myArray)
{
if(currentchar != c)
{
count = 1;
currentchar = c;
}
if(count > max)
{
max = count;
}
count++;
}
return max;
}
I changed the code... now this code does not use math.max and I think I eleminated the mistake... I've no IDE at the moment to test it
public static int GetMaxSubstringLenght(char[] myArray)
{
if (myArray.Length == 0)
return 0;
if (myArray.Length == 1)
return 1;
int max = 1;
int localMax = 1;
for (int i = 0; i < myArray.Length - max; i++ )
{
if (myArray[i] == myArray[i + 1])
{
localMax++;
}
else
{
max = Math.Max(max, localMax);
localMax = 1;
}
}
return Math.Max(max, localMax);
}
static int LongestCharSequence(string s)
{
if (string.IsNullOrEmpty(s)) return 0;
var prevChar = '\0';
int cmax = 0;
int max = 1;
foreach (char c in s)
{
if (c != prevChar)
{
cmax = 1;
prevChar = c;
}
else
{
if (++cmax > max) max = cmax;
}
}
return max;
}
recursion!
static int LongestCharSequence(string s)
{
int i = (s?.Length ?? 0) == 0 ? 0 : 1;
for (; i < s?.Length; i++)
if (s[i] != s[i - 1]) return Math.Max(i, LongestCharSequence(s.Substring(i)));
return i;
}
Another solution using my favorite nested loop technique:
public static int MaxSubstringLength(string s)
{
int maxLength = 0;
for (int length = s != null ? s.Length : 0, pos = 0; pos < length;)
{
int start = pos;
while (++pos < length && s[pos] == s[start]) { }
maxLength = Math.Max(maxLength, pos - start);
}
return maxLength;
}
I don't know why I've come up with the following CS0029 error in the last line (return dmin). It's telling me that I can't implicitly convert type int to int[]:
private static int[] MinDistance(int[] sortedArray)
{
int dmin = int.MaxValue;
int length = sortedArray.Length;
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (sortedArray[i] != sortedArray[j] && Math.Abs(i - j) < dmin)
{
dmin = Math.Abs(i - j);
}
}
}
return dmin;
dmin is an Int, but MinDistance is returning an array of int (int[]). If you need the int and not an array change the first line to:
private static int MinDistance(int[] sortedArray)
Change your code
private static int MinDistance(int[] sortedArray)
{
int dmin = int.MaxValue;
int length = sortedArray.Length;
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (sortedArray[i] != sortedArray[j] && Math.Abs(i - j) < dmin)
{
dmin = Math.Abs(i - j);
}
}
}
return dmin;
As everyone said, your mistake is here to declare your function as returning an Array of int (> int[]) where as in the code, you are returning an int value (dmin, the minimum value of your to-be-sorted array).
What you need to do is :
1/ change the declaration of your function so it returns an int, as stated by Aimnox
2/ declare an int where you are calling your function :
int[] sortedArray = MinDistance(unsortedArray); // WRONG
int minValue = MinDistance(unsortedArray); // RIGHT
you've gotten yourself tied in knots here with your arrays
you are feeding in an array converting it to an integer value and then trying to treat that as an array, so firstly you need to think about what you are doing
so do you want THE minumum value or ALL minimum values?
if its THE min then
int min = MinDistance(array);
private static int MinDistance(int[] sortedArray)
{
int dmin = int.MaxValue;
int length = sortedArray.Length;
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (sortedArray[i] != sortedArray[j] && Math.Abs(i - j) < dmin)
{
dmin = Math.Abs(i - j);
}
}
}
return dmin;
}
if its ALL then
int[] allMin = MinDistance(array);
private static int[] MinDistance(int[] sortedArray)
{
List<int> dmin = new List<int>();
int length = sortedArray.Length;
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (sortedArray[i] != sortedArray[j] && Math.Abs(i - j) < dmin)
{
dmin.Add(Math.Abs(i - j));
}
}
}
return dmin.ToArray();
}
note this just corrects the typing issue not your logic
I'm doing a class assignment,
I need to create an 2D array of random numbers and sort them either bubble or other sorting codes. I'm fine with single array, but the problem is a 2D array filled with random numbers, I just don't get it.
Random numbers should be made of (-I,I) interval it's a user input. Sorry for bad english, haven't gotten any degree. In working on visual C# windows form.
looking for simple couple cicles method.
example. : A[MxN] ->>> B[MxN] (Sorted 1.....n)
Getting the random numbers is trivial:
Random rnd;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
array[y][x] = l - rnd.Next(2 * l + 1);
Random.Next() will return a random value between 0 and the given parameter (excluding the parameter; which is the reason for the + 1).
A 2D array can be sorted just like a 1D array, it only depends how you want to handle multiple lines, e.g. is it just for display or do you want to sort every line for itself, etc.
Here's a solution which first sorts each row's columns into order, then sorts each row comparing by first column, then second, etc:
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
double[,] data = GenerateData();
OutputData(data, "Before");
SortData(ref data);
OutputData(data, "After");
}
double[,] GenerateData()
{
Random randomGenerator = new Random(DateTime.UtcNow.Millisecond);
double[,] data = new double[5, 5];
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
data[i, j] = (randomGenerator.NextDouble() * 2) - 1;
}
}
return data;
}
void OutputData(double[,] data, string message)
{
Console.WriteLine("=====================");
Console.WriteLine(message);
Console.WriteLine("=====================");
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
Console.Write(data[i, j]);
Console.Write("\t");
}
Console.WriteLine();
}
}
void SortData(ref double[,] data)
{
//sort sub arrays
SortDataRows(ref data);
//sort this array
for (int i = 0; i < data.GetLength(0)-1; i++)
{
for (int j = i; j < data.GetLength(0); j++)
{
for (int k = 0; k < data.GetLength(1); k++)
{
if (data[i, k].CompareTo(data[j, k]) < 0) //if already in order exit loop
{
break;
} else if (data[i, k].CompareTo(data[j, k]) > 0) //if out of order switch and loop
{
SwapRows(ref data, i, j);
break;
}//else orders are equal so far; continue to loop
}
}
}
}
void SortDataRows(ref double[,] data)
{
for (int row = 0; row < data.GetLength(0); row++)
{
for (int i = 0; i < data.GetLength(1) - 1; i++)
{
for (int j = i; j < data.GetLength(1); j++)
{
if (data[row, i].CompareTo(data[row, j]) > 0)
{
Swap<double>(ref data[row, i], ref data[row, j]);
}
}
}
}
}
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
void SwapRows(ref double[,]data, int i, int j)
{
for (int k = 0; k < data.GetLength(1); k++)
{
Swap<double>(ref data[i, k], ref data[j, k]);
}
}
}
}
The code's not the best (haven't had a cup of tea yet), but should do what you're after.
Here's a better solution (not using a 2D array as such, but using a structure which can easily be converted to/from such an array):
sing System.Diagnostics;
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
List<List<double>> data = GenerateData(5, 5).ToList<List<double>>();
OutputData(data,"Before");
foreach (List<double> item in data)
{
item.Sort();
}
data.Sort(CompareListOfDoubles);
OutputData(data,"After");
}
private IEnumerable<List<double>> GenerateData(int index1, int index2)
{
Random rnd = new Random(DateTime.UtcNow.Millisecond);
List<double> result;
for (int i = 0; i < index1; i++)
{
result = new List<double>(index2);
for (int j = 0; j < index2; j++)
{
result.Add(rnd.NextDouble() * 2 - 1);
}
yield return result;
}
}
private void OutputData(List<List<double>> data, string message)
{
Console.WriteLine(message);
foreach (List<double> list in data)
{
foreach (double datum in list)
{
Console.Write(datum);
Console.Write("\t");
}
Console.WriteLine();
}
}
static int CompareListOfDoubles(List<double> a, List<double> b)
{
for (int i = 0; i < a.Count; i++)
{
if (i > b.Count) return -1;
if (a[i] > b[i]) return -1;
if (a[i] < b[i]) return 1;
}
if (b.Count > a.Count) return 1;
return 0;
}
double[,] ConvertListListDoubleTo2DArray(List<List<double>> data)
{
double[,] result = new double[data.Count, data[0].Count];
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = data[i][j];
}
}
return result;
}
}