Creating an online palindrome - palindrome

I am trying to create an online palindrome sensor(The alphabet consists of 0,1,2,3,...9). The code is as follows:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int x=0;
int y=0;
int c;
int i=0;
while(1)
{
cin>>c;
//I keep a track of previous number in x and its reverse in y and use them to create the
//the new number and reverse at every input. Then I compare x and y. If equal the number is
//a palindrome.
/*eg:(When 121 is entered digit by digit)
i=0:-
x=10*0+1 y=0+ 10^0 *1
i=1:-
x=10*1+2 y=1+ 10^1 *2
i=2:-
x=10*12+1 y=21+ 10^2 *1
*/
x=10*x+c;
y=y+ static_cast<int>(pow(10.0,static_cast<double>(i)) *c);
cout<<"y= "<<y<<" and "<<"x= "<<x<<endl;
if(y==x)
cout<<"Palindrome"<<endl;
i++;
}
return 0;
}
First, I enter 1 and it was indicated as palindrome(as expected). Then, I entered 2 and nothing happened(as expected, 'y= 21 and x= 12' was printed). But, then I again entered 1 and this time too nothing happened(not as expected) and this was printed:
y= 120 and x= 121
Can anyone tell me, how did y become 120 when it was supposed to be 121?

You are doing far too much math:
public static boolean isPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
All you need to do is fill an array with values as the user enters them and invoke a function similar to this. The use of exponents is a colossal waste of resources when simpler solutions exist.

Related

what is the difference between these 2 for loop in dart?

i just started learning dart but there is something i cant figure out.
the first loop it prints me from 1 3 5 7 9
the second one it prints for me from 0 to 9.
why did it remove the even numbers from the loop below? i only added a variable in the first loop
void main () {
for(double a = 0; a <10 ; a++)
{
double b = a++;
print (a);
}
print("---");
for(double a = 0; a <10 ; a++)
{
print(a);
}
}
the a++ is a shortcut to a = a +1, which means that b in each step is getting the value of a+1 and the second loop would only print odd numbers since you are jumping 2 steps in each loop (a++ in the loop brackets and the b = a++)

C question in logical OR: 2 operands evaluated (0) false, but the result works as TRUE range

My doubt is about the basic theory of "or logical operator". Especifically, logical OR returns true only if either one operand is true.
For instance, in this OR expression (x<O || x> 8) using x=5 when I evalute the 2 operand, I interpret it as both of them are false.
But I have an example that does not fit wiht it rule. On the contrary the expression works as range between 0 and 8, both included.
Following the code:
#include <stdio.h>
int main(void)
{
int x ; //This is the variable for being evaluated
do
{
printf("Imput a figure between 1 and 8 : ");
scanf("%i", &x);
}
while ( x < 1 || x > 8); // Why this expression write in this way determinate the range???
{
printf("Your imput was ::: %d ",x);
printf("\n");
}
printf("\n");
}
I have modified my first question. I really appreciate any helpo in order to clarify my doubt
In advance, thank you very much. Otto
It's not a while loop; it's a do ... while loop. The formatting makes it hard to see. Reformatted:
#include <stdio.h>
int main(void) {
int x;
// Execute the code in the `do { }` block once, no matter what.
// Keep executing it again and again, so long as the condition
// in `while ( )` is true.
do {
printf("Imput a figure between 1 and 8 : ");
scanf("%i", &x);
} while (x < 1 || x > 8);
// This creates a new scope. While perfectly valid C,
// this does absolutely nothing in this particular case here.
{
printf("Your imput was ::: %d ",x);
printf("\n");
}
printf("\n");
}
The block with the two printf calls is not part of the loop. The while (x < 1 || x > 8) makes it so that the code in the do { } block runs, so long as x < 1 or x > 8. In other words, it runs until x is between 1 and 8. This has the effect of asking the user to input a number again and again, until they finally input a number that's between 1 and 8.

Flutter/Dart List with set size and bit shifting question

