c# arrays with counter controlled for loop - c#

Good day
I have have this assignment at school about a factious company that measures covid-19 temperatures. We are asked to design a c# program that will perform tasks with the stats.
The array of collected temperatures from 50 people:
double[] temperatures = new double[50] {36.7, 36.5, 36.6, 36.9, 37.0, 36.2, 36.4, 36.8, 37.2, 37.4,
36.2, 36.6, 36.7, 36.9, 36.8, 36.7, 36.5, 37.0, 36.3, 36.7,
37.6, 37.1, 37.8, 38.2, 36.7, 36.8, 36.5, 36.8, 37.1, 37.9,
36.0, 35.5, 36.8, 36.9, 37.0, 37.8, 36.4, 36.8, 36.7, 36.1,
37.2, 37.1, 38.5, 37.4, 37.9, 38.0, 35.9, 37.0, 36.7, 36.5};
Body Temperature Categories and Body Temperature Ranges (in Celsius)
Cold: Lower than 36.5 - Normal: From 36.5 to 37.4 - Hot: Higher than 37.4
Problem: find out how many element in the Array fall under 'normal' body temperature.
The required method to solve the problem is 'counter controlled for loop'.
Thanks in advance!
double normalTemp = temperatures[0];
double hotTemp = temperatures[0];
double coldTemp = temperatures[0];
for (double index = 0; index < temperatures.Length; index++)
{
if (index >= 36.5 && normalTemp <= 37.4)
{
normalTemp = index;
}
}
Console.WriteLine("Number of Normal Temperatures: {0}", normalTemp);
This is what I've tried, cant seem to find a way

You are not checking the temperature itself, but checking on the index of the array instead and in your declaration of the double normalTemp = temperatures[0]; you are assigning the first value in the array which is incorrect.
int normalTemp = 0;
for (int index = 0; index < temperatures.Length; index++)
{
if (temperatures[index] >= 36.5 && temperatures[index] <= 37.4)
{
++normalTemp;
}
}
Console.WriteLine("Number of Normal Temperatures: {0}", normalTemp);

Your code has an obvious bug! You are iterating through indices of your array and then trying to use the index instead of the underlying array element which would be temperatures[index]. Also array index is an int so it's pointless to declare it as a double! So your criteria (the if block) should look like this after the fix:
if (temperatures[index] >= 36.5 && temperatures[index] <= 37.4)
{
normalTemp++;
}

int normalTemp = 0;
for (int index = 0; index < temperatures.Length; index++)
{
if (tempretures[index] >= 36.5 && tempretures[index] <= 37.4)
{
normalTemp ++;
}
}
Console.WriteLine("Number of Normal Temperatures: {0}", normalTemp);

Related

Ask user to apply columns and rows for a 2d array

