Insert integer in an array C++ - c++

I wrote the following code to convert string of type 'aaadddbbbccc' to 'a3d3b3c3' :
#include <iostream>
#include <string.h>
using namespace std;
void stringCompression(char *str,char *newStr){
int a[256] = {0};
int newCount = 0;
for(int i = 0; i < strlen(str) ; i++){
int j = str[i];
if (a[j] == 0 && strlen(newStr) <= strlen(str)){
a[j] = 1 ;
newStr[newCount] = str[i];
newCount++;
int count = 0;
for (int n = i; n < strlen(str); n++){
if(str[i] == str[n]){
count = count + 1;
}
}
newStr[newCount] =(char) count;
newCount++ ;
} else if (strlen(newStr) > strlen(str)){
strcpy(newStr,str);
}
}
}
int main() {
char str[] = "abcdabcdabcd";
char *newStr = new char[strlen(str)+1];
stringCompression(str,newStr);
cout << newStr;
return 0;
}
My problem is at step
newStr[newCount] =(char) count;
even though it is inserted but the output is not a3b3c3d3 but a*squarebox*b*squarebox*c*squarebox*d*squarebox*. squarebox being 2*2 matrix with one value as the number that is desired. I am using eclipse IDE.
. I would really appreciate your help. How can I correct this. Am I using the correct approach?
Thanks in advance.

