Fill program in C - c

I am trying to create a program in C that, given the user's input of a character boarder for a shape, fills the shape in.
http://pastebin.com/aax1dt0b
#include <stdio.h>
#include "simpio.h"
#include "genlib.h"
#define size 100
bool initArray(bool a[size][size]);
bool getshape(bool a[size][size]); /* Gets the input of the boarder of the shape from the user */
void fill(int x, int y, bool a[size][size]); /* fills the shape */
void printarray(bool a[size][size]); /* prints the filled shape */
main()
{
int x, y;
char i;
bool a[size][size];
initArray(a);
getshape(a);
printf("Enter the coordinates of the point the shape should be filled.\n");
printf("x=n\n"); /* gets the coordinates of the array to begin the fill algorithm from */
x = GetInteger();
printf("y=\n");
y = GetInteger();
fill(x, y, a);
printarray(a);
printf("Scroll up to view your filled shape\n");
getchar();
}
bool initArray(bool a[size][size])
{
int i, j;
for (i = 0; i < 100; i++)
{
for (j = 0; j < 100; j++)
{
a[i][j] = FALSE;
}
}
}
bool getshape(bool a[size][size])
{
int i, j, k;
bool flag;
char ch;
ch = 1;
printf("Enter your shape. When you are finished, type 'E'. \n");
for (i = 0; i < 100; i++)
{
flag = TRUE;
for (j = 0; ch != 10; j++)
{
ch = getchar();
if (ch == 69)
{
return a;
}
if (ch != 32) a[i][j] = TRUE;
}
ch = 1;
}
}
void fill(int x, int y, bool a[size][size])
{
if (a[y][x] != TRUE) a[y][x] = TRUE;
if (a[y][x - 1] != TRUE) fill(x - 1, y, a);
if (a[y - 1][x] != TRUE) fill(x, y - 1, a);
if (a[y][x + 1] != TRUE) fill(x + 1, y, a);
if (a[y + 1][x] != TRUE) fill(x, y + 1, a);
}
void printarray(bool a[size][size])
{
int i, j;
printf("\n\n\n");
for (i = 0; i < 100; i++)
{
for (j = 0; j < 100; j++)
{
if (a[i][j] == FALSE) printf(" ");
if (a[i][j] == TRUE) printf("*");
}
printf("\n");
}
}
My program works for the most part, but when it prints the filled shape, it adds one additional character to each row. For example, if the user's input it
***
* *
***
Then the output will be
****
****
**** (one extra row then it should be)
whereas it should be
***
***
***
anyone know how I can fix this?

Although there are several potential problems in your code, I'm going to just identifying the problem of the 4th column *'s. In the code below, although you're checking ch!=10 in the for statement, the value of a[i][j] is getting assigned TRUE before terminating the loop. So you might want to do if(ch!=32 && ch!=10) a[i][j]=TRUE;.
flag=TRUE;
for(j=0;ch!=10;j++)
{
ch=getchar();
if(ch==69)
{
return a;
}
if(ch!=32) a[i][j]=TRUE;
}
ch=1;

Related

Flood fill path in C

I want to create a program where if I input
for example:
5
###O#
#OOO#
##O##
#OO##
##O##
5 is the size of the maze.
output: yes
, because there is a path to cross the maze
if the input is
5
###O#
#OOO#
#####
#OO##
##O##
the output will be no, because the path is blocked.
this is my current code,, it's not working properly
#include <stdio.h>
#include <stdbool.h>
#define MAX 1001
char maze[MAX][MAX];
bool passed[MAX][MAX];
void move(int y, int x, int size)
{
if (maze[y][x] == '#' || passed[y][x] == true || y < 0 || x < 0 || y >= size || x >= size) return;
passed[y][x] = true;
move(y + 1, x, length, width);
move(y - 1, x, length, width);
move(y, x + 1, length, width);
move(y, x - 1, length, width);
}
int main()
{
int size;
scanf("%d", &size);
int y, x;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
scanf(" %c", &maze[i][j]);
if (maze[i][j] == 'O')
{
y = i;
x = j;
}
}
}
move(y, x, size);
if (passed[size- 1][size- 1])
{
printf("Yes\n");
}
else
{
printf("No\n");
}
return 0;
}

