How to find certain target in jagged array with C# - c#

So I set up jagged arrays and got the question from the user.
Have finished setting up the target value based on the user's answer.
But cannot show the boolean value whether the target value is in the jagged array when I used the loop.
It only shows the "True" value whether the target is in the jagged array or not.
class HW03_04
{
static void Main()
{
int[][] array =
{
new int[] {9, 6, 48, 15, 23},
new int[] {7, 56, 23, 4, 62},
new int[] {13, 25, 7, 56, 2},
new int[] {84, 30, 5, 0, 17}
};
Console.Write("What is your target value? ");
int targetValue = Convert.ToInt32(Console.ReadLine());
bool answer = Convert.ToBoolean(targetValue);
Console.WriteLine("{0}", answer);
}
static bool target(int[][] arrSearch, int targetValue)
{
int size = arrSearch.Length;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < arrSearch[i].Length; j++)
{
if (arrSearch[i][j] == targetValue)
{
return true;
}
}
}
return false;
}
}
Please help fixing the loop to show proper boolean value.

You need to call your function, change your line to:
bool answer = target(array, targetValue);

Related

How do I compare two arrays to find common elements (random numbers vs. user input)?

I'm trying to create a lottery number program that accepts 10 guesses from the user between the numbers 1-25. The user guesses are stored in the user array. If the user enters the wrong value (< 1 or > 25) the number will not be stored within the user array. The program stores 10 random numbers in another array. So, two arrays in total.
How to compare the two arrays to find common elements, to let the user know how many correct guesses the user made compared to the random numbers array? For this part, I am only allowed to use loops.
I have tried using continue; below the first If, but that messes things up.
I have tried to move the ending curly brackets for the first for-loop to below the first If, but that also messes things up at the "compare the two arrays" part.
//User array
int[] användarTal = new int[10];
//Random numbers array
int[] slumpadeTal = new int[10];
//Generator for 10 random numbers.
Random randomerare = new Random();
//Foor-loop for storing user's 10 guesses in the user array.
for (int i = 0; i < användarTal.Length; i++)
{
Console.Write("Enter your guess: ");
string input = Console.ReadLine();
int num = Convert.ToInt32(input);
användarTal[i] = num;
//If the user enters wrong value
if (num < 1 || num > 25)
{
Console.WriteLine("Wrong! You must enter a number between 1-25!");
användarTal[i] = i--; //Wrong number will not be stored in the user array.
}
// continue;
// }
//For-loop for storing and writing out the 10 random numbers.
for (int j = 0; j < slumpadeTal.Length; j++)
{
Console.WriteLine(randomerare.Next(1, 26));
// Checking if the two arrays have any common numbers
if (användarTal[i] == slumpadeTal[j])
{
Console.WriteLine(användarTal[i]);
}
}
I found this solution which I have tried to implement into my program, but I can't get the program to run the way it's supposed to.
int[] arr1 = { 12, 5, 45, 47, 22, 10 };
int[] arr2 = { 23, 45, 10, 58, 78, 77, 46 };
for (int i = 0; i < arr1.Length; i++)
{
for (int j = 0; j < arr2.Length; j++)
{
if (arr1[i] == arr2[j])
{
Console.WriteLine(arr1[i]);
}
}
}
int[] arr1 = { 12, 5, 45, 47, 22, 10 };
int[] arr2 = { 23, 45, 10, 58, 78, 77, 46 };
for (int i = 0; i < arr1.Length; i++)
{
for (int j = 0; j < arr2.Length; j++)
{
if (arr1[i] == arr2[j])
{
Console.WriteLine(arr1[i]);
}
}
}
I dont see an issue with this code, seems like it should execute fine.
However you can optimise this using Linq
int[] array1 = { 12, 5, 45, 47, 22, 10 };
int[] array2 = { 23, 45, 10, 58, 78, 77, 46 };
int[] commonElements = array1.Intersect(array2);
Console.WriteLine("Common Elements: {0}", string.Join(",", commonElements));
See https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.intersect?view=net-7.0
It seems that you want to store and guess unique numbers only.
To be sure that numbers are unique, let's use HashSet<int> instead
of arrays:
using System.Linq;
...
// Random numbers array
HashSet<int> slumpadeTal = Enumerable
.Range(1, 25)
.OrderBy(item => Random.Shared.NextDouble())
.Take(10)
.ToHashSet();
Then let's ask user to guess
HashSet<int> användarTal = new HashSet<int>();
while (användarTal.Count < slumpadeTal.Count) {
while (true) {
Console.Write("Enter your guess: ");
if (int.TryParse(Console.ReadLine(), out int guess) &&
guess >= 1 && guess <= 25) {
användarTal.Add(guess);
break;
}
Console.WriteLine("Incorrect guess; it should be 1..25");
}
}
Having both collections filled in you can easily compare them
int guessedRight = slumpadeTal
.Count(item => slumpadeTal.Contains(item));

Quick Sort working for small input - Need Fresh Pair of eye to find bug

I know there are lot of resources on QuickSort but I need a fresh pair of eyes to catch a bug. I have written the QuickSort Algorithm, but it works for small array, but with large array it throws invalid result (last 3-4 elements didn't sort at all).
Test Case 1:
Input: { 5, 7, 2, 8, 10, 15, 14, 16, 16, 19, 20, 19, 3, 1, 5 }
OutPut: 1,2,3,5,10,14,15,16,16,19,20,19,7,5,8 (WRONG)
Test Case 2:
Input: { 5,1,15,2,8}
Output: 1,2,5,8,15
[TestMethod]
public void QuickSort_test()
{
//input
int[] input = InputArray();
//Algo
int n = input.Length-1;
QuickSort(0,n,input);
//matching result
bool isSorted = IsSorted(input);
Assert.AreEqual(true, isSorted);
}
private void QuickSort(int low, int high, int[] arr)
{
if(low< high)
{
//finding pivot correct index
int idxPivot = Partition(low, high, arr);
//Recursive QuickSort, on elements left on pivot and elements right on pivot
int h = high - idxPivot;
QuickSort(low, idxPivot - 1, arr); //left of pivot
QuickSort(idxPivot + 1, h, arr); //right of pivot
}
}
private int Partition(int low, int high, int[] arr)
{
int pivot = arr[high];
int idxp = low - 1; //smaller than pivot
for (int i = low; i < high; i++) //since element at high is already pivot, no need to run loop till that
{
if(arr[i]< pivot) //current ele < pivot . increment pivotsmallerIndex and swap current element with pivot smaller index
// hence making current element as the smaller element from pivot
{
idxp++;
//swapping
int temp = arr[idxp];
arr[idxp] = arr[i];
arr[i] = temp;
}
}
//idxp contains the last smallest element from the pivot
//so swapping pivot with the next element of idxp
int temp1 = arr[idxp + 1];
arr[idxp+1] = pivot;
arr[high] = temp1;
//return index of pivot, since it is added at idxp+1 now
return idxp + 1;
}
public int[] InputArray()
{
return new int[] { 5, 7, 2, 8, 10, 15, 14, 16, 16, 19, 20, 19, 3, 1, 5 };
//return new int[] { 5,1,15,2,8};
}

how to get the array containing minimum difference array elements

[Image of the actual problem]
we have to choose the best item/items based on input3 which is items to be selected. the choice should be such that we don't take maximum item always. Instead we take items which are not having much difference.
input1: total items
input2: array of items
input3: items to be selected
Scenario 1:
input: 6, {44,55,605,100,154,190}, 1
output should be: {605}
input: 5, {15,85,32,31,2}, 2
output should be: {32,31}
as we increase the number of items to be selected, output should have more item in selected with minimum difference.
Below is the code i am trying, i am new to this please help:
i am stuck how to make this dynamic.
public static int[] Find(int totalItems, int[] values, int totalToBeSelected)
{
var i = values;
int[] results = new int[totalToBeSelected];
var resultList = new List<int>();
if (totalToBeSelected == 1)
{
resultList.Add(values.Max());
return resultList.ToArray();
}
Array.Sort(i);
var minmumDiff = (i[0] - i[1]) * -1;
for (int k = 1; k < i.Length; k++)
{
var differnce = i[k] - i[k - 1];
if (differnce < minmumDiff)
{
resultList.Add(i[k]);
resultList.Add(i[k - 1]);
minmumDiff = differnce;
}
}
return resultList.ToArray();
}
You can look at this function.
public static int[] Find(int totalItems, int[] values, int totalToBeSelected)
{
Array.Sort(values);
Array.Reverse(values); // We need any value greater than max items diff. Max array item (first item after the sort) enough for it.
int diff = values[0];
int indx = 0;
for (int i = 0; i < totalItems - totalToBeSelected +1; i++)
{
int temp_diff = values[i] - values[i + totalToBeSelected - 1]; // We are looking for any items group that max and min value difference is minimum
if (temp_diff < diff )
{
diff = temp_diff;
indx = i;
}
}
int[] results = new int[totalToBeSelected];
Array.Copy(values, indx, results, 0, totalToBeSelected);
return results;
}
Sample:
Find( 6, new int[] { 44, 55, 605, 100, 154, 190 }, 1 );
Out: { 605 }
Find( 5, new int[] { 15, 85, 32, 31, 2 }, 2 );
Out: { 32, 31 }
The conditions in the question are unclear, some assumptions had to be made.
class Program
{
static void Main(string[] args)
{
var items = new[] {12,14,22,24,6};//new[] { 15, 85, 32, 31, 2};//new[] { 44, 55, 605, 100, 154, 190 };
var totalItems = items.Count();
var numberOfItemsToSelect = 3;
var result = Find(totalItems, items, numberOfItemsToSelect);
PrintList(result);
Console.ReadLine();
}
static void PrintList(IEnumerable<int> scoreList)
{
foreach (var score in scoreList)
{
Console.Write(score);
Console.Write(" ");
}
}
public static int[] Find(int totalItems, int[]values, int totalTobeSelected)
{
var result = new List<int>();
if (totalTobeSelected <= 1)
{
result.Add(values.Max());
}
else if (totalTobeSelected == totalItems)
{
result.AddRange(values.OrderBy(i => i).ToList());
}
else
{
var mainSet = values.OrderBy(i => i).ToList();
var setDic = new Dictionary<int, IEnumerable<int>>();
for (int i = 0; (totalItems - i >= totalTobeSelected); i++)
{
var set = mainSet.GetRange(i, totalTobeSelected);
//Inside a set, we choose the difference between the first and the second number
// ex: set = {2, 4, 9} => diff = |2-4| = 2.
var diff = Math.Abs(set[0] - set[1]);
// given two sets with the same diff, we select the first one base on the sort order of the main set:
// ex: main set = {2,4,8,10}. Both {2,4} and {6,8} have a diff of 2 so we select {2,4}
if (setDic.ContainsKey(diff)) continue;
setDic.Add(diff, set);
}
if (setDic.Count > 0)
{
var minKey = setDic.Keys.Min();
result.AddRange(setDic[minKey]);
}
}
return result.ToArray();
}
}

How to reverse an array using three separate methods in C#

I'm currently going through an ebook in order to learn C# and I am currently at a place where I am stuck. I feel that once I have pushed through and understand this next bit, it will really accelerate my understanding and learning as I move on to classes next.
The current challenge I face I must do the following :
Make a program that uses methods to reverse an array.
Create three methods: one to create the array, one to print the array and one to reverse the array.
Ideally it would allow the user to input the desired length of the array.
Not allowed to use the reverse array method.
This is the code I have gotten so far but I'm extremely stuck on how to create the reverse method and I feel like what I currently have isn't what is required either. I just need that extra push here for it to click in place and for me to get the understanding I need. Feel free to just positions hints / tips / advice as oppose to the solution if you so wish.
Thank you all.
using System;
namespace Using_methods_to_reverse_an_array
{
class Program
{
static int[] CreateArray()
{
int[] array = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return array;
}
static void PrintNumbers()
{
foreach (int numbers in CreateArray())
{
Console.WriteLine(numbers);
}
}
static void Main(string[] args)
{
int[] numbers = CreateArray();
PrintNumbers();
Console.ReadLine();
}
}
}
static int[] Reverse(int[] arr){
int [] arr2 = new int[arr.Length];
for (int i = arr.Length - 1, i2 = 0; i >= 0; i--, i2++)
{
arr2[i2] = arr[i];
}
return arr2;
}
static void PrintNumbers(int[] arr)
{
foreach (int numbers in arr)
{
Console.WriteLine(numbers);
}
}
static void Main(){
int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] arr2 = Reverse(arr);
PrintNumbers(arr2);
}
prints
10
9
8
7
6
5
4
3
2
1
Thanks a ton for the help everyone, after doing some more Googling and tests my final product is this :
using System;
namespace Using_methods_to_reverse_an_array
{
class Program
{
static int[] CreateArray()
{
int[] array = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return array;
}
static void PrintNumbers(int[] array)
{
foreach (int numbers in array )
{
Console.WriteLine(numbers);
}
}
static void ReverseNumbers(int[] array)
{
for (int i = 0; i < array.Length/2; i++)
{
int temp = array[i];
array[i] = array[array.Length - i - 1];
array[array.Length - i - 1] = temp;
}
}
static void Main(string[] args)
{
int[] numbers = CreateArray();
ReverseNumbers(numbers);
PrintNumbers(numbers);
Console.ReadLine();
}
}
}
Maybe I misunderstood, but I think this should do it:
class Program
{
static int[] CreateArray()
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
return array;
}
//I changed this to receive an input array
static void PrintNumbers( int[] inputArray)
{
foreach (int numbers in inputArray)
{
Console.WriteLine(numbers);
}
}
//this function should reverse any array passed to it
static void ReverseArray(int[] inputArray)
{
int len = inputArray.Length;
int[] newArray = new int[len];
foreach (int i in inputArray)
{
newArray[i] = inputArray[len - 1];
len--;
}
}
static void Main(string[] args)
{
int[] numbers = CreateArray();
PrintNumbers(numbers);
ReverseArray(numbers);
//Console.ReadLine();
}
}

