Skip to content

Instantly share code, notes, and snippets.

@chnirt
Created May 21, 2022 08:51
Show Gist options
  • Save chnirt/f3e75b8b1614bcce53cafe5faba514d9 to your computer and use it in GitHub Desktop.
Save chnirt/f3e75b8b1614bcce53cafe5faba514d9 to your computer and use it in GitHub Desktop.
Binary numbers with N digits and k 1s
// You are trying to figure out how many binary numbers there are that have N digits and k 1s, and are multiples of 3. Binary numbers that have N digits also include ones that start with 0.
// Suppose that N = 3 and K = 2. Binary numbers with three digits in this case include the following: 000, 001, 010, 011, 100, 101, 110, and 111--8 binary numbers in total. Among these numbers, the ones that have two 1s are 011, 101, and 110. Among these three numbers, two--011 and 110--are multiples of 3.
// Suppose parameters N and K are given, where N represents the number of digits of the given binary number(s) and K the number of 1s in these binary numbers. Please write a function solution that returns the number of binary numbers that have N digits and k 1s and are multiples of 3
// Constraints
// N is a natural number between 1 and 50.
// K is a natural number between 1 and N.
// Examples
// N K result
// 3 2 2
// 4 2 4
// 6 3 2
// Example #1
// Demonstrated in the prompt above.
// Example #2
// The binary numbers that have two 1s and 4 digits and are multiples of 3 are 0011, 0110, 1001, and 1100--4 in total.
// Example #3
// The binary numbers that have three 1s and 6 digits and are multiples of 3 are 101010 and 010101--two.
// -----
/*
Swift 4 program for
Generate all the binary strings of N bits
*/
class BinaryText
{
func solution(_ record: String, _ start: Int, _ last: Int) -> [String]
{
if (start == last)
{
return [record];
}
// Find result using recursion
let binaryNumber1 = self.solution(record + String("0"), start + 1, last);
let binaryNumber2 = self.solution(record + String("1"), start + 1, last);
return binaryNumber1 + binaryNumber2;
}
func binaryString(_ n: Int) -> [String]
{
// N indicate digit in binary
if (n <= 0)
{
return [];
}
// print(" Digit : ", n ," ");
let binaryNumber: [String] = self.solution("", 0, n);
return binaryNumber
}
}
func main(_ n: Int,_ k: Int)
{
let task: BinaryText = BinaryText();
var array: [String] = task.binaryString(n);
array = array.filter({
$0.components(separatedBy:"1").count - 1 == k
})
array = array.filter({
Int($0, radix: 2)! % 3 == 0
})
print(array)
}
main(3, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment