2275. Largest Combination with bitwise and greater than zero

Contents

2275. Largest Combination with bitwise and greater than zero#

The bitwise AND of an array nums is the bitwise AND of all integers in nums.

For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1. Also, for nums = [7], the bitwise AND is 7. You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination.

Return the size of the largest combination of candidates with a bitwise AND greater than 0.

## code

import os
import logging
import traceback
import datetime
from typing import List


def get_logger(LEVEL: str = "INFO") -> logging.Logger:
    logger = logging.getLogger("custom_logger")
    logger.setLevel(getattr(logging, LEVEL.upper(), logging.INFO))
    stream_handler = logging.StreamHandler()
    formatter = logging.Formatter(
        fmt="[%(asctime)s %(levelname)s] %(message)s", datefmt="%Y/%m/%d %H:%M:%S"
    )
    stream_handler.setFormatter(formatter)
    if logger.hasHandlers():
        logger.handlers.clear()
    logger.addHandler(stream_handler)
    return logger


def sol(problem_num, func):
    script_dir = os.getcwd()  # os.path.dirname(os.path.abspath(__file__))
    path = script_dir + f"\\txt\\{problem_num}" + ".txt"

    try:
        with open(path, "r") as getter:
            line_count = 1
            while True:
                line = getter.readline()
                if not line:
                    logger.info("EOF")
                    break
                try:
                    inp, oup = line.strip().split()

                    ############## WARNING :input output fitti
                    inp = list(map(int, inp.split(",")))
                    oup = int(oup.strip())
                    ##############

                    if not func(inp) == oup:
                        raise ValueError(f"wrong output in line : {line}")
                    logger.info(f"{line_count} : {inp} : {oup == func(inp)}")
                    line_count += 1

                except Exception as e:
                    logger.error(traceback.format_exc())
                    logger.info(f"FINISHED WITH ERROR IN {line_count}")
                    line_count += 1

    except FileNotFoundError:
        logger.error(f"File not found: {path}")
    except Exception as e:
        logger.error(f"Error opening file: {e}")
        logger.error(traceback.format_exc())


class Solution:
    def largestCombination(self, candidates: List[int]) -> int:
        max_number = 10**7
        bit_len = max_number.bit_length()
        bit_counts = [0] * (bit_len)

        for num in candidates:
            for i in range(24):
                if num & (1 << i):
                    bit_counts[i] += 1
        return max(bit_counts)


problem_num = 2275
global logger
logger = get_logger("info")
sol(problem_num, Solution().largestCombination)
[2024/11/07 13:40:18 ERROR] Traceback (most recent call last):
  File "C:\Users\WAI\AppData\Local\Temp\ipykernel_49372\407775703.py", line 45, in sol
    raise ValueError(f"wrong output in line : {line}")
ValueError: wrong output in line : 16,17,71,62,12,24,14 3


[2024/11/07 13:40:18 INFO] FINISHED WITH ERROR IN 1
[2024/11/07 13:40:18 ERROR] Traceback (most recent call last):
  File "C:\Users\WAI\AppData\Local\Temp\ipykernel_49372\407775703.py", line 45, in sol
    raise ValueError(f"wrong output in line : {line}")
ValueError: wrong output in line : 8,8 1

[2024/11/07 13:40:18 INFO] FINISHED WITH ERROR IN 2
[2024/11/07 13:40:18 INFO] EOF

bitsiwe counting#

Biotmask, counting์„ ๊ฐœ๋…์„ ๊ฒฐํ•ฉํ•ด์„œ ํ‘ธ๋Š” ๋ฌธ์ œ๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ๋‹ค. bitwise ์—ฐ์‚ฐ์„ ํ™œ์šฉํ•ด ๋ถ€๋ถ„์ง‘ํ•ฉ์ด๋‚˜ ์กฐํ•ฉ์„ ๋น ๋ฅด๊ฒŒ ๊ณ„์‚ฐํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ์— ์œ ์šฉํ•œ ์ ‘๊ทผ์ด๋‹ค.

๋น„ํŠธ๋งˆ์Šคํฌ ํ™œ์šฉ : ๋น„ํŠธ๋งˆ์Šคํฌ๋Š” ๊ฐ ์ˆซ์ž๋ฅผ ๋น„ํŠธ ๋‹จ์œ„๋กœ ๋‹ค๋ฃจ์–ด ํšจ์œจ์ ์œผ๋กœ ์ •๋ณด(ํŠน์ • ๋น„ํŠธ๊ฐ€ 1 0) ์ €์žฅํ•˜๊ณ , ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.

์นด์šดํŒ… ์ตœ์ ํ™” : ๋น„ํŠธ ์œ„์น˜๋ณ„๋กœ 1์˜ ๋นˆ๋„๋ฅผ ์นด์šดํŒ…ํ•จ์œผ๋กœ์จ, ์ „์ฒด ์กฐํ•ฉ์„ ๊ณ„์‚ฐํ•˜์ง€ ์•Š๊ณ ๋„ ๊ฐ€์žฅ ํฐ ์กฐํ•ฉ์˜ ํฌ๊ธฐ๋ฅผ ์ฐพ๋Š” ๋ฐฉ์‹์ด๋‹ค. ๊ฐ ๋น„ํŠธ๊ฐ€ ์–ด๋–ค ์ˆซ์ž์—์„œ 1๋กœ ์„ค์ •๋˜๋Š”์ง€ ์นด์šดํŒ…ํ•˜์—ฌ, ์ตœ๋Œ€ ์กฐํ•ฉํฌ๊ธฐ๋ฅผ ๊ฒฐ์ •ํ•œ๋‹ค. ์ง์ ‘ ๊ณ„์‚ฐํ•˜์ง€ ์•Š๊ณ  ๋‹ค๋ฅธ ๊ฒƒ์„ ํ•˜๋ฉด ๊ฒฐ๋ก ์ ์œผ๋กœ ํ•ด๋‹น ๊ณ„์‚ฐ์ด ๋˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ‘ธ๋Š” ๋ฐฉ์‹โ€ฆ!