Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Console.WriteLine ("Enter the number of book to delete (1 to {0})", amount);
int posToDelete = Convert.ToInt32 (Console.ReadLine ())-1;
for (int i = posToDelete; i < amount - 1; i++)
b [i] = b [i + 1];
amount--;
// hi! i am new to programming... could anyone please explain this to me in detail
// * what is the use of -1 after the readline
// * explain me the loop plz
//link of the question
//http://practiceexercisescsharp.blogspot.com.es/2013/05/411-books-database.html
fisrt question:
An array is start from 0.
for example: There is an array b includes 4 elements.
b[4] = {1,2,3,4};
so b[0] is 1 and b[3] is 4.
there is no b[4].
if you want to delete the second item(which element is 2) ,you should delete b[1].
so the position is 1.
This is why we use -1 after the readline.
second question:
for (int i = posToDelete; i < amount - 1; i++)
{
b [i] = b [i + 1];
amount--;
}
int = posToDelete is the position of the item we want to delete.
we use the next item to replace it.
this is b[i] = b[i+1];
because we delete one item,the amount need -1;
we also use b[4] for example:
if we delete 2.
initial:[1,2,3,4] amount=4;
loop begin: [1,2,3,4] posDelete is 1,amount is 3;
b[1]=b[2];we use 3 to replace 2;
b[2]=b[3];we use 4 to replace 3;
i is increasing until i is 3;the loop end.
the new array is [1,3,4].
Chances are the indexer of your book array is layout like the following:
book[0] = "Book1" //Where user inputs 1 and then subtract 1 from it to access index 0
Consider the following examples:
book[0] = "Book1" //Book input is 1 less 1 = index of 0
book[1] = "Book2" //Book input is 2 less 1 = index of 1
book[2] = "Book3" //Book input is 3 less 1 = index of 2
Of course the logic of deleting the book is in question, since we are not sure how the book is really arranged in Arrays or Collections. But in your case, you are specifying the position so it can be said that position 1 is
equal to index 0.
Related
This question already has answers here:
How to sort a list so that the same changes would happen in another list?
(3 answers)
Closed 3 months ago.
I have a question:
For example I had a list with 132 and a second list 123
I would want my 132 list.sort but the 123 list to sort like 132:
was:
132
123
After
123
132
Not switch place but if the first element changes position in list 1 so should list 2, please help.
This answer involves writing (or editing an existing) sorting algorithm.
In the example below, I've illustrated a way in Javascript to enhance a simple Bubble Sort algorithm to include a second array to manipulate aswell.
I know the question is for C#, but the same concepts apply.
The arrays need to have the same length, otherwise you will get errors.
// Bubblesort algorithm stolen from https://www.geeksforgeeks.org/bubble-sort/
// edited to include a second array (arr2) that mirrors the sorting of the first array
function swap(arr, xp, yp)
{
var temp = arr[xp];
arr[xp] = arr[yp];
arr[yp] = temp;
}
function bubbleSort( arr, arr2, n)
{
var i, j;
for (i = 0; i < n-1; i++)
{
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr,j,j+1);
// swap the elements of the second array aswell
swap(arr2,j,j+1);
}
}
}
}
// just a function for printing
function printArray(arr, size)
{
var i;
for (i=0; i < size; i++)
document.write(arr[i]+ " ");
document.write("<br />");
}
// the two arrays
var array1 = [5, 1, 4, 2, 8];
var array2 = [2, 3, 4, 5, 6];
var n = 5;
document.write("UnSorted arrays: <br />");
printArray(array1, n);
printArray(array2, n);
bubbleSort(array1, array2, n);
document.write("Sorted arrays: <br />");
printArray(array1, n);
printArray(array2, n);
If you run the above snippet, you see that the '1' in the second position of the first array has moved to the first position.
The second array had a '3' in the second position, which is also swapped to the first position, like the first array did.
Long story short: The second array mirrors the sorting of the first array.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have challenge to solve Sales by Match problem using c# without use List collection ?
*Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are N =7 socks with colors ar=[1,2,1,2,1,3,2] There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2 .*
you can try this code
static int sockMerchant(int n, int[] ar) {
int matchingPairsCount= 0 ;
int[] arr =new int[n];
var ix=0;
for (int i = 0 ; i< ar.Length ; i++)
{
int countPairs = 0 ;
for(int j = 0 ;j< ar.Length ;j++)
{
if(ar[i] == ar[j] && i<j&& (!arr.Contains(i)|| i==0))
{
arr[ix]=j;
ix++;
matchingPairs = matchingPairs + 1 ;
break;
}
}
}
return matchingPairsCount;
}
You can use it using the following code
var ar = new int[] { 1,2,1,2,1,3,2 };
ar.GroupBy( g => g ).Sum( g => Math.Floor( g.Count() / 2.0 ) );
It groups all the items in the array first, and then sums up all pairs. You can try it here
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
for(i = 2000; i >= 0; i -= 40)
{
Console.WriteLine("Your score is {0}", i);
}
i'm trying to count backwards from 2000 by 40 every time someone loops another for loop:
int count = 0;
for (int i = 0; i < random || i > random; i++)
{
count++;
Console.WriteLine("\r\nGuess [{0}]: Please enter a number:", i + 1);
string guessString = Console.ReadLine();
I'm trying to make a scoreboard so every time you don't guess a number correctly, it deducts 40 from 2000.
If I understand correctly, the variables you need are: the amount of guesses, the score, the value to find, and then in each iteration you need the user's input. This can be solved with a single loop.
Here's some pseudocode to show how you can approach this:
remainingGuesses = 50
score = 2000
while remainingGuesses > 0
userInput = GetInput()
if userInput == random
break
remainingGuesses = remainingGuesses - 1;
score = score - 40
return score
You could otherwise go from attempt 0 to 49 and say score = 2000 - 40 * attempts
If I understand correctly from the comments above, you want to deduct 40 points every time someone guesses a number incorrectly.
You can have a variable that holds the score and initialize it with 2000 points and create a function that deducts 40 points each time someone guesses wrong.
int startingPoints = 2000;
public void DeductPoints() {
startingPoints -= 40;
}
And then, you can do some if/else statements to do checks on the score and the corresponding output you want to show to the user.
everyone. I've this small task to do:
There are two sequences of numbers:
A[0], A[1], ... , A[n].
B[0], B[1], ... , B[m].
Do the following operations with the sequence A:
Remove the items whose indices are divisible by B[0].
In the items remained, remove those whose indices are divisible by B[1].
Repeat this process up to B[m].
Output the items finally remained.
Input is like this: (where -1 is delimiter for two sequences A and B)
1 2 4 3 6 5 -1 2 -1
Here goes my code (explanation done via comments):
List<int> result = new List<int>(); // list for sequence A
List<int> values = new List<int>(); // list for holding value to remove
var input = Console.ReadLine().Split().Select(int.Parse).ToArray();
var len = Array.IndexOf(input, -1); // getting index of the first -1 (delimiter)
result = input.ToList(); // converting input array to List
result.RemoveRange(len, input.Length - len); // and deleting everything beyond first delimiter (including it)
for (var i = len + 1; i < input.Length - 1; i++) // for the number of elements in the sequence B
{
for (var j = 0; j < result.Count; j++) // going through all elmnts in sequence A
{
if (j % input[i] == 0) // if index is divisible by B[i]
{
values.Add(result[j]); // adding associated value to List<int> values
}
}
foreach (var value in values) // after all elements in sequence A have been looked upon, now deleting those who apply to criteria
{
result.Remove(value);
}
}
But the problem is that I'm only passing 5/11 tests cases. The 25% is 'Wrong result' and the rest 25% - 'Timed out'. I understand that my code is probably very badly written, but I really can't get to understand how to improve it.
So, if someone more experienced could explain (clarify) next points to me it would be very cool:
1. Am I doing parsing from the console input right? I feel like it could be done in a more elegant/efficient way.
2. Is my logic of getting value which apply to criteria and then storing them for later deleting is efficient in terms of performance? Or is there any other way to do it?
3. Why is this code not passing all test-cases or how would you change it in order to pass all of them?
I'm writing the answer once again, since I have misunderstood the problem completely. So undoubtly the problem in your code is a removal of elements. Let's try to avoid that. Let's try to make a new array C, where you can store all the correct numbers that should be left in the A array after each removal. So if index id is not divisible by B[i], you should add A[id] to the array C. Then, after checking all the indices with the B[i] value, you should replace the array A with the array C and do the same for B[i + 1]. Repeat until you reach the end of the array B.
The algorithm:
1. For each value in B:
2. For each id from 1 to length(A):
3. If id % value != 0, add A[id] to C
4. A = C
5. Return A.
EDIT: Be sure to make a new array C for each iteration of the 1. loop (or clear C after replacing A with it)
This question already has answers here:
Add all natural numbers that are multiples of 3 and 5 : What is the bug in the following code
(5 answers)
Project Euler: Problem 1 (Possible refactorings and run time optimizations)
(13 answers)
Closed 9 years ago.
Project Euler - Problem 1: Find the sum of all the multiples of 3 or 5 below 1000.
Looking through the questions here about the same problem I assume the way I tried to solve is is quite bad. What is the best way to solve this?
And my other question: The sum value doesn't match the answer. I think the problem is that when I use foreach to write out the list value its starts from 705 instead of 3, but I have no idea why. I would appreciate if someone could explain it to me.
This is the code that I'm using now:
List<int> numbers = new List<int>();
for (int i = 3; i < 1000; i += 3)
{
numbers.Add(i);
}
for (int j = 5; j < 1000; j += 5)
{
numbers.Add(j);
}
numbers.ForEach(Console.WriteLine);
int sum1 = numbers.Sum();
Console.WriteLine(sum1);
Console.ReadLine();
This is because numbers allows duplicates. Note that you are going to have some duplicates, there - for example, numbers 15, 30, 45, and so on, will be added twice.
Replace
List<int> numbers = new List<int>();
with
ISet<int> numbers = new HashSet<int>();
and it's going to work because a HashSet won't allow duplicate values.
This is the first problem on Project Euler.
Personally, I used a one liner :
Enumerable.Range(0, 1000).Where(n => n % 3 == 0 || n % 5 == 0).Sum()
But you can also use the long way for more readability :
int sum = 0;
for (int i = 0; i < 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
{
sum = sum + i;
}
}
If you don't know how the modulo (%) operator works, I suggest you read it here
If you need more details about the problem itself, just create an account on Project Euler, enter the answer, and read the Problem Overview.
You're not accounting for numbers that are both multiples of 3 and 5
If I were you, I'd have something like the following
for(int i=1; i<1000; i++)
{
if(i is a multiple of 15)
//account for 15
else if(i is a multiple of 3)
//account for 3
else if(i is a multiple of 5)
//account for 5
}
The reason your output starts with 705 is because your list of numbers is quite long (532 numbers to be exact). Your Console window can only contain a couple of lines before it starts scrolling.
So you do start with the number 3, it's just not visible.
As others have pointed out, the issue is that your code counts multiples of 15 twice. Of course, this task is pretty easy using Linq's Range and Where methods:
var numbers = Enumerable.Range(0, 1000)
.Where(n => n % 3 == 0 || n % 5 == 0);
foreach(var n in numbers)
{
Console.WriteLine(n);
}
var sum = numbers.Sum();
Console.WriteLine(sum);
Console.ReadLine();
You have duplicate values in the list. Thats why total sum is invalid. You better change the Data Structure to HashSet which not allow duplicates.
If you can't do that or you have to proceed with this way, try below
call numbers = numbers.Distinct().ToList(); before numbers.ForEach(Console.WriteLine);
I think the problem is that when I use foreach to write out the list
value its starts from 705 instead of 3, but I have no idea why.
Problem is duplicate values, foreach will print correctly but you may not able to scroll console to beginning of printing.
try Console.WriteLine(string.Join(",", numbers));
You could also solve it with Linq. Use Enumerable.Range to get all numbers between 0 and 999 (inclusive). Then use Where to filter those out which are divisible by 3 or divisible by 5. Finally use Sum.