The problem is that
newStr[newCount] =(char) count;
converts the number "count" into the character corresponding to that number according to the ascii table (http://www.asciitable.com/), which is "end of text" for "3", that does not correspond to any number.
You should convert "count" into a string instead. See here for example:
Easiest way to convert int to string in C++
However, be aware that it might be longer than one digit, for example if count is "11", it will take two letters in string representation.

Hey you have to use http://www.cplusplus.com/reference/cstdlib/itoa/ to convert integer to char string

Related

Modification of counting sort

The Counting sort below sorts elements based on their ASCII value.
The code below works fine but I want to do some I/O modification. The code doesn't take custom input.
I tried to do some changes but getting undefined behavior. My first doubt is why I'm getting undefined behavior. secondly, Please provide me with the code which will make the below code run as expected. The comment portion is what I tried by myself.I want it to take input from user.
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
#define RANGE 255
void countSort(char arr[]) //void countSort(char arr[],int n)
{
char output[strlen(arr)]; //char output[n];
int count[RANGE + 1], i;
memset(count, 0, sizeof(count));
for(i = 0; arr[i]; i++) {
count[arr[i]]++;
}
for (i = 1; i <= RANGE; ++i) {
count[i] += count[i-1];
}
for (i = 0; arr[i]; ++i) {
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
for (i = 0; arr[i]; ++i) {
arr[i] = output[i];
}
}
// Driver code
int main()
{
char arr[] = "geeksforgeeks";
countSort(arr);
cout<< "Sorted character array is "<<arr;
/*
int n;
cin>>n;
char arr[n];
for(int i=0;i<n;i++) {
cin>>arr[i];
}
countSort(arr,n);
for(int i=0;i<n;i++) {
cout<<endl<<arr[i];
}
*/
return 0;
}
So the OP asked, how to take an input from the user and sort this. And not a predefined string in a given char array.
I will give the answer. But the question is tagged with C++, and I will convert it to C++.
By the way. The code in the question is a one to one copy from GeeksforGeeks and tries to code the so called Counting Sort algorithm in C++ that is described here.
Since the code is taken from GeeksforGeeks I unfortunately need to blame user "rathbhupendra" for really bad C++ code. I am truly sorry.
The code is using:
C-Style arrays
Variable Length Arrays (Compiler extension. Not C++ compliant)
strlen
memset
#include<bits/stdc++.h> and #include<string.h>
using namespace std
unusal end conditions in for loops for(i = 0; arr[i]; ++i)
char arrays instead of std::strings
a Macro to define an array size (#define RANGE 255)
So, nothing C++.
And now, the answer.
You need to read the string from the user in a variable of type std::string with the function std::getline.
A std::string can be used like a character array. No difference.
Please see the C++ solution:
EDIT
Edited on the comments of MichaelDorgan
#include <iostream>
#include <string>
#include <vector>
constexpr size_t AsciiRange = 256;
// Convert signed char to unsigned size_t type.
inline size_t char2sizet(char c) { return static_cast<size_t>(static_cast<unsigned char>(c)); }
void countSort(std::string& stringToSort)
{
std::vector<size_t> count(AsciiRange, 0U);
size_t i { 0U };
for (i = 0U; i < stringToSort.size(); i++) {
count[char2sizet(stringToSort[i])]++;
}
for (i = 1U; i < AsciiRange; ++i) {
count[i] += count[i - 1U];
}
std::string output(stringToSort);
for (i = 0U; i < stringToSort.size(); ++i) {
output[count[char2sizet(stringToSort[i])] - 1U] = stringToSort[i];
--count[char2sizet(stringToSort[i])];
}
stringToSort = output;
}
int main()
{
std::cout << "\nPlease enter a string:\n\n";
// Get the string from the user
std::string inputString{};
getline(std::cin, inputString);
// Sort it by characters
countSort(inputString);
// Show result
std::cout << "\n\n\nString sorted by characters is:\n\n" << inputString << '\n';
return 0;
}
Hope this helps . . .
I geuss by 'getting undefined behavior' you meant segmentation fault which sometimes occured. The problem lies in this line
for(i = 0; arr[i]; i++)
instead you should write
for(i = 0; i < n; i++)
You can check that in the first case at the end of each loop arr[i] is sometimes some weird character(this character doesn't belong to the input string) and count[arr[i]] for this char returns negative number which produce segmentation fault here
output[count[arr[i]]-1] = arr[i];

How do I turn a string number into an int array of the individual digits

I have 20 digit strings ex: 12345678912345678912.
I want to turn this into an array of ints [1,2,3...2]
How would I do that?
(I kept getting errors with sstream, atoi/stoi)
Create a new array, and convert each number character to number. Just subtract '0' from the number character and you will get the number.
The number character - '0' = the ASCII value of that character - the ASCII value of '0' = the number.
std::vector<int> digits;
for (int i = 0; i < s.size(); i++)
digits.push_back(s[i] - '0');
Using ASCII is way to here.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string s;
cin>>s;
int len = s.length();
int arr[len];
for( int it=0; it<len; it++ ){
// using ascii value
arr[it] = s[it] - '0';
}
for(int it=0; it<len; it++){
cout<<arr[it]<<" ";
}
return 0;
}
// Example program
#include <iostream>
#include <string>
int main()
{
// convert char to int
std::string str = "12345678912345678912";
int digits[str.size()];
for (size_t i=0; i<str.size(); i++) {
digits[i] = str[i] - '0';
}
// print out the string
std::cout << str << std::endl;
// print out the digits
for (size_t i=0; i<str.size(); i++) {
std::cout << digits[i];
}
std::cout << std::endl;
}
You need to learn to work with C++ standard string and character strings. Then learn to use standard function to convert character to integer. Following are some useful references:
http://www.cplusplus.com/reference/string/string/c_str/
http://www.cplusplus.com/reference/cstdlib/atoi/
http://www.cplusplus.com/reference/cstring/strncpy/
Above mentioned solutions are correct. Here is another way to solve your problem.
int main()
{
string input = "123456789";
int sum = 0;
const char * icstring = input.c_str(); // input character string
for(int i = 0; i < input.size(); i++)
{
char scstring[2]; // single character string
// Copy first digit to scstring
strncpy_s(scstring, icstring, 1);
// Convert scstring to integer using C library function 'atoi'
int digit = atoi(scstring); // cout << "i = " << endl;
sum += digit;
icstring++; // process next character
}
cout << "Sum of integers : " << sum << endl;
return 0;
}

finding if one string ("AB") is subset of another ("ABCD")?

i had my midterm today. this was the first question. i could not solve this.
the exact requirement is as follows :
we have to determine if a string , lets say , "DA" is subset of another, "ABCD". the number of letters is crucial, for exmaple "DAD" is not a subset of "ABCD". because "D" is repeated twice whereas in the parent string "D" occurs once. also it can be assumed that that no. of letters of parent string is always equal to or greater than the other.
i thought a lot about this. my approach towards this was that i will compare the characters of the to-be-found substring with the parent string. if a match is found i will store its index in a third array. so in the end i will have the arrays of characters of the parent array which matched characters from the other array.this is how far i have been able to get.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char array[] = "ABCD";
char array1[] = "AB";
int size = strlen(array);
int size1 = strlen(array1);
int temp[size];
int no = 0;
for (int i = 0; i< size1; i++)
{
for (int j = 0; j< size; j++)
{
if (array1[i]==array[j])
{
for(int k = 0; k<size ; k++)
{
if (temp[k] != j)
{
temp[no] = j;
no++;
}
}
}
}
}
for (int i = 0; i<size; i++)
cout<<endl<<temp[i]<<" ";
return 0;
}
kindly help in solving this and do tel me if you have another approach to this.
also, are arrays or a string a better approach to this problem.
i am writing in c++
thanks in advance
(I recently used this as a quiz for my students but we're using Groovy and Java.)
A simple aproach: create a copy of the string ("ABCD") and strike matched letters so that they won't match again, for example after matching a "D" and "A", the copy would be "_BC_" and it would not match another "D".
You can also count the number of occurrences of each letter in each string and make sure the count of each letter in the second string is less than or equal to the count of each letter in the first string. This might be better in the case where you want to compare multiple potential substrings to a single collection of letters (e.g. comparing all the words in the dictionary to the current letters in Boggle).
This code will do that. It has the primary limitation that it only works with strings containing the 26 capital letters in the English alphabet. But it gets the idea across.
#include <iostream>
#include <cstring>
using namespace std;
void stringToArray(char *theString, int *countArray) {
int stringLength = strlen(theString);
for (int i=0; i<26; i++) {
countArray[i] = 0;
}
for (int i=0; i<stringLength; i++) {
countArray[theString[i] - 'A']++;
}
}
bool arrayIsSubset(int *superCount, int *subCount) {
//returns true if subCount is a subset of superCount
bool isSubset = true;
for (int i=0; i<26 && isSubset; i++) {
isSubset = subCount[i] <= superCount[i];
}
return isSubset;
}
int main()
{
char array[] = "ABCD";
char array1[] = "AB";
char array2[] = "ABB";
int letterCount[26], letterCount1[26], letterCount2[26];
stringToArray(array, letterCount);
stringToArray(array1, letterCount1);
stringToArray(array2, letterCount2);
cout << "array1 is " << (arrayIsSubset(letterCount, letterCount1) ? "" : "not ") << "a subset" << endl;
cout << "array2 is " << (arrayIsSubset(letterCount, letterCount2) ? "" : "not ") << "a subset" << endl;
}
produces:
array1 is a subset
array2 is not a subset

Summing Large Numbers

I have being doing some problems on the Project Euler website and have come across a problem. The Question asks,"Work out the first ten digits of the sum of the following one-hundred 50-digit numbers." I am guessing there is some mathematical way to solve this but I was just wondering how numbers this big are summed? I store the number as a string and convert each digit to a long but the number is so large that the sum does not work.
Is there a way to hold very large numbers as a variable (that is not a string)? I do not want the code to the problem as I want to solve that for myself.
I was just wondering how numbers this big are summed?
You can use an array:
long LargeNumber[5] = { < first_10_digits>, < next_10_digits>....< last_10_digits> };
Now you can calculate the sum of 2 large numbers:
long tempSum = 0;
int carry = 0;
long sum[5] = {0,0,0,0,0};
for(int i = 4; i >= 0; i--)
{
tempSum = largeNum1[i] + largeNum2[i] + carry; //sum of 10 digits
if( i == 0)
sum[i] = tempSum; //No carry in case of most significant digit
else
sum[i] = tempSum % 1000000000; //Extra digits to be 'carried over'
carry = tempSum/1000000000;
}
for( int i = 0; i < 5; i++ )
cout<<setw(10)<<setfill('0')<<sum[i]<<"\n"; //Pad with '0' on the left if needed
Is there a way to hold very large numbers as a variable (that is not a
string)?
There's no primitive for this, you can use any data structure (arrays/queues/linkedlist) and handle it suitably
I am guessing there is some mathematical way to solve this
Of course! But,
I do not want the code to the problem as I want to solve that for myself.
You may store the digits in an array. To save space and increase performance in the operations, store the digits of the number in base 10^9. so a number
182983198432847829347802092190
will be represented as the following in the array
arr[0]=2092190
arr[1]=78293478 arr[2]=19843284 arr[3]=182983
just for the sake of clarity, the number is represented as summation of arr[i]*(10^9i)
now start with i=0 and start adding the numbers the way you learnt as a kid.
I have done in java, Here I am taking to numbers N1 and N2, And I have create an array of size 1000. Lets take an example How to solve this, N1=12, N2=1234. For N1=12, temp=N1%10=2, Now add this digit with digit N2 from right to Left and store the result into array starting from i=0, similarly for rest digit of N1. The array will store the result but in reverse order. Have a looking on this link. Please check this link http://ideone.com/V5knEd
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception {
Scanner scan=new Scanner(System.in);
int A=scan.nextInt();
int B=scan.nextInt();
int [] array=new int[1000];
Arrays.fill(array,0);
int size=add(A,B,array);
for(int i=size-1;i>=0;i--){
System.out.print(array[i]);
}
}
public static int add(int A, int B, int [] array){
int carry=0;
int i=0;
while(A>0 || B>0){
int sum=A%10+B%10+carry+array[i];
array[i]=sum%10;
carry=sum/10;
A=A/10;
B=B/10;
i++;
}
while(carry>0){
array[i]=array[i]+carry%10;
carry=carry/10;
i++;
}
return i;
}
}
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
struct grid{
int num[50];
};
int main()
{
struct grid obj[100];
char ch;
ifstream myfile ("numbers.txt");
if (myfile.is_open())
{
for(int r=0; r<100; r++)
{
for(int c=0; c<50; c++)
{
myfile >> ch;
obj[r].num[c] = ch - '0';
}
}
myfile.close();
int result[50],temp_sum = 0;
for (int c = 49; c>=0; c--)
{
for (int r=0; r<100; r++)
{
temp_sum += obj[r].num[c];
}
result[c] = temp_sum%10;
temp_sum = temp_sum/10;
}
string temp;
ostringstream convert;
convert << temp_sum;
temp = convert.str();
cout << temp_sum;
for(unsigned int count = 0; count < (10 - temp.length()); count++)
{
cout << result[count];
}
cout << endl;
}
return 0;
}
This the best way for your time and memory size :D
#include <iostream >
#include <climits >
using namespace std;
int main()
{
unsigned long long z;
cin >>z;
z=z*(z+1)/2;
C out << z;
return 0;
}

Arrays: Passing Index of String Array to Index of Int Array for Output only

I am looking to pass the int values of an array to the indices of a string array "behind the scenes." I want the string arrays to be ouput with their strings, however I want to do math on the indices the strings represent.
In other words I would like to combine or blend them together so that I have 4 arrays: 2 of them are int arrays, 1 of the int arrays is for doing math on; and 2 of them are string arrays, both of them are for display to the screen purposes only.
If I try to loop through the int arrays and assign the string array elements to their corresponding indices, it won't compile, and I get the error message:
"Cannot convert 'std::string' to 'int' in assignment."
If I try to loop through the string arrays and assign them the int array values to their corresponding indices, it compiles, however I get the ASCII representation of the int values, rather than the numbers.
Here is the code for looping through the int arrays:
#include <iostream>
using namespace std;
int main()
{
int typeArray[4] = {55,66,77,88};
int valArray[13] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
string types[4] = {"Manny", "Moe", "Jack", "John" };
string values[13] = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen"};
for (int i = 0; i < sizeof(typeArray)/sizeof(int); i++)
{
for (int j = 0; j < sizeof(valArray)/sizeof(int); j++)
{
typeArray[i] = types[0];
valArray[j] = values[0];
}
}
system("Pause");
return 0;
}
AGAIN, IT WON'T COMPILE, AND I GET THE ERROR MESSAGE NOTED ABOVE.
Here is the code for looping through the string arrays and the output:
#include <iostream>
using namespace std;
int main()
{
int typeArray[4] = {55,66,77,88};
int valArray[13] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
string types[4] = {"Manny", "Moe", "Jack", "John" };
string values[13] = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen"};
for (int i = 0; i < sizeof(types)/sizeof(int); i++)
{
for (int j = 0; j < sizeof(values)/sizeof(int); j++)
{
types[i] = typeArray[0];
values[j] = valArray[0];
cout << "This is types array: " << types[i] << " This is values array: " << values[j] << endl;
}
}
system("Pause");
return 0;
}
HERE IS THE OUTPUT SHOWING ASCII CONVERSIONS OF THE INTS:
This is types array: 7 This is values array: ☺
Please advise, thanks!
The problem is you can't store a String in an int you can however create a String from an int this is why the second option compiles.
However when you do this you get the character with the ASCII value equal to the int. So in your case you get the ASCII character for 7 which is the character you are printing.
If you want to print the 7 you need to get the ASCII code for 7 you can do this with:
types[i] = typeArray[0] + '0';
But I don't think this what you actually want to do.
You could create a structure that holds an int and a String to keep them together, and then make an array of that struct.
typedef struct typeStruct {
int value;
string disp;
} typeStruct;
typeStruct types[13];
Edit: based on your comment on this answer I think you want this
string values[6] = {"INVALID", "one", "two", "three", "four", "five"};
int size = 6;
...
//This prints the value for a given int
void printValue(int val) {
cout << values[val] << endl;
}
//This gets the int val for a given string
int getValue(string str) {
for(int i = 0; i < size; i++) {
if(str.compare(values[i]) == 0) {
return i;
}
}
return -1;
}
It looks like you should use
Map<int, string>
It will help you to bind an integer value to the string.
Anyway, you're getting an error because you are trying to assign string to int.