I'm writing to a piece of hardware using bluetooth and need to format my data in a specific way.
When I get the value from the device I have do a little bit shifting to get the correct answer.
Here is a breakdown of the values I am getting back from the device.
byte[1] = (unsigned char)temp;
byte[2] = (unsigned char)(temp>>8);
byte[3] = (unsigned char)(temp>>16);
byte[4] = (unsigned char)(temp>>24);
It is a List with a size of 4. A real world example would be this:
byte[1] = '46';
byte[2] = '2';
byte[3] = '0';
byte[4] = '0';
This should work out to be
558
My working code to get this is:
int _shiftLeft(int n, int amount) {
return n << amount;
}
int _getValue(List<int> list) {
int temp;
temp = list[1];
temp += _shiftLeft(list[2], 8);
temp += _shiftLeft(list[3], 16);
temp += _shiftLeft(list[4], 24);
return temp;
}
The actual list I get back from the device is quite large but I only need values 1-4.
This works great and gets me the correct value back. Now I have to write to the device. So if I have a value of 558, I need to build a list of size 4 with the same bit shifting but in reverse. Following the exact method above but in reverse. What is the best way to do this?
Basically if I pass a method a value of '558' I need to get back a List<int> of [46,2,0,0]
You can get only the lower 8 bits by the bitwise AND operation & 255 (or & 0xFF).
Just combining this with bit shifting will do.
int _shiftRight(int n, int amount) {
return n >> amount;
}
List<int> _getList(int value) {
final list = <int>[];
list.add(value & 255);
list.add(_shiftRight(value, 8) & 255);
list.add(_shiftRight(value, 16) & 255);
list.add(_shiftRight(value, 24) & 255);
return list;
}
It can be simplified using for as follows:
List<int> _getList(int value) {
final list = <int>[];
for (int i = 0; i < 4; i++) {
list.add(value >> i * 8 & 255);
}
return list;
}

Split a integer into its separate digits

Say I have an integer, 9802, is there a way I can split that value in the four individual digits : 9, 8, 0 & 2 ?
Keep doing modulo-10 and divide-by-10:
int n; // from somewhere
while (n) { digit = n % 10; n /= 10; }
This spits out the digits from least-significant to most-significant. You can clearly generalise this to any number base.
You probably want to use mod and divide to get these digits.
Something like:
Grab first digit:
Parse digit: 9802 mod 10 = 2
Remove digit: (int)(9802 / 10) = 980
Grab second digit:
Parse digit: 980 mod 10 = 0
Remove digit: (int)(980 / 10) = 98
Something like that.
if you need to display the digits in the same order you will need to do the module twice visa verse this is the code doing that:
#import <Foundation/Foundation.h>
int main (int argc, char * argv[])
{
#autoreleasepool {
int number1, number2=0 , right_digit , count=0;
NSLog (#"Enter your number.");
scanf ("%i", &number);
do {
right_digit = number1 % 10;
number1 /= 10;
For(int i=0 ;i<count; i++)
{
right_digit = right_digit*10;
}
Number2+= right_digit;
Count++;
}
while ( number != 0 );
do {
right_digit = number2 % 10;
number2 /= 10;
Nslog(#”digit = %i”, number2);
}
while ( number != 0 );
}
}
return 0;
}
i hope that it is useful :)

"Nearly divisible"

