I'am trying to write a program for converting the given string in cross manner(i.e Diagonal from left-right and from right-left). If the string length is even it returns a message else arrange it in a cross form.
The code is:
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
char str2[50][50];
int lenstr;
int i,j;
char temp;
printf("Enter the string :\n");
scanf("%s",str);
lenstr = strlen(str);
if(lenstr %2 == 0)
{
printf("The string length must be an odd length");
}
else
{
j = 0;
temp = 0;
for(i = 0;i == lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = lenstr; i==0 ;i--)
{
j = lenstr;
str2[i][j] = str[temp];
temp = temp + 1;
j = j - 1;
}
for(i = 0;i<lenstr;i++)
{
for(j = 0;j<lenstr;j++)
{
printf("%c",str2[i][j]);
}
printf("\n");
}
}
return 0;
}
The output to the program must be for example: geeks
g g
e e
e
k k
s s
But the output obtained consists of different shapes(like heart,smiley face etc...). Explain the concept behind to correct it and if can please explain when using pointers for the same program. Any help appreciated.
In your code, you need to change the for loop condition checking expressions, like i == lenstr and later i==0. They are not entering the loop, essentially.
Instead, you can replace the whole block
for(i = 0;i == lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = lenstr; i==0 ;i--)
{
j = lenstr;
str2[i][j] = str[temp];
temp = temp + 1;
j = j - 1;
}
in your code by
for(i = 0;i<lenstr;i++)
for(j = 0;j<lenstr;j++)
str2[i][j] = ' '; //fill 2D array with space
for(i = 0;i < lenstr;i++)
{
str2[i][i] = str[i]; //set the character
str2[i][lenstr- i -1] = str[i]; //reverse position
}
and get the desired output.
See it LIVE.
Your logic to store diagonal string seems to be wrong. In the first loop you store left-right diagonal and your index goes from 0 to length-1 and your column starts from 0; increment it by 1. Its same for right-left diagonal, only difference being column starts from length-1 and ends at 0. Hence you need to initialize temp = lenstr -1;
temp = lenstr -1;
for(i = 0;i <lenstr;i++)
{
str2[i][j] = str[i];
j = j + 1;
}
for(i = 0;i <lenstr;i++)
{
str2[i][temp] = str[i];
temp = temp - 1;
}
I think the problem is that str2 is not getting initialized. The first two for loops should be something like
for(i = 0;i < lenstr;i++)
and
for(i = lenstr; i>=0 ;i--)
Here is my five cents. The program allows to enter words with an odd or even number of letters.
Enjoy!:)
#include <stdio.h>
#include <string.h>
#define N 25
int main(void)
{
while ( 1 )
{
char s[N];
printf( "Enter a string less than %zu characters (Enter-exit): ", N );
if ( !fgets( s, N, stdin ) || s[0] == '\n' ) break;
size_t n = strlen( s );
if ( s[n-1] == '\n' ) s[--n] = '\0';
printf( "\n" );
for ( size_t i = 1, j = n; i <= n; i++, j-- )
{
char c = s[i-1];
if ( i < j ) printf( "%*c%*c\n", i, c, j - i, c );
else if ( j < i ) printf( "%*c%*c\n", j, c, i - j, c );
else printf( "%*c\n", i, c );
}
}
return 0;
}
If to enter
Stackoverflow
hello
then the program output will be
Enter a string less than 25 characters (Enter-exit): Stackoverflow
S S
t t
a a
c c
k k
o o
v
e e
r r
f f
l l
o o
w w
Enter a string less than 25 characters (Enter-exit): hello
h h
e e
l
l l
o o
Enter a string less than 25 characters (Enter-exit):
import java.util.*;
public class CrossCharacter {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String str = in.next();
int len = str.length();
char[][] ch_matrix = new char[len][len];
len--;
for(int i=0;i<=len;i++)
ch_matrix[i][i] = ch_matrix[i][len-i] = str.charAt(i);
for(int i=0;i<=len;i++){
for(int j=0;j<=len;j++)
System.out.print(ch_matrix[i][j]);
System.out.println();
}
}
}
# include<stdio.h>
void main() {
char n[100],temp;
int i = 0, j;
scanf("%s", &n);
m = strlen(n);
for(i = 0; i <= m - 1;)
temp[i];
i++;
for(j = 0; j < m - 1; j++)
{
if(i == j + 1 || j == m - 1 - i + 1)
printf("%c",temp);
else
printf(" "):
}
printf("\n");
getch();
}
Related
How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div 4):
(Problem) Chef has an array A of length N. Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .
Determine the minimum possible value of X. If no possible value of X exists, output -1.
Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int* binary_number(int n) // returns pointer to a array of length 20(based on given constrains) representing binary
{
int* ptc;
ptc = (int*) malloc(20*sizeof(int));
for(int i = 0; i < 20; i++)
{
if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
else {*(ptc + i) = 0;}
n = n % (int) pow(2,19-i) ;
}
return ptc;
}
int or_value(int* ptc, int n) // Takes in pointers containing 1 or zero and gives the logical OR
{
for(int k = 0; k < n; n++)
{
if(*ptc == *(ptc + 20*k)){continue;} // pointers are 20 units apart
else{return 1;break;}
}
return *ptc;
}
int main(void) {
int t; scanf("%d", &t);
for (int i = 0; i < t; i++)
{
int n, y;
scanf("%d %d", &n, &y);
int a[n];
for(int j = 0; j < n ; j++)
{
scanf("%d", &a[j]);
}
int b[20*n];
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 20; k++)
{
b[20*j + k] = *(binary_number(a[n])+k);
}
}
int c = 0;
int p = 0;
for (int j = 0; j < 20; j++)
{
if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
}
if (p==1){printf("-1");}
else {printf("%d\n", c);}
}
return 0;
}
I'm trying to develop a code to solve the Travelling salesman problem in C, but I have some restrictions: I can only use "for, "while", "do", arrays, matrix and simple things like that, so, no functions or recursion (unfortunately).
What I've got so far:
The user will will type the city coordinates X and Y like this:
8.15 1.58
9.06 9.71
1.27 9.57
9.13 4.85
The code to storage the coordinates.
float city[4][2];
int i;
for (i=0; i<4; i++)
scanf("%f %f", &cidade[i][0], &cidade[i][1]);
There are 4 cities, so "i" goes from 0 to 3. X and Y are storaged on the second dimension of the matrix, [0] and [1].
The problem now is that I have to generate ALL POSSIBLE permutations of the first dimension of the matrix. It seems easy with just 4 cities, because all possible routes are (it must starts with city A everytime):
A B C D
A B D C
A C B D
A C D B
A D C B
A D B C
But I'll have to expand it for 10 cities. People have told me that it will use 9 nested foor loops, but I'm not being able to develop it =(
Can somebody give me an idea?
Extending to 10 (and looking up city names) as an exercise for the reader. And it's horrid, but that's what you get with your professor's limitations
#include <stdio.h>
int main(void) {
for (int one = 0; one < 4; one++) {
for (int two = 0; two < 4; two++) {
if (two != one) {
for (int three = 0; three < 4; three++) {
if (one != three && two != three) {
for (int four = 0; four < 4; four++)
if (one != four && two != four && three != four) {
printf("%d %d %d %d\n", one, two, three, four);
}
}
}
}
}
}
return 0;
}
This is based on https://stackoverflow.com/a/3928241/5264491
#include <stdio.h>
int main(void)
{
enum { num_perm = 10 };
int perm[num_perm];
int i;
for (i = 0; i < num_perm; i++) {
perm[i] = i;
}
for (;;) {
int j, k, l, tmp;
for (i = 0; i < num_perm; i++) {
printf("%d%c", perm[i],
(i == num_perm - 1 ? '\n' : ' '));
}
/*
* Find largest j such that perm[j] < perm[j+1].
* Break if no such j.
*/
j = num_perm;
for (i = 0; i < num_perm - 1; i++) {
if (perm[i + 1] > perm[i]) {
j = i;
}
}
if (j == num_perm) {
break;
}
for (i = j + 1; i < num_perm; i++) {
if (perm[i] > perm[j]) {
l = i;
}
}
tmp = perm[j];
perm[j] = perm[l];
perm[l] = tmp;
/* reverse j+1 to end */
k = (num_perm - 1 - j) / 2; /* pairs to swap */
for (i = 0; i < k; i++) {
tmp = perm[j + 1 + i];
perm[j + 1 + i] = perm[num_perm - 1 - i];
perm[num_perm - 1 - i] = tmp;
}
}
return 0;
}
I have a string where I need to do substring operation. I'm trying to achieve something like this for example if the input string is com then the output must be something like this -
c
co
com
o
om
m.. I have tried this
for(int i=0 ; i<len ;i++)
{
printf("%s",&string[strlen(string)-i]));
}
A substring is defined by its left and right ends so there are O(n*n) substrings in a string of length n.
int n = strlen(string);
for(int i = 0; i < n; i++)
{ for(int j = i; j < n; j++)
{ /* print substring from i to j */
for(int k = i; k <= j; k++)
{ printf("%c", string[k]);
}
printf("\n");
}
}
You're missing a comma in your code:
for(int i=0 ; i<len ;i++)
{
printf("%s", &string[strlen(string)-i])
}
But that will print "", "m", "om" - not what you want.
Something more like:
// start at each point in the string
for ( const char *start = string; *start; ++start )
{
// for each starting point, go from the whole remainder down
// to just one character
for ( const char *end = string + strlen(string); end > start; --end )
{
for ( const char *s = start; s < end; ++s )
putchar(*s);
putchar('\n');
}
}
Example: https://ideone.com/XXoYv6
Substring means any contiguous group of characters.
For the n string
it will generate (n*(n-1) /2) substrings.
For example of String
source = "STACK"
Length of the character is 5, so it total substring would be (5(5-1) /2) = 10
We have to iterate through the first element of string and print all the substring and than onwards one by one we increment the index of i and printing the substring from range (j to k)
public void generateSubString(String source){
char[] arr = source.toCharArray();
for(int i = 0; i<arr.length; i++){
for(int j = i ; j < arr.length; j++){
for(int k = i; k<=j; k++){
System.out.print(arr[k]);
}
System.out.println();
}
OUTPUT:
S
ST
STA
STAC
STACK
T
TA
TAC
TACK
A
AC
ACK
C
CK
K
Below is the code to find all substrings of a string in javascript without for loop, which will increase the speed of code.
const devideSubStr = (str) => {
var totalLoop = str.length * ((str.length + 1)/2);
// looping count
let i = 0;
var totalChar = 1;//character to get
var charFrom = 0;// from which index
var strLength = str.length;//length of digit
while( i < totalLoop){
console.log(str.substr(charFrom, totalChar))
charFrom ++;
i ++;
if(charFrom == strLength){
charFrom = 0;
strLength = strLength - 1;
totalChar ++;
}
}}
I'm currently reading in a list of words from a file and trying to sort them line by line.
I can read each line in and print the words out just fine, but I can't seem to sort each line individually. The first line is sorted, but the second is not. Can anyone see where I'm going wrong? Thanks!
int fd;
int n_char = 0;
int charCount = 0, wordCount = 0, lineCount = 0;
int wordsPerLine[100];
char buffer;
char words[6][9];
fd = open(inputfile, O_RDONLY);
if (fd == -1) {
exit(1);
}
wordsPerLine[0] = 0;
/* use the read system call to obtain 10 characters from fd */
while( (n_char = read(fd, &buffer, sizeof(char))) != 0) {
if (buffer == '\n' || buffer == ' ') {
words[wordCount][charCount] = '\0';
charCount = 0;
wordCount++;
wordsPerLine[lineCount] += 1;
if (buffer == '\n') {
lineCount++;
wordsPerLine[lineCount] = 0;
}
} else {
words[wordCount][charCount++] = buffer;
}
}
printf("Num Words: %d --- Num Lines: %d\n", wordCount, lineCount);
char tmp[9];
int m, n;
int i, x, totalCount = 0;
for (i = 0; i < lineCount; i++) {
for (x = 0; x < wordsPerLine[i]; x++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = 0; n < wordsPerLine[i]; n++) {
if(strcmp(words[n-1], words[n])>0) {
strcpy(tmp, words[n-1]);
strcpy(words[n-1], words[n]);
strcpy(words[n], tmp);
}
}
} /* end sorting */
}
}
printf("Sorted:\n");
totalCount = 0;
for(i = 0; i < lineCount; i++) {
printf("Line %d (%d words)\n", i + 1, wordsPerLine[i]);
for(x = 0; x < wordsPerLine[i]; x++) {
printf("%s\n", words[totalCount++]);
}
}
My sample input file is:
great day out
foo bar food
Let's go by small parts...
To see if the problem is in the reading, comment the reading part and try to add:
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};
and set the counters to the value they would with this input also...
Your loop is accessing some data out of the bounds... I would recommend you to try your sorting code with an array of numbers first and see if it is sorting them correctly...
#include<stdio.h>
#define N 6
int main()
{
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};
int numbers[] = {20, 10, 50, 5, 30, -50};
int i, j, temp;
for(i = 0; i < N - 1; i++)
for(j = 0; j < N - 1; j++)
if(numbers[j] > numbers[j + 1])
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
for(i = 0; i < N; i++)
{
printf("%d\n", numbers[i]);
//printf("%s\n", words[i]);
}
}
Note also that this is the least efficient implementation of bubble sort (but is the same you provided), you can improve it by adding a variable to check in the inner loop some change happened for instance(which would mean that it is already sorted and you can stop sorting)...
Also, after each iteration on the outter loop one element is going to be placed in its final place (try to find out which one), which means that you won't need to consider this element in the next iteration, so after each iteration in the outer loop the number of elements compared in the inner loop can be reduced by 1...
you can find more info about bubble sort here
/* iterate through each line */
for (i = 0; i < lineCount; i++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = m+1; n < wordsPerLine[i]; n++) {
if(strcmp(words[n + totalCount], words[m + totalCount]) < 0) {
strcpy(tmp, words[m + totalCount]);
strcpy(words[m + totalCount], words[n + totalCount]);
strcpy(words[n + totalCount], tmp);
}
}
} /* end sorting */
totalCount += wordsPerLine[i];
}
I just needed to keep a running count of each word per line, so i know what line to start comparing with
I have the next KMP-implementation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int kmp(char substr[], char str[])
{
int i, j, N, M;
N = strlen(str);
M = strlen(substr);
int *d = (int*)malloc(M * sizeof(int));
d[0] = 0;
for(i = 0, j = 0; i < M; i++)
{
while(j > 0 && substr[j] != substr[i])
{
j = d[j - 1];
}
if(substr[j] == substr[i])
{
j++;
d[i] = j;
}
}
for(i = 0, j = 0; i < N; i++)
{
while(j > 0 && substr[j] != str[i])
{
j = d[j - 1];
}
if(substr[j] == str[i])
{
j++;
}
if(j == M)
{
free(d);
return i - j + 1;
}
}
free(d);
return -1;
}
int main(void)
{
char substr[] = "World",
str[] = "Hello World!";
int pos = kmp(substr, str);
printf("position starts at: %i\r\n", pos);
return 0;
}
You can test it here: http://liveworkspace.org/code/d2e7b3be72083c72ed768720f4716f80
It works well on small strings, and I have tested it with a large loop, on this way all is fine.
But if I change the substring I'm searching for and the complete string to these:
char substr[] = "%end%",
str[] = "<h1>The result is: <%lua% oleg = { x = 0xa }
table.insert(oleg, y) oleg.y = 5 print(oleg.y) %end%></h1>";
Only after first try, this implementation fails...
Please, could you help me with repairing implementation of KMP to make the algorithm work with such data in strings...
In one place you deviate from your source, the source has
while(j>0 && p[j]!=p[i]) j = d[j-1];
if(p[j]==p[i])
j++;
d[i]=j;
while you have
while(j > 0 && substr[j] != substr[i])
{
j = d[j - 1];
}
if(substr[j] == substr[i])
{
j++;
d[i] = j;
}
being deceived by the source's indentation. In the source, there are no braces around the if() branch, so only the increment j++; is controlled by the if; d[i] = j; is unconditional.
Then, the source has an error, probably due to the unusual use of indices. The correct way to set up the array is
int *d = (int*)malloc(M * sizeof(int));
d[0] = 0;
for(i = 1, j = 0; i < M; i++)
{
while(j > 0 && substr[j-1] != substr[i-1])
{
j = d[j - 1];
}
if(substr[j] == substr[i])
j++;
d[i] = j;
}
But it's confusing, since the setup here uses the indices i-1 and j-1 as well as i and j to determine d[i]. The usual way to implement it is different; the way it is implemented in C#. Since that's the form you find in most sources, it's far easier to convince yourself of the correctness of that.