Inversing integers and printing it in console [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an array of integers, which have to be converted into its inverses, so that, my program reads a series of integers from a user, fills an array with it, and then print it's inverses in a writeline. I had an idea to put inversed integers into double array, but still I don't know how to inverse (so that it looks like that - 1/N) it.
Finally, inversed integers should be printed in WriteLines.

You can use double inverse = 1.0 / number

If I understand correctly, this should work:
int arrayOfIntegers[] = <Your Array of Integers>;
foreach (input in arrayOfIntegers){
Console.WriteLine(1.0 / (double)in);
}

for(int i = 0; i < numbers.Length(); i++)
{
Console.WriteLine("1 / " + numbers[i].ToString());
}
or the foreach version:
foreach(int i in numbers)
{
Console.WriteLine("1 / " + i.ToString());
}
or to get cute:
foreach(int i in numbers)
{
Console.WriteLine("1 / {0} = {1}", i, 1.0 / i);
}

Of course this is a very basic exercise, I would like to introduce LINQ to you:
var output = yourArray.Select(x=> {
float f = 1f/x;
Console.Write(((decimal)f) + " ");
return f;
}).ToArray();
//This way you can still store the array while print all the inversed elements

Related

Splitting numbers into list/array (e.g. 1998 to 1,9,9,8) [closed]

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
this is my first post so excuse me if I am not being clear enough.
As the title says I want to split a number into smaller parts, for example 1998 to 1,9,9,8. I have looked around but I am stuck trying to figure out the right term to search for.
Reason why I want this done is to later multiply every other number with either 1 or 2 to be able to examine whether it's correct or not.
Sorry I can't provide any code because I am not sure how I should tackle this problem.
As #mjwills said, mod is what you want.
static IEnumerable<int> Digitize(int num)
{
while (num > 0)
{
int digit = num % 10;
yield return digit;
num = num / 10;
}
}
And then call it like so:
static void Main(string[] _)
{
int num = 1998;
int[] digits = Digitize(num).ToArray();
Console.WriteLine($"Original: {num}");
foreach (var digit in digits)
Console.WriteLine(digit);
}
make a string of that number and make it like this
```
int a = 1990;
int[] intArray = new int[a.ToString().Length];
int index = 0;
foreach( char ch in a.ToString())
{
intArray[index] = int.Parse(ch.ToString());
index++;
}

Algorithm to generate all combinations of a specific size from a single set [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I am looking for solution in c# to generate combinations on given list of characters or word to perform dictionary attack on zip files. because we lost passwords file for those zip. Advantage is that we know possible words on it. Dictionary should contain all the combos of words that I choose. And all characters/words are small case only.
Example: Let say we have a set of chars:
Set A = {A,B,C}
A,B,C =3
AA,AB,AC
BA,BB,BC
CA,CB,CC =9
AAA,AAB,AAC,ABA,ABB,ABC,ACA,ACB,ACC
BAA,BAB,BAC,BBA,BBB,BBC,BCA,BCB,BCC
CAA,CAB,CAC,CBA,CBB,CBC,CCA,CCB,CCA = 27
TOTAL POSIBLE COMBINATION 39
from the list of words a single word/character may repeat maximum of 4 times. If any such alogrithm/logic available please suggest.
Here is a C# implementation using recursion:
static char[] A={'a','b','c'};
static int N = 3;
static void foo(string s)
{
if (s.Length == N)
{
Console.WriteLine(s);
return;
}
for (int i = 0; i < A.Length; i++)
{
string t = s;
t += A[i];
foo(t);
}
}
Demo
If you want to retrieve the values later, store the strings in a global array before returning from function foo().

Fibonacci numbers [closed]

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 9 years ago.
Improve this question
So I have this problem where I have to calculate the Fibonacci number of any given number from the user. I don't know how to do the actual calculations part, but everything else works. Here's my code. Can someone help me with the calculation part?
using System;
namespace Assignment
{
class MainClass
{
public static void Main (string[] args)
{
int sum = 0;
Console.WriteLine("Fibonacci Number: ");
String fib = Console.ReadLine ();
double result = Convert.ToDouble (fib);
for(int i = 0; i <= result; i++)
{
sum = i * i - 1;
}
Console.WriteLine ("!" + result + " = " + sum);
}
}
}
Extension on recursion approach - use anonymous recursion (which uses Fibonacci as example of recursive call):
Define recursive function: f(n+1) = f(n) + f(n-1);.
Grab definition of Y-Combinator from the article:
delegate Func<A,R> Recursive<A,R>(Recursive<A,R> r);
static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
{
Recursive<A, R> rec = r => a => f(r(r))(a);
return rec(rec);
}
Now use Y-combinator to construct recursive function:
Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
Ready to call:
var fibOfSmallNumber = fib(4);
Now for large values you'd need BigInteger
Func<BigInteger,BigInteger> fibForBigNumbers =
Y<BigInteger,BigInteger>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
var fibOfBigNumber = fib(4);
Don't expect it to return value in short amount of time - default recursive implementation is very slow. Instead you should apply Memoization to remember previous values of the function (which also covered in the article).
Do you know the definition of the Fibonacci numbers? Please look them up; they have nothing to do with the polynomial x² - 1. The point of the problem is for you to translate the algorithm into C♯.
There are three general approaches you'll find:
Iteration by a for loop.
Recursion.
Direct formulas using exponentiation.
Try it all three ways. I suggest you look at the textbook by Graham, Knuth, and Patashnik, Concrete Mathematics. You'll learn some of the history too.
If what you want is the nth fibonacci number something like this should work:
const double goldenratio = 1.6180339887;
int n = 16;
int nthfib = Math.Round(Math.Pow(goldenratio, n - 1) / Math.Sqrt(5));
nthfib will equal the 16th fibonacci number, 610.
Since the fibonacci sequence gets very large rather quickly, you might need a limit set on n so that nthfib doesn't max out.

Getting average values from one Array to another Array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I’m no programmer but I’m learning C# to build a foreign exchange trading system and Arrays are being a struggle…
The problem I have is the following…
I have a one dimensional Array with, let’s say, 100 elements in it.
Now I need to build another one dimensional array with a 10 elements rolling average based on the first Array.
Said in another way, I need to take the elements from the first Array starting in i = 0 up to i = 9 and average them and save the average in a new array. Than move one step forward and take i = 1 up to i = 10 from the original Array and average them and save the result in the new Array….and so forth….in Excel this would be extremely easy….
My need to have the data in Arrays is because later I will need to compare the last 10 elements rolling average with historical data….
Please, can anyone build a sample code that I can work with?
Many thanks
Paulo
Maybe something like this could work... Did this on my mac in sublime text so you'll still have to work with. Should get the point though.
public class Foo
{
List<int> main = new List<int>(100);
List<int> rollingAverages = new List<int>(100);
public void Add(int score)
{
main.Add(score);
if(main.Count > 10)
{
int rollingAverage = AverageLast10();
rollingAverages.Add(rollingAverage);
}
}
public int AverageLast10()
{
int sum = 0;
for(int i = main.Count - 10; i < 10; i++)
{
sum += main[i];
}
return sum / 10;
}
}
Somewhere else in the code
Foo foo = new Foo();
foo.Add(94);
foo.Add(94);
...
yadda yadda yadda

Storing integers from Console to an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Im writing a program that asks the console for x numbers from the console. If they pick the number 4, then 4 different numbers should be stored. Then the program must store all these inputed numbers in an array, and then add the numbers together and print it out in the console.
So, i tried to do:
Console.WriteLine("Write out a number: ");
int[] x = int[].Parse(Console.ReadLine());
and apparently you cant read in array elements from the console on that way, so do I need to store them inside an variabel and then add them to an new array?
Console.Writeline("Enter the number of numbers to add: ");
//Yes, I know you should actually do validation here
var numOfNumbersToAdd = int.Parse(Console.Readline());
int value;
int[] arrayValues = new int[numOfNumbersToAdd];
for(int i = 0; i < numOfNumbersToAdd; i++)
{
Console.Writeline("Please enter a value: ");
//Primed read
var isValidValue = int.TryParse(Console.Readline(), out value);
while(!isValidValue) //Loop until you get a value
{
Console.WriteLine("Invalid value, please try again: "); //Tell the user why they are entering a value again...
isValidValue = int.TryParse(Console.Readline(), out value);
}
arrayValues[i] = value; //store the value in the array
}
//I would much rather do this with LINQ and Lists, but the question asked for arrays.
var sum = 0;
foreach(var v in arrayValues)
{
sum += v;
}
Console.Writeline("Sum {0}", sum);

Categories