I want to print numbers on label from 1-to 100
The number's sum must be dividing on 4.
Example:
print 35. because 3+5 = 8 .
8 dividing on 4.
This is code
from loop printing numbers. but how choose those numbers?
print those numbers from 1 to 100 ;
for (int i = 1; i < 100; i++)
{
//select numbers wich sum is dividing on 4
label3.Text += Convert.ToString(i) + " | ";
}
Stolen from Greg Hewgill answer's, you can use his algorithm and use remainder operator (%) like;
int sum, temp;
for (int i = 1; i < 100; i++)
{
sum = 0;
temp = i;
while (temp != 0)
{
sum += temp % 10;
temp /= 10;
}
if (sum % 4 == 0)
{
Console.WriteLine(i);
}
}
Result will be;
4
8
13
17
22
26
31
35
39
40
44
48
53
57
62
66
71
75
79
80
84
88
93
97
Here a demonstration.
You should use a nested loop for that , and use the % operator (% means the rest of division):
for (int i = 1; i < 100; i++)
{
for (int j = i; j < 100; j++)
{
//select numbers wich sum is dividing on 4
if( (i+j)%4 == 0)
{
label3.Text += Convert.ToString(i) + Convert.ToString(j) " | ";
}
}
}
Related
Input examples:
7 9 12 16 18 21 25 27 30 34 36 39 43 45 48 52 54 57 61
7 9 12 16 18 21 25 27 30 34 36 39 43 45 48 52 54 57 ... 75 79
Note that it ends with a space.
I want to get 57 in the first case and 75 in the second case as integer. I tried with the following:
Convert.ToInt32(Shorten(sequence).Split(' ').ElementAt(sequence.Length - 2));
The problem is that sequence.Length is not really the right index.
You can use the overload for Split() and pass the RemoveEmptyEntires enum:
string input = "7 9 12 16 18 21 25 27 30 34 36 39 43 45 48 52 54 57 61 ";
var splitInput = input.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
var inputInt = Convert.ToInt32(splitInput[splitInput.Length - 2]);
// inputInt is 57
Doing it this way allows your last element to actually be what you want.
Fiddle here
Based on maccettura's answer, in C# 8 you can simplify index acces like so
var input = "1 2 3";
var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var value = parts.Length >= 2 ? Convert.ToInt32(parts[^2]) : null;
How about something that doesn't use strings at all.
public static int? SplitReverseInt(this string str, int ixFromBack)
{
var inWord = false;
var wEnd = 0;
var found = 0;
for (int i = str.Length - 1; i >= 0; i--)
{
var charr = str[i];
if (char.IsWhiteSpace(charr))
{
// we found the beginning of a word
if (inWord)
{
if (found == ixFromBack)
{
var myInt = 0;
for (int j = i+1; j <= wEnd; j++)
myInt = (myInt * 10 + str[j] - '0');
return myInt;
}
inWord = false;
found++;
}
}
else
{
if (!inWord)
{
wEnd = i;
inWord = true;
}
}
}
// word (number) is at the beginning of the string
if (inWord && found == ixFromBack)
{
var myInt = 0;
for (int j = 0; j <= wEnd; j++)
myInt = (myInt * 10 + str[j] - '0');
return myInt;
}
return null;
}
Performance is about 10 times faster on the example strings.
This only loops from the back, and only fetches one number, it doesnt create substrings or an array of strings we don't need.
Use like this:
var numberFromBack = SplitReverseInt(input, 1);
I have a dynamic matrix and I need to to calculate sum of digits in this way:
0 1 2 3 4 5 6
10 11 12 13 14 15 16
20 21 22 23 24 25 26
30 31 32 33 34 35 36
40 41 42 43 44 45 46
50 51 52 53 54 55 56
60 61 62 63 64 65 66
I can't understand in which way I should compare i and j:
long result = 0;
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
// only works for diagonal
if (i == j) // should use j - 1 or i - 1?
{
result += matrix[i][j];
}
}
}
no need to scan full matrix:
long result = 0;
for (int i = 0; i < len; i++)
{
result += matrix[i][i]; // diagonal
if (i < len - 1) // stay within array bounds
result += matrix[i][i+1]; // next to diagonal
}
modification without index check on every iteration:
// assign corner value from bottom row to result
long result = matrix[len-1][len-1];
// for each row (except last!) add diagonal and next to diagonal values
for (int i = 0; i < len-1; i++)
result += matrix[i][i] + matrix[i][i+1];
A standard 52 card deck may be represented using integer values: {0,1,..,50,51}. A standard poker hand contains 5 values from this set, without repetition.
To represent all 52C5 unique hands from a deck, the following loop may be used:
for (int card1 = 0; card1 < 48; card1++)
{
for (int card2 = card1 + 1; card2 < 49; card2++)
{
for (int card3 = card2 + 1; card3 < 50; card3++)
{
for (int card4 = card3 + 1; card4 < 51; card4++)
{
for (int card5 = card4 + 1; card5 < 52; card5++)
{
var handAbcde = new List<int> { card1, card2, card3, card4, card5 };
// do something with the hand...
}
}
}
}
}
I would like to know how to make this a recursive function. I attempted but I could not preserve the ordering of the cards from lowest to highest, as it would for the for loops above.
Example of desired output: (observe sequential ordering from lowest to highest without repetition)
0 1 2 3 4
0 1 2 3 5
0 1 2 3 6
.
.
.
47 48 49 50 49
47 48 49 50 50
47 48 49 50 51
Here's a helpful extension method, which does what you want using recursion:
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> items, int count)
{
int i = 0;
foreach (var item in items)
{
if (count == 1) yield return new T[] { item };
else foreach (var result in items.Skip(i + 1).GetPermutations(count - 1))
yield return new T[] { item }.Concat(result);
++i;
}
}
And here's a sample use, to generate all possible combinations of five cards from a 52-card deck:
foreach (var hand in Enumerable.Range(0, 52).GetPermutations(5))
{
foreach (var card in hand)
Console.Write(card + " ");
Console.WriteLine();
}
I came across the following question for an interview.
For a given number of digits, generate all the numbers such that the value of a higher order digit is less than a lower order digit.
145 // 1 < 4 < 5
Is there a better (efficient) way to do this than the one I have come up with:
public static void GenerateSpecialNumbers(int noDigits)
{
int prod = 1;
for(int i=0; i < noDigits; i++)
{
prod = prod * 10;
}
int minValue = prod/10;
int maxValue = prod - 1;
for(int i = minValue; i < maxValue; i++)
{
bool isValid = true;
int num = i;
int max = int.MaxValue;
while(num > 0)
{
int digit = num % 10;
if(digit >= max)
{
isValid = false;
break;
}
max = digit;
num = num/10;
}
if(isValid)
Console.WriteLine(i);
}
}
EDIT:
Output for 3 digits:
123
124
125
126
127
128
129
134
135
136
137
138
139
145
146
147
148
149
156
157
158
159
167
168
169
178
179
189
234
235
236
237
238
239
245
246
247
248
249
256
257
258
259
267
268
269
278
279
289
345
346
347
348
349
356
357
358
359
367
368
369
378
379
389
456
457
458
459
467
468
469
478
479
489
567
568
569
578
579
589
678
679
689
789
Nice puzzle! Here's my take:
static void Main()
{
WriteNumbers(3);
}
static void WriteNumbers(int digits, int number = 0)
{
int i = (number % 10) + 1;
number *= 10;
for (; i <= 9; i++)
{
if (digits == 1)
Console.WriteLine(number + i);
else
WriteNumbers(digits - 1, number + i);
}
}
Yes, this problem has a simple recursive description that constructs all the numbers without having to test and throw any away.
For example, the valid n digit numbers include "1".append(all valid n-1 digit numbers using only digits >1)
Each digit has a lower bound of one plus the digit immediately to its left. Can you find a simple upper bound?
Since I like table-based things, I would generate the table for n = 2 first (< 100 entries, obviously) and just hold it in an initialized array.
Then f(n) = the digits in the sequence N [1, 2, 3, 4, 5, 6, 7, 8, 9] composed with f(n-1) where f(n-1)[0] > N
i.e. for n = 3:
1, f(2) where f(2)[0] > 1: 123, 124, 125, ...
2, f(2) where f(2)[0] > 2: 234, 235, 236, ...
...
for (i1 from 1 to 9)
for (i2 from 1 to i1 - 1)
for (i3 from 1 to i2 - 1)
print(i1 * 1 + i2 * 10 + i3 * 100);
No recursion needed for fixed-length numbers. Easy to code and fail-safe.
Please note that the loop upper bounds are not fixed. This is what makes this work.
Here is my solution with help from #Hand-E-Food and #Ben Voigt's comment. I feel this is easier to understand:
static void WriteNumbers(int digits, int left=0,int number=0)
{
for(int i=left+1; i<10; i++)
{
if(digits==1)
{
Console.WriteLine(number*10+i);
}
else
{
WriteNumbers(digits - 1, i, number*10 + i);
}
}
}
Here's a hint: if there are N possible digit values, and you want to pick M of them, the number of possibilities is "N choose M".
Here's a solution (albeit kind of hack-ish) that will work for any number of digits:
private static void printSpecialNumbers(int noOfDigits){
int max = (int) Math.pow(10, noOfDigits);
int min = (int) Math.pow(10, noOfDigits-1);
for(int i = min; i < max; i++){
if(isSpecialNumber(i))
System.out.println(i);
}
}
private static boolean isSpecialNumber(int i){
String intString = String.valueOf(i);
String[] digits = intString.split("");
for(int k = 1; k < digits.length-1; k++){
if(Integer.valueOf(digits[k]) >= Integer.valueOf(digits[k+1]))
return false;
}
return true;
}
Is it possible to generate a multiplication table (for example, from 1 to 9) with a single for loop?
Yes, using something like this... But why not using two nested loops?
for (int i = 0; i < 9 * 9; ++i)
{
int a = i / 9 + 1;
int b = i % 9 + 1;
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
}
To generate the multiplication table of 1-9 with a single for loop you could loop 81 time and use the division and modulo operator to get the two operands.
for (int i = 0; i < 9*9; ++i)
{
int a = i / 9 + 1;
int b = i % 9 + 1;
Console.WriteLine($"{a} * {b} = {a * b}");
//Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
}
Note, there must be a better way to construct the output, but I'm not familiar with C#.
Here's a hint for one way to do it.
How can you extract all of the needed multipliers and multiplicands from a single integer from 0 to 81?
try:
Console.WriteLine(" 1 2 3 4 5 6 7 8 9");
for (int i = 1; i<10; i++)
Console.WriteLine(
string.Format("{0}: {1:#0} {2:#0} {3:#0} {4:#0} " +
"{5:#0} {6:#0} {7:#0} {8:#0} {9:#0}",
i, i, 2*i, 3*i, 4*i, 5*i, 6*i, 7*i, 8*i, 9*i));
here, the code for multiplication tables based on our criteria
suppose
Enter a value:2
Enter b value:10
then the output is like 2*1=2 to 2*10=20...
static void Main(string[] args)
{
int a, b, c, d;
Console.WriteLine("enter a value:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter b value:");
b = Convert.ToInt32(Console.ReadLine());
for (d = 1; d <=b; d++)
{
c = a * d;
Console.WriteLine("{0}*{1}={2}",a,d,c);
}
Console.ReadLine();
}
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the value:");
int m = int.Parse(Console.ReadLine());
if (m == 0)
return;
for(int i=1;i<=10;i++)
Console.WriteLine("{0} * {1} ={2}",m,i,m*i);
Console.ReadLine();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication11
{
class Program
{
int a;
int b;
int c;
public void Accept()
{
Console.WriteLine("enter the no.:");
a = Convert.ToInt32(Console.ReadLine());
}
public void Process()
{
for (int c = 1; c <= 10; c++)
{
b = a * c;
Console.WriteLine("table: {0}", b);
}
Console.ReadLine();
}
public void Display()
{
//Console.WriteLine(a "X" + c +"="b);
}
static void Main(string[] args)
{
Program pr = new Program();
pr.Accept();
pr.Process();
Console.ReadKey();
}
}
}
It is C solution, but you may easily re-write it into whatever language you like.
#include <stdio.h>
void Mult_table(int n)
{
int i;
int a = 0;
int b = 0;
int count = 0;
for (i= 0; i< n*n; ++i)
{
a = i/n + 1;
b = i%n + 1;
printf("%4d ", a*b);
count++;
if(count %n == 0) /*new line*/
{
printf("\n");
}
}
}
Output (if n = 10, but will work with any n):
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100