//Ask user how many woodchucks to simulate
while(!validNumber)
{
Write("How many woodchucks would you like to simulate? (1 - 100) ");
int.TryParse(ReadLine(), out woodchuckSim);
if((woodchuckSim <= 0) || (woodchuckSim > 100))
{
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
}
if((woodchuckSim >= 1) && (woodchuckSim <= 100))
{
validNumber = true;
}
}
//Ask user how many days to simulate
while(!validDays)
{
Write("\nHow many days would you like to simulate? (1 - 10) ");
int.TryParse(ReadLine(), out numOfDays);
if((numOfDays <= 0) || (numOfDays > 10))
{
WriteLine("Please enter a positive whole number between 1 and 10: ");
}
if((numOfDays >= 1) && (numOfDays <= 10))
{
validDays = true;
}
}
//Using random class populate each cell between 1 and 50 that represents # of pieces of wood chucked by specific woodchuck on that specific day
int[,] sim = new int[woodchuckSim, numOfDays];
WriteLine($"{woodchuckSim} {numOfDays}");
for (int i = 0; i < sim.Length; i++)
{
for (int j = 0; j < sim.Length; j++)
{
sim[i, j] = ran1.Next(1, 50);
WriteLine(sim[i, j]);
}
}
WriteLine("Press any key to continue...");
ReadLine();
So this is my code so far, and I keep getting a "Index was outside the bounds of the array" error and I'm basically trying to ask the user to input the numbers of woodchucks and the number of days then populate the 2d array with random numbers. Any help will be really appreciated, and btw I am a beginner in programming. Thanks!
As Quercus already said, Length property refers to overall size of the array and array.GetLength(index) should be used instead.
Moreover, since you are a beginner in programming as you mentioned, I would like to tell you as an advice that it would be better to use if-else statement in this case:
if((woodchuckSim <= 0) || (woodchuckSim > 100)) {
WriteLine("\nPlease enter a correct amount of woodchucks to simulate: ");
} else {
validNumber = true;
}
If-else statement is pretty basic but important concept in programming and since your if hypotheses are mutual exclusive you can use it here for a nicer code.
You have incorrect cycle bounds. sim.Length is an overall size of array, which is woodchuckSim * numOfDays.
To get size of each dimension use sim.GetLength(0) and sim.GetLength(1) respectively.
Length is the size of the first dimension of the array - the number of Woodchucks in your case. For the size of the other dimensions, you could use GetLength(index):
for (int i = 0; i < sim.GetLength(0); i++)
{
for (int j = 0; j < sim.GetLength(1); j++)
{
sim[i, j] = ran1.Next(1, 50);
WriteLine(sim[i, j]);
}
}

Output least number of slices required to sort an array in C#

I want to output the number of slices required to slice an unsorted array of n distinct integers into one or more slices and sort them so that when the sorted slices are joined back (in the same order), it gives the original array in the sorted order.
For example,
Given array = [2,1,6,4,3,7]
If you slice the given array like this : [2,1] [6,4,3] [7] Then sort these individually like this: [1,2] [3,4,6] [7] And finally, join them back like this : [1,2,3,4,6,7] You get the original array in sorted order. So, the number of slices is 3
I tried to search it in Stack Overflow/Google and found the following solution but it doesn't seem to work for the above input (returns 2 instead of 3).
public int solution(int[] A)
{
if (A.Length < 3) return A.Length;
    int count = 0;
    for (int i = 1; i < A.Length; i++)
    {
         if (A[i] > A[i - 1]) count += 1;
    }
    return count;
}
Can anyone suggest how can we approach this problem and appropriately solve this in C#
public int solution(int[] A) {
int l = A.length;
if (l < 3) return l;
int count = 0;
for (int i = 1; i < l; i++) {
if (A[i] > A[i - 1]) count += 1;
}
if (A[l - 1] > A[l - 2]) {
count += 1;
}
return count;
}

Find N consecutive integers on a array, whose sum(of consecutive integers) S is a integer that i have

explanation
I have been staring at the problem for a few of minutes.
And i did some research before i ask this quest , but it were in different cases and they didn't included what i really need.
I found this piece of code in SO.
static int GetLargestSum(int[] array, int n, int sum)
{
int largestSum = 0;
int previousSum = 0;
for (int i = 0; i <= array.Length - n; i++)
{
if (i == 0)
{
for (int j = 0; j < n; j++)
{
largestSum += array[j];
}
previousSum = largestSum;
}
else
{
int currentSum = previousSum - array[i - 1] + array[i + n - 1];
if (currentSum > largestSum)
{
largestSum = currentSum;
}
previousSum = currentSum;
}
}
return largestSum;
}
And yes this works but if works for only the largest sum.
I tried to modify it to add the sum var into the code but that didn't actually went that well.
So i would really appreciate if someone helps me, bcs i am stuck in this algorithm.
Thank you!
The way to solve it would be to iterate over each segment of the array and evaluate its sum. A crude first draft would look something like this
public static int ConsecutiveSumArrangements(int[] vals, int count, int sum)
{
var number = 0;
for (int i = 0; i < (vals.Length - count); i++)
{
var segSum = vals.Skip(i).Take(count).Sum();
if (segSum == sum)
{
number++;
}
}
return number;
}
Maybe it is easier think in another way than try to correct this code. An idea is using slide window. Pseudo code look like
sum = 0
sol = 0
start = 0
end = 0
// sum of the first m elements
while end < m
sum = sum + s[end]
end = end + 1
If sum == d
sol = sol + 1
while end < n
sum = sum + s[end]
sum = sum - s[start]
end = end + 1
start = start + 1
if sum == d
sol = sol + 1
// in the loop we add the next element and subtract the first element
//so, we keep the length of m elements

