Fibonnacci sequence using Arrays and For Loops - c#

This program is to create a wave like structure using C# with the fibonnaci sequence and arrays. With the number of the sequence being at the end and asterisks equaling what number is on the current line in front. This is all done using the For loops and having the upper limiter done by the Array, I solve that limiter problem by using the .Length aspect of Arrays but I don't grasp the concept of how to properly use the array within this sequence.
This first part of code I have the sequence building up using my array with 12 index as I only need the 11 first fibonacci sequences.
The problem I am running into is within the second part of the code.
class Program
{
static void Main(string[] args)
{
int a = 0, b = 1;
int[] fibArray = new int[12];
fibArray[0] = 0;
fibArray[1] = 1;
Console.WriteLine("0");
Console.WriteLine("*1");
for (int i = 3; i <= fibArray.Length; i++)
{
fibArray[i] = a + b;
a = b;
b = fibArray[i];
for(int y = 1; y <= fibArray[i]; y++)
{
Console.Write("*");
}
Console.Write("" + fibArray[i]);
Console.WriteLine();
}
With this second part of code I am unable to get it to register and output the sequence. Mostly I am unsure of how to properly set up my array to ensure that the fibonacci sequence is able to go reverse as well. I understand the sequence is typically f(n)=f(n-1)+f(n-2), I cannot wrap my head around how to properly use arrays in this context.
for (int p = fibArray[11]; p >= fibArray.Length; p--)
{
for (int k = 1; k <= p; k++)
{
Console.Write("*");
}
Console.Write(""+ b);
Console.WriteLine();
}
}
}
}
Sorry for ranting, just trying to explain the code as a whole but to give a sum of what I am asking about.
It would be how to use the Arrays, what I did wrong with my current code, and what aspect I could use to control the loops using the Array itself.
To give an overall example of the desired output it would be like so:
0
*1
*1
**2
***3
***3
**2
*1
*1
0

Some things to note about your original code. You manually set the first two values in the sequence at elements 0 and 1, but then skipped over element 2 and started from element 3. Your loop was including the length of the array as valid index when it should start at (array length - 1) since arrays are zero based in .Net.
You can output the correct length of asterisks by using this string constructor.
I'd separate the generation of the sequence from the output:
static void Main(string[] args)
{
// building the Fibonacci sequence (no output at this time)
int[] fibArray = new int[12];
for (int i = 0; i < fibArray.Length; i++)
{
switch (i)
{
case 0:
fibArray[i] = 0;
break;
case 1:
fibArray[i] = 1;
break;
default:
fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
break;
}
}
// increasing curve
for (int i = 0; i < fibArray.Length; i++)
{
Console.WriteLine(new String('*', fibArray[i]) + fibArray[i].ToString());
}
// decreasing curve
for (int i = (fibArray.Length-1); i >= 0; i--)
{
Console.WriteLine(new String('*', fibArray[i]) + fibArray[i].ToString());
}
Console.WriteLine();
Console.Write("Press Enter to Quit");
Console.ReadLine();
}
Output:
0
*1
*1
**2
***3
*****5
********8
*************13
*********************21
**********************************34
*******************************************************55
*****************************************************************************************89
*****************************************************************************************89
*******************************************************55
**********************************34
*********************21
*************13
********8
*****5
***3
**2
*1
*1
0
Press Enter to Quit

Related

Increasing sequence in one dimensional array

