I'm unable to move the hash sign to the right to get the below shape.
My below code is working not as expected but I need to get the below shape.
Please how do I do it?
#
##
###
####
#####
######
#######
public class MyProgramTest
{
public static void StaircaseChallenge(int n)
{
for (int i = 1; i <= n; i++) {
Console.WriteLine(MySpace(i) + HashSign(i));
}
}
public static string HashSign(int n)
{
string t = "";
for (int i = 1; i <= n; i++) {
t += "#";
}
return t;
}
public static string MySpace(int n)
{
string t = "/t";
for (int i = 1; i < n; i++)
{
t += " ";
}
return t;
}
}
Try this:
public class MyProgramTest
{
public static void StaircaseChallenge(int n)
{
for (int i = 1; i <= n; i++)
{
Console.WriteLine(" ".PadLeft(n - i+1, ' ')+"#".PadLeft(i,'#'));
}
}
Or make few changes to your code:
public class MyProgramTest
{
public static void StaircaseChallenge(int n)
{
for (int i = 1; i <= n; i++)
{
Console.WriteLine(MySpace(n - i + 1) + HashSign(i));
}
}
public static string HashSign(int n)
{
string t = "";
for (int i = 1; i <= n; i++)
{
t += "#";
}
return t;
}
public static string MySpace(int n)
{
string t = string.Empty;
for (int i = 1; i < n; i++)
{
t += " ";
}
return t;
}
}
A more memory efficient way would be using the StringBuilder class.
For this situation it's not critical, but nice to know.
// define the amount of steps
int n=8;
// amount of leading whitespaces, for later usage
int padding=0;
// this one is the "working" memory, initialized by n + padding whitespaces
StringBuilder currentLine=new StringBuilder(new string(' ',n+padding));
// it counts down from the last index to the one indicated by padding
for (int i = currentLine.Length-1; i >=padding; i--)
{
// replace the char at the current index with #; (here: always the index of the last whitespace)
currentLine[i]='#';
// display a copy of the current state on the console,
Console.WriteLine(currentLine.ToString());
}
Please change only few things in your code :
public class MyProgramTest
{
public static void StaircaseChallenge(int n)
{
for (int i = 1; i <= n; i++) {
Console.WriteLine(MySpace(i, n) + HashSign(i));
}
}
public static string HashSign(int n)
{
string t = "";
for (int i = 1; i <= n; i++) {
t += "#";
}
return t;
}
public static string MySpace(int m, int n)
{
string t = "";
for (int i = 1; i <= n - m; i++)
{
t += " ";
}
return t;
}
}
You have to pass more one variable is n (number of row) in MySpace() function for leave space. When you pass number of row in MySpace() function then it will leave (number of row - 1) space. So if you enter 5 then first time it will leave 4 space and then put "#" like wise.
Related
For the same 1 of the test cases have passed while all the other had failed. The failed ones test cases were of very long strings. but could not understand where did I go wrong.
The number of test cases and string is been read in the main function, and string gets passed to this function.
public static int getMaxScore(string jewels)
{
string temp=jewels;
int count=0;
for(int i=0;i<temp.Length-1;i++)
{
for(int j=i;j<temp.Length-1;j++)
{
if(jewels[i]==jewels[j+1])
{
temp=jewels.Remove(i,2);
count++;
}
else
{
continue;
}
}
}
return count;
}
for the passed 1, there were 2 test cases. In that, one being jewels="abcddcbd" and the other being "abcd". Expected Output was 3 for the first string and 0 for the second. however, i got the expected output for this test case. but failed all other ones(those are very long strings)
jewels="edmamjboxwzfjsgnmycuutvkhzerdiabcvzlnoazreuavyemxqwgyzdvrzyohamwamziqvdduequyyspfipvigooyqmwllvp"
Can somebody help me in knowing what is wrong in my code or how can I obtain the result I want?
Thanks in Advance!!!
Sounds a Jewel Quest puzzle. Checking a string for adjacent equal characters, remove them and increase the counter by 1. Removing the two characters from the string could produce a new one with adjacent equal characters so it must be checked again from the beginning to remove them, increase the counter, and do it all over again until no more.
public static int getMaxScore(string jewels)
{
var count = 0;
var max = jewels.Length;
var i = 0;
var chars = jewels.ToList();
var adj = 2; //<- Change to increase the number of adjacent chars.
while (i < max)
{
if (chars.Count >= adj && i <= chars.Count - adj &&
chars.Skip(i).Take(adj).Distinct().Count() == 1)
{
count++;
chars.RemoveRange(i, adj);
max = chars.Count;
i = 0;
}
else
i++;
}
return count;
}
Testing:
void TheCaller()
{
Console.WriteLine(getMaxScore("abcddcbd"));
Console.WriteLine(getMaxScore("abcd"));
Console.WriteLine(getMaxScore("edmamjboxwzfjsgnmycuutvkhzerdiabcvzlnoazreuavyemxqwgyzdvrzyohamwamziqvdduequyyspfipvigooyqmwllvp"));
}
Writes 3, 0, and 5 respectively.
public static int CountThings(string s)
{
if(s.Length < 2) { return 0; }
int n = 0;
for (int i = 0; i < s.Length - 1; i++)
{
if (s[i] == s[i + 1])
{
int start = i;
int end = i + 1;
while (s[start] == s[end] && start >= 0 && end <= s.Length - 1)
{
n++;
start--;
end++;
}
}
}
return n;
}
For grits and shins, here's a compact recursive version:
static void Main(string[] args)
{
string jewels = "edmamjboxwzfjsgnmycuutvkhzerdiabcvzlnoazreuavyemxqwgyzdvrzyohamwamziqvdduequyyspfipvigooyqmwllvp";
int score = getMaxScore(new StringBuilder(jewels));
Console.WriteLine($"jewels = {jewels}");
Console.WriteLine($"score = {score}");
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}
static int getMaxScore(StringBuilder jewels)
{
for(int i=0; i<(jewels.Length-1); i++)
if (jewels[i]==jewels[i+1])
return 1 + getMaxScore(jewels.Remove(i, 2));
return 0;
}
I need to count the number of comparisons done by the following search function..
Also how to calculate the execution time..Any help? I want the count and time to be printed in the output.
// C# program for Naive Pattern Searching
using System;
class GFG {
public static void search(String txt, String pat)
{
int M = pat.Length;
int N = txt.Length;
/* A loop to slide pat one by one */
for (int i = 0; i <= N - M; i++) {
int j;
/* For current index i, check for pattern
match */
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
// if pat[0...M-1] = txt[i, i+1, ...i+M-1]
if (j == M)
Console.WriteLine("Pattern found at index " + i);
}
}
// Driver code
public static void Main()
{
String txt = "AABAACAADAABAAABAA";
String pat = "AABA";
search(txt, pat);
}
}
// This code is Contributed by Sam007
I need to count the number of comparisons done by the following search function...
You can use counter for this:
public static void search(String txt, String pat, out int counter)
{
int M = pat.Length;
int N = txt.Length;
counter = 0;
/* A loop to slide pat one by one */
for (int i = 0; i <= N - M; i++)
{
int j;
/* For current index i, check for pattern
match */
for (j = 0; j < M; j++)
{
counter++; // counter for below if statement
if (txt[i + j] != pat[j])
{
break;
}
}
// if pat[0...M-1] = txt[i, i+1, ...i+M-1]
if (j == M)
{
Console.WriteLine("Pattern found at index " + i);
}
counter++; // counter for above if statement
}
}
Also how to calculate the execution time.
You can use StopWatch class for this case:
public static async Task Main(string[] args)
{
String txt = "AABAACAADAABAAABAA";
String pat = "AABA";
var stopWatch = new Stopwatch();
stopWatch.Start();
search(txt, pat, out var counter);
stopWatch.Stop();
Console.WriteLine("--------------");
Console.WriteLine($"Count of operations: {counter}, elapsed time: {stopWatch.ElapsedMilliseconds} miliseconds");
}
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
I have this Sunday Algorithm, which checks some occurrences in some text.
class Program
{
static int alphabet = 512;
static int[] table = new int[alphabet];
static int[] occurence(string pattern)
{
for(char a = (char)0; a<(char)alphabet;a++)
{
table[(int)a] = -1;
}
for(int i = 0; i< pattern.Length;i++)
{
char a = pattern[i];
table[(int)a] = i;
}
return table;
}
public static int Sunday(string text, string pattern)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int k = 0;
int i = 0;
int[] table = new int[pattern.Length];
table = occurence(pattern);
while(i <= text.Length - pattern.Length)
{
int j = 0;
while(j<pattern.Length && text[i+j] == pattern[j])
{
j++;
}
if(j==pattern.Length)
{
k++;
}
i += pattern.Length;
if(i<text.Length)
{
i -= table[(int)text[i]];
}
}
timer.Stop();
Console.WriteLine(timer.Elapsed);
return k;
}
static void Main(string[] args)
{
string text = File.ReadAllText(#"C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Test Patterns\Book1.txt");
string pattern = "frankenstein";
Console.WriteLine(Sunday(text, pattern));
}
}
This is my algorithm, which works well on small input of text. In the code, I try to read a text file which consists of roughly 80 000 words and 450 000 characters. I get this exception:
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Sunday1.Program.Sunday(String text, String pattern) in C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Sunday1\Sunday1\Program.cs:line 55
at Sunday1.Program.Main(String[] args) in C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Sunday1\Sunday1\Program.cs:line 68
..at the following line:
i -= table[(int)text[i]];
Is it because it can not fit in string or is it something else?
Changing the algorithm to read and check line by line may be a solution, but is there a way to avoid it?
A char has a length of two bytes or 16 bits not 9. So I guess your alphabet should therefore probably be 65336 or simply char.MaxValue instead of 512.
Also there's no need of the static fields. You can make them local to occurence(). And in Sunday, you don't need to initialize table with new int[pattern.Length], you can directly use occurence(pattern).
class Program
{
static int[] occurence(string pattern)
{
int[] table = new int[char.MaxValue + 1];
for (int a = 0; a < char.MaxValue + 1; a++)
{
table[a] = -1;
}
for (int i = 0; i < pattern.Length; i++)
{
char a = pattern[i];
table[(int)a] = i;
}
return table;
}
public static int Sunday(string text, string pattern)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int k = 0;
int i = 0;
int[] table = occurence(pattern);
while (i <= text.Length - pattern.Length)
{
int j = 0;
while (j < pattern.Length && text[i + j] == pattern[j])
{
j++;
}
if (j == pattern.Length)
{
k++;
}
i += pattern.Length;
if (i < text.Length)
{
i -= table[(int)text[i]];
}
}
timer.Stop();
Console.WriteLine(timer.Elapsed);
return k;
}
static void Main(string[] args)
{
string text = File.ReadAllText(#"C:\Users\Bacho\Desktop\Studies\Advanced Algorithms\Test Patterns\Book1.txt");
string pattern = "frankenstein";
Console.WriteLine(Sunday(text, pattern));
}
}
This is program consumes 36.50 MB of memory but I want it to be less than 32 MB
public static void CreateText(string text)
{
if (Convert.ToInt32(text.Length) <= 80)
{
int n;
string str = "";
string count = "";
char[] mas = text.ToCharArray();
for (int i = 0; i < Convert.ToInt32(mas.Length); i++)
{
if (int.TryParse(mas[i].ToString(), out n))
{
count += mas[i].ToString();
}
else
{
if (String.IsNullOrEmpty(count))
{
str += mas[i].ToString();
}
else
{
for (int j = 0; j < Convert.ToInt32(count); j++)
{
str += mas[i].ToString();
}
count = "";
}
}
}
Console.WriteLine(str);
} else {
Console.WriteLine("Error");
}
}
To reduce memory footprint you need to get read of temporary string objects generated by applying operation += against a string. String is immutable object in C#, so += creates new string. StringBuilder is mutable, so use it instead of string. You also need to have count as an int, not string or StringBuilder.
public static void CreateText(string mas)
{
if (mas.Length <= 80)
{
StringBuilder str;
int count;
for (int i = 0; i < mas.Length; i++)
{
if (mas[i] >= '0' && mas[i] <= '9')
count = count * 10 + mas[i] - '0';
else
{
if (count == 0)
str.Append(mas[i]);
else
{
for (int j = 0; j < count; j++)
str.Append(mas[i]);
count = 0;
}
}
}
Console.WriteLine(str.ToString());
}
else
Console.WriteLine("Error");
}
This probably isn't possible. Most of the RAM in a 36MB program is just core framework libraries. 36MB is nothing.
But I do see some potential improvements, the biggest of which are maintaining count as an integer rather than a string and using a string constructor and StringBuilder instead of appending to a string all the time:
public static void CreateText(string text)
{
if (text != null && text.Length <= 80)
{
int n; int count = 0;
StringBuilder result = new StringBuilder();
char[] mas = text.ToCharArray();
foreach(char c in text)
{
if (int.TryParse(c.ToString(), out n))
{
count = (count * 10) + n;
}
else
{
if (count == 0)
{
result.Append(c);
}
else
{
result.Append(new string(c, count));
count = 0;
}
}
}
Console.WriteLine(result.ToString());
} else {
Console.WriteLine("Error");
}
}
There is a potential bug there if you want to be able to explicitly set 0 repetition in the input string. If that's the case, we'll need something that is slightly less efficient, but should still have a big improvement over the original:
public static void CreateText(string text)
{
if (text != null && text.Length <= 80)
{
int n; int count = -1;
StringBuilder result = new StringBuilder();
char[] mas = text.ToCharArray();
foreach(char c in text)
{
if (int.TryParse(c.ToString(), out n))
{
if (count == -1) count = 0;
count = (count * 10) + n;
}
else
{
if (count == -1)
{
result.Append(c);
}
else
{
result.Append(new string(c, count));
count = -1;
}
}
}
Console.WriteLine(result.ToString());
} else {
Console.WriteLine("Error");
}
}
Try this:
public static void CreateText(string text)
{
if (text.Length <= 80)
{
var str = new StringBuilder();
var count = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
int n;
if (int.TryParse(text[i].ToString(), out n))
{
count.Append(text[i]);
}
else
{
if (String.IsNullOrEmpty(count.ToString()))
{
str.Append(text[i]);
}
else
{
for (int j = 0; j < Convert.ToInt32(count.ToString()); j++)
{
str.Append(text[i].ToString());
}
count.Clear();
}
}
}
Console.WriteLine(str);
}
else
{
Console.WriteLine("Error");
}
}
What I did was:
Remove the string contetantions (since they are immutable) and used a StringBuilder instead.
No need to convert to a char[] since your can treat a String as one (it implements the indexer)
Moved the n closed to used to it's only allocated if needed
I have some string in format like that
XXXX-XXXX-X_X_
All "_" should be replaced with Letters and numberst to prodce sth like that:
XXXX-XXXX-XAXA
XXXX-XXXX-XAXB
XXXX-XXXX-XAXC
XXXX-XXXX-XAXD
XXXX-XXXX-XAXE
XXXX-XXXX-XAXF
XXXX-XXXX-XAXG
(...)
XXXX-XXXX-XZX8
XXXX-XXXX-XZX9
XXXX-XXXX-X0XA
(...)
XXXX-XXXX-X2XA
XXXX-XXXX-X2XB
I know hoe to make it with one "_".
string alphaLetters = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789ABCDEF";
foreach (char letter in alphaLetters.ToCharArray())
{
Numbers.Add(number.Replace('_', letter)));
}
I want this code to be working with unknown number of "_".
Can you help?
IMHO it must be recursive. (Note: that does not mean it must use recursive method call, although I used recursive call in the following code, it can be easily converted to internal recursion stack. )
public static void RunSnippet()
{
var r = new List<string>();
Replace("asd_asd_asd_".ToCharArray(), 0, r);
foreach(var s in r) { Console.WriteLine(s); }
}
public static char[] possibilities = new char[] { 'A', 'B', 'C' };
public static void Replace(char[] chars, int startIndex, IList<string> result)
{
for (int i = startIndex; i < chars.Length; i++)
{
if (chars[i] != '_')
{
continue;
}
// we found first '_'
for (int j = 0; j < possibilities.Length; j++)
{
chars[i] = possibilities[j];
Replace(chars, i + 1, result);
}
chars[i] = '_'; // take back what we replaced
return; //we're done here
}
// we didn't find any '_', so all were replaced and we have result:
result.Add(new string(chars));
}
Try this one:
var alphaIndexes = new List<int>();
string alphaLetters = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789ABCDEF";
for(int n = 0; n<Numbers.Count; n++) {
char[] numberLetters = Numbers[n].ToCharArray();
int position = 0;
for(int i = numberLetters.Length - 1; i>=0; i--) {
if(numberLetters[i] == '_') {
int alphaIndex = 0;
if(alphaIndexes.Count <= position)
alphaIndexes.Add(0);
else {
alphaIndex = alphaIndexes[position];
}
numberLetters[i] = alphaLetters[alphaIndex];
position++;
}
}
if(alphaIndexes.Count > 0) {
alphaIndexes[0]++;
for(int j = 0; j < alphaIndexes.Count; j++) {
if(alphaIndexes[j] >= alphaLetters.Length) {
alphaIndexes[j] = 0;
if (j < alphaIndexes.Count)
alphaIndexes[j+1]++;
}
}
}
Numbers[n] = new String(numberLetters);
Numbers[n].Dump();
}