Loop without IF or SWITCH condition within it - c#

I want to print the number like as shown below using the loop and without using if or switch condition.
1
2
3
4
5
5
5
6
6
7
8
9
9
10
Note: When loop comes to number 5 it has to iterate 3 times and when it comes to 6 and 9 it has to iterate 2 times.
Example:
I have the following code which prints numbers same as they meet the condition.
My Try:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Print Numbers 1 To 10");
for (int i = 1; i <= 10; i++)
{
Console.WriteLine( i==5 || i == 6 || i == 9 ? i.ToString() + Environment.NewLine + i.ToString() : i.ToString());
}
Console.ReadLine();
}
}

Try this:
for (int i = 1; i <= 14; i++)
Console.WriteLine(i - i / 6 - i / 7 - i / 9 + i / 12 - i / 13 + i / 14);
At position i = 6, i = 7, i = 9 and i = 13 you want to repeat the previous value, so subtract i / _, but need to add i / 12 and i / 14 because from 12 and 14 subtractions i / 6 and i / 7 start counting twice.

For starters, the ? mark operator is an if statement. So using that is out. But you could make an array:
int[] myNums = {1,2,3,4,5,5,5,6,6,7,8,9,9};
for (int i = 0; i < myNums.length; i++) {
Console.WriteLine(myNums[i]);
}

You could store the relationship between the number and the iteration count in a dictionary. The number to print would be the key and the number of times to print would be the value. You could then achieve what you need with then following:
var printNumbers = new Dictionary<int, int> { { 1, 1 }, { 2, 1 },{ 3, 1 },{ 4, 1 },{ 5, 3 }, { 6, 2 }, { 7, 1 }, { 8, 1 }, { 9, 2 } };
foreach (var num in printNumbers)
{
for (int i = 0; i < num.Value; i++)
{
Console.WriteLine(num.Key);
}
}

Related

Generating a for while foreach algorithm in c# with a pyramidal structure

I have been trying to get this to work for 3 days, and I feel like I'm using the wrong approach, if anyone can correct me I will wax your car. Background, client asked to me make a simple pyramid algorithm. I want to select add everything to a list of objects and make everything on the left side true and everything on the right side false. Every other line reads the line 2 lines prior and adds multiple entries. The first time it adds a number like 1 it's one time, then it adds two 1's for each 1 until there is 4. So the first time it enters a 1 on line 1, then on line 3 it adds a 1 two times, then on line 5 it reads from line 3 and adds each of those 1's 2 times.
Here is a visual representation.
|1|
|2| |3|
|1|1| |4|5|
|2|2|3|3| |6|7|8|9|
|1|1|1|1|4|4|5|5| |10|11|12|13|14|15|16|17|
|2|2|2|2|3|3|3|3|6|6|7|7|8|8|9|9| |18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33
The order this list would be is:
1|2|3|1|1|4|5|2|2|3|3|6|7|8|9|1|1|1|1|4|4|5|5|10|11|12|13|14|15|16|17...
I keep getting close, but it fails to generate the correct output. `
for (int i = 1; i < 50; i = i * 2)
{
Response.Write(i.ToString() + " - ");
var previousLevel = (i / 2 / 2);
foreach (var oc in infoRows.Where(x => x.level == previousLevel))
{
for (int p = i; p > 0; p--)
{
Response.Write(oc.id + "*");
}
}
while (level <= i)
{
for (int r = 1; r <= i; r++)
{
InfoRow tempInforow = new InfoRow();
tempInforow.customerCode = GenerateCustomerNumber(position);
tempInforow.id = customerId;
tempInforow.sendtoidnumber = level.ToString();
tempInforow.status = 0; // GetStatus(position, totalCount);
tempInforow.position = position;
tempInforow.level = i;
infoRows.Add(tempInforow);
customerId++;
position++;
Response.Write(tempInforow.id + "-");
level++;
}
}
}
`
Essentially this generates the following:
1 - 1-
2 - 2-3-
4 - 1*1*1*1*4-5-6-7-
8 - 2*2*2*2*2*2*2*2*3*3*3*3*3*3*3*3*8-9-10-11-12-13-14-15-
16 - 4*4*4*4*4*4*4*4*4*4*4*4*4*4*4*4*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*6*6*6*6*6*6*6*6*6*6*6*6*6*6*6*6*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*16-17-18-19-20-21-22-23-24-25-26-27-28-29-30-31-
32 -
I've tried 30 different ways with switch statements, while statements, for and foreach statements, the closest I can get to this working is level 4.
Can someone suggest another way. Maybe a multidimensional array or idk what. Thank you.
Let's write the sequence down and have a look on what's going on:
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ...
seq 1 2 3 1 1 4 5 2 2 3 3 6 7 8 9 1 1 1 1 4 4 5 5 10 ...
^ ^ ^ ^ ^ ^
| |
if # is power of 2 (e.g. 8 == 2**3)
we should copy and double # / 4 items (here 8 / 4 == 2 items)
starting from # / 4 item (here 8 / 4 == 2, starting from item #2)
Time to implement this algorithm
Code:
using System.Linq;
...
private static List<int> Pyramid(int size) {
if (size < 0)
throw new ArgumentOutOfRangeException(nameof(size));
if (size <= 3)
return Enumerable.Range(1, size).ToList();
List<int> result = new List<int>(size) { 1, 2, 3 };
for (int value = 4; result.Count < size; )
if (BitOperations.IsPow2(result.Count + 1)) {
int chunk = (result.Count + 1) / 4;
for (int i = 0; i < chunk && result.Count < size; ++i) {
result.Add(result[chunk - 1 + i]);
if (result.Count >= size)
return result;
result.Add(result[chunk - 1 + i]);
}
}
else
result.Add(value++);
return result;
}
Demo:
// First 31 items from the pyramid
Console.Write(string.Join("|", Pyramid(31)));
Output:
1|2|3|1|1|4|5|2|2|3|3|6|7|8|9|1|1|1|1|4|4|5|5|10|11|12|13|14|15|16|17