You're given an array of integers,in case if you see subsequence in which each following bigger than the previous on one(2 3 4 5) you have to rewrite this subsequence in the resulting array like this 2 - 5 and then the rest of the array. So in general what is expected when you have 1 2 3 5 8 10 11 12 13 14 15 the output should be something like 1-3 5 8 10-15.
I have my own idea but can't really implement it so all I managed to do is:
static void CompactArray(int[] arr)
{
int[] newArr = new int[arr.length];
int l = 0;
for (int i = 0,k=1; i <arr.length ; i+=k,k=1) {
if(arr[i+1]==arr[i]+1)
{
int j = i;
while (arr[j+1]==arr[j]+1)
{
j++;
k++;
}
if (k>1)
{
}
}
else if(k==1)
{
newArr[i] = arr[i];
}
}
In short here I walk through the array and checking if next element is sum of one and previous array element and if so I'm starting to walk as long as condition is true and after that i just rewriting elements under indices and then move to the next.
I expect that people will help me to develop my own solution by giving me suggestions instead of throwing their own based on the tools which language provides because I had that situation on the russian forum and it didn't help me, and also I hope that my explanation is clear because eng isn't my native language so sorry for possible mistakes.
If I understand the problem correctly, you just need to print the result on the screen, so I'd start with declaring the variable which will hold our result string.
var result = string.Empty
Not using other array to store the state will help us keep the code clean and much more readable.
Let's now focus on the main logic. We'd like to loop over the array.
for (int i = 0; i < array.Length; i++)
{
// Let's store the initial index of current iteration.
var beginningIndex = i;
// Jump to the next element, as long as:
// - it exists (i + 1 < array.Length)
// - and it is greater from current element by 1 (array[i] == array[i+1] - 1)
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
// If the current element is the same as the one we started with, add it to the result string.
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
// If it is different element, add the range from beginning element to the one we ended with.
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
All that's left is printing the result:
Console.WriteLine(result)
Combining it all together would make the whole function look like:
static void CompactArray(int[] array)
{
var result = string.Empty;
for (int i = 0; i < array.Length; i++)
{
var beginningIndex = i;
while (i + 1 < array.Length && array[i] == array[i+1] - 1)
{
i++;
}
if (i == beginningIndex)
{
result += $"{array[i]} ";
}
else
{
result += $"{array[beginningIndex]}-{array[i]} ";
}
}
Console.WriteLine(result);
}

Longest Ascending Sequence C#

So I am quite new to C# and having face a problem which requires me to:
Search the longest ascending sequence of integers in an array of integers. As sequence of elements xi (1 ≤ i ≤ n) is ascending if xi < xi+1 for all i (1 ≤ i ≤ n - 1). The size of the array is to be chosen by the user. Values of the array are random numbers are between 0 and 1000 generated by the computer. The program shall print the start index and the length of the longest ascending sequence.
Here are my code so far (I can only sort array in ascending order):
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace AscendingSequences
{
class AscendingSequences
{
public static void Main(string[] args)
{
Console.WriteLine("Ascending Sequence!");
GenerateNumber();
}
public static void GenerateNumber()
{
int i, j, n, number;
int[] array = new int[100];
int[] array1 = new int[100];
Random random = new Random();
Console.Write("\nInput the number of element to be store in the array: ");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("\nThe {0} array is generating-----\n", n);
for (i = 0; i < n; i++)
{
array[i] = random.Next(1, 20);
Console.Write("\nThe array|{0}| is {1} ", i, array[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(array[j] < array[i])
{
number = array[i];
array[i] = array[j];
array[j] = number;
}
}
}
Console.Write("\nElements of array in sorted ascending order is: ");
for(i=0; i<n;i++)
{
Console.Write("{0} ", array[i]);
}
}
}
}
This is the assignment given to me:
your approach to first order the array was wrong and that caused some people to be confused unfortunately.
if you start by ordering your array you lose the information of the original location of these elements which are important. Instead you should loop through your array and do a check if the current element is bigger than the previous one(ascending).
//start and length are the "current" values and max are the max found
int start = 0, length = 0, maxstart = 0, maxlength = 0;
//loop through array (starting from index 1 to avoid out of bounds)
for (int i = 1; i < array.Length; i++)
{
//check if current sequence is longer than previously recorded
if (length > maxlength)
{
maxstart = start;
maxlength = length;
}
//if previous element <= to current element
if (array[i - 1] <= array[i])
{
//if the current element isn't part of the current sequence, then start a new sequence
if (start + length < i)
{
start = i - 1;
length = 2;
}
else
{
//count the length
length++;
}
}
}
Here is a .net fiddle with working code:
https://dotnetfiddle.net/1GLmEB
EDIT:
to reply to your question in the comments on how this works start + length < i
This condition checks if the current value is part of the sequence.
The variable start is the start of the last/current found sequence and length is the length.
When this condition returns true it means it falls outside the last found sequence and it resets the values of start and length(true = outside, false = inside)
So lets go through some cases and see why this works:
1 2 3 1 1 2 3 1 1
* > > > e ^
start = 3 (*)
length = 4 (>)
i = 8 (^)
3+4 = e
3+4<8 //true : new sequence
so the last found sequence started at 3 and was 4 long.
this means that this sequence will end at index 7.
since we are currently checking for index 8 in our loop we can see that it isn't part of the same sequence.
1 2 3 1 1 2 3 4 1
* > > > > ê
start = 3 (*)
length = 5 (>)
i = 8 (^)
3+4 = e
3+5<8 //false : current sequence
so the last found sequence started at 3 and was 5 long.
this means that this sequence will end at index 8.
since we are currently checking for index 8 in our loop we can see that it is part of the same sequence.
in hindsight it might have been less confusing if this if statement was turned around (true = inside, false = outside). However I won't change the code now to avoid further confusion.

Why does my C# code does not work as intended (arrays transformation, newbie)

I'm trying to take array of numbers (0 or 1 only) and repeatedly transform it as follows:
first and last numbers are always 0;
all the other numbers are
derived from previous state of array: if array[n] and its two neighbours
(array[n-1], array[n] and array[n+1]) have the same value (three 0s or three 1s) then newarray[n] should be be 1, otherwise it should be 0 (that produces nice patterns).
For example, if the array size is 10 and it starts with all zeroes, then program should output this:
0000000000
0111111110
0011111100
0001111000
0100110010
0000000000
0111111110
...and so on
I wrote a code that should do this and it doesn't work as intended. It always does first transformation perfectly but then begins some wrong, asymmetric, crazy stuff:
0000000000
0111111110
0000000000
0101010100
0000000010
0101010000
What makes my code behave the way it does?
Here is the code:
namespace test
{
class Program
{
public static void Main(string[] args)
{
const int leng = 10; //length of array
int[] arrayone = new int[leng];
int[] arraytwo = new int[leng];
for (int i = 0; i<=leng-1; i++)
{
arrayone[i] = 0;
arraytwo[i] = 0;
} //making two arrays and filling them with zeroes
for (int i = 0; i<=leng-1; i++)
{
Console.Write(arrayone[i]);
}
Console.WriteLine(' '); //printing the first state of array
for (int st=1; st<=16; st++) //my main loop
{
arraytwo[0]=0;
arraytwo[leng - 1]=0; //making sure that first and last elements are zero. I'm not sure I need this since I fill both arrays with zeroes in the beginning. But it probably doesn't hurt?
for (int i = 1; i<=leng-2; i++) //calculating new states for elements from second to second-to-last
{
if (((arrayone[i-1]) + (arrayone[i]) + (arrayone[i+1]) == 0) | ((arrayone[i-1]) + (arrayone[i]) + (arrayone[i+1]) == 3) == true)
arraytwo[i] = 1;
else
arraytwo[i] = 0;
}
//by now arraytwo contains transformed version of arrayone
for (int i = 0; i<=leng-1; i++)
{
Console.Write(arraytwo[i]);
} //printing result
arrayone = arraytwo; //copying content of arraytwo to arrayone for the next round of transformation;
Console.WriteLine(' ');
}
Console.Write(" ");
Console.ReadKey(true);
}
}
}
Tweakable version: https://dotnetfiddle.net/8htp9N
As pointed out you're talking an object and working on it, at the end of that you're assigning the reference not the values. one way to combat that would be
for your line: arrayone = arraytwo;
change it to : arrayone = (int[])arraytwo.Clone();
this will copy the values - for integers this will be sufficient.
Please, notice how your current code is complex and thus diffcult to debug. Make it simpler, extract a method:
using System.Linq;
...
private static IEnumerable<int[]> Generate(int width) {
int[] item = new int[width];
while (true) {
yield return item.ToArray(); // .ToArray() - return a copy of the item
int[] next = new int[width];
for (int i = 1; i < item.Length - 1; ++i)
if (item[i - 1] == item[i] && item[i] == item[i + 1])
next[i] = 1;
item = next;
}
}
Then you can put
public static void Main(string[] args) {
var result = Generate(10) // each line of 10 items
.Take(7) // 7 lines
.Select(item => string.Concat(item));
Console.Write(string.Join(Environment.NewLine, result));
}
Outcome:
0000000000
0111111110
0011111100
0001111000
0100110010
0000000000
0111111110

When arrays go awry?

I'm trying to learn C# by solving mathematical problems. For example, I'm working on finding the sum of factors of 3 or 5 in the first 1000 positive numbers. I have the basic shell of the code laid out, but it isn't behaving how I'm expecting it to.
Right now, instead of getting a single output of 23, I am instead getting 1,1,3,3,5,5,7,7,9,9. I imagine I messed up the truncate function somehow. Its a bloody mess, but its the only way I can think of checking for factors. Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
using System;
namespace Problem1
{
class Problem1
{
public static void Main()
{
//create a 1000 number array
int[] numberPool = new int[10];
//use for loop to assign the first 1000 positive numbers to the array
for (int i = 0; i < numberPool.Length; i++)
{
numberPool[i] = i + 1;
}
//check for factors of 3 or 5 using if/then statment
foreach (int i in numberPool)
if ((i / 3) == Math.Truncate((((decimal)(i / 3)))) || ((i / 5) == Math.Truncate(((decimal)(i / 5)))))
{
numberPool[i] = i;
}
else
{
numberPool[i] = 0;
}
//throw the 0s and factors together and get the sum!
int sum = 0;
for (int x = 0;x < numberPool.Length;x++)
{
sum = sum + numberPool[x];
}
Console.WriteLine(sum);
Console.ReadLine();
//uncomment above if running in vbs
}
}
}
The foreach loop has a few errors.
If you want to modify the array you are looping through use a for loop. Also, use modulus when checking remainders.
for (int i = 0; i < numberPool.Length; i++)
{
if (numberPool[i] % 3 == 0 || numberPool[i] % 5 == 0)
{
// Do nothing
}
else
{
numberPool[i] = 0;
}
}
Modulus (%) will give the remainder when dividing two integers.
Another useful shortcut, variable = variable + x can be replaced with variable += x
Please note that there are more concise ways of doing this but since you are learning the language I will leave that for you to find.
#kailanjian gave some great advice for you but here is another way your initial logic can be simplified for understanding:
//the sum of factors
int sum = 0;
//the maximum number we will test for
int maxNum = 1000;
//iterate from 1 to our max number
for (int i = 1; i <= maxNum; i++)
{
//the number is a factor of 3 or 5
if (i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
//output our sum
Console.WriteLine(sum);
You also stated:
Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
Your program logic will execute in the order that you list it and won't move on to the next given command until it is complete with the last. So your sum output will only be printed once it has completed our for loop iteration.

How to write groups of numbers using Console.Write?

I'm very new to C# (And Stack Overflow, forgive me for any poor etiquette here), and I'm writing the game Mastermind in a console application. I'm trying to show a list of the user's guesses at the end of the game, and I know that using Console.WriteLine(); will just give me 30-odd lines off numbers which don't tell the user anything.
How can I alter my code so that the program displays 4 numbers in a group, at a time? For example:
1234
1234
1234
//Store numbers in a history list
ArrayList guesses = new ArrayList(); //This is the ArrayList
Console.WriteLine("Please enter your first guess.");
guess1 = Convert.ToInt32(Console.ReadLine());
guesses.Add(guess1);
foreach (int i in guesses)
{
Console.Write(i);
}
I assume that each element of your byte array is a single digit (0-9). If that assumption is invalid -- please let me know, I'll modify the code :)
Action<IEnumerable<int>> dump = null;
dump = items =>
{
if(items.Any())
{
var head = String.Join("", items.Take(4));
Console.WriteLine(head);
var tail = items.Skip(4);
dump(tail);
}
};
dump(guesses);
It looks like you're most of the way there, you have a console write that writes them all out without linebreaks. Next add an integer count and set it to zero. Increment it by one in the foreach loop. count % 4 == 0 will then be true for all counts that are a multiple of four. This means you can stick an if block there with a write-line to give you your groups of four.
List<int> endResult = new List<int>();
StringBuilder tempSb = new StringBuilder();
for(int i=0; i < groups.Count; i++)
{
if(i % 4 == 0) {
endResult.Add(int.Parse(sb.ToString()));
tempSb.Clear(); // remove what was already added
}
tempSb.Append(group[i]);
}
// check to make sure there aren't any stragglers left in
// the StringBuilder. Would happen if the count of groups is not a multiple of 4
if(groups.Count % 4 != 0) {
groups.Add(int.Parse(sb.ToString()));
}
This will give you a list of 4 digit ints and make sure you don't lose any if your the number of ints in your groups list is not a multiple of 4. Please note that I am continuing based on what you provided, so groups is the ArrayList of ints.
This is some thing I quickly put together:
Update:
ArrayList guesses = new ArrayList(); //This is the ArrayList
// Four or more
guesses.Add(1); guesses.Add(2);
guesses.Add(3);guesses.Add(4);
guesses.Add(5); guesses.Add(6); guesses.Add(7);guesses.Add(8); guesses.Add(9);
//Uncomment-Me for less than four inputs
//guesses.Add(1); guesses.Add(2);
int position = 0;
if (guesses.Count < 4)
{
for (int y = 0; y < guesses.Count; y++)
{
Console.Out.Write(guesses[y]);
}
}
else
{
for (int i = 1; i <= guesses.Count; i++)
{
if (i%4 == 0)
{
Console.Out.WriteLine(string.Format("{0}{1}{2}{3}", guesses[i - 4], guesses[i - 3],
guesses[i - 2], guesses[i - 1]));
position = i;
}
else
{
if (i == guesses.Count)
{
for (int j = position; j < i; j++)
{
Console.Out.Write(guesses[j]);
}
}
}
}
}

Categories