Created
March 31, 2011 16:35
-
-
Save DanielRapp/896710 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
class MainClass | |
{ | |
// Write the contents of the array 'arr' and separate each value with 'separator' | |
static void WriteLineArray(int[] arr, string separator) | |
{ | |
for (int i = 0; i < arr.Length; i++) { | |
if (i == arr.Length - 1) separator = ""; | |
Console.Write(arr[i] + separator); | |
} | |
Console.Write("\n"); | |
} | |
// Fill the array 'arr' with random numbers between params min and max | |
static void RandomFill(int[] arr, int min, int max) | |
{ | |
Random rand = new Random(); | |
// Fill array 'rands' with random numbers between min and max inclusive | |
for (int i = 0; i < arr.Length; i++) | |
arr[i] = min + rand.Next(max + 1 - min); | |
} | |
// Sort the array 'arr' with the bubble sort algorithm | |
static void SortArray(int[] arr) | |
{ | |
for (int i = 0; i < arr.Length; i++) { | |
for (int j = i+1; j < arr.Length; j++) { | |
if (arr[i] > arr[j]) { | |
// Swap i & j | |
int temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
} | |
} | |
} | |
public static void Main (string[] args) | |
{ | |
Console.Write("Hur många slumptal i intervallet 0-999 önskar? "); | |
int nums = Int32.Parse(Console.ReadLine()); | |
int[] rands = new int[nums]; | |
// Fill array with integers between 0 and 999 inclusive | |
RandomFill(rands, 0, 999); | |
// Sort 'rands' | |
SortArray(rands); | |
// Print array values | |
Console.WriteLine("Här är de slumpade talen: "); | |
WriteLineArray(rands, ", "); | |
// Find the first instance of a number above 500 in 'rands' | |
int pivot = 0; | |
do { | |
pivot++; | |
} while (rands[pivot] < 500); | |
// Create two new arrays that will hold all numbers < 500 and >= 500 in rands | |
int bottomIndex = pivot, | |
topIndex = rands.Length - pivot; | |
int[] bottomRands = new int[bottomIndex], | |
topRands = new int[topIndex]; | |
// Copy all numbers in 'rands' that are < 500 into a new array | |
Array.Copy(rands, 0, bottomRands, 0, bottomIndex); | |
// Copy all numbers in 'rands' that are >= 500 into a new array | |
Array.Copy(rands, bottomIndex, topRands, 0, topIndex); | |
// Print 'bottomRands' and 'topRands' | |
Console.WriteLine("Dessa {0} tal är i intervallet 0-499", bottomIndex); | |
WriteLineArray(bottomRands, ", "); | |
Console.WriteLine("Dessa {0} tal är i intervallet 500-999", topIndex); | |
WriteLineArray(topRands, ", "); | |
Console.ReadKey(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment