Multiply a number by 2 in Brainfuck? - brainfuck

Given an arbitrarily long number, how can I output its double? I know how to multiply small numbers together as long as the result is <10, but what about larger integers like 32984335, and doubling something like that? I don't know the right way to handle something like this.

This is the algorithm you need to implement:
Start the current count with 0;
Multiply the current count by ten: this can be achieved by dupping 10 times, and then adding all dupes together;
Read a digit;
If it's null proceed to 8;
Convert it to an actual number: this can be achieved by subtracting 48;
Add it to the current count;
Proceed to 2;
Duplicate the current count;
Adding the dupes together;
Divide by ten using repeated subtraction; keep quotient and remainder;
Grab the remainder;
Make it a digit (add 48);
Print it;
Grab the quotient from 10;
If it's not zero, goto 10;
The end.
All these steps consists of basic brainfuck idioms, so it should be easy to implement.

Here's a start. It will multiply a byte of input, but I think you can build off it to make it work for any number. Basically, you take in a number, and store the number to multiply by (2) in the next pointer. You loop decrementing the first number, and then nest a loop decrementing the second number; in each iteration of the inner loop, you increment the pointer to the right of your second operand. This is your result.
, take input to ptr 0
[
- decrement first operand (input)
>++ number to multiply by (2) at ptr 1
[
>+ result in ptr 2
<- decrement second operand (2)
]
<
]
>> move to result

Here is my BF code: http://ideone.com/2Y9pk8
->>+>,+
[
-----------
[
-->++++++[-<------>]<
[->+<[->+<[->+<[->+<[>----<-<+>[->+<]]]]]]>
[-<++>]<+
>,+
[
-----------
[->+<]
]
>[-<+>]<
]
<[<]
>-[<++++++++[->++++++<]>.[-]]
>[<++++++++[->++++++<]>-.[-]>]
++++++++++.[-]
<+[-<+]
->>+>,+
]
It reads each number in each line until EOF, and multiply all numbers by two..

Here is the code for multiplying a number by 2.
,[>++<-]>.
Hope this helps.

Related

Mean of values before and after a specific element

I have an array of 1 x 400, where all element values are above 1500. However, I have some elements that have values<50 which are wrong measures and I would like to have the mean of the elements before and after the wrong measured data points and replace it in the main array.
For instance, element number 17 is below 50 so I want to take the mean of elements 16 and 18 and replace element 17 with the new mean.
Can someone help me, please? many thanks in advance.
No language is specified in the question, but for Python you could work with List Comprehension:
# array with 400 values, some of which are incorrect
arr = [...]
arr = [arr[i] if arr[i] >= 50 else (arr[i-1]+arr[i+1])/2 for i in range(len(arr))]
That is, if arr[i] is less than 50, it'll be replaced by the average value of the element before and after it. There are two issues with this approach.
If i is the first or last element, then one of the two values will be undefined, and no mean can be obtained. This can be fixed by just using the value of the available neighbour, as specified below
If two values in a row are very low, the leftmost one will use the rightmost one to calculate its value, which will result in a very low value. This is a problem that may not occur for you in practice, but it is an inherent result of the way you wish to recalculate values, and you might want to keep it in mind.
Improved version, keeping in mind the edge cases:
# don't alter the first and last item, even if they're low
arr = [arr[i] if arr[i] >= 50 or i == 0 or i+1 == len(arr) else (arr[i-1]+arr[i+1])/2 for i in range(len(arr))]
# replace the first and last element if needed
if arr[0] < 50:
arr[0] = arr[1]
if arr[len(arr)-1] < 50:
arr[len(arr)-1] = arr[len(arr)-2]
I hope this answer was useful for you, even if you intend to use another language or framework than python.

Hash an 8 digit number that contains non repetitive digits from 1 to 8 only

Given that a number can contain only digits from 1 to 8 (with no repetition), and is of length 8, how can we hash such numbers without using a hashSet?
We can't just directly use the value of the number of the hashing value, as the stack size of the program is limited. (By this, I mean that we can't directly make the index of an array, represent our number).
Therefore, this 8 digit number needs to be mapped to, at maximum, a 5 digit number.
I saw this answer. The hash function returns a 8-digit number, for a input that is an 8-digit number.
So, what can I do here?
There's a few things you can do. You could subtract 1 from each digit and parse it as an octal number, which will map one-to-one every number from your domain to the range [0,16777216) with no gaps. The resulting number can be used as an index into a very large array. An example of this could work as below:
function hash(num) {
return parseInt(num
.toString()
.split('')
.map(x => x - 1), 8);
}
const set = new Array(8**8);
set[hash(12345678)] = true;
// 12345678 is in the set
Or if you wanna conserve some space and grow the data structure as you add elements. You can use a tree structure with 8 branches at every node and a maximum depth of 8. I'll leave that up to you to figure out if you think it's worth the trouble.
Edit:
After seeing the updated question, I began thinking about how you could probably map the number to its position in a lexicographically sorted list of the permutations of the digits 1-8. That would be optimal because it gives you the theoretical 5-digit hash you want (under 40320). I had some trouble formulating the algorithm to do this on my own, so I did some digging. I found this example implementation that does just what you're looking for. I've taken inspiration from this to implement the algorithm in JavaScript for you.
function hash(num) {
const digits = num
.toString()
.split('')
.map(x => x - 1);
const len = digits.length;
const seen = new Array(len);
let rank = 0;
for(let i = 0; i < len; i++) {
seen[digits[i]] = true;
rank += numsBelowUnseen(digits[i], seen) * fact(len - i - 1);
}
return rank;
}
// count unseen digits less than n
function numsBelowUnseen(n, seen) {
let count = 0;
for(let i = 0; i < n; i++) {
if(!seen[i]) count++;
}
return count;
}
// factorial fuction
function fact(x) {
return x <= 0 ? 1 : x * fact(x - 1);
}
kamoroso94 gave me the idea of representing the number in octal. The number remains unique if we remove the first digit from it. So, we can make an array of length 8^7=2097152, and thus use the 7-digit octal version as index.
If this array size is bigger than the stack, then we can use only 6 digits of the input, convert them to their octal values. So, 8^6=262144, that is pretty small. We can make a 2D array of length 8^6. So, total space used will be in the order of 2*(8^6). The first index of the second dimension represents that the number starts from the smaller number, and the second index represents that the number starts from the bigger number.

binary to decimal in objective-c

I want to convert the decimal number 27 into binary such a way that , first the digit 2 is converted and its binary value is placed in an array and then the digit 7 is converted and its binary number is placed in that array. what should I do?
thanks in advance
That's called binary-coded decimal. It's easiest to work right-to-left. Take the value modulo 10 (% operator in C/C++/ObjC) and put it in the array. Then integer-divide the value by 10 (/ operator in C/C++/ObjC). Continue until your value is zero. Then reverse the array if you need most-significant digit first.
If I understand your question correctly, you want to go from 27 to an array that looks like {0010, 0111}.
If you understand how base systems work (specifically the decimal system), this should be simple.
First, you find the remainder of your number when divided by 10. Your number 27 in this case would result with 7.
Then you integer divide your number by 10 and store it back in that variable. Your number 27 would result in 2.
How many times do you do this?
You do this until you have no more digits.
How many digits can you have?
Well, if you think about the number 100, it has 3 digits because the number needs to remember that one 10^2 exists in the number. On the other hand, 99 does not.
The answer to the previous question is 1 + floor of Log base 10 of the input number.
Log of 100 is 2, plus 1 is 3, which equals number of digits.
Log of 99 is a little less than 2, but flooring it is 1, plus 1 is 2.
In java it is like this:
int input = 27;
int number = 0;
int numDigits = Math.floor(Log(10, input)) + 1;
int[] digitArray = new int [numDigits];
for (int i = 0; i < numDigits; i++) {
number = input % 10;
digitArray[numDigits - i - 1] = number;
input = input / 10;
}
return digitArray;
Java doesn't have a Log function that is portable for any base (it has it for base e), but it is trivial to make a function for it.
double Log( double base, double value ) {
return Math.log(value)/Math.log(base);
}
Good luck.

how can I count the number of set bits in a uint in specman?

I want to count the number of set bits in a uint in Specman:
var x: uint;
gen x;
var x_set_bits: uint;
x_set_bits = ?;
What's the best way to do this?
One way I've seen is:
x_set_bits = pack(NULL, x).count(it == 1);
pack(NULL, x) converts x to a list of bits.
count acts on the list and counts all the elements for which the condition holds. In this case the condition is that the element equals 1, which comes out to the number of set bits.
I don't know Specman, but another way I've seen this done looks a bit cheesy, but tends to be efficient: Keep a 256-element array; each element of the array consists of the number of bits corresponding to that value. For example (pseudocode):
bit_count = [0, 1, 1, 2, 1, ...]
Thus, bit_count2 == 1, because the value 2, in binary, has a single "1" bit. Simiarly, bit_count[255] == 8.
Then, break the uint into bytes, use the byte values to index into the bit_count array, and add the results. Pseudocode:
total = 0
for byte in list_of_bytes
total = total + bit_count[byte]
EDIT
This issue shows up in the book Beautiful Code, in the chapter by Henry S. Warren. Also, Matt Howells shows a C-language implementation that efficiently calculates a bit count. See this answer.

choose random value

I am new to iPhone programming. I have 10 number say (1,2,3,4,5,6,7,8,9,10). I want to choose randomly 1 number from the above 10 numbers. How can I choose a random number from a set of numbers?
If you simply want a value between 1 and 10, you can use the standard C rand() method. This returns an integer between zero and RAND_MAX.
To get a value between 0 and 9 you can use the % operator. So to get a value between 1 and 10 you can use:
rand()%10 + 1
If you don't want the same series of pseudo random numbers each time, you'll need to use srand to seed the random number generator. A good value to seed it with would be the current time.
If you're asking about choosing a number from a list of arbitrary (and possibly non consecutive) numbers, you could use the following.
int numbers[] = {2,3,5,7,11,13,17,19,23,29};
int randomChoice = numbers[rand()%10];
To generate a random number you should use random() function. But if you call it twice it gives you two equal answers. Before calling random(), call srand(time()) to get fresh new random number. if you want to use for(int i = 0; ...) to create numbers,
use srand(time() + i).
Something like this:
- (IBAction)generate:(id)sender
{
// Generate a number between 1 and 10 inclusive
int generated;
generated = (random() % 10) + 1;
}