I`m am doing a nested loop problem and I was wondering how I could make the numbers after they reach a certain number start to decrease. The things I have tried start an infinite loop in the console. Here is an Example of the output wanted.
1
222
33333
4444444
555555555
4444444
33333
222
1
here is my code :
public class DisplayPattern {
public static void main(String[] args) {
int odd = 1;
int numbOfSpaces = 4;
for (int i = 1; i <= 9; i++) {
for (int j = numbOfSpaces; j >= 1; j--) {
System.out.print(" ");
}
for (int j = 1; j <= odd; j++) {
System.out.print(i);
}
System.out.println();
if(i < 5) {
odd = odd + 2;
numbOfSpaces = numbOfSpaces - 1;
}
else {
odd = odd -2;
numbOfSpaces = numbOfSpaces + 1;
}
}
}
}
Here is the output I am getting:
1
222
33333
4444444
555555555
6666666
77777
888
9
The easiest way to do this with you code (meaning least amount of mods) is to add a variable NumberToPrint = 1; next to the other declared variables and instead of printing i you print NumberToPrint.
Next you have to increment and decrement the number
if(i < 5) {
NumberToPrint++;
//the other stuff still goes here
...
}
else {
NumberToPrint--;
//the other stuff still goes here
...
Having said that, this is not the right approach. Try to think of a way to make this generic and parametrize everything including the maximum number to go to. See how you can fix you code to work with numbers that have 2 digits or 3... so one.
Related
I'm trying to implement my own version of the sum of subsets problem, using backtracking, to get all the possible solutions of obtaining a given sum from an array of elements. At the moment, I'm getting output stuck in an infinite, the output adds up to the sum that I want, but it exceeds the number of elements of a type available in the array. I'm not sure why this happens, because I put some stopping conditions. The code:
#include <stdio.h>
#define MAX 1024
int coins_array[] = {1,1,1,1,1,3,3,3,3,3,3,3,3,3,3,10,10,10,10,10,15,15,15,15,15,15};
int N = sizeof(coins_array) / sizeof(coins_array[0]);
int S = 27, Sol[MAX], sum, sol;
int acceptable(int step)
{
int i = 0, sum = 0;
for(i = 1; i <= step; i++)
{
sum += Sol[i];
}
if((sum <= S) && (step <= N))
return 1;
return 0;
}
int solution(int sum)
{
if (sum == S)
return 1;
return 0;
}
void print_solution(int step)
{
int i;
for(i = 1 ; i <= step ; ++i)
printf("%d ",Sol[i]);
printf("\n");
}
void back(int step)
{
int i;
for(i = 0; i < N; i++)
{
Sol[step] = coins_array[i];
sum += coins_array[i];
if(acceptable(step) == 1)
{
if(solution(sum) == 1)
{
print_solution(step);
}
else
back(step+1);
}
sum -= coins_array[i];
}
}
int main()
{
back(1);
return 0;
}
Output (in an infinite loop):
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 3
So, the numbers add up to the desired sum, however it exceeds the number of available 1's, and doesn't make use of 10 or 15. I ran to this in the debugger and I believe the problem for the loop is at back(step+1). Any idea how I could fix this?
Not sure this covers all problems in your code but it's at least its one bug that needs to be fixed.
Your current code uses the same coin several times. For instance if you set the target to be 2 (i.e. S = 2), your code will generate a solution where coins_array[0] is used twice.
This happens because your back function always starts looking at the coins_array from index zero.
void back(int step)
{
int i;
for(i = 0; i < N; i++)
^^^^^
Always starting from zero is wrong
Instead you need to start from the "next unused" coin. Unfortunately your current code doesn't track that so you need to redesign your solution.
To show the above described problem I made some minor changes to your program - 1) Reduced the available coins 2) Changed the target value 3) Added an array to track which coin (aka index) was used 4) printed the index
So with these change your code looks like:
#define MAX 1024
int coins_array[] = {1,1,3};
int N = sizeof(coins_array) / sizeof(coins_array[0]);
int S = 2, Sol[MAX], IndexUsed[MAX], sum, sol;
int acceptable(int step)
{
int i = 0, sum = 0;
for(i = 1; i <= step; i++)
{
sum += Sol[i];
}
if((sum <= S) && (step <= N))
return 1;
return 0;
}
int solution(int sum)
{
if (sum == S)
return 1;
return 0;
}
void print_solution(int step)
{
int i;
for(i = 1 ; i <= step ; ++i)
printf("%d (%d) ",Sol[i], IndexUsed[i]);
printf("\n");
}
void back(int step)
{
int i;
for(i = 0; i < N; i++)
{
Sol[step] = coins_array[i];
IndexUsed[step] = i;
sum += coins_array[i];
if(acceptable(step) == 1)
{
if(solution(sum) == 1)
{
print_solution(step);
}
else
back(step+1);
}
sum -= coins_array[i];
}
}
int main()
{
back(1);
return 0;
}
and generates the output (with my comments added):
1 (0) 1 (0) // Illegal - coin at index 0 used twice
1 (0) 1 (1) // Legal - coin at index 0 and 1 used to reach the sum 2
1 (1) 1 (0) // Illegal - this combination have already been used
1 (1) 1 (1) // Illegal - coin at index 1 used twice
As you can see, your code prints 4 solutions but it should only have printed 1. As already stated, this happens because your code always start from index zero in the function back
Problem: To display the sum of this pattern for n terms like 1+11+111+1111+11111..n terms
Test Data:
Input the number of terms: 5.
Expected Output:
1 + 11 + 111 + 1111 + 11111
The Sum is : 12345
I am trying this way->
//To display the sum of series like 1+11+111+11111
#include <stdio.h>
int
main(void){
//Here i declared some variables for storing information
int number,iteration,value=1,j,summation=0;
//Message to user
printf("Input the number of terms : ");
//taking input from the user
scanf("%d",&number);
//this condition will work till the iteration reaches to the inputted number
for(iteration=1; iteration<=number; iteration++){
for(j=1; j<=iteration; j++){
//To display the series like 1 11 111 1111 11111
printf("%d",value);
if(j==1){
summation=summation+value;
}
else if(j==2){
summation=summation+value*10;
}
else if(j==3){
summation=summation+value*100;
}
else if(j==4){
summation=summation+value*1000;
}
else if(j==5){
summation=summation+value*10000;
}
}
printf(" ");
}
printf("\n");
//To display the summation
printf("The summation is : %d",summation);
return 0;}
Now my problem is: This code does not work according to my expectation. It is working up to input value 5. But when I want to give input 6 times then I need to add an else if condition additionally in my code. I need to do this task whenever I increase the input value.
When the input value is 6 and i need to add and make the condition like that->
else if(j==6){
summation=summation+value*100000;
}
So I think, this is not the way of a proper solution to a problem. Every time I need to do the same thing for the inputted value. How can I solve this problem?. After that how can I simplify the solution? I believe that you guys are expert than me. Please share your knowledge with me. Thank you in advance.
Pass the input number to this function.
int findSum(int n)
{
int sum=0, cnt= 1;
for (int i = 1; i <= n; i++) {
sum += cnt;
cnt = (cnt * 10) + 1;
}
return sum;
}
If you want to make this work for large N (say, 1,000 or 20,000,000), you won’t be able use int or long long values. Instead, you could allocate an array of uint8s, and do your own digit-by-digit addition arithmetic, including the carry operation. Then print the results at the end. It wouldn’t be fast but it would work.
To keep your code simple, think right-to-left. Start with the least significant digit in the zero-th array element.
Here's an example that uses uint64_t to represent larger numbers. It shows the output you want for 1 up to 20 digits (longer causes an overflow).
The trick is to generate the numbers 1, 11, 111, and so on from the previous one by multiplying by 10 and adding 1. For example, 11111 = 1111 * 10 + 1.
#include <inttypes.h>
#include <stdio.h>
void sum(int n) {
uint64_t t = 0;
uint64_t x = 1;
for (int i = 0; i < n; i++) {
if (i > 0) printf(" + ");
printf("%" PRIu64, x);
t += x;
x = (x * 10) + 1;
}
printf(" = %" PRIu64 "\n", t);
}
int main() {
for (int i = 1; i < 21; i++) {
sum(i);
}
}
Here's a version that works for any n. It computes the total in time linear in n, although printing the terms being summed necessarily requires O(n^2) time.
The code works by noting that the last digit of the total consists of n 1s being added, the next-to last n-1 1s and so on. Plus carry of course. Note that the result is always exactly n digits long.
#include <stdio.h>
#include <stdlib.h>
void sum(int n) {
for (int i = 1; i <= n; i++) {
if (i > 1) printf(" + ");
for(int j = 0; j < i; j++) putchar('1');
}
printf(" = ");
char *s = malloc(n + 1);
s[n] = '\0';
int t = 0;
for (int i = n - 1; i >= 0; i--) {
t += i + 1;
s[i] = '0' + (t % 10);
t /= 10;
}
printf("%s\n", s);
free(s);
}
int main() {
sum(50);
}
Output (wrapped):
1 + 11 + 111 + 1111 + 11111 + 111111 + 1111111 + 11111111 + 111111111 + 1111111111 + 11111111111 + 111111111111 +
1111111111111 + 11111111111111 + 111111111111111 + 1111111111111111 + 11111111111111111 + 1111111111111111 11 +
1111111111111111111 + 11111111111111111111 + 111111111111111111111 + 1111111111111111111111 + 11111111111111111111111 +
111111111111111111111111 + 1111111111111111111111111 + 11111111111111111111111111 + 11111111111 1111111111111111 +
1111111111111111111111111111 + 11111111111111111111111111111 + 111111111111111111111111111111 +
1111111111111111111111111111111 + 11111111111111111111111111111111 + 111111111111111111111111111111111 +
1111111111111111111111111111111111 + 11111111111111111111111111111111111 + 111111111111111111111111111111111111 +
1111111111111111111111111111111111111 + 11111111111111111111111111111111111111 + 1111111111111111111111111
11111111111111 + 1111111111111111111111111111111111111111 + 11111111111111111111111111111111111111111 +
111111111111111111111111111111111111111111 + 1111111111111111111111111111111111111111111 + 1111111111111111111111111
1111111111111111111 + 111111111111111111111111111111111111111111111 + 1111111111111111111111111111111111111111111111 +
11111111111111111111111111111111111111111111111 + 111111111111111111111111111111111111111111111111 +
1111111111111111111111111111111111111111111111111 + 11111111111111111111111111111111111111111111111111 =
12345679012345679012345679012345679012345679012340
For handling numbers greater than int/long limits, you can use an array to get the sums per digit and print the output as a string.
#include <stdio.h>
int
main (int argc, char *argv[])
{
int n, i, j;
scanf("%d", &n);
char ones[n];
char sum[n + 1]; // + 1 index in case of a carry out
char output[n + 2]; // +1 more index than sum for null byte
// initialize to 0s
for (i = 0; i < n; i++) {
ones[i] = sum[i] = output[i] = 0;
}
sum[n] = output[n] = output[n+1] = 0;
for (i = 0; i < n; i++) {
ones[i] = 1;
output[i] = '1';
for (j = 0; j <= i; j++) { // add the current number of ones to sum
sum[j] += ones[j];
if (sum[j] >= 10) { // if theres a carry
sum[j + 1] += (sum[j] / 10); // add the carry to the next index
sum[j] %= 10; // keep the last digit
}
}
if (i == n - 1) {
printf ("%s ", output);
} else printf ("%s + ", output);
}
if(sum[n] == 0) {// leading digit is 0
i = n - 1;
} else i = n;
for (j = 0; i >= 0; i--, j++) {
output[j] = sum[i] + '0';
}
printf ("The sum is: %s\n", output);
return 0;
}
Given your user input variable number, the code may look something like this:
//...
if (number < 0)
{
// do some error handling
return -1;
}
int value_to_add = 1;
int sum = 0;
while (number--)
{
sum += value_to_add;
value_to_add = value_to_add * 10 + 1;
}
// ... (result is in "sum")
You also may consider the possibility of overflow (when the result gets so big that it does not fit in an int). You could, for instance, limit the user input (number).
glad to help!
(it seems like a homework, so hope you can learn something)
You're doing this with many 'if's to decide how much it should plus. And another way is to use *10+1 every time.
Please see the code:
#include <stdio.h>
long long sum,tmp=1,n;
int main(void){
scanf("%lld",&n);
for(int i=0;i<n;i++){
if(i<n-1)printf("%lld + ",tmp);
else printf("%lld ",tmp);
sum+=tmp;
tmp=tmp*10+1;
}
printf("= %lld",sum);
return 0;
}
That's it.
Wish you a good day:)
If I understood correctly you want to be able to programmatically add new terms without having to use an if statement. To do it I suggest you
for (j=0; j<=iteration; j++){
int powerOf10 = (int) pow((double) 10,j); //power elevation: notice 10^0=1, 10^1=10..
summation+=value*powerOf10;
}
This was just to give you an idea. Obviously, this code can be further refined.
If you don't understand all the casting I performed to compute powerOf10 I leave you this post: Why is my power operator (^) not working?
Paul Hankin's answer shows how to solve this problem for values of n greater than the number of digits storable in a long long.
That approach could be combined with another, based on a simple observation. If we write the sum starting from the greatest number, we can note an emerging pattern.
111111111111111111111111111111111111111111111...111 +
11111111111111111111111111111111111111111111...111 +
...
1111111111111111111111111111111111111...111 =
----------------------------------------------------
123456789999999999999999999999999999999999999...999 +
111111111111111111111111111111111111...111 =
----------------------------------------------------
123456790111111111111111111111111111111111111...110 +
11111111111111111111111111111111111...111 +
...
1111111111111111111111111111...111 =
----------------------------------------------------
123456790123456789999999999999999999999999999...998 +
111111111111111111111111111...111 =
----------------------------------------------------
123456790123456790111111111111111111111111111...109 +
11111111111111111111111111...111 +
...
1111111111111111111...111 =
----------------------------------------------------
123456790123456790123456789999999999999999999...997 +
111111111111111111...111 =
----------------------------------------------------
123456790123456790123456790111111111111111111...108 +
^ ^ ^ ^ ...
In practice, we can start by "filling" the number (represented as a string of n characters) with the repeating pattern "123456790" from left to right (the most significant digit beeing always '1').
Then, starting from the least significant digit, we can apply the algorithm of the sum with carry, but only as long as the calculated digit is different from the one already there (except the last one, which is always n % 10).
Only a few steps are needed, just around the number of decimal digits of n.
I'm having a difficult time trying to calculate a number through an array that I have that contains only 0's and 1's. I have built a function that multiplies the exponent for each number but I'm having a bit of difficulty.
The problem is that I run into a loop that calculates all of the exponents of 2 instead of running 3 times, so if I'm trying to calculate 0000000000000000000000000000111 (which supposed to run 3 times) I get 1,2,4,8,16,32,64...4194304... and all of that 3 times.
My code is:
for(int i = 31; i > 0; i--){
if(EndArray[i] == 1){
for(x = 0; x < 30 ; x++){
UnsignedArray[30-x] = ExpoFunction(x);
}
}
}
ExpoFunction is:
int ExpoFunction(int x){
int result = 1;
for(int i = 0 ; i < x ; i++){
result *= 2;
}
return result;
}
EndArray is an array that contains 32 numbers of 0's and 1's. example: 0000000000000000000000000000111 which supposed to be 7.
At the end of this, I want to put everything in a new array which called UnsignedArray and then to sum all of UnsignedArray's numbers together.
Any ideas whats wrong or a better way?
You want to store all exponents in UnsignedArray, then sum all value in this array to have the decimal number, right ? If i am not wrong, your for loop should change to:
for(int i = 30; i >= 0; i--){ // should run from 30 to 0, not from 31 to 1
if(EndArray[i] == 1){
// just store one time, not using for loop of x as you did in your code.
UnsignedArray[30-i] = ExpoFunction(30-i);
printf("%d\n", UnsignedArray[30-i]); // if you want to test the value.
}
}
The main function for testing:
int main()
{
int EndArray[31] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1};
unsigned int UnsignedArray[31] = {0};
for(int i = 30; i >= 0; i--){
if(EndArray[i] == 1){
UnsignedArray[30-i] = ExpoFunction(30-i);
printf("%u\n", UnsignedArray[30-i]);
}
}
unsigned int sum = 0;
for(int i = 0; i < 31; i++) {
sum += UnsignedArray[i];
}
printf("decimal: %u", sum);
return 0;
}
The output:
1
2
4
decimal: 7
So for my assignment I have to take the inputs of length and width and print out patterns of "*" based on the inputs. The minimum height is 7 and only goes up by odd integers and width is any multiple of 6.
The basic format of the output using a height of 7 and width of 12:
************
************
*** ***
*** ***
*** ***
************
************
So basically the first and last 2 lines are straight through the entire width, with the odd numbered rows containing 3 asterisks followed by 3 spaces, until it reaches the end of the width. The even numbered rows start off with 3 spaces.
I've figured out how to print the first two lines using the following code:
do
{
printf("*");
++i;
}while(i<width);
printf("\n");
do
{
printf("*");
++j;
}while(j<=width);
printf("\n");
But for the life of me, I cannot come up with the correct way to use basic nested loops to print out the inside pattern. I asked a programmer friend who is unfamiliar with C but wrote up a basic program in Java. I don't know Java and have tried to translate it but notice some big discrepancies in the logic between the two languages that is causing me headaches. Here is his code:
// LOGGING
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function (text) {
$("#console-log").append($(consoleLine).html(text));
}
};
// PATTERN PARAMETERS
var rows = 6;
var cols = 7;
// hard code a space so html respects it
var space = " "
console.log("cols: " + cols + " rows: " + rows);
for (y = 0; y < rows; ++y) {
var line = "";
for (x = 0; x < cols; ++x) {
// First two and last two rows do not have patterns and just print filled
if (y == 0 || y == 1 || y == rows - 1 || y == rows - 2) {
line += "*";
} else {
if (y % 2 == 0) {
// Even row
line += x % 6 < 3 ? "*" : space;
} else {
// Odd row
line += x % 6 >= 3 ? "*" : space;
}
}
}
console.log(line);
}
Please help me or point me in the right direction!! I've searched online but can't seem to find a solution that's worked yet!
Edit- forgot to mention that all "printf" uses can only print one character at a time... Such as a single *
Edit edit- I GOT IT WORKING!!!! Thank you all so, so much for your input and guidance! Here's what I have that is working perfectly:
for (y = 0; y < height; ++y)
{
printf("\n");
for (x = 0; x < width; ++x)
{
// First two and last two rows do not have patterns and just print filled lines
if (y == 0 || y == 1 || y == height - 1 || y == height - 2)
{
printf("*");
}
else
{
if (y % 2 == 0)
{
if(x%6<3)
{
printf("*");
}
else
{
printf(" ");
}
} else {
// Odd row
if(x%6>=3)
{
printf("*");
}
else
{
printf(" ");
}
}
}
}
printf("\n");
Write a function with 3 arguments n,a,b that prints n groups of 3 of each argument a and b alternately. You can call this function to print the 4 different kinds of lines. You can make a loop to print the middle section repeatedly. Have fun!
A simpler alternative:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int row, col, height = atoi(argv[1]), cols = atoi(argv[2]);
for (row = 0; row < height; row++) {
for (col = 0; col < cols; col++) {
putchar(row < 2 || row >= height - 2 ||
col % 6 / 3 == row % 2 ? '*' : ' ');
}
putchar('\n');
}
}
What I'm trying to accomplish is making a function to the following:
Imagine that I have between 1-9 squares. Those squares have a number assigned to them globally, not individually. They are like a set, and that set has this number.
E.g.: | _ | _ | _ | 19
What I'm trying to do is a function that gives me the possible combinations depending on number of squares and the number associated with them. For the example above: 9, 8, 2 is one of the possible combinations. However I just want the numbers that are in those combinations, not the combinations themselves. Plus they have to be unique (shouldn't be 9, 9, 1). Oh and those numbers range from 1-9 only.
How can I achieve this in C? If you are wondering this is for a puzzle game.
Thanks in advance!
Looks like you are trying to find a restricted Partition of the integer on the right. The link should give you a good starting place, and you should be able to find some algorithms that generate partitions of an integer into an arbitrary number of parts.
For future reference, in combinatorics we say "order doesn't matter" to mean "I only want the set of numbers, not a specific ordering"
//Sets the given digit array to contain the "first" set of numbers which sum to sum
void firstCombination(int digits[], int numDigits, int sum) {
reset(digits, 0, 1, numDigits, sum);
}
//Modifies the digit array to contain the "next" set of numbers with the same sum.
//Returns false when no more combinations left
int nextCombination(int digits[], int numDigits) {
int i;
int foundDiffering = 0;
int remaining = 0;
for (i = numDigits - 1; i > 0; i--) {
remaining += digits[i];
if (digits[i] - digits[i - 1] > 1) {
if (foundDiffering || digits[i] - digits[i - 1] > 2) {
digits[i - 1]++;
remaining--;
break;
} else
foundDiffering = 1;
}
}
if (i == 0)
return 0;
else {
reset(digits, i, digits[i - 1] + 1, numDigits - i, remaining);
return 1;
}
}
//Helper method for firstCombination and nextCombination
void reset(int digits[], int off, int lowestValue, int numDigits, int sum) {
int i;
int remaining = sum;
for (i = 0; i < numDigits; i++) {
digits[i + off] = lowestValue;
remaining -= lowestValue;
lowestValue++;
}
int currentDigit = 9;
for (i = numDigits + off - 1; i >= off; i--) {
if (remaining >= currentDigit - digits[i]) {
remaining -= currentDigit - digits[i];
digits[i] = currentDigit;
currentDigit--;
} else {
digits[i] += remaining;
break;
}
}
}
It sounds like what you're working on is very similar to kakuro, also know as Cross Sums: http://en.wikipedia.org/wiki/Cross_Sums
There are generators out there for these kinds of puzzles, for example: http://www.perlmonks.org/?node_id=550884
I suspect that most kakuro generators would have to solve your exact problem, so you might look at some for inspiration.