Simple syntax to print out Nim address - nim-lang

How to print out Nim address
just like in C:
int array[] = { 7, 8, 9 };
printf(" %p ", (void *)&array);
? the try:
var
arr = newSeq[array[2,int]](2)
refVar = addr arr
echo refVar
gave:
Error: type mismatch: got <ptr seq[array[0..1, int]]>
but expected one of:
proc echo(x: varargs[typed, `$`])
first type mismatch at position: 1
required type for x: varargs[typed]
but expression 'refVar' is of type: ptr seq[array[0..1, int]
Please help out !

Use repr to get a string representation of a value that also contains the memory address:
var
arr = newSeq[array[2,int]](2)
refVar = addr arr
echo arr.repr # 0x7f5c2fcbd050#[[0, 0], [0, 0]]
echo refVar.repr # ptr 0x564bd37d7528 --> 0x7f5c2fcbd050#[[0, 0], [0, 0]]

If you just want the memory address alone (not what else repr gives you), the simplest way is:
echo cast[int](arr.addr).toHex

Related

Python 3.8: Bytes to a list of hex

I'm currently banging by head bloody over this problem I have:
I have a method where I receive a byte input of a defined length of 8:
def ConvertToHexAndSend(serialnumber):
if len(serialnumber) != 8:
throw a good exception...
Some good converter code here..
The method shall then take the serialnumber and split it into a list with the size 4.
Example:
serialnumber = b'12345678'
Expected output:
[0x12, 0x34, 0x56, 0x78]
What I have tried so far:
new_list = list(serialnumber) # Gives a list of [49, 50, 51, 52, 53, 54, 55, 56] and then:
first byte = new_list[0] << 8 + new_list[1] # gives some riddish value
and
hex(serialnumber[0]) # Gives '0x32' string
and
first_byte = serialnumber[0] + serialnumber[1] # Gives int 99
But no success so far.. any idea?
You want something like:
result = list(bytes.fromhex(serialnumber.decode('ascii')))
Your bytes are represent a hex-string. So use the bytes.fromhex to read that (converting the bytes to str first), and you can use list to get a list of int objects from the new resulting bytes object

Get all possible sums from a list of numbers

Let's say I have a list of numbers: 2, 2, 5, 7
Now the result of the algorithm should contain all possible sums.
In this case: 2+2, 2+5, 5+7, 2+2+5, 2+2+5+7, 2+5+7, 5+7
I'd like to achieve this by using Dynamic Programming. I tried using a matrix but so far I have not found a way to get all the possibilities.
Based on the question, I think that the answer posted by AT-2016 is correct, and there is no solution that can exploit the concept of dynamic programming to reduce the complexity.
Here is how you can exploit dynamic programming to solve a similar question that asks to return the sum of all possible subsequence sums.
Consider the array {2, 2, 5, 7}: The different possible subsequences are:
{2},{2},{5},{7},{2,5},{2,5},{5,7},{2,5,7},{2,5,7},{2,2,5,7},{2,2},{2,7},{2,7},{2,2,7},{2,2,5}
So, the question is to find the sum of all these elements from all these subsequences. Dynamic Programming comes to the rescue!!
Arrange the subsequences based on the ending element of each subsequence:
subsequences ending with the first element: {2}
subsequences ending with the second element: {2}, {2,2}
subsequences ending with the third element: {5},{2,5},{2,5},{2,2,5}
subsequences ending with the fourth element: {7},{5,7},{2,7},{2,7},{2,2,7},{2,5,7},{2,5,7},{2,2,5,7}.
Here is the code snippet:
The array 's[]' calculates the sums for 1,2,3,4 individually, that is, s[2] calculates the sum of all subsequences ending with third element. The array 'dp[]' calculates the overall sum till now.
s[0]=array[0];
dp[0]=s[0];
k = 2;
for(int i = 1; i < n; i ++)
{
s[i] = s[i-1] + k*array[i];
dp[i] = dp[i-1] + s[i];
k = k * 2;
}
return dp[n-1];
This is done in C# and in an array to find the possible sums that I used earlier:
static void Main(string[] args)
{
//Set up array of integers
int[] items = { 2, 2, 5, 7 };
//Figure out how many bitmasks is needed
//4 bits have a maximum value of 15, so we need 15 masks.
//Calculated as: (2 ^ ItemCount) - 1
int len = items.Length;
int calcs = (int)Math.Pow(2, len) - 1;
//Create array of bitmasks. Each item in the array represents a unique combination from our items array
string[] masks = Enumerable.Range(1, calcs).Select(i => Convert.ToString(i, 2).PadLeft(len, '0')).ToArray();
//Spit out the corresponding calculation for each bitmask
foreach (string m in masks)
{
//Get the items from array that correspond to the on bits in the mask
int[] incl = items.Where((c, i) => m[i] == '1').ToArray();
//Write out the mask, calculation and resulting sum
Console.WriteLine(
"[{0}] {1} = {2}",
m,
String.Join("+", incl.Select(c => c.ToString()).ToArray()),
incl.Sum()
);
}
Console.ReadKey();
}
Possible outputs:
[0001] 7 = 7
[0010] 5 = 5
[0011] 5 + 7 = 12
[0100] 2 = 2
This is not an answer to the question because it does not demonstrate the application of dynamic programming. Rather it notes that this problem involves multisets, for which facilities are available in Sympy.
>>> from sympy.utilities.iterables import multiset_combinations
>>> numbers = [2,2,5,7]
>>> sums = [ ]
>>> for n in range(2,1+len(numbers)):
... for item in multiset_combinations([2,2,5,7],n):
... item
... added = sum(item)
... if not added in sums:
... sums.append(added)
...
[2, 2]
[2, 5]
[2, 7]
[5, 7]
[2, 2, 5]
[2, 2, 7]
[2, 5, 7]
[2, 2, 5, 7]
>>> sums.sort()
>>> sums
[4, 7, 9, 11, 12, 14, 16]
I have a solution that can print a list of all possible subset sums.
Its not dynamic programming(DP) but this solution is faster than the DP approach.
void solve(){
ll i, j, n;
cin>>n;
vector<int> arr(n);
const int maxPossibleSum=1000000;
for(i=0;i<n;i++){
cin>>arr[i];
}
bitset<maxPossibleSum> b;
b[0]=1;
for(i=0;i<n;i++){
b|=b<<arr[i];
}
for(i=0;i<maxPossibleSum;i++){
if(b[i])
cout<<i<<endl;
}
}
Input:
First line has the number of elements N in the array.
The next line contains N space-separated array elements.
4
2 2 5 7
----------
Output:
0
2
4
5
7
9
11
12
14
16
The time complexity of this solution is O(N * maxPossibleSum/32)
The space complexity of this solution is O(maxPossibleSum/8)

Reorder string characters in Swift

So, let's say I have a String that is: "abc" and I want to change each character position so that I can have "cab" and later "bca". I want the character at index 0 to move to 1, the one on index 1 to move to 2 and the one in index 2 to 0.
What do I have in Swift to do this? Also, let's say instead of letters I had numbers. Is there any easier way to do it with integers?
Swift 2:
extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
mutating func cycleAround() {
insert(removeLast(&self), atIndex: startIndex)
}
}
var ar = [1, 2, 3, 4]
ar.cycleAround() // [4, 1, 2, 3]
var letts = "abc".characters
letts.cycleAround()
String(letts) // "cab"
Swift 1:
func cycleAround<C : RangeReplaceableCollectionType where C.Index : BidirectionalIndexType>(inout col: C) {
col.insert(removeLast(&col), atIndex: col.startIndex)
}
var word = "abc"
cycleAround(&word) // "cab"
In the Swift Algorithms package there is a rotate command
import Algorithms
let string = "abcde"
var stringArray = Array(string)
for _ in 0..<stringArray.count {
stringArray.rotate(toStartAt: 1)
print(String(stringArray))
}
Result:
bcdea
cdeab
deabc
eabcd
abcde

