simple number series - numbers

This is a simple number series question, I have numbers in series like
2,4,8,16,32,64,128,256 these numbers are formed by 2,2(square),2(cube) and so on.
Now if I add 2+4+8 = 14. 14 will get only by the addition 2,4 and 8.
so i have 14in my hand now, By some logic i need to get the values which are helped to get 14
Example:
2+4+8 = 14
14(some logic) = 2,4,8.

This is an easy one:
2+4+8=14 ... 14+2=16
2+4+8+16=30 ... 30+2=32
2+4+8+16+32=62 ... 62+2=64
So you just need to add 2 to your sum, then calculate ld (binary logarithm), and then subtract 1. This gives you the number of elements of your sequence you need to add up.
e.g. in PHP:
$target=14;
$count=log($target+2)/log(2)-1;
echo $count;
gives 3, so you have to add the first 3 elements of your sequence to get 14.

Check the following C# code:
x = 14; // In your case
indices = new List<int>();
for (var i = 31; i >= i; i--)
{
var pow = Math.Pow(2, i);
if x - pow >= 0)
{
indices.Add(pow);
x -= pow;
}
}
indices.Reverse();

assuming C:
unsigned int a = 14;
while( a>>=1)
{
printf("%d ", a+1);
}

if this is programming, something like this would suffice:
int myval = 14;
int maxval = 256;
string elements = "";
for (int i = 1; i <= maxval; i*=2)
{
if ((myval & i) != 0)
elements += "," + i.ToString();
}

Use congruency module 2-powers: 14 mod 2 = 0, 14 mod 4 = 2, 14 mod 8 = 6, 14 mod 16 = 14, 14 mod 32 = 14...
The differences of this sequence are the numbers you look for 2 - 0 = 2, 6 - 2 = 4, 14 - 6 = 8, 14 - 14 = 0, ...
It's called the p-adic representation and is formally a bit more difficult to explain, but I hope this gives you an idea for an algorithm.

Related

Palindrome Number: what is wrong with my code?

I am writing code in c++ to detect if an input number is a Palindrome Number, which means its reverse is the same as the origin. I have problems computing the reverse int.
e.g.
121 returns true;
123 returns false;
12321 returns true;
10 returns false;
I input 123 and the sum should be 321. However, my code keeps returning 386. I stepped into the function with xcode. Still, I have no idea why reverse += (3 * 10) + 2 turns to be 35 or why the final reverse number to be 386.
int origin = x;
int reverse = 0;
while (x != 0) {
int digit = x % 10;
reverse += ((reverse * 10) + digit);
x /= 10;
}
why reverse += (3 * 10) + 2 turns to be 35
Because += adds what is on the right to the existing value of what’s on the left. (3 * 10) + 2 is 32, but reverse was already 3 and so you are adding your 32 to the existing 3, which is 35.
You don’t want to add to the value of reverse; you want to replace it.
Change
reverse += ((reverse * 10) + digit)
To
reverse = ((reverse * 10) + digit)

Pass-by-value vs pass-by-reference vs pass-by-value-result

I've got this question, and I'm a bit confused as to what would be printed, especially for pass-by-reference. What value would be passed to x if there are two parameters? Thanks!
Consider the following program. For each of the following parameter-passing methods, what is printed?
a. Passed by value
b. Passed by reference
c. Passed by value-result
void main()
{
int x = 5;
foo (x,x);
print (x);
}
void foo (int a, int b)
{
a = 2 * b + 1;
b = a - 1;
a = 3 * a - b;
}
The first two should be pretty straightforward, the last one is probably throwing you because it's not really a C++ supported construct. It's something that had been seen in Fortran and Ada some time ago. See this post for more info
As for your results, I think this is what you would get:
1)
5
2)
x = 5,
a = 2 * 5 + 1 = 11
b = 11 - 1 = 10
a = 3 * 10 - 10 = 20; // remember, a and b are the same reference!
x = 20
3) Consider this (in C++ style). We will copy x into a variable, pass that by reference, and then copy the result back to x:
void main()
{
int x = 5;
int copy = x;
foo (copy,copy); // copy is passed by reference here, for sake of argument
x = copy;
print (x);
}
Since nothing in the foo function is doing anything with x directly, your result will be the same as in #2.
Now, if we had something like this for foo
void foo (int a, int b)
{
a = 2 * b + 1;
x = a - 1; // we'll assume x is globally accessible
a = 3 * a - b;
}
Then # 2 would produce the same result, but #3 would come out like so:
a = 2 * 5 + 1 = 11
x = 11 - 1 = 10 // this no longer has any effect on the final result
a = 3 * 11 - 11 = 22
x = 22

