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 1 year ago.
Improve this question
I have a small issue to get my bubble sort algorithm to run correctly in C# but I can't figure out my mistake.
For ex. Random Input:
23,20, 17, 11, 17, 18, 4, 1, 16, 11
Output
20, 17, 11, 17, 18, 4, 1, 16, 11, 23
public class BubbleSort
{
public static void Start()
{
Console.WriteLine("This is a BubbleSort Program!");
Console.WriteLine("Pease enter the amount of Numbers to sort:");
int userNumber = int.Parse(Console.ReadLine());
int[] randomNumbers = new int[userNumber]; //Create an array of a random lengh (user decides)
Random r = new Random();
for (int i = 0; i < userNumber; i++)
{
randomNumbers[i] = r.Next(1, 25); //fill array with random numbers between 1 and 25
}
for (int i = 0; i < userNumber; i++)
{
Console.Write(" " + randomNumbers[i]); //write down the Array numbers unsorted
}
Console.ReadKey();
Console.WriteLine("");
bool getSwapper = true;
while (getSwapper) //Runs as long as there are numbers to sort
{
for (int i = 1; i < randomNumbers.Length; i++)
{
int tempNumber = 0;
if (randomNumbers[i - 1] > randomNumbers[i])
{
tempNumber = randomNumbers[i - 1]; //safe the bigger number in a temp var
randomNumbers[i - 1] = randomNumbers[i]; //overwrites the bigger number with the smaller one
randomNumbers[i] = tempNumber; //overwrites the smaller with the bigger one
getSwapper = true; //sets swapper to true
}
}
for (int i = 0; i < randomNumbers.Length; i++)
{
Console.Write(" " + randomNumbers[i]); //lists the sorted numbers of the array
}
Console.ReadKey();
}
}
}
}
You have two issues:
You should reset getSwapper to false.
You print the randomNumbers too early when they are not sorted yet.
Code:
bool getSwapper = true;
while (getSwapper) //Runs as long as there are numbers to sort
{
getSwapper = false; // <- reset getSwagger or we'll have an infinite loop;
for (int i = 1; i < randomNumbers.Length; i++)
{
int tempNumber = 0;
if (randomNumbers[i - 1] > randomNumbers[i])
{
tempNumber = randomNumbers[i - 1]; //safe the bigger number in a temp var
randomNumbers[i - 1] = randomNumbers[i]; //overwrites the bigger number with the smaller one
randomNumbers[i] = tempNumber; //overwrites the smaller with the bigger one
getSwapper = true; //sets swapper to true
}
}
} // <- You should end while here
// <- It's the right time now (when getSwapper is false) to print the results
for (int i = 0; i < randomNumbers.Length; i++)
{
Console.Write(" " + randomNumbers[i]); //lists the sorted numbers of the array
}
Console.ReadKey();
#Dmitry Bychenko already gave the correct answer that contains what you were missing.
I want to share a simple bubble sort algorithm with you that I just did, fewer lines of code, less complex. It may help you to master this algorithm.
Code:
var arrayValues = new[] { 99, 12, 11, 300, 400, 10, 9, 3, 6, 5, 7, 8};
for (var mainLoop = 0; mainLoop < arrayValues.Length; mainLoop++)
{
for (var innerLoop = mainLoop + 1; innerLoop < arrayValues.Length; innerLoop++)
{
if (arrayValues[mainLoop] <= arrayValues[innerLoop])
{
continue;
}
var temp = arrayValues[mainLoop];
arrayValues[mainLoop] = arrayValues[innerLoop];
arrayValues[innerLoop] = temp;
}
}
Related
First array is filled randomly, its length is set from the console .I have an array in which I need to write a sub-array of repeating numbers and the number of repeating numbers. For example {3 3 3 3 3 4}, 3 3 3 3 is the repeating numbers, 4 is their number.
The problem is that if there are repeating numbers at the end of the array, the loop doesn't output them and if I enter the debug mode, I can see that not all numbers are written. What could be the problem?
for (int i = 1; i < array.Length; i++)
{
if (array[i - 1] == array[i])
{
if((i + 1) != array.Length)
{
duplicateCount++;
addArray = array[i - 1];
duplicate += addArray + " ";
}
else
{
duplicateCount++;
lastElement = array[i - 1];
duplicate += lastElement;
}
}
else
{
if (duplicateCount != 1)
{
addPrevious = array[i - 1];
duplicate += addPrevious + " ";
duplicateArrays.Add(duplicate + duplicateCount);
duplicate = "";
duplicateCount = 1;
}
else
{
duplicateCount = 1;
}
}
}
duplicateArrays.Add(duplicate + duplicateCount);
While the Antidisestablishmentarianism code is the shortest one, it uses '^' which is index from end operator introduced in C# 8.0. I'm not carping about that but it's a difference worth knowing. Compiling the same code in the older version will generate a compile time exception. I'll be giving a long yet beginner friendly code which is pretty self-explanatory if you read it twice.
static void Main(string[] args)
{
int[] RandomArray = new int[] { 1, 2, 2, 3, 4, 4, 3, 1, 5, 2, 9, 8, 9, 8, 8, 5, 3, 4, 1 };
int RandomArrayLength = RandomArray.Length;
List<int[]> SubArrayList = new List<int[]>();
List<int> visited = new List<int>();
for (int i = 0; i < RandomArrayLength; i++)
{
int elem = RandomArray[i];
if (!visited.Contains(elem))
{
visited.Add(elem);
List<int> templist = new List<int>();
for (int j = 0; j < RandomArrayLength; j++)
{
if (elem == RandomArray[j])
{
templist.Add(elem);
}
}
if (templist.Count > 1) //You can remove this condition if you want to include all the elements
{
int elemCount = templist.Count;
List<int> sublist = new List<int>();
sublist.AddRange(templist);
sublist.Add(elemCount);
SubArrayList.Add(sublist.ToArray());
}
}
else
{
continue;
}
}
int SubArrayListCount = SubArrayList.Count;
for (int i = 0; i < SubArrayListCount; i++)
{
int[] SubArr = SubArrList[i];
int SubArrCount = SubArr.Length;
for (int j = 0; j < SubArrCount; j++)
{
Console.Write(SubArr[j].ToString() + " ");
}
Console.WriteLine();
}
}
I want to write a program that finds the longest sequence of equal elements in an array of integers. If several longest sequences exist, we should print the leftmost one. e.g. Input: 0 1 1 5 2 2 6 3 3
Output: 1 1
I know that my code doesn't work correctly, but I don't know how to fix it. I should solve the problem using only arrays because I don't know how to use lists.
int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
for (int i = 0; i < numbers.Length; i++)
{
int[] currentSequenceOfEqualElements = new int[numbers.Length];
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
if (currentSequenceOfEqualElements[0] == 0)
{
currentSequenceOfEqualElements[0] = numbers[i];
currentSequenceOfEqualElements[1] = numbers[i];
}
else
{
currentSequenceOfEqualElements[i + 2] = numbers[i];
}
}
else
{
break;
}
}
Console.WriteLine(string.Join(' ', currentSequenceOfEqualElements));
}
I will be very grateful if you can explain to me how to do it.
Here is the solution using the MoreLinq library (https://morelinq.github.io/) that mjwills suggested.
Once you get used to linq and morelinq methods the code is easier to understand than custom algo with nested loops and if.
var numbers = new int[]{ 0, 1, 1, 5, 2, 2, 6, 3, 3};
var result = numbers.GroupAdjacent(x => x)
.MaxBy(x => x.Count())
.FirstOrDefault();
foreach (var i in result)
{
Console.Write($"{i} ");
}
Here's a simple solution, using only loops and no linq. It should be nice and easy to understand.
int[] numbers = new[] { 0, 1, 1, 5, 2, 2, 6, 3, 3 };
// Some variables to keep track of the sequence we're currently looking
// at, and the longest sequence we've found so far. We're going to start
// the loop at the 2nd number, so we'll initialize these as if we've
// already processed the first number (which is 0, so we've seen the
// first number of a sequence of 0's).
// Number of numbers in the current sequence
int count = 1;
// Number which is part of the longest sequence so faar
int longestNum = numbers[0];
// Number of numbers in the longest sequence we've seen so far
int longestCount = 1;
for (int i = 1; i < numbers.Length; i++)
{
// We're starting a new sequence
if (numbers[i] != numbers[i-1])
{
count = 0;
}
count++;
// Have we just found a new longest sequence?
if (count > longestCount)
{
longestCount = count;
longestNum = numbers[i];
}
}
// longestNum = 1 and longestCount = 2 (because the longest sequence
// had 2 1's in it). Turn this into the string "1 1".
Console.WriteLine(
string.Join(" ", Enumerable.Repeat(longestNum, longestCount)));
// If you wanted to end up with an array containing [1, 1], then:
int[] result = new int[longestCount];
Array.Fill(result, longestNum);
I will illustrate a recursive answer for your question, below is the code, I kept some if-else statements that there is no need to have them, but at least the code shows the idea.
The code has a basic method that should be exposed as public and a private recursive method that does the heavy lifting. The longest sequence is the empty array(list)
var longSequenceEqualElem = new List<int>();
Later on the recursion, you pass all the elems of the array through all the recursion calls to keep querying the positions, the pos parameter indicates the position level of the recursion.
if (pos < elems.Length) //stop the recursion here, the position will fall out of the indexes of the array, just return what you have in sequence that should be the longest.
The following statement if (sequence.Contains(elems[pos])) means that you found the same number you were carrying on the sequence in the position pos, so you can add it to the sequence and call the recursion with the adjacent position(pos + 1)
If the element in position pos is not part of the sequence you had, then you need to call the recursion with a new sequence containing elems[pos] and later compare the result of that recursion call with the sequence you had to see which of them is the longest one.
Hope this helps
class Program
{
static void Main(string[] args)
{
var elemts = new int[] { 0, 1, 1, 5, 2, 2, 6, 3, 3 };
var result = LongestSequence(elemts);
foreach (var i in result)
{
Console.Write(i + "\t");
}
Console.ReadLine();
}
public static int[] LongestSequence(int[] elems)
{
var longSequenceEqualElem = new List<int>();
return LongestSequenceRec(elems, longSequenceEqualElem, 0);
}
private static int[] LongestSequenceRec(int[] elems, List<int> sequence, int pos)
{
if (pos < elems.Length)
{
if (sequence.Contains(elems[pos]))
{
sequence.Add(elems[pos]);
return LongestSequenceRec(elems, sequence, pos + 1);
}
else
{
var newSeq = LongestSequenceRec(elems, new List<int> { elems[pos] }, pos + 1);
return (newSeq.Length > sequence.Count) ? newSeq.ToArray() : sequence.ToArray();
}
}
return sequence.ToArray();
}
}
static void Main()
{
int[] array1 = new int[9] {0, 1, 1, 5, 2, 2, 6, 3, 3};
int[] array2 = new int[9] {0, 0, 0, 0, 0, 0, 0, 0, 0};
int max_count = 1;
int tempCount = 1;
int num = 0;
for (int i = 0; i < array1.Length - 1; i++)
{
if (array1[i] == array1[i + 1]) tempCount++;
else tempCount = 1;
if (tempCount > max_count)
{
max_count = tempCount;
num = array1[i];
}
}
for (int i = 0; i < max_count; i++) array2[i] = num;
for (int i = 0; i < max_count; i++) Console.Write(array2[i] + " ");
Console.ReadKey();
}
I want to find the total number of digits divisible by 5 between 1 - 100, in C# windows form, how to proceed from here?
int sum;
private void button2_Click(object sender, EventArgs e)
{
int[] intarray = new int[100];
for (int i = 0; i < 99; i++)
{
intarray[i] = i + 1;
}
foreach (int a in intarray)
{
if (a / 5 == 0)
{
}
}
}
Note than a / 5 == 0 is wrong. For example 10 is divisible by 2, the result is 10/5 = 2, not equal to 0.
if (a % 5 == 0)
{
//then a is divisible by 5. print or store it
}
The modulus operator, also known as Remainder, returns the remainder of the integer division.
Therefore, the full answer:
int nInRange = 0;
foreach (int a in intarray)
if (a % 5 == 0)
nInRange++;
Maybe this is what you want.
public static IEnumerable<int> GetIntsDivisible(int start, int finish, int divisor)
{
for (var i = start; i <= finish; i++)
if (i % divisor == 0)
yield return i;
}
public static void Main()
{
Console.WriteLine(string.Join(", ", GetIntsDivisible(1, 100, 5)));
}
or if you don't want to yield
public static List<int> GetIntsDivisible(int start, int finish, int divisor)
{
var result = new List<int>();
for (var i = start; i <= finish; i++)
if (i % divisor == 0)
result.Add(i);
return result;
}
Output
5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100
Full demo here
Initialize a variable as 0
for e.g. Count = 0;
then add statement Count++ in your if block as follows:
if (a % 5 == 0)
{
Count++;
}
Since question is a bit vague in exact requirement, I will write the basic logic that can find the numbers exactly divisible by other number.
There is something called modulus (%) operator. It gives you the remainder of division.e.g. 11%5 will be 1, 13%5 will be 3, whereas 15%5 will be 0
so logic goes like,
for(int i=0;i<=100;i++)
{
if((i%5)==0)
{
\\this is ur number
}
}
Every one has address your question but no one talk about this weird attempt.
I really think you should take 5 minute and read your code because you are just running everywhere.
You should take the pen and paper before going head first into coding.
Here is a simple reading of your code so you understand what you were doing.
Line 1:
int[] intarray = new int[100];
So you start win an array, I guess it's for the result, right ? You will not be storing the number from 1 to 100 for no reason?
Line 2:
for (int i = 0; i < 99; i++)
Now we count from 0 to 98, I though it was form 1 to 100 .. Yes 98 as you are using < instead of <=
Line 3:
intarray[i] = i + 1;
Why ? 3rd line and you are already lost! You are filling the array with number you just iterate. It's like filling a bottle with water, then use it to fill an other bottle because you needed water.
If you iterate from 1 to 100 you could have check if it was divisible.
for (int i = 1; i <= 100; i++)
Line 4:
foreach (int a in intarray)
Again ? We are back counting from 1 to 100..
Line 5:
if (a / 5 == 0)
If this is suppose to tell you if it divisible thats wrong. The correct math operator is the Modulo. The division symbole won't give you the result you expect.
{1,2,3,4} will give you True. Anything else will be false.
int count = 0;
for (int i = 1; i <= 100; i++)
{
if ((i % 5) == 0)
{
count++;
textBox1.Text = count.ToString();
}
}
Alternatively,
int num = (100 + 5) / 5 - (1 + 5 - 1) / 5;
//Show result here
I have an array of numbers that have some duplicate values.
I want to find the first two duplicate numbers.
The real problem is it must be in best performance and I cant use LINQ it must be in classic codes.
The real question is about best performance so it means best answer is the fastest language and fastest algorithm.
I tried it in C#:
int[] numbers = {5, 2, 10, 18, 55, 100, 10, 50, 23, 6, 14, 25, 12};
int result1 = -1;
int result2 = -1;
for (int i = 0; i < numbers.Length; i++)
{
for (int j = 0; j < numbers.Length; j++)
{
if (numbers[j] == numbers[i] & i != j)
{
result2 = j;
result1 = i;
J = numbers.Length; //this will cause loop exit.
i = numbers.Length; //this will cause first loop to exit.
}
}
}
Console.Write("The result of search is {0} and {1}", result1, result2);
Console.ReadLine();
I will appreciate any answers ;)
Use a dictionary to store the numbers and where you found them, and when you find one that exists in the dictionary, you have your duplicate and its position. Adding and locating items in a dictionary are O(1) operations, so the algorighm is an O(n) operation:
int[] numbers = { 5, 2, 10, 18, 55, 100, 10, 50, 23, 6, 14, 25, 12 };
Dictionary<int, int> found = new Dictionary<int,int>();
int result1 = -1, result2 = -1;
for (int i = 0; i < numbers.Length; i++) {
int number = numbers[i];
int pos;
if (found.TryGetValue(number, out pos)) {
result1 = pos;
result2 = i;
break;
}
found.Add(number, i);
}
Console.Write("The result of search is {0} and {1}", result1, result2);
Console.ReadLine();
For some additional performance you can preallocate space for all the items in the dictionary that it might need. This uses more memory in the average case, but keeps the dictionary from repeatedly allocating more space when it grows:
Dictionary<int, int> found = new Dictionary<int,int>(numbers.Length);
I have 2 one dimensional arrays, containing the exact same values:
public int[] start = new int[21] { 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14 };
public int[] end = new int[21] { 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14 };
Below is the code I use to generate a random index, and grab the element from the array with said index, and stick it in a 2D array, with randomly generated X and Y index.
for (int i = 0; i < 21; i++)
{
Random ranNum = new Random();
int genX = 0;
int genY = 5;
int indx = 1;
while (gameBoard[genX, genY].rank > -1)
{
genX = ranNum.Next(0, 9);
genY = ranNum.Next(5, 8);
}
while (start[indx] == -1)
{
indx = ranNum.Next(0, 21);
}
if (gameBoard[genX, genY].rank == -1)
{
gameBoard[genX, genY].rank = start[indx];
start[indx] = -1;
}
while (gameBoard[genX, genY].rank > -1)
{
genX = ranNum.Next(0, 9);
genY = ranNum.Next(0, 3);
}
while (end[indx] == -1)
{
indx = ranNum.Next(0, 21);
}
if (gameBoard[genX, genY].rank == -1)
{
gameBoard[genX, genY].rank = end[indx];
end[indx] = -1;
}
}
Basically, it takes a value from the "start" and "end" arrays, replaces them with a '-1' (so they don't get picked again), scans the 2D array for '-1s' (so it doesn't place the number in a location that already has one), and places it there.
Notice that the min and max value for the random are different for the "start" and "end" arrays. This is to ensure that they end up far away from each other, on the other side of the 2D array.
This code works. Now, I have a code that resets all the variables back to their previous state. A reset function which also works. See, if the user is not content with the random placement, they can reset the arrays, and randomize again.
At which point the program simply hangs / locks up. No error, no messages, it just stops working. Please, could you share any ideas on how / why this happens?
Note: If I remove the entire while loop concerning the "end" array, the program can randomize and reset all it wants.
Anyway, the code for the reset:
int resVal = 0;
for (int i = 0; i < 21; i++)
{
startBoard[i] = resVal;
enemyBoard[i] = resVal;
if (i == 0)
resVal++;
else if (i >= 6 && i < 19)
resVal++;
}
for (int y = 0; y < 8; y++)
{
for (int x = 0; x < 9; x++)
{
gameBoard[x, y] = new classPiece();
gameBoard[x, y].rank = -1;
}
}
Move Random ranNum = new Random(); out of the cycle.