How to get the second highest number in an array in Visual C#?

I have an array of ints. I want to get the second highest number in that array. Is there an easy way to do this?
Try this (using LINQ):
int secondHighest = (from number in numbers
orderby number descending
select number).Skip(1).First();
You could sort the array and choose the item at the second index, but the following O(n) loop will be much faster.
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int largest = int.MinValue;
int second = int.MinValue;
foreach (int i in myArray)
{
if (i > largest)
{
second = largest;
largest = i;
}
else if (i > second)
second = i;
}
System.Console.WriteLine(second);
Yes, have 2 vars (first and second) passthrough the array and each time compair what you get with this two cells (always putting the highest on first and the 2nd highest on second)
with one pass you will get the 2nd higher on the second var.
You don't specify if you want to do this with the minimum complexity.
Assuming your array is unsorted, please see: How to find the kth largest element in an unsorted array of length n in O(n)?
To find Kth largest element in an unsorted array: Build a max heap in O(n). Now remove k elements from the heap; where each removal costs log(n) time to maintain the heap. Total time complexity = O(n + klogn)
To understand building Max heap in O(n) see Binary heap
max1=0;
max2=0;
for( int i=0; i < a.Length; i++)
{
if (arr[i]> max1)
{
max2=max1;
max1=arr[i];
}
else
{
if (a[i]!= max1) && ( a[i] > max2)
max2[i]=arr[i];
}
}
Getting the max number first, once the max is changed do a comparison against the second high number to see if it needs to swapped. The second if statement checks if the value is less than the max and is greater than the second highest value. Because of the short circuit, if the first condition fails then it exits the if and skips
static void Main(string[] args)
{
//int[] arr = new int[10] { 9, 4, 6, 2, 11, 100, 53, 23, 72, 81 };
int[] arr = { 1, 8, 4, 5, 12, 2, 5, 6, 7, 1, 90, 100, 56, 8, 34 };
int MaxNum = 0;
int SecNum = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] > MaxNum)
{
if (MaxNum > SecNum) { SecNum = MaxNum; }
MaxNum = arr[i];
}
if (arr[i] < MaxNum && arr[i] > SecNum)
{
SecNum = arr[i];
}
}
Console.WriteLine("Highest Num: {0}. Second Highest Num {1}.", MaxNum, SecNum);
Console.ReadLine();
}
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int num1=0, temp=0;
for (int i = 0; i < myArray.Length; i++)
{
if (myArray[i] >= num1)
{
num1 = myArray[i];
}
else if ((myArray[i] < num1) && (myArray[i] > temp))
{
temp = myArray[i];
}
}
Console.WriteLine("The Largest Number is: " + num1);
Console.WriteLine("The Second Highest Number is: " + temp);
int[] arr = { 1, 8, 4, 5, 12, 2, 5, 6, 7, 1, 90, 100, 56, 8, 34 };
int first, second;
// Assuming the array has at least one element:
first = second = arr[0];
for(int i = 1; i < arr.Length; ++i)
{
if (first < arr[i])
{
// 'first' now contains the 2nd largest number encountered thus far:
second = first;
first = arr[i];
}
}
MessageBox.Show(second.ToString());
static void Main(string[] args)
{
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5,12,11,14 };
int num1 = 0, temp = 0;
for (int i = 0; i < myArray.Length; i++)
{
if (myArray[i] >= num1)
{
temp = num1;
num1 = myArray[i];
}
else if ((myArray[i] < num1) && (myArray[i] > temp))
{
temp = myArray[i];
}
}
Console.WriteLine("The Largest Number is: " + num1);
Console.WriteLine("The Second Highest Number is: " + temp);
Console.ReadKey();
}
There are two possibilities to find second highest number from an array.
1). Find second max number from an array.
int[] myArray = { 0, 2, 3, 8, 13};
int max = 0;
int second_max = 0;
foreach (int arr in myArray) {
if (arr > max)
{
second_max = max;
max = arr;
}
}
Console.WriteLine("First highest number is: "+max);
Console.WriteLine("Second highest number is: " + second_max);
2). Find second max number with the smallest complexity from an array.
int[] myArray = { 0, 2, 3, 13, 8};//smaller number is given after
larger number
int max = 0;
int second_max = 0;
foreach (int arr in myArray) {
if (arr > max)
{
second_max = max;
max = arr;
}
else if (arr > second_max)
{
second_max = arr;
}
}
Console.WriteLine("First highest number is: "+max);
Console.WriteLine("Second highest number is: " + second_max);

Categories

Resources