Ignoring non integers in an unknown length of data input - char

i am new to c language and seeking help in understanding my mistake.
I want to write a program that counts the number of 2 digit numbers in a row of integers and chars, for example " 21c sdhhj 32 fhddhf234 45" here are 3 two digit numbers. I set terminations to my loop (failed scanf %d or EOF) and still get an infinite loop. I understand thet failed scanf of integers should return 0 or -1 at EOF so why i get infinite loop? Thank you in advance! :)
void read(int blue[],int red[],int couple[])
{
int vote=0,rcount=0,bcount=0;
int ok=-2;
while (ok!=EOF)
{
ok=scanf("%d",&vote);
if (ok==0)
continue;
if (vote<TOTAL&&vote>0)
{
rcount=vote%10;
bcount=vote/10;
if (rcount==bcount)
continue;
couple[vote]++;
red[rcount]++;
blue[bcount]++;
}
ok=0;
}
i want to scan and store them as long as they are smaller then TOTAL (99) until the input is over.

Related

golang: How to get first bit of byte [duplicate]

This question already has answers here:
How do I get the bits from a byte in golang?
(5 answers)
Closed 8 months ago.
I have a hash:
b := hash.Sum(nil)
I am really just interested in the first bit of that byte. Is it 0 or 1?
So far I have this:
s := strconv.FormatInt(int64(b[0]),2)
if s[0] == '0' {
// it's 0
} else {
// it's 1
}
But I am sure there is a much more elegant (and more performant?) way to do this.
you could just check the result of bitwise and operator
if b[0] & 0x1 == 0x1 {
// it's 1
} else {
// it's 0
}
The Sum() function of a hash returns a slice of bytes. You want to isolate the first bit of the first byte, correct?
It's a simple matter of bit-twiddling. 2 or 3 machine instructions at most.
Depending on what you mean by "first bit",
This gives you the high-order/most significant/leftmost bit of a byte:
func HighOrderBit(b byte) byte {
return (b >> 7) & 0x01
}
And this gives you the low-order/least significant/rightmost bit of a byte:
func LowOrderBit(b byte) byte {
return (b >> 0) & 0x01
}
Note that the above works for any integer type: the only difference being the size of the right shift in highOrderBit(). The number of bits to shift right is the size of the integer type in bits minus one (e.g., for a 64-bit integer, the shift value is 64-1, or 63).

Generating fixed length random number in Go lang

I need to generate an unique random number in Golang. I have a simple ruby code for it:
(0...16).map { rand(10).to_s }.join
So, effectively i need to generate a number of length 16 where each digit is randomly picked up from [0-9]. I did not understand how random.Intn(n) function can help me. Any idea how can I do this?
One way is:
s := ""
for i := 0; i < 16; i++ {
s += (string)(rand.Intn(10) + 48)
}
48 is the ascii value for 0.
Or by using #Flimzy's more efficient suggestion:
s := fmt.Sprintf("%016d", rand.Int63n(1e16))
where "%016d" will help pad the number with zeros.

Distinct number of changes in real time data

Hi I am taking in data in real time where the value goes from 1009 , 1008 o 1007 to 0. I am trying to count the number of distinct times this occurs, for example the snippet below should count 2 distinct periods of change.
1008
1009
1008
0
0
0
1008
1007
1008
1008
1009
9
0
0
1009
1008
I have written a for loop as below but I can't figure out if the logic is correct as I get multiple increments instead of just the one
if(current != previous && current < 100)
x++;
else
x = x;
You tagged this with the LabVIEW tag. Is this actually supposed to be LabVIEW code?
Your logic has a bug related to the noise you say you have - if the value is less than 100 and it changes (for instance from 9 to 0), you log that as a change. You also have a line which doesn't do anything (x=x), although if this is supposed to be LV code, then this could make sense.
The code you posted here does not seem to make sense to me if I understand your goal. My understanding is that you want to identify this specific pattern:
1009
1008
1007
0
And that any deviation from this sequence of numbers would constitute data that should be ignored. To this end, you should be monitoring the history of the past 3 numbers. In C you might write this logic in the following way:
#include <stdio.h>
//Function to get the next value from our data stream.
int getNext(int *value) {
//Variable to hold our return code.
int code;
//Replace following line to get gext number from the stream. Possible read from a file?
*value = 0;
//Replace following logic to set 'code' appropriately.
if(*value == -1)
code = -1;
else
code = 0;
//Return 'code' to the caller.
return code;
}
//Example application for counting the occurrences of the sequence '1009','1008','1007','0'.
int main(int argc, char **argv) {
//Declare 4 items to store the past 4 items in the sequence (x0-x3)
//Declare a count and a flag to monitor the occurrence of our pattern
int x0 = 0, x1 = 0, x2 = 0, x3 = 0, count = 0, occurred = 0;
//Run forever (just as an example, you would provide your own looping structure or embed the algorithm in your app).
while(1) {
//Get the next element (implement getNext to provide numbers from your data source).
//If the function returns non-zero, exit the loop and print the count.
if( getNext(&x0) != 0 )
break;
//If the newest element is 0, we can trigger a check of the prior 3.
if(x0 == 0) {
//Set occurred to 0 if the prior elements don't match our pattern.
occurred = (x1 == 1007) && (x2 == 1008) && (x3 == 1009);
if(occurred) {
//Occurred was 1, meaning the pattern was matched. Increment our count.
count++;
//Reset occurred
occurred = 0;
}
//If the newest element is not 0, dont bother checking. Just shift the elements down our list.
} else {
x3 = x2; //Shift 3rd element to 4th position
x2 = x1; //Shift 2nd element to 3rd position
x1 = x0; //Shift 1st element to 2nd position
}
}
printf("The pattern count is %d\n", count);
//Exit application
return 0;
}
Note that the getNext function is just shown here as an example but obviously what I have implemented will not work. This function should be implemented based on how you are extracting data from the stream.
Writing the application in this way might not make sense within your larger application but the algorithm is what you should take away from this. Essentially you want to buffer 4 elements in a rolling window. You push the newest element into x0 and shift the others down. After this process you check the four elements to see if they match your desired pattern and increment the count accordingly.
If the requirement is to count falling edges and you don't care about the specific level, and want to reject noise band or ripple in the steady state then just make the conditional something like
if ((previous - current) > threshold)
No complex shifting, history, or filtering required. Depending on the application you can follow up with a debounce (persistency check) to ignore spurious samples (just keep track of falling/rising, or fell/rose as simple toggling state spanning a desired number of samples).
Code to the pattern, not the specific values; use constant or adjustable parameters to control the value sensitivity.

Is it possible to convert any base to any base (range 2 to 46)

I know it is simple and possible to convert any base to any base. First, convert any base to decimal and then decimal to any other base. However, I had done this before for range 2 to 36 but never done for 2 to 46.
I don't understand what I will put after 36, because 36 means 'z' (1-10 are decimal numbers then the 26 characters of the alphabet).
Please explains what happens after 36.
Every base has a purpose. Usually we do base conversion to make complex computations simpler.
Here are some most popular bases used and their representation.
2-binary numeral system
used internally by nearly all computers, is base two. The two digits are 0 and 1, expressed from switches displaying OFF and ON respectively.
8-octal system
is occasionally used in computing. The eight digits are 0–7.
10-decimal system
the most used system of numbers in the world, is used in arithmetic. Its ten digits are 0–9.
12-duodecimal (dozenal) system
is often used due to divisibility by 2, 3, 4 and 6. It was traditionally used as part of quantities expressed in dozens and grosses.
16-hexadecimal system
is often used in computing. The sixteen digits are 0–9 followed by A–F.
60-sexagesimal system
originated in ancient Sumeria and passed to the Babylonians. It is still used as the basis of our modern circular coordinate system (degrees, minutes, and seconds) and time measuring (minutes and hours).
64-Base 64
is also occasionally used in computing, using as digits A–Z, a–z, 0–9, plus two more characters, often + and /.
256-bytes
is used internally by computers, actually grouping eight binary digits together. For reading by humans, bytes are usually shown in hexadecimal.
The octal, hexadecimal and base-64 systems are often used in computing because of their ease as shorthand for binary. For example, every hexadecimal digit has an equivalent 4 digit binary number.
Radices are usually natural numbers. However, other positional systems are possible, e.g. golden ratio base (whose radix is a non-integer algebraic number), and negative base (whose radix is negative).
Your doubt is whether we can convert any base to any other base after base exceeds 36
( # of Alphabets + # of digits = 26+ 10= 36)
Taking example of 64-Base
It uses A–Z(Upper case)(26), a–z(lower case)(26), 0–9(10), plus 2 more characters. This way the constraint of 36 is resolved.
As we have (26+26+10+2)64 symbols in 64-base for representation, we can represent any number in 64 base. Similarly for more base they use different symbols for representation.
Source: http://en.wikipedia.org/wiki/Radix
The symbols you use for digits are arbitrary. For example base64 encoding uses 'A' to represent the zero valued digit and '0' represents the digit with the value 52. In base64 the digits go through the alphabet A-Z, then the lower case alphabet a-z, then the traditional digits 0-9, and then usually '+' and '/'.
One base 60 system used these symbols:
So the symbols used are arbitrary. There's nothing that 'happens' after 36 except what you say happens for your system.
With number systems, you are allowed to play god.
Playing god
What you need to understand is, that symbols are completely arbitrary. There is no god-given rule for "what comes after 36". You are free to define whatever you like.
To encode numbers with a certain base, all you need is the following:
base-many distinct symbols
a total order on the symbols
An arbitrary example
Naturally, there's an infinite amount of possibilities to create such a symbol table for a certain base:
Θ
ェ
す
)
0
・
_
o
や
ι
You could use this, to encode numbers with base 10. Θ being the zero-element, ェ being the one, etc.
Conventions
Of course, your peers would not be too happy if you started using the above symbol table. Because the symbols are arbitrary, we need conventions. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 is a convention, as are the symbols we use for hexadecimal, binary, etc. It is generally agreed upon what symbol table we use for what basis, that is why we can read the numbers someone else writes down.
The important thing to remember is that all numbers are symbolic of a value. Thus if you wanted to do that, you could just make a list containing the values at each position. After base 36, you simply run out of characters you can make a logical sequence out of. For example, if you used the Cambodian Alphabet with 70 odd characters, you could do base 80.
Here is the complete code I have written, hope this will help.
import java.util.Scanner;
/*
* author : roottraveller, nov 4th 2017
*/
public class BaseXtoBaseYConversion {
BaseXtoBaseYConversion() {
}
public static String convertBaseXtoBaseY(String inputNumber, final int inputBase, final int outputBase) {
int decimal = baseXToDecimal(inputNumber, inputBase);
return decimalToBaseY(decimal, outputBase);
}
private static int baseXNumeric(char input) {
if (input >= '0' && input <= '9') {
return Integer.parseInt(input + "");
} else if (input >= 'a' && input <= 'z') {
return (input - 'a') + 10;
} else if (input >= 'A' && input <= 'Z') {
return (input - 'A') + 10;
} else {
return Integer.MIN_VALUE;
}
}
public static int baseXToDecimal(String input, final int base) {
if(input.length() <= 0) {
return Integer.MIN_VALUE;
}
int decimalValue = 0;
int placeValue = 0;
for (int index = input.length() - 1; index >= 0; index--) {
decimalValue += baseXNumeric(input.charAt(index)) * (Math.pow(base, placeValue));
placeValue++;
}
return decimalValue;
}
private static char baseYCharacter(int input) {
if (input >= 0 && input <= 9) {
String str = String.valueOf(input);
return str.charAt(0);
} else {
return (char) ('a' + (input - 10));
//return ('A' + (input - 10));
}
}
public static String decimalToBaseY(int input, int base) {
String result = "";
while (input > 0) {
int remainder = input % base;
input = input / base;
result = baseYCharacter(remainder) + result; // Important, Notice the reverse order here
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter : number baseX baseY");
while(true) {
String inputNumber = scanner.next();
int inputBase = scanner.nextInt();
int outputBase = scanner.nextInt();
String outputNumber = convertBaseXtoBaseY(inputNumber, inputBase, outputBase);
System.out.println("Result = " + outputNumber);
}
}
}

What is the best algorithm to find whether an anagram is of a palindrome?

In this problem we consider only strings of lower-case English letters (a-z).
A string is a palindrome if it has exactly the same sequence of characters when traversed left-to-right as right-to-left. For example, the following strings are palindromes:
"kayak"
"codilitytilidoc"
"neveroddoreven"
A string A is an anagram of a string B if it consists of exactly the same characters, but possibly in another order. For example, the following strings are each other's anagrams:
A="mary" B="army" A="rocketboys" B="octobersky" A="codility" B="codility"
Write a function
int isAnagramOfPalindrome(String S);
which returns 1 if the string s is a anagram of some palindrome, or returns 0 otherwise.
For example your function should return 1 for the argument "dooernedeevrvn", because it is an anagram of a palindrome "neveroddoreven". For argument "aabcba", your function should return 0.
'Algorithm' would be too big word for it.
You can construct a palindrome from the given character set if each character occurs in that set even number of times (with possible exception of one character).
For any other set, you can easily show that no palindrome exists.
Proof is simple in both cases, but let me know if that wasn't clear.
In a palindrome, every character must have a copy of itself, a "twin", on the other side of the string, except in the case of the middle letter, which can act as its own twin.
The algorithm you seek would create a length-26 array, one for each lowercase letter, and start counting the characters in the string, placing the quantity of character n at index n of the array. Then, it would pass through the array and count the number of characters with an odd quantity (because one letter there does not have a twin). If this number is 0 or 1, place that single odd letter in the center, and a palindrome is easily generated. Else, it's impossible to generate one, because two or more letters with no twins exist, and they can't both be in the center.
I came up with this solution for Javascript.
This solution is based on the premise that a string is an anagram of a palindrome if and only if at most one character appears an odd number of times in it.
function solution(S) {
var retval = 0;
var sorted = S.split('').sort(); // sort the input characters and store in
// a char array
var array = new Array();
for (var i = 0; i < sorted.length; i++) {
// check if the 2 chars are the same, if so copy the 2 chars to the new
// array
// and additionally increment the counter to account for the second char
// position in the loop.
if ((sorted[i] === sorted[i + 1]) && (sorted[i + 1] != undefined)) {
array.push.apply(array, sorted.slice(i, i + 2));
i = i + 1;
}
}
// if the original string array's length is 1 or more than the length of the
// new array's length
if (sorted.length <= array.length + 1) {
retval = 1;
}
//console.log("new array-> " + array);
//console.log("sorted array-> " + sorted);
return retval;
}
i wrote this code in java. i don't think if its gonna be a good one ^^,
public static int isAnagramOfPalindrome(String str){
ArrayList<Character> a = new ArrayList<Character>();
for(int i = 0; i < str.length(); i++){
if(a.contains(str.charAt(i))){
a.remove((Object)str.charAt(i));
}
else{
a.add(str.charAt(i));
}
}
if(a.size() > 1)
return 0;
return 1;
}
Algorithm:
Count the number of occurrence of each character.
Only one character with odd occurrence is allowed since in a palindrome the maximum number of character with odd occurrence can be '1'.
All other characters should occur in an even number of times.
If (2) and (3) fail, then the given string is not a palindrome.
This adds to the other answers given. We want to keep track of the count of each letter seen. If we have more than one odd count for a letter then we will not be able to form a palindrome. The odd count would go in the middle, but only one odd count can do so.
We can use a hashmap to keep track of the counts. The lookup for a hashmap is O(1) so it is fast. We are able to run the whole algorithm in O(n). Here's it is in code:
if __name__ == '__main__':
line = input()
dic = {}
for i in range(len(line)):
ch = line[i]
if ch in dic:
dic[ch] += 1
else:
dic[ch] = 1
chars_whose_count_is_odd = 0
for key, value in dic.items():
if value % 2 == 1:
chars_whose_count_is_odd += 1
if chars_whose_count_is_odd > 1:
print ("NO")
else:
print ("YES")
I have a neat solution in PHP posted in this question about complexities.
class Solution {
// Function to determine if the input string can make a palindrome by rearranging it
static public function isAnagramOfPalindrome($S) {
// here I am counting how many characters have odd number of occurrences
$odds = count(array_filter(count_chars($S, 1), function($var) {
return($var & 1);
}));
// If the string length is odd, then a palindrome would have 1 character with odd number occurrences
// If the string length is even, all characters should have even number of occurrences
return (int)($odds == (strlen($S) & 1));
}
}
echo Solution :: isAnagramOfPalindrome($_POST['input']);
It uses built-in PHP functions (why not), but you can make it yourself, as those functions are quite simple. First, the count_chars function generates a named array (dictionary in python) with all characters that appear in the string, and their number of occurrences. It can be substituted with a custom function like this:
$count_chars = array();
foreach($S as $char) {
if array_key_exists($char, $count_chars) {
$count_chars[$char]++;
else {
$count_chars[$char] = 1;
}
}
Then, an array_filter with a count function is applied to count how many chars have odd number of occurrences:
$odds = 0;
foreach($count_chars as $char) {
$odds += $char % 2;
}
And then you just apply the comparison in return (explained in the comments of the original function).
return ($odds == strlen($char) % 2)
This runs in O(n). For all chars but one, must be even. the optional odd character can be any odd number.
e.g.
abababa
def anagram_of_pali(str):
char_list = list(str)
map = {}
nb_of_odds = 0
for char in char_list:
if char in map:
map[char] += 1
else:
map[char] = 1
for char in map:
if map[char] % 2 != 0:
nb_of_odds += 1
return True if nb_of_odds <= 1 else False
You just have to count all the letters and check if there are letters with odd counts. If there are more than one letter with odd counts the string does not satisfy the above palindrome condition.
Furthermore, since a string with an even number letters must not have a letter with an odd count it is not necessary to check whether string length is even or not. It will take O(n) time complexity:
Here's the implementation in javascript:
function canRearrangeToPalindrome(str)
{
var letterCounts = {};
var letter;
var palindromeSum = 0;
for (var i = 0; i < str.length; i++) {
letter = str[i];
letterCounts[letter] = letterCounts[letter] || 0;
letterCounts[letter]++;
}
for (var letterCount in letterCounts) {
palindromeSum += letterCounts[letterCount] % 2;
}
return palindromeSum < 2;
}
All right - it's been a while, but as I was asked such a question in a job interview I needed to give it a try in a few lines of Python. The basic idea is that if there is an anagram that is a palindrome for even number of letters each character occurs twice (or something like 2n times, i.e. count%2==0). In addition, for an odd number of characters one character (the one in the middle) may occur only once (or an uneven number - count%2==1).
I used a set in python to get the unique characters and then simply count and break the loop once the condition cannot be fulfilled. Example code (Python3):
def is_palindrome(s):
letters = set(s)
oddc=0
fail=False
for c in letters:
if s.count(c)%2==1:
oddc = oddc+1
if oddc>0 and len(s)%2==0:
fail=True
break
elif oddc>1:
fail=True
break
return(not fail)
def is_anagram_of_palindrome(S):
L = [ 0 for _ in range(26) ]
a = ord('a')
length = 0
for s in S:
length += 1
i = ord(s) - a
L[i] = abs(L[i] - 1)
return length > 0 and sum(L) < 2 and 1 or 0
While you can detect that the given string "S" is a candidate palindrome using the given techniques, it is still not very useful. According to the implementations given,
isAnagramOfPalindrome("rrss") would return true but there is no actual palindrome because:
A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction. (Wikipedia)
And Rssr or Srrs is not an actual word or phrase that is interpretable. Same with it's anagram. Aarrdd is not an anagram of radar because it is not interpretable.
So, the solutions given must be augmented with a heuristic check against the input to see if it's even a word, and then a verification (via the implementations given), that it is palindrome-able at all. Then there is a heuristic search through the collected buckets with n/2! permutations to search if those are ACTUALLY palindromes and not garbage. The search is only n/2! and not n! because you calculate all permutations of each repeated letter, and then you mirror those over (in addition to possibly adding the singular pivot letter) to create all possible palindromes.
I disagree that algorithm is too big of a word, because this search can be done pure recursively, or using dynamic programming (in the case of words with letters with occurrences greater than 2) and is non trivial.
Here's some code: This is same as the top answer that describes algorithm.
1 #include<iostream>
2 #include<string>
3 #include<vector>
4 #include<stack>
5
6 using namespace std;
7
8 bool fun(string in)
9 {
10 int len=in.size();
11 int myints[len ];
12
13 for(int i=0; i<len; i++)
14 {
15 myints[i]= in.at(i);
16 }
17 vector<char> input(myints, myints+len);
18 sort(input.begin(), input.end());
19
20 stack<int> ret;
21
22 for(int i=0; i<len; i++)
23 {
24 if(!ret.empty() && ret.top()==input.at(i))
25 {
26 ret.pop();
27 }
28 else{
29 ret.push(input.at(i));
30 }
31 }
32
33 return ret.size()<=1;
34
35 }
36
37 int main()
38 {
39 string input;
40 cout<<"Enter word/number"<<endl;
41 cin>>input;
42 cout<<fun(input)<<endl;
43
44 return 0;
45 }

Resources