So I am facing hair loss day by day because of this sub-task required for my first year assignment.
I need to print a 'box' around the number at coordinate [5][5] / i.e center of the board during the initialization stage of the program.
The 'box' consists of "|" covering the sides and "_" on top and bottom of the number at coordinate [5][5].
When I execute this program, the board shows but the 'box' doesn't. Why is this happening??
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//FUNCTION: Draw the Board
int drawBoard()
{
//Declare array size
int board[9][9];
//initialize variables
int rows, columns, randomNumber, flag;
//random number seed generator
srand(time(NULL));
for ( rows = 0 ; rows < 9 ; rows++ )
{
for ( columns = 0 ; columns < 9 ; columns++ )
{
flag = 0;
do
{
//generate random numbers from 2 - 8
randomNumber = rand() %7 + 2;
board[rows][columns] = randomNumber;
//Display the 'box' if rows and columns == 5 / i.e - board[5][5]
if ( rows == 5 && columns == 5 )
{ //Checks for 2 adjacent numbers
if ( board[rows][columns] == board[rows - 1][columns] || board[rows][columns] == board[rows][columns - 1] )
{
flag = 0;
continue;
}
else
{
flag = 1;
//Print 'box'
marker( rows, columns );
}
}
//Checks for 2 adjacent numbers.
if ( board[rows][columns] == board[rows - 1][columns] || board[rows][columns] == board[rows][columns - 1] )
{
flag = 0;
continue;
}
else
//Prints the correct board
{
flag = 1;
printf( " %d ", board[rows][columns] );
}
} while ( flag == 0 ); //end outer do-while
}//end inner for-loop
printf("\n\n");
}//end outer for-loop
}//end FUNCTION drawBoard
//FUNCTION: Mark the surrounding of the number with "|" and "_" at board[5][5]
void marker( int x, int y, int** board )
{
board[x][y-1] == "\n _ ";
board[x][y+1] == "\n _ ";
board[x-1][y] == " |";
board[x+1][y] == "| ";
}
int main()
{
drawBoard();
}
TI
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
//FUNCTION: Draw the Board
char tochar(int i)
{
return i+'0';
}
void marker( int x, int y, char board[][19] );
int check(int x, int y, char board[][19])
{
if(x>1&&board[2*x+1][2*y+1]==board[2*x-1][2*y+1])
return 1;
if(y>1&&board[2*x+1][2*y+1]==board[2*x+1][2*y-1])
return 1;
return 0;
}
int drawBoard()
{
//Declare array size
char board[19][19];
memset(board,32, sizeof(board));
//initialize variables
int rows, columns, randomNumber, flag;
//random number seed generator
srand(time(NULL));
for ( rows = 0 ; rows < 9 ; rows++ )
{
for ( columns = 0 ; columns < 9 ; columns++ )
{
flag = 0;
do
{
//generate random numbers from 2 - 8
randomNumber = rand() %7 + 2;
board[2*rows+1][2*columns+1] = tochar(randomNumber);
//Display the 'box' if rows and columns == 5 / i.e - board[5][5]
if ( rows == 4 && columns == 4 )
{ //Checks for 2 adjacent numbers
if ( check(rows, columns, board))
{
flag = 0;
}
else
{
flag = 1;
marker( 2*rows+1, 2*columns+1, board );
//Print 'box'
}
}
else
{
//Checks for 2 adjacent numbers.
if ( check(rows, columns, board))
{
flag = 0;
}
else
//Prints the correct board
{
flag = 1;
// printf( " %c ", board[2*rows+1][2*columns+1] );
}
}
} while ( flag == 0 ); //end outer do-while
}//end inner for-loop
printf("\n\n");
}//end outer for-loop
for(rows=0;rows<19;rows++)
{
for(columns=0;columns<19;columns++)
{
printf("%c",board[rows][columns]);
}
printf("\n");
}
}//end FUNCTION drawBoard
//FUNCTION: Mark the surrounding of the number with "|" and "_" at board[5][5]
void marker( int x, int y, char board[][19] )
{
board[x][y-1] = '|';
board[x][y+1] = '|';
board[x-1][y] = '_';
board[x+1][y] = '_';
/*
192
191
217
218
*/
}
int main()
{
drawBoard();
}
void marker( int x, int y, int** board )
{
board[x][y-1] == "\n _ ";
board[x][y+1] == "\n _ ";
board[x-1][y] == " |";
board[x+1][y] == "| ";
}
This won't work. The '==' is for comparing, not assigning. You need a '='.
However, board is an array of int, you can't assign a const char* (because that's what "something" is) in an array of int. Your board should be an array of char, and then you can assign like this:
void marker( int x, int y, char** board )
{
board[x][y-1] = '_';
board[x][y+1] = '_';
board[x-1][y] = '|';
board[x+1][y] = '|';
}
Another problem is that the center of the board is at index [4][4], the fifth element of a table of size 9. But that is a smaller problem...
I see what you want to do here, this isn't the way I usually think, so I may be not helpfull :s
first, a mistake:
in "drawboard": marker( rows, columns )
prototype of "marker": void marker( int x, int y, int** board ). I don't think compilation with flag will work (and yes, flags ARE helpfull, try "gcc -Wall -Wextra -Werror")
Moreover, I think you should re-think your function "marker", it can't work.
I think board[x][y-1] = "\n _ " would do the trick, if you return(board[x][y-1]) but again, I would have work with a char**, not an integer tab, and with many short functions (and used write instead of printf :p)
Related
So basically the user inputs how many countries they have visited in a variable, then I take it as the size of the array.
After that I use a for loop to list out all the countries visited. But I want to make my code a little smarter and put and at the end of the sentence for the final country.
For example 3 countries:
You visited Japan, Korea and Canada.
^ ^^^
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int number_of_p = get_int("How many countries did you visit?\n");
string countries[number_of_p];
for (int x = 0; x < number_of_p; x++)
{
countries[x] = get_string("What countries did you visit?\n");
}
printf("You visited %i countries, including: ", number_of_p);
for (int x = 0; x < number_of_p; x++)
{
printf("%s, ", countries[x]);
/* looks for last element in arrays, inserts 'and'
to make it look grammatically correct. */
if (countries[x] == number_of_p - 1 ) // ERROR HERE
{
printf(" and ");
}
}
printf(".\n");
}
I'm getting a comparison between pointer (char*) and integer error.
What does char* mean?
How do I access the last element in an array?
countries[x] is a string (which in CS50 is a typedef of char*), number_of_p is an int, you can't compare them, they are different types, you may have wanted to compare the index x, a possible (and quick) fix for your code, including the punctuation could look like this:
Live demo
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int number_of_p = get_int("How many countries did you visit?\n");
string countries[number_of_p];
for (int x = 0; x < number_of_p; x++)
{
countries[x] = get_string("What countries did you visit?\n");
}
printf("You visited %i countries, including: ", number_of_p);
for (int x = 0; x < number_of_p; x++)
{
printf("%s", countries[x]);
if(x < number_of_p - 2){
printf(", ");
}
if (x == number_of_p - 2)
{
printf(" and ");
}
}
printf(".\n");
}
Input:
3
Japan
Korea
Canada
Output:
You visited 3 countries, including: Japan, Korea and Canada.
The condition in the if statement
if (countries[x] == number_of_p - 1 )
does not make a sense. The left operand countries[x] has the type char * while the right operand has the type int.
That is the type specifier string is an alias for the type char * and this declaration of an array
string countries[number_of_p];
is the same as
char * countries[number_of_p];
So you have an array of pointers that point to strings.
The alias string for the type char * in C defined the following way
typedef char * string;
The loop can look like
for (int x = 0; x < number_of_p; x++)
{
if ( x != 0 )
{
putchar( ',' );
putchar( ' ' );
if ( x == number_of_p - 1 )
{
printf( "%s ", "and " );
}
}
printf("%s", countries[x]);
}
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
enum { number_of_p = 3 };
char *countries[number_of_p] =
{
"Japan", "Korea", "Canada"
};
printf( "You visited %i countries, including: ", number_of_p );
for (int x = 0; x < number_of_p; x++)
{
if ( x != 0 )
{
putchar( ',' );
putchar( ' ' );
if ( x == number_of_p - 1 )
{
printf( "%s ", "and" );
}
}
printf("%s", countries[x]);
}
return 0;
}
Its output is
You visited 3 countries, including: Japan, Korea, and Canada
You can do this sort of thing with one printf, using a predefined string for the separator. Using a single printf rather than special casing the tail of the list is generally easier to maintain. Many people find the ternary operator confusing; here's the approach in two different ways, using a switch first and the ternary operator second:
#include<stdio.h>
int main(void)
{
char *countries[] = { "foo", "bar", "baz" };
int number_of_p = sizeof countries / sizeof *countries;
/* First loop, using a switch */
for( int x = 0; x < number_of_p; x++ ) {
char *div = ", ";
switch( x ){
case sizeof countries / sizeof *countries - 2: div = ", and "; break;
case sizeof countries / sizeof *countries - 1: div = ".\n"; break;
}
printf("%s%s", countries[x], div);
}
/* Same loop as above, with if/else instead of the switch */
for( int x = 0; x < number_of_p; x++ ) {
char *div = ", ";
if( x == number_of_p - 2 ) {
div = ", and ";
} else if( x == number_of_p - 1 ) {
div = ".\n";
}
printf("%s%s", countries[x], div);
}
/* Same loop as above, written less verbosely */
for( int x = 0; x < number_of_p; x++ ) {
printf("%s%s", countries[x], x == number_of_p - 2 ? ", and " :
x == number_of_p - 1 ? ".\n" : ", ");
}
}
An assignment we have been given is to draw an X in C using only while loops and if statements (maths and expressions are allowed).
I have only done the first half of the X in code, as the other half is just the reverse.
The challenging part is the middle dashes (-), as I'm struggling to find a way to make them count backward by 2 through while loops.
Am I overthinking this way too much? If so, what would be a better approach to this problem?
This is my first time learning C and we are not allowed for loops or anything beyond a basic level.
Thanks for reading!
int size, fLine, rowCounter, tempSize;
printf("Enter size: ");
scanf("%d", &size);
// The split will half the size of the X to run 2 seperate while loops
// One loop for the top half and another for the lower half.
int split = ((size - 1) / 2);
int row = 1;
// Top half of the X
while (row <= split) {
// Condition to print out the top and bottom line of the X
if ((row == 1) || (row == size)) {
printf("*");
// tempSize will allow for the counter to decrease without
// affecting the size variable
tempSize = size;
// Will add the middle dashes on the top line
while ((tempSize - 2) > 0) {
printf("-");
tempSize--;
}
printf("*\n");
row++;
} else {
// The dashes before the first asterisks
// rowCounter allows the row number to be decreased in the
// while loop
rowCounter = row - 1;
while (rowCounter > 0) {
printf("-");
rowCounter--;
}
printf("*");
// Will add size + (row * -2) dashes into the middle
// **This section is the subject of the question!**
rowCounter = row * 2;
tempSize = rowCounter - size; // 2 - 5 = -3
while (tempSize < (size - 1)) {
printf("-");
tempSize++;
}
printf("*");
// Will add the final dashes. Exactly the same as the first
// while loop
rowCounter = row - 1;
while (rowCounter > 1) {
printf("-");
rowCounter--;
}
printf("-\n");
row++;
} //Yet to add the middle line and the bottom half!
}
return 0;
}
Expected Result:
Enter Size: 5
*---*
-*-*-
--*--
-*-*-
*---*
Actual Result:
Enter Size: 5
*---*
-*-----*-
I want the middle values to count BACKWARD so 9, 7, 5, 3, 1, etc., instead of upwards by 2.
i have a much easier solution
#include <stdio.h>
int size, i=0, j=0;
printf("Please Enter a Odd Size: \n")
scanf(%d, &size);
while(size%2==0)
{
printf("Only Odd size is ok \n");
printf("Please Enter a Odd Size: \n")
scanf(%d, &size);
}
while(i<size)
{
j=0;
while(j<size)
{
if(j == i || i == (size-1)-j)
{
printf("!");
}
else
{
printf("-");
}
j++;
}
printf("\n\n");
i++;
}
the output is:
!---!
-!-!-
--!--
-!-!-
!---!
I messed around a little:
#include <stdio.h>
int main()
{
int size = 5;
if( size % 2 == 1 )
{
fprintf( stdout, "now drawing\n");
int lineCount = 0;
int lastPost = size - 1;
while( lineCount < size )
{
int rowCount = 0;
while( rowCount < size )
{
if( ( rowCount == lineCount )
|| ( rowCount == lastPost ) )
{
fprintf( stdout, "X");
}
else
{
fprintf( stdout, ".");
}
++rowCount;
}
fprintf( stdout, "\n");
--lastPost;
++lineCount;
}
}
else
{
fprintf( stderr, "size must be odd!\n");
}
return 0;
}
I have been asked this question during an interview, and have been struggling to find an elegant solution (in C), Problem statement:
You are given a two-dimensional array with M rows and N columns.
You are initially positioned at (0,0) which is the top-left cell in
the array.
You are allowed to move either right or downwards.
The array is filled with 1′s and 0′s. A 1 indicates that you can move
through that cell, a 0 indicates that you cannot move through the
cell.
Write a function in C ‘numberOfPaths’ which takes in the above two dimensional array, return the number of valid paths from the top-left cell to the bottom-right cell (i.e. [0,0] to [M-1,N-1]).
Edit: forgot to mention that the requirement is for a recursive solution
help would be greatly appreciated!
Thanks
If you are looking for a recursive solution you can use DFS.
DFS (array, x, y)
{
if (array [x][y]==0 || x>M || y>N){
return;
}
if (x==M && y==N){
count++;
return;
}
DFS (array, x, y+1);
DFS (array, x+1, y);
}
The number of paths to a given point is just the number of paths to the point above, plus the number of paths to the point to the left. So, the pseudo-code would roughly be:
num_paths[0][0] = 1;
for (x = 0; x < M; ++x)
for (y = 0; y < N; ++y)
if (!allowed_through[x][y])
num_paths[x][y] = 0;
else
num_paths[x][y] = num_paths[x-1][y] + num_paths[x][y-1];
You need special cases for x=0 and y=0, but otherwise, I think that should do.
#include <stdio.h>
int count=0;
int maxrows = 10;
int maxcols = 10;
int M, N;
void DFS (int array[][10], int x, int y)
{
int r, c;
/* process element at input row and column */
if (array [x][y]==0 || x>M || y>N){
/* no path forward; return */
return;
}
if (x==M-1 && y==N-1){
/* found path; increment count */
count++;
return;
}
/* recurse: to matrix starting from same row, next column */
r = x;
c = y +1;
if (c < N-1) {
DFS (array, r,c);
} else {
/* if last column - check to see */
/* if rest of rows in last column allow for a path */
int tr = r;
while ( tr <= M-1) {
if (array[tr][c] == 1) {
tr++;
}
else {
return;
}
}
/* reached last node - path exists! */
count++;
}
/* recurse: to matrix starting from next row, same column */
r = x+1;
c = y;
if (r < M-1) {
DFS (array, r,c);
} else {
/* if last row - check to see */
/* if rest of columns in last row allow for a path */
int tc = c;
while ( tc <= N-1) {
if (array[r][tc] == 1) {
tc++;
} else {
return;
}
}
/* reached last node - path exists! */
count++;
}
}
int main () {
int i, j;
scanf("%d %d",&M,&N);
int a[10][10] = {};
int row, col;
for(i=0;i<M;i++)
for(j=0;j<N;j++)
scanf("%d", &a[i][j]);
if ((M > maxrows) || (N > maxcols)) {
printf("max of 10 rows and 10 cols allowed for input\n");
return (-1);
};
/* print input matrix */
for(row=0;row<M;row++) {
for(col=0;col<N;col++){
printf("%d ",a[row][col]);
}
printf(" EOR\n");
}
DFS(a,0,0);
printf("number of paths is %d\n", count);
return 0;
}
Try this function its a preliminary step before printing all the paths.
If the size of the vector Out is 0 then the # of paths are 0, but if size(Out) > 0 then the size of vector Nodes + 1 are the total number of paths from top left to bottom right.
#include <iostream>
#include <vector>
using namespace std;
typedef vector<pair<int,int> > vPii;
bool pathTL2BR( int Arr2D[][4], vPii &Out, vPii &Nodes,
int _x,int _y, int _M, int _N)
{
bool out1 = false;
bool out2 = false;
if( Arr2D[_x][_y] == 1 )
{
if( _y+1 < _N )
out1 = pathTL2BR( Arr2D, Out, Nodes, _x, _y+1, _M, _N);
if( _x+1 < _M )
out2 = pathTL2BR( Arr2D, Out, Nodes, _x+1, _y, _M, _N);
if( (out1 || out2) ||
( (_x == (_M-1)) && (_y == (_N-1)) ) )
{
if(out1 && out2)
Nodes.push_back( make_pair(_x,_y ) );
Out.push_back( make_pair(_x,_y ) );
return true;
}
else
return false;
}
else
return false;
}
// Driver program to test above function
int main()
{
int Arr2D[][4] = {
{1,1,1,1},
{0,1,0,1},
{0,1,0,1},
{0,1,0,1}
};
vPii Out;
vPii Nodes;
vector<vPii> Output;
pathTL2BR( Arr2D, Out, Nodes, 0, 0, 4, 4);
return 0;
}
This is a python solution, I have put explanations in the comments.
def find_num_paths(arr_2D, i, j):
# i,j is the start point and you have to travel all the way back to 0,0
if i == j and i == 0:
return 1 # you have reached the start point
if i < 0 or j < 0 or arr_2D[i][j] == 0: # out of range or no path from that point
return 0
if arr_2D[i][j] == 1:
return find_num_paths(arr_2D, i, j-1) + find_num_paths(arr_2D, i-1, j) + find_num_paths(arr_2D, i-1, j-1) # you could go one step above, to the left or diagonally up.
I was trying to search for a particular word in a matrix of characters through C but was unable to come to a fixed solution.
For ex:
Suppose I have to search for the word INTELLIGENT in a matrix of characters (3*9)
(Once you have picked a character from the matrix to form a sentence, you cannot pick it again to form the same sentence.There is a path from any cell to all its neighboring cells. A neighbor may share an edge or a corner.)
IIIINN.LI
....TTEGL
.....NELI
Output: YES (the word INTELLIGENT can be found)
Can anybody please give a solution to the above problem !!!!
Use a depth first search.
You can do this using a recursive algorthm. Find all the (unused) places containing the first letter then see if it is possible to find the rest of the word on the remaining board by starting from one of the adjacent squares.
#include <stdio.h>
char Matrix[3][9] = {
{ 'I','I','I','I','N','N','.','L','I'},
{ '.','.','.','.','T','T','E','G','L'},
{ '.','.','.','.',',','N','E','L','I'}
};
char Choice[3][9] = { { 0 }, { 0 }, { 0 } };
const char WORD[] = "INTELLIGENT";
const int Len = sizeof(WORD)-1;
int Path[sizeof(WORD)-1] = { 0 };
char get(int row, int col){
if(1 > col || col > 9) return '\0';
if(1 > row || row > 3) return '\0';
if(Choice[row-1][col-1] || Matrix[row-1][col-1] == '.')
return '\0';
else
return Matrix[row-1][col-1];
}
#define toLoc(r, c) (r)*10+(c)
#define getRow(L) L/10
#define getCol(L) L%10
int search(int loc, int level){
int r,c,x,y;
char ch;
if(level == Len) return 1;//find it
r = getRow(loc);
c = getCol(loc);
ch = get(r,c);
if(ch == 0 || ch != WORD[level]) return 0;
Path[level]=toLoc(r,c);
Choice[r-1][c-1] = 'v';//marking
for(x=-1;x<=1;++x){
for(y=-1;y<=1;++y){
if(search(toLoc(r+y,c+x), level + 1)) return 1;
}
}
Choice[r-1][c-1] = '\0';//reset
return 0;
}
int main(void){
int r,c,i;
for(r=1;r<=3;++r){
for(c=1;c<=9;++c){
if(search(toLoc(r,c), 0)){
printf("YES\nPath:");
for(i=0;i<Len;++i){
printf("(%d,%d)", getRow(Path[i]), getCol(Path[i]));
}
printf("\n");
return 0;
}
}
}
printf("NO\n");
return 0;
}
I think this is what you mean..... Though it seems simpler to what you currently have been offered, so I may have misunderstood the question.
I use Numpy to reshape an arbitrary array into a single
list of letters, then we create a mask of the search term and
a copy of the input list.
I tick off each letter to search for while updating the mask.
import numpy as np
import copy
def findInArray(I,Word):
M=[list(x) for x in I]
M=list(np.ravel(M))
print "Letters to start: %s"%"".join(M)
Mask=[False]*len(Word)
T = copy.copy(M)
for n,v in enumerate(Word):
try:
p=T.index(v)
except ValueError:
pass
else:
T[p]=''
Mask[n]=True
print "Letters left over: %s"%"".join(T)
if all(Mask):print "Found %s"%Word
else:print "%s not Found"%Word
print "\n"
return all(Mask)
I=["IIIINN.LI","....TTEGL",".....NELI"]
findInArray(I,"INTEL")
findInArray(I,"INTELLIGENT")
findInArray(I,"INTELLIGENCE")
Example output
Letters to start: IIIINN.LI....TTEGL.....NELI
Letters left over: IIIN.I....TGL.....NELI
Found INTEL
Letters to start: IIIINN.LI....TTEGL.....NELI
Letters left over: II.I.........NLI
Found INTELLIGENT
Letters to start: IIIINN.LI....TTEGL.....NELI
Letters left over: II.I....T.....NLI
INTELLIGENCE not Found
#include <stdio.h>
#define ROW 1
#define COL 11
char Matrix[ROW][COL] = { { 'I','N','T','E','L','L','I','G','E', 'N', 'T'} };
char Choice[ROW][COL] = { { 0 } };
const char WORD[] = "INTELLIGENT";
const int Len = sizeof(WORD)-1;
int Path[sizeof(WORD)-1] = { 0 };
char get(int row, int col){
if(1 > col || col > COL) return '\0';
if(1 > row || row > ROW) return '\0';
if(Choice[row-1][col-1] || Matrix[row-1][col-1] == '.')
return '\0';
else
return Matrix[row-1][col-1];
}
#define toLoc(r, c) (r)*16+(c)
#define getRow(L) L/16
#define getCol(L) L%16
int search(int loc, int level){
int r,c,x,y;
char ch;
if(level == Len) return 1;//find it
r = getRow(loc);
c = getCol(loc);
ch = get(r,c);
if(ch == 0 || ch != WORD[level]) return 0;
Path[level]=toLoc(r,c);
Choice[r-1][c-1] = 'v';//marking
for(x=-1;x<=1;++x){
for(y=-1;y<=1;++y){
if(search(toLoc(r+y,c+x), level + 1)) return 1;
}
}
Choice[r-1][c-1] = '\0';//reset
return 0;
}
int main(void){
int r,c,i;
for(r=1;r<=ROW;++r){
for(c=1;c<=COL;++c){
if(search(toLoc(r,c), 0)){
printf("YES\nPath:");
for(i=0;i<Len;++i){
printf("(%d,%d)", getRow(Path[i]), getCol(Path[i]));
}
printf("\n");
return 0;
}
}
}
printf("NO\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define TAB_STOP 8
/* replaces tabs from input with the proper amount of blank spots */
int Detab()
{
int c, x;
int column;
x = column = 0;
while((c=getchar())!=EOF)
{
if(c == '\n') /* reseting counter if newline */
{
putchar(c);
return 1;
}
else if(c!='\t') /* column counts places to tab spot */
{
putchar(c);
column++;
if(column == TAB_STOP)
column = 0;
}
else /* tab */
{
for(x=0; x<TAB_STOP - column; x++)
putchar('_');
column = 0;
}
}
return 0;
}
#define MAX_ARGUMENTS 100
int main(int argc, char *argv[])
{
int i, val = 0;
int nums[MAX_ARGUMENTS];
int x = 0;
for(i = 1; i < argc; i++) {
while(isdigit(*argv[i])) {
val = val * 10 + *argv[i] - '0';
*++argv[i];
}
if(x > MAX_ARGUMENTS - 1)
return 0;
nums[x++] = val;
nums[x] = '\0';
val = 0;
}
while(Detab(nums));
printf("Press any key to continue.\n");
getchar();
return 0;
}
In main i put all the arguments(numbers) inside nums array and then pass it to detab. So now im interested what would be the smart way to edit detab so it works. I'm still trying to figure out for a working pseudocode but i dont really know.
The way i tought it should work is:
if arguments are 5, 8, 10 then a tab inside first 4 characters leads to position 5, in 5 - 7th char leads to pos 8 etc.
In case of a newline, the arguments start all over again from the begining.
The most common way is to have Detab accept a pointer (which points to an element in an array) and the length of that array:
int Detab(int* data, int len); // access data[0] through data[len - 1]
Call it like so:
void example() {
int array[] = {5, 8, 10};
Detab(array, 3);
// or:
Detab(array, sizeof array / sizeof *array); // second parameter evaluates to 3
// without using a magic constant
}
Here's some pseudocode for expanding tabs:
def expandtabs_in_line(line, tabstops, default, space):
result = ""
for c in line:
if c != "\t":
result += c
else:
for stop in tabstops:
if stop > len(result):
result += space * (stop - len(result))
break
else:
result += space * (default - (len(result) % default))
return result
def expandtabs(lines, tabstops=[], default=8):
for line in lines:
yield expandtabs_in_line(line, tabstops, default, " ")
Try it out at codepad.