I have written the following code in an effort to try and compute the values down there below, but all my arrays do not work; especially the ones in the for loops. Can someone help teach me how to declare an array inside a loop? They keep showing errors like "Did you miss declaring a new object?"
Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public class seasonal
{
public float mTotal;
public float movingAverage;
public int y;
public char quarter;
public char ssq;
public int rank;
public float forecast;
public float centralMovingAverage;
public float cmTotal;
public float sSeasonal;
}
public static int i;
public static int j;
public static int k = 0;
public static int n;
static void Main(string[] args)
{
int x; int r; int m; int c; int u = 0;
seasonal temp = new seasonal();
int n1; int n2; int n3; int n4; int sumr1 = 0; int sumr2 = 0; int sumr3 = 0; int sumr4 = 0;
float h; float ss; float sum; float sums1 = 0; float sums2 = 0; float sums3 = 0; float sums4 = 0; float tsums;
Console.WriteLine("Enter the no. of observations");
string nObservations = Console.ReadLine();
n = Convert.ToInt32(nObservations);
seasonal[] seasonal = new seasonal[n];
seasonal[] s = new seasonal[n];
for (i = 0; i < n; i++)
{
Console.Write("{0:D}:", (i+1) );
string value = Console.ReadLine();
int observation = Convert.ToInt32(value);
seasonal thisSeasonal = new seasonal();
thisSeasonal.y = observation;
seasonal[i] = thisSeasonal;
if (i>=0 && i<3)
{
seasonal[i].quarter = '1';
}
if (i>=3 && i<6)
{
seasonal[i].quarter = '2';
}
if (i>=6 && i<9)
{
seasonal[i].quarter = '3';
}
if (i>=9 && i<12)
{
seasonal[i].quarter = '4';
}
if (i>12)
{
r = i % 12;
if (r>=0 && r<3)
{
seasonal[i].quarter = '1';
}
if (r>=3 && r<6)
{
seasonal[i].quarter = '2';
}
if (r>=6 && r<9)
{
seasonal[i].quarter = '3';
}
if (r>=9 && r<12)
{
seasonal[i].quarter = '4';
}
}
for (i = k; i < n-3; i++)
{
sum = 0;
for (j = u+k; j < 4+k; j++)
{
sum += seasonal[j].y;
seasonal[i].mTotal = sum;
seasonal[i].movingAverage = seasonal[i].mTotal / 4;
Console.Write("{0:f}", seasonal[i].movingAverage);
k++;
}
}
for ( i = 0; i < (n-4); i++)
{
ss = 0;
for (j = 0; j < (2+i); j++)
{
ss += seasonal[j].movingAverage;
}
seasonal[i].cmTotal = ss;
seasonal[i].centralMovingAverage = seasonal[i].cmTotal / 2;
seasonal[i].sSeasonal = (seasonal[i+2].y)/(seasonal[i].centralMovingAverage);
if (i == 0 || i % 4 == 0)
{
seasonal[i].ssq = '3';
}
if (i == 1 || i % 4 == 1)
{
seasonal[i].ssq = '4';
}
if (i == 2 || i % 4 == 2)
{
seasonal[i].ssq = '1';
}
if (i == 3 || i % 4 == 3)
{
seasonal[i].ssq = '2';
}
Console.Write("\n{0:f}", seasonal[i].centralMovingAverage);
Console.Write("\n {0:f}", seasonal[i].sSeasonal);
}
}
for (m= 0; m < n; m++)
{
s[m] = seasonal[m];
}
for ( i = 0; i < (n-5); i++)
{
for ( j = 0; j < (n-4); j++)
{
if (s[i].sSeasonal > s[j].sSeasonal)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
for ( k = 0; k < (n-4); k++)
{
s[k].rank = k + 1;
Console.Write("\n\t {0:D}", s[k].rank);
}
for ( i = 0; i < (n-4); i++)
{
if (s[i].ssq == '1')
{
sumr1 += s[i].rank;
sums1 += s[i].sSeasonal;
//n1 ++;
}
if (s[i].ssq == '2')
{
sumr2 += s[i].rank;
sums2 += s[i].sSeasonal;
//n2++;
}
if (s[i].ssq == '3')
{
sumr3 += s[i].rank;
sums3 += s[i].sSeasonal;
//n3++;
}
if (s[i].ssq == '4')
{
sumr4 += s[i].rank;
sums4 += s[i].sSeasonal;
//n4++;
}
}
tsums = ((sums1/4)+(sums2/4)+(sums3/4)+(sums4/4));
Console.Write("\n\n\n{0:f}",tsums);
Console.Write("\n\n\n\n\n{0:D}",sumr1);
Console.Write("\n\n\n\n{0:D}",sumr2);
Console.Write("\n\n\n\n{0:D}",sumr3);
Console.Write("\n\n\n\n\n{0:D}",sumr4);
Console.Write("\n{0:f}",sums1/4);
Console.Write("\n\n{0:f}",sums2/4);
Console.Write("\n\n{0:f}",sums3/4);
Console.Write("\n\n{0:f}",sums4/4);
Console.Write("\n{0:f}",((sums1/4)/tsums)*4);
Console.Write("\n\n{0:f}",((sums2/4)/tsums)*4);
Console.Write("\n\n{0:f}",((sums3/4)/tsums)*4);
Console.Write("\n\n{0:f}",((sums4/4)/tsums)*4);
}
}
}
You need to initialise the objects in your arrays:
Seasonal[] seasonal = new Seasonal[n];
for (int l = 0; l < seasonal.Length; l++)
{
seasonal[l] = new Seasonal();
}
Seasonal[] s = new Seasonal[n];
for (int l = 0; l < s.Length; l++)
{
s[l] = new Seasonal();
}
This only solves the initialisation problem, though. You may want to look at naming conventions for readability, and then the index off by 1 you'll experience at roughly line 105.
instead of working with
seasonal[] seasonal = new seasonal[n];
seasonal[] s = new seasonal[n];
do work with
seasonal[] s1 = new seasonal[n];
seasonal[] s2 = new seasonal[n];
But when I see code like, this, where you just copy your array:
for (m= 0; m < n; m++)
{
s[m] = seasonal[m];
}
why would you do that? copy the entire array instead of every single entry..
why do you not use any c# constructs?
The problem is this line:
sum += seasonal[j].y;
But there isn't a simple fix. You are creating each object individually through the loop instead of before you enter the loop so each iteration is looking at null objects. Also, the loop this line is in reads past the end of the array. The code is a bit complex to easily see what you're trying to do and how to fix it.
Just an example for to simplify some of your code:
you wrote the following:
if (i>=0 && i<3)
{
seasonal[i].quarter = '1';
}
if (i>=3 && i<6)
{
seasonal[i].quarter = '2';
}
if (i>=6 && i<9)
{
seasonal[i].quarter = '3';
}
if (i>=9 && i<12)
{
seasonal[i].quarter = '4';
}
if (i>12)
{
r = i % 12;
if (r>=0 && r<3)
{
seasonal[i].quarter = '1';
}
if (r>=3 && r<6)
{
seasonal[i].quarter = '2';
}
if (r>=6 && r<9)
{
seasonal[i].quarter = '3';
}
if (r>=9 && r<12)
{
seasonal[i].quarter = '4';
}
}
you could write that instead:
if(i >= 0)
seasonal[i].quarter = (((i % 12)/3) + 1).ToString();
I don' think this code
seasonal[] seasonal = new seasonal[n];
seasonal[] s = new seasonal[n];
is correct. Try
seasonal[] seas = (seasonal[])Array.CreateInstance(typeof(seasonal), n);
Related
I need make symmetric letter “W” in string Array
get_w() Is method that should return string array that contains letter "W"
get_w(5) # should return:
public string[] GetW(int h)
{
if (h < 2) return new string[h];
int row = 0;
int stars_number = h * 4 - 3;
int times = 0;
StringBuilder[] c = new StringBuilder[h];
for(int a = 0; a < h; a++)
{
c[a] = new StringBuilder();
c[a].Length = stars_number;
}
for (int i = 0; i < stars_number; i++)
{
if (i == h - 1) times = 1;
if (i == stars_number-2 * h + 1) times = 2;
if (i == stars_number - h) times = 3;
c[row][i] = '*';
if (row < h - 1 && (times == 0 || times == 2))
{
row += 1;
}
else
{
row -= 1;
}
}
string []str = new string[h];
for(int i = 0; i < h; i ++)
{
str[i] = c[i].ToString();
}
return str;
}
if I compile it in a VS i get no errors.Here is an example of the result
This task is taken from the Codewars
but if I try to test on Codewars with the code I described above, I get this error
Edited:I changed returning array with "h" length to empty array and had got this
i found the task solution by replacing charters that equal '\0' with character ' '
here is working code
public string[] GetW(int h)
{
if (h < 2) return new string[]{};
int row = 0;
int stars_number = h * 4 - 3;
int times = 0;
StringBuilder[] c = new StringBuilder[h];
for(int a = 0; a < h; a++)
{
c[a] = new StringBuilder();
c[a].Length = stars_number;
}
for (int i = 0; i < stars_number; i++)
{
if (i == h - 1) times = 1;
if (i == stars_number-2 * h + 1) times = 2;
if (i == stars_number - h) times = 3;
c[row][i] = '*';
if (row < h - 1 && (times == 0 || times == 2))
{
row += 1;
}
else
{
row -= 1;
}
}
string []str = new string[h];
for(int i = 0; i < h; i ++)
{
c[i].Replace('\0', ' ');
str[i] = c[i].ToString();
}
return str;
}
And here is result of test
This program calculates the expected number of toin cosses until a given sequence will appear. The formula sums powers of two, where powers are those k for which the first k elements of the sequence match the last k elements, in order.
My question is why, when I test it with two different sequences, it only returns one result twice. I assume that it is doing exactly what it looks like and overwriting test1 with test4 when test4 is instanciated, but this code looks to me to be similar to code from smaller exercises that did not have this overwriting behaviour.
This is my second programming course, and my first in C#, neither has been in my mother tongue, so I might be a bit slow with some of the concepts.
I suspect this has to do with one of the lines with public static... (I am not sure how to refer to them) or maybe a protection level. The expectation for test1 should be 38 (2 + 2^2 + 2^5).
using System;
namespace CSProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Expectation tests");
PlayerSequence test1 = new PlayerSequence("bc00100");
PlayerSequence test4 = new PlayerSequence("101101");
Console.WriteLine("Expectation of test1 bc00100");
Console.WriteLine (test1.Expectation ());
Console.WriteLine("Expectation of test4 101101");
Console.WriteLine(test4.Expectation());
}
}
class PlayerSequence
{
//ATTRIBUTES
private static bool[] sequence;
//CONSTRUCTORS
public PlayerSequence()
{
}
public PlayerSequence(string sequence_String)//Seems to work!!
{
char[] sequence_array = sequence_String.ToCharArray();
int inputLength = sequence_array.Length;
int sequence_length = 0;
for( int i = 0; i < inputLength; i++) {
if (sequence_array[i] == '1' || sequence_array[i] == '0') {
sequence_length++;
}
}
sequence = new bool[sequence_length];///KEYItem
int input_index_adjustment = 0;
for (int i = 0; i < inputLength; i++) {
int sVal;
if (!Int32.TryParse(sequence_String[i].ToString(), out sVal))
{
input_index_adjustment++;
continue;
}
if (sVal == (Int32)1)
PlayerSequence.sequence[i - input_index_adjustment] = true;
if (sVal == (Int32)0)
PlayerSequence.sequence[i - input_index_adjustment] = false;
if(sVal != 1 && sVal != 0)
input_index_adjustment++;
}
}
public override string ToString()//Works
{
string retString;
retString = "";
for (int i = 0; i < sequence.Length;i++) {
if (sequence[i] == true) retString = retString + "T ";
else retString = retString + "H ";
}
return retString;
}
public ulong Expectation(){
ulong espTA = 0;
for (int kexp = 0; kexp < /*PlayerSequence.*/sequence.Length; kesp++)
{
if(SeqCheck(sequence,kesp+1))
expTA = expTA + (ulong)Math.Pow(2, kexp+1);
}
return espTA;
}//end Expectation
public static bool SeqCheck(bool[] toCheck, int k){
//Test of required property for each power of 2 here k
int a = toCheck.Length ;
bool seqgood = false;
bool[] checkStart = new bool[k];
bool[] checkEnd = new bool[k];
for (int i = 0; i < k; i++) {//loop sets up subarrays to compare
checkStart[i] = toCheck[i];
checkEnd[i] = toCheck[a - k + i];
}
for (int i = 0; i < k; i++){//loop does comparison
if(checkStart[i] != checkEnd[i])
{
seqgood = false;
break;
}
seqgood = true;
}
return seqgood;
}//end SeqCheck
}//end PlayerSequence class
}//End this section of the namespace
It is your use of the static keyword for the local variable in your class. By doin so, you make the variable a part of the type (PlayerSequence) and not the instance of PlayerSequence (test1, test4). Below worked on my machine.
class PlayerSequence
{
//ATTRIBUTES
private bool[] sequence;
//CONSTRUCTORS
public PlayerSequence()
{
}
public PlayerSequence(string sequence_String)//Seems to work!!
{
char[] sequence_array = sequence_String.ToCharArray();
int inputLength = sequence_array.Length;
int sequence_length = 0;
for (int i = 0; i < inputLength; i++)
{
if (sequence_array[i] == '1' || sequence_array[i] == '0')
{
sequence_length++;
}
}
sequence = new bool[sequence_length];///KEYItem
int input_index_adjustment = 0;
for (int i = 0; i < inputLength; i++)
{
int sVal;
if (!Int32.TryParse(sequence_String[i].ToString(), out sVal))
{
input_index_adjustment++;
continue;
}
if (sVal == (Int32)1)
sequence[i - input_index_adjustment] = true;
if (sVal == (Int32)0)
sequence[i - input_index_adjustment] = false;
if (sVal != 1 && sVal != 0)
input_index_adjustment++;
}
}
public override string ToString()//Works
{
string retString;
retString = "";
for (int i = 0; i < sequence.Length; i++)
{
if (sequence[i] == true) retString = retString + "T ";
else retString = retString + "H ";
}
return retString;
}
public ulong Expectation()
{
ulong espTA = 0;
for (int kexp = 0; kexp < sequence.Length; kexp++)
{
if (SeqCheck(sequence, kexp + 1))
espTA = espTA + (ulong)Math.Pow(2, kexp + 1);
}
return espTA;
}//end Expectation
public bool SeqCheck(bool[] toCheck, int k)
{
//Test of required property for each power of 2 here k
int a = toCheck.Length;
bool seqgood = false;
bool[] checkStart = new bool[k];
bool[] checkEnd = new bool[k];
for (int i = 0; i < k; i++)
{//loop sets up subarrays to compare
checkStart[i] = toCheck[i];
checkEnd[i] = toCheck[a - k + i];
}
for (int i = 0; i < k; i++)
{//loop does comparison
if (checkStart[i] != checkEnd[i])
{
seqgood = false;
break;
}
seqgood = true;
}
return seqgood;
}//end SeqCheck
}
So Im making tetris and I need to make 7 blocks. The problem is is that I have to copy paste the code in 7 different classes(and then changing the grid) so I thought maybe using subclass would be much easier. The problem is I dont know how to do that.
this is my general block class:
public class Block
{
Color Color;
const int x = 4;
const int y = 4;
bool[,] vorm;
Texture2D block;
float FallTimer;
public bool FallingBlock = false;
Random Random = new Random();
ZBlock zBlock = new ZBlock();
TBlock tBlock = new TBlock();
SBlock sBlock = new SBlock();
OBlock oBlock = new OBlock();
JBlock jBlock = new JBlock();
LBlock lBlock = new LBlock();
IBlock iBlock = new IBlock();
public void HandleInput()
{
if (Tetris.inputHelper.KeyPressed(Keys.Down))
{
FallTimer = 0;
for (int i = 0; i < blokvorm.GetLength(0); i++)
{
for (int j = 0; j < blokvorm.GetLength(1); j++) ;
// blokvorm[i, j] += 15;
}
}
}
public void speed(GameTime gameTime)
{
double SpeedCounter = 3;
int LevelCounter = 1;
if (LevelCounter < Tetris.GameWorld.level)
{
SpeedCounter -= 0.5;
LevelCounter++;
}
FallTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (Math.Round(FallTimer, 1) == SpeedCounter)
{
FallTimer = 0;
//BlockPosition.Y += 15;
}
}
public bool[,] blokvorm
{
get
{
vorm = new bool[x, y];
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
{
vorm[i, j] = false;
}
int r = Random.Next(7);
if (r == 0)
{
vorm = ZBlock.zblock();
}
else if (r == 1)
{
vorm = TBlock.tblock();
}
else if (r == 2)
{
vorm = SBlock.sblock();
}
else if (r == 3)
{
vorm = OBlock.oblock();
}
else if (r == 4)
{
vorm = JBlock.jblock();
}
else if (r == 5)
{
vorm = LBlock.lblock();
}
else if (r == 6)
{
vorm = IBlock.iblock();
}
return vorm;
}
}
public TBlock TBlock
{
get { return tBlock; }
}
public ZBlock ZBlock
{
get { return zBlock; }
}
public SBlock SBlock
{
get { return sBlock; }
}
public OBlock OBlock
{
get { return oBlock; }
}
public JBlock JBlock
{
get { return jBlock; }
}
public LBlock LBlock
{
get { return lBlock; }
}
public IBlock IBlock
{
get { return iBlock; }
}
public void Draw(SpriteBatch spriteBatch, ContentManager Content)
{
block = Content.Load<Texture2D>("Block");
spriteBatch.Begin();
if (!FallingBlock)
{
for (int i = 0; i < blokvorm.GetLength(0); i++)
{
for (int j = 0; j < blokvorm.GetLength(1); j++)
if (blokvorm[i, j])
spriteBatch.Draw(block, new Vector2(30 + (i * 15), 30 + (j * 15)), Color.White);
}
spriteBatch.End();
}
}
}
}
So How can I use this class to create other 7 block classes(T, L, I, O etc) easily?
Edit: My block all looks like this:
{
const int x = 4;
const int y = 4;
public bool[,] tblock()
{
vorm = new bool[x, y];
for (int i = 0; i < x; i++)
for (int j = 0; j <y; j++)
{
vorm[i, j] = false;
vorm[0, 1] = true;
vorm[1, 1] = true;
vorm[1, 0] = true;
vorm[2, 1] = true;
}
Color = Color.Indigo;
return vorm;
}
public void RotationLinks(InputHelper inputhelper)
{
bool[,] nieuw = new bool[x, y];
if (inputhelper.KeyPressed(Keys.Left))
{
for (int a = 0; a < 4; ++a)
for (int b = 0; b < 4; ++b)
nieuw[a, b] = vorm[x - a - 1, b];
vorm = nieuw;
}
}
}
}
So to make other 6 I copied theh whole code and change the grid value. Is there a possible way to make it easier using bock class?
Here's the part 1 of my question, if you wanna check the background of this question :
Detecting brackets in input string
Forgive me if the title doesn't match, since I also confused how to name it appropriately to picture my problem. If anyone knows a more appropriate title, feel free to edit.
So, given below code (my own code) :
private const int PARTICLE_EACH_CHAR = 4;
/*ProcessBarLines : string s only contains numbers, b, [, and ]*/
private int ProcessBarLines(Canvas canvas, string s, int lastLineAboveNotation)
{
List<int> bracket = new List<int>();
List<int> other = new List<int>();
int currentCloseNumber = 0;
int currentOpenNumber = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '[')
{
bracket.Add(i);
currentOpenNumber++;
if (i - 1 > 0 && s[i - 1] != '[')
{
currentOpenNumber = 1;
}
}
else if (s[i] == ']')
{
bracket.Add(i);
currentCloseNumber++;
if (i + 1 >= s.Length || s[i + 1] != ']' || currentOpenNumber == currentCloseNumber)
{
int min = bracket.Count - (currentCloseNumber * 2);
int max = bracket[bracket.Count - 1];
List<int> proc = new List<int>();
int firstIndex = -1;
int lastIndex = -1;
for (int ii = 0; ii < other.Count; ii++)
{
if (other[ii] > min && other[ii] < max)
{
proc.Add(other[ii]);
if (firstIndex == -1)
{
firstIndex = ii;
lastIndex = ii;
}
else
{
lastIndex = ii;
}
}
}
double leftPixel = firstIndex * widthEachChar;
double rightPixel = (lastIndex * widthEachChar) + widthEachChar;
DrawLine(canvas, currentCloseNumber, leftPixel,
rightPixel, lastLineAboveNotation * heightEachChar / PARTICLE_EACH_CHAR);
lastLineAboveNotation += currentCloseNumber - 1;
currentOpenNumber -= currentCloseNumber;
currentCloseNumber = 0;
}
}
else
{
other.Add(i);
}
}
return lastLineAboveNotation + 1;
}
Here's the test cases :
Picture 1 & 2 is the correct answer, and picture 3 is the wrong answer. Picture 3 should have a line, just like inverted from number 2, but, apparently, (if you look closely) the line is drawn on the right, but it should be on the left to be correct (above 0).
I figured, the problem is, I'm quite sure on the "min". Since it doesn't give the correct starting value.
Any idea on this? Feel free to clarify anything. It's used for writing numeric musical scores.
Btw, DrawLine() just meant to draw the line above the numbers, it's not the problem.
Finally! I found it!
private int ProcessBarLines(Canvas canvas, string s, int lastLineAboveNotation)
{
List<int> bracket = new List<int>();
List<int> other = new List<int>();
int currentCloseNumber = 0;
int currentOpenNumber = 0;
int space = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '[')
{
bracket.Add(i);
currentOpenNumber++;
if (i - 1 > 0 && s[i - 1] != '[')
{
currentOpenNumber = 1;
}
}
else if (s[i] == ']')
{
bracket.Add(i);
currentCloseNumber++;
if (i + 1 >= s.Length || s[i + 1] != ']' || currentOpenNumber == currentCloseNumber)
{
int min = bracket[Math.Max(bracket.Count - ((currentCloseNumber * 2) + space), 0)];
int max = bracket[bracket.Count - 1];
space = max - min - 1;
List<int> proc = new List<int>();
int firstIndex = -1;
int lastIndex = -1;
for (int ii = 0; ii < other.Count; ii++)
{
if (other[ii] > min && other[ii] < max)
{
proc.Add(other[ii]);
other[ii] = -1;
if (firstIndex == -1)
{
firstIndex = ii;
lastIndex = ii;
}
else
{
lastIndex = ii;
}
}
}
double leftPixel = firstIndex * widthEachChar;
double rightPixel = (lastIndex * widthEachChar) + widthEachChar;
DrawLine(canvas, currentCloseNumber, leftPixel,
rightPixel, lastLineAboveNotation * heightEachChar / PARTICLE_EACH_CHAR);
lastLineAboveNotation += 1;
currentOpenNumber -= currentCloseNumber;
currentCloseNumber = 0;
}
}
else
{
other.Add(i);
}
}
return lastLineAboveNotation + 1;
}
If someone got a more efficient code, please let us know!
There is an error with that string.compiler thingy and i dont know what to do. i really need some help please
char[] valWord = new char[100];
Console.WriteLine(textBox1.Text);
valWord = textBox1.Text;
int beg = 0;
int val = 0;
int value = 0;
for (int i = 0; i < 100; i++)
{
if (valWord[i] == ' ' || valWord[i] == '\0')
{
char[] temp = new char[100];
for (int j = 0; j < i - beg; j++)
{
temp[j] = valWord[beg + j];
}
temp[i - beg] = '\0';
//there is an error in this if statement: String.Compare
if (String.Compare(temp, "thousand") == 0)
{
value += (val*1000);
val = 0;
}
else if (String.Compare(temp, "hundred") == 0)
{
value += (val*100);
val = 0;
}
else if (String.Compare(temp, "one") == 0)
{
val = 1;
}
else if (String.Compare(temp, "two") == 0)
{
val = 2;
}
if (valWord[i] == '\0')
{
value += val;
break;
}
}
Console.WriteLine(textBox2.Text);
}
else
{
_list.Add(name, new GenericList());
}
You can't compare a string to a char array. They are different types.
Use if (string.Equals(new string(temp),"thousand")) instead.
As per MSDN, there is no such function overload defined for String.Compare