I am trying to solve the following question on LeetCode; Write a function that takes an unsigned integer and returns the number of '1' bits it has. Constraints: The input must be a binary string of length 32.
I have written the following code for that which works fine for inputs 00000000000000000000000000001011 and 00000000000000000000000010000000 (provided internally by the website) but give output 0 for input 11111111111111111111111111111101 and in my local compiler for the last input it says "out of range"
class Solution {
// you need treat n as an unsigned value
fun hammingWeight(n:Int):Int {
var num = n
var setCountBit = 0
while (num > 0) {
setCountBit++
num= num and num-1
}
return setCountBit
}
}
To correctly convert binary string to Int and avoid "out of range error", you need to do the following (I believe LeetCode does the same under the hood):
fun binaryStringToInt(s: String): Int = s.toUInt(radix = 2).toInt()
"11111111111111111111111111111101" is equivalent to 4294967293. This is greater than Int.MAX_VALUE, so it will be represented as negative number after .toInt() convertion (-3 in this case).
Actually, this problem could be solved with one-liner in Kotlin 1.4:
fun hammingWeight(n: Int): Int = n.countOneBits()
But LeetCode uses Kotlin 1.3.10, so you need to adjust your solution to handle negative Ints as well.
Please change the type of your input variable from Int to a type like Double .At the moment The given value is bigger than the maximum value that a type Int number can store.
I'm on this frustrating journey trying to get a specific character from a Swift string. I have an Objective-C function, something like
- ( NSString * ) doIt: ( char ) c
that I want to call from Swift.
This c is eventually passed to a C function in the back that does the weightlifting here but this function gets tripped over when c is or A0.
Now I have two questions (apologies SO).
I am trying to use different encodings, especially the ASCII variants, hoping one would convert (A0) to spcae (20 or dec 32). The verdict seems to be that I need to hardcode this but if there is a failsafe, non-hardcoded way I'd like to hear about it!
I am really struggling with the conversion itself. How do I access a specific character using a specific encoding in Swift?
a) I can use
s.utf8CString[ i ]
but then I am bound to UTF8.
b) I can use something like
let s = "\u{a0}"
let p = UnsafeMutablePointer < CChar >.allocate ( capacity : n )
defer
{
p.deallocate()
}
// Convert to ASCII
NSString ( string : s ).getCString ( p,
maxLength : n,
encoding : CFStringConvertEncodingToNSStringEncoding ( CFStringBuiltInEncodings.ASCII.rawValue ) )
// Hope for 32
let c = p[ i ]
but this seems overkill. The string is converted to NSString to apply the encoding and I need to allocate a pointer, all just to get a single character.
c) Here it seems Swift String's withCString is the man for the job, but I can not even get it to compile. Below is what Xcode's completion gives but even after fiddling with it for a long time I am still stuck.
// How do I use this
// ??
s.withCString ( encodedAs : _UnicodeEncoding.Protocol ) { ( UnsafePointer < FixedWidthInteger & UnsignedInteger > ) -> Result in
// ??
}
TIA
There are two withCString() methods: withCString(_:) calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of UTF-8 code units. Example:
// An emulation of your Objective-C method.
func doit(_ c: CChar) {
print(c, terminator: " ")
}
let s = "a\u{A0}b"
s.withCString { ptr in
var p = ptr
while p.pointee != 0 {
doit(p.pointee)
p += 1
}
}
print()
// Output: 97 -62 -96 98
Here -62 -96 is the signed character representation of the UTF-8 sequence C2 A0 of the NO-BREAK SPACE character U+00A0.
If you just want to iterate over all UTF-8 characters of the string sequentially then you can simply use the .utf8 view. The (unsigned) UInt8 bytes must be converted to the corresponding (signed) CChar:
let s = "a\u{A0}b"
for c in s.utf8 {
doit(CChar(bitPattern: c))
}
print()
I am not aware of a method which transforms U+00A0 to a “normal” space character, so you have to do that manually. With
let s = "a\u{A0}b".replacingOccurrences(of: "\u{A0}", with: " ")
the output of the above program would be 97 32 98.
The withCString(encodedAs:_:) method calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of code units. Example:
let s = "a\u{A0}b€"
s.withCString(encodedAs: UTF16.self) { ptr in
var p = ptr
while p.pointee != 0 {
print(p.pointee, terminator: " ")
p += 1
}
}
print()
// Output: 97 160 98 8364
This method is probably of limited use for your purpose because it can only be used with UTF8, UTF16 and UTF32.
For other encodings you can use the data(using:) method. It produces a Data value which is a sequence of UInt8 (an unsigned type). As above, these must be converted to the corresponding signed character:
let s = "a\u{A0}b"
if let data = s.data(using: .isoLatin1) {
data.forEach {
doit(CChar(bitPattern: $0))
}
}
print()
// Output: 97 -96 98
Of course this may fail if the string is not representable in the given encoding.
It would be a basic question, but I couldn't figure out a solution. I need to initialize a constant out of the right-side value of below either type.
val test: Either<String, Int> = 1.right()
I tried something like below but it shrinks the scope of the constant.
when(test) {
is Either.Right -> {val get:Int = test.b}
is Either.Left -> println(test.a)
}
I want that get to be scoped outside of when statement. Is there any way to do it or Arrow Either is not made for this purpose?
The important question is: what should happen if the Either is Left. In this example it is created close to where it's used, so it is obvious to you as a developer. But to the compiler what is inside the Either can be either an Int or a String.
You can extract the value using for example fold:
val x = test.fold({ 0 }, {it}) // provide 0 as default in case the Either was a `Left`
// x = 1
another option is getOrElse
val test = 1.right()
val x = test.getOrElse { 42 } // again, default in case it was a `Left`
// x = 42
You can also work with it without unwrapping it:
val test = 1.right()
val testPlus10 = test.map { it + 10 } // adds 10 to `test` if it is `Right`, does nothing otherwise
val x = testPlus10.getOrElse { 0 } // unwrap by providing a default value
// x = 11
For more example check the official docs.
Recommended reading: How do I get the value out of my Monad
Other than the obvious fact that the first form could use a variable and not just a string literal, is there any reason to use one over the other, and if so under which cases?
In code:
// Given:
var foo = {'bar': 'baz'};
// Then
var x = foo['bar'];
// vs.
var x = foo.bar;
Context: I've written a code generator which produces these expressions and I'm wondering which is preferable.
(Sourced from here.)
Square bracket notation allows the use of characters that can't be used with dot notation:
var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax
including non-ASCII (UTF-8) characters, as in myForm["ダ"] (more examples).
Secondly, square bracket notation is useful when dealing with
property names which vary in a predictable way:
for (var i = 0; i < 10; i++) {
someFunction(myForm["myControlNumber" + i]);
}
Roundup:
Dot notation is faster to write and clearer to read.
Square bracket notation allows access to properties containing
special characters and selection of
properties using variables
Another example of characters that can't be used with dot notation is property names that themselves contain a dot.
For example a json response could contain a property called bar.Baz.
var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax
The bracket notation allows you to access properties by name stored in a variable:
var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello
obj.x would not work in this case.
The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.
So if you know that the property you are interested in is called “length”, you say value.length. If you want to extract the property named by the value held in the variable i, you say value[i]. And because property names can be any string, if you want to access a property named “2” or “John Doe”, you must use square brackets: value[2] or value["John Doe"]. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe” is a valid variable name and so cannot be accessed through dot notation.
In case of Arrays
The elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The length property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write array.length because that is easier to write than array["length"].
Dot notation does not work with some keywords (like new and class) in internet explorer 8.
I had this code:
//app.users is a hash
app.users.new = {
// some code
}
And this triggers the dreaded "expected indentifier" (at least on IE8 on windows xp, I havn't tried other environments). The simple fix for that is to switch to bracket notation:
app.users['new'] = {
// some code
}
Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like
var x = elem["foo[]"]; // can't do elem.foo[];
This can be extended to any property containing special characters.
Both foo.bar and foo["bar"] access a property on foo but not necessarily the same property. The difference is in how bar is interpreted. When using a dot, the word after the dot is the literal name of the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas foo.bar fetches the
property of value named “bar” , foo["bar"] tries to evaluate the expression "bar" and uses the result, converted to a string, as the property name
Dot Notation’s Limitation
if we take this oject :
const obj = {
123: 'digit',
123name: 'start with digit',
name123: 'does not start with digit',
$name: '$ sign',
name-123: 'hyphen',
NAME: 'upper case',
name: 'lower case'
};
accessing their propriete using dot notation
obj.123; // ❌ SyntaxError
obj.123name; // ❌ SyntaxError
obj.name123; // ✅ 'does not start with digit'
obj.$name; // ✅ '$ sign'
obj.name-123; // ❌ SyntaxError
obj.'name-123';// ❌ SyntaxError
obj.NAME; // ✅ 'upper case'
obj.name; // ✅ 'lower case'
But none of this is a problem for the Bracket Notation:
obj['123']; // ✅ 'digit'
obj['123name']; // ✅ 'start with digit'
obj['name123']; // ✅ 'does not start with digit'
obj['$name']; // ✅ '$ sign'
obj['name-123']; // ✅ 'does not start with digit'
obj['NAME']; // ✅ 'upper case'
obj['name']; // ✅ 'lower case'
accessing variable using variable :
const variable = 'name';
const obj = {
name: 'value'
};
// Bracket Notation
obj[variable]; // ✅ 'value'
// Dot Notation
obj.variable; // undefined
You need to use brackets if the property name has special characters:
var foo = {
"Hello, world!": true,
}
foo["Hello, world!"] = false;
Other than that, I suppose it's just a matter of taste. IMHO, the dot notation is shorter and it makes it more obvious that it's a property rather than an array element (although of course JavaScript does not have associative arrays anyway).
Be careful while using these notations:
For eg. if we want to access a function present in the parent of a window.
In IE :
window['parent']['func']
is not equivalent to
window.['parent.func']
We may either use:
window['parent']['func']
or
window.parent.func
to access it
You have to use square bracket notation when -
The property name is number.
var ob = {
1: 'One',
7 : 'Seven'
}
ob.7 // SyntaxError
ob[7] // "Seven"
The property name has special character.
var ob = {
'This is one': 1,
'This is seven': 7,
}
ob.'This is one' // SyntaxError
ob['This is one'] // 1
The property name is assigned to a variable and you want to access the
property value by this variable.
var ob = {
'One': 1,
'Seven': 7,
}
var _Seven = 'Seven';
ob._Seven // undefined
ob[_Seven] // 7
Bracket notation can use variables, so it is useful in two instances where dot notation will not work:
1) When the property names are dynamically determined (when the exact names are not known until runtime).
2) When using a for..in loop to go through all the properties of an object.
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Case where [] notation is helpful :
If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -
var a = { 1 : 3 };
Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.
Dot notation is always preferable. If you are using some "smarter" IDE or text editor, it will show undefined names from that object.
Use brackets notation only when you have the name with like dashes or something similar invalid. And also if the name is stored in a variable.
Let me add some more use case of the square-bracket notation. If you want to access a property say x-proxy in a object, then - will be interpreted wrongly. Their are some other cases too like space, dot, etc., where dot operation will not help you. Also if u have the key in a variable then only way to access the value of the key in a object is by bracket notation. Hope you get some more context.
An example where the dot notation fails
json = {
"value:":4,
'help"':2,
"hello'":32,
"data+":2,
"😎":'😴',
"a[]":[
2,
2
]
};
// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json["😎"]);
console.log(json["a[]"]);
// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.😎);
console.log(json.a[]);
The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name
Or when you want to dynamically change the classList action for an element:
// Correct
showModal.forEach(node => {
node.addEventListener(
'click',
() => {
changeClass(findHidden, 'remove'); // Correct
},
true
);
});
//correct
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList[className]('hidden'));// Correct
}
}
// Incorrect
function changeClass(findHidden, className) {
for (let item of findHidden) {
console.log(item.classList.className('hidden')); // Doesn't work
}
}
I'm giving another example to understand the usage differences btw them clearly. When using nested array and nested objects
const myArray = [
{
type: "flowers",
list: [ "a", "b", "c" ],
},
{
type: "trees",
list: [ "x", "y", "z" ],
}
];
Now if we want to access the second item from the trees list means y.
We can't use bracket notation all the time
const secondTree = myArray[1]["list"][1]; // incorrect syntex
Instead, we have to use
const secondTree = myArray[1].list[1]; // correct syntex
The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is mostly used as it is easier to read and comprehend. So why should we use bracket notation and what is the difference between then? well, the bracket notation [] allows us to access object properties using variables because it converts the expression inside the square brackets to a string.
const person = {
name: 'John',
age: 30
};
//dot notation
const nameDot = person.name;
console.log(nameDot);
// 'John'
const nameBracket = person['name'];
console.log(nameBracket);
// 'John'
Now, let's look at a variable example:
const person = {
name: 'John',
age: 30
};
const myName = 'name';
console.log(person[myName]);
// 'John'
Another advantage is that dot notation only contain be alphanumeric (and _ and $) so for instance, if you want to access an object like the one below (contains '-', you must use the bracket notation for that)
const person = {
'my-name' : 'John'
}
console.log(person['my-name']); // 'John'
// console.log(person.my-name); // Error
I want to achieve the following functionality:
extend RED GREEN BLUE packet {...}
this line will cause the struct members in the curly brackets,
to be added to all the specified subtypes of a certain enumerated type.
the result will look like this:
extend RED packet {...}
extend BLUE packet {...}
extend GREEN packet {...}
extend BIG MEDIUM RED BLUE GREEN packet {...}
this line will extend all possible combinations of the
items from each enumerated type with the struct members
that appear in the curly brackets.
the result will look like this:
extend MEDIUM RED packet {...}
extend MEDIUM BLUE packet {...}
extend MEDIUM GREEN packet {...}
extend BIG RED packet {...}
extend BIG BLUE packet {...}
extend BIG GREEN packet {...}
Thanks,
This macro solves this problem, yet there is a small limitation.
Since this macro is ‘define as computed’ , the struct you are going to apply it on should be defined in a different file than the file that uses the macro.
A simple use case is shown here: (suppose this macro is in a file called dac.e):
define <multi_when'statement> "ext_s \[<detr'name>,...\] <base'type> \{<sm'exp>,...\}" as computed {
var our_struct:rf_struct=rf_manager.get_type_by_name(<base'type>).as_a(rf_struct);
var fields:list of rf_field = our_struct.as_a(rf_struct).get_declared_fields();
var rf_type_list:list of rf_type;
var list_of_0_index:list of uint;
var field_names:list of string;
var list_of_enums:list of rf_enum;
var temp_index:uint=0;
var used_types_list:list of rf_type;
var enumerations:list of string;
var indices:list of uint;
var num_of_each_enum:list of uint;
var size_of_final_list_of_enumerations_to_be_used:uint=1;
var enum_items_list:list of rf_enum_item;
var final_list_of_enumerations_to_be_used: list of string;
var multiplication_list_algrtm1:list of uint;
var multiplication_list_algrtm2:list of uint;
var multiplication_uint_algrtm:uint=1;
if (<detr'names>.is_empty()){
error("you did not supply any when subtypes");
};
for each (field) in fields{
rf_type_list.add(field.get_type());
field_names.add(field.get_name());
};
for each (typ) in rf_type_list{
if (rf_type_list[index] is not a rf_enum){
rf_type_list.delete(index);
field_names.delete(index);
};
};
if (rf_type_list.is_empty()){
error("the type ",<base'type>," does not have any enumerated type fields.");
};
for each (typ) using index (typ_index) in rf_type_list {
num_of_each_enum.add(0);
if(indices.is_empty()){
indices.add(0);
}else {
indices.add(indices[typ_index-1])
};
enum_items_list = typ.as_a(rf_enum).get_items();
for each (enum_item) in <detr'names> {
if (enum_items_list.has(it.get_name()==enum_item)){
out(enum_item, " is found in ",typ.get_name());
enumerations.add(append(enum_item,"'",field_names[typ_index]));
indices[typ_index]+=1;
num_of_each_enum[typ_index]+=1;
};
};
};
for each in num_of_each_enum do { // avoid enums that are not used - to
if (it==0){
list_of_0_index.add(index);
};
};
if (!list_of_0_index.is_empty()){
list_of_0_index=list_of_0_index.reverse();
for each in list_of_0_index {
num_of_each_enum.delete(it);
indices.delete(it);
field_names.delete(it);
}
};
enumerations=enumerations.unique(it);
if (enumerations.is_empty()){
error("no legal enumerated values were used in the ext_s macro, please check that the arguments in square brackets are in the form of [<enum_item1>,<enum_item2>,...]");
};
//remove the last index (not relevant - and add 0 in the indices[0]
indices.add0(0);
indices.delete(indices.size()-1);
for each in num_of_each_enum do {
size_of_final_list_of_enumerations_to_be_used*=it;
};
for each in num_of_each_enum do {
multiplication_uint_algrtm*=it;
multiplication_list_algrtm1.add(size_of_final_list_of_enumerations_to_be_used/multiplication_uint_algrtm);
multiplication_list_algrtm2.add(size_of_final_list_of_enumerations_to_be_used/multiplication_list_algrtm1[index]);
};
//build the final list of string to be used in the extend statement:
for i from 1 to size_of_final_list_of_enumerations_to_be_used{
final_list_of_enumerations_to_be_used.add("");
};
for k from 0 to indices.size()-1 do {
temp_index=0;
for j from 0 to multiplication_list_algrtm2[k]-1 do {
for i from 0 to multiplication_list_algrtm1[k]-1 do {
final_list_of_enumerations_to_be_used[temp_index]=append(final_list_of_enumerations_to_be_used[temp_index]," ",enumerations[indices[k]+j%num_of_each_enum[k]]);
temp_index+=1;
};
};
};
for each in final_list_of_enumerations_to_be_used do {
result = appendf("%s extend %s %s {",result,it, <base'type> );
for each in <sm'exps> do {
result= appendf("%s %s;",result,it);
};
result = append(result , "};");
};
print result;
};
Note that this macro solves an interesting problem:
Suppose you have a list of a bunch of items of certain types (for example : {a1,a2,b1,b2,c1,c2,c3…}),
And you do not preliminarily know how many types are there in this list (in this example there are 3 types-a,b,c - but there could be more or less). So question is, how do you create a list of all possible combinations of all items from all type (for example: 0. a1-b1-c1 1.a1-b1-c2…..11.a2-b2-c3), without knowing how many types are there in the list? You can follow the code and figure out the algorithm to do that (using list of indices, how many items are there from each type and so….).
The file that should be loaded prior to macro (dac.e) is :
Struct.e:
<'
type t1:[A1,A2,A3,A4,A5];
type t2:[B1,B2,B3];
type t3:[C1,C2,C3];
struct s{
a:uint(bits:4);
t_1:t1;
t_2:t2;
t_3:t3;
};
'>
And the test file is :
<'
Import dac.e;
import struct.e;
//use the macro
ext_s [A1,A2,B1,B2] s {x:int,keep x==6,y:int,keep y==10};
extend sys{
s1:A1 B1 s;
s2:A2 B1 s;
s3:A1 s;
run() is also{
print s1;
print s2;
print s3;
};
};
'>
Please comment if you have any question.