In the scenario where you have two groups of numbers, each containing the numbers 1 to 10, how would you go about incrementing each number until it hits its upper limit?
For example, to procude the numbers as follows:
1.1
1.2
1.3
...
1.9
1.10
2.1
2.2
2.3
...
2.9
2.10
etc...
My effort is pretty abysmal so far - I started with for loops and couldnt get a decent result, moved onto a while loop and still havent got a working solution, but here's what I have so far.
class Program
{
static void Main()
{
int group01 = 1;
int group01Max = 10;
int group02 = 2;
int group02Max = 10;
while (group01 < group01Max)
{
while (group02 < group02Max)
{
Console.WriteLine(string.Format("{0}.{1}", group01, group02));
}
}
}
}
I'm not entirely sure if this is what you're asking, but do you mean something like this?
a = 10
b = 10
for(int i = 0; i < a; i++){
string tmp = i.toString();
for(int j = 0; j < b; j++){
tmp += "." + j.toString();
}
Console.WriteLine(tmp);
}
edit: using $"" notation would simplify this as done in the answer below
a = 10
b = 10
for(int i = 0; i < a; i++){;
for(int j = 0; j < b; j++){
Console.WriteLine($"{i}.{j}");
}
}
It can be easily done by nesting one loop in another loop.
foreach(var firstIndex in firstGroup)
{
foreach(var secondIndex in secondGroup)
{
Console.WriteLine($"{firstIndex}.{secondIndex}");
}
}
Enumerable.Range(1, 10).Select(n1 => Enumerable.Range(1, 10).Select(n2 => (n1, n2)))
Or if you want the special formatting,
Enumerable.Range(1, 10).SelectMany(n1 => Enumerable.Range(1, 10).Select(n2 => $"{n1}.{n2}"))
Related
I'm currently working on a little lottery game in a console window made with C#.
I added a feature that lets the user randomize the 6 numbers he will have on his ticket but noticed that my random number generator sometimes generates the same number even though you can theoretically only have a number once, so I built this check to see if any number is the same only to notice that I cant go back to randomizing a new list of numbers because the goto function cant go out of a loop (CS0159). Any other way to do this?
Code:
Console.WriteLine("\nRandomized 6 numbers: ");
// Randomize 6 numbers in for the array randomList
for (int z = 0; z <= 5; z++)
{
SameNum:
int rndNum = rnd.Next(1, 50);
randomList[z] = rndNum;
}
// Once the list is done check if any elements of the array
// are the same and if yes go back to SameNum to generate a new
// List of 6 numbers
for (int a = 0; a <= 5; a++)
{
for (int b = 0; b <= 5; b++)
{
while (randomList[a] == randomList[b])
{
goto SameNum;
}
}
}
// Display the random list if there are no same numbers
for (int c = 0; c <= 5; c++)
{
Console.WriteLine(randomList[c] + " ");
}
Possible solution.
List<int> digits = new List<int>();
int z= 0;
while(z <= 5)
{
int rndNum = rnd.Next(1, 50);
if(!digits.Contains(rndNum))
{
digits.Add(rnbNum);
z++;
}
}
int[] randomList = digits.ToArray();
digits.Clear();
I am working on a project that compares the time bubble and selection sort take. I made two separate programs and combined them into one and now bubble sort is running much faster than selection sort. I checked to make sure that the code wasn't just giving me 0s because of some conversion error and was running as intended. I am using System.Diagnostics; to measure the time. I also checked that the machine was not the problem, I ran it on Replit and got similar results.
{
class Program
{
public static int s1 = 0;
public static int s2 = 0;
static decimal bubblesort(int[] arr1)
{
int n = arr1.Length;
var sw1 = Stopwatch.StartNew();
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr1[j] > arr1[j + 1])
{
int tmp = arr1[j];
// swap tmp and arr[i] int tmp = arr[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = tmp;
s1++;
}
}
}
sw1.Stop();
// Console.WriteLine(sw1.ElapsedMilliseconds);
decimal a = Convert.ToDecimal(sw1.ElapsedMilliseconds);
return a;
}
static decimal selectionsort(int[] arr2)
{
int n = arr2.Length;
var sw1 = Stopwatch.StartNew();
// for (int e = 0; e < 1000; e++)
// {
for (int x = 0; x < arr2.Length - 1; x++)
{
int minPos = x;
for (int y = x + 1; y < arr2.Length; y++)
{
if (arr2[y] < arr2[minPos])
minPos = y;
}
if (x != minPos && minPos < arr2.Length)
{
int temp = arr2[minPos];
arr2[minPos] = arr2[x];
arr2[x] = temp;
s2++;
}
}
// }
sw1.Stop();
// Console.WriteLine(sw1.ElapsedMilliseconds);
decimal a = Convert.ToDecimal(sw1.ElapsedMilliseconds);
return a;
}
static void Main(string[] args)
{
Console.WriteLine("Enter the size of n");
int n = Convert.ToInt32(Console.ReadLine());
Random rnd = new System.Random();
decimal bs = 0M;
decimal ss = 0M;
int s = 0;
int[] arr1 = new int[n];
int tx = 1000; //tx is a variable that I can use to adjust sample size
decimal tm = Convert.ToDecimal(tx);
for (int i = 0; i < tx; i++)
{
for (int a = 0; a < n; a++)
{
arr1[a] = rnd.Next(0, 1000000);
}
ss += selectionsort(arr1);
bs += bubblesort(arr1);
}
bs = bs / tm;
ss = ss / tm;
Console.WriteLine("Bubble Sort took " + bs + " miliseconds");
Console.WriteLine("Selection Sort took " + ss + " miliseconds");
}
}
}
What is going on? What is causing bubble sort to be fast or what is slowing down Selection sort? How can I fix this?
I found that the problem was that the Selection Sort was looping 1000 times per method run in addition to the 1000 runs for sample size, causing the method to perform significantly worse than bubble sort. Thank you guys for help and thank you TheGeneral for showing me the benchmarking tools. Also, the array that was given as a parameter was a copy instead of a reference, as running through the loop manually showed me that the bubble sort was doing it's job and not sorting an already sorted array.
To solve your initial problem you just need to copy your arrays, you can do this easily with ToArray():
Creates an array from a IEnumerable.
ss += selectionsort(arr1.ToArray());
bs += bubblesort(arr1.ToArray());
However let's learn how to do a more reliable benchmark with BenchmarkDotNet:
BenchmarkDotNet Nuget
Official Documentation
Given
public class Sort
{
public static void BubbleSort(int[] arr1)
{
int n = arr1.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr1[j] > arr1[j + 1])
{
int tmp = arr1[j];
// swap tmp and arr[i] int tmp = arr[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = tmp;
}
}
}
}
public static void SelectionSort(int[] arr2)
{
int n = arr2.Length;
for (int x = 0; x < arr2.Length - 1; x++)
{
int minPos = x;
for (int y = x + 1; y < arr2.Length; y++)
{
if (arr2[y] < arr2[minPos])
minPos = y;
}
if (x != minPos && minPos < arr2.Length)
{
int temp = arr2[minPos];
arr2[minPos] = arr2[x];
arr2[x] = temp;
}
}
}
}
Benchmark code
[SimpleJob(RuntimeMoniker.Net50)]
[MemoryDiagnoser()]
public class SortBenchmark
{
private int[] data;
[Params(100, 1000)]
public int N;
[GlobalSetup]
public void Setup()
{
var r = new Random(42);
data = Enumerable
.Repeat(0, N)
.Select(i => r.Next(0, N))
.ToArray();
}
[Benchmark]
public void Bubble() => Sort.BubbleSort(data.ToArray());
[Benchmark]
public void Selection() => Sort.SelectionSort(data.ToArray());
}
Usage
static void Main(string[] args)
{
BenchmarkRunner.Run<SortBenchmark>();
}
Results
Method
N
Mean
Error
StdDev
Bubble
100
8.553 us
0.0753 us
0.0704 us
Selection
100
4.757 us
0.0247 us
0.0231 us
Bubble
1000
657.760 us
7.2581 us
6.7893 us
Selection
1000
300.395 us
2.3302 us
2.1796 us
Summary
What have we learnt? Your bubble sort code is slower ¯\_(ツ)_/¯
It looks like you're passing in the sorted array into Bubble Sort. Because arrays are passed by reference, the sort that you're doing on the array is editing the same contents of the array that will be eventually passed into bubble sort.
Make a second array and pass the second array into bubble sort.
I've been trying to learn more about C#, and so I was doing a little practicing with Lists:
static void Main()
{
List<List<int>> a = new List<List<int>>();
List<int> temp = new List<int>();
temp.Add(1);
a.Add(temp);
for (int i = 0; i < 9; i++)
{
temp.Clear();
temp.Add(1);
for (int q = 0; q < a[i].Count-1; q++)
{
temp.Add(a[i][q] + a[i][q+1]);
}
temp.Add(1);
a.Add(temp);
}
foreach (var i in a[8])
Console.Write(i + " ");
Console.WriteLine();
}
I converted this to C++, and it works perfectly. However, in C#, a[i].Count is always 1. Even though after the first loop the size must be 2.
My only guess is that there's some major difference between C++'s Vector and C#'s List that I've apparently missed. Any ideas?
Here's the C++ code which works:
int main()
{
std::vector<std::vector<int>> a;
std::vector<int> b;
b.push_back(1);
a.push_back(b);
for (int i = 0; i < 9; i++)
{
b.clear();
b.push_back(1);
for (int q = 0; q < a[i].size()-1; q++)
{
b.push_back(a[i][q] + a[i][q+1]);
}
b.push_back(1);
a.push_back(b);
}
for (auto i : a[8])
{
std::cout << i << ' ';
}
}
Output for C++ Code:
1 8 28 56 70 56 28 8 1
Output For C# Code:
1 1
Any help is appreciated, thanks!
Look at your C# code a.Add(temp);. This temp variable is a reference type, so it will always add the same memory object.
To fix that, you can use LINQ to solve it:
a.Add(temp.ToList());. ToList() will generate a new object with different memory.
I have modified your code slightly, the main difference to not is, C# there are mainly 2
kind of types, one is a reference type and one is a value type.
List is a reference type.
In your code, you always clearing and adding numbers to the temp list.
that always points to the same object, so when you clear in the nth row, it's also clearing all the rows before it.
List<List<int>> a = new List<List<int>>();
a.Add(new List<int> { 1 });
for (int i = 0; i < 9; i++)
{
List<int> temp = new List<int>();
temp.Add(1);
for (int q = 0; q < a[i].Count - 1; q++)
{
temp.Add(a[i][q] + a[i][q + 1]);
}
temp.Add(1);
a.Add(temp);
}
foreach (var row in a)
{
foreach (var col in row)
{
Console.Write(col + " ");
}
Console.WriteLine();
}
Console.ReadKey();
I'm trying to store an unknown amount of data into an array, while using a forloop to get data! My task is to find and sum all the numbers form 1 to 1000 that can be divided be 3 and 5.
for (int i = 1; i < 1001; i++)
if (i%3==0)
{
if (i%5==0)
{
//this doesn't work, have tried to convert it to string, didn't work either
int[] array = { i };
//trying to loop the values
for (int j = 0; j < array.Length; i++)
{
//how can I loop this so I dont have to write it all out?
int sum1 = array[j]
}
}
}
Console.ReadKey();
Just because computers can perform repetitive task well doesn't mean you ignore Mathematics. If I got it right, you are trying to find the sum of all the numbers less than 1000 which are divisible by both 3 and 5. So that boils down to all the multiples of 15. Now if you take the floor of 1000/15, you get the the last multiple, which in this case is 66. So, you have to sum the series:
15, 15*2, 15*3,...15*66
=15*(1+2+3+..+66) [15*sum of first 66 positive natural numbers]
=15*66*67/2
So generalizing, finding sum of all numbers less than a and divisible by b is given by:
limit = floor(a/b);
sum = b*limit*(limit+1)/2;
Something like this:
var ListOfInts=new List<int>();
for (int i = 1; i < 1001; i++) {
if (i % 3 == 0 && i % 5 == 0)
ListOfInts.Add(i);
}
var result = ListOfInts.Sum();
Perhaps this code does what you want:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> li = new List<int>();
for (int i = 1; i <= 1000; i++)
{
if (i%3 == 0 && i%5 == 0)
{
li.Add(i);
}
}
Console.Write("sum is " + li.Sum());
Console.ReadLine();
}
}
}
The number devides by 3 and 5 means it devides by 15. So you can start iterating from 15 and incrementing by 15 to skip some iterations:
int sum = 0;
for (int i = 15; i <= 1000; i += 15)
sum += i;
Thanks guys! Alot of good answers, i'm still trying to understand some of them but thanks :)
How come that
List<int> li = new List<int>();
for (int i = 1; i <= 1000; i++)
{
if (i%3 == 0 && i%5 == 0)
{
li.Add(i);
}
}
Console.Write("sum is " + li.Sum());
Console.ReadLine();
give me this
while the code down under
var ListofInts = new List<int>();
for (int i = 0; i < 1001; i++)
{
if (i%3==0 && i%5==0)
{
ListofInts.Add(i);
var result = ListofInts.Sum();
Console.Write(result + ", ");
}
}
gives me this?
I have five arrays of varying lengths and I need to iterate through all of them generating all possible combinations of the contents. I'm currently using 5 nested for loops like so:
for (int a = 1; a < Array1.Length - 1; a++)
{
for (int b = 1; b < Array2.Length - 1; b++)
{
for (int c = 1; c < Array3.Length - 1; c++)
{
for (int d = 1; d < Array4.Length - 1; d++)
{
for (int e = 1; e < Array5.Length - 1; e++)
{
//do something
}
}
}
}
}
Due to the size of the arrays, I end up with more than 456 million iterations. I'm pretty new to programming in general, and C# specifically. I'm just curious if there is a more efficient way to accomplish this.
Thank you.
You go though that many iterations because there are that many combinations: this is called combinatorial explosion. You cannot do it more efficiently if you must go through all possible combinations.
You can code it with fewer lines of code or without hard-coding the number of arrays (five in your case) by using recursion. However, the number of iterations is not going to change, only the number of lines of code.
void processCombination(int[] combination) {
// combination[i] has the index of array #i
...
}
void combine(int p, int[] indexes, int[] sizes) {
if (p == indexes.Length) {
processCombination(indexes);
} else {
for (indexes[p] = 0 ; indexes[p] != sizes[p] ; indexes[p]++) {
combine(p+1, indexes, sizes);
}
}
}