I need to write out my array using a for-loop. This is my code. The reason I have to do it with a for-loop is because it is for a school project and the teacher does not accept anything else. What the code is doing right now is that first it creates an array with random numbers and make sure there are no duplicates then it makes sure it is sorted with bigger numbers first.
int[] myArray = new int[20];
Random random = new Random();
bool isUnique;
for (int i = 0; i < myArray.Length; i++) {
isUnique = false;
while (!isUnique) {
isUnique = true;
myArray[i] = random.Next(1, 100);
for (int j = 0; j < i; j++) {
if (myArray[i] == myArray[j]) {
isUnique = false;
}
}
}
}
bool isSorted;
int change;
for (int i = 0; i < myArray.Length; i++) {
isSorted = false;
while (!isSorted) {
isSorted = true;
for (int j = i + 1; j < myArray.Length; j++) {
if (myArray[i] < myArray[j]) {
change = myArray[j];
myArray[j] = myArray[i];
myArray[i] = change;
isSorted = false;
}
}
}
}
Works for me.
for (var i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}
Prints your array, it's sorted fine and prints biggest to smallest.
What isn't working?
I rewrote your code to less verbose variant:
int[] myArray = new int[20];
Random random = new Random();
int randomValue = 0;
// Fill array
for (int i = 0; i < myArray.Length; i++)
{
do randomValue = random.Next(1, 100);
while (myArray.Contains(randomValue));
myArray[i] = randomValue;
}
// Sort array
myArray = myArray.OrderByDescending(x => x).ToArray();
For write array to console you should use cycle:
for (var i = 0; i < myArray.Length; i++)
Console.WriteLine(myArray[i] + " ");
But for best and less verbose result you should use this:
Console.WriteLine(string.Join(", ", myArray));
It's return this:
97, 95, 93, 92, 91, 85, 84, 78, 77, 76, 75, 68, 57, 45, 24, 22, 14, 10, 8, 4
Related
So I am trying to solve this task "Digit Difference Sort" on Codefights
Given an array of integers, sort its elements by the difference of their largest and smallest digits.
In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152].
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I have an issue with two numbers having the same difference. Here's what I wrote so far:
int[] digitDifferenceSort(int[] a) {
return a.OrderBy(x => difference(x)).ToArray();
}
int difference(int x)
{
int min = 9, max = 0;
do
{
int tmp = x % 10;
min = Math.Min(min, tmp);
max = Math.Max(max, tmp);
} while ((x /= 10) > 0);
return max - min;
}
Didn't do much (for example the output is still [7, 23, 887, 243, 152] rather than [7, 887, 23, 243, 152])
How do I make element with larger index come first in result? What should I use instead of OrderBy?
I don't consider your difference method, i assume it works fine.
To your question: you have to keep revered order of the array (that the items with the same difference arrive will be sorted reverse). To do it, you could just reverse you input array: all items with not identical difference will be ordered correctly, and with the same differece will be ordered reversed:
int[] digitDifferenceSort(int[] a)
{
return a.Reverse().OrderBy(x => difference(x)).ToArray();
}
Following is my code for the above question digit difference sort. I am also getting output when running in Eclipse but when I paste the code on code signal it gives me a null pointer exception.
package NormalPrograms;
import java.util.ArrayList;
import java.util.Collections;
public class DigitDifferenceSort {
// For index wise sorting in descending order
public static int[] sortingnumberindexwise(int[] a, ArrayList<Integer> index) {
int k = 0;
int[] res = new int[index.size()];
int[] finalres = new int[index.size()];
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < index.size(); j++) {
if (a[i] == (int) index.get(j)) {
res[k] = i;
index.remove(j);
k++;
break;
}
}
}
int g = 0;
k = 0;
for (int i = 0; i < res.length; i++) {
finalres[g] = a[res[k]];
g++;
k++;
}
return finalres;
}
public static int[] finddigitDifferenceandSort(int[] p) {
int[] finres = new int[p.length];
for (int i = 0; i < finres.length; i++) {
finres[i] = p[i];
}
// This finres array act as an temp array and reused to make final result array
int digit = 0;
ArrayList<Integer> A = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
B.add(new ArrayList<Integer>());
}
for (int i = 0; i < p.length; i++) {
int temp = 0;
temp = p[i];
while (p[i] > 0) {
digit = p[i] % 10;
p[i] /= 10;
A.add(digit);
}
int b = Collections.max(A);
int c = Collections.min(A);
int diff = b - c;
B.get(diff).add(temp);
A.clear();
}
for (int i = 0; i < B.size(); i++) {
if (B.get(i).size() > 1) {
ArrayList<Integer> C = new ArrayList<Integer>();
for (int k = 0; k < B.get(i).size(); k++) {
C.add(B.get(i).get(k));
}
B.get(i).clear();
for (int j : sortingnumberindexwise(finres, C)) {
B.get(i).add(j);
}
} else {
continue;
}
}
int k = 0;
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B.get(i).size(); j++) {
if (B.get(i).size() == 0)
continue;
else {
finres[k] = B.get(i).get(j);
k++;
}
}
}
return finres;
}
public static void main(String[] args) {
int[] a = { 12, 21, 1, 1, 1, 2, 2, 3 };
for (int i : finddigitDifferenceandSort(a)) {
System.out.print(i + " ");
}
}
}
This is my first question here, so sorry for any mistake.
How to do second loop to generate unique rows?
Every time when i add second loop to find unique solution program hangup...
static void Main(string[] args)
{
int[,] tab = new int[9, 9];
Random r = new Random();
List<int> temp = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
while (true)
{
bool uniq = true;
int randomNumber = r.Next(0, 9);
for (int z = 0; z < i; z++)
{
if (randomNumber==tab[z,j])
{
uniq = false;
}
}
if (uniq == false)
{
continue;
}
tab[i, j] = randomNumber;
temp.Remove(randomNumber);
break;
}
Try this:
private Random r = new Random();
void Main()
{
int[,] tab = new int[9, 9];
List<int> digits = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < 9; i++)
{
List<int> temp = digits.OrderBy(x => r.Next()).ToList();
for (int j = 0; j < 9; j++)
{
tab[i, j] = temp[j];
}
}
}
I am working on an issue where i need to Declare a two - dimensional array named multiplicationTable
that contains 4 elements by 4 elements.Initialize it in
a nested loop to contain elements that equal to the value
that is the product of the two index values for
each element. In a second nested loop, display the values
in the console output, with column elements separated with
commas, and row elements separated with carriage returns. This is what i have so far, for some reason can't wrap my brain around the solution! Any help would be appreciated!.
double[,] multiplicationTable = new double[4, 4];// { {1,2,3,4 }, {5,6,7,8 }, {9,10,11,12 }, {13,14,15,16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
double d = multiplicationTable[i, j];
if (j < multiplicationTable.GetLength(1) - 1)
{
Console.Write(d + ",");
}
else
{
Console.Write(d);
}
}
Console.Write("\n");
}
Console.ReadKey();
Why not try to solve this with String.Join method? It is easy to use and will save you a lot of if-else statements. Here it is how it will look like with this method:
double[,] multiplicationTable = new double[4, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[4];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}
Console.ReadKey();
double[,] multiplicationTable = new double[4, 4];
for (int i = 0; i < multiplicationTable.GetLength(0); i++)
{
var temp = new string[multiplicationTable.GetLength(0)];
for (int j = 0; j < multiplicationTable.GetLength(1); j++)
{
multiplicationTable[i, j] = i * j;
temp[j] = multiplicationTable[i, j].ToString();
}
Console.WriteLine(string.Join(",", temp));
}
I couldn't get it to work, I am trying to arrange the values of the array in ascending order by using for loop.
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
for (int i = 0; i <= arr.Length; i++)
{
if (arr[i] > arr[i + 1])
{
int temp = arr[i + 1];
arr[i] = arr[i + 1];
arr[i] = temp;
}
Console.Write(arr[i]);
}
I am assuming that you are not using Array.Sort because you are doing this as a learning exercise; there is no other way to avoid this very common library function.
The reason your algorithm does not work is that it is not enough to go through an array once, and swap items that are out of order. Try doing this as a mental experiment, when the array is almost sorted, but the first element is at the end, like this:
2 3 4 5 6 7 1
A single path would bring you closer, but it wouldn't bring you all the way to a sorted array:
2 3 4 5 6 1 7
As you can see, you have to repeat this process multiple times, until the array is sorted. How do you know that the array is sorted? You know that when the entire inner loop did not have a single swap.
Here is how you can implement this:
bool didSwap;
do {
didSwap = false;
for (int i = 0; i < arr.Length-1; i++)
{
if (arr[i] > arr[i + 1])
{
int temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
didSwap = true;
}
}
} while (didSwap);
for (int i = 0; i != arr.Length ; i++) {
Console.Write(arr[i]);
}
Note several changes from your code:
The printing is done in the separate loop, after the sorting is complete
The loop goes to arr.length-1, not to arr.length, because otherwise your last check will go outside the bounds of the array.
This sorting algorithm is called Bubble Sort. There are various optimizations to this algorithm that can make it go slightly faster.
In general, bubble sort is among the slower sorting algorithms. When the number of items to sort is high, you should consider an advanced algorithm, or use the library implementation.
int[] Array = { 11, 33, 5, -3, 19, 8, 49 };
int temp;
for (int i = 0; i < Array.Length - 1; i++)
{
for (int j = i + 1; j < Array.Length; j++)
{
if (Array[i] > Array[j])
{
temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
Console.Write("Sorted:");
foreach (int sort in Array)
Console.Write("{0} ", sort);
If you want to make your own sorting, then it's not enough to just loop through the items once and swap them. The closest to that is the bubble sort algorithm, where you loop over the array repeatedly until there is no more items to swap:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
bool swapped = true;
while (swapped) {
swapped = false;
for (int i = 0; i < arr.Length - 1; i++) {
if (arr[i] > arr[i + 1]) {
swapped = true;
int temp = arr[i + 1];
arr[i] = arr[i + 1];
arr[i] = temp;
}
}
}
for (int i = 0; i < arr.Length - 1; i++) {
Console.Write(arr[i]);
}
There are also built in methods to sort data, which is easier to use, more efficient, and already thoroughly tested:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
Array.Sort(arr);
Use Linq Order by:
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
int[] ascOrderedArray = (from i in arr orderby i ascending select i).ToArray();
I think it could be easy and why do you need for loop.
using System;
namespace bubble_sort
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
int[] arr = new int[50];
int n;
Console.WriteLine("Enter no of elements you want to store in an array");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter elements in an array");
for (int i = 1; i <= n; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
p.bubblesort(arr, n);
Console.ReadKey();
}
public void bubblesort(int[] arr, int n)
{
int temp;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Console.WriteLine("Array after sorting");
for (int i = 1; i <= n; i++)
{
Console.WriteLine(arr[i]);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace basicsorting
{
public class Program
{
public static void Main(string[] args)
{
int i2, k, j;
Console.WriteLine("How many elements you want to sort? ");
i2 = Convert.ToInt32(Console.ReadLine());
int[] values = new int[i2];
int n1 = 0;
int n = 0; ;
int i;
Console.WriteLine("Enter the elements of array {0}", n1);
for (i = 0; i < i2; i++)
{
Console.WriteLine("Enter the elements of array {0}");
n = Convert.ToInt32(Console.ReadLine());
Convert.ToInt32(values[i] = n);
}
for (i = 0; i < i2; i++)
{
k = Convert.ToInt32(values[i]);
for (j = i - 1; j >= 0 && k < values[j]; j--)
values[j + 1] = values[j];
values[j + 1] = k;
}
for (i = 0; i < i2; i++)
{
Console.WriteLine("sorting elements {0}", values[i]);
}
Console.ReadLine();
}
}
}
int[] array = new int[] { 8, 9, 5, 6, 7, 4, 3, 2, 1 };
int[] outPut = new int[] { };
int temp = 0;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
var first = array[i];
var second = array[j];
if (array[i] < array[j]) {
temp = first;
array[i] = second;
array[j] = temp;
}
}
}
foreach (var item in array) {
Console.WriteLine(item);
}
Console.ReadKey();
}
foreach (var item in array) {
Console.WriteLine(item);
}
Console.ReadKey();
int temp = 0;
int[] arr = new int[] { 5, 6, 2, 4, 1 };
for (int i = 0; i <= arr.Length - 1; i++)
{
for (int j = i + 1; j <= arr.Length - 1; j++)
{
if (arr[i] > arr[j]) //> Asecnding Order < Desending Order
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Console.Write(arr[i]);
}
Console.ReadLine();
public int[] sortArray(params int[] numbers)
{
for(int i = 0; i < numbers.Length; i++)
{
for(int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] < numbers[j])
{
continue;
}else if (numbers[i] > numbers[j])
{
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
return numbers;
}
You should do like :
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
for (int i = 0; i < arr.Length-1; i++)
{
if (arr[i] < arr[i + 1])
{
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
// to verify sorted Array
for (int i = 0; i < arr.Length; i++)
{
console.write( arr[i].ToString());
}
For last 1 you need not to check it will be automatically ordered.
#Jon Skeet They wanted to use a for loop.
There are numerous types of sorts. The simplest is Bubble Sort.
int[] arr = new int[5] { 5, 6, 2, 4, 1 };
//bubble sort
for (int i = arr.Length - 1; i > 0; i--)
{
for (int j = 0; j <= i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int highValue = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = highValue;
}
}
}
foreach(int i in arr) Console.Write(i);
I am working on a small assignment where I need to display data (0 to 99 - make sure all the numbers are displayed) randomly in a data grid view of 10 rows and 10 columns. I am unable to figure out the logic that needs to be written for this scenario. Currently I am doing like shown below, two for loops, one for row and other columns and iterating it...
int[] arr = new int[] { 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 58, 69, 60, 61, 62, 63, 64 };
char c = Convert.ToChar(arr.GetValue(new Random().Next(0, 21)));
for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 10; col++)
{
if ((row + col) == 9)
{
this.dataGridView1.Rows[row].Cells[col].Value = string.Format("{0} {1}", c, ((row + 1) * 9));
}
else
{
this.dataGridView1.Rows[row].Cells[col].Value = string.Format("{0} {1}", Convert.ToChar(arr.GetValue(new Random().Next(0, 21))), row * 10 + (col));
System.Threading.Thread.Sleep(15);
}
}
}
Out put:
Expected:
Code for randomly distributing the numbers from 0 to 99.
Thanks in Advance.
By small assignment do you mean school assignment? If so, I don't want to write everything for you, but to point you in the right direction:
The first step I would take initializing an array with a size of 100, and placing the numbers 0-99 on the array. Then, I would find a method for shuffling the array (Linq's OrderBy used with the Random class may be useful to you here). Then, I would iterate through the shuffled array, and place those items inside the grid. I think you have the general grid looping idea down, with the embedded for loops... I'm not sure what the point of the Thread Sleep is, though.
Check with this if you ain't done with your coding...
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < 10; i++)
dt.Columns.Add("col" + i.ToString(), typeof(int));
Random r = new Random();
List<int> l = new List<int>(100);
int temp=0;
for (int i = 9; i >= 0; i--)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < 10; j++)
{
temp = r.Next(99);
if (!l.Contains(temp) || (j == 0 && i == 0))
{
dr["col" + j.ToString()] = temp;
l.Add(temp);
}
else
j -= 1;
}
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
This is what I was finally able to do it. It worked!!!
public static class ThreadSafeRandom
{
[ThreadStatic]
private static Random Local;
public static Random ThisThreadsRandom
{
get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); }
}
}
static class MyExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
The above code does the shuffling of numbers.
var numbers = new List<int>(Enumerable.Range(0, 100));
numbers.Shuffle();
List<int> final = numbers.GetRange(0, 100);
int[,] f = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
f[i, j] = final[(i * 10) + j];
}
}
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (f[i, j] % 9 == 0)
{
this.dataGridView1.Rows[i].Cells[j].Value = string.Format("{0} {1}", charSymbol, f[i, j]);
}
else
{
this.dataGridView1.Rows[i].Cells[j].Value = string.Format("{0} {1}", GetRandomChar(), f[i, j]);
}
}
}