I am using Arch Linux and when I am compiling and running the following C code,
#include <stdio.h>
#include<string.h>
int main(void) {
char s1[]="Hello";
char s2[]="World";
strcat(s1,s2);
int s2_len=strlen(s2);
printf("s1 = %s, s2 = %s and length of s2 = %d.\n", s1, s2, s2_len);
return 0;
}
I am getting the output:
s1 = HelloWorld, s2 = orld and length of s2 = 4.
Although the output shoud be s1 = HelloWorld, s2 = World and length of s2 = 5. and it is the output when I am using some online IDE.
Can somebody explain me why is this happening?
char s1[]="Hello";
char s2[]="World";
strcat(s1,s2);
The variable declarations allocate memory for 5 characters each, plus the terminating NUL byte. Your strcat call writes past that space, which produces undefined results.
In this case, the memory layout is probably something like this
0 1 2 3 4 5 6 7 8 9 10 11
H e l l o \0 W o r l d \0
^ ^
s1 s2
After the strcat, the result is:
0 1 2 3 4 5 6 7 8 9 10 11
H e l l o W o r l d \0 \0
^ ^
s1 s2
Which gives the result you see. Note that there could be other possible results, the program could e.g. crash at the strcat call.
Related
I am having an issue with coding this, I need some similar code with this but written in RPG to count the digits in a number.
NumField (15, 0) packed decimal
EVAL numDig = %len(%trim(%char(NumField)))
the %editc built in function dates back to the begin of time. So does %len, %trim and varying fields.
** ---------------------- test0003r ---------------------------
dtest0003r pi
d errmsg s 256a
d packNum s 15p 0
d lx s 10i 0
d v20 s 20a varying
d ch50 s 50a
/free
packNum = 32553;
v20 = %trim(%editc(packNum:'Z')) ;
lx = %len(v20) ;
ch50 = %trim(%editc(lx:'Z')) + ' ' + v20 ;
dsply ch50 ;
*inlr = '1' ;
return ;
/end-free
A fun challenge.
#zen, I agree with others. I would not try to code this in RPG III. I would either convert the RPG III program to RPG IV, or I would call an RPG IV program to do this calculation.
But here is some RPG III code that gets the number of digits. It is horrible code, and almost completely untested. I would never use this code or recommend that anyone else use this code.
C Z-ADD1.2 NUM 52
C EXSR SUB1
C Z-ADD-123.45 NUM 52
C EXSR SUB1
C Z-ADD0 NUM 52
C EXSR SUB1
C RETRN
C SUB1 BEGSR
C MOVELNUM STR 30 P
C '0':' ' XLATESTR STR2 30 P
C ' ' CHECKSTR2 P 50
C P IFGT 0
C SUBSTSTR2:P STR3 30 P
C ' ' CHEKRSTR3 P 50
C ENDIF
C P DSPLY
C ENDSR
It displays 2, 5, 0.
Given a string, and a set of four alphabets (A, B, C, D) for generating strings of length n. I need a generalized mathematical formula to calculate the number of neighbors for any string of length n with at most d mismatches, and the number of neighbors with exactly d mismatches.
For example: Given a string=”AAA” and d=3
We have 9 Strings with exactly d=1
BAA
CAA
DAA
ABA
ACA
ADA
AAB
AAC
AAD
We have 27 Strings with exactly d=2
BBA BCA BDA
BAB BAC BAD
CBA CCA CDA
CAB CAC CAD
DBA DCA DDA
DAB DAC DAD
ABB ABC ABD
ACB ACC ACD
ADB ADC ADD
We have 27 Strings with exactly d=3
BBB CBB DBB
BCB CCB DCB
BDB CDB DDB
BBC CBC DBC
BCC CCC DCC
BDC CDC DDC
BBD CBD DBD
BCD CCD DCD
BDD CDD DDD
Number of Strings with at most d=3 are 9+27+27=63 strings
Let's consider a string of size n.
We want to know how many 'neighbors' this string has, with a distance d. The first thing we remark, with your definition of 'distance', is that it means that we must choose d characters among the n of the string and modify them. So there are n choose d possible combinations of charactersto modify.
Each of these can be modified in 3 different manners (since the size of the alphabet is 4.
So ultimately, we have:
n choose d possible combinations of characters that will be modified
d characters will be modified, and each of them can be modified in 3different manners.
So the formula is ultimately (s - 1) ^ d * (n choose d), where s is the size of the alphabet (here 4). I let you verify that it fits the first examples you provided.
If you want to try it out:
#include <iostream>
#include <string>
using namespace std;
int n = 3; int d = 2;
string s = "AAA";
int counter(string curr, int index, int currd){
if(currd == 0 || index == n){
cout<<curr<<s.substr(index, n - index)<<endl;
return 1;
}
int ans = 0;
for(char c = 'A'; c < 'E'; c++){
if(c != s[index]){
ans += counter(curr + c, index + 1, currd - 1);
}
else{
ans += counter(curr + c, index + 1, currd);
}
}
return ans;
}
int main(){
cout<<"answer = "<<counter("", 0, d) - 1;
}
I am newbie at Go and I wish to iterate the characters of a string
package main
import (
"fmt"
)
func main() {
var a string = "abcd"
for i, c := range a {
fmt.Printf("%d %s\n", i, c)
}
}
I want the output to be
0 a
1 b
2 c
3 d
but it's not. What am I doing wrong?
Fix the go vet and package fmt format error messages (type rune is an alias for type int32):
10: Printf format %s has arg c of wrong type rune
0 %!s(int32=97)
1 %!s(int32=98)
2 %!s(int32=99)
3 %!s(int32=100)
Playground: https://play.golang.org/p/oM9D8oNlaAO
A rune is a Unicode code point (character), not a string.
Use %c not%s. For example,
package main
import (
"fmt"
)
func main() {
var a string = "abcd"
for i, c := range a {
fmt.Printf("%d %c\n", i, c)
}
}
Playground: https://play.golang.org/p/LFQPGZ9X5kk
Output:
0 a
1 b
2 c
3 d
An example of type string UTF-8 variable-length encoding:
package main
import (
"fmt"
)
func main() {
var a string = "Greece Ελλάδα"
for i, c := range a {
fmt.Printf("%2d %c\n", i, c)
}
}
Playground: https://play.golang.org/p/Fdgg6UMXAAt
Output:
0 G
1 r
2 e
3 e
4 c
5 e
6
7 Ε
9 λ
11 λ
13 ά
15 δ
17 α
References:
Go package fmt documentation.
The Go Blog: Strings, bytes, runes and characters in Go.
I am trying to solve a string matching problem using Rabin-karp algorithm.
I made use of horner's method for calculating hash function,but i forgot to use modulo operator..its like this now.
(this is for starting pattern length of the big string)
1 for(i=0;i<l1;i++)
2 {
3 unsigned long long int k2 = *(s1+i);
4 p1 += k2 * k1;
5 k1 = (k1 * 31);
6 }
where s1 is a string containing characters,and its like
s1[0](k1^0) + s1[1](k1^1) and so on....
and i did the same for the pattern we need to find..
0 unsigned long long int j;
1 for(j=0;j<l1;j++)
2 {
3 unsigned long long int k3 = *(str+j);
4 p2 += k3 * k4;
5 k4 = (k4 *31);
6 }
Now i am going through strings of length = pattern length in the big string.
Code for that is..
0 long long int ll1 = strlen(s1),ll2=strlen(str);
1 for(j=1;j<=ll2;j++)
2 {
3 printf("p1 and p2 are %d nd %d\n",p1,p2);
4 if ( p2 == p1)
5 {
6 r1 = 1;
7 break;
8 }
9 long int w1 = *(str+j-1);
10 p2 -= w1;
11 p2 = p2/31;
12 long int lp = *(str+j+l1-1);
13 p2 += ((lp *vp));
14 }
15 if ( r1 == 0)
16 {
17 printf("n\n");
18 }
19 else
20 {
21 printf("y\n");
22 }
23 }
where str is the big string,s1 is pattern string.
I tested for multiple inputs an i am getting correct answers for all of them but its taking a lot of time..i then realized its because of high calculations needed when the pattern string is too long and if we use a modulo operator we can minimize those calculations..**my question is how to incorporate modulo operator in this code while searching for patterns?
**
My entire code:
http://ideone.com/81hOiU
Please help me out with this,i tried searching in net but could not find help.
Thanks in Advance!
Given a string s containing only lower case alphabets (a - z), find (i.e print) the characters that are repeated.
For ex, if string s = "aabcacdddec"
Output: a c d
3 approaches to this problem exists:
[brute force] Check every char of string (i.e s[i] with every other char and print if both are same)
Time complexity: O(n^2)
Space complexity: O(1)
[sort and then compare adjacent elements] After sorting (in O(n log(n) time), traverse the string and check if s[i] ans s[i + 1] are equal
Time complexity: O(n logn) + O(n) = O(n logn)
Space complexity: O(1)
[store the character count in an array] Create an array of size 26 (to keep track of a - z) and for every s[i], increment value stored at index = s[i] - 26 in the array. Finally traverse the array and print all elements (i.e 'a' + i) with value greater than 1
Time complexity: O(n)
Space complexity: O(1) but we have a separate array for storing the frequency of each element.
Is there a O(n) approach that DOES NOT use any array/hash table/map (etc)?
HINT: Use BIT Vectors
This is the element distinctness problem, so generally speaking - no there is no way to solve it in O(n) without extra space.
However, if you regard the alphabet as constant size (a-z characters only is pretty constant) you can either create a bitset of these characters, in O(1) space [ it is constant!] or check for each character in O(n) if it repeats more than once, it will be O(constant*n), which is still in O(n).
Pseudo code for 1st solution:
bit seen[] = new bit[SIZE_OF_ALPHABET] //contant!
bit printed[] = new bit[SIZE_OF_ALPHABET] //so is this!
for each i in seen.length: //init:
seen[i] = 0
printed[i] = 0
for each character c in string: //traverse the string:
i = intValue(c)
//already seen it and didn't print it? print it now!
if seen[i] == 1 and printed[i] == 0:
print c
printed[i] = 1
else:
seen[i] = 1
Pseudo code for 2nd solution:
for each character c from a-z: //constant number of repeats is O(1)
count = 0
for each character x in the string: //O(n)
if x==c:
count += 1
if count > 1
print count
Implementation in Java
public static void findDuplicate(String str) {
int checker = 0;
char c = 'a';
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i) - c;
if ((checker & (1 << val)) > 0) {
System.out.println((char)(c+val));
}else{
checker |= (1 << val);
}
}
}
Uses as int as storage and performs bit wise operator to find the duplicates.
it is in O(n) .. explanation follows
Input as "abddc"
i==0
STEP #1 : val = 98 - 98 (0) str.charAt(0) is a and conversion char to int is 98 ( ascii of 'a')
STEP #2 : 1 << val equal to ( 1 << 0 ) equal to 1 finally 1 & 0 is 0
STEP #3 : checker = 0 | ( 1 << 0) equal to 0 | 1 equal to 1 checker is 1
i==1
STEP #1 : val = 99 - 98 (1) str.charAt(1) is b and conversion char to int is 99 ( ascii of 'b')
STEP #2 : 1 << val equal to ( 1 << 1 ) equal to 2 finally 1 & 2 is 0
STEP #3 : checker = 2 | ( 1 << 1) equal to 2 | 1 equal to 2 finally checker is 2
i==2
STEP #1 : val = 101 - 98 (3) str.charAt(2) is d and conversion char to int is 101 ( ascii of 'd')
STEP #2 : 1 << val equal to ( 1 << 3 ) equal to 8 finally 2 & 8 is 0
STEP #3 : checker = 2 | ( 1 << 3) equal to 2 | 8 equal to 8 checker is 8
i==3
STEP #1 : val = 101 - 98 (3) str.charAt(3) is d and conversion char to int is 101 ( ascii of 'd')
STEP #2 : 1 << val equal to ( 1 << 3 ) equal to 8 finally 8 & 8 is 8
Now print 'd' since the value > 0
You can also use the Bit Vector, depends upon the language it would space efficient. In java i would prefer to use int for this fixed ( just 26) constant case
The size of the character set is a constant, so you could scan the input 26 times. All you need is a counter to store the number of times you've seen the character corresponding to the current iteration. At the end of each iteration, print that character if your counter is greater than 1.
It's O(n) in runtime and O(1) in auxiliary space.
Implementation in C# (recursive solution)
static void getNonUniqueElements(string s, string nonUnique)
{
if (s.Count() > 0)
{
char ch = s[0];
s = s.Substring(1);
if (s.LastIndexOf(ch) > 0)
{
if (nonUnique.LastIndexOf(ch) < 0)
nonUnique += ch;
}
getNonUniqueElements(s, nonUnique);
}
else
{
Console.WriteLine(nonUnique);
return;
}
}
static void Main(string[] args)
{
getNonUniqueElements("aabcacdddec", "");
Console.ReadKey();
}