eclipse skips main function instead of executing it

I am using eclipse 3.2020 on WIN10 and I have a problem executing my main function.
When I run the program as it is, I get no output to conole, even when I add a printf in the first line, and the exit code is -1,073,741,819. When I comment out/ delete the line solve(s); the code run as intended and gives exit code 0.
Edit: added full code (both solve and print_sol are in solver.c)
Edit 2: As mentioned in the comments, the problem was in the code (bug) and not eclipse, I just assumed that an error message will be printed if there is one.
p.s.: I still find the fact a printf in the start won't print if there is a runtime error in another part of the main function quite weird.
main.c:
#include "solver.h"
#include <stdlib.h>
int main(int argc, char** argv){
int **grid = (int**) malloc(sizeof(int*) * 4);
for (int i = 0; i < 4 ; i++){
grid[i] = (int*) malloc(sizeof(int) * 4);
}
int mat[4][4] = {{1,0,3,0}
,{2,0,0,0}
,{3,0,0,0}
,{4,2,0,0}};
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
grid[i][j] = mat[i][j];
}
}
solver *s = create_solver(4, &grid);
solve(s);
print_sol(s);
}
solver.h:
#ifndef SOLVER_H_
#define SOLVER_H_
typedef struct sudoku_solver solver;
/*creates a new solver using the length of one row of the board.
*Then, the user will follow the instructions on screen to input the board*/
solver* create_solver(int row_len, int ***input_board_ptr);
/*if solver is NULL, an error will appear.
*Otherwise, The board that was given won't be changed, and neither
*the solver nor the solution (unless saved before using get_sol)
*will be accessible after this*/
void destroy_solver(solver *solver);
/*if solver is NULL, an error will appear.
*Otherwise, it will solve the inputed board*/
void solve(solver *solver);
/*if "solve" wasn't executed before, an error will appear.
*Otherwise, it will print a solution to the inputed board*/
void print_sol(solver *solver);
/*if "solve" wasn't executed before, an error will appear.
*Otherwise, returns a solution to the inputed board as a matrix of integers*/
int** get_sol(solver *solver);
#endif /* SOLVER_H_ */
solver.c:
#include "solver.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
/*the board will be represented by an array of size NxN.
*the value of every board cell is between 0 and N when 0
*means "default value"*/
typedef struct sudoku_solver{
/*length of one row of the board*/
int N;
/*a pointer to the solution board*/
int ***sol_ptr;
}solver;
solver* create_solver(int row_len, int ***input_board_ptr){
solver *s = (solver*) malloc(sizeof(solver));
/*throw an ERROR if the malloc failed*/
/*row_len is a variable, so we have to declare everything dynamically */
/*allocating the sol matrix as an array of pointers (1 out of 2D)*/
int **sol = (int**) malloc(row_len * sizeof(int*));
for (int i = 0; i < row_len; i++){
/*allocating every row (the second D)
*while making sol equal to input_board*/
sol[i] = (int*) malloc(row_len * sizeof(int));
for (int j = 0; j < row_len; j++){
sol[i][j] = (*input_board_ptr)[i][j];
}
}
s->N = row_len;
/*if row_len != pow(sqrt(row_len),2) then throw invalid input ERROR*/
s->sol_ptr = &sol;
return s;
}
void destroy_solver(solver *s){
for (int i = 0; i < s->N; i++){
free((*(s->sol_ptr))[i]);
}
free(*(s->sol_ptr));
free(s->sol_ptr);
free(s);
}
int* calc_next(int x, int y, int *next, solver *s);
bool isSafe(int x, int y, int val, solver *s);
bool solve_rec(int x, int y, solver *s);
void solve(solver *s){
int n = s->N;
int next[2];
int ***sp = s->sol_ptr;
//find next empty space
if ((*sp)[0][0] == 0){
next[0] = 0;
next[1] = 1;
}
else{
calc_next(0, 0, next, s);
}
int nextX = next[0];
int nextY = next[1];
for (int i = 1; i < n; i++){
if (isSafe(nextX, nextY, i, s)){
(*sp)[nextX][nextY] = i;
if(solve_rec(nextX, nextY, s)){
return;
}
//backtrack
(*sp)[nextX][nextY] = 0;
}
}
printf("no sol");
return;
}
bool solve_rec(int x, int y, solver *s){
int n = s->N;
int next[2];
int ***sp = s->sol_ptr;
if (x == n - 1 && y == n - 1){
return true;
}
//find next empty space
calc_next(x, y, next, s);
int nextX = next[0];
int nextY = next[1];
for (int i = 1; i < n; i++){
if (isSafe(nextX, nextY, i, s)){
(*sp)[nextX][nextY] = i;
if(solve_rec(nextX, nextY, s)){
return true;
}
//backtrack
(*sp)[nextX][nextY] = 0;
}
}
return false;
}
bool isSafe(int x, int y, int val, solver *s){
int n = s->N;
int ***sp = s->sol_ptr;
/*check row*/
for (int j = 0; j < n; j++){
if ((*sp)[x][j] == val){
return false;
}
}
/*check col*/
for (int i = 0; i < n; i++){
if ((*sp)[i][y] == val){
return false;
}
}
/*check block
*the index of a block in a grid is just like the index of entry in block.
*In sudoku, there are bs*bs blocks, and each has bs rows and bs columns*/
int bs = sqrt(n); // block size
int block_x_index = x / bs;
int block_y_index = y / bs;
for(int i = block_x_index * bs; i < bs * (block_x_index + 1); i++){
for(int j = block_y_index * bs; j < bs * (block_y_index + 1); j++){
if ((*sp)[i][j] == val){
return false;
}
}
}
return true;
}
/*assuming x,y is not the last place in the grid,
* finds the next empty place after it*/
int* calc_next(int x, int y, int *next, solver *s){
int n;
int ***sp = s->sol_ptr;
/*find the first empty place*/
do{
n = s->N;
if (y == n - 1){
x++;
y = 0;
}
else{
y++;
}
}while ((*sp)[x][y] != 0);
next[0] = x;
next[1] = y;
return next;
}
void print_sol(solver *s){
int n = s->N;
int bs = sqrt(n); // block size
char curr;
int rows_passed, col_passed;
for (int i = 0; i < n + bs - 1; i++){
for (int j = 0; j < n + bs - 1; j++){
//if it's a grid row
if (i == bs || ((i - bs) % (bs + 1)) == 0){
//if it's also a grid col
if (j == bs || ((j - bs) % (bs + 1) == 0)){
curr = '+';
}
else{
curr = '-';
}
}
//if it's only a grid col
else if (j == bs || ((j - bs) % (bs + 1) == 0)){
curr = '|';
}
else{
rows_passed = i / (bs + 1);
col_passed = j / (bs + 1);
curr = '0' + (*(s->sol_ptr))[i-rows_passed][j-col_passed];
}
printf("%c",curr);
}
printf("\n");
}
}
int** get_sol(solver *solver){
return *(solver->sol_ptr);
}
Thank you.
Please learn how to use your debugger. In this case, it would take you directly to the problem: you're crashing with an access violation (Windows 0xc0000005) here:
void solve(solver *s) {
int n = s->N;
int next[2];
int ***sp = s->sol_ptr;
//find next empty space
if ((*sp)[0][0] == 0) { // <-- Access violation here: "sp" incorrectly initialized!
next[0] = 0;
next[1] = 1;
}
The underlying problem is that although sudoku_solver.N was initialized to "4" ... sudoku_solver.sol_ptr[0][0] is pointing to uninitialized memory.
PS:
Yes, it's very definitely "executing". It wouldn't crash if it didn't run ;)

Why isn't the code coming out of recursion?

The problem is to find the number of times a word occurs in a given N x N matrix of alphabets. We can move from any cell to other adjacent cell. The first line has one integer N and then a N x N matrix. Next line has M (size of the word) and then a string to be found in the matrix.
Input:
4
ABCD
ABCD
ABCD
ABCD
2
BC
Expected output:
10
I have written the following code for the same and used recursion for solving the problem. The function adj checks if the character is adjacent in the matrix with the previous character using their indexes. The function check increases the count whenever the string is completed. The 2-d array keeps a check on the visited and unvisited elements.
I am getting the output as
OUPUT
1
EDIT 1: This output is just because of the debugging print statement, so the if statement is being visited only once. It does not mean that the count variable is 1 after many recursion calls.
EDIT 2: There shouldn't be & in the scanf statement for word. But still the output is not the desired one.
EDIT 3:
Another input
7
SHELDON
HSTYUPQ
EHGXBAJ
LMNNQQI
DTYUIOP
OZXCVBN
NQWERTY
7
SHELDON
Expected output:
5
My output - 1
EDIT 4(Solved!): So the problem was in writing the no. of columns as 500 for the grid matrix, changing it to 5 did the job! Thanks to #gsamaras
Code
#include <stdio.h>
int vis[500][500], count;
int adj(int a, int b, int c, int d) {
if((c == a - 1) && (d == b - 1)) {
return 1;
}
else if((c == a - 1) && (d == b)) {
return 1;
}
else if((c == a) && (d == b - 1)) {
return 1;
}
else if((c == a - 1) && (d == b + 1)) {
return 1;
}
else if((c == a + 1) && (d == b)) {
return 1;
}
else if((c == a + 1) && (d == b + 1)) {
return 1;
}
else if((c == a) && (d == b + 1)) {
return 1;
}
else if((c == a + 1) && (d == b - 1)) {
return 1;
}
else {
return 0;
}
}
void check(char grid[][500],int i, int j, int id, char word[], int n, int m) {
if(id == m) {
count++;
printf("%d\n", count); // just to debug
}
else {
for(int p = 0; p < n; p++) {
for(int q = 0;q < n; q++) {
if((grid[p][q] == word[id]) && (adj(i, j, p, q)) && (vis[p][q] != 1)) {
vis[p][q] = 1;
check(grid, p, q, id + 1, word, n, m);
vis[p][q] = 0;
}
}
}
}
}
int main() {
int n, m, id = 0;
char blank;
scanf("%d", &n);
scanf("%c", &blank);
char grid[n][n+1];
for(int i = 0; i < n; i++) {
scanf("%s", grid[i]);
grid[i][n] = '\0';
}
scanf("%d", &m);
char word[m+1];
scanf("%s", &word);
for(int i = 0; i < n; i++) {
for(int j = 0;j < n; j++) {
if(grid[i][j] == word[id]) {
vis[i][j] = 1;
check(grid, i, j, id + 1, word, n, m);
vis[i][j] = 0;
}
}
}
printf("%d\n", count);
return 0;
}
Change this:
void check(char grid[][500], ......
to this:
void check(char grid[][5], ....... // that should be equal to N + 1 (5 in your case)
since your grid is of size N x N + 1. With the 500 as the dimension, you distorted the grid, and when trying to search into it recursively, you wouldn't traverse the grid that you would expect to traverse..
As you see this is not flexible, since N can vary. You cannot declare grid as global, since its dimensions are not fixed. Dynamic memory allocation should be used instead.
Change this:
scanf("%s", &word);
to this:
scanf("%s", word);
since word is an array of characters.
Complete example with Dynamic Memory Allocation:
#include <stdio.h>
#include <stdlib.h>
int vis[500][500], count;
char **get(int N, int M) { /* Allocate the array */
int i;
char **p;
p = malloc(N*sizeof(char *));
for(i = 0 ; i < N ; i++)
p[i] = malloc( M*sizeof(char) );
return p;
}
void free2Darray(char** p, int N) {
int i;
for(i = 0 ; i < N ; i++)
free(p[i]);
free(p);
}
int adj(int a, int b, int c, int d) {
// Same as in your question
}
void check(char** grid, int i, int j, int id, char word[], int n, int m) {
if(id == m) {
count++;
printf("count = %d\n", count); // just to debug
}
else {
for(int p = 0; p < n; p++) {
for(int q = 0;q < 499; q++) {
//printf("p = %d, q = %d, id = %d, grid[p][q] = %c, word[id] = %c\n", p, q, id, grid[p][q], word[id]);
if((grid[p][q] == word[id]) && (adj(i, j, p, q)) && (vis[p][q] != 1)) {
vis[p][q] = 1;
check(grid, p, q, id + 1, word, n, m);
vis[p][q] = 0;
}
}
}
}
}
int main() {
int n, m, id = 0;
char blank;
scanf("%d", &n);
scanf("%c", &blank);
char** grid = get(n, n + 1);
for(int i = 0; i < n; i++) {
scanf("%s", grid[i]);
grid[i][n] = '\0';
}
scanf("%d", &m);
char word[m+1];
scanf("%s", word);
for(int i = 0; i < n; i++) {
for(int j = 0;j < n; j++) {
//printf("i = %d, j = %d, id = %d\n", i, j, id);
if(grid[i][j] == word[id]) {
vis[i][j] = 1;
check(grid, i, j, id + 1, word, n, m);
vis[i][j] = 0;
}
}
}
printf("%d\n", count);
free2Darray(grid, n);
return 0;
}
Output (for your 1st input):
count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
count = 8
count = 9
count = 10
10
PS: Not a problem, just a suggestion about readability: count is initialized to 0, because it's a global variable, but it's always best to explicitly initialize your variables, when it matters.

how do I writing function for this code

I'm trying to write a function or method for the code. I'm really lost at how to come with the loop that print out the number born and number died in the output below.
Here is my code:
#include <stdio.h>
char grid[10][10];
// Moved this function here
int occ(int x, int y) {
int i, j, count;
char gridCopy[10][10];
// You probably are going to do this often in the future
// Make a function for it instead of having the same code often
void printGrid() {
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++)
printf("%c", grid[i][j]);
printf("\n");
}
}
You don't need gridCopy in occ function.
Please remember that array is transposed. When you access element (x,y) you need to use grid[y][x]
Below is the working code with function generateNext() which generates next state for whole grid array. This is place where you need girdCopy. Results are exactly the same as in your example.
#include <stdio.h>
#include <stdlib.h>
char grid[10][10];
int born,died,generation;
// Moved this function here
int occ(int x, int y) {
int count;
int xm1,xp1,ym1,yp1;
xm1=x-1;xp1=x+1;ym1=y-1;yp1=y+1;
if (xm1<0) // handle boundary cases - wrap around
xm1=9;
if (ym1<0)
ym1=9;
if (xp1>9)
xp1=0;
if (yp1>9)
yp1=0;
// Checking on the value of the neighboring cells
count = 0;
if (grid[ym1][x] == '*')
count++;
if (grid[ym1][xp1] == '*')
count++;
if (grid[y][xp1] == '*')
count++;
if (grid[yp1][xp1] == '*')
count++;
if (grid[yp1][x] == '*')
count++;
if (grid[yp1][xm1] == '*')
count++;
if (grid[y][xm1] == '*')
count++;
if (grid[ym1][xm1] == '*')
count++;
return count;
}
void generateNext()
{
int x,y;
char gridCopy[10][10];
born=0;died=0;
generation++;
for (y=0; y<10; y++) {
for (x=0; x<10; x++) {
gridCopy[y][x]=grid[y][x];
}
}
for (y=0; y<10; y++) {
for (x=0; x<10; x++) {
if (grid[y][x]=='*' && occ(x,y)<2)
{gridCopy[y][x]='-';died++;}
if (grid[y][x]=='*' && occ(x,y)>3)
{gridCopy[y][x]='-';died++;}
if (grid[y][x]=='-' && occ(x,y)==3)
{gridCopy[y][x]='*';born++;}
}
}
for (y=0; y<10; y++) {
for (x=0; x<10; x++) {
grid[y][x]=gridCopy[y][x];
}
}
}
// You probably are going to do this often in the future
// Make a function for it instead of having the same code often
void printGrid() {
int x, y;
for (y = 0; y < 10; y++) {
for (x = 0; x < 10; x++)
printf("%c", grid[y][x]);
printf("\n");
}
}
/*
*
*/
int main(int argc, char** argv) {
int x, y, answ;
// Setting entire grid to '-'
for (y = 0; y < 10; y++)
for (x = 0; x < 10; x++)
grid[y][x] = '-'; // No need for a variable, just use '-' directly
// Printing out grid
printf("This is the original array\n");
printGrid();
// Setting initial state
grid[5][4] = '*'; // No need for a variable, just use '*' directly
grid[5][5] = '*';
grid[5][6] = '*';
grid[4][4] = '*'; grid[3][4] = '*';
grid[4][6] = '*'; grid[3][6] = '*';
// Printing out grid
printf("This is the new array\n");
printGrid();
//printf("The number of neighbors is: %d\n", occ(3, 3));
generation=0;
answ=1;
while(answ)
{
generateNext();
printf("\n\nGeneration number %d",generation);
printf("\nBorn=%d,Died=%d\n",born,died);
printGrid();
printf("\nPrint next generation-1,Exit-0:");
scanf("%d",&answ);
}
return (EXIT_SUCCESS);
}
Counting is similar to what you have to do to print or copy the whole grid: you use the same loop(s), but at each cell, add to the appropriate counter depending on what is in it.
Alternatively, if keep counts of the number of dead and live cells, you can update those as you update the grid: if a cell changes, update the counters appropriately if the cell becomes alive or becomes dead. This can also be used if you need to report how many were born & how many died each turn.

Generate all binary strings of length n with k bits set.(need to write on C)

Please help me to solve this task:
Generate all binary strings of length n with k bits set.(need to write on C)
for example:
n=5
k=3
11100
00111
11010
01011
**01110
11001
10011
**01101
**10110
10101
** can't generate these permutations
Code:
#include <stdio.h>
#define N 10
int main (void)
{
int mas[N]={0},kst,m,n1,z,a,b;
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d",&kst);
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d",&n1);
for(m=0;m1;m++)
mas[m]=1;
for(m=0;m<kst;m++)
printf("%d",mas[m]);
printf("\n");
for(m=0;m<n1;m++){
for(z=0;z<(kst-1);z++)
if((mas[z]==1) && (mas[z+1]==0)){
a=mas[z];
mas[z]=mas[z+1];
mas[z+1]=a;
for(b=0;b<kst;b++)
printf("%d",mas[b]);
printf("\n");
}
}
return 0;
}
I have solved this problem earlier! please find my code below! I hope this will help you out.
#include<stdio.h>
int NumberOfBitsSet(int number)
{
int BitsSet = 0;
while(number != 0)
{
if(number & 0x01)
{
BitsSet++;
}
number = number >> 1;
}
return BitsSet;
}
void PrintNumberInBinary(int number, int NumBits)
{
int val;
val = 1 << NumBits; // here val is the maximum possible number of N bits with only MSB set
while(val != 0)
{
if(number & val)
{
printf("1");
}
else
{
printf("0");
}
val = val >> 1;
}
}
int main()
{
int n,k,i;
int max,min;
printf("enter total number of bits and number of bits to be set:\n");
scanf("%d %d", &n, &k);
min = ((1 << k) - 1); //min possible values with k bits set
max = (min << (n-k)); //max possible value with k bits set!
//printf("%d %d", min, max);
for(i=0; i<= max; i++)
{
if(!(i<min))
{
if(NumberOfBitsSet(i) == k)
{
PrintNumberInBinary(i, (n-1));
printf("\n");
}
}
}
return 0;
}
Your code is a mess ;)
Seriously: first rule when solving a task in code is to write clean code, use sensible variable naming etc.
For tasks like this one I would suggest using this.
Now to your sample code: it would not compile and it is hard to read what you are trying to do. Formatted and with some comments:
#include <stdio.h>
#define N 10
int main(void)
{
int mas[N] = {0};
int kst, m, n1, z, a, b;
/* Read width ? */
printf("\n\nVvedit` rozmirnist` masyvu: ");
scanf("%d", &kst);
/* Read number of bit's set? */
printf("\n\nVvedit` kil`kist` odynyc`: ");
scanf("%d", &n1);
/* m1 is not defined, thus the loop give no meaning.
* Guess you are trying to set "bits" integers to 1.
*/
for (m = 0; m1; m++)
mas[m] = 1;
/* This should be in a function as 1. You do it more then once, and
* 2. It makes the code much cleaner and easy to maintain.
*/
for (m = 0; m < kst; m++)
printf("%d", mas[m]);
printf("\n");
for (m = 0; m < n1; m++) {
for (z = 0; z < (kst - 1); z++) {
if ((mas[z] == 1) && (mas[z + 1] == 0)) {
a = mas[z]; /* Same as a = 1; */
mas[z] = mas[z + 1]; /* Same as mas[z] = 0; */
mas[z + 1] = a; /* Same as mas[z + 1] = 1; */
/* Put this into a function. */
for (b = 0; b < kst; b++)
printf("%d", mas[b]);
printf("\n");
}
}
}
return 0;
}
The extensive use of printf when one are not sure of what is going on is a precious tool.
This is not a solution, (it is basically doing the same as your post, but split up), but a sample of something that might be easier to work with. I have also used a char array as C-string instead of integer array. Easier to work with in this situation.
If you want to use integer array I'd suggest you add a print_perm(int *perm, int width) helper function to get it out of the main code.
#include <stdio.h>
#define MAX_WIDTH 10
int get_spec(int *width, int *bits)
{
fprintf(stderr, "Enter width (max %-2d): ", MAX_WIDTH);
scanf("%d", width);
if (*width > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *width, MAX_WIDTH);
return 1;
}
fprintf(stderr, "Enter set bits (max %-2d): ", *width);
scanf("%d", bits);
if (*bits > MAX_WIDTH) {
fprintf(stderr, "Bad input: %d > %d\n", *bits, MAX_WIDTH);
return 1;
}
return 0;
}
void permutate(int width, int bits)
{
char perm[MAX_WIDTH + 1];
int i, j;
/* Set "bits" */
for (i = 0; i < width; ++i)
perm[i] = i < bits ? '1' : '0';
/* Terminate C string */
perm[i] = '\0';
fprintf(stderr, "\nPermutations:\n");
printf("%s\n", perm);
for (i = 0; i < bits; ++i) {
/* Debug print current perm and outer iteration number */
printf("%*s LOOP(%d) %s\n",
width, "", i, perm
);
for (j = 0; j < (width - 1); ++j) {
if (perm[j] == '1' && perm[j + 1] == '0') {
perm[j] = '0';
perm[j + 1] = '1';
printf("%s j=%d print\n",
perm, j
);
} else {
/* Debug print */
printf("%*s j=%d skip %s\n",
width, "", j, perm
);
}
}
}
}
int main(void)
{
int width, bits;
if (get_spec(&width, &bits))
return 1;
permutate(width, bits);
return 0;
}
If you want to list all of the permutations uniquely without doing "iterate and check", you can do something like this:
# Move peg x up m using s
# x is negative
# m is positive
def move(x, m, s):
for i in range(1, m+1):
s2 = list(s)
s2[x] = 0
s2[x - i] = 1
print(s2)
if x + 1 < 0:
move(x+1, i, s2)
# Print all unique permutations of
# n bits with k ones (and n-k zeros)
def uniqPerms(n, k):
s = [0 for _ in range(n-k)] + [1 for _ in range(k)]
print(s)
move(-k, n-k, s)
if __name__ == '__main__':
from sys import argv
uniqPerms(int(argv[1]), int(argv[2]))
The idea is that you inch the 1's up recursively, so that each movement produces a unique list (since a 1 is now somewhere none was before).
And you said it must be in C:
#include <stdio.h>
#include <stdlib.h>
enum { n = 8 };
struct string
{
char str[n + 1];
};
void move(int x, int m, string s)
{
for (int i = 0; i <= m; ++i)
{
string s2 = s;
s2.str[n + x] = '0';
s2.str[n + x - i] = '1';
printf("%s\n", s2.str);
if (x + 1 < 0)
move(x + 1, i, s2);
}
}
void uniqPerms(int k)
{
string s;
for (int i = 0; i < n - k; ++i)
s.str[i] = '0';
for (int i = n - k; i < n; ++i)
s.str[i] = '1';
s.str[n] = '\0';
printf("%s\n", s.str);
move(-k, n - k, s);
}
int main(int argc, char *argv[])
{
uniqPerms(atoi(argv[1]));
return 0;
}
try this
A[n-1]=0;
func(n-1);
A[n-1]=1;
func(n-1);
//Think simple people but please bear with me i love java
//Assume array A is globally defined
void Binary(int n)
{
if(n<1)
{
System.out.println(A);
}
else
{
A[n-1]=0;
Binary(n-1);
A[n-1]=1;
Binary(n-1);
}
}
here is the recursive solution
#include <iostream>
#include <vector>
using namespace std;
char v[4];
int count = 0;
void printString(){
int i;
for(i = 0; i < 4; i++){
cout << v[i] << " ";
}
cout <<count << endl;
}
void binary(int n){
if(n < 0){
if(count == 2)
printString();
}
else{
v[n] = '0';
binary(n - 1);
v[n] = '1';
count++;
binary(n-1);
count--;
}
}
int main(){
binary(3);
return 0;
}
#include<stdio.h>
int main(){
int n,k,i,j,a[50];
//lets suppose maximum size is 50
printf("Enter the value for n");
scanf("%d",&n);
printf("Enter the value for k");
scanf("%d",&k);
//create an initial bitstring of k 1's and n-k 0's;
for(i=0;i<n;i++){
if(k>0)
a[i]=1;
else
a[i]=0;
k--;
}
for(i=0;i<n;i++){
if(a[i]==1){
for(j=0;j<n;j++){
if(j!=i&&a[j]==0){
a[j]=1;a[i]=0;
for(k=0;k<n;k++){printf("%d\n",a[k]);}
a[i]=1; a[j]=0;
}}}}
return 0;
}
**If Complexity doesn't matter you can use the following code which are done in java. which will provide the desired output in o(2^n).Here I have find all the combination of 0 and 1 for the given n bits in array of size n.In case of K bit is set I have counted the number of 1 presented is equal to k using countBits() funtion.if so I have printed that array.
public class GenerateAllStringOfNBitsWithKBitsSet {
public static int a[] ={0,0,0,0,0};
static int k=3;
public static boolean countBits(){
int y=0;
for(int i=0;i<a.length;i++)
y += a[i] & 1 ;
if(y==k)
return true;
return false;
}
public static void gen(int n)
{
if(n<1)
{
if(countBits())
System.out.println(Arrays.toString(a));
}
else
{
a[n-1]=0;
gen(n-1);
a[n-1]=1;
gen(n-1);
}
}
public static void main(String[] args) {
GenerateAllStringOfNBitsWithKBitsSet.gen(a.length);
}
}

Resources