Solving Twitter Puddle with Zipper

This is a follow-up to my previous question. Consider the following puzzle
I would like to generate a waterLevel array, so that the i-th item is the water level at the i-th point and then sum them up to solve the puzzle.
waterLevel[i] =
max(0, min(max of left neighbors, max of right neighbors) - height[i])
I would probably try to code it with Zipper
waterLevels = heights.toZipper.cobind {z =>
max(0, min(max(z.left), max(z.right)) - z.focus
}.toList
Does it make sense ?
My solution with java, it comes with tests with expected solution:
package com.company;
import java.util.*;
enum Orientation {DOWN, UP};
class Walls{
public static void main(String []args){
HashMap<String, Integer> tests = new HashMap<String,Integer>();
tests.put("2 5 1 2 3 4 7 7 6", 10);
tests.put("2 2 5 1 3 1 2 1 7 7 6", 17);
tests.put("2 7 2 7 4 7 1 7 3 7", 18);
tests.put("4 6 7 7 4 3 2 1 5 2", 10);
tests.put("5 2 5 1 2 3 4 7 7 6 2 7 1 2 3 4 5 5 4", 26);
Iterator it = tests.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
it.remove();
String[] strings = ((String)pairs.getKey()).split(" ");
int[] walls = new int[strings.length];
for (int i = 0; i < walls.length; i++){
walls[i] = Integer.parseInt(strings[i].trim());
}
System.out.println(pairs.getKey()+" result="+accumulatedWater(walls)+" expected= " +pairs.getValue());
}
}
static int accumulatedWater(int []wall){
int MAX = 0;
int start = 0;
for(int i=0;i < wall.length;i++){ //let's go to the first peak
if(wall[i] >= MAX){
MAX = wall[i];
start = i;
}else{
break;
}
}
int []accumulate_max = new int[MAX+1]; // sums up to certain height
int []accumulate_max_step = new int[MAX+1]; // steps up to certain height
Orientation going = Orientation.DOWN;
int prev = MAX;
int local_sum=0;
int total_sum=0;
int PREVPEAK = MAX;
for(int i=start+1; i< wall.length; i++){
if( i == wall.length -1 ||
wall[i] < prev && going == Orientation.UP ){
going = Orientation.DOWN;
if(wall[i-1] >= MAX){
total_sum += accumulate_max_step[MAX-1] * MAX - accumulate_max[MAX-1];
MAX = wall[i-1];
PREVPEAK = MAX;
accumulate_max = new int[MAX+1];
accumulate_max_step = new int[MAX+1];
local_sum = 0;
}else{
int indexNewPeak = (i == wall.length -1 && wall[i]> wall[i-1]) ? i : i-1;
int water = accumulate_max_step[wall[indexNewPeak]-1] * wall[indexNewPeak] - accumulate_max[wall[indexNewPeak]-1];
if(wall[indexNewPeak] > PREVPEAK){
local_sum = water;
PREVPEAK = wall[indexNewPeak];
}else{
local_sum += water;
}
}
}else if(wall[i]>prev){
going = Orientation.UP;
}
for(int j=wall[i];j <= MAX;j++){
accumulate_max[j] += wall[i];
accumulate_max_step[j] += 1;
}
prev = wall[i];
}
return total_sum + local_sum;
}
}

Multiply numbers after each other

Exercise Product1ToN (Loop): Write a program called Product1ToN to compute the product of integers 1 to 10 (i.e., 1×2×3×...×10). Try computing the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and explain the results.
How can I do this, and are their multiple ways?
Try this:
private int Product1ToN(int n){
int result = 1, ctr = 1;
while(ctr <= n){
result *= ctr++;
}
return result;
}
Hope this helps.

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 :)