Multiply element in multidimensional array

-> Please help with the implementation of a function
Basically I want to manipulate an image
Imagine that the image can be brake apart in pixels
-> each pixel of the image will be (for an easy example) "a number"
int[,] originalImage = new int[,]
{
{ 1,2,3 },
{ 4,5,6 }
};
And I need to double the size of the image x2 (or x3, x4, etc)
the pixel "1" when double the size will be copied on te right position, down and on the corner
int[,] expectedResult = new int[,]
{
{ 1,1,2,2,3,3 },
{ 1,1,2,2,3,3 },
{ 4,4,5,5,6,6 },
{ 4,4,5,5,6,6 }
};
How does the function can be implemented?
Multiply(int[,] originalImage, int multiply)
Note there are oodles of libraries that would do this in math or image processing. However, purely for academic purposes
Given
private static int[,] DoStuff(int[,] array,int size)
{
var sizeX = array.GetLength(0);
var sizeY = array.GetLength(1);
var newArray = new int[sizeX * size, sizeY * size];
for (var i = 0; i < newArray.GetLength(0); i++)
for (var j = 0; j < newArray.GetLength(1); j++)
newArray[i, j] = array[i / size, j / size];
return newArray;
}
Usage
int[,] originalImage =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
var newArray = DoStuff(originalImage,3);
for (var i = 0; i < newArray.GetLength(0); i++)
{
for (var j = 0; j < newArray.GetLength(1); j++)
Console.Write(newArray[i, j] + " ");
Console.WriteLine();
}
Output
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
1 1 1 2 2 2 3 3 3
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6
4 4 4 5 5 5 6 6 6

How to input and output values in array [][,] and [,][] (mix of jagged array and multidimensional array)

I am trying to improve my code on how to find items in my multidimensional array, because I want to avoid possible future performance issues when I increase the data volume. I am a newbie to programming, so there are lots of stuff I do not know. I have been searching a lot around topics multidimensional array, jagged arrays, sorting. I think I need to use jagged array because I need to sort in order to locate third largest and 6.largest number. But I realize that I have to ask for some assistance on examples or link to more information because I am having problems making progress in defining my jagged array. I will try to isolate each issue because I get stuck on things I believe might be easy for people that are more familiar with arrays than me. It should be possible to mix jagged and multidimensional arrays according to jagged-arrays
Here is example of [][] which is working
using System;
using System.Collections;
namespace SortJaggedArray
{
class host
{
[STAThread]
static void Main(string[] args)
{
int[][] arr = new int[2][];
arr[0] = new int[3] {1,5,3};
arr[1] = new int[4] {4,2,8,6};
// Write out a header for the output.
Console.WriteLine("Array - Unsorted\n");
for (int i = 0; i < arr.Length; i++)
{
System.Console.WriteLine("Outer array " + i);
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j] + " ");
}
System.Console.WriteLine(" ");
System.Console.WriteLine(" ");
}
Console.ReadLine();
}
}
}
//Output:
//Outer array 0
//1 5 3
//Outer array 1
//4 2 8 6
Here is my example of [][,] where the input is working, but I struggle with how to write the output:
using System;
using System.Collections;
namespace SortJaggedArray
{
class host
{
[STAThread]
static void Main(string[] args)
{
int[][,] arr = new int[2][,]
{
new int[,] { { 1, 3 }, { 5, 2 }, { 3, 9 } },
new int[,] { { 4, 1 }, { 2, 7 }, { 8, 5 }, { 6, 3 } }
};
// Write out a header for the output.
Console.WriteLine("Array - Unsorted\n");
foreach (int i in arr)
Console.WriteLine(i);
Console.ReadLine();
}
}
}
Wanted output:
Nr 0:
1, 3
5, 2
3, 9
Nr 1:
4, 1
2, 7
8, 5
6, 3
Question 1:
How to write the WriteLine / for / foreach in order to see the content of the jagged array [][,] ?
Question 2:
I want to change this into [,][] but then I get problems in how to input/output data in such jagged array. How to input data? How to Writeline / for / forearch to see the content of jagged array [,][] ?
You need to iterate over every dimension:
for(int i=0; i<arr.Length; i++){
Console.WriteLine($"Nr {i}:");
for(int j=0;j<arr[i].GetLength(0);j++){
for(int k=0;k<arr[i].GetLength(1);k++){
Console.Write($"{arr[i][j,k]} ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Outputs:
Nr 0:
1 3
5 2
3 9
Nr 1:
4 1
2 7
8 5
6 3
package array;
import java.util.Scanner;
public class multiDimensionalArray {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i, j;
int values[][]=new int [3][3];
System.out.println("Enter array values");
for(i=0; i<3; i++) {
for(j=0; j<3; j++) {
values[i][j]=sc.nextInt();
}
}
System.out.println("Entered values are: \t");
for(i=0; i<3; i++) {
for(j=0; j<3; j++) {
System.out.print("\t"+values[i][j]);
}
System.out.print("\n");
}
}
}
In case other readers have the same question, I want to add code example on how Magnetron's example also helped me to solve the same issue for array [,][]
using System;
using System.Collections;
namespace SortJaggedArray
{
class host
{
[STAThread]
static void Main(string[] args)
{
int[,][] arr = new int[2,3][];
arr[0,0] = new int[3] { 1, 5, 3 };
arr[0,1] = new int[4] { 4, 2, 8, 6 };
arr[0,2] = new int[2] { 2, 8 };
arr[1,0] = new int[2] { 7, 5 };
arr[1,1] = new int[5] { 8, 7, 5, 9, 2 };
arr[1,2] = new int[2] { 1, 4};
// Write out a header for the output.
Console.WriteLine("Array - Unsorted\n");
for (int i = 0; i < arr.GetLength(0); i++)
{
Console.WriteLine($"Nr {i}:");
for (int j = 0; j < arr.GetLength(1); j++)
{
for (int k = 0; k < arr[i,j].Length; k++)
{
Console.Write($"{arr[i,j][k]} ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
//Output:
//Nr 0:
//1 5 3
//4 2 8 6
//2 8
//Nr 1:
//7 5
//8 7 5 9 2
//1 4

Rotate Outer N x N Square Array, while leaving inner square array unmoved

How can I rotate (or shift) a 2D square array but leave any elements that are not on the "border" of the array unmoved?
Example:
1 2 3 4
12 13 14 5
11 15 16 6
10 9 8 7
What I want:
12 1 2 3
11 13 14 4
10 15 16 5
9 8 7 6
That was just an example. I need this to work on any square array of N width where 2 < N < 100
If the array is stored as a square .NET array of rank 2 the code is pretty simple mainly consisting of four loops - one for each edge:
var array = new [,] {
{ 1, 2, 3, 4, 5 },
{ 16, 17, 18, 19, 6 },
{ 15, 24, 25, 20, 7 },
{ 14, 23, 22, 21, 8 },
{ 13, 12, 11, 10, 9 }
};
// Rank = 2 and "square" and side length >= 2 checks removed for clarity.
var sideLength = array.GetLength(0);
// Save first element from top edge.
var element00 = array[0, 0];
// Rotate left edge.
for (var y = 1; y < sideLength; y += 1)
array[y - 1, 0] = array[y, 0];
// Rotate bottom edge.
for (var x = 1; x < sideLength; x += 1)
array[sideLength - 1, x - 1] = array[sideLength - 1, x];
// Rotate right edge.
for (var y = sideLength - 2; y >= 0; y -= 1)
array[y + 1, sideLength - 1] = array[y, sideLength - 1];
// Rotate top edge.
for (var x = sideLength - 2; x > 0; x -= 1)
array[0, x + 1] = array[0, x];
// Put saved element in place.
array[0, 1] = element00;
Now the original array has been rotated as described in the question.
If the array is stored as a one dimensional array it is easier to create a class to perform the rotation. This class can store properties (the array and the side length) that can be used across method calls to simplify the code.
The four loops contains the same logic even though they look different:
class ArrayRotator<T> {
public ArrayRotator(T[] array) {
if (array == null)
throw new ArgumentNullException("array");
var sideLength = (Int32) Math.Sqrt(array.Length);
if (sideLength*sideLength != array.Length)
throw new ArgumentException("Not a square.", "array");
Array = array;
SideLength = sideLength;
}
public T[] Array { get; private set; }
public Int32 SideLength { get; private set; }
public void RotateArray() {
if (SideLength < 3)
return;
// Save first element from top edge.
var element00 = Array[0];
// Rotate left edge.
for (var y = 1; y < SideLength; y += 1)
CopyElement(0, y, 0, y - 1);
// Rotate bottom edge.
for (var x = 1; x < SideLength; x += 1)
CopyElement(x, SideLength - 1, x - 1, SideLength - 1);
// Rotate right edge.
for (var y = SideLength - 2; y >= 0; y -= 1)
CopyElement(SideLength - 1, y, SideLength - 1, y + 1);
// Rotate top edge.
for (var x = SideLength - 2; x > 0; x -= 1)
CopyElement(x, 0, x + 1, 0);
// Put saved element in place.
Array[1] = element00;
}
void CopyElement(Int32 x1, Int32 y1, Int32 x2, Int32 y2) {
Array[GetIndex(x2, y2)] = Array[GetIndex(x1, y1)];
}
Int32 GetIndex(Int32 x, Int32 y) {
return y*SideLength + x;
}
}
Here is how to use the class:
var array = new [] {
1, 2, 3, 4,
12, 13, 14, 5,
11, 15, 16, 6,
10, 9, 8, 7
};
var arrayRotator = new ArrayRotator<Int32>(array);
arrayRotator.RotateArray();
Now the original array has been rotated as described in the question.
I found this question pretty interesting and fun, I've devised a little solution that works as long as the array conforms to a perfect square, this should work regardless of the side length.
NOTE: this is not the most optimized solution (I'm keen to try and make a more elegant solution, but this should suffice for now).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArraySquareRotation
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[]
{
1, 2, 3, 4, 5, 3,
12, 13, 14, 5, 6, 1,
11, 15, 16, 6, 7, 22,
10, 9, 8, 7, 8, 30,
11, 15, 16, 6, 7, 22,
1, 2, 3, 4, 5, 3
};
// detect array size
int size = arr.Length;
// calculate the side length of the array (in terms of index)
int sideLength = BruteForceSquareDimensions(size);
// find the start of the last side of the square
int lastRowStartIndex = size - sideLength;
// a placeholder for us to generate a shifted array
int[] arrRotated = new int[size];
Console.WriteLine("Detected square with side length {0}", sideLength);
Console.WriteLine();
for (int i = 1; i <= size; i++)
{
// side rotation
if ((i % sideLength) == 0 && i != size)
{
// is multiple of
// right hand side, shift down
arrRotated[i + sideLength - 1] = arr[i - 1];
// left hand side, shift up
arrRotated[i + sideLength - (sideLength * 2)] = arr[i];
} else if (i < sideLength)
{
int lastRowIndex = sideLength * (sideLength - 1);
// first row, shift right
arrRotated[i] = arr[i - 1];
// last row, shit left
arrRotated[i + lastRowIndex - 1] = arr[i + lastRowStartIndex];
} else if(i < lastRowStartIndex)
{
// the inner square (this case may need some work)
arrRotated[i - 1] = arr[i - 1];
}
}
Console.WriteLine("Printing original array");
Console.WriteLine("======================");
PrintSquareArray(arr);
Console.WriteLine();
Console.WriteLine("Printing Shifted array");
Console.WriteLine("======================");
PrintSquareArray(arrRotated);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
/// <summary>
/// there is definately a better way.
/// </summary>
/// <param name="size"></param>
/// <returns></returns>
static int BruteForceSquareDimensions(int size)
{
int sideLength = 0;
for (int i = 1; i < size; i++)
{
if ((i * i) == size)
{
sideLength = i;
}
}
return sideLength;
}
/// <summary>
/// This method just prints the array in the desired readable format
/// </summary>
/// <param name="arr"></param>
static void PrintSquareArray(int[] arr)
{
int size = arr.Length;
int sideLength = BruteForceSquareDimensions(size);
for(int i = 1; i <= size; i++)
{
if ((i % sideLength) == 0)
{
Console.WriteLine(arr[i - 1]);
}
else
{
Console.Write(arr[i - 1] + "\t");
}
}
}
}
}
The output should look as follows (Square):
Detected square with side length 4
Printing original array
======================
1 2 3 4
12 13 14 5
11 15 16 6
10 9 8 7
Printing Shifted array
======================
12 1 2 3
11 13 14 4
10 15 16 5
9 8 7 6
Press any key to exit
And here's a 6 by 6
Detected square with side length 6
Printing original array
======================
1 2 3 4 5 3
12 13 14 5 6 1
11 15 16 6 7 22
10 9 8 7 8 30
11 15 16 6 7 22
1 2 3 4 5 3
Printing Shifted array
======================
12 1 2 3 4 5
11 13 14 5 6 3
10 15 16 6 7 1
11 9 8 7 8 22
1 15 16 6 7 30
2 3 4 5 3 22
Press any key to exit
Here's what I got. Tested on the 4x4 you provided and the following 5x5 square array. Also, I am assuming the data is stored in jagged arrays, such that 1 array contains n arrays each of length n.
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
static int[][] Transform(int[][] old)
{
var maxIdx = old.Length-1;
var canvas = new List<int[]>();
//top border
var top = new List<int>();
top.Add(old[1][0]);
for (var i = 0; i < maxIdx; i++)
{
top.Add(old[0][i]);
}
//bottom border
var bottom = new List<int>();
for (var i = 1; i < maxIdx+1; i++)
{
bottom.Add(old[maxIdx][i]);
}
bottom.Add(old[maxIdx - 1][maxIdx]);
//middle
var middle = new List<int[]>();
for (var i = 1; i < maxIdx; i++) //for each inner array
{
var inside = new List<int>();
inside.Add(old[i + 1][0]);
for (var j = 1; j < maxIdx; j++)
{
inside.Add(old[i][j]);
}
inside.Add(old[i - 1][maxIdx]);
middle.Add(inside.ToArray());
}
//Rebuild
canvas.Add(top.ToArray());
foreach (var arr in middle)
{
canvas.Add(arr);
}
canvas.Add(bottom.ToArray());
return canvas.ToArray();
}

Printing out 3 elements in array per line

I have an array with x number of elements and want to print out three elements per line (with a for-loop).
Example:
123 343 3434
342 3455 13355
3444 534 2455
I guess i could use %, but I just can't figure out how to do it.
For loop is more suitable:
var array = Enumerable.Range(0, 11).ToArray();
for (int i = 0; i < array.Length; i++)
{
Console.Write("{0,-5}", array[i]);
if (i % 3 == 2)
Console.WriteLine();
}
Outputs:
0 1 2
3 4 5
6 7 8
9 10
Loop through the array 3 at a time and use String.Format().
This should do it...
for (int i = 0; i < array.Length; i += 3)
Console.WriteLine(String.Format("{0,6} {1,6} {2,6}", array[i], array[i + 1], array[i + 2]));
But if the number of items in the array is not divisable by 3, you'll have to add some logic to make sure you don't go out of bounds on the final loop.
You perhaps need to fix the format spacing...
for(int i=0;i<array.Length;i++)
{
Console.Write(array[i] + " ");
if((i+1)%3==0)
Console.WriteLine();
}
Long... but with comments:
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int count = list.Count;
int numGroups = list.Count / 3 + ((list.Count % 3 == 0) ? 0 : 1); // A partially-filled group is still a group!
for (int i = 0; i < numGroups; i++)
{
int counterBase = i * 3;
string s = list[counterBase].ToString(); // if this a partially filled group, the first element must be here...
if (counterBase + 1 < count) // but the second...
s += list[counterBase + 1].ToString(", 0");
if (counterBase + 2 < count) // and third elements may not.
s += list[counterBase + 2].ToString(", 0");
Console.WriteLine(s);
}

Categories

Resources