The listed code is from a larger project that I am working on (I deleted almost everything else that wasn't necessary for this posting) that is having some trouble running properly. I found the line that is causing the error but I'm hoping for an explanation as to why this line is causing it.
#include <iostream>
#include <tgmath.h>
using namespace std;
int main() {
const int m = 2; // Number of rows
const int n = 2; // Number of cols
int totalPoss = 0; // Number of unique possibile m X n binary matrices
// 2^(m * n) = the number of unique binary
// combinations of m X n matrices
int stop = pow(2, m * n);
// Error when a = 0, 1 | m = 0 | n = 1
for (int a = 0; a < stop; a++) {
int poss[m][n] = {0}; // 2D Array to store each possible matrix
int nextGen[m][n] = {0}; // 2D Array to store the next generation of cells
int rem[m * n]; // 1D Array to store the binary entries of the poss[m][n]
totalPoss = a;
int hold = a; // Stores the current "possibility number" (i.e when
// a = hold = 1 the binary equivilent of 1 will be stored
// in rem[m * n])
// Generate binary number based on whatever a is at current iteration
int c = 0;
while (hold > 0) {
// storing remainder in binary array
rem[c] = hold % 2;
hold = hold / 2;
c++;
}
cout << "Binary: ";
for (int i = 0; i < (m * n); i++) {
cout << rem[i] << " ";
}
cout << endl << endl;
}
cout << "Total possibilities: " << totalPoss+1 << endl;
return 0;
}
The line in question is line 19, or int nextGen[m][n] = {0};. The program's purpose in this state is to output all possible unique binary numbers of 4 bits. The number to translate to binary is determined by the initial for loop. The number is translated in the while loop and stored in rem[m][n]. This code works fine unless you include line 19. For whatever reason when this 2D array is created the output for 0 and 1 is 1 14 0 0 but outputs correctly for 2-15. My question is why this one (seemingly) unrelated line breaks my code.
Thank you!
rem is not completely initialized. The loop that assigns values only iterates until hold is zero, so it does not set the higher elements. But the loop that prints it always prints n * m elements.
The effect of defining nextGen is incidental. It may affect where rem is placed in memory, resulting in it happening to contain zeroes rather than other bits (and likely you are compiling without optimization).
Initialize rem to all zeroes or change the loop that sets its elements.
I have got some doubts while solving - Name That Number.
It goes like this -
Among the large Wisconsin cattle ranchers, it is customary to brand cows with serial numbers to please the Accounting Department. The cowhands don't appreciate the advantage of this filing system, though, and wish to call the members of their herd by a pleasing name rather than saying, "C'mon, #4734, get along."
Help the poor cowhands out by writing a program that will translate the brand serial number of a cow into possible names uniquely associated with that serial number. Since the cowhands all have cellular saddle phones these days, use the standard Touch-Tone(R) telephone keypad mapping to get from numbers to letters (except for "Q" and "Z"):
2: A,B,C 5: J,K,L 8: T,U,V
3: D,E,F 6: M,N,O 9: W,X,Y
4: G,H,I 7: P,R,S
Acceptable names for cattle are provided to you in a file named "dict.txt", which contains a list of fewer than 5,000 acceptable cattle names (all letters capitalized). Take a cow's brand number and report which of all the possible words to which that number maps are in the given dictionary which is supplied as dict.txt in the grading environment (and is sorted into ascending order).
For instance, brand number 4734 produces all the following names:
GPDG GPDH GPDI GPEG GPEH GPEI GPFG GPFH GPFI GRDG GRDH GRDI
GREG GREH GREI GRFG GRFH GRFI GSDG GSDH GSDI GSEG GSEH GSEI
GSFG GSFH GSFI HPDG HPDH HPDI HPEG HPEH HPEI HPFG HPFH HPFI
HRDG HRDH HRDI HREG HREH HREI HRFG HRFH HRFI HSDG HSDH HSDI
HSEG HSEH HSEI HSFG HSFH HSFI IPDG IPDH IPDI IPEG IPEH IPEI
IPFG IPFH IPFI IRDG IRDH IRDI IREG IREH IREI IRFG IRFH IRFI
ISDG ISDH ISDI ISEG ISEH ISEI ISFG ISFH ISFI
As it happens, the only one of these 81 names that is in the list of valid names is "GREG".
Write a program that is given the brand number of a cow and prints all the valid names that can be generated from that brand number or ``NONE'' if there are no valid names. Serial numbers can be as many as a dozen digits long.
Here is what I tried to solve this problem. Just go through all the names in the list and check which is satisfying the constraints given.
int numForChar(char c){
if (c=='A'||c=='B'||c=='C') return 2;
else if(c=='D'||c=='E'||c=='F') return 3;
else if(c=='G'||c=='H'||c=='I') return 4;
else if(c=='J'||c=='K'||c=='L') return 5;
else if(c=='M'||c=='N'||c=='O') return 6;
else if(c=='P'||c=='R'||c=='S') return 7;
else if(c=='T'||c=='U'||c=='V') return 8;
else if(c=='W'||c=='X'||c=='Y') return 9;
else return 0;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
freopen("namenum.in","r",stdin);
freopen("namenum.out","w",stdout);
string S; cin >> S;
int len = S.length();
freopen("dict.txt","r",stdin);
string x;
while(cin >> x){
string currName = x;
if(currName.length() != S.length()) continue;
string newString = x;
for(int i=0;i<len;i++){
//now encode the name as a number according to the rules
int num = numForChar(currName[i]);
currName[i] = (char)num;
}
if(currName == S){
cout << newString << "\n";
}
}
return 0;
}
Unfortunately, when I submit it to the judge, for some reason, it says no output produced that is my program created an empty output file. What's possibly going wrong?
Any help would be much appreciated. Thank You.
UPDATE: I tried what Some Programmer Dude suggested by adding a statement else return 0; at the end of the numOfChar function in case of a different alphabet. Unfortunately, it didn't work.
So after looking further at the question and exploring the information for Name That Number. I realized that it is not a current contest, and just a practice challenge. Thus, I updated my answer and also giving you my version of a successful submission. Nonetheless, that is a spoiler and will be posted after why your code was not working.
First, you forgot a } after the declaration of your number function. Secondary, you did not implement anything to check whether if the input fail to yield a valid name. Third, when you use numForChar() on the character of currName, the function yielded an integer value. That is not a problem, the problem is that it is not the ASCII code but is a raw number. You then compare that against a character of the input string. Of which, is an ASCII's value of a digit. Thus, your code can't never find a match. To fix that you can just add 48 to the return value of the numForChar() function or xor the numForChar() return's value to 48.
You are on the right track with your method. But there is a few hints. If you are bored you can always skip to the spoiler. You don't need to use the numForChar() function to actually get a digit value from a character. You can just use a constant array. A constant array is faster than that many if loop.
For example, you know that A, B, C will yield two and A's ASCII code is 65, B's is 66, and C's equal to 67. For that 3, you can have an array of 3 indexes, 0, 1, 2 and all of them stores a 2. Thus, if you get B, you subtract B's ASCII code 65 will yield 1. That that is the index to get the value from.
For getting a number to a character you can have a matrix array of char instead. Skip the first 2 index, 0 and 1. Each first level index, contain 3 arrays of 3 characters that are appropriate to their position.
For dictionary comparing, it is right that we don't need to actually look at the word if the length are unequal. However, besides that, since their dictionary words are sorted, if the word's first letter is lower than the range of the input first letter, we can skip that. On the other hand, if words' first letter are now higher than the highest of the input first letter, there isn't a point in continue searching. Take note that my English for code commenting are almost always bad unless I extensively document it.
Your Code(fixed):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int numForChar(char c){
if (c=='A'||c=='B'||c=='C') return 2;
else if(c=='D'||c=='E'||c=='F') return 3;
else if(c=='G'||c=='H'||c=='I') return 4;
else if(c=='J'||c=='K'||c=='L') return 5;
else if(c=='M'||c=='N'||c=='O') return 6;
else if(c=='P'||c=='R'||c=='S') return 7;
else if(c=='T'||c=='U'||c=='V') return 8;
else if(c=='W'||c=='X'||c=='Y') return 9;
else return 0;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
ifstream fin("namenum.in");
ifstream dict("dict.txt");
ofstream fout("namenum.out");
string S;
fin >> S;
int len = S.length();
bool match = false;
string x;
while(dict >> x){
string currName = x;
if(currName.length() != S.length()) continue;
string newString = x;
for(int i=0;i<len;i++){
//now encode the name as a number according to the rules
int num = numForChar(currName[i]) ^ 48;
currName[i] = (char)num;
}
if(currName == S){
fout << newString << "\n";
match = true;
}
}
if ( match == false ){
fout << "NONE" << endl;
}
return 0;
}
Spoiler Code(Improved):
#include <fstream>
#include <string>
using namespace std;
// A = 65
// 65 - 0 = 65
const char wToN[] = {
// A ,B ,C ,D ,E ,F ,G ,H ,I ,
'2','2','2','3','3','3','4','4','4',
// J ,K ,L ,M ,N ,O ,P ,Q ,R ,S
'5','5','5','6','6','6','7','7','7','7',
// T ,U ,V ,W ,X ,Y ,Z
'8','8','8','9','9','9','9'
};
// 2 = {A, B, C} = 2[0] = A, 2[1] = B, 2[2] C
const char nToW[10][3] = {
{}, // 0 skip
{}, // 1
{'A','B','C'},
{'D','E','F'},
{'G','H','I'},
{'J','K','L'},
{'M','N','O'},
{'P','R','S'},
{'T','U','V'},
{'W','X','Y'}
};
int main(){
ifstream fin("namenum.in");
ifstream dict("dict.txt");
ofstream fout("namenum.out");
string S;
fin >> S;
// Since this will not change
// make this a const to make it
// run faster.
const int len = S.length();
// lastlen is last Index of length
// We calculate this value here,
// So we do not have to calculate
// it for every loop.
const int lastLen = len - 1;
int i = 0;
unsigned char digits[len];
unsigned char firstLetter[3];
// If not match print None
bool match = false;
for ( ; i < len; i++ ){
// No need to check upper bound
// constrain did not call for check.
if ( S[i] < '2' ) {
fout << "NONE" << endl;
return 0;
}
}
const char digit1 = S[0] ^ 48;
// There are 3 set of first letter.
// We get them by converting digits[0]'s
// value using the nToW array.
firstLetter[0] = nToW[digit1][0];
firstLetter[1] = nToW[digit1][1];
firstLetter[2] = nToW[digit1][2];
string dictStr;
while(dict >> dictStr){
// For some reason, when keeping the i = 0 here
// it seem to work faster. That could be because of compiler xor.
i = 0;
// If it is higher than our range
// then there is no point contineuing.
if ( dictStr[0] > firstLetter[2] ) break;
// Skip if first character is lower
// than our range. or If they are not equal in length
if ( dictStr[0] < firstLetter[0] || dictStr.length() != len ) continue;
// If we are in the letter range
// we always check the second letter
// not the first, since we skip the first
i = 1;
for ( int j = 1; j < len; j++ ){
// We convert each letter in the word
// to the corresponding int value
// by subtracting the word ASCII value
// to 65 and use it again our wToN array.
// if it does not match the digits at
// this current position we end the loop.
if ( wToN[dictStr[i] - 65] != S[j] ) break;
// if we get here and there isn't an unmatch then it is a match.
if ( j == lastLen ) {
match = true;
fout << dictStr << endl;
break;
}
i++;
}
}
// No match print none.
if ( match == false ){
fout << "NONE" << endl;
}
return 0;
}
I suggest you use c++ file handling. Overwriting stdin and stdout doesn't seem appropriate.
Add these,
std::ifstream dict ("dict.txt");
std::ofstream fout ("namenum.out");
std::ifstream fin ("namenum.in");
Accordingly change,
cin >> S --to--> fin >> S;
cin >> x --to--> dict >> x
cout << newString --to--> fout << newString
The question:
Input data will give the number of test-cases in the first line.
Then test-cases themselves will follow, one case per line.
Each test-case describes an array of positive integers with value of 0 marking end. (this zero should not be included into calculations!!!).
Answer should contain average values for each array, rounded to nearest integer (see task on rounding), separated by spaces.
Problem:
Works fine but at third indice sum is assigned value of arrayInput and it messes everything up. Why does this happen and how can I fix it?
//araytest
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
//var
int i = 0;
int array[13] = {};
//take in # arrays
cin >> i;
for(int x = 0; x<i; x++ )
{
//reset variables (for every array)
float arraySize = 0,
sum = 0, avg = 0;
int indice = 0,
arrayInput = 0;
while(cin >> arrayInput){
if(arrayInput == 0)
{
if(indice == 0)
{
arraySize = 1; /*if only 0 put in first indice
to prevent divide by 0 */
break;
}
else
{
arraySize = indice; // 0 doesn't count
break;
}
}
sum += arrayInput;
array[indice] = arrayInput;
arrayInput = 0;
indice++;
}
avg = round(sum/arraySize);
cout << avg << " ";
}
return 0;
}
First, like other people said, the array you used in this code is totally useless. It did nothing but save arrayinput.
Second, you let arraysize sum avg to be type float. However, arrayinput is assigned to be integer!! That means you never get result like this 2.xxx. So the type you declare for variables is meaningless. They should have same type declaration. I don't understand why you code does not work well. Because if you enter integer number, you wont get anything wrong. But it will crash if you give number like 2.xxx or x.xxx.
i know that int and char cant be specified by different data types and char basically represents the ASCII values. what confuses me is storing them in the SAME data type which can be used later on. For example, if i were to input int and char both type of data from the user in variable x, how would i define the variable? like with what type of it?
lets say you were to input integers from the user and when the user enters a symbol('='), the program ends.
void main()
{
int count, flag = 0;
int i = 0;
int x = 0;
const int ASCII_VALUE_OF_EQ = '='
x = ASCII_VALUE_OF_EQ;
for (i = 0; i <=10; i++){
cout << "Enter the number = ";
cin >> x;
if (x == ASCII_VALUE_OF_EQ)
break;
}
//to find if the number before '=' was prime
int m = 2; int c = 0;
while (m < x)
{
if (x%m == 0){
c++;
break;
}
m++;
}
if (c == 0){
cout << x << " is a Prime number"<<endl<<"here are all the prime numbers that come before '='" << endl;
for (int a = 2; a <= x; a++)
{
int c = 0;
for (int b = 1; b <= a; b++)
{
if (a%b == 0)
c++;
}
if (c == 2){
cout << a << endl;
continue;
}
}
}
getch();
}
Here you want to write a smart piece of code that interprets different kind of input strings differently. If you are searching for a ready-made C++ function that interprets a string exactly as you want then you will be disappointed. There is no such magical function. :-(
Lets say I write in "0" as the input for your program. Do I want zero int(0) or the integral value of ascii('0') (int(48))??? Your magical string interpreter artificial intelligence function has to find out what I want! :-)
Read in one line of input as string
Find out how do you want to interpret the string with your magic AI function. Here are a few tips how to detect what the user wants: If the string length is 1 and it isn't a digit ('0'-'9') then you could treat it as a character (and you could use the first character of the string as an integer or you could exit your loop in some other cases - for example if it is a '=' character) otherwise you could treat it as the string representation of an integer and you could actually convert it to an integer with the std::stoi standard library function.
Of course you can use any other methods to detect the contents of the input string, I just gave you a tip as a kickstarter.
You may face other differences later, for example what happens if the user enters the input by specifying a few space characters before the actual input (and so on...) but these are just error handling codepieces. First get your code working with "correct" input.
How do we reverse a number with leading zeroes in number ?
For ex: If input is 004,
output should be 400.
I wrote below program but it works only when no leading zeroes in input.
int num;
cout<<"Enter number "<<endl;
cin>>num;
int rev = 0;
int reminder;
while(num != 0)
{
reminder = num % 10;
rev = rev * 10 + reminder;
num = num / 10;
}
cout<<"Reverse = "<<rev<<endl;
Is there any way to input a number with leading zeroes ? Even then, Above logic doesn't work for such numbers.
Any simple solution ? It is doable by taking input as string and processing it. But that doesn't look nice.
*EDIT: If length of number is known, it looks to be possible to reverse a number with leading zeroes. (Without using string)*
I shall post the code as soon as it works.
EDIT 2: I tried to put back characters to cin stream and then read and calculate the reverse. It is working for 2 digit numbers.
But if length is known, its far easier to find reverse. All i need to do is, multiply by 10 for required number of times.
So i think, i would go with string approach.
Hoping that interviewer would be happy :)
Leading zeroes are not represented by binary numbers (int, double, etc.) So you'll probably have to use std::string. Read the input into the string, then call std::reverse() passing the string as input.
Yes, you must use a string. You cannot store leading zeros in an int.
If you know the total width you'd like the number to be before-hand, you can reuse the code you have and store the results (from right to left) in a zero initialized array. Note: you'd probably want to add some error checking to the code listed below.
int num, width;
cout<<"Enter number "<<endl;
cin>>num;
cout<<"Enter width: "<<endl;
cin>>width;
int rev[width];
for (int i = 0; i < width; ++i)
rev[i] = 0;
int cnt = width - 1;
int rev = 0;
int reminder;
while(num != 0)
{
reminder = num % 10;
// rev = rev * 10 + reminder;
rev[cnt] = remainder;
--cnt;
num = num / 10;
}
cout << "Reverse: ";
for (int i = 0; i < width; ++i)
cout << rev[i];
cout << endl;
This will allow you to manipulate the number more easily in the future as well.
Read the number in string format (that is, use std::string) and reverse the string.
Once you convert your input to an integer, which you do in line 3, any information about the leading zeroes in the input of the user is lost.
You'll have to use a string.
A recursive approach, but easily converted to a loop...
#include <iostream>
int f(int value = 1)
{
char c;
return (std::cin.get(c) && isdigit(c))
? (c - '0') * value + f(10 * value)
: 0;
}
int main()
{
std::cout << f() << '\n';
}
As ChrisF said, you need to load a string, because 4 and 004 is the same int and you cannot distinguish it after you assign it to an int variable.
The next thing to do is trim the string to contain just digits (if you want to be correct) and run std::reverse on it - and you're done.
Keep the number as a string, and use std::reverse.
std::string num;
std::cout << "Enter number " << std::endl;
std::cin >> num;
std::string rev(num);
std::reverse(rev.begin(), rev.end());
std::cout << "Reverse = " << rev << std::endl;
Replace your while loop with a for loop with the same number of runs as you wish the original number has digits (including leading zeros). e.g. 004 would require the loop to be run 3 times, and not to terminate prematurely once x == 0.
s = int(raw_input(" enter the no of tyms :"))
n = 0
list, list1 = [], []
while n <= s:
m = raw_input("enter the number:")
n=n+1
list.append(m)
print list
list.reverse()
print list
Reverse in one of the best lang Python.