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 6 years ago.
Improve this question
Good morning :) I'm working on C# and I want to write a code that can calculate the less number of hops from any point to particular point, as a picture show
click here to show the picture
I have points from 1 to 12, so if I want to calculate the less number of hops from the point 12 to 1 it will be 1 with counterclockwise not 11 hops with clockwise.
another example to clarify my question, if I want to calculate the less number of hops from the point 11 to 4 it will be 5 with counterclockwise not 6 hops with clockwise. notice : the number of points may be an odd number.
I hope you understand my question ..
Try clockwise, anticlockwise and take minimum:
private static int Hops(int a, int b) {
return Math.Min((12 + a - b) % 12, (12 + b - a) % 12);
}
Tests:
// 5
Console.WriteLine(Hops(11, 4));
// 1
Console.WriteLine(Hops(12, 1));
Edit: As Matthew Watson has mentioned in comments, you may want to know whether it clockwise or anticlockwise:
private static int ClockwiseHops(int a, int b) {
return (12 + b - a) % 12;
}
private static int AntiClockwiseHops(int a, int b) {
return (12 + a - b) % 12;
}
private static int Hops(int a, int b) {
return Math.Min(ClockwiseHops(a, b), AntiClockwiseHops(a, b));
}
private static String Solve(int a, int b) {
int hops = Hops(a, b);
if (hops == ClockwiseHops(a, b))
return String.Format("{0} -> {1} (clockwise) {2} hops", a, b, hops);
else
return String.Format("{1} -> {0} (anticlockwise) {2} hops", a, b, hops);
}
Tests:
// 12 -> 1 (clockwise) 1 hops
Console.WriteLine(Solve(12, 1));
// 11 -> 4 (clockwise) 5 hops
Console.WriteLine(Solve(11, 4));
Have you considered the % Modulo Operator? That will give you the remainder of of the first number divided by the second. For example:
6 % 3 = 0 (3 goes into 6 exactly twice so zero remaining)
10 % 4 = 2 (4 goes into 10 twice with a remainder of two)
So you will want to try both routes and then check which one is smaller.
so try:
int numberOfPositions = 12;
Math.Min ((numberOfPositions + b - a) % numberOfPositions, (numberOfPositions + a -b) % numberOfPositions);
If you would like to see how modulo calculations work then there's an online calculator here:
http://www.miniwebtool.com/modulo-calculator/
Is it this simple?
int NUM_OF_NODES = 12;
int numOfHops = NUM_OF_NODES;
int point1 = 11;
int point2 = 4;
int path1 = Math.Abs(point1 - point2);
int path2 = numOfHops - path1;
int result = path1 < path2 ? path1 : path2;
return result;
For simple function
public int getLeastPath(int point1, int point2)
{
int path1 = Math.Abs(point1 - point2);
int path2 = NUM_OF_NODES - path1;
return path1 < path2 ? path1 : path2;
}
EX : 11-8
1.Get the mod of first number and last number
11% 12 = 1
8 % 12 = 8
add the sum
if it is less than 12 > 1 + 8 = 9
else sub
subtract with the 12 -9 = 3
compare 9 with 3, lesser value will be the answer.
The easiest answers were already provided but here's a recursive function, that actually "jumps" from one number to the other:
Func<int, int, int, int> Hop = null;
Hop = (direction, start, end) =>
{
if (start < 1)
start = 12;
if (start != end)
return 1 + Hop(direction, (start + direction), end);
return 0;
};
Related
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 1 year ago.
Improve this question
Does it have a shorter way than doing something like this:
int[] Summe = new int[6];
Summe[0] = 1;
Summe[1] = 2;
Summe[2] = 3;
Summe[3] = 4;
Summe[4] = 5;
Summe[5] = 6;
Console.WriteLine(Summe[0] + Summe[1] + Summe[2] + Summe[3] + Summe[4] + Summe[5]);
Console.ReadKey();
Using the Enumerable.Sum() method which computes the sum of a sequence of numeric values and Enumerable.Take() which returns a specified number of contiguous elements from the start of a sequence.
Console.WriteLine(Summe.Take(10).Sum());
OR from high school
// sum of integers from 1 to n
int SumNaturalNumbers(int n)
{
return n * (n + 1) / 2;
}
Formula for the general algebraic series starting from a and difference between terms d (Arithmetic progression and series)
sum = n / 2 * (2 * a + (n - 1) * d)
I think using a foreach loop may be helpful here, since you're dealing with an array. Also, you can define your array on one line.
int[] Summe = { 1, 2, 3, 4, 5, 6 };
int total = 0;
foreach (int number in Summe)
{
total += number;
}
Console.WriteLine(total);
Console.ReadKey();
You can simplify this process by simply putting this operation into a while loop.
int i = 0; // tell your program what 'i' should be upon first running the code
while (i < 10) // if 'i' is less than 10, run this block of code. You can change 10 to anything you want
{
Console.WriteLine("i = {0}", i);
i++; // increment
}
This will print each number individually, but you want to calculate the sum of every number, so you could do something like this:
{
public static void Main()
{
int j, sum = 0;
Console.Write("\n\n");
Console.Write("Find the sum of first 10 natural numbers:\n");
Console.Write("----------------------------------------------");
Console.Write("\n\n");
Console.Write("The first 10 natural number are :\n");
for (j = 1; j <= 10; j++)
{
sum = sum + j; // add the previous number to the current one
Console.Write("{0} ",j);
}
Console.Write("\nThe Sum is : {0}\n", sum);
}
}
The above code prints the sum of the first 10 natural numbers. I added some additional lines simply to make the program more legible. Again, you can change the number 10 to whatever number you want.
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 1 year ago.
Improve this question
How to make output : 1 1 2 6 3 11 4 16 5 21. when i input start value = 1, and end value = 5
my code :
Console.Write("input start value : ");
start = int.Parse(Console.ReadLine());
Console.Write("input end value : ");
end = int.Parse(Console.ReadLine());
Console.WriteLine("");
for (int i = start; i <= end; i++)
{
Console.WriteLine(i);
for (int j = i; j <= end; j++)
{
int z = 1;
if (start != j)
{
z++;
Console.WriteLine((j * j) + z);
}
else
{
Console.WriteLine(start + " this j start value");
}
}
}
So it's not entirely clear to me if the 5 is used both as an end value for the 1,2,3,4,5 as well as a difference value for the 1,6,11,16,21 but I'll assume yes. Here's an algorithm for you to implement (this looks like homework, so think of this as a tip - you'll get more out of doing the coding yourself but this is how you should approach any coding exercise: write out the algorithm in the language you think in then translate it to c#)
ask the user for a start value and convert to int
ask the user for an end value and convert to int
work out a variable called n which is end minus start
make a for loop starting at x = 0, running while x is less than or equal to n ; incrementing x by 1
print out startValue plus x
print out startValue plus (endValue times x)
loop around
For a start and end of 1 and 5, the loop runs from 0 to 4. The first time the loop runs, x is 0, startValue is 1, so a 1+0 and a 1+(5*0) are printed - both 1. This continues up to the end value where x is 4, 4+1 is printed - which is 5 - and 1+(4*5) is printed - which is 21
As #dxiv has posted in the comments, the pattern for the set of numbers is to combine 1,2,3,4,5 and 1,6,11,16,21. The pattern that I see is that the gap between the second set of numbers is equal to the ending number.
We can define a function which generates these numbers:
IEnumerable<int> GetNumbers(int start, int end)
{
for (int number = start; number <= end; number++)
{
yield return number;
yield return start + ((number - 1) * end);
}
}
And can output the results like:
int start = 1;
int end = 5;
Console.WriteLine(string.Join(' ', GetNumbers(start, end)));
Output
1 1 2 6 3 11 4 16 5 21
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 5 years ago.
Improve this question
if doublevalue = 124.75 then it shoud be rounded to 125.00
if doublevalue = 124.25 then it shoud be rounded to 124.50
in short after decimal point digit greater than 50 must rounded to 100 and less than 50 should rounded to 50
please help me get this type of code
Simply do the following:
Math.Ceiling(YourValue * 2)/2
Explanation
Suppose your number can be written as X + Y, where X is the integer part and Y is the fractional part. Multiplying it with 2 will make it 2X + 2Y, where 2X will be an even number, double of the integer part. For Y, there are two cases:
If Y >= 0.5, 2Y will be equal to 1 + Z (where 0 <= Z < 1), thus the entire number will be 2X + 1 + Z.
If Y < 0.5, 2Y will be equal to Z (where 0 <= Z < 1), thus the entire number will be 2X + Z.
Doing Math.Ceiling() in the first case will return 2X + 2 and dividing it by 2 will return X + 1, which is the nearest higher integer, (3.7 will become 4).
Doing Math.Ceiling() in the second case will return 2X + 1 and dividing it by 2 will return X + 0.5, or X.5 , (3.3 will become 3.5).
your conditions are not clear from your question, but the principle is to isolate the digits after the decimal point and that decide what to do:
private static double GetFixedNumber(double n)
{
var x = n - Math.Floor(n);
double result = 0;
if (x >= 0.75)
{
result = Math.Floor(n) + 1;
}
else if (x >= 0.25)
{
result = Math.Floor(n) + 0.5;
}
else
{
result = Math.Floor(n);
}
return result;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine( RoundUp(124.25, 2));
}
public static double RoundUp(double input, int places)
{
double multiplier = input*2;
double numberround = Math.Round(multiplier, MidpointRounding.AwayFromZero)/2;
return numberround;
}
}
}
Or compute it yourself:
// flipped the decision around - else it is kindof the same.
static double WorksAsWell(double input)
{
var floored = Math.Floor(input);
if (floored == input) // special case so exact 127. stays that way
return floored;
if (input - floored >= 0.5)
return floored+1;
return floored+0.5;
}
static double RoundToHalfesOrFulls(double input)
{
int asInt = (int)Math.Floor(input);
double remainder = input-asInt;
if(remainder < 0.5)
return asInt+0.5;
return asInt+1.0;
}
public static void Main()
{
for(int i= 12700; i < 12800; i+=5)
System.Console.WriteLine(string.Format("{0} = {1}",i/100.0, RoundToHalfesOrFulls(i/100.0)));
}
}
Output: (RoundToHalfesOrFulls)
127 = 127
127.05 = 127
127.1 = 127
127.15 = 127
127.2 = 127
127.25 = 127
127.3 = 127
127.35 = 127
127.4 = 127
127.45 = 127
127.5 = 127.5
127.55 = 127.5
127.6 = 127.5
127.65 = 127.5
127.7 = 127.5
127.75 = 127.5
127.8 = 127.5
127.85 = 127.5
127.9 = 127.5
127.95 = 127.5
I need to create a function that will generate 2 random numbers between x and y (e.g. x = 1, y = 20) which when added will not involve regrouping / carryover or which when subracted will not involve borrowing.
For example,
18 + 1 = good
14 + 5 = good
18-7 = good
29 - 8 = good
15 + 6 = bad
6 + 7 = bad
21 - 3 = bad
36 - 8 = bad etc.
I want to create a simple worksheet generator that will generate sample problems using the requirements above.
I guess I could always convert the number to string, get the right most digit for each of the 2 numbers, convert them back to integer, and test if one is greater than the other. Repeat for all the digit. Only thing is, that is so damn ugly (read inefficient). I am sure that there is a better way. Anyone have any suggestions? Thanks
Generate them one digit at a time. e.g
a1 = rand(9)
a2 = rand(9 - a1)
b1 = rand(9)
b2 = rand(9 - b1)
x = b1*10 + a1
y = b2*10 + a2
From the construction you know that x+y will not involve any carry, because a1+a2 <= 9 and b1 + b2 <= 9.
You can do similar for subtraction.
If you want to restrict the overall range to be [1..20] instead of [1..99], just adjust the range for the leftmost digit:
b1 = rand(1)
b2 = rand(1 - b1)
using System;
class Sample {
static void Main() {
var rnd = new Random();
var x = 1;
var y = 20;
var a = rnd.Next(x, y);
var b = rnd.Next(x, y);
var op = '+';
Console.WriteLine("{0} {2} {1} = {3}", a, b, op , isValid(a, b, op)? "good":"bad");
op = '-';
Console.WriteLine("{0} {2} {1} = {3}", a, b, op , isValid(a, b, op)? "good":"bad");
}
static bool isValid(int x, int y, char op){
int a = x % 10;
int b = y % 10;
switch (op){
case '+':
return a + b < 10;
case '-':
return x >= y && a - b >= 0;
default:
throw new Exception(String.Format("unknown operator '{0}'", op));
}
}
}
Breaking up the numbers into digits is indeed exactly what you need to do. It does not matter whether you do that by arithmetic manipulation (division and modulus by 10) or by converting the numbers into strings, but fundamentally your question is precisely about the individual digits of the numbers.
For the subtraction x − y, no borrows are required if and only if none of the digits in y are greater than the corresponding digit in x.
For the addition x + y, there will be no carries if and only if the sum of each pair of corresponding digits is less than 10.
Here's some pseudo-C# for checking these conditions:
bool CanSubtractWithoutBorrow (uint x, uint y) {
while (y > 0) {
if ((x % 10) < (y % 10)) return False;
x /= 10; y /= 10;
}
return True;
}
bool CanAddWithoutCarry (uint x, uint y) {
while (x > 0 && y > 0) {
if ((x % 10) + (y % 10) >= 10) return False;
x /= 10; y /= 10;
}
return True;
}
You need to look at each pair digit in turn, and see if adding or subtracting them involves carries.
You can get the rightmost digit by taking the value modulo 10, x%10, and you can erase the right most digit by dividing by 10.
No string conversions are necessary.
pls, I HAVE A NUMBER say 9 and i want to find how to create a program to check if a number b is maybe 21(ie 9+12) or 33(ie 9 + 24) or 45(9 + 36) and so on. Can i get it in C# or SQL
With the clarification, it looks like you want to find whether there is an integer x for which (in math terms, not code)
b = 9 + 12x
is true; so you want to know whether b-9 is some multiple of 12; which is easy:
bool isMatch = ((b - 9) % 12) == 0;
and if you want to know which x:
int x = (b - 9) / 12;
It's not entirely clear from your question, but I think you're looking for the modulo operator. 21 % 12 = 9, 33 % 12 = 9, 45 % 12 = 9.
In C# and SQL this is just %, and it is used like an arithmetic operator (+, -, etc)
I think you've got three variables and than the solution will be like this:
var a = 9;
var b = 12;
var c = 21;
var isInRange = IsInRange(c, a, b);
private bool IsInRange(int input, int offset, int multiple){
return ((input - offset) % multiple) == 0;
}
Subtract your original number (in this case 9) from the number B, and then see if B % 12 is different from zero.