I want to check if a floating point value is "nearly" a multiple of 32. E.g. 64.1 is "nearly" divisible by 32, and so is 63.9.
Right now I'm doing this:
#define NEARLY_DIVISIBLE 0.1f
float offset = fmodf( val, 32.0f ) ;
if( offset < NEARLY_DIVISIBLE )
{
// its near from above
}
// if it was 63.9, then the remainder would be large, so add some then and check again
else if( fmodf( val + 2*NEARLY_DIVISIBLE, 32.0f ) < NEARLY_DIVISIBLE )
{
// its near from below
}
Got a better way to do this?
well, you could cut out the second fmodf by just subtracting 32 one more time to get the mod from below.
if( offset < NEARLY_DIVISIBLE )
{
// it's near from above
}
else if( offset-32.0f>-1*NEARLY_DIVISIBLE)
{
// it's near from below
}
In a standard-compliant C implementation, one would use the remainder function instead of fmod:
#define NEARLY_DIVISIBLE 0.1f
float offset = remainderf(val, 32.0f);
if (fabsf(offset) < NEARLY_DIVISIBLE) {
// Stuff
}
If one is on a non-compliant platform (MSVC++, for example), then remainder isn't available, sadly. I think that fastmultiplication's answer is quite reasonable in that case.
You mention that you have to test near-divisibility with 32. The following theory ought to hold true for near-divisibility testing against powers of two:
#define THRESHOLD 0.11
int nearly_divisible(float f) {
// printf(" %f\n", (a - (float)((long) a)));
register long l1, l2;
l1 = (long) (f + THRESHOLD);
l2 = (long) f;
return !(l1 & 31) && (l2 & 31 ? 1 : f - (float) l2 <= THRESHOLD);
}
What we're doing is coercing the float, and float + THRESHOLD to long.
f (long) f (long) (f + THRESHOLD)
63.9 63 64
64 64 64
64.1 64 64
Now we test if (long) f is divisible with 32. Just check the lower five bits, if they are all set to zero, the number is divisible by 32. This leads to a series of false positives: 64.2 to 64.8, when converted to long, are also 64, and would pass the first test. So, we check if the difference between their truncated form and f is less than or equal to THRESHOLD.
This, too, has a problem: f - (float) l2 <= THRESHOLD would hold true for 64 and 64.1, but not for 63.9. So, we add an exception for numbers less than 64 (which, when incremented by THRESHOLD and subsequently coerced to long -- note that the test under discussion has to be inclusive with the first test -- is divisible by 32), by specifying that the lower 5 bits are not zero. This will hold true for 63 (1000000 - 1 == 1 11111).
A combination of these three tests would indicate whether the number is divisible by 32 or not. I hope this is clear, please forgive my weird English.
I just tested the extensibility to other powers of three -- the following program prints numbers between 383.5 and 388.4 that are divisible by 128.
#include <stdio.h>
#define THRESHOLD 0.11
int main(void) {
int nearly_divisible(float);
int i;
float f = 383.5;
for (i=0; i<50; i++) {
printf("%6.1f %s\n", f, (nearly_divisible(f) ? "true" : "false"));
f += 0.1;
}
return 0;
}
int nearly_divisible(float f) {
// printf(" %f\n", (a - (float)((long) a)));
register long l1, l2;
l1 = (long) (f + THRESHOLD);
l2 = (long) f;
return !(l1 & 127) && (l2 & 127 ? 1 : f - (float) l2 <= THRESHOLD);
}
Seems to work well so far!
I think it's right:
bool nearlyDivisible(float num,float div){
float f = num % div;
if(f>div/2.0f){
f=f-div;
}
f=f>0?f:0.0f-f;
return f<0.1f;
}
For what I gather you want to detect if a number is nearly divisible by other, right?
I'd do something like this:
#define NEARLY_DIVISIBLE 0.1f
bool IsNearlyDivisible(float n1, float n2)
{
float remainder = (fmodf(n1, n2) / n2);
remainder = remainder < 0f ? -remainder : remainder;
remainder = remainder > 0.5f ? 1 - remainder : remainder;
return (remainder <= NEARLY_DIVISIBLE);
}
Why wouldn't you just divide by 32, then round and take the difference between the rounded number and the actual result?
Something like (forgive the untested/pseudo code, no time to lookup):
#define NEARLY_DIVISIBLE 0.1f
float result = val / 32.0f;
float nearest_int = nearbyintf(result);
float difference = abs(result - nearest_int);
if( difference < NEARLY_DIVISIBLE )
{
// It's nearly divisible
}
If you still wanted to do checks from above and below, you could remove the abs, and check to see if the difference is >0 or <0.
This is without uing the fmodf twice.
int main(void)
{
#define NEARLY_DIVISIBLE 0.1f
#define DIVISOR 32.0f
#define ARRAY_SIZE 4
double test_var1[ARRAY_SIZE] = {63.9,64.1,65,63.8};
int i = 54;
double rest;
for(i=0;i<ARRAY_SIZE;i++)
{
rest = fmod(test_var1[i] ,DIVISOR);
if(rest < NEARLY_DIVISIBLE)
{
printf("Number %f max %f larger than a factor of the divisor:%f\n",test_var1[i],NEARLY_DIVISIBLE,DIVISOR);
}
else if( -(rest-DIVISOR) < NEARLY_DIVISIBLE)
{
printf("Number %f max %f less than a factor of the divisor:%f\n",test_var1[i],NEARLY_DIVISIBLE,DIVISOR);
}
}
return 0;
}