Where is the flaw in my algorithm to find the size of the largest subarray with each element within dista

For example, given the array A={1,3,2,17,10}, the answer is 3 because the collection {1,2,3} is the largest collection such that for some a in the collection, every element in the collection is the range [a, a + 4] (that's a+4 inclusive).
My algorithm is like
int[] toys = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
Array.Sort(toys);
int max_together = 0;
for(int i = 0; i < toys.Length; ++i)
{
int plus_four = toys[i] + 4;
int j = i + 1;
for(; j < toys.Length && toys[j] <= plus_four; ++j);
int span = j - i;
if(span > max_together)
{
max_together = span;
}
}
and it's failing most of the test cases.
Or maybe I'm reading https://www.hackerrank.com/challenges/priyanka-and-toys?h_r=next-challenge&h_v=zen incorrectly ...
My full solution is
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
Console.ReadLine(); // N
int[] toys = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
Array.Sort(toys);
int max_together = 0;
for(int i = 0; i < toys.Length; ++i)
{
int plus_four = toys[i] + 4;
int j = i + 1;
for(; j < toys.Length && toys[j] <= plus_four; ++j);
int span = j - i;
if(span > max_together)
{
max_together = span;
}
}
Console.WriteLine(1 + (toys.Length - max_together));
}
}
On quick look i found that you are trying to find maximum span on sorted array(i.e. 1,2,3,10,17) whereas the test cases wants you to find the maximum span on given array(i.e. 1,3,2,17,10), the one before sorting.
if you buy 1 toy whose weight is w1 ,you get all toys whose weight is in between [w1,w1+4] for free. The question asks you to find minimum number of toys you need to buy ,so that you get all toys in the input. In this example A={1,3,2,17,10}, the answer is 3 because you need to buy toy 1(or 2 or 3) ,17 and 10.
Java code
int num[] = {1,3,2,17,10};
Arrays.sort(num);
int result=1;
int lastToy=num[0];
for(int i=1;i<n;i++)
{
if(num[i] > lastToy+4)
{
result++;
lastToy= num[i];
}
}

creating an array of indexes that has the size of the loop that fills the data

This is the method im having issues with
this is the code with isssues
this is code im having issues with
static void FindDuplicates(int maxValue, int[]totalOfScores) {
int finalWinner = 0;
int i = 0;
int[] WinnerIndex = new int [totalOfScores.Length];
for (int g = 0; g < totalOfScores.Length; g++) {
if (totalOfScores[g] == maxValue)
for (i = 0; i < WinnerIndex.Length; i++) {
WinnerIndex[i] = g;
finalWinner = WinnerIndex[i];
Console.WriteLine("\n\nThe Highest Scoring comp was comp Number {0} With a total score of {1}", finalWinner + 1, maxValue);
}
}
}
If your question is on the dynamic array size, do not use array, use List instead. Or use Array.Resize(). But if I understand your goal correctly, you are trying to list all competitors that have the highest score, in this example competitors 3 and 4 you don't really need array for the results at all. Instead do:
static void FindDuplicates(int maxValue, int[] totalOfScores){
for (int i = 0; i < totalOfScores.Length; i++) {
if (totalOfScores[i] == maxValue){
Console.WriteLine("\n\nThe Highest Scoring comp was comp Number {0} With a total score of {1}", i+1, maxValue);
}
}
}
By the way, I would rename FindDuplicates as FindAllWinners (or then I have misunderstood your intentions).

Categories

Resources