Concatenate number with string in Swift

I need to concatenate a String and Int as below:
let myVariable: Int = 8
return "first " + myVariable
But it does not compile, with the error:
Binary operator '+' cannot be applied to operands of type 'String' and 'Int'
What is the proper way to concatenate a String + Int?
If you want to put a number inside a string, you can just use String Interpolation:
return "first \(myVariable)"
You have TWO options;
return "first " + String(myVariable)
or
return "first \(myVariable)"
To add an Int to a String you can do:
return "first \(myVariable)"
If you're doing a lot of it, consider an operator to make it more readable:
func concat<T1, T2>(a: T1, b: T2) -> String {
return "\(a)" + "\(b)"
}
let c = concat("Horse ", "cart") // "Horse cart"
let d = concat("Horse ", 17) // "Horse 17"
let e = concat(19.2345, " horses") // "19.2345 horses"
let f = concat([1, 2, 4], " horses") // "[1, 2, 4] horses"
operator infix +++ {}
#infix func +++ <T1, T2>(a: T1, b: T2) -> String {
return concat(a, b)
}
let c1 = "Horse " +++ "cart"
let d1 = "Horse " +++ 17
let e1 = 19.2345 +++ " horses"
let f1 = [1, 2, 4] +++ " horses"
You can, of course, use any valid infix operator, not just +++.
Optional keyword would appear when you have marked variable as optional with ! during declaration.
To avoid Optional keyword in the print output, you have two options:
Mark the optional variable as non-optional. For this, you will have
to give default value.
Use force unwrap (!) symbol, next to variable
In your case, this would work just fine
return "first \(myVariable!)"
var a = 2
var b = "Hello W"
print("\(a) " + b)
will print 2 Hello W
Here is documentation about String and characters
var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"

How can I use a type as a function parameter in C# 4.0?

Visual Studio reports that
"'PhoenixEngineTypes.BehaviorTypes' is a 'type' but is used like a 'variable'".
public void AddBehavior(BehaviorTypes type)
{
if (Enum.IsDefined(BehaviorTypes, type))
{
switch (type)
{
case BehaviorTypes.render:
break;
}
}
The definition of BehaviorTypes is:
[Flags]
enum BehaviorTypes : uint
{
default_behavior = 1 >> 0,
select = 1 >> 1,
render = 1 >> 2,
animate = 1 >> 3,
navigate = 1 >> 4,
rotate = 1 >> 5,
group = 1 >> 6,
scale = 1 >> 7,
collide = 1 >> 8,
kill = 1 >> 9,
attack = 1 >> 10,
audio = 1 >> 11,
all = UInt32.MaxValue
}
And finally:
public static bool IsDefined(Type enumType, object value);
Why can't I do this?
I tried using typeof(type) and it compiles, but why waste a function call when the type is not variable? Shouldn't I be able to use the token directly?
You need to call IsDefined as follows
Enum.IsDefined(typeof(BehaviorTypes), type)
as it expects an instance of Type as input. BehaviorTypes is not an instance of Type, but you can get the corresponding Type instance for a type by using typeof.
See http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx

Resources