I have a []string retry and I have some strings inside of it let's say:
a 2 , a 3 , h 9, asd 123 and so on. They all have intervals between the letter and the integer. Now I need to get how long is the letter part (in this case "qwe 2" the letter length is 3 and the integer part is 2). I'm later using .substring from the specified index at which the letter part finishes and the integer one starts.
string[] s = new string[5];
List<string> retry = new List<string>();
int max = 1;
for (int i = 0; i < s.Length; i++)
{
s[i] = Console.ReadLine();
}
Console.WriteLine(" ");
Array.Sort(s);
for (int j = 0; j < s.Length; j++)
{
if (j > 0)
{
if (s[j] == s[j - 1])
{
max++;
if (retry.Any(x => x.Contains(s[j])))
{
retry.Add(s[j] + " " + max);
}
else
{
if (j <= s.Length - 1)
{
if (s[j-1] != s[j])
{
retry.Add(s[j] + " " + max);
}
else
{
retry.Add(s[j] + " " + max);
}
}
}
}
else
{
max = 1;
}
}
}
for (int j = 0; j < retry.ToArray().Length; j++)
{
for (int k = j + 1; k < retry.ToArray().Length; k++)
{
var a1=retry[j].Substring(0,1);
var a2 = retry[k].Substring(0,1);
if(a1==a2)
{
var b1 = retry[j].Substring(2);
var b2 = retry[k].Substring(2);
if(int.Parse(b1)>int.Parse(b2))
{
retry.Remove(a2 + " "+ b2);
}
else
{
retry.Remove(a1 + " " + b1);
}
}
}
Console.WriteLine(retry[j]);
}
Console.ReadKey();
This only works for 1 letter.
The code below should get the result as expected:
string [] entries = {"xyz 1","q 2","poiuy 4"};
for(int i=0;i<entries.Length;i++)
{
var parts = entries[i].Split(' ');
var txtCount = parts[0].Length;
Console.WriteLine(String.Format("{0} {1}", txtCount, parts[1]));
}
How about...
string[] test = new [] { "qwe 2", "a 2", "b 3", "asd 123" };
foreach (var s in test)
{
var lastLetterIndex = Array.FindLastIndex(s.ToCharArray(), Char.IsLetter);
var lastNumberIndex = Array.FindLastIndex(s.ToCharArray(), Char.IsNumber);
Console.WriteLine(s);
Console.WriteLine("Letter Length : " + (lastLetterIndex + 1));
Console.WriteLine("Number Length : " + (lastNumberIndex - lastLetterIndex));
}
Console.ReadKey();
This iterates through all of the strings and counts the length of the chars, and stores the value of the number, as well as its index. Note that this information is lost upon each iteration, but I'll leave it to you to worry about storing that if you need that information for longer than the duration of an iteration.
int letterLength = 0, number = 0, index = 0;
string[] testString = { "a 2", "a 3", "h 9", "asd 123", "sw", "swa23", "swag 2464" };
foreach (string str in testString)
{
letterLength = 0;
index = -1;
int i = 0;
for (; i < str.Length; i++)
{
char c = str[i];
if (Char.IsLetter(c)) letterLength++;
else if (Char.IsNumber(c)) break;
}
StringBuilder strBuilder = new StringBuilder();
for (; i < str.Length; i++)
{
char c = str[i];
if (index == -1) index = str.IndexOf(c);
strBuilder.Append(c);
number = Int32.Parse(strBuilder.ToString());
}
Console.WriteLine($"String: {str}\nLetter Length: {letterLength} Number: {number} Index: {index}\n");
}
Related
I have to implement a simple spell checker. Basically I have to user input an incorrect sentence or a word, then a number N, and then N correct words each on new line. The program has to output "incorrect word: suggestion". If there is no suggestions available it should output "incorrect word: no suggestions" and if all the words from sentence are correct it should display "Correct text!". The typos can be:
Misspeled word.
Swapped letters.
Extra letter.
Missing letter.
To do this I implemented Levensthein minumim distance algorithm, which calculates the minimum number of modifications that a string has to take to be transformed into another string. All the test cases are fine but I want to reduce the cyclomatic complexity of the main method from 27 to below 26. Any suggestion would be helpful. For the example:
Thsi is an texzt fr tet
5
This
an
text
for
test
It displays:
Thsi: This
an: no suggestions
texzt: text
fr: for
tet: text test
using System;
using System.Collections.Generic;
namespace MisspelledWords
{
class Program
{
static void Main(string[] args)
{
string sentence = Console.ReadLine();
sentence = sentence.ToLower();
int numWords = int.Parse(Console.ReadLine());
const int doi = 2;
const int doi2 = 3;
int index = 0;
int index1 = 0;
string[] correctWords = new string[numWords];
for (int i = 0; i < numWords; i++)
{
correctWords[i] = Console.ReadLine();
}
foreach (string word in sentence.Split(' '))
{
index++;
int minDistance = int.MaxValue;
string closestWord = "";
foreach (string correctWord in correctWords)
{
int distance = GetLevenshteinDistance(word, correctWord);
if (distance < minDistance)
{
minDistance = distance;
closestWord = correctWord;
}
}
Message(minDistance, closestWord, word, index, ref index1, correctWords);
if (index1 != 0)
{
return;
}
}
static void Message(int minDistance, string closestWord, string word, int index, ref int index1, string[] correctWords)
{
if (minDistance >= doi)
{
// Print the misspelled word followed by "no suggestions"
Console.WriteLine(word + ": (no suggestion)");
}
else if (minDistance < doi && closestWord != word || minDistance >= doi2)
{
// Find all correct words that have the same minimum distance
List<string> suggestions = new List<string>();
foreach (string correctWord in correctWords)
{
int distance = GetLevenshteinDistance(word, correctWord);
if (distance == minDistance)
{
suggestions.Add(correctWord);
}
}
// Print the misspelled word followed by the suggestions
Console.Write(word + ": ");
Console.WriteLine(string.Join(" ", suggestions));
}
else if (minDistance == 0 && index > 1)
{
Console.WriteLine("Text corect!");
index1++;
}
}
static int Min(int value1, int value2, int value3)
{
return Math.Min(Math.Min(value1, value2), value3);
}
static int GetLevenshteinDistance(string word1, string word2)
{
int[,] distance = new int[word1.Length + 1, word2.Length + 1];
InitializeDistanceMatrix(distance, word1, word2);
CalculateLevenshteinDistance(distance, word1, word2);
return distance[word1.Length, word2.Length];
}
static void InitializeDistanceMatrix(int[,] distance, string word1, string word2)
{
for (int i = 0; i <= word1.Length; i++)
{
for (int j = 0; j <= word2.Length; j++)
{
if (i == 0)
{
distance[i, j] = j;
}
else if (j == 0)
{
distance[i, j] = i;
}
}
}
}
static void CalculateLevenshteinDistance(int[,] distance, string word1, string word2)
{
for (int i = 0; i <= word1.Length; i++)
{
for (int j = 0; j <= word2.Length; j++)
{
CLD(i, j, distance, word1, word2);
}
}
}
static void CLD(int i, int j, int[,] distance, string word1, string word2)
{
const int v = 2;
if (i <= 0 || j <= 0)
{
return;
}
distance[i, j] = Min(
distance[i - 1, j] + 1,
distance[i, j - 1] + 1,
distance[i - 1, j - 1] + (word1[i - 1] == word2[j - 1] ? 0 : 1));
// Check if swapping the characters at positions i and j results in a new minimum distance
if (i <= 1 || j <= 1 || word1[i - 1] != word2[j - v] || word1[i - v] != word2[j - 1])
{
return;
}
distance[i, j] = Math.Min(distance[i, j], distance[i - v, j - v] + 1);
}
Console.ReadLine();
}
}
}
I have a 2D Array in C# with user input to fill the Array. I need help to find the sum for every column and row.
var input = Console.ReadLine();
var n = int.Parse(input);
int[,] intArr = new int[n, 3];
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
for (int j = 0; j < 3; j++)
{
intArr[i, j] = int.Parse(parts[j]);
}
}
if (n == 1)
{
Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
Console.WriteLine("Row1: " + (intArr[n - 1, 0]));
Console.WriteLine("Row2: " + (intArr[n - 1, 1]));
Console.WriteLine("Row3: " + (intArr[n - 1, 2]));
}
if (n == 2)
{
Console.WriteLine("Sum of column " + Convert.ToString(n - 1) + ": " + (intArr[n - 2, 0] + intArr[n - 2, 1] + intArr[n - 2, 2]));
Console.WriteLine("Sum of column " + Convert.ToString(n) + ": " + (intArr[n - 1, 0] + intArr[n - 1, 1] + intArr[n - 1, 2]));
Console.WriteLine("Row 1: " + (intArr[n - 2, 0] + intArr[n - 1, 0]));
Console.WriteLine("Row 2: " + (intArr[n - 2, 1] + intArr[n - 1, 1]));
Console.WriteLine("Row 3: " + (intArr[n - 1, 2] + intArr[n - 1, 1]));
}
}
User input:
2
1 2 3
4 5 6
The output:
Sum of column 1: 6
Sum of column 2: 15
Row 1: 5
Row 2: 7
Row 3: 11
I want this output for N columns enter by user, but I am stuck!
Thank you!
Not sure, is your problem that you get an undesired result or that you have a model with a fixed number of elements? An array is a fixed size data container, so if you want any number of columns the architecture perhaps is where you want to change away from array.
Anyway, problem 1 is that you let user chose how many rows they want, but now how many column, so presuming there will be 3 conflicts with you data. So you have on array the .getUpperBound() for that which takes a range parameter and this way we can use a dynamic strucure
//From:
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
for (int j = 0; j < 3; j++)
{
intArr[i, j] = int.Parse(parts[j]);
}
}
//TO:
var rows = new List<int[]>();
for (int i = 0; i < n; i++)
{
input = Console.ReadLine();
var parts = input.Split(' ');
var listOf = new List<int>();
for (int j = 0; j < parts.GetUpperBound(0); j++)
{
listOf.Add(int.Parse(parts[j]));
}
rows.Add(listOf.ToArray());
}
from https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate?view=net-5.0 You get the aggregation capability
[Fact]
public void SumExerciseTest()
{
/*
The output:
Sum of column 1: 6
Sum of column 2: 15
Row 1: 5
Row 2: 7
Row 3: 11 => 9
*/
var testData = new[] { "1 2 3", "4 5 6" };
var input = "2"; // Console.ReadLine();
var n = int.Parse(input);
var rows = new List<int[]>(n);
for (int i = 0; i < n; i++)
{
input = testData[i];
var parts = input.Split(' ');
var listOf = new List<int>();
for (int j = 0; j <= parts.GetUpperBound(0); j++)
{
listOf.Add(int.Parse(parts[j]));
}
rows.Add(listOf.ToArray());
}
var rowSums = new List<int>(n);
foreach (int[] row in rows)
{
rowSums.Add(row.Aggregate((result, item) => result + item));
}
int maxLength = 0;
var rowLengths = new List<int>(n);
foreach (int[] row in rows)
{
rowLengths.Add(row.Length);
}
maxLength = rowLengths.Max();
int[] columnSums = new int[maxLength];
for (int idx = 0; idx < columnSums.Length; idx++){
foreach (var row in rows)
{
if (row.GetUpperBound(0) >= idx)
{
columnSums[idx] += row[idx];
}
}
}
int counter = 0;
//Outputting:
foreach(var sum in rowSums)
{
counter += 1;
System.Diagnostics.Debug.WriteLine($"Row {counter}: {sum}");
}
counter = 0;
foreach(var sum in columnSums)
{
counter += 1;
System.Diagnostics.Debug.WriteLine($"Column {counter}: {sum}");
}
Well, let's implement (extract) methods for summing arbitrary column and row:
private static int SumColumn(int[,] array, int column) {
if (array == null)
throw new ArgumentNullException(nameof(array));
if (column < 0 || column >= array.GetLength(1))
throw new ArgumentOutOfRangeException(nameof(column));
int result = 0;
for (int r = 0; r < array.GetLength(0); ++r)
result += array[r, column];
return result;
}
private static int SumRow(int[,] array, int row) {
if (array == null)
throw new ArgumentNullException(nameof(array));
if (row < 0 || row >= array.GetLength(0))
throw new ArgumentOutOfRangeException(nameof(row));
int result = 0;
for (int c = 0; c < array.GetLength(1); ++c)
result += array[row, c];
return result;
}
then you can put
for (int c = 0; c < intArr.GetLength(1); ++c)
Console.WriteLine($" Sum of column {c + 1}: {SumColumn(intArr, c)}");
for (int r = 0; r < intArr.GetLength(0); ++r)
Console.WriteLine($" Sum of row {r + 1}: {SumRow(intArr, r)}");
Here is the code it's able to run (w/ output issues):
Another "issue" when I output the buckets sorted with a loop it outputs the "blank" array spaces as well(as expected). How could I tell the program to "skip" empty entries on output to console? (bit lost atm) been trying for hours...
Bucket sort loses items from original array
The program takes the random data in the program and sorts by last name into buckets then sorting the "buckets" with a bubble sorts.
Thank you to anyone in advance.
Current issue is located lines:
int y = 0;
for (int a = 0; a < (studentInfo.Length - 1); a++)
{ //no idea...Errors at a = 14... because the a + 1 index...so uh
if (String.Compare(studentInfo[a].studentLastName, studentInfo[a + 1].studentLastName) > 0)
bucketOne[y] = studentInfo[a].studentLastName;
else
bucketTwo[y] = studentInfo[a].studentLastName;
y++;
}
Full/:
class Program
{
struct StudentIDs
{
public int studentIDs;
public string studentLastName;
public string studentFirstName;
}
struct UserStudentIDs
{
public int UserstudentIDs;
public string UserstudentLastName;
public string UserstudentFirstName;
}
static void Main(string[] args)
{
StudentIDs[] studentInfo = new StudentIDs[15];
studentInfo[0].studentIDs = 331;
studentInfo[0].studentLastName = "Thomas";
studentInfo[0].studentFirstName = "Joe";
studentInfo[1].studentIDs = 225;
studentInfo[1].studentLastName = "Smith";
studentInfo[1].studentFirstName = "Lisa";
studentInfo[2].studentIDs = 002;
studentInfo[2].studentLastName = "Jones";
studentInfo[2].studentFirstName = "Tina";
studentInfo[3].studentIDs = 333;
studentInfo[3].studentLastName = "White";
studentInfo[3].studentFirstName = "Bryan";
studentInfo[4].studentIDs = 998;
studentInfo[4].studentLastName = "Huff";
studentInfo[4].studentFirstName = "John";
studentInfo[5].studentIDs = 500;
studentInfo[5].studentLastName = "Street";
studentInfo[5].studentFirstName = "Zak";
studentInfo[6].studentIDs = 772;
studentInfo[6].studentLastName = "Abel";
studentInfo[6].studentFirstName = "Karen";
studentInfo[7].studentIDs = 222;
studentInfo[7].studentLastName = "Streit";
studentInfo[7].studentFirstName = "Susan";
studentInfo[8].studentIDs = 332;
studentInfo[8].studentLastName = "Thomas";
studentInfo[8].studentFirstName = "Dan";
studentInfo[9].studentIDs = 141;
studentInfo[9].studentLastName = "Bryient";
studentInfo[9].studentFirstName = "Bill";
studentInfo[10].studentIDs = 880;
studentInfo[10].studentLastName = "Forte";
studentInfo[10].studentFirstName = "Mary";
studentInfo[11].studentIDs = 900;
studentInfo[11].studentLastName = "Ferguson";
studentInfo[11].studentFirstName = "Fran";
studentInfo[12].studentIDs = 220;
studentInfo[12].studentLastName = "Worke";
studentInfo[12].studentFirstName = "Elaine";
studentInfo[13].studentIDs = 635;
studentInfo[13].studentLastName = "Knapp";
studentInfo[13].studentFirstName = "Justin";
studentInfo[14].studentIDs = 445;
studentInfo[14].studentLastName = "Dustin";
studentInfo[14].studentFirstName = "Tom";
WriteLine(" STUDENT INFO: (Unsorted Data) ");
for (int i = 0; i < studentInfo.Length; i++)
{
WriteLine("Student ID #: {0} ------ Last Name: {1} -- First Name: {2} ",
studentInfo[i].studentIDs, studentInfo[i].studentLastName, studentInfo[i].studentFirstName);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] bucketOne = new string[15];
string[] bucketTwo = new string[15];
int y = 0;
for (int a = 0; a < (studentInfo.Length - 1); a++)
{//no idea...Errors at a = 14... because the a + 1 index...so uh
if (String.Compare(studentInfo[a].studentLastName, studentInfo[a + 1].studentLastName) > 0)
//if ((studentInfo[a].studentLastName.CompareTo(studentInfo[a + 1].studentLastName)) > 0)
bucketOne[y] = studentInfo[a].studentLastName;
else
bucketTwo[y] = studentInfo[a].studentLastName;
y++;
}
//sort two buckets now with bubble sorting counts swaps and compare
int swap = 0,
compare = 0;
string tempString = " ";
bool Swapping;
do
{
Swapping = false;
for (int index = 0; index < (studentInfo.Length - 1); index++)
{
compare++;
if (string.Compare(bucketOne[index], bucketOne[index + 1]) < 0)
{
tempString = bucketOne[index];
bucketOne[index] = bucketOne[index + 1];
bucketOne[index + 1] = tempString;
swap++;
Swapping = true;
}
}
} while (Swapping == true);
//Bubble Sort Two
int swapTwo = 0,
compareTwo = 0;
string tempStringTwo = " ";
bool SwappingTwo;
do
{
SwappingTwo = false;
for (int index = 0; index < (studentInfo.Length - 1); index++)
{
compareTwo++;
if (string.Compare(bucketTwo[index], bucketTwo[index + 1]) < 0)
{
tempStringTwo = bucketTwo[index];
bucketTwo[index] = bucketTwo[index + 1];
bucketTwo[index + 1] = tempStringTwo;
swapTwo++;
SwappingTwo = true;
}
}
} while (SwappingTwo == true);
WriteLine("Bucket One Sorted: ");
for (int i = 0; i < bucketOne.Length; i++)
{
WriteLine("\nLast Names (Bucket One): {0}", bucketOne[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
WriteLine("\nBucket Two Sorted: ");
for (int i = 0; i < bucketTwo.Length; i++)
{
WriteLine("\nLast Names (Bucket Two): {0}", bucketTwo[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] FullBucket = bucketOne.Union(bucketTwo).ToArray(); // would remove any of the "same" name...
Array.Reverse(FullBucket);
foreach (var StudentLastName in FullBucket)
{
WriteLine(StudentLastName);
}
//string[] FullBucket = new string[15];
//for (int i = 0; i < FullBucket.Length; i++)
//{
// if (i >= bucketOne.Length) //- bucketOne.Length
// FullBucket[i] = bucketTwo[i];
// else
// FullBucket[i] = bucketOne[i];
//}
//string[] FullBucket = bucketOne.Concat(bucketTwo).ToArray();
//string[] FullBucket = new string[15];
//int numOne = 0, //i
// numTwo = 0, //j
// numThree = 0; //k
//// Traverse both array
//while (numOne < bucketOne.Length && numTwo < bucketTwo.Length)
//{
// // Check if current element of first
// // array is smaller than current element
// // of second array. If yes, store first
// // array element and increment first array
// // index. Otherwise do same with second array
// if (string.Compare(bucketOne[numOne], bucketTwo[numTwo]) < 0)//???????????????
// FullBucket[numThree = numThree + numThree] = bucketOne[numOne++];
// else
// FullBucket[numThree++] = bucketTwo[numTwo++];
//}
//// Store remaining elements of first array
//while (numOne < bucketOne.Length)
// FullBucket[numThree++] = bucketOne[numOne++];
//// Store remaining elements of second array
//while (numTwo < (bucketTwo.Length - 1))
// FullBucket[numThree++] = bucketTwo[numTwo++];
//WriteLine(" \nSTUDENT INFO: (Sorted Data) ");
//for (int i = 0; i < (FullBucket.Length - 1); i++) //Length -1 ?????
//{
// WriteLine("Student ID #: {0} ------ Last Name: {1} -- First Name: {2} ",
// studentInfo[i].studentIDs, studentInfo[i].studentLastName, studentInfo[i].studentFirstName);
//}
//ReadLine();
UserStudentIDs[] UserstudentInfo = new UserStudentIDs[20];
int RecordIndex = 0;
WriteLine("Enter Student ID #: ");
UserstudentInfo[RecordIndex].UserstudentIDs = Convert.ToInt32(ReadLine());
WriteLine("You May Enter Up To 20 Records: (Or 999 to Finish)");
while (UserstudentInfo[RecordIndex].UserstudentIDs != 999)
{
WriteLine("Enter Student First Name: ");
UserstudentInfo[RecordIndex].UserstudentFirstName = ReadLine();
WriteLine("Enter Student Last Name: ");
UserstudentInfo[RecordIndex].UserstudentLastName = ReadLine();
RecordIndex++;
WriteLine("Enter Student ID #: ");
UserstudentInfo[RecordIndex].UserstudentIDs = Convert.ToInt32(ReadLine());
}
WriteLine(" USER STUDENT INFO: (Unsorted Data) ");
for (int i = 0; i < RecordIndex; i++) //or user..info.length...etc
{
WriteLine("Student ID #: {0} ------ Last Name: {1} -- First Name: {2} ",
UserstudentInfo[i].UserstudentIDs, UserstudentInfo[i].UserstudentLastName, UserstudentInfo[i].UserstudentFirstName);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] bucketThree = new string[20];
string[] bucketFour = new string[20];
int L = 0;
for (int a = 0; a < RecordIndex; a++) // or ? (studentInfo.Length - 1)
{//no idea here again....
if (String.Compare(UserstudentInfo[a].UserstudentLastName, UserstudentInfo[a + 1].UserstudentLastName) > 0)
bucketThree[L] = UserstudentInfo[a].UserstudentLastName;
else
bucketFour[L] = UserstudentInfo[a].UserstudentLastName;
L++;
}
int swapThree = 0,
compareThree = 0;
string tempStringThree = " ";
bool SwappingThree;
do
{
SwappingThree = false;//(studentInfo.Length - 1)
for (int index = 0; index < RecordIndex; index++)
{
compareThree++;
if (string.Compare(bucketThree[index], bucketThree[index + 1]) < 0)
{
tempStringThree = bucketThree[index];
bucketThree[index] = bucketThree[index + 1];
bucketThree[index + 1] = tempStringThree;
swapThree++;
SwappingThree = true;
}
}
} while (SwappingThree == true);
int swapFour = 0,
compareFour = 0;
string tempStringFour = " ";
bool SwappingFour;
do
{
SwappingFour = false; //(studentInfo.Length - 1) or record index?
for (int index = 0; index < RecordIndex; index++)
{
compareFour++;
if (string.Compare(bucketFour[index], bucketFour[index + 1]) < 0)
{
tempStringFour = bucketFour[index];
bucketFour[index] = bucketFour[index + 1];
bucketFour[index + 1] = tempStringFour;
swapFour++;
SwappingFour = true;
}
}
} while (SwappingFour == true);
WriteLine("Bucket Three Sorted: ");
for (int i = 0; i < bucketThree.Length; i++)
{
WriteLine("\nLast Names (Bucket One): {0}", bucketThree[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
WriteLine("\nBucket Four Sorted: ");
for (int i = 0; i < bucketFour.Length; i++)
{
WriteLine("\nLast Names (Bucket Two): {0}", bucketFour[i]);
}
Write("\nPress Enter To Continue! ");
ReadLine();
string[] UserFullBucket = bucketThree.Union(bucketFour).ToArray();
Array.Reverse(UserFullBucket);
foreach (var UserStudentLastName in UserFullBucket)
{
WriteLine(UserStudentLastName);
}
ReadLine();
}
}
I need to write a program, which finds the maximal sequence of increasing elements in an array arr[n]. It is not necessary the elements to be consecutively placed. E.g.: {9, 6, 2, 7, 4, 7, 6, 5, 8, 4} -> {2, 4, 6, 8}.
I have some guidelines to use 2 nested loops and one additional array.
So far i know how to use if statements, loops and little arrays.
Any suggestions pls...?
This is my start so far (am I on a good track?):
Console.Write("Elements in array: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
int[] result;
for (int index = 0; index < arr.Length; index++)
{
Console.Write("Array [{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
for (int indexOut = 0; indexOut < n; indexOut++)
{
for (int indexIn = 1; indexIn < n; indexIn++)
{
}
}
nested loops are 1 loop inside another:
for (int 1 = 0; i < something.length; i++) {
for ( int j = 0; j < somethingElse.length; j++) {
// code
}
}
I think I found your solution here:
http://www.geeksforgeeks.org/dynamic-programming-set-3-longest-increasing-subsequence/
/* Dynamic Programming C/C++ implementation of LIS problem */
#include<stdio.h>
#include<stdlib.h>
/* lis() returns the length of the longest increasing
subsequence in arr[] of size n */
int lis( int arr[], int n )
{
int *lis, i, j, max = 0;
lis = (int*) malloc ( sizeof( int ) * n );
/* Initialize LIS values for all indexes */
for ( i = 0; i < n; i++ )
lis[i] = 1;
/* Compute optimized LIS values in bottom up manner */
for ( i = 1; i < n; i++ )
for ( j = 0; j < i; j++ )
if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for ( i = 0; i < n; i++ )
if ( max < lis[i] )
max = lis[i];
/* Free memory to avoid memory leak */
free( lis );
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LIS is %d\n", lis( arr, n ) );
return 0;
}
You will have to modify it a little to generate the actual array.
My code:
// Arr[]
int n = 10;
int[] arr = new int[n];
for (int index = 0; index < n; index++)
{
Console.Write("Array[{0}] = ", index);
arr[index] = int.Parse(Console.ReadLine());
}
// Len[]
int[] len = new int[n];
for (int index = 0; index < n; index++)
{
len[index] = 1;
}
// Correct len[]
for (int indexCount = 1; indexCount < n; indexCount++)
{
for (int indexNumber = 0; indexNumber < indexCount; indexNumber++)
{
if (arr[indexCount] > arr[indexNumber] && len[indexCount] < len[indexNumber] + 1)
{
len[indexCount] = len[indexNumber] + 1;
}
}
}
// Print new len[]
// Just to keep track of numbers
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < n; index++)
{
Console.Write(" " + len[index] + " ");
}
Console.WriteLine("}");
// Search for the max number in len[]
int max = int.MinValue;
int maxPosition = 0;
for (int index = 0; index < len.Length; index++)
{
if (len[index] > max)
{
max = len[index];
maxPosition = index;
}
}
// Create the result in result[]
int[] result = new int[max];
int i = (max - 1);
int maxCount = max;
for (int index = maxPosition; index >= 0; index--)
{
if (len[index] == max)
{
result[i] = arr[index];
max--;
i--;
}
}
// Print the result[]
Console.WriteLine();
Console.Write("{");
for (int index = 0; index < maxCount; index++)
{
Console.Write(" " + result[index] + " ");
}
Console.WriteLine("}");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int maincount = 0;
int indices = 0;
int increment = 0;
int count = 0;
int finalcount = 0;
int checkvalue = 0;
string consincval = null;
string consincval1 = null;
string finalconsincval = null;
Console.WriteLine("Enter number of rows of the array");
int len = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns of the array");
int wid = int.Parse(Console.ReadLine());
int[,] consecincrease = new int[len, wid];
Console.WriteLine("Enter the Values of array");
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
consecincrease[index, index1] = int.Parse(Console.ReadLine());
Console.Write("The value of the {0} {1}" + ":" + " " + "{2}", index, index1, consecincrease[index, index1]);
Console.WriteLine();
}
}
for (int index = 0; index < consecincrease.GetLength(0); index++)
{
for (int index1 = 0; index1 < consecincrease.GetLength(1); index1++)
{
increment = 0;
checkvalue = consecincrease[index, index1];
for ( indices = increment; indices < consecincrease.GetLength(1)-1; indices++)
{
if (checkvalue < consecincrease[index, indices +1])
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
checkvalue = consecincrease[index, indices+1];
consincval1 = consincval1 + " " + consincval + " ";
}
}
if (count == 0)
{
}
else if (count >= 1)
{
consincval = Convert.ToString(checkvalue);
count++;
maincount = count;
consincval1 = consincval1 + " " + consincval + " ";
}
if (finalcount < maincount)
{
finalcount = maincount;
finalconsincval = consincval1;
count = 0;
consincval1 = null;
consincval = null;
}
else
{
count = 0;
consincval1 = null;
consincval = null;
}
increment ++;
}
}
Console.WriteLine();
Console.WriteLine(finalconsincval);
Console.ReadLine();
}
}
}
So I've got an array of integer. I want to use a loop and exclude integers that makes the equation true. So that would be like
for (int n = 0; n < first9char.Length; n++ ) {
if (first9char[n] == clickValue) {
first9char[n] = first9char[n + 1];
But then it only changes the value that is equal to not changing whole array. So is there any way to do this?
I want to use it in this loop.
if (UserSquareMethod.clickedBoxes[0] == -1) {
MessageBox.Show("You have not selected any box");
} else {
int i = 0;
do {
if (textButtonArray[clickedBox[i]].Text == "" || clickValue == "") {
textButtonArray[clickedBox[i]].Text = clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 14, FontStyle.Bold);
}
else
{
textButtonArray[clickedBox[i]].Text += "," + clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 5, FontStyle.Regular);
string[] first9char = textButtonArray[clickedBox[i]].Text.Split(new string[] { "," }, StringSplitOptions.None);
for (int j = 1; j < first9char.Length; j++)
{
for (int k = j - 1; k >= 0; k--)
{
if (first9char[j] == first9char[k])
{
if (clearNumberClicked == true)
{
first9char = Array.FindAll(first9char, x => x != clickValue);
label2.Text = first9char[0];
//int n = 0;
//for (int p = 0; p < first9char.Length; p++)
//{
// if (first9char[p] != clickValue)
// {
// first9char[n] = first9char[p];
// n++;
// label2.Text += "," + first9char[n];
// }
// }
//for (int n = 0; n < first9char.Length; n++ ) {
//if (first9char[n] == clickValue) {
// first9char[n] = first9char[n + 1];
// for ( int p = 0; p < n; p++) {
//}
//}
//}
MessageBox.Show("Clear the number" + first9char[(first9char.Length - 1)] + "and " + clickValue + " " + first9char.Length);
}
else {
first9char[j] = "";
textButtonArray[clickedBox[i]].Text = first9char[0];
MessageBox.Show("You cannot enter the same number again!"+ first9char[j]+j);
for (int m = 1; m < (first9char.Length - 1); m++) {
textButtonArray[clickedBox[i]].Text += ","+ first9char[m];
}
}
}
}
}
if (textButtonArray[clickedBox[i]].Text.Length > 9)
{
textButtonArray[clickedBox[i]].Text = first9char[0] + "," + first9char[1] + "," + first9char[2] + "," + first9char[3] + "," + first9char[4];
MessageBox.Show("You cannot enter more than 5 numbers, please clear the box if you want to enter different number." + textButtonArray[clickedBox[i]].Text.Length);
}
}
i++;
}
while (clickedBox[i] != -1);
}
}
I would use LINQ for this:
first9char = first9char.Where(x => x != clickValue).ToArray();
It just means "pick the items that don't match". If you can't use LINQ for some reason, then just keep another counter, and make sure to only loop to n from there on in:
int n = 0;
for(int i = 0; i < first9char.Length; i++) {
if(first9char[i] != clickValue) {
first9char[n] = first9char[i];
n++;
}
